Skip to content

Official Codebase of 3DCodeVerse

Python

ci: drop the stock Pylint workflow (ran py3.8-3.10 on a >=3.11 codebase with no config, so it could only ever fail); lint is ruff, configured in harness/pyproject.toml

gaoypenge4b43653f52d
diff --git a/.github/workflows/pylint.yml b/.github/workflows/pylint.yml
deleted file mode 100644
index c73e032c..00000000
--- a/.github/workflows/pylint.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-name: Pylint
-
-on: [push]
-
-jobs:
- build:
- runs-on: ubuntu-latest
- strategy:
- matrix:
- python-version: ["3.8", "3.9", "3.10"]
- steps:
- - uses: actions/checkout@v4
- - name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v3
- with:
- python-version: ${{ matrix.python-version }}
- - name: Install dependencies
- run: |
- python -m pip install --upgrade pip
- pip install pylint
- - name: Analysing the code with pylint
- run: |
- pylint $(git ls-files '*.py')
diff --git a/README.md b/README.md
index d2408ec6..c2c0ba40 100644
--- a/README.md
+++ b/README.md
@@ -9,6 +9,11 @@ The 3dcodeverse project. Top-level layout:
plan → generate → gate → render → judge → refine loop, with text-to-image
texturing and data-flywheel records. See `harness/README.md`.
+ 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`.
+
- **`finetune/`** — LLM finetuning recipes (LoRA / full-parameter SFT, execution-
and geometry-feedback DPO via unpatched LLaMA-Factory) and the execution-based
evaluation stack (3DCodeBench + per-dialect executors) used to train open
diff --git a/harness/README.md b/harness/README.md
index ce972654..8e7ae2d8 100644
--- a/harness/README.md
+++ b/harness/README.md
@@ -27,8 +27,10 @@ renders, judges, refines, textures and records every run as data-flywheel materi
pairs, captions, sqlite index, HTML gallery.
```bash
-pip install -e . # entry points: 3dcodeverse, 3dcv
-(cd runtime_js && npm install)
+bash scripts/setup.sh # install everything + run doctor (idempotent; see docs/INSTALL.md)
+# ...or by hand:
+pip install -e '.[all,dev]' # entry points: 3dcodeverse, 3dcv
+(cd runtime_js && npm ci) # [email protected] + puppeteer 24 (chrome → ~/.cache/puppeteer)
3dcv doctor
3dcv make "a mid-century wooden dining chair" --track static_object --language blender
3dcv make "a kitchen cabinet with one door and a drawer" --track articulated_object --language urdf_blender
@@ -43,6 +45,7 @@ gemini-cli) 0.64 → 0.89, 36 min, $0.68; garden scene 0.56 → 0.60 over 2 refi
45 min, $2.90; neon-rain shader (graphics, single-shot) 0.79 first round, 2 min, $0.05;
best-of-2 stool 0.56 → 0.61, 7.6 min, $0.24.
-Docs: `docs/ARCHITECTURE.md` (design + what a run does) · `docs/INTERFACES.md`
+Docs: `docs/INSTALL.md` (install / prerequisites / doctor troubleshooting) ·
+`docs/ARCHITECTURE.md` (design + what a run does) · `docs/INTERFACES.md`
(signatures) · `docs/RUNBOOK.md` (operate / extend) · `docs/DECISIONS.md` (ADRs) ·
`docs/EVAL.md` (evaluation protocol + judge calibration) · `CLAUDE.md` (working rules).
diff --git a/harness/bench/run_bench.py b/harness/bench/run_bench.py
index 54263f9b..bb37c950 100644
--- a/harness/bench/run_bench.py
+++ b/harness/bench/run_bench.py
@@ -44,6 +44,9 @@ class BenchPrompt(BaseModel):
must_have: list[str] = Field(default_factory=list)
dimensions_m: dict[str, float] | None = None
tags: list[str] = Field(default_factory=list)
+ language: Language | None = Field(
+ default=None, description="per-prompt override of the battery language "
+ "(e.g. the opengl_python rows of a glsl_shader battery)")
class Battery(BaseModel):
@@ -97,7 +100,7 @@ def build_spec(
"""Shared Spec core for bench drivers (``run_bench`` / ``compare_backends``).
Drivers resolve their own ``Backends`` and pass their leading tag."""
return Spec(
- id=f"{battery.name}/{item.id}", track=battery.track, language=battery.language, prompt=item.prompt,
+ id=f"{battery.name}/{item.id}", track=battery.track, language=item.language or battery.language, prompt=item.prompt,
constraints=Constraints(must_have=list(item.must_have), dimensions_m=item.dimensions_m),
budget=Budget(max_rounds=rounds, max_usd=max_usd, max_minutes=max_minutes),
backends=backends, tags=[tag0, battery.name, item.tier, item.category, *extra_tags, *item.tags],
diff --git a/harness/codeverse/contracts/__init__.py b/harness/codeverse/contracts/__init__.py
index 376dda8f..889a2d08 100644
--- a/harness/codeverse/contracts/__init__.py
+++ b/harness/codeverse/contracts/__init__.py
@@ -56,8 +56,8 @@ from codeverse.contracts.plan import (
EffectPlan,
GraphicsPlan,
JointPlan,
- PassPlan,
PartPlan,
+ PassPlan,
Plan,
ScenePlan,
StaticPlan,
@@ -66,4 +66,61 @@ from codeverse.contracts.plan import (
from codeverse.contracts.run import RoundRecord, RunRecord, RunStatus
from codeverse.contracts.spec import Constraints, ReferenceImage, RunOptions, Spec
-__all__ = [name for name in dir() if not name.startswith("_")]
+__all__ = [
+ "AcceptanceItem",
+ "AgentJob",
+ "AgentResult",
+ "ApiAgentOptions",
+ "ArticulatedPlan",
+ "AssetPlan",
+ "BBox",
+ "Backends",
+ "Budget",
+ "BuildResult",
+ "CameraPlan",
+ "ChatMessage",
+ "ChatRequest",
+ "ChatResponse",
+ "Constraints",
+ "ENTRY_FILE",
+ "EffectPlan",
+ "FileChange",
+ "GateFinding",
+ "GateReport",
+ "GraphicsPlan",
+ "ImagePart",
+ "ImprovementItem",
+ "JointPlan",
+ "JudgeIssue",
+ "Judgment",
+ "LANGUAGE_LABEL",
+ "Language",
+ "Measurement",
+ "PartMeasure",
+ "PartPlan",
+ "PassPlan",
+ "Plan",
+ "ReferenceImage",
+ "RenderSet",
+ "RenderView",
+ "RoundRecord",
+ "RunOptions",
+ "RunRecord",
+ "RunStatus",
+ "ScenePlan",
+ "Severity",
+ "Spec",
+ "StaticPlan",
+ "TRACK_INFO",
+ "TRACK_LANGUAGES",
+ "TextPart",
+ "ToolCallPart",
+ "ToolResultPart",
+ "ToolSpec",
+ "Track",
+ "TrackInfo",
+ "Usage",
+ "Vec3",
+ "ZonePlan",
+ "code_file",
+]
diff --git a/harness/codeverse/contracts/run.py b/harness/codeverse/contracts/run.py
index 0e58ef36..ed7d4137 100644
--- a/harness/codeverse/contracts/run.py
+++ b/harness/codeverse/contracts/run.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from enum import StrEnum
from typing import Any
@@ -37,7 +37,7 @@ class RoundRecord(BaseModel):
renders: RenderSet | None = None
judgment: Judgment | None = None
usage: Usage = Field(default_factory=Usage)
- started_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
+ started_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
duration_s: float = 0.0
notes: str = ""
@@ -58,7 +58,7 @@ class RunRecord(BaseModel):
total_usage: Usage = Field(default_factory=Usage)
environment: dict[str, str] = Field(default_factory=dict, description="tool versions, git sha, host")
prompt_hashes: dict[str, str] = Field(default_factory=dict)
- started_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
+ started_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
finished_at: datetime | None = None
error: str = ""
extra: dict[str, Any] = Field(default_factory=dict)
diff --git a/harness/codeverse/contracts/spec.py b/harness/codeverse/contracts/spec.py
index 7665922e..f1bcddae 100644
--- a/harness/codeverse/contracts/spec.py
+++ b/harness/codeverse/contracts/spec.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from datetime import datetime, timezone
+from datetime import UTC, datetime
from pydantic import BaseModel, Field, model_validator
@@ -51,7 +51,7 @@ class Spec(BaseModel):
options: RunOptions = Field(default_factory=RunOptions)
seed: int = 0
tags: list[str] = Field(default_factory=list)
- created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
+ created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
@model_validator(mode="after")
def _language_fits_track(self) -> Spec:
diff --git a/harness/codeverse/spatial/__init__.py b/harness/codeverse/spatial/__init__.py
index 5837e9a9..372bfb3b 100644
--- a/harness/codeverse/spatial/__init__.py
+++ b/harness/codeverse/spatial/__init__.py
@@ -5,6 +5,13 @@ yields: a python callable, a JSON schema for native tool-calling, an MCP tool,
and a prompt card. Observations are structured (text + numbers + images).
"""
-from codeverse.spatial.registry import Observation, ToolDef, ToolUsageError, get_tool, list_tools, tool
+from codeverse.spatial.registry import (
+ Observation,
+ ToolDef,
+ ToolUsageError,
+ get_tool,
+ list_tools,
+ tool,
+)
__all__ = ["Observation", "ToolDef", "ToolUsageError", "get_tool", "list_tools", "tool"]
diff --git a/harness/codeverse/spatial/registry.py b/harness/codeverse/spatial/registry.py
index a57f33f9..b2e5cff2 100644
--- a/harness/codeverse/spatial/registry.py
+++ b/harness/codeverse/spatial/registry.py
@@ -16,9 +16,10 @@ Observations: ``text`` (what the agent reads), ``numbers`` (machine-readable),
from __future__ import annotations
import inspect
+from collections.abc import Callable
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Any, Callable
+from typing import Any
from pydantic import BaseModel, Field
diff --git a/harness/docs/INSTALL.md b/harness/docs/INSTALL.md
new file mode 100644
index 00000000..16e659e7
--- /dev/null
+++ b/harness/docs/INSTALL.md
@@ -0,0 +1,556 @@
+# Installing the 3dcodeverse harness
+
+Everything below was executed on this machine (WSL2 Ubuntu, RTX 5090, Python
+3.13.9, node v24.14.0, Blender 5.0.1) on 2026-08-23; the version numbers and the
+`3dcodeverse doctor` output in §9 are real, not illustrative. Paths are relative
+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) ·
+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) ·
+8. [Keys, CLIs and settings](#8-keys-clis-and-settings) ·
+9. [Verify — `3dcodeverse doctor`](#9-verify--3dcodeverse-doctor) ·
+10. [5-minute smoke](#10-5-minute-smoke) · 11. [Uninstall / cleanup](#11-uninstall--cleanup) ·
+12. [Appendix: verified versions](#12-appendix-verified-versions-on-this-box)
+
+---
+
+## 1. TL;DR
+
+```bash
+git clone <repo> 3dcodeverse && cd 3dcodeverse
+bash harness/scripts/setup.sh # python + node deps + chrome + doctor
+```
+
+`scripts/setup.sh` is idempotent — it checks the interpreter versions, runs
+`pip install -e 'harness[all,dev]'`, runs `npm ci` in `runtime_js/` **only when the
+lockfile actually moved**, makes sure puppeteer's Chrome is downloaded, and
+finishes by printing `3dcodeverse doctor`. Useful flags:
+`--extras cad,urdf`, `--python /path/to/python`, `--no-node`, `--no-chrome`,
+`--no-doctor`, `--no-gpu`, `--force-npm`, `--help`.
+
+The manual equivalent:
+
+```bash
+pip install -e 'harness[all,dev]'
+cd harness/runtime_js && npm ci && npx puppeteer browsers install chrome && cd ..
+3dcodeverse doctor
+```
+
+> **Running installs on a busy box.** `npm ci` deletes `node_modules/` before
+> re-creating it, and `pip install -e` rewrites the entry points. If benches or
+> renders are running against this checkout, use `setup.sh` (which skips `npm ci`
+> when the lockfile is unchanged) or wait for them to finish.
+
+---
+
+## 2. Prerequisites
+
+| 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"` |
+| **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 |
+| **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) |
+
+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
+to (619 MB here after a week of benches).
+
+---
+
+## 3. Get the code
+
+```bash
+git clone <repo> 3dcodeverse
+cd 3dcodeverse
+```
+
+Layout: the harness is the `harness/` subdirectory (python dist `3dcodeverse`,
+import package `codeverse`, CLIs `3dcodeverse` and `3dcv`). See the repo
+`README.md` for the other top-level components.
+
+A virtualenv is recommended but not required — this box installs into a conda
+base env:
+
+```bash
+python -m venv .venv && source .venv/bin/activate # or: conda create -n cv3d python=3.13
+```
+
+---
+
+## 4. Python package + extras
+
+```bash
+pip install -e harness # core only
+pip install -e 'harness[all,dev]' # everything (what setup.sh does)
+```
+
+`-e` (editable) is the intended mode: the harness is developed in place and the
+console scripts (`3dcodeverse`, `3dcv`) point back at the checkout.
+
+Core dependencies (always installed): pydantic + pydantic-settings (contracts,
+settings), typer + rich (CLI), jinja2 (prompt templates), pyyaml, numpy, trimesh
+(mesh measurement), python-fcl (collision), pillow, google-genai, anthropic,
+openai, playwright.
+
+| extra | pulls | unlocks |
+|---|---|---|
+| `cad` | cadquery | the `cadquery` language (`--language cadquery`) |
+| `urdf` | yourdfpy, scipy | the `articulated_object` track: URDF parse/validate + joint math |
+| `graphics` | moderngl | the `graphics` track (`glsl_shader`, `opengl_python`) — headless GL rendering in `spatial/gl_render.py` |
+| `mesh` | shapely, networkx, manifold3d | `cross_section` filled-area/hollow ratio (shapely), mesh split / connectivity (networkx), joint-sweep boolean intersections (`trimesh.boolean(engine="manifold")`) |
+| `mcp` | mcp | `3dcv mcp` / `codeverse.spatial.mcp_server`, i.e. spatial tools for the `gemini-cli`, `claude-code` and `codex` backends |
+| `flywheel` | pyarrow | `3dcv flywheel export --pack` (parquet shards) |
+| `all` | all of the above | — |
+| `dev` | pytest, pytest-timeout, ruff | the test suite and the linter |
+
+`graphics`, `mesh`, `mcp` and `flywheel` are lazily imported: without them the
+harness installs and starts fine and only the named feature raises `ImportError`
+at the moment you use it. `3dcodeverse doctor` lists every one of these modules
+under `python deps` and only tolerates `manifold3d`, `yourdfpy`, `mcp`, `shapely`
+as WARN — everything else missing is a FAIL.
+
+Run the offline test suite to confirm the install:
+
+```bash
+cd harness
+python -m pytest tests -q -m "not live" # needs node + Blender for the full set
+python -m pytest tests -q -m "not live and not blender and not node" # pure-python subset
+```
+
+---
+
+## 5. runtime_js — the node side
+
+**Short answer to "is `runtime_js/node_modules` basically an installation of
+node.js?"** — no. Node.js itself is a *system prerequisite* you install once
+(§2). `runtime_js/` is a small **npm package owned by the harness**, and
+`node_modules/` is that package's dependency tree, downloaded by npm into the
+checkout. It is not optional decoration: apart from the `graphics` track, every
+render in the harness goes through it (`spatial/render.py` → `render_glb.mjs` →
+three.js in headless Chrome), whichever language produced the GLB.
+
+```
+harness/runtime_js/
+ package.json committed — 3 direct deps
+ package-lock.json committed — exact tree (100 packages), the reproducibility unit
+ node_modules/ NOT committed — .gitignore'd, ~97 MB, created by `npm ci`
+ *.mjs *.cjs lib/ the harness's own node code (see runtime_js/README.md)
+```
+
+Direct dependencies and what they are for:
+
+| package | version here | used for |
+|---|---|---|
+| `three` | 0.182.0 | GLB export (`export_glb.mjs`), the render rig, the scene host, GLSL preflight |
+| `puppeteer` | 24.43.1 | headless Chrome for WebGL rendering (`gpu_launch.cjs`, `browser_daemon.cjs`) |
+| `three-mesh-bvh` | 0.9.14 | accelerated raycasts in scene probes |
+
+### Install / refresh
+
+```bash
+cd harness/runtime_js
+npm ci # exact lockfile install; ~2 s, 100 packages, 95–97 MB
+npx puppeteer browsers install chrome # only if the Chrome cache is missing (see below)
+```
+
+Use **`npm ci`**, not `npm install`: `ci` installs exactly what
+`package-lock.json` pins and never rewrites it, which is what keeps renders
+reproducible. `npm ci` **deletes `node_modules/` first**, so do not run it while
+a bench or render is using this checkout.
+
+You need to re-run it when:
+
+* `node_modules/` does not exist (fresh clone — it is gitignored, so cloning
+ never brings it), or
+* you pulled a change to `runtime_js/package.json` / `package-lock.json`, or
+* `3dcodeverse doctor` reports `three` or `puppeteer` FAIL.
+
+`scripts/setup.sh` automates exactly that test: it compares the mtime of
+`package-lock.json` against `node_modules/.package-lock.json` and skips the
+reinstall when nothing moved (`--force-npm` overrides).
+
+### Chrome
+
+puppeteer downloads its own Chrome build (it does **not** use a system Chrome)
+into `~/.cache/puppeteer` — here `chrome/linux-148.0.7778.97` and
+`chrome-headless-shell/linux-148.0.7778.97`, 636 MB together. npm's
+`postinstall` normally does this for you; run the explicit command when the
+cache was cleared or when `PUPPETEER_SKIP_DOWNLOAD` was set:
+
+```bash
+cd harness/runtime_js && npx puppeteer browsers install chrome
+# [email protected] /home/yipeng/.cache/puppeteer/chrome/linux-148.0.7778.97/chrome-linux64/chrome
+```
+
+Re-running it is a no-op that just prints the cached path. `PUPPETEER_CACHE_DIR`
+moves the cache elsewhere (keep it consistent between install and run).
+
+### Why generated code never sees this directory
+
+Agent-written Three.js code is **raw** — it does `import * as THREE from 'three'`
+and nothing else; it never imports a harness module and never gets a
+`node_modules/` of its own inside the run workspace. The harness resolves that
+bare specifier for it in two places:
+
+* **node**: `node --import runtime_js/lib/resolve_three.mjs …` installs a
+ `registerHooks` resolver that redirects `three`, `three/addons/*` and
+ `three-mesh-bvh` into `runtime_js/node_modules`, for a module living anywhere
+ on disk (`NODE_PATH` cannot do this — it is CommonJS-only). Python side:
+ `spatial.node.run_node(..., three_hook=True)`.
+* **browser**: `serve.cjs` mounts `runtime_js/` at `/__runtime/` on the loopback
+ server and `importMapHtml()` emits an import map pointing `three` at
+ `/__runtime/node_modules/three/build/three.module.js`. Nothing is ever fetched
+ from a CDN.
+
+So `runtime_js/node_modules` is a *harness* dependency, on the same footing as
+the harness's python dependencies — not part of the generated artifact, and not
+something the agent may install into.
+
+---
+
+## 6. Blender
+
+Optional, but the `static_object` default language and the entire
+`articulated_object` track need it. Any headless-capable 4.2+ / 5.x build works.
+
+Option A — distro package (simplest, often older):
+
+```bash
+sudo apt-get install blender # or: brew install --cask blender
+```
+
+Option B — official tarball (what this box uses, no sudo needed); check
+<https://www.blender.org/download/> for the current file name:
+
+```bash
+mkdir -p ~/tools && cd ~/tools
+curl -LO https://download.blender.org/release/Blender5.0/blender-5.0.1-linux-x64.tar.xz
+tar xf blender-5.0.1-linux-x64.tar.xz
+~/tools/blender-5.0.1-linux-x64/blender --version
+```
+
+### The `LD_LIBRARY_PATH` wrapper trick
+
+The stock Linux build links `libSM.so.6` / `libICE.so.6` even in `--background`
+mode, and those are not installed system-wide here (no sudo). They were
+extracted from the Ubuntu debs into `~/.local/xlibs`, and a one-line wrapper on
+`PATH` prepends that directory to the loader path so no caller has to remember —
+`~/.local/bin/blender-5.0`:
+
+```bash
+#!/bin/bash
+BLENDER_HOME="${BLENDER_HOME:-/home/yipeng/3dcodeverse_data/tools/blender-5.0.1-linux-x64}"
+export LD_LIBRARY_PATH="/home/yipeng/.local/xlibs/usr/lib/x86_64-linux-gnu:${LD_LIBRARY_PATH}"
+exec "$BLENDER_HOME/blender" "$@"
+```
+
+Make it executable (`chmod +x ~/.local/bin/blender-5.0`) and keep the name — it
+is the first candidate the harness looks for. If your distro does have the X11
+libs, point the wrapper at the tarball and drop the `LD_LIBRARY_PATH` line, or
+skip the wrapper entirely.
+
+### How the harness finds it
+
+`Settings.resolve_blender()` (`codeverse/config.py`) returns the first hit of:
+
+1. `settings.binaries.blender` if that path exists — set it in the settings YAML
+ or with `CV3D_BINARIES__BLENDER=/path/to/blender`;
+2. `blender-5.0`, `blender`, `blender-5.1`, `blender-4.2` on `PATH`, in that order.
+
+Nothing found → `3dcodeverse doctor` reports `blender FAIL` and builds raise
+`BlenderNotFoundError`. Blender is always invoked `-b --factory-startup` with
+`PYTHONPATH`/`PYTHONHOME` stripped from the child env, so your conda env cannot
+leak into bpy.
+
+---
+
+## 7. GPU / headless rendering
+
+Nothing to install beyond the `graphics` extra (§4) and `runtime_js` (§5) — the
+harness picks the backend itself and both paths have a software fallback.
+
+* **Three.js / scenes** → headless Chrome via `runtime_js/gpu_launch.cjs`, which
+ tries `--use-angle=gl-egl` plus the Mesa d3d12 env and probes
+ `UNMASKED_RENDERER`; a negative verdict is cached 20 minutes in
+ `~/.cache/codeverse/gpu_probe.json`, and it falls back to SwiftShader.
+ Force with `CV3D_RENDER_GPU=on|off|auto` (node side) or `render.gpu` in the
+ settings YAML / `CV3D_RENDER__GPU`.
+* **graphics track** → moderngl in a fresh subprocess per render
+ (`spatial/gl_render.py`), which sets `GALLIUM_DRIVER=d3d12` +
+ `MESA_LOADER_DRIVER_OVERRIDE=d3d12` first and retries with
+ `LIBGL_ALWAYS_SOFTWARE=1` + llvmpipe if the context cannot be created. You do
+ not set these yourself.
+
+On a headless Linux server without a GPU, both fallbacks work out of the box;
+expect renders to take a few times longer. On WSL2 you need the vendor's WSL
+driver installed on the Windows side for the d3d12 path — check with
+`3dcodeverse doctor`'s `chrome webgl` row.
+
+---
+
+## 8. Keys, CLIs and settings
+
+### 8.1 Model API keys
+
+| variable | needed for | notes |
+|---|---|---|
+| `GEMINI_API_KEYS` | all `gemini:*` models (planner, judge, captioner, generators) | comma-separated list; the whole list becomes one `KeyPool` (per-key rate limits, 30 s cooldown on 429, dead keys benched 1 h) |
+| `GEMINI_API_KEY` / `GOOGLE_API_KEY` | same | single-key fallback when `GEMINI_API_KEYS` is unset |
+| `ANTHROPIC_API_KEY` | `anthropic:*` chat models | optional; not set here → those backends are unavailable (doctor WARN) |
+| `OPENAI_API_KEY` | `openai:*` chat models | optional; `CV3D_OPENAI_BASE_URL` points at a compatible gateway |
+
+Resolution order for the Gemini keys (`codeverse/config.py`), first non-empty wins:
+settings YAML `gemini_api_keys:` → `GEMINI_API_KEYS` (csv) → `GEMINI_API_KEY` /
+`GOOGLE_API_KEY` → the legacy compatibility file
+`~/.config/astra3d/gemini_keys.env`, from which a line
+`GEMINI_API_KEYS="key1,key2,…"` is read (this is where the 22 keys on this box
+come from). Duplicates are removed, order preserved. Keys are never written
+into run records.
+
+```bash
+export GEMINI_API_KEYS="key1,key2,key3" # e.g. in ~/.bashrc
+3dcodeverse doctor --live # one ~$0.00001 "pong" call
+```
+
+### 8.2 Subscription CLIs (all optional)
+
+Only needed if you want `--generator gemini-cli:… | claude-code:… | codex:… | agy:…`.
+The default generator (`api-agent:gemini:gemini-3.7-flash`) needs none of them.
+
+```bash
+npm i -g @google/gemini-cli # gemini (0.53.0 here)
+npm i -g @anthropic-ai/claude-code # claude (2.1.241 here)
+npm i -g @openai/codex # codex (0.149.0 here)
+# agy (Antigravity, 1.1.19 here) ships with the Antigravity IDE
+```
+
+`claude`, `codex` and `agy` authenticate against your local subscription (their
+own `login` flows) — test lightly. The harness handles the per-CLI quirks for
+you; the ones worth knowing:
+
+* **gemini-cli** — the harness writes a *system settings* file to
+ `~/.cache/codeverse/gemini_cli_settings.json` and passes it via
+ `GEMINI_CLI_SYSTEM_SETTINGS_PATH`, forcing three things (do not undo them):
+ `security.auth.selectedType = "gemini-api-key"` (a pool key is injected as
+ `GEMINI_API_KEY`, other credential env is stripped),
+ `experimental.dynamicModelConfiguration = true` — without it an unknown model
+ id is *silently substituted* and the run is flagged
+ `exit_reason=model_substituted` — and `security.folderTrust.enabled = false`,
+ without which the workspace MCP servers are silently ignored even with
+ `--skip-trust`, so the agent loses every spatial tool. A pre-existing OAuth
+ login of your own is overridden, not consumed.
+* **codex** — MCP tools need `default_tools_approval_mode="approve"`, which the
+ harness passes on the command line.
+* **agy** — no per-workspace MCP; spatial tools are reached through
+ `3dcv tools <name> --json … --workspace .` instead.
+
+The spatial MCP server itself is the `mcp` extra (§4); check it with
+`python -m codeverse.spatial.mcp_server --workspace <ws> --list`.
+
+### 8.3 Settings file and `CV3D_` overrides
+
+Loaded in this order, later wins: built-in defaults →
+`~/.config/codeverse/config.yaml` → `./codeverse.yaml` (current working
+directory) → `CV3D_*` environment variables. Neither YAML file is required —
+this box runs on defaults plus env.
+
+```yaml
+# ~/.config/codeverse/config.yaml
+runs_dir: /data/runs
+cache_dir: /data/cache/codeverse
+binaries:
+ blender: /home/yipeng/.local/bin/blender-5.0
+ ffmpeg: ffmpeg
+render:
+ gpu: auto # auto | on | off
+ width: 768
+limits:
+ agent_timeout_s: 1800
+ max_parallel_agents: 6
+default_judge: gemini:gemini-3.1-pro-preview
+default_candidates: 1
+```
+
+Env equivalents use the `CV3D_` prefix and `__` for nesting:
+
+```bash
+export CV3D_RUNS_DIR=/data/runs
+export CV3D_BINARIES__BLENDER=/opt/blender/blender
+export CV3D_RENDER__GPU=off
+export CV3D_LIMITS__AGENT_TIMEOUT_S=900
+export CV3D_DEFAULT_CANDIDATES=2
+```
+
+Three more are read directly by the runtime (not via `Settings`):
+`CV3D_RENDER_GPU` (`auto|on|off`, seen by the node/moderngl renderers),
+`CV3D_CACHE_DIR` (where `gpu_launch.cjs` puts the shared-browser endpoint file)
+and `CV3D_BROWSER_REUSE=off` (disable the shared headless-Chrome daemon).
+
+---
+
+## 9. Verify — `3dcodeverse doctor`
+
+```bash
+cd harness && 3dcodeverse doctor # add --live for one tiny Gemini call, --no-gpu to skip the Chrome probe, --json for machine output
+```
+
+Real output on this box (exit code 0; any FAIL row makes it exit 1):
+
+```
+ 3dcv doctor
+┏━━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
+┃ check ┃ status ┃ detail ┃
+┡━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
+│ python │ OK │ 3.13.9 (/home/yipeng/miniconda3/bin/python3.13) │
+│ python deps │ OK │ 21/21 importable │
+│ blender │ OK │ Blender 5.0.1 @ /home/yipeng/.local/bin/blender-5.0 │
+│ node │ OK │ v24.14.0 │
+│ three │ OK │ 0.182.0 (…/harness/runtime_js/node_modules) │
+│ puppeteer │ OK │ v24.43.1; chrome cache found (~/.cache/puppeteer) │
+│ chrome webgl │ OK │ GPU: ANGLE (Microsoft Corporation, D3D12 (NVIDIA │
+│ │ │ GeForce RTX 5090 Laptop GPU), OpenGL ES 3.1) │
+│ gemini keys │ OK │ 22 key(s) │
+│ anthropic key │ WARN │ not set (anthropic:* backends unavailable) │
+│ openai key │ WARN │ not set (openai:* backends unavailable) │
+│ gemini-cli │ OK │ 0.53.0 │
+│ claude │ OK │ 2.1.241 (Claude Code) │
+│ codex │ OK │ codex-cli 0.149.0 │
+│ agy │ OK │ 1.1.19 │
+│ git │ OK │ git version 2.53.0 │
+│ ffmpeg │ WARN │ not found (turntable mp4 disabled) │
+│ mcp │ OK │ mcp + codeverse.spatial.mcp_server importable │
+└───────────────┴────────┴─────────────────────────────────────────────────────┘
+```
+
+`--live` adds one more row (real output here, and the cheapest possible proof
+that the keys work end to end):
+
+```
+│ gemini live call │ OK │ 'pong' cost=$0.00001 │
+```
+
+### Troubleshooting table
+
+| row | status | meaning | fix |
+|---|---|---|---|
+| `python` | — | interpreter running the CLI | if it is not the interpreter you installed into, your shell is picking up another `3dcodeverse` — `which -a 3dcodeverse`, reinstall with `python -m pip install -e harness` |
+| `python deps` | FAIL | a core import is missing/broken | `pip install -e 'harness[all]'`; a broken native lib (`fcl`, `manifold3d`) shows up here too — reinstall that wheel (`pip install --force-reinstall python-fcl`) |
+| `python deps` | WARN | only `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` |
+| `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`) |
+| `chrome webgl` | WARN | Chrome launched but on SwiftShader | fine, just slower; on WSL2 install the vendor WSL GPU driver, on a server install Mesa EGL. `CV3D_RENDER_GPU=off` to stop probing |
+| `chrome webgl` | FAIL | the browser could not launch at all | usually missing shared libs for Chrome (`ldd ~/.cache/puppeteer/chrome/*/chrome-linux64/chrome \| grep -i "not found"`) or a stale endpoint file — `rm -f ~/.cache/codeverse/browser_*.lock` and retry; `--no-gpu` skips this probe |
+| `chrome webgl` | SKIP | `runtime_js/gpu_launch.cjs` not present | you are not in a full checkout |
+| `gemini keys` | FAIL | no keys resolved | `export GEMINI_API_KEYS="k1,k2"` (§8.1) — everything model-driven needs this |
+| `anthropic key` / `openai key` | WARN | not set | expected unless you use `anthropic:*` / `openai:*`; export the key to clear it |
+| `gemini-cli` / `claude` / `codex` / `agy` | WARN | CLI not on `PATH` | optional (§8.2); only that `--generator` is unavailable |
+| `git` | FAIL | git missing | install git — run workspaces are git repos |
+| `ffmpeg` | WARN | not found | optional; turntables become GIFs. `sudo apt-get install ffmpeg` (or `conda install -c conda-forge ffmpeg`) |
+| `mcp` | WARN | `mcp` package or the server module missing | `pip install -e 'harness[mcp]'`; only affects the agentic CLI backends |
+| `gemini live call` (`--live`) | FAIL | key rejected / no network | check the key value and outbound access; a `503 … high demand` is transient, not an install problem |
+
+---
+
+## 10. 5-minute smoke
+
+The cheapest end-to-end run is a single-shot shader on the `graphics` track
+(~$0.05, ~2 minutes, no Blender, no node). Point it at a throwaway runs
+directory so you do not mix it into real data:
+
+```bash
+cd harness
+3dcv make "a slow rotating neon hex grid" \
+ --track graphics --language glsl_shader \
+ --generator single-shot:gemini:gemini-3.7-flash \
+ --rounds 0 --max-usd 0.30 --max-minutes 20 \
+ --runs-dir /tmp/cv3d_smoke
+3dcv status <slug> --runs-dir /tmp/cv3d_smoke
+```
+
+If node and Blender are installed, the equivalent object-track smoke is
+`3dcv make "a simple wooden stool" --track static_object --language blender
+--generator single-shot:gemini:gemini-3.7-flash --rounds 0` (~$0.1, a few
+minutes).
+
+Artifacts land in `<runs-dir>/<slug>/`:
+
+```
+spec.json plan.json record.json run_state.json events.jsonl
+src/ the generated code (a git repo — one commit per round)
+artifacts/ build.json, census.json, measurement.json,
+ object.glb (object tracks) / frames/ + frames_sheet.png +
+ preview.gif + metrics.json (graphics)
+artifacts/renders/rNN/ per-round view PNGs + sheet.png
+artifacts/gates/rNN/ deterministic gate output
+artifacts/judge/rNN.json the VLM verdict and the computed score
+trajectories/ per-call transcripts
+```
+
+`3dcv status <slug>` prints the rounds table, cost and last events; the full
+operating guide is `docs/RUNBOOK.md`.
+
+> **`capacity storm N/10 … waiting Ns`** means the Gemini endpoint is busy, not
+> that your install is broken: the harness backs off (up to 10 waits, ~10 min in
+> total) and rotates keys. While the bench batteries on this box were saturating
+> `gemini-3.7-flash`, a smoke with `--max-minutes 8` gave up in the planner with
+> `status=budget … elapsed 11.2 min exceeds max_minutes 8.0` after spending
+> $0.0091 — hence the roomier `--max-minutes 20` above. `3dcv resume <slug>
+> --runs-dir …` continues from the last completed stage. To prove the key path
+> alone, `3dcodeverse doctor --live` is the one-call version
+> (`gemini live call OK 'pong' cost=$0.00001`).
+
+---
+
+## 11. Uninstall / cleanup
+
+```bash
+pip uninstall 3dcodeverse # removes the editable install + 3dcodeverse/3dcv
+rm -rf harness/runtime_js/node_modules # ~97 MB, re-creatable with `npm ci`
+rm -rf ~/.cache/puppeteer # ~636 MB of downloaded Chrome builds
+rm -rf ~/.cache/codeverse # harness cache (619 MB here) — see below
+rm -rf harness/3dcodeverse.egg-info harness/.pytest_cache harness/.ruff_cache
+```
+
+`~/.cache/codeverse` (or `cache_dir` / `CV3D_CACHE_DIR`) holds only regenerable
+things: `renders/` and `judge_images/` (render + montage cache), `textures/` and
+`texture_plans/` (texture-pass cache — deleting these costs real money to
+regenerate), `gpu_probe.json`, `gemini_cli_settings.json`, `browser_*.lock` (the shared
+headless-Chrome endpoint file — do not delete it while renders are running).
+
+**Your data is not in either cache.** `runs/`, `bench/out/` and any exported
+dataset are the flywheel output — delete them deliberately, never as part of a
+cleanup. On this machine `harness/runs/` (the `e2e_*` reference runs) and
+`harness/bench/out/` are read-only reference material.
+
+Uninstalling does not touch `~/.config/codeverse/config.yaml`,
+`~/.config/astra3d/gemini_keys.env` or the globally installed CLIs — remove
+those by hand (`npm rm -g @google/gemini-cli @anthropic-ai/claude-code @openai/codex`).
+
+---
+
+## 12. Appendix: verified versions on this box
+
+| component | version | where |
+|---|---|---|
+| python | 3.13.9 | `/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` |
+| 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` |
+| git | 2.53.0 | `/usr/bin/git` |
+| ffmpeg | not installed | — |
+| gemini-cli / claude / codex / agy | 0.53.0 / 2.1.241 / 0.149.0 / 1.1.19 | npm global / `~/.local/bin` |
+| GPU (Chrome WebGL) | ANGLE · D3D12 · NVIDIA GeForce RTX 5090 Laptop GPU · OpenGL ES 3.1 | via `--use-angle=gl-egl` + Mesa d3d12 |
diff --git a/harness/pyproject.toml b/harness/pyproject.toml
index 9c5a1ede..e99fc6c1 100644
--- a/harness/pyproject.toml
+++ b/harness/pyproject.toml
@@ -27,8 +27,14 @@ dependencies = [
]
[project.optional-dependencies]
-cad = ["cadquery>=2.4"]
-urdf = ["yourdfpy>=0.0.56", "scipy>=1.11"]
+# What each extra unlocks is documented in docs/INSTALL.md §4.
+cad = ["cadquery>=2.4"] # language `cadquery`
+urdf = ["yourdfpy>=0.0.56", "scipy>=1.11"] # track `articulated_object` (urdf_blender)
+graphics = ["moderngl>=5.8"] # track `graphics` (glsl_shader / opengl_python)
+mesh = ["shapely>=2.0", "networkx>=3.2", "manifold3d>=2.3"] # cross_section area, mesh split, joint-sweep booleans
+mcp = ["mcp>=1.0"] # `3dcv mcp` spatial-tool server for the agentic CLIs
+flywheel = ["pyarrow>=15"] # `3dcv flywheel export --pack` (parquet)
+all = ["3dcodeverse[cad,urdf,graphics,mesh,mcp,flywheel]"]
dev = ["pytest>=8", "pytest-timeout>=2.3", "ruff>=0.5"]
[project.scripts]
diff --git a/harness/runtime_js/README.md b/harness/runtime_js/README.md
index 92a0ce6d..33f5001f 100644
--- a/harness/runtime_js/README.md
+++ b/harness/runtime_js/README.md
@@ -2,7 +2,32 @@
Everything Three.js / headless-Chrome the harness does lives here. **Agent code
never imports from this directory**; it only imports `three` (and
-`three/addons/...`), which the harness resolves for it.
+`three/addons/...`), which the harness resolves for it — through the
+`--import lib/resolve_three.mjs` hook in node, and through the import map
+`serve.cjs::importMapHtml()` in the browser (runtime_js is mounted at
+`/__runtime/`; nothing is fetched from a CDN).
+
+## Install
+
+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.
+
+```bash
+cd harness/runtime_js
+npm ci # exact-lockfile install (~2 s); NOT `npm install`
+npx puppeteer browsers install chrome # only if ~/.cache/puppeteer is empty
+```
+
+`bash harness/scripts/setup.sh` does both of these (plus the python install and
+`3dcodeverse doctor`) and skips `npm ci` when the lockfile has not moved.
+
+Re-run `npm ci` after a fresh clone or after pulling a `package.json` /
+`package-lock.json` change — it deletes `node_modules/` first, so never while a
+render or bench is running. Deps: `three` 0.182 (export + render + scene host),
+`puppeteer` 24 (headless Chrome, downloads its own build into `~/.cache/puppeteer`),
+`three-mesh-bvh` 0.9.14 (accelerated raycasts). Full guide: `../docs/INSTALL.md`.
```
gpu_launch.cjs launchBrowser({gpu:'auto'|'on'|'off'}) → {browser, gpu, renderer, shared, release()};
@@ -63,7 +88,7 @@ Python entry points: `codeverse.spatial.node.run_node`, `codeverse.spatial.rende
`codeverse.languages.threejs.ThreeJsRuntime`.
Quick checks:
-```
+```bash
node --import lib/resolve_three.mjs export_glb.mjs --ws /path/to/ws
node render_glb.mjs --glb ws/artifacts/object.glb --out /tmp/r --views '[{"name":"front","azimuth":0,"elevation":10}]'
```
diff --git a/harness/runtime_js/lib/backdrop.mjs b/harness/runtime_js/lib/backdrop.mjs
new file mode 100644
index 00000000..ba06f9c8
--- /dev/null
+++ b/harness/runtime_js/lib/backdrop.mjs
@@ -0,0 +1,39 @@
+/**
+ * Backdrop classification — THE single owner of "is this drawable sky, ground
+ * or content?" for a scene. Used by the census (`host_census.mjs`, which
+ * decides what `content_bbox` covers) and by the frame-coverage instrument
+ * (`host_coverage.mjs`, which masks the same three classes per frame), so the
+ * word "content" means exactly one thing everywhere.
+ *
+ * Rules (name + world-box shape, in order):
+ * sky a sky-ish name spanning > 50 m, or anything enormous (span > 2 km,
+ * or tall AND wide: sy > 300 with span > 300)
+ * content an InstancedMesh (scatter spans the map but is not ground)
+ * ground a ground-ish name on a wide, flat box (span > 20, sy < 6 % of span)
+ * or any very wide, very flat box (span > 40, sy < 2 % of span)
+ * or — only when `contentSpan` is known (coverage) — a flat box far
+ * larger than the content itself (span > 2.5 × contentSpan)
+ * content everything else
+ */
+
+export const SKY_NAME_RE = /\b(sky|skydome|skybox|stars|clouds?|sun|moon|atmosphere)\b/i;
+export const GROUND_NAME_RE = /\b(ground|terrain|floor|water|ocean|sea|lake|river|plane|sand|grass|land)\b/i;
+
+/**
+ * 'sky' | 'ground' | 'content' for one drawable with world box `box`.
+ * @param {object} obj mesh/points/line/sprite (only `name`, `parent`, `isInstancedMesh` are read)
+ * @param {{min:{x,y,z}, max:{x,y,z}}} box world-space AABB
+ * @param {number} contentSpan horizontal span of the known content bbox (0 = unknown)
+ */
+export function classifyBackdrop(obj, box, contentSpan = 0) {
+ const name = obj.name || (obj.parent && obj.parent.name) || '';
+ const sx = box.max.x - box.min.x, sy = box.max.y - box.min.y, sz = box.max.z - box.min.z;
+ const span = Math.max(sx, sz);
+ if (SKY_NAME_RE.test(name) && span > 50) return 'sky';
+ if (span > 2000 || (sy > 300 && span > 300)) return 'sky';
+ if (obj.isInstancedMesh) return 'content'; // scattered instances span the map but are not ground
+ if (span > 20 && sy < 0.06 * span && GROUND_NAME_RE.test(name)) return 'ground';
+ if (span > 40 && sy < 0.02 * span) return 'ground';
+ if (contentSpan > 0 && span > 2.5 * contentSpan && sy < 0.1 * span) return 'ground';
+ return 'content';
+}
diff --git a/harness/runtime_js/lib/browser/camera_fit.js b/harness/runtime_js/lib/browser/camera_fit.js
index 11720c89..c80b1483 100644
--- a/harness/runtime_js/lib/browser/camera_fit.js
+++ b/harness/runtime_js/lib/browser/camera_fit.js
@@ -1,5 +1,6 @@
-// Camera fitting shared by the object and scene renderers (browser ESM; imports 'three'
-// through the page's import map).
+// Camera fitting for the OBJECT rig (browser ESM; imports 'three' through the page's
+// import map). The distance math itself is shared with the scene orbit rig —
+// `fitDistance` in /__runtime/lib/orbit.mjs is the single owner (pure, no three).
//
// import { viewDirection, fitCameraToBox } from '/__runtime/lib/browser/camera_fit.js';
//
@@ -7,14 +8,13 @@
// from above (90 = camera on +X = the object's right side); elevation above the horizon.
import * as THREE from 'three';
+import { fitDistance, orbitDirection } from '../orbit.mjs';
const DEG = Math.PI / 180;
/** Unit vector from the target towards the camera for (azimuth, elevation) in degrees. */
export function viewDirection(azimuthDeg, elevationDeg) {
- const az = azimuthDeg * DEG;
- const el = elevationDeg * DEG;
- return new THREE.Vector3(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el));
+ return new THREE.Vector3(...orbitDirection(azimuthDeg, elevationDeg));
}
/** The 8 corners of a Box3. */
@@ -26,44 +26,37 @@ export function boxCorners(box) {
return out;
}
+/**
+ * Screen-up for a view: near-vertical views make (0,1,0) ~collinear with the
+ * view direction, which makes lookAt's roll unstable — pin up to -Z (front at
+ * the bottom, like a plan drawing).
+ */
+function screenUp(elevationDeg) {
+ if (Math.abs(elevationDeg) > 60) return [0, 0, elevationDeg > 0 ? -1 : 1];
+ return [0, 1, 0];
+}
+
/**
* Place `camera` along (azimuth, elevation) from the box centre so that the
- * projected bbox corners fill `fill` of the half-frame (both axes). Projected
- * extent is ~1/distance, so a few multiplicative iterations converge.
+ * projected bbox corners fill `fill` of the half-frame (both axes).
* Returns {position, lookAt, distance}.
*/
-export function fitCameraToBox(camera, box, azimuthDeg, elevationDeg, { fill = 0.85, iterations = 8, margin = 1.0 } = {}) {
+export function fitCameraToBox(camera, box, azimuthDeg, elevationDeg, { fill = 0.85, margin = 1.0 } = {}) {
const center = box.getCenter(new THREE.Vector3());
const size = box.getSize(new THREE.Vector3());
- const radius = Math.max(size.length() / 2, 1e-3) * margin;
+ const radius = Math.max(size.length() / 2, 1e-3) * margin; // near/far scale only
const dir = viewDirection(azimuthDeg, elevationDeg);
- // Near-vertical views: (0,1,0) is ~collinear with the view direction which makes
- // lookAt's roll unstable; pin screen-up to -Z (front at the bottom, like a plan).
- if (Math.abs(elevationDeg) > 60) camera.up.set(0, 0, elevationDeg > 0 ? -1 : 1);
- else camera.up.set(0, 1, 0);
+ const up = screenUp(elevationDeg);
+ camera.up.set(up[0], up[1], up[2]);
- const fovRad = camera.fov * DEG;
- let d = radius / Math.sin(fovRad / 2);
- const corners = boxCorners(box);
- for (let i = 0; i < iterations; i++) {
- camera.position.copy(center).addScaledVector(dir, d);
- camera.lookAt(center);
- camera.near = Math.max(d * 0.01, 1e-4);
- camera.far = d * 10 + radius * 4;
- camera.updateProjectionMatrix();
- camera.updateMatrixWorld(true);
- let maxExt = 1e-6;
- for (const c of corners) {
- const ndc = c.clone().project(camera);
- maxExt = Math.max(maxExt, Math.abs(ndc.x), Math.abs(ndc.y));
- }
- const next = d * (maxExt / fill);
- if (Math.abs(next - d) < 1e-4 * d) {
- d = next;
- break;
- }
- d = next;
- }
+ const tanV = Math.tan((camera.fov * DEG) / 2);
+ const d = Math.max(
+ 1e-4,
+ fitDistance(
+ { min: box.min.toArray(), max: box.max.toArray() },
+ center.toArray(), dir.toArray(), tanV * camera.aspect, tanV, 1 / fill, up,
+ ),
+ );
camera.position.copy(center).addScaledVector(dir, d);
camera.lookAt(center);
camera.near = Math.max(d * 0.01, 1e-4);
diff --git a/harness/runtime_js/lib/browser/renderer.js b/harness/runtime_js/lib/browser/renderer.js
new file mode 100644
index 00000000..791f4baf
--- /dev/null
+++ b/harness/runtime_js/lib/browser/renderer.js
@@ -0,0 +1,41 @@
+// THE WebGLRenderer factory for every page-side rig (object renders through
+// studio.js/render_rig.js, scenes through scene_host.mjs): one set of fixed
+// harness settings — antialias, pixel ratio 1, sRGB output, ACES tone mapping,
+// PCF soft shadows, preserveDrawingBuffer (canvas readback) — so an object
+// render and a scene render expose the same colour pipeline.
+//
+// import { makeRenderer, rendererString } from '/__runtime/lib/browser/renderer.js';
+
+import * as THREE from 'three';
+
+/**
+ * WebGLRenderer on `canvas` sized width x height (device pixel ratio 1).
+ * @param {{transparent?: boolean, logDepth?: boolean}} opts
+ * transparent - alpha buffer (transparent background renders)
+ * logDepth - logarithmic depth buffer (huge scenes)
+ */
+export function makeRenderer(canvas, width, height, { transparent = false, logDepth = false } = {}) {
+ const renderer = new THREE.WebGLRenderer({
+ canvas,
+ antialias: true,
+ alpha: transparent,
+ preserveDrawingBuffer: true,
+ powerPreference: 'high-performance',
+ logarithmicDepthBuffer: !!logDepth,
+ });
+ renderer.setPixelRatio(1);
+ renderer.setSize(width, height, false);
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.0;
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+ return renderer;
+}
+
+/** UNMASKED_RENDERER_WEBGL string (or the masked one) of a renderer's context. */
+export function rendererString(renderer) {
+ const gl = renderer.getContext();
+ const ext = gl.getExtension('WEBGL_debug_renderer_info');
+ return String(ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER));
+}
diff --git a/harness/runtime_js/lib/browser/studio.js b/harness/runtime_js/lib/browser/studio.js
index 4006235a..06f447b2 100644
--- a/harness/runtime_js/lib/browser/studio.js
+++ b/harness/runtime_js/lib/browser/studio.js
@@ -1,32 +1,18 @@
// Neutral studio look for object renders: RoomEnvironment PMREM + key/fill/rim
-// directionals, ACES tone mapping, sRGB output, optional shadow catcher.
+// directionals, optional shadow catcher, and the shared renderer factory
+// (renderer.js: ACES tone mapping, sRGB output, PCF shadows).
//
// import { makeRenderer, buildStudio, applyMode } from '/__runtime/lib/browser/studio.js';
import * as THREE from 'three';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { makeRenderer, rendererString } from './renderer.js';
-export const BACKGROUNDS = { studio: 0xe9e9ec, white: 0xffffff, transparent: null };
-
-/** WebGLRenderer on `canvas` sized width x height (device pixel ratio 1). */
-export function makeRenderer(canvas, width, height, { transparent = false } = {}) {
- const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: transparent, preserveDrawingBuffer: true, powerPreference: 'high-performance' });
- renderer.setPixelRatio(1);
- renderer.setSize(width, height, false);
- renderer.outputColorSpace = THREE.SRGBColorSpace;
- renderer.toneMapping = THREE.ACESFilmicToneMapping;
- renderer.toneMappingExposure = 1.0;
- renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = THREE.PCFSoftShadowMap;
- return renderer;
-}
+// the renderer factory lives in renderer.js (shared with the scene host); it is
+// re-exported here because studio.js is the object rig's one-stop import
+export { makeRenderer, rendererString };
-/** UNMASKED_RENDERER_WEBGL string (or the masked one). */
-export function rendererString(renderer) {
- const gl = renderer.getContext();
- const ext = gl.getExtension('WEBGL_debug_renderer_info');
- return String(ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER));
-}
+export const BACKGROUNDS = { studio: 0xe9e9ec, white: 0xffffff, transparent: null };
/**
* Add environment + lights (+ shadow catcher) to `scene`, scaled to `box`.
diff --git a/harness/runtime_js/lib/host_census.mjs b/harness/runtime_js/lib/host_census.mjs
index e5ced1b5..ac9d7925 100644
--- a/harness/runtime_js/lib/host_census.mjs
+++ b/harness/runtime_js/lib/host_census.mjs
@@ -2,18 +2,12 @@
* Deterministic scene census (page-side, pure over a THREE.Scene).
* Counts meshes / instances / lights / triangles / custom-shader materials,
* measures per top-level group (zone) world bboxes, classifies sky/ground
- * groups, computes a content bbox (sky + ground excluded) and pairwise zone
+ * groups (shared rules: `backdrop.mjs`), computes a content bbox (sky + ground excluded) and pairwise zone
* overlap statistics. Returns plain JSON.
*/
-function triCount(geom) {
- if (!geom || !geom.attributes || !geom.attributes.position) return 0;
- const n = geom.index ? geom.index.count : geom.attributes.position.count;
- if (geom.drawRange && Number.isFinite(geom.drawRange.count) && geom.drawRange.count !== Infinity) {
- return Math.floor(Math.min(n, geom.drawRange.count) / 3);
- }
- return Math.floor(n / 3);
-}
+import { classifyBackdrop } from './backdrop.mjs';
+import { geometryTriangles as triCount } from './census.mjs';
export function isCustomShader(mat, THREE) {
if (!mat) return false;
@@ -31,22 +25,6 @@ function boxToJson(box) {
};
}
-const SKY_NAME_RE = /\b(sky|skydome|skybox|stars|clouds?|sun|moon|atmosphere)\b/i;
-const GROUND_NAME_RE = /\b(ground|terrain|floor|water|ocean|sea|lake|river|plane|sand|grass|land)\b/i;
-
-/** Classify one mesh as 'sky' | 'ground' | 'content' from name + world box. */
-function classifyMesh(mesh, box) {
- const name = mesh.name || (mesh.parent && mesh.parent.name) || '';
- const sx = box.max.x - box.min.x, sy = box.max.y - box.min.y, sz = box.max.z - box.min.z;
- const span = Math.max(sx, sz);
- if (SKY_NAME_RE.test(name) && span > 50) return 'sky';
- if (span > 2000 || (sy > 300 && span > 300)) return 'sky';
- if (mesh.isInstancedMesh) return 'content'; // scattered instances span the map but are not ground
- if (span > 20 && sy < 0.06 * span && GROUND_NAME_RE.test(name)) return 'ground';
- if (span > 40 && sy < 0.02 * span) return 'ground';
- return 'content';
-}
-
function walkGroup(root, THREE) {
let meshes = 0, instances = 0, tris = 0, lights = 0, custom = 0;
const kinds = { sky: 0, ground: 0, content: 0 };
@@ -81,7 +59,7 @@ function walkGroup(root, THREE) {
mb.copy(gb).applyMatrix4(o.matrixWorld);
}
if (mb.isEmpty()) return;
- const kind = classifyMesh(o, mb);
+ const kind = classifyBackdrop(o, mb); // shared rules (lib/backdrop.mjs); no content bbox yet here
kinds[kind] += 1;
boxAll.union(mb);
if (kind === 'content') box.union(mb);
diff --git a/harness/runtime_js/lib/host_coverage.mjs b/harness/runtime_js/lib/host_coverage.mjs
index f02c5f68..0a60008a 100644
--- a/harness/runtime_js/lib/host_coverage.mjs
+++ b/harness/runtime_js/lib/host_coverage.mjs
@@ -5,30 +5,17 @@
* fog/background off, a flat white override material on everything left —
* followed by a downscaled readback. `sky_frac` is the remainder.
*
- * The backdrop classifier mirrors the census rules (name + world-bbox size) so
- * "content" here means the same thing as `census.content_bbox`; a mesh is also
- * backdrop when its footprint is far larger than the content bbox (scatter
- * across the whole ground).
+ * The backdrop classifier is shared with the census (`lib/backdrop.mjs`) so
+ * "content" here means the same thing as `census.content_bbox`; passing the
+ * content span additionally treats a mesh whose footprint is far larger than
+ * the content bbox (scatter across the whole ground) as backdrop.
*/
-const SAMPLE_W = 96;
-const SAMPLE_H = 54;
-const SKY_NAME_RE = /\b(sky|skydome|skybox|stars|clouds?|sun|moon|atmosphere)\b/i;
-const GROUND_NAME_RE = /\b(ground|terrain|floor|water|ocean|sea|lake|river|plane|sand|grass|land)\b/i;
+import { classifyBackdrop } from './backdrop.mjs';
+import { sampleFrame } from './host_metrics.mjs';
+
+export { classifyBackdrop }; // re-export: this module used to own the classifier
-/** 'sky' | 'ground' | 'content' for one drawable with world box `box`. */
-export function classifyBackdrop(obj, box, contentSpan) {
- const name = obj.name || (obj.parent && obj.parent.name) || '';
- const sx = box.max.x - box.min.x, sy = box.max.y - box.min.y, sz = box.max.z - box.min.z;
- const span = Math.max(sx, sz);
- if (SKY_NAME_RE.test(name) && span > 50) return 'sky';
- if (span > 2000 || (sy > 300 && span > 300)) return 'sky';
- if (obj.isInstancedMesh) return 'content';
- if (span > 20 && sy < 0.06 * span && GROUND_NAME_RE.test(name)) return 'ground';
- if (span > 40 && sy < 0.02 * span) return 'ground';
- if (contentSpan > 0 && span > 2.5 * contentSpan && sy < 0.1 * span) return 'ground';
- return 'content';
-}
function collectDrawables(scene, THREE, contentSpan) {
const out = [];
@@ -47,13 +34,7 @@ function collectDrawables(scene, THREE, contentSpan) {
}
function brightFraction(canvas) {
- const small = document.createElement('canvas');
- small.width = SAMPLE_W;
- small.height = SAMPLE_H;
- const ctx = small.getContext('2d', { willReadFrequently: true });
- ctx.drawImage(canvas, 0, 0, SAMPLE_W, SAMPLE_H);
- const { data } = ctx.getImageData(0, 0, SAMPLE_W, SAMPLE_H);
- const n = SAMPLE_W * SAMPLE_H;
+ const { data, n } = sampleFrame(canvas);
let bright = 0;
for (let i = 0; i < n; i++) {
if (data[i * 4] + data[i * 4 + 1] + data[i * 4 + 2] > 3 * 64) bright += 1;
diff --git a/harness/runtime_js/lib/host_env.mjs b/harness/runtime_js/lib/host_env.mjs
index c64a3502..c5a6b79f 100644
--- a/harness/runtime_js/lib/host_env.mjs
+++ b/harness/runtime_js/lib/host_env.mjs
@@ -2,7 +2,8 @@
* Node-side environment for the scene host drivers: browser launch and
* workspace serving. Thin ESM adapters over the two CJS runtime modules —
* `gpu_launch.cjs` (GPU-verified headless Chrome) and `serve.cjs` (loopback
- * static server + import map). Single consumer: `lib/host_page.mjs`.
+ * static server + import map). Consumers: `lib/host_page.mjs` (scenes) and
+ * `render_glb.mjs` (objects) — no other module reaches for the CJS files.
*/
import path from 'node:path';
@@ -24,6 +25,16 @@ export async function launchBrowser(opts = {}) {
return gpuLaunch.launchBrowser(opts);
}
+/**
+ * Serve arbitrary directories / in-memory routes (see serve.cjs); runtime_js is
+ * always mounted at `runtimeMount()`. The object renderer serves the GLB's
+ * directory this way; scenes go through `serveWorkspace` below.
+ * @returns {Promise<{server, base: string, url: (p: string) => string, close: () => Promise<void>}>}
+ */
+export async function serveDirs(opts = {}) {
+ return serve.serveDirs(opts);
+}
+
/** URL prefix under which runtime_js is served ('/__runtime/'). */
export function runtimeMount() {
return serve.RUNTIME_MOUNT;
diff --git a/harness/runtime_js/lib/host_metrics.mjs b/harness/runtime_js/lib/host_metrics.mjs
index dc66ff10..849a918e 100644
--- a/harness/runtime_js/lib/host_metrics.mjs
+++ b/harness/runtime_js/lib/host_metrics.mjs
@@ -3,18 +3,28 @@
* readback of the render canvas and near-geometry tests for a camera.
*/
-const SAMPLE_W = 96;
-const SAMPLE_H = 54;
+export const SAMPLE_W = 96;
+export const SAMPLE_H = 54;
-/** Mean luminance and dark/blown fractions of the current canvas. */
-export function frameStats(canvas) {
+/**
+ * Downscaled RGBA readback of `canvas` on the shared 96x54 sampling grid.
+ * THE one place a render canvas is sampled page-side (frame statistics here,
+ * coverage mask passes in host_coverage.mjs) — same grid, same cost, so the
+ * numbers of the two instruments are comparable.
+ * @returns {{data: Uint8ClampedArray, n: number}}
+ */
+export function sampleFrame(canvas) {
const small = document.createElement('canvas');
small.width = SAMPLE_W;
small.height = SAMPLE_H;
const ctx = small.getContext('2d', { willReadFrequently: true });
ctx.drawImage(canvas, 0, 0, SAMPLE_W, SAMPLE_H);
- const { data } = ctx.getImageData(0, 0, SAMPLE_W, SAMPLE_H);
- const n = SAMPLE_W * SAMPLE_H;
+ return { data: ctx.getImageData(0, 0, SAMPLE_W, SAMPLE_H).data, n: SAMPLE_W * SAMPLE_H };
+}
+
+/** Mean luminance and dark/blown fractions of the current canvas. */
+export function frameStats(canvas) {
+ const { data, n } = sampleFrame(canvas);
let sum = 0, sumSq = 0, dark = 0, blown = 0;
let top = 0, bottom = 0;
const hist = new Uint32Array(8);
diff --git a/harness/runtime_js/lib/orbit.mjs b/harness/runtime_js/lib/orbit.mjs
index 77c1f7e8..4b0dcc3b 100644
--- a/harness/runtime_js/lib/orbit.mjs
+++ b/harness/runtime_js/lib/orbit.mjs
@@ -67,10 +67,18 @@ function corners(bbox) {
/**
* Smallest distance along `dir` (unit, from `center`) at which every corner sits
* inside a camera looking back at `center` with the given half-angle tangents.
+ *
+ * THE distance fit for both rigs: the scene orbit (this module) and the object
+ * rig (`browser/camera_fit.js`, which passes the screen-up vector it gives the
+ * THREE camera). Exact per-corner solution — the projected half-extent of a
+ * corner is `(offAxis * margin) / (tan · (dist - depthOffset))`, so requiring
+ * ≤ 1 on both axes for all eight corners is one max, no iteration.
+ * @param {number[]|null} upHint screen-up used for the roll (default: +Y, or
+ * -Z for an exactly vertical view — what THREE's lookAt does)
*/
-export function fitDistance(bbox, center, dir, tanH, tanV, margin) {
+export function fitDistance(bbox, center, dir, tanH, tanV, margin, upHint = null) {
// same roll as THREE's lookAt (world up = +Y unless the view is exactly vertical)
- const up0 = Math.abs(dir[1]) > 0.9999 ? [0, 0, -1] : [0, 1, 0];
+ const up0 = upHint || (Math.abs(dir[1]) > 0.9999 ? [0, 0, -1] : [0, 1, 0]);
const f = dir.map((v) => -v); // forward; right = forward × up0; up = right × forward
const cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
const norm = (v) => { const l = Math.hypot(...v) || 1; return v.map((x) => x / l); };
diff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjs
index 9350fbcc..af427e07 100644
--- a/harness/runtime_js/lib/scene_host.mjs
+++ b/harness/runtime_js/lib/scene_host.mjs
@@ -19,6 +19,7 @@ import { frameStats, nearGeometry } from './host_metrics.mjs';
import { frameCoverage } from './host_coverage.mjs';
import { installShaderErrorHook } from './host_shader_errors.mjs';
import { attributeErrors, captured, captureMaterialSources, materialAudit, stripCustomShaders } from './host_compile.mjs';
+import { makeRenderer, rendererString } from './browser/renderer.js';
const FIXED_DT = 1 / 30;
const LOAD_IDLE_TIMEOUT_MS = 30000;
@@ -64,27 +65,14 @@ function runUpdate(t, dt) {
}
}
-function makeRenderer(width, height, opts) {
+/** Host canvas + the shared harness renderer (lib/browser/renderer.js). */
+function makeHostRenderer(width, height, opts) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
canvas.id = '3dcv-canvas';
document.body.appendChild(canvas);
- const renderer = new THREE.WebGLRenderer({
- canvas,
- antialias: true,
- preserveDrawingBuffer: true,
- powerPreference: 'high-performance',
- logarithmicDepthBuffer: !!opts.logDepth,
- });
- renderer.setPixelRatio(1);
- renderer.setSize(width, height, false);
- renderer.outputColorSpace = THREE.SRGBColorSpace;
- renderer.toneMapping = THREE.ACESFilmicToneMapping;
- renderer.toneMappingExposure = 1.0;
- renderer.shadowMap.enabled = true;
- renderer.shadowMap.type = THREE.PCFSoftShadowMap;
- return { renderer, canvas };
+ return { renderer: makeRenderer(canvas, width, height, { logDepth: !!opts.logDepth }), canvas };
}
function validateCameras(raw) {
@@ -147,14 +135,12 @@ async function boot(opts) {
state.height = opts.height || 576;
window.requestAnimationFrame = () => { state.rafCalls += 1; return 0; };
window.cancelAnimationFrame = () => {};
- const { renderer, canvas } = makeRenderer(state.width, state.height, opts);
+ const { renderer, canvas } = makeHostRenderer(state.width, state.height, opts);
state.renderer = renderer;
state.canvas = canvas;
installShaderErrorHook(renderer, state.shaderErrors);
try {
- const gl = renderer.getContext();
- const ext = gl.getExtension('WEBGL_debug_renderer_info');
- info.renderer = String(ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER));
+ info.renderer = rendererString(renderer);
} catch (e) { info.renderer = 'unknown'; }
info.stage = 'import';
diff --git a/harness/runtime_js/lib/shader_report.mjs b/harness/runtime_js/lib/shader_report.mjs
index b6da4c48..a223e4ba 100644
--- a/harness/runtime_js/lib/shader_report.mjs
+++ b/harness/runtime_js/lib/shader_report.mjs
@@ -16,20 +16,18 @@ import fs from 'node:fs';
import path from 'node:path';
import { auditFile, fixHintFor, hasGlsl, locateSourceLine } from './glsl_audit.mjs';
import { errorSummary } from './host_page.mjs';
+import { listJsFiles } from './syntax_check.mjs';
-/** All .js/.mjs sources under <root>/<sub> as [{file, text}] (posix rel paths). */
+/**
+ * All .js/.mjs sources under <root>/<sub> as [{file, text}] (posix rel paths,
+ * sorted). The directory walk itself is `syntax_check.listJsFiles` — the one
+ * source-file walker in runtime_js.
+ */
export function listSources(root, sub = 'src') {
- const out = [];
- const walk = (dir) => {
- if (!fs.existsSync(dir)) return;
- for (const ent of fs.readdirSync(dir, { withFileTypes: true })) {
- const p = path.join(dir, ent.name);
- if (ent.isDirectory()) { if (ent.name !== 'node_modules') walk(p); continue; }
- if (/\.(m?js)$/.test(ent.name)) out.push({ file: path.relative(root, p).split(path.sep).join('/'), text: fs.readFileSync(p, 'utf8') });
- }
- };
- walk(path.join(root, sub));
- return out;
+ return listJsFiles(path.join(root, sub)).map((p) => ({
+ file: path.relative(root, p).split(path.sep).join('/'),
+ text: fs.readFileSync(p, 'utf8'),
+ }));
}
/**
diff --git a/harness/runtime_js/render_glb.mjs b/harness/runtime_js/render_glb.mjs
index e298b815..25859d63 100644
--- a/harness/runtime_js/render_glb.mjs
+++ b/harness/runtime_js/render_glb.mjs
@@ -9,36 +9,27 @@
// Writes <out>/view_<name>.png for every view + <out>/views.json, and prints one JSON
// line last on stdout: {ok, renderer, gpu, views:[{name,path,camera_position,look_at,fov,...}],
// warnings, timing_ms}. Exit 1 (with {ok:false,error}) on any failure.
+//
+// Thin driver: arg parsing / JSON-last-line protocol come from lib/cli.mjs, the
+// browser + static server from lib/host_env.mjs, the browser release dance from
+// lib/host_page.mjs, and everything visual from lib/browser/render_rig.js.
import fs from 'node:fs';
import path from 'node:path';
-import { parseArgs } from 'node:util';
-import { createRequire } from 'node:module';
-const require = createRequire(import.meta.url);
-const { launchBrowser } = require('./gpu_launch.cjs');
-const { serveDirs, importMapHtml, RUNTIME_MOUNT } = require('./serve.cjs');
+import { ensureDir, finish, parseCli, writeJson } from './lib/cli.mjs';
+import { launchBrowser, importMapHtml, runtimeMount, serveDirs } from './lib/host_env.mjs';
+import { releaseBrowser } from './lib/host_page.mjs';
const MODES = ['shaded', 'wire', 'normals', 'silhouette', 'clay'];
-function cli() {
- const { values } = parseArgs({
- options: {
- glb: { type: 'string' },
- out: { type: 'string' },
- views: { type: 'string' },
- mode: { type: 'string', default: 'shaded' },
- width: { type: 'string', default: '768' },
- height: { type: 'string', default: '768' },
- isolate: { type: 'string', default: '' },
- explode: { type: 'string', default: '0' },
- background: { type: 'string', default: 'studio' },
- 'anim-time': { type: 'string' },
- gpu: { type: 'string', default: 'auto' },
- shadow: { type: 'string', default: '1' },
- fill: { type: 'string', default: '0.85' },
- 'timeout-s': { type: 'string', default: '240' },
- },
+function config() {
+ const values = parseCli({
+ glb: {}, out: {}, views: {},
+ mode: { default: 'shaded' }, width: { default: '768' }, height: { default: '768' },
+ isolate: { default: '' }, explode: { default: '0' }, background: { default: 'studio' },
+ 'anim-time': {}, gpu: { default: 'auto' }, shadow: { default: '1' }, fill: { default: '0.85' },
+ 'timeout-s': { default: '240' },
});
if (!values.glb || !values.out || !values.views) throw new Error('--glb, --out and --views are required');
if (!MODES.includes(values.mode)) throw new Error(`--mode must be one of ${MODES.join('|')}`);
@@ -67,44 +58,36 @@ function cli() {
}
function pageHtml(cfg) {
- const config = { ...cfg, glbUrl: '/' + path.basename(cfg.glb) };
- delete config.glb;
- delete config.out;
+ const config_ = { ...cfg, glbUrl: '/' + path.basename(cfg.glb) };
+ delete config_.glb;
+ delete config_.out;
return `<!doctype html><html><head><meta charset="utf-8">${importMapHtml()}
<style>html,body{margin:0;background:#000}canvas{display:block}</style></head>
<body><canvas id="c" width="${cfg.width}" height="${cfg.height}"></canvas>
<script type="module">
-import { renderGlbViews } from '${RUNTIME_MOUNT}lib/browser/render_rig.js';
+import { renderGlbViews } from '${runtimeMount()}lib/browser/render_rig.js';
window.__c3v_result = null;
-renderGlbViews(${JSON.stringify(config)}).then(
+renderGlbViews(${JSON.stringify(config_)}).then(
(r) => { window.__c3v_result = r; },
(e) => { window.__c3v_result = { ok: false, error: String(e && e.message || e), stack: String(e && e.stack || '') }; },
);
</script></body></html>`;
}
-function emit(obj) {
- process.stdout.write(JSON.stringify(obj) + '\n');
-}
-
async function main() {
const t0 = Date.now();
- const cfg = cli();
+ const cfg = config();
if (!fs.existsSync(cfg.glb)) throw new Error(`GLB not found: ${cfg.glb}`);
- fs.mkdirSync(cfg.out, { recursive: true });
+ ensureDir(cfg.out);
const srv = await serveDirs({ root: path.dirname(cfg.glb), routes: { '/__render.html': { body: pageHtml(cfg) } } });
const consoleErrors = [];
let launched = null;
let page = null;
- let gpu = false;
- let launchRenderer = '';
- const timing = {};
+ let record = null;
try {
launched = await launchBrowser({ gpu: cfg.gpu });
- gpu = launched.gpu;
- launchRenderer = launched.renderer;
- timing.launch_ms = Date.now() - t0;
+ const timing = { launch_ms: Date.now() - t0 };
page = await launched.browser.newPage();
await page.setViewport({ width: cfg.width, height: cfg.height, deviceScaleFactor: 1 });
@@ -127,10 +110,10 @@ async function main() {
const { b64: _b64, ...meta } = v;
views.push({ ...meta, path: file, mode: cfg.mode });
}
- const record = {
+ record = {
ok: true,
- renderer: result.renderer || launchRenderer,
- gpu,
+ renderer: result.renderer || launched.renderer,
+ gpu: launched.gpu,
mode: cfg.mode,
bbox: result.bbox,
views,
@@ -138,20 +121,16 @@ async function main() {
console_errors: consoleErrors,
timing_ms: { ...timing, ...result.timing, total_ms: Date.now() - t0 },
};
- fs.writeFileSync(path.join(cfg.out, 'views.json'), JSON.stringify(record, null, 2));
- emit(record);
+ writeJson(path.join(cfg.out, 'views.json'), record);
} finally {
// page first, then release: a shared browser is disconnected, never closed
if (page) await page.close().catch(() => {});
- if (launched && launched.browser) {
- if (typeof launched.release === 'function') await Promise.resolve(launched.release()).catch(() => {});
- else await launched.browser.close().catch(() => {});
- }
+ await releaseBrowser(launched).catch(() => {});
await srv.close();
}
+ return finish(record, 0);
}
main().catch((err) => {
- emit({ ok: false, error: err.message, details: err.details || null, stack: String(err.stack || '').split('\n').slice(0, 8) });
- process.exit(1);
+ finish({ ok: false, error: err.message, details: err.details || null, stack: String(err.stack || '').split('\n').slice(0, 8) }, 1);
});
diff --git a/harness/scripts/setup.sh b/harness/scripts/setup.sh
new file mode 100755
index 00000000..64bee889
--- /dev/null
+++ b/harness/scripts/setup.sh
@@ -0,0 +1,147 @@
+#!/usr/bin/env bash
+# 3dcodeverse harness — idempotent installer / updater.
+#
+# bash harness/scripts/setup.sh [options]
+#
+# Does, in order: version checks (python >= 3.11, node >= 20) -> `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+
+
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+HARNESS="$(cd "$HERE/.." && pwd)"
+RUNTIME_JS="$HARNESS/runtime_js"
+
+PY="${PYTHON:-python3}"
+EXTRAS="all,dev"
+DO_PYTHON=1
+DO_NODE=1
+DO_CHROME=1
+DO_DOCTOR=1
+FORCE_NPM=0
+DOCTOR_ARGS=()
+
+usage() {
+ cat <<'USAGE'
+usage: setup.sh [options]
+
+ --extras LIST pip extras to install (default: all,dev; "" = none)
+ --python BIN python interpreter to install into (default: $PYTHON or python3)
+ --no-python skip the pip install step
+ --no-node skip `npm ci` in runtime_js
+ --no-chrome skip the puppeteer chrome download
+ --no-doctor skip the final `3dcodeverse doctor`
+ --force-npm run `npm ci` even when node_modules looks up to date
+ (WARNING: npm ci deletes node_modules first — do not use
+ while renders/benches are running against this tree)
+ --no-gpu pass --no-gpu to doctor (skips the headless-Chrome probe)
+ -h, --help this message
+USAGE
+}
+
+while [ $# -gt 0 ]; do
+ case "$1" in
+ --extras) EXTRAS="${2-}"; shift 2 ;;
+ --extras=*) EXTRAS="${1#*=}"; shift ;;
+ --python) PY="${2-}"; shift 2 ;;
+ --python=*) PY="${1#*=}"; shift ;;
+ --no-python) DO_PYTHON=0; shift ;;
+ --no-node) DO_NODE=0; shift ;;
+ --no-chrome) DO_CHROME=0; shift ;;
+ --no-doctor) DO_DOCTOR=0; shift ;;
+ --force-npm) FORCE_NPM=1; shift ;;
+ --no-gpu) DOCTOR_ARGS+=(--no-gpu); shift ;;
+ -h|--help) usage; exit 0 ;;
+ *) echo "setup.sh: unknown option: $1" >&2; usage >&2; exit 2 ;;
+ esac
+done
+
+step() { printf '\n\033[1m== %s\033[0m\n' "$*"; }
+info() { printf ' %s\n' "$*"; }
+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)"
+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)"
+info "python $PY_VER ($("$PY" -c 'import sys; print(sys.executable)'))"
+
+command -v git >/dev/null 2>&1 || die "git not found (every round is a git commit in the run workspace)"
+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_OK=0
+ info "node $NODE_VER (need >= $MIN_NODE_MAJOR — three.js / scene / GLB tracks will not run)"
+ else
+ info "node $NODE_VER"
+ fi
+else
+ NODE_OK=0
+ info "node not found (three.js / scene / GLB export tracks will not run)"
+fi
+
+if command -v blender-5.0 >/dev/null 2>&1 || command -v blender >/dev/null 2>&1 || [ -n "${CV3D_BINARIES__BLENDER:-}" ]; then
+ info "blender found"
+else
+ info "blender not found (optional: blender / urdf_blender tracks unavailable — docs/INSTALL.md §6)"
+fi
+command -v ffmpeg >/dev/null 2>&1 && info "ffmpeg found" || info "ffmpeg not found (optional: turntables fall back to animated GIF)"
+
+# ------------------------------------------------------------------ python pkg
+if [ "$DO_PYTHON" -eq 1 ]; then
+ step "pip install -e $HARNESS${EXTRAS:+[$EXTRAS]}"
+ if [ -n "$EXTRAS" ]; then
+ "$PY" -m pip install -e "$HARNESS[$EXTRAS]"
+ else
+ "$PY" -m pip install -e "$HARNESS"
+ fi
+else
+ step "pip install (skipped: --no-python)"
+fi
+
+# -------------------------------------------------------------------- runtime_js
+if [ "$DO_NODE" -eq 1 ] && [ "$NODE_OK" -eq 1 ]; then
+ step "runtime_js node_modules (three + puppeteer)"
+ command -v npm >/dev/null 2>&1 || die "npm not found (it ships with node)"
+ [ -f "$RUNTIME_JS/package-lock.json" ] || die "missing $RUNTIME_JS/package-lock.json"
+ STAMP="$RUNTIME_JS/node_modules/.package-lock.json"
+ if [ "$FORCE_NPM" -eq 1 ] || [ ! -d "$RUNTIME_JS/node_modules" ] || [ ! -f "$STAMP" ] \
+ || [ "$RUNTIME_JS/package-lock.json" -nt "$STAMP" ]; then
+ info "running npm ci (this deletes and re-creates node_modules)"
+ ( cd "$RUNTIME_JS" && npm ci )
+ else
+ info "up to date — node_modules matches package-lock.json (use --force-npm to reinstall)"
+ fi
+
+ if [ "$DO_CHROME" -eq 1 ]; then
+ step "puppeteer chrome (~/.cache/puppeteer)"
+ ( cd "$RUNTIME_JS" && npx --no puppeteer browsers install chrome )
+ fi
+else
+ step "runtime_js (skipped: no usable node, or --no-node)"
+fi
+
+# ----------------------------------------------------------------------- doctor
+if [ "$DO_DOCTOR" -eq 1 ]; then
+ step "3dcodeverse doctor"
+ if command -v 3dcodeverse >/dev/null 2>&1; then
+ 3dcodeverse doctor ${DOCTOR_ARGS[@]+"${DOCTOR_ARGS[@]}"} || true
+ else
+ info "3dcodeverse not on PATH — falling back to python -m codeverse.cli.main"
+ "$PY" -m codeverse.cli.main doctor ${DOCTOR_ARGS[@]+"${DOCTOR_ARGS[@]}"} || true
+ fi
+fi
+
+printf '\n\033[1mdone.\033[0m Next: docs/INSTALL.md §10 (5-minute smoke).\n'
diff --git a/harness/tests/agents/test_api_agent.py b/harness/tests/agents/test_api_agent.py
index c243c1f4..250ab710 100644
--- a/harness/tests/agents/test_api_agent.py
+++ b/harness/tests/agents/test_api_agent.py
@@ -99,7 +99,7 @@ def test_loop_writes_file_and_finishes(tmp_ws):
assert last_req.messages[-1].role == "tool" and isinstance(last_req.messages[-1].parts[0], ToolResultPart)
assert last_req.tools and {t.name for t in last_req.tools} >= {"read_file", "write_file", "edit_file", "list_files", "run_shell"}
# transcript
- kinds = [json.loads(l)["kind"] for l in Path(res.transcript_path).read_text().splitlines()]
+ kinds = [json.loads(ln)["kind"] for ln in Path(res.transcript_path).read_text().splitlines()]
assert kinds[0] == "system" and kinds.count("assistant") == 3 and kinds.count("tool_result") == 2
rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
assert rec["nudged"] is False and "write_file" in rec["tools"]
@@ -192,7 +192,7 @@ def test_compaction_triggers_in_loop(tmp_ws, monkeypatch):
fake = FakeChatModel([resp("", call("read_file", path="src/big.txt")) for _ in range(8)] + [resp("done")])
res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, max_turns=12))
assert res.ok
- kinds = [json.loads(l)["kind"] for l in Path(res.transcript_path).read_text().splitlines()]
+ kinds = [json.loads(ln)["kind"] for ln in Path(res.transcript_path).read_text().splitlines()]
assert "compact" in kinds
assert any(m.text.startswith(FACTS_TAG) for m in fake.requests[-1].messages if m.role == "user")
diff --git a/harness/tests/agents/test_gemini_cli.py b/harness/tests/agents/test_gemini_cli.py
index 7a48ab99..c029a3df 100644
--- a/harness/tests/agents/test_gemini_cli.py
+++ b/harness/tests/agents/test_gemini_cli.py
@@ -88,8 +88,8 @@ def test_transient_failure_retries_once_with_other_key(tmp_ws: Workspace, agent:
assert (tmp_ws.root / "attempts.txt").read_text() == "2"
rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
assert rec["attempts"] == 2 and (Path(res.transcript_path).parent / "stdout.2.json").exists()
- lines = [json.loads(l) for l in Path(res.transcript_path).read_text().splitlines()]
- keys = [l["key_tail"] for l in lines if l["kind"] == "invoke"]
+ lines = [json.loads(ln) for ln in Path(res.transcript_path).read_text().splitlines()]
+ keys = [ln["key_tail"] for ln in lines if ln["kind"] == "invoke"]
assert keys == ["k1", "k2"]
diff --git a/harness/tests/agents/test_watchdog.py b/harness/tests/agents/test_watchdog.py
index c2068735..fd2074f8 100644
--- a/harness/tests/agents/test_watchdog.py
+++ b/harness/tests/agents/test_watchdog.py
@@ -17,7 +17,7 @@ def test_normal_run_streams_lines(tmp_path: Path):
res = run_with_watchdog(
[PY, "-c", "import sys; print('a'); print('b', file=sys.stderr); print('c')"],
cwd=tmp_path, env=os.environ, soft_timeout_s=10, idle_grace_s=5, hard_timeout_s=20,
- on_line=lambda s, l: seen.append((s, l)),
+ on_line=lambda stream, text: seen.append((stream, text)),
)
assert res.rc == 0 and not res.timed_out
assert res.stdout.splitlines() == ["a", "c"]
diff --git a/harness/tests/bench_prompts/test_v2_batteries.py b/harness/tests/bench_prompts/test_v2_batteries.py
index e70a02e9..a6d888e5 100644
--- a/harness/tests/bench_prompts/test_v2_batteries.py
+++ b/harness/tests/bench_prompts/test_v2_batteries.py
@@ -139,9 +139,8 @@ def test_scene_prompts_state_composition_contracts():
def test_graphics_v2_opengl_prompts_carry_language_override():
"""The ogl_* rows must run under opengl_python; the loader forwards the
per-prompt override into the Spec (BenchPrompt.language or battery.language)."""
- from codeverse.contracts.common import Backends, Language
-
from bench.run_bench import build_spec
+ from codeverse.contracts.common import Backends, Language
b = _load("graphics_v2")
assert b.language == Language.GLSL_SHADER
diff --git a/harness/tests/compare_bench/test_compare_matrix.py b/harness/tests/compare_bench/test_compare_matrix.py
index 18191bb0..5d5640a6 100644
--- a/harness/tests/compare_bench/test_compare_matrix.py
+++ b/harness/tests/compare_bench/test_compare_matrix.py
@@ -12,7 +12,13 @@ REPO = Path(__file__).resolve().parents[2]
if str(REPO) not in sys.path:
sys.path.insert(0, str(REPO))
-from bench._compare_report import CellResult, PairRow, arm_stats, load_jsonl, pair_stats # noqa: E402
+from bench._compare_report import ( # noqa: E402
+ CellResult,
+ PairRow,
+ arm_stats,
+ load_jsonl,
+ pair_stats,
+)
from bench._fixed_eval import acceptance_from_spec # noqa: E402
from bench.compare_backends import ( # noqa: E402
CompareDeps,
diff --git a/harness/tests/install/__init__.py b/harness/tests/install/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/install/test_docs.py b/harness/tests/install/test_docs.py
new file mode 100644
index 00000000..d1e4f50a
--- /dev/null
+++ b/harness/tests/install/test_docs.py
@@ -0,0 +1,196 @@
+"""Offline guards for the install documentation.
+
+Covers only the files the install guide owns (``docs/INSTALL.md``, the three
+READMEs, ``scripts/setup.sh``) so a doc change elsewhere cannot fail them:
+
+* ``docs/INSTALL.md`` exists and is non-empty;
+* every command in a fenced *shell* block starts with a binary we expect a
+ reader to have (catches copy-paste typos and invented tools);
+* every internal markdown link, backticked ``*.md`` path and same-page anchor
+ resolves;
+* ``scripts/setup.sh`` is executable, parses (``bash -n``) and answers ``--help``;
+* every extra declared in ``pyproject.toml`` is documented in INSTALL.md.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import subprocess
+import sys
+import tomllib
+from pathlib import Path
+
+import pytest
+
+HARNESS = Path(__file__).resolve().parents[2]
+REPO = HARNESS.parent
+INSTALL = HARNESS / "docs" / "INSTALL.md"
+SETUP = HARNESS / "scripts" / "setup.sh"
+
+#: docs owned by the install guide (repo README is optional: the harness can be checked out alone)
+OWNED_DOCS = [INSTALL, HARNESS / "README.md", HARNESS / "runtime_js" / "README.md", REPO / "README.md"]
+
+SHELL_LANGS = {"bash", "sh", "shell", "console", "zsh"}
+
+#: first token of a documented command must be one of these (or have one as its basename)
+ALLOWED_BINARIES = {
+ # shell builtins / coreutils
+ "bash", "sh", "cd", "ls", "cat", "echo", "printf", "mkdir", "rm", "cp", "mv", "chmod", "ln",
+ "export", "source", "exec", "test", "time", "which", "du", "df", "head", "tail", "grep",
+ "sed", "awk", "xargs", "tee", "ldd", "tar", "curl", "wget", "unzip", "open",
+ # toolchain
+ "git", "python", "python3", "pip", "pip3", "pytest", "conda", "uv", "node", "npm", "npx", "nvm",
+ "sudo", "apt-get", "apt", "brew", "dnf", "pacman",
+ # this project
+ "3dcv", "3dcodeverse", "setup.sh", "blender", "ffmpeg", "gemini", "claude", "codex", "agy",
+}
+
+_ENV_ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
+_MD_LINK = re.compile(r"\[[^\]]*\]\(([^)\s]+)")
+_BACKTICK_MD = re.compile(r"`([\w./~-]+\.md)`")
+
+
+# --------------------------------------------------------------------------- helpers
+def fenced_blocks(text: str) -> list[tuple[str, str]]:
+ """[(language, body)] for every ``` fenced block (language ``""`` when unlabelled)."""
+ blocks: list[tuple[str, str]] = []
+ lang: str | None = None
+ body: list[str] = []
+ for line in text.splitlines():
+ if line.lstrip().startswith("```"):
+ if lang is None:
+ lang = line.lstrip()[3:].strip().lower()
+ body = []
+ else:
+ blocks.append((lang, "\n".join(body)))
+ lang = None
+ body = []
+ elif lang is not None:
+ body.append(line)
+ return blocks
+
+
+def shell_commands(body: str) -> list[str]:
+ """First token of every command in a shell block (continuations joined, comments and
+ leading ``VAR=value`` assignments stripped, ``&&``/``||``/``;``/``|`` split)."""
+ out: list[str] = []
+ text = re.sub(r"\\\n\s*", " ", body) # join line continuations
+ for raw in text.splitlines():
+ line = raw.strip()
+ if not line or line.startswith("#") or line.startswith("$ #"):
+ continue
+ line = line.removeprefix("$ ").strip()
+ line = re.sub(r"\s+#.*$", "", line) # trailing comment
+ for part in re.split(r"&&|\|\||[;|]", line):
+ part = part.strip().strip("()").strip()
+ if not part or part in {"then", "else", "fi", "do", "done"}:
+ continue
+ tokens = part.split()
+ while tokens and _ENV_ASSIGN.match(tokens[0]):
+ tokens.pop(0)
+ if tokens:
+ out.append(tokens[0])
+ return out
+
+
+def slugify(heading: str) -> str:
+ """GitHub-style anchor slug for a markdown heading."""
+ text = heading.strip().lstrip("#").strip().lower()
+ text = re.sub(r"[^\w\s-]", "", text.replace("`", ""))
+ return re.sub(r"\s", "-", text)
+
+
+def existing_docs() -> list[Path]:
+ return [p for p in OWNED_DOCS if p.is_file()]
+
+
+# --------------------------------------------------------------------------- tests
+def test_install_guide_exists() -> None:
+ assert INSTALL.is_file(), f"{INSTALL} is missing"
+ text = INSTALL.read_text()
+ assert len(text) > 2000, "docs/INSTALL.md looks truncated"
+ for needle in ("runtime_js", "npm ci", "3dcodeverse doctor", "GEMINI_API_KEYS", "scripts/setup.sh"):
+ assert needle in text, f"docs/INSTALL.md never mentions {needle!r}"
+
+
[email protected]("doc", existing_docs(), ids=lambda p: str(p.relative_to(REPO)))
+def test_shell_commands_use_known_binaries(doc: Path) -> None:
+ bad: list[str] = []
+ for lang, body in fenced_blocks(doc.read_text()):
+ if lang not in SHELL_LANGS:
+ continue
+ for cmd in shell_commands(body):
+ name = cmd.split("/")[-1]
+ if cmd not in ALLOWED_BINARIES and name not in ALLOWED_BINARIES:
+ bad.append(cmd)
+ assert not bad, f"{doc}: unknown command(s) in shell blocks: {sorted(set(bad))}"
+
+
[email protected]("doc", existing_docs(), ids=lambda p: str(p.relative_to(REPO)))
+def test_internal_links_resolve(doc: Path) -> None:
+ text = doc.read_text()
+ headings = {slugify(ln) for ln in text.splitlines() if ln.startswith("#")}
+ missing: list[str] = []
+ for target in _MD_LINK.findall(text):
+ if target.startswith(("http://", "https://", "mailto:", "<")):
+ continue
+ if target.startswith("#"):
+ if target[1:] not in headings:
+ missing.append(f"anchor {target}")
+ continue
+ path, _, anchor = target.partition("#")
+ if path and not (doc.parent / path).exists():
+ missing.append(f"link {target}")
+ assert not missing, f"{doc}: unresolved {missing}"
+
+
[email protected]("doc", existing_docs(), ids=lambda p: str(p.relative_to(REPO)))
+def test_backticked_markdown_paths_resolve(doc: Path) -> None:
+ """`docs/INSTALL.md`-style references must point at a file that exists."""
+ missing = []
+ for ref in sorted(set(_BACKTICK_MD.findall(doc.read_text()))):
+ if ref.startswith("~"):
+ continue
+ if not any((base / ref).exists() for base in (doc.parent, HARNESS, REPO)):
+ missing.append(ref)
+ assert not missing, f"{doc}: backticked markdown path(s) do not exist: {missing}"
+
+
+def test_setup_script_is_executable_and_parses() -> None:
+ assert SETUP.is_file(), f"{SETUP} is missing"
+ assert os.access(SETUP, os.X_OK), f"{SETUP} is not executable (chmod +x)"
+ assert SETUP.read_text().startswith("#!"), "scripts/setup.sh has no shebang"
+ proc = subprocess.run(["bash", "-n", str(SETUP)], capture_output=True, text=True, timeout=60)
+ assert proc.returncode == 0, f"bash -n failed:\n{proc.stderr}"
+
+
+def test_setup_script_help_works() -> None:
+ proc = subprocess.run(["bash", str(SETUP), "--help"], capture_output=True, text=True, timeout=60)
+ assert proc.returncode == 0, f"setup.sh --help exited {proc.returncode}:\n{proc.stderr}"
+ assert "--extras" in proc.stdout
+
+
+def test_every_pyproject_extra_is_documented() -> None:
+ with (HARNESS / "pyproject.toml").open("rb") as fh:
+ extras = tomllib.load(fh)["project"]["optional-dependencies"]
+ text = INSTALL.read_text()
+ undocumented = [name for name in extras if f"`{name}`" not in text]
+ assert not undocumented, f"extras missing from docs/INSTALL.md: {undocumented}"
+
+
+def test_doctor_rows_have_troubleshooting_entries() -> None:
+ """Every check `3dcv doctor` can print must appear in the INSTALL troubleshooting table."""
+ from codeverse.cli import doctor as doctor_mod
+
+ text = INSTALL.read_text()
+ names = {"python", "python deps", "blender", "node", "three", "puppeteer", "chrome webgl",
+ "gemini keys", "anthropic key", "openai key", "gemini-cli", "claude", "codex", "agy",
+ "git", "ffmpeg", "mcp"}
+ assert hasattr(doctor_mod, "run_doctor")
+ missing = [n for n in sorted(names) if f"`{n}`" not in text]
+ assert not missing, f"doctor rows undocumented in docs/INSTALL.md: {missing}"
+
+
+if __name__ == "__main__": # pragma: no cover
+ sys.exit(pytest.main([__file__, "-q"]))
diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.py
index e62b4d2e..cad73d23 100644
--- a/harness/tests/models/test_retry.py
+++ b/harness/tests/models/test_retry.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import pytest
import pytest
from codeverse.models.retry import backoff_delay, with_retries
diff --git a/harness/tests/texturing/conftest.py b/harness/tests/texturing/conftest.py
index 4b5f4885..d3d911bb 100644
--- a/harness/tests/texturing/conftest.py
+++ b/harness/tests/texturing/conftest.py
@@ -19,7 +19,6 @@ from codeverse.contracts.spec import Spec
from codeverse.texturing.generate import FakeImageModel
-
def _box(ext: tuple[float, float, float], center: tuple[float, float, float]) -> trimesh.Trimesh:
m = trimesh.creation.box(extents=ext)
m.apply_translation(center)