Skip to content

Official Codebase of 3DCodeVerse

Python

Trim comments and docstrings to the present tense: code unchanged (AST-identical), prose 11 095 → 3 926 lines

gaoypeng07af197f913b
diff --git a/harness/codeverse3d/__init__.py b/harness/codeverse3d/__init__.py
index 723428a0..2316d346 100644
--- a/harness/codeverse3d/__init__.py
+++ b/harness/codeverse3d/__init__.py
@@ -1,30 +1,17 @@
"""codeverse3d — the 3dcodeverse harness.
-A backend harness in which LLMs (API models or agentic CLIs) write RAW,
-executable 3D code — Blender ``bpy``, CadQuery, Three.js, URDF, GLSL — for
-four tracks (static objects, articulated objects, scenes, graphics). Every run is
-planned, generated, linted, executed, measured, rendered, judged, refined and
-finally emitted as a data-flywheel record.
+A backend harness in which LLMs write RAW, executable 3D code (Blender ``bpy``, CadQuery,
+Three.js, URDF, GLSL) for four tracks (static objects, articulated objects, scenes, graphics).
-Package map (each sub-package has its own docstring):
+Package map:
-- ``conventions`` single source of truth for frames, units, naming.
-- ``config`` settings (keys, binaries, defaults) — layered, typed.
-- ``contracts`` pydantic models shared by everything (Spec, Plan, Gate,
- Judgment, Usage, RunRecord ...). No logic lives here.
-- ``models`` ChatModel backends: Gemini / Anthropic / OpenAI (+ key pool).
-- ``agents`` CodingAgent backends: the vendor CLIs — antigravity (agy,
- Google's models) / claude-code / codex.
-- ``languages`` LanguageRuntime per raw language: lint, build, export.
-- ``spatial`` language-agnostic 3D tools on GLB/scene: measure, render,
- slice, isolate, silhouette, joints, probes — also served as
- an MCP server to agentic harnesses.
-- ``judges`` VLM judges + rubrics + deterministic metrics.
-- ``tracks`` static_object / articulated_object / scene / graphics pipelines.
-- ``orchestrator`` stage runner, round loop, budget, candidate selection.
-- ``record`` what every run writes: record.json, deliverable/, telemetry.
-- ``addons`` optional tools that READ finished runs (gallery, dataset, cost report, …).
-- ``cli`` ``3dcode`` command line.
+- ``conventions`` frames, units, naming. - ``config`` typed layered settings.
+- ``contracts`` shared pydantic models. - ``models`` ChatModel backends + key pool.
+- ``agents`` vendor CLI coding agents. - ``languages`` per-language lint / build / export.
+- ``spatial`` 3D tools on GLB / scene, also an MCP server.
+- ``judges`` VLM judges + rubrics. - ``tracks`` the four pipelines.
+- ``orchestrator`` stage runner, round loop. - ``record`` record.json, deliverable/, telemetry.
+- ``addons`` tools that read finished runs. - ``cli`` the ``3dcode`` command line.
"""
__version__ = "0.1.0"
diff --git a/harness/codeverse3d/addons/__init__.py b/harness/codeverse3d/addons/__init__.py
index 31dbedfb..a1451a6b 100644
--- a/harness/codeverse3d/addons/__init__.py
+++ b/harness/codeverse3d/addons/__init__.py
@@ -1,20 +1 @@
-"""Optional tools that READ finished runs — nothing a run needs in order to happen.
-
-* ``gallery`` the run browser (``3dcode gallery serve|build``)
-* ``dataset`` run records → samples, packs, preference pairs, captions, an index
- (``3dcode flywheel export|pairs|caption|index``)
-* ``costreport`` the cost audit of finished runs (``3dcode cost``)
-* ``calibration`` judge repeatability / calibration over recorded runs
- (``python -m codeverse3d.addons.calibration``)
-* ``skill_targets`` each skill bundle's falsifiable claim, measured (``3dcode skills …``,
- ``eval/bench/skill_targets.py``)
-* ``select`` which round of a finished run to hand over, and ``deliverable/`` for it
- (``3dcode pick``; ``3dcode make`` calls it after the run) — the reader
- every other reader asks for a run's baseline / picked score
-
-The boundary is one-way and pinned by ``tests/core/test_addons_boundary.py``: an addon may
-import anything in ``codeverse3d``; outside ``codeverse3d.cli`` nothing in ``codeverse3d`` imports an
-addon. What a run itself writes (``record.json``, the per-round ``artifacts/rNN/``,
-telemetry) is NOT an addon — that is ``codeverse3d.record``; booking its cost while it runs is
-``codeverse3d.cost``.
-"""
+"""Optional tools that READ finished runs — nothing a run needs in order to happen."""
diff --git a/harness/codeverse3d/addons/calibration.py b/harness/codeverse3d/addons/calibration.py
index 19cb5792..c2312bc4 100644
--- a/harness/codeverse3d/addons/calibration.py
+++ b/harness/codeverse3d/addons/calibration.py
@@ -1,19 +1,4 @@
-"""Judge calibration smoke: re-judge finished runs and ask "does the judge separate good from bad?"
-
-``calibrate(run_dirs)`` reads each run's ``rounds/rNN.json`` (read-only), rebuilds
-the ``JudgeInput`` the way ``3dcode judge`` does (``cli/_judge.build_judge_input``: spec,
-renders, measurement, gates, plan digest, acceptance, previous verdict, track context,
-stored clay views, GLB) and picks the judge class it would (``make_judge``),
-re-judges every round with ``n_samples`` (montage order shuffled per sample) and
-tabulates, per round: gate error count, the stored overall, the new mean/std,
-per-criterion std, defects and caps. Across rounds it reports the Pearson and
-Spearman correlation between gate error counts and the new scores (expected
-negative), and between stored and new overalls. Optionally renders a clay /
-normals geometry set for the picked round (``addons/select``) when it stored none — from
-its own GLB (``select.round_file``; none when it kept none) — so the geometry montage is exercised. Output goes to ``out_dir`` (never into the run).
-
-CLI: ``python -m codeverse3d.addons.calibration runs/a runs/b --model gemini:gemini-4-argon --n 3 --out scratch/``
-"""
+"""Judge calibration smoke: re-judge finished runs and check the judge separates good from bad."""
from __future__ import annotations
@@ -44,10 +29,6 @@ log = logging.getLogger(__name__)
def _run_label(run_dir: Path) -> str:
- """A label that stays unique across a battery: bench cells all end in ``.../run``, so
- ``run_dir.name`` collided for every cell and their judgment files overwrote each other.
- The whole filtered tail is kept — a 2-part tail (``<arm>_run``) still collided across
- a battery's prompts, and dropped the control/treatment arm in an ab_plan layout."""
parts = run_dir.resolve().parts
tail = [q for q in parts[-5:] if q not in ("runs", "cells")]
return "_".join(tail) if tail[-1] == "run" else tail[-1]
@@ -55,7 +36,6 @@ def _run_label(run_dir: Path) -> str:
# --------------------------------------------------------------------------- data
class RoundCase(BaseModel):
- """One judgeable round reconstructed from a run directory."""
run: str
round_index: int
@@ -76,7 +56,7 @@ def _stored_weighted(case: RoundCase) -> float | None:
return None
try:
return round(load_rubric(case.rubric).weighted_overall(case.stored.scores), 3)
- except Exception: # noqa: BLE001 — a retired rubric name must not kill the report
+ except Exception: # noqa: BLE001
return None
@@ -87,9 +67,6 @@ class CalibrationRow(BaseModel):
gate_errors: int
gate_warnings: int
stored_overall: float | None = None
- #: the stored PER-CRITERION scores re-weighted by today's rubric — old records exist
- #: whose overall contradicts their own scores (a violin: scores→0.428, overall 0.018),
- #: and a correlation against such an overall measures the corruption, not the judge
stored_weighted: float | None = None
stored_backend: str = ""
mean: float
@@ -157,14 +134,13 @@ class CalibrationTable(BaseModel):
# --------------------------------------------------------------------------- loading runs
def load_run_cases(run_dir: Path, *, rounds: list[int] | None = None) -> list[RoundCase]:
- """Rebuild judge inputs for every judgeable round of a run (rounds with renders)."""
run_dir = Path(run_dir)
ws = Workspace(run_dir)
saved = [RoundRecord.model_validate_json(p.read_text()) for p in sorted((run_dir / "rounds").glob("r*.json"))]
try:
run = load_record(ws)
picked = select.summarise(run_dir, record=run).round
- except RecordError: # an interrupted run: rounds/ + spec.json, and the same fallback rule over them
+ except RecordError:
run = RunRecord(spec=Spec.model_validate_json(ws.spec_path.read_text()), workspace=str(run_dir))
picked = select.fallback_round(saved)
cases: list[RoundCase] = []
@@ -173,7 +149,6 @@ def load_run_cases(run_dir: Path, *, rounds: list[int] | None = None) -> list[Ro
continue
if rec.renders is None or not rec.renders.views:
continue
- # the same input, views and paths the in-run judge and `3dcode judge` see
cases.append(RoundCase(
run=_run_label(run_dir), round_index=rec.index, kind=rec.kind, rubric=rubric_for(run, rec, None),
inp=build_judge_input(ws, run, rec),
@@ -186,8 +161,6 @@ def load_run_cases(run_dir: Path, *, rounds: list[int] | None = None) -> list[Ro
def render_geometry_views(case: RoundCase, out_dir: Path, mode: str) -> RenderSet | None:
- """Clay/normals renders of the picked round's own GLB (object tracks only; None when that
- round kept none — never the last build's ``artifacts/object.glb`` in its place)."""
if case.inp.spec.track.value == "scene":
return None
if not case.glb:
@@ -199,14 +172,13 @@ def render_geometry_views(case: RoundCase, out_dir: Path, mode: str) -> RenderSe
views = list(OBJECT_CLAY_VIEWS)
try:
return render_glb(case.glb, out_dir / case.run / f"geometry_{mode}", views=views, mode=mode, sheet=False)
- except Exception as e: # noqa: BLE001 — calibration must not die on a render hiccup
+ except Exception as e: # noqa: BLE001
log.warning("geometry render failed for %s: %s", case.run, e)
return None
# --------------------------------------------------------------------------- statistics
def pearson(xs: list[float], ys: list[float], method: str = "linear") -> float | None:
- """``statistics.correlation`` at 4 decimals; None when either side is constant or n < 2."""
if len(xs) < 2 or len(set(xs)) < 2 or len(set(ys)) < 2:
return None
return round(statistics.correlation(xs, ys, method=method), 4)
@@ -254,15 +226,6 @@ def calibrate(
chat_model: Any = None,
fixed_order: bool = False,
) -> CalibrationTable:
- """Re-judge every round of ``run_dirs`` with ``n_samples`` and tabulate separation/noise.
-
- Writes ``calibration_<model>.json`` / ``.md`` into ``out_dir`` (default: cwd) and
- never touches the run directories. ``chat_model`` injects a ChatModel (tests).
- ``fixed_order`` sends every sample the same montage order, so ``mean_std`` becomes the
- model's own re-judge σ instead of its order-permutation σ (see ``VlmJudge.fixed_order``).
- ``thinking`` defaults to ``Settings.judge.thinking`` — the level the in-run judge uses, so
- a calibration measures the judge the loop runs (gemini-4-argon thinks only from 'medium', D105).
- """
model_id = model_id or get_settings().default_judge
thinking = thinking or get_settings().judge.thinking
out = Path(out_dir) if out_dir else Path.cwd()
@@ -273,11 +236,11 @@ def calibrate(
if not cases:
raise ValueError(f"no judgeable rounds found under {list(map(str, run_dirs))}")
geometry: dict[int, RenderSet | None] = {}
- for i, c in enumerate(cases): # a round's stored clay views win; render only where there are none
+ for i, c in enumerate(cases):
want = geometry_mode and c.is_picked and c.inp.geometry_views is None
geometry[i] = render_geometry_views(c, out, geometry_mode) if want else None
- def kind(c: RoundCase) -> tuple[str, str, bool]: # what make_judge's choice of class depends on
+ def kind(c: RoundCase) -> tuple[str, str, bool]:
return c.rubric, c.inp.spec.track.value, bool(c.inp.spec.references)
judges = {kind(c): make_judge(c.inp.spec, c.rubric, model_id, n_samples, thinking=thinking,
diff --git a/harness/codeverse3d/addons/costreport/audit.py b/harness/codeverse3d/addons/costreport/audit.py
index eaf083f0..d05e3f77 100644
--- a/harness/codeverse3d/addons/costreport/audit.py
+++ b/harness/codeverse3d/addons/costreport/audit.py
@@ -1,21 +1,4 @@
-"""Cost audit over a directory of runs: where the money and the minutes go.
-
-``audit_runs(paths)`` reads every run's own ledger (``telemetry/cost.jsonl``, the one record
-of money — docs/COST.md §12) and its record, stamps every row with the run's track /
-language / status, and aggregates:
-
-* $ per run, per track, per stage, per role, per backend, per model;
-* token composition (input / cached / output / thoughts) and the effective
- $/1k-token rate each bucket actually paid;
-* time next to the money — the run's minutes (``RunRecord.minutes``) and its model time;
-* **waste**: repair loops that never got their round to build, best-of-N candidates that
- lost, and spend in a round the clock cut. Nothing is waste for scoring below another
- round: since 2026-09-22 every round is kept and any of them can be the one handed over.
-
-A directory with no ledger has no rows and is left out: the reconstruction of pre-ledger
-runs from their trajectories, verdicts and events went on 2026-09-22 (434 of 467 archived
-runs carry a ledger; the 33 without are five v1 batteries outside the repo).
-"""
+"""Cost audit over a directory of runs: where the money and the minutes go."""
from __future__ import annotations
@@ -39,7 +22,6 @@ from codeverse3d.record.record import (
@dataclass
class RunLedger:
- """One run's (or compare cell's) ledger rows plus what a cost report says about it."""
run: str = ""
path: Path = Path()
@@ -48,11 +30,11 @@ class RunLedger:
status: str = ""
stop_reason: str = ""
n_rounds: int = 0
- round_built: list[bool | None] = field(default_factory=list) # per round: did its build (+repair) succeed
- selected_candidate: str = "" # "c1" when the run ran best-of-N and c1 won
- minutes: float | None = None # RunRecord.minutes (a one-shot cell: its cell.json minutes)
- cell_score: float | None = None # a one-shot compare cell's one score (it has no record)
- written_usd: float = 0.0 # the rows as written, before a --recheck re-priced them
+ round_built: list[bool | None] = field(default_factory=list)
+ selected_candidate: str = ""
+ minutes: float | None = None
+ cell_score: float | None = None
+ written_usd: float = 0.0
rows: list[CallCost] = field(default_factory=list)
@property
@@ -65,8 +47,6 @@ class RunLedger:
def _rows(root: Path, led: RunLedger, *, recheck: bool) -> None:
- """Add ``root``'s own ledger rows to ``led`` — stamped with its run name where a battery
- copied them without one, and re-priced from today's table when ``recheck``."""
for row in load_ledger(root):
led.written_usd += row.cost_usd
row.run = row.run or led.run
@@ -81,7 +61,6 @@ def _rows(root: Path, led: RunLedger, *, recheck: bool) -> None:
def read_run(run_dir: Path, *, name: str = "", recheck: bool = False) -> RunLedger:
- """A run directory: its ledger rows and its record's facts (an unreadable record keeps the rows)."""
led = RunLedger(run=name or run_dir.name, path=run_dir)
try:
rec = load_record(run_dir)
@@ -100,9 +79,6 @@ def read_run(run_dir: Path, *, name: str = "", recheck: bool = False) -> RunLedg
def read_cell(cell_dir: Path, *, name: str, recheck: bool = False) -> RunLedger:
- """A ``compare_backends`` / ``ab_plan`` cell. A harness arm is its run plus the cell's own
- ledger (the fixed evaluator's judge, a repair arm's extra generations); a one-shot or
- bare-agent arm is the cell ledger alone, described by ``cell.json`` and ``eval/spec.json``."""
if (cell_dir / "run" / "record.json").is_file():
led = read_run(cell_dir / "run", name=name, recheck=recheck)
else:
@@ -118,10 +94,6 @@ def read_cell(cell_dir: Path, *, name: str, recheck: bool = False) -> RunLedger:
def find_runs(root: str | Path) -> list[Path]:
- """Every run directory under ``root`` (a dir with ``record.json``) and every compare cell
- (a dir with ``cell.json``; one that wraps a harness run is named by the cell, not its
- ``run/``), found by ``record.find_run_dirs``: once each — a cell another battery symlinks in
- included — and never inside a run (its ``_assets/``, ``_cand/`` sub-workspaces are part of it)."""
base = Path(root)
if _is_run_or_cell(base):
return [base]
@@ -132,16 +104,14 @@ def _is_run_or_cell(d: Path) -> bool:
return is_run_dir(d) or (d / "cell.json").is_file()
-#: dimensions the audit always aggregates on
AUDIT_DIMENSIONS = ("run", "track", "language", "stage", "role", "backend", "model", "provider",
"status", "outcome", "source", "key")
@dataclass
class WasteItem:
- """One dollar that bought nothing (or bought a worse artifact)."""
- kind: str # repair_no_converge | lost_candidate | post_budget
+ kind: str
run: str
usd: float
detail: str = ""
@@ -150,7 +120,6 @@ class WasteItem:
@dataclass
class Audit:
- """Everything the report needs; ``summary`` holds the bucket maps."""
runs: list[RunLedger] = field(default_factory=list)
rows: list[CallCost] = field(default_factory=list)
@@ -200,7 +169,6 @@ class Audit:
def _waste(led: RunLedger) -> list[WasteItem]:
items: list[WasteItem] = []
- # repair loops that never got their round to build
unbuilt = {i for i, ok in enumerate(led.round_built) if ok is False}
repair = [r for r in led.rows if r.stage is Stage.REPAIR and r.round in unbuilt]
if repair:
@@ -208,16 +176,12 @@ def _waste(led: RunLedger) -> list[WasteItem]:
detail=f"{len(repair)} repair call(s) in round(s) "
f"{', '.join(f'r{i:02d}' for i in sorted({r.round for r in repair}))} "
f"that still did not build"))
- # best-of-N candidates that lost (their whole sub-workspace is thrown away): the candidate
- # clone's sessions are labelled ``baseline_c<k>``. Generator sessions only — the
- # quick-judge rows inside a candidate carry no candidate marker.
won = led.selected_candidate
losers = [r for r in led.rows if r.stage is Stage.CANDIDATE and not (won and r.label.endswith(f"_{won}"))]
if losers:
names = sorted({r.label.rsplit("_", 1)[-1] for r in losers})
items.append(WasteItem("lost_candidate", led.run, sum(r.cost_usd for r in losers),
detail=f"best-of-N: {', '.join(names)} lost to {won or '(unknown)'}"))
- # anything spent on a round that finished after the budget was blown
if led.stop_reason in ("budget",) or led.status == "budget":
extra = [r for r in led.rows if r.round is not None and led.n_rounds and r.round > led.n_rounds - 1]
if extra:
@@ -227,9 +191,6 @@ def _waste(led: RunLedger) -> list[WasteItem]:
def audit_runs(paths: Iterable[str | Path], *, recheck: bool = False) -> Audit:
- """Read + aggregate every run and cell under ``paths`` (run dirs or trees). A run is named
- by its place under the path it was found from (``RunId``), so an A/B battery's control and
- variant cells of one prompt stay two runs."""
audit = Audit()
for root in map(Path, paths):
for d in find_runs(root):
@@ -257,8 +218,6 @@ def _add(audit: Audit, led: RunLedger) -> None:
# --------------------------------------------------------------------------- derived views
def cached_input_share(audit: Audit) -> tuple[int, int, float]:
- """``(cached, total input, $ paid for cache reads)`` — how much of every prompt
- is context we have already sent before."""
cached = audit.summary.total.cached_tokens
total = audit.summary.total.input_tokens
usd = sum(min(r.cached_tokens, r.input_tokens) * r.price_cached / 1e6 for r in audit.rows)
@@ -266,8 +225,6 @@ def cached_input_share(audit: Audit) -> tuple[int, int, float]:
def uncached_if_no_cache(audit: Audit) -> float:
- """What the same traffic would have cost with a 0% cache-hit rate — the
- measured value of prompt caching as it stands today."""
extra = 0.0
for r in audit.rows:
cached = min(r.cached_tokens, r.input_tokens)
@@ -276,7 +233,6 @@ def uncached_if_no_cache(audit: Audit) -> float:
def stage_latency(audit: Audit) -> dict[str, tuple[float, float]]:
- """stage → (model seconds, share of all model seconds)."""
per: dict[str, float] = {}
for r in audit.rows:
per[str(r.stage)] = per.get(str(r.stage), 0.0) + r.latency_ms / 1000.0
@@ -285,7 +241,6 @@ def stage_latency(audit: Audit) -> dict[str, tuple[float, float]]:
def price_confidence(audit: Audit) -> dict[str, float]:
- """$ by how trustworthy the price row behind it is."""
out: dict[str, float] = {}
for r in audit.rows:
key = r.price_source if r.price_source in ("unknown", "provider-reported") \
diff --git a/harness/codeverse3d/addons/costreport/caching.py b/harness/codeverse3d/addons/costreport/caching.py
index c245aaa5..28fd7d12 100644
--- a/harness/codeverse3d/addons/costreport/caching.py
+++ b/harness/codeverse3d/addons/costreport/caching.py
@@ -1,18 +1,4 @@
-"""Per-session cache behaviour, read back out of the ledger.
-
-Gemini's implicit cache (and Anthropic's explicit one) only ever matches a
-**prefix**: the shared part must be byte-identical from token 0, and cache reads
-cost 10 % of input. This module answers the after-the-fact question — did a
-session's later turns actually read the cache, and what did that save?
-
-It used to also carry a prompt-ASSEMBLY half (``Block``/``order_blocks``/
-``prefix_report``/``cache_efficiency``) for building cache-friendly prompts. That
-experiment was measured and reverted (docs/COST.md §13: every prompt family here
-sits below the provider's minimum cacheable prefix, so reordering bought nothing),
-and the code sat with no production caller until it was deleted on 2026-08-28.
-
-``3dcode cost cache <slug>`` is the reader.
-"""
+"""Per-session cache behaviour, read back out of the ledger."""
from __future__ import annotations
@@ -23,7 +9,6 @@ from dataclasses import dataclass
# --------------------------------------------------------------------------- ledger view
@dataclass
class SessionCache:
- """Cache behaviour of ONE agent session (or one-shot call) as the ledger saw it."""
key: str
n_calls: int = 0
@@ -41,21 +26,14 @@ class SessionCache:
@property
def saved_usd(self) -> float:
- """USD the cache reads saved against paying full input price for them."""
return self.cached_tokens * max(0.0, self.price_input - self.price_cached) / 1e6
@property
def cold_usd(self) -> float:
- """USD still paid at full price for the uncached head of the session."""
return self.first_input * self.price_input / 1e6 if not self.first_cached else 0.0
def session_key(label: str) -> str:
- """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]
while parts and len(parts[-1]) > 1 and parts[-1][0] in "tsr" and parts[-1][1:].isdigit():
parts = parts[:-1]
@@ -63,13 +41,7 @@ def session_key(label: str) -> str:
def session_cache(rows: Sequence[object]) -> list[SessionCache]:
- """Per-session cache behaviour from ledger rows (``codeverse3d.cost.CallCost``).
-
- Sessions are ``(round, session_key(<key>))`` groups in ledger order, so the first row of a
- group is that session's cold turn — the one the audit shows pays full price
- (docs/COST.md §4). Use it to check whether a prompt-ordering change actually
- moved ``cached_tokens``, not just the prompt."""
- out: dict[tuple[object, str], SessionCache] = {} # insertion order IS ledger order
+ out: dict[tuple[object, str], SessionCache] = {}
for row in rows:
k = (getattr(row, "round", None), session_key(str(getattr(row, "label", "") or "")))
s = out.get(k)
diff --git a/harness/codeverse3d/addons/costreport/report.py b/harness/codeverse3d/addons/costreport/report.py
index 62111403..2e0b9821 100644
--- a/harness/codeverse3d/addons/costreport/report.py
+++ b/harness/codeverse3d/addons/costreport/report.py
@@ -64,8 +64,7 @@ BUCKET_HEADERS = ("key", "USD", "share", "calls", "input", "cached", "output", "
def keyed_buckets(audit: Audit) -> list[CostBucket]:
- """Per-API-key buckets (``CallCost.key``), most calls first; empty for ledgers
- written before the key suffix was recorded (2026-08-26)."""
+ """Per-API-key buckets (``CallCost.key``), most calls first."""
return sorted((b for b in audit.summary.dimension("key").values() if b.key != "(none)"),
key=lambda b: -b.n_calls)
diff --git a/harness/codeverse3d/addons/dataset/captions.py b/harness/codeverse3d/addons/dataset/captions.py
index b3c2c595..681321d3 100644
--- a/harness/codeverse3d/addons/dataset/captions.py
+++ b/harness/codeverse3d/addons/dataset/captions.py
@@ -1,19 +1,4 @@
-"""Caption one finished run: ``{detailed, instruction, factory}`` (STORAGE_RULES §6).
-
-* ``detailed`` image-grounded, objective description of what was rendered
- (parts, materials, proportions; motion / animation for articulated + scenes).
-* ``instruction`` one natural user request that asks for this as code and names
- the target language generically ("a Blender Python script", "a Three.js scene").
-* ``factory`` code-grounded build recipe: parts + construction order + techniques.
-
-Rules enforced in code: strict JSON schema, no API/class names, no brand names,
-each field non-empty. Captions are stored in ``record.extra["captions"]`` (with
-provenance) and ``<ws>/captions.json``; the run is re-packaged (deliverable/ +
-telemetry/ + ``record.json``, so the priced captioner call reaches the run's
-ledger and ``deliverable/captions.json`` exists) — or, with
-``out_dir`` (read-only runs), written as a side-car ``<out_dir>/<slug>.json`` that
-``export_samples(captions_dir=...)`` picks up.
-"""
+"""Caption one finished run: ``{detailed, instruction, factory}``."""
from __future__ import annotations
@@ -36,11 +21,8 @@ from codeverse3d.workspace import Workspace
MAX_CODE_CHARS = 12_000
N_VIEWS = 2
-#: view-name fragments that show motion (articulated track) — shown to the captioner first
MOTION_VIEW_HINTS = ("articulation", "pose_")
-#: how the instruction must name the target (generic, no API names), and the word that must
-#: appear in it (lower case)
LANGUAGE_PHRASE: dict[Language, tuple[str, str]] = {
Language.BLENDER: ("a Blender Python script", "blender"),
Language.CADQUERY: ("a CadQuery script", "cadquery"),
@@ -51,15 +33,12 @@ LANGUAGE_PHRASE: dict[Language, tuple[str, str]] = {
Language.GLSL_SHADER: ("a GLSL fragment shader", "glsl"),
Language.OPENGL_PYTHON: ("an OpenGL Python program", "opengl"),
}
-#: leaked API / platform tokens that must not appear in any caption. NOTE:
-#: ``THREE.`` (the API namespace) is checked case-sensitively below — the
-#: platform name "Three.js" is REQUIRED in threejs instructions and must not trip it.
+#: leaked API / platform tokens banned from captions; ``THREE.`` is checked case-sensitively because "Three.js" is required.
_FORBIDDEN = re.compile(
r"\b(bpy|bmesh|mathutils|cq\.|cadquery\.|GLTFLoader|ShaderMaterial|MeshStandardMaterial|"
r"Workplane|moderngl|Shadertoy|Sketchfab|Gemini|Claude|OpenAI|GPT|Antigravity)\b",
re.IGNORECASE,
)
-#: all-caps ``THREE.<Symbol>`` namespace usage (case-sensitive; "Three.js" / "THREE.js" stay legal)
_FORBIDDEN_THREE_NS = re.compile(r"\bTHREE\.(?!js\b)")
@@ -143,7 +122,6 @@ def _user_prompt(record: RunRecord, code: str) -> str:
def validate_captions(caps: Captions, language: Language) -> list[str]:
- """Rule violations (empty list = ok)."""
problems = []
for field in ("detailed", "instruction", "factory"):
m = _FORBIDDEN.search(getattr(caps, field)) or _FORBIDDEN_THREE_NS.search(getattr(caps, field))
@@ -159,15 +137,6 @@ def caption_sample(
ws: Workspace, record: RunRecord, model_id: str, *, model: object | None = None,
out_dir: Path | str | None = None, slug: str | None = None
) -> Captions:
- """Caption the round of ``record`` a sample is made of (``sample.exported_round``).
-
- Default: store into ``record.extra["captions"]`` + ``<ws>/captions.json`` and
- refresh what a caption changes: telemetry/ (``package_run``), ``record.json``, and
- ``deliverable/`` when a round has been packaged (it carries captions.json). With ``out_dir`` the workspace is left untouched and
- ``<out_dir>/<slug>.json`` (captions + provenance) is written instead — ``slug``
- should be the run's :class:`~codeverse3d.contracts.run.RunId` slug; without one the
- side-car falls back to the directory basename (flat layouts only: every nested
- battery run is named ``run`` and the side-cars would overwrite each other)."""
if model is None:
model = get_chat_model(model_id)
images, used = _round_images(ws, record)
@@ -185,7 +154,7 @@ def caption_sample(
resp = model.generate(ChatRequest(messages=messages, system=system, response_schema=schema,
temperature=0.3, thinking="low", max_wait_s=900.0, label="captioner")) # type: ignore[attr-defined]
cost += resp.usage.cost_usd
- data = resp.parsed # the adapters parse against response_schema (leniently) or raise
+ data = resp.parsed
try:
caps = Captions.model_validate(data)
except Exception as e:
@@ -211,10 +180,10 @@ def caption_sample(
from codeverse3d.record.record import package_run
ws.write_json(ws.root / "captions.json", payload)
- package_run(ws, record) # cost.json goes stale otherwise
+ package_run(ws, record)
ws.write_json(ws.record_path, record)
handed = load_deliverable(ws)
- if handed is not None and handed.round is not None: # ... and the hand-over's captions.json + manifest
+ if handed is not None and handed.round is not None:
build_deliverable(ws, record, handed.round)
return caps
diff --git a/harness/codeverse3d/addons/dataset/export.py b/harness/codeverse3d/addons/dataset/export.py
index ab9429d2..9efd4143 100644
--- a/harness/codeverse3d/addons/dataset/export.py
+++ b/harness/codeverse3d/addons/dataset/export.py
@@ -1,28 +1,4 @@
-"""Export run records → dataset sample folders + ``metadata.parquet``.
-
-``export_samples(runs_dir, out_dir)`` writes one sample folder per run (see
-``sample.py`` for the layout), records every file it wrote — sha256 each — in
-``<out>/dataset_manifest.json`` (:func:`write_manifest`, below) and builds the text
-index FROM those manifest entries, never from a directory rescan (so repeated
-exports into the same folder stay consistent and nothing the selection did not
-choose can leak into the index):
-
-* ``<out>/metadata.parquet`` — STORAGE_RULES §4 columns (``id, key, name,
- captions{detailed,instruction,factory}, meta_json, code, tar, byte_start,
- byte_len, n_files``) plus queryable extras (``track, language, score, passed,
- generator, quality_tier, complexity (+band), gate_errors, cost_usd, rounds, status,
- code_fingerprint, code_sha256, prompt_hash, duplicate_of, near_duplicate_of,
- has_captions``). ``tar``/``byte_*`` are filled by ``pack.py``; ``duplicate_of``
- (raw hash) and ``near_duplicate_of`` (normalised) by the dedupe pass.
-* ``<out>/metadata.jsonl`` — same rows, one JSON object per line.
-* ``<out>/duplicates.json`` — the duplicate groups found by the last export.
-* ``<out>/dataset_manifest.json`` — the generation manifest: the filters, one
- hashed entry per exported sample, and every dropped run with its reason
- (``duplicate_of:<id>`` for de-duplicated rows). ``pack.py`` consumes ONLY this.
-
-Captions come from ``record.extra["captions"]``, else ``<ws>/captions.json``,
-else ``<captions_dir>/<slug>.json`` (side-car written by ``3dcode flywheel caption --out``).
-"""
+"""Export run records → dataset sample folders + ``metadata.parquet``."""
from __future__ import annotations
@@ -71,12 +47,6 @@ class ExportReport(BaseModel):
def load_captions(
ws: Workspace, record: RunRecord, captions_dir: Path | None = None, *, slug: str | None = None
) -> dict[str, Any]:
- """Full captions dict (text fields + provenance) from record.extra, ``<ws>/captions.json``
- or ``<captions_dir>/<slug>.json``; ``{}`` when the run is not captioned.
-
- ``slug`` is the run's :class:`~codeverse3d.contracts.run.RunId` slug; without it the
- side-car falls back to the directory basename (correct only for flat layouts —
- every nested battery run is named ``run`` and would read a stranger's captions)."""
caps = record.extra.get("captions") or {}
if caps.get("detailed"):
return dict(caps)
@@ -95,7 +65,6 @@ def _caption_texts(caps: dict[str, Any]) -> dict[str, str]:
class ExportedSample(NamedTuple):
- """What :func:`export_one` wrote: the sample dir plus the hashes the manifest needs."""
dest: Path
file_hashes: dict[str, str]
@@ -107,11 +76,6 @@ def export_one(
ws: Workspace, record: RunRecord, out_dir: Path, *,
captions_dir: Path | None = None, run_id: RunId | None = None
) -> ExportedSample:
- """Write the sample folder for one run; returns the dir plus a sha256 per file
- written (every byte in the folder passes through here, so it is hashed here).
-
- ``run_id`` carries the collision-safe identity minted at discovery time; without
- one the key falls back to the directory basename (flat layouts only)."""
key = run_id.slug if run_id is not None else S.sample_key(ws)
dest = out_dir / S.sample_rel_dir(record, key)
rnd = S.exported_round(ws, record)
@@ -149,18 +113,6 @@ def export_samples(
captions_dir: Path | str | None = None,
drop_duplicates: bool = False,
) -> ExportReport:
- """Export every eligible run under ``runs_dir`` into ``out_dir`` and rebuild the index.
-
- The exported round is the one ``addons/select`` picks (the highest judged score, or
- what the run's ``selection.json`` handed over). Runs whose round never built are skipped unless
- ``include_unbuilt`` (failed runs are still useful for repair pairs, not as
- dataset samples). Byte-identical duplicates (same raw ``code_sha256`` + prompt)
- are marked ``duplicate_of`` and, with ``drop_duplicates``, left out of the index
- AND of the manifest entries, recorded under ``manifest.dropped`` as
- ``duplicate_of:<id>`` (folders stay on disk). Normalised duplicates are only
- MARKED (``near_duplicate_of``) — never dropped: whitespace inside a string
- literal is not a duplicate.
- """
out = Path(out_dir)
out.mkdir(parents=True, exist_ok=True)
rep = ExportReport()
@@ -168,10 +120,8 @@ def export_samples(
def _bad(d: Path, e: Exception) -> None:
rep.skipped[str(d)] = f"invalid record: {e}"
- # Fail FAST on identity collisions: two run dirs whose samples would land in the
- # same folder must abort before anything is written — the rmtree-before-write in
- # export_one is how 79 nested-battery records used to collapse into ONE sample.
- # A dest left by an EARLIER pass stays overwritable; only same-pass duplicates raise.
+ # Abort on same-pass identity collisions before writing anything (export_one rmtrees its dest);
+ # a dest left by an earlier pass stays overwritable.
found: list[FoundRun] = list(iter_runs(runs_dir, on_error=_bad))
dest_owner: dict[str, Path] = {}
for ws, rec, rid in found:
@@ -200,7 +150,7 @@ def export_samples(
if not include_unbuilt and not (rnd.build is not None and rnd.build.ok):
_skip(ws.root, rid, "the exported round did not build")
continue
- if only_passed and not (j is not None and j.passed): # the judge's verdict on THAT round
+ if only_passed and not (j is not None and j.passed):
_skip(ws.root, rid, "the judge did not pass the exported round")
continue
if min_score is not None and (score is None or score < min_score):
@@ -212,7 +162,7 @@ def export_samples(
except S.SampleError as e:
_skip(ws.root, rid, str(e))
continue
- except Exception as e: # git errors etc. — report, keep going
+ except Exception as e:
_skip(ws.root, rid, f"{type(e).__name__}: {e}")
continue
rep.n_exported += 1
@@ -222,8 +172,7 @@ def export_samples(
run=rid, sample_id=exported.meta.id, sample_rel_dir=rel_dir,
files=exported.file_hashes, code_fingerprint=exported.meta.code_fingerprint,
code_sha256=exported.code_sha256))
- # rows come from the manifest's own selection, never a rescan — a rescan is how
- # dropped duplicates used to ship and how a planted src/meta.json became a row
+ # rows come from the manifest's own selection, never a rescan.
rows = [row_for_sample(out / e.sample_rel_dir) for e in entries]
rep.duplicates = mark_duplicates(rows)
rep.n_duplicates = sum(len(g.duplicates) for g in rep.duplicates)
@@ -247,16 +196,11 @@ def export_samples(
rep.n_indexed = len(rows)
for r in rows:
rep.tiers[r["quality_tier"]] = rep.tiers.get(r["quality_tier"], 0) + 1
- # JSONL first, and unconditionally: it carries the same rows with no third-party
- # dependency, so a core-only install still gets a complete, indexed dataset.
rep.jsonl = str(write_jsonl(rows, out / JSONL_NAME))
try:
rep.parquet = str(write_parquet(rows, out / PARQUET_NAME))
except ImportError:
- # docs/INSTALL.md §4 scopes pyarrow to the `flywheel` extra and promises the
- # harness only raises at the moment the named feature is used. Crashing here
- # left a partial dataset on disk (samples written, no index at all) and the
- # rows were already computed — degrade loudly instead.
+ # pyarrow is an optional extra: degrade loudly instead of leaving a partial dataset.
rep.notes.append(f"{PARQUET_NAME} skipped: pyarrow is not installed "
f"(pip install -e 'harness[flywheel]'); {JSONL_NAME} has the same rows")
log.warning("%s", rep.notes[-1])
@@ -265,7 +209,6 @@ def export_samples(
# --------------------------------------------------------------------------- index rows
def row_for_sample(sample_dir: Path) -> dict[str, Any]:
- """One parquet row from a sample folder (reads meta.json / captions.json / entry)."""
meta_text = (sample_dir / "meta.json").read_text()
meta = json.loads(meta_text)
caps_path = sample_dir / "captions.json"
@@ -344,16 +287,6 @@ def parquet_schema() -> Any:
def write_parquet(rows: list[dict[str, Any]], path: Path, *, commit: bool = True) -> Path:
- """One row per sample, in :func:`parquet_schema` order. ``commit=False`` leaves the
- file at ``<path>.tmp`` and returns it, so a caller can publish it with other files.
-
- ``from_pylist(schema=...)`` DROPS any key the schema does not name, silently: that is
- how ``complexity`` / ``complexity_band`` — filled by :func:`row_for_sample`, kept in
- metadata.jsonl, and advertised in this module's docstring — went missing from the
- parquet, so every query of the dataset by complexity band returned nothing. The
- schema and the row keys are asserted equal here so a future column cannot vanish
- the same way.
- """
import pyarrow as pa
import pyarrow.parquet as pq
@@ -372,7 +305,6 @@ def write_parquet(rows: list[dict[str, Any]], path: Path, *, commit: bool = True
def write_jsonl(rows: list[dict[str, Any]], path: Path, *, commit: bool = True) -> Path:
- """``commit=False``: leave ``<path>.tmp`` and return it (see :func:`write_parquet`)."""
tmp = path.with_suffix(".jsonl.tmp")
with tmp.open("w") as fh:
for r in rows:
@@ -392,7 +324,6 @@ class ManifestError(RuntimeError):
class ManifestFilters(BaseModel):
- """The selection knobs the export ran with (provenance for the dataset)."""
min_score: float | None = None
only_passed: bool = False
@@ -403,7 +334,6 @@ class ManifestFilters(BaseModel):
class ManifestEntry(BaseModel):
- """One exported sample folder, hashed file by file at write time."""
run: RunId
sample_id: str
@@ -417,7 +347,6 @@ class ManifestEntry(BaseModel):
class DroppedRun(BaseModel):
- """A run the selection refused — nothing is dropped silently."""
run: RunId
reason: str = Field(description='filter reason, export error, or "duplicate_of:<sample id>"')
@@ -432,14 +361,12 @@ class DatasetGenerationManifest(BaseModel):
def write_manifest(manifest: DatasetGenerationManifest, out_dir: Path | str) -> Path:
- """Atomic write (tmp + replace) of ``<out_dir>/dataset_manifest.json``."""
if manifest.generated_at is None:
manifest = manifest.model_copy(update={"generated_at": datetime.now(UTC)})
return write_text_atomic(Path(out_dir) / MANIFEST_NAME, manifest.model_dump_json(indent=2))
def load_manifest(out_dir: Path | str) -> DatasetGenerationManifest:
- """Read ``<out_dir>/dataset_manifest.json``; missing or invalid is a hard error."""
path = Path(out_dir) / MANIFEST_NAME
if not path.is_file():
raise ManifestError(
diff --git a/harness/codeverse3d/addons/dataset/pack.py b/harness/codeverse3d/addons/dataset/pack.py
index 65fb2b8a..5eb98731 100644
--- a/harness/codeverse3d/addons/dataset/pack.py
+++ b/harness/codeverse3d/addons/dataset/pack.py
@@ -1,18 +1,5 @@
-"""Pack the manifest's sample folders into plain ``samples-NNN.tar`` files and fill
-the ``tar / byte_start / byte_len / n_files`` locator columns (STORAGE_RULES §3-4).
-
-``pack_samples`` consumes ONLY ``<out>/dataset_manifest.json`` (written by
-``export_samples``) — no directory rescan, so a duplicate dropped at export can
-never ship and nothing outside the manifest reaches an archive. Every file is
-sha256-verified against the manifest as it is added (fail fast, naming the file);
-the archives AND the two index files are written as ``.tmp`` and moved into place
-in one final loop, so a failure anywhere — including in ``write_parquet`` — leaves
-the previous archives and index untouched. Tars left over from a re-pack that
-produced fewer shards are removed after that loop.
-
-Each sample's files are written consecutively so ``byte_start..+byte_len`` is a
-valid sub-tar; ``verify_locators`` round-trips every row.
-"""
+"""Pack the manifest's sample folders into plain ``samples-NNN.tar`` files and fill the ``tar /
+byte_start / byte_len / n_files`` locator columns."""
from __future__ import annotations
@@ -38,7 +25,6 @@ from codeverse3d.addons.dataset.export import (
from codeverse3d.addons.dataset.quality import mark_duplicates
MAX_TAR_BYTES = int(2.5 * 1024**3)
-#: per-member allowance for tar headers/padding in the rollover size estimate
TAR_HEADER_SLACK = 1024
@@ -63,12 +49,6 @@ def _entry_sizes(sdir: Path, entry: ManifestEntry, rels: list[str]) -> int:
def pack_samples(out_dir: Path | str, *, tar_prefix: str = "", max_tar_bytes: int = MAX_TAR_BYTES) -> PackReport:
- """Write ``samples-NNN.tar`` under ``out_dir`` from the dataset manifest and
- rewrite the index (rows rebuilt from the manifest's sample dirs, locators filled).
-
- ``tar_prefix`` is prepended to the tar file name in the ``tar`` column so it
- can be repo-root-relative (e.g. ``"3dcodeverse/static_object/"``).
- """
out = Path(out_dir)
try:
manifest = load_manifest(out)
@@ -96,7 +76,7 @@ def pack_samples(out_dir: Path | str, *, tar_prefix: str = "", max_tar_bytes: in
tar.close()
final = out / f"samples-{tar_idx:03d}.tar"
tmp = out / f"samples-{tar_idx:03d}.tar.tmp"
- tar = tarfile.open(tmp, mode="w", format=tarfile.PAX_FORMAT) # noqa: SIM115 - closed in _open_new/finally
+ tar = tarfile.open(tmp, mode="w", format=tarfile.PAX_FORMAT) # noqa: SIM115
tmp_to_final.append((tmp, final))
final_name = final.name
rep.tars.append(final.name)
@@ -135,20 +115,18 @@ def pack_samples(out_dir: Path | str, *, tar_prefix: str = "", max_tar_bytes: in
rep.n_samples += 1
tar.close()
tar = None
- # the index is published WITH the tars: a failure here used to leave every new
- # tar in place and the old index pointing into it (byte offsets of a re-pack)
tmp_to_final.append((write_parquet(rows, out / PARQUET_NAME, commit=False), out / PARQUET_NAME))
tmp_to_final.append((write_jsonl(rows, out / JSONL_NAME, commit=False), out / JSONL_NAME))
done = True
finally:
- if not done: # leave the previous archives and index exactly as they were
+ if not done:
if tar is not None:
tar.close()
for tmp, _final in tmp_to_final:
tmp.unlink(missing_ok=True)
for tmp, final in tmp_to_final:
os.replace(tmp, final)
- for stale in out.glob("samples-*.tar"): # a re-pack with fewer shards must leave no dead tar
+ for stale in out.glob("samples-*.tar"):
n = stale.name[len("samples-"):-len(".tar")]
if n.isdigit() and int(n) >= tar_idx:
stale.unlink()
@@ -157,7 +135,6 @@ def pack_samples(out_dir: Path | str, *, tar_prefix: str = "", max_tar_bytes: in
def verify_locators(out_dir: Path | str) -> int:
- """Round-trip every row's byte range through ``tarfile``; returns rows checked."""
out = Path(out_dir)
import pyarrow.parquet as pq
diff --git a/harness/codeverse3d/addons/dataset/pairs.py b/harness/codeverse3d/addons/dataset/pairs.py
index 39f4eac6..3a311b7c 100644
--- a/harness/codeverse3d/addons/dataset/pairs.py
+++ b/harness/codeverse3d/addons/dataset/pairs.py
@@ -1,27 +1,4 @@
-"""Preference / repair / cross-backend pairs from run records (no model calls).
-
-Output is JSONL, one object per pair. All kinds share::
-
- {kind, run, prompt, prompt_hash, track, language, generator,
- chosen: {round, commit, files: {path: code}, score, truncated_files: [...]},
- rejected: {...}, delta, reason}
-
-* ``preference`` rounds i < j of one run with judge Δ ≥ ``min_delta``; reason =
- the judge's improvement plan of round i (what the builder was told to fix).
- Degraded (judge-outage) verdicts are treated as *no score*, never as a 0.0.
-* ``repair`` a failed build (round k) → the next round that builds, matched
- structurally (no track ever emits a ``kind='repair'`` round — lifecycle labels
- the fixing round ``refine``); ``error`` carries the structured build failure.
- ``source: "round"``.
-* ``repair`` (``source: "in_round"``) — a round whose build failed right after
- generation and was fixed by ``build_with_repair`` inside the same round
- (``notes`` say "repair attempts: N (fixed)"): the ``rNN <kind>: generated``
- commit is the rejected state, the round's final commit the chosen one; the
- error message comes from the round's failing ``build.done`` events.
-* ``cross_backend`` the same (prompt, track, language) run under ≥ 2 generators; each
- run is its picked round (``addons/select``), the top one against each other candidate
- with Δ ≥ ``min_delta``.
-"""
+"""Preference / repair / cross-backend pairs from run records (no model calls)."""
from __future__ import annotations
@@ -45,7 +22,6 @@ MAX_INLINE_CODE = 200_000
def _side(ws: Workspace, rnd: RoundRecord, *, cache: dict[str, dict[str, Any]]) -> dict[str, Any]:
- """Inline code (≤ 200 KB) for a round; cached per commit."""
key = rnd.commit or f"wt:{rnd.index}"
if key not in cache:
try:
@@ -81,16 +57,13 @@ def _base(ws: Workspace, rec: RunRecord, kind: str, *, slug: str | None = None)
}
-#: the judge Δ at which two rounds are a preference pair — and, in
-#: :mod:`codeverse3d.addons.dataset.refine`, the Δ at which a transition counts as improved. One
-#: constant, so a Δ that is a preference pair here is never "unchanged" there.
+#: judge delta at which two rounds are a preference pair (and a refine transition counts as improved).
MIN_PREFERENCE_DELTA = 0.05
def preference_pairs(ws: Workspace, rec: RunRecord, *, min_delta: float,
slug: str | None = None) -> list[dict[str, Any]]:
cache: dict[str, dict[str, Any]] = {}
- # degraded (judge-outage) verdicts are glitches, not 0.0 scores — leave those rounds out
judged = [r for r in rec.rounds if effective_judgment(r) is not None and r.commit]
out = []
for a_i, lo in enumerate(judged):
@@ -127,11 +100,6 @@ def _error_of(rnd: RoundRecord) -> dict[str, Any]:
def repair_pairs(ws: Workspace, rec: RunRecord, *, slug: str | None = None) -> list[dict[str, Any]]:
- """(broken round, error) → (the next round that builds).
-
- Matched structurally: the tracks never emit a ``kind='repair'`` round
- (lifecycle labels every post-baseline round ``refine``), so any round whose
- build succeeds directly repairs the nearest earlier failed build."""
cache: dict[str, dict[str, Any]] = {}
out = []
rounds = rec.rounds
@@ -155,7 +123,6 @@ def repair_pairs(ws: Workspace, rec: RunRecord, *, slug: str | None = None) -> l
def _round_build_errors(ws: Workspace, index: int) -> list[str]:
- """Failing ``build.done`` error messages of one round, from events.jsonl."""
out: list[str] = []
for ev in read_jsonl_lenient(ws.events_path, dicts_only=True):
if ev.get("event") == "build.done" and ev.get("round") == index and ev.get("ok") is False:
@@ -166,11 +133,6 @@ def _round_build_errors(ws: Workspace, index: int) -> list[str]:
def in_round_repair_pairs(ws: Workspace, rec: RunRecord, *, slug: str | None = None) -> list[dict[str, Any]]:
- """Builds fixed by ``build_with_repair`` *inside* a round.
-
- ``tracks/steps.py`` commits ``rNN <kind>: generated`` right before the
- build+repair loop and notes "repair attempts: N (fixed)" when the loop
- repaired a failing build; the generated tree is the rejected state."""
cache: dict[str, dict[str, Any]] = {}
out = []
for rnd in rec.rounds:
@@ -188,7 +150,7 @@ def in_round_repair_pairs(ws: Workspace, rec: RunRecord, *, slug: str | None = N
rej_files, rej_skipped = git_history.decode_text_files(raw, max_total=MAX_INLINE_CODE)
chosen = _side(ws, rnd, cache=cache)
if rej_files == chosen["files"]:
- continue # the repair changed nothing under the code roots
+ continue
errors = _round_build_errors(ws, rnd.index)
pair = _base(ws, rec, "repair", slug=slug)
pair.update(
@@ -208,8 +170,6 @@ def in_round_repair_pairs(ws: Workspace, rec: RunRecord, *, slug: str | None = N
def cross_backend_pairs(
groups: dict[tuple[str, str, str], list[tuple[Workspace, RunRecord, str]]], *, min_delta: float
) -> list[dict[str, Any]]:
- """``groups`` values are ``(ws, record, slug)`` — the slug is the RunId slug the
- scan minted (``ws.root.name`` collides across nested battery layouts)."""
out = []
for (_h, _t, _l), runs in groups.items():
gens = {r.spec.backends.generator for _, r, _s in runs}
@@ -217,7 +177,7 @@ def cross_backend_pairs(
continue
cands = []
for ws, rec, slug in runs:
- picked = select.summarise(ws.root, record=rec).picked_round # None = no judged round
+ picked = select.summarise(ws.root, record=rec).picked_round
rnd = next((r for r in rec.rounds if r.index == picked), None)
if rnd is not None:
cands.append((ws, rec, slug, rnd))
@@ -246,7 +206,6 @@ def cross_backend_pairs(
def build_pairs(runs_dir: Path | str, out_jsonl: Path | str, *, min_delta: float = MIN_PREFERENCE_DELTA) -> int:
- """Write all pair kinds for the runs under ``runs_dir``; returns the number written."""
out = Path(out_jsonl)
out.parent.mkdir(parents=True, exist_ok=True)
groups: dict[tuple[str, str, str], list[tuple[Workspace, RunRecord, str]]] = defaultdict(list)
diff --git a/harness/codeverse3d/addons/dataset/quality.py b/harness/codeverse3d/addons/dataset/quality.py
index b45ee81a..7852c208 100644
--- a/harness/codeverse3d/addons/dataset/quality.py
+++ b/harness/codeverse3d/addons/dataset/quality.py
@@ -1,8 +1,4 @@
-"""Code fingerprints, quality tiers and duplicate groups.
-
-* ``code_fingerprint(files)`` sha256 of whitespace/comment-normalised code.
-* ``code_sha256(files)`` sha256 of the raw bytes (the exact-content hash).
-"""
+"""Code fingerprints, quality tiers and duplicate groups."""
from __future__ import annotations
@@ -19,7 +15,6 @@ _TRAILING_COMMENT = re.compile(r"\s+(#|//).*$")
def normalise_code(text: str) -> str:
- """Drop comment-only lines, trailing comments, blank lines and all whitespace."""
out = []
for line in text.splitlines():
if _COMMENT.match(line):
@@ -32,7 +27,6 @@ def normalise_code(text: str) -> str:
def _digest(files: Mapping[str, str | bytes], content: Callable[[str | bytes], bytes]) -> str:
- """Order-independent sha256 over ``path \0 content(data) \0`` for every file."""
h = hashlib.sha256()
for path in sorted(files):
for part in (path.encode(), content(files[path])):
@@ -42,15 +36,11 @@ def _digest(files: Mapping[str, str | bytes], content: Callable[[str | bytes], b
def code_fingerprint(files: Mapping[str, str | bytes]) -> str:
- """Order-independent sha256 over ``(path, normalised code)`` pairs."""
return _digest(files, lambda data: normalise_code(
data.decode("utf-8", errors="replace") if isinstance(data, bytes) else data).encode())
def code_sha256(files: Mapping[str, str | bytes]) -> str:
- """Order-independent sha256 over the RAW ``(path, bytes)`` pairs — the
- exact-content counterpart of :func:`code_fingerprint` (no normalisation,
- no lossy decode)."""
return _digest(files, lambda data: data.encode("utf-8") if isinstance(data, str) else data)
@@ -61,12 +51,10 @@ TIER_C_MIN_SCORE = 0.6
def prompt_id(prompt: str) -> str:
- """Stable 16-hex id of a (stripped) user prompt — shared by samples, pairs and the index."""
return hashlib.sha256(prompt.strip().encode()).hexdigest()[:16]
def quality_tier(*, passed: bool | None, gate_errors: int, score: float | None) -> QualityTier:
- """Tier rule (see module docstring). ``passed`` None = never judged."""
if passed:
return "A" if gate_errors == 0 else "B"
if score is not None and score >= TIER_C_MIN_SCORE:
@@ -82,7 +70,6 @@ class DuplicateGroup(BaseModel):
def _rank(row: dict[str, Any]) -> tuple:
- """Lower is better: tier, -score, gate errors, un-captioned, key (stable)."""
score = row.get("score")
return (
TIER_ORDER.get(str(row.get("quality_tier") or "D"), 9),
@@ -94,8 +81,6 @@ def _rank(row: dict[str, Any]) -> tuple:
def _group(rows: Iterable[dict[str, Any]], column: str) -> list[DuplicateGroup]:
- """Groups of ≥ 2 rows sharing ``(row[column], prompt_hash)``; blank keys never group.
- The rows are not modified — ``mark_duplicates`` stamps them."""
buckets: dict[tuple[str, str], list[dict[str, Any]]] = defaultdict(list)
for r in rows:
key = str(r.get(column) or "")
@@ -113,18 +98,14 @@ def _group(rows: Iterable[dict[str, Any]], column: str) -> list[DuplicateGroup]:
def find_duplicates(rows: Iterable[dict[str, Any]]) -> list[DuplicateGroup]:
- """Exact duplicates: identical RAW ``(code_sha256, prompt_hash)`` — the only DROP set."""
return _group(rows, "code_sha256")
def find_near_duplicates(rows: Iterable[dict[str, Any]]) -> list[DuplicateGroup]:
- """Normalised duplicates (``code_fingerprint``) — MARKED as ``near_duplicate_of``, never dropped."""
return _group(rows, "code_fingerprint")
def mark_duplicates(rows: list[dict[str, Any]]) -> list[DuplicateGroup]:
- """Stamp ``duplicate_of`` (raw) and ``near_duplicate_of`` (normalised) in place;
- returns the exact groups — the only ones a caller may drop."""
groups = find_duplicates(rows)
dup_of = {d: g.canonical for g in groups for d in g.duplicates}
near_of = {d: g.canonical for g in find_near_duplicates(rows) for d in g.duplicates}
diff --git a/harness/codeverse3d/addons/dataset/refine.py b/harness/codeverse3d/addons/dataset/refine.py
index c9b37657..1b680b84 100644
--- a/harness/codeverse3d/addons/dataset/refine.py
+++ b/harness/codeverse3d/addons/dataset/refine.py
@@ -1,22 +1,4 @@
-"""Refine rounds as transitions: what the round was told, what it changed, what it scored.
-
-:mod:`codeverse3d.addons.dataset.pairs` exports whole code trees per round and never looks at what
-asked for the change, so a refine round arrives as two 30 kB files with no cause. This
-exports the transition instead — one row per refine round::
-
- (the previous round's judge issues + improvement plan + gate ERRORs with their
- fix hints + the refine tasks compiled for the round) -> src/ diff -> score delta
-
-Both sides come from the round's OWN recorded commit, never ``HEAD``: only 54 of 239
-recorded runs have HEAD at their last round, and 152 end on a "restore best round rNN"
-commit. ``instructions`` is ``RoundRecord.instructions``, the task list
-``build_refine_instructions`` compiled — not the per-group prompt text the sessions were
-handed, which is a rendering of it.
-
-The rows are data, not a training format: ``finetune/llamafactory/build_refine_sft.py``
-turns them into the message shape the finetune pipeline consumes. ``--with-code`` inlines
-the changed files so that conversion needs no access to the runs.
-"""
+"""Refine rounds as transitions: what the round was told, what it changed, what it scored."""
from __future__ import annotations
@@ -39,15 +21,11 @@ from codeverse3d.record.git_history import (
from codeverse3d.record.record import effective_judgment, effective_score, iter_runs
from codeverse3d.workspace import Workspace
-#: rounds that answer a judgment. An asset round is driven by its own pass, and
-#: a repair round by a build error the judge never saw.
REFINE_KINDS: tuple[str, ...] = ("refine", "rewrite", "detail")
-#: a diff longer than this is truncated, with the untruncated size kept on the row
MAX_DIFF_BYTES = 200_000
class RefineTransition(BaseModel):
- """One refine round: its brief, its diff, its score delta."""
battery: str
run: str
@@ -73,8 +51,6 @@ class RefineTransition(BaseModel):
score_after: float | None
score_delta: float | None
outcome: str = Field(description="improved | unchanged | regressed | unscored")
- #: --with-code: the WHOLE tree before (the state the brief describes) and only the
- #: files the round changed after (the answer), so a converter needs no run access
before_files: dict[str, str] | None = None
after_files: dict[str, str] | None = None
@@ -93,8 +69,6 @@ def _gate_errors(rnd: RoundRecord) -> list[dict[str, Any]]:
def outcome_of(delta: float | None, threshold: float) -> str:
- """The label. One rule, shared with ``pairs.MIN_PREFERENCE_DELTA``, so a Δ that is a
- preference pair there is never "unchanged" here."""
if delta is None:
return "unscored"
if delta >= threshold:
@@ -117,7 +91,7 @@ def _transition(ws: Workspace, rec: RunRecord, prev: RoundRecord, cur: RoundReco
try:
out[path] = raw.decode("utf-8")
except UnicodeDecodeError:
- continue # a binary file under src/: the diff already says it changed
+ continue
return out
files_before, files_after = _text(prev.commit, None), _text(cur.commit, changed)
return RefineTransition(
@@ -134,12 +108,6 @@ def _transition(ws: Workspace, rec: RunRecord, prev: RoundRecord, cur: RoundReco
def transitions(runs_dir: Path | str, *, threshold: float = MIN_PREFERENCE_DELTA,
max_diff_bytes: int = MAX_DIFF_BYTES, with_code: bool = False,
drops: Counter[str] | None = None) -> Iterator[RefineTransition]:
- """Every exportable refine transition under ``runs_dir``; every one that is not is counted.
-
- A run reachable through more than one path (54 of 239 under ``eval/bench/out``, where the
- batteries symlink each other's cells) is found once (``find_run_dirs``), at the path it
- physically lives at. A row is named by its ``RunId`` (``battery``, ``run`` = the slug), the
- 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__}"])):
@@ -165,7 +133,6 @@ def transitions(runs_dir: Path | str, *, threshold: float = MIN_PREFERENCE_DELTA
def build_refine(runs_dir: Path | str, out_jsonl: Path | str, **kw: Any) -> tuple[int, Counter[str]]:
- """Write the transitions as JSONL; return ``(rows, drops)``."""
drops: Counter[str] = Counter()
out = Path(out_jsonl)
out.parent.mkdir(parents=True, exist_ok=True)
diff --git a/harness/codeverse3d/addons/dataset/sample.py b/harness/codeverse3d/addons/dataset/sample.py
index 22db94f4..5a2a5932 100644
--- a/harness/codeverse3d/addons/dataset/sample.py
+++ b/harness/codeverse3d/addons/dataset/sample.py
@@ -1,16 +1,4 @@
-"""One dataset sample from one run: typed ``meta.json`` + folder layout.
-
-Sample folder (STORAGE_RULES §3/§8 compatible)::
-
- <out>/<track>/<language>/<key>/
- code.<ext> copy of the entry file (parquet ``code`` column)
- src/** the full raw code tree at the exported commit (lossless)
- robot.urdf (urdf_blender) copy of src/robot.urdf
- meta.json SampleMeta (typed, below)
- captions.json {detailed, instruction, factory} or {} when not captioned
- renders/ view_*.png, sheet.png, object.glb (< 20 MB)
- meshes/<link>.glb (urdf_blender) per-link meshes referenced by robot.urdf
-"""
+"""One dataset sample from one run: typed ``meta.json`` + folder layout."""
from __future__ import annotations
@@ -52,7 +40,6 @@ class SampleError(RuntimeError):
class AcceptanceEntry(BaseModel):
- """One plan acceptance item joined with the judge's verdict for the exported round."""
id: str
text: str = ""
@@ -62,7 +49,6 @@ class AcceptanceEntry(BaseModel):
class SampleMeta(BaseModel):
- """``meta.json`` — everything a consumer needs without opening record.json."""
id: str
key: str
@@ -120,10 +106,6 @@ class SampleMeta(BaseModel):
def sample_key(ws: Workspace) -> str:
- """FALLBACK key: the directory basename — correct for the flat ``runs/<id>``
- layout only. Exporters that scanned a root pass the collision-safe
- :class:`~codeverse3d.contracts.run.RunId` slug instead (``export_one(run_id=…)``):
- in nested battery layouts every run dir is literally named ``run``."""
return ws.root.name
@@ -136,16 +118,11 @@ def sample_rel_dir(record: RunRecord, key: str) -> Path:
def exported_round(ws: Workspace, record: RunRecord) -> RoundRecord | None:
- """The round a sample is made of: the one every reader shows (``select.summarise().round``:
- the pick, else — nothing judged — ``select.fallback_round``, a score-less tier-D sample),
- else — no round built with renders — the last round (``export --include-unbuilt``'s code)."""
shown = select.summarise(ws.root, record=record).round
return next((r for r in record.rounds if r.index == shown), record.rounds[-1] if record.rounds else None)
def code_files_for_round(ws: Workspace, rnd: RoundRecord | None) -> tuple[dict[str, bytes], str]:
- """Raw code tree for a round → ``(files, source)`` where source is ``commit``,
- ``deliverable`` (the packaged snapshot of the handed-over round) or ``working_tree``."""
if rnd is not None and rnd.commit and ws.has_commit(rnd.commit):
return git_history.read_tree_at(ws, rnd.commit), "commit"
packaged = _deliverable_code(ws)
@@ -155,8 +132,6 @@ def code_files_for_round(ws: Workspace, rnd: RoundRecord | None) -> tuple[dict[s
def _deliverable_code(ws: Workspace) -> dict[str, bytes]:
- """``deliverable/src|public/**`` — the snapshot kept when git is unreadable
- (a run copied without its .git, an archived deliverable)."""
files: dict[str, bytes] = {}
for root in git_history.CODE_ROOTS:
base = ws.deliverable / root
@@ -169,7 +144,6 @@ def _deliverable_code(ws: Workspace) -> dict[str, bytes]:
def write_code_tree(dest: Path, files: dict[str, bytes], language: Language) -> tuple[str, list[str]]:
- """Write ``src/**`` + ``code.<ext>`` (+ ``robot.urdf``); return (entry, written paths)."""
written: list[str] = []
for rel, data in sorted(files.items()):
p = dest / rel
@@ -188,7 +162,6 @@ def write_code_tree(dest: Path, files: dict[str, bytes], language: Language) ->
def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str]:
- """Copy the round's views, contact sheet and a small object.glb."""
out: list[str] = []
rdir = dest / "renders"
rdir.mkdir(parents=True, exist_ok=True)
@@ -201,7 +174,7 @@ def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str
if rnd is not None and rnd.renders is not None:
names = [v.name for v in rnd.renders.views]
- by_stem = len(set(names)) != len(names) # scene views repeat a camera name per time → use file stems
+ by_stem = len(set(names)) != len(names)
for v in rnd.renders.views:
src = ws.rebase(v.path)
if not src.is_file():
@@ -216,9 +189,9 @@ def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str
if sheet.is_file():
_cp(sheet, f"sheet{sheet.suffix or '.png'}")
if not any(o.startswith("renders/sheet") for o in out):
- packaged = ws.deliverable / "sheet.png" # the handed-over round's sheet
+ packaged = ws.deliverable / "sheet.png"
_cp(packaged if packaged.is_file() else None, "sheet.png")
- for name in ("object.glb", "preview.gif"): # the round's OWN build (graphics: its animated loop preview)
+ for name in ("object.glb", "preview.gif"):
src = select.round_file(ws, rnd, name)
if src is not None and src.stat().st_size < MAX_GLB_BYTES:
_cp(src, name)
@@ -226,7 +199,6 @@ def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str
def copy_link_meshes(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str]:
- """(urdf_blender) copy the round's own per-link meshes so the sample's robot.urdf resolves."""
out_dir = round_outputs(ws, rnd)
src = out_dir / "meshes" if out_dir is not None else None
if src is None or not src.is_dir():
@@ -244,7 +216,6 @@ def copy_link_meshes(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list
def acceptance_entries(record: RunRecord, rnd: RoundRecord | None) -> list[AcceptanceEntry]:
- """Plan checklist items joined with the round's judge verdicts (ids only when no plan)."""
j = effective_judgment(rnd) if rnd is not None else None
verdicts = dict(j.acceptance_results) if j is not None else {}
items = list(getattr(record.plan, "acceptance", []) or []) if record.plan is not None else []
@@ -264,13 +235,11 @@ def build_meta(
captions: dict[str, Any] | None = None,
) -> SampleMeta:
spec = record.spec
- j = effective_judgment(rnd) if rnd is not None else None # degraded verdicts count as unjudged
+ j = effective_judgment(rnd) if rnd is not None else None
caps = captions if captions is not None else (record.extra.get("captions") or {})
code_files = [f for f in files if f.startswith("src/")]
gates = gate_error_summary(rnd)
n_gate_errors = sum(gates.values())
- # difficulty next to quality: a tier-A five-box stool and a tier-A machine are
- # not the same training sample (eval/docs/COMPLEXITY.md)
cx = select.round_complexity_block(ws, rnd)
name = ""
if record.plan is not None:
@@ -327,9 +296,6 @@ def build_meta(
def telemetry_digest(ws: Workspace, record: RunRecord) -> dict[str, Any]:
- """The few accounting numbers a dataset consumer wants inline: total, per stage,
- model + thinking level per role, rubric/price hashes. ``{}`` when a run has no
- telemetry (old layout and nothing computable)."""
from codeverse3d.record.telemetry import load_telemetry
tele = load_telemetry(ws, record)
diff --git a/harness/codeverse3d/addons/gallery/cards.py b/harness/codeverse3d/addons/gallery/cards.py
index 60c7e416..f15f843c 100644
--- a/harness/codeverse3d/addons/gallery/cards.py
+++ b/harness/codeverse3d/addons/gallery/cards.py
@@ -1,16 +1,4 @@
-"""One run, drawn three ways: a card, a table row, and a compare column.
-
-Design rules this module exists to hold in one place:
-
-* **one hero image per card.** A card is a scanning target, not a proof sheet:
- eight 70 px tiles in a 320 px card are eight illegible tiles. The contact
- sheet is still one click away (the ``⊞ n`` disclosure over the image).
-* **two links, then a menu.** ``detail`` plus the one artifact that track
- actually wants; everything else lives behind ``⋮`` so a wall of blue text
- never competes with the render.
-* **the verdict is peripheral.** A 6 px coloured rail down the left edge is
- readable out of the corner of the eye while scrolling; a pill is not.
-"""
+"""One run, drawn three ways: a card, a table row, and a compare column."""
from __future__ import annotations
@@ -18,8 +6,6 @@ from codeverse3d.addons.gallery.model import VERDICT_META, RunEntry, RunLink, hu
from codeverse3d.addons.gallery.theme import esc
from codeverse3d.addons.gallery.urls import UrlMaker
-#: links promoted next to ``detail`` on the card, best-first — the one artifact
-#: you actually open for that track
PRIMARY_LINKS = ("glb", "preview.gif", "articulation", "src/")
@@ -28,11 +14,6 @@ def fmt(value: float | None, digits: int = 3, dash: str = "—") -> str:
def complexity_chip(entry: RunEntry) -> str:
- """``cx 0.65`` — how much artifact was actually built, next to what it scored.
-
- Complexity is *difficulty*, not quality: the pair is the point. A run with no
- complexity block (a graphics/scene run, or one recorded before the vector
- existed) simply shows nothing."""
if entry.complexity is None:
return ""
axes = " · ".join(f"{k.replace('_', ' ')} {v:g}" for k, v in entry.complexity_axes.items())
@@ -50,7 +31,6 @@ def verdict_tag(entry: RunEntry) -> str:
def _menu(entry: RunEntry, urls: UrlMaker, shown: set[str]) -> str:
- """Everything that did not earn a place on the card, behind a ``⋮``."""
rest = [ln for ln in entry.links if ln.label not in shown]
if not rest:
return ""
@@ -73,14 +53,13 @@ def card_actions(entry: RunEntry, urls: UrlMaker) -> str:
if primary is not None:
shown.add(primary.label)
parts.append(f"<a href='{esc(urls.link(entry, primary))}'>{esc(primary.label)}</a>")
- if not urls.has_detail: # the static build has no detail page: offer the workspace instead
+ if not urls.has_detail:
parts.insert(0, f"<a class='go' href='{esc(urls.dir(entry))}'>workspace →</a>")
shown.add("workspace")
return f"<div class='actions'>{''.join(parts)}{_menu(entry, urls, shown)}</div>"
def card_shot(entry: RunEntry, urls: UrlMaker) -> str:
- """The hero view, with the full contact sheet one disclosure click away."""
image = entry.card_image
if not image:
return "<div class='shot'><div class='noshot'>no render</div></div>"
@@ -105,10 +84,6 @@ def select_box(entry: RunEntry) -> str:
def render_card(entry: RunEntry, urls: UrlMaker, *, hidden: bool = False) -> str:
- """One run card. A pending / broken run keeps the same shape and says why.
-
- ``hidden`` pre-applies the server-side filter, so a curl'd query string shows
- the right runs while the client can still widen the filter without a reload."""
hide = " is-hidden" if hidden else ""
name = entry.title or entry.slug
head = (f"<div class='titlerow'>{tier_tag(entry)}"
@@ -136,7 +111,6 @@ def render_card(entry: RunEntry, urls: UrlMaker, *, hidden: bool = False) -> str
+ cx)
gates = (f"<span class='tag pill-warn'>{entry.gate_errors} gate err</span>" if entry.gate_errors
else "<span class='tag pill-ok'>gates clean</span>")
- # why the run stopped (max_rounds / budget / agent_quota / …) — never a pass or a fail
status = f"<span class='tag' title='why the run stopped'>{esc(entry.status)}</span>" if entry.status else ""
caption = f"<p class='xs faint clamp1'>{esc(entry.caption)}</p>" if entry.caption else ""
err = f"<div class='err clamp2' title='{esc(entry.error)}'>{esc(entry.error[:300])}</div>" \
@@ -187,7 +161,6 @@ def render_row(entry: RunEntry, urls: UrlMaker, *, hidden: bool = False) -> str:
def gallery_figure(label: str, href: str, src: str, *, eager: bool = False) -> str:
- """A render tile whose caption floats on a gradient instead of a black bar."""
human = humanize_view(label)
loading = "eager" if eager else "lazy"
return (f"<figure><a href='{esc(href)}'>"
diff --git a/harness/codeverse3d/addons/gallery/compare.py b/harness/codeverse3d/addons/gallery/compare.py
index 67cb7f22..e16c844e 100644
--- a/harness/codeverse3d/addons/gallery/compare.py
+++ b/harness/codeverse3d/addons/gallery/compare.py
@@ -1,13 +1,4 @@
-"""Bulk triage: the side-by-side compare page and the CSV export.
-
-Both are **read-only projections of the index** — ``/compare?runs=a/b,c/d`` and
-``/export.csv?runs=…`` (or any index filter). Nothing here writes, queues or
-re-runs anything: the gallery deliberately exposes no mutation endpoint, so the
-bulk bar offers *compare*, *export* and *copy paths* and stops there.
-
-The compare page is a metric-per-row table so the eye travels along one row and
-compares like with like; a per-run column of stacked cards does not do that.
-"""
+"""Bulk triage: the side-by-side compare page and the CSV export."""
from __future__ import annotations
@@ -20,7 +11,6 @@ from codeverse3d.addons.gallery.model import VERDICT_META, RunEntry
from codeverse3d.addons.gallery.theme import esc, footer, page_shell, top_bar
from codeverse3d.addons.gallery.urls import UrlMaker
-#: how many runs a compare page will lay out before it says "too many"
MAX_COMPARE = 8
COMPARE_CSS = """
@@ -87,7 +77,6 @@ def _delta(entry: RunEntry) -> str:
def render_compare(entries: list[RunEntry], urls: UrlMaker, *, note: str = "") -> str:
- """``n`` runs as columns, one metric per row."""
if not entries:
inner = ("<div class='panel'><h2>nothing to compare</h2><p class='muted'>Tick two or more "
"runs on the index and press <b>compare</b>.</p></div>")
@@ -156,8 +145,6 @@ _FORMULA_PREFIXES = ("=", "+", "-", "@")
def csv_safe(value: object) -> object:
- """Neutralise spreadsheet formula injection: a string cell starting with
- ``= + - @`` (an LLM-written prompt or title can) is prefixed with ``'``."""
if isinstance(value, str) and value.startswith(_FORMULA_PREFIXES):
return "'" + value
return value
@@ -169,7 +156,6 @@ CSV_COLUMNS = ("battery", "slug", "title", "verdict", "tier", "track", "language
def export_csv(entries: list[RunEntry]) -> str:
- """The selected runs as CSV — the one export a read-only tool owes a spreadsheet."""
buf = io.StringIO()
writer = csv.writer(buf, lineterminator="\n")
writer.writerow(CSV_COLUMNS)
diff --git a/harness/codeverse3d/addons/gallery/detail.py b/harness/codeverse3d/addons/gallery/detail.py
index ea1926a2..5681a5ba 100644
--- a/harness/codeverse3d/addons/gallery/detail.py
+++ b/harness/codeverse3d/addons/gallery/detail.py
@@ -1,11 +1,4 @@
-"""The per-run detail page (``/run/<battery>/<slug>``).
-
-Everything the harness recorded about one run, in the order you actually ask
-for it: what it produced, how each round went, what the judge said about the
-picked round (``addons/select``), what the deterministic measurement says, every
-render, where the money went, and the code itself. The record is re-read per request, so a run a
-bench is still writing shows its latest rounds without a restart.
-"""
+"""The per-run detail page (``/run/<battery>/<slug>``)."""
from __future__ import annotations
@@ -57,7 +50,6 @@ ul.plain li{display:list-item}
"""
-#: judge severities, worst first — a triage reader must see "critical" before "minor"
SEVERITY_ORDER = {"critical": 0, "blocker": 0, "major": 1, "moderate": 2, "minor": 3, "nit": 4}
SEVERITY_CLASS = {"critical": "pill-fail", "blocker": "pill-fail", "major": "pill-fail",
"moderate": "pill-warn", "minor": "pill-warn"}
@@ -78,8 +70,6 @@ def _picked(entry: RunEntry, rec: RunRecord) -> RoundRecord | None:
def _hero(entry: RunEntry, urls: UrlMaker, rec: RunRecord) -> str:
- """One big legible view + the facts. Every other angle is in ``renders`` below,
- which is where a grid belongs — the top of the page answers "what is this?"."""
image = entry.hero or entry.sheet
label = entry.hero_label or ("Contact sheet" if entry.sheet else "")
shot = (f"<a href='{esc(urls.file(entry, image))}' title='open full size'>"
@@ -193,7 +183,6 @@ def _measurement_panel(entry: RunEntry, rec: RunRecord) -> str:
return _panel("measurement", f"<div class='kvs'>{rows}</div>{parts}", anchor="measurement")
-#: axis -> (label, format) for the complexity panel, in reading order
_CX_ROWS = (
("part_count", "parts", "{:.0f}"),
("assembly_depth", "sub-assembly depth", "{:.0f}"),
@@ -207,10 +196,6 @@ _CX_ROWS = (
def _complexity_panel(entry: RunEntry, rec: RunRecord) -> str:
- """What was BUILT, measured without a VLM — the difficulty half of the verdict.
-
- Read it next to the judge panel: a high score on a low index is an easy win,
- a low score on a high index is the framework hitting its ceiling."""
block = rec.extra.get("complexity")
if entry.complexity is None and not isinstance(block, dict):
return ""
@@ -224,7 +209,7 @@ def _complexity_panel(entry: RunEntry, rec: RunRecord) -> str:
plan_parts = block.get("plan_parts")
if isinstance(plan_parts, int) and plan_parts:
rows.append(_kv("plan parts", str(plan_parts)))
- built = entry.complexity_axes.get("part_count", block.get("part_count")) # the picked round's
+ built = entry.complexity_axes.get("part_count", block.get("part_count"))
if isinstance(built, (int, float)):
rows.append(_kv("built / planned parts", f"{float(built) / plan_parts:.2f}"))
trail = block.get("by_round")
@@ -262,7 +247,6 @@ def _cost_panel(entry: RunEntry, ws: Workspace, rec: RunRecord) -> str:
tele = load_telemetry(ws, rec)
cost = tele.cost if tele is not None else None
if cost is None:
- # old runs have no telemetry/: fall back to the record's own totals + per-round usage
rows = "".join(_kv(k, f"${v:.4f}") for k, v in sorted(entry.cost_by_stage.items(), key=lambda kv: -kv[1]))
u = rec.total_usage
rows += "".join([_kv("total", f"${u.cost_usd:.4f}"),
@@ -316,7 +300,6 @@ def _code_panel(entry: RunEntry, urls: UrlMaker, rec: RunRecord) -> str:
# --------------------------------------------------------------------------- page
def _neighbours(urls: UrlMaker, prev: RunEntry | None, nxt: RunEntry | None) -> str:
- """Triage is sequential: the next bad run is one click away, not a trip home."""
def one(target: RunEntry | None, glyph: str, side: str, ident: str) -> str:
if target is None:
return f"<span class='btn dead' aria-hidden='true'>{glyph}</span>"
@@ -328,7 +311,6 @@ def _neighbours(urls: UrlMaker, prev: RunEntry | None, nxt: RunEntry | None) ->
def _foot_nav(urls: UrlMaker, prev: RunEntry | None, nxt: RunEntry | None) -> str:
- """The same walk, repeated where the reader actually finishes reading."""
def one(target: RunEntry | None, glyph: str) -> str:
if target is None:
return "<span></span>"
@@ -353,7 +335,6 @@ document.addEventListener('keydown',function(e){
def render_detail(entry: RunEntry, urls: UrlMaker, ws: Workspace, rec: RunRecord, *,
prev: RunEntry | None = None, nxt: RunEntry | None = None) -> str:
- """Full detail page for a run whose record parsed."""
nav = "".join(f"<a href='#{a}'>{a}</a>" for a in
("rounds", "judge", "complexity", "measurement", "renders", "cost", "code"))
body = (
@@ -381,7 +362,6 @@ def render_detail(entry: RunEntry, urls: UrlMaker, ws: Workspace, rec: RunRecord
def render_broken_detail(entry: RunEntry, urls: UrlMaker) -> str:
- """Detail page for a run with no usable record — still links every file."""
links = " · ".join(f"<a href='{esc(urls.link(entry, link))}'>{esc(link.label)}</a>" for link in entry.links)
body = (top_bar("3dcode gallery", entry.battery,
crumbs=f"<a href='/'>gallery</a> <span class='faint'>/</span> <b>{esc(entry.slug)}</b>")
diff --git a/harness/codeverse3d/addons/gallery/index.py b/harness/codeverse3d/addons/gallery/index.py
index 5c4310cd..310ad592 100644
--- a/harness/codeverse3d/addons/gallery/index.py
+++ b/harness/codeverse3d/addons/gallery/index.py
@@ -1,14 +1,4 @@
-"""Build the gallery index from run roots.
-
-``build_index(roots)`` walks every run directory once, reads ``record.json`` and
-turns it into a :class:`~codeverse3d.addons.gallery.model.RunEntry` whose every path is
-**run-relative**. It is deliberately cheap (no image work, no git): ~80 runs
-index in well under a second, which is what makes ``--reload`` free.
-
-Robustness is a feature here, not a nicety: a bench writing into these
-directories means a record can be absent, empty or half-written at any moment,
-and the gallery must still render. Nothing in this module raises for one bad run.
-"""
+"""Build the gallery index from run roots."""
from __future__ import annotations
@@ -40,13 +30,11 @@ from codeverse3d.record.record import (
)
from codeverse3d.workspace import Workspace
-#: run roots the CLI defaults to when the user names none
DEFAULT_RUNS = "runs"
DEFAULT_BENCH_GLOB = "eval/bench/out/*/runs"
def default_roots(base: Path | str = ".") -> list[Path]:
- """``runs/`` plus every ``eval/bench/out/*/runs`` that exists, in that order."""
base = Path(base)
roots: list[Path] = []
if (base / DEFAULT_RUNS).is_dir():
@@ -83,24 +71,14 @@ def _round_sheet(ws: Workspace, rec: RunRecord, index: int) -> str:
def picked_sheet(ws: Workspace, rec: RunRecord, picked: int | None) -> str:
- """Contact sheet of the card's round (``select.summarise().round``), else the packaged
- deliverable sheet — never another round's."""
return (_round_sheet(ws, rec, picked) if picked is not None else "") or _first_file(
ws.root, "deliverable/sheet.png", "artifacts/frames_sheet.png")
-#: view names that make the best single thumbnail, most telling first. A ¾ view
-#: shows silhouette *and* depth; a flat orthographic front hides both. A stored pre-D47
-#: run matches through ``conventions.view_key``.
HERO_PREFERENCE = ("front_right_high", "back_left_high", "front_right_low", "front_left_low", "front")
def hero_view(ws: Workspace, rec: RunRecord, picked: int | None) -> tuple[str, str, int]:
- """``(rel, label, n_views)`` — the ONE image a card should show (from the picked round).
-
- A card that shows an 8-up contact sheet at 320 px shows eight unreadable
- thumbnails; one 320 px hero view is legible. Costs a single ``is_file``
- beyond what the record already told us, so the index stays cheap."""
rnd = next((r for r in rec.rounds if r.index == picked), None)
if rnd is None or rnd.renders is None or not rnd.renders.views:
return "", "", 0
@@ -115,17 +93,11 @@ def hero_view(ws: Workspace, rec: RunRecord, picked: int | None) -> tuple[str, s
def _articulation_sheet(ws: Workspace, picked: int | None) -> str:
- """The card's round's pose sheet — never another round's."""
rel = f"artifacts/renders/r{picked:02d}/poses/articulation_sheet.png" if picked is not None else ""
return rel if rel and (ws.root / rel).is_file() else ""
def entry_links(ws: Workspace, rec: RunRecord | None, picked: int | None) -> list[RunLink]:
- """The working links of a card: workspace, record, code, sheet, GLB, track extras — the
- artifact files of the handed-over round (``deliverable/``), else of the picked round
- (``select.round_file``: ``artifacts/rNN/``, or ``artifacts/`` of a run recorded before rounds
- kept their own, for the round it rebuilt there) — never another round's. A run with no
- round to show (no record yet, no round built with renders) links whatever ``artifacts/`` holds."""
run = ws.root
rnd = next((r for r in rec.rounds if r.index == picked), None) if rec is not None else None
out = round_outputs(ws, rnd)
@@ -177,18 +149,14 @@ def round_rows(ws: Workspace, rec: RunRecord) -> list[RoundRow]:
for row in select.round_rows(ws.root, record=rec)]
-#: complexity axes worth putting on a card / detail page (the index carries the rest)
_CX_AXES = ("part_count", "assembly_depth", "tri_count", "materials",
"silhouette", "feature_density", "symmetry_groups", "hollowness")
def _complexity(ws: Workspace, rec: RunRecord, picked: int | None) -> tuple[float | None, str, dict[str, float]]:
- """``(index, band, axes)`` of the picked round's artifact (``select.round_complexity_block``).
- A run built before the complexity vector existed has none (``eval/bench/complexity_report.py``
- recomputes those from the GLB)."""
try:
block = select.round_complexity_block(ws, next((r for r in rec.rounds if r.index == picked), None))
- except Exception: # noqa: BLE001 - a card is never worth an exception
+ except Exception: # noqa: BLE001
block = None
if block is None or block.get("index") is None:
return None, "", {}
@@ -197,12 +165,6 @@ def _complexity(ws: Workspace, rec: RunRecord, picked: int | None) -> tuple[floa
def entry_from_record(battery: str, ws: Workspace, rec: RunRecord, *, slug: str | None = None) -> RunEntry:
- """A complete card from a parsed record (never raises: every field degrades).
-
- ``slug`` is the RunId slug the scan minted; without one the directory basename is
- used (correct for flat layouts only — nested battery runs are all named ``run``).
- The card is the round every reader shows (``select.summarise().round``: the pick, else
- ``select.fallback_round``): its score, sheet, hero and tier."""
summary = select.summarise(ws.root, record=rec)
picked = summary.round
rnd = next((r for r in rec.rounds if r.index == picked), None)
@@ -235,17 +197,11 @@ def entry_from_record(battery: str, ws: Workspace, rec: RunRecord, *, slug: str
def _spec_fields(run_dir: Path) -> dict[str, str]:
- """Prompt / track / language straight from spec.json — a run with no record yet
- still deserves a readable card (and spec.json can be half-written too)."""
spec = read_json_or_none(run_dir / "spec.json") or {}
return {k: str(spec.get(k) or "") for k in ("prompt", "track", "language")}
def entry_for_dir(battery: str, run_dir: Path, *, slug: str | None = None) -> RunEntry:
- """One run directory → an entry, whatever state it is in.
-
- ``slug`` is the RunId slug the scan minted (default: the directory basename,
- which is only unique in flat layouts)."""
ws = Workspace(run_dir)
slug = slug or run_dir.name
fields = _spec_fields(run_dir)
@@ -260,17 +216,12 @@ def entry_for_dir(battery: str, run_dir: Path, *, slug: str | None = None) -> Ru
error=str(e)[:400], links=entry_links(ws, None, None), **fields)
try:
return entry_from_record(battery, ws, rec, slug=slug)
- except Exception as e: # noqa: BLE001 - one weird record must not break the page
+ except Exception as e: # noqa: BLE001
return RunEntry(battery=battery, slug=slug, path=str(run_dir), state="broken",
error=f"{type(e).__name__}: {e}"[:400], links=entry_links(ws, None, None), **fields)
def _pending_direct_children(root: Path, found: set[Path]) -> list[Path]:
- """Direct children with a spec.json but no record.json yet — a bench mid-write
- still deserves a readable (pending) card. Only DIRECT children qualify: a run is
- otherwise gated on record.json exactly like ``record.record.is_run_dir``, because
- accepting spec-only directories during descent counted every nested ``eval/``
- judge workspace of a battery cell as a phantom run."""
if not root.is_dir():
return []
return [d for d in sorted(root.iterdir())
@@ -279,15 +230,6 @@ def _pending_direct_children(root: Path, found: set[Path]) -> list[Path]:
def scan_root(root: Path, label: str | None = None) -> RootSection:
- """Runs under ``root``. Uses ``find_run_dirs`` rather than a one-level
- ``iterdir()``: a compare_backends or ab_plan battery directory holds its runs four
- and five levels down, so pointing the gallery at one built a page "of 0 runs" and
- exited 0 — the silent-empty failure, on a directory full of real runs.
-
- Every entry is named by its :class:`~codeverse3d.contracts.run.RunId` slug, so two
- nested runs whose directories are both called ``run`` stay two entries. A slug
- that still repeats within the root gets ``#2``/``#3`` — the same precedent as
- duplicate section labels in :func:`build_index`."""
root = Path(root)
label = label or battery_label(root)
found = find_run_dirs(root, predicate=is_run_dir)
@@ -304,7 +246,6 @@ def scan_root(root: Path, label: str | None = None) -> RootSection:
def build_index(roots: list[Path] | list[str]) -> GalleryIndex:
- """Scan every root; duplicate labels get ``label#2`` so URLs stay unique."""
t0 = time.perf_counter()
sections: list[RootSection] = []
used: dict[str, int] = {}
diff --git a/harness/codeverse3d/addons/gallery/model.py b/harness/codeverse3d/addons/gallery/model.py
index 175fc172..2af78dce 100644
--- a/harness/codeverse3d/addons/gallery/model.py
+++ b/harness/codeverse3d/addons/gallery/model.py
@@ -1,15 +1,4 @@
-"""Human-readable labels for the gallery.
-
-Two small vocabularies live here so the page renderers never invent wording:
-
-* :func:`humanize_view` — the render pipeline's machine view names
- (``front_right_34``, ``t=2.5s``, ``pose_door_hinge@upper``) become the words a
- person would say ("Front Right ¾", "t = 2.5 s", "Pose · door_hinge@upper");
-* :data:`VERDICTS` — the three **disjoint** triage buckets every run falls into
- exactly once, so a status breakdown always sums to the number of runs shown. None of
- them is a pass or a fail: a run has none since 2026-09-22 — its card shows the score of
- the round ``addons/select`` picks.
-"""
+"""Human-readable labels for the gallery."""
from __future__ import annotations
@@ -21,20 +10,16 @@ from pydantic import BaseModel, Field
from codeverse3d.addons import select
-#: the three buckets, in the order they are always displayed
VERDICTS = ("judged", "unjudged", "error")
-#: bucket → (short label, css class, what it means)
VERDICT_META: dict[str, tuple[str, str, str]] = {
"judged": ("judged", "v-judged", "a round was judged: the card shows the picked round's score"),
"unjudged": ("unjudged", "v-none", "the run finished but no round has a verdict"),
"error": ("error", "v-err", "no record.json, or a corrupt / half-written one"),
}
-#: view-name tokens that are not words
_TOKENS = {"34": "¾", "3q": "¾", "hdri": "HDRI", "uv": "UV", "ao": "AO", "id": "ID"}
-#: whole names the render pipeline emits that deserve a written-out label
_WHOLE = {
"articulation_sheet": "Articulation poses",
"articulation": "Articulation poses",
@@ -57,15 +42,6 @@ def _word(token: str) -> str:
def humanize_view(name: str) -> str:
- """A render view's machine name as a person would read it.
-
- >>> humanize_view("view_front_right_34.png")
- 'Front Right ¾'
- >>> humanize_view("t=2.5s")
- 't = 2.5 s'
- >>> humanize_view("pose_door_hinge@upper")
- 'Pose · door_hinge@upper'
- """
raw = (name or "").strip()
if not raw:
return ""
@@ -89,17 +65,13 @@ def humanize_view(name: str) -> str:
# ===================================================================== model
-#: how an entry's link should be opened: raw bytes, a directory listing, the code
-#: viewer, the GLB viewer, or another gallery page
LinkKind = Literal["file", "dir", "code", "viewer"]
RunState = Literal["ok", "pending", "broken"]
-#: filter names the index page understands
FILTER_KEYS = ("q", "track", "lang", "tier", "backend", "verdict", "battery")
class RunLink(BaseModel):
- """One artifact of a run, addressed relative to the run directory."""
label: str
rel: str = Field(default="", description="run-relative posix path ('' = the run dir itself)")
@@ -107,20 +79,12 @@ class RunLink(BaseModel):
class RoundRow(select.RoundRow):
- """``select.RoundRow`` plus what the detail page's rounds table draws: the gate
- breakdown and the round's contact sheet."""
gates: dict[str, int] = Field(default_factory=dict, description="gate name → error count")
sheet: str = Field(default="", description="run-relative contact sheet of this round")
class RunEntry(BaseModel):
- """A run as the gallery shows it. ``state`` is the honest one:
-
- * ``ok`` — ``record.json`` parsed
- * ``pending`` — a run directory with a spec but no record yet (a bench still writing)
- * ``broken`` — a record that is missing/corrupt/half-written; the card says why
- """
battery: str = Field(description="section label — the run root's name")
slug: str
@@ -165,23 +129,16 @@ class RunEntry(BaseModel):
@property
def key(self) -> str:
- """Stable id used in URLs and as the DOM key: ``<battery>/<slug>``."""
return f"{self.battery}/{self.slug}"
@property
def verdict(self) -> str:
- """The triage bucket — exactly one of :data:`~codeverse3d.addons.gallery.model.VERDICTS`.
-
- The three are disjoint *and* exhaustive on purpose: a status breakdown built
- from them always sums to the number of runs on screen. A run whose record
- is missing or corrupt is an ``error``, never a silent "unjudged"."""
if self.state != "ok":
return "error"
return "unjudged" if self.score is None else "judged"
@property
def card_image(self) -> str:
- """What the card shows: the single hero view, else the contact sheet."""
return self.hero or self.sheet
def search_text(self) -> str:
@@ -189,7 +146,6 @@ class RunEntry(BaseModel):
self.language, self.generator)).lower()
def card_data(self) -> dict[str, object]:
- """The compact record the page's JS filters / sorts / summarises on."""
return {
"key": self.key, "battery": self.battery, "slug": self.slug, "name": self.title or self.slug,
"track": self.track, "lang": self.language, "backend": self.generator, "tier": self.tier,
@@ -200,7 +156,6 @@ class RunEntry(BaseModel):
class RootSection(BaseModel):
- """All runs found under one root (``runs/`` or one bench battery)."""
label: str
path: str
@@ -208,11 +163,6 @@ class RootSection(BaseModel):
class Summary(BaseModel):
- """The numbers in the summary strip — computed over whatever is *currently* selected.
-
- ``breakdown`` is the load-bearing one: disjoint buckets that **sum to ``n``**, so the
- strip can state "89 runs = 80 judged · 4 unjudged · 5 error". There is no pass rate:
- a run is not passed or failed (2026-09-22) — the scores say how the runs went."""
n: int = 0
n_judged: int = 0
@@ -226,7 +176,6 @@ class Summary(BaseModel):
def verdict_breakdown(entries: list[RunEntry]) -> dict[str, int]:
- """``{bucket: count}`` over every bucket (zeros included), summing to ``len(entries)``."""
counts = dict.fromkeys(VERDICTS, 0)
for e in entries:
counts[e.verdict] += 1
@@ -234,7 +183,6 @@ def verdict_breakdown(entries: list[RunEntry]) -> dict[str, int]:
def summarize(entries: list[RunEntry]) -> Summary:
- """Summary strip for ``entries`` (the same arithmetic the page's JS does)."""
scored = [e.score for e in entries if e.score is not None]
total = sum(e.cost_usd for e in entries)
return Summary(
@@ -249,8 +197,6 @@ def summarize(entries: list[RunEntry]) -> Summary:
class GalleryIndex(BaseModel):
- """Everything the index page needs, plus the (battery, slug) → entry lookup
- the server routes on (a request can only ever reach a run that is in here)."""
sections: list[RootSection] = Field(default_factory=list)
built_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
@@ -267,7 +213,6 @@ class GalleryIndex(BaseModel):
return None
def facets(self) -> dict[str, list[str]]:
- """Sorted distinct values for every drop-down filter."""
es = self.entries()
return {
"track": sorted({e.track for e in es if e.track}),
@@ -279,7 +224,6 @@ class GalleryIndex(BaseModel):
def match(entry: RunEntry, flt: dict[str, str]) -> bool:
- """Does ``entry`` survive the filter dict (the same rule as the page's JS)?"""
q = (flt.get("q") or "").strip().lower()
if q and q not in entry.search_text():
return False
@@ -293,7 +237,6 @@ def match(entry: RunEntry, flt: dict[str, str]) -> bool:
def sort_entries(entries: list[RunEntry], key: str) -> list[RunEntry]:
- """Sort a copy of ``entries``: score/cost/time/complexity descending, name ascending."""
if key == "cost":
return sorted(entries, key=lambda e: (-e.cost_usd, e.slug))
if key == "time":
diff --git a/harness/codeverse3d/addons/gallery/page.py b/harness/codeverse3d/addons/gallery/page.py
index f29665c3..a047f9cf 100644
--- a/harness/codeverse3d/addons/gallery/page.py
+++ b/harness/codeverse3d/addons/gallery/page.py
@@ -1,16 +1,4 @@
-"""The index page: status rail, filters, per-battery sections, cards + table.
-
-Rendered identically for the local server and the static build — the only
-difference is the :class:`~codeverse3d.addons.gallery.urls.UrlMaker` it is handed. The
-initial filter is applied **server-side** (so ``curl '/?track=graphics'`` and a
-no-JS browser both see the right runs and the right summary) and then re-applied
-client-side on every keystroke without a reload.
-
-The summary is a *breakdown*, not a scoreboard: disjoint buckets that add up to the
-number of runs on screen (``89 shown = 80 judged + 4 unjudged + 5 error``), next to the
-mean / median picked-round score. There is no pass rate: a run is not passed or failed
-(2026-09-22).
-"""
+"""The index page: status rail, filters, per-battery sections, cards + table."""
from __future__ import annotations
@@ -45,10 +33,6 @@ def _verdict_chip(bucket: str, count: int, *, total: int) -> str:
def _summary_strip(entries: list[RunEntry], total: int) -> str:
- """One compact rail: how many runs, what happened to them, what they cost.
-
- Deliberately ~1/3 the height of the old 7-tile grid — on a 900 px laptop the
- first row of runs has to be visible without scrolling."""
s = summarize(entries)
segs = "".join(
f"<span class='seg {VERDICT_META[b][1]}' id='vs-{b}' style='flex:{s.breakdown[b]}'"
@@ -105,11 +89,6 @@ def _controls(index: GalleryIndex, flt: dict[str, str], sort: str) -> str:
# --------------------------------------------------------------------------- bulk bar
def _bulk_bar() -> str:
- """Multi-select actions. It is on screen from the start (greyed out) because a
- bulk action nobody can see is a bulk action nobody uses.
-
- Compare / export / copy paths only: this server has no mutation route at all,
- so a "re-run" button would be a lie."""
return (
"<div class='selbar empty' id='selbar' role='region' aria-label='bulk actions'>"
"<span class='selcount'><b class='num' id='sel-n'>0</b> selected"
@@ -144,8 +123,6 @@ def _section(label: str, path: str, entries: list[RunEntry], hidden: set[str], u
def render_index(index: GalleryIndex, urls: UrlMaker, *, title: str = "3dcode gallery",
flt: dict[str, str] | None = None, sort: str = "score", view: str = "cards",
note: str = "", extra_html: str = "") -> str:
- """The whole index page as one HTML document. ``extra_html`` (already
- escaped markup, e.g. eval/bench/report.py's stats tables) goes under the summary strip."""
flt = {k: (flt or {}).get(k, "") for k in FILTER_KEYS}
all_entries = index.entries()
selected = [e for e in all_entries if match(e, flt)]
@@ -181,7 +158,6 @@ def render_index(index: GalleryIndex, urls: UrlMaker, *, title: str = "3dcode ga
def render_static(index: GalleryIndex, *, title: str = "3dcode gallery", embed: bool = False,
thumb_px: int = THUMB_PX, sort: str = "score", view: str = "cards",
extra_html: str = "") -> str:
- """The complete HTML document for ``index`` (no server involved)."""
note = ("images are inlined; the links open the original run directories on this machine"
if embed else "images and links point at the run directories with file:// — "
"use `3dcode gallery serve` for a page that works anywhere")
@@ -191,7 +167,6 @@ def render_static(index: GalleryIndex, *, title: str = "3dcode gallery", embed:
def build_static(roots: list[Path] | list[str], out_html: Path | str, *, title: str | None = None,
embed: bool = False, thumb_px: int = THUMB_PX) -> tuple[Path, int, GalleryIndex]:
- """Scan ``roots`` and write one self-contained page; ``(path, n_runs, index)``."""
index = build_index(roots)
label = title or ("3dcode gallery — " + ", ".join(s.label for s in index.sections[:4])
+ ("…" if len(index.sections) > 4 else ""))
diff --git a/harness/codeverse3d/addons/gallery/server.py b/harness/codeverse3d/addons/gallery/server.py
index f9fb41ac..dcf1be9e 100644
--- a/harness/codeverse3d/addons/gallery/server.py
+++ b/harness/codeverse3d/addons/gallery/server.py
@@ -1,19 +1,4 @@
-"""The local gallery server: ``3dcode gallery serve``.
-
-Stdlib only (``http.server`` + a thread pool), loopback by default, read-only by
-construction — there is no route that writes anything. Routing is split in two
-so it can be tested without a socket: :meth:`GalleryApp.route` maps a decoded
-path + query to a :class:`Response`, and the request handler only moves bytes.
-
-Safety model (see also ``gallery/urls.py``):
-
-* a URL names a run by ``(battery, slug)`` and those must exist **in the index**,
- which only ever contains directories found under the roots the user declared;
-* the remainder of the path is resolved with ``safe_join`` inside that run
- directory — ``..``, absolute paths and escaping symlinks are refused with 403;
-* the only other readable tree is the vendored three.js, behind its own whitelist;
-* binding a non-loopback address requires the user to have typed ``--host``.
-"""
+"""The local gallery server: ``3dcode gallery serve``."""
from __future__ import annotations
@@ -39,10 +24,7 @@ from codeverse3d.addons.gallery.urls import PathError, UrlMaker, content_type, s
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 8765
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
-#: ``<img src=….svg>`` embed keeps rendering — image loads create no document, so
-#: the sandbox directive never applies to them.
+#: /file/ types a browser would execute: served with CSP sandbox so LLM-authored HTML/SVG never runs same-origin.
SANDBOXED_TYPES = frozenset({"text/html", "image/svg+xml"})
@@ -52,7 +34,6 @@ class GalleryError(RuntimeError):
@dataclass
class Response:
- """What a route produced: either a body or a file to stream."""
status: int = 200
content_type: str = "text/html; charset=utf-8"
@@ -78,7 +59,6 @@ def _error_page(status: int, title: str, detail: str) -> Response:
class GalleryApp:
- """Index + routing. One instance per server; safe to share across threads."""
def __init__(self, roots: list[Path] | list[str], *, reload: bool = False,
title: str = "3dcode gallery", runtime_js: Path | str | None = None) -> None:
@@ -91,7 +71,6 @@ class GalleryApp:
self.index = build_index(self.roots)
def refresh(self) -> None:
- """Re-scan the roots (``--reload``); cheap — records only, no images."""
if not self.reload:
return
with self._lock:
@@ -101,8 +80,8 @@ class GalleryApp:
def _entry(self, battery: str, slug: str, *, rescan: bool = True) -> RunEntry | None:
index = self.index
entry = index.find(battery, slug)
- if entry is None and rescan: # a run created since the last scan
- with self._lock: # one scan at a time, and a waiter never replaces a newer index
+ if entry is None and rescan:
+ with self._lock:
if self.index is index:
self.index = build_index(self.roots)
entry = self.index.find(battery, slug)
@@ -116,8 +95,6 @@ class GalleryApp:
return sort_entries([e for e in self.index.entries() if match(e, flt)], query.get("sort", "score"))
def picked(self, keys: list[str]) -> tuple[list[RunEntry], list[str]]:
- """``(entries, unknown_keys)`` for ``battery/slug`` keys, in the order given — with at
- most ONE re-scan, however many keys are unknown (it was one full scan per key)."""
found, missing, scanned = [], [], False
for key in keys:
battery, _, slug = key.partition("/")
@@ -130,7 +107,6 @@ class GalleryApp:
return found, missing
def _picked(self, query: dict[str, str]) -> tuple[list[RunEntry], UrlMaker, str]:
- """What ``?runs=`` names, capped BEFORE any lookup, with a note about anything dropped."""
self.refresh()
keys = parse_keys(query.get("runs", ""))
notes = []
@@ -144,7 +120,6 @@ class GalleryApp:
# ----------------------------------------------------------------- routing
def route(self, path: str, query: dict[str, str] | None = None) -> Response:
- """Decoded ``path`` (``/run/x/y``) + query → a response. Never raises."""
query = query or {}
parts = [unquote(p) for p in path.split("/") if p != ""]
try:
@@ -153,7 +128,7 @@ class GalleryApp:
return _error_page(403, "forbidden", str(e))
except FileNotFoundError as e:
return _error_page(404, "not found", str(e))
- except Exception as e: # noqa: BLE001 - a broken run must not kill the server
+ except Exception as e: # noqa: BLE001
return _error_page(500, "gallery error", f"{type(e).__name__}: {e}")
def _route(self, parts: list[str], query: dict[str, str]) -> Response:
@@ -195,7 +170,7 @@ class GalleryApp:
if not viewer_page.viewer_available(self.runtime_js):
return _error_page(501, "no viewer",
"runtime_js/node_modules/three is not installed; open the raw GLB instead")
- safe_join(entry.path, rel) # validate before the page links to it
+ safe_join(entry.path, rel)
return Response.html(viewer_page.render_viewer(entry, self.urls, rel))
target = safe_join(entry.path, rel)
if target.is_dir():
@@ -220,13 +195,11 @@ class GalleryApp:
broken = entry.model_copy(update={"state": state, "error": str(e)[:400]})
return Response.html(render_broken_detail(broken, self.urls))
- fresh = entry_from_record(entry.battery, ws, rec, slug=entry.slug) # newest rounds, even mid-bench
+ fresh = entry_from_record(entry.battery, ws, rec, slug=entry.slug)
prev, nxt = self.neighbours(entry)
return Response.html(render_detail(fresh, self.urls, ws, rec, prev=prev, nxt=nxt))
def neighbours(self, entry: RunEntry) -> tuple[RunEntry | None, RunEntry | None]:
- """The runs either side of ``entry`` in its battery, in the index's own order,
- so triage can walk a battery run by run instead of bouncing off the index."""
section = next((s for s in self.index.sections if s.label == entry.battery), None)
if section is None:
return None, None
@@ -240,7 +213,6 @@ class GalleryApp:
def _js_type(path: Path) -> str:
- """Vendor modules must be served as JavaScript for ``<script type=module>``."""
return "text/javascript; charset=utf-8" if path.suffix in (".js", ".mjs") else content_type(path)
@@ -251,7 +223,7 @@ class _Handler(BaseHTTPRequestHandler):
app: GalleryApp
quiet: bool = True
- def do_GET(self) -> None: # noqa: N802 - stdlib naming
+ def do_GET(self) -> None: # noqa: N802
self._respond(body=True)
def do_HEAD(self) -> None: # noqa: N802
@@ -293,13 +265,11 @@ class _Handler(BaseHTTPRequestHandler):
handle.close()
def _stream(self, handle: Any, length: int) -> None:
- """Write exactly ``length`` bytes so the response stays framed even if the
- file is truncated underneath us mid-read."""
remaining = length
while remaining > 0:
chunk = handle.read(min(STREAM_CHUNK, remaining))
if not chunk:
- self.wfile.write(b"\0" * remaining) # file shrank: keep the framing valid
+ self.wfile.write(b"\0" * remaining)
return
self.wfile.write(chunk)
remaining -= len(chunk)
@@ -311,7 +281,6 @@ class _Handler(BaseHTTPRequestHandler):
def make_server(app: GalleryApp, host: str = DEFAULT_HOST, port: int = DEFAULT_PORT,
*, quiet: bool = True) -> ThreadingHTTPServer:
- """A bound, not-yet-serving :class:`ThreadingHTTPServer` (``port=0`` = ephemeral)."""
handler = type("_BoundHandler", (_Handler,), {"app": app, "quiet": quiet})
try:
return ThreadingHTTPServer((host, port), handler) # type: ignore[arg-type]
@@ -322,7 +291,6 @@ def make_server(app: GalleryApp, host: str = DEFAULT_HOST, port: int = DEFAULT_P
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 = host or DEFAULT_HOST
app = GalleryApp(roots, reload=reload, title=title)
httpd = make_server(app, bind, port)
@@ -343,5 +311,5 @@ def serve(roots: list[Path] | list[str], *, host: str | None = None,
def _open(url: str) -> None:
import webbrowser
- with contextlib.suppress(Exception): # headless box, no browser
+ with contextlib.suppress(Exception):
webbrowser.open(url)
diff --git a/harness/codeverse3d/addons/gallery/urls.py b/harness/codeverse3d/addons/gallery/urls.py
index 8a8cff61..2bf87bc3 100644
--- a/harness/codeverse3d/addons/gallery/urls.py
+++ b/harness/codeverse3d/addons/gallery/urls.py
@@ -1,10 +1,4 @@
-"""How a run-relative path becomes an href.
-
-The page renderers never build URLs themselves — they ask a :class:`UrlMaker`.
-That is the whole difference between the served gallery (real routes, images
-fetched lazily over HTTP) and the static single-file build (``file://`` links,
-images optionally inlined as ``data:`` URIs), so the HTML is written once.
-"""
+"""How a run-relative path becomes an href."""
from __future__ import annotations
@@ -21,9 +15,7 @@ JPEG_QUALITY = 78
class UrlMaker:
- """Server-side URLs (the default): every route is handled by ``gallery.server``."""
- #: does this target have per-run detail pages?
has_detail = True
def detail(self, entry: RunEntry) -> str:
@@ -42,7 +34,6 @@ class UrlMaker:
return f"/viewer/{quote(entry.battery)}/{quote(entry.slug)}/{quote(rel)}"
def img(self, entry: RunEntry, rel: str) -> str:
- """``src`` for an ``<img>``: a URL here, a ``data:`` URI in embed mode."""
return self.file(entry, rel)
def link(self, entry: RunEntry, link: RunLink) -> str:
@@ -50,11 +41,6 @@ class UrlMaker:
class StaticUrls(UrlMaker):
- """``file://`` targets for the shareable single-file build.
-
- ``embed=True`` inlines every contact sheet as a downscaled JPEG ``data:`` URI
- so the page survives being copied off this machine; the links still point at
- the original run directories (they work on the box that produced them)."""
has_detail = False
@@ -97,12 +83,11 @@ def thumbnail_data_uri(path: Path | str, *, max_px: int = THUMB_PX) -> str:
im.thumbnail((max_px, max_px))
buf = io.BytesIO()
im.save(buf, format="JPEG", quality=JPEG_QUALITY, optimize=True)
- except Exception: # noqa: BLE001 - missing PIL, unreadable/half-written file
+ except Exception: # noqa: BLE001
return ""
return "data:image/jpeg;base64," + base64.b64encode(buf.getvalue()).decode()
-#: extensions the harness writes that the stdlib does not type correctly (or at all)
CONTENT_TYPES: dict[str, str] = {
".glb": "model/gltf-binary",
".gltf": "model/gltf+json",
@@ -141,9 +126,6 @@ CONTENT_TYPES: dict[str, str] = {
def content_type(path: Path | str) -> str:
- """Content type for a run artifact. Unknown text-ish files fall back to
- ``text/plain`` (a browser must never be asked to *download* source code),
- everything else to ``application/octet-stream``."""
suffix = Path(path).suffix.lower()
if suffix in CONTENT_TYPES:
return CONTENT_TYPES[suffix]
@@ -161,9 +143,6 @@ class PathError(ValueError):
def safe_join(root: Path | str, rel: str) -> Path:
- """``root / rel`` when ``rel`` stays inside ``root``; :class:`PathError` otherwise.
-
- ``rel`` is a URL path fragment that has already been percent-decoded."""
base = Path(root).resolve()
rel = (rel or "").strip()
if "\x00" in rel:
@@ -176,7 +155,7 @@ def safe_join(root: Path | str, rel: str) -> Path:
target = base.joinpath(*parts)
try:
resolved = target.resolve()
- except OSError as e: # broken symlink loop, too many levels, …
+ except OSError as e:
raise PathError(f"unresolvable path: {rel!r} ({e})") from e
if resolved != base and base not in resolved.parents:
raise PathError(f"path escapes the run directory: {rel!r}")
diff --git a/harness/codeverse3d/addons/select.py b/harness/codeverse3d/addons/select.py
index eba1fe22..f6702183 100644
--- a/harness/codeverse3d/addons/select.py
+++ b/harness/codeverse3d/addons/select.py
@@ -1,31 +1,4 @@
-"""Which round of a finished run to hand over — and the hand-over itself (``3dcode pick``).
-
-Since 2026-09-22 the run loop keeps every round, ends at the last one and calls no run
-passed or failed: the judge scores each round and its verdict shapes the next one, and
-choosing among the rounds is a READER's job. This addon is that reader, and the one every
-other reader asks (gallery, dataset, cost report, calibration, the CLI, eval/bench):
-
-* :func:`round_rows` one typed row per saved round — the effective judged score, the
- judge's own verdict for that round, gate errors, commit, cost, minutes;
-* :func:`pick` the round to hand over: the highest judged score, ties to fewer gate
- errors, then the earlier round. ``by="pairwise"`` lets the position-
- swapped pairwise judge decide between the top two when they sit within
- the judge's noise (the verdict is paid once and cached in
- ``artifacts/judge/``);
-* :func:`summarise` baseline score, the picked round and its score, the delta, rounds run
- and the stop reason — the round ``selection.json`` names when the run
- was packaged, else :func:`pick`'s — and ``round``, the one a reader
- SHOWS: the picked round, else :func:`fallback_round`;
-* :func:`fallback_round` the round every reader shows when nothing was judged: the latest
- round that built and has renders;
-* :func:`round_file` a round's OWN build output (its GLB, GIF), never the last build's —
- and :func:`round_complexity_block` its complexity vector;
-* :func:`package` ``deliverable/`` for one round and ``selection.json`` (round, method,
- scores) beside ``record.json``.
-
-Nothing here runs during a run: ``3dcode make`` calls :func:`pick` + :func:`package` after the
-track returns (unless ``--no-pick``).
-"""
+"""Which round of a finished run to hand over — and the hand-over itself (``3dcode pick``)."""
from __future__ import annotations
@@ -58,18 +31,14 @@ from codeverse3d.workspace import Workspace
log = logging.getLogger(__name__)
SELECTION_NAME = "selection.json"
-#: |Δscore| at or below this is judge noise: ``by="pairwise"`` asks the pairwise judge
PAIRWISE_MARGIN = 0.03
-#: the runner-up replaces the top-scored round only when the pairwise judge is this sure
PAIRWISE_MIN_CONFIDENCE = 0.6
PickBy = Literal["score", "pairwise"]
-#: how ``selection.json``'s round was chosen: by score, by the pairwise judge, or named (``--round``)
Method = Literal["score", "pairwise", "round"]
class RoundRow(BaseModel):
- """One saved round, as a reader needs it."""
index: int
kind: str = ""
@@ -84,7 +53,6 @@ class RoundRow(BaseModel):
class RunSummary(BaseModel):
- """A run in one line — no pass/fail: the scores say how it went."""
rounds: int = Field(default=0, description="rounds run (the baseline included)")
stop_reason: str = ""
@@ -98,7 +66,6 @@ class RunSummary(BaseModel):
class Selection(BaseModel):
- """``selection.json``: which round ``deliverable/`` holds, and why."""
round: int
method: Method
@@ -107,8 +74,6 @@ class Selection(BaseModel):
class PairwiseNote(BaseModel):
- """One paid pairwise verdict — does round ``b`` beat round ``a``? — as cached in
- ``artifacts/judge/rAA_vs_rBB_pairwise.json`` so a second ``3dcode pick`` re-reads it."""
a: str = Field(description="label of the top-scored round")
b: str = Field(description="label of the runner-up")
@@ -126,7 +91,6 @@ def _load(run_dir: Path | str, record: RunRecord | None) -> RunRecord:
def round_rows(run_dir: Path | str, *, record: RunRecord | None = None) -> list[RoundRow]:
- """One row per round of the run's ``record.json`` (``record=`` skips re-reading it)."""
rows = []
for r in _load(run_dir, record).rounds:
j = effective_judgment(r)
@@ -138,23 +102,17 @@ def round_rows(run_dir: Path | str, *, record: RunRecord | None = None) -> list[
def _ranked(rows: list[RoundRow]) -> list[RoundRow]:
- """Judged rounds, best first: highest score, then fewer gate errors, then the earlier round."""
return sorted((r for r in rows if r.score is not None), key=lambda r: (-(r.score or 0.0), r.gate_errors, r.index))
# --------------------------------------------------------------------------- a round's own outputs
def round_file(ws: Workspace, rnd: RoundRecord | None, name: str = "object.glb") -> Path | None:
- """Round ``rnd``'s own build output ``name`` (``record.deliverable.round_outputs``), else
- None — never the canonical ``artifacts/<name>`` on its own: that is the LAST build's."""
out = round_outputs(ws, rnd)
p = out / name if out is not None else None
return p if p is not None and p.is_file() else None
def round_complexity_block(ws: Workspace, rnd: RoundRecord | None) -> dict | None:
- """Round ``rnd``'s complexity vector: its own measurement's block, else — a run recorded
- before rounds carried one — ``artifacts/measurement.json``'s when that canonical build is
- this round's. Never another round's (``record.extra["complexity"]`` is the LAST one's)."""
block = round_complexity(rnd) if rnd is not None else None
if block is None and rnd is not None and round_outputs(ws, rnd) == ws.artifacts:
block = ((read_json_or_none(ws.artifacts / "measurement.json") or {}).get("extra") or {}).get("complexity")
@@ -164,13 +122,6 @@ def round_complexity_block(ws: Workspace, rnd: RoundRecord | None) -> dict | Non
# --------------------------------------------------------------------------- pick
def pick(run_dir: Path | str, *, by: PickBy = "score", pairwise_model: str | None = None,
record: RunRecord | None = None, judge: Any | None = None) -> int | None:
- """The round to hand over, or None when no round was judged.
-
- ``by="pairwise"``: when the top two scores are within :data:`PAIRWISE_MARGIN`, the
- pairwise judge (``pairwise_model``, default the run's judge; ``judge`` injects one)
- compares their renders and the runner-up wins only with confidence ≥
- :data:`PAIRWISE_MIN_CONFIDENCE`. A verdict already paid for this pair is re-read,
- never re-bought."""
rec = _load(run_dir, record)
ranked = _ranked(round_rows(run_dir, record=rec))
if not ranked:
@@ -184,9 +135,6 @@ def pick(run_dir: Path | str, *, by: PickBy = "score", pairwise_model: str | Non
def pairwise_verdict(ws: Workspace, rec: RunRecord, a: int, b: int, *, model: str, judge: Any | None = None) -> PairwiseNote:
- """Does round ``b`` beat round ``a``? Position-swapped pairwise judge, one paid verdict
- per (pair, model), cached at ``artifacts/judge/rAA_vs_rBB_pairwise.json``. A judge
- outage keeps ``a`` (never a worse pick for a failed call)."""
cache = ws.judge_path(a, f"_vs_r{b:02d}_pairwise")
rounds = {r.index: r for r in rec.rounds}
renders = [judged_subset(resolve_paths(ws, rounds[i].renders)) for i in (a, b)]
@@ -194,7 +142,6 @@ def pairwise_verdict(ws: Workspace, rec: RunRecord, a: int, b: int, *, model: st
if renders[0] is None or renders[1] is None:
note.error = "a round has no renders to compare"
return note
- # the verdict is about THESE pictures: a re-rendered round is a new comparison
seen = hashlib.sha256("\n".join(sha256_file(v.path) if Path(v.path).is_file() else v.path
for rs in renders for v in rs.views).encode()).hexdigest()
stored = read_json_or_none(cache) or {}
@@ -209,7 +156,7 @@ def pairwise_verdict(ws: Workspace, rec: RunRecord, a: int, b: int, *, model: st
with call_context(stage=Stage.PAIRWISE, role=Role.JUDGE, label="pick"):
res = judge.compare(rec.spec, renders[0], renders[1],
rubric=rubric_of(rec))
- except Exception as e: # noqa: BLE001 — an outage must not move the pick
+ except Exception as e: # noqa: BLE001
log.warning("pairwise pick failed: %s", e)
note.error = f"{type(e).__name__}: {e}"
return note
@@ -223,9 +170,6 @@ def pairwise_verdict(ws: Workspace, rec: RunRecord, a: int, b: int, *, model: st
def fallback_round(rounds: Iterable[RoundRecord]) -> int | None:
- """The round a reader shows when nothing was judged (no pick, no ``selection.json``): the
- latest round that built and has renders, else None. The ONE rule for the gallery card,
- the dataset sample and index row, ``3dcode judge``'s default and calibration's stand-in."""
return max((r.index for r in rounds
if r.build is not None and r.build.ok and r.renders is not None and r.renders.views), default=None)
@@ -235,14 +179,11 @@ def load_selection(ws: Workspace) -> Selection | None:
data = read_json_or_none(ws.root / SELECTION_NAME)
try:
return Selection.model_validate(data) if data is not None else None
- except ValueError: # a hand-edited file must not break every reader
+ except ValueError:
return None
def summarise(run_dir: Path | str, *, record: RunRecord | None = None) -> RunSummary:
- """The run in one line. The picked round is the one ``selection.json`` names (what was
- packaged), else what :func:`pick` chooses by score; ``round`` is that, else
- :func:`fallback_round`."""
rec = _load(run_dir, record)
rows = round_rows(run_dir, record=rec)
by_index = {r.index: r for r in rows}
@@ -261,11 +202,6 @@ def summarise(run_dir: Path | str, *, record: RunRecord | None = None) -> RunSum
# --------------------------------------------------------------------------- package
def package(run_dir: Path | str, round_index: int, *, method: Method = "round") -> Path:
- """Write ``deliverable/`` for round ``round_index`` (from its commit and ``artifacts/rNN/``,
- no rebuild) and ``selection.json``; returns the deliverable directory.
-
- The record is re-packaged (``record.repackage``), so its total takes in what the hand-over
- paid — a pairwise verdict; the run's money is its ledger's."""
ws = Workspace(run_dir)
rec = load_record(ws)
if not any(r.index == round_index for r in rec.rounds):
diff --git a/harness/codeverse3d/addons/skill_targets.py b/harness/codeverse3d/addons/skill_targets.py
index 6c03f078..d73a0c27 100644
--- a/harness/codeverse3d/addons/skill_targets.py
+++ b/harness/codeverse3d/addons/skill_targets.py
@@ -1,28 +1,4 @@
-"""What each bundle CLAIMS to move — one deterministic quantity per skill.
-
-WHY this file exists. A library you cannot measure per-skill is one you can only
-maintain by taste. ``metadata.evidence`` says where a bundle's *prose* came from;
-nothing said what the bundle is supposed to *do* to a run, in a number a machine can
-recompute. This is that: one row per bundle, naming the quantity, the direction, and
-the gate kinds (``skills.registry``) or artefact it is read out of.
-
-Three rules the rows obey:
-
-* **Deterministic only.** Every row is read from a gate report, a build result or a
- measured artefact — never from the judge. An 8-prompt A/A of the judged score gave
- paired sd 0.202 and needs ~408 paired prompts to resolve +0.02 (``eval/docs/EVAL.md`` §8);
- a skills A/B read out on ``score`` at n=8 is a coin toss. These do not carry that
- variance.
-* **One owner per quantity.** ``contract/instance_bbox`` belongs to
- ``c3d-repeats-and-mirrors``, so ``c3d-bbox-contract``'s row excludes it. Two
- bundles sharing a metric means an A/B cannot say which one moved it.
-* **``measurable=False`` is a finding, not a gap.** A bundle whose claim no
- deterministic instrument can see says so here rather than borrowing a judged
- criterion and calling it evidence.
-
-``eval/bench/skill_targets.py`` is the readout; ``tests/skills/test_targets.py`` pins the
-rows against the live gate vocabulary and against each bundle's own frontmatter.
-"""
+"""What each bundle CLAIMS to move — one deterministic quantity per skill."""
from __future__ import annotations
@@ -35,22 +11,19 @@ from typing import Any
from codeverse3d.skills.model import Skill
-#: the direction that counts as an improvement
DOWN = "down"
UP = "up"
-#: where the readout gets the number
-SRC_GATE = "gate_kinds" #: count findings of `kinds` in the last gated round
-SRC_BUILD = "build" #: the round's BuildResult
-SRC_GLB = "glb" #: recomputed from the measured round's own object.glb (artifacts/rNN/)
-SRC_FRAMES = "frames" #: recomputed from the round's sampled frames
-SRC_ARTIFACT = "artifact" #: a gate report written beside the run, not into the record
+SRC_GATE = "gate_kinds"
+SRC_BUILD = "build"
+SRC_GLB = "glb"
+SRC_FRAMES = "frames"
+SRC_ARTIFACT = "artifact"
SOURCES = (SRC_GATE, SRC_BUILD, SRC_GLB, SRC_FRAMES, SRC_ARTIFACT)
@dataclass(frozen=True)
class Target:
- """One bundle's falsifiable claim."""
skill: str
metric: str
@@ -58,13 +31,9 @@ class Target:
unit: str
source: str
why: str
- #: ``gate/kind`` (or a ``gate/*`` family, see skills.registry) counted when ``source == SRC_GATE``
kinds: tuple[str, ...] = ()
- #: severities that count; empty == every actionable (non-INFO) finding
severities: tuple[str, ...] = ()
- #: languages the metric is defined over; empty == every language
languages: tuple[str, ...] = field(default_factory=tuple)
- #: False when no deterministic instrument can see the bundle's claim
measurable: bool = True
caveat: str = ""
@@ -232,10 +201,7 @@ TARGETS: tuple[Target, ...] = (
why="every gl_frames finding in the whole graphics corpus (3 flicker, 1 low detail) came "
"from opengl_python, and flicker is trap 1 (a sampled solver) showing up in pixels",
),
- # ------------------------------------------------------------- 2026-09-01 recipe port
- # The four bundles ported from the scene_multifile_graphics reference carry that
- # harness's measured findings; OUR baselines attach when the sceneloop A/B lands.
- # Until then the honest target is the same frame-gate family the recipes serve.
+ # ------------------------------------------------------------- recipe port
Target(
skill="c3d-scene-atmosphere",
metric="env_bake_orientation_flags",
@@ -286,7 +252,7 @@ TARGETS: tuple[Target, ...] = (
caveat="NOT yet measurable here: judged quality only. A variance census (per-material "
"value spread over sampled texels) is the candidate instrument.",
),
- # ------------------------------------------------------------- 2026-10-14 scene_blender (D105)
+ # ------------------------------------------------------------- scene_blender
Target(
skill="c3d-bpy-scene-placement",
metric="bpy_placement_errors",
@@ -343,22 +309,13 @@ def target_for(skill: str) -> Target | None:
# ===================================================================== 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`` via
-# ``file``) and the prompt corpus's ``prompts/_claims.toml`` (``file`` relative to prompts/).
-# The constant is ``python = "module:NAME"`` or ``js = "<path>:NAME"`` (an ``export const`` numeric
-# literal; ``runtime_js/...`` under the configured runtime, any other path under the package).
-# The text must stand as its own token (``0.5 m`` is not inside ``10.5 m`` or ``0.5 mm``) and, with
-# ``context``, on a line that also carries that phrase — a short "2 mm" cannot pass by occurring
-# anywhere else in the file.
+# A claim pins a number some text states to the code constant that produces it (``_claims/<name>.toml``,
+# ``prompts/_claims.toml``); the text must stand as its own token and, with ``context``, share a line with that phrase.
CLAIMS_DIR = "_claims"
PROMPT_CLAIMS = "_claims.toml"
def claims_path(skill: Skill | str, root: Path | None = None) -> Path:
- """The claims file for ``skill``: a ``Skill``'s OWN root first (``<its dir>.parent/_claims/<name>.toml``
- — a variant overlay bundle pins its numbers beside itself, D105), then the library root ``root``
- (default ``skills_dir()``). A bare name looks in the library root only."""
from codeverse3d.skills import skills_dir
name = skill.name if isinstance(skill, Skill) else skill
@@ -380,13 +337,10 @@ def _load_rows(p: Path) -> list[dict[str, Any]]:
def load_claims(skill: Skill | str, root: Path | None = None) -> list[dict[str, Any]]:
- """The claim rows for one skill ([] when the bundle pins nothing); a ``Skill`` finds an overlay's
- own ``_claims/`` first (:func:`claims_path`)."""
return _load_rows(claims_path(skill, root))
def resolve(dotted: str) -> Any:
- """``module:NAME`` or ``module.NAME`` → the live object."""
mod, _, attr = dotted.partition(":") if ":" in dotted else dotted.rpartition(".")
if not mod or not attr:
raise ValueError(f"claim python target {dotted!r} must be 'module:NAME'")
@@ -394,7 +348,6 @@ def resolve(dotted: str) -> Any:
def resolve_js(target: str) -> float:
- """``<path>:NAME`` → the number ``[export] const NAME = <literal>`` states in that JS file."""
rel, _, name = target.rpartition(":")
if not rel or not name:
raise ValueError(f"claim js target {target!r} must be '<path>:NAME'")
@@ -413,17 +366,12 @@ def resolve_js(target: str) -> float:
def _target(row: dict[str, Any]) -> tuple[str, Any]:
- """``(target, live value)`` of a row — its ``python`` or ``js`` constant."""
if row.get("js"):
return f"js:{row['js']}", resolve_js(str(row["js"]))
return str(row["python"]), resolve(str(row["python"]))
def render_claim(row: dict[str, Any]) -> str:
- """The string the live constant produces, per this row's scale/format. With ``sep`` the
- constant is a sequence: each item is formatted (default ``{:g}``) and joined by ``sep``, the
- last pair by ``last_sep`` when given — so ``(0, 1, 2.5)`` renders ``0, 1 and 2.5`` whole,
- and a fourth item changes the text."""
value = _target(row)[1]
scale = row.get("scale")
fmt = row.get("format")
@@ -437,14 +385,11 @@ def render_claim(row: dict[str, Any]) -> str:
def stated(text: str, doc: str, context: str = "") -> bool:
- """Does ``doc`` state ``text`` as its own token (on a line that also says ``context``)?"""
pat = re.compile(rf"(?<![\w.]){re.escape(text)}(?!\w|\.\d)")
return any(pat.search(line) and context in line for line in doc.splitlines())
def check_rows(rows: list[dict[str, Any]], read: Any) -> list[str]:
- """Every stale or missing claim among ``rows``; ``read(file)`` returns the text a row's
- ``file`` names (``file`` absent → ``read(None)``)."""
issues: list[str] = []
for i, row in enumerate(rows):
where = f"claim[{i}] {row.get('key', '?')}"
@@ -456,7 +401,7 @@ def check_rows(rows: list[dict[str, Any]], read: Any) -> list[str]:
continue
try:
live = render_claim(row)
- except Exception as e: # noqa: BLE001 — a bad target is a claim problem
+ except Exception as e: # noqa: BLE001
issues.append(f"{where}: cannot resolve {row.get('js') or row.get('python')!r}: {e}")
continue
try:
@@ -473,7 +418,6 @@ def check_rows(rows: list[dict[str, Any]], read: Any) -> list[str]:
def check_claims(skill: Skill, root: Path | None = None) -> list[str]:
- """Every stale or missing claim in one bundle, as human lines (empty == clean)."""
try:
rows = load_claims(skill, root)
except (ValueError, OSError) as e:
@@ -482,7 +426,6 @@ def check_claims(skill: Skill, root: Path | None = None) -> list[str]:
def check_prompt_claims(root: Path | None = None) -> list[str]:
- """The same check over the prompt corpus: ``prompts/_claims.toml``, ``file`` relative to prompts/."""
base = Path(root) if root is not None else Path(__file__).resolve().parents[1] / "prompts"
try:
rows = _load_rows(base / PROMPT_CLAIMS)
diff --git a/harness/codeverse3d/agents/backends.py b/harness/codeverse3d/agents/backends.py
index 72dccde3..99c87278 100644
--- a/harness/codeverse3d/agents/backends.py
+++ b/harness/codeverse3d/agents/backends.py
@@ -1,10 +1,8 @@
"""The three vendor CLI backends: ``claude-code:<model>``, ``codex:<model>``, ``agy:<model>``.
-Each one runs ONE headless session with the prompt on stdin (``cli_common.invoke``), reads its
-CLI's own wire format back into an ``AgentResult`` and leaves retrying to the CLI itself: the
-harness never loops over a session (one round-level transport retry lives in
-``tracks/lifecycle``). Google's models go through ``agy`` — Antigravity in Gemini-API mode,
-one key per session from the shared pool (see the antigravity section).
+Each runs ONE headless session with the prompt on stdin (``cli_common.invoke``), reads its CLI's
+wire format back into an ``AgentResult`` and leaves retrying to the CLI. Google's models go
+through ``agy`` (Antigravity in Gemini-API mode, one key per session from the shared pool).
"""
from __future__ import annotations
@@ -52,14 +50,6 @@ log = logging.getLogger(__name__)
class _CliAgent:
- """What the vendor backends share.
-
- Everything that MATTERS about a CLI backend differs — argv vocabulary, JSON wire
- format, usage/pricing shape, key handling — and stays in the subclass. What they
- share is their id and "is the binary there?", which was four and three verbatim
- copies until 2026-08-28. Subclasses set ``kind`` / ``cli_label`` and assign
- ``model`` / ``binary`` in __init__.
- """
kind: str
cli_label: str
@@ -80,46 +70,26 @@ def _compose_prompt(job: AgentJob) -> str:
# ===================================================================== claude_code
-#: ``--allowedTools``. "Skill" is claude-code 2.1's model-invoked skill tool: without it
-#: the bundles the harness materialises into ``ws/.claude/skills/`` are listed at session
-#: start and then DENIED on activation, which reads in the transcript as the model
-#: ignoring them. It only ever opens files already inside the workspace.
+#: ``--allowedTools``; "Skill" is needed or the routed bundles in ``ws/.claude/skills/`` are denied on activation.
ALLOWED_TOOLS = ("Read", "Edit", "Write", "MultiEdit", "Glob", "Grep", "Skill",
"Bash(node:*)", "Bash(python:*)", "Bash(python3:*)", "Bash(ls:*)", f"mcp__{MCP_SERVER_NAME}__*")
-#: claude-code's skill-activation tool (2.1.280: input ``{"skill": <name>, "args"?}``)
CLAUDE_SKILL_TOOL = "Skill"
-#: A harness session sees the bundles the harness routed into ``<ws>/.claude/skills`` and
-#: nothing else. claude-code 2.1.280 otherwise lists 26 more (2026-09-22 rig): the account-
-#: synced skills and plugins (``anthropic-skills:*``, ``deep-research``, …) come with the
-#: "user" setting source, so ``--setting-sources project`` drops them — and with them the
-#: owner's ~/.claude/settings.json (hooks, env, effortLevel): a session no longer inherits
-#: whoever runs the harness, and its effort is stated instead (``Settings.agents.claude_effort``,
-#: default "xhigh" — what sessions ran at while they inherited the owner's settings). The bundled skills go with ``CLAUDE_CODE_DISABLE_BUNDLED_SKILLS`` (build_env);
-#: ``design`` and ``doctor`` survive that switch by design and are hidden by name through the
-#: documented ``skillOverrides`` setting. Checked against a local fake API and in one live
-#: subscription session (2026-09-22): the init event lists exactly the routed bundles, and
-#: subscription auth does not need the user setting source.
+#: A session sees only the bundles the harness routed into ``<ws>/.claude/skills``. ``--setting-sources
+#: project`` drops the account-synced skills and the user's settings (effort is stated via
+#: ``Settings.agents.claude_effort``); ``CLAUDE_CODE_DISABLE_BUNDLED_SKILLS`` (build_env) drops the
+#: bundled ones, and ``design`` / ``doctor`` survive that switch so ``skillOverrides`` hides them by name.
CLAUDE_SETTING_SOURCES = "project"
CLAUDE_SETTINGS = {"skillOverrides": {"design": "off", "doctor": "off"}}
def parse_claude_json(stdout: str) -> dict[str, Any] | None:
- """The ``type == "result"`` envelope of a ``claude -p`` stream, else ``None``."""
return find_json_object(stdout, lambda d: d.get("type") == "result")
class ClaudeStream:
- """Folded view over ``--output-format stream-json``, fed live: the tool calls the
- session made, the skill index its ``init`` event reported (the list the model was
- shown), each message's usage block (``messages``: the last copy per message id — what a
- session killed before its result event billed), the CLI's own ``api_retry`` events
- (``retries``: ``(t, announced back-off s)``) and when every other event
- arrived (``progress``) — the two ``cli_common.provider_wait`` reads.
-
- Since 2026-09-22 the backend streams instead of printing one envelope: the envelope
- (the last, ``type == "result"`` line) is unchanged, and the lines before it are the
- only record of which skills the session activated (docs/SKILLS.md §4 — "the logs
- contain zero occurrences of any c3d- name" under ``--output-format json``)."""
+ """Folded view over ``--output-format stream-json``, fed live: the tool calls, the skill index the
+ ``init`` event reported, each message's usage block (last copy per message id), the CLI's
+ ``api_retry`` events and the arrival time of every other event (``cli_common.provider_wait``)."""
def __init__(self) -> None:
self.calls: list[ToolCall] = []
@@ -141,7 +111,6 @@ class ClaudeStream:
if not isinstance(ev, dict):
return
if 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))
return
self.progress.append(time.time())
@@ -167,11 +136,7 @@ class ClaudeStream:
self.calls[i] = dataclasses.replace(self.calls[i], failed=True)
def usage(self, model: str) -> Usage:
- """What a session that never printed its result event billed: every message's own
- usage block, summed. The input side is exact (a message knows its prompt when it
- starts); ``output_tokens`` is a FLOOR — stream-json repeats the block each message
- started with, before its output was counted (a finished 2026-09-22 session: 154 of
- 30 106). Priced from the table: the ``total_cost_usd`` event never came."""
+ """Usage of a session that never printed its result event: every message's usage block, summed (``output_tokens`` is a floor)."""
if not self.messages: # died before its first reply: nothing billed, nothing to price
return Usage(backend="claude-code", model=model)
keys = ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "output_tokens")
@@ -183,10 +148,8 @@ class ClaudeStream:
def usage_from_envelope(env: dict[str, Any], model: str) -> Usage:
- """``input_tokens`` is the TOTAL prompt (uncached + cache reads + cache writes), the
- convention pricing.py and anthropic.py share. The envelope's own ``input_tokens`` is the
- uncached part only, and CostBucket clamps ``cached`` to ``input``: every cache-read token
- past it and every cache-write token used to vanish from the ledger."""
+ """``input_tokens`` is the TOTAL prompt (uncached + cache reads + cache writes), the convention
+ pricing.py and anthropic.py share; the envelope's own ``input_tokens`` is the uncached part only."""
u = env.get("usage") or {}
cache_read = int(u.get("cache_read_input_tokens") or 0)
usage = Usage(
@@ -203,17 +166,11 @@ def usage_from_envelope(env: dict[str, Any], model: str) -> Usage:
def primary_served_model(env: dict[str, Any], model: str) -> str:
- """The model that actually did the WORK, of the (up to two) that one session bills.
+ """The model that did the WORK, of the (up to two) that one session bills.
- ``claude -p`` 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 — so taking
- ``served[0]`` recorded a model that did ~1% of the tokens whenever ``--model`` was an
- ALIAS ('sonnet', 'opus', or the default arm). A sonnet-vs-default comparison was
- therefore labelled haiku-vs-haiku, in CallCost.model and in OneShotResult.usage.
-
- The envelope's top-level ``usage`` block reports the MAIN conversation only, so the
- entry whose token counts match it is the work model; otherwise take the dearest.
- An id we passed verbatim is already a served name and is kept as-is.
+ ``claude -p`` also bills a small background model, which can be listed first. The envelope's
+ top-level ``usage`` covers the main conversation only, so the entry whose counts match is the
+ work model; otherwise the dearest. An id passed verbatim is kept.
"""
served: dict[str, Any] = env.get("modelUsage") or {}
if not served or model in served:
@@ -229,16 +186,12 @@ def primary_served_model(env: dict[str, Any], model: str) -> str:
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", ""))
if proc.timed_out:
return classify_end(proc, ok=False, text=text)
if env is None or proc.rc != 0:
- # a 529 / overloaded exit is the provider's, not the task's (AgentResult.transient)
return classify_end(proc, ok=False, text=text, said=(proc.stderr, proc.stdout))
if env.get("is_error") or sub.startswith("error"):
- # the turn cap is the task's budget, never the provider's
return SessionEnd("budget") if "max_turns" in sub else classify_end(proc, ok=False, text=text, said=(text,))
return classify_end(proc, ok=True, text=text)
@@ -252,10 +205,7 @@ class ClaudeCodeAgent(_CliAgent):
self.binary = binary or get_settings().binaries.claude_cli
def build_argv(self, s: Session) -> list[str]:
- """``-p`` with no prompt argument: the prompt comes on stdin, byte for byte."""
job = s.job
- # stream-json (+ the --verbose it requires in -p mode): same final envelope, plus the
- # tool calls the skill read probe reads as ground truth (ClaudeStream)
argv = [self.binary, "-p", "--output-format", "stream-json", "--verbose",
"--dangerously-skip-permissions",
"--max-turns", str(job.max_turns), "--no-session-persistence",
@@ -266,9 +216,7 @@ class ClaudeCodeAgent(_CliAgent):
if effort := get_settings().agents.claude_effort:
argv += ["--effort", effort]
if job.spatial_tools:
- # written fresh into the harness-owned trajectory dir for THIS session, from
- # the typed job — never the workspace's .mcp.json, which the agent can rewrite
- # between rounds to choose what the next session launches (audit 2026-08-27)
+ # written fresh into the harness-owned trajectory dir, never the workspace's .mcp.json (agent-writable)
cfg = s.traj.dir / "mcp.json"
cmd = mcp_command_for(s.ws, job)
cfg.write_text(json.dumps(
@@ -282,7 +230,6 @@ class ClaudeCodeAgent(_CliAgent):
return argv
def build_env(self, s: Session) -> dict[str, str]:
- # keep ANTHROPIC_API_KEY if the user relies on it; subscription auth needs nothing
env = hardened_env(s.ws, s.job, keep={"ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"})
env["CLAUDE_CODE_DISABLE_BUNDLED_SKILLS"] = "1" # see CLAUDE_SETTINGS
return env
@@ -326,29 +273,21 @@ class ClaudeCodeAgent(_CliAgent):
# ===================================================================== codex
-#: ``-c`` for every codex session: the routed bundles in ``<ws>/.agents/skills`` only. codex
-#: 0.155.1 otherwise lists its five bundled ``.system`` skills (imagegen, openai-docs,
-#: plugin-creator, skill-creator, skill-installer) next to them — gone with this switch
-#: (``codex debug prompt-input``, 2026-09-22). User-level roots (``~/.codex/skills``,
-#: ``~/.agents/skills``) have no stable switch; none exist on this machine.
+#: ``-c`` for every codex session: only the routed bundles, not codex's bundled ``.system`` skills.
CODEX_SKILL_OVERRIDES = ("-c", "skills.bundled.enabled=false")
_TOOL_ITEMS = ("command_execution", "file_change", "mcp_tool_call", "web_search", "tool_call")
#: the item fields a tool trace keeps: what was run, never what came back. codex has no
-#: skill tool — it lists skills in its prompt and opens SKILL.md with a shell command, so
-#: the command string IS the activation record (0.155.1)
+#: skill tool; the shell command that opens SKILL.md is the activation record.
_TRACE_KEYS = ("command", "server", "tool", "arguments", "changes", "query")
-#: what ``-c model_reasoning_effort=`` accepts; ``""`` means "leave it to ~/.codex/config.toml"
REASONING_EFFORTS = ("", "minimal", "low", "medium", "high", "xhigh")
def split_model_effort(model: str, effort: str | None = None) -> tuple[str, str]:
"""``('gpt-5.6-sol@low', None) -> ('gpt-5.6-sol', 'low')``.
- Precedence: an explicit ``effort`` argument, then an ``@<effort>`` suffix on the
- model id, then ``Settings.agents.codex_reasoning_effort`` (default ``high`` — the
- codex CLI's own default is *medium*, and the harness would rather pay for thinking).
- ``""`` at any level means "pass no override and let ~/.codex/config.toml decide".
+ Precedence: ``effort`` argument, ``@<effort>`` suffix, ``Settings.agents.codex_reasoning_effort``;
+ ``""`` passes no override (``~/.codex/config.toml`` decides).
"""
name, _, suffix = model.partition("@")
chosen = effort if effort is not None else (suffix or get_settings().agents.codex_reasoning_effort)
@@ -359,17 +298,12 @@ def split_model_effort(model: str, effort: str | None = None) -> tuple[str, str]
def effort_overrides(effort: str) -> list[str]:
- """The ``-c`` pair for a reasoning effort (empty when nothing should be forced)."""
return ["-c", f"model_reasoning_effort={effort}"] if effort else []
-#: A session killed before its turn completed books no usage (codex reports it per TURN and
-#: ``--ephemeral`` leaves no rollout), so its cost is ESTIMATED from what the stream shows: every
-#: completed item is one more request that re-reads the context, which grows by that item.
-#: Constants fitted on the 356 completed codex sessions on record (2026-09-23): codex's own
-#: system prompt + tool schemas ≈ 20k tokens, ≈ 1k tokens per returned image, 4 chars/token,
-#: output ≈ 1.13 % of input. Estimated input / actual: median 1.01, p10–p90 0.66–1.35;
-#: estimated $ / actual $: median 0.93, p10–p90 0.62–1.34.
+#: A session killed before its turn completed books no usage (codex reports per TURN, ``--ephemeral``
+#: leaves no rollout), so cost is ESTIMATED: every completed item is one more request re-reading a
+#: growing context. Constants are fitted to completed sessions.
_EST_SYSTEM_TOKENS = 20_000
_EST_IMAGE_TOKENS = 1_000
_EST_CHARS_PER_TOKEN = 4.0
@@ -378,7 +312,6 @@ _B64_DATA = re.compile(r'"data"\s*:\s*"[A-Za-z0-9+/=]{200,}"')
class CodexEvents:
- """Folded view over the JSONL event stream."""
def __init__(self) -> None:
self.messages: list[str] = []
@@ -390,7 +323,6 @@ class CodexEvents:
self.thread_id = ""
self.n_events = 0
self.calls: list[ToolCall] = []
- #: (text tokens, images) each completed item added to the context — the estimate's input
self.items: list[tuple[float, int]] = []
def feed(self, line: str) -> None:
@@ -434,9 +366,6 @@ class CodexEvents:
tool_calls=self.tool_calls)
def estimated_usage(self, model: str, prompt_chars: int) -> Usage:
- """What a session whose turn never completed most likely spent (see ``_EST_*``):
- one request per completed item plus the one in flight, each reading the whole context
- so far; everything but each request's new content is a cache hit."""
ctx = prompt_chars / _EST_CHARS_PER_TOKEN + _EST_SYSTEM_TOKENS
prompt = uncached = ctx
for text, images in self.items:
@@ -456,9 +385,6 @@ def parse_codex_jsonl(stdout: str) -> CodexEvents:
def codex_end(proc: CompletedProc, events: CodexEvents, text: str) -> SessionEnd:
- """How a ``codex exec --json`` process ended (``cli_common.classify_end`` with codex's evidence:
- its own error events — a dropped stream, a 5xx it gave up on) — the harness session and the
- bench one-shot alike."""
ok = not proc.timed_out and proc.rc == 0 and events.n_events > 0 and not (events.errors and events.turns_completed == 0)
return classify_end(proc, ok=ok, text=text, said=(*events.errors, proc.stderr))
@@ -472,7 +398,6 @@ class CodexAgent(_CliAgent):
self.binary = binary or get_settings().binaries.codex_cli
def build_argv(self, s: Session) -> list[str]:
- """``-`` as the prompt: codex exec reads it from stdin."""
job = s.job
argv = [self.binary, "exec", "--json", "-C", str(s.ws.root), "--sandbox", "workspace-write",
"--skip-git-repo-check", "--ephemeral", "--color", "never"]
@@ -489,10 +414,7 @@ class CodexAgent(_CliAgent):
return hardened_env(s.ws, s.job, keep={"OPENAI_API_KEY", "CODEX_API_KEY"})
def run(self, job: AgentJob) -> AgentResult:
- """``usage`` arrives per TURN (``turn.completed``), and ``--ephemeral`` leaves no rollout,
- so a session killed mid-turn (1 of 357 recorded codex sessions) books an ESTIMATE from its
- stream (:meth:`CodexEvents.estimated_usage`, ``usage_estimated``). ``provider_wait_s`` stays 0.0: codex retries a 5xx inside its HTTP
- client without an event (two fake 503s, 2026-09-22: nothing on the stream)."""
+ """A killed session books an ESTIMATE (:meth:`CodexEvents.estimated_usage`); ``provider_wait_s`` stays 0.0."""
ok, why = self.available()
s = begin_session(job, self.kind)
try:
@@ -503,8 +425,7 @@ class CodexAgent(_CliAgent):
proc = invoke(s, self.build_argv(s), self.build_env(s), prompt=prompt,
stdout_name="stdout.jsonl", on_stdout=events.feed)
record_tool_calls(s, events.calls, source="codex exec --json")
- # no turn completed but requests were made (items, or a watchdog kill): an estimate,
- # flagged on the result and booked as source="estimate" — never a silent $0
+ # no turn completed but requests were made: an estimate, booked as source="estimate", never a silent $0
estimated = events.turns_completed == 0 and (bool(events.items) or proc.timed_out)
usage = (events.estimated_usage(self.model, len(prompt)) if estimated else events.usage(self.model))
usage.latency_ms = int(proc.duration_s * 1000)
@@ -529,9 +450,8 @@ class CodexAgent(_CliAgent):
# ===================================================================== antigravity
def api_model_effort(model: str, asked: str | None = None) -> tuple[str, str]:
- """``gemini-4-argon-low`` → ``('gemini-4-argon', 'low')``. Precedence: the model id's
- ``-low/-medium/-high`` suffix, then ``asked`` (``AgentJob.effort`` — a caller's explicit ask),
- then ``AGY_API_EFFORT``. No caller asks today, so a bare id runs at high (owner, 2026-10-15)."""
+ """``gemini-4-argon-low`` → ``('gemini-4-argon', 'low')``. Precedence: the id's effort suffix,
+ ``asked`` (``AgentJob.effort``), then ``AGY_API_EFFORT``."""
for effort in EFFORTS:
if model.endswith(f"-{effort}"):
return model[: -len(effort) - 1], effort
@@ -539,58 +459,31 @@ def api_model_effort(model: str, asked: str | None = None) -> tuple[str, str]:
def parse_agy_json(stdout: str) -> dict[str, Any] | None:
- """agy's envelope is the JSON line carrying ``response`` or ``status``."""
return find_json_object(stdout, lambda d: "response" in d or "status" in d)
-#: what agy prints on stderr when its own ``--print-timeout`` stops a turn in progress
-#: (``[agy] print timeout after 8m0s with turn in progress; returning partial output``; 1.3.4,
-#: still 1.4.12) — the envelope says ``SUCCESS`` with whatever response there was (usually none)
+#: what agy prints on stderr when its own ``--print-timeout`` stops a turn in progress; the
+#: envelope still says ``SUCCESS``
AGY_PRINT_TIMEOUT = "print timeout after"
-#: since 1.4.11 the envelope also says WHY a turn ended early: ``print_timeout`` | ``interrupted``
-#: | ``error``, the field absent on a normal finish. The typed verdict, read first; the stderr
-#: line is the fallback for an envelope without the field. Live 1.4.12 (2026-11-03): the clock
-#: firing while agy retried a 503 gave ``status: ERROR, finished_reason: error`` AND the stderr
-#: line — an error, not a timeout.
+#: the envelope's ``finished_reason``: ``print_timeout`` | ``interrupted`` | ``error``, absent on a
+#: normal finish. Read first; the stderr line is the fallback.
AGY_FINISHED_REASON = "finished_reason"
-#: the per-session CLI log agy writes into the trajectory dir (``--log-file``)
AGY_LOG = "agy.log"
-#: where agy keeps each conversation under its HOME: one SQLite file named by the envelope's
-#: ``conversation_id``, a ``steps`` table whose ``step_payload`` is protobuf
AGY_CONVERSATIONS = Path(".gemini") / "antigravity-cli" / "conversations"
-#: where agy records each step as it takes it, under the session's HOME: ``brain/<id>/`` (step
-#: outputs, its own transcript) and the conversation database — the session's activity for the
-#: watchdog (:func:`~codeverse3d.agents.cli_common.activity_paths`; D112). agy prints nothing
-#: until it exits, so without them a session that reads before it writes is "idle" from second 0.
-#: Passed by name: the watchdog's walk skips ``.gemini``, and the rest of the dir (presence lock,
-#: updater, caches) is touched at start-up, not per step.
+#: where agy records each step under the session's HOME, for the watchdog's activity check; agy
+#: prints nothing until it exits. Passed by name because the watchdog's walk skips ``.gemini``.
AGY_STEP_DIRS = (Path(".gemini") / "antigravity-cli" / "brain", AGY_CONVERSATIONS)
-#: agy's Gemini-API mode (1.2+, checked live on 1.3.4, 2026-10-13, and 1.4.12, 2026-11-03): ``modelProvider: "gemini"``
-#: in its settings plus ``GEMINI_API_KEY`` in the env — no sign-in, billed to the key, and the
-#: catalogue is the API's. Without the setting the key alone is ignored and the CLI asks for a
-#: login. It is the ONLY way the harness runs agy (owner, 2026-10-13): no subscription sign-in,
-#: no non-Gemini model.
+#: agy's Gemini-API mode: ``modelProvider: "gemini"`` in its settings plus ``GEMINI_API_KEY`` in the
+#: env. Without the setting the key alone is ignored. It is the only mode the harness runs.
AGY_SETTINGS = Path(".gemini") / "antigravity-cli" / "settings.json"
AGY_API_SETTINGS = {"modelProvider": "gemini"}
-#: in API mode ``--model gemini-api://<id>`` sends ``<id>`` to the API verbatim — any model the
-#: key serves, listed by ``agy models`` or not (gemini-4-argon) — and ``--effort`` sets its
-#: thinking level (low → 1, high → 3 in the CLI log, 2026-10-13)
+#: in API mode ``--model gemini-api://<id>`` sends ``<id>`` to the API verbatim; ``--effort`` sets the thinking level
AGY_API_SCHEME = "gemini-api://"
-#: the effort an API-mode id without a ``-low/-medium/-high`` suffix runs at when the job asks for
-#: none (``AgentJob.effort`` is None): the Gemini API's own default thinking level. Every track's
-#: argon sessions run here — owner, 2026-10-15: "argon 强度就直接设置high" (D110)
+#: the effort an id without a ``-low/-medium/-high`` suffix runs at when the job asks for none
AGY_API_EFFORT = "high"
-#: the model an ``agy`` generator with no model runs (owner, 2026-10-13)
DEFAULT_AGY_MODEL = "gemini-4-argon"
-#: agy's ONLY MCP config is per user (``~/.gemini/config/mcp_config.json``, the shape
-#: ``agy mcp add`` writes; still so on 1.4.12 — no scope flag, and its session-only
-#: ``--settings <json>`` covers settings, not MCP) — so an API-key session gets a HOME of its
-#: own, and this file in it
+#: agy's only MCP config is per user, so an API-key session gets a HOME of its own with this file in it
AGY_MCP_CONFIG = Path(".gemini") / "config" / "mcp_config.json"
-#: a tool call inside a step payload is three consecutive strings — its id, the tool name,
-#: the JSON arguments (``call_4419682`` · ``view_file`` · ``{"AbsolutePath": ...}``), read out
-#: of recorded conversations; no schema needed, and a tool result step that echoes the
-#: call is folded by the id
_AGY_CALL_ID = re.compile(r"call_\w+")
_AGY_TOOL = re.compile(r"[a-z][a-z0-9_]*")
@@ -609,8 +502,6 @@ def _varint(buf: bytes, i: int) -> tuple[int, int]:
def _pb_strings(buf: bytes, depth: int = 0) -> list[str]:
- """Every printable UTF-8 string in a protobuf message, nested messages included, in
- wire order — a schema-free walk; raises ValueError on bytes that are not protobuf."""
out: list[str] = []
i = 0
while i < len(buf):
@@ -644,9 +535,8 @@ def _pb_strings(buf: bytes, depth: int = 0) -> list[str]:
def agy_tool_calls(db: Path) -> list[ToolCall]:
"""Every tool call recorded in one agy conversation database, once per call id.
- agy has no skill tool (1.2.2, still 1.4.12): its prompt lists the skills and the model opens
- ``SKILL.md`` with its file tool (``read_file{Path}`` on 1.4.x, ``view_file{AbsolutePath}``
- before), so the file path IS the activation record — the walk below is name-agnostic."""
+ agy has no skill tool; the model opens ``SKILL.md`` with its file tool, so the path is the activation record.
+ """
calls: dict[str, ToolCall] = {}
con = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
try:
@@ -668,9 +558,8 @@ def agy_tool_calls(db: Path) -> list[ToolCall]:
return list(calls.values())
-#: agy 1.2.8's CLI log (``--log-file``; glog format, LOCAL time, no year) reports every failed
-#: model call it is about to retry: ``I0922 14:53:40.358454 284 run.go:395] Run: attempt 1 failed
-#: (Error 503, Message: ..., Status: UNAVAILABLE, Details: []), retrying in 4s``
+#: agy's CLI log (``--log-file``; glog format, local time, no year) reports every model call it will retry:
+#: ``I0922 14:53:40.358454 284 run.go:395] Run: attempt 1 failed (Error 503, ...), retrying in 4s``
_AGY_RETRY = re.compile(r"^[IWEF](?P<md>\d{4}) (?P<hms>\d\d:\d\d:\d\d)(?P<frac>\.\d+)?\s.*\battempt \d+ failed "
r"\((?P<why>.*)\), retrying in (?P<wait>[0-9.hmsuµn]+)\s*$")
_GO_DURATION = re.compile(r"([0-9.]+)(h|ms|m|s|us|µs|ns)")
@@ -678,7 +567,6 @@ _GO_UNIT = {"h": 3600.0, "m": 60.0, "s": 1.0, "ms": 1e-3, "us": 1e-6, "µs": 1e-
def agy_retries(log_path: Path) -> list[tuple[float, float, str]]:
- """``(t, announced back-off s, why)`` for every retried model call in one agy CLI log."""
now = time.time()
year = time.localtime(now).tm_year
out: list[tuple[float, float, str]] = []
@@ -698,8 +586,7 @@ def agy_retries(log_path: Path) -> list[tuple[float, float, str]]:
def agy_error(stderr: str) -> dict[str, Any]:
- """agy's own verdict on a turn that died (1.2.x through 1.4.12, exit code 3): the ``AGY_ERROR: {...}`` line —
- ``status``, ``error_code``, ``retryable`` — typed, where the envelope has only prose."""
+ """agy's typed verdict on a turn that died: the ``AGY_ERROR: {...}`` stderr line (``status``, ``error_code``, ``retryable``)."""
for line in reversed(stderr.splitlines()):
if line.startswith("AGY_ERROR:"):
with contextlib.suppress(json.JSONDecodeError):
@@ -709,12 +596,9 @@ def agy_error(stderr: str) -> dict[str, Any]:
def usage_from_agy(env: dict[str, Any], model: str) -> Usage:
- """The envelope's tokens, priced at the Gemini list rate. agy (1.3.4; the same on 1.4.12,
- 2026-11-03) splits neither way the pricing convention does: ``input_tokens`` EXCLUDES
- ``cache_read_tokens`` (a live 18-minute session, 2026-10-13: 582 179 input against 10 980 664
- cache reads), so the total prompt is their sum; and ``output_tokens`` CONTAINS
- ``thinking_tokens`` (``total == input + output`` on every envelope), so the thinking share
- moves to ``thoughts_tokens``, billed once."""
+ """The envelope's tokens, priced at the Gemini list rate. ``input_tokens`` EXCLUDES
+ ``cache_read_tokens`` (total prompt is their sum); ``output_tokens`` CONTAINS ``thinking_tokens``
+ (moved to ``thoughts_tokens``, billed once)."""
u = env.get("usage") or {}
thinking = int(u.get("thinking_tokens") or 0)
cached = int(u.get("cache_read_tokens") or 0)
@@ -731,17 +615,12 @@ def usage_from_agy(env: dict[str, Any], model: str) -> Usage:
def _key_pool() -> KeyPool:
- """THE process-wide Gemini pool — ``models.gemini.shared_pool``: the same cooldowns and
- dead-key bench the API path uses; a session takes its key with ``session_key`` (no
- in-flight slot: the CLI makes its own calls for minutes)."""
from codeverse3d.models.gemini import shared_pool
return shared_pool(list(get_settings().gemini_api_keys))
def _pool_outcome(end: SessionEnd, ok: bool, died: dict[str, Any]) -> str:
- """What one session tells the pool about its key. A hang, a bad answer or the agent's own
- failure is not the key's fault (``skip``: counters untouched)."""
code = died.get("error_code")
if code in (401, 403) or "API_KEY_INVALID" in json.dumps(died):
return "dead"
@@ -751,9 +630,8 @@ def _pool_outcome(end: SessionEnd, ok: bool, died: dict[str, Any]) -> str:
class AntigravityAgent(_CliAgent):
- """``agy:<gemini model>`` (default ``gemini-4-argon``), always in agy's Gemini-API mode: one
- pool key, a HOME of its own under the cache dir holding the API-mode settings and the 3dcode
- MCP server (deleted after the session; the tool trace is read out first), usage priced."""
+ """``agy:<gemini model>`` (default ``gemini-4-argon``) in agy's Gemini-API mode: one pool key and a
+ HOME of its own (API-mode settings + the 3dcode MCP server, deleted after the session), usage priced."""
kind = "agy"
cli_label = "agy"
@@ -768,23 +646,17 @@ class AntigravityAgent(_CliAgent):
return super().available()
def served_model(self) -> str:
- """The API model id the session is booked under (the effort suffix stripped)."""
return api_model_effort(self.model)[0]
def effort_for(self, job: AgentJob) -> str:
- """The ``--effort`` this job's session runs at (:func:`api_model_effort`)."""
return api_model_effort(self.model, job.effort)[1]
def model_args(self, job: AgentJob) -> list[str]:
return ["--model", f"{AGY_API_SCHEME}{self.served_model()}", "--effort", self.effort_for(job)]
def build_argv(self, s: Session) -> list[str]:
- """No ``--print``: agy reads the prompt from a piped stdin, byte for byte, and still
- answers as print mode (``--print -`` would send the prompt "-"). ``--log-file`` keeps
- its CLI log with the session — the record of the retries it made. ``--print-timeout``
- sits a minute past the watchdog's hard limit: at ``timeout_s + 1 min`` (as it was) agy
- cut off every session still working, with ``status: SUCCESS`` and an empty response
- (live, argon scene sessions, 2026-10-13), before the watchdog's grace began."""
+ """No ``--print``: agy reads the prompt from piped stdin. ``--print-timeout`` sits a minute past
+ the watchdog's hard limit so agy's own clock never cuts off a session the watchdog still allows."""
minutes = max(1, int((s.job.timeout_s + HARD_GRACE_S) // 60) + 1)
return [self.binary, "--dangerously-skip-permissions",
"--print-timeout", f"{minutes}m", "--output-format", "json",
@@ -792,9 +664,6 @@ class AntigravityAgent(_CliAgent):
*self.model_args(s.job)]
def build_home(self, s: Session) -> Path:
- """A fresh HOME for one session: the API-mode settings and, when the job has
- spatial tools, the 3dcode MCP server — which keeps the REAL home (the harness reads its
- settings, keys and caches from there)."""
home = get_settings().cache_dir / "agy_homes" / f"{s.traj.dir.name}-{os.getpid()}-{time.time_ns()}"
(home / AGY_SETTINGS).parent.mkdir(parents=True, exist_ok=True)
(home / AGY_SETTINGS).write_text(json.dumps(AGY_API_SETTINGS))
@@ -815,8 +684,6 @@ class AntigravityAgent(_CliAgent):
return env
def _record_trace(self, s: Session, home: Path, conversation_id: str) -> int:
- """The session's tool calls, from agy's own conversation database — never fatal.
- Returns how many (agy's JSON envelope carries no tool count of its own)."""
db = home / AGY_CONVERSATIONS / f"{conversation_id}.db" if conversation_id else None
if db is None or not db.is_file():
s.notes.append("no agy conversation record found for this session: tool trace missing")
@@ -828,11 +695,8 @@ class AntigravityAgent(_CliAgent):
return 0
def run(self, job: AgentJob) -> AgentResult:
- """``usage`` comes from agy's envelope only: a killed session books nothing (its
- conversation database is named by the envelope's id). ``provider_wait_s`` from its log.
- No retry loop: agy retries its own model calls (waits ≤ 30 s since 1.3.4, stops at once
- on a spent daily quota), and a transient death goes back to the round loop's one retry —
- which takes a fresh key, the 429'd one cooling in the pool."""
+ """``usage`` comes from agy's envelope only (a killed session books nothing). No retry loop: agy
+ retries its own model calls, and a transient death goes back to the round loop's one retry with a fresh key."""
ok, why = self.available()
s = begin_session(job, self.kind)
home, lease = None, None
@@ -893,7 +757,6 @@ class AntigravityAgent(_CliAgent):
def _compose_prompt_agy(s: Session) -> str:
- """agy has no system-prompt flag; prepend harness instructions + the absolute workspace path."""
head = f"Workspace root: {s.ws.root}\nWork ONLY inside it, using your file tools."
if (s.ws.root / "AGENTS.md").is_file():
head += " Read AGENTS.md there first and follow it."
diff --git a/harness/codeverse3d/agents/cli_common.py b/harness/codeverse3d/agents/cli_common.py
index 7631046f..5cf878d7 100644
--- a/harness/codeverse3d/agents/cli_common.py
+++ b/harness/codeverse3d/agents/cli_common.py
@@ -1,9 +1,6 @@
-"""What every vendor-CLI backend (``agents/backends.py``) shares: the trajectory folder
-(prompt.md, transcript.jsonl, stdout/stderr, result.json under
-``ws.trajectory_dir(label, round)``, one layout whatever the backend), the watchdog'd
-session process, the hardened environment, the session's write scope and locks, failure
-classification, and the tool-call trace. (``cli/`` is the harness's own ``3dcode`` CLI.)
-"""
+"""What every vendor-CLI backend shares: the trajectory folder (prompt, transcript, stdout/stderr,
+result.json), the watchdog'd session process, the hardened environment, write-scope enforcement,
+failure classification and the tool-call trace."""
from __future__ import annotations
@@ -33,15 +30,12 @@ from codeverse3d.proc import (
)
from codeverse3d.workspace import Workspace
-#: per-session transcript caps. Rows are byte-capped individually but nothing capped
-#: the file: a child emitting 100k lines wrote 27 MB, ~406 MB at the per-row cap. The
-#: unabridged (bounded) stream still lands in stdout.json.
+#: per-session transcript caps; the unabridged (bounded) stream still lands in stdout.json
LINE_BUDGET_BYTES = 64 * 1024 * 1024
LINE_BUDGET_ROWS = 200_000
class Trajectory:
- """Append-only writer for one agent session's files."""
def __init__(self, directory: Path | str):
self.dir = Path(directory)
@@ -91,7 +85,6 @@ class Trajectory:
append_jsonl_line(self.transcript_path, rec, self._lock)
def write_result(self, result: BaseModel, **extra: Any) -> None:
- """Write ``result.json`` = AgentResult fields + any extra diagnostics."""
write_json_atomic(self.result_path, result.model_dump(mode="json") | extra)
def read_transcript(self) -> list[dict[str, Any]]:
@@ -104,12 +97,7 @@ _SKIP_DIRS = {"node_modules", ".git", "__pycache__", ".gemini"}
@dataclass
class CompletedProc:
- """Outcome of :func:`run_with_watchdog`.
-
- ``stdout``/``stderr`` are bounded to ``codeverse3d.proc.STREAM_BUDGET_BYTES`` per
- stream (head + tail kept, truncation marker in between) — streaming consumers
- that must see every line unconditionally use ``on_line``.
- """
+ """Outcome of :func:`run_with_watchdog`; ``stdout``/``stderr`` are bounded per stream (head + tail kept)."""
rc: int
stdout: str
@@ -120,7 +108,6 @@ class CompletedProc:
class ActivityTracker:
- """Thread-safe 'last time something happened' clock."""
def __init__(self) -> None:
self._lock = threading.Lock()
@@ -136,8 +123,7 @@ class ActivityTracker:
def _latest_mtime(dirs: Iterable[Path]) -> float:
- """Newest mtime under ``dirs`` — a directory is walked, a FILE is its own mtime (a
- ``shared_tree`` session watches only its own files, D111)."""
+ """Newest mtime under ``dirs``: a directory is walked, a FILE is its own mtime."""
latest = 0.0
for d in dirs:
if d.is_file():
@@ -172,18 +158,9 @@ def run_with_watchdog(
) -> CompletedProc:
"""Run ``cmd`` streaming output; kill the process group on idle/hard timeout.
- ``on_line(stream, line)`` is called for every line (stream is ``"stdout"``
- or ``"stderr"``). ``activity_dirs`` (default ``cwd/src``; a file is watched as itself)
- are polled for mtime changes (every ``scan_s``) that also count as activity.
-
- Since 2026-08-27 the process lifecycle lives in
- :class:`codeverse3d.proc.ManagedProcess`; this function keeps only the clocks.
- Fixed by that move: a KeyboardInterrupt anywhere in the poll loop kills the
- group before propagating (it used to orphan the whole node → chrome tree —
- SIGINT never reaches a ``start_new_session`` child); stdin is written from a
- helper thread, so a child that never reads a >64 KiB prompt (every agent
- CLI gets its prompt on stdin) can no longer wedge the main thread before the
- clocks start; captured output is bounded per stream (head+tail + marker).
+ ``on_line(stream, line)`` is called for every line. ``activity_dirs`` (default ``cwd/src``) are
+ polled for mtime changes that also count as activity. Process lifecycle lives in
+ :class:`codeverse3d.proc.ManagedProcess`; stdin is written from a helper thread.
"""
if hard_timeout_s is None:
hard_timeout_s = max(soft_timeout_s * 1.5, soft_timeout_s + 600.0)
@@ -228,14 +205,6 @@ def run_with_watchdog(
def _reject_control_chars(cmd: Sequence[str], cwd: object) -> None:
- """Fail with an argv position and an excerpt instead of a bare "embedded null byte".
-
- ``subprocess.Popen`` raises ``ValueError: embedded null byte`` naming nothing at all —
- not the argument, not the offset, not the value. On 2026-08-24 that cost an hour to
- trace back to five ``\\u0000`` escapes a planner had written into plan.json four stages
- earlier (see ``schema_utils.strip_control_chars``, which is the actual cure). This is
- the backstop: if one ever leaks again, the error says where.
- """
for i, arg in enumerate(cmd):
text = str(arg)
j = text.find("\x00")
@@ -252,15 +221,13 @@ 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) — a vendor CLI's env."""
+ """``os.environ`` minus secrets (``proc.scrub_secrets``) but for the ``keep`` names."""
env = scrub_secrets(dict(os.environ)) | {k: v for k, v in os.environ.items() if k in keep}
env["PYTHONUNBUFFERED"] = "1"
return env
def hardened_env(ws: Workspace, job: AgentJob, *, keep: set[str] | None = None) -> dict[str, str]:
- """:func:`clean_env` plus the git ceiling and ``job.env``."""
env = clean_env(keep or set())
env["GIT_CEILING_DIRECTORIES"] = str(ws.root.parent)
env.update(job.env)
@@ -268,7 +235,6 @@ def hardened_env(ws: Workspace, job: AgentJob, *, keep: set[str] | None = None)
def default_mcp_command(ws: Workspace, *, language: str = "", track: str = "", round_index: int | None = None) -> list[str]:
- """The stdio MCP server command exposing the spatial tool registry for ``ws``."""
cmd = [sys.executable, "-m", "codeverse3d.spatial.mcp_server", "--workspace", str(ws.root)]
if language:
cmd += ["--language", language]
@@ -280,14 +246,11 @@ def default_mcp_command(ws: Workspace, *, language: str = "", track: str = "", r
def mcp_command_for(ws: Workspace, job: AgentJob) -> list[str]:
- """The 3dcode MCP command for this job, from the TYPED job.
-
- It deliberately does NOT read the workspace's ``.mcp.json``. That file lives where
- the agent works and every CLI backend runs unsandboxed inside it, so an agent that
- rewrote it in round 0 chose what executable the NEXT round's codex/claude launched —
- with provider credentials in the environment, and (for codex) outside the
- ``--sandbox workspace-write`` its own shell obeys. The command is rebuilt from the
- job every session instead; nothing on disk can redirect it (audit 2026-08-27)."""
+ """The 3dcode MCP command for this job, built from the TYPED job.
+
+ It never reads the workspace's ``.mcp.json``: the agent can rewrite it between rounds and
+ choose what the next session launches.
+ """
return default_mcp_command(ws, language=job.language, track=job.track, round_index=job.round)
@@ -296,8 +259,7 @@ def mcp_command_for(ws: Workspace, job: AgentJob) -> list[str]:
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):
-#: byte-snapshotted by :func:`begin_session`, compared + restored by :func:`_enforce_scope`
+#: gitignored control files git cannot revert; byte-snapshotted by :func:`begin_session`, restored by :func:`_enforce_scope`
UNTRACKED_CONTROL_FILES = ("run_state.json", "record.json")
#: the harness appends to the event stream MID-session — exempt from the tamper revert
_CONTROL_EXEMPT = frozenset({"events.jsonl"})
@@ -310,17 +272,11 @@ def _hinted(path: str, hints: frozenset[str]) -> bool:
def attribute_changes(files: list[FileChange], *, write_roots: list[str],
only: Iterable[str] | None = None) -> list[FileChange]:
"""The subset of a whole-worktree git diff that belongs to ONE session: inside its
- ``write_roots`` and not harness-owned. (Agent sessions on one workspace are serialised —
- :data:`EXCLUSIVE_KINDS` — so there is no sibling SESSION to attribute against; the
- edit_only scope is enforced by :func:`_enforce_scope`, which REVERTS an out-of-scope write
- rather than hiding it from ``files_changed``.)
-
- ``only`` — a ``shared_tree`` job's ``files_hint`` (D111): harness writers that take no
- session lock (the scene asset single-shots) change the same tree while the session runs,
- and the diff cannot tell their files from the session's. The env session of iteration 4
- (argon loop, 2026-10-15) wrote nothing in 12 of 15 runs and was credited with the asset
- files every time, so its stage read ``ok``. Under ``only`` a path outside it is not the
- session's."""
+ ``write_roots`` and not harness-owned.
+
+ ``only`` (a ``shared_tree`` job's ``files_hint``): harness writers that take no session lock
+ change the same tree meanwhile, so a path outside ``only`` is not the session's.
+ """
roots = tuple(r.strip("/") for r in write_roots if r.strip("/"))
own = _clean(only) if only is not None else None
out: list[FileChange] = []
@@ -338,7 +294,6 @@ def attribute_changes(files: list[FileChange], *, write_roots: list[str],
@dataclass
class Session:
- """State for one CLI agent run (created by :func:`begin_session`)."""
ws: Workspace
job: AgentJob
@@ -352,17 +307,12 @@ class Session:
attempt: int = 1
files_hint: frozenset[str] = frozenset()
ws_lock: threading.RLock | None = None
- #: bytes of :data:`UNTRACKED_CONTROL_FILES` at session start (None = absent)
control_snapshot: dict[str, bytes | None] = field(default_factory=dict)
# --------------------------------------------------------------------------- serialisation
-#: agent kinds whose sessions are EXCLUSIVE per workspace — today, every kind. No
-#: backend has write-time enforcement (scope is checked post-session by
-#: :func:`_enforce_scope`), and both session snapshots run ``git add -A`` — a
-#: late-starting session's ``pre:`` commit absorbs a sibling's in-flight writes, which
-#: makes concurrent provenance (and any per-path rollback) unfixable after the fact.
-#: So agent sessions on one workspace are serialised.
+#: agent kinds whose sessions are EXCLUSIVE per workspace (every kind): scope is checked post-session,
+#: and a late session's ``pre:`` commit (``git add -A``) would absorb a sibling's in-flight writes.
EXCLUSIVE_KINDS = frozenset({"claude-code", "codex", "agy"})
_WS_SESSION_LOCKS: dict[str, threading.RLock] = {}
@@ -370,42 +320,31 @@ _WS_SESSION_LOCKS_GUARD = threading.Lock()
def _session_lock(ws: Workspace) -> threading.RLock:
- """One re-entrant lock per workspace root. Re-entrant so a thread that begins a
- session it never finishes (argv-building tests do) cannot deadlock itself; real
- sessions begin, finish and release on their own worker thread."""
+ """One re-entrant lock per workspace root (so a thread that never finishes a session cannot deadlock itself)."""
with _WS_SESSION_LOCKS_GUARD:
return _WS_SESSION_LOCKS.setdefault(str(ws.root), threading.RLock())
@contextlib.contextmanager
def exclusive_workspace(ws: Workspace) -> Iterator[None]:
- """Hold ``ws``'s session lock for a HARNESS writer that commits while agent sessions may run on
- the same workspace (the scene env recovery beside an escalated asset session, D112).
-
- WHY the lock and not "restore an out-of-scope path to HEAD instead of ``head_before``": every
- commit is ``git add -A``, so a harness commit made mid-session also absorbs the session's own
- in-flight writes — restoring to HEAD would keep exactly the out-of-scope writes the revert
- exists to undo, on every track. Holding the lock keeps every harness commit out of every
- session's window, so ``head_before`` stays the whole truth :func:`_enforce_scope` relies on.
- Argon loop iteration 5, scene_blender r1_10: the asset session's revert restored env.py to its
- ``head_before`` and erased the harness's recovered env (+391 lines) — round 0 rendered black."""
+ """Hold ``ws``'s session lock for a HARNESS writer that commits while agent sessions may run.
+
+ A harness commit mid-session (``git add -A``) would absorb the session's in-flight writes and
+ break the ``head_before`` that :func:`_enforce_scope` restores to.
+ """
lock = _session_lock(ws)
with lock:
yield
def release_session(s: Session) -> None:
- """Release ``s``'s workspace lock (idempotent). ``finish_session`` always calls it;
- the CLI backends also call it in a ``finally`` so a session that crashes between
- begin and finish cannot starve every later session on the same workspace."""
lock, s.ws_lock = s.ws_lock, None
if lock is not None:
lock.release()
def _session_label(ws: Workspace, label: str, round_index: int) -> tuple[str, int]:
- """``label`` for attempt 1; ``<label>.a<n>`` when ``trajectories/<label>_rNN`` already
- holds a finished attempt (result.json) — a silent-bail retry must not overwrite it."""
+ """``label`` for attempt 1; ``<label>.a<n>`` when a finished attempt (result.json) already exists."""
n, cand = 1, label
while (ws.trajectory_dir(cand, round_index) / "result.json").exists():
n += 1
@@ -414,11 +353,8 @@ def _session_label(ws: Workspace, label: str, round_index: int) -> tuple[str, in
def begin_session(job: AgentJob, kind: str) -> Session:
- """Create the trajectory dir, write prompt.md and snapshot src/ (``pre:<label>``).
-
- For :data:`EXCLUSIVE_KINDS` the per-workspace session lock is taken BEFORE the
- ``pre:`` commit and held until ``finish_session`` releases it — see the constant's
- comment for why concurrent CLI sessions in one workspace are unfixable."""
+ """Create the trajectory dir, write prompt.md and snapshot src/ (``pre:<label>``), taking the
+ per-workspace lock first for :data:`EXCLUSIVE_KINDS`."""
ws = Workspace(job.workspace)
if not ws.root.is_dir():
raise FileNotFoundError(f"workspace does not exist: {ws.root}")
@@ -446,23 +382,16 @@ def begin_session(job: AgentJob, kind: str) -> Session:
def _clean(seq: Any) -> frozenset[str]:
- """Normalise a path list: str(), strip, drop empties."""
return frozenset(p for p in (str(x).strip() for x in seq) if p)
def _enforce_scope(s: Session) -> dict[str, str]:
- """Revert a CLI session's out-of-scope writes; returns the reverted paths.
-
- Post-hoc, because every backend is a vendor CLI and none has a write-time file gate
- (the in-process one that did was deleted 2026-08-28). Three layers:
- ``job.read_only`` ALWAYS — harness-owned source the agent must call, never rewrite
- (scene_threejs's ``src/lib/``); ``job.write_roots`` ALWAYS — a CLI session used to be able
- to write and commit a root-level ``conftest.py``; then, for ``edit_only``, the
- narrowing to ``files_hint`` + ``always_writable`` (a pre-existing file outside it is
- out of scope; new files stay allowed). Only safe because sessions on one workspace
- are serialised (:data:`EXCLUSIVE_KINDS`) and a harness writer that commits mid-run takes the
- same lock (:func:`exclusive_workspace`): ``head_before`` holds no sibling's in-flight work and
- no harness commit lands inside the session's window."""
+ """Revert a CLI session's out-of-scope writes; returns ``{path: reason}``.
+
+ Layers: ``job.read_only`` and ``job.write_roots`` always; for ``edit_only``, the narrowing to
+ ``files_hint`` + ``always_writable`` (new files stay allowed). Relies on sessions on one
+ workspace being serialised, so ``head_before`` holds no sibling's or harness's work.
+ """
roots = tuple(r.strip("/") for r in s.job.write_roots if r.strip("/"))
frozen = _clean(s.job.read_only)
narrow = (s.files_hint | _clean(s.job.always_writable)
@@ -470,12 +399,11 @@ def _enforce_scope(s: Session) -> dict[str, str]:
reverted: dict[str, str] = {}
restore: list[str] = []
remove: list[str] = []
- # no empty-scope early-out: control files are enforced under ANY job scope
for f in s.ws.changed_files(s.head_before):
parts = Path(f.path).parts
if not parts or parts[0] in HARNESS_OWNED_DIRS or f.path in _CONTROL_EXEMPT:
continue
- if f.path in HARNESS_OWNED_FILES: # was a silent skip: the tamper survived AND went unreported
+ if f.path in HARNESS_OWNED_FILES:
why = "harness control file: never agent-writable"
elif is_harness_owned(f.path, frozen):
why = "harness-owned: call its functions, never rewrite it"
@@ -521,25 +449,17 @@ def finish_session(
effort: str = "",
**extra: Any,
) -> AgentResult:
- """Commit the agent's work, compute ``files_changed`` via git (attributed to this
- session — see :func:`attribute_changes`; a ``shared_tree`` job is credited with its
- ``files_hint`` only), write result.json. ``turns`` is the
- backend's own count (``AgentResult.turns``); ``transient`` / ``quota`` / ``stalled`` its typed
- failure class (:class:`SessionEnd`) and ``provider_wait_s`` the time its CLI lost to provider errors
- (:func:`provider_wait`); ``effort`` what the backend passed its CLI (``AgentResult.effort``);
- ``extra`` lands in result.json only.
-
- Write scope is enforced here for the CLI backends (they have no write-time gate):
- writes outside ``write_roots`` (and, for ``edit_only``, outside ``files_hint``) are
- reverted to this session's own ``pre:`` commit and the session is failed
- (:func:`_enforce_scope`)."""
+ """Commit the agent's work, compute ``files_changed`` via git (attributed to this session),
+ write result.json. ``extra`` lands in result.json only.
+
+ Writes outside ``write_roots`` (or, for ``edit_only``, ``files_hint``) are reverted to the
+ session's ``pre:`` commit and the session is failed (:func:`_enforce_scope`).
+ """
try:
errors = list(errors or [])
reverted = _enforce_scope(s)
if reverted:
ok = False
- # each path carries ITS reason: a read_only revert used to be blamed on
- # write_roots ("may only write under ['src']") for a file under src/
msg = ("out-of-scope writes reverted: "
+ "; ".join(f"{p} ({why})" for p, why in sorted(reverted.items())))
errors.append(msg)
@@ -564,27 +484,20 @@ def finish_session(
def failed(s: Session, reason: str, message: str, usage: Usage | None = None) -> AgentResult:
- """Shortcut for an ``ok=False`` result with one error line."""
return finish_session(s, ok=False, exit_reason=reason, text="", usage=usage or Usage(), errors=[message])
# --------------------------------------------------------------------------- invoke
-#: seconds without output or workspace activity before the watchdog kills a CLI agent;
-#: read at call time by :func:`invoke` so a test can monkeypatch it here.
+#: seconds without output or workspace activity before the watchdog kills a CLI agent (read at call time)
IDLE_GRACE_S = 300.0
-#: how far past its soft timeout a session that is still working may run before the watchdog
-#: kills it whatever it is doing — the hard limit is ``timeout_s + HARD_GRACE_S``. A CLI with
-#: a clock of its own must be set past it (agy ``--print-timeout``), or that clock decides.
+#: how far past its soft timeout a working session may run: the hard limit is ``timeout_s + HARD_GRACE_S``;
+#: a CLI with a clock of its own must be set past it (agy ``--print-timeout``)
HARD_GRACE_S = 300.0
-#: how often the watchdog re-reads the activity paths' mtimes; read at call time like
-#: :data:`POLL_S` so a test can turn it down.
+#: how often the watchdog re-reads the activity paths' mtimes (read at call time)
SCAN_S = 5.0
-#: watchdog poll period. A real vendor CLI runs for minutes, so 1 s of latency on
-#: noticing it exited is free — but a FAKE cli in a test exits in milliseconds and then
-#: waits out the poll, which was ~1 s on every agent.run() in the suite. Same shape as
-#: IDLE_GRACE_S: read at call time so tests can turn it down (tests/agents/conftest.py).
+#: watchdog poll period (read at call time so tests can turn it down)
POLL_S = 1.0
@@ -602,29 +515,15 @@ def invoke(
) -> CompletedProc:
"""Run one CLI agent process under the watchdog and record it in the trajectory.
- The prompt goes to the CLI on STDIN, always, for every backend — never on argv and never
- through a file the agent must read. argv caps one argument at 128 KiB (``MAX_ARG_STRLEN``),
- and the file stub this replaced (``task_prompt.md`` above 100 kB) handed the prompt to the
- agent's own file tool, which (gemini-cli's ``read_file``, 2 000 lines) silently dropped the
- last zones of a 5-zone scene prompt. Each CLI reads its whole stdin as the prompt,
- byte for byte (checked 2026-09-22 against claude-code 2.1.280, codex
- 0.155.1 and agy 1.2.8 with a 185 000-character, 2 502-line prompt; agy alone truncates a
- request past ~175 kB, whatever carries it).
-
- One block every backend shares: the ``invoke`` transcript line, ``run_with_watchdog``
- (workspace cwd, the job's soft timeout, ``IDLE_GRACE_S``, every output line into the
- transcript, ``src/`` + ``public/`` as activity dirs — a ``shared_tree`` job's own files only —
- plus ``activity``, the backend's own record of the session's steps, :func:`activity_paths`)
- and the stdout/stderr captures next to
- the transcript. ``stdout_name`` sets the capture's name (codex streams JSONL →
- ``stdout.jsonl``); ``on_stdout`` / ``on_stderr`` also receive each line as it arrives (the
- backends fold their event streams live). The ``invoke`` line records the prompt's size,
- plus ``invoke_extra`` (agy in API mode adds ``model``, the ``effort`` it passed and ``key_tail``).
+ The prompt goes to the CLI on STDIN for every backend (never argv or a file the agent must
+ read). Output lines go into the transcript; ``src/`` + ``public/`` (a ``shared_tree`` job's own
+ files) plus ``activity`` are the activity dirs. ``stdout_name`` names the capture;
+ ``on_stdout`` / ``on_stderr`` also receive each line; ``invoke_extra`` lands in the ``invoke`` row.
"""
soft = float(s.job.timeout_s)
hard = soft + HARD_GRACE_S
if s.job.hard_deadline_s is not None:
- # This runs AFTER begin_session's workspace lock. A queued job must not regain the window it had before waiting for a peer.
+ # runs AFTER begin_session's workspace lock: a queued job must not regain the window it had before waiting
hard = min(hard, max(0.0, s.job.hard_deadline_s - time.monotonic()))
soft = min(soft, hard)
s.traj.append("invoke", argv=list(argv), stdin_bytes=len(prompt.encode("utf-8")),
@@ -651,37 +550,23 @@ def invoke(
def activity_paths(s: Session, steps: Sequence[Path] = ()) -> list[Path]:
- """What the watchdog polls as this session's activity: ``src/`` + ``public/``, or — a
- ``shared_tree`` job (D111) — its ``files_hint`` paths alone; plus ``steps``, where the
- CLI itself records each step it takes (agy: its per-session HOME's ``brain/`` and
- ``conversations/``, :data:`~codeverse3d.agents.backends.AGY_STEP_DIRS`).
-
- The asset single-shots writing ``src/assets/`` beside the env session kept it "alive" until
- ~300 s after their last write, so its kill time followed the asset stage (421-616 s on a
- 420 s window in the 12 iteration-4 runs whose session wrote nothing) instead of its own
- work. Narrowed to its own file, though, a session that is READING was idle from second 0:
- agy prints nothing until it exits, so its soft window was a hard kill — 22 of 26 env
- sessions and 4 of 21 refines of iteration 5 died at exactly the window with nothing written,
- mid-read (D112). A step the CLI records is activity; a session that takes none for
- ``IDLE_GRACE_S`` past its window is still killed there, and every session stops at its
- hard limit."""
+ """What the watchdog polls as this session's activity: ``src/`` + ``public/``, or a
+ ``shared_tree`` job's ``files_hint`` paths alone; plus ``steps``, where the CLI itself records
+ each step (agy prints nothing until it exits, so a session that only reads would look idle).
+ """
own = [s.ws.root / h for h in sorted(s.files_hint)] if s.job.shared_tree else [s.ws.src, s.ws.public]
return own + list(steps)
def watchdog_error(proc: CompletedProc) -> str:
- """The error line every CLI backend records when the watchdog killed its process."""
return f"killed by watchdog ({proc.killed_reason}) after {proc.duration_s:.0f}s"
# --------------------------------------------------------------------------- tool trace
-#: The CLI's OWN record of what it called, normalised into ``transcript.jsonl`` by every
-#: backend after its session: one :data:`TOOL_CALL_ROW` per call, then ONE
-#: :data:`TOOL_TRACE_ROW` saying "this session's calls are all here" — a session without
-#: it left no trace, and its silence must not read as "called nothing". The skill read
-#: probe (``skills/telemetry.py``) reads these rows instead of file atimes, which its own
-#: control bundle caught "reading" in 27 of 33 sessions (docs/SKILLS.md §4). Arguments are
-#: compacted to :data:`TRACE_ARG_CHARS` per value: a path survives, a file body does not.
+#: The CLI's OWN record of what it called, normalised into ``transcript.jsonl`` by every backend:
+#: one :data:`TOOL_CALL_ROW` per call, then ONE :data:`TOOL_TRACE_ROW` saying "this session's calls
+#: are all here" (a session without it left no trace, which must not read as "called nothing").
+#: Arguments are compacted to :data:`TRACE_ARG_CHARS` per value.
TOOL_CALL_ROW = "tool_call"
TOOL_TRACE_ROW = "tool_trace"
TRACE_ARG_CHARS = 400
@@ -689,11 +574,8 @@ TRACE_ARG_CHARS = 400
@dataclass(frozen=True)
class ToolCall:
- """One tool call as the CLI reported it. ``skill`` names the bundle when the call was
- the CLI's own skill-activation tool (claude-code ``Skill``),
- so a reader of the trace never needs any vendor's tool vocabulary; ``failed`` is the
- CLI's own verdict on the call (a ``sed`` of a mis-expanded skill path read nothing —
- codex 0.155.1 did exactly that on its first try, 2026-09-22)."""
+ """One tool call as the CLI reported it. ``skill`` names the bundle when the call was the CLI's
+ skill-activation tool; ``failed`` is the CLI's own verdict on the call."""
tool: str
args: Mapping[str, Any] = field(default_factory=dict)
@@ -714,9 +596,8 @@ def record_tool_calls(s: Session, calls: Iterable[ToolCall], *, source: str,
skills_index: Sequence[str] | None = None) -> int:
"""Append one session's tool calls and the closing :data:`TOOL_TRACE_ROW`; returns the count.
- ``source`` says where the backend read them (its event stream, its chat record);
- ``skills_index`` is the skill list the CLI itself reported as available, when it
- reports one (claude-code's ``init`` event) — the proof the index reached the model."""
+ ``skills_index`` is the skill list the CLI reported as available, when it reports one.
+ """
n = 0
for c in calls:
row: dict[str, Any] = {"tool": c.tool, "args": _compact(dict(c.args))}
@@ -732,28 +613,18 @@ def record_tool_calls(s: Session, calls: Iterable[ToolCall], *, source: str,
# --------------------------------------------------------------------------- failures
-#: THE vocabulary for what a CLI says about the call that ended its session — one place for
-#: every backend. The backends turn it into typed flags (``AgentResult.transient`` / ``.quota``)
-#: that ride ``GenerationResult`` into ``RoundFailed``; the round loop never reads a message.
-#: Transient: a provider failure a retry may get through — capacity (5xx, UNAVAILABLE,
-#: overloaded), rate limits (429, RESOURCE_EXHAUSTED) and the transport (a dropped, refused or
-#: reset connection, an empty or broken stream). The gRPC status names match case-sensitively:
-#: lower-case "internal" is in every node stack trace (``node:internal/process/...``), which made
-#: any crashed CLI look transient. A plain "timed out" is NOT here: the watchdog's own kill, a
-#: slow MCP tool and a provider timeout all say it, and a retry of the first two buys another
-#: full window for the same outcome (provider timeouts arrive typed: agy's ``AGY_ERROR``,
-#: ``ModelError(status=408, retryable=True)``).
+#: the vocabulary for what a CLI says about the call that ended its session. Transient: a provider
+#: failure a retry may get through (capacity, rate limits, dropped transport). gRPC status names
+#: match case-sensitively ("internal" is in every node stack trace). A plain "timed out" is NOT
+#: here: the watchdog's kill and a slow MCP tool say it too, and a retry buys the same outcome.
_TRANSIENT_RE = re.compile(
r"(?-i:\b(?:UNAVAILABLE|INTERNAL|RESOURCE_EXHAUSTED|DEADLINE_EXCEEDED)\b)|\b(?:429|50[0234]|529)\b|overloaded"
r"|rate.?limit|empty response|Invalid stream|fetch failed|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN"
r"|socket hang up|connection reset|stream disconnected",
re.IGNORECASE,
)
-#: Quota: the vendor's usage limit or credits are spent and nothing gets through until they reset
-#: (codex "You've hit your usage limit", claude "usage limit reached" / "You've hit your limit" /
-#: "out of usage credits", OpenAI ``insufficient_quota``). Not a rate limit: gemini says "Quota
-#: exceeded ... per minute" and "You exceeded your current quota" of a per-key 429 the key pool
-#: rotates past, so neither phrase is here.
+#: Quota: the vendor's usage limit or credits are spent. Not a rate limit: gemini's per-key
+#: "quota exceeded" 429s are rotated past by the key pool, so those phrases are not here.
_QUOTA_RE = re.compile(
r"usage limit|hit your limit|out of (?:extra )?usage|usage credits|credit balance (?:is )?too low"
r"|purchase more credits|insufficient[_ ]quota|insufficient credits|billing hard limit",
@@ -763,7 +634,6 @@ _RATE_LIMIT_RE = re.compile(r"\b429\b|(?-i:\bRESOURCE_EXHAUSTED\b)|rate.?limit",
def is_quota_failure(*texts: str) -> bool:
- """The vendor's usage limit is spent (``AgentResult.quota``): stop, do not retry."""
return any(_QUOTA_RE.search(t or "") for t in texts)
@@ -774,15 +644,13 @@ def is_transient_failure(*texts: str) -> bool:
def is_rate_limited(*texts: str) -> bool:
- """A 429: transient, and the key that got it should cool down (``exit_reason="budget"``)."""
return any(_RATE_LIMIT_RE.search(t or "") for t in texts)
@dataclass(frozen=True)
class SessionEnd:
- """How a CLI session ended: ``exit_reason`` (completed | timeout | budget | error) and the
- typed failure class ``AgentResult.transient`` / ``.quota`` carry. ``rate_limited`` is a
- 429 — agy in API mode cools its key in the pool."""
+ """How a CLI session ended: ``exit_reason`` (completed | timeout | budget | error) plus the typed
+ failure class; ``rate_limited`` is a 429 (agy cools its key in the pool)."""
exit_reason: str
transient: bool = False
@@ -793,21 +661,13 @@ class SessionEnd:
def classify_end(proc: CompletedProc, *, ok: bool, text: str, said: Sequence[str] = (),
provider_failed: bool = False) -> SessionEnd:
- """THE end rule for every CLI backend (N71; D83) — each backend brings only its vendor's
- evidence: ``said`` (what the CLI printed about the call that ended it) and ``provider_failed``
- (a typed vendor verdict: agy's ``AGY_ERROR.retryable``).
-
- A watchdog kill is ``timeout`` and never ``transient`` (the key it ran on is not at fault). It
- is ``stalled`` when the watchdog found the session IDLE — no output, no workspace write and no
- step the CLI recorded for ``IDLE_GRACE_S`` past its window — and it answered nothing: a hang
- (iteration 5, r1_09: "connection reset by peer", then 10.8 minutes of silence), which the round
- loop and the stage retry give ONE more session when the clock still holds a minimum window
- (D112). A kill at the hard limit is the task's own pace: a retry buys the same window for the
- same outcome. Until D112 a kill was transient whenever the CLI's log held ANY provider retry —
- one 4 s 503 at t=0 — so the same 901 s / zero-file kill was retried in r1_05 and r1_09 and
- ended r1_07 and r1_08 as no_change. Any other failure is ``quota`` / ``transient`` by the
- vocabulary above, and ``budget`` when the usage limit is spent or the call was rate limited,
- for every vendor."""
+ """The end rule for every CLI backend; each brings only its vendor's evidence: ``said`` (what the
+ CLI printed about the call that ended it) and ``provider_failed`` (a typed vendor verdict).
+
+ A watchdog kill is ``timeout``, never ``transient``; ``stalled`` when the watchdog found the
+ session IDLE and it produced no text. Any other failure is ``quota`` / ``transient`` by the
+ vocabulary above, and ``budget`` when the usage limit is spent or the call was rate limited.
+ """
if ok:
return SessionEnd("completed")
if proc.timed_out:
@@ -824,14 +684,11 @@ def provider_wait(failures: Iterable[tuple[float, float]], end: float,
progress: Iterable[float] | None = None) -> float:
"""Seconds a session lost to provider errors, from the CLI's own record of them.
- ``failures`` are ``(t, backoff_s)``: when the CLI reported a failed API attempt, and the
- back-off it announced before the next one (0 when it does not say). ``progress`` are the times the session demonstrably moved on (a model message, a
- tool result); ``None`` when the CLI records none (agy's log). Failures with no progress
- between them form one burst, which costs from the last progress before it — when the
- request that failed went out; its first failure when nothing precedes it — until the
- CLI tried again after the burst's last failure (``t + backoff``). A burst no progress
- ever followed costs until ``end``: the CLI gave up, or the watchdog killed it mid-storm.
- A lower bound wherever the back-off is unannounced."""
+ ``failures`` are ``(t, backoff_s)``; ``progress`` are the times the session demonstrably moved
+ on (``None`` when the CLI records none). Failures with no progress between them form one
+ burst, costing from the last progress before it until the CLI retried after it (or until
+ ``end`` when nothing followed). A lower bound wherever the back-off is unannounced.
+ """
fails = sorted(failures)
prog = sorted(progress) if progress is not None else []
total, i = 0.0, 0
@@ -848,12 +705,7 @@ def provider_wait(failures: Iterable[tuple[float, float]], end: float,
def find_json_object(stdout: str, accept: Callable[[dict[str, Any]], bool]) -> dict[str, Any] | None:
- """The one JSON envelope a CLI printed, possibly around log noise.
-
- Tries the whole text; unwraps a top-level list (claude's stream-json array) to
- its LAST accepted element; then ``{``-starting lines from the END (claude / agy
- print one envelope per line after their chatter). ``accept`` says which dict is the
- envelope."""
+ """The one JSON envelope a CLI printed, possibly among log noise; ``accept`` picks the dict."""
s = stdout.strip()
if not s:
return None
diff --git a/harness/codeverse3d/agents/materialize.py b/harness/codeverse3d/agents/materialize.py
index 686cfd4b..3a5002ef 100644
--- a/harness/codeverse3d/agents/materialize.py
+++ b/harness/codeverse3d/agents/materialize.py
@@ -1,25 +1,8 @@
-"""Materialise per-workspace agent instructions + ignore file.
+"""Per-workspace agent instructions + ignore file.
One shared body is written to ``AGENTS.md`` (codex / agy) and ``CLAUDE.md`` (claude-code):
-task-agnostic rules, how to call the ``3dcode`` spatial tools, and the language contract.
-(agy reads ``GEMINI.md`` as well as ``AGENTS.md``; a third copy would be
-loaded twice.) MCP wiring — never a file in the workspace, which is agent-writable:
-
-* claude-code → per-session ``trajectories/<label>_rNN/mcp.json`` (``agents/backends.py``)
-* codex → ``-c`` overrides (:func:`codex_mcp_overrides`, built per session by its backend)
-* agy → the ``mcp_config.json`` of the session's own HOME (``AntigravityAgent.build_home``)
-
-Skills: the routed ``SKILL.md`` bundles are written per ROUND, not here — the set depends
-on the round's kind and the previous round's gate findings (``codeverse3d/skills``,
-``tracks/skills_hook.py``). ``skills.materialize.write_index`` then edits a marked section
-into the body files this module writes, so there is exactly one shared head and no
-new one (docs/COST.md §13 measured and reverted a second head at +2,925 tokens/call).
-Nothing here needs to change for the CLIs to see them: codex's per-tool approval override
-below is scoped to ``mcp_servers.3dcode.*`` and cannot reach its skills loader.
-claude-code needs ``Skill`` in its ``--allowedTools`` (``backends.ALLOWED_TOOLS``), and each
-backend records what its CLI activated (``cli_common.record_tool_calls``).
-
-Ignore file: ``.antigravityignore`` hides only noise (:data:`IGNORE_LINES`).
+rules, the ``3dcode`` tool cards and the language contract. MCP wiring is never a file in
+the workspace (it is agent-writable). Skills are written per round by ``codeverse3d/skills``.
"""
from __future__ import annotations
@@ -36,10 +19,7 @@ log = logging.getLogger(__name__)
MCP_SERVER_NAME = "3dcode"
MCP_TOOL_TIMEOUT_MS = 600_000
-#: ``.antigravityignore`` — agy's own ignore file. The agent-facing artefacts must stay readable:
-#: ``artifacts/*.json`` (the build tool advertises ``census.json`` etc.) and
-#: ``artifacts/tool_renders/``. Only noise / harness-private output is hidden — ``trajectories/``
-#: whole since the prompt reaches every CLI on stdin.
+#: agy's ignore file: hides harness-private noise only; the agent-facing artefacts stay readable.
IGNORE_FILE = ".antigravityignore"
IGNORE_LINES = (
"artifacts/renders/", "artifacts/judge/", "trajectories/",
@@ -52,8 +32,7 @@ IGNORE_LINES = (
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
- # agy's ONLY tool documentation, and the whole registry taught dead-end object tools
+ # filter to the MCP server's track/language tool set (this file is agy's only tool documentation)
spec = (read_json_or_none(ws.spec_path) if ws is not None else None) or {}
tools = list_tools(track=str(spec.get("track", "")), language=str(spec.get("language", "")))
names = {t.name for t in tools}
@@ -111,8 +90,7 @@ def _toml_str_list(items: list[str]) -> str:
return "[" + ", ".join(json.dumps(x) for x in items) + "]"
-#: codex ≥ 0.14x asks for per-tool approval before running an MCP tool; ``codex exec`` has
-#: nobody to answer, so without this every 3dcode call is auto-cancelled ("requires approval").
+#: codex asks for per-tool approval before an MCP tool runs; ``codex exec`` has nobody to answer.
CODEX_MCP_APPROVAL_MODE = "approve"
@@ -121,9 +99,7 @@ def codex_mcp_overrides(mcp_command: list[str]) -> list[str]:
return [
"-c", f"mcp_servers.{MCP_SERVER_NAME}.command={json.dumps(mcp_command[0])}",
"-c", f"mcp_servers.{MCP_SERVER_NAME}.args={_toml_str_list(mcp_command[1:])}",
- # Codex filters the environment of stdio MCP subprocesses. Preserve the
- # caller's explicit engine/runtime selection (e.g. a frozen benchmark
- # checkout) instead of silently importing an unrelated editable install.
+ # codex filters the environment of stdio MCP subprocesses; pass the engine/runtime selection through.
"-c", f"mcp_servers.{MCP_SERVER_NAME}.env_vars={_toml_str_list(['PYTHONPATH', 'C3D_RUNTIME_JS'])}",
"-c", f"mcp_servers.{MCP_SERVER_NAME}.tool_timeout_sec={MCP_TOOL_TIMEOUT_MS // 1000}",
"-c", f"mcp_servers.{MCP_SERVER_NAME}.startup_timeout_sec=60",
@@ -139,23 +115,10 @@ def materialize_workspace(
contract_md: str,
mcp_command: list[str] | None = None,
) -> None:
- """Write AGENTS.md / CLAUDE.md + the ignore file into ``ws``.
-
- ``mcp_command`` defaults to ``cli_common.default_mcp_command(ws)`` — the same
- ``sys.executable`` the backends launch; three callers used to spell a bare ``python``
- here, which the body text and codex's ``-c`` overrides then quoted verbatim.
-
- Returns nothing: the ``Materialized`` DTO this used to build (body/ignore paths, the
- argv, a warnings list) was discarded by every production caller —
- ``tracks/common.Services.materialize`` is typed ``-> None``.
-
- The body is the hard rules, the tool cards and the language contract — nothing else is
- written for the agent to read (D107, owner 2026-10-15: no language ships a cookbook; the
- interface facts are in the contract, the craft in the routed skills)."""
+ """Write AGENTS.md / CLAUDE.md + the ignore file into ``ws``."""
mcp_command = list(mcp_command) if mcp_command else default_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-owned
- # per-session file, so an agent-planted server cannot reach the next round (audit 2026-08-27).
+ # no MCP server is written into the workspace: every CLI gets 3dcode from a harness-owned per-session file
(ws.root / IGNORE_FILE).write_text("\n".join(IGNORE_LINES) + "\n")
diff --git a/harness/codeverse3d/agents/registry.py b/harness/codeverse3d/agents/registry.py
index 60a018e7..b91cd956 100644
--- a/harness/codeverse3d/agents/registry.py
+++ b/harness/codeverse3d/agents/registry.py
@@ -11,18 +11,8 @@ from codeverse3d.contracts.agent import AgentJob, AgentResult
class CodingAgent(Protocol):
"""Runs ONE headless agent session in ``job.workspace``.
- Contract for implementations:
- * the agent may only write under ``job.write_roots`` (harness materialises
- AGENTS.md/CLAUDE.md + MCP config before the call; see
- ``agents/materialize.py``),
- * never raise for agent failures — return ``AgentResult(ok=False, exit_reason=...)``,
- * fill ``usage`` (tokens + cost) as precisely as the CLI allows,
- * write the full transcript to ``job.workspace/trajectories/...`` and set
- ``transcript_path``,
- * compute ``files_changed`` via ``Workspace.changed_files`` (git), not by
- trusting the agent's claims,
- * respect ``job.timeout_s`` with an activity-aware watchdog (kill the whole
- process group on timeout).
+ Implementations never raise for agent failures (return ``AgentResult(ok=False, ...)``),
+ write only under ``job.write_roots``, and compute ``files_changed`` from git.
"""
kind: str # claude-code | codex | agy
@@ -50,8 +40,7 @@ def parse_agent_id(agent_id: str) -> tuple[str, str]:
def get_coding_agent(agent_id: str) -> CodingAgent:
- """The (metered) CodingAgent for ``<kind>:<model>`` — the same wrap
- ``models.registry.get_chat_model`` gives a chat model."""
+ """The (metered) CodingAgent for ``<kind>:<model>``."""
from codeverse3d.cost.instrument import metered_agent
return metered_agent(_build_agent(agent_id))
diff --git a/harness/codeverse3d/cli/_common.py b/harness/codeverse3d/cli/_common.py
index 71468f6a..a1494332 100644
--- a/harness/codeverse3d/cli/_common.py
+++ b/harness/codeverse3d/cli/_common.py
@@ -1,6 +1,5 @@
-"""Shared CLI plumbing: Rich formatting (run summaries, tables, observations, doctor
-rows), the run-mutation mutex, workspace opening / creation and the cost-quality dial
-resolution every command goes through."""
+"""Shared CLI plumbing: Rich formatting, the run mutex, workspace opening / creation and
+variant resolution."""
from __future__ import annotations
@@ -54,8 +53,6 @@ def fmt_usd(v: float) -> str:
def rounds_table(rows: list[RoundRow], picked: int | None) -> Table:
- """One row per round (``select.round_rows``: a degraded verdict counts as unjudged);
- "passed" is the judge's own verdict for THAT round."""
t = Table(title="rounds (* = picked)", show_lines=False)
for col in ("#", "kind", "build", "gate err", "score", "passed", "cost", "min", "commit"):
t.add_column(col, justify="right" if col in ("#", "gate err", "score", "cost", "min") else "left")
@@ -68,8 +65,6 @@ def rounds_table(rows: list[RoundRow], picked: int | None) -> Table:
def print_record_summary(record: RunRecord, ws_root: Path | None = None) -> None:
- """The run in one panel — its stop reason, the baseline and the round ``addons/select``
- picks (never a pass or a fail: a run has none) — and a row per round."""
from codeverse3d.addons import select
spec = record.spec
@@ -92,9 +87,7 @@ def print_record_summary(record: RunRecord, ws_root: Path | None = None) -> None
lines.append(f"workspace: {ws_root}")
picked = next((r for r in record.rounds if r.index == s.round), None)
if picked is not None and picked.renders is not None and picked.renders.contact_sheet:
- # rebase, never print the stored string: record.json holds the ABSOLUTE path
- # of the host that produced the run, so a moved/archived run printed a sheet
- # that does not exist while the real one sat under this root.
+ # record.json stores absolute paths of the producing host; rebase onto this root
lines.append(f"sheet: {ws.rebase(picked.renders.contact_sheet)}")
if ws.deliverable_manifest_path.is_file():
lines.append(f"deliverable: {ws.deliverable}")
@@ -116,8 +109,7 @@ def print_observation(obs: Any, *, as_json: bool) -> None:
if as_json:
console.print_json(obs.model_dump_json())
return
- # three states, not two: a FAIL verdict is an answer the tool computed, an error is a
- # tool that could not run (the same split the MCP server reports as is_error)
+ # FAIL is a computed verdict; error is a tool that could not run
state, style = ("ok", "green") if obs.ok else (("error", "red") if obs.failed else ("FAIL", "yellow"))
console.print(Panel(obs.text, title=f"[{style}]{state}[/{style}] ({obs.duration_ms} ms)", expand=False))
if obs.numbers:
@@ -127,7 +119,6 @@ def print_observation(obs: Any, *, as_json: bool) -> None:
def doctor_table(rows: list[tuple[str, str, str]]) -> Table:
- """rows: (check, status OK|WARN|FAIL, detail)."""
t = Table(title="3dcode doctor")
t.add_column("check", style="bold")
t.add_column("status")
@@ -143,15 +134,13 @@ REPO_ROOT = Path(__file__).resolve().parents[2]
class CliError(typer.Exit):
- """Typed, already-reported failure → exit code."""
def __init__(self, message: str, code: int = 1):
err(message)
super().__init__(code=code)
-#: the evaluation lives NEXT TO the harness (``<repo>/eval``) and is never imported by it;
-#: the gallery only looks for the batteries' run directories under ``eval/bench/out``
+#: ``<repo>/eval``, never imported by the harness
EVAL_ROOT = REPO_ROOT.parent / "eval"
@@ -160,7 +149,6 @@ def runs_root(runs_dir: Path | None) -> Path:
def open_workspace(slug: str, runs_dir: Path | None = None) -> Workspace:
- """``slug`` may be a run name under runs_dir or a path to a run directory."""
p = Path(slug)
if p.is_dir() and (p / "spec.json").is_file():
return Workspace(p)
@@ -186,8 +174,8 @@ def make_slug(prompt: str, track: str, language: str, explicit: str | None = Non
@contextmanager
def mutating(target: Any, *, what: str, action: str = "enter") -> Iterator[None]:
- """The run mutex (``runlock.exclusive``) around anything that writes into a run
- directory, reported as a typed exit. ``target`` is a Workspace or a run root."""
+ """The run mutex around anything that writes into a run directory; ``target`` is a
+ Workspace or a run root."""
from codeverse3d.proc import RunLocked, exclusive
root = target if isinstance(target, (str, Path)) else target.root # NB: Path.root is "/"
@@ -201,8 +189,7 @@ def mutating(target: Any, *, what: str, action: str = "enter") -> Iterator[None]
def create_workspace(root: Path, *, force: bool) -> Workspace:
- """Create (or ``--force``-replace) a run directory. The caller holds the run mutex —
- the rmtree below would otherwise wipe a live holder's workspace."""
+ """Create (or ``--force``-replace) a run directory; the caller holds the run mutex."""
ws = Workspace(root)
if ws.root.exists() and any(ws.root.iterdir()):
if not force:
@@ -213,9 +200,7 @@ def create_workspace(root: Path, *, force: bool) -> Workspace:
def parse_kv_floats(items: list[str], flag: str) -> dict[str, float]:
- """``key=value`` pairs of positive, finite floats (``--dim``: metres). ``height=0``,
- ``-1``, ``nan``, ``inf`` and a nameless ``=1`` used to be accepted, frozen on the spec and
- handed to the planner, the contract gate and the judge as a stated dimension."""
+ """``key=value`` pairs of positive, finite floats (``--dim``: metres)."""
out: dict[str, float] = {}
for it in items:
if "=" not in it:
@@ -233,9 +218,7 @@ def parse_kv_floats(items: list[str], flag: str) -> dict[str, float]:
def check_minutes(max_minutes: float | None) -> None:
- """``--max-minutes`` must leave the run some time: 0 planned (paid), then stopped at the
- first clock check with no round — a ``budget`` run with nothing in it. ``inf``/``nan`` is no clock at
- all: the session deadline cannot be computed from it."""
+ """``--max-minutes`` must be a finite number above 0."""
if max_minutes is not None and max_minutes <= 0:
raise CliError(f"--max-minutes must be above 0 (got {max_minutes:g}): a run with no time builds nothing", code=2)
if max_minutes is not None and not math.isfinite(max_minutes):
@@ -243,11 +226,7 @@ def check_minutes(max_minutes: float | None) -> None:
def check_backends(backends: Any) -> None:
- """Refuse a backend id this build cannot construct, before a run directory exists.
-
- The ids were only resolved when a stage first asked for the model or agent, so an
- unknown ``--generator`` (``antigravity:...``, a typo) surfaced AFTER the paid plan
- stage, as a traceback and an orphan run. The parsers are the constructors' own."""
+ """Refuse a backend id this build cannot construct, before a run directory exists."""
from codeverse3d.agents.registry import parse_agent_id
from codeverse3d.models.registry import parse_model_id
from codeverse3d.tracks.generation import is_single_shot, single_shot_model_id
@@ -265,11 +244,9 @@ def check_backends(backends: Any) -> None:
raise CliError(f"--{role} {value!r}: {e}", code=2) from None
-# --------------------------------------------------------------------------- the variant (D105)
+# --------------------------------------------------------------------------- the variant
@dataclass(frozen=True)
class ResolvedVariant:
- """The prompt/skill variant a ``3dcode make`` freezes on ``RunOptions.variant``: its name
- (``""`` = base), version and overlay hash, and where the choice came from."""
name: str
version: int
@@ -278,16 +255,12 @@ class ResolvedVariant:
@property
def label(self) -> str:
- """One line for the run table: ``argon v1 (3f2a…) via --variant``, or ``base``."""
return f"{self.name} v{self.version} ({self.hash}) via {self.source}" if self.name else "base"
def resolve_variant(settings: Any | None, generator: str, flag: str | None = None) -> ResolvedVariant:
- """THE resolver for the variant (): ``--variant NAME`` (``flag``)
- over ``settings.variant`` (``C3D_VARIANT``) over ``settings.variants[<generator>]`` — the id as
- typed, then by ``<kind>:<served model>`` — over the base. An unknown name is the typed
- 'bad configuration' refusal (exit 2) BEFORE a run directory exists, never a traceback after
- the paid plan stage."""
+ """Resolve the variant: ``flag`` over ``settings.variant`` over ``settings.variants[<generator>]``
+ over the base. An unknown name is a typed refusal (exit 2)."""
from codeverse3d.prompts import variants as V
settings = settings or get_settings()
@@ -307,8 +280,6 @@ def resolve_variant(settings: Any | None, generator: str, flag: str | None = Non
def record_variant(record: RunRecord) -> str:
- """The variant a stored run used: the spec's frozen name, else what the track stamped on the record
- (``extra["variant"]["name"]`` — a run that resolved it from the process switch)."""
block = record.extra.get("variant")
stamped = str(block.get("name") or "") if isinstance(block, dict) else ""
return record.spec.options.variant or stamped
@@ -316,9 +287,7 @@ def record_variant(record: RunRecord) -> str:
@contextmanager
def replay_variant(record: RunRecord) -> Iterator[str]:
- """Activate the variant a stored run used, so a replay (``3dcode judge``) reads the prompt files the
- run read. A variant this tree no longer ships is a warning and the base prompts, never a refusal:
- the renders and gates being replayed are on disk."""
+ """Activate the variant a stored run used; an unshipped one warns and falls back to base."""
from codeverse3d.prompts.variants import activate, variant_info
name = record_variant(record)
diff --git a/harness/codeverse3d/cli/_judge.py b/harness/codeverse3d/cli/_judge.py
index 24d7b8a0..f4ce34ea 100644
--- a/harness/codeverse3d/cli/_judge.py
+++ b/harness/codeverse3d/cli/_judge.py
@@ -1,14 +1,5 @@
-"""``3dcode judge`` implementation: re-judge a round with the SAME inputs the
-in-run judge saw.
-
-The payload is ``judges.base.round_input`` — the builder the in-run judge uses — fed from
-disk: the round's renders / measurement / gates from ``rounds/rNN.json`` (fallback: the
-round inside record.json), the typed plan from record.json (else ``plan.json``), ``previous``
-the loop's (``record.previous_verdict``: round N-1's, None when it went unjudged), the track's
-``extra_context`` rebuilt from the stored gates / frame metrics, and the clay geometry views rendered for the in-run judge
-(``renders/rNN/clay/``) reattached when present. The judge class is the in-run one:
-``judges.vlm_judge.judge_for``, the rule the live run uses.
-"""
+"""``3dcode judge`` implementation: re-judge a stored round with the inputs the in-run judge
+saw, built by ``judges.base.round_input`` from the run directory."""
from __future__ import annotations
@@ -28,7 +19,6 @@ from codeverse3d.workspace import Workspace
def load_round(ws: Workspace, rec: RunRecord, index: int) -> RoundRecord | None:
- """rounds/rNN.json (written by the round loop) beats the copy in record.json."""
p = ws.root / "rounds" / f"r{index:02d}.json"
if p.is_file():
try:
@@ -39,7 +29,6 @@ def load_round(ws: Workspace, rec: RunRecord, index: int) -> RoundRecord | None:
def rubric_for(rec: RunRecord, rnd: RoundRecord, override: str | None) -> str:
- """--rubric > the rubric the round was judged with > the run's (``record.rubric_of``)."""
from codeverse3d.record.record import rubric_of
if override:
@@ -50,8 +39,7 @@ def rubric_for(rec: RunRecord, rnd: RoundRecord, override: str | None) -> str:
def stored_plan(ws: Workspace, rec: RunRecord) -> Plan | None:
- """The run's typed plan: record.json's, else ``plan.json`` read as the track's plan model
- (a run that stopped before its record was written)."""
+ """The run's typed plan: record.json's, else ``plan.json``."""
if rec.plan is not None:
return rec.plan
from codeverse3d.tracks import get_track
@@ -64,9 +52,6 @@ def stored_plan(ws: Workspace, rec: RunRecord) -> Plan | None:
def extra_context_for(ws: Workspace, rec: RunRecord, plan: Plan | None, rnd: RoundRecord) -> str:
- """The track pipeline's OWN ``judge_context`` over the stored artifacts —
- ``judge_context(ws, plan, round_index, build, gates)`` needs no run context,
- so the CLI never restates the per-track formatting."""
from codeverse3d.tracks import get_track
build = rnd.build if rnd.build is not None else BuildResult(ok=False, language=rec.spec.language.value)
@@ -77,7 +62,6 @@ def extra_context_for(ws: Workspace, rec: RunRecord, plan: Plan | None, rnd: Rou
def clay_geometry_views(ws: Workspace, index: int) -> RenderSet | None:
- """The clay views the in-run judge saw (``renders/rNN/clay/``), when present."""
d = ws.renders_dir(index) / "clay"
if not d.is_dir():
return None
@@ -87,7 +71,6 @@ def clay_geometry_views(ws: Workspace, index: int) -> RenderSet | None:
def build_judge_input(ws: Workspace, rec: RunRecord, rnd: RoundRecord) -> Any:
- """``round_input`` for a stored round (``3dcode judge``, calibration)."""
plan = stored_plan(ws, rec)
return round_input(rec.spec, plan, rnd, renders=judged_subset(resolve_paths(ws, rnd.renders)), gates=rnd.gates,
previous=previous_verdict([load_round(ws, rec, rnd.index - 1)], rnd.index), extra_context=extra_context_for(ws, rec, plan, rnd),
@@ -95,8 +78,7 @@ def build_judge_input(ws: Workspace, rec: RunRecord, rnd: RoundRecord) -> Any:
def stored_glb_path(ws: Workspace, rnd: RoundRecord) -> str | None:
- """The round's own GLB (``select.round_file``; never the canonical one, the last build's)
- — what lets ``3dcode judge`` reproduce the D48 conditional slice payload from the stored gates."""
+ """The round's own GLB (never the canonical one, which is the last build's)."""
from codeverse3d.addons.select import round_file
glb = round_file(ws, rnd)
@@ -104,8 +86,6 @@ def stored_glb_path(ws: Workspace, rnd: RoundRecord) -> str | None:
def make_judge(spec: Spec, rubric_name: str, model_id: str, n: int, **options: Any) -> Any:
- """The class the live run would use (``vlm_judge.judge_for``); ``options`` go to the
- judge (calibration's cache dir, thinking level, fixed order)."""
from codeverse3d.judges import vlm_judge
from codeverse3d.judges.rubrics import load_rubric
@@ -118,10 +98,8 @@ def make_judge(spec: Spec, rubric_name: str, model_id: str, n: int, **options: A
def count_prompt_images(inp: Any, rubric_name: str, judge: Any = None) -> int | None:
- """Number of image parts a single judge sample will send (None on failure).
-
- With ``judge`` given, its D48 slice payload is counted too, so a dirty round's
- printed count matches what the verdict call actually sends."""
+ """Number of image parts a single judge sample sends (None on failure), including
+ ``judge``'s slice payload when given."""
try:
from codeverse3d.contracts.chat import ImagePart
from codeverse3d.judges.prompt_builder import build_judge_messages
diff --git a/harness/codeverse3d/cli/cost_cmd.py b/harness/codeverse3d/cli/cost_cmd.py
index 81f686d4..45c144aa 100644
--- a/harness/codeverse3d/cli/cost_cmd.py
+++ b/harness/codeverse3d/cli/cost_cmd.py
@@ -1,4 +1,5 @@
-"""``3dcode cost`` — what the runs cost and where the money went.
+"""``3dcode cost`` — what the runs cost and where the money went, from each run's
+``telemetry/cost.jsonl`` ledger.
3dcode cost <slug> # one run, from its own ledger
3dcode cost --runs-dir eval/bench/out/x # a whole battery, aggregated
@@ -7,9 +8,6 @@
3dcode cost runs/ --recheck # re-price with today's table (drift vs what was billed)
3dcode cost prices [--stale] [--unverified]
3dcode cost estimate gemini:… --in 12000 --out 800
-
-Every run is read from its own ledger (``telemetry/cost.jsonl``) — one priced row per
-real model call; a run recorded before the ledger existed (2026-08-23) has none.
"""
from __future__ import annotations
@@ -28,13 +26,10 @@ from codeverse3d.cli._common import console, ok, runs_root, warn
STALE_AFTER_DAYS = 90
class _CostGroup(TyperGroup):
- """``3dcode cost <slug|path> ...`` — a first argument that is not a subcommand
- is forwarded to ``show`` instead of failing with "No such command"."""
+ """A first argument that is not a subcommand is forwarded to ``show``."""
def resolve_command(self, ctx: click.Context, args: list[str]): # type: ignore[override]
- # Membership test rather than catching UsageError: typer >= 0.22 vendors its
- # own click (typer._click), so the error it raises is NOT click.UsageError
- # and the except clause silently stopped matching (CI, typer 0.27).
+ # typer vendors its own click, so its UsageError is not click.UsageError: test membership
if args and not args[0].startswith("-") and args[0] not in self.commands:
return "show", self.get_command(ctx, "show"), args
return super().resolve_command(ctx, args)
@@ -50,10 +45,7 @@ def cost(
recheck: Annotated[bool, typer.Option("--recheck", help="re-price every call with today's table")] = False,
md: Annotated[Path | None, typer.Option("--md", help="also write the full markdown report here")] = None,
) -> None:
- """Cost breakdown: per stage, per role, per model, waste, $ per run.
-
- ``3dcode cost <slug>`` reports one run from its own ledger; ``--runs-dir <dir>``
- aggregates every run under a root (a bench battery)."""
+ """Cost breakdown: per stage, per role, per model, waste, $ per run."""
if ctx.invoked_subcommand is not None:
return
if runs_dir is None:
@@ -71,12 +63,11 @@ def show(
per_run: Annotated[bool, typer.Option("--per-run/--no-per-run")] = True,
runs_dir: Annotated[Path | None, typer.Option("--runs-dir", help="runs root a bare slug is resolved against")] = None,
) -> None:
- """Cost breakdown for runs named by slug or path (``3dcode cost <slug>`` lands here)."""
+ """Cost breakdown for runs named by slug or path."""
_report([_resolve(str(p), runs_dir) for p in paths], md=md, recheck=recheck, limit=limit, per_run=per_run)
def _resolve(arg: str, runs_dir: Path | None) -> Path:
- """A bare argument is a path when it exists, else a slug under the runs root."""
p = Path(arg)
if p.exists():
return p
@@ -115,11 +106,7 @@ def prices(
stale: Annotated[bool, typer.Option("--stale", help=f"only rows older than {STALE_AFTER_DAYS} days or approximate")] = False,
days: Annotated[int, typer.Option("--days", help="staleness threshold in days")] = STALE_AFTER_DAYS,
) -> None:
- """The USD price table with its provenance (source + checked date + status).
-
- A row is flagged when it was last checked more than ``--days`` ago, when the
- price is marked approximate, or when its status is not ``verified`` — those
- are the dollars an audit cannot stand behind."""
+ """The USD price table with its provenance; flags stale, approximate or unverified rows."""
from codeverse3d.models.pricing import PRICES, price_provenance
rows, flagged = [], 0
@@ -178,8 +165,7 @@ def cache(
paths: Annotated[list[Path], typer.Argument(help="run slugs or run dirs")],
runs_dir: Annotated[Path | None, typer.Option("--runs-dir")] = None,
) -> None:
- """Did prompt caching actually happen? Per session: the cold first call, the
- cached share, the dollars the cache saved and the dollars the cold head cost."""
+ """Did prompt caching happen? Per session: cold first call, cached share, dollars saved."""
from codeverse3d.addons.costreport.caching import session_cache
from codeverse3d.cost.ledger import load_ledger
diff --git a/harness/codeverse3d/cli/flywheel_cmd.py b/harness/codeverse3d/cli/flywheel_cmd.py
index 9198adb3..95b4217c 100644
--- a/harness/codeverse3d/cli/flywheel_cmd.py
+++ b/harness/codeverse3d/cli/flywheel_cmd.py
@@ -29,18 +29,15 @@ def export_cmd(
captions_dir: Annotated[Path | None, typer.Option("--captions-dir", help="side-car captions written by `caption --out`")] = None,
drop_duplicates: Annotated[bool, typer.Option("--drop-duplicates", help="leave byte-identical duplicates (raw code sha256 + prompt) out of the index, manifest and tars (recorded under the manifest's dropped); normalised ones are only marked near_duplicate_of")] = False,
) -> None:
- """Export runs → sample folders + dataset_manifest.json + metadata.jsonl/.parquet
- (+ optional plain tars, packed FROM the manifest)."""
+ """Export runs → sample folders + dataset_manifest.json + metadata.jsonl/.parquet (+ tars)."""
from codeverse3d.addons.dataset.export import export_samples
if pack:
- # pack_samples rewrites the index and reads it back with pyarrow, so --pack
- # cannot degrade the way a plain export can. Say so BEFORE the first sample is
- # written rather than after a few hundred, with a raw ModuleNotFoundError.
+ # --pack reads the index back with pyarrow: fail before the first sample is written
try:
import pyarrow # noqa: F401
except ImportError:
- # escaped: rich reads "[flywheel]" as markup and would print the tag away
+ # escaped: rich reads "[flywheel]" as markup
raise C.CliError(escape("--pack needs the flywheel extra: "
"pip install -e 'harness[flywheel]'")) from None
@@ -119,12 +116,10 @@ def caption_cmd(
if not force and load_captions(ws, rec, out, slug=slug).get("detailed"):
skipped += 1
continue
- # PER RUN: captioning rewrites record.json (--out writes a side-car instead and
- # touches nothing), and a locked run is skipped with a warning — one live run must
- # not abort a --all batch of hundreds
+ # per run: captioning rewrites record.json (--out writes a side-car instead); a locked
+ # run is skipped so one live run does not abort an --all batch
lock = nullcontext() if out else exclusive(ws.root, what=f"3dcode flywheel caption {ws.root.name}")
try:
- # the priced captioner call joins the run's ledger (as `3dcode judge` does)
with lock, run_ledger(ws.root, run=ws.root.name, create=False):
caps = caption_sample(ws, rec, model, out_dir=out, slug=slug)
except (CaptionError, RunLocked) as e:
diff --git a/harness/codeverse3d/cli/inspect_cmd.py b/harness/codeverse3d/cli/inspect_cmd.py
index 44228880..3a03999f 100644
--- a/harness/codeverse3d/cli/inspect_cmd.py
+++ b/harness/codeverse3d/cli/inspect_cmd.py
@@ -1,12 +1,5 @@
-"""``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
-the graphics-track frame copy, and the ``judge`` re-judge that
-writes ``artifacts/judge/rNN_cli.json`` (default: the round ``addons/select`` picks). The
-single-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
-dispatch), ``mcp`` and the registration of every command.
-"""
+"""``3dcode render`` / ``3dcode judge`` — act on one existing run: re-render its working
+tree, or re-judge a round into ``artifacts/judge/rNN_cli.json``."""
from __future__ import annotations
@@ -46,31 +39,26 @@ def render(
spec = C.load_spec(ws)
if mode not in RENDER_MODES:
raise C.CliError(f"--mode must be one of {' | '.join(RENDER_MODES)}, not {mode!r}", code=2)
- if mode != "shaded" and spec.track in (Track.SCENE, Track.GRAPHICS): # was silently rendered shaded
+ if mode != "shaded" and spec.track in (Track.SCENE, Track.GRAPHICS):
raise C.CliError(f"--mode {mode} is for object runs; a {spec.track.value} run renders shaded only", code=2)
- if spec.track is Track.GRAPHICS and (width or height): # the frames are the runtime's size: dropped silently
+ if spec.track is Track.GRAPHICS and (width or height):
raise C.CliError("--width/--height do not apply to a graphics run: its frames are rendered at the runtime's size",
code=2)
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 dir
+ # a graphics render rebuilds the run: one writer per run dir
with C.mutating(ws, what=f"3dcode render {ws.root.name}", action="render"):
if spec.track is Track.GRAPHICS:
_render_graphics(ws, spec, out_dir)
return
- # the size settings are honoured by the in-run renders (tracks/static_object.py,
- # tracks/scene.py) and were silently dropped by the one command whose whole job is
- # rendering, so a CLI render did not match the one the judge saw
r = get_settings().render
if spec.track is Track.SCENE:
from codeverse3d.languages import get_runtime
from codeverse3d.spatial.tool_common import load_plan
from codeverse3d.tracks.scene import SCENE_TIMES
- # the in-run rig (tracks/scene.ScenePipeline.render): the plan's cameras at the judged
- # times — not the cameras createScene() authored, which the judge never saw on their own
plan = load_plan(ws.plan_path) if ws.plan_path.is_file() else None
- rs = get_runtime(spec.language).render_scene( # a scene language's runtime is a SceneRuntime (D101)
+ rs = get_runtime(spec.language).render_scene(
ws, out_dir, cameras=list(plan.cameras) if isinstance(plan, ScenePlan) else None,
times=SCENE_TIMES, width=width or r.scene_width, height=height or r.scene_height)
else:
@@ -108,9 +96,7 @@ def judge(
] = None,
runs_dir: RunsDirOpt = None,
) -> None:
- """Re-judge a round with the SAME inputs as the in-run judge (renders + measurement +
- gates + acceptance + plan digest + previous verdict + stored clay views); writes
- artifacts/judge/rNN_cli.json."""
+ """Re-judge a round with the same inputs as the in-run judge; writes artifacts/judge/rNN_cli.json."""
from codeverse3d.addons import select
from codeverse3d.cli import _judge as J
from codeverse3d.record.record import RecordError, join_post_run, load_record
@@ -120,7 +106,6 @@ def judge(
rec = load_record(ws)
except RecordError as e:
raise C.CliError(str(e), code=2) from e
- # the round `pick` packaged (selection.json), else the best-scored one, else select.fallback_round
idx = round_index if round_index is not None else select.summarise(ws.root, record=rec).round
if idx is None:
raise C.CliError(f"no round of {ws.root.name} built with renders: nothing to judge (--round N names one)")
@@ -128,30 +113,24 @@ def judge(
if rnd is None or rnd.renders is None or not rnd.renders.views:
raise C.CliError(f"round {idx} has no renders (rounds/r{idx:02d}.json / record.json)")
rubric_name = J.rubric_for(rec, rnd, rubric)
- with C.replay_variant(rec): # the run's prompt/skill overlay (D105): the replay reads what the run read
+ with C.replay_variant(rec):
inp = J.build_judge_input(ws, rec, rnd)
- # an archived run keeps its sheet but may have pruned the per-view PNGs: say so, instead of
- # the judge's own FileNotFoundError / JudgeImageError escaping as a traceback
missing = [v.path for v in inp.renders.views if not Path(v.path).is_file()]
if missing:
raise C.CliError(f"round {idx}: {len(missing)} of its {len(inp.renders.views)} judged renders are not on disk "
f"(e.g. {missing[0]}): nothing to re-judge it from", code=2)
- # --thinking is a replay knob (D105): the level reaches the judge as its own, else the settings'
try:
judge_obj = J.make_judge(rec.spec, rubric_name, model or rec.spec.backends.judge, n,
**({"thinking": thinking} if thinking else {}))
- except ValueError as e: # an unknown thinking level
+ except ValueError as e:
raise C.CliError(str(e), code=2) from e
n_images = J.count_prompt_images(inp, rubric_name, judge_obj)
- # writes artifacts/judge/rNN_cli.json into the run: one writer per run dir; the verdict is built
- # under the run's variant, like its inputs above
+ # writes into the run: one writer per run dir; judged under the run's variant
with C.mutating(ws, what=f"3dcode judge {ws.root.name}", action="judge"), C.replay_variant(rec):
try:
- # a re-judge joins the run's ledger (and its record's total) when it has one; otherwise
- # the per-process log (a ledger holding only this verdict would be read as the whole run's cost)
with join_post_run(ws):
verdict = judge_obj.judge(inp)
- except ValueError as e: # e.g. a measured rubric fed to a judge that computes nothing
+ except ValueError as e:
raise C.CliError(f"judge failed: {e}") from e
except Exception as e:
from codeverse3d.judges.vlm_judge import ReferenceJudgeError
@@ -169,7 +148,7 @@ def judge(
"overall": f"{verdict.overall:.3f}",
"passed": verdict.passed,
"std": verdict.score_std,
- "thinking": getattr(judge_obj, "thinking", "-"), # a judge class of its own may carry none
+ "thinking": getattr(judge_obj, "thinking", "-"),
"prompt images": n_images if n_images is not None else "?",
"stored score": f"{rnd.judgment.overall:.3f}" if rnd.judgment else "-",
"summary": verdict.summary,
@@ -182,7 +161,6 @@ def judge(
def _render_graphics(ws, spec: Spec, out_dir: Path) -> None:
- """Graphics runs have no GLB: regenerate the judged frames + sheet via the runtime."""
import shutil
from codeverse3d.languages import get_runtime
diff --git a/harness/codeverse3d/cli/layout_cmd.py b/harness/codeverse3d/cli/layout_cmd.py
index 4fe950e1..5be815e3 100644
--- a/harness/codeverse3d/cli/layout_cmd.py
+++ b/harness/codeverse3d/cli/layout_cmd.py
@@ -1,16 +1,6 @@
-"""``3dcode show`` — THE single-run view, in four sections:
-
-* **STATUS** — where the run stands: the run, the rounds, the process holding the run
- lock, run_state, best-of-N candidates, the latest events. It needs no
- record.json, so it works mid-run; ``3dcode status`` is ``show --section status``;
-* **DELIVERABLE** — what the run produced and where to find it;
-* **QUALITY EVIDENCE** — why we believe it is good (score, rubric, gates, acceptance);
-* **COST & SETTINGS** — tokens and dollars per stage, model ids, thinking levels,
- rubric hash, budget vs spent, wall clock.
-
-Works on the new layout and on runs written before it: the cost / settings block
-is computed on the fly when ``telemetry/`` is not there yet.
-"""
+"""``3dcode show`` — the single-run view: STATUS (works mid-run, without record.json;
+``3dcode status`` is ``show --section status``), DELIVERABLE, QUALITY EVIDENCE and
+COST & SETTINGS."""
from __future__ import annotations
@@ -55,8 +45,6 @@ def _section(title: str) -> None:
# --------------------------------------------------------------------------- status
def print_status(ws: Workspace, record: RunRecord | None, n_events: int) -> None:
- """Where the run stands. Needs no record.json: a run in flight shows its spec, its lock
- holder, run_state and the latest events."""
from codeverse3d.proc import EventLog, holder_of, read_json_or_none
_section("STATUS — where the run stands")
@@ -68,7 +56,7 @@ def print_status(ws: Workspace, record: RunRecord | None, n_events: int) -> None
"prompt": spec.prompt, "track": spec.track.value, "language": spec.language.value,
"generator": spec.backends.generator, "judge": spec.backends.judge, "workspace": ws.root}))
state: dict[str, Any] = {}
- if (held := holder_of(ws.root)) is not None: # kill THAT pid, never `pkill -f 3dcode`
+ if (held := holder_of(ws.root)) is not None:
state["RUNNING NOW"] = f"pid {held.get('pid', '?')} ({held.get('what') or '3dcode'})"
if ws.state_path.is_file():
raw = read_json_or_none(ws.state_path)
@@ -106,8 +94,6 @@ MAX_ROWS_PER_ROLE = 6
def _deliverable_table(d: RunDeliverable) -> Table:
- """One row per file, except roles with many files (frame stacks, link meshes,
- a multi-file source tree) which collapse into a single counted row."""
t = Table(title="files (deliverable/)", show_lines=False)
for col in ("role", "path", "size"):
t.add_column(col, justify="right" if col == "size" else "left")
@@ -126,7 +112,6 @@ def _deliverable_table(d: RunDeliverable) -> Table:
def _unpackaged_artifact_rows(ws: Workspace) -> dict[str, Any]:
- """A run not yet packaged: show physical artifacts instead of ``deliverable/``."""
rows: dict[str, Any] = {}
for name in ("object.glb", "object.stl", "object.step", "robot.urdf", "preview.gif"):
p = ws.artifacts / name
@@ -164,7 +149,7 @@ def print_evidence(ws: Workspace, record: RunRecord) -> None:
_section("QUALITY EVIDENCE — why we believe it")
s = select.summarise(ws.root, record=record)
- rnd = next((r for r in record.rounds if r.index == s.round), None) # the pick, else select.fallback_round
+ rnd = next((r for r in record.rounds if r.index == s.round), None)
j = effective_judgment(rnd) if rnd is not None else None
gates = gate_error_summary(rnd)
rows: dict[str, Any] = {
@@ -178,11 +163,7 @@ def print_evidence(ws: Workspace, record: RunRecord) -> None:
rows["acceptance"] = f"{sum(1 for v in acc.values() if v)}/{len(acc)} met" if acc else "-"
rows["judge summary"] = j.summary[:300]
if rnd is not None and rnd.renders is not None and rnd.renders.contact_sheet:
- # rebase, never print the stored string: record.json holds the ABSOLUTE path the
- # renderer wrote, so an archived / rsynced / moved run made `3dcode show` print a
- # sheet under the ORIGINAL root — a path that is not there, next to an object.glb
- # that resolved correctly (it is recomputed from the workspace), which is what
- # made the breakage silent and partial. ``_fmt`` does the same for `3dcode status`.
+ # record.json stores absolute paths of the producing host; rebase onto this root
rows["contact sheet"] = ws.rebase(rnd.renders.contact_sheet)
if rnd is not None and rnd.measurement is not None:
mm = rnd.measurement
@@ -224,7 +205,7 @@ def print_cost_and_settings(ws: Workspace, record: RunRecord) -> None:
tele = load_telemetry(ws, record)
computed = False
if tele is None or tele.cost is None:
- tele = build_telemetry(ws, record, write=False) # incomplete telemetry: compute without writing
+ tele = build_telemetry(ws, record, write=False)
computed = True
cost, settings = tele.cost, tele.settings
if cost is not None:
diff --git a/harness/codeverse3d/cli/main.py b/harness/codeverse3d/cli/main.py
index 3fcdf113..a186d541 100644
--- a/harness/codeverse3d/cli/main.py
+++ b/harness/codeverse3d/cli/main.py
@@ -1,14 +1,5 @@
-"""``3dcode`` — the 3dcodeverse command line.
-
-Thin by design: every command builds typed inputs and calls into the harness
-packages through function-local imports, so ``3dcode --help`` loads none of them.
-
-Owns the typer app and every registration, the run-starting commands ``make`` /
-``resume`` (spec building, track dispatch, budget raising, and the
-hand-over after the run), ``pick`` and ``mcp``. ``render`` / ``judge`` live in the sibling
-``cli/inspect_cmd.py``, the single-run view ``show`` (and its ``status`` alias) in
-``cli/layout_cmd.py``; all are registered here.
-"""
+"""``3dcode`` — the command line: the typer app, every registration, and ``make`` /
+``resume`` / ``pick`` / ``mcp``. Commands import the harness lazily so ``--help`` stays fast."""
from __future__ import annotations
@@ -121,7 +112,7 @@ def resolve_roots(roots: list[Path] | None) -> list[Path]:
raise C.CliError("not a directory: " + ", ".join(str(m) for m in missing))
return [Path(r) for r in roots]
found = default_roots(Path.cwd())
- seen = {p.resolve() for p in found} # D77: the batteries live in <repo>/eval/bench/out/<b>/runs
+ seen = {p.resolve() for p in found}
found += [p for p in sorted((C.EVAL_ROOT / "bench" / "out").glob("*/runs")) if p.is_dir() and p.resolve() not in seen]
if not found:
fallback = Path(get_settings().runs_dir)
@@ -213,9 +204,7 @@ app.command(
def _root(
ctx: typer.Context, version: Annotated[bool, typer.Option("--version", is_eager=True)] = False
) -> None:
- # `kill -USR1 <pid>` dumps every thread's stack to stderr (the run log): the
- # 2026-08-28 scope_tj_r3 hang (futex wait, every socket CLOSE-WAIT, 41 min past
- # its window) was undiagnosable without it — py-spy needs ptrace rights WSL denies.
+ # `kill -USR1 <pid>` dumps every thread's stack to stderr (py-spy needs ptrace, which WSL denies)
if hasattr(signal, "SIGUSR1") and sys.__stderr__ is not None:
# best-effort: a captured stderr (CliRunner's StringIO) has no fileno
with contextlib.suppress(Exception):
@@ -226,11 +215,7 @@ def _root(
if ctx.invoked_subcommand is None:
console.print(ctx.get_help())
raise typer.Exit()
- # Build the settings HERE so a bad configuration value is one typed error instead of a
- # raw traceback out of whichever command happened to touch get_settings() first: the app
- # runs with pretty_exceptions_enable=False, and `C3D_PROFILE=bogus` used to dump a
- # Python stack from every command — including `3dcode doctor`, the one you would run to
- # find out what is wrong with your configuration.
+ # build the settings here so a bad value is one typed error, not a traceback from any command
try:
get_settings()
except ValueError as e:
@@ -321,7 +306,7 @@ def make(
) -> None:
"""Create a run (workspace + spec.json) and execute the track pipeline."""
image, dim, must, must_not, tag = image or [], dim or [], must or [], must_not or [], tag or []
- if not prompt.strip(): # a blank prompt was planned, generated and judged as is
+ if not prompt.strip():
raise C.CliError("the prompt is empty: say what to build", code=2)
C.check_minutes(max_minutes)
for p in image:
@@ -329,7 +314,7 @@ def make(
raise C.CliError(f"reference image not found: {p}")
from PIL import Image, UnidentifiedImageError
- try: # a file that is no image reached the planner and the provider, and failed there
+ try:
with Image.open(p) as im:
im.verify()
except (UnidentifiedImageError, OSError, SyntaxError) as e:
@@ -340,15 +325,13 @@ def make(
settings = get_settings()
if candidates is None:
candidates = settings.default_candidates
- if candidates > 1 and not TRACK_INFO[track].best_of_n: # the same rule for best-of-N
+ if candidates > 1 and not TRACK_INFO[track].best_of_n:
raise _no_best_of_n(track)
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` too
+ # resolved once here and frozen on the spec
chosen = C.resolve_variant(settings, backends.generator, variant)
- # validate the whole Spec BEFORE touching the filesystem: an invalid
- # track/language combination must not leave an orphan run directory behind.
+ # validate the whole Spec before touching the filesystem (no orphan run directory)
try:
spec = Spec(
id=run_slug,
@@ -371,9 +354,7 @@ def make(
)
except ValueError as e:
raise C.CliError(f"invalid run spec: {e}") from e
- # THE run mutex, taken BEFORE the workspace is created (or --force wipes one) and
- # held through the run itself: everything below mutates
- # this run directory, and two 3dcode on one slug corrupt each other (runlock.py).
+ # the run mutex: taken before the workspace is created (or --force wipes one), held through the run
with C.mutating(C.runs_root(runs_dir) / run_slug, what=f"3dcode make {run_slug}", action="create"):
ws = C.create_workspace(C.runs_root(runs_dir) / run_slug, force=force)
ws.write_json(ws.spec_path, spec)
@@ -412,11 +393,9 @@ def _run_track(spec: Spec, ws, *, resume: bool, candidates: int | None = None, f
from codeverse3d.proc import install_stop_handlers
from codeverse3d.tracks import get_track
- install_stop_handlers() # a stop signal kills the run's agent / build trees too
+ install_stop_handlers()
options: dict = {"n_candidates": candidates} if candidates else {}
try:
- # already inside the run mutex (make / resume take it); every model call and
- # agent session of this run lands in telemetry/cost.jsonl
with run_ledger(ws.root, run=ws.root.name):
record = get_track(spec.track, **options).run(spec, ws, resume=resume, force=force)
except KeyboardInterrupt:
@@ -428,17 +407,15 @@ def _run_track(spec: Spec, ws, *, resume: bool, candidates: int | None = None, f
from codeverse3d.tracks.lifecycle import SpecChanged
if isinstance(e, SpecChanged):
- # a refusal with instructions, not a crash: no traceback, and the run
- # itself was never entered (reconcile_resume raises before any stage)
raise C.CliError(str(e), code=2) from None
- if isinstance(e, StateCorrupt): # raised before any stage, like SpecChanged
+ if isinstance(e, StateCorrupt):
raise C.CliError(f"{e} — unreadable run state; move run_state.json aside and resume from the "
f"round journal (rounds/)", code=2) from None
err_console.print_exception(max_frames=8)
raise C.CliError(
f"run failed: {type(e).__name__}: {e} (workspace {ws.root}; see events.jsonl)"
) from e
- if pick: # the hand-over: the best-scored round → deliverable/
+ if pick:
with run_ledger(ws.root, run=ws.root.name):
_pick_and_package(ws, by="score")
print_record_summary(record, ws.root)
@@ -448,7 +425,7 @@ def _run_track(spec: Spec, ws, *, resume: bool, candidates: int | None = None, f
def _pick_and_package(ws, *, by: str, round_index: int | None = None,
judge_model: str | None = None) -> int | None:
- """``codeverse3d.addons.select``: choose the round (or take ``round_index``) and package it."""
+ """Choose the round (or take ``round_index``) and package it."""
from codeverse3d.addons import select
idx = round_index if round_index is not None else select.pick(ws.root, by=by, pairwise_model=judge_model)
@@ -466,15 +443,8 @@ def _pick_and_package(ws, *, by: str, round_index: int | None = None,
def _finished_reason(ws, raised: dict) -> str:
"""Why this run must not be re-entered, or "" when resuming it is meaningful.
- A run that reached a terminal state has nothing to resume, and re-entering it is
- destructive, not idempotent: `3dcode resume` on a finished run re-ran the plan stage
- as a real billed model call and rewrote run_state.status back to 'planning', leaving
- a finished run stuck mid-pipeline. Two stops are the documented exceptions — raising
- the cap a run stopped on is how you continue it: BUDGET (any raised cap) and
- MAX_ROUNDS (a raised ``--rounds``; the run goes on from its last round). The stops
- that name something outside the run — AGENT_QUOTA (the vendor's limit) and
- JUDGE_UNAVAILABLE (the judge's provider) — resume as they are: the loop re-judges the
- unjudged last round and goes on, where ``--force`` would have thrown every paid round away.
+ A finished run is refused (re-entering re-runs the paid plan stage), except BUDGET and
+ MAX_ROUNDS stops whose cap was raised, and AGENT_QUOTA / JUDGE_UNAVAILABLE stops.
"""
from codeverse3d.contracts.run import RunStatus
from codeverse3d.orchestrator import RunState, StateCorrupt
@@ -482,7 +452,7 @@ def _finished_reason(ws, raised: dict) -> str:
try:
state = RunState.load(ws)
except StateCorrupt:
- return "" # let the track report it the way it always has
+ return ""
if state is None:
return ""
status = state.status
@@ -498,10 +468,7 @@ def _finished_reason(ws, raised: dict) -> str:
def _clock_spent(ws, max_minutes: float) -> str:
- """Why a resume would stop before doing anything, or "": the run's clock (the budget snapshot's
- ACTIVE minutes, which a resume — ``--force`` included — keeps counting) is already at the cap.
- Resumed anyway, a plain resume stopped at `budget` at once, and ``--force`` first archived every
- paid round and then did so (live, 2026-09-23)."""
+ """Why a resume would stop at once, or "": the active minutes (kept across ``--force``) are at the cap."""
from codeverse3d.orchestrator import BudgetSnapshot, RunState, StateCorrupt
try:
@@ -542,15 +509,10 @@ def resume(
] = False,
no_pick: Annotated[bool, typer.Option("--no-pick", help="do not pick + package a round afterwards")] = False,
) -> None:
- """Resume an interrupted / partial run (or start a `--no-run` one).
-
- ``--max-minutes`` / ``--rounds`` rewrite the spec's budget
- first — the only way to continue a BUDGET-stopped run. A run that already
- reached a terminal state is refused unless ``--force``, which archives its rounds
- (``rounds/pre_force/``) and starts it again at round 0 — paid, and a new final state."""
+ """Resume an interrupted / partial run (or start a `--no-run` one); a finished run needs --force."""
C.check_minutes(max_minutes)
ws = C.open_workspace(slug, runs_dir)
- # the run mutex, before the spec is rewritten (a budget raise is a mutation)
+ # the run mutex, before the spec is rewritten
with C.mutating(ws, what=f"3dcode resume {ws.root.name}"):
spec = C.load_spec(ws)
if candidates and candidates > 1 and not TRACK_INFO[spec.track].best_of_n:
@@ -594,11 +556,10 @@ def pick(
if by not in ("score", "pairwise"):
raise C.CliError(f"--by must be score or pairwise, not {by!r}", code=2)
- if judge and (by != "pairwise" or round_index is not None): # no pairwise verdict is bought: it was dropped
+ if judge and (by != "pairwise" or round_index is not None):
raise C.CliError("--judge is the pairwise judge: it goes with --by pairwise (and no --round)", code=2)
ws = C.open_workspace(slug, runs_dir)
- # writes deliverable/ + selection.json (a pairwise verdict is paid):
- # one writer per run dir, and the money joins the run's ledger
+ # writes deliverable/ + selection.json: one writer per run dir
with (C.mutating(ws, what=f"3dcode pick {ws.root.name}", action="pick"),
run_ledger(ws.root, run=ws.root.name, create=False)):
try:
@@ -621,7 +582,7 @@ app.command()(judge)
# --------------------------------------------------------------------------- mcp
@app.command()
def mcp(workspace: Annotated[Path, typer.Option("--workspace")]) -> None:
- """Serve the spatial tools over stdio MCP (exec `python -m codeverse3d.spatial.mcp_server`)."""
+ """Serve the spatial tools over stdio MCP."""
if not workspace.is_dir():
raise C.CliError(f"workspace not found: {workspace}")
os.execvp(
diff --git a/harness/codeverse3d/cli/skills_cmd.py b/harness/codeverse3d/cli/skills_cmd.py
index 7e4f9e41..6d88df43 100644
--- a/harness/codeverse3d/cli/skills_cmd.py
+++ b/harness/codeverse3d/cli/skills_cmd.py
@@ -1,10 +1,4 @@
-"""``3dcode skills`` — look at the library, validate it, and read the read-rate.
-
-``report`` is the command that matters. The whole system exists because a tool that
-exists is not a tool that gets used (the former ``read_cookbook`` tool: 0 of 16 zone sessions), so the
-first question about any battery is not "did the score move" but "did anyone open the
-file". Everything else here is plumbing for that answer.
-"""
+"""``3dcode skills`` — list and validate the skill library, and report how often agents read it."""
from __future__ import annotations
@@ -31,21 +25,14 @@ def _root(ctx: typer.Context) -> None:
def list_skills(
routes: Annotated[bool, typer.Option("--routes", help="show the rules that can attach each skill")] = False,
) -> None:
- """Every bundle in the library, with its evidence label, body size and its ONE claim.
-
- ``target`` is the deterministic quantity the bundle says it moves (docs/SKILLS_LEDGER.md);
- ``dir`` is the direction that counts as an improvement, and a ``?`` marks a bundle whose
- claim no deterministic instrument can see. Read them out with
- ``python eval/bench/skill_targets.py eval/bench/out``.
- """
+ """Every bundle in the library, with its evidence label, body size and its one claim."""
from rich.table import Table
from codeverse3d.addons.skill_targets import target_for
from codeverse3d.skills import iter_skills
from codeverse3d.skills.registry import ROUTED_SKILLS, ROUTES
- # the base library, then every shipped variant's overlay (D105): an overlay row is labelled with
- # its variant, and under --routes it lists the overlay's own [[route]] rows beside the base table
+ # the base library, then every shipped variant's overlay (rows labelled by variant)
roots = _roots()
found = [(root, s) for root in roots for s in iter_skills(root.path)]
overlay_rows = {root.variant: _overlay_routes(root.variant) for root in roots if root.variant}
@@ -95,19 +82,17 @@ def validate(
from codeverse3d.skills.model import SkillError, parse_skill
from codeverse3d.skills.registry import ROUTED_SKILLS
- # every root a run can route from: the base library, then each shipped variant's overlay (D105) —
- # an overlay bundle is routed the moment its variant is active, so a malformed one fails HERE,
- # labelled `<variant>/<bundle>`, instead of being skipped from a session with a logged warning
+ # every root a run can route from, so a malformed overlay bundle fails here as `<variant>/<bundle>`
roots = _roots()
total = bad = tables_bad = 0
base_names: set[str] = set()
- unshipped: list[str] = [] # overlay rows that route a bundle no root ships
+ unshipped: list[str] = []
for root in roots:
dirs = bundle_dirs(root.path)
total += len(dirs)
for d in dirs:
issues = validate_bundle(d)
- with contextlib.suppress(SkillError): # a parse failure is already reported above
+ with contextlib.suppress(SkillError):
issues += check_claims(parse_skill(d))
if issues:
bad += 1
@@ -126,7 +111,7 @@ def validate(
console.print(f"[{style}]{root.variant}/routes.toml: {len(orphans)} row(s) route a bundle "
f"nobody ships:[/] {', '.join(orphans)}")
unshipped += orphans
- prompt_issues = check_prompt_claims() # the prompt corpus's pinned numbers, the same check
+ prompt_issues = check_prompt_claims()
for i in prompt_issues:
console.print(f"[red]FAIL[/] prompts/_claims.toml - {i}")
missing = [n for n in ROUTED_SKILLS if n not in base_names]
@@ -140,8 +125,7 @@ def validate(
def _roots() -> list:
- """Every root the library ships (``skills.shipped_roots``); a shipped ``variant.toml`` that does not
- parse is reported and exits 1 rather than tracing back."""
+ """Every root the library ships; a ``variant.toml`` that does not parse is reported and exits 1."""
from codeverse3d.skills import shipped_roots
try:
@@ -152,8 +136,7 @@ def _roots() -> list:
def _overlay_routes(variant: str) -> tuple:
- """A variant's own ``[[route]]`` rows for the ``--routes`` column; a table that does not type-check
- is said once here and listed as empty (``skills validate`` is where it fails)."""
+ """A variant's ``[[route]]`` rows for the ``--routes`` column; an invalid table lists as empty."""
from codeverse3d.skills import variants_table
try:
@@ -164,8 +147,7 @@ def _overlay_routes(variant: str) -> tuple:
def _check_table(root, available: set[str]) -> tuple[int, list[str]]:
- """One overlay's ``routes.toml``: ``(1 if it does not type-check else 0, the rows whose skill no root
- ships as ``RULE -> skill``)``. The failure is printed here, FAIL-labelled by the variant."""
+ """One overlay's ``routes.toml``: ``(1 if invalid else 0, rows routing a skill no root ships)``."""
from codeverse3d.skills import variants_table
try:
@@ -181,18 +163,7 @@ def report(
runs_dir: Annotated[Path, typer.Argument(help="a runs root, a bench out dir, or one workspace")],
as_json: Annotated[bool, typer.Option("--json")] = False,
) -> None:
- """Deep-read rate per skill and per backend — the number that replaces "0 of 16".
-
- Target from the design: >= 60% deep-read rate for a CLI backend. A skill
- under 20% over 20 sessions is merged or deleted.
-
- Sessions measured by atime whose CONTROL bundle was also "read" are counted separately
- and excluded from the rate: git's own diff and every CLI's skill activation both bump
- atime, so in those sessions the probe saw nothing it can attribute to the agent
- (docs/SKILLS.md section 4). Sessions measured from the CLI's own tool calls
- (``evidence: transcript``, 2026-09-22) are exact and always counted; one whose agent
- opened the control is reported, not dropped.
- """
+ """Deep-read rate per skill and per backend; atime sessions that also "read" the control are excluded."""
from rich.table import Table
from codeverse3d.contracts.run import SkillsUsage
@@ -200,7 +171,7 @@ def report(
from codeverse3d.skills.telemetry import SKILLS_FILE, TELEMETRY_DIR
rows: list[dict] = []
- for p in unique_files(runs_dir, SKILLS_FILE, subruns=True): # a symlinked cell once; candidates' sessions too
+ for p in unique_files(runs_dir, SKILLS_FILE, subruns=True):
if p.parent.name == TELEMETRY_DIR:
rows.extend(read_jsonl_lenient(p))
if not rows:
@@ -209,7 +180,7 @@ def report(
per: dict[tuple[str, str], list[int]] = {}
- def _blind(r: dict) -> bool: # the probe saw nothing: SkillsUsage.deep_read_rate says None
+ def _blind(r: dict) -> bool:
u = SkillsUsage.model_validate(r)
return bool(u.listed) and u.deep_read_rate is None
@@ -219,7 +190,7 @@ def report(
no_control = sum(1 for r in rows if not r.get("control_present"))
for r in rows:
if _blind(r):
- continue # the probe was blind here; counting it would lie
+ continue
backend = str(r.get("agent", "?")).split(":", 1)[0]
reads = {x["name"]: x for x in r.get("reads", [])}
for name in r.get("listed", []):
diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.py
index 93bd70e8..e839dce8 100644
--- a/harness/codeverse3d/config.py
+++ b/harness/codeverse3d/config.py
@@ -4,13 +4,11 @@ Resolution order (later wins): built-in defaults < ``~/.config/3dcodeverse/confi
< ``./3dcodeverse.yaml`` < environment variables (``C3D_*``). Secrets are never
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).
+Gemini keys: ``GEMINI_API_KEYS`` (csv), ``GEMINI_API_KEY`` or ``~/.config/astra3d/gemini_keys.env``.
-One switch grammar: every ``C3D_*`` knob the harness reads is a field here, read through
-``get_settings()`` at the call that uses it — no module reads the environment by hand. A
-field ``x`` is ``C3D_X`` (a nested ``section.x`` is ``C3D_SECTION__X``, plus the flat
-spellings in :data:`Settings.FLAT`); an on/off switch is a :data:`Flag`.
+Every ``C3D_*`` knob is a field here, read through ``get_settings()``. A field ``x`` is
+``C3D_X`` (nested ``section.x`` is ``C3D_SECTION__X``, plus :data:`Settings.FLAT`); an on/off
+switch is a :data:`Flag`.
"""
from __future__ import annotations
@@ -48,8 +46,6 @@ log = logging.getLogger(__name__)
def _or_default(value: Any, handler: ValidatorFunctionWrapHandler, info: ValidationInfo) -> Any:
- """A switch that does not parse warns and keeps its DEFAULT (D44 c): a typo in a bench
- command runs the arm that never set it — not a crash mid-battery, and not the variant."""
try:
return handler(value.strip() if isinstance(value, str) else value)
except ValidationError:
@@ -57,15 +53,12 @@ def _or_default(value: Any, handler: ValidatorFunctionWrapHandler, info: Validat
raise PydanticUseDefault() from None
-#: an on/off switch: on/off, 1/0, true/false, yes/no (any case, t/f and y/n too); anything
-#: else warns and keeps the field's default
+#: an on/off switch (on/off, 1/0, true/false, yes/no); anything else keeps the default
Flag = Annotated[bool, WrapValidator(_or_default)]
-#: a switch that is a count (>= 0); anything else warns and keeps the field's default
Count = Annotated[int, Field(ge=0), WrapValidator(_or_default)]
-#: THE supported Blender: 5.2 LTS (owner, 2026-10-14 — developed and measured on 5.2.2; 4.2 / 5.0
-#: compatibility was dropped, D104). ``3dcode doctor`` fails anything older.
+#: the supported Blender (5.2 LTS); ``3dcode doctor`` fails anything older.
BLENDER_MIN: tuple[int, int] = (5, 2)
@@ -78,8 +71,6 @@ class Binaries(BaseModel):
class Agents(BaseModel):
- """Knobs for the CLI-backed coding agents (the subscription CLIs)."""
-
codex_reasoning_effort: str = Field(
default="high",
description="`-c model_reasoning_effort=` passed to every `codex:` call (agent and one-shot). "
@@ -103,13 +94,9 @@ class Render(BaseModel):
"the node side reads too)")
sheet_cols: int = 4
sheet_tile: int = 384
- # scene_blender pictures (spatial/render_blender.py, owner D1/D8 2026-09-24; the 5.2.2 fast path D104,
- # 2026-10-14). Measured on this box (RTX 5090, Blender 5.2.2 LTS, 1024x576, 460 objects): Cycles
- # CUDA 32 spp + GPU OIDN 0.64 s/frame, 0.21 s/frame once persistent data keeps the synced scene
- # between the cameras of one job (8 frames 5.3 s → 2.2 s); 64 spp 0.69 s, 128 spp 0.86 s; CPU 2.3 s
- # at 32 spp. EEVEE in background is SLOWER here: 5.2 s/frame + a 12 s shader compile per process,
- # GPU only under the Mesa d3d12 env (spatial/gl_render.GPU_ENV) — without it EEVEE silently lands
- # on llvmpipe (10x). OptiX is unavailable under WSL2 (and probing it crashes Blender): CUDA only.
+ # scene_blender pictures (spatial/render_blender.py). Cycles CUDA + GPU OIDN is the fast path;
+ # EEVEE needs the Mesa d3d12 env (spatial/gl_render.GPU_ENV) or lands on llvmpipe.
+ # OptiX is unavailable under WSL2 and probing it crashes Blender: CUDA only.
blender_engine: Annotated[Literal["cycles", "eevee"], BeforeValidator(lambda v: str(v).strip().lower())] = Field(
default="cycles", description="judged-frame engine for scene_blender (C3D_RENDER__BLENDER_ENGINE)")
blender_frame_time_limit_s: float = Field(
@@ -134,13 +121,8 @@ class Limits(BaseModel):
render_timeout_s: int = 300
agent_timeout_s: int = AGENT_TIMEOUT_S
bpy_rlimit_gb: int = 12
- # Both measured, not guessed (docs/COST.md Part III). These size the
- # *subprocess* side (blender / node / chrome), which is bound by cores — 24
- # here — and NOT by the provider: the model-call ceiling is Rate.max_in_flight.
- # 32 concurrent blender builds of a recorded model.py peaked at 16 workers
- # (1 392 builds/min; 24 workers gave 1 168, 32 gave 1 019), so a fan-out of 12
- # agent tasks x their own builds stays inside the knee and leaves cores for the
- # render pass, whose tail is minutes long.
+ # These size the subprocess side (blender / node / chrome, bound by cores); the model-call
+ # ceiling is Rate.max_in_flight.
max_parallel_agents: int = Field(default=12, ge=1, description="thread fan-out for agent tasks (>= 1)")
max_parallel_builds: int = Field(default=8, ge=1, description="concurrent build subprocesses (>= 1)")
agent_max_turns: Count = Field(
@@ -153,25 +135,16 @@ class Limits(BaseModel):
class Rate(BaseModel):
- """The model-call ceiling and the 503 hedge (``docs/COST.md`` Part III).
-
- ``max_in_flight`` is a MACHINE-WIDE ceiling on the harness's own concurrent model calls
- (flock'd slot files under ``<cache_dir>/slots/``, shared by every process — COST §23)
- and is deliberately separate from ``Limits.max_parallel_agents`` /
- ``max_parallel_builds``: blender / node / chrome are CPU-bound and sized by cores, model
- calls are network-bound and sized by the provider. 0 = unlimited. A vendor CLI
- session takes a key from the pool but no slot. There is no RPM / TPM quota here any more:
- since the api-agent went the harness's own calls peaked at 2.6 % of one key's RPM
- and 3.9 % of its TPM, so the buckets they fed never engaged (COST §19).
+ """The model-call ceiling and the 503 hedge.
+
+ ``max_in_flight`` is machine-wide (flock'd slot files under ``<cache_dir>/slots/``), separate
+ from the core-bound ``Limits`` fan-outs. 0 = unlimited. A vendor CLI session takes a key
+ but no slot.
"""
max_in_flight: int = Field(
default=96,
- ge=0, # NEGATIVE is not "unlimited" here: 0 is. Without this bound -5 survived config,
- # was reported as FITTING the pool budget by `3dcode doctor`, poisoned the shared
- # in-flight accounting, and finally died as a bare ValueError from
- # threading.BoundedSemaphore inside KeyPool -- at the first model call, long
- # after the workspace and spec.json were written.
+ ge=0, # negative is not "unlimited" (0 is); a negative would poison the slot accounting
description="machine-wide cap on concurrent model calls (0 = off): every process draws "
"from the same N slot files, so the machine never exceeds the largest N any process runs "
"with. Measured knee: a 128-call burst of 12k-token prompts ran 29.6 calls/min at 16 "
@@ -189,8 +162,6 @@ class Rate(BaseModel):
class Judge(BaseModel):
- """Judge payload size — what one verdict is allowed to send (docs/COST.md §3)."""
-
max_px: int = Field(default=1024, description="longest edge of a montage / crop sent to the judge")
montages: int = Field(default=5, description="max 2x2 montages per verdict (14-view rig, D47)")
detail_crops: int = Field(default=2, description="max zoomed detail crops per verdict")
@@ -210,13 +181,9 @@ class Judge(BaseModel):
class Placement(BaseModel):
- """The scene_placement gate's thresholds (spatial/scene_placement.py), metres / fractions. Settings
- fields so a per-model variant or an A/B can tighten them and the record names what a run used.
- The defaults are the STRICT standards the owner asked for on 2026-10-14 (D105; the 2026-09
- calibration was floating ERROR 0.15 m / > 3, sunk ERROR 0.30 m + 25 %, overlap WARN 0.20 /
- ERROR 0.60): a 8 cm hover, a 20 cm burial or a 35 % box overlap is an ERROR now, and a
- 10 % overlap is reported. The JS measurement (host_placement.mjs) keeps its own CONTACT /
- FLOATING / SUNK constants: these decide severities only."""
+ """The scene_placement gate's thresholds (spatial/scene_placement.py), metres / fractions.
+ The JS measurement (host_placement.mjs) keeps its own CONTACT / FLOATING / SUNK constants:
+ these decide severities only."""
contact_m: float = Field(default=0.02, ge=0, description="foot within this of a surface = seated")
floating_outdoor_m: float = Field(default=0.05, ge=0, description="gap above which an outdoor asset floats")
@@ -233,14 +200,10 @@ class Placement(BaseModel):
class Settings(BaseSettings):
- # env_ignore_empty: ``C3D_X=`` is unset, never "" (an empty C3D_CACHE_DIR was the cwd)
model_config = SettingsConfigDict(env_prefix="C3D_", env_nested_delimiter="__", extra="ignore",
env_ignore_empty=True)
- #: Nested knobs that also have a flat spelling — the name the docs, the node side and the
- #: A/B commands type. ``C3D_MAX_IN_FLIGHT=16`` went into three launch commands on
- #: 2026-08-24 before anyone noticed only ``C3D_RATE__MAX_IN_FLIGHT`` was read. The flat
- #: one wins when both are set; the nested field validates it.
+ #: nested knobs with a flat spelling; the flat one wins
FLAT: ClassVar[dict[str, tuple[str, str]]] = {
"C3D_MAX_IN_FLIGHT": ("rate", "max_in_flight"),
"C3D_RENDER_GPU": ("render", "gpu"),
@@ -250,9 +213,7 @@ class Settings(BaseSettings):
@classmethod
def settings_customise_sources(cls, settings_cls: Any, init_settings: Any, env_settings: Any,
dotenv_settings: Any, file_secret_settings: Any) -> tuple[Any, ...]:
- """``C3D_*`` beats the yaml files (``get_settings`` passes those as init kwargs, which
- pydantic-settings ranks FIRST): a switch in a config file must never override the
- environment an A/B arm runs under."""
+ """``C3D_*`` beats the yaml files (passed as init kwargs, which would otherwise rank first)."""
return env_settings, init_settings, dotenv_settings, file_secret_settings
@model_validator(mode="before")
@@ -280,8 +241,6 @@ class Settings(BaseSettings):
openai_api_key: str = ""
openai_base_url: str = ""
- # Backend-role defaults: the literals live in ONE place — contracts/common.py::Backends
- # (which also documents why the judge default is the pro tier).
default_planner: str = Field(default_factory=lambda: Backends().planner)
default_generator: str = Field(default_factory=lambda: Backends().generator)
default_judge: str = Field(default_factory=lambda: Backends().judge)
@@ -297,11 +256,8 @@ class Settings(BaseSettings):
"a 55 800-token plan needs ~930 s and died at the socket, its tokens billed and discarded. "
"Owner's rule 2026-08-27: time may be generous, errors may not.")
- # Per-model prompt/skill variants (D105, 2026-10-14): an overlay directory
- # codeverse3d/prompts/variants/<name>/ (prompt files that shadow the base ones) plus
- # codeverse3d/skills/variants/<name>/ (bundles that shadow base bundles, routes.toml with
- # boosts). Chosen EXPLICITLY — by name, or by an exact generator-id lookup — never by a
- # regex over the model id (Law 4). `3dcode make --variant` freezes the choice on the spec.
+ # Per-model prompt/skill variants: overlays under prompts/variants/<name>/ and
+ # skills/variants/<name>/, chosen by name or exact generator id, never by regex.
variant: str = Field(default="", description="prompt/skill variant for every run of this process "
"(C3D_VARIANT; a name under codeverse3d/prompts/variants/); '' = base")
variants: dict[str, str] = Field(default_factory=dict, description="exact generator id → variant name, "
@@ -310,9 +266,7 @@ class Settings(BaseSettings):
"`variant` is empty, by the id as typed and then by '<kind>:<served model>'")
# ------------------------------------------------------------------ switches
- # The A/B switches and runtime overrides, each read as C3D_<NAME> at the call that uses
- # it. An A/B arm is a child process with its own environment (eval/bench/ab_plan.py), and
- # tracks/plan_features.py derives which C3D_* names are live from these fields.
+ # tracks/plan_features.py derives the live C3D_* names from these fields.
skills: Flag = Field(default=True, description="route, materialise and measure skill bundles "
"(D81, on since 2026-09-22); C3D_SKILLS=0 is an A/B's no-skills arm")
skills_max: Count = Field(
@@ -345,9 +299,6 @@ class Settings(BaseSettings):
# ------------------------------------------------------------------ helpers
def backends(self, **overrides: str | None) -> Backends:
- """The ``Backends`` for a new Spec from the settings defaults. Keyword
- overrides (``planner`` / ``generator`` / ``judge`` / ``captioner``) win
- when truthy; ``None`` / ``""`` falls through to the default."""
base: dict[str, str] = {
"planner": self.default_planner,
"generator": self.default_generator,
@@ -363,8 +314,7 @@ class Settings(BaseSettings):
return Backends(**base)
def resolve_blender(self) -> str:
- """The configured binary (a path or a name on PATH), else the first Blender on PATH. A
- configured one that is not there is "none", never a silent substitute for it."""
+ """The configured binary, else the first Blender on PATH; a configured-but-missing one is ``""``."""
if self.binaries.blender:
return shutil.which(self.binaries.blender) or ""
for cand in ("blender-5.2", "blender"):
@@ -374,11 +324,7 @@ class Settings(BaseSettings):
return ""
def runtime_js_dir(self) -> Path:
- """The Node runtime (runtime_js/) — repo-relative in an editable install.
-
- ``C3D_RUNTIME_JS`` overrides the location (the wheel does not package
- runtime_js, so a non-editable install MUST point this at a checkout).
- Missing dir → a loud error at first use instead of a cryptic node crash."""
+ """The Node runtime dir; ``C3D_RUNTIME_JS`` overrides it (required for a non-editable install)."""
d = self.runtime_js.expanduser() if self.runtime_js else Path(__file__).resolve().parent.parent / "runtime_js"
if not d.is_dir():
raise RuntimeError(
@@ -389,9 +335,7 @@ class Settings(BaseSettings):
def _load_yaml(path: Path) -> dict:
- """A config file's mapping; a file that is not one is a ``ValueError`` naming it (the CLI
- reports that as a bad configuration — a YAML syntax error or a top-level list used to
- escape every command as a raw traceback)."""
+ """A config file's mapping; anything else is a ``ValueError`` naming the file."""
if not path.is_file():
return {}
try:
@@ -405,7 +349,6 @@ def _load_yaml(path: Path) -> dict:
def _legacy_gemini_keys() -> list[str]:
- """Read ``GEMINI_API_KEYS`` from the owner's astra3d keys file (csv, quoted)."""
if not _LEGACY_KEYS_FILE.is_file():
return []
m = re.search(r'GEMINI_API_KEYS="?([^"\n]+)"?', _LEGACY_KEYS_FILE.read_text())
@@ -424,16 +367,6 @@ def _env_gemini_keys() -> list[str]:
def _deep_merge(base: dict, overlay: dict) -> dict:
- """Recursive dict merge — ``overlay`` wins per SETTING, not per section.
-
- ``dict.update`` replaced a whole sub-dict, so a project ``./3dcodeverse.yaml`` that
- merely NAMED a section silently dropped every sibling key the user had set in
- ``~/.config/3dcodeverse/config.yaml`` — those keys fell back to the built-in Field
- defaults, not to the user's values (2026-08-24: a user's per-key TPM quota was lost to
- a project file that set only the in-flight cap). docs/INSTALL.md §8.3 documents the
- order as "built-in defaults < user config < project config < env", which every reader
- takes as per-setting.
- """
out = dict(base)
for k, v in overlay.items():
if isinstance(v, dict) and isinstance(out.get(k), dict):
@@ -445,7 +378,6 @@ def _deep_merge(base: dict, overlay: dict) -> dict:
@lru_cache(maxsize=1)
def get_settings() -> Settings:
- """Build the singleton Settings (cached; call ``get_settings.cache_clear()`` in tests)."""
data: dict = {}
for p in (_USER_CONFIG, Path("3dcodeverse.yaml")):
data = _deep_merge(data, _load_yaml(p))
diff --git a/harness/codeverse3d/contracts/artifacts.py b/harness/codeverse3d/contracts/artifacts.py
index 321917ee..ad4f2751 100644
--- a/harness/codeverse3d/contracts/artifacts.py
+++ b/harness/codeverse3d/contracts/artifacts.py
@@ -19,8 +19,7 @@ class Severity(StrEnum):
class LintKind(StrEnum):
- """``data.kind`` of a ``lint:<language>`` finding — what routes a skill (``skills.registry``)
- and what a cap rule's ``kinds`` are matched against. One vocabulary for every lint."""
+ """``data.kind`` of a ``lint:<language>`` finding: routes skills and matches cap rules."""
SYNTAX = "syntax" # the file does not parse
MISSING_FILE = "missing_file" # an entry / planned part file is absent
@@ -43,9 +42,8 @@ class LintKind(StrEnum):
CENSUS = "census" # INFO: what the lint saw
-#: ``GateFinding.data["kind"]`` of a plan part that is still the skeleton's placeholder box
-#: (``spatial.contract``, D110) — the one gate ERROR the next refine round puts ahead of every
-#: other (``orchestrator.build_refine_instructions``): nothing else about a part matters until it exists
+#: ``GateFinding.data["kind"]`` of a plan part that is still the skeleton's placeholder box;
+#: the next refine round puts it ahead of every other gate error.
PLACEHOLDER_PART = "placeholder_part"
@@ -65,10 +63,7 @@ class GateFinding(BaseModel):
with_target: bool = False,
with_hint: bool = True,
) -> str:
- """One presentation line for prompts/reports — no leading ``- `` (callers
- own their list bullets). ``message`` is always present; the flags opt in
- to a ``GATE <gate>:`` prefix, a ``[<severity>]`` tag, a `` [<target>]``
- suffix and the `` FIX: <fix_hint>`` suffix (default on, when non-empty)."""
+ """One line for prompts/reports, no leading bullet; the flags opt in to prefix/tag/suffix parts."""
parts: list[str] = []
if with_gate:
parts.append(f"GATE {self.gate}:")
@@ -101,8 +96,6 @@ class GateReport(BaseModel):
class BuildResult(BaseModel):
- """Result of executing the raw code and exporting the canonical artifact."""
-
ok: bool
language: str
glb_path: str | None = None
@@ -155,9 +148,7 @@ class Measurement(BaseModel):
extra: dict[str, Any] = Field(default_factory=dict)
-#: every mode the object rig draws (runtime_js/render_glb.mjs MODES, pinned by
-#: tests/spatial_tools/test_tools.py). The tool layer advertised "depth" from the
-#: first commit; no renderer ever had it.
+#: every mode the object rig draws (runtime_js/render_glb.mjs MODES)
RENDER_MODES = ("shaded", "wire", "normals", "silhouette", "clay")
@@ -225,8 +216,7 @@ class Judgment(BaseModel):
@property
def degraded(self) -> bool:
- """A judge glitch (an outage, an unparseable verdict), never a score: its 0.0 must not
- reach a pick or a refine plan (``judges.rubrics.degraded_judgment`` writes one)."""
+ """A judge glitch (outage, unparseable verdict), never a score: must not reach a pick or refine plan."""
if self.summary.startswith("judge_error:"):
return True
try:
diff --git a/harness/codeverse3d/contracts/chat.py b/harness/codeverse3d/contracts/chat.py
index 7b7b242c..b9b616fa 100644
--- a/harness/codeverse3d/contracts/chat.py
+++ b/harness/codeverse3d/contracts/chat.py
@@ -48,11 +48,7 @@ class ChatRequest(BaseModel):
system: str = ""
response_schema: dict[str, Any] | None = Field(default=None, description="force JSON matching this schema")
temperature: float = 0.7
- #: 65 536 is the declared output limit of every gemini-3.x model the harness uses
- #: (models.get: input 1 048 576 / output 65 536). It is a CEILING, not a reservation —
- #: only tokens actually produced are billed — and a low one silently truncates a
- #: thinking model mid-answer: a 15 359-token thought hit the old 16 000 default at
- #: 15 996 and the turn arrived with no tool call (art_med_tool_chest, 2026-08-27).
+ #: A ceiling, not a reservation: a low one truncates a thinking model mid-answer.
max_output_tokens: int = 65_536
thinking: Literal["off", "low", "medium", "high"] = "low"
label: str = Field(default="", description="for logs/cost ledger: planner / judge / generate ...")
diff --git a/harness/codeverse3d/contracts/common.py b/harness/codeverse3d/contracts/common.py
index 7466333d..3858348a 100644
--- a/harness/codeverse3d/contracts/common.py
+++ b/harness/codeverse3d/contracts/common.py
@@ -43,11 +43,7 @@ TRACK_LANGUAGES: dict[Track, tuple[Language, ...]] = {
class TrackInfo(BaseModel):
- """Per-track registry row: default judge rubric + human label.
-
- THE single source for what used to be restated as ``TRACK_RUBRIC`` /
- ``RUBRIC_BY_TRACK`` / ``TYPE_LABEL`` in judges, flywheel and cli.
- """
+ """Per-track registry row: default judge rubric + human label."""
model_config = ConfigDict(frozen=True)
@@ -68,7 +64,6 @@ TRACK_INFO: dict[Track, TrackInfo] = {
}
#: entry file inside the workspace per language — the file a build starts from.
-#: THE single source for entry paths (runtimes' first entry_glob, flywheel export).
ENTRY_FILE: dict[Language, str] = {
Language.BLENDER: "src/model.py",
Language.CADQUERY: "src/model.py",
@@ -80,17 +75,9 @@ ENTRY_FILE: dict[Language, str] = {
Language.OPENGL_PYTHON: "src/program.py",
}
-#: source files the HARNESS writes under ``src/`` and owns: the agent reads them and calls what
-#: they define, never writes them (``AgentJob.read_only`` — the agent's write scope excludes them).
-#: Measured 2026-08-26 (eval/bench/out/seed_v1, aurora brief): helpers seeded into the agent's own
-#: ``src/common.glsl`` were gone by the end of the run — it rewrote the file — so a seeded file has
-#: to be one the agent cannot rewrite. (glsl_shader's seeded ``src/recipes.glsl`` went with the
-#: recipe seeding, D107.) An entry ending in ``/`` is a DIRECTORY prefix: every file under it is
-#: owned — the effect library is named without listing every path; an entry without one is an
-#: exact file (no language ships one since D107; the rule stays for the next seeded file, and
-#: ``tests`` exercise it on a synthetic entry).
+#: source files the HARNESS writes under ``src/``: the agent reads and calls them, never writes them.
+#: An entry ending in ``/`` is a directory prefix; otherwise an exact file.
HARNESS_OWNED_SRC: dict[Language, tuple[str, ...]] = {
- # the effect library (D51): the agent imports and calls it, never rewrites it.
Language.SCENE_THREEJS: ("src/lib/",),
}
@@ -116,8 +103,7 @@ LANGUAGE_LABEL: dict[Language, str] = {
def code_file(language: Language) -> str:
- """Top-level flywheel copy of the entry file: ``code`` + the entry suffix
- (``code.py`` / ``code.js`` / ``code.frag``)."""
+ """Top-level flywheel copy of the entry file: ``code`` + the entry suffix."""
entry = ENTRY_FILE[language]
return "code" + entry[entry.rfind(".") :]
@@ -150,18 +136,10 @@ class Usage(BaseModel):
class Budget(BaseModel):
- """Hard ceilings for a run. The orchestrator stops (cleanly) when any is hit.
-
- The ceilings are non-negative by construction. A negative one is not a small
- budget, it is an unrunnable one: ``BudgetGuard.ok()`` is False before a single
- token is spent and ``grant_grace`` cannot lift a hard ceiling back above zero —
- so the workspace and the git-committed spec are created for a run that can only die.
-
- A run is bounded by ``max_rounds`` and ``max_minutes``. Cost is accumulated per call
- for the ledger and the run record, and never gates anything.
+ """Hard ceilings for a run (rounds, minutes); the orchestrator stops cleanly when one is hit.
- ``extra="forbid"``: a caller still passing a retired ceiling (``max_usd``) or a typo
- must raise, not be silently swallowed, including when loading a stored spec.
+ Ceilings are non-negative by construction (a negative one is an unrunnable budget).
+ Cost is recorded but never gates anything. ``extra="forbid"`` makes unknown keys raise.
"""
model_config = ConfigDict(extra="forbid")
@@ -179,24 +157,18 @@ class Backends(BaseModel):
* Coding agents: ``agy:gemini-4-argon`` (``-low``/``-medium``/``-high``; Gemini models only) · ``claude-code:sonnet``
· ``codex:gpt-6.1-sol``
- The coding agent is always a VENDOR agent: the harness supplies the workspace, the
- prompt and its 3D tools (over MCP) and reads the result. The in-process
- ``api-agent`` tool loop was deleted 2026-08-28 — reimplementing agent plumbing the
- vendors already ship was never this project's job (owner's call).
+ The coding agent is always a vendor agent: the harness supplies the workspace, prompt
+ and 3D tools (over MCP) and reads the result.
"""
planner: str = "gemini:gemini-4-argon"
generator: str = "agy:gemini-4-argon"
- # The judge drives the refine loop: the pro tier has ~3x lower sample noise than
- # flash (calibration 2026-08-23: std 0.03 vs 0.08-0.12) for ~$0.07 per verdict.
judge: str = "gemini:gemini-3.1-pro-preview"
captioner: str = "gemini:gemini-4-argon"
# ------------------------------------------------------------------ joint coupling
-#: |multiplier| below this is a coupling that transmits no motion. ONE value: the plan
-#: validator used 1e-9 while the URDF loader and lint used 1e-12, so a coupling the
-#: planner was forbidden to write was one the loader accepted.
+#: |multiplier| below this is a coupling that transmits no motion (shared by plan, lint and loader).
MIMIC_MIN_MULTIPLIER = 1e-9
@@ -235,13 +207,8 @@ class MimicIssue(BaseModel):
def mimic_issues(specs: Collection[MimicSpec]) -> list[MimicIssue]:
"""Every rule a ``<mimic>`` has to satisfy, checked once over the whole joint set.
- Three layers reject the same bad couplings — ``ArticulatedPlan._check_mimics``,
- ``languages/urdf.lint`` and ``spatial.joints_model.load_urdf`` — and they had three
- copies of the walk that disagreed on the multiplier floor. The rules live here; each
- caller renders the issues in its own vocabulary (``ValueError`` / gate finding /
- ``UrdfError``), picks the first one when it reports only one, and decides what is
- fatal: ``out_of_range`` is a warning in the lint and ignored by the loader, because
- the coupling still poses the mechanism — the follower's own limits are what disagree.
+ Callers render the issues in their own vocabulary and decide what is fatal
+ (``out_of_range`` is only a warning: the coupling still poses the mechanism).
"""
order = list(specs)
by_key = {s.key: s for s in order}
@@ -280,12 +247,9 @@ def mimic_issues(specs: Collection[MimicSpec]) -> list[MimicIssue]:
def _driven_range(follower: MimicSpec, driver: MimicSpec) -> tuple[float, float] | None:
- """Where the coupling actually takes ``follower`` when both declare limits, if that
- is outside the follower's own — ``None`` when it fits or the limits are unknown.
+ """Where the coupling takes ``follower`` if outside its own limits, else ``None``.
- Slack is 1 % of the follower's span: the one case in 94 recorded couplings
- (wave2_lean, a folding brace) overshot 2.248 against 2.2, which is the multiplier and
- the limit rounded from different numbers rather than a mechanism that jams.
+ Slack is 1 % of the follower's span, absorbing multiplier/limit rounding.
"""
if None in (follower.lower, follower.upper, driver.lower, driver.upper):
return None
diff --git a/harness/codeverse3d/contracts/plan.py b/harness/codeverse3d/contracts/plan.py
index 607bcef6..74caeb95 100644
--- a/harness/codeverse3d/contracts/plan.py
+++ b/harness/codeverse3d/contracts/plan.py
@@ -1,11 +1,7 @@
-"""Plans: the planner's structured decomposition. Every plan carries an
-*acceptance checklist* — concrete, verifiable items derived from the spec —
-so acceptance can be mechanical (evidence), not an opinion.
+"""Plans: the planner's structured decomposition, each with an acceptance checklist.
-Plans are written by an LLM under a JSON schema and then VALIDATED IN CODE
-(unit axes, single-root joint trees, sane limits, unique names). Invalid
-plans are re-asked with the validation errors, before any generator runs.
-"""
+Written by an LLM under a JSON schema, then validated in code; invalid plans are re-asked
+with the validation errors."""
from __future__ import annotations
@@ -24,16 +20,13 @@ from codeverse3d.contracts.common import (
)
from codeverse3d.conventions import to_snake
-#: a thinking model's self-reference leaked into structured output: measured 2026-08-28
-#: (gear_cq_ss), the PLANNER emitted a part literally named "Gemini25FlashThinking" and
-#: the generator faithfully modelled a placeholder pillar for it — judged 0.0. High-
-#: precision patterns only: "CameraFlash" or "ModelStand" must stay legal.
+#: model ids / placeholders that leak into part names. High-precision patterns only:
+#: "CameraFlash" or "ModelStand" must stay legal.
_MODEL_NAME_LEAK = re.compile(r"(?i)(gemini|gpt[-_ ]?\d|claude|llama|qwen|deepseek|placeholder)")
def reject_model_leak(v: str) -> str:
- """Reject (never mangle) part names that are model ids / placeholders — the planner
- is re-asked with this error, exactly like an unsafe camera name."""
+ """Reject (never mangle) part names that are model ids / placeholders."""
m = _MODEL_NAME_LEAK.search(v)
if m:
raise ValueError(
@@ -69,17 +62,13 @@ class AcceptanceItem(BaseModel):
priority: Literal["must", "should"] = "must"
-#: how far a sub-part may stick out of its parent's bbox before the plan is rejected:
-#: ``max(SUBPART_SLACK_M, SUBPART_REL_SLACK × parent extent)`` per axis. Planner boxes are
-#: design intent, not measurements, so the check catches "this child is somewhere else
-#: entirely", never a 3 mm rounding.
+#: how far a sub-part may stick out of its parent's bbox: ``max(SUBPART_SLACK_M,
+#: SUBPART_REL_SLACK × parent extent)`` per axis (planner boxes are design intent).
SUBPART_SLACK_M = 0.01
SUBPART_REL_SLACK = 0.15
-#: A ``revolute`` range over 2π whose limits both sit inside ±``DEGREES_MAX_ABS`` and whose span is
-#: at least ``DEGREES_MIN_SPAN`` was written in DEGREES (door ``0..90``, lid ``-180..0``): 30 rad is
-#: nearly five turns, which no hinge is planned in. A span between 2π and 30 (``0..4π``, ``0..6.5``,
-#: ``0..10``) is read as radians — an implausible hinge either way — and becomes ``continuous``
-#: (``ArticulatedPlan._normalise_raw``).
+#: A ``revolute`` range over 2π with both limits inside ±``DEGREES_MAX_ABS`` and a span of at
+#: least ``DEGREES_MIN_SPAN`` is read as degrees; a smaller span over 2π is radians and becomes
+#: ``continuous``.
DEGREES_MAX_ABS = 360.0
DEGREES_MIN_SPAN = 30.0
@@ -224,9 +213,7 @@ class JointPlan(BaseModel):
if self.type == "prismatic" and (self.upper - self.lower) > 5.0:
raise ValueError(f"joint {self.name}: prismatic range > 5 m is implausible")
if to_snake(self.parent) == to_snake(self.child):
- # name BOTH sides: pydantic truncates the offending value right after the
- # joint name, so "parent == child" was all the model ever saw, and it rewrote
- # the same joint through every re-ask (7 runs lost that way, 2026-09-03).
+ # name BOTH sides: pydantic truncates the offending value after the joint name.
same = "" if self.parent == self.child else (
f" ('{self.parent}' and '{self.child}' are the same name once normalised)")
raise ValueError(
@@ -274,41 +261,23 @@ class ArticulatedPlan(StaticPlan):
@model_validator(mode="before")
@classmethod
def _normalise_raw(cls, data: object) -> object:
- """Repair the three planner mistakes that failed validation twice on compare_art_v2
- (2026-08-25: 5 of 14 articulated prompts, a third of the harness's losses) — each is
- a schema-shaped slip a re-ask did not fix, not a design decision worth a run.
-
- 1. a joint whose ``parent`` / ``child`` names a SUB-PART: the sub-part is promoted to a
- top-level part (``attach_to`` = its former parent) — anything a joint moves is a link;
- 2. a ``revolute`` joint whose range exceeds 2π: with both limits inside ±360 and a span of
- at least 30 the planner wrote DEGREES (door ``0..90``, lid ``-180..0`` — the template says
- rad), so the limits and a ``rest`` inside them are converted with ``math.radians`` and the
- joint stays ``revolute``; any other span over 2π (``0..4π``, ``-4π..4π``) becomes
- ``continuous`` (limits dropped). The band 2π < span < 30 (``0..6.5``, ``0..10``) is
- ambiguous and is read as radians: a wrong ``continuous`` there is what the run got before,
- while a wrong degrees reading would squeeze a full turn into a 6° hinge without a trace.
- A converted range that is still over 2π (``-360..360``) falls through to ``continuous``;
- 2b. swapped or out-of-range limits: ``upper < lower`` is written as the swap it is
- (a hinge "from 90 to 0"), and a ``rest`` outside ``[lower, upper]`` is clamped to
- the nearer limit — both killed cs37_urdf_02 at the planner (2026-08-29, 3.7-flash)
- after two re-asks, and neither is a design decision worth a dead run;
- 3. a sub-part sticking out of its parent's bbox by more than the slack: the parent bbox
- grows to enclose it (planner boxes are design intent, not measurements).
- 4. a ``root_link`` that names no part but loosely matches exactly ONE (af_excavator
- 2026-08-31, 3.7-flash: ``root_link: chassis`` over a part list that spelt it
- differently — two re-asks did not fix it and the run died at the planner): the
- root is rewritten to that part. Zero or several candidates still raise.
- Every repair is recorded in ``normalisations`` so the record shows what the planner
- actually wrote. Anything else still fails validation and is re-asked.
+ """Repair schema-shaped planner slips that are not design decisions:
+
+ 1. a joint naming a sub-part promotes it to a top-level part;
+ 1b/1c. a joint naming a part or sub-part by a unique fragment is resolved;
+ 2. revolute limits written in degrees become radians; other ranges over 2π become ``continuous``;
+ 2b. swapped limits are swapped back, an out-of-range ``rest`` is clamped;
+ 3. a sub-part outside its parent's bbox grows the parent;
+ 4. a ``root_link`` naming no part is rewritten when exactly one part matches.
+
+ Every repair is recorded in ``normalisations``; anything else fails validation.
"""
if not isinstance(data, dict):
return data
data = dict(data)
parts = [dict(p) for p in (data.get("parts") or []) if isinstance(p, dict)]
joints = [dict(j) for j in (data.get("joints") or []) if isinstance(j, dict)]
- # harness-only: the planner is told to leave this empty, and one did not (articulated_v2
- # scissor_mirror, 2026-08-26: two lines of design prose landed here) — a planner's text
- # would read as a harness repair in the record, so incoming values are dropped
+ # harness-only field: any incoming value is dropped
notes: list[str] = []
if not parts or not joints:
return data
@@ -332,10 +301,7 @@ class ArticulatedPlan(StaticPlan):
kept.append(child)
part["children"] = kept
- # 1b. a joint that names a link by a UNIQUE fragment of a real part ("Lid" for
- # "ChestLid"): a naming slip, not a design decision. Measured 2026-08-27
- # (art_med_tool_chest, 3.6-flash): 'joint LidHinge references unknown link(s)
- # Carcass/Lid' three times in a row, killing the run at the planner with 0 rounds.
+ # 1b. a joint naming a link by a unique fragment of a real part ("Lid" for "ChestLid")
known = set(by_name)
for j in joints:
for side in ("parent", "child"):
@@ -348,14 +314,8 @@ class ArticulatedPlan(StaticPlan):
j[side] = by_name[hits[0]].get("name")
notes.append(f"joint {j.get('name')}.{side} '{raw_name}' resolved to the one part it names: {j[side]}")
- # 1c. a joint that names a SUB-PART by a fragment (af_grandfather_clock 2026-08-31,
- # 3.7-flash: everything nested under clock_case, the joint said GlazedDoor, the child
- # spelt it longer — the exact-match promotion above missed it, 1b searches top-level
- # links only, and the re-ask complaint listed top-level parts only, so both re-asks
- # died the same way). Sub-part names are longer and decorated, so the affix rule is
- # too weak here: the match is WORD-SUBSET (every word of the reference appears in the
- # candidate's words — {glazed,door} ⊆ {glazed,front,door}; "arm" still never matches
- # "alarm"). A unique hit promotes the child and rewrites the joint side.
+ # 1c. a joint naming a sub-part by a fragment: WORD-SUBSET match ({glazed,door} within
+ # {glazed,front,door}; "arm" never matches "alarm"); a unique hit is promoted.
sub_index: dict[str, tuple[dict, dict]] = {}
for part in list(parts):
for child in part.get("children") or []:
@@ -459,16 +419,14 @@ class ArticulatedPlan(StaticPlan):
names = {to_snake(p.get("name", "")): p.get("name") for p in parts if p.get("name")}
rk = to_snake(root)
if rk not in names:
- # same word-boundary rule as repair 1b, never bare substring ("arm" != "alarm")
+ # word-boundary rule as in 1b, never bare substring
hits = [orig for k, orig in names.items()
if rk in k.split("_") or k.endswith(f"_{rk}") or k.startswith(f"{rk}_")]
if len(hits) == 1:
notes.append(f"root_link '{root}' named no part; rewrote to '{hits[0]}'")
data["root_link"] = hits[0]
elif not hits:
- # 4b. nothing even loosely matches (a UUID, prose — ab_repairs
- # grand_piano 2026-08-29, three plans in a row): the one part no
- # joint names as a child is the root; unique → unambiguous
+ # 4b. nothing matches: the one part no joint names as a child is the root
children = {to_snake(str(j.get("child", ""))) for j in joints}
roots = [orig for k, orig in names.items() if k not in children]
if len(roots) == 1:
@@ -513,9 +471,7 @@ class ArticulatedPlan(StaticPlan):
return self
def _check_mimics(self) -> None:
- """Every declared coupling must name a joint that exists, moves, and does not lead
- back to the joint that follows it — the rules are ``common.mimic_issues`` so the
- plan, the lint and the URDF loader cannot drift apart."""
+ """Every coupling must name a joint that exists, moves, and does not loop (``common.mimic_issues``)."""
by_name = {j.name: j for j in self.joints}
issues = mimic_issues([
MimicSpec(key=to_snake(j.name), name=j.name, movable=j.type != "fixed",
@@ -526,8 +482,7 @@ class ArticulatedPlan(StaticPlan):
follower = by_name.get(i.joint)
wanted = follower.mimic.joint if follower is not None and follower.mimic else i.target
if i.kind == "out_of_range":
- continue # the plan does not reject a coupling for overshooting a limit;
- # the lint warns (contracts.common._driven_range says why)
+ continue # only the lint warns about overshooting a limit
raise ValueError({
"immobile": f"joint {i.joint}: a fixed joint cannot mimic {wanted}",
"zero_multiplier": f"mimic of {wanted}: multiplier 0 means the joint cannot move; use type=fixed",
@@ -548,17 +503,15 @@ class ZonePlan(BaseModel):
contents: list[str] = Field(default_factory=list, description="asset names placed in this zone")
-#: the asset kinds each scene language plans (D5): ``bpy`` = a procedural module of a Blender
-#: scene (``src/assets/<snake>.py``), ``threejs`` its three.js twin, ``blender_glb`` a hero built as
-#: an object and shipped as a GLB (both languages)
+#: the asset kinds each scene language plans: ``bpy`` / ``threejs`` = a procedural module,
+#: ``blender_glb`` = a hero built as an object and shipped as a GLB
SCENE_ASSET_KINDS: dict[str, tuple[str, ...]] = {
"scene_threejs": ("threejs", "blender_glb"),
"scene_blender": ("bpy", "blender_glb"),
}
-#: what ``AssetPlan.kind`` means to the planner of each scene language — the description the
-#: swapped schema carries (scene_threejs keeps the field's own text, byte-identical)
+#: what ``AssetPlan.kind`` means to the planner of each scene language (scene_threejs keeps the field's own text)
SCENE_KIND_DOCS: dict[str, str] = {
"scene_blender": "bpy = a procedural Blender module (src/assets/<snake>.py, built once at the origin and "
"placed as collection instances); blender_glb = a hero built as an object and shipped as a GLB",
@@ -569,9 +522,7 @@ class AssetPlan(BaseModel):
name: str = Field(description="PascalCase asset name")
kind: Literal["threejs", "bpy", "blender_glb"] = Field(
description="threejs = procedural module; blender_glb = built with bpy and compiled to a GLB",
- # the schema a planner is handed names the kinds of ITS language (SCENE_ASSET_KINDS): the
- # default is scene_threejs's, byte-identical to before `bpy` existed; a scene_blender
- # planner swaps in its own enum (``scene_plan_schema``)
+ # default is scene_threejs's enum; ``scene_plan_schema`` swaps in the language's own
json_schema_extra={"enum": list(SCENE_ASSET_KINDS["scene_threejs"])},
)
description: str = Field(description="construction in numbers and colours; the builder realises it")
@@ -586,14 +537,11 @@ class EffectPlan(BaseModel):
target: str = Field(default="", description="zone / asset / scene it applies to")
-#: a camera name becomes a render FILENAME (``render_scene.mjs`` writes ``<name>_<t>.png``);
-#: the charset ``render_glb.mjs`` already enforces for view names, plus a length bound.
+#: a camera name becomes a render filename, so it is charset- and length-bounded
CAMERA_NAME_RE = re.compile(r"[A-Za-z0-9_-]{1,64}")
-#: The scene host (``scene_host.mjs`` validateCameras) states the same name / fov / position
-#: rules for the cameras ``createScene`` returns; a plan that broke them used to validate here and
-#: then draw a WARN on src/scene.js every round that no agent owns (audit 2026-09-24 N10).
+#: Same name / fov / position rules as ``scene_host.mjs`` validateCameras.
class CameraPlan(BaseModel):
name: str = Field(description="letters/digits/_/- only; it becomes a render filename")
position: Vec3
@@ -604,7 +552,7 @@ class CameraPlan(BaseModel):
@field_validator("name")
@classmethod
def _filename_safe(cls, v: str) -> str:
- """Reject (never mangle) unsafe names — the planner is re-asked with the error."""
+ """Reject (never mangle) unsafe names."""
if not CAMERA_NAME_RE.fullmatch(v):
raise ValueError(
f"camera name {v!r} must match [A-Za-z0-9_-]{{1,64}}: it becomes a render "
@@ -664,12 +612,8 @@ class ScenePlan(BaseModel):
def scene_plan_schema(language: Language | str) -> dict[str, Any]:
- """The ``ScenePlan`` JSON schema a planner of ``language`` is handed: ``AssetPlan.kind``'s enum
- (and its description) are that language's (:data:`SCENE_ASSET_KINDS`). scene_threejs's is
- ``ScenePlan.model_json_schema()`` byte for byte — the default the field carries — so every
- recorded scene_threejs planner request is unchanged; a scene_blender planner is offered
- ``bpy`` / ``blender_glb`` and never ``threejs``. ``KeyError`` for a language that plans no
- scene."""
+ """The ``ScenePlan`` JSON schema for ``language``: ``AssetPlan.kind``'s enum and description
+ are that language's. ``KeyError`` for a language that plans no scene."""
kinds = SCENE_ASSET_KINDS[Language(language).value]
schema = ScenePlan.model_json_schema()
kind = schema["$defs"]["AssetPlan"]["properties"]["kind"]
@@ -762,8 +706,7 @@ class EngineeringBrief(BaseModel):
@property
def is_useful(self) -> bool:
- """A brief with no assemblies AND no signature features tells the planner nothing —
- the caller discards it rather than pasting an empty block into the prompt."""
+ """False when the brief tells the planner nothing and should be discarded."""
return len(self.sub_assemblies) >= 2 or len(self.signature_features) >= 2
diff --git a/harness/codeverse3d/contracts/run.py b/harness/codeverse3d/contracts/run.py
index 7c0c6454..c4ac6786 100644
--- a/harness/codeverse3d/contracts/run.py
+++ b/harness/codeverse3d/contracts/run.py
@@ -1,12 +1,5 @@
-"""The run record — ``record.json`` — and everything stored inside it.
-
-``RunRecord`` (rounds, totals, provenance: the flywheel unit), ``RunId`` (where a run
-sits in a runs dir or a battery), the per-round skills usage, and the packaged
-``telemetry/`` + ``deliverable/`` blocks. The skills shapes live here rather than in
-``codeverse3d/skills`` so ``contracts`` stays a leaf that ``record``, ``addons`` and the
-CLI import without the router, and a stored record re-reads on a build with no skill
-library at all.
-"""
+"""The run record (``record.json``) and everything stored inside it: ``RunRecord``, ``RunId``,
+per-round skills usage, and the ``telemetry/`` + ``deliverable/`` blocks."""
from __future__ import annotations
@@ -30,7 +23,7 @@ from codeverse3d.contracts.spec import Spec
class SkillRead(BaseModel):
- """The read probe's verdict for one materialised bundle (design §6.4)."""
+ """The read probe's verdict for one materialised skill bundle."""
name: str
surfaced: bool = Field(default=False, description="transcript: the agent activated the skill or opened its "
@@ -44,10 +37,7 @@ class SkillRead(BaseModel):
class SkillsUsage(BaseModel):
- """``RoundRecord.skills`` — listed vs read vs what it cost, per round.
-
- The metric that replaces the former ``read_cookbook`` tool's "0 of 16 calls" is :attr:`deep_read_rate`.
- """
+ """``RoundRecord.skills``: skills listed vs read vs what it cost, per round."""
listed: list[str] = Field(default_factory=list)
reads: list[SkillRead] = Field(default_factory=list)
@@ -77,9 +67,8 @@ class SkillsUsage(BaseModel):
@property
def deep_read_rate(self) -> float | None:
- """None when there is nothing listed, or when the atime control says the probe is blind: git reads
- every untracked file for ``files_changed`` and CLI activation opens ``references/``, so atime says
- "read" when nobody chose to — only the control tells. Transcript evidence is trusted as is."""
+ """None when nothing is listed or the atime control shows the probe is blind (git and CLI
+ activation touch files nobody chose to read). Transcript evidence is trusted as is."""
if not self.listed or (self.evidence == "atime" and self.control_present and self.control_read):
return None
return len(self.deep) / len(self.listed)
@@ -92,19 +81,10 @@ RUN_PATH_NOISE = frozenset({"arms", "cells", "runs"})
class RunId(BaseModel):
- """Where a run directory sits inside its scan root — and the ONE name to call it.
-
- Run identity used to be ``ws.root.name`` everywhere, which is right for the flat
- ``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
- and the gallery collapsed whole batteries into one entry.
+ """Where a run directory sits inside its scan root, and the one name to call it.
- ``battery`` labels the scan root the run was found under; ``rel`` is the run
- directory's posix path relative to that root. Only the scanner still knows the
- root, so only the scanner can mint one of these
- (``record.record.run_id_for``)."""
+ ``battery`` labels the scan root; ``rel`` is the run dir's posix path relative to it.
+ Only the scanner knows the root, so only it mints one (``record.record.run_id_for``)."""
model_config = ConfigDict(frozen=True)
@@ -118,15 +98,8 @@ class RunId(BaseModel):
def slug(self) -> str:
"""The stable, filesystem-safe name of this run.
- * a flat ``rel`` (no parent directories — today's ``runs/<id>`` layout) keeps
- the basename UNCHANGED, so every existing dataset/index/side-car stays valid;
- * a nested ``rel`` joins the meaningful path segments with ``__``, dropping the
- structural noise (:data:`RUN_PATH_NOISE`) and a trailing ``run`` — e.g.
- ``cells/cmp_easy_stool/harness_api/run`` → ``cmp_easy_stool__harness_api``.
- ``.attemptN`` retry suffixes live on a kept segment and survive.
-
- Path segments cannot contain ``/``, so the join alone makes the slug a single
- path component; nothing else is mangled."""
+ A flat ``rel`` keeps its basename; a nested one joins its meaningful segments with ``__``
+ (dropping :data:`RUN_PATH_NOISE` and a trailing ``run``)."""
parts = self._parts()
if len(parts) <= 1:
return parts[0] if parts else self.battery
@@ -139,7 +112,7 @@ class RunId(BaseModel):
@property
def cell(self) -> str | None:
- """The prompt/cell id segment (``cells/<cell>/…``) when the layout has one."""
+ """The ``cells/<cell>/…`` segment, when the layout has one."""
parts = self._parts()
if "cells" in parts:
i = parts.index("cells")
@@ -149,8 +122,7 @@ class RunId(BaseModel):
@property
def arm(self) -> str | None:
- """The arm segment: ``arms/<arm>/…`` (ab_plan) or the directory between the
- cell and its ``run`` (compare_backends), when the layout has one."""
+ """The ``arms/<arm>/…`` segment, or the directory between the cell and its ``run``."""
parts = self._parts()
if "arms" in parts:
i = parts.index("arms")
@@ -163,10 +135,7 @@ class RunId(BaseModel):
class RunStatus(StrEnum):
- """Where a run is — and once it has stopped, only WHY it stopped. Never a verdict:
- since 2026-09-22 a run is the baseline plus ``max_rounds`` refine rounds, cut short
- only by the clock or a hard failure, and which round to hand over is a reader's
- question (``codeverse3d.addons.select``)."""
+ """Where a run is, and once stopped, why it stopped. Never a verdict."""
PLANNING = "planning"
GENERATING = "generating"
@@ -181,12 +150,9 @@ class RunStatus(StrEnum):
class StepTime(BaseModel):
- """One timed step of a run: the clock it took and the part of that clock it lost to
- provider errors — 503 / 429 / overloaded / timeout retries and their back-off, inside a
- vendor CLI (``AgentResult.provider_wait_s``) or an API call (``cost.instrument``). The
- run's minutes are the sum of ``wall_s - lost_s`` over its steps (owner, 2026-09-22).
- Parallel work — fan-out sessions, judge samples, the scene's assets beside its env — is
- ONE step, so no second of the clock is counted twice."""
+ """One timed step: its wall clock and the part lost to provider errors (503 / 429 / timeouts).
+
+ Parallel work is ONE step, so no second is counted twice."""
step: str = Field(description="plan | skeleton | assets+env+layouts | zones | assemble | candidates"
" | generate | build | gates | render | judge")
@@ -232,11 +198,9 @@ class RoundRecord(BaseModel):
# --------------------------------------------------------------------------- telemetry (settings + cost)
class RoleSettings(BaseModel):
- """Resolved model settings for ONE role of a run (planner/generator/judge/…).
+ """Resolved model settings for ONE role of a run.
- ``source`` says where the sampling knobs came from: ``run`` (stamped by the track as it
- ran, ``record.extra["sampling"]``) or ``spec`` (only the model is known — a vendor CLI owns
- its knobs; the values are left empty rather than guessed)."""
+ ``source``: ``run`` (stamped as it ran) or ``spec`` (only the model is known)."""
role: str
model: str = ""
@@ -248,7 +212,7 @@ class RoleSettings(BaseModel):
class SettingsSnapshot(BaseModel):
- """Everything that decided HOW the run ran — the 'key step settings' block."""
+ """Everything that decided how the run ran."""
schema_version: int = 1
roles: list[RoleSettings] = Field(default_factory=list)
@@ -271,7 +235,6 @@ class SettingsSnapshot(BaseModel):
class StageCost(BaseModel):
- """Token + money subtotal for one stage of the run (plan / generate / judge / …)."""
stage: str
calls: int = 0
@@ -284,8 +247,7 @@ class StageCost(BaseModel):
class CostSummary(BaseModel):
- """``telemetry/cost.json``: the run's ledger rows summarised — what the run cost, where, and
- its minutes against ``max_minutes``."""
+ """``telemetry/cost.json``: the run's ledger rows summarised."""
schema_version: int = 1
total_usd: float = Field(default=0.0, description="the ledger's sum at list price = record.total_usage")
@@ -300,7 +262,6 @@ class CostSummary(BaseModel):
class RunTelemetry(BaseModel):
- """``record.telemetry`` — accounting + settings, kept apart from the deliverable."""
schema_version: int = 1
settings: SettingsSnapshot | None = None
@@ -309,7 +270,6 @@ class RunTelemetry(BaseModel):
# --------------------------------------------------------------------------- deliverable
class DeliverableFile(BaseModel):
- """One file handed to the user, with its identity."""
path: str = Field(description="run-relative path (under deliverable/)")
role: str = Field(description="code | model | urdf | mesh | sheet | preview | frames | captions | bundle | manifest")
@@ -318,7 +278,7 @@ class DeliverableFile(BaseModel):
class RunDeliverable(BaseModel):
- """``deliverable/manifest.json`` — the round that was handed over, as paths + hashes + sizes."""
+ """``deliverable/manifest.json``: the handed-over round as paths + hashes + sizes."""
schema_version: int = 1
dir: str = "deliverable"
@@ -335,7 +295,7 @@ class RunDeliverable(BaseModel):
class RunRecord(BaseModel):
- """One run; selection is recorded separately after generation finishes."""
+ """One run."""
spec: Spec
plan: StaticPlan | ArticulatedPlan | ScenePlan | GraphicsPlan | None = None
@@ -357,11 +317,6 @@ class RunRecord(BaseModel):
@property
def minutes(self) -> float:
- """THE minutes of a run, the one number every reader reports: the ``wall_s - lost_s``
- of every step, run-level and round, so time lost to 503 / 429 / token-limit errors
- does not count (owner, 2026-09-22). It is a statistic, not the budget: the
- ``max_minutes`` clock (``orchestrator.BudgetGuard``) counts every active second,
- errors included, because it must stop a run even in a 503 storm.
-
- """
+ """The run's minutes: ``wall_s - lost_s`` over every step. A statistic, not the budget
+ clock (``BudgetGuard`` counts provider errors too)."""
return sum(s.active_s for s in self.steps) / 60.0 + sum(r.minutes for r in self.rounds)
diff --git a/harness/codeverse3d/conventions.py b/harness/codeverse3d/conventions.py
index 1b051335..9d4a7306 100644
--- a/harness/codeverse3d/conventions.py
+++ b/harness/codeverse3d/conventions.py
@@ -1,8 +1,7 @@
"""Single source of truth for 3D conventions used by prompts, tools and gates.
-Everything that talks about axes, units, frames, view presets or naming must
-import from here — never restate a convention inline (the reference harnesses
-drifted into 3-4 incompatible ``snake_case`` helpers and two up-axes).
+Everything that talks about axes, units, frames, view presets or naming imports
+from here — never restate a convention inline.
Frames
------
@@ -31,8 +30,6 @@ if TYPE_CHECKING:
class Frame(StrEnum):
- """Named coordinate conventions."""
-
Z_UP_NEG_Y_FRONT = "z_up_neg_y_front" # blender / cadquery / urdf
Y_UP_POS_Z_FRONT = "y_up_pos_z_front" # three.js / glTF
@@ -50,9 +47,7 @@ LANGUAGE_FRAME: dict[str, Frame] = {
"urdf_blender": Frame.Z_UP_NEG_Y_FRONT,
"threejs": Frame.Y_UP_POS_Z_FRONT,
"scene_threejs": Frame.Y_UP_POS_Z_FRONT,
- # a Blender scene is authored Z-up; its plan, gates and census GLB stay in the GLB frame (D12)
"scene_blender": Frame.Z_UP_NEG_Y_FRONT,
- # GL clip space is Y-up: graphics output is framed like the three.js/glTF frame.
"glsl_shader": Frame.Y_UP_POS_Z_FRONT,
"opengl_python": Frame.Y_UP_POS_Z_FRONT,
}
@@ -61,15 +56,12 @@ GLB_FRAME = Frame.Y_UP_POS_Z_FRONT
def authoring_frame(language: str) -> Frame:
- """``language``'s authoring frame; an unknown / empty id is the GLB frame itself."""
return LANGUAGE_FRAME.get(str(language), GLB_FRAME)
def to_authoring_frame(v: Sequence[float], language: str, *, extents: bool = False) -> tuple[float, float, float]:
- """A GLB-frame vector (Y-up, +Z front) in ``language``'s authoring frame: the inverse of the
- glTF export mapping ``(x, y, z) → (x, z, -y)``, so a Z-up language reads ``(x, -z, y)``.
- ``extents`` (sizes, size deltas) are permuted, never sign-flipped — and that permutation is
- its own inverse: it also takes a Z-up plan's (W, D, H) into the GLB frame's (W, H, D)."""
+ """A GLB-frame vector in ``language``'s authoring frame (a Z-up language reads ``(x, -z, y)``).
+ ``extents`` (sizes) are permuted, never sign-flipped; the permutation is its own inverse."""
x, y, z = (float(c) for c in v)
if authoring_frame(language) is Frame.Z_UP_NEG_Y_FRONT:
return (x, z if extents else -z, y)
@@ -77,18 +69,15 @@ def to_authoring_frame(v: Sequence[float], language: str, *, extents: bool = Fal
def glb_basis(language: str) -> tuple[tuple[float, float, float], ...]:
- """The 3×3 rows taking a ``language``-frame vector into the GLB frame — the glTF export
- mapping ``(x, y, z) → (x, z, -y)`` for a Z-up language, identity otherwise; the inverse of
- :func:`to_authoring_frame`. Handed to a harness writer that cannot import this module (the
- scene_blender census-GLB writer runs inside Blender), so the mapping is still stated once."""
+ """The 3×3 rows taking a ``language``-frame vector into the GLB frame (identity for Y-up).
+ Handed to writers that cannot import this module (the census-GLB writer runs in Blender)."""
if authoring_frame(language) is Frame.Z_UP_NEG_Y_FRONT:
return ((1.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, -1.0, 0.0))
return ((1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0))
def from_authoring_frame(v: Sequence[float], language: str) -> tuple[float, float, float]:
- """The inverse of :func:`to_authoring_frame` for a point / direction: ``language``'s frame
- into the GLB frame — :func:`glb_basis` applied, so the mapping is stated once."""
+ """A point / direction in ``language``'s frame, in the GLB frame (:func:`glb_basis` applied)."""
x, y, z = (float(c) for c in v)
r = glb_basis(language)
return (r[0][0] * x + r[0][1] * y + r[0][2] * z, r[1][0] * x + r[1][1] * y + r[1][2] * z,
@@ -96,7 +85,6 @@ def from_authoring_frame(v: Sequence[float], language: str) -> tuple[float, floa
def frame_doc(frame: Frame) -> str:
- """Return the one-paragraph prompt text describing ``frame``."""
if frame is Frame.Z_UP_NEG_Y_FRONT:
return (
"Coordinate frame: Z is UP, -Y is the FRONT of the object (the face a "
@@ -114,16 +102,12 @@ def frame_doc(frame: Frame) -> str:
# --------------------------------------------------------------------------- views
@dataclass(frozen=True)
class ViewPreset:
- """A canonical camera direction: azimuth (deg, 0 = front, CCW from above) and
- elevation (deg above the horizon). Distance is fitted to the asset bbox."""
-
name: str
azimuth_deg: float
elevation_deg: float
-#: Judge view set for objects — the 14-view rig (brilliana camera numbers):
-#: three rings ±30° + eye-level cardinals + poles; adopted 2026-08-31, D47.
+#: Judge view set for objects: 14 views (rings at ±30°, eye-level cardinals, poles).
OBJECT_VIEWS: tuple[ViewPreset, ...] = (
ViewPreset("front_right_high", 45.0, 30.0),
ViewPreset("back_right_high", 135.0, 30.0),
@@ -141,10 +125,8 @@ OBJECT_VIEWS: tuple[ViewPreset, ...] = (
ViewPreset("bottom", 0.0, -90.0),
)
-#: The measured legacy clay cameras (the judge's geometry montage) — its OWN tuple,
-#: not a subset of the rig. Its ``top`` (el 88) shares a name with the rig's ``top``
-#: (el 90): that is fine ONLY because nothing unions the two tuples by name — clay
-#: tiles carry ``mode != "shaded"`` and prompt_builder resolves their labels here first.
+#: Clay cameras (the judge's geometry montage), separate from the rig. Its ``top`` shares a
+#: name with the rig's: never union the two tuples by name.
OBJECT_CLAY_VIEWS: tuple[ViewPreset, ...] = (
ViewPreset("front_right_34", 35.0, 22.0),
ViewPreset("back_left_34", 215.0, 22.0),
@@ -154,22 +136,18 @@ OBJECT_CLAY_VIEWS: tuple[ViewPreset, ...] = (
_OBJECT_VIEW_BY_NAME: dict[str, ViewPreset] = {v.name: v for v in OBJECT_VIEWS}
-#: Quick 4-view subset (cheap gates, agent contact sheets, candidates,
-#: scene assets) — by NAME so a rig reorder cannot silently change it.
+#: Quick 4-view subset (cheap gates, contact sheets, candidates), picked by name.
OBJECT_VIEWS_QUICK: tuple[ViewPreset, ...] = tuple(
_OBJECT_VIEW_BY_NAME[n] for n in ("front_right_high", "back_left_high", "front", "top")
)
-#: The articulation sheet's three views per pose (``joints_export.render_poses``) — by
-#: NAME too: it was ``OBJECT_VIEWS_QUICK[:3]``, which a reorder of the quick set changes.
+#: The articulation sheet's three views per pose (``joints_export.render_poses``).
ARTICULATION_VIEWS: tuple[ViewPreset, ...] = tuple(
_OBJECT_VIEW_BY_NAME[n] for n in ("front_right_high", "back_left_high", "front")
)
-#: the pre-D47 8-view rig's names → their twin in the 14-view rig. Stored runs carry them,
-#: and the clay cameras (``OBJECT_CLAY_VIEWS``) still use them. Every view preference list
-#: is written in rig names and matches a view by :func:`view_key`, so no list keeps its own
-#: subset of the old names.
+#: Clay-camera view names → their twin in the rig; view preference lists use rig names and
+#: match through :func:`view_key`.
LEGACY_VIEW_ALIASES: dict[str, str] = {
"front_right_34": "front_right_high",
"back_left_34": "back_left_high",
@@ -178,22 +156,17 @@ LEGACY_VIEW_ALIASES: dict[str, str] = {
def view_key(name: str) -> str:
- """A view's rig name: ``front_right_34`` → ``front_right_high``; anything else unchanged."""
return LEGACY_VIEW_ALIASES.get(name, name)
def views_by_preference(views: Sequence[RenderView], names: Sequence[str]) -> list[RenderView]:
- """The ``views`` whose :func:`view_key` is in ``names``, in the order of ``names``."""
rank = {n: i for i, n in enumerate(names)}
return sorted((v for v in views if view_key(v.name) in rank), key=lambda v: rank[view_key(v.name)])
-#: Scene overview rig (scenes sit on ground: aerial + eye level, no underside). The
-#: ``overview_*`` views reach the judge (the first ``render_scene.MAX_JUDGE_OVERVIEWS``);
-#: ``overview_low_front`` (2026-10-14, scene) is the CONTACT camera — elevation under 10°
-#: puts it at ground level just outside the content (``orbit.mjs fitContactCamera``), the
-#: angle at which daylight under a base and a part through a neighbour are visible, and the
-#: tile the judge's contact crops are cut from. The ``eye_*`` views are diagnostics only.
+#: Scene rig (aerial + eye level). ``overview_*`` reach the judge; ``overview_low_front``
+#: (elevation < 10°) is the ground-level contact camera the contact crops are cut from;
+#: ``eye_*`` are diagnostics only.
SCENE_VIEWS: tuple[ViewPreset, ...] = (
ViewPreset("overview_front_right", 40.0, 32.0),
ViewPreset("overview_back_left", 220.0, 32.0),
@@ -211,104 +184,68 @@ _NON_WORD = re.compile(r"[^0-9A-Za-z]+")
def to_snake(name: str) -> str:
- """``SeatCushion`` / ``seat cushion`` / ``Seat-Cushion2`` → ``seat_cushion2``.
-
- This is THE name normaliser; every wrapper and prompt must use it.
- """
+ """``SeatCushion`` / ``seat cushion`` / ``Seat-Cushion2`` → ``seat_cushion2`` (THE name normaliser)."""
s = _NON_WORD.sub("_", name.strip())
s = _CAMEL_SPLIT.sub("_", s)
s = re.sub(r"_+", "_", s).strip("_").lower()
return s or "part"
-#: a part / assembly name as the contracts require it: ``SeatCushion``, instances ``SeatCushion_3``.
-#: All-caps acronyms are valid PascalCase (owner, 2026-09-22): ``LED``, ``TV``, ``A``,
-#: ``TVStand``, ``LEDStrip``, ``HDMIPort1``, ``CPU_2``. The stdlib-only wrapper
-#: ``languages/wrappers/run_cq.py`` keeps a copy (it cannot import this package);
-#: ``tests/core/test_names.py`` pins the two together.
+#: a part / assembly name: ``SeatCushion``, instances ``SeatCushion_3``; acronyms (``LED``,
+#: ``TVStand``, ``CPU_2``) are valid. ``wrappers/run_cq.py`` keeps a copy; tests pin them.
PASCAL_RE = re.compile(r"^[A-Z][A-Za-z0-9]*(?:_\d+)?$")
-#: a URDF link name — also its Blender object name and its ``meshes/<link>.glb`` stem. The
-#: skeleton writes the plan part's snake_case key (``DoorHandle`` → ``door_handle``); the plan's
-#: PascalCase spelling is accepted too, because every gate matches parts by :func:`to_snake`.
-#: Either way a plain identifier — never ``Door.001``, a space or a path. The Blender-run link
-#: wrapper keeps a copy (``run_bpy_links._SAFE_LINK``); ``tests/core/test_names.py`` pins them.
+#: a URDF link name (also its Blender object name and ``meshes/<link>.glb`` stem): a plain
+#: identifier. ``run_bpy_links._SAFE_LINK`` keeps a copy; tests pin them.
LINK_NAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
-#: how an instance name maps to its part: ``Leg_2`` (the contract's ``Name_N``), Blender's
-#: auto-suffix ``Leg.001`` and ``Leg-2`` all read as part ``Leg``; up to three digits, so a
-#: scene asset's hex id that happens to be all digits (``DonkeyCart_800006``) is no index.
+#: instance name → part: ``Leg_2``, ``Leg.001`` and ``Leg-2`` all read as ``Leg``; at most
+#: three digits, so an all-digit asset id (``DonkeyCart_800006``) is no index.
_INSTANCE_RE = re.compile(r"^(?P<base>.+?)[_.-](?P<idx>\d{1,3})$")
def split_instance(name: str) -> tuple[str, str]:
- """``Leg_2`` → (``Leg``, ``"2"``); a name with no instance suffix → (name, ``""``). THE
- instance rule: the measure table, the contract match and refine grouping all read it."""
m = _INSTANCE_RE.match(name)
return (m.group("base"), m.group("idx")) if m else (name, "")
-#: a URDF link's geometry pieces are exported as ``<link>__<i>`` nodes under the link node
-#: (``spatial/joints_export``); ``spatial/measure`` merges them back into the link's part.
+#: separator of a URDF link's geometry-piece nodes ``<link>__<i>``.
LINK_PIECE_SEP = "__"
-#: the harness's own mark on a scene's ZONE roots (D111): ``userData[ZONE_ROOT_KEY] = <zone name>`` in
-#: three.js, set by the assembler (``render_scene_js``'s ``addZone``), and the census GLB's zone node
-#: ``extras`` for scene_blender (``wrappers/_census_glb.py``, handed the key on argv — it cannot import
-#: this module), which GLTFLoader turns into the same ``userData``. The placement table reads it
-#: (``runtime_js/lib/host_placement.mjs`` ``ZONE_ROOT_KEY``; ``tests/scene_runtime/test_zone_roots.py``
-#: pins the two): only children of a marked root are placed assets — every other root (env scenery, a
-#: zone's stray ``scene.add``) is scenery, never a row. A key, never a name test: a zone may name its
-#: group anything, and an env group may be called anything too.
+#: userData / glTF extras key marking a scene ZONE root; only children of a marked root are
+#: placed assets. ``host_placement.mjs`` keeps a copy; tests pin them.
ZONE_ROOT_KEY = "c3d_zone"
def to_pascal(name: str) -> str:
- """``seat_cushion`` / ``seat cushion`` → ``SeatCushion``; a name that is already
- PascalCase (no underscore) comes back unchanged, so ``TVStand`` stays ``TVStand``.
-
- For a name without an instance suffix ``to_snake(to_pascal(n)) == to_snake(n)`` — the
- snake name is the key every gate matches parts by (``CPU_2`` / ``Leg_0`` fold to
- ``Cpu2`` / ``Leg0``: an instance name is not a plan name). The reverse loses acronyms: ``to_pascal("tv_stand")``
- is ``TvStand``, so a name rebuilt from a snake key (a file stem, a GLB key, a zone
- module) is ``TvStand`` — code that compares such a name must compare ``to_snake``.
- """
+ """``seat_cushion`` → ``SeatCushion``; acronyms are lost (``tv_stand`` → ``TvStand``), so compare via ``to_snake``."""
if "_" not in name and PASCAL_RE.match(name):
return name
return "".join(w[:1].upper() + w[1:] for w in to_snake(name).split("_") if w) or "Part"
def slugify(text: str, max_len: int = 48) -> str:
- """Filesystem/URL-safe slug for run directories."""
s = to_snake(text)[:max_len].strip("_")
return s or "run"
def fmt3(vec: Sequence[float]) -> str:
- """A vector as the prompts print it: ``0.100, 0.250, -0.030`` (metres, 3 decimals)."""
return ", ".join(f"{float(x):.3f}" for x in vec)
# --------------------------------------------------------------------------- limits
-#: Triangle ceilings: the object one is the depth gate's upper clamp (``tracks/depth.budget_gate``),
-#: the only place an object's triangle count is enforced — no build wrapper checks it.
+#: Triangle ceilings; the object one is the depth gate's upper clamp (``tracks/depth.budget_gate``).
MAX_TRIS_OBJECT = 600_000
MAX_TRIS_SCENE = 3_000_000
-#: Scene draw budget on the probe census's ``totals.draws`` — one per visible mesh / points /
-#: line / sprite per material group, an InstancedMesh once (``host_census.mjs`` ``objectDraws``).
-#: ``scene_probe`` WARNs above the first and fails the build above the second, so the repair loop
-#: fixes it inside the round (D99). Tuned on 753 recorded scene rounds: median fps drops below 5
-#: past ~5 000; every round past 15 000 ran at ≤ 5 fps, and only 0.4 % of pre-D93 harness rounds
-#: (p99 12 348) reach it.
+#: Scene draw budget on the probe census's ``totals.draws``: ``scene_probe`` WARNs above the
+#: first and fails the build above the second.
DRAWS_WARN_SCENE = 5_000
MAX_DRAWS_SCENE = 15_000
#: Default tolerance for bbox contract checks, in meters.
BBOX_TOLERANCE_M = 0.01
-#: "Stands on the ground": the lowest point within this of up = 0 (meters). The contract gate
-#: WARNs past it (ERRORs past 3x) and the Blender skeleton's self-check asserts it; texts say
-#: "at up = 0" without the number (D93/D98).
+#: "Stands on the ground": the lowest point within this of up = 0 (meters); WARN past it, ERROR past 3x.
GROUND_TOL_M = 0.01
#: Parts are "touching" when the surface gap is below this (meters).
CONTACT_GAP_M = 0.002
diff --git a/harness/codeverse3d/cost/context.py b/harness/codeverse3d/cost/context.py
index 6be53824..1915a1be 100644
--- a/harness/codeverse3d/cost/context.py
+++ b/harness/codeverse3d/cost/context.py
@@ -1,35 +1,9 @@
-"""Where a call sits in a run — the attribution the ledger needs.
-
-A :class:`CallContext` answers "which run, which round, which stage, which
-role" for the call that is about to happen. Precedence:
-
-1. what the caller passed explicitly (a judge knows it is judging) — always wins;
-2. a label that names a **job of its own** (``judge:…``, ``planner``,
- ``caption…``, ``pairwise:…`` — :data:`SELF_DESCRIBING`).
- Such a call is not the work of whatever agent session happens to surround it,
- so it outranks the ambient context. This is the fix for a measured
- mis-attribution: an in-process tool that bills a model *inside* an agent
- session (a captioner, a judge invoked as a tool) was filed
- under the session's ``stage=refine / role=generator``;
-3. the ambient context (:func:`call_context`) — set by
- :mod:`codeverse3d.cost.instrument` around an agent session. It beats a
- *generation* label because the session knows more than a call made inside it
- does: a best-of-N candidate session runs with ``job.kind="candidate"`` while a
- tool it calls bills a model under a plain ``baseline`` label;
-4. what is left of the label (a generation stage, the round tag) — kept explicit because the
- ambient context is bound per stage, not per call (``proc.fan_out`` does copy ContextVars into
- its workers, D105; the label is the finer attribution).
-
-A label that names nothing (:data:`~codeverse3d.cost.types.Stage.OTHER`) states
-nothing and never displaces anything.
-
-The **run binding** (:func:`bound_run`, the run slug) is a plain ``ContextVar``.
-A bench worker that opens its own run in its own thread gets its own binding, and a
-worker thread inherits its caller's because ``codeverse3d.proc.fan_out`` copies the
-context (bb6179c). There is deliberately no process-wide fallback: restoring one by
-value republished a sibling's run the moment the first parallel run exited, and rows
-written afterwards landed in that finished run's file (2026-08-30 — the interleave
-1756866 deleted the ``_active_ledgers`` global for, left standing on this half).
+"""Where a call sits in a run: the attribution the ledger needs.
+
+Precedence: explicit arguments > a label naming a job of its own (:data:`SELF_DESCRIBING`)
+> the ambient context (:func:`call_context`) > the rest of the label. The run binding
+(:func:`bound_run`) is a plain ``ContextVar`` copied into fan-out workers, with no
+process-wide fallback.
"""
from __future__ import annotations
@@ -64,8 +38,7 @@ class CallContext:
)
def resolved(self) -> CallContext:
- """Fill role from stage (and stage from label) so the row is never ``other``
- when something better can be derived."""
+ """Fill role from stage (and stage from label) so the row is never ``other`` needlessly."""
stage = self.stage or (stage_for_label(self.label) if self.label else None)
role = self.role or (role_for_stage(stage) if stage else None)
return replace(self, stage=stage, role=role)
@@ -80,11 +53,7 @@ _run_var: ContextVar[str] = ContextVar("c3d_cost_run", default="")
@contextmanager
def bound_run(run: str) -> Iterator[None]:
- """Name the run every row written inside the block belongs to.
-
- Unwinds with the ``ContextVar`` token instead of re-setting the previous value:
- two of these open at once (``bench.run_bench``'s pool) must undo independently
- — see the module docstring."""
+ """Name the run every row written inside the block belongs to (concurrent blocks unwind independently)."""
token = _run_var.set(run or "")
try:
yield
@@ -111,11 +80,7 @@ def call_context(
role: Role | str | None = None,
label: str = "",
) -> Iterator[CallContext]:
- """Set the ambient attribution for the duration of the block (this thread).
-
- Used by :mod:`codeverse3d.cost.instrument` around an agent session and by the
- judges around a verdict; nesting merges, so an inner block only has to name
- what it changes."""
+ """Set the ambient attribution for the block; nesting merges."""
ctx = _ctx.get().merge(CallContext(run=run, round=round, stage=_stage(stage), role=_role(role), label=label))
token = _ctx.set(ctx)
try:
@@ -143,8 +108,7 @@ def _role(value: Role | str | None) -> Role | None:
# --------------------------------------------------------------------------- labels
-#: request-label prefix → (stage, role). Longest prefix wins; anything else is
-#: routed through ``stage_for_label`` (which understands generation labels).
+#: request-label prefix → (stage, role); longest prefix wins, the rest goes through ``stage_for_label``.
_LABEL_HINTS: tuple[tuple[str, Stage, Role], ...] = (
("planner", Stage.PLAN, Role.PLANNER),
("plan", Stage.PLAN, Role.PLANNER),
@@ -156,9 +120,7 @@ _LABEL_HINTS: tuple[tuple[str, Stage, Role], ...] = (
def context_from_label(label: str) -> CallContext:
- """Best-effort attribution from a ``ChatRequest.label``: its head names the job
- (``judge:…``, a generation stage) and the judge's
- ``…:r<NN>:s<k>`` tag carries the round."""
+ """Best-effort attribution from a ``ChatRequest.label`` (head names the job, ``r<NN>`` the round)."""
low = (label or "").strip()
if not low:
return _EMPTY
@@ -174,8 +136,7 @@ def context_from_label(label: str) -> CallContext:
def _stated(stage: Stage | None) -> Stage | None:
- """``Stage.OTHER`` is "the label told us nothing" — not a statement, so it must
- not outrank the ambient session context."""
+ """``Stage.OTHER`` states nothing, so it must not outrank the ambient context."""
return None if stage is Stage.OTHER else stage
@@ -188,20 +149,13 @@ def _round_from_label(label: str) -> int | None:
return None
-#: Stages a label can name that describe a job of their own. A call whose label
-#: says "judge" / "plan" / "caption" / "pairwise" is doing that job
-#: even when an agent session surrounds it, so it outranks the ambient context;
-#: a generation stage in a label does not (see the module docstring).
+#: Stages whose label names a job of its own: they outrank the ambient session context.
SELF_DESCRIBING: frozenset[Stage] = frozenset(
{Stage.PLAN, Stage.JUDGE, Stage.PAIRWISE, Stage.CAPTION})
def attribute(explicit: CallContext | None = None, *, label: str = "") -> CallContext:
- """The final attribution for one call.
-
- Precedence (see the module docstring): explicit > a label that names a job of
- its own > the ambient session context > the rest of the label. The row's
- ``label`` is always the most specific one available."""
+ """The final attribution for one call (precedence in the module docstring)."""
ctx = current()
if label:
from_label = context_from_label(label)
@@ -216,13 +170,10 @@ def attribute(explicit: CallContext | None = None, *, label: str = "") -> CallCo
# --------------------------------------------------------------------------- per-attempt sink
@dataclass(frozen=True)
class AttemptRecord:
- """One round-trip of one logical model call (``models.retry.rotate_with_retries``).
+ """One round-trip of one logical model call, reported to the sink from :func:`attempt_recording`.
- The metering layer (``instrument.MeteredChatModel``) installs a sink for these
- with :func:`attempt_recording`; the backend reports every round-trip — the
- winner included — so a hedge loser's and a charged-but-invalid reply's tokens
- reach the ledger instead of vanishing (audit 2026-08-27). A discarded one that cost
- money becomes a ``source="extra"`` row."""
+ Every round-trip is reported, winner included; a discarded one that cost money becomes a
+ ``source="extra"`` ledger row."""
attempt: int #: 1-based issue order within the logical call
key: str #: the full API key that served it; the ledger keeps only its last 4 chars
@@ -234,10 +185,8 @@ class AttemptRecord:
AttemptSink = Callable[[AttemptRecord], None]
-#: Request-scoped sink for per-attempt rows. A ContextVar rather than a new
-#: parameter because ``ChatModel.generate(request)`` is a protocol many backends
-#: implement; the backend captures the sink ONCE at call entry, so a hedge loser
-#: that lands later in its own thread still reports through the captured callable.
+#: Request-scoped sink for per-attempt rows; the backend captures it once at call entry so a
+#: hedge loser landing later in another thread still reports.
_attempt_sink: ContextVar[AttemptSink | None] = ContextVar("c3d_cost_attempt_sink", default=None)
diff --git a/harness/codeverse3d/cost/guard.py b/harness/codeverse3d/cost/guard.py
index e1c5bc2b..ec47f586 100644
--- a/harness/codeverse3d/cost/guard.py
+++ b/harness/codeverse3d/cost/guard.py
@@ -1,14 +1,4 @@
-"""Estimate what a call will cost **before** sending it, and pick a tier.
-
-The ledger (``telemetry/cost.jsonl``) records money *after* it is spent, and
-``orchestrator.BudgetGuard`` is only the wall clock. This is the cheap estimate that belongs in front of a
-call: how many tokens am I about to send, and what will they cost on this model?
-
-Token counts are estimates (≈4 characters per token for prose/code, a flat
-per-image count for vision parts) — good to ±15% for prompt sizing, which is all
-a routing decision needs. When the exact number matters, price the ``Usage``
-the provider returns (``codeverse3d.cost.record_call``).
-"""
+"""Estimate what a call will cost before sending it (token counts are ~4 chars/token, +-15%)."""
from __future__ import annotations
@@ -19,11 +9,9 @@ from codeverse3d.contracts.common import Usage
from codeverse3d.cost.types import normalise_ids
from codeverse3d.models.pricing import estimate_cost, price_provenance
-#: characters per token — Gemini/OpenAI English prose and code both sit near 4
CHARS_PER_TOKEN = 4.0
-#: tokens billed for one image part, by longest edge (Gemini bills 1290 for a
-#: 1024² tile; smaller images are cheaper, larger ones are tiled)
+#: tokens billed for one image part, by longest edge
IMAGE_TOKENS: dict[int, int] = {256: 258, 512: 258, 768: 1032, 1024: 1290, 2048: 5160}
@@ -42,7 +30,6 @@ def image_tokens(n: int = 1, *, px: int = 1024) -> int:
@dataclass(frozen=True)
class CostEstimate:
- """What one call is expected to cost, and how much to trust the number."""
model_id: str
provider: str
@@ -69,11 +56,7 @@ def estimate_call(
prompt: str | Sequence[str] = "",
n_images: int = 0,
) -> CostEstimate:
- """Price a call that has not happened yet.
-
- ``model_id`` is any harness id (``gemini:gemini-3.8-flash``,
- ``api-agent:gemini:gemini-3.8-flash``). Give either token counts or the
- ``prompt`` text, plus ``n_images`` vision parts (1024 px) either way."""
+ """Price a call that has not happened yet, from token counts or ``prompt`` text plus ``n_images``."""
kind, provider, model = normalise_ids("", model_id)
if not provider:
kind, provider, model = normalise_ids(model_id, model_id)
diff --git a/harness/codeverse3d/cost/instrument.py b/harness/codeverse3d/cost/instrument.py
index 4e085230..0304b52c 100644
--- a/harness/codeverse3d/cost/instrument.py
+++ b/harness/codeverse3d/cost/instrument.py
@@ -1,24 +1,8 @@
-"""Meter every model call and every agent session into the ledger.
-
-Two thin proxies do the whole job:
-
-* :class:`MeteredChatModel` wraps a :class:`~codeverse3d.models.base.ChatModel`.
- Every ``generate`` appends one :class:`~codeverse3d.cost.types.CallCost` row
- (tokens, the unit prices actually used + their provenance, $, latency,
- cache hit, outcome). Because ``models.registry.get_chat_model`` returns the
- proxy, this covers the planner, the judges, the captioner and single-shot
- generation.
-* :class:`MeteredAgent` wraps a :class:`~codeverse3d.agents.registry.CodingAgent`.
- It sets the ambient attribution (round / stage / label) for the session so
- the model rows above land in the right bucket and, because every backend is a
- vendor CLI whose calls we cannot see, records one session row from
- ``AgentResult.usage``. ``agents.registry
- .get_coding_agent`` returns the proxy.
-
-Accounting is never allowed to fail a run: every hook is wrapped, and an
-exception in the ledger is logged and swallowed. The proxies forward every
-other attribute, so a caller that reaches for ``model.pool`` or ``agent.kind``
-sees the real object's.
+"""Meter every model call and agent session into the ledger.
+
+:class:`MeteredChatModel` appends one ``CallCost`` row per ``generate``; :class:`MeteredAgent`
+sets the attribution for a session and records its one session row. Accounting never fails
+a run: ledger errors are logged and swallowed, and other attributes forward to the real object.
"""
from __future__ import annotations
@@ -58,7 +42,6 @@ log = logging.getLogger(__name__)
class _Proxy:
- """Forward everything to the wrapped object; the subclasses add the meter."""
def __init__(self, inner: Any):
self._inner = inner
@@ -79,7 +62,6 @@ class _Proxy:
class MeteredChatModel(_Proxy):
- """ChatModel proxy that appends one ledger row per call."""
@property
def provider(self) -> str:
@@ -88,10 +70,7 @@ class MeteredChatModel(_Proxy):
# -- the meter --------------------------------------------------------
def generate(self, request: ChatRequest) -> ChatResponse:
call_id = uuid4().hex # joins the per-attempt rows to the call's logical row
- # captured NOW: a hedge loser lands after this call returned, in a thread with
- # no context — neither the run's ledger, its name, the stage/role/round
- # attribution (the loser's row used to fall back to the bare label) nor the
- # open tallies are reachable
+ # captured now: a hedge loser lands after this call returned, in a thread with no context
ledger = default_ledger()
run = run_binding().run
ctx = attribute(label=request.label)
@@ -109,9 +88,7 @@ class MeteredChatModel(_Proxy):
with attempt_recording(attempt_row):
resp = self._inner.generate(request)
except BaseException as exc: # noqa: BLE001 - record the attempt, then re-raise
- # a failed call may still have been billed: ModelError.usage carries what the
- # provider charged (a bad-JSON reply costs like a good one) — but only when
- # the round-trips did not already book it, or the last one counts twice
+ # a failed call may still have been billed (ModelError.usage), unless a round-trip already booked it
ms = int((time.perf_counter() - t0) * 1000)
usage = getattr(exc, "usage", None)
usage = usage if isinstance(usage, Usage) else Usage(backend=self.provider, model=self.model)
@@ -123,9 +100,6 @@ class MeteredChatModel(_Proxy):
raise
ms = int((time.perf_counter() - t0) * 1000)
book_time(ms / 1000, trips.lost_ms(ms, resp.usage.latency_ms) / 1000)
- # which key served it and how many round-trips it took (gemini.py puts both in
- # ``raw``); until 2026-08-26 no telemetry row carried either, so the per-key
- # distribution of calls could only be probed, never read
self._record(resp.usage, request, outcome="ok", ms=ms,
key=resp.raw.get("key"), attempts=resp.raw.get("attempts", 0),
call_id=call_id)
@@ -144,10 +118,7 @@ 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:
- """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``."""
+ """Book a discarded round-trip that still cost money as ``source="extra"``; True when it did."""
if not (rec.discarded and rec.usage.cost_usd):
return False
try:
@@ -168,9 +139,7 @@ class MeteredChatModel(_Proxy):
class _RoundTrips:
- """The round-trips of ONE logical call, as the backend reported them through the attempt
- sink (``models.retry.rotate_with_retries``), reduced to what the minutes need: how long
- the ones that got an answer took, and whether any failed without one."""
+ """The round-trips of one logical call, reduced to what the minutes need: time answered, any failure."""
def __init__(self) -> None:
self.answered_ms = 0 # the winner, and a reply that came back unusable (bad JSON, empty)
@@ -187,10 +156,7 @@ class _RoundTrips:
self.failed = True
def lost_ms(self, wall_ms: int, answer_ms: int) -> int:
- """The call's milliseconds lost to provider errors: everything outside its answered
- round-trips once one failed without an answer — its failed tries, their back-off and
- the key waits between them. A backend that reports no round-trips (the SDK adapters)
- is charged everything outside the answer it returned."""
+ """Milliseconds lost to provider errors: everything outside the answered round-trips once one failed."""
if not self.seen:
return max(0, wall_ms - answer_ms)
return max(0, wall_ms - self.answered_ms) if self.failed else 0
@@ -210,8 +176,7 @@ def _outcome(exc: BaseException) -> str:
class MeteredAgent(_Proxy):
- """CodingAgent proxy: attribution for the session + its one ledger row. The
- job runs as given — the turn cap is decided in ``tracks.generation``."""
+ """CodingAgent proxy: attribution for the session + its one ledger row."""
@property
def kind(self) -> str:
@@ -223,9 +188,7 @@ class MeteredAgent(_Proxy):
with call_context(round=job.round, stage=stage, role=Role.GENERATOR, label=job.label):
result = self._inner.run(job)
wall_s = time.perf_counter() - t0
- # the CLI's own retries of 503 / 429 / token-limit errors, read from its log
book_time(wall_s, float(result.provider_wait_s or 0.0))
- # an opaque CLI: its session row is the only record
self._record_session(job, result, stage, int(wall_s * 1000))
return result
@@ -240,7 +203,6 @@ class MeteredAgent(_Proxy):
latency_ms=usage.latency_ms or ms,
n_calls=max(1, int(result.tool_calls or 1)),
source="estimate" if result.usage_estimated else "session",
- # the effort the CLI was given (agy --effort): a loop splits by it (D110)
**({"effort": result.effort} if result.effort else {}))
except Exception as e: # pragma: no cover
log.debug("cost: could not record agent session %s: %s", job.label, e)
@@ -248,8 +210,7 @@ class MeteredAgent(_Proxy):
# --------------------------------------------------------------------------- factories
def metered_chat_model(model: Any) -> Any:
- """Wrap ``model`` unless it is already metered. Metering cannot be switched off: the
- ledger is the only record of money (the ``C3D_COST_LEDGER=off`` switch went 2026-09-22)."""
+ """Wrap ``model`` unless it is already metered. Metering cannot be switched off."""
if model is None or isinstance(model, MeteredChatModel):
return model
return MeteredChatModel(model)
@@ -266,20 +227,9 @@ def metered_agent(agent: Any) -> Any:
def run_ledger(workspace: str | Path, *, run: str = "", create: bool = True) -> Iterator[CostLedger | None]:
"""Meter one run into ``<workspace>/telemetry/cost.jsonl``.
- Binds the run name and points :func:`~codeverse3d.cost.ledger.record_call` at the
- run's ledger for the duration of the block.
-
- ``create=False`` is for work done *after* a run finished (``3dcode judge``,
- a re-pick): it appends only when the run already keeps a
- ledger, because a ledger holding nothing but the re-judge would be read as
- the whole run's cost and hide everything the run really spent. Without one
- the rows go to the per-process log instead.
-
- **Nests and parallelises.** Both bindings unwind by ``ContextVar`` token, so a
- bench cell that opens a ledger for the cell and then a second one for the
- harness run inside it keeps both, and ``bench.run_bench`` can run N prompts in
- N threads without their rows mixing — a save-and-restore by value could not,
- because a fresh worker saved whatever a sibling had published last."""
+ ``create=False`` (work after a run finished) appends only to an existing ledger, else rows go
+ to the per-process log, so a re-judge never masquerades as the run's whole cost.
+ Nests and parallelises: bindings unwind by ``ContextVar`` token."""
ws = Path(workspace)
if not create and existing_ledger_path(ws) is None:
with bound_run(run or ws.name):
diff --git a/harness/codeverse3d/cost/ledger.py b/harness/codeverse3d/cost/ledger.py
index 155d828a..981506b3 100644
--- a/harness/codeverse3d/cost/ledger.py
+++ b/harness/codeverse3d/cost/ledger.py
@@ -1,15 +1,7 @@
"""Append-only cost ledger: one JSONL row per model / agent call.
-Writer (``record_call``) — callers hand it the ``Usage`` they already have; the
-ledger resolves the price row, records the unit prices it used and their
-provenance, and appends one line. It never raises and never blocks a run:
-accounting must not be able to fail a build.
-
-Reader (``load_ledger``) tolerates rows written by older/newer versions
-(unknown fields are kept, missing fields default).
-
-Aggregator (``summarise``) buckets rows by any of ``run / stage / role /
-backend / model / provider / round / outcome``.
+``record_call`` prices and appends a row (never raises); ``load_ledger`` reads rows back
+tolerantly; ``summarise`` buckets them by dimension.
"""
from __future__ import annotations
@@ -47,18 +39,13 @@ from codeverse3d.proc import iter_jsonl_lines
log = logging.getLogger(__name__)
-#: the ledger of a run lives in its telemetry bucket (``<run>/telemetry/``) — the
-#: one name it has: the root ``cost_ledger.jsonl`` and ``telemetry/usage.jsonl`` aliases went
-#: on 2026-09-22 (runs written before keep them as dangling-safe symlinks nobody reads)
+#: a run's ledger lives in ``<run>/telemetry/``
TELEMETRY_DIR = "telemetry"
TELEMETRY_LEDGER = f"{TELEMETRY_DIR}/cost.jsonl"
DIMENSIONS = ("run", "stage", "role", "backend", "model", "provider", "round", "outcome")
-#: backends that bill us themselves (a subscription CLI reporting ``total_cost_usd``).
-#: Their dollar is authoritative and their reported model id is not — claude-code
-#: names one of the served models, not the one that did the work — so these rows
-#: are never re-priced from the token table.
+#: backends that report their own cost: authoritative, so never re-priced from the token table
PROVIDER_PRICED_BACKENDS = frozenset({"claude-code"})
@@ -86,19 +73,13 @@ _fallback: CostLedger | None = None
#: sentinel: "this execution context did not state a ledger"
_UNSET: Any = object()
-#: context-local override of the default ledger. Context-local ONLY, like
-#: ``codeverse3d.cost.context._run_var``: a bench worker running its own prompt in its
-#: own thread must not have its rows land in a sibling run's file, and a process-wide
-#: copy of it could not unwind correctly when two runs overlap (2026-08-30).
+#: context-local ONLY override of the default ledger, so parallel runs never share a file
_default_var: ContextVar[Any] = ContextVar("c3d_cost_default_ledger", default=_UNSET)
@contextmanager
def bound_ledger(path: str | Path) -> Iterator[CostLedger]:
- """Point :func:`record_call` at ``path`` for the duration of the block.
-
- Unwinds with the ``ContextVar`` token, so nested and parallel blocks each undo
- exactly their own binding."""
+ """Point :func:`record_call` at ``path`` for the block."""
led = CostLedger(path)
token = _default_var.set(led)
try:
@@ -108,13 +89,8 @@ def bound_ledger(path: str | Path) -> Iterator[CostLedger]:
def default_ledger() -> CostLedger:
- """The ledger :func:`record_call` writes to when no ``ledger=`` is given: whatever
- :func:`bound_ledger` bound here, else the per-process fallback log
- (:func:`process_ledger_path`), so a call made outside any run — ``3dcode judge``, a
- bench script, a notebook — is still accounted for. There is no off switch: the
- ledger is the only record of money (``C3D_COST_LEDGER``, which read ``off`` or a path —
- and, as a Settings field, made every command die on anything but a boolean — went
- 2026-09-22)."""
+ """The ledger :func:`record_call` writes to: the bound one, else the per-process fallback
+ log, so a call outside any run is still accounted for. There is no off switch."""
global _fallback
led = _default_var.get()
if led is not _UNSET:
@@ -126,9 +102,7 @@ def default_ledger() -> CostLedger:
def process_ledger_path() -> Path:
- """The fallback log for calls made with no run context: one file per process
- under ``<cache_dir>/cost/``. Never inside a run directory, so it can never be
- mistaken for a run's own ledger."""
+ """The fallback log for calls with no run context: one file per process under ``<cache_dir>/cost/``."""
from codeverse3d.config import get_settings
base = Path(get_settings().cache_dir)
@@ -137,22 +111,17 @@ def process_ledger_path() -> Path:
def existing_ledger_path(workspace: str | Path) -> Path | None:
- """The ledger file a run actually has, or ``None``: ``telemetry/cost.jsonl``, the only one
- read (a walk of every run under ``$HOME`` on 2026-08-30 found 677 root ``cost_ledger.jsonl``
- files, every one a symlink to it)."""
+ """The run's ``telemetry/cost.jsonl`` if it exists, else ``None``."""
p = Path(workspace) / TELEMETRY_LEDGER
return p if p.is_file() else None
def open_run_ledger(workspace: str | Path) -> CostLedger:
- """The run's ledger, ``telemetry/cost.jsonl``, ready to append to (the file is created by
- its first row)."""
+ """The run's ledger (the file is created by its first row)."""
return CostLedger(Path(workspace) / TELEMETRY_LEDGER)
-#: context._stage is the same function; ledger already imports from context. NOT true
-#: of the neighbouring _as_role — that one returns Role.OTHER where context._role returns
-#: None, and Role.OTHER is truthy, so it survives CallContext.resolved().
+#: ``_as_role`` differs from ``context._role``: it returns Role.OTHER (truthy) where that returns None.
_as_stage = _stage
@@ -175,10 +144,7 @@ def price_call(
) -> tuple[float, dict[str, Any]]:
"""``(cost_usd, price fields)`` for one call.
- ``reprice=False`` keeps the cost the caller already computed (that is what
- was actually billed at the time) and only *records* which price row would
- explain it; ``reprice=True`` recomputes from the current table — how a cost
- audit re-values an old run."""
+ ``reprice=False`` keeps the caller's cost and only records the price row; ``True`` recomputes it."""
prov_model = model or usage.model
kind, provider, name = normalise_ids(backend or usage.backend, prov_model)
row = price_provenance(provider, name)
@@ -232,21 +198,10 @@ def record_call(
tallies: tuple[Tally, ...] | None = None,
**extra: Any,
) -> CallCost:
- """Append one priced call to the ledger, book it into the open tallies
- (``cost.tally`` — or ``tallies``, captured by a caller whose row lands later in a
- thread with no context), and return the row.
-
- Callers pass the ``Usage`` they already hold::
+ """Append one priced call to the ledger, book it into the open tallies (or ``tallies``), return the row.
- from codeverse3d.cost import record_call
- record_call(res.usage, run=ws.slug, round=idx, stage="baseline",
- role="generator", ledger=ws.root / "telemetry" / "cost.jsonl")
-
- Anything the caller leaves out (``run`` / ``round`` / ``stage`` / ``role``) is
- resolved from the ambient run context and the call label — see
- :mod:`codeverse3d.cost.context`.
-
- Never raises: a failure to account is logged, not propagated."""
+ Unstated ``run`` / ``round`` / ``stage`` / ``role`` resolve from the ambient context and label.
+ Never raises."""
u = usage or Usage()
ctx = attribute(CallContext(run=run, round=round, stage=_as_stage(stage), role=_as_role(role),
label=label), label=label)
@@ -291,12 +246,7 @@ def record_call(
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 the
- rest of the file.
-
- Paid-but-discarded round-trips are ``source="extra"`` rows and always count: nothing
- else records them."""
+ """Read a ledger file, or a run directory holding one; bad lines are skipped."""
p = Path(path)
if p.is_dir():
found = existing_ledger_path(p)
@@ -322,8 +272,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)."""
+ """The money and tokens of ``rows`` as one ``Usage`` (list price)."""
t = summarise(rows, dimensions=()).total
return 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,
@@ -331,8 +280,7 @@ def ledger_usage(rows: Iterable[CallCost]) -> Usage:
def summarise(rows: Iterable[CallCost], *, dimensions: Sequence[str] = DIMENSIONS) -> Summary:
- """Total + per-dimension buckets. ``dimensions`` may name any scalar field
- of :class:`CallCost` (defaults to :data:`DIMENSIONS`)."""
+ """Total + per-dimension buckets (``dimensions`` may name any scalar ``CallCost`` field)."""
out = Summary()
for row in rows:
out.total.add(row)
diff --git a/harness/codeverse3d/cost/tally.py b/harness/codeverse3d/cost/tally.py
index 2951dd76..3800ab7f 100644
--- a/harness/codeverse3d/cost/tally.py
+++ b/harness/codeverse3d/cost/tally.py
@@ -1,19 +1,8 @@
"""What the meters saw inside one block of work: its money and its lost time.
-A :class:`Tally` is opened with :func:`tally` around a block (a round, a timed step) and
-nests; everything metered inside the block books into every tally that is open:
-
-* ``cost.ledger.record_call`` books each priced row, so ``Tally.usage`` is exactly the
- money ``telemetry/cost.jsonl`` holds for the block — the round's cost is read here, never
- accumulated a second way;
-* the proxies in ``cost.instrument`` book each API call's and each agent session's wall
- clock and the part of it lost to provider errors (503 / 429 / overloaded / timeout
- retries and their back-off), per thread, so :meth:`Tally.lost_s` knows what the block
- lost even when its work ran side by side.
-
-:func:`timed` turns one block into a ``StepTime`` row — the unit a run's minutes are
-summed from (owner, 2026-09-22). The binding is a ``ContextVar``: ``proc.fan_out`` copies
-the context, so a worker thread books into its caller's tallies.
+A :class:`Tally` opened by :func:`tally` nests; the ledger books priced rows and the
+``cost.instrument`` proxies book wall/lost seconds into every open tally. :func:`timed`
+turns a block into a ``StepTime`` row. The binding is a ``ContextVar`` that fan-out copies.
"""
from __future__ import annotations
@@ -29,7 +18,6 @@ from codeverse3d.contracts.run import StepTime
class Tally:
- """The money and the lost seconds one block of work booked (see the module docstring)."""
def __init__(self) -> None:
self.usage = Usage()
@@ -47,10 +35,8 @@ class Tally:
t[1] += min(lost_s, wall_s)
def lost_s(self) -> float:
- """Seconds of the block's clock lost to provider errors. Calls in one thread ran one
- after the other, so their losses add up; threads ran side by side (fan-out sessions,
- judge samples, best-of-N candidates), so the block lost what its slowest thread would
- have been spared: ``max(wall) - max(wall - lost)`` over the threads."""
+ """Seconds lost to provider errors: losses add within a thread; across parallel threads
+ it is ``max(wall) - max(wall - lost)``."""
with self._lock:
if not self._time:
return 0.0
@@ -62,7 +48,6 @@ _open: ContextVar[tuple[Tally, ...]] = ContextVar("c3d_cost_tallies", default=()
@contextmanager
def tally() -> Iterator[Tally]:
- """Open a tally for the block (nested ones all receive what the block books)."""
t = Tally()
token = _open.set(_open.get() + (t,))
try:
@@ -72,8 +57,7 @@ def tally() -> Iterator[Tally]:
def open_tallies() -> tuple[Tally, ...]:
- """The tallies this execution context books into — captured by a caller whose work may
- land later in a thread with no context (a hedge loser's billed round-trip)."""
+ """The tallies this context books into, for callers whose work lands later in a thread without it."""
return _open.get()
@@ -89,8 +73,7 @@ def book_time(wall_s: float, lost_s: float) -> None:
@contextmanager
def timed(step: str, into: list[StepTime], *, round_index: int | None = None) -> Iterator[Tally]:
- """Time ``step`` into ``into`` — its wall clock and what it lost — whether the block
- returns or raises. A step that took no time (a cached stage) leaves no row."""
+ """Time ``step`` into ``into`` whether the block returns or raises; a ~0 s step leaves no row."""
t0 = time.monotonic()
with tally() as t:
try:
diff --git a/harness/codeverse3d/cost/types.py b/harness/codeverse3d/cost/types.py
index 13d97981..939f5690 100644
--- a/harness/codeverse3d/cost/types.py
+++ b/harness/codeverse3d/cost/types.py
@@ -1,12 +1,4 @@
-"""Typed rows and buckets for the cost ledger / audit.
-
-One :class:`CallCost` = one billable model or agent call. Rows are written
-append-only (``ledger.py``) and aggregated into :class:`Summary` buckets
-(``ledger.summarise``).
-
-Nothing here imports the orchestrator or the tracks: the cost package is a
-leaf so any caller (track, judge, bench script) can use it.
-"""
+"""Typed rows and buckets for the cost ledger: one :class:`CallCost` per billable call, aggregated into :class:`Summary`."""
from __future__ import annotations
@@ -16,15 +8,10 @@ from pydantic import BaseModel, ConfigDict, Field
class Stage(StrEnum):
- """Where in a run the money was spent. Mirrors the stage/round vocabulary
- of ``events.jsonl`` (``stage.start``/``generate.done`` labels)."""
+ """Where in a run the money was spent."""
PLAN = "plan"
- #: SKELETON / GATES / RENDER are *deterministic harness work* (no model call at
- #: all); kept in the enum so latency can be attributed to them from events
- #: (:data:`STAGE_ORDER`, ``audit.stage_latency``). ASSEMBLE is deterministic too
- #: since the scene track's ``compose`` agent session was removed (2026-09-22); older
- #: ledgers still carry it.
+ #: SKELETON / GATES / RENDER / ASSEMBLE are deterministic harness work, kept for latency attribution
SKELETON = "skeleton"
ASSETS = "assets"
ENV = "env"
@@ -42,12 +29,11 @@ class Stage(StrEnum):
OTHER = "other"
-#: the order stages are shown in (the cost report, the telemetry summary): the enum's own
+#: the order stages are shown in
STAGE_ORDER: tuple[str, ...] = tuple(s.value for s in Stage)
class Role(StrEnum):
- """Which job the model was doing (``Backends`` roles)."""
PLANNER = "planner"
GENERATOR = "generator"
@@ -56,10 +42,7 @@ class Role(StrEnum):
OTHER = "other"
-#: a bare ``GenerationTask.kind`` whose money belongs to a differently-named stage:
-#: ``MeteredAgent.run`` files the session row by ``job.kind`` — until 2026-08-29 only the
-#: tracks side knew these, so every scene zone / compose / asset / rebuild session landed in
-#: the ledger as ``other``.
+#: a bare ``GenerationTask.kind`` whose money belongs to a differently-named stage
_KIND_STAGES: dict[str, Stage] = {
"generate": Stage.BASELINE,
"rebuild": Stage.REPAIR,
@@ -75,14 +58,9 @@ _LABEL_STAGES: tuple[tuple[str, Stage], ...] = (
("env", Stage.ENV),
("baseline", Stage.BASELINE),
("refine", Stage.REFINE),
- # the static track's surface-detail round (labels "detail" / "detail_<scope>") was a
- # refine pass under another name. The round went on 2026-09-22; the row stays so a
- # label of a run that recorded one still reads as refine, not "other".
("detail", Stage.REFINE),
("candidate", Stage.CANDIDATE),
("cand", Stage.CANDIDATE),
- # the zone-layout planner calls (tracks/zone_layout.py) charge the guard as "plan";
- # unclassified, their ledger rows said other/other while the guard said plan
("zone-layout", Stage.PLAN),
("plan", Stage.PLAN),
("judge", Stage.JUDGE),
@@ -91,9 +69,8 @@ _LABEL_STAGES: tuple[tuple[str, Stage], ...] = (
def stage_for_label(label: str) -> Stage:
- """Map a task kind or a generation/trajectory label (``zone``, ``refine_drip_tray``,
- ``r00_baseline_repair1``, ``asset_koi``) to its :class:`Stage`. A bare kind or
- stage name wins outright; repair labels win over the label they repair."""
+ """Map a task kind or generation label (``zone``, ``asset_koi``) to its :class:`Stage`.
+ A bare kind wins outright; repair labels win over the label they repair."""
low = (label or "").strip().lower()
if not low:
return Stage.OTHER
@@ -129,7 +106,7 @@ _BACKEND_PROVIDER: dict[str, str] = {
"openai": "openai",
"claude-code": "anthropic",
"anthropic": "anthropic",
- "agy": "gemini", # the harness runs agy on Gemini API keys only (D103)
+ "agy": "gemini",
"antigravity": "gemini",
}
@@ -137,10 +114,7 @@ _BACKEND_PROVIDER: dict[str, str] = {
def split_model_id(backend: str, model: str) -> tuple[str, str]:
"""``("api-agent", "gemini:gemini-3.8-flash") -> ("gemini", "gemini-3.8-flash")``.
- Falls back to the backend kind when the id carries no provider prefix
- (``("codex", "gpt-6.1-sol") -> ("openai", "gpt-6.1-sol")``); an unknown
- backend yields provider ``""`` so pricing reports the model as unknown
- instead of guessing a rate."""
+ Without a provider prefix the backend kind decides; an unknown backend yields provider ``""``."""
m = (model or "").strip()
if ":" in m:
provider, _, rest = m.partition(":")
@@ -159,9 +133,7 @@ AGENT_KINDS = frozenset({"api-agent", "gemini-cli", "claude-code", "codex", "agy
def normalise_ids(backend: str, model: str) -> tuple[str, str, str]:
- """``("gemini:gemini-3.1-pro-preview", "")`` → ``(backend, provider, model)`` with
- one canonical spelling per model, so ``gemini:gemini-3.8-flash`` (judge id) and
- ``gemini-3.8-flash`` (per-call usage) bucket together."""
+ """``(backend, provider, model)`` with one canonical spelling per model, so judge ids and usage ids bucket together."""
provider, bare = split_model_id(backend, model)
kind = (backend or "").strip().lower()
if ":" in kind:
@@ -172,10 +144,9 @@ def normalise_ids(backend: str, model: str) -> tuple[str, str, str]:
class CallCost(BaseModel):
- """One priced call. Append-only ledger row; every field is JSON-scalar so
- old rows keep loading when new fields are added (all have defaults)."""
+ """One priced ledger row; every field is a JSON scalar with a default so old rows keep loading."""
- model_config = ConfigDict(extra="allow") # forward-compatible with newer writers
+ model_config = ConfigDict(extra="allow")
ts: float = 0.0
run: str = ""
@@ -208,30 +179,20 @@ class CallCost(BaseModel):
cache_hit: bool = False
outcome: str = "ok" # ok | error | timeout | budget | degraded | discarded
n_calls: int = 1 # >1 when a row aggregates a whole agent session
- #: extra = a round-trip that was discarded yet billed (hedge loser, charged-but-invalid
- #: reply); nothing else records it, so unlike ``attempt`` it counts in every total
- #: estimate = a session whose vendor reported no usage (a killed codex turn), priced from its stream
+ #: extra = a discarded but billed round-trip (counts in every total); estimate = priced from the stream
source: str = "live" # live | record | events | transcript | stdout | residual | session | estimate | attempt | extra
- #: which API key served the call, as its last 4 chars ("…ab12") — never the key
- #: itself; "" for a failed call, a session row, or a row older than 2026-08-26
+ #: last 4 chars of the API key that served the call ("…ab12"); "" when none
key: str = ""
- #: round-trips the retry machine issued for this call (hedged siblings included);
- #: 1 = clean, 0 = not recorded
+ #: round-trips issued for this call (1 = clean, 0 = not recorded)
attempts: int = 0
- #: joins a call's per-attempt rows (``source="attempt"``) to its logical row;
- #: minted per logical call by ``instrument.MeteredChatModel`` (uuid4 hex), ""
- #: for rows older than 2026-08-27 and for writers that do not mint one
+ #: joins a call's per-attempt rows to its logical row
call_id: str = ""
- #: 1-based round-trip number within its logical call (``source="attempt"`` rows)
attempt: int = 0
- #: True when this round-trip's response was thrown away: a hedge loser, or a
- #: failed try of a call that went on to retry. A paid one is ``source="extra"``
- #: and counts; a free one is ``source="attempt"`` and is filtered out
+ #: this round-trip's response was thrown away (paid: ``source="extra"``, counted; free: ``attempt``, filtered)
discarded: bool = False
class CostBucket(BaseModel):
- """Aggregate of many :class:`CallCost` rows under one key."""
key: str = ""
n_calls: int = 0
@@ -272,12 +233,11 @@ class CostBucket(BaseModel):
@property
def attempts_per_call(self) -> float:
- """Mean round-trips per call (1.0 = every call landed first time); 0 when unrecorded."""
+ """Mean round-trips per call; 0 when unrecorded."""
return self.attempts / self.n_attempted if self.n_attempted else 0.0
class Summary(BaseModel):
- """``summarise()`` output: a total plus one bucket map per dimension."""
total: CostBucket = Field(default_factory=CostBucket)
by: dict[str, dict[str, CostBucket]] = Field(default_factory=dict)
diff --git a/harness/codeverse3d/doctor.py b/harness/codeverse3d/doctor.py
index da68596f..58273c3c 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. Moved out of ``cli/`` 2026-08-28: only the typer
-shim is a CLI concern (tests/install imports these checks as documentation facts).
+puppeteer, the GPU probe, keys, the machine-wide in-flight slots, the vendor CLIs, MCP.
"""
from __future__ import annotations
@@ -17,17 +16,8 @@ Row = tuple[str, str, str]
_PY_DEPS = ("pydantic", "pydantic_settings", "typer", "rich", "jinja2", "yaml", "numpy", "trimesh", "fcl", "PIL", "pyarrow",
"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`
-#: were absent from the list entirely until 2026-08-24, so an environment installed without
-#: [graphics] passed doctor "21/21 importable" and then failed in the graphics track with
-#: "no usable OpenGL context: No module named 'moderngl'" — a missing pip package reported
-#: as a GPU/driver problem (docs/INSTALL.md §4 promises every extra is listed here).
-#: EVERY module of every extra must be here, or the base install misreports itself: the
-#: map was missing scipy/networkx/pyarrow, so a fresh clone installed exactly as
-#: 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.
+#: modules from an OPTIONAL extra: missing is a WARN naming the extra, not a broken install.
+#: Every module of every extra must be listed here or the base install misreports itself.
_OPTIONAL_DEPS = {"shapely": "mesh", "networkx": "mesh", "matplotlib": "mesh",
"yourdfpy": "urdf", "scipy": "urdf", "mcp": "mcp",
"moderngl": "graphics", "cadquery": "cad", "pyarrow": "flywheel"}
@@ -76,11 +66,9 @@ def check_blender() -> list[Row]:
return [("blender", "OK" if okk else "FAIL", f"{v} @ {b}")]
-#: one headless Blender run: the Cycles CUDA device list, one timed 256x144 32-spp Cycles frame on it
-#: (the judged-frame fast path: GPU OIDN + persistent data, render_bpy_scene.setup_render) and (with
-#: EEVEE) a 32x18 EEVEE frame whose GL renderer string says whether the d3d12 env put it on the GPU
-#: or it fell to llvmpipe. OptiX is never probed (no libnvoptix under WSL2: init error 7804, and
-#: switching the compute device type back afterwards crashes Blender 5.2.2).
+#: one headless Blender run: the Cycles CUDA device list, a timed Cycles frame, and (with EEVEE) a
+#: tiny EEVEE frame whose GL renderer says GPU or llvmpipe. OptiX is never probed (it crashes
+#: Blender under WSL2).
_BLENDER_RENDER_PROBE = """
import json, sys, time
import bpy
@@ -127,8 +115,7 @@ print("C3D_DOCTOR " + json.dumps(out))
def check_blender_render(*, eevee: bool = True, timeout_s: int = 120) -> list[Row]:
- """What scene_blender's judged frames render on (owner D1/D8): Cycles on CUDA or on the CPU,
- EEVEE on the GPU or silently on llvmpipe, and the machine-wide GPU render slots."""
+ """What scene_blender's judged frames render on: Cycles CUDA / CPU, EEVEE GPU / llvmpipe, GPU slots."""
import json
from codeverse3d.languages.blender import blender_env
@@ -191,7 +178,6 @@ def check_node() -> list[Row]:
except RuntimeError as e: # non-editable install without C3D_RUNTIME_JS
rows.append(("runtime_js", "FAIL", str(e)))
return rows
- # a missing, torn or non-object package.json is the same broken install: never a crash
three = read_json_or_none(rj / "node_modules" / "three" / "package.json")
pup = read_json_or_none(rj / "node_modules" / "puppeteer" / "package.json")
if three is not None:
@@ -210,9 +196,8 @@ def check_node() -> list[Row]:
return rows
-#: ``release()``, never ``browser.close()``: by default the handle is the daemon's SHARED
-#: browser, and close() sends CDP Browser.close, which takes it down under any concurrent
-#: run rendering on it. release() disconnects a shared browser and closes an owned one.
+#: ``release()``, never ``browser.close()``: the handle may be the daemon's shared browser, which
+#: close() would take down under concurrent runs.
_PROBE_JS = (
"const {launchBrowser}=require(process.argv[1]);"
"launchBrowser({gpu:'auto'}).then(async r=>{console.log(JSON.stringify({gpu:r.gpu,renderer:r.renderer}));"
@@ -249,10 +234,6 @@ def check_gpu_probe(timeout_s: int = 120) -> list[Row]:
def check_pool(live: bool) -> list[Row]:
- """The key pool's live picture: in-flight, and the outcomes this process has seen.
-
- Only meaningful once something has used the pool this process, so it is part
- of ``--live`` (``check_keys`` makes one call just before)."""
from codeverse3d.models.gemini import shared_pool
s = get_settings()
diff --git a/harness/codeverse3d/judges/base.py b/harness/codeverse3d/judges/base.py
index 30f2e36b..cb04ccac 100644
--- a/harness/codeverse3d/judges/base.py
+++ b/harness/codeverse3d/judges/base.py
@@ -1,5 +1,4 @@
-"""``JudgeInput``, the ONE way a round becomes one (``round_input`` + ``plan_summary``: the in-run
-judge and every replay of a stored round build it here) and the pure replay helpers."""
+"""``JudgeInput`` and the one place a round becomes one (``round_input``), plus the pure replay helpers."""
from __future__ import annotations
@@ -22,18 +21,15 @@ from codeverse3d.contracts.spec import Spec
from codeverse3d.conventions import to_authoring_frame
from codeverse3d.workspace import Workspace
-#: tracks whose rounds have one canonical GLB the judge slice channel (D48) may cut;
-#: scene and graphics have none and are unaffected.
+#: tracks whose rounds have one canonical GLB the judge slice channel may cut
SLICE_TRACKS = ("static_object", "articulated_object")
-#: the rubric of a static object judged against reference images: it adds the measured silhouette criterion
+#: rubric for a static object judged against reference images (adds the silhouette criterion)
REFERENCE_RUBRIC = "reference"
def run_rubric(spec: Spec, default: str = "") -> str:
- """The rubric a run of ``spec`` is judged on — the ONE rule, for the run loop and every replay.
- A static object with reference images is scored on :data:`REFERENCE_RUBRIC`; any other run on
- ``default`` (a track's own) or its track's. Other tracks keep their rubric with references:
- their judge still sees the images."""
+ """The rubric a run of ``spec`` is judged on: :data:`REFERENCE_RUBRIC` for a static object with
+ references, else ``default`` or the track's own."""
if spec.references and spec.track is Track.STATIC_OBJECT:
return REFERENCE_RUBRIC
return default or TRACK_INFO[spec.track].rubric
@@ -60,13 +56,9 @@ class JudgeInput(BaseModel):
)
-# ===================================================================== one round → one JudgeInput
def plan_summary(plan: Plan | None, language: str) -> str:
- """The plan digest the judge reads, for every track. An object's overall size is written
- W×H×D in the GLB frame (Y-up) — the frame of the measurement table beside it — so a Z-up
- plan's (W, D, H) is permuted first. Four track methods and a fifth dict digest for the
- replays used to write this: a replayed Z-up object read W×D×H, and a replayed shader lost
- its style, passes, key visuals and motion."""
+ """The plan digest the judge reads. An object's size is written W×H×D in the GLB frame (Y-up),
+ so a Z-up plan's (W, D, H) is permuted first."""
if isinstance(plan, GraphicsPlan):
passes = ", ".join(f"{p.name} ({p.kind})" for p in plan.passes)
return (f"{plan.title}: {plan.summary} Style: {plan.style}. Passes: {passes}. Key visuals: {'; '.join(plan.key_visuals)}. "
@@ -88,28 +80,18 @@ def plan_summary(plan: Plan | None, language: str) -> str:
def round_input(spec: Spec, plan: Plan | None, rnd: RoundRecord, *, renders: RenderSet, gates: Sequence[GateReport],
previous: Judgment | None, extra_context: str, geometry_views: RenderSet | None,
glb_path: str | None) -> JudgeInput:
- """The judge payload of one round. The in-run judge (``tracks/steps._judge``) builds it from the
- round in hand, every replay of a stored round (``3dcode judge``, calibration:
- ``cli/_judge.build_judge_input``) from disk — so a replay reads what the in-run judge read."""
+ """The judge payload of one round, built from the round in hand or replayed from disk."""
return JudgeInput(
spec=spec, renders=renders, measurement=rnd.measurement, gates=list(gates),
acceptance=list(getattr(plan, "acceptance", None) or []), plan_summary=plan_summary(plan, spec.language),
part_names=[p.name for p in plan.parts] if isinstance(plan, StaticPlan) else [],
round_index=rnd.index, previous=previous, extra_context=extra_context, geometry_views=geometry_views,
- # D48: the round's canonical GLB feeds the conditional slice channel (object tracks only)
glb_path=glb_path if spec.track.value in SLICE_TRACKS else None,
)
-# ===================================================================== round replay
def resolve_paths(ws: Workspace, rs: RenderSet | None) -> RenderSet | None:
- """Render paths out of a round record, resolved against THIS workspace.
-
- Delegates to ``Workspace.rebase``: this used to rebase only paths for which
- ``is_absolute()`` was False, which made it a no-op against every record the harness
- itself writes (they are all absolute) — so a moved or archived run kept pointing at
- the host it was produced on.
- """
+ """Render paths out of a round record, resolved against THIS workspace."""
if rs is None:
return None
fixed = [v.model_copy(update={"path": str(ws.rebase(v.path))}) for v in rs.views]
@@ -119,8 +101,7 @@ def resolve_paths(ws: Workspace, rs: RenderSet | None) -> RenderSet | None:
def judged_subset(rs: RenderSet | None) -> RenderSet | None:
- """The views the in-run judge actually saw: the per-view ``judge`` flags
- stamped at render time; legacy rounds (no flags) keep every stored view."""
+ """The views the in-run judge saw (per-view ``judge`` flags); rounds without flags keep every view."""
if rs is None or not any(v.judge is not None for v in rs.views):
return rs
return rs.model_copy(update={"views": [v for v in rs.views if v.judge]})
diff --git a/harness/codeverse3d/judges/pairwise.py b/harness/codeverse3d/judges/pairwise.py
index 380bdbbc..6776b366 100644
--- a/harness/codeverse3d/judges/pairwise.py
+++ b/harness/codeverse3d/judges/pairwise.py
@@ -1,11 +1,7 @@
"""``PairwiseJudge``: which of two candidates better satisfies the spec?
-Position bias is real, so the comparison runs TWICE with A/B swapped (the two
-orderings run in parallel via ``codeverse3d.proc``); the winner is declared
-only when both orderings agree, otherwise ``tie``. Each call sees the brief,
-the rubric's criteria (titles + descriptions) and ONE 2×2 montage per candidate
-(the 4 most informative views — never a big sheet: VLM judges flip with many
-tiles).
+The comparison runs twice with A/B swapped; a winner needs both orderings to agree, else ``tie``.
+Each call sees one 2×2 montage per candidate.
"""
from __future__ import annotations
@@ -52,7 +48,7 @@ class CriterionWinner(BaseModel):
class PairwiseReply(BaseModel):
- """Wire schema for one ordering (lists, not dicts: provider schemas dislike free-form keys)."""
+ """Wire schema for one ordering."""
winner: Literal["A", "B", "tie"] = Field(description="which candidate better satisfies the brief overall")
confidence: float = Field(ge=0.0, le=1.0, description="0.5 = coin flip, 1.0 = certain")
@@ -93,21 +89,19 @@ class PairwiseJudge:
self, spec: Spec, renders_a: RenderSet, renders_b: RenderSet, *,
rubric: str | Rubric = "static_object"
) -> PairwiseResult:
- """The two orderings' requests are tagged ``pairwise:fwd`` / ``pairwise:swap``
- so logs — and deterministic fakes — can tell concurrent orderings apart."""
rub = rubric if isinstance(rubric, Rubric) else load_rubric(rubric)
usage = Usage()
verdicts: list[tuple[Winner, float, list[str]]] = []
orderings: list[dict] = []
errors: list[str] = []
- self.model # noqa: B018 — materialise the lazy chat model once, before the threads race
+ self.model # noqa: B018
results = fan_out(
(False, True), lambda swapped: self._ordering(spec, rub, renders_a, renders_b, swapped),
max_workers=2, label="pairwise:orderings", item_name=lambda s: f"swapped={s}",
)
- for res in results: # ordered accumulation: (fwd, swap)
+ for res in results:
if isinstance(res, Exception):
- raise res # ModelError / parse failures are captured; anything else is a bug
+ raise res
u, verdict, ordering, error = res
usage = usage + u
if error:
@@ -123,8 +117,6 @@ class PairwiseJudge:
def _ordering(
self, spec: Spec, rub: Rubric, renders_a: RenderSet, renders_b: RenderSet, swapped: bool
) -> tuple[Usage, tuple[Winner, float, list[str]] | None, dict | None, str]:
- """One A/B ordering → ``(usage, verdict, ordering, error)`` (never raises for
- model/parse failures — the caller aggregates them as errors)."""
first, second = (renders_b, renders_a) if swapped else (renders_a, renders_b)
req = self._request(spec, rub, first, second, label="pairwise:swap" if swapped else "pairwise:fwd")
try:
@@ -136,7 +128,7 @@ class PairwiseJudge:
reply = PairwiseReply.model_validate(payload)
except JsonParseError as e:
return resp.usage, None, None, f"parse: no JSON object in reply: {e}"
- except ValueError as e: # pydantic's ValidationError
+ except ValueError as e:
return resp.usage, None, None, f"parse: {e}"
winner = _map_winner(reply.winner, swapped)
reasons = [_unswap_text(r, swapped) for r in reply.reasons]
@@ -145,7 +137,6 @@ class PairwiseJudge:
"criteria_won": {c.criterion: _map_winner(c.winner, swapped) for c in reply.criteria_won}}
return resp.usage, (winner, reply.confidence, reasons), ordering, ""
- # ------------------------------------------------------------------ prompt
def _request(
self, spec: Spec, rub: Rubric, first: RenderSet, second: RenderSet, *, label: str = "pairwise"
) -> ChatRequest:
@@ -168,12 +159,10 @@ class PairwiseJudge:
)
def _side_images(self, tag: str, rs: RenderSet, *, scene: bool) -> list[tuple[str, ImagePart]]:
- """One 2×2 montage of the candidate's most informative views (plus its pose sheet / geometry
- montage if any), from the views the verdict judge saw, ranked for the track: a scene's
- own cameras first, as the verdict judge ranks them."""
+ """One 2×2 montage of the candidate's most informative views, ranked for the track."""
montages = plan_montages(judged_subset(rs), scene=scene, max_montages=2, detail_crops=0)
out: list[tuple[str, ImagePart]] = []
- for i, m in enumerate(montages, 1): # plan_montages already caps a grid at MAX_TILES=4
+ for i, m in enumerate(montages, 1):
lbl = f"CANDIDATE {tag} — " + montage_label(m, i, len(montages))
strip = f"CANDIDATE {tag} — {m.title.split(' (')[0]}"
png = render_montage(m, cache_dir=self.cache_dir, tile_px=MONTAGE_TILE_PX)
@@ -205,11 +194,10 @@ def _combine(
winners = {v[0] for v in verdicts}
reasons = [r for v in verdicts for r in v[2]][:8]
conf = statistics.fmean(v[1] for v in verdicts)
- if len(verdicts) == 1: # only one ordering succeeded → downgrade confidence, keep winner
+ if len(verdicts) == 1:
return PairwiseResult(winner=verdicts[0][0], confidence=round(conf * 0.5, 3), reasons=reasons,
orderings=orderings, usage=usage, error=" || ".join(errors))
if len(winners) == 1:
return PairwiseResult(winner=verdicts[0][0], confidence=round(conf, 3), reasons=reasons, orderings=orderings, usage=usage)
- # disagreement (position bias or genuine ambiguity) → tie, low confidence
return PairwiseResult(winner="tie", confidence=round(min(0.4, 1.0 - conf), 3), reasons=reasons, orderings=orderings,
usage=usage, error="orderings disagree")
diff --git a/harness/codeverse3d/judges/prompt_builder.py b/harness/codeverse3d/judges/prompt_builder.py
index 2e33bc14..2d207ed2 100644
--- a/harness/codeverse3d/judges/prompt_builder.py
+++ b/harness/codeverse3d/judges/prompt_builder.py
@@ -1,14 +1,7 @@
-"""What the judge SEES: image prep, montage planning and message assembly.
-
-* image prep (``prepare_image``): every image sent to a judge is downscaled
- (≤ ``max_px`` on the long side) and carries a burnt-in label (``VIEW 5/14 — front ·
- az 0° el 0°``) the model can cite as evidence; prepared files are cached under
- ``<cache_dir>/<sha>.png`` keyed by source path, mtime, size, max_px and label text.
-* montage planning (``plan_montages`` / ``render_montage``): ranked views packed into
- ≤2×2 sheets — shaded, geometry (clay/normals), poses, detail crops.
-* message assembly (``build_judge_messages``): rubric + montages + measurements +
- acceptance items → the ``ChatRequest`` system/messages; ``judge_prompt_hash`` is the
- verdict's provenance stamp.
+"""What the judge sees: image prep, montage planning and message assembly.
+
+``prepare_image`` downscales and labels every image; ``plan_montages`` / ``render_montage`` pack ranked views
+into ≤2×2 sheets; ``build_judge_messages`` assembles the request; ``judge_prompt_hash`` stamps a verdict.
"""
from __future__ import annotations
@@ -53,9 +46,7 @@ from codeverse3d.spatial.measure import measure_summary_table
from codeverse3d.spatial.sheet import crop_region, load_font, montage_2x2
_PRESETS: dict[str, ViewPreset] = {v.name: v for v in (*OBJECT_VIEWS, *SCENE_VIEWS)}
-#: Clay tiles label their OWN cameras: ``OBJECT_CLAY_VIEWS.top`` sits at el 88 while the
-#: rig's ``top`` is el 90, so a geometry-mode tile resolves here before ``_PRESETS`` —
-#: labelling a clay tile with the rig's numbers was the rig_ab payload_c.py pitfall.
+#: clay tiles label their own cameras (``OBJECT_CLAY_VIEWS.top`` is el 88, the rig's is 90), so they resolve here first
_CLAY_PRESETS: dict[str, ViewPreset] = {v.name: v for v in OBJECT_CLAY_VIEWS}
@@ -68,8 +59,7 @@ def default_cache_dir() -> Path:
def view_az_el(view: RenderView) -> tuple[float, float] | None:
- """Azimuth/elevation (deg) of a view: from the preset name (geometry-mode tiles
- prefer the clay rig's own cameras), else from camera geometry (Y-up)."""
+ """Azimuth/elevation (deg) of a view: from the preset name, else from camera geometry (Y-up)."""
if view.mode != "shaded" and view.name in _CLAY_PRESETS:
p = _CLAY_PRESETS[view.name]
return p.azimuth_deg, p.elevation_deg
@@ -83,7 +73,7 @@ def view_az_el(view: RenderView) -> tuple[float, float] | None:
horiz = math.hypot(dx, dz)
if horiz < 1e-9 and abs(dy) < 1e-9:
return None
- az = math.degrees(math.atan2(dx, dz)) % 360.0 # 0 = +Z front, CCW from above
+ az = math.degrees(math.atan2(dx, dz)) % 360.0
el = math.degrees(math.atan2(dy, horiz))
return round(az, 1), round(el, 1)
return None
@@ -92,13 +82,10 @@ def view_az_el(view: RenderView) -> tuple[float, float] | None:
def prepare_image(
src: str | Path, *, label: str = "", max_px: int = 768, cache_dir: Path | None = None
) -> Path:
- """Downscale ``src`` to ≤ ``max_px`` on its long side and burn ``label`` into a top strip.
-
- Returns the cached PNG path. Raises ``JudgeImageError`` if the source is missing.
- """
+ """Downscale ``src`` to ≤ ``max_px`` and burn ``label`` into a top strip; returns the cached PNG path."""
cache = Path(cache_dir) if cache_dir else default_cache_dir()
cache.mkdir(parents=True, exist_ok=True)
- out = cache / f"{_key([_stat(str(src)), str(max_px), label])}.png" # _stat raises JudgeImageError
+ out = cache / f"{_key([_stat(str(src)), str(max_px), label])}.png"
if out.is_file():
return out
with Image.open(src) as im:
@@ -109,9 +96,9 @@ def prepare_image(
im = im.resize((max(1, round(w * scale)), max(1, round(h * scale))), Image.LANCZOS)
if label:
im = _with_label_strip(im, label)
- tmp = unique_tmp(out) # unique per writer: concurrent judges share the cache
+ tmp = unique_tmp(out)
im.save(tmp, format="PNG", optimize=True)
- tmp.replace(out) # atomic; a concurrent identical write simply wins last
+ tmp.replace(out)
return out
@@ -123,7 +110,6 @@ def _with_label_strip(im: Image.Image, label: str) -> Image.Image:
canvas.paste(im, (0, strip_h))
draw = ImageDraw.Draw(canvas)
text = label
- # truncate to fit
while text and draw.textlength(text, font=font) > w - 12 and len(text) > 8:
text = text[:-2]
font_px = getattr(font, "size", 11)
@@ -135,32 +121,22 @@ def image_part(path: Path, label: str) -> ImagePart:
return ImagePart(path=str(path), mime="image/png", label=label)
-# ===================================================================== montage
MontageKind = Literal["shaded", "geometry", "poses", "pose_sheet", "detail"]
-#: modes that show geometry without material/lighting noise: every render mode but shaded
GEOMETRY_MODES = tuple(m for m in RENDER_MODES if m != "shaded")
-#: most-informative-first order for the object rig (names from conventions.OBJECT_VIEWS):
-#: montage 1 = {front_right_high, back_left_high, top, bottom}, so a montage-cap
-#: truncation still sees the underside; then the eye ring, then the remaining rings.
+#: most-informative-first order for the object rig; montage 1 includes the underside
OBJECT_RANK = (
- # a STORED pre-D47 run (and a clay tile) ranks by its rig twin, ``conventions.view_key``
"front_right_high", "back_left_high", "top", "bottom",
"front", "right", "back", "left",
"front_right_low", "back_left_low", "front_left_high", "back_right_high",
"front_left_low", "back_right_low",
)
-#: scene rig: authored cameras first (graded for composition), then the overview rig.
-#: The rig names come from ``conventions.SCENE_VIEWS`` — anything else in a scene render
-#: set is a camera the SCENE authored, whatever it is called (they are PascalCase plan
-#: names such as ``Establishing``, never a fixed prefix).
+#: scene rig: authored cameras first, then the overview rig; any name not in ``conventions.SCENE_VIEWS`` is authored
SCENE_OVERVIEW_RANK = ("overview_front_right", "overview_back_left", "overview_top", "overview_low_front",
"eye_front", "eye_right", "eye_back_left")
SCENE_RIG_NAMES = frozenset(v.name for v in SCENE_VIEWS) | frozenset(SCENE_OVERVIEW_RANK)
-#: the rig tiles a contact crop may be cut from (the judged ``overview_*`` views; the eye
-#: rig never reaches the judge, so a crop from it would cite a tile the judge cannot see)
+#: the rig tiles a contact crop may be cut from (only the judged ``overview_*`` views)
SCENE_OVERVIEW_NAMES = frozenset(n for n in SCENE_OVERVIEW_RANK if n.startswith("overview"))
-#: the gate whose findings become contact crops and the MEASURED PLACEMENT line
PLACEMENT_GATE = "scene_placement"
POSE_PREFIX = "pose_"
POSE_SHEET_NAMES = ("articulation_sheet", "pose_sheet")
@@ -171,15 +147,13 @@ _POSITIONS = {
4: ("top-left", "top-right", "bottom-left", "bottom-right"),
}
MAX_TILES = 4
-#: payload knobs (defaults; ``Settings.judge`` overrides per run). 5 montages carry the
-#: 14-view rig + the clay geometry montage; 3 silently dropped the low ring + poles (D47).
+#: payload knobs (defaults; ``Settings.judge`` overrides per run)
MAX_MONTAGES = 5
MAX_DETAIL_CROPS = 2
@dataclass(frozen=True)
class Montage:
- """One judge image: 1–4 tiles (or a pass-through sheet / a detail crop)."""
kind: MontageKind
tiles: tuple[RenderView, ...]
@@ -193,7 +167,6 @@ class Montage:
return self.kind == "detail"
-# --------------------------------------------------------------------------- view grouping / ranking
def is_pose_view(v: RenderView) -> bool:
return v.name.startswith(POSE_PREFIX)
@@ -207,12 +180,11 @@ def is_geometry_view(v: RenderView) -> bool:
def rank_views(views: list[RenderView], *, scene: bool) -> list[RenderView]:
- """Most informative first; unknown names keep their given order after the known ones."""
if scene:
def key(iv: tuple[int, RenderView]) -> tuple[int, int, int]:
i, v = iv
if v.name not in SCENE_RIG_NAMES:
- return (0, 0, i) # the scene's OWN cameras: the pictures being graded
+ return (0, 0, i)
if v.name in SCENE_OVERVIEW_RANK:
return (1, SCENE_OVERVIEW_RANK.index(v.name), i)
return (2, 0, i)
@@ -237,8 +209,7 @@ def plan_montages(
detail_crops: int = MAX_DETAIL_CROPS,
gates: Sequence[GateReport] = (),
) -> list[Montage]:
- """Decide which montages a judge call gets (see module docstring for the priority).
- ``gates`` feed a scene's contact crops (``plan_detail_crops``); objects ignore them."""
+ """Decide which montages a judge call gets; ``gates`` feed a scene's contact crops."""
shaded = [v for v in renders.views if not (is_pose_view(v) or is_pose_sheet(v) or is_geometry_view(v))]
poses = [v for v in renders.views if is_pose_view(v)]
sheets = [v for v in renders.views if is_pose_sheet(v)]
@@ -260,7 +231,7 @@ def plan_montages(
candidates.append(Montage("geometry", tuple(geo), f"GEOMETRY-ONLY views ({geo[0].mode}: no materials — look for holes, black/inverted faces, intersections, gaps)"))
for extra in shaded_groups[1:]:
candidates.append(Montage("shaded", tuple(extra), "SHADED views (remaining)"))
- if sheets and poses: # the sheet already shows the poses; the 2×2 is a larger-tile duplicate, lowest priority
+ if sheets and poses:
candidates.append(Montage("poses", tuple(poses[:MAX_TILES]), "POSED views (joints moved by the harness; tile label = pose)"))
chosen = candidates[: max(0, max_montages)]
chosen.extend(plan_detail_crops(shaded, scene=scene, gates=gates, limit=max(0, detail_crops)))
@@ -268,7 +239,6 @@ def plan_montages(
def _match_geometry(geometry: list[RenderView], primary: tuple[RenderView, ...]) -> list[RenderView]:
- """Prefer geometry views whose names match the primary shaded montage, then the rest."""
names = [v.name for v in primary]
by_name = {v.name: v for v in geometry}
out = [by_name[n] for n in names if n in by_name]
@@ -278,14 +248,8 @@ def _match_geometry(geometry: list[RenderView], primary: tuple[RenderView, ...])
def plan_detail_crops(shaded: list[RenderView], *, scene: bool, gates: Sequence[GateReport] = (),
limit: int = MAX_DETAIL_CROPS) -> list[Montage]:
- """The crops a verdict sends, ``limit`` = ``Settings.judge.detail_crops`` (0 = none).
-
- Objects: the centre crop of the best view at 2× (detail legibility) + the ground band of
- the lowest view, cut to ``limit``. Scenes (scene, 2026-10-14): the centre crop plus up
- to ``limit`` CONTACT CROPS — close-ups around the placement findings the gate measured
- (``plan_contact_crops``), so the judge sees the daylight under a base at crop scale
- instead of reading the gate's sentence about it.
- """
+ """The crops a verdict sends, ``limit`` = ``Settings.judge.detail_crops``: a centre crop plus a ground band
+ for objects, plus contact crops around placement findings for scenes."""
if not shaded or limit <= 0:
return []
centre = Montage("detail", (shaded[0],), f"DETAIL CROP — centre of {shaded[0].name} at 2×",
@@ -302,20 +266,13 @@ def plan_detail_crops(shaded: list[RenderView], *, scene: bool, gates: Sequence[
return out[:limit]
-# --------------------------------------------------------------------------- scene contact crops
-#: a crop smaller than this of the frame (per axis) would upscale a 1024-px tile past ~4.5×
+#: a crop smaller than this fraction of the frame (per axis) would over-upscale a tile
CONTACT_CROP_MIN_FRAC = 0.22
-#: padding around the projected asset box, as a fraction of the box's own size: the gap
-#: under a base and the neighbour a part passes through are OUTSIDE the box
+#: padding around the projected asset box, as a fraction of the box's size
CONTACT_CROP_PAD = 0.6
-#: an asset filling more than this of the tile on either axis needs no crop: the tile is the crop
CONTACT_CROP_MAX_FRAC = 0.8
-#: which rig tile a crop prefers, by the tile's elevation: ``(upper bound, weight)`` rows, the
-#: first whose bound exceeds the elevation applies. The ground-level contact tile (< 10°) is
-#: built for this and counts 1.5×; a 32° overview counts as drawn; a top-down tile (≥ 60°)
-#: shows a base's shadow, not its gap, and is the last resort at a quarter.
+#: which rig tile a crop prefers, by elevation: ``(upper bound, weight)`` rows; the first bound above the elevation applies
CONTACT_TILE_WEIGHT: tuple[tuple[float, float], ...] = ((10.0, 1.5), (60.0, 1.0), (90.1, 0.25))
-#: placement kinds that carry a per-asset box, and how their magnitude is printed in the label
CONTACT_KINDS: dict[str, tuple[str, str]] = {
"floating": ("gap_m", "{:.2f} m"), "unsupported": ("gap_m", "{:.2f} m"), "cantilevered": ("gap_max_m", "{:.2f} m"),
"sunken": ("sunk_m", "{:.2f} m"), "interpenetration": ("overlap", "{:.0%}"), "scale": ("factor", "{:g}×"),
@@ -323,9 +280,7 @@ CONTACT_KINDS: dict[str, tuple[str, str]] = {
def _camera_frame(view: RenderView) -> tuple[tuple[float, float, float], ...] | None:
- """``(eye, forward, right, up)`` of a view's camera in the GLB frame, with THREE's lookAt
- roll (world up +Y unless the view is vertical, then −Z) — the convention ``orbit.mjs``
- fits the rig with, so a projection here lands where the tile drew it."""
+ """``(eye, forward, right, up)`` of a view's camera in the GLB frame, with three.js lookAt roll."""
if view.camera_position is None or view.look_at is None:
return None
eye = tuple(float(c) for c in view.camera_position)
@@ -349,10 +304,8 @@ def _view_aspect(view: RenderView) -> float:
def project_box(view: RenderView, center: Sequence[float], size: Sequence[float]) -> tuple[float, float, float, float] | None:
- """The frame-fraction box ``(left, top, right, bottom)`` the GLB-frame AABB ``center ±
- size/2`` covers in ``view`` (vertical ``fov``, the rig's 50° when the record has none), or
- None when the camera is unknown, a corner is behind the lens, or the box's centre is
- outside the frame. Fractions may run past 0..1 for a box that is partly out of frame."""
+ """The frame-fraction box ``(left, top, right, bottom)`` a GLB-frame AABB covers in ``view``, or None if
+ the camera is unknown, a corner is behind the lens, or the centre is outside the frame."""
frame = _camera_frame(view)
if frame is None:
return None
@@ -373,13 +326,13 @@ def project_box(view: RenderView, center: Sequence[float], size: Sequence[float]
y = (rel[0] * u[0] + rel[1] * u[1] + rel[2] * u[2]) / (depth * tan_v)
us.append((x + 1) / 2)
vs.append((1 - y) / 2)
- if not (0.0 <= us[0] <= 1.0 and 0.0 <= vs[0] <= 1.0): # the centre must be in the picture
+ if not (0.0 <= us[0] <= 1.0 and 0.0 <= vs[0] <= 1.0):
return None
return min(us[1:]), min(vs[1:]), max(us[1:]), max(vs[1:])
def _finding_box(f: GateFinding) -> tuple[list[float], list[float]] | None:
- """``(center, size)`` from a placement finding's ``data.bbox`` (scene_placement, 2026-10-14), or None."""
+ """``(center, size)`` from a placement finding's ``data.bbox``, or None."""
box = f.data.get("bbox") if isinstance(f.data, dict) else None
if not isinstance(box, dict):
return None
@@ -402,8 +355,7 @@ def _contact_label(f: GateFinding) -> str:
def _crop_around(box: tuple[float, float, float, float]) -> tuple[float, float, float, float]:
- """A crop window around a projected box: padded by ``CONTACT_CROP_PAD``, never under
- ``CONTACT_CROP_MIN_FRAC`` on either axis, shifted (not shrunk) back inside the frame."""
+ """A crop window around a projected box: padded, never under the minimum fraction, shifted inside the frame."""
left, top, right, bottom = box
cx, cy = (left + right) / 2, (top + bottom) / 2
hw = max((right - left) * (1 + CONTACT_CROP_PAD) / 2, CONTACT_CROP_MIN_FRAC / 2)
@@ -423,8 +375,7 @@ def _crop_around(box: tuple[float, float, float, float]) -> tuple[float, float,
def placement_findings_for_crops(gates: Sequence[GateReport]) -> list[GateFinding]:
- """The scene_placement findings a contact crop can be cut for: ERROR before WARN, the larger
- magnitude first, one per asset, only those carrying a box."""
+ """The placement findings a contact crop can be cut for: ERROR before WARN, larger first, one per asset."""
rank = {Severity.ERROR: 0, Severity.WARN: 1, Severity.INFO: 2}
found: list[GateFinding] = [f for g in gates if g.gate == PLACEMENT_GATE for f in g.findings
if f.severity != Severity.INFO and str(f.data.get("kind") or "") in CONTACT_KINDS
@@ -450,15 +401,8 @@ def _tile_weight(elevation_deg: float) -> float:
def plan_contact_crops(shaded: list[RenderView], gates: Sequence[GateReport]) -> list[Montage]:
- """One crop per placement finding (``placement_findings_for_crops`` order), cut from the
- judged overview tile that shows the asset largest: every ``overview_*`` view at the first
- time whose camera is recorded projects the finding's box (``project_box``), its projected
- size weighted by the tile's elevation (``CONTACT_TILE_WEIGHT``: the ground-level contact
- tile first, the top-down one last); a tile where the box fills the frame needs no crop. No
- box, no camera, no tile that sees it — no crop: the verdict never dies on a crop. Added
- 2026-10-14 (scene) because the judge read the gate's floating sentences instead of the
- pictures: the crop puts the measured contact in front of it at the scale a person would
- check."""
+ """One crop per placement finding, cut from the judged overview tile that shows the asset largest.
+ No box, camera or tile that sees it means no crop."""
overviews = [v for v in shaded if v.name in SCENE_OVERVIEW_NAMES]
if not overviews:
return []
@@ -478,7 +422,7 @@ def plan_contact_crops(shaded: list[RenderView], gates: Sequence[GateReport]) ->
if max(w, h) > CONTACT_CROP_MAX_FRAC:
continue
el = (view_az_el(v) or (0.0, 0.0))[1]
- score = max(w, h) * _tile_weight(el) - i * 1e-6 # ties keep rank order
+ score = max(w, h) * _tile_weight(el) - i * 1e-6
if best is None or score > best[0]:
best = (score, v, proj)
if best is None:
@@ -491,7 +435,6 @@ def plan_contact_crops(shaded: list[RenderView], gates: Sequence[GateReport]) ->
return out
-# --------------------------------------------------------------------------- shuffling
def shuffle_montages(montages: list[Montage], seed: int | None) -> list[Montage]:
"""Permute montage order and the tile order inside each grid; detail crops stay last."""
if seed is None:
@@ -511,7 +454,6 @@ def shuffle_montages(montages: list[Montage], seed: int | None) -> list[Montage]
return out + details
-# --------------------------------------------------------------------------- labels
def tile_label(v: RenderView) -> str:
bits = [v.name]
azel = view_az_el(v)
@@ -543,7 +485,6 @@ def montage_label(m: Montage, index: int, total: int) -> str:
return f"MONTAGE {index}/{total} — {m.title}: " + ", ".join(f"{p} = {tile_label(v)}" for p, v in zip(pos, m.tiles, strict=True))
-# --------------------------------------------------------------------------- rendering
def _key(parts: list[str]) -> str:
return hashlib.sha1("|".join(parts).encode()).hexdigest()[:20]
@@ -557,11 +498,7 @@ def _stat(p: str) -> str:
def render_montage(m: Montage, *, cache_dir: Path | None = None, tile_px: int = 512) -> Path:
- """Build (or fetch from cache) the PNG for one montage; pass-through sheets return their source.
-
- Writes go through a per-writer temp file + atomic replace so concurrent
- judges sharing a cache directory never read a half-written PNG.
- """
+ """Build (or fetch from cache) the PNG for one montage; writes are atomic so concurrent judges share the cache."""
if m.passthrough:
_stat(m.tiles[0].path)
return Path(m.tiles[0].path)
@@ -583,7 +520,6 @@ def render_montage(m: Montage, *, cache_dir: Path | None = None, tile_px: int =
def describe_montages(montages: list[Montage]) -> str:
- """One line per image for the VIEW RIG paragraph (what each image is, in send order)."""
grids = [m for m in montages if not m.is_detail]
details = [m for m in montages if m.is_detail]
lines = [f"- image {i}: {m.title}" for i, m in enumerate(grids, 1)]
@@ -591,14 +527,13 @@ def describe_montages(montages: list[Montage]) -> str:
return "\n".join(lines)
-# ===================================================================== prompt_builder
if TYPE_CHECKING: # pragma: no cover
from codeverse3d.judges.base import JudgeInput
-TEXT_BUDGET_CHARS = 24_000 # ≈ 6k tokens
-MAX_PX = 1024 # montages are 2×2 grids: keep them legible
+TEXT_BUDGET_CHARS = 24_000
+MAX_PX = 1024
MONTAGE_TILE_PX = 512
-SLICE_MAX_PX = 1024 # D48 slice images: single drawings, sent at the montage size
+SLICE_MAX_PX = 1024
_ROLE = """You are the BLIND JUDGE of a 3D-code harness: exacting but fair.
You see only the brief, a plan digest, measured numbers, deterministic gate findings and labelled renders of the result — never the builder's code or reasoning. Judge what is visible and measured; do not invent faults and do not credit what you cannot see.
@@ -616,12 +551,9 @@ SCORING RULES
- Reply with ONE JSON object matching the requested schema; no prose outside it."""
-#: D48: end of the DEFECT CHECKLIST scoring-rule bullet in ``_ROLE`` — the anchor the
-#: provenance-elicitation sentence is appended after on slice (gate-ERROR) rounds.
+#: end of the DEFECT CHECKLIST scoring-rule bullet in ``_ROLE``; the provenance sentence is appended after it
_DEFECT_BULLET_END = 'do not mark a defect to "be safe", and do not hide one to be kind.'
-#: D48: one neutral, defect-agnostic sentence. Measured (42-item battery, n=3 pro): it turns
-#: dirty-round defect votes into locatable citations (62/97 image-located, 26 explicit
-#: text-only, 2/23 fabricated slice cites — both guard-caught) without naming any defect.
+#: one neutral, defect-agnostic sentence for slice (gate-ERROR) rounds
PROVENANCE_ELICITATION = (
"For each defect you mark present, say where it is visible (MONTAGE n / "
"DETAIL CROP n / slice n) or state that it rests on the measured text alone."
@@ -636,8 +568,7 @@ def _rubric_block(rubric: Rubric) -> str:
continue
floor = f", hard floor {c.floor:.2f}" if c.floor is not None else ""
lines.append(f"{i}. {c.id} (weight {c.weight:.2f}{floor}) — {c.label}: {c.description.strip()}")
- # every anchor the rubric declares, richest scale first (rubrics may add levels
- # between the four required ones — e.g. scene_v1's 0.5 "diorama on a flat plane")
+ # every anchor the rubric declares, richest scale first
for lvl in sorted(c.anchors, key=lambda k: -float(k)):
lines.append(f" {lvl}: {c.anchors[lvl]}")
if rubric.defects:
@@ -657,18 +588,15 @@ def _rubric_block(rubric: Rubric) -> str:
def build_system_prompt(rubric: Rubric, *, provenance_elicitation: bool = False) -> str:
- """The judge's system prompt. ``provenance_elicitation=True`` (D48, slice rounds only)
- appends :data:`PROVENANCE_ELICITATION` once to the DEFECT CHECKLIST bullet; the default
- is byte-identical to the pre-D48 prompt, which keeps ``judge_prompt_hash`` stable."""
+ """The judge's system prompt; ``provenance_elicitation`` appends :data:`PROVENANCE_ELICITATION` once."""
role = _ROLE
if provenance_elicitation:
- if role.count(_DEFECT_BULLET_END) != 1: # the anchor moved: fail loudly, not silently
+ if role.count(_DEFECT_BULLET_END) != 1:
raise ValueError("prompt_builder._ROLE: the defect-checklist bullet anchor drifted")
role = role.replace(_DEFECT_BULLET_END, _DEFECT_BULLET_END + " " + PROVENANCE_ELICITATION)
return role + "\n\n" + _rubric_block(rubric)
-# --------------------------------------------------------------------------- text sections
def _clip(text: str, limit: int) -> str:
text = text.strip()
return text if len(text) <= limit else text[: limit - 12].rstrip() + " …[clipped]"
@@ -708,17 +636,12 @@ def measurement_section(m: Measurement | None) -> str:
return "MEASUREMENTS (harness, Y-up meters):\n" + _clip(str(measure_summary_table(m)), 6000)
-#: MEASURED STRUCTURE clips. p90 of the 321 stored static_object rounds that report a
-#: contact count is 26 contacts (2026-08-30, scratch corpus_ledger.py over eval/bench/out); the
-#: whole block has to stay near 500 tokens on such a round, so contacts and planned joins
-#: are cut with an "… n more" rather than listed to the end.
+#: MEASURED STRUCTURE clips: contacts and planned joins are cut with an "… n more"
LEDGER_MAX_CONTACTS = 24
LEDGER_MAX_JOINS = 20
-#: Parts whose lowest vertex is within this of the object's lowest point are the ground-contact
-#: candidates; only those get a floor gap in the prompt (a lamp shade is not "above the floor").
+#: parts whose lowest vertex is within this of the object's lowest point are the ground-contact candidates
GROUND_BAND_MM = 10.0
-#: A near-floor gap at or under this is a hairline: the corpus has a verdict writing "legs end
-#: above the ground plane" on 0.3 mm, so the number is printed instead of the adjective.
+#: a near-floor gap at or under this is a hairline: the number is printed instead of the adjective
GROUND_GAP_REPORT_MM = 0.5
_PASSED_FLOATING = (
@@ -730,9 +653,7 @@ _PASSED_FLOATING = (
def contact_ledger(gates: list[GateReport]) -> tuple[GateReport, GateFinding] | None:
- """The connectivity gate's per-pair table — one INFO finding per report since 2026-08-30
- (``spatial.connectivity._ledger``) — with the report that carries it; ``None`` on a
- round recorded before it existed."""
+ """The connectivity gate's per-pair table (one INFO finding) with its report; ``None`` if absent."""
for g in gates:
if g.gate != "connectivity":
continue
@@ -743,17 +664,9 @@ def contact_ledger(gates: list[GateReport]) -> tuple[GateReport, GateFinding] |
def gates_section(gates: list[GateReport], *, max_errors: int = 12, max_warns: int = 8, scene: bool = False) -> str:
- """The judge's gate facts. ERRORs are listed as recorded. With a contact ledger the
- connectivity WARNs are not prose any more: the audit of 420 judged static rounds
- (2026-08-30, eval/docs/EVAL.md §6) found the judge marking interpenetration on every gate
- ERROR (69/69) and on 110 rounds whose only evidence was a WARN the rubric tells it to
- ignore — it read the gate's sentences, not the images (same images, gate text removed:
- 13 of 24 flags flipped). So the WARNs become one measured line and a MEASURED STRUCTURE
- block (contacts, planned joins contact/open, floor gaps) the judge can cite instead.
- Without a ledger (older rounds) the text is the pre-ledger text byte for byte, which is
- what keeps ``3dcode judge <old-slug>`` comparable with the verdict it stored.
- ``scene`` (scene, 2026-10-14) is the scene track's own branch — ``_scene_gates_section``;
- the object text above is untouched by it."""
+ """The judge's gate facts. ERRORs are listed as recorded; with a contact ledger the connectivity WARNs
+ become one measured line plus a MEASURED STRUCTURE block, without one the plain text. ``scene`` has
+ its own branch (``_scene_gates_section``)."""
if not gates:
return "GATE FINDINGS: (no gates run)"
if scene:
@@ -768,12 +681,7 @@ def gates_section(gates: list[GateReport], *, max_errors: int = 12, max_warns: i
if not errs and not warns:
lines.append("no errors or warnings — parts are connected and contracts hold.")
if any(g.gate == "connectivity" and g.passed for g in gates):
- # The connectivity gate MEASURES mesh-to-mesh contact; a VLM reads shading. Measured
- # 2026-08-26 (fancy_v1 gas_street_lamp, plan-pinned pair): on a lamp whose gate said
- # "all 9 parts connected, gap <= 2 mm", the judge called the dark seam under the
- # pedestal "floating in mid-air, a clear daylight gap" — CRITICAL — and scored
- # structure_plausibility 0.4 against 1.0 for the near-identical sibling. A measured
- # contact outranks a shadow (CLAUDE.md law 3); the seam is at most a craftsmanship note.
+ # the connectivity gate measures contact; a VLM reads shading, so a measured contact outranks a shadow
lines.append(_PASSED_FLOATING)
return "\n".join(lines)
conn, ledger = found
@@ -795,13 +703,9 @@ def gates_section(gates: list[GateReport], *, max_errors: int = 12, max_warns: i
return "\n".join(lines)
-# --------------------------------------------------------------------------- the scene branch
-#: the order the scene gates are listed in: what was measured about the place first (the
-#: placement rows), then the frames, then lint / build / console reports. A typed rank, so a
-#: new gate name lands in the tail by default — never a regex on the name.
+#: the order the scene gates are listed in; a gate not named lands in the tail
SCENE_GATE_ORDER: dict[str, int] = {PLACEMENT_GATE: 0, "scene_frames": 1}
-#: the per-kind magnitude a MEASURED PLACEMENT line reports as "worst" (the same keys the
-#: findings carry; cantilevered rows report their widest column gap)
+#: the per-kind magnitude a MEASURED PLACEMENT line reports as "worst"
PLACEMENT_WORST: dict[str, tuple[str, str]] = {
"floating": ("gap_m", "{:.2f} m"), "sunken": ("sunk_m", "{:.2f} m"), "unsupported": ("gap_m", "{:.2f} m"),
"interpenetration": ("overlap", "{:.0%} of the smaller box"), "cantilevered": ("gap_max_m", "{:.2f} m"),
@@ -809,11 +713,8 @@ PLACEMENT_WORST: dict[str, tuple[str, str]] = {
def _scene_gates_section(gates: list[GateReport], *, max_errors: int, max_warns: int) -> str:
- """The scene judge's gate facts (scene): reports in ``SCENE_GATE_ORDER``, the ERRORs as
- recorded, one MEASURED PLACEMENT line built from the scene_placement report's own counts
- (``placement_block``), and the WARNs grouped by (gate, kind) as the object ledger branch
- groups them — eight flat lines used to cut a round's WARNs mid-list with every frame
- WARN behind the placement ones."""
+ """The scene judge's gate facts: reports in ``SCENE_GATE_ORDER``, ERRORs as recorded, one MEASURED
+ PLACEMENT line, and the WARNs grouped by (gate, kind)."""
ordered = sorted(gates, key=lambda g: SCENE_GATE_ORDER.get(g.gate, len(SCENE_GATE_ORDER)))
status = ", ".join(f"{g.gate}={'pass' if g.passed else 'FAIL'}" for g in ordered)
lines = [f"GATE FINDINGS (deterministic; treat as facts): {status}"]
@@ -834,12 +735,8 @@ def placement_report(gates: Sequence[GateReport]) -> GateReport | None:
def placement_block(gates: Sequence[GateReport]) -> str:
- """MEASURED PLACEMENT: the scene_placement gate's own summary (checked / placed / exempt /
- free-tagged, the count per kind) with the worst magnitude per kind read off the typed
- findings, the thresholds the gate used when it recorded them, and — on a clean report — the
- sentence that tells the judge which checklist items the measurement already answered (the
- arithmetic veto, ``rubrics.measured_absent``, holds when the judge does not listen). Empty
- without the gate or when its probe failed (nothing was measured)."""
+ """MEASURED PLACEMENT: the scene_placement gate's summary with the worst magnitude per kind, its thresholds,
+ and on a clean report the sentence naming the checklist items already answered. Empty without the gate."""
rep = placement_report(gates)
if rep is None:
return ""
@@ -861,8 +758,6 @@ def placement_block(gates: Sequence[GateReport]) -> str:
head = (f"MEASURED PLACEMENT (scene_placement gate: every placed asset's foot columns against what is under it, "
f"every pair's box overlap): {int(d.get('checked') or 0)} assets checked of {int(d.get('total') or 0)} placed, "
f"{sum(exempt.values())} exempt ({exempt.get('free', 0)} tagged free)")
- # the gate's own per-kind counts (floating / sunken / unsupported / interpenetration, in its
- # order), then any kind only the findings know (a cantilevered row has no count yet)
kinds = [k for k in PLACEMENT_WORST if k in counts] + [k for k in worst if k not in counts]
parts = []
for kind in kinds:
@@ -886,11 +781,8 @@ def placement_block(gates: Sequence[GateReport]) -> str:
def connectivity_error_pairs(gates: list[GateReport]) -> list[tuple[str, str]]:
- """The connectivity gate's ERROR-level penetration part pairs — the D48 slice
- channel's hatch targets. The pair is read the way the measured batteries read it:
- the finding's ``target`` (falling back to ``data.entering``) against ``data.other``
- (falling back to ``data.container``) — never ``data.entering`` first, whose
- direction is the probe's, not the finding's."""
+ """The connectivity gate's ERROR-level penetration part pairs (the slice channel's hatch targets): ``target``
+ against ``data.other``, falling back to ``data.entering`` / ``data.container``."""
pairs: set[frozenset[str]] = set()
for g in gates:
if g.gate != "connectivity":
@@ -920,8 +812,7 @@ def _capped(label: str, items: list[str], cap: int) -> list[str]:
def _structure_block(conn: GateReport, d: dict) -> list[str]:
- """N parts / E contacts / floating / overlaps, the contact graph, the plan's joins measured
- contact or OPEN, and the floor gap of the parts that could be standing on the floor."""
+ """N parts / E contacts / floating / overlaps, the contact graph, planned joins, and floor gaps."""
parts = list(d.get("parts") or [])
contacts = list(d.get("contacts") or [])
gap = float(d.get("contact_gap_mm") or 0.0)
@@ -933,8 +824,6 @@ def _structure_block(conn: GateReport, d: dict) -> list[str]:
planned = list(d.get("planned") or [])
if planned:
lines.append("- " + _planned_line(planned, gap))
- # the planned joins already list their contacts pair by pair; the adjacency adds what the
- # plan did not ask for (an apron touching a stretcher) instead of repeating it
planned_pairs = {frozenset((str(a), str(b))) for a, b, _g, st in planned if st == "contact"}
other = [c for c in contacts if frozenset((str(c[0]), str(c[1]))) not in planned_pairs]
if other:
@@ -950,8 +839,7 @@ def _structure_block(conn: GateReport, d: dict) -> list[str]:
def _gap(mm: float) -> str:
- """A contact's gap: nothing when it rounds to 0.0 mm (most do), else the number —
- 26 "0.0" tokens were a fifth of the block on the p90 round."""
+ """A contact's gap: nothing when it rounds to 0.0 mm, else the number."""
return f" {mm:.1f}" if round(mm, 1) else ""
@@ -966,7 +854,7 @@ def _adjacency(contacts: list, cap: int) -> str:
def _planned_line(planned: list, gap_mm: float) -> str:
- """OPEN joins first so the clip never hides one: they are the assembly_fit signal."""
+ """OPEN joins first so the clip never hides one."""
rows = [(str(a), str(b), float(g), str(st)) for a, b, g, st in planned]
open_rows = [r for r in rows if r[3] != "contact"]
contact_rows = [r for r in rows if r[3] == "contact"]
@@ -1003,22 +891,15 @@ def _ground_line(ground: dict) -> str:
def _overlap_line(conn: GateReport, d: dict) -> str:
- """The measured replacement for the interpenetration WARN prose. The gate's ERROR
- pairs are already listed under errors; every other overlapping pair is a weld by the
- gate's own rule (depth ≤ 10 mm; the through-ratio is a fact, not a severity), and the
- rubric says a weld is not the defect — the judge marked it anyway on 110 WARN-only rounds.
- A pair reaching half-way or more through its partner is named as a measurement: the ratio
- saturates at the mid-plane and cannot tell "ends inside" from "out the far side", so that
- reading is left to the geometry montage."""
+ """The measured replacement for the interpenetration WARN prose: overlapping pairs are welds by the gate's
+ rule; a pair reaching half-way through its partner is named as a measurement."""
over = list(d.get("overlaps") or [])
if not over:
return ""
error_pairs = {(f.target, f.data.get("other")) for f in conn.findings
if f.severity == Severity.ERROR and f.data.get("kind") == "penetration"}
rest = [r for r in over if (str(r[0]), str(r[1])) not in error_pairs]
- # classified by MEASURED depth, never by severity: the gate keeps a deep overlap a WARN when
- # only a sliver of surface is inside (a stile 17 mm through a seat), and calling that a
- # "weld under the ERROR line" would hand the judge a false fact (skeptic 2026-08-30)
+ # classified by measured depth, never by severity (a deep overlap can still be a WARN)
deep = [r for r in rest if float(r[2]) > PENETRATION_ERROR_M * 1000]
welds = [r for r in rest if float(r[2]) <= PENETRATION_ERROR_M * 1000]
text = f"connectivity measured {len(over)} mating overlaps"
@@ -1034,7 +915,7 @@ def _overlap_line(conn: GateReport, d: dict) -> str:
"surface is inside — a continuous member through a slab reads like this; the montage decides: "
+ "; ".join(f"{a}/{b} {float(dp):.1f} mm (through-ratio {float(t):.2f})" for a, b, dp, t in deep[:3])
+ ("" if len(deep) <= 3 else f"; … {len(deep) - 3} more") + ".")
- mid = [r for r in welds if float(r[3]) >= 0.5] # the gate names the ratio in its message from 0.5 up
+ mid = [r for r in welds if float(r[3]) >= 0.5]
if mid:
text += (" Measured, not a defect claim: "
+ "; ".join(f"{a}/{b} reaches {min(float(t), 1.0):.0%} of the way to its partner's mid-plane ({float(dp):.1f} mm)"
@@ -1044,8 +925,7 @@ def _overlap_line(conn: GateReport, d: dict) -> str:
def _grouped_warnings(rest: list[tuple[GateReport, GateFinding]], max_warns: int) -> list[str]:
- """One line per (gate, kind), ``max_warns`` findings each — 8 flat lines used to cut a
- 15-WARN round (p90) mid-list, dropping every contract WARN behind the connectivity ones."""
+ """One line per (gate, kind), ``max_warns`` findings each."""
if not rest:
return []
groups: dict[str, list[GateFinding]] = {}
@@ -1063,11 +943,7 @@ def _grouped_warnings(rest: list[tuple[GateReport, GateFinding]], max_warns: int
def _passed_paragraph(n_parts: int, n_contacts: int, gap_mm: float, overlaps: list) -> str:
- # Same voice as the legacy paragraph (2026-08-26 gas_street_lamp seam), now with the
- # measurement it rests on and the interpenetration half. The injunction against the
- # interpenetration tick is only made when the veto will honour it: every overlap under
- # VETO_PENETRATION_DEPTH_M (rubrics._rule_gates_clean). A deeper WARN — a stile through a
- # seat, a rod to a plate's mid-plane — is named as a measurement and the picture decides.
+ # the interpenetration injunction is made only when the veto honours it (every overlap under VETO_PENETRATION_DEPTH_M)
head = (
f"CONNECTIVITY PASSED: all {n_parts} parts are in measured contact ({n_contacts} contacts, gap <= {gap_mm:g} mm). "
"A dark seam or shadow line where two parts meet is contact, not daylight. Do NOT report any "
@@ -1104,8 +980,7 @@ def previous_section(prev: Judgment | None, round_index: int) -> str:
return "\n".join(lines)
-#: The fixed sentences of the view-rig paragraph (everything that is not a count or a
-#: per-run probe line). Kept as constants so ``judge_prompt_hash`` covers them.
+#: the fixed sentences of the view-rig paragraph, constants so ``judge_prompt_hash`` covers them
RIG_RULES: dict[str, str] = {
"grid": (
"Each montage is a ≤2×2 grid; every tile carries a label under it ('name · az/el[· mode][· t=]') and the "
@@ -1119,12 +994,7 @@ RIG_RULES: dict[str, str] = {
"geometry": "The GEOMETRY-ONLY montage shows the same object without materials/lighting: use it for holes, inverted (black) faces, intersections and floating parts; use the SHADED montage for materials and detail.",
"poses": "POSE tiles show the SAME object with joints moved by the harness (tile label = joint@value or rest). Judge articulation only from them and the joint table.",
"scene_cams": "Views named overview_* and eye_* are harness cameras fitted to the scene bounds (layout X-ray); every other view is one of the scene's own authored cameras (grade composition/lighting on those); 't=' is the animation time.",
- # 2026-10-15 (owner's rule: requirements, not templates): the craft list names what to read against the
- # BRIEF's place, not one recipe (foreground prop + blended ground + fog), and nothing_moves is the
- # MEASURED MOTION line's — the rubric forbids judging motion by comparing tiles
"scene_craft": "On the authored cameras also read the CRAFT of the picture, not only its contents: depth readable for what each shot frames, surfaces that read as the brief's materials rather than one flat colour, variety among repeated elements, the secondary detail the brief's place implies, and distance softened where the brief's weather would soften it — each judged against what THIS place would have, not a fixed recipe. The same camera at two times appears as separate tiles; nothing_moves is answered from the MEASURED MOTION line only, never by comparing tiles.",
- # scene (2026-10-14): the high overview tiles lift room ceilings (scene_host.skyLayersBelow) and
- # drop the fog; the low one is the contact camera; CONTACT CROPs are diagnostic close-ups
"scene_contact": "The high overview_* tiles (overview_front_right / overview_back_left / overview_top) are rendered with the fog removed and room ceilings lifted: a missing roof, lid or haze in them is never a defect. overview_low_front stands at ground level just outside the content, where daylight under a base shows. CONTACT CROP images are diagnostic close-ups cut from an overview tile around a placement finding the gate measured (the label names the asset, the kind and the number): judge the contact they show — base meets ground, part through neighbour — never their composition, lighting or dressing. Every floating / sunken / clipping / scale claim must name its view and its asset.",
"object": "All views show the same object. Use top + low views for symmetry, footprint and ground contact.",
}
@@ -1155,9 +1025,8 @@ def view_rig_section(renders: RenderSet, montages: list[Montage], *, scene: bool
def slice_rig_section(labels: list[str]) -> str:
- """The D48 slice block appended to the view rig on gate-ERROR rounds: what the slice
- images are (facts only: F2 wording for the hatch), the anti-over-read sentence (F3 —
- an in-plane gap is not evidence of disconnection), and the slice list in send order."""
+ """The slice block appended to the view rig on gate-ERROR rounds: what the slices are, the anti-over-read
+ sentence, and the slice list in send order."""
lines = "\n".join(f"- slice {i}: {lbl}" for i, lbl in enumerate(labels, 1))
return (f"After the crops, {len(labels)} cross-section slice(s) show the interior: "
"slices cut the object on two centre planes; each part keeps one color "
@@ -1171,17 +1040,8 @@ def slice_rig_section(labels: list[str]) -> str:
def judge_prompt_hash(rubric: Rubric) -> str:
- """Hash of everything the judge is told that is constant for a rubric.
-
- Covers the system prompt (``_ROLE`` + the rubric block as rendered), the fixed
- view-rig rules and the wire schema's structure (field order is the
- observe-then-score protocol; ``EVAL.md`` §6 records that changing it moved the
- flash judge's σ from 0.01 to 0.08). Per-run content (brief, plan digest,
- measurements, acceptance ids, images) is deliberately excluded, so two runs judged
- under the same protocol share the hash and a prompt edit is visible in every
- ``ScoreBreakdown.judge_prompt_hash`` / ``record.prompt_hashes["judge"]`` it touched.
- ``rubric_hash`` (the YAML alone) stays alongside for the narrower question.
- """
+ """Hash of everything the judge is told that is constant for a rubric: the system prompt, the fixed
+ view-rig rules and the wire schema's structure. Per-run content is excluded."""
payload = "\n".join([
build_system_prompt(rubric),
*(RIG_RULES[k] for k in sorted(RIG_RULES)),
@@ -1190,7 +1050,6 @@ def judge_prompt_hash(rubric: Rubric) -> str:
return prompt_hash(payload)
-# --------------------------------------------------------------------------- images
def montage_image_parts(
renders: RenderSet,
*,
@@ -1203,8 +1062,7 @@ def montage_image_parts(
cache_dir: Path | None = None,
gates: Sequence[GateReport] = (),
) -> tuple[list[tuple[str, ImagePart]], list[Montage]]:
- """(label, ImagePart) pairs for the montages of a render set, plus the montage plan (in send
- order). ``gates`` feed a scene's contact crops (``plan_contact_crops``)."""
+ """(label, ImagePart) pairs for the montages of a render set, plus the montage plan in send order."""
montages = shuffle_montages(
plan_montages(renders, geometry_views=geometry_views, scene=scene, max_montages=max_montages, detail_crops=detail_crops,
gates=gates),
@@ -1224,7 +1082,6 @@ def montage_image_parts(
return out, montages
-# --------------------------------------------------------------------------- assembly
def build_judge_messages(
inp: JudgeInput,
rubric: Rubric,
@@ -1242,20 +1099,9 @@ def build_judge_messages(
) -> tuple[str, list[ChatMessage]]:
"""Return ``(system, [user_message])`` for a rubric judge call.
- ``geometry_views`` is an optional second RenderSet rendered with
- ``mode='clay'`` / ``'normals'`` (tracks may pass it); when absent, geometry
- views embedded in ``inp.renders`` (by ``RenderView.mode``) are used, else the
- geometry montage is skipped. ``shuffle_seed`` permutes montage and tile
- order (n-sample noise control). ``extra_images`` (label, path) are placed
- BEFORE the montages (e.g. reference images); ``extra_text`` is appended to
- the text block (e.g. measured silhouette).
-
- ``slice_images`` (label, path) are the D48 cross-section slices: placed AFTER
- the montages and detail crops (the measured placement — the ``extra_images``
- prepend was not what the batteries tested), described by
- :func:`slice_rig_section` in the view-rig text, and ``provenance_elicitation``
- adds one sentence to the system prompt's defect-checklist bullet. With both
- left at their defaults the output is byte-identical to the pre-D48 payload.
+ ``geometry_views`` is an optional clay/normals RenderSet; ``shuffle_seed`` permutes montage and tile order;
+ ``extra_images`` go BEFORE the montages and ``slice_images`` AFTER the montages and crops; ``extra_text``
+ is appended to the text block; ``provenance_elicitation`` adds one sentence to the system prompt.
"""
system = build_system_prompt(rubric, provenance_elicitation=provenance_elicitation)
is_scene = inp.spec.track.value == "scene"
@@ -1290,7 +1136,7 @@ def build_judge_messages(
for lbl, ip in images:
parts.append(TextPart(text=lbl))
parts.append(ip)
- for lbl, p in slices: # D48: slices AFTER the montages and crops — the measured placement
+ for lbl, p in slices:
parts.append(TextPart(text=lbl))
parts.append(image_part(prepare_image(p, label=lbl, max_px=SLICE_MAX_PX, cache_dir=cache_dir), lbl))
parts.append(TextPart(text="Now score every criterion with evidence, answer every defect-checklist item and every acceptance item, and return the JSON object."))
diff --git a/harness/codeverse3d/judges/rubrics.py b/harness/codeverse3d/judges/rubrics.py
index 4cedba33..da61e9ad 100644
--- a/harness/codeverse3d/judges/rubrics.py
+++ b/harness/codeverse3d/judges/rubrics.py
@@ -1,19 +1,8 @@
-"""Rubrics: typed criteria + weights + floors + deterministic caps, loaded from YAML.
-
-A rubric is data, not prose: every criterion carries *anchored* descriptions
-(what 1.0 / 0.7 / 0.4 / 0.1 look like) so two judges read the same scale, an
-optional hard ``floor`` (a criterion below its floor fails the verdict no matter
-the weighted mean) and a ``kind`` (``visual`` = scored by the VLM,
-``measured`` = scored in code and merely *shown* to the VLM).
-
-``caps`` are rules that bound the overall score from deterministic gate
-findings (build error → 0.0, floating part → ≤ 0.6 ...) — see ``apply_caps`` below.
-
-``defects`` is a fixed **binary checklist** the VLM answers (present / absent)
-— "a part floats", "lying on its back", "flat untextured" … — and the code
-turns into arithmetic: ``penalty`` is subtracted from the weighted overall and
-``cap`` bounds it. Binary items survive the compressed dynamic range of
-flash-class judges far better than 0..1 scores do.
+"""Rubrics: typed criteria, weights, floors, deterministic caps and a binary defect checklist, loaded from YAML.
+
+A criterion is ``visual`` (scored by the VLM) or ``measured`` (scored in code, shown to the VLM).
+``caps`` bound the overall score from gate findings; ``defects`` turn the VLM's present/absent answers
+into a penalty and a cap.
"""
from __future__ import annotations
@@ -91,12 +80,7 @@ class Criterion(BaseModel):
class DefectItem(BaseModel):
- """One binary checklist item the judge answers; scored in code.
-
- ``penalty`` is subtracted from the weighted overall when the defect is
- present (majority vote over samples); ``cap`` bounds the overall. Either may
- be absent (a purely informational item has penalty 0 and no cap).
- """
+ """One binary checklist item; ``penalty`` is subtracted from the overall and ``cap`` bounds it when present."""
id: str
text: str = Field(description="concrete, visually checkable statement of the defect")
@@ -115,24 +99,9 @@ class DefectItem(BaseModel):
class CapRule(BaseModel):
"""Bounds the overall score when a deterministic signal fires.
- ``when="gate"`` rules match ``GateFinding`` records: ``gate`` is an fnmatch
- pattern on the gate name (``"build*"``), ``severity`` the minimum severity,
- ``kinds`` a list of tokens any of which must appear in ``finding.data.kind``
- / ``finding.data.code`` or, only for a finding that has neither, in the lower-cased message.
- ``when="acceptance"`` fires when any ``must`` acceptance item is not verified;
- with ``graded`` the cap is ``cap + (1 - cap) · verified/total`` over the must
- items instead of the flat ``cap``.
- ``when="console"`` fires when the render set reports console errors (scenes).
- ``when="missing_views"`` fires when NO render view has a name/mode containing
- any of ``kinds`` (e.g. ``kinds: [pose_, articulation_sheet]`` = the articulated
- rubric requires posed views).
-
- ``measures`` names the checklist defects this gate rule is the MEASUREMENT of
- (default: the rule's own id). ``measured_absent`` reads it: a passed gate the
- rule watches vetoes those checklist claims. Audited 2026-08-30 over 420
- static_object verdicts: ``penetration_error`` had never vetoed ``interpenetration``
- because the match was on ``id`` alone — 237 interpenetration flags, 69 with a gate
- ERROR behind them, 0 vetoes.
+ ``when`` is ``gate`` (matches ``GateFinding`` by gate pattern, minimum severity and ``kinds``),
+ ``acceptance`` (a ``must`` item unverified; ``graded`` scales the cap by verified/total),
+ ``console`` or ``missing_views``. ``measures`` names the checklist defects this rule measures.
"""
id: str
@@ -190,7 +159,6 @@ class Rubric(BaseModel):
raise ValueError(f"duplicate defect ids in rubric {self.name}")
return self
- # ------------------------------------------------------------------ helpers
@property
def weights(self) -> dict[str, float]:
return {c.id: c.weight for c in self.criteria}
@@ -227,12 +195,7 @@ class Rubric(BaseModel):
_source: dict[str, Any] | None = PrivateAttr(default=None)
def content_hash(self) -> str:
- """A hash of what the YAML DECLARES, not of the model's defaults.
-
- Hashing ``model_dump`` moved the hash of every rubric — scene_v1, shader_v1/v2
- included — when ``CapRule`` gained ``measures`` and ``graded`` (2026-08-30),
- although their files had not changed a byte; a schema field must never re-key
- recorded verdicts. A rubric built without a source dict (tests) hashes its dump."""
+ """A hash of what the YAML declares, not of the model's defaults, so a schema field never re-keys verdicts."""
src = self._source if self._source is not None else self.model_dump(mode="json")
payload = json.dumps(src, sort_keys=True, default=str)
return hashlib.sha256(payload.encode()).hexdigest()[:12]
@@ -245,7 +208,7 @@ def list_rubrics() -> list[str]:
def rubric_from_dict(data: dict, *, name_hint: str = "") -> Rubric:
try:
rubric = Rubric(**data)
- except Exception as e: # pydantic ValidationError / TypeError
+ except Exception as e:
raise RubricError(f"invalid rubric {name_hint or data.get('name')!r}: {e}") from e
rubric._source = json.loads(json.dumps(data, default=str))
return rubric
@@ -267,7 +230,6 @@ def load_rubric(name: str) -> Rubric:
return rubric_from_dict(data, name_hint=path.stem)
-# ===================================================================== output_schema
class JudgeParseError(ValueError):
"""The model's reply could not be turned into a complete JudgeOutput."""
@@ -309,18 +271,13 @@ class JudgeOutput(BaseModel):
def build_wire_model(rubric: Rubric, acceptance_ids: list[str]) -> type[BaseModel]:
- """A pydantic model whose ``criteria`` / ``acceptance`` objects have FIXED keys.
-
- Criterion ids are valid identifiers (enforced by the rubric). Acceptance ids
- are arbitrary strings → fields ``acc_<i>`` aliased to the id.
- """
+ """A pydantic model whose ``criteria`` / ``acceptance`` objects have fixed keys (``acc_<i>`` aliased to the id)."""
crit_fields: dict[str, Any] = {
c.id: (CriterionScore, Field(description=f"{c.label}: {c.description.strip()[:200]}"))
for c in rubric.visual_criteria()
}
Criteria = create_model("Criteria", **crit_fields)
- # Field order = generation order for JSON-mode models: observe (summary, strengths, issues, defect
- # checklist, acceptance) BEFORE scoring, so the scores follow the evidence rather than the reverse.
+ # field order = generation order: evidence before scores
fields: dict[str, Any] = {
"summary": (str, Field(description="2-4 sentences: what it is, what is right, what is most wrong")),
"strengths": (list[str], Field(default_factory=list, description="≤ 5 short bullets")),
@@ -351,7 +308,6 @@ def wire_schema(rubric: Rubric, acceptance_ids: list[str]) -> dict[str, Any]:
return build_wire_model(rubric, acceptance_ids).model_json_schema(by_alias=True)
-# --------------------------------------------------------------------------- parsing
def _records_to_dict(value: Any, key_names: tuple[str, ...]) -> dict[str, Any]:
"""Accept ``{id: {...}}`` or ``[{id: ..., ...}, ...]`` and return ``{id: {...}}``."""
if isinstance(value, dict):
@@ -409,11 +365,7 @@ def _coerce_defects(value: Any) -> tuple[dict[str, bool], dict[str, str]]:
def parse_judge_output(
payload: Any, rubric: Rubric, acceptance_ids: list[str], *, measured_scores: dict[str, float] | None = None
) -> JudgeOutput:
- """Validate a parsed reply (dict) or raw text into a complete ``JudgeOutput``.
-
- ``measured_scores`` (criterion id → score) are injected for ``kind: measured``
- criteria so the output always covers the full rubric.
- """
+ """Validate a parsed reply (dict) or raw text into a complete ``JudgeOutput``; ``measured_scores`` fill ``measured`` criteria."""
if isinstance(payload, str):
try:
payload = parse_json_lenient(payload)
@@ -450,23 +402,22 @@ def parse_judge_output(
if missing:
raise JudgeParseError(f"judge reply missing criteria {missing}")
extra = [k for k in out.criteria if k not in rubric.weights]
- for k in extra: # unknown criteria are ignored, not scored
+ for k in extra:
out.criteria.pop(k)
missing_acc = [a for a in acceptance_ids if a not in out.acceptance]
- for a in missing_acc: # unanswered acceptance items count as NOT verified
+ for a in missing_acc:
out.acceptance[a] = AcceptanceVerdict(verified=False, evidence="not answered by judge")
known = {d.id for d in rubric.defects}
- for k in [k for k in out.defects if k not in known]: # unknown checklist ids are ignored
+ for k in [k for k in out.defects if k not in known]:
out.defects.pop(k)
out.defect_evidence.pop(k, None)
for d in rubric.defects:
- if d.id not in out.defects: # unanswered defect → absent (the conservative direction for a penalty)
+ if d.id not in out.defects:
out.defects[d.id] = False
out.defect_evidence[d.id] = "not answered by judge"
return out
-# ===================================================================== caps
_SEV_RANK = {Severity.INFO: 0, Severity.WARN: 1, Severity.ERROR: 2}
@@ -486,10 +437,8 @@ class CapResult(BaseModel):
def _finding_tokens(f: GateFinding) -> str:
- """What a cap rule's ``kinds`` are matched against: the gate's typed ``data.kind`` /
- ``data.code``, and the message only for a finding that carries neither (old records).
- Never the target: a part named ``kitchen_island`` fired ``floating_part`` on a
- penetration finding (audit 2026-09-24, N50)."""
+ """What a cap rule's ``kinds`` are matched against: the finding's ``data.kind`` / ``data.code``, and the
+ message only if it has neither. Never the target name."""
typed = " ".join(str(f.data.get(k, "")) for k in ("kind", "code")).strip()
return (typed or f.message).lower()
@@ -517,30 +466,10 @@ def missing_must_items(
def measured_absent(rubric: Rubric, defect_id: str, gates: list[GateReport]) -> bool:
- """True when a deterministic gate MEASURED the thing this checklist defect claims, and found nothing.
-
- A checklist defect is a VLM's reading of a picture. Some of them — a floating part, an
- interpenetration — are also what a gate measures on the exported mesh, and the rubric
- already says which: a ``when="gate"`` cap rule whose ``measures`` names the defect and
- whose ``kinds`` name the findings. When every gate that rule watches ran and passed
- with no ERROR finding of those kinds, the measurement contradicts the perception, and
- the perception must not cap.
-
- Measured 2026-08-26 on a plan-pinned pair (fancy_v1 gas_street_lamp): the connectivity
- gate said "all 9 parts connected, gap <= 2 mm"; the judge read the dark seam under the
- pedestal as "floating in mid-air, a clear daylight gap", marked floating_part present, and
- ``defect:floating_part`` capped the run at 0.6 (uncapped 0.72) against 0.96 for a sibling
- the eye cannot tell apart. CLAUDE.md law 3: gates decide geometry, the VLM is perception.
-
- Audited 2026-08-30 (420 static_object verdicts): the veto had fired 10 times. It matched
- ``r.id == defect_id`` — ``penetration_error`` never reached ``interpenetration`` — and the
- rules watched ``gate: "*"``, so a failing contract gate (53 of the 62 blocked cases)
- switched off a veto the connectivity gate had earned. Now ``measures`` carries the
- defect ids and the object rubrics watch ``connectivity`` alone.
-
- A defect with no matching gate rule (wrong_object, missing_named_part …) is never
- overridden: nothing measured it. A gate that did not run overrides nothing either.
- When several rules measure one defect, every one of them must be clean.
+ """True when a gate measured the thing this checklist defect claims and found nothing.
+
+ The rule is the ``when="gate"`` cap rule whose ``measures`` names the defect; every gate it
+ watches must have run and passed. A defect with no such rule is never overridden.
"""
rules = [r for r in rubric.caps if r.when == "gate" and defect_id in r.measures and r.kinds]
if not rules:
@@ -548,30 +477,13 @@ def measured_absent(rubric: Rubric, defect_id: str, gates: list[GateReport]) ->
return all(_rule_gates_clean(r, gates) for r in rules)
-#: A penetration the gate rated WARN but measured at least this deep is NOT "measured
-#: absent": the rubric excuses "weld overlaps of a few mm", and the veto that trusted every
-#: WARN was switching off 163 interpenetration claims — and, since 2026-08-30, a stile 17 mm
-#: through a seat is a WARN too. From here up the judge's reading stands and the picture
-#: decides. The line is 8 mm, not 5: the paired re-judge marked the pipe tee's 5.8 mm
-#: branch socket — the canonical DESIGNED weld — as the defect the moment a 5 mm line let
-#: the claim stand (−0.32 on that side), and the corpus holds only 9 standing claims in the
-#: 5–8 mm band (sockets, vise rails) against 16 at 8–10 mm and 43 with an ERROR behind them.
+#: a penetration WARN at least this deep is NOT "measured absent": the judge's reading stands
VETO_PENETRATION_DEPTH_M = 0.008
def _rule_gates_clean(rule: CapRule, gates: list[GateReport]) -> bool:
- """Every gate ``rule`` watches ran and reports no finding of its ``kinds`` that is an
- ERROR — or a WARN whose measured magnitude reaches the rule's veto line
- (``CapRule.veto_warn_keys``; default: a penetration ``depth_m`` of
- ``VETO_PENETRATION_DEPTH_M``). A report is watched when its name OR one of its findings'
- ``gate`` matches the rule, the same predicate the cap side (``_finding_matches``) uses.
-
- Scoped to the rule's kinds since scoring version 4 (2026-10-14): a failed report used to
- cancel the veto whatever it failed on, and on the scene track the placement rows and the
- plan checks share ONE report — a ``no_fog`` or ``missing_content`` ERROR let every
- "floating asset" claim stand although the rows had measured none (scene splits the
- placement caps per kind for the same reason). A failed report that names no ERROR finding
- at all cannot say what failed and still counts as not clean."""
+ """Every gate ``rule`` watches ran and reports no finding of its ``kinds`` that is an ERROR, or a WARN
+ whose magnitude reaches the veto line. A failed report naming no ERROR finding counts as not clean."""
watched = [g for g in gates if fnmatch(g.gate, rule.gate) or any(fnmatch(f.gate, rule.gate) for f in g.findings)]
if not watched:
return False
@@ -620,10 +532,7 @@ def apply_caps(
) -> CapResult:
"""Apply every rubric cap rule; the overall becomes ``min(overall, caps...)``.
- Only the first matching finding per rule is recorded as evidence (one ledger
- line per rule), but all rules are evaluated. ``defects_present`` (checklist
- id → True) adds one ``defect:<id>`` ledger line per present defect that
- carries a ``cap``.
+ One ledger line per rule (first matching finding) and one ``defect:<id>`` line per present capped defect.
"""
applied: list[CapApplied] = []
for rule in rubric.caps:
@@ -679,11 +588,6 @@ def _rule_hit(
return None
total = sum(1 for a in acceptance_items if a.priority == "must")
verified = total - len(missing)
- # A flat cap was the DECISIVE cap on 121 of 424 static_object verdicts (28.6 %,
- # audited 2026-08-30): one unverified must item out of ten pinned the score to
- # 0.600 exactly as ten out of ten did. Graded, the cap keeps its floor at ``cap``
- # (0 of n verified) and climbs linearly to 1.0; pass/fail is untouched — the
- # verdict still fails on ``must_missing``.
cap = rule.cap + (1.0 - rule.cap) * verified / total if rule.graded and total else rule.cap
return CapApplied(rule=rule.id, cap=cap,
evidence=f"{verified} of {total} must items verified; not verified: {', '.join(missing[:6])}")
@@ -700,7 +604,6 @@ def _rule_hit(
return None
-# ===================================================================== scoring
SCORING_VERSION = 4
"""The arithmetic downstream of the model, stamped into every ``ScoreBreakdown``.
@@ -776,11 +679,7 @@ def _representative(samples: list[JudgeOutput], overalls: list[float]) -> JudgeO
def _vote(votes: list[bool], tie_break: bool) -> tuple[bool, bool]:
"""Majority of ``votes``; an exact tie takes ``tie_break``. Returns (decision, was_tie).
- Acceptance ties take the representative sample (the owner's policy: a must-item tie
- decides pass/fail, and the old ties→False failed a run on one dissent). Defect ties
- take ``False``: the rubric puts the burden of proof on the defect ("present only when an
- image or a gate finding shows it"), so a split vote has not met it. 419 of 420 corpus
- verdicts are n=1 — this moves nothing on disk (2026-08-30).
+ Acceptance ties take the representative sample; defect ties take ``False`` (the defect bears the burden).
"""
if not votes:
return False, False
@@ -804,11 +703,7 @@ def aggregate_samples(
sample_errors: list[str] | None = None,
judge_prompt_hash: str = "",
) -> Judgment:
- """Combine ≥ 1 parsed samples into a Judgment (raises ValueError on zero samples).
-
- ``views`` feeds ``missing_views`` cap rules (e.g. the articulated rubric's
- required pose sheet).
- """
+ """Combine ≥ 1 parsed samples into a Judgment (raises ValueError on zero); ``views`` feed ``missing_views`` caps."""
if not samples:
raise ValueError("aggregate_samples needs at least one sample")
per_crit: dict[str, list[float]] = {c.id: [] for c in rubric.criteria}
@@ -850,8 +745,7 @@ def aggregate_samples(
defects[did], tied = _vote(v, False)
if tied:
tie_broken.append(did)
- # a checklist defect that a passed gate measured as absent neither penalises nor caps
- # (``veto_measured_defects``); it is still named in the verdict tail
+ # a defect a passed gate measured as absent neither penalises nor caps (``veto_measured_defects``)
defects, overridden = veto_measured_defects(rubric, defects, gates)
penalty = round(sum(rubric.defect(did).penalty for did, on in defects.items() if on), 4)
after_defects = max(0.0, overall_uncapped - penalty)
diff --git a/harness/codeverse3d/judges/vlm_judge.py b/harness/codeverse3d/judges/vlm_judge.py
index 434e89d7..5a8f5233 100644
--- a/harness/codeverse3d/judges/vlm_judge.py
+++ b/harness/codeverse3d/judges/vlm_judge.py
@@ -1,18 +1,9 @@
"""``VlmJudge``: rubric YAML + labelled renders + measurements → ``Judgment``.
-Per sample: one ``ChatRequest`` with a per-rubric JSON schema (criteria scored
-0..1 with evidence, the rubric's binary defect checklist, issues, improvement
-plan, acceptance verdicts); samples differ by montage/tile order (shuffle seed)
-so n-sample mean/std measures judge noise. With ``n_samples > 1`` the model
-calls run in parallel (``codeverse3d.proc``); results accumulate in sample order. Score/defect penalties/floors/caps
-/pass are computed in code (``rubrics.aggregate_samples``). Images are ≤2×2 montages
-(``prompt_builder``); tracks may pass a clay/normals ``JudgeInput.geometry_views`` RenderSet. Retries: up to
-``max_attempts`` per sample on ``ModelError`` / parse failure, all of them inside one
-``sample_budget_s`` (:data:`SAMPLE_BUDGET_S`) that also clips the model's own retry
-deadline (``ChatRequest.max_wait_s``); if no sample
-succeeds, a *degraded* Judgment (``passed=False, overall=0, summary
-'judge_error: …'``, ``raw.status='degraded'``) is returned for the orchestrator
-to treat as a glitch, never as a score.
+Per sample, one ``ChatRequest`` with a per-rubric JSON schema; samples differ by montage order so the
+n-sample std measures judge noise. Score, penalties, floors, caps and pass are computed in code
+(``rubrics.aggregate_samples``). Retries stay inside one ``sample_budget_s``; if no sample succeeds a
+*degraded* Judgment (``raw.status='degraded'``) is returned, which the orchestrator treats as a glitch.
"""
from __future__ import annotations
@@ -62,47 +53,32 @@ from codeverse3d.spatial.silhouette import (
log = logging.getLogger(__name__)
-#: retry budget for ONE judge sample, every attempt included — the owner's rule
-#: (2026-08-27): generous time, zero timeouts. For scale, the verdict call is 42 s p50 /
-#: 73 s p90 on a normal day and 50 / 103 s under a storm (audit 2026-08-26 §2); the old
-#: 240 s cap, and before it 3 x (a 300 s read timeout + the model's 900 s retry deadline),
-#: lost two storm-day rounds 1 162 s and 927 s before a second sample answered in 128 s.
+#: retry budget for ONE judge sample, every attempt included
SAMPLE_BUDGET_S = 900.0
-#: the floor of one attempt's ``max_wait_s``: a last attempt still gets a real try
SAMPLE_MIN_WAIT_S = 20.0
-#: D48 slice-image labels, keyed by ``sections.JUDGE_SLICE_PLANES`` name (the tested wording)
SLICE_LABELS = {
"front_back": "cross-section front-back · interior view",
"left_right": "cross-section left-right · interior view",
}
-#: the judge's thinking levels (``ChatRequest.thinking``); the run default is ``Settings.judge.thinking``
THINKING_LEVELS: tuple[str, ...] = ("off", "low", "medium", "high")
-#: Per-track montage ceilings under the ``Settings.judge.montages`` dial. D47's 3 → 5 was
-#: measured on the OBJECT rig only (docs/DECISIONS.md D47); graphics keeps the pre-D47 3 until a
-#: battery measures it. The scene rig moved 3 → 4 with scene (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.
+#: per-track montage ceilings under the ``Settings.judge.montages`` dial
TRACK_MONTAGE_CAP: dict[str, int] = {"scene": 4, "graphics": 3}
@dataclass
class JudgeContext:
- """Per-call extras a subclass may supply (see ``VlmJudge.context``)."""
measured_scores: dict[str, float] = field(default_factory=dict)
extra_text: str = ""
extra_images: list[tuple[str, str]] = field(default_factory=list)
- #: what building the context cost (ReferenceJudge's mismatch pass is a real model
- #: call); folded into the verdict so BudgetGuard and record.total_usage see it
+ #: what building the context cost; folded into the verdict so budgets see it
usage: Usage = field(default_factory=Usage)
class VlmJudge:
- """Rubric judge over a ``ChatModel``. Thread-safe (stateless between calls)."""
name = "vlm"
@@ -122,12 +98,7 @@ class VlmJudge:
fixed_order: bool = False,
):
self.rubric: Rubric = rubric if isinstance(rubric, Rubric) else load_rubric(rubric)
- # Every sample of one call normally sees the montages and tiles in a different order
- # (shuffle_seed below), so score_std is a view-ORDER robustness figure — the number
- # docs/COST.md §8's judge noise was tabulated from. fixed_order sends the identical
- # prompt n times: the re-judge σ of the model itself, which is what the loop's
- # stop thresholds and the pairwise margin are actually keyed to (audit 2026-08-30;
- # brilliana measured 0.013 vs 0.035 between the two on 512 calls).
+ # fixed_order sends the identical prompt n times (re-judge sigma) instead of shuffling view order
self.fixed_order = bool(fixed_order)
self.model_id = model_id or get_settings().default_judge
self.n_samples = max(1, int(n_samples))
@@ -136,11 +107,8 @@ 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: Settings.judge
jd = get_settings().judge
- # ``thinking=None`` reads ``Settings.judge.thinking`` (C3D_JUDGE__THINKING) — the one place a run,
- # a replay (`3dcode judge --thinking`) and the calibration tool take the level from (D105:
- # gemini-4-argon thinks only from 'medium')
+ # ``thinking=None`` reads ``Settings.judge.thinking``
level = str(jd.thinking if thinking is None else thinking)
if level not in THINKING_LEVELS:
raise ValueError(f"judge thinking must be one of {' | '.join(THINKING_LEVELS)}, not {level!r}")
@@ -155,43 +123,36 @@ class VlmJudge:
self.label = label
def _montages_for(self, inp: JudgeInput) -> int:
- """Per-track montage cap (``TRACK_MONTAGE_CAP``: scene 4, graphics 3; the object rig takes
- the dial, D47)."""
+ """Per-track montage cap (``TRACK_MONTAGE_CAP``); the object rig takes the dial."""
cap = TRACK_MONTAGE_CAP.get(inp.spec.track.value)
if cap is None:
return self.max_montages
return min(self.max_montages, cap)
- # ------------------------------------------------------------------ provenance
@property
def prompt_hash(self) -> str:
- """``prompt_builder.judge_prompt_hash`` for this judge's rubric (recorded per verdict)."""
return judge_prompt_hash(self.rubric)
- # ------------------------------------------------------------------ model
@property
def model(self) -> ChatModel:
if self._model is None:
self._model = get_chat_model(self.model_id)
return self._model
- # ------------------------------------------------------------------ API
def judge(self, inp: JudgeInput) -> Judgment:
- """Judge one round. ``inp.geometry_views`` feeds the geometry montage (clay/normals
- views embedded in ``inp.renders`` by ``RenderView.mode`` are always routed there too)."""
+ """Judge one round; clay/normals views in ``inp.renders`` are routed to the geometry montage."""
geometry_views = inp.geometry_views
acceptance_ids = [a.id for a in inp.acceptance]
schema = wire_schema(self.rubric, acceptance_ids)
ctx = self.context(inp)
measured, extra_text, extra_images = ctx.measured_scores, ctx.extra_text, ctx.extra_images
usage = ctx.usage
- slice_images, elicit = self.slice_payload(inp) # D48: [] / False on a clean round
+ slice_images, elicit = self.slice_payload(inp)
samples: list[JudgeOutput] = []
errors: list[str] = []
reqs: list[ChatRequest] = []
for k in range(self.n_samples):
seed = None if (self.fixed_order or (self.n_samples == 1 and k == 0)) else (inp.round_index * 1000 + k)
- # a missing render is a pipeline bug, not a judge glitch → JudgeImageError propagates
system, messages = build_judge_messages(
inp, self.rubric, shuffle_seed=seed, geometry_views=geometry_views, max_montages=self._montages_for(inp),
detail_crops=self.detail_crops, max_px=self.max_px, cache_dir=self.cache_dir,
@@ -200,22 +161,18 @@ class VlmJudge:
)
reqs.append(ChatRequest(
messages=messages, system=system, response_schema=schema, temperature=self.temperature,
- thinking=self.thinking, # type: ignore[arg-type] # validated against THINKING_LEVELS in __init__
- # proc.fan_out copies the caller's contextvars into every sample thread, so the ledger's
- # ambient attribution reaches a worker; it is bound per STAGE (the track's call_context
- # around a round), so the label stays explicit with what only this call knows — the judge
- # job (self-describing: cost/context.SELF_DESCRIBING), its rubric, round and sample
+ thinking=self.thinking, # type: ignore[arg-type]
+ # fan_out copies contextvars into every sample thread; the label adds what only this call knows
label=f"{self.label}:{self.rubric.name}:r{inp.round_index:02d}:s{k}",
))
- if len(reqs) == 1: # serial path: no pool, no thread hop
+ if len(reqs) == 1:
outcomes = [self._sample(reqs[0], acceptance_ids, measured)]
else:
- self.model # noqa: B018 — materialise the lazy chat model once, before the threads race
+ self.model # noqa: B018
results = fan_out(
reqs, lambda r: self._sample(r, acceptance_ids, measured),
max_workers=len(reqs), label=f"{self.label}:samples", item_name=lambda r: r.label,
)
- # ordered accumulation; _sample never raises, but a crashed worker still counts as an error
outcomes = [
r if not isinstance(r, Exception) else (None, Usage(), f"{type(r).__name__}: {r}")
for r in results
@@ -238,13 +195,8 @@ class VlmJudge:
judge_prompt_hash=self.prompt_hash,
)
- # ------------------------------------------------------------------ hook (ReferenceJudge overrides)
def context(self, inp: JudgeInput) -> JudgeContext:
- """Per-call extras: measured-criterion scores (code), extra text and extra images.
-
- The base judge computes no measured criteria, so a rubric that declares
- some cannot be used with it (use ``ReferenceJudge`` or a subclass).
- """
+ """Per-call extras: measured-criterion scores, extra text and extra images (none in the base judge)."""
if self.rubric.measured_criteria():
raise ValueError(
f"rubric {self.rubric.name} has measured criteria "
@@ -252,18 +204,11 @@ class VlmJudge:
)
return JudgeContext()
- # ------------------------------------------------------------------ D48 conditional slices
def slice_payload(self, inp: JudgeInput) -> tuple[list[tuple[str, str]], bool]:
- """``([(label, png_path)…], provenance_elicitation)`` for the D48 slice channel.
-
- The channel fires ONLY when ``Settings.judge.slices == "on-error"``, the track is
- an object track, ``inp.glb_path`` exists, AND the connectivity gate carries ≥ 1
- ERROR finding; otherwise ``([], False)`` and the payload is byte-identical to the
- pre-D48 one. On a firing round the slices are rendered (cached by GLB identity +
- error pairs) into the judge cache dir; F4 may drop them all, in which case the
- elicitation sentence still applies (the tested v3 semantics: elicitation follows
- dirtiness, not slice count). A missing mesh extra disables the channel; a render
- crash degrades to text-only elicitation — a verdict never dies on a drawing.
+ """``([(label, png_path)…], provenance_elicitation)`` for the slice channel.
+
+ Fires only when ``Settings.judge.slices == "on-error"``, the track is an object track, ``inp.glb_path``
+ exists and the connectivity gate has an ERROR; otherwise ``([], False)``. Never raises.
"""
if get_settings().judge.slices != "on-error":
return [], False
@@ -280,18 +225,13 @@ class VlmJudge:
except ImportError as e:
log.warning("judge slices disabled: %s (install the 'mesh' extra)", e)
return [], False
- except Exception as e: # noqa: BLE001 — the drawing must never sink the verdict
+ except Exception as e: # noqa: BLE001
log.warning("judge slice render failed for %s: %s", glb, e)
return [], True
return [(SLICE_LABELS[s.name], str(out_dir / s.png)) for s in manifest.rendered()], True
def _render_slices(self, glb: Path, pairs: list[tuple[str, str]]):
- """Render (or reuse) the slice set for ``glb`` under the judge cache dir.
-
- Keyed like ``prepare_image``: path + mtime + size + the error pairs, so a
- rebuilt GLB re-renders and concurrent judges of the same round share one set.
- Writes go to a per-writer temp dir renamed into place (a concurrent identical
- writer simply wins first)."""
+ """Render (or reuse) the slice set for ``glb``, cached by path + mtime + size + error pairs."""
from codeverse3d.spatial.sections import SliceManifest, judge_slices
cache = Path(self.cache_dir) if self.cache_dir else default_cache_dir()
@@ -302,14 +242,12 @@ class VlmJudge:
shutil.rmtree(tmp, ignore_errors=True)
try:
judge_slices(glb, pairs, tmp)
- # a concurrent identical writer may have renamed first — then use theirs
with contextlib.suppress(OSError):
tmp.rename(out_dir)
- finally: # a mid-render crash (or losing the race) must not leave the .tmp behind
+ finally:
shutil.rmtree(tmp, ignore_errors=True)
return out_dir, SliceManifest.model_validate_json(mpath.read_text())
- # ------------------------------------------------------------------ one sample with retries
def _sample(
self, req: ChatRequest, acceptance_ids: list[str], measured: dict[str, float]
) -> tuple[JudgeOutput | None, Usage, str]:
@@ -323,16 +261,15 @@ class VlmJudge:
+ (f"; last: {last}" if last else ""))
log.warning("judge %s: %s", req.label, last[:300])
break
- # the model may retry inside this call, never past what the sample can still afford
req = req.model_copy(update={"max_wait_s": max(SAMPLE_MIN_WAIT_S, remaining)})
t0 = time.monotonic()
try:
resp: ChatResponse = self.model.generate(req)
except ModelError as e:
- usage = usage + (getattr(e, "usage", None) or Usage()) # the provider billed it
+ usage = usage + (getattr(e, "usage", None) or Usage())
last = f"ModelError(attempt {attempt}): {e}"
log.warning("judge %s: %s", req.label, last)
- if not e.retryable: # same request again cannot fix a 400 / a blocked prompt
+ if not e.retryable:
break
continue
usage = usage + resp.usage
@@ -348,17 +285,14 @@ class VlmJudge:
return None, usage, last or "unknown judge failure"
-# ===================================================================== reference
-#: IoU → score mapping: ≤ 0.25 → 0, ≥ 0.85 → 1, linear in between (matches the rubric anchors).
+#: IoU → score: ≤ 0.25 → 0, ≥ 0.85 → 1, linear between
IOU_LOW, IOU_HIGH = 0.25, 0.85
#: score the measured criterion gets when the measurement cannot be trusted
-#: (unreliable mask, or a reference whose proportions contradict the brief)
NEUTRAL_SCORE = 0.5
-#: views handed to the mismatch pass (front-ish first, then a 3/4 and a side); a stored
-#: pre-D47 run matches through ``conventions.view_key``.
+#: views handed to the mismatch pass (front-ish first, then a 3/4 and a side)
DIFF_VIEW_NAMES: tuple[str, ...] = ("front", "front_right_high", "front_left_high", "right", "left")
@@ -367,12 +301,10 @@ def iou_to_score(iou: float) -> float:
def _diff_enabled(flag: bool) -> bool:
- """``flag`` unless ``C3D_REFERENCE_DIFF`` switched the pass off (``Settings.reference_diff``)."""
return flag and get_settings().reference_diff
class ReferenceJudge(VlmJudge):
- """VlmJudge + reference images + measured silhouette + named mismatches."""
name = "reference"
@@ -391,7 +323,6 @@ class ReferenceJudge(VlmJudge):
self.silhouette_fn = silhouette_fn or compare_silhouette
self.diff = diff
- # ------------------------------------------------------------------ hook
def context(self, inp: JudgeInput) -> JudgeContext:
refs = [r for r in inp.spec.references if Path(r.path).is_file()]
images: list[tuple[str, str]] = []
@@ -422,35 +353,27 @@ class ReferenceJudge(VlmJudge):
return JudgeContext(measured_scores=measured_scores, extra_text="\n\n".join(blocks), extra_images=images,
usage=diff.usage if diff is not None else Usage())
- # ------------------------------------------------------------------ proportion guard
def dimension_conflict(self, inp: JudgeInput, refs: list[Any]) -> dict[str, Any]:
- """Does the target reference's own outline contradict the brief's dimensions?
-
- When it does, no numeric proportion signal derived from that picture may be
- used against the object — the brief wins (``reference.dimension_conflict``).
- """
+ """Does the target reference's own outline contradict the brief's dimensions? If so the brief wins."""
targets = [r for r in refs if r.role == "target"] or refs
if not targets:
return {"conflict": False}
try:
return dimension_conflict(inp.spec, targets[0].path)
- except Exception as e: # noqa: BLE001 — advisory
+ except Exception as e: # noqa: BLE001
log.warning("dimension-conflict check failed: %s", e)
return {"conflict": False, "error": str(e)}
def silhouette_score(self, match: ReferenceMatch) -> tuple[float, str]:
- """IoU → measured score, NEUTRAL when the reference contradicts the brief or the
- mask is unreliable. Returns ``(score, ' (why)')``."""
+ """IoU → measured score, neutral when the reference contradicts the brief or the mask is unreliable."""
if match.conflict:
return NEUTRAL_SCORE, " (NEUTRAL: the reference's proportions contradict the brief's dimensions)"
if not match.reliable:
return NEUTRAL_SCORE, " (NEUTRAL: the background mask was unreliable)"
return iou_to_score(match.iou), ""
- # ------------------------------------------------------------------ mismatch pass
def reference_diff(self, inp: JudgeInput, refs: list[Any], match: ReferenceMatch | None) -> Any | None:
- """One extra vision call naming concrete mismatches. ``None`` when disabled;
- never raises (a failed diff simply contributes no text)."""
+ """One extra vision call naming concrete mismatches; ``None`` when disabled; never raises."""
if not _diff_enabled(self.diff):
return None
targets = [r.path for r in refs if r.role == "target"] or [r.path for r in refs]
@@ -460,12 +383,11 @@ class ReferenceJudge(VlmJudge):
try:
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 verdict
+ except Exception as e: # noqa: BLE001
log.warning("reference diff pass failed: %s", e)
return None
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)]
for v in views:
if len(picked) >= 3:
@@ -490,17 +412,8 @@ LIKENESS_NOTE = (
class LikenessJudge(VlmJudge):
- """``VlmJudge`` + the reference photos of the REAL thing — for tracks with no silhouette.
-
- ``ReferenceJudge`` is built for objects: it measures a best-view silhouette IoU against
- the target photo and runs a part-inventory mismatch pass. Neither means anything for a
- fragment shader or a scene, where a reference photo answers a different question — does
- this LOOK like the thing? Measured 2026-08-26 (teaser aurora, three versions, flash and
- codex): every version scored 0.78-0.94 with an empty issues list while none resembled an
- aurora (a comb of straight teal bars; pink cotton-wool lobes), because the brief is a
- checklist of nouns and the rubric had nothing to say about likeness. This judge attaches
- up to three photos beside the frames with :data:`LIKENESS_NOTE` and leaves the rubric alone.
- """
+ """``VlmJudge`` + reference photos, for tracks with no silhouette: the photos are attached beside the
+ frames with :data:`LIKENESS_NOTE` and the rubric is unchanged."""
name = "likeness"
@@ -522,12 +435,9 @@ class ReferenceJudgeError(RuntimeError):
def judge_for(track: Track, rubric: str | Rubric, *, references: bool) -> type[VlmJudge]:
- """The judge class that scores a round: ONE rule for the live run (``BaseTrack.make_judge``)
- and every replay (``3dcode judge``, calibration), so a replay is judged as the run was.
-
- A rubric with measured criteria needs :class:`ReferenceJudge`, the judge that computes
- them; reference photos get :class:`LikenessJudge` on graphics and scene (nothing there to
- silhouette-match) and :class:`ReferenceJudge` on the object tracks; else :class:`VlmJudge`."""
+ """The judge class that scores a round, shared by the live run and every replay: :class:`ReferenceJudge`
+ for measured criteria or object-track references, :class:`LikenessJudge` for graphics/scene references,
+ else :class:`VlmJudge`."""
rub = rubric if isinstance(rubric, Rubric) else load_rubric(rubric)
if rub.measured_criteria() or (references and not TRACK_INFO[track].likeness_refs):
return ReferenceJudge
diff --git a/harness/codeverse3d/languages/_ast_lint.py b/harness/codeverse3d/languages/_ast_lint.py
index a1896e4a..71a3ed00 100644
--- a/harness/codeverse3d/languages/_ast_lint.py
+++ b/harness/codeverse3d/languages/_ast_lint.py
@@ -1,13 +1,5 @@
-"""Shared AST-lint primitives for the python authoring languages (blender, cadquery, opengl_python).
-
-Each language keeps its own collector and rules — only the language-neutral
-pieces live here: :func:`dotted` (dotted-name of an Attribute/Name chain),
-:class:`ImportCollector` (the ``{top-level module: first line}`` visitor), the
-:data:`BASE_FORBIDDEN_IMPORTS` floor every language's forbidden set must
-include (a drift test pins the superset), and :func:`check_imports` (the
-forbidden → ERROR / not-allowed → WARN routing, with the finding text owned by
-the caller via ``make_finding``).
-"""
+"""Language-neutral AST-lint primitives for the python languages: ``dotted``, ``ImportCollector``,
+``BASE_FORBIDDEN_IMPORTS`` and ``check_imports``."""
from __future__ import annotations
@@ -16,12 +8,7 @@ from collections.abc import Callable, Collection, Mapping
from codeverse3d.contracts.artifacts import GateFinding
-#: modules no agent script may import in ANY python language (subprocesses,
-#: network, file-system side effects, dynamic import). Languages compose their
-#: supersets: blender adds ``pathlib`` (but allows ``os``/``sys`` — headless bpy
-#: scripts legitimately touch them and the sandbox confines the damage),
-#: cadquery adds ``os``/``sys``/``pathlib`` + the OCC/CQ tooling packages,
-#: opengl_python adds ``os``/``sys`` + clock/tempfile/io modules (determinism).
+#: modules no agent script may import in any python language; languages add their own supersets
BASE_FORBIDDEN_IMPORTS: frozenset[str] = frozenset({
"subprocess", "urllib", "requests", "socket", "http", "shutil", "ctypes", "pickle",
"multiprocessing", "threading", "webbrowser", "ftplib", "smtplib", "importlib",
@@ -29,8 +16,6 @@ BASE_FORBIDDEN_IMPORTS: frozenset[str] = frozenset({
class ImportCollector(ast.NodeVisitor):
- """``imports``: ``{top-level module: first line}`` of every import, in document order
- (a subclass visits the rest of the tree for its own rules)."""
def __init__(self) -> None:
self.imports: dict[str, int] = {}
@@ -44,16 +29,7 @@ class ImportCollector(ast.NodeVisitor):
def safe_parse(source: str, filename: str = "<src>") -> tuple[ast.AST | None, BaseException | None]:
- """``ast.parse`` that never raises: ``(tree, None)`` or ``(None, exception)``.
-
- Besides ``SyntaxError``, CPython raises ``RecursionError`` (3.12+), ``SystemError``
- ("AST constructor recursion depth mismatch", 3.11) or ``MemoryError`` on a source
- whose expressions / literals nest deeper than the parser's C stack, and
- ``ValueError`` on null bytes. A generated file can do any of these; a lint
- that lets them escape crashes the whole run (compare_v4_calm 2026-08-25:
- ``veh_easy_toy_car``'s round died in ``build_once`` instead of the agent being
- told to flatten its literal).
- """
+ """``ast.parse`` that never raises: ``(tree, None)`` or ``(None, exception)``."""
try:
return ast.parse(source, filename=filename), None
except SyntaxError as e:
@@ -95,19 +71,11 @@ def check_imports(
allowed: Collection[str],
make_finding: Callable[[str, str, int], GateFinding],
) -> list[GateFinding]:
- """Route each ``{top-level module: line}`` through the language's import policy.
-
- ``make_finding(kind, module, line)`` builds the finding — ``kind`` is
- ``"forbidden"`` (module in ``forbidden``) or ``"unexpected"`` (module in
- neither set); the caller owns message, severity and hint text.
- """
+ """Route each ``{top-level module: line}`` through the import policy; ``make_finding`` builds the finding."""
out: list[GateFinding] = []
for mod, line in imports.items():
if not mod:
- # `from . import helpers` has no top-level module to police: ast gives
- # `node.module is None` and every visitor records "". Reporting it produced
- # "import of '' is unexpected" — a finding the agent cannot act on — in all
- # three languages that share this helper (2026-08-30).
+# `from . import x` has no top-level module (node.module is None); skip it.
continue
if mod in forbidden:
out.append(make_finding("forbidden", mod, line))
diff --git a/harness/codeverse3d/languages/_common.py b/harness/codeverse3d/languages/_common.py
index 6cfbec2f..1a6b1ff7 100644
--- a/harness/codeverse3d/languages/_common.py
+++ b/harness/codeverse3d/languages/_common.py
@@ -1,19 +1,7 @@
-"""Shared helpers for the language runtimes — the wrapper build of the python ones
-(blender, cadquery, urdf), and the finding locations and typed failure names every lint uses.
-
-The python runtimes execute a *wrapper script* in a subprocess (Blender's python or the
-harness python). The wrapper writes ``artifacts/build.json`` (+ ``census.json``)
-and the runtime turns those into a :class:`BuildResult`. This module owns:
-
-* :func:`run_wrapper_build` — the blender / cadquery build: invalidate, missing entry,
- wrapper subprocess, then :func:`compose_build_result`;
-* :func:`compose_build_result` — wrapper json + process outcome → BuildResult,
- failing loud when the wrapper did not report, published as ``build.json``;
-* :func:`read_json_file` / :func:`strip_blender_noise`;
-* :func:`line_of` / :func:`ws_rel` — the lints' finding locations.
-
-Wrappers themselves are standalone scripts in ``languages/wrappers/`` (they never
-import ``codeverse3d``; Blender's bundled python cannot see this package).
+"""Shared helpers for the language runtimes: the python wrapper build (blender, cadquery, urdf),
+finding locations and the typed failure names every lint uses.
+
+Wrappers are standalone scripts in ``languages/wrappers/``; they never import ``codeverse3d``.
"""
from __future__ import annotations
@@ -28,9 +16,7 @@ from codeverse3d.contracts.common import ENTRY_FILE, Language
from codeverse3d.proc import ProcResult, read_json_or_none, run_subprocess, tail, write_json_atomic
from codeverse3d.workspace import Workspace
-#: The one spelling of every runtime's typed build failures — recorded in build.json /
-#: record.json / bench cells, so the strings stay as first recorded (2026-08-29: threejs,
-#: urdf said "Timeout" and the GL runtimes "MissingEntry"; nothing keyed on either).
+#: The one spelling of every runtime's typed build failures (recorded in build.json / record.json).
MISSING_ENTRY = "MissingEntryFile"
BUILD_TIMEOUT = "BuildTimeout"
@@ -111,11 +97,7 @@ def read_json_file(path: Path) -> dict[str, Any]:
def missing_entry(ws: Workspace, language: Language, *, write: bool = True) -> BuildResult | None:
- """The one "entry file missing" check every runtime's ``build`` makes after wiping its
- outputs: a typed ``MISSING_ENTRY`` failure (published as ``build.json`` unless ``write``
- is off) when ``ENTRY_FILE[language]`` is absent, else ``None``. Until 2026-09-24 five
- checks gave three outcomes: urdf a ``LintError``, and a scene with no ``scene.js`` a
- ``scene_probe`` harness failure that no repair was ever asked to fix."""
+ """Typed ``MISSING_ENTRY`` failure (published as ``build.json`` unless ``write`` is off) when the entry file is absent, else ``None``."""
entry = ENTRY_FILE[language]
if (ws.root / entry).is_file():
return None
@@ -129,11 +111,9 @@ def missing_entry(ws: Workspace, language: Language, *, write: bool = True) -> B
def run_wrapper_build(ws: Workspace, *, language: Language, extras: Mapping[str, str],
argv: Callable[[], list[str]], env: dict[str, str], timeout_s: float,
output_filter: Callable[[str], str] | None = None) -> BuildResult:
- """Run a python wrapper build; ``extras`` maps a ``BuildResult.extra_paths`` key to its
- artifact file name. The outputs are invalidated BEFORE the missing-entry early return
- (a deleted model.py must not leave the previous round's object.glb + build.json
- (ok: true) looking current), and ``argv`` is called only after that check, so a
- missing Blender binary raises where it always did."""
+ """Run a python wrapper build; ``extras`` maps a ``BuildResult.extra_paths`` key to its artifact file name.
+
+ Outputs are invalidated before the missing-entry return so a stale glb never looks current."""
ws.artifacts.mkdir(parents=True, exist_ok=True)
build_json = ws.artifacts / "build.json"
ws.stage_artifacts("build.json", "census.json", "object.glb", *extras.values()).invalidate()
@@ -156,17 +136,10 @@ def compose_build_result(
output_filter: Callable[[str], str] | None = None,
publish: bool = True,
) -> BuildResult:
- """Merge the wrapper's ``build.json`` with the process outcome, and write the result
- over it: ``build.json`` is always the BuildResult, the one status file the tools read.
-
- Contract: success requires the wrapper to say ``ok`` AND — for a build that has one
- (``glb_path``) — a non-empty GLB on disk. Timeouts / crashes before ``build.json``
- exists become a failed BuildResult with a typed error (``BUILD_TIMEOUT`` /
- ``WrapperCrash``) — never an exception — so the orchestrator can route them to repair.
- The wrapper's own diagnostics (traceback, warnings, exports …) land in
- ``census["build_report"]``. ``publish=False`` leaves ``build_json`` as the wrapper wrote it
- (a runtime that finishes the build itself — scene_blender probes the census GLB next).
- """
+ """Merge the wrapper's ``build.json`` with the process outcome and write the result over it.
+
+ Success requires wrapper ``ok`` and, when ``glb_path`` is set, a non-empty GLB. Timeouts and
+ crashes become a failed BuildResult. ``publish=False`` leaves ``build_json`` as the wrapper wrote it."""
stdout_tail = tail(output_filter(proc.stdout) if output_filter else proc.stdout)
stderr_tail = tail(output_filter(proc.stderr) if output_filter else proc.stderr)
base = dict(language=language, stdout_tail=stdout_tail, stderr_tail=stderr_tail, duration_ms=proc.duration_ms)
diff --git a/harness/codeverse3d/languages/_gl_common.py b/harness/codeverse3d/languages/_gl_common.py
index 4021fd54..4db2aa7e 100644
--- a/harness/codeverse3d/languages/_gl_common.py
+++ b/harness/codeverse3d/languages/_gl_common.py
@@ -1,19 +1,5 @@
-"""Shared build plumbing for the two graphics languages (glsl_shader, opengl_python).
-
-``finish_build`` turns a :class:`GlResult` into the canonical artifact set —
-``artifacts/frames/*.png`` (written by the runner), ``artifacts/frames_sheet.png``,
-``artifacts/preview.gif``, ``artifacts/metrics.json`` (frame stats + the
-``gl_frames`` gate), ``artifacts/build.json`` — and a typed :class:`BuildResult`
-(``glb_path`` is always None: the deliverable is code + frames; ``gates`` carries the
-``gl_frames`` report, which the round takes from there).
-``judge_times`` derives the judged times from the plan's duration.
-``make_host`` is the one place a runtime turns settings into a :class:`GlHost`.
-
-GLSL info-log parsing lives here too (:class:`GlslMessage`, :class:`LineMap`,
-:func:`parse_glsl_log`) so ``opengl_python`` does not depend on its sibling
-``glsl_shader`` package; ``glsl_shader/wrap.py`` composes sources and keeps
-``compose`` / ``Composed`` / ``first_error``, importing the types from here.
-"""
+"""Shared build plumbing for the graphics languages (glsl_shader, opengl_python): ``finish_build``,
+``judge_times``, ``make_host`` and the GLSL info-log parser."""
from __future__ import annotations
@@ -47,13 +33,7 @@ MAX_PIXELS = 1920 * 1080
def invalidate_stale_outputs(ws: Workspace) -> None:
- """Wipe the previous build's GL artifacts at the TOP of ``build()``.
-
- Hoisted from ``GlHost._run`` (which still wipes its own out_dir) so the
- ``MISSING_ENTRY`` early returns — which never reach the host — also clear
- ``frames/`` and ``gl_result.json``; sheet/gif/metrics/build.json were never
- cleared anywhere, so a failed build left the previous round's sheet looking
- current to every bare-existence reader (``read_metrics``, the gallery)."""
+ """Wipe the previous build's GL artifacts at the top of ``build()``, including on MISSING_ENTRY returns."""
ws.stage_artifacts(BUILD_JSON, SHEET_NAME, GIF_NAME, METRICS_NAME).invalidate()
(ws.artifacts / RESULT_NAME).unlink(missing_ok=True)
frames = ws.artifacts / FRAMES_DIR
@@ -130,8 +110,6 @@ def finish_build(ws: Workspace, res: GlResult, *, language: str, error_file: str
if res.ok and not res.judge_frames:
result.error_type, result.error_message = "NoFrames", "the renderer produced no frames"
if not result.ok:
- # a failed build must not leave the previous round's derived artifacts
- # (sheet / gif / metrics are written only on ok above) looking current
ws.stage_artifacts(SHEET_NAME, GIF_NAME, METRICS_NAME).invalidate()
ws.write_json(art / BUILD_JSON, result)
return result
@@ -160,8 +138,7 @@ def traceback_location(tb: str, program_path: Path) -> tuple[str, int | None]:
# --------------------------------------------------------------------------- GLSL info logs
-# The composed-source line map (``wrap.compose`` builds one) and the driver-dialect
-# log parser live here so both GL runtimes can map compiler messages to agent files.
+# Composed-source line map and driver-dialect log parser shared by both GL runtimes.
@dataclass(frozen=True)
diff --git a/harness/codeverse3d/languages/_js_lint.py b/harness/codeverse3d/languages/_js_lint.py
index d9696392..46b55ea3 100644
--- a/harness/codeverse3d/languages/_js_lint.py
+++ b/harness/codeverse3d/languages/_js_lint.py
@@ -1,27 +1,6 @@
-"""Shared node-side lint primitives for the JS authoring languages (threejs, scene_threejs).
-
-Replaces two copies of the same algorithm: ``threejs/lint.py:check_syntax`` +
-``_lint_imports`` and ``scene_threejs/lint.py:_node_check`` + ``_check_imports``.
-Both matched static, re-export and dynamic import specifiers with near-identical
-regexes and applied the same allowlist (``three``, ``three/addons/*``,
-``three/examples/jsm/*``, relative files under ``src/``). They differed only in
-message text (owned by the caller via ``make_finding``, as in :mod:`_ast_lint`) and
-in two defects this module fixes: threejs's fallback message was a ``list``
-(``splitlines()[-1:]``), and scene's escape check was a ``str.startswith`` prefix
-test that let ``src2/`` pass. Escape is decided before existence so a
-symlink/``..`` hop out of ``src/`` is reported as an escape, never as "missing".
-
-Syntax is ``runtime_js/lib/syntax_check.mjs`` (export_glb's checker too) in ONE node
-process per lint, skipping files whose bytes already parsed — it was one ``node --check``
-per file: 51 on a scene, 44 of them unchanged ``src/lib`` modules, ≈ 2.5 s a build call.
-
-:func:`check_named_imports` is the second half of the import policy: ``check_imports`` only
-asks whether the TARGET exists, so ``import { concrete } from '../lib/materials.js'`` passed
-the lint and died at module link ("does not provide an export named 'concrete'") — the
-argon loop's iteration 0 lost two whole zones to it at assembly (run
-``it00_scene_threejs_r1_18``, scored 0.47). Exports are read from the target's source
-text (:func:`module_exports`), once per file per lint through the caller's cache.
-"""
+"""Shared node-side lint primitives for the JS authoring languages (threejs, scene_threejs):
+syntax check, import policy, named-import and export-surface checks. The caller owns finding text
+via ``make_finding``."""
from __future__ import annotations
@@ -36,23 +15,18 @@ from codeverse3d.languages._common import line_of
from codeverse3d.proc import sha256_file
from codeverse3d.spatial.node import NodeError, run_node, runtime_js_dir
-# threejs's regexes (the superset: side-effect ``import './x.js'``, ``export * from``,
-# ``export * as ns from`` and multi-line ``import {\n a,\n b\n} from`` all match)
_IMPORT_RE = re.compile(
r"""(?:^|\n)\s*(?:import\s+(?:[^'";]*?\s+from\s+)?|export\s+(?:\*(?:\s+as\s+\w+)?|\{[^}]*\})\s+from\s+)['"]([^'"]+)['"]"""
)
_DYN_IMPORT_RE = re.compile(r"""\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)""")
_URL_RE = re.compile(r"https?://")
-# strings and comments in ONE alternation so a '//' inside a string is not a comment
_TOKEN_RE = re.compile(
r"""'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`|//[^\n]*|/\*.*?\*/""", re.S
)
def strip_js(src: str, *, strings: bool = True) -> str:
- """Blank out comments (and, with ``strings``, string contents), keeping newlines so line
- numbers survive: the forbidden-token lints read code, never a comment quoting the contract.
- scene_threejs keeps strings (its network rule matches URL literals)."""
+ """Blank out comments (and, with ``strings``, string contents), keeping newlines so line numbers survive."""
def repl(m: re.Match[str]) -> str:
tok = m.group(0)
if not tok.startswith("/"):
@@ -63,22 +37,17 @@ def strip_js(src: str, *, strings: bool = True) -> str:
@dataclass(frozen=True)
class SyntaxProblem:
- """What ``node --check`` reported: ``line`` is None when it could not be parsed
- (or node could not run), ``stderr_tail`` is the last 600 chars of stderr."""
+ """What ``node --check`` reported: ``line`` is None when unparseable; ``stderr_tail`` is the last 600 chars."""
line: int | None
message: str
stderr_tail: str
-#: sha256 of file contents that parsed — library modules are byte-identical build after build
_PARSED: set[str] = set()
def node_check_syntax(paths: Sequence[Path]) -> dict[Path, SyntaxProblem]:
- """``{path: problem}`` for every file of ``paths`` that does not parse as an ES
- module; one ``node`` for the lot, and none at all when every file's content
- already parsed in this process."""
digests: dict[Path, str] = {}
out: dict[Path, SyntaxProblem] = {}
for p in paths:
@@ -105,7 +74,6 @@ def node_check_syntax(paths: Sequence[Path]) -> dict[Path, SyntaxProblem]:
def js_sources(src: Path, *, dotfiles: bool = False, mjs: bool = False) -> list[Path]:
- """The ``*.js`` under ``src`` (never ``node_modules``); scene also lints dot-files and ``*.mjs``."""
if not src.is_dir():
return []
js = sorted(p for p in src.rglob("*.js") if "node_modules" not in p.parts and (dotfiles or not p.name.startswith(".")))
@@ -113,7 +81,6 @@ def js_sources(src: Path, *, dotfiles: bool = False, mjs: bool = False) -> list[
def import_specs(src: str) -> list[tuple[str, int]]:
- """``(specifier, 1-based line)`` for every static, re-export and dynamic import in ``src``."""
out = [(m.group(1), m.start(1)) for m in _IMPORT_RE.finditer(src)]
out += [(m.group(1), m.start(1)) for m in _DYN_IMPORT_RE.finditer(src)]
return [(spec, line_of(src, pos)) for spec, pos in out]
@@ -131,12 +98,10 @@ class ImportKind(StrEnum):
@dataclass(frozen=True)
class ImportVerdict:
kind: ImportKind
- #: resolved relative target (set for the three relative kinds), else None
target: Path | None = None
def classify_import(spec: str, path: Path, src_root: Path) -> ImportVerdict:
- """Apply the JS import policy to one specifier found in ``path`` (a file under ``src_root``)."""
if spec == "three" or spec.startswith("three/addons/") or spec.startswith("three/examples/jsm/"):
return ImportVerdict(ImportKind.ALLOWED)
if spec.startswith("./") or spec.startswith("../"):
@@ -160,12 +125,7 @@ def check_imports(
*,
make_finding: Callable[[ImportVerdict, str, int], GateFinding],
) -> tuple[list[GateFinding], set[Path]]:
- """Classify every import in ``src``; return the findings for the non-allowed ones
- and the set of resolved relative files it imports.
-
- ``make_finding(verdict, spec, line)`` builds the finding — the caller owns
- message, severity and hint text.
- """
+ """Classify every import in ``src``; return the findings for non-allowed ones and the resolved relative files."""
findings: list[GateFinding] = []
targets: set[Path] = set()
for spec, line in import_specs(src):
@@ -200,15 +160,12 @@ _EXPORT_DEFAULT_RE = re.compile(r"\bexport\s+default\b")
# ``export const { a, b } = …`` / ``export const [x] = …``: names inside a pattern
_EXPORT_PATTERN_RE = re.compile(r"\bexport\s+(?:const|let|var)\s*[\[{]")
-#: ``{resolved target: its exports}`` — one lint reads each ``src/lib`` module once, not once
-#: per importer (a scene has ~50 files importing the same dozen modules)
ExportsCache = dict[Path, frozenset[str] | None]
@dataclass(frozen=True)
class NamedImport:
- """One static ``import { a, b as c } from '<spec>'``: ``names`` are the IMPORTED names
- (``a`` and ``b`` — what the target module must export, not the local aliases)."""
+ """One static ``import { a, b as c } from '<spec>'``; ``names`` are the imported names, not aliases."""
spec: str
names: tuple[str, ...]
@@ -216,8 +173,6 @@ class NamedImport:
def named_import_specs(src: str) -> list[NamedImport]:
- """Every static named import of ``src`` (comments blanked first, so a commented-out
- import is not parsed); ``import * as m`` and default-only imports yield nothing."""
code = strip_js(src, strings=False) # the specifier is a string literal: keep strings
out: list[NamedImport] = []
for m in _NAMED_IMPORT_RE.finditer(code):
@@ -229,10 +184,7 @@ def named_import_specs(src: str) -> list[NamedImport]:
def module_exports(src: str) -> frozenset[str] | None:
- """The names an ES module's source text exports, or ``None`` when its surface cannot be
- enumerated from the text alone: a bare ``export * from '…'`` (another module's surface —
- not resolved transitively, so nothing is reported against such a module) or a
- destructuring ``export const { a } = …`` pattern. ``export default`` exports ``default``."""
+ """Names an ES module's source exports, or ``None`` when not enumerable from text (bare ``export * from``, destructured exports)."""
code = strip_js(src)
if _EXPORT_PATTERN_RE.search(code):
return None
@@ -262,11 +214,7 @@ SIGNATURE_CHARS = 240
def export_signatures(src: str) -> list[str]:
- """Every name the module exports, an exported function — a declaration, or a ``const`` bound to
- an arrow / function expression — as ``name(params)`` (its parameter list as written, whitespace
- collapsed, capped at :data:`SIGNATURE_CHARS`), sorted; ``[]`` when the surface cannot be
- enumerated (:func:`module_exports`). Facts read off the text —
- the index a single-shot writer gets of a library it cannot open (D112)."""
+ """Every exported name, functions as ``name(params)`` (capped at :data:`SIGNATURE_CHARS`), sorted; ``[]`` when not enumerable."""
names = module_exports(src)
if not names:
return []
@@ -278,7 +226,6 @@ def export_signatures(src: str) -> list[str]:
sigs[name] = sig if len(sig) <= SIGNATURE_CHARS else sig[:SIGNATURE_CHARS - 2] + "…)"
def _close(start: int) -> int:
- """The index just past the ``)`` matching the ``(`` before ``start``."""
depth, i = 1, start
while i < len(code) and depth:
depth += {"(": 1, ")": -1}.get(code[i], 0)
@@ -297,7 +244,6 @@ def export_signatures(src: str) -> list[str]:
def exported_names(path: Path) -> frozenset[str] | None:
- """:func:`module_exports` of the file at ``path`` (``None`` when it cannot be read)."""
try:
return module_exports(path.read_text(errors="replace"))
except OSError:
@@ -305,7 +251,6 @@ def exported_names(path: Path) -> frozenset[str] | None:
def describe_exports(names: frozenset[str], *, limit: int = 12) -> str:
- """``it exports: a, b, …`` (sorted, at most ``limit`` named) or ``it exports nothing``."""
if not names:
return "it exports nothing"
shown = sorted(names)[:limit]
@@ -320,14 +265,9 @@ def check_named_imports(
make_finding: Callable[[str, str, int, frozenset[str]], GateFinding],
exports: ExportsCache | None = None,
) -> list[GateFinding]:
- """A finding per imported name that its target module does not export, for every named
- import of ``src`` whose specifier resolves to an existing ``.js`` / ``.mjs`` file under
- ``src_root`` (``'three'`` and the non-allowed kinds are :func:`check_imports`'s business).
-
- ``make_finding(spec, name, line, exports)`` builds the finding — the caller owns message,
- severity and hint; ``exports`` is the target's surface, for an "it exports: …" listing.
- Pass one ``exports`` cache for the whole lint so each target is read once.
- """
+ """A finding per imported name its target module does not export, for relative targets under ``src_root``.
+
+ Pass one ``exports`` cache for the whole lint."""
cache: ExportsCache = {} if exports is None else exports
findings: list[GateFinding] = []
for imp in named_import_specs(src):
diff --git a/harness/codeverse3d/languages/base.py b/harness/codeverse3d/languages/base.py
index 513379eb..71e8c7a5 100644
--- a/harness/codeverse3d/languages/base.py
+++ b/harness/codeverse3d/languages/base.py
@@ -1,12 +1,4 @@
-"""LanguageRuntime protocol + registry.
-
-A runtime knows how to (1) lay down starter files for a plan — and so which file
-owns what (``expected_files`` / ``files_for``: the tracks ask, never restate), (2)
-statically lint agent code for known pitfalls, (3) execute it in a sandboxed
-subprocess and export the canonical artifact(s). Its authoring contract is prompt
-material (``prompts/<lang>/contract.md``, found by ``prompts.catalog.language_prompt``).
-Runtimes never import agent code into the harness process.
-"""
+"""LanguageRuntime protocol + registry: starter files, static lint, sandboxed build, file ownership."""
from __future__ import annotations
@@ -50,20 +42,15 @@ class LanguageRuntime(Protocol):
...
def files_for(self, plan: Plan | None, target: str) -> list[str]:
- """The files that own a refine target (a part, zone, asset, camera, env word); ``[]`` = no
- owner, so the task stays whole-artifact."""
+ """The files that own a refine target (part, zone, asset, camera, env word); ``[]`` leaves the task whole-artifact."""
...
@runtime_checkable
class SceneRuntime(LanguageRuntime, Protocol):
- """What the scene track asks of its language (D101): where a zone / asset lives, how the
- entry is assembled from the zones, how the built scene is probed and rendered. The scene
- stages, ``Services`` and the scene tools reach a scene language only through this."""
+ """What the scene track asks of its language: zone / asset locations, entry assembly, probe and render."""
- #: the environment module the env stage writes (``src/env.js`` / ``src/env.py``): the one
- #: file a scene session owns besides the zones and assets, named by the runtime so no track
- #: code tests a path for ``.js`` / ``.py``
+#: the environment module the env stage writes (``src/env.js`` / ``src/env.py``)
env_file: str
def zone_file(self, name: str) -> str:
@@ -80,21 +67,15 @@ class SceneRuntime(LanguageRuntime, Protocol):
...
def lib_interface(self, ws: Workspace) -> str:
- """The harness-owned ``src/lib/`` as facts, one line per module: the names it exports and
- their parameter lists, read off the files (D112: the env recovery's single-shot cannot open
- them, and invented ``gravel`` / ``pavingPatch`` / a ``roughness=`` keyword); ``""`` for a
- language that ships none."""
+ """The harness-owned ``src/lib/`` as one fact line per module (exports and parameters); ``""`` if none."""
...
def check_env(self, ws: Workspace) -> str:
- """The env module alone: ``""`` when it lints clean, builds with nothing beside it and
- lights what it builds; else the failure, quoted for a repair prompt (D112). A check the
- harness cannot run returns ``""`` — never a verdict on the module."""
+ """The env module alone: ``""`` when it lints, builds and lights clean; else the failure, quoted for a repair prompt."""
...
def probe(self, ws: Workspace, *, timeout_s: float | None = None) -> SceneProbeResult:
- """Load the built scene headlessly: the ``scene_probe`` gate + the census (``census.json``),
- under the build's own budget by default (D111)."""
+ """Load the built scene headlessly: the ``scene_probe`` gate + the census."""
...
def render_scene(self, ws: Workspace, out_dir: Path, *, cameras: list[CameraPlan] | None = None, orbit: bool = True,
@@ -105,9 +86,7 @@ class SceneRuntime(LanguageRuntime, Protocol):
class RuntimeLayout:
- """``expected_files`` / ``files_for`` for a runtime whose entry file (+ ``extra_files``) owns
- the whole artifact — or, when it sets ``part_file``, one file per plan part too. The scene
- runtime lays out zones / assets / env and overrides both."""
+ """``expected_files`` / ``files_for`` for a runtime whose entry file (+ ``extra_files``) owns the whole artifact."""
language: Language
#: files a whole-artifact session owns besides the entry (urdf: robot.urdf; glsl_shader: common.glsl)
@@ -128,8 +107,7 @@ class RuntimeLayout:
return [ENTRY_FILE[self.language]] if key in ("overall", "assembly", "object", "") else []
-#: Language → (module, class). Adding a language is a row, and the import stays lazy
-#: (a runtime pulls in bpy / moderngl / node bindings the other six do not need).
+#: Language → (module, class); the import is lazy.
_RUNTIMES: dict[Language, tuple[str, str]] = {
Language.BLENDER: ("codeverse3d.languages.blender", "BlenderRuntime"),
Language.CADQUERY: ("codeverse3d.languages.cadquery", "CadQueryRuntime"),
diff --git a/harness/codeverse3d/languages/blender/__init__.py b/harness/codeverse3d/languages/blender/__init__.py
index 5215043d..f8879290 100644
--- a/harness/codeverse3d/languages/blender/__init__.py
+++ b/harness/codeverse3d/languages/blender/__init__.py
@@ -32,13 +32,10 @@ GATE = "lint:blender"
ALLOWED_IMPORTS = {
"bpy", "bmesh", "mathutils", "math", "random", "numpy", "np", "itertools", "functools",
"collections", "typing", "dataclasses", "colorsys", "statistics", "operator", "enum", "copy",
- # os/sys are deliberately ALLOWED here (unlike cadquery/opengl): headless bpy scripts
- # touch them legitimately and the forbidden-call rules below catch the harmful uses.
"sys", "os", "__future__", "bpy_extras",
"parts", # the workspace's own src/parts/<snake>.py modules (multi-file layout)
}
FORBIDDEN_IMPORTS = frozenset(BASE_FORBIDDEN_IMPORTS | {"pathlib"})
-# dotted-name prefixes of calls that violate the contract (harness owns them)
FORBIDDEN_CALL_PREFIXES: tuple[tuple[str, str], ...] = (
("bpy.ops.render.", "rendering is done by the harness; delete all bpy.ops.render.* calls"),
("bpy.ops.export_", "export is done by the harness; delete all bpy.ops.export_* calls"),
@@ -64,8 +61,7 @@ WARN_CALL_PREFIXES: tuple[tuple[str, str, LintKind], ...] = (
("sys.exit", "do not exit; let the script fall off the end", LintKind.SANDBOX),
)
# Principled BSDF inputs that raise KeyError in Blender 4.x/5.x → their replacement.
-# Verified against Blender 5.2.2 LTS (2026-10-14): 'Anisotropic' and 'Specular Tint' STILL EXIST (do not
-# list them); 5.2.2 also has 'Thin Wall', 'Thin Film Thickness' and 'Thin Film IOR'.
+# Verified on Blender 5.2.2: 'Anisotropic' and 'Specular Tint' still exist (do not list them).
REMOVED_BSDF_INPUTS = {
"Specular": "Specular IOR Level", "Subsurface": "Subsurface Weight", "Transmission": "Transmission Weight",
"Emission": "Emission Color (+ 'Emission Strength')", "Subsurface Color": "Base Color (subsurface tint removed)",
@@ -76,19 +72,18 @@ KNOWN_BINDINGS = ("Vector", "Matrix", "Euler", "Quaternion", "bmesh", "math", "r
class BpyCollector(ast.NodeVisitor):
- """One pass over the tree; rules read the collected facts."""
def __init__(self) -> None:
- self.imports: dict[str, int] = {} # top-level module → line
+ self.imports: dict[str, int] = {}
self.bound: set[str] = set()
self.calls: list[tuple[str, ast.Call]] = []
- self.attr_stores: list[tuple[str, int]] = [] # dotted target of assignments
+ self.attr_stores: list[tuple[str, int]] = []
self.name_loads: list[tuple[str, int]] = []
- self.bm_names: set[str] = set() # names bound from bmesh.new() / bmesh.from_edit_mesh()
- self.bm_subscripts: list[tuple[str, int]] = [] # (base name, line) of <name>.verts/edges/faces[i]
+ self.bm_names: set[str] = set()
+ self.bm_subscripts: list[tuple[str, int]] = []
self.bsdf_inputs: list[tuple[str, int, bool]] = [] # (key, line, inside `if '<key>' in x.inputs:`)
- self._guarded: list[frozenset[str]] = [] # keys the enclosing if/elif tests are membership checks of
- self.names_assigned: list[str] = [] # string constants assigned to .name / name=
+ self._guarded: list[frozenset[str]] = []
+ self.names_assigned: list[str] = []
self.constants: list[tuple[str, int]] = []
self.gn_item_stores: list[tuple[str, int]] = [] # (key, line) of <x>["Socket_N"] = … (pre-5.2 GN inputs)
self.has_temp_override = False
@@ -186,8 +181,6 @@ class BpyCollector(ast.NodeVisitor):
def visit_Subscript(self, node: ast.Subscript) -> None:
if isinstance(node.value, ast.Attribute):
- # only <Name>.verts/edges/faces[i] — e.verts[0] (BMEdge) / me.edges[i] (Mesh) are
- # filtered later against the names actually bound to a bmesh (BMElemSeq).
if (node.value.attr in ("verts", "edges", "faces") and not isinstance(node.slice, ast.Slice)
and isinstance(node.value.value, ast.Name)):
self.bm_subscripts.append((node.value.value.id, node.lineno))
@@ -213,10 +206,8 @@ def _f(kind: LintKind, sev: Severity, msg: str, line: int | None = None, hint: s
-# The API traps of bpy itself, whatever the file builds: the object lint (``_rules``) and the scene
-# lint (``languages/scene_blender``) both call these, so a Blender rename is learned once.
+# API traps of bpy itself, shared by the object lint and the scene lint.
def call_traps(c: BpyCollector, name: str, call: ast.Call) -> list[GateFinding]:
- """Removed / context-dependent operator and method calls (one call)."""
out: list[GateFinding] = []
E, W = Severity.ERROR, Severity.WARN
if name.startswith("bpy.ops.") and call.args and isinstance(call.args[0], ast.Dict):
@@ -235,8 +226,6 @@ def call_traps(c: BpyCollector, name: str, call: ast.Call) -> list[GateFinding]:
if name.endswith("modifier_apply") and not c.has_temp_override:
out.append(_f(LintKind.API_TRAP, W, "bpy.ops.object.modifier_apply needs the object active+selected in OBJECT mode", call.lineno,
"either leave modifiers unapplied (the exporter applies them) or wrap: `with bpy.context.temp_override(object=obj): bpy.ops.object.modifier_apply(modifier=mod.name)`"))
- # the rule's own precondition: a script that sets the active object before joining (as a
- # urdf_blender model does to get one joined object per link) has done what the warning asks
if (name.endswith("bpy.ops.object.join") or name == "bpy.ops.object.join") and not any(
t.endswith("view_layer.objects.active") for t, _ in c.attr_stores):
out.append(_f(LintKind.API_TRAP, W, "bpy.ops.object.join needs all parts selected + an active object; the result inherits the ACTIVE object's transform", call.lineno,
@@ -249,7 +238,6 @@ def call_traps(c: BpyCollector, name: str, call: ast.Call) -> list[GateFinding]:
def store_traps(target: str, line: int) -> list[GateFinding]:
- """Assignments to properties Blender 4.1 removed."""
if target.endswith(".use_auto_smooth") or target.endswith(".auto_smooth_angle"):
return [_f(LintKind.API_TRAP, Severity.ERROR, f"`{target}` was removed in Blender 4.1", line, "use bpy.ops.object.shade_smooth_by_angle(angle=...) or mark sharp edges; or just shade_smooth()")]
return []
@@ -263,8 +251,7 @@ def use_nodes_trap(target: str, line: int) -> list[GateFinding]:
def gn_input_traps(c: BpyCollector) -> list[GateFinding]:
- """Geometry-nodes modifier inputs set the pre-5.2 way: ``mod["Socket_2"] = v`` raises TypeError
- ("id properties not supported for this type") since Blender 5.2 (verified on 5.2.2)."""
+ """Geometry-nodes modifier inputs set the pre-5.2 way (``mod["Socket_2"] = v``) raise TypeError on 5.2."""
return [_f(LintKind.API_TRAP, Severity.ERROR, f"`[...][{key!r}] = ...`: geometry-nodes modifier inputs are RNA properties in Blender 5.2 "
"(TypeError at runtime)", line,
f"getattr(mod.properties.inputs, {key!r}).value = <value> (identifiers: mod.properties.inputs.keys(); "
@@ -273,7 +260,7 @@ def gn_input_traps(c: BpyCollector) -> list[GateFinding]:
def solver_traps(c: BpyCollector, source: str) -> list[GateFinding]:
- """``solver = 'FAST'``: the boolean solver was renamed — Blender 5.2.2 has FLOAT / EXACT / MANIFOLD."""
+ """``solver = 'FAST'``: renamed; 5.2 has FLOAT / EXACT / MANIFOLD."""
lines = source.splitlines()
return [_f(LintKind.API_TRAP, Severity.ERROR, "boolean solver 'FAST' does not exist in Blender 5.x (TypeError at runtime)", line,
"solver = 'MANIFOLD' (closed meshes) or 'EXACT'; 'FLOAT' is the old FAST")
@@ -293,8 +280,6 @@ def source_traps(c: BpyCollector, source: str) -> list[GateFinding]:
out.append(_f(LintKind.API_TRAP, I, "'Specular Tint' is an RGBA colour in Blender 4.x/5.x (a float raises TypeError)", line,
'assign a 4-tuple: inputs["Specular Tint"].default_value = (r, g, b, 1.0)'))
has_lookup = any(n.endswith("ensure_lookup_table") for n, _ in c.calls)
- # only subscripts on a BMESH object need ensure_lookup_table (BMElemSeq); e.verts[0]
- # (BMEdge/BMFace tuples) and me.edges[i] (Mesh collections) are always fine.
bm_subs = [line for base, line in c.bm_subscripts if base in c.bm_names or base == "bm"]
if "bmesh" in c.imports and bm_subs and not has_lookup:
out.append(_f(LintKind.API_TRAP, E, "bmesh verts/edges/faces indexed with [] but ensure_lookup_table() is never called → IndexError", bm_subs[0],
@@ -360,11 +345,7 @@ def lint_blender_source(
) -> GateReport:
"""Lint one bpy script; returns ``GateReport(gate='lint:blender')``.
- ``expect_names=False`` silences the PascalCase-name warning (multi-file entry files
- only import and call builders); ``expect_bpy=False`` allows helper modules that do
- not touch bpy. :func:`codeverse3d.languages.blender.lint_workspace` lints a
- whole ``src/`` tree with these set per file.
- """
+ ``expect_names=False`` / ``expect_bpy=False`` relax the PascalCase-name and bpy-use checks for entry and helper files."""
t0 = time.monotonic()
findings: list[GateFinding] = []
tree, exc = safe_parse(source, target)
@@ -386,17 +367,14 @@ PARTS_DIR = "parts"
def part_file_rel(part_name: str) -> str:
- """``'Seat Cushion'`` → ``'src/parts/seat_cushion.py'`` (workspace-relative)."""
return f"src/{PARTS_DIR}/{to_snake(part_name)}.py"
def build_fn_name(part_name: str) -> str:
- """``'SeatCushion'`` → ``'build_seat_cushion'`` (the function a part file must export)."""
return f"build_{to_snake(part_name)}"
def part_files(ws: Workspace) -> list[Path]:
- """Part modules present in the workspace (sorted; underscore helper modules excluded)."""
d = ws.src / PARTS_DIR
if not d.is_dir():
return []
@@ -404,7 +382,6 @@ def part_files(ws: Workspace) -> list[Path]:
def source_files(ws: Workspace) -> list[Path]:
- """Every agent-authored python file under ``src/`` (entry first), including nested dirs."""
entry = ws.src / "model.py"
rest = sorted(p for p in ws.src.rglob("*.py") if p != entry)
return ([entry] if entry.is_file() else []) + rest
@@ -415,7 +392,6 @@ def _exported_functions(tree: ast.Module) -> set[str]:
def _imported_part_modules(tree: ast.Module) -> set[str]:
- """snake names of ``parts.<snake>`` modules the entry references via import statements."""
out: set[str] = set()
for node in ast.walk(tree):
if isinstance(node, ast.ImportFrom) and node.module:
@@ -434,7 +410,6 @@ def _imported_part_modules(tree: ast.Module) -> set[str]:
def _layout_rules(ws: Workspace, parts: list[Path], entry_tree: ast.Module | None) -> list[GateFinding]:
- """Cross-file rules: naming, exported builders, import-time side effects, unused part files."""
out: list[GateFinding] = []
E, W = Severity.ERROR, Severity.WARN
imported = _imported_part_modules(entry_tree) if entry_tree is not None else set()
@@ -468,7 +443,6 @@ def _layout_rules(ws: Workspace, parts: list[Path], entry_tree: ast.Module | Non
def lint_workspace(ws: Workspace) -> GateReport:
- """Lint every python file under ``src/`` + the multi-file layout rules (one merged report)."""
t0 = time.monotonic()
entry = ws.root / ENTRY_REL
if not entry.is_file():
@@ -491,7 +465,6 @@ def lint_workspace(ws: Workspace) -> GateReport:
# ===================================================================== skeleton
-#: base colour for a part whose material names no family: a bare colour word
_COLOUR_WORDS: tuple[tuple[str, tuple[float, float, float]], ...] = (
("black", (0.05, 0.05, 0.05)), ("white", (0.9, 0.9, 0.9)), ("red", (0.7, 0.1, 0.1)),
("blue", (0.1, 0.2, 0.7)), ("green", (0.1, 0.5, 0.2)),
@@ -499,9 +472,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 ``_pbr`` (THE PBR table), else a bare
- colour word at the Principled defaults, else neutral grey."""
+ """Placeholder (rgb, roughness, metallic) from the material family, else a bare colour word, else grey."""
hit = family_for(text)
pbr = pbr_for(hit.family) if hit else None
if pbr is not None:
@@ -511,7 +482,6 @@ def finish_for(text: str) -> tuple[tuple[float, float, float], float, float]:
def instance_centers(bbox: BBox, n: int, symmetry: str) -> list[tuple[float, float, float]]:
- """Placeholder centres for ``n`` instances of a part using the plan's symmetry hint."""
cx, cy, cz = bbox.center
if n <= 1:
return [(cx, cy, cz)]
@@ -597,7 +567,6 @@ def _constants(p: PartPlan) -> str:
def _part_function(p: PartPlan) -> str:
- """``def build_<snake>() -> bpy.types.Object`` (placeholder box; instances looped inside)."""
pascal, snake, fn = to_pascal(p.name), to_snake(p.name), build_fn_name(p.name)
pre = snake.upper()
rgb, rough, metal = finish_for(f"{p.material} {p.description}")
@@ -678,7 +647,6 @@ ACCEPTANCE:
# ----------------------------------------------------------------------------- public renderers
def part_file_source(p: PartPlan) -> str:
- """Complete ``src/parts/<snake>.py`` text for one plan part (self-contained, runnable)."""
pascal, fn = to_pascal(p.name), build_fn_name(p.name)
doc = (
f'"""{pascal} — {p.role} (part module; imported by src/model.py).\n\n'
@@ -696,12 +664,10 @@ def part_file_source(p: PartPlan) -> str:
def selfcheck_source(ground_tol_m: float = GROUND_TOL_M) -> str:
- """The entry's self-check with its "stands on z=0" tolerance filled in."""
return SELFCHECK.replace("__GROUND_TOL__", f"{ground_tol_m:g}")
def model_file_source(plan: StaticPlan, *, ground_tol_m: float = GROUND_TOL_M) -> str:
- """Complete multi-file entry ``src/model.py``: imports, ordered calls, self-check."""
imports = "\n".join(f"from {PARTS_DIR}.{to_snake(p.name)} import {build_fn_name(p.name)}" for p in plan.parts)
calls = "\n".join(f" {build_fn_name(p.name)}()" for p in plan.parts)
return (
@@ -717,9 +683,7 @@ def model_file_source(plan: StaticPlan, *, ground_tol_m: float = GROUND_TOL_M) -
def write_blender_skeleton(ws: Workspace, plan: StaticPlan, *, ground_tol_m: float = GROUND_TOL_M) -> list[Path]:
"""Write the starter files (overwrites) and return the written paths (entry first).
- ``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 and whose module twin is allowed 20 mm."""
+ ``ground_tol_m`` is the self-check's "stands on z=0" tolerance."""
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))
@@ -741,10 +705,7 @@ class BlenderNotFoundError(RuntimeError):
def blender_env() -> dict[str, str]:
- """Environment for a headless Blender child: keep the user's env but make sure the
- host python (conda) cannot leak into Blender's bundled interpreter, and strip
- credential-shaped vars (:func:`codeverse3d.proc.scrub_secrets`) — the model-authored
- ``model.py`` executes inside this process and must never see API keys."""
+ """Environment for a headless Blender child: host python cannot leak in, credential-shaped vars are stripped."""
env = scrub_secrets(dict(os.environ))
for k in ("PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP"):
env.pop(k, None)
@@ -795,14 +756,12 @@ class BlenderRuntime(RuntimeLayout):
return write_blender_skeleton(ws, plan)
def lint(self, ws: Workspace) -> GateReport:
- """Lint every python file under ``src/`` + the multi-file layout rules."""
return lint_workspace(ws)
def build(
self, ws: Workspace, *, timeout_s: int | None = None, stl: bool = True, blend: bool = False,
seed: int = 0,
) -> BuildResult:
- """Run the wrapper; never raises for agent-code failures (typed BuildResult instead)."""
return run_wrapper_build(
ws, language=self.language, extras={"stl": "object.stl", "blend": "object.blend"},
argv=lambda: self.build_command(ws, stl=stl, blend=blend, seed=seed),
diff --git a/harness/codeverse3d/languages/blender/_pbr.py b/harness/codeverse3d/languages/blender/_pbr.py
index 19df4b21..5fd294e1 100644
--- a/harness/codeverse3d/languages/blender/_pbr.py
+++ b/harness/codeverse3d/languages/blender/_pbr.py
@@ -1,24 +1,6 @@
-"""THE material-family table: real PBR numbers for the finishes objects are made of.
-
-Why this file exists. The judge's weakest object criterion after ``geometry_detail``
-is ``materials`` (mean 0.701 over 110 recorded verdicts), and its complaints are
-almost always one of two sentences:
-
-* *"the chrome parts lack metallic reflections and appear as matte grey"*
- (`mus_easy_drum` r0) / *"the drill bit and chuck lack metallic material
- properties, appearing as flat grey plastic"* (`tool_med_hand_drill` r1);
-* *"materials are flat colors without any character such as wood grain"*
- (`bld_easy_shed` r0) / *"the blue material lacks roughness variation or bump
- mapping, making it look like smooth plastic rather than cast iron"*
- (`tool_hard_bench_vise` r1).
-
-The numbers below are the ones a materials artist would type — measured
-dielectric IORs, the metallic/roughness pairs the glTF and Disney/Substance
-guides publish, and the clear-coat that separates lacquered wood from raw
-timber. ``languages/blender`` reads them (``family_for`` / ``pbr_for``) to give a
-part whose name or material names a finish its PBR factors.
-
-Everything here is data + pure functions; nothing imports a model or touches a file.
+"""The material-family table: PBR factors (metallic, roughness, IOR, clear-coat) per finish.
+
+``languages/blender`` reads it (``family_for`` / ``pbr_for``). Data + pure functions only.
"""
from __future__ import annotations
@@ -31,13 +13,7 @@ from codeverse3d.conventions import to_snake
class Pbr(BaseModel):
- """One material family's physically-plausible factors.
-
- ``ior``/``clearcoat``/``sheen``/``transmission`` have no home in core glTF
- ``pbrMetallicRoughness`` (they are KHR extensions / Blender + three
- ``MeshPhysicalMaterial`` inputs) — they are carried here because the Blender and
- three.js authoring paths (Principled BSDF / MeshPhysicalMaterial) do use them.
- """
+ """One material family's physically-plausible factors."""
family: str
metallic: float = Field(ge=0.0, le=1.0)
@@ -47,11 +23,9 @@ class Pbr(BaseModel):
clearcoat_roughness: float = 0.1
sheen: float = 0.0
transmission: float = 0.0
- #: linear-ish sRGB base colour a real sample of this finish sits near (a hint,
- #: never forced onto an authored colour)
+#: base colour a real sample of this finish sits near (a hint, never forced)
base_hint: tuple[float, float, float] = (0.5, 0.5, 0.5)
- #: how far the roughness may plausibly wander before the value is "wrong for
- #: this family" (the normaliser's confidence band)
+#: plausible roughness spread (the normaliser's confidence band)
roughness_band: tuple[float, float] = (0.0, 1.0)
metallic_band: tuple[float, float] = (0.0, 1.0)
note: str = ""
@@ -68,7 +42,7 @@ def _m(
roughness_band=rband, metallic_band=mband, note=note)
-#: family -> PBR factors (with the plausible bands each value may take). Metals, woods, polymers, rest.
+#: family -> PBR factors with plausible bands
MATERIALS: dict[str, Pbr] = {
"painted_metal": _m("painted_metal", 0.0, 0.35, clearcoat=0.35, ccr=0.10, base=(0.30, 0.32, 0.36),
rband=(0.08, 0.7), mband=(0.0, 0.35),
@@ -116,8 +90,7 @@ MATERIALS: dict[str, Pbr] = {
note="paint on timber: flatter than car enamel, and the grain still shows through"),
}
-#: substrate keywords — WHAT the part is made of. Checked before finishes, because
-#: "varnished beech" is wood with a coat, not a coating on nothing.
+#: substrate keywords (what the part is made of), checked before finishes
SUBSTRATE_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
("wood_hard", ("oak", "walnut", "teak", "maple", "beech", "birch", "mahogany", "cherry", "ash",
"hardwood", "veneer", "plywood", "bamboo", "rosewood")),
@@ -155,8 +128,7 @@ FINISH_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
("gloss", ("gloss", "glossy", "shiny", "high-gloss", "highgloss")),
)
-#: (substrate, finish) -> family. ``None`` finish = bare; a substrate row missing a
-#: finish falls back to its ``None`` entry.
+#: (substrate, finish) -> family; ``None`` finish = bare
_RESOLVE: dict[tuple[str, str | None], str] = {
("wood_hard", None): "hardwood", ("wood_hard", "painted"): "painted_wood",
("wood_soft", None): "softwood", ("wood_soft", "painted"): "painted_wood",
@@ -203,9 +175,7 @@ class FamilyMatch(NamedTuple):
def _tokens(text: str) -> set[str]:
- """Whole words of ``text`` as :func:`~codeverse3d.conventions.to_snake` splits them
- (snake_case, kebab-case, CamelCase and acronyms: ``PVCPipe`` → ``pvc``, ``pipe``),
- plus the words joined (``pvcpipe``)."""
+ """Whole words of ``text`` as ``to_snake`` splits them, plus the words joined."""
s = str(text or "")
parts = [w for w in to_snake(s).split("_") if w] if any(c.isascii() and c.isalnum() for c in s) else []
joined = "".join(parts)
@@ -239,16 +209,9 @@ def _substrate(toks: set[str]) -> tuple[str, str] | None:
def family_for(*texts: str) -> FamilyMatch | None:
- """Resolve a material family from free text.
-
- Two orderings do the work. Across arguments: the FIRST text that resolves wins,
- so callers pass the most specific evidence first (material name, then node name,
- then the plan's prose) — a node called ``SteamWand`` whose material is
- ``SteamWandChrome`` must not become silicone because the plan's sentence
- mentions a silicone tip. Within one text: substrate before finish, so
- *"varnished beech"* is ``hardwood`` (a coat on wood), *"satin white lacquer"* is
- ``painted_metal`` and *"chrome-plated steel"* is ``chrome``.
- ``None`` when nothing matches."""
+ """Resolve a material family from free text; ``None`` when nothing matches.
+
+ The first argument that resolves wins; within one text, substrate before finish."""
for text in texts: # material name beats node name beats the plan's prose
hit = _resolve_one(_tokens(text))
if hit is not None:
diff --git a/harness/codeverse3d/languages/cadquery/__init__.py b/harness/codeverse3d/languages/cadquery/__init__.py
index d7b0f91a..621e7173 100644
--- a/harness/codeverse3d/languages/cadquery/__init__.py
+++ b/harness/codeverse3d/languages/cadquery/__init__.py
@@ -55,11 +55,7 @@ TO_DEGREES_FUNCS = {"degrees", "rad2deg"}
def looks_like_radians(expr: ast.expr) -> bool:
- """True when ``expr`` is a radians expression (``math.pi``, ``math.pi / 2``, ``i * 2 * math.pi / n``,
- ``math.radians(a)``) — never a plain name/number, never a conversion TO degrees
- (``a * 180 / math.pi``, ``math.degrees(a)``). Only the ``pi``/``tau`` constants and the
- radians/degrees helpers are inspected, so identifiers such as ``n_pins`` or ``pitch`` cannot match.
- """
+ """True when ``expr`` is a radians expression (``math.pi / 2``, ``math.radians(a)``), not a conversion to degrees."""
hit = False
def walk(node: ast.AST, inverted: bool) -> bool:
@@ -307,9 +303,7 @@ WRAPPER = Path(__file__).resolve().parent.parent / "wrappers" / "run_cq.py"
def cadquery_env() -> dict[str, str]:
- """Environment for the wrapper subprocess that executes the model-authored
- ``src/model.py``: the user's env minus credential-shaped vars
- (:func:`codeverse3d.proc.scrub_secrets`)."""
+ """Environment for the wrapper subprocess: the user's env minus credential-shaped vars."""
env = scrub_secrets(dict(os.environ))
env.pop("PYTHONSTARTUP", None)
env.setdefault("OMP_NUM_THREADS", "4")
@@ -332,7 +326,7 @@ class CadQueryRuntime(RuntimeLayout):
return ws.src / "model.py"
def build_command(self, ws: Workspace, *, seed: int = 0) -> list[str]:
- """The wrapper's own --tolerance / --angular-tolerance defaults are the tessellation."""
+ """The wrapper's own tolerance defaults are the tessellation."""
return [
self._python, str(WRAPPER), "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts),
"--rlimit-gb", str(self._rlimit_gb), "--seed", str(seed),
diff --git a/harness/codeverse3d/languages/glsl_shader/__init__.py b/harness/codeverse3d/languages/glsl_shader/__init__.py
index 78d3cbc6..0b99c68e 100644
--- a/harness/codeverse3d/languages/glsl_shader/__init__.py
+++ b/harness/codeverse3d/languages/glsl_shader/__init__.py
@@ -53,8 +53,7 @@ MAIN_IMAGE_TRAILER = """
void main() { mainImage(fragColor, gl_FragCoord.xy); }
"""
-#: ONE left-to-right scan: a `//` inside a block comment and a `/*` inside a line comment
-#: are comment text. Two passes (blocks, then lines) blanked real code after `// … /*`.
+#: One left-to-right scan: `//` inside a block comment and `/*` inside a line comment are comment text.
_COMMENT = re.compile(r"//[^\n]*|/\*.*?\*/", re.S)
_MAIN_IMAGE = re.compile(r"\bvoid\s+mainImage\s*\(")
_PLAIN_MAIN = re.compile(r"\bvoid\s+main\s*\(\s*(void)?\s*\)")
@@ -91,10 +90,7 @@ def _unconditional(src: str) -> str:
def detect_convention(shader_src: str) -> str:
- """``main`` when the author wrote a ``main()`` (with or without a ``mainImage`` it calls — the usual
- Shadertoy-port pattern), else ``mainImage`` (the harness appends the ``main()`` trailer). Appending
- the trailer to a file that already has ``main()`` redefined it: codex gpt-6-luna wrote both on 4 of
- 4 one-shot shaders (p3x_graphics_v2, 2026-09-23) and every one failed to compile at ``harness:3``."""
+ """``main`` when the author wrote a ``main()``, else ``mainImage`` (the harness appends the ``main()`` trailer)."""
shader_src = strip_comments(shader_src)
# a main() only inside #if/#ifdef (a STANDALONE guard) is not the entry point the harness compiles
if _PLAIN_MAIN.search(_unconditional(shader_src)):
@@ -114,8 +110,7 @@ def _piece(text: str) -> str:
def compose(shader_src: str, common_src: str | None = None, *,
shader_file: str = "src/shader.frag", common_file: str = "src/common.glsl") -> Composed:
- """Header + common + shader (+ trailer) with a line
- map back to the agent files."""
+ """Header + common + shader (+ trailer) with a line map back to the agent files."""
convention = detect_convention(shader_src)
pieces: list[tuple[str, str]] = [("harness", HEADER)]
if common_src and common_src.strip():
@@ -138,8 +133,7 @@ def compose(shader_src: str, common_src: str | None = None, *,
# --------------------------------------------------------------------------- compiler messages
-# GlslMessage / LineMap / parse_glsl_log live in ``_gl_common`` (shared with opengl_python)
-# and are re-exported above; only source composition + first_error remain here.
+# GlslMessage / LineMap / parse_glsl_log live in ``_gl_common``.
def first_error(messages: list[GlslMessage]) -> GlslMessage | None:
for m in messages:
if m.kind == "error":
@@ -353,7 +347,7 @@ class GlslShaderRuntime(RuntimeLayout):
def build(self, ws: Workspace, *, timeout_s: int | None = None, times: list[float] | None = None,
preview: bool = True, width: int | None = None, height: int | None = None) -> BuildResult:
ws.artifacts.mkdir(parents=True, exist_ok=True)
- invalidate_stale_outputs(ws) # BEFORE the MISSING_ENTRY return, so it also clears
+ invalidate_stale_outputs(ws)
if (missing := missing_entry(ws, self.language)) is not None:
return missing
plan = graphics_plan(ws)
diff --git a/harness/codeverse3d/languages/opengl_python/wrappers/run_gl.py b/harness/codeverse3d/languages/opengl_python/wrappers/run_gl.py
index 445486c9..57dd230d 100644
--- a/harness/codeverse3d/languages/opengl_python/wrappers/run_gl.py
+++ b/harness/codeverse3d/languages/opengl_python/wrappers/run_gl.py
@@ -1,31 +1,7 @@
-"""Standalone moderngl runner (never imports codeverse3d).
-
-Usage: ``python run_gl.py --job job.json``
-
-``job.json``::
-
- {"mode": "shader" | "program",
- "out_dir": "...", # frames/ + result.json are written here
- "width": 1280, "height": 720,
- "times": [0.0, 1.0, 2.5], # judged frames
- "extra_times": [0.5, 1.5], # gif-only frames (optional)
- "fps": 30, # simulation step for feedback shaders
- "max_steps": 240,
- # shader mode: fully wrapped sources (header already prepended by the harness)
- "frag_src": "...", "buffer_a_src": "..." | null, "feedback": false,
- # program mode
- "program_path": "/abs/src/program.py", "program_cwd": "/abs/src"}
-
-Writes ``<out_dir>/frames/f<NN>_t<T>.png`` (8-bit RGB, top-down) and
-``<out_dir>/gl_result.json``::
-
- {"ok": bool, "stage": "context|compile|compile_buffer_a|setup|render|import",
- "error_type": "", "error_message": "", "traceback": "", "renderer": "...",
- "frames": [{"index", "time", "path", "judge": bool, "nan": int, "inf": int,
- "mean": float}], "duration_ms": int}
-
-Exit code 0 whenever gl_result.json was written (even for agent errors); 3 when the
-GL context could not be created (the harness retries with another driver env).
+"""Standalone moderngl runner (never imports codeverse3d): ``python run_gl.py --job job.json``.
+
+Writes ``<out_dir>/frames/f<NN>_t<T>.png`` and ``<out_dir>/gl_result.json``. Exit code 0 whenever
+gl_result.json was written (even for agent errors); 3 when the GL context could not be created.
"""
from __future__ import annotations
@@ -147,7 +123,7 @@ def _schedule(job: dict) -> list[tuple[float, bool]]:
def run_shader(ctx, job: dict, out_dir: Path) -> dict:
- import moderngl # noqa: F401 (already imported by caller; explicit for clarity)
+ import moderngl # noqa: F401
w, h = int(job["width"]), int(job["height"])
quad = ctx.buffer(np.array([-1, -1, 1, -1, -1, 1, 1, 1], dtype="f4").tobytes())
diff --git a/harness/codeverse3d/languages/scene_blender/__init__.py b/harness/codeverse3d/languages/scene_blender/__init__.py
index 204f08c2..239d342b 100644
--- a/harness/codeverse3d/languages/scene_blender/__init__.py
+++ b/harness/codeverse3d/languages/scene_blender/__init__.py
@@ -1,17 +1,9 @@
-"""scene_blender: multi-file bpy scenes on the ``scene`` track (DESIGN 2026-09-24 §3, phase 1).
+"""scene_blender: multi-file bpy scenes on the ``scene`` track.
The agent writes ``src/env.py`` / ``src/zones/<snake>.py`` / ``src/assets/<snake>.py`` in the Blender
-frame (``conventions.LANGUAGE_FRAME``: Z up, −Y front, metres); the harness assembles ``src/scene.py``
-(data only: which zones / assets / heroes, and the plan's cameras converted to that frame) and builds
-it in ONE Blender process (``languages/wrappers/run_bpy_scene.py``): every builder isolated, a zone
-that raises dropped with its ``file:line``. The geometry gates are the JS ones, run on the
-harness-written census GLB (``wrappers/_census_glb.py`` → ``runtime_js/lib/glb_scene.mjs``) — one
-implementation of census, placement and camera fitting for both scene languages. The plan stays in
-the GLB frame (D12): only the files the agent reads are converted.
-
-This module: lint (the object track's bpy traps + a scene policy table), layout, skeleton, assembler,
-and the ``SceneRuntime``. Rendering (``render_scene``) is DESIGN phase 2 and not here yet.
-"""
+frame; the harness assembles ``src/scene.py`` and builds it in one Blender process
+(``wrappers/run_bpy_scene.py``). Geometry gates run on the harness-written census GLB.
+This module holds lint, layout, skeleton, assembler and the ``SceneRuntime``."""
from __future__ import annotations
@@ -79,41 +71,35 @@ if TYPE_CHECKING:
LANGUAGE = Language.SCENE_BLENDER
log = logging.getLogger(__name__)
-ENTRY_REL = ENTRY_FILE[LANGUAGE] # "src/scene.py"
+ENTRY_REL = ENTRY_FILE[LANGUAGE]
GATE = "lint:scene_blender"
-#: the harness's frame clock: ``frame(t) = 1 + round(t * FPS)`` — the wrapper sets it, the render
-#: driver samples it (t = 0 → frame 1, t = 1.5 → frame 46)
+#: the harness frame clock: ``frame(t) = 1 + round(t * FPS)``
FPS = 30
TIMES: tuple[float, ...] = (0.0, 1.5)
def frame_of(t: float) -> int:
- """The Blender frame that shows animation time ``t`` (seconds)."""
return 1 + round(t * FPS)
# ===================================================================== layout
-#: what a whole-scene session edits: the entry and the environment (zones and assets have their own)
-SCENE_FILES: tuple[str, ...] = (ENTRY_REL, "src/env.py") # == (ENTRY_REL, ENV_FILE); ENV_FILE is defined with the starter tree
+#: what a whole-scene session edits
+SCENE_FILES: tuple[str, ...] = (ENTRY_REL, "src/env.py")
#: refine targets that are the environment's, whatever the plan calls its zones
ENV_WORDS = frozenset({"env", "environment", "lighting", "sky", "fog", "ground", "water", "light", "world", "sun"})
def zone_file(name: str) -> str:
- """``src/zones/<snake>.py`` — the module that builds zone ``name``."""
return f"src/zones/{to_snake(name)}.py"
def asset_file(asset: AssetPlan) -> str:
- """A procedural asset's module (``bpy``; a three.js-kind asset in a Blender plan is one too); a
- hero's compiled GLB."""
snake = to_snake(asset.name)
return f"public/assets/{snake}.glb" if asset.kind == "blender_glb" else f"src/assets/{snake}.py"
def scene_files_for(plan: Plan | None, target: str, *, alias: dict[str, str] | None = None) -> list[str]:
- """The files that own a scene refine target — the same routing as scene_threejs's
- (``languages.scene_threejs.scene_files_for``), over this language's file table."""
+ """The files that own a scene refine target (same routing as scene_threejs)."""
zone_plans = list(getattr(plan, "zones", None) or [])
zones = {to_snake(z.name) for z in zone_plans}
assets = {to_snake(a.name): a for a in (getattr(plan, "assets", None) or [])}
@@ -135,7 +121,6 @@ def scene_files_for(plan: Plan | None, target: str, *, alias: dict[str, str] | N
def module_files(ws: Workspace, sub: str) -> list[Path]:
- """``src/<sub>/*.py`` (sorted; ``_`` helper modules excluded)."""
d = ws.src / sub
return sorted(p for p in d.glob("*.py") if not p.name.startswith("_")) if d.is_dir() else []
@@ -149,10 +134,9 @@ def hero_files(ws: Workspace) -> list[Path]:
ALLOWED_IMPORTS = frozenset({
"bpy", "bmesh", "mathutils", "math", "random", "numpy", "itertools", "functools", "collections", "typing",
"dataclasses", "colorsys", "statistics", "operator", "enum", "copy", "__future__", "bpy_extras",
- "env", "zones", "assets", # the workspace's own packages (src/ is on sys.path)
+ "env", "zones", "assets",
})
-#: the object track's floor + everything that reads a clock or the file system: a scene is
-#: deterministic by construction and the harness owns every file
+#: the object track's floor + everything that reads a clock or the file system
FORBIDDEN_IMPORTS = frozenset(BASE_FORBIDDEN_IMPORTS | {"os", "sys", "pathlib", "time", "datetime", "tempfile",
"glob", "io", "shlex"})
#: numpy's random module is fine only through a seeded generator
@@ -180,8 +164,7 @@ CALL_POLICY: tuple[tuple[str, Severity, LintKind, str, str], ...] = (
("bpy.ops.view3d.", Severity.WARN, LintKind.API_TRAP, "view3d operators fail in background mode (no 3D viewport)", "delete it"),
("bpy.ops.screen.", Severity.WARN, LintKind.API_TRAP, "screen operators fail in background mode", "delete it"),
)
-#: scene settings the harness owns: an assigned dotted target that CONTAINS one of these (a
-#: material's ``cycles`` or a modifier's ``render_levels`` are the agent's, so the dots matter)
+#: scene settings the harness owns: an assigned dotted target that CONTAINS one of these
_STORE_OWNED_IN: tuple[tuple[str, str], ...] = (
("scene.render.", "render settings"), ("scene.cycles.", "Cycles settings"), ("scene.eevee.", "EEVEE settings"),
("scene.view_settings.", "colour management"), ("scene.display_settings.", "colour management"),
@@ -191,8 +174,7 @@ _STORE_OWNED_END: tuple[tuple[str, str], ...] = (
("scene.camera", "the active camera"), ("scene.frame_start", "the frame range"), ("scene.frame_end", "the frame range"),
("scene.frame_current", "the current frame"), ("scene.render", "render settings"),
)
-#: Blender's simple-expression driver subset (verified on 5.0.1: ``driver.is_simple_expression``);
-#: anything else runs Python, which a ``--factory-startup`` build silently evaluates to 0 (D10)
+#: Blender's simple-expression driver subset; anything else evaluates to 0 under ``--factory-startup``
SIMPLE_DRIVER_FUNCS = frozenset({
"radians", "degrees", "abs", "fabs", "floor", "ceil", "trunc", "round", "int", "sin", "cos", "tan", "asin",
"acos", "atan", "atan2", "exp", "log", "sqrt", "smoothstep", "fmod", "pow", "min", "max", "clamp", "lerp",
@@ -203,7 +185,6 @@ _SIMPLE_NODES = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Compare, ast.BoolOp
def simple_driver(expr: str) -> bool:
- """Is ``expr`` inside Blender's simple-expression subset (no Python needed to evaluate it)?"""
try:
tree = ast.parse(expr.strip(), mode="eval")
except (SyntaxError, ValueError, RecursionError, MemoryError):
@@ -220,8 +201,6 @@ def simple_driver(expr: str) -> bool:
class _SceneFacts(ast.NodeVisitor):
- """What the scene policy needs beyond the object-track collector: primitive operators inside
- loops, handler access, driver expressions, unseeded randomness, links into the scene root."""
def __init__(self) -> None:
self.loop_ops: list[tuple[str, int]] = []
@@ -238,7 +217,7 @@ class _SceneFacts(ast.NodeVisitor):
self.generic_visit(node)
self._loops -= 1
- visit_For = visit_While = visit_ListComp = visit_GeneratorExp = _loop # type: ignore[assignment]
+ visit_For = visit_While = visit_ListComp = visit_GeneratorExp = _loop
def visit_Attribute(self, node: ast.Attribute) -> None:
if dotted(node) == "bpy.app.handlers" or dotted(node).startswith("bpy.app.handlers."):
@@ -282,7 +261,6 @@ def _f(kind: LintKind, sev: Severity, msg: str, line: int | None, hint: str, tar
def _regate(findings: list[GateFinding], target: str) -> list[GateFinding]:
- """The object track's bpy traps, re-stamped as this gate's findings on ``target``."""
out = []
for f in findings:
line = f.data.get("line")
@@ -352,10 +330,9 @@ def _policy(c: BpyCollector, facts: _SceneFacts, *, target: str, role: str) -> l
def lint_scene_source(source: str, *, target: str, role: str) -> list[GateFinding]:
- """Lint one scene module; ``role`` is ``entry`` / ``env`` / ``zone`` / ``asset`` / ``helper``."""
tree, exc = safe_parse(source, target)
if tree is None:
- msg, hint, line = describe_parse_failure(exc) # type: ignore[arg-type]
+ msg, hint, line = describe_parse_failure(exc)
return [_f(LintKind.SYNTAX, Severity.ERROR, msg, line, hint, target)]
c = BpyCollector()
c.visit(tree)
@@ -396,7 +373,6 @@ def _role(ws: Workspace, p: Path) -> str:
def lint(ws: Workspace) -> GateReport:
- """Every ``src/**.py``; passed iff no ERROR."""
t0 = time.monotonic()
findings: list[GateFinding] = []
if not (ws.root / ENTRY_REL).is_file():
@@ -418,7 +394,7 @@ STARTER_DIR = Path(__file__).resolve().parent / "starter" / "src"
ENV_FILE = "src/env.py"
-#: the env check's data entry (deleted after use): no zone, asset or hero, so only build_env runs
+#: the env check's data entry (deleted after use): only build_env runs
ENV_CHECK_REL = "src/_c3d_env_check.py"
@@ -426,11 +402,7 @@ _TB_FRAME_RE = re.compile(r'File "(?P<file>[^"]+)", line (?P<line>\d+)')
def env_frame(traceback_text: str) -> str:
- """``src/env.py:N`` — the deepest frame of a Python traceback that is the env module's own, with its
- source line when the traceback quotes it — or ``""`` when no frame is. ``check_env`` leads with it
- when the raise surfaced inside a module the env called — a ``bpy_extras`` helper, bmesh's own python
- (D112 review: a recovered env was reported at the helper's line while its own bad call was
- ``env.py:287``, and the repair single-shot writes env.py)."""
+ """``src/env.py:N`` of the deepest traceback frame in the env module (with its source line), or ``""``."""
lines = traceback_text.splitlines()
found = ""
for i, text in enumerate(lines):
@@ -449,10 +421,8 @@ def _put(path: Path, text: str, written: list[Path]) -> None:
def write_example(ws: Workspace) -> list[Path]:
- """The complete plan-less starter scene (``starter/src/**/*.py``: entry, env, zones and assets)
- into ``ws.src`` — scene_threejs's ``write_example`` twin. Raises when the starter tree is
- missing: an rglob over an absent directory writes nothing and reports success, which is how a
- wheel without package data once shipped empty scenes (tests/core/test_portability.py)."""
+ """Write the plan-less starter scene (``starter/src/**/*.py``) into ``ws.src``; raises when the
+ starter tree is missing (an rglob over an absent directory would silently write nothing)."""
if not STARTER_DIR.is_dir():
raise FileNotFoundError(
f"scene_blender starter tree missing: {STARTER_DIR} — this install has no package data "
@@ -468,27 +438,16 @@ def write_example(ws: Workspace) -> list[Path]:
# ===================================================================== skeleton
def _v(v: Sequence[float], *, extents: bool = False) -> tuple[float, float, float]:
- """A plan (GLB-frame) vector in this language's frame (D12: prompts and skeleton convert)."""
- return tuple(round(c, 3) for c in to_authoring_frame(v, LANGUAGE.value, extents=extents)) # type: ignore[return-value]
+ return tuple(round(c, 3) for c in to_authoring_frame(v, LANGUAGE.value, extents=extents))
-#: the placeholder plate's side as a multiple of the plan span (the three.js skeleton's
-#: ``PLACEHOLDER_GROUND_SPANS``): past the 2 × span the ``fog_short`` gate measures once the author's
-#: atmosphere is in, so no authored camera reads a plate edge before the land is built. No
-#: minimum world size.
+#: the placeholder plate's side as a multiple of the plan span
PLACEHOLDER_GROUND_SPANS = 3.0
def _env_source(plan: ScenePlan) -> str:
- """``src/env.py`` as an interface stub: the plan's data (bounds, interior, glazed, the sun the
- plan states), the two exports the wrapper calls, and a PLACEHOLDER body that builds ONE thing —
- a level plate named Ground past the plan span — and no world, no lamp, no atmosphere: as
- written the stub FAILS the probe (no world / no atmosphere) and the frame gate (black frames)
- until the author writes the brief's. It used to be a finished landscape (a level pad of the
- bounds' half-span + 15 m, fbm hills beyond, a mossy ground, a fog box, a room shell with one
- ceiling light): 30 of 30 iteration-0 scenes kept its shape; then a passing placeholder (a
- neutral sun at 45° / 35°, a haze) that any brief could keep for the same reason (the
- de-templating of 2026-10-15)."""
+ """``src/env.py`` as an interface stub: the plan's data, the two exports the wrapper calls and a
+ placeholder ground plate. No world, lamp or atmosphere, so it fails the probe until the author writes them."""
from codeverse3d.languages.scene_threejs import sun_from_plan
c, e = _v(plan.bounds.center), _v(plan.bounds.extents, extents=True)
@@ -563,7 +522,6 @@ def build_env(ctx):
'''
-#: the asset placeholder's blockout (``str.format`` fields)
_ASSET_BODY = """import bmesh
import bpy
@@ -591,7 +549,7 @@ def build_{snake}(ctx, variant=0):
def _asset_source(a: AssetPlan) -> str:
snake, pascal = to_snake(a.name), to_pascal(a.name)
- w, h, d = (max(0.05, float(v)) for v in a.approx_size_m) # plan order: width, height, depth
+ w, h, d = (max(0.05, float(v)) for v in a.approx_size_m)
rgb, rough, metal = finish_for(a.description)
return f'''"""src/assets/{snake}.py — asset "{pascal}": {a.description.strip()}
@@ -607,9 +565,6 @@ CONTRACT: build_{snake}(ctx, variant=0) -> bpy.types.Collection — link every p
def _zone_source(z: ZonePlan, assets: dict[str, AssetPlan]) -> str:
- """The zone's interface and a TODO naming the plan's contents — no positions. The stub used to
- tile the contents on a quarter-extent grid inside the bbox and say "keep them inside the bbox":
- the seed of the blocks-in-a-rectangle look (the de-templating of 2026-10-15)."""
snake, pascal = to_snake(z.name), to_pascal(z.name)
c, e = _v(z.bbox.center), _v(z.bbox.extents, extents=True)
todo = []
@@ -652,7 +607,6 @@ def _cam(c: CameraPlan) -> str:
def render_scene_py(zones: Sequence[str], assets: Sequence[str], heroes: Sequence[str], cameras: Sequence[CameraPlan],
*, title: str = "", summary: str = "") -> str:
- """Deterministic ``src/scene.py``: data the wrapper reads, nothing to execute."""
def table(keys: Sequence[str]) -> str:
return "{\n" + "".join(f' "{k}": "{to_pascal(k)}",\n' for k in keys) + "}" if keys else "{}"
@@ -676,9 +630,7 @@ CAMERAS = [
def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:
- """Starter files for a scene plan (env, one module per zone and per procedural asset, the
- assembled entry); ``public/assets/`` for the heroes. Without a plan the complete example scene
- is the skeleton (``write_example``)."""
+ """Starter files for a scene plan; without a plan the complete example scene."""
if plan is None:
return write_example(ws)
if not isinstance(plan, ScenePlan):
@@ -700,14 +652,12 @@ def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:
# ===================================================================== build
WRAPPER = Path(__file__).resolve().parent.parent / "wrappers" / "run_bpy_scene.py"
-#: what a build (re)writes under ``artifacts/`` — wiped first, so nothing of a previous build reads as current
+#: what a build (re)writes under ``artifacts/``; wiped first
BUILD_OUTPUTS = ("build.json", "census.json", "census.glb", "scene.blend", "bpy_build.json", "bpy_census.json",
"scene_probe.json")
class WrapperRun(BaseModel):
- """One Blender process over the workspace: the wrapper's report as a BuildResult (typed
- timeout / crash / script error), its raw report and the bpy facts."""
result: BuildResult
report: dict[str, Any] = Field(default_factory=dict)
@@ -718,10 +668,7 @@ _SUN_RE = re.compile(r"^SUN_AZIMUTH_DEG\s*=\s*(-?\d+(?:\.\d+)?)", re.M)
def _fallback_camera(plan: ScenePlan | None, ws: Workspace | None = None) -> CameraPlan:
- """An overview when the plan names no camera (the schema requires one, so this is the plan-less
- path): in the PLAN frame (Y up), on the lit side — the env's ``SUN_AZIMUTH_DEG`` (compass 0 = +X,
- 90 = +Y in this language's Z-up frame, i.e. -Z in the plan's), the rig's 45° guess without one —
- at the bounds' span from their centre; derived, never a fixed corner."""
+ """An overview camera (PLAN frame) on the lit side at the bounds' span, for a plan with no camera."""
from codeverse3d.languages.scene_threejs import SUN_AZIMUTH_GUESS_DEG
azimuth = SUN_AZIMUTH_GUESS_DEG
@@ -751,7 +698,6 @@ class AssembleResult(BaseModel):
class SceneBlenderRuntime:
- """``SceneRuntime`` for ``Language.SCENE_BLENDER``."""
language = LANGUAGE
entry_globs: tuple[str, ...] = (ENTRY_REL, "src/zones/*.py", "src/assets/*.py", "src/env.py")
@@ -761,8 +707,6 @@ class SceneBlenderRuntime:
@property
def env_file(self) -> str:
- """The environment module (``src/env.py``): what an env session edits, the file the
- scene track hints for the whole-scene stage (``SceneRuntime.env_file``)."""
return ENV_FILE
def __init__(self, *, blender: str | None = None, settings: Settings | None = None) -> None:
@@ -783,16 +727,11 @@ class SceneBlenderRuntime:
return lint(ws)
def lib_interface(self, ws: Workspace) -> str:
- return "" # nothing harness-owned ships into a scene_blender workspace
+ return ""
def check_env(self, ws: Workspace) -> str:
- """``""`` when ``src/env.py`` lints clean, runs ``build_env`` in Blender with nothing beside
- it, and lights what it builds (``probes.unlit``); else the first failure, quoted. A Blender
- that cannot run is the harness's: ``""``. What the scene track asks of a recovered env (D112):
- in argon loop iteration 5, three recovered env.py modules failed at assembly (a ``curb_ mats``
- SyntaxError, an AttributeError, an unknown ``roughness=`` keyword) and two more that a scope
- revert kept from assembly were broken too (``noise_ centered = ...`` did not parse; a tuple
- rotation raised inside a helper the env called)."""
+ """``""`` when ``src/env.py`` lints clean, runs ``build_env`` alone and lights what it builds;
+ else the first failure, quoted. A Blender that cannot run gives ``""``."""
from codeverse3d.spatial.probes import unlit
env = ws.root / ENV_FILE
@@ -816,8 +755,7 @@ class SceneBlenderRuntime:
e = raised[0]
at = f"{e.get('error_file') or ENV_FILE}:{e.get('error_line')}" if e.get("error_line") else ENV_FILE
if (e.get("error_file") or ENV_FILE) != ENV_FILE and (own_at := env_frame(str(e.get("traceback") or ""))):
- # the raise surfaced inside a module the env called: the repair writes env.py, so the
- # env's own call line leads and the helper's line stays as where it surfaced
+ # the raise surfaced in a helper the env called: lead with the env's own call line
at = f"{own_at} (raised in {at})"
return f"{at}: build_env raised {e.get('error_type')}: {str(e.get('error_message'))[:600]}"
if not run.result.ok:
@@ -837,9 +775,7 @@ class SceneBlenderRuntime:
def run_wrapper(self, ws: Workspace, out_dir: Path, *, zones: dict[str, str] | None = None, blend: bool = True,
timeout_s: float | None = None, entry: str = ENTRY_REL) -> WrapperRun:
- """Build the workspace in Blender, outputs into ``out_dir`` (``bpy_build.json``,
- ``bpy_census.json``, ``census.glb``, ``scene.blend``); ``zones`` overrides the entry's ZONES;
- ``entry`` is another data entry under ``src/`` (the env check's, :func:`check_env`)."""
+ """Build the workspace in Blender into ``out_dir``; ``zones`` overrides ZONES, ``entry`` is another data entry."""
out_dir.mkdir(parents=True, exist_ok=True)
basis = ",".join(f"{v:g}" for row in glb_basis(LANGUAGE.value) for v in row)
cmd = [self.blender_binary(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",
@@ -866,8 +802,7 @@ class SceneBlenderRuntime:
def _measure(self, ws: Workspace, *, timeout_s: float | None, keep: tuple[str, ...] = ()
) -> tuple[WrapperRun, GateReport | None, dict[str, Any]]:
- """Wrapper + the census-GLB probe: (the Blender run, the ``scene_probe`` gate or ``None``
- when nothing was built, the merged census). Every output but ``keep`` is wiped first."""
+ """Wrapper + census-GLB probe: (Blender run, ``scene_probe`` gate or None, merged census)."""
from codeverse3d.spatial.probes import PROBE_GATE, run_probe
ws.artifacts.mkdir(parents=True, exist_ok=True)
@@ -880,14 +815,12 @@ class SceneBlenderRuntime:
gate = GateReport.of(PROBE_GATE, findings, duration_ms=probe.duration_ms)
ws.write_json(ws.artifacts / "gates" / "scene_probe.json", gate)
if census:
- census["language"] = LANGUAGE.value # the placement / frame hints speak bpy for it
+ census["language"] = LANGUAGE.value
ws.write_json(ws.artifacts / "census.json", census)
return run, gate, census
# ------------------------------------------------------------------ protocol
def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
- """Blender build + the census-GLB probe; ok iff the scene built and ``scene_probe`` passed
- (a dropped zone, an env that raised or a Python driver fail it, with their file:line)."""
t0 = time.time()
ws.artifacts.mkdir(parents=True, exist_ok=True)
if (missing := missing_entry(ws, self.language)) is not None:
@@ -917,8 +850,6 @@ class SceneBlenderRuntime:
return res
def probe(self, ws: Workspace, *, timeout_s: float | None = None) -> SceneProbeResult:
- """The build's own measurement (Blender run + census-GLB probe), without touching
- ``build.json``: an offline scene has no cheaper way to load."""
from codeverse3d.spatial.probes import PROBE_GATE, probe_result
if not (ws.root / ENTRY_REL).is_file():
@@ -937,8 +868,6 @@ class SceneBlenderRuntime:
return probe_result(gate, census)
def assemble(self, ws: Workspace, plan: ScenePlan) -> AssembleResult:
- """Build every zone module on disk once (isolated, no .blend) and write ``src/scene.py``
- with the zones that built and the plan's cameras — scene_threejs's assembler semantics."""
return assemble(self, ws, plan)
def render_scene(self, ws: Workspace, out_dir: Path, *, cameras: list[CameraPlan] | None = None, orbit: bool = True,
@@ -950,9 +879,7 @@ class SceneBlenderRuntime:
def stage_findings(report: dict[str, Any]) -> list[GateFinding]:
- """The wrapper's isolated-stage failures as ``scene_probe`` findings: a zone / asset / env that
- raised is an ERROR on its ``file:line`` (the zone is gone from the scene); a hero GLB that
- would not import or is missing is a WARN on the file."""
+ """The wrapper's isolated-stage failures as ``scene_probe`` findings (ERROR for a dropped zone / asset / env, WARN for a bad hero GLB)."""
from codeverse3d.spatial.probes import PROBE_GATE
out: list[GateFinding] = []
@@ -998,7 +925,7 @@ def assemble(runtime: SceneBlenderRuntime, ws: Workspace, plan: ScenePlan | None
census: dict[str, Any] = {}
out = ws.root / ENTRY_REL
if probe:
- # the probe run needs an entry that lists every asset and hero; its zones come from --zones
+ # the probe run's entry lists every asset and hero; zones come from --zones
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(render_scene_py([], assets, heroes, cams))
run = runtime.run_wrapper(ws, ws.artifacts / _ASSEMBLE_OUT, zones={z: to_pascal(z) for z in zones}, blend=False,
diff --git a/harness/codeverse3d/languages/scene_threejs/__init__.py b/harness/codeverse3d/languages/scene_threejs/__init__.py
index 5ce5aa4a..73260a67 100644
--- a/harness/codeverse3d/languages/scene_threejs/__init__.py
+++ b/harness/codeverse3d/languages/scene_threejs/__init__.py
@@ -47,7 +47,6 @@ _CREATE_SCENE_RE = re.compile(r"export\s+(?:async\s+)?function\s+createScene\b|e
_BUILD_RE = re.compile(r"export\s+(?:async\s+)?function\s+build\b|export\s+(?:const|let)\s+build\b|export\s*\{[^}]*\bbuild\b[^}]*\}")
_BUILD_ANY_RE = re.compile(r"export\s+(?:async\s+)?function\s+build[A-Za-z0-9_]*\b|export\s+(?:const|let)\s+build[A-Za-z0-9_]*\b")
-#: (regex, severity, message, hint, kind)
_PATTERNS: list[tuple[re.Pattern[str], Severity, str, str, LintKind]] = [
(re.compile(r"\brequestAnimationFrame\s*\("), Severity.ERROR, "requestAnimationFrame: the host drives update(t, dt)", "delete your render loop; animate inside update(t, dt)", LintKind.HARNESS_OWNED),
(re.compile(r"\bsetAnimationLoop\s*\("), Severity.ERROR, "renderer.setAnimationLoop: the host drives rendering", "remove it; animate inside update(t, dt)", LintKind.HARNESS_OWNED),
@@ -69,17 +68,8 @@ def _f(kind: LintKind, sev: Severity, msg: str, *, target: str, hint: str = "",
def _is_lib(path: Path, ws: Workspace) -> bool:
- """Is this one of the harness's own effect modules (``src/lib/*.js``)?
-
- They ship into every workspace (D51) and are verified by the harness's own
- suite — ``tests/scene_runtime/lib/`` — not by the workspace gate, whose job
- is to police the code the AGENT writes. Linting them as agent code was
- three hard ERRORs (a node-only font fallback importing
- ``node:module`` / ``node:fs/promises`` / ``node:url``, which the browser
- half never touches) plus twelve "large file" WARNs telling the agent to
- split files it does not own. Syntax is still checked below: a library file
- the agent broke must still fail loudly.
- """
+ """Is this one of the harness's own effect modules (``src/lib/*.js``)? They are verified by the
+ harness suite, not linted as agent code; syntax is still checked."""
return path.parent == ws.src / "lib"
@@ -89,11 +79,8 @@ def _syntax_finding(p: SyntaxProblem, rel: str) -> GateFinding:
def _check_imports(rel: str, text: str, ws: Workspace, path: Path, export_cache: ExportsCache) -> list[GateFinding]:
- """The import policy on one agent file: the specifier kinds, then — for a relative target
- that exists — every imported name against what the target exports. ``src/lib`` modules
- are never linted as agent code, but they ARE read here as targets (``export_cache`` holds
- each one's surface for the whole lint): a name the catalog does not list is a SyntaxError
- at module link, which drops the whole zone at assembly."""
+ """The import policy on one agent file: specifier kinds, then every name imported from a relative
+ target against what it exports (an unknown name is a SyntaxError at module link)."""
def make_finding(v: ImportVerdict, spec: str, line: int) -> GateFinding:
tgt = f"{rel}:{line}"
if v.kind is ImportKind.ESCAPES:
@@ -117,7 +104,6 @@ def _check_imports(rel: str, text: str, ws: Workspace, path: Path, export_cache:
def lint(ws: Workspace) -> GateReport:
- """Run all static checks; passed iff no ERROR findings."""
t0 = time.time()
findings: list[GateFinding] = []
files = js_sources(ws.src, dotfiles=True, mjs=True)
@@ -136,7 +122,7 @@ def lint(ws: Workspace) -> GateReport:
if _is_lib(path, ws):
continue
findings.extend(_check_imports(rel, text, ws, path, export_cache))
- code = strip_js(text, strings=False) # a comment quoting the contract is not a call
+ code = strip_js(text, strings=False)
for pat, sev, msg, hint, kind in _PATTERNS:
m = pat.search(code)
if m:
@@ -156,17 +142,12 @@ def lint(ws: Workspace) -> GateReport:
# ===================================================================== skeleton
STARTER_DIR = Path(__file__).resolve().parent / "starter" / "src"
-#: the harness-owned effect library (``src/lib/*.js``), shipped into EVERY workspace by both
-#: skeleton paths (a planned run once got the effects catalog in its prompt and no ``src/lib/``
-#: to import from — every ``from './lib/grass.js'`` a 2026-09-01 agent wrote was a build error).
-#: The example scene's own files (``zones/``, ``assets/``, ``shaders/``) ship ONLY without a plan:
-#: a planned workspace used to carry a pine tree, a windmill and a pond shader whatever the brief,
-#: and its stubs cited them as the pattern (the de-templating of 2026-10-15).
+#: the harness-owned effect library (``src/lib/*.js``), shipped into every workspace; the example
+#: scene's own files (``zones/``, ``assets/``, ``shaders/``) ship only without a plan
LIB_DIR = STARTER_DIR / "lib"
def lib_files() -> list[Path]:
- """The effect-library modules shipped into a workspace, sorted."""
return sorted(LIB_DIR.glob("*.js"))
@@ -182,13 +163,8 @@ def _write_lib(ws: Workspace, written: list[Path]) -> None:
def write_example(ws: Workspace) -> list[Path]:
- """Copy the full example scene into ws.src (overwrites).
-
- Raises when the starter tree is not there: rglob over a missing directory yields
- nothing, so this used to write ZERO files and report success — which is exactly what
- a non-editable (wheel) install produced before the starter tree was added to
- package-data, and it surfaced much later as an empty scene rather than a bad install.
- """
+ """Copy the full example scene into ws.src (overwrites); raises when the starter tree is missing
+ (an rglob over an absent directory would silently write nothing)."""
if not STARTER_DIR.is_dir():
raise FileNotFoundError(
f"scene_threejs starter tree missing: {STARTER_DIR} — this install has no package data "
@@ -202,23 +178,17 @@ def write_example(ws: Workspace) -> list[Path]:
return written
-#: the stub plate's side as a multiple of the plan span: its edge then sits 1.5 spans from the
-#: centre — past the 2 × span the ``fog_short`` gate measures once the author's fog is in — so no
-#: authored camera reads a plate edge before the land is built. Derived from the plan alone: no
-#: minimum world size.
+#: the stub plate's side as a multiple of the plan span
PLACEHOLDER_GROUND_SPANS = 3.0
_AZIMUTH_RE = re.compile(r"azimuth[^0-9\-]{0,12}(-?\d+(?:\.\d+)?)", re.I)
_ELEVATION_RE = re.compile(r"elevation[^0-9\-]{0,12}(-?\d+(?:\.\d+)?)", re.I)
-#: the overview rig's own guess when a scene states no sun azimuth (``sun_azimuth`` below)
+#: the overview rig's guess when a scene states no sun azimuth
SUN_AZIMUTH_GUESS_DEG = 45.0
def sun_from_plan(plan: ScenePlan) -> tuple[float | None, float | None]:
- """The sun azimuth and elevation (degrees) the plan's ``environment`` paragraph states
- ("sun azimuth 250° elevation 8°"), ``None`` for each it does not: the skeleton carries the
- PLAN's light into the env stub rather than a light of its own (the de-templating of
- 2026-10-15: a hardcoded azimuth 60 / elevation 38 / mood 'day' shipped in every env)."""
+ """The sun azimuth and elevation (degrees) the plan's ``environment`` paragraph states, ``None`` for each it does not."""
text = plan.environment
az = _AZIMUTH_RE.search(text)
el = _ELEVATION_RE.search(text)
@@ -278,13 +248,8 @@ export function buildEnv(ctx) {{
def _env_for_plan(plan: ScenePlan) -> str:
- """``src/env.js`` as an interface stub under the plan's data: the plate side from the span, the
- sun azimuth / elevation the plan states, the room box for an interior — and no light, sky or
- atmosphere. The starter's finished landscape (a level disc inside the bounds' radius with
- hills and a ridge beyond) was kept byte for byte by 29 of 30 iteration-0 scenes, and the
- passing placeholder that replaced it (a day sun rig at azimuth 60, a grey fog) built and
- passed for any brief, so it was kept too: a placeholder that passes is a template by another
- name (the de-templating of 2026-10-15)."""
+ """``src/env.js`` as an interface stub under the plan's data: plate side, stated sun angles, the
+ room box for an interior; no light, sky or atmosphere."""
ex = plan.bounds.extents
span = max(ex[0], ex[2], 1.0)
az, el = sun_from_plan(plan)
@@ -312,29 +277,23 @@ def _env_for_plan(plan: ScenePlan) -> str:
# ===================================================================== layout
-#: what a whole-scene session edits: the entry and the environment (every zone and asset module
-#: has its own session and its own file below)
+#: what a whole-scene session edits: the entry and the environment
SCENE_FILES: tuple[str, ...] = ("src/scene.js", "src/env.js")
#: refine targets that are the environment's, whatever the plan calls its zones
ENV_WORDS = frozenset({"env", "environment", "lighting", "sky", "fog", "ground", "water", "light"})
def zone_file(name: str) -> str:
- """``src/zones/<snake>.js`` — the module that builds zone ``name``."""
return f"src/zones/{to_snake(name)}.js"
def asset_file(asset: AssetPlan) -> str:
- """A three.js asset's factory module; a Blender hero's compiled GLB (built in its own sub-workspace)."""
snake = to_snake(asset.name)
return f"src/assets/{snake}.js" if asset.kind == "threejs" else f"public/assets/{snake}.glb"
def scene_files_for(plan: Plan | None, target: str, *, alias: dict[str, str] | None = None) -> list[str]:
- """The files that own a scene refine target. A three.js asset is fixed in its factory — a merged
- asset's (``alias``: the dedupe note) in its survivor's, its own file being only the variant shim; a
- hero ships as a GLB, so it is fixed where it is placed: the zones that list it. Cameras belong to
- ``scene.js``, env words to ``env.js``; "Zone/Asset" (the placement gate) to the zone's file."""
+ """The files that own a scene refine target: an aliased asset in its survivor, a hero where it is placed, cameras in ``scene.js``, env words in ``env.js``."""
zone_plans = list(getattr(plan, "zones", None) or [])
zones = {to_snake(z.name) for z in zone_plans}
assets = {to_snake(a.name): a for a in (getattr(plan, "assets", None) or [])}
@@ -381,9 +340,6 @@ export function build{pascal}(T = THREE) {{
def _zone_stub(z: ZonePlan, assets: dict[str, AssetPlan]) -> str:
- """The zone's interface and a TODO naming the plan's contents — no positions. The stub used
- to tile the contents on a quarter-extent grid inside the bbox and say "keep everything inside
- the plan bbox": the seed of the blocks-in-a-rectangle look (the de-templating of 2026-10-15)."""
snake, pascal = to_snake(z.name), to_pascal(z.name)
c, e = z.bbox.center, z.bbox.extents
imports, todo = [], []
@@ -423,10 +379,7 @@ export function build(ctx) {{
def _scene_for_plan(plan: ScenePlan) -> str:
- """The skeleton's entry point IS the assembled shape (``render_scene_js`` over the
- plan's zones, cameras and GLB assets) under the starter's contract header: the
- assemble stage overwrites this file with that very emitter, so the env / zone
- sessions author against the ``createScene`` they will actually ship with."""
+ """The skeleton's entry is the assembled shape under the starter's contract header."""
header = (STARTER_DIR / "scene.js").read_text().split("import * as THREE")[0]
glbs = [to_snake(a.name) for a in plan.assets if a.kind == "blender_glb"]
body = render_scene_js([to_snake(z.name) for z in plan.zones], list(plan.cameras[:6]), glbs, env_ok=True)
@@ -435,7 +388,6 @@ def _scene_for_plan(plan: ScenePlan) -> str:
def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:
- """Write starter files into ``ws.src``; returns the written paths."""
if plan is None or not isinstance(plan, ScenePlan):
return write_example(ws)
written: list[Path] = []
@@ -469,8 +421,6 @@ class ZoneProbe(BaseModel):
class ZoneProbeReport(BaseModel):
- """``probe_zone_modules`` outcome; ``camera_specs`` carries the driver-fitted cameras
- (``{azimuth, overview, zones:[{group, position, lookAt, fov}]}``)."""
probes: dict[str, ZoneProbe] = Field(default_factory=dict)
census: dict[str, Any] = Field(default_factory=dict)
@@ -507,25 +457,11 @@ def sun_azimuth(ws: Workspace, default: float = 45.0) -> float:
return default
-# --------------------------------------------------------------------------- probing
-#: How a Blender-built asset is preloaded in EVERY assembled entry point. One
-#: spelling, because there are three of them (the assembled `src/scene.js`, the
-#: assembler's probe module, and `render_scene_js`) and they had drifted into three.
-#:
-#: The loaded root is NAMED after its asset. A glTF root arrives called whatever the
-#: exporter wrote — Blender writes "Scene" — and every check that reads the scene
-#: graph by name then cannot see it. Measured on bench/out/scene_baseline
-#: (2026-09-05): rooftop_garden's `lounge_sofa.glb` loaded fine (`glb_assets:
-#: meshes_in_scene 1, in_scene true`) and `scene_placement` still reported
-#: "zone PergolaLounge is missing planned contents: LoungeSofa", because the object
-#: in the zone was called "Scene". `to_pascal` on the file key rebuilds exactly the
-#: plan's asset name, which is where the key came from.
+#: How a Blender-built asset is preloaded in every assembled entry point. The loaded root is
+#: NAMED after its asset (``to_pascal`` of the file key): a glTF root arrives as "Scene", which
+#: name-based checks cannot see.
def _glb_preload_js(glbs: list[str], *, target: str, on_error: str, indent: str = " ") -> str:
- """The `assetFiles` literal + preload loop, or "" when the plan has no GLB asset.
-
- ``target`` is the assets object to fill (``assets`` / ``ctx.assets``); ``on_error``
- is the JS statement run in the catch, with ``e`` and ``a`` (the asset entry) bound.
- """
+ """The `assetFiles` literal + preload loop, or "" when the plan has no GLB asset; ``on_error`` is the JS catch statement."""
if not glbs:
return ""
files = ", ".join(f"{g}: {{ name: '{to_pascal(g)}', url: '/assets/{g}.glb' }}" for g in glbs)
@@ -537,8 +473,7 @@ def _glb_preload_js(glbs: list[str], *, target: str, on_error: str, indent: str
" const root = gltf.scene;",
" 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)
+ # GLTFLoader leaves castShadow / receiveShadow false; set them like procedural assets
" root.traverse((o) => { if (o.isMesh) o.castShadow = o.receiveShadow = true; });",
f" {target}[key] = root;",
" } catch (e) { " + on_error + " }",
@@ -600,13 +535,6 @@ export async function createScene({{ renderer, loaders }}) {{
def probe_zone_modules(ws: Workspace, *, timeout_s: float = 90.0, sun_azimuth_deg: float | None = None) -> ZoneProbeReport:
- """Probe env + every zone module independently in the browser host.
-
- Returns a :class:`ZoneProbeReport` (zone probes by snake name, census, other
- console errors). When
- ``sun_azimuth_deg`` is given the driver also fits overview + per-group
- cameras from the measured bboxes (``camera_specs``).
- """
from codeverse3d.spatial.render_scene import run_scene_script
zones = zone_files(ws)
@@ -615,10 +543,9 @@ def probe_zone_modules(ws: Workspace, *, timeout_s: float = 90.0, sun_azimuth_de
from codeverse3d.spatial.render_scene import _bounds_json, plan_bounds, probe_env_args
args = ["--ws", str(ws.root), "--scene", PROBE_REL, "--timeout-ms", str(int(timeout_s * 1000))]
- args += probe_env_args() # the zone probe sees the same settle/repair/exposure world as the renders
+ args += probe_env_args()
if sun_azimuth_deg is not None:
args += ["--sun-azimuth", str(sun_azimuth_deg)]
- # the overview is framed like the render rig's: inside the plan's bounds
if (bounds := plan_bounds(ws)) is not None:
args += ["--bounds", _bounds_json(bounds)]
try:
@@ -654,14 +581,12 @@ def probe_zone_modules(ws: Workspace, *, timeout_s: float = 90.0, sun_azimuth_de
# --------------------------------------------------------------------------- the env module alone
-#: the env check's probe entry (deleted after use; the leading ``_`` keeps it out of every listing)
+#: the env check's probe entry (deleted after use)
ENV_PROBE_REL = "src/_c3v_env_probe.js"
def lib_interface(ws: Workspace) -> str:
- """The workspace's ``src/lib/`` surface, one line per module: every exported name, a function
- with its parameter list as written (:func:`~codeverse3d.languages._js_lint.export_signatures`).
- Facts read off the files — what a single-shot writer, which cannot open them, may import (D112)."""
+ """The workspace's ``src/lib/`` surface, one line per module: exported names and parameter lists."""
from codeverse3d.languages._js_lint import export_signatures
lib = ws.src / "lib"
@@ -671,11 +596,8 @@ def lib_interface(ws: Workspace) -> str:
def check_env(ws: Workspace, *, timeout_s: float = 90.0) -> str:
- """``""`` when ``src/env.js`` passes the lint (its own findings), loads and runs ``buildEnv`` in the
- browser host with no zone beside it, and lights what it builds (``probes.unlit``); else the first
- failure, quoted. A probe that cannot run is the harness's, not the module's: ``""`` (logged).
- What the scene track asks of a recovered env before it counts as written (D112): 5 of 21
- recovered env modules of argon loop iteration 5 failed only later, at assembly."""
+ """``""`` when ``src/env.js`` lints clean, runs ``buildEnv`` alone in the browser host and lights what
+ it builds; else the first failure, quoted. A probe that cannot run gives ``""`` (logged)."""
import logging
from codeverse3d.spatial.probes import unlit
@@ -700,7 +622,7 @@ def check_env(ws: Workspace, *, timeout_s: float = 90.0) -> str:
finally:
probe_path.unlink(missing_ok=True)
s = res.summary
- # nothing but the env module (and the library it imports) runs in this probe: every console error is its
+ # only the env module and its library run here: every console error is the env's
errors = [e for e in s.get("console_errors", []) if not e.startswith("boot[")]
boot = s.get("boot") or {}
if not boot.get("ok"):
@@ -713,9 +635,6 @@ def check_env(ws: Workspace, *, timeout_s: float = 90.0) -> str:
# --------------------------------------------------------------------------- cameras
def fallback_camera(plan: ScenePlan | None, azimuth_deg: float = SUN_AZIMUTH_GUESS_DEG) -> CameraPlan:
- """An overview when nothing was measurable: on the lit side (``azimuth_deg`` is the scene's
- ``SUN_AZIMUTH_DEG``, 0 = +X, 90 = +Z), at the bounds' span from their centre, looking at it —
- derived, not the fixed +X+Z corner shot every example once showed."""
if plan is None:
c, r = (0.0, 0.0, 0.0), 30.0
else:
@@ -733,10 +652,8 @@ def _plan_from_spec(spec: dict[str, Any], *, name: str, purpose: str) -> CameraP
def cameras_from_specs(specs: dict[str, Any], probes: dict[str, ZoneProbe], *, max_cameras: int = 6,
plan: ScenePlan | None = None, azimuth_deg: float = SUN_AZIMUTH_GUESS_DEG) -> list[CameraPlan]:
- """Convert driver-fitted camera specs (``probe_scene.mjs --sun-azimuth``;
- math owned by ``runtime_js/lib/orbit.mjs``) into CameraPlans: overview
- first, then per-zone cameras, largest footprints first. Falls back to a
- fixed overview when nothing was measurable."""
+ """Convert driver-fitted camera specs into CameraPlans (overview first, then zones by footprint);
+ falls back to a fixed overview when nothing was measurable."""
healthy = [p for p in probes.values() if p.ok and p.bbox]
overview = (specs or {}).get("overview")
if not healthy or not overview:
@@ -760,11 +677,9 @@ def _cam_literal(c: CameraPlan) -> str:
def render_scene_js(zones: list[str], cameras: list[CameraPlan], glbs: list[str], *, env_ok: bool = True) -> str:
- """Deterministic src/scene.js source for the given healthy zone snake names."""
imports = "\n".join(f"import {{ build as build{to_pascal(z)} }} from './zones/{z}.js';" for z in zones)
calls = "\n".join(f" await addZone(build{to_pascal(z)}, '{to_pascal(z)}');" for z in zones)
env_import = "import { buildEnv, heightAt } from './env.js';" if env_ok else ""
- # buildEnv/build may be async (lint + the assembler probe both accept it): await consistently
env_build = " const env = (await buildEnv(ctx)) || {};\n ctx.env = env;" if env_ok else " const env = {};"
height = "heightAt" if env_ok else "() => 0"
glb_preload = _glb_preload_js(
@@ -822,7 +737,6 @@ export async function createScene({{ renderer, loaders }}) {{
def assemble(ws: Workspace, plan: ScenePlan | None = None, *, cameras: str = "derive", probe: bool = True,
timeout_s: float = 90.0) -> AssembleResult:
- """Probe zones, derive cameras, write ``src/scene.js``. ``cameras='plan'`` keeps the plan's."""
warnings: list[str] = []
zones = zone_files(ws)
if not zones:
@@ -868,7 +782,6 @@ def assemble(ws: Workspace, plan: ScenePlan | None = None, *, cameras: str = "de
class SceneThreeJsRuntime:
language = Language.SCENE_THREEJS
entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.SCENE_THREEJS], "src/zones/*.js", "src/assets/*.js", "src/env.js", "src/shaders/*.js")
- #: ``SceneRuntime.env_file``: the module the env stage writes (``SCENE_FILES[1]``)
env_file: str = SCENE_FILES[1]
zone_file = staticmethod(zone_file)
@@ -899,7 +812,7 @@ class SceneThreeJsRuntime:
return write_skeleton(ws, plan)
def lint(self, ws: Workspace) -> GateReport:
- return lint(ws) # the module-level gates function (class ns is not in method scope)
+ return lint(ws)
def lib_interface(self, ws: Workspace) -> str:
return lib_interface(ws)
@@ -908,15 +821,8 @@ class SceneThreeJsRuntime:
return check_env(ws)
def render_asset(self, ws: Workspace, name: str, out_dir: Path, *, timeout_s: float = 180.0) -> RenderSet:
- """Quick sheet of ONE procedural asset module, on the rig a Blender hero's GLB gets.
-
- ``src/assets/<snake>.js`` is exported to a GLB by the object track's own build
- (``ThreeJsRuntime.build`` on a scratch workspace whose two-line entry calls
- ``build<Pascal>``: the same memory cap, heap flag and typed errors) and rendered with
- ``spatial.render.render_glb``. This is the hook ``scene_assets`` looks
- for before judging a threejs asset; nothing defined it until 2026-09-07, so no
- procedural asset was ever judged (0 of 860 recorded) while every hero was.
- """
+ """Quick sheet of ONE procedural asset module: exported to a GLB by the object track's build
+ on a scratch workspace and rendered like a hero GLB."""
from codeverse3d.languages.threejs import ThreeJsRuntime
from codeverse3d.spatial.render import RenderError, render_glb
@@ -933,15 +839,10 @@ class SceneThreeJsRuntime:
return render_glb(res.glb_path, out_dir, views=list(OBJECT_VIEWS_QUICK), width=512, height=512, sheet=True)
def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
- """Probe + shader preflight (one browser boot); ok iff the module loads
- and no shader errors. The two GateReports are the build's own
- (``BuildResult.gates``, which the round appends to its gates) and land
- under ``artifacts/gates/`` as well."""
+ """Probe + shader preflight (one browser boot); ok iff the module loads and no shader errors."""
t0 = time.time()
ws.artifacts.mkdir(parents=True, exist_ok=True)
- # a probe/driver crash must not leave the previous round's census or the root
- # driver outputs (scene_probe.json / shader_preflight.json) looking current;
- # census.json is only rewritten `if census:` below, so it MUST be wiped here
+ # wipe stale driver outputs so a crashed probe never looks current (census.json is only rewritten `if census:`)
ws.stage_artifacts("census.json", "scene_probe.json", "shader_preflight.json", "build.json").invalidate()
if (missing := missing_entry(ws, self.language)) is not None:
return missing
@@ -972,9 +873,7 @@ class SceneThreeJsRuntime:
duration_ms=int((time.time() - t0) * 1000),
census=census,
gates=[probe, shaders],
- # a driver that could not run is not a defect in the scene; `probes.probe_report`
- # and `run_probe` already mark it, and `build_with_repair` reads this
- # so the round does not spend its repair budget rewriting working code
+ # a driver that could not run is not a scene defect; the round must not spend repair budget on it
harness_failure=bool(first is not None and first.data.get("harness_failure")),
)
ws.write_json(ws.artifacts / "build.json", res)
diff --git a/harness/codeverse3d/languages/threejs/__init__.py b/harness/codeverse3d/languages/threejs/__init__.py
index dc3a7a3c..c24301f6 100644
--- a/harness/codeverse3d/languages/threejs/__init__.py
+++ b/harness/codeverse3d/languages/threejs/__init__.py
@@ -1,5 +1,4 @@
-"""three.js (static object) language runtime: raw ESM authored by the agent,
-GLB export + census by ``runtime_js/export_glb.mjs``."""
+"""three.js (static object) language runtime: raw ESM, GLB export + census by ``runtime_js/export_glb.mjs``."""
from __future__ import annotations
@@ -117,8 +116,7 @@ def _f(kind: LintKind, sev: Severity, target: str, message: str, hint: str) -> G
def _lint_imports(ws: Workspace, path: Path, src: str, findings: list[GateFinding], export_cache: ExportsCache) -> set[Path]:
- """Validate import specifiers and, on a relative target, the imported names (a name the
- part does not export is a SyntaxError at link); return the set of resolved relative targets."""
+ """Validate import specifiers and imported names; return the set of resolved relative targets."""
rel = ws_rel(ws, path)
def make_finding(v: ImportVerdict, spec: str, line: int) -> GateFinding:
@@ -264,11 +262,7 @@ def render_object(plan: StaticPlan) -> str:
def write_skeleton(ws: Workspace, plan: Plan, *, overwrite: bool = False) -> list[Path]:
- """Write ``src/package.json``, ``src/object.js`` and ``src/parts/*.js``; return written paths.
-
- Existing files are kept unless ``overwrite`` (so re-running on a refined
- workspace never clobbers agent work).
- """
+ """Write ``src/package.json``, ``src/object.js`` and ``src/parts/*.js``; existing files are kept unless ``overwrite``."""
if not isinstance(plan, StaticPlan):
raise TypeError(f"threejs skeleton needs a StaticPlan, got {type(plan).__name__}")
written: list[Path] = []
@@ -313,17 +307,13 @@ class ThreeJsRuntime(RuntimeLayout):
def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
"""Run ``runtime_js/export_glb.mjs`` on ``src/object.js`` → ``artifacts/object.glb``.
- Never raises for agent-code failures: they come back as ``ok=False`` with
- ``error_type/message/file/line`` and the stdout/stderr tails. Harness
- misconfiguration (missing node, missing script) still raises.
- """
+ Agent-code failures return ``ok=False``; harness misconfiguration raises."""
settings = get_settings()
timeout_s = timeout_s or settings.limits.build_timeout_s
ws.artifacts.mkdir(parents=True, exist_ok=True)
glb = ws.artifacts / GLB_NAME
census = ws.artifacts / CENSUS_NAME
- # build.json is in the wipe too: the node-missing raise below returns before
- # _write_build_json, and a stale ok:true build.json must not survive it
+ # build.json is wiped too: the node-missing raise below skips _write_build_json
ws.stage_artifacts(GLB_NAME, CENSUS_NAME, BUILD_JSON, "export_error.json").invalidate()
if (missing := missing_entry(ws, self.language)) is not None:
return missing
@@ -386,12 +376,7 @@ class ThreeJsRuntime(RuntimeLayout):
@staticmethod
def _part_file(ws: Workspace | None, part: object) -> str:
- """``src/parts/<snake>.js`` for the plan part named in a validation error (when that file exists).
-
- Contract errors raised by the exporter (NaN geometry, empty bbox) carry no src
- frame — the throw site is export_glb.mjs — but name the offending part; the
- naming convention (``conventions.to_snake``) turns that into the file to repair.
- """
+ """``src/parts/<snake>.js`` for the plan part named in a validation error (when that file exists)."""
if ws is None or not isinstance(part, str) or not part.strip():
return ""
rel = part_file_rel(part)
diff --git a/harness/codeverse3d/languages/urdf/__init__.py b/harness/codeverse3d/languages/urdf/__init__.py
index f6e20f57..cdcb2844 100644
--- a/harness/codeverse3d/languages/urdf/__init__.py
+++ b/harness/codeverse3d/languages/urdf/__init__.py
@@ -45,17 +45,12 @@ from codeverse3d.spatial.joints_sweep import sweep_collisions, sweep_findings
from codeverse3d.workspace import ArtifactStage, Workspace
# ===================================================================== consistency
-#: this gate's own name — a bare ``GATE`` here was shadowed by the lint section's
-#: ``GATE = "lint:urdf"`` 59 lines below when the package became one module (2026-08-28),
-#: so every FK finding went out mislabelled until 2026-08-28.
+#: this gate's own name
FK_GATE = "fk_consistency"
def check_fk_consistency(robot: Robot, census_links: dict[str, dict[str, Any]], *, tol_m: float = 0.001) -> list[GateFinding]:
- """Compare every link's FK-posed mesh bbox at rest with the authored census bbox.
-
- Returns one ERROR finding per inconsistent link carrying the corrected visual
- origin (``fix_hint`` is copy-pasteable XML) and an INFO summary otherwise."""
+ """Compare every link's FK-posed mesh bbox at rest with the authored census bbox; ERROR per inconsistent link with a corrected origin."""
T = fk(robot, {})
out: list[GateFinding] = []
for name, link in robot.links.items():
@@ -102,10 +97,7 @@ URDF_REL = "src/robot.urdf"
MODEL_REL = ENTRY_FILE[Language.URDF_BLENDER]
_STATE_WORDS = ("open", "closed", "opened", "extended", "retracted", "raised", "lowered", "folded", "unfolded")
-#: model.py runs in the SAME Blender python as the blender language's model.py, so it is linted
-#: by that language's rules (``lint_blender_source``: imports, harness-owned and removed bpy APIs,
-#: file IO); these are the few a link script adds on top. Until 2026-09-24 this module kept its
-#: own looser lists: one source gave 7 ERRORs as blender and 2 WARNs as urdf.
+#: model.py runs in Blender's python, so it is linted by the blender language's rules; these are the extras a link script adds.
LINK_SCRIPT_CALLS: dict[str, tuple[Severity, str, LintKind]] = {
"exit": (Severity.ERROR, "exits Blender before the links are exported", LintKind.SANDBOX),
"quit": (Severity.ERROR, "exits Blender before the links are exported", LintKind.SANDBOX),
@@ -127,7 +119,6 @@ def _floats(text: str | None) -> list[float] | None:
# ------------------------------------------------------------------ URDF
def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFinding], list[str]]:
- """Lint URDF source. Returns (findings, link_names)."""
out: list[GateFinding] = []
try:
root = ET.fromstring(text)
@@ -173,7 +164,6 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
_lint_mimics(joints, out)
- # tree structure
children = set(parent_of)
roots = [n for n in link_names if n not in children]
if len(roots) != 1:
@@ -192,13 +182,8 @@ def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFindin
def _lint_mimics(joints: list[ET.Element], out: list[GateFinding]) -> None:
- """``<mimic>`` couplings, over the whole file: a declaration may name a joint that is
- written later, and a cycle is only visible on the graph. The RULES are
- ``contracts.common.mimic_issues`` — shared with the plan validator and the URDF
- loader, which rejected different multipliers from this lint until 2026-09-03."""
- # EVERY named joint becomes a spec, coupled or not: an uncoupled joint is what the
- # coupled ones are allowed to name, and mimic_issues resolves targets against the set
- # it is given.
+ """``<mimic>`` couplings over the whole file; the rules are ``contracts.common.mimic_issues``."""
+ # every named joint becomes a spec; mimic_issues resolves targets against that set
specs: list[MimicSpec] = []
for el in joints:
jname = el.get("name", "")
@@ -222,10 +207,7 @@ def _lint_mimics(joints: list[ET.Element], out: list[GateFinding]) -> None:
specs.append(MimicSpec(key=jname, name=jname, movable=movable, target=src or None,
multiplier=mult, offset=off, lower=lo, upper=hi))
known = sorted({el.get("name", "") for el in joints if el.get("name")})
- # NOT checked here: whether a follower of `<driver>_1` should also follow `_2..n`.
- # Only the skeleton knows which `_N` names are instances of one plan joint (an agent
- # names joints `hinge_1` / `hinge_2` by hand all the time), so that note is written
- # where the instancing happens — compute_urdf_frames — as a comment in the file.
+ # not checked here: whether a follower of `<driver>_1` also follows `_2..n` (only the skeleton knows the instances)
for i in mimic_issues(specs):
j, t = i.joint, i.target
if i.kind == "immobile":
@@ -374,8 +356,7 @@ def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: di
# ------------------------------------------------------------------ model.py
def lint_model_text(text: str, link_names: list[str], *, label: str = MODEL_REL) -> list[GateFinding]:
- """model.py: the blender language's lint + LINK_SCRIPT_CALLS, ``while True`` and every URDF
- link name appearing as a string literal (the wrapper looks objects up by exact name)."""
+ """model.py: the blender language's lint + LINK_SCRIPT_CALLS, ``while True`` and URDF link names as string literals."""
out = [f.model_copy(update={"gate": GATE})
for f in lint_blender_source(text, target=label, expect_names=False).findings]
tree, _ = safe_parse(text, label)
@@ -425,7 +406,6 @@ DEFAULT_VELOCITY = 1.0
@dataclass(frozen=True)
class LinkFrame:
- """World placement of one link frame at rest + its plan bbox."""
name: str
frame_xyz: tuple[float, float, float]
@@ -483,7 +463,6 @@ def _expand_parts(plan: ArticulatedPlan) -> list[tuple[str, PartPlan, tuple[floa
def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
- """Pure function: plan → link frames + joint rows in the enforced convention."""
parts = _expand_parts(plan)
base_names = {to_snake(p.name) for p in plan.parts}
root = to_snake(plan.root_link)
@@ -502,8 +481,7 @@ def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
lower, upper = j.lower - j.rest, j.upper - j.rest
mim = None
if j.mimic is not None:
- # every copy of an instanced follower follows the SAME driver; the driver's own
- # name is resolved after emission, when the instance suffixes are known
+ # every copy of an instanced follower follows the same driver; resolved after emission
mim = (to_snake(j.mimic.joint), float(j.mimic.multiplier), float(j.mimic.offset))
joints.append(JointRow(name=to_snake(j.name) + suffix, type=j.type, parent=parent, child=child,
origin_xyz=(0.0, 0.0, 0.0), axis=tuple(float(v) for v in j.axis), lower=lower, upper=upper,
@@ -518,10 +496,7 @@ def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
for k, c in enumerate(children):
add_joint(j, c, parent, "" if len(children) == 1 else f"_{k + 1}")
- # A driver whose child is instanced exists only as <name>_1..._n, so the plan's name
- # names no joint in the file: follow the first instance, the rule an instanced PARENT
- # link already uses above. The plan validator guarantees the target is a plan joint,
- # so anything unresolved here is a bug in this function, not in the plan.
+ # A driver whose child is instanced exists only as <name>_1..._n: follow the first instance.
emitted = {jr.name for jr in joints}
for i, jr in enumerate(joints):
if jr.mimic is None or jr.mimic[0] in emitted:
@@ -529,20 +504,17 @@ def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
target, mult, off = jr.mimic
if f"{target}_1" not in emitted:
raise ValueError(f"joint {jr.name}: mimic target {target!r} was not emitted; joints are {sorted(emitted)}")
- # the other instances stay independent inputs the sweep drives on their own; say so
- # in the file, here where the instancing is known, rather than guessing from names
+ # the other instances stay independent inputs; say so in the file
others = sorted(n for n in emitted if n.startswith(f"{target}_") and n != f"{target}_1")
joints[i] = replace(jr, mimic=(f"{target}_1", mult, off),
mimic_note=f"follows {target}_1 only; {', '.join(others)} stay independent inputs "
"(add a <mimic> per instance if they move together)")
- # link frames: root at origin, others at their pivot
for name, p, center in parts:
frame = (0.0, 0.0, 0.0) if name == root else pivot_of.get(name, (0.0, 0.0, 0.0))
pj = next((jr.name for jr in joints if jr.child == name), None)
links[name] = LinkFrame(name=name, frame_xyz=frame, bbox_center=center,
bbox_extents=tuple(float(v) for v in p.bbox.extents), parent_joint=pj)
- # joint origins relative to the parent link frame
fixed: list[JointRow] = []
for jr in joints:
pf = links[jr.parent].frame_xyz
@@ -556,7 +528,6 @@ def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
# ------------------------------------------------------------------ text renderers
def _limit_note(jr: JointRow) -> str:
- """Comment explaining a rest-shifted limit (empty when the plan's rest is 0)."""
if jr.lower is None or jr.upper is None or abs(jr.rest) < 1e-12:
return ""
return (f" <!-- plan lower={_fmt(jr.lower + jr.rest)} upper={_fmt(jr.upper + jr.rest)} rest={_fmt(jr.rest)}: "
@@ -639,7 +610,6 @@ def box(name, center, size):
def write_skeleton(ws: Workspace, plan: ArticulatedPlan) -> list[Path]:
- """Write src/model.py + src/robot.urdf; returns the written paths."""
frames = compute_urdf_frames(plan)
ws.src.mkdir(parents=True, exist_ok=True)
model = ws.src / "model.py"
@@ -654,8 +624,7 @@ WRAPPER = Path(__file__).resolve().parent.parent / "wrappers" / "run_bpy_links.p
REST_PENETRATION_MAX_M = 0.005
FK_TOL_M = 0.001
-#: every canonical artifact this build owns — staged together so a failed build
-#: can never leave a previous round's output looking current
+#: every canonical artifact this build owns, staged together
STAGED_OUTPUTS = ("build.json", "census.json", "meshes", "robot.urdf", "object.glb")
@@ -676,13 +645,8 @@ class UrdfBlenderRuntime(RuntimeLayout):
# ------------------------------------------------------------ build
def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
- """All five canonical outputs go through one :class:`ArtifactStage`: entering
- it invalidates them BEFORE any early return can leak a previous round's
- files, everything is written to staging, and only an ``ok=True`` build
- promotes the full set. Every exit path publishes the FINAL BuildResult as
- ``artifacts/build.json`` — the wrapper's own build.json used to stay on disk
- saying ``ok: true`` while a post-wrapper check (UrdfError / FkInconsistent /
- RestPenetration) failed the build."""
+ """All canonical outputs go through one :class:`ArtifactStage`: invalidated on entry, promoted only on ``ok=True``;
+ ``artifacts/build.json`` is always the final BuildResult."""
t0 = time.time()
settings = get_settings()
timeout_s = timeout_s or settings.limits.build_timeout_s
@@ -695,8 +659,6 @@ class UrdfBlenderRuntime(RuntimeLayout):
art = ws.artifacts
def finish(res: BuildResult) -> BuildResult:
- # disk never contradicts the returned result: build.json is ALWAYS the
- # final BuildResult; the rest of the set is published only on ok
ws.write_json(stage.path("build.json"), res)
if res.ok:
stage.promote()
@@ -714,7 +676,6 @@ class UrdfBlenderRuntime(RuntimeLayout):
if (missing := missing_entry(ws, self.language, write=False)) is not None:
return finish(missing)
- # 1. lint (cheap, no Blender)
lint = self.lint(ws)
census: dict[str, Any] = {"lint": [f.model_dump(mode="json") for f in lint.findings]}
if not lint.passed:
@@ -739,7 +700,6 @@ class UrdfBlenderRuntime(RuntimeLayout):
file=wrapped.error_file or "src/model.py", line=wrapped.error_line, census=census,
stdout_tail=wrapped.stdout_tail, stderr_tail=wrapped.stderr_tail)
- # 3. URDF copy + load (staged files; extra_paths name the canonical homes)
urdf_staged = stage.path("robot.urdf")
shutil.copyfile(ws.root / "src" / "robot.urdf", urdf_staged)
extra = {"urdf": str(art / "robot.urdf"), "meshes_dir": str(art / "meshes")}
@@ -748,19 +708,16 @@ class UrdfBlenderRuntime(RuntimeLayout):
except UrdfError as e:
return fail("UrdfError", str(e), census=census)
- # 4. FK consistency
fk_findings = check_fk_consistency(robot, census.get("links") or {}, tol_m=FK_TOL_M)
census["fk_check"] = [f.model_dump(mode="json") for f in fk_findings]
if fk_findings:
msg = "\n".join(f"- {f.as_line()}" for f in fk_findings)
return fail("FkInconsistent", f"URDF frames do not reproduce the authored geometry:\n{msg}", census=census)
- # 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
+ # 5. the rest pose decides the build; other poses are the joint_sweep gate
report = sweep_collisions(robot, [{}])
findings = sweep_findings(report, rest_max_m=REST_PENETRATION_MAX_M)
- # 6. canonical GLB at rest
urdf_to_glb(robot, stage.path("object.glb"), None)
extra["object_glb"] = str(art / "object.glb")
res = BuildResult(ok=True, language=self.language.value, glb_path=str(art / "object.glb"), extra_paths=extra,
diff --git a/harness/codeverse3d/languages/wrappers/_census.py b/harness/codeverse3d/languages/wrappers/_census.py
index e5863671..0dcc4594 100644
--- a/harness/codeverse3d/languages/wrappers/_census.py
+++ b/harness/codeverse3d/languages/wrappers/_census.py
@@ -1,11 +1,7 @@
-"""Scene census for the Blender build wrappers — executed BY Blender, never imported by the harness.
+"""Scene census for the Blender build wrappers; runs inside Blender, never imported by the harness.
-``run_bpy.py`` and ``run_bpy_links.py`` import it as a sibling module; it must therefore
-stay standalone (no ``codeverse3d`` imports). It inspects the scene after the agent
-script ran: evaluated triangle counts, world bboxes, materials, parents, and the contract
-warnings the build cannot otherwise see (cameras, lights, visible boolean cutters,
-unlinked meshes, default primitive names, material slots no polygon uses).
-"""
+Imported by run_bpy.py / run_bpy_links.py as a sibling, so it stays standalone. Reports
+evaluated triangle counts, bboxes, materials, parents and contract warnings."""
from __future__ import annotations
@@ -19,7 +15,6 @@ MEASURABLE_TYPES = ("MESH", "CURVE", "SURFACE", "FONT", "META")
def world_bbox(obj_eval: Any, Vector: Any) -> tuple[list[float], list[float]] | None:
- """World-space AABB of an evaluated object (rounded to 0.01 mm); None when it has no bounds."""
corners = [obj_eval.matrix_world @ Vector(c) for c in obj_eval.bound_box]
if not corners:
return None
@@ -29,17 +24,12 @@ def world_bbox(obj_eval: Any, Vector: Any) -> tuple[list[float], list[float]] |
def is_hidden(obj: Any, vl_names: set[str] | None = None) -> bool:
- """True when the object will not render/export (hidden or not in the view layer).
-
- ``vl_names`` is ``set(bpy.context.view_layer.objects.keys())``: objects that are not in
- the view layer (e.g. their collection has ``layer_collection.exclude = True``) report
- ``hide_get() == False`` yet are NOT exported — the census must not count them either.
- """
+ """True when the object will not export: hidden, or not in the view layer (``vl_names``)."""
if vl_names is not None and obj.name not in vl_names:
return True
try:
return bool(obj.hide_render or obj.hide_viewport or obj.hide_get())
- except RuntimeError: # object not in the view layer
+ except RuntimeError:
return True
@@ -66,9 +56,7 @@ def _object_record(obj: Any, dg: Any, scene_objects: set[str], vl_names: set[str
rec["has_uv"] = bool(me.uv_layers)
rec["has_vertex_colors"] = bool(me.color_attributes)
if rec["n_material_slots"] and len(me.polygons):
- # which slots the EXPORT actually uses: modifiers can add indices the
- # authored mesh never had (solidify's material_offset), and an index past
- # the last slot is clamped at export instead of raising
+ # modifiers can add slot indices the mesh never had; export clamps out-of-range ones
per_poly = [0] * len(me.polygons)
me.polygons.foreach_get("material_index", per_poly)
rec["material_indices_used"] = sorted(set(per_poly))
@@ -84,19 +72,13 @@ def _object_record(obj: Any, dg: Any, scene_objects: set[str], vl_names: set[str
def _named(items: list[str], limit: int = 6) -> str:
- """Join at most ``limit`` names — the build shows only 10 warnings, one must not eat them all."""
head = ", ".join(items[:limit])
return head if len(items) <= limit else f"{head} (+{len(items) - limit} more)"
def material_slot_warnings(meshes: list[dict[str, Any]]) -> list[str]:
- """Material slots the polygons never use — the part was authored in N colours and exports in one.
-
- Every new polygon starts on slot 0, so an assignment that silently no-opped (a real run
- read ``res['faces']`` from ``bmesh.ops.create_cube``, which returns only ``{'verts'}``,
- and shipped an 11-slot arm in one off-white) is invisible in the census's material list:
- the materials are all there. Only the per-polygon indices show it.
- """
+ """Material slots no polygon uses: an assignment that silently no-opped leaves them unused
+ while the material list still looks complete."""
unused: list[str] = []
clamped: list[str] = []
for o in meshes:
@@ -160,13 +142,12 @@ def _warnings(bpy: Any, objects: list[dict[str, Any]], boolean_operands: dict[st
def collect_census(bpy: Any) -> dict[str, Any]:
- """Census of every object in ``bpy.data`` (visible meshes count toward the scene bbox / tris)."""
from mathutils import Vector
bpy.context.view_layer.update()
dg = bpy.context.evaluated_depsgraph_get()
scene_objects = set(bpy.context.scene.objects.keys())
- vl_names = set(bpy.context.view_layer.objects.keys()) # what the exporter can actually see
+ vl_names = set(bpy.context.view_layer.objects.keys())
boolean_operands: dict[str, list[str]] = {}
objects: list[dict[str, Any]] = []
total_tris = 0
diff --git a/harness/codeverse3d/languages/wrappers/_census_glb.py b/harness/codeverse3d/languages/wrappers/_census_glb.py
index 4dc6c598..69f89b76 100644
--- a/harness/codeverse3d/languages/wrappers/_census_glb.py
+++ b/harness/codeverse3d/languages/wrappers/_census_glb.py
@@ -1,38 +1,16 @@
-"""The scene_blender census GLB — executed BY Blender (``run_bpy_scene.py``), never imported by the harness.
-
-The geometry gates are the JS ones (``probe_scene.mjs`` → ``host_census`` + ``host_placement``), so a
-Blender scene reaches them as a GLB the harness writes itself from the EVALUATED depsgraph — what
-renders: modifiers, geometry nodes and instances included. The official glTF exporter is not usable
-for this (DESIGN §1.4: it silently drops geometry-nodes instances, and with ``export_gn_mesh`` it did
-not finish in 10 min on 73 k grass blades; this writer: 0.1–0.4 s). Geometry, names, base colour
-and custom properties only: the file is an instrument for gates, never a picture.
-
-Layout (what the census and the placement table read):
-
-* root nodes = env objects (whatever is not in a zone collection), by object name — ``backdrop.mjs``
- classifies ``Ground`` / ``Terrain`` / ``Water`` / ``Sky…`` by name, so names are carried verbatim;
-* one root node per ZONE collection, named for it and marked ``extras[zone_key]`` (D111: the
- placement table's zone roots; env roots are scenery); its children = the zone's root objects, their
- parent chains as child nodes (group nodes carry no transform: every mesh node holds its world
- matrix, so an Empty's rotation can never be applied twice);
-* a collection-instance Empty = a node whose children are one mesh node per instanced object, all
- sharing one glTF mesh per source mesh — a clone per placed asset, which ``host_placement`` checks;
-* any other instance cloud (geometry nodes, particles, dupli-verts/faces) = one
- ``EXT_mesh_gpu_instancing`` node per (instancer, source mesh) — an ``InstancedMesh`` in three.js,
- counted as instances and exempt from per-asset placement exactly like scatter is today;
-* a mesh every material of which is volume-only (a fog box) is not written: it is not matter, and
- the fog is reported from bpy instead (``run_bpy_scene.scene_facts``);
-* custom properties of str/int/float/bool value → node ``extras`` → three.js ``userData`` (so
- ``obj["placement"] = "free"`` exempts a deliberately airborne thing, as ``userData.placement`` does);
-* the scene's ``extras.c3d_cameras`` carries the harness cameras in the GLB frame — the adapter
- (``runtime_js/lib/glb_scene.mjs``) hands them to the host;
-* a non-finite matrix or vertex is never written (``JSON.parse`` rejects ``NaN``): the writer collects
- every one (``_finite.Offenders``) and raises ``NonFiniteError`` before writing — the model's build
- error, naming the object, the channel and the file that built it (D114).
-
-Frame: ``basis`` (3×3 rows, from ``conventions.glb_basis`` via the wrapper's argv) takes a Blender
-vector into the GLB frame (Y-up, +Z front); nothing here restates it.
-"""
+"""The scene_blender census GLB; runs inside Blender (``run_bpy_scene.py``), never imported by the harness.
+
+Writes a GLB from the evaluated depsgraph (modifiers, geometry nodes and instances included) so
+the JS geometry gates can read a Blender scene. Geometry, names, base colour and custom
+properties only; it is an instrument for gates, never a picture.
+
+Layout: env objects are root nodes by name; each ZONE collection is one root node marked
+``extras[zone_key]``; collection instances are nodes sharing one glTF mesh per source mesh; other
+instance clouds are ``EXT_mesh_gpu_instancing`` nodes; volume-only meshes are skipped; custom
+properties become node ``extras``; ``extras.c3d_cameras`` carries the harness cameras. A
+non-finite matrix or vertex is never written: it raises ``NonFiniteError`` as the model's error.
+
+``basis`` (from ``conventions.glb_basis``) takes a Blender vector into the GLB frame."""
from __future__ import annotations
@@ -43,7 +21,7 @@ from collections.abc import Callable
from typing import Any
import numpy as np
-from _finite import NonFiniteError, Offenders, bad_rows, finite # sibling, Blender-executed
+from _finite import NonFiniteError, Offenders, bad_rows, finite
MEASURABLE_TYPES = ("MESH", "CURVE", "SURFACE", "FONT", "META")
_FLOAT, _UINT = 5126, 5125
@@ -68,7 +46,6 @@ def is_volume_material(mat: Any) -> bool:
def is_volume_only(obj: Any) -> bool:
- """Every material slot of ``obj`` is a volume material (and it has at least one)."""
mats = [s.material for s in getattr(obj, "material_slots", ())]
return bool(mats) and all(is_volume_material(m) for m in mats)
@@ -92,7 +69,6 @@ def _input_value(node: Any, name: str, default: Any) -> Any:
# ----------------------------------------------------------------------------- math
def _quaternions(rot: np.ndarray) -> np.ndarray:
- """(n, 3, 3) rotation matrices → (n, 4) quaternions (x, y, z, w), Shepperd's method."""
n = rot.shape[0]
q = np.empty((n, 4), np.float64)
tr = rot[:, 0, 0] + rot[:, 1, 1] + rot[:, 2, 2]
@@ -120,10 +96,9 @@ def _quaternions(rot: np.ndarray) -> np.ndarray:
def _trs(mats: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
- """(n, 4, 4) GLB-frame matrices → translations, quaternions, scales (a mirror flips one scale)."""
t = mats[:, :3, 3]
lin = mats[:, :3, :3]
- s = np.linalg.norm(lin, axis=1) # column norms: L = R · diag(s)
+ s = np.linalg.norm(lin, axis=1)
s = np.where(s < 1e-12, 1e-12, s)
r = lin / s[:, None, :]
neg = np.linalg.det(r) < 0
@@ -183,8 +158,7 @@ class _Writer:
return self.mat_ix[key]
def mesh(self, key: Any, me: Any, slots: list[Any], owner: Any) -> int | None:
- """One glTF mesh per source mesh datablock (``key``); ``None`` for an empty one, and for one
- with a non-finite vertex (recorded against ``owner``, the object that shows it)."""
+ """One glTF mesh per source mesh datablock; ``None`` when empty or holding a non-finite vertex."""
if key in self.mesh_ix:
return self.mesh_ix[key]
me.calc_loop_triangles()
@@ -221,8 +195,7 @@ class _Writer:
return self.b4 @ np.array(mw, np.float64) @ self.b4.T
def node_matrix(self, mw: Any, *blame: Any, via: str = "") -> list[float] | None:
- """``mw`` in the GLB frame as a glTF column-major list; ``None`` (recorded against ``blame``)
- when it holds a non-finite value."""
+ """``mw`` as a glTF column-major list in the GLB frame; ``None`` when non-finite."""
m = self.glb_matrix(mw)
if not finite(m):
self.bad.transform(*blame, via=via)
@@ -230,7 +203,6 @@ class _Writer:
return m.T.reshape(-1).tolist()
def node(self, node: dict[str, Any], path: tuple[str, ...]) -> int:
- """Append ``node`` under the group node of ``path`` (a root when ``path`` is empty)."""
self.nodes.append(node)
i = len(self.nodes) - 1
if path:
@@ -256,7 +228,7 @@ class _Writer:
}
if any("extensions" in n for n in self.nodes):
g["extensionsUsed"] = ["EXT_mesh_gpu_instancing"]
- js = json.dumps(g, separators=(",", ":"), allow_nan=False).encode() # NaN is not JSON (D114)
+ js = json.dumps(g, separators=(",", ":"), allow_nan=False).encode()
js += b" " * (-len(js) % 4)
head = struct.pack("<III", 0x46546C67, 2, 12 + 8 + len(js) + 8 + len(self.buf))
return (head + struct.pack("<II", len(js), 0x4E4F534A) + js
@@ -264,10 +236,9 @@ class _Writer:
def extras_of(obj: Any) -> dict[str, Any]:
- """Custom properties a gate can read (``placement = 'free'``); IDProperty groups / arrays and
- non-finite floats (not JSON) dropped."""
+ """Custom properties a gate can read; IDProperty groups / arrays and non-finite floats are dropped."""
out: dict[str, Any] = {}
- for k in obj.keys(): # noqa: SIM118 — a bpy ID is not iterable over its custom properties
+ for k in obj.keys(): # noqa: SIM118
v = obj[k]
if isinstance(v, float) and not finite([v]):
continue
@@ -287,15 +258,10 @@ def _chain(obj: Any) -> list[Any]:
def write_census_glb(bpy: Any, path: str, *, basis: list[list[float]], zones: dict[str, str],
cameras: list[dict[str, Any]], zone_key: str,
origin: Callable[[Any], str] | None = None) -> dict[str, Any]:
- """Write the census GLB of the current (t = 0) state to ``path``; return its stats.
-
- ``zones`` maps a zone COLLECTION name to itself for every zone the wrapper built (the node
- name); every object in one of them (recursively) hangs under that zone's node, and that node's
- ``extras`` carry ``{zone_key: <zone>}`` (``conventions.ZONE_ROOT_KEY``, D111) — the mark the
- placement table measures the zone's children by; every other root is scenery.
+ """Write the census GLB of the current state to ``path``; return its stats.
- Raises ``NonFiniteError`` (nothing written) when a matrix or vertex it would write is NaN / inf;
- ``origin(obj)`` names the file that built an original object, for that report."""
+ ``zones`` maps each zone collection name to itself; objects under one hang under its node.
+ Raises ``NonFiniteError`` (nothing written) on a NaN / inf matrix or vertex."""
t0 = time.perf_counter()
w = _Writer(np.array(basis, np.float64), Offenders(origin))
zone_of: dict[str, str] = {}
@@ -311,8 +277,6 @@ def write_census_glb(bpy: Any, path: str, *, basis: list[list[float]], zones: di
return ((zone,) if zone else ()) + tuple(o.name for o in chain)
def ensure_groups(obj: Any, *, own: bool = False) -> tuple[str, ...]:
- """Group nodes for the ancestors of ``obj`` (+ ``obj`` itself when ``own``), top down so each
- carries its object's custom properties; returns the path ``obj``'s own node hangs under."""
chain = _chain(obj)
zone = zone_of.get(chain[0].name)
base = (zone,) if zone else ()
@@ -325,10 +289,9 @@ def write_census_glb(bpy: Any, path: str, *, basis: list[list[float]], zones: di
"clouds": 0, "volumes_skipped": []}
dg = bpy.context.evaluated_depsgraph_get()
clouds: dict[tuple[tuple[str, ...], Any], tuple[int | None, str, list[np.ndarray], Any, str]] = {}
- for zone in zones: # an empty zone is still a group the census can see
+ for zone in zones:
own = extras_of(bpy.data.collections[zone]) if zone in bpy.data.collections else {}
w.group((zone,), {**own, zone_key: zone})
- # an object that hosts an instance cloud is its own group (its mesh + the cloud = one row)
hosts = {inst.parent.original.name for inst in dg.object_instances
if inst.is_instance and inst.parent is not None and inst.parent.original.instance_type != "COLLECTION"}
for inst in dg.object_instances:
@@ -340,23 +303,18 @@ def write_census_glb(bpy: Any, path: str, *, basis: list[list[float]], zones: di
if host is None or host.hide_render or is_volume_only(ob):
continue
if host.type in MEASURABLE_TYPES and host.type != "MESH":
- # a bevelled curve / a text object: the depsgraph lists the owner's own evaluated
- # mesh component as an instance OF the owner (Blender 5.2.2, measured 2026-10-14:
- # is_instance, parent = the curve, original = the curve) — written once, from the
- # owner, by _write_other_types; a cloud here would be a phantom second copy
+ # curve and text meshes have their own writer; skip the instance
continue
- # the geometry and the placement are both checked before either skips: two independent
- # NaNs are one report, not two repair attempts
+ # check geometry and placement before either skips: two NaNs are one report
ix = w.mesh(ob.data.as_pointer(), ob.data, [s.material for s in ob.material_slots], ob.original)
- if host.instance_type == "COLLECTION": # a placed asset: one clone node per instanced mesh
+ if host.instance_type == "COLLECTION":
m = w.node_matrix(inst.matrix_world, host, ob.original, via=f"(instanced by {host.name!r})")
if ix is None or m is None:
continue
w.node({"name": ob.name, "mesh": ix, "matrix": m}, ensure_groups(host, own=True))
stats["instanced_tris"] += w.mesh_tris[ix]
continue
- key = (path_of(host), ob.data.as_pointer()) # Blender-frame matrices, converted in one batch below
- # a geometry-nodes instance is listed AS its host (object name = the host's): the mesh names it
+ key = (path_of(host), ob.data.as_pointer())
source = f"mesh {ob.data.name!r}" if ob.name == host.name else repr(ob.name)
clouds.setdefault(key, (ix, ob.name, [], host, source))[2].append(np.array(inst.matrix_world, np.float32))
continue
@@ -369,7 +327,6 @@ def write_census_glb(bpy: Any, path: str, *, basis: list[list[float]], zones: di
m = w.node_matrix(ob.matrix_world, orig)
if ix is None or m is None:
continue
- # a mesh with children is its own group (one placement row), its geometry a node inside it
under = ensure_groups(orig, own=bool(orig.children) or orig.name in hosts)
node = {"name": orig.name, "mesh": ix, "matrix": m}
if ex := extras_of(orig):
@@ -406,7 +363,6 @@ def write_census_glb(bpy: Any, path: str, *, basis: list[list[float]], zones: di
def _write_other_types(dg: Any, w: _Writer, stats: dict[str, Any], ensure_groups: Any) -> None:
- """Curves, text, surfaces and metaballs that stayed their own type after evaluation."""
for inst in dg.object_instances:
ob = inst.object
if inst.is_instance or ob.type == "MESH" or ob.type not in MEASURABLE_TYPES:
@@ -431,7 +387,6 @@ def _write_other_types(dg: Any, w: _Writer, stats: dict[str, Any], ensure_groups
def _glb_camera(c: dict[str, Any], b3: np.ndarray) -> dict[str, Any]:
- """A harness camera (Blender frame: ``location`` / ``look_at``, vertical ``fov``) as the host's spec."""
pos = (b3 @ np.array(c["location"], np.float64)).tolist()
look = (b3 @ np.array(c["look_at"], np.float64)).tolist()
return {"name": str(c["name"]), "position": [round(v, 5) for v in pos], "lookAt": [round(v, 5) for v in look],
diff --git a/harness/codeverse3d/languages/wrappers/_finite.py b/harness/codeverse3d/languages/wrappers/_finite.py
index 7c7d3180..841d93bc 100644
--- a/harness/codeverse3d/languages/wrappers/_finite.py
+++ b/harness/codeverse3d/languages/wrappers/_finite.py
@@ -1,16 +1,8 @@
-"""Non-finite (NaN / inf) transforms and vertices — executed BY Blender, never imported by the harness.
+"""Non-finite (NaN / inf) transforms and vertices; runs inside Blender, never imported by the harness.
-A model's bpy code that divides by zero, normalizes a zero vector or takes ``math.acos`` of 1.0000001
-leaves a NaN in an object's location / rotation / scale or in its vertices. Blender keeps it
-silently; what reads the scene afterwards does not: the census GLB's JSON carried
-``"matrix":[NaN,…]`` and the probe host's ``JSON.parse`` failed — read as a HARNESS failure, so the
-model was never told (D114, 2026-10-17); the official glTF exporter drops a NaN translation (the
-object exports at the origin) and writes NaN vertices into the buffer. So every wrapper checks
-what it is about to write, and a non-finite value is the MODEL's build error, naming the object,
-the channel and — when the wrapper knows it — the file that built it.
-
-Standalone: numpy + the duck-typed bpy objects it is handed (a unit test hands it plain objects).
-"""
+Blender keeps NaNs silently but exporters and JSON readers fail on them, so each wrapper
+checks what it is about to write and reports a non-finite value as the model's build error.
+Standalone: numpy plus duck-typed bpy objects."""
from __future__ import annotations
@@ -20,7 +12,7 @@ from typing import Any
import numpy as np
TRANSFORM_ERROR, GEOMETRY_ERROR = "NonFiniteTransform", "NonFiniteGeometry"
-#: an object's own channel is finite, its world matrix is not: something evaluated produced it
+#: the object's own channels are finite but its world matrix is not
EVALUATED_NOTE = "matrix_world (its own location/rotation/scale are finite: a constraint, driver or parent produced it)"
_SHOWN = 8
_CAUSES = ("usual causes: a division by zero, normalized() of a zero-length vector, math.acos/asin/sqrt "
@@ -28,7 +20,6 @@ _CAUSES = ("usual causes: a division by zero, normalized() of a zero-length vect
def finite(values: Any) -> bool:
- """Every number in ``values`` (a vector, a matrix, an array) is finite; ``True`` when it holds none."""
try:
arr = np.asarray([list(r) if _iterable(r) else r for r in values] if _iterable(values) else values,
dtype=np.float64)
@@ -46,7 +37,6 @@ def _fmt(values: Any) -> str:
def own_channels(obj: Any) -> list[str]:
- """``obj``'s own transform channels holding a non-finite value, as ``"location=(nan, 0, 1.2)"``."""
mode = str(getattr(obj, "rotation_mode", "XYZ"))
rot = {"QUATERNION": "rotation_quaternion", "AXIS_ANGLE": "rotation_axis_angle"}.get(mode, "rotation_euler")
drot = "delta_rotation_quaternion" if mode == "QUATERNION" else "delta_rotation_euler"
@@ -62,8 +52,7 @@ def own_channels(obj: Any) -> list[str]:
def transform_culprit(*objs: Any) -> tuple[Any, list[str]]:
- """The first of ``objs`` — each walked up its parent chain — whose own channels are non-finite,
- with those channels; ``(objs[0], [EVALUATED_NOTE])`` when every channel on the way is finite."""
+ """First of ``objs`` (walking up parents) whose own channels are non-finite, with those channels."""
for obj in objs:
o = obj
while o is not None:
@@ -74,13 +63,11 @@ def transform_culprit(*objs: Any) -> tuple[Any, list[str]]:
def bad_rows(co: np.ndarray) -> int:
- """How many rows of an (n, k) array hold a non-finite value."""
return int((~np.isfinite(co.reshape(co.shape[0], -1))).any(axis=1).sum()) if co.size else 0
class NonFiniteError(ValueError):
- """Raised by a writer that found offenders, BEFORE writing anything: the build's error is
- ``offenders.report()``, the model's to fix."""
+ """Raised before anything is written; ``offenders.report()`` is the build error."""
def __init__(self, offenders: Offenders) -> None:
self.offenders = offenders
@@ -88,8 +75,7 @@ class NonFiniteError(ValueError):
class Offenders:
- """What a wrapper found non-finite, one row per (object, kind); ``origin(obj)`` names the file that
- built ``obj`` (``""`` when unknown). Falsy while empty; :meth:`report` is the build error."""
+ """What a wrapper found non-finite, one row per (object, kind). Falsy while empty."""
def __init__(self, origin: Callable[[Any], str] | None = None) -> None:
self.origin = origin
@@ -99,17 +85,13 @@ class Offenders:
return bool(self.rows)
def transform(self, *objs: Any, via: str = "") -> None:
- """A non-finite world matrix of ``objs[0]`` (the others: who else could carry it — an
- instance's source object); ``via`` says how it reached the scene."""
culprit, channels = transform_culprit(*objs)
detail = "; ".join(channels)
- if culprit is not objs[0]: # ``via`` says how the culprit reached objs[0] — nothing when it IS objs[0]
+ if culprit is not objs[0]:
detail = f"{detail} (makes {getattr(objs[0], 'name', '?')!r} non-finite)" + (f" {via}" if via else "")
self._add(culprit, "transform", detail)
def instances(self, host: Any, source: str, bad: int, total: int) -> None:
- """``bad`` of the ``total`` instances of ``source`` (as shown: ``"'Blade'"``, ``"mesh 'BladeMesh'"``)
- that ``host`` scatters (geometry nodes, particles, dupli-verts) have a non-finite transform."""
self._add(host, "instances", f"{bad} of {total} instances of {source} it scatters have a non-finite "
"transform (geometry nodes / particles: a NaN position, rotation or scale)")
@@ -123,12 +105,11 @@ class Offenders:
if self.origin is not None:
try:
file = self.origin(obj) or ""
- except Exception: # noqa: BLE001 — a lookup must never cost the report
+ except Exception: # noqa: BLE001
file = ""
self.rows[(name, kind)] = {"object": name, "kind": kind, "detail": detail, "file": file}
def report(self) -> dict[str, Any]:
- """The build-report fields (``error_type`` / ``error_message`` / ``error_file`` / ``error_line``)."""
rows = list(self.rows.values())
kind = GEOMETRY_ERROR if all(r["kind"] == "vertices" for r in rows) else TRANSFORM_ERROR
shown = [f"{r['object']!r}" + (f" [{r['file']}]" if r["file"] else "") + f": {r['detail']}" for r in rows[:_SHOWN]]
@@ -140,7 +121,6 @@ class Offenders:
def scan_objects(objs: Iterable[Any], dg: Any, offenders: Offenders) -> Offenders:
- """World matrix + evaluated vertices of each of ``objs`` (bpy objects) into ``offenders``."""
for obj in objs:
if not finite(obj.matrix_world):
offenders.transform(obj)
diff --git a/harness/codeverse3d/languages/wrappers/_wrapper_common.py b/harness/codeverse3d/languages/wrappers/_wrapper_common.py
index 2e2d039a..4a1871b6 100644
--- a/harness/codeverse3d/languages/wrappers/_wrapper_common.py
+++ b/harness/codeverse3d/languages/wrappers/_wrapper_common.py
@@ -1,13 +1,7 @@
-"""What every python build wrapper does around the agent's script — run_bpy.py and
-run_bpy_links.py inside Blender (its bundled python 3.11), run_cq.py in the harness python.
+"""Shared helpers for the python build wrappers (run_bpy, run_bpy_links, run_cq).
-Standalone: stdlib only and no 3.12+ syntax, never imported by the harness. A wrapper puts
-its own directory on ``sys.path`` and imports this module as a sibling; ``run_script`` takes
-that directory off again before the agent's code runs.
-
-The report a wrapper writes is ``build.json`` — the runtime reads it once and replaces it
-with the final ``BuildResult`` (``languages/_common.compose_build_result``).
-"""
+Standalone: stdlib only, no 3.12+ syntax, never imported by the harness. The wrapper's
+directory is on ``sys.path`` for the import and removed before the agent's code runs."""
from __future__ import annotations
@@ -23,24 +17,21 @@ from collections.abc import Callable
from typing import Any
WRAPPER_DIR = os.path.dirname(os.path.realpath(__file__))
-PARTS_PKG = "parts" # src/parts/<snake>.py → ``from parts.<snake> import build_<snake>``
+PARTS_PKG = "parts"
def wrapper_argv() -> list[str]:
- """The wrapper's own arguments: after ``--`` under Blender, else ``sys.argv[1:]``."""
return sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else sys.argv[1:]
def new_report(rlimit_gb: float, **extra: Any) -> dict[str, Any]:
- """The build.json skeleton; applies the memory cap first (RLIMIT_AS, so a geometry bomb
- dies in-process)."""
+ """The build.json skeleton; applies the memory cap first (RLIMIT_AS)."""
_apply_rlimit(rlimit_gb)
return {"ok": False, "error_type": "", "error_message": "", "error_file": "",
"error_line": None, "error_source": "", "traceback": "", "warnings": [], "exported": {}, **extra}
def _apply_rlimit(gb: float) -> None:
- """Best effort: where RLIMIT_AS cannot be set the build runs uncapped."""
if gb <= 0:
return
try:
@@ -55,7 +46,6 @@ def _apply_rlimit(gb: float) -> None:
def seed_everything(seed: int) -> None:
- """``random``, numpy and ``mathutils.noise`` (whichever this interpreter has)."""
random.seed(seed)
try:
import numpy as np
@@ -72,9 +62,7 @@ def seed_everything(seed: int) -> None:
def src_relative(path: str, src_dir: str) -> str | None:
- """``/ws/src/parts/leg.py`` → ``src/parts/leg.py`` when ``path`` lives under ``src_dir``; else None.
-
- Every runtime reports ``error_file`` workspace-relative so the repair loop can open it."""
+ """``/ws/src/parts/leg.py`` -> ``src/parts/leg.py`` when under ``src_dir``; else None."""
real_src = os.path.realpath(src_dir)
real = os.path.realpath(path)
if real == real_src or not real.startswith(real_src + os.sep):
@@ -83,11 +71,7 @@ def src_relative(path: str, src_dir: str) -> str | None:
def map_exception(exc: BaseException, script_path: str, *, hint: str = "", memory: str = "") -> dict[str, Any]:
- """Traceback → {error_type, error_message, error_file, error_line, error_source, traceback}.
-
- The innermost frame under ``src/`` wins, so a failure in a part or helper file is
- reported against that file, not the ``model.py`` line that called it. ``hint`` is
- appended to the message; ``memory`` replaces it on a MemoryError (what to reduce)."""
+ """Traceback -> error fields; the innermost frame under ``src/`` wins."""
src_dir = os.path.dirname(os.path.abspath(script_path))
info: dict[str, Any] = {"error_type": type(exc).__name__, "error_message": (str(exc) or type(exc).__name__) + hint,
"error_file": "", "error_line": None, "error_source": ""}
@@ -107,18 +91,13 @@ def map_exception(exc: BaseException, script_path: str, *, hint: str = "", memor
def run_script(script_path: str) -> tuple[BaseException | None, dict[str, Any] | None]:
- """Execute the agent's entry script as ``__main__`` → (what it raised, its globals).
-
- ``<ws>/src`` goes first on ``sys.path`` (``from parts.leg import build_leg``, a helper
- module beside model.py); the wrapper's own directory goes off it, no bytecode is
- written into the git-tracked src/. ``sys.exit(0)`` is not a failure: it returns
- ``(None, None)`` — no globals to read."""
+ """Run the agent's entry script as ``__main__`` -> (exception, globals); ``sys.exit(0)`` gives ``(None, None)``."""
src_dir = os.path.dirname(os.path.abspath(script_path))
sys.path[:] = [p for p in sys.path if os.path.realpath(p) not in (os.path.realpath(src_dir), WRAPPER_DIR)]
sys.path.insert(0, src_dir)
sys.dont_write_bytecode = True
for name in [m for m in sys.modules if m == PARTS_PKG or m.startswith(PARTS_PKG + ".")]:
- del sys.modules[name] # never reuse a stale module from somewhere else on the path
+ del sys.modules[name]
importlib.invalidate_caches()
saved_argv = sys.argv
sys.argv = [script_path]
@@ -126,7 +105,7 @@ def run_script(script_path: str) -> tuple[BaseException | None, dict[str, Any] |
return None, runpy.run_path(script_path, run_name="__main__")
except SystemExit as e:
return (None, None) if e.code in (None, 0) else (e, None)
- except BaseException as e: # noqa: BLE001 — every failure must be reported, never propagate
+ except BaseException as e: # noqa: BLE001
return e, None
finally:
sys.argv = saved_argv
@@ -134,9 +113,7 @@ def run_script(script_path: str) -> tuple[BaseException | None, dict[str, Any] |
def write_report(out_dir: str, report: dict[str, Any], census: dict[str, Any], t0: float, *,
names: tuple[str, str] = ("build.json", "census.json")) -> None:
- """census.json + build.json (``names``: the report's and the census's file names), atomically;
- a failure's traceback also goes to stderr, where the runtime's ``stderr_tail`` (and so the
- repair prompt) picks it up."""
+ """Write census.json + build.json atomically; a failure's traceback also goes to stderr."""
report["duration_ms"] = int((time.monotonic() - t0) * 1000)
_write_json_atomic(os.path.join(out_dir, names[1]), census)
_write_json_atomic(os.path.join(out_dir, names[0]), report)
@@ -152,8 +129,7 @@ def _write_json_atomic(path: str, data: Any) -> None:
def exit_after(main: Callable[[], int]) -> None:
- """``sys.exit(main())``: 0 once the report is written (even when the script failed),
- 2 on a wrapper bug — traceback on stderr, no report."""
+ """0 once the report is written (even when the script failed); 2 on a wrapper bug."""
try:
code = main()
except Exception: # noqa: BLE001
diff --git a/harness/codeverse3d/languages/wrappers/render_bpy_scene.py b/harness/codeverse3d/languages/wrappers/render_bpy_scene.py
index 9bdf0489..ee0de844 100644
--- a/harness/codeverse3d/languages/wrappers/render_bpy_scene.py
+++ b/harness/codeverse3d/languages/wrappers/render_bpy_scene.py
@@ -1,38 +1,12 @@
-"""Blender render driver for a built ``scene_blender`` workspace — executed BY Blender, never
-imported by the harness.
+"""Blender render driver for a built ``scene_blender`` workspace; runs inside Blender, never imported by the harness.
blender -b --factory-startup <ws>/artifacts/scene.blend --python render_bpy_scene.py -- <job.json>
-The harness (``spatial/render_blender.py``) writes the job; every number in it is already in
-the BLENDER frame (Z-up, -Y front, metres — the harness converts, ``conventions`` owns frames):
-
- {"out": "/abs/dir", "result": "/abs/dir/blender_frames.json",
- "engine": "cycles" | "eevee" | "workbench", "samples": 32, "device": "GPU" | "CPU",
- "frame_time_limit_s": 20.0, "width": 1024, "height": 576, "times": [0.0, 1.5],
- "authored": true, "cameras": [{"name", "kind", "position", "look_at", "fov", "no_fog", "times"}]}
-
-What it does:
- 1. render settings — ALL harness-owned, whatever the .blend carries: engine, samples,
- device (Cycles CUDA; no CUDA device → CPU, recorded), adaptive sampling + OIDN on the GPU,
- persistent data (the scene is synced once for all cameras), a per-frame time cap, a fixed
- seed, AgX / look None / exposure 0 on the sRGB display, RGB 8-bit PNG, no transparent film;
- 2. cameras: with ``authored`` the .blend's own camera objects (``scene["c3d_cameras"]`` gives
- their order, else the scene camera first then by name; ``cam["c3d_look_at"]`` their target,
- else 10 m along the view axis), rendered as authored at every time; then one harness camera
- per job spec (vertical ``fov`` like three.js), at the spec's own times;
- 3. per time (ascending): ``frame_set(1 + round(t * fps))``, then every camera renders one PNG
- ``<name>_<tag>.png`` (the three.js driver's file names); ``no_fog`` views render with the
- world volume unlinked AND a room shell's lid lifted — every mesh named ``Ceiling…`` under
- a ``RoomShell…`` parent whose evaluated world bbox top is below the camera is render-hidden
- for that frame (the three.js host's ``skyLayersBelow`` rule, scene_host.mjs; the rubric
- tells the judge the high overviews show interiors with the lid off) and named in the
- frame's ``hidden`` (the overview rig reads structure, not atmosphere);
- 4. writes the result json atomically: the frames (Blender-frame poses, per-frame wall ms),
- the device actually used, the GL renderer (EEVEE / Workbench) and every per-frame error.
-
-A frame that fails is recorded and the others still render. Exit codes: 0 = result written;
-2 = driver bug (no result). Standalone: stdlib + bpy only.
-"""
+The harness (``spatial/render_blender.py``) writes the job, already in the Blender frame. The
+driver owns all render settings, renders the authored cameras then the harness cameras at each
+time (``no_fog`` views drop the world volume, fog boxes and room-shell lids), and writes the
+result json atomically. A failed frame is recorded and the rest still render. Exit 0 = result
+written; 2 = driver bug. Standalone: stdlib + bpy only."""
from __future__ import annotations
@@ -46,8 +20,8 @@ from typing import Any
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
import bpy # noqa: E402
-from _census_glb import is_volume_only # noqa: E402 (sibling: the census's own fog test)
-from _wrapper_common import ( # noqa: E402 (sibling, Blender-executed)
+from _census_glb import is_volume_only # noqa: E402
+from _wrapper_common import ( # noqa: E402
_write_json_atomic,
exit_after,
wrapper_argv,
@@ -55,14 +29,13 @@ from _wrapper_common import ( # noqa: E402 (sibling, Blender-executed)
from mathutils import Vector # noqa: E402
ENGINES = {"cycles": "CYCLES", "eevee": "BLENDER_EEVEE", "workbench": "BLENDER_WORKBENCH"}
-#: a harness camera's clip range: Cycles has no depth-precision cost, so the far plane is simply out of the way
+#: harness-camera clip range; the far plane is simply out of the way
CLIP_START, CLIP_END = 0.05, 20000.0
LOOK_AHEAD_M = 10.0
def tag(t: float) -> str:
- """``0 → t0``, ``1.5 → t1p5``: the three.js driver's ``tag()`` (render_scene.mjs), so both
- languages name a view's file the same way."""
+ """``0 -> t0``, ``1.5 -> t1p5``: the same file-name tag as the three.js driver."""
s = f"{t:.2f}".rstrip("0").rstrip(".")
return "t" + s.replace(".", "p")
@@ -78,7 +51,6 @@ def frame_of(t: float, scene: Any) -> int:
# --------------------------------------------------------------------------- settings
def setup_render(scene: Any, job: dict[str, Any]) -> dict[str, Any]:
- """Engine / device / samples / colour: returns what was actually configured."""
engine = str(job.get("engine") or "cycles")
samples = int(job.get("samples") or 32)
want = str(job.get("device") or "GPU").upper()
@@ -106,8 +78,7 @@ def setup_render(scene: Any, job: dict[str, Any]) -> dict[str, Any]:
if engine == "cycles":
c = scene.cycles
if want == "GPU":
- # CUDA only — OptiX is never probed: on this WSL2 box Blender 5.2.2 has no libnvoptix
- # (init error 7804) and setting compute_device_type to OPTIX and back crashes Blender.
+ # CUDA only: OptiX is never probed (setting compute_device_type to OPTIX crashes Blender under WSL2)
prefs = bpy.context.preferences.addons["cycles"].preferences
try:
prefs.compute_device_type = "CUDA"
@@ -130,17 +101,14 @@ def setup_render(scene: Any, job: dict[str, Any]) -> dict[str, Any]:
c.denoising_use_gpu = info["device"] == "GPU"
c.seed = 0
c.use_animated_seed = False
- # The fast path (Blender 5.2.2 LTS, RTX 5090, 1024x576, 460 objects, 32 spp): persistent
- # data keeps the synced scene + BVH across the cameras of one job — 8 frames 5.3 s → 2.2 s
- # (0.64 → 0.21 s per frame after the first). The per-frame time cap bounds a heavy
- # scene's sampling (0 = none); the job's render timeout is the outer wall.
+ # persistent data keeps the synced scene across a job's cameras; the per-frame time cap bounds sampling (0 = none)
r.use_persistent_data = True
c.time_limit = max(0.0, float(job.get("frame_time_limit_s") or 0.0))
info["persistent_data"] = True
info["frame_time_limit_s"] = c.time_limit
elif engine == "eevee":
scene.eevee.taa_render_samples = samples
- info["device"] = want # the GL context decides; the harness picks the env (d3d12 = GPU)
+ info["device"] = want
else:
info["samples"] = 0
info["device"] = want
@@ -153,14 +121,13 @@ def _vec(v: Any) -> list[float]:
def vertical_fov_deg(cam: Any, aspect: float) -> float:
- """The camera's VERTICAL field of view at the render aspect (the plan's fov is vertical)."""
d = cam.data
fit = d.sensor_fit
if fit == "VERTICAL":
return math.degrees(d.angle_y)
if fit == "HORIZONTAL" or aspect >= 1.0:
return math.degrees(2 * math.atan(math.tan(d.angle_x / 2) / aspect))
- return math.degrees(d.angle_x) # AUTO on a portrait frame: the sensor width spans the height
+ return math.degrees(d.angle_x)
def authored_cameras(scene: Any) -> list[Any]:
@@ -205,9 +172,8 @@ def harness_camera(spec: dict[str, Any]) -> Any:
# --------------------------------------------------------------------------- fog
def unlink_world_volume(scene: Any) -> list[tuple[Any, Any]]:
- """Remove the world output's Volume links; returns them for ``relink``."""
w = scene.world
- if w is None or w.node_tree is None: # 5.x: a world always has a node tree (use_nodes is deprecated)
+ if w is None or w.node_tree is None:
return []
removed = []
for n in w.node_tree.nodes:
@@ -224,22 +190,13 @@ def relink(scene: Any, links: list[tuple[Any, Any]]) -> None:
# --------------------------------------------------------------------------- fog boxes
-#: a volume-only mesh at least this wide (largest evaluated bbox side, m) is a fog box, hidden from the
-#: fog-free views; anything smaller is a puff of steam, smoke or dust and stays in every view
+#: a volume-only mesh at least this wide (m) is a fog box; smaller ones are steam / dust and stay
FOG_BOX_MIN_M = 8.0
def hide_fog_boxes(scene: Any) -> list[Any]:
- """Render-hide every bounded fog volume and return those objects (restore with ``hide_render = False``).
-
- WHY. The ``no_fog`` views are the judge's placement views: ``unlink_world_volume`` takes the world's
- Volume out, but 30/30 iteration-0 and 14/15 iteration-2 Blender envs built the fog as a
- volume-only BOX, which those views kept, so the judge read floating / sunken /
- interpenetration through 0.003-0.008 /m of haze over a few hundred metres (2026-10-15: the
- iteration-2 overview tiles came out milky). A fog box is a mesh every material of which is
- volume-only (``_census_glb.is_volume_only``, the census's own test) and whose largest evaluated
- bbox side is >= ``FOG_BOX_MIN_M``; a soft particle (a volume-only material on a small mesh) is
- smaller and stays. Linked library data and already hidden objects are left alone."""
+ """Render-hide every bounded fog volume (volume-only mesh, largest bbox side >= ``FOG_BOX_MIN_M``);
+ returns them. Linked library data and already hidden objects are left alone."""
depsgraph = bpy.context.evaluated_depsgraph_get()
boxes = []
for ob in scene.objects:
@@ -259,12 +216,8 @@ ROOM_SHELL_PREFIX, LID_PREFIX = "RoomShell", "Ceiling"
def lift_lids(scene: Any, camera: Any) -> list[Any]:
- """Render-hide every room shell lid under ``camera`` and return those objects (restore with
- ``hide_render = False``). A lid is a mesh object named ``Ceiling…`` whose parent is named
- ``RoomShell…`` (the prompts promise the author the rig lifts it by name) and whose evaluated world-space bbox top is below the camera's
- z: ``scene_host.skyLayersBelow``'s rule, so both languages' overview tiles show the same
- interior. An author's own roof, a lid the camera is under, an already hidden lid and
- linked library data (never written) stay."""
+ """Render-hide every room-shell lid (a ``Ceiling…`` mesh under a ``RoomShell…`` parent) whose
+ bbox top is below ``camera``; returns them. Mirrors ``scene_host.skyLayersBelow``."""
depsgraph = bpy.context.evaluated_depsgraph_get()
eye_z = camera.evaluated_get(depsgraph).matrix_world.translation.z
lids = []
@@ -287,7 +240,7 @@ def gl_renderer() -> str:
import gpu
return f"{gpu.platform.vendor_get()} {gpu.platform.renderer_get()}".strip()
- except Exception: # noqa: BLE001 — no GL context (Cycles) is not an error
+ except Exception: # noqa: BLE001
return ""
@@ -305,7 +258,7 @@ def main() -> int:
result.update(setup_render(scene, job))
aspect = float(job["width"]) / float(job["height"])
times = sorted({float(t) for t in job.get("times") or [0.0]})
- scene.frame_set(frame_of(times[0], scene)) # evaluated poses (constraints, keyframed cameras) at the first time
+ scene.frame_set(frame_of(times[0], scene))
specs: list[dict[str, Any]] = []
if job.get("authored", True):
specs += [authored_spec(o, aspect, times) for o in authored_cameras(scene)]
@@ -340,7 +293,7 @@ def main() -> int:
t0 = time.perf_counter()
try:
bpy.ops.render.render(write_still=True)
- except Exception as e: # noqa: BLE001 — one failed frame must not cost the others
+ except Exception as e: # noqa: BLE001
result["errors"].append(f"render failed for '{s['name']}' at t={t:g}: {type(e).__name__}: {e}"[:600])
continue
finally:
diff --git a/harness/codeverse3d/languages/wrappers/run_bpy.py b/harness/codeverse3d/languages/wrappers/run_bpy.py
index 21338e21..9ef53892 100644
--- a/harness/codeverse3d/languages/wrappers/run_bpy.py
+++ b/harness/codeverse3d/languages/wrappers/run_bpy.py
@@ -1,28 +1,12 @@
-"""Blender build wrapper — executed BY Blender, never imported by the harness.
+"""Blender build wrapper; runs inside Blender, never imported by the harness.
blender -b --factory-startup --python run_bpy.py -- \
- --script /abs/src/model.py --out /abs/artifacts [--stl] [--blend] \
- [--rlimit-gb 12] [--seed 0]
-
-What it does (in order):
- 1. caps the address space (RLIMIT_AS) so geometry bombs die in-process;
- 2. empties the factory scene (Cube/Camera/Light + orphan data), sets metric units;
- 3. seeds ``random`` / numpy / mathutils.noise;
- 4. runs the agent's ``model.py`` with ``<ws>/src`` on ``sys.path`` (so ``from
- parts.seat import build_seat`` and ``import parts.seat`` work) and maps any
- exception to ``<file under src/>:<line>`` (model.py or a part file);
- 5. collects a census (``_census.py``: evaluated tri counts, world bboxes, materials, parents);
- 6. warns on leftovers (cameras, lights, touched render settings, visible cutters);
- 7. refuses a NaN / inf world matrix or evaluated vertex in what it would export (``_finite``,
- D114: the glTF exporter drops a NaN translation silently) as the script's error;
- 8. exports ``object.glb`` (Y-up, +Z front), optionally ``object.stl`` (Z-up) and ``object.blend``
- (in-memory images packed first: :func:`save_blend`);
- 9. writes ``build.json`` + ``census.json`` atomically and exits 0.
-
-Exit codes: 0 = reported (even if the script failed); 2 = wrapper bug (no report).
-Standalone: Blender's python cannot import ``codeverse3d``; the sibling modules
-(``_wrapper_common``, ``_census``) are imported from this file's own directory.
-"""
+ --script /abs/src/model.py --out /abs/artifacts [--stl] [--blend] [--rlimit-gb 12] [--seed 0]
+
+Caps memory, clears the factory scene, seeds RNGs, runs the agent's ``model.py`` with ``<ws>/src``
+on ``sys.path``, collects the census and contract warnings, refuses non-finite geometry, exports
+``object.glb`` (+ optional stl / blend) and writes ``build.json`` + ``census.json``.
+Exit 0 = reported (even if the script failed); 2 = wrapper bug."""
from __future__ import annotations
@@ -35,7 +19,7 @@ import traceback
from typing import Any
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
-from _census import collect_census, is_hidden # noqa: E402 (siblings, Blender-executed)
+from _census import collect_census, is_hidden # noqa: E402
from _finite import Offenders, scan_objects # noqa: E402
from _wrapper_common import ( # noqa: E402
PARTS_PKG,
@@ -69,7 +53,6 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
# ----------------------------------------------------------------------------- scene prep
def clear_scene(bpy: Any) -> None:
- """Remove every object + datablock of the factory scene; keep scene/world."""
for obj in list(bpy.data.objects):
bpy.data.objects.remove(obj, do_unlink=True)
for coll in list(bpy.data.collections):
@@ -77,11 +60,10 @@ def clear_scene(bpy: Any) -> None:
for attr in ("meshes", "materials", "cameras", "lights", "curves", "images", "node_groups", "textures"):
block = getattr(bpy.data, attr)
for item in list(block):
- with contextlib.suppress(RuntimeError): # data still used by a linked library
+ with contextlib.suppress(RuntimeError):
block.remove(item)
scene = bpy.context.scene
- # removing "Collection" leaves the view layer's active collection dangling → bpy.context.collection
- # would be None; point it back at the scene master collection so `.objects.link()` works.
+ # removing "Collection" leaves the active collection dangling; point it at the master collection
bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection
scene.unit_settings.system = "METRIC"
scene.unit_settings.scale_length = 1.0
@@ -100,7 +82,6 @@ def render_fingerprint(bpy: Any) -> dict[str, Any]:
# ----------------------------------------------------------------------------- errors
def import_hint(exc: BaseException, src_dir: str) -> str:
- """Extra guidance for the two import mistakes a multi-file model makes."""
msg = str(exc)
if isinstance(exc, ModuleNotFoundError) and (f"'{PARTS_PKG}." in msg or f"'{PARTS_PKG}'" in msg):
mod = msg.split("'")[1].split(".")[-1]
@@ -120,10 +101,10 @@ def script_error(exc: BaseException, script: str) -> dict[str, Any]:
def select_exportables(bpy: Any) -> list[Any]:
bpy.ops.object.select_all(action="DESELECT")
chosen = []
- vl_names = set(bpy.context.view_layer.objects.keys()) # same predicate as the census
+ vl_names = set(bpy.context.view_layer.objects.keys())
for obj in bpy.context.scene.objects:
if obj.type in EXPORT_TYPES and not is_hidden(obj, vl_names):
- with contextlib.suppress(RuntimeError): # not in the view layer (excluded collection)
+ with contextlib.suppress(RuntimeError):
obj.select_set(True)
chosen.append(obj)
if chosen:
@@ -132,7 +113,6 @@ def select_exportables(bpy: Any) -> list[Any]:
def export_glb(bpy: Any, path: str) -> None:
- """Kwargs verified on Blender 5.2.2 LTS (io_scene_gltf2; the offline suite exercises this call)."""
bpy.ops.export_scene.gltf(
filepath=path,
export_format="GLB",
@@ -144,8 +124,6 @@ def export_glb(bpy: Any, path: str) -> None:
export_image_format="AUTO",
export_cameras=False,
export_lights=False,
- # a keyframed object becomes a glTF clip the scene loops (scene heroes, 2026-09-07);
- # an object nobody keyframed exports exactly as before
export_animations=True,
export_frame_range=True,
export_extras=False,
@@ -155,25 +133,21 @@ def export_glb(bpy: Any, path: str) -> None:
def export_stl(bpy: Any, path: str) -> None:
- """The native exporter (forward 'Y' default, Z-up); Blender 5.2 LTS only (D104)."""
bpy.ops.wm.stl_export(filepath=path, export_selected_objects=True, apply_modifiers=True, ascii_format=False, global_scale=1.0)
def pack_images(bpy: Any) -> list[str]:
- """Pack every image the script made or changed IN MEMORY (``bpy.data.images.new`` + ``pixels``:
- ``is_dirty``) into the .blend — 8-bit as PNG, float as OpenEXR — and return their names. Unpacked,
- the reopened file regenerates such an image blank: every material using it renders black (D114;
- an untouched generated image regenerates itself and is left alone)."""
+ """Pack every image the script generated in memory into the .blend (8-bit PNG, float OpenEXR);
+ unpacked, the reopened file regenerates it blank. Returns their names."""
packed = []
for img in bpy.data.images:
- if img.source != "VIEWER" and img.is_dirty: # a generated image's type is UV_TEST, not IMAGE
+ if img.source != "VIEWER" and img.is_dirty:
img.pack()
packed.append(img.name)
return packed
def save_blend(bpy: Any, path: str, *, compress: bool = False) -> list[str]:
- """``pack_images`` + ``save_as_mainfile(copy=True)``; returns the warnings (a failed pack)."""
warnings = []
try:
pack_images(bpy)
@@ -186,7 +160,7 @@ def save_blend(bpy: Any, path: str, *, compress: bool = False) -> list[str]:
# ----------------------------------------------------------------------------- main
def main() -> int:
args = parse_args(wrapper_argv())
- import bpy # noqa: PLC0415 — only available inside Blender
+ import bpy # noqa: PLC0415
out_dir = os.path.abspath(args.out)
os.makedirs(out_dir, exist_ok=True)
@@ -208,7 +182,6 @@ def main() -> int:
if exc is not None:
report.update(script_error(exc, script))
- # the script may have left edit mode / odd selection states behind
try:
if bpy.context.object and bpy.context.object.mode != "OBJECT":
bpy.ops.object.mode_set(mode="OBJECT")
@@ -225,7 +198,7 @@ def main() -> int:
bad = scan_objects(chosen, bpy.context.evaluated_depsgraph_get(), Offenders())
if bad:
report.update(bad.report())
- chosen = [] # nothing exported: a NaN would ship as an object at the origin
+ chosen = []
if chosen:
glb = os.path.join(out_dir, GLB_NAME)
try:
diff --git a/harness/codeverse3d/languages/wrappers/run_bpy_links.py b/harness/codeverse3d/languages/wrappers/run_bpy_links.py
index b5679c93..bf6c24b7 100644
--- a/harness/codeverse3d/languages/wrappers/run_bpy_links.py
+++ b/harness/codeverse3d/languages/wrappers/run_bpy_links.py
@@ -1,22 +1,11 @@
-"""Blender-side build wrapper for the ``urdf_blender`` language (run BY THE HARNESS).
+"""Blender-side build wrapper for the ``urdf_blender`` language; runs inside Blender, never imported by the harness.
blender -b --factory-startup --python run_bpy_links.py -- \
--script src/model.py --urdf src/robot.urdf --out artifacts/ [--rlimit-gb 12] [--seed 0]
-1. empties the scene, seeds, executes ``model.py`` (``_wrapper_common``: errors mapped to
- their ``src/`` file and line, ``sys.exit(0)`` is not a failure — as for the blender language),
-2. takes the blender language's census of the scene (``_census.collect_census``),
- and fails a link whose world matrix or evaluated vertices hold a NaN / inf (``_finite``, D114),
-3. matches URDF link names to objects (an object named exactly ``<link>`` plus
- anything parented under it forms that link's mesh),
-4. exports ``<out>/meshes/<link>.glb`` per link with the geometry baked in WORLD
- coordinates at the authored rest pose, Z-up (``export_yup=False`` — the file
- holds URDF-frame coordinates, NOT glTF Y-up), then
-5. writes ``<out>/census.json`` and ``<out>/build.json``.
-
-Self-contained on purpose: Blender's bundled python cannot import ``codeverse3d``; the
-sibling modules are imported from this file's own directory.
-"""
+Runs ``model.py``, takes the census, refuses non-finite links, matches URDF link names to objects
+(``<link>`` plus anything parented under it), exports ``<out>/meshes/<link>.glb`` per link in
+WORLD coordinates at the rest pose, Z-up (URDF frame, not glTF Y-up), and writes census.json + build.json."""
import argparse
import os
@@ -30,7 +19,7 @@ import bpy
from mathutils import Matrix, Vector
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
-from _census import ( # noqa: E402 (siblings, Blender-executed)
+from _census import ( # noqa: E402
MEASURABLE_TYPES,
collect_census,
is_hidden,
@@ -54,15 +43,12 @@ def _snake(name: str) -> str:
return re.sub(r"_+", "_", s).strip("_").lower()
-#: link names double as ``meshes/<link>.glb`` filename stems: plain identifiers only.
-#: The lint layer states the same rule (``conventions.LINK_NAME_RE``) but only WARNs,
-#: so the wrapper enforces it — ``../evil`` must be a build error, never a file written
-#: outside ``meshes/``.
+#: link names are used as ``meshes/<link>.glb`` stems; the lint only WARNs, so the wrapper
+#: enforces plain identifiers (``../evil`` must be a build error)
_SAFE_LINK = re.compile(r"[A-Za-z][A-Za-z0-9_]*")
def _bad_links(links: list[str]) -> list[str]:
- """Link names that are unsafe as filenames (not plain identifiers)."""
return [name for name in links if not _SAFE_LINK.fullmatch(name or "")]
@@ -72,7 +58,6 @@ def _urdf_links(urdf_path: Path) -> list[str]:
def _evaluated_world_mesh(ob, depsgraph):
- """New bpy Mesh datablock of ``ob`` (modifiers applied) in WORLD coordinates."""
ev = ob.evaluated_get(depsgraph)
me = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph)
me.transform(ob.matrix_world)
@@ -80,7 +65,6 @@ def _evaluated_world_mesh(ob, depsgraph):
def _export_link(link: str, objects: list, out_glb: Path, depsgraph) -> dict:
- """Join ``objects`` (world space) into one temp object and export it as GLB."""
meshes = [_evaluated_world_mesh(ob, depsgraph) for ob in objects]
temp_objs = []
for i, me in enumerate(meshes):
@@ -153,8 +137,7 @@ def main() -> int:
census.update(collect_census(bpy))
depsgraph = bpy.context.evaluated_depsgraph_get()
by_name = {ob.name: ob for ob in bpy.data.objects if ob.type in MEASURABLE_TYPES or ob.type == "EMPTY"}
- # a hidden object (a boolean cutter, as the census tells agents to hide one) is not
- # geometry: the blender language's export skips it by the same predicate
+ # hidden objects (boolean cutters) are not geometry; same predicate as the blender language
vl_names = set(bpy.context.view_layer.objects.keys())
claimed: set[str] = set()
for link in links:
@@ -171,12 +154,12 @@ def main() -> int:
census["hints"][link] = f"object '{link}' has no visible mesh geometry (type {ob.type})"
continue
claimed.update(o.name for o in group)
- if bad := scan_objects(group, depsgraph, Offenders()): # D114: never a NaN baked into a link mesh
+ if bad := scan_objects(group, depsgraph, Offenders()):
err = bad.report()
return fail(err["error_type"], f"link {link}: {err['error_message']}")
try:
census["links"][link] = _export_link(link, group, out / "meshes" / f"{link}.glb", depsgraph)
- except Exception as e: # export failure is a build failure
+ except Exception as e:
return fail("ExportError", f"link {link}: {e}")
census["unmatched_objects"] = [o["name"] for o in census["objects"]
if o["type"] in MEASURABLE_TYPES and not o["hidden"] and o["name"] not in claimed]
diff --git a/harness/codeverse3d/languages/wrappers/run_bpy_scene.py b/harness/codeverse3d/languages/wrappers/run_bpy_scene.py
index e80294b5..91fc6a9e 100644
--- a/harness/codeverse3d/languages/wrappers/run_bpy_scene.py
+++ b/harness/codeverse3d/languages/wrappers/run_bpy_scene.py
@@ -1,33 +1,14 @@
-"""Blender SCENE build wrapper (scene_blender) — executed BY Blender, never imported by the harness.
+"""Blender SCENE build wrapper (scene_blender); runs inside Blender, never imported by the harness.
blender -b --factory-startup --python run_bpy_scene.py -- \
--scene /abs/src/scene.py --out /abs/artifacts --basis 1,0,0,0,0,1,0,-1,0 --zone-key c3d_zone \
[--fps 30] [--frames 1,46] [--rlimit-gb 12] [--seed 0] [--zones '{"a": "A"}'] [--no-blend]
-What it does (in order), DESIGN §3.3:
- 1. caps the address space, empties the factory scene (and its world), metric units, ``fps`` and
- the frame range (harness-owned), seeds ``random`` / numpy / mathutils.noise;
- 2. runs ``src/scene.py`` (assembled by the harness: ``ZONES`` / ``ASSETS`` / ``HEROES`` /
- ``CAMERAS`` data; a single-file scene defines ``create_scene(ctx)`` instead) — a failure here
- is the build's error, mapped to ``src/<file>:<line>``;
- 3. builds the ctx (``SceneContext``) and runs, EACH IN ITS OWN try/except, ``env.build_env``,
- every hero import (``public/assets/<snake>.glb``), every ``assets.<snake>.build_<snake>`` and
- every ``zones.<snake>.build``: a stage that raises is reported with its ``file:line`` and
- whatever it created is removed — the zone is DROPPED, the rest of the scene still builds and
- is measured (the assembler's probe semantics);
- 4. hides the asset sources (they render through their collection instances), creates the
- harness cameras (plan fov is VERTICAL, as in three.js), sets frame 1 (t = 0);
- 5. writes the bpy facts the GLB cannot carry (``bpy_census.json``: lights, fog, background,
- drivers that will not run, unique vs instanced triangles), the census GLB (``_census_glb``;
- a NaN / inf matrix or vertex fails the build as ``NonFiniteTransform`` / ``NonFiniteGeometry``
- naming the object and the file that built it — the model's error, D114) and the compressed
- ``scene.blend`` the render driver opens (in-memory images packed: ``run_bpy.save_blend``);
- 6. writes ``bpy_build.json`` and exits 0.
-
-``--zones`` overrides ``ZONES`` (the assembler's probe: every zone module on disk). Exit codes: 0 =
-reported (even if the script failed); 2 = wrapper bug (no report). Standalone: the sibling modules
-are imported from this file's own directory.
-"""
+Clears the factory scene, runs ``src/scene.py``, then builds env, heroes, assets and zones, each
+in its own try/except (a failing zone is reported with ``file:line`` and dropped; the rest still
+builds). Hides asset sources, creates the harness cameras, writes the bpy facts, the census GLB,
+the compressed ``scene.blend`` and ``bpy_build.json``. ``--zones`` overrides ``ZONES``.
+Exit 0 = reported (even if the script failed); 2 = wrapper bug."""
from __future__ import annotations
@@ -43,7 +24,7 @@ import time
from typing import Any
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
-from _census_glb import ( # noqa: E402 (siblings)
+from _census_glb import ( # noqa: E402
is_volume_material,
is_volume_only,
write_census_glb,
@@ -84,13 +65,10 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
class SceneContext:
- """What ``build_env`` / ``build_<asset>`` / zone ``build`` receive (DESIGN §3.2): data, never verbs.
+ """What ``build_env`` / ``build_<asset>`` / zone ``build`` receive: data, never verbs.
- ``scene`` the bpy Scene (render settings are harness-owned) · ``collection`` the Collection this
- builder links into (the zone's own, pre-created and active) · ``height_at(x, y) -> z`` the
- env's ground · ``env`` what ``build_env`` returned · ``assets`` ``{snake: Collection}`` (procedural
- assets and imported heroes) · ``rng(seed)`` the only randomness · ``fps`` / ``times`` the
- harness's frame clock: ``frame(t) = 1 + round(t * fps)``."""
+ ``scene``, ``collection`` (the builder's own, active), ``height_at(x, y)``, ``env``, ``assets``,
+ ``rng(seed)``, ``fps`` / ``times`` (``frame(t) = 1 + round(t * fps)``)."""
def __init__(self, scene: Any, fps: int, times: tuple[float, ...]) -> None:
self.scene = scene
@@ -116,7 +94,7 @@ def _flat(x: float, y: float) -> float:
# ----------------------------------------------------------------------------- scene prep
def prepare_scene(bpy: Any, fps: int, frames: tuple[int, int]) -> None:
clear_scene(bpy)
- for world in list(bpy.data.worlds): # a scene's world is the env's to build (no factory grey)
+ for world in list(bpy.data.worlds):
bpy.data.worlds.remove(world)
scene = bpy.context.scene
scene.render.fps = fps
@@ -148,23 +126,20 @@ def new_collection(bpy: Any, name: str, parent: Any) -> Any:
def activate(bpy: Any, coll: Any) -> None:
- """Make ``coll`` the active collection, so ``bpy.ops`` primitives land in it."""
lc = layer_collection(bpy.context.view_layer, coll)
if lc is not None:
bpy.context.view_layer.active_layer_collection = lc
class Stages:
- """Runs one builder at a time; a raise is recorded with its ``src/`` file:line and everything
- the builder created is removed again (objects and collections). ``origin`` maps every object a
- builder that returned created (``as_pointer()``) to its file — a census report names it (D114)."""
+ """Runs one builder at a time; a raise is recorded with its ``src/`` file:line and what the
+ builder created is removed. ``origin`` maps created objects (``as_pointer()``) to their file."""
def __init__(self, bpy: Any, script: str, report: dict[str, Any]) -> None:
self.bpy, self.script, self.report = bpy, script, report
self.origin: dict[int, str] = {}
def claim(self, file: str, before: set[int]) -> None:
- """Every object not in ``before`` (pointers) was made by ``file``."""
for o in self.bpy.data.objects:
if (p := o.as_pointer()) not in before:
self.origin.setdefault(p, file)
@@ -180,7 +155,7 @@ class Stages:
out = fn()
self.claim(default_file, objs)
return out, True
- except BaseException as e: # noqa: BLE001 — a builder's failure is a finding, never the wrapper's
+ except BaseException as e: # noqa: BLE001
if isinstance(e, KeyboardInterrupt):
raise
info = map_exception(e, self.script, memory=MEMORY_HINT)
@@ -262,7 +237,6 @@ def build_assets(bpy: Any, ctx: SceneContext, stages: Stages, ws: str, heroes: d
def build_zones(bpy: Any, ctx: SceneContext, stages: Stages, zones: dict[str, str], report: dict[str, Any]) -> dict[str, str]:
- """Build every zone; returns ``{snake: collection name}`` of the zones that built."""
scene_coll = bpy.context.scene.collection
built: dict[str, str] = {}
for snake, pascal in zones.items():
@@ -293,23 +267,22 @@ def build_zones(bpy: Any, ctx: SceneContext, stages: Stages, zones: dict[str, st
def add_cameras(bpy: Any, cams: list[dict[str, Any]], report: dict[str, Any]) -> None:
- from mathutils import Vector # noqa: PLC0415 — Blender-only
+ from mathutils import Vector # noqa: PLC0415
coll = new_collection(bpy, CAMERAS_COLLECTION, bpy.context.scene.collection)
first = None
for c in cams:
data = bpy.data.cameras.new(str(c["name"]))
- data.sensor_fit = "VERTICAL" # the plan's fov is vertical, as three.js's PerspectiveCamera.fov
+ data.sensor_fit = "VERTICAL"
data.angle_y = math.radians(float(c.get("fov", 50.0)))
data.clip_start, data.clip_end = 0.05, 20000.0
ob = bpy.data.objects.new(str(c["name"]), data)
coll.objects.link(ob)
ob.location = Vector(c["location"])
ob.rotation_euler = (Vector(c["look_at"]) - ob.location).to_track_quat("-Z", "Y").to_euler()
- ob["c3d_look_at"] = [float(v) for v in c["look_at"]] # the render driver's aim (Blender frame)
+ ob["c3d_look_at"] = [float(v) for v in c["look_at"]]
report["cameras"].append({"name": str(c["name"]), "object": ob.name})
first = first or ob
- # the plan's camera order, by object name (the render driver reads it from the .blend)
bpy.context.scene["c3d_cameras"] = [c["object"] for c in report["cameras"]]
if first is not None:
bpy.context.scene.camera = first
@@ -342,7 +315,6 @@ def _volume_density(node: Any) -> float | None:
def _material_density(mat: Any) -> float | None:
- """The density of the volume shader a volume material outputs (``None`` when unreadable)."""
tree = getattr(mat, "node_tree", None) if mat is not None else None
out = next((n for n in tree.nodes if n.bl_idname == "ShaderNodeOutputMaterial"), None) if tree is not None else None
if out is None or not out.inputs["Volume"].is_linked:
@@ -351,7 +323,6 @@ def _material_density(mat: Any) -> float | None:
def _world_facts(world: Any) -> tuple[dict[str, Any] | None, str | None]:
- """(world-volume fog | None, background kind | None) of the scene's world."""
tree = getattr(world, "node_tree", None) if world is not None else None
if tree is None:
return None, None
@@ -380,8 +351,7 @@ def _world_facts(world: Any) -> tuple[dict[str, Any] | None, str | None]:
def _drivers(bpy: Any) -> list[dict[str, Any]]:
- """Drivers that will not evaluate here: a Python (non-simple) expression — silently 0 under
- ``--factory-startup`` (DESIGN §1.1) — or one Blender reports invalid (D10)."""
+ """Drivers that will not evaluate here: Python expressions (silently 0 under ``--factory-startup``) or invalid ones."""
out: list[dict[str, Any]] = []
blocks = [("object", bpy.data.objects), ("material", bpy.data.materials), ("node_group", bpy.data.node_groups),
("world", bpy.data.worlds), ("shape_key", bpy.data.shape_keys), ("mesh", bpy.data.meshes),
@@ -402,15 +372,12 @@ def _drivers(bpy: Any) -> list[dict[str, Any]]:
def handler_counts(bpy: Any) -> dict[str, int]:
- """``{handler list: length}`` — Blender's own add-ons register some at startup, so what the
- scene added is what grew."""
+ """``{handler list: length}``; add-ons register some at startup, so only growth counts."""
return {name: len(getattr(bpy.app.handlers, name)) for name in dir(bpy.app.handlers)
if not name.startswith("_") and isinstance(getattr(bpy.app.handlers, name), list)}
def scene_facts(bpy: Any, handlers_before: dict[str, int]) -> dict[str, Any]:
- """What only Blender knows (DESIGN §4.2): the keys the JS census fills for three.js
- (``fog`` / ``background`` / ``environment`` / lights) plus drivers, handlers and triangles."""
dg = bpy.context.evaluated_depsgraph_get()
light_types: dict[str, int] = {}
unique: dict[Any, int] = {}
@@ -426,7 +393,7 @@ def scene_facts(bpy: Any, handlers_before: dict[str, int]) -> dict[str, Any]:
if ob.type not in ("MESH", "CURVE", "SURFACE", "FONT", "META") or (inst.is_instance and ob.type != "MESH"):
continue
if inst.is_instance and inst.parent is not None and inst.parent.original.type in ("CURVE", "SURFACE", "FONT", "META"):
- continue # a curve / text's own evaluated mesh component (counted from the owner; _census_glb skips it too)
+ continue
src = ob if inst.is_instance else ob.original
if is_volume_only(src):
if not inst.is_instance:
@@ -461,7 +428,7 @@ def scene_facts(bpy: Any, handlers_before: dict[str, int]) -> dict[str, Any]:
# ----------------------------------------------------------------------------- main
def main() -> int:
args = parse_args(wrapper_argv())
- import bpy # noqa: PLC0415 — only available inside Blender
+ import bpy # noqa: PLC0415
out_dir = os.path.abspath(args.out)
os.makedirs(out_dir, exist_ok=True)
@@ -483,7 +450,7 @@ def main() -> int:
purge_workspace_modules()
t_exec = time.monotonic()
- exc, g = run_script(script) # src/ goes first on sys.path: `import env`, `zones.<snake>` resolve there
+ exc, g = run_script(script)
if exc is not None:
report.update(map_exception(exc, script, memory=MEMORY_HINT))
report["exec_ms"] = int((time.monotonic() - t_exec) * 1000)
@@ -495,10 +462,10 @@ def main() -> int:
zones = {str(k): str(v) for k, v in json.loads(args.zones).items()}
ctx = SceneContext(bpy.context.scene, args.fps, tuple(float(t) for t in g.get("TIMES", (0.0, 1.5))))
stages = Stages(bpy, script, report)
- stages.claim("src/scene.py", set()) # what the entry's own top-level code made
+ stages.claim("src/scene.py", set())
build_env(bpy, ctx, stages, src)
assets_root = build_assets(bpy, ctx, stages, ws, dict(g.get("HEROES") or {}), dict(g.get("ASSETS") or {}), report)
- if callable(g.get("create_scene")): # single-file mode: one scene.py builds everything
+ if callable(g.get("create_scene")):
activate(bpy, bpy.context.scene.collection)
ctx.collection = bpy.context.scene.collection
stages.run("scene", "create_scene", "src/scene.py", lambda: g["create_scene"](ctx))
@@ -510,12 +477,12 @@ def main() -> int:
bpy.ops.object.mode_set(mode="OBJECT")
lc = layer_collection(bpy.context.view_layer, assets_root)
if lc is not None:
- lc.exclude = True # sources at the origin render only through their instances
+ lc.exclude = True
add_cameras(bpy, list(g.get("CAMERAS") or []), report)
if render_fingerprint(bpy) != render_before:
report["warnings"].append("the scene changed render settings (engine/resolution/filepath/frames): "
"the harness owns them; delete that code")
- bpy.context.scene.frame_set(first) # the census is the t = 0 pose
+ bpy.context.scene.frame_set(first)
facts = scene_facts(bpy, handlers_before)
basis = [[float(v) for v in args.basis.split(",")[i * 3:i * 3 + 3]] for i in range(3)]
@@ -524,9 +491,9 @@ def main() -> int:
zones={name: name for name in built.values()}, cameras=list(g.get("CAMERAS") or []),
zone_key=args.zone_key, origin=stages.origin_of)
report["exported"]["glb"] = os.path.join(out_dir, GLB_NAME)
- except NonFiniteError as e: # the scene's NaN / inf, not the writer's: the model's build error (D114)
+ except NonFiniteError as e:
report.update(e.offenders.report())
- except Exception as e: # noqa: BLE001 — a writer failure is the harness's, reported as such
+ except Exception as e: # noqa: BLE001
import traceback # noqa: PLC0415
report.update(error_type="CensusGlbError", error_message=f"census GLB writer failed: {e}",
@@ -534,7 +501,7 @@ def main() -> int:
if not args.no_blend:
blend = os.path.join(out_dir, BLEND_NAME)
try:
- report["warnings"].extend(save_blend(bpy, blend, compress=True)) # the judged frames render it
+ report["warnings"].extend(save_blend(bpy, blend, compress=True))
report["exported"]["blend"] = blend
except Exception as e: # noqa: BLE001
report["warnings"].append(f".blend save failed: {e}")
diff --git a/harness/codeverse3d/languages/wrappers/run_cq.py b/harness/codeverse3d/languages/wrappers/run_cq.py
index 146eeb04..fae46da2 100644
--- a/harness/codeverse3d/languages/wrappers/run_cq.py
+++ b/harness/codeverse3d/languages/wrappers/run_cq.py
@@ -1,16 +1,11 @@
-"""CadQuery build wrapper — run by the harness in a subprocess, never imported.
+"""CadQuery build wrapper; run by the harness in a subprocess, never imported.
python run_cq.py --script /abs/src/model.py --out /abs/artifacts \
[--rlimit-gb 8] [--tolerance 0.001] [--angular-tolerance 0.15] [--seed 0]
-Steps: RLIMIT_AS → seed → exec model.py with traceback→line mapping (``_wrapper_common``,
-shared with the Blender wrappers) → read the module-level ``result`` (cq.Assembly
-preferred, or Workplane / Shape) → tessellate each part (world location applied) →
-``object.glb`` (Y-up, +Z front, named nodes, PBR base colour from cq.Color) +
-``object.step`` + ``object.stl`` → ``census.json`` + ``build.json`` (atomic). Exit 0
-whenever a report was written; 2 on wrapper bugs. Standalone: imports cadquery / numpy /
-trimesh and its sibling ``_wrapper_common`` only (never ``codeverse3d``).
-"""
+Runs ``model.py``, reads its module-level ``result`` (Assembly, Workplane or Shape), tessellates
+each part and writes ``object.glb`` (Y-up, +Z front), ``.step``, ``.stl``, ``census.json`` and
+``build.json``. Exit 0 whenever a report was written; 2 on a wrapper bug. Standalone."""
from __future__ import annotations
@@ -22,7 +17,7 @@ import time
from typing import Any
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
-from _wrapper_common import ( # noqa: E402 (sibling module)
+from _wrapper_common import ( # noqa: E402
exit_after,
map_exception,
new_report,
@@ -51,12 +46,10 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
def entry_relative(script_path: str) -> str:
- """``src/model.py`` for the entry script itself."""
return src_relative(script_path, os.path.dirname(os.path.abspath(script_path))) or os.path.basename(script_path)
def occ_hint(exc: BaseException) -> str:
- """What an OCC kernel refusal usually means, appended to its message."""
if "BRep_API: command not done" in str(exc) or "StdFail_NotDone" in type(exc).__name__:
return (" — OCC kernel refused the operation: fillet/chamfer radius >= adjacent wall/face size, conflicting "
"adjacent fillets, or degenerate geometry. Clamp radii (< 0.45 x min thickness), select fewer edges, "
@@ -70,12 +63,8 @@ def script_error(exc: BaseException, script: str) -> dict[str, Any]:
# ----------------------------------------------------------------------------- parts
def _as_shape(cq: Any, obj: Any, warnings: list[str] | None = None, label: str = "result") -> Any:
- """Workplane / Shape → one Shape (compound when several solids).
-
- A Workplane whose stack holds only Faces/Edges/Wires/Vertices (a trailing selector such
- as ``.faces(">Z")``) is NOT exported as a sheet: the solid it was selected from is used
- (``findSolid``) with a warning, or an error names the stack types when there is none.
- """
+ """Workplane / Shape -> one Shape. A stack of only Faces/Edges/Wires/Vertices falls back to
+ its source solid (``findSolid``) with a warning, or errors naming the stack types."""
if isinstance(obj, cq.Workplane):
vals = [v for v in obj.vals() if isinstance(v, cq.Shape)]
if not vals:
@@ -84,7 +73,7 @@ def _as_shape(cq: Any, obj: Any, warnings: list[str] | None = None, label: str =
kinds = sorted({type(v).__name__ for v in vals})
try:
solid = obj.findSolid(searchStack=True, searchParents=True)
- except Exception as e: # noqa: BLE001 — ValueError from cadquery; anything else is equally "no solid"
+ except Exception as e: # noqa: BLE001
raise ValueError(f"{label}: Workplane stack holds only {'/'.join(kinds)} objects, not a Solid — "
f"end the chain with a solid (.extrude()/.box()/.revolve(); drop the trailing selector) [{e}]") from e
if warnings is not None:
@@ -98,7 +87,6 @@ def _as_shape(cq: Any, obj: Any, warnings: list[str] | None = None, label: str =
def flatten_assembly(cq: Any, assy: Any, warnings: list[str] | None = None) -> list[dict[str, Any]]:
- """Depth-first leaves: {name, shape (world-located), rgba, path}."""
out: list[dict[str, Any]] = []
def walk(node: Any, parent_loc: Any, parent_rgba: Any, path: list[str]) -> None:
@@ -139,7 +127,7 @@ def part_census(part: dict[str, Any], n_tris: int) -> dict[str, Any]:
rec["volume_m3"] = round(float(shape.Volume()), 9)
rec["n_solids"] = len(shape.Solids())
rec["valid"] = bool(shape.isValid())
- except Exception as e: # noqa: BLE001 — census must not kill the build
+ except Exception as e: # noqa: BLE001
rec["census_error"] = str(e)
return rec
@@ -199,7 +187,7 @@ def main() -> int:
t0 = time.monotonic()
report = new_report(args.rlimit_gb)
seed_everything(args.seed)
- import cadquery as cq # noqa: PLC0415 — after the rlimit, before the script
+ import cadquery as cq # noqa: PLC0415
script = os.path.abspath(args.script)
err: dict[str, Any] | None = None
@@ -247,7 +235,7 @@ def main() -> int:
build_glb(meshes, glb)
report["exported"]["glb"] = glb
export_step_stl(cq, ns["result"], parts, out_dir, args.tolerance, args.angular_tolerance, report)
- except Exception as e: # noqa: BLE001 — export-time failure in agent geometry
+ except Exception as e: # noqa: BLE001
err = script_error(e, script)
if not err["error_file"]:
err["error_type"], err["error_message"] = "ExportError", f"{type(e).__name__}: {e}"
diff --git a/harness/codeverse3d/models/anthropic.py b/harness/codeverse3d/models/anthropic.py
index 22826e9e..e403084d 100644
--- a/harness/codeverse3d/models/anthropic.py
+++ b/harness/codeverse3d/models/anthropic.py
@@ -1,14 +1,8 @@
"""ChatRequest ⇄ Anthropic Messages API dicts (messages, submit tool, thinking, parse).
-Model-family rules (Anthropic API, 2026-10):
-* 4.6+ family (opus-5/5.5, sonnet-5/5.5, haiku-5.5, fable-5/5.1, mythos, opus-4-6/7/8,
- sonnet-4-6): ``thinking={"type":"adaptive"}`` + ``output_config.effort``;
- ``budget_tokens`` is rejected; sampling params are rejected on opus-5/sonnet-5/haiku-5/
- fable/4.7/4.8. Fable, Mythos, Opus 5.5 and Sonnet 5.5 cannot turn thinking off
- (``disabled`` is a 400) and reject a forced ``tool_choice``: "off" is effort ``low``.
-* older models (haiku-4-5, sonnet-4-5, opus-4-1 …): ``thinking={"type":
- "enabled","budget_tokens":N}`` (N < max_tokens), temperature must be left
- at default while thinking is on.
+Adaptive-thinking models take ``thinking={"type":"adaptive"}`` + ``output_config.effort``;
+some always think (``disabled`` is a 400) and reject a forced ``tool_choice``, so "off" is
+effort ``low``. Older models take ``budget_tokens`` (< max_tokens) and need default temperature.
"""
from __future__ import annotations
@@ -144,7 +138,7 @@ def build_kwargs(request: ChatRequest, model: str) -> dict[str, Any]:
if not thinking_on:
kw["tool_choice"] = {"type": "tool", "name": SUBMIT_TOOL}
else:
- # forced tool_choice is incompatible with thinking; nudge instead
+ # forced tool_choice is incompatible with thinking
system = (
(system + "\n\n" if system else "")
+ f"When you have the final answer, call the `{SUBMIT_TOOL}` tool exactly once with the complete JSON object."
@@ -174,7 +168,7 @@ def parse_content(content: list[Any]) -> tuple[str, Any]:
# ===================================================================== anthropic
def classify_exception(exc: BaseException) -> ModelError:
- """Map anthropic SDK exceptions onto ``ModelError`` (the shared ladder in parts.py)."""
+ """Map anthropic SDK exceptions onto ``ModelError``."""
import anthropic
return classify_sdk_exception(exc, anthropic, "Anthropic")
@@ -205,7 +199,6 @@ class AnthropicModel(SdkModel):
def _once(self, kwargs: dict[str, Any], request: ChatRequest, deadline: float) -> ChatResponse:
client = self.client()
with Stopwatch() as sw:
- # the client is built once with a fixed timeout; the deadline is per call
msg = client.messages.create(
model=self.model, timeout=attempt_timeout_s(deadline, self.timeout_s), **kwargs)
text, submit = parse_content(msg.content)
@@ -219,12 +212,7 @@ class AnthropicModel(SdkModel):
parsed: Any = None
if request.response_schema is not None:
if submit is not None:
- # The SDK hands back tool input already parsed, so it never passes through
- # parse_json_lenient -> strip_control_chars the way the gemini/openai text
- # paths do. A model NUL in a `submit` field would otherwise survive into
- # plan.json and detonate stages later at subprocess.Popen ("embedded null
- # byte"): the identical failure strip_control_chars was written to end, and
- # sanitising at ingestion is the only place that covers every model.
+ # tool input skips parse_json_lenient; strip NULs here or they reach subprocess.Popen
parsed = strip_control_chars(submit)
if not text:
text = json.dumps(parsed)
diff --git a/harness/codeverse3d/models/base.py b/harness/codeverse3d/models/base.py
index 49570028..26554009 100644
--- a/harness/codeverse3d/models/base.py
+++ b/harness/codeverse3d/models/base.py
@@ -30,13 +30,8 @@ class ChatModel(Protocol):
class ModelError(RuntimeError):
- """A model call failed. ``attempts`` is how many round-trips the retry machine
- issued before giving up (0 = unknown / not a retried call); the cost ledger
- records it on the error row (``docs/COST.md`` §24). ``usage`` is what the
- provider ALREADY billed for the failed call — a bad-JSON reply is charged like
- a good one — so the ledger and the key pool's TPM accounting can see real
- consumption instead of assuming a failure was free (mirrors
- ``tracks.planner.PlanningError.usage``); empty when nothing was billed."""
+ """A model call failed. ``attempts`` = round-trips issued (0 = unknown); ``usage`` =
+ what the provider already billed for the failed call (empty when nothing was)."""
def __init__(
self,
diff --git a/harness/codeverse3d/models/gemini.py b/harness/codeverse3d/models/gemini.py
index 37d7cd17..6b678086 100644
--- a/harness/codeverse3d/models/gemini.py
+++ b/harness/codeverse3d/models/gemini.py
@@ -1,11 +1,5 @@
-"""The whole Gemini stack in one module (merged 2026-08-28, d512ccc):
-
-* conversion — ``ChatRequest`` ⇄ google-genai types (``to_contents``, ``build_config``,
- ``extract_candidate``, ``parse_usage``); pure, unit-testable offline;
-* ``GeminiModel`` — the ``ChatModel``: a shared ``KeyPool`` over the configured keys,
- ``rotate_with_retries`` with the hedge, streaming with stall detection, per-attempt
- ledger rows;
-"""
+"""Gemini backend: ``ChatRequest`` ⇄ google-genai conversion, and ``GeminiModel`` (shared
+``KeyPool``, ``rotate_with_retries`` with hedge, streaming with stall detection, per-attempt ledger rows)."""
from __future__ import annotations
@@ -45,12 +39,12 @@ from codeverse3d.models.pricing import estimate_cost
from codeverse3d.models.retry import KeyPool, KeyPoolExhausted, OnAttempt, _Try, rotate_with_retries
from codeverse3d.models.schema_utils import JsonParseError, parse_json_lenient, to_gemini_schema
-#: thinking level → token budget; ``off`` → 0 where the model allows it
+#: thinking level → token budget
THINKING_BUDGET: dict[str, int] = {"off": 0, "low": 1024, "medium": 4096, "high": 16384}
-#: finish reasons that are worth one more attempt (transient model glitches)
+#: finish reasons worth one more attempt
RETRYABLE_FINISH = {"RECITATION", "MALFORMED_FUNCTION_CALL", "OTHER", "UNEXPECTED_TOOL_CALL"}
-#: finish reasons that will not improve by retrying
+#: finish reasons retrying cannot fix
FATAL_FINISH = {"SAFETY", "PROHIBITED_CONTENT", "BLOCKLIST", "SPII", "IMAGE_SAFETY"}
@@ -68,7 +62,7 @@ def to_contents(messages: list[ChatMessage]) -> list[types.Content]:
parts: list[types.Part] = message_blocks(msg, text=lambda t: types.Part.from_text(text=t), image=_image_part)
if not parts:
continue
- # merge consecutive same-role turns (Gemini wants strict alternation)
+ # Gemini wants strict role alternation
if out and out[-1].role == role:
out[-1].parts.extend(parts) # type: ignore[union-attr]
else:
@@ -106,12 +100,7 @@ def build_config(
def clip_timeout(
config: types.GenerateContentConfig, timeout_ms: int
) -> types.GenerateContentConfig:
- """A copy of ``config`` whose per-request HTTP timeout is ``timeout_ms`` (the
- SAME object when it already matches — the common full-budget case allocates
- nothing). :func:`build_config` owns the initial ``timeout_ms``; this is the
- one sanctioned way to shorten it for a single attempt whose remaining retry
- budget is smaller than the configured read timeout
- (``GeminiModel._attempt_config``)."""
+ """``config`` with its HTTP timeout set to ``timeout_ms`` (same object if unchanged)."""
current = config.http_options.timeout if config.http_options is not None else None
if current == timeout_ms:
return config
@@ -134,8 +123,7 @@ def parse_usage(resp: types.GenerateContentResponse, model: str) -> Usage:
def _guard_candidates(resp: types.GenerateContentResponse, usage: Usage | None, what: str) -> Any:
- """The first candidate, or the two billed failures every Gemini reply can carry:
- a blocked prompt (non-retryable) and no candidates at all (retryable)."""
+ """The first candidate, or a blocked-prompt (fatal) / no-candidates (retryable) error."""
pf = resp.prompt_feedback
if pf is not None and pf.block_reason:
raise ModelError(
@@ -150,10 +138,7 @@ def _guard_candidates(resp: types.GenerateContentResponse, usage: Usage | None,
def extract_candidate(
resp: types.GenerateContentResponse, usage: Usage | None = None
) -> tuple[str, str]:
- """→ ``(text, finish_reason)``. Raises ``ModelError`` on blocked
- prompts (non-retryable) or empty candidates (retryable); ``usage`` (what the caller
- already parsed off ``resp``) rides on the error, because every one of these
- failures was billed."""
+ """→ ``(text, finish_reason)``; raises ``ModelError`` carrying ``usage`` (these failures are billed)."""
cand = _guard_candidates(resp, usage, "Gemini")
finish = str(cand.finish_reason.value if cand.finish_reason else "") or "UNKNOWN"
texts: list[str] = []
@@ -167,10 +152,8 @@ def extract_candidate(
f"Gemini produced no content (finish_reason={finish})", retryable=False, usage=usage
)
if finish == "MAX_TOKENS":
- # Gemini 3 models always think (budget 0 is accepted but ignored); a tiny
- # max_output_tokens is eaten by thoughts. Retrying cannot help — and this is
- # the most expensive failure on Gemini 3: every thought token was billed. The
- # finish reason stays in the text: the planner's grow-the-budget retry keys on it.
+ # Gemini 3 always thinks; a small max_output_tokens is eaten by thoughts. The
+ # "finish_reason=MAX_TOKENS" text is matched by the planner's grow-the-budget retry.
thoughts = resp.usage_metadata.thoughts_token_count if resp.usage_metadata else None
raise ModelError(
f"Gemini produced no content (finish_reason=MAX_TOKENS): max_output_tokens exhausted by thinking "
@@ -187,15 +170,8 @@ log = logging.getLogger(__name__)
_RETRY_DELAY_RE = re.compile(r"retryDelay['\"]?\s*:\s*['\"]?(\d+(?:\.\d+)?)s")
-#: ceiling of the per-READ (inter-chunk) HTTP timeout under streaming. Five runs
-#: died tonight (drill/vise/clamp x2, one plan hang) because a hung NON-streaming
-#: read holds the socket for the whole attempt budget — up to model_timeout_s
-#: (1200 s) — and the timeout is then terminal. Streaming separates the two
-#: cases: a hung socket delivers no chunk and dies within this ceiling with the
-#: rest of the retry budget intact, while a legitimate 930 s plan streams tokens
-#: continuously (145 tok/s p50, audit 2026-08-27) and is bounded only by its
-#: attempt budget. Generous vs the longest silent prefix we allow for thinking
-#: before the first chunk. ``C3D_STREAM=off`` restores the buffered call.
+#: ceiling of the inter-chunk read timeout under streaming: a hung socket dies within it,
+#: while a long healthy stream is bounded only by its attempt budget (``C3D_STREAM=off`` buffers)
STREAM_STALL_S = 300.0
_pools: dict[tuple[str, ...], KeyPool] = {}
@@ -204,18 +180,15 @@ _registry_lock = threading.Lock()
def shared_pool(keys: list[str], *, max_in_flight: int | None = None) -> KeyPool:
- """One ``KeyPool`` per distinct (key list, in-flight cap) per process; an unset cap comes
- from ``Settings.rate.max_in_flight``. Its slots are machine-wide: every process draws
- from the same ``<cache_dir>/slots/gemini/NN.lock`` files (``retry.Slots``, COST §23)."""
+ """One ``KeyPool`` per (key list, in-flight cap) per process; slots are machine-wide
+ (``<cache_dir>/slots/gemini/NN.lock``)."""
cap = _rate().max_in_flight if max_in_flight is None else max_in_flight
sig = (*keys, f"|{cap}")
with _registry_lock:
pool = _pools.get(sig)
if pool is None:
slots = get_settings().cache_dir / "slots" / "gemini" if cap else None
- # a random first key: every process makes the same calls in the same order, so
- # parallel runs starting at key 0 all put their planner calls and agy sessions
- # on the same few keys (live, 2026-10-13: 4 parallel runs, one planner key)
+ # random first key, so parallel processes do not all start on key 0
pool = KeyPool(keys, max_in_flight=cap or 0, slots_dir=slots, start=random.randrange(len(keys)))
_pools[sig] = pool
return pool
@@ -237,7 +210,7 @@ def _keys_or_raise(keys: list[str] | None, pool: KeyPool | None) -> list[str]:
def _client_for(key: str, timeout_s: float, factory: Callable[[str], Any] | None) -> Any:
- """One ``genai.Client`` per (key, timeout), process-wide; ``factory`` (tests) bypasses the cache."""
+ """One ``genai.Client`` per (key, timeout), process-wide; ``factory`` bypasses the cache."""
if factory is not None:
return factory(key)
ck = (key, int(timeout_s * 1000))
@@ -274,11 +247,8 @@ def _retry_after_s(exc: BaseException) -> float | None:
def _ipv4_client_args() -> dict[str, Any]:
- """Bind the sync transport to IPv4. Every one of tonight's five hung reads sat
- on an IPv6 destination (2001:4860::/32) with the response headers never arriving
- — the WSL2 IPv6 path drops these silently and a buffered read then holds the
- socket for the whole attempt budget. ``C3D_IPV4=off`` restores the default
- (dual-stack) resolution."""
+ """Bind the sync transport to IPv4: the WSL2 IPv6 path silently hangs reads
+ (``C3D_IPV4=off`` restores dual-stack)."""
return {"transport": httpx.HTTPTransport(local_address="0.0.0.0")} if get_settings().ipv4 else {}
@@ -287,11 +257,8 @@ def _drain_stream(
deadline: float,
clock: Callable[[], float] = time.monotonic,
) -> list[types.GenerateContentResponse]:
- """Collect every chunk, enforcing the ATTEMPT budget between chunks. The wire
- timeout under streaming only bounds the silence BETWEEN chunks (httpx applies
- the read timeout per network read), so a healthy-but-endless stream is cut
- here instead. Tokens generated before the cut were billed but cannot be
- counted: usage_metadata only arrives on the final chunk."""
+ """Collect every chunk, enforcing the attempt ``deadline`` between chunks (the wire
+ timeout only bounds silence between chunks)."""
chunks: list[types.GenerateContentResponse] = []
for ch in it:
chunks.append(ch)
@@ -306,9 +273,8 @@ def _drain_stream(
def _merge_stream_chunks(
chunks: list[types.GenerateContentResponse],
) -> types.GenerateContentResponse:
- """One response out of a chunk sequence: parts concatenate in arrival order;
- finish_reason, usage_metadata and prompt_feedback come from the last chunk
- that carries each (usage is cumulative and final-chunk-only on this API)."""
+ """One response from a chunk sequence: parts concatenate; finish_reason, usage_metadata
+ and prompt_feedback come from the last chunk carrying each."""
if not chunks:
raise ModelError("Gemini stream yielded no chunks", retryable=True)
parts: list[types.Part] = []
@@ -328,7 +294,7 @@ def _merge_stream_chunks(
parts.extend(cand.content.parts)
if cand.finish_reason is not None:
finish = cand.finish_reason
- if base is None: # no chunk carried a candidate: let extract_candidate raise its way
+ if base is None: # no candidates: extract_candidate raises
base = chunks[-1]
else:
base.candidates[0].content = types.Content(role="model", parts=parts)
@@ -340,9 +306,7 @@ def _merge_stream_chunks(
class GeminiModel:
- """ChatModel for ``gemini:<model>``: a shared ``KeyPool``, ``rotate_with_retries``
- (hedge, ``ChatRequest.max_wait_s`` deadline), streaming with stall detection and
- per-attempt ledger rows."""
+ """ChatModel for ``gemini:<model>``."""
provider = "gemini"
@@ -360,12 +324,9 @@ class GeminiModel:
client_factory: Callable[[str], Any] | None = None,
) -> None:
self.model = model
- #: None = rotate_with_retries' default (60). 0 = a 503 is final: for probes,
- #: whose whole point is a fast verdict — the storm branch does NOT consume
- #: max_attempts, so max_attempts=1 alone still retried a 503 for up to 15 min.
+ #: None = rotate_with_retries' default; 0 = a 503 is final (the storm branch ignores max_attempts)
self.storm_attempts = storm_attempts
- #: keys a retry is raced on after the call's first 503 (``Settings.rate.hedge``,
- #: 2; 1 = off) — see ``rotate_with_retries`` and docs/COST.md §27
+ #: keys a retry is raced on after the first 503 (1 = off)
self.hedge = max(1, int(_rate().hedge if hedge is None else hedge))
keys = _keys_or_raise(keys, pool)
self.pool = pool or shared_pool(keys)
@@ -388,7 +349,7 @@ class GeminiModel:
state = {"config": self._config(request)}
def downgrade_thinking(err: ModelError) -> bool:
- """Free-retry hook: model rejects ThinkingConfig → retry without it, once."""
+ """Model rejects ThinkingConfig → retry without it, once."""
if not (self._thinking_ok and err.status == 400 and "thinking" in str(err).lower()):
return False
with self._lock:
@@ -398,7 +359,7 @@ class GeminiModel:
return True
budget = retry_budget_s(request.max_wait_s)
- deadline = time.monotonic() + budget # mirrors rotate_with_retries' own deadline
+ deadline = time.monotonic() + budget
stats: dict[str, Any] = {}
resp = rotate_with_retries(
self.pool,
@@ -418,7 +379,6 @@ class GeminiModel:
on_attempt=self._attempt_hook(),
**({} if self.storm_attempts is None else {"storm_attempts": self.storm_attempts}),
)
- # how hard the call was, next to which key served it (``_once``): ledger fields
resp.raw["attempts"] = int(stats.get("attempts", 0))
return resp
@@ -432,18 +392,12 @@ class GeminiModel:
def _attempt_config(
self, config: types.GenerateContentConfig, deadline: float
) -> types.GenerateContentConfig:
- """The config for ONE attempt: its HTTP read timeout is the remaining retry
- budget, capped at ``self.timeout_s`` and floored at
- :data:`parts.SDK_TIMEOUT_FLOOR_S`. A 20 s-budget turn used to hand the provider
- a 300 s socket — the dominant deadline overshoot (audit 2026-08-27)."""
+ """Config whose HTTP timeout is the remaining retry budget (see ``attempt_timeout_s``)."""
return clip_timeout(config, int(attempt_timeout_s(deadline, self.timeout_s) * 1000))
def _attempt_hook(self) -> OnAttempt:
- """Per-round-trip observer: feeds the ledger's per-attempt sink when the metering
- layer installed one (``cost.instrument.MeteredChatModel``) — a DISCARDED round-trip
- that still cost money is booked there as an ``extra`` row, the only record of it (D84).
- Captured once per logical call so a hedge loser landing later, in its own thread,
- still reports through it."""
+ """Per-round-trip observer feeding the ledger's attempt sink (books discarded round-trips).
+ The sink is captured once per call so a late hedge loser still reports."""
sink = attempt_sink()
def on_attempt(t: _Try, no: int, discarded: bool) -> None:
@@ -475,11 +429,7 @@ class GeminiModel:
model=self.model, contents=contents, config=config
)
else:
- # the attempt budget (what _attempt_config put on the wire for the
- # buffered call) becomes an in-loop deadline; the wire timeout drops
- # to the stall ceiling, which under streaming bounds only the gap
- # between chunks. A hung socket now costs <=STREAM_STALL_S of the
- # retry budget instead of all of it.
+ # the attempt budget becomes an in-loop deadline; the wire timeout drops to the stall ceiling
cfg_ms = config.http_options.timeout if config.http_options is not None else None
attempt_s = (float(cfg_ms) / 1000.0) if cfg_ms else self.timeout_s
wire = clip_timeout(config, int(min(attempt_s, STREAM_STALL_S) * 1000))
@@ -491,7 +441,7 @@ class GeminiModel:
time.monotonic() + attempt_s,
)
resp = _merge_stream_chunks(chunks)
- usage = parse_usage(resp, self.model) # BEFORE extract_candidate: its raises carry it
+ usage = parse_usage(resp, self.model) # before extract_candidate, whose raises carry it
usage.latency_ms = sw.ms
usage.cost_usd = estimate_cost("gemini", self.model, usage)
text, finish = extract_candidate(resp, usage)
@@ -501,12 +451,11 @@ class GeminiModel:
parsed = parse_json_lenient(text)
except JsonParseError as exc:
if finish in FATAL_FINISH or finish == "MAX_TOKENS":
- # blocked, or truncated: retrying the same request cannot help
raise ModelError(
f"structured output unavailable (finish_reason={finish}; "
f"raise max_output_tokens if truncated): {exc}",
retryable=False,
- usage=usage, # the provider billed this reply; the ledger wants it
+ usage=usage,
) from exc
raise ModelError(
f"structured output is not valid JSON (finish_reason={finish}): {exc}",
diff --git a/harness/codeverse3d/models/health.py b/harness/codeverse3d/models/health.py
index 228b9e17..2ec5cb4b 100644
--- a/harness/codeverse3d/models/health.py
+++ b/harness/codeverse3d/models/health.py
@@ -1,20 +1,6 @@
-"""Is a model actually serving right now?
-
-A batch job is the worst place to discover a provider outage. On 2026-08-24 a
-``gemini-3.7-flash`` capacity storm ran for hours; eight bench cells were launched
-into it and each spent 56-87 minutes losing to 503s before recording a failure, and
-the judge model went down with it. The provider was unreachable within seconds of
-the first call — the cost was entirely in not asking.
-
-``probe`` asks once per key, in parallel, with a short timeout and no retries: the
-point is a fast verdict, not a successful call. Callers use it as a preflight gate
-before spending real money.
-
-The probe prompt is deliberately **the size of real work**, not five tokens. Measured
-2026-08-24: during the flash degradation a trivial prompt answered while the 12-24 k
-token planner calls beside it were still 503-ing, so a tiny probe passed the preflight
-and the battery then lost two cells to the wall at 15 min each. A probe that does not
-resemble the workload does not measure the workload.
+"""Is a model actually serving right now? ``probe`` asks once per key, in parallel, with a
+short timeout and no retries; callers use it as a preflight gate before spending real money.
+The probe prompt is workload-sized: a tiny prompt can pass while large calls still fail.
"""
from __future__ import annotations
@@ -28,25 +14,12 @@ from codeverse3d.models.registry import build_chat_model
log = logging.getLogger(__name__)
-#: enough of the pool to tell an outage from one unlucky key, without a long probe
+#: pool keys sampled per probe
DEFAULT_SAMPLE = 6
-#: a healthy model answers a workload-sized prompt well inside this
DEFAULT_TIMEOUT_S = 30.0
-#: prompt size the probe sends, in tokens. Sized like a real planner/generator call
-#: (docs/COST.md §20 measured the corpus at ~12 k input): a 5-token probe answers when
-#: a 12 k one does not, which is exactly the false green light this gate must not give.
-#: 4 probes x 8 k tokens is ~$0.003 on flash — irrelevant next to one wasted battery.
+#: probe prompt size in tokens, sized like a real planner/generator call
PROBE_TOKENS = 8000
-#: below this share of answering calls, treat the model as down.
-#:
-#: NOT 0.5. A preflight guards a BATTERY, and one cell is dozens of model calls that
-#: must all land: at p per call a 20-call cell completes with p**20, so p = 0.5 is not
-#: "half healthy", it is zero. Retries soften it — roughly p >= 0.7 for a coin-flip
-#: chance at a cell — so the bar sits above that with margin. Measured 2026-08-24: the
-#: gate passed flash at 2/4 and the battery then lost both its first cells to the retry
-#: deadline at ~15 min each. The asymmetry decides the tie: refusing wrongly costs one
-#: 2-minute re-probe, starting wrongly costs hours. A judgement call, not a measured
-#: optimum.
+#: below this share of answering calls the model counts as down (a battery needs many calls to land)
DEFAULT_MIN_OK = 0.75
@@ -104,19 +77,13 @@ def probe(
def _probe_prompt(tokens: int = PROBE_TOKENS) -> str:
- """A workload-sized prompt whose answer is still one word.
-
- Filler carries the token weight; the instruction at the end keeps the RESPONSE
- tiny, so the probe costs input tokens (cheap, and the thing under test) rather
- than output tokens.
- """
+ """A workload-sized prompt whose answer is still one word."""
filler = "The quick brown fox jumps over the lazy dog. " * max(1, tokens // 9)
return f"{filler}\n\nIgnore the text above. Reply with the single word: pong"
def _bare_model(model_id: str, timeout_s: float):
- """The model with retries switched off — a probe that retries measures nothing. A bare
- name is a gemini model."""
+ """The model with retries off; a bare name is a gemini model."""
if ":" not in model_id:
model_id = f"gemini:{model_id}"
extra = {"storm_attempts": 0} if model_id.startswith("gemini:") else {}
diff --git a/harness/codeverse3d/models/openai.py b/harness/codeverse3d/models/openai.py
index 6ae3d492..7b5b7810 100644
--- a/harness/codeverse3d/models/openai.py
+++ b/harness/codeverse3d/models/openai.py
@@ -1,8 +1,6 @@
"""ChatRequest ⇄ OpenAI Chat Completions dicts (messages, response_format).
-Chat Completions (not Responses) was chosen because every OpenAI-compatible
-endpoint (``OPENAI_BASE_URL``: vLLM, OpenRouter, Ollama, …) speaks it, while
-the Responses API is OpenAI-only.
+Chat Completions is used because every OpenAI-compatible endpoint (``OPENAI_BASE_URL``) speaks it.
"""
from __future__ import annotations
@@ -50,7 +48,7 @@ def is_reasoning_model(model: str) -> bool:
def reasoning_effort(model: str, thinking: str) -> str | None:
"""Map ``thinking`` onto ``reasoning_effort`` (None for non-reasoning models). gpt-6 has no
- off switch — ``none`` / ``minimal`` are rejected — so "off" is its lowest effort, ``low``."""
+ off switch, so "off" is ``low``."""
if not is_reasoning_model(model):
return None
return "low" if thinking == "off" else thinking
@@ -127,7 +125,7 @@ log = logging.getLogger(__name__)
def classify_exception(exc: BaseException) -> ModelError:
- """Map openai SDK exceptions onto ``ModelError`` (the shared ladder in parts.py)."""
+ """Map openai SDK exceptions onto ``ModelError``."""
import openai
return classify_sdk_exception(exc, openai, "OpenAI")
@@ -193,7 +191,6 @@ class OpenAIModel(SdkModel):
def _once(self, kwargs: dict[str, Any], request: ChatRequest, deadline: float) -> ChatResponse:
client = self.client()
with Stopwatch() as sw:
- # the client is built once with a fixed timeout; the deadline is per call
completion = client.chat.completions.create(
model=self.model, timeout=attempt_timeout_s(deadline, self.timeout_s), **kwargs)
if not completion.choices:
diff --git a/harness/codeverse3d/models/parts.py b/harness/codeverse3d/models/parts.py
index d089aabf..5b015c09 100644
--- a/harness/codeverse3d/models/parts.py
+++ b/harness/codeverse3d/models/parts.py
@@ -51,7 +51,7 @@ def message_blocks(msg: ChatMessage, *, text: Callable[[str], Any], image: Calla
def default_timeout_s() -> float:
- """``Settings.model_timeout_s`` — the per-attempt HTTP ceiling every API adapter uses."""
+ """``Settings.model_timeout_s``."""
return float(get_settings().model_timeout_s)
@@ -92,7 +92,7 @@ class SdkModel:
class Stopwatch:
- """``with Stopwatch() as sw: ...; sw.ms``"""
+ """Context-manager timer: ``with Stopwatch() as sw: ...`` leaves the elapsed milliseconds in ``sw.ms``."""
def __enter__(self) -> Stopwatch:
self._t0 = time.perf_counter()
@@ -104,23 +104,15 @@ class Stopwatch:
def retryable_status(status: int | None) -> bool:
- """THE HTTP statuses a retry may get through, for every provider (N76): request timeout
- 408, conflict 409, rate limit 429 and every 5xx (anthropic's 529 overloaded among them) —
- the list the openai and anthropic SDKs retry themselves."""
+ """HTTP statuses worth retrying: 408, 409, 429 and every 5xx."""
return status is not None and (status in (408, 409, 429) or status >= 500)
def classify_sdk_exception(exc: BaseException, sdk: Any, label: str) -> Any:
"""The openai/anthropic SDK exception ladder → ``ModelError``.
- anthropic-sdk-python is a fork of openai-python, so ``APIStatusError`` /
- ``APITimeoutError`` / ``APIConnectionError`` / ``APIError`` and ``.status_code`` /
- ``.message`` are the same names on both — this ladder was written out twice,
- differing only in the module and the label.
-
- The MESSAGE WORDING IS LOAD-BEARING: eval/bench/_infra.py string-matches "request timed
- out" and "connection error" to tell a provider outage from a model failure, so the
- f"{label} …" forms below must stay byte-identical to what each adapter emitted.
+ The message wording is load-bearing: eval/bench/_infra.py string-matches "request timed
+ out" and "connection error" to tell a provider outage from a model failure.
"""
if isinstance(exc, ModelError):
return exc
@@ -136,11 +128,7 @@ def classify_sdk_exception(exc: BaseException, sdk: Any, label: str) -> Any:
return ModelError(f"{label} unexpected error: {type(exc).__name__}: {exc}", retryable=False)
-#: floor of the per-attempt SDK / HTTP read timeout (gemini's too) derived from what is
-#: left of the call's ``max_wait_s`` budget: a call that starts near its deadline still gets
-#: ONE real attempt instead of an instant timeout. Same 20 s as the judge's own
-#: ``SAMPLE_MIN_WAIT_S``, so an attempt in flight overshoots the deadline by at most this
-#: floor — never by the full read timeout (audit 2026-08-27, when that ceiling was 300 s).
+#: floor of the per-attempt timeout, so a call near its deadline still gets one real attempt
SDK_TIMEOUT_FLOOR_S = 20.0
@@ -152,25 +140,15 @@ def retry_budget_s(max_wait_s: float | None) -> float:
def attempt_timeout_s(deadline: float, ceiling: float) -> float:
- """The SDK timeout for ONE attempt: what is left of ``deadline``, capped at the
- client's ``timeout_s`` and floored at :data:`SDK_TIMEOUT_FLOOR_S`.
-
- The retry loop checks the deadline only BETWEEN attempts and both SDK clients are
- built once with a fixed ``timeout`` (600 s), so a judge told it had 20 s of budget
- left held a socket for 600 s (audit 2026-08-29). The floor is what keeps a legitimate
- long completion (the 930 s plan budget) on its full ``timeout_s`` — this shortens an
- attempt, it never lengthens one. Gemini's ``_attempt_config`` clips through it too.
- """
+ """Per-attempt SDK timeout: time left to ``deadline``, capped at ``ceiling``, floored at
+ :data:`SDK_TIMEOUT_FLOOR_S`. The retry loop checks the deadline only between attempts."""
return min(ceiling, max(SDK_TIMEOUT_FLOOR_S, deadline - time.monotonic()))
def retry_one_key(attempt: Any, *, label: str, classify: Any, attempts: int, sleep: Any,
max_wait_s: float | None = None) -> Any:
- """The SDK adapters' retry loop: ``rotate_with_retries`` over a fresh one-key pool with no
- cooldown, no storm patience and no hedge — so a 429 / 5xx / 529 / timeout is retried
- ``attempts`` times with the ≤ ``MAX_WAIT_S`` backoff, inside the request's ``max_wait_s``
- deadline (``None`` = ``RETRY_DEADLINE_S``), and a raised ``ModelError`` says how many
- round-trips it took. ``label`` names the call in the log ("anthropic <model>")."""
+ """The SDK adapters' retry loop: ``rotate_with_retries`` over a one-key pool, no cooldown,
+ storm patience or hedge, inside the request's ``max_wait_s`` deadline."""
from codeverse3d.models.retry import KeyPool, rotate_with_retries
return rotate_with_retries(KeyPool([label], cooldown_s=0.0), lambda _key: attempt(), classify=classify,
diff --git a/harness/codeverse3d/models/pricing.py b/harness/codeverse3d/models/pricing.py
index 6ebda915..7709cbe8 100644
--- a/harness/codeverse3d/models/pricing.py
+++ b/harness/codeverse3d/models/pricing.py
@@ -1,17 +1,8 @@
"""USD price table (per 1M tokens) + ``estimate_cost`` + price provenance.
-Every ``Usage`` is priced here (providers never return USD). Each row carries its
-provenance — where the number came from and when it was last checked — so a cost
-report can say *which* price row produced a dollar and whether it was verified or
-merely inferred (``3dcode cost prices``).
-
-Only the standard (short-context) tier is modelled, **except** the documented
-long-prompt tiers of Gemini pro, Claude Haiku 5.5 and GPT-6, which ``estimate_cost`` applies
-automatically (``Price.long_context``). Cache *storage* fees (Gemini explicit
-caching, $/1M-tokens/hour), Anthropic 1h-cache writes, batch/flex discounts,
-data-residency and fast-mode multipliers are **not** modelled — see
-``docs/COST.md``. Unknown models price at 0.0 and log a warning once per
-(provider, model).
+Each row carries its provenance (source status and check date). Long-prompt tiers
+are modelled (``Price.long_context``); cache storage, 1h cache writes, batch and fast-mode
+multipliers are not. Unknown models price at 0.0 and warn once.
"""
from __future__ import annotations
@@ -28,9 +19,6 @@ log = logging.getLogger(__name__)
#: date the tables below were last reconciled against the providers' pricing pages
CHECKED = "2026-08-23"
-#: 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)
class LongContext:
@@ -44,16 +32,9 @@ class LongContext:
@dataclass(frozen=True)
class Price:
- """USD per 1M tokens, and where the number came from. ``cached`` = cache-read input;
- ``cache_write`` = cache creation (Anthropic explicit caching, 5-minute TTL);
- ``thoughts`` are billed at the output rate.
-
- 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
- * ``unverified`` — the model is not listed on the page (retired / alias / CLI-only)
- """
+ """USD per 1M tokens. ``cached`` = cache-read input, ``cache_write`` = cache creation;
+ thoughts bill at the output rate. ``status``: verified | inferred (nearest sibling) |
+ unverified (not on the pricing page)."""
input: float
output: float
@@ -69,12 +50,8 @@ class Price:
# fmt: off
PRICES: dict[tuple[str, str], Price] = {
# ---------------------------------------------------------------- gemini
- # 4 argon: introductory rates valid through 2026-11-30; they double on 2026-12-01
- # ($4.00 / $20.00 / $0.20). Update then. No >200k tier; output includes thinking.
("gemini", "gemini-4-argon"): Price(2.00, 10.00, 0.10, checked="2026-10-13",
note="intro rate through 2026-11-30, then 4.00/20.00/0.20"),
- # 3.8 flash: introductory rates valid through 2026-12-31; they double
- # on 2027-01-01 ($1.50 / $7.50 / $0.15). Update then. No >200k surcharge.
("gemini", "gemini-3.8-flash"): Price(0.75, 3.75, 0.075, checked="2026-09-21",
note="intro rate through 2026-12-31, then 1.50/7.50/0.15"),
("gemini", "gemini-3.1-pro-preview"): Price(2.00, 12.00, 0.20,
@@ -90,22 +67,18 @@ PRICES: dict[tuple[str, str], Price] = {
("gemini", "gemini-2.5-flash"): Price(0.30, 2.50, 0.03, note="cached was 0.075 here until 2026-08-23; published 0.03"),
("gemini", "gemini-2.5-flash-lite"): Price(0.10, 0.40, 0.01, note="cached was 0.025 here until 2026-08-23; published 0.01"),
# ------------------------------------------------------------- anthropic
- # Only the current generation is kept (owner, 2026-10-13): a model no longer
- # here prices at $0 with a warning; a recorded run keeps the cost it was booked at.
("anthropic", "claude-fable-5-1"): Price(10.00, 50.00, 0.25, cache_write=12.50, checked="2026-10-13",
note="1h cache write 20.00 (not modelled)"),
("anthropic", "claude-opus-5-5"): Price(4.00, 20.00, 0.20, cache_write=5.00, checked="2026-10-13",
note="fast mode is 8.00/40.00 (not modelled)"),
("anthropic", "claude-sonnet-5-5"): Price(2.00, 10.00, 0.10, cache_write=2.50, checked="2026-10-13"),
- # haiku-5.5 is priced by prompt length: >100k tokens (cache reads and writes included)
- # pays 0.50/2.50/0.05 for the whole request; its 0.625 cache write there is not modelled.
+ # haiku-5.5: prompts over 100k tokens bill the whole request at the long tier
("anthropic", "claude-haiku-5-5"): Price(0.10, 0.50, 0.01, cache_write=0.125, checked="2026-10-13",
long_context=LongContext(100_000, 0.50, 2.50, 0.05)),
- # kept for the small model claude-code reports next to the main one (``claude-haiku-4-5-20251001``)
+ # the small model claude-code reports next to the main one
("anthropic", "claude-haiku-4-5"): Price(1.00, 5.00, 0.10, cache_write=1.25, checked="2026-10-13"),
# ---------------------------------------------------------------- openai
- # >272k input bills the whole request at 2x input/cache and 1.5x output. CLI aggregate
- # usage is a notional estimate, not per-request billing.
+ # >272k input bills the whole request at 2x input/cache and 1.5x output
("openai", "gpt-6-astra"): Price(10.00, 50.00, 1.00, cache_write=12.50, checked="2026-10-13",
long_context=LongContext(272_000, 20.00, 75.00, 2.00)),
("openai", "gpt-6.1-sol"): Price(2.00, 10.00, 0.10, cache_write=2.50, checked="2026-10-13",
@@ -125,18 +98,15 @@ def _normalise(model: str) -> str:
return model.strip().lower()
-#: the reasoning efforts agy spells into its model ids (``gemini-3.8-flash-medium``): the same
-#: model at the same per-token rate — unmatched, every agy session was priced $0 (live, 2026-09-23)
+#: reasoning efforts agy spells into its model ids (``gemini-3.8-flash-medium``): same model, same rate
EFFORTS = ("low", "medium", "high")
# words that may follow a priced model id without changing which model it is
_VERSION_WORDS = frozenset({"latest", "preview", "exp", "beta", "alpha", "stable", "snapshot", *EFFORTS})
def _is_version_suffix(rest: str) -> bool:
- """True when ``rest`` (what follows a table key in a model id) is only a
- version / date / channel tag — ``-20260301``, ``@001``, ``-preview-05-20``,
- ``-latest`` — and not a sibling model name (``-nano``, ``-mini``, ``-codex``,
- ``.5``), which must price separately or be reported unknown."""
+ """True when ``rest`` (what follows a table key) is only a version/date/channel tag,
+ not a sibling model name (``-mini``, ``.5``)."""
if not rest or rest[0] not in "-_@:":
return False
segments = rest[1:].split("-")
@@ -158,10 +128,8 @@ def _match(provider: str, model: str) -> tuple[tuple[str, str], Price] | None:
def lookup_price(provider: str, model: str) -> Price | None:
- """Exact match first, then the longest table key that ``model`` extends by a
- pure version/date suffix (``claude-opus-5-20260301``, ``gemini-3.8-flash-preview-09``).
- A different family name after the key (``gpt-6.1-sol-mini`` vs ``gpt-6.1-sol``) is NOT a
- match: unknown → ``None`` so the caller prices 0.0 and warns, never a sibling's rate."""
+ """Exact match, else the longest table key extended only by a version/date suffix.
+ A sibling name (``gpt-6.1-sol-mini``) is unknown → ``None``, never a sibling's rate."""
found = _match(provider, model)
return found[1] if found else None
@@ -178,8 +146,7 @@ class PriceRow:
@property
def approximate(self) -> bool:
- """True when the dollar cannot be trusted to the cent: no row, an
- inferred/unverified row, or a row flagged ``approximate``."""
+ """True when the dollar is not exact: no row, a non-verified row, or flagged."""
return self.price is None or self.price.approximate or self.price.status != "verified"
@property
@@ -192,8 +159,7 @@ class PriceRow:
def price_provenance(provider: str, model: str) -> PriceRow:
- """Resolve ``provider:model`` to a price **and its source**. Never raises;
- an unknown model comes back as ``match="unknown"``, ``price=None``."""
+ """Resolve ``provider:model`` to a price and its source; unknown → ``match="unknown"``."""
prov = (provider or "").strip().lower()
found = _match(prov, model)
if not found:
@@ -204,9 +170,8 @@ def price_provenance(provider: str, model: str) -> PriceRow:
def unit_prices(provider: str, model: str, *, prompt_tokens: int = 0) -> tuple[float, float, float]:
- """``(input, cached, output)`` USD per 1M actually charged for a prompt of
- ``prompt_tokens`` — the long-context tier when the model has one and the
- prompt crosses its threshold. Unknown model → ``(0, 0, 0)``."""
+ """``(input, cached, output)`` USD per 1M for a prompt of ``prompt_tokens`` (long tier
+ past its threshold). Unknown model → zeros."""
price = lookup_price(provider, model)
if price is None:
return (0.0, 0.0, 0.0)
@@ -217,11 +182,8 @@ def unit_prices(provider: str, model: str, *, prompt_tokens: int = 0) -> tuple[f
def estimate_cost(provider: str, model: str, usage: Usage) -> float:
- """USD for one call. ``usage.input_tokens`` is the TOTAL prompt size (cached
- tokens included); cached tokens are re-priced at the cache-read rate.
- ``usage.thoughts_tokens`` are billed as output when the provider reports
- them separately from ``output_tokens`` (Gemini); Anthropic/OpenAI fold
- reasoning into ``output_tokens`` already, so callers must not double count."""
+ """USD for one call. ``input_tokens`` includes cached tokens (re-priced at the cache-read
+ rate); ``thoughts_tokens`` bill as output, so callers must not also fold them into ``output_tokens``."""
price = lookup_price(provider, model)
if price is None:
key = (provider, _normalise(model))
@@ -242,10 +204,8 @@ def estimate_cost(provider: str, model: str, usage: Usage) -> float:
def openai_usage(backend: str, model: str, *, prompt: int, cached: int, completion: int, reasoning: int,
**extra: Any) -> Usage:
- """OpenAI-family tokens (the SDK and codex alike) as a priced ``Usage``. ``completion``
- already CONTAINS ``reasoning`` (measured on codex: output − reasoning tracks the answer
- length), so the reasoning share moves to ``thoughts_tokens`` — still visible, and billed
- once by :func:`estimate_cost` (output + thoughts), never twice."""
+ """OpenAI-family tokens as a priced ``Usage``. ``completion`` contains ``reasoning``;
+ the reasoning share moves to ``thoughts_tokens`` so it is billed once."""
usage = Usage(backend=backend, model=model, input_tokens=prompt, output_tokens=max(0, completion - reasoning),
cached_tokens=cached, thoughts_tokens=reasoning, **extra)
usage.cost_usd = estimate_cost("openai", model, usage)
@@ -253,9 +213,7 @@ def openai_usage(backend: str, model: str, *, prompt: int, cached: int, completi
def cache_write_surcharge(provider: str, model: str, cache_write_tokens: int) -> float:
- """Extra USD (on top of the normal input rate already charged by
- ``estimate_cost``) for explicit cache creation, e.g. Anthropic's
- ``cache_creation_input_tokens`` billed at 1.25× input."""
+ """Extra USD on top of the input rate ``estimate_cost`` already charged, for cache creation."""
price = lookup_price(provider, model)
if price is None or cache_write_tokens <= 0 or price.cache_write is None:
return 0.0
diff --git a/harness/codeverse3d/models/retry.py b/harness/codeverse3d/models/retry.py
index 32a1e4aa..1b94cae2 100644
--- a/harness/codeverse3d/models/retry.py
+++ b/harness/codeverse3d/models/retry.py
@@ -1,36 +1,10 @@
-"""The scheduling machine under every model call (merged 2026-08-28, d512ccc):
-
-1. ``KeyPool``: a multi-key pool with 429 cooldown, dead-key benching, a health score
- and the ``max_in_flight`` ceiling, which is machine-wide (``Slots``: flock'd lock
- files every process shares) — used by ``GeminiModel`` (22 keys on the owner's box)
- but provider-neutral;
-2. ``rotate_with_retries``, the one retry loop (the pool, hedging, the ``RETRY_DEADLINE_S``
- deadline) — the SDK adapters run it over a one-key pool (``parts.retry_one_key``).
-
-Every wait anywhere in here clips to ``MAX_WAIT_S``.
-
-The pool:
-
-* ``acquire()`` picks the next healthy key round-robin, honouring 429 cool-downs; it
- blocks (bounded) when every key is cooling and raises ``KeyPoolExhausted`` after
- ``timeout_s``. ``max_in_flight`` additionally caps how many calls may be out at
- once 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; ``lease_session_key()`` picks a key for a
- vendor 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
- (docs/COST.md §19).
-* ``report(key, outcome)`` feeds back ``ok | 429 | 5xx | error | dead | skip`` so the
- pool can cool a key down and adjust its health score. ``skip`` is a content
- failure the key did not cause (bad JSON, empty candidates): health and counters are
- untouched. ``dead`` is for key-scoped auth/permission failures (revoked / suspended /
- invalid key): the key is benched for ``dead_cooldown_s`` (default one hour) and
- re-probed once that elapses — a dead key must never keep failing its share of calls.
-* ``stats()`` exposes counters for logs / ``3dcode doctor --live``: per-key health and
- cooldown, in-flight and peak in-flight.
-
-Thread-safe; ``clock`` / ``sleep`` are injectable for deterministic tests.
+"""The scheduling machine under every model call.
+
+``KeyPool``: multi-key pool with 429 cooldown, dead-key benching, health scores and a
+machine-wide ``max_in_flight`` ceiling (``Slots``, flock'd lock files). ``rotate_with_retries``:
+the one retry loop (pool, hedging, ``RETRY_DEADLINE_S``); SDK adapters run it over a one-key pool.
+Every wait clips to ``MAX_WAIT_S``. ``report`` outcomes: ok | 429 | 5xx | error | dead | skip
+(``skip`` = a content failure the key did not cause). Thread-safe; ``clock`` / ``sleep`` injectable.
"""
from __future__ import annotations
@@ -56,8 +30,7 @@ class KeyPoolExhausted(RuntimeError):
"""Every key is cooling down (or every slot is busy) and the wait budget ran out."""
-# message fragments of key-scoped failures (revoked / suspended / expired / disabled
-# project); HTTP 401 / 403 are key-scoped regardless of wording
+# message fragments of key-scoped failures; HTTP 401 / 403 are key-scoped regardless
_DEAD_KEY_MARKERS = (
"api_key_invalid",
"api key not valid",
@@ -72,8 +45,7 @@ _DEAD_KEY_MARKERS = (
def is_dead_key_error(err: ModelError) -> bool:
- """True when ``err`` indicts the API key rather than the request, so the call
- should move to another key instead of failing."""
+ """True when ``err`` indicts the API key rather than the request."""
if err.status in (401, 403):
return True
text = str(err).lower()
@@ -81,9 +53,7 @@ def is_dead_key_error(err: ModelError) -> bool:
def failure_outcome(err: ModelError) -> Outcome:
- """``KeyPool.report`` outcome for a failed call (``rotate_with_retries``' default
- ``outcome_of``). Content-level failures (bad JSON, empty candidates) carry no status
- and are not the key's fault: ``skip`` leaves health / counters alone."""
+ """``KeyPool.report`` outcome for a failed call; status-less content failures are ``skip``."""
if err.status == 429:
return "429"
if (err.status or 0) >= 500:
@@ -93,23 +63,13 @@ def failure_outcome(err: ModelError) -> Outcome:
return "error" if err.status else "skip"
+#: Longest single retry / cooldown wait (seconds): the pool rotates keys rather than sitting out
+#: a long backoff, so patience comes from the number of attempts, never from one sleep.
MAX_WAIT_S = 3.0
-"""The longest any single retry / cooldown wait may be (seconds).
-
-House rule (owner, 2026-08-24, tightened 5 s -> 3 s on 2026-08-27): with 22 keys
-there is always another key to try, so the harness rotates rather than sitting
-out a long backoff. Patience comes from the NUMBER of attempts, never from the
-length of one sleep. This is the single source for every wait — generic
-backoff, storm sleeps and 429 cooldowns all clip to it.
-"""
+#: Default total wait budget of one :meth:`KeyPool.acquire` (seconds): the in-flight slot wait plus
+#: the key / cooldown wait; ``None`` waits forever.
ACQUIRE_TIMEOUT_S = 120.0
-"""Default total wait budget of one :meth:`KeyPool.acquire` (seconds).
-
-Covers BOTH the ``max_in_flight`` slot wait and the key/cooldown wait; a caller
-with a deadline passes something smaller (``retry.rotate_with_retries`` passes
-``min(ACQUIRE_TIMEOUT_S, remaining budget)``). ``None`` waits forever.
-"""
@dataclass
@@ -134,22 +94,12 @@ class _KeyState:
class Slots:
- """``n`` machine-wide in-flight slots: the docs/COST.md §20 knee, enforced across processes.
-
- One lock file per slot, ``<root>/NN.lock``, held with ``fcntl.flock`` while ONE model call
- is out. Every process pointed at the same ``root`` draws from ``00 .. n-1``, so the
- machine never has more calls in flight than the largest ``n`` any of them runs with, and
- a process with a smaller cap only ever uses its own first ``n`` files. flock locks an
- open file DESCRIPTION and every take opens its own, so two threads of one process
- exclude each other exactly as two processes do. The kernel drops the lock when its
- holder dies — SIGKILL and the OOM killer included — so a dead process never strands a
- slot: the staleness problem that kept a machine-wide limiter deferred in §23 does not
- exist for flock (``proc.exclusive`` relies on the same property).
+ """``n`` machine-wide in-flight slots: one lock file per slot, ``<root>/NN.lock``, held with
+ ``fcntl.flock`` while one model call is out. The kernel drops a dead holder's lock, so a
+ killed process never strands a slot.
"""
- #: how long a waiter naps between two sweeps of the files while every slot is busy
- #: (seconds, jittered x0.5..1.5). A model call takes seconds, so this bounds the extra
- #: latency a free slot costs a waiter, and a sweep is n non-blocking flock calls.
+ #: nap between sweeps while every slot is busy (seconds, jittered x0.5..1.5)
POLL_S = 0.05
def __init__(self, n: int, root: Path | str) -> None:
@@ -163,9 +113,8 @@ class Slots:
return self.root / f"{i:02d}.lock"
def try_take(self) -> int | None:
- """A held slot (its file descriptor), or ``None`` when all ``n`` are busy — never
- waits. The sweep starts at a random slot, so a process with a small cap is not
- starved by a big one that always fills the low numbers first."""
+ """A held slot (its file descriptor), or ``None`` when all are busy; never waits.
+ The sweep starts at a random slot so a small-cap process is not starved."""
start = random.randrange(self.n)
for step in range(self.n):
fd = os.open(self._path((start + step) % self.n), os.O_RDWR | os.O_CREAT, 0o666)
@@ -181,8 +130,7 @@ class Slots:
return None
def take(self, timeout_s: float | None) -> int:
- """Wait for a slot, at most ``timeout_s`` (``None`` = forever); its descriptor.
- Raises ``KeyPoolExhausted`` once the wait is over."""
+ """Wait up to ``timeout_s`` (``None`` = forever) for a slot; raises ``KeyPoolExhausted``."""
deadline = None if timeout_s is None else time.monotonic() + timeout_s
while (fd := self.try_take()) is None:
left = None if deadline is None else deadline - time.monotonic()
@@ -194,16 +142,14 @@ class Slots:
@staticmethod
def give(fd: int) -> None:
- """Hand a slot back. LOCK_UN first: a descriptor a forked child inherited must not
- keep the slot held after this process is done with it."""
+ """Hand a slot back; LOCK_UN first so a forked child's inherited descriptor does not keep it held."""
try:
fcntl.flock(fd, fcntl.LOCK_UN)
finally:
os.close(fd)
def busy(self) -> int:
- """How many slots somebody holds right now, machine-wide (``3dcode doctor``). A
- shared probe per file, released at once: it never takes a slot from a caller."""
+ """How many slots are held machine-wide (``3dcode doctor``); never takes one."""
n = 0
for i in range(self.n):
try:
@@ -220,7 +166,7 @@ class Slots:
class KeyPool:
- """Round-robin key pool with cooldowns and an in-flight ceiling. See module docstring."""
+ """Round-robin key pool with cooldowns and an in-flight ceiling."""
def __init__(
self,
@@ -246,13 +192,11 @@ class KeyPool:
self._rr = start % len(uniq)
self._in_flight = 0
self._peak_in_flight = 0
- # Machine-wide ceiling on concurrent model calls, independent of the caller's
- # thread pools: blender/node/chrome workers are CPU-bound and sized by cores,
- # while this is sized by the provider (docs/COST.md Part III). 0 = unlimited.
+ # machine-wide ceiling on concurrent model calls; 0 = unlimited
self._max_in_flight = int(max_in_flight or 0)
if self._max_in_flight and slots_dir is None:
raise ValueError("max_in_flight needs slots_dir: the slots are lock files every process shares")
- #: the machine-wide slots (``None`` when uncapped); ``3dcode doctor`` reads it
+ #: the machine-wide slots (``None`` when uncapped)
self.slots = Slots(self._max_in_flight, slots_dir) if self._max_in_flight else None
self._held: list[int] = [] # slot descriptors of this process's in-flight calls
now = clock()
@@ -269,15 +213,9 @@ class KeyPool:
exclude: set[str] | frozenset[str] | None = None,
timeout_s: float | None = ACQUIRE_TIMEOUT_S,
) -> str:
- """Return the next usable key, blocking (bounded by ``timeout_s``) while all
- keys are cooling down. ``exclude`` skips keys that already failed this call.
- Raises ``KeyPoolExhausted`` at once when no key can become available before
- the deadline (e.g. every key is dead) — availability only moves later.
-
- When ``max_in_flight`` is set the call also waits for a free machine-wide slot;
- :meth:`release` hands it back. ``timeout_s`` bounds the slot wait AND the key
- wait together (``None`` = wait forever): the slot wait used to be unbounded, so
- a caller 20 s from its deadline could sit on the semaphore for minutes."""
+ """Next usable key, blocking up to ``timeout_s`` (slot wait + key wait) while all keys cool.
+ ``exclude`` skips keys that already failed this call; raises ``KeyPoolExhausted`` at once
+ when no key can become available before the deadline."""
slot = None
if self.slots is not None:
t0 = self._clock()
@@ -295,13 +233,8 @@ class KeyPool:
return key
def try_acquire(self, *, exclude: set[str] | frozenset[str] | None = None) -> str | None:
- """:meth:`acquire` that never waits: a key usable *right now* (and a free
- ``max_in_flight`` slot), else ``None`` — nothing is reserved or counted then.
-
- For the extra keys of a hedged retry (``rotate_with_retries(hedge=...)``): the
- primary request is already in flight, so a partner that is not free at once
- is not worth waiting for. A returned key holds a slot like any other and
- must be :meth:`release`-d."""
+ """:meth:`acquire` that never waits: a key usable now, else ``None``. Used for hedge
+ partners; a returned key holds a slot and must be :meth:`release`-d."""
slot = None
if self.slots is not None and (slot := self.slots.try_take()) is None:
return None
@@ -317,18 +250,10 @@ class KeyPool:
return key
def lease_session_key(self, leases: Path | str, *, timeout_s: float | None = ACQUIRE_TIMEOUT_S) -> tuple[str, int | None]:
- """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: one
- agy session, 11 M prompt tokens in 18 min, 429'd), and every parallel ``3dcode make``
- is its own process with its own pool — so a session holds ``fcntl.flock`` on
- ``<leases>/<key hash>.lock`` for its length, and the next one, in any process, skips a
- key that is held. Only when every ready key is in a session is one shared (lease
- ``None``). Returns ``(key, lease)``; close the lease with :meth:`end_lease`. The kernel
- drops a dead holder's lock, so a killed run never strands a key (as :class:`Slots`)."""
+ """A key for a vendor-CLI session: rotation, cooldowns and benching like :meth:`acquire`
+ but no in-flight slot, and one live session per key machine-wide while keys suffice
+ (a ``flock`` on ``<leases>/<key hash>.lock``). Returns ``(key, lease)``; close the lease
+ with :meth:`end_lease`. When every ready key is in a session one is shared (lease ``None``)."""
root = Path(leases)
root.mkdir(parents=True, exist_ok=True)
busy: set[str] = set()
@@ -388,13 +313,7 @@ class KeyPool:
self._sleep(wait)
def release(self) -> None:
- """Mark one :meth:`acquire`-d call finished (call it in a ``finally``).
-
- Frees the in-flight gauge and one of this process's slots (they are
- interchangeable: the count is what the machine sees); outcome accounting is
- :meth:`report`, which may legitimately be called more than once for one call (a
- key that looked dead is reported again once a sibling proves the request fine).
- A stray ``release`` is a no-op."""
+ """Mark one :meth:`acquire`-d call finished (call in a ``finally``); a stray release is a no-op."""
with self._lock:
if self._in_flight <= 0:
return
@@ -404,8 +323,7 @@ class KeyPool:
Slots.give(slot)
def report(self, key: str, outcome: Outcome, *, retry_after_s: float | None = None) -> None:
- """Feed back the result of a call made with ``key`` (``retry_after_s``: a 429's
- suggested delay, clipped to ``MAX_WAIT_S``)."""
+ """Feed back a call's result (``retry_after_s``: a 429's delay, clipped to ``MAX_WAIT_S``)."""
with self._lock:
st = self._by_key.get(key)
if st is None:
@@ -419,15 +337,14 @@ class KeyPool:
st.n_429 += 1
st.health *= 0.5
cool = retry_after_s if retry_after_s and retry_after_s > 0 else self._cooldown_s
- # House rule (owner, 2026-08-24): no single wait exceeds MAX_WAIT_S — we
- # rotate to another key instead of sitting out a provider's suggested delay.
+ # rotate to another key rather than sit out the provider's delay
cool = min(cool, MAX_WAIT_S)
st.cooldown_until = max(st.cooldown_until, now + cool)
elif outcome == "5xx":
st.n_5xx += 1
st.health *= 0.8
elif outcome == "dead":
- # key-scoped failure: bench it; re-probed once the long cooldown passes
+ # key-scoped failure: bench until the long cooldown passes
st.n_dead += 1
st.health = 0.0
st.dead_until = max(st.dead_until, now + self._dead_cooldown_s)
@@ -437,7 +354,7 @@ class KeyPool:
st.health *= 0.9
def stats(self) -> dict[str, Any]:
- """Counters per key (keys are redacted to their last 4 chars)."""
+ """Counters per key (keys redacted to their last 4 chars)."""
with self._lock:
now = self._clock()
per_key = [
@@ -471,8 +388,7 @@ class KeyPool:
# ----------------------------------------------------------------- private
def _pick(self, now: float, exclude) -> _KeyState | None:
- """Round-robin scan; prefer the first healthy, ready key; otherwise the
- healthiest ready key. Advances the RR cursor past the chosen key."""
+ """Round-robin: the first healthy ready key, else the healthiest ready key."""
n = len(self._states)
best: _KeyState | None = None
best_idx = -1
@@ -495,23 +411,11 @@ class KeyPool:
# ===================================================================== retry
-#: the longest ONE logical call may spend being retried, waits and timeouts included.
-#: The storm branch used to be bounded only in ATTEMPTS: 60 storm attempts x (a 300 s
-#: read timeout + a <=5 s wait) is **5.1 hours** for a single call, though the docstring
-#: claimed "~5 min". Measured 2026-08-24: that, plus a wall-clock ceiling only checked
-#: when a call is BILLED (a stalled call bills nothing), let a run with --max-minutes 90
-#: reach 200 minutes during a flash outage. Past this deadline the call gives up and the
-#: cell is recorded infra_failed, which is re-runnable (`--redo-status infra_failed`).
-#: 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 ready
-RETRY_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.
-#: Measured 2026-08-26 §5.2: a failed 503 costs the 21-50 s round-trip the provider
-#: holds before rejecting (not the <= MAX_WAIT_S sleep), storm streaks average 4.7 attempts,
-#: and a 503 bills nothing — so racing the next attempt on two fresh keys is free.
+#: a key below this health is passed over while a healthier one is ready
+MIN_HEALTH = 0.3
+RETRY_DEADLINE_S = 1800.0 # ceiling of one logical call, retries included
+
+#: keys a retry is raced on once a call has met its first 503/529
DEFAULT_HEDGE = 2
if TYPE_CHECKING: # pragma: no cover
@@ -521,24 +425,11 @@ log = logging.getLogger(__name__)
def cause_for(err: BaseException, exc: BaseException | None) -> BaseException | None:
- """The cause to raise ``err`` from — ``None`` when it would be ``err`` itself.
-
- Every adapter's ``classify()`` returns an already-classified ``ModelError``
- unchanged (gemini.py, openai.py, anthropic.py), so ``raise err from exc`` below is
- often ``raise e from e``, and CPython's ``raise ... from ...`` does NOT check for a
- cycle the way it does for ``__context__``. The result — ``e.__cause__ is e`` — is a
- chain no naive walker survives: on 2026-08-27 it took ``eval/bench/_infra.py`` to a
- RecursionError inside ``run_cell``'s except handler and a compare matrix lost 11
- finished cells. Dropping the self-cause is invisible otherwise: none of these
- raises sits inside an ``except`` block, and ``__suppress_context__`` is already set.
- """
+ """The cause to raise ``err`` from, ``None`` when it would be ``err`` itself (a
+ self-cause chain recurses forever in naive walkers)."""
return None if exc is err else exc
-#: per-round-trip hook of :func:`rotate_with_retries`: ``(try, attempt_no, discarded)``.
-#: ``attempt_no`` is the 1-based issue order within the logical call; ``discarded``
-#: is True for every round-trip that is not the winning one (hedge losers included).
-#: Fired exactly once per round-trip: buffered tries flush when the call settles,
-#: and a hedge loser still in flight reports the moment it lands (its own thread).
+#: per-round-trip hook of :func:`rotate_with_retries`: ``(try, attempt_no, discarded)``; fired once per round-trip
OnAttempt = Callable[["_Try", int, bool], None]
@@ -576,69 +467,23 @@ def rotate_with_retries[T](
) -> T:
"""Run ``call(key)`` against a rotating :class:`KeyPool` until it succeeds.
- The state machine (used by ``GeminiModel``):
-
- * success → ``pool.report(key, "ok")``; keys that looked dead during this call are
- benched (another key proved the request itself is fine) and the result is returned.
- * ``on_free_retry(err)`` returning ``True`` → retry at once, for free
- (no sleep, no budget) — e.g. a thinking-config downgrade.
- * ``outcome_of(err) == "dead"`` (key-scoped auth failure) → rotate at once
- for free; the key is only benched once a sibling key proves the request
- is fine. Every key failing the same way raises without benching.
- * ``"429"`` → cool the key down (honouring ``retry_after``); rotation is
- FREE while an untried key remains (0.5 s courtesy pause), otherwise the
- 429 counts against ``max_attempts`` with exponential backoff.
- * ``"503"``/529 → EXACTLY like the 429 path: the key is added to this call's
- failed set and rotation to an untried key is FREE (no sleep, no budget, no
- ``max_attempts``) for as long as ANY untried key remains — a 20-key pool
- rotates 19 times before it ever waits. Measured 2026-08-26 with one tiny
- request per key in parallel, three rounds 20 s apart, during the day's
- "high demand" storm — gemini-3.7-flash answered on 15/22, 18/22 and 21/22
- keys while only 5, 4 and 1 keys said 503 at the same instant. A 503 is per
- key at any moment, so the next key is the cure and a wait is the last
- resort. Only once EVERY key in the pool has 503'd within this one logical
- call is it a
- * **capacity storm** (the whole pool is out of capacity, the backstop): that gets
- its own patience budget — up to ``storm_attempts`` waits with
- backoff capped at ``storm_max_delay`` = ``MAX_WAIT_S`` (3 s) per wait (the house
- rule), so patience comes from the NUMBER of waits (60 x <=3 s) rather than from
- long sleeps that do NOT consume ``max_attempts`` — all inside the
- ``RETRY_DEADLINE_S`` / ``max_total_s`` deadline. Observed 2026-08-23: a
- multi-minute gemini-3.7-flash "high demand" outage killed 8 bench runs
- under the plain 6-attempt budget.
- * other retryable errors → exponential backoff + jitter until
- ``max_attempts``; non-retryable errors raise immediately.
-
- **Hedging** (``hedge``, default :data:`DEFAULT_HEDGE`; ``1`` disables). From the
- FIRST 503/529 of a call onwards, every further attempt is issued on up to ``hedge``
- distinct keys at once and the first success wins. Why: on the 2026-08-26 storm
- day the cost of a failed 503 was the **21-50 s round-trip** the provider held
- before rejecting, not the <= MAX_WAIT_S sleep (logged sleep was 13 % of the wait), and
- storm streaks averaged **4.7 attempts** — racing two keys cuts the expected number
- of rounds to ~1.7. A 503 bills nothing, so while it is storming the hedge is free;
- the price is paid only when BOTH keys answer: the second success is discarded and
- that call's tokens are wasted (a few cents for a chat turn).
- Mechanics: the attempt's first key is acquired as usual (it may wait for a slot or
- a cooldown); the extra keys come from :meth:`KeyPool.try_acquire` and are simply
- skipped when no fresh key or ``max_in_flight`` slot is free *right now*, so a hedge
- never waits for a partner and every hedged request holds its own slot. The calls
- run in a per-attempt ``ThreadPoolExecutor`` that is shut down without waiting: a
- loser keeps running until its own round-trip ends, then reports its outcome to
- the pool and releases its slot; the winner is returned the moment it lands. When
- every hedged key fails, the attempt is ONE attempt for the storm / backoff
- accounting and the worst error decides the branch (a non-retryable error first,
- then a plain retryable one, a 429, a dead key, and a 503 last).
-
- ``stats`` (optional, caller-owned dict) receives the call's telemetry on the way
- out — success or failure: ``attempts`` = round-trips issued (hedged siblings
- included; 1 = clean), ``hedged`` = hedged attempts, ``storm`` = storm waits. A
- raised ``ModelError`` carries ``attempts`` itself (the cost ledger's error row);
- ``GeminiModel`` copies it into ``ChatResponse.raw`` on success.
-
- ``on_attempt`` (optional) hears every round-trip exactly once — see
- :data:`OnAttempt`; the cost layer uses it to write per-attempt ledger rows so a
- hedge loser's and a charged-but-invalid reply's tokens stop vanishing.
- Exceptions from the hook are swallowed: accounting must never break a call.
+ * success: report ok, bench keys that looked dead, return.
+ * ``on_free_retry(err)`` true: retry at once, free (e.g. thinking-config downgrade).
+ * dead key (auth failure): rotate free; benched only once a sibling key succeeds.
+ * 429 / 503 / 529: the key joins the call's failed set; rotation to an untried key is
+ free. Only when every key has failed within this call is a 503 a capacity storm:
+ up to ``storm_attempts`` waits (capped at ``storm_max_delay``) outside ``max_attempts``.
+ * other retryable errors: exponential backoff + jitter up to ``max_attempts``;
+ non-retryable raise at once.
+ * everything is bounded by ``max_total_s``.
+
+ Hedging (``hedge``; 1 disables): from the first 503/529 on, each attempt runs on up to
+ ``hedge`` distinct keys at once and the first success wins. Extra keys come from
+ ``try_acquire`` (never waited for); losers finish on their own and report to the pool and
+ ``on_attempt``. When all fail, the worst error decides the branch (``_severity``).
+
+ ``stats`` receives ``attempts``, ``hedged`` and ``storm`` counts. ``on_attempt`` hears
+ every round-trip once (exceptions from it are swallowed).
"""
failed_keys: set[str] = set() # keys that 429'd / 503'd or looked dead during this call
dead_keys: set[str] = set()
@@ -647,24 +492,21 @@ def rotate_with_retries[T](
winner: _Try | None = None
def bench() -> None:
- # mark keys that failed with key-scoped errors dead — called once the call
- # got past the auth layer on some other key (success, 429, 5xx, bad JSON …)
+ # bench dead-looking keys once another key got past the auth layer
for k in dead_keys:
pool.report(k, "dead")
dead_keys.clear()
def run_one(key: str) -> _Try:
- """One round-trip on ``key``: report its outcome to the pool and hand the slot
- back. Runs inline for a single key and in a worker thread when hedged, so it
- touches none of this call's state and never raises a ``ModelError`` itself."""
+ """One round-trip on ``key``: report to the pool and release the slot. Touches none of
+ this call's state (it may run in a hedge thread)."""
try:
try:
result = call(key)
except Exception as exc: # noqa: BLE001 - classification is delegated
err = classify(exc)
outcome = outcome_of(err)
- # a key that looks dead is reported "error" now and benched only once a
- # sibling proves the request itself is fine (bench())
+ # a dead-looking key is benched later, by bench()
pool.report(key, "error" if outcome == "dead" else outcome,
retry_after_s=retry_after(exc) if (outcome == "429" and retry_after) else None)
return _Try(key, None, err, exc, outcome)
@@ -674,10 +516,7 @@ def rotate_with_retries[T](
pool.release()
def run_attempt(keys: Sequence[str]) -> list[_Try]:
- """Issue ``call`` on every key; return the tries that completed up to and
- including the first success, in completion order. Losers still in flight
- finish on their own (``run_one`` reports and releases for them, and the
- ``on_attempt`` hook hears their tokens when they land)."""
+ """Issue ``call`` on every key; return tries completed up to the first success."""
first_no = counts["attempts"] + 1
counts["attempts"] += len(keys)
if len(keys) == 1:
@@ -699,8 +538,7 @@ def rotate_with_retries[T](
if t.err is None:
for other in futures:
if id(other) not in consumed_futs:
- # fires at once when the sibling already landed — either way
- # exactly once, so the hook still hears a loser's tokens
+ # fires once, at once if the sibling already landed
other.add_done_callback(
partial(_discard_loser, on_attempt=on_attempt,
attempt_no=nos[id(other)])
@@ -719,7 +557,7 @@ def rotate_with_retries[T](
return monotonic() >= deadline
def clip(delay: float) -> float:
- """A sleep never outlives the budget: waking only to give up helps nobody."""
+ """A sleep never outlives the budget."""
return delay if deadline == float("inf") else min(delay, max(0.0, deadline - monotonic()))
def gave_up(err: ModelError) -> ModelError:
@@ -732,16 +570,13 @@ def rotate_with_retries[T](
try:
while attempt < max_attempts:
if out_of_time() and last_err is not None:
- # checked wherever the loop can spend time, not only around the
- # sleeps: a free rotation must not out-live the caller's budget
+ # free rotations must not out-live the budget
raise gave_up(last_err) from cause_for(last_err, last_exc)
attempt += 1
- # never go back to a key that looked dead this call; throttled keys are
- # excluded while an untried one remains, else acquire() waits for a cooldown
+ # skip dead-looking keys; skip throttled ones while an untried key remains
exclude = dead_keys | (failed_keys if len(failed_keys) < len(pool) else set())
budget_left = None if deadline == float("inf") else max(0.0, deadline - monotonic())
try:
- # the key/slot wait must fit the remaining budget, never outlive it
keys = [pool.acquire(
exclude=exclude,
timeout_s=ACQUIRE_TIMEOUT_S if budget_left is None
@@ -755,8 +590,6 @@ def rotate_with_retries[T](
break # no fresh key / slot right now: never wait for a hedge partner
keys.append(extra)
tries = run_attempt(keys)
- # bookkeeping for every failed try of this attempt: a hedged loser's dead
- # key or 503 counts exactly as a lone one would
free = False
for t in tries:
if t.err is None:
@@ -773,7 +606,6 @@ def rotate_with_retries[T](
winner = won
bench()
return won.result
- # every key of this attempt failed: the worst error decides the branch
worst = min(tries, key=_severity)
err, exc, key = worst.err, worst.exc, worst.key
assert err is not None
@@ -783,8 +615,6 @@ def rotate_with_retries[T](
attempt -= 1
continue
if worst.outcome == "dead":
- # key-scoped: move on at once (no budget, no sleep); the key is only
- # benched once another key proves the request itself is fine
if len(dead_keys) < len(pool):
if out_of_time():
raise gave_up(err) from cause_for(err, exc)
@@ -795,22 +625,16 @@ def rotate_with_retries[T](
if is_storm(err) and storm < storm_attempts and not out_of_time():
failed_keys.update(t.key for t in tries)
if len(failed_keys) < len(pool):
- # a 503 is per key at any instant (see the docstring): the next
- # UNTRIED key is the cure — free rotation, no sleep, no budget,
- # no storm yet. Same rule as the 429 path: while an untried key
- # remains, rotation is free; it is only a storm once the WHOLE
- # pool has 503'd inside this one call.
+ # a 503 is per key: while an untried key remains rotation is free
attempt -= 1
log.warning("%s key …%s 503 (%s); rotating to a fresh key (%d/%d tried%s)",
label, key[-4:], err, len(failed_keys), len(pool),
f", hedging x{hedge}" if hedging else "")
continue
- # capacity storm: EVERY key in the pool said 503 in this call, so
- # waiting is the only cure — paid from its own budget, not max_attempts
+ # capacity storm: every key said 503, so wait (own budget, not max_attempts)
storm += 1
counts["storm"] = storm
- # jitter FIRST, cap LAST: capping before a >1 jitter factor let a
- # "<=5 s" wait land at 6.25 s in the wild (observed 2026-08-24).
+ # jitter first, cap last, so the wait never exceeds the cap
raw = base_delay * (2 ** min(storm, 8)) * (0.75 + 0.5 * random.random())
delay = clip(min(storm_max_delay, raw))
log.warning("%s capacity storm %d/%d (%s); waiting %.0fs",
@@ -823,7 +647,6 @@ def rotate_with_retries[T](
if len(failed_keys) < len(pool):
if out_of_time():
raise gave_up(err) from cause_for(err, exc)
- # an untried key remains: rotation is free, only a courtesy pause
attempt -= 1
log.warning(
"%s key …%s throttled (%s); rotating to a fresh key", label, key[-4:], err
@@ -852,8 +675,7 @@ def rotate_with_retries[T](
if stats is not None:
stats.update(counts)
if on_attempt is not None:
- # flush every completed round-trip now that the winner is known; a hedge
- # loser still in flight reports itself when it lands (_discard_loser)
+ # flush completed round-trips; a loser still in flight reports via _discard_loser
for no, t in finished:
try:
on_attempt(t, no, t is not winner)
@@ -873,8 +695,7 @@ class _Try:
def _severity(t: _Try) -> int:
- """Rank a failed try so the worst one decides a hedged attempt's branch:
- non-retryable (0) < plain retryable (1) < 429 (2) < dead key (3) < 503/529 (4)."""
+ """Rank a failed try: non-retryable 0 < retryable 1 < 429 2 < dead key 3 < 503/529 4."""
err = t.err
assert err is not None
if t.outcome == "dead":
@@ -889,10 +710,7 @@ def _severity(t: _Try) -> int:
def _discard_loser(
fut: Future[_Try], on_attempt: OnAttempt | None = None, attempt_no: int = 0
) -> None:
- """A hedged sibling that finished after the winner: its pool report and slot
- release already happened in ``run_one``; here it is logged and handed to the
- ``on_attempt`` hook — always as discarded, a late success included — so its
- paid tokens reach the cost ledger at all."""
+ """A hedge sibling that finished after the winner: handed to ``on_attempt`` as discarded."""
try:
t = fut.result()
except BaseException as exc: # noqa: BLE001 - a crashed loser must not crash the caller
diff --git a/harness/codeverse3d/models/schema_utils.py b/harness/codeverse3d/models/schema_utils.py
index acec1e2f..501de603 100644
--- a/harness/codeverse3d/models/schema_utils.py
+++ b/harness/codeverse3d/models/schema_utils.py
@@ -1,23 +1,9 @@
"""JSON-schema adapters for the three providers, a fence-tolerant JSON parser and
``ask_structured`` (one schema-validated call → object | None, usage, error).
-Pydantic v2 emits ``$defs``/``$ref``, ``title``, ``default``, ``const``,
-``prefixItems`` (tuples), ``anyOf [.., {"type":"null"}]`` and so on. Each
-provider accepts a different subset:
-
-* Gemini ``response_schema`` / function ``parameters``: OpenAPI-ish subset —
- no ``$ref``, no ``additionalProperties``, no ``const``, no ``prefixItems``;
- ``nullable`` instead of null unions; ``propertyOrdering`` controls key order.
-* OpenAI strict ``json_schema``: every object needs ``additionalProperties:
- false`` and ``required`` listing every property; ``$defs`` are fine. Optional
- fields keep their own type — null is allowed only where the source schema
- already allows it (``anyOf [T, null]``); a non-null ``default`` is hinted in
- the description. So the wire contract equals the pydantic one and the model
- never returns ``null`` where the contract wants ``""`` / ``1`` / ``[]``.
-* Anthropic tool ``input_schema`` / ``output_config.format``: standard JSON
- schema; we inline refs to be safe and set ``additionalProperties: false``.
-
-All functions are pure and return new dicts (inputs are never mutated).
+Pydantic schemas are rewritten per provider: Gemini takes an OpenAPI-ish subset, OpenAI strict
+needs closed objects with every property required, Anthropic takes inlined standard JSON schema.
+All functions are pure and return new dicts.
"""
from __future__ import annotations
@@ -58,9 +44,7 @@ _GEMINI_DROP = {
# ----------------------------------------------------------------- $ref inline
def inline_refs(schema: dict[str, Any]) -> dict[str, Any]:
- """Return a copy with every local ``$ref`` (``#/$defs/X`` / ``#/definitions/X``)
- replaced by the referenced definition and the defs tables removed.
- Recursive schemas raise ``ValueError`` (providers can't express them anyway)."""
+ """Copy with every local ``$ref`` replaced by its definition; recursive schemas raise ``ValueError``."""
root = copy.deepcopy(schema)
defs: dict[str, Any] = {}
for table in ("$defs", "definitions"):
@@ -79,7 +63,6 @@ def inline_refs(schema: dict[str, Any]) -> dict[str, Any]:
if name in stack:
raise ValueError(f"recursive $ref {ref!r} cannot be inlined")
merged = dict(defs[name])
- # siblings of $ref (e.g. description) override the definition's
for k, v in node.items():
if k != "$ref":
merged[k] = v
@@ -97,7 +80,7 @@ def _is_null(s: Any) -> bool:
def _merge_prefix_items(node: dict[str, Any]) -> dict[str, Any]:
- """Tuples → arrays: ``prefixItems`` becomes ``items`` (union if heterogeneous)."""
+ """``prefixItems`` becomes ``items`` (union if heterogeneous)."""
items = node.pop("prefixItems")
if not isinstance(items, list) or not items:
return node
@@ -113,8 +96,7 @@ def _merge_prefix_items(node: dict[str, Any]) -> dict[str, Any]:
# --------------------------------------------------------------------- gemini
def to_gemini_schema(schema: dict[str, Any]) -> dict[str, Any]:
- """Sanitise a pydantic JSON schema for ``GenerateContentConfig.response_schema``
- / ``FunctionDeclaration.parameters`` (see module docstring)."""
+ """Sanitise a pydantic JSON schema for Gemini ``response_schema`` / function ``parameters``."""
root = inline_refs(schema)
def walk(node: Any) -> Any:
@@ -123,17 +105,14 @@ def to_gemini_schema(schema: dict[str, Any]) -> dict[str, Any]:
if not isinstance(node, dict):
return node
node = {k: v for k, v in node.items() if k not in _GEMINI_DROP}
- # const → enum
if "const" in node:
node["enum"] = [node.pop("const")]
node.setdefault("type", _json_type(node["enum"][0]))
- # type: ["string","null"] → type + nullable
if isinstance(node.get("type"), list):
types = [t for t in node["type"] if t != "null"]
if len(types) != len(node["type"]):
node["nullable"] = True
node["type"] = types[0] if len(types) == 1 else types
- # anyOf/oneOf with null → nullable
for key in ("anyOf", "oneOf"):
if key in node:
variants = [v for v in node[key] if not _is_null(v)]
@@ -151,12 +130,11 @@ def to_gemini_schema(schema: dict[str, Any]) -> dict[str, Any]:
node = {**inner, **node}
if "prefixItems" in node:
node = _merge_prefix_items(node)
- # enum values must be strings for Gemini; keep type consistent
+ # Gemini enums are strings only
if "enum" in node:
node["enum"] = [str(v) if not isinstance(v, str) else v for v in node["enum"]]
node["type"] = "string"
node.pop("format", None)
- # format: only a few are accepted
if (
"format" in node
and node.get("type") == "string"
@@ -170,7 +148,7 @@ def to_gemini_schema(schema: dict[str, Any]) -> dict[str, Any]:
if props:
node["propertyOrdering"] = list(props.keys())
else:
- # Gemini rejects empty OBJECT properties; describe as free-form
+ # Gemini rejects empty OBJECT properties
node.pop("properties")
node.pop("propertyOrdering", None)
if "items" in node:
@@ -196,9 +174,7 @@ def _json_type(value: Any) -> str:
# ------------------------------------------------------------ openai / anthropic
def _walk_schema(root: Any, on_object: Callable[[dict[str, Any], Callable[[Any], Any]], None]) -> Any:
- """The walk the strict (openai) and the anthropic schema share: drop metadata, flatten
- tuples, recurse into combinators and items. ``on_object(node, walk)`` rewrites a node's
- ``properties`` — the one place the two differ."""
+ """Walk shared by the openai-strict and anthropic schemas; ``on_object(node, walk)`` rewrites ``properties``."""
def walk(node: Any) -> Any:
if isinstance(node, list):
@@ -223,12 +199,8 @@ def _walk_schema(root: Any, on_object: Callable[[dict[str, Any], Callable[[Any],
def to_openai_strict_schema(schema: dict[str, Any]) -> dict[str, Any]:
- """OpenAI *strict* structured outputs: every object gets
- ``additionalProperties: false`` and ``required`` = all properties. Optional
- fields keep their type: null is accepted only where the source already says
- so (``x: T | None``), never added — the consumer validates with the original
- pydantic model, which rejects ``null`` for ``x: str = ""`` / ``list = []``.
- A non-null ``default`` becomes a ``[default: …]`` hint. ``$defs`` are inlined."""
+ """OpenAI strict schema: closed objects, every property required. Null is allowed only
+ where the source allows it; a non-null ``default`` becomes a ``[default: …]`` hint."""
def strict_object(node: dict[str, Any], walk: Callable[[Any], Any]) -> None:
props = {k: walk(v) for k, v in node["properties"].items()}
@@ -248,15 +220,14 @@ def to_openai_strict_schema(schema: dict[str, Any]) -> dict[str, Any]:
def _with_default_hint(sub: dict[str, Any], default: Any) -> dict[str, Any]:
- """Keep the field non-null; tell the model what to emit when it has nothing."""
+
hint = f"[default: {json.dumps(default)}]"
desc = str(sub.get("description") or "").strip()
return {**sub, "description": f"{desc} {hint}".strip()}
def to_anthropic_schema(schema: dict[str, Any]) -> dict[str, Any]:
- """Standard JSON schema with refs inlined, tuples flattened and
- ``additionalProperties: false`` on objects (tool ``input_schema`` / format)."""
+ """Standard JSON schema, refs inlined, objects closed."""
def closed_object(node: dict[str, Any], walk: Callable[[Any], Any]) -> None:
node["properties"] = {k: walk(v) for k, v in node["properties"].items()}
@@ -275,8 +246,7 @@ class JsonParseError(ValueError):
def _first_balanced(text: str, opener: str = "{", closer: str = "}") -> str | None:
- """The first depth-balanced ``{...}`` span (naive counting; braces inside JSON
- strings can fool it, which is why it is only one candidate among several)."""
+ """The first depth-balanced ``{...}`` span (naive: braces inside strings can fool it)."""
start = text.find(opener)
if start < 0:
return None
@@ -291,27 +261,15 @@ def _first_balanced(text: str, opener: str = "{", closer: str = "}") -> str | No
return None
-#: C0 control characters that are never legitimate inside a model's text field. TAB,
-#: LF and CR are kept — they carry meaning in a description or a code snippet.
+#: C0 control characters except TAB, LF and CR
_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
-#: what a stripped control character is replaced BY. A space, not "": the observed case
-#: was a model writing \u0000 where it meant a glyph it could not encode ("0.078 × 0.300"
-#: -> "0.078 \x00 0.300"), and deleting the byte would silently fuse "0.078" and "0.300"
-#: into a different number. A space keeps the text honest and readable.
+#: replaced by a space, not "": deleting could fuse adjacent numbers
_CONTROL_SUB = " "
def strip_control_chars(value: Any) -> Any:
- """Recursively replace C0 control characters in every string of a parsed JSON value.
-
- A model can emit ``\u0000`` — it is legal JSON, pydantic accepts it, and the harness
- persists it happily. It then detonates far away: on 2026-08-24 a gemini-3.7-flash
- plan carried five of them (written where the model meant ``×`` and ``±``), survived
- validation and ``plan.json``, and killed all four generation tasks of a codex cell
- four stages later with ``ValueError: embedded null byte`` out of ``subprocess.Popen``
- — an error naming no file, no field and no value. Sanitising at ingestion is the
- only place that covers every model, every track and every downstream consumer.
- """
+ """Replace C0 control characters in every string of a parsed JSON value (a NUL later
+ crashes ``subprocess.Popen`` far from its source)."""
if isinstance(value, str):
return _CONTROL_RE.sub(_CONTROL_SUB, value)
if isinstance(value, dict):
@@ -322,10 +280,7 @@ def strip_control_chars(value: Any) -> Any:
def parse_json_lenient(text: str) -> Any:
- """Parse JSON from model text tolerating code fences, leading prose and
- trailing chatter. Tries: whole text → fenced block → first balanced {...}
- → outermost {...} / [...] span. Raises ``JsonParseError`` when nothing
- parses."""
+ """Parse JSON from model text tolerating fences, leading prose and trailing chatter."""
if text is None:
raise JsonParseError("empty response")
s = text.strip()
@@ -347,7 +302,6 @@ def parse_json_lenient(text: str) -> Any:
return strip_control_chars(json.loads(cand))
except json.JSONDecodeError as exc:
last_err = exc
- # tolerate trailing commas
fixed = re.sub(r",\s*([}\]])", r"\1", cand)
if fixed != cand:
try:
@@ -360,15 +314,7 @@ def parse_json_lenient(text: str) -> Any:
def ask_structured(model: Any, schema: type[BaseModel], *, system: str, text: str,
images: Sequence[ImagePart] = (), temperature: float,
label: str) -> tuple[Any, Usage, str]:
- """One structured call → ``(validated object | None, usage, error)``.
-
- Several callers (the reference mismatch diff, the planner's brief, ...) built the same ChatRequest
- (thinking="low", the 65 536 ceiling, the 900 s wait), caught the same two failure
- families and parsed the same two ways. They differ only in what they RETURN on
- failure, which is why this hands the error back rather than raising or deciding.
- Not for callers that need to separate parse errors from call errors
- (``judges.pairwise``, ``tracks.planner.plan``).
- """
+ """One structured call → ``(validated object | None, usage, error)``; failures are returned, not raised."""
req = ChatRequest(messages=[ChatMessage.user(text, images=list(images) or None)], system=system,
response_schema=schema.model_json_schema(), temperature=temperature,
thinking="low", max_output_tokens=65_536, max_wait_s=900.0, label=label)
@@ -376,8 +322,7 @@ def ask_structured(model: Any, schema: type[BaseModel], *, system: str, text: st
resp = model.generate(req)
except ModelError as e: # e.usage is what the provider ALREADY billed for the failure
return None, e.usage, f"call failed: {e}"
- try: # the parse is inside: every provider raises ModelError first today, but this
- # function must not depend on all three keeping that half of the ChatModel contract
+ try:
payload = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text)
return schema.model_validate(payload), resp.usage, ""
except (JsonParseError, ValidationError, TypeError) as e:
diff --git a/harness/codeverse3d/orchestrator.py b/harness/codeverse3d/orchestrator.py
index dae8e7be..a1fcc727 100644
--- a/harness/codeverse3d/orchestrator.py
+++ b/harness/codeverse3d/orchestrator.py
@@ -1,10 +1,4 @@
-"""Orchestration: the stage runner with resume, run state, the round policy
-(RoundPolicy), refine-task compilation and the budget clock.
-
-One module since 2026-08-28: the seven-file package predates the 1,500-line cap,
-nobody ever imported the package itself, and refine_tasks existed only to be
-re-exported by rounds. candidates.py moved into tracks/candidates.py earlier.
-"""
+"""Orchestration."""
from __future__ import annotations
@@ -36,15 +30,11 @@ log = logging.getLogger(__name__)
# ===================================================================== state
class StageState(BaseModel):
- """One completed stage: its inputs hash (the result JSON is at ``stages/<name>.json``)."""
inputs_hash: str
class RunState(BaseModel):
- """Everything the orchestrator needs to resume a run — except the round history, which is
- the round journal's alone (``rounds/rNN.json`` + each round's commit; ``lifecycle.reconcile_resume``
- reads it)."""
status: RunStatus = RunStatus.PLANNING
stages: dict[str, StageState] = Field(default_factory=dict)
@@ -112,21 +102,14 @@ def _jsonable(obj: Any) -> Any:
class StageRunner:
- """Runs stages with resume semantics on top of ``RunState`` + ``EventLog``.
-
- ``frozen`` (the run already has rounds): a stage with a recorded result serves it even when
- its key drifted (``stage.frozen``) — the rounds refined what it wrote, and re-running it would
- re-pay its session and overwrite that work. ``resume --force`` archives the rounds to
- ``rounds/pre_force/`` whether or not the spec changed (``reconcile_resume``), so the run starts
- again at round 0 unfrozen — the one way to regenerate a stage under existing rounds."""
+ """Runs stages with resume semantics on top of ``RunState`` + ``EventLog``."""
def __init__(self, ws: Workspace, events: EventLog, state: RunState | None = None, *, frozen: bool = False):
self.ws = ws
self.events = events
self.state = state if state is not None else RunState()
self.frozen = frozen
- #: the scene baseline fans sibling stages out in parallel; the bookkeeping
- #: (``state.stages`` + the ``run_state.json`` save) must not interleave
+ #: stage bookkeeping + ``run_state.json`` save must not interleave across parallel stages
self._lock = threading.Lock()
# ----------------------------------------------------------------- paths
@@ -143,21 +126,13 @@ class StageRunner:
model: type[BaseModel] | None = None,
timed_step: bool = True,
) -> T:
- """Run ``fn`` unless a cached result for the same ``inputs`` exists. A stage that runs
- is a timed step of the run (``RunState.steps``) — unless ``timed_step=False``: a stage
- that runs beside its siblings is timed once, as their group, by its caller."""
+ """Run ``fn`` unless a cached result for the same ``inputs`` exists."""
h = hash_inputs(inputs)
path = self.result_path(name)
prior = self.state.stages.get(name)
if prior is not None and (prior.inputs_hash == h or self.frozen) and path.is_file():
- # A cached result that cannot be read back is a cache MISS, not a dead run.
- # ``inputs_hash`` covers the INPUTS only, never the result model's schema, so a
- # contract that gained a field invalidates nothing — and a clobbered file
- # invalidates nothing either. Both used to escape as ValidationError /
- # JSONDecodeError through BaseTrack.run, which marks the run FAILED and
- # re-raises, so every later `3dcode resume <slug>` died the same way with no way
- # out (there is no flag to drop a cached stage). Re-run instead and
- # overwrite the file — the same tolerance load_ledger and _read_jsonl apply.
+ # A cached result that cannot be read back (schema drift, clobbered file) is a
+ # cache MISS: re-run and overwrite instead of dying on every resume.
try:
result = _revive(json.loads(path.read_text()), model)
except (OSError, ValueError) as e: # ValidationError is a ValueError
@@ -252,16 +227,6 @@ def build_refine_instructions(
max_tasks: int = 6,
extra: Sequence[RefineTask] = (),
) -> list[RefineTask]:
- """Gate ERRORS first (with fix hints) — a part still the skeleton's placeholder
- (``PLACEHOLDER_PART``) ahead of every other gate ERROR —, then ``extra`` harness-derived tasks
- (e.g. reference-silhouette mismatch), then failed *must* acceptance items,
- then the judge's improvement plan; de-duplicated by (target, kind, finding kind), capped.
- Gate/acceptance/extra tasks are never dropped by the cap unless they alone exceed it.
-
- The finding kind (``GateFinding.data["kind"]``) is part of a gate task's key (D111): with
- (target, ``gate:<gate>``) alone every env ERROR of ``scene_placement`` collapsed into the
- first, so ``no_fog`` hid ``no_background`` from the refine prompt (argon loop iteration 4,
- r1_08 / r1_10). Two findings of one kind on one target are still one task."""
known = _known_targets(plan)
tasks: list[RefineTask] = []
seen: set[tuple[str, str, str]] = set()
@@ -302,10 +267,7 @@ def build_refine_instructions(
def plan_parallel_groups(tasks: Sequence[RefineTask]) -> list[TaskGroup]:
- """Group tasks by file ownership. Tasks with unknown files (``[]``) cannot
- be isolated, so if any exists everything collapses into ONE group (a single
- whole-object task). Otherwise groups are the connected components of the
- "shares a file" relation — each group may run concurrently with the others."""
+ """Group tasks by file ownership."""
if not tasks:
return []
if any(not t.files for t in tasks):
@@ -343,12 +305,7 @@ def plan_refine_groups(
allow_fanout: bool = True,
parallel_min_tasks: int = 2,
) -> tuple[list[TaskGroup], bool]:
- """The ONE grouping rule of the refine scaffold (``BaseTrack.refine_tasks``).
-
- Groups by file ownership via :func:`plan_parallel_groups`; the groups run in
- parallel only when fan-out is allowed for the track, at least
- ``parallel_min_tasks`` file-disjoint groups exist and every group owns
- files. Otherwise everything collapses into ONE whole-artifact group."""
+ """The ONE grouping rule of the refine scaffold (``BaseTrack.refine_tasks``)."""
groups = plan_parallel_groups(tasks)
parallel = allow_fanout and len(groups) >= parallel_min_tasks and all(g.files for g in groups)
if not parallel:
@@ -357,10 +314,7 @@ def plan_refine_groups(
def compact_instructions(tasks: Sequence[RefineTask], max_lines: int = 6) -> list[str]:
- """The instruction lines handed to ONE generation task: grouped by target
- (instances ``Leg_0``/``Leg_1`` fold into ``Leg``), ordered by priority, capped
- at ``max_lines``. A flash-class agent given 12 near-identical connectivity
- errors fixes none; given "FrontLeg: (a) … (b) …" it fixes the part."""
+ """The instruction lines handed to ONE generation task."""
if not tasks:
return []
groups: dict[str, list[RefineTask]] = {}
@@ -407,8 +361,7 @@ def _known_targets(plan: Plan | None) -> dict[str, str]:
def _canon_target(target: str, known: dict[str, str]) -> str:
- """Plan name for ``target``; instance suffixes (``Leg_1``, ``leg.2``) keep the
- suffix but take the plan's spelling of the base name."""
+ """Plan name for ``target``."""
hit = known.get(to_snake(target))
if hit is not None:
return hit
@@ -433,33 +386,24 @@ def _acceptance_target(item: AcceptanceItem, known: dict[str, str]) -> str:
# ===================================================================== rounds
@dataclass(frozen=True)
class RoundPolicy:
- """The refine loop's knobs. There is no stop knob besides ``max_rounds``: a run is the
- baseline plus ``max_rounds`` refine rounds, cut short only by the clock or a hard
- failure (owner, 2026-09-22 — the pass / plateau / regression / diminishing-returns
- stops, the rewrite and the surface-detail rounds they drove are gone)."""
+ """The refine loop's knobs."""
max_rounds: int = 4 # refine rounds AFTER the baseline
max_refine_tasks: int = 6
max_instructions_per_task: int = 6 # lines handed to ONE generation task (grouped by target)
parallel_min_tasks: int = 2 # fan out only when >= this many file-disjoint groups
n_candidates: int = 1 # best-of-N baseline (candidates generated in parallel, best kept)
- judge_samples: int = 1 # VLM judge samples per round (flash: std ≈ 0.001 between samples → 1 is enough)
- #: seconds of the hard clock a refine / rebuild session leaves for its round's build, gates, render
- #: and judge (D112: 201 s measured for iteration 5 r1_09 — build 11 s, render 24 s, judge 166 s)
+ judge_samples: int = 1
+ #: seconds of the hard clock a refine session leaves for build, gates, render and judge
judge_reserve_s: float = 240.0
- #: the shortest AGENT session window worth opening; with ``judge_reserve_s`` it is what a refine
- #: round, a transport / stall retry or a stage retry needs left on the clock before it is launched
- #: (D112). A single-shot call has no session window: it needs the judge reserve only.
+ #: shortest agent session window worth opening; a single-shot call needs only the judge reserve
min_session_s: float = 180.0
def need_s(self, *, single_shot: bool = False) -> float:
- """What :meth:`can_open` asks of the clock: the judge reserve, plus the minimum session window
- when the generation is an agent session."""
+ """What :meth:`can_open` asks of the clock."""
return self.judge_reserve_s + (0.0 if single_shot else self.min_session_s)
def can_open(self, budget: BudgetGuard, *, single_shot: bool = False) -> bool:
- """Does the hard clock still hold :meth:`need_s` — a minimum session window (agent sessions
- only) plus the judge reserve?"""
return budget.left_s() >= self.need_s(single_shot=single_shot)
@@ -477,14 +421,7 @@ class BudgetExceeded(RuntimeError):
class BudgetGuard:
- """The run's clock against ``Budget.max_minutes`` — a LIMIT, not a statistic.
-
- It counts every active second, provider errors included, because it has to stop a run
- even in a 503 storm; the run's minutes (``RunRecord.minutes``, docs/COST.md §31) leave
- those errors out and never stop anything. ``check`` raises ``BudgetExceeded`` past the
- ceiling; ``ok`` is its non-raising twin. Money is not the guard's (2026-09-22): the
- ledger, ``telemetry/cost.jsonl``, is the one record of it.
- """
+ """The run's clock against ``Budget.max_minutes`` — a LIMIT, not a statistic."""
def __init__(
self,
@@ -495,8 +432,7 @@ class BudgetGuard:
):
self.budget = budget
self.start_time = time.time() if start_time is None else start_time
- #: ACTIVE seconds carried over from previous sessions of this run (``restore``
- #: sets it from the snapshot); downtime between sessions never counts.
+ #: ACTIVE seconds carried over from previous sessions of this run.
self._active_s: float = 0.0
self._lock = threading.Lock()
#: fraction of the hard ceiling the *baseline* may use (1.0 = no soft cap)
@@ -506,25 +442,18 @@ class BudgetGuard:
# ----------------------------------------------------------------- resume snapshot
def snapshot(self) -> BudgetSnapshot:
- """The clock for ``run_state.json``, so a resume continues the SAME budget instead of
- a fresh one. Grace and config are deliberately absent: grace is one attempt's salvage
- headroom — persisting it would ratchet the hard ceiling run over run, and the ceiling
- always comes from the current spec."""
+ """The clock for ``run_state.json``, so a resume continues the SAME budget instead of a fresh one."""
with self._lock:
return BudgetSnapshot(active_s=self._active_s + (time.time() - self.start_time))
def restore(self, snap: BudgetSnapshot) -> None:
- """Adopt a snapshot: ``start_time`` stays *now*, so ``elapsed_minutes`` is prior ACTIVE
- seconds plus this session — never the downtime in between. The ceiling comes from
- the (possibly raised) spec budget, so a raised cap (``--max-minutes``) grants exactly
- the difference, never a fresh full cap."""
+ """Adopt a snapshot."""
with self._lock:
self._active_s = float(snap.active_s)
self.start_time = time.time()
def elapsed_minutes(self) -> float:
- """Cumulative ACTIVE minutes: prior sessions' seconds (restored from the
- snapshot) plus this session's wall clock. Downtime costs nothing."""
+ """Cumulative ACTIVE minutes."""
return (self._active_s + (time.time() - self.start_time)) / 60.0
# ----------------------------------------------------------------- ceilings
@@ -533,9 +462,7 @@ class BudgetGuard:
return self.budget.max_minutes + self.grace_minutes
def grant_grace(self, *, minutes: float = 0.0) -> None:
- """Extend the HARD wall-clock ceiling (never shrink it). Used once by finalise /
- salvage so a run that tripped the clock mid-stage can still deliver a judged
- round instead of no score at all."""
+ """Extend the HARD wall-clock ceiling (never shrink it)."""
with self._lock:
self.grace_minutes = max(self.grace_minutes, max(0.0, float(minutes)))
@@ -571,11 +498,7 @@ class BudgetGuard:
return True
def timeout_s(self, want_s: float, *, floor_s: float = 60.0, soft: bool = True) -> int:
- """``want_s`` clipped to the wall-clock actually left (soft cap when ``soft``).
-
- A generation session must never be allowed to outlive the run's budget:
- the greenhouse scene lost 54 minutes to zone agents that kept working
- after the ceiling had already been crossed."""
+ """``want_s`` clipped to the wall-clock actually left (soft cap when ``soft``)."""
left = max(0.0, (self.soft_minutes() if soft else self.hard_minutes) - self.elapsed_minutes()) * 60.0
return int(max(floor_s, min(float(want_s), left) if left > 0 else floor_s))
@@ -589,7 +512,6 @@ class BudgetGuard:
class BudgetSnapshot(BaseModel):
- """What survives a resume (``run_state.extra["budget_snapshot"]``): cumulative ACTIVE
- seconds."""
+ """What survives a resume (``run_state.extra["budget_snapshot"]``)."""
active_s: float = 0.0
diff --git a/harness/codeverse3d/proc.py b/harness/codeverse3d/proc.py
index 99742d26..a5ddb99b 100644
--- a/harness/codeverse3d/proc.py
+++ b/harness/codeverse3d/proc.py
@@ -1,14 +1,8 @@
"""Process-level primitives shared across the harness.
-One home for the run-a-child-process pattern (own process group, wall-clock
-timeout, group kill, bounded captured output — :class:`ManagedProcess` and its
-thin wrapper :func:`run_subprocess`), the tmp+rename JSON write, the tolerant
-JSON / JSONL readers every "best effort" side-car consumer needs, the run's event
-stream (:class:`EventLog`, :data:`NULL_EVENTS`), the per-run mutex
-(:func:`exclusive`) and the context-carrying thread fan-out (:func:`fan_out`). Peer
-of ``workspace.py``; stdlib-only — imports nothing from ``codeverse3d`` so wrappers,
-spatial helpers and agents can all use it without layering back-edges.
-
+Run-a-child-process (:class:`ManagedProcess`, :func:`run_subprocess`), atomic JSON writes, tolerant
+JSON / JSONL readers, the event stream (:class:`EventLog`), the per-run mutex (:func:`exclusive`)
+and the context-carrying :func:`fan_out`. Stdlib-only: imports nothing from ``codeverse3d``.
"""
from __future__ import annotations
@@ -35,8 +29,6 @@ from typing import IO, Any
@dataclass(frozen=True)
class ProcResult:
- """Outcome of one subprocess run."""
-
returncode: int
stdout: str
stderr: str
@@ -55,21 +47,9 @@ def run_subprocess(
) -> ProcResult:
"""Run ``cmd`` in its own process group; kill the whole group on timeout.
- Never raises on non-zero exit — callers inspect :attr:`ProcResult.returncode`.
- ``preexec_fn`` runs in the child before exec (e.g. rlimits); the child is
- always started in a new session so the group kill reaps grandchildren.
-
- Thin wrapper over :class:`ManagedProcess` since 2026-08-27, which changed three
- behaviours on purpose:
-
- * output decodes as utf-8 ``errors="replace"`` — one bad byte used to raise
- UnicodeDecodeError out of ``communicate()`` and lose the whole result;
- * each stream is capped at :data:`STREAM_BUDGET_BYTES` (head + tail kept, a
- truncation marker in between) instead of growing unbounded in RAM;
- * KeyboardInterrupt — or any exception — mid-run kills the process group before
- propagating. ``start_new_session`` children sit outside the terminal's
- foreground group, so Ctrl-C's SIGINT never reaches them: without this, every
- interrupt during a blender/node/render run orphaned the whole tree.
+ Never raises on non-zero exit. Output decodes as utf-8 ``errors="replace"`` and each stream is
+ capped at :data:`STREAM_BUDGET_BYTES`; any exception mid-run (Ctrl-C included) kills the group.
+ ``preexec_fn`` runs in the child before exec (e.g. rlimits).
"""
t0 = time.monotonic()
timed_out = False
@@ -78,7 +58,7 @@ def run_subprocess(
mp.wait(timeout=timeout_s)
except subprocess.TimeoutExpired:
timed_out = True
- mp.kill() # straight SIGKILL on the group, as this path has always behaved
+ mp.kill()
return ProcResult(
returncode=mp.returncode if mp.returncode is not None else -1,
stdout=mp.stdout_text,
@@ -88,18 +68,14 @@ def run_subprocess(
)
-#: how long to keep draining the pipes after the child is dead. Kept from the old
-#: ``_drain_after_kill`` (and ``agents/watchdog.py``'s ``thread.join(timeout=10)``);
-#: a descendant that setsid'd or daemonised while inheriting stdout/stderr keeps the
-#: pipes open with no upper bound, and waiting on it silently voided ``timeout_s``
-#: for every build/render path that funnels through here.
+#: how long to keep draining the pipes after the child is dead; a daemonised descendant holding
+#: the pipes open would otherwise void ``timeout_s``.
DRAIN_TIMEOUT_S = 10.0
_ABANDONED = "(output truncated: a detached descendant still held the pipe past the drain window)"
_STILL_HELD = "(output truncated: a process in the group still held the pipe past the drain window)"
def _group_alive(pgid: int) -> bool:
- """True while ANY member of process group ``pgid`` exists (the leader may be gone)."""
try:
os.killpg(pgid, 0)
except (ProcessLookupError, PermissionError):
@@ -107,29 +83,15 @@ def _group_alive(pgid: int) -> bool:
return True
-#: per-stream cap on captured output: the first ``budget // 2`` bytes and the last
-#: ``budget - budget // 2`` bytes are kept, with a truncation marker in between.
-#: 8 MiB per stream — roomy for real build/render logs, while a runaway print loop
-#: 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.
+#: per-stream cap on captured output: head and tail halves are kept with a marker between.
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
-#: budget could apply; a line longer than this reaches ``on_line`` as several
-#: chunk-sized calls.
+#: longest chunk one pump read returns (bounds RAM when a child prints no newline).
_LINE_CAP_BYTES = 1024 * 1024
class _BoundedSink:
- """Head+tail byte buffer for ONE stream (first half of the budget from the head,
- last half from the tail, everything between counted and replaced by a marker).
-
- The lock only pairs one pump thread's ``feed`` with a late ``text`` read — it is
- never contended in the normal path (``text`` runs after the pump is joined).
- """
-
def __init__(self, budget: int) -> None:
self._lock = threading.Lock()
self._head_max = budget // 2
@@ -155,7 +117,6 @@ class _BoundedSink:
self._dropped += len(gone)
def text(self) -> str:
- """Decoded output — ``errors="replace"``, so a bad byte costs one U+FFFD, not the run."""
with self._lock:
head = self._head.decode("utf-8", errors="replace")
tail_part = b"".join(self._tail).decode("utf-8", errors="replace")
@@ -170,28 +131,11 @@ class _BoundedSink:
class ManagedProcess:
"""A ``Popen`` in its own session whose process group cannot outlive the ``with`` block.
- The shared lifecycle core under :func:`run_subprocess` and
- ``agents/cli_common.run_with_watchdog`` (which keep their public signatures):
-
- * binary pipes + two pump threads feeding a :class:`_BoundedSink` per stream
- (:data:`STREAM_BUDGET_BYTES` each, decoded utf-8 ``errors="replace"``);
- * an optional ``on_line(stream, line)`` observer called from the pump threads for
- every line (``stream`` is ``"stdout"``/``"stderr"``, the line is decoded with
- its trailing newline stripped; a line longer than :data:`_LINE_CAP_BYTES`
- arrives as several chunk-sized calls; observer exceptions are suppressed);
- * a stdin WRITER THREAD — a child that never reads a >64 KiB pipe-buffer of
- stdin can no longer wedge the caller's main thread in ``stdin.write`` (every
- agent CLI gets its prompt on stdin, up to hundreds of kB);
- * ``__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 → :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 zombie
- is left. A descendant that setsid'd away and still holds a pipe cannot stall
- the drain: closing the stream from this thread would block on the buffer lock
- the parked reader holds (measured), so the stuck pump is flagged to stop, drops
- its in-flight chunk, and self-cleans whenever its read finally returns —
- ``stderr_text`` then carries a truncation note.
+ Shared core of :func:`run_subprocess` and ``agents/cli_common.run_with_watchdog``: two pump
+ threads feed a bounded sink per stream, an optional ``on_line(stream, line)`` observer sees
+ each line (exceptions suppressed), and stdin is written from its own thread. ``__exit__``
+ on any exception, or with the child still running, SIGTERMs the group (SIGKILL after
+ :data:`TERMINATE_GRACE_S`), drains the pumps for at most :data:`DRAIN_TIMEOUT_S` and reaps.
"""
def __init__(
@@ -208,8 +152,7 @@ class ManagedProcess:
self._stop = threading.Event() # tells an abandoned pump to quit feeding
self._abandoned = "" # the truncation note to append, once we know which one
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 begun
+ # started and registered under the guard so a stop can neither miss this group nor race a new one
with _LIVE_GUARD:
if _STOPPING.is_set():
raise ProcessStopping(f"not starting {cmd[0]!r}: this process is stopping")
@@ -271,17 +214,14 @@ class ManagedProcess:
return self.proc.poll()
def wait(self, timeout: float | None = None) -> int:
- """``Popen.wait`` — raises ``subprocess.TimeoutExpired`` exactly like it."""
return self.proc.wait(timeout=timeout)
@property
def stdout_text(self) -> str:
- """Decoded, bounded stdout. Complete only once the ``with`` block has exited."""
return self._sinks["stdout"].text()
@property
def stderr_text(self) -> str:
- """Decoded, bounded stderr (+ a note when an escaped descendant held the pipe)."""
text = self._sinks["stderr"].text()
if self._abandoned:
return f"{text}\n{self._abandoned}" if text else self._abandoned
@@ -289,7 +229,6 @@ class ManagedProcess:
# ------------------------------------------------------------- kills and teardown
def kill(self) -> None:
- """SIGKILL the whole group right now (fall back to just the child)."""
try:
os.killpg(self.proc.pid, signal.SIGKILL)
except (ProcessLookupError, PermissionError):
@@ -297,10 +236,7 @@ class ManagedProcess:
self.proc.kill()
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
os.killpg(self.proc.pid, signal.SIGTERM)
except ProcessLookupError:
return
@@ -320,12 +256,9 @@ class ManagedProcess:
return self
def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: object) -> None:
- # Any in-flight exception (KeyboardInterrupt included) or a group still alive at
- # scope exit: the group dies HERE. Ctrl-C's SIGINT never reaches a
- # start_new_session child, so this is all that stands between an interrupt and an
- # orphaned blender/node/chrome tree. Never swallows exc. LEADER liveness is the
- # wrong question — one that exits 0 leaves its same-group grandchildren running;
- # reap it (a zombie still counts as a member), then ask if the GROUP exists.
+ # start_new_session children never see Ctrl-C, so the group dies here on any exception or
+ # if still alive. Ask whether the GROUP exists, not the leader (it may exit 0 with
+ # grandchildren running).
try:
self.proc.poll()
if _group_alive(self.proc.pid):
@@ -348,27 +281,19 @@ class ManagedProcess:
self._abandoned = _STILL_HELD if _group_alive(self.proc.pid) else _ABANDONED
-#: every :class:`ManagedProcess` whose group may still be alive, in THIS process — what a stop
-#: signal kills. A run's agent sessions and builds run in worker threads, and a signal is
-#: delivered to the main thread only: ``__exit__`` never ran for them, so SIGTERM (and Ctrl-C,
-#: while the main thread waited on the pool) left agy / blender / chrome trees running and
-#: billing (live, 2026-10-13: a SIGTERM'd ``3dcode make`` orphaned its agy session).
+#: every :class:`ManagedProcess` whose group may still be alive; a stop signal kills these
+#: (signals reach only the main thread, so worker-thread ``__exit__`` never runs).
_LIVE: set[ManagedProcess] = set()
_LIVE_GUARD = threading.Lock()
-#: set once a stop began: no new child is started after it (a worker thread whose session was
-#: just killed would otherwise go on to its retry or its next build)
_STOPPING = threading.Event()
-#: how long a stopping process may take to unwind before it is ended outright. Exit joins the
-#: worker threads, and one inside a model call can hold it for that call's whole timeout (20 min)
STOP_GRACE_S = 30.0
class ProcessStopping(RuntimeError):
- """A child was asked for after this process began to stop."""
+ """A child was requested after this process began to stop."""
def kill_live_children() -> int:
- """Refuse new children from now on and SIGKILL every live child group; how many there were."""
with _LIVE_GUARD:
_STOPPING.set()
live = list(_LIVE)
@@ -378,10 +303,8 @@ def kill_live_children() -> int:
def install_stop_handlers() -> None:
- """SIGTERM and SIGINT kill every live child group and refuse new ones, then end the process
- as they would (``KeyboardInterrupt`` / exit 143) so the run records its stop — and, should
- the unwinding outlast :data:`STOP_GRACE_S` (exit waits on worker threads), end it outright
- with the same status. Main thread only — a no-op elsewhere."""
+ """SIGTERM / SIGINT kill every live child group, refuse new ones, then end the process
+ (``KeyboardInterrupt`` / exit 143), outright after :data:`STOP_GRACE_S`. Main thread only."""
if threading.current_thread() is not threading.main_thread():
return
@@ -400,8 +323,7 @@ def install_stop_handlers() -> None:
# ------------------------------------------------------------------ env scrubbing
-#: The ONE owner of the credential patterns: ``agents/cli_common.clean_env`` (the vendor CLIs'
-#: env) calls :func:`scrub_secrets` too.
+#: The one owner of the credential patterns (``agents/cli_common.clean_env`` uses :func:`scrub_secrets`).
_SECRET_EXACT: frozenset[str] = frozenset({
"GEMINI_API_KEYS", "GEMINI_API_KEY", "GOOGLE_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY",
"OPENAI_ORG_ID", "HF_TOKEN", "HUGGINGFACE_TOKEN", "GITHUB_TOKEN", "GH_TOKEN",
@@ -413,14 +335,7 @@ _SECRET_SUFFIXES: tuple[str, ...] = (
def scrub_secrets(env: dict[str, str]) -> dict[str, str]:
- """``env`` minus credential-shaped variables (exact names + ``*_API_KEY``-style suffixes).
-
- Model-generated code runs in subprocesses that inherit the harness environment
- (blender, the cadquery python, node) and nothing generated ever legitimately needs
- a credential — so the keys must not be there to leak into logs, artifacts or child
- processes. Everything else (PATH, HOME, DISPLAY, MESA_*/GALLIUM_* render config...)
- passes through untouched.
- """
+ """``env`` minus credential-shaped variables (exact names + ``*_API_KEY``-style suffixes)."""
return {
k: v for k, v in env.items()
if k not in _SECRET_EXACT and not k.endswith(_SECRET_SUFFIXES)
@@ -428,14 +343,12 @@ def scrub_secrets(env: dict[str, str]) -> dict[str, str]:
def tail(text: str, *, max_lines: int = 40, max_chars: int = 4000) -> str:
- """Last ``max_lines`` lines of ``text``, capped at ``max_chars`` characters."""
lines = text.splitlines()[-max_lines:]
s = "\n".join(lines)
return s[-max_chars:] if len(s) > max_chars else s
def sha256_file(path: Path | str) -> str:
- """Chunked sha256 of one file — for manifests / caches keyed on content."""
h = hashlib.sha256()
with Path(path).open("rb") as fh:
for chunk in iter(lambda: fh.read(1 << 20), b""):
@@ -459,19 +372,11 @@ def version_line(cmd: Sequence[str], *, timeout: float) -> tuple[int | None, str
def unique_tmp(path: Path) -> Path:
- """A temp sibling of ``path`` unique to this process AND thread.
-
- A FIXED ``<name>.tmp`` is a race: two writers of the same destination both
- create it and the second ``replace()`` finds its source already renamed away,
- raising FileNotFoundError. The harness fans work out over thread pools, so
- "one writer per destination" does not hold — see ``tracks/scene_asset_gen``,
- where the losing thread's asset gate was silently skipped.
- """
+ """A temp sibling of ``path`` unique to this process and thread (a fixed ``.tmp`` races between writers)."""
return path.with_name(f"{path.name}.{os.getpid()}-{threading.get_ident()}.tmp")
def write_text_atomic(path: Path, text: str, *, encoding: str = "utf-8") -> Path:
- """tmp + rename so readers never see a partial file, safe under concurrency."""
path.parent.mkdir(parents=True, exist_ok=True)
tmp = unique_tmp(path)
try:
@@ -484,40 +389,14 @@ def write_text_atomic(path: Path, text: str, *, encoding: str = "utf-8") -> Path
def write_json_atomic(path: Path, data: Any) -> None:
- """tmp + rename so readers never see a partial file — including when several
- writers race for the same path.
-
- Delegates to :func:`write_text_atomic`, whose tmp name is private to this writer
- (pid + thread id). One shared ``<path>.tmp`` was NOT atomic across writers: A could
- rename B's half-written tmp into place — readers then observed truncated or
- zero-byte JSON at the published path — and B's own ``replace()`` died with
- FileNotFoundError. That is not hypothetical here: the scene track fans zone agents
- out over ONE workspace root and every agent's MCP ``build`` tool writes
- ``artifacts/build.json`` and ``artifacts/measurement.json`` through this
- function, and a clobbered ``run_state.json`` is an unresumable run
- (``RunState.load`` refuses to guess). Last writer to rename still wins.
- """
write_text_atomic(path, json.dumps(data, indent=2, ensure_ascii=False, default=str))
# ------------------------------------------------------------------ tolerant reads
def read_json_or_none(path: Path | str, *, errors: str | None = None) -> dict[str, Any] | None:
- """Parse ``path`` as a JSON object; ``None`` when absent, unreadable, malformed
- or not a dict at the top level.
-
- The one tolerant reader behind every "use it if it is there" side-car: it
- replaced identical ``try: json.loads(read_text()) except (OSError, ValueError)``
- copies in ``record/telemetry.read_json``, ``eval/bench/complexity_report._read_json``,
- ``gallery/index._measurement_complexity`` / ``_spec_fields``, ``runlock._holder``,
- ``languages/threejs/__init__.py``'s plan loader, ``cost/reconstruct._read_json``,
- ``spatial/_render_common.read_json`` and ``cli/_judge.plan_summary_for`` — all
- the same algorithm, differing only in whether they also checked ``isinstance(dict)``
- (which every caller then relied on anyway). A strict reader that must raise on
- a corrupt input (``Workspace.read_json``) deliberately does NOT use this.
-
- ``errors`` is ``read_text``'s decode policy (``"replace"`` for files another
- process may still be writing). Reads UTF-8, the encoding :func:`write_json_atomic`
- writes.
+ """Parse ``path`` as a JSON object; ``None`` when absent, unreadable, malformed or not a dict.
+
+ ``errors`` is ``read_text``'s decode policy (``"replace"`` for files still being written).
"""
try:
data = json.loads(Path(path).read_text(encoding="utf-8", errors=errors))
@@ -529,10 +408,7 @@ def read_json_or_none(path: Path | str, *, errors: str | None = None) -> dict[st
def iter_jsonl_lines(path: Path | str) -> Iterator[tuple[int, str]]:
"""``(line_no, line)`` for every non-blank line of a JSONL file, 1-based.
- Missing file → nothing; decoded UTF-8 with ``errors="replace"`` so one bad byte
- (or a SIGKILL mid-append) costs at most that line. Shared by
- :func:`read_jsonl_lenient` and by the model-validating readers that keep their own
- per-line parse (``cost/ledger.load_ledger``, ``eval/bench/_jsonl.read_jsonl``).
+ Missing file → nothing; invalid bytes are replaced so one bad byte costs at most that line.
"""
p = Path(path)
if not p.is_file():
@@ -547,12 +423,6 @@ def read_jsonl_lenient(
) -> list[Any]:
"""Every parseable JSON line of ``path``; unparseable lines are skipped (debug-logged
to ``log`` when given), ``dicts_only`` also drops non-object rows.
-
- Replaced the same skip-bad-lines loop in ``events.EventLog.read``,
- ``cost/reconstruct._read_jsonl``, ``flywheel/trajectories.read_events``,
- ``cli/skills_cmd`` (skills report) and ``agents/transcript.read_transcript`` —
- a truncated last line must never lose the rest of the file (the contract
- ``cost.ledger.load_ledger`` has always had).
"""
out: list[Any] = []
for i, line in iter_jsonl_lines(path):
@@ -569,14 +439,6 @@ def read_jsonl_lenient(
def append_jsonl_line(path: Path | str, rec: Any, lock: threading.Lock) -> None:
- """Append ``rec`` as one JSON line under ``lock`` (``ensure_ascii=False``,
- ``default=str`` so paths / enums / datetimes serialise).
-
- Replaced the identical bodies of ``events.EventLog.emit`` and
- ``agents/transcript.Trajectory.append``. ``cost/ledger.CostLedger.append`` is NOT
- a copy — it mkdirs, flushes and swallows OSError ("flushed on write") — and keeps
- its own.
- """
line = json.dumps(rec, ensure_ascii=False, default=str)
with lock, Path(path).open("a", encoding="utf-8") as fh:
fh.write(line + "\n")
@@ -593,39 +455,29 @@ class EventLog:
self.path.parent.mkdir(parents=True, exist_ok=True)
def emit(self, event: str, **data: Any) -> None:
- """Append one event. ``event`` is the event name (e.g. ``round.start``);
- ``data`` may use any keys, including ``kind``."""
append_jsonl_line(self.path, {"t": round(time.time(), 3), "event": event, **data}, self._lock)
def read(self) -> list[dict[str, Any]]:
- """Read the log, skipping unparseable lines with a debug log.
-
- ``emit`` appends one buffered ``write``, so a SIGKILL / OOM kill / reboot
- leaves a partial trailing line — and a killed run is exactly when someone
- types ``3dcode status``. A truncated last line must never lose the rest of
- the file (same contract as ``cost.ledger.load_ledger``)."""
return read_jsonl_lenient(self.path, log=log)
class _NullEvents:
- """An event sink that drops everything: what a function that takes ``events=None`` emits to."""
+ """An event sink that drops everything."""
def emit(self, event: str, **data: Any) -> None:
pass
-#: normalise optional telemetry once — ``events = NULL_EVENTS if events is None else events`` —
-#: never ``events or NULL_EVENTS``: an empty list-based fake log is falsy
+#: use ``NULL_EVENTS if events is None else events``, never ``events or NULL_EVENTS`` (an empty fake log is falsy)
NULL_EVENTS = _NullEvents()
# ===================================================================== runlock
-#: directory (beside the run dirs, never inside one) holding the flock files
LOCKS_DIR = ".locks"
class RunLocked(RuntimeError):
- """Another live holder — process or thread — is already running this run."""
+ """Another process or thread is already running this run."""
def _held_message(run_root: Path | str, held: dict, *, action: str) -> str:
@@ -641,7 +493,6 @@ def _held_message(run_root: Path | str, held: dict, *, action: str) -> str:
def flock_path(run_root: Path | str) -> Path:
- """The flock file for this run: ``<runs>/.locks/<slug>.lock``."""
root = Path(run_root).resolve()
return root.parent / LOCKS_DIR / f"{root.name}.lock"
@@ -668,11 +519,8 @@ def _write_record(fd: int, rec: dict) -> None:
def holder_of(run_root: Path | str) -> dict | None:
- """The ``{pid, started, what}`` of whoever holds this run — without taking it.
-
- ``None`` when nobody does, including after a SIGKILL: the kernel dropped the flock but
- the record is still in the file, so a probe (shared, non-blocking, released at once)
- tells the difference and ``3dcode status`` never names a pid that is already gone."""
+ """The ``{pid, started, what}`` of whoever holds this run, without taking it; ``None`` if nobody
+ does (a stale record left by a SIGKILL is detected by probing the flock)."""
try:
fd = os.open(flock_path(run_root), os.O_RDONLY)
except OSError:
@@ -692,17 +540,14 @@ def holder_of(run_root: Path | str) -> dict | None:
def exclusive(run_root: Path | str, *, what: str = "", action: str = "enter") -> Iterator[None]:
"""THE mutex for one run: hold it around every mutation of the run directory.
- Raises :class:`RunLocked`, naming the holder, when anyone else has it — another
- process, or another THREAD of this one (the bench drivers run runs in a pool). Only
- the SAME thread re-enters, so the CLI can take it at the mutation boundary and the
- code under it can take it again."""
+ Raises :class:`RunLocked` when another process or thread holds it; the same thread re-enters."""
key, me = str(flock_path(run_root)), threading.get_ident()
with _HELD_GUARD:
entry = _HELD.get(key)
if entry is not None:
if entry[1] != me:
raise RunLocked(_held_message(run_root, holder_of(run_root) or {}, action=action))
- yield # the SAME thread re-entering: the outermost `with` owns the release
+ yield # re-entry: the outermost `with` owns the release
return
path = Path(key)
path.parent.mkdir(parents=True, exist_ok=True)
@@ -716,7 +561,7 @@ def exclusive(run_root: Path | str, *, what: str = "", action: str = "enter") ->
except BaseException:
os.close(fd)
raise
- try: # inside the try that owns the fd: a failed write must not leak an unreleasable lock
+ try: # a failed write must not leak the lock
_write_record(fd, {"pid": os.getpid(), "started": time.time(), "what": what})
with _HELD_GUARD:
_HELD[key] = [fd, me]
@@ -749,10 +594,6 @@ def fan_out[T, R](
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
- # (the cost ledger's run/stage/role attribution) follows a parallel judge
- # sample, best-of-N candidate or bench cell instead of falling back to the
- # process default.
ctx_snapshot = contextvars.copy_context()
results: list[R | Exception] = [None] * len(items) # type: ignore[list-item]
if not items:
diff --git a/harness/codeverse3d/prompts/__init__.py b/harness/codeverse3d/prompts/__init__.py
index af1f329f..9f7edbfd 100644
--- a/harness/codeverse3d/prompts/__init__.py
+++ b/harness/codeverse3d/prompts/__init__.py
@@ -1,10 +1,7 @@
"""Prompt loader: markdown + jinja2 templates, content-hashed for provenance.
-Every name resolves through the ACTIVE VARIANT first (``prompts/variants.py``, D105): a file
-``variants/<name>/<rel>`` shadows ``<rel>``, a missing overlay file falls back to the base, and
-with no variant active nothing here changes — the base environment is the single
-``FileSystemLoader`` it always was, so base rendering is byte-identical (the manifest pins it).
-Callers do not change: ``load_text`` / ``render`` / ``catalog.language_text`` take the same names.
+Names resolve through the active variant first (``prompts/variants.py``): an overlay file shadows the
+base file, a missing overlay file falls back to the base.
"""
from __future__ import annotations
@@ -24,22 +21,18 @@ log = logging.getLogger(__name__)
PROMPTS_DIR = Path(__file__).resolve().parent
-#: the flags every prompt environment renders with — the base one and each variant's
_FLAGS: dict[str, Any] = {"undefined": StrictUndefined, "trim_blocks": True, "lstrip_blocks": True,
"keep_trailing_newline": True, "autoescape": False}
_env = Environment(loader=FileSystemLoader(str(PROMPTS_DIR)), **_FLAGS)
-#: same environment (loader + flags; its own template cache), but an unknown name renders
-#: empty instead of raising — used only as the fallback in :func:`render`, never as the default.
+#: lenient environment: an unknown name renders empty; the fallback in :func:`render` only
_lenient_env = _env.overlay(undefined=ChainableUndefined)
@lru_cache(maxsize=16)
def _env_for(variant: str) -> tuple[Environment, Environment]:
- """``(strict, lenient)`` environments: the base pair for ``""``; for a variant a ``ChoiceLoader``
- pair — the overlay directory first, the base second, so an overlay template may ``{% include %}``
- or ``{% extends %}`` a base file, and a name the overlay does not ship renders from the base."""
+ """``(strict, lenient)`` environments: the base pair for ``""``, else overlay-first then base."""
if not variant:
return _env, _lenient_env
env = Environment(loader=ChoiceLoader([FileSystemLoader(str(variant_root(variant))),
@@ -48,8 +41,7 @@ def _env_for(variant: str) -> tuple[Environment, Environment]:
def _resolve(variant: str, rel_path: str) -> Path:
- """The file ``rel_path`` reads from under ``variant``: its overlay copy when one exists, else the
- base path (which may not exist either — the caller decides what a missing file means)."""
+ """The file ``rel_path`` reads from under ``variant``: its overlay copy if any, else the base path."""
if variant:
overlay = variant_root(variant) / rel_path
if overlay.is_file():
@@ -66,19 +58,14 @@ def _load(variant: str, rel_path: str) -> str:
def load_text(rel_path: str) -> str:
- """Raw prompt text, e.g. ``load_text("blender/contract.md")`` — the active variant's copy first."""
return _load(active_variant(), rel_path)
def render(rel_path: str, **ctx: Any) -> str:
"""Render a jinja template under prompts/ with ``ctx``.
- StrictUndefined is deliberate: a template that silently drops a section because a
- caller renamed a variable is worse than a loud failure at development time. But a
- template edited while a run is IN FLIGHT is a different matter — the run reloads the
- file at its next round boundary and dies on a variable its caller has never heard of.
- So a missing name degrades the prompt (that one section renders empty) instead of
- killing the task, and says so in the log. Everything else still raises.
+ StrictUndefined raises on a missing name, except that a name missing at render time degrades
+ that one section to empty (logged) so an edit made while a run is in flight cannot kill it.
"""
env, lenient = _env_for(active_variant())
template = env.get_template(rel_path)
diff --git a/harness/codeverse3d/prompts/catalog.py b/harness/codeverse3d/prompts/catalog.py
index a8ec379f..2aed8262 100644
--- a/harness/codeverse3d/prompts/catalog.py
+++ b/harness/codeverse3d/prompts/catalog.py
@@ -1,24 +1,8 @@
-"""What prompt material exists, and how each piece reaches the model.
+"""What prompt material exists and how each piece reaches the model.
-ONE answer to a question that had six. A per-language prompt file was once resolved in
-`languages/_docs.py`, `tracks/common.py`, `agents/materialize.py` and `tracks/scene_assets.py`,
-each with its own path arithmetic — and the ``urdf_blender`` → ``prompts/urdf/`` mapping was
-written out three times and missing in a fourth, which is why the articulated agent received
-part of its prompt material late for weeks. Until 2026-09-22 the contract still came through
-the runtime (``contract_doc``), the system prompt and the effects catalog through
-``tracks/prompting``: every per-language prompt file (``contract.md`` first) is now found by
-:func:`language_prompt`.
-
-The split this file encodes (owner, 2026-08-28):
-
-* **PROMPT material** — everything the harness writes and the harness puts in a message.
- It lives here, under ``codeverse3d/prompts/``, and modules load it on demand through this
- catalog rather than building paths.
-* **AGENT-read bundles** — ``codeverse3d/skills/c3d-*/`` (SKILL.md + references/ + a
- ``_claims`` file pinning its numbers to live constants). The agent decides to read
- those; the harness only materialises them.
-
-A file that tries to be both is the thing this split exists to prevent.
+* PROMPT material: what the harness writes into a message; lives under ``codeverse3d/prompts/`` and
+ is found through :func:`language_prompt`.
+* AGENT-read bundles: ``codeverse3d/skills/c3d-*/``, which the agent chooses to read.
"""
from __future__ import annotations
@@ -28,21 +12,16 @@ from collections.abc import Sequence
from codeverse3d.contracts.common import Language
from codeverse3d.prompts import load_text
-#: ``Language.URDF_BLENDER`` is ``"urdf_blender"``; its prompts live in ``prompts/urdf/``.
PROMPT_DIRS: dict[Language, str] = {Language.URDF_BLENDER: "urdf"}
def language_prompt(language: Language, name: str) -> str:
- """``<dir>/<name>`` under ``prompts/`` — THE path of a language's ``contract.md`` and
- ``system.md`` (and the scene languages' ``asset.md``, scene_threejs's ``effects_catalog.md``)."""
+ """``<dir>/<name>`` under ``prompts/``: the path of a language's ``contract.md`` / ``system.md`` etc."""
return f"{PROMPT_DIRS.get(language, language.value)}/{name}"
def language_text(language: Language, name: str) -> str:
- """The text of :func:`language_prompt`, or ``""`` for a file the language does not ship
- (the two scene languages ship ``asset.md``, scene_threejs an effects catalog). No language ships
- a cookbook (D107, owner 2026-10-15): interface and language facts are in ``contract.md`` /
- ``system.md``, the craft in the skills as short optional practices."""
+ """The text of :func:`language_prompt`, or ``""`` for a file the language does not ship."""
try:
return load_text(language_prompt(language, name))
except FileNotFoundError:
@@ -51,11 +30,7 @@ def language_text(language: Language, name: str) -> str:
def contract_sections(text: str, headings: Sequence[str]) -> str:
"""The ``## `` sections of a contract whose heading starts with one of ``headings``, in the
- contract's own order, under its preamble (the ``# `` title and anything before the first
- ``## ``). A session that writes one asset module, or a planner that writes JSON, is handed
- the sections it acts on — the files, the gates, the lint — not the whole contract (the
- copyability review of 2026-10-15: the asset brief had grown 52 % by carrying the wiring
- example of modules it must not write)."""
+ contract's order, under its preamble."""
out: list[str] = []
keep = True
for line in text.splitlines():
diff --git a/harness/codeverse3d/prompts/variants.py b/harness/codeverse3d/prompts/variants.py
index 3ce570bd..b352256d 100644
--- a/harness/codeverse3d/prompts/variants.py
+++ b/harness/codeverse3d/prompts/variants.py
@@ -1,26 +1,9 @@
-"""Per-model prompt / skill variants: one overlay directory per name, chosen explicitly (D105).
-
-WHY. The owner's 2026-10-14 decision: gemini-4-argon on the scene track gets its own prompt
-wording and skill routing, tuned by a loop (``eval/bench/loop.py``) that must be able to accept
-or roll back a change without touching the base files every other model reads. A variant is
-therefore an OVERLAY, never a fork: ``codeverse3d/prompts/variants/<name>/<rel>`` shadows
-``codeverse3d/prompts/<rel>`` for the callers of :func:`codeverse3d.prompts.load_text` /
-``render`` (they do not change), and ``codeverse3d/skills/variants/<name>/`` shadows bundles by
-name and adds ``routes.toml`` boosts (``codeverse3d.skills``). Everything a variant does is a
-file the loop can diff, snapshot and hash — :func:`variant_hash` goes into the run record beside
-the prompt hashes, so two runs can be told apart by what their models were shown.
-
-HOW it is chosen (Law 4: never a regex over the model id). ``Settings.variant``
-(``C3D_VARIANT``, or ``3dcode make --variant``, frozen on ``RunOptions.variant``) names one for
-the whole process; otherwise ``Settings.variants`` maps an EXACT generator id to a name — by the
-id as typed, then by ``<kind>:<served model>`` (``agy:gemini-4-argon-high`` runs the model
-``gemini-4-argon``, so one mapping keyed on the served model covers every effort suffix). An
-unknown name is a ``ValueError`` at resolution time, before a run directory exists.
-
-WHERE it is active. A ``ContextVar`` set by :func:`activate` around the whole run
-(``tracks/lifecycle.BaseTrack.run``) and inherited by every fan-out thread, because
-``proc.fan_out`` copies the caller's context into its workers; outside any run,
-``get_settings().variant`` — the process switch, like every other ``C3D_*`` knob.
+"""Per-model prompt / skill variants: one overlay directory per name.
+
+``prompts/variants/<name>/<rel>`` shadows ``prompts/<rel>`` and ``skills/variants/<name>/`` shadows
+skill bundles. A variant is chosen by ``Settings.variant`` or by ``Settings.variants`` keyed on the
+generator id (exact, then ``<kind>:<served model>``); an unknown name raises ``ValueError``. The
+active one is a ``ContextVar`` set by :func:`activate` around a run; :func:`variant_hash` records it.
"""
from __future__ import annotations
@@ -40,15 +23,11 @@ from codeverse3d.config import Settings, get_settings
log = logging.getLogger(__name__)
-#: the overlay directories: ``VARIANTS_DIR/<name>/`` mirrors ``codeverse3d/prompts/`` file for file
VARIANTS_DIR: Path = Path(__file__).resolve().parent / "variants"
-#: the one file every variant must ship (its name, version, generators and knobs)
VARIANT_FILE = "variant.toml"
-#: ``[knobs]`` may set ONLY these ``Settings`` fields — the skills dials a variant tunes. Applied like a
-#: profile (``Settings.apply_profile``): a field the user stated themselves wins.
+#: ``[knobs]`` may set only these ``Settings`` fields; applied as defaults, user-stated values win
KNOB_FIELDS: frozenset[str] = frozenset({"skills_max", "skills_only"})
_KNOB_TYPES: dict[str, type] = {"skills_max": int, "skills_only": str}
-#: files under an overlay that are documentation, never material a model sees: left out of the hash
HASH_EXCLUDED: frozenset[str] = frozenset({"README.md"})
_ACTIVE: ContextVar[str | None] = ContextVar("c3d_variant", default=None)
@@ -56,7 +35,6 @@ _WARNED: set[str] = set()
class VariantInfo(BaseModel):
- """``variant.toml``, parsed and type-checked."""
model_config = {"frozen": True}
@@ -68,22 +46,18 @@ class VariantInfo(BaseModel):
knobs: dict[str, Any] = Field(default_factory=dict, description="Settings fields to apply (KNOB_FIELDS only)")
-# --------------------------------------------------------------------------- the catalogue
def _plain_name(name: str) -> bool:
- """A variant name is a plain directory name: no separators, no dot-prefix."""
return bool(name) and Path(name).name == name and not name.startswith(".")
def variant_root(name: str) -> Path:
- """``VARIANTS_DIR / name`` — the prompts half of the overlay (it need not exist yet)."""
if not _plain_name(name):
raise ValueError(f"variant name {name!r} must be a plain directory name")
return VARIANTS_DIR / name
def list_variants() -> dict[str, VariantInfo]:
- """Every variant the tree ships, by name (a directory under ``VARIANTS_DIR`` with a ``variant.toml``).
- A file that does not parse raises: a shipped variant is never half-known."""
+ """Every shipped variant by name (a directory under ``VARIANTS_DIR`` with a ``variant.toml``)."""
if not VARIANTS_DIR.is_dir():
return {}
return {d.name: _parse(d / VARIANT_FILE, d.name)
@@ -91,7 +65,6 @@ def list_variants() -> dict[str, VariantInfo]:
def variant_info(name: str) -> VariantInfo:
- """``variant.toml`` of ``name``; ``ValueError`` for an unknown name (naming the known ones)."""
path = variant_root(name) / VARIANT_FILE if _plain_name(name) else None
if path is None or not path.is_file():
known = ", ".join(list_variants()) or "none"
@@ -139,10 +112,8 @@ def _parse(path: Path, dir_name: str) -> VariantInfo:
knobs=dict(knobs))
-# --------------------------------------------------------------------------- selection
def served_id(generator_id: str) -> str:
- """``agy:gemini-4-argon-high`` → ``agy:gemini-4-argon``: the id by the model the vendor serves, without
- the effort suffix; ``""`` for an id that is not ``<kind>:<model>`` (a single-shot id, a bare name)."""
+ """``agy:gemini-4-argon-high`` → ``agy:gemini-4-argon``; ``""`` for an id that is not ``<kind>:<model>``."""
from codeverse3d.agents.backends import api_model_effort
from codeverse3d.agents.registry import parse_agent_id
@@ -154,9 +125,8 @@ def served_id(generator_id: str) -> str:
def resolve_variant(settings: Settings, generator_id: str) -> str:
- """The variant name for a run of ``generator_id`` under ``settings``: ``settings.variant`` (non-empty)
- > ``settings.variants[generator_id]`` > ``settings.variants["<kind>:<served model>"]`` > ``""`` (base).
- Plain dict lookups, never a pattern over the id. An unknown name raises ``ValueError``."""
+ """The variant name for ``generator_id``: ``settings.variant``, else ``settings.variants`` by id,
+ else by ``<kind>:<served model>``, else ``""`` (base). An unknown name raises ``ValueError``."""
name = settings.variant.strip()
if not name and settings.variants:
name = settings.variants.get(generator_id, "")
@@ -170,10 +140,7 @@ def resolve_variant(settings: Settings, generator_id: str) -> str:
return name
-# --------------------------------------------------------------------------- the active variant
def active_variant() -> str:
- """The variant everything resolves through right now: the ``ContextVar`` :func:`activate` set, else
- the process switch ``get_settings().variant``. ``""`` is the base."""
current = _ACTIVE.get()
if current is not None:
return current
@@ -188,8 +155,7 @@ def active_variant() -> str:
@contextmanager
def activate(name: str) -> Iterator[str]:
- """Set the active variant for the block (``""`` = base). An unknown name raises before anything in
- the block renders from a directory that does not exist. Nests: the outer value returns on exit."""
+ """Set the active variant for the block (``""`` = base); an unknown name raises. Nests."""
name = (name or "").strip()
if name:
variant_info(name)
@@ -200,7 +166,6 @@ def activate(name: str) -> Iterator[str]:
_ACTIVE.reset(token)
-# --------------------------------------------------------------------------- provenance
def _skills_root(name: str) -> Path:
from codeverse3d.skills import variant_dir
@@ -208,10 +173,7 @@ def _skills_root(name: str) -> Path:
def variant_hash(name: str) -> str:
- """``sha256[:12]`` over the sorted ``(relpath, bytes)`` of the prompt AND skills overlay files of
- ``name`` (``README.md`` left out: documentation, not prompt material); ``""`` for the base. The two
- trees are keyed ``prompts/<rel>`` and ``skills/<rel>`` so a same-named file in both still counts twice.
- For an empty overlay this is the hash of ``variant.toml`` + ``routes.toml``, so a version bump moves it."""
+ """``sha256[:12]`` over the sorted prompt and skills overlay files of ``name``; ``""`` for the base."""
if not name:
return ""
variant_info(name)
@@ -229,8 +191,7 @@ def variant_hash(name: str) -> str:
def variant_block(name: str) -> dict[str, Any]:
- """``{"name", "version", "hash"}`` for a record (``RunRecord.extra["variant"]``, the ``variant.active``
- event). Tolerant: a variant that vanished mid-run keeps its name with version 0 / hash ``""``."""
+ """``{"name", "version", "hash"}`` for a record; a variant that vanished keeps its name with version 0."""
if not name:
return {"name": "", "version": 0, "hash": ""}
try:
@@ -240,12 +201,9 @@ def variant_block(name: str) -> dict[str, Any]:
return {"name": name, "version": 0, "hash": ""}
-# --------------------------------------------------------------------------- knobs
def apply_variant_knobs(settings: Settings, info: VariantInfo) -> dict[str, Any]:
- """Set ``info.knobs`` (those in ``fields``) on ``settings`` as DEFAULTS, the way a profile is applied:
- a field the user stated (config file / ``C3D_*`` / an explicit constructor kwarg — ``model_fields_set``)
- is never touched, and the field-set is restored afterwards so a knob is not later mistaken for a
- statement (``Settings.apply_profile.put_section`` keeps the same invariant). Returns what was set."""
+ """Set ``info.knobs`` on ``settings`` as defaults: fields the user stated are untouched and the
+ field-set is restored. Returns what was set."""
stated = set(settings.model_fields_set)
applied: dict[str, Any] = {}
for field_name, value in info.knobs.items():
@@ -259,16 +217,8 @@ def apply_variant_knobs(settings: Settings, info: VariantInfo) -> dict[str, Any]
@contextmanager
def knobs_applied(settings: Settings, info: VariantInfo | None) -> Iterator[dict[str, Any]]:
- """:func:`apply_variant_knobs` for the block ONLY (``info`` ``None``: nothing applied).
-
- WHY a block. The prompt and skill overlays are scoped by :func:`activate`'s ``ContextVar``, but
- the knobs are written onto a ``Settings`` object that outlives the run — the process singleton
- ``attach_skills`` reads, a rig's injected Settings — so a variant's ``skills_max`` stayed on it for
- every later run of the process (a manifest rig, a bench cell after a variant cell, any script
- calling ``track.run`` twice), and since ``apply_variant_knobs`` keeps the field-set, the leaked
- value was indistinguishable from the default. On exit — whatever the block raised — every knob
- field goes back to its prior value and its prior field-set membership; a statement the block made
- to any OTHER field is kept. Yields what was set, for the ``variant.active`` event."""
+ """:func:`apply_variant_knobs` for the block only: every knob field returns to its prior value and
+ field-set membership on exit. Yields what was set."""
prior = {field_name: getattr(settings, field_name) for field_name in KNOB_FIELDS}
stated = set(settings.model_fields_set) & KNOB_FIELDS
applied = apply_variant_knobs(settings, info) if info is not None else {}
@@ -276,7 +226,7 @@ def knobs_applied(settings: Settings, info: VariantInfo | None) -> Iterator[dict
yield applied
finally:
for field_name, value in prior.items():
- setattr(settings, field_name, value) # pydantic marks each as set: undone next line
+ setattr(settings, field_name, value)
settings.__pydantic_fields_set__ = (set(settings.model_fields_set) - KNOB_FIELDS) | stated
diff --git a/harness/codeverse3d/record/deliverable.py b/harness/codeverse3d/record/deliverable.py
index d9229dac..f8aa482c 100644
--- a/harness/codeverse3d/record/deliverable.py
+++ b/harness/codeverse3d/record/deliverable.py
@@ -1,23 +1,7 @@
-"""``<run>/deliverable/`` — the hand-over folder for ONE round, and what every round keeps
-so that any of them can be handed over later without a rebuild.
-
-Everything in the folder is a *copy*, regenerated from the run's own evidence, so it can
-be zipped and sent on its own:
-
-* ``src/**`` (+ ``public/**`` for scenes, their GLB assets included) — the raw code at the
- round's commit;
-* the round's artifact — ``object.glb`` (+ ``.stl`` / ``.step``), or
- ``robot.urdf`` + ``meshes/*.glb``, or ``frames/*.png`` (the judged frames) +
- ``frames_sheet.png`` + ``preview.gif`` — from ``artifacts/rNN/`` (:func:`keep_round_artifacts`);
-* ``sheet.png`` — the round's contact sheet (one picture of the result);
-* ``captions.json`` when the run is captioned;
-* ``manifest.json`` — every OTHER file with its role, size and sha256. It does not list
- itself: a file cannot carry its own hash, and the returned object must be exactly what
- is on disk.
-
-WHICH round is not decided here: since 2026-09-22 the run keeps every round and ends at the
-last one, and ``codeverse3d.addons.select`` picks a round and packages it. Renders per
-round, gates, judge verdicts and measurements stay in ``artifacts/``; tokens, prices and settings stay in ``telemetry/``.
+"""``<run>/deliverable/``: the hand-over folder for ONE round, regenerated as copies from the run's evidence.
+
+Holds the round's raw code, its artifact (GLB/STL/STEP, URDF + meshes, or judged frames + sheet + GIF),
+``sheet.png``, ``captions.json`` and ``manifest.json`` (every other file with role, size and sha256).
"""
from __future__ import annotations
@@ -37,9 +21,7 @@ from codeverse3d.workspace import Workspace
log = logging.getLogger(__name__)
-#: 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.
+#: a round's build output → its role in the hand-over (these and ``meshes/`` are what a round keeps)
_ARTIFACT_ROLES: tuple[tuple[str, str], ...] = (
("object.glb", "model"),
("object.stl", "model"),
@@ -53,16 +35,12 @@ _MESH_DIR = "meshes"
def keep_round_artifacts(ws: Workspace, round_index: int) -> list[str]:
- """Copy the round's build outputs to ``artifacts/rNN/`` (names relative to
- ``artifacts/``); ``[]`` when the round built nothing to keep.
-
- Only the files a hand-over needs, and real copies: the next round's build replaces the
- canonical ones, and a kept round must never change under a writer that happens to
- write in place (a hard link would share that inode). A scene keeps nothing here — its
- hand-over (``src/`` + ``public/``, GLB assets included) is the round's git commit — and
- a graphics round keeps its sheet and GIF; its judged frames are in ``renders/rNN/``."""
+ """Copy the round's build outputs to ``artifacts/rNN/`` (names relative to ``artifacts/``).
+
+ Real copies, never hard links, so a later in-place build cannot change a kept round.
+ A scene keeps nothing here (its hand-over is the git commit)."""
dest = ws.round_artifacts(round_index)
- if dest.exists(): # the same round built again (a transport retry): its last build wins
+ if dest.exists(): # the same round built again: its last build wins
shutil.rmtree(dest)
names = [n for n, _ in _ARTIFACT_ROLES if (ws.artifacts / n).is_file()]
meshes = sorted((ws.artifacts / _MESH_DIR).glob("*.glb")) if (ws.artifacts / _MESH_DIR).is_dir() else []
@@ -74,9 +52,7 @@ def keep_round_artifacts(ws: Workspace, round_index: int) -> list[str]:
class _Writer:
- """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."""
+ """Collects files into ``deliverable/`` as real copies (a hard link would let edits break the manifest sha256)."""
def __init__(self, ws: Workspace):
self.ws = ws
@@ -151,8 +127,7 @@ def _copy_captions(ws: Workspace, record: RunRecord, w: _Writer) -> None:
def _stable_timestamp(previous: RunDeliverable | None, current: RunDeliverable) -> datetime:
- """Keep the old timestamp when the content is byte-identical, so re-running the
- packager (or the migration) is a no-op instead of a diff."""
+ """Keep the old timestamp when the content is byte-identical."""
if previous is None or previous.generated_at is None:
return current.generated_at or datetime.now(UTC)
same = {(f.path, f.sha256) for f in previous.files} == {(f.path, f.sha256) for f in current.files}
@@ -160,10 +135,7 @@ def _stable_timestamp(previous: RunDeliverable | None, current: RunDeliverable)
def build_deliverable(ws: Workspace, record: RunRecord, round_index: int | None, *, clean: bool = True) -> RunDeliverable:
- """(Re)build ``<run>/deliverable/`` for round ``round_index`` and return the typed manifest.
-
- Idempotent: the folder is rebuilt from scratch every time, so a second call
- on an unchanged run produces byte-identical content."""
+ """(Re)build ``<run>/deliverable/`` for round ``round_index`` and return the manifest (idempotent)."""
rnd = next((r for r in record.rounds if r.index == round_index), None)
previous = load_deliverable(ws) if ws.deliverable_manifest_path.is_file() else None
out = round_outputs(ws, rnd)
@@ -186,11 +158,11 @@ def build_deliverable(ws: Workspace, record: RunRecord, round_index: int | None,
)
manifest.generated_at = _stable_timestamp(previous, manifest)
write_json_atomic(ws.deliverable_manifest_path, manifest.model_dump(mode="json"))
- return manifest # exactly what is on disk: len(files) and total_bytes == sum(f.bytes)
+ return manifest
def load_deliverable(ws: Workspace) -> RunDeliverable | None:
- """``deliverable/manifest.json`` (the round ``codeverse3d.addons.select`` packaged), else None."""
+ """``deliverable/manifest.json``, else None."""
path = ws.deliverable_manifest_path
if not path.is_file():
return None
diff --git a/harness/codeverse3d/record/git_history.py b/harness/codeverse3d/record/git_history.py
index d06b1a92..5d7b6579 100644
--- a/harness/codeverse3d/record/git_history.py
+++ b/harness/codeverse3d/record/git_history.py
@@ -1,15 +1,8 @@
-"""Read-only git helpers for the flywheel: file trees at a commit, binary-safe.
-
-The exporter / pairs builder must never touch the working tree of a run
-(another process may be resuming it), so everything here reads the object database
-of the run's repository (``ls-tree`` / ``cat-file`` / ``diff``).
-
-Read-only is not the same as safe: a run's ``.git/config`` and ``.gitattributes``
-were writable by the agent, and git config can name a program to RUN. Every
-invocation therefore goes through the same sanitised argv + environment the
-workspace's own git uses (:data:`~codeverse3d.workspace.GIT_SAFE_FLAGS`,
-:func:`~codeverse3d.workspace.git_safe_env`), and every content-rendering command
-adds :data:`~codeverse3d.workspace.GIT_SAFE_DIFF_FLAGS`.
+"""Read-only git helpers: file trees at a commit, binary-safe, never touching the working tree.
+
+A run's ``.git/config`` and ``.gitattributes`` are agent-writable and can name a program to run, so
+every call uses the workspace's sanitised flags and environment (``GIT_SAFE_FLAGS``, ``git_safe_env``,
+and ``GIT_SAFE_DIFF_FLAGS`` for content-rendering commands).
"""
from __future__ import annotations
@@ -32,10 +25,7 @@ class GitReadError(RuntimeError):
def _run(ws: Workspace, *args: str, stdin: bytes | None = None) -> subprocess.CompletedProcess[bytes]:
- """One sanitised git invocation; ``stdin`` feeds ``cat-file --batch`` its object list.
-
- Every way the call can fail — no git binary, a timeout, a non-zero exit — is one
- :class:`GitReadError`, so a caller catches one thing."""
+ """One sanitised git invocation; every failure is a :class:`GitReadError`."""
try:
proc = subprocess.run(
["git", *GIT_SAFE_FLAGS, *args], cwd=ws.root, capture_output=True, check=False,
@@ -68,15 +58,10 @@ def _keep(rel: str) -> bool:
def read_tree_at(ws: Workspace, commit: str, *, paths: Collection[str] | None = None) -> dict[str, bytes]:
- """``{repo-relative path: bytes}`` for every code file at ``commit`` (binary-safe);
- ``paths`` narrows it to those files, so a caller after two of forty streams two.
-
- ``ls-tree`` + ``cat-file --batch``, never ``git archive``: archive renders content
- through ``convert_to_working_tree``, so an agent-planted ``filter.<name>.smudge``
- RUNS — and unlike textconv there is no flag to turn it off (``-c
- core.attributesFile=/dev/null`` only silences the GLOBAL attributes file; the
- in-repo ``.gitattributes`` and ``.git/info/attributes`` are still read).
- ``cat-file`` hands back the raw blob and applies no filter unless asked."""
+ """``{repo-relative path: bytes}`` for every code file at ``commit``; ``paths`` narrows it.
+
+ ``ls-tree`` + ``cat-file --batch``, never ``git archive``: archive runs an agent-planted
+ ``filter.<name>.smudge`` and no flag disables it; ``cat-file`` applies no filter."""
if not ws.has_commit(commit):
raise GitReadError(f"commit {commit!r} not found in {ws.root}")
entries: list[tuple[str, str]] = [] # (blob sha, path)
@@ -86,9 +71,7 @@ def read_tree_at(ws: Workspace, commit: str, *, paths: Collection[str] | None =
continue
meta, _, path = rec.partition("\t")
parts = meta.split()
- # mode 120000 is a SYMLINK, stored as a blob whose content is the link target:
- # `git archive` filtered it (tar member, not a file) and this path must too, or
- # `src/link.py -> model.py` comes back as a one-line file saying "model.py".
+ # mode 120000 is a symlink (a blob holding the target path): skip it
if len(parts) < 3 or parts[1] != "blob" or parts[0] == "120000" or not _keep(path):
continue
if paths is not None and path not in paths:
@@ -115,12 +98,7 @@ def read_tree_at(ws: Workspace, commit: str, *, paths: Collection[str] | None =
def diff_between(ws: Workspace, before: str, after: str, *, max_bytes: int | None = None) -> tuple[str, int, bool]:
"""Unified diff of the code roots between two commits: ``(text, total_bytes, truncated)``.
- ``total_bytes`` is what git actually produced, so a capped row still records the
- size it was capped from. The useful shas are the ones recorded on the rounds,
- rather than ``HEAD``, which may contain later changes. A
- sha the repository no longer holds raises rather than diffing against an empty
- tree: ``git diff`` itself refuses an unknown object, so no pre-check is needed.
- """
+ ``total_bytes`` is the uncapped size. An unknown sha raises."""
raw = _run(ws, "diff", *GIT_SAFE_DIFF_FLAGS, before, after, "--", *CODE_ROOTS).stdout
total = len(raw)
if max_bytes is not None and total > max_bytes:
@@ -136,7 +114,7 @@ def changed_files_between(ws: Workspace, before: str, after: str) -> list[str]:
def read_working_tree(ws: Workspace) -> dict[str, bytes]:
- """Fallback when a round has no commit: the current ``src/`` + ``public/``."""
+ """The current ``src/`` + ``public/``, for a round with no commit."""
files: dict[str, bytes] = {}
for root in CODE_ROOTS:
base = ws.root / root
@@ -151,12 +129,9 @@ def read_working_tree(ws: Workspace) -> dict[str, bytes]:
def decode_text_files(files: dict[str, bytes], *, max_total: int | None = None) -> tuple[dict[str, str], list[str]]:
- """UTF-8 decode text files; binary files are listed in the second return value.
+ """UTF-8 decode text files; binary ones go in the second return value.
- ``max_total`` caps the summed decoded length (files are added in sorted path
- order; the first file that does not fit is truncated with a marker and the
- rest are skipped into the ``skipped`` list).
- """
+ ``max_total`` caps the summed length in sorted order: the first overflow is truncated, the rest skipped."""
text: dict[str, str] = {}
skipped: list[str] = []
total = 0
diff --git a/harness/codeverse3d/record/record.py b/harness/codeverse3d/record/record.py
index 82c59941..34eb1943 100644
--- a/harness/codeverse3d/record/record.py
+++ b/harness/codeverse3d/record/record.py
@@ -1,10 +1,7 @@
"""Run records: finalise / load / iterate.
-``finalize_record`` is the last step of every track run: it fills the
-environment (tool versions + harness git sha), reads the run's total off its cost ledger
-(``telemetry/cost.jsonl``, the one record of money), writes ``telemetry/`` and writes ``record.json`` atomically. ``deliverable/`` is not
-the run's: which round to hand over is ``codeverse3d.addons.select``'s question
-(2026-09-22). Telemetry is best-effort: a run is never failed by it.
+``finalize_record`` fills the environment, reads the run's total off its cost ledger, writes
+``telemetry/`` and ``record.json`` atomically. Telemetry is best-effort and never fails a run.
"""
from __future__ import annotations
@@ -53,13 +50,8 @@ def _git(args: list[str], cwd: Path) -> subprocess.CompletedProcess[str] | None:
def _harness_git_sha(pkg_file: Path | None = None) -> str:
"""Commit of the harness checkout this package runs from (``""`` outside a checkout).
- The repository root is wherever git finds it — ``harness/`` is a subdirectory of
- the 3dcodeverse repo, so ``.git`` lives one level ABOVE the package (the old
- ``parents[2] / ".git"`` probe never matched and every record shipped an empty sha).
- Two guards keep a wheel or a venv copy from borrowing an unrelated repo's sha:
- the file itself must be tracked by the repo git resolves to, and a modified
- working tree is marked ``-dirty`` so a score is never attributed to a clean commit
- it did not run on.
+ The file itself must be tracked (a wheel or venv copy must not borrow an unrelated repo's
+ sha); a modified tree is marked ``-dirty``.
"""
here = (pkg_file or Path(__file__)).resolve()
tracked = _git(["ls-files", "--error-unmatch", here.name], here.parent)
@@ -89,7 +81,7 @@ def _chrome_version() -> str:
def _node_pkg_version(name: str) -> str:
try:
pkg = node_modules_dir() / name / "package.json"
- except RuntimeError: # no runtime_js: a provenance field, never the end of a finished run
+ except RuntimeError: # no runtime_js: provenance only
return ""
return str((read_json_or_none(pkg) or {}).get("version", ""))
@@ -117,23 +109,19 @@ def environment_versions() -> dict[str, str]:
# --------------------------------------------------------------------------- derived fields
def effective_judgment(r: RoundRecord):
- """The round's judgment, or ``None`` when it is a degraded (judge-outage)
- verdict — the flywheel must treat those as 'no score', never as a 0.0."""
+ """The round's judgment, or ``None`` when degraded (never a 0.0 score)."""
j = r.judgment
return None if j is None or j.degraded else j
def previous_verdict(rounds: Iterable[RoundRecord | None], index: int) -> Judgment | None:
- """The verdict round ``index``'s judge is shown as the last one: round ``index - 1``'s effective
- judgment, None when that round went unjudged — never an older round's (the judge prompt calls
- it round N-1). The round loop's rule; ``3dcode judge`` and calibration replay it."""
+ """Round ``index - 1``'s effective judgment (None when unjudged), never an older round's."""
prev = next((r for r in rounds if r is not None and r.index == index - 1), None)
return effective_judgment(prev) if prev is not None else None
def rubric_of(record: RunRecord) -> str:
- """The rubric ``record``'s run is judged on: the one it stamped (``extra["rubric"]``), else —
- an older record — its last judged round's, else the run rule (``judges.base.run_rubric``)."""
+ """The run's rubric: the stamped one, else its last judged round's, else ``judges.base.run_rubric``."""
from codeverse3d.judges.base import run_rubric
judged = (r.judgment.rubric for r in reversed(record.rounds) if r.judgment is not None and r.judgment.rubric)
@@ -141,7 +129,7 @@ def rubric_of(record: RunRecord) -> str:
def stop_reason(record: RunRecord) -> str:
- """Why the run stopped: ``extra["stop_reason"]`` (what the loop stamped), else its status."""
+ """Why the run stopped: the stamped ``stop_reason``, else its status."""
return str(record.extra.get("stop_reason") or record.status.value)
@@ -156,19 +144,14 @@ def _n_gate_errors(r: RoundRecord) -> int:
def round_complexity(r: RoundRecord) -> dict[str, Any] | None:
- """The round's objective complexity vector, as measured on its own build.
-
- ``spatial/measure.py`` stores it in ``Measurement.extra["complexity"]``; a
- round measured before that existed (or one whose build failed) has none."""
+ """The round's objective complexity vector (``Measurement.extra["complexity"]``), or None."""
m = r.measurement
block = (m.extra.get("complexity") if m is not None else None)
return block if isinstance(block, dict) else None
def round_summary(r: RoundRecord) -> dict[str, Any]:
- """Compact per-round digest (the dataset sample's ``rounds_summary``).
-
- A degraded judgment shows up as score/passed None + ``judge_degraded``."""
+ """Compact per-round digest; a degraded judgment shows as score/passed None + ``judge_degraded``."""
j = effective_judgment(r)
cx = round_complexity(r)
return {
@@ -189,8 +172,7 @@ def round_summary(r: RoundRecord) -> dict[str, Any]:
def fill_derived(record: RunRecord) -> RunRecord:
- """Fill finished_at/environment when absent and the complexity block. No best round,
- baseline or final score: which round counts is ``addons.select``'s question (2026-09-22)."""
+ """Fill finished_at/environment when absent and the complexity block."""
if record.finished_at is None:
record.finished_at = datetime.now(UTC)
env = dict(environment_versions())
@@ -203,11 +185,7 @@ def fill_derived(record: RunRecord) -> RunRecord:
def complexity_block(record: RunRecord) -> dict[str, Any] | None:
- """``record.extra["complexity"]``: the complexity vector of the last measured round —
- the build ``src/`` and ``artifacts/`` end at — plus what the plan asked for and the
- per-round trail. ``plan_parts`` / ``parts_per_plan_part`` say whether the build
- reached the plan's ambition or collapsed it (eval/docs/COMPLEXITY.md). A reader that
- wants the picked round's vector reads that round's own (:func:`round_complexity`)."""
+ """``record.extra["complexity"]``: the last measured round's vector, plus plan parts and the per-round trail."""
cx = next((c for c in (round_complexity(r) for r in reversed(record.rounds)) if c), None)
if cx is None:
return None
@@ -224,21 +202,16 @@ def complexity_block(record: RunRecord) -> dict[str, Any] | None:
# --------------------------------------------------------------------------- io
def package_run(ws: Workspace, record: RunRecord) -> None:
- """Read the run's total off its ledger, materialise ``telemetry/`` and mirror it onto the
- record. ``record.total_usage`` is the sum of ``telemetry/cost.jsonl`` at list price — every
- billed row once: the planner, an aborted round, a retried session, a round-trip the
- provider billed and the call discarded, and post-run work (a pairwise pick) once it
- joined the ledger. A run with no ledger keeps what it has.
-
- Best-effort by contract: a failure is logged and the run still gets its
- ``record.json`` (the old layout is always enough to read a run)."""
+ """Read the run's total off its ledger (``record.total_usage`` = its sum at list price), write ``telemetry/``.
+
+ Best-effort: a failure is logged and the run still gets its ``record.json``."""
from codeverse3d.record.telemetry import build_telemetry
if existing_ledger_path(ws.root) is not None:
record.total_usage = ledger_usage(load_ledger(ws.root))
try:
ws.ensure_layout()
- except OSError as e: # read-only mount, exotic filesystem
+ except OSError as e: # read-only mount
log.warning("run layout not created in %s: %s", ws.root, e)
return
try:
@@ -248,8 +221,7 @@ def package_run(ws: Workspace, record: RunRecord) -> None:
def repackage(ws: Workspace) -> RunRecord | None:
- """Re-package a finished run's ``record.json`` after its ledger grew (:func:`package_run`), and
- return it; None — nothing written — when the run keeps no ledger or no readable record."""
+ """Re-package a finished run's ``record.json`` after its ledger grew; None when there is no ledger or record."""
if existing_ledger_path(ws.root) is None:
return None
try:
@@ -263,10 +235,8 @@ def repackage(ws: Workspace) -> RunRecord | None:
@contextmanager
def join_post_run(ws: Workspace) -> Iterator[None]:
- """Work on a FINISHED run that may spend money (a re-judge, a pairwise
- pick): its rows join the run's ledger when it keeps one (``run_ledger(create=False)``), and
- on the way out — also when the work raised after paying — the record is re-packaged, so
- ``record.total_usage`` stays the ledger's sum (D84)."""
+ """Work on a finished run that may spend money: rows join its ledger, and the record is
+ re-packaged on the way out (even on error) so ``total_usage`` stays the ledger's sum."""
from codeverse3d.cost.instrument import run_ledger
try:
@@ -291,33 +261,24 @@ def load_record(ws: Workspace | Path | str) -> RunRecord:
raise RecordError(f"no record.json in {ws.root}")
try:
return RunRecord.model_validate_json(ws.record_path.read_text())
- except Exception as e: # pydantic ValidationError / JSON error
+ except Exception as e:
raise RecordError(f"invalid record.json in {ws.root}: {e}") from e
-# Battery layouts nest their runs at these depths below the battery root: run_bench
-# ``runs/<id>`` = 2, compare_backends ``cells/<id>/<arm>/run`` = 4, ab_plan
-# ``arms/<arm>/cells/<id>/<slug>/run`` = 6. Seven covers all three with a margin and
-# stops a mistyped root from walking a whole home directory.
+# deepest battery layout is 6 levels; 7 also stops a mistyped root from walking a home directory
RUN_SEARCH_DEPTH = 7
#: subdirectories that mark a bench battery directory rather than a plain runs root
BATTERY_MARKERS = ("runs", "cells", "arms")
-#: run-layout directories that hold a SUB-workspace (a scene asset candidate, a rejected
-#: best-of-N candidate): their files belong to that sub-run, not to the run above them.
-#: :func:`unique_files` and the bench survey scripts skip them by this one name.
+#: directories holding a sub-workspace (asset / best-of-N candidate): their files are not the parent run's
SUBRUN_DIRS: frozenset[str] = frozenset({"_cand", "_assets"})
def unique_files(root: Path | str, name: str, *, subruns: bool = False) -> list[Path]:
"""Every file called ``name`` under ``root``, once per file on disk.
- Battery trees symlink each other's cells and every run has
- ``run/telemetry/trajectories -> run/trajectories``, so a walk must say what it does
- about symlinks: this one follows them (``recurse_symlinks=True``) and collapses the
- two paths of one file by its resolved path. Sub-workspaces (:data:`SUBRUN_DIRS`) are
- skipped unless ``subruns`` (a best-of-N candidate's session is a session). The one walker for every survey that counts sessions, records or artefacts —
- each hand-rolled copy of it has at some point counted a file twice."""
+ Follows symlinks and collapses duplicates by resolved path; sub-workspaces
+ (:data:`SUBRUN_DIRS`) are skipped unless ``subruns``."""
seen: dict[Path, Path] = {}
root = Path(root)
for p in sorted(root.rglob(name, recurse_symlinks=True)):
@@ -332,8 +293,7 @@ def is_run_dir(p: Path) -> bool:
def battery_label(root: Path | str) -> str:
- """Label for a scan root: the battery name for ``eval/bench/out/<battery>/runs``,
- else the directory's own name (the same rule the gallery sections use)."""
+ """Label for a scan root: the battery name for ``.../out/<battery>/runs``, else the directory name."""
root = Path(root)
if root.name == "runs" and root.parent.name and root.parent.parent.name == "out":
return root.parent.name
@@ -341,14 +301,11 @@ def battery_label(root: Path | str) -> str:
def run_id_for(root: Path | str, run_dir: Path) -> RunId:
- """The :class:`~codeverse3d.contracts.run.RunId` of ``run_dir`` as found under scan
- root ``root``. Identity is minted HERE, at discovery time — the Workspace
- resolves its root and forgets where the scan started, so it cannot do this."""
+ """The ``RunId`` of ``run_dir`` under scan root ``root`` (minted here: a Workspace forgets the scan root)."""
return RunId(battery=battery_label(root), rel=run_dir.relative_to(Path(root)).as_posix())
class FoundRun(NamedTuple):
- """One discovered run: workspace + parsed record + identity within the scan root."""
ws: Workspace
record: RunRecord
@@ -359,14 +316,8 @@ def find_run_dirs(root: Path | str, *, predicate: Callable[[Path], bool] = is_ru
max_depth: int = RUN_SEARCH_DEPTH) -> list[Path]:
"""Run directories under ``root``, sorted.
- Direct children win when there are any — that is the ``3dcode`` runs root and the
- run_bench ``runs/`` layout, and it keeps the common case a single ``iterdir()``.
- Only when there are none do we descend, which is what makes a compare_backends or
- ab_plan BATTERY directory work: those hold their runs four and five levels down, so
- every exporter used to scan one level, find nothing and report "0 runs" as a success.
- A directory that IS a run is never descended into (a run holds candidate workspaces
- of its own). A run reached through more than one path (``eval/bench/out``'s batteries
- symlink each other's cells) is listed once, at the path it physically lives at.
+ Direct children win; only when there are none does it descend (battery layouts).
+ A run is never descended into, and one reached through several paths is listed once, at its physical path.
"""
root = Path(root)
if not root.is_dir():
@@ -401,19 +352,16 @@ def _once(root: Path, dirs: list[Path]) -> list[Path]:
def skip_unreadable(run_dir: Path, error: Exception) -> None:
- """``iter_runs(on_error=...)`` for a reader that indexes what it can: one unreadable
- record.json is a warning, not the end of the whole pass."""
+ """``iter_runs(on_error=...)`` handler: log and skip an unreadable record.json."""
log.warning("skipping %s: %s", run_dir, error)
def iter_runs(
runs_dir: Path | str, *, on_error: Callable[[Path, Exception], None] | None = None
) -> Iterator[FoundRun]:
- """Yield a :class:`FoundRun` ``(ws, record, run_id)`` for every run directory
- holding a record.json.
+ """Yield a :class:`FoundRun` for every run directory holding a record.json.
- Invalid records raise ``RecordError`` unless ``on_error`` is given, in which
- case it is called and iteration continues (exporters collect skip reasons).
+ Invalid records raise ``RecordError`` unless ``on_error`` is given.
"""
root = Path(runs_dir)
if not root.is_dir():
@@ -421,12 +369,7 @@ def iter_runs(
children = find_run_dirs(root)
battery_dirs = [m for m in BATTERY_MARKERS if (root / m).is_dir()]
if not children and battery_dirs:
- # Silence must not look like an empty dataset. This guard used to test only for
- # ``<root>/runs`` — true for the run_bench layout, false for compare_backends
- # (cells/) and ab_plan (arms/), i.e. exactly today's batteries, which therefore
- # reported "0 runs" as a success. find_run_dirs now FINDS all three layouts, so
- # reaching here means a battery directory that really is empty; an ordinary runs
- # root with no runs in it stays a legitimate empty result.
+ # a battery directory that holds no run must not look like an empty dataset
raise FileNotFoundError(
f"no run directories under {root} — it looks like a battery directory "
f"({', '.join(battery_dirs)}/) but holds no record.json within "
diff --git a/harness/codeverse3d/record/telemetry.py b/harness/codeverse3d/record/telemetry.py
index 0a313998..670b9222 100644
--- a/harness/codeverse3d/record/telemetry.py
+++ b/harness/codeverse3d/record/telemetry.py
@@ -1,19 +1,5 @@
-"""Run telemetry: the resolved settings snapshot + the summary of the money ledger.
-
-Beside the ledger itself, ``telemetry/cost.jsonl`` (one priced row per model call, written
-while the run happens — ``codeverse3d.cost``), two files under ``<run>/telemetry/``:
-
-* ``settings.json`` — how the run was configured: model id per role, thinking
- level / temperature / judge samples, rounds + budget, rubric and its content
- hash, prompt and skill hashes, tool versions, harness git sha, key-pool size,
- price-table hash, render + limit settings.
-* ``cost.json`` — the run-layout summary of the ledger rows: totals, per stage, per
- role, per model, per round, the run's minutes against ``max_minutes``.
-
-The same content is mirrored into ``record.telemetry`` so a consumer that only
-has ``record.json`` sees it too. Nothing here is required for a run to
-succeed: every builder degrades to "what could be read".
-"""
+"""Run telemetry: ``telemetry/settings.json`` (how the run was configured) and ``cost.json``
+(summary of the ledger rows), mirrored into ``record.telemetry``. Builders degrade to what could be read."""
from __future__ import annotations
@@ -41,7 +27,7 @@ log = logging.getLogger(__name__)
# --------------------------------------------------------------------------- settings snapshot
def price_table_version() -> str:
- """Content hash of the USD price table — the run was costed with THIS table."""
+ """Content hash of the USD price table."""
from codeverse3d.models.pricing import PRICES
payload = json.dumps(
@@ -52,7 +38,7 @@ def price_table_version() -> str:
def backend_kind(model_id: str) -> str:
- """``api-agent:gemini:gemini-3.8-flash`` → ``api-agent``; ``gemini:x`` → ``gemini``."""
+ """``gemini:x`` → ``gemini``."""
return model_id.split(":", 1)[0] if ":" in model_id else model_id
@@ -69,10 +55,7 @@ def rubric_hash(name: str) -> str:
def _role_settings(record: RunRecord) -> list[RoleSettings]:
- """The model per role from the spec; the sampling knobs from what the track stamped as it
- ran (``record.extra["sampling"]``: the planner's temperature, the judge's temperature /
- thinking / samples). A vendor CLI owns its own knobs, and a record written before
- 2026-09-22 carries none: left empty, never guessed."""
+ """The model per role from the spec; sampling knobs from ``record.extra["sampling"]``, else left empty."""
b = record.spec.backends
sampling = record.extra.get("sampling") or {}
roles: list[RoleSettings] = []
@@ -89,7 +72,7 @@ def _role_settings(record: RunRecord) -> list[RoleSettings]:
def settings_snapshot(record: RunRecord) -> SettingsSnapshot:
- """The resolved 'how was this run configured' block (no secrets, ever)."""
+ """The resolved configuration block (no secrets)."""
spec = record.spec
rubric = rubric_of(record)
s = get_settings()
@@ -120,9 +103,7 @@ def settings_snapshot(record: RunRecord) -> SettingsSnapshot:
def _variant_fields(record: RunRecord) -> tuple[str, int, str]:
- """``(name, version, hash)`` of the variant the run used (D105): what the track stamped as it ran
- (``record.extra["variant"]``), else the environment / the spec's frozen name with no version or hash
- (a record written by another tool); the base is ``("", 0, "")``."""
+ """``(name, version, hash)`` of the variant the run used; the base is ``("", 0, "")``."""
block = record.extra.get("variant")
block = block if isinstance(block, dict) else {}
name = str(block.get("name") or record.environment.get("variant") or record.spec.options.variant or "")
@@ -139,7 +120,7 @@ _TOOL_KEYS = frozenset({"python", "platform", "host", "blender", "blender_path",
# --------------------------------------------------------------------------- the ledger (codeverse3d.cost)
def ledger_rows(ws: Workspace) -> list[CallCost]:
- """The run's priced per-call rows, ``telemetry/cost.jsonl`` (none when it has no ledger)."""
+ """The run's priced per-call rows (none without a ledger)."""
try:
return load_ledger(ws.root)
except Exception as e: # noqa: BLE001 - accounting must never fail a run
@@ -148,9 +129,7 @@ def ledger_rows(ws: Workspace) -> list[CallCost]:
def cost_summary(record: RunRecord, rows: list[CallCost]) -> CostSummary:
- """The ledger rows as the run layout shows them: total, per stage / role / model (the
- ledger's own ``summarise`` — money by stage is computed there and nowhere else), per round,
- and the run's minutes against ``max_minutes``."""
+ """The ledger rows as the run layout shows them: total, per stage / role / model / round, and minutes."""
summ = summarise(rows, dimensions=("stage", "role", "model"))
rank = {s: i for i, s in enumerate(STAGE_ORDER)}
by_stage = [StageCost(stage=b.key, calls=b.n_calls, input_tokens=b.input_tokens, output_tokens=b.output_tokens,
@@ -200,6 +179,6 @@ def load_telemetry(ws: Workspace, record: RunRecord | None = None) -> RunTelemet
settings=SettingsSnapshot.model_validate(settings) if settings else None,
cost=CostSummary.model_validate(cost) if cost else None,
)
- except Exception as e: # a hand-edited file must not break status/export
+ except Exception as e:
log.warning("unreadable telemetry in %s: %s", ws.root, e)
return None
diff --git a/harness/codeverse3d/reference.py b/harness/codeverse3d/reference.py
index 22f309f8..5548f582 100644
--- a/harness/codeverse3d/reference.py
+++ b/harness/codeverse3d/reference.py
@@ -1,12 +1,8 @@
"""Reference comparison: judge a render against the user's own ``--image`` pictures.
-The user's reference images ride in ``spec.references``. This module is what
-measures and names the distance between one of them and a render: the brief's
-dimension band vs the picture's outline (:func:`dimension_conflict` — when they
-disagree the BRIEF wins and the picture is a shape target only), and one vision
-call that lists concrete mismatches (:func:`compare`). The planner, the
-generator's ``compare_reference`` tool, the silhouette gate and the judge
-(:class:`codeverse3d.judges.vlm_judge.ReferenceJudge`) all read it.
+Measures and names the distance between a ``spec.references`` image and a render: the brief's
+dimension band vs the picture's outline (:func:`dimension_conflict`; the BRIEF wins on a conflict)
+and one vision call listing concrete mismatches (:func:`compare`).
"""
from __future__ import annotations
@@ -36,8 +32,6 @@ _SEVERITY_ORDER = {"critical": 0, "major": 1, "minor": 2}
class Mismatch(BaseModel):
- """One concrete difference between the reference and the render."""
-
kind: MismatchKind
target: str = Field(default="overall", description="part name from the plan, or 'overall'")
detail: str = Field(description="what the reference shows vs what the render shows")
@@ -62,11 +56,9 @@ class ReferenceDiff(BaseModel):
error: str = ""
def top(self, n: int = 3) -> list[Mismatch]:
- """The ``n`` mismatches worth spending a refine task on (severity first)."""
return sorted(self.mismatches, key=lambda m: _SEVERITY_ORDER.get(m.severity, 3))[:n]
def as_text(self, n: int = 6) -> str:
- """Compact block for a judge / agent prompt (empty when nothing to say)."""
if self.error or not (self.mismatches or self.matches):
return ""
lines = ["REFERENCE DIFF (harness vision pass, target = the REFERENCE image):"]
@@ -83,7 +75,6 @@ class ReferenceDiff(BaseModel):
# ===================================================================== spec_text
def brief_text(spec: Spec) -> str:
- """The prompt + the constraints a picture could show, as one block."""
lines = [spec.prompt.strip()]
c = spec.constraints
if c.style:
@@ -142,15 +133,8 @@ _WIDTH_KEYS = ("width", "length", "depth", "diameter")
def expected_aspect_range(spec: Spec) -> tuple[float, float] | None:
- """The width/height band any straight-on elevation of the brief could show.
-
- A brief does not say which face a photograph shows, so the honest expectation
- is a RANGE: the narrowest and the widest horizontal extent the brief states,
- each over the stated height. Only a picture outside that band by more than
- :data:`ASPECT_TOL` disagrees with the brief — which keeps a chair whose photo
- is a little wide from being flagged while still catching a 0.14 m grinder body
- photographed with its 0.12 m crank arm.
- """
+ """The width/height band any straight-on elevation of the brief could show (a RANGE, since the
+ brief does not say which face a photograph shows)."""
dims = spec.constraints.dimensions_m or {}
height = dims.get("height")
if not height or height <= 0:
@@ -162,18 +146,13 @@ def expected_aspect_range(spec: Spec) -> tuple[float, float] | None:
def expected_front_aspect(spec: Spec) -> float | None:
- """Mid-point of :func:`expected_aspect_range` (``None`` if unstated)."""
rng = expected_aspect_range(spec)
return None if rng is None else (rng[0] + rng[1]) / 2
def dimension_conflict(spec: Spec, image: Path | str) -> dict[str, Any]:
- """``{conflict, expected_aspect, image_aspect, error}`` — never raises.
-
- ``conflict`` is True only when the brief states a height plus one horizontal
- dimension AND the image's own silhouette aspect is off by more than
- :data:`ASPECT_TOL`. An unmeasurable image is never a conflict.
- """
+ """``{conflict, expected_aspect, image_aspect, error}`` — never raises; conflict only when the
+ image's silhouette aspect is off the brief's band by more than :data:`ASPECT_TOL`."""
rng = expected_aspect_range(spec)
out: dict[str, Any] = {"conflict": False, "expected_aspect": expected_front_aspect(spec),
"expected_range": list(rng) if rng else None, "image_aspect": None, "error": ""}
@@ -198,7 +177,6 @@ def dimension_conflict(spec: Spec, image: Path | str) -> dict[str, Any]:
def conflict_note(info: dict[str, Any]) -> str:
- """One line for a judge / CLI, empty when there is no conflict."""
if not info.get("conflict"):
return ""
lo, hi = info.get("expected_range") or (0.0, 0.0)
diff --git a/harness/codeverse3d/skills/__init__.py b/harness/codeverse3d/skills/__init__.py
index 99ff1c9f..9f5e8db6 100644
--- a/harness/codeverse3d/skills/__init__.py
+++ b/harness/codeverse3d/skills/__init__.py
@@ -1,38 +1,13 @@
"""The 3dcode skill library: task-scoped rule sheets, routed automatically, read-measured.
-A *skill* is not a recipe library — the two sides of the split in ``prompts/catalog.py``:
-PROMPT material (``contract.md`` / ``system.md``: interface, sandbox, measured requirements)
-is what the harness puts in a message; a skill is AGENT-READ material the harness only
-materialises: <=350 lines of measured requirements and a few short optional practices for
-one recurring failure class (library / API names, fences of ~12 lines at most, numbers only
-where a gate or the judge measures them — D107), attached to a session only when the track /
-language / kind / plan / **previous round's gate findings** say it applies. (The cookbooks
-that preceded the library were deleted track by track, D106 / D107; the ``read_cookbook`` MCP
-tool that served them a chapter at a time was measured at 0 calls in 16 zone sessions.)
-
-Why the library lives inside the package: every backend reads it from a materialised
-workspace copy, but the source of truth ships in the wheel, so it must be package data
-(``pyproject.toml`` ``[tool.setuptools.package-data]``) — a sibling wave already shipped
-a wheel whose starter tree was silently empty for want of that glob.
-
-Per-model variants (D105, 2026-10-14): ``<skills_dir>/variants/<name>/`` is an OVERLAY on
-the library while that variant is active (``codeverse3d.prompts.variants.active_variant``):
-its bundles shadow base bundles by name or add new ones (:func:`all_skills` merges the two
-roots, :func:`library_roots`), its ``_claims/`` is consulted first
-(``addons/skill_targets.claims_path``), and its ``routes.toml`` — boosts, disabled rule ids,
-extra typed rows — reshapes the routing table (:func:`variants_table`, parsed with ``tomllib``
-into typed records; ``registry.select`` applies it). ``bundle_dirs`` never descends into it:
-``variants/`` has no ``SKILL.md``, so the base listing is what it always was — ``3dcode skills
-validate`` / ``list`` walk every shipped root through :func:`shipped_roots`.
-
-Public surface for the rest of the harness::
-
- from codeverse3d.skills import select, attach_skills, probe_reads
-
-``select`` is pure and testable; ``attach_skills`` writes the routed bundles into a
-workspace and returns what it wrote; ``probe_reads`` says afterwards which of them were
-actually opened — from the CLI's own tool calls where its backend recorded them. Everything
-is behind ``C3D_SKILLS``: ON by default since 2026-09-22, ``C3D_SKILLS=0`` turns it off.
+A skill is AGENT-READ material (<=350 lines of requirements and short optional practices for one
+failure class) that the harness only materialises, when track / language / kind / plan / the
+previous round's gate findings say it applies. The library ships as package data.
+``<skills_dir>/variants/<name>/`` overlays it while that variant is active: its bundles shadow
+base ones by name, its ``routes.toml`` reshapes the routing table.
+
+Public surface: ``select`` (pure routing), ``attach_skills`` (write the routed bundles),
+``probe_reads`` (which were opened). Controlled by ``C3D_SKILLS`` (default on).
"""
from __future__ import annotations
@@ -59,15 +34,13 @@ if TYPE_CHECKING:
log = logging.getLogger(__name__)
-#: the per-model overlays live under the library: ``<skills_dir>/variants/<name>/``
+#: per-model overlays: ``<skills_dir>/variants/<name>/``
VARIANTS_SUBDIR = "variants"
-#: a variant's routing-table overlay, beside its bundles
+#: a variant's routing-table overlay
ROUTES_FILE = "routes.toml"
def skills_dir() -> Path:
- """The bundle root: this package's directory, as for prompts and rubrics
- (``C3D_SKILLS_DIR`` points it elsewhere, read at call time)."""
override = get_settings().skills_dir
if override:
return override.expanduser()
@@ -75,13 +48,10 @@ def skills_dir() -> Path:
def variant_dir(name: str) -> Path:
- """``<skills_dir>/variants/<name>`` — the skills half of a variant overlay (it need not exist)."""
return skills_dir() / VARIANTS_SUBDIR / name
def library_roots(variant: str | None = None) -> list[Path]:
- """The bundle roots in shadowing order: the base library, then the active variant's overlay
- when the variant ships one. ``variant`` names one explicitly instead of :func:`active_variant`."""
name = active_variant() if variant is None else variant
roots = [skills_dir()]
if name:
@@ -94,10 +64,7 @@ def library_roots(variant: str | None = None) -> list[Path]:
def bundle_dirs(root: Path | None = None) -> list[Path]:
"""Every directory under the library that looks like a bundle, sorted by name.
- ``_claims/`` and ``__pycache__/`` are deliberately invisible: the library shares a
- directory with this package's modules, and a pure tree is what ``skills-ref
- validate`` and the CLIs expect to walk. ``variants/`` has no ``SKILL.md`` and is skipped
- the same way — an overlay root is listed by passing it as ``root``.
+ ``_claims/``, ``__pycache__/`` and ``variants/`` are invisible; pass an overlay as ``root``.
"""
base = Path(root) if root is not None else skills_dir()
if not base.is_dir():
@@ -108,11 +75,6 @@ def bundle_dirs(root: Path | None = None) -> list[Path]:
def iter_skills(root: Path | None = None, *, strict: bool = False) -> Iterator[Skill]:
- """Every valid bundle. A broken one is logged and skipped unless ``strict``.
-
- Skipping is the right default in a run: one malformed bundle must cost that skill,
- not the battery. ``3dcode skills validate`` and the test suite pass ``strict=True``.
- """
for d in bundle_dirs(root):
try:
yield parse_skill(d)
@@ -123,9 +85,6 @@ def iter_skills(root: Path | None = None, *, strict: bool = False) -> Iterator[S
def all_skills(root: Path | None = None, *, strict: bool = False) -> dict[str, Skill]:
- """name → Skill. With no ``root``: the base library updated by the active variant's overlay
- (a same-name bundle shadows the base one, a new name is added); with ``root``: that directory
- alone. Empty when no bundles ship yet."""
if root is not None:
return {s.name: s for s in iter_skills(root, strict=strict)}
out: dict[str, Skill] = {}
@@ -135,8 +94,6 @@ def all_skills(root: Path | None = None, *, strict: bool = False) -> dict[str, S
def load_skill(name: str, root: Path | None = None) -> Skill:
- """One bundle by name — the active variant's copy first; raises :class:`SkillError` when it is
- missing or invalid."""
roots = [Path(root)] if root is not None else list(reversed(library_roots()))
for base in roots:
d = base / name
@@ -147,25 +104,20 @@ def load_skill(name: str, root: Path | None = None) -> Skill:
@dataclass(frozen=True)
class ShippedRoot:
- """One root the library ships: the base (``variant == ""``) or one variant's skills overlay."""
variant: str
path: Path
def label(self, bundle: str) -> str:
- """How the CLIs and the doctor name a bundle of this root: ``<variant>/<bundle>`` for an overlay."""
return f"{self.variant}/{bundle}" if self.variant else bundle
def shipped_roots(variants: Iterable[str] | None = None) -> list[ShippedRoot]:
- """The base root, then the skills overlay of every shipped variant that has one — every directory
- a run can route a bundle from, whichever variant it activates. ``3dcode skills validate`` /
- ``list`` walk THIS rather than :func:`bundle_dirs` alone: an overlay bundle
- a loop iteration wrote is routed the moment its variant is active (:func:`all_skills`), so a
- malformed one must fail validation here, not vanish from a session with a logged warning while
- the row that named it routes nothing. ``variants`` names the ones to walk; the default is every
- variant ``prompts.variants.list_variants`` knows, and a ``variant.toml`` that does not parse raises
- its ``ValueError`` (a shipped variant is never half-known)."""
+ """The base root, then the skills overlay of every shipped variant that has one.
+
+ ``3dcode skills validate`` / ``list`` walk this so a malformed overlay bundle fails validation
+ instead of silently not routing. ``variants`` defaults to every variant ``list_variants`` knows.
+ """
from codeverse3d.prompts.variants import list_variants
names = list(list_variants()) if variants is None else list(variants)
@@ -177,9 +129,6 @@ def shipped_roots(variants: Iterable[str] | None = None) -> list[ShippedRoot]:
# ===================================================================== the variant routing table
@dataclass(frozen=True)
class RouteBoost:
- """``[[boost]]``: ``delta`` is added to the priority of every route naming ``skill``
- (``registry.effective_priority`` clamps: a standing row stays below 90, a gate-fired row never
- falls under it)."""
skill: str
delta: int
@@ -187,8 +136,7 @@ class RouteBoost:
@dataclass(frozen=True)
class VariantRoutes:
- """A variant's ``routes.toml``: boosts, disabled base rule ids and extra typed rows, parsed with
- ``tomllib`` (no regex). The extra rows are appended AFTER the base table (ties keep base order)."""
+ """A variant's ``routes.toml``: boosts, disabled base rule ids and extra typed rows (appended after the base table)."""
variant: str = ""
routes: tuple[Route, ...] = ()
@@ -197,7 +145,6 @@ class VariantRoutes:
@property
def boost_map(self) -> dict[str, int]:
- """skill → summed delta (what ``registry.select`` takes)."""
out: dict[str, int] = {}
for b in self.boosts:
out[b.skill] = out.get(b.skill, 0) + b.delta
@@ -209,10 +156,7 @@ class VariantRoutes:
def variants_table(name: str) -> VariantRoutes:
- """The variant's table: ``<skills_dir>/variants/<name>/routes.toml`` parsed, or an empty table when
- the variant ships none (or ``name`` is the base). A table that does not type-check raises
- ``ValueError`` naming the row and the problem — ``attach_skills`` logs it and routes with the
- base table, so a typo costs the overlay, never the round."""
+ """The variant's parsed ``routes.toml``, or an empty table when it ships none; raises ``ValueError`` naming the bad row."""
if not name:
return VariantRoutes()
path = variant_dir(name) / ROUTES_FILE
@@ -227,8 +171,7 @@ _ROUTE_TUPLES = ("tracks", "languages", "kinds", "requires_all", "requires_any",
def parse_routes(path: Path, *, variant: str = "") -> VariantRoutes:
- """Parse one ``routes.toml`` into typed records; every typing error is a ``ValueError`` that names
- the row (``<path>: [[route]] #2: priority must be an integer``)."""
+ """Parse one ``routes.toml`` into typed records; every typing error is a ``ValueError`` naming the row."""
from codeverse3d.skills.registry import GATE_FIRED_PRIORITY, ROUTES, Route
try:
@@ -247,8 +190,7 @@ def parse_routes(path: Path, *, variant: str = "") -> VariantRoutes:
for where, row in _rows(data, "route", path, _ROUTE_KEYS):
findings = _tuple(row, "findings", where)
priority = _int(row, "priority", where)
- # the table's law (design §5.2 law 2): a priority >= 90 MEANS "a gate routed this" to telemetry
- # and to Selection.gate_fired, so an extra row may only sit there when it answers a finding
+ # a priority >= 90 means "a gate routed this" (Selection.gate_fired): only rows that name findings may sit there
if findings and priority < GATE_FIRED_PRIORITY:
raise ValueError(f"{where}: a gate-fired row (it names findings) needs priority >= "
f"{GATE_FIRED_PRIORITY}, got {priority}")
diff --git a/harness/codeverse3d/skills/materialize.py b/harness/codeverse3d/skills/materialize.py
index 15a80ada..cd7073a9 100644
--- a/harness/codeverse3d/skills/materialize.py
+++ b/harness/codeverse3d/skills/materialize.py
@@ -1,32 +1,8 @@
-"""Write the routed bundles into a workspace, as real files, twice.
+"""Write the routed skill bundles into a workspace as real files, in both discovery roots.
-WHY twice: the discovery roots were read out of the shipped binaries, not assumed.
-codex and agy both read ``<ws>/.agents/skills/<name>/SKILL.md``; claude-code
-2.1 reads ``<ws>/.claude/skills/<name>/SKILL.md`` and has **no** ``.agents`` skill root at
-all (its ``.agents`` strings are plugin-migration paths). So the same bytes go to both.
-
-WHY copies and not symlinks: codex refuses them outright ("Symbolic links are not allowed
-in skills"). A 2-10 KB duplicate in a disposable workspace costs nothing.
-
-WHY ``os.utime`` at the end: the read probe in ``telemetry.py`` says a bundle was opened
-when ``atime > mtime``. That only means anything if the two start equal, so
-materialisation stamps them equal instead of trusting whatever the copy left behind.
-
-WHY a CONTROL bundle goes in beside them: because ``atime > mtime`` turned out to be a
-much weaker signal than the design assumed, and measured on 2026-08-25 it fires with
-nobody reading anything. Two independent causes, both verified:
-
-* ``Workspace.changed_files`` runs ``git add -A -N`` then ``git diff --numstat`` after
- every agent session, and git reads each untracked file to compute the diff. On a real
- git workspace that alone flips all four files of a bundle to "read".
-* every CLI (codex 0.149.0, claude-code 2.1.245, agy 1.1.20 — and gemini-cli 0.53.0, gone since D103) opens
- ``references/*.md`` while activating a skill, including on a task whose description does
- not match and with the prompt telling them not to activate anything.
-
-Neither can be argued away, so the probe carries its own falsification: one extra bundle
-that is never routed, never indexed and never mentioned. If IT comes back "read", the
-session's atime evidence proves nothing and ``deep_read_rate`` reports ``None`` instead of
-a confident 100%.
+Copies, not symlinks (codex refuses symlinks). A never-routed CONTROL bundle goes in beside
+them: if the control reads as "read" the atime probe in ``telemetry.py`` proves nothing
+(git and every CLI touch bundle files regardless). ``os.utime`` stamps atime == mtime.
"""
from __future__ import annotations
@@ -60,8 +36,7 @@ BODY_FILES = ("AGENTS.md", "CLAUDE.md")
MARK_BEGIN = "<!-- 3dcode:skills -->"
MARK_END = "<!-- /3dcode:skills -->"
-#: the never-routed bundle whose atime falsifies the probe. Named so it sorts away from
-#: the real ones, and worded so an agent that does read it has been told it is a control.
+#: the never-routed bundle whose atime falsifies the read probe
CONTROL_NAME = "zz-c3d-read-control"
CONTROL_SKILL_MD = f"""---
name: {CONTROL_NAME}
@@ -115,12 +90,7 @@ def _copy_bundle(skill: Skill, dest_root: Path) -> list[Path]:
def materialize_skills(ws_root: Path, skills: Sequence[Skill]) -> list[Path]:
- """Copy each bundle into both discovery roots; returns every file written.
-
- Stale bundles from a previous round are removed, so the workspace always shows the
- set this round actually routed — otherwise the read probe would credit a skill that
- a later round no longer attaches.
- """
+ """Copy each bundle into both discovery roots, removing stale bundles; returns every file written."""
root = Path(ws_root)
wanted = {s.name for s in skills} | {CONTROL_NAME}
written: list[Path] = []
@@ -140,12 +110,7 @@ def materialize_skills(ws_root: Path, skills: Sequence[Skill]) -> list[Path]:
def write_index(ws_root: Path, text: str) -> list[str]:
- """Replace (or append) the marked skills section in every agent body file.
-
- A marked section rather than a rewrite of the body: ``agents/materialize.py`` writes
- the body once per run, but the routed set changes per round, and rewriting the whole
- file from here would duplicate its knowledge of what belongs in it.
- """
+ """Replace (or append) the marked skills section in every agent body file."""
block = f"{MARK_BEGIN}\n{text.strip()}\n{MARK_END}\n" if text.strip() else ""
out: list[str] = []
for name in BODY_FILES:
@@ -180,14 +145,8 @@ def attach_skills(
) -> SkillsMaterialized:
"""Route → write → return what a session will see. The one entry point tracks call.
- The caller decides whether the feature is on (``Settings.skills``); this function
- assumes it is, so a test can attach without setting the environment.
-
- ``only`` (env ``C3D_SKILLS_ONLY``) restricts the LIBRARY before routing, which is
- what an effect A/B needs: the delta then belongs to one bundle instead of to whatever
- set of five the router happened to pick. Restricting the library — rather than
- filtering ``sel`` afterwards — also stops the cap from spending a slot on a bundle
- that is not under test and then dropping the one that is.
+ ``only`` restricts the LIBRARY before routing (an A/B isolates one bundle; filtering
+ ``sel`` afterwards would let the cap waste a slot on a bundle not under test).
"""
cfg = get_settings()
picked = frozenset(n.strip() for n in cfg.skills_only.split(",") if n.strip()) if only is None else only
@@ -199,8 +158,7 @@ def attach_skills(
if not library:
log.warning("C3D_SKILLS_ONLY=%s matches no bundle in the library; this session attaches nothing",
",".join(sorted(picked)))
- # the active variant (D105): its overlay bundles are already in all_skills() (select's default
- # library) and its routes.toml reshapes the table — extra rows after the base ones, boosts, disabled ids
+ # the active variant's overlay bundles are already in all_skills(); its routes.toml extends the table
variant = active_variant()
table = _routes_table(variant)
sel: list[Selection] = select(
@@ -213,8 +171,7 @@ def attach_skills(
out = SkillsMaterialized(listed=[s.name for s in sel], selections=list(sel),
reasons={s.name: s.reason for s in sel}, attached_at=time.time(), variant=variant)
if not sel or single_shot:
- # an empty selection is a legal desired set: the sweep must still run, or last
- # round's bundles stay live where the native CLIs discover skills by directory
+ # an empty selection must still sweep, or last round's bundles stay discoverable
with suppress(OSError):
materialize_skills(ws_root, [])
if not sel:
@@ -222,7 +179,7 @@ def attach_skills(
return out
if single_shot:
- # No read loop: a pointer to a file it cannot open would be pure cost.
+ # no read loop: a pointer to a file it cannot open would be pure cost
name, text = inline_body(sel)
out.inlined = name
out.index_tokens = 0
@@ -242,8 +199,7 @@ def attach_skills(
def _routes_table(variant: str) -> Any:
- """The variant's ``routes.toml`` as typed rows, or the empty table when it does not type-check: a
- typo in the overlay costs the overlay (logged, base routing), never the round's skills."""
+ """The variant's ``routes.toml`` as typed rows; an invalid overlay falls back to the base table."""
from codeverse3d.skills import VariantRoutes, variants_table
try:
diff --git a/harness/codeverse3d/skills/model.py b/harness/codeverse3d/skills/model.py
index 4879dcd9..dc489576 100644
--- a/harness/codeverse3d/skills/model.py
+++ b/harness/codeverse3d/skills/model.py
@@ -1,10 +1,4 @@
-"""Typed shapes for the skill library — one bundle, one selection, one session's usage.
-
-Frozen on purpose: a ``Skill`` is parsed from a file on disk once and then flows into
-prompts, workspaces and the run record. If any of those could mutate it, the body we
-measured (``body_tokens``) and the body we materialised could silently differ, and the
-telemetry in §6.4 of the design would be measuring a file nobody sent.
-"""
+"""Typed shapes for the skill library (frozen): one bundle, one selection, one session's usage."""
from __future__ import annotations
@@ -17,10 +11,7 @@ from pydantic import BaseModel, Field
from codeverse3d.cost.guard import text_tokens
-#: `metadata.evidence` values. A bundle whose claims are carried over from a reference
-#: library but which our own corpus cannot back yet is `inherited-unverified`, and the
-#: router refuses it when C3D_SKILLS_UNVERIFIED is off (design §5.2 law 3; the switch defaults
-#: ON since 2026-09-22, so the whole library routes unless it is set to 0).
+#: ``metadata.evidence`` values; the router refuses ``inherited-unverified`` when C3D_SKILLS_UNVERIFIED is 0.
EVIDENCE_MEASURED = "measured"
EVIDENCE_INHERITED = "inherited-unverified"
EVIDENCE_MIXED = "mixed"
@@ -47,7 +38,6 @@ class Skill(BaseModel):
@property
def body_tokens(self) -> int:
- """Estimated prompt tokens of the body — the number the budget test asserts."""
return text_tokens(self.body)
@property
@@ -60,16 +50,11 @@ class Skill(BaseModel):
@property
def verified(self) -> str:
- """ISO date the bundle's claims were last checked against the harness."""
return self.metadata.get("verified", "")
class Selection(BaseModel):
- """One routed skill **with the reason it was routed**, so telemetry can say WHY.
-
- astra3d had a human type ``skills: [...]``; we derive the set, which is only an
- improvement if the derivation is auditable after the fact.
- """
+ """One routed skill with the reason it was routed."""
model_config = {"frozen": True}
@@ -84,12 +69,11 @@ class Selection(BaseModel):
@property
def gate_fired(self) -> bool:
- """True when a previous-round gate finding routed this (design §5.2 law 2)."""
+ """True when a previous-round gate finding routed this."""
return self.priority >= 90
class SkillsMaterialized(BaseModel):
- """What :func:`codeverse3d.skills.materialize.materialize_skills` wrote into a workspace."""
listed: list[str] = Field(default_factory=list, description="skill names, in attach order")
selections: list[Selection] = Field(default_factory=list, description="the routed rows, with the reason each fired")
@@ -112,11 +96,10 @@ NAME_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
NAME_MAX = 64
DESCRIPTION_MAX = 1024
COMPATIBILITY_MAX = 500
-#: our body cap: half the spec's recommended 500 lines / 5,000 tokens, because
-#: docs/COST.md §4 shows we pay for every prompt byte on every turn, not once.
+#: body cap, kept small because every prompt byte is paid on every turn
BODY_MAX_LINES = 350
BODY_MAX_TOKENS = 2500
-#: the spec's top-level keys. Anything else belongs in `metadata`.
+#: the spec's top-level keys; anything else belongs in `metadata`
SPEC_KEYS = frozenset({"name", "description", "license", "compatibility", "metadata", "allowed-tools"})
_FRONTMATTER = re.compile(r"\A---[ \t]*\r?\n(.*?)\r?\n---[ \t]*\r?\n?", re.S)
@@ -148,12 +131,7 @@ def _as_str_map(value: object, where: str) -> dict[str, str]:
def nonstring_metadata(fm: dict) -> list[str]:
- """metadata values YAML did not hand back as strings.
-
- An unquoted ``verified: 2026-08-25`` is a YAML *date*, not a string, and the spec says
- metadata is string to string. ``_as_str_map`` coerces so a run never dies of it; the
- validator reports it so a bundle is not shipped depending on our leniency.
- """
+ """metadata values YAML did not hand back as strings (an unquoted ``verified: 2020-01-01`` is a date)."""
meta = fm.get("metadata")
if not isinstance(meta, dict):
return []
@@ -222,11 +200,7 @@ def _references(bundle: Path) -> tuple[str, ...]:
def validate_bundle(bundle: Path) -> list[str]:
- """Every problem with one bundle directory, as human lines (empty == clean).
-
- Structural problems come back as one line; budget/evidence/layout problems are
- listed together so `3dcode skills validate` fixes a bundle in one round trip.
- """
+ """Every problem with one bundle directory, as human lines (empty == clean)."""
bundle = Path(bundle)
try:
skill = parse_skill(bundle)
diff --git a/harness/codeverse3d/skills/prompting.py b/harness/codeverse3d/skills/prompting.py
index 9f741daf..fe495670 100644
--- a/harness/codeverse3d/skills/prompting.py
+++ b/harness/codeverse3d/skills/prompting.py
@@ -1,17 +1,7 @@
-"""How one shared skill library reaches each coding agent — the ONE place that differs.
-
-The library itself is agent-agnostic: plain `agentskills.io` bundles under
-``codeverse3d/skills/<name>/SKILL.md``, routed by ``registry.py`` from typed inputs. Nothing
-in it knows what a backend is. What genuinely differs between backends is only
-**delivery**, and only in one bit: which discovery root does it read?
-
-Read out of the shipped binaries, not assumed: codex and agy read
-``<ws>/.agents/skills/<name>/SKILL.md``; claude-code 2.1 reads ``<ws>/.claude/skills/…``
-and has no ``.agents`` skill root at all. All three have a NATIVE skill loader (they find
-and index the bundles themselves), so none is handed a second index — it would list the
-same skills twice. Adding a backend is ONE row here — not a new module, not a branch in
-three files. (The loaderless path — an explicit index plus a ``read_skill`` tool — served
-the in-process api-agent and went with it: ``agents/registry.KINDS`` accepts only these three.)
+"""How the shared skill library reaches each coding agent: the discovery root each backend reads.
+
+Bundles are plain ``SKILL.md`` files; all three CLIs have a native skill loader, so only the
+mandate is added to the instructions.
"""
from __future__ import annotations
@@ -27,9 +17,7 @@ __all__ = ["AGENTS_SKILL_ROOT", "CLAUDE_SKILL_ROOT", "skill_path"]
AGENTS_SKILL_ROOT = ".agents/skills"
CLAUDE_SKILL_ROOT = ".claude/skills"
-#: The whole per-backend policy: the discovery root each backend reads (bundles are written
-#: to every root anyway, so this is only the path we NAME to it). One row per backend; a
-#: kind not listed here (a test's fake agent) reads the shared ``.agents`` root.
+#: per-backend discovery root; an unlisted kind reads the shared ``.agents`` root.
_BACKEND_ROOTS: dict[str, str] = {
"claude-code": CLAUDE_SKILL_ROOT,
"codex": AGENTS_SKILL_ROOT,
@@ -38,8 +26,7 @@ _BACKEND_ROOTS: dict[str, str] = {
# ===================================================================== prompting
-#: what every backend is told. Its own index lists every skill it can see, including any
-#: the user installed globally, so "the ones that match" is the right instruction there.
+#: what every backend is told.
MANDATE = ("Skills for this task are installed in this workspace. Any whose description matches "
"your task are MANDATORY — activate and read them before writing code.")
@@ -53,25 +40,19 @@ def skill_path(name: str, *, agent_kind: str = "") -> str:
def index_block(skills: Sequence[Skill | Selection]) -> str:
- """The text appended to the AGENTS.md body ('' when nothing is routed): the mandate
- only — every backend's native loader already indexes the bundles."""
+ """The mandate appended to the AGENTS.md body ('' when nothing is routed)."""
return f"{_HEADING}\n\n{MANDATE}\n" if skills else ""
def index_tokens(skills: Sequence[Skill | Selection]) -> int:
- """What the index costs in message 0 — recorded per round so §5.4 is auditable."""
+ """Token cost of the index in message 0."""
return text_tokens(index_block(skills))
def repair_pointers(selections: Sequence[Selection], *, agent_kind: str = "",
answering: Sequence[str] = ()) -> str:
- """Name the skills that answer THIS failure, beside it (repair rounds only).
-
- Two ways in: a selection that a previous round's gate already routed, and a name in
- ``answering`` — the skills whose routes cover a finding the current build/lint just
- produced, which is discovered after the round attached its set. Everything else is
- left out: the standing sheets are already in the workspace, and repeating them in the
- volatile tail would pay twice for the same text and say nothing new.
+ """Name the skills that answer THIS failure (repair rounds only): those a previous gate
+ routed, plus the names in ``answering``.
"""
want = set(answering)
fired = [s for s in selections if s.gate_fired or s.name in want]
@@ -84,11 +65,7 @@ def repair_pointers(selections: Sequence[Selection], *, agent_kind: str = "",
def inline_body(selections: Sequence[Selection], *, max_tokens: int = 2500) -> tuple[str, str]:
- """``(name, text)`` for the single-shot arm: the one highest-priority body, inlined.
-
- A single-shot call cannot open a file, so a pointer would be a cost with no benefit
- and would quietly make the arm incomparable with the agent arms. One body, capped.
- """
+ """``(name, text)`` for the single-shot arm: the highest-priority body that fits, inlined."""
for s in selections:
if s.skill.body_tokens <= max_tokens:
return s.name, f"{_HEADING} — {s.name}\n\n{s.skill.description}\n\n{s.skill.body.strip()}\n"
diff --git a/harness/codeverse3d/skills/registry.py b/harness/codeverse3d/skills/registry.py
index ba0f7a2e..acbd03ea 100644
--- a/harness/codeverse3d/skills/registry.py
+++ b/harness/codeverse3d/skills/registry.py
@@ -1,20 +1,9 @@
-"""The routing table (design §5.2) and the one place a gate finding becomes a routing kind.
-
-Two things live here and nowhere else:
-
-**finding_kind()** — a finding's kind is ``"<gate>/<data.kind>"``, the kind the gate itself
-wrote (``connectivity/penetration``, ``scene_frames/no_motion``); the ``lint:<language>``
-gates are one ``lint`` family, typed by ``contracts.artifacts.LintKind``. Every gate now writes
-a kind; a finding recorded before its gate did (a lint or motion_direction round before
-2026-09-24) is ``"<gate>/untyped"``, which only a family row (``joint_sweep/*``) answers. No
-message text is read: the regex this replaced left seven scene_frames kinds unrouted and R19
-unreachable (audit 2026-09-24, N52), and every gate reword could unroute a skill. INFO lines
-("all 7 parts are connected") are census, not defects, and have no kind.
-
-**ROUTES** — typed rows, evaluated by ``select()`` below. A row fires when ALL of its stated
-conditions hold; ``priority`` decides who survives the cap, and every gate-fired row sits
-at >= 90 so a repair round spends its budget on what actually broke. Routing a kind is a
-claim that a skill helps, and that claim needs evidence; most kinds have no row.
+"""The skill routing table and the one place a gate finding becomes a routing kind.
+
+``finding_kind()`` maps a finding to ``"<gate>/<data.kind>"`` (all ``lint:<language>`` gates are one
+``lint`` family; an untyped finding is ``"<gate>/untyped"``); no message text is read and INFO
+lines have no kind. ``ROUTES`` are typed rows evaluated by ``select()``: a row fires when all its
+conditions hold, ``priority`` decides who survives the cap, and gate-fired rows sit at >= 90.
"""
from __future__ import annotations
@@ -28,7 +17,6 @@ from codeverse3d.contracts.artifacts import LintKind
from codeverse3d.skills.model import EVIDENCE_INHERITED, Selection, Skill
# --------------------------------------------------------------------------- finding kinds
-#: the kind of a finding whose gate writes no ``data.kind``
UNTYPED = "untyped"
#: the kinds a route or a bundle target names on its own — the gates' own words
CONNECTIVITY_PENETRATION = "connectivity/penetration"
@@ -51,17 +39,14 @@ SHADER_PREFLIGHT = "shader_preflight/*"
MOTION_WRONG_DIRECTION = "motion_direction/wrong_direction"
LINT = "lint/*"
LINT_PART_NOT_IMPORTED = f"lint/{LintKind.PART_NOT_IMPORTED.value}"
-#: the scene_placement gate's seating kinds (spatial/scene_placement.py; ``free_exempt`` and
-#: ``cantilevered`` are 2026-10-14's, D105). Its PLAN kinds (no_fog, world_edge, scale, zone_empty, …)
-#: are deliberately not here: they are env / composition findings, not seating.
+#: the scene_placement seating kinds; its PLAN kinds (no_fog, world_edge, ...) are not seating
SCENE_PLACEMENT_FLOATING = "scene_placement/floating"
SCENE_PLACEMENT_SUNKEN = "scene_placement/sunken"
SCENE_PLACEMENT_UNSUPPORTED = "scene_placement/unsupported"
SCENE_PLACEMENT_INTERPENETRATION = "scene_placement/interpenetration"
SCENE_PLACEMENT_FREE_EXEMPT = "scene_placement/free_exempt"
SCENE_PLACEMENT_CANTILEVERED = "scene_placement/cantilevered"
-#: the six seating kinds a placement row answers (a family pattern ``"scene_placement/*"`` would
-#: also attach the placement sheet to a no_fog or stamped_ring finding, which it cannot fix)
+#: the seating kinds a placement row answers (a ``scene_placement/*`` pattern would over-attach)
SCENE_PLACEMENT_SEATING: tuple[str, ...] = (
SCENE_PLACEMENT_FLOATING, SCENE_PLACEMENT_SUNKEN, SCENE_PLACEMENT_UNSUPPORTED,
SCENE_PLACEMENT_INTERPENETRATION, SCENE_PLACEMENT_FREE_EXEMPT, SCENE_PLACEMENT_CANTILEVERED,
@@ -69,7 +54,6 @@ SCENE_PLACEMENT_SEATING: tuple[str, ...] = (
def gate_family(gate: str) -> str:
- """A gate's name as its findings' kinds carry it: every ``lint:<language>`` gate folds to ``lint``."""
gate = gate.strip().lower()
return "lint" if gate.startswith("lint") else gate
@@ -88,12 +72,10 @@ def finding_kind(finding: Any) -> str | None:
def kind_matches(kind: str, patterns: tuple[str, ...]) -> bool:
- """``kind`` is one of ``patterns``: an exact kind, or a family ending in ``*`` (``gl_frames/*``)."""
return any(kind.startswith(p[:-1]) if p.endswith("*") else kind == p for p in patterns)
def finding_kinds(findings: object) -> list[str]:
- """Distinct kinds of an iterable of ``GateFinding`` (or of ``GateReport``s), in order."""
out: list[str] = []
for f in _iter_findings(findings):
k = finding_kind(f)
@@ -116,17 +98,15 @@ OBJECT_TRACKS = ("static_object", "articulated_object")
BLENDER_LANGS = ("blender", "urdf_blender")
THREEJS_LANGS = ("scene_threejs", "threejs")
BPY_SCENE_LANGS = ("scene_blender",)
-#: the scene track's session kinds (tracks/scene.py: env, zone, refine, rebuild; asset is quiet)
+#: the scene track's session kinds that attach skills
BPY_SCENE_KINDS = ("env", "zone", "refine", "rebuild")
BUILD_KINDS = ("baseline", "part", "refine", "rebuild", "repair")
-#: kinds that attach nothing on their own (design §5.2 law 4): short, narrow sessions the
-#: corpus attaches no defect class to. A gate-fired row still reaches them.
+#: kinds that attach nothing on their own; a gate-fired row still reaches them
QUIET_KINDS = ("asset", "asset_fix", "reference")
@dataclass(frozen=True)
class Route:
- """One row of the table. Empty tuple == "any"; ``findings`` == "a gate fired"."""
rule: str
skill: str
@@ -144,7 +124,6 @@ class Route:
return bool(self.findings)
def matches_finding(self, kinds: list[str]) -> str | None:
- """The first routed finding kind this row answers, or None."""
return next((k for pat in self.findings for k in kinds if kind_matches(k, (pat,))), None)
@@ -154,17 +133,14 @@ ROUTES: tuple[Route, ...] = (
Route("R2", "c3d-part-contact", 95, kinds=("repair", "refine", "rebuild"),
findings=("connectivity/*", "joint_sweep/*"),
why="the previous round's connectivity/joint gate fired"),
- # R3 and R4 are object tracks only: the sheet's proof loop is measure / check_contract /
- # isolate, and a scene session has none of those tools (both reached scene sessions until 2026-09-22)
+ # R3 and R4 are object tracks only: a scene session has no measure / check_contract / isolate tools
Route("R3", "c3d-bbox-contract", 65, tracks=OBJECT_TRACKS,
kinds=("baseline", "part", "refine", "rebuild"),
why="this session owns dimensions, and the plan's numbers are the contract"),
Route("R4", "c3d-bbox-contract", 95, tracks=OBJECT_TRACKS, kinds=("repair", "refine", "rebuild"),
findings=("contract/*",),
why="the previous round's contract gate fired"),
- # R5 was c3d-form-manifest, retired 2026-08-25: read 2/19 (11%, CI [3%,31%]) before and
- # after its description was revised. See docs/SKILLS_LEDGER.md (the bundle's text is in git history). The id is
- # not reused — a route id is how a ledger row and a run record refer to a routing decision.
+ # R5 is retired; a route id is how a ledger row and a run record name a routing decision, so ids are never reused
Route("R6", "c3d-repeats-and-mirrors", 55, tracks=OBJECT_TRACKS,
kinds=("baseline", "part", "refine", "rebuild"),
requires_any=("has_instances", "has_symmetry"),
@@ -217,15 +193,11 @@ ROUTES: tuple[Route, ...] = (
Route("R23", "c3d-opengl-pipeline", 80, tracks=("graphics",), languages=("opengl_python",),
kinds=("baseline", "refine", "repair", "rebuild"),
why="pipeline setup and pass structure: originality 0.330 is the lowest criterion anywhere"),
- # R24 is one row per language: the design writes it as a single line, but a Route names
- # exactly one skill so telemetry can say which one the finding routed.
+ # one row per language: a Route names exactly one skill so telemetry can say which one a finding routed
Route("R24-glsl", "c3d-glsl-craft", 90, tracks=("graphics",), languages=("glsl_shader",),
findings=(GL_FRAMES,), why="the frame gate saw no motion or no detail"),
Route("R24-opengl", "c3d-opengl-pipeline", 90, tracks=("graphics",), languages=("opengl_python",),
findings=(GL_FRAMES,), why="the frame gate saw no motion or no detail"),
- # R25-R28 (2026-09-01): the graphics-recipe port from the scene_multifile_graphics
- # reference (eval/docs/EVAL.md sceneloop entry). Atmosphere and materials ride every
- # env/baseline build; water and night only when the plan's own words ask for them.
Route("R25", "c3d-scene-atmosphere", 70, tracks=("scene",), languages=("scene_threejs",),
kinds=("baseline", "env", "refine"),
why="the sky bake is the light source every PBR surface reflects; 4/9 reference scenes shipped it inverted"),
@@ -238,11 +210,6 @@ ROUTES: tuple[Route, ...] = (
Route("R28", "c3d-scene-materials", 65, tracks=("scene",), languages=("scene_threejs",),
kinds=("baseline", "zone", "refine"),
why="flat albedo and identical twins are the reference audit's most-cited surface defects"),
- # R29-R34 (2026-10-14, D105): the scene_blender bundles. Placement rides every build session
- # because every placed thing is a measured row and the 2026-10-14 thresholds make a hand's
- # breadth of hover an ERROR; lighting and materials ride the sessions that author light and
- # surfaces. R34 is the three.js half of "a gate-fired route on scene_placement for both
- # languages": composition's first rule is the one height function everything samples.
Route("R29", "c3d-bpy-scene-placement", 80, tracks=("scene",), languages=BPY_SCENE_LANGS, kinds=BPY_SCENE_KINDS,
why="every placed thing is a measured placement row, and the strict 2026-10-14 thresholds make a "
"hand's breadth of hover an ERROR with a score ceiling"),
@@ -265,7 +232,7 @@ ROUTES: tuple[Route, ...] = (
"samples is the bundle's first rule"),
)
-#: every skill the table can attach — the Author phase's contract for which bundles must exist
+#: every skill the table can attach
ROUTED_SKILLS: tuple[str, ...] = tuple(dict.fromkeys(r.skill for r in ROUTES))
@@ -283,10 +250,7 @@ _NIGHT_WORDS = ("night", "neon", "dusk", "evening", "moonlit", "moonlight", "lam
def plan_signals(plan: Any | None) -> dict[str, Any]:
- """Route-relevant facts about a plan. Tolerant by design: a missing/partial plan
- yields all-false signals rather than raising, because a planner failure must not
- also take out the round's skills. Kept here, not on the Plan contracts: adding a
- routing signal must not migrate every stored plan."""
+ """Route-relevant facts about a plan; a missing or partial plan yields all-false signals."""
parts = list(getattr(plan, "parts", None) or [])
joints = list(getattr(plan, "joints", None) or [])
effects = list(getattr(plan, "effects", None) or [])
@@ -307,8 +271,6 @@ def plan_signals(plan: Any | None) -> dict[str, Any]:
"has_joints": bool(joints),
"joint_types": sorted({str(getattr(j, "type", "")) for j in joints if getattr(j, "type", "")}),
"has_custom_shader": bool(effects) or any(w in text for w in _SHADER_WORDS),
- # scene-content signals (2026-09-01, the graphics-recipe port): matched against the
- # plan's own words so the water/night recipes ride only when the brief wants them
"wants_water": any(w in text for w in _WATER_WORDS),
"wants_night": any(w in text for w in _NIGHT_WORDS),
}
@@ -326,16 +288,13 @@ def _row_applies(row: Route, track: str, language: str, kind: str, signals: dict
return not (row.requires_any and not any(signals.get(k) for k in row.requires_any))
-#: the floor of a gate-fired row (design §5.2 law 2). ``model.Selection.gate_fired`` reads a priority
-#: >= 90 as "a gate routed this", so a variant boost may neither lift a standing row up to it nor
-#: drop a fired row under it — the table's meaning must survive the overlay
+#: the floor of a gate-fired row: ``Selection.gate_fired`` reads priority >= 90 as "a gate routed this",
+#: so a variant boost may not move a row across it
GATE_FIRED_PRIORITY = 90
def effective_priority(row: Route, boosts: Mapping[str, int]) -> int:
- """``row.priority`` plus the variant's boost for its skill, clamped to the table's law: a standing
- row stays below :data:`GATE_FIRED_PRIORITY` (a warning says it was clamped — the boost is too
- big, not wrong), a gate-fired row never drops below it, nothing goes under 0."""
+ """``row.priority`` plus the variant's boost, clamped so standing rows stay below and gate-fired rows at or above the floor."""
delta = int(boosts.get(row.skill, 0))
if not delta:
return row.priority
@@ -366,13 +325,8 @@ def select(
) -> list[Selection]:
"""The routed bundles for one session, ranked, capped, each with its reason.
- ``findings`` may be ``GateFinding``s, ``GateReport``s, or already-classified kind
- strings — the caller usually has the previous ``RoundRecord.gates`` on hand.
-
- ``routes`` / ``boosts`` / ``disabled`` are a variant's reshaping of the table
- (``skills.variants_table``): the rows to evaluate, in order (a variant's extra rows come after
- the base ones, so ties keep the base order), a priority delta per skill
- (:func:`effective_priority` clamps it) and the rule ids to skip.
+ ``findings`` may be ``GateFinding``s, ``GateReport``s or kind strings; ``routes`` / ``boosts`` /
+ ``disabled`` are a variant's reshaping of the table.
"""
from codeverse3d.skills import all_skills
@@ -392,14 +346,12 @@ def select(
if row.gate_fired and hit is None:
continue
if not row.gate_fired and kind in QUIET_KINDS:
- # design §5.2 law 4: short, narrow sessions attach nothing on their own
continue
if not _row_applies(row, track, language, kind, sig):
continue
skill = lib.get(row.skill)
if skill is None:
- # The Author phase ships bodies in its own commits; a table row without a
- # bundle must not crash a run — it is a missing skill, not a broken harness.
+ # a table row without a bundle must not crash a run
log.debug("route %s names skill %r, which is not in the library", row.rule, row.skill)
continue
if skill.evidence == EVIDENCE_INHERITED and not allow_unverified:
@@ -413,13 +365,11 @@ def select(
if prev is None:
best[row.skill] = Selection(skill=skill, priority=priority, rules=(row.rule,), reason=reason)
elif priority > prev.priority:
- # a gate-fired row overrides the standing one, and says so in the reason
best[row.skill] = Selection(skill=skill, priority=priority, rules=(*prev.rules, row.rule), reason=reason)
else:
best[row.skill] = prev.model_copy(update={"rules": (*prev.rules, row.rule)})
- # priority first (law 2: gate-fired rows outrank standing ones), then table order —
- # a stable, testable ranking, so the cap always cuts the same tail.
+ # priority first (gate-fired outranks standing), then table order: the cap cuts a stable tail
ranked = sorted(best.values(), key=lambda s: (-s.priority, first_seen[s.name]))
return ranked[:max(0, max_skills)]
diff --git a/harness/codeverse3d/skills/telemetry.py b/harness/codeverse3d/skills/telemetry.py
index 895f72c4..c22323fb 100644
--- a/harness/codeverse3d/skills/telemetry.py
+++ b/harness/codeverse3d/skills/telemetry.py
@@ -1,45 +1,10 @@
-"""Did anyone actually READ it? Measured from the CLI's own record where there is one.
-
-The fact this whole system has to answer: the former ``read_cookbook`` tool was called by
-**0 of 16** zone sessions and 1 of 4 env sessions on ``scenes_v1_flash``, although the
-prompt of the day named five chapters by title. A tool that exists is not a tool that gets used, and shipping a
-nicer file format without measuring reads would repeat that at a new price.
-
-**Ground truth first (2026-09-22).** Every CLI backend now folds its session's tool
-calls into ``trajectories/<label>/transcript.jsonl`` (``agents/cli_common.record_tool_calls``:
-claude-code's ``Skill``/``Read`` from stream-json, codex's shell commands from
-``exec --json``, agy's ``read_file`` — ``view_file`` before 1.4 — from its conversation database). A
-bundle is *surfaced* when a call activated it or named its ``SKILL.md``, *deep* when a
-call named a file under its ``references/``, and the control is read when a call touched
-it — ``SkillsUsage.evidence == "transcript"``. A bundle the trace calls surfaced but not
-deep is still deep when a file under its ``references/`` was opened and the control's
-``references/`` were not (signal 3: nothing scanned references/ wholesale) — claude-code
-2.1.317 read them with ``cd …/<name> && … cat "$f"`` (live, 2026-11-03), a call that names
-no path to match. Only when a session after the attach left
-no trace does the probe fall back to the atime signals below, which the control proved
-blind in 27 of 33 sessions (docs/SKILLS.md §4):
-
-1. **atime probe** — the root filesystem is ext4 with ``relatime``, where the first read
- after a write bumps ``atime``. ``materialize_skills`` stamps ``atime == mtime`` on
- every file it writes, so ``atime > mtime`` afterwards means the file was opened. No
- parsing, and it works identically for all five backends.
-2. **references/ depth probe** — signal 1 has an obvious false positive: a CLI's startup
- scan opens SKILL.md to read the frontmatter. The design assumed nothing scans
- ``references/*.md``, so an atime bump there meant the agent read the body and followed
- it. **Measured 2026-08-25, that assumption is false**, for two independent reasons:
- ``Workspace.changed_files`` runs ``git add -A -N`` + ``git diff`` after every session
- and git reads every untracked file to diff it; and all four CLIs open ``references/``
- while activating a skill, even one whose description does not match the task. So the
- depth signal is kept — it is still the difference between "listed" and "opened" — but
- it is no longer trusted on its own, which is what signal 3 is for. (A bundle that
- ships no ``references/`` cannot be probed for depth and says so via
- ``deep_measurable`` instead of quietly scoring 0.)
-3. **the control bundle** — ``materialize.write_control`` puts one never-routed,
- never-indexed bundle beside the real ones. Nothing should ever open it. When it comes
- back opened, this session's atime evidence proves nothing, ``control_read`` is set and
- ``deep_read_rate`` returns ``None`` rather than a confident 100%. It costs two small
- files and turns a metric that could silently read 100% forever into one that says when
- it cannot see.
+"""Did the agent READ the routed skills? Measured from the CLI's own tool trace where there is one.
+
+A bundle is *surfaced* when a call activated it or named its ``SKILL.md``, *deep* when a call
+named a file under its ``references/``. When a session left no trace the probe falls back to
+atime (``materialize_skills`` stamps ``atime == mtime``; a later atime means opened). The
+never-routed control bundle falsifies that fallback: if it reads as opened, ``deep_read_rate``
+is ``None`` instead of a confident 100%.
"""
from __future__ import annotations
@@ -59,7 +24,7 @@ from codeverse3d.skills.prompting import AGENTS_SKILL_ROOT, CLAUDE_SKILL_ROOT
log = logging.getLogger(__name__)
TELEMETRY_DIR = "telemetry"
-SKILLS_FILE = "skills.jsonl" # the per-session roll-up, written after it
+SKILLS_FILE = "skills.jsonl"
#: seconds of slack: some filesystems round atime/mtime differently on the two writes
ATIME_EPSILON_S = 1.0
@@ -73,9 +38,7 @@ def _opened(path: Path) -> bool:
def probe_reads(ws_root: Path, materialized: SkillsMaterialized) -> SkillsUsage:
- """What the sessions since the attach did with the bundles we attached, per skill.
-
- From their tool traces when every one of them left one; from atime otherwise."""
+ """Per skill, what the sessions since the attach did with the bundles (trace first, atime fallback)."""
from codeverse3d.skills.materialize import CONTROL_NAME
root = Path(ws_root)
@@ -90,18 +53,14 @@ def probe_reads(ws_root: Path, materialized: SkillsMaterialized) -> SkillsUsage:
refs = [f for b in bundles for f in sorted((b / "references").glob("*.md"))]
if trace is not None:
surfaced, deep = trace[name]
- # a shell read names no path the trace can match (claude-code 2.1.317, live
- # 2026-11-03: `cd …/<name> && for f in $(find references -type f); do cat "$f"; done`)
- # but bumps the reference's atime — proof exactly while the control's references
- # stay untouched, i.e. nothing scanned references/ wholesale (module doc, signal 3)
+ # a shell read names no path the trace can match but bumps the reference's atime;
+ # counts as proof only while the control's references stay untouched
if not deep and not control_refs_read:
deep = any(_opened(f) for f in refs)
else:
surfaced = any(_opened(b / "SKILL.md") for b in bundles)
deep = any(_opened(f) for f in refs)
# reading a reference means the bundle was reached, whatever SKILL.md's atime says
- # (relatime can miss the second access within 24 h, and some CLIs stream the body
- # out of their own index rather than re-opening the file)
surfaced = surfaced or deep
reads.append(SkillRead(
name=name, surfaced=surfaced, deep=deep, deep_measurable=bool(refs),
@@ -117,13 +76,11 @@ def probe_reads(ws_root: Path, materialized: SkillsMaterialized) -> SkillsUsage:
def trace_reads(ws_root: Path, names: Sequence[str], *, since: float = 0.0) -> dict[str, tuple[bool, bool]] | None:
- """``{name: (surfaced, deep)}`` from the tool calls the CLI sessions logged after ``since``.
+ """``{name: (surfaced, deep)}`` from tool calls logged after ``since``.
- ``None`` — "no ground truth, use the fallback" — when no session ran after the attach,
- or when one of them left no ``tool_trace`` marker (a CLI that died before its backend
- could read its record, or a backend that cannot): that session's reads would be
- MISSING, not absent, and a partial trace would under-count exactly like a blind probe
- over-counts. A session is a transcript with an ``invoke`` row at or after ``since``."""
+ ``None`` (use the fallback) when no session ran after the attach or one left no
+ ``tool_trace`` marker: a partial trace would under-count.
+ """
from codeverse3d.agents.cli_common import TOOL_CALL_ROW, TOOL_TRACE_ROW
from codeverse3d.workspace import Workspace
@@ -155,10 +112,8 @@ def _t(row: dict[str, Any]) -> float:
def _called(name: str, calls: Sequence[dict[str, Any]]) -> tuple[bool, bool]:
- """(surfaced, deep) for one bundle. Matched on ``<name>/SKILL.md`` and
- ``<name>/references/<file>`` anywhere in a call's arguments, so a relative path, an
- absolute one, codex's ``r1/<name>/SKILL.md`` root alias expanded or not, and a
- ``cat``/``sed`` shell line all count; a listing of ``references`` does not."""
+ """(surfaced, deep) for one bundle, matched on ``<name>/SKILL.md`` and ``<name>/references/<file>``
+ anywhere in a call's arguments; a listing of ``references`` does not count."""
body = re.compile(rf"(?<![\w-]){re.escape(name)}/SKILL\.md")
ref = re.compile(rf"(?<![\w-]){re.escape(name)}/references/[^\s\"'`]+")
surfaced = deep = False
@@ -172,10 +127,8 @@ def _called(name: str, calls: Sequence[dict[str, Any]]) -> tuple[bool, bool]:
def _control_state(root: Path) -> tuple[bool, bool, bool]:
- """(a control was materialised, something opened it, something opened its ``references/``)
- — the probe's own falsification. The third is the stricter signal: a CLI's discovery scan
- opens every ``SKILL.md`` (claude-code does, 2.1.317), nothing legitimate opens an unrouted
- bundle's references."""
+ """(a control was materialised, something opened it, something opened its ``references/``);
+ the third is the stricter signal, since a CLI's discovery scan opens every ``SKILL.md``."""
from codeverse3d.skills.materialize import CONTROL_NAME
present = opened = refs_opened = False
@@ -191,7 +144,7 @@ def _control_state(root: Path) -> tuple[bool, bool, bool]:
def append_usage(ws_root: Path, usage: SkillsUsage, **context: Any) -> Path | None:
- """One JSON line per (run, round, session) — the file ``3dcode skills report`` reads."""
+ """One JSON line per (run, round, session)."""
try:
d = Path(ws_root) / TELEMETRY_DIR
d.mkdir(parents=True, exist_ok=True)
diff --git a/harness/codeverse3d/spatial/_render_common.py b/harness/codeverse3d/spatial/_render_common.py
index b413e13a..55a1c47e 100644
--- a/harness/codeverse3d/spatial/_render_common.py
+++ b/harness/codeverse3d/spatial/_render_common.py
@@ -1,15 +1,4 @@
-"""Shared core of the three render flavours (object GLB, scene, GL frames).
-
-``render.py`` (objects, node + headless Chrome), ``render_scene.py`` (scene
-workspaces, same browser through the scene host) and the graphics build
-(``languages/_gl_common`` via ``gl_render``) all repeat the same four chores:
-resolve the output directory, turn ``ViewPreset``s into the driver's camera
-JSON, and build the labelled contact sheet with the settings' grid. They live here once so the flavours differ only in
-what they actually drive.
-
-Nothing in here talks to node — see ``spatial.node.run_node`` (objects) and
-``spatial.render_scene.run_scene_script`` (scenes) for that.
-"""
+"""Chores shared by the object, scene and GL render flavours: output dir, view payload, contact sheet."""
from __future__ import annotations
@@ -23,8 +12,7 @@ from codeverse3d.spatial.sheet import contact_sheet
def out_directory(out_dir: Path | str, *, clean: Sequence[str] = ()) -> Path:
- """Resolve + create ``out_dir``; ``clean`` names side-cars of a previous run
- that must never be read as if they belonged to this one."""
+ """Resolve + create ``out_dir``; delete the ``clean`` side-car files left by a previous run."""
d = Path(out_dir).resolve()
d.mkdir(parents=True, exist_ok=True)
for name in clean:
@@ -33,14 +21,12 @@ def out_directory(out_dir: Path | str, *, clean: Sequence[str] = ()) -> Path:
def view_specs(views: Sequence[ViewPreset]) -> list[dict[str, Any]]:
- """``ViewPreset``s → the ``[{name, azimuth, elevation}]`` payload every
- renderer driver takes (render_glb ``--views``, render_scene ``--orbit-views``)."""
+ """``ViewPreset``s → the ``[{name, azimuth, elevation}]`` payload the render drivers take."""
return [{"name": v.name, "azimuth": float(v.azimuth_deg), "elevation": float(v.elevation_deg)} for v in views]
def build_sheet(images: Sequence[tuple[str, str | Path]], out: Path | str) -> str | None:
- """Labelled contact sheet at the configured grid (``settings.render.sheet_cols``
- / ``sheet_tile``); ``None`` when there is nothing to show."""
+ """Labelled contact sheet at the configured grid; ``None`` when there are no images."""
if not images:
return None
settings = get_settings()
diff --git a/harness/codeverse3d/spatial/complexity.py b/harness/codeverse3d/spatial/complexity.py
index f1d62e1d..fbf64b62 100644
--- a/harness/codeverse3d/spatial/complexity.py
+++ b/harness/codeverse3d/spatial/complexity.py
@@ -1,43 +1,4 @@
-"""Objective complexity of a built artifact — no VLM, no renders, no model call.
-
-``complexity_of_parts`` turns the world-space part meshes of the canonical GLB
-into a :class:`ComplexityVector`: eight measured axes plus one 0–1 ``index``
-computed from documented weights. It answers "how much *thing* is actually
-here?" so that a judge score can be read against the difficulty of what was
-built (eval/docs/COMPLEXITY.md), and so a battery can state an expected complexity
-band instead of a vibe.
-
-The eight axes
-
-* ``part_count`` — parts with geometry in the canonical GLB.
-* ``assembly_depth`` — depth of the node graph below the effective top level
- (1 = flat list of parts, 3 = sub-assemblies of sub-assemblies).
-* ``tri_count`` — triangles in the whole artifact.
-* ``materials`` — distinct materials bound to its geometry.
-* ``silhouette`` — mean isoperimetric quotient ``P² / 4πA`` of the
- silhouette in the three axis-aligned projections (1.0 = a disc, ~1.3 = a
- square, 10+ = a chair, 60 = a birdcage). Computed from geometry (surface
- samples rasterised at ``SILHOUETTE_RES``), not from a render, so it needs no
- GPU and is identical on every machine.
-* ``feature_density`` — small *and* sharp edges per unit surface area, made
- dimensionless with the bbox diagonal: ``n · diag² / area``. An edge counts
- when its dihedral angle exceeds ``_SHARP_DEG`` and it is shorter than
- ``_SMALL_EDGE_FRAC`` of the diagonal — i.e. bevels, chamfers, flutes,
- mouldings, hardware, fine tessellation of curved surfaces. A box stack
- scores ~100, a machined instrument ~10 000.
-* ``symmetry_groups`` — families of geometrically repeated parts (same tri
- count and same extents to 1 mm): 4 identical legs are one group. Organised
- repetition is what separates a 20-part machine from 20 random blobs.
-* ``hollowness`` — mean per-part concavity ``1 − volume / hull_volume``
- over watertight parts: 0 for solid boxes and cylinders, high for tubes,
- shells, C-frames and bent bars.
-
-``index`` is ``Σ wᵢ · normᵢ(axisᵢ)`` with the weights in
-``COMPLEXITY_WEIGHTS`` and the saturating normalisers in ``_NORMALISERS`` (both
-public data; eval/docs/COMPLEXITY.md records why each number is what it is). It is
-a *difficulty* measure, never a *quality* measure: a rich broken model and a
-rich good model score the same index.
-"""
+"""Objective complexity of a built artifact — no VLM, no renders, no model call."""
from __future__ import annotations
@@ -59,20 +20,15 @@ __all__ = [
"band_of",
]
-#: Bump when an axis, a weight or a normaliser changes — stored on every vector
-#: so an old record is never silently compared against a new scale.
COMPLEXITY_VERSION = 1
SILHOUETTE_RES = 128
-#: samples per grid cell: at 12 the chance a covered pixel is missed is ~6e-6, so the
-#: mask has no sampling pinholes and the perimeter is the shape's, not the noise's
_SAMPLES_PER_CELL = 12
-_SAMPLE_SEED = 0 # law 10: the same GLB must always yield the same vector
+_SAMPLE_SEED = 0
_SHARP_DEG = 20.0
_SMALL_EDGE_FRAC = 0.02
_DUP_TOL_M = 1e-3
-#: axis -> weight of its normalised value in ``index`` (sums to 1.0).
COMPLEXITY_WEIGHTS: dict[str, float] = {
"part_count": 0.20,
"assembly_depth": 0.07,
@@ -84,9 +40,6 @@ COMPLEXITY_WEIGHTS: dict[str, float] = {
"hollowness": 0.09,
}
-#: axis -> (kind, lo, hi). ``log`` maps log(x) linearly from log(lo)..log(hi)
-#: onto 0..1; ``lin`` maps x itself. Everything is clipped to [0, 1], so the
-#: pair is "the value that scores 0" and "the value that saturates at 1".
_NORMALISERS: dict[str, tuple[str, float, float]] = {
"part_count": ("log", 1.0, 30.0),
"assembly_depth": ("lin", 1.0, 4.0),
@@ -98,7 +51,6 @@ _NORMALISERS: dict[str, tuple[str, float, float]] = {
"hollowness": ("lin", 0.0, 1.0),
}
-#: index -> label. The complexity battery states an expected band per prompt.
_BANDS: tuple[tuple[float, str], ...] = (
(0.25, "trivial"),
(0.40, "simple"),
@@ -159,8 +111,8 @@ def _raster(pts2: np.ndarray, res: int) -> np.ndarray:
def _close(grid: np.ndarray) -> np.ndarray:
- """3×3 binary closing (dilate then erode) — seals sampling pinholes without
- bridging real gaps wider than one pixel. Pure numpy: scipy is an extra."""
+ """3×3 binary closing (dilate then erode) — seals sampling pinholes without bridging real
+ gaps wider than one pixel."""
out = grid
for op in (np.logical_or, np.logical_and):
acc = out.copy()
@@ -172,12 +124,7 @@ def _close(grid: np.ndarray) -> np.ndarray:
def _mask_perimeter(grid: np.ndarray) -> float:
- """4-connected crack-boundary length of the mask, in pixels.
-
- Uncorrected on purpose: a correction that is right for curves is wrong for
- axis-aligned rectangles, and this axis is comparative. Reference points on
- this scale: a solid box ≈ 1.3, a sphere ≈ 1.6, a chair ≈ 10, a birdcage ≈ 60.
- """
+ """4-connected crack-boundary length of the mask, in pixels."""
p = int(np.count_nonzero(grid[:-1, :] ^ grid[1:, :]))
p += int(np.count_nonzero(grid[:, :-1] ^ grid[:, 1:]))
p += int(np.count_nonzero(grid[0, :]) + np.count_nonzero(grid[-1, :]))
@@ -186,14 +133,8 @@ def _mask_perimeter(grid: np.ndarray) -> float:
def _silhouette_stats(mesh: trimesh.Trimesh) -> tuple[float, float, float]:
- """``(isoperimetric quotient, fill fraction, mirror symmetry)`` averaged over
- the three axis-aligned projections.
-
- Each projection is sampled with faces weighted by their PROJECTED area
- (``|n·view| · area``): sampling the raw surface would spend a third of its
- points on faces that project to a line, and the resulting pinholes would be
- read as perimeter — a solid box measured 89 instead of 1.3 before this.
- """
+ """``(isoperimetric quotient, fill fraction, mirror symmetry)`` averaged over the three axis-
+ aligned projections."""
n = _SAMPLES_PER_CELL * SILHOUETTE_RES * SILHOUETTE_RES
quotients: list[float] = []
fills: list[float] = []
@@ -274,11 +215,7 @@ def _hollowness(parts: dict[str, trimesh.Trimesh | None]) -> tuple[float, float]
def _symmetry_groups(parts: dict[str, trimesh.Trimesh | None]) -> tuple[int, int]:
- """``(families of geometrically identical parts, parts inside such a family)``.
-
- Identity is (triangle count, extents rounded to ``_DUP_TOL_M``) — position
- and orientation are ignored, so mirrored legs and a ring of spokes count.
- """
+ """``(families of geometrically identical parts, parts inside such a family)``."""
buckets: dict[tuple[int, tuple[int, ...]], int] = {}
for mesh in parts.values():
if mesh is None or not len(mesh.faces):
@@ -327,12 +264,7 @@ def complexity_of_parts(
scene: trimesh.Scene | None = None,
materials: int = 0,
) -> ComplexityVector:
- """Complexity of already-loaded world-space part meshes.
-
- ``scene`` (when given) supplies the node graph for ``assembly_depth`` and
- the material count. Never raises: a degenerate artifact yields a
- near-zero vector with ``extra["error"]``.
- """
+ """Complexity of already-loaded world-space part meshes."""
solid = OrderedDict((k, v) for k, v in parts.items() if v is not None and len(v.faces))
if not solid:
return ComplexityVector(extra={"error": "no geometry"})
diff --git a/harness/codeverse3d/spatial/connectivity.py b/harness/codeverse3d/spatial/connectivity.py
index 54302da1..1f27922c 100644
--- a/harness/codeverse3d/spatial/connectivity.py
+++ b/harness/codeverse3d/spatial/connectivity.py
@@ -1,42 +1,4 @@
-"""Connectivity gate: are all parts of the GLB physically attached?
-
-Mechanism
----------
-1. Load one world-space mesh per top-level node (``measure.solid_parts``,
- memoized on the file's stat so repeat gates on one GLB parse it once).
-2. For every part pair whose AABBs come within ``gap_m`` of each other compute
- the exact minimum surface distance (``fcl.distance`` on per-part BVHs that
- are built once and shared across all pairs; sampled closest-point fallback
- when fcl is missing) and the closest points.
-3. Contact graph: edge when distance ≤ ``gap_m``. The *support component* is
- the connected component holding the ground-touching parts (lowest point at
- y ≤ gap) — or the largest component when nothing touches the ground.
-4. Parts outside the support component are **floating** → ERROR with the
- nearest supported part and the exact translation vector that closes the gap.
-5. Overlapping AABB pairs are probed for mutual containment of surface samples
- (:func:`penetration_probe`): the whole surface first, then densely where the
- overlap is, so the tip of a thin member inside another part is measured with
- enough points. A pair is reported when the depth is above
- ``PENETRATION_WARN_M`` and the overlap is either a visible share of the whole
- part (``PENETRATION_MIN_FRACTION``) or dense where it is
- (``PENETRATION_MIN_INSIDE`` / ``PENETRATION_MIN_LOCAL_FRACTION``); ERROR
- above ``PENETRATION_ERROR_M`` when the overlap is also a visible share of the
- part, else WARN (parts are allowed to overlap by a hair for welding, not to
- pass through each other; a deep overlap only the dense pass can see is
- reported in full and left to the judge). The through-ratio — how far
- the entering member reaches into the part it enters — is measured and named in
- the message, never a severity (``THROUGH_FAR_SIDE_RATIO``).
-6. Tiny disconnected islands inside a single part → WARN (stray geometry).
-7. One INFO *contact ledger*: every contact with its gap, every measured overlap
- down to the sub-threshold welds, the ground gap per part and the plan's
- ``attach_to`` edges measured regardless of the AABB prefilter
- (``planned_edges``). INFO never changes ``passed``; the judge payload reads it.
-
-All thresholds are module constants (meters) and keyword-overridable. Pass the
-authoring ``language`` so translation hints are written in the frame the agent
-codes in (Blender/CadQuery/URDF are Z-up; the GLB is Y-up) — a hint in the wrong
-frame moves a part forward instead of down.
-"""
+"""Connectivity gate: are all parts of the GLB physically attached?"""
from __future__ import annotations
@@ -58,53 +20,19 @@ from codeverse3d.spatial.joints_collide import fcl_collision_object, inside_isla
from codeverse3d.spatial.measure import GlbLoadError, fmt_vec, solid_parts
GATE = "connectivity"
-#: one planned join: (child, parent) or (child, (parent copies the child's box touches, …))
PlannedEdge = tuple[str, "str | Sequence[str]"]
-#: parts smaller than this (max extent) are ignored for floating checks (INFO only)
MIN_PART_SIZE_M = 0.01
-#: penetration depth that is reported as WARN / ERROR. These bound the REST pose only,
-#: and with a 600-point surface draw per part: this check asks "do these two surfaces sit
-#: inside each other as built". ``joint_sweep`` asks a different question on posed meshes
-#: — "does moving a joint drive one link through another" — at its own thresholds. They
-#: are not one check with two dials: do not align the numbers (DECISIONS.md D53, with the
-#: corpus measurement behind it in eval/bench/penetration_thresholds.py).
PENETRATION_WARN_M = 0.002
PENETRATION_ERROR_M = 0.010
-#: fraction of one part's samples inside the other before we call it penetration ...
PENETRATION_MIN_FRACTION = 0.02
-#: ... or, when the overlap is a small share of a large part, dense where it is: at
-#: least this many samples inside and this share of the samples in the overlap region.
-#: Measured 2026-08-30 on h2h_telescope: the spreader arm tips 4 mm inside three 24 mm
-#: legs were 4–6 of 600 whole-surface samples (0.7–1.0 %), under the fraction floor,
-#: while a third of the arm's surface at the joint was inside the leg.
PENETRATION_MIN_INSIDE = 4
PENETRATION_MIN_LOCAL_FRACTION = 0.2
-#: through_ratio = 2 · depth / thickness of the part entered: 1 means the entering
-#: member reaches the far side (the rubric's "rail poking out of the far side of a leg").
-#: It is MEASURED AND REPORTED, never a severity of its own: the corpus re-run
-#: (2026-08-30, 217 runs) showed a 0.9 ERROR line firing on 31 pairs in 9 runs that are
-#: designed joinery — a boom seated 5 mm into a mast (0.96), arch stretchers 8 mm into
-#: 8 mm ribs (0.91–0.97) — because the number saturates at the container's mid-plane and
-#: cannot tell "ends inside" from "out the far side". Severity stays on depth alone
-#: (the contract's own 2 mm / 10 mm lines); the judge, who sees the picture, gets the
-#: ratio as a fact in the message and the ledger.
THROUGH_FAR_SIDE_RATIO = 0.9
-#: surface samples per part for containment / fallback distance tests
N_SAMPLES = 600
-#: when fewer than LOCAL_MIN_SAMPLES of the entering part's whole-surface samples lie in
-#: the overlap region, LOCAL_EXTRA_SAMPLES more are drawn on its faces CLIPPED to the region
-#: (a plate's 300 mm face around an 8 mm rod is 0.05 % in-region; rejection sampling it
-#: never reached the rod's axis). The max depth of a finite sample under-estimates the
-#: true reach by ~ radius/√n, which is why 512 and not 64: at 64, a 24 mm rail through a
-#: 10 mm plate read 0.89, one hair under THROUGH_FAR_SIDE_RATIO
LOCAL_MIN_SAMPLES = 128
LOCAL_EXTRA_SAMPLES = 512
-#: the entering part's vertices inside the AABB overlap are tested too: a tip's end cap
-#: is a vertex ring, and vertices find an overlap smaller than 1/N_SAMPLES of the
-#: surface that uniform samples miss (capped so a 200k-vertex part is one ray pass)
LOCAL_MAX_VERTICES = 1500
_REGION_HAIR_M = 0.001
-#: an island is "tiny" when its largest extent is below this fraction of the part's
TINY_ISLAND_FRACTION = 0.05
_RNG_SEED = 7
@@ -125,20 +53,7 @@ class PairDistance:
@dataclass(frozen=True)
class Penetration:
- """The deepest direction of an overlap probe: ``entering``'s surface inside ``container``.
-
- ``fraction_inside`` is the share of N_SAMPLES whole-surface samples inside the other
- part, max over both directions — the pre-2026-08-30 number, kept for comparability
- across the corpus. ``local_fraction`` / ``inside_count`` are measured on the samples
- that lie in the overlap region only, which is what makes a 10 mm tip on a 400 mm arm
- visible; ``thickness_m`` is the container's (:func:`part_thickness`).
-
- ``through_ratio`` is the PAIR's: the smaller of the two directions' 2 · depth /
- thickness. One direction alone reads a 5 mm disc sunk 2.3 mm into a base as "the base
- reaches 82 % of the way through the disc" (h2h_microscope FieldIlluminator) — a designed
- inset. A member that really passes through another scores ≈ 1 both ways: the rod
- reaches the plate's mid-plane AND the plate's faces cut through the rod's whole
- cross-section; an inset or socket is high one way and low the other."""
+ """The deepest direction of an overlap probe."""
entering: str
container: str
@@ -151,8 +66,7 @@ class Penetration:
@property
def own_through_ratio(self) -> float:
- """This direction's 2 · depth / thickness of the container, clipped to [0, 2]: the
- deepest a surface point can sit inside a member is half its thickness."""
+ """This direction's 2 · depth / thickness of the container, clipped to [0, 2]."""
if self.thickness_m <= 0.0:
return 0.0
return float(min(2.0, max(0.0, 2.0 * self.depth_m / self.thickness_m)))
@@ -164,10 +78,7 @@ class Penetration:
class _PartCache:
- """Per-part collision geometry built once and shared across every pair: the
- ``fcl.CollisionObject``, the oriented islands the
- containment test runs on, and the thickness. Before 2026-08-30 the islands were
- re-split per pair — on a 20-part model that is ~190 splits of the same 20 meshes."""
+ """Per-part collision geometry built once and shared across every pair."""
def __init__(self, parts: dict[str, trimesh.Trimesh]):
self._parts = parts
@@ -200,12 +111,7 @@ def pair_distance(
obj_a: Any = None,
obj_b: Any = None,
) -> PairDistance:
- """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 caller
- testing many pairs builds each part's BVH once instead of once per pair.
- """
+ """Exact (fcl) minimum distance between two meshes with closest points."""
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)
@@ -222,9 +128,7 @@ def _sample(mesh: trimesh.Trimesh, n: int, rng: np.random.Generator) -> np.ndarr
def part_thickness(mesh: trimesh.Trimesh) -> float:
- """Thinnest extent of ``mesh``: the smaller of its AABB and its PCA-aligned box —
- a tube's diameter or a plate's thickness whichever way it is turned. The AABB
- alone reads a diagonal 24 mm tripod leg as 311 mm (h2h_telescope TripodLegs_1)."""
+ """Thinnest extent of ``mesh``."""
v = np.asarray(mesh.vertices, dtype=float)
ext = float(np.min(mesh.extents))
if len(v) < 4:
@@ -236,19 +140,7 @@ def part_thickness(mesh: trimesh.Trimesh) -> float:
def _inside_depth(islands: list[trimesh.Trimesh], pts: np.ndarray) -> tuple[np.ndarray, float]:
- """(mask of ``pts`` inside one of ``islands``, max distance of those to the surface).
-
- Containment is the per-island, fixed-direction parity ray test the articulation gate
- already uses (:func:`codeverse3d.spatial.joints_collide.inside_island`), NOT
- ``Trimesh.contains``. ``contains`` needs a watertight mesh, so this used to
- ``continue`` past any open shell — and when NEITHER part was watertight it returned
- (0.0, 0.0), indistinguishable from "no overlap", with no warning that the check had
- not run. A 50 mm post driven into a base passed the gate as soon as both parts were
- modelled as open-bottomed shells, which is the common case for agent-exported meshes
- (open shells, boolean leftovers, mirrored halves, single-sided planes); only the
- mixed closed/open case still fired, which is why the shipped tests stayed green.
- Islands that are not watertight are tested the same way and the answer is
- approximate — the same trade joints_collide.penetration documents and flags."""
+ """(mask of ``pts`` inside one of ``islands``, max distance of those to the surface)."""
inside = np.zeros(len(pts), dtype=bool)
depth = 0.0
if len(pts) == 0:
@@ -281,9 +173,7 @@ def _faces_touching(mesh: trimesh.Trimesh, lo: np.ndarray, hi: np.ndarray) -> tr
def _region_samples(src: trimesh.Trimesh, lo: np.ndarray, hi: np.ndarray, rng: np.random.Generator) -> np.ndarray:
- """LOCAL_EXTRA_SAMPLES surface samples of ``src`` inside the box: its touching faces are
- clipped by the box's six planes and sampled (rejection sampling of the unclipped faces
- is the fallback when the clip fails or leaves nothing)."""
+ """LOCAL_EXTRA_SAMPLES surface samples of ``src`` inside the box."""
sub = _faces_touching(src, lo, hi)
if sub is None:
return np.zeros((0, 3), dtype=float)
@@ -308,10 +198,7 @@ def _probe_direction(
seeds: np.ndarray | None,
rng: np.random.Generator,
) -> Penetration:
- """``src``'s surface inside ``dst``: the whole-surface samples ``pts`` first, then a
- dense pass on the region where the overlap actually is (around the inside samples,
- the inside vertices and ``seeds``, grown by half the thinner part) — or on the whole
- AABB overlap when it is too small to have caught LOCAL_MIN_SAMPLES samples."""
+ """``src``'s surface inside ``dst``."""
islands = cache.islands(name_dst)
lo = np.maximum(src.bounds[0], dst.bounds[0]) - _REGION_HAIR_M
hi = np.minimum(src.bounds[1], dst.bounds[1]) + _REGION_HAIR_M
@@ -323,8 +210,6 @@ def _probe_direction(
verts = verts[np.linspace(0, len(verts) - 1, LOCAL_MAX_VERTICES).astype(int)]
hit_v, depth_v = _inside_depth(islands, verts)
depth = max(depth, depth_v)
- # fcl's closest points of two intersecting Convex objects are (0, 0, 0): keep only seeds
- # that lie in the AABB overlap
seeds = seeds[_in_box(seeds, lo, hi)] if seeds is not None and len(seeds) else np.zeros((0, 3))
found = np.vstack([pts[hit], verts[hit_v], seeds])
in_box = _in_box(pts, lo, hi)
@@ -357,12 +242,8 @@ def penetration_probe(
cache: _PartCache | None = None,
seeds: np.ndarray | None = None,
) -> Penetration:
- """Mutual containment of ``a`` and ``b``, both directions; the deeper one is returned
- with ``fraction_inside`` = the max over both. ``seeds`` are known overlap points (the
- fcl closest points of a pair at distance 0) that localise the dense pass."""
+ """Mutual containment of ``a`` and ``b``, both directions."""
cache = cache if cache is not None else _PartCache({name_a: a, name_b: b})
- # the two whole-surface draws come first, in the pre-2026-08-30 order, so fraction_inside
- # is the same number the corpus was scored with; the dense pass draws from its own stream
rng = np.random.default_rng(_RNG_SEED)
pts_a, pts_b = _sample(a, N_SAMPLES, rng), _sample(b, N_SAMPLES, rng)
ab = _probe_direction(name_a, a, name_b, b, cache, pts_a, seeds, rng)
@@ -401,20 +282,11 @@ def _island_findings(name: str, mesh: trimesh.Trimesh, islands: list[trimesh.Tri
def _penetration_finding(a: str, b: str, pen: Penetration, warn_m: float, error_m: float) -> GateFinding:
through = pen.through_ratio
- # ERROR keeps the pre-2026-08-30 meaning — deep AND a visible share of the part
- # (``PENETRATION_MIN_FRACTION``) — now with the depth measured properly. A pair found
- # only by the dense local pass (a stile 17 mm through a seat slab, 1 % of either surface)
- # is reported with every number but stays a WARN: with ERROR by depth alone the corpus
- # re-run flipped 27 runs of such joinery pass→fail on a cap the eye cannot confirm; the
- # judge, who sees the picture, is the one who can (D46 d). What still flips (14 of 217
- # runs) is a pair the old gate already reported, now measured 9.4 → 11.3 mm deep.
sev = (Severity.ERROR if pen.depth_m > error_m and pen.fraction_inside >= PENETRATION_MIN_FRACTION
else Severity.WARN)
msg = (f"'{a}' and '{b}' interpenetrate by ≈{pen.depth_m * 1000:.1f} mm "
f"({pen.fraction_inside:.0%} of surface samples inside, {pen.local_fraction:.0%} where they meet)")
if through >= 0.5:
- # the ratio saturates at the mid-plane: a tenon that STOPS there and a rail that passes
- # clean through read the same, so the words say what was measured and no more
msg += (f" — '{pen.entering}' reaches {min(through, 1.0):.0%} of the way to the mid-plane of "
f"'{pen.container}' ({pen.thickness_m * 1000:.0f} mm thick)")
if through >= THROUGH_FAR_SIDE_RATIO:
@@ -438,8 +310,7 @@ def _ledger(
unresolved: list[str],
gap_m: float,
) -> GateFinding:
- """The per-pair table ``check_connectivity`` used to compute and drop at exit: what
- the judge payload needs to say "these are welds" without the VLM guessing."""
+ """The per-pair table ``check_connectivity`` computes."""
order = {n: i for i, n in enumerate(names)}
contacts = [[a, b, _mm(exact[(a, b)].distance)] for a, b in sorted(edges, key=lambda e: (order[e[0]], order[e[1]]))]
over = [[a, b, _mm(p.depth_m), round(p.through_ratio, 2)] for a, b, p in overlaps if _mm(p.depth_m) > 0.0]
@@ -462,11 +333,7 @@ def check_connectivity(
language: str = "",
planned_edges: Sequence[PlannedEdge] = (),
) -> GateReport:
- """Run the connectivity gate on ``glb`` (see module docstring). ``language`` selects
- the frame of the translation hints (default: the GLB frame, labelled as such).
- ``planned_edges`` are the plan's ``attach_to`` pairs: each is measured exactly and
- listed in the ledger as contact/open; an open one is reported, not an ERROR — whether
- a missed planned join fails the gate is the owner's call (not made, 2026-08-30)."""
+ """Run the connectivity gate on ``glb`` (see module docstring)."""
t0 = time.time()
up = "z" if language_frame(language) is Frame.Z_UP_NEG_Y_FRONT else "y"
findings: list[GateFinding] = []
@@ -491,7 +358,7 @@ def check_connectivity(
edges: set[tuple[str, str]] = set()
exact: dict[tuple[str, str], PairDistance] = {}
overlaps: list[tuple[str, str, Penetration]] = []
- cache = _PartCache(parts) # one BVH / island split / thickness per part, shared across pairs
+ cache = _PartCache(parts)
for a, b in itertools.combinations(big, 2):
lower = _aabb_gap(parts[a].bounds, parts[b].bounds)
if lower > gap_m:
@@ -501,12 +368,8 @@ def check_connectivity(
if pd.distance <= gap_m:
edges.add((a, b))
if lower == 0.0: # AABBs overlap → possible penetration
- # at distance 0 fcl's closest points lie ON the overlap: a seed for the dense pass
seeds = np.array([pd.point_a, pd.point_b], dtype=float) if pd.distance <= 0.0 else None
if seeds is not None:
- # two intersecting Convex objects give fcl nothing to report and it returns the
- # ORIGIN as both closest points; a part centred on the origin would keep it as
- # a seed and widen the dense region over nothing
seeds = seeds[np.any(seeds != 0.0, axis=1)]
seeds = seeds if len(seeds) else None
pen = penetration_probe(a, parts[a], b, parts[b], cache=cache, seeds=seeds)
@@ -517,30 +380,11 @@ def check_connectivity(
findings.append(_penetration_finding(a, b, pen, penetration_warn_m, penetration_error_m))
# ---- components → floating parts
comps = collide.components(big, edges)
- # TOUCHING the ground, not merely at-or-below it: the old one-sided `<= gap_m`
- # counted a part buried 1 m under the floor as grounded, so a model authored around
- # the origin instead of on it (a routine agent mistake, which the contract gate
- # already reports separately as "object floats 1000 mm below the ground") put every
- # part in `grounded`, hence in `support`, and switched the floating check off for the
- # whole run. abs() makes the sunk model fall through to the "no part touches the
- # ground" WARN branch and report the same floating ERROR it does at y=0.
grounded = {n for n in big if abs(float(parts[n].bounds[0][1])) <= gap_m}
support_sets = [c for c in comps if c & grounded]
if support_sets:
- # THE support component (see the module docstring): ONE component, not the union
- # of every ground-touching one. Unioning made this max() dead and let any part
- # that merely reaches y=0 count as supported, so the commonest static-object
- # defect -- a leg 5 mm short of the seat, a rail shy of its post -- passed as long
- # as the part still stood on the floor, and the INFO line then claimed "all 5
- # parts are connected (3 contacts)" for a graph that needs >= 4 edges. It also
- # mutated the winning set in place, corrupting `comps`; hence the copy.
support = set(max(support_sets, key=lambda c: sum(len(parts[n].faces) for n in c)))
else:
- # Nothing touches the ground, so there is no ground to reason from: take the
- # LOWEST component as the base (face count only breaks ties). Picking the
- # biggest instead made a model authored around the origin report its base as the
- # floating part and the thing sitting on top as the support — the same finding as
- # the correctly-placed model, but with the two parts swapped.
support = min(comps, key=lambda c: (round(min(float(parts[n].bounds[0][1]) for n in c), 6),
-sum(len(parts[n].faces) for n in c))) if comps else set()
findings.append(GateFinding(gate=GATE, severity=Severity.WARN, message=f"no part touches the ground ({up}=0)",
@@ -595,11 +439,6 @@ def check_connectivity(
pd = pair_distance(a, parts[a], b, parts[b], obj_a=cache.fcl(a), obj_b=cache.fcl(b))
exact[(a, b)] = pd
rows.append([a, b, _mm(pd.distance), "contact" if pd.distance <= gap_m else "open"])
- # a group is ONE planned join offered against every parent copy the child's box
- # touches (contract.planned_joins): the exact distances say which copy it meant —
- # every CONTACT row, else the nearest OPEN one. Resolving the tie by list order
- # printed "OPEN: Brace_1→Leg_0" for a join the plan never meant (skeptic 2026-08-30);
- # reducing per CHILD instead hid a second, genuinely open join.
contacts = [r for r in rows if r[3] == "contact"]
planned.extend(contacts if contacts else rows[:1] if len(rows) <= 1 else [min(rows, key=lambda r: r[2])])
if len(big) > 1 and not any(f.severity == Severity.ERROR for f in findings):
@@ -617,11 +456,7 @@ def _nearest_supported(
cache: _PartCache,
n_candidates: int = 3,
) -> PairDistance | None:
- """Exact distance from floating part ``n`` to its nearest supported part.
-
- Candidates are ranked by AABB lower bound; the closest few get an exact test
- (reusing the per-part BVHs in ``cache``).
- """
+ """Exact distance from floating part ``n`` to its nearest supported part."""
if not support:
return None
ranked = sorted(support, key=lambda o: _aabb_gap(parts[n].bounds, parts[o].bounds))[:n_candidates]
diff --git a/harness/codeverse3d/spatial/contract.py b/harness/codeverse3d/spatial/contract.py
index 3da83474..6b5e158b 100644
--- a/harness/codeverse3d/spatial/contract.py
+++ b/harness/codeverse3d/spatial/contract.py
@@ -1,34 +1,4 @@
-"""Contract gate: does the built GLB honour the plan's part list and boxes?
-
-Plans are authored in the language's *native* frame (see ``conventions``):
-blender / cadquery / urdf are Z-up with -Y front, three.js is Y-up. The GLB is
-always Y-up, so plan boxes are converted with the glTF mapping
-``(x, y, z) → (x, z, -y)`` before comparison — and every number in a fix hint
-(sizes, deltas, centres, translation vectors) is converted *back* into the
-authoring frame and labelled, because hints are pasted verbatim into refine
-prompts that speak the language's frame.
-
-Severity policy (``tol = max(tol_m, REL_TOL × plan extent)`` per axis):
-* plan part missing in the GLB → ERROR
-* plan part still the skeleton's placeholder box (:func:`is_placeholder`: every measured row at
- most ``PLACEHOLDER_MAX_TRIS`` triangles, a closed solid filling its box, and within
- ``PLACEHOLDER_TOL_M`` of the plan box) → ERROR
- ``data["kind"] == "placeholder_part"`` (D110): it passes every box check by construction, so
- without this a session cut off mid-draft shipped stand-ins the gates called perfect
-* bbox centre / extents off by > tol → WARN (exact delta in the hint);
- > ``ERROR_FACTOR × tol`` → ERROR
-* overall bbox vs ``overall_bbox`` → same policy
-* overall extents are the plan's with up swapped for a horizontal axis → ERROR
- ``data["kind"] == "orientation"`` (lying down / stood on end); the two horizontal
- extents swapped → WARN "turned" (the az-0 view then shows a side, not the front)
-* lowest point off up = 0 by > ``GROUND_TOL_M`` → WARN (> ``ERROR_FACTOR ×`` → ERROR);
- footprint off-centre → WARN
-* GLB parts the plan never mentioned → INFO
-
-Every WARN/ERROR carries ``data["kind"]`` (missing_part · placeholder_part · instance_count · part_bbox ·
-instance_bbox · overall_bbox · orientation · ground_gap · footprint_offset): the rubric
-caps and the skill router key on it, never on the message.
-"""
+"""Contract gate: does the built GLB honour the plan's part list and boxes?"""
from __future__ import annotations
@@ -62,29 +32,10 @@ from codeverse3d.conventions import (
from codeverse3d.spatial.measure import fmt_extent_cm, fmt_vec
GATE = "contract"
-#: relative tolerance on extents (fraction of the plan's extent)
REL_TOL = 0.10
-#: a delta beyond ERROR_FACTOR × tolerance is an error, not a warning
ERROR_FACTOR = 3.0
_AXES = ("x", "y", "z")
-# Orientation (2026-08-30). A 90° turn about a horizontal axis leaves the AABB of the
-# planned box with its up extent swapped for a horizontal one, so "lying down" is a
-# permutation test on extents — but planners size THIN axes badly (h2h c_clamp: 9.6 cm
-# planned for a 2.4 cm clamp), so only the planned LONG axis is required to reappear,
-# within ORIENT_FIT; the thin one may be over-planned by up to ORIENT_OVER (the h2h
-# clock: 26 cm planned, 34 cm real). The up extent itself must have shrunk by
-# ORIENT_LYING; a build merely too short (fancy_v1 chamber_organ, 1.15 m for 3.2 m
-# planned, nothing sideways) or a 2× scale error is contract_violation, not this.
-# "Stood on end" (taller than planned, the planned width now up) needs ORIENT_STOOD:
-# planners under-size tall objects — loop_w7 orrery 0.32 m planned / 0.47 m built and
-# fancy_v1 smock_windmill 18.5 / 25.8 m are upright and sit at 1.4–1.5×. The rotation
-# axis's own extent must not have moved by more than ORIENT_THIRD (sysprompt_ab
-# b36_v0_01r: a table 1.38 m wide for a 0.48 m chair — wrong object, not rotated), and
-# near-cubes say nothing (ORIENT_ANISO). Over every measured static_object round under
-# eval/bench/out (629 measurements: 435 rounds + 194 final measurement.json, 217 runs) these
-# fire 0 times; on the brilliana c_clamp and gate_valve GLBs (both lying, by eye) they
-# fire with the right axis.
ORIENT_FIT = float(np.log(1.25))
ORIENT_LYING = float(np.log(1.5))
ORIENT_STOOD = float(np.log(2.0))
@@ -92,15 +43,6 @@ ORIENT_THIRD = float(np.log(1.5))
ORIENT_ANISO = 1.5
ORIENT_OVER = 1.4
-#: The skeleton's stand-in for a part is ONE axis-aligned box at the plan box — blender
-#: ``add_box`` / urdf ``box`` (``primitive_cube_add``, scale applied), three.js ``BoxGeometry``,
-#: cadquery ``Workplane.box`` — which every exporter writes as 12 triangles. A part whose every
-#: measured row is that small, that exactly placed and a closed solid FILLING its box is the
-#: placeholder, whatever its name says (no source grep, Law 4). 1 mm is a tenth of the contract
-#: tolerance (max(10 mm, 10 %)). The fill test keeps real 12-triangle hexahedra built to plan
-#: (a tapered cadquery fretboard, fill 0.879; wedges; open panes) out: over 942 measured part rows
-#: of loop_argon iter_00/01, the 68 true placeholders were all watertight at fill 1.000. A real
-#: part is taken for one only when it is itself a bare box built to the plan's millimetre.
PLACEHOLDER_MAX_TRIS = 12
PLACEHOLDER_TOL_M = 0.001
PLACEHOLDER_MIN_FILL = 1.0 - 1e-3
@@ -108,7 +50,7 @@ PLACEHOLDER_MIN_FILL = 1.0 - 1e-3
# --------------------------------------------------------------------------- frames
def frame_label(language: str) -> str:
- """Short frame tag for fix hints, e.g. ``"blender frame: Z-up, -Y front"``."""
+ """Short frame tag for fix hints, e.g."""
if language_frame(language) is Frame.Z_UP_NEG_Y_FRONT:
return f"{language} frame: Z-up, -Y front"
return f"{language} frame: Y-up, +Z front" if language else "GLB frame: Y-up, +Z front"
@@ -124,27 +66,17 @@ def plan_bbox_to_glb(bbox: BBox, language: str) -> BBox:
def glb_vec_to_plan(v, language: str, *, extents: bool = False) -> np.ndarray:
- """``conventions.to_authoring_frame`` as an array: hints must be written in the frame the
- agent codes in."""
+ """``conventions.to_authoring_frame`` as an array."""
return np.asarray(to_authoring_frame(v, language, extents=extents), dtype=float)
# --------------------------------------------------------------------------- matching
def match_parts(plan_parts: list[PartPlan], measured: list[PartMeasure]) -> tuple[dict[str, list[PartMeasure]], list[PartMeasure]]:
- """Map each plan part → measured rows (``Name``, ``Name_0``… accepted); plus unmatched rows.
-
- Exact names are claimed FIRST, and the ``Name_0..Name_N`` instance pass
- (``conventions.split_instance``) never takes a node that another plan part names
- exactly. The instance pattern once took ``shelf2`` for ``Shelf``, so a plan of
- ``Shelf`` + ``Shelf2`` had ``Shelf`` swallow the ``Shelf2`` node before ``Shelf2`` was
- considered — a false "missing from the GLB" ERROR and a real 0.75 judge cap on geometry
- that matched the plan exactly. ``Shelf``/``Shelf2``, ``Slat``/``Slat1``, ``Tier``/``Tier2``
- are ordinary planner output for PascalCase part names.
- """
+ """Map each plan part → measured rows (``Name``, ``Name_0``… accepted)."""
remaining = {m.name: m for m in measured}
matched: dict[str, list[PartMeasure]] = {pp.name: [] for pp in plan_parts}
reserved = {to_snake(pp.name) for pp in plan_parts}
- for pp in plan_parts: # pass 1: the node this plan part names exactly
+ for pp in plan_parts:
snake = to_snake(pp.name)
hits = [m for n, m in list(remaining.items()) if to_snake(n) == snake]
for m in hits:
@@ -162,13 +94,7 @@ def match_parts(plan_parts: list[PartPlan], measured: list[PartMeasure]) -> tupl
def is_placeholder(rows: list[PartMeasure], plan_box: BBox) -> bool:
"""Is this plan part (its measured rows, one per instance) still the skeleton's box?
-
- ``plan_box`` is in the GLB frame (:func:`plan_bbox_to_glb`). Every row must carry at most
- ``PLACEHOLDER_MAX_TRIS`` triangles (0 = not measured: never a placeholder), be watertight
- with a volume of at least ``PLACEHOLDER_MIN_FILL`` of its own box (not measured / open: never
- a placeholder) and have the plan's extents within ``PLACEHOLDER_TOL_M`` per axis; a single
- instance must also sit at the plan centre — the skeleton places instance copies by the
- symmetry hint, so only their size is the plan's."""
+ ``plan_box`` is in the GLB frame (:func:`plan_bbox_to_glb`)."""
if not rows:
return False
ext, ctr = np.asarray(plan_box.extents, dtype=float), np.asarray(plan_box.center, dtype=float)
@@ -186,23 +112,8 @@ def is_placeholder(rows: list[PartMeasure], plan_box: BBox) -> bool:
def planned_joins(plan: Plan | None, measurement: Measurement | None) -> list[tuple[str, tuple[str, ...]]]:
- """The plan's ``attach_to`` edges spelled in the GLB's part names, for the connectivity ledger.
-
- The ONE resolver: the track's gate and the MCP ``check_connectivity`` / folded build
- check all call this, so the agent-facing ledger and the judge's read the same pairs.
- Names resolve the way ``check_contract`` resolves them (``match_parts``: the exact node
- first, then the ``Name_0..N`` instances). Counted 2026-08-30 over the 357 stored
- static_object rounds that carry attach_to edges: 965 of 2 666 raw plan names are
- instance parts absent from the mesh under their plan spelling (``FrontLeg`` →
- ``FrontLeg_0``/``FrontLeg_1``) — feeding raw names listed them as unresolved.
- Each child copy joins the copy of its parent it TOUCHES by AABB (gap ≤ CONTACT_GAP_M),
- and every touching copy when several do: a brace spanning Leg_1→Leg_3 whose box also
- grazes Leg_0 ties at 0 for all three, and picking the first by list order sent it to
- Leg_0 alone — a false OPEN. The gate measures every pair exactly and reduces per
- child (the contact row wins, else the smallest gap), so emitting candidates costs
- nothing but a guess. A child touching no copy joins the nearest one — the full cross
- product would report the far apron/leg pair of every chair as OPEN.
- """
+ """The plan's ``attach_to`` edges spelled in the GLB's part names, for the connectivity
+ ledger."""
if plan is None or measurement is None or not measurement.parts:
return []
parts = list(getattr(plan, "parts", []) or [])
@@ -223,8 +134,7 @@ def planned_joins(plan: Plan | None, measurement: Measurement | None) -> list[tu
def _aabb_gap(a: np.ndarray | tuple, b: np.ndarray | tuple) -> float:
- """Euclidean distance between two boxes given as ``(min, max)`` corners, 0 when they
- overlap (``connectivity`` feeds it ``trimesh.bounds``: a mesh pair's lower bound)."""
+ """Euclidean distance between two ``(min, max)`` corner boxes, 0 when they overlap."""
(lo_a, hi_a), (lo_b, hi_b) = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
return float(np.linalg.norm(np.maximum(np.maximum(lo_a - hi_b, lo_b - hi_a), 0.0)))
@@ -255,9 +165,7 @@ def _fmt_delta(v: np.ndarray) -> str:
def _box_findings(target: str, d: _BoxDelta, plan: BBox, *, what: str, kind: str, language: str,
check_center: bool = True) -> list[GateFinding]:
- """WARN/ERROR findings for one box comparison (empty when within tolerance).
- ``d``/``plan`` are in the GLB frame; every number in the hint (and ``data``) is
- written back in ``language``'s authoring frame so the agent can paste it."""
+ """WARN/ERROR findings for one box comparison (empty when within tolerance)."""
out: list[GateFinding] = []
ext_bad = np.abs(d.extents) > d.tol
ctr_bad = check_center and np.any(np.abs(d.center) > d.tol)
@@ -290,11 +198,8 @@ def _log_ratio(a: float, b: float) -> float:
def _orientation_finding(m: Measurement, plan: StaticPlan, language: str) -> GateFinding | None:
- """Is the object lying down / stood on end (ERROR) or turned 90° about up (WARN)?
-
- Everything is in the plan frame: ``meas`` is the measured overall extents mapped back
- with :func:`glb_vec_to_plan`, ``up`` the frame's up axis from ``conventions``. One
- finding at most; the thresholds and the corpus behind them are documented at the top."""
+ """Is the object lying down / stood on end (ERROR) or turned 90° about up (WARN)? Everything
+ is in the plan frame."""
planned = np.asarray(plan.overall_bbox.extents, dtype=float)
meas = glb_vec_to_plan(m.extents, language, extents=True)
if np.any(planned <= 1e-6) or np.any(meas <= 1e-6):
@@ -304,7 +209,7 @@ def _orientation_finding(m: Measurement, plan: StaticPlan, language: str) -> Gat
horizontal = [a for a in range(3) if a != up]
best: tuple[float, str, int] | None = None # (fit, pose, h)
for h in horizontal:
- k = 3 - up - h # the axis the object turned about keeps its extent
+ k = 3 - up - h
if _log_ratio(meas[k], planned[k]) > ORIENT_THIRD:
continue
shrink = _log_ratio(meas[up], planned[up])
@@ -321,8 +226,6 @@ def _orientation_finding(m: Measurement, plan: StaticPlan, language: str) -> Gat
if best is not None:
_, pose, h = best
k = 3 - up - h
- # a disagreement with the PLANNED box, phrased as one: a plan that boxed a wall clock
- # flat makes an upright build read "stood", and the judge treats ERROR text as fact
verb = "is lying down relative to the planned box" if pose == "lying" else "stands on end relative to the planned box"
return GateFinding(
gate=GATE, severity=Severity.ERROR, target="overall",
@@ -390,22 +293,18 @@ def _check_object_plan(m: Measurement, plan: StaticPlan, language: str, tol_m: f
d = _box_delta(np.asarray(rows[0].bbox_min), np.asarray(rows[0].bbox_max), box, tol_m)
findings.extend(_box_findings(target, d, box, what=f"part '{pp.name}'", kind="part_bbox", language=language))
else:
- # instances: each copy should have the planned extents; the centre is unknowable
per = [_box_delta(np.asarray(r.bbox_min), np.asarray(r.bbox_max), box, tol_m) for r in rows]
union = _box_delta(np.min([r.bbox_min for r in rows], axis=0), np.max([r.bbox_max for r in rows], axis=0), box, tol_m)
worst_each = max(per, key=lambda d: float(np.max(np.abs(d.extents) / d.tol)))
- # accept whichever reading (per-instance or union) fits the plan better
if float(np.max(np.abs(union.extents) / union.tol)) < float(np.max(np.abs(worst_each.extents) / worst_each.tol)):
findings.extend(_box_findings(target, union, box, what=f"'{pp.name}' (all instances)", kind="instance_bbox", language=language, check_center=False))
else:
findings.extend(_box_findings(target, worst_each, box, what=f"'{pp.name}' (each instance)", kind="instance_bbox", language=language, check_center=False))
- # overall bbox
ob = plan_bbox_to_glb(plan.overall_bbox, language)
d = _box_delta(np.asarray(m.bbox_min), np.asarray(m.bbox_max), ob, tol_m)
findings.extend(_box_findings("overall", d, ob, what="overall", kind="overall_bbox", language=language))
if (orient := _orientation_finding(m, plan, language)) is not None:
findings.append(orient)
- # ground + footprint
if abs(m.ground_gap_m) > GROUND_TOL_M:
where = "above" if m.ground_gap_m > 0 else "below"
findings.append(GateFinding(
@@ -429,8 +328,8 @@ def _check_object_plan(m: Measurement, plan: StaticPlan, language: str, tol_m: f
def check_contract(measurement: Measurement, plan: StaticPlan, *, language: str, tol_m: float = BBOX_TOLERANCE_M) -> GateReport:
- """Compare ``measurement`` (from the GLB) with an object ``plan`` authored in ``language``'s frame.
- Scenes are checked by ``scene_placement`` from the census, never here."""
+ """Compare ``measurement`` (from the GLB) with an object ``plan`` authored in ``language``'s
+ frame."""
t0 = time.time()
findings = _check_object_plan(measurement, plan, language, tol_m)
if not findings:
diff --git a/harness/codeverse3d/spatial/frame_metrics.py b/harness/codeverse3d/spatial/frame_metrics.py
index 731677f8..d898264b 100644
--- a/harness/codeverse3d/spatial/frame_metrics.py
+++ b/harness/codeverse3d/spatial/frame_metrics.py
@@ -1,19 +1,8 @@
"""Frame-quality gate for scene renders: ``scene_frames``.
-Reads the deterministic ``camera_checks`` that ``render_scene`` leaves in
-``metrics.json`` (per camera: mean luminance, dark/blown/modal fractions,
-content/ground/sky coverage, nearest geometry, eye height) and turns them into
-``GateFinding``s with copyable fix hints, so a too-dark dusk, a blown sky, a
-camera buried in a wall or an establishing shot that shows a tiny island of
-content become gate findings (→ judge caps + refine instructions) instead of
-silently lowering a VLM score.
-
-* ``frame_findings(metrics)`` → GateReport
-* ``frame_gate_from_renders(rs_or_path)`` → GateReport (RenderSet / out dir / metrics.json)
-* ``frame_summary_text(metrics)`` → per-camera table for tool observations / prompts
-
-Authored cameras get ERRORs; harness orbit views only WARN (the agent does not
-place them) except for the content-sparse overview, which is informational.
+Turns the ``camera_checks`` in ``metrics.json`` (luminance, coverage, nearest geometry, eye height) into
+``GateFinding``s with fix hints. ``frame_findings`` / ``frame_gate_from_renders`` build the report,
+``frame_summary_text`` the per-camera table. Authored cameras get ERRORs; harness orbit views only WARN.
"""
from __future__ import annotations
@@ -29,12 +18,7 @@ FRAME_GATE = "scene_frames"
# thresholds (fractions of the frame / of full white)
DARK_MEAN_LUM = 0.12
-#: a frame this dark in the MEAN is still correctly exposed when it has real contrast --
-#: a lantern-lit night is dim on average and bright where the lanterns are. Measured
-#: 2026-08-25 on tsr_scn_temple_night r01: the three authored cameras sat at lum_std
-#: 0.171 / 0.199 / 0.249 while the flat overview rig sat at 0.058, so lum_std separates
-#: "low-key by design" from "unlit or broken" cleanly. ``lum_std`` has been in the
-#: camera_checks payload from host_metrics.mjs all along; this gate never read it.
+#: a dark-mean frame with at least this luminance std is low-key by design, not unlit
LOWKEY_MIN_STD = 0.12
DARK_FRAC = 0.35
BLOWN_FRAC = 0.20
@@ -49,9 +33,7 @@ TARGET_BLOCKED_FRAC = 0.5 # the line of sight to lookAt is cut before this
BLOCKED_RAYS_MIN = 6 # of the 3 x 3 sight rays, within near_limit_m (host BLOCKED_M)
EYE_MAX_ABOVE_GROUND_M = 80.0
-#: for a frame that is dark AND flat -- nothing is lit, so adding light is right. The hints
-#: state the measurement and leave the construction open (owner's rule, 2026-10-15): a library
-#: call or a number is an example, never the fix.
+#: hint for a frame that is dark and flat (nothing is lit)
_DARK_HINT = (
"the frame is too dark (the gate wants mean luminance >= 0.12, or real contrast with <= 35 % near-black pixels): "
"raise the key and the fill until the authored frames measure over the line without flattening them (scene_views: "
@@ -60,12 +42,7 @@ _DARK_HINT = (
"fill })` is one way to a balanced rig, and a set sun (elevation < 0) is its night rig; a fog colour that matches "
"the sky keeps the distance readable; dusk and night are colour, not black"
)
-#: for a frame that is dark but CONTRASTY -- something IS lit, so adding fill is the
-#: wrong move and actively destroys the picture. Measured 2026-08-25: temple_night was
-#: told by _DARK_HINT to add a HemisphereLight, did so, and the resulting flat fill
-#: washed the granite paving to near-white, flattened the scene to "snow at dawn" and
-#: drowned a working KoiWater ShaderMaterial -- the effect was running the whole time.
-#: The judge then scored the washed-out version 0.7287 and passed it.
+#: hint for a frame that is dark but contrasty (something is lit; flat fill would destroy it)
_LOWKEY_HINT = (
"this frame is DIM BUT LIT — it has real contrast, so flat fill (an AmbientLight / HemisphereLight, a stronger "
"DirectionalLight) is the wrong move: it turns a night scene into a grey wash, washes dark materials out to "
@@ -107,8 +84,7 @@ _LOW_HINT = ("the eye has to be >= 0.3 m above the surface beneath it (measured:
_HIGH_HINT = ("bring the camera below 80 m above the surface it stands over (measured: ground_below_m), to a height the "
"brief's viewpoint justifies — a tower top, a ridge, a rooftop, eye level — still aimed at its subject")
-#: scene_blender's words for the same fixes (D1, lane B): bpy lamps / world nodes / keyframes, the
-#: Blender frame (z up), ``ctx.height_at``. The thresholds are the same; only the advice differs.
+#: scene_blender's wording of the same fixes (bpy lamps / world nodes / keyframes, z up)
_BPY_HINTS: dict[str, str] = {
"dark": (
"the frame is too dark (the gate wants mean luminance >= 0.12, or real contrast with <= 35 % near-black pixels): "
@@ -154,8 +130,7 @@ _BPY_HINTS: dict[str, str] = {
"rebuild, say so in the plan: `assets[].kind: blender_glb` must not claim a hero the rendered scene does not contain."),
}
-#: fix hints per scene language (``metrics["language"]``; a payload without one is three.js, as
-#: every recorded round is)
+#: fix hints per scene language (``metrics["language"]``; none means three.js)
HINTS: dict[str, dict[str, str]] = {
"scene_threejs": {"dark": _DARK_HINT, "lowkey": _LOWKEY_HINT, "blown": _BLOWN_HINT, "flat": _FLAT_HINT,
"near": _NEAR_HINT, "static": _STATIC_HINT, "small": _SMALL_HINT, "eye": _EYE_HINT, "low": _LOW_HINT,
@@ -163,11 +138,7 @@ HINTS: dict[str, dict[str, str]] = {
"scene_blender": _BPY_HINTS,
}
-#: a judged Blender frame slower than this (GPU seconds at the configured samples; the CPU
-#: fallback gets ``SLOW_FRAME_CPU_FACTOR`` x) is a WARN naming the heaviest zone (owner D2).
-#: Calibrated 2026-09-24 on this box, Cycles CUDA 32 spp + OIDN at 1024x576: 0.9 s for a
-#: 520 k-tri / 310-object scene, 3.6 s with 72 k GN grass blades + 30 point lights + glass +
-#: a world volume — 10 s is ~3x the heaviest probe scene.
+#: a judged Blender frame slower than this (GPU seconds; CPU gets ``SLOW_FRAME_CPU_FACTOR`` x) is a WARN
SLOW_FRAME_S = 10.0
SLOW_FRAME_CPU_FACTOR = 3.3
@@ -194,15 +165,12 @@ def _exposure_findings(chk: dict[str, Any], *, authored: bool, hints: dict[str,
name = str(chk.get("name", "?"))
sev = Severity.ERROR if authored else Severity.WARN
out: list[GateFinding] = []
- # the orbit rig is the HARNESS's camera, not the scene's picture: say so in every
- # message, or a dark ground-level rig shot of a rooftop reads to the judge as the
- # scene being unlit (measured: it cost the rooftop battery a 0.60 cap three rounds running)
+ # the orbit rig is the harness's camera: every message says so, or the judge blames the scene
rig = "" if authored else "harness rig view (not an authored camera): "
mean, dark, blown, modal = (_num(chk, k) for k in ("mean_lum", "dark_frac", "blown_frac", "modal_frac"))
std = _num(chk, "lum_std")
is_dark = (mean is not None and mean < DARK_MEAN_LUM) or (dark is not None and dark > DARK_FRAC)
- # dim BUT lit: real contrast and not mostly black. A night scene must not be failed
- # for being a night scene, and must never be told to flatten itself with fill light.
+ # dim but lit: real contrast; a night scene must not be told to add fill light
low_key = is_dark and std is not None and std >= LOWKEY_MIN_STD and (dark is None or dark <= DARK_FRAC)
if is_dark:
msg = (f"frame too dark: mean luminance {mean:.2f}, {dark or 0:.0%} of pixels near black" if mean is not None
@@ -236,10 +204,7 @@ def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float |
out.append(_f(sev, name, rig + f"camera inside / touching geometry: {where}", hints["near"],
kind="camera_in_geometry", view=name, nearest_hit_m=near, inside=inside[:5]))
else:
- # The shot is a surface: most of the 3 x 3 sight rays end within arm's reach. cmp6's
- # crypt (2026-09-09): a squat stone pillar 0.8 m in front of AthanorDetail filled the
- # frame, the hero behind it was never seen, and the judge called the HERO "a massive
- # untextured grey box" for two rounds — nothing measured said the lens was blocked.
+ # the shot is a surface: most of the 3 x 3 sight rays end within arm's reach
near_rays, rays_total = _num(chk, "near_rays"), _num(chk, "rays_total")
if authored and near_rays is not None and rays_total and near_rays >= BLOCKED_RAYS_MIN:
limit = _num(chk, "near_limit_m") or 1.5
@@ -250,8 +215,7 @@ def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float |
"sightline; render this view and look before re-judging",
kind="camera_blocked", view=name, near_rays=near_rays, nearest_hit_m=near,
nearest_hit_name=chk.get("nearest_hit_name", "")))
- # …or the line of sight to the plan's lookAt is cut well before it (a pillar between the
- # lens and its subject; a close-up meets its own subject near the full distance).
+ # or the line of sight to the plan's lookAt is cut well before it
t_dist, t_hit = _num(chk, "target_distance_m"), _num(chk, "target_hit_m")
if authored and t_dist and t_hit is not None and t_hit < TARGET_BLOCKED_FRAC * t_dist:
cutter = str(chk.get("target_hit_name") or "geometry")
@@ -264,10 +228,7 @@ def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float |
below = _num(chk, "ground_below_m")
above_g = _num(chk, "ground_above_m")
if authored and above_g is not None:
- # A ground surface straight above the lens: a camera under the terrain looks up at back
- # faces, so its frame renders "fine" (structures floating over a void) — cmp6's
- # lighthouse shot its slipway from under the headland for three rounds. The camera
- # repair lifts it when it runs; this is the verdict when it did not.
+ # a ground surface straight above the lens: the frame looks up at back faces and renders "fine"
under = str(chk.get("ground_above_name") or "a ground surface")
buried = _frame_looks_buried(chk)
out.append(_f(Severity.ERROR if buried else Severity.WARN, name,
@@ -276,11 +237,7 @@ def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float |
kind="camera_underground" if buried else "camera_under_ground_mesh",
view=name, eye_height_m=eye, ground_above_m=above_g))
elif authored and below is not None:
- # The ray straight down from the eye (``nearGeometry``): the surface this lens
- # actually stands over. Scene-wide ``ground_y`` is the top of the HIGHEST ground
- # mesh, and on relief terrain it called a camera at eye level on a low patch an
- # "ant's-eye view" (loop 21 ski station: eye 3.20 m, snow mound 3.14 m) — a false
- # WARN the judge then repeated as a major issue.
+ # the ray straight down from the eye: the surface this lens stands over (scene-wide ground_y is wrong on relief terrain)
under = str(chk.get("ground_below_name") or "the surface beneath it")
if below < EYE_MIN_ABOVE_GROUND_M:
out.append(_f(Severity.WARN, name, f"camera eye only {below:.2f} m above {under} — ant's-eye view",
@@ -291,14 +248,11 @@ def _geometry_findings(chk: dict[str, Any], *, authored: bool, ground_y: float |
hints["high"],
kind="camera_high", view=name, eye_height_m=eye, ground_below_m=below))
elif authored and eye is not None and ground_y is not None:
- # Nothing beneath the lens (under the terrain, off the ground's edge) or an older
- # census: compare with the scene's highest ground surface.
+ # nothing beneath the lens: compare with the scene's highest ground surface
above = eye - ground_y
if above < -0.2:
- # ``ground_y`` is the TOP of every ground-classified mesh in the scene (census),
- # so a hill, a terrace or a raised backdrop puts it metres above a camera
- # that is standing in the open. Only call the camera buried when the frame
- # agrees: a buried camera renders dark, empty or from inside geometry.
+ # ground_y is the top of every ground mesh, so terrain can sit above an open camera:
+ # only call it buried when the frame agrees
buried = _frame_looks_buried(chk)
out.append(_f(Severity.ERROR if buried else Severity.WARN, name,
f"camera is {-above:.1f} m below the scene's highest ground surface ({ground_y:.2f} m)"
@@ -403,16 +357,7 @@ HINTS["scene_threejs"]["unused_glb"] = _UNUSED_GLB_HINT
def _glb_findings(census: dict[str, Any], hints: dict[str, str]) -> list[GateFinding]:
"""A GLB that was loaded and contributed no geometry to the rendered scene.
- Measured 2026-08-25 on tsr_scn_boat_workshop_v2: ``src/scene.js`` loads
- ``/assets/clinker_skiff.glb`` — a real Blender hero, authored, built and copied into
- ``public/assets`` — while ``src/zones/central_bay.js`` calls a procedural
- ``buildClinkerSkiff(THREE)`` that a refine round wrote over the asset slot. The hull in
- every shipped frame is JavaScript. Nothing flagged it, and the check the wave was
- using to verify the multi-language claim (``plan.json`` -> ``assets[].kind``) still
- reported ``blender_glb``, because the plan records what was PLANNED.
-
- WARN, not ERROR: the picture is fine, and an author who deep-copies geometry
- (``geometry.clone()``) rather than cloning the object would read as unused here.
+ WARN, not ERROR: deep-copied geometry would read as unused.
"""
rows = census.get("glb_assets")
if not isinstance(rows, list):
@@ -435,18 +380,12 @@ HERO_DETAIL_MIN_FRAC = 0.02 # of the frame, in the camera NAMED for the her
def _hero_findings(checks: list[dict[str, Any]], census: dict[str, Any]) -> list[GateFinding]:
- """A Blender hero that is IN the scene but in no authored frame — or nearly absent from
- the camera named for it. ``camera_checks[].glb_frac`` (``glbCoverage``: a mask render
- per GLB per camera, occlusion included). cmp6's crypt (2026-09-09): the athanor stood
- behind a squat pillar in every authored shot, the judge called the HERO "a massive
- untextured grey box", and two refine rounds rebuilt the wrong thing — "in the scene"
- (``glb_assets``) was known, "in the frame" was not."""
+ """A Blender hero that is in the scene but in no authored frame, or nearly absent from its named camera (``camera_checks[].glb_frac``)."""
rows = census.get("glb_assets")
if not isinstance(rows, list):
return []
authored = [c for c in checks if _view_kind(c) == "authored"]
- # which camera is NAMED for which hero is the host's rule (scene_host.mjs namesHero — the one
- # camera repair re-aims by); a census from before 2026-09-23 carries no hero_for
+ # which camera is named for which hero is the host's rule (scene_host.mjs namesHero)
named = {str(c.get("name", "?")): c.get("hero_for") or [] for c in authored}
out: list[GateFinding] = []
for r in rows:
@@ -460,13 +399,11 @@ def _hero_findings(checks: list[dict[str, Any]], census: dict[str, Any]) -> list
if v is not None:
seen[str(c.get("name", "?"))] = v
if not seen:
- continue # older census, or no authored camera
+ continue
base = url.rsplit("/", 1)[-1]
best = max(seen.values())
listing = ", ".join(f"{n} {v:.1%}" for n, v in list(seen.items())[:6])
- # one instance's extent (scene_host glbUsage; until 2026-10-14 the union of every clone was the
- # size, and a 2.2 m sofa placed three times read "6.5 m across"); the copy count says why the
- # frame fraction and the size can disagree
+ # one instance's extent; the copy count explains why frame fraction and size can disagree
size = _num(r, "size_m")
copies = int(r.get("instances") or 0)
placed = f" ({size:.1f} m across as placed{f', {copies} copies' if copies > 1 else ''})" if size else ""
@@ -490,10 +427,7 @@ def _hero_findings(checks: list[dict[str, Any]], census: dict[str, Any]) -> list
def _render_time_findings(metrics: dict[str, Any]) -> list[GateFinding]:
- """A Blender frame set whose median JUDGED frame took longer than ``SLOW_FRAME_S`` (owner
- D2: offline rendering has no draw budget; its cost is seconds per frame). WARN, naming the
- zone with the most triangles — the first place to thin. Silent for every payload without a
- ``blender`` block (three.js)."""
+ """WARN when the median judged Blender frame took longer than ``SLOW_FRAME_S``, naming the heaviest zone; silent for three.js."""
b = metrics.get("blender")
if not isinstance(b, dict):
return []
@@ -550,8 +484,7 @@ def frame_findings(metrics: dict[str, Any]) -> GateReport:
def frame_gate_from_renders(source: RenderSet | Path | str) -> GateReport:
- """``scene_frames`` gate from a RenderSet (locates its metrics.json), a render
- directory or a metrics.json path. Missing metrics → an empty passing report."""
+ """``scene_frames`` gate from a RenderSet, a render directory or a metrics.json path; missing metrics → empty passing report."""
from codeverse3d.spatial.render_scene import metrics_path_for
if isinstance(source, RenderSet):
diff --git a/harness/codeverse3d/spatial/frame_motion.py b/harness/codeverse3d/spatial/frame_motion.py
index 34fb48d3..3d22b822 100644
--- a/harness/codeverse3d/spatial/frame_motion.py
+++ b/harness/codeverse3d/spatial/frame_motion.py
@@ -1,18 +1,7 @@
-"""Deterministic inter-frame MOTION for scene renders.
-
-``render_scene`` photographs every camera at ``times`` (default t = 0 s and
-t = 1.5 s). Whether anything actually moved between those frames is a
-*measurement*, not a perception task: a VLM comparing two tiles that live in
-different montage images cannot see a 2 % pixel change, and every scene judged
-so far was told "nothing moves" while the water and the foliage were in fact
-animating. So the harness measures it here, in code, and hands the judge the
-number (law 3: deterministic gates/measurements run by the harness, the VLM only
-perceives).
-
-``motion_rows(metrics, out_dir)`` diffs the first and last rendered frame of
-each camera and returns one ``MotionRow`` per camera;
-``motion_summary_text(rows)`` renders the table that goes into the judge's
-context and into the ``scene_frames`` gate.
+"""Deterministic inter-frame motion for scene renders.
+
+``motion_rows`` diffs the first and last rendered frame of each camera into ``MotionRow``s;
+``motion_summary_text`` renders the table the judge and the ``scene_frames`` gate read.
"""
from __future__ import annotations
@@ -112,11 +101,7 @@ def _pair_rows(entries: Sequence[dict[str, Any]], out_dir: Path) -> list[MotionR
def motion_rows(metrics: dict[str, Any], out_dir: Path | str) -> list[MotionRow]:
- """One row per camera rendered at ≥ 2 times (authored cameras first).
-
- ``metrics`` is a ``render_scene`` metrics payload; the view paths inside it
- are relative to ``out_dir``. Unreadable or single-time views are skipped —
- a missing row means "not measured", never "static"."""
+ """One row per camera rendered at ≥ 2 times (authored first); unreadable views are skipped (not measured, not static)."""
entries = metrics.get("views") or []
if not isinstance(entries, list):
return []
@@ -132,7 +117,7 @@ def scene_moves(rows: Sequence[MotionRow]) -> bool | None:
def motion_summary_text(rows: Sequence[MotionRow], *, max_rows: int = 10) -> str:
- """The table the judge and the refine prompts read (empty string = nothing measured)."""
+ """The table the judge and refine prompts read (empty string = nothing measured)."""
if not rows:
return ""
moves = scene_moves(rows)
@@ -153,17 +138,14 @@ def motion_summary_text(rows: Sequence[MotionRow], *, max_rows: int = 10) -> str
def motion_from_dir(out_dir: Path | str) -> list[MotionRow]:
- """Convenience: read ``<out_dir>/metrics.json`` and measure it."""
+ """Measure ``<out_dir>/metrics.json``."""
d = Path(out_dir)
metrics = read_json_or_none(d / "metrics.json")
return [] if metrics is None else motion_rows(metrics, d)
def motion_text_for(out_dir: Path | str) -> str:
- """``motion_summary_text`` for one render directory; ``""`` on any problem.
-
- This is what a track puts in front of the judge, so it must never be the reason a
- round fails: instrumentation that cannot be read is simply absent."""
+ """``motion_summary_text`` for one render directory; ``""`` on any problem (never fails a round)."""
try:
return motion_summary_text(motion_from_dir(out_dir))
except Exception as e: # noqa: BLE001 — judge context must never break a round
diff --git a/harness/codeverse3d/spatial/frame_stats.py b/harness/codeverse3d/spatial/frame_stats.py
index 3b5c266a..00898c3c 100644
--- a/harness/codeverse3d/spatial/frame_stats.py
+++ b/harness/codeverse3d/spatial/frame_stats.py
@@ -1,12 +1,6 @@
-"""Visual + temporal metrics for a rendered frame sequence (numpy + PIL only).
-
-Per frame: mean luminance, luminance std, % near-black, % blown-out pixels,
-colourfulness (Hasler–Süsstrunk), edge density (gradient magnitude above a
-threshold). Temporal: mean absolute difference between consecutive frames
-(0 → static), duplicate frames, flicker (very large diffs), plus NaN/Inf counts
-reported by the GL runner (float readback). ``frame_gate`` turns the sequence
-into the ``gl_frames`` GateReport the graphics track + rubric caps consume
-(``data["kind"]`` ∈ nan · black · blown · static · flicker · duplicate · low_detail).
+"""Per-frame and temporal metrics of a rendered frame sequence, and the ``gl_frames`` gate built on them.
+
+``data["kind"]`` of a finding is one of nan · black · blown · static · flicker · duplicate · low_detail.
"""
from __future__ import annotations
@@ -81,7 +75,7 @@ def luminance(rgb: np.ndarray) -> np.ndarray:
def colourfulness(rgb: np.ndarray) -> float:
- """Hasler & Süsstrunk (2003) metric on 0..1 floats (≈0 grey, ~0.3+ vivid)."""
+ """Hasler-Süsstrunk colourfulness on 0..1 floats (≈0 grey, ~0.3+ vivid)."""
r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
rg = r - g
yb = 0.5 * (r + g) - b
@@ -133,10 +127,7 @@ def sequence_stats(frames: Sequence[tuple[float, str | Path]], *, nan_counts: Se
seq.mean_diff = float(np.mean(diffs))
seq.max_diff = float(np.max(diffs))
seq.n_duplicates = sum(1 for d in diffs if d < DUPLICATE_DIFF)
- # MAX, not mean: 'static' is a scoring cap (shader.yaml static_frames), so it must
- # require that NO sampled pair changed. With the mean, an effect whose motion is
- # concentrated between two of the five sampled times (0/1/2.5/4/6 s) is averaged down
- # by the three quiet pairs and convicted while animating.
+ # MAX, not mean: 'static' is a scoring cap, so no sampled pair may have changed.
seq.static = seq.max_diff < STATIC_DIFF
seq.flicker = seq.max_diff > FLICKER_DIFF and len(diffs) >= 2
return seq
@@ -144,7 +135,7 @@ def sequence_stats(frames: Sequence[tuple[float, str | Path]], *, nan_counts: Se
# --------------------------------------------------------------------------- gate
def frame_gate(seq: SequenceStats, *, motion_expected: bool = True, gate: str = GATE) -> GateReport:
- """Deterministic findings the judge/refiner/caps consume (``data["kind"]`` set)."""
+ """Findings the judge, refiner and caps consume."""
f: list[GateFinding] = []
def add(sev: Severity, kind: str, msg: str, hint: str, target: str = "overall", **data: object) -> None:
diff --git a/harness/codeverse3d/spatial/gl_render.py b/harness/codeverse3d/spatial/gl_render.py
index e3050f2c..886b3b02 100644
--- a/harness/codeverse3d/spatial/gl_render.py
+++ b/harness/codeverse3d/spatial/gl_render.py
@@ -1,20 +1,7 @@
"""GlHost: headless moderngl rendering of fragment shaders / raw OpenGL programs.
-moderngl contexts are not fork-safe and the harness is multi-threaded, so every
-render happens in a fresh ``python3`` subprocess running the standalone
-``languages/opengl_python/wrappers/run_gl.py``. The host tries the GPU driver
-environment first (Mesa d3d12 on WSL2) and falls back to llvmpipe when the
-context cannot be created; the decision is cached per process.
-
-Public API::
-
- host = GlHost() # gpu="auto" | "on" | "off"
- res = host.render_fragment_shader(frag_src, out_dir, width=1280, height=720, times=(0, 1, 2.5),
- buffer_a_src=None, feedback=False, extra_times=())
- res = host.run_program(program_path, out_dir, width=..., height=..., times=...)
- res.ok · res.frames[GlFrame] · res.judge_frames · res.stage · res.error_message · res.renderer
-
-Artifacts derived from a result: :func:`write_contact_sheet`, :func:`write_gif`.
+Every render runs in a fresh subprocess (``run_gl.py``; moderngl contexts are not fork-safe).
+GPU (Mesa d3d12) is tried first, llvmpipe is the fallback; the choice is cached per process.
"""
from __future__ import annotations
@@ -33,7 +20,7 @@ from codeverse3d.proc import run_subprocess
RUNNER = Path(__file__).resolve().parent.parent / "languages" / "opengl_python" / "wrappers" / "run_gl.py"
-#: Mesa d3d12 driver env (GPU on WSL2). Falls back to llvmpipe when unusable.
+#: Mesa d3d12 driver env (GPU on WSL2).
GPU_ENV: dict[str, str] = {
"GALLIUM_DRIVER": "d3d12",
"MESA_LOADER_DRIVER_OVERRIDE": "d3d12",
@@ -92,7 +79,7 @@ def _base_env(extra: dict[str, str]) -> dict[str, str]:
def gpu_preference(gpu: str) -> list[bool]:
- """Order of attempts: [True, False] (GPU then CPU) for auto, etc."""
+ """Order of attempts (True = GPU) for ``gpu`` in auto/on/off."""
if gpu == "on":
return [True]
if gpu == "off":
@@ -133,9 +120,7 @@ class GlHost:
# ------------------------------------------------------------------ internals
def _run(self, job: dict[str, Any], out_dir: Path) -> GlResult:
- # The subprocess starts inside out_dir. A relative job path would be
- # resolved against that directory a second time and appear to crash
- # before it could write any result (observed with --out examples/...).
+ # The subprocess starts inside out_dir: a relative job path would be resolved twice.
out_dir = Path(out_dir).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
(out_dir / RESULT_NAME).unlink(missing_ok=True)
@@ -186,11 +171,7 @@ class GlHost:
# --------------------------------------------------------------------------- derived artifacts
def write_contact_sheet(frames: Sequence[GlFrame], out: Path, *, cols: int = 3, tile_w: int = 480) -> Path:
- """Labelled grid of frames keeping their aspect ratio (``t=<s>`` under each tile).
-
- Thin wrapper over :func:`codeverse3d.spatial.sheet.contact_sheet` (the one
- sheet builder) with a 16:9-style cell derived from the first frame.
- """
+ """Labelled grid of frames (``t=<s>`` under each tile), cell sized from the first frame."""
from codeverse3d.spatial.sheet import contact_sheet, tile_size
frames = list(frames)
@@ -201,7 +182,7 @@ def write_contact_sheet(frames: Sequence[GlFrame], out: Path, *, cols: int = 3,
def write_gif(frames: Sequence[GlFrame], out: Path, *, width: int = 480, fps: int = 6) -> Path | None:
- """Animated GIF preview from ALL frames (judge + extra), resized to ``width``."""
+ """Animated GIF of all frames (judge + extra)."""
from codeverse3d.spatial.sheet import write_gif as _write_gif
ordered = sorted(frames, key=lambda f: f.time)
diff --git a/harness/codeverse3d/spatial/joints_collide.py b/harness/codeverse3d/spatial/joints_collide.py
index feacdb28..14cadfa4 100644
--- a/harness/codeverse3d/spatial/joints_collide.py
+++ b/harness/codeverse3d/spatial/joints_collide.py
@@ -1,17 +1,4 @@
-"""Per-link collision bodies for the pose sweep (:mod:`joints_sweep`).
-
-FCL (``python-fcl``) answers the boolean surface-collide and
-the exact separation distance on BVH models. Penetration *depth* is measured
-deterministically on the link's **watertight islands**: a surface sample of
-body A counts as inside body B when a fixed-direction parity ray test (forward
-and backward rays agree) places it inside one of B's islands, and its depth is
-the unsigned distance to that island's surface. This is independent of the
-mesh winding (agent meshes routinely come out inverted) and does not depend on
-``Trimesh.contains`` / signed normals on the merged link mesh, which is usually
-non-watertight (touching panels share vertices) and was re-cast with *random*
-rays. Islands that are not watertight are tested the same way but flagged
-``approx``.
-"""
+"""Per-link collision bodies for the pose sweep (:mod:`joints_sweep`)."""
from __future__ import annotations
@@ -21,13 +8,12 @@ import trimesh
from trimesh.ray import ray_util
_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 components(names: list[str], edges: set[tuple[str, str]]) -> list[set[str]]:
- """Connected components of ``names`` under ``edges`` (union-find) — the contact
- graph of the connectivity gate and the fixed-joint groups of the pose sweep."""
+ """Connected components of ``names`` under ``edges`` (union-find) — the contact graph of the
+ connectivity gate and the fixed-joint groups of the pose sweep."""
parent = {n: n for n in names}
def find(x: str) -> str:
@@ -45,11 +31,7 @@ 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). Convex meshes get the cheap ``fcl.Convex``
- (same choice trimesh's CollisionManager makes — building a BVH for a
- 300k-tri convex part costs ~0.7 s); everything else gets a BVH. Shared by
- :class:`LinkBody` and the connectivity gate so each mesh's collision
- geometry is built exactly once."""
+ """``fcl.CollisionObject`` for ``mesh`` (identity transform)."""
if 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()),
@@ -72,8 +54,7 @@ def _sample_points(mesh: trimesh.Trimesh) -> np.ndarray:
def oriented_islands(mesh: trimesh.Trimesh) -> list[trimesh.Trimesh]:
- """Connected components of ``mesh``; watertight ones get outward-facing normals
- (inverted winding → ``invert()``), so volumes/booleans are meaningful."""
+ """Connected components of ``mesh``."""
try:
islands = list(mesh.split(only_watertight=False))
except Exception:
@@ -87,11 +68,7 @@ def oriented_islands(mesh: trimesh.Trimesh) -> list[trimesh.Trimesh]:
def inside_island(island: trimesh.Trimesh, points: np.ndarray) -> np.ndarray:
- """Deterministic parity containment (fixed ray direction, both directions must agree).
-
- Public because the connectivity gate measures interpenetration the same way: it must
- work on the non-watertight meshes agents actually export, where ``Trimesh.contains``
- cannot answer at all."""
+ """Deterministic parity containment (fixed ray direction, both directions must agree)."""
if len(points) == 0:
return np.zeros(0, dtype=bool)
return np.asarray(ray_util.contains_points(island.ray, points, check_direction=_RAY_DIR), dtype=bool)
@@ -134,7 +111,8 @@ class LinkBody:
return np.vstack([pts.min(axis=0), pts.max(axis=0)])
def depth_of(self, points_world: np.ndarray) -> float:
- """Max distance-to-surface of the ``points_world`` that lie inside one of this body's islands."""
+ """Max distance-to-surface of the ``points_world`` that lie inside one of this body's
+ islands."""
local = trimesh.transform_points(points_world, self.T_inv)
depth = 0.0
for island, pq in zip(self.islands, self._island_pq, strict=True):
@@ -162,8 +140,8 @@ def collide(a: LinkBody, b: LinkBody) -> bool:
def contained(a: LinkBody, b: LinkBody, n: int | None = 24) -> bool:
- """True when surface samples of one body lie inside the other (FCL's surface-only
- collide misses a part fully swallowed by another). ``n`` samples per side (None = all)."""
+ """True when surface samples of one body lie inside the other (FCL's surface-only collide
+ misses a part fully swallowed by another)."""
if n is None:
pa, pb = a.points, b.points
else:
@@ -180,7 +158,6 @@ def distance(a: LinkBody, b: LinkBody) -> float:
def penetration(a: LinkBody, b: LinkBody) -> tuple[float, bool]:
- """Max penetration depth (m) of A's surface into B or B's into A; ``approx``
- when an island is not watertight (the inside test is then heuristic)."""
+ """Max penetration depth (m) of A's surface into B or B's into A."""
depth = max(b.depth_of(a.points), a.depth_of(b.points))
return depth, not (a.watertight and b.watertight)
diff --git a/harness/codeverse3d/spatial/joints_export.py b/harness/codeverse3d/spatial/joints_export.py
index c5b3c3cc..45fb4645 100644
--- a/harness/codeverse3d/spatial/joints_export.py
+++ b/harness/codeverse3d/spatial/joints_export.py
@@ -1,13 +1,5 @@
-"""Export a posed :class:`Robot` to the canonical GLB (node hierarchy mirroring
-links, joint extras) and render articulation sheets.
-
-GLB convention: Y-up, +Z front (``codeverse3d.conventions.GLB_FRAME``). The
-URDF world (Z-up, -Y front) is rotated by ``Rx(-90°)`` at the ``<robot name>``
-node; every link is a child node (name = link name) whose local matrix is the
-joint transform ``T_origin · Motion(q)``; geometry lives in the link frame.
-Non-root link nodes carry ``extras.joint`` and the scene carries
-``extras.joints / links / pose`` (same keys as the owner's dataset builder).
-"""
+"""Export a posed :class:`Robot` to the canonical GLB (node hierarchy mirroring links, joint extras)
+and render articulation sheets."""
from __future__ import annotations
@@ -27,9 +19,7 @@ from codeverse3d.spatial.render import render_glb
from codeverse3d.spatial.sheet import contact_sheet
ARTICULATION_SHEET_NAME = "articulation_sheet.png"
-#: URDF (Z-up, -Y front) → glTF (Y-up, +Z front): (x, y, z) → (x, z, -y)
ZUP_TO_YUP = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]], dtype=float)
-#: scene-graph base frame of the exported GLB (not a glTF node; must not collide with a link name)
SCENE_BASE_FRAME = "__scene__"
@@ -43,10 +33,7 @@ def joint_extras(j: Joint) -> dict[str, Any]:
def robot_node_name(robot: Robot) -> str:
- """Name of the ``<robot>`` root node (carries the Z-up → Y-up rotation). Scene-graph
- node names must be unique, so a robot named like one of its links (``<robot
- name="body">`` with a link ``body``) gets a ``__root`` suffix instead of silently
- aliasing the link node — which would drop the rotation and the link's placement."""
+ """Name of the ``<robot>`` root node (carries the Z-up → Y-up rotation)."""
name = robot.name or "robot"
while name in robot.links or name == SCENE_BASE_FRAME:
name += "__root"
@@ -56,11 +43,8 @@ def robot_node_name(robot: Robot) -> str:
def robot_scene(robot: Robot, pose: dict[str, float] | None = None) -> trimesh.Scene:
"""Build the trimesh.Scene (hierarchical, Y-up) for ``robot`` at ``pose``."""
fk(robot, pose or {}) # validates joint names
- # the RESOLVED pose: a <mimic> follower moves with its driver in the export too, not
- # only in fk. The sheet the judge sees and the sweep's collision check are the same
- # mechanism only if both pose it the same way (review, 2026-09-04: they did not).
pose = resolve_q(robot, pose or {})
- scene = trimesh.Scene(base_frame=SCENE_BASE_FRAME) # never a link name (a link 'world' would close a cycle)
+ scene = trimesh.Scene(base_frame=SCENE_BASE_FRAME)
robot_node = robot_node_name(robot)
meta = {"links": robot.link_order(), "frame": "y_up_pos_z_front", "pose": dict(pose), "units": "meters"}
meta["joints"] = [joint_extras(j) for j in robot.joints.values()]
@@ -77,7 +61,7 @@ def robot_scene(robot: Robot, pose: dict[str, float] | None = None) -> trimesh.S
if len(pieces) == 1:
scene.add_geometry(pieces[0].copy(), node_name=name, geom_name=name, parent_node_name=parent_node,
transform=local, metadata=extras)
- else: # several materials: link node + one geometry child per piece (names stay unique)
+ else:
scene.graph.update(frame_to=name, frame_from=parent_node, matrix=local, metadata=extras)
for i, piece in enumerate(pieces):
scene.add_geometry(piece.copy(), node_name=f"{name}{LINK_PIECE_SEP}{i}", geom_name=f"{name}{LINK_PIECE_SEP}{i}", parent_node_name=name,
@@ -105,9 +89,7 @@ def render_poses(
width: int = 512,
height: int = 512,
) -> list[tuple[str, RenderSet]]:
- """Export one GLB per pose, render ``views`` for each (default: ``ARTICULATION_VIEWS``)
- and write ``out_dir/articulation_sheet.png`` (rest / each joint at lower & upper
- by default — the image the judge sees). Returns ``[(pose_name, RenderSet)]``."""
+ """Export one GLB per pose and render ``views`` of each."""
out_dir = out_directory(out_dir)
poses = poses if poses is not None else limit_poses(robot)
views = tuple(views or ARTICULATION_VIEWS)
diff --git a/harness/codeverse3d/spatial/joints_model.py b/harness/codeverse3d/spatial/joints_model.py
index 45c170fc..f20ad0b0 100644
--- a/harness/codeverse3d/spatial/joints_model.py
+++ b/harness/codeverse3d/spatial/joints_model.py
@@ -1,18 +1,4 @@
-"""URDF data model + loader + forward kinematics (numpy, trimesh).
-
-Conventions (see ``codeverse3d/languages/urdf/CONTRACT.md``):
-
-* URDF frames are Z-up, -Y front, meters. ``<origin xyz rpy>`` uses the URDF
- rotation order ``R = Rz(yaw) · Ry(pitch) · Rx(roll)``.
-* A joint's ``<origin>`` places the joint frame in the PARENT link frame; the
- child link frame coincides with the joint frame at ``q = 0``; ``<axis>`` is
- expressed in the joint frame. ``T_child = T_parent · T_origin · Motion(q)``.
-* Mesh files referenced by ``<mesh filename>`` are taken in RAW coordinates
- (standard URDF semantics). Our wrapper writes ``meshes/<link>.glb`` with
- vertices in URDF (Z-up) coordinates (``export_yup=False``), so no axis
- conversion happens on load. ``Link.mesh`` is stored in the LINK frame (the
- visual origin is already applied).
-"""
+"""URDF data model + loader + forward kinematics (numpy, trimesh)."""
from __future__ import annotations
@@ -28,9 +14,6 @@ from codeverse3d.contracts.common import MimicIssue, MimicSpec, mimic_issues
MOVABLE_TYPES = ("revolute", "prismatic", "continuous")
JOINT_TYPES = MOVABLE_TYPES + ("fixed",)
-#: link names that cannot become GLB nodes: glTF readers (trimesh) use ``world`` as the
-#: scene-graph base frame and stomp on a node of that name (the export then loses its
-#: frame / cycles). ``load_urdf`` rejects them; ``lint`` reports them first.
RESERVED_LINK_NAMES = frozenset({"world"})
@@ -40,9 +23,7 @@ class UrdfError(ValueError):
# ------------------------------------------------------------------ small math
def parse_floats(text: str | None, n: int, what: str) -> tuple[float, ...]:
- """Parse ``"a b c"`` → ``n`` finite floats; raises ``UrdfError`` with ``what`` on bad input.
- The ONE number reader of a URDF: the loader and the lint both parse through it, so
- lint-clean text cannot raise here at build time (``lower="0 1"`` did, 2026-09-24)."""
+ """Parse ``"a b c"`` → ``n`` finite floats."""
parts = (text or "").split()
if len(parts) != n:
raise UrdfError(f"{what}: expected {n} number{'s' if n > 1 else ''}, got {text!r}")
@@ -76,7 +57,7 @@ def matrix_to_rpy(R: np.ndarray) -> tuple[float, float, float]:
sy = -R[2, 0]
sy = max(-1.0, min(1.0, float(sy)))
pitch = math.asin(sy)
- if abs(math.cos(pitch)) < 1e-9: # gimbal lock: fold yaw into roll
+ if abs(math.cos(pitch)) < 1e-9:
roll = math.atan2(-R[1, 2], R[1, 1])
yaw = 0.0
else:
@@ -128,13 +109,7 @@ def parse_origin(elem: ET.Element | None, what: str) -> np.ndarray:
# ------------------------------------------------------------------ model
@dataclass(frozen=True)
class Mimic:
- """A joint driven by another: ``q = multiplier * q[joint] + offset`` (URDF <mimic>).
-
- Coupled mechanisms (umbrella ribs on one runner, a pantograph's crossing arms, a
- tambour's slats) have one degree of freedom and many moving links; without this the
- sweep drives every link independently and poses the mechanism in states it cannot
- reach (compare_art_v3/v4: umbrella, scissor_mirror and folding_workbench are the
- lowest-scoring prompts on the battery)."""
+ """A joint driven by another."""
joint: str
multiplier: float = 1.0
@@ -172,8 +147,8 @@ class Joint:
@dataclass
class Link:
name: str
- mesh: trimesh.Trimesh | None = None # merged, in LINK frame (visual origin applied) — used for QC
- submeshes: list[trimesh.Trimesh] = field(default_factory=list) # per-material pieces, LINK frame — used for export
+ mesh: trimesh.Trimesh | None = None
+ submeshes: list[trimesh.Trimesh] = field(default_factory=list)
visual_origin: np.ndarray = field(default_factory=lambda: np.eye(4))
mesh_file: str | None = None
@@ -199,7 +174,7 @@ class Robot:
return [j for j in self.joints.values() if j.movable]
def independent_joints(self) -> list[Joint]:
- """The degrees of freedom: movable joints that do not follow another one."""
+ """The degrees of freedom."""
return [j for j in self.joints.values() if j.movable and j.mimic is None]
def link_order(self) -> list[str]:
@@ -280,15 +255,13 @@ def _link_from_xml(el: ET.Element, urdf_dir: Path, meshes_dir: Path | None, *, l
if parts:
link.submeshes = parts
merged = parts[0].copy() if len(parts) == 1 else trimesh.util.concatenate(parts)
- # exporters split vertices per normal/uv; merge them back so topology (watertight, islands) is real
merged.merge_vertices(merge_tex=True, merge_norm=True)
link.mesh = merged
return link
def parse_joint(el: ET.Element) -> Joint:
- """One ``<joint>`` element → :class:`Joint` (strict: raises ``UrdfError``). The URDF
- lint calls it too, so every rule it enforces is a lint ERROR before any Blender run."""
+ """Parse one ``<joint>`` element into a :class:`Joint`, raising :class:`UrdfError` on anything unsupported."""
name = el.get("name", "")
jtype = el.get("type", "")
if jtype not in JOINT_TYPES:
@@ -328,14 +301,12 @@ def parse_joint(el: ET.Element) -> Joint:
raise UrdfError(f"joint {name}: <mimic> needs joint=\"<other joint>\"")
mult = _scalar(mim, "multiplier", f"joint {name} <mimic>", 1.0)
off = _scalar(mim, "offset", f"joint {name} <mimic>", 0.0)
- # the multiplier floor is NOT checked here: mimic_issues owns every coupling rule,
- # and a copy at parse time makes the shared one unreachable (review, 2026-09-03)
j.mimic = Mimic(joint=src, multiplier=mult, offset=off)
return j
def _mimic_message(issue: MimicIssue, joints: dict[str, Joint]) -> str:
- """A coupling rule broken by this URDF, in URDF words (rules: contracts.common)."""
+ """Describe a broken ``<mimic>`` coupling rule in URDF words."""
j, t, kind = issue.joint, issue.target, issue.kind
if kind == "immobile":
return f"joint {j}: <mimic> on a {joints[j].type} joint has nothing to follow"
@@ -351,11 +322,7 @@ def _mimic_message(issue: MimicIssue, joints: dict[str, Joint]) -> str:
def load_urdf(urdf_path: Path | str, meshes_dir: Path | str | None = None, *, load_meshes: bool = True) -> Robot:
- """Parse a URDF file into a :class:`Robot` (strict: raises ``UrdfError``).
-
- ``meshes_dir`` overrides where ``<mesh filename>`` basenames are looked up
- (default: relative to the URDF file). Mesh coordinates are taken raw.
- """
+ """Parse a URDF file into a :class:`Robot`, raising :class:`UrdfError` on malformed input."""
urdf_path = Path(urdf_path)
try:
root_el = ET.parse(urdf_path).getroot()
@@ -403,10 +370,7 @@ def load_urdf(urdf_path: Path | str, meshes_dir: Path | str | None = None, *, lo
# ------------------------------------------------------------------ FK
def resolve_q(robot: Robot, q: dict[str, float] | None = None) -> dict[str, float]:
- """``q`` with every mimicking joint's value computed from the joint it follows.
-
- A value given for a driven joint is ignored: the mechanism has one input, and the
- sweep must not be able to pose it out of its own coupling."""
+ """``q`` with every mimicking joint's value computed from the joint it follows."""
out = {k: float(v) for k, v in (q or {}).items()}
for j in robot.joints.values():
if j.mimic is None:
@@ -424,8 +388,7 @@ def resolve_q(robot: Robot, q: dict[str, float] | None = None) -> dict[str, floa
def fk(robot: Robot, q: dict[str, float] | None = None) -> dict[str, np.ndarray]:
- """World transform of every link frame for joint values ``q`` (missing → 0).
- Mimicking joints follow the joint they name, whatever ``q`` says about them."""
+ """World transform of every link frame for joint values ``q`` (missing → 0)."""
q = q or {}
unknown = set(q) - set(robot.joints)
if unknown:
diff --git a/harness/codeverse3d/spatial/joints_poses.py b/harness/codeverse3d/spatial/joints_poses.py
index 46368607..59903f6e 100644
--- a/harness/codeverse3d/spatial/joints_poses.py
+++ b/harness/codeverse3d/spatial/joints_poses.py
@@ -22,12 +22,7 @@ def _joint_values(j: Joint) -> list[float]:
def pose_samples(robot: Robot, n_random: int = 8, seed: int = 0) -> list[dict[str, float]]:
- """Deterministic pose set: rest, each joint at lower/mid/upper (others at 0),
- then ``n_random`` seeded random combinations within limits.
- Continuous joints sample 0, ±π/2, π and random in [-π, π]."""
- # only the degrees of freedom are driven: a mimicking joint follows its source
- # through fk, so sampling it independently would pose a coupled mechanism in a
- # state the mechanism cannot reach
+ """Deterministic pose set."""
movable = robot.independent_joints()
poses: list[dict[str, float]] = [{}]
for j in movable:
@@ -49,7 +44,7 @@ def pose_samples(robot: Robot, n_random: int = 8, seed: int = 0) -> list[dict[st
def pose_label(robot: Robot, q: dict[str, float]) -> str:
- """Short deterministic label: ``rest`` · ``hinge@upper`` · ``hinge=0.52,slide=0.10``."""
+ """Short deterministic label."""
active = {k: v for k, v in q.items() if abs(v) > 1e-12}
if not active:
return "rest"
@@ -67,13 +62,8 @@ def pose_label(robot: Robot, q: dict[str, float]) -> str:
def limit_poses(robot: Robot) -> list[tuple[str, dict[str, float]]]:
- """``rest`` + every INPUT joint at its lower and upper limit (deduped) — the pose set
- behind the articulation contact sheet and ``joint_sweep(joints=...)``.
-
- Independent joints only, for the same reason as :func:`pose_samples`: ``fk`` resolves a
- driven joint from the one it follows and ignores a value handed in for it, so a tile
- labelled ``<driven>@upper`` would render the rest pose under a label that says it moved
- (an 8-rib umbrella: 16 mislabelled duplicates)."""
+ """``rest`` + every INPUT joint at its lower and upper limit (deduped) — the pose set behind
+ the articulation contact sheet and ``joint_sweep(joints=...)``."""
out: list[tuple[str, dict[str, float]]] = [("rest", {})]
for j in robot.independent_joints():
if j.type == "continuous":
diff --git a/harness/codeverse3d/spatial/joints_sweep.py b/harness/codeverse3d/spatial/joints_sweep.py
index fc8a8c0d..5f8cf006 100644
--- a/harness/codeverse3d/spatial/joints_sweep.py
+++ b/harness/codeverse3d/spatial/joints_sweep.py
@@ -1,9 +1,6 @@
-"""Pose sweep QC on a :class:`Robot`: overlaps, contacts, floating links, motion
-direction. Collision bodies live in :mod:`joints_collide` (FCL for the boolean
-collide / distance queries; deterministic per-island containment for the
-penetration depth — FCL's mesh-mesh contact depths are per-triangle artefacts).
-:func:`sweep_gate` is THE ``joint_sweep`` verdict: the round's gate and the tool's.
-"""
+"""Pose sweep QC on a :class:`Robot`: overlaps, contacts, floating links, motion direction.
+
+Collision bodies live in :mod:`joints_collide`."""
from __future__ import annotations
@@ -26,7 +23,6 @@ from codeverse3d.workspace import Workspace
log = logging.getLogger(__name__)
-#: the articulated track's gate id — every finding this module emits carries it
SWEEP_GATE = "joint_sweep"
@@ -41,9 +37,7 @@ class Overlap(BaseModel):
class FloatingLink(BaseModel):
- """A link that is not physically attached to its PARENT link the way its
- joint type requires (fixed → touching; revolute/continuous → hinge edge
- within ``hinge_clearance_m``; prismatic → inserted into / touching the parent)."""
+ """A link that is not attached to its parent link the way its joint type requires."""
link: str
nearest: str = Field(default="", description="the parent link it should attach to")
@@ -84,13 +78,7 @@ class MotionCheck(BaseModel):
observed_dir: tuple[float, float, float]
ok: bool
message: str
- #: how aligned the observed tangent is with the expected direction (dot product)
cos: float = 0.0
- #: an axis that WOULD send positive motion the expected way, computed from the
- #: pivot geometry (revolute: normalize(r x want); prismatic: want) — None when the
- #: lever arm is degenerate. Added 2026-08-31: af_swiss_knife failed this check on
- #: the same joints three rounds straight while the agent guessed; the geometry
- #: admits an exact answer, so the hint should state it.
suggested_axis: tuple[float, float, float] | None = None
@@ -103,17 +91,13 @@ def sweep_collisions(
contact_gap_m: float = CONTACT_GAP_M,
hinge_clearance_m: float = 0.01,
) -> SweepReport:
- """Collide every link pair in every pose. Overlaps deeper than ``tol_m``
- are reported; at the rest pose every link is checked for attachment to its
- PARENT link according to its joint type (``floating`` = not attached)."""
+ """Collide every link pair in every pose."""
names = robot.meshed_links()
if not names:
raise UrdfError("sweep_collisions: robot has no link meshes")
bodies = {n: collide.LinkBody(n, robot.links[n].mesh) for n in names} # type: ignore[arg-type]
per_pose: list[PoseReport] = []
islands = {n: len(bodies[n].islands) for n in names}
- # links joined only by fixed joints never move relative to each other: their overlap is
- # structural and is measured once (at rest when the sweep has a rest pose, else first pose)
comps = collide.components(list(robot.links), {(j.parent, j.child) for j in robot.joints.values() if j.type == "fixed"})
rigid_group = {n: i for i, comp in enumerate(comps) for n in comp}
labels = [pose_label(robot, q) for q in poses]
@@ -137,10 +121,10 @@ def sweep_collisions(
if collide.collide(ba, bb) or (gap_aabb <= 0.0 and collide.contained(ba, bb)):
dist = 0.0
if rigid and idx != rigid_pose:
- pass # structural overlap, already measured in pose ``rigid_pose``
+ pass
else:
depth, approx = collide.penetration(ba, bb)
- if round(depth, 4) > tol_m: # 0.1 mm: float32 mesh coordinates carry no finer meaning
+ if round(depth, 4) > tol_m:
overlaps.append(
Overlap(a=a, b=b, depth_m=round(depth, 6), approx=approx, rigid=rigid)
)
@@ -150,7 +134,7 @@ def sweep_collisions(
if dist <= contact_gap_m:
touching.add((a, b))
floating: list[FloatingLink] = []
- if pose_label(robot, q) == "rest": # attachment is a structural (rest-pose) property
+ if pose_label(robot, q) == "rest":
for n in names:
j = robot.parent_joint(n)
if j is None or j.parent not in bodies:
@@ -160,7 +144,7 @@ def sweep_collisions(
thr = contact_gap_m
elif j.type == "prismatic":
if collide.aabb_gap(bodies[n].aabb, bodies[j.parent].aabb) <= 0.0:
- continue # inserted into the parent's envelope (drawer in cavity)
+ continue
thr = hinge_clearance_m
else: # revolute / continuous / planar / floating
thr = hinge_clearance_m
@@ -181,7 +165,7 @@ def _summarise(per_pose: list[PoseReport], n_links: int, islands: dict[str, int]
for o in pr.overlaps:
if o.depth_m > s.max_penetration_m:
s.max_penetration_m, s.worst_pose = o.depth_m, pr.label
- if pr.label == "rest" or o.rigid: # structural overlaps count as rest penetration
+ if pr.label == "rest" or o.rigid:
s.rest_max_penetration_m = max(s.rest_max_penetration_m, o.depth_m)
if pr.overlaps:
s.overlapping_poses.append(pr.label)
@@ -194,13 +178,12 @@ def _summarise(per_pose: list[PoseReport], n_links: int, islands: dict[str, int]
# ------------------------------------------------------------------ gate findings
def sweep_findings(report: SweepReport, *, rest_max_m: float = 0.005, hinge_clearance_m: float = 0.01) -> list[GateFinding]:
- """Turn a sweep report into gate findings (ERROR for rest penetration > ``rest_max_m``,
- overlaps in moved poses and floating links beyond ``hinge_clearance_m``; WARN otherwise)."""
+ """Turn a sweep report into gate findings: rest penetration beyond ``rest_max_m``, moved-pose overlaps, and floating links beyond ``hinge_clearance_m``."""
gate = SWEEP_GATE
out: list[GateFinding] = []
for pr in report.per_pose:
for o in pr.overlaps:
- at_rest = pr.label == "rest" or o.rigid # a weld between rigidly joined links is a rest-pose property
+ at_rest = pr.label == "rest" or o.rigid
sev = Severity.ERROR if (not at_rest or o.depth_m > rest_max_m) else Severity.WARN
out.append(GateFinding(
gate=gate, severity=sev, target=f"{o.a}|{o.b}",
@@ -229,19 +212,11 @@ def sweep_findings(report: SweepReport, *, rest_max_m: float = 0.005, hinge_clea
return out
-#: ERROR findings kept after aggregation (the deepest pairs); the rest fold into one WARN
MAX_PAIR_FINDINGS = 8
def aggregate_findings(findings: list[GateFinding]) -> list[GateFinding]:
- """One finding per link pair (or per floating link), the worst pose first.
-
- compare_art_v3 (2026-08-28): a run produced 59 penetration findings for a handful of
- pairs — one per sampled pose — and the refine prompt carried them as 59 lines the
- agent could not act on; the loop burnt its budget without converging. Merge the
- poses of a pair into one line that says how many poses, the worst depth and where,
- keep the deepest ``MAX_PAIR_FINDINGS`` as ERRORs and summarise the remainder.
- """
+ """One finding per link pair (or per floating link), the worst pose first."""
groups: dict[tuple[str, str | None], list[GateFinding]] = {}
order: list[tuple[str, str | None]] = []
for f in findings:
@@ -280,14 +255,13 @@ def aggregate_findings(findings: list[GateFinding]) -> list[GateFinding]:
return errors + warns
-#: share of a link's sampled surface that must lie inside ONE other link to call it buried
BURIED_FRACTION = 0.98
BURIED_SAMPLES = 200
def _inside_fraction(body: Any, points_world: np.ndarray) -> float:
- """Share of ``points_world`` inside any of ``body``'s islands (these LinkBodies are
- built from world meshes, so the pose transform is the identity)."""
+ """Share of ``points_world`` inside any of ``body``'s islands (these LinkBodies are built
+ from world meshes, so the pose transform is the identity)."""
local = trimesh.transform_points(points_world, body.T_inv)
mask = np.zeros(len(local), dtype=bool)
for isl in body.islands:
@@ -296,11 +270,7 @@ def _inside_fraction(body: Any, points_world: np.ndarray) -> float:
def buried_links(robot: Robot, *, samples: int = BURIED_SAMPLES, fraction: float = BURIED_FRACTION) -> list[GateFinding]:
- """Links whose surface lies (almost) entirely inside another link at rest — the part
- can neither be seen nor move (compare_art_v4: a clamp's swivel pad was generated
- inside the jaw and the judge reported it missing). Uses the sweep's own
- :class:`LinkBody` island containment, so this check and the collision sweep agree
- about what "inside" means; works on the open meshes agents actually export."""
+ """Findings for links whose surface lies (almost) entirely inside another link at rest, so the part can neither be seen nor move."""
meshes = link_world_meshes(robot, {})
bodies = {n: collide.LinkBody(n, m) for n, m in meshes.items() if not m.is_empty and m.area > 0}
out: list[GateFinding] = []
@@ -331,26 +301,13 @@ def buried_links(robot: Robot, *, samples: int = BURIED_SAMPLES, fraction: float
# ------------------------------------------------------------------ the gate
def find_urdf(ws: Workspace) -> Path | None:
- """The BUILT ``artifacts/robot.urdf`` — or None, which means "run build first".
-
- Only the build's copy pairs with ``artifacts/meshes`` (a failed build invalidates both).
- The authored ``src/robot.urdf`` was a fallback until 2026-09-23: the round never reached
- it (its gates run on a green build only), and the tool refused before it; what it could
- do was sweep an edited URDF against the last build's meshes (review 2 C5)."""
+ """The BUILT ``artifacts/robot.urdf`` — or None, which means "run build first"."""
urdf = ws.artifacts / "robot.urdf"
return urdf if urdf.is_file() else None
def sweep_gate(ws: Workspace) -> tuple[GateReport, Robot | None]:
- """THE ``joint_sweep`` verdict on the built robot, and the robot (None when none loaded).
-
- Every pose of :func:`pose_samples` collided, the findings one per link pair
- (:func:`aggregate_findings`, D50), plus :func:`buried_links`. The round's gate
- (``tracks/articulated_object.default_joint_sweep``, which adds the pose renders) and
- the ``joint_sweep`` tool both report exactly this, so the agent's check and the
- round's can no longer disagree (until 2026-09-22 the tool failed any overlap past
- 2 mm and any gap, the gate had a 5 mm rest / 30 mm hinge WARN band and buried links).
- """
+ """THE ``joint_sweep`` verdict on the built robot, and the robot (None when none loaded)."""
urdf = find_urdf(ws)
if urdf is None:
return GateReport.of(SWEEP_GATE, [GateFinding(
@@ -382,8 +339,7 @@ _DIRS: dict[str, tuple[float, float, float]] = {
def motion_direction_check(robot: Robot, joint: str, expected: str, *, probe: float | None = None) -> MotionCheck:
"""Does the child's centroid move along ``expected`` (``'+z'``, ``'-y'``, ``'up'``,
- ``'front'``, ``'open_up'`` ...) when ``joint`` moves positively from rest?
- Revolute joints are probed with a small angle so the initial tangent direction is tested."""
+ ``'front'``, ``'open_up'`` ...) when ``joint`` moves positively from rest? Revolute joints"""
key = expected.strip().lower()
if key not in _DIRS:
raise UrdfError(f"motion_direction_check: unknown direction {expected!r}; use one of {sorted(_DIRS)}")
@@ -391,7 +347,7 @@ def motion_direction_check(robot: Robot, joint: str, expected: str, *, probe: fl
if j is None or not j.movable:
raise UrdfError(f"motion_direction_check: {joint!r} is not a movable joint")
driven_by = None
- if j.mimic is not None: # a driven joint has no input of its own: probe what drives it
+ if j.mimic is not None:
driven_by = j
while driven_by.mimic is not None:
driven_by = robot.joints[driven_by.mimic.joint]
@@ -416,12 +372,7 @@ def motion_direction_check(robot: Robot, joint: str, expected: str, *, probe: fl
ok = cos > 0.5
suggested = None
if not ok:
- # ``want``/``s`` are WORLD vectors, but URDF <axis> lives in the JOINT frame
- # (fk composes parent @ origin @ motion(q), so the axis acts after origin) —
- # express the suggestion there, or a rotated origin / rotated ancestor chain
- # makes the "exact" repair install a provably wrong axis (repro: a hinge with
- # rpy="0 0 1.57" kept its motion ERROR after installing the world-frame value).
- R_joint = fk(robot, {})[j.child][:3, :3] # motion(0) = I, so this is rot(parent @ origin)
+ R_joint = fk(robot, {})[j.child][:3, :3]
if j.type == "prismatic":
suggested = tuple(round(float(v), 3) for v in R_joint.T @ want)
else:
diff --git a/harness/codeverse3d/spatial/mcp_server.py b/harness/codeverse3d/spatial/mcp_server.py
index c1e9f6b5..0021399c 100644
--- a/harness/codeverse3d/spatial/mcp_server.py
+++ b/harness/codeverse3d/spatial/mcp_server.py
@@ -2,17 +2,7 @@
python -m codeverse3d.spatial.mcp_server --workspace <ws> [--track X] [--language Y] [--round N]
-One MCP tool per registry tool (name, description, JSON schema from
-``ToolDef.schema()``). Results are content blocks: one ``TextContent`` with the
-observation text (+ compact numbers when small) and one ``ImageContent`` per
-observation image (base64 PNG, long side ≤ 1024 px, at most ``MAX_IMAGES``).
-``is_error`` is ``Observation.failed`` (the tool could not run) — never a
-negative verdict, which is an ordinary result whose text leads with FAIL.
-Every result is bounded here — ``MAX_TEXT_CHARS`` of text, at most
-:func:`max_images_for` images, and ``MAX_IMAGE_BYTES`` of encoded image data across
-them — because this is the last place the harness owns before the payload becomes
-the vendor's prompt.
-Track / language default to ``<ws>/spec.json`` so agents need no flags.
+One MCP tool per registry tool; a result is one bounded text block plus bounded base64 PNG images. ``is_error`` means the tool could not run, never a FAIL verdict. Track / language default to ``<ws>/spec.json``.
"""
from __future__ import annotations
@@ -36,19 +26,11 @@ from codeverse3d.workspace import Workspace
MAX_IMAGES = 4
MAX_IMAGE_SIDE = 1024
MAX_NUMBERS_CHARS = 1200
-#: hard ceiling on the text block of ONE result (text + numbers), twice the largest
-#: per-tool limit in ``observe`` — an Observation built by hand (``joint_sweep``,
-#: ``compare_reference``) never goes through those, and nothing may hand the model an
-#: unbounded payload from here.
+#: ceiling on the text block of one result (text + numbers)
MAX_TEXT_CHARS = 6000
-#: ceiling on the encoded image data of ONE result. The count and the 1024 px long side
-#: bound pixels, not bytes: the largest recorded articulation sheet (1,966,609 B,
-#: 1176x3350) still encodes to 394,988 base64 characters after the downscale, so without
-#: this a legal result could hand the model ~280 k tokens of image. That leaves only ~1 %
-#: of headroom, so a slightly taller sheet is DOWNSCALED to fit rather than dropped
-#: (``_fit_first``): shipping no picture at all is the worse failure.
+#: ceiling on the encoded image bytes of one result; an over-budget sheet is downscaled, not dropped
MAX_IMAGE_BYTES = 400_000
-#: long sides tried, in order, when the first image does not fit the byte bound
+#: long sides tried when the first image does not fit
IMAGE_FALLBACK_SIDES = (768, 512, 384)
SERVER_NAME = "3dcode"
@@ -78,25 +60,14 @@ def encode_image(path: str, max_side: int = MAX_IMAGE_SIDE) -> str | None:
def max_images_for(obs: Observation) -> int:
- """Image budget for ONE result, by outcome: none for a call that failed, one for a
- FAIL verdict, ``MAX_IMAGES`` for a pass.
-
- A failed call ships none because the vendor CLI stringifies an ``is_error`` result
- whole, base64 included — 275 kB of contact sheet arrives as ~261 k prompt tokens of
- text (docs/COST.md §30, which also has the one-image rule's reasoning).
- """
+ """Image budget: none for a failed call (vendor CLIs stringify ``is_error`` results, base64 included), one for FAIL, ``MAX_IMAGES`` for a pass."""
if obs.failed:
return 0
return MAX_IMAGES if obs.ok else 1
def _fit_first(path: str, budget: int) -> tuple[str | None, int]:
- """The first image, re-encoded smaller until it fits ``budget``.
-
- Returns ``(base64, long side used)`` or ``(None, 0)``. ``images[0]`` is the contact
- sheet — the one picture the round is about — and the byte bound has ~1 % of headroom
- over the largest recorded sheet, so "over budget" means "a bit taller than last time",
- not "unreasonable"."""
+ """The first image (the contact sheet), re-encoded smaller until it fits ``budget``: ``(base64, long side)`` or ``(None, 0)``."""
b64 = encode_image(path)
if b64 is not None and len(b64) <= budget:
return b64, MAX_IMAGE_SIDE
@@ -108,21 +79,17 @@ def _fit_first(path: str, budget: int) -> tuple[str | None, int]:
def observation_content(obs: Observation) -> list[Any]:
- """Observation → MCP content blocks (text first, then images), both bounded."""
+ """Observation → bounded MCP content blocks (text first, then images)."""
from mcp import types
text = obs.text
if obs.numbers:
nums = json.dumps(obs.numbers, default=str)
text += "\n" + (nums if len(nums) <= MAX_NUMBERS_CHARS else fmt_numbers(obs.numbers))
- # 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 prompt
+ # the slice makes the ceiling hard: truncate's omitted-marker overshoots its budget
blocks: list[Any] = [types.TextContent(type="text", text=truncate(text, MAX_TEXT_CHARS)[:MAX_TEXT_CHARS])]
- # 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 that
- # silently shipped no picture is the case this guards.
+ # images[0] is the contact sheet; later images repeat it per view, so the budget stops at
+ # the first that does not fit. Dropped images are always said in the text.
wanted = obs.images[:max_images_for(obs)]
kept, spent, dropped, shrunk = [], 0, 0, 0
for i, p in enumerate(wanted):
@@ -146,8 +113,7 @@ def observation_content(obs: Observation) -> list[Any]:
notes.append(f"[{dropped} image(s) not attached: over the {MAX_IMAGE_BYTES}-byte "
"payload bound or unreadable; the files are in the workspace]")
if notes:
- # inside the ceiling, not appended past it: this is the last bound before the
- # vendor's prompt, so the note takes room from the body rather than adding to it
+ # the note takes room from the body so the text ceiling holds
tail = "\n" + "\n".join(notes)
body = blocks[0].text[:max(0, MAX_TEXT_CHARS - len(tail))]
blocks[0] = types.TextContent(type="text", text=body + tail)
@@ -157,15 +123,7 @@ def observation_content(obs: Observation) -> list[Any]:
async def call_tool(ctx: ToolContext, defs: dict[str, Any], params: Any) -> Any:
- """One MCP tool call → a ``CallToolResult``.
-
- Module level, not a closure inside :func:`make_server`, so the coupling below can be
- driven by a test instead of grepped for: ``is_error`` is ``Observation.failed``, NOT
- ``not ok``. A tool that RAN and answered FAIL is a result the model must read; an MCP
- error is a call the vendor retries instead (a mean 119k prompt tokens, $0.030 blended)
- — and, on gemini-cli, one whose images it re-sends as base64 TEXT. The FAIL verdict
- leads the text.
- """
+ """One MCP tool call → ``CallToolResult``; ``is_error`` is ``Observation.failed``, not ``not ok`` (vendors retry MCP errors)."""
from mcp import types
tdef = defs.get(params.name)
diff --git a/harness/codeverse3d/spatial/measure.py b/harness/codeverse3d/spatial/measure.py
index ca56e79a..5a25ace5 100644
--- a/harness/codeverse3d/spatial/measure.py
+++ b/harness/codeverse3d/spatial/measure.py
@@ -1,21 +1,4 @@
-"""Measure the canonical GLB (Y-up, meters, one named top-level node per part).
-
-``measure_glb`` turns a GLB into a :class:`Measurement` (bbox, extents, per-part
-rows, islands, ground gap, footprint offset, materials). Degenerate input
-(empty meshes, parts without geometry) becomes findings in ``Measurement.extra``
-— never an exception — so agents see *what* is wrong instead of a traceback.
-
-``part_meshes`` is the shared loader other spatial modules use: it returns one
-world-space ``trimesh.Trimesh`` per top-level node (all child meshes merged).
-``cached_parts`` is the memoized front door for gates that re-read the same
-GLB (keyed on path + size + mtime_ns; ``load_scene`` itself is never cached —
-a caller mutating a scene), and ``solid_parts`` is that front door minus the
-empty parts — what connectivity / sections want.
-
-``Measurement.extra["complexity"]`` carries the objective complexity vector
-(``spatial/complexity.py``) alongside the census — additive, best-effort, and
-never a reason for a measurement to fail.
-"""
+"""Measure the canonical GLB (Y-up, meters, one named top-level node per part)."""
from __future__ import annotations
@@ -80,18 +63,7 @@ def gltf_node_names(glb: Path | str) -> list[str | None]:
def node_name_findings(glb: Path | str) -> list[str]:
- """Findings for a GLB whose node names trimesh cannot key on.
-
- trimesh names graph nodes by their glTF ``name`` and de-duplicates collisions, and
- on THREE.GLTFExporter files with repeated / missing names (the brilliana gallery's
- desk-lamp-q2: 21 unnamed, 'Arm' x2, 'Shade' x2, 'Rivet' x4) that walk went wrong in
- two ways at once — the root ``pivot`` matrix was dropped from its descendants and a
- renamed 'Arm' was re-parented to the world, so an upright lamp measured as lying on
- its side with a part 28 mm under the floor (2026-08-30). The harness's own exporters
- name every node uniquely (blender, cadquery, and export_glb.mjs bake instances to
- ``<Name>_<i>``: 0 of 14 recorded threejs GLBs differ from the naive bounds), so this
- fires on foreign files and on an agent that reused a name — either way the numbers
- downstream are approximate and the reader is told."""
+ """Findings for a GLB whose node names trimesh cannot key on."""
names = gltf_node_names(glb)
if not names:
return []
@@ -109,8 +81,7 @@ def node_name_findings(glb: Path | str) -> list[str]:
def _subtree_nodes(scene: trimesh.Scene, root: str) -> list[str]:
- """All nodes under ``root`` (inclusive), depth first; cycle-safe (a malformed
- graph, e.g. a node named like the base frame, must not hang the gate)."""
+ """All nodes under ``root`` (inclusive), depth first."""
children = scene.graph.transforms.children
out, stack, seen = [], [root], set()
while stack:
@@ -124,16 +95,7 @@ def _subtree_nodes(scene: trimesh.Scene, root: str) -> list[str]:
def world_transform(scene: trimesh.Scene, node: str) -> np.ndarray:
- """``node``'s world matrix, composed by walking the edge matrices up to the base frame.
-
- Not ``scene.graph.get(node)``: trimesh 4.12 leaves the SCENE-ROOT node's own matrix out
- of its descendants' world transforms. A GLB whose root node carries the Z-up→Y-up
- rotation — what THREE.GLTFExporter writes for a Z-up scene (``pivot``, the brilliana
- gallery) — therefore measured as lying on its side: desk-lamp-q2 bounds y ∈ [−0.12, 0.12],
- z ∈ [0, 0.45] from trimesh against y ∈ [0, 0.45] from the node walk and from the render
- rig (2026-08-30). Every gate downstream — bbox, ground gap, floating, orientation —
- read that wrong pose, and the judge read the gate text. Cycle-safe (a malformed graph
- must not hang the gate)."""
+ """``node``'s world matrix, composed by walking the edge matrices up to the base frame."""
edges = scene.graph.transforms.edge_data
parents = scene.graph.transforms.parents
m = np.eye(4)
@@ -162,8 +124,6 @@ def _world_mesh(scene: trimesh.Scene, node: str) -> trimesh.Trimesh | None:
return None
m = geom.copy()
m.apply_transform(transform)
- # exporters split vertices along hard edges / UV seams; topology queries
- # (islands, watertightness) need positions merged back together
with contextlib.suppress(Exception):
m.merge_vertices(merge_tex=True, merge_norm=True)
return m
@@ -181,9 +141,8 @@ def _node_has_geometry(scene: trimesh.Scene, node: str) -> bool:
def effective_top_nodes(scene: trimesh.Scene) -> list[str]:
- """Direct children of the scene root, descending through single wrapper
- nodes that carry no geometry themselves (a three.js root Group, a URDF
- ``<robot>`` node) so that parts are found at the first meaningful level."""
+ """Direct children of the scene root, descending through single wrapper nodes that carry no
+ geometry themselves (a three.js root Group, a URDF ``<robot>`` node) so that parts are"""
tops = _children(scene, scene.graph.base_frame)
seen = 0
while len(tops) == 1 and not _node_has_geometry(scene, tops[0]) and _children(scene, tops[0]) and seen < 4:
@@ -193,15 +152,7 @@ def effective_top_nodes(scene: trimesh.Scene) -> list[str]:
def part_meshes(scene: trimesh.Scene) -> OrderedDict[str, trimesh.Trimesh | None]:
- """One world-space mesh per part, in scene order.
-
- Flat scenes: a part is an effective top-level node (see
- :func:`effective_top_nodes`) and its whole subtree is merged.
- Hierarchical link exports (scene ``metadata['links']`` present, as written
- by ``spatial.joints_export``): every link node is its own part; only its
- own geometry (the node itself or ``<link>__<i>`` pieces) is merged, child
- links stay separate. A part with no geometry maps to ``None``.
- """
+ """One world-space mesh per part, in scene order."""
out: OrderedDict[str, trimesh.Trimesh | None] = OrderedDict()
links = scene.metadata.get("links") if isinstance(scene.metadata, dict) else None
nodes = set(scene.graph.nodes)
@@ -216,13 +167,12 @@ def part_meshes(scene: trimesh.Scene) -> OrderedDict[str, trimesh.Trimesh | None
for top in tops:
meshes = [m for n in _subtree_nodes(scene, top) if (m := _world_mesh(scene, n)) is not None]
name = str(top)
- if name in out: # duplicate node names: suffix so nothing is silently merged
+ if name in out:
k = 2
while f"{name}~{k}" in out:
k += 1
name = f"{name}~{k}"
out[name] = trimesh.util.concatenate(meshes) if meshes else None
- # geometry that hangs directly on the root (no named node) — keep it visible
if not tops and scene.geometry:
for gname, geom in scene.geometry.items():
if isinstance(geom, trimesh.Trimesh) and len(geom.faces):
@@ -231,7 +181,6 @@ def part_meshes(scene: trimesh.Scene) -> OrderedDict[str, trimesh.Trimesh | None
# --------------------------------------------------------------------- parse memo
-#: LRU entries: parsed parts + finished Measurement for one (path, size, mtime_ns)
_LRU_MAX = 4
_lru_lock = threading.Lock()
@@ -255,7 +204,7 @@ def _stat_key(p: Path) -> tuple[str, int, int] | None:
def _cache_entry(key: tuple[str, int, int]) -> _CacheEntry:
- """The (possibly fresh) LRU entry for ``key``; evicts the oldest past ``_LRU_MAX``."""
+ """The (possibly fresh) LRU entry for ``key``."""
with _lru_lock:
e = _lru.get(key)
if e is None:
@@ -267,12 +216,7 @@ def _cache_entry(key: tuple[str, int, int]) -> _CacheEntry:
def cached_parts(glb: Path | str) -> OrderedDict[str, trimesh.Trimesh | None]:
- """``part_meshes(load_scene(glb))`` memoized on the file's stat (LRU of 4).
-
- Rewriting the file (new size or mtime_ns) invalidates the entry. The
- returned dict is a fresh copy per call, but the meshes are SHARED between
- callers — treat them as read-only (copy before transforming).
- """
+ """``part_meshes(load_scene(glb))`` memoized on the file's stat (LRU of 4)."""
p = Path(glb)
key = _stat_key(p)
if key is None:
@@ -284,9 +228,8 @@ def cached_parts(glb: Path | str) -> OrderedDict[str, trimesh.Trimesh | None]:
def solid_parts(glb: Path | str) -> OrderedDict[str, trimesh.Trimesh]:
- """:func:`cached_parts` without the empty ones — the loader every geometry
- gate (connectivity, sections) starts from: one world-space mesh per part,
- only parts that actually have faces. Meshes are SHARED (read-only)."""
+ """:func:`cached_parts` without the empty ones — the loader every geometry gate
+ (connectivity, sections) starts from."""
return OrderedDict((k, v) for k, v in cached_parts(glb).items() if v is not None and len(v.faces))
@@ -331,13 +274,7 @@ def _measure_part(name: str, mesh: trimesh.Trimesh) -> PartMeasure:
def measure_glb(glb: Path | str) -> Measurement:
- """Compute the language-agnostic census of the canonical GLB.
-
- Raises :class:`GlbLoadError` only when the file is unreadable; an empty or
- degenerate model yields a zero-extent ``Measurement`` with findings in
- ``extra["findings"]``. Memoized on the file's stat (same LRU as
- :func:`cached_parts`); every call returns its own deep copy.
- """
+ """Compute the language-agnostic census of the canonical GLB."""
p = Path(glb)
key = _stat_key(p)
entry = _cache_entry(key) if key is not None else None
@@ -357,9 +294,7 @@ def measure_glb(glb: Path | str) -> Measurement:
def _complexity_extra(
scene: trimesh.Scene, parts: OrderedDict[str, trimesh.Trimesh | None], materials: int
) -> dict[str, Any] | None:
- """The complexity vector as a plain dict, or ``None`` when it cannot be
- computed. Additive by contract: measuring must never fail because an
- artifact defeats one complexity axis."""
+ """The complexity vector as a plain dict, or ``None`` when it cannot be computed."""
from codeverse3d.spatial.complexity import complexity_of_parts
try:
@@ -423,39 +358,30 @@ def _measure(scene: trimesh.Scene, parts: OrderedDict[str, trimesh.Trimesh | Non
# --------------------------------------------------------------------------- table
def instance_groups(names: list[str]) -> OrderedDict[str, list[str]]:
- """Group ``Leg_0, Leg_1, Leg_2`` → ``{"Leg": [...]}``; singletons keep their name."""
+ """Group instance names such as ``Leg_0, Leg_1, Leg_2`` under their shared base name ``Leg``."""
groups: OrderedDict[str, list[str]] = OrderedDict()
for n in names:
groups.setdefault(split_instance(n)[0], []).append(n)
- # a "group" with a single member is just the part itself
out: OrderedDict[str, list[str]] = OrderedDict()
for key, members in groups.items():
if len(members) > 1:
- # a bare base name ("lens" beside "lens_1") lands in the group with no
- # index — sort it first
members = sorted(members, key=lambda n: int(split_instance(n)[1] or -1))
out[key if len(members) > 1 else members[0]] = members
return out
def fmt_extent_cm(ext: Any) -> str:
- """``34.0×47.0×34.0`` — a size in centimetres. THE extent formatter (measure
- table, contract gate) so every prompt/finding states sizes the same way."""
+ """``34.0×47.0×34.0`` — a size in centimetres."""
return "×".join(f"{float(v) * 100:.1f}" for v in ext)
def fmt_vec(v: Any, digits: int = 3) -> str:
- """``(+0.010, -0.000, +0.250)`` — a signed metre vector. THE vector formatter
- for gate hints (``+ 0.0`` keeps a rounded zero from printing as ``-0.000``)."""
+ """``(+0.010, -0.000, +0.250)`` — a signed metre vector."""
return "(" + ", ".join(f"{round(float(x), digits) + 0.0:+.{digits}f}" for x in v) + ")"
def measure_summary_table(m: Measurement, max_rows: int = 30) -> str:
- """Compact markdown table for prompts (judge/agent): totals + per-part rows.
-
- Instances (``Leg_0..3``) collapse to one row with their union bbox; rows are
- capped at ``max_rows`` (largest parts first, then an "… n more" line).
- """
+ """Compact markdown table for prompts (judge/agent)."""
lines = [
f"overall: {fmt_extent_cm(m.extents)} cm (W×H×D, Y-up) · centre ({m.center[0]:.3f}, {m.center[1]:.3f}, {m.center[2]:.3f}) m"
f" · {m.tri_count} tris · {len(m.parts)} parts · {m.n_islands} islands"
diff --git a/harness/codeverse3d/spatial/node.py b/harness/codeverse3d/spatial/node.py
index 8a708d69..7c22dc2c 100644
--- a/harness/codeverse3d/spatial/node.py
+++ b/harness/codeverse3d/spatial/node.py
@@ -1,11 +1,6 @@
-"""Run harness-owned node scripts (``runtime_js/*.mjs``) as subprocesses.
-
-All node work in the harness goes through :func:`run_node`: it sets
-``NODE_PATH`` to ``runtime_js/node_modules`` (CommonJS resolution), optionally
-adds the ESM ``--import`` hook that lets agent code outside ``runtime_js``
-import ``three`` / ``three/addons/*``, enforces a timeout, kills the whole
-process group on expiry and parses the *last JSON line* of stdout (the
-convention every runtime_js script follows).
+"""Run harness-owned node scripts (``runtime_js/*.mjs``) as subprocesses via :func:`run_node`.
+
+It sets ``NODE_PATH``, optionally the ``three`` import hook, enforces a timeout and parses the last JSON line of stdout.
"""
from __future__ import annotations
@@ -25,13 +20,7 @@ from codeverse3d.proc import run_subprocess, scrub_secrets, version_line
TAIL_CHARS = 4000
-#: Oldest node the harness runs on — the single source of truth for the floor.
-#: 20.6.0 is what ``node --import`` needs (``run_node(three_hook=True)``, the only
-#: way agent code outside runtime_js can ``import 'three'``); everything else the
-#: harness and ``runtime_js`` use is older (``node:util.parseArgs`` 18.3), and the
-#: npm dependencies bottom out at node 18. ``runtime_js/package.json``'s
-#: ``engines.node`` restates this for npm and is pinned to it by
-#: ``tests/core/test_portability.py``.
+#: Oldest supported node (``--import`` hooks); ``runtime_js/package.json`` engines mirrors it.
NODE_MIN: tuple[int, int, int] = (20, 6, 0)
NODE_MIN_STR = ".".join(str(n) for n in NODE_MIN)
@@ -39,11 +28,7 @@ _VERSION_RE = re.compile(r"v?(\d+)\.(\d+)\.(\d+)")
class NodeError(RuntimeError):
- """A node script failed (non-zero exit, timeout or missing binary).
-
- ``result`` carries whatever was captured so callers can turn it into a
- ``BuildResult`` / ``GateReport`` without losing the tail.
- """
+ """A node script failed (non-zero exit, timeout or missing binary); ``result`` holds what was captured."""
def __init__(self, message: str, result: NodeResult | None = None):
super().__init__(message)
@@ -73,13 +58,7 @@ class NodeResult:
return self.stderr[-TAIL_CHARS:]
-#: A render failure that is the BOX, not the scene: the browser or the page died
-#: under the driver — the renderer process crashed, the tab was reaped under memory
-#: pressure, the shared browser was retired mid-call. The same workspace renders on
-#: the next attempt, so one retry is worth its wall clock. Measured 2026-09-05: four
-#: cells of the `scenes_v1` baseline lost every render — and with it the judge, after
-#: the models had already been paid for — to "Attempted to use detached Frame" while
-#: the box sat at load 93 with swap full.
+#: Signs that the browser or page died under the driver (the box, not the scene).
BROWSER_LOST_MARKERS = (
"detached frame",
"target closed",
@@ -90,10 +69,7 @@ BROWSER_LOST_MARKERS = (
"connection closed",
)
-#: Render failures that are the box, not the model — worth exactly one more attempt. One
-#: tuple for both render paths: `render.py` had it since 2026-08-28, the scene drivers
-#: retried only the browser-loss half and lost 14 renders to "Waiting failed: 60000ms
-#: exceeded" under contention on 2026-09-07 (all green when re-run alone).
+#: Render failures of the box rather than the model; worth one more attempt.
TRANSIENT_MARKERS = ("waiting failed", "timed out", "timeout", "produced no result", *BROWSER_LOST_MARKERS)
@@ -103,8 +79,7 @@ def transient_failure(text: object) -> bool:
return any(marker in lowered for marker in TRANSIENT_MARKERS)
-#: Env for a retry after a browser loss: take an OWNED browser, because the shared
-#: one advertised in the cache is the suspect (`runtime_js/gpu_launch.cjs`).
+#: Retry env after a browser loss: use an owned browser, the shared one is the suspect.
OWN_BROWSER_ENV: dict[str, str] = {"C3D_BROWSER_REUSE": "off"}
@@ -167,20 +142,13 @@ def parse_node_version(text: str) -> tuple[int, int, int] | None:
@lru_cache(maxsize=8)
def node_version(node_bin: str) -> tuple[int, int, int] | None:
- """``node --version`` for ``node_bin``, or None when it cannot be asked.
-
- Cached per binary: this runs at most once per interpreter per node path.
- """
+ """``node --version`` for ``node_bin``, or None when it cannot be asked (cached)."""
rc, line = version_line([node_bin, "--version"], timeout=20)
return parse_node_version(line) if rc == 0 else None
def node_version_error(version: tuple[int, int, int] | None) -> str:
- """The actionable message for a too-old ``version``, or ``""`` when it is fine.
-
- Unknown versions pass: a node we could not interrogate fails later with its
- own error, and guessing here would break more than it protects.
- """
+ """The actionable message for a too-old ``version``, or ``""``; unknown versions pass."""
if version is None or version >= NODE_MIN:
return ""
got = ".".join(str(n) for n in version)
@@ -209,14 +177,9 @@ def run_node(
mem_limit_gb: float | None = None,
check: bool = True,
) -> NodeResult:
- """Run ``node [node_args] script [args]`` and return a :class:`NodeResult`.
-
- * ``three_hook=True`` adds ``--import runtime_js/lib/resolve_three.mjs`` so the
- script (and anything it imports, e.g. agent code) can ``import 'three'``.
- * On timeout the process group is killed and ``NodeError`` is raised.
- * With ``check=True`` (default) a non-zero exit raises ``NodeError`` whose
- ``.result`` has the tails and ``last_json`` (a structured error record when
- the script emitted one).
+ """Run ``node [node_args] script [args]``; ``three_hook`` lets the script ``import 'three'``.
+
+ Timeout, or non-zero exit with ``check``, raises ``NodeError`` carrying the tails.
"""
settings = get_settings()
node_bin = settings.binaries.node
@@ -229,8 +192,7 @@ def run_node(
cmd += ["--import", str(three_import_hook())]
cmd += [str(script), *(args or [])]
- # node runs harness drivers AND model-generated code (scene.js, agent modules):
- # credential-shaped vars are stripped; env_extra (harness-owned) is applied after.
+ # node runs model-generated code: credential-shaped vars are stripped; env_extra applies after.
env = scrub_secrets(dict(os.environ))
env["NODE_PATH"] = str(node_modules_dir())
env.setdefault("C3D_CACHE_DIR", str(settings.cache_dir))
diff --git a/harness/codeverse3d/spatial/observe.py b/harness/codeverse3d/spatial/observe.py
index 05a8691c..59c0e54c 100644
--- a/harness/codeverse3d/spatial/observe.py
+++ b/harness/codeverse3d/spatial/observe.py
@@ -1,13 +1,5 @@
-"""Helpers that keep tool Observations compact and workspace-safe.
-
-* ``fmt_numbers`` – one-line ``k=v`` rendering with sane float precision.
-* ``truncate`` – head/tail truncation with a marker (never mid-line when possible).
-* ``rel_path`` – workspace-relative display path (never leak host paths in text).
-* ``lint_lines`` / ``build_failure_lines`` – the one lint / BUILD FAILED report
- format shared by the ``build`` and ``gl_probe`` / ``gl_frames`` tools.
-* ``text_observation`` / ``gate_observation`` / ``render_observation`` – the
- standard Observation builders (truncation applied once).
-"""
+"""Helpers that keep tool Observations compact and workspace-safe: number/path formatting,
+truncation, the shared lint / BUILD FAILED report, and the standard Observation builders."""
from __future__ import annotations
@@ -95,15 +87,7 @@ def text_observation(
images: Sequence[str | Path] = (),
limit: int = MAX_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, …)
- goes through here so truncation and the image budget are applied exactly once, in
- one place. ``ok=False`` is a verdict (LINT/BUILD
- FAILED is the answer, and the text says so first); ``failed`` is only for a
- tool that could not run.
- """
+ """Observation from text lines, truncated to ``limit``. ``ok=False`` is a verdict; ``failed`` means the tool 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=[str(i) for i in images if i])
@@ -116,8 +100,7 @@ _SEV_TAG = {Severity.ERROR: "ERROR", Severity.WARN: "WARN", Severity.INFO: "info
# --------------------------------------------------------------------------- build reports
def lint_lines(report: GateReport, root: Path, *, errors_only: bool) -> list[str]:
- """``- ERROR (src/x.py): msg`` (+ `` fix: …``) for the errors or the warnings
- of a lint report — INFO findings are never shown to the agent."""
+ """``- ERROR (src/x.py): msg`` (+ fix hint) lines for the errors or the warnings; INFO is never shown."""
want = Severity.ERROR if errors_only else Severity.WARN
out = []
for f in report.findings:
@@ -131,20 +114,16 @@ def lint_lines(report: GateReport, root: Path, *, errors_only: bool) -> list[str
def error_file_display(error_file: str, root: Path) -> str:
- """``BuildResult.error_file`` for the agent: runtimes report either an absolute
- path (→ workspace-relative) or an already-relative one (kept — ``rel_path``
- would resolve it against the cwd and fall back to the bare file name)."""
+ """``error_file`` for the agent: absolute paths become workspace-relative, relative ones are kept."""
if not error_file or not Path(error_file).is_absolute():
return error_file
return rel_path(error_file, root)
def build_failure_lines(br: BuildResult, root: Path, lint_warns: Sequence[str], *, tail_n: int) -> list[str]:
- """``BUILD FAILED: <type>: <message> at <file>:<line>`` + stderr tail (when it
- adds to the message) + up to 10 lint hints — the failure report of every
- build-running tool."""
+ """``BUILD FAILED: <type>: <message> at <file>:<line>`` + stderr tail + up to 10 lint hints."""
where = f" at {error_file_display(br.error_file, root)}:{br.error_line}" if br.error_file else ""
- # the location stays on the headline even when the message is multi-line (GLSL)
+ # the location stays on the headline when the message is multi-line
head, _, rest = sanitize_text(br.error_message, root).partition("\n")
lines = [f"BUILD FAILED: {br.error_type or 'Error'}: {head}{where}"] + ([rest] if rest else [])
tail = proc.tail(sanitize_text(br.stderr_tail, root).rstrip("\n"), max_lines=tail_n)
@@ -159,11 +138,7 @@ def gate_observation(report: GateReport, *, title: str = "", max_findings: int =
images: Iterable[str] = (), failed: bool = False) -> Observation:
"""Errors first, each with its fix hint; counts in ``numbers``.
- The verdict leads the text for every gate, ``title`` or not: a failing gate is a
- result, not a tool error (``Observation.failed`` stays False), so PASS/FAIL is all
- the model has to go on. ``title`` names the gate, never the verdict. ``failed`` is
- for the one caller whose gate report can also mean the tool did not run (the scene
- probe driver dying); it forces ``ok=False``, because a call that failed has no verdict.
+ The PASS/FAIL verdict leads the text. ``failed`` marks a tool that could not run and forces ``ok=False``.
"""
findings = sorted(report.findings, key=lambda f: _SEV_ORDER.get(f.severity, 3))
n_err = sum(1 for f in findings if f.severity == Severity.ERROR)
@@ -188,15 +163,7 @@ def gate_observation(report: GateReport, *, title: str = "", max_findings: int =
def render_observation(rs: RenderSet, root: Path, *, note: str = "", max_individual: int = 4) -> Observation:
"""Contact sheet first, individual views when few; text lists views + cameras.
- The negative outcomes are NOT one answer. **Console errors** are a verdict
- (``ok=False``, ``failed=False``) whether or not any view came back: the scene ran
- far enough to log them and the agent fixes them in ``src/`` — a scene that fails to
- boot returns an empty RenderSet whose ``console_errors`` say why (``render_scene``),
- and reporting that as a broken call would buy a blind retry of the very thing that
- just explained itself. **No views and nothing logged** is a failure
- (``failed=True``): the tool's product is pictures, it has none and no reason, and
- nothing the agent edits changes that. Either way the verdict leads the text, since
- a negative verdict now only reaches the model as text.
+ Console errors are a verdict (``ok=False``); no views and nothing logged is a failure (``failed=True``).
"""
images: list[str] = []
if rs.contact_sheet:
diff --git a/harness/codeverse3d/spatial/probes.py b/harness/codeverse3d/spatial/probes.py
index 855ec5d8..8eecd3dc 100644
--- a/harness/codeverse3d/spatial/probes.py
+++ b/harness/codeverse3d/spatial/probes.py
@@ -1,18 +1,4 @@
-"""Scene probes: the import/census gate and the shader-preflight report reader.
-
-* ``run_probe(ws, compile=)`` → (scene_probe, shader_preflight, census) — THE
- ``probe_scene.mjs`` driver call; ``compile=True`` (the scene build and the
- ``shader_probe`` tool) adds the shader preflight to the same boot
-* ``probe_scene(ws)`` → (GateReport 'scene_probe', census) — the standalone probe
- (the ``scene_probe`` tool, ``check_placement(rebuild=true)``)
-* ``probe_report`` / ``shader_report`` — the two gates, pure over the driver JSON.
-
-An OFFLINE scene (scene_blender, D2/D3) is probed on its census GLB (``glb=``): the same driver,
-census and placement code through the harness adapter ``runtime_js/lib/glb_scene.mjs``, with no
-settle and no camera repair (the picture is Blender's, so the JS copy is never mutated), the bpy
-facts the GLB cannot carry merged into the census before any finding is drawn (``facts=``), and
-the triangle gate on UNIQUE triangles instead of the draw budget (D99 has no meaning offline).
-"""
+"""Scene probes: the import/census gate and the shader-preflight report reader."""
from __future__ import annotations
@@ -42,13 +28,7 @@ _BOOT_HINTS = {
class SceneProbeResult(BaseModel):
- """``probe_scene`` result: unpacks as ``gate, census = probe_scene(ws)`` and also
- dumps to a dict generic tool adapters can read. Tool semantics: ``ok`` /
- ``errors`` describe whether the PROBE TOOL ran — a gate that fails on
- agent-fixable findings keeps ``ok=True`` with the finding lines under
- ``findings``; ``errors`` holds only harness/driver failures and is what the
- tool maps to ``Observation.failed`` (MCP ``is_error``). Gate truth stays on
- ``gate.passed``, which is the observation's verdict."""
+ """``probe_scene`` result."""
gate: GateReport
census: dict[str, Any] = Field(default_factory=dict)
@@ -62,12 +42,7 @@ class SceneProbeResult(BaseModel):
def probe_result(gate: GateReport, census: dict[str, Any]) -> SceneProbeResult:
- """A ``harness_failure`` finding IS a driver failure, wherever it was raised.
-
- ``ok`` is "the tool could run" (``registry.Observation.failed = not ok``) and the
- agent-facing ``findings`` deliberately exclude harness failures — so a report that
- carries one and nothing else used to come back ok, with no errors and no findings: a
- probe that reads healthy and measured nothing."""
+ """A ``harness_failure`` finding IS a driver failure, wherever it was raised."""
errors = [f.message[:800] for f in gate.findings if f.data.get("harness_failure")]
lines = [f"[{f.severity.value}] {f.target or ''}: {f.message}" for f in gate.findings
if f.severity != Severity.INFO and not f.data.get("harness_failure")]
@@ -81,29 +56,15 @@ def _f(gate: str, sev: Severity, msg: str, *, target: str | None = None, hint: s
def run_probe(ws: Workspace, *, compile: bool = False, timeout_s: float | None = None,
glb: Path | None = None, facts: Mapping[str, Any] | None = None,
) -> tuple[GateReport, GateReport, dict[str, Any]]:
- """One ``probe_scene.mjs`` boot → (scene_probe, shader_preflight, census).
-
- ``compile`` also runs the shader preflight on the same page; without it — or when the
- scene never boots — the preflight is a failed-empty gate. ``timeout_s`` defaults to
- the build timeout, capped at 120 s. A driver that cannot run is a ``harness_failure``
- finding, never a raise — except a driver whose own watchdog fired twice inside the scene's
- own code (``SceneRenderError.scene_timed_out``): that is the scene's construction cost and an
- ERROR against the code (:func:`timeout_finding`, D111). ``glb`` probes an offline scene's
- census GLB instead of ``src/scene.js`` (module docstring), ``facts`` its bpy census; the GLB
- is the harness's own export of a scene Blender already built, so a boot of it that never
- finishes stays the harness's, like every other failure to boot it (:func:`offline_report`)."""
+ """One ``probe_scene.mjs`` boot → (scene_probe, shader_preflight, census)."""
t0 = time.time()
timeout_s = min(float(timeout_s or get_settings().limits.build_timeout_s), 120.0)
args = ["--ws", str(ws.root), "--out", str(ws.artifacts / "scene_probe.json"), "--timeout-ms", str(int(timeout_s * 1000))]
if compile:
args += ["--compile", "--shaders-out", str(ws.artifacts / "shader_preflight.json")]
if glb is not None:
- # D3: nothing moves the JS copy of a scene Blender renders — no settle, no camera repair
- args += ["--glb", str(Path(glb).resolve()), "--no-settle"] # node runs in runtime_js/: a relative path would miss
+ args += ["--glb", str(Path(glb).resolve()), "--no-settle"]
else:
- # 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()
no_preflight = GateReport(gate=SHADER_GATE, passed=False, findings=[])
try:
@@ -127,16 +88,7 @@ def run_probe(ws: Workspace, *, compile: bool = False, timeout_s: float | None =
def timeout_finding(timeout_s: float, *, phase: str) -> GateFinding:
"""A probe whose watchdog fired inside the scene's own code (``render_scene.SCENE_PHASES``) —
- after the driver's one retry, on a browser of its own — is an ERROR against the CODE.
-
- WHY (D111). 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 no longer booted inside 120 s. The probe filed
- it as a harness failure with "not your code; retry or report": the agent, told so by its own build
- tool, went quiet until the watchdog killed it, and the round then spent 3 x 240 s rebuilding the
- same code (``repair.MAX_HARNESS_REBUILDS``) and was never scored. The previous round of the same
- workspace booted in 8 s: what changed is the code. Not ``harness_failure``, so the round's repair
- session receives it (``tracks/repair.build_with_repair``) and the build tool reports it as a finding.
- scene_threejs only: an offline scene's census GLB is the harness's export (:func:`run_probe`)."""
+ after the driver's one retry, on a browser of its own — is an ERROR against the CODE."""
entry = ENTRY_FILE[Language.SCENE_THREEJS]
what = {"scene": f"importing {entry} and createScene()", "census": "the census of what createScene() built",
"update": "update(t, dt)"}.get(phase, "the scene's boot")
@@ -148,10 +100,7 @@ def timeout_finding(timeout_s: float, *, phase: str) -> GateFinding:
def probe_scene(ws: Workspace, *, timeout_s: float | None = None) -> SceneProbeResult:
- """Import-only probe: module loads, shape valid, cameras valid, update runs, census. The
- budget defaults to the BUILD's (:func:`run_probe`): the ``scene_probe`` tool used to probe at
- 60 s while the build allowed 120 s, so since D111 made a timeout the code's, the agent's own
- tool would have condemned a scene the build accepts."""
+ """Import-only probe."""
report, _, census = run_probe(ws, timeout_s=timeout_s)
if census:
ws.write_json(ws.artifacts / "census.json", census)
@@ -159,23 +108,12 @@ def probe_scene(ws: Workspace, *, timeout_s: float | None = None) -> SceneProbeR
def probe_report(summary: dict[str, Any], *, duration_ms: int = 0) -> tuple[GateReport, dict[str, Any]]:
- """Interpret a ``probe_scene.mjs`` summary into the ``scene_probe`` GateReport
- (+ census). Pure over the driver JSON, so the combined single-boot build
- (``probe_scene.mjs --compile``, scene_threejs runtime) reuses it."""
+ """Interpret a ``probe_scene.mjs`` summary into the ``scene_probe`` GateReport (+ census)."""
gate = PROBE_GATE
findings: list[GateFinding] = []
s = summary
boot = s.get("boot") or {}
if "boot" not in s:
- # NO boot record at all is not a verdict about the scene: `probe_scene.mjs` always
- # carries `boot` in its summary, so an absent one means the driver produced no
- # parsable summary line — its stdout tail was dropped (`proc._ABANDONED`), or it
- # died in a way `run_scene_script` let through with exit 0. Saying "scene did not
- # boot" here hands the agent a defect that does not exist and names nothing it can
- # fix: on desert_canyon (bench/out/scene_baseline, 2026-09-05) the run spent three
- # repair attempts on `[?] scene did not boot` with an identical signature, while the
- # driver's own artifacts/scene_probe.json recorded `ok: true, boot.ok: true,
- # stage: ready` — and the workspace boots in 600 ms today, unchanged.
findings.append(_f(gate, Severity.ERROR, "scene probe produced no result (driver output lost)",
target="src/scene.js",
hint="this is a harness/driver failure, not your code; retry or report",
@@ -190,7 +128,7 @@ def probe_report(summary: dict[str, Any], *, duration_ms: int = 0) -> tuple[Gate
msg += " — " + "; ".join(missing[:4])
findings.append(_f(gate, Severity.ERROR, f"[{stage}] {msg}"[:1500], target="src/scene.js",
hint=_BOOT_HINTS.get(stage, "fix the quoted error"), stage=stage))
- for p in boot.get("camera_problems", []): # {severity, text}: the host grades each problem
+ for p in boot.get("camera_problems", []):
findings.append(_f(gate, Severity(p["severity"]), f"cameras: {p['text']}", target="src/scene.js",
hint="cameras: [{name:'overview', position:[x,y,z], lookAt:[x,y,z], fov:50}, ...] (1-6 entries)"))
if boot.get("ok") and s.get("update_ok") is False:
@@ -200,7 +138,7 @@ def probe_report(summary: dict[str, Any], *, duration_ms: int = 0) -> tuple[Gate
if e.startswith("boot["):
continue
if e.startswith("update(t=") and s.get("update_ok") is False:
- continue # already reported as the update(t, dt) finding above
+ continue
findings.append(_f(gate, Severity.ERROR, f"console: {e}"[:1000], target="src/scene.js",
hint="the browser console must stay clean: fix the quoted error"))
for w in s.get("console_warnings", []):
@@ -215,13 +153,9 @@ def probe_report(summary: dict[str, Any], *, duration_ms: int = 0) -> tuple[Gate
target="src/scene.js", hint="delete your own render loop; the host drives update()"))
census = s.get("census") or {}
findings.extend(_census_findings(census))
- # the first camera's lens and exposure are scene_frames' (frame_metrics) — one camera, one
- # gate; `first_camera` stays in the probe summary (scene_probe.json)
return GateReport.of(gate, findings, duration_ms=duration_ms), census
-#: census keys an offline scene's bpy facts own: the JS census of a GLB cannot see a world, a
-#: volume or a lamp, so its own values for these are replaced, never mixed
FACT_KEYS = ("fog", "background", "environment", "light_types")
@@ -237,9 +171,7 @@ def merge_facts(census: dict[str, Any], facts: Mapping[str, Any]) -> dict[str, A
def offline_report(summary: dict[str, Any], facts: Mapping[str, Any], *, duration_ms: int = 0) -> tuple[GateReport, dict[str, Any]]:
- """The ``scene_probe`` gate of an offline scene over its census-GLB probe. The host loaded a
- file the HARNESS wrote, so a boot or console failure is the harness's (``harness_failure``),
- never the agent's; the verdict is the census's."""
+ """The ``scene_probe`` gate of an offline scene over its census-GLB probe."""
boot = summary.get("boot") or {}
fail = [e for e in summary.get("console_errors", []) if not e.startswith("boot[")]
if not boot.get("ok"):
@@ -258,9 +190,7 @@ def offline_report(summary: dict[str, Any], facts: Mapping[str, Any], *, duratio
def _offline_findings(c: dict[str, Any]) -> list[GateFinding]:
- """What only an offline scene can get wrong: a triangle count the renderer must hold in
- memory (UNIQUE triangles — an instance costs a matrix, not a mesh; D2), drivers the build
- will never evaluate (D10) and frame handlers the deliverable would depend on."""
+ """What only an offline scene can get wrong."""
bpy = c.get("bpy") or {}
out: list[GateFinding] = []
unique = int(bpy.get("unique_tris") or 0)
@@ -330,15 +260,7 @@ def _census_findings(c: dict[str, Any], *, offline: bool = False) -> list[GateFi
def unlit(census: Mapping[str, Any], *, offline: bool) -> GateFinding | None:
- """The ERROR for a scene that nothing lights: no lamp and no world (bpy), or no light, no
- background and no environment map (three.js) — every frame renders black.
-
- An ERROR since D112 (was a WARN): argon loop iteration 5, scene_blender r1_10 built round 0 on
- the skeleton's placeholder env (lights 0, background null); the build passed with
- "0 errors", the round-0 repair fixed an asset and left the env, and every frame was 96-99 %
- black — judged 0.109 after the full render and judge spend. An ERROR fails the build, so the
- repair session is handed the env module before anything is rendered. The same rule checks
- an env module alone (``SceneRuntime.check_env``)."""
+ """The ERROR for a scene that nothing lights."""
lights = int((census.get("totals") or {}).get("lights", 0) or 0)
if lights or census.get("background"):
return None
@@ -353,10 +275,7 @@ def unlit(census: Mapping[str, Any], *, offline: bool) -> GateFinding | None:
def _draw_findings(c: dict[str, Any]) -> list[GateFinding]:
- """The scene draw budget (D99): ``totals.draws`` against ``DRAWS_WARN_SCENE`` /
- ``MAX_DRAWS_SCENE``. The count is the census's, so it is the number ``scene_probe`` shows
- and the same on every machine, camera and load — fps is not (2 961 draws measured 10.4,
- 9.6 and 1.6 fps in three rounds of one run). An ERROR fails the build, which puts it in the repair loop."""
+ """The scene draw budget."""
draws = int(c.get("totals", {}).get("draws", 0))
if draws <= DRAWS_WARN_SCENE:
return []
@@ -372,9 +291,8 @@ def _draw_findings(c: dict[str, Any]) -> list[GateFinding]:
def shader_report(report: dict[str, Any], *, duration_ms: int = 0) -> GateReport:
- """Interpret a shader-preflight report (the ``shader_report`` block of
- ``probe_scene.mjs --compile``) into the ``shader_preflight`` GateReport. Pure over
- the driver JSON."""
+ """Interpret a shader-preflight report (the ``shader_report`` block of ``probe_scene.mjs
+ --compile``) into the ``shader_preflight`` GateReport."""
gate = SHADER_GATE
findings: list[GateFinding] = []
rep = report
diff --git a/harness/codeverse3d/spatial/registry.py b/harness/codeverse3d/spatial/registry.py
index f7bf67d9..09571c8b 100644
--- a/harness/codeverse3d/spatial/registry.py
+++ b/harness/codeverse3d/spatial/registry.py
@@ -1,20 +1,6 @@
-"""Tool registry: one definition → python fn + JSON schema + MCP + prompt card.
+"""Tool registry: one ``@tool(name, ArgsModel, description)`` definition → python fn + JSON schema + MCP + prompt card.
-Usage::
-
- class MeasureArgs(BaseModel):
- parts: list[str] = Field(default_factory=list, description="limit to these part names")
-
- @tool("measure", MeasureArgs, "Measure bbox/extents/islands of the built object (and per part).")
- def measure(ctx: ToolContext, args: MeasureArgs) -> Observation: ...
-
-``ToolContext`` carries the workspace and settings; tools never touch globals.
-``ToolDef.call`` is the one error boundary: ``ToolUsageError`` becomes a usage
-Observation, anything else a failed Observation — a tool body never needs try/except.
-Observations: ``text`` (what the agent reads), ``numbers`` (machine-readable),
-``images`` (paths, small PNGs the agent may view), ``ok`` (the VERDICT) and
-``failed`` (the tool could not run). The two are different answers and only
-``failed`` may reach the model as a protocol error — see :class:`Observation`.
+``ToolDef.call`` is the one error boundary: tool bodies never need try/except.
"""
from __future__ import annotations
@@ -36,12 +22,10 @@ class NoArgs(BaseModel):
class Observation(BaseModel):
"""A tool's answer: ``ok`` is the VERDICT, ``failed`` says the tool could not run.
- Only ``failed`` becomes MCP ``is_error``; a negative verdict is a result, not a
- broken call (what that cost when the two were one flag: docs/COST.md §30).
+ Only ``failed`` becomes MCP ``is_error``; a negative verdict is a result, not a broken call.
"""
- # validate_assignment: the invariant below has to hold for `obs.failed = ...` at a call
- # site as well, not only at construction (spatial/tools.scene_probe did exactly that)
+ # validate_assignment: the failed-implies-not-ok invariant must hold on later assignment too
model_config = ConfigDict(validate_assignment=True)
ok: bool = True
@@ -54,24 +38,16 @@ class Observation(BaseModel):
@model_validator(mode="after")
def _a_failure_is_never_a_pass(self) -> Observation:
- """``failed`` implies ``not ok``: a tool that could not run has no verdict to
- report, and ``Observation(ok=True, failed=True)`` was representable."""
+ """``failed`` implies ``not ok``."""
if self.failed and self.ok:
raise ValueError("Observation(ok=True, failed=True): a tool that could not run has no verdict")
return self
@classmethod
def error(cls, text: str, **numbers: Any) -> Observation:
- """The tool could not run: every failure caught at the :meth:`ToolDef.call`
- boundary and every missing / unreadable artefact is built here.
-
- It is not the only thing that sets ``failed``. Three results are failures
- the tool computed rather than exceptions it caught, and they set the flag on
- an observation they compose themselves: ``build`` (the runtime reported
- success and left no readable GLB), ``scene_probe`` (the probe driver died)
- and ``observe.render_observation`` (no view AND no console error — with one
- it is a verdict). Those four places are the whole list; nothing else may set
- ``failed``.
+ """The tool could not run (caught exceptions, missing artefacts).
+
+ Only ``build``, ``scene_probe`` and ``observe.render_observation`` also set ``failed`` themselves.
"""
return cls(ok=False, failed=True, text=text, numbers=numbers)
@@ -103,13 +79,13 @@ class ToolDef:
cost_hint: str = "fast" # fast | slow
def schema(self) -> dict[str, Any]:
- """JSON schema of the arguments object (for native tool calling / MCP)."""
+ """JSON schema of the arguments object."""
s = self.args_model.model_json_schema()
s.pop("title", None)
return s
def card(self) -> str:
- """Prompt card: name, one-line purpose, args with descriptions."""
+ """Prompt card: name, purpose, args with descriptions."""
props = self.schema().get("properties", {})
req = set(self.schema().get("required", []))
lines = [f"- `{self.name}` ({self.cost_hint}): {self.description}"]
@@ -186,5 +162,5 @@ def tool_cards(*, track: str = "", language: str = "") -> str:
def _ensure_loaded() -> None:
- """Import the module that registers every tool (idempotent)."""
+ """Import the module that registers every tool."""
import codeverse3d.spatial.tools # noqa: F401 — its @tool decorators fill _REGISTRY
diff --git a/harness/codeverse3d/spatial/render.py b/harness/codeverse3d/spatial/render.py
index 60049ef1..5b10902f 100644
--- a/harness/codeverse3d/spatial/render.py
+++ b/harness/codeverse3d/spatial/render.py
@@ -1,9 +1,6 @@
"""Headless renders of the canonical GLB (three.js in headless Chrome, GPU when available).
-``render_glb`` is the one entry point the tracks/judges/tools use. Results are
-cached under ``<cache_dir>/renders/<sha256(glb)+params>/`` so repeated judge
-calls on the same artifact do not re-render; cached PNGs are copied into the
-requested ``out_dir`` so every call still yields a self-contained directory.
+``render_glb`` is the entry point; results are cached under ``<cache_dir>/renders/`` and copied into ``out_dir``.
"""
from __future__ import annotations
@@ -33,7 +30,7 @@ from codeverse3d.spatial.node import (
)
BACKGROUNDS = ("studio", "white", "transparent")
-CACHE_VERSION = 4 # bump when the rig changes in a way that invalidates cached PNGs
+CACHE_VERSION = 4 # bump when the rig changes the pixels
log = logging.getLogger(__name__)
@@ -48,12 +45,7 @@ def _cache_key(glb: Path, params: dict[str, Any]) -> str:
return hashlib.sha256(blob.encode()).hexdigest()[:24]
-#: Every file that can change what an object render LOOKS like: the driver, the
-#: page-side rig, the studio (environment/backdrop/lights) and the camera-fit math.
-#: Host plumbing (lib/cli.mjs, lib/host_env.mjs, lib/host_page.mjs) is deliberately
-#: NOT here — it cannot change a pixel, and hashing it would drop every cached PNG
-#: on an unrelated edit. ``tests/threejs_render/test_studio_rig.py`` walks the real
-#: import graph and fails when a new page-side module is missing from this list.
+#: Every file that can change what an object render looks like (host plumbing excluded); a test checks the import graph.
RIG_FILES = (
"render_glb.mjs",
"lib/browser/render_rig.js",
@@ -66,7 +58,7 @@ RIG_FILES = (
def _rig_signature() -> str:
- """Hash of the JS rig files so editing the rig invalidates the cache."""
+ """Hash of the JS rig files; editing the rig invalidates the cache."""
rt = runtime_js_dir()
h = hashlib.sha256()
for rel in RIG_FILES:
@@ -94,11 +86,9 @@ def render_glb(
timeout_s: float | None = None,
use_cache: bool = True,
) -> RenderSet:
- """Render ``glb`` from ``views`` (default :data:`OBJECT_VIEWS`) into ``out_dir``.
+ """Render ``glb`` from ``views`` (default :data:`OBJECT_VIEWS`): ``view_<name>.png``, ``views.json`` and ``sheet.png``.
- Writes ``view_<name>.png`` per view, ``views.json`` (camera data) and, when
- ``sheet`` is true, ``sheet.png`` (labelled contact sheet). Raises
- :class:`RenderError` on failure — never returns a partial RenderSet.
+ Raises :class:`RenderError` on failure; never returns a partial RenderSet.
"""
glb = Path(glb).resolve()
out_dir = Path(out_dir).resolve()
@@ -124,8 +114,7 @@ def render_glb(
"background": background,
"anim_time": anim_time,
"shadow": bool(shadow),
- # requested mode ('auto' fragments from 'on'/'off' — accepted over a hit
- # serving the other backend's pixels and lying about RenderSet.renderer)
+ # the requested mode, so a cache hit never serves the other backend's pixels
"gpu": gpu,
"rig": _rig_signature(),
}
@@ -141,11 +130,7 @@ def render_glb(
except RenderError as e:
if not transient_failure(e):
raise
- # compare_art_v4 (2026-08-28): under 12 concurrent cells the browser took 7.5 s to
- # open a page and the viewer's wait expired ("Waiting failed"); the cell lost its
- # in-loop judge for the round. One retry with twice the time is cheap next to that.
- # A browser LOSS is retried on a browser of our own: the shared one
- # advertised in the cache is the suspect, so re-using it repeats the failure.
+ # one retry with twice the time; a browser loss is retried on an owned browser
own = browser_was_lost(e)
log.warning(
"render_glb transient failure, retrying once with %.0f s%s: %s",
@@ -180,9 +165,6 @@ def render_glb(
)
-#: render failures that are the box, not the model: a retry is worth one more timeout.
-#: The vocabulary lives in `spatial/node.py` next to the browser-loss half, shared with
-#: the scene drivers since 2026-09-07 (they used to retry only a browser loss).
RETRY_PAUSE_S = 3.0
@@ -219,8 +201,7 @@ def _run_render(
def _store_in_cache(cache_dir: Path, out_dir: Path, record: dict[str, Any]) -> None:
- # per-writer tmp + tolerant rename (the vlm_judge._render_slices shape): a pid-only
- # name let two judge threads share a tmp dir and delete each other's half-copied PNGs
+ # per-writer tmp + tolerant rename: concurrent judge threads must not share a tmp dir
tmp = unique_tmp(cache_dir)
shutil.rmtree(tmp, ignore_errors=True)
try:
@@ -228,9 +209,9 @@ def _store_in_cache(cache_dir: Path, out_dir: Path, record: dict[str, Any]) -> N
for v in record["views"]:
shutil.copy2(out_dir / f"view_{v['name']}.png", tmp / f"view_{v['name']}.png")
(tmp / "views.json").write_text(json.dumps(record, indent=1))
- with contextlib.suppress(OSError): # a concurrent identical writer won the race; keep theirs
+ with contextlib.suppress(OSError): # a concurrent writer won; keep theirs
tmp.replace(cache_dir)
- finally: # a mid-copy crash (or losing the race) must not leave the .tmp behind
+ finally: # never leave the .tmp behind
shutil.rmtree(tmp, ignore_errors=True)
diff --git a/harness/codeverse3d/spatial/render_blender.py b/harness/codeverse3d/spatial/render_blender.py
index 96d155d7..1edff6c5 100644
--- a/harness/codeverse3d/spatial/render_blender.py
+++ b/harness/codeverse3d/spatial/render_blender.py
@@ -1,37 +1,12 @@
"""Render a built ``scene_blender`` workspace: Blender makes the pictures, the JS host measures.
-``render_blender_scene(ws, out_dir, ...)`` is what ``SceneBlenderRuntime.render_scene`` calls
-(DESIGN §2 "render", owner D1/D3/D8 2026-09-24). Four steps, one output format:
-
-1. **orbit fit** — ``runtime_js/fit_orbit.mjs`` fits ``conventions.SCENE_VIEWS`` to the census
- the build's probe wrote (``artifacts/census.json``): the same ``orbit.mjs`` the three.js
- driver runs in-page, so there is one implementation of the fitting;
-2. **pixels** — ``languages/wrappers/render_bpy_scene.py`` inside Blender on the built
- ``artifacts/scene.blend``: the authored cameras × every time + the first
- ``MAX_JUDGE_OVERVIEWS`` overview views at the first time (what someone reads — the judge and
- the motion metric; the eye-level rig views get geometry checks but no pixels). The high
- overviews (``noFog``) render without the world volume and with a room shell's lid lifted —
- the three.js host's ``skyLayersBelow`` rule, so both languages are judged on the same
- interior (the driver names what it hid in each frame's ``hidden``). Engine /
- samples / device / per-frame time cap come from ``Settings.render.blender_*`` (Cycles CUDA
- 32 spp + GPU OIDN + persistent data by default — the fast path measured on Blender 5.2.2 LTS,
- see ``render_bpy_scene.setup_render``); a GPU render holds one of ``blender_gpu_slots``
- machine-wide flock'd slots and falls back to the CPU when none frees within
- ``blender_gpu_wait_s`` or the GPU run dies;
-3. **geometry** — ``runtime_js/render_scene.mjs --external-frames`` on the census GLB the build
- wrote (``--glb``: booted through ``runtime_js/lib/glb_scene.mjs``): camera checks (near
- geometry, inside a mesh, ground below/above, line of sight, coverage masks) from the scene,
- luminance statistics from the Blender PNG (``host_metrics.imageFrameStats`` — the one
- ``frameStats``), ``views.json`` / ``metrics.json`` in the three.js driver's schema, with no
- settle, no camera repair, no post chain (D3: the picture is Blender's);
-4. **the RenderSet** — ``render_scene.render_set_from_metrics``, exactly as for three.js:
- motion, errors, the judge subset, the contact sheet.
-
-``metrics.json`` gains two keys the three.js payload does not carry: ``language``
-(``"scene_blender"``: the frame gate's fix hints are per language) and ``blender`` (engine,
-device, samples, the fallback reason, the per-step wall times).
+``render_blender_scene`` runs four steps with one output format: (1) ``fit_orbit.mjs`` fits the orbit
+rig to the build's census; (2) ``render_bpy_scene.py`` renders the authored cameras x times plus the
+first ``MAX_JUDGE_OVERVIEWS`` overviews in Blender (GPU runs hold a machine-wide flock slot, CPU
+fallback); (3) ``render_scene.mjs --external-frames`` does the geometry checks and frame stats on the
+census GLB; (4) ``render_scene.render_set_from_metrics`` builds the RenderSet. ``metrics.json`` adds
+``language`` and ``blender`` keys.
"""
-
from __future__ import annotations
import json
@@ -65,15 +40,14 @@ from codeverse3d.workspace import Workspace
log = logging.getLogger(__name__)
DRIVER = Path(__file__).resolve().parent.parent / "languages" / "wrappers" / "render_bpy_scene.py"
-#: the language whose authoring frame the .blend is in. scene_blender's LANGUAGE_FRAME row
-#: (lane A) is Z-up / -Y front, the same frame as blender's; switch to it once that row lands.
+#: the language whose authoring frame the .blend is in
FRAME_LANGUAGE = "scene_blender"
LANGUAGE = "scene_blender"
JOB_NAME = "blender_job.json"
RESULT_NAME = "blender_frames.json"
EXTERNAL_NAME = "blender_views.json"
SLOT_DIR = "blender_gpu"
-#: the keys of a view entry — render_scene.mjs's own view schema
+#: keys of a view entry (render_scene.mjs's view schema)
_VIEW_KEYS = ("name", "kind", "path", "time_s", "position", "lookAt", "fov", "render_ms")
@@ -92,8 +66,7 @@ def _to_glb(v: Sequence[float]) -> list[float]:
def _blender_env(engine: str, device: str) -> dict[str, str]:
- """A headless Blender child's env; EEVEE / Workbench on the GPU need the Mesa d3d12 env
- (without it they silently land on llvmpipe — measured 10x slower, no error)."""
+ """A headless Blender child's env; EEVEE / Workbench on the GPU need the Mesa d3d12 env or they silently use llvmpipe."""
from codeverse3d.languages.blender import blender_env
from codeverse3d.spatial.gl_render import GPU_ENV
@@ -129,11 +102,9 @@ def _failure(proc: ProcResult) -> str:
def render_frames(blend: Path, out_dir: Path, job: dict[str, Any], *, timeout_s: float,
settings: Settings | None = None) -> dict[str, Any]:
- """Run the Blender driver under the GPU-slot policy; its result json + ``fallback`` / ``slot_wait_ms``.
+ """Run the Blender driver under the GPU-slot policy; result json + ``fallback`` / ``slot_wait_ms``.
- ``blender_device == "gpu"``: take a slot (wait ≤ ``blender_gpu_wait_s``) and render on the
- GPU; all slots busy → CPU; a GPU run that dies without a result → one CPU run. A timeout
- is the scene's weight, not the device's: it raises ``SceneRenderError`` with no retry."""
+ GPU: take a slot (wait ≤ ``blender_gpu_wait_s``); all busy, or a GPU run that dies → CPU. A timeout raises without retry."""
s = settings or get_settings()
fallback = ""
wait_ms = 0
@@ -186,10 +157,7 @@ def fit_orbit(census_path: Path, views: Sequence[ViewPreset], *, width: int, hei
def _pixel_orbit(specs: list[dict[str, Any]]) -> set[str]:
- """The rig views that get Blender pixels: the first ``MAX_JUDGE_OVERVIEWS`` overviews — the
- same four tiles ``render_scene.select_judge_views`` hands the judge (the three high views
- and the ground-level ``overview_low_front`` since scene); the eye-level rig is measured
- by the geometry pass and never rendered."""
+ """The rig views that get Blender pixels: the first ``MAX_JUDGE_OVERVIEWS`` overviews (the judge's tiles)."""
return set([str(o["name"]) for o in specs if str(o["name"]).startswith("overview")][:MAX_JUDGE_OVERVIEWS])
@@ -213,16 +181,10 @@ def render_blender_scene(
engine: str | None = None,
samples: int | None = None,
) -> RenderSet:
- """Authored cameras (+ the orbit rig) × ``times`` rendered by Blender → a RenderSet whose
- ``metrics.json`` has the three.js driver's schema.
-
- ``cameras=None`` renders the cameras the .blend carries (the build made them from the
- plan); explicit ``cameras`` (GLB frame, like every plan camera) replace them. ``blend``
- defaults to ``artifacts/scene.blend``, ``census`` (the orbit fit) to ``artifacts/census.json``;
- ``glb`` (default ``artifacts/census.glb``) is what the geometry pass boots through the host. ``engine``
- / ``samples`` override Settings (a tool's preview tier: ``engine="workbench"``). A missing
- .blend yields an empty RenderSet whose ``console_errors`` say why; a driver that cannot run
- raises ``SceneRenderError``."""
+ """Authored cameras (+ the orbit rig) × ``times`` rendered by Blender → a RenderSet (three.js-schema ``metrics.json``).
+
+ ``cameras=None`` uses the cameras the .blend carries; explicit ones (GLB frame) replace them. A missing .blend gives
+ an empty RenderSet with ``console_errors``; a driver that cannot run raises ``SceneRenderError``."""
s = get_settings()
out_dir = out_directory(out_dir, clean=("metrics.json", "views.json", RESULT_NAME, EXTERNAL_NAME))
blend = blend or ws.artifacts / "scene.blend"
@@ -259,7 +221,7 @@ def render_blender_scene(
blender_ms = int((time.monotonic() - t0) * 1000)
views = [_glb_view(f) for f in frames.get("frames") or []]
write_json_atomic(out_dir / EXTERNAL_NAME, views)
- # 3. geometry: every camera the scene has (authored as Blender saw them) + the whole rig
+ # 3. geometry: authored cameras as Blender saw them + the whole rig
specs = [{"name": c["name"], "kind": c.get("kind") or "authored", "position": _to_glb(c["position"]),
"lookAt": _to_glb(c["look_at"]), "fov": c.get("fov")}
for c in frames.get("cameras") or [] if c.get("kind") == "authored"]
@@ -269,7 +231,7 @@ def render_blender_scene(
timeout_s=tmo, glb=glb)
geometry_ms = int((time.monotonic() - t0) * 1000)
if not metrics.get("views"):
- metrics["views"] = views # the pictures exist even when the geometry pass could not run
+ metrics["views"] = views
# 4. merge the Blender facts; one schema downstream
errors = [f"blender: {e}" for e in frames.get("errors") or []]
if geometry_error:
diff --git a/harness/codeverse3d/spatial/render_scene.py b/harness/codeverse3d/spatial/render_scene.py
index 9f5a70a6..48302fe0 100644
--- a/harness/codeverse3d/spatial/render_scene.py
+++ b/harness/codeverse3d/spatial/render_scene.py
@@ -1,15 +1,8 @@
"""Render a ``scene_threejs`` workspace through the node host (headless GPU Chrome).
-``render_scene(ws, out_dir, ...)`` drives ``runtime_js/render_scene.mjs``:
-authored cameras + an overview orbit rig (``conventions.SCENE_VIEWS``, fitted
-to the scene CONTENT, guarded by the plan bounds) at one or more animation
-times, deterministic instruments (console/shader errors, fps, census, camera
-checks incl. luminance + content coverage) and a labelled contact sheet built
-from the JUDGE subset of views. Returns a ``RenderSet`` with every view; the
-full instrument payload is left at ``out_dir/metrics.json`` (``metrics_path_for``
-finds it again from a RenderSet). Each ``RenderView`` (and each entry of the
-driver's ``views.json``) carries ``judge: true|false`` — stamped once from
-``select_judge_views`` at render time.
+``render_scene`` drives ``runtime_js/render_scene.mjs``: authored cameras + a fitted orbit rig at one or more
+times, with deterministic instruments left in ``out_dir/metrics.json`` and a contact sheet of the judge subset.
+Each view carries ``judge: true|false``, stamped once from ``select_judge_views``.
"""
from __future__ import annotations
@@ -41,29 +34,18 @@ log = logging.getLogger(__name__)
#: views the judge sees (contact sheet + individual images are built from these)
JUDGE_MAX_VIEWS = 10
-#: how many overview-rig tiles the judge gets (layout / grounding X-ray; the eye-level
-#: rig views are diagnostics only and never reach the judge). 4 since scene
-#: (2026-10-14): the three high views plus ``overview_low_front``, the ground-level contact
-#: camera the judge's contact crops are cut from (``conventions.SCENE_VIEWS``).
+#: overview-rig tiles the judge gets; the eye-level rig views are diagnostics only
MAX_JUDGE_OVERVIEWS = 4
-#: The ``probe_scene.mjs`` watchdog phases that are the scene's own construction work (D111): the
-#: module import + createScene() + the boot settle (``scene``), the census + placement table over
-#: what it built (``census``) and ``update``. Every other phase — ``host`` (browser launch, page
-#: ready), ``report``, ``compile`` (the shader preflight), ``close`` — and a driver killed by the
-#: process clock (node itself starved: its own watchdog never got to run) are the box's.
+#: ``probe_scene.mjs`` watchdog phases that are the scene's own work; every other phase, or a process-clock kill, is the box's.
SCENE_PHASES = frozenset({"scene", "census", "update"})
class SceneRenderError(RuntimeError):
"""The node driver could not run (missing node/deps, timeout, crash).
- ``timed_out`` (typed, D111): the driver ran out of its budget — its own watchdog's summary
- (``lib/cli.armWatchdog``: ``timed_out: true``, exit 3) or the process clock above it — after
- the one retry :func:`run_scene_script` grants. ``phase`` is the watchdog's word for where the
- driver was (empty from the process clock or a driver that names none); :attr:`scene_timed_out`
- is the one case that is a verdict on the code (``probes.run_probe``), not the box."""
+ ``timed_out``: the driver ran out of budget after the retry; ``phase`` is the watchdog's phase (may be empty)."""
def __init__(self, message: str, *, timed_out: bool = False, phase: str = ""):
super().__init__(message)
@@ -72,27 +54,20 @@ class SceneRenderError(RuntimeError):
@property
def scene_timed_out(self) -> bool:
- """The driver's own watchdog fired while the scene's code was running (:data:`SCENE_PHASES`)."""
+ """The driver's watchdog fired while the scene's code was running (a verdict on the code, not the box)."""
return self.timed_out and self.phase in SCENE_PHASES
def _driver_failed(r: NodeResult) -> bool:
- """The DRIVER could not run (exit 2/3, or a non-zero exit with no summary line).
- Exit 1 is a scene that failed, which is a verdict, not a driver failure."""
+ """The driver could not run (exit 2/3, or non-zero with no summary); exit 1 is a failed scene."""
return r.rc in (2, 3) or (r.rc != 0 and not r.summary)
def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd: Path | None = None) -> NodeResult:
- """Run ``runtime_js/<script>`` via ``codeverse3d.spatial.node.run_node`` (which
- delegates to ``codeverse3d.proc.run_subprocess``: own process group, group kill
- on timeout). The driver prints a JSON summary as its LAST stdout line; a
- timeout or exit code 2/3 means the driver itself failed → ``SceneRenderError``.
-
- A driver that lost its BROWSER (``node.BROWSER_LOST_MARKERS``) — or whose own watchdog
- fired (``timed_out``: a wedged shared browser times out the same way, D111) — is retried
- once on a browser of its own. That failure is the box, not the workspace, and without the
- retry it costs the round every render and therefore its judge — the object path
- has retried it since 2026-08-28 (``spatial/render.py``), the scene path did not.
+ """Run ``runtime_js/<script>``; the driver prints a JSON summary as its last stdout line.
+
+ Timeout or exit 2/3 raises ``SceneRenderError``. A lost browser, a watchdog timeout, transient failures
+ and lost output are retried once, the first two on an owned browser.
"""
rt = runtime_js_dir()
path = rt / script
@@ -100,7 +75,7 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:
raise SceneRenderError(f"missing node driver {path}")
env_extra: dict[str, str] = {}
gpu = get_settings().render.gpu
- if gpu: # Settings already folds the flat C3D_RENDER_GPU in; the driver reads only that spelling
+ if gpu:
env_extra["C3D_RENDER_GPU"] = gpu
argv = [str(a) for a in args]
@@ -109,7 +84,7 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:
return run_node(path, argv, cwd=cwd or rt, timeout_s=timeout_s, env_extra=env, check=False)
except NodeError as e:
if e.result is not None and e.result.timed_out:
- # the PROCESS clock: node's own watchdog (timeout_s - 20 s) never ran — the box, no phase
+ # the process clock: node's own watchdog never ran (the box, no phase)
raise SceneRenderError(f"{script} timed out after {timeout_s:.0f}s\n{e.result.stderr_tail}",
timed_out=True) from e
raise SceneRenderError(f"{script} could not run: {e}") from e
@@ -117,19 +92,11 @@ def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd:
r = attempt(env_extra)
err = str(r.summary.get("error", "")) if r.summary else r.stderr_tail
lost_browser = _driver_failed(r) and browser_was_lost(err)
- # the driver's own watchdog fired: retried on an OWNED browser, so a wedged shared one cannot
- # time out both attempts and have the second read as the scene's construction cost (D111)
+ # watchdog timeout: retry on an owned browser so a wedged shared one cannot time out both attempts
timed_out = not lost_browser and _driver_failed(r) and bool(r.summary.get("timed_out"))
- # the rest of the transient vocabulary (`node.TRANSIENT_MARKERS`): a host that timed out
- # waiting for the page under contention ("Waiting failed: 60000ms exceeded") — the object
- # path retried it, this one did not, and a battery cell lost every render to it
+ # the rest of ``node.TRANSIENT_MARKERS``
transient = not lost_browser and not timed_out and _driver_failed(r) and transient_failure(err)
- # Every scene driver ends with a JSON summary line (`lib/cli.finish` / `fail`), so a run
- # that produced none had its stdout tail dropped — `proc._ABANDONED`, which a loaded box
- # makes routine. That is transient and worth one more attempt; without it the empty
- # summary reaches `probes.probe_report`, which used to render it as "[?] scene did not
- # boot" and spend the round's repair budget on a defect that was never there
- # (desert_canyon, bench/out/scene_baseline, 2026-09-05).
+ # every driver ends with a JSON summary line, so none means the output was lost: transient
lost_output = not lost_browser and not r.summary
if lost_browser or lost_output or transient or timed_out:
log.warning(
@@ -153,29 +120,18 @@ 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``
- switches (``Settings``). Every driver invocation — standalone
- probe, render, and the combined single-boot build — appends these, so a census is
- always measured under the same settle / camera-repair policy the
- renders use."""
+ """Scene-driver flags from the settle / camera-repair settings; every driver invocation appends them."""
s = get_settings()
args: list[str] = []
- if not s.settle: # A/B switch for the boot-time auto-seat
+ if not s.settle:
args.append("--no-settle")
- if s.camera_repair: # default ON since 2026-08-30: pure insurance —
- # zero triggers across a whole healthy battery (scene_px_v1: layout camera-clearance
- # 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.
+ if s.camera_repair:
args.append("--camera-repair")
return args
def post_chain_args() -> list[str]:
- """``--no-post`` when ``C3D_POST`` is off. The post chain (GTAO + selective
- bloom + grade, ``runtime_js/lib/browser/post.js``) is ON by default for scene
- PICTURES only: object renders never touch this driver, and the scene probe runs
- raw because it is a 320x180 geometry instrument, not a judged frame. Kept out
- of :func:`probe_env_args` for exactly that reason."""
+ """``--no-post`` when the post chain is off. It applies to scene pictures only; the probe runs raw, so this is not in :func:`probe_env_args`."""
return [] if get_settings().post else ["--no-post"]
@@ -219,15 +175,9 @@ def render_scene(
) -> RenderSet:
"""Render authored (+ orbit) views at ``times``; returns a RenderSet.
- ``cameras=None`` uses the cameras authored in ``createScene()``. ``bounds``
- (default: the workspace plan's bounds) guards the orbit framing against
- scatter that sprawls past the plan. The contact sheet holds at most
- ``JUDGE_MAX_VIEWS`` tiles (the ``select_judge_views`` subset). A
- scene that fails to boot yields an empty RenderSet whose ``console_errors``
- say why (the build gate normally catches that earlier); a driver failure
- raises ``SceneRenderError``.
+ ``cameras=None`` uses the cameras authored in ``createScene()``; ``bounds`` defaults to the plan's. A scene that
+ fails to boot yields an empty RenderSet with ``console_errors``; a driver failure raises ``SceneRenderError``.
"""
- # never read a previous run's instruments
out_dir = out_directory(out_dir, clean=("metrics.json", "views.json"))
settings = get_settings()
args: list[str] = [
@@ -249,15 +199,13 @@ def render_scene(
try:
res = run_scene_script("render_scene.mjs", args, timeout_s=tmo + 30)
except SceneRenderError as e:
- # The driver died mid-run but this invocation already wrote instruments:
- # a scene-side failure the round loop must see as a gate finding, not a
- # harness crash. No metrics at all = a genuine driver problem: re-raise.
+ # instruments already written: a scene-side failure for the gate; none written: a driver problem
if not (out_dir / "metrics.json").is_file():
raise
driver_error = str(e).splitlines()[0][:500]
res = NodeResult(rc=2, stdout="", stderr="", last_json={"error": driver_error}, duration_ms=0)
metrics = read_json_or_none(out_dir / "metrics.json") or {}
- for w in metrics.get("host_warnings") or []: # e.g. a post chain that could not be built: judged RAW
+ for w in metrics.get("host_warnings") or []:
log.warning("render_scene host warning: %s", w)
extra = [driver_error] if driver_error else []
if not metrics and res.summary.get("error"):
@@ -270,11 +218,7 @@ def render_scene(
def render_set_from_metrics(out_dir: Path, metrics: dict[str, Any], *, width: int, height: int,
orbit_views: Sequence[ViewPreset] = SCENE_VIEWS, sheet: bool = True, duration_ms: int = 0,
renderer: str = "", extra_errors: Sequence[str] = ()) -> RenderSet:
- """A scene driver's ``metrics.json`` payload → the RenderSet every scene language returns:
- motion measured and persisted, the views, the console / shader / driver errors, the judge
- subset stamped once (``select_judge_views``) into the views and ``views.json``, the contact
- sheet. ``render_scene`` (three.js pixels) and ``render_blender.render_blender_scene``
- (Blender pixels) both end here, so the two languages cannot drift apart downstream."""
+ """A scene driver's ``metrics.json`` payload → the RenderSet: motion, views, errors, the stamped judge subset, the contact sheet."""
_store_motion(out_dir, metrics)
views: list[RenderView] = []
for v in metrics.get("views", []):
@@ -295,9 +239,8 @@ def render_set_from_metrics(out_dir: Path, metrics: dict[str, Any], *, width: in
duration_ms=duration_ms, console_errors=errors, fps=float(fps) if fps is not None else None,
out_dir=str(out_dir),
)
- # stamp the judge subset ONCE (select_judge_views stays a pure function)
chosen = select_judge_views(rs, max_n=JUDGE_MAX_VIEWS, orbit_names=[v.name for v in orbit_views])
- keep = {id(v) for v in chosen.views} # same objects, so identity is exact
+ keep = {id(v) for v in chosen.views}
for v in rs.views:
v.judge = id(v) in keep
_mark_judge_views(out_dir / "views.json", rs.views)
@@ -308,11 +251,7 @@ def render_set_from_metrics(out_dir: Path, metrics: dict[str, Any], *, width: in
def _store_motion(out_dir: Path, metrics: dict[str, Any]) -> None:
- """Measure inter-frame motion (``spatial.frame_motion``) and persist it into the
- payload AND into ``metrics.json``, so every later reader — the ``scene_frames``
- gate, the judge context, the agent's frame table — sees the same numbers without
- re-reading the PNGs. Never fatal: a scene that could not be diffed simply has no
- ``motion`` key (which means "not measured", never "static")."""
+ """Measure inter-frame motion into the payload and ``metrics.json``; never fatal (no ``motion`` key = not measured)."""
from codeverse3d.spatial.frame_motion import motion_rows
if not metrics.get("views"):
@@ -332,10 +271,8 @@ def _store_motion(out_dir: Path, metrics: dict[str, Any]) -> None:
def select_judge_views(rs: RenderSet, max_n: int = JUDGE_MAX_VIEWS, *, orbit_names: Sequence[str] | None = None) -> RenderSet:
- """Copy of ``rs`` with the views a judge should see (≤ ``max_n``), in priority order:
- authored cameras at the first time · the first two overview orbit views at that time
- · the first two authored cameras at the last time · remaining orbit / authored /
- other views. Tracks call this before judging; the full set stays on disk."""
+ """Copy of ``rs`` with the views a judge should see (≤ ``max_n``): authored cameras at the first time, the first
+ overviews at that time, the first two authored cameras at the last time."""
orbit = set(orbit_names if orbit_names is not None else [v.name for v in SCENE_VIEWS])
views = list(rs.views)
if not views or max_n <= 0:
@@ -349,19 +286,16 @@ def select_judge_views(rs: RenderSet, max_n: int = JUDGE_MAX_VIEWS, *, orbit_nam
ordered: list[RenderView] = [*at(authored, t0), *at(overview, t0)[:MAX_JUDGE_OVERVIEWS]]
if t_last != t0:
ordered += [v for v in at(authored, t_last) if v.name in first_two]
- # Everything left is the harness's own eye-level rig: cameras nobody authored, fitted
- # to the bounds, routinely staring at a fence or standing at street level under a
- # rooftop. They stay on disk (and in the frame gate) as diagnostics, but a judge that
- # SEES them marks the scene unlit / undressed for pictures the builder never framed.
+ # the eye-level rig is left out: cameras nobody authored mislead the judge
if not ordered:
ordered = list(views)
chosen = ordered[:max_n]
keep = {id(v) for v in chosen}
- return rs.model_copy(update={"views": [v for v in views if id(v) in keep]}) # disk order, judge subset
+ return rs.model_copy(update={"views": [v for v in views if id(v) in keep]}) # disk order
def _mark_judge_views(views_json: Path, views: Sequence[RenderView]) -> None:
- """Serialise each view's stamped ``judge`` flag into the driver's views.json."""
+ """Write each view's ``judge`` flag into views.json."""
if not views_json.is_file():
return
try:
@@ -375,8 +309,7 @@ def _mark_judge_views(views_json: Path, views: Sequence[RenderView]) -> None:
def metrics_path_for(rs: RenderSet) -> Path | None:
- """``metrics.json`` of a RenderSet: the stamped ``out_dir`` when present, else
- guessed as a sibling of the sheet / views (rounds recorded before stamping)."""
+ """``metrics.json`` of a RenderSet: in ``out_dir``, else beside the sheet / views."""
if rs.out_dir:
p = Path(rs.out_dir) / "metrics.json"
if p.is_file():
diff --git a/harness/codeverse3d/spatial/scene_placement.py b/harness/codeverse3d/spatial/scene_placement.py
index ae340275..ccd753de 100644
--- a/harness/codeverse3d/spatial/scene_placement.py
+++ b/harness/codeverse3d/spatial/scene_placement.py
@@ -1,35 +1,5 @@
-"""Scene placement gate ``scene_placement``: floating / sunken / unsupported /
-interpenetrating assets, measured — not judged.
-
-Added 2026-08-26. Audit that day: the scene track had NO deterministic placement
-check (``probes.py`` reported 2-D zone-footprint overlap as INFO; the census
-``ground_y`` fed camera checks only); the scene_v1 ``floating_part`` cap (kinds
-floating / sunken / unsupported, gate ``*``) could never fire because no scene gate
-emitted those words; ``contracts/plan.py`` declared acceptance ``how: probe`` that
-nothing probed; in 52 recorded scene sessions the object tools ``check_connectivity``
-/ ``measure`` were called 0 times (they fail on a scene workspace). Floating /
-sunken was left to the VLM (defect −0.06).
-
-Numbers come from ``runtime_js/lib/host_placement.mjs`` (per placed asset: foot-column
-gap to the surface beneath, burial depth, water, contacts; 3-D interpenetration pairs),
-carried in the probe census under ``placement``; this module turns them into
-``GateFinding`` rows whose messages contain the cap words and whose ``fix_hint`` names
-the move ("lower X by 0.23 m onto Terrain"). Sunk is judged relative to the asset's
-height and its name words because the harness's own starter scene buries rocks
-20–50 % of their height, digs a pond basin 1.4 m under the terrain and drives jetty
-posts 0.97 m into the pond bed — a naive "> 0.10 m" rule flagged all of them
-(measured 2026-08-26). Word matching is a set lookup on ``to_snake`` words.
-
-Thresholds are ``Settings.placement`` (``config.Placement``), read when the gate RUNS: the owner
-asked for stricter contact standards on 2026-10-14 (D105) and the defaults are those — floating
-ERROR at 0.08 m or more than 2 floaters, sunk ERROR 0.20 m + 20 % of the height, interpenetration
-WARN at 10 % / ERROR at 35 % of the smaller box — while a variant or an A/B arm sets its own
-through ``C3D_PLACEMENT__*`` and the summary INFO finding records what a round was judged by.
-Two findings the strict pass added: ``free_exempt`` (the share of assets tagged
-``placement='free'`` — w1_tearoom, 2026-10-13, tagged 17 of 36 and passed) and ``cantilevered``
-(seated on one foot column of four or more while the others hang). Every per-asset finding
-carries ``data.bbox`` (GLB-frame centre + size) so the judge's contact crops can be aimed at it.
-"""
+"""Scene placement gate ``scene_placement``: floating / sunken / unsupported / interpenetrating
+assets, measured — not judged."""
from __future__ import annotations
@@ -53,32 +23,14 @@ if TYPE_CHECKING:
log = logging.getLogger(__name__)
GATE = "scene_placement"
-#: The metres / fractions that grade a row are ``Settings.placement`` (``config.Placement``), taken
-#: at call time — ``placement_findings(thresholds=…)``, default ``get_settings().placement`` — never
-#: at import, so an A/B child's ``C3D_PLACEMENT__FLOATING_ERROR_M`` is what its rounds are judged by.
-#: The JS probe keeps its own measurement constants (host_placement.mjs CONTACT_TOL_M / FLOATING_M /
-#: SUNK_M / OVERLAP_MIN_FRAC): those decide what is MEASURED, these decide severities.
MAX_FINDINGS_PER_KIND = 8
-#: ``free_exempt`` needs this many ``placement='free'`` rows before their share is a finding: one
-#: hanging lantern among two placed things is 50 % and would cap a correct scene (scene caps a
-#: free_exempt ERROR at 0.75). The case it exists for — w1_tearoom, argon, 2026-10-13 — tagged 17.
FREE_EXEMPT_MIN_ROWS = 2
-#: ``cantilevered`` needs this many foot columns resting on at most this many: a crate seated by its
-#: lowest corner on a slope rests on 1 of 4 (what seating by the lowest vertex produces); a level box
-#: on a planar slope rests on an edge, 2 columns, and is not flagged.
CANTILEVER_MIN_COLUMNS, CANTILEVER_MAX_RESTING = 4, 1
-#: setting / environment words that make a scene "indoors" (tighter floating tolerance)
INDOOR_WORDS = frozenset({
"attic", "basement", "bathroom", "bedroom", "cabin", "cellar", "chamber", "classroom", "cockpit", "corridor", "garage", "hall", "hut", "indoor",
"indoors", "inside", "interior", "kitchen", "lab", "laboratory", "library", "lobby", "office", "room", "studio", "tent", "warehouse", "workshop",
})
-#: What counts as seated, ONE file shared with the boot-time settle (``host_placement.settleScene``),
-#: so the gate never reports what the settle deliberately leaves (audit 2026-09-24 N27): name words
-#: exempt from "sunken" — below ground by definition (``buried_ok``), following the terrain
-#: (``slope_ok``), or driven / grown in up to ``partial_ok_frac`` of their height (``partial_ok``).
-#: The settle's other acceptance — a floating asset that touches a neighbour is mounted on it — is
-#: ``AssetRow.attached`` here.
PLACEMENT_WORDS = "placement_words.json"
@@ -97,8 +49,7 @@ def _seated_words() -> _SeatedWords:
def _nums(v: object) -> list[float] | None:
- """Three numbers, or None: a census group with no geometry measures its box as nulls
- (sota_sydney_opera's HarbourBridgeZone), which must skip a check, not crash the gate."""
+ """Three numbers, or None."""
if not isinstance(v, list | tuple) or len(v) != 3:
return None
try:
@@ -161,8 +112,7 @@ class AssetRow(BaseModel):
return size[1] if size else 0.0
def bbox_data(self) -> dict[str, list[float]] | None:
- """``{"center", "size"}`` of the row's box in the GLB frame, on every per-asset finding: the
- judge's contact crops (judges/prompt_builder.plan_detail_crops) are aimed at it."""
+ """``{"center", "size"}`` of the row's box in the GLB frame, on every per-asset finding."""
b = self.bbox or {}
lo, hi = _nums(b.get("min")), _nums(b.get("max"))
if lo is None or hi is None:
@@ -177,14 +127,12 @@ class Interpenetration(BaseModel):
b: str
zone_a: str = ""
zone_b: str = ""
- aabb_overlap: float = 0.0 # box overlap / smaller box (the reported number)
- inside_frac: float = 0.0 # vertices of the smaller inside the larger (the confirmation)
+ aabb_overlap: float = 0.0
+ inside_frac: float = 0.0
class SceneryRoots(BaseModel):
- """The roots outside every marked zone (D111): env scenery, a zone's stray ``scene.add`` — never
- rows and never paired with each other; their pieces support, bury, hold (``attached``) and clip
- the zone assets, but are not measured as placed things themselves."""
+ """The roots outside every marked zone."""
model_config = ConfigDict(extra="ignore")
@@ -214,30 +162,18 @@ def _words(name: str) -> set[str]:
def infer_indoor(text: str) -> bool:
- """Does the plan's setting / environment text say the scene is indoors? (The word
- list is the fallback for a plan written before ``ScenePlan.interior`` existed; the
- typed flag wins — :func:`is_interior`.)"""
+ """True when the plan's setting / environment text names an indoor word (fallback for plans without ``ScenePlan.interior``)."""
return bool(_words(text) & INDOOR_WORDS)
def is_interior(plan: Any) -> bool:
- """The plan's typed ``interior`` flag (D69) whenever it has one, True OR False; the setting
- text only for a plan without it (absent or None — a plan.json older than the field).
-
- It used to be ``bool(flag) or infer_indoor(...)``, so ``interior: False`` lost to the word
- list: a zone named ``GiantTrunkCorridor`` snake-splits to "corridor", and "hold the frame
- luminance inside 0.42-0.62" says "inside". 6 of 26 outdoor plans of argon loop iteration 5
- were measured at the 2 cm indoor tolerance — three 4-5 cm gaps in a redwood forest became
- ``floating`` ERRORs and a 0.60 gate cap (D112)."""
+ """The plan's typed ``interior`` flag whenever it has one, True OR False."""
flag = plan.get("interior") if isinstance(plan, dict) else getattr(plan, "interior", None)
if isinstance(flag, bool):
return flag
return infer_indoor(setting_text(plan))
-#: the fix hints / messages that name a language's API, per scene language (``census["language"]``;
-#: a census without one is three.js, as every recorded round is). The checks and their numbers
-#: are the same for every language; only the words that tell the author what to type differ.
LANGUAGE_WORDS: dict[str, dict[str, str]] = {
"scene_threejs": {
"seat": "seat it with heightAt(x, z) or on the surface it stands on",
@@ -309,11 +245,8 @@ def _sunk_severity(row: AssetRow, p: Placement) -> Severity | None:
def _cantilever(row: AssetRow, p: Placement) -> bool:
- """Seated on at most ``CANTILEVER_MAX_RESTING`` of ≥ ``CANTILEVER_MIN_COLUMNS`` foot columns while
- another hangs past the outdoor floating tolerance: a crate seated by its lowest corner on a slope,
- a bench with one leg on a rock. ``gap_max_m`` / ``columns_resting`` are the column measures
- host_placement.mjs added on 2026-10-14; a row measured before says nothing. Slope-following names
- (stairs, ramps, paths — placement_words.json) meet the ground unevenly by construction."""
+ """Seated on at most ``CANTILEVER_MAX_RESTING`` of ≥ ``CANTILEVER_MIN_COLUMNS`` foot columns
+ while another hangs past the outdoor floating tolerance."""
if row.columns < CANTILEVER_MIN_COLUMNS or row.columns_resting is None or row.gap_max_m is None:
return False
if row.columns_resting > CANTILEVER_MAX_RESTING or row.gap_max_m <= p.floating_outdoor_m:
@@ -323,10 +256,7 @@ def _cantilever(row: AssetRow, p: Placement) -> bool:
def _asset_findings(rows: list[AssetRow], *, p: Placement, floating_m: float, ground_y: float | None,
words: dict[str, str], indoor: bool = False) -> list[GateFinding]:
- """A floating / unsupported row states its gap to the millimetre and the tolerance it was
- measured against (D112): "floating 0.05 m" for a 0.048 m gap in a forest the prompt calls
- outdoors (0.05 m tolerance) read as a contradiction, and the refine session of iteration 5
- r1_07 spent its whole window paging a 3 772-line probe dump to resolve it."""
+ """A floating / unsupported row states its gap to the millimetre and the tolerance it was measured against."""
out: list[GateFinding] = []
tolerance = f"{'indoor' if indoor else 'outdoor'} tolerance {floating_m:.2f} m"
floating: list[tuple[AssetRow, float]] = []
@@ -342,11 +272,10 @@ def _asset_findings(rows: list[AssetRow], *, p: Placement, floating_m: float, gr
gap = row.ground_gap_m
if gap is None or row.on_water:
continue
- if row.attached: # mounted on what it touches: the settle leaves it, so does the gate
+ if row.attached:
continue
support = _support_label(row, ground_y)
if row.sunk_m > 0 or gap <= p.contact_m:
- # seated at its lowest column — on how many of the others?
if _cantilever(row, p):
out.append(_f(Severity.WARN, f"{q} rests on {row.columns_resting} of its {row.columns} foot columns: the others "
f"hang up to {row.gap_max_m:.2f} m above {support} (tilt {row.tilt_m or 0:.2f} m)",
@@ -379,13 +308,8 @@ def _asset_findings(rows: list[AssetRow], *, p: Placement, floating_m: float, gr
def _pair_findings(pairs: list[Interpenetration], p: Placement, rows: dict[str, AssetRow]) -> list[GateFinding]:
out: list[GateFinding] = []
- # one finding per PAIR OF NAMES, keeping the worst overlap: a zone that stamps four
- # TerracottaPlanters against one arbour used to yield four identical ERRORs
- # (measured on t36_santorini) and flood the refine prompt with one fact
best: dict[tuple[str, str], Interpenetration] = {}
for pr in pairs:
- # the probe reports every pair past its own floor (host_placement OVERLAP_MIN_FRAC = the
- # default overlap_warn); an arm that raises overlap_warn filters here
if pr.aabb_overlap <= p.overlap_warn:
continue
key = tuple(sorted((f"{pr.zone_a}/{pr.a}", f"{pr.zone_b}/{pr.b}")))
@@ -405,11 +329,7 @@ def _pair_findings(pairs: list[Interpenetration], p: Placement, rows: dict[str,
def _free_exempt_finding(t: PlacementTable, p: Placement, words: dict[str, str]) -> GateFinding | None:
- """One finding per report: the share of placed assets tagged ``placement='free'`` — exempt from
- every check — among the assets that would otherwise have been checked. The tag is for hanging
- and airborne things; it is also the one line that silences the gate, and the hint on every
- floating finding names it. Measured on w1_tearoom (argon, 2026-10-13): 17 of 36 placed things
- tagged free, the gate's only finding a sunken shoji screen."""
+ """One finding per report."""
free = [r for r in t.assets if r.exempt == "free"]
n = t.checked + len(free)
if len(free) < FREE_EXEMPT_MIN_ROWS or n == 0:
@@ -426,8 +346,7 @@ def _free_exempt_finding(t: PlacementTable, p: Placement, words: dict[str, str])
def _cap_per_kind(findings: list[GateFinding]) -> list[GateFinding]:
- """Keep the worst ``MAX_FINDINGS_PER_KIND`` per kind (ERROR first, then magnitude); the
- rest becomes one INFO line, so 30 floating pebbles cannot flood the refine prompt."""
+ """Keep the worst ``MAX_FINDINGS_PER_KIND`` per kind (ERROR first, then magnitude)."""
rank = {Severity.ERROR: 0, Severity.WARN: 1, Severity.INFO: 2}
by_kind: dict[str, list[GateFinding]] = {}
for f in findings:
@@ -443,14 +362,12 @@ def _cap_per_kind(findings: list[GateFinding]) -> list[GateFinding]:
return out
-#: the per-asset kinds the summary counts (``free_exempt`` is one finding per report, counted apart)
ASSET_KINDS = ("floating", "sunken", "unsupported", "interpenetration", "cantilevered")
def placement_findings(table: dict[str, Any] | PlacementTable, *, indoor: bool = False, language: str | None = None,
thresholds: Placement | None = None) -> GateReport:
- """The ``scene_placement`` GateReport for one census placement table: pure given ``thresholds``,
- which default to the process's ``Settings.placement`` (read now, not at import)."""
+ """The ``scene_placement`` GateReport for one census placement table."""
t = table if isinstance(table, PlacementTable) else PlacementTable.model_validate(table or {})
if t.error:
return GateReport.of(GATE, [
@@ -464,8 +381,6 @@ def placement_findings(table: dict[str, Any] | PlacementTable, *, indoor: bool =
+ _pair_findings(t.interpenetrations, p, {r.qualified: r for r in t.assets}))
free = _free_exempt_finding(t, p, words)
findings = _cap_per_kind(raw) + ([free] if free is not None else [])
- # `counts` are what was MEASURED, `listed` what survived the per-kind cap: the judge's measured
- # block and the loop's diagnosis read the first, the refine prompt shows the second
counts = {k: sum(1 for f in raw if f.data.get("kind") == k) for k in ASSET_KINDS}
listed = {k: sum(1 for f in findings if f.data.get("kind") == k) for k in ASSET_KINDS}
n_free = sum(1 for r in t.assets if r.exempt == "free")
@@ -492,37 +407,17 @@ def placement_findings(table: dict[str, Any] | PlacementTable, *, indoor: bool =
# --------------------------------------------------------------------------- plan-aware checks
-#: measured 2026-08-30 across the 48 scored runs of the four scene batteries: the top
-#: standing defects are exactly the ones nothing measured — thin_atmosphere 32/48 and
-#: undressed_scene 31/48 while the census already records ``fog`` / ``background`` and
-#: every placed asset's name, zone and bbox. These checks are pure functions of the
-#: census + the plan; their ERRORs route into refine with the zone as the target.
SCALE_WARN, SCALE_ERROR = 2.5, 4.0
-#: linear fog must reach past the plan's far side (fog far >= this many plan spans); exp fog
-#: must not dissolve it (1/density >= span / this)
FOG_FAR_MIN_SPANS, FOG_DENSITY_MAX_PER_SPAN = 2.0, 1.5
-#: the tolerance on a PLANNED asset's position against the plan bounds: ``max(this, 10 % of the
-#: span)``. Generous on purpose (owner, 2026-10-15): the bounds are where the plan's named
-#: contents are measured, not a wall the place stops at — scenery past them is the world
-#: continuing, which ``world_edge`` below asks for.
BOUNDS_MARGIN_MIN_M = 5.0
BOUNDS_MARGIN_FRAC = 0.10
-#: the world continues past the bounds: outdoors, something standing (``WORLD_EDGE_MIN_HEIGHT_M``
-#: or taller — terrain, buildings, trees, walls, cliffs, whatever the place has) reaches past this
-#: multiple of the bounds half-extent, or the edge of the built world is in view from every camera
-#: that looks outward (world_edge_visible stood in 11/19 scene_final_v1 verdicts). 1.25x the
-#: half-extent is a deliberately lenient floor; WHAT continues the place is the brief's choice,
-#: and the fog gate covers the far distance.
WORLD_EDGE_REACH_FACTOR = 1.25
WORLD_EDGE_MIN_HEIGHT_M = 2.0
-#: stamped ring (host_census `stamps`): copies, where the ring sits relative to the plan's
-#: half-extent, and how even / alike it must be before it is called stamped
RING_MIN_COPIES = 8
RING_BACKDROP_FRAC = 0.6
RING_RADIUS_CV_MAX = 0.08
RING_GAP_CV_MAX = 0.25
-RING_SIZE_CV_MAX = 0.25 # loop 24's ski station: 32 peaks, radius spread 0.8 %, SIZE spread 15 % — still "identical pyramids stamped in a ring" to the judge
-#: the two hints that name no language API — the same words for both scene languages
+RING_SIZE_CV_MAX = 0.25
RING_HINT = ("break the pattern — uneven spacing, mixed sizes and silhouettes, clusters and gaps — or close the distance "
"some other way the place suggests (a ridge line, a treeline, buildings, open water); the check calls a ring "
"when >= {min_n} copies have radius spread <= {rcv:.0%}, spacing spread <= {gcv:.0%} and size spread <= {scv:.0%}")
@@ -574,7 +469,7 @@ def _plan_bounds(plan: Any) -> tuple[tuple[float, ...], tuple[float, ...]] | Non
def _layout_budget(layout: Any) -> int:
- """Total things the L2 layout put in the zone: placements + dressing counts."""
+ """Total things the L2 layout put in the zone."""
if layout is None:
return 0
get = layout.get if isinstance(layout, dict) else lambda k, d=0: getattr(layout, k, d)
@@ -588,37 +483,17 @@ def _layout_budget(layout: Any) -> int:
def _row_names(row: AssetRow) -> str:
- """The row's own name plus its named descendants, snake-cased for loose matching.
-
- A zone that wraps its content in one group ("IslandAssembly") used to hide every
- planned asset from this check: `eval/bench/out/scene_fixed` (2026-09-05) reported three
- floating_islands zones as "missing planned contents: FloatingRock, Windmill, SkyPine"
- while the zone module built each one and named it exactly that, one level down.
- """
+ """The row's own name plus its named descendants, snake-cased for loose matching."""
return " ".join(to_snake(n) for n in [row.name, *row.inner])
def contract_findings(census: dict[str, Any] | None, plan: Any,
layouts: dict[str, Any] | None = None, unavailable: Sequence[str] = ()) -> list[GateFinding]:
- """Deterministic plan-vs-census checks: env atmosphere present, the world continuing
- past the bounds, every zone dressed with its planned contents, plausible scale, planned
- contents inside the world bounds — and, when a zone has an L2 layout, an INFO line with
- its census count against that layout's own budget.
-
- ``unavailable`` = assets the asset stage could not build (the zones were told
- "NOT AVAILABLE — do not reference"): a zone is not missing what it was told not to
- place. Measured 2026-09-07 (ab_temple_hero): the ERROR "missing planned contents:
- BronzeCenser" recurred every round for a hero that never existed, with the hint
- "clone its GLB"."""
+ """Deterministic plan-vs-census checks."""
if not isinstance(census, dict) or plan is None:
return []
words = placement_words(census.get("language"))
out: list[GateFinding] = []
- # -- density, as a NOTE: the census count against the L2 layout's own budget. Until
- # 2026-10-15 a zone under half its budget was an ERROR ("underdressed"), which made the
- # layout's prop / ground-cover bands a requirement the brief never stated (owner's rule:
- # the harness states requirements, not templates). The counts a brief DOES state are
- # its acceptance items, verified by name by the judge; this line only informs.
groups = {to_snake(g.get("name", "")): g for g in (census.get("groups") or [])
if isinstance(g, dict)}
for zone_name, layout in (layouts or {}).items():
@@ -633,16 +508,11 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
f"(placements + props + ground cover) — a note, not a requirement: the counts the brief "
"states are its acceptance items",
target=zone_name, kind="density_note", have=have, budget=budget))
- # -- atmosphere: the two env facts the census measures on every boot
if "fog" in census and census.get("fog") is None:
out.append(_f(Severity.ERROR, words["no_fog_msg"], target="env", kind="no_fog", hint=words["no_fog"]))
if "background" in census and census.get("background") is None:
out.append(_f(Severity.ERROR, words["no_background_msg"], target="env", kind="no_background",
hint=words["no_background"]))
- # -- fog that ends inside the world: measured 2026-09-08 over eleven exterior runs, every
- # one with fog far >= 2 x the plan span scored >= 0.60 and the three at 1.4-1.6 x scored
- # 0.42-0.60 with "no aerial perspective", "world edge", "backdrop floating in the sky" —
- # past fog far the land is the background colour while the unfogged sky stays sharp
fog = census.get("fog")
pb = _plan_bounds(plan)
if isinstance(fog, dict) and pb and not is_interior(plan):
@@ -658,11 +528,6 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
"stays sharp: a world edge and backdrops floating in the sky",
target="env", kind="fog_short", fog=fog, plan_span_m=round(span, 1),
hint=words["fog_far"].format(need=FOG_FAR_MIN_SPANS * span, spans=FOG_FAR_MIN_SPANS)))
- # -- a stamped ring: >= 8 same-size copies evenly on a circle round the world's edge.
- # Five of six exteriors on 2026-09-09 drew their horizon as "a ring of identical cones
- # stamped round the perimeter" / "rocks in a perfect circle" and the judge called each a
- # toy backdrop, twice. The census measures the ring (host_census `stamps`); a rotunda's
- # columns or chairs round a table sit INSIDE the content and are not it.
bounds = _plan_bounds(plan)
if bounds and isinstance(census.get("groups"), list):
lo, hi = bounds
@@ -683,11 +548,6 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
radius_cv=rcv, gap_cv=gcv, size_cv=scv,
hint=RING_HINT.format(min_n=RING_MIN_COPIES, rcv=RING_RADIUS_CV_MAX, gcv=RING_GAP_CV_MAX,
scv=RING_SIZE_CV_MAX)))
- # -- the world continues past the bounds (outdoors): a WARN-level note when nothing standing
- # reaches past WORLD_EDGE_REACH_FACTOR x the half-extent. Until 2026-10-15 this was the
- # "no_backdrop" ERROR whose hint prescribed a silhouette ring of 24-40 pieces — the one
- # construction 57 of 59 iteration-0 plans then built. The measurement is unchanged; what
- # continues the place is the brief's.
groups = census.get("groups")
if bounds and isinstance(groups, list) and not is_interior(plan):
lo, hi = bounds
@@ -715,18 +575,11 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
rows = [AssetRow.model_validate(r) for r in (table.get("assets") or [])] if table else []
if not rows:
return out
- # -- every zone dressed with what the plan put there (names matched loosely on words)
by_zone: dict[str, list[AssetRow]] = {}
for r in rows:
by_zone.setdefault(to_snake(r.zone), []).append(r)
all_names = " ".join(_row_names(r) for r in rows)
gone = {to_snake(u) for u in unavailable}
- # a table cut by its row cap (host_placement MAX_ASSETS: rows are written zone by zone, in scene
- # order) stops wherever it stops: a zone past the cut has no rows although the census holds its
- # built group, and the zone AT the cut (the last row's) has only its first rows (iteration 4,
- # r1_01: an envelope of 337 meshes filled the table and ScooterParkingNook, built and visibly
- # present, was "zone_empty"). A table cut by its time budget still writes a row per asset
- # (exempt "time_budget"), so a zone with no row there really placed nothing.
cut = bool(table.get("truncated")) and int(table.get("total") or 0) > len(rows)
at_cut = to_snake(rows[-1].zone) if cut else None
built = {to_snake(str(g.get("name", ""))) for g in census.get("groups") or []
@@ -734,8 +587,6 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
for zone_name, contents in _plan_zones(plan):
zk = to_snake(zone_name)
placed = by_zone.get(zk, [])
- # what the zone was allowed to place: an asset the asset stage never built was
- # announced "NOT AVAILABLE" to it, for zone_empty exactly as for missing_content
expected = [c for c in contents if to_snake(c) not in gone]
if not placed and expected and cut and zk in built:
out.append(_f(Severity.INFO, f"zone {zone_name} was not measured: the placement table was truncated before "
@@ -760,7 +611,6 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
hint=f"place each listed asset ({words['place']}) inside this "
f"zone's bbox, {words['in_zone']}, AND give the object the plan's name for it — every gate and the "
"judge find it by that name, so a lantern called 'LanternPost1' reads as absent"))
- # -- plausible scale vs the plan's approx_size_m
sizes = _plan_asset_sizes(plan)
for r in rows:
size = _nums((r.bbox or {}).get("size"))
@@ -770,8 +620,6 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
key = next((k for k in sizes if k in rk), "")
if not key:
continue
- # a wrapper of instances is measured as ONE instance: the plan sized the fence panel, the
- # row is the whole run (host_placement `families`)
n, measured = r.instance_size(key)
what = f"each of the {n} {key} instances in {r.qualified}" if n else r.qualified
if not n:
@@ -786,12 +634,6 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
out.append(_f(sev, f"{what} measures {measured:.2f} m but the plan sized {key} at ~{sizes[key]:.2f} m ({f:.1f}x)",
target=r.qualified, kind="scale", factor=round(f, 2), zone=r.zone, instances=n, bbox=r.bbox_data(),
hint=f"scale {'each ' + key if n else r.name} so its largest dimension is ~{sizes[key]:.2f} m as planned"))
- # -- PLANNED contents inside the world bounds: a row carrying a planned asset's name (matched
- # the way missing_content matches it) is measured against the bounds + a generous margin,
- # as a WARN. Anything else past the bounds — the rest of the street, outlying trees, the far
- # shore — is the place continuing, which the world_edge check asks for, and is not reported.
- # Until 2026-10-15 every placed row outside bounds + max(2 m, 5 %) was an ERROR: with the
- # world-edge check that left a ring round the centre as the only legal way to continue.
bounds = _plan_bounds(plan)
if bounds:
lo, hi = bounds
@@ -819,9 +661,7 @@ def contract_findings(census: dict[str, Any] | None, plan: Any,
def placement_census(ws: Workspace, probe: Callable[..., SceneProbeResult], *, force_probe: bool = False,
timeout_s: float = 60.0) -> dict[str, Any]:
- """The census dict carrying ``placement``: the last build's ``artifacts/census.json``,
- or a fresh ``probe`` (the language's ``SceneRuntime.probe``) when it is missing / predates
- the table / ``force_probe``."""
+ """The census dict carrying ``placement``."""
census = None if force_probe else read_json_or_none(ws.artifacts / "census.json")
if isinstance(census, dict) and isinstance(census.get("placement"), dict):
return census
@@ -835,36 +675,30 @@ def placement_census(ws: Workspace, probe: Callable[..., SceneProbeResult], *, f
def setting_text(plan: Any) -> str:
- """The plan text the indoor/outdoor rule reads (``setting`` / ``environment`` /
- ``title``), from a plan dict or a ScenePlan; ``""`` for anything else."""
+ """The plan text the indoor/outdoor rule reads (``setting`` / ``environment`` / ``title``),
+ from a plan dict or a ScenePlan."""
if isinstance(plan, dict):
return " ".join(str(plan.get(k) or "") for k in ("setting", "environment", "title"))
return " ".join(str(getattr(plan, k, "") or "") for k in ("setting", "environment", "title"))
def placement_gate(ws: Workspace, census: dict[str, Any] | None, plan: Any) -> GateReport | None:
- """THE ``scene_placement`` verdict: the round's gate (``ScenePipeline.gates``) and the
- ``check_placement`` tool both return it, on the same inputs — the census, the plan and
- what the run's stages recorded in the workspace (the L2 zone layouts, the assets the
- asset stage could not build). Until 2026-09-22 the tool reported
- :func:`placement_findings` alone, so it never showed the plan checks (fog, world edge,
- zone contents, scale, bounds) the round then failed on."""
+ """THE ``scene_placement`` verdict."""
assets = _stage_result(ws, "assets")
unavailable = [name for name, r in assets.items() if isinstance(r, dict) and not r.get("ok", True)]
return placement_gate_safe(census, plan=plan, layouts=_stage_result(ws, "layouts"), unavailable=unavailable)
def _stage_result(ws: Workspace, name: str) -> dict[str, Any]:
- """A cached stage's result (``orchestrator.StageRunner`` writes ``stages/<name>.json``), ``{}`` when absent."""
+ """A cached stage's result (``orchestrator.StageRunner`` writes ``stages/<name>.json``),
+ ``{}`` when absent."""
res = (read_json_or_none(ws.stages / f"{name}.json") or {}).get("result")
return res if isinstance(res, dict) else {}
def placement_gate_safe(census: dict[str, Any] | None, *, plan: Any = None,
layouts: dict[str, Any] | None = None, unavailable: Sequence[str] = ()) -> GateReport | None:
- """Round-gate entry: ``None`` when the census has no placement table (scene did not
- boot, or an older driver), a WARN-only report when anything raises — never an
- exception, so the placement check cannot kill a round."""
+ """Round-gate entry."""
try:
table = (census or {}).get("placement")
if not isinstance(table, dict):
diff --git a/harness/codeverse3d/spatial/sections.py b/harness/codeverse3d/spatial/sections.py
index b17e1a7b..c71541b5 100644
--- a/harness/codeverse3d/spatial/sections.py
+++ b/harness/codeverse3d/spatial/sections.py
@@ -1,16 +1,4 @@
-"""Cross-sections of the canonical GLB, drawn ONE way.
-
-Every part is sectioned with an axis-aligned plane, its loops combined with the
-even-odd rule (shapely, so a hollow tube keeps its hole) and drawn with matplotlib:
-one colour per instance group, a legend, a scale bar, and the pairwise in-plane
-overlaps as darkened blends. Two callers:
-
-* ``judge_slices`` (D48) — the judge's conditional interior evidence: two vertical
- centre slices where ONLY connectivity-gate-ERROR part pairs get a red hatch,
- written with a typed :class:`SliceManifest`;
-* ``cross_section`` — the agent tool: any axis, any position, plus loop / area /
- hollow-ratio numbers. It drew its own PIL picture until 2026-09-22.
-"""
+"""Cross-sections of the canonical GLB, drawn ONE way."""
from __future__ import annotations
@@ -26,7 +14,6 @@ from codeverse3d.spatial.measure import GlbLoadError, instance_groups, solid_par
from codeverse3d.spatial.registry import Observation
_AXES = "xyz"
-#: the (horizontal, vertical) axes drawn for each slicing axis
_PLANE_AXES = {0: (2, 1), 1: (0, 2), 2: (0, 1)}
@@ -49,9 +36,8 @@ def cross_section(
*,
parts: Sequence[str] | None = None,
) -> Observation:
- """Slice the GLB at ``axis = at`` (a fraction of the selected parts' bbox) → the
- judge-style section image + loop / filled-area / hollow-ratio numbers. A plane that
- cuts nothing answers in text, with no image."""
+ """Slice the GLB at ``axis = at`` (a fraction of the selected parts' bbox) → the judge-style
+ section image + loop / filled-area / hollow-ratio numbers."""
axis = axis.lower()
if axis not in _AXES:
return Observation.error(f"axis must be one of x|y|z, got {axis!r}")
@@ -89,23 +75,17 @@ def cross_section(
return Observation(ok=True, text=text, numbers=numbers, images=images)
-# ===================================================================== judge slices (D48)
-#: the two centre planes the judge slice channel cuts (name → plane-normal axis index,
-#: horizontal axis index, human title, axes note). Vertical is Y (up) on both.
+# ===================================================================== judge slices
JUDGE_SLICE_PLANES: dict[str, tuple[int, int, str, str]] = {
"front_back": (0, 2, "front-back",
"horizontal = front-back (Z, front right), vertical = up (Y); cut at centre x"),
"left_right": (2, 0, "left-right",
"horizontal = left-right (X), vertical = up (Y); cut at centre z"),
}
-#: F1: only part pairs the connectivity gate measured as ERROR get this fill + hatch
_OVERLAP_FACE = "#ff1a1a"
-#: legend rows (instance groups) drawn before the "… +n more parts" row
JUDGE_SLICE_LEGEND_MAX = 16
-#: F4: a slice whose effective section area is under this fraction of the cut parts'
-#: projected-silhouette area is dropped (the plane mostly misses the object)
DEGENERATE_SLICE_FRAC = 0.05
-_HULL_SAMPLE = 4000 # vertex subsample for projected-silhouette convex hulls (seeded rng)
+_HULL_SAMPLE = 4000
class SliceOverlapPair(BaseModel):
@@ -117,7 +97,7 @@ class SliceOverlapPair(BaseModel):
class JudgeSlice(BaseModel):
- """One rendered (or dropped) judge slice; ``png`` is a file name beside the manifest."""
+ """One rendered (or dropped) judge slice."""
name: str
rendered: bool
@@ -131,12 +111,7 @@ class JudgeSlice(BaseModel):
class SliceManifest(BaseModel):
- """What ``judge_slices`` rendered and why — the provenance record beside the PNGs.
-
- ``hatched_pairs`` (F1: gate-ERROR only) vs ``plain_pairs`` (every other in-plane
- overlap, drawn as a darkened blend with no callout) is what makes a judge's
- "visible in slice n" citation auditable after the fact.
- """
+ """What ``judge_slices`` rendered and why — the provenance record beside the PNGs."""
glb: str
slices: list[JudgeSlice] = Field(default_factory=list)
@@ -149,8 +124,7 @@ class SliceManifest(BaseModel):
def _loops_2d(mesh: trimesh.Trimesh, origin: np.ndarray, axis: int, horiz: int, vert: int,
tol: float) -> tuple[list[np.ndarray], list[np.ndarray]]:
- """Section ``mesh`` with the axis-aligned plane through ``origin``; return (closed,
- open) 2D polylines in (``horiz``, ``vert``) (closed = endpoints within ``tol``)."""
+ """Section ``mesh`` with the axis-aligned plane through ``origin``."""
normal = np.zeros(3)
normal[axis] = 1.0
try:
@@ -175,9 +149,8 @@ def _loops_2d(mesh: trimesh.Trimesh, origin: np.ndarray, axis: int, horiz: int,
def _cut(parts: dict[str, trimesh.Trimesh], origin: np.ndarray, axis: int, horiz: int, vert: int,
tol: float) -> tuple[dict[str, Any], dict[str, list[np.ndarray]], dict[str, int]]:
- """Every part on one plane → (part → even-odd shapely polygon, part → outline-only
- polylines, part → number of section loops). A non-watertight / non-loop section
- falls back to raw outline strokes for that part (no fill, no overlap test)."""
+ """Every part on one plane → (part → even-odd shapely polygon, part → outline-only polylines,
+ part → number of section loops)."""
sections: dict[str, Any] = {}
strokes: dict[str, list[np.ndarray]] = {}
loops: dict[str, int] = {}
@@ -200,15 +173,12 @@ def _frame(parts: dict[str, trimesh.Trimesh]) -> tuple[np.ndarray, float, float,
bounds = np.array([[min(p.bounds[0][i] for p in parts.values()) for i in range(3)],
[max(p.bounds[1][i] for p in parts.values()) for i in range(3)]])
scale = float((bounds[1] - bounds[0]).max())
- # ignore hairline contact slivers (planned joins touch or overlap by design): keep only
- # overlap regions at least ~2·erode thick somewhere — tuned near the connectivity
- # gate's ~10 mm interpenetration ERROR threshold (PENETRATION_ERROR_M)
return bounds, max(scale * 1e-5, 1e-9), (1e-3 * scale) ** 2, max(0.002, 5e-4 * scale)
def _filled_area(sections: dict[str, Any]) -> tuple[float, float]:
- """(material area on the plane, hollow ratio = the share of the outlines' area that
- is a hole)."""
+ """(material area on the plane, hollow ratio = the share of the outlines' area that is a
+ hole)."""
if not sections:
return 0.0, 0.0
from shapely.geometry import Polygon
@@ -222,8 +192,8 @@ def _filled_area(sections: dict[str, Any]) -> tuple[float, float]:
def _overlaps(sections: dict[str, Any], errset: set[frozenset[str]], area_eps: float,
erode: float) -> tuple[list[tuple[str, str, Any]], list[tuple[str, str, Any]]]:
- """Pairwise intersections of the filled section polygons → (gate-ERROR pairs, every
- other pair). F1: only the first get the red hatch."""
+ """Pairwise intersections of the filled section polygons → (gate-ERROR pairs, every other
+ pair)."""
pnames = list(sections)
overlaps: list[tuple[str, str, Any]] = []
plain_overlaps: list[tuple[str, str, Any]] = []
@@ -238,7 +208,7 @@ def _overlaps(sections: dict[str, Any], errset: set[frozenset[str]], area_eps: f
continue
try:
if inter.buffer(-erode).is_empty:
- continue # thinner than ~2·erode everywhere: contact sliver
+ continue
except Exception: # noqa: BLE001
pass
(overlaps if frozenset((a, b)) in errset else plain_overlaps).append((a, b, inter))
@@ -301,7 +271,7 @@ def _slice_patch(geom: Any, **kw: Any) -> Any:
def _hull_area(pts2: np.ndarray) -> float:
- """Convex-hull area of a 2D point set (0.0 for degenerate sets; seeded subsample)."""
+ """Convex-hull area of a 2D point set, 0.0 for degenerate sets."""
pts2 = np.asarray(pts2, dtype=float)
if len(pts2) < 3:
return 0.0
@@ -342,8 +312,7 @@ def _fmt_len(m: float) -> str:
def _colours(names: list[str]) -> tuple[Any, dict[str, str], dict[str, Any]]:
- """(instance groups, part → group, group → tab20 colour): one colour per instance
- group so 40-part objects stay legible, stable across the planes of one object."""
+ """(instance groups, part → group, group → tab20 colour)."""
import matplotlib
matplotlib.use("Agg")
@@ -359,9 +328,7 @@ def _draw(png: Path, sections: dict[str, Any], strokes: dict[str, list[np.ndarra
overlaps: list[tuple[str, str, Any]], plain_overlaps: list[tuple[str, str, Any]],
bounds: np.ndarray, horiz: int, vert: int, colours: tuple[Any, dict[str, str], dict[str, Any]],
*, legend_title: str, title: str) -> None:
- """One section image (~1000 px, white): per-part fills, outline-only strokes, plain
- darkened overlaps, hatched gate-ERROR overlaps, a scale bar and a capped legend,
- framed on the object's full extent in (``horiz``, ``vert``)."""
+ """One section image (~1000 px, white)."""
import matplotlib
matplotlib.use("Agg")
@@ -386,7 +353,7 @@ def _draw(png: Path, sections: dict[str, Any], strokes: dict[str, list[np.ndarra
for lp in lines:
ax.plot(lp[:, 0], lp[:, 1], color=color_of_group[g], linewidth=1.4, zorder=3)
drawn_groups[g] = True # True = outline-only somewhere
- for a, b, inter in plain_overlaps: # F1: not gate-ERROR — darkened blend, no callout
+ for a, b, inter in plain_overlaps:
fill = _slice_patch(inter, facecolor=_mix_dark(color_of_group[group_of[a]],
color_of_group[group_of[b]]),
edgecolor="none", linewidth=0.0, zorder=4)
@@ -402,7 +369,6 @@ def _draw(png: Path, sections: dict[str, Any], strokes: dict[str, list[np.ndarra
if hatch is not None:
ax.add_patch(hatch)
- # frame the drawing on the slice plane's full object extent
h_lo, h_hi = bounds[0][horiz], bounds[1][horiz]
v_lo, v_hi = bounds[0][vert], bounds[1][vert]
pad = 0.06 * max(h_hi - h_lo, v_hi - v_lo, 1e-6)
@@ -411,7 +377,6 @@ def _draw(png: Path, sections: dict[str, Any], strokes: dict[str, list[np.ndarra
ax.set_aspect("equal")
ax.axis("off")
- # scale bar, bottom-left
bar = _nice_scale(h_hi - h_lo + 2 * pad)
y0 = v_lo - pad - 0.03 * (v_hi - v_lo + 2 * pad)
ax.plot([h_lo, h_lo + bar], [y0, y0], color="black", linewidth=3, zorder=6)
@@ -429,7 +394,7 @@ def _draw(png: Path, sections: dict[str, Any], strokes: dict[str, list[np.ndarra
if len(drawn_groups) > JUDGE_SLICE_LEGEND_MAX:
handles.append(Patch(facecolor="white", edgecolor="white",
label=f"… +{len(drawn_groups) - JUDGE_SLICE_LEGEND_MAX} more parts"))
- if overlaps: # F2: factual wording, only ever true for gate-ERROR pairs
+ if overlaps:
handles.append(Patch(facecolor=_OVERLAP_FACE, edgecolor="white",
hatch="////", label="measured overlap (gate ERROR)"))
ax.legend(handles=handles, loc="upper right", fontsize=7, framealpha=0.9,
@@ -445,29 +410,7 @@ def judge_slices(
out_dir: Path | str,
planes: tuple[str, ...] = ("front_back", "left_right"),
) -> SliceManifest:
- """Render the judge's interior cross-section slices (D48) → :class:`SliceManifest`.
-
- Two vertical centre slices of the canonical GLB (Y-up, meters), one PNG each
- (``slice_<name>.png``, ~768 px, white background): per-part fills with a legend
- (instance groups share a row, capped at :data:`JUDGE_SLICE_LEGEND_MAX`), a scale
- bar, and a neutral title. ``error_pairs`` are the connectivity gate's ERROR-level
- penetration part pairs (order inside a pair does not matter):
-
- * F1 — ONLY those pairs get the red fill + white hatch; every other section
- intersection (planned joins, sub-threshold welds) is a plain darkened blend of
- the two part colors, no callout. A hairline contact sliver (thinner than
- ~2×erosion everywhere, tuned near the gate's 10 mm ERROR line) is not drawn.
- * F2 — the legend names the hatch factually: "measured overlap (gate ERROR)".
- * F4 — a degenerate slice (effective section area under
- :data:`DEGENERATE_SLICE_FRAC` of the cut parts' projected silhouette — the plane
- mostly misses the object) is dropped, not rendered, so a case carries 0–2 slices.
-
- A non-watertight / non-loop section falls back to raw outline strokes for that
- part (no fill, no overlap test). Deterministic (seeded subsampling, Agg backend);
- the manifest is written beside the PNGs as ``manifest.json`` with ``png`` fields
- holding bare file names. Needs matplotlib + shapely (the ``mesh`` extra): an
- ImportError propagates to the caller.
- """
+ """Render the judge's interior cross-section slices → :class:`SliceManifest`."""
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
errset = {frozenset(p) for p in (error_pairs or ()) if len(set(p)) == 2}
@@ -498,9 +441,6 @@ def judge_slices(
manifest.slices.append(JudgeSlice(name=name, rendered=False, reason="plane cuts nothing"))
continue
- # F4: degenerate-slice check — effective section area (filled polygons + convex
- # hulls of outline-only stroke sets, so full-size open sections still count) vs
- # the cut parts' projected-silhouette area on the slice plane.
filled_area = sum(g.area for g in sections.values())
stroke_hull_area = sum(
_hull_area(np.vstack(lines)) for p, lines in strokes.items() if p not in sections)
diff --git a/harness/codeverse3d/spatial/sheet.py b/harness/codeverse3d/spatial/sheet.py
index b9f5e06a..51bf2045 100644
--- a/harness/codeverse3d/spatial/sheet.py
+++ b/harness/codeverse3d/spatial/sheet.py
@@ -1,13 +1,4 @@
-"""Contact sheets: a deterministic labelled grid of PNGs (PIL only).
-
-Used for judge inputs and agent observations: one image, every view labelled
-under its tile, fixed tile size so the VLM sees consistent scale.
-
-This module is also the one home for shared PIL drawing bits: ``load_font``,
-:func:`write_gif` and the sheet geometry/palette constants (``LABEL_H``,
-``PAD``, ``BG``, ``LABEL_BG``, ``LABEL_FG``) are public and reused by
-``spatial.gl_render`` and ``judges.images``.
-"""
+"""Contact sheets: a deterministic labelled grid of PNGs (PIL only)."""
from __future__ import annotations
@@ -17,7 +8,6 @@ from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
-#: shared sheet geometry / palette (public — imported by other drawing modules)
LABEL_H = 28
PAD = 6
BG = (250, 250, 250)
@@ -29,11 +19,7 @@ _FONTS_BOLD = ("DejaVuSans-Bold.ttf", "LiberationSans-Bold.ttf", "Arialbd.ttf")
def load_font(size: int = 15, bold: bool = False) -> ImageFont.ImageFont | ImageFont.FreeTypeFont:
- """First available truetype font at ``size`` (PIL default as last resort).
-
- The candidate list covers the fonts present on typical Linux/CI hosts;
- ``bold=True`` prefers the bold faces and falls back to the regular ones.
- """
+ """First available truetype font at ``size`` (PIL default as last resort)."""
names = (*_FONTS_BOLD, *_FONTS) if bold else _FONTS
for name in names:
try:
@@ -55,9 +41,7 @@ def _fit(im: Image.Image, tile_w: int, tile_h: int) -> Image.Image:
def tile_size(tile: int | tuple[int, int], sample: str | Path | None = None) -> tuple[int, int]:
- """Resolve the ``tile`` argument: a square side, an explicit (w, h), or a
- width plus ``sample`` — an image whose aspect ratio the cell should keep
- (how the graphics-track frame sheets stay 16:9)."""
+ """Resolve the ``tile`` argument."""
if isinstance(tile, tuple):
return max(1, int(tile[0])), max(1, int(tile[1]))
tile_w = max(1, int(tile))
@@ -77,14 +61,7 @@ def contact_sheet(
tile: int | tuple[int, int] = 384,
label: bool = True,
) -> Path:
- """Write a grid of ``(label, png_path)`` tiles to ``out`` and return it.
-
- THE sheet builder: object views, scene views and graphics frame sheets all
- come through here. ``tile`` is a square side or an explicit ``(w, h)`` cell
- (see :func:`tile_size`). Missing/unreadable images become a grey tile with
- the label so the sheet never silently drops a view. Output is deterministic
- for identical inputs.
- """
+ """Write a grid of ``(label, png_path)`` tiles to ``out`` and return it."""
if not images:
raise ValueError("contact_sheet: no images")
tile_w, tile_h = tile_size(tile)
@@ -120,11 +97,7 @@ def contact_sheet(
def write_gif(frames: Sequence[str | Path], out: Path | str, *, fps: int = 12, width: int | None = None) -> Path:
- """Animated GIF from ``frames`` (adaptive 128-colour palette, looping).
-
- THE gif writer (the graphics preview; ``width`` downscales with BILINEAR).
- Raises ``ValueError`` without frames.
- """
+ """Animated GIF from ``frames`` (adaptive 128-colour palette, looping)."""
if not frames:
raise ValueError("write_gif: no frames")
ims = []
@@ -148,11 +121,7 @@ def montage_2x2(
out: Path | str,
tile: int = 512,
) -> Path:
- """A labelled ≤ 2×2 grid (1–4 tiles) — the judge-facing montage format.
-
- VLM judges get position-biased and saturate with many tiles, so judge
- images carry at most four views each. Raises ``ValueError`` above 4.
- """
+ """A labelled ≤ 2×2 grid (1–4 tiles) — the judge-facing montage format."""
if not 1 <= len(images) <= MONTAGE_MAX_TILES:
raise ValueError(f"montage_2x2: need 1..{MONTAGE_MAX_TILES} tiles, got {len(images)}")
cols = 1 if len(images) == 1 else 2
@@ -166,12 +135,8 @@ def crop_region(
*,
min_px: int = 512,
) -> Path:
- """Crop ``src`` to the fractional box ``(left, top, right, bottom)`` (0..1) and
- upscale so the long side is ≥ ``min_px`` (a "detail crop" for judges).
-
- Returns ``out``. Raises ``ValueError`` for an empty box, ``OSError`` for an
- unreadable image.
- """
+ """Crop ``src`` to the fractional box ``(left, top, right, bottom)`` (0..1) and upscale so
+ the long side is ≥ ``min_px`` (a "detail crop" for judges)."""
x0, y0, x1, y1 = (max(0.0, min(1.0, float(v))) for v in box_frac)
if x1 <= x0 or y1 <= y0:
raise ValueError(f"crop_region: empty box {box_frac}")
diff --git a/harness/codeverse3d/spatial/silhouette.py b/harness/codeverse3d/spatial/silhouette.py
index 11526f0a..5b3d5b24 100644
--- a/harness/codeverse3d/spatial/silhouette.py
+++ b/harness/codeverse3d/spatial/silhouette.py
@@ -1,23 +1,4 @@
-"""Silhouette comparison between a render and a reference image.
-
-Foreground mask (documented limits):
-* PNG with an alpha channel → ``alpha > 0`` (renders on transparent background).
-* Otherwise the background colour is the median of the border pixels; pixels
- farther than ``tol`` from it are "object-coloured", and the background region
- is the flood fill from the image border through non-object pixels. Enclosed
- pockets therefore count as *foreground* (a chair's back is one silhouette),
- which is what we want for shape comparison but hides interior holes.
-* Works for silhouette-mode renders and product photos on a plain backdrop.
- Shaded renders with a contact shadow include the shadow in the mask (pale
- objects on pale studio backdrops are the weak case — always render the
- *render* side in ``silhouette`` mode); textured / gradient backgrounds
- over-segment (``reliable`` becomes False when a fill is < 0.2 % or > 95 %).
-
-IoU is computed on **bbox-normalised** masks at 256² (each silhouette cropped
-to its bounding box and scaled to fit, aspect preserved), so framing and scale
-differences do not dominate — ``aspect_ratio_err`` carries the shape-proportion
-signal separately.
-"""
+"""Silhouette comparison between a render and a reference image."""
from __future__ import annotations
@@ -35,20 +16,10 @@ from codeverse3d.contracts.spec import ReferenceImage, Spec
from codeverse3d.conventions import views_by_preference
MASK_SIZE = 256
-#: colour-distance tolerance (0-441) from the border colour: adaptive between these bounds
-#: (≈ BORDER_TOL_BASE + BORDER_TOL_K × border std), so flat backdrops get a tight threshold
BORDER_TOL_MIN = 10.0
BORDER_TOL_MAX = 40.0
BORDER_TOL_K = 4.0
_MIN_FILL = 0.002
-#: a mask whose BOUNDING BOX spans essentially the whole frame localised nothing, however
-#: much or little area it covers. Measured 2026-08-25 over the 21 reference photos in
-#: astra3d-brilliana/references_images: 9 of them (coffee_cup, flower, flower_2, F1 car,
-#: blackberry, disney_land, ferris_wheel, micky_character, sc2_protoss) flood-filled to
-#: corner-to-corner masks — a coffee cup on a table read as 73.8 % "object" — while the
-#: area test passed every one of them, because it only rejects fills above 95 %. Real
-#: single-view renders sit at 0.60-0.69 here and the closest surviving photo at 0.969, so
-#: the bar has room on both sides.
_MAX_BBOX_COVER = 0.98
@@ -92,10 +63,7 @@ def _flood_outside(bg_like: np.ndarray) -> np.ndarray:
def foreground_mask(path: Path | str, size: int = MASK_SIZE, tol: float | None = None) -> np.ndarray:
- """Boolean foreground mask (≤ size², aspect preserved). See module docstring.
-
- ``tol`` overrides the adaptive colour tolerance (useful for tests).
- """
+ """Boolean foreground mask (≤ size², aspect preserved)."""
rgba = _load_rgba(path, size)
alpha = rgba[..., 3]
if alpha.min() < 250: # has real transparency → trust it
@@ -113,12 +81,7 @@ def foreground_mask(path: Path | str, size: int = MASK_SIZE, tol: float | None =
def _bbox_cover(mask: np.ndarray) -> float:
- """Fraction of the frame the mask's BOUNDING BOX spans (1.0 = corner to corner).
-
- Separate from fill: a photo whose background the border-colour model failed on comes
- back as a scattered mask of 40-80 % area whose bbox is still the entire image. Area
- says "plausible object"; the bbox says "nothing was located".
- """
+ """Fraction of the frame the mask's BOUNDING BOX spans (1.0 = corner to corner)."""
ys, xs = np.nonzero(mask)
if ys.size == 0:
return 0.0
@@ -127,7 +90,7 @@ def _bbox_cover(mask: np.ndarray) -> float:
def _normalise(mask: np.ndarray, size: int = MASK_SIZE) -> tuple[np.ndarray, float]:
- """Crop to the mask bbox and scale into a size² canvas; returns (canvas, aspect w/h)."""
+ """Crop to the mask bbox and scale into a size² canvas."""
ys, xs = np.nonzero(mask)
canvas = np.zeros((size, size), dtype=bool)
if len(ys) == 0:
@@ -145,7 +108,7 @@ def _normalise(mask: np.ndarray, size: int = MASK_SIZE) -> tuple[np.ndarray, flo
def _diff_image(a: np.ndarray, b: np.ndarray, out: Path) -> Path:
- """Overlay: red = reference only, blue = render only, grey = both."""
+ """Overlay."""
h, w = a.shape
img = np.full((h, w, 3), 255, dtype=np.uint8)
both = a & b
@@ -158,16 +121,7 @@ def _diff_image(a: np.ndarray, b: np.ndarray, out: Path) -> Path:
def compare_silhouette(render_png: Path | str, reference_png: Path | str, *, diff_png: Path | str | None = None) -> dict[str, Any]:
- """IoU + fills + aspect error between a render and a reference image.
-
- Returns ``{iou, ref_fill, render_fill, aspect_ratio_err, ref_aspect, render_aspect,
- reliable, diff_png_path?}``. ``reliable`` is False when either mask is empty, covers
- more than 95 % of the pixels, or has a bounding box spanning the whole frame — all
- three mean the background estimate failed and the IoU below is arithmetic on noise.
- The caller must honour it: :class:`~codeverse3d.judges.vlm_judge.ReferenceJudge` scores
- ``silhouette_match`` NEUTRAL rather than low, because "we could not measure this" is
- not the same as "it does not match".
- """
+ """IoU + fills + aspect error between a render and a reference image."""
ref_mask = foreground_mask(reference_png)
ren_mask = foreground_mask(render_png)
ref_fill = float(ref_mask.mean())
@@ -192,11 +146,7 @@ def compare_silhouette(render_png: Path | str, reference_png: Path | str, *, dif
def silhouette_aspect(path: Path | str) -> float:
- """Width/height of the foreground bounding box (0.0 when the mask is empty).
-
- The one number that says whether a picture and a brief agree about the
- object's PROPORTIONS, independent of framing or resolution.
- """
+ """Width/height of the foreground bounding box (0.0 when the mask is empty)."""
mask = foreground_mask(path)
ys, xs = np.nonzero(mask)
if len(ys) == 0:
@@ -206,17 +156,11 @@ def silhouette_aspect(path: Path | str) -> float:
return w / h if h else 0.0
-#: render views a reference photo could plausibly have been shot from — a straight-on
-#: studio elevation matches ``front``/``right``/``left``/``back``, a 3/4 product shot
-#: matches the ``*_high`` ring. ``top``, ``bottom`` and the low ring are never a
-#: product-shot camera. A stored pre-D47 run matches through ``conventions.view_key``.
CANDIDATE_VIEWS: tuple[str, ...] = (
"front", "front_right_high", "front_left_high", "right", "left", "back", "back_left_high",
)
-#: ``compare_silhouette``'s shape: (render png, reference png) → its result dict. Injectable, so
-#: the track's services and the judge's tests can stand in for the mask arithmetic.
CompareFn = Callable[[str, str], dict[str, Any]]
@@ -228,16 +172,7 @@ def best_view_match(
diff_png: Path | str | None = None,
compare: CompareFn | None = None,
) -> dict[str, Any]:
- """IoU of the render view that best matches ``reference``, and which one it was.
-
- A reference photograph has ONE camera; comparing it to a fixed ``front`` render
- punishes an object whose reference happens to be a three-quarter shot. Scoring
- the best-matching candidate view instead measures *shape* rather than *camera
- agreement* — and the chosen view is reported so the number stays auditable.
-
- Returns the :func:`compare_silhouette` dict plus ``view`` (the winning view name)
- and ``per_view`` (name → IoU). ``{"error": ...}`` when nothing could be compared.
- """
+ """IoU of the render view that best matches ``reference``, and which one it was."""
compare = compare or compare_silhouette
per_view: dict[str, float] = {}
best: tuple[float, RenderView, dict[str, Any]] | None = None
@@ -265,17 +200,13 @@ def best_view_match(
def target_reference(references: Sequence[ReferenceImage]) -> str | None:
- """THE silhouette target: the first readable reference with role ``target``, else the first
- readable one; ``None`` when no reference file exists."""
+ """THE silhouette target."""
readable = [r for r in references if Path(r.path).is_file()]
return next((r.path for r in readable if r.role == "target"), readable[0].path if readable else None)
class ReferenceMatch(BaseModel):
- """The one silhouette measurement of a round against its target reference: the
- ``reference_silhouette`` gate records it (and refines on it), the reference judge scores
- ``silhouette_match`` from it. Until 2026-09-24 the gate compared the ``front`` render only
- while the judge took the best-matching view — 0.26 vs 0.995 on one reference (audit N51)."""
+ """The one silhouette measurement of a round against its target reference."""
iou: float
ref_fill: float | None = None
@@ -291,15 +222,13 @@ class ReferenceMatch(BaseModel):
@property
def scorable(self) -> bool:
- """May the IoU be read as a shape verdict? Not on an unreliable mask, and not when
- the reference contradicts the brief (the brief wins; the score is neutral)."""
+ """True when the IoU may be read as a shape verdict: the mask is reliable and the reference does not contradict the brief."""
return self.reliable and not self.conflict
def measure_reference(renders: Sequence[RenderView], spec: Spec, *, compare: CompareFn | None = None) -> ReferenceMatch | None:
""":class:`ReferenceMatch` of ``renders`` against ``spec``'s target reference, or ``None``
- when the spec has no readable reference or no render view could be compared. An error in
- ``compare`` itself propagates: the caller decides what "unavailable" means."""
+ when the spec has no readable reference or no render view could be compared."""
from codeverse3d.reference import dimension_conflict # reference.py imports this module
ref = target_reference(spec.references)
diff --git a/harness/codeverse3d/spatial/tool_common.py b/harness/codeverse3d/spatial/tool_common.py
index 22b1fb36..8b1c0e24 100644
--- a/harness/codeverse3d/spatial/tool_common.py
+++ b/harness/codeverse3d/spatial/tool_common.py
@@ -1,8 +1,4 @@
-"""Shared plumbing for the spatial tools: context lookups, render-output caching and
-plan/spec loading.
-
-Tools never touch globals: everything flows through :class:`ToolContext`.
-"""
+"""Shared plumbing for the spatial tools: context lookups, render-output caching and plan/spec loading."""
from __future__ import annotations
@@ -60,22 +56,12 @@ def reference_path(ctx: ToolContext, index: int) -> tuple[Path, dict]:
def glb_path(ctx: ToolContext) -> Path:
- """``artifacts/object.glb``, refusing when the LATEST build did not produce it.
-
- Bare ``is_file()`` let every consumer (measure / render_views / compare /
- texture tools) operate on the previous round's geometry as if it were current
- after a failed or lint-blocked build."""
+ """``artifacts/object.glb``, refusing when the latest build failed (a stale GLB must not read as current)."""
p = ctx.workspace.artifacts / "object.glb"
- # build.json is THE build status: every runtime publishes its final BuildResult there and
- # a lint refusal writes one too; unreadable/absent stays permissive (a GLB placed by hand)
+ # build.json is the build status; unreadable/absent stays permissive (a GLB placed by hand)
status = read_json_or_none(ctx.workspace.artifacts / "build.json")
- # status FIRST: a failed build publishes nothing, so the file is missing for a
- # reason the agent needs — it was told "run build first" right after its build
- # failed on RestPenetration and spent the rest of its turns looking for the
- # wrong problem (measured 2026-08-27, art_med_tool_chest).
+ # check status first: a failed build leaves no file, and the agent needs that reason
if status is not None and not status.get("ok"):
- # BuildResult serialises error_message, not "error" — reading the wrong key cost
- # the agent the message and left only the type (found by review 2026-08-28)
why = str(status.get("error_message") or status.get("error_type") or "see the build output")
raise ToolUsageError(
f"the last build FAILED ({why[:200]}) — there is no current object.glb to read. "
@@ -107,8 +93,7 @@ def load_plan(path: Path) -> Plan:
def plan_or_none(path: Path) -> Plan | None:
- """:func:`load_plan` for a caller with defaults: ``None`` when plan.json is absent,
- unreadable or not a valid plan (the runtimes: resolution, skeleton hints)."""
+ """:func:`load_plan`, or ``None`` when plan.json is absent or invalid."""
try:
return load_plan(path)
except (ToolUsageError, OSError, ValueError, TypeError):
@@ -142,9 +127,7 @@ def _file_stamp(p: Path) -> str:
def tool_out_dir(ctx: ToolContext, name: str) -> Path:
- """``artifacts/tool_renders/r<NN>_<name>`` (created) — THE output location for
- anything a tool renders/writes for the agent, so every tool artifact is
- round-stamped and lands in one place."""
+ """``artifacts/tool_renders/r<NN>_<name>`` (created): the round-stamped output dir for tool artifacts."""
d = ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_{name}"
d.mkdir(parents=True, exist_ok=True)
return d
@@ -167,16 +150,7 @@ def cached_render_glb(
explode: float = 0.0,
sheet: bool = True,
) -> RenderSet:
- """``render_glb`` into a deterministic per-call out_dir; the CACHE lives in
- ``spatial.render``, which is the only thing allowed to decide a PNG is still good.
-
- This used to keep a second ``renderset.json`` marker here, keyed on the GLB's
- size+mtime alone. It served stale views whenever a rebuild landed on the same
- size and mtime, ignored a rig edit / CACHE_VERSION bump entirely, and — because the
- marker stores absolute paths — a copied workspace returned views inside the ORIGINAL
- one. ``render_glb``'s key (sha256 of the GLB + CACHE_VERSION + the rig signature)
- has none of those holes, so one authority is both cheaper and correct.
- """
+ """``render_glb`` into a deterministic per-call out_dir; the pixel cache lives only in ``spatial.render``."""
# resolved at call time: tests patch the module attribute
from codeverse3d.spatial.render import render_glb
@@ -190,11 +164,7 @@ def cached_render_glb(
def gl_metrics_summary(ws: Workspace, *, hints: bool = True, root: Path | None = None) -> tuple[list[str], dict[str, Any], bool]:
"""Frame stats + ``gl_frames`` findings of a graphics build as (lines, numbers, ok).
- Reads ``artifacts/metrics.json`` through ``languages._gl_common.read_metrics``
- — the one reader — and formats it the same way for every caller (the ``build``
- tool, ``gl_probe`` and ``gl_frames``). ``hints`` appends each finding's fix
- hint; ``root`` sanitises workspace paths out of the messages. Returns
- ``(["(no frame metrics)"], {}, True)`` when the build wrote none.
+ ``hints`` appends fix hints; ``root`` strips workspace paths. ``(["(no frame metrics)"], {}, True)`` when none.
"""
from codeverse3d.languages._gl_common import read_metrics
from codeverse3d.spatial.observe import sanitize_text
diff --git a/harness/codeverse3d/spatial/tools.py b/harness/codeverse3d/spatial/tools.py
index 3ae13079..039c96fd 100644
--- a/harness/codeverse3d/spatial/tools.py
+++ b/harness/codeverse3d/spatial/tools.py
@@ -1,10 +1,6 @@
-"""Every spatial tool registered with ``@tool``, in sections: build / measure / gates /
-sections · rendering · articulation · scenes · graphics · reference.
-``import codeverse3d.spatial.tools`` registers all of them.
+"""Every spatial tool registered with ``@tool``; importing this module registers them all.
-House rules: observations are compact (errors first, fix hints attached), text
-never contains absolute host paths (images are absolute — the harness converts),
-and every tool is cheap to call repeatedly.
+Observations are compact (errors first, fix hints attached) and their text never carries absolute host paths.
"""
from __future__ import annotations
@@ -77,9 +73,7 @@ def _measure_after_build(ctx: ToolContext, br: BuildResult) -> tuple[Measurement
return m, measure_summary_table(m)
-#: languages whose build has no GLB deliverable — build ok is reported through
-#: the language's own artifacts instead of 'no GLB path'; the scene tools serve every
-#: scene language through its ``SceneRuntime`` (D101)
+#: languages whose build has no GLB deliverable; build ok is reported through their own artifacts
SCENE_LANGUAGES = tuple(lang.value for lang in TRACK_LANGUAGES[Track.SCENE])
GRAPHICS_LANGS = tuple(lang.value for lang in TRACK_LANGUAGES[Track.GRAPHICS])
@@ -89,7 +83,6 @@ def _no_glb_summary(ctx: ToolContext, br: BuildResult, language: str) -> tuple[b
ws = ctx.workspace
census = dict(br.census) if isinstance(br.census, dict) else {}
if language in GRAPHICS_LANGS:
- # same frame-stats formatter the gl_probe / gl_frames tools use
lines, numbers, ok = gl_metrics_summary(ws, hints=False, root=ws.root)
for key in ("frames", "sheet", "gif"):
p = br.extra_paths.get(key)
@@ -107,13 +100,7 @@ def _no_glb_summary(ctx: ToolContext, br: BuildResult, language: str) -> tuple[b
def _gl_gate_verdict(numbers: dict[str, Any]) -> list[str]:
- """The FRAME GATE line that goes ABOVE the '… OK' headline, or [] when it passed.
-
- The shader compiled and the frames rendered, so the gate verdict is the answer and
- not an error to retry (``Observation.failed`` stays False) — it has to be readable
- at the top of the text, where the '… OK' headline would otherwise be the only
- verdict the model sees. Shared by ``build`` (graphics), ``gl_probe``, ``gl_frames``.
- """
+ """The FRAME GATE line that goes above the '… OK' headline, or [] when it passed (a verdict, not a tool failure)."""
n = int(numbers.get("gate_errors", 0))
if not n:
return []
@@ -125,10 +112,7 @@ _LINT_WARNS_SHOWN = 10
def _lint_gate(ctx: ToolContext, rt: Any, *, verb: str) -> tuple[Observation | None, list[str]]:
- """Lint before any build-running tool builds: (refusal observation | None, warning
- lines). Lint ERRORs skip the build (docs/DECISIONS.md L5) and are recorded as the
- LATEST build status — without that the previous build.json (ok: true) + object.glb
- stayed readable as current."""
+ """Lint before building: (refusal observation | None, warning lines). Lint errors skip the build and are recorded as the latest build status."""
ws = ctx.workspace
lint: GateReport = rt.lint(ws)
errs = lint_lines(lint, ws.root, errors_only=True)
@@ -145,8 +129,7 @@ def _lint_gate(ctx: ToolContext, rt: Any, *, verb: str) -> tuple[Observation | N
def _build_failed(ctx: ToolContext, br: BuildResult, warns: list[str]) -> Observation:
- """The BUILD FAILED observation of every build-running tool; ``error_file`` is
- workspace-relative (house rule: text never carries absolute host paths)."""
+ """The BUILD FAILED observation of every build-running tool."""
ws = ctx.workspace
return text_observation(build_failure_lines(br, ws.root, warns, tail_n=_STDERR_TAIL_LINES), ok=False, limit=3000,
numbers={"stage": "build", "ok": False, "duration_ms": br.duration_ms, "error_type": br.error_type,
@@ -154,12 +137,9 @@ def _build_failed(ctx: ToolContext, br: BuildResult, warns: list[str]) -> Observ
def _env_unlit_only(br: BuildResult) -> str:
- """The headline line for a scene build whose ONLY errors are ``probes.unlit`` (nothing lights the
- scene), else ``""``. The round's build fails on that ERROR so its repair is handed the env module
- (D112); a session's own ``build`` reports it above a BUILD OK instead — most sessions that build
- while the env is still the placeholder (an asset session beside the env stage, a zone session
- after a failed env stage) cannot write the env module, and a BUILD FAILED they cannot clear would
- cost them their window."""
+ """Headline for a scene build whose only errors are ``probes.unlit``, else ``""``.
+
+ A session's own ``build`` reports it above BUILD OK, since many sessions cannot write the env module."""
if br.ok or br.harness_failure:
return ""
errors = [f for g in br.gates for f in g.errors]
@@ -172,7 +152,6 @@ def _env_unlit_only(br: BuildResult) -> str:
@tool("build", NoArgs, "Lint + build the code in src/ with the language runtime, export artifacts/object.glb and measure it. Call after every edit.", cost_hint="slow")
def build(ctx: ToolContext, args: NoArgs) -> Observation:
- # ToolDef.call stamps Observation.duration_ms for every tool — no timing here
from codeverse3d.languages import get_runtime
ws = ctx.workspace
@@ -190,7 +169,6 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
numbers["env_unlit"] = True
broken = False
if not br.glb_path and language in SCENE_LANGUAGES + GRAPHICS_LANGS:
- # languages without a GLB deliverable: report the language's own artifacts
ok, extra_lines, extra_numbers = _no_glb_summary(ctx, br, language)
lines = _gl_gate_verdict(extra_numbers) + [f"BUILD OK ({br.duration_ms} ms)"] + extra_lines
numbers.update(extra_numbers)
@@ -198,8 +176,7 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
else:
m, table = _measure_after_build(ctx, br)
ok = m is not None
- # the runtime reported success and left nothing measurable: the tool could not
- # answer (not a verdict on the code), and the headline must not read BUILD OK
+ # success with nothing measurable: the tool could not answer, so no BUILD OK headline
broken = m is None
lines = [f"BUILD OK ({br.duration_ms} ms) → {rel_path(br.glb_path, ws.root)}" if ok
else f"BUILD PRODUCED NO USABLE GLB ({br.duration_ms} ms): {table}"]
@@ -223,8 +200,7 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
return text_observation(lines, ok=ok, failed=broken, numbers=numbers, limit=3000)
-#: the object-GLB toolset (everything that reads artifacts/object.glb): scene and
-#: graphics builds never write that file, so serving these there was a dead-end loop
+#: tracks whose builds write artifacts/object.glb (the object-GLB toolset)
_OBJECT_TRACKS = (Track.STATIC_OBJECT.value, Track.ARTICULATED_OBJECT.value)
@@ -261,7 +237,7 @@ def measure(ctx: ToolContext, args: MeasureArgs) -> Observation:
def check_connectivity(ctx: ToolContext, args: NoArgs) -> Observation:
glb = glb_path(ctx)
plan = load_plan(ctx.workspace.plan_path) if ctx.workspace.plan_path.is_file() else None
- try: # the plan's attach_to pairs in the GLB's part names — the same resolver as the track's gate
+ try: # the plan's attach_to pairs, in the GLB's part names
planned = planned_joins(plan, measure_glb(glb)) if plan is not None else []
except GlbLoadError as e:
return Observation.error(f"check_connectivity: {e}")
@@ -347,7 +323,7 @@ def render_sheet(ctx: ToolContext, args: RenderSheetArgs) -> Observation:
obs = _render(ctx, views=[v.name for v in OBJECT_VIEWS], mode=args.mode, isolate=[], explode=0.0, size=512,
note=f"{args.mode} 14-view sheet")
if obs.ok and obs.images:
- obs.images = obs.images[:1] # the sheet alone is the deliverable here
+ obs.images = obs.images[:1]
return obs
@@ -394,11 +370,7 @@ class JointSweepArgs(BaseModel):
def _poses_for(robot, joints: list[str] | None) -> list[tuple[str, dict[str, float]]] | None:
- """``limit_poses`` narrowed to ``joints`` (rest kept); ``None`` = the full sheet.
-
- An unknown joint name narrows to nothing but rest, which is a wrong-but-visible sheet
- rather than a silent fallback to everything — the agent sees one tile and its typo.
- """
+ """``limit_poses`` narrowed to ``joints`` (rest kept); ``None`` = the full sheet."""
if not joints:
return None
want = set(joints)
@@ -411,17 +383,9 @@ def _poses_for(robot, joints: list[str] | None) -> list[tuple[str, dict[str, flo
"check always covers the whole robot.",
tracks=(Track.ARTICULATED_OBJECT.value,), cost_hint="slow")
def joint_sweep(ctx: ToolContext, args: JointSweepArgs) -> Observation:
- """The round's own verdict (``joints_sweep.sweep_gate``) — until 2026-09-22 the tool ran a
- second sweep with its own rules and could pass what the round then failed, or the reverse.
-
- ``joints`` narrows the RENDER to those joints' limit poses (plus rest). The collision
- sweep still covers every joint — a change to one joint can collide with another, and
- that check is cheap. Rendering is not: every pose is a GLB export plus three views, so
- a 10-joint object renders ~63 images per call, and agents call this 3-8 times a round.
- Measured 2026-08-25: articulated rounds ran a median 1007 s against 497 s for static
- objects, with the agent session — mostly waiting on sweeps — as the whole difference."""
+ """The round's own verdict (``sweep_gate``); ``joints`` narrows only the pose renders, the collision sweep covers every joint."""
ws = ctx.workspace
- if find_urdf(ws) is None: # the gate's own rule: the built URDF only
+ if find_urdf(ws) is None:
return Observation.error("joint_sweep: artifacts/robot.urdf not found — run `build` first")
report, robot = sweep_gate(ws)
images: list[str] = []
@@ -446,11 +410,7 @@ def _scene_runtime(ctx: ToolContext) -> SceneRuntime:
"line numbers — the build's own probe + preflight, so the verdict is the build's.",
languages=(Language.SCENE_THREEJS.value,), cost_hint="slow")
def shader_probe(ctx: ToolContext, args: NoArgs) -> Observation:
- """The build's own probe + shader preflight (``run_probe(compile=True)``: one ``probe_scene.mjs
- --compile`` boot under the render policy). Until 2026-09-22 this ran a second driver,
- check_shaders.mjs at 256x144 without the settle / camera-repair / exposure flags, whose
- verdict could differ from the build's. A scene that never boots gets no preflight:
- the probe's report says why."""
+ """The build's own probe + shader preflight; a scene that never boots gets no preflight (the probe's report says why)."""
probe, shaders, _census = run_probe(ctx.workspace, compile=True)
died = [f.message for f in probe.findings if f.data.get("harness_failure")]
if died:
@@ -463,8 +423,7 @@ def shader_probe(ctx: ToolContext, args: NoArgs) -> Observation:
languages=SCENE_LANGUAGES, cost_hint="slow")
def scene_probe(ctx: ToolContext, args: NoArgs) -> Observation:
res = _scene_runtime(ctx).probe(ctx.workspace)
- # ok = the gate verdict; failed = the probe TOOL could not run (SceneProbeResult
- # semantics): agent-fixable findings are a FAIL the agent must read, not an error
+ # ok = the gate verdict; failed = the probe tool could not run
obs = gate_observation(res.gate, title="scene probe", failed=bool(res.errors))
if res.errors:
obs.text += "\nerrors:\n" + "\n".join(f" ! {e[:200]}" for e in res.errors[:10])
@@ -504,13 +463,11 @@ def scene_views(ctx: ToolContext, args: SceneViewsArgs) -> Observation:
def _frame_table(out_dir: Path) -> str:
- """The deterministic numbers behind the pictures — exposure/coverage per camera plus the
- measured motion between the times. Without them the agent is asked to LOOK at a sheet and
- guess whether its sway is visible or its dusk is too dark; with them it can read the answer."""
+ """The numbers behind the pictures: exposure/coverage per camera plus measured motion between the times."""
try:
metrics = read_json_or_none(out_dir / "metrics.json")
return frame_summary_text(metrics) if metrics else ""
- except Exception: # noqa: BLE001 — a tool observation must never fail on instrumentation
+ except Exception: # noqa: BLE001
return ""
@@ -607,7 +564,7 @@ def gl_probe(ctx: ToolContext, args: GlProbeArgs) -> Observation:
def gl_frames(ctx: ToolContext, args: GlFramesArgs) -> Observation:
if len(args.times) > MAX_FRAMES:
raise ToolUsageError(f"times must hold at most {MAX_FRAMES} values", "gl_frames() renders the judged times")
- # empty → the build's own default, `judge_times(plan duration)`: the frames the judge will see
+ # empty → the build's default: the frames the judge will see
times = sorted(set(float(t) for t in args.times)) if args.times else None
err, br, warns = _run_build(ctx, times=times, width=args.width, height=args.height)
if err is not None:
@@ -632,8 +589,7 @@ def gl_frames(ctx: ToolContext, args: GlFramesArgs) -> Observation:
# ===================================================================== reference
-#: what the agent should compare, in the order that decides whether the object
-#: reads as the real thing (identity before polish)
+#: what the agent compares, identity before polish
CHECKLIST = (
"1) part inventory — is every part visible in the reference present in your model, and nothing invented? "
"2) counts — spokes / slats / rods / panes / flutes: count them in the reference and match the number. "
diff --git a/harness/codeverse3d/tracks/articulated_object.py b/harness/codeverse3d/tracks/articulated_object.py
index 820c98fc..24cc58f9 100644
--- a/harness/codeverse3d/tracks/articulated_object.py
+++ b/harness/codeverse3d/tracks/articulated_object.py
@@ -1,10 +1,4 @@
-"""ArticulatedObjectTrack: the static pipeline + URDF pose sweep + pose views.
-
-Language: urdf_blender (bpy link meshes + hand-written URDF). After the build
-the harness loads ``artifacts/robot.urdf``, samples joint poses, sweeps for
-penetrations / floating links (→ gate ERRORS with concrete fix hints) and
-renders a pose sheet which is appended to the judge's views.
-"""
+"""ArticulatedObjectTrack."""
from __future__ import annotations
@@ -57,8 +51,6 @@ class ArticulatedPipeline(ObjectPipeline):
@staticmethod
def _axis_repair(ctx: RunContext) -> list[str]:
- """Measure → deterministically fix wrong joint axes BEFORE the sweep renders,
- so this round's poses, renders and judge all see the corrected motion."""
if not get_settings().axis_repair:
return []
try:
@@ -117,13 +109,7 @@ class ArticulatedObjectTrack(StaticObjectTrack):
# ----------------------------------------------------------------------------- sweep adapter
def default_joint_sweep(ws: Workspace, plan: Plan | None, out_dir: Path) -> tuple[GateReport, list[RenderView]]:
- # ``plan`` is unread HERE — the sweep reads the built URDF off disk — but it stays in
- # the Services.joint_sweep signature: it is the interface's information, and the test
- # double (tests/orchestrator_tracks/fakes.py) synthesises its poses and findings from
- # plan.joints because it has no URDF to read.
- """The round's ``joint_sweep`` gate — ``spatial.joints_sweep.sweep_gate``, the verdict the
- ``joint_sweep`` tool reports too — and ``render_poses`` (pose views +
- ``articulation_sheet.png`` for the judge)."""
+ # ``plan`` is unread here (the sweep reads the URDF off disk); it stays for the Services signature.
from codeverse3d.spatial.joints_export import ARTICULATION_SHEET_NAME, render_poses
from codeverse3d.spatial.joints_sweep import SWEEP_GATE, sweep_gate
@@ -138,10 +124,7 @@ def default_joint_sweep(ws: Workspace, plan: Plan | None, out_dir: Path) -> tupl
v = rs.views[0]
views.append(RenderView(name=f"pose_{label}", path=v.path, mode=v.mode, width=v.width, height=v.height))
except RenderError as e:
- # The pose renders are the judge's evidence, not the gate's: the collision sweep
- # above is already measured. A render timeout here (art_verify architect_lamp,
- # 2026-08-26: 330 s in render_glb.mjs with three articulated runs sharing the
- # browser) used to raise out of gates() and fail the run before its first round.
+ # pose renders are the judge's evidence, not the gate's: a render failure must not fail the round
log.warning("pose renders failed; the sweep gate stands without a sheet: %s", e)
gate.findings.append(GateFinding(gate=SWEEP_GATE, severity=Severity.WARN, target="poses",
message=f"pose renders failed ({str(e)[:160]}); the judge sees no articulation sheet this round",
@@ -183,11 +166,7 @@ _DIR_GROUPS = {"front": "y", "back": "y", "-y": "y", "+y": "y", "up": "z", "down
def expected_direction(motion: str) -> str | None:
- """Direction key for an obvious motion description, else ``None``.
-
- Rules: explicit signed axes win; otherwise the first (longest) phrase hit;
- text naming two different axes ("up and to the left"), negations or pure
- rotations ("spins around its axis") → ``None`` (ambiguous — skip)."""
+ """Direction key for an obvious motion description, else ``None``."""
text = " ".join((motion or "").lower().replace("_", " ").split())
if not text or any(m in text for m in _SKIP_MARKERS):
return None
@@ -230,9 +209,7 @@ def axis_fix_hint(joint_name: str, axis: Sequence[float] | None, expected: str)
def _set_axis_in_urdf_text(text: str, urdf_joint: str, axis: tuple[float, float, float]) -> str | None:
- """``text`` with joint ``urdf_joint``'s ``<axis xyz>`` replaced (inserted when
- missing). String surgery instead of an XML round-trip so authored comments and
- formatting survive; ``None`` when the joint block cannot be located safely."""
+ """``text`` with joint ``urdf_joint``'s ``<axis xyz>`` replaced (inserted when missing)."""
xyz = f"{axis[0]:g} {axis[1]:g} {axis[2]:g}"
start = -1
pos = 0
@@ -273,17 +250,7 @@ def _set_axis_in_urdf_text(text: str, urdf_joint: str, axis: tuple[float, float,
def repair_motion_axes(ws: Workspace, report: GateReport | None) -> list[str]:
- """Deterministically rewrite provably-wrong ``<axis xyz>`` in ``src/robot.urdf``.
-
- For every motion_direction ERROR whose measured data admits an exact fix:
- anti-parallel motion (``cos <= -0.5``) negates the authored axis; otherwise a
- computed ``suggested_axis`` is written verbatim. The same fixes rode along as
- fix_hints for a whole battery and the agents applied none of them
- (ax_metronome / ax_swiss_knife, 2026-08-31): the measurement exists, so the
- execution goes deterministic. ``C3D_AXIS_REPAIR=0`` disables. Both the
- authored file and the built ``artifacts/robot.urdf`` copy are updated so the
- re-run gate and the pose sweep see the repair. Returns repaired plan-joint
- names; a finding without measured data (``cos``) is never touched."""
+ """Deterministically rewrite provably-wrong ``<axis xyz>`` in ``src/robot.urdf``."""
if report is None or not get_settings().axis_repair:
return []
src = ws.src / "robot.urdf"
@@ -338,9 +305,7 @@ def repair_motion_axes(ws: Workspace, report: GateReport | None) -> list[str]:
def default_motion_checks(ws: Workspace, plan: Plan | None) -> GateReport | None:
- """Run ``motion_direction_check`` for every plan joint with an obvious motion
- direction. ``None`` when the plan has no such joints; unknown joints /
- missing meshes are WARN findings (the sweep gate already reports them)."""
+ """Run ``motion_direction_check`` for every plan joint with an obvious motion direction."""
joints = list(getattr(plan, "joints", None) or [])
wanted = [(j, expected_direction(j.motion)) for j in joints]
wanted = [(j, d) for j, d in wanted if d is not None]
@@ -374,9 +339,7 @@ def default_motion_checks(ws: Workspace, plan: Plan | None) -> GateReport | None
if chk.ok:
findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.INFO, target=j.name, message=chk.message, data=data))
else:
- # anti-parallel: the sign is provably wrong — negate. Orthogonal (the
- # af_swiss_knife class: three rounds of guessing on the same joints): the
- # geometry admits an exact axis, so the hint states it verbatim.
+ # anti-parallel: the sign is wrong, negate; orthogonal: the geometry admits an exact axis, state it.
if chk.cos >= -0.5 and chk.suggested_axis is not None:
sx, sy, sz = chk.suggested_axis
hint = (f"in src/robot.urdf set joint '{j.name}' <axis xyz=\"{sx:g} {sy:g} {sz:g}\"/> "
diff --git a/harness/codeverse3d/tracks/candidates.py b/harness/codeverse3d/tracks/candidates.py
index 803e9c60..934de6f1 100644
--- a/harness/codeverse3d/tracks/candidates.py
+++ b/harness/codeverse3d/tracks/candidates.py
@@ -1,17 +1,4 @@
-"""Best-of-N baseline (track side).
-
-``run_best_of_n`` — N baseline candidates are generated IN PARALLEL, each in its own
-throw-away sub-workspace (``<ws>/_cand/c<k>``: own git repo, copy of the skeleton + spec +
-plan, own AGENTS.md/MCP config), built (+repair), gated, quick-rendered (4 views) and
-judged (n_samples=1) — the ordinary round (``steps._run_round``, kind ``candidate``) with
-two knobs turned: ``quick_render`` in place of ``pipeline.render`` and no clay views. Each
-candidate's round trace goes to its own ``events.jsonl``; the run log carries
-``candidate.*``. The winner — built, then the highest quick score, then fewer gate errors,
-then the earlier candidate — is copied back into the run workspace and the ordinary
-round-0 pipeline (build → gates → 14-view render → full judge) runs on it. That is the
-ONE choice the loop still makes (2026-09-22: no pairwise tie-break, no best round).
-Every candidate is charged to the run budget and persisted in ``rounds/candidates.json``.
-"""
+"""Best-of-N baseline (track side)."""
from __future__ import annotations
@@ -59,9 +46,8 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],
def _one(k: int) -> CandidateRecord:
sub, label = subs[k], f"c{k}"
ctx.events.emit("candidate.start", candidate=k, workspace=str(sub.ws.root))
- # kind="candidate" is what the cost ledger files the sessions under (Stage.CANDIDATE)
tasks_k = [t.model_copy(update={"label": f"{t.label}_{label}", "kind": "candidate"}) for t in tasks]
- with tally() as spent: # the candidate's cost: the ledger rows it books
+ with tally() as spent:
rec = _run_round(sub, index=0, kind="candidate", tasks=tasks_k, pipeline=pipeline,
files_hint=list(files_hint), render=partial(quick_render, pipeline=pipeline),
geometry_views=False, spent=spent)
@@ -74,8 +60,6 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],
duration_s=cand.duration_s, cost_usd=round(rec.usage.cost_usd, 4), commit=rec.commit[:10])
return cand
- # the candidates run side by side: one step of the run's minutes (each candidate round
- # keeps its own steps in its sub-workspace)
with timed("candidates", ctx.state.steps, round_index=0):
results = fan_out(list(range(n)), _one, max_workers=ctx.settings.limits.max_parallel_agents,
label="candidates", item_name=lambda k: f"c{k}")
@@ -94,9 +78,6 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],
budget_stop: BudgetExceeded | None = None
for k, r in enumerate(results):
if isinstance(r, Exception):
- # a candidate that tripped the ceiling is a failed candidate, not the
- # round's verdict: the sibling's finished work is still selected, adopted
- # and persisted below; the guard's boundary check stops the run afterwards.
if isinstance(r, BudgetExceeded) and budget_stop is None:
budget_stop = r
records.append(CandidateRecord(index=k, label=f"c{k}", workspace=str(subs[k].ws.root),
@@ -106,12 +87,11 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],
records.append(r)
if not any(r.commit for r in records):
if budget_stop is not None:
- raise budget_stop # nothing usable survived: the budget stop stands
+ raise budget_stop
died = [r for r in results if isinstance(r, Exception)]
raise RoundFailed("; ".join(f"{r.label}: {r.notes}" for r in records) or "every candidate failed",
transient=any(e.transient if isinstance(e, RoundFailed) else is_model_outage(e) for e in died),
quota=any(isinstance(e, RoundFailed) and e.quota for e in died),
- # D112: a hung candidate is retried by the round loop like a hung single session
stalled=any(isinstance(e, RoundFailed) and e.stalled for e in died))
best = rank_candidates(records)[0]
records[best].selected = True
@@ -127,7 +107,7 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],
for r in records if r.index != best)
notes = [f"best-of-{n}: selected {records[best].label} "
f"(quick score {records[best].score if records[best].score is None else round(records[best].score, 3)}; others: {others or '-'})"]
- ctx.budget.check() # boundary: the winner is adopted + persisted; a real ceiling stop lands here
+ ctx.budget.check()
return run_round(ctx, index=0, kind="baseline", tasks=[], pipeline=pipeline, files_hint=list(files_hint),
extra_usage=usage, extra_notes=notes)
@@ -152,30 +132,12 @@ def make_candidate_context(track: Any, ctx: RunContext, k: int) -> RunContext:
def quick_render(ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None, *,
pipeline: RoundPipeline) -> RenderSet | None:
- """Cheap renders for ranking a candidate — by the route THIS track actually has.
-
- An object has a GLB and gets the reduced-view, reduced-resolution rig, which is the
- whole point of a "quick" render. A shader has no GLB at all, and returning None there
- meant the candidate was never judged, scored None, and best-of-N fell through to index
- 0 — so every extra candidate was generated, paid for and discarded unlooked-at.
-
- Measured 2026-08-25 across the teaser battery: static_object and articulated_object
- candidates all carried real scores, and all SIX graphics runs recorded
- ``scores: {c0: null, c1: null}`` with ``selected: 0``, two of them at n=3. No
- ``candidate.judge_failed`` event fired anywhere — nothing errored, the judge was simply
- never reached.
-
- So when there is no GLB, fall back to ``pipeline.render``, which is the renderer the
- track uses for its real rounds (frames for graphics, authored cameras for a scene).
- That costs more than the quick rig; it costs less than paying for N generations and
- keeping the first one blind.
- """
+ """Cheap renders for ranking a candidate — by the route THIS track actually has."""
out_dir = ctx.ws.renders_dir(round_index) / "quick"
try:
if build.glb_path:
rs = ctx.services.render_object(Path(build.glb_path), out_dir, views=OBJECT_VIEWS_QUICK,
width=QUICK_PX, height=QUICK_PX)
- # ArticulatedPipeline.gates() parks its sweep views here for render() to pick up
pose = ctx.extra.pop("pose_views", None)
if pose:
rs.views = list(rs.views) + list(pose)
diff --git a/harness/codeverse3d/tracks/common.py b/harness/codeverse3d/tracks/common.py
index 184da296..c74eb010 100644
--- a/harness/codeverse3d/tracks/common.py
+++ b/harness/codeverse3d/tracks/common.py
@@ -1,13 +1,4 @@
-"""Shared track machinery: the run context, the services seam, the single-shot path.
-
-``Services`` is the tracks' injection seam: every call into a sibling package
-(models, agents, runtimes, spatial tools, judges, record) goes through one
-method here so a test can subclass it with fakes (``tests/orchestrator_tracks/
-fakes.py``) and an articulated test double can synthesise joint sweeps from the
-plan. The targets are modules of this same package — never optional — and are
-imported lazily only to keep ``tracks`` importable without loading Blender,
-Chrome or a model client. Nothing here touches a network.
-"""
+"""Shared track machinery: the run context, the services seam, the single-shot path."""
from __future__ import annotations
@@ -75,10 +66,7 @@ class Services:
return _import("codeverse3d.spatial.measure", "measure_glb")(glb)
def connectivity(self, glb: Path, language: str = "", planned_edges: Sequence[tuple[str, str | Sequence[str]]] = ()) -> GateReport:
- """``language`` selects the frame of the fix hints (the author's frame, not the GLB's);
- ``planned_edges`` are the plan's attach_to pairs spelled in GLB part names — the gate
- measures each one and lists it contact/open in its contact ledger (the judge's
- assembly_fit ground truth since 2026-08-30)."""
+ """Connectivity gate; ``language`` selects the frame of the fix hints (the author's frame, not the GLB's)."""
return _import("codeverse3d.spatial.connectivity", "check_connectivity")(
glb, language=language, planned_edges=tuple(planned_edges))
@@ -93,8 +81,7 @@ class Services:
return runtime.render_scene(ws, out_dir, cameras=cameras, orbit=True, times=tuple(times), width=width, height=height, sheet=True)
def render_geometry(self, glb: Path, out_dir: Path, *, views: Sequence[ViewPreset]) -> RenderSet:
- """Clay renders (no materials/textures) exposing holes/intersections for the judge's
- geometry montage — cheap thanks to the render cache."""
+ """Clay renders (no materials/textures) exposing holes/intersections for the judge's"""
return _import("codeverse3d.spatial.render", "render_glb")(glb, out_dir, views=list(views), mode="clay", sheet=False)
def frame_gate(self, renders: RenderSet) -> GateReport:
@@ -148,14 +135,12 @@ class RunContext:
agent_id: str
plan: Plan | None = None
judge: Any | None = None
- agent: Any | None = None # CodingAgent instance (agent path)
- model: Any | None = None # ChatModel (single-shot path)
+ agent: Any | None = None
+ model: Any | None = None
contract_text: str = ""
tool_cards: str = ""
prompt_hashes: dict[str, str] = field(default_factory=dict)
extra: dict[str, Any] = field(default_factory=dict)
- #: the prompt/skill variant this run activated (``prompts/variants.py``, D105): ``""`` = base.
- #: Informative here — the overlay itself is the ContextVar ``BaseTrack.run`` sets around the run
variant: str = ""
@property
@@ -177,16 +162,11 @@ class RunContext:
# ----------------------------------------------------------------------------- strategy
def single_shot_ctx(ctx: RunContext) -> RunContext | None:
- """A copy of ``ctx`` bound to the single-shot strategy, or None when the
- generator has no usable chat model (CLI agents, tests with fake services)."""
+ """A copy of ``ctx`` bound to the single-shot strategy, or None when none is available."""
cached = ctx.extra.get("_single_shot_ctx")
if cached is not None:
- return cached or None # False = known-unavailable
+ return cached or None
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 = None
if sid:
@@ -202,8 +182,6 @@ def single_shot_ctx(ctx: RunContext) -> RunContext | None:
def generate_for(ctx: RunContext, task: GenerationTask) -> GenerationResult:
- """``generate()`` with everything ``ctx`` knows — the one call every stage makes. A session
- that died of a provider failure comes back ``transient``; the round loop's one retry is the
- only retry above the CLI's own."""
+ """``generate()`` with everything ``ctx`` knows — the one call every stage makes. A session"""
return generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
budget=ctx.budget, events=ctx.events)
diff --git a/harness/codeverse3d/tracks/depth.py b/harness/codeverse3d/tracks/depth.py
index 73b78f46..a6af9654 100644
--- a/harness/codeverse3d/tracks/depth.py
+++ b/harness/codeverse3d/tracks/depth.py
@@ -1,35 +1,4 @@
-"""Generation depth: complexity budgets.
-
-Measured on the recorded corpus (183 judged rounds / 81 runs, see the wave's
-``complexity_baseline.md``), three facts shape this module:
-
-1. **The complexity ceiling is set in round 0 and never moves.** Across 88
- consecutive refine-round pairs the built part count changed *zero* times: the
- refine loop is a repair loop (``refine_object.j2``: "keep everything else as it
- is"). Whatever depth the baseline session managed is the depth that ships.
-2. **Parts are punished, density is not.** One point per run, ``n_plan`` vs
- ``assembly_fit`` ρ = −0.48 and vs ``geometry_detail`` ρ = −0.41, while
- ``tri_per_part`` is flat-to-positive (+0.08 / +0.18 on materials). Extra parts
- cost score through the floating-part / interpenetration caps; extra triangles
- *inside* a part cost nothing. Within one difficulty tier (static_v2 r00) the
- sign flips: ``n_built`` vs ``geometry_detail`` = +0.34 — more parts DO buy
- detail once difficulty is held constant, they just also buy gate errors.
-3. **A flat limit says nothing.** ``MAX_TRIS_OBJECT`` is 600 000 against a corpus p50
- of ~6 000 and an all-time max of 54 210; build timeout 300 s against p50 0.25 s /
- p99 8.3 s. A 4-part stool and a 25-part machine hit the same numbers.
-
-The *measurement* side of the same question — how much artifact actually got built,
-on eight objective axes — is ``codeverse3d/spatial/complexity.py`` + ``eval/docs/COMPLEXITY.md``.
-This module is the *target* side: what THIS plan should be allowed and asked to spend.
-
-Hence: :func:`depth_budget` (how many triangles / how much build time this *plan*
-deserves, checked by :func:`budget_gate`; the generate / refine briefs get the numberless
-:data:`DETAIL_ADVICE`, and each object language's ``contract.md`` states the gate's per-object
-constants as a measured requirement (D107, pinned in ``prompts/_claims.toml``); how many PARTS a prompt deserves is
-``tracks.planner.plan_budget``, which also owns the thin-plan re-ask). The per-part scoped
-baseline that lived here (``scope_groups`` / ``interfaces_text``) was deleted by D110: one session
-drafts the whole object.
-"""
+"""Generation depth: complexity budgets."""
from __future__ import annotations
@@ -45,13 +14,9 @@ if TYPE_CHECKING:
#: 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.
TRIS_PER_UNIT_TARGET = 2_000
-#: below this per unit the part is a primitive stand-in (the ≤100 tri/part bin scores worst)
TRIS_PER_UNIT_FLOOR = 350
-#: hard ceiling per unit — 10× the target leaves room for subdivided organics without
-#: letting a smooth-shaded blob eat the whole budget
TRIS_PER_UNIT_MAX = 20_000
-#: seconds of headless build time one unit may cost (corpus p99 for a WHOLE object is 8.3 s)
BUILD_S_PER_UNIT = 3.0
MIN_BUILD_S = 20
@@ -60,16 +25,13 @@ MIN_BUILD_S = 20
class DepthBudget:
"""What THIS object is allowed to spend, sized from its own plan."""
- n_units: int # parts × instances — the things that actually get built
+ n_units: int
min_tris: int
target_tris: int
max_tris: int
max_build_s: int
-#: What the generate / refine briefs say about detail. No numbers: the triangle and build-time
-#: budget below is enforced by :func:`budget_gate`, whose findings state this object's numbers
-#: (owner, 2026-09-22); the per-built-object rule itself is in each object ``contract.md`` (D107).
DETAIL_ADVICE = (
"- Spend detail INSIDE the parts the plan already names — the edges, profiles, seams and repeats the "
"real object carries — not on new parts the plan does not list. Measured on this harness: detail "
@@ -101,14 +63,7 @@ BUDGET_GATE = "detail_budget"
def budget_gate(measurement: Any, build: Any, budget: DepthBudget) -> Any:
- """``detail_budget`` gate: is this object as dense as its own plan says it should be?
-
- Deterministic, so the judge is never asked "does it look detailed enough" —
- code answers it. Over the ceiling is an ERROR (the build is too heavy to ship);
- under the floor and over the build-time budget are WARNs, because a thin object
- is a quality problem, not a broken one — the static track deliberately does NOT
- turn the thin WARN into a refine task: density is the detail round's job.
- """
+ """``detail_budget`` gate: is this object as dense as its own plan says it should be?"""
from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity
findings: list[Any] = []
diff --git a/harness/codeverse3d/tracks/generation.py b/harness/codeverse3d/tracks/generation.py
index 52fa1d86..5e6547cc 100644
--- a/harness/codeverse3d/tracks/generation.py
+++ b/harness/codeverse3d/tracks/generation.py
@@ -1,34 +1,4 @@
-"""Code generation: one entry point, two strategies.
-
-* **CodingAgent path** — ``agent_id`` is any id ``codeverse3d.agents`` knows
- (``agy:*``, ``claude-code:*``, ``codex:*``):
- the workspace is materialised once per run (AGENTS.md + MCP config), then
- ``agent.run(AgentJob)``. Truth is on disk: ``ok`` means files changed.
-* **Single-shot path** — ``agent_id = "single-shot:<provider>:<model>"``: one
- ``ChatRequest`` whose answer is a multi-file envelope (``prompts/system/singleshot_format.md``),
- parsed by ``parse_multifile`` and written under the allowed roots. This is
- handled here (not in the agents registry) because it is not an agent.
-
-Neither path commits; the round commits once after all (possibly parallel)
-tasks finished. Neither path builds; see ``tracks/repair.py``.
-
-**Turn budget — off by default, measured.** The audit's turn-≥20 share (39.3%
-of the agent bill, docs/COST.md §4) looked like $14 of waste, so wave 2 capped
-every session at 28 turns. A controlled A/B rejected it — same prompt, n=3 per
-arm: capped $1.381 / **0.479**, uncapped $1.360 / **0.684** (docs/COST.md §17).
-A session cut off mid-task leaves work the next round pays for again.
-
-So there is **no default cap** (``DEFAULT_AGENT_MAX_TURNS`` is 0 → the backend's own
-``AgentJob.max_turns``). A machine may still set one (``C3D_AGENT_MAX_TURNS`` >
-``Settings.limits.agent_max_turns``; no cost profile sets one), and a cap that IS set
-stays **graceful**: the session is not killed but asked, in a short wrap-up
-(``DEFAULT_WRAPUP_TURNS``), for one last build + summary.
-
-**Every dollar is on the ledger.** Both strategies spend through the metered model or
-agent (``cost.instrument``), one row per call or session — a retried session
-(``<label>.a2``) and a wrap-up session included, even when the *next* attempt then
-raises. The run's clock (``BudgetGuard``) is checked at the session boundary.
-"""
+"""Code generation: one entry point, two strategies."""
from __future__ import annotations
@@ -61,12 +31,8 @@ from codeverse3d.workspace import C3D_DIR, Workspace
log = logging.getLogger(__name__)
-
-# ===================================================================== single-shot envelope
-# (merged back from codeverse3d/tracks/envelope.py, 2026-08-28 — the split existed only
-# to hold a re-export shim; this module was its one importer)
ALLOWED_ROOTS: tuple[str, ...] = ("src/", "public/")
-#: where an out-of-workspace task image is copied so a vendor CLI can read it (D9: a CLI reads only inside its workspace)
+#: where an out-of-workspace task image is copied so a vendor CLI can read it
IMAGES_DIR = f"{C3D_DIR}/images"
@@ -89,12 +55,7 @@ _FENCE_PATH_HINT = re.compile(
def parse_multifile(text: str, *, expected_files: list[str] | None = None) -> dict[str, str]:
- """Parse the ``system/singleshot_format.md`` envelope → ``{path: content}``.
-
- Tolerant to: a fenced block wrapping a file body; an answer that is ONE fenced
- block when exactly one entry file is expected; fenced blocks preceded by a line
- naming the path. Raises ``MultiFileParseError`` otherwise.
- """
+ """Parse the ``system/singleshot_format.md`` envelope → ``{path: content}``."""
files: dict[str, str] = {}
for m in _BLOCK.finditer(text):
path = _clean_path(m.group("path"))
@@ -104,7 +65,6 @@ def parse_multifile(text: str, *, expected_files: list[str] | None = None) -> di
fences = list(_FENCE.finditer(text))
expected = [_clean_path(p) for p in (expected_files or [])]
if fences:
- # fenced blocks preceded by a path mention
for m in fences:
probe = text[: m.start()][-400:].rstrip(" \t")
probe += ("" if probe.endswith("\n") else "\n") + "```"
@@ -127,16 +87,12 @@ _HEADER_LINE = re.compile(r"^[ \t]*===\s*FILE:\s*[^\n=]+?\s*===[ \t]*\r?\n")
def _strip_envelope_header(body: str) -> str:
- """A truncated answer (cut before ``=== END FILE ===``) reaches the single-file
- fallback with its ``=== FILE: … ===`` header still attached; treat the
- unterminated block as the file's body instead of shipping the header as line 1."""
m = _HEADER_LINE.match(body)
return body[m.end():] if m else body
def _clean_path(p: str) -> str:
- """Normalised (``//`` and ``./`` collapsed — ``src//lib/x.js`` IS ``src/lib/x.js``, so it must
- meet the harness-owned / scope checks as that), relative; a trailing ``/`` is kept."""
+ """Normalised path with ``//`` and ``./`` collapsed, so ``src//lib/x.js`` is ``src/lib/x.js``."""
p = p.strip().strip("`'\"").replace("\\", "/").lstrip("/")
if not p:
return p
@@ -160,7 +116,7 @@ def safe_relpath(path: str) -> str:
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 file
+ if p.endswith("/"):
raise 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}")
@@ -175,20 +131,7 @@ def write_files(
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
- to add README.md / package.json despite the format rule) or unwritable is
- SKIPPED — reported via ``on_skip`` — instead of aborting the whole write:
- the valid files were already paid for.
-
- ``only`` (an ``edit_only`` task's file scope, entry included when owned) skips a
- path that ALREADY EXISTS and is not listed — new files stay allowed; ``frozen``
- (the language's harness-owned files and directories, e.g. scene_threejs's ``src/lib/``) is
- skipped outright (``is_harness_owned``, the CLI side's rule).
- The single-shot envelope has no write-time gate, so this is where a scoped task is
- stopped from rewriting a sibling's file — the mirror of the CLI backends' post-hoc
- ``_enforce_scope`` (until 2026-08-29 only that side protected the harness files)."""
+ """Write parsed files under the workspace; returns git-style FileChange rows."""
scope = {_clean_path(p) for p in only} if only is not None else None
owned = {_clean_path(p) for p in frozen}
changes: list[FileChange] = []
@@ -218,9 +161,6 @@ def write_files(
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(content if content.endswith("\n") else content + "\n")
except OSError as e:
- # Same contract as an out-of-root path: one unwritable block (a path that
- # is already a directory, a name the filesystem rejects) must not throw
- # away the files that DID parse -- the whole answer was already paid for.
if on_skip is not None:
on_skip(raw, str(e))
log.warning("skipping unwritable file from generator: %s: %s", rel, e)
@@ -230,11 +170,7 @@ def write_files(
SINGLE_SHOT_PREFIX = "single-shot:"
-#: default cap on model turns per agent session: 0 = none, the session runs under the
-#: backend's own ``AgentJob.max_turns``. A 28-turn default was measured and rejected
-#: (A/B: no saving, −0.205 score) — see the module docstring and docs/COST.md §17.
DEFAULT_AGENT_MAX_TURNS = 0
-#: turns granted to the wrap-up session that lands a final build + summary when a cap IS set
DEFAULT_WRAPUP_TURNS = 6
WRAPUP_PROMPT = (
@@ -250,31 +186,21 @@ WRAPUP_PROMPT = (
def agent_max_turns(default: int = DEFAULT_AGENT_MAX_TURNS) -> int:
- """The turn cap a machine asks for: ``Settings.limits.agent_max_turns`` (also spelled
- ``C3D_AGENT_MAX_TURNS``) > ``default``.
-
- ``0`` means *no cap*: the caller leaves ``AgentJob.max_turns`` at the backend's
- own default. That is the measured default (docs/COST.md §17)."""
+ """The turn cap a machine asks for: ``Settings.limits.agent_max_turns`` when set, else ``default``."""
return get_settings().limits.agent_max_turns or max(0, int(default))
def turn_capped(res: Any) -> bool:
- """True when the agent stopped because it ran out of turns (not money/time).
-
- claude-code reports the subtype ``error_max_turns``; it surfaces as
- ``exit_reason="budget"``."""
if getattr(res, "exit_reason", "") != "budget":
return False
return any("max_turns" in str(e) for e in (getattr(res, "errors", None) or []))
-#: what a single-shot call thinks at when its task asks for nothing (``GenerationTask.thinking`` '')
SINGLE_SHOT_THINKING = "medium"
def session_effort(task: GenerationTask) -> AgentEffort | None:
- """``AgentJob.effort`` for ``task``: its ``thinking`` when the caller explicitly asked for an
- agent effort, else None — the backend's default (agy: ``AGY_API_EFFORT`` = high)."""
+ """``AgentJob.effort`` for ``task``: its ``thinking`` when the caller explicitly asked for an"""
return task.thinking if task.thinking in get_args(AgentEffort) else None # type: ignore[return-value]
@@ -300,7 +226,7 @@ class GenerationTask(BaseModel):
"explicit ask — the single-shot call uses it, and an agent session gets it as AgentJob.effort "
"(``off`` reaches no agent). No track asks for less than high today (D110)",
)
- max_output_tokens: int = 65_536 # the model's declared ceiling; unused tokens cost nothing
+ max_output_tokens: int = 65_536
timeout_s: int | None = None
edit_only: bool = Field(
default=False,
@@ -353,21 +279,16 @@ class GenerationResult(BaseModel):
@classmethod
def from_error(cls, label: str, e: BaseException) -> GenerationResult:
- """The failed result of a generation call that RAISED, classified by the error's type
- rather than its message: the round loop reads ``transient`` / ``quota``, never text."""
+ """The failed result of a generation call that RAISED, classified by the error's type"""
return cls(ok=False, notes=f"{type(e).__name__}: {e}", label=label, transient=is_model_outage(e))
def is_model_outage(e: BaseException) -> bool:
- """Is this a *service* failure (the model is down) rather than a bad answer?
-
- Read off the ``ModelError`` the models layer raises — ``retryable`` or an HTTP status of
- capacity / rate limiting — never off its message. A 503 capacity storm reaches us only
- after ``models.retry`` has already spent its whole storm budget waiting."""
+ """Is this a *service* failure (the model is down) rather than a bad answer?"""
from codeverse3d.models.base import ModelError
from codeverse3d.models.parts import retryable_status
- if isinstance(e, ModelError): # a spent key pool is retryable=False, status 429: an outage all the same
+ if isinstance(e, ModelError):
return bool(e.retryable) or retryable_status(e.status)
return False
@@ -383,19 +304,11 @@ def single_shot_model_id(agent_id: str) -> str:
return agent_id[len(SINGLE_SHOT_PREFIX) :]
-#: the floor of a single-shot call's own deadline. A task's ``timeout_s`` caps its model call:
-#: an asset task (420 s) once held a runaway stream for ~20 minutes — 1 087 chunks before the
-#: retry layer gave up — and the stage that waited for it left the zones a 180 s session that
-#: wrote nothing (iteration 2 of the argon loop, 2026-10-15: 31 of 2 697 single-shot asset calls
-#: ran past 420 s, all the way to the retry ceiling). But a stage degraded to single-shot by a
-#: spent soft budget carries the budget's FLOOR as its timeout (120-180 s), shorter than a
-#: legitimate call (asset calls p50 96 s, p95 260 s) — the floor keeps those whole.
SINGLE_SHOT_MIN_WAIT_S = 420.0
def single_shot_wait_s(timeout_s: float | None, retry_deadline_s: float) -> float:
- """The longest one single-shot generation may wait: the retry ceiling, capped by the task's own
- timeout when it has one (never below :data:`SINGLE_SHOT_MIN_WAIT_S`)."""
+ """The longest one single-shot generation may wait: the retry ceiling, capped by the task's own"""
if timeout_s is None:
return retry_deadline_s
return min(retry_deadline_s, max(float(timeout_s), SINGLE_SHOT_MIN_WAIT_S))
@@ -422,29 +335,18 @@ def generate_files(
temperature=task.temperature,
thinking=task.thinking or SINGLE_SHOT_THINKING,
max_output_tokens=task.max_output_tokens,
- # the RUN's remaining wall clock AND the task's own window, not the models' 1800 s
- # default — and past the hard ceiling this refuses to buy the call at all
max_wait_s=_deadline_preflight(budget, single_shot_wait_s(task.timeout_s, RETRY_DEADLINE_S)),
label=f"{task.label}:r{task.round:02d}",
)
def ask(r: ChatRequest) -> Any:
- # attributed like ``MeteredAgent.run``: stage from the task's kind, its round — the
- # label alone filed ``zones_*`` under ``other`` (audit 2026-09-24 N72)
with call_context(round=task.round, stage=stage_for_label(task.kind or task.label)):
return model.generate(r)
resp = ask(req)
usage = resp.usage
- # the clock is not enforced here: the response is already paid for, and raising would
- # discard it before transcript/parse/write_files — the round's generate step does
- # (steps.run_generation_tasks)
retry = False
if _is_truncated(resp):
- # cut off by max_output_tokens: the envelope is unterminated — one retry with a
- # DOUBLED budget beats writing a half-file. Already at the 65,536 model ceiling
- # there is nothing to grow: a re-ask would be byte-identical and full price, so
- # it is not bought (the default task budget IS the ceiling since 2026-08-27).
grown = min(task.max_output_tokens * 2, 65_536)
retry = grown > int(req.max_output_tokens or 0)
events.emit("generate.truncated", label=task.label, finish_reason=str(resp.finish_reason), retry=retry)
@@ -464,7 +366,7 @@ def generate_files(
label=task.label)
if _is_truncated(resp):
- if retry: # the RETRY was cut off too; the first cut is already in the log
+ if retry:
events.emit("generate.truncated", label=task.label, finish_reason=str(resp.finish_reason), retry=False)
return _result(f"truncated: finish_reason={resp.finish_reason}")
try:
@@ -492,10 +394,7 @@ def generate_files(
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 (a
- timed-out session that produced nothing bills nothing, so the accounting-driven
- check alone never fires) and clip the wait to the remaining wall clock (a flat
- 30-minute session once ran 9 minutes past the ceiling, measured 2026-08-27)."""
+ """Gate a session on the run clock: refuse to start past the hard ceiling, else return the wait to use."""
if budget is None:
return wait_s
budget.check()
@@ -518,33 +417,14 @@ def run_agent_task(
budget: BudgetGuard | None = None,
events: Any | None = None,
) -> GenerationResult:
- """CodingAgent path. ``ok`` = the agent changed files (envelope-vs-disk truth).
-
- A turn cap is applied only when the machine asks for one (``C3D_AGENT_MAX_TURNS`` >
- ``Settings.limits.agent_max_turns`` > :data:`DEFAULT_AGENT_MAX_TURNS`, which is 0 = the
- backend's own ``AgentJob.max_turns``; a 28-turn default was measured and rejected, see the
- module docstring). Hitting whatever cap is in force is not a failure: one
- short wrap-up session is asked for a final build and a summary, so the money
- already spent leaves a buildable workspace instead of a session that was cut
- off mid-edit. Every session — first attempt, silent-bail retry, wrap-up — is
- charged to ``budget`` as it ends, so nothing is lost when a later attempt raises."""
+ """CodingAgent path. ``ok`` = the agent changed files (envelope-vs-disk truth)."""
events = NULL_EVENTS if events is None else events
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
- # against the soft share handed every scene refine session after the 0.55 share
- # exactly the 120 s floor instead of the ≤ 900 s it asked for. A task with no
- # window of its own (repair) is still bounded by the soft share, so a failing
- # baseline cannot eat the refine rounds' half. (Both found by review 2026-08-29.)
timeout = _deadline_preflight(budget, timeout, soft=task.timeout_s is None)
- # 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:
- # ``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)
- turns_cap = agent_max_turns() # 0 = leave AgentJob's own default
+ turns_cap = agent_max_turns()
# typed job context honoured by every CodingAgent: round → trajectory dir + ToolContext,
# language/track → spatial tool filtering, files_hint → the edit_only scope.
language, track = _spec_lang_track(ws)
@@ -574,8 +454,7 @@ def run_agent_task(
changes = res.files_changed
if turn_capped(res):
- # the turns are gone, the money is not wasted: ask for a landing, not more work
- events.emit( # (the money itself is the session's ledger row)
+ events.emit(
"generate.turn_cap",
label=task.label,
round=task.round,
@@ -593,8 +472,6 @@ def run_agent_task(
not changes
and not acc.wrapped
and res.exit_reason not in ("timeout", "budget")
- # a provider failure or a spent usage limit is not a bail: a second session meets the
- # same wall (the round loop's one retry handles a transient)
and not (res.transient or res.quota)
):
events.emit("generate.silent_bail", label=task.label, exit_reason=res.exit_reason)
@@ -638,13 +515,7 @@ def run_agent_task(
class _SessionAcc:
- """Runs the agent sessions of ONE task and keeps their accounting.
-
- Each session is a ledger row the moment it returns (label ``<task>``/``<task>.a2`` for
- the retry, ``<task>.wrapup`` for the landing session — ``cost.instrument.MeteredAgent``),
- so a crash in a later session can never erase what an earlier one already spent — the
- ``.a2`` hole of docs/COST.md §6. The run's clock is checked before and after
- every session, including sessions whose vendor returned no usage."""
+ """Runs the agent sessions of ONE task and keeps their accounting."""
def __init__(self, *, task: GenerationTask, budget: BudgetGuard | None):
self.task = task
@@ -658,9 +529,7 @@ class _SessionAcc:
def run(
self, agent: Any, job: AgentJob, *, wrapup: bool = False, optional: bool = False
) -> AgentResult | None:
- """One session. ``optional`` sessions (wrap-up, silent-bail retry) never
- take the task down: a crash there leaves the earlier, already charged
- session as the result instead of discarding money that was really spent."""
+ """One session. ``optional`` sessions (wrap-up, silent-bail retry) never"""
self.sessions += 1
self.wrapped = self.wrapped or wrapup
label = self.task.label + (
@@ -678,8 +547,6 @@ class _SessionAcc:
self.errors.append(f"{label}: {type(e).__name__}: {e}")
return None
self.usage = self.usage + res.usage
- # the count as the BACKEND reports it: a size
- # signal for the generate.turn_cap event, not what the cap is enforced against
self.turns += res.turns
if self.budget is not None:
self.budget.check()
@@ -687,16 +554,7 @@ class _SessionAcc:
def _images_block(images: list[ImagePart], ws: Workspace) -> str:
- """The task's images (reference photos, the judged contact sheet) as a prompt
- section. No vendor CLI takes an image on argv, so the agent opens the files with
- its own file/image tools; until 2026-08-29 the only carrier was ``AgentJob.images``,
- which no backend read, so the contact sheet the judge scored reached no CLI session
- (that field is gone since 2026-08-30 — this block IS the delivery).
-
- Every image is copied into ``.3dcode/images/`` first (D9),
- and listed workspace-relative: a CLI reads only INSIDE its workspace (``--image
- ref.png`` stores the host's absolute path), and the judged contact sheet sits under
- ``artifacts/renders/``, which ``.antigravityignore`` hides from agy."""
+ """The task's images (reference photos, the judged contact sheet) as a prompt"""
paths: list[tuple[str, str]] = []
for i in images:
if not i.path:
@@ -706,7 +564,7 @@ def _images_block(images: list[ImagePart], ws: Workspace) -> str:
try:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dest)
- except OSError as e: # unreadable source: naming it is still better than silence
+ except OSError as e:
log.warning("task image %s could not be copied into %s: %s", src, dest, e)
paths.append((i.label or "image", str(src)))
continue
@@ -727,12 +585,7 @@ def _spec_lang_track(ws: Workspace) -> tuple[str, str]:
def _always_writable(language: str, task: GenerationTask) -> list[str]:
- """The entry file, exempt from ``edit_only`` — but only for a task that OWNS it.
-
- Owning tasks: ``owns_entry=True`` (assembly / whole-object / single-file tasks, and
- scoped refines whose prompt promises entry access) or a ``files_hint`` naming the
- entry. Part / zone / detail / asset tasks own nothing here — under the old
- unconditional exemption, parallel scoped sessions raced on the entry file unopposed."""
+ """The entry file, exempt from ``edit_only`` — but only for a task that OWNS it."""
try:
entry = ENTRY_FILE[Language(language)]
except (ValueError, KeyError):
@@ -741,8 +594,7 @@ def _always_writable(language: str, task: GenerationTask) -> list[str]:
def _envelope_scope(ws: Workspace, task: GenerationTask) -> tuple[set[str] | None, list[str]]:
- """``write_files``'s ``only`` (an ``edit_only`` task: files_hint + the entry when
- owned) and ``frozen`` (the language's harness-owned files) for a single-shot task."""
+ """The ``only`` set for ``write_files`` (an ``edit_only`` task's files plus the always-writable ones, else ``None``) and the frozen files."""
language, _ = _spec_lang_track(ws)
frozen = _read_only(language)
if not task.edit_only or not task.files_hint:
@@ -751,8 +603,7 @@ def _envelope_scope(ws: Workspace, task: GenerationTask) -> tuple[set[str] | Non
def _read_only(language: str) -> list[str]:
- """The harness-owned files of the language (scene_threejs's ``src/lib/``): every session
- of the run — baseline, refine, repair — may read them, none may write them."""
+ """The harness-owned files of the language (scene_threejs's ``src/lib/``): every session"""
try:
return list(HARNESS_OWNED_SRC.get(Language(language), ()))
except ValueError:
@@ -770,11 +621,7 @@ def generate(
budget: BudgetGuard | None = None,
events: Any | None = None,
) -> GenerationResult:
- """Dispatch to the single-shot or the coding-agent strategy by ``agent_id``.
-
- ``agent`` / ``model`` may be injected (tests, reuse); otherwise they are
- resolved lazily through ``codeverse3d.agents`` / ``codeverse3d.models``.
- """
+ """Dispatch to the single-shot or the coding-agent strategy by ``agent_id``."""
if is_single_shot(agent_id):
if model is None:
model = get_chat_model(single_shot_model_id(agent_id))
diff --git a/harness/codeverse3d/tracks/graphics.py b/harness/codeverse3d/tracks/graphics.py
index de606d7c..108db544 100644
--- a/harness/codeverse3d/tracks/graphics.py
+++ b/harness/codeverse3d/tracks/graphics.py
@@ -1,14 +1,4 @@
-"""GraphicsTrack: plan (GraphicsPlan) → skeleton → baseline → refine rounds → finalise.
-
-Languages: glsl_shader (Shadertoy-style fragment shader) · opengl_python (raw
-moderngl program). Reuses ``BaseTrack`` (lifecycle) and ``run_round`` (steps)
-unchanged; the track-specific pieces are the prompt context (no 3D frame) and the
-render step (the sampled frames + contact sheet as the RenderSet
-the ``shader`` judge sees); the ``gl_frames`` gate is the build's own
-(``BuildResult.gates``). Planning is ``tracks/planner.py``'s, like every track's
-(template, worked example, T = 0.5, acceptance: all dispatched on the track there).
-Refinement is always one whole-program task.
-"""
+"""GraphicsTrack."""
from __future__ import annotations
@@ -56,8 +46,7 @@ def passes_table(plan: GraphicsPlan | None) -> str:
def graphics_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
- """Every variable the graphics templates may reference (StrictUndefined): the base
- context (``prompting.base_prompt_context``) plus the graphics plan's own fields."""
+ """Every variable the graphics templates may reference (StrictUndefined)."""
plan = ctx.plan if isinstance(ctx.plan, GraphicsPlan) else None
res = plan.resolution if plan else (1280, 720)
return base_prompt_context(ctx, **{
@@ -103,9 +92,7 @@ def frames_render_set(ws: Workspace, build: BuildResult, round_index: int) -> Re
def frame_stats_text(ws: Workspace, round_index: int | None = None) -> str:
- """The frame metrics as judge / refine text: round ``round_index``'s own copy
- (``renders/rNN/metrics.json``), else the canonical file, quoted only for the round it belongs
- to — the LAST build's (no later round in the journal)."""
+ """The frame metrics as judge / refine text."""
where = ws.renders_dir(round_index) if round_index is not None else None
if round_index is not None and where is not None and not (where / METRICS_NAME).is_file():
later = any(int(p.stem[1:]) > round_index for p in (ws.root / "rounds").glob("r[0-9][0-9].json"))
@@ -123,8 +110,7 @@ def frame_stats_text(ws: Workspace, round_index: int | None = None) -> str:
class GraphicsPipeline:
- """No measurement; no gates of its own — the build's ``gl_frames`` report is the round's
- gate (``BuildResult.gates``, appended by ``steps``); render = the frames."""
+ """No measurement."""
def measure(self, ctx: RunContext, build: BuildResult) -> Measurement | None:
return None
diff --git a/harness/codeverse3d/tracks/lifecycle.py b/harness/codeverse3d/tracks/lifecycle.py
index f111ffe5..a45847fc 100644
--- a/harness/codeverse3d/tracks/lifecycle.py
+++ b/harness/codeverse3d/tracks/lifecycle.py
@@ -1,13 +1,4 @@
-"""BaseTrack: the resumable plan → pre-round stages → rounds → finalise lifecycle.
-
-Concrete tracks (static / articulated / scene / graphics) declare their pre-round graph
-(``stages``: :class:`StageNode` tuples, walked by :func:`run_stages`) and override the
-hooks (``plan_model``, ``make_pipeline``, ``baseline_tasks`` and the refine scaffold's
-``_refine_task``); what differs per track at PLANNING time is
-``tracks/planner.py``'s alone. All bookkeeping — workspace, events, budget, run
-state, stage cache, the fixed round count, record — lives here once. Which round of a
-finished run to hand over is not the core's question: ``codeverse3d.addons.select``.
-"""
+"""BaseTrack: the resumable plan → pre-round stages → rounds → finalise lifecycle."""
from __future__ import annotations
@@ -83,9 +74,7 @@ log = logging.getLogger(__name__)
def plan_stage_inputs(spec: Spec) -> dict[str, Any]:
- """Only the spec fields the PLAN depends on: hashing the whole Spec meant that
- raising ``budget.max_minutes`` in spec.json (the only way to continue a BUDGET-stopped
- run) re-planned + re-skeletoned on resume, overwriting src/ under existing rounds."""
+ """Only the spec fields the PLAN depends on: hashing the whole Spec meant that"""
return {
"prompt": spec.prompt,
"track": spec.track.value,
@@ -98,12 +87,6 @@ def plan_stage_inputs(spec: Spec) -> dict[str, Any]:
def plan_stage_key(spec: Spec, track: Track) -> dict[str, Any]:
- """The plan stage's cache key: a run's, and the one a pinned A/B plan is seeded under
- (``eval/bench/pin_plan``) — a seed under any other key is a cache MISS and re-plans.
-
- A variant (the spec's frozen one, else the active one) is part of the key ONLY when set: it may
- overlay the planner template, so its plan is cached — and a pinned plan seeded — under its name,
- while the default run's key never moves (``tests/prompts/manifest.py`` STAGE_HINT)."""
key: dict[str, Any] = {"spec": plan_stage_inputs(spec), "track": track.value}
variant = spec.options.variant or active_variant()
if variant:
@@ -112,47 +95,31 @@ def plan_stage_key(spec: Spec, track: Track) -> dict[str, Any]:
def spec_fingerprint(spec: Spec) -> str:
- """Identity of the spec THE PLAN depends on (hash of :func:`plan_stage_inputs`).
-
- Stamped into ``state.extra["spec_fingerprint"]`` on first run and verified by
- ``reconcile_resume``. Budget raises — the sanctioned way to continue a
- BUDGET-stopped run — are outside ``plan_stage_inputs`` and never change it."""
+ """Identity of the spec THE PLAN depends on (hash of :func:`plan_stage_inputs`)."""
return hash_inputs(plan_stage_inputs(spec))
class SpecChanged(RuntimeError):
- """spec.json's plan inputs changed under an existing run.
-
- Resuming would pair the recorded rounds with a new spec/plan in record.json —
- fake prompt→code provenance. Fork a new run, or resume with ``--force`` to
- archive the old rounds under ``rounds/pre_force/`` and re-plan."""
+ """spec.json's plan inputs changed under an existing run."""
# ============================================================================ the pre-round graph
@dataclass(frozen=True)
class StageNode:
- """One pre-round stage of a track's declared graph (``BaseTrack.stages``).
-
- ``key``: what the result depends on — the stage is cached under it (``stages/<name>.json``,
- ``StageRunner``), and served as recorded once rounds exist (``StageRunner.frozen``). ``None``:
- not cached, it runs every session (an idempotent step). ``when``: the ``Settings`` switch the
- stage runs under. ``seeds_src``: it writes the whole ``src/`` — never run once rounds exist,
- recorded or not. The result lands in ``ctx.extra[name]`` for the stages after it."""
+ """One pre-round stage of a track's declared graph (``BaseTrack.stages``)."""
name: str
- run: Callable[[Any, RunContext], Any] # (track, ctx) -> result
+ run: Callable[[Any, RunContext], Any]
key: Callable[[RunContext], dict[str, Any]] | None = None
when: Callable[[Settings], bool] | None = None
seeds_src: bool = False
-#: a track's pre-round graph, in order; an inner tuple = siblings that run side by side
Stages = tuple[StageNode | tuple[StageNode, ...], ...]
def run_stages(track: BaseTrack, ctx: RunContext, runner: StageRunner, stages: Stages) -> None:
- """Walk ``stages``. Siblings run side by side as ONE timed step of the run's minutes, each
- its own cached stage; a failing sibling is raised after every sibling finished and cached."""
+ """Walk ``stages``. Siblings run side by side as ONE timed step of the run's minutes, each"""
def one(node: StageNode, *, timed_step: bool = True) -> Any:
if node.key is None:
return node.run(track, ctx)
@@ -191,32 +158,22 @@ def _skeleton_key(ctx: RunContext) -> dict[str, Any]:
return {"plan": ctx.plan, "language": ctx.language.value}
-#: the buildable placeholder of every file the plan names
SKELETON = StageNode("skeleton", _skeleton, key=_skeleton_key, seeds_src=True)
-#: the vendor CLI's workspace files (AGENTS.md / CLAUDE.md, the ignore file): once per agent kind
MATERIALIZE = StageNode("materialize", lambda t, c: t.ensure_materialized(c))
-#: a stage boundary: the run stops here when the hard budget is spent
CLOCK = StageNode("clock", lambda t, c: c.budget.check())
class BaseTrack:
- """Shared lifecycle. Subclasses set ``track``, ``rubric``, ``plan_model``, their pre-round
- ``stages`` and parameterise the refine scaffold via the hooks below (``_refine_task`` …)."""
+ """Shared lifecycle. Subclasses set ``track``, ``rubric``, ``plan_model``, their pre-round"""
track: Track
rubric: str
plan_model: type[Plan]
- #: the pre-round graph, between the plan and round 0 (docs/ARCHITECTURE.md §7 is drawn from it)
stages: Stages = (SKELETON, MATERIALIZE)
generate_template: str = ""
refine_template: str = ""
- #: refine fan-out — the scene's zones / assets / env only: graphics is ONE whole-program task and the
- #: object tracks ONE whole-object session (D110)
allow_refine_fanout: bool = True
- #: share of the run budget the BASELINE may use (1.0 = no soft cap). The scene
- #: track lowers it so the refine rounds always inherit money and minutes.
soft_budget_fraction: float = 1.0
- #: the whole-program baseline session's sampling temperature
baseline_temperature: float = 0.5
def __init__(
@@ -247,7 +204,6 @@ class BaseTrack:
raise NotImplementedError
def baseline_tasks(self, ctx: RunContext) -> list[GenerationTask]:
- """Round 0: one whole-program session — ``generate_template`` over :meth:`generate_context`."""
files = ctx.runtime.expected_files(ctx.plan)
prompt = render(self.generate_template, **self.generate_context(
ctx, skeleton_files=skeleton_files(ctx) if ctx.single_shot else {}, previous_error=""))
@@ -260,23 +216,15 @@ class BaseTrack:
return language_system_prompt(ctx.language, tools=not ctx.single_shot)
def round_extra_notes(self, ctx: RunContext) -> list[str]:
- """Notes folded into every round record (e.g. 'the baseline was degraded')."""
return list(ctx.extra.get("degraded") or [])
def prepare_salvage(self, ctx: RunContext) -> bool:
- """Make the workspace buildable after a stage tripped the budget before
- round 0. Return False when the track has nothing to salvage. The default
- says yes exactly when the baseline left code past the pre-round stages — a
- session that committed (or wrote) before the clock stopped it, or the adopted
- best-of-N winner: paid code must not be thrown away by a ceiling trip before
- r00 (neon_glsl c007b166 spent $0.254 on a committed baseline and got 0 rounds).
- A bare skeleton still returns False."""
+ """Make the workspace buildable after a stage tripped the budget before"""
prepared = ctx.extra.get("prepared_commit")
return bool(prepared) and any(c.path.startswith(ALLOWED_ROOTS) for c in ctx.ws.changed_files(since=prepared))
# ---- refine hooks (the scaffold below is shared; tracks fill in the task)
def refine_file_for_target(self, ctx: RunContext) -> Callable[[str], list[str]]:
- """``target → [files]`` for refine tasks: the runtime's layout (``[]`` = no owner)."""
return lambda target: ctx.runtime.files_for(ctx.plan, target)
def extra_refine_tasks(self, ctx: RunContext, last: RoundRecord) -> Sequence[Any]:
@@ -293,10 +241,7 @@ class BaseTrack:
# ------------------------------------------------------------------ refine scaffold
def refine_tasks(self, ctx: RunContext, last: RoundRecord) -> tuple[list[GenerationTask], list[str]]:
- """The round after ``last``: rebuild guard → instructions → groups → per-track ``_refine_task``.
-
- Always built on ``last`` — the previous round, whatever it scored (2026-09-22: no
- refine-from-best, no whole-artifact rewrite after a regression)."""
+ """The round after ``last``: rebuild guard → instructions → groups → per-track ``_refine_task``."""
index = last.index + 1
if last.build is None or not last.build.ok:
rebuild = self._rebuild_task(ctx, last, index).model_copy(update={"reserve_s": ctx.policy.judge_reserve_s})
@@ -329,23 +274,12 @@ class BaseTrack:
def run(self, spec: Spec, ws: Workspace, *, resume: bool = False, force: bool = False) -> RunRecord:
ws.create()
variant = self.variant_for(spec)
- # the run's own ledger even when nobody opened one (a test, a script): the CLI /
- # bench open the same file first and run_ledger nests, restoring theirs on exit.
- # Keep THEIR name when they bound one — a compare_backends cell is "<prompt>:<arm>",
- # and rebinding it to the directory ("run") collapsed every cell into one bucket.
- # The variant overlay (D105) wraps the WHOLE run: every prompt file, template and skill
- # bundle below resolves through it, in the fan-out threads too (proc.fan_out copies the
- # context); a resume re-activates what the spec froze. Its knobs hold for exactly as long.
with activate(variant), run_ledger(ws.root, run=run_binding().run or ws.root.name), \
self._apply_variant(variant) as knobs:
if not ws.spec_path.is_file() or not resume:
ws.write_json(ws.spec_path, spec)
events = EventLog(ws.events_path)
state = RunState.load_or_new(ws, resume=resume)
- # BEFORE build_context (which restores the budget snapshot from state.extra):
- # make the state agree with the durable round journal, verify spec identity,
- # and take the reconciled rounds as the loop's initial history — so the
- # FAILED/BUDGET handlers below serialize the real rounds, never [].
rounds: list[RoundRecord] = self.reconcile_resume(spec, ws, events, state, resume=resume, force=force)
ctx = self.build_context(spec, ws, events, state)
runner = StageRunner(ws, events, state, frozen=bool(rounds))
@@ -361,7 +295,7 @@ class BaseTrack:
model=self.plan_model)
self.after_plan(ctx)
run_stages(self, ctx, runner, self.stages)
- ctx.extra["prepared_commit"] = ws.head() # what a salvage compares the baseline's work with
+ ctx.extra["prepared_commit"] = ws.head()
stop = self._round_loop(ctx, rounds)
except BudgetExceeded as e:
events.emit("budget.exceeded", reason=e.reason)
@@ -370,7 +304,7 @@ class BaseTrack:
except Exception as e: # noqa: BLE001 — persist a FAILED record, then fail loud
error = f"{type(e).__name__}: {e}"
events.emit("run.failed", error=error, traceback=traceback.format_exc()[-3000:])
- self._save_budget(ctx) # the clock and the step log must survive for resume
+ self._save_budget(ctx)
state.status, state.error = RunStatus.FAILED, error
state.save(ws)
rec = self._record(ctx, rounds, RunStatus.FAILED, error=error)
@@ -378,23 +312,15 @@ class BaseTrack:
raise
return self.finalise(ctx, rounds, stop, error=error)
- # ------------------------------------------------------------------ the variant (D105)
+ # ------------------------------------------------------------------ the variant
@staticmethod
def variant_for(spec: Spec) -> str:
- """The variant this run activates: the spec's frozen choice (``3dcode make --variant``,
- ``run_bench --variant``), else the process switch — ``C3D_VARIANT``, or ``C3D_VARIANTS`` by the
- generator id — read from ``get_settings()`` like every other switch, so a direct ``track.run``
- under an A/B arm's environment honours it. An unknown name raises before anything is paid."""
+ """The variant this run activates: the spec's frozen choice, else the one resolved for its generator."""
return spec.options.variant or resolve_variant(get_settings(), spec.backends.generator)
@contextmanager
def _apply_variant(self, variant: str) -> Iterator[dict[str, Any]]:
- """The variant's ``[knobs]`` as defaults on the process settings (where ``attach_skills`` reads
- ``skills_max`` / ``skills_only``) and on an injected ``Settings`` too, for the RUN ONLY: both
- objects outlive it (the singleton, a rig's shared Settings), so the prior values and field-sets
- come back on exit and the next run of this process starts from its own base, never from a knob
- the last variant left behind (``knobs_applied``). A user-stated field wins
- (``apply_variant_knobs``). Yields what was set, for the ``variant.active`` event."""
+ """Apply the variant's ``[knobs]`` as defaults on the process settings for the duration of the run."""
if not variant:
yield {}
return
@@ -408,28 +334,6 @@ class BaseTrack:
# ------------------------------------------------------------------ resume reconciliation
def reconcile_resume(self, spec: Spec, ws: Workspace, events: EventLog, state: RunState,
*, resume: bool, force: bool) -> list[RoundRecord]:
- """The round history a resume goes on from: the on-disk round journal (``rounds/rNN.json``
- + its git commit, written at the end of every round) — the one record of it; the state file
- keeps no copy that a crash could leave behind. On resume:
-
- 1. **Spec identity.** ``state.extra["spec_fingerprint"]`` (hash of
- :func:`plan_stage_inputs`, stamped on first run) must match the spec we are
- resuming with; budget raises are outside the fingerprint by construction.
- On a mismatch a plain resume raises :class:`SpecChanged`; ``--force``
- emits ``resume.spec_changed`` and re-plans — old rounds are never paired with a
- new spec/plan. ``--force`` archives the old journal + ``record.json`` to
- ``rounds/pre_force/`` whether the spec changed or not: with no rounds left the
- pre-round stages are no longer frozen (``StageRunner.frozen``), so this is the
- one way to regenerate a stage whose key drifted under existing rounds.
- 2. **Journal integrity.** Trailing rounds whose commit git does not have are
- dropped (half-written journal), with a ``resume.dropped_rounds`` event.
- 3. **The tree.** The working tree goes back on the LAST round's commit when anything
- left it elsewhere — a crash mid-round, or the finalise of a run recorded before
- 2026-09-22, which restored its best round. The next round refines the round
- before it, always.
-
- Returns the loop's initial round history. A fresh (non-resume) run only
- stamps the fingerprint and starts empty."""
fp = spec_fingerprint(spec)
stored = str(state.extra.get("spec_fingerprint") or "")
if not resume:
@@ -448,7 +352,7 @@ class BaseTrack:
)
events.emit("resume.spec_changed", old_fingerprint=stored, new_fingerprint=fp,
archived_rounds=len(journal))
- state.stages.pop("plan", None) # the plan must be rebuilt from the edited spec
+ state.stages.pop("plan", None)
if force and (journal or ws.record_path.is_file()):
archived = self._archive_pre_force(ws)
events.emit("resume.archived", dest=str(archived), rounds=len(journal))
@@ -458,7 +362,7 @@ class BaseTrack:
dropped: list[int] = []
for rec in journal:
if dropped or not rec.commit or not ws.has_commit(rec.commit):
- dropped.append(rec.index) # half-written tail: rNN.json without its commit
+ dropped.append(rec.index)
else:
kept.append(rec)
if dropped:
@@ -477,8 +381,6 @@ class BaseTrack:
@staticmethod
def _archive_pre_force(ws: Workspace) -> Path:
- """Move the old journal + record.json under ``rounds/pre_force/`` (never delete
- evidence; a second --force lands in ``pre_force_2/`` and so on)."""
rounds_dir = ws.root / "rounds"
dest, n = rounds_dir / "pre_force", 1
while dest.exists():
@@ -502,8 +404,6 @@ class BaseTrack:
# the active minutes keep counting, so a raised cap (--max-minutes / --rounds)
# grants only the difference, never a fresh full cap
budget.restore(BudgetSnapshot.model_validate(snap))
- # the judge sample count is the settings' (a profile's), however the track was built:
- # `3dcode make` and a bench battery judge alike (N74; it was resolved in the CLI only)
policy = self._policy or RoundPolicy(max_rounds=spec.budget.max_rounds,
judge_samples=max(1, int(settings.judge.samples or 1)))
policy = replace(policy, n_candidates=self._resolve_candidates(spec, settings))
@@ -511,8 +411,6 @@ class BaseTrack:
ctx = RunContext(spec=spec, ws=ws, events=events, settings=settings, budget=budget, runtime=runtime,
services=self.services, state=state, policy=policy, track=self.track, rubric=rubric,
agent_id=spec.backends.generator,
- # metered like the ones services hand out: an injected agent or model spends
- # money too, and the ledger is the only record of it
agent=metered_agent(self._agent), model=metered_chat_model(self._model),
variant=active_variant())
ctx.contract_text = language_text(spec.language, "contract.md")
@@ -521,9 +419,7 @@ class BaseTrack:
return ctx
def _resolve_candidates(self, spec: Spec, settings: Settings) -> int:
- """Best-of-N width: constructor (CLI --candidates) > ``spec.options.candidates``
- (the persisted carrier — spec.json travels with the run) > settings default. 1 on a
- track without best-of-N (``TrackInfo.best_of_n``): the record names the width that ran."""
+ """Best-of-N width: constructor value, else ``spec.options.candidates``, else the settings default."""
if not TRACK_INFO[self.track].best_of_n:
return 1
n = self._n_candidates
@@ -534,8 +430,7 @@ class BaseTrack:
return max(1, int(n or 1))
def make_judge(self, ctx: RunContext, *, n_samples: int | None = None) -> Any:
- """The main judge: injected, else the class ``judges.vlm_judge.judge_for`` names (the rule
- ``3dcode judge`` and calibration replay with), built through the services seam."""
+ """The main judge: the injected one, else an instance of the class ``judge_for`` picks for this track."""
if self._judge is not None:
return self._judge
from codeverse3d.judges.vlm_judge import LikenessJudge, ReferenceJudge, judge_for
@@ -552,8 +447,6 @@ class BaseTrack:
"""Bind judge / generator backends once the plan exists."""
if ctx.judge is None:
ctx.judge = self.make_judge(ctx)
- # provenance: the judge protocol (role prompt + rig rules + wire schema) is hashed
- # like the generator prompts, so a judge-prompt edit is visible in record.json
judge_hash = getattr(ctx.judge, "prompt_hash", "")
if isinstance(judge_hash, str) and judge_hash:
ctx.prompt_hashes["judge"] = judge_hash
@@ -570,7 +463,7 @@ class BaseTrack:
plan = run_planner(ctx.spec, ctx.spec.backends.planner, self.plan_model, ctx.ws,
model=metered_chat_model(self._planner_model), events=ctx.events, budget=ctx.budget)
finally:
- self._save_budget(ctx) # the clock and the plan step, on success AND PlanningError
+ self._save_budget(ctx)
return plan
# ------------------------------------------------------------------ stages
@@ -592,14 +485,6 @@ class BaseTrack:
# ------------------------------------------------------------------ round loop
def _round_loop(self, ctx: RunContext, rounds: list[RoundRecord]) -> RunStatus:
- """The baseline, then ``max_rounds`` refine rounds — each built on the round before it.
-
- FIXED rounds (owner, 2026-09-22): the judge scores every round and its verdict shapes
- the next round's tasks, but nothing here decides that another round is not worth
- buying. The run stops early only on the clock (``BudgetGuard``) or a hard failure:
- the vendor's quota, a refine round whose sessions changed nothing, or a last round
- that leaves nothing to ask for (no gate error, no failed must-item, no judge plan) or
- no verdict to ask from."""
pipeline = self.make_pipeline()
rejudged: set[int] = set()
transport_retried: set[int] = set()
@@ -615,17 +500,13 @@ class BaseTrack:
index = len(rounds)
last = rounds[-1] if rounds else None
if _unjudged(last) and last.index not in rejudged and ctx.budget.ok():
- # judge outage/degraded verdict on a clean build: re-judge the SAME commit once
- # (no regeneration) — before planning refinements from nothing, and before the
- # last round ends the run unscored (`--rounds 0` used to stop MAX_ROUNDS with an
- # unjudged baseline: the re-judge lived in the refine branch only)
rejudged.add(last.index)
if rejudge_round(ctx, pipeline, last, previous=previous_verdict(rounds, last.index)):
self._save_budget(ctx)
- if index > ctx.policy.max_rounds: # the baseline + max_rounds refine rounds all ran
+ if index > ctx.policy.max_rounds:
return _stop(RunStatus.JUDGE_UNAVAILABLE if _unjudged(last) else RunStatus.MAX_ROUNDS)
if not ctx.budget.ok():
- if not rounds: # the stages spent the clock without raising: the ONE budget path (salvage)
+ if not rounds:
ctx.budget.check()
return _stop(RunStatus.BUDGET)
previous = previous_verdict(rounds, index)
@@ -641,9 +522,6 @@ class BaseTrack:
# that is only because the judge never scored the round, say so.
return _stop(RunStatus.JUDGE_UNAVAILABLE if _unjudged(last) else RunStatus.NO_REFINE_TASKS)
if last is not None and not ctx.policy.can_open(ctx.budget, single_shot=ctx.single_shot):
- # D112: a refine round (or its transport / stall retry) that cannot also be built and
- # judged before the clock stops is money for edits nobody scores (iteration 5, r1_09:
- # the retry launched with 15 min left, was cut at the budget edge, never judged)
ctx.events.emit("round.skipped_budget", round=index, left_s=round(ctx.budget.left_s(), 1),
need_s=ctx.policy.need_s(single_shot=ctx.single_shot))
return _stop(RunStatus.BUDGET)
@@ -658,54 +536,26 @@ class BaseTrack:
extra_notes=self.round_extra_notes(ctx))
except RoundFailed as e:
if e.quota:
- # The vendor's own usage limit: not a transport death (a retry meets the
- # same wall) — the agent is gone until the limit resets. cmp8
- # (2026-09-09): three runs filed a plateau on "You've hit your usage
- # limit … try again at Sep 14th".
ctx.events.emit("round.agent_quota", round=index, detail=str(e)[:500])
if index == 0:
raise
return _stop(RunStatus.AGENT_QUOTA)
if index not in transport_retried and (e.transient or e.stalled):
- # A 503 storm / dropped socket / overloaded provider is not an agent
- # verdict — the session never really happened. Re-run the SAME
- # round once, baseline included (rc=247 alone killed three whole
- # runs on 2026-08-29), before letting the failure mean anything.
- # ``continue`` re-enters through the loop head, so the budget and
- # round ceilings still guard the retry. Typed since 2026-09-22
- # (RoundFailed.transient): a session that merely timed out on its own
- # work, or a CLI that crashed with no provider error, is not retried. A session
- # the watchdog found HUNG (``stalled``: idle, nothing produced) is retried by the
- # same rule, whatever the vendor's log says (D112); the window check at the loop
- # head keeps the retry from launching when it could not also be judged.
transport_retried.add(index)
ctx.events.emit("round.transport_retry", round=index, stalled=e.stalled and not e.transient,
detail=str(e)[:500])
continue
if index == 0:
raise
- # every session of a refine round failed or changed nothing: the next round
- # would be asked the same thing from the same code
ctx.events.emit("round.no_change", round=index, detail=str(e)[:500])
return _stop(RunStatus.NO_CHANGE)
rounds.append(rec)
self._save_budget(ctx)
def _salvage(self, ctx: RunContext, rounds: list[RoundRecord]) -> None:
- """The budget stopped the run with work nobody has judged: give ONE bounded grace and run
- a no-generation round (build → gates → render → judge) on what is in the workspace.
-
- * Before round 0 (the greenhouse scene: the zone fan-out crossed the ceiling, so the run
- finished with no build, no render, no judge and no score at all): the baseline.
- * After it (D112): a refine round whose sessions changed files before the clock stopped
- them — a session cut at the budget edge, or a round stopped after its generate step.
- Iteration 5, r1_09: the transport retry's edits (the camera that capped the run at 0.60)
- were committed and thrown away; finalise rebuilt round 0. A refine killed by its OWN
- hard limit was always built and judged (iteration 4, the same run: 0.817).
-
- Any failure here is swallowed: the run is already stopping on budget."""
+ """The budget stopped the run with work nobody has judged: give ONE bounded grace and run"""
if ctx.plan is None:
- return # the PLAN itself blew the budget → nothing to salvage
+ return
last = rounds[-1] if rounds else None
edits: list[str] = []
if last is not None:
@@ -713,7 +563,7 @@ class BaseTrack:
return
edits = [f.path for f in ctx.ws.changed_files(last.commit) if f.path.split("/", 1)[0] in ("src", "public")]
if not edits:
- return # the stop came before anything changed: the last round IS the work
+ return
grace_min = max(5.0, ctx.spec.budget.max_minutes * 0.15)
ctx.budget.grant_grace(minutes=grace_min)
reason = ("no round completed before the clock stop" if last is None
@@ -744,11 +594,8 @@ class BaseTrack:
# ------------------------------------------------------------------ finalise
def finalise(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, error: str = "") -> RunRecord:
- """Write the record. The workspace ENDS AT THE LAST ROUND: a round the budget or a crash
- cut mid-way can leave src/ past it, so it is put back and rebuilt — the only restore a
- run does (every round's own build is kept under artifacts/rNN/, and choosing a round
- to hand over is ``codeverse3d.addons.select``'s job, after the run)."""
- self._save_budget(ctx) # the clock and an aborted round's steps must survive for resume
+ """Write the record. The workspace ENDS AT THE LAST ROUND: a round the budget or a crash"""
+ self._save_budget(ctx)
last = rounds[-1] if rounds else None
rebuild_err = ""
rebuild_ok = False
@@ -758,7 +605,7 @@ class BaseTrack:
try:
build = ctx.runtime.build(ctx.ws, timeout_s=ctx.settings.limits.build_timeout_s)
ctx.events.emit("finalise.rebuild", round=last.index, ok=build.ok)
- if not build.ok: # the runtime invalidated the canonical artifact FIRST — it is gone
+ if not build.ok:
rebuild_err = f"{build.error_type or 'BuildFailed'}: {build.error_message}"[:300]
else:
rebuild_ok = True
@@ -766,16 +613,12 @@ class BaseTrack:
rebuild_err = f"{type(e).__name__}: {e}"[:300]
ctx.events.emit("finalise.rebuild_failed", error=rebuild_err)
if rebuild_err:
- # keep the earned status + scores; the record says the artifact is gone
ctx.extra["finalise_rebuild_failed"] = rebuild_err
error = error or f"finalise rebuild failed: {rebuild_err}"
elif rebuild_ok:
- # a rebuild that RAN and succeeded clears the stale flag a prior failed finalise
- # left (the prior-record merge would otherwise carry it forward); no-rebuild
- # resumes keep the prior flag — the artifact may still be the missing one
ctx.extra["finalise_rebuild_failed"] = ""
ctx.state.status, ctx.state.stop_reason, ctx.state.error = status, status.value, error
- self._save_budget(ctx) # saves state too
+ self._save_budget(ctx)
rec = self._record(ctx, rounds, status, error=error)
self.services.finalize_record(ctx.ws, rec)
ctx.events.emit("run.done", status=status.value, rounds=len(rounds),
@@ -785,8 +628,7 @@ class BaseTrack:
@staticmethod
def _needs_restore(ws: Workspace, commit: str) -> bool:
- """src/ != ``commit``: HEAD moved on, OR an aborted round dirtied the tree
- without committing (budget stop mid-generation) — HEAD alone cannot see that."""
+ """src/ != ``commit``: HEAD moved on, OR an aborted round dirtied the tree"""
if ws.head() != commit:
return True
try:
@@ -796,10 +638,7 @@ class BaseTrack:
return False
def _record(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, error: str) -> RunRecord:
- """The run record. Its ``total_usage`` is the sum of the run's ledger at list price —
- every billed row once: the planner, the scene stages, aborted rounds, retried sessions,
- round-trips the provider billed and the call discarded — not a sum kept here."""
- cands = ctx.ws.root / "rounds" / "candidates.json" # best-of-N summary: the file is the one copy
+ cands = ctx.ws.root / "rounds" / "candidates.json"
extra: dict[str, Any] = {"stop_reason": status.value, "rubric": ctx.rubric, "budget": ctx.budget.summary(),
"n_candidates": ctx.policy.n_candidates,
"candidates": ctx.ws.read_json(cands) if cands.is_file() else None,
@@ -807,19 +646,11 @@ class BaseTrack:
if ctx.extra.get("finalise_rebuild_failed"):
extra["finalise_rebuild_failed"] = ctx.extra["finalise_rebuild_failed"]
if ctx.extra.get("aborted_rounds"):
- # rounds the budget (or a crash) cut after the money was spent: they are not
- # in ``rounds``, so name them here (their dollars are in the ledger, the total).
extra["aborted_rounds"] = ctx.extra["aborted_rounds"]
- # A resume rewrite must not drop what earlier sessions / other packages put on
- # the record post-hoc (flywheel captions, prior
- # sessions' aborted_rounds, prompt hashes of stages not re-executed): seed from
- # the prior record — unknown keys preserved, this session's values win.
- # the variant this session ran under (D105): name/version/hash beside the prompt hashes, so two
- # runs can be told apart by what their models were shown; the base writes "" / 0 / "" and no hash
variant = variant_block(ctx.variant)
extra["variant"] = variant
prior_extra, prior_hashes = self._prior_record_fields(ctx.ws)
- if ctx.extra.get("finalise_rebuild_failed", None) == "": # rebuilt successfully this session
+ if ctx.extra.get("finalise_rebuild_failed", None) == "":
prior_extra.pop("finalise_rebuild_failed", None)
prior_aborted = prior_extra.get("aborted_rounds")
for k, v in prior_extra.items():
@@ -832,7 +663,7 @@ class BaseTrack:
if ctx.variant and variant["hash"]:
hashes["variant"] = variant["hash"]
elif not ctx.variant:
- hashes.pop("variant", None) # a prior session's overlay is not this session's
+ hashes.pop("variant", None)
return RunRecord(
spec=ctx.spec, plan=ctx.plan, workspace=str(ctx.ws.root), status=status, rounds=rounds,
total_usage=ledger_usage(load_ledger(ctx.ws.root)), steps=list(ctx.state.steps),
@@ -844,19 +675,16 @@ class BaseTrack:
)
def sampling(self, judge: Any) -> dict[str, dict[str, Any]]:
- """``record.extra["sampling"]``: the knobs this run's API roles sampled with — the
- planner's temperature (``plan_temperature``: graphics 0.5, the rest 0.4) and the judge's
- own temperature / thinking / samples. The settings snapshot reads it."""
+ """``record.extra["sampling"]``: the knobs this run's API roles sampled with."""
knobs = {k: getattr(judge, k) for k in ("temperature", "thinking", "n_samples")
if isinstance(getattr(judge, k, None), (int, float, str))}
return {"planner": {"temperature": plan_temperature(self.track)}, **({"judge": knobs} if knobs else {})}
@staticmethod
def _prior_record_fields(ws: Workspace) -> tuple[dict[str, Any], dict[str, str]]:
- """``(extra, prompt_hashes)`` of the record.json a previous session wrote
- (empty when there is none / it cannot be read — never run-fatal)."""
+ """``(extra, prompt_hashes)`` of the record.json a previous session wrote"""
prior = read_json_or_none(ws.record_path)
- if prior is None: # a corrupt old record must not block finalise
+ if prior is None:
if ws.record_path.is_file():
log.warning("prior record.json unreadable; post-hoc extra keys not carried over")
return {}, {}
diff --git a/harness/codeverse3d/tracks/plan_features.py b/harness/codeverse3d/tracks/plan_features.py
index 7a8b35fe..48fb5f73 100644
--- a/harness/codeverse3d/tracks/plan_features.py
+++ b/harness/codeverse3d/tracks/plan_features.py
@@ -1,27 +1,12 @@
-"""What an A/B rig may assume about a ``C3D_*`` switch — ``eval/bench/ab_plan.py`` asks.
+"""Plan-feature switches that change generation-side behaviour."""
-Eval-only: no runtime module imports this. Every switch the harness reads is a ``Settings``
-field (``config.py``), so which names are live is derived from ``Settings.model_fields``
-instead of a hand-kept list: an arm that differs only by a name no field reads is
-byte-identical to its control (one A/B printed "keep, mean delta +0.344" for two such arms,
-CQ-5), and ``ab_plan`` refuses it. ``pin_plan_blockers`` keeps ``--pin-plan`` from sharing
-one plan across arms whose switch acts at or before planning.
-"""
from __future__ import annotations
from codeverse3d.config import Settings
-#: switches that act AFTER planning — ``--pin-plan`` may share one plan across arms that
-#: differ only by these. Anything else is treated as plan-side: refusing to pin costs one
-#: noisy A/B, pinning wrongly costs a confident wrong answer (eval/docs/EVAL.md §8.1
-#: measured it — the A/A's worst pair differed 1 part vs 10). ``C3D_VARIANT`` / ``C3D_VARIANTS``
-#: (``prompts/variants.py``, D105) are deliberately NOT here: a variant overlays prompt files, the
-#: planner templates included, and its name is part of the plan stage key
-#: (``lifecycle.plan_stage_key``) — two arms that differ by variant must each plan.
GENERATION_SIDE_ENV: frozenset[str] = frozenset({"C3D_SKILLS", "C3D_SKILLS_MAX", "C3D_SKILLS_UNVERIFIED",
"C3D_SKILLS_ONLY", "C3D_REFERENCE_DIFF"})
-#: the two the node side reads itself (runtime_js: gpu_launch.cjs, browser_daemon.cjs)
NODE_SIDE_ENV: frozenset[str] = frozenset({"C3D_BROWSER_REUSE", "C3D_PAGE_TTL_MS"})
@@ -37,19 +22,12 @@ def _read(key: str) -> bool:
def dead_env_keys(env: dict[str, str]) -> list[str]:
- """The ``C3D_*`` keys of ``env`` that no Settings field reads — empty when the arm really
- differs. A key outside the ``C3D_`` family is not judged (it may matter to a CLI)."""
+ """The ``C3D_*`` keys of ``env`` that no Settings field reads — empty when the arm really"""
return sorted(k for k in env if k.startswith("C3D_") and not _read(k))
def pin_plan_blockers(variant_env: dict[str, str]) -> list[str]:
- """Which of ``variant_env``'s switches forbid sharing one plan between the arms.
-
- Empty list = every switch this A/B changes acts after planning, so both arms can be
- seeded with the same ``plan.json`` and the paired difference stops carrying the
- planner's spread (the dominant variance term, eval/docs/EVAL.md §8.1). A dead key
- blocks nothing: no code reads it, so it cannot change a plan.
- """
+ """Which of ``variant_env``'s switches forbid sharing one plan between the arms."""
dead = set(dead_env_keys(variant_env))
return [f"{key} is not known to act after planning" for key in sorted(variant_env)
if key not in GENERATION_SIDE_ENV and key not in dead]
diff --git a/harness/codeverse3d/tracks/planner.py b/harness/codeverse3d/tracks/planner.py
index 51c7e5b8..0acd4321 100644
--- a/harness/codeverse3d/tracks/planner.py
+++ b/harness/codeverse3d/tracks/planner.py
@@ -1,24 +1,4 @@
-"""Planner: spec → validated Plan (StaticPlan / ArticulatedPlan / ScenePlan / GraphicsPlan).
-
-The ONE owner of what differs per track at planning time — the system-prompt template
-(``PLAN_TEMPLATES``), the worked example (``plan_example``), the sampling temperature
-(``plan_temperature``), the output-token floor, the plan budget's unit (graphics counts
-passes) and the deterministic acceptance items (``ensure_acceptance``): all dispatched on
-``spec.track``, so no track class parameterises the loop.
-
-An optional cheap **brief expansion** (``expand_brief``, below) turns the one-line
-request into an engineering brief, which — together with a **plan budget derived
-from the request** — goes into one structured ``ChatRequest`` (system prompt from
-``prompts/tracks/plan_<track>.j2``, ``response_schema`` = the plan model's JSON
-schema, reference images inline). The answer is validated IN CODE by the pydantic
-plan models; a plan the schema rejects is re-asked twice with the exact validation
-errors, plus one restart from the request when it is degenerate (then ``PlanningError``),
-and a plan that validates but is boxes-at-different-sizes against its budget is re-asked
-once with that specific complaint (then shipped anyway — a mediocre plan beats no plan). The harness
-finally appends deterministic acceptance items derived from the spec constraints
-and folds the brief + sub-parts into the plan's own text (generated artifacts are
-weak links — framework-owned requirements never rely on the model remembering them).
-"""
+"""Planner: spec → validated Plan (StaticPlan / ArticulatedPlan / ScenePlan / GraphicsPlan)."""
from __future__ import annotations
@@ -72,11 +52,7 @@ def brief_cache_dir() -> Path:
def _reference_digest(spec: Spec) -> list[dict[str, str]]:
- """Identify the reference images by path AND content hash.
-
- The same path can hold different bytes from one run to the next, so the path
- alone does not separate two runs; the bytes do. An unreadable file
- still contributes its path, so it can never collapse onto "no references"."""
+ """Identify the reference images by path AND content hash."""
out: list[dict[str, str]] = []
for r in spec.references:
try:
@@ -88,13 +64,7 @@ def _reference_digest(spec: Spec) -> list[dict[str, str]]:
def brief_cache_key(spec: Spec, model_id: str) -> str:
- """Every input to the call must be in the key.
-
- ``expand_brief`` attaches ``spec.references`` to the request and tells the model
- to read the dimensions and features off them, so a key that omits them lets an
- ``--image`` run drink a brief generated WITHOUT the image (and vice versa) —
- silently, from the machine-wide ~/.cache/codeverse3d/briefs, with cached=True in
- events.jsonl."""
+ """Every input to the call must be in the key."""
c = spec.constraints
payload = json.dumps({
"prompt": spec.prompt.strip(), "track": spec.track.value, "language": spec.language.value,
@@ -108,10 +78,7 @@ def brief_cache_key(spec: Spec, model_id: str) -> str:
def expand_brief(spec: Spec, model_id: str, *, model: Any | None = None, events: Any | None = None,
cache_dir: Path | None = None) -> tuple[EngineeringBrief | None, Usage]:
- """One cheap structured call → :class:`EngineeringBrief`, cached by prompt hash.
-
- Never raises and never blocks planning: any failure returns ``(None, usage)`` and the
- planner runs exactly as it did before."""
+ """One cheap structured call → :class:`EngineeringBrief`, cached by prompt hash."""
events = NULL_EVENTS if events is None else events
usage = Usage()
cdir = cache_dir if cache_dir is not None else brief_cache_dir()
@@ -125,7 +92,7 @@ def expand_brief(spec: Spec, model_id: str, *, model: Any | None = None, events:
events.emit("plan.brief", cached=True, key=key, n_sub=len(brief.sub_assemblies),
n_signature=len(brief.signature_features), cost_usd=0.0)
return brief, usage
- except (ValidationError, ValueError, OSError) as e: # a stale/corrupt cache entry is not fatal
+ except (ValidationError, ValueError, OSError) as e:
log.warning("brief cache %s unusable (%s); regenerating", path, e)
if model is None:
model = get_chat_model(model_id)
@@ -151,7 +118,7 @@ def expand_brief(spec: Spec, model_id: str, *, model: Any | None = None, events:
events.emit("plan.brief_failed", error=f"{type(e).__name__}: {e}"[:300])
return None, usage
try:
- write_text_atomic(path, brief.model_dump_json(indent=1)) # a torn entry re-buys the call
+ write_text_atomic(path, brief.model_dump_json(indent=1))
except OSError as e:
log.warning("could not cache brief at %s: %s", path, e)
events.emit("plan.brief", cached=False, key=key, n_sub=len(brief.sub_assemblies),
@@ -216,8 +183,7 @@ EVIDENCE_MIN_CHECKLIST = 4
# --------------------------------------------------------------------- "is this a box?"
#: construction verbs / counted repeated features that make a part description more than
#: "a box of size X". Stems, not bare words: `taper` alone never matches "tapered", which
-#: is how every real plan writes it (measured — the un-stemmed version fired the gate on
-#: 77 % of the recorded plans instead of 43 %).
+#: is how every real plan writes it.
_CRAFT = re.compile(
r"\b(bevel\w*|chamfer\w*|fillet\w*|round(?:ed)?[- ](?:edge|corner|over)\w*|bullnose\w*|taper\w*|groove\w*"
r"|flute\w*|thread(?:ed|s)?|helix|helical|spline\w*|loft\w*|revolv\w*|extrud\w*|bezier|swept|sweep\w*"
@@ -226,22 +192,18 @@ _CRAFT = re.compile(
r"|recess\w*|emboss\w*|moulding\w*|molding\w*|curv\w*|arc\b|arch\w*|spiral\w*|dome[ds]?|domed|ogee"
r"|scroll\w*|pierc\w*|perforat\w*|crown\w*|swage\w*|bulg\w*|waist\w*|concave|convex|rebate[ds]?|dovetail\w*"
r"|mortise\w*|tenon\w*|splay\w*|conical|tapering|beading|reeded|turned|rounded|radius|radii)\b"
- r"|\br\s*=\s*\d", # "bullnose r=10 mm" — a stated radius is construction, not a box
+ r"|\br\s*=\s*\d",
re.I)
_COUNTED = re.compile(
r"\b\d+\s*(x|×)?\s*(slats?|spokes?|teeth|dentils?|panes?|rafters?|bolts?|screws?|rivets?|holes?|segments?"
r"|facets?|ribs?|flutes?|turns?|steps?|rings?|wires?|bars?|louvres?|louvers?|vents?|grooves?|studs?|pads?)\b",
re.I)
-#: the graphics analogue of :data:`_CRAFT`: a PASS is not "a box" when it names a real
-#: technique. Object craft words (bevel, taper, flute) never appear in a shader plan, so
-#: the object vocabulary would flag every pass ever written.
_GFX_CRAFT = re.compile(
r"\b(fbm|noise|hash|sdf|raymarch|ray[- ]?march|march|domain[- ]?warp|voronoi|worley|curl|advect|feedback"
r"|parallax|refract|reflect|fresnel|bokeh|blur|bloom|vignette|aberration|tonemap|gamma|dither|grain"
r"|particle|instanc|scatter|caustic|godray|god[- ]ray|volumetric|shadow|ao\b|ambient occlusion|palette"
r"|gradient|dissolve|erosion|turbulen|flow[- ]?map|displac|tessell|subsurface|halftone|posteris|posteriz)\b",
re.I)
-#: two or more numeric literals make a pass description a recipe rather than an adjective
_NUMBER = re.compile(r"\d+(?:\.\d+)?")
@@ -257,8 +219,7 @@ def has_pass_detail(text: str) -> bool:
@dataclass(frozen=True)
class PlanBudget:
- """What this request is worth, in plan units. ``target_parts`` is what the prompt
- asks the planner for; ``min_parts`` is what the quality gate insists on."""
+ """What this request is worth, in plan units. ``target_parts`` is what the prompt"""
target_parts: int
min_parts: int
@@ -267,9 +228,6 @@ class PlanBudget:
min_detail_parts: int
min_assemblies: int
reason: str = ""
- #: is there EVIDENCE that this request needs ``target_parts``? A checklist of four or
- #: more items, or a brief. Without it ``target_parts`` is an aspiration the prompt
- #: states and the quality gate must not enforce: "a stool" is allowed to be four parts.
evidence: bool = False
def as_dict(self) -> dict[str, int | str | bool]:
@@ -278,21 +236,12 @@ class PlanBudget:
"min_assemblies": self.min_assemblies, "budget_evidence": self.evidence, "reason": self.reason}
-#: the graphics track counts PASSES, not parts: more than ~6 stops being a plan and starts
-#: being a wish-list. The floor is 1 (D107): pass count correlated with the judge on
-#: graphics_v2 (visual_richness +0.40, mean 3.1 passes), but a correlation is not a requirement,
-#: and a mandated layer stack was the graphics twin of D106's three-depth-layer rule. Only a
-#: checklist long enough to be evidence (``EVIDENCE_MIN_CHECKLIST``) raises a floor.
GRAPHICS_CAP = 6
GRAPHICS_MIN = 1
def plan_budget(spec: Spec, brief: EngineeringBrief | None = None) -> PlanBudget:
- """Derive the plan's size budget from the REQUEST, not from a constant.
-
- Drivers: the user's own checklist (``must_have``), and — when a brief exists — the
- sub-assemblies × signature features a real one has. Capped by the language's
- practical limit (:data:`PART_CAP`)."""
+ """Derive the plan's size budget from the REQUEST, not from a constant."""
if spec.track is Track.GRAPHICS:
return _graphics_budget(spec)
cap = PART_CAP.get(spec.language.value, DEFAULT_PART_CAP)
@@ -300,9 +249,6 @@ def plan_budget(spec: Spec, brief: EngineeringBrief | None = None) -> PlanBudget
reasons = []
want = 0
if n_must:
- # one part (or sub-part) per checklist item is PARITY, not padding: the measured
- # ratio on the hard battery was 0.91 parts per checklist item, and the runs with the
- # highest ratio scored best on intent_fidelity (+0.26).
want = max(want, n_must)
reasons.append(f"{n_must} checklist items")
n_visible = 0
@@ -311,11 +257,7 @@ def plan_budget(spec: Spec, brief: EngineeringBrief | None = None) -> PlanBudget
if n_sub + n_sig:
want = max(want, n_sub + n_sig)
reasons.append(f"{n_sub} sub-assemblies + {n_sig} signature features")
- # externally visible features drive the LEAF budget, not the top-level part count:
- # "six vertical flutes on the body" is a sub-part of the body, not a part of its own.
n_visible = len(brief.visible_from_outside)
- # ``target`` sizes the answer (plan_tokens) and never drops below MIN_PARTS; the FLOOR is the
- # request's own count, so a 4-item checklist is never told it needs 6 parts (D107)
target = max(MIN_PARTS, min(cap, int(want)))
floor = max(2, int(round(0.85 * min(cap, int(want)))))
min_assemblies = 0
@@ -347,11 +289,7 @@ def _graphics_budget(spec: Spec) -> PlanBudget:
def budget_block(budget: PlanBudget, *, unit: str = "parts") -> str:
- """The budget as a prompt block for the planner's user message.
-
- A floor and a detail minimum are stated only when the request is EVIDENCE of them (a brief,
- or a checklist of :data:`EVIDENCE_MIN_CHECKLIST` items) — the only case the quality gate
- enforces them; otherwise the block states the ceiling and nothing that sets a count (D107)."""
+ """The budget as a prompt block for the planner's user message."""
lines = [f"PLAN BUDGET (derived from this request: {budget.reason}):"]
if budget.evidence:
lines.append(f"- plan at least {budget.min_parts} top-level {unit} (ceiling {budget.cap_parts}); "
@@ -371,17 +309,7 @@ def budget_block(budget: PlanBudget, *, unit: str = "parts") -> str:
# ----------------------------------------------------------------------------- quality gate
def plan_quality_complaint(plan_obj: Any, budget: PlanBudget, *, unit: str = "parts") -> str:
- """"" when the plan is worth building; otherwise the SPECIFIC complaint to re-ask with.
-
- Two classes of complaint. **Hard** ones fire on their own because they mean the plan
- cannot carry the request: too few parts for the checklist, or boxes-at-different-sizes
- (too few parts saying anything a primitive cannot). **Soft** ones — no assemblies
- nested, one material for the whole object — ride along with a hard one but never
- trigger a re-ask by themselves, because each is routinely correct on its own (a
- wrought-iron arch really is all one material).
-
- Never absolute: every threshold comes from ``budget``, which comes from the request.
- Measured retro-fire rate on the 86 recorded runs is in the wave report."""
+ """"" when the plan is worth building; otherwise the SPECIFIC complaint to re-ask with."""
parts: list[Any] = list(getattr(plan_obj, "parts", None) or getattr(plan_obj, "passes", None) or [])
if not parts:
return ""
@@ -425,10 +353,7 @@ def plan_quality_complaint(plan_obj: Any, budget: PlanBudget, *, unit: str = "pa
# ----------------------------------------------------------------------------- enrichment
def _fold_pass(ps: Any) -> None:
- """Fold a graphics pass's ``elements`` + ``detail_hint`` into its ``description``.
-
- ``graphics.passes_table`` prints ``| name | kind | description |`` — one markdown
- row — so the fold must stay on a single line and must be idempotent."""
+ """Fold a graphics pass's ``elements`` + ``detail_hint`` into its ``description``."""
if not (ps.elements or ps.detail_hint) or " · " in ps.description:
return
bits = [ps.description.rstrip().rstrip(".")]
@@ -440,21 +365,7 @@ def _fold_pass(ps: Any) -> None:
def enrich_plan(plan_obj: Any, brief: EngineeringBrief | None) -> Any:
- """Fold what the BRIEF knows back into the plan's own fields, after validation.
-
- A part's own depth needs no folding: ``tracks/prompting.py`` renders
- ``PartPlan.children`` and ``PartPlan.detail_hint`` straight from the typed fields, so
- copying them into ``description`` would print every sub-part twice. A graphics PASS is
- the exception — ``graphics.passes_table`` renders only ``description`` — so
- ``elements`` are folded there, on ONE line because that table is markdown.
-
- * the brief's signature features become ``should`` acceptance items — ``should``, not
- ``must``: a flash brief's private wishes must never trip ``missing_must_acceptance``,
- which caps a finished object at 0.60 (the lesson ``ensure_acceptance`` already
- records for the scene track);
- * ``style_notes`` gains the reference instance and what the object does NOT have —
- the two brief facts that change how the whole object is built rather than one part.
- """
+ """Fold what the BRIEF knows back into the plan's own fields, after validation."""
for ps in getattr(plan_obj, "passes", None) or []:
_fold_pass(ps)
if brief is None:
@@ -476,11 +387,7 @@ def enrich_plan(plan_obj: Any, brief: EngineeringBrief | None) -> Any:
# ===================================================================== worked examples
def plan_example(track: Track, language: Language | None = None) -> dict[str, Any]:
- """Compact, valid worked example per track (concrete beats abstract) — and, where a language
- plans differently, per language: a scene_blender plan names ``bpy`` modules where a three.js
- plan names ``threejs`` ones (``SCENE_ASSET_KINDS``). Its NUMBERS are the same Y-up GLB-frame
- numbers (D12: the plan never changes frame; the skeleton and the prompts convert for the
- author), so the two examples differ in the asset kinds and nothing else."""
+ """Compact, valid worked example per track (concrete beats abstract) — and, where a language"""
if track is Track.SCENE and language is Language.SCENE_BLENDER:
example = plan_example(Track.SCENE)
for asset in example["assets"]:
@@ -488,8 +395,6 @@ def plan_example(track: Track, language: Language | None = None) -> dict[str, An
asset["kind"] = "bpy"
return example
if track is Track.GRAPHICS:
- # the SCHEMA on an effect nobody asked for (no battery prompt is a tide pool) — two passes
- # because this effect has two, never a pass list, a layering or a post chain to copy
return {
"title": "Tide pool ripples", "summary": "Looking straight down into a shallow tide pool: pebbles and weed on "
"the floor, rings spreading from drops that fall at irregular intervals; light shifts over the pebbles.",
@@ -513,10 +418,6 @@ def plan_example(track: Track, language: Language | None = None) -> dict[str, An
],
}
if track is Track.SCENE:
- # ONE place's plan, shaped like that place (an L of quay on the west, open water east and
- # running OUT of the bounds, the mole and the village street running out too, open quay-head
- # ground the zones do not cover) — never a layout to copy. Its bounds centre, Quay bbox and
- # Overview position are pinned by tests/scene_blender/test_prompts.
return {
"title": "Harbour at dusk", "summary": "Small fishing harbour: an L of granite quay on the west side, two boats "
"moored against it, the basin opening east to the sea; the mole runs out of the bounds to the north-east.",
@@ -550,9 +451,6 @@ def plan_example(track: Track, language: Language | None = None) -> dict[str, An
"acceptance": [{"id": "a1", "text": "Two boats float on the water inside the basin", "how": "visual", "priority": "must"},
{"id": "a2", "text": "Quay top at y≈1.2 m, boats' waterline at y≈0", "how": "probe", "priority": "must"}],
}
- # The SCHEMA on an object nobody asks for (a profile, a counted repeat, a nested assembly,
- # an instanced row) — never a part list, a layout or numbers to copy. Upright's one-copy
- # bbox is what c3d-repeats-and-mirrors points at.
parts = [
{"name": "Base", "role": "weighted foot", "description": "disc 400 mm dia, 30 mm thick, top edge rounded r=8 mm, "
"four 20 mm square sockets for the uprights",
@@ -611,7 +509,6 @@ def plan_example(track: Track, language: Language | None = None) -> dict[str, An
base["root_link"] = "Cabinet"
base["joints"] = [{"name": "DrawerSlide", "type": "prismatic", "parent": "Cabinet", "child": "Drawer", "axis": [0, -1, 0],
"pivot": [0, -0.02, 0.45], "lower": 0.0, "upper": 0.35, "rest": 0.0, "motion": "drawer pulls out towards -Y"}]
- # its own checks, not the chair's: the base's seat-height / four-legs items describe another object
base["acceptance"] = [{"id": "a1", "text": "Cabinet top at 0.60 m ± 0.02 m above the ground", "how": "measure", "priority": "must"},
{"id": "a2", "text": "Cabinet stands on the ground at rest", "how": "visual", "priority": "must"},
{"id": "j1", "text": "Drawer slides out 0.35 m along -Y without penetrating the cabinet", "how": "articulation", "priority": "must"}]
@@ -620,51 +517,23 @@ def plan_example(track: Track, language: Language | None = None) -> dict[str, An
P = TypeVar("P", bound=BaseModel)
-#: re-ask budgets — a plan the SCHEMA rejects and a plan the QUALITY gate rejects are
-#: different failures and get separate chances (see ``plan``).
-MAX_VALIDATION_REASKS = 2 # was 1: compare_art_v2 lost 5 of 14 articulated prompts at this gate (2026-08-25)
+MAX_VALIDATION_REASKS = 2
MAX_QUALITY_REASKS = 1
-#: a validation failure whose plan is DEGENERATE (joints naming links the plan never lists)
-#: is answered by re-sampling from the original prompt instead of editing the broken answer
-#: in context; at most this many times per plan. Measured 2026-09-02: 3-4 % of plan calls
-#: end this way, and both in-context re-asks reproduce the same broken plan verbatim.
MAX_PLAN_RESTARTS = 1
-#: Output room for the plan call, sized from the plan budget. A deep plan is much longer
-#: JSON than a flat one AND Gemini 3.x bills its thinking against the same ceiling, so the
-#: flat 24 000 that served 8 box-parts truncates a 12-part plan with sub-parts —
-#: ``finish_reason=MAX_TOKENS``, no JSON, and the whole RUN dies at the plan stage. This
-#: was measured, not guessed: the first live pass of this wave failed exactly there on both
-#: prompts. Callers may raise the floor; this only ever raises it further.
PLAN_TOKENS_PER_PART = 600
PLAN_TOKENS_PER_LEAF = 400
-PLAN_TOKENS_MAX = 65_536 # the model's declared output ceiling
-#: one more attempt when the model truncates anyway, with half again as much room
+PLAN_TOKENS_MAX = 65_536
TRUNCATION_GROWTH = 1.5
-#: retry budget (``ChatRequest.max_wait_s``) for one planner call — the owner's floor
-#: (2026-08-27): 15 minutes before a plan may be cut off. For scale, the call itself is
-#: 13.7 s p50 / 32 s p90 / 76 s max (audit 2026-08-26 §2); the flat 300 s that once stood
-#: here is what killed grown re-asks (see the deadline-vs-answer block below).
PLAN_MAX_WAIT_S = 900.0
-#: ...but a deadline must fit the ANSWER it asked for, or the tokens are billed and then
-#: thrown away on a timeout. Measured over 395 real planner calls (2026-08-27): output
-#: runs at 145 tok/s p50 and 60 tok/s p10, and the largest answers seen were 32 k tokens
-#: in 152-199 s. At the p10 rate a 32 k answer needs 532 s and a 65 k one 1 089 s, so the
-#: flat 300 s guaranteed a timeout the moment a re-ask grew the budget — which is exactly
-#: how art_med_tool_chest and fancy_bl_windsor_chair died at the planner (2026-08-27).
PLAN_SLOW_TOKENS_PER_S = 60.0
PLAN_WAIT_OVERHEAD_S = 60.0
-#: a retry after truncation may wait this much longer than the size rule says (the pro
-#: planner streams a 55k-token answer slower than PLAN_SLOW_TOKENS_PER_S, 2026-08-28)
TRUNCATION_WAIT_SCALE = 1.5
def plan_wait_s(tokens: int, guard: object | None = None, *, scale: float = 1.0) -> float:
- """How long one planner call may take, given the answer size it asked for.
-
- Never below :data:`PLAN_MAX_WAIT_S`, and clipped to the wall clock the run has left
- (``BudgetGuard.timeout_s``) so a big plan cannot outlive its own run."""
+ """How long one planner call may take, given the answer size it asked for."""
want = max(PLAN_MAX_WAIT_S, tokens / PLAN_SLOW_TOKENS_PER_S + PLAN_WAIT_OVERHEAD_S) * scale
fn = getattr(guard, "timeout_s", None)
return float(fn(want, floor_s=PLAN_MAX_WAIT_S)) if callable(fn) else want
@@ -691,11 +560,7 @@ _PLACEHOLDERS = {"string", "str", "name", "text", "..."}
def _schema_echo(raw: dict[str, Any]) -> str:
- """"" or what in ``raw`` is a JSON-schema placeholder (``"name": "string"``) rather than content.
-
- compare_art_v4_pf0 (2026-08-28): flash answered a casement-window brief with a plan
- whose joint was ``{"name": "string", "axis": [0, 0, 0], ...}`` and failed the zero-axis
- validator three times; the re-ask echoed 'zero axis', which was not the problem."""
+ """"" or what in ``raw`` is a JSON-schema placeholder (``"name": "string"``) rather than content."""
bad: list[str] = []
if str(raw.get("object_name", "")).strip().lower() in _PLACEHOLDERS:
bad.append("object_name")
@@ -707,11 +572,7 @@ def _schema_echo(raw: dict[str, Any]) -> str:
def missing_link_names(raw: Any) -> list[str]:
- """Link names the joints reference that ``parts`` does not define (snake-compared).
-
- The one failure class measured on 200 plan calls (2026-09-02, both trees, 3-4 %): the
- planner writes ONE top-level part and hangs every joint off links it never lists, then
- reproduces that answer through both in-context re-asks."""
+ """Link names the joints reference that ``parts`` does not define (snake-compared)."""
if not isinstance(raw, dict):
return []
parts = raw.get("parts")
@@ -747,17 +608,10 @@ def restart_note(raw: Any, missing: list[str], budget: PlanBudget) -> str:
def restart_enabled() -> bool:
- """Kill switch for the degenerate-plan restart (``C3D_PLAN_RESTART``, ON; docs/COST.md §30)."""
return get_settings().plan_restart
-#: an invalid plan attempt is written here, so a run that DIES at the plan stage still says
-#: what the model wrote. Pydantic truncates the offending value in its message, so the
-#: event log alone cannot answer "what did it actually write?" — the question every
-#: plan-stage failure class starts from (eval/docs/PAPER_WRITING.md §5.1).
INVALID_PLAN_DIR = "stages/plan/invalid"
-#: bound per file: a plan is a few kB; anything larger is a runaway answer and the head of
-#: it is what says so
MAX_INVALID_PLAN_BYTES = 200_000
@@ -773,21 +627,13 @@ def _record_invalid(ws: Workspace, attempt: int, raw: Any, text: str) -> None:
def degenerate_plan(raw: Any, budget: PlanBudget) -> bool:
- """A plan too small to be an attempt at this request: a third of the floor or less.
-
- The quality complaint owns everything above that line — this is only the collapsed
- answer (usually ONE top-level part) that the in-context re-ask reproduces instead of
- fixing, which is why it is also the restart's trigger."""
+ """A plan too small to be an attempt at this request: a third of the floor or less."""
parts = raw.get("parts") if isinstance(raw, dict) else None
return isinstance(parts, list) and len(parts) <= max(2, budget.min_parts // 3)
def _thin_plan_note(raw: Any, budget: PlanBudget) -> str:
- """A second line for the validation re-ask when the invalid plan is also far too small.
-
- compare_art_v4_pf0 (2026-08-28): flash answered an architect-lamp brief with ONE part
- ("base") and a joint naming a link it never listed, three times in a row — the re-ask
- only echoed the unknown-link error, so the model kept fixing the wrong thing."""
+ """A second line for the validation re-ask when the invalid plan is also far too small."""
if not degenerate_plan(raw, budget):
return ""
parts = raw.get("parts")
@@ -799,18 +645,13 @@ def _truncated(exc: Exception) -> bool:
"""Did this model error mean 'the answer did not fit'?"""
return "MAX_TOKENS" in str(exc)
-#: the planner's system-prompt template per (track, language); ``(track, None)`` is the track's
-#: default and the fallback for every language without a row of its own. A scene_blender
-#: director reads the bpy twin: the same plan shape and frame (D12), the bpy library and the
-#: ``bpy`` asset kind instead of the three.js effects and ``threejs``.
PLAN_TEMPLATES: dict[tuple[Track, Language | None], str] = {
(Track.STATIC_OBJECT, None): "tracks/plan_static.j2",
(Track.ARTICULATED_OBJECT, None): "tracks/plan_articulated.j2",
(Track.SCENE, None): "tracks/plan_scene.j2",
(Track.SCENE, Language.SCENE_BLENDER): "tracks/plan_scene_bpy.j2",
- (Track.GRAPHICS, None): "tracks/plan_graphics.j2", # no 3D frame: passes, uniforms, motion
+ (Track.GRAPHICS, None): "tracks/plan_graphics.j2",
}
-#: the output-token floor ``plan_tokens`` grows from; a graphics plan starts at the model's ceiling
PLAN_OUTPUT_FLOOR = 24_000
@@ -820,16 +661,14 @@ def plan_template(track: Track, language: Language | None = None) -> str:
def plan_schema(spec: Spec, plan_model: type[BaseModel]) -> dict[str, Any]:
- """The response schema the planner call carries: a scene's names the asset kinds of ITS
- language (``scene_plan_schema``); every other plan is its model's schema as is."""
+ """The response schema the planner call carries: a scene's names the asset kinds of ITS"""
if issubclass(plan_model, ScenePlan):
return scene_plan_schema(spec.language)
return plan_model.model_json_schema()
def plan_temperature(track: Track) -> float:
- """What the planner samples at: 0.5 for a shader brief, 0.4 for everything else. THE value —
- ``record/telemetry`` reports this function, not a default it guesses."""
+ """The planner sampling temperature: 0.5 for a shader brief, 0.4 otherwise."""
return 0.5 if track is Track.GRAPHICS else 0.4
@@ -845,8 +684,6 @@ def plan_event_stats(plan_obj: Any) -> dict[str, Any]:
parts = getattr(plan_obj, "parts", []) or []
return {"n_parts": len(parts),
"n_zones": len(getattr(plan_obj, "zones", []) or []),
- # depth, so the flywheel can tell a 10-part plan of boxes from a 10-part plan of
- # assemblies without re-reading plan.json
"n_nested_parts": sum(1 for p in parts if getattr(p, "children", None)),
"n_subparts": sum(len(getattr(p, "children", None) or []) for p in parts),
"n_leaves": getattr(plan_obj, "leaf_count", len(parts)),
@@ -855,27 +692,7 @@ def plan_event_stats(plan_obj: Any) -> dict[str, Any]:
def plan[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Workspace, *, model: Any | None = None,
events: Any | None = None, budget: Any | None = None) -> P:
- """Plan and write ``ws.plan_path``: optional brief expansion → one structured planner
- call → re-asks (schema, quality, a degenerate-plan restart). ``model`` may be injected (tests).
- Everything that differs per track is looked up from ``spec.track`` (module docstring);
- the validated plan is finalised by ``ensure_acceptance(normalise_names(...))``.
-
- The two re-asks have SEPARATE budgets and different complaints:
- ``MAX_VALIDATION_REASKS`` for a plan the schema rejects, ``MAX_QUALITY_REASKS`` for a
- plan that validates but is boxes-at-different-sizes against the derived budget
- (:func:`plan_quality_complaint`). A quality re-ask never eats
- the validation re-ask, and a plan that fails quality twice is still USED — a mediocre
- plan beats no plan.
-
- Output room comes from :func:`plan_tokens` (the budget sizes it), and a
- ``finish_reason=MAX_TOKENS`` error buys ONE more attempt with half again as much room
- instead of killing the run — the deeper plan is longer JSON and Gemini bills thinking
- against the same ceiling.
-
- ``budget`` (the run's ``BudgetGuard``; ``guard`` below, because ``budget`` becomes this
- request's PlanBudget) only clips each call's wait to the clock left; every call is a
- ledger 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."""
+ """Plan and write ``ws.plan_path``: optional brief expansion → one structured planner"""
guard = budget
events = NULL_EVENTS if events is None else events
if model is None:
@@ -896,8 +713,6 @@ def plan[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Works
tokens = plan_tokens(budget, PLAN_TOKENS_MAX if spec.track is Track.GRAPHICS else PLAN_OUTPUT_FLOOR)
thinking = "medium"
wait_scale = 1.0
- # 4 = the first call + truncation retries; it was 2 + the geometry re-ask's 2 (D49, code
- # removed 2026-09-21) — the total is kept so a default run has the attempts it always had
for attempt in range(4 + MAX_VALIDATION_REASKS + MAX_QUALITY_REASKS + MAX_PLAN_RESTARTS):
req = ChatRequest(messages=messages, system=system, response_schema=schema, temperature=plan_temperature(spec.track),
thinking=thinking, max_output_tokens=tokens, label=f"planner{'-retry' if attempt else ''}",
@@ -906,14 +721,10 @@ def plan[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Works
resp = model.generate(req)
except Exception as e: # noqa: BLE001 — a truncated plan is retryable; anything else is not
if not (_truncated(e) and tokens < PLAN_TOKENS_MAX):
- raise # not a truncation, or already at the model ceiling: nothing to grow
+ raise
grown += 1
tokens = min(PLAN_TOKENS_MAX, int(tokens * TRUNCATION_GROWTH))
- # A bigger budget alone does not help when thinking ate the last one: with the pro
- # planner a 55k-token retry ran ~16 min into the provider's deadline (504) and the
- # cell was lost (compare_art_v4_pp, 2026-08-28). Retry with low thinking and a
- # compact-answer note on the last user turn.
- thinking = "off" # "low" still streamed past a 990 s attempt budget on 2 of 6 pro cells
+ thinking = "off"
wait_scale = TRUNCATION_WAIT_SCALE
messages = messages[:-1] + [_with_note(messages[-1], TRUNCATION_NOTE.format(tokens=tokens))]
events.emit("plan.truncated", attempt=attempt, max_output_tokens=tokens, thinking=thinking)
@@ -921,7 +732,7 @@ def plan[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Works
usage = usage + resp.usage
try:
raw = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text)
- except ValueError: # JsonParseError: nothing parsed — the re-ask below says so
+ except ValueError:
raw = None
try:
if not isinstance(raw, dict):
@@ -936,23 +747,11 @@ def plan[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Works
_record_invalid(ws, attempt, raw, resp.text)
events.emit("plan.invalid", attempt=attempt, error=last_error[:500])
missing = missing_link_names(raw)
- # The measured class is BOTH conditions: a collapsed plan (one top-level part)
- # whose joints name links it never listed. A full plan with one misspelled
- # link is the re-ask's job — restarting throws away parts that were right.
if (missing and degenerate_plan(raw, budget)
and restarts < MAX_PLAN_RESTARTS and restart_enabled()):
- # Editing a degenerate answer in context reproduces it: the model reads its
- # own one-part plan and returns it again (measured, both re-asks, 2026-09-02).
- # Re-sample from the original request instead, with the rule it broke. This
- # replaces the conversation rather than extending it, so it spends an
- # ATTEMPT, not one of the two re-ask slots the next invalid answer needs.
restarts += 1
events.emit("plan.restart", attempt=attempt, n_parts=len(raw.get("parts") or []),
missing=missing[:10])
- # rebuilt from the ORIGINAL request, so a compact-answer note an earlier
- # truncation retry added is rebuilt with it: this attempt keeps that
- # retry's smaller `tokens` and thinking="off", and dropping the note
- # while keeping the budget asks for the answer that did not fit.
note = TRUNCATION_NOTE.format(tokens=tokens) if thinking == "off" else ""
messages = base_messages[:-1] + [
ChatMessage.user(base_messages[-1].text + restart_note(raw, missing, budget) + note,
@@ -997,7 +796,7 @@ def _echo(raw: Any, text: str) -> ChatMessage:
# ----------------------------------------------------------------------------- prompts
#: the ``## `` headings of a scene contract the PLANNER acts on: it writes JSON, so it reads the
#: files the builders will own and what is measured on them — not the assembler wiring, the shader
-#: loading or the worked modules (the copyability review of 2026-10-15: +38 % on the planner brief)
+#: loading or the worked modules.
PLANNER_CONTRACT_SECTIONS: dict[Language, tuple[str, ...]] = {
Language.SCENE_THREEJS: ("Files", "createScene return value", "What is measured", "Naming"),
Language.SCENE_BLENDER: ("Files", "Frame and units", "What the renderer does", "Motion", "Naming", "Placement",
@@ -1006,8 +805,6 @@ PLANNER_CONTRACT_SECTIONS: dict[Language, tuple[str, ...]] = {
def planner_contract(lang: Language) -> str:
- """The contract text a planner of ``lang`` reads: the scene languages' measured sections only,
- every other language's contract whole."""
text = language_text(lang, "contract.md")
headings = PLANNER_CONTRACT_SECTIONS.get(lang)
return contract_sections(text, headings) if headings else text
@@ -1036,7 +833,7 @@ def build_user_prompt(spec: Spec, *, brief: Any | None = None, budget: PlanBudge
block = brief_block(brief)
if block:
lines += ["", block]
- if spec.track is not Track.SCENE: # a scene is planned in zones + assets, not parts
+ if spec.track is not Track.SCENE:
lines += ["", budget_block(budget or plan_budget(spec), unit=unit)]
if spec.references:
lines += ["", f"REFERENCE IMAGES: {len(spec.references)} attached — match their shape, proportions and visible details; "
@@ -1048,8 +845,7 @@ def build_user_prompt(spec: Spec, *, brief: Any | None = None, budget: PlanBudge
# ----------------------------------------------------------------------------- deterministic acceptance
def add_acceptance_item(items: list[AcceptanceItem], prefix: str, text: str, how: str, *,
priority: str = "must") -> None:
- """Append a framework-derived acceptance item (*must* unless told otherwise) unless an
- item with the same text exists; the id is ``<prefix><N>`` with N chosen to be unique."""
+ """Append a framework-derived acceptance item (*must* unless told otherwise) unless an"""
if text.strip().lower() in {a.text.strip().lower() for a in items}:
return
ids = {a.id for a in items}
@@ -1060,19 +856,7 @@ def add_acceptance_item(items: list[AcceptanceItem], prefix: str, text: str, how
def ensure_acceptance[P: BaseModel](plan_obj: P, spec: Spec) -> P:
- """Append acceptance items derived from the spec constraints when missing.
-
- A *must* item that the judge cannot verify caps the score (``missing_must_acceptance``)
- AND fails the run outright, so only the items the harness can hold the builder to may
- carry that priority. On the SCENE track the planner writes its own checklist before
- the scene exists ("the parapet is 1.05 m high", "the gorge reads 200 m
- deep") and there is no measurement pass to settle them — a flash planner's private
- wishes were capping finished scenes at 0.60. The spec's ``must_have`` list is the
- contract with the user, so on that track the plan's own items stay on the checklist as
- ``should`` (the judge still answers them, the refine loop still reads them) and only the
- spec-derived items keep ``must``. A shader has no size, triangle count or ground: the graphics
- track gets the spec's checklist and, when the plan animates, one probe item that the frames
- change (never 'ground contact')."""
+ """Append acceptance items derived from the spec constraints when missing."""
items: list[AcceptanceItem] = list(plan_obj.acceptance)
if spec.track is Track.SCENE:
items = [a if a.priority == "should" else a.model_copy(update={"priority": "should"}) for a in items]
@@ -1097,11 +881,7 @@ def ensure_acceptance[P: BaseModel](plan_obj: P, spec: Spec) -> P:
def articulation_acceptance(plan_obj: Any, items: list[AcceptanceItem]) -> list[AcceptanceItem]:
- """One ``articulation`` item per moving joint the planner's own checklist does not cover
- (2026-08-28, phase 4 item 6): the judge reads the pose sheet — rest, lower, upper — so the
- plan's rest-pose and motion statements become questions it answers per joint instead of
- prose it may skip. ``should`` priority: an unverified item steers the refine loop's
- judge tasks but never fails the run (a *must* the judge cannot verify does)."""
+ """One ``articulation`` item per moving joint the planner's own checklist does not cover"""
joints = [j for j in (getattr(plan_obj, "joints", None) or []) if j.type != "fixed"]
if not joints:
return []
@@ -1124,8 +904,7 @@ def articulation_acceptance(plan_obj: Any, items: list[AcceptanceItem]) -> list[
def normalise_names[P: BaseModel](plan_obj: P) -> P:
- """PascalCase part/link/zone/asset names in place — prompts ask for it; code guarantees it.
- Normalisation keeps the snake key, so validated uniqueness/tree properties are preserved."""
+ """PascalCase part/link/zone/asset names in place — prompts ask for it; code guarantees it."""
for attr in ("parts", "zones", "assets"):
for item in getattr(plan_obj, attr, None) or []:
item.name = to_pascal(item.name)
diff --git a/harness/codeverse3d/tracks/prompting.py b/harness/codeverse3d/tracks/prompting.py
index 197b49b9..3eb58191 100644
--- a/harness/codeverse3d/tracks/prompting.py
+++ b/harness/codeverse3d/tracks/prompting.py
@@ -1,10 +1,4 @@
-"""Prompt context for the tracks' jinja templates (``prompts/tracks/*.j2``).
-
-Everything a template may reference is produced here from the spec, the plan
-and the run context — exact numbers (bbox tables in meters), acceptance lines,
-the language frame doc, reference-image notes. Which file owns what is the
-runtime's answer (``LanguageRuntime.expected_files`` / ``files_for``).
-"""
+"""Prompt context for the tracks' jinja templates (``prompts/tracks/*.j2``)."""
from __future__ import annotations
@@ -50,11 +44,7 @@ def parts_table(plan: Plan) -> str:
def part_details(plan: Plan) -> str:
- """Per-part construction notes, including the sub-parts an ASSEMBLY part is made of.
-
- Sub-parts (``PartPlan.children``) are a planning device — the parent is still ONE
- named export node — but they are where the depth lives, so the builder must see
- them with their own boxes, not just a sentence."""
+ """Per-part construction notes, including the sub-parts an ASSEMBLY part is made of."""
out: list[str] = []
for p in getattr(plan, "parts", None) or ():
sym = p.symmetry if getattr(p, "symmetry", "none") != "none" else "no symmetry"
@@ -115,30 +105,13 @@ def constraints_text(spec: Any) -> str:
def language_system_prompt(language: Language, *, role: str = "", tools: bool = True, **vars: Any) -> str:
- """The generator's system prompt: ``prompts/<dir>/system.md``, or a role template.
-
- These were f-strings inside each track class until 2026-08-28 — two sentences each,
- and for the three static-object languages literally the SAME two sentences with the
- language's name substituted, though bpy mesh modelling, CadQuery's B-rep workplanes
- and three.js BufferGeometry share almost nothing but the word "3D". Per language, in
- the prompt corpus, so the seven can diverge and be edited without touching code.
- """
- # rendered, not read raw: a system prompt that tells a SINGLE-SHOT session to call
- # gl_probe is instructing something it has no tools to do, and the self-check loop is
- # the whole point of the graphics prompt. `tools` lets the file say so itself.
- # (The v0 two-sentence arm of the system-prompt A/B was retired 2026-08-29: a
- # three-way null, eval/docs/EVAL.md.)
+ """The generator's system prompt: ``prompts/<dir>/system.md``, or a role template."""
base = render(language_prompt(language, "system.md"), tools=tools).strip()
if not role:
return base
- # roles COMPOSE with the language base rather than replacing it. Replacing was the
- # shape inherited from the f-strings, and it left every fatal language-specific fact —
- # the self-check loop, the sampled-time contract — absent from exactly the stage that
- # violates it: the repair pass.
return base + "\n\n" + render(f"system/role_{role}.j2", language=language.value, **vars).strip()
-#: the ``## `` headings of a scene contract an ASSET session acts on (``contract_sections``)
ASSET_CONTRACT_SECTIONS: tuple[str, ...] = ("Files", "The `ctx`", "Allowed imports", "FORBIDDEN", "Blender 5.2 API facts",
"What the renderer does", "Naming")
@@ -152,9 +125,6 @@ def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
"language": ctx.language.value,
"frame_doc": frame_doc(LANGUAGE_FRAME[ctx.language.value]),
"contract": ctx.contract_text,
- # a scene_blender asset session writes ONE module the zones instance: it is handed the
- # contract's ctx table, imports, lint policy, API facts and render budgets, not the
- # assembler, the cameras or the worked env / zone modules it must not write
"asset_contract": contract_sections(ctx.contract_text, ASSET_CONTRACT_SECTIONS),
"tool_cards": ctx.tool_cards,
"single_shot": ctx.single_shot,
@@ -172,9 +142,6 @@ def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
"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),
- # The want -> call table for the effect library that ships in every
- # scene_threejs workspace (D51). "" for every other language (no such file), so
- # the templates that carry it stay byte-identical elsewhere.
"effects_catalog": language_text(ctx.language, "effects_catalog.md"),
}
d.update(extra)
@@ -195,14 +162,7 @@ def reference_images(ctx: RunContext, limit: int = 3) -> list[ImagePart]:
def judged_sheet(last: Any) -> list[ImagePart]:
- """The contact sheet the judge scored last round, as ONE inline image for the refine session.
-
- "What the judge saw" reached the refine agent as a paragraph of text; the picture it
- was written about did not. A session told "the horn intersects the case" then had to
- re-render to find out which view showed it. One image is cheap next to a session of
- 30 tool turns, and it is the same file the score came from, so the agent and the judge
- are finally looking at the same thing.
- """
+ """The contact sheet the judge scored last round, as ONE inline image for the refine session."""
sheet = getattr(getattr(last, "renders", None), "contact_sheet", None)
if not sheet or not Path(sheet).is_file():
return []
@@ -215,13 +175,7 @@ def judged_sheet(last: Any) -> list[ImagePart]:
def _likeness_note(ctx: RunContext, refs: list[Any]) -> str:
- """Graphics / scene: the photos say what the REAL thing looks like, not what to compose.
-
- The object-track note asks for a silhouette match and an IoU tool; a shader has no
- silhouette. What an aurora / a harbour / a nebula needs from a photo is its physics —
- dominant colour, how the structure folds and thins, where the light sits, how much of
- the frame stays dark — and the judge sees the same photos beside the frames.
- """
+ """Graphics / scene: the photos say what the REAL thing looks like, not what to compose."""
lines = [
f"REFERENCE PHOTOS ({len(refs)}) of the REAL thing come with this task. They are not a composition to copy; "
"they show what the brief's subject actually looks like: its dominant colour and where the secondary "
@@ -276,18 +230,14 @@ def skeleton_files(ctx: RunContext, max_chars: int = MAX_SKELETON_CHARS) -> dict
def refine_inline_files(ctx: RunContext, rels: Sequence[str]) -> dict[str, str]:
- """The files a refine task may edit, inlined for the prompt — single-shot only (it has
- no read tool); an agent session reads them itself, so it gets ``{}``."""
+ """The files a refine task may edit, inlined for the prompt in single-shot mode and empty otherwise."""
return current_files(ctx, rels) if ctx.single_shot else {}
def current_files(
ctx: RunContext, rels: Sequence[str], max_chars: int = MAX_SKELETON_CHARS
) -> dict[str, str]:
- """``{rel: text}`` for the files that exist, trimmed to ``max_chars`` in total. The
- language's harness-owned files (``HARNESS_OWNED_SRC``, e.g. scene_threejs's ``src/lib/``) are
- never inlined: the single-shot prompt once showed one as an editable skeleton file while
- every write to it is refused."""
+ """``{rel: text}`` for the files that exist, trimmed to ``max_chars`` in total. The"""
owned = set(HARNESS_OWNED_SRC.get(ctx.language, ()))
out: dict[str, str] = {}
total = 0
@@ -326,7 +276,6 @@ def judge_digest(last: RoundRecord, max_issues: int = 8) -> str:
def measurement_vs_plan(
last: RoundRecord, plan: Plan | None, language: Language = Language.THREEJS
) -> str:
- """Exact numbers (in the plan's frame): measured overall/part bboxes vs planned ones."""
m = last.measurement
if m is None or plan is None or not hasattr(plan, "overall_bbox"):
return ""
diff --git a/harness/codeverse3d/tracks/repair.py b/harness/codeverse3d/tracks/repair.py
index 3d64c077..6d2bbb6d 100644
--- a/harness/codeverse3d/tracks/repair.py
+++ b/harness/codeverse3d/tracks/repair.py
@@ -1,13 +1,4 @@
-"""Build → error-focused repair loop (no judge, no renders: cheap first).
-
-``build_with_repair`` runs ``runtime.lint`` + ``runtime.build``; while the
-build fails (or lint reports ERRORs) and attempts remain, it dispatches ONE
-repair task carrying a structured error report (file:line, message, traceback
-tail, lint findings with fix hints, the attached skills that answer the
-findings). Identical consecutive error signatures escalate (higher
-temperature/thinking for single-shot; an explicit "same error again" notice
-for agents) — the tell that the previous edit did not touch the cause.
-"""
+"""Build → error-focused repair loop (no judge, no renders: cheap first)."""
from __future__ import annotations
@@ -24,9 +15,6 @@ from codeverse3d.tracks.prompting import base_prompt_context, current_files, lan
log = logging.getLogger(__name__)
-#: How many times a build that failed IN THE HARNESS is simply re-run before the round
-#: gives up. Cheap (no model call) and bounded: the node driver already retries once
-#: itself, so a failure that survives this many rebuilds is not transient.
MAX_HARNESS_REBUILDS = 2
MAX_REPAIR_CONTEXT_CHARS = 40_000
@@ -54,11 +42,7 @@ def error_signature(build: BuildResult, lint: GateReport) -> str:
def format_error_report(build: BuildResult, lint: GateReport, skills: str = "") -> str:
- """Compact, structured error report for the fixer (the ONLY thing it must fix).
-
- ``skills`` is the gate→skill pointer block: the bundles already in the workspace that
- answer THESE findings, named beside them. Pointers, not text — the bodies are on
- disk, and the repair prompt is the volatile tail nobody caches."""
+ """Compact, structured error report for the fixer (the ONLY thing it must fix)."""
lines: list[str] = []
if not build.ok:
loc = build.error_file + (f":{build.error_line}" if build.error_line else "") if build.error_file else "(unknown file)"
@@ -80,8 +64,7 @@ def format_error_report(build: BuildResult, lint: GateReport, skills: str = "")
def files_for_repair(ctx: RunContext, build: BuildResult, lint: GateReport, files_hint: list[str]) -> dict[str, str]:
- """Current contents of the failing file(s) (≤ 40k chars total) for single-shot repair —
- inlined by ``prompting.current_files``, which never inlines a harness-owned file."""
+ """Current contents of the failing file(s), at most 40k chars in total, for single-shot repair."""
cands: list[str] = []
if build.error_file:
cands.append(_rel(ctx, build.error_file))
@@ -96,9 +79,7 @@ def files_for_repair(ctx: RunContext, build: BuildResult, lint: GateReport, file
def _rel(ctx: RunContext, path: str) -> str:
- """``path`` relative to the workspace, or ``""`` when it points outside it (an absolute
- path elsewhere, a ``..`` escape): never a file to inline. Was ``lstrip("./")``, which
- strips a character SET — ``../x`` became ``x`` and ``.env.js`` became ``env.js`` (B14)."""
+ """``path`` relative to the workspace, or ``""`` when it points outside it."""
p = path.replace("\\", "/")
root = str(ctx.ws.root).replace("\\", "/").rstrip("/") + "/"
p = p.removeprefix(root)
@@ -115,11 +96,7 @@ def build_once(ctx: RunContext) -> tuple[BuildResult, GateReport]:
def build_with_repair(ctx: RunContext, *, round_index: int, label: str, files_hint: list[str] | None = None,
max_attempts: int | None = None, timeout_s: int | None = None) -> RepairOutcome:
- """Lint+build; on failure run up to ``max_repair_attempts`` error-focused repairs.
-
- ``timeout_s`` clips every repair session (a scene asset's window is a share of the
- run, not the 1 800 s agent default: measured 2026-09-07, a 25-minute scene could
- spend 70 minutes on one hero's three repairs)."""
+ """Lint+build; on failure run up to ``max_repair_attempts`` error-focused repairs."""
files_hint = list(files_hint or [])
max_attempts = ctx.spec.budget.max_repair_attempts if max_attempts is None else max_attempts
build, lint = build_once(ctx)
@@ -130,17 +107,7 @@ def build_with_repair(ctx: RunContext, *, round_index: int, label: str, files_hi
repeats = 0
attempt = 0
rebuilds = 0
- # the rebuilds are gated by their OWN bound, not by the repair budget: a round run
- # with max_repair_attempts=0 (a baseline arm) still gets its harness retries
while not outcome.ok and (attempt < max_attempts or build.harness_failure):
- # A build that failed because the HARNESS could not run it is not a defect the
- # agent can fix, and handing it over costs the round its whole repair budget on
- # working code. Measured 2026-09-05 (japanese_garden): three
- # repairs against "scene probe produced no result (driver output lost)" rewrote
- # 5, then 14, then 3 files — the 14 included env.js and every zone — and deleted
- # the texture use the arm existed to measure, before the fourth build passed on
- # its own. Re-run the build instead; the driver's own retry has already fired,
- # so this is the second line, bounded and cheap (no model call).
if build.harness_failure:
if rebuilds >= MAX_HARNESS_REBUILDS:
log.warning("build kept failing in the harness (%s); giving up without a repair",
@@ -171,8 +138,6 @@ def build_with_repair(ctx: RunContext, *, round_index: int, label: str, files_hi
ctx.events.emit("build.done", round=round_index, ok=build.ok, lint_errors=len(lint.errors), attempt=attempt,
error=build.error_message[:200], duration_ms=build.duration_ms)
if res.transient and not outcome.ok:
- # the repair session died in a 503 storm (D68): whatever it wrote is built above;
- # another session would spend its whole window at the same wall
ctx.events.emit("repair.storm", round=round_index, attempt=attempt, notes=res.notes[:200])
break
return outcome
@@ -188,7 +153,7 @@ def make_repair_task(ctx: RunContext, build: BuildResult, lint: GateReport, *, r
failing_files=sorted(files) if files else [build.error_file] if build.error_file else files_hint))
ctx.record_prompt("repair", prompt)
temperature = min(1.0, 0.3 + 0.25 * repeats)
- thinking = ("", "high", "high")[min(repeats, 2)] # "": the single-shot default (medium), agy its own (high)
+ thinking = ("", "high", "high")[min(repeats, 2)]
return GenerationTask(label=label, prompt=prompt, system=_repair_system(ctx), files_hint=sorted(files) or files_hint,
round=round_index, kind="repair", temperature=temperature, thinking=thinking, timeout_s=timeout_s)
diff --git a/harness/codeverse3d/tracks/scene.py b/harness/codeverse3d/tracks/scene.py
index 3e8afbae..50260663 100644
--- a/harness/codeverse3d/tracks/scene.py
+++ b/harness/codeverse3d/tracks/scene.py
@@ -1,23 +1,4 @@
-"""SceneTrack: the plan, the pre-round stages (``SceneTrack.stages``: the whole baseline), rounds.
-
-Languages: every scene language, through its ``SceneRuntime`` (D101). Generation is staged (each stage cached by
-``StageRunner`` for resume); the round loop then builds (probe + shaders — the
-build's two gate reports join the round's gates),
-renders authored cameras + orbit at t=0 and t=1.5, judges with ``scene``
-(console/shader errors become gate ERRORS) and dispatches refine tasks per
-zone / asset / env / camera, in parallel when file-disjoint.
-
-Cost/latency shaping (the baseline used to eat the whole budget, leaving the
-refine rounds nothing):
-
-* assets are single-shot by default (``scene_assets``);
-* **one session writes every zone** (D70) and exclusively owns their files;
- ``scene.js`` is assembled deterministically, without a session;
-* every stage session gets a timeout clipped to the wall-clock actually left;
-* the baseline runs against a **soft sub-budget** (``soft_budget_fraction``);
- when it is spent the stages degrade (single-shot instead of an agent session,
- fewer assets, no asset judge) instead of dying at the hard cap.
-"""
+"""SceneTrack."""
from __future__ import annotations
@@ -69,19 +50,14 @@ log = logging.getLogger(__name__)
SCENE_TIMES: tuple[float, float] = (0.0, 1.5)
MAX_CONSOLE_ERRORS = 8
-# No cookbook (D106 / D107): the four ENV and six ZONE chapters once inlined into every session were
-# executed verbatim by the 60 iteration-0 scenes. Interface facts live in contract.md / system.md,
-# the craft in the skills as short optional practices; the prompts state requirements and what measures them.
+
ENV_TIMEOUT_S = 420
ZONE_TIMEOUT_S = 600
-#: what round 0 still needs once the zones are written — assemble, build, render, gates and the judge
-#: (4-8 min measured in iteration 2) — and what the zone window therefore never eats into
+#: what round 0 still needs once the zones are written; the zone window never eats into it
ROUND0_RESERVE_S = 600.0
-#: the shortest zone window worth opening: an agent session spends its first minutes reading the
-#: briefs, the skills and the asset files (24-27 reads in the two sessions killed at 180 s)
+#: the shortest zone window worth opening (a session spends its first minutes reading)
ZONE_MIN_S = 300.0
-#: a refine session that runs for half an hour (the desert-canyon round 1 did) spends the
-#: wall clock the NEXT round needed; clip it to what the hard budget still allows
+#: clips a refine session to what the hard budget still allows
REFINE_TIMEOUT_S = 900
@@ -95,16 +71,14 @@ class SceneTemplates:
asset: str
-#: per language — the three.js templates stay the files they were (byte-identical), the bpy
-#: twins carry the same context keys with Blender wording and the bpy library's calls
+
SCENE_TEMPLATES: dict[Language, SceneTemplates] = {
Language.SCENE_THREEJS: SceneTemplates("tracks/scene_env.j2", "tracks/scene_zone.j2", "tracks/scene_refine.j2",
"tracks/scene_asset.j2"),
Language.SCENE_BLENDER: SceneTemplates("tracks/scene_env_bpy.j2", "tracks/scene_zone_bpy.j2", "tracks/scene_refine_bpy.j2",
"tracks/scene_asset_bpy.j2"),
}
-#: ``SceneRuntime.env_file`` per language, for a runtime that does not state it (a fake, an
-#: older runtime): the typed fallback of :func:`env_file`, never a ``.js`` / ``.py`` test
+#: fallback for a runtime that does not state ``SceneRuntime.env_file``
ENV_FILES: dict[Language, str] = {Language.SCENE_THREEJS: "src/env.js", Language.SCENE_BLENDER: "src/env.py"}
@@ -114,17 +88,11 @@ def scene_templates(language: Language) -> SceneTemplates:
def env_file(ctx: RunContext) -> str:
- """The environment module of this run's scene language: the runtime's word (``env_file``),
- else the typed per-language table."""
+ """The environment module of this run's scene language."""
return getattr(ctx.runtime, "env_file", None) or ENV_FILES[ctx.language]
def plan_vec(v: Sequence[float], language: Language, *, extents: bool = False) -> tuple[float, float, float]:
- """A plan (GLB-frame, Y-up) vector in ``language``'s authoring frame — the identity for a
- Y-up language, so the three.js prompts keep their numbers byte for byte; a Z-up author (bpy)
- reads ``(x, -z, y)`` points and ``(w, d, h)`` sizes (D12: the plan itself never changes frame).
- ``+ 0.0`` folds the ``-0.0`` a negated zero leaves into ``0.0`` (``fmt3`` would print ``-0.000``)
- and is the identity on every other finite value."""
x, y, z = to_authoring_frame(v, language.value, extents=extents)
return (x + 0.0, y + 0.0, z + 0.0)
@@ -142,18 +110,14 @@ def plan_camera_line(c: CameraPlan, language: Language) -> str:
class ScenePipeline:
- """No GLB measurement; the placement gate from the build's census (the build's own probe and
- preflight reports join the round through ``BuildResult.gates``); render_scene; console caps."""
+ """No GLB measurement."""
def measure(self, ctx: RunContext, build: BuildResult) -> Measurement | None:
return None
def gates(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> list[GateReport]:
- # scene_placement (2026-08-26): floating / sunken / unsupported / interpenetrating assets from
- # the probe census's placement table — the first deterministic placement gate on this track
- # (before it, the scene_v1 floating_part cap could never fire) — plus the plan checks. The
- # check_placement tool returns the same verdict. Advisory instrumentation: a failure is a
- # WARN finding, never an exception, so it cannot kill a round.
+ # placement gate (floating / sunken / interpenetrating assets) plus the plan checks;
+ # advisory: a failure is a WARN finding, never an exception.
placement = placement_gate(ctx.ws, build.census, ctx.plan)
return [placement] if placement is not None else []
@@ -170,9 +134,7 @@ class ScenePipeline:
for e in errs[:MAX_CONSOLE_ERRORS]]
out = [GateReport.of("render_console", findings)]
try:
- # scene_frames: exposure / camera-in-geometry / coverage checks from metrics.json
- # (missing metrics → a passing empty report); its ERROR findings carry fix hints
- # that build_refine_instructions routes into the next round's tasks.
+ # scene_frames checks from metrics.json; ERROR findings carry fix hints into the next round
out.append(ctx.services.frame_gate(renders))
except Exception as e: # noqa: BLE001 — the frame gate is advisory instrumentation
log.warning("scene frame gate failed: %s", e)
@@ -180,15 +142,13 @@ class ScenePipeline:
return out
def judge_views(self, ctx: RunContext, renders: RenderSet) -> RenderSet:
- """The ≤ 10 views the judge sees (authored@t0 first); the full set stays on disk:
- the per-view ``judge`` flags ``render_scene`` stamps on every set it returns."""
+ """The ≤ 10 views the judge sees (authored@t0 first)."""
return judged_subset(renders) # type: ignore[return-value]
def judge_context(self, ws: Workspace, plan: Plan | None, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
if not isinstance(plan, ScenePlan):
return ""
- # the measured motion goes FIRST: this block is clipped to ~2.5 k chars in the judge
- # prompt and a long environment plan used to push everything after it off the end
+ # the measured motion goes FIRST: this block is clipped in the judge prompt
lines = [t for t in (motion_text_for(ws.renders_dir(round_index)),) if t]
lines.append(f"Environment plan: {plan.environment}"[:1200])
lines.append("Animation plan: " + "; ".join(plan.animation))
@@ -197,8 +157,7 @@ class ScenePipeline:
def _plan_agent(ctx: RunContext) -> dict[str, Any]:
- # the WHOLE plan (+ agent), not enumerated fields (2026-08-31): a mood/title/bounds/camera-only
- # re-plan used to hit a stale cached stage
+ # the WHOLE plan (+ agent), not enumerated fields
return {"plan": ctx.plan, "agent": ctx.agent_id}
@@ -209,19 +168,14 @@ class SceneTrack(BaseTrack):
#: the pre-round graph writes the whole baseline; round 0 builds, renders and judges it
stages = (
SKELETON, MATERIALIZE,
- # side by side (2026-08-30): the env brief reads no asset output — la_boulevard's 15 + 12 min ran
- # in max(15, 12), a whole refine round saved. Each is its OWN cached stage (2026-08-31): a failing
- # sibling never costs a succeeded one its paid result. Layouts: L2 zone layouts, an accelerator
- # (C3D_ZONE_LAYOUTS, default on), riding along at no wall clock (beb6605)
+ # side by side; each is its OWN cached stage so a failing sibling never costs a succeeded one
(StageNode("assets", lambda t, c: run_asset_stage(c), key=_plan_agent),
StageNode("env", lambda t, c: t._env_stage(c), key=_plan_agent),
StageNode("layouts", lambda t, c: t._layouts_stage(c), key=_plan_agent, when=lambda s: s.zone_layouts)),
StageNode("asset_api", lambda t, c: t._asset_api(c)),
- # ONE session writes every zone (D70)
StageNode("zones", lambda t, c: t._zones_stage(c), key=lambda c: {
"plan": c.plan, "asset_api": c.extra["asset_api"], "layouts": c.extra.get("layouts", {}), "agent": c.agent_id}),
- # after the zones are recorded: a run the clock stops here keeps them (salvage assembles
- # them; a resume serves them instead of paying the session again)
+ # after the zones are recorded: a clock stop here keeps them
CLOCK,
# scene.js, deterministic: no session
StageNode("assemble", lambda t, c: t._assemble_stage(c), key=lambda c: {"plan": c.plan}),
@@ -230,8 +184,7 @@ class SceneTrack(BaseTrack):
def make_pipeline(self) -> ScenePipeline:
return ScenePipeline()
- #: the baseline (the pre-round stages → round 0) may use this share of the run budget; the
- #: rest belongs to the refine rounds.
+ #: share of the run budget the baseline may use; the rest is for refine rounds
soft_budget_fraction = 0.55
# ------------------------------------------------------------------ stages
@@ -248,10 +201,7 @@ class SceneTrack(BaseTrack):
return {}
def _asset_api(self, ctx: RunContext) -> str:
- """What the zones are told about the assets. The asset results come back revived (a cached
- stage is JSON), with the merge map the STAGE used: its cap depends on the soft budget at the
- time (a degraded run folded more), so it is read back for a resumed run and the zones to
- agree."""
+ """What the zones are told about the assets."""
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)
@@ -260,8 +210,7 @@ class SceneTrack(BaseTrack):
# ---- degradation ------------------------------------------------------
def _strategy(self, ctx: RunContext, stage: str) -> RunContext:
- """The context a stage should generate with: the agent normally, single-shot
- once the baseline has spent its soft sub-budget (never dying at the hard cap)."""
+ """The context a stage should generate with."""
reason = ctx.budget.soft_exceeded()
if not reason:
return ctx
@@ -281,18 +230,7 @@ class SceneTrack(BaseTrack):
# ---- the stage session ------------------------------------------------
def _stage_session(self, ctx: RunContext, stage: str, kind: str,
task_for: Callable[[RunContext], GenerationTask]) -> GenerationResult:
- """The one way a baseline stage (env, zones) runs its session: the strategy the soft budget
- leaves (``_strategy``), the task built for it, this stage's skills routed into the workspace
- and — single-shot — inlined, the session, its skills telemetry and the stage's commit. A
- session that raises still leaves its telemetry and its commit before the exception goes on.
-
- The skills are this hook's job, not ``steps.run_round``'s: a scene builds its whole baseline
- in its pre-round ``stages``, in sessions that never pass through ``run_round`` (``scene.js`` is
- assembled, not written), so the router's ``kinds=("env", "zone")`` rows were selected and
- delivered to nobody — 0 opens out of 30 listings, measured 2026-08-25. ``index=0``: these
- stages ARE round 0's generation. One attach per stage keeps it to one AGENTS.md write, and
- closing the telemetry row per session keeps ``3dcode skills report`` from reading a stage's
- listing as "listed, unread"."""
+ """The one way a baseline stage (env, zones) runs its session."""
gen = self._strategy(ctx, stage)
task = task_for(gen)
skills_hook.attach_for_round(gen, index=0, kind=kind)
@@ -300,13 +238,8 @@ class SceneTrack(BaseTrack):
task = skills_hook.with_inlined_skill(gen, [task])[0]
res = generate_for(gen, task)
if (res.transient or res.stalled) and not res.ok and ctx.policy.can_open(ctx.budget, single_shot=gen.single_shot):
- # ONE transport retry, the round loop's rule (lifecycle: a 503 storm / dropped
- # socket / a session that HUNG is not a verdict on the work — the session never
- # really happened): the same task again under the ``.a2`` label the CLI's own second
- # session wears, so the ledger and the trajectory dir tell the two apart. Typed:
- # ``GenerationResult.transient`` / ``.stalled`` only — a quota wall or a session that
- # worked to its hard limit is not retried — and only when the clock still holds a
- # minimum window plus the judge reserve (``RoundPolicy.can_open``, D112).
+ # ONE transport retry (transient / stalled only, never a quota wall) under the ``.a2``
+ # label, and only when the clock holds a minimum window plus the judge reserve.
ctx.events.emit("stage.transport_retry", stage=stage, label=task.label, stalled=res.stalled and not res.transient,
detail=res.notes[:500])
res = generate_for(gen, task.model_copy(update={"label": f"{task.label}.a2"}))
@@ -316,13 +249,6 @@ class SceneTrack(BaseTrack):
ctx.ws.commit(stage)
def _env_stage(self, ctx: RunContext) -> dict[str, Any]:
- """The env session, honest (D111): ``ok`` only when the env module ITSELF was written in this
- stage — the session's ``files_changed`` (its ``files_hint`` alone: ``shared_tree``) or the
- file's mtime, the test the zone stage uses. Iteration 4 of the argon loop (scene_threejs,
- 2026-10-15): the session read for 7-10 minutes and wrote nothing in 12 of 15 runs, was
- credited with the asset files the single-shots wrote beside it, and the stage read ``ok``;
- round 0 was unlit and the one refine round wrote the whole environment from the skeleton.
- A failed stage gets ONE recovery before the zones are written (:meth:`_recover_env`)."""
rel, t0 = env_file(ctx), time.time()
res = self._stage_session(ctx, "env", "env", self._env_task)
written = {c.path for c in res.files_changed}
@@ -333,25 +259,6 @@ class SceneTrack(BaseTrack):
return out
def _recover_env(self, ctx: RunContext, failed: dict[str, Any]) -> dict[str, Any]:
- """One single-shot generation of the env module the session left unwritten — the
- :meth:`_recover_zones` rule for the env stage (D111): a fresh brief, single-shot (it cannot
- spend its window reading), bounded by the env window the budget still allows. It runs
- before the zone stage starts, so no zone is authored against the skeleton's placeholder
- (iteration 4, r1_01: a zone author built its own replacement world inside its zone file).
-
- CHECKED (D112): the written module counts only once the runtime's env check passes
- (``SceneRuntime.check_env``: its lint, a build with nothing beside it, something that lights
- it); a failure gets ONE repair single-shot with the check's words and the file fed back (the
- asset ladder's single-shot + repair). Both prompts carry the ``src/lib/`` interface of a language
- that ships one (``SceneRuntime.lib_interface``) — names and parameter lists, read off the files. Iteration 5
- (2026-10-16): 7 of 21 unchecked recoveries were broken or unlit (a SyntaxError, a non-existent
- ``gravel`` export, a ``roughness=`` keyword no function takes) and reached round 0 as an
- assembly without env. A module that still fails is replaced by what was there before (the
- placeholder: zones import its interface), and the stage reports it failed.
-
- Under :func:`~codeverse3d.agents.cli_common.exclusive_workspace` (D112): an escalated asset
- session may hold the workspace while this runs, and a harness commit inside its window was
- reverted by its scope check (iteration 5, scene_blender r1_10: the recovered env erased)."""
from codeverse3d.agents.cli_common import exclusive_workspace
gen = ctx if ctx.single_shot else (single_shot_ctx(ctx) or ctx)
@@ -391,11 +298,9 @@ class SceneTrack(BaseTrack):
return out
def _env_task(self, ctx: RunContext, **recovery: str) -> GenerationTask:
- """``recovery``: the recovery's extra facts (``lib_interface``, ``env_check_error``,
- ``env_previous`` — :meth:`_recover_env`); the session's own brief has none."""
+ """``recovery``."""
prompt = render(scene_templates(ctx.language).env, **self._ctx(ctx, **recovery))
ctx.record_prompt("scene_env", prompt)
- # shared_tree: the asset single-shots write src/ side by side with this session (D111)
return GenerationTask(label="env", prompt=prompt, system=self.system_prompt(ctx), files_hint=[env_file(ctx)], round=0, kind="env",
temperature=0.5, timeout_s=ctx.budget.timeout_s(ENV_TIMEOUT_S, floor_s=120),
images=reference_images(ctx), shared_tree=True)
@@ -403,15 +308,13 @@ class SceneTrack(BaseTrack):
def _zones_stage(self, ctx: RunContext) -> dict[str, Any]:
plan: ScenePlan = ctx.plan # type: ignore[assignment]
t0 = time.time()
- # one author for the whole world (D70; the fan-out control arm was removed 2026-09-21)
zones = list(plan.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
# recorded + committed; the boundary check after the stage stops the run
log.warning("zones session failed: %s: %s", type(e).__name__, e)
- # a clock that tripped as a FINISHED session was charged: what it wrote is recorded as
- # written (salvage assembles it, a resume serves it), the stop as a note beside it
+ # a clock trip after a FINISHED session: what it wrote is recorded, the stop noted beside it
stopped = isinstance(e, BudgetExceeded)
out = {}
for zone in zones:
@@ -423,9 +326,7 @@ class SceneTrack(BaseTrack):
out = {}
for zone in zones:
rel = ctx.runtime.zone_file(zone.name)
- # a session that owns several zones must have produced EVERY file; the skeleton
- # left a stub at every zone path, so existence proves nothing — the file
- # must have been reported as changed or actually rewritten in this stage
+ # existence proves nothing (the skeleton left stubs): the file must be reported changed or rewritten
ok = r.ok and (len(zones) == 1 or rel in written or _touched(ctx.ws.root / rel, t0))
out[zone.name] = {"ok": ok, "files": [rel] if ok else [], "notes": r.notes}
failed = [z for z in zones if not out[z.name]["ok"]]
@@ -435,15 +336,7 @@ class SceneTrack(BaseTrack):
return out
def _recover_zones(self, ctx: RunContext, failed: list[ZonePlan]) -> dict[str, dict[str, Any]]:
- """One single-shot generation per zone the batched session left unwritten, side by side.
-
- WHY. ``zones.done`` already listed such zones as failed and nothing acted on it: the
- skeleton's stub (``build`` returns the empty collection) went to assembly, every planned
- content was ``zone_empty`` and ``missing_must_acceptance`` capped the run at ~0.18 — and the
- refine round, handed "three empty zones" among its targets, spent its 15 minutes on asset
- files (iteration 2, r1_11 / r1_15, 2026-10-15). An unwritten zone is the stage's job, not
- refine's: each gets its own brief again, single-shot (fast, and it cannot spend its window
- reading), bounded by the zone window. A recovery that also fails leaves the stub, as before."""
+ """One single-shot generation per zone the batched session left unwritten, side by side."""
from codeverse3d.proc import fan_out
gen = ctx if ctx.single_shot else (single_shot_ctx(ctx) or ctx)
@@ -471,10 +364,7 @@ class SceneTrack(BaseTrack):
return results
def _zone_task(self, ctx: RunContext, batch: list[ZonePlan]) -> GenerationTask:
- """One task for one zone, or for every zone of the scene in one session (D70).
-
- A batched task exclusively owns every file it lists, so ``files_hint``
- attribution and the refine fan-out stay file-disjoint."""
+ """One task for one zone, or for every zone of the scene in one session."""
plan: ScenePlan = ctx.plan # type: ignore[assignment]
names = [z.name for z in batch]
files = [ctx.runtime.zone_file(z.name) for z in batch]
@@ -482,10 +372,7 @@ class SceneTrack(BaseTrack):
briefs = []
for i, zone in enumerate(batch):
neighbours = [f"{z.name}: {plan_bbox_line(z.bbox, ctx.language)}" for z in plan.zones if z.name != zone.name]
- # the brief's per-zone head for every zone; the shared tail (cameras, assets, the
- # contract, the measured list, tools, the catalog, the output rules) ONCE, after the
- # last head — a two-zone session used to read the contract and the 25k catalog twice
- # with "HOW TO FINISH" landing between zone 1 and zone 2 (2026-10-15)
+ # per-zone head for every zone; the shared tail (cameras, assets, contract, tools, catalog) ONCE after the last head
briefs.append(render(template, **self._ctx(ctx, zone_name=zone.name, zone_description=zone.description,
zone_bbox=plan_bbox_line(zone.bbox, ctx.language), zone_contents=zone.contents,
zone_file=ctx.runtime.zone_file(zone.name), neighbours=neighbours,
@@ -509,7 +396,7 @@ class SceneTrack(BaseTrack):
"and scored 0.32 where the brief-by-brief fan-out reached 0.60.\n")
prompt = header + "\n\n---\n\n".join(briefs)
label = "zones_" + "_".join(to_snake(n) for n in names)
- ctx.record_prompt("scene_zone", prompt) # the whole prompt the session read, not its first brief
+ ctx.record_prompt("scene_zone", prompt) # the whole prompt the session read
# the batch exclusively owns its zone files; env/scene/asset files belong to other sessions
# the window grows with the batch: one author writing four zones is four zones of work
return GenerationTask(label=label, prompt=prompt, system=self.system_prompt(ctx), files_hint=files,
@@ -523,9 +410,7 @@ class SceneTrack(BaseTrack):
return {"ok": True, "deterministic": True, "result": result} # StageRunner.stage jsonables it
def prepare_salvage(self, ctx: RunContext) -> bool:
- """The budget stopped a stage before round 0: assemble whatever the stages DID
- write (the skeleton guarantees a stub per zone) so the run still delivers a
- built, rendered, judged scene instead of no score at all."""
+ """The budget stopped a stage before round 0."""
plan: ScenePlan = ctx.plan # type: ignore[assignment]
zones = [z for z in plan.zones if (ctx.ws.root / ctx.runtime.zone_file(z.name)).is_file()]
if not zones:
@@ -561,9 +446,7 @@ class SceneTrack(BaseTrack):
timeout_s=ctx.budget.timeout_s(REFINE_TIMEOUT_S, floor_s=180, soft=False))
def _rebuild_task(self, ctx: RunContext, last: RoundRecord, index: int) -> GenerationTask:
- """One repair task carrying the structured error report (build + lint; the probe's
- and the preflight's findings are the build's log tail), targeted at the failing
- module when the build names one."""
+ """One repair task carrying the structured build and lint error report."""
lint = next((g for g in last.gates if g.gate.startswith("lint")), GateReport(gate="lint", passed=True))
report = format_error_report(last.build, lint) if last.build else "build did not run"
files: list[str] = []
@@ -583,15 +466,7 @@ class SceneTrack(BaseTrack):
# ------------------------------------------------------------------ helpers
def _ctx(self, ctx: RunContext, **extra: Any) -> dict[str, Any]:
- """The variables every scene template may use. Plan numbers are printed in the AUTHORING
- frame of the run's language (``plan_vec``: the identity for three.js, so those prompts are
- byte-identical; a bpy author reads Z-up points and (w, d, h) sizes, D12), plus the
- runtime's file names (``env_file`` / ``entry_file``) so a template never spells a path.
-
- ``bounds`` is the extent of the PLANNED content and the cameras' subject — what the
- placement gate measures placed assets against — not the edge of the world: terrain,
- backdrop and scenery continue beyond it as the brief implies, and a template that
- reads it must say so (owner, 2026-10-15)."""
+ """The variables every scene template may use."""
plan: ScenePlan = ctx.plan # type: ignore[assignment]
lang = ctx.language
zones_table = "\n".join(f"- {z.name}: {z.description} — {plan_bbox_line(z.bbox, lang)}; contents: {', '.join(z.contents) or '-'}"
@@ -608,8 +483,6 @@ class SceneTrack(BaseTrack):
# ----------------------------------------------------------------------------- helpers
def _touched(path: Any, since: float) -> bool:
- """Was ``path`` (re)written after ``since``? (mtime beats existence: every zone
- path already holds a skeleton stub.)"""
try:
return path.is_file() and path.stat().st_mtime > since
except OSError:
@@ -617,22 +490,13 @@ def _touched(path: Any, since: float) -> bool:
def zone_window_s(ctx: RunContext, n_zones: int) -> int:
- """The zone session's window: ``ZONE_TIMEOUT_S`` per zone, clipped to the HARD budget minus
- :data:`ROUND0_RESERVE_S` — never to the scene track's soft cap.
-
- WHY. The soft cap (0.55 of the run) protects the refine round's time, but a scene whose zones
- are empty has nothing to refine: two iteration-2 runs reached the zone stage 0.4 min before the
- cap (a runaway asset call had held the asset stage for 47 min), so the session was clipped to
- the 180 s floor, read 24-27 files and was killed before writing a zone (2026-10-15). The zones
- are the scene; refine gets whatever they leave. Past the soft cap the stage still degrades to
- single-shot (``_strategy``); this only sizes the window it runs in."""
+ """The zone session's window."""
left = (ctx.budget.hard_minutes - ctx.budget.elapsed_minutes()) * 60.0 - ROUND0_RESERVE_S
return int(max(ZONE_MIN_S, min(float(ZONE_TIMEOUT_S * max(1, n_zones)), left)))
def _guess_target(error: str, ctx: RunContext) -> str:
- """The refine target a console error names: a zone or asset by its snake name, the env
- module or the entry by the RUNTIME's file names (``env_file``, ``ENTRY_FILE``), else overall."""
+ """The refine target a console error names."""
low = error.lower()
for attr in ("zones", "assets"):
for item in getattr(ctx.plan, attr, None) or []:
diff --git a/harness/codeverse3d/tracks/scene_assets.py b/harness/codeverse3d/tracks/scene_assets.py
index 9e9ad593..95f327a2 100644
--- a/harness/codeverse3d/tracks/scene_assets.py
+++ b/harness/codeverse3d/tracks/scene_assets.py
@@ -1,23 +1,4 @@
-"""Scene asset stage: cheap-first generation of one module per asset, fanned out.
-
-* ``threejs`` assets → ``src/assets/<snake>.js`` exporting ``build<Pascal>`` —
- generated **single-shot** (one chat call) + a deterministic node check + ONE
- error-feedback repair; a full agent session is the escalation, not the default
- (agent sessions cost 10× and 10 minutes per file).
-* ``bpy`` assets (a scene_blender plan's modules) → ``src/assets/<snake>.py`` defining
- ``build_<snake>(ctx, variant=0)`` — the SAME ladder; the deterministic check builds the
- one module in a throw-away Blender workspace (``check_bpy_asset``) and measures it off
- the census GLB like a hero.
-* ``blender_glb`` assets are **heroes**: a sub-workspace under ``<ws>/_assets/<snake>``
- runs the Blender runtime and climbs the SAME single-shot ladder (``_ladder``) before
- an agent session; the GLB is copied to ``public/assets/<snake>.glb``.
-
-Near-identical props are merged into one factory with an ``opts.variant``; the
-list is capped at ``MAX_ASSETS`` in plan (= priority) order, and harder when the
-soft budget is spent. Assets are judged only when the judge can tell us
-something the deterministic check cannot (heroes, or anything big enough to
-matter in frame).
-"""
+"""Scene asset stage."""
from __future__ import annotations
@@ -68,28 +49,19 @@ MAX_ASSETS = 8
DEGRADED_MAX_ASSETS = 4
#: an asset smaller than this share of the scene bbox volume is not worth a judge call
JUDGE_VOLUME_FRACTION = 0.05
-#: the plan's largest module is judged whatever its share of the scene — once it is at least
-#: this big (a bollard is not a hero, a boat is)
+#: the plan's largest module is judged whatever its share, once at least this big
JUDGE_MIN_VOLUME_M3 = 1.0
ASSET_AGENT_TIMEOUT_S = 420
-#: no SINGLE asset session may take more than this share of the whole run. The stage
-#: waits for its slowest asset, and budget.timeout_s only bites near the ceiling: on a
-#: 25-minute scene (2026-08-27) seven assets finished inside 5.7 min while one escalation
-#: ran the full 420 s and held the stage to 10.9 min — 28 % of the run for one asset, and
-#: round 0 did not start until 18.9 min.
+#: no single asset session may take more than this share of the run (the stage waits for its slowest asset)
ASSET_SESSION_SHARE = 0.15
ASSET_RUBRIC = "asset"
-#: the asset kinds that are a MODULE in the scene workspace (one factory per file, placed by the
-#: zones); ``blender_glb`` is the hero, built as an object and shipped as a GLB
+#: asset kinds that are a MODULE in the scene workspace; ``blender_glb`` is the hero, shipped as a GLB
MODULE_KINDS: frozenset[str] = frozenset({"threejs", "bpy"})
-#: the languages whose asset sessions share the SCENE workspace (a stray write would hit zones /
-#: env, so their tasks are ``edit_only``); a blender hero owns its whole sub-workspace
+#: languages whose asset sessions share the scene workspace (tasks are ``edit_only``); a hero owns its sub-workspace
SCENE_LANGUAGES: frozenset[Language] = frozenset(TRACK_LANGUAGES[Track.SCENE])
def asset_timeout_s(ctx: Any, floor_s: int) -> int:
- """``ASSET_AGENT_TIMEOUT_S`` clipped to one asset's share of the run AND to the
- wall clock actually left (:meth:`BudgetGuard.timeout_s`, which owns the floor)."""
share = ctx.budget.budget.max_minutes * 60.0 * ASSET_SESSION_SHARE
return ctx.budget.timeout_s(min(ASSET_AGENT_TIMEOUT_S, share), floor_s=floor_s)
@@ -113,15 +85,6 @@ class AssetResult(BaseModel):
def asset_api_summary(plan: ScenePlan, results: dict[str, AssetResult], alias: dict[str, str] | None = None, *,
language: Language = Language.SCENE_THREEJS) -> str:
- """What zone/composer tasks need to know about each asset (names + sizes + how to get it),
- in the words of the scene language that places them.
-
- three.js: a module is imported and its factory called; a hero is preloaded into
- ``ctx.assets`` and cloned. Merged assets (``alias``) point at the surviving factory and
- the ``opts.variant`` the zone must pass. bpy: the harness builds EVERY module (a merged
- twin's shim included) and imports every hero before any zone runs, so each is a Collection
- at ``ctx.assets['<snake>']`` to place as a collection instance — the zone never imports or
- calls a factory, and a merged twin needs no variant number."""
alias = alias or {}
lines = []
for a in plan.assets:
@@ -192,9 +155,7 @@ def run_asset_stage(ctx: RunContext) -> dict[str, AssetResult]:
out: dict[str, AssetResult] = {}
for asset, r in zip(assets, results, strict=True):
if isinstance(r, Exception):
- # a BudgetExceeded worker is a failed asset like any other: the siblings'
- # finished modules are still shimmed + committed below, and the guard's own
- # boundary check stops the run AFTER the paid work is persisted.
+ # a failed worker is a failed asset: siblings' modules are still shimmed + committed before the boundary check stops the run
out[asset.name] = AssetResult(name=asset.name, kind=asset.kind, ok=False, notes=f"{type(r).__name__}: {r}")
ctx.events.emit("asset.failed", asset=asset.name, error=f"{type(r).__name__}: {r}")
else:
@@ -219,7 +180,6 @@ def _spec_hashes_path(ctx: RunContext) -> Path:
def _spec_hash_matches(ctx: RunContext, asset: AssetPlan) -> bool:
- """False when unrecorded (pre-fix runs regenerate once, then reuse)."""
return (read_json_or_none(_spec_hashes_path(ctx)) or {}).get(asset.name) == _asset_spec_hash(asset)
@@ -235,22 +195,12 @@ def _record_spec_hashes(ctx: RunContext, results: dict[str, AssetResult], assets
# ----------------------------------------------------------------------------- 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.
-
- ``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."""
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.
+ # committed-child reuse: a resume must not re-pay a finished asset (deterministic check, no model call)
if (ctx.ws.root / rel).is_file() and _spec_hash_matches(ctx, asset):
chk0 = check_fn(ctx, rel, name, expected_size_m=asset.approx_size_m)
if chk0.ran and chk0.ok:
@@ -268,10 +218,7 @@ def build_module_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> Ass
def _module_result(ctx: RunContext, asset: AssetPlan, rel: str, strategy: str, chk: AssetCheck | None, notes: str, *,
check: Callable[[RunContext], AssetCheck], language: Language, judge: bool) -> AssetResult:
- """What a MODULE asset's ladder outcome means (both module kinds): a module that will not
- import / build is NOT AVAILABLE to zones; a merely imperfect one (size off, still a bit
- plain) stays usable — the ladder already spent a repair on it. Then the quick-sheet judge
- + ONE fix pass, when the runtime can render the module alone (``render_asset``)."""
+ """What a MODULE asset's ladder outcome means (both module kinds)."""
if strategy == "outage":
return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy=strategy, notes=notes)
ok = (ctx.ws.root / rel).is_file() and not (chk is not None and chk.ran and chk.fatal)
@@ -282,8 +229,7 @@ def _module_result(ctx: RunContext, asset: AssetPlan, rel: str, strategy: str, c
render_asset = getattr(ctx.runtime, "render_asset", None)
if ok and callable(render_asset) and _judge_wanted(ctx, asset, chk, judge=judge):
def _after_fix(gen: RunContext) -> bool:
- # a fix that breaks the module makes it NOT AVAILABLE — the zones must not import it;
- # a SOFT finding (size, tris) is no reason to revert a fix that imports (the hero's rule)
+ # a fix that breaks the module makes it NOT AVAILABLE; a SOFT finding is no reason to revert
c = check(ctx)
if c.ran and c.fatal:
result.ok, result.path = False, ""
@@ -305,27 +251,17 @@ def _module_result(ctx: RunContext, asset: AssetPlan, rel: str, strategy: str, c
def _ladder(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language, files: list[str],
check: Callable[[RunContext], AssetCheck], timeout_s: int | None) -> tuple[str, AssetCheck | None, str]:
- """The cheap-first ladder BOTH asset kinds climb: single-shot → deterministic ``check`` →
- ONE error-feedback repair → (only then) the full agent session.
-
- Returns ``(strategy, last check, notes)``; ``strategy == "outage"`` means the model
- itself was down and the asset was given up before the expensive rung. The check is
- per kind — a node import for a three.js module, a Blender build + measurement for a
- hero — and the ladder is one, which is what makes the two kinds comparable.
- """
+ """The cheap-first ladder BOTH asset kinds climb."""
sub = single_shot_ctx(ctx)
chk: AssetCheck | None = None
strategy, notes = "", ""
outage = False
if sub is not None:
for attempt in range(2): # first shot + ONE error-feedback repair
- # after an OUTAGE the model never wrote a file: the second shot is the first shot
- # again, not a "repair" of the skeleton stub against a 503 it cannot fix
+ # after an outage the model wrote nothing: the second shot is the first again
feedback = repair_feedback(chk, rel) if chk is not None and not outage else ""
try:
- # the ladder's window bounds the single-shot call too (D108): without it the call ran on the
- # retry ceiling — one hung hero waited 1 800 s twice and held the asset stage to 66 min
- # (iteration 3, r1_13, 2026-10-15)
+ # the ladder's window bounds the single-shot call too
res = _generate_asset(sub, asset, rel, language=language, attempt=attempt, files=files,
feedback=feedback, timeout_s=timeout_s)
except Exception as e: # noqa: BLE001 — a bad answer escalates; a dead model does not
@@ -349,9 +285,7 @@ def _ladder(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language,
if not strategy and not outage:
ctx.events.emit("asset.escalated", asset=asset.name, errors=(chk.errors[:3] if chk else []))
if not strategy and outage:
- # the model itself is down (503 capacity storm), and the retry layer already spent its
- # storm budget waiting: a full agent session is ten times the money and the same wall.
- # Give the asset up cheaply — the zones read "NOT AVAILABLE" and build around it.
+ # model down and retries exhausted: give the asset up cheaply; zones read "NOT AVAILABLE" and build around it
ctx.events.emit("asset.skipped_outage", asset=asset.name, errors=(chk.errors[:2] if chk else []))
return "outage", chk, "generator unavailable (model outage); asset skipped"
if not strategy: # no chat model, or single-shot failed twice → the full agent session
@@ -381,9 +315,6 @@ def _generate_asset(ctx: RunContext, asset: AssetPlan, rel: str, *, language: La
def _inline(ctx: RunContext, files: list[str]) -> str:
- """The file(s) a single-shot rewrite must return, inlined the way every other prompt
- inlines them (``prompting.current_files``: trimmed to one budget, harness-owned files
- skipped) — a hero has parts, not one file."""
return "".join(f"--- {rel} ---\n```\n{body}\n```\n" for rel, body in current_files(ctx, files, 24_000).items())
@@ -397,21 +328,8 @@ HERO_THIN_PLAN_PARTS = 2
def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> AssetResult:
- """Sub-workspace → the static planner's part list → the SAME ladder a threejs asset
- climbs → the GLB checked like a module → ``public/assets/<snake>.glb``.
-
- Until 2026-09-07 a hero got a one-part plan, a full agent session first, and no check
- of the GLB it produced. Measured over the 18 recorded heroes (eval/bench/out, 2026-08-25 →
- 09-05): 15 first sessions killed at the asset timeout (booked at $0 — a killed CLI
- reports no usage), 12 GLBs one joined mesh with vertex paint (the one-part plan plus
- the Blender contract's "one object per plan part" leave no other way to colour it, so
- wood and iron share one roughness), median asset 0.57 with 2 of 18 passing, and
- every fix prompt reading "Style of the whole scene: (none)" because the sub-spec's
- prompt IS the asset sheet.
- """
snake = to_snake(asset.name)
- # committed-child reuse (review-3 S2), blender twin: a GLB only exists at this
- # path when a previous session finished the build+copy; a measurable one is done.
+ # committed-child reuse: a measurable GLB at this path means the build already finished
glb = ctx.ws.root / ctx.runtime.asset_file(asset)
if glb.is_file() and glb.stat().st_size > 0 and _spec_hash_matches(ctx, asset) \
and (size := _measure_size(ctx, glb)) is not None:
@@ -421,8 +339,7 @@ def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> As
w, h, d = asset.approx_size_m
sub_ws = Workspace(ctx.ws.root / "_assets" / snake).create()
runtime = ctx.services.runtime(Language.BLENDER)
- # the sub-spec IS the asset sheet (the static machinery — planner, contract gate, tools —
- # reads it); the SCENE's brief and style travel in `extra` for the asset prompts
+ # the sub-spec IS the asset sheet; the scene's brief and style travel in `extra`
sub_spec = Spec(id=f"{ctx.spec.id}-asset-{snake}", track=Track.STATIC_OBJECT, language=Language.BLENDER,
prompt=asset.description, references=list(ctx.spec.references),
constraints=Constraints(style=ctx.spec.constraints.style,
@@ -438,14 +355,11 @@ def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> As
if not (sub_ws.root / HERO_ENTRY).is_file(): # a re-entry keeps the previous session's work
from codeverse3d.languages.blender import write_blender_skeleton
- # the object skeleton with the hero's ground tolerance: the scene seats every clone,
- # and 20 mm is the sink rule its module twin gets (measured 2026-09-07: 2.9 mm and
- # 4.0 mm cost two single-shot rungs and an agent escalation each)
+ # the hero's ground tolerance (20 mm sink rule, as its module twin)
write_blender_skeleton(sub_ws, sub.plan, ground_tol_m=HERO_GROUND_TOL_M)
sub_ws.commit("skeleton")
if 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 %
+ # language contract alone: harness_contract.md's ±1 cm bbox acceptance contradicts the prop sheet's ±5 %
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)
@@ -504,22 +418,14 @@ def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> As
def hero_plan(sub: RunContext, asset: AssetPlan) -> StaticPlan:
- """The static-object planner's part list for a hero, or the one-part sheet when it fails.
-
- One planner call, the hero's own ``plan.json``: the part names the Blender contract
- demands, per-part bboxes, ``style_notes`` and an acceptance list — what a static_object
- run gets, from the code that gives it to them.
- """
+ """The static-object planner's part list for a hero, or the one-part sheet when it fails."""
try:
model = sub.services.chat_model(sub.spec.backends.planner)
plan = run_planner(sub.spec, sub.spec.backends.planner, StaticPlan, sub.ws, model=model, events=sub.events,
budget=sub.budget)
features = hero_features(asset.description)
if len(plan.parts) <= HERO_THIN_PLAN_PARTS and len(features) > HERO_THIN_PLAN_PARTS:
- # a one-part answer for a prop whose sheet names several features (the windmill got
- # 'BrickBase' alone twice on 2026-09-07 while every other hero got 7-12 parts): ask
- # ONCE more with the features as the checklist, which is what sizes the planner's
- # part budget (plan_budget: must_have) and names the parts it must list
+ # a one-part answer for a multi-feature sheet: ask once more with the features as the checklist
sub.events.emit("asset.plan_thin", asset=asset.name, n_parts=len(plan.parts), features=features)
spec2 = sub.spec.model_copy(update={"constraints": sub.spec.constraints.model_copy(update={"must_have": features})})
plan = run_planner(spec2, spec2.backends.planner, StaticPlan, sub.ws, model=model, events=sub.events,
@@ -535,10 +441,7 @@ def hero_plan(sub: RunContext, asset: AssetPlan) -> StaticPlan:
def hero_features(description: str, limit: int = 8) -> list[str]:
- """The features an asset sheet names — its clauses of two words or more — as a checklist.
-
- 'an octagonal brick base, a thatched body, a cap with a gallery and four lattice sails'
- → four items; the planner's part budget is sized from must_have (plan_budget)."""
+ """The features an asset sheet names — its clauses of two words or more — as a checklist."""
out: list[str] = []
for clause in re.split(r"[;,]|\band\b|\bwith\b|\bplus\b", description):
words = clause.strip(" .:()").split()
@@ -550,9 +453,6 @@ def hero_features(description: str, limit: int = 8) -> list[str]:
def _blender_check(ctx: RunContext, asset: AssetPlan, files: list[str], *, label: str, timeout_s: int) -> AssetCheck:
- """Build the hero — the agent path gets ONE error-focused repair session, the single-shot
- path none (its repair is the ladder's feedback rewrite) — then the soft findings a
- threejs module gets, from one measurement of the GLB."""
outcome = build_with_repair(ctx, round_index=0, label=label, files_hint=files,
max_attempts=0 if ctx.single_shot else 1, timeout_s=timeout_s)
b = outcome.build
@@ -583,11 +483,7 @@ def asset_plan(asset: AssetPlan) -> StaticPlan:
# ----------------------------------------------------------------------------- judge + fix
def _judge_wanted(ctx: RunContext, asset: AssetPlan, chk: AssetCheck | None, *, judge: bool) -> bool:
- """Stop paying for what is already good.
-
- A VLM verdict on a 0.3 m pebble that already passed the deterministic check
- tells us nothing the scene judge will not see anyway. Heroes (blender_glb)
- and anything big enough to dominate a frame keep their verdict."""
+ """Stop paying for what is already good."""
if not judge:
return False
if not ctx.budget.soft_ok():
@@ -596,10 +492,7 @@ def _judge_wanted(ctx: RunContext, asset: AssetPlan, chk: AssetCheck | None, *,
if asset.kind == "blender_glb":
return True
frac = _volume_fraction(ctx, asset)
- # the plan's LARGEST module (of at least JUDGE_MIN_VOLUME_M3) keeps its verdict whatever its
- # share: no prop reaches 5 % of a scene's volume (measured 2026-09-07 over two scenes:
- # 1e-5 .. 2e-3), so the share rule alone judged nothing, and the biggest prop is the one
- # that dominates frames
+ # the plan's LARGEST module (at least JUDGE_MIN_VOLUME_M3) keeps its verdict whatever its share
w, h, d = asset.approx_size_m
dominant = asset.name == _largest_module(ctx) and w * h * d >= JUDGE_MIN_VOLUME_M3
if chk is not None and chk.ok and chk.ran and frac < JUDGE_VOLUME_FRACTION and not dominant:
@@ -635,11 +528,7 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
language: Language, after_fix: Callable[[RunContext], bool] | None = None,
measure_fn: Callable[[], Any] | None = None,
snapshot: Callable[[], Callable[[], None]] | None = None) -> AssetResult:
- """Quick-sheet judge with asset (n_samples=1); ONE fix pass when below threshold,
- then the fix is checked (``after_fix(gen_ctx)``) and JUDGED AGAIN — ``score`` describes
- the asset that ships, ``score_before`` the one that was fixed. The fix climbs the
- same cheap rung as the generation: one chat call when the run has a chat model
- (measured 2026-09-07: an agent fix session for a single-shot hero timed out at $0)."""
+ """Quick-sheet judge with asset (n_samples=1)."""
from codeverse3d.judges.base import JudgeInput
events = ctx.events
@@ -655,8 +544,7 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
d.mkdir(parents=True, exist_ok=True)
try:
renders = render_fn(d)
- # the measurement the rubric's proportions criterion reads (a hero's quick sheet used to
- # arrive with "MEASUREMENTS: (none available)"); re-measured after a fix
+ # the measurement the rubric's proportions criterion reads; re-measured after a fix
measurement = measure_fn() if measure_fn is not None else None
verdict: Judgment = judge.judge(JudgeInput(spec=ctx.spec, renders=renders, round_index=round_index,
measurement=measurement,
@@ -667,8 +555,7 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
return None
write_json_atomic(d / "judge.json", verdict.model_dump(mode="json")) # replayable, like a round's judge/rNN.json
if verdict.degraded:
- # a degraded verdict is no verdict: score stays None and `judged` False, and the
- # fix pass is skipped (its improvement_plan is empty by construction).
+ # a degraded verdict is no verdict: score stays None and the fix pass is skipped
events.emit("asset.judge_degraded", asset=asset.name)
return None
events.emit("asset.judged", asset=asset.name, round=round_index, score=round(verdict.overall, 3), passed=verdict.passed)
@@ -704,8 +591,7 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
if again is None:
return result
if again.overall < (result.score or 0.0) and restore is not None:
- # a fix that judges WORSE is undone (loop 1's BronzeCenser went 0.526 → 0.43 through
- # its fix and shipped that way); `snapshot()` before the fix returned the restore
+ # a fix that judges WORSE is undone
restore()
result.fixed = False
events.emit("asset.fix_reverted", asset=asset.name, before=round(result.score or 0.0, 3), after=round(again.overall, 3))
@@ -716,9 +602,7 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
# ----------------------------------------------------------------------------- helpers
def asset_template(language: Language) -> str:
- """The asset-session template of a scene language (``tracks/scene.SCENE_TEMPLATES``); a blender
- hero — not a scene language — reads the three.js table's ``scene_asset.j2``, whose bpy branch
- it has always used."""
+ """The asset-session template of a scene language (``tracks/scene.SCENE_TEMPLATES``)."""
from codeverse3d.tracks.scene import (
SCENE_TEMPLATES, # scene imports this module: resolved at call time
)
@@ -727,15 +611,7 @@ def asset_template(language: Language) -> str:
def _asset_system(ctx: RunContext, language: Language) -> str:
- """The system prompt for one asset generation — same language, DIFFERENT task.
-
- A blender hero runs the full static-object machinery (plan, gates, judge) in its
- sub-workspace, so it gets the blender language base COMPOSED with the prop-for-a-scene
- role overlay. A three.js asset module is not a scene build at all — the scene_threejs
- base (lighting, cameras, multi-file) would mislead it — so it gets the dedicated
- asset-module prompt instead of that base. A bpy module likewise gets its own
- ``scene_blender/asset.md``, with the prop role overlay that tells it what a scene prop is.
- """
+ """The system prompt for one asset generation — same language, DIFFERENT task."""
if language is Language.SCENE_THREEJS:
return language_text(Language.SCENE_THREEJS, "asset.md").strip()
if language is Language.SCENE_BLENDER:
@@ -745,29 +621,18 @@ def _asset_system(ctx: RunContext, language: Language) -> str:
def _scene_context(ctx: RunContext) -> dict[str, Any]:
- """The SCENE's brief and style for an asset prompt, whichever spec ``ctx`` carries.
-
- A blender hero runs in a sub-context whose spec IS the asset sheet (the static machinery
- needs that), so ``spec_prompt`` would render the asset description as the scene. Every
- recorded hero fix prompt (18, 2026-08-25 → 09-05) read "Style of the whole scene: (none)".
- """
+ """The SCENE's brief and style for an asset prompt, whichever spec ``ctx`` carries."""
brief = ctx.extra.get("scene_brief")
return {"spec_prompt": brief, "constraints": ctx.extra.get("scene_style") or "(none)"} if brief else {}
-#: what names a library row (scene_threejs, the one language with a library): the factory right after a
-#: backtick — a camelCase call (``makeTree(``, ``patchWind``); a bare lowercase one (``seat``, ``block``)
-#: is an ordinary word in a sheet — and the module it lives in (``lib/tree.js``).
+#: what names a library row: a camelCase factory after a backtick (a bare lowercase word is ordinary prose), and the ``lib/`` module
_CATALOG_RES: dict[Language, tuple[re.Pattern[str], re.Pattern[str]]] = {
Language.SCENE_THREEJS: (re.compile(r"`([a-z]+[A-Z]\w*)[(`]"), re.compile(r"`lib/(\w+\.js)`")),
}
def library_rows(description: str, language: Language = Language.SCENE_THREEJS) -> str:
- """The effects-catalog rows of the library factories an asset sheet names, by call or by module
- (D100): a module asset may compose ``src/lib/``, and a single-shot writer cannot open the
- module to learn the call — the rows carry it. The whole catalog is a zone-sized prompt.
- ``""`` for a language without a library (scene_blender, a blender hero)."""
if language not in _CATALOG_RES:
return ""
call_re, module_re = _CATALOG_RES[language]
@@ -858,17 +723,13 @@ class AssetCheck(BaseModel):
def check_threejs_asset(ctx: RunContext, rel: str, pascal: str, *, timeout_s: float = 60.0,
expected_size_m: tuple[float, float, float] | None = None) -> AssetCheck:
- """Import ``rel`` in node, call ``build<Pascal>(THREE, {})`` and inspect the group.
-
- Never raises: an unavailable node runtime yields ``ran=False, ok=True`` so the
- strategy falls back to "the scene build will catch it"."""
+ """Import ``rel`` in node, call ``build<Pascal>(THREE, {})`` and inspect the group."""
path = ctx.ws.root / rel
if not path.is_file():
return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"{rel} was not written"])
try:
from codeverse3d.spatial.node import run_node, runtime_js_dir
- # the workspace's own lib/lifecycle.js: the instance the asset's `../lib/` imports load (D100)
lifecycle = ctx.ws.src / "lib" / "lifecycle.js"
args = [path.resolve().as_uri(), f"build{pascal}"] + ([lifecycle.resolve().as_uri()] if lifecycle.is_file() else [])
res = run_node(runtime_js_dir() / "lib" / "asset_check.mjs", args, cwd=ctx.ws.root,
@@ -890,17 +751,11 @@ def check_threejs_asset(ctx: RunContext, rel: str, pascal: str, *, timeout_s: fl
return chk
-#: the probe zone of a bpy asset check: ONE collection instance of the module at the origin, so
-#: the census GLB (which excludes the asset sources themselves) carries exactly the asset's
-#: evaluated geometry — measured like a hero's GLB, in the same Y-up frame
+#: probe zone of a bpy asset check: one collection instance at the origin, so the census GLB carries exactly the asset's geometry
BPY_CHECK_ZONE = "check"
def _bpy_check_workspace(ws: Workspace, rel: str, snake: str) -> Workspace:
- """A throw-away workspace under ``_assets/`` (git-ignored, beside the hero sub-workspaces)
- holding only what one module's build needs: an entry that lists this asset alone, the
- module and the probe zone. Rebuilt from scratch on every check so a module's last attempt
- never shadows its next."""
from codeverse3d.languages.scene_blender import render_scene_py
scratch = Workspace(ws.root / "_assets" / f"{snake}_check")
@@ -925,19 +780,7 @@ def _bpy_check_workspace(ws: Workspace, rel: str, snake: str) -> Workspace:
def check_bpy_asset(ctx: RunContext, rel: str, snake: str, *, expected_size_m: tuple[float, float, float] | None = None,
timeout_s: float | None = None) -> AssetCheck:
- """Build ``src/assets/<snake>.py`` alone in Blender and inspect what it made.
-
- The scene_blender wrapper (``runtime.run_wrapper``) runs on a throw-away workspace whose
- entry lists only this asset and whose one zone instances it: a module that raises is FATAL
- with its ``file:line`` (the wrapper's isolated-stage report), the module's own triangles
- come from the bpy facts, and the instance's size, ground contact, mesh and material counts
- come off the census GLB through ``services.measure`` — the hero's measurement, so the
- soft findings (size vs the plan beyond 2.5×, sunk below z = 0, the triangle budget, a
- one-box placeholder) are the three.js module's exactly.
-
- Never raises: a runtime without a Blender build (a fake, no binary) and a harness fault inside
- the wrapper (``BuildResult.harness_failure``: the census-GLB writer) yield ``ran=False, ok=True``
- — the scene build will catch it."""
+ """Build ``src/assets/<snake>.py`` alone in Blender and inspect what it made."""
path = ctx.ws.root / rel
if not path.is_file():
return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"{rel} was not written"])
@@ -958,18 +801,15 @@ def check_bpy_asset(ctx: RunContext, rel: str, snake: str, *, expected_size_m: t
return AssetCheck(ok=False, ran=True, fatal=True,
errors=[f"{where}: {e.get('error_type')}: {str(e.get('error_message'))[:300]}"])
if run.result.harness_failure:
- # the wrapper's OWN instrumentation failed after the stages ran (``CensusGlbError``: the
- # census-GLB writer), not the module — the rule of a runtime without Blender: never a blocker
+ # the wrapper's own instrumentation failed (``CensusGlbError``), not the module: never a blocker
log.warning("bpy asset check could not finish for %s: %s", rel, run.result.error_type)
return AssetCheck(ok=True, ran=False, warnings=[f"checker unavailable: {run.result.error_type}"])
if report.get("nonfinite"):
- # the build finished but left a NaN / inf the census refused (D114): the module's error as reported
return AssetCheck(ok=False, ran=True, fatal=True,
errors=[f"{report.get('error_file') or rel}: {report.get('error_type')}: "
f"{str(report.get('error_message'))[:600]}"])
if not run.result.ok:
- # the wrapper itself did not finish — a build that never ends or dies (an unbounded loop,
- # an allocation past the rlimit) is this module's doing: the entry lists nothing else
+ # the wrapper did not finish (unbounded loop, allocation past the rlimit): this module's doing
return AssetCheck(ok=False, ran=True, fatal=True,
errors=[f"the module's build did not finish: {run.result.error_type}: {run.result.error_message}"[:300]])
if any(e.get("stage") == "zone" for e in report.get("errors") or []):
@@ -1039,13 +879,7 @@ def _family(name: str) -> str:
def select_assets(assets: list[AssetPlan], cap: int) -> tuple[list[AssetPlan], dict[str, str]]:
- """The assets to actually build, in plan (= priority) order, plus the merge map.
-
- Dedupe is a *rescue*, not a default: while the plan fits under ``cap`` every planned
- prop is built (single-shot assets are nearly free, and a distinct prop is worth more
- than a variant flag). Only an over-long list is folded — turning "drop the 9th
- asset" into "the 9th asset is a variant of the 3rd" — and whatever is still over the
- cap is truncated by priority."""
+ """The assets to actually build, in plan (= priority) order, plus the merge map."""
alias: dict[str, str] = {}
if len(assets) > cap:
assets, alias = dedupe_assets(assets)
@@ -1057,13 +891,7 @@ def select_assets(assets: list[AssetPlan], cap: int) -> tuple[list[AssetPlan], d
def dedupe_assets(assets: list[AssetPlan]) -> tuple[list[AssetPlan], dict[str, str]]:
- """Fold near-identical props into ONE parameterised factory.
-
- Two assets merge when their head nouns belong to the same family AND their
- largest dimensions are within 3× — "HeroBoulder" (2.5 m) and "TalusRock"
- (0.5 m) are different props; "SteppingStone" and "PondRock" are one factory
- with a variant. Plan order is priority: the first one survives.
- Returns ``(kept_assets, {dropped_name: kept_name})``."""
+ """Fold near-identical props into ONE parameterised factory."""
kept: list[AssetPlan] = []
alias: dict[str, str] = {}
for a in assets:
@@ -1105,8 +933,7 @@ def variant_index(alias: dict[str, str], name: str) -> int:
def write_dedupe_note(ws: Workspace, alias: dict[str, str]) -> None:
- """Persist the merge map the stage USED: the ``asset_api`` stage reads it back, because the cap that
- made it (`MAX_ASSETS` or `DEGRADED_MAX_ASSETS`) depends on the soft budget at the time."""
+ """Persist the merge map the stage USED."""
write_json_atomic(ws.root / "stages" / "asset_aliases.json", {"alias": alias})
@@ -1118,13 +945,7 @@ def read_dedupe_note(ws: Workspace) -> dict[str, str]:
def write_variant_shims(ws: Workspace, alias: dict[str, str], available: set[str], *,
language: Language = Language.SCENE_THREEJS) -> list[str]:
- """Replace a merged asset's skeleton stub with a shim onto the surviving factory.
-
- three.js: zone code is TOLD to call ``build<Kept>(THREE, {variant: n})``, but a zone that
- imports the old name anyway must get the real prop, not the placeholder blockout box the
- skeleton left behind. bpy: the wrapper builds every ``src/assets/*.py`` into
- ``ctx.assets``, so the shim IS how the merged twin exists — ``build_<dropped>`` builds the
- survivor's variant into its own Collection and the zones place it by its own name."""
+ """Replace a merged asset's skeleton stub with a shim onto the surviving factory."""
written: list[str] = []
for dropped, kept in sorted(alias.items()):
if kept not in available:
diff --git a/harness/codeverse3d/tracks/skills_hook.py b/harness/codeverse3d/tracks/skills_hook.py
index f75f4dfc..110b8831 100644
--- a/harness/codeverse3d/tracks/skills_hook.py
+++ b/harness/codeverse3d/tracks/skills_hook.py
@@ -1,15 +1,5 @@
-"""Where the skill system meets a round: route before generating, measure after.
+"""Skills hook: attaches the selected skills to a track's prompts."""
-Kept out of ``codeverse3d/skills`` so that package stays pure (no ``RunContext``, no
-workspace conventions, no environment) and testable without a run. Kept out of
-``steps.py`` so a round's control flow does not grow a second subject.
-
-Everything here is a no-op when ``C3D_SKILLS=0`` (the system is ON by default since
-2026-09-22), and every function swallows its own failures: a skill that cannot be routed,
-written or probed must cost that skill, not the round. The switch is ``Settings.skills``,
-read at the call. ``record_usage`` reads what the round's sessions did
-from their CLIs' own tool calls (``skills/telemetry.probe_reads``), atime only as fallback.
-"""
from __future__ import annotations
@@ -24,13 +14,11 @@ from codeverse3d.tracks.common import RunContext
log = logging.getLogger(__name__)
-CTX_KEY = "skills" # ctx.extra slot holding this round's SkillsMaterialized
+CTX_KEY = "skills"
def attach_for_round(ctx: RunContext, *, index: int, kind: str, findings: Sequence[GateReport] = ()) -> Any | None:
- """Route + materialise this round's skills. Returns the ``SkillsMaterialized``.
-
- ``findings``: the previous round's gates — the input no CLI's own loader can see."""
+ """Route + materialise this round's skills. Returns the ``SkillsMaterialized``."""
from codeverse3d.skills import attach_skills
# drop the previous round's set first: a failure below must not leave this round
@@ -52,9 +40,6 @@ def attach_for_round(ctx: RunContext, *, index: int, kind: str, findings: Sequen
log.warning("skills not attached for round %d (%s): %s", index, kind, e)
return None
ctx.extra[CTX_KEY] = got
- # the body a session actually saw is part of what decided the run: hash it beside the
- # prompt hashes so a later comparison of two runs can tell "same skill, new wording"
- # from "different skill"
for sel in got.selections:
ctx.record_prompt(f"skill:{sel.name}", sel.skill.body)
ctx.events.emit("skills.attached", round=index, kind=kind, skills=got.listed,
@@ -64,12 +49,7 @@ def attach_for_round(ctx: RunContext, *, index: int, kind: str, findings: Sequen
def with_inlined_skill(ctx: RunContext, tasks: Sequence[Any]) -> list[Any]:
- """Single-shot only: prepend the one routed body to each task prompt.
-
- A single-shot call has no read loop, so a pointer to a file it cannot open would be
- cost with no benefit — and, worse, would make the single-shot arm quietly
- incomparable with the agent arms. One body, capped, in the prompt.
- """
+ """Single-shot only: prepend the one routed body to each task prompt."""
got = ctx.extra.get(CTX_KEY)
if not got or not getattr(got, "inlined", ""):
return list(tasks)
@@ -82,14 +62,7 @@ def with_inlined_skill(ctx: RunContext, tasks: Sequence[Any]) -> list[Any]:
def repair_pointers(ctx: RunContext, build: BuildResult, lint: GateReport) -> str:
- """Name the attached skills that answer the CURRENT failure: the lint and the build's own
- reports (``BuildResult.gates`` — a scene's shader_preflight), the same reports a refine
- round routes on.
-
- The repair prompt's only pointer to material (D107): the attached bundles whose routes
- match the build / lint finding kinds. It only names skills that are already in the
- workspace, so it adds pointers rather than text.
- """
+ """Name the attached skills that answer the CURRENT failure: the lint and the build's own"""
got = ctx.extra.get(CTX_KEY)
if not got or not getattr(got, "selections", None):
return ""
@@ -97,15 +70,11 @@ def repair_pointers(ctx: RunContext, build: BuildResult, lint: GateReport) -> st
from codeverse3d.skills.registry import ROUTES, finding_kinds
kinds = finding_kinds([lint, *build.gates])
- # ANY route for the skill, not just the rules that fired at attach time: the build/lint failure a
- # repair session is looking at was discovered afterwards, and the sheet that answers it is
- # already sitting in the workspace
answering = [s.name for s in got.selections if any(r.skill == s.name and r.matches_finding(kinds) for r in ROUTES)]
return _fmt(got.selections, agent_kind=ctx.agent_kind, answering=answering)
def record_usage(ctx: RunContext, *, index: int, kind: str) -> SkillsUsage | None:
- """After the round's sessions: what was read. Also appends ``telemetry/skills.jsonl``."""
got = ctx.extra.get(CTX_KEY)
if not got:
return None
diff --git a/harness/codeverse3d/tracks/static_object.py b/harness/codeverse3d/tracks/static_object.py
index fcab6c72..65cd9615 100644
--- a/harness/codeverse3d/tracks/static_object.py
+++ b/harness/codeverse3d/tracks/static_object.py
@@ -1,13 +1,4 @@
-"""StaticObjectTrack: plan → skeleton → draft → refine rounds → finalise (D110, baseline-first).
-
-Languages: blender (bpy) · cadquery · threejs (articulated_object subclasses it for urdf_blender).
-Round 0 is ONE agent session that drafts the WHOLE object — every part file and the entry
-(``BaseTrack.baseline_tasks`` over ``generate_static.j2``); every refine round is ONE session that
-edits the whole object in place (``allow_refine_fanout = False``), driven by the gate ERRORs
-(placeholder parts first), the failed must-acceptance items and the judge's improvement plan.
-No per-part scoped baseline and no parallel part sessions: they ran serially behind the
-per-workspace session lock since 2026-08-28 and left 13-14 of 15 argon runs with placeholder parts.
-"""
+"""StaticObjectTrack."""
from __future__ import annotations
@@ -52,8 +43,7 @@ from codeverse3d.workspace import Workspace
log = logging.getLogger(__name__)
-#: the 4 clay views judged for holes/intersections — their own measured cameras (D47),
-#: NOT a name-filter over OBJECT_VIEWS (which silently shrank under renamed rigs)
+#: the 4 clay views judged for holes/intersections; their own cameras, not a name filter over OBJECT_VIEWS
GEOMETRY_VIEWS = OBJECT_CLAY_VIEWS
@@ -78,8 +68,7 @@ class ObjectPipeline:
out.append(
ctx.services.contract(measurement, ctx.plan, BBOX_TOLERANCE_M, ctx.language.value)
)
- # 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).
+ # deterministic density check against the plan; the judge is never asked about detail
out.append(budget_gate(measurement, build, depth_budget(ctx.plan, ctx.settings.limits.build_timeout_s)))
return out
@@ -105,10 +94,7 @@ class ObjectPipeline:
def geometry_views(
self, ctx: RunContext, round_index: int, build: BuildResult
) -> RenderSet | None:
- """4 clay views for the judge's geometry montage (holes, intersections).
-
- The plain-geometry render exposes defects that materials hide; cached, so
- near-free. Object tracks only — scenes/graphics have no single GLB."""
+ """4 clay views for the judge's geometry montage (holes, intersections)."""
if not build.glb_path:
return None
out_dir = ctx.ws.renders_dir(round_index) / "clay"
@@ -129,12 +115,7 @@ class ObjectPipeline:
build: BuildResult,
gates: list[GateReport],
) -> str:
- """Nothing beyond ``gates_section``. The measured-structure block the judge reads
- (contacts, planned joins, floor gaps, the weld line) is rendered by
- ``judges.prompt_builder.gates_section`` from the connectivity report's contact
- ledger — the report is stored in ``rounds/rNN.json``, so ``3dcode judge <slug>``,
- calibration and every other reader of the round record get the same block as the
- in-run judge without this method restating it (2026-08-30)."""
+ """Nothing beyond ``gates_section``."""
return ""
@@ -144,8 +125,7 @@ class StaticObjectTrack(BaseTrack):
plan_model = StaticPlan
generate_template = "tracks/generate_static.j2"
refine_template = "tracks/refine_object.j2"
- #: ONE whole-object refine session per round (D110): the part files interlock, and a split
- #: round ran its sessions one after another behind the workspace lock anyway
+ #: the part files interlock: one whole-object refine session per round
allow_refine_fanout = False
def make_pipeline(self) -> ObjectPipeline:
@@ -153,21 +133,13 @@ class StaticObjectTrack(BaseTrack):
# ------------------------------------------------------------------ refine (scaffold hooks)
def extra_refine_tasks(self, ctx: RunContext, last: RoundRecord) -> Sequence[RefineTask]:
- # NB: the `detail_budget` WARN is deliberately NOT turned into a refine task. Measured:
- # refine rounds that added > 2000 triangles while assembly was still open lost 0.075 of
- # assembly_fit and 0.025 of overall.
+ # the `detail_budget` WARN is deliberately NOT a refine task (adding triangles while assembly is open lowers the score)
return reference_refine_tasks(ctx, last)
def _refine_task(
self, ctx: RunContext, group: TaskGroup, last: RoundRecord, index: int, *, parallel: bool
) -> GenerationTask:
- """The round's ONE whole-object session: every file in scope, edited in place; each
- instruction line names the files its target owns. ``group`` is the round's single group
- (no fan-out), its tasks already ordered gate ERRORs → acceptance → judge plan.
-
- A single-shot call has no read tool: it sees only the files inlined for it, so when the
- tasks name files it is fenced to them (``edit_only``, the entry still writable) — a model
- told "the whole object" once could rewrite a part file it was never shown."""
+ """The round's ONE whole-object session."""
fenced = ctx.single_shot and bool(group.files)
files = list(group.files) if fenced else ctx.runtime.expected_files(ctx.plan)
lines = compact_instructions(group.tasks, max_lines=ctx.policy.max_instructions_per_task)
@@ -202,22 +174,11 @@ class StaticObjectTrack(BaseTrack):
)
-#: the shortest refine window opened: below it the hard run clock decides anyway
REFINE_MIN_WINDOW_S = 120.0
def object_session_window_s(ctx: RunContext) -> int:
- """A refine session's window: the agent default, clipped so that the session — which the
- watchdog lets run ``HARD_GRACE_S`` past its window while it is still working — ends
- ``RoundPolicy.judge_reserve_s`` before the run's HARD ceiling (the round's build, gates, renders and
- judge: 0.7 min measured for an object, 2026-10-15; one reserve for every track since D112 — it was
- ``OBJECT_ROUND_RESERVE_S``, 180 s, beside the refine task's own ``GenerationTask.reserve_s``).
-
- WHY. With no window of its own the session ran to the run's deadline: the baseline-first
- smoke's blender refine (started at 25.8 min, 36 min allowed) was killed by the run clock at
- 60.0 min after $4.63 of work, and the round was dropped unbuilt and unjudged — as were all
- three refines of iteration 0's dining chair. Ended earlier, its edits are built and judged
- and the picker chooses between the rounds."""
+ """A refine session's window."""
left = ctx.budget.left_s() - ctx.policy.judge_reserve_s - HARD_GRACE_S
return int(max(REFINE_MIN_WINDOW_S, min(float(ctx.settings.limits.agent_timeout_s), left)))
@@ -228,10 +189,6 @@ IOU_REFINE_THRESHOLD = 0.6
def silhouette_gate(ctx: RunContext, renders: RenderSet) -> GateReport | None:
- """The round's :func:`~codeverse3d.spatial.silhouette.measure_reference` — the measurement the
- reference judge scores — as a finding: WARN below the refine threshold when the IoU is a shape
- verdict (reliable mask, reference agrees with the brief), else INFO. ``None`` when the spec
- has no reference or nothing could be compared."""
try:
m = measure_reference(renders.views, ctx.spec, compare=ctx.services.silhouette)
except Exception as e: # noqa: BLE001 — advisory measurement; never fails a round
diff --git a/harness/codeverse3d/tracks/steps.py b/harness/codeverse3d/tracks/steps.py
index 537eb9da..992233f1 100644
--- a/harness/codeverse3d/tracks/steps.py
+++ b/harness/codeverse3d/tracks/steps.py
@@ -1,23 +1,4 @@
-"""One round = generate → build(+repair) → gates → measure → render → judge → commit.
-
-``run_round`` is track-agnostic; a ``RoundPipeline`` supplies the track-specific
-gates / measurement / rendering. Every step writes its artifact under the
-workspace (gates/rNN, renders/rNN, judge/rNN.json, rounds/rNN.json, and the build
-outputs a hand-over needs under artifacts/rNN/) so a run can be resumed, the flywheel
-can replay it, and any round can be packaged later without a rebuild.
-
-Two cost rules live here (docs/COST.md §5, §6):
-
-* **never pay for a verdict you will not use** — :func:`skip_judge_reason` drops
- the judge only where the verdict is provably never bought at all, and
- :func:`rejudge_round` re-buys one only after the judge was TRIED and failed, so
- a skip is a saving and not a deferral. Two wave-2 branches were removed for
- failing exactly that test (docs/COST.md §17).
-* **a round's cost is its ledger rows** — the round runs inside a ``cost.tally``, so
- ``RoundRecord.usage`` is exactly what ``telemetry/cost.jsonl`` booked while it ran, and a
- round that raises half-way still reports it (``rounds/aborted_rNN.json``). Each step it
- runs is timed into ``RoundRecord.steps`` (docs/COST.md §31).
-"""
+"""One round = generate → build(+repair) → gates → measure → render → judge → commit."""
from __future__ import annotations
@@ -60,41 +41,25 @@ class RoundPipeline(Protocol):
def gates(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> list[GateReport]: ...
def render(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> RenderSet: ...
def judge_context(self, ws: Workspace, plan: Plan | None, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
- """Track-specific judge context. Deliberately ``RunContext``-free so
- ``3dcode judge`` can rebuild the in-run context from stored artifacts."""
+ """Track-specific judge context. Deliberately ``RunContext``-free so"""
...
-#: ``(ctx, round_index, build, measurement) → renders`` — ``RoundPipeline.render`` or a
-#: cheaper stand-in (best-of-N candidates rank on ``candidates.quick_render``)
RenderFn = Callable[[RunContext, int, BuildResult, Measurement | None], RenderSet | None]
class RoundFailed(RuntimeError):
- """Every generation task of a round failed — nothing to build.
-
- Typed, so the round loop never reads the message: ``transient`` — a task died of a
- provider failure (a vendor-CLI 503 storm, a dropped socket, a ``ModelError`` outage), so
- the round is re-run once before the failure may mean anything; ``quota`` — the vendor's
- usage limit is spent, so the run stops as ``agent_quota``. Neither — the agents ran
- and changed nothing: a ``no_change`` stop. The flags come from each backend's own
- classification (``AgentResult``) through ``GenerationResult``; until 2026-09-22 the loop
- substring-matched the joined notes, with a vocabulary that had drifted from the backends'
- (a codex usage limit reached the loop only because the loop's list said "usage limit")."""
+ """Every generation task of a round failed — nothing to build."""
def __init__(self, message: str, *, transient: bool = False, quota: bool = False, stalled: bool = False) -> None:
super().__init__(message)
self.transient = transient
self.quota = quota
- #: a session hung (``GenerationResult.stalled``, D112): retried like a transport death
self.stalled = stalled
@classmethod
def of(cls, results: Sequence[GenerationResult], default: str) -> RoundFailed:
- """The round's failure: every task's notes, and the typed flags of any of them — except
- ``stalled``, which needs EVERY session to have hung or died of transport (D112): a split
- round whose other session worked to its hard limit and wrote nothing is that session's
- verdict, and the round loop retries a round whole."""
+ """The round's failure: every task's notes, and the typed flags of any of them — except"""
return cls("; ".join(f"{r.label}: {r.notes}" for r in results) or default,
transient=any(r.transient for r in results), quota=any(r.quota for r in results),
stalled=any(r.stalled for r in results) and all(r.stalled or r.transient for r in results))
@@ -105,10 +70,7 @@ def round_record_path(ctx: RunContext, index: int) -> Path:
def load_round_journal(ws: Workspace) -> list[RoundRecord]:
- """The on-disk round journal: ``rounds/r*.json`` sorted, contiguous prefix only.
-
- Workspace-level (no ``RunContext``) because ``lifecycle.reconcile_resume``
- reads it before the context exists."""
+ """The on-disk round journal: ``rounds/r*.json`` sorted, contiguous prefix only."""
d = ws.root / "rounds"
if not d.is_dir():
return []
@@ -123,8 +85,7 @@ def load_round_journal(ws: Workspace) -> list[RoundRecord]:
def run_generation_tasks(ctx: RunContext, tasks: Sequence[GenerationTask], *,
steps: list[StepTime]) -> list[GenerationResult]:
- """Run tasks side by side — one ``generate`` step: its sessions share one clock. Raises
- ``RoundFailed`` when none succeeded."""
+ """Run tasks side by side — one ``generate`` step: its sessions share one clock. Raises"""
if not tasks:
return []
@@ -141,16 +102,16 @@ def run_generation_tasks(ctx: RunContext, tasks: Sequence[GenerationTask], *,
for task, r in zip(tasks, results, strict=True):
if isinstance(r, Exception):
if isinstance(r, BudgetExceeded) and budget_stop is None:
- budget_stop = r # a failed item; the siblings' paid results still land in ``out``
+ budget_stop = r
ctx.events.emit("generate.failed", label=task.label, error=f"{type(r).__name__}: {r}")
out.append(GenerationResult.from_error(task.label, r))
else:
out.append(r)
if not any(r.ok for r in out):
if budget_stop is not None:
- raise budget_stop # nothing usable survived the batch
+ raise budget_stop
raise RoundFailed.of(out, "no generation task succeeded")
- ctx.budget.check() # step boundary: single-shot money is booked non-enforcing upstream
+ ctx.budget.check()
return out
@@ -168,18 +129,7 @@ def run_round(
extra_usage: Usage | None = None,
extra_notes: Sequence[str] = (),
) -> RoundRecord:
- """Execute one round and persist its record. Budget is charged as it goes.
- ``previous`` / ``findings``: the previous round's verdict and gates (the judge reads the one,
- the skill router the other).
-
- ``tasks`` may be empty when the code is already in place (scene stages,
- best-of-N winner copied in): the round is then build → gates → render →
- judge only. ``extra_usage`` / ``extra_notes`` fold pre-round work
- (candidate generation) into the record.
- ``_run_round`` (the same round without the aborted-round record) also takes
- ``render`` (replaces ``pipeline.render``) and ``geometry_views=False`` (skips the
- clay views): the two knobs a best-of-N candidate turns (``candidates.run_best_of_n``
- calls it directly for each candidate in its sub-workspace)."""
+ """Execute one round and persist its record. Budget is charged as it goes."""
steps: list[StepTime] = []
with tally() as spent:
try:
@@ -187,8 +137,6 @@ def run_round(
previous=previous, findings=findings, files_hint=files_hint, extra_usage=extra_usage,
extra_notes=extra_notes, steps=steps, spent=spent)
except BaseException as e:
- # the round died half-way (budget stop, 503 storm, RoundFailed): what it burned
- # is in its tally — the ledger rows booked while it ran — so it is not invisible
record_aborted_round(ctx, index=index, kind=kind, usage=spent.usage,
error=f"{type(e).__name__}: {e}", steps=steps)
raise
@@ -212,8 +160,7 @@ def _run_round(
steps: list[StepTime] | None = None,
spent: Tally,
) -> RoundRecord:
- """The round's body. ``spent`` is the tally the caller opened around it: the round's
- cost is what it booked (+ ``extra_usage``, work paid before the round began)."""
+ """The round's body. ``spent`` is the tally the caller opened around it: the round's"""
t0 = time.time()
steps = [] if steps is None else steps
ctx.events.emit("round.start", round=index, kind=kind, n_tasks=len(tasks))
@@ -221,9 +168,6 @@ def _run_round(
started_at=datetime.now(UTC))
notes: list[str] = list(extra_notes)
- # a candidate IS a baseline written in a sub-workspace: route its skills as baseline work,
- # or every kind-gated bundle (the *-forms / *-joints routes) drops out and the winner is
- # generated with a strictly smaller library than a --candidates 1 baseline (review 2026-08-29)
skill_kind = "baseline" if kind == "candidate" else kind
skills_hook.attach_for_round(ctx, index=index, kind=skill_kind, findings=findings)
gens = run_generation_tasks(ctx, skills_hook.with_inlined_skill(ctx, tasks), steps=steps)
@@ -249,12 +193,6 @@ def _run_round(
with timed("render", steps, round_index=index):
rec.renders = (render or pipeline.render)(ctx, index, outcome.build, rec.measurement)
except RenderError as e:
- # A render that times out (measured 2026-08-26, art_verify camera_tripod: the
- # refine round built in 1.2 s, then render_glb.mjs hit its 330 s timeout with
- # three articulated runs and two readouts sharing the browser) used to raise
- # out of the round and record the whole run `failed` -- with a judged round 0
- # already on disk. The round is kept: build, measurement and gates stand and
- # the judge is skipped (no renders), so a pick passes over it.
rec.renders = None
notes.append(f"render failed: {str(e)[:200]}")
ctx.events.emit("render.failed", round=index, error=str(e)[:400])
@@ -262,8 +200,6 @@ def _run_round(
if callable(post) and rec.renders is not None:
with timed("gates", steps, round_index=index):
gates.extend(post(ctx, index, rec.renders))
- # the build's own reports (scene_probe + shader_preflight, gl_frames) after the
- # track's: the judge's warning list is capped and reads them in this order
gates.extend(outcome.build.gates)
n_err = sum(len(g.errors) for g in gates)
ctx.events.emit("gates.done", round=index, n_gates=len(gates), n_errors=n_err,
@@ -277,7 +213,6 @@ def _run_round(
rec.judgment = _judge(ctx, pipeline, index, outcome.build, gates, rec, previous, notes,
geometry_views=geometry_views)
else:
- # a failed build's own reports say why (a shader error lives in shader_preflight)
gates.extend(outcome.build.gates)
notes.append(f"build failed: {outcome.build.error_type}: {outcome.build.error_message[:200]}")
rec.gates = gates
@@ -286,7 +221,6 @@ def _run_round(
rec.commit = ctx.ws.commit(f"r{index:02d} {kind}")
if outcome.build.ok:
- # every round keeps what a hand-over of it needs: the next build replaces artifacts/
keep_round_artifacts(ctx.ws, index)
rec.usage = spent.usage + (extra_usage or Usage())
rec.duration_s = round(time.time() - t0, 2)
@@ -300,19 +234,7 @@ def _run_round(
# ----------------------------------------------------------------------------- cost of a round
def skip_judge_reason(ctx: RunContext, *, renders: RenderSet | None) -> str:
- """Why this round must NOT be judged (``""`` = judge it).
-
- Only states in which the verdict is never bought at all — a skip that the
- loop buys back a moment later (``rejudge_round``) is not a saving, it is a
- ``judge.retry`` plus a lost score:
-
- * ``no judge configured`` / ``no renders`` — there is nothing to buy.
-
- A round that finished past the wall clock is still judged (2026-09-22): its verdict is
- what lets ``addons.select`` pick it, and the generation it scores is already paid for.
- A broken build never gets here (``run_round`` judges only when the build is
- ok) and a round in which nothing changed never gets here either
- (``run_generation_tasks`` raises :class:`RoundFailed` first)."""
+ """Why this round must NOT be judged (``""`` = judge it)."""
if ctx.judge is None:
return "no judge configured"
if renders is None or not renders.views:
@@ -322,14 +244,7 @@ def skip_judge_reason(ctx: RunContext, *, renders: RenderSet | None) -> str:
def record_aborted_round(ctx: RunContext, *, index: int, kind: str, usage: Usage, error: str,
steps: Sequence[StepTime] = ()) -> None:
- """A round that raised half-way still reports what it burned.
-
- Its record is written next to the round records as ``aborted_rNN.json`` (never
- ``rNN.json``: the round did not happen, and ``load_round_journal`` must not
- resume from it), its cost is remembered in ``ctx.extra`` so the run record can carry
- it, and the steps it did run join the run-level steps (``RunState.steps``): their
- minutes were spent. Accounting a stop must never raise on top of the stop that is
- already happening."""
+ """A round that raised half-way still reports what it burned."""
try:
ctx.state.steps.extend(steps)
rec = RoundRecord(index=index, kind=kind, agent_backend=ctx.agent_id, usage=usage, steps=list(steps),
@@ -346,11 +261,7 @@ def record_aborted_round(ctx: RunContext, *, index: int, kind: str, usage: Usage
def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildResult, gates: list[GateReport],
rec: RoundRecord, previous: Judgment | None, notes: list[str], *,
geometry_views: bool = True) -> Judgment | None:
- """Judge one round; ``None`` when the verdict is unusable (the judge crashed or returned
- a degraded non-score). What the attempt cost reaches the round either way: its calls
- are ledger rows, booked into the round's tally. Failure notes are appended to the
- CALLER's ``notes`` list — ``_run_round`` joins that list into ``rec.notes`` at the end
- of the round, so writing to ``rec.notes`` here was silently lost."""
+ """Judge one round; ``None`` when the verdict is unusable."""
renders = rec.renders
jv = getattr(pipeline, "judge_views", None)
if callable(jv) and renders is not None:
@@ -387,19 +298,12 @@ def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildRes
def rejudge_round(ctx: RunContext, pipeline: RoundPipeline, rec: RoundRecord, previous: Judgment | None = None) -> bool:
- """Re-judge an already built+rendered round whose judgment FAILED or was degraded.
-
- No regeneration, no rebuild: the same commit is judged again. On success the
- round record is updated in place and re-persisted. Returns True when the
- round now has a usable judgment."""
if ctx.judge is None or rec.build is None or not rec.build.ok or rec.renders is None or not rec.renders.views:
return False
ctx.events.emit("judge.retry", round=rec.index)
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, 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 record
rec.usage = rec.usage + spent.usage
if judgment is not None:
rec.judgment = judgment
diff --git a/harness/codeverse3d/tracks/zone_layout.py b/harness/codeverse3d/tracks/zone_layout.py
index 5c7192dc..0e5102f4 100644
--- a/harness/codeverse3d/tracks/zone_layout.py
+++ b/harness/codeverse3d/tracks/zone_layout.py
@@ -1,17 +1,4 @@
-"""L2 zone layouts: one cheap structured call per zone, in parallel, validated.
-
-Why this layer exists (measured 2026-08-30 across the 48 scored scene runs):
-``ZonePlan.contents`` is a list of NAMES — the zone agent freehand-places
-everything, and the final rounds still carried 55 interpenetration, 38 sunken
-and 22 floating gate ERRORS, with undressed_scene standing in 31/48 verdicts.
-The layout is planning work, so it is done by the PLANNER model with a schema
-(never a coding agent), validated deterministically against the zone bbox and
-the plan, re-asked once with the exact complaint, and handed to the zone
-builder as numbers to realise.
-
-Layouts are an optional accelerator like the engineering brief: any failure
-returns no layout for that zone and generation proceeds exactly as before.
-"""
+"""L2 zone layouts."""
from __future__ import annotations
@@ -38,22 +25,11 @@ LAYOUT_WAIT_S = 300.0
COUNT_SLACK = 4
#: cluster centres may sit this far outside the zone bbox (assets have radius)
BBOX_MARGIN_M = 1.0
-#: lens margin beyond the asset's own reach. Two measurements set this: fv_izakaya_night
-#: (2026-08-30) — BarCounter 0.7 m from the PotDetail camera put the lens INSIDE the
-#: counter, three capped rounds, unfixable downstream; and dg_izakaya_night (2026-08-31)
-#: — the first tune (1.2 m base + footprint/2 + full spread) rejected EVERY placement a
-#: small indoor zone could offer ("WoodenStool 1.8 m from OdenStationDetail — keep
-#: >= 1.8 m") until the layout was dropped entirely, muting the layer exactly where it
-#: helps. The validator now rejects only what puts the LENS inside the asset's reach
-#: (half footprint + half spread + this margin, floored at 0.8 m); polite shot spacing
-#: stays in the prompt, where a director can trade it off.
+#: lens margin beyond the asset's own reach; the validator rejects only a lens INSIDE the
+#: asset's reach (half footprint + half spread + this, floored), spacing stays in the prompt.
CAMERA_CLEAR_M = 0.4
CAMERA_CLEAR_FLOOR_M = 0.8
-#: two LARGE assets whose cluster centres nearly coincide are stacked into each other —
-#: fv2_alpine_night's RetainingWall x PrayerBench interpenetration. Deliberately narrow:
-#: only same-spot (< 0.6 m) pairs where BOTH footprints are >= 0.8 m and neither stands on
-#: the other — a stool against a counter (small footprint) or bottles on a bar
-#: (support relation) must never be rejected.
+#: two LARGE assets on nearly the same spot are stacked; small footprints and supported items are never rejected.
STACK_DIST_M = 0.6
STACK_MIN_FOOT_M = 0.8
@@ -75,18 +51,14 @@ def validate_layout(layout: ZoneLayout, zone: ZonePlan, plan: ScenePlan) -> str:
f"x {lo[0]:.1f}..{hi[0]:.1f}, z {lo[2]:.1f}..{hi[2]:.1f}")
if p.count > COUNT_SLACK * hints[k]:
problems.append(f"{p.asset} count {p.count} is over {COUNT_SLACK}x the plan's instances_hint {hints[k]}")
- # the shot must survive the layout: a cluster whose footprint reaches a camera
- # puts geometry inside the lens (fv_izakaya_night), and nothing downstream can fix it
+ # a cluster whose footprint reaches a camera puts geometry inside the lens
foot = max(known[k].approx_size_m[0], known[k].approx_size_m[2])
need = max(CAMERA_CLEAR_FLOOR_M, foot / 2 + p.spread_m / 2 + CAMERA_CLEAR_M)
base = known[to_snake(p.support)].approx_size_m[1] if to_snake(p.support) in known else 0.0
top = base + known[k].approx_size_m[1]
for cam in plan.cameras:
if cam.position[1] > top + CAMERA_CLEAR_M:
- # the check is 2D by design (clusters stand on the floor), so an aerial /
- # establishing camera must escape it vertically: a lens this far above the
- # cluster's top cannot be inside it, and rejecting every large placement
- # under a high camera dropped the whole zone's layout (review of PR #3)
+ # the check is 2D; a lens well above the cluster's top cannot be inside it
continue
dist = math.hypot(x - cam.position[0], z - cam.position[2])
if dist < need:
@@ -118,20 +90,13 @@ def validate_layout(layout: ZoneLayout, zone: ZonePlan, plan: ScenePlan) -> str:
def ground_point(xz: tuple[float, float], language: Language | str) -> tuple[float, float]:
- """A layout's ground point — ``(x, z)`` in the plan's Y-up frame — as the two horizontal
- coordinates an author of ``language`` places with: the same pair for a Y-up language, ``(x, y)``
- with ``y = -z`` for a Z-up one (``conventions.to_authoring_frame``; D12: the plan stays Y-up,
- only what the author reads is converted)."""
v = to_authoring_frame((xz[0], 0.0, xz[1]), str(language))
x, y = (v[0], v[1]) if authoring_frame(str(language)) is Frame.Z_UP_NEG_Y_FRONT else (v[0], v[2])
- # ``+ 0.0`` folds the ``-0.0`` a negated zero leaves (z = 0 is the director's default cluster line;
- # the brief would print ``(3.0, -0.0)``) — the fold ``tracks.scene.plan_vec`` uses
+ # ``+ 0.0`` folds ``-0.0`` so the brief never prints ``(3.0, -0.0)``
return (x + 0.0, y + 0.0)
def layout_block(layout: ZoneLayout | dict[str, Any] | None, *, language: Language | str = Language.SCENE_THREEJS) -> str:
- """The prompt table a zone builder realises (`""` when there is no layout), its points in the
- authoring frame of ``language`` (scene_threejs's reads the layout's own numbers)."""
if layout is None:
return ""
lay = layout if isinstance(layout, ZoneLayout) else ZoneLayout.model_validate(layout)
@@ -168,10 +133,7 @@ def _one_layout(zone: ZonePlan, plan: ScenePlan, model: Any, budget: Any, events
f"{zone.description}\nContents to place: {', '.join(zone.contents) or '(none)'}")
complaint = ""
for attempt in (0, 1):
- # the run clock outranks the layout (review-3 S3): past the hard ceiling the
- # documented degraded mode is "no layout for this zone", and a call that does
- # go out gets the wall clock actually left, never a flat 300 s — the re-ask
- # preflights again, so it cannot buy a second window past the ceiling
+ # past the hard ceiling the layout is skipped; a call that goes out gets the wall clock left
try:
max_wait_s = _deadline_preflight(budget, LAYOUT_WAIT_S, soft=True, floor_s=20.0)
except BudgetExceeded as e:
@@ -196,8 +158,7 @@ def _one_layout(zone: ZonePlan, plan: ScenePlan, model: Any, budget: Any, events
def layout_zones(plan: ScenePlan, model: Any, *, budget: Any = None, events: Any = None,
max_workers: int = 6) -> dict[str, ZoneLayout]:
- """One validated layout per zone, computed in parallel. Failures drop out silently
- (an exception or double rejection yields no layout for that zone, never a dead run)."""
+ """One validated layout per zone, computed in parallel."""
events = NULL_EVENTS if events is None else events
results = fan_out(list(plan.zones), lambda z: _one_layout(z, plan, model, budget, events), max_workers=max_workers, label="layouts",
diff --git a/harness/codeverse3d/workspace.py b/harness/codeverse3d/workspace.py
index b52305e3..a95350c5 100644
--- a/harness/codeverse3d/workspace.py
+++ b/harness/codeverse3d/workspace.py
@@ -1,9 +1,7 @@
"""Run workspace: fixed directory layout + git snapshots of ``src/``.
-A workspace is a directory under ``runs/<slug>/`` (see docs/ARCHITECTURE.md §3).
-``src/`` (and ``public/``) is a git repository so every round is a commit:
-diffs, rollback and "files changed by the agent" come for free and the
-flywheel can replay any round.
+A workspace is a directory under ``runs/<slug>/``; ``src/`` (and ``public/``) is a git
+repository so every round is a commit (diffs, rollback, "files changed by the agent").
"""
from __future__ import annotations
@@ -24,10 +22,10 @@ from pydantic import BaseModel
from codeverse3d.contracts.agent import FileChange
from codeverse3d.proc import write_json_atomic
-#: the top-level buckets of a run directory ; ``artifacts/`` is the evidence
+#: top-level buckets of a run directory
DELIVERABLE_DIR = "deliverable" # (a) what the user asked for
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``)
+#: harness-owned read-only files inside the workspace
C3D_DIR = ".3dcode"
#: directories every run owns
@@ -43,32 +41,24 @@ _GITIGNORE_LINES = (
)
-#: prepended to every git argv run against a run workspace: an agent-planted hook or
-#: fsmonitor never runs, and the GLOBAL attributes file cannot name a driver either.
-#: ``-c`` outranks ``.git/config``, so these hold even in a repository the agent has
-#: written to. ``diff.external`` is deliberately NOT here: ``-c diff.external=`` sets
-#: it to the empty string, which git tries to EXECUTE (``fatal: external diff died``) on
-#: any diff that forgets ``GIT_SAFE_DIFF_FLAGS`` — and ``--no-ext-diff`` there is what
-#: neutralises a planted driver in the first place.
+#: prepended to every git argv run against a run workspace: an agent-planted hook, fsmonitor or
+#: global attributes file never runs. ``-c`` outranks ``.git/config``. ``diff.external`` is
+#: deliberately not set here: an empty value makes git try to execute it.
GIT_SAFE_FLAGS = ("-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false",
"-c", "core.attributesFile=/dev/null")
-#: added to every git command that RENDERS file content (diff / show / log -p). A
-#: NAMED driver — ``.gitattributes`` "*.bin diff=x" plus ``[diff "x"] textconv``/``command``
-#: in .git/config, both agent-writable — is not reachable by ``-c``, and ``--no-ext-diff``
-#: alone does not disable textconv: without ``--no-textconv`` that driver EXECUTES.
+#: added to every git command that renders file content: a named diff / textconv driver in the
+#: agent-writable .git/config is not reachable by ``-c`` and would execute without these.
GIT_SAFE_DIFF_FLAGS = ("--no-ext-diff", "--no-textconv")
-#: a has_commit probe that has not answered by then answers no (record/git_history.py reads use 60 s too)
+#: a has_commit probe that has not answered by then answers no
HAS_COMMIT_TIMEOUT_S = 60
-#: local (.git/config) config that makes git EXECUTE a program. ``-c`` cannot override a
-#: local ``filter.*`` / ``diff.*`` driver, so these are unset in place before every commit.
+#: local (.git/config) keys that make git EXECUTE a program; unset in place before every commit.
_GIT_EXEC_SECTIONS = ("filter", "diff", "alias", "gpg", "credential")
_GIT_EXEC_KEYS = ("core.hookspath", "core.fsmonitor", "core.sshcommand", "core.pager", "commit.gpgsign")
def _git_home() -> str:
- """HOME for workspace git: harness-owned, never the workspace (whose agent-written
- ``.gitconfig`` git reads as its GLOBAL config). The cache_dir DEFAULT, spelled out:
- workspace.py may not import config (tests/install/test_import_direction)."""
+ """HOME for workspace git: harness-owned, never the workspace. The cache_dir default, spelled
+ out because this module may not import config."""
d = Path.home() / ".cache" / "codeverse3d" / "githome"
with contextlib.suppress(OSError): # a missing HOME is harmless; an unwritable one must not sink git
d.mkdir(parents=True, exist_ok=True)
@@ -76,27 +66,15 @@ def _git_home() -> str:
def git_safe_env(**extra: str) -> dict[str, str]:
- """Environment for git in an agent-writable repository: no system or global config
- (``.gitconfig`` written into the workspace is git's GLOBAL config when HOME is the
- workspace), a fixed PATH, and no credential prompt. ``extra`` adds identity."""
+ """Environment for git in an agent-writable repository: no system / global config, fixed PATH,
+ no credential prompt. ``extra`` adds identity."""
return {"PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": _git_home(),
"GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1",
"GIT_TERMINAL_PROMPT": "0", **extra}
class WorkspaceGitError(subprocess.CalledProcessError):
- """A git command in a run workspace failed, carrying git's own explanation.
-
- Subclasses CalledProcessError so existing ``except subprocess.CalledProcessError``
- handlers keep working. The reason it exists: CalledProcessError.__str__ drops
- stderr, and codeverse3d/cli/main.py reports failures as
- "run failed: {type(e).__name__}: {e}" — so a stale ``.git/index.lock`` surfaced as
- the bare line "Command '['git', 'add', '-A']' returned non-zero exit status 128"
- while git's own "fatal: Unable to create ... index.lock: File exists" sat unread in
- e.stderr. The 4-try/1.2 s retry loop above is built for a LIVE holder and can never
- clear a stale lock, so every subsequent ``3dcode resume <slug>`` repeated the same
- opaque failure with no clue and no named remedy.
- """
+ """A failed git command that keeps git's own stderr in its message."""
def __init__(self, root: Path, args: tuple[str, ...], returncode: int, stderr: str):
super().__init__(returncode, ["git", *args], None, stderr)
@@ -114,35 +92,16 @@ class WorkspaceGitError(subprocess.CalledProcessError):
class Workspace:
- """Paths + snapshot helpers for one run. Cheap to construct; no I/O until used."""
-
def __init__(self, root: Path | str):
self.root = Path(root).resolve()
self._cfg_mtime: int = -1 # .git/config mtime at the last _sanitise_git_config
# ----------------------------------------------------------------- paths
def rebase(self, stored: str | Path) -> Path:
- """A path out of ``record.json`` / ``run_state.json``, resolved against THIS
- workspace wherever it was written.
-
- The records store ABSOLUTE host paths (29 per run: rounds[].renders[].path,
- contact_sheet, build.glb_path, build.extra_paths, census exports, and
- run_state.stages[].result_path), so archiving, moving or rsyncing a run silently
- broke every consumer that trusted them — `3dcode show` printed a contact sheet at
- the old location that did not exist, while the real one sat under the new root.
- object.glb kept working because it is recomputed from the workspace, which made
- the breakage partial and therefore silent.
-
- Relative paths join the root (what the old ``_judge.resolve_paths`` did, and the
- only case it handled). An absolute path under another root is re-rooted FIRST,
- by its longest trailing segment that exists under this root — for a moved run the
- tail is intact even though the prefix is not, and for a COPIED/rsynced run this
- workspace's own file must win even while the original still exists (readers used
- to read, and a retexture to write past, the original's files until that directory
- was deleted). A path already under this root, or with no local tail match, is
- returned as-is — an existing original still resolves, and a missing one is
- reported as a real missing file rather than a silently wrong one.
- """
+ """A stored (possibly foreign absolute) path resolved against THIS workspace.
+
+ Relative paths join the root; an absolute path outside it is re-rooted by its longest
+ trailing segment that exists here, else returned as-is."""
p = Path(stored)
if not p.is_absolute():
return self.root / p
@@ -172,12 +131,10 @@ class Workspace:
@property
def deliverable(self) -> Path:
- """(a) the hand-over folder: one round's code + artifact + sheet + captions (``3dcode pick``)."""
return self.root / DELIVERABLE_DIR
@property
def telemetry(self) -> Path:
- """(c) cost ledger, per-call usage rows, resolved settings, stages, trajectories."""
return self.root / TELEMETRY_DIR
@property
@@ -200,7 +157,6 @@ class Workspace:
return self.artifacts / "renders" / f"r{round_index:02d}"
def rendered_rounds(self) -> list[int]:
- """The rounds that have a :meth:`renders_dir`, ascending."""
return sorted(int(p.name[1:]) for p in (self.artifacts / "renders").glob("r[0-9][0-9]") if p.is_dir())
def gates_dir(self, round_index: int) -> Path:
@@ -210,8 +166,6 @@ class Workspace:
return self.artifacts / "judge" / f"r{round_index:02d}{suffix}.json"
def round_artifacts(self, round_index: int) -> Path:
- """``artifacts/rNN/`` — the round's own copy of the build outputs a hand-over needs
- (``codeverse3d.record.deliverable.keep_round_artifacts``)."""
return self.artifacts / f"r{round_index:02d}"
def trajectory_dir(self, stage: str, round_index: int) -> Path:
@@ -246,7 +200,6 @@ class Workspace:
return self
def ensure_layout(self) -> None:
- """Create the directory buckets. Idempotent."""
for d in LAYOUT_DIRS:
(self.root / d).mkdir(parents=True, exist_ok=True)
@@ -255,17 +208,12 @@ class Workspace:
# ----------------------------------------------------------------- json io
def write_json(self, path: Path, model: BaseModel | dict[str, Any]) -> None:
- """Atomic JSON write (tmp + rename, via :func:`codeverse3d.proc.write_json_atomic`)."""
data = model.model_dump(mode="json") if isinstance(model, BaseModel) else model
write_json_atomic(path, data)
# ----------------------------------------------------------------- artifact staging
def stage_artifacts(self, *names: str) -> ArtifactStage:
- """An :class:`ArtifactStage` over canonical ``artifacts/`` names.
-
- Use as a context manager for the full stage-then-promote lifecycle, or
- call ``.invalidate()`` on the returned stage for a bare wipe of the
- canonical names (a bare wipe, no staging)."""
+ """An :class:`ArtifactStage` over canonical ``artifacts/`` names (context manager, or a bare ``.invalidate()``)."""
return ArtifactStage(self, names)
def read_json(self, path: Path) -> dict[str, Any]:
@@ -277,8 +225,6 @@ class Workspace:
@property
def _lock(self) -> threading.RLock:
- """One in-process lock per workspace root: parallel agent/tool threads
- must not race on .git/index."""
key = str(self.root)
with Workspace._LOCKS_GUARD:
return Workspace._LOCKS.setdefault(key, threading.RLock())
@@ -300,8 +246,6 @@ class Workspace:
return proc
def _sanitise_git_config(self) -> None:
- """Unset the exec-capable keys an agent may have written into ``.git/config``.
- Cached on the file's mtime, so the common path costs one stat."""
cfg = self.root / ".git" / "config"
mtime = cfg.stat().st_mtime_ns if cfg.is_file() else 0
if mtime == self._cfg_mtime:
@@ -322,9 +266,6 @@ class Workspace:
self._git("commit", "-q", "-m", "init", "--allow-empty")
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."""
path = self.root / ".gitignore"
existing = path.read_text().splitlines() if path.is_file() else []
have = {line.strip() for line in existing}
@@ -336,11 +277,6 @@ class Workspace:
return True
def commit(self, message: str) -> str:
- """Commit everything tracked (src/, public/, plan, ...) and return the sha.
-
- ONE transaction: ``_git`` locks per command, so a sibling thread that committed
- between the commit and the ``rev-parse`` made this return ITS sha — the round
- journal then named a commit this task never made (repro'd 2026-08-27)."""
with self._lock:
self._sanitise_git_config()
self._git("add", "-A")
@@ -351,9 +287,6 @@ class Workspace:
return self._git("rev-parse", "HEAD").stdout.strip()
def has_commit(self, commit: str) -> bool:
- """Does this repo actually have ``commit``? A round journal can name a commit
- the crash never wrote (``tracks/lifecycle.reconcile_resume`` drops such rounds).
- A read that cannot answer — no git binary, no repo dir, a hung git — is a no."""
if not commit:
return False
try:
@@ -363,7 +296,6 @@ class Workspace:
return False
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 + the diff are one unit: a sibling commit between them mislabels a status
self._sanitise_git_config() # `add` applies clean filters; -c cannot unset a local one
self._git("add", "-A", "-N") # register untracked so they show up in diff
@@ -377,7 +309,6 @@ class Workspace:
return changes
def restore(self, commit: str) -> None:
- """Make src/ + public/ exactly match ``commit`` (artifacts untouched)."""
with self._lock: # rm + rmtree + checkout + add: a sibling must never see the half-removed tree
tracked = self._git("ls-tree", "--name-only", commit).stdout.split()
roots = [r for r in ("src", "public") if r in tracked]
@@ -393,12 +324,6 @@ class Workspace:
self._git("add", "-A")
def restore_paths(self, commit: str, paths: Sequence[str]) -> None:
- """Make just ``paths`` match ``commit`` (worktree + index; everything else untouched).
-
- Used by the CLI post-hoc write-scope check (``agents/cli_common.finish_session``):
- an ``edit_only`` session's out-of-scope writes are rolled back to the session's own
- ``pre:`` commit without disturbing its in-scope work. Every path must exist in
- ``commit`` — the caller passes only modified/deleted paths, which by definition did."""
if not paths:
return
self._git("checkout", "-q", commit, "--", *paths)
@@ -407,36 +332,12 @@ class Workspace:
class ArtifactStage:
"""Stage-then-promote lifecycle for a fixed set of canonical ``artifacts/`` names.
- The invariant this enforces: a canonical artifact exists on disk ONLY when the
- build/pass that owns it finished with that artifact as its result. Before this,
- every runtime's early return (missing entry file, lint error, wrapper crash)
- left the *previous* round's ``object.glb`` / ``build.json`` looking current, and
- every downstream consumer (measure/render tools, deliverable packaging, the
- gallery) trusted bare existence.
-
- Lifecycle (``with ws.stage_artifacts("build.json", "object.glb") as stage:``):
-
- * ``__enter__`` **invalidates** the canonical names immediately — before any
- early return can leak — and claims a private staging directory under
- ``artifacts/.staging/<pid>-<nonce>/``;
- * ``path(name)`` is the staging location to write ``name`` to (wrappers taking
- an ``--out`` directory can be pointed at ``staging_dir`` directly);
- * ``promote(*names)`` publishes staged entries into ``artifacts/`` —
- ``os.replace`` per file (atomic: staging lives on the same filesystem);
- * exit without promote **discards** the staging directory — canonical stays absent.
-
- ``invalidate()`` also works standalone (no ``with``) as the one-call
- replacement for wiping the canonical names by hand with ``shutil.rmtree``.
-
- Directory promotion (``meshes/``) is NOT atomic: the old dir is renamed away
- (parked inside the staging dir), the new one renamed in, then the parked copy
- is removed. A reader can observe the name missing between the two renames, and
- a SIGKILL between them leaves the old copy parked under ``artifacts/.staging/``
- — inert, because every consumer reads canonical paths only, and the next stage
- of the same names starts by invalidating them. Concurrent stages over the same
- names (the scene track fans agents over one workspace) each use a private
- staging dir; promotion follows the ``write_json_atomic`` precedent: last writer
- to rename wins.
+ A canonical artifact exists on disk ONLY when the build that owns it finished with it.
+ ``with ws.stage_artifacts(...)`` invalidates the names on enter and claims a private
+ ``artifacts/.staging/<pid>-<nonce>/``; ``path(name)`` is where to write, ``promote()``
+ publishes (``os.replace`` per file), exit without promote discards. ``invalidate()`` also
+ works standalone. Directory promotion is not atomic (rename old away, new in, drop old);
+ concurrent stages use private staging dirs and the last rename wins.
"""
STAGING_ROOT = ".staging"
@@ -451,7 +352,7 @@ class ArtifactStage:
# ------------------------------------------------------------------ lifecycle
def __enter__(self) -> ArtifactStage:
self.invalidate()
- _ = self.staging_dir # claim it now so wrappers can be pointed at it
+ _ = self.staging_dir
return self
def __exit__(self, *exc: object) -> None:
@@ -459,7 +360,6 @@ class ArtifactStage:
@property
def staging_dir(self) -> Path:
- """The private staging directory (created on first use)."""
if self._dir is None:
d = self._ws.artifacts / self.STAGING_ROOT / f"{os.getpid()}-{os.urandom(4).hex()}"
d.mkdir(parents=True, exist_ok=True)
@@ -467,7 +367,6 @@ class ArtifactStage:
return self._dir
def path(self, name: str) -> Path:
- """Staging location for ``name`` (parent directories created)."""
self._check(name)
p = self.staging_dir / name
p.parent.mkdir(parents=True, exist_ok=True)
@@ -475,7 +374,6 @@ class ArtifactStage:
# ------------------------------------------------------------------ operations
def invalidate(self, *names: str) -> None:
- """Remove the canonical copies of ``names`` (default: every staged name)."""
for name in names or self.names:
self._check(name)
target = self._ws.artifacts / name
@@ -485,12 +383,8 @@ class ArtifactStage:
target.unlink(missing_ok=True)
def promote(self, *names: str) -> list[Path]:
- """Publish staged entries into ``artifacts/`` and return the canonical paths.
-
- With explicit ``names``, every named entry must exist in staging
- (``FileNotFoundError`` otherwise — a build that claims success without its
- outputs is a bug, not a skip). With no arguments, every staged name that
- was actually written is published and the rest are left invalidated."""
+ """Publish staged entries into ``artifacts/``; explicit ``names`` must all exist
+ (``FileNotFoundError``), otherwise every staged name that was written is published."""
chosen = names or self.names
published: list[Path] = []
for name in chosen:
@@ -510,7 +404,6 @@ class ArtifactStage:
return published
def discard(self) -> None:
- """Drop the staging directory (anything not promoted is gone)."""
if self._dir is not None:
shutil.rmtree(self._dir, ignore_errors=True)
with contextlib.suppress(OSError): # tidy the shared .staging parent when empty
@@ -523,8 +416,6 @@ class ArtifactStage:
raise ValueError(f"{name!r} is not staged here (staged: {list(self.names)})")
def _replace_dir(self, src: Path, dest: Path, name: str) -> None:
- """Replace-dir strategy: rename old away (parked in staging), rename new in,
- remove old. See the class docstring for the atomicity limits."""
parked: Path | None = None
if dest.exists():
parked = self.staging_dir / f"{name.replace('/', '_')}.old"