Skip to content

Official Codebase of 3DCodeVerse

Python

local gallery (3dcv gallery serve): multi-battery index with live filters/search/sort, per-run detail pages (rounds, judge verdict, measurements, cost, code), GLB orbit viewer on the vendored three.js, loopback-only read-only server with path-traversal guards; portability pass toward a 3.10 floor; 2614 tests, ruff clean

gaoypengbf9071a1af68
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e7240691..971683fa 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -20,12 +20,21 @@ jobs:
working-directory: harness
tests:
+ # THE TWO ENDS OF THE SUPPORTED RANGE: 3.10 is the floor in pyproject's
+ # requires-python (and ruff's target-version), 3.13 is what the harness is
+ # developed and measured on. Anything in between is covered by both ends
+ # agreeing; anything outside is not supported. The floor job is the one that
+ # catches a 3.11+ stdlib name or a PEP 695 annotation sneaking in (see
+ # codeverse/_compat.py and tests/core/test_portability.py).
+ # Node is not installed on the runner, so the node floor (20.6.0, see
+ # runtime_js/package.json "engines") is only checked by the version logic in
+ # tests/core/test_portability.py — the `node`-marked tests are deselected below.
name: offline tests (py${{ matrix.python-version }})
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
- python-version: ["3.11", "3.13"]
+ python-version: ["3.10", "3.13"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
@@ -36,7 +45,8 @@ jobs:
run: pip install -e ./harness[dev]
# The suite is marked: `live` needs API keys, `blender` needs a Blender
# binary, `node` needs runtime_js/node_modules — none exist on a runner,
- # so CI runs the pure-python subset (locally: 1159 tests, here ~900).
+ # so CI runs the pure-python subset (1809 on 3.10 / 1810 on 3.13 locally;
+ # the whole offline suite is 2413 / 2414).
- name: pytest (pure python subset)
run: python -m pytest tests/core tests/models tests/judges tests/orchestrator_tracks tests/flywheel_cli tests/bench_prompts tests/cost -q -m "not live and not blender and not node"
working-directory: harness
diff --git a/README.md b/README.md
index c2c0ba40..8eab8e44 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,8 @@ The 3dcodeverse project. Top-level layout:
Install with `bash harness/scripts/setup.sh` (idempotent: python deps, the
`runtime_js/` node deps, puppeteer's Chrome, then `3dcodeverse doctor`) —
prerequisites, extras, keys, GPU notes and troubleshooting are in
- `harness/docs/INSTALL.md`.
+ `harness/docs/INSTALL.md`. Needs **python 3.10+** and **node 20.6+** on Linux
+ (developed on 3.13 / node 24; CI runs both ends — `harness/docs/INSTALL.md` §2.1).
- **`finetune/`** — LLM finetuning recipes (LoRA / full-parameter SFT, execution-
and geometry-feedback DPO via unpatched LLaMA-Factory) and the execution-based
diff --git a/harness/CLAUDE.md b/harness/CLAUDE.md
index 2199fab4..e830141b 100644
--- a/harness/CLAUDE.md
+++ b/harness/CLAUDE.md
@@ -27,17 +27,27 @@ calibration) before changing anything.
7. No wrapper re-centres or grounds the object: export **as authored**, warn in the
build, let `check_contract`/`check_connectivity` gate it.
+## Supported versions (what other people can run this on)
+python **3.10+** · node **20.6+** · Blender 4.2+ · Linux x86_64. Developed and
+measured on 3.13 / node 24; CI runs both ends of the python range. The floor is
+load-bearing, not decorative: `pyproject` `requires-python` + ruff `target-version`,
+`codeverse/_compat.py` (the only place allowed to name `StrEnum` / `datetime.UTC` /
+`tomllib`), `spatial/node.py:NODE_MIN` + `runtime_js/package.json` `engines`, all
+pinned together by `tests/core/test_portability.py`. Do not use a 3.11+ stdlib name
+or PEP 695 syntax — that test and the 3.10 CI job will fail. Details: `docs/INSTALL.md` §2.1.
+
## Environment (this machine)
- Gemini keys: `~/.config/astra3d/gemini_keys.env` (22 keys) → `get_settings().gemini_api_keys`
(or `GEMINI_API_KEYS` / `GEMINI_API_KEY` env). Settings: `~/.config/codeverse/config.yaml`
or `./codeverse.yaml`, env prefix `CV3D_` (`CV3D_RENDER__GPU=off`, `CV3D_RUNS_DIR=…`,
`CV3D_DEFAULT_CANDIDATES=2`).
- Blender 5.0.1 headless: `~/.local/bin/blender-5.0` (always `--factory-startup`; clear scene).
-- Node 24 + `runtime_js/node_modules` ([email protected], puppeteer; chrome cached). Headless
+- Node 24 (floor 20.6) + `runtime_js/node_modules` ([email protected], puppeteer; chrome cached). Headless
Chrome WebGL uses the GPU on WSL2 with `--use-angle=gl-egl` + Mesa d3d12 env (see
`runtime_js/gpu_launch.cjs`; `CV3D_RENDER_GPU=on|off|auto`); SwiftShader fallback.
Bare ESM `import 'three'` needs `--import runtime_js/lib/resolve_three.mjs`
- (`spatial.node.run_node(three_hook=True)`) — `NODE_PATH` alone does not work.
+ (`spatial.node.run_node(three_hook=True)`) — `NODE_PATH` alone does not work;
+ that hook is `module.registerHooks` on node ≥ 22.15, `module.register` below.
The `graphics` track renders with moderngl (d3d12 GPU context, llvmpipe fallback).
- CLIs: `gemini` 0.53 (api-key auth + `dynamicModelConfiguration` + `folderTrust.enabled=false`
via the system settings file the harness writes — else it silently substitutes models /
@@ -70,6 +80,7 @@ cd /home/yipeng/3dcodeverse/harness
3dcv cost prices [--stale] · 3dcv cost profiles · 3dcv cost estimate gemini:gemini-3.1-pro-preview --in 12000
3dcv flywheel export runs/ dataset/ [--pack --drop-duplicates --captions-dir d/] · 3dcv flywheel pairs runs/ pairs.jsonl
3dcv flywheel caption <slug> [--out dir] · 3dcv flywheel gallery runs/ gallery.html
+3dcv gallery serve [ROOTS...] [--port 8765] [--reload] · 3dcv gallery build --out gallery.html [--embed]
3dcv bench run bench/prompts/static_objects_v1.yaml --generator ... --judge gemini:gemini-3.1-pro-preview
python -m codeverse.judges.calibration runs/<slug>... --model gemini:gemini-3.1-pro-preview --n 3 --out out/
python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml --arms harness:api-agent:gemini:gemini-3.7-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out bench/out/compare_v1
diff --git a/harness/README.md b/harness/README.md
index 8e7ae2d8..0416ede5 100644
--- a/harness/README.md
+++ b/harness/README.md
@@ -25,6 +25,15 @@ renders, judges, refines, textures and records every run as data-flywheel materi
* **Flywheel:** git-versioned `src/` per round, `record.json`, sample export with
quality tiers + dedupe (+ parquet, tar locators), preference/repair/trajectory
pairs, captions, sqlite index, HTML gallery.
+* **Looking at results:** `3dcv gallery serve` — a local page over `runs/` +
+ `bench/out/*/runs` with filters, a per-filter summary strip and a detail page per run;
+ it serves the run directories too, so every link (sheet, renders, `src/`, `object.glb`
+ in an orbit viewer, `record.json`) actually opens. `3dcv gallery build --embed` writes
+ the same page as one shareable file.
+
+**Supported versions:** python **3.10+** and node **20.6+** (Linux x86_64; Blender
+4.2+ optional). Developed and measured on python 3.13 / node 24 — CI runs both
+ends of that range. See `docs/INSTALL.md` §2.1.
```bash
bash scripts/setup.sh # install everything + run doctor (idempotent; see docs/INSTALL.md)
@@ -36,6 +45,7 @@ pip install -e '.[all,dev]' # entry points: 3dcodeverse, 3dcv
3dcv make "a kitchen cabinet with one door and a drawer" --track articulated_object --language urdf_blender
3dcv make "a small japanese garden at dusk with a koi pond" --track scene --language scene_threejs
3dcv make "neon cyberpunk rain on a window" --track graphics --language glsl_shader
+3dcv gallery serve # browse every run at http://127.0.0.1:8765/ (docs/RUNBOOK.md §4)
python -m pytest tests -q -m "not live"
```
diff --git a/harness/bench/_oneshot.py b/harness/bench/_oneshot.py
index 162246da..d35e0795 100644
--- a/harness/bench/_oneshot.py
+++ b/harness/bench/_oneshot.py
@@ -220,7 +220,7 @@ class ClaudeOneShot:
def codex_default_model() -> str:
"""The model ``codex`` will use when none is passed (``~/.codex/config.toml``), for labelling/pricing."""
try:
- import tomllib
+ from codeverse._compat import tomllib
cfg = tomllib.loads((Path.home() / ".codex" / "config.toml").read_text())
return str(cfg.get("model") or "")
diff --git a/harness/bench/compare_backends.py b/harness/bench/compare_backends.py
index be51bb0c..a5adde58 100644
--- a/harness/bench/compare_backends.py
+++ b/harness/bench/compare_backends.py
@@ -39,12 +39,14 @@ import time
import traceback
from collections.abc import Callable, Sequence
from concurrent.futures import ThreadPoolExecutor, as_completed
-from datetime import UTC, datetime
+from datetime import datetime
from pathlib import Path
from typing import Any, Literal
from pydantic import BaseModel, Field
+from codeverse._compat import UTC
+
REPO = Path(__file__).resolve().parents[1]
if str(REPO) not in sys.path: # `python bench/compare_backends.py` from anywhere
sys.path.insert(0, str(REPO))
diff --git a/harness/bench/run_bench.py b/harness/bench/run_bench.py
index b5a35703..caa25f3b 100644
--- a/harness/bench/run_bench.py
+++ b/harness/bench/run_bench.py
@@ -25,13 +25,14 @@ import time
import traceback
from collections.abc import Callable, Sequence
from concurrent.futures import ThreadPoolExecutor, as_completed
-from datetime import UTC, datetime
+from datetime import datetime
from pathlib import Path
from typing import Any
import yaml
from pydantic import BaseModel, Field
+from codeverse._compat import UTC
from codeverse.config import get_settings
from codeverse.contracts.common import Backends, Budget, Language, Track
from codeverse.contracts.run import RunRecord
diff --git a/harness/codeverse/_compat.py b/harness/codeverse/_compat.py
new file mode 100644
index 00000000..32ebe4cb
--- /dev/null
+++ b/harness/codeverse/_compat.py
@@ -0,0 +1,63 @@
+"""Standard-library shims for the supported python floor (**3.10**).
+
+The harness is developed on 3.13 but must install and run on every interpreter
+in ``requires-python`` (see ``docs/INSTALL.md`` §2.1 "Supported versions"). This
+module is the *only* place that bridges that gap: import the name from here and
+write ordinary code everywhere else — no ``sys.version_info`` branches scattered
+through the package.
+
+Every shim is defined **unconditionally**, i.e. 3.10 and 3.13 execute the same
+objects, so what CI proves on the floor is what runs on the newest interpreter.
+The one exception is :data:`tomllib`, which cannot be emulated and falls back to
+the ``tomli`` backport (a conditional dependency in ``pyproject.toml``).
+
+| shim | replaces | added to the stdlib in | delete this shim when the floor is |
+|---|---|---|---|
+| :class:`StrEnum` | ``enum.StrEnum`` | 3.11 | ≥ 3.11 |
+| :data:`UTC` | ``datetime.UTC`` | 3.11 | ≥ 3.11 |
+| :data:`tomllib` | ``tomllib`` | 3.11 | ≥ 3.11 |
+
+Deleting one is mechanical: raise the floor in ``pyproject.toml``, then
+``from enum import StrEnum`` / ``from datetime import UTC`` / ``import tomllib``
+at the call sites and drop the entry here.
+"""
+
+from __future__ import annotations
+
+from datetime import timezone
+from enum import Enum
+
+__all__ = ["UTC", "StrEnum", "tomllib"]
+
+
+#: ``datetime.UTC``, the 3.11 spelling of the singleton it aliases.
+UTC = timezone.utc
+
+
+class StrEnum(str, Enum):
+ """``enum.StrEnum`` (3.11+) for the 3.10 floor.
+
+ Same observable behaviour as the stdlib class for the way the harness uses
+ it — ``str(x)``/``format(x)``/``"%s"``/``json.dumps`` all give the *value*,
+ ``repr`` stays ``<Cls.NAME: 'value'>``, members are real ``str`` (so they
+ compare, hash, sort and serialise as their value), and ``auto()`` yields the
+ lower-cased member name. Unlike the stdlib class it does not reject
+ non-``str`` member values; every enum here spells its values out as string
+ literals, and mypy/ruff would catch a stray one.
+ """
+
+ # Enum's own __str__/__format__ would print "Cls.NAME"; the stdlib StrEnum
+ # inherits str's instead (via ReprEnum). Bind them explicitly so the
+ # behaviour is the same on 3.10 (mixin rules) and on 3.11+ (ReprEnum rules).
+ __str__ = str.__str__
+ __format__ = str.__format__
+
+ @staticmethod
+ def _generate_next_value_(name: str, start: int, count: int, last_values: list) -> str:
+ return name.lower()
+
+
+try: # 3.11+
+ import tomllib
+except ModuleNotFoundError: # 3.10 — pyproject pulls the `tomli` backport there
+ import tomli as tomllib # type: ignore[no-redef]
diff --git a/harness/codeverse/cli/doctor.py b/harness/codeverse/cli/doctor.py
index 5a443601..89c56a7b 100644
--- a/harness/codeverse/cli/doctor.py
+++ b/harness/codeverse/cli/doctor.py
@@ -63,10 +63,16 @@ def check_blender() -> list[Row]:
def check_node() -> list[Row]:
+ from codeverse.spatial.node import NODE_MIN_STR, node_version_error, parse_node_version
+
s = get_settings()
rows: list[Row] = []
okk, v = _ver([s.binaries.node, "--version"])
- rows.append(("node", "OK" if okk else "FAIL", v))
+ too_old = node_version_error(parse_node_version(v)) if okk else ""
+ if too_old:
+ rows.append(("node", "FAIL", f"{v} — too old, need >= {NODE_MIN_STR} (nvm install --lts)"))
+ else:
+ rows.append(("node", "OK" if okk else "FAIL", v if okk else f"{v} (need >= {NODE_MIN_STR})"))
rj = s.runtime_js_dir()
three = rj / "node_modules" / "three" / "package.json"
pup = rj / "node_modules" / "puppeteer" / "package.json"
diff --git a/harness/codeverse/cli/flywheel_cmd.py b/harness/codeverse/cli/flywheel_cmd.py
index 27732a34..debb8513 100644
--- a/harness/codeverse/cli/flywheel_cmd.py
+++ b/harness/codeverse/cli/flywheel_cmd.py
@@ -162,9 +162,11 @@ def gallery_cmd(
out_html: Annotated[Path, typer.Argument(help="output .html (self-contained)")],
title: Annotated[str | None, typer.Option("--title")] = None,
thumb_px: Annotated[int, typer.Option("--thumb-px", min=128, help="thumbnail long edge")] = 640,
+ embed: Annotated[bool, typer.Option("--embed/--no-embed", help="inline the contact sheets as data: URIs")] = True,
) -> None:
- """One self-contained HTML page: best sheet, score, cost, prompt, links per run."""
- from codeverse.flywheel.gallery import write_gallery
+ """Alias of `3dcv gallery build` (kept for scripts): one self-contained HTML page."""
+ from codeverse.gallery.static_site import build_static
- path, n = write_gallery(runs_dir, out_html, title=title, thumb_px=thumb_px)
+ path, n, _ = build_static([runs_dir], out_html, title=title, embed=embed, thumb_px=thumb_px)
ok(f"gallery of {n} runs → {path} ({path.stat().st_size // 1024} KB)")
+ console.print("[dim]`3dcv gallery serve` serves the same page with working links[/dim]")
diff --git a/harness/codeverse/cli/gallery_cmd.py b/harness/codeverse/cli/gallery_cmd.py
new file mode 100644
index 00000000..c3c26430
--- /dev/null
+++ b/harness/codeverse/cli/gallery_cmd.py
@@ -0,0 +1,96 @@
+"""``3dcv gallery serve | build`` — look at runs locally.
+
+``serve`` is the one you want day to day: it indexes every run root, serves the
+page on loopback and serves the run directories themselves, so every link on
+every card actually opens (sheet, renders, record.json, src/, GLB, GIFs).
+``build`` writes the same page as a single file for sharing.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Annotated
+
+import typer
+
+from codeverse.cli import _common as C
+from codeverse.cli._fmt import console, kv_table, ok, warn
+
+gallery_app = typer.Typer(no_args_is_help=True)
+
+RootsArg = Annotated[list[Path] | None, typer.Argument(
+ help="run roots (default: ./runs plus every ./bench/out/*/runs that exists)")]
+
+
+def resolve_roots(roots: list[Path] | None) -> list[Path]:
+ """Explicit roots (validated) or the defaults; a clear error when there are none."""
+ from codeverse.gallery.index import default_roots
+
+ if roots:
+ missing = [r for r in roots if not Path(r).is_dir()]
+ if missing:
+ 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())
+ if not found:
+ from codeverse.config import get_settings
+
+ fallback = Path(get_settings().runs_dir)
+ if fallback.is_dir():
+ return [fallback]
+ raise C.CliError(f"no run roots found under {Path.cwd()} (looked for runs/ and bench/out/*/runs); "
+ f"pass one explicitly: `3dcv gallery serve path/to/runs`")
+ return found
+
+
+@gallery_app.command("serve")
+def serve_cmd(
+ roots: RootsArg = None,
+ port: Annotated[int, typer.Option("--port", min=0, max=65535, help="0 = pick a free port")] = 8765,
+ host: Annotated[str | None, typer.Option("--host", help="default 127.0.0.1; any non-loopback address must be "
+ "typed here explicitly")] = None,
+ open_browser: Annotated[bool, typer.Option("--open/--no-open", help="open the page in a browser")] = True,
+ reload: Annotated[bool, typer.Option("--reload", help="re-scan the roots on every page load "
+ "(cheap: records only, images stay lazy)")] = False,
+ title: Annotated[str, typer.Option("--title")] = "3dcv gallery",
+) -> None:
+ """Serve the gallery (and the run directories) on localhost."""
+ from codeverse.gallery.server import GalleryError, serve
+
+ root_paths = resolve_roots(roots)
+
+ def announce(app, url: str) -> None:
+ ix = app.index
+ console.print(kv_table("gallery", {
+ "url": url, "runs": len(ix.entries()), "roots": len(ix.sections),
+ "index built in": f"{ix.build_ms} ms", "reload": reload,
+ "sections": ", ".join(f"{s.label}({len(s.entries)})" for s in ix.sections)}))
+ console.print("[dim]Ctrl-C to stop[/dim]")
+
+ try:
+ serve(root_paths, host=host, host_explicit=host is not None, port=port, reload=reload,
+ open_browser=open_browser, title=title, on_start=announce)
+ except GalleryError as e:
+ raise C.CliError(str(e)) from e
+ ok("gallery stopped")
+
+
+@gallery_app.command("build")
+def build_cmd(
+ roots: RootsArg = None,
+ out: Annotated[Path, typer.Option("--out", help="output .html")] = Path("gallery.html"),
+ embed: Annotated[bool, typer.Option("--embed", help="inline the contact sheets as data: URIs so the page can "
+ "be shared (much bigger; links still point here)")] = False,
+ title: Annotated[str | None, typer.Option("--title")] = None,
+ thumb_px: Annotated[int, typer.Option("--thumb-px", min=128, help="embedded thumbnail long edge")] = 720,
+) -> None:
+ """Write the gallery as one self-contained HTML file."""
+ from codeverse.gallery.static_site import build_static
+
+ path, n, index = build_static(resolve_roots(roots), out, title=title, embed=embed, thumb_px=thumb_px)
+ broken = sum(1 for e in index.entries() if e.state != "ok")
+ if broken:
+ warn(f"{broken} run(s) have no usable record.json (shown as broken cards)")
+ ok(f"gallery of {n} runs → {path} ({path.stat().st_size // 1024} KB)")
+ if not embed:
+ console.print("[dim]file:// links; `--embed` inlines the images, `3dcv gallery serve` makes them clickable[/dim]")
diff --git a/harness/codeverse/cli/main.py b/harness/codeverse/cli/main.py
index bdc6e81e..c68b0d80 100644
--- a/harness/codeverse/cli/main.py
+++ b/harness/codeverse/cli/main.py
@@ -22,6 +22,7 @@ from codeverse.cli.bench_cmd import bench_app
from codeverse.cli.cost_cmd import cost_app
from codeverse.cli.doctor import doctor_app
from codeverse.cli.flywheel_cmd import flywheel_app
+from codeverse.cli.gallery_cmd import gallery_app
from codeverse.cli.texture_cmd import texture_app
from codeverse.cli.tools_cmd import tools
from codeverse.config import get_settings
@@ -31,6 +32,7 @@ from codeverse.contracts.spec import Constraints, ReferenceImage, RunOptions, Sp
app = typer.Typer(name="3dcv", help="3dcodeverse: LLMs write raw 3D code; the harness builds, judges, refines, records.",
pretty_exceptions_enable=False)
app.add_typer(flywheel_app, name="flywheel", help="Dataset export / pairs / captions / index.")
+app.add_typer(gallery_app, name="gallery", help="Look at runs locally: `serve` on localhost, `build` one shareable HTML file.")
app.add_typer(bench_app, name="bench", help="Prompt batteries: run + report.")
app.add_typer(cost_app, name="cost", help="Cost audit: per stage/role/model, waste, $ per passing artifact.")
app.add_typer(doctor_app, name="doctor", help="Environment checks.")
@@ -240,7 +242,9 @@ def _print_candidates(ws) -> None:
def _event_time(ev: dict) -> str:
- from datetime import UTC, datetime
+ from datetime import datetime
+
+ from codeverse._compat import UTC
try:
return datetime.fromtimestamp(float(ev["t"]), UTC).strftime("%H:%M:%S")
diff --git a/harness/codeverse/contracts/artifacts.py b/harness/codeverse/contracts/artifacts.py
index 5fa6b5b9..509cfcfd 100644
--- a/harness/codeverse/contracts/artifacts.py
+++ b/harness/codeverse/contracts/artifacts.py
@@ -2,11 +2,11 @@
from __future__ import annotations
-from enum import StrEnum
from typing import Any
from pydantic import BaseModel, Field
+from codeverse._compat import StrEnum
from codeverse.contracts.common import Vec3
diff --git a/harness/codeverse/contracts/common.py b/harness/codeverse/contracts/common.py
index 86258f22..8fb13aba 100644
--- a/harness/codeverse/contracts/common.py
+++ b/harness/codeverse/contracts/common.py
@@ -2,11 +2,12 @@
from __future__ import annotations
-from enum import StrEnum
from typing import Annotated
from pydantic import BaseModel, ConfigDict, Field
+from codeverse._compat import StrEnum
+
Vec3 = Annotated[tuple[float, float, float], Field(description="x, y, z")]
diff --git a/harness/codeverse/contracts/run.py b/harness/codeverse/contracts/run.py
index 4cef3a4a..0b2540a7 100644
--- a/harness/codeverse/contracts/run.py
+++ b/harness/codeverse/contracts/run.py
@@ -2,12 +2,12 @@
from __future__ import annotations
-from datetime import UTC, datetime
-from enum import StrEnum
+from datetime import datetime
from typing import Any
from pydantic import BaseModel, Field
+from codeverse._compat import UTC, StrEnum
from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, RenderSet
from codeverse.contracts.common import Usage
from codeverse.contracts.judgment import Judgment
diff --git a/harness/codeverse/contracts/spec.py b/harness/codeverse/contracts/spec.py
index d5281a3d..4908bebd 100644
--- a/harness/codeverse/contracts/spec.py
+++ b/harness/codeverse/contracts/spec.py
@@ -2,10 +2,11 @@
from __future__ import annotations
-from datetime import UTC, datetime
+from datetime import datetime
from pydantic import BaseModel, Field, model_validator
+from codeverse._compat import UTC
from codeverse.contracts.common import TRACK_LANGUAGES, Backends, Budget, Language, Track
diff --git a/harness/codeverse/conventions.py b/harness/codeverse/conventions.py
index f1258c3c..fd1c0531 100644
--- a/harness/codeverse/conventions.py
+++ b/harness/codeverse/conventions.py
@@ -22,7 +22,8 @@ from __future__ import annotations
import re
from dataclasses import dataclass
-from enum import StrEnum
+
+from codeverse._compat import StrEnum
UNITS = "meters"
diff --git a/harness/codeverse/cost/types.py b/harness/codeverse/cost/types.py
index bb4dd2fc..c3f5982d 100644
--- a/harness/codeverse/cost/types.py
+++ b/harness/codeverse/cost/types.py
@@ -10,10 +10,9 @@ leaf so any caller (track, judge, texturing, bench script) can use it.
from __future__ import annotations
-from enum import StrEnum
-
from pydantic import BaseModel, ConfigDict, Field
+from codeverse._compat import StrEnum
from codeverse.contracts.common import Usage
diff --git a/harness/codeverse/flywheel/captions.py b/harness/codeverse/flywheel/captions.py
index f65235ae..39755fa9 100644
--- a/harness/codeverse/flywheel/captions.py
+++ b/harness/codeverse/flywheel/captions.py
@@ -17,11 +17,12 @@ from __future__ import annotations
import json
import re
-from datetime import UTC, datetime
+from datetime import datetime
from pathlib import Path
from pydantic import BaseModel, Field
+from codeverse._compat import UTC
from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart
from codeverse.contracts.common import ENTRY_FILE, Language, Track
from codeverse.contracts.run import RunRecord
diff --git a/harness/codeverse/flywheel/deliverable.py b/harness/codeverse/flywheel/deliverable.py
index d6f5a3cc..6f9dd79c 100644
--- a/harness/codeverse/flywheel/deliverable.py
+++ b/harness/codeverse/flywheel/deliverable.py
@@ -23,9 +23,10 @@ import json
import logging
import os
import shutil
-from datetime import UTC, datetime
+from datetime import datetime
from pathlib import Path
+from codeverse._compat import UTC
from codeverse.contracts.common import ENTRY_FILE, Language
from codeverse.contracts.run import DeliverableFile, RoundRecord, RunDeliverable, RunRecord
from codeverse.flywheel import _git
diff --git a/harness/codeverse/flywheel/record.py b/harness/codeverse/flywheel/record.py
index f7a43ce5..139c74bf 100644
--- a/harness/codeverse/flywheel/record.py
+++ b/harness/codeverse/flywheel/record.py
@@ -16,12 +16,13 @@ import logging
import platform
import subprocess
from collections.abc import Callable, Iterator
-from datetime import UTC, datetime
+from datetime import datetime
from functools import lru_cache
from pathlib import Path
from typing import Any
from codeverse import __version__
+from codeverse._compat import UTC
from codeverse.config import get_settings
from codeverse.contracts.common import Usage
from codeverse.contracts.run import RoundRecord, RunRecord
diff --git a/harness/codeverse/gallery/__init__.py b/harness/codeverse/gallery/__init__.py
new file mode 100644
index 00000000..54d85b3e
--- /dev/null
+++ b/harness/codeverse/gallery/__init__.py
@@ -0,0 +1,29 @@
+"""The local run gallery: ``3dcv gallery serve`` (localhost) and ``3dcv gallery build`` (one file).
+
+* ``index`` ``build_index(roots)`` · ``default_roots()`` — record.json → typed entries
+* ``model`` ``RunEntry`` / ``RootSection`` / ``GalleryIndex`` / ``summarize`` / ``match``
+* ``page`` the index page (summary strip, filters, cards + table)
+* ``detail`` ``/run/<battery>/<slug>`` — rounds, judge, measurement, renders, cost, code
+* ``code`` directory listings + the file viewer
+* ``viewer`` optional GLB viewer on the vendored three.js (no CDN)
+* ``server`` ``GalleryApp.route`` + ``serve(...)`` — loopback-only unless --host is typed
+* ``static_site`` ``build_static(roots, out.html, embed=…)``
+"""
+
+from codeverse.gallery.index import build_index, default_roots
+from codeverse.gallery.model import GalleryIndex, RootSection, RunEntry, Summary, summarize
+from codeverse.gallery.server import (
+ DEFAULT_HOST,
+ DEFAULT_PORT,
+ GalleryApp,
+ GalleryError,
+ resolve_host,
+ serve,
+)
+from codeverse.gallery.static_site import build_static, render_static
+
+__all__ = [
+ "DEFAULT_HOST", "DEFAULT_PORT", "GalleryApp", "GalleryError", "GalleryIndex", "RootSection",
+ "RunEntry", "Summary", "build_index", "build_static", "default_roots", "render_static",
+ "resolve_host", "serve", "summarize",
+]
diff --git a/harness/codeverse/gallery/cards.py b/harness/codeverse/gallery/cards.py
new file mode 100644
index 00000000..04dc2701
--- /dev/null
+++ b/harness/codeverse/gallery/cards.py
@@ -0,0 +1,180 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+from codeverse.gallery.labels import VERDICT_META, humanize_view
+from codeverse.gallery.model import RunEntry, RunLink
+from codeverse.gallery.theme import esc
+from codeverse.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", "textured glb", "preview.gif", "articulation", "src/")
+
+
+def fmt(value: float | None, digits: int = 3, dash: str = "—") -> str:
+ return dash if value is None else format(value, f".{digits}f")
+
+
+def tier_tag(entry: RunEntry) -> str:
+ return f"<span class='tag tier {esc(entry.tier)}' title='quality tier {esc(entry.tier)}'>{esc(entry.tier)}</span>"
+
+
+def verdict_tag(entry: RunEntry) -> str:
+ label, cls, why = VERDICT_META[entry.verdict]
+ return f"<span class='tag {cls}' title='{esc(why)}'>{esc(label)}</span>"
+
+
+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 ""
+ items = "".join(f"<a href='{esc(urls.link(entry, ln))}'>{esc(ln.label)}</a>" for ln in rest)
+ return ("<details class='menu'><summary title='every other artifact of this run'"
+ f" aria-label='more links'>⋮</summary><div class='pop'>{items}</div></details>")
+
+
+def _primary(entry: RunEntry) -> RunLink | None:
+ by_label = {ln.label: ln for ln in entry.links}
+ return next((by_label[name] for name in PRIMARY_LINKS if name in by_label), None)
+
+
+def card_actions(entry: RunEntry, urls: UrlMaker) -> str:
+ shown = {"detail"}
+ parts = []
+ if urls.has_detail:
+ parts.append(f"<a class='go' href='{esc(urls.detail(entry))}'>detail →</a>")
+ primary = _primary(entry)
+ 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
+ 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>"
+ label = entry.hero_label or "contact sheet"
+ alt = f"{label} — {entry.slug}"
+ inner = (f"<a href='{esc(urls.detail(entry) if urls.has_detail else urls.file(entry, image))}'>"
+ f"<img loading='lazy' decoding='async' src='{esc(urls.img(entry, image))}' "
+ f"alt='{esc(alt)}'></a><span class='viewtag'>{esc(label)}</span>")
+ if entry.sheet and entry.hero and entry.n_views > 1:
+ inner += (f"<details class='views'><summary title='all {entry.n_views} views'>"
+ f"⊞ {entry.n_views}</summary>"
+ f"<img class='sheetover' loading='lazy' decoding='async' "
+ f"src='{esc(urls.img(entry, entry.sheet))}' alt='all views — {esc(entry.slug)}'>"
+ f"</details>")
+ return f"<div class='shot'>{inner}</div>"
+
+
+def select_box(entry: RunEntry) -> str:
+ return (f"<label class='pick' title='select for compare / export'>"
+ f"<input type='checkbox' class='sel' data-key='{esc(entry.key)}'"
+ f" aria-label='select {esc(entry.slug)}'></label>")
+
+
+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)}"
+ f"<a class='name' href='{esc(urls.detail(entry))}' title='{esc(entry.slug)}'>{esc(name)}</a>"
+ f"<span class='score num' title='best score'>{fmt(entry.score)}</span></div>")
+ prompt = (f"<p class='prompt' title='{esc(entry.prompt)}'>{esc(entry.prompt)}</p>"
+ if entry.prompt else "")
+ if entry.state != "ok":
+ return (f"<article class='card broken v-err{hide}' data-run='{esc(entry.key)}'"
+ f" data-verdict='error'>{select_box(entry)}<div class='body'>{head}"
+ f"<div class='err'>{esc(entry.state)}: {esc(entry.error)}</div>{prompt}"
+ f"{card_actions(entry, urls)}</div></article>")
+ tags = "".join(f"<span class='tag'>{esc(t)}</span>"
+ for t in (entry.track, entry.language, entry.generator) if t)
+ delta = ""
+ if entry.baseline_score is not None and entry.score is not None:
+ cls = "up" if entry.score >= entry.baseline_score else "down"
+ delta = f" <span class='{cls}'>{entry.score - entry.baseline_score:+.3f}</span>"
+ best = f"r{entry.best_round}" if entry.best_round is not None else "r–"
+ facts2 = (f"<span>{fmt(entry.baseline_score)} → <b>{fmt(entry.score)}</b>{delta}</span>"
+ f"<span>{best}/{entry.rounds}</span>"
+ f"<span>${entry.cost_usd:.2f}</span>"
+ + (f"<span>{entry.minutes:.0f} min</span>" if entry.minutes is not None else ""))
+ 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>")
+ # the run status only earns a chip when it says something the verdict does not
+ # ("passed" next to a green `passed` pill is noise; "plateau"/"budget"/"failed" is not)
+ redundant = not entry.status or (entry.passed and entry.status == "passed")
+ status = "" if redundant else f"<span class='tag'>{esc(entry.status)}</span>"
+ caption = f"<p class='xs faint clamp1'>{esc(entry.caption)}</p>" if entry.caption else ""
+ err = f"<div class='err'>{esc(entry.error[:300])}</div>" if entry.error else ""
+ return (
+ f"<article class='card {VERDICT_META[entry.verdict][1]}{hide}' data-run='{esc(entry.key)}'"
+ f" data-verdict='{esc(entry.verdict)}'>{select_box(entry)}{card_shot(entry, urls)}"
+ f"<div class='body'>{head}{prompt}{caption}"
+ f"<div class='facts'>{verdict_tag(entry)}{gates}{status}</div>"
+ f"<div class='facts small num'>{facts2}</div>"
+ f"<div class='facts tags'>{tags}</div>"
+ f"{err}{card_actions(entry, urls)}</div></article>"
+ )
+
+
+TABLE_HEAD = ("<tr><th class='pickcol'><span class='sr'>select</span></th><th class='thumbcol'></th>"
+ "<th>run</th><th>verdict</th><th>track</th><th>lang</th><th>backend</th><th>tier</th>"
+ "<th class='n'>base</th><th class='n'>best</th><th class='n'>Δ</th><th class='n'>gates</th>"
+ "<th class='n'>$</th><th class='n'>min</th><th class='n'>sec</th><th>links</th></tr>")
+
+
+def render_row(entry: RunEntry, urls: UrlMaker, *, hidden: bool = False) -> str:
+ delta = (entry.score - entry.baseline_score
+ if entry.score is not None and entry.baseline_score is not None else None)
+ links = " ".join(f"<a href='{esc(urls.link(entry, link))}'>{esc(link.label)}</a>"
+ for link in entry.links if link.label in ("workspace", "src/", "sheet", "glb"))
+ image = entry.card_image
+ thumb = (f"<a href='{esc(urls.detail(entry))}'><img class='rowthumb' loading='lazy' decoding='async'"
+ f" src='{esc(urls.img(entry, image))}' alt=''></a>" if image else "")
+ seconds = "—" if entry.minutes is None else f"{entry.minutes * 60:.0f}"
+ return (
+ f"<tr class='{'is-hidden ' if hidden else ''}{VERDICT_META[entry.verdict][1]}'"
+ f" data-run='{esc(entry.key)}' data-verdict='{esc(entry.verdict)}'>"
+ f"<td class='pickcol'>{select_box(entry)}</td><td class='thumbcol'>{thumb}</td>"
+ f"<td class='wide'><a href='{esc(urls.detail(entry))}'>{esc(entry.title or entry.slug)}</a>"
+ f"<div class='xs faint'>{esc(entry.slug)}</div></td>"
+ f"<td>{verdict_tag(entry)}</td>"
+ f"<td>{esc(entry.track)}</td><td>{esc(entry.language)}</td><td>{esc(entry.generator)}</td>"
+ f"<td>{tier_tag(entry)}</td>"
+ f"<td class='n'>{fmt(entry.baseline_score)}</td><td class='n'>{fmt(entry.score)}</td>"
+ f"<td class='n'>{'—' if delta is None else format(delta, '+.3f')}</td>"
+ f"<td class='n'>{entry.gate_errors}</td><td class='n'>{entry.cost_usd:.2f}</td>"
+ f"<td class='n'>{fmt(entry.minutes, 1)}</td><td class='n'>{seconds}</td>"
+ f"<td class='rowlinks'>{links}</td></tr>"
+ )
+
+
+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)}'>"
+ f"<img loading='{loading}' decoding='async' src='{esc(src)}' alt='{esc(human)}'>"
+ f"<figcaption>{esc(human)}</figcaption></a></figure>")
diff --git a/harness/codeverse/gallery/code.py b/harness/codeverse/gallery/code.py
new file mode 100644
index 00000000..8910a997
--- /dev/null
+++ b/harness/codeverse/gallery/code.py
@@ -0,0 +1,167 @@
+"""Reading a run's code in the browser: directory listings + a file viewer.
+
+No external JS and no highlighter dependency — the "syntax-highlighted-ish"
+look is one tokeniser over comments / strings / numbers / keywords, applied only
+to the languages the harness actually generates. Everything else is a plain
+``<pre>`` with line numbers, which is what makes this safe to point at any file
+in a run directory.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from codeverse.gallery.model import RunEntry
+from codeverse.gallery.paths import safe_join
+from codeverse.gallery.theme import esc, footer, page_shell, top_bar
+from codeverse.gallery.urls import UrlMaker
+
+MAX_VIEW_BYTES = 512 * 1024
+HIGHLIGHT_SUFFIXES = {".py", ".js", ".mjs", ".cjs", ".frag", ".vert", ".glsl", ".json"}
+TEXT_SUFFIXES = HIGHLIGHT_SUFFIXES | {".md", ".txt", ".urdf", ".xml", ".yaml", ".yml", ".jsonl", ".log",
+ ".cfg", ".ini", ".toml", ".csv", ".html", ".css", ".sh"}
+
+_KEYWORDS = (
+ "def|class|import|from|as|return|yield|pass|raise|try|except|finally|with|lambda|global|nonlocal|assert|del|"
+ "if|elif|else|for|while|break|continue|in|is|not|and|or|None|True|False|self|await|async|"
+ "const|let|var|function|export|default|new|this|typeof|instanceof|extends|super|"
+ "uniform|varying|attribute|precision|highp|mediump|lowp|out|inout|discard|"
+ "void|bool|int|float|double|vec2|vec3|vec4|ivec2|ivec3|mat2|mat3|mat4|sampler2D|samplerCube|struct|null|true|false"
+)
+_TOKENS = re.compile(
+ r"(?P<comment>//[^\n]*|#[^\n]*|/\*.*?\*/)"
+ r"|(?P<str>\"\"\".*?\"\"\"|'''.*?'''|\"(?:\\.|[^\"\\\n])*\"|'(?:\\.|[^'\\\n])*')"
+ r"|(?P<num>\b\d+\.?\d*(?:[eE][-+]?\d+)?\b)"
+ rf"|(?P<kw>\b(?:{_KEYWORDS})\b)",
+ re.S,
+)
+
+CODE_CSS = """
+.code-css .cm{color:var(--fg-3);font-style:italic}
+.code-css .st{color:var(--ok)}
+.code-css .nu{color:var(--warn)}
+.code-css .kw{color:var(--accent);font-weight:600}
+.filelist{list-style:none;margin:0;padding:0}
+.filelist li{display:flex;gap:var(--s-3);padding:5px 0;border-bottom:1px solid var(--line);font-size:var(--fs-sm)}
+.filelist li a{font-family:var(--mono);overflow-wrap:anywhere}
+.filelist .sz{margin-left:auto;color:var(--fg-3);font-variant-numeric:tabular-nums;white-space:nowrap}
+"""
+
+
+def highlight(text: str, *, suffix: str = "") -> str:
+ """Escaped HTML for ``text``; light token colouring for known code suffixes."""
+ if suffix.lower() not in HIGHLIGHT_SUFFIXES:
+ return esc(text)
+ out: list[str] = []
+ pos = 0
+ for m in _TOKENS.finditer(text):
+ out.append(esc(text[pos:m.start()]))
+ cls = {"comment": "cm", "str": "st", "num": "nu", "kw": "kw"}[m.lastgroup or "kw"]
+ out.append(f"<span class='{cls}'>{esc(m.group())}</span>")
+ pos = m.end()
+ out.append(esc(text[pos:]))
+ return "".join(out)
+
+
+def numbered(text: str, *, suffix: str = "") -> str:
+ """``<pre>`` with a line-number gutter (selectable code, unselectable numbers)."""
+ lines = highlight(text, suffix=suffix).split("\n")
+ body = "\n".join(f"<span class='ln'>{i}</span>{line}" for i, line in enumerate(lines, 1))
+ return f"<pre class='code code-css'>{body}</pre>"
+
+
+def is_text(path: Path) -> bool:
+ return path.suffix.lower() in TEXT_SUFFIXES
+
+
+def read_text(path: Path) -> tuple[str, str]:
+ """``(text, note)`` — truncates huge files and never raises for binary content."""
+ try:
+ data = path.read_bytes()
+ except OSError as e:
+ return "", f"unreadable: {e}"
+ note = ""
+ if len(data) > MAX_VIEW_BYTES:
+ data, note = data[:MAX_VIEW_BYTES], f"truncated to {MAX_VIEW_BYTES // 1024} KB of {len(data) // 1024} KB"
+ try:
+ return data.decode("utf-8"), note
+ except UnicodeDecodeError:
+ return data.decode("utf-8", "replace"), (note + "; " if note else "") + "not valid UTF-8 (replaced)"
+
+
+def _crumbs(entry: RunEntry, urls: UrlMaker, rel: str) -> str:
+ parts = ["<a href='/'>gallery</a>", f"<a href='{esc(urls.detail(entry))}'>{esc(entry.slug)}</a>"]
+ walked = ""
+ for piece in [p for p in rel.split("/") if p]:
+ walked = f"{walked}/{piece}" if walked else piece
+ parts.append(f"<a href='{esc(urls.code(entry, walked))}'>{esc(piece)}</a>")
+ return " <span class='faint'>/</span> ".join(parts)
+
+
+def render_dir(entry: RunEntry, urls: UrlMaker, rel: str) -> str:
+ """A directory listing inside a run (``src/``, ``artifacts/frames/`` …)."""
+ target = safe_join(entry.path, rel)
+ if not target.is_dir():
+ raise FileNotFoundError(f"not a directory: {rel}")
+ rows = []
+ for child in sorted(target.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower())):
+ child_rel = f"{rel}/{child.name}".strip("/") if rel else child.name
+ if child.is_dir():
+ rows.append(f"<li><a href='{esc(urls.dir(entry, child_rel))}'>{esc(child.name)}/</a>"
+ f"<span class='sz'>dir</span></li>")
+ else:
+ href = urls.code(entry, child_rel) if is_text(child) else urls.file(entry, child_rel)
+ try:
+ size = child.stat().st_size
+ except OSError:
+ size = 0
+ rows.append(f"<li><a href='{esc(href)}'>{esc(child.name)}</a>"
+ f"<a class='sz' href='{esc(urls.file(entry, child_rel))}'>{size:,} B · raw</a></li>")
+ listing = "".join(rows) or "<li class='faint'>empty</li>"
+ body = (top_bar("3dcv gallery", entry.slug, crumbs=_crumbs(entry, urls, rel))
+ + f"<main class='wrap'><div class='panel'><h2>{esc(rel or '.')}</h2>"
+ f"<ul class='filelist'>{listing}</ul></div></main>"
+ + footer(entry.path))
+ return page_shell(f"{rel or '/'} — {entry.slug}", body, extra_css=CODE_CSS)
+
+
+def render_file(entry: RunEntry, urls: UrlMaker, rel: str) -> str:
+ """One file as a readable page (a directory redirects to the listing)."""
+ target = safe_join(entry.path, rel)
+ if target.is_dir():
+ return render_dir(entry, urls, rel)
+ if not target.is_file():
+ raise FileNotFoundError(f"not a file: {rel}")
+ if not is_text(target):
+ body = (top_bar("3dcv gallery", entry.slug, crumbs=_crumbs(entry, urls, rel))
+ + f"<main class='wrap'><div class='panel'><h2>{esc(rel)}</h2>"
+ f"<p class='muted small'>binary file — "
+ f"<a href='{esc(urls.file(entry, rel))}'>open the raw bytes</a></p></div></main>"
+ + footer(str(target)))
+ return page_shell(f"{rel} — {entry.slug}", body, extra_css=CODE_CSS)
+ text, note = read_text(target)
+ head = (f"<h2>{esc(rel)}</h2><p class='small muted'>{len(text.splitlines())} lines · "
+ f"<a href='{esc(urls.file(entry, rel))}'>raw</a>"
+ + (f" · <span class='pill-warn'>{esc(note)}</span>" if note else "") + "</p>")
+ body = (top_bar("3dcv gallery", entry.slug, crumbs=_crumbs(entry, urls, rel))
+ + f"<main class='wrap'><div class='panel'>{head}{numbered(text, suffix=target.suffix)}</div></main>"
+ + footer(str(target)))
+ return page_shell(f"{rel} — {entry.slug}", body, extra_css=CODE_CSS)
+
+
+def src_files(run_dir: Path | str, limit: int = 200) -> list[tuple[str, int]]:
+ """``(run-relative path, size)`` for every file under ``src/`` (sorted, capped)."""
+ root = Path(run_dir) / "src"
+ if not root.is_dir():
+ return []
+ out: list[tuple[str, int]] = []
+ for p in sorted(root.rglob("*")):
+ if p.is_file() and ".git" not in p.parts and "node_modules" not in p.parts:
+ try:
+ out.append((p.relative_to(run_dir).as_posix(), p.stat().st_size))
+ except OSError:
+ continue
+ if len(out) >= limit:
+ break
+ return out
diff --git a/harness/codeverse/gallery/detail.py b/harness/codeverse/gallery/detail.py
new file mode 100644
index 00000000..4719084c
--- /dev/null
+++ b/harness/codeverse/gallery/detail.py
@@ -0,0 +1,297 @@
+"""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
+best round, 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.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.contracts.common import ENTRY_FILE
+from codeverse.contracts.run import RunRecord
+from codeverse.flywheel.record import effective_judgment
+from codeverse.gallery.code import CODE_CSS, numbered, read_text, src_files
+from codeverse.gallery.index import best_sheet
+from codeverse.gallery.model import RunEntry
+from codeverse.gallery.theme import esc, footer, page_shell, top_bar
+from codeverse.gallery.urls import UrlMaker
+from codeverse.workspace import Workspace
+
+DETAIL_CSS = CODE_CSS + """
+.hero{display:grid;grid-template-columns:minmax(0,1.15fr) minmax(0,1fr);gap:var(--s-4);align-items:start}
+@media (max-width:900px){.hero{grid-template-columns:1fr}}
+.hero .shotbox{background:var(--surface);border:1px solid var(--line);border-radius:var(--r-3);
+ overflow:hidden;box-shadow:var(--shadow)}
+.hero .shotbox img{width:100%;display:block;background:var(--sunken)}
+.linkrow{display:flex;flex-wrap:wrap;gap:6px 10px;margin-top:var(--s-3);font-size:var(--fs-sm);
+ overflow-wrap:anywhere}
+.badges{display:flex;flex-wrap:wrap;gap:6px;margin-bottom:var(--s-3)}
+.best{background:var(--accent-soft)}
+details.round{border-top:1px solid var(--line);padding:var(--s-2) 0}
+details.round summary{cursor:pointer;font-size:var(--fs-sm)}
+"""
+
+
+def _fmt(v: float | None, d: int = 3) -> str:
+ return "—" if v is None else format(v, f".{d}f")
+
+
+def _kv(key: str, value: str) -> str:
+ return f"<div class='kv'><span class='k'>{esc(key)}</span><span class='v'>{value}</span></div>"
+
+
+def _panel(title: str, inner: str, *, anchor: str = "") -> str:
+ ident = f" id='{esc(anchor)}'" if anchor else ""
+ return f"<div class='panel'{ident}><h2>{esc(title)}</h2>{inner}</div>"
+
+
+def _rel(run: Path, path: str | None) -> str:
+ if not path:
+ return ""
+ p = Path(path)
+ p = p if p.is_absolute() else run / p
+ try:
+ return p.resolve().relative_to(run.resolve()).as_posix()
+ except (ValueError, OSError):
+ return ""
+
+
+# --------------------------------------------------------------------------- sections
+def _hero(entry: RunEntry, urls: UrlMaker, rec: RunRecord) -> str:
+ sheet = entry.sheet
+ shot = (f"<a href='{esc(urls.file(entry, sheet))}'><img src='{esc(urls.file(entry, sheet))}' "
+ f"alt='contact sheet — {esc(entry.slug)}' loading='eager'></a>") if sheet else \
+ "<div class='empty'>no contact sheet</div>"
+ badges = (f"<span class='tag tier {esc(entry.tier)}'>{esc(entry.tier)}</span>"
+ f"<span class='tag {'pill-pass' if entry.passed else ('pill-fail' if entry.passed is False else '')}'>"
+ f"{'passed' if entry.passed else ('failed' if entry.passed is False else 'unjudged')}</span>"
+ f"<span class='tag'>{esc(entry.status)}</span>"
+ f"<span class='tag'>{esc(entry.track)}</span><span class='tag'>{esc(entry.language)}</span>")
+ delta = ("—" if entry.score is None or entry.baseline_score is None
+ else format(entry.score - entry.baseline_score, "+.3f"))
+ facts = "".join([
+ _kv("score", f"<b>{_fmt(entry.score)}</b> (baseline {_fmt(entry.baseline_score)}, Δ {delta})"),
+ _kv("rounds", f"{entry.rounds} · best r{entry.best_round if entry.best_round is not None else '–'}"),
+ _kv("gate errors", str(entry.gate_errors) + (
+ " — " + ", ".join(f"{k}:{v}" for k, v in entry.gate_summary.items()) if entry.gate_summary else "")),
+ _kv("cost", f"${entry.cost_usd:.3f}" + (f" · {entry.minutes:.1f} min" if entry.minutes is not None else "")),
+ _kv("generator", esc(entry.generator)),
+ _kv("judge", esc(entry.judge)),
+ _kv("planner", esc(rec.spec.backends.planner)),
+ _kv("workspace", f"<code class='xs'>{esc(entry.path)}</code>"),
+ ])
+ links = " · ".join(f"<a href='{esc(urls.link(entry, link))}'>{esc(link.label)}</a>" for link in entry.links)
+ prompt = f"<p>{esc(entry.prompt)}</p>"
+ caption = f"<p class='small faint'>{esc(entry.caption)}</p>" if entry.caption else ""
+ err = f"<div class='err'>{esc(entry.error)}</div>" if entry.error else ""
+ return (f"<div class='hero'><div class='shotbox'>{shot}</div>"
+ f"<div class='panel' style='margin:0'><div class='badges'>{badges}</div>{prompt}{caption}{err}"
+ f"<div class='kvs' style='margin-top:var(--s-3)'>{facts}</div>"
+ f"<div class='linkrow'>{links}</div></div></div>")
+
+
+def _rounds_table(entry: RunEntry, urls: UrlMaker) -> str:
+ head = ("<tr><th>r</th><th>kind</th><th class='n'>score</th><th>verdict</th><th class='n'>gates</th>"
+ "<th>build</th><th class='n'>$</th><th class='n'>s</th><th>commit</th><th>sheet</th></tr>")
+ rows = []
+ for r in entry.round_rows:
+ verdict = "—" if r.passed is None else ("pass" if r.passed else "fail")
+ build = "—" if r.build_ok is None else ("ok" if r.build_ok else "failed")
+ gates = str(r.gate_errors) + (" (" + ", ".join(f"{k}:{v}" for k, v in r.gates.items()) + ")" if r.gates else "")
+ sheet = f"<a href='{esc(urls.file(entry, r.sheet))}'>sheet</a>" if r.sheet else "—"
+ best = " class='best'" if r.index == entry.best_round else ""
+ rows.append(f"<tr{best}><td class='n'>{r.index}</td><td>{esc(r.kind)}</td>"
+ f"<td class='n'>{_fmt(r.score)}</td><td>{verdict}</td><td class='n'>{esc(gates)}</td>"
+ f"<td>{build}</td><td class='n'>{r.cost_usd:.3f}</td><td class='n'>{r.duration_s:.0f}</td>"
+ f"<td><code class='xs'>{esc(r.commit)}</code></td><td>{sheet}</td></tr>")
+ body = "".join(rows) or "<tr><td colspan='10' class='faint'>no rounds recorded</td></tr>"
+ return _panel(f"rounds ({len(entry.round_rows)})",
+ f"<div class='tablewrap' style='display:block'><table><thead>{head}</thead>"
+ f"<tbody>{body}</tbody></table></div>", anchor="rounds")
+
+
+def _judgment_panel(rec: RunRecord, best: int | None) -> str:
+ rnd = next((r for r in rec.rounds if r.index == best), None)
+ j = effective_judgment(rnd) if rnd is not None else None
+ if j is None:
+ return _panel("judge", "<p class='faint small'>the best round has no (non-degraded) verdict.</p>",
+ anchor="judge")
+ scores = "".join(_kv(k, f"{v:.3f}") for k, v in sorted(j.scores.items()))
+ issues = "".join(
+ f"<li><b>{esc(i.severity)}</b> · {esc(i.target)} · {esc(i.kind)} — {esc(i.detail)}"
+ + (f" <span class='faint'>[{esc(i.evidence)}]</span>" if i.evidence else "") + "</li>"
+ for i in j.issues) or "<li class='faint'>none reported</li>"
+ plan = "".join(f"<li><b>p{it.priority}</b> {esc(it.target)} — {esc(it.instruction)}</li>"
+ for it in sorted(j.improvement_plan, key=lambda i: i.priority)) or "<li class='faint'>none</li>"
+ strengths = "".join(f"<li>{esc(s)}</li>" for s in j.strengths)
+ accept = "".join(f"<span class='tag {'pill-pass' if ok else 'pill-fail'}'>{esc(k)}</span>"
+ for k, ok in sorted(j.acceptance_results.items()))
+ inner = (
+ f"<p class='small muted'>rubric <code>{esc(j.rubric)}</code> · {esc(j.judge_backend)} · "
+ f"n={j.n_samples} · std {j.score_std:.3f} · overall <b>{j.overall:.3f}</b> "
+ f"({'passed' if j.passed else 'failed'})</p>"
+ f"<p style='margin-top:var(--s-2)'>{esc(j.summary)}</p>"
+ f"<div class='kvs' style='margin-top:var(--s-3)'>{scores}</div>"
+ + (f"<h3 style='margin-top:var(--s-4)'>strengths</h3><ul class='plain'>{strengths}</ul>" if strengths else "")
+ + f"<h3 style='margin-top:var(--s-4)'>issues ({len(j.issues)})</h3><ul class='plain'>{issues}</ul>"
+ + f"<h3 style='margin-top:var(--s-4)'>improvement plan</h3><ul class='plain'>{plan}</ul>"
+ + (f"<h3 style='margin-top:var(--s-4)'>acceptance</h3><div class='facts'>{accept}</div>" if accept else "")
+ )
+ return _panel(f"judge — best round r{best}", inner, anchor="judge")
+
+
+def _measurement_panel(rec: RunRecord, best: int | None) -> str:
+ rnd = next((r for r in rec.rounds if r.index == best), None)
+ m = rnd.measurement if rnd is not None else None
+ if m is None:
+ m = next((r.measurement for r in reversed(rec.rounds) if r.measurement is not None), None)
+ if m is None:
+ return ""
+ def vec(v) -> str:
+ return " ".join(f"{x:+.3f}" for x in v)
+ rows = "".join([
+ _kv("extents (m)", vec(m.extents)), _kv("bbox min", vec(m.bbox_min)), _kv("bbox max", vec(m.bbox_max)),
+ _kv("centre", vec(m.center)), _kv("triangles", f"{m.tri_count:,}"), _kv("meshes", str(m.n_meshes)),
+ _kv("islands", str(m.n_islands)), _kv("materials", str(m.materials)),
+ _kv("ground gap (m)", f"{m.ground_gap_m:+.4f}"), _kv("footprint offset (m)", f"{m.footprint_offset_m:.4f}"),
+ _kv("frame", esc(m.frame)),
+ ])
+ parts = ""
+ if m.parts:
+ head = "<tr><th>part</th><th class='n'>tris</th><th class='n'>islands</th><th>extents (m)</th></tr>"
+ body = "".join(
+ f"<tr><td>{esc(p.name)}</td><td class='n'>{p.tri_count:,}</td><td class='n'>{p.islands}</td>"
+ f"<td class='n'>{' '.join(f'{b - a:.3f}' for a, b in zip(p.bbox_min, p.bbox_max, strict=False))}</td></tr>"
+ for p in m.parts)
+ parts = (f"<div class='tablewrap' style='display:block;margin-top:var(--s-3)'>"
+ f"<table><thead>{head}</thead><tbody>{body}</tbody></table></div>")
+ return _panel("measurement", f"<div class='kvs'>{rows}</div>{parts}", anchor="measurement")
+
+
+def _renders_panel(entry: RunEntry, urls: UrlMaker, rec: RunRecord, best: int | None) -> str:
+ run = Path(entry.path)
+ rnd = next((r for r in rec.rounds if r.index == best), None)
+ figs: list[tuple[str, str]] = []
+ if rnd is not None and rnd.renders is not None:
+ for v in rnd.renders.views:
+ rel = _rel(run, v.path)
+ if rel and (run / rel).is_file():
+ label = v.name + (f" · t={v.time_s:g}s" if v.time_s is not None else "")
+ figs.append((label, rel))
+ extra = [(link.label, link.rel) for link in entry.links
+ if link.label in ("articulation", "preview.gif") and link.rel]
+ for label, rel in extra:
+ figs.append((label, rel))
+ if not figs:
+ return ""
+ cells = "".join(
+ f"<figure><a href='{esc(urls.file(entry, rel))}'>"
+ f"<img loading='lazy' src='{esc(urls.file(entry, rel))}' alt='{esc(label)}'></a>"
+ f"<figcaption>{esc(label)}</figcaption></figure>" for label, rel in figs)
+ return _panel(f"renders ({len(figs)})", f"<div class='shots'>{cells}</div>", anchor="renders")
+
+
+def _cost_panel(entry: RunEntry, ws: Workspace, rec: RunRecord) -> str:
+ from codeverse.flywheel.telemetry import load_telemetry
+
+ 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}"),
+ _kv("input tokens", f"{u.input_tokens:,}"), _kv("output tokens", f"{u.output_tokens:,}")])
+ per_round = "".join(_kv(f"r{r.index} {r.kind}", f"${r.usage.cost_usd:.4f} · {r.duration_s:.0f}s")
+ for r in rec.rounds)
+ return _panel("cost", f"<div class='kvs'>{rows}</div>"
+ f"<h3 style='margin-top:var(--s-4)'>per round</h3><div class='kvs'>{per_round}</div>",
+ anchor="cost")
+ head = ("<tr><th>stage</th><th class='n'>calls</th><th class='n'>in tok</th><th class='n'>out tok</th>"
+ "<th class='n'>cached</th><th class='n'>$</th><th class='n'>s</th></tr>")
+ body = "".join(
+ f"<tr><td>{esc(s.stage)}</td><td class='n'>{s.calls}</td><td class='n'>{s.input_tokens:,}</td>"
+ f"<td class='n'>{s.output_tokens:,}</td><td class='n'>{s.cached_tokens:,}</td>"
+ f"<td class='n'>{s.cost_usd:.4f}</td><td class='n'>{s.seconds:.0f}</td></tr>"
+ for s in sorted(cost.by_stage, key=lambda s: -s.cost_usd))
+ totals = "".join([
+ _kv("total", f"${cost.total_usd:.4f}"),
+ _kv("budget", f"${cost.budget_usd:.2f}" + (f" ({cost.budget_used_pct:.0f}% used)"
+ if cost.budget_used_pct is not None else "")),
+ _kv("calls", str(cost.n_calls)),
+ _kv("wall clock", f"{cost.wall_clock_s / 60:.1f} min"),
+ _kv("unattributed", f"${cost.unattributed_usd:.4f}"),
+ _kv("post-run", f"${cost.post_run_usd:.4f}"),
+ ])
+ by_model = "".join(_kv(k, f"${v:.4f}") for k, v in sorted(cost.by_model.items(), key=lambda kv: -kv[1]))
+ by_role = "".join(_kv(k, f"${v:.4f}") for k, v in sorted(cost.by_role.items(), key=lambda kv: -kv[1]))
+ inner = (f"<div class='kvs'>{totals}</div>"
+ f"<div class='tablewrap' style='display:block;margin-top:var(--s-3)'>"
+ f"<table><thead>{head}</thead><tbody>{body}</tbody></table></div>"
+ f"<h3 style='margin-top:var(--s-4)'>by model</h3><div class='kvs'>{by_model}</div>"
+ f"<h3 style='margin-top:var(--s-4)'>by role</h3><div class='kvs'>{by_role}</div>")
+ return _panel("cost breakdown", inner, anchor="cost")
+
+
+def _code_panel(entry: RunEntry, urls: UrlMaker, rec: RunRecord) -> str:
+ run = Path(entry.path)
+ files = src_files(run)
+ if not files:
+ return ""
+ listing = "".join(
+ f"<li><a href='{esc(urls.code(entry, rel))}'>{esc(rel)}</a>"
+ f"<a class='sz' href='{esc(urls.file(entry, rel))}'>{size:,} B · raw</a></li>" for rel, size in files)
+ entry_rel = ENTRY_FILE.get(rec.spec.language, "")
+ shown = ""
+ target = run / entry_rel if entry_rel else None
+ if target is not None and target.is_file():
+ text, note = read_text(target)
+ shown = (f"<h3 style='margin-top:var(--s-4)'>{esc(entry_rel)}"
+ f" <span class='faint small'>{esc(note)}</span></h3>"
+ + numbered(text, suffix=target.suffix))
+ return _panel(f"code ({len(files)} files)", f"<ul class='filelist'>{listing}</ul>{shown}", anchor="code")
+
+
+# --------------------------------------------------------------------------- page
+def render_detail(entry: RunEntry, urls: UrlMaker, ws: Workspace, rec: RunRecord) -> str:
+ """Full detail page for a run whose record parsed."""
+ best = entry.best_round
+ if not entry.sheet:
+ entry = entry.model_copy(update={"sheet": best_sheet(ws, rec)})
+ nav = " · ".join(f"<a href='#{a}'>{a}</a>" for a in
+ ("rounds", "judge", "measurement", "renders", "cost", "code"))
+ body = (
+ top_bar("3dcv gallery",
+ crumbs=f"<a href='/'>gallery</a> <span class='faint'>/</span> "
+ f"<a href='/?battery={esc(entry.battery)}'>{esc(entry.battery)}</a> "
+ f"<span class='faint'>/</span> <b>{esc(entry.slug)}</b>")
+ + "<main class='wrap'>"
+ + _hero(entry, urls, rec)
+ + f"<p class='small muted' style='margin-top:var(--s-4)'>jump to: {nav}</p>"
+ + _rounds_table(entry, urls)
+ + _judgment_panel(rec, best)
+ + _measurement_panel(rec, best)
+ + _renders_panel(entry, urls, rec, best)
+ + _cost_panel(entry, ws, rec)
+ + _code_panel(entry, urls, rec)
+ + "</main>"
+ + footer(f"{entry.path} · record.json re-read on every request")
+ )
+ return page_shell(f"{entry.slug} — 3dcv gallery", body, extra_css=DETAIL_CSS)
+
+
+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("3dcv gallery", entry.battery,
+ crumbs=f"<a href='/'>gallery</a> <span class='faint'>/</span> <b>{esc(entry.slug)}</b>")
+ + "<main class='wrap'>"
+ + _panel(entry.slug, f"<div class='err'>{esc(entry.state)}: {esc(entry.error)}</div>"
+ f"<p style='margin-top:var(--s-3)'>{esc(entry.prompt)}</p>"
+ f"<div class='linkrow'>{links}</div>")
+ + "</main>" + footer(entry.path))
+ return page_shell(f"{entry.slug} — 3dcv gallery", body, extra_css=DETAIL_CSS)
diff --git a/harness/codeverse/gallery/index.py b/harness/codeverse/gallery/index.py
new file mode 100644
index 00000000..c1fd6038
--- /dev/null
+++ b/harness/codeverse/gallery/index.py
@@ -0,0 +1,268 @@
+"""Build the gallery index from run roots.
+
+``build_index(roots)`` walks every run directory once, reads ``record.json`` and
+turns it into a :class:`~codeverse.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.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+
+from codeverse.contracts.run import RunRecord
+from codeverse.flywheel.quality import quality_tier
+from codeverse.flywheel.record import RecordError, best_round_index, effective_judgment, load_record
+from codeverse.flywheel.sample import gate_error_summary, telemetry_digest
+from codeverse.gallery.labels import humanize_view
+from codeverse.gallery.model import GalleryIndex, RootSection, RoundRow, RunEntry, RunLink
+from codeverse.workspace import Workspace
+
+#: run roots the CLI defaults to when the user names none
+DEFAULT_RUNS = "runs"
+DEFAULT_BENCH_GLOB = "bench/out/*/runs"
+
+
+def default_roots(base: Path | str = ".") -> list[Path]:
+ """``runs/`` plus every ``bench/out/*/runs`` that exists, in that order."""
+ base = Path(base)
+ roots: list[Path] = []
+ if (base / DEFAULT_RUNS).is_dir():
+ roots.append(base / DEFAULT_RUNS)
+ roots += sorted(p for p in base.glob(DEFAULT_BENCH_GLOB) if p.is_dir())
+ return roots
+
+
+def root_label(root: Path) -> str:
+ """Section label: ``runs`` for the plain runs dir, the battery name for a bench out dir."""
+ root = Path(root)
+ if root.name == "runs" and root.parent.name and root.parent.parent.name == "out":
+ return root.parent.name
+ return root.name or str(root)
+
+
+def _rel(run_dir: Path, path: Path | str | None) -> str:
+ """``path`` as a run-relative posix string, or ``""`` when it is outside the run."""
+ if not path:
+ return ""
+ p = Path(path)
+ p = p if p.is_absolute() else run_dir / p
+ try:
+ return p.resolve().relative_to(run_dir.resolve()).as_posix()
+ except (ValueError, OSError):
+ return ""
+
+
+def _first_file(run_dir: Path, *rels: str) -> str:
+ for rel in rels:
+ if (run_dir / rel).is_file():
+ return rel
+ return ""
+
+
+def _round_sheet(ws: Workspace, rec: RunRecord, index: int) -> str:
+ rnd = next((r for r in rec.rounds if r.index == index), None)
+ if rnd is not None and rnd.renders is not None and rnd.renders.contact_sheet:
+ rel = _rel(ws.root, rnd.renders.contact_sheet)
+ if rel and (ws.root / rel).is_file():
+ return rel
+ return _first_file(ws.root, f"artifacts/renders/r{index:02d}/sheet.png")
+
+
+def best_sheet(ws: Workspace, rec: RunRecord) -> str:
+ """Contact sheet of the best round, falling back to the packaged deliverable sheet."""
+ best = best_round_index(rec)
+ if best is not None:
+ rel = _round_sheet(ws, rec, best)
+ if rel:
+ return rel
+ for rnd in reversed(rec.rounds):
+ rel = _round_sheet(ws, rec, rnd.index)
+ if rel:
+ return rel
+ return _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.
+HERO_PREFERENCE = ("front_right_34", "back_left_34", "low_front_left", "front")
+
+
+def hero_view(ws: Workspace, rec: RunRecord, best: int | None) -> tuple[str, str, int]:
+ """``(rel, label, n_views)`` — the ONE image a card should show.
+
+ 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 == best), None)
+ if rnd is None or rnd.renders is None or not rnd.renders.views:
+ return "", "", 0
+ views = [v for v in rnd.renders.views if not v.name.startswith(("pose_", "articulation"))]
+ if not views:
+ return "", "", 0
+ by_name = {v.name: v for v in views}
+ chosen = next((by_name[n] for n in HERO_PREFERENCE if n in by_name), views[0])
+ rel = _rel(ws.root, chosen.path)
+ if not rel or not (ws.root / rel).is_file():
+ return "", "", len(views)
+ return rel, humanize_view(chosen.name), len(views)
+
+
+def _articulation_sheet(ws: Workspace, best: int | None) -> str:
+ order = [best] if best is not None else []
+ order += [int(p.name[1:]) for p in sorted((ws.artifacts / "renders").glob("r[0-9][0-9]"), reverse=True)
+ if p.is_dir()]
+ for idx in order:
+ rel = f"artifacts/renders/r{idx:02d}/poses/articulation_sheet.png"
+ if (ws.root / rel).is_file():
+ return rel
+ return ""
+
+
+def entry_links(ws: Workspace, rec: RunRecord | None, best: int | None) -> list[RunLink]:
+ """The working links of a card: workspace, record, code, sheet, GLB, track extras."""
+ run = ws.root
+ links = [RunLink(label="workspace", rel="", kind="dir"),
+ RunLink(label="record.json", rel="record.json")]
+ for name in ("spec.json", "plan.json"):
+ if (run / name).is_file():
+ links.append(RunLink(label=name, rel=name))
+ if (run / "src").is_dir():
+ links.append(RunLink(label="src/", rel="src", kind="code"))
+ sheet = best_sheet(ws, rec) if rec is not None else ""
+ if sheet:
+ links.append(RunLink(label="sheet", rel=sheet))
+ glb = _first_file(run, "deliverable/object.glb", "artifacts/object.glb")
+ if glb:
+ links.append(RunLink(label="glb", rel=glb, kind="viewer"))
+ textured = _first_file(run, "deliverable/object_textured.glb", "artifacts/object_textured.glb")
+ if textured:
+ links.append(RunLink(label="textured glb", rel=textured, kind="viewer"))
+ urdf = _first_file(run, "deliverable/robot.urdf", "artifacts/robot.urdf", "src/robot.urdf")
+ if urdf:
+ links.append(RunLink(label="robot.urdf", rel=urdf))
+ art = _articulation_sheet(ws, best)
+ if art:
+ links.append(RunLink(label="articulation", rel=art))
+ gif = _first_file(run, "deliverable/preview.gif", "artifacts/preview.gif")
+ if gif:
+ links.append(RunLink(label="preview.gif", rel=gif))
+ if (run / "artifacts" / "frames").is_dir():
+ links.append(RunLink(label="frames/", rel="artifacts/frames", kind="dir"))
+ for tex in ("deliverable/textures", "artifacts/textures", "public/textures"):
+ if (run / tex).is_dir():
+ links.append(RunLink(label="textures/", rel=tex, kind="dir"))
+ break
+ if (run / "public" / "assets").is_dir():
+ links.append(RunLink(label="assets/", rel="public/assets", kind="dir"))
+ if (run / "telemetry" / "cost.json").is_file():
+ links.append(RunLink(label="cost.json", rel="telemetry/cost.json"))
+ return links
+
+
+def round_rows(ws: Workspace, rec: RunRecord) -> list[RoundRow]:
+ rows: list[RoundRow] = []
+ for r in rec.rounds:
+ j = effective_judgment(r)
+ gates = gate_error_summary(r)
+ rows.append(RoundRow(
+ index=r.index, kind=r.kind, commit=r.commit[:12],
+ build_ok=None if r.build is None else r.build.ok,
+ score=j.overall if j else None, passed=j.passed if j else None,
+ gate_errors=sum(gates.values()), gates={k: v for k, v in gates.items() if v},
+ cost_usd=round(r.usage.cost_usd, 6), duration_s=round(r.duration_s, 1),
+ sheet=_round_sheet(ws, rec, r.index),
+ ))
+ return rows
+
+
+def entry_from_record(battery: str, ws: Workspace, rec: RunRecord) -> RunEntry:
+ """A complete card from a parsed record (never raises: every field degrades)."""
+ best = best_round_index(rec)
+ rnd = next((r for r in rec.rounds if r.index == best), None)
+ j = effective_judgment(rnd) if rnd is not None else None
+ gates = gate_error_summary(rnd)
+ n_err = sum(gates.values())
+ minutes = ((rec.finished_at - rec.started_at).total_seconds() / 60.0) if rec.finished_at else None
+ digest = telemetry_digest(ws, rec)
+ caps = rec.extra.get("captions") or {}
+ hero, hero_label, n_views = hero_view(ws, rec, best)
+ plan = rec.plan
+ return RunEntry(
+ battery=battery, slug=ws.root.name, path=str(ws.root), state="ok",
+ title=(getattr(plan, "object_name", "") or getattr(plan, "title", "") or "") if plan else "",
+ prompt=rec.spec.prompt, track=rec.spec.track.value, language=rec.spec.language.value,
+ generator=rec.spec.backends.generator, judge=rec.spec.backends.judge,
+ status=rec.status.value, error=rec.error, caption=str(caps.get("instruction", "") or ""),
+ score=j.overall if j else rec.final_score, baseline_score=rec.baseline_score,
+ passed=j.passed if j else None,
+ tier=quality_tier(passed=j.passed if j else None, gate_errors=n_err, score=j.overall if j else None),
+ gate_errors=n_err, gate_summary={k: v for k, v in gates.items() if v},
+ cost_usd=rec.total_usage.cost_usd, minutes=round(minutes, 1) if minutes is not None else None,
+ rounds=len(rec.rounds), best_round=best,
+ sheet=best_sheet(ws, rec), hero=hero, hero_label=hero_label, n_views=n_views,
+ links=entry_links(ws, rec, best), round_rows=round_rows(ws, rec),
+ cost_by_stage={k: round(v, 4) for k, v in (digest.get("by_stage") or {}).items()},
+ models=dict(digest.get("models") or {}),
+ )
+
+
+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)."""
+ try:
+ spec = json.loads((run_dir / "spec.json").read_text())
+ except (OSError, ValueError):
+ return {}
+ return {k: str(spec.get(k) or "") for k in ("prompt", "track", "language")}
+
+
+def entry_for_dir(battery: str, run_dir: Path) -> RunEntry:
+ """One run directory → an entry, whatever state it is in."""
+ ws = Workspace(run_dir)
+ fields = _spec_fields(run_dir)
+ if not (run_dir / "record.json").is_file():
+ return RunEntry(battery=battery, slug=run_dir.name, path=str(run_dir), state="pending",
+ error="no record.json yet (run in progress or never finished)",
+ links=entry_links(ws, None, None), **fields)
+ try:
+ rec = load_record(ws)
+ except (RecordError, OSError, ValueError) as e:
+ return RunEntry(battery=battery, slug=run_dir.name, path=str(run_dir), state="broken",
+ error=str(e)[:400], links=entry_links(ws, None, None), **fields)
+ try:
+ return entry_from_record(battery, ws, rec)
+ except Exception as e: # noqa: BLE001 - one weird record must not break the page
+ return RunEntry(battery=battery, slug=run_dir.name, path=str(run_dir), state="broken",
+ error=f"{type(e).__name__}: {e}"[:400], links=entry_links(ws, None, None), **fields)
+
+
+def is_run_dir(p: Path) -> bool:
+ return p.is_dir() and ((p / "record.json").is_file() or (p / "spec.json").is_file())
+
+
+def scan_root(root: Path, label: str | None = None) -> RootSection:
+ label = label or root_label(root)
+ entries = [entry_for_dir(label, d) for d in sorted(root.iterdir()) if is_run_dir(d)] if root.is_dir() else []
+ return RootSection(label=label, path=str(Path(root).resolve()), entries=entries)
+
+
+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] = {}
+ for root in roots:
+ root = Path(root)
+ base = root_label(root)
+ used[base] = used.get(base, 0) + 1
+ label = base if used[base] == 1 else f"{base}#{used[base]}"
+ sections.append(scan_root(root, label))
+ return GalleryIndex(sections=sections, build_ms=int((time.perf_counter() - t0) * 1000),
+ roots=[str(Path(r).resolve()) for r in roots])
diff --git a/harness/codeverse/gallery/labels.py b/harness/codeverse/gallery/labels.py
new file mode 100644
index 00000000..0af72d85
--- /dev/null
+++ b/harness/codeverse/gallery/labels.py
@@ -0,0 +1,91 @@
+"""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 four **disjoint** triage buckets every run falls into
+ exactly once, so a status breakdown always sums to the number of runs shown.
+"""
+
+from __future__ import annotations
+
+#: the four buckets, in the order they are always displayed
+VERDICTS = ("passed", "failed", "unjudged", "error")
+
+#: bucket → (short label, css class, what it means)
+VERDICT_META: dict[str, tuple[str, str, str]] = {
+ "passed": ("passed", "v-pass", "judged and over the rubric threshold"),
+ "failed": ("failed", "v-fail", "judged and under the rubric threshold"),
+ "unjudged": ("unjudged", "v-none", "the run finished but has no 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",
+ "preview.gif": "Animated preview",
+ "preview": "Animated preview",
+ "sheet": "Contact sheet",
+ "wire": "Wireframe",
+ "normals": "Normals",
+ "depth": "Depth",
+}
+
+
+def _word(token: str) -> str:
+ low = token.lower()
+ if low in _TOKENS:
+ return _TOKENS[low]
+ if not token:
+ return token
+ return token[:1].upper() + token[1:] if token[:1].islower() else token
+
+
+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 ""
+ stem = raw
+ for suffix in (".png", ".jpg", ".jpeg", ".webp"):
+ if stem.lower().endswith(suffix):
+ stem = stem[: -len(suffix)]
+ break
+ if stem.lower().startswith("view_"):
+ stem = stem[5:]
+ low = stem.lower()
+ if low in _WHOLE:
+ return _WHOLE[low]
+ if low.startswith("t=") and low.endswith("s"):
+ return f"t = {stem[2:-1]} s"
+ if low.startswith("pose_"):
+ return f"Pose · {stem[5:]}"
+ if low.startswith("frame_"):
+ return f"Frame {stem[6:]}"
+ return " ".join(_word(t) for t in stem.split("_") if t) or stem
+
+
+def verdict_label(verdict: str) -> str:
+ return VERDICT_META.get(verdict, (verdict, "", ""))[0]
+
+
+def verdict_class(verdict: str) -> str:
+ return VERDICT_META.get(verdict, ("", "", ""))[1]
+
+
+def verdict_title(verdict: str) -> str:
+ return VERDICT_META.get(verdict, ("", "", ""))[2]
diff --git a/harness/codeverse/gallery/model.py b/harness/codeverse/gallery/model.py
new file mode 100644
index 00000000..49e87e46
--- /dev/null
+++ b/harness/codeverse/gallery/model.py
@@ -0,0 +1,255 @@
+"""Typed model of the local gallery.
+
+One :class:`RunEntry` per run directory (a run that has no ``record.json`` yet, or
+a corrupt one, is still an entry — ``state`` says so), grouped into
+:class:`RootSection` per run root (``runs/``, ``bench/out/<battery>/runs``).
+Every path an entry exposes is **run-relative** so the server can turn it into a
+URL and the static builder into a ``file://`` link — nothing here knows about HTTP.
+"""
+
+from __future__ import annotations
+
+import statistics
+from datetime import datetime
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+from codeverse._compat import UTC
+from codeverse.gallery.labels import VERDICTS
+
+#: 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 and ``/api/runs`` both understand
+FILTER_KEYS = ("q", "track", "lang", "tier", "backend", "pass", "verdict", "battery")
+SORT_KEYS = ("score", "cost", "time", "name")
+
+
+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)")
+ kind: LinkKind = "file"
+
+
+class RoundRow(BaseModel):
+ """One refine round, flattened for the detail page's rounds table."""
+
+ index: int
+ kind: str = ""
+ commit: str = ""
+ build_ok: bool | None = None
+ score: float | None = None
+ passed: bool | None = None
+ gate_errors: int = 0
+ gates: dict[str, int] = Field(default_factory=dict, description="gate name → error count")
+ cost_usd: float = 0.0
+ duration_s: float = 0.0
+ 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
+ path: str = Field(description="absolute run directory")
+ state: RunState = "ok"
+ error: str = ""
+
+ title: str = ""
+ prompt: str = ""
+ track: str = ""
+ language: str = ""
+ generator: str = ""
+ judge: str = ""
+ status: str = ""
+ caption: str = ""
+
+ score: float | None = None
+ baseline_score: float | None = None
+ passed: bool | None = None
+ tier: str = "D"
+ gate_errors: int = 0
+ gate_summary: dict[str, int] = Field(default_factory=dict)
+ cost_usd: float = 0.0
+ minutes: float | None = None
+ rounds: int = 0
+ best_round: int | None = None
+
+ sheet: str = Field(default="", description="run-relative contact sheet (best round)")
+ hero: str = Field(default="", description="run-relative single hero view (the card's image)")
+ hero_label: str = Field(default="", description="what the hero view shows, humanised")
+ n_views: int = Field(default=0, description="how many individual views the best round has")
+ links: list[RunLink] = Field(default_factory=list)
+ round_rows: list[RoundRow] = Field(default_factory=list)
+ cost_by_stage: dict[str, float] = Field(default_factory=dict)
+ models: dict[str, str] = Field(default_factory=dict)
+
+ @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 pass_state(self) -> str:
+ return "pass" if self.passed else ("fail" if self.passed is False else "na")
+
+ @property
+ def verdict(self) -> str:
+ """The triage bucket — exactly one of :data:`~codeverse.gallery.labels.VERDICTS`.
+
+ The four 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"
+ if self.passed is None:
+ return "unjudged"
+ return "passed" if self.passed else "failed"
+
+ @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:
+ return " ".join((self.slug, self.title, self.prompt, self.caption, self.track,
+ 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,
+ "pass": self.pass_state, "verdict": self.verdict, "score": self.score,
+ "cost": round(self.cost_usd, 6), "minutes": self.minutes, "state": self.state,
+ "text": self.search_text(),
+ }
+
+
+class RootSection(BaseModel):
+ """All runs found under one root (``runs/`` or one bench battery)."""
+
+ label: str
+ path: str
+ entries: list[RunEntry] = Field(default_factory=list)
+
+
+class Summary(BaseModel):
+ """The numbers in the summary strip — computed over whatever is *currently* selected.
+
+ ``breakdown`` is the load-bearing one: four disjoint buckets that **sum to
+ ``n``**, so the strip can state "89 runs = 40 passed · 40 failed · 4 unjudged
+ · 5 error" instead of the old un-addable "89 runs / 50% (40/80) / not ok 5"."""
+
+ n: int = 0
+ n_judged: int = 0
+ n_passed: int = 0
+ breakdown: dict[str, int] = Field(default_factory=dict,
+ description="verdict bucket → count; sums to n")
+ pass_rate: float | None = None
+ mean_score: float | None = None
+ median_score: float | None = None
+ total_usd: float = 0.0
+ usd_per_pass: float | None = None
+ minutes: float = 0.0
+ broken: int = 0
+
+ def sums(self) -> bool:
+ """The invariant the strip promises the reader."""
+ return sum(self.breakdown.values()) == self.n
+
+
+def verdict_breakdown(entries: list[RunEntry]) -> dict[str, int]:
+ """``{bucket: count}`` over all four buckets (zeros included), summing to ``len(entries)``."""
+ counts = dict.fromkeys(VERDICTS, 0)
+ for e in entries:
+ counts[e.verdict] += 1
+ return counts
+
+
+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]
+ judged = [e for e in entries if e.passed is not None]
+ passed = [e for e in judged if e.passed]
+ total = sum(e.cost_usd for e in entries)
+ return Summary(
+ n=len(entries), n_judged=len(judged), n_passed=len(passed),
+ breakdown=verdict_breakdown(entries),
+ pass_rate=(len(passed) / len(judged)) if judged else None,
+ mean_score=round(statistics.fmean(scored), 4) if scored else None,
+ median_score=round(statistics.median(scored), 4) if scored else None,
+ total_usd=round(total, 4),
+ usd_per_pass=round(total / len(passed), 4) if passed else None,
+ minutes=round(sum(e.minutes or 0.0 for e in entries), 1),
+ broken=sum(1 for e in entries if e.state != "ok"),
+ )
+
+
+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))
+ build_ms: int = 0
+ roots: list[str] = Field(default_factory=list)
+
+ def entries(self) -> list[RunEntry]:
+ return [e for s in self.sections for e in s.entries]
+
+ def find(self, battery: str, slug: str) -> RunEntry | None:
+ for s in self.sections:
+ if s.label == battery:
+ return next((e for e in s.entries if e.slug == slug), None)
+ 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}),
+ "lang": sorted({e.language for e in es if e.language}),
+ "backend": sorted({e.generator for e in es if e.generator}),
+ "tier": [t for t in "ABCD" if any(e.tier == t for e in es)],
+ "battery": [s.label for s in self.sections],
+ }
+
+
+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
+ for key, value in (("track", entry.track), ("lang", entry.language), ("tier", entry.tier),
+ ("backend", entry.generator), ("battery", entry.battery)):
+ want = (flt.get(key) or "").strip()
+ if want and want != value:
+ return False
+ want_verdict = (flt.get("verdict") or "").strip()
+ if want_verdict and want_verdict != entry.verdict:
+ return False
+ want_pass = (flt.get("pass") or "").strip()
+ return not (want_pass and want_pass != entry.pass_state)
+
+
+def sort_entries(entries: list[RunEntry], key: str) -> list[RunEntry]:
+ """Sort a copy of ``entries``: score/cost/time descending, name ascending."""
+ if key == "cost":
+ return sorted(entries, key=lambda e: (-e.cost_usd, e.slug))
+ if key == "time":
+ return sorted(entries, key=lambda e: (-(e.minutes or 0.0), e.slug))
+ if key == "name":
+ return sorted(entries, key=lambda e: (e.slug, e.battery))
+ return sorted(entries, key=lambda e: (-(e.score if e.score is not None else -1.0), e.slug))
diff --git a/harness/codeverse/gallery/page.py b/harness/codeverse/gallery/page.py
new file mode 100644
index 00000000..c5c09676
--- /dev/null
+++ b/harness/codeverse/gallery/page.py
@@ -0,0 +1,224 @@
+"""The index page: summary strip, filters, per-battery sections, cards + table.
+
+Rendered identically for the local server and the static build — the only
+difference is the :class:`~codeverse.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.
+"""
+
+from __future__ import annotations
+
+import json
+
+from codeverse.gallery.model import (
+ FILTER_KEYS,
+ GalleryIndex,
+ RunEntry,
+ match,
+ sort_entries,
+ summarize,
+)
+from codeverse.gallery.scripts import INDEX_JS
+from codeverse.gallery.theme import esc, footer, page_shell, top_bar
+from codeverse.gallery.urls import UrlMaker
+
+INDEX_CSS = """
+.tablewrap{display:none}
+body.view-table .grid{display:none}
+body.view-table .tablewrap{display:block}
+body.view-table section.battery > .rootpath{margin-bottom:var(--s-2)}
+.card.broken .body{gap:8px}
+"""
+
+
+def _fmt(value: float | None, digits: int = 3, dash: str = "—") -> str:
+ return dash if value is None else format(value, f".{digits}f")
+
+
+def _tier_tag(entry: RunEntry) -> str:
+ return f"<span class='tag tier {esc(entry.tier)}' title='quality tier'>{esc(entry.tier)}</span>"
+
+
+def _pass_tag(entry: RunEntry) -> str:
+ if entry.passed is None:
+ return "<span class='tag' title='never judged'>unjudged</span>"
+ cls = "pill-pass" if entry.passed else "pill-fail"
+ return f"<span class='tag {cls}'>{'passed' if entry.passed else 'failed'}</span>"
+
+
+def _links_html(entry: RunEntry, urls: UrlMaker) -> str:
+ parts = []
+ if urls.has_detail:
+ parts.append(f"<a href='{esc(urls.detail(entry))}'><b>detail</b></a>")
+ parts += [f"<a href='{esc(urls.link(entry, link))}'>{esc(link.label)}</a>" for link in entry.links]
+ return "<div class='links'>" + "".join(parts) + "</div>"
+
+
+def _shot(entry: RunEntry, urls: UrlMaker) -> str:
+ if not entry.sheet:
+ return "<div class='shot'><div class='noshot'>no render</div></div>"
+ href = urls.file(entry, entry.sheet)
+ alt = f"contact sheet — {entry.slug}"
+ return (f"<a class='shot' href='{esc(href)}' title='open the full-size sheet'>"
+ f"<img loading='lazy' decoding='async' src='{esc(urls.img(entry, entry.sheet))}' alt='{esc(alt)}'></a>")
+
+
+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
+ title_href = urls.detail(entry)
+ head = (f"<div class='titlerow'>{_tier_tag(entry)}"
+ f"<a class='name' href='{esc(title_href)}'>{esc(name)}</a>"
+ f"<span class='score num' title='best score'>{_fmt(entry.score)}</span></div>")
+ if entry.state != "ok":
+ body = (f"{head}<div class='err'>{esc(entry.state)}: {esc(entry.error)}</div>"
+ f"<p class='prompt'>{esc(entry.prompt)}</p>{_links_html(entry, urls)}")
+ return (f"<article class='card broken na{hide}' data-run='{esc(entry.key)}'>"
+ f"<div class='body'>{body}</div></article>")
+ tags = "".join(f"<span class='tag'>{esc(t)}</span>" for t in (entry.track, entry.language, entry.generator) if t)
+ delta = ""
+ if entry.baseline_score is not None and entry.score is not None:
+ delta = f" <span class='faint'>({entry.score - entry.baseline_score:+.3f})</span>"
+ best = f"r{entry.best_round}" if entry.best_round is not None else "r–"
+ facts2 = (f"<span>baseline {_fmt(entry.baseline_score)} → best {_fmt(entry.score)}{delta}</span>"
+ f"<span>{best} of {entry.rounds} round{'' if entry.rounds == 1 else 's'}</span>")
+ gates = (f"<span class='tag pill-warn'>{entry.gate_errors} gate err</span>" if entry.gate_errors
+ else "<span class='tag'>gates clean</span>")
+ money = (f"${entry.cost_usd:.2f}" + (f" · {entry.minutes:.1f} min" if entry.minutes is not None else ""))
+ # the run status only earns a chip when it says something the verdict does not
+ # ("passed" next to a green `passed` pill is noise; "plateau"/"budget"/"failed" is not)
+ redundant = not entry.status or (entry.passed and entry.status == "passed")
+ status = "" if redundant else f"<span class='tag'>{esc(entry.status)}</span>"
+ caption = f"<p class='xs faint'>{esc(entry.caption)}</p>" if entry.caption else ""
+ err = f"<div class='err'>{esc(entry.error[:300])}</div>" if entry.error else ""
+ return (
+ f"<article class='card {entry.pass_state}{hide}' data-run='{esc(entry.key)}'>"
+ f"{_shot(entry, urls)}"
+ f"<div class='body'>{head}"
+ f"<p class='prompt' title='{esc(entry.prompt)}'>{esc(entry.prompt)}</p>{caption}"
+ f"<div class='facts'>{tags}</div>"
+ f"<div class='facts small'>{facts2}</div>"
+ f"<div class='facts'>{_pass_tag(entry)}{gates}<span class='tag'>{esc(money)}</span>{status}</div>"
+ f"{err}{_links_html(entry, urls)}</div></article>"
+ )
+
+
+TABLE_HEAD = ("<tr><th>run</th><th>track</th><th>lang</th><th>backend</th><th>tier</th>"
+ "<th class='n'>base</th><th class='n'>best</th><th class='n'>Δ</th><th class='n'>gates</th>"
+ "<th class='n'>$</th><th class='n'>min</th><th>status</th><th>links</th></tr>")
+
+
+def render_row(entry: RunEntry, urls: UrlMaker, *, hidden: bool = False) -> str:
+ delta = (entry.score - entry.baseline_score
+ if entry.score is not None and entry.baseline_score is not None else None)
+ links = " ".join(f"<a href='{esc(urls.link(entry, link))}'>{esc(link.label)}</a>"
+ for link in entry.links if link.label in ("workspace", "src/", "sheet", "glb"))
+ return (
+ f"<tr class='{'is-hidden' if hidden else ''}' data-run='{esc(entry.key)}'>"
+ f"<td class='wide'><a href='{esc(urls.detail(entry))}'>{esc(entry.title or entry.slug)}</a>"
+ f"<div class='xs faint'>{esc(entry.slug)}</div></td>"
+ f"<td>{esc(entry.track)}</td><td>{esc(entry.language)}</td><td>{esc(entry.generator)}</td>"
+ f"<td>{_tier_tag(entry)}</td>"
+ f"<td class='n'>{_fmt(entry.baseline_score)}</td><td class='n'>{_fmt(entry.score)}</td>"
+ f"<td class='n'>{'—' if delta is None else format(delta, '+.3f')}</td>"
+ f"<td class='n'>{entry.gate_errors}</td><td class='n'>{entry.cost_usd:.2f}</td>"
+ f"<td class='n'>{_fmt(entry.minutes, 1)}</td>"
+ f"<td>{esc(entry.status or entry.state)}</td><td>{links}</td></tr>"
+ )
+
+
+def _select(name: str, label: str, options: list[str], value: str, *, any_label: str = "all") -> str:
+ opts = [f"<option value=''>{esc(any_label)}</option>"]
+ opts += [f"<option value='{esc(o)}'{' selected' if o == value else ''}>{esc(o)}</option>" for o in options]
+ return (f"<label for='f-{name}'>{esc(label)}"
+ f"<select id='f-{name}' name='{name}'>{''.join(opts)}</select></label>")
+
+
+def _controls(index: GalleryIndex, flt: dict[str, str], sort: str) -> str:
+ facets = index.facets()
+ q = esc(flt.get("q", ""))
+ parts = [
+ f"<label for='f-q'>search<input type='search' id='f-q' name='q' value='{q}' "
+ f"placeholder='prompt, slug, model… (/)' autocomplete='off'></label>",
+ _select("track", "track", facets["track"], flt.get("track", "")),
+ _select("lang", "language", facets["lang"], flt.get("lang", "")),
+ _select("tier", "tier", facets["tier"], flt.get("tier", "")),
+ _select("backend", "backend", facets["backend"], flt.get("backend", "")),
+ _select("pass", "verdict", ["pass", "fail", "na"], flt.get("pass", ""), any_label="any"),
+ _select("battery", "battery", facets["battery"], flt.get("battery", "")),
+ _select("sort", "sort", ["score", "cost", "time", "name"], sort, any_label="score"),
+ "<button class='btn' id='f-reset' type='button'>reset</button>",
+ ]
+ return f"<form class='controls' onsubmit='return false'>{''.join(parts)}</form>"
+
+
+STATS = (("s-n", "runs"), ("s-pass", "pass rate"), ("s-score", "mean / median"), ("s-cost", "total $"),
+ ("s-perpass", "$ per pass"), ("s-time", "wall clock"), ("s-broken", "not ok"))
+
+
+def _summary_strip(entries: list[RunEntry], total: int) -> str:
+ s = summarize(entries)
+ values = {
+ "s-n": str(s.n) if s.n == total else f"{s.n} / {total}",
+ "s-pass": f"{round(100 * s.pass_rate)}% ({s.n_passed}/{s.n_judged})" if s.pass_rate is not None else "—",
+ "s-score": f"{_fmt(s.mean_score)} / {_fmt(s.median_score)}",
+ "s-cost": f"${s.total_usd:.2f}",
+ "s-perpass": f"${s.usd_per_pass:.2f}" if s.usd_per_pass is not None else "—",
+ "s-time": f"{s.minutes / 60:.1f} h" if s.minutes >= 90 else f"{round(s.minutes)} min",
+ "s-broken": str(s.broken),
+ }
+ cells = "".join(f"<div class='stat'><div class='k'>{esc(label)}</div>"
+ f"<div class='v num' id='{sid}'>{esc(values[sid])}</div></div>" for sid, label in STATS)
+ return f"<div class='strip'>{cells}</div>"
+
+
+def _section(label: str, path: str, entries: list[RunEntry], hidden: set[str], urls: UrlMaker) -> str:
+ cards = "".join(render_card(e, urls, hidden=e.key in hidden) for e in entries)
+ rows = "".join(render_row(e, urls, hidden=e.key in hidden) for e in entries)
+ visible = sum(1 for e in entries if e.key not in hidden)
+ return (
+ f"<section class='battery{'' if visible else ' is-hidden'}' id='b-{esc(label)}'>"
+ f"<h2>{esc(label)} <span class='count' data-count>{visible} run{'' if visible == 1 else 's'}</span></h2>"
+ f"<div class='rootpath'>{esc(path)}</div>"
+ f"<div class='grid' data-items>{cards}</div>"
+ f"<div class='tablewrap'><table><thead>{TABLE_HEAD}</thead>"
+ f"<tbody data-items>{rows}</tbody></table></div></section>"
+ )
+
+
+def render_index(index: GalleryIndex, urls: UrlMaker, *, title: str = "3dcv gallery",
+ flt: dict[str, str] | None = None, sort: str = "score", view: str = "cards",
+ note: str = "") -> str:
+ """The whole index page as one HTML document."""
+ 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)]
+ hidden = {e.key for e in all_entries} - {e.key for e in selected}
+ data = json.dumps([e.card_data() for e in all_entries], separators=(",", ":")).replace("</", "<\\/")
+ sections = "".join(
+ _section(s.label, s.path, sort_entries(s.entries, sort), hidden, urls)
+ for s in index.sections if s.entries)
+ if not sections:
+ sections = "<div class='empty'>no runs found under the given roots</div>"
+ empty = ("<div class='empty is-hidden' id='empty'>nothing matches this filter</div>"
+ if selected else "<div class='empty' id='empty'>nothing matches this filter</div>")
+ right = (f"<button class='btn' id='view-btn' type='button' aria-pressed='{'true' if view == 'table' else 'false'}'>"
+ f"{'▤ table' if view == 'table' else '▦ cards'}</button>")
+ body = (
+ top_bar("3dcv gallery", f"{len(all_entries)} runs · {len(index.sections)} roots", right=right)
+ + "<main class='wrap'>"
+ + (f"<p class='small muted'>{esc(note)}</p>" if note else "")
+ + _summary_strip(selected, len(all_entries))
+ + _controls(index, flt, sort)
+ + sections + empty + "</main>"
+ + footer(f"built in {index.build_ms} ms · {index.built_at:%Y-%m-%d %H:%M UTC} · "
+ f"roots: {', '.join(index.roots)}")
+ )
+ data_block = f"<script type='application/json' id='gallery-data'>{data}</script>"
+ return page_shell(title, body + data_block, scripts=INDEX_JS, extra_css=INDEX_CSS,
+ body_class="view-table" if view == "table" else "")
diff --git a/harness/codeverse/gallery/paths.py b/harness/codeverse/gallery/paths.py
new file mode 100644
index 00000000..dfdc7f13
--- /dev/null
+++ b/harness/codeverse/gallery/paths.py
@@ -0,0 +1,52 @@
+"""Path safety for the local file server.
+
+Two independent gates, both required:
+
+1. the run directory must come from the **index** — a URL can only ever name a
+ ``(battery, slug)`` pair the scanner found under a declared root; and
+2. :func:`safe_join` resolves the rest of the URL inside that run directory and
+ refuses anything that escapes it (``..`` segments, absolute paths, encoded
+ separators, symlinks pointing out of the run).
+
+``tests/gallery/test_server.py`` walks the traversal cases.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path, PurePosixPath
+
+
+class PathError(ValueError):
+ """A requested path is outside the run directory (or is not usable)."""
+
+
+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:
+ raise PathError("null byte in path")
+ if rel.startswith(("/", "\\")) or (len(rel) > 1 and rel[1] == ":"):
+ raise PathError(f"absolute path refused: {rel!r}")
+ parts = [p for p in PurePosixPath(rel.replace("\\", "/")).parts if p not in ("", ".")]
+ if any(p == ".." for p in parts):
+ raise PathError(f"parent traversal refused: {rel!r}")
+ target = base.joinpath(*parts)
+ try:
+ resolved = target.resolve()
+ except OSError as e: # broken symlink loop, too many levels, …
+ 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}")
+ return resolved
+
+
+def is_inside(root: Path | str, path: Path | str) -> bool:
+ """True when ``path`` resolves inside ``root`` (used for the declared roots)."""
+ try:
+ base, p = Path(root).resolve(), Path(path).resolve()
+ except OSError:
+ return False
+ return p == base or base in p.parents
diff --git a/harness/codeverse/gallery/scripts.py b/harness/codeverse/gallery/scripts.py
new file mode 100644
index 00000000..402f13a2
--- /dev/null
+++ b/harness/codeverse/gallery/scripts.py
@@ -0,0 +1,135 @@
+"""The gallery's client-side behaviour — plain ES5-ish JS, no dependencies.
+
+The page ships its run table as JSON in a ``<script type="application/json">``
+block; filtering, sorting, the per-section counts and the whole summary strip are
+recomputed from that array on every input event. Nothing here fetches: a filter
+change never reloads the page, and the URL is kept in sync with
+``history.replaceState`` so a filtered view can be copied, bookmarked or curled.
+"""
+
+from __future__ import annotations
+
+INDEX_JS = r"""
+(function(){
+var node=document.getElementById('gallery-data');
+if(!node) return;
+var DATA=JSON.parse(node.textContent);
+var KEYS=['q','track','lang','tier','backend','pass','battery'];
+var els={};
+KEYS.concat(['sort']).forEach(function(k){els[k]=document.getElementById('f-'+k);});
+var F={};
+
+function readControls(){
+ KEYS.forEach(function(k){F[k]=els[k]?String(els[k].value||'').trim():'';});
+}
+function match(r){
+ if(F.q && r.text.indexOf(F.q.toLowerCase())<0) return false;
+ if(F.track && r.track!==F.track) return false;
+ if(F.lang && r.lang!==F.lang) return false;
+ if(F.tier && r.tier!==F.tier) return false;
+ if(F.backend && r.backend!==F.backend) return false;
+ if(F.pass && r.pass!==F.pass) return false;
+ if(F.battery && r.battery!==F.battery) return false;
+ return true;
+}
+function num(v){return (v===null||v===undefined)?-1:Number(v);}
+function cmp(a,b){
+ var s=els.sort?els.sort.value:'score';
+ if(s==='name') return a.slug<b.slug?-1:(a.slug>b.slug?1:0);
+ var k=(s==='cost')?'cost':(s==='time'?'minutes':'score');
+ var d=num(b[k])-num(a[k]);
+ if(d) return d;
+ return a.slug<b.slug?-1:1;
+}
+function fmt(v,d){return (v===null||v===undefined)?'—':Number(v).toFixed(d);}
+function set(id,txt){var e=document.getElementById(id); if(e) e.textContent=txt;}
+
+function summarize(rows){
+ var scored=[],total=0,mins=0,judged=0,passed=0,broken=0;
+ rows.forEach(function(r){
+ if(typeof r.score==='number') scored.push(r.score);
+ total+=r.cost||0; mins+=r.minutes||0;
+ if(r.pass!=='na'){judged++; if(r.pass==='pass') passed++;}
+ if(r.state!=='ok') broken++;
+ });
+ var mean=scored.length?scored.reduce(function(a,b){return a+b;},0)/scored.length:null;
+ var srt=scored.slice().sort(function(a,b){return a-b;});
+ var med=null;
+ if(srt.length) med=srt.length%2?srt[(srt.length-1)/2]:(srt[srt.length/2-1]+srt[srt.length/2])/2;
+ set('s-n', rows.length===DATA.length?String(rows.length):rows.length+' / '+DATA.length);
+ set('s-pass', judged?Math.round(100*passed/judged)+'% ('+passed+'/'+judged+')':'—');
+ set('s-score', fmt(mean,3)+' / '+fmt(med,3));
+ set('s-cost', '$'+total.toFixed(2));
+ set('s-perpass', passed?'$'+(total/passed).toFixed(2):'—');
+ set('s-time', mins>=90?(mins/60).toFixed(1)+' h':Math.round(mins)+' min');
+ set('s-broken', String(broken));
+}
+
+function apply(){
+ readControls();
+ var keep={},rows=[];
+ DATA.forEach(function(r){ if(match(r)){keep[r.key]=1; rows.push(r);} });
+ var all=document.querySelectorAll('[data-run]');
+ for(var i=0;i<all.length;i++){
+ var hide=!keep[all[i].getAttribute('data-run')];
+ all[i].classList.toggle('is-hidden',hide);
+ }
+ rows.sort(cmp);
+ var order={};
+ rows.forEach(function(r,i){order[r.key]=i;});
+ var boxes=document.querySelectorAll('[data-items]');
+ for(var b=0;b<boxes.length;b++){
+ var kids=[].slice.call(boxes[b].children).filter(function(k){return k.getAttribute('data-run');});
+ kids.sort(function(x,y){
+ var a=order[x.getAttribute('data-run')], c=order[y.getAttribute('data-run')];
+ return (a===undefined?1e9:a)-(c===undefined?1e9:c);
+ });
+ for(var k=0;k<kids.length;k++) boxes[b].appendChild(kids[k]);
+ }
+ var secs=document.querySelectorAll('section.battery');
+ for(var s=0;s<secs.length;s++){
+ var vis=[].slice.call(secs[s].querySelectorAll('.grid > [data-run]'))
+ .filter(function(e){return !e.classList.contains('is-hidden');}).length;
+ var c=secs[s].querySelector('[data-count]');
+ if(c) c.textContent=vis+(vis===1?' run':' runs');
+ secs[s].classList.toggle('is-hidden',vis===0);
+ }
+ var empty=document.getElementById('empty');
+ if(empty) empty.classList.toggle('is-hidden',rows.length>0);
+ summarize(rows);
+ syncUrl();
+}
+
+function syncUrl(){
+ var p=new URLSearchParams();
+ KEYS.forEach(function(k){ if(F[k]) p.set(k,F[k]); });
+ if(els.sort && els.sort.value && els.sort.value!=='score') p.set('sort',els.sort.value);
+ if(document.body.classList.contains('view-table')) p.set('view','table');
+ var qs=p.toString();
+ try{ history.replaceState(null,'',qs?('?'+qs):location.pathname); }catch(e){}
+}
+
+KEYS.concat(['sort']).forEach(function(k){
+ if(!els[k]) return;
+ els[k].addEventListener('input',apply);
+ els[k].addEventListener('change',apply);
+});
+var reset=document.getElementById('f-reset');
+if(reset) reset.addEventListener('click',function(){
+ KEYS.forEach(function(k){ if(els[k]) els[k].value=''; });
+ if(els.sort) els.sort.value='score';
+ apply();
+});
+var vb=document.getElementById('view-btn');
+if(vb) vb.addEventListener('click',function(){
+ var on=document.body.classList.toggle('view-table');
+ vb.setAttribute('aria-pressed',on?'true':'false');
+ vb.textContent=on?'▤ table':'▦ cards';
+ syncUrl();
+});
+document.addEventListener('keydown',function(e){
+ if(e.key==='/' && document.activeElement!==els.q && els.q){ e.preventDefault(); els.q.focus(); }
+});
+apply();
+})();
+"""
diff --git a/harness/codeverse/gallery/server.py b/harness/codeverse/gallery/server.py
new file mode 100644
index 00000000..f04278fb
--- /dev/null
+++ b/harness/codeverse/gallery/server.py
@@ -0,0 +1,340 @@
+"""The local gallery server: ``3dcv 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/paths.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``.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import socket
+import threading
+from dataclasses import dataclass, field
+from datetime import datetime
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from typing import Any
+from urllib.parse import parse_qs, unquote, urlsplit
+
+from codeverse._compat import UTC
+from codeverse.gallery import code as code_page
+from codeverse.gallery import viewer as viewer_page
+from codeverse.gallery.detail import render_broken_detail, render_detail
+from codeverse.gallery.index import build_index
+from codeverse.gallery.model import FILTER_KEYS, RunEntry, match, sort_entries
+from codeverse.gallery.page import render_index
+from codeverse.gallery.paths import PathError, safe_join
+from codeverse.gallery.theme import esc, footer, page_shell, top_bar
+from codeverse.gallery.urls import UrlMaker, content_type
+
+DEFAULT_HOST = "127.0.0.1"
+DEFAULT_PORT = 8765
+LOOPBACK = {"127.0.0.1", "::1", "localhost", "0:0:0:0:0:0:0:1"}
+STREAM_CHUNK = 256 * 1024
+
+
+class GalleryError(RuntimeError):
+ """The server cannot start (bad host, port in use, no roots)."""
+
+
+def resolve_host(host: str | None, *, explicit: bool = False) -> str:
+ """Loopback unless the user explicitly asked for something else.
+
+ A default, an env var or a config file can never move the gallery off
+ 127.0.0.1: only ``explicit=True`` (the ``--host`` flag was typed) does."""
+ if host is None or not host.strip():
+ return DEFAULT_HOST
+ h = host.strip()
+ if h not in LOOPBACK and not explicit:
+ raise GalleryError(f"refusing to bind {h}: pass --host {h} explicitly to leave loopback")
+ return h
+
+
+@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"
+ body: bytes = b""
+ path: Path | None = None
+ headers: dict[str, str] = field(default_factory=dict)
+
+ @classmethod
+ def html(cls, markup: str, status: int = 200) -> Response:
+ return cls(status=status, body=markup.encode("utf-8"))
+
+ @classmethod
+ def json(cls, payload: Any, status: int = 200) -> Response:
+ return cls(status=status, content_type="application/json; charset=utf-8",
+ body=json.dumps(payload, default=str).encode("utf-8"))
+
+ @classmethod
+ def text(cls, text: str, status: int = 200) -> Response:
+ return cls(status=status, content_type="text/plain; charset=utf-8", body=text.encode("utf-8"))
+
+
+def _error_page(status: int, title: str, detail: str) -> Response:
+ body = (top_bar("3dcv gallery", "", crumbs="<a href='/'>gallery</a>")
+ + f"<main class='wrap'><div class='panel'><h2>{status} — {esc(title)}</h2>"
+ f"<p class='muted'>{esc(detail)}</p></div></main>" + footer("3dcv gallery"))
+ return Response.html(page_shell(f"{status} {title}", body), status=status)
+
+
+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 = "3dcv gallery", runtime_js: Path | str | None = None) -> None:
+ self.roots = [Path(r).resolve() for r in roots]
+ self.reload = reload
+ self.title = title
+ self.runtime_js = runtime_js
+ self.urls = UrlMaker()
+ self._lock = threading.Lock()
+ 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:
+ self.index = build_index(self.roots)
+
+ # ----------------------------------------------------------------- helpers
+ def _entry(self, battery: str, slug: str) -> RunEntry | None:
+ entry = self.index.find(battery, slug)
+ if entry is None: # a run created since the last scan
+ self.index = build_index(self.roots)
+ entry = self.index.find(battery, slug)
+ return entry
+
+ def _filters(self, query: dict[str, str]) -> dict[str, str]:
+ return {k: query.get(k, "") for k in FILTER_KEYS}
+
+ def selected(self, query: dict[str, str]) -> list[RunEntry]:
+ flt = self._filters(query)
+ return sort_entries([e for e in self.index.entries() if match(e, flt)], query.get("sort", "score"))
+
+ # ----------------------------------------------------------------- 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:
+ return self._route(parts, query)
+ except PathError as e:
+ 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
+ return _error_page(500, "gallery error", f"{type(e).__name__}: {e}")
+
+ def _route(self, parts: list[str], query: dict[str, str]) -> Response:
+ if not parts or parts == ["index.html"]:
+ self.refresh()
+ return Response.html(render_index(
+ self.index, self.urls, title=self.title, flt=self._filters(query),
+ sort=query.get("sort", "score"), view=query.get("view", "cards")))
+ head, rest = parts[0], parts[1:]
+ if head == "healthz":
+ return Response.text("ok")
+ if head == "api":
+ return self._api(rest, query)
+ if head == "vendor":
+ target = viewer_page.vendor_path("/".join(rest), self.runtime_js)
+ if target is None:
+ raise FileNotFoundError("/".join(rest))
+ return Response(content_type=_js_type(target), path=target)
+ if head in ("run", "file", "dir", "code", "viewer"):
+ if len(rest) < 2:
+ raise FileNotFoundError("expected /<battery>/<slug>/…")
+ entry = self._entry(rest[0], rest[1])
+ if entry is None:
+ raise FileNotFoundError(f"unknown run {rest[0]}/{rest[1]}")
+ rel = "/".join(rest[2:])
+ return self._run_route(head, entry, rel)
+ raise FileNotFoundError("/".join(parts))
+
+ def _run_route(self, head: str, entry: RunEntry, rel: str) -> Response:
+ if head == "run":
+ return self._detail(entry)
+ if head == "dir":
+ return Response.html(code_page.render_dir(entry, self.urls, rel))
+ if head == "code":
+ return Response.html(code_page.render_file(entry, self.urls, rel))
+ if head == "viewer":
+ 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
+ return Response.html(viewer_page.render_viewer(entry, self.urls, rel))
+ target = safe_join(entry.path, rel)
+ if target.is_dir():
+ return Response.html(code_page.render_dir(entry, self.urls, rel))
+ if not target.is_file():
+ raise FileNotFoundError(f"{entry.slug}/{rel}")
+ return Response(content_type=content_type(target), path=target)
+
+ def _detail(self, entry: RunEntry) -> Response:
+ from codeverse.flywheel.record import RecordError, load_record
+ from codeverse.workspace import Workspace
+
+ ws = Workspace(entry.path)
+ try:
+ rec = load_record(ws)
+ except (RecordError, OSError, ValueError) as e:
+ state = entry.state if entry.state != "ok" else "broken"
+ broken = entry.model_copy(update={"state": state, "error": str(e)[:400]})
+ return Response.html(render_broken_detail(broken, self.urls))
+ from codeverse.gallery.index import entry_from_record
+
+ fresh = entry_from_record(entry.battery, ws, rec) # newest rounds, even mid-bench
+ return Response.html(render_detail(fresh, self.urls, ws, rec))
+
+ def _api(self, rest: list[str], query: dict[str, str]) -> Response:
+ self.refresh()
+ what = rest[0] if rest else "runs"
+ if what == "runs":
+ rows = self.selected(query)
+ return Response.json({"n": len(rows), "total": len(self.index.entries()),
+ "runs": [e.model_dump(mode="json") for e in rows]})
+ if what == "summary":
+ from codeverse.gallery.model import summarize
+
+ return Response.json(summarize(self.selected(query)).model_dump(mode="json"))
+ if what == "index":
+ return Response.json(self.index.model_dump(mode="json"))
+ raise FileNotFoundError("/api/" + "/".join(rest))
+
+
+def _js_type(path: Path) -> str:
+ """Vendor modules must be served as JavaScript for ``<script type=module>``."""
+ return "text/javascript; charset=utf-8" if path.suffix in (".js", ".mjs") else content_type(path)
+
+
+# --------------------------------------------------------------------------- http plumbing
+class _Handler(BaseHTTPRequestHandler):
+ server_version = "3dcv-gallery"
+ protocol_version = "HTTP/1.1"
+ app: GalleryApp
+ quiet: bool = True
+
+ def do_GET(self) -> None: # noqa: N802 - stdlib naming
+ self._respond(body=True)
+
+ def do_HEAD(self) -> None: # noqa: N802
+ self._respond(body=False)
+
+ def _respond(self, *, body: bool) -> None:
+ split = urlsplit(self.path)
+ query = {k: v[0] for k, v in parse_qs(split.query).items()}
+ resp = self.app.route(split.path, query)
+ handle = None
+ length = len(resp.body)
+ if resp.path is not None:
+ # open first, then fstat THAT descriptor: a file a bench is still writing
+ # cannot change length between the header and the body
+ try:
+ handle = resp.path.open("rb")
+ length = os.fstat(handle.fileno()).st_size
+ except OSError:
+ resp, handle = _error_page(404, "not found", str(resp.path)), None
+ length = len(resp.body)
+ try:
+ self.send_response(resp.status)
+ self.send_header("Content-Type", resp.content_type)
+ self.send_header("Content-Length", str(length))
+ self.send_header("Cache-Control", "no-cache")
+ self.send_header("X-Content-Type-Options", "nosniff")
+ for k, v in resp.headers.items():
+ self.send_header(k, v)
+ self.end_headers()
+ if not body:
+ return
+ with contextlib.suppress(BrokenPipeError, ConnectionResetError):
+ if handle is None:
+ self.wfile.write(resp.body)
+ else:
+ self._stream(handle, length)
+ finally:
+ if handle is not None:
+ 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
+ return
+ self.wfile.write(chunk)
+ remaining -= len(chunk)
+
+ def log_message(self, fmt: str, *args: Any) -> None:
+ if not self.quiet:
+ super().log_message(fmt, *args)
+
+
+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]
+ except OSError as e:
+ raise GalleryError(f"cannot bind {host}:{port}: {e}") from e
+
+
+def serve(roots: list[Path] | list[str], *, host: str | None = None, host_explicit: bool = False,
+ port: int = DEFAULT_PORT, reload: bool = False, open_browser: bool = False,
+ title: str = "3dcv gallery", on_start: Any = None) -> None:
+ """Build the index and serve it until Ctrl-C."""
+ bind = resolve_host(host, explicit=host_explicit)
+ app = GalleryApp(roots, reload=reload, title=title)
+ httpd = make_server(app, bind, port)
+ url = f"http://{'127.0.0.1' if bind == '0.0.0.0' else bind}:{httpd.server_address[1]}/" # noqa: S104
+ if on_start is not None:
+ on_start(app, url)
+ if open_browser:
+ threading.Thread(target=_open, args=(url,), daemon=True).start()
+ try:
+ httpd.serve_forever()
+ except KeyboardInterrupt:
+ pass
+ finally:
+ httpd.shutdown()
+ httpd.server_close()
+
+
+def _open(url: str) -> None:
+ import webbrowser
+
+ with contextlib.suppress(Exception): # headless box, no browser
+ webbrowser.open(url)
+
+
+def free_port(host: str = DEFAULT_HOST) -> int:
+ """An ephemeral free port (tests, and ``--port 0``)."""
+ with socket.socket() as s:
+ s.bind((host, 0))
+ return int(s.getsockname()[1])
+
+
+def started_at() -> str:
+ return datetime.now(UTC).isoformat(timespec="seconds")
diff --git a/harness/codeverse/gallery/static_site.py b/harness/codeverse/gallery/static_site.py
new file mode 100644
index 00000000..554ad3ce
--- /dev/null
+++ b/harness/codeverse/gallery/static_site.py
@@ -0,0 +1,47 @@
+"""``3dcv gallery build`` — the shareable single-file form of the same page.
+
+Identical markup to the served gallery; only the URL maker differs. Without
+``--embed`` the ``<img>`` tags point at the run directories with ``file://``
+(fast, tiny file, works on this machine); with ``--embed`` every contact sheet is
+inlined as a downscaled JPEG so the page can be copied or published — at the
+price of a much bigger file. The write is atomic: a bench reading the previous
+gallery never sees a half-written one.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.gallery.index import build_index
+from codeverse.gallery.model import GalleryIndex
+from codeverse.gallery.page import render_index
+from codeverse.gallery.urls import THUMB_PX, StaticUrls
+
+
+def render_static(index: GalleryIndex, *, title: str = "3dcv gallery", embed: bool = False,
+ thumb_px: int = THUMB_PX, sort: str = "score", view: str = "cards") -> 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 `3dcv gallery serve` for a page that works anywhere")
+ return render_index(index, StaticUrls(embed=embed, thumb_px=thumb_px),
+ title=title, sort=sort, view=view, note=note)
+
+
+def write_atomic(path: Path, text: str) -> Path:
+ """tmp + rename, so a reader never sees a partial gallery."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(path.name + ".tmp")
+ tmp.write_text(text, encoding="utf-8")
+ tmp.replace(path)
+ return path
+
+
+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 ("3dcv gallery — " + ", ".join(s.label for s in index.sections[:4])
+ + ("…" if len(index.sections) > 4 else ""))
+ html = render_static(index, title=label, embed=embed, thumb_px=thumb_px)
+ return write_atomic(Path(out_html), html), len(index.entries()), index
diff --git a/harness/codeverse/gallery/theme.py b/harness/codeverse/gallery/theme.py
new file mode 100644
index 00000000..55056730
--- /dev/null
+++ b/harness/codeverse/gallery/theme.py
@@ -0,0 +1,235 @@
+"""The gallery's design system: one token set, one page shell, no external assets.
+
+Everything is inlined (offline is a hard requirement — no CDN, no Google Fonts).
+Colour, spacing, radius and type scale live as custom properties on ``:root``;
+dark mode is expressed **three** times on purpose so both the OS preference and
+the manual toggle win in both directions:
+
+* ``:root`` — the complete light palette (the only place a colour is born)
+* ``@media (prefers-color-scheme: dark)`` guarded by ``:root:not([data-theme="light"])``
+* ``:root[data-theme="dark"]`` — the manual toggle
+
+``page_shell`` is the only place that emits ``<html>``; every page in this
+package returns a body fragment and hands it here.
+"""
+
+from __future__ import annotations
+
+import html
+
+TOKENS = """
+:root{
+ --bg:#f7f7f8; --surface:#ffffff; --sunken:#eeeef1; --line:#dcdce2; --line-strong:#c3c3cd;
+ --fg:#16161a; --fg-2:#4b4b57; --fg-3:#75757f;
+ --accent:#2f5bd0; --accent-fg:#ffffff; --accent-soft:#e6ecfb;
+ --ok:#1f7a3d; --ok-soft:#e2f3e7; --bad:#b3261e; --bad-soft:#fbe6e4; --warn:#8a5a00; --warn-soft:#fbf0d9;
+ --tier-a:#1f7a3d; --tier-b:#5c7a1f; --tier-c:#8a5a00; --tier-d:#b3261e;
+ --shadow:0 1px 2px rgba(16,16,24,.06), 0 4px 12px rgba(16,16,24,.05);
+ --r-1:4px; --r-2:8px; --r-3:14px;
+ --s-1:4px; --s-2:8px; --s-3:12px; --s-4:16px; --s-5:24px; --s-6:36px;
+ --fs-xs:11.5px; --fs-sm:12.5px; --fs-md:14px; --fs-lg:17px; --fs-xl:22px;
+ --sans:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
+ --mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,"Liberation Mono",monospace;
+ --maxw:1680px;
+}
+@media (prefers-color-scheme: dark){
+ :root:not([data-theme="light"]){
+ --bg:#0f1013; --surface:#17181c; --sunken:#111216; --line:#2a2c33; --line-strong:#3b3e47;
+ --fg:#e8e8ec; --fg-2:#b1b2bd; --fg-3:#83848f;
+ --accent:#7aa2f7; --accent-fg:#0f1013; --accent-soft:#1b2438;
+ --ok:#5fd18b; --ok-soft:#14291d; --bad:#ff8a80; --bad-soft:#2e1614; --warn:#e3b341; --warn-soft:#2b2210;
+ --tier-a:#5fd18b; --tier-b:#a8cf5c; --tier-c:#e3b341; --tier-d:#ff8a80;
+ --shadow:0 1px 2px rgba(0,0,0,.5), 0 6px 18px rgba(0,0,0,.35);
+ }
+}
+:root[data-theme="dark"]{
+ --bg:#0f1013; --surface:#17181c; --sunken:#111216; --line:#2a2c33; --line-strong:#3b3e47;
+ --fg:#e8e8ec; --fg-2:#b1b2bd; --fg-3:#83848f;
+ --accent:#7aa2f7; --accent-fg:#0f1013; --accent-soft:#1b2438;
+ --ok:#5fd18b; --ok-soft:#14291d; --bad:#ff8a80; --bad-soft:#2e1614; --warn:#e3b341; --warn-soft:#2b2210;
+ --tier-a:#5fd18b; --tier-b:#a8cf5c; --tier-c:#e3b341; --tier-d:#ff8a80;
+ --shadow:0 1px 2px rgba(0,0,0,.5), 0 6px 18px rgba(0,0,0,.35);
+}
+"""
+
+BASE_CSS = """
+*,*::before,*::after{box-sizing:border-box}
+html{-webkit-text-size-adjust:100%}
+body{margin:0;background:var(--bg);color:var(--fg);font:var(--fs-md)/1.5 var(--sans);
+ overflow-x:hidden;font-variant-numeric:tabular-nums}
+.wrap{max-width:var(--maxw);margin:0 auto;padding:var(--s-5) var(--s-4) var(--s-6)}
+a{color:var(--accent);text-decoration:none}
+a:hover{text-decoration:underline}
+a:focus-visible,button:focus-visible,select:focus-visible,input:focus-visible,summary:focus-visible{
+ outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--r-1)}
+h1,h2,h3{margin:0;font-weight:650;letter-spacing:-.01em;line-height:1.25}
+h1{font-size:var(--fs-xl)} h2{font-size:var(--fs-lg)} h3{font-size:var(--fs-md)}
+p{margin:0}
+code,pre,.mono{font-family:var(--mono)}
+.num{font-variant-numeric:tabular-nums}
+.muted{color:var(--fg-2)} .faint{color:var(--fg-3)}
+.small{font-size:var(--fs-sm)} .xs{font-size:var(--fs-xs)}
+
+header.top{position:sticky;top:0;z-index:20;background:color-mix(in srgb,var(--bg) 88%,transparent);
+ backdrop-filter:blur(8px);border-bottom:1px solid var(--line)}
+header.top .bar{max-width:var(--maxw);margin:0 auto;padding:var(--s-3) var(--s-4);
+ display:flex;gap:var(--s-3) var(--s-4);align-items:center;flex-wrap:wrap;overflow-wrap:anywhere}
+.brand{display:flex;gap:var(--s-2);align-items:baseline}
+.brand b{font-size:var(--fs-lg);letter-spacing:-.02em}
+.spacer{margin-left:auto}
+.btn{font:inherit;font-size:var(--fs-sm);color:var(--fg);background:var(--surface);border:1px solid var(--line);
+ border-radius:var(--r-2);padding:5px 10px;cursor:pointer}
+.btn:hover{border-color:var(--line-strong)}
+.btn[aria-pressed="true"]{background:var(--accent-soft);border-color:var(--accent);color:var(--fg)}
+
+.crumbs{display:flex;gap:var(--s-2);align-items:center;font-size:var(--fs-sm);color:var(--fg-2);flex-wrap:wrap;
+ overflow-wrap:anywhere;min-width:0}
+.crumbs a{color:var(--fg-2)}
+
+.strip{display:grid;grid-template-columns:repeat(auto-fit,minmax(132px,1fr));gap:var(--s-2);
+ margin:var(--s-4) 0}
+.stat{background:var(--surface);border:1px solid var(--line);border-radius:var(--r-2);padding:var(--s-3)}
+.stat .k{font-size:var(--fs-xs);text-transform:uppercase;letter-spacing:.06em;color:var(--fg-3)}
+.stat .v{font-size:var(--fs-lg);font-weight:650;margin-top:2px}
+
+.controls{display:flex;gap:var(--s-2);align-items:center;flex-wrap:wrap;margin:var(--s-4) 0 var(--s-3);
+ padding:var(--s-3);background:var(--surface);border:1px solid var(--line);border-radius:var(--r-2)}
+.controls label{display:flex;gap:6px;align-items:center;font-size:var(--fs-sm);color:var(--fg-2)}
+select,input[type=search]{font:inherit;font-size:var(--fs-sm);color:var(--fg);background:var(--bg);
+ border:1px solid var(--line);border-radius:var(--r-1);padding:4px 6px;max-width:100%}
+input[type=search]{min-width:min(260px,60vw)}
+
+section.battery{margin:var(--s-5) 0}
+section.battery > h2{display:flex;gap:var(--s-2);align-items:baseline}
+.count{font-size:var(--fs-sm);color:var(--fg-3);font-weight:500}
+.rootpath{font-size:var(--fs-xs);color:var(--fg-3);font-family:var(--mono);margin-top:2px;
+ overflow-wrap:anywhere}
+
+.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(320px,100%),1fr));gap:var(--s-4);
+ margin-top:var(--s-3)}
+.card{background:var(--surface);border:1px solid var(--line);border-radius:var(--r-3);overflow:hidden;
+ display:flex;flex-direction:column;box-shadow:var(--shadow)}
+.card.pass{border-top:3px solid var(--ok)} .card.fail{border-top:3px solid var(--bad)}
+.card.na{border-top:3px solid var(--line-strong)}
+.card .shot{display:block;background:var(--sunken);aspect-ratio:16/10;overflow:hidden}
+.card .shot img{width:100%;height:100%;object-fit:contain;display:block}
+.card .noshot{width:100%;height:100%;display:flex;align-items:center;justify-content:center;
+ color:var(--fg-3);font-size:var(--fs-sm)}
+.card .body{padding:var(--s-3);display:flex;flex-direction:column;gap:6px;flex:1}
+.titlerow{display:flex;gap:var(--s-2);align-items:center}
+.titlerow .name{font-weight:650;overflow-wrap:anywhere;min-width:0}
+.titlerow .score{margin-left:auto;font-size:var(--fs-lg);font-weight:650}
+.prompt{color:var(--fg-2);font-size:var(--fs-sm);overflow-wrap:anywhere;display:-webkit-box;-webkit-line-clamp:3;
+ -webkit-box-orient:vertical;overflow:hidden}
+.facts{font-size:var(--fs-sm);color:var(--fg-2);display:flex;flex-wrap:wrap;gap:2px 8px}
+.links{display:flex;flex-wrap:wrap;gap:2px 8px;font-size:var(--fs-sm);padding-top:2px;
+ border-top:1px solid var(--line);margin-top:auto}
+
+.tag{display:inline-flex;align-items:center;gap:4px;font-size:var(--fs-xs);padding:1px 7px;border-radius:999px;
+ border:1px solid var(--line);color:var(--fg-2);background:var(--sunken);white-space:nowrap}
+.tier{font-weight:700;color:var(--accent-fg)}
+.tier.A{background:var(--tier-a);border-color:var(--tier-a)}
+.tier.B{background:var(--tier-b);border-color:var(--tier-b)}
+.tier.C{background:var(--tier-c);border-color:var(--tier-c)}
+.tier.D{background:var(--tier-d);border-color:var(--tier-d)}
+.pill-pass{color:var(--ok);background:var(--ok-soft);border-color:var(--ok)}
+.pill-fail{color:var(--bad);background:var(--bad-soft);border-color:var(--bad)}
+.pill-warn{color:var(--warn);background:var(--warn-soft);border-color:var(--warn)}
+
+.tablewrap{overflow-x:auto;margin-top:var(--s-3);border:1px solid var(--line);border-radius:var(--r-2);
+ background:var(--surface)}
+table{border-collapse:collapse;width:100%;font-size:var(--fs-sm)}
+th,td{text-align:left;padding:6px 10px;border-bottom:1px solid var(--line);white-space:nowrap}
+th{font-size:var(--fs-xs);text-transform:uppercase;letter-spacing:.05em;color:var(--fg-3);
+ position:sticky;top:0;background:var(--surface)}
+tbody tr:last-child td{border-bottom:0}
+td.wide{white-space:normal;min-width:220px;max-width:520px}
+td.n,th.n{text-align:right;font-variant-numeric:tabular-nums}
+
+.panel{background:var(--surface);border:1px solid var(--line);border-radius:var(--r-2);
+ padding:var(--s-4);margin:var(--s-4) 0}
+.panel > h2{margin-bottom:var(--s-3)}
+.kvs{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:var(--s-2) var(--s-4)}
+.kv{display:flex;gap:var(--s-2);font-size:var(--fs-sm);border-bottom:1px dotted var(--line);padding:3px 0}
+.kv .k{color:var(--fg-3);min-width:110px}
+.kv .v{overflow-wrap:anywhere}
+ul.plain{margin:0;padding-left:18px;font-size:var(--fs-sm);color:var(--fg-2)}
+ul.plain li{margin:2px 0}
+
+.shots{display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:var(--s-3)}
+.shots figure{margin:0;background:var(--sunken);border:1px solid var(--line);border-radius:var(--r-2);
+ overflow:hidden}
+.shots img{width:100%;display:block;background:var(--sunken)}
+.shots figcaption{font-size:var(--fs-xs);color:var(--fg-3);padding:4px 6px;overflow-wrap:anywhere}
+
+pre.code{margin:0;padding:var(--s-3);background:var(--sunken);border:1px solid var(--line);
+ border-radius:var(--r-2);overflow-x:auto;font-size:var(--fs-sm);line-height:1.55;tab-size:4}
+pre.code .ln{display:inline-block;width:3.5em;color:var(--fg-3);user-select:none;text-align:right;
+ padding-right:1em}
+.err{color:var(--bad);background:var(--bad-soft);border:1px solid var(--bad);border-radius:var(--r-1);
+ padding:var(--s-2);font-size:var(--fs-sm);overflow-wrap:anywhere;white-space:pre-wrap}
+.is-hidden{display:none !important}
+.empty{padding:var(--s-5);text-align:center;color:var(--fg-3)}
+footer.foot{max-width:var(--maxw);margin:0 auto;padding:var(--s-4);color:var(--fg-3);font-size:var(--fs-xs);
+ border-top:1px solid var(--line);overflow-wrap:anywhere}
+"""
+
+#: sets the stored theme before first paint so a manual choice never flashes
+THEME_BOOT_JS = """
+(function(){try{var t=localStorage.getItem('3dcv-gallery-theme');
+if(t==='dark'||t==='light')document.documentElement.setAttribute('data-theme',t);}catch(e){}})();
+"""
+
+THEME_TOGGLE_JS = """
+(function(){var b=document.getElementById('theme-btn');if(!b)return;
+function cur(){var a=document.documentElement.getAttribute('data-theme');if(a)return a;
+return matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light';}
+function paint(){b.textContent=cur()==='dark'?'\\u25D1 dark':'\\u25D0 light';}
+b.addEventListener('click',function(){var n=cur()==='dark'?'light':'dark';
+document.documentElement.setAttribute('data-theme',n);
+try{localStorage.setItem('3dcv-gallery-theme',n);}catch(e){}paint();});paint();})();
+"""
+
+#: inline favicon so a browser never issues a /favicon.ico request the server would 404
+FAVICON = ("<link rel='icon' href=\"data:image/svg+xml,"
+ "%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E"
+ "%3Crect width='16' height='16' rx='3' fill='%232f5bd0'/%3E"
+ "%3Cpath d='M4 11V5l4 2.4L12 5v6' stroke='white' stroke-width='1.6' fill='none'/%3E"
+ "%3C/svg%3E\">")
+
+THEME_BUTTON = '<button class="btn" id="theme-btn" type="button" title="light / dark">theme</button>'
+
+
+def esc(text: object) -> str:
+ return html.escape(str(text), quote=True)
+
+
+def page_shell(title: str, body: str, *, scripts: str = "", extra_css: str = "",
+ head_extra: str = "", body_class: str = "", modules: str = "") -> str:
+ """A complete, self-contained HTML document. ``body`` is a fragment.
+
+ ``scripts`` runs as a classic script after the body; ``modules`` as an ES
+ module (the GLB viewer needs one)."""
+ cls = f" class='{esc(body_class)}'" if body_class else ""
+ mod = f"<script type='module'>{modules}</script>\n" if modules else ""
+ return (
+ "<!doctype html>\n<html lang='en'>\n<head>\n<meta charset='utf-8'>\n"
+ "<meta name='viewport' content='width=device-width,initial-scale=1'>\n"
+ f"<title>{esc(title)}</title>\n{FAVICON}\n"
+ f"<script>{THEME_BOOT_JS}</script>\n"
+ f"<style>{TOKENS}{BASE_CSS}{extra_css}</style>\n{head_extra}</head>\n<body{cls}>\n"
+ f"{body}\n"
+ f"<script>{THEME_TOGGLE_JS}{scripts}</script>\n{mod}</body>\n</html>\n"
+ )
+
+
+def top_bar(title: str, subtitle: str = "", *, crumbs: str = "", right: str = "") -> str:
+ """Sticky header: brand + optional breadcrumb trail + the theme toggle."""
+ sub = f"<span class='muted small'>{esc(subtitle)}</span>" if subtitle else ""
+ crumb = f"<nav class='crumbs'>{crumbs}</nav>" if crumbs else ""
+ return (f"<header class='top'><div class='bar'><div class='brand'><b>{esc(title)}</b>{sub}</div>"
+ f"{crumb}<div class='spacer'></div>{right}{THEME_BUTTON}</div></header>")
+
+
+def footer(text: str) -> str:
+ return f"<footer class='foot'>{esc(text)}</footer>"
diff --git a/harness/codeverse/gallery/urls.py b/harness/codeverse/gallery/urls.py
new file mode 100644
index 00000000..0c5a6887
--- /dev/null
+++ b/harness/codeverse/gallery/urls.py
@@ -0,0 +1,153 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+import base64
+import io
+import mimetypes
+from pathlib import Path
+from urllib.parse import quote
+
+from codeverse.gallery.model import RunEntry, RunLink
+
+THUMB_PX = 720
+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:
+ return f"/run/{quote(entry.battery)}/{quote(entry.slug)}"
+
+ def file(self, entry: RunEntry, rel: str) -> str:
+ return f"/file/{quote(entry.battery)}/{quote(entry.slug)}/{quote(rel)}"
+
+ def dir(self, entry: RunEntry, rel: str = "") -> str:
+ return f"/dir/{quote(entry.battery)}/{quote(entry.slug)}/{quote(rel)}"
+
+ def code(self, entry: RunEntry, rel: str) -> str:
+ return f"/code/{quote(entry.battery)}/{quote(entry.slug)}/{quote(rel)}"
+
+ def viewer(self, entry: RunEntry, rel: str) -> str:
+ 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:
+ return {"dir": self.dir, "code": self.code, "viewer": self.viewer}.get(link.kind, self.file)(entry, link.rel)
+
+
+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
+
+ def __init__(self, *, embed: bool = False, thumb_px: int = THUMB_PX) -> None:
+ self.embed = embed
+ self.thumb_px = thumb_px
+
+ def _uri(self, entry: RunEntry, rel: str) -> str:
+ p = Path(entry.path) / rel if rel else Path(entry.path)
+ return p.as_uri() if p.is_absolute() else quote(str(p))
+
+ def detail(self, entry: RunEntry) -> str:
+ return self._uri(entry, "")
+
+ def file(self, entry: RunEntry, rel: str) -> str:
+ return self._uri(entry, rel)
+
+ def dir(self, entry: RunEntry, rel: str = "") -> str:
+ return self._uri(entry, rel)
+
+ def code(self, entry: RunEntry, rel: str) -> str:
+ return self._uri(entry, rel)
+
+ def viewer(self, entry: RunEntry, rel: str) -> str:
+ return self._uri(entry, rel)
+
+ def img(self, entry: RunEntry, rel: str) -> str:
+ if not self.embed:
+ return self._uri(entry, rel)
+ return thumbnail_data_uri(Path(entry.path) / rel, max_px=self.thumb_px) or self._uri(entry, rel)
+
+
+def thumbnail_data_uri(path: Path | str, *, max_px: int = THUMB_PX) -> str:
+ """Downscaled JPEG as a ``data:`` URI; ``""`` when the image cannot be read."""
+ try:
+ from PIL import Image
+
+ with Image.open(path) as im:
+ im = im.convert("RGB")
+ im.thumbnail((max_px, max_px))
+ buf = io.BytesIO()
+ im.save(buf, format="JPEG", quality=JPEG_QUALITY, optimize=True)
+ except Exception: # noqa: BLE001 - missing PIL, unreadable/half-written file
+ 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",
+ ".stl": "model/stl",
+ ".step": "model/step",
+ ".stp": "model/step",
+ ".obj": "text/plain; charset=utf-8",
+ ".urdf": "text/plain; charset=utf-8",
+ ".py": "text/plain; charset=utf-8",
+ ".js": "text/plain; charset=utf-8",
+ ".mjs": "text/plain; charset=utf-8",
+ ".cjs": "text/plain; charset=utf-8",
+ ".frag": "text/plain; charset=utf-8",
+ ".vert": "text/plain; charset=utf-8",
+ ".glsl": "text/plain; charset=utf-8",
+ ".md": "text/plain; charset=utf-8",
+ ".txt": "text/plain; charset=utf-8",
+ ".log": "text/plain; charset=utf-8",
+ ".yaml": "text/plain; charset=utf-8",
+ ".yml": "text/plain; charset=utf-8",
+ ".csv": "text/plain; charset=utf-8",
+ ".jsonl": "text/plain; charset=utf-8",
+ ".json": "application/json; charset=utf-8",
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".gif": "image/gif",
+ ".webp": "image/webp",
+ ".svg": "image/svg+xml",
+ ".mp4": "video/mp4",
+ ".webm": "video/webm",
+ ".blend": "application/octet-stream",
+}
+
+
+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]
+ guessed, _ = mimetypes.guess_type(str(path))
+ if guessed is None:
+ return "application/octet-stream"
+ if guessed.startswith("text/") and "charset" not in guessed:
+ return f"{guessed}; charset=utf-8"
+ return guessed
diff --git a/harness/codeverse/gallery/viewer.py b/harness/codeverse/gallery/viewer.py
new file mode 100644
index 00000000..94d4b956
--- /dev/null
+++ b/harness/codeverse/gallery/viewer.py
@@ -0,0 +1,140 @@
+"""Optional GLB viewer, served from the **vendored** three.js in ``runtime_js/``.
+
+No CDN: the page declares an import map that points ``three`` and
+``three/addons/`` at ``/vendor/...``, which the server maps onto
+``runtime_js/node_modules/three/``. When that package is not installed the
+viewer is simply not offered and the GLB link stays a plain download.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from codeverse.gallery.model import RunEntry
+from codeverse.gallery.theme import esc, footer, page_shell, top_bar
+from codeverse.gallery.urls import UrlMaker
+
+#: URL prefix → path under node_modules/three
+VENDOR_MAP = {"three/build/": "build/", "three/examples/jsm/": "examples/jsm/"}
+
+VIEWER_CSS = """
+#stage{width:100%;height:min(78vh,900px);background:var(--sunken);border:1px solid var(--line);
+ border-radius:var(--r-3);overflow:hidden;position:relative}
+#stage canvas{display:block;width:100%;height:100%}
+#hint{position:absolute;left:10px;bottom:10px;font-size:var(--fs-xs);color:var(--fg-3);
+ background:color-mix(in srgb,var(--surface) 80%,transparent);padding:3px 8px;border-radius:999px}
+#vmsg{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;
+ color:var(--fg-2);font-size:var(--fs-sm);padding:var(--s-4);text-align:center}
+"""
+
+VIEWER_JS = r"""
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+
+const stage = document.getElementById('stage');
+const msg = document.getElementById('vmsg');
+const src = stage.dataset.src;
+const dark = getComputedStyle(document.body).getPropertyValue('--sunken').trim() || '#eee';
+
+const renderer = new THREE.WebGLRenderer({antialias:true, alpha:true});
+renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
+renderer.setSize(stage.clientWidth, stage.clientHeight);
+stage.appendChild(renderer.domElement);
+
+const scene = new THREE.Scene();
+const camera = new THREE.PerspectiveCamera(35, stage.clientWidth/stage.clientHeight, 0.01, 500);
+camera.position.set(1.6, 1.2, 2.0);
+const controls = new OrbitControls(camera, renderer.domElement);
+controls.enableDamping = true;
+
+scene.add(new THREE.HemisphereLight(0xffffff, 0x404050, 2.2));
+const key = new THREE.DirectionalLight(0xffffff, 2.0);
+key.position.set(2.5, 4, 3);
+scene.add(key);
+
+new GLTFLoader().load(src, (gltf) => {
+ msg.remove();
+ scene.add(gltf.scene);
+ const box = new THREE.Box3().setFromObject(gltf.scene);
+ const size = box.getSize(new THREE.Vector3());
+ const centre = box.getCenter(new THREE.Vector3());
+ const radius = Math.max(size.length() * 0.5, 0.05);
+ const grid = new THREE.GridHelper(Math.max(2, radius * 4), 20, 0x888888, 0xcccccc);
+ grid.material.opacity = 0.35; grid.material.transparent = true;
+ grid.position.y = box.min.y;
+ scene.add(grid);
+ controls.target.copy(centre);
+ camera.near = radius / 100; camera.far = radius * 100;
+ camera.position.copy(centre).add(new THREE.Vector3(radius*1.6, radius*1.1, radius*2.0));
+ camera.updateProjectionMatrix();
+ controls.update();
+ document.getElementById('dims').textContent =
+ size.x.toFixed(3)+' × '+size.y.toFixed(3)+' × '+size.z.toFixed(3)+' m';
+}, undefined, (err) => { msg.textContent = 'could not load this GLB: ' + err; });
+
+addEventListener('resize', () => {
+ renderer.setSize(stage.clientWidth, stage.clientHeight);
+ camera.aspect = stage.clientWidth/stage.clientHeight;
+ camera.updateProjectionMatrix();
+});
+(function loop(){ requestAnimationFrame(loop); controls.update(); renderer.render(scene, camera); })();
+"""
+
+
+def three_root(runtime_js: Path | str | None = None) -> Path | None:
+ """``runtime_js/node_modules/three`` when the vendored copy is installed."""
+ if runtime_js is None:
+ from codeverse.config import get_settings
+
+ runtime_js = get_settings().runtime_js_dir()
+ p = Path(runtime_js) / "node_modules" / "three"
+ return p if (p / "build" / "three.module.js").is_file() else None
+
+
+def viewer_available(runtime_js: Path | str | None = None) -> bool:
+ return three_root(runtime_js) is not None
+
+
+def vendor_path(rel: str, runtime_js: Path | str | None = None) -> Path | None:
+ """Map a ``/vendor/<rel>`` URL onto the vendored three.js tree (or ``None``).
+
+ Only the two whitelisted subtrees are reachable, and :func:`safe_join` still
+ checks the result — a vendor URL can never leave ``node_modules/three``."""
+ from codeverse.gallery.paths import PathError, safe_join
+
+ root = three_root(runtime_js)
+ if root is None:
+ return None
+ for prefix, sub in VENDOR_MAP.items():
+ if rel.startswith(prefix):
+ try:
+ target = safe_join(root, sub + rel[len(prefix):])
+ except PathError:
+ return None
+ return target if target.is_file() else None
+ return None
+
+
+def render_viewer(entry: RunEntry, urls: UrlMaker, rel: str) -> str:
+ """The GLB viewer page for one artifact of a run."""
+ import_map = json.dumps({"imports": {"three": "/vendor/three/build/three.module.js",
+ "three/addons/": "/vendor/three/examples/jsm/"}})
+ src = urls.file(entry, rel)
+ body = (
+ top_bar("3dcv gallery", entry.slug,
+ crumbs=f"<a href='/'>gallery</a> <span class='faint'>/</span> "
+ f"<a href='{esc(urls.detail(entry))}'>{esc(entry.slug)}</a> "
+ f"<span class='faint'>/</span> <b>{esc(rel)}</b>")
+ + "<main class='wrap'>"
+ + f"<div id='stage' data-src='{esc(src)}'><div id='vmsg'>loading {esc(rel)}…</div>"
+ f"<div id='hint'>drag to orbit · scroll to zoom · right-drag to pan</div></div>"
+ + f"<p class='small muted' style='margin-top:var(--s-3)'>bounding box: <span id='dims' class='num'>—</span>"
+ f" · <a href='{esc(src)}'>download the raw GLB</a>"
+ f" · <a href='{esc(urls.detail(entry))}'>back to the run</a></p>"
+ + "</main>" + footer("three.js served from runtime_js/node_modules — no network required")
+ )
+ return page_shell(f"{rel} — {entry.slug}", body, extra_css=VIEWER_CSS,
+ head_extra=f"<script type='importmap'>{import_map}</script>\n",
+ modules=VIEWER_JS)
diff --git a/harness/codeverse/orchestrator/state.py b/harness/codeverse/orchestrator/state.py
index d73f77fd..90e2bab3 100644
--- a/harness/codeverse/orchestrator/state.py
+++ b/harness/codeverse/orchestrator/state.py
@@ -8,11 +8,12 @@ completed, and the best round/commit seen so far. Writes are atomic
from __future__ import annotations
-from datetime import UTC, datetime
+from datetime import datetime
from typing import Any
from pydantic import BaseModel, Field, ValidationError
+from codeverse._compat import UTC
from codeverse.contracts.run import RunStatus
from codeverse.workspace import Workspace
diff --git a/harness/codeverse/spatial/node.py b/harness/codeverse/spatial/node.py
index 5bfc85ad..4d646412 100644
--- a/harness/codeverse/spatial/node.py
+++ b/harness/codeverse/spatial/node.py
@@ -13,8 +13,11 @@ from __future__ import annotations
import contextlib
import json
import os
+import re
import resource
+import subprocess
from dataclasses import dataclass, field
+from functools import lru_cache
from pathlib import Path
from typing import Any
@@ -23,6 +26,18 @@ from codeverse.proc import run_subprocess
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``.
+NODE_MIN: tuple[int, int, int] = (20, 6, 0)
+NODE_MIN_STR = ".".join(str(n) for n in NODE_MIN)
+
+_VERSION_RE = re.compile(r"v?(\d+)\.(\d+)\.(\d+)")
+
class NodeError(RuntimeError):
"""A node script failed (non-zero exit, timeout or missing binary).
@@ -95,6 +110,48 @@ def _limit_memory(limit_gb: float | None):
return _pre
+def parse_node_version(text: str) -> tuple[int, int, int] | None:
+ """``"v20.6.1\\n"`` -> ``(20, 6, 1)``; None when the output is not a version."""
+ m = _VERSION_RE.search(text.strip())
+ return (int(m.group(1)), int(m.group(2)), int(m.group(3))) if m else 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.
+ """
+ try:
+ proc = subprocess.run([node_bin, "--version"], capture_output=True, text=True,
+ timeout=20, check=False)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ return parse_node_version(proc.stdout or proc.stderr) if proc.returncode == 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.
+ """
+ if version is None or version >= NODE_MIN:
+ return ""
+ got = ".".join(str(n) for n in version)
+ return (f"node {got} is too old: 3dcodeverse needs node >= {NODE_MIN_STR} "
+ f"(`--import` module hooks; see runtime_js/package.json \"engines\"). "
+ f"Install a newer one (`nvm install --lts`, or https://nodejs.org) and put it on PATH, "
+ f"or point the harness at it with CV3D_BINARIES__NODE=/path/to/node.")
+
+
+def require_node_version(node_bin: str) -> None:
+ """Raise :class:`NodeError` when ``node_bin`` is older than :data:`NODE_MIN`."""
+ msg = node_version_error(node_version(node_bin))
+ if msg:
+ raise NodeError(msg)
+
+
def run_node(
script: Path | str,
args: list[str] | None = None,
@@ -118,6 +175,7 @@ def run_node(
"""
settings = get_settings()
node_bin = settings.binaries.node
+ require_node_version(node_bin)
script = Path(script)
if not script.is_file():
raise NodeError(f"node script not found: {script}")
diff --git a/harness/codeverse/tracks/lifecycle.py b/harness/codeverse/tracks/lifecycle.py
index e9afd078..4aec24d4 100644
--- a/harness/codeverse/tracks/lifecycle.py
+++ b/harness/codeverse/tracks/lifecycle.py
@@ -14,10 +14,11 @@ import platform
import traceback
from collections.abc import Sequence
from dataclasses import replace
-from datetime import UTC, datetime
+from datetime import datetime
from pathlib import Path
from typing import Any
+from codeverse._compat import UTC
from codeverse.config import Settings, get_settings
from codeverse.contracts.artifacts import GateReport
from codeverse.contracts.common import Track, Usage
diff --git a/harness/codeverse/tracks/steps.py b/harness/codeverse/tracks/steps.py
index f4a08b60..a170d9f1 100644
--- a/harness/codeverse/tracks/steps.py
+++ b/harness/codeverse/tracks/steps.py
@@ -23,10 +23,11 @@ from __future__ import annotations
import logging
import time
from collections.abc import Sequence
-from datetime import UTC, datetime
+from datetime import datetime
from pathlib import Path
from typing import Any, Protocol
+from codeverse._compat import UTC
from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, RenderSet
from codeverse.contracts.common import Usage
from codeverse.contracts.judgment import Judgment
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 07bda81f..2e73519b 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -66,6 +66,8 @@ the flywheel unit.
```
codeverse/
+ _compat.py the ONLY stdlib shims for the python floor (StrEnum, UTC, tomllib — all 3.11+;
+ floor is 3.10, see docs/INSTALL.md §2.1). Its docstring says when each dies
conventions.py frames (LANGUAGE_FRAME, GLB_FRAME), units, OBJECT_VIEWS/_QUICK, SCENE_VIEWS,
to_snake/to_pascal/slugify, MAX_TRIS_*, BBOX_TOLERANCE_M, CONTACT_GAP_M (THE source)
config.py Settings (CV3D_* env, ~/.config/codeverse/config.yaml; role defaults come from
@@ -112,10 +114,18 @@ codeverse/
common.py (RunContext, Services), motion.py, reference.py, static_object.py,
articulated_object.py, scene.py, scene_assets.py, graphics.py + graphics_steps.py
flywheel/ record.py, export.py, pack.py, sample.py, pairs.py, trajectories.py (repair-pair
- mining), captions.py, quality.py (tiers + dedupe), gallery.py, dedupe.py, index.py
+ mining), captions.py, quality.py (tiers + dedupe), gallery.py (the shared
+ self-contained renderer bench/report.py reuses), dedupe.py, index.py
+ gallery/ THE local run gallery (`3dcv gallery serve|build`): index.py (run roots →
+ typed RunEntry, tolerant of half-written records), model.py, page.py (cards +
+ table + filters + per-filter summary), detail.py (/run/<battery>/<slug>),
+ code.py (src browser), viewer.py (GLB orbit viewer on the vendored three.js),
+ paths.py (traversal guard), urls.py (server vs file:// targets + content types),
+ server.py (stdlib http.server, loopback-only), static_site.py, theme.py, scripts.py
prompts/ system/*, <lang>/{contract,cookbook}.md (incl. glsl_shader/, opengl_python/),
texturing/*.md, tracks/*.j2 (incl. plan/generate/refine_graphics.j2)
- cli/ main.py, tools_cmd.py, flywheel_cmd.py, bench_cmd.py, texture_cmd.py, doctor.py
+ cli/ main.py, tools_cmd.py, flywheel_cmd.py, gallery_cmd.py, bench_cmd.py,
+ texture_cmd.py, doctor.py
bench/ run_bench.py, report.py (reuses flywheel gallery), compare_backends.py,
prompts/{static_objects_v1 (24), articulated_v1 (12), scenes_v1 (12), compare_v1 (8)}.yaml
runtime_js/ export_glb.mjs (placement policy, instance baking, selfcheck) render_glb.mjs
@@ -337,3 +347,13 @@ repair pairs and **in-session repair pairs mined from api-agent transcripts**
{detailed, instruction, factory} captions (image-grounded, brand-free, `--out` for
side-car mode); `flywheel gallery` renders a self-contained HTML gallery (tier
badges, thumbnails, filter/sort) that `bench/report.py` reuses.
+
+`codeverse/gallery/` is the **local** answer to the same question: `3dcv gallery
+serve` indexes `runs/` + every `bench/out/*/runs`, serves the page **and the run
+directories** on 127.0.0.1 (so every link opens: sheet, renders, `src/`, `object.glb`
+in an orbit viewer built on the vendored three.js, `record.json`), and re-reads a
+run's record per request so a battery that is still writing shows up live. A run
+with no record yet is a *pending* card, a half-written one a *broken* card. Two
+gates keep it safe: a URL can only name a `(battery, slug)` the scanner found under
+a declared root, and `paths.safe_join` refuses anything that escapes that run
+directory. `3dcv gallery build [--embed]` writes the same page as one file.
diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.md
index 16e659e7..7b93b313 100644
--- a/harness/docs/INSTALL.md
+++ b/harness/docs/INSTALL.md
@@ -8,7 +8,8 @@ to the harness root `/home/yipeng/3dcodeverse/harness` unless absolute.
Once installed, read `docs/RUNBOOK.md` (how to run), `docs/ARCHITECTURE.md`
(what a run does) and `CLAUDE.md` (working rules).
-1. [TL;DR](#1-tldr) · 2. [Prerequisites](#2-prerequisites) ·
+1. [TL;DR](#1-tldr) · 2. [Prerequisites](#2-prerequisites)
+(incl. [supported versions](#21-supported-versions)) ·
3. [Get the code](#3-get-the-code) · 4. [Python package + extras](#4-python-package--extras) ·
5. [runtime_js — the node side](#5-runtime_js--the-node-side) · 6. [Blender](#6-blender) ·
7. [GPU / headless rendering](#7-gpu--headless-rendering) ·
@@ -50,15 +51,41 @@ cd harness/runtime_js && npm ci && npx puppeteer browsers install chrome && cd .
## 2. Prerequisites
+### 2.1 Supported versions
+
+The harness is **developed and measured on python 3.13 / node 24**, and
+**supported down to python 3.10 / node 20.6** — both ends are installed from
+scratch and run in CI on every push (`.github/workflows/ci.yml`), so the floor is
+a tested claim, not an aspiration.
+
+| component | floor | developed on | how the floor is enforced | what you lose at the floor |
+|---|---|---|---|---|
+| **python** | **3.10** | 3.13 | `requires-python = ">=3.10"` (pip refuses 3.9); ruff `target-version = "py310"`; CI matrix 3.10 + 3.13; `tests/core/test_portability.py` parses every module with `ast.parse(feature_version=(3, 10))` and bans direct imports of 3.11-only stdlib names | nothing — the offline suite is green on both (2413 passed / 1 skipped on 3.10 vs 2414 passed on 3.13; the one skip is the `enum.StrEnum` parity check, which needs 3.11 to have something to compare against). Resolved deps are a little older (numpy 2.2 vs 2.4, scipy 1.15 vs 1.18, networkx 3.4 vs 3.6, cadquery 2.7 vs 2.8) and pip additionally installs `tomli` |
+| **node** | **20.6.0** | 24 (LTS) | `runtime_js/package.json` `engines.node`; `codeverse.spatial.node.NODE_MIN` fails every node workload with an actionable message; `3dcv doctor`'s `node` row; `scripts/setup.sh` | nothing. 20.6.0 is where `node --import` lands, which the `three` resolver hook needs; below 22.15 it registers the older async loader hooks (`lib/resolve_three_async.mjs`) instead of the in-thread ones — same resolutions, a few ms slower at startup. Verified: all 93 `node`-marked tests (GLB export, headless-Chrome renders, scene probes, shader preflight) pass on node 20.19.5 |
+| **Blender** | 4.2 | 5.0.1 | runtime probe only (`Settings.resolve_blender()`) | untested below 4.2; the `blender` / `urdf_blender` languages are the only users |
+| **OS** | Linux x86_64 | WSL2 Ubuntu | — | macOS should work (pure-python + node + Blender; no code is Linux-specific except `resource.setrlimit` guards) but is **not** tested. Windows is not supported: use WSL2 |
+
+Python 3.11 and 3.12 are in the middle of a range whose two ends CI proves, and
+are not run separately. The three 3.11 stdlib names the harness wants —
+`enum.StrEnum`, `datetime.UTC`, `tomllib` — live behind `codeverse/_compat.py`,
+whose docstring says exactly when each shim can be deleted (when the floor
+reaches 3.11). Nothing else in the package is newer than 3.10.
+
+Raising the floor later is a four-line change: `requires-python`, ruff's
+`target-version`, `PY_FLOOR` in `tests/core/test_portability.py`, `MIN_PY_MINOR`
+in `scripts/setup.sh` — the test will then tell you which shims to delete.
+
+### 2.2 What you need installed
+
| what | required? | verified here | how it degrades without it |
|---|---|---|---|
-| **Python 3.11+** | yes | 3.13.9 (`/home/yipeng/miniconda3/bin/python`) | nothing runs; `requires-python = ">=3.11"` |
+| **Python 3.10+** | yes | 3.13.9 (`/home/yipeng/miniconda3/bin/python`) | nothing runs; `requires-python = ">=3.10"` (§2.1) |
| **git** | yes | 2.53.0 | run workspaces are git repos (one commit per round); `Workspace.create()` and the flywheel trajectory/pair miners fail |
-| **node ≥ 20** | yes, except for the `graphics` track | v24.14.0 (npm 11.9.0) | the `threejs` / `scene_threejs` languages disappear **and no object renders happen at all**: `spatial/render.py` renders *every* GLB (Blender-built and CadQuery-built included) with three.js in headless Chrome. Only `graphics` (moderngl) is node-free |
+| **node ≥ 20.6** | yes, except for the `graphics` track | v24.14.0 (npm 11.9.0) | the `threejs` / `scene_threejs` languages disappear **and no object renders happen at all**: `spatial/render.py` renders *every* GLB (Blender-built and CadQuery-built included) with three.js in headless Chrome. Only `graphics` (moderngl) is node-free |
| **Blender 4.2+ / 5.x** | optional | 5.0.1 (`~/.local/bin/blender-5.0`) | `blender` and `urdf_blender` languages unavailable → the `static_object` default language and the whole `articulated_object` track cannot build (`BlenderNotFoundError`); scenes lose planner-chosen bpy GLB assets |
| **ffmpeg** | optional | **not installed** | `render_turntable` silently writes an animated **GIF** via PIL instead of `.mp4` (`spatial/turntable.py`); nothing else changes |
| **EGL-capable GPU stack** | optional | ANGLE / D3D12 / RTX 5090 Laptop | headless Chrome falls back to **SwiftShader** and moderngl to **llvmpipe** — everything still renders, just several times slower; no correctness change |
-| C toolchain | usually no | — | only if pip has to build a wheel from source (`python-fcl`, `manifold3d` ship wheels for cp311–cp313 x86_64) |
+| C toolchain | usually no | — | only if pip has to build a wheel from source (`python-fcl`, `manifold3d` ship wheels for cp310–cp313 x86_64) |
Disk: ~100 MB for `runtime_js/node_modules`, ~640 MB for puppeteer's Chrome,
~1 GB for a Blender tarball, plus whatever `runs/` and `~/.cache/codeverse` grow
@@ -446,7 +473,7 @@ that the keys work end to end):
| `python deps` | FAIL | a core import is missing/broken | `pip install -e 'harness[all]'`; a broken native lib (`fcl`, `manifold3d`) shows up here too — reinstall that wheel (`pip install --force-reinstall python-fcl`) |
| `python deps` | WARN | only `manifold3d` / `yourdfpy` / `mcp` / `shapely` missing | install the matching extra: `pip install -e 'harness[mesh,urdf,mcp]'` (§4) |
| `blender` | FAIL | no binary found, or `--version` failed | §6 — install Blender, or `export CV3D_BINARIES__BLENDER=/path/to/blender`. If it is found but fails, run it by hand: a `libSM.so.6`/`libICE.so.6` error means you need the `LD_LIBRARY_PATH` wrapper |
-| `node` | FAIL | node missing or < 20 | install node 20+ (`nvm install 24`) or set `binaries.node` |
+| `node` | FAIL | node missing or older than 20.6.0 (§2.1) | install a newer node (`nvm install --lts`) or point `binaries.node` / `CV3D_BINARIES__NODE` at one. The same check fires from every node workload (`codeverse.spatial.node.run_node`), so a too-old node cannot fail obscurely mid-render |
| `three` | FAIL | `runtime_js/node_modules/three` missing | `cd harness/runtime_js && npm ci` (§5) |
| `puppeteer` | FAIL | not installed in `runtime_js` | `cd harness/runtime_js && npm ci` |
| `puppeteer` | WARN | installed, but no Chrome in `~/.cache/puppeteer` | `cd harness/runtime_js && npx puppeteer browsers install chrome` (or unset `PUPPETEER_SKIP_DOWNLOAD` / fix `PUPPETEER_CACHE_DIR`) |
@@ -544,9 +571,9 @@ those by hand (`npm rm -g @google/gemini-cli @anthropic-ai/claude-code @openai/c
| component | version | where |
|---|---|---|
-| python | 3.13.9 | `/home/yipeng/miniconda3/bin/python` |
+| python | 3.13.9 (floor 3.10 — §2.1, verified in a clean 3.10.21 venv) | `/home/yipeng/miniconda3/bin/python` |
| pip packages | pydantic 2.13.2 · trimesh 4.12.2 · python-fcl 0.7.0.11 · moderngl 5.12.0 · shapely 2.1.2 · networkx 3.6.1 · manifold3d 3.5.2 · pyarrow 24.0.0 · mcp 2.0.0 · scipy 1.18.0 · yourdfpy 0.0.60 · cadquery 2.8.0 · google-genai 2.10.0 · pytest 9.1.1 · ruff 0.15.20 | editable install of `harness/` |
-| node / npm | v24.14.0 / 11.9.0 | `/home/yipeng/miniconda3/bin/node` |
+| node / npm | v24.14.0 / 11.9.0 (floor 20.6.0 — §2.1, verified against node 20.19.5) | `/home/yipeng/miniconda3/bin/node` |
| runtime_js deps | three 0.182.0 · puppeteer 24.43.1 · three-mesh-bvh 0.9.14 (100 packages, 97 MB) | `harness/runtime_js/node_modules` |
| Chrome (puppeteer) | 148.0.7778.97 (+ headless-shell) | `~/.cache/puppeteer` |
| Blender | 5.0.1 (2025-12-16) | `~/.local/bin/blender-5.0` → `~/3dcodeverse_data/tools/blender-5.0.1-linux-x64` |
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 667a46c2..101c89ab 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -198,7 +198,14 @@ export+render live in `runtime_js/` (`export_glb.mjs`, `render_glb.mjs`,
**Placement policy (all languages)**: nothing re-centres or drops to ground at
export; the build warns and the contract/connectivity gates report it.
**Δ Node ESM resolution**: bare `import 'three'` needs
-`run_node(..., three_hook=True)` (`--import runtime_js/lib/resolve_three.mjs`).
+`run_node(..., three_hook=True)` (`--import runtime_js/lib/resolve_three.mjs`;
+`module.registerHooks` on node >= 22.15, `module.register` +
+`lib/resolve_three_async.mjs` down to the 20.6 floor — same resolutions).
+**Δ Node floor**: `spatial.node.NODE_MIN = (20, 6, 0)` is the single source of truth
+(`runtime_js/package.json` `engines.node` mirrors it). `run_node` calls
+`require_node_version()` before spawning, so an old node raises `NodeError` with the fix
+in the message instead of failing obscurely; `parse_node_version` / `node_version_error`
+are the pure helpers `3dcv doctor` reuses for its `node` row.
## spatial/
```python
@@ -359,11 +366,19 @@ from codeverse.flywheel.captions import caption_sample # Δ (ws, record, model_i
# out_dir → side-car <out_dir>/<slug>.json, run untouched
from codeverse.flywheel.gallery import write_gallery, gallery_items, render_gallery # self-contained HTML gallery (tier badges,
# thumbs); bench/report.py reuses it
+from codeverse.gallery import build_index, default_roots, build_static, serve, GalleryApp # THE local gallery
+ # build_index(roots) -> GalleryIndex (sections of RunEntry; never raises per run)
+ # build_static(roots, out_html, *, embed=False) -> (path, n, index)
+ # GalleryApp(roots, reload=False).route(path, query) -> Response (pure, testable)
+ # serve(roots, *, host=None, host_explicit=False, port=8765, reload=False)
+from codeverse.gallery.paths import safe_join # (root, rel) -> Path inside root, else PathError
+from codeverse.gallery.urls import content_type # .glb→model/gltf-binary, .py/.js/.frag→text/plain; charset=utf-8
from codeverse.flywheel.index import build_index, query, summary # sqlite + parquet: adds quality_tier, gate_errors, cost_usd,
# rounds, status, code_fingerprint, prompt_hash, duplicate_of, has_captions
3dcodeverse make [--profile economy|balanced|quality]|resume|status|show|render|judge|tools|mcp
|texture {pass,scene-pack,show}|cost {<slug>,show,cache,prices,profiles,estimate}
- |flywheel {export,pairs,caption,index,dedupe,gallery}|bench {run,report}|doctor # alias: 3dcv
+ |flywheel {export,pairs,caption,index,dedupe,gallery}|gallery {serve,build}
+ |bench {run,report}|doctor # alias: 3dcv
```
## Events and records
diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.md
index c5f5c343..726d4507 100644
--- a/harness/docs/RUNBOOK.md
+++ b/harness/docs/RUNBOOK.md
@@ -111,6 +111,34 @@ artifacts in `artifacts/` (`object.glb`, `robot.urdf` + `meshes/`, scene
`3dcv status <slug>` prints the rounds table (best round starred), cost and the last
events.
+### Looking at results locally
+
+```bash
+3dcv gallery serve # ./runs + every ./bench/out/*/runs → http://127.0.0.1:8765/
+3dcv gallery serve bench/out/static_v2_flash/runs --port 9000 --reload --no-open
+3dcv gallery build --out gallery.html [--embed] # one self-contained file (--embed inlines the sheets)
+3dcv flywheel gallery runs/ gallery.html # alias of `gallery build --embed` (old signature)
+```
+`serve` indexes the run roots (records only — ~85 runs in ~0.15 s) and serves the run
+**directories** too, so every link works: contact sheet, full-size renders, `record.json`,
+`plan.json`/`spec.json`, the `src/` tree (browsable, line-numbered, `raw` = text/plain),
+`object.glb` (orbit viewer on the vendored three.js — no network), articulation sheets,
+`preview.gif`, frames, textures. The page has a live summary strip (n, pass rate,
+mean/median score, total $, $ per passing artifact, wall clock — **recomputed per filter**),
+filters (track / language / tier / backend / verdict / battery + text search over
+prompt+slug) and sort (score / cost / time / name) that never reload, a card ⇄ table
+toggle, light/dark, and a detail page per run (`/run/<battery>/<slug>`) with every round,
+the best round's judge verdict + issues + improvement plan, the measurement table, the
+full render set, the cost breakdown and the code.
+
+Filters live in the query string, so a view can be curled or bookmarked:
+`curl -s 'http://127.0.0.1:8765/?track=graphics&tier=A&sort=cost'`, and
+`/api/runs?...` / `/api/summary?...` return the same selection as JSON.
+`--reload` re-scans on every page load, which is what you want while a bench is writing:
+a run with no `record.json` yet shows as a *pending* card and a half-written one as
+*broken*, never as a crash. The server binds `127.0.0.1` and refuses any other address
+unless you type `--host` yourself; it never serves a path outside the declared roots.
+
## 5. Resume, re-render, re-judge, texture, export
```bash
@@ -125,7 +153,7 @@ events.
[--captions-dir caps/] [--drop-duplicates]
3dcv flywheel pairs runs/ pairs.jsonl [--min-delta 0.05] [--no-trajectories]
3dcv flywheel caption <slug> [--model …] [--out caps/] # --out = side-car mode, run untouched
-3dcv flywheel gallery runs/ gallery.html [--title …] # self-contained HTML gallery (tiers, thumbs)
+3dcv flywheel gallery runs/ gallery.html [--title …] # alias of `3dcv gallery build --embed` (§4)
3dcv flywheel index runs/ runs_index.sqlite · 3dcv flywheel dedupe dataset/
python -m codeverse.judges.calibration runs/<slug> [runs/<slug2> …] --model gemini:gemini-3.1-pro-preview --n 3 --out out/
# re-judges recorded rounds; writes calibration_<model>.md/.json (never touches runs/)
diff --git a/harness/pyproject.toml b/harness/pyproject.toml
index 70cd96c9..2abcb8b3 100644
--- a/harness/pyproject.toml
+++ b/harness/pyproject.toml
@@ -7,8 +7,21 @@ name = "3dcodeverse"
version = "0.1.0"
description = "3dcodeverse: a data-flywheel harness for LLM-written 3D code (Blender / CadQuery / Three.js / URDF / GLSL) across static objects, articulated objects and scenes."
readme = "README.md"
-requires-python = ">=3.11"
+# Floor = 3.10 (the oldest interpreter the whole dependency set still resolves on and the
+# offline suite is green on); developed and measured on 3.13. CI runs both ends.
+# Nothing in the package uses a 3.11+ stdlib name directly — the three that were used
+# (StrEnum, datetime.UTC, tomllib) live behind codeverse/_compat.py.
+requires-python = ">=3.10"
license = { text = "Apache-2.0" }
+classifiers = [
+ "License :: OSI Approved :: Apache Software License",
+ "Programming Language :: Python :: 3.10",
+ "Programming Language :: Python :: 3.11",
+ "Programming Language :: Python :: 3.12",
+ "Programming Language :: Python :: 3.13",
+ "Operating System :: POSIX :: Linux",
+ "Operating System :: MacOS",
+]
dependencies = [
"pydantic>=2.7",
"pydantic-settings>=2.3",
@@ -25,6 +38,7 @@ dependencies = [
"anthropic>=0.40",
"openai>=1.40",
"playwright>=1.45",
+ 'tomli>=2.0; python_version < "3.11"', # stdlib `tomllib` backport — see codeverse/_compat.py
]
[project.optional-dependencies]
@@ -50,7 +64,7 @@ codeverse = ["prompts/**/*", "judges/rubrics/*.yaml", "languages/**/wrappers/*",
[tool.ruff]
line-length = 100
-target-version = "py311"
+target-version = "py310" # == requires-python floor: no 3.11+ idiom may slip in
[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP", "SIM"]
diff --git a/harness/runtime_js/README.md b/harness/runtime_js/README.md
index 066cc166..6ff6b574 100644
--- a/harness/runtime_js/README.md
+++ b/harness/runtime_js/README.md
@@ -11,8 +11,20 @@ never imports from this directory**; it only imports `three` (and
This directory is an ordinary npm package owned by the harness: `package.json`
and `package-lock.json` are committed, `node_modules/` is **not** (gitignored,
-~97 MB, 100 packages). Node itself is a system prerequisite (>= 20; v24.14.0
-here) — installing it is separate from what `npm ci` does here.
+~97 MB, 100 packages). Node itself is a system prerequisite — installing it is
+separate from what `npm ci` does here.
+
+**Node floor: 20.6.0** (`package.json` `engines.node`; developed on v24.14.0).
+20.6.0 is where `node --import` lands, which `lib/resolve_three.mjs` needs; the
+npm dependencies themselves bottom out at node 18, and `node:util.parseArgs`
+(the CLI helpers) at 18.3. Between 20.6 and 22.15 the resolver registers the
+older *async* loader hooks (`lib/resolve_three_async.mjs`, a separate loader
+thread) instead of the in-thread `module.registerHooks`; the resolutions are
+identical. The python side refuses to spawn an older node with an actionable
+message (`codeverse.spatial.node.NODE_MIN`, mirrored by `3dcv doctor`'s `node`
+row), and `tests/core/test_portability.py` pins the two declarations together.
+The floor is exercised, not assumed: the 93 `node`-marked tests all pass on node
+20.19.5 (`CV3D_BINARIES__NODE=/path/to/node20 pytest tests -m "node and not live and not blender"`).
```bash
cd harness/runtime_js
@@ -58,7 +70,9 @@ render_glb.mjs --glb --out --views '[{name,azimuth,elevation}]' [--mode s
args/JSON protocol from lib/cli.mjs, browser + server from lib/host_env.mjs,
browser release from lib/host_page.mjs, everything visual from lib/browser/
lib/resolve_three.mjs node --import hook: bare 'three' / 'three/addons/*' (and three-mesh-bvh) resolve
- from runtime_js/node_modules for modules anywhere on disk (NODE_PATH is CJS-only)
+ from runtime_js/node_modules for modules anywhere on disk (NODE_PATH is CJS-only);
+ module.registerHooks on node >= 22.15, module.register + lib/resolve_three_async.mjs
+ on the 20.6 floor. Redirect rule stated once in lib/three_redirect.mjs
lib/node_polyfills.mjs FileReader/Blob/self shims so GLTFExporter writes binary GLB without a DOM
lib/census.mjs per-part tri counts, world bboxes, materials, NaN check naming mesh + part (node + browser)
lib/instances.mjs bakeInstancedMeshes(THREE, root): InstancedMesh → Group of named plain meshes
diff --git a/harness/runtime_js/lib/resolve_three.mjs b/harness/runtime_js/lib/resolve_three.mjs
index 832c6371..2b0c55d9 100644
--- a/harness/runtime_js/lib/resolve_three.mjs
+++ b/harness/runtime_js/lib/resolve_three.mjs
@@ -6,27 +6,32 @@
// Every bare specifier that is `three` or `three/...` is re-resolved as if it
// were imported from runtime_js/, i.e. from runtime_js/node_modules/three with
// its exports map (`three/addons/*` -> examples/jsm/*). Nothing else is touched.
+//
+// Two node APIs do this, and the floor (node 20.6, see ../package.json
+// "engines") only has the older one:
+// * `module.registerHooks` (node >= 22.15 / 23.5) — synchronous, in-thread,
+// no worker, no serialisation. Preferred when present.
+// * `module.register` (node >= 20.6) — the original async hooks, run on a
+// separate loader thread (./resolve_three_async.mjs).
+// Both produce the same resolutions; drop the fallback when the node floor
+// reaches 22.15.
-import { registerHooks } from 'node:module';
-import { pathToFileURL } from 'node:url';
-import path from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-const RUNTIME_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
-// Must end with '/' so it acts as a directory parent for resolution.
-const RUNTIME_PARENT = pathToFileURL(RUNTIME_DIR + path.sep).href;
-
-const REDIRECTED = ['three', 'three-mesh-bvh'];
+import module from 'node:module';
+import { RUNTIME_PARENT, isRedirected } from './three_redirect.mjs';
-function isRedirected(spec) {
- return REDIRECTED.some((p) => spec === p || spec.startsWith(p + '/'));
+if (typeof module.registerHooks === 'function') {
+ module.registerHooks({
+ resolve(specifier, context, nextResolve) {
+ if (isRedirected(specifier)) {
+ return nextResolve(specifier, { ...context, parentURL: RUNTIME_PARENT });
+ }
+ return nextResolve(specifier, context);
+ },
+ });
+} else if (typeof module.register === 'function') {
+ module.register('./resolve_three_async.mjs', import.meta.url);
+} else {
+ throw new Error(
+ `3dcodeverse needs node >= 20.6.0 for module loader hooks; this is ${process.version}`,
+ );
}
-
-registerHooks({
- resolve(specifier, context, nextResolve) {
- if (isRedirected(specifier)) {
- return nextResolve(specifier, { ...context, parentURL: RUNTIME_PARENT });
- }
- return nextResolve(specifier, context);
- },
-});
diff --git a/harness/runtime_js/lib/resolve_three_async.mjs b/harness/runtime_js/lib/resolve_three_async.mjs
new file mode 100644
index 00000000..9cf70250
--- /dev/null
+++ b/harness/runtime_js/lib/resolve_three_async.mjs
@@ -0,0 +1,13 @@
+// Async loader hooks (`module.register`, node >= 20.6) — the fallback shape of
+// the redirect in resolve_three.mjs, used on node < 22.15 where the cheaper
+// in-thread `module.registerHooks` does not exist. This module is loaded on
+// node's loader thread; it must not import anything from the application.
+
+import { RUNTIME_PARENT, isRedirected } from './three_redirect.mjs';
+
+export async function resolve(specifier, context, nextResolve) {
+ if (isRedirected(specifier)) {
+ return nextResolve(specifier, { ...context, parentURL: RUNTIME_PARENT });
+ }
+ return nextResolve(specifier, context);
+}
diff --git a/harness/runtime_js/lib/three_redirect.mjs b/harness/runtime_js/lib/three_redirect.mjs
new file mode 100644
index 00000000..e222158c
--- /dev/null
+++ b/harness/runtime_js/lib/three_redirect.mjs
@@ -0,0 +1,18 @@
+// Which bare specifiers get re-resolved as if imported from runtime_js/, and
+// from where. Shared by the two loader-hook shapes in resolve_three.mjs so the
+// redirect rule is stated once (the async hook runs on its own loader thread and
+// cannot see the sync hook's module scope).
+
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const RUNTIME_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+/** Parent URL to resolve from; must end with '/' so it acts as a directory. */
+export const RUNTIME_PARENT = pathToFileURL(RUNTIME_DIR + path.sep).href;
+
+const REDIRECTED = ['three', 'three-mesh-bvh'];
+
+export function isRedirected(spec) {
+ return REDIRECTED.some((p) => spec === p || spec.startsWith(p + '/'));
+}
diff --git a/harness/runtime_js/package-lock.json b/harness/runtime_js/package-lock.json
index c9c18c5d..a1499da0 100644
--- a/harness/runtime_js/package-lock.json
+++ b/harness/runtime_js/package-lock.json
@@ -11,6 +11,9 @@
"puppeteer": "^24.43.1",
"three": "^0.182.0",
"three-mesh-bvh": "^0.9.0"
+ },
+ "engines": {
+ "node": ">=20.6.0"
}
},
"node_modules/@babel/code-frame": {
diff --git a/harness/runtime_js/package.json b/harness/runtime_js/package.json
index aa9322bf..4c3f8a18 100644
--- a/harness/runtime_js/package.json
+++ b/harness/runtime_js/package.json
@@ -4,6 +4,9 @@
"version": "0.1.0",
"description": "Harness-owned node runtime for 3dcodeverse: GLB export, headless GPU rendering, scene probes, shader preflight. Agent code never imports from here; it only imports 'three'.",
"type": "module",
+ "engines": {
+ "node": ">=20.6.0"
+ },
"dependencies": {
"three": "^0.182.0",
"puppeteer": "^24.43.1",
diff --git a/harness/scripts/setup.sh b/harness/scripts/setup.sh
index 64bee889..0d9a8a36 100755
--- a/harness/scripts/setup.sh
+++ b/harness/scripts/setup.sh
@@ -3,15 +3,18 @@
#
# bash harness/scripts/setup.sh [options]
#
-# Does, in order: version checks (python >= 3.11, node >= 20) -> `pip install -e
+# Does, in order: version checks (python >= 3.10, node >= 20.6) -> `pip install -e
# harness[<extras>]` -> `npm ci` in runtime_js *only when the lockfile moved* ->
# puppeteer chrome download (no-op when cached) -> `3dcodeverse doctor`.
# Re-running is safe: every step is a no-op when it is already satisfied.
# Full guide: docs/INSTALL.md
set -euo pipefail
-MIN_PY_MINOR=11 # python 3.11+
-MIN_NODE_MAJOR=20 # node 20+
+# The supported floor (docs/INSTALL.md §2.1). Pinned to pyproject's requires-python
+# and to codeverse/spatial/node.py NODE_MIN by tests/core/test_portability.py.
+MIN_PY_MINOR=10 # python 3.10+
+MIN_NODE_MAJOR=20 # node 20.6+ (`node --import` module hooks)
+MIN_NODE_MINOR=6
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
HARNESS="$(cd "$HERE/.." && pwd)"
@@ -68,7 +71,7 @@ die() { printf '\033[31merror:\033[0m %s\n' "$*" >&2; exit 1; }
# --------------------------------------------------------------- prerequisites
step "prerequisites"
-command -v "$PY" >/dev/null 2>&1 || die "python interpreter not found: $PY (install python 3.11+ or pass --python)"
+command -v "$PY" >/dev/null 2>&1 || die "python interpreter not found: $PY (install python 3.$MIN_PY_MINOR+ or pass --python)"
PY_VER="$("$PY" -c 'import sys; print("%d.%d.%d" % sys.version_info[:3])')"
"$PY" -c "import sys; sys.exit(0 if sys.version_info[:2] >= (3, $MIN_PY_MINOR) else 1)" \
|| die "python 3.$MIN_PY_MINOR+ required, found $PY_VER ($PY)"
@@ -80,10 +83,12 @@ info "git $(git --version | awk '{print $3}')"
NODE_OK=1
if command -v node >/dev/null 2>&1; then
NODE_VER="$(node --version)" # vNN.NN.NN
- NODE_MAJOR="${NODE_VER#v}"; NODE_MAJOR="${NODE_MAJOR%%.*}"
- if [ "$NODE_MAJOR" -lt "$MIN_NODE_MAJOR" ]; then
+ NODE_NUM="${NODE_VER#v}"
+ NODE_MAJOR="${NODE_NUM%%.*}"; NODE_REST="${NODE_NUM#*.}"; NODE_MINOR="${NODE_REST%%.*}"
+ if [ "$NODE_MAJOR" -lt "$MIN_NODE_MAJOR" ] \
+ || { [ "$NODE_MAJOR" -eq "$MIN_NODE_MAJOR" ] && [ "$NODE_MINOR" -lt "$MIN_NODE_MINOR" ]; }; then
NODE_OK=0
- info "node $NODE_VER (need >= $MIN_NODE_MAJOR — three.js / scene / GLB tracks will not run)"
+ info "node $NODE_VER (need >= $MIN_NODE_MAJOR.$MIN_NODE_MINOR — three.js / scene / GLB tracks will not run)"
else
info "node $NODE_VER"
fi
diff --git a/harness/tests/core/test_portability.py b/harness/tests/core/test_portability.py
new file mode 100644
index 00000000..b75fc820
--- /dev/null
+++ b/harness/tests/core/test_portability.py
@@ -0,0 +1,231 @@
+"""Guards for the supported-version floor (docs/INSTALL.md §2.1 "Supported versions").
+
+The harness is developed on python 3.13 / node 24 but must install and run on
+python 3.10 / node 20.6. Nothing here needs either of those installed: the
+python guards read the tree, and the node guards drive the version logic with
+fakes. Three things are pinned:
+
+* the floors agree across ``pyproject.toml``, ``ruff``, ``scripts/setup.sh``,
+ ``codeverse/spatial/node.py`` and ``runtime_js/package.json``;
+* no module reaches past the floor — no 3.12 syntax, and the three 3.11 stdlib
+ names the harness needs come from ``codeverse/_compat`` and nowhere else;
+* the ``StrEnum`` shim behaves exactly like ``enum.StrEnum``.
+"""
+
+from __future__ import annotations
+
+import ast
+import enum
+import json
+import re
+from datetime import datetime, timezone
+from pathlib import Path
+
+import pytest
+
+from codeverse._compat import UTC, StrEnum, tomllib
+from codeverse.spatial.node import (
+ NODE_MIN,
+ NODE_MIN_STR,
+ NodeError,
+ node_version_error,
+ parse_node_version,
+ require_node_version,
+)
+
+HARNESS = Path(__file__).resolve().parents[2]
+PY_FLOOR = (3, 10)
+PY_FLOOR_STR = "3.10"
+COMPAT = HARNESS / "codeverse" / "_compat.py"
+
+#: stdlib names added in 3.11 that must be imported from ``codeverse._compat`` instead
+FLOOR_VIOLATIONS = {
+ ("enum", "StrEnum"): "codeverse._compat.StrEnum",
+ ("datetime", "UTC"): "codeverse._compat.UTC",
+ ("tomllib", None): "codeverse._compat.tomllib",
+}
+
+
+def _py_files() -> list[Path]:
+ out: list[Path] = []
+ for sub in ("codeverse", "bench", "tests"):
+ out += [p for p in (HARNESS / sub).rglob("*.py") if "__pycache__" not in p.parts]
+ return sorted(out)
+
+
+# --------------------------------------------------------------------- the floors agree
+def test_pyproject_floor_matches_ruff_target() -> None:
+ cfg = tomllib.loads((HARNESS / "pyproject.toml").read_text())
+ assert cfg["project"]["requires-python"] == f">={PY_FLOOR_STR}"
+ assert cfg["tool"]["ruff"]["target-version"] == "py" + PY_FLOOR_STR.replace(".", "")
+ classifiers = cfg["project"]["classifiers"]
+ assert f"Programming Language :: Python :: {PY_FLOOR_STR}" in classifiers
+
+
+def test_setup_script_checks_the_same_floors() -> None:
+ text = (HARNESS / "scripts" / "setup.sh").read_text()
+ assert re.search(rf"^MIN_PY_MINOR={PY_FLOOR[1]}\b", text, re.M), "setup.sh python floor drifted"
+ assert re.search(rf"^MIN_NODE_MAJOR={NODE_MIN[0]}\b", text, re.M), "setup.sh node major floor drifted"
+ assert re.search(rf"^MIN_NODE_MINOR={NODE_MIN[1]}\b", text, re.M), "setup.sh node minor floor drifted"
+
+
+def test_runtime_js_engines_matches_node_min() -> None:
+ pkg = json.loads((HARNESS / "runtime_js" / "package.json").read_text())
+ assert pkg["engines"]["node"] == f">={NODE_MIN_STR}"
+
+
+# ------------------------------------------------------------------- nothing exceeds it
[email protected]("path", _py_files(), ids=lambda p: str(p.relative_to(HARNESS)))
+def test_module_parses_and_stays_on_the_floor(path: Path) -> None:
+ """Floor-version syntax only, and no direct import of a 3.11-only stdlib name."""
+ source = path.read_text()
+ try:
+ tree = ast.parse(source, filename=str(path), feature_version=PY_FLOOR)
+ except SyntaxError as e: # PEP 695 generics / `type X = ...` / anything newer
+ pytest.fail(f"{path.relative_to(HARNESS)} does not parse on python {PY_FLOOR_STR}: {e.msg}")
+
+ if path == COMPAT:
+ return # the one module allowed to name them
+ bad: list[str] = []
+ for node in ast.walk(tree):
+ if isinstance(node, ast.ImportFrom) and node.module:
+ for alias in node.names:
+ use = FLOOR_VIOLATIONS.get((node.module, alias.name))
+ if use:
+ bad.append(f"line {node.lineno}: from {node.module} import {alias.name} -> use {use}")
+ elif isinstance(node, ast.Import):
+ for alias in node.names:
+ use = FLOOR_VIOLATIONS.get((alias.name, None))
+ if use:
+ bad.append(f"line {node.lineno}: import {alias.name} -> use {use}")
+ assert not bad, f"{path.relative_to(HARNESS)}: 3.11+ stdlib name(s) below the floor:\n " + "\n ".join(bad)
+
+
+# ------------------------------------------------------------------------ the shims work
+class Colour(StrEnum):
+ RED = "red"
+ DEEP_BLUE = enum.auto()
+
+
+#: 3.10 has no ``enum.StrEnum`` to compare against — there the shim is the only
+#: implementation, and the absolute assertions below are the whole contract.
+requires_stdlib_strenum = pytest.mark.skipif(
+ not hasattr(enum, "StrEnum"), reason="enum.StrEnum needs python 3.11+"
+)
+
+
+def _std_colour() -> type:
+ class StdColour(enum.StrEnum): # type: ignore[attr-defined]
+ RED = "red"
+ DEEP_BLUE = enum.auto()
+
+ return StdColour
+
+
+def test_str_enum_shim_behaviour() -> None:
+ """What every call site relies on: members are their value, everywhere."""
+ assert str(Colour.RED) == "red"
+ assert f"{Colour.RED}" == "red" and f"{Colour.RED:>5}" == " red"
+ assert "%s" % Colour.RED == "red" # noqa: UP031 — %-formatting is exactly what this asserts
+ assert json.dumps(Colour.RED) == '"red"'
+ assert repr(Colour.RED) == "<Colour.RED: 'red'>"
+ assert isinstance(Colour.RED, str) and Colour.RED == "red" and hash(Colour.RED) == hash("red")
+ assert Colour.DEEP_BLUE == "deep_blue", "auto() must lower-case the member name"
+ assert Colour("red") is Colour.RED
+ assert sorted(Colour) == ["deep_blue", "red"]
+
+
+@requires_stdlib_strenum
+def test_str_enum_shim_matches_the_stdlib() -> None:
+ """On 3.11+ the shim must be indistinguishable from ``enum.StrEnum``."""
+ std_colour = _std_colour()
+ for name in ("RED", "DEEP_BLUE"):
+ shim, std = Colour[name], std_colour[name]
+ assert str(shim) == str(std)
+ assert f"{shim}" == f"{std}"
+ assert f"{shim:>8}" == f"{std:>8}"
+ assert "%s" % shim == "%s" % std # noqa: UP031 — %-formatting is exactly what this asserts
+ assert json.dumps(shim) == json.dumps(std)
+ assert repr(shim).split(".", 1)[1] == repr(std).split(".", 1)[1]
+ assert shim.value == std.value and shim.name == std.name
+
+
+def test_str_enum_shim_serialises_through_pydantic() -> None:
+ from pydantic import BaseModel
+
+ class M(BaseModel):
+ shim: Colour
+
+ m = M(shim="red")
+ assert m.model_dump_json() == '{"shim":"red"}'
+ assert m.model_dump(mode="json") == {"shim": "red"}
+ assert M.model_json_schema()["$defs"]["Colour"]["enum"] == ["red", "deep_blue"]
+
+
+def test_utc_shim() -> None:
+ assert UTC is timezone.utc
+ assert datetime.now(UTC).tzinfo is UTC
+
+
+def test_tomllib_shim_parses() -> None:
+ assert tomllib.loads('a = 1\n[t]\nb = "x"\n') == {"a": 1, "t": {"b": "x"}}
+
+
+def test_compat_documents_every_shim() -> None:
+ """Each exported shim must say in the module docstring when it can be deleted."""
+ import codeverse._compat as compat
+
+ doc = compat.__doc__ or ""
+ for name in compat.__all__:
+ assert name in doc, f"codeverse/_compat.py docstring never mentions {name}"
+ assert "3.11" in doc
+
+
+# ------------------------------------------------------------------- the node floor gate
+ "text,expected",
+ [
+ ("v24.14.0\n", (24, 14, 0)),
+ ("v20.6.0", (20, 6, 0)),
+ ("v18.20.4", (18, 20, 4)),
+ ("20.6.1", (20, 6, 1)),
+ ("v22.0.0-nightly20240101", (22, 0, 0)),
+ ("not found", None),
+ ("", None),
+ ],
+)
+def test_parse_node_version(text: str, expected: tuple[int, int, int] | None) -> None:
+ assert parse_node_version(text) == expected
+
+
[email protected]("version", [(20, 6, 0), (20, 6, 1), (22, 15, 0), (24, 14, 0), None])
+def test_node_version_accepted(version: tuple[int, int, int] | None) -> None:
+ """At or above the floor passes; an unknown version is not our error to raise."""
+ assert node_version_error(version) == ""
+
+
[email protected]("version", [(20, 5, 9), (18, 20, 4), (16, 0, 0)])
+def test_node_version_rejected_with_an_actionable_message(version: tuple[int, int, int]) -> None:
+ msg = node_version_error(version)
+ assert ".".join(str(n) for n in version) in msg, "says which node was found"
+ assert NODE_MIN_STR in msg, "says which node is needed"
+ assert "CV3D_BINARIES__NODE" in msg and "nvm" in msg, "says how to fix it"
+
+
+def test_run_node_refuses_an_old_node_before_spawning(tmp_path, monkeypatch) -> None:
+ """The gate fires in run_node, so every node workload fails loudly and early."""
+ import codeverse.spatial.node as node_mod
+
+ script = tmp_path / "noop.mjs"
+ script.write_text("console.log('{}')\n")
+ monkeypatch.setattr(node_mod, "node_version", lambda _bin: (18, 20, 4))
+ monkeypatch.setattr(node_mod, "run_subprocess", lambda *a, **k: pytest.fail("spawned an old node"))
+ with pytest.raises(NodeError, match="too old"):
+ node_mod.run_node(script)
+
+
+def test_require_node_version_passes_on_a_new_enough_node(monkeypatch) -> None:
+ import codeverse.spatial.node as node_mod
+
+ monkeypatch.setattr(node_mod, "node_version", lambda _bin: (20, 6, 0))
+ require_node_version("node") # must not raise
diff --git a/harness/tests/flywheel_cli/conftest.py b/harness/tests/flywheel_cli/conftest.py
index e6fb58c5..b68fe358 100644
--- a/harness/tests/flywheel_cli/conftest.py
+++ b/harness/tests/flywheel_cli/conftest.py
@@ -5,11 +5,12 @@ from __future__ import annotations
import struct
import zlib
-from datetime import UTC, datetime
+from datetime import datetime
from pathlib import Path
import pytest
+from codeverse._compat import UTC
from codeverse.contracts.artifacts import (
BuildResult,
GateFinding,
diff --git a/harness/tests/gallery/conftest.py b/harness/tests/gallery/conftest.py
new file mode 100644
index 00000000..b5bb0929
--- /dev/null
+++ b/harness/tests/gallery/conftest.py
@@ -0,0 +1,43 @@
+"""A synthetic multi-root run tree: two batteries, a good/failing/pending/corrupt run.
+
+Reuses ``tests.flywheel_cli.conftest.make_fake_run`` so the gallery is exercised
+against exactly the records the rest of the flywheel tests use.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from codeverse.contracts.common import Language
+from tests.flywheel_cli.conftest import make_fake_run, tiny_png
+
+
+def gallery_tree(tmp_path: Path) -> dict[str, Path]:
+ """``{"runs": …, "battery": …}`` — two roots holding six run directories."""
+ runs = tmp_path / "runs"
+ battery = tmp_path / "bench" / "out" / "static_v9" / "runs"
+ battery.mkdir(parents=True)
+
+ make_fake_run(runs, "wooden_chair_ab12cd34") # passes
+ make_fake_run(runs, "lamp_three", prompt="a desk lamp", language=Language.THREEJS,
+ scores=(0.70, 0.72)) # fails
+ make_fake_run(battery, "ctrl_med_toaster", prompt="a chrome toaster", scores=(0.4, 0.9))
+ make_fake_run(battery, "art_easy_hinge", prompt="a cabinet door",
+ language=Language.URDF_BLENDER, scores=(0.6, 0.81))
+
+ corrupt = battery / "half_written" # bench mid-write
+ corrupt.mkdir()
+ (corrupt / "spec.json").write_text(json.dumps({"prompt": "a stool", "track": "static_object",
+ "language": "blender"}))
+ (corrupt / "record.json").write_text('{"spec": {"id": "half', encoding="utf-8")
+
+ pending = battery / "not_started"
+ pending.mkdir()
+ (pending / "spec.json").write_text(json.dumps({"prompt": "a bookshelf", "track": "static_object",
+ "language": "blender"}))
+ tiny_png(pending / "artifacts" / "renders" / "r00" / "sheet.png")
+ return {"runs": runs, "battery": battery, "root": tmp_path}
diff --git a/harness/tests/gallery/test_cli.py b/harness/tests/gallery/test_cli.py
new file mode 100644
index 00000000..6272272d
--- /dev/null
+++ b/harness/tests/gallery/test_cli.py
@@ -0,0 +1,78 @@
+"""``3dcv gallery build|serve`` and the ``3dcv flywheel gallery`` alias."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+from codeverse.cli.gallery_cmd import resolve_roots
+from codeverse.cli.main import app
+
+runner = CliRunner()
+
+
+def test_gallery_group_is_registered():
+ r = runner.invoke(app, ["--help"])
+ assert r.exit_code == 0 and "gallery" in r.output
+ r = runner.invoke(app, ["gallery", "--help"])
+ assert r.exit_code == 0 and "serve" in r.output and "build" in r.output
+ r = runner.invoke(app, ["gallery", "serve", "--help"])
+ assert r.exit_code == 0
+ for flag in ("--port", "--host", "--reload", "--open"):
+ assert flag in r.output, flag
+
+
+def test_build_writes_a_page(gallery_tree: dict[str, Path], tmp_path: Path):
+ out = tmp_path / "g.html"
+ r = runner.invoke(app, ["gallery", "build", str(gallery_tree["runs"]), str(gallery_tree["battery"]),
+ "--out", str(out), "--title", "batch 9"])
+ assert r.exit_code == 0, r.output
+ assert "gallery of 6 runs" in r.output
+ markup = out.read_text()
+ assert "batch 9" in markup and "wooden_chair_ab12cd34" in markup
+ assert "data:image/jpeg" not in markup # link mode by default
+
+
+def test_build_embed(gallery_tree: dict[str, Path], tmp_path: Path):
+ out = tmp_path / "e.html"
+ r = runner.invoke(app, ["gallery", "build", str(gallery_tree["runs"]), "--out", str(out), "--embed"])
+ assert r.exit_code == 0, r.output
+ assert "data:image/jpeg;base64," in out.read_text()
+
+
+def test_build_rejects_a_missing_root(tmp_path: Path):
+ r = runner.invoke(app, ["gallery", "build", str(tmp_path / "nope"), "--out", str(tmp_path / "x.html")])
+ assert r.exit_code != 0 and "not a directory" in r.output
+
+
+def test_flywheel_gallery_alias_still_works(gallery_tree: dict[str, Path], tmp_path: Path):
+ out = tmp_path / "alias.html"
+ r = runner.invoke(app, ["flywheel", "gallery", str(gallery_tree["runs"]), str(out), "--title", "batch 1"])
+ assert r.exit_code == 0, r.output
+ assert "gallery of 2 runs" in r.output
+ markup = out.read_text()
+ assert "batch 1" in markup
+ assert "data:image/jpeg;base64," in markup # the alias keeps the old self-contained behaviour
+
+
+def test_default_roots_from_cwd(gallery_tree: dict[str, Path], monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.chdir(gallery_tree["root"])
+ roots = resolve_roots(None)
+ assert [r.name for r in roots] == ["runs", "runs"]
+ assert str(roots[1]).endswith(os.path.join("bench", "out", "static_v9", "runs"))
+
+
+def test_no_roots_anywhere_is_a_clear_error(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.chdir(tmp_path)
+ monkeypatch.setenv("CV3D_RUNS_DIR", str(tmp_path / "absent"))
+ from codeverse.config import get_settings
+
+ get_settings.cache_clear()
+ try:
+ r = runner.invoke(app, ["gallery", "build", "--out", str(tmp_path / "x.html")])
+ assert r.exit_code != 0 and "no run roots found" in r.output
+ finally:
+ get_settings.cache_clear()
diff --git a/harness/tests/gallery/test_index.py b/harness/tests/gallery/test_index.py
new file mode 100644
index 00000000..bde145c3
--- /dev/null
+++ b/harness/tests/gallery/test_index.py
@@ -0,0 +1,102 @@
+"""Index building over a synthetic runs tree (including a corrupt record)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from codeverse.gallery.index import build_index, default_roots, entry_for_dir, root_label
+from codeverse.gallery.model import match, sort_entries, summarize
+
+
+def test_build_index_sections_and_states(gallery_tree: dict[str, Path]):
+ index = build_index([gallery_tree["runs"], gallery_tree["battery"]])
+ assert [s.label for s in index.sections] == ["runs", "static_v9"]
+ assert index.build_ms >= 0
+ states = {e.slug: e.state for e in index.entries()}
+ assert states == {"lamp_three": "ok", "wooden_chair_ab12cd34": "ok", "art_easy_hinge": "ok",
+ "ctrl_med_toaster": "ok", "half_written": "broken", "not_started": "pending"}
+ broken = index.find("static_v9", "half_written")
+ assert broken is not None and "record.json" in broken.error
+ assert broken.prompt == "a stool" and broken.track == "static_object" # spec still read
+ pending = index.find("static_v9", "not_started")
+ assert pending is not None and pending.prompt == "a bookshelf"
+ # a broken/pending run still offers its workspace, and nothing raised
+ assert "workspace" in {link.label for link in broken.links}
+
+
+def test_entry_fields_and_links(gallery_tree: dict[str, Path]):
+ entry = entry_for_dir("runs", gallery_tree["runs"] / "wooden_chair_ab12cd34")
+ assert entry.state == "ok" and entry.passed is True and entry.tier == "A"
+ assert entry.score == 0.80 and entry.baseline_score == 0.55 and entry.rounds == 2
+ assert entry.best_round == 1 and entry.minutes is not None
+ assert entry.sheet == "artifacts/renders/r01/sheet.png"
+ labels = [link.label for link in entry.links]
+ assert labels[:2] == ["workspace", "record.json"]
+ assert "src/" in labels and "sheet" in labels and "glb" in labels
+ assert all(not Path(link.rel).is_absolute() for link in entry.links) # every link is run-relative
+ assert [r.index for r in entry.round_rows] == [0, 1]
+ assert entry.round_rows[1].sheet == "artifacts/renders/r01/sheet.png"
+ assert entry.key == "runs/wooden_chair_ab12cd34"
+
+
+def test_corrupt_record_does_not_raise(tmp_path: Path):
+ run = tmp_path / "runs" / "boom"
+ run.mkdir(parents=True)
+ (run / "record.json").write_bytes(b"\x00\x01not json")
+ index = build_index([tmp_path / "runs"])
+ (entry,) = index.entries()
+ assert entry.state == "broken" and entry.error
+
+
+def test_empty_record_from_a_half_written_write(tmp_path: Path):
+ run = tmp_path / "runs" / "empty"
+ run.mkdir(parents=True)
+ (run / "record.json").write_text("")
+ (entry,) = build_index([tmp_path / "runs"]).entries()
+ assert entry.state == "broken"
+
+
+def test_valid_json_but_not_a_record(tmp_path: Path):
+ run = tmp_path / "runs" / "wrong_shape"
+ run.mkdir(parents=True)
+ (run / "record.json").write_text(json.dumps({"hello": "world"}))
+ (entry,) = build_index([tmp_path / "runs"]).entries()
+ assert entry.state == "broken" and "invalid record.json" in entry.error
+
+
+def test_filter_and_sort_and_summary(gallery_tree: dict[str, Path]):
+ index = build_index([gallery_tree["runs"], gallery_tree["battery"]])
+ entries = index.entries()
+ assert [e.slug for e in sort_entries(entries, "score")][0] == "ctrl_med_toaster" # 0.9
+ assert [e.slug for e in sort_entries(entries, "name")] == sorted(e.slug for e in entries)
+ by_cost = sort_entries(entries, "cost")
+ assert by_cost[0].cost_usd >= by_cost[-1].cost_usd
+ threejs = [e for e in entries if match(e, {"lang": "threejs"})]
+ assert [e.slug for e in threejs] == ["lamp_three"]
+ assert [e.slug for e in entries if match(e, {"q": "TOASTER"})] == ["ctrl_med_toaster"]
+ assert [e.slug for e in entries if match(e, {"pass": "fail"})] == ["lamp_three"]
+ assert {e.slug for e in entries if match(e, {"battery": "static_v9"})} == {
+ "art_easy_hinge", "ctrl_med_toaster", "half_written", "not_started"}
+ s = summarize([e for e in entries if e.state == "ok"])
+ assert s.n == 4 and s.n_judged == 4 and s.n_passed == 3
+ assert s.pass_rate == 0.75 and s.mean_score is not None and s.median_score is not None
+ assert s.total_usd > 0 and s.usd_per_pass == round(s.total_usd / 3, 4)
+ facets = index.facets()
+ assert facets["track"] == ["articulated_object", "static_object"]
+ assert facets["battery"] == ["runs", "static_v9"]
+
+
+def test_default_roots_and_labels(gallery_tree: dict[str, Path]):
+ base = gallery_tree["root"]
+ roots = default_roots(base)
+ assert [root_label(r) for r in roots] == ["runs", "static_v9"]
+ assert default_roots(base / "nope") == []
+
+
+def test_duplicate_labels_are_disambiguated(tmp_path: Path):
+ a, b = tmp_path / "a" / "runs", tmp_path / "b" / "runs"
+ a.mkdir(parents=True)
+ b.mkdir(parents=True)
+ index = build_index([a, b])
+ assert [s.label for s in index.sections] == ["runs", "runs#2"]
diff --git a/harness/tests/gallery/test_page.py b/harness/tests/gallery/test_page.py
new file mode 100644
index 00000000..c2e8ad0b
--- /dev/null
+++ b/harness/tests/gallery/test_page.py
@@ -0,0 +1,153 @@
+"""The rendered page: it parses, it is self-contained, and the filter is applied
+server-side so a curl'd query string already shows the right runs."""
+
+from __future__ import annotations
+
+import re
+from html.parser import HTMLParser
+from pathlib import Path
+
+from codeverse.gallery.index import build_index
+from codeverse.gallery.page import render_index
+from codeverse.gallery.static_site import build_static, render_static
+from codeverse.gallery.urls import StaticUrls, UrlMaker
+
+VOID = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",
+ "source", "track", "wbr"}
+
+
+class _Checker(HTMLParser):
+ """Parses the document and collects every URL-bearing attribute + tag balance."""
+
+ def __init__(self) -> None:
+ super().__init__(convert_charrefs=True)
+ self.urls: list[str] = []
+ self.stack: list[str] = []
+ self.unbalanced: list[str] = []
+ self.ids: list[str] = []
+ self.tags: list[str] = []
+
+ def handle_starttag(self, tag, attrs):
+ self.tags.append(tag)
+ d = dict(attrs)
+ for key in ("src", "href", "action", "srcset", "poster", "data-src"):
+ if d.get(key):
+ self.urls.append(d[key])
+ if d.get("id"):
+ self.ids.append(d["id"])
+ if tag not in VOID:
+ self.stack.append(tag)
+
+ def handle_endtag(self, tag):
+ if tag in VOID:
+ return
+ if self.stack and self.stack[-1] == tag:
+ self.stack.pop()
+ elif tag in self.stack:
+ while self.stack and self.stack.pop() != tag:
+ self.unbalanced.append(tag)
+ else:
+ self.unbalanced.append(tag)
+
+
+def _parse(markup: str) -> _Checker:
+ c = _Checker()
+ c.feed(markup)
+ return c
+
+
+def _assert_offline(markup: str) -> _Checker:
+ c = _parse(markup)
+ external = [u for u in c.urls if u.split(":", 1)[0].lower() in ("http", "https", "ftp")
+ or u.startswith("//")]
+ assert not external, f"external references: {external[:5]}"
+ for bad in ("cdn.", "googleapis.com", "unpkg", "jsdelivr", "@import url(http"):
+ assert bad not in markup, bad
+ assert not c.unbalanced, f"unbalanced tags: {c.unbalanced[:5]}"
+ return c
+
+
+def test_static_build_parses_and_is_self_contained(gallery_tree: dict[str, Path], tmp_path: Path):
+ out = tmp_path / "out" / "gallery.html"
+ path, n, index = build_static([gallery_tree["runs"], gallery_tree["battery"]], out, embed=True)
+ assert path == out and n == 6 and out.is_file()
+ markup = out.read_text()
+ checker = _assert_offline(markup)
+ assert markup.startswith("<!doctype html>")
+ assert "data:image/jpeg;base64," in markup # --embed inlined the sheets
+ assert any(u.startswith("file://") for u in checker.urls) # links point at the run dirs
+ assert "gallery-data" in checker.ids and "s-perpass" in checker.ids
+ assert markup.count("<article class='card") == 6
+ for slug in ("wooden_chair_ab12cd34", "half_written", "not_started"):
+ assert slug in markup
+ assert "broken:" in markup and "pending:" in markup # the two non-ok cards say why
+
+
+def test_static_build_without_embed_is_small_and_links_files(gallery_tree: dict[str, Path], tmp_path: Path):
+ out = tmp_path / "linked.html"
+ build_static([gallery_tree["runs"]], out, embed=False)
+ markup = out.read_text()
+ _assert_offline(markup)
+ assert "data:image/jpeg" not in markup
+ assert "file://" in markup
+
+
+def test_build_static_is_atomic(gallery_tree: dict[str, Path], tmp_path: Path):
+ out = tmp_path / "g.html"
+ build_static([gallery_tree["runs"]], out)
+ first = out.read_text()
+ build_static([gallery_tree["runs"], gallery_tree["battery"]], out)
+ assert out.read_text() != first
+ assert not list(tmp_path.glob("*.tmp")) # no temp file left behind
+
+
+def test_server_page_applies_the_filter_server_side(gallery_tree: dict[str, Path]):
+ index = build_index([gallery_tree["runs"], gallery_tree["battery"]])
+ markup = render_index(index, UrlMaker(), flt={"lang": "threejs"}, sort="score")
+ _assert_offline(markup)
+ # every card is still in the DOM (so the client can widen the filter without a reload)
+ assert markup.count("<article class='card") == 6
+ # ...but only the matching one is visible, and the summary counts only that one
+ assert len(re.findall(r"<article class='card [^']*is-hidden' data-run=", markup)) == 5
+ assert ">1 / 6<" in markup
+ assert "<option value='threejs' selected>" in markup
+
+
+def test_sections_counts_and_table_mode(gallery_tree: dict[str, Path]):
+ index = build_index([gallery_tree["runs"], gallery_tree["battery"]])
+ markup = render_index(index, UrlMaker(), view="table")
+ assert "<body class='view-table'>" in markup
+ assert "id='b-runs'" in markup and "id='b-static_v9'" in markup
+ assert ">2 runs<" in markup and ">4 runs<" in markup
+ assert len(re.findall(r"<tr class='[^']*' data-run=", markup)) == 6
+
+
+def test_detail_links_are_offered_only_when_the_target_has_them(gallery_tree: dict[str, Path]):
+ index = build_index([gallery_tree["runs"]])
+ markup = render_index(index, UrlMaker())
+ assert "/run/runs/wooden_chair_ab12cd34" in markup
+ assert "/file/runs/wooden_chair_ab12cd34/artifacts/renders/r01/sheet.png" in markup
+ assert "/code/runs/wooden_chair_ab12cd34/src" in markup
+ assert "/viewer/runs/wooden_chair_ab12cd34/artifacts/object.glb" in markup
+ # the static form never advertises server-only routes
+ static = render_static(index, embed=False)
+ assert "/run/runs/" not in static and "/viewer/" not in static
+
+
+def test_html_escaping_of_a_hostile_prompt(tmp_path: Path):
+ from tests.flywheel_cli.conftest import make_fake_run
+
+ runs = tmp_path / "runs"
+ make_fake_run(runs, "xss", prompt="a chair <script>alert(1)</script> & \"quotes\"")
+ markup = render_index(build_index([runs]), UrlMaker())
+ assert "<script>alert(1)</script>" not in markup
+ assert "&lt;script&gt;alert(1)&lt;/script&gt;" in markup
+ _assert_offline(markup)
+
+
+def test_static_urls_of_an_entry(gallery_tree: dict[str, Path]):
+ entry = build_index([gallery_tree["runs"]]).entries()[0]
+ urls = StaticUrls(embed=False)
+ assert urls.file(entry, "record.json").startswith("file://")
+ assert urls.file(entry, "record.json").endswith("/record.json")
+ assert not urls.has_detail
diff --git a/harness/tests/gallery/test_server.py b/harness/tests/gallery/test_server.py
new file mode 100644
index 00000000..1f980cb8
--- /dev/null
+++ b/harness/tests/gallery/test_server.py
@@ -0,0 +1,217 @@
+"""The local server: routing, path-traversal refusal, content types, live reload.
+
+Offline by construction — the integration test binds an ephemeral loopback port
+in a background thread and talks to it with ``http.client``.
+"""
+
+from __future__ import annotations
+
+import http.client
+import json
+import threading
+from pathlib import Path
+
+import pytest
+
+from codeverse.gallery.paths import PathError, safe_join
+from codeverse.gallery.server import (
+ DEFAULT_HOST,
+ GalleryApp,
+ GalleryError,
+ make_server,
+ resolve_host,
+)
+from codeverse.gallery.urls import content_type
+
+
+def app(gallery_tree: dict[str, Path]) -> GalleryApp:
+ return GalleryApp([gallery_tree["runs"], gallery_tree["battery"]])
+
+
+# --------------------------------------------------------------------------- routing
+def test_index_and_api_routes(app: GalleryApp):
+ r = app.route("/")
+ assert r.status == 200 and r.content_type.startswith("text/html")
+ assert b"3dcv gallery" in r.body
+ assert app.route("/index.html").status == 200
+ assert app.route("/healthz").body == b"ok"
+ api = json.loads(app.route("/api/runs", {"lang": "threejs"}).body)
+ assert api["total"] == 6 and api["n"] == 1 and api["runs"][0]["slug"] == "lamp_three"
+ summary = json.loads(app.route("/api/summary", {"battery": "runs"}).body)
+ assert summary["n"] == 2
+ assert app.route("/api/nope").status == 404
+
+
+def test_detail_page(app: GalleryApp):
+ r = app.route("/run/runs/wooden_chair_ab12cd34")
+ assert r.status == 200
+ page = r.body.decode()
+ for anchor in ("id='rounds'", "id='judge'", "id='renders'", "id='code'", "id='cost'"):
+ assert anchor in page, anchor
+ assert "thicken the legs" in page # the judge's improvement plan
+ assert "primitive_cube_add" in page # the code viewer inlined the entry file
+ assert app.route("/run/runs/nope").status == 404
+ assert app.route("/run/runs").status == 404
+
+
+def test_detail_of_a_broken_run_does_not_crash(app: GalleryApp):
+ r = app.route("/run/static_v9/half_written")
+ assert r.status == 200 and b"broken" in r.body
+ r = app.route("/run/static_v9/not_started")
+ assert r.status == 200 and b"pending" in r.body
+
+
+def test_file_dir_and_code_routes(app: GalleryApp):
+ base = "/file/runs/wooden_chair_ab12cd34"
+ rec = app.route(f"{base}/record.json")
+ assert rec.status == 200 and rec.content_type == "application/json; charset=utf-8"
+ assert rec.path is not None and rec.path.name == "record.json"
+ png = app.route(f"{base}/artifacts/renders/r01/sheet.png")
+ assert png.status == 200 and png.content_type == "image/png"
+ glb = app.route(f"{base}/artifacts/object.glb")
+ assert glb.status == 200 and glb.content_type == "model/gltf-binary"
+ src = app.route(f"{base}/src/model.py")
+ assert src.status == 200 and src.content_type == "text/plain; charset=utf-8"
+ code = app.route("/code/runs/wooden_chair_ab12cd34/src/model.py")
+ assert code.status == 200 and b"primitive_cube_add" in code.body and b"class='ln'" in code.body
+ listing = app.route("/dir/runs/wooden_chair_ab12cd34/src")
+ assert listing.status == 200 and b"model.py" in listing.body
+ assert app.route(f"{base}/artifacts").status == 200 # a file route onto a dir lists it
+ assert app.route(f"{base}/does/not/exist.png").status == 404
+
+
+ "../../../../etc/passwd",
+ "..%2f..%2fetc/passwd",
+ "%2e%2e/%2e%2e/etc/passwd",
+ "src/../../../../etc/passwd",
+ "src/../../lamp_three/record.json",
+ "....//....//etc/passwd",
+])
+def test_path_traversal_is_refused(app: GalleryApp, bad: str):
+ r = app.route(f"/file/runs/wooden_chair_ab12cd34/{bad}")
+ assert r.status in (403, 404), f"{bad} → {r.status}"
+ assert b"root:x:" not in r.body
+
+
+def test_absolute_paths_are_refused(app: GalleryApp):
+ # '//etc/passwd' collapses to 'etc/passwd' inside the run (404, not a read)
+ assert app.route("/file/runs/wooden_chair_ab12cd34//etc/passwd").status == 404
+ assert safe_join(app.roots[0], "wooden_chair_ab12cd34").is_dir()
+ with pytest.raises(PathError):
+ safe_join(app.roots[0], "/etc/passwd")
+ with pytest.raises(PathError):
+ safe_join(app.roots[0], "../..")
+ with pytest.raises(PathError):
+ safe_join(app.roots[0], "a/../../b")
+ with pytest.raises(PathError):
+ safe_join(app.roots[0], "x\x00y")
+
+
+def test_symlink_out_of_the_run_is_refused(app: GalleryApp, tmp_path: Path):
+ run = app.roots[0] / "wooden_chair_ab12cd34"
+ outside = tmp_path / "secret.txt"
+ outside.write_text("classified")
+ (run / "escape").symlink_to(outside)
+ r = app.route("/file/runs/wooden_chair_ab12cd34/escape")
+ assert r.status == 403 and b"classified" not in r.body
+
+
+def test_unknown_run_and_unknown_route(app: GalleryApp):
+ assert app.route("/file/nope/nope/record.json").status == 404
+ assert app.route("/wat").status == 404
+ assert app.route("/file").status == 404
+
+
+def test_vendor_and_viewer(app: GalleryApp):
+ from codeverse.gallery.viewer import viewer_available
+
+ v = app.route("/viewer/runs/wooden_chair_ab12cd34/artifacts/object.glb")
+ if viewer_available():
+ assert v.status == 200 and b"importmap" in v.body
+ js = app.route("/vendor/three/build/three.module.js")
+ assert js.status == 200 and js.content_type.startswith("text/javascript")
+ assert app.route("/vendor/three/../../../etc/passwd").status == 404
+ assert app.route("/vendor/nope.js").status == 404
+ else: # runtime_js/node_modules not installed
+ assert v.status == 501
+
+
+def test_content_type_table():
+ assert content_type("a.glb") == "model/gltf-binary"
+ assert content_type("a.frag") == "text/plain; charset=utf-8"
+ assert content_type("a.js") == "text/plain; charset=utf-8"
+ assert content_type("a.gif") == "image/gif"
+ assert content_type("a.unknownext") == "application/octet-stream"
+
+
+# --------------------------------------------------------------------------- host guard
+def test_host_guard():
+ assert resolve_host(None) == DEFAULT_HOST
+ assert resolve_host("") == DEFAULT_HOST
+ assert resolve_host("localhost") == "localhost"
+ assert resolve_host("0.0.0.0", explicit=True) == "0.0.0.0" # noqa: S104 - the point of the test
+ with pytest.raises(GalleryError):
+ resolve_host("0.0.0.0") # noqa: S104
+ with pytest.raises(GalleryError):
+ resolve_host("192.168.1.5")
+
+
+# --------------------------------------------------------------------------- reload
+def test_reload_picks_up_a_run_written_after_startup(gallery_tree: dict[str, Path]):
+ from tests.flywheel_cli.conftest import make_fake_run
+
+ app = GalleryApp([gallery_tree["runs"]], reload=True)
+ assert len(app.index.entries()) == 2
+ make_fake_run(gallery_tree["runs"], "brand_new", prompt="a new stool")
+ app.route("/")
+ assert len(app.index.entries()) == 3
+ assert app.route("/run/runs/brand_new").status == 200
+
+
+def test_no_reload_still_finds_a_new_run_by_url(gallery_tree: dict[str, Path]):
+ from tests.flywheel_cli.conftest import make_fake_run
+
+ app = GalleryApp([gallery_tree["runs"]], reload=False)
+ make_fake_run(gallery_tree["runs"], "late_arrival", prompt="a late stool")
+ assert app.route("/run/runs/late_arrival").status == 200
+
+
+# --------------------------------------------------------------------------- over a real socket
+def test_over_a_loopback_socket(app: GalleryApp):
+ httpd = make_server(app, DEFAULT_HOST, 0)
+ port = httpd.server_address[1]
+ thread = threading.Thread(target=httpd.serve_forever, daemon=True)
+ thread.start()
+ try:
+ conn = http.client.HTTPConnection(DEFAULT_HOST, port, timeout=10)
+
+ def get(path: str):
+ conn.request("GET", path)
+ resp = conn.getresponse()
+ return resp.status, resp.getheader("Content-Type"), resp.read()
+
+ status, ctype, body = get("/")
+ assert status == 200 and ctype.startswith("text/html") and b"wooden_chair" in body
+ status, ctype, body = get("/file/runs/wooden_chair_ab12cd34/artifacts/renders/r01/sheet.png")
+ assert status == 200 and ctype == "image/png" and body[:8] == b"\x89PNG\r\n\x1a\n"
+ status, ctype, _ = get("/file/runs/wooden_chair_ab12cd34/artifacts/object.glb")
+ assert status == 200 and ctype == "model/gltf-binary"
+ status, ctype, body = get("/api/runs?tier=A")
+ assert status == 200 and ctype.startswith("application/json") and json.loads(body)["n"] >= 1
+ status, _, body = get("/file/runs/wooden_chair_ab12cd34/..%2f..%2f..%2fetc%2fpasswd")
+ assert status in (403, 404) and b"root:x:" not in body
+ conn.request("HEAD", "/")
+ head = conn.getresponse()
+ assert head.status == 200 and head.read() == b"" and int(head.getheader("Content-Length")) > 0
+ conn.close()
+ finally:
+ httpd.shutdown()
+ httpd.server_close()
+ thread.join(timeout=5)
+
+
+def test_make_server_reports_a_bad_bind(app: GalleryApp):
+ with pytest.raises(GalleryError):
+ make_server(app, "203.0.113.1", 0) # TEST-NET-3: never assigned to this host
diff --git a/harness/tests/install/test_docs.py b/harness/tests/install/test_docs.py
index d1e4f50a..b174ed36 100644
--- a/harness/tests/install/test_docs.py
+++ b/harness/tests/install/test_docs.py
@@ -18,11 +18,12 @@ import os
import re
import subprocess
import sys
-import tomllib
from pathlib import Path
import pytest
+from codeverse._compat import tomllib
+
HARNESS = Path(__file__).resolve().parents[2]
REPO = HARNESS.parent
INSTALL = HARNESS / "docs" / "INSTALL.md"
diff --git a/harness/tests/spatial_tools/test_mcp_server.py b/harness/tests/spatial_tools/test_mcp_server.py
index a0c233c2..e0aa15ee 100644
--- a/harness/tests/spatial_tools/test_mcp_server.py
+++ b/harness/tests/spatial_tools/test_mcp_server.py
@@ -45,13 +45,18 @@ def test_cli_list(stool_ctx: ToolContext, capsys: pytest.CaptureFixture[str]) ->
assert main(["--workspace", str(stool_ctx.workspace.root / "nope")]) == 2
-def test_stdio_roundtrip(stool_ctx: ToolContext) -> None:
+def test_stdio_roundtrip(stool_ctx: ToolContext, tmp_path: Path) -> None:
from mcp import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client
+ # `errlog` is handed straight to loop.subprocess_exec, which needs a real
+ # fileno(); pytest's captured sys.stderr (stdio_client's default) has none
+ # from anyio 4.14 on. A file also keeps the server's stderr readable here.
+ errlog = (tmp_path / "server.err").open("w")
+
async def run():
params = StdioServerParameters(command=sys.executable, args=["-m", "codeverse.spatial.mcp_server", "--workspace", str(stool_ctx.workspace.root)])
- async with stdio_client(params) as (r, w), ClientSession(r, w) as s:
+ async with stdio_client(params, errlog=errlog) as (r, w), ClientSession(r, w) as s:
await s.initialize()
tools = await s.list_tools()
by_name = {t.name: t for t in tools.tools}
@@ -68,4 +73,7 @@ def test_stdio_roundtrip(stool_ctx: ToolContext) -> None:
unknown = await s.call_tool("nope", {})
assert unknown.is_error
- asyncio.run(asyncio.wait_for(run(), timeout=120))
+ try:
+ asyncio.run(asyncio.wait_for(run(), timeout=120))
+ finally:
+ errlog.close()