Skip to content

Official Codebase of 3DCodeVerse

Python

harness: 3dcodeverse v0.1 — raw-language 3D codegen harness (tracks: static/articulated/scene; backends: gemini/anthropic/openai APIs + gemini-cli/claude-code/codex/agy/api-agent; spatial tools + MCP; VLM judges; flywheel)

gaoypengbe40ae8d6c49
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..07132c3f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,11 @@
+__pycache__/
+*.egg-info/
+.pytest_cache/
+.ruff_cache/
+node_modules/
+runs/
+harness/runs/
+bench/out/
+*.pyc
+harness/logs/
+*.log
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 00000000..4939a9c1
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,8 @@
+# 3dcodeverse (repo root)
+
+The harness lives in **`harness/`** — read `harness/CLAUDE.md` +
+`harness/docs/ARCHITECTURE.md` before touching it. Install with
+`pip install -e harness`. Run tests with
+`cd harness && python -m pytest tests -q -m "not live"`.
+
+Other top-level folders are separate components (datasets, web, papers).
diff --git a/README.md b/README.md
index 4b602eab..588b310b 100644
--- a/README.md
+++ b/README.md
@@ -1 +1,12 @@
-# 3dcodeverse
\ No newline at end of file
+# 3dcodeverse
+
+The 3dcodeverse project. Top-level layout:
+
+- **`harness/`** — the 3dcodeverse harness (python dist `3dcodeverse`, import
+ `codeverse`, CLI `3dcodeverse` / `c3v`): the backend that turns prompts into
+ raw 3D code (Blender bpy / CadQuery / Three.js / URDF / GLSL) through a
+ plan → generate → gate → render → judge → refine loop, and emits
+ data-flywheel records. See `harness/README.md`.
+
+Other large components (datasets, papers, web) live in their own top-level
+folders.
diff --git a/harness/CLAUDE.md b/harness/CLAUDE.md
new file mode 100644
index 00000000..2a9d79e8
--- /dev/null
+++ b/harness/CLAUDE.md
@@ -0,0 +1,51 @@
+# 3dcodeverse — standing context
+
+Backend harness (python package `codeverse`, CLI `c3v`) for LLM-written **raw** 3D
+code: Blender bpy · CadQuery · Three.js · URDF · GLSL, across three tracks
+(`static_object`, `articulated_object`, `scene`), with pluggable backends
+(Gemini/Anthropic/OpenAI APIs + gemini-cli / claude-code / codex / antigravity /
+in-process api-agent) and a data-flywheel record per run.
+
+Read `docs/ARCHITECTURE.md` (design + package map + authoring contracts) and
+`docs/INTERFACES.md` (binding cross-package signatures) before changing anything.
+
+## Laws (do not break)
+1. Generated code is raw language — never an SDK/helper import; the harness owns
+ wrappers/exporters (`codeverse/languages/*/wrappers`, `runtime_js/`).
+2. `codeverse/contracts/` is data-only and shared; `conventions.py` is the only
+ place that states frames/units/naming. Import, never restate.
+3. Deterministic gates/measurements run by the harness; VLM only for perception.
+ Score is computed in code from rubric weights; caps/floors are explicit.
+4. Typed everything; no regex-on-id control flow; no god files (≤ ~400 lines).
+5. Cheap first: lint → build → gates → 4-view sheet → VLM. Budgets are hard.
+6. Every round = a git commit of `src/`; every call = a `Usage`; every run = `record.json`.
+
+## Environment (this machine)
+- Gemini keys: `~/.config/astra3d/gemini_keys.env` (22 keys) → `get_settings().gemini_api_keys`.
+- 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
+ Chrome WebGL uses the GPU on WSL2 with `--use-angle=gl-egl` + Mesa d3d12 env (see
+ `runtime_js/gpu_launch.cjs`); SwiftShader fallback.
+- CLIs: `gemini` 0.53 (api-key auth + `dynamicModelConfiguration` via system settings file,
+ else it silently substitutes models), `codex` 0.147, `claude` 2.1, `agy` 1.1.5 — the last
+ three run on local subscriptions: test lightly.
+- Main test model: `gemini-3.7-flash`. Judge default: `gemini-3.7-flash` (n_samples=2) or
+ `gemini-3.1-pro-preview` for calibration runs.
+
+## Commands
+```
+pip install -e /home/yipeng/3dcodeverse/harness # once
+c3v doctor
+c3v make "a mid-century wooden dining chair" --track static_object --language blender
+c3v make "..." --track articulated_object --language urdf_blender
+c3v make "..." --track scene --language scene_threejs --generator gemini-cli:gemini-3.7-flash
+c3v resume <slug> · c3v status <slug> · c3v render <slug> · c3v judge <slug>
+c3v tools list · c3v mcp --workspace runs/<slug>
+c3v flywheel export runs/ dataset/ · c3v bench run bench/prompts/static_objects_v1.yaml
+python -m pytest tests -q -m "not live"
+```
+
+## Reference material (ideas only — never copy code)
+`/home/yipeng/3dcodeverse_refs/_reports/*.md` — deep reads of astra3d-brilliana,
+scene_multifile_graphics, opentopos, articraft, img2threejs, SpatialClaw, the owner's
+3dcodeverse_data scripts, and a skills/pitfalls research report.
diff --git a/harness/README.md b/harness/README.md
new file mode 100644
index 00000000..d2099f75
--- /dev/null
+++ b/harness/README.md
@@ -0,0 +1,27 @@
+# 3dcodeverse
+
+A backend harness in which LLMs write **raw, executable 3D code** — Blender `bpy`,
+CadQuery, Three.js, URDF, GLSL — and a harness plans, builds, measures, renders,
+judges, refines and records every run as data-flywheel material.
+
+* **Tracks:** `static_object` · `articulated_object` · `scene`
+* **Languages:** `blender` · `cadquery` · `threejs` · `urdf_blender` · `scene_threejs`
+* **Backends:** Gemini / Anthropic / OpenAI APIs; gemini-cli, Claude Code, Codex,
+ Antigravity CLI; and an in-process `api-agent` tool loop on any API model.
+* **Spatial tools** (also an MCP server for agentic CLIs): build, measure,
+ render_views/sheet, isolate, cross_section, check_connectivity, check_contract,
+ compare_silhouette, joint_sweep, shader_probe, scene_probe, read_cookbook.
+* **Judging:** rubric VLM judge with code-computed scores, floors and caps from
+ deterministic gates; pairwise and reference judges.
+* **Flywheel:** git-versioned `src/` per round, `record.json`, sample export,
+ preference/repair pairs, captions.
+
+```bash
+pip install -e .
+c3v doctor
+c3v make "a mid-century wooden dining chair" --track static_object --language blender
+c3v make "a kitchen cabinet with one door and a drawer" --track articulated_object --language urdf_blender
+c3v make "a small japanese garden at dusk with a koi pond" --track scene --language scene_threejs
+```
+
+Design: `docs/ARCHITECTURE.md` · Interfaces: `docs/INTERFACES.md` · Working rules: `CLAUDE.md`.
diff --git a/harness/bench/__init__.py b/harness/bench/__init__.py
new file mode 100644
index 00000000..33ff24fb
--- /dev/null
+++ b/harness/bench/__init__.py
@@ -0,0 +1,5 @@
+"""Prompt batteries + bench runner/report (``c3v bench run|report``).
+
+Methodology: paired runs (same battery, same fixed judge model) across
+generators; prompts stratified by tier (easy/medium/hard) and category.
+"""
diff --git a/harness/bench/prompts/articulated_v1.yaml b/harness/bench/prompts/articulated_v1.yaml
new file mode 100644
index 00000000..39a8c6cc
--- /dev/null
+++ b/harness/bench/prompts/articulated_v1.yaml
@@ -0,0 +1,67 @@
+name: articulated_v1
+track: articulated_object
+language: urdf_blender
+description: >
+ 12 articulated-object prompts (URDF + bpy link meshes), 4 per tier. must_have
+ items name the joints the judge/FK sweep must verify.
+prompts:
+ - id: art_easy_cabinet_door
+ tier: easy
+ category: furniture
+ prompt: a kitchen wall cabinet with a single hinged door that swings open 110 degrees
+ must_have: [cabinet box, one door on a vertical hinge axis, door swings outward up to 110 degrees, handle on the free edge]
+ - id: art_easy_drawer_unit
+ tier: easy
+ category: furniture
+ prompt: a bedside drawer unit with two drawers that slide out
+ must_have: [carcass, two drawers on prismatic slides, drawers pull out at least 30 cm, drawer pulls]
+ - id: art_easy_laptop
+ tier: easy
+ category: electronics
+ prompt: a laptop whose screen lid opens from closed to 135 degrees on a hinge at the back edge
+ must_have: [base with keyboard, lid with screen, revolute hinge along the back edge, range 0 to 135 degrees]
+ - id: art_easy_scissors
+ tier: easy
+ category: tools
+ prompt: a pair of scissors with two blades pivoting about a central screw
+ must_have: [two blade-and-handle halves, one revolute pivot at the screw, blades cross when closed, opens about 60 degrees]
+ - id: art_med_folding_chair
+ tier: medium
+ category: furniture
+ prompt: a folding chair whose seat lifts up and whose front legs pivot toward the back legs to fold flat
+ must_have: [seat hinged to the frame, front leg frame pivoting about a cross bar, back rest, folds to a flat state]
+ - id: art_med_desk_lamp
+ tier: medium
+ category: lighting
+ prompt: a desk lamp with a round base, a lower arm that pivots at the base and an upper arm that pivots at the elbow, ending in a shade
+ must_have: [weighted base, lower arm revolute at base, upper arm revolute at elbow, shade at the tip, both joints have limits]
+ - id: art_med_toolbox
+ tier: medium
+ category: tools
+ prompt: a metal toolbox with a lid hinged along the back edge and a fold-down carry handle on top of the lid
+ must_have: [box body, lid hinged at the rear edge, handle hinged on the lid, lid opens 100 degrees, latch on the front]
+ - id: art_med_wheelbarrow
+ tier: medium
+ category: garden
+ prompt: a wheelbarrow with a spinning front wheel and a tray that tips forward on its axle to dump
+ must_have: [tray, two handles, two rear legs, front wheel on a continuous axle joint, tipping joint for the tray]
+ - id: art_hard_door_handle
+ tier: hard
+ category: architecture
+ prompt: a house door in its frame with hinges, a lever handle that rotates down 40 degrees, and a latch bolt that retracts when the handle turns
+ must_have: [door frame, door on vertical hinges, lever handle revolute, latch bolt prismatic, door swings 90 degrees]
+ - id: art_hard_treasure_chest
+ tier: hard
+ category: props
+ prompt: a wooden treasure chest with a domed lid on rear hinges, a hasp that flips over a staple, and a small inner tray that slides sideways
+ must_have: [chest body, domed lid revolute at rear, hasp revolute on the lid, sliding inner tray, iron bands]
+ - id: art_hard_swivel_chair
+ tier: hard
+ category: furniture
+ prompt: an office swivel chair with a five-star base on casters, a gas lift that raises the seat, a seat that swivels, and a backrest that tilts back
+ must_have: [five-arm base with five caster wheels, prismatic gas lift, continuous swivel joint, backrest tilt joint with limits, armrests]
+ - id: art_hard_bicycle_wheel_stand
+ tier: hard
+ category: vehicles
+ prompt: a bicycle front wheel and fork on a repair stand, with the wheel spinning on its axle, the fork turning about the steering tube, and a brake caliper whose arms pinch the rim
+ must_have: [spoked wheel on a continuous axle joint, fork on a steering revolute joint, two brake arms pivoting toward the rim, stand base]
diff --git a/harness/bench/prompts/scenes_v1.yaml b/harness/bench/prompts/scenes_v1.yaml
new file mode 100644
index 00000000..79aa70b8
--- /dev/null
+++ b/harness/bench/prompts/scenes_v1.yaml
@@ -0,0 +1,68 @@
+name: scenes_v1
+track: scene
+language: scene_threejs
+description: >
+ 12 scene prompts (multi-file Three.js + GLSL), 4 per tier. Each must_have
+ names the environment, a signature effect and an animated element so the
+ scene judge and probes have concrete targets.
+prompts:
+ - id: scn_easy_japanese_garden
+ tier: easy
+ category: nature
+ prompt: a small japanese garden with a koi pond, a wooden bridge, stone lanterns, raked gravel and a maple tree, soft afternoon light
+ must_have: [pond with reflective water, arched bridge, at least two stone lanterns, maple tree with red foliage, raked gravel pattern, gentle water ripple animation]
+ - id: scn_easy_desert_canyon
+ tier: easy
+ category: nature
+ prompt: a desert canyon with layered red rock walls, a dry river bed, scattered boulders and distant haze fog
+ must_have: [tall layered canyon walls on both sides, sandy floor, boulders, distance fog, warm sun with long shadows, drifting dust or heat shimmer]
+ - id: scn_easy_rooftop_garden
+ tier: easy
+ category: urban
+ prompt: a rooftop garden with planters, a pergola, string lights and a city skyline view at golden hour
+ must_have: [rooftop platform with parapet, planters with plants, pergola, string lights that glow, skyline of distant buildings, swaying plant animation]
+ - id: scn_easy_greenhouse
+ tier: easy
+ category: interior
+ prompt: a glass greenhouse interior with rows of potted plants, a central water feature and sunlight through the panes
+ must_have: [glass walls and roof with frames, rows of plant benches, water feature with animated water, visible light shafts or bright panes, hanging baskets]
+ - id: scn_med_coastal_village
+ tier: medium
+ category: landscape
+ prompt: a coastal fishing village at dusk with a harbour, moored boats, cottages with lit windows, a lighthouse and gentle animated waves
+ must_have: [harbour wall and water, at least three boats bobbing, cottages with emissive windows, lighthouse with rotating beam, dusk sky gradient, wave animation]
+ - id: scn_med_cozy_cabin
+ tier: medium
+ category: interior
+ prompt: a cozy log cabin interior at night with a flickering fireplace glow, an armchair, a rug, bookshelves and snow visible through the window
+ must_have: [log walls, fireplace with animated flicker light, armchair and rug, bookshelf with books, window with snowy exterior, warm colour grading]
+ - id: scn_med_snowy_hut
+ tier: medium
+ category: landscape
+ prompt: a snowy mountain hut at night with falling snow particles, a glowing window, pine trees and a distant mountain ridge
+ must_have: [hut with snow-covered roof, emissive window, falling snow particle system, pine trees, mountain ridge silhouette, moonlit lighting]
+ - id: scn_med_medieval_market
+ tier: medium
+ category: urban
+ prompt: a medieval market square with market stalls under striped awnings, a central well, timber-framed houses and fluttering banners
+ must_have: [at least four stalls with awnings, stone well, timber-framed houses around the square, banners or flags waving, cobblestone ground, daylight with shadows]
+ - id: scn_hard_cyberpunk_alley
+ tier: hard
+ category: urban
+ prompt: a rain-soaked cyberpunk alley at night with neon signs, wet reflective ground shader, steam vents, holographic billboards and falling rain
+ must_have: [narrow alley between tall buildings, several neon signs with emissive glow, wet ground with reflections via a custom shader, rain particles, animated steam, flickering hologram]
+ - id: scn_hard_floating_islands
+ tier: hard
+ category: fantasy
+ prompt: floating sky islands connected by rope bridges, with waterfalls pouring off the edges into clouds, a windmill on the largest island and drifting cloud layers
+ must_have: [at least three floating islands at different heights, rope bridges, animated waterfalls, cloud layer below, windmill with rotating sails, islands gently bobbing]
+ - id: scn_hard_underwater_reef
+ tier: hard
+ category: nature
+ prompt: an underwater coral reef with animated caustic light patterns, schools of fish, swaying kelp, rising bubbles and blue volumetric fog
+ must_have: [reef with varied coral shapes, caustics shader on the sea floor, fish school animation, swaying kelp, bubble particles, blue depth fog]
+ - id: scn_hard_autumn_forest
+ tier: hard
+ category: nature
+ prompt: an autumn forest path with god rays through the canopy, falling leaves, a stream with a small wooden footbridge and morning mist
+ must_have: [many trees with autumn foliage, visible light shafts, falling leaf particles, stream with moving water, footbridge, ground mist]
diff --git a/harness/bench/prompts/static_objects_v1.yaml b/harness/bench/prompts/static_objects_v1.yaml
new file mode 100644
index 00000000..cb9705a7
--- /dev/null
+++ b/harness/bench/prompts/static_objects_v1.yaml
@@ -0,0 +1,137 @@
+name: static_objects_v1
+track: static_object
+language: blender
+description: >
+ 24 static-object prompts, 8 categories × 3 tiers (easy / medium / hard).
+ Every prompt carries must_have items the planner turns into acceptance checks.
+ Same battery runs under any generator; keep the judge model fixed across arms.
+prompts:
+ # ---------------------------------------------------------------- furniture
+ - id: furn_easy_stool
+ tier: easy
+ category: furniture
+ prompt: a simple three-legged round wooden stool, 45 cm tall
+ must_have: [round seat, three splayed legs of equal length, legs touch the ground]
+ dimensions_m: {height: 0.45}
+ - id: furn_med_dining_chair
+ tier: medium
+ category: furniture
+ prompt: a mid-century wooden dining chair with a slatted backrest and tapered legs
+ must_have: [four tapered legs, seat slab, backrest with at least three vertical slats, back legs continue into back posts]
+ - id: furn_hard_rolltop_desk
+ tier: hard
+ category: furniture
+ prompt: a writing desk with two pedestals of three drawers each, a central knee-hole, a leather inlay top and brass drawer pulls
+ must_have: [two drawer pedestals, three drawers per pedestal with visible fronts, knee-hole gap, brass pull handles, desk top overhangs]
+ # ---------------------------------------------------------------- vehicles
+ - id: veh_easy_toy_car
+ tier: easy
+ category: vehicles
+ prompt: a chunky toy car with a rounded body and four thick wheels
+ must_have: [one-piece rounded body, four wheels touching the ground, wheels protrude sideways]
+ - id: veh_med_pickup
+ tier: medium
+ category: vehicles
+ prompt: a pickup truck with a two-door cab, open cargo bed, wheel arches and side mirrors
+ must_have: [cab with windows, open rear bed, four wheels with hubs, front grille and headlights, side mirrors]
+ - id: veh_hard_tractor
+ tier: hard
+ category: vehicles
+ prompt: a farm tractor with large rear tyres with treads, small front wheels, an exposed engine block, exhaust stack, driver seat, steering wheel and a roll bar
+ must_have: [rear wheels much larger than front wheels, tyre tread detail, exhaust stack, seat and steering wheel, roll bar, engine hood]
+ # ---------------------------------------------------------------- tools
+ - id: tool_easy_hammer
+ tier: easy
+ category: tools
+ prompt: a claw hammer with a wooden handle and a steel head
+ must_have: [cylindrical handle, steel head with a flat face, forked claw on the back]
+ - id: tool_med_hand_drill
+ tier: medium
+ category: tools
+ prompt: a cordless power drill with a pistol grip, trigger, battery pack in the base of the grip and a keyless chuck holding a drill bit
+ must_have: [pistol grip body, trigger, battery block under grip, chuck with a bit, side vents]
+ - id: tool_hard_bench_vise
+ tier: hard
+ category: tools
+ prompt: a cast-iron bench vise with fixed and sliding jaws, a lead screw with a tommy bar handle, guide rails, a small anvil face and mounting base with bolt holes
+ must_have: [two jaws with a visible gap, sliding jaw on guide rails, lead screw with sliding T handle, anvil flat, base with bolt holes]
+ # ---------------------------------------------------------------- appliances
+ - id: appl_easy_kettle
+ tier: easy
+ category: appliances
+ prompt: an electric kettle with a spout, a lid and a side handle on a round base
+ must_have: [pot body, pouring spout, handle opposite the spout, lid on top, round base]
+ - id: appl_med_toaster
+ tier: medium
+ category: appliances
+ prompt: a two-slot retro toaster with rounded chrome body, a lever on the side, a browning dial and a crumb tray
+ must_have: [two bread slots on top, side lever, dial knob, rounded body, small feet]
+ - id: appl_hard_espresso
+ tier: hard
+ category: appliances
+ prompt: an espresso machine with a group head and portafilter, a steam wand, a drip tray with grate, a water tank at the back, and a top-mounted cup warmer with a pressure gauge on the front panel
+ must_have: [portafilter with handle under a group head, steam wand on the side, drip tray with grate, water tank, pressure gauge, cup warmer rail]
+ # ---------------------------------------------------------------- plants
+ - id: plant_easy_cactus
+ tier: easy
+ category: plants
+ prompt: a potted barrel cactus in a terracotta pot with soil
+ must_have: [ribbed round cactus body, terracotta pot with rim, soil surface]
+ - id: plant_med_palm
+ tier: medium
+ category: plants
+ prompt: a small potted palm with a textured trunk and eight arching fronds made of many leaflets
+ must_have: [textured trunk, at least eight fronds, fronds arch downward, leaflets along each frond, pot]
+ - id: plant_hard_bonsai
+ tier: hard
+ category: plants
+ prompt: a bonsai tree with a twisted thick trunk, three layered foliage pads, exposed roots over a rock and a shallow oval ceramic tray with moss
+ must_have: [twisted trunk with taper, at least three distinct foliage pads, exposed roots gripping a rock, shallow oval tray, moss surface]
+ # ---------------------------------------------------------------- buildings
+ - id: bld_easy_shed
+ tier: easy
+ category: buildings
+ prompt: a small garden shed with a pitched roof, one door and one window
+ must_have: [box walls, pitched roof overhang, door on front, window]
+ - id: bld_med_lighthouse
+ tier: medium
+ category: buildings
+ prompt: a tapered lighthouse with red and white bands, a gallery with railing, a glass lantern room and a domed cap, on a rocky base
+ must_have: [tapered tower, alternating bands, gallery walkway with railing, glass lantern room, dome, rock base]
+ - id: bld_hard_windmill
+ tier: hard
+ category: buildings
+ prompt: a Dutch windmill with an octagonal tapered body, thatched cap, four lattice sails, a balcony stage with railing, a door, and two shuttered windows
+ must_have: [octagonal tapered body, cap, four lattice sails in a cross, balcony with railing, door, shuttered windows]
+ # ---------------------------------------------------------------- toys
+ - id: toy_easy_blocks
+ tier: easy
+ category: toys
+ prompt: a stack of five alphabet blocks of decreasing size in a slightly twisted tower
+ must_have: [five cubes, decreasing size upward, each slightly rotated, all stacked touching]
+ - id: toy_med_rocking_horse
+ tier: medium
+ category: toys
+ prompt: a wooden rocking horse with curved rockers, a saddle, handles and a mane
+ must_have: [horse body with head and four legs, two curved rockers, saddle, handle grips, mane]
+ - id: toy_hard_train
+ tier: hard
+ category: toys
+ prompt: a toy steam locomotive with a boiler, smokestack, cab with windows, cowcatcher, six driving wheels with connecting rods, and a coal tender with four wheels
+ must_have: [cylindrical boiler, smokestack, cab, cowcatcher, six large wheels with rods, separate tender with coal load and four wheels]
+ # ---------------------------------------------------------------- musical instruments
+ - id: mus_easy_drum
+ tier: easy
+ category: musical_instruments
+ prompt: a snare drum with tension rods and two drumsticks resting on top
+ must_have: [cylindrical shell, top head, at least eight tension rods around the rim, two sticks]
+ - id: mus_med_acoustic_guitar
+ tier: medium
+ category: musical_instruments
+ prompt: an acoustic guitar with a figure-eight body, sound hole, bridge, fretted neck, headstock with six tuning pegs and six strings
+ must_have: [figure-eight body, sound hole, bridge, neck with frets, headstock, six tuning pegs, six strings]
+ - id: mus_hard_drum_kit
+ tier: hard
+ category: musical_instruments
+ prompt: a five-piece drum kit with a bass drum with pedal, snare on a stand, two rack toms, a floor tom, a hi-hat and two cymbals on stands, and a throne
+ must_have: [bass drum with pedal, snare on stand, two mounted toms, floor tom with legs, hi-hat with two cymbals, two crash/ride cymbals on stands, drum throne]
diff --git a/harness/bench/report.py b/harness/bench/report.py
new file mode 100644
index 00000000..b4cd5599
--- /dev/null
+++ b/harness/bench/report.py
@@ -0,0 +1,185 @@
+"""Aggregate a bench run: per-tier / per-category stats → markdown + HTML gallery.
+
+``build_report(out_dir)`` reads ``results.jsonl`` (or results.json), aggregates
+mean/median/pass-rate/cost per tier and category, writes ``report.md`` and
+``report.html`` (contact sheets copied into ``report_assets/``).
+"""
+
+from __future__ import annotations
+
+import html
+import json
+import shutil
+import statistics
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from bench.run_bench import BenchItemResult
+
+TIER_ORDER = {"easy": 0, "medium": 1, "hard": 2}
+
+
+class GroupStats(BaseModel):
+ group: str
+ n: int
+ n_scored: int
+ baseline_mean: float | None
+ final_mean: float | None
+ final_median: float | None
+ delta_mean: float | None
+ pass_rate: float | None
+ cost_mean: float
+ minutes_mean: float
+ errors: int
+
+
+class BenchReport(BaseModel):
+ name: str
+ n: int
+ by_tier: list[GroupStats] = Field(default_factory=list)
+ by_category: list[GroupStats] = Field(default_factory=list)
+ overall: GroupStats | None = None
+ markdown: str = ""
+ html: str = ""
+
+
+def load_results(out_dir: Path) -> list[BenchItemResult]:
+ jl = out_dir / "results.jsonl"
+ if jl.is_file():
+ latest: dict[str, BenchItemResult] = {}
+ for line in jl.read_text().splitlines():
+ if line.strip():
+ r = BenchItemResult.model_validate_json(line)
+ latest[r.id] = r
+ return list(latest.values())
+ js = out_dir / "results.json"
+ if js.is_file():
+ return [BenchItemResult.model_validate(r) for r in json.loads(js.read_text())]
+ raise FileNotFoundError(f"no results.jsonl / results.json in {out_dir}")
+
+
+def _mean(xs: list[float]) -> float | None:
+ return round(statistics.fmean(xs), 4) if xs else None
+
+
+def _stats(group: str, rs: list[BenchItemResult]) -> GroupStats:
+ finals = [r.score_final for r in rs if r.score_final is not None]
+ bases = [r.score_baseline for r in rs if r.score_baseline is not None]
+ deltas = [r.score_final - r.score_baseline for r in rs if r.score_final is not None and r.score_baseline is not None]
+ passed = [r.passed for r in rs if r.passed is not None]
+ return GroupStats(
+ group=group, n=len(rs), n_scored=len(finals), baseline_mean=_mean(bases), final_mean=_mean(finals),
+ final_median=round(statistics.median(finals), 4) if finals else None, delta_mean=_mean(deltas),
+ pass_rate=round(sum(passed) / len(passed), 4) if passed else None,
+ cost_mean=round(statistics.fmean([r.cost_usd for r in rs]), 4) if rs else 0.0,
+ minutes_mean=round(statistics.fmean([r.minutes for r in rs]), 2) if rs else 0.0,
+ errors=sum(1 for r in rs if r.status in ("error", "failed") or r.errors),
+ )
+
+
+def _grouped(rs: list[BenchItemResult], key: str) -> list[GroupStats]:
+ groups: dict[str, list[BenchItemResult]] = {}
+ for r in rs:
+ groups.setdefault(getattr(r, key) or "(none)", []).append(r)
+ names = sorted(groups, key=lambda g: (TIER_ORDER.get(g, 99), g))
+ return [_stats(g, groups[g]) for g in names]
+
+
+def _fmt(v: float | None, spec: str = ".3f") -> str:
+ return "-" if v is None else format(v, spec)
+
+
+def _md_table(title: str, stats: list[GroupStats]) -> str:
+ lines = [f"### {title}", "", "| group | n | scored | baseline | final | median | Δ | pass | $/run | min/run | errors |",
+ "|---|---|---|---|---|---|---|---|---|---|---|"]
+ for s in stats:
+ lines.append(f"| {s.group} | {s.n} | {s.n_scored} | {_fmt(s.baseline_mean)} | {_fmt(s.final_mean)} | "
+ f"{_fmt(s.final_median)} | {_fmt(s.delta_mean, '+.3f')} | {_fmt(s.pass_rate, '.0%')} | "
+ f"{s.cost_mean:.2f} | {s.minutes_mean:.1f} | {s.errors} |")
+ return "\n".join(lines) + "\n"
+
+
+def _sheet_for(r: BenchItemResult) -> Path | None:
+ ws = Path(r.workspace) if r.workspace else None
+ if ws is None or not (ws / "record.json").is_file():
+ return None
+ try:
+ rec = json.loads((ws / "record.json").read_text())
+ except ValueError:
+ return None
+ best = rec.get("best_round")
+ for rnd in rec.get("rounds", []):
+ if rnd.get("index") == best and rnd.get("renders") and rnd["renders"].get("contact_sheet"):
+ p = Path(rnd["renders"]["contact_sheet"])
+ p = p if p.is_absolute() else ws / p
+ return p if p.is_file() else None
+ return None
+
+
+def build_report(out_dir: Path | str, *, title: str | None = None) -> BenchReport:
+ out = Path(out_dir)
+ results = sorted(load_results(out), key=lambda r: (TIER_ORDER.get(r.tier, 99), r.id))
+ meta = json.loads((out / "battery.json").read_text()) if (out / "battery.json").is_file() else {}
+ name = title or meta.get("battery", {}).get("name", out.name)
+ rep = BenchReport(name=name, n=len(results), by_tier=_grouped(results, "tier"),
+ by_category=_grouped(results, "category"), overall=_stats("all", results))
+ opts = meta.get("options", {})
+ md = [f"# bench report — {name}", "", f"runs: {len(results)} · generator: {opts.get('generator') or 'default'} · "
+ f"judge: {opts.get('judge') or 'default'} · rounds ≤ {opts.get('rounds', '?')}", ""]
+ md.append(_md_table("overall", [rep.overall] if rep.overall else []))
+ md.append(_md_table("by tier", rep.by_tier))
+ md.append(_md_table("by category", rep.by_category))
+ md += ["### per prompt", "", "| id | tier | category | baseline | final | passed | rounds | $ | min | status |",
+ "|---|---|---|---|---|---|---|---|---|---|"]
+ for r in results:
+ md.append(f"| {r.id} | {r.tier} | {r.category} | {_fmt(r.score_baseline)} | {_fmt(r.score_final)} | "
+ f"{'-' if r.passed is None else ('yes' if r.passed else 'no')} | {r.rounds} | {r.cost_usd:.2f} | "
+ f"{r.minutes:.1f} | {r.status}{' ⚠' if r.errors else ''} |")
+ rep.markdown = "\n".join(md) + "\n"
+ (out / "report.md").write_text(rep.markdown)
+ rep.html = _html_gallery(out, name, results, rep)
+ (out / "report.html").write_text(rep.html)
+ return rep
+
+
+def _html_gallery(out: Path, name: str, results: list[BenchItemResult], rep: BenchReport) -> str:
+ assets = out / "report_assets"
+ assets.mkdir(exist_ok=True)
+ cards = []
+ for r in results:
+ sheet = _sheet_for(r)
+ img = ""
+ if sheet is not None:
+ dst = assets / f"{r.id}{sheet.suffix}"
+ shutil.copy2(sheet, dst)
+ img = f'<img src="report_assets/{dst.name}" loading="lazy">'
+ badge = "pass" if r.passed else ("fail" if r.passed is False else "na")
+ cards.append(
+ f'<div class="card {badge}">{img}<div class="meta"><b>{html.escape(r.id)}</b> · {html.escape(r.tier)} · '
+ f'{html.escape(r.category)}<br>baseline {_fmt(r.score_baseline)} → final {_fmt(r.score_final)} · '
+ f'rounds {r.rounds} · ${r.cost_usd:.2f} · {r.minutes:.1f} min · {html.escape(r.status)}'
+ f'{"<br><span class=err>" + html.escape(r.errors[:200]) + "</span>" if r.errors else ""}</div></div>'
+ )
+
+ def _rows(stats: list[GroupStats]) -> str:
+ return "".join(
+ f"<tr><td>{html.escape(s.group)}</td><td>{s.n}</td><td>{_fmt(s.baseline_mean)}</td><td>{_fmt(s.final_mean)}</td>"
+ f"<td>{_fmt(s.delta_mean, '+.3f')}</td><td>{_fmt(s.pass_rate, '.0%')}</td><td>{s.cost_mean:.2f}</td></tr>"
+ for s in stats
+ )
+
+ table = ("<table><tr><th>group</th><th>n</th><th>baseline</th><th>final</th><th>Δ</th><th>pass</th><th>$/run</th></tr>"
+ + _rows([rep.overall] if rep.overall else []) + _rows(rep.by_tier) + "</table>")
+ style = ("body{font-family:system-ui,sans-serif;margin:24px;background:#111;color:#eee}"
+ ".grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(380px,1fr));gap:14px}"
+ ".card{background:#1c1c1c;border-radius:8px;overflow:hidden;border:2px solid #333}.card.pass{border-color:#2e7d32}"
+ ".card.fail{border-color:#8a1c1c}.card img{width:100%;display:block}.meta{padding:8px;font-size:13px}"
+ ".err{color:#f88}table{border-collapse:collapse;margin:12px 0}td,th{border:1px solid #444;padding:4px 10px}")
+ return (f"<!doctype html><meta charset='utf-8'><title>bench {html.escape(name)}</title><style>{style}</style>"
+ f"<h1>bench — {html.escape(name)}</h1>{table}<div class='grid'>{''.join(cards)}</div>")
+
+
+def report_dict(rep: BenchReport) -> dict[str, Any]:
+ return rep.model_dump(mode="json", exclude={"markdown", "html"})
diff --git a/harness/bench/run_bench.py b/harness/bench/run_bench.py
new file mode 100644
index 00000000..62e47372
--- /dev/null
+++ b/harness/bench/run_bench.py
@@ -0,0 +1,200 @@
+"""Run a prompt battery through a track with N parallel workers; resumable.
+
+Layout of ``out_dir``::
+
+ battery.json the battery as loaded (+ overrides used)
+ runs/<id>/ one workspace per prompt (slug = prompt id)
+ results.jsonl append-only, one line per finished prompt (resume source)
+ results.csv / results.json rewritten at the end from results.jsonl
+
+Every prompt becomes a ``Spec`` with the battery's track/language, a FIXED judge
+model (methodology: paired runs share the judge), and the generator under test.
+"""
+
+from __future__ import annotations
+
+import csv
+import json
+import time
+import traceback
+from collections.abc import Callable
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+import yaml
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.common import Backends, Budget, Language, Track
+from codeverse.contracts.run import RunRecord
+from codeverse.contracts.spec import Constraints, Spec
+from codeverse.workspace import Workspace
+
+RESULT_FIELDS = ("id", "tier", "category", "score_baseline", "score_final", "passed", "rounds", "cost_usd",
+ "minutes", "status", "errors", "workspace", "generator", "judge")
+
+
+class BenchPrompt(BaseModel):
+ id: str
+ prompt: str
+ tier: str = Field(description="easy | medium | hard")
+ category: str = ""
+ must_have: list[str] = Field(default_factory=list)
+ dimensions_m: dict[str, float] | None = None
+ tags: list[str] = Field(default_factory=list)
+
+
+class Battery(BaseModel):
+ name: str
+ track: Track
+ language: Language
+ description: str = ""
+ prompts: list[BenchPrompt] = Field(min_length=1)
+
+ @classmethod
+ def load(cls, path: Path | str) -> Battery:
+ data = yaml.safe_load(Path(path).read_text())
+ return cls.model_validate(data)
+
+
+class BenchItemResult(BaseModel):
+ id: str
+ tier: str
+ category: str = ""
+ score_baseline: float | None = None
+ score_final: float | None = None
+ passed: bool | None = None
+ rounds: int = 0
+ cost_usd: float = 0.0
+ minutes: float = 0.0
+ status: str = ""
+ errors: str = ""
+ workspace: str = ""
+ generator: str = ""
+ judge: str = ""
+
+
+class BenchOptions(BaseModel):
+ generator: str | None = None
+ planner: str | None = None
+ judge: str | None = None
+ rounds: int = 4
+ max_usd: float = 5.0
+ max_minutes: float = 60.0
+ parallel: int = 2
+ limit: int | None = None
+ ids: list[str] = Field(default_factory=list)
+ tiers: list[str] = Field(default_factory=list)
+ resume: bool = True
+
+
+def spec_for(battery: Battery, item: BenchPrompt, opts: BenchOptions) -> Spec:
+ backends = Backends(**{k: v for k, v in {"generator": opts.generator, "planner": opts.planner,
+ "judge": opts.judge}.items() if v})
+ return Spec(
+ id=f"{battery.name}/{item.id}", track=battery.track, language=battery.language, prompt=item.prompt,
+ constraints=Constraints(must_have=list(item.must_have), dimensions_m=item.dimensions_m),
+ budget=Budget(max_rounds=opts.rounds, max_usd=opts.max_usd, max_minutes=opts.max_minutes),
+ backends=backends, tags=["bench", battery.name, item.tier, item.category, *item.tags],
+ )
+
+
+def result_from_record(item: BenchPrompt, rec: RunRecord, minutes: float, ws: Workspace) -> BenchItemResult:
+ best = next((r for r in rec.rounds if r.index == rec.best_round), None)
+ return BenchItemResult(
+ id=item.id, tier=item.tier, category=item.category, score_baseline=rec.baseline_score,
+ score_final=rec.final_score, passed=None if best is None or best.judgment is None else best.judgment.passed,
+ rounds=len(rec.rounds), cost_usd=rec.total_usage.cost_usd, minutes=round(minutes, 2),
+ status=rec.status.value, errors=rec.error, workspace=str(ws.root),
+ generator=rec.spec.backends.generator, judge=rec.spec.backends.judge,
+ )
+
+
+def _load_done(results_jsonl: Path) -> dict[str, BenchItemResult]:
+ done: dict[str, BenchItemResult] = {}
+ if results_jsonl.is_file():
+ for line in results_jsonl.read_text().splitlines():
+ if line.strip():
+ r = BenchItemResult.model_validate_json(line)
+ done[r.id] = r
+ return done
+
+
+def _select(battery: Battery, opts: BenchOptions) -> list[BenchPrompt]:
+ items = battery.prompts
+ if opts.ids:
+ items = [p for p in items if p.id in set(opts.ids)]
+ if opts.tiers:
+ items = [p for p in items if p.tier in set(opts.tiers)]
+ if opts.limit is not None:
+ items = items[: opts.limit]
+ return items
+
+
+RunFn = Callable[[Spec, Workspace, bool], RunRecord]
+
+
+def _default_run(spec: Spec, ws: Workspace, resume: bool) -> RunRecord:
+ from codeverse.tracks import get_track
+
+ return get_track(spec.track).run(spec, ws, resume=resume)
+
+
+def run_battery(
+ battery_path: Path | str, out_dir: Path | str, opts: BenchOptions | None = None, *,
+ run_fn: RunFn | None = None, on_result: Callable[[BenchItemResult], None] | None = None,
+) -> list[BenchItemResult]:
+ """Run (or resume) a battery; returns every result (previous + new)."""
+ opts = opts or BenchOptions()
+ run_fn = run_fn or _default_run
+ battery = Battery.load(battery_path)
+ out = Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ (out / "battery.json").write_text(json.dumps({"battery": battery.model_dump(mode="json"),
+ "options": opts.model_dump(mode="json"),
+ "started_at": datetime.now(UTC).isoformat()}, indent=2))
+ results_jsonl = out / "results.jsonl"
+ done = _load_done(results_jsonl) if opts.resume else {}
+ todo = [p for p in _select(battery, opts) if p.id not in done]
+
+ def _one(item: BenchPrompt) -> BenchItemResult:
+ ws = Workspace(out / "runs" / item.id)
+ resume = ws.exists()
+ if not resume:
+ ws.create()
+ spec = spec_for(battery, item, opts)
+ if not resume:
+ ws.write_json(ws.spec_path, spec)
+ t0 = time.time()
+ try:
+ rec = run_fn(spec, ws, resume)
+ except Exception as e: # one failing prompt must not kill the battery
+ return BenchItemResult(id=item.id, tier=item.tier, category=item.category, status="error",
+ errors=f"{type(e).__name__}: {e}\n{traceback.format_exc()[-1500:]}",
+ minutes=round((time.time() - t0) / 60, 2), workspace=str(ws.root),
+ generator=spec.backends.generator, judge=spec.backends.judge)
+ return result_from_record(item, rec, (time.time() - t0) / 60, ws)
+
+ with ThreadPoolExecutor(max_workers=max(1, opts.parallel)) as pool, results_jsonl.open("a") as fh:
+ futs = {pool.submit(_one, item): item for item in todo}
+ for fut in as_completed(futs):
+ res = fut.result()
+ done[res.id] = res
+ fh.write(res.model_dump_json() + "\n")
+ fh.flush()
+ if on_result:
+ on_result(res)
+ ordered = [done[p.id] for p in battery.prompts if p.id in done]
+ write_results(out, ordered)
+ return ordered
+
+
+def write_results(out_dir: Path, results: list[BenchItemResult]) -> None:
+ rows: list[dict[str, Any]] = [r.model_dump(mode="json") for r in results]
+ (out_dir / "results.json").write_text(json.dumps(rows, indent=2))
+ with (out_dir / "results.csv").open("w", newline="") as fh:
+ w = csv.DictWriter(fh, fieldnames=list(RESULT_FIELDS))
+ w.writeheader()
+ for r in rows:
+ w.writerow({k: r.get(k) for k in RESULT_FIELDS})
diff --git a/harness/codeverse/__init__.py b/harness/codeverse/__init__.py
new file mode 100644
index 00000000..bba02f94
--- /dev/null
+++ b/harness/codeverse/__init__.py
@@ -0,0 +1,29 @@
+"""codeverse — the 3dcodeverse harness.
+
+A backend harness in which LLMs (API models or agentic CLIs) write RAW,
+executable 3D code — Blender ``bpy``, CadQuery, Three.js, URDF, GLSL — for
+three tracks (static objects, articulated objects, scenes). Every run is
+planned, generated, linted, executed, measured, rendered, judged, refined and
+finally emitted as a data-flywheel record.
+
+Package map (each sub-package has its own docstring):
+
+- ``conventions`` single source of truth for frames, units, naming.
+- ``config`` settings (keys, binaries, defaults) — layered, typed.
+- ``contracts`` pydantic models shared by everything (Spec, Plan, Gate,
+ Judgment, Usage, RunRecord ...). No logic lives here.
+- ``models`` ChatModel backends: Gemini / Anthropic / OpenAI (+ key pool).
+- ``agents`` CodingAgent backends: gemini-cli / claude-code / codex /
+ antigravity / api-agent (tool loop on any ChatModel).
+- ``languages`` LanguageRuntime per raw language: lint, build, export.
+- ``spatial`` language-agnostic 3D tools on GLB/scene: measure, render,
+ slice, isolate, silhouette, joints, probes — also served as
+ an MCP server to agentic harnesses.
+- ``judges`` VLM judges + rubrics + deterministic metrics.
+- ``tracks`` static_object / articulated_object / scene pipelines.
+- ``orchestrator`` stage runner, round loop, fan-out, budget, events.
+- ``flywheel`` run records → dataset samples / preference pairs.
+- ``cli`` ``c3v`` command line.
+"""
+
+__version__ = "0.1.0"
diff --git a/harness/codeverse/agents/__init__.py b/harness/codeverse/agents/__init__.py
new file mode 100644
index 00000000..4a36bb0b
--- /dev/null
+++ b/harness/codeverse/agents/__init__.py
@@ -0,0 +1,10 @@
+"""CodingAgent backends (agentic sessions on a workspace).
+
+Ids: ``gemini-cli:<model>`` · ``claude-code:<model>`` · ``codex:<model>`` ·
+``agy:<model>`` · ``api-agent:<provider>:<model>``.
+"""
+
+from codeverse.agents.base import CodingAgent
+from codeverse.agents.registry import get_coding_agent, parse_agent_id
+
+__all__ = ["CodingAgent", "get_coding_agent", "parse_agent_id"]
diff --git a/harness/codeverse/agents/antigravity.py b/harness/codeverse/agents/antigravity.py
new file mode 100644
index 00000000..6717cc05
--- /dev/null
+++ b/harness/codeverse/agents/antigravity.py
@@ -0,0 +1,151 @@
+"""``agy:<model>`` — Antigravity CLI (Google) headless session on a workspace.
+
+argv: ``agy --print <prompt> --model <model> --dangerously-skip-permissions
+--print-timeout <N>m --output-format json --add-dir <ws>``
+
+Observed (agy 1.1.x) JSON envelope::
+
+ {"conversation_id": "...", "status": "SUCCESS" | "ERROR", "response": "...", ["error": "..."],
+ "duration_seconds": 2.3, "num_turns": 1,
+ "usage": {"input_tokens", "output_tokens", "thinking_tokens", "cache_read_tokens", "total_tokens"}}
+
+MCP: agy only supports *global* registration (``agy mcp add``), so no
+per-workspace server is wired; the materialised body tells the agent to call
+``python -m codeverse.cli.main tools <name> --json ...`` from the shell instead.
+Cost: subscription-billed → ``cost_usd`` 0 with a note. Plain-text output is
+accepted when the JSON envelope is missing.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from codeverse.agents.cli_common import (
+ Session,
+ begin_session,
+ deliver_prompt,
+ exists_on_path,
+ failed,
+ finish_session,
+ hardened_env,
+ tail,
+)
+from codeverse.agents.watchdog import run_with_watchdog
+from codeverse.config import get_settings
+from codeverse.contracts.agent import AgentJob, AgentResult
+from codeverse.contracts.common import Usage
+
+IDLE_GRACE_S = 300.0
+
+
+def parse_agy_json(stdout: str) -> dict[str, Any] | None:
+ s = stdout.strip()
+ if not s:
+ return None
+ for cand in (s, *reversed([ln for ln in s.splitlines() if ln.strip().startswith("{")])):
+ try:
+ obj = json.loads(cand)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(obj, dict) and ("response" in obj or "status" in obj):
+ return obj
+ return None
+
+
+def usage_from_agy(env: dict[str, Any], model: str) -> Usage:
+ u = env.get("usage") or {}
+ return Usage(
+ backend="agy", model=model,
+ input_tokens=int(u.get("input_tokens") or 0),
+ output_tokens=int(u.get("output_tokens") or 0),
+ cached_tokens=int(u.get("cache_read_tokens") or 0),
+ thoughts_tokens=int(u.get("thinking_tokens") or 0),
+ cost_usd=0.0, # subscription; no USD exposed
+ latency_ms=int(float(env.get("duration_seconds") or 0.0) * 1000),
+ )
+
+
+class AntigravityAgent:
+ kind = "agy"
+
+ def __init__(self, model: str, binary: str | None = None):
+ self.model = model
+ self.binary = binary or get_settings().binaries.agy_cli
+
+ @property
+ def id(self) -> str:
+ return f"{self.kind}:{self.model}"
+
+ def available(self) -> tuple[bool, str]:
+ if not exists_on_path(self.binary):
+ return False, f"agy CLI not found: {self.binary!r}"
+ return True, "ok"
+
+ def build_argv(self, s: Session, prompt: str) -> list[str]:
+ minutes = max(1, int(s.job.timeout_s // 60) + 1)
+ argv = [self.binary, "--print", prompt, "--dangerously-skip-permissions",
+ "--print-timeout", f"{minutes}m", "--output-format", "json",
+ "--add-dir", str(s.ws.root), "--disable-slash-commands"]
+ if self.model:
+ argv += ["--model", self.model]
+ return argv
+
+ def build_env(self, s: Session) -> dict[str, str]:
+ return hardened_env(s.ws, s.job)
+
+ def run(self, job: AgentJob) -> AgentResult:
+ ok, why = self.available()
+ s = begin_session(job, self.kind)
+ if not ok:
+ return failed(s, "error", why)
+ prompt = deliver_prompt(s, _compose_prompt(s))
+ argv = self.build_argv(s, prompt)
+ s.traj.append("invoke", argv=[a if a != prompt else f"<prompt {len(prompt)} chars>" for a in argv])
+ proc = run_with_watchdog(
+ argv, cwd=s.ws.root, env=self.build_env(s), soft_timeout_s=job.timeout_s, idle_grace_s=IDLE_GRACE_S,
+ on_line=lambda stream, line: s.traj.append("line", stream=stream, text=line[:4000]),
+ activity_dirs=[s.ws.src, s.ws.public],
+ )
+ s.traj.write_text("stdout.json", proc.stdout)
+ s.traj.write_text("stderr.log", proc.stderr)
+ env = parse_agy_json(proc.stdout)
+ usage = usage_from_agy(env, self.model) if env else Usage(backend=self.kind, model=self.model)
+ usage.latency_ms = usage.latency_ms or int(proc.duration_s * 1000)
+ text = str(env.get("response", "")) if env else proc.stdout.strip()
+ errors: list[str] = []
+ if env is None:
+ s.notes.append("no JSON envelope from agy; usage unknown (zeros), response taken from plain stdout")
+ s.notes.append("agy is subscription-billed: cost_usd=0")
+ if proc.timed_out:
+ ok, reason = False, "timeout"
+ errors.append(f"killed by watchdog ({proc.killed_reason}) after {proc.duration_s:.0f}s")
+ elif proc.rc != 0 or (env is not None and str(env.get("status", "SUCCESS")).upper() not in ("SUCCESS", "OK")):
+ ok, reason = False, "error"
+ errors.append(f"rc={proc.rc}; status={(env or {}).get('status')}; error={(env or {}).get('error', '')}; "
+ f"stderr tail: {tail(proc.stderr, 1500)}")
+ elif not text.strip():
+ ok, reason = False, "error"
+ errors.append("empty response")
+ else:
+ ok, reason = True, "completed"
+ return finish_session(
+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=0, errors=errors,
+ rc=proc.rc, killed_reason=proc.killed_reason,
+ conversation_id=(env or {}).get("conversation_id", ""), num_turns=(env or {}).get("num_turns", 0),
+ )
+
+
+def _compose_prompt(s: Session) -> str:
+ """agy has no system-prompt flag; prepend harness instructions + the absolute workspace path."""
+ job = s.job
+ head = f"Workspace root: {s.ws.root}\nWork ONLY inside it, using your file tools."
+ if (s.ws.root / "AGENTS.md").is_file():
+ head += " Read AGENTS.md there first and follow it."
+ head += "\n"
+ if job.system_append:
+ head += f"\n<harness_instructions>\n{job.system_append}\n</harness_instructions>\n"
+ return f"{head}\n{job.prompt}"
+
+
+__all__ = ["AntigravityAgent", "parse_agy_json", "usage_from_agy"]
diff --git a/harness/codeverse/agents/api_agent.py b/harness/codeverse/agents/api_agent.py
new file mode 100644
index 00000000..ddd6119a
--- /dev/null
+++ b/harness/codeverse/agents/api_agent.py
@@ -0,0 +1,232 @@
+"""``api-agent:<provider>:<model>`` — in-process agentic loop on any ChatModel.
+
+Tools: sandboxed file tools (+ ``run_shell``) and every spatial registry tool
+(``build``, ``measure``, ``render_views`` ...) as native function calls. The
+loop runs until the model stops calling tools or ``job.max_turns``; it writes a
+per-turn transcript JSONL, accumulates ``Usage``, compacts old tool results
+when the context grows, and applies the *freshness* rule: a model that claims
+to be done after editing files without a subsequent ``build`` is nudged once.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from typing import Any
+
+from codeverse.agents.api_tools import FileTools, SpatialTools, ToolOutcome
+from codeverse.agents.cli_common import Session, begin_session, failed, finish_session
+from codeverse.agents.context import compact_messages, message_chars
+from codeverse.contracts.agent import AgentJob, AgentResult
+from codeverse.contracts.chat import (
+ ChatMessage,
+ ChatRequest,
+ ChatResponse,
+ TextPart,
+ ToolCallPart,
+ ToolResultPart,
+ ToolSpec,
+)
+from codeverse.contracts.common import Usage
+
+log = logging.getLogger(__name__)
+
+BUILD_TOOL = "build"
+COMPACT_AT_CHARS = 350_000
+MODEL_RETRIES = 3
+DEFAULT_SYSTEM = (
+ "You are an expert 3D programmer working inside a harness-managed workspace. "
+ "Use the tools to read, write and verify code under src/ and public/. Write RAW code in the "
+ "language the task names; never import from `codeverse` or any helper SDK. Call `build` after "
+ "every batch of edits and only finish on a clean build. Reply with a short summary when done; "
+ "never ask questions — decide and proceed."
+)
+FRESHNESS_NUDGE = (
+ "You edited files after your last `build`. Run the `build` tool now, read its result, fix any "
+ "errors, and only then give your final summary."
+)
+
+
+class ApiAgent:
+ kind = "api-agent"
+
+ def __init__(self, model: str, chat_model: Any | None = None):
+ self.model = model # '<provider>:<model>'
+ self._chat_model = chat_model
+
+ @property
+ def id(self) -> str:
+ return f"{self.kind}:{self.model}"
+
+ def _chat(self):
+ if self._chat_model is None:
+ from codeverse.models import get_chat_model
+
+ self._chat_model = get_chat_model(self.model)
+ return self._chat_model
+
+ def available(self) -> tuple[bool, str]:
+ try:
+ from codeverse.models import parse_model_id
+
+ parse_model_id(self.model)
+ except Exception as e: # noqa: BLE001 - report, don't raise
+ return False, str(e)
+ try:
+ self._chat()
+ except Exception as e: # noqa: BLE001
+ return False, f"chat model unavailable: {e}"
+ return True, "ok"
+
+ # ------------------------------------------------------------------ run
+ def run(self, job: AgentJob) -> AgentResult:
+ s = begin_session(job, self.kind)
+ try:
+ chat = self._chat()
+ except Exception as e: # noqa: BLE001
+ return failed(s, "error", f"chat model unavailable: {e}")
+ loop = _Loop(self, s, chat)
+ return loop.run()
+
+
+class _Loop:
+ """One session's state: tools, messages, usage, freshness, compaction."""
+
+ def __init__(self, agent: ApiAgent, s: Session, chat: Any):
+ self.agent, self.s, self.chat = agent, s, chat
+ job = s.job
+ extra = job.extra
+ self.files = FileTools(s.ws, job.write_roots, allow_shell=bool(extra.get("allow_shell", True)))
+ self.spatial: SpatialTools | None = None
+ if job.spatial_tools:
+ self.spatial = SpatialTools(s.ws, track=str(extra.get("track", "")), language=str(extra.get("language", "")),
+ round_index=int(extra.get("round", 0) or 0))
+ if not self.spatial.tools:
+ s.notes.append("spatial registry is empty; running with file tools only")
+ self.spatial = None
+ self.specs: list[ToolSpec] = self.files.specs() + (self.spatial.specs() if self.spatial else [])
+ self.usage = Usage(backend="api-agent", model=agent.model)
+ self.tool_calls = 0
+ self.last_write_turn = -1
+ self.last_build_turn = -1
+ self.nudged = False
+ self.errors: list[str] = []
+ self.messages: list[ChatMessage] = [ChatMessage.user(job.prompt)]
+ self.system = self._system_prompt()
+ self.max_usd = float(extra.get("max_usd", 0) or 0)
+ self.t_deadline = time.monotonic() + job.timeout_s
+
+ def _system_prompt(self) -> str:
+ agents_md = self.s.ws.root / "AGENTS.md"
+ base = agents_md.read_text() if agents_md.is_file() else DEFAULT_SYSTEM
+ if self.s.job.system_append:
+ base += "\n\n" + self.s.job.system_append
+ return base
+
+ # ------------------------------------------------------------------ loop
+ def run(self) -> AgentResult:
+ job = self.s.job
+ traj = self.s.traj
+ traj.append("system", text=self.system[:20000], tools=[t.name for t in self.specs])
+ ok, reason, text = False, "budget", ""
+ for turn in range(job.max_turns):
+ if time.monotonic() > self.t_deadline:
+ reason, self.errors = "timeout", self.errors + [f"wall clock exceeded {job.timeout_s}s"]
+ break
+ resp = self._generate(turn)
+ if resp is None:
+ reason = "error"
+ break
+ text = resp.text
+ self.messages.append(_assistant_message(resp))
+ traj.append("assistant", turn=turn, text=resp.text[:20000],
+ tool_calls=[{"id": c.id, "name": c.name, "arguments": c.arguments} for c in resp.tool_calls],
+ usage=resp.usage.model_dump(), finish_reason=resp.finish_reason)
+ if not resp.tool_calls:
+ if self._needs_build_nudge():
+ self.nudged = True
+ self.messages.append(ChatMessage.user(FRESHNESS_NUDGE))
+ traj.append("nudge", turn=turn, text=FRESHNESS_NUDGE)
+ continue
+ ok, reason = True, "completed"
+ break
+ self._execute(turn, resp.tool_calls)
+ if self.max_usd and self.usage.cost_usd > self.max_usd:
+ reason, self.errors = "budget", self.errors + [f"cost {self.usage.cost_usd:.3f} > max_usd {self.max_usd}"]
+ break
+ if message_chars(self.messages) > COMPACT_AT_CHARS:
+ self.messages = compact_messages(self.messages, keep_recent=6, facts=self._facts())
+ traj.append("compact", turn=turn, chars=message_chars(self.messages))
+ else:
+ self.errors.append(f"max_turns ({job.max_turns}) reached")
+ return finish_session(self.s, ok=ok, exit_reason=reason, text=text, usage=self.usage,
+ tool_calls=self.tool_calls, errors=self.errors, turns=len(self.messages),
+ nudged=self.nudged, tools=[t.name for t in self.specs])
+
+ def _generate(self, turn: int) -> ChatResponse | None:
+ req = ChatRequest(messages=self.messages, system=self.system, tools=self.specs,
+ temperature=float(self.s.job.extra.get("temperature", 0.3)),
+ thinking=self.s.job.extra.get("thinking", "low"), label=f"api-agent:{self.s.label}:t{turn}")
+ delay = 2.0
+ for attempt in range(MODEL_RETRIES):
+ try:
+ resp = self.chat.generate(req)
+ self.usage = self.usage + resp.usage
+ return resp
+ except Exception as e: # ModelError or provider glitch
+ retryable = bool(getattr(e, "retryable", False))
+ self.s.traj.append("model_error", turn=turn, attempt=attempt, error=str(e)[:2000], retryable=retryable)
+ if not retryable or attempt == MODEL_RETRIES - 1:
+ self.errors.append(f"model error on turn {turn}: {type(e).__name__}: {e}")
+ return None
+ time.sleep(delay)
+ delay *= 2
+ return None
+
+ # ------------------------------------------------------------------ tools
+ def _execute(self, turn: int, calls: list[ToolCallPart]) -> None:
+ parts: list[ToolResultPart] = []
+ for call in calls:
+ self.tool_calls += 1
+ out = self._dispatch(call.name, dict(call.arguments or {}))
+ if call.name in ("write_file", "edit_file") and not out.is_error:
+ self.last_write_turn = turn
+ if call.name in (BUILD_TOOL, "run_build"):
+ self.last_build_turn = turn
+ parts.append(ToolResultPart(call_id=call.id, name=call.name, content=out.text, images=out.images, is_error=out.is_error))
+ self.s.traj.append("tool_result", turn=turn, name=call.name, call_id=call.id, ok=not out.is_error,
+ content=out.text[:8000], images=[i.path for i in out.images], numbers=out.numbers)
+ self.messages.append(ChatMessage(role="tool", parts=parts))
+
+ def _dispatch(self, name: str, args: dict[str, Any]) -> ToolOutcome:
+ if name == "run_build" and self.spatial and BUILD_TOOL in self.spatial.names():
+ name = BUILD_TOOL
+ if name in self.files.names():
+ return self.files.call(name, args)
+ if self.spatial and name in self.spatial.names():
+ return self.spatial.call(name, args)
+ return ToolOutcome(f"unknown tool {name!r}; available: {sorted(t.name for t in self.specs)}", is_error=True)
+
+ def _needs_build_nudge(self) -> bool:
+ has_build = bool(self.spatial and BUILD_TOOL in self.spatial.names())
+ return has_build and not self.nudged and self.last_write_turn > self.last_build_turn
+
+ def _facts(self) -> str:
+ writes = list(dict.fromkeys(self.files.writes))
+ lines = [f"- tool calls so far: {self.tool_calls}",
+ f"- files written/edited (in order): {', '.join(writes) if writes else 'none'}",
+ f"- last build turn: {self.last_build_turn} (last write turn: {self.last_write_turn})"]
+ return "\n".join(lines)
+
+
+def _assistant_message(resp: ChatResponse) -> ChatMessage:
+ parts: list[Any] = []
+ if resp.text:
+ parts.append(TextPart(text=resp.text))
+ parts.extend(resp.tool_calls)
+ if not parts:
+ parts.append(TextPart(text=""))
+ return ChatMessage(role="assistant", parts=parts)
+
+
+__all__ = ["ApiAgent", "DEFAULT_SYSTEM", "FRESHNESS_NUDGE"]
diff --git a/harness/codeverse/agents/api_tools.py b/harness/codeverse/agents/api_tools.py
new file mode 100644
index 00000000..4a64758f
--- /dev/null
+++ b/harness/codeverse/agents/api_tools.py
@@ -0,0 +1,230 @@
+"""Tool set for the in-process ``api-agent``: sandboxed file tools + shell + spatial registry.
+
+Every tool returns a :class:`ToolOutcome` (text, images, is_error). Paths are
+resolved inside the workspace; writes are restricted to ``write_roots``.
+``run_shell`` accepts only an allow-listed interpreter/command with no shell
+operators, runs under the watchdog and never inherits host secrets.
+"""
+
+from __future__ import annotations
+
+import fnmatch
+import json
+import os
+import shlex
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from codeverse.agents.watchdog import run_with_watchdog
+from codeverse.config import get_settings
+from codeverse.contracts.chat import ImagePart, ToolSpec
+from codeverse.workspace import Workspace
+
+READ_CAP_CHARS = 60_000
+SHELL_OUT_CAP = 6_000
+SHELL_TIMEOUT_S = 180.0
+SHELL_ALLOW = ("node", "python", "python3", "ls", "cat", "head", "tail", "wc", "grep", "find", "stat")
+_SHELL_OPERATORS = {"|", "&&", "||", ";", ">", ">>", "<", "2>", "&"}
+_SKIP_GLOB_DIRS = (".git", "node_modules", "__pycache__", "trajectories")
+
+
+@dataclass
+class ToolOutcome:
+ text: str
+ images: list[ImagePart] = field(default_factory=list)
+ is_error: bool = False
+ numbers: dict[str, Any] = field(default_factory=dict)
+
+
+class PathDenied(ValueError):
+ pass
+
+
+def _schema(props: dict[str, dict[str, Any]], required: list[str]) -> dict[str, Any]:
+ return {"type": "object", "properties": props, "required": required}
+
+
+class FileTools:
+ """read_file / write_file / edit_file / list_files / run_shell inside one workspace."""
+
+ def __init__(self, ws: Workspace, write_roots: list[str], *, allow_shell: bool = True):
+ self.ws = ws
+ self.write_roots = [(ws.root / r).resolve() for r in write_roots]
+ self.allow_shell = allow_shell
+ self.writes: list[str] = [] # workspace-relative paths written/edited, in order
+
+ # ------------------------------------------------------------------ specs
+ def specs(self) -> list[ToolSpec]:
+ roots = ", ".join(os.path.relpath(r, self.ws.root) + "/" for r in self.write_roots)
+ specs = [
+ ToolSpec(name="read_file", description="Read a text file in the workspace (path relative to the workspace root).",
+ parameters=_schema({"path": {"type": "string", "description": "workspace-relative path"}}, ["path"])),
+ ToolSpec(name="write_file", description=f"Create or overwrite a text file. Only allowed under: {roots}. Parent dirs are created.",
+ parameters=_schema({"path": {"type": "string"}, "content": {"type": "string"}}, ["path", "content"])),
+ ToolSpec(name="edit_file", description=f"Exact-string replacement in an existing file (under {roots}). `old` must occur exactly once unless all=true.",
+ parameters=_schema({"path": {"type": "string"}, "old": {"type": "string"}, "new": {"type": "string"},
+ "all": {"type": "boolean", "description": "replace every occurrence", "default": False}},
+ ["path", "old", "new"])),
+ ToolSpec(name="list_files", description="List workspace files matching a glob (default '**/*' under src/). Hidden/git/node_modules skipped.",
+ parameters=_schema({"glob": {"type": "string", "description": "e.g. 'src/**/*.js'", "default": "src/**/*"}}, [])),
+ ]
+ if self.allow_shell:
+ specs.append(ToolSpec(
+ name="run_shell",
+ description=f"Run ONE command in the workspace root (no pipes/redirects/network). Allowed programs: {', '.join(SHELL_ALLOW)}. "
+ "Use it to syntax-check (`node --check src/x.js`, `python -m py_compile src/model.py`) or inspect files.",
+ parameters=_schema({"cmd": {"type": "string", "description": "the command line, e.g. 'node --check src/object.js'"},
+ "timeout_s": {"type": "integer", "default": 60}}, ["cmd"]),
+ ))
+ return specs
+
+ def names(self) -> set[str]:
+ return {s.name for s in self.specs()}
+
+ # ------------------------------------------------------------------ dispatch
+ def call(self, name: str, args: dict[str, Any]) -> ToolOutcome:
+ fn = {"read_file": self.read_file, "write_file": self.write_file, "edit_file": self.edit_file,
+ "list_files": self.list_files, "run_shell": self.run_shell}.get(name)
+ if fn is None or (name == "run_shell" and not self.allow_shell):
+ return ToolOutcome(f"unknown tool {name!r}", is_error=True)
+ try:
+ return fn(**args)
+ except TypeError as e:
+ return ToolOutcome(f"{name}: bad arguments: {e}", is_error=True)
+ except PathDenied as e:
+ return ToolOutcome(f"{name}: {e}", is_error=True)
+ except OSError as e:
+ return ToolOutcome(f"{name}: {type(e).__name__}: {e}", is_error=True)
+
+ # ------------------------------------------------------------------ paths
+ def _resolve(self, path: str, *, write: bool) -> Path:
+ if not isinstance(path, str) or not path.strip():
+ raise PathDenied("path must be a non-empty workspace-relative string")
+ p = Path(path)
+ p = (self.ws.root / p).resolve() if not p.is_absolute() else p.resolve()
+ root = self.ws.root.resolve()
+ if p != root and root not in p.parents:
+ raise PathDenied(f"path escapes the workspace: {path}")
+ if ".git" in p.relative_to(root).parts:
+ raise PathDenied("the .git directory is off limits")
+ if write and not any(p == r or r in p.parents for r in self.write_roots):
+ roots = ", ".join(os.path.relpath(r, root) + "/" for r in self.write_roots)
+ raise PathDenied(f"writes are only allowed under {roots} (got {path})")
+ return p
+
+ # ------------------------------------------------------------------ tools
+ def read_file(self, path: str) -> ToolOutcome:
+ p = self._resolve(path, write=False)
+ if not p.is_file():
+ return ToolOutcome(f"no such file: {path}", is_error=True)
+ text = p.read_text(errors="replace")
+ if len(text) > READ_CAP_CHARS:
+ text = text[:READ_CAP_CHARS] + f"\n... [truncated; file has {len(text)} chars]"
+ return ToolOutcome(text)
+
+ def write_file(self, path: str, content: str) -> ToolOutcome:
+ p = self._resolve(path, write=True)
+ p.parent.mkdir(parents=True, exist_ok=True)
+ existed = p.exists()
+ p.write_text(content)
+ rel = os.path.relpath(p, self.ws.root)
+ self.writes.append(rel)
+ return ToolOutcome(f"{'overwrote' if existed else 'created'} {rel} ({len(content)} chars, {content.count(chr(10)) + 1} lines)")
+
+ def edit_file(self, path: str, old: str, new: str, all: bool = False) -> ToolOutcome: # noqa: A002 - API name
+ p = self._resolve(path, write=True)
+ if not p.is_file():
+ return ToolOutcome(f"no such file: {path} (use write_file to create it)", is_error=True)
+ text = p.read_text()
+ n = text.count(old)
+ if not old:
+ return ToolOutcome("`old` must be non-empty; read the file and quote the exact text to replace", is_error=True)
+ if n == 0:
+ return ToolOutcome(f"`old` not found in {path}; read_file it and copy the exact text", is_error=True)
+ if n > 1 and not all:
+ return ToolOutcome(f"`old` occurs {n} times in {path}; include more context or pass all=true", is_error=True)
+ p.write_text(text.replace(old, new) if all else text.replace(old, new, 1))
+ rel = os.path.relpath(p, self.ws.root)
+ self.writes.append(rel)
+ return ToolOutcome(f"edited {rel}: replaced {n if all else 1} occurrence(s)")
+
+ def list_files(self, glob: str = "src/**/*") -> ToolOutcome:
+ root = self.ws.root
+ out = []
+ for p in sorted(root.rglob("*")):
+ if not p.is_file():
+ continue
+ rel = p.relative_to(root).as_posix()
+ if any(part in _SKIP_GLOB_DIRS or part.startswith(".") for part in Path(rel).parts[:-1]):
+ continue
+ if fnmatch.fnmatch(rel, glob) or fnmatch.fnmatch(rel, glob.replace("**/", "")):
+ out.append(f"{rel} ({p.stat().st_size} B)")
+ if len(out) >= 300:
+ out.append("... (truncated at 300)")
+ break
+ return ToolOutcome("\n".join(out) if out else f"no files match {glob!r}")
+
+ def run_shell(self, cmd: str, timeout_s: int = 60) -> ToolOutcome:
+ try:
+ argv = shlex.split(cmd)
+ except ValueError as e:
+ return ToolOutcome(f"cannot parse command: {e}", is_error=True)
+ if any(tok in _SHELL_OPERATORS for tok in argv): # no shell is involved; this is just a clear message
+ return ToolOutcome("shell operators (| && ; > <) are not allowed; run ONE plain command", is_error=True)
+ if not argv or os.path.basename(argv[0]) not in SHELL_ALLOW:
+ return ToolOutcome(f"program {argv[0] if argv else ''!r} not allowed; use one of {SHELL_ALLOW}", is_error=True)
+ for a in argv[1:]:
+ if a.startswith("/") and not a.startswith(str(self.ws.root)):
+ return ToolOutcome(f"absolute paths outside the workspace are not allowed: {a}", is_error=True)
+ env = {
+ "PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": str(self.ws.root), "LANG": "C.UTF-8",
+ "NODE_PATH": str(get_settings().runtime_js_dir() / "node_modules"), "PYTHONDONTWRITEBYTECODE": "1",
+ "NO_PROXY": "*", "no_proxy": "*",
+ }
+ t = float(max(5, min(int(timeout_s), int(SHELL_TIMEOUT_S))))
+ proc = run_with_watchdog(argv, cwd=self.ws.root, env=env, soft_timeout_s=t, idle_grace_s=5, hard_timeout_s=t + 5,
+ activity_dirs=[], poll_s=0.2)
+ body = f"$ {cmd}\nrc={proc.rc}" + (" (killed: timeout)" if proc.timed_out else "")
+ if proc.stdout.strip():
+ body += "\n--- stdout ---\n" + _cap(proc.stdout)
+ if proc.stderr.strip():
+ body += "\n--- stderr ---\n" + _cap(proc.stderr)
+ return ToolOutcome(body, is_error=proc.rc != 0)
+
+
+def _cap(text: str, n: int = SHELL_OUT_CAP) -> str:
+ if len(text) <= n:
+ return text
+ head, tail_ = n // 4, n - n // 4
+ return text[:head] + f"\n... [{len(text) - n} chars omitted] ...\n" + text[-tail_:]
+
+
+class SpatialTools:
+ """Bridge from the ``codeverse.spatial.registry`` to native tool calls."""
+
+ def __init__(self, ws: Workspace, *, track: str = "", language: str = "", round_index: int = 0):
+ from codeverse.spatial.registry import ToolContext, list_tools
+
+ self.ctx = ToolContext(workspace=ws, round_index=round_index, language=language, track=track)
+ self.tools = {t.name: t for t in list_tools(track=track, language=language)}
+
+ def specs(self) -> list[ToolSpec]:
+ return [ToolSpec(name=t.name, description=t.description, parameters=t.schema()) for t in self.tools.values()]
+
+ def names(self) -> set[str]:
+ return set(self.tools)
+
+ def call(self, name: str, args: dict[str, Any]) -> ToolOutcome:
+ t = self.tools.get(name)
+ if t is None:
+ return ToolOutcome(f"unknown spatial tool {name!r}", is_error=True)
+ obs = t.call(self.ctx, args)
+ text = obs.text
+ if obs.numbers:
+ text += "\n\nnumbers: " + json.dumps(obs.numbers, default=str)[:4000]
+ images = [ImagePart(path=p, label=Path(p).stem) for p in obs.images if Path(p).is_file()]
+ return ToolOutcome(text, images=images, is_error=not obs.ok, numbers=obs.numbers)
+
+
+__all__ = ["FileTools", "SpatialTools", "ToolOutcome", "PathDenied", "SHELL_ALLOW"]
diff --git a/harness/codeverse/agents/base.py b/harness/codeverse/agents/base.py
new file mode 100644
index 00000000..2f77336f
--- /dev/null
+++ b/harness/codeverse/agents/base.py
@@ -0,0 +1,38 @@
+"""The CodingAgent protocol every agentic backend implements."""
+
+from __future__ import annotations
+
+from typing import Protocol, runtime_checkable
+
+from codeverse.contracts.agent import AgentJob, AgentResult
+
+
+@runtime_checkable
+class CodingAgent(Protocol):
+ """Runs ONE headless agent session in ``job.workspace``.
+
+ Contract for implementations:
+ * the agent may only write under ``job.write_roots`` (harness materialises
+ AGENTS.md/GEMINI.md/CLAUDE.md + MCP config before the call; see
+ ``agents/materialize.py``),
+ * never raise for agent failures — return ``AgentResult(ok=False, exit_reason=...)``,
+ * fill ``usage`` (tokens + cost) as precisely as the CLI allows,
+ * write the full transcript to ``job.workspace/trajectories/...`` and set
+ ``transcript_path``,
+ * compute ``files_changed`` via ``Workspace.changed_files`` (git), not by
+ trusting the agent's claims,
+ * respect ``job.timeout_s`` with an activity-aware watchdog (kill the whole
+ process group on timeout).
+ """
+
+ kind: str # gemini-cli | claude-code | codex | agy | api-agent
+ model: str
+
+ @property
+ def id(self) -> str: ...
+
+ def run(self, job: AgentJob) -> AgentResult: ...
+
+ def available(self) -> tuple[bool, str]:
+ """(is_usable, reason) — binary found / auth present / model known."""
+ ...
diff --git a/harness/codeverse/agents/claude_code.py b/harness/codeverse/agents/claude_code.py
new file mode 100644
index 00000000..a3fe0e03
--- /dev/null
+++ b/harness/codeverse/agents/claude_code.py
@@ -0,0 +1,167 @@
+"""``claude-code:<model>`` — headless Claude Code session on a workspace.
+
+argv: ``claude -p <prompt> --output-format json --dangerously-skip-permissions
+--model <model> --max-turns N --allowedTools ... [--mcp-config ws/.mcp.json
+--strict-mcp-config] [--append-system-prompt ...]``
+
+JSON envelope (claude 2.1.x, observed): ``{type:"result", subtype:"success",
+is_error, result, session_id, num_turns, duration_ms, total_cost_usd,
+stop_reason, terminal_reason, usage:{input_tokens, output_tokens,
+cache_read_input_tokens, cache_creation_input_tokens,
+output_tokens_details:{thinking_tokens}}, modelUsage:{<model>:{costUSD,...}}}``.
+Auth: whatever the user's ``claude`` login is (subscription or
+``ANTHROPIC_API_KEY``); we pass that variable through untouched if present.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from codeverse.agents.cli_common import (
+ Session,
+ begin_session,
+ deliver_prompt,
+ exists_on_path,
+ failed,
+ finish_session,
+ hardened_env,
+ is_transient_failure,
+ tail,
+)
+from codeverse.agents.watchdog import run_with_watchdog
+from codeverse.config import get_settings
+from codeverse.contracts.agent import AgentJob, AgentResult
+from codeverse.contracts.common import Usage
+
+ALLOWED_TOOLS = ("Read", "Edit", "Write", "MultiEdit", "Glob", "Grep",
+ "Bash(node:*)", "Bash(python:*)", "Bash(python3:*)", "Bash(ls:*)", "mcp__c3v__*")
+IDLE_GRACE_S = 300.0
+
+
+def parse_claude_json(stdout: str) -> dict[str, Any] | None:
+ """Envelope is one JSON object; tolerate leading log noise and stream-json arrays."""
+ s = stdout.strip()
+ if not s:
+ return None
+ try:
+ obj = json.loads(s)
+ except json.JSONDecodeError:
+ obj = None
+ for line in reversed(s.splitlines()):
+ line = line.strip()
+ if line.startswith("{"):
+ try:
+ cand = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(cand, dict) and cand.get("type") == "result":
+ return cand
+ obj = obj or cand
+ return obj if isinstance(obj, dict) else None
+ if isinstance(obj, list): # stream-json array: last result event wins
+ results = [e for e in obj if isinstance(e, dict) and e.get("type") == "result"]
+ return results[-1] if results else None
+ return obj if isinstance(obj, dict) else None
+
+
+def usage_from_envelope(env: dict[str, Any], model: str) -> Usage:
+ u = env.get("usage") or {}
+ usage = Usage(
+ backend="claude-code", model=model,
+ input_tokens=int(u.get("input_tokens") or 0),
+ output_tokens=int(u.get("output_tokens") or 0),
+ cached_tokens=int(u.get("cache_read_input_tokens") or 0),
+ thoughts_tokens=int(((u.get("output_tokens_details") or {}).get("thinking_tokens")) or 0),
+ tool_calls=max(int(env.get("num_turns") or 0) - 1, 0),
+ cost_usd=float(env.get("total_cost_usd") or 0.0),
+ latency_ms=int(env.get("duration_ms") or 0),
+ )
+ # modelUsage carries the real served model name(s); keep the first when ours is an alias
+ served = list((env.get("modelUsage") or {}).keys())
+ if served and model not in served:
+ usage.model = served[0]
+ return usage
+
+
+class ClaudeCodeAgent:
+ kind = "claude-code"
+
+ def __init__(self, model: str, binary: str | None = None):
+ self.model = model
+ self.binary = binary or get_settings().binaries.claude_cli
+
+ @property
+ def id(self) -> str:
+ return f"{self.kind}:{self.model}"
+
+ def available(self) -> tuple[bool, str]:
+ if not exists_on_path(self.binary):
+ return False, f"claude CLI not found: {self.binary!r}"
+ return True, "ok"
+
+ def build_argv(self, s: Session, prompt: str) -> list[str]:
+ job = s.job
+ argv = [self.binary, "-p", prompt, "--output-format", "json", "--dangerously-skip-permissions",
+ "--max-turns", str(job.max_turns), "--no-session-persistence",
+ "--allowedTools", ",".join(ALLOWED_TOOLS)]
+ if self.model:
+ argv += ["--model", self.model]
+ mcp = s.ws.root / ".mcp.json"
+ if job.spatial_tools and mcp.is_file():
+ argv += ["--mcp-config", str(mcp), "--strict-mcp-config"]
+ else:
+ argv += ["--strict-mcp-config"] # never inherit the user's ambient MCP servers
+ if job.system_append:
+ argv += ["--append-system-prompt", job.system_append]
+ return argv
+
+ def build_env(self, s: Session) -> dict[str, str]:
+ # keep ANTHROPIC_API_KEY if the user relies on it; subscription auth needs nothing
+ return hardened_env(s.ws, s.job, keep={"ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"})
+
+ def run(self, job: AgentJob) -> AgentResult:
+ ok, why = self.available()
+ s = begin_session(job, self.kind)
+ if not ok:
+ return failed(s, "error", why)
+ prompt = deliver_prompt(s, job.prompt)
+ argv = self.build_argv(s, prompt)
+ s.traj.append("invoke", argv=[a if a != prompt else f"<prompt {len(prompt)} chars>" for a in argv])
+ proc = run_with_watchdog(
+ argv, cwd=s.ws.root, env=self.build_env(s), soft_timeout_s=job.timeout_s, idle_grace_s=IDLE_GRACE_S,
+ on_line=lambda stream, line: s.traj.append("line", stream=stream, text=line[:4000]),
+ activity_dirs=[s.ws.src, s.ws.public],
+ )
+ s.traj.write_text("stdout.json", proc.stdout)
+ s.traj.write_text("stderr.log", proc.stderr)
+ env = parse_claude_json(proc.stdout)
+ usage = usage_from_envelope(env, self.model) if env else Usage(backend=self.kind, model=self.model)
+ usage.latency_ms = usage.latency_ms or int(proc.duration_s * 1000)
+ text = str((env or {}).get("result") or "")
+ turns = int((env or {}).get("num_turns") or 0)
+ errors: list[str] = []
+ if proc.timed_out:
+ reason, ok = "timeout", False
+ errors.append(f"killed by watchdog ({proc.killed_reason}) after {proc.duration_s:.0f}s")
+ elif env is None or proc.rc != 0:
+ reason, ok = "error", False
+ errors.append(f"rc={proc.rc}; no result envelope; stderr tail: {tail(proc.stderr, 1500)}")
+ if is_transient_failure(proc.stderr, proc.stdout):
+ reason = "budget" if "rate" in proc.stderr.lower() else "error"
+ elif env.get("is_error") or str(env.get("subtype", "")).startswith("error"):
+ ok = False
+ sub = str(env.get("subtype", ""))
+ reason = "budget" if "max_turns" in sub else "error"
+ errors.append(f"claude reported {sub or 'is_error'}: {tail(text, 800)}")
+ else:
+ reason, ok = "completed", True
+ return finish_session(
+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=max(turns - 1, 0),
+ errors=errors, rc=proc.rc, killed_reason=proc.killed_reason, num_turns=turns,
+ session_id=(env or {}).get("session_id", ""), subtype=(env or {}).get("subtype", ""),
+ model_usage=(env or {}).get("modelUsage", {}),
+ )
+
+
+__all__ = ["ClaudeCodeAgent", "parse_claude_json", "usage_from_envelope", "ALLOWED_TOOLS"]
diff --git a/harness/codeverse/agents/cli_common.py b/harness/codeverse/agents/cli_common.py
new file mode 100644
index 00000000..bb7eb1cb
--- /dev/null
+++ b/harness/codeverse/agents/cli_common.py
@@ -0,0 +1,205 @@
+"""Shared plumbing for subprocess-based CodingAgent backends.
+
+* :func:`hardened_env` — child environment without unrelated secrets.
+* :func:`begin_session` / :func:`finish_session` — trajectory dir, git
+ snapshot before/after, ``files_changed`` from git, ``result.json``.
+* :func:`deliver_prompt` — argv prompt or "read the prompt file" stub.
+* :func:`estimate_cost_safe` — lazy bridge to ``codeverse.models.pricing``.
+* :func:`is_transient_failure` — 429 / 503 / empty-response detection.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import re
+import sys
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from codeverse.agents.transcript import Trajectory
+from codeverse.contracts.agent import AgentJob, AgentResult
+from codeverse.contracts.common import Usage
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+#: argv prompts above this many bytes are written to a file instead.
+MAX_ARGV_PROMPT_BYTES = 100_000
+
+_SECRET_EXACT = {
+ "GEMINI_API_KEYS", "GEMINI_API_KEY", "GOOGLE_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY",
+ "OPENAI_ORG_ID", "HF_TOKEN", "HUGGINGFACE_TOKEN", "GITHUB_TOKEN", "GH_TOKEN", "AWS_SECRET_ACCESS_KEY",
+ "AWS_SESSION_TOKEN", "SUPABASE_SERVICE_ROLE_KEY", "CODEX_API_KEY",
+}
+_SECRET_SUFFIXES = ("_API_KEY", "_SECRET", "_SECRET_KEY", "_TOKEN", "_AUTH_TOKEN", "_PASSWORD", "_PRIVATE_KEY")
+
+
+def is_secret_env(name: str) -> bool:
+ """True for env vars that look like credentials (stripped from agent children)."""
+ return name in _SECRET_EXACT or name.endswith(_SECRET_SUFFIXES)
+
+
+def hardened_env(ws: Workspace, job: AgentJob, *, keep: set[str] | None = None) -> dict[str, str]:
+ """Copy ``os.environ`` minus secrets, plus recursion guard + git ceiling + ``job.env``.
+
+ ``keep`` names secrets that must survive (e.g. the CLI's own auth var).
+ """
+ keep = keep or set()
+ env = {k: v for k, v in os.environ.items() if k in keep or not is_secret_env(k)}
+ env["C3V_AGENT_CONTEXT"] = "1"
+ env["GIT_CEILING_DIRECTORIES"] = str(ws.root.parent)
+ env["PYTHONUNBUFFERED"] = "1"
+ env.update(job.env)
+ return env
+
+
+def default_mcp_command(ws: Workspace, *, language: str = "", track: str = "", round_index: int | None = None) -> list[str]:
+ """The stdio MCP server command exposing the spatial tool registry for ``ws``."""
+ cmd = [sys.executable, "-m", "codeverse.spatial.mcp_server", "--workspace", str(ws.root)]
+ if language:
+ cmd += ["--language", language]
+ if track:
+ cmd += ["--track", track]
+ if round_index is not None:
+ cmd += ["--round", str(round_index)]
+ return cmd
+
+
+def mcp_command_for(ws: Workspace, job: AgentJob) -> list[str]:
+ """The c3v MCP command for this job: ``.mcp.json`` (materialised) > ``job.extra['mcp_command']`` > default."""
+ mcp = ws.root / ".mcp.json"
+ if mcp.is_file():
+ try:
+ srv = (json.loads(mcp.read_text()).get("mcpServers") or {}).get("c3v")
+ except json.JSONDecodeError:
+ srv = None
+ if srv and srv.get("command"):
+ return [srv["command"], *srv.get("args", [])]
+ if job.extra.get("mcp_command"):
+ return list(job.extra["mcp_command"])
+ return default_mcp_command(ws, language=str(job.extra.get("language", "")), track=str(job.extra.get("track", "")),
+ round_index=int(job.extra.get("round", 0) or 0))
+
+
+# --------------------------------------------------------------------------- session
+@dataclass
+class Session:
+ """State for one CLI agent run (created by :func:`begin_session`)."""
+
+ ws: Workspace
+ job: AgentJob
+ kind: str
+ label: str
+ round_index: int
+ traj: Trajectory
+ head_before: str
+ t0: float = field(default_factory=time.monotonic)
+ notes: list[str] = field(default_factory=list)
+
+
+def begin_session(job: AgentJob, kind: str) -> Session:
+ """Create the trajectory dir, write prompt.md and snapshot src/ (``pre:<label>``)."""
+ ws = Workspace(job.workspace)
+ if not ws.root.is_dir():
+ raise FileNotFoundError(f"workspace does not exist: {ws.root}")
+ if not (ws.root / ".git").exists():
+ ws.create()
+ label = job.label or kind
+ round_index = int(job.extra.get("round", 0) or 0)
+ traj = Trajectory(ws.trajectory_dir(label, round_index))
+ traj.write_prompt(job.prompt, job.system_append)
+ head_before = ws.commit(f"pre:{label}")
+ return Session(ws=ws, job=job, kind=kind, label=label, round_index=round_index,
+ traj=traj, head_before=head_before)
+
+
+def finish_session(
+ s: Session,
+ *,
+ ok: bool,
+ exit_reason: str,
+ text: str,
+ usage: Usage,
+ tool_calls: int = 0,
+ errors: list[str] | None = None,
+ **extra: Any,
+) -> AgentResult:
+ """Commit the agent's work, compute ``files_changed`` via git, write result.json."""
+ s.ws.commit(f"agent:{s.label}")
+ files = s.ws.changed_files(s.head_before)
+ res = AgentResult(
+ ok=ok, exit_reason=exit_reason, text=text, files_changed=files,
+ transcript_path=str(s.traj.transcript_path if s.traj.transcript_path.exists() else s.traj.dir),
+ usage=usage, duration_s=round(time.monotonic() - s.t0, 3), tool_calls=tool_calls,
+ errors=list(errors or []),
+ )
+ s.traj.write_result(res, kind=s.kind, label=s.label, round=s.round_index,
+ head_before=s.head_before, head_after=s.ws.head(), notes=s.notes, **extra)
+ return res
+
+
+def failed(s: Session, reason: str, message: str, usage: Usage | None = None) -> AgentResult:
+ """Shortcut for an ``ok=False`` result with one error line."""
+ return finish_session(s, ok=False, exit_reason=reason, text="", usage=usage or Usage(), errors=[message])
+
+
+# --------------------------------------------------------------------------- prompts
+def deliver_prompt(s: Session, prompt: str, *, max_bytes: int = MAX_ARGV_PROMPT_BYTES) -> str:
+ """Return the text to pass on argv: the prompt itself, or a stub pointing at a file."""
+ if len(prompt.encode("utf-8")) <= max_bytes:
+ return prompt
+ p = s.traj.write_text("task_prompt.md", prompt)
+ s.notes.append(f"prompt ({len(prompt)} chars) delivered via file {p}")
+ rel = os.path.relpath(p, s.ws.root)
+ return (
+ f"Your full task is in the file `{rel}` (relative to the current working directory). "
+ "Read that file completely with your file-reading tool FIRST, then carry out every "
+ "instruction in it. Do not ask for confirmation."
+ )
+
+
+# --------------------------------------------------------------------------- failures
+_TRANSIENT_RE = re.compile(
+ r"(\b429\b|RESOURCE_EXHAUSTED|rate.?limit|quota|\b503\b|UNAVAILABLE|overloaded|"
+ r"\b502\b|\b500\b|INTERNAL|empty response|Invalid stream|ECONNRESET|ETIMEDOUT|socket hang up)",
+ re.IGNORECASE,
+)
+_QUOTA_RE = re.compile(r"(\b429\b|RESOURCE_EXHAUSTED|quota|rate.?limit)", re.IGNORECASE)
+
+
+def is_transient_failure(*texts: str) -> bool:
+ """Heuristic: did the CLI die of a rate-limit / 5xx / empty-stream glitch?"""
+ return any(_TRANSIENT_RE.search(t or "") for t in texts)
+
+
+def is_quota_failure(*texts: str) -> bool:
+ return any(_QUOTA_RE.search(t or "") for t in texts)
+
+
+def tail(text: str, n: int = 2000) -> str:
+ return text if len(text) <= n else text[-n:]
+
+
+# --------------------------------------------------------------------------- pricing
+def estimate_cost_safe(provider: str, model: str, usage: Usage) -> float:
+ """``codeverse.models.pricing.estimate_cost`` when available; else 0.0 + warning."""
+ try:
+ from codeverse.models.pricing import estimate_cost
+ except ImportError:
+ log.warning("codeverse.models.pricing unavailable; cost for %s:%s recorded as 0", provider, model)
+ return 0.0
+ try:
+ return float(estimate_cost(provider, model, usage))
+ except Exception as e: # unknown model in the price table must not sink the run
+ log.warning("estimate_cost(%s, %s) failed: %s", provider, model, e)
+ return 0.0
+
+
+def exists_on_path(binary: str) -> bool:
+ from shutil import which
+
+ return bool(which(binary)) or Path(binary).is_file()
diff --git a/harness/codeverse/agents/codex.py b/harness/codeverse/agents/codex.py
new file mode 100644
index 00000000..48b42291
--- /dev/null
+++ b/harness/codeverse/agents/codex.py
@@ -0,0 +1,181 @@
+"""``codex:<model>`` — headless OpenAI Codex CLI session on a workspace.
+
+argv: ``codex exec --json -C <ws> --sandbox workspace-write --skip-git-repo-check
+[--model <model>] [-c mcp_servers.c3v.command=... -c mcp_servers.c3v.args=[...]] <prompt>``
+(prompt on stdin when long). stdout is JSONL:
+
+* ``{"type":"thread.started","thread_id":...}`` / ``turn.started``
+* ``{"type":"item.completed","item":{"type":"agent_message"|"reasoning"|
+ "command_execution"|"file_change"|"mcp_tool_call", ...}}``
+* ``{"type":"turn.completed","usage":{"input_tokens","cached_input_tokens","output_tokens",
+ "reasoning_output_tokens","cache_write_input_tokens"}}``
+* ``{"type":"turn.failed","error":{"message":...}}`` / ``{"type":"error","message":...}``
+"""
+
+from __future__ import annotations
+
+import json
+
+from codeverse.agents.cli_common import (
+ Session,
+ begin_session,
+ estimate_cost_safe,
+ exists_on_path,
+ failed,
+ finish_session,
+ hardened_env,
+ mcp_command_for,
+ tail,
+)
+from codeverse.agents.materialize import codex_mcp_overrides
+from codeverse.agents.watchdog import run_with_watchdog
+from codeverse.config import get_settings
+from codeverse.contracts.agent import AgentJob, AgentResult
+from codeverse.contracts.common import Usage
+
+IDLE_GRACE_S = 300.0
+STDIN_PROMPT_BYTES = 100_000
+_TOOL_ITEMS = ("command_execution", "file_change", "mcp_tool_call", "web_search", "tool_call")
+
+
+class CodexEvents:
+ """Folded view over the JSONL event stream."""
+
+ def __init__(self) -> None:
+ self.messages: list[str] = []
+ self.errors: list[str] = []
+ self.tool_calls = 0
+ self.turns_completed = 0
+ self.usage_raw: dict[str, int] = {"input_tokens": 0, "cached_input_tokens": 0, "output_tokens": 0,
+ "reasoning_output_tokens": 0, "cache_write_input_tokens": 0}
+ self.thread_id = ""
+ self.n_events = 0
+
+ def feed(self, line: str) -> None:
+ line = line.strip()
+ if not line.startswith("{"):
+ return
+ try:
+ ev = json.loads(line)
+ except json.JSONDecodeError:
+ return
+ self.n_events += 1
+ t = ev.get("type", "")
+ if t == "thread.started":
+ self.thread_id = str(ev.get("thread_id", ""))
+ elif t == "item.completed":
+ item = ev.get("item") or {}
+ it = item.get("type", "")
+ if it == "agent_message":
+ self.messages.append(str(item.get("text", "")))
+ elif it in _TOOL_ITEMS:
+ self.tool_calls += 1
+ elif t == "turn.completed":
+ self.turns_completed += 1
+ for k in self.usage_raw:
+ self.usage_raw[k] += int((ev.get("usage") or {}).get(k) or 0)
+ elif t == "turn.failed":
+ self.errors.append(str((ev.get("error") or {}).get("message") or ev))
+ elif t == "error":
+ self.errors.append(str(ev.get("message") or ev))
+
+ def usage(self, model: str) -> Usage:
+ u = Usage(
+ backend="codex", model=model,
+ input_tokens=self.usage_raw["input_tokens"], output_tokens=self.usage_raw["output_tokens"],
+ cached_tokens=self.usage_raw["cached_input_tokens"], tool_calls=self.tool_calls,
+ thoughts_tokens=self.usage_raw["reasoning_output_tokens"],
+ )
+ u.cost_usd = estimate_cost_safe("openai", model, u)
+ return u
+
+
+def parse_codex_jsonl(stdout: str) -> CodexEvents:
+ ev = CodexEvents()
+ for line in stdout.splitlines():
+ ev.feed(line)
+ return ev
+
+
+class CodexAgent:
+ kind = "codex"
+
+ def __init__(self, model: str, binary: str | None = None):
+ self.model = model
+ self.binary = binary or get_settings().binaries.codex_cli
+
+ @property
+ def id(self) -> str:
+ return f"{self.kind}:{self.model}"
+
+ def available(self) -> tuple[bool, str]:
+ if not exists_on_path(self.binary):
+ return False, f"codex CLI not found: {self.binary!r}"
+ return True, "ok"
+
+ def build_argv(self, s: Session, prompt: str | None) -> list[str]:
+ """``prompt=None`` means 'read it from stdin' (``-`` positional)."""
+ job = s.job
+ argv = [self.binary, "exec", "--json", "-C", str(s.ws.root), "--sandbox", "workspace-write",
+ "--skip-git-repo-check", "--ephemeral", "--color", "never"]
+ if self.model:
+ argv += ["--model", self.model]
+ if job.spatial_tools:
+ argv += codex_mcp_overrides(mcp_command_for(s.ws, job))
+ argv.append(prompt if prompt is not None else "-")
+ return argv
+
+ def build_env(self, s: Session) -> dict[str, str]:
+ return hardened_env(s.ws, s.job, keep={"OPENAI_API_KEY", "CODEX_API_KEY"})
+
+ def run(self, job: AgentJob) -> AgentResult:
+ ok, why = self.available()
+ s = begin_session(job, self.kind)
+ if not ok:
+ return failed(s, "error", why)
+ prompt = _compose_prompt(job)
+ via_stdin = len(prompt.encode("utf-8")) > STDIN_PROMPT_BYTES
+ argv = self.build_argv(s, None if via_stdin else prompt)
+ events = CodexEvents()
+ s.traj.append("invoke", argv=[a if a != prompt else f"<prompt {len(prompt)} chars>" for a in argv], stdin=via_stdin)
+
+ def on_line(stream: str, line: str) -> None:
+ s.traj.append("line", stream=stream, text=line[:4000])
+ if stream == "stdout":
+ events.feed(line)
+
+ proc = run_with_watchdog(
+ argv, cwd=s.ws.root, env=self.build_env(s), soft_timeout_s=job.timeout_s, idle_grace_s=IDLE_GRACE_S,
+ on_line=on_line, stdin=prompt if via_stdin else None, activity_dirs=[s.ws.src, s.ws.public],
+ )
+ s.traj.write_text("stdout.jsonl", proc.stdout)
+ s.traj.write_text("stderr.log", proc.stderr)
+ usage = events.usage(self.model)
+ usage.latency_ms = int(proc.duration_s * 1000)
+ text = "\n\n".join(m for m in events.messages if m.strip())
+ errors = list(events.errors)
+ if proc.timed_out:
+ ok, reason = False, "timeout"
+ errors.append(f"killed by watchdog ({proc.killed_reason}) after {proc.duration_s:.0f}s")
+ elif proc.rc != 0 or events.n_events == 0:
+ ok, reason = False, "error"
+ errors.append(f"rc={proc.rc}; events={events.n_events}; stderr tail: {tail(proc.stderr, 1500)}")
+ elif events.errors and events.turns_completed == 0:
+ ok, reason = False, "error"
+ else:
+ ok, reason = True, "completed"
+ return finish_session(
+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=events.tool_calls, errors=errors,
+ rc=proc.rc, killed_reason=proc.killed_reason, thread_id=events.thread_id,
+ turns_completed=events.turns_completed, usage_raw=events.usage_raw,
+ )
+
+
+def _compose_prompt(job: AgentJob) -> str:
+ """codex exec has no system-prompt flag: prepend ``system_append``."""
+ if not job.system_append:
+ return job.prompt
+ return f"<harness_instructions>\n{job.system_append}\n</harness_instructions>\n\n{job.prompt}"
+
+
+__all__ = ["CodexAgent", "CodexEvents", "parse_codex_jsonl"]
diff --git a/harness/codeverse/agents/context.py b/harness/codeverse/agents/context.py
new file mode 100644
index 00000000..772bf4ab
--- /dev/null
+++ b/harness/codeverse/agents/context.py
@@ -0,0 +1,67 @@
+"""Deterministic context compaction for the api-agent loop (no LLM involved).
+
+Old tool-result bodies are trimmed to a stub, old images are dropped, and a
+"facts so far" note is inserted after the first user message so the model keeps
+the task + a running summary while the transcript on disk stays complete.
+"""
+
+from __future__ import annotations
+
+from codeverse.contracts.chat import ChatMessage, ImagePart, TextPart, ToolResultPart
+
+STUB_CHARS = 240
+FACTS_TAG = "<facts_so_far>"
+
+
+def message_chars(messages: list[ChatMessage]) -> int:
+ """Rough context size: text chars + a flat 4k per image."""
+ n = 0
+ for m in messages:
+ for p in m.parts:
+ if isinstance(p, TextPart):
+ n += len(p.text)
+ elif isinstance(p, ToolResultPart):
+ n += len(p.content) + 4000 * len(p.images)
+ elif isinstance(p, ImagePart):
+ n += 4000
+ else: # tool call
+ n += len(str(getattr(p, "arguments", "")))
+ return n
+
+
+def _stub(content: str) -> str:
+ if len(content) <= STUB_CHARS:
+ return content
+ return content[:STUB_CHARS] + f" … [compacted; {len(content)} chars originally]"
+
+
+def compact_messages(messages: list[ChatMessage], *, keep_recent: int = 8, facts: str = "") -> list[ChatMessage]:
+ """Return a new message list with old tool results stubbed and a facts note.
+
+ The first message (the task) and the last ``keep_recent`` messages are kept
+ verbatim; everything in between has tool-result bodies shortened and images
+ removed. Any earlier facts note is replaced.
+ """
+ if len(messages) <= keep_recent + 1:
+ return list(messages)
+ head, middle, tail = messages[0], messages[1:-keep_recent], messages[-keep_recent:]
+ out: list[ChatMessage] = [head]
+ if facts:
+ out.append(ChatMessage.user(f"{FACTS_TAG}\n{facts}\n</facts_so_far>"))
+ for m in middle:
+ if m.role == "user" and m.text.startswith(FACTS_TAG):
+ continue # superseded
+ if m.role != "tool":
+ out.append(m)
+ continue
+ parts = [
+ ToolResultPart(call_id=p.call_id, name=p.name, content=_stub(p.content), images=[], is_error=p.is_error)
+ if isinstance(p, ToolResultPart) else p
+ for p in m.parts
+ ]
+ out.append(ChatMessage(role="tool", parts=parts))
+ out.extend(tail)
+ return out
+
+
+__all__ = ["compact_messages", "message_chars", "FACTS_TAG"]
diff --git a/harness/codeverse/agents/gemini_cli.py b/harness/codeverse/agents/gemini_cli.py
new file mode 100644
index 00000000..02f216b4
--- /dev/null
+++ b/harness/codeverse/agents/gemini_cli.py
@@ -0,0 +1,247 @@
+"""``gemini-cli:<model>`` — headless Gemini CLI session on a workspace.
+
+argv: ``gemini -p <prompt> -m <model> --approval-mode yolo --skip-trust --output-format json``
+
+* env hardening: host secrets stripped, one pool key as ``GEMINI_API_KEY``,
+ ``GEMINI_CLI_SYSTEM_SETTINGS_PATH`` forcing api-key auth + dynamic model
+ configuration (otherwise an unknown model is *silently* substituted), Node
+ heap cap, no self-relaunch.
+* JSON envelope ``{session_id, response, stats:{models:{<m>:{tokens:{input,
+ candidates, cached, thoughts}}}, tools:{totalCalls}}}`` → Usage (+ cost via
+ pricing). Requested model absent from ``stats.models`` → ``model_substituted``.
+* one retry (rotated key) on transient failures (429 / 503 / empty response).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from pathlib import Path
+from typing import Any
+
+from codeverse.agents.cli_common import (
+ Session,
+ begin_session,
+ deliver_prompt,
+ estimate_cost_safe,
+ exists_on_path,
+ failed,
+ finish_session,
+ hardened_env,
+ is_quota_failure,
+ is_transient_failure,
+ tail,
+)
+from codeverse.agents.watchdog import CompletedProc, run_with_watchdog
+from codeverse.config import get_settings
+from codeverse.contracts.agent import AgentJob, AgentResult
+from codeverse.contracts.common import Usage
+
+log = logging.getLogger(__name__)
+
+SYSTEM_SETTINGS = {
+ # folderTrust must be OFF: with it on, gemini-cli silently disables the workspace
+ # .gemini/settings.json mcpServers (even with --skip-trust) → no c3v tools.
+ "security": {"auth": {"selectedType": "gemini-api-key"}, "folderTrust": {"enabled": False}},
+ "experimental": {"dynamicModelConfiguration": True},
+ "general": {"topicUpdateNarration": False},
+}
+IDLE_GRACE_S = 300.0
+
+
+class _LocalKeyRotor:
+ """Fallback key rotation used only when ``codeverse.models.keypool`` is absent."""
+
+ def __init__(self, keys: list[str]):
+ self._keys, self._i = list(keys), 0
+
+ def acquire(self, *, exclude: set[str] | None = None) -> str:
+ for _ in range(len(self._keys)):
+ k = self._keys[self._i % len(self._keys)]
+ self._i += 1
+ if not exclude or k not in exclude or len(self._keys) == 1:
+ return k
+ return self._keys[0]
+
+ def report(self, key: str, status: str) -> None: # parity with KeyPool.report
+ return None
+
+
+_POOLS: dict[tuple[str, ...], Any] = {}
+
+
+def _key_pool(keys: list[str]):
+ """Process-wide pool per key set so cooldowns persist across agent runs."""
+ tkey = tuple(keys)
+ if tkey in _POOLS:
+ return _POOLS[tkey]
+ try:
+ from codeverse.models.keypool import KeyPool
+
+ pool = KeyPool(keys)
+ except ImportError:
+ log.warning("codeverse.models.keypool unavailable; using local round-robin")
+ pool = _LocalKeyRotor(keys)
+ _POOLS[tkey] = pool
+ return pool
+
+
+def write_system_settings(path: Path | None = None) -> Path:
+ """Write the gemini-cli system-settings json (api-key auth + dynamic models) and return its path."""
+ path = path or (get_settings().cache_dir / "gemini_cli_settings.json")
+ path.parent.mkdir(parents=True, exist_ok=True)
+ want = json.dumps(SYSTEM_SETTINGS, indent=2)
+ if not path.is_file() or path.read_text() != want:
+ path.write_text(want)
+ return path
+
+
+def parse_gemini_json(stdout: str) -> dict[str, Any] | None:
+ """The CLI prints one JSON object (possibly after log noise); find it."""
+ s = stdout.strip()
+ if not s:
+ return None
+ try:
+ return json.loads(s)
+ except json.JSONDecodeError:
+ pass
+ start = s.find("{")
+ while start != -1:
+ try:
+ obj = json.loads(s[start:])
+ return obj if isinstance(obj, dict) else None
+ except json.JSONDecodeError:
+ start = s.find("{", start + 1)
+ return None
+
+
+def usage_from_stats(stats: dict[str, Any], model: str) -> Usage:
+ """Sum tokens across every served model (normally just ``model``)."""
+ u = Usage(backend="gemini-cli", model=model)
+ for _name, m in (stats.get("models") or {}).items():
+ tok = (m or {}).get("tokens") or {}
+ u.input_tokens += int(tok.get("input") or tok.get("prompt") or 0)
+ u.output_tokens += int(tok.get("candidates") or 0)
+ u.cached_tokens += int(tok.get("cached") or 0)
+ u.thoughts_tokens += int(tok.get("thoughts") or 0)
+ u.tool_calls = int(((stats.get("tools") or {}).get("totalCalls")) or 0)
+ u.cost_usd = estimate_cost_safe("gemini", model, u)
+ return u
+
+
+class GeminiCliAgent:
+ kind = "gemini-cli"
+
+ def __init__(self, model: str, binary: str | None = None):
+ self.model = model
+ self.binary = binary or get_settings().binaries.gemini_cli
+
+ @property
+ def id(self) -> str:
+ return f"{self.kind}:{self.model}"
+
+ def available(self) -> tuple[bool, str]:
+ if not exists_on_path(self.binary):
+ return False, f"gemini CLI not found: {self.binary!r}"
+ if not get_settings().gemini_api_keys:
+ return False, "no Gemini API keys configured"
+ return True, "ok"
+
+ # ------------------------------------------------------------------ build
+ def build_argv(self, prompt: str) -> list[str]:
+ return [self.binary, "-p", prompt, "-m", self.model, "--approval-mode", "yolo",
+ "--skip-trust", "--output-format", "json"]
+
+ def build_env(self, s: Session, api_key: str) -> dict[str, str]:
+ env = hardened_env(s.ws, s.job)
+ env["GEMINI_API_KEY"] = api_key
+ env["GEMINI_CLI_SYSTEM_SETTINGS_PATH"] = str(write_system_settings())
+ env["GEMINI_CLI_NO_RELAUNCH"] = "1"
+ node_opts = env.get("NODE_OPTIONS", "")
+ if "--max-old-space-size" not in node_opts:
+ env["NODE_OPTIONS"] = f"{node_opts} --max-old-space-size=6144".strip()
+ return env
+
+ # ------------------------------------------------------------------ run
+ def run(self, job: AgentJob) -> AgentResult:
+ ok, why = self.available()
+ s = begin_session(job, self.kind)
+ if not ok:
+ return failed(s, "error", why)
+ prompt = deliver_prompt(s, _compose_prompt(job))
+ pool = _key_pool(get_settings().gemini_api_keys)
+ attempts = 0
+ used: set[str] = set()
+ usage_total = Usage(backend=self.kind, model=self.model)
+ while True:
+ attempts += 1
+ key = pool.acquire(exclude=used or None)
+ used.add(key)
+ proc = self._invoke(s, prompt, key, attempt=attempts)
+ outcome = self._interpret(s, proc)
+ usage_total = usage_total + outcome["usage"]
+ pool.report(key, "429" if outcome["quota"] else ("ok" if outcome["ok"] else "5xx"))
+ if outcome["ok"] or outcome["exit_reason"] in ("timeout", "model_substituted") or not outcome["transient"] or attempts >= 2:
+ break
+ s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); retrying with rotated key")
+ s.traj.append("retry", attempt=attempts, reason=outcome["errors"][:1])
+ usage_total.cost_usd = round(usage_total.cost_usd, 6)
+ return finish_session(
+ s, ok=outcome["ok"], exit_reason=outcome["exit_reason"], text=outcome["text"],
+ usage=usage_total, tool_calls=usage_total.tool_calls, errors=outcome["errors"],
+ attempts=attempts, rc=proc.rc, killed_reason=proc.killed_reason, session_id=outcome.get("session_id", ""),
+ )
+
+ def _invoke(self, s: Session, prompt: str, key: str, *, attempt: int) -> CompletedProc:
+ argv = self.build_argv(prompt)
+ env = self.build_env(s, key)
+ s.traj.append("invoke", attempt=attempt, argv=[a if a != prompt else f"<prompt {len(prompt)} chars>" for a in argv],
+ model=self.model, key_tail=key[-4:])
+ proc = run_with_watchdog(
+ argv, cwd=s.ws.root, env=env, soft_timeout_s=s.job.timeout_s, idle_grace_s=IDLE_GRACE_S,
+ on_line=lambda stream, line: s.traj.append("line", stream=stream, text=line[:4000]),
+ activity_dirs=[s.ws.src, s.ws.public],
+ )
+ suffix = "" if attempt == 1 else f".{attempt}"
+ s.traj.write_text(f"stdout{suffix}.json", proc.stdout)
+ s.traj.write_text(f"stderr{suffix}.log", proc.stderr)
+ return proc
+
+ def _interpret(self, s: Session, proc: CompletedProc) -> dict[str, Any]:
+ parsed = parse_gemini_json(proc.stdout)
+ stats = (parsed or {}).get("stats") or {}
+ usage = usage_from_stats(stats, self.model) if stats else Usage(backend=self.kind, model=self.model)
+ usage.latency_ms = int(proc.duration_s * 1000)
+ text = str((parsed or {}).get("response") or "")
+ errors: list[str] = []
+ served = list((stats.get("models") or {}).keys())
+ out: dict[str, Any] = {"usage": usage, "text": text, "ok": False, "exit_reason": "error",
+ "transient": False, "quota": False, "errors": errors,
+ "session_id": (parsed or {}).get("session_id", "")}
+ if proc.timed_out:
+ out["exit_reason"] = "timeout"
+ errors.append(f"killed by watchdog ({proc.killed_reason}) after {proc.duration_s:.0f}s")
+ return out
+ if served and self.model not in served:
+ out["exit_reason"] = "model_substituted"
+ errors.append(f"requested {self.model!r} but CLI served {served}")
+ return out
+ if parsed is None or proc.rc != 0 or not text.strip():
+ out["transient"] = is_transient_failure(proc.stderr, proc.stdout) or (parsed is not None and not text.strip())
+ out["quota"] = is_quota_failure(proc.stderr, proc.stdout)
+ errors.append(f"rc={proc.rc}; response={'<empty>' if not text.strip() else 'ok'}; stderr tail: {tail(proc.stderr, 1500)}")
+ out["exit_reason"] = "budget" if out["quota"] else "error"
+ return out
+ out["ok"] = True
+ out["exit_reason"] = "completed"
+ return out
+
+
+def _compose_prompt(job: AgentJob) -> str:
+ """gemini-cli has no system-prompt flag: prepend ``system_append`` to the prompt."""
+ if not job.system_append:
+ return job.prompt
+ return f"<harness_instructions>\n{job.system_append}\n</harness_instructions>\n\n{job.prompt}"
+
+
+__all__ = ["GeminiCliAgent", "parse_gemini_json", "usage_from_stats", "write_system_settings"]
diff --git a/harness/codeverse/agents/materialize.py b/harness/codeverse/agents/materialize.py
new file mode 100644
index 00000000..6b308920
--- /dev/null
+++ b/harness/codeverse/agents/materialize.py
@@ -0,0 +1,216 @@
+"""Materialise per-workspace agent instructions + MCP configs.
+
+One shared body is written to ``AGENTS.md`` (codex / generic), ``GEMINI.md``
+(gemini-cli) and ``CLAUDE.md`` (claude-code): task-agnostic rules, how to call
+the ``c3v`` spatial tools, where the cookbook is, and the language contract.
+MCP wiring:
+
+* gemini-cli → ``ws/.gemini/settings.json`` (merged) ``mcpServers.c3v``
+* claude-code → ``ws/.mcp.json``
+* codex → ``-c`` overrides returned in :class:`Materialized.codex_overrides`
+* agy (Antigravity) → no per-workspace MCP; the body documents the CLI fallback.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+from pathlib import Path
+
+from pydantic import BaseModel, Field
+
+from codeverse.prompts import PROMPTS_DIR
+from codeverse.workspace import Workspace
+
+C3V_DIR = ".c3v" # harness-owned read-only docs inside the workspace
+MCP_SERVER_NAME = "c3v"
+MCP_TOOL_TIMEOUT_MS = 600_000
+IGNORE_LINES = ("artifacts/", "trajectories/", ".git/", "node_modules/", "__pycache__/", ".gemini/tmp/")
+
+
+class Materialized(BaseModel):
+ """What :func:`materialize_workspace` wrote and how each CLI reaches the tools."""
+
+ body_files: list[str] = Field(default_factory=list)
+ mcp_files: list[str] = Field(default_factory=list)
+ ignore_files: list[str] = Field(default_factory=list)
+ cookbook_path: str = ""
+ mcp_command: list[str] = Field(default_factory=list)
+ codex_overrides: list[str] = Field(default_factory=list, description="extra argv for `codex exec` (-c k=v pairs)")
+ agy_mcp: str = Field(default="", description="how Antigravity reaches the tools")
+ warnings: list[str] = Field(default_factory=list)
+
+
+# --------------------------------------------------------------------------- body
+def _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str]) -> str:
+ if not spatial_tools:
+ return (
+ "## Spatial tools\n\n"
+ "No spatial tools are available in this session. Verify your work by reading the "
+ "code carefully and keeping every dimension explicit; the harness builds, measures "
+ "and renders after you finish.\n"
+ )
+ from codeverse.spatial.registry import tool_cards
+
+ cards = tool_cards() or "(the tool registry is empty in this environment)"
+ if agent_kind == "claude-code":
+ how = "Tools are exposed by the MCP server `c3v`; their names appear as `mcp__c3v__<name>` (e.g. `mcp__c3v__build`)."
+ elif agent_kind == "agy":
+ how = (
+ "This session has no MCP server. Call a tool from the shell instead:\n"
+ "`python -m codeverse.cli.main tools <name> --json '{\"arg\": \"value\"}'` "
+ "(run from the workspace root; prints the observation as text + JSON)."
+ )
+ elif agent_kind == "api-agent":
+ how = "Tools are native function calls with exactly the names below."
+ elif agent_kind == "gemini-cli":
+ how = (
+ f"Tools are exposed by the MCP server `{MCP_SERVER_NAME}`; they appear in your tool list as "
+ f"`mcp_{MCP_SERVER_NAME}_<name>` (or plain `<name>`). Prefer them over shell commands."
+ )
+ else:
+ how = f"Tools are exposed by the MCP server `{MCP_SERVER_NAME}` (command: `{' '.join(mcp_command)}`); call them by name."
+ return (
+ "## Spatial tools (c3v)\n\n"
+ f"{how}\n\n"
+ "Workflow: edit → `build` → read the errors/numbers → fix → `build` again. Use `render_views` / "
+ "`render_sheet` to LOOK at what you made before declaring it finished; use `measure` / "
+ "`check_contract` to prove dimensions. Never finish on a failing build.\n\n"
+ f"{cards}\n"
+ )
+
+
+def _body(agent_kind: str, contract_md: str, cookbook_note: str, spatial_tools: bool, mcp_command: list[str]) -> str:
+ return (
+ "# c3v workspace — rules for the coding agent\n\n"
+ "You are working inside a harness-managed workspace. Read this whole file before acting.\n\n"
+ "## Hard rules\n\n"
+ "1. You may create or edit files ONLY under `src/` and `public/`. Never modify `artifacts/`, "
+ "`trajectories/`, `.git/`, `.gemini/`, `.c3v/`, or this file — they are harness-owned.\n"
+ "2. Write RAW code in the language named by the contract below. Never import from `codeverse` or "
+ "any helper SDK; do not install packages; do not use the network; do not write "
+ "camera / render / export / file-output code unless the contract explicitly asks for it — "
+ "the harness owns export and rendering.\n"
+ "3. Do not run `git`; the harness snapshots your work before and after the session.\n"
+ "4. Keep dimensions explicit and in meters; follow the coordinate frame stated in the contract.\n"
+ "5. When you are done, reply with a SHORT summary of what you changed and what you verified. "
+ "Do not ask questions — there is no human in the loop; make a reasonable decision and proceed.\n\n"
+ f"{_tool_section(agent_kind, spatial_tools, mcp_command)}\n"
+ f"## Cookbook\n\n{cookbook_note}\n\n"
+ f"## Language contract\n\n{contract_md.strip()}\n"
+ )
+
+
+# --------------------------------------------------------------------------- configs
+def _merge_json(path: Path, patch: dict) -> None:
+ data: dict = {}
+ if path.is_file():
+ try:
+ data = json.loads(path.read_text() or "{}")
+ except json.JSONDecodeError as e:
+ raise ValueError(f"{path} is not valid JSON; refusing to merge: {e}") from e
+ for k, v in patch.items():
+ if isinstance(v, dict) and isinstance(data.get(k), dict):
+ data[k].update(v)
+ else:
+ data[k] = v
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(data, indent=2) + "\n")
+
+
+def _drop_server(path: Path) -> None:
+ if not path.is_file():
+ return
+ try:
+ data = json.loads(path.read_text() or "{}")
+ except json.JSONDecodeError:
+ return
+ servers = data.get("mcpServers")
+ if isinstance(servers, dict) and MCP_SERVER_NAME in servers:
+ servers.pop(MCP_SERVER_NAME)
+ path.write_text(json.dumps(data, indent=2) + "\n")
+
+
+def _toml_str_list(items: list[str]) -> str:
+ return "[" + ", ".join(json.dumps(x) for x in items) + "]"
+
+
+def codex_mcp_overrides(mcp_command: list[str]) -> list[str]:
+ """``-c`` pairs that register the c3v MCP server for one ``codex exec`` call."""
+ return [
+ "-c", f"mcp_servers.{MCP_SERVER_NAME}.command={json.dumps(mcp_command[0])}",
+ "-c", f"mcp_servers.{MCP_SERVER_NAME}.args={_toml_str_list(mcp_command[1:])}",
+ "-c", f"mcp_servers.{MCP_SERVER_NAME}.tool_timeout_sec={MCP_TOOL_TIMEOUT_MS // 1000}",
+ "-c", f"mcp_servers.{MCP_SERVER_NAME}.startup_timeout_sec=60",
+ ]
+
+
+def _resolve_cookbook(ws: Workspace, cookbook_rel: str) -> Path | None:
+ if not cookbook_rel:
+ return None
+ for cand in (ws.root / cookbook_rel, PROMPTS_DIR / cookbook_rel, Path(cookbook_rel)):
+ if cand.is_file():
+ return cand
+ return None
+
+
+# --------------------------------------------------------------------------- entry
+def materialize_workspace(
+ ws: Workspace,
+ *,
+ agent_kind: str,
+ contract_md: str,
+ cookbook_rel: str,
+ spatial_tools: bool,
+ mcp_command: list[str],
+) -> Materialized:
+ """Write AGENTS.md / GEMINI.md / CLAUDE.md + MCP configs + ignore files into ``ws``."""
+ out = Materialized(mcp_command=list(mcp_command))
+ if spatial_tools and not mcp_command:
+ raise ValueError("spatial_tools=True requires a non-empty mcp_command")
+
+ # cookbook: copy into the harness-owned .c3v/ dir so every CLI can read it in-workspace
+ src = _resolve_cookbook(ws, cookbook_rel)
+ if src is not None:
+ dest = ws.root / C3V_DIR / "cookbook.md"
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(src, dest)
+ out.cookbook_path = str(dest)
+ cookbook_note = (
+ f"The cookbook for this language — copyable, verified snippets and skeletons — is at "
+ f"`{C3V_DIR}/cookbook.md` (relative to the workspace root). Read the relevant sections "
+ "before writing code and copy its patterns exactly."
+ + (" You may also call the `read_cookbook` tool." if spatial_tools else "")
+ )
+ else:
+ out.warnings.append(f"cookbook not found: {cookbook_rel!r}")
+ cookbook_note = "No cookbook is available in this session; rely on the contract below."
+
+ body = _body(agent_kind, contract_md, cookbook_note, spatial_tools, list(mcp_command))
+ for name in ("AGENTS.md", "GEMINI.md", "CLAUDE.md"):
+ (ws.root / name).write_text(body)
+ out.body_files.append(str(ws.root / name))
+
+ gemini_settings = ws.root / ".gemini" / "settings.json"
+ claude_mcp = ws.root / ".mcp.json"
+ if spatial_tools:
+ server = {"command": mcp_command[0], "args": list(mcp_command[1:]), "timeout": MCP_TOOL_TIMEOUT_MS}
+ _merge_json(gemini_settings, {"mcpServers": {MCP_SERVER_NAME: server}})
+ _merge_json(claude_mcp, {"mcpServers": {MCP_SERVER_NAME: {"type": "stdio", **server}}})
+ out.mcp_files = [str(gemini_settings), str(claude_mcp)]
+ out.codex_overrides = codex_mcp_overrides(list(mcp_command))
+ out.agy_mcp = (
+ "Antigravity CLI only supports GLOBAL MCP registration (`agy mcp add ...`), which would "
+ "leak across parallel runs; no per-workspace MCP is written. The body documents the "
+ "`python -m codeverse.cli.main tools <name> --json ...` shell fallback instead."
+ )
+ else:
+ _drop_server(gemini_settings)
+ _drop_server(claude_mcp)
+ out.agy_mcp = "spatial tools disabled"
+
+ ignore_text = "\n".join(IGNORE_LINES) + "\n"
+ for name in (".geminiignore", ".aiexclude"):
+ (ws.root / name).write_text(ignore_text)
+ out.ignore_files.append(str(ws.root / name))
+ return out
diff --git a/harness/codeverse/agents/registry.py b/harness/codeverse/agents/registry.py
new file mode 100644
index 00000000..53d2097e
--- /dev/null
+++ b/harness/codeverse/agents/registry.py
@@ -0,0 +1,43 @@
+"""Agent id parsing + factory."""
+
+from __future__ import annotations
+
+from functools import lru_cache
+
+from codeverse.agents.base import CodingAgent
+
+KINDS = ("gemini-cli", "claude-code", "codex", "agy", "api-agent")
+
+
+def parse_agent_id(agent_id: str) -> tuple[str, str]:
+ """``api-agent:gemini:gemini-3.7-flash`` → ('api-agent', 'gemini:gemini-3.7-flash')."""
+ if ":" not in agent_id:
+ raise ValueError(f"agent id must be '<kind>:<model>', got {agent_id!r}")
+ kind, model = agent_id.split(":", 1)
+ if kind not in KINDS:
+ raise ValueError(f"unknown agent kind {kind!r}; known: {KINDS}")
+ return kind, model
+
+
+@lru_cache(maxsize=32)
+def get_coding_agent(agent_id: str) -> CodingAgent:
+ kind, model = parse_agent_id(agent_id)
+ if kind == "gemini-cli":
+ from codeverse.agents.gemini_cli import GeminiCliAgent
+
+ return GeminiCliAgent(model)
+ if kind == "claude-code":
+ from codeverse.agents.claude_code import ClaudeCodeAgent
+
+ return ClaudeCodeAgent(model)
+ if kind == "codex":
+ from codeverse.agents.codex import CodexAgent
+
+ return CodexAgent(model)
+ if kind == "agy":
+ from codeverse.agents.antigravity import AntigravityAgent
+
+ return AntigravityAgent(model)
+ from codeverse.agents.api_agent import ApiAgent
+
+ return ApiAgent(model)
diff --git a/harness/codeverse/agents/transcript.py b/harness/codeverse/agents/transcript.py
new file mode 100644
index 00000000..f3783d68
--- /dev/null
+++ b/harness/codeverse/agents/transcript.py
@@ -0,0 +1,83 @@
+"""Trajectory folder helper: prompt.md, transcript.jsonl, stdout/stderr, result.json.
+
+Every CodingAgent backend writes its session here
+(``ws.trajectory_dir(label, round)``) so the flywheel and ``c3v status`` can
+read one uniform layout regardless of backend.
+"""
+
+from __future__ import annotations
+
+import json
+import threading
+import time
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel
+
+
+class Trajectory:
+ """Append-only writer for one agent session's files."""
+
+ def __init__(self, directory: Path | str):
+ self.dir = Path(directory)
+ self.dir.mkdir(parents=True, exist_ok=True)
+ self._lock = threading.Lock()
+
+ # ------------------------------------------------------------------ paths
+ @property
+ def prompt_path(self) -> Path:
+ return self.dir / "prompt.md"
+
+ @property
+ def transcript_path(self) -> Path:
+ return self.dir / "transcript.jsonl"
+
+ @property
+ def result_path(self) -> Path:
+ return self.dir / "result.json"
+
+ @property
+ def stdout_path(self) -> Path:
+ return self.dir / "stdout.log"
+
+ @property
+ def stderr_path(self) -> Path:
+ return self.dir / "stderr.log"
+
+ # ------------------------------------------------------------------ writes
+ def write_prompt(self, prompt: str, system: str = "") -> Path:
+ body = prompt if not system else f"<!-- system -->\n{system}\n\n<!-- prompt -->\n{prompt}"
+ self.prompt_path.write_text(body)
+ return self.prompt_path
+
+ def write_text(self, name: str, text: str) -> Path:
+ p = self.dir / name
+ p.write_text(text)
+ return p
+
+ def write_json(self, name: str, data: BaseModel | dict[str, Any] | list[Any]) -> Path:
+ p = self.dir / name
+ payload = data.model_dump(mode="json") if isinstance(data, BaseModel) else data
+ tmp = p.with_suffix(p.suffix + ".tmp")
+ tmp.write_text(json.dumps(payload, indent=2, ensure_ascii=False, default=str))
+ tmp.replace(p)
+ return p
+
+ def append(self, kind: str, **data: Any) -> None:
+ """Append one JSONL turn: ``{"t": epoch, "kind": kind, **data}``."""
+ rec = {"t": round(time.time(), 3), "kind": kind, **data}
+ line = json.dumps(rec, ensure_ascii=False, default=str)
+ with self._lock, self.transcript_path.open("a") as fh:
+ fh.write(line + "\n")
+
+ def write_result(self, result: BaseModel, **extra: Any) -> Path:
+ """Write ``result.json`` = AgentResult fields + any extra diagnostics."""
+ data = result.model_dump(mode="json")
+ data.update(extra)
+ return self.write_json("result.json", data)
+
+ def read_transcript(self) -> list[dict[str, Any]]:
+ if not self.transcript_path.is_file():
+ return []
+ return [json.loads(ln) for ln in self.transcript_path.read_text().splitlines() if ln.strip()]
diff --git a/harness/codeverse/agents/watchdog.py b/harness/codeverse/agents/watchdog.py
new file mode 100644
index 00000000..6b2b4d0c
--- /dev/null
+++ b/harness/codeverse/agents/watchdog.py
@@ -0,0 +1,175 @@
+"""Activity-aware subprocess runner for headless agent CLIs.
+
+Three clocks govern a run:
+
+* ``soft_timeout_s`` — the nominal budget. After it elapses the process may
+ keep going *only while it is visibly working*.
+* ``idle_grace_s`` — past the soft timeout, if nothing happened (no stdout /
+ stderr line, no file mtime change under ``activity_dirs``) for this long,
+ the process group is killed (``killed_reason="idle"``).
+* ``hard_timeout_s`` — absolute ceiling; kill regardless (``"hard_timeout"``).
+
+The child is started in its own session so ``os.killpg`` takes the whole
+tree (node → chrome, blender, mcp servers ...).
+"""
+
+from __future__ import annotations
+
+import contextlib
+import os
+import signal
+import subprocess
+import threading
+import time
+from collections.abc import Callable, Iterable, Mapping, Sequence
+from dataclasses import dataclass, field
+from pathlib import Path
+
+_SKIP_DIRS = {"node_modules", ".git", "__pycache__", ".gemini", ".gemini_home"}
+
+
+@dataclass
+class CompletedProc:
+ """Outcome of :func:`run_with_watchdog`."""
+
+ rc: int
+ stdout: str
+ stderr: str
+ duration_s: float
+ timed_out: bool = False
+ killed_reason: str = "" # "" | idle | hard_timeout
+ stdout_lines: list[str] = field(default_factory=list, repr=False)
+ stderr_lines: list[str] = field(default_factory=list, repr=False)
+
+
+class ActivityTracker:
+ """Thread-safe 'last time something happened' clock."""
+
+ def __init__(self) -> None:
+ self._lock = threading.Lock()
+ self._last = time.monotonic()
+
+ def touch(self) -> None:
+ with self._lock:
+ self._last = time.monotonic()
+
+ def idle_for(self) -> float:
+ with self._lock:
+ return time.monotonic() - self._last
+
+
+def _latest_mtime(dirs: Iterable[Path]) -> float:
+ latest = 0.0
+ for d in dirs:
+ if not d.is_dir():
+ continue
+ for root, subdirs, files in os.walk(d):
+ subdirs[:] = [s for s in subdirs if s not in _SKIP_DIRS]
+ for f in files:
+ try:
+ latest = max(latest, os.stat(os.path.join(root, f)).st_mtime)
+ except OSError:
+ continue
+ return latest
+
+
+def _pump(stream, sink: list[str], tracker: ActivityTracker, on_line: Callable[[str, str], None] | None, tag: str) -> None:
+ for raw in iter(stream.readline, b""):
+ line = raw.decode("utf-8", errors="replace").rstrip("\n")
+ sink.append(line)
+ tracker.touch()
+ if on_line is not None:
+ with contextlib.suppress(Exception): # observer bugs must not kill the pump
+ on_line(tag, line)
+ stream.close()
+
+
+def kill_process_group(proc: subprocess.Popen, grace_s: float = 5.0) -> None:
+ """SIGTERM the child's process group, then SIGKILL after ``grace_s``."""
+ if proc.poll() is not None:
+ return
+ try:
+ os.killpg(proc.pid, signal.SIGTERM)
+ except ProcessLookupError:
+ return
+ try:
+ proc.wait(timeout=grace_s)
+ except subprocess.TimeoutExpired:
+ with contextlib.suppress(ProcessLookupError):
+ os.killpg(proc.pid, signal.SIGKILL)
+ proc.wait(timeout=5)
+
+
+def run_with_watchdog(
+ cmd: Sequence[str],
+ *,
+ cwd: Path | str,
+ env: Mapping[str, str] | None,
+ soft_timeout_s: float,
+ idle_grace_s: float = 300.0,
+ hard_timeout_s: float | None = None,
+ on_line: Callable[[str, str], None] | None = None,
+ stdin: str | None = None,
+ activity_dirs: Sequence[Path] | None = None,
+ poll_s: float = 1.0,
+ scan_s: float = 5.0,
+) -> CompletedProc:
+ """Run ``cmd`` streaming output; kill the process group on idle/hard timeout.
+
+ ``on_line(stream, line)`` is called for every line (stream is ``"stdout"``
+ or ``"stderr"``). ``activity_dirs`` (default ``cwd/src``) are polled for
+ mtime changes (every ``scan_s``) that also count as activity.
+ """
+ if hard_timeout_s is None:
+ hard_timeout_s = max(soft_timeout_s * 1.5, soft_timeout_s + 600.0)
+ cwd = Path(cwd)
+ dirs = list(activity_dirs) if activity_dirs is not None else [cwd / "src"]
+ tracker = ActivityTracker()
+ t0 = time.monotonic()
+ proc = subprocess.Popen(
+ list(cmd), cwd=str(cwd), env=dict(env) if env is not None else None,
+ stdin=subprocess.PIPE if stdin is not None else subprocess.DEVNULL,
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True,
+ )
+ out: list[str] = []
+ err: list[str] = []
+ threads = [
+ threading.Thread(target=_pump, args=(proc.stdout, out, tracker, on_line, "stdout"), daemon=True),
+ threading.Thread(target=_pump, args=(proc.stderr, err, tracker, on_line, "stderr"), daemon=True),
+ ]
+ for t in threads:
+ t.start()
+ if stdin is not None:
+ try:
+ proc.stdin.write(stdin.encode("utf-8")) # type: ignore[union-attr]
+ proc.stdin.close() # type: ignore[union-attr]
+ except BrokenPipeError:
+ pass
+
+ killed = ""
+ last_mtime = _latest_mtime(dirs)
+ next_scan = t0 + scan_s
+ while proc.poll() is None:
+ now = time.monotonic()
+ elapsed = now - t0
+ if now >= next_scan:
+ m = _latest_mtime(dirs)
+ if m > last_mtime:
+ last_mtime = m
+ tracker.touch()
+ next_scan = now + scan_s
+ if elapsed >= hard_timeout_s:
+ killed = "hard_timeout"
+ elif elapsed >= soft_timeout_s and tracker.idle_for() >= idle_grace_s:
+ killed = "idle"
+ if killed:
+ kill_process_group(proc)
+ break
+ time.sleep(poll_s)
+ for t in threads:
+ t.join(timeout=10)
+ rc = proc.returncode if proc.returncode is not None else -9
+ return CompletedProc(
+ rc=rc, stdout="\n".join(out), stderr="\n".join(err), duration_s=time.monotonic() - t0,
+ timed_out=bool(killed), killed_reason=killed, stdout_lines=out, stderr_lines=err,
+ )
diff --git a/harness/codeverse/cli/__init__.py b/harness/codeverse/cli/__init__.py
new file mode 100644
index 00000000..844b2c43
--- /dev/null
+++ b/harness/codeverse/cli/__init__.py
@@ -0,0 +1 @@
+"""``c3v`` command line."""
diff --git a/harness/codeverse/cli/_common.py b/harness/codeverse/cli/_common.py
new file mode 100644
index 00000000..ef5b9dd1
--- /dev/null
+++ b/harness/codeverse/cli/_common.py
@@ -0,0 +1,115 @@
+"""Shared CLI plumbing: lazy imports (sub-packages may be incomplete), workspace
+resolution, slug building, typed exits. Keeps ``main.py`` thin."""
+
+from __future__ import annotations
+
+import hashlib
+import importlib
+import shutil
+import sys
+from pathlib import Path
+from typing import Any
+
+import typer
+
+from codeverse.cli._fmt import console, err
+from codeverse.config import get_settings
+from codeverse.contracts.spec import Spec
+from codeverse.conventions import slugify
+from codeverse.workspace import Workspace
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+
+
+class CliError(typer.Exit):
+ """Typed, already-reported failure → exit code."""
+
+ def __init__(self, message: str, code: int = 1):
+ err(message)
+ super().__init__(code=code)
+
+
+def lazy(module: str, attr: str | None = None) -> Any:
+ """Import ``module`` (and ``attr``) at call time; a clear message when the
+ sub-package is not implemented yet (packages are developed in parallel)."""
+ try:
+ mod = importlib.import_module(module)
+ except ImportError as e:
+ raise CliError(
+ f"{module} is not available ({e}). This command needs that sub-package; "
+ f"run `c3v doctor` to see what is installed.", code=2
+ ) from e
+ if attr is None:
+ return mod
+ try:
+ return getattr(mod, attr)
+ except AttributeError as e:
+ raise CliError(f"{module}.{attr} is missing ({e}); the sub-package may be incomplete.", code=2) from e
+
+
+def import_bench() -> Any:
+ """``bench`` lives at the repo root (not inside the package); make it importable."""
+ try:
+ return importlib.import_module("bench")
+ except ImportError:
+ if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+ return lazy("bench")
+
+
+def runs_root(runs_dir: Path | None) -> Path:
+ return Path(runs_dir) if runs_dir is not None else Path(get_settings().runs_dir)
+
+
+def open_workspace(slug: str, runs_dir: Path | None = None) -> Workspace:
+ """``slug`` may be a run name under runs_dir or a path to a run directory."""
+ p = Path(slug)
+ if p.is_dir() and (p / "spec.json").is_file():
+ return Workspace(p)
+ ws = Workspace(runs_root(runs_dir) / slug)
+ if not ws.exists():
+ raise CliError(f"run not found: {ws.root} (no spec.json)")
+ return ws
+
+
+def load_spec(ws: Workspace) -> Spec:
+ try:
+ return Spec.model_validate_json(ws.spec_path.read_text())
+ except Exception as e:
+ raise CliError(f"invalid spec.json in {ws.root}: {e}") from e
+
+
+def make_slug(prompt: str, track: str, language: str, explicit: str | None = None) -> str:
+ if explicit:
+ return slugify(explicit, 64)
+ h = hashlib.sha256(f"{prompt.strip()}|{track}|{language}".encode()).hexdigest()[:8]
+ return f"{slugify(prompt, 40)}_{h}"
+
+
+def create_workspace(root: Path, *, force: bool) -> Workspace:
+ ws = Workspace(root)
+ if ws.root.exists() and any(ws.root.iterdir()):
+ if not force:
+ raise CliError(f"{ws.root} already exists; use --force to overwrite or --slug for a new name")
+ shutil.rmtree(ws.root)
+ ws.create()
+ return ws
+
+
+def parse_kv_floats(items: list[str], flag: str) -> dict[str, float]:
+ out: dict[str, float] = {}
+ for it in items:
+ if "=" not in it:
+ raise CliError(f"{flag} expects key=value, got {it!r}")
+ k, v = it.split("=", 1)
+ try:
+ out[k.strip()] = float(v)
+ except ValueError as e:
+ raise CliError(f"{flag} {k}: not a number: {v!r}") from e
+ return out
+
+
+def echo_json(obj: Any) -> None:
+ import json
+
+ console.print_json(json.dumps(obj, default=str, ensure_ascii=False))
diff --git a/harness/codeverse/cli/_fmt.py b/harness/codeverse/cli/_fmt.py
new file mode 100644
index 00000000..19b4cf04
--- /dev/null
+++ b/harness/codeverse/cli/_fmt.py
@@ -0,0 +1,106 @@
+"""Rich formatting for the CLI: run summaries, tables, observations, doctor rows."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+from rich.console import Console
+from rich.panel import Panel
+from rich.table import Table
+
+from codeverse.contracts.run import RunRecord
+
+console = Console(emoji=False)
+err_console = Console(stderr=True, style="bold red", emoji=False)
+
+
+def err(msg: str) -> None:
+ err_console.print(f"error: {msg}")
+
+
+def ok(msg: str) -> None:
+ console.print(f"[green]{msg}[/green]")
+
+
+def warn(msg: str) -> None:
+ console.print(f"[yellow]{msg}[/yellow]")
+
+
+def fmt_score(s: float | None) -> str:
+ return "-" if s is None else f"{s:.3f}"
+
+
+def fmt_usd(v: float) -> str:
+ return f"${v:.4f}"
+
+
+def rounds_table(record: RunRecord) -> Table:
+ t = Table(title="rounds", show_lines=False)
+ for col in ("#", "kind", "build", "gate err", "score", "passed", "cost", "secs", "commit"):
+ t.add_column(col, justify="right" if col in ("#", "gate err", "score", "cost", "secs") else "left")
+ for r in record.rounds:
+ build = "-" if r.build is None else ("ok" if r.build.ok else "[red]FAIL[/red]")
+ j = r.judgment
+ passed = "-" if j is None else ("[green]yes[/green]" if j.passed else "no")
+ t.add_row(str(r.index), r.kind, build, str(sum(len(g.errors) for g in r.gates)), fmt_score(r.score),
+ passed, fmt_usd(r.usage.cost_usd), f"{r.duration_s:.0f}", r.commit[:8])
+ return t
+
+
+def print_record_summary(record: RunRecord, ws_root: Path | None = None) -> None:
+ spec = record.spec
+ status_col = {"passed": "green", "failed": "red", "budget": "yellow", "plateau": "yellow"}.get(record.status.value, "cyan")
+ lines = [
+ f"[bold]{spec.prompt}[/bold]",
+ f"track={spec.track.value} language={spec.language.value} generator={spec.backends.generator}",
+ f"status=[{status_col}]{record.status.value}[/{status_col}] baseline={fmt_score(record.baseline_score)} "
+ f"best={fmt_score(record.final_score)} (round {record.best_round}) rounds={len(record.rounds)} "
+ f"cost={fmt_usd(record.total_usage.cost_usd)}",
+ ]
+ if record.error:
+ lines.append(f"[red]error: {record.error}[/red]")
+ if ws_root is not None:
+ lines.append(f"workspace: {ws_root}")
+ best = next((r for r in record.rounds if r.index == record.best_round), None)
+ if best is not None and best.renders is not None and best.renders.contact_sheet:
+ lines.append(f"sheet: {best.renders.contact_sheet}")
+ glb = ws_root / "artifacts" / "object.glb"
+ if glb.is_file():
+ lines.append(f"glb: {glb}")
+ console.print(Panel("\n".join(lines), title="run", expand=False))
+ if record.rounds:
+ console.print(rounds_table(record))
+
+
+def kv_table(title: str, rows: dict[str, Any]) -> Table:
+ t = Table(title=title, show_header=False)
+ t.add_column("key", style="bold")
+ t.add_column("value")
+ for k, v in rows.items():
+ t.add_row(str(k), str(v))
+ return t
+
+
+def print_observation(obs: Any, *, as_json: bool) -> None:
+ if as_json:
+ console.print_json(obs.model_dump_json())
+ return
+ style = "green" if obs.ok else "red"
+ console.print(Panel(obs.text, title=f"[{style}]{'ok' if obs.ok else 'error'}[/{style}] ({obs.duration_ms} ms)", expand=False))
+ if obs.numbers:
+ console.print(kv_table("numbers", obs.numbers))
+ for img in obs.images:
+ console.print(f"image: {img}")
+
+
+def doctor_table(rows: list[tuple[str, str, str]]) -> Table:
+ """rows: (check, status OK|WARN|FAIL, detail)."""
+ t = Table(title="c3v doctor")
+ t.add_column("check", style="bold")
+ t.add_column("status")
+ t.add_column("detail")
+ col = {"OK": "green", "WARN": "yellow", "FAIL": "red", "SKIP": "dim"}
+ for name, status, detail in rows:
+ t.add_row(name, f"[{col.get(status, 'white')}]{status}[/{col.get(status, 'white')}]", detail)
+ return t
diff --git a/harness/codeverse/cli/bench_cmd.py b/harness/codeverse/cli/bench_cmd.py
new file mode 100644
index 00000000..f0dd240f
--- /dev/null
+++ b/harness/codeverse/cli/bench_cmd.py
@@ -0,0 +1,61 @@
+"""``c3v bench run <battery.yaml> | report <dir>``."""
+
+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, ok
+
+bench_app = typer.Typer(no_args_is_help=True)
+
+
+@bench_app.command("run")
+def run_cmd(
+ battery: Annotated[Path, typer.Argument(help="bench/prompts/<name>.yaml")],
+ out: Annotated[Path | None, typer.Option("--out", help="default bench/out/<battery name>")] = None,
+ generator: Annotated[str | None, typer.Option("--generator")] = None,
+ planner: Annotated[str | None, typer.Option("--planner")] = None,
+ judge: Annotated[str | None, typer.Option("--judge", help="fixed judge model for the whole battery")] = None,
+ parallel: Annotated[int, typer.Option("--parallel", min=1)] = 4,
+ rounds: Annotated[int, typer.Option("--rounds", min=0)] = 4,
+ max_usd: Annotated[float, typer.Option("--max-usd")] = 5.0,
+ limit: Annotated[int | None, typer.Option("--limit")] = None,
+ ids: Annotated[list[str] | None, typer.Option("--id", help="only these prompt ids")] = None,
+ tiers: Annotated[list[str] | None, typer.Option("--tier")] = None,
+ no_resume: Annotated[bool, typer.Option("--no-resume")] = False,
+ report: Annotated[bool, typer.Option("--report/--no-report")] = True,
+) -> None:
+ """Run every prompt of a battery through its track (N parallel workers); resumable."""
+ if not battery.is_file():
+ raise C.CliError(f"battery not found: {battery}")
+ b = C.import_bench()
+ run_bench = C.lazy("bench.run_bench")
+ opts = run_bench.BenchOptions(generator=generator, planner=planner, judge=judge, rounds=rounds, max_usd=max_usd,
+ parallel=parallel, limit=limit, ids=ids or [], tiers=tiers or [], resume=not no_resume)
+ out_dir = out or (C.REPO_ROOT / "bench" / "out" / battery.stem)
+ console.print(f"battery={battery} out={out_dir} generator={generator or 'default'} judge={judge or 'default'}")
+
+ def _on(res) -> None:
+ console.print(f" [{res.status}] {res.id}: baseline={res.score_baseline} final={res.score_final} "
+ f"rounds={res.rounds} ${res.cost_usd:.2f} {res.minutes:.1f}min" + (f" [red]{res.errors[:80]}[/red]" if res.errors else ""))
+
+ results = run_bench.run_battery(battery, out_dir, opts, on_result=_on)
+ ok(f"{len(results)} results → {out_dir / 'results.csv'}")
+ if report:
+ rep = C.lazy("bench.report").build_report(out_dir)
+ console.print(rep.markdown)
+ ok(f"report → {out_dir / 'report.md'} / report.html")
+ del b
+
+
+@bench_app.command("report")
+def report_cmd(out_dir: Annotated[Path, typer.Argument()]) -> None:
+ """Aggregate results.jsonl → report.md + report.html (gallery of contact sheets)."""
+ C.import_bench()
+ rep = C.lazy("bench.report").build_report(out_dir)
+ console.print(rep.markdown)
+ ok(f"report → {out_dir / 'report.md'} / report.html")
diff --git a/harness/codeverse/cli/doctor.py b/harness/codeverse/cli/doctor.py
new file mode 100644
index 00000000..0713d856
--- /dev/null
+++ b/harness/codeverse/cli/doctor.py
@@ -0,0 +1,203 @@
+"""``c3v doctor`` — environment checks (deps, Blender, node/three/chrome, keys, CLIs, MCP)."""
+
+from __future__ import annotations
+
+import importlib
+import json
+import shutil
+import subprocess
+from pathlib import Path
+from typing import Annotated
+
+import typer
+
+from codeverse.cli._fmt import console, doctor_table
+from codeverse.config import get_settings
+
+doctor_app = typer.Typer(invoke_without_command=True)
+
+Row = tuple[str, str, str]
+_PY_DEPS = ("pydantic", "pydantic_settings", "typer", "rich", "jinja2", "yaml", "numpy", "trimesh", "PIL", "pyarrow",
+ "scipy", "shapely", "networkx", "manifold3d", "playwright", "google.genai", "anthropic", "openai",
+ "yourdfpy", "mcp")
+_CLI_TIMEOUT = 25
+
+
+def _ver(cmd: list[str], timeout: int = _CLI_TIMEOUT) -> tuple[bool, str]:
+ if not shutil.which(cmd[0]) and not Path(cmd[0]).is_file():
+ return False, "not found"
+ try:
+ p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
+ except subprocess.TimeoutExpired:
+ return False, f"timed out after {timeout}s"
+ except OSError as e:
+ return False, str(e)
+ out = (p.stdout or p.stderr).strip().splitlines()
+ first = out[0].strip() if out else ""
+ return p.returncode == 0, first[:100] or f"exit {p.returncode}"
+
+
+def check_python_deps() -> list[Row]:
+ missing, present = [], []
+ for mod in _PY_DEPS:
+ try:
+ importlib.import_module(mod)
+ present.append(mod)
+ except Exception: # ImportError or a broken native lib
+ missing.append(mod)
+ import sys
+
+ rows: list[Row] = [("python", "OK", sys.version.split()[0] + f" ({sys.executable})")]
+ status = "OK" if not missing else ("WARN" if set(missing) <= {"manifold3d", "yourdfpy", "mcp", "shapely"} else "FAIL")
+ rows.append(("python deps", status, f"{len(present)}/{len(_PY_DEPS)} importable" + (f"; missing: {', '.join(missing)}" if missing else "")))
+ return rows
+
+
+def check_blender() -> list[Row]:
+ s = get_settings()
+ b = s.resolve_blender()
+ if not b:
+ return [("blender", "FAIL", "no binary (set C3V_BINARIES__BLENDER or put blender-5.0 on PATH)")]
+ okk, v = _ver([b, "--version"], timeout=60)
+ return [("blender", "OK" if okk else "FAIL", f"{v} @ {b}")]
+
+
+def check_node() -> list[Row]:
+ s = get_settings()
+ rows: list[Row] = []
+ okk, v = _ver([s.binaries.node, "--version"])
+ rows.append(("node", "OK" if okk else "FAIL", v))
+ rj = s.runtime_js_dir()
+ three = rj / "node_modules" / "three" / "package.json"
+ pup = rj / "node_modules" / "puppeteer" / "package.json"
+ if three.is_file():
+ rows.append(("three", "OK", json.loads(three.read_text()).get("version", "?") + f" ({rj / 'node_modules'})"))
+ else:
+ rows.append(("three", "FAIL", f"runtime_js/node_modules/three missing — run `npm install` in {rj}"))
+ if pup.is_file():
+ cache = Path.home() / ".cache" / "puppeteer"
+ chrome = any(cache.rglob("chrome")) if cache.is_dir() else False
+ rows.append(("puppeteer", "OK" if chrome else "WARN",
+ f"v{json.loads(pup.read_text()).get('version', '?')}; chrome cache {'found' if chrome else 'missing'} ({cache})"))
+ else:
+ rows.append(("puppeteer", "FAIL", "not installed in runtime_js"))
+ return rows
+
+
+_PROBE_JS = (
+ "const {launchBrowser}=require(process.argv[1]);"
+ "launchBrowser({gpu:'auto'}).then(async r=>{console.log(JSON.stringify({gpu:r.gpu,renderer:r.renderer}));"
+ "await r.browser.close();process.exit(0)}).catch(e=>{console.log(JSON.stringify({error:String(e&&e.message||e)}));process.exit(1)})"
+)
+
+
+def check_gpu_probe(timeout_s: int = 120) -> list[Row]:
+ """Launch headless Chrome through runtime_js/gpu_launch.cjs and report the WebGL renderer."""
+ import os
+ import signal
+
+ s = get_settings()
+ rj = s.runtime_js_dir()
+ launcher = rj / "gpu_launch.cjs"
+ if not launcher.is_file():
+ return [("chrome webgl", "SKIP", f"{launcher} missing (spatial render package not installed yet)")]
+ cmd = [s.binaries.node, "-e", _PROBE_JS, str(launcher)]
+ try:
+ proc = subprocess.Popen(cmd, cwd=rj, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ start_new_session=True)
+ out, errs = proc.communicate(timeout=timeout_s)
+ except subprocess.TimeoutExpired:
+ os.killpg(proc.pid, signal.SIGKILL)
+ return [("chrome webgl", "FAIL", f"probe timed out after {timeout_s}s")]
+ except OSError as e:
+ return [("chrome webgl", "FAIL", str(e))]
+ line = next((ln for ln in reversed(out.strip().splitlines()) if ln.startswith("{")), "")
+ try:
+ res = json.loads(line) if line else {}
+ except ValueError:
+ res = {}
+ if "error" in res or proc.returncode != 0:
+ detail = str(res.get("error") or (errs.strip().splitlines() or ["unknown error"])[-1])
+ return [("chrome webgl", "FAIL", detail[:160])]
+ renderer = str(res.get("renderer", "?"))
+ return [("chrome webgl", "OK" if res.get("gpu") else "WARN",
+ f"{'GPU' if res.get('gpu') else 'CPU/software'}: {renderer[:120]}")]
+
+
+def check_keys(live: bool) -> list[Row]:
+ s = get_settings()
+ n = len(s.gemini_api_keys)
+ rows: list[Row] = [("gemini keys", "OK" if n else "FAIL", f"{n} key(s)")]
+ rows.append(("anthropic key", "OK" if s.anthropic_api_key else "WARN", "set" if s.anthropic_api_key else "not set (anthropic:* backends unavailable)"))
+ rows.append(("openai key", "OK" if s.openai_api_key else "WARN", "set" if s.openai_api_key else "not set (openai:* backends unavailable)"))
+ if live and n:
+ try:
+ from codeverse.contracts.chat import ChatMessage, ChatRequest
+ from codeverse.models import get_chat_model
+
+ m = get_chat_model("gemini:gemini-3.7-flash")
+ r = m.generate(ChatRequest(messages=[ChatMessage.user("Reply with the single word: pong")],
+ temperature=0.0, max_output_tokens=16, thinking="off", label="doctor"))
+ rows.append(("gemini live call", "OK" if "pong" in r.text.lower() else "WARN",
+ f"{r.text.strip()[:40]!r} cost=${r.usage.cost_usd:.5f}"))
+ except Exception as e:
+ rows.append(("gemini live call", "FAIL", f"{type(e).__name__}: {str(e)[:120]}"))
+ return rows
+
+
+def check_clis() -> list[Row]:
+ s = get_settings()
+ rows: list[Row] = []
+ for name, binary in (("gemini-cli", s.binaries.gemini_cli), ("claude", s.binaries.claude_cli),
+ ("codex", s.binaries.codex_cli), ("agy", s.binaries.agy_cli)):
+ okk, v = _ver([binary, "--version"])
+ rows.append((name, "OK" if okk else "WARN", v if okk else f"{v} (backend {name} unavailable)"))
+ okk, v = _ver(["git", "--version"])
+ rows.append(("git", "OK" if okk else "FAIL", v))
+ okk, v = _ver([s.binaries.ffmpeg, "-version"])
+ rows.append(("ffmpeg", "OK" if okk else "WARN", v if okk else "not found (turntable mp4 disabled)"))
+ return rows
+
+
+def check_mcp() -> list[Row]:
+ try:
+ importlib.import_module("mcp")
+ except ImportError:
+ return [("mcp", "WARN", "python package `mcp` missing (MCP server for CLIs unavailable)")]
+ try:
+ importlib.import_module("codeverse.spatial.mcp_server")
+ return [("mcp", "OK", "mcp + codeverse.spatial.mcp_server importable")]
+ except ImportError as e:
+ return [("mcp", "WARN", f"codeverse.spatial.mcp_server not importable ({e})")]
+
+
+def run_doctor(*, live: bool = False, gpu: bool = True) -> list[Row]:
+ rows: list[Row] = []
+ rows += check_python_deps()
+ rows += check_blender()
+ rows += check_node()
+ if gpu:
+ rows += check_gpu_probe()
+ rows += check_keys(live)
+ rows += check_clis()
+ rows += check_mcp()
+ return rows
+
+
+@doctor_app.callback(invoke_without_command=True)
+def doctor(
+ ctx: typer.Context,
+ live: Annotated[bool, typer.Option("--live", help="make one tiny Gemini call")] = False,
+ gpu: Annotated[bool, typer.Option("--gpu/--no-gpu", help="probe headless Chrome WebGL")] = True,
+ as_json: Annotated[bool, typer.Option("--json")] = False,
+) -> None:
+ """Check python deps, Blender, node/three/puppeteer, keys, CLIs and MCP."""
+ if ctx.invoked_subcommand:
+ return
+ rows = run_doctor(live=live, gpu=gpu)
+ if as_json:
+ console.print_json(json.dumps([{"check": c, "status": s, "detail": d} for c, s, d in rows]))
+ else:
+ console.print(doctor_table(rows))
+ if any(s == "FAIL" for _, s, _ in rows):
+ raise typer.Exit(code=1)
diff --git a/harness/codeverse/cli/flywheel_cmd.py b/harness/codeverse/cli/flywheel_cmd.py
new file mode 100644
index 00000000..f0c415f7
--- /dev/null
+++ b/harness/codeverse/cli/flywheel_cmd.py
@@ -0,0 +1,146 @@
+"""``c3v flywheel export | pairs | caption | index | dedupe``."""
+
+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
+
+flywheel_app = typer.Typer(no_args_is_help=True)
+
+
+@flywheel_app.command("export")
+def export_cmd(
+ runs_dir: Annotated[Path, typer.Argument(help="runs root")],
+ out_dir: Annotated[Path, typer.Argument(help="dataset folder")],
+ min_score: Annotated[float | None, typer.Option("--min-score")] = None,
+ only_passed: Annotated[bool, typer.Option("--only-passed")] = False,
+ pack: Annotated[bool, typer.Option("--pack", help="also pack samples-NNN.tar + byte-range locators")] = False,
+ tar_prefix: Annotated[str, typer.Option("--tar-prefix", help="repo-root-relative prefix for the tar column")] = "",
+ include_unbuilt: Annotated[bool, typer.Option("--include-unbuilt", help="also export runs whose best round never built")] = False,
+) -> None:
+ """Export runs → sample folders + metadata.parquet (+ optional plain tars)."""
+ from codeverse.flywheel.export import export_samples
+
+ rep = export_samples(runs_dir, out_dir, min_score=min_score, only_passed=only_passed, include_unbuilt=include_unbuilt)
+ console.print(kv_table("export", {"runs": rep.n_runs, "exported": rep.n_exported, "indexed": rep.n_indexed,
+ "skipped": len(rep.skipped), "parquet": rep.parquet}))
+ for d, why in list(rep.skipped.items())[:20]:
+ warn(f"skip {Path(d).name}: {why}")
+ if pack:
+ from codeverse.flywheel.pack import pack_samples, verify_locators
+
+ prep = pack_samples(out_dir, tar_prefix=tar_prefix)
+ n = verify_locators(out_dir)
+ ok(f"packed {prep.n_samples} samples into {prep.tars}; verified {n} locators")
+
+
+@flywheel_app.command("pairs")
+def pairs_cmd(
+ runs_dir: Annotated[Path, typer.Argument()],
+ out_jsonl: Annotated[Path, typer.Argument()],
+ min_delta: Annotated[float, typer.Option("--min-delta")] = 0.05,
+) -> None:
+ """Preference / repair / cross-backend pairs → JSONL."""
+ from codeverse.flywheel.pairs import build_pairs
+
+ n = build_pairs(runs_dir, out_jsonl, min_delta=min_delta)
+ ok(f"{n} pairs → {out_jsonl}")
+
+
+@flywheel_app.command("caption")
+def caption_cmd(
+ target: Annotated[str, typer.Argument(help="run slug/dir, or a runs root with --all")],
+ model: Annotated[str, typer.Option("--model")] = "gemini:gemini-3.7-flash",
+ all_runs: Annotated[bool, typer.Option("--all", help="caption every un-captioned run under target")] = False,
+ force: Annotated[bool, typer.Option("--force", help="re-caption even if captions exist")] = False,
+ runs_dir: Annotated[Path | None, typer.Option("--runs-dir")] = None,
+) -> None:
+ """Caption run(s): {detailed, instruction, factory} via a chat model."""
+ from codeverse.flywheel.captions import CaptionError, caption_sample
+ from codeverse.flywheel.record import iter_runs, load_record
+
+ if all_runs:
+ targets = [(ws, rec) for ws, rec in iter_runs(target, on_error=lambda d, e: warn(f"skip {d.name}: {e}"))]
+ else:
+ ws = C.open_workspace(target, runs_dir)
+ targets = [(ws, load_record(ws))]
+ done = skipped = failed = 0
+ for ws, rec in targets:
+ if not force and (rec.extra.get("captions") or {}).get("detailed"):
+ skipped += 1
+ continue
+ try:
+ caps = caption_sample(ws, rec, model)
+ except CaptionError as e:
+ failed += 1
+ warn(str(e))
+ continue
+ done += 1
+ console.print(f"[bold]{ws.root.name}[/bold]: {caps.instruction}")
+ ok(f"captioned {done}, skipped {skipped} (already), failed {failed}")
+ if failed and not done:
+ raise typer.Exit(code=1)
+
+
+@flywheel_app.command("index")
+def index_cmd(
+ runs_dir: Annotated[Path, typer.Argument()],
+ out_sqlite: Annotated[Path, typer.Argument()] = Path("runs_index.sqlite"),
+ show: Annotated[bool, typer.Option("--summary/--no-summary")] = True,
+) -> None:
+ """Build the SQLite index (runs / rounds / usage) and print a summary."""
+ from codeverse.flywheel.index import build_index, summary
+
+ n = build_index(runs_dir, out_sqlite)
+ ok(f"indexed {n} runs → {out_sqlite}")
+ if show and n:
+ from rich.table import Table
+
+ t = Table(title="summary")
+ for col in ("track", "language", "generator", "n", "pass", "baseline", "final", "Δ", "cost"):
+ t.add_column(col)
+ for r in summary(out_sqlite):
+ t.add_row(r["track"], r["language"], r["generator"], str(r["n"]),
+ f"{(r['pass_rate'] or 0):.2f}", f"{(r['baseline_mean'] or 0):.3f}", f"{(r['final_mean'] or 0):.3f}",
+ f"{(r['delta_mean'] or 0):+.3f}", f"${(r['cost_usd'] or 0):.2f}")
+ console.print(t)
+
+
+@flywheel_app.command("dedupe")
+def dedupe_cmd(
+ dataset_dir: Annotated[Path, typer.Argument(help="exported dataset folder")],
+ mesh: Annotated[bool, typer.Option("--mesh/--no-mesh", help="also fingerprint renders/object.glb")] = True,
+ threshold: Annotated[float, typer.Option("--threshold")] = 0.9,
+) -> None:
+ """Report near-duplicate sample groups (code fingerprint + mesh voxel Jaccard)."""
+ import json
+
+ from codeverse.flywheel.dedupe import (
+ DedupeItem,
+ code_fingerprint,
+ mesh_fingerprint,
+ near_duplicates,
+ )
+
+ items = []
+ for meta_path in sorted(dataset_dir.rglob("meta.json")):
+ sdir = meta_path.parent
+ meta = json.loads(meta_path.read_text())
+ files = {p.relative_to(sdir).as_posix(): p.read_bytes() for p in (sdir / "src").rglob("*") if p.is_file()}
+ fp = None
+ glb = sdir / "renders" / "object.glb"
+ if mesh and glb.is_file():
+ try:
+ fp = mesh_fingerprint(glb)
+ except Exception as e: # unreadable glb → code-only
+ warn(f"{meta['key']}: mesh fingerprint failed: {e}")
+ items.append(DedupeItem(id=meta["id"], code_fp=code_fingerprint(files), mesh_fp=fp))
+ groups = near_duplicates(items, mesh_threshold=threshold)
+ console.print(f"{len(items)} samples, {len(groups)} duplicate groups")
+ for g in groups:
+ console.print(" " + " == ".join(g))
diff --git a/harness/codeverse/cli/main.py b/harness/codeverse/cli/main.py
new file mode 100644
index 00000000..bbebf2c3
--- /dev/null
+++ b/harness/codeverse/cli/main.py
@@ -0,0 +1,231 @@
+"""``c3v`` — the 3dcodeverse command line.
+
+Thin by design: every command builds typed inputs and calls into the harness
+packages lazily (``cli/_common.lazy``), so the CLI imports and prints help
+even while some sub-packages are incomplete.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+from typing import Annotated
+
+import typer
+
+from codeverse import __version__
+from codeverse.cli import _common as C
+from codeverse.cli._fmt import console, err_console, kv_table, ok, print_record_summary, warn
+from codeverse.cli.bench_cmd import bench_app
+from codeverse.cli.doctor import doctor_app
+from codeverse.cli.flywheel_cmd import flywheel_app
+from codeverse.cli.tools_cmd import tools
+from codeverse.contracts.common import Backends, Budget, Language, Track
+from codeverse.contracts.spec import Constraints, ReferenceImage, Spec
+
+app = typer.Typer(name="c3v", 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(bench_app, name="bench", help="Prompt batteries: run + report.")
+app.add_typer(doctor_app, name="doctor", help="Environment checks.")
+app.command("tools", help="List spatial tools or run one: `c3v tools list` | `c3v tools <name> --json '{...}' --workspace ws`.")(tools)
+
+RunsDirOpt = Annotated[Path | None, typer.Option("--runs-dir", help="runs root (default: settings.runs_dir)")]
+
+
[email protected](invoke_without_command=True)
+def _root(ctx: typer.Context, version: Annotated[bool, typer.Option("--version", is_eager=True)] = False) -> None:
+ if version:
+ console.print(f"c3v {__version__}")
+ raise typer.Exit()
+ if ctx.invoked_subcommand is None:
+ console.print(ctx.get_help())
+ raise typer.Exit()
+
+
+# --------------------------------------------------------------------------- make / resume
+def make(
+ prompt: Annotated[str, typer.Argument(help="what to build")],
+ track: Annotated[Track, typer.Option("--track")] = Track.STATIC_OBJECT,
+ language: Annotated[Language, typer.Option("--language")] = Language.BLENDER,
+ generator: Annotated[str | None, typer.Option(help="api-agent:gemini:gemini-3.7-flash | gemini-cli:... | claude-code:... | codex:... | agy:...")] = None,
+ planner: Annotated[str | None, typer.Option()] = None,
+ judge: Annotated[str | None, typer.Option()] = None,
+ captioner: Annotated[str | None, typer.Option()] = None,
+ image: Annotated[list[Path] | None, typer.Option("--image", help="reference image(s)")] = None,
+ rounds: Annotated[int, typer.Option("--rounds", min=0)] = 4,
+ max_usd: Annotated[float, typer.Option("--max-usd")] = 5.0,
+ max_minutes: Annotated[float, typer.Option("--max-minutes")] = 60.0,
+ slug: Annotated[str | None, typer.Option("--slug")] = None,
+ runs_dir: RunsDirOpt = None,
+ dim: Annotated[list[str] | None, typer.Option("--dim", help="width=1.2 (meters); repeatable")] = None,
+ must: Annotated[list[str] | None, typer.Option("--must", help="hard requirement; repeatable")] = None,
+ must_not: Annotated[list[str] | None, typer.Option("--must-not")] = None,
+ style: Annotated[str, typer.Option("--style")] = "",
+ tag: Annotated[list[str] | None, typer.Option("--tag")] = None,
+ seed: Annotated[int, typer.Option("--seed")] = 0,
+ force: Annotated[bool, typer.Option("--force", help="overwrite an existing run dir")] = False,
+ no_run: Annotated[bool, typer.Option("--no-run", help="only create the workspace + spec.json")] = False,
+) -> None:
+ """Create a run (workspace + spec.json) and execute the track pipeline."""
+ image, dim, must, must_not, tag = image or [], dim or [], must or [], must_not or [], tag or []
+ for p in image:
+ if not p.is_file():
+ raise C.CliError(f"reference image not found: {p}")
+ run_slug = C.make_slug(prompt, track.value, language.value, slug)
+ ws = C.create_workspace(C.runs_root(runs_dir) / run_slug, force=force)
+ backends = Backends(**{k: v for k, v in {"generator": generator, "planner": planner, "judge": judge,
+ "captioner": captioner}.items() if v})
+ try:
+ spec = Spec(
+ id=run_slug, track=track, language=language, prompt=prompt,
+ references=[ReferenceImage(path=str(p.resolve())) for p in image],
+ constraints=Constraints(dimensions_m=C.parse_kv_floats(dim, "--dim") or None, must_have=must,
+ must_not=must_not, style=style),
+ budget=Budget(max_rounds=rounds, max_usd=max_usd, max_minutes=max_minutes),
+ backends=backends, seed=seed, tags=tag,
+ )
+ except ValueError as e:
+ raise C.CliError(str(e)) from e
+ ws.write_json(ws.spec_path, spec)
+ ws.commit("spec")
+ console.print(kv_table("run", {"slug": run_slug, "workspace": ws.root, "track": track.value,
+ "language": language.value, "generator": backends.generator}))
+ if no_run:
+ ok(f"spec written: {ws.spec_path} (not run; `c3v resume {run_slug}` to start)")
+ return
+ _run_track(spec, ws, resume=False)
+
+
+def _run_track(spec: Spec, ws, *, resume: bool) -> None:
+ get_track = C.lazy("codeverse.tracks", "get_track")
+ try:
+ record = get_track(spec.track).run(spec, ws, resume=resume)
+ except KeyboardInterrupt:
+ raise C.CliError(f"interrupted; resume with `c3v resume {ws.root.name}`", code=130) from None
+ except Exception as e: # the track failed outside its own error handling
+ err_console.print_exception(max_frames=8)
+ raise C.CliError(f"run failed: {type(e).__name__}: {e} (workspace {ws.root}; see events.jsonl)") from e
+ print_record_summary(record, ws.root)
+ if record.status.value == "failed":
+ raise typer.Exit(code=1)
+
+
+def resume(slug: str, runs_dir: RunsDirOpt = None) -> None:
+ """Resume an interrupted / partial run (or start a `--no-run` one)."""
+ ws = C.open_workspace(slug, runs_dir)
+ _run_track(C.load_spec(ws), ws, resume=True)
+
+
+# --------------------------------------------------------------------------- status
+def status(slug: str, runs_dir: RunsDirOpt = None, events: Annotated[int, typer.Option("--events", help="tail N events")] = 8) -> None:
+ """Show spec / run_state / record / recent events of a run."""
+ from codeverse.events import EventLog
+ from codeverse.flywheel.record import RecordError, load_record
+
+ ws = C.open_workspace(slug, runs_dir)
+ spec = C.load_spec(ws)
+ rows = {"workspace": ws.root, "track": spec.track.value, "language": spec.language.value,
+ "generator": spec.backends.generator, "judge": spec.backends.judge, "prompt": spec.prompt}
+ if ws.state_path.is_file():
+ try:
+ state = json.loads(ws.state_path.read_text())
+ rows["run_state"] = ", ".join(f"{k}={v}" for k, v in state.items() if not isinstance(v, (dict, list)))[:300]
+ except ValueError:
+ rows["run_state"] = "(unreadable)"
+ console.print(kv_table("status", rows))
+ try:
+ print_record_summary(load_record(ws), ws.root)
+ except RecordError as e:
+ warn(f"no record yet ({e})")
+ evs = EventLog(ws.events_path).read()
+ if evs:
+ console.print(f"[dim]last {min(events, len(evs))} of {len(evs)} events:[/dim]")
+ for ev in evs[-events:]:
+ extra = {k: v for k, v in ev.items() if k not in ("t", "kind")}
+ console.print(f" {ev.get('kind')} {json.dumps(extra, default=str)[:160]}")
+
+
+# --------------------------------------------------------------------------- render / judge
+def render(
+ slug: str,
+ round_index: Annotated[int | None, typer.Option("--round")] = None,
+ mode: Annotated[str, typer.Option("--mode", help="shaded | wire | normals | clay | silhouette")] = "shaded",
+ out: Annotated[Path | None, typer.Option("--out")] = None,
+ runs_dir: RunsDirOpt = None,
+) -> None:
+ """Render the current artifact (object.glb or the scene) with the canonical rig."""
+ ws = C.open_workspace(slug, runs_dir)
+ spec = C.load_spec(ws)
+ idx = round_index if round_index is not None else _latest_round(ws)
+ out_dir = out or ws.renders_dir(idx) / ("cli" if mode == "shaded" else f"cli_{mode}")
+ if spec.track is Track.SCENE:
+ render_scene = C.lazy("codeverse.spatial.render", "render_scene")
+ rs = render_scene(ws, out_dir, cameras=None)
+ else:
+ glb = ws.artifacts / "object.glb"
+ if not glb.is_file():
+ raise C.CliError(f"no artifact to render: {glb} (run a build first)")
+ render_glb = C.lazy("codeverse.spatial.render", "render_glb")
+ rs = render_glb(glb, out_dir, mode=mode)
+ console.print(kv_table("renders", {"views": len(rs.views), "sheet": rs.contact_sheet, "dir": out_dir,
+ "renderer": rs.renderer, "ms": rs.duration_ms}))
+
+
+def judge(
+ slug: str,
+ round_index: Annotated[int | None, typer.Option("--round")] = None,
+ rubric: Annotated[str | None, typer.Option("--rubric")] = None,
+ model: Annotated[str | None, typer.Option("--model", help="judge chat model id")] = None,
+ n: Annotated[int, typer.Option("--n", min=1)] = 1,
+ runs_dir: RunsDirOpt = None,
+) -> None:
+ """Re-judge a round's renders (writes artifacts/judge/rNN_cli.json)."""
+ from codeverse.flywheel.record import load_record
+
+ ws = C.open_workspace(slug, runs_dir)
+ rec = load_record(ws)
+ idx = round_index if round_index is not None else (rec.best_round if rec.best_round is not None else _latest_round(ws))
+ rnd = next((r for r in rec.rounds if r.index == idx), None)
+ if rnd is None or rnd.renders is None:
+ raise C.CliError(f"round {idx} has no renders in record.json")
+ JudgeInput = C.lazy("codeverse.judges.base", "JudgeInput")
+ VlmJudge = C.lazy("codeverse.judges.vlm_judge", "VlmJudge")
+ rubric_name = rubric or {Track.STATIC_OBJECT: "static_object_v1", Track.ARTICULATED_OBJECT: "articulated_v1",
+ Track.SCENE: "scene_v1"}[rec.spec.track]
+ acceptance = list(getattr(rec.plan, "acceptance", []) or [])
+ inp = JudgeInput(spec=rec.spec, renders=rnd.renders, measurement=rnd.measurement, gates=rnd.gates,
+ acceptance=acceptance, round_index=idx)
+ verdict = VlmJudge(rubric=rubric_name, model_id=model or rec.spec.backends.judge, n_samples=n).judge(inp)
+ ws.write_json(ws.judge_path(idx, "_cli"), verdict)
+ console.print(kv_table("judgment", {"rubric": verdict.rubric, "overall": f"{verdict.overall:.3f}",
+ "passed": verdict.passed, "std": verdict.score_std, "summary": verdict.summary,
+ "cost": f"${verdict.usage.cost_usd:.4f}"}))
+ for it in verdict.improvement_plan:
+ console.print(f" [{it.priority}] {it.target}: {it.instruction}")
+
+
+def _latest_round(ws) -> int:
+ rdir = ws.artifacts / "renders"
+ idxs = sorted(int(p.name[1:]) for p in rdir.glob("r[0-9][0-9]") if p.is_dir()) if rdir.is_dir() else []
+ return idxs[-1] if idxs else 0
+
+
+# --------------------------------------------------------------------------- mcp
+def mcp(workspace: Annotated[Path, typer.Option("--workspace")]) -> None:
+ """Serve the spatial tools over stdio MCP (exec `python -m codeverse.spatial.mcp_server`)."""
+ if not workspace.is_dir():
+ raise C.CliError(f"workspace not found: {workspace}")
+ os.execvp(sys.executable, [sys.executable, "-m", "codeverse.spatial.mcp_server", "--workspace", str(workspace)])
+
+
+if __name__ == "__main__": # pragma: no cover
+ app()
diff --git a/harness/codeverse/cli/tools_cmd.py b/harness/codeverse/cli/tools_cmd.py
new file mode 100644
index 00000000..0f2dd801
--- /dev/null
+++ b/harness/codeverse/cli/tools_cmd.py
@@ -0,0 +1,57 @@
+"""``c3v tools`` — list registry tools or run one (prints an Observation).
+
+This is also the fallback path for agentic CLIs without MCP support: the
+prompt tells them to shell out to ``c3v tools <name> --json '{...}' --workspace .``.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Annotated
+
+import typer
+
+from codeverse.cli import _common as C
+from codeverse.cli._fmt import console, print_observation
+
+
+def tools(
+ name: Annotated[str, typer.Argument(help="'list' or a tool name")] = "list",
+ args_json: Annotated[str, typer.Option("--json", help="arguments object as JSON")] = "{}",
+ workspace: Annotated[Path | None, typer.Option("--workspace")] = None,
+ round_index: Annotated[int, typer.Option("--round")] = 0,
+ as_json: Annotated[bool, typer.Option("--json-out", help="print the Observation as JSON")] = False,
+ cards: Annotated[bool, typer.Option("--cards", help="(list) print prompt cards instead of a table")] = False,
+) -> None:
+ registry = C.lazy("codeverse.spatial.registry")
+ if name == "list":
+ defs = registry.list_tools()
+ if cards:
+ console.print(registry.tool_cards())
+ return
+ from rich.table import Table
+
+ t = Table(title="spatial tools")
+ for col in ("name", "cost", "tracks", "languages", "description"):
+ t.add_column(col)
+ for d in defs:
+ t.add_row(d.name, d.cost_hint, ",".join(d.tracks) or "*", ",".join(d.languages) or "*", d.description)
+ console.print(t)
+ return
+ try:
+ tdef = registry.get_tool(name)
+ except KeyError as e:
+ raise C.CliError(str(e)) from e
+ try:
+ arguments = json.loads(args_json)
+ except ValueError as e:
+ raise C.CliError(f"--json is not valid JSON: {e}") from e
+ ws_root = workspace or Path.cwd()
+ ws = C.open_workspace(str(ws_root))
+ spec = C.load_spec(ws)
+ ctx = registry.ToolContext(workspace=ws, round_index=round_index, language=spec.language.value, track=spec.track.value)
+ obs = tdef.call(ctx, arguments)
+ print_observation(obs, as_json=as_json)
+ if not obs.ok:
+ raise typer.Exit(code=1)
diff --git a/harness/codeverse/config.py b/harness/codeverse/config.py
new file mode 100644
index 00000000..14b8f6fb
--- /dev/null
+++ b/harness/codeverse/config.py
@@ -0,0 +1,131 @@
+"""Harness settings: keys, binaries, directories, defaults.
+
+Resolution order (later wins): built-in defaults < ``~/.config/codeverse/config.yaml``
+< ``./codeverse.yaml`` < environment variables (``C3V_*``). Secrets are never
+written to run records.
+
+Gemini keys: ``GEMINI_API_KEYS`` (csv) or ``GEMINI_API_KEY`` or the owner's
+``~/.config/astra3d/gemini_keys.env`` file (read-only compatibility).
+"""
+
+from __future__ import annotations
+
+import os
+import re
+import shutil
+from functools import lru_cache
+from pathlib import Path
+
+import yaml
+from pydantic import BaseModel, Field
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+_LEGACY_KEYS_FILE = Path.home() / ".config" / "astra3d" / "gemini_keys.env"
+_USER_CONFIG = Path.home() / ".config" / "codeverse" / "config.yaml"
+
+
+class Binaries(BaseModel):
+ blender: str = Field(default="", description="path to a Blender 4.2+/5.x binary (headless capable)")
+ node: str = "node"
+ gemini_cli: str = "gemini"
+ claude_cli: str = "claude"
+ codex_cli: str = "codex"
+ agy_cli: str = "agy"
+ ffmpeg: str = "ffmpeg"
+
+
+class Render(BaseModel):
+ width: int = 768
+ height: int = 768
+ scene_width: int = 1024
+ scene_height: int = 576
+ gpu: str = Field(default="auto", description="auto | on | off (headless Chrome WebGL backend)")
+ sheet_cols: int = 4
+ sheet_tile: int = 384
+
+
+class Limits(BaseModel):
+ build_timeout_s: int = 300
+ render_timeout_s: int = 300
+ agent_timeout_s: int = 1800
+ bpy_rlimit_gb: int = 12
+ max_parallel_agents: int = 6
+ max_parallel_builds: int = 3
+
+
+class Settings(BaseSettings):
+ model_config = SettingsConfigDict(env_prefix="C3V_", env_nested_delimiter="__", extra="ignore")
+
+ runs_dir: Path = Field(default=Path("runs"))
+ cache_dir: Path = Field(default=Path.home() / ".cache" / "codeverse")
+ binaries: Binaries = Field(default_factory=Binaries)
+ render: Render = Field(default_factory=Render)
+ limits: Limits = Field(default_factory=Limits)
+
+ gemini_api_keys: list[str] = Field(default_factory=list)
+ anthropic_api_key: str = ""
+ openai_api_key: str = ""
+ openai_base_url: str = ""
+
+ default_planner: str = "gemini:gemini-3.7-flash"
+ default_generator: str = "api-agent:gemini:gemini-3.7-flash"
+ default_judge: str = "gemini:gemini-3.7-flash"
+
+ # ------------------------------------------------------------------ helpers
+ def resolve_blender(self) -> str:
+ if self.binaries.blender and Path(self.binaries.blender).exists():
+ return self.binaries.blender
+ for cand in ("blender-5.0", "blender", "blender-5.1", "blender-4.2"):
+ p = shutil.which(cand)
+ if p:
+ return p
+ return ""
+
+ def runtime_js_dir(self) -> Path:
+ return Path(__file__).resolve().parent.parent / "runtime_js"
+
+
+def _load_yaml(path: Path) -> dict:
+ if not path.is_file():
+ return {}
+ with path.open() as fh:
+ return yaml.safe_load(fh) or {}
+
+
+def _legacy_gemini_keys() -> list[str]:
+ """Read ``GEMINI_API_KEYS`` from the owner's astra3d keys file (csv, quoted)."""
+ if not _LEGACY_KEYS_FILE.is_file():
+ return []
+ m = re.search(r'GEMINI_API_KEYS="?([^"\n]+)"?', _LEGACY_KEYS_FILE.read_text())
+ if not m:
+ return []
+ return [k.strip() for k in m.group(1).split(",") if k.strip()]
+
+
+def _env_gemini_keys() -> list[str]:
+ csv = os.environ.get("GEMINI_API_KEYS", "")
+ keys = [k.strip() for k in csv.split(",") if k.strip()]
+ single = os.environ.get("GEMINI_API_KEY") or os.environ.get("GOOGLE_API_KEY")
+ if single and single not in keys:
+ keys.append(single)
+ return keys
+
+
+@lru_cache(maxsize=1)
+def get_settings() -> Settings:
+ """Build the singleton Settings (cached; call ``get_settings.cache_clear()`` in tests)."""
+ data: dict = {}
+ for p in (_USER_CONFIG, Path("codeverse.yaml")):
+ deep = _load_yaml(p)
+ data.update(deep)
+ s = Settings(**data)
+ if not s.gemini_api_keys:
+ s.gemini_api_keys = _env_gemini_keys() or _legacy_gemini_keys()
+ if not s.anthropic_api_key:
+ s.anthropic_api_key = os.environ.get("ANTHROPIC_API_KEY", "")
+ if not s.openai_api_key:
+ s.openai_api_key = os.environ.get("OPENAI_API_KEY", "")
+ # de-dupe keys preserving order
+ seen: set[str] = set()
+ s.gemini_api_keys = [k for k in s.gemini_api_keys if not (k in seen or seen.add(k))]
+ return s
diff --git a/harness/codeverse/contracts/__init__.py b/harness/codeverse/contracts/__init__.py
new file mode 100644
index 00000000..fd6f9146
--- /dev/null
+++ b/harness/codeverse/contracts/__init__.py
@@ -0,0 +1,54 @@
+"""Typed contracts shared across the harness. Data only — no behaviour.
+
+Modules:
+- ``common`` enums, vectors, usage/cost.
+- ``spec`` what the user asked for (track, language, prompt, budget, backends).
+- ``plan`` what the planner decided (parts / joints / zones / acceptance).
+- ``artifacts`` what tools produced (measurements, renders, gate reports, builds).
+- ``judgment`` what judges said (scores, issues, improvement plan).
+- ``run`` the run record (rounds, totals, provenance) — the flywheel unit.
+- ``chat`` ChatModel request/response shapes.
+- ``agent`` CodingAgent job/result shapes.
+"""
+
+from codeverse.contracts.agent import AgentJob, AgentResult, FileChange
+from codeverse.contracts.artifacts import (
+ BuildResult,
+ GateFinding,
+ GateReport,
+ Measurement,
+ PartMeasure,
+ RenderSet,
+ RenderView,
+ Severity,
+)
+from codeverse.contracts.chat import (
+ ChatMessage,
+ ChatRequest,
+ ChatResponse,
+ ImagePart,
+ TextPart,
+ ToolCallPart,
+ ToolResultPart,
+ ToolSpec,
+)
+from codeverse.contracts.common import Backends, Budget, Language, Track, Usage, Vec3
+from codeverse.contracts.judgment import ImprovementItem, JudgeIssue, Judgment
+from codeverse.contracts.plan import (
+ AcceptanceItem,
+ ArticulatedPlan,
+ AssetPlan,
+ BBox,
+ CameraPlan,
+ EffectPlan,
+ JointPlan,
+ PartPlan,
+ Plan,
+ ScenePlan,
+ StaticPlan,
+ ZonePlan,
+)
+from codeverse.contracts.run import RoundRecord, RunRecord, RunStatus
+from codeverse.contracts.spec import Constraints, ReferenceImage, Spec
+
+__all__ = [name for name in dir() if not name.startswith("_")]
diff --git a/harness/codeverse/contracts/agent.py b/harness/codeverse/contracts/agent.py
new file mode 100644
index 00000000..ea41a46f
--- /dev/null
+++ b/harness/codeverse/contracts/agent.py
@@ -0,0 +1,43 @@
+"""CodingAgent job/result — one headless agentic session on a workspace."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.common import Usage
+
+
+class FileChange(BaseModel):
+ path: str
+ status: str # added | modified | deleted
+ lines_added: int = 0
+ lines_removed: int = 0
+
+
+class AgentJob(BaseModel):
+ workspace: str
+ prompt: str
+ system_append: str = ""
+ model: str = ""
+ label: str = ""
+ timeout_s: int = 1800
+ max_turns: int = 60
+ allow_network: bool = False
+ spatial_tools: bool = Field(default=True, description="expose the c3v MCP spatial tools to the agent")
+ write_roots: list[str] = Field(default_factory=lambda: ["src", "public"], description="dirs the agent may edit")
+ env: dict[str, str] = Field(default_factory=dict)
+ extra: dict[str, Any] = Field(default_factory=dict)
+
+
+class AgentResult(BaseModel):
+ ok: bool
+ exit_reason: str = "" # completed | timeout | error | budget | model_substituted
+ text: str = ""
+ files_changed: list[FileChange] = Field(default_factory=list)
+ transcript_path: str = ""
+ usage: Usage = Field(default_factory=Usage)
+ duration_s: float = 0.0
+ tool_calls: int = 0
+ errors: list[str] = Field(default_factory=list)
diff --git a/harness/codeverse/contracts/artifacts.py b/harness/codeverse/contracts/artifacts.py
new file mode 100644
index 00000000..10e06325
--- /dev/null
+++ b/harness/codeverse/contracts/artifacts.py
@@ -0,0 +1,103 @@
+"""What deterministic tools produce: builds, measurements, renders, gates."""
+
+from __future__ import annotations
+
+from enum import StrEnum
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.common import Vec3
+
+
+class Severity(StrEnum):
+ ERROR = "error" # blocks acceptance; routed to a repair task
+ WARN = "warn" # shown to judge/agent; does not block
+ INFO = "info"
+
+
+class GateFinding(BaseModel):
+ gate: str
+ severity: Severity
+ target: str | None = Field(default=None, description="part / zone / joint / file this is about")
+ message: str
+ fix_hint: str = Field(default="", description="concrete, copyable instruction for the fixer")
+ data: dict[str, Any] = Field(default_factory=dict)
+
+
+class GateReport(BaseModel):
+ gate: str
+ passed: bool
+ findings: list[GateFinding] = Field(default_factory=list)
+ duration_ms: int = 0
+
+ @property
+ def errors(self) -> list[GateFinding]:
+ return [f for f in self.findings if f.severity == Severity.ERROR]
+
+
+class BuildResult(BaseModel):
+ """Result of executing the raw code and exporting the canonical artifact."""
+
+ ok: bool
+ language: str
+ glb_path: str | None = None
+ extra_paths: dict[str, str] = Field(default_factory=dict, description="stl/step/urdf/blend ...")
+ stdout_tail: str = ""
+ stderr_tail: str = ""
+ error_type: str = ""
+ error_message: str = ""
+ error_file: str = ""
+ error_line: int | None = None
+ duration_ms: int = 0
+ census: dict[str, Any] = Field(default_factory=dict, description="language-native census (objects, materials ...)")
+
+
+class PartMeasure(BaseModel):
+ name: str
+ bbox_min: Vec3
+ bbox_max: Vec3
+ tri_count: int = 0
+ islands: int = 1
+ volume_m3: float | None = None
+ watertight: bool | None = None
+
+
+class Measurement(BaseModel):
+ """Language-agnostic census computed from the canonical GLB (Y-up, meters)."""
+
+ bbox_min: Vec3
+ bbox_max: Vec3
+ extents: Vec3
+ center: Vec3
+ tri_count: int
+ n_meshes: int
+ n_islands: int
+ parts: list[PartMeasure] = Field(default_factory=list)
+ ground_gap_m: float = Field(default=0.0, description="lowest point minus 0 (negative = below ground)")
+ footprint_offset_m: float = Field(default=0.0, description="xz distance of bbox centre from origin")
+ materials: int = 0
+ frame: str = "y_up_pos_z_front"
+ extra: dict[str, Any] = Field(default_factory=dict)
+
+
+class RenderView(BaseModel):
+ name: str
+ path: str
+ mode: str = "shaded" # shaded | wire | normals | silhouette | depth | clay
+ width: int = 0
+ height: int = 0
+ camera_position: Vec3 | None = None
+ look_at: Vec3 | None = None
+ fov: float | None = None
+ time_s: float | None = Field(default=None, description="animation time for scenes")
+
+
+class RenderSet(BaseModel):
+ views: list[RenderView] = Field(default_factory=list)
+ contact_sheet: str | None = Field(default=None, description="one labelled grid image of all views")
+ turntable: str | None = None
+ renderer: str = ""
+ duration_ms: int = 0
+ console_errors: list[str] = Field(default_factory=list, description="(scenes) JS/WebGL errors seen")
+ fps: float | None = None
diff --git a/harness/codeverse/contracts/chat.py b/harness/codeverse/contracts/chat.py
new file mode 100644
index 00000000..31700bc1
--- /dev/null
+++ b/harness/codeverse/contracts/chat.py
@@ -0,0 +1,86 @@
+"""ChatModel request/response shapes — provider-neutral."""
+
+from __future__ import annotations
+
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.common import Usage
+
+
+class TextPart(BaseModel):
+ type: Literal["text"] = "text"
+ text: str
+
+
+class ImagePart(BaseModel):
+ type: Literal["image"] = "image"
+ path: str | None = None
+ data_b64: str | None = None
+ mime: str = "image/png"
+ label: str = ""
+
+
+class ToolCallPart(BaseModel):
+ type: Literal["tool_call"] = "tool_call"
+ id: str
+ name: str
+ arguments: dict[str, Any] = Field(default_factory=dict)
+
+
+class ToolResultPart(BaseModel):
+ type: Literal["tool_result"] = "tool_result"
+ call_id: str
+ name: str
+ content: str
+ images: list[ImagePart] = Field(default_factory=list)
+ is_error: bool = False
+
+
+Part = TextPart | ImagePart | ToolCallPart | ToolResultPart
+
+
+class ChatMessage(BaseModel):
+ role: Literal["user", "assistant", "tool"]
+ parts: list[Part]
+
+ @classmethod
+ def user(cls, text: str, images: list[ImagePart] | None = None) -> ChatMessage:
+ parts: list[Part] = [TextPart(text=text)]
+ parts.extend(images or [])
+ return cls(role="user", parts=parts)
+
+ @classmethod
+ def assistant(cls, text: str) -> ChatMessage:
+ return cls(role="assistant", parts=[TextPart(text=text)])
+
+ @property
+ def text(self) -> str:
+ return "\n".join(p.text for p in self.parts if isinstance(p, TextPart))
+
+
+class ToolSpec(BaseModel):
+ name: str
+ description: str
+ parameters: dict[str, Any] = Field(description="JSON schema of the arguments object")
+
+
+class ChatRequest(BaseModel):
+ messages: list[ChatMessage]
+ system: str = ""
+ response_schema: dict[str, Any] | None = Field(default=None, description="force JSON matching this schema")
+ tools: list[ToolSpec] | None = None
+ temperature: float = 0.7
+ max_output_tokens: int = 16000
+ thinking: Literal["off", "low", "medium", "high"] = "low"
+ label: str = Field(default="", description="for logs/cost ledger: planner / judge / generate ...")
+
+
+class ChatResponse(BaseModel):
+ text: str = ""
+ parsed: Any = None
+ tool_calls: list[ToolCallPart] = Field(default_factory=list)
+ finish_reason: str = ""
+ usage: Usage = Field(default_factory=Usage)
+ raw: dict[str, Any] = Field(default_factory=dict)
diff --git a/harness/codeverse/contracts/common.py b/harness/codeverse/contracts/common.py
new file mode 100644
index 00000000..33dc1e24
--- /dev/null
+++ b/harness/codeverse/contracts/common.py
@@ -0,0 +1,88 @@
+"""Enums and small value types used everywhere."""
+
+from __future__ import annotations
+
+from enum import StrEnum
+from typing import Annotated
+
+from pydantic import BaseModel, Field
+
+Vec3 = Annotated[tuple[float, float, float], Field(description="x, y, z")]
+
+
+class Track(StrEnum):
+ """What kind of 3D thing we are producing."""
+
+ STATIC_OBJECT = "static_object"
+ ARTICULATED_OBJECT = "articulated_object"
+ SCENE = "scene"
+
+
+class Language(StrEnum):
+ """Raw authoring language of the deliverable (no SDKs on top)."""
+
+ BLENDER = "blender" # pure bpy script → GLB/STL
+ CADQUERY = "cadquery" # pure cadquery script → STEP/STL/GLB
+ THREEJS = "threejs" # procedural three.js (ESM) → GLB via GLTFExporter
+ URDF_BLENDER = "urdf_blender" # bpy link meshes + hand-written URDF
+ SCENE_THREEJS = "scene_threejs" # multi-file three.js scene (+GLSL, +GLB assets)
+
+
+#: languages allowed per track
+TRACK_LANGUAGES: dict[Track, tuple[Language, ...]] = {
+ Track.STATIC_OBJECT: (Language.BLENDER, Language.CADQUERY, Language.THREEJS),
+ Track.ARTICULATED_OBJECT: (Language.URDF_BLENDER,),
+ Track.SCENE: (Language.SCENE_THREEJS,),
+}
+
+
+class Usage(BaseModel):
+ """Normalised token/cost accounting for ONE model or agent call."""
+
+ backend: str = ""
+ model: str = ""
+ input_tokens: int = 0
+ output_tokens: int = 0
+ cached_tokens: int = 0
+ thoughts_tokens: int = 0
+ tool_calls: int = 0
+ cost_usd: float = 0.0
+ latency_ms: int = 0
+
+ def __add__(self, other: Usage) -> Usage:
+ return Usage(
+ backend=self.backend or other.backend,
+ model=self.model if self.model == other.model else (self.model or other.model),
+ input_tokens=self.input_tokens + other.input_tokens,
+ output_tokens=self.output_tokens + other.output_tokens,
+ cached_tokens=self.cached_tokens + other.cached_tokens,
+ thoughts_tokens=self.thoughts_tokens + other.thoughts_tokens,
+ tool_calls=self.tool_calls + other.tool_calls,
+ cost_usd=self.cost_usd + other.cost_usd,
+ latency_ms=self.latency_ms + other.latency_ms,
+ )
+
+
+class Budget(BaseModel):
+ """Hard ceilings for a run. The orchestrator stops (cleanly) when any is hit."""
+
+ max_rounds: int = 4
+ max_usd: float = 5.0
+ max_minutes: float = 60.0
+ max_repair_attempts: int = 3 # per build failure before escalating
+
+
+class Backends(BaseModel):
+ """Which model/agent does which job. Ids are ``<kind>:<model>``:
+
+ * API chat models: ``gemini:gemini-3.7-flash`` · ``anthropic:claude-sonnet-5``
+ · ``openai:gpt-5.6-sol``
+ * Coding agents: ``gemini-cli:gemini-3.7-flash`` · ``claude-code:sonnet``
+ · ``codex:gpt-5.6-sol`` · ``agy:gemini-3.6-flash-high``
+ · ``api-agent:gemini:gemini-3.7-flash`` (in-process tool loop on a ChatModel)
+ """
+
+ planner: str = "gemini:gemini-3.7-flash"
+ generator: str = "api-agent:gemini:gemini-3.7-flash"
+ judge: str = "gemini:gemini-3.7-flash"
+ captioner: str = "gemini:gemini-3.7-flash"
diff --git a/harness/codeverse/contracts/judgment.py b/harness/codeverse/contracts/judgment.py
new file mode 100644
index 00000000..2cec2cd2
--- /dev/null
+++ b/harness/codeverse/contracts/judgment.py
@@ -0,0 +1,45 @@
+"""Judge outputs: rubric scores + structured, targeted improvement plan."""
+
+from __future__ import annotations
+
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.common import Usage
+
+
+class JudgeIssue(BaseModel):
+ target: str = Field(description="part / zone / joint / asset / 'overall'")
+ kind: Literal[
+ "geometry", "proportion", "detail", "material", "assembly", "articulation",
+ "lighting", "composition", "animation", "effect", "fidelity", "scale", "bug",
+ ]
+ severity: Literal["critical", "major", "minor"]
+ detail: str = Field(description="what is wrong, observable in the renders")
+ evidence: str = Field(default="", description="which view(s) / measurement show it")
+
+
+class ImprovementItem(BaseModel):
+ target: str
+ kind: Literal["geometry", "material", "assembly", "articulation", "lighting", "composition", "animation", "effect", "bug"]
+ instruction: str = Field(description="concrete, actionable change for the builder")
+ priority: int = Field(ge=1, le=5, description="1 = do first")
+ expected_gain: float = Field(default=0.0, ge=0.0, le=1.0)
+
+
+class Judgment(BaseModel):
+ rubric: str
+ judge_backend: str = ""
+ scores: dict[str, float] = Field(description="criterion → 0..1")
+ overall: float = Field(ge=0.0, le=1.0, description="weighted by the rubric (computed in code)")
+ passed: bool
+ summary: str = ""
+ strengths: list[str] = Field(default_factory=list)
+ issues: list[JudgeIssue] = Field(default_factory=list)
+ improvement_plan: list[ImprovementItem] = Field(default_factory=list)
+ acceptance_results: dict[str, bool] = Field(default_factory=dict, description="acceptance item id → verified")
+ n_samples: int = 1
+ score_std: float = 0.0
+ usage: Usage = Field(default_factory=Usage)
+ raw: str = ""
diff --git a/harness/codeverse/contracts/plan.py b/harness/codeverse/contracts/plan.py
new file mode 100644
index 00000000..67a888b5
--- /dev/null
+++ b/harness/codeverse/contracts/plan.py
@@ -0,0 +1,204 @@
+"""Plans: the planner's structured decomposition. Every plan carries an
+*acceptance checklist* — concrete, verifiable items derived from the spec —
+so acceptance can be mechanical (evidence), not an opinion.
+
+Plans are written by an LLM under a JSON schema and then VALIDATED IN CODE
+(unit axes, single-root joint trees, sane limits, unique names). Invalid
+plans are re-asked with the validation errors, before any generator runs.
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Literal
+
+from pydantic import BaseModel, Field, model_validator
+
+from codeverse.contracts.common import Vec3
+from codeverse.conventions import to_snake
+
+
+class BBox(BaseModel):
+ """Axis-aligned box in the plan's frame: centre + full extents (meters)."""
+
+ center: Vec3
+ extents: Vec3
+
+ @property
+ def min(self) -> tuple[float, float, float]:
+ return tuple(c - e / 2 for c, e in zip(self.center, self.extents, strict=True)) # type: ignore[return-value]
+
+ @property
+ def max(self) -> tuple[float, float, float]:
+ return tuple(c + e / 2 for c, e in zip(self.center, self.extents, strict=True)) # type: ignore[return-value]
+
+
+class AcceptanceItem(BaseModel):
+ """One verifiable requirement. ``how`` says which evidence proves it."""
+
+ id: str
+ text: str
+ how: Literal["measure", "visual", "probe", "articulation"] = "visual"
+ priority: Literal["must", "should"] = "must"
+
+
+class PartPlan(BaseModel):
+ name: str = Field(description="PascalCase unique part name, e.g. SeatCushion")
+ role: str = Field(description="what this part is / does, one line")
+ description: str = Field(description="shape, construction and visible detail the builder must realise")
+ bbox: BBox
+ material: str = Field(default="", description="material / finish in plain words")
+ attach_to: str | None = Field(default=None, description="parent part name this part touches")
+ symmetry: Literal["none", "mirror_x", "mirror_y", "radial"] = "none"
+ instances: int = Field(default=1, ge=1, description="identical copies (e.g. 4 legs)")
+
+
+class StaticPlan(BaseModel):
+ object_name: str
+ summary: str
+ overall_bbox: BBox
+ style_notes: str = ""
+ parts: list[PartPlan] = Field(min_length=1)
+ acceptance: list[AcceptanceItem] = Field(default_factory=list)
+
+ @model_validator(mode="after")
+ def _unique_names(self) -> StaticPlan:
+ seen: set[str] = set()
+ for p in self.parts:
+ key = to_snake(p.name)
+ if key in seen:
+ raise ValueError(f"duplicate part name (after normalisation): {p.name}")
+ seen.add(key)
+ names = {to_snake(p.name) for p in self.parts}
+ for p in self.parts:
+ if p.attach_to and to_snake(p.attach_to) not in names:
+ raise ValueError(f"part {p.name} attaches to unknown part {p.attach_to}")
+ return self
+
+
+class JointPlan(BaseModel):
+ name: str
+ type: Literal["revolute", "prismatic", "continuous", "fixed"]
+ parent: str = Field(description="parent link (part) name")
+ child: str = Field(description="child link (part) name")
+ axis: Vec3 = Field(description="unit axis in the plan frame")
+ pivot: Vec3 = Field(description="a point on the joint axis, WORLD coords (rest pose)")
+ lower: float = Field(default=0.0, description="rad for revolute, m for prismatic")
+ upper: float = Field(default=0.0)
+ rest: float = Field(default=0.0, description="joint value in the authored rest pose")
+ motion: str = Field(default="", description="what moving this joint does, one line")
+
+ @model_validator(mode="after")
+ def _sane(self) -> JointPlan:
+ n = math.sqrt(sum(a * a for a in self.axis))
+ if n < 1e-6:
+ raise ValueError(f"joint {self.name}: zero axis")
+ if abs(n - 1.0) > 1e-3:
+ self.axis = tuple(a / n for a in self.axis) # type: ignore[assignment]
+ if self.type in ("revolute", "prismatic"):
+ if self.upper < self.lower:
+ raise ValueError(f"joint {self.name}: upper < lower")
+ if not (self.lower - 1e-9 <= self.rest <= self.upper + 1e-9):
+ raise ValueError(f"joint {self.name}: rest {self.rest} outside [{self.lower},{self.upper}]")
+ if self.type == "revolute" and (self.upper - self.lower) > 2 * math.pi + 1e-6:
+ raise ValueError(f"joint {self.name}: revolute range > 2π, use continuous")
+ if self.type == "prismatic" and (self.upper - self.lower) > 5.0:
+ raise ValueError(f"joint {self.name}: prismatic range > 5 m is implausible")
+ if to_snake(self.parent) == to_snake(self.child):
+ raise ValueError(f"joint {self.name}: parent == child")
+ return self
+
+
+class ArticulatedPlan(StaticPlan):
+ root_link: str
+ joints: list[JointPlan] = Field(min_length=1)
+
+ @model_validator(mode="after")
+ def _tree(self) -> ArticulatedPlan:
+ links = {to_snake(p.name) for p in self.parts}
+ root = to_snake(self.root_link)
+ if root not in links:
+ raise ValueError(f"root_link {self.root_link} is not a part")
+ parent_of: dict[str, str] = {}
+ for j in self.joints:
+ p, c = to_snake(j.parent), to_snake(j.child)
+ if p not in links or c not in links:
+ raise ValueError(f"joint {j.name} references unknown link(s) {j.parent}/{j.child}")
+ if c in parent_of:
+ raise ValueError(f"link {j.child} has two parent joints")
+ if c == root:
+ raise ValueError(f"root link {self.root_link} cannot be a joint child")
+ parent_of[c] = p
+ # every non-root link must reach root
+ for link in links - {root}:
+ seen, cur = set(), link
+ while cur != root:
+ if cur in seen or cur not in parent_of:
+ raise ValueError(f"link {link} is not connected to root {self.root_link} (single-root tree required)")
+ seen.add(cur)
+ cur = parent_of[cur]
+ return self
+
+
+class ZonePlan(BaseModel):
+ name: str = Field(description="PascalCase zone name, e.g. Harbour")
+ description: str
+ bbox: BBox
+ contents: list[str] = Field(default_factory=list, description="asset names placed in this zone")
+
+
+class AssetPlan(BaseModel):
+ name: str = Field(description="PascalCase asset name")
+ kind: Literal["threejs", "blender_glb"] = Field(
+ description="threejs = procedural module; blender_glb = built with bpy and compiled to a GLB"
+ )
+ description: str
+ approx_size_m: Vec3
+ instances_hint: int = 1
+
+
+class EffectPlan(BaseModel):
+ name: str
+ kind: Literal["glsl_material", "postprocess", "particles", "animated_geometry"]
+ description: str
+ target: str = Field(default="", description="zone / asset / scene it applies to")
+
+
+class CameraPlan(BaseModel):
+ name: str
+ position: Vec3
+ look_at: Vec3
+ fov: float = 50.0
+ purpose: str = ""
+
+
+class ScenePlan(BaseModel):
+ title: str
+ summary: str
+ setting: str = Field(description="place, era, weather, time of day")
+ mood: str = ""
+ bounds: BBox
+ environment: str = Field(description="sky, sun/moon, fog, ground, water — one paragraph")
+ zones: list[ZonePlan] = Field(min_length=1)
+ assets: list[AssetPlan] = Field(default_factory=list)
+ effects: list[EffectPlan] = Field(default_factory=list)
+ animation: list[str] = Field(default_factory=list, description="what moves and how")
+ cameras: list[CameraPlan] = Field(min_length=1, max_length=6)
+ acceptance: list[AcceptanceItem] = Field(default_factory=list)
+
+ @model_validator(mode="after")
+ def _names(self) -> ScenePlan:
+ assets = {to_snake(a.name) for a in self.assets}
+ zones = set()
+ for z in self.zones:
+ k = to_snake(z.name)
+ if k in zones:
+ raise ValueError(f"duplicate zone {z.name}")
+ zones.add(k)
+ for c in z.contents:
+ if to_snake(c) not in assets:
+ raise ValueError(f"zone {z.name} lists unknown asset {c}")
+ return self
+
+
+Plan = StaticPlan | ArticulatedPlan | ScenePlan
diff --git a/harness/codeverse/contracts/run.py b/harness/codeverse/contracts/run.py
new file mode 100644
index 00000000..6ac1ba19
--- /dev/null
+++ b/harness/codeverse/contracts/run.py
@@ -0,0 +1,64 @@
+"""The run record: one entry per run, the unit the flywheel indexes."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from enum import StrEnum
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, RenderSet
+from codeverse.contracts.common import Usage
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import ArticulatedPlan, ScenePlan, StaticPlan
+from codeverse.contracts.spec import Spec
+
+
+class RunStatus(StrEnum):
+ PLANNING = "planning"
+ GENERATING = "generating"
+ REFINING = "refining"
+ PASSED = "passed"
+ PLATEAU = "plateau"
+ BUDGET = "budget"
+ FAILED = "failed"
+
+
+class RoundRecord(BaseModel):
+ index: int
+ kind: str = Field(description="baseline | refine | repair | texture | asset:<name> ...")
+ commit: str = Field(default="", description="git commit of src/ after this round")
+ agent_backend: str = ""
+ instructions: list[str] = Field(default_factory=list, description="what the agent was asked to change")
+ build: BuildResult | None = None
+ gates: list[GateReport] = Field(default_factory=list)
+ measurement: Measurement | None = None
+ 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))
+ duration_s: float = 0.0
+ notes: str = ""
+
+ @property
+ def score(self) -> float | None:
+ return self.judgment.overall if self.judgment else None
+
+
+class RunRecord(BaseModel):
+ spec: Spec
+ plan: StaticPlan | ArticulatedPlan | ScenePlan | None = None
+ workspace: str
+ status: RunStatus = RunStatus.PLANNING
+ rounds: list[RoundRecord] = Field(default_factory=list)
+ best_round: int | None = None
+ baseline_score: float | None = None
+ final_score: float | None = None
+ 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))
+ 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
new file mode 100644
index 00000000..dac2a5f8
--- /dev/null
+++ b/harness/codeverse/contracts/spec.py
@@ -0,0 +1,52 @@
+"""The Spec: everything the user asked for, frozen at run start."""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+from pydantic import BaseModel, Field, model_validator
+
+from codeverse.contracts.common import TRACK_LANGUAGES, Backends, Budget, Language, Track
+
+
+class ReferenceImage(BaseModel):
+ path: str
+ role: str = "target" # target | style | detail
+ note: str = ""
+
+
+class Constraints(BaseModel):
+ """Optional hard requirements the user states up front. Each becomes an
+ acceptance item the planner must carry and a gate can verify."""
+
+ dimensions_m: dict[str, float] | None = Field(
+ default=None, description="e.g. {'width': 1.2, 'depth': 0.6, 'height': 0.75}"
+ )
+ max_triangles: int | None = None
+ style: str = ""
+ must_have: list[str] = Field(default_factory=list)
+ must_not: list[str] = Field(default_factory=list)
+
+
+class Spec(BaseModel):
+ id: str
+ track: Track
+ language: Language
+ prompt: str
+ references: list[ReferenceImage] = Field(default_factory=list)
+ constraints: Constraints = Field(default_factory=Constraints)
+ budget: Budget = Field(default_factory=Budget)
+ backends: Backends = Field(default_factory=Backends)
+ seed: int = 0
+ tags: list[str] = Field(default_factory=list)
+ created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
+
+ @model_validator(mode="after")
+ def _language_fits_track(self) -> Spec:
+ allowed = TRACK_LANGUAGES[self.track]
+ if self.language not in allowed:
+ raise ValueError(
+ f"language {self.language} is not valid for track {self.track}; "
+ f"allowed: {[a.value for a in allowed]}"
+ )
+ return self
diff --git a/harness/codeverse/conventions.py b/harness/codeverse/conventions.py
new file mode 100644
index 00000000..7db79d08
--- /dev/null
+++ b/harness/codeverse/conventions.py
@@ -0,0 +1,145 @@
+"""Single source of truth for 3D conventions used by prompts, tools and gates.
+
+Everything that talks about axes, units, frames, view presets or naming must
+import from here — never restate a convention inline (the reference harnesses
+drifted into 3-4 incompatible ``snake_case`` helpers and two up-axes).
+
+Frames
+------
+* ``blender`` / ``cadquery`` / ``urdf``: **Z-up, -Y is the object's front**,
+ meters. (Blender's "Front" view looks along +Y, so a front face points -Y.)
+* ``threejs`` / ``scene_threejs``: **Y-up, +Z is the front**, meters.
+* Canonical exchange format is **GLB (glTF 2.0): Y-up, +Z front, meters**.
+ Blender's glTF exporter maps (x, y, z) → (x, z, -y), so a Blender -Y front
+ becomes glTF +Z front — the two native frames agree once exported.
+* Objects stand on the ground: the lowest point is at up=0 and the footprint
+ is centred on the up-axis. Scenes may use any origin but bounds are declared.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from enum import StrEnum
+
+UNITS = "meters"
+
+
+class Frame(StrEnum):
+ """Named coordinate conventions."""
+
+ Z_UP_NEG_Y_FRONT = "z_up_neg_y_front" # blender / cadquery / urdf
+ Y_UP_POS_Z_FRONT = "y_up_pos_z_front" # three.js / glTF
+
+
+#: up / front axes per frame as unit vectors (x, y, z)
+FRAME_AXES: dict[Frame, dict[str, tuple[float, float, float]]] = {
+ Frame.Z_UP_NEG_Y_FRONT: {"up": (0, 0, 1), "front": (0, -1, 0), "right": (1, 0, 0)},
+ Frame.Y_UP_POS_Z_FRONT: {"up": (0, 1, 0), "front": (0, 0, 1), "right": (1, 0, 0)},
+}
+
+#: language id → native authoring frame
+LANGUAGE_FRAME: dict[str, Frame] = {
+ "blender": Frame.Z_UP_NEG_Y_FRONT,
+ "cadquery": Frame.Z_UP_NEG_Y_FRONT,
+ "urdf_blender": Frame.Z_UP_NEG_Y_FRONT,
+ "threejs": Frame.Y_UP_POS_Z_FRONT,
+ "scene_threejs": Frame.Y_UP_POS_Z_FRONT,
+}
+
+GLB_FRAME = Frame.Y_UP_POS_Z_FRONT
+
+
+def frame_doc(frame: Frame) -> str:
+ """Return the one-paragraph prompt text describing ``frame``."""
+ if frame is Frame.Z_UP_NEG_Y_FRONT:
+ return (
+ "Coordinate frame: Z is UP, -Y is the FRONT of the object (the face a "
+ "viewer sees from the default front view), +X is the object's right. "
+ "Units are meters. The object stands on the ground plane z=0 and its "
+ "footprint is centred on the Z axis."
+ )
+ return (
+ "Coordinate frame: Y is UP, +Z is the FRONT of the object (towards the "
+ "default camera), +X is the object's right. Units are meters. The object "
+ "stands on the ground plane y=0 and its footprint is centred on the Y axis."
+ )
+
+
+# --------------------------------------------------------------------------- views
+@dataclass(frozen=True)
+class ViewPreset:
+ """A canonical camera direction: azimuth (deg, 0 = front, CCW from above) and
+ elevation (deg above the horizon). Distance is fitted to the asset bbox."""
+
+ name: str
+ azimuth_deg: float
+ elevation_deg: float
+
+
+#: Judge view set for objects: 3/4 views + orthographic-ish sides + top + underside.
+OBJECT_VIEWS: tuple[ViewPreset, ...] = (
+ ViewPreset("front_right_34", 35.0, 22.0),
+ ViewPreset("back_left_34", 215.0, 22.0),
+ ViewPreset("front", 0.0, 8.0),
+ ViewPreset("right", 90.0, 8.0),
+ ViewPreset("back", 180.0, 8.0),
+ ViewPreset("left", 270.0, 8.0),
+ ViewPreset("top", 0.0, 88.0),
+ ViewPreset("low_front_left", 325.0, -12.0),
+)
+
+#: Quick 4-view subset (cheap gates, contact sheets for agents).
+OBJECT_VIEWS_QUICK: tuple[ViewPreset, ...] = (
+ OBJECT_VIEWS[0],
+ OBJECT_VIEWS[1],
+ OBJECT_VIEWS[2],
+ OBJECT_VIEWS[6],
+)
+
+#: Scene overview rig (scenes sit on ground: aerial + eye level, no underside).
+SCENE_VIEWS: tuple[ViewPreset, ...] = (
+ ViewPreset("overview_front_right", 40.0, 32.0),
+ ViewPreset("overview_back_left", 220.0, 32.0),
+ ViewPreset("overview_top", 0.0, 87.0),
+ ViewPreset("eye_front", 0.0, 10.0),
+ ViewPreset("eye_right", 90.0, 14.0),
+ ViewPreset("eye_back_left", 235.0, 12.0),
+)
+
+
+# --------------------------------------------------------------------------- names
+_CAMEL_SPLIT = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
+_NON_WORD = re.compile(r"[^0-9A-Za-z]+")
+
+
+def to_snake(name: str) -> str:
+ """``SeatCushion`` / ``seat cushion`` / ``Seat-Cushion2`` → ``seat_cushion2``.
+
+ This is THE name normaliser; every wrapper and prompt must use it.
+ """
+ s = _NON_WORD.sub("_", name.strip())
+ s = _CAMEL_SPLIT.sub("_", s)
+ s = re.sub(r"_+", "_", s).strip("_").lower()
+ return s or "part"
+
+
+def to_pascal(name: str) -> str:
+ """``seat_cushion`` / ``seat cushion`` → ``SeatCushion``."""
+ return "".join(w[:1].upper() + w[1:] for w in to_snake(name).split("_") if w) or "Part"
+
+
+def slugify(text: str, max_len: int = 48) -> str:
+ """Filesystem/URL-safe slug for run directories."""
+ s = to_snake(text)[:max_len].strip("_")
+ return s or "run"
+
+
+# --------------------------------------------------------------------------- limits
+#: Triangle budgets used by gates/prompts (soft caps; judge sees the count).
+MAX_TRIS_OBJECT = 600_000
+MAX_TRIS_SCENE = 3_000_000
+#: Default tolerance for bbox contract checks, in meters.
+BBOX_TOLERANCE_M = 0.01
+#: Parts are "touching" when the surface gap is below this (meters).
+CONTACT_GAP_M = 0.002
diff --git a/harness/codeverse/events.py b/harness/codeverse/events.py
new file mode 100644
index 00000000..b0f933fd
--- /dev/null
+++ b/harness/codeverse/events.py
@@ -0,0 +1,33 @@
+"""Append-only JSONL event log per run (one line per stage/tool/model event).
+
+Events are the audit trail that the flywheel, the CLI ``status`` view and
+tests read. Keep payloads small (paths + numbers, not file contents).
+"""
+
+from __future__ import annotations
+
+import json
+import threading
+import time
+from pathlib import Path
+from typing import Any
+
+
+class EventLog:
+ def __init__(self, path: Path):
+ self.path = Path(path)
+ self._lock = threading.Lock()
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+
+ def emit(self, event: str, **data: Any) -> None:
+ """Append one event. ``event`` is the event name (e.g. ``round.start``);
+ ``data`` may use any keys, including ``kind``."""
+ rec = {"t": round(time.time(), 3), "event": event, **data}
+ line = json.dumps(rec, default=str, ensure_ascii=False)
+ with self._lock, self.path.open("a") as fh:
+ fh.write(line + "\n")
+
+ def read(self) -> list[dict[str, Any]]:
+ if not self.path.is_file():
+ return []
+ return [json.loads(line) for line in self.path.read_text().splitlines() if line.strip()]
diff --git a/harness/codeverse/flywheel/__init__.py b/harness/codeverse/flywheel/__init__.py
new file mode 100644
index 00000000..bc1e6a82
--- /dev/null
+++ b/harness/codeverse/flywheel/__init__.py
@@ -0,0 +1,12 @@
+"""Flywheel: run records → dataset samples, preference pairs, captions, dedupe, index.
+
+Public API (see docs/INTERFACES.md):
+
+* ``record`` ``finalize_record(ws, record)`` · ``load_record(ws)`` · ``iter_runs(runs_dir)``
+* ``export`` ``export_samples(runs_dir, out_dir, min_score=..)`` → ``ExportReport``
+* ``pack`` ``pack_samples(out_dir)`` (plain tars + byte-range locators, optional)
+* ``pairs`` ``build_pairs(runs_dir, out_jsonl, min_delta=..)`` → n
+* ``captions`` ``caption_sample(ws, record, model_id)`` → ``Captions``
+* ``dedupe`` ``code_fingerprint`` · ``mesh_fingerprint`` · ``near_duplicates``
+* ``index`` ``build_index(runs_dir, out_sqlite)`` + query helpers
+"""
diff --git a/harness/codeverse/flywheel/_git.py b/harness/codeverse/flywheel/_git.py
new file mode 100644
index 00000000..c5178996
--- /dev/null
+++ b/harness/codeverse/flywheel/_git.py
@@ -0,0 +1,128 @@
+"""Read-only git helpers for the flywheel: file trees at a commit, binary-safe.
+
+The exporter / pairs builder must never touch the working tree of a run
+(another process may be resuming it), so everything here goes through
+``git archive`` / ``git ls-tree`` on the run's repository.
+"""
+
+from __future__ import annotations
+
+import io
+import subprocess
+import tarfile
+from pathlib import Path
+
+from codeverse.workspace import Workspace
+
+_GIT_TIMEOUT_S = 60
+_ENV = {"PATH": "/usr/bin:/bin:/usr/local/bin", "GIT_TERMINAL_PROMPT": "0"}
+
+#: directories of a workspace that hold agent-authored code
+CODE_ROOTS: tuple[str, ...] = ("src", "public")
+_SKIP_PARTS = {"node_modules", "__pycache__", ".git"}
+
+
+class GitReadError(RuntimeError):
+ """A git read (ls-tree / archive) failed or the commit does not exist."""
+
+
+def _run(ws: Workspace, *args: str) -> subprocess.CompletedProcess[bytes]:
+ try:
+ proc = subprocess.run(
+ ["git", *args], cwd=ws.root, capture_output=True, check=False, env=_ENV, timeout=_GIT_TIMEOUT_S
+ )
+ except subprocess.TimeoutExpired as e: # pragma: no cover - defensive
+ raise GitReadError(f"git {' '.join(args)} timed out in {ws.root}") from e
+ if proc.returncode != 0:
+ raise GitReadError(f"git {' '.join(args)} failed in {ws.root}: {proc.stderr.decode(errors='replace').strip()}")
+ return proc
+
+
+def commit_exists(ws: Workspace, commit: str) -> bool:
+ if not commit:
+ return False
+ try:
+ _run(ws, "cat-file", "-e", f"{commit}^{{commit}}")
+ return True
+ except GitReadError:
+ return False
+
+
+def _keep(rel: str) -> bool:
+ parts = Path(rel).parts
+ return bool(parts) and parts[0] in CODE_ROOTS and not any(p in _SKIP_PARTS for p in parts)
+
+
+def list_files_at(ws: Workspace, commit: str) -> list[str]:
+ """Sorted repo-relative paths under the code roots at ``commit``."""
+ out = _run(ws, "ls-tree", "-r", "--name-only", "-z", commit, "--", *CODE_ROOTS).stdout
+ return sorted(p for p in out.decode("utf-8", errors="replace").split("\0") if p and _keep(p))
+
+
+def read_tree_at(ws: Workspace, commit: str) -> dict[str, bytes]:
+ """``{repo-relative path: bytes}`` for every code file at ``commit`` (binary-safe)."""
+ if not commit_exists(ws, commit):
+ raise GitReadError(f"commit {commit!r} not found in {ws.root}")
+ # `git archive` errors on a pathspec that matches nothing, so only pass roots that exist.
+ listed = list_files_at(ws, commit)
+ present = [r for r in CODE_ROOTS if any(p.startswith(r + "/") for p in listed)]
+ if not present:
+ return {}
+ data = _run(ws, "archive", "--format=tar", commit, "--", *present).stdout
+ files: dict[str, bytes] = {}
+ with tarfile.open(fileobj=io.BytesIO(data), mode="r:") as tar:
+ for m in tar.getmembers():
+ if not m.isfile() or not _keep(m.name):
+ continue
+ fh = tar.extractfile(m)
+ if fh is not None:
+ files[m.name] = fh.read()
+ return files
+
+
+def read_working_tree(ws: Workspace) -> dict[str, bytes]:
+ """Fallback when a round has no commit: the current ``src/`` + ``public/``."""
+ files: dict[str, bytes] = {}
+ for root in CODE_ROOTS:
+ base = ws.root / root
+ if not base.is_dir():
+ continue
+ for p in sorted(base.rglob("*")):
+ if p.is_file():
+ rel = p.relative_to(ws.root).as_posix()
+ if _keep(rel):
+ files[rel] = p.read_bytes()
+ return files
+
+
+def decode_text_files(files: dict[str, bytes], *, max_total: int | None = None) -> tuple[dict[str, str], list[str]]:
+ """UTF-8 decode text files; binary files are listed in the second return value.
+
+ ``max_total`` caps the summed decoded length (files are added in sorted path
+ order; the first file that does not fit is truncated with a marker and the
+ rest are skipped into the ``skipped`` list).
+ """
+ text: dict[str, str] = {}
+ skipped: list[str] = []
+ total = 0
+ for path in sorted(files):
+ raw = files[path]
+ if b"\0" in raw[:8000]:
+ skipped.append(path)
+ continue
+ try:
+ s = raw.decode("utf-8")
+ except UnicodeDecodeError:
+ skipped.append(path)
+ continue
+ if max_total is not None and total + len(s) > max_total:
+ room = max_total - total
+ if room > 200:
+ text[path] = s[:room] + f"\n... [truncated {len(s) - room} chars]"
+ total = max_total
+ else:
+ skipped.append(path)
+ continue
+ text[path] = s
+ total += len(s)
+ return text, skipped
diff --git a/harness/codeverse/flywheel/captions.py b/harness/codeverse/flywheel/captions.py
new file mode 100644
index 00000000..2c6c9c53
--- /dev/null
+++ b/harness/codeverse/flywheel/captions.py
@@ -0,0 +1,193 @@
+"""Caption one finished run: ``{detailed, instruction, factory}`` (STORAGE_RULES §6).
+
+* ``detailed`` image-grounded, objective description of what was rendered
+ (parts, materials, proportions; motion / animation for articulated + scenes).
+* ``instruction`` one natural user request that asks for this as code and names
+ the target language generically ("a Blender Python script", "a Three.js scene").
+* ``factory`` code-grounded build recipe: parts + construction order + techniques.
+
+Rules enforced in code: strict JSON schema, no API/class names, no brand names,
+each field non-empty. Captions are stored in ``record.extra["captions"]`` (with
+provenance) and ``<ws>/captions.json``; ``record.json`` is rewritten.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from datetime import UTC, datetime
+from pathlib import Path
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.run import RunRecord
+from codeverse.flywheel import _git
+from codeverse.flywheel.sample import ENTRY_BY_LANGUAGE, best_round_record, code_files_for_round
+from codeverse.prompts import prompt_hash
+from codeverse.workspace import Workspace
+
+MAX_CODE_CHARS = 12_000
+N_VIEWS = 2
+
+#: how the instruction must name the target (generic, no API names)
+LANGUAGE_PHRASE: dict[Language, str] = {
+ Language.BLENDER: "a Blender Python script",
+ Language.CADQUERY: "a CadQuery script",
+ Language.THREEJS: "a Three.js module",
+ Language.URDF_BLENDER: "a URDF model with Blender-Python-built link meshes",
+ Language.SCENE_THREEJS: "a Three.js scene",
+}
+#: leaked API / platform tokens that must not appear in any caption
+_FORBIDDEN = re.compile(
+ r"\b(bpy|bmesh|mathutils|cq\.|cadquery\.|THREE\.|GLTFLoader|ShaderMaterial|MeshStandardMaterial|"
+ r"Workplane|Shadertoy|Sketchfab|Gemini|Claude|OpenAI|GPT|Antigravity)\b",
+ re.IGNORECASE,
+)
+
+
+class Captions(BaseModel):
+ detailed: str = Field(min_length=20, description="objective, image-grounded description (2-5 sentences)")
+ instruction: str = Field(min_length=15, description="one natural user request asking to generate this as code")
+ factory: str = Field(min_length=20, description="code-grounded build recipe: parts + construction order")
+
+
+class CaptionProvenance(BaseModel):
+ captioner: str
+ round_index: int | None
+ images_used: list[str]
+ code_chars: int
+ prompt_hash: str
+ created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
+ cost_usd: float = 0.0
+
+
+class CaptionError(RuntimeError):
+ pass
+
+
+def _system_prompt() -> str:
+ return (
+ "You label 3D assets for a code-generation dataset. You receive rendered views of an asset, "
+ "the user's original request, and the raw source code that built it. Return STRICT JSON with "
+ "exactly the keys detailed, instruction, factory (string values).\n"
+ "- detailed: an objective description of what is VISIBLE in the renders: the object/scene, its "
+ "main parts, proportions, materials/colours, and — if it articulates or animates — how its parts "
+ "move. 2-5 sentences, grounded in the images.\n"
+ "- instruction: ONE natural user request (1-2 sentences, imperative) asking an AI to generate this "
+ "asset as {language_phrase}; mention the key parts/requirements a user would state.\n"
+ "- factory: a technical build recipe (3-6 sentences) derived from the CODE: which parts are built, "
+ "in what order, from which primitives/operations (extrusions, booleans, lofts, instancing, joints, "
+ "shader effects...), how they are positioned and finished.\n"
+ "Rules: be specific to THIS asset; describe shapes in plain words; do NOT mention API, module, "
+ "class or function names, file names, model/vendor names or platforms; no markdown."
+ )
+
+
+def _round_images(ws: Workspace, record: RunRecord) -> tuple[list[ImagePart], list[str]]:
+ rnd = best_round_record(record)
+ images: list[ImagePart] = []
+ used: list[str] = []
+ if rnd is None or rnd.renders is None:
+ return images, used
+
+ def _add(path: str | None, label: str) -> None:
+ if not path or len(images) >= N_VIEWS + 1:
+ return
+ p = Path(path)
+ if not p.is_absolute():
+ p = ws.root / p
+ if p.is_file():
+ images.append(ImagePart(path=str(p), label=label))
+ used.append(str(p))
+
+ _add(rnd.renders.contact_sheet, "contact sheet (all views, labelled)")
+ for v in rnd.renders.views[:N_VIEWS]:
+ _add(v.path, f"view: {v.name}")
+ return images, used
+
+
+def _code_excerpt(ws: Workspace, record: RunRecord) -> str:
+ rnd = best_round_record(record)
+ files, _src = code_files_for_round(ws, rnd)
+ entry = ENTRY_BY_LANGUAGE[record.spec.language]
+ ordered = {k: files[k] for k in sorted(files, key=lambda k: (k != entry, k))}
+ text, _skipped = _git.decode_text_files(ordered, max_total=MAX_CODE_CHARS)
+ return "\n\n".join(f"### {p}\n{t}" for p, t in text.items())
+
+
+def _user_prompt(record: RunRecord, code: str) -> str:
+ kind = {Track.STATIC_OBJECT: "static object", Track.ARTICULATED_OBJECT: "articulated object", Track.SCENE: "scene"}[record.spec.track]
+ return (
+ f"Asset kind: {kind}.\nOriginal user request: {record.spec.prompt}\n\n"
+ f"Source code (raw, may be truncated):\n{code}\n\nReturn the JSON now."
+ )
+
+
+def validate_captions(caps: Captions, language: Language) -> list[str]:
+ """Rule violations (empty list = ok)."""
+ problems = []
+ for field in ("detailed", "instruction", "factory"):
+ m = _FORBIDDEN.search(getattr(caps, field))
+ if m:
+ problems.append(f"{field}: must not mention '{m.group(0)}' (API/platform name)")
+ phrase_words = {Language.BLENDER: "blender", Language.CADQUERY: "cadquery", Language.THREEJS: "three.js",
+ Language.URDF_BLENDER: "urdf", Language.SCENE_THREEJS: "three.js"}[language]
+ if phrase_words not in caps.instruction.lower():
+ problems.append(f"instruction: must name the target language ({LANGUAGE_PHRASE[language]})")
+ return problems
+
+
+def caption_sample(ws: Workspace, record: RunRecord, model_id: str, *, model: object | None = None) -> Captions:
+ """Caption the best round of ``record``; stores into record.extra + captions.json."""
+ if model is None:
+ from codeverse.models import get_chat_model
+
+ model = get_chat_model(model_id)
+ images, used = _round_images(ws, record)
+ code = _code_excerpt(ws, record)
+ if not code and not images:
+ raise CaptionError(f"{ws.root}: no code and no renders to caption")
+ system = _system_prompt().replace("{language_phrase}", LANGUAGE_PHRASE[record.spec.language])
+ user = _user_prompt(record, code)
+ messages = [ChatMessage.user(user, images=images)]
+ schema = Captions.model_json_schema()
+ cost = 0.0
+ caps: Captions | None = None
+ problems: list[str] = []
+ for _attempt in range(2):
+ resp = model.generate(ChatRequest(messages=messages, system=system, response_schema=schema,
+ temperature=0.3, thinking="low", label="captioner")) # type: ignore[attr-defined]
+ cost += resp.usage.cost_usd
+ data = resp.parsed if isinstance(resp.parsed, dict) else _parse_json(resp.text)
+ try:
+ caps = Captions.model_validate(data)
+ except Exception as e:
+ problems = [f"invalid JSON/schema: {e}"]
+ else:
+ problems = validate_captions(caps, record.spec.language)
+ if not problems:
+ break
+ messages = messages + [ChatMessage.assistant(resp.text or json.dumps(data)),
+ ChatMessage.user("Fix these problems and return the JSON again:\n- " + "\n- ".join(problems))]
+ if caps is None or problems:
+ raise CaptionError(f"{ws.root}: captions rejected after retry: {problems}")
+ rnd = best_round_record(record)
+ prov = CaptionProvenance(captioner=model_id, round_index=rnd.index if rnd else None, images_used=used,
+ code_chars=len(code), prompt_hash=prompt_hash(system), cost_usd=cost)
+ record.extra["captions"] = {**caps.model_dump(), "provenance": prov.model_dump(mode="json")}
+ ws.write_json(ws.root / "captions.json", caps.model_dump())
+ ws.write_json(ws.record_path, record)
+ return caps
+
+
+def _parse_json(text: str) -> dict:
+ s = text.strip()
+ if s.startswith("```"):
+ s = s.strip("`")
+ s = s[s.find("{"):]
+ try:
+ return json.loads(s[s.find("{"): s.rfind("}") + 1])
+ except ValueError as e:
+ raise CaptionError(f"captioner returned non-JSON: {text[:200]!r}") from e
diff --git a/harness/codeverse/flywheel/dedupe.py b/harness/codeverse/flywheel/dedupe.py
new file mode 100644
index 00000000..306dd81d
--- /dev/null
+++ b/harness/codeverse/flywheel/dedupe.py
@@ -0,0 +1,142 @@
+"""Near-duplicate detection: code fingerprints + coarse mesh fingerprints.
+
+* ``code_fingerprint(files)`` sha256 of whitespace/comment-normalised code.
+* ``mesh_fingerprint(glb)`` bbox extents (cm), triangle bucket and a 16³ voxel
+ occupancy set computed with trimesh — compare with Jaccard.
+* ``near_duplicates(items)`` union-find groups: identical code fingerprint OR
+ mesh Jaccard ≥ threshold with compatible extents.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import math
+import re
+from collections.abc import Iterable, Mapping
+from pathlib import Path
+
+import numpy as np
+from pydantic import BaseModel, Field
+
+_COMMENT = re.compile(r"^\s*(#|//|\*|/\*).*$")
+_TRAILING_COMMENT = re.compile(r"\s+(#|//).*$")
+VOXEL_RES = 16
+
+
+def normalise_code(text: str) -> str:
+ """Drop comment-only lines, trailing comments, blank lines and all whitespace."""
+ out = []
+ for line in text.splitlines():
+ if _COMMENT.match(line):
+ continue
+ line = _TRAILING_COMMENT.sub("", line)
+ line = re.sub(r"\s+", "", line)
+ if line:
+ out.append(line)
+ return "\n".join(out)
+
+
+def code_fingerprint(files: Mapping[str, str | bytes]) -> str:
+ """Order-independent sha256 over ``(path, normalised code)`` pairs."""
+ h = hashlib.sha256()
+ for path in sorted(files):
+ data = files[path]
+ text = data.decode("utf-8", errors="replace") if isinstance(data, bytes) else data
+ h.update(path.encode())
+ h.update(b"\0")
+ h.update(normalise_code(text).encode())
+ h.update(b"\0")
+ return h.hexdigest()
+
+
+class MeshFingerprint(BaseModel):
+ extents_cm: tuple[int, int, int]
+ tri_count: int
+ tri_bucket: int = Field(description="log2 bucket of the triangle count")
+ voxels: list[int] = Field(description="occupied cell indices in a VOXEL_RES³ grid over the bbox")
+ digest: str
+
+ def jaccard(self, other: MeshFingerprint) -> float:
+ a, b = set(self.voxels), set(other.voxels)
+ if not a and not b:
+ return 1.0
+ return len(a & b) / len(a | b)
+
+ def extents_compatible(self, other: MeshFingerprint, tol: float = 0.1) -> bool:
+ for x, y in zip(self.extents_cm, other.extents_cm, strict=True):
+ if max(x, y) == 0:
+ continue
+ if abs(x - y) / max(x, y) > tol:
+ return False
+ return True
+
+
+def mesh_fingerprint(glb: Path | str, *, res: int = VOXEL_RES, samples: int = 50_000, seed: int = 0) -> MeshFingerprint:
+ """Coarse, pose-sensitive shape fingerprint of a GLB (seeded surface samples → voxel grid).
+
+ Deterministic for identical geometry; near-identical meshes give Jaccard ≈ 1."""
+ import trimesh
+
+ loaded = trimesh.load(str(glb), force="scene")
+ mesh = loaded.to_mesh() if isinstance(loaded, trimesh.Scene) else loaded
+ if mesh is None or mesh.is_empty or len(mesh.faces) == 0:
+ raise ValueError(f"mesh_fingerprint: no triangles in {glb}")
+ ext = mesh.bounding_box.extents
+ pts, _ = trimesh.sample.sample_surface(mesh, samples, seed=seed)
+ lo = mesh.bounds[0]
+ span = np.where(ext > 1e-9, ext, 1.0)
+ idx = np.clip(((pts - lo) / span * res).astype(int), 0, res - 1)
+ cells = sorted(set((idx[:, 0] * res * res + idx[:, 1] * res + idx[:, 2]).tolist()))
+ tri = int(len(mesh.faces))
+ digest = hashlib.sha1(
+ (",".join(map(str, cells)) + f"|{[int(round(e * 100)) for e in ext]}").encode()
+ ).hexdigest()[:16]
+ return MeshFingerprint(
+ extents_cm=tuple(int(round(e * 100)) for e in ext), # type: ignore[arg-type]
+ tri_count=tri,
+ tri_bucket=int(math.log2(max(tri, 1))),
+ voxels=cells,
+ digest=digest,
+ )
+
+
+class DedupeItem(BaseModel):
+ id: str
+ code_fp: str = ""
+ mesh_fp: MeshFingerprint | None = None
+
+
+def near_duplicates(items: Iterable[DedupeItem], *, mesh_threshold: float = 0.9) -> list[list[str]]:
+ """Groups (size ≥ 2) of ids that are exact-code duplicates or near-identical meshes."""
+ items = list(items)
+ parent = {it.id: it.id for it in items}
+
+ def find(x: str) -> str:
+ while parent[x] != x:
+ parent[x] = parent[parent[x]]
+ x = parent[x]
+ return x
+
+ def union(a: str, b: str) -> None:
+ ra, rb = find(a), find(b)
+ if ra != rb:
+ parent[rb] = ra
+
+ by_code: dict[str, str] = {}
+ for it in items:
+ if it.code_fp:
+ if it.code_fp in by_code:
+ union(by_code[it.code_fp], it.id)
+ else:
+ by_code[it.code_fp] = it.id
+ meshed = [it for it in items if it.mesh_fp is not None]
+ for i, a in enumerate(meshed):
+ for b in meshed[i + 1 :]:
+ fa, fb = a.mesh_fp, b.mesh_fp
+ assert fa is not None and fb is not None
+ if fa.extents_compatible(fb) and fa.jaccard(fb) >= mesh_threshold:
+ union(a.id, b.id)
+ groups: dict[str, list[str]] = {}
+ for it in items:
+ groups.setdefault(find(it.id), []).append(it.id)
+ return sorted((sorted(g) for g in groups.values() if len(g) > 1), key=lambda g: g[0])
diff --git a/harness/codeverse/flywheel/export.py b/harness/codeverse/flywheel/export.py
new file mode 100644
index 00000000..c739ed9f
--- /dev/null
+++ b/harness/codeverse/flywheel/export.py
@@ -0,0 +1,221 @@
+"""Export run records → dataset sample folders + ``metadata.parquet``.
+
+``export_samples(runs_dir, out_dir)`` writes one sample folder per run (see
+``sample.py`` for the layout) and then rebuilds the text index from *every*
+``meta.json`` under ``out_dir`` (so repeated exports into the same folder stay
+consistent):
+
+* ``<out>/metadata.parquet`` — STORAGE_RULES §4 columns (``id, key, name,
+ captions{detailed,instruction,factory}, meta_json, code, tar, byte_start,
+ byte_len, n_files``) plus a few queryable extras (``track, language, score,
+ passed, generator``). ``tar``/``byte_*`` are filled by ``pack.py``.
+* ``<out>/metadata.jsonl`` — same rows, one JSON object per line.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import shutil
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.run import RunRecord
+from codeverse.flywheel import sample as S
+from codeverse.flywheel.record import iter_runs
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+PARQUET_NAME = "metadata.parquet"
+JSONL_NAME = "metadata.jsonl"
+CAPTION_KEYS = ("detailed", "instruction", "factory")
+
+
+class ExportReport(BaseModel):
+ n_runs: int = 0
+ n_exported: int = 0
+ n_indexed: int = 0
+ skipped: dict[str, str] = Field(default_factory=dict, description="run dir → reason")
+ exported: list[str] = Field(default_factory=list, description="sample dirs (relative to out_dir)")
+ parquet: str = ""
+ jsonl: str = ""
+
+
+def _captions_of(record: RunRecord) -> dict[str, str]:
+ caps = record.extra.get("captions") or {}
+ return {k: str(caps.get(k, "") or "") for k in CAPTION_KEYS} if caps.get("detailed") else {}
+
+
+def export_one(ws: Workspace, record: RunRecord, out_dir: Path, *, overwrite: bool = True) -> Path:
+ """Write the sample folder for one run; returns the sample dir."""
+ key = S.sample_key(ws)
+ dest = out_dir / S.sample_rel_dir(record, key)
+ rnd = S.best_round_record(record)
+ files, code_source = S.code_files_for_round(ws, rnd)
+ if not files:
+ raise S.SampleError("no code files in src/ (nothing to export)")
+ if dest.exists():
+ if not overwrite:
+ raise S.SampleError(f"sample dir exists: {dest}")
+ shutil.rmtree(dest)
+ dest.mkdir(parents=True)
+ entry, written = S.write_code_tree(dest, files, record.spec.language)
+ if entry not in written:
+ raise S.SampleError(f"entry file {S.ENTRY_BY_LANGUAGE[record.spec.language]} missing at {code_source}")
+ renders = S.copy_renders(ws, rnd, dest)
+ captions = _captions_of(record)
+ (dest / "captions.json").write_text(json.dumps(captions, indent=2, ensure_ascii=False))
+ all_files = sorted(written + renders + ["captions.json", "meta.json"])
+ meta = S.build_meta(
+ ws, record, key=key, entry=entry, files=all_files, renders=renders, rnd=rnd, code_source=code_source
+ )
+ tmp = dest / "meta.json.tmp"
+ tmp.write_text(meta.model_dump_json(indent=2))
+ tmp.replace(dest / "meta.json")
+ return dest
+
+
+def export_samples(
+ runs_dir: Path | str,
+ out_dir: Path | str,
+ *,
+ min_score: float | None = None,
+ only_passed: bool = False,
+ best_round: bool = True,
+ overwrite: bool = True,
+ include_unbuilt: bool = False,
+) -> ExportReport:
+ """Export every eligible run under ``runs_dir`` into ``out_dir`` and rebuild the index.
+
+ ``best_round`` is the only supported selection (kept as a parameter for
+ API stability); the best round is chosen by ``record.best_round`` or the
+ highest judged score. Runs whose best round never built are skipped unless
+ ``include_unbuilt`` (failed runs are still useful for repair pairs, not as
+ dataset samples).
+ """
+ if not best_round:
+ raise ValueError("export_samples: only best_round=True is supported")
+ out = Path(out_dir)
+ out.mkdir(parents=True, exist_ok=True)
+ rep = ExportReport()
+
+ def _bad(d: Path, e: Exception) -> None:
+ rep.skipped[str(d)] = f"invalid record: {e}"
+
+ for ws, rec in iter_runs(runs_dir, on_error=_bad):
+ rep.n_runs += 1
+ rnd = S.best_round_record(rec)
+ score = rnd.score if rnd is not None else None
+ if rnd is None:
+ rep.skipped[str(ws.root)] = "no rounds"
+ continue
+ if not include_unbuilt and not (rnd.build is not None and rnd.build.ok):
+ rep.skipped[str(ws.root)] = "best round did not build"
+ continue
+ if only_passed and not (rnd is not None and rnd.judgment is not None and rnd.judgment.passed):
+ rep.skipped[str(ws.root)] = "not passed"
+ continue
+ if min_score is not None and (score is None or score < min_score):
+ rep.skipped[str(ws.root)] = f"score {score} < min_score {min_score}"
+ continue
+ try:
+ dest = export_one(ws, rec, out, overwrite=overwrite)
+ except S.SampleError as e:
+ rep.skipped[str(ws.root)] = str(e)
+ continue
+ except Exception as e: # git errors etc. — report, keep going
+ rep.skipped[str(ws.root)] = f"{type(e).__name__}: {e}"
+ continue
+ rep.n_exported += 1
+ rep.exported.append(str(dest.relative_to(out)))
+ rows = collect_rows(out)
+ rep.n_indexed = len(rows)
+ rep.parquet = str(write_parquet(rows, out / PARQUET_NAME))
+ rep.jsonl = str(write_jsonl(rows, out / JSONL_NAME))
+ return rep
+
+
+# --------------------------------------------------------------------------- index rows
+def row_for_sample(sample_dir: Path) -> dict[str, Any]:
+ """One parquet row from a sample folder (reads meta.json / captions.json / entry)."""
+ meta_text = (sample_dir / "meta.json").read_text()
+ meta = json.loads(meta_text)
+ caps_path = sample_dir / "captions.json"
+ caps = json.loads(caps_path.read_text()) if caps_path.is_file() else {}
+ entry = sample_dir / meta["entry"]
+ code = entry.read_text(errors="replace") if entry.is_file() else ""
+ n_files = sum(1 for p in sample_dir.rglob("*") if p.is_file())
+ return {
+ "id": meta["id"],
+ "key": meta["key"],
+ "name": meta.get("name", ""),
+ "captions": {k: str(caps.get(k, "") or "") for k in CAPTION_KEYS},
+ "meta_json": meta_text,
+ "code": code,
+ "tar": "",
+ "byte_start": None,
+ "byte_len": None,
+ "n_files": n_files,
+ "track": meta.get("track", ""),
+ "language": meta.get("language", ""),
+ "score": meta.get("score"),
+ "passed": meta.get("passed"),
+ "generator": meta.get("generator", ""),
+ }
+
+
+def collect_rows(out_dir: Path) -> list[dict[str, Any]]:
+ rows = []
+ for meta in sorted(out_dir.rglob("meta.json")):
+ try:
+ rows.append(row_for_sample(meta.parent))
+ except (OSError, ValueError, KeyError) as e:
+ log.warning("skipping %s: %s", meta.parent, e)
+ return rows
+
+
+def parquet_schema() -> Any:
+ import pyarrow as pa
+
+ return pa.schema(
+ [
+ ("id", pa.string()),
+ ("key", pa.string()),
+ ("name", pa.string()),
+ ("captions", pa.struct([(k, pa.string()) for k in CAPTION_KEYS])),
+ ("meta_json", pa.string()),
+ ("code", pa.string()),
+ ("tar", pa.string()),
+ ("byte_start", pa.int64()),
+ ("byte_len", pa.int64()),
+ ("n_files", pa.int32()),
+ ("track", pa.string()),
+ ("language", pa.string()),
+ ("score", pa.float64()),
+ ("passed", pa.bool_()),
+ ("generator", pa.string()),
+ ]
+ )
+
+
+def write_parquet(rows: list[dict[str, Any]], path: Path) -> Path:
+ import pyarrow as pa
+ import pyarrow.parquet as pq
+
+ table = pa.Table.from_pylist(rows, schema=parquet_schema())
+ tmp = path.with_suffix(".parquet.tmp")
+ pq.write_table(table, tmp, compression="zstd")
+ tmp.replace(path)
+ return path
+
+
+def write_jsonl(rows: list[dict[str, Any]], path: Path) -> Path:
+ tmp = path.with_suffix(".jsonl.tmp")
+ with tmp.open("w") as fh:
+ for r in rows:
+ fh.write(json.dumps(r, ensure_ascii=False) + "\n")
+ tmp.replace(path)
+ return path
diff --git a/harness/codeverse/flywheel/index.py b/harness/codeverse/flywheel/index.py
new file mode 100644
index 00000000..a2df76e6
--- /dev/null
+++ b/harness/codeverse/flywheel/index.py
@@ -0,0 +1,137 @@
+"""Small SQLite index over run records (runs / rounds / usage) for dashboards.
+
+``build_index(runs_dir, out_sqlite)`` rebuilds the database from scratch;
+query helpers return plain dicts so a dashboard / notebook needs no ORM.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+from pathlib import Path
+from typing import Any
+
+from codeverse.contracts.run import RoundRecord, RunRecord
+from codeverse.flywheel.pairs import prompt_hash
+from codeverse.flywheel.record import iter_runs
+from codeverse.workspace import Workspace
+
+_SCHEMA = """
+CREATE TABLE runs (
+ slug TEXT PRIMARY KEY, workspace TEXT, track TEXT, language TEXT, prompt TEXT, prompt_hash TEXT,
+ generator TEXT, planner TEXT, judge TEXT, status TEXT,
+ baseline_score REAL, final_score REAL, best_round INTEGER, n_rounds INTEGER, passed INTEGER,
+ cost_usd REAL, input_tokens INTEGER, output_tokens INTEGER,
+ started_at TEXT, finished_at TEXT, duration_s REAL, error TEXT, has_captions INTEGER
+);
+CREATE TABLE rounds (
+ slug TEXT, round_index INTEGER, kind TEXT, commit_sha TEXT, agent_backend TEXT,
+ build_ok INTEGER, gate_errors INTEGER, score REAL, passed INTEGER, n_issues INTEGER,
+ cost_usd REAL, duration_s REAL, started_at TEXT,
+ PRIMARY KEY (slug, round_index)
+);
+CREATE TABLE usage (
+ slug TEXT, round_index INTEGER, role TEXT, backend TEXT, model TEXT,
+ input_tokens INTEGER, output_tokens INTEGER, cached_tokens INTEGER, thoughts_tokens INTEGER,
+ tool_calls INTEGER, cost_usd REAL, latency_ms INTEGER
+);
+CREATE INDEX idx_runs_track ON runs(track, language);
+CREATE INDEX idx_runs_prompt ON runs(prompt_hash);
+CREATE INDEX idx_rounds_slug ON rounds(slug);
+"""
+
+
+def _run_row(ws: Workspace, rec: RunRecord) -> tuple:
+ best = next((r for r in rec.rounds if r.index == rec.best_round), None)
+ passed = None if best is None or best.judgment is None else int(best.judgment.passed)
+ dur = (rec.finished_at - rec.started_at).total_seconds() if rec.finished_at else None
+ return (
+ ws.root.name, str(ws.root), rec.spec.track.value, rec.spec.language.value, rec.spec.prompt,
+ prompt_hash(rec.spec.prompt), rec.spec.backends.generator, rec.spec.backends.planner,
+ rec.spec.backends.judge, rec.status.value, rec.baseline_score, rec.final_score, rec.best_round,
+ len(rec.rounds), passed, rec.total_usage.cost_usd, rec.total_usage.input_tokens,
+ rec.total_usage.output_tokens, rec.started_at.isoformat(),
+ rec.finished_at.isoformat() if rec.finished_at else None, dur, rec.error,
+ int(bool((rec.extra.get("captions") or {}).get("detailed"))),
+ )
+
+
+def _round_row(slug: str, r: RoundRecord) -> tuple:
+ return (
+ slug, r.index, r.kind, r.commit, r.agent_backend,
+ None if r.build is None else int(r.build.ok), sum(len(g.errors) for g in r.gates), r.score,
+ None if r.judgment is None else int(r.judgment.passed), 0 if r.judgment is None else len(r.judgment.issues),
+ r.usage.cost_usd, r.duration_s, r.started_at.isoformat(),
+ )
+
+
+def _usage_rows(slug: str, r: RoundRecord) -> list[tuple]:
+ rows = [(slug, r.index, "agent", r.usage.backend, r.usage.model, r.usage.input_tokens, r.usage.output_tokens,
+ r.usage.cached_tokens, r.usage.thoughts_tokens, r.usage.tool_calls, r.usage.cost_usd, r.usage.latency_ms)]
+ if r.judgment is not None:
+ u = r.judgment.usage
+ rows.append((slug, r.index, "judge", u.backend, u.model, u.input_tokens, u.output_tokens, u.cached_tokens,
+ u.thoughts_tokens, u.tool_calls, u.cost_usd, u.latency_ms))
+ return rows
+
+
+def build_index(runs_dir: Path | str, out_sqlite: Path | str) -> int:
+ """(Re)build the SQLite index; returns the number of runs indexed."""
+ out = Path(out_sqlite)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ tmp = out.with_suffix(out.suffix + ".tmp")
+ if tmp.exists():
+ tmp.unlink()
+ n = 0
+ con = sqlite3.connect(tmp)
+ try:
+ con.executescript(_SCHEMA)
+ for ws, rec in iter_runs(runs_dir):
+ slug = ws.root.name
+ con.execute(f"INSERT INTO runs VALUES ({','.join('?' * 23)})", _run_row(ws, rec))
+ con.executemany(f"INSERT INTO rounds VALUES ({','.join('?' * 13)})", [_round_row(slug, r) for r in rec.rounds])
+ con.executemany(f"INSERT INTO usage VALUES ({','.join('?' * 12)})",
+ [row for r in rec.rounds for row in _usage_rows(slug, r)])
+ n += 1
+ con.commit()
+ finally:
+ con.close()
+ tmp.replace(out)
+ return n
+
+
+# --------------------------------------------------------------------------- queries
+def _connect(db: Path | str) -> sqlite3.Connection:
+ con = sqlite3.connect(f"file:{Path(db)}?mode=ro", uri=True)
+ con.row_factory = sqlite3.Row
+ return con
+
+
+def query(db: Path | str, sql: str, params: tuple = ()) -> list[dict[str, Any]]:
+ con = _connect(db)
+ try:
+ return [dict(r) for r in con.execute(sql, params).fetchall()]
+ finally:
+ con.close()
+
+
+def summary(db: Path | str) -> list[dict[str, Any]]:
+ """Per (track, language, generator): n, pass rate, mean baseline/final, cost."""
+ return query(
+ db,
+ "SELECT track, language, generator, COUNT(*) AS n, AVG(passed) AS pass_rate, "
+ "AVG(baseline_score) AS baseline_mean, AVG(final_score) AS final_mean, "
+ "AVG(final_score - baseline_score) AS delta_mean, SUM(cost_usd) AS cost_usd, "
+ "AVG(n_rounds) AS rounds_mean FROM runs GROUP BY track, language, generator ORDER BY track, language",
+ )
+
+
+def top_runs(db: Path | str, n: int = 20, *, track: str | None = None) -> list[dict[str, Any]]:
+ where = "WHERE track = ?" if track else ""
+ params: tuple = (track, n) if track else (n,)
+ return query(db, f"SELECT slug, track, language, generator, final_score, passed, cost_usd, n_rounds "
+ f"FROM runs {where} ORDER BY final_score DESC LIMIT ?", params)
+
+
+def round_curve(db: Path | str, slug: str) -> list[dict[str, Any]]:
+ return query(db, "SELECT round_index, kind, score, passed, build_ok, gate_errors, cost_usd FROM rounds "
+ "WHERE slug = ? ORDER BY round_index", (slug,))
diff --git a/harness/codeverse/flywheel/pack.py b/harness/codeverse/flywheel/pack.py
new file mode 100644
index 00000000..6ba0ff32
--- /dev/null
+++ b/harness/codeverse/flywheel/pack.py
@@ -0,0 +1,111 @@
+"""Pack exported sample folders into plain ``samples-NNN.tar`` files and fill
+the ``tar / byte_start / byte_len / n_files`` locator columns (STORAGE_RULES §3-4).
+
+Each sample's files are written consecutively so ``byte_start..+byte_len`` is a
+valid sub-tar; ``verify_locators`` round-trips every row.
+"""
+
+from __future__ import annotations
+
+import io
+import json
+import tarfile
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.flywheel.export import (
+ JSONL_NAME,
+ PARQUET_NAME,
+ collect_rows,
+ write_jsonl,
+ write_parquet,
+)
+
+MAX_TAR_BYTES = int(2.5 * 1024**3)
+
+
+class PackError(RuntimeError):
+ pass
+
+
+class PackReport(BaseModel):
+ n_samples: int = 0
+ tars: list[str] = Field(default_factory=list)
+ parquet: str = ""
+
+
+def _sample_dir_for(out_dir: Path, meta: dict[str, Any]) -> Path:
+ return out_dir / meta["track"] / meta["language"] / meta["key"]
+
+
+def pack_samples(out_dir: Path | str, *, tar_prefix: str = "", max_tar_bytes: int = MAX_TAR_BYTES) -> PackReport:
+ """Write ``samples-NNN.tar`` under ``out_dir`` and rewrite the index with locators.
+
+ ``tar_prefix`` is prepended to the tar file name in the ``tar`` column so it
+ can be repo-root-relative (e.g. ``"3dcodeverse/static_object/"``).
+ """
+ out = Path(out_dir)
+ rows = collect_rows(out)
+ if not rows:
+ raise PackError(f"no samples under {out}")
+ rep = PackReport()
+ tar_idx = 0
+ tar: tarfile.TarFile | None = None
+ tar_path: Path | None = None
+
+ def _open_new() -> None:
+ nonlocal tar, tar_path, tar_idx
+ if tar is not None:
+ tar.close()
+ tar_path = out / f"samples-{tar_idx:03d}.tar"
+ tar = tarfile.open(tar_path, mode="w", format=tarfile.PAX_FORMAT)
+ rep.tars.append(tar_path.name)
+ tar_idx += 1
+
+ _open_new()
+ assert tar is not None and tar_path is not None
+ for row in rows:
+ meta = json.loads(row["meta_json"])
+ sdir = _sample_dir_for(out, meta)
+ files = sorted(p for p in sdir.rglob("*") if p.is_file())
+ size = sum(p.stat().st_size for p in files) + 1024 * (len(files) + 1)
+ if tar.offset > 0 and tar.offset + size > max_tar_bytes:
+ _open_new()
+ start = tar.offset
+ for p in files:
+ tar.add(p, arcname=f"{meta['key']}/{p.relative_to(sdir).as_posix()}", recursive=False)
+ row["tar"] = f"{tar_prefix}{tar_path.name}"
+ row["byte_start"] = start
+ row["byte_len"] = tar.offset - start
+ row["n_files"] = len(files)
+ rep.n_samples += 1
+ tar.close()
+ rep.parquet = str(write_parquet(rows, out / PARQUET_NAME))
+ write_jsonl(rows, out / JSONL_NAME)
+ return rep
+
+
+def verify_locators(out_dir: Path | str) -> int:
+ """Round-trip every row's byte range through ``tarfile``; returns rows checked."""
+ out = Path(out_dir)
+ import pyarrow.parquet as pq
+
+ table = pq.read_table(out / PARQUET_NAME).to_pylist()
+ n = 0
+ for row in table:
+ if not row["tar"]:
+ raise PackError(f"row {row['id']} has no tar locator")
+ tpath = out / Path(row["tar"]).name
+ with tpath.open("rb") as fh:
+ fh.seek(row["byte_start"])
+ blob = fh.read(row["byte_len"])
+ members = tarfile.open(fileobj=io.BytesIO(blob), mode="r:").getmembers()
+ files = [m for m in members if m.isfile()]
+ if len(files) != row["n_files"]:
+ raise PackError(f"row {row['id']}: {len(files)} files in range, expected {row['n_files']}")
+ if not all(m.name.startswith(row["key"] + "/") for m in files):
+ raise PackError(f"row {row['id']}: foreign member in byte range")
+ n += 1
+ return n
diff --git a/harness/codeverse/flywheel/pairs.py b/harness/codeverse/flywheel/pairs.py
new file mode 100644
index 00000000..f2c47218
--- /dev/null
+++ b/harness/codeverse/flywheel/pairs.py
@@ -0,0 +1,185 @@
+"""Preference / repair / cross-backend pairs from run records (no model calls).
+
+Output is JSONL, one object per pair. All kinds share::
+
+ {kind, run, prompt, prompt_hash, track, language, generator,
+ chosen: {round, commit, files: {path: code}, score, truncated_files: [...]},
+ rejected: {...}, delta, reason}
+
+* ``preference`` rounds i < j of one run with judge Δ ≥ ``min_delta``; reason =
+ the judge's improvement plan of round i (what the builder was told to fix).
+* ``repair`` a failed build (round k-1) → the ``repair`` round k that builds;
+ ``error`` carries the structured build failure.
+* ``cross_backend`` the same (prompt, track, language) run under ≥ 2 generators;
+ best vs each other candidate with Δ ≥ ``min_delta``.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from collections import defaultdict
+from pathlib import Path
+from typing import Any
+
+from codeverse.contracts.run import RoundRecord, RunRecord
+from codeverse.flywheel import _git
+from codeverse.flywheel.record import iter_runs
+from codeverse.workspace import Workspace
+
+MAX_INLINE_CODE = 200_000
+
+
+def prompt_hash(prompt: str) -> str:
+ return hashlib.sha256(prompt.strip().encode()).hexdigest()[:16]
+
+
+def _side(ws: Workspace, rnd: RoundRecord, *, cache: dict[str, dict[str, Any]]) -> dict[str, Any]:
+ """Inline code (≤ 200 KB) for a round; cached per commit."""
+ key = rnd.commit or f"wt:{rnd.index}"
+ if key not in cache:
+ try:
+ raw = _git.read_tree_at(ws, rnd.commit) if rnd.commit else _git.read_working_tree(ws)
+ except _git.GitReadError:
+ raw = {}
+ text, skipped = _git.decode_text_files(raw, max_total=MAX_INLINE_CODE)
+ cache[key] = {"files": text, "truncated_files": skipped}
+ c = cache[key]
+ return {
+ "round": rnd.index,
+ "kind": rnd.kind,
+ "commit": rnd.commit,
+ "score": rnd.score,
+ "passed": None if rnd.judgment is None else rnd.judgment.passed,
+ "build_ok": None if rnd.build is None else rnd.build.ok,
+ "files": c["files"],
+ "truncated_files": c["truncated_files"],
+ }
+
+
+def _base(ws: Workspace, rec: RunRecord, kind: str) -> dict[str, Any]:
+ return {
+ "kind": kind,
+ "run": ws.root.name,
+ "workspace": str(ws.root),
+ "prompt": rec.spec.prompt,
+ "prompt_hash": prompt_hash(rec.spec.prompt),
+ "track": rec.spec.track.value,
+ "language": rec.spec.language.value,
+ "generator": rec.spec.backends.generator,
+ }
+
+
+def preference_pairs(ws: Workspace, rec: RunRecord, *, min_delta: float) -> list[dict[str, Any]]:
+ cache: dict[str, dict[str, Any]] = {}
+ judged = [r for r in rec.rounds if r.judgment is not None and r.commit]
+ out = []
+ for a_i, lo in enumerate(judged):
+ for hi in judged[a_i + 1 :]:
+ delta = hi.judgment.overall - lo.judgment.overall # type: ignore[union-attr]
+ if delta < min_delta or lo.commit == hi.commit:
+ continue
+ pair = _base(ws, rec, "preference")
+ pair.update(
+ chosen=_side(ws, hi, cache=cache),
+ rejected=_side(ws, lo, cache=cache),
+ delta=round(delta, 4),
+ reason=[it.instruction for it in lo.judgment.improvement_plan], # type: ignore[union-attr]
+ issues=[i.model_dump(mode="json") for i in lo.judgment.issues], # type: ignore[union-attr]
+ )
+ out.append(pair)
+ return out
+
+
+def _error_of(rnd: RoundRecord) -> dict[str, Any]:
+ b = rnd.build
+ if b is None:
+ return {}
+ return {
+ "type": b.error_type,
+ "message": b.error_message,
+ "file": b.error_file,
+ "line": b.error_line,
+ "stderr_tail": b.stderr_tail[-4000:],
+ "stdout_tail": b.stdout_tail[-2000:],
+ "gate_errors": [f.message for g in rnd.gates for f in g.errors],
+ }
+
+
+def repair_pairs(ws: Workspace, rec: RunRecord) -> list[dict[str, Any]]:
+ """(broken round, error) → (repair round that builds)."""
+ cache: dict[str, dict[str, Any]] = {}
+ out = []
+ rounds = rec.rounds
+ for k, rnd in enumerate(rounds):
+ if not rnd.kind.startswith("repair") or rnd.build is None or not rnd.build.ok:
+ continue
+ broken = next((r for r in reversed(rounds[:k]) if r.build is not None and not r.build.ok), None)
+ if broken is None or not broken.commit or not rnd.commit or broken.commit == rnd.commit:
+ continue
+ pair = _base(ws, rec, "repair")
+ pair.update(
+ chosen=_side(ws, rnd, cache=cache),
+ rejected=_side(ws, broken, cache=cache),
+ delta=None,
+ error=_error_of(broken),
+ reason=list(rnd.instructions),
+ )
+ out.append(pair)
+ return out
+
+
+def cross_backend_pairs(groups: dict[tuple[str, str, str], list[tuple[Workspace, RunRecord]]], *, min_delta: float) -> list[dict[str, Any]]:
+ out = []
+ for (_h, _t, _l), runs in groups.items():
+ gens = {r.spec.backends.generator for _, r in runs}
+ if len(gens) < 2:
+ continue
+ cands = []
+ for ws, rec in runs:
+ best = next((r for r in rec.rounds if r.index == rec.best_round), None)
+ if best is None or best.judgment is None:
+ continue
+ cands.append((ws, rec, best))
+ if len(cands) < 2:
+ continue
+ cands.sort(key=lambda c: c[2].judgment.overall, reverse=True) # type: ignore[union-attr]
+ w_ws, w_rec, w_rnd = cands[0]
+ w_side = _side(w_ws, w_rnd, cache={})
+ w_side["generator"] = w_rec.spec.backends.generator
+ for ws, rec, rnd in cands[1:]:
+ delta = w_rnd.judgment.overall - rnd.judgment.overall # type: ignore[union-attr]
+ if rec.spec.backends.generator == w_rec.spec.backends.generator or delta < min_delta:
+ continue
+ pair = _base(w_ws, w_rec, "cross_backend")
+ l_side = _side(ws, rnd, cache={})
+ l_side["generator"] = rec.spec.backends.generator
+ l_side["run"] = ws.root.name
+ pair.update(
+ chosen=w_side, rejected=l_side, delta=round(delta, 4),
+ reason=f"best-of across generators: {w_rec.spec.backends.generator} > {rec.spec.backends.generator}",
+ candidates=[{"run": c[0].root.name, "generator": c[1].spec.backends.generator,
+ "score": c[2].judgment.overall} for c in cands], # type: ignore[union-attr]
+ )
+ out.append(pair)
+ return out
+
+
+def build_pairs(runs_dir: Path | str, out_jsonl: Path | str, *, min_delta: float = 0.05) -> int:
+ """Write all pair kinds for the runs under ``runs_dir``; returns the number written."""
+ out = Path(out_jsonl)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ groups: dict[tuple[str, str, str], list[tuple[Workspace, RunRecord]]] = defaultdict(list)
+ n = 0
+ tmp = out.with_suffix(out.suffix + ".tmp")
+ with tmp.open("w") as fh:
+ for ws, rec in iter_runs(runs_dir):
+ groups[(prompt_hash(rec.spec.prompt), rec.spec.track.value, rec.spec.language.value)].append((ws, rec))
+ for pair in preference_pairs(ws, rec, min_delta=min_delta) + repair_pairs(ws, rec):
+ fh.write(json.dumps(pair, ensure_ascii=False) + "\n")
+ n += 1
+ for pair in cross_backend_pairs(groups, min_delta=min_delta):
+ fh.write(json.dumps(pair, ensure_ascii=False) + "\n")
+ n += 1
+ tmp.replace(out)
+ return n
diff --git a/harness/codeverse/flywheel/record.py b/harness/codeverse/flywheel/record.py
new file mode 100644
index 00000000..cc741740
--- /dev/null
+++ b/harness/codeverse/flywheel/record.py
@@ -0,0 +1,201 @@
+"""Run records: finalise / load / iterate.
+
+``finalize_record`` is the last step of every track run: it fills the
+environment (tool versions + harness git sha), derives best/baseline/final
+scores and totals when the track left them empty, adds a compact per-round
+summary under ``record.extra["rounds_summary"]`` and writes ``record.json``
+atomically.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import platform
+import subprocess
+from collections.abc import Callable, Iterator
+from datetime import UTC, datetime
+from functools import lru_cache
+from pathlib import Path
+from typing import Any
+
+from codeverse import __version__
+from codeverse.config import get_settings
+from codeverse.contracts.common import Usage
+from codeverse.contracts.run import RoundRecord, RunRecord
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+_VERSION_TIMEOUT_S = 30
+
+
+class RecordError(RuntimeError):
+ """A record.json is missing or invalid."""
+
+
+# --------------------------------------------------------------------------- environment
+def _cmd_first_line(cmd: list[str]) -> str:
+ try:
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=_VERSION_TIMEOUT_S, check=False)
+ except (OSError, subprocess.TimeoutExpired) as e:
+ return f"error: {type(e).__name__}"
+ out = (proc.stdout or proc.stderr).strip().splitlines()
+ return out[0].strip() if out else f"exit {proc.returncode}"
+
+
+def _harness_git_sha() -> str:
+ repo = Path(__file__).resolve().parents[2]
+ if not (repo / ".git").exists():
+ return ""
+ try:
+ proc = subprocess.run(
+ ["git", "-C", str(repo), "rev-parse", "HEAD"], capture_output=True, text=True, timeout=10, check=False
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return ""
+ return proc.stdout.strip() if proc.returncode == 0 else ""
+
+
+def _three_version() -> str:
+ pkg = get_settings().runtime_js_dir() / "node_modules" / "three" / "package.json"
+ if not pkg.is_file():
+ return ""
+ try:
+ return str(json.loads(pkg.read_text()).get("version", ""))
+ except (OSError, ValueError):
+ return ""
+
+
+@lru_cache(maxsize=1)
+def environment_versions() -> dict[str, str]:
+ """Tool versions + harness provenance. Cached per process (Blender is slow to ask)."""
+ s = get_settings()
+ env: dict[str, str] = {
+ "python": platform.python_version(),
+ "codeverse": __version__,
+ "platform": platform.platform(),
+ "host": platform.node(),
+ "harness_git_sha": _harness_git_sha(),
+ }
+ blender = s.resolve_blender()
+ env["blender"] = _cmd_first_line([blender, "--version"]) if blender else ""
+ env["blender_path"] = blender
+ env["node"] = _cmd_first_line([s.binaries.node, "--version"])
+ env["three"] = _three_version()
+ return env
+
+
+# --------------------------------------------------------------------------- derived fields
+def best_round_index(record: RunRecord) -> int | None:
+ """The round to export: ``record.best_round`` when valid, else the highest
+ judged score (ties → fewer gate errors), else the last round with a
+ successful build, else the last round."""
+ by_index = {r.index: r for r in record.rounds}
+ if record.best_round is not None and record.best_round in by_index:
+ return record.best_round
+ if not record.rounds:
+ return None
+ judged = [r for r in record.rounds if r.judgment is not None]
+ if judged:
+ best = max(judged, key=lambda r: (r.judgment.overall, -_n_gate_errors(r), r.index)) # type: ignore[union-attr]
+ return best.index
+ built = [r for r in record.rounds if r.build is not None and r.build.ok]
+ if built:
+ return built[-1].index
+ return record.rounds[-1].index
+
+
+def _n_gate_errors(r: RoundRecord) -> int:
+ return sum(len(g.errors) for g in r.gates)
+
+
+def round_summary(r: RoundRecord) -> dict[str, Any]:
+ """Compact per-round digest (for record.extra, dashboards and the CLI)."""
+ return {
+ "index": r.index,
+ "kind": r.kind,
+ "commit": r.commit[:12],
+ "agent_backend": r.agent_backend,
+ "build_ok": None if r.build is None else r.build.ok,
+ "gate_errors": _n_gate_errors(r),
+ "score": r.score,
+ "passed": None if r.judgment is None else r.judgment.passed,
+ "issues": 0 if r.judgment is None else len(r.judgment.issues),
+ "cost_usd": round(r.usage.cost_usd, 6),
+ "duration_s": round(r.duration_s, 1),
+ }
+
+
+def _sum_usage(rounds: list[RoundRecord]) -> Usage:
+ total = Usage()
+ for r in rounds:
+ total = total + r.usage
+ if r.judgment is not None:
+ total = total + r.judgment.usage
+ return total
+
+
+def fill_derived(record: RunRecord) -> RunRecord:
+ """Fill best/baseline/final/total_usage/finished_at/environment when absent."""
+ if record.best_round is None:
+ record.best_round = best_round_index(record)
+ scored = [r for r in record.rounds if r.score is not None]
+ if record.baseline_score is None and scored:
+ record.baseline_score = scored[0].score
+ if record.final_score is None and record.best_round is not None:
+ best = next((r for r in record.rounds if r.index == record.best_round), None)
+ record.final_score = best.score if best else None
+ if record.total_usage.cost_usd == 0 and record.total_usage.input_tokens == 0 and record.rounds:
+ record.total_usage = _sum_usage(record.rounds)
+ if record.finished_at is None:
+ record.finished_at = datetime.now(UTC)
+ env = dict(environment_versions())
+ env.update(record.environment) # the track's own entries win
+ record.environment = env
+ record.extra["rounds_summary"] = [round_summary(r) for r in record.rounds]
+ return record
+
+
+# --------------------------------------------------------------------------- io
+def finalize_record(ws: Workspace, record: RunRecord) -> Path:
+ """Fill derived fields + environment and write ``record.json`` atomically."""
+ record.workspace = record.workspace or str(ws.root)
+ fill_derived(record)
+ ws.write_json(ws.record_path, record)
+ return ws.record_path
+
+
+def load_record(ws: Workspace | Path | str) -> RunRecord:
+ ws = ws if isinstance(ws, Workspace) else Workspace(ws)
+ if not ws.record_path.is_file():
+ raise RecordError(f"no record.json in {ws.root}")
+ try:
+ return RunRecord.model_validate_json(ws.record_path.read_text())
+ except Exception as e: # pydantic ValidationError / JSON error
+ raise RecordError(f"invalid record.json in {ws.root}: {e}") from e
+
+
+def iter_runs(
+ runs_dir: Path | str, *, on_error: Callable[[Path, Exception], None] | None = None
+) -> Iterator[tuple[Workspace, RunRecord]]:
+ """Yield ``(Workspace, RunRecord)`` for every run directory holding a record.json.
+
+ Invalid records raise ``RecordError`` unless ``on_error`` is given, in which
+ case it is called and iteration continues (exporters collect skip reasons).
+ """
+ root = Path(runs_dir)
+ if not root.is_dir():
+ raise FileNotFoundError(f"runs dir not found: {root}")
+ for d in sorted(p for p in root.iterdir() if p.is_dir()):
+ if not (d / "record.json").is_file():
+ continue
+ ws = Workspace(d)
+ try:
+ rec = load_record(ws)
+ except RecordError as e:
+ if on_error is None:
+ raise
+ on_error(d, e)
+ continue
+ yield ws, rec
diff --git a/harness/codeverse/flywheel/sample.py b/harness/codeverse/flywheel/sample.py
new file mode 100644
index 00000000..022f665d
--- /dev/null
+++ b/harness/codeverse/flywheel/sample.py
@@ -0,0 +1,242 @@
+"""One dataset sample from one run: typed ``meta.json`` + folder layout.
+
+Sample folder (STORAGE_RULES §3/§8 compatible)::
+
+ <out>/<track>/<language>/<key>/
+ code.<ext> copy of the entry file (parquet ``code`` column)
+ src/** the full raw code tree at the exported commit (lossless)
+ robot.urdf (urdf_blender) copy of src/robot.urdf
+ meta.json SampleMeta (typed, below)
+ captions.json {detailed, instruction, factory} or {} when not captioned
+ renders/ view_*.png, sheet.png, turntable.mp4, object.glb (< 20 MB)
+"""
+
+from __future__ import annotations
+
+import shutil
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse import __version__
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.run import RoundRecord, RunRecord
+from codeverse.flywheel import _git
+from codeverse.flywheel.record import best_round_index
+from codeverse.workspace import Workspace
+
+#: entry file inside src/ per language
+ENTRY_BY_LANGUAGE: dict[Language, str] = {
+ Language.BLENDER: "src/model.py",
+ Language.CADQUERY: "src/model.py",
+ Language.URDF_BLENDER: "src/model.py",
+ Language.THREEJS: "src/object.js",
+ Language.SCENE_THREEJS: "src/scene.js",
+}
+#: top-level copy of the entry (``code.<ext>``)
+CODE_FILE_BY_LANGUAGE: dict[Language, str] = {
+ Language.BLENDER: "code.py",
+ Language.CADQUERY: "code.py",
+ Language.URDF_BLENDER: "code.py",
+ Language.THREEJS: "code.js",
+ Language.SCENE_THREEJS: "code.js",
+}
+LANGUAGE_LABEL: dict[Language, str] = {
+ Language.BLENDER: "Blender Python",
+ Language.CADQUERY: "CadQuery (Python)",
+ Language.URDF_BLENDER: "URDF + Blender Python",
+ Language.THREEJS: "Three.js (ESM)",
+ Language.SCENE_THREEJS: "Three.js scene (multi-file ESM + GLSL)",
+}
+TYPE_LABEL: dict[Track, str] = {
+ Track.STATIC_OBJECT: "3D Objects",
+ Track.ARTICULATED_OBJECT: "Articulated Objects",
+ Track.SCENE: "3D Scenes",
+}
+MAX_GLB_BYTES = 20 * 1024 * 1024
+SOURCE_NAME = "3dcodeverse"
+SAMPLE_LICENSE = "CC-BY-4.0"
+
+
+class SampleError(RuntimeError):
+ """The run cannot be turned into a sample (no code, no commit, ...)."""
+
+
+class SampleMeta(BaseModel):
+ """``meta.json`` — everything a consumer needs without opening record.json."""
+
+ id: str
+ key: str
+ name: str
+ type: str
+ track: str
+ language: str
+ language_label: str
+ entry: str
+ multi_file: bool
+ files: list[str] = Field(description="all files in the sample folder (relative)")
+ renders: list[str] = Field(default_factory=list)
+ environment: dict[str, str] = Field(default_factory=dict)
+ source: str = SOURCE_NAME
+ source_run: str = ""
+ license: str = SAMPLE_LICENSE
+ harness_version: str = __version__
+ prompt: str
+ constraints: dict[str, Any] = Field(default_factory=dict)
+ tags: list[str] = Field(default_factory=list)
+ generator: str = ""
+ planner: str = ""
+ judge_backend: str = ""
+ judge_rubric: str = ""
+ score: float | None = None
+ passed: bool | None = None
+ baseline_score: float | None = None
+ acceptance_results: dict[str, bool] = Field(default_factory=dict)
+ rounds: int = 0
+ best_round: int | None = None
+ code_commit: str = ""
+ code_source: str = Field(default="commit", description="commit | working_tree")
+ status: str = ""
+ cost_usd: float = 0.0
+ usage: dict[str, Any] = Field(default_factory=dict)
+ created_at: datetime
+ finished_at: datetime | None = None
+ has_captions: bool = False
+ captioner: str = ""
+ prompt_hashes: dict[str, str] = Field(default_factory=dict)
+
+
+def sample_key(ws: Workspace) -> str:
+ return ws.root.name
+
+
+def sample_id(record: RunRecord, key: str) -> str:
+ return f"{SOURCE_NAME}/{record.spec.track.value}/{record.spec.language.value}/{key}"
+
+
+def sample_rel_dir(record: RunRecord, key: str) -> Path:
+ return Path(record.spec.track.value) / record.spec.language.value / key
+
+
+def _resolve(ws: Workspace, p: str | None) -> Path | None:
+ if not p:
+ return None
+ path = Path(p)
+ if not path.is_absolute():
+ path = ws.root / path
+ return path if path.is_file() else None
+
+
+def code_files_for_round(ws: Workspace, rnd: RoundRecord | None) -> tuple[dict[str, bytes], str]:
+ """Raw code tree for a round → ``(files, source)`` where source is
+ ``commit`` or ``working_tree`` (fallback when the round has no usable commit)."""
+ if rnd is not None and rnd.commit and _git.commit_exists(ws, rnd.commit):
+ return _git.read_tree_at(ws, rnd.commit), "commit"
+ return _git.read_working_tree(ws), "working_tree"
+
+
+def write_code_tree(dest: Path, files: dict[str, bytes], language: Language) -> tuple[str, list[str]]:
+ """Write ``src/**`` + ``code.<ext>`` (+ ``robot.urdf``); return (entry, written paths)."""
+ written: list[str] = []
+ for rel, data in sorted(files.items()):
+ p = dest / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_bytes(data)
+ written.append(rel)
+ entry_src = ENTRY_BY_LANGUAGE[language]
+ code_name = CODE_FILE_BY_LANGUAGE[language]
+ if entry_src in files:
+ (dest / code_name).write_bytes(files[entry_src])
+ written.append(code_name)
+ if language is Language.URDF_BLENDER and "src/robot.urdf" in files:
+ (dest / "robot.urdf").write_bytes(files["src/robot.urdf"])
+ written.append("robot.urdf")
+ return code_name, written
+
+
+def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str]:
+ """Copy the round's views, contact sheet, turntable and a small object.glb."""
+ out: list[str] = []
+ rdir = dest / "renders"
+ rdir.mkdir(parents=True, exist_ok=True)
+
+ def _cp(src: Path | None, name: str) -> None:
+ if src is None:
+ return
+ shutil.copy2(src, rdir / name)
+ out.append(f"renders/{name}")
+
+ if rnd is not None and rnd.renders is not None:
+ for v in rnd.renders.views:
+ src = _resolve(ws, v.path)
+ if src is not None:
+ suffix = src.suffix or ".png"
+ _cp(src, f"view_{v.name}{suffix}")
+ sheet = _resolve(ws, rnd.renders.contact_sheet)
+ if sheet is not None:
+ _cp(sheet, f"sheet{sheet.suffix or '.png'}")
+ tt = _resolve(ws, rnd.renders.turntable)
+ if tt is not None:
+ _cp(tt, f"turntable{tt.suffix or '.mp4'}")
+ glb = ws.artifacts / "object.glb"
+ if glb.is_file() and glb.stat().st_size < MAX_GLB_BYTES:
+ _cp(glb, "object.glb")
+ return out
+
+
+def build_meta(
+ ws: Workspace, record: RunRecord, *, key: str, entry: str, files: list[str], renders: list[str],
+ rnd: RoundRecord | None, code_source: str,
+) -> SampleMeta:
+ spec = record.spec
+ j = rnd.judgment if rnd is not None else None
+ caps = record.extra.get("captions") or {}
+ code_files = [f for f in files if f.startswith("src/")]
+ name = ""
+ if record.plan is not None:
+ name = getattr(record.plan, "object_name", "") or getattr(record.plan, "title", "")
+ return SampleMeta(
+ id=sample_id(record, key),
+ key=key,
+ name=name,
+ type=TYPE_LABEL[spec.track],
+ track=spec.track.value,
+ language=spec.language.value,
+ language_label=LANGUAGE_LABEL[spec.language],
+ entry=entry,
+ multi_file=len(code_files) > 1,
+ files=sorted(files),
+ renders=sorted(renders),
+ environment=dict(record.environment),
+ source_run=str(ws.root),
+ prompt=spec.prompt,
+ constraints=spec.constraints.model_dump(mode="json", exclude_none=True),
+ tags=list(spec.tags),
+ generator=spec.backends.generator,
+ planner=spec.backends.planner,
+ judge_backend=(j.judge_backend if j else "") or spec.backends.judge,
+ judge_rubric=j.rubric if j else "",
+ score=j.overall if j else None,
+ passed=j.passed if j else None,
+ baseline_score=record.baseline_score,
+ acceptance_results=dict(j.acceptance_results) if j else {},
+ rounds=len(record.rounds),
+ best_round=rnd.index if rnd is not None else None,
+ code_commit=rnd.commit if rnd is not None else "",
+ code_source=code_source,
+ status=record.status.value,
+ cost_usd=round(record.total_usage.cost_usd, 6),
+ usage=record.total_usage.model_dump(mode="json"),
+ created_at=spec.created_at,
+ finished_at=record.finished_at,
+ has_captions=bool(caps.get("detailed")),
+ captioner=str((caps.get("provenance") or {}).get("captioner", "")),
+ prompt_hashes=dict(record.prompt_hashes),
+ )
+
+
+def best_round_record(record: RunRecord) -> RoundRecord | None:
+ idx = best_round_index(record)
+ return next((r for r in record.rounds if r.index == idx), None)
diff --git a/harness/codeverse/judges/__init__.py b/harness/codeverse/judges/__init__.py
new file mode 100644
index 00000000..927534d7
--- /dev/null
+++ b/harness/codeverse/judges/__init__.py
@@ -0,0 +1 @@
+"""Judges: VLM rubric judge, pairwise judge, reference-fidelity judge, metrics."""
diff --git a/harness/codeverse/judges/base.py b/harness/codeverse/judges/base.py
new file mode 100644
index 00000000..955e0eb5
--- /dev/null
+++ b/harness/codeverse/judges/base.py
@@ -0,0 +1,30 @@
+"""Judge protocol + inputs."""
+
+from __future__ import annotations
+
+from typing import Protocol
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import GateReport, Measurement, RenderSet
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.contracts.spec import Spec
+
+
+class JudgeInput(BaseModel):
+ spec: Spec
+ renders: RenderSet
+ measurement: Measurement | None = None
+ gates: list[GateReport] = Field(default_factory=list)
+ acceptance: list[AcceptanceItem] = Field(default_factory=list)
+ plan_summary: str = Field(default="", description="short plan digest (parts/zones/joints) for grounding")
+ round_index: int = 0
+ previous: Judgment | None = Field(default=None, description="last verdict (for delta framing)")
+ extra_context: str = ""
+
+
+class Judge(Protocol):
+ name: str
+
+ def judge(self, inp: JudgeInput) -> Judgment: ...
diff --git a/harness/codeverse/judges/caps.py b/harness/codeverse/judges/caps.py
new file mode 100644
index 00000000..9bf609d2
--- /dev/null
+++ b/harness/codeverse/judges/caps.py
@@ -0,0 +1,105 @@
+"""Deterministic caps: bound the overall score from gate findings / acceptance.
+
+The VLM never sees or computes these. ``apply_caps`` returns the capped overall
+and a ledger of which rules fired and why, so the verdict is auditable.
+"""
+
+from __future__ import annotations
+
+from fnmatch import fnmatch
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.judges.rubrics import CapRule, Rubric
+
+_SEV_RANK = {Severity.INFO: 0, Severity.WARN: 1, Severity.ERROR: 2}
+
+
+class CapApplied(BaseModel):
+ rule: str
+ cap: float
+ evidence: str = Field(description="which finding / acceptance item triggered it")
+
+
+class CapResult(BaseModel):
+ overall: float
+ caps_applied: list[CapApplied] = Field(default_factory=list)
+
+ @property
+ def capped(self) -> bool:
+ return bool(self.caps_applied)
+
+
+def _finding_tokens(f: GateFinding) -> str:
+ """Searchable lower-cased text for a finding: data.kind / data.code / message / target."""
+ bits = [str(f.data.get("kind", "")), str(f.data.get("code", "")), f.message, f.target or ""]
+ return " ".join(bits).lower()
+
+
+def _finding_matches(rule: CapRule, report: GateReport, f: GateFinding) -> bool:
+ if not fnmatch(report.gate, rule.gate) and not fnmatch(f.gate, rule.gate):
+ return False
+ if _SEV_RANK[f.severity] < _SEV_RANK[rule.severity]:
+ return False
+ if rule.kinds:
+ text = _finding_tokens(f)
+ return any(k.lower() in text for k in rule.kinds)
+ return True
+
+
+def missing_must_items(
+ acceptance_items: list[AcceptanceItem], acceptance_results: dict[str, bool]
+) -> list[str]:
+ """Ids of ``must`` acceptance items that are not verified (missing counts as failed)."""
+ return [a.id for a in acceptance_items if a.priority == "must" and not acceptance_results.get(a.id, False)]
+
+
+def apply_caps(
+ rubric: Rubric,
+ overall: float,
+ gates: list[GateReport],
+ acceptance_results: dict[str, bool],
+ acceptance_items: list[AcceptanceItem] | None = None,
+ *,
+ console_errors: list[str] | None = None,
+) -> CapResult:
+ """Apply every rubric cap rule; the overall becomes ``min(overall, caps...)``.
+
+ Only the first matching finding per rule is recorded as evidence (one ledger
+ line per rule), but all rules are evaluated.
+ """
+ applied: list[CapApplied] = []
+ for rule in rubric.caps:
+ evidence = _rule_evidence(rule, gates, acceptance_results, acceptance_items or [], console_errors or [])
+ if evidence is not None:
+ applied.append(CapApplied(rule=rule.id, cap=rule.cap, evidence=evidence))
+ capped = overall
+ for a in applied:
+ capped = min(capped, a.cap)
+ return CapResult(overall=max(0.0, min(1.0, capped)), caps_applied=applied)
+
+
+def _rule_evidence(
+ rule: CapRule,
+ gates: list[GateReport],
+ acceptance_results: dict[str, bool],
+ acceptance_items: list[AcceptanceItem],
+ console_errors: list[str],
+) -> str | None:
+ if rule.when == "acceptance":
+ missing = missing_must_items(acceptance_items, acceptance_results)
+ if missing:
+ return f"must items not verified: {', '.join(missing[:6])}"
+ return None
+ if rule.when == "console":
+ if console_errors:
+ return f"{len(console_errors)} console error(s); first: {console_errors[0][:160]}"
+ return None
+ for report in gates:
+ for f in report.findings:
+ if _finding_matches(rule, report, f):
+ target = f" [{f.target}]" if f.target else ""
+ return f"{report.gate}{target}: {f.message[:200]}"
+ return None
diff --git a/harness/codeverse/judges/images.py b/harness/codeverse/judges/images.py
new file mode 100644
index 00000000..b7571adf
--- /dev/null
+++ b/harness/codeverse/judges/images.py
@@ -0,0 +1,126 @@
+"""Judge image preparation: downscale, label strips, caching, view geometry.
+
+Every image sent to a judge goes through ``prepare_image`` so the token cost is
+bounded (≤ ``max_px`` on the long side) and every view carries a burnt-in label
+(``VIEW 3/8 — front · az 0° el 8°``) that the model can cite as evidence.
+Prepared files are cached under ``<cache_dir>/<sha>.png`` keyed by source path,
+mtime, size, max_px and label text.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import math
+from pathlib import Path
+
+from PIL import Image, ImageDraw, ImageFont
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import RenderView
+from codeverse.contracts.chat import ImagePart
+from codeverse.conventions import OBJECT_VIEWS, SCENE_VIEWS, ViewPreset
+
+_PRESETS: dict[str, ViewPreset] = {v.name: v for v in (*OBJECT_VIEWS, *SCENE_VIEWS)}
+
+
+class JudgeImageError(FileNotFoundError):
+ """A render referenced by a RenderSet is missing or unreadable."""
+
+
+def default_cache_dir() -> Path:
+ return get_settings().cache_dir / "judge_images"
+
+
+def view_az_el(view: RenderView) -> tuple[float, float] | None:
+ """Azimuth/elevation (deg) of a view: from the preset name, else from camera geometry (Y-up)."""
+ if view.name in _PRESETS:
+ p = _PRESETS[view.name]
+ return p.azimuth_deg, p.elevation_deg
+ if view.camera_position is not None:
+ cx, cy, cz = view.camera_position
+ lx, ly, lz = view.look_at or (0.0, 0.0, 0.0)
+ dx, dy, dz = cx - lx, cy - ly, cz - lz
+ horiz = math.hypot(dx, dz)
+ if horiz < 1e-9 and abs(dy) < 1e-9:
+ return None
+ az = math.degrees(math.atan2(dx, dz)) % 360.0 # 0 = +Z front, CCW from above
+ el = math.degrees(math.atan2(dy, horiz))
+ return round(az, 1), round(el, 1)
+ return None
+
+
+def view_label(view: RenderView, index: int, total: int) -> str:
+ """``VIEW 3/8 — front · az 0° el 8°`` (+ ``t=1.5s`` / mode when relevant)."""
+ bits = [f"VIEW {index}/{total} — {view.name}"]
+ azel = view_az_el(view)
+ if azel is not None:
+ bits.append(f"az {azel[0]:.0f}° el {azel[1]:.0f}°")
+ if view.mode and view.mode != "shaded":
+ bits.append(view.mode)
+ if view.time_s is not None:
+ bits.append(f"t={view.time_s:g}s")
+ return " · ".join(bits)
+
+
+def _font(size: int) -> ImageFont.ImageFont | ImageFont.FreeTypeFont:
+ for cand in ("DejaVuSans-Bold.ttf", "DejaVuSans.ttf", "Arial.ttf"):
+ try:
+ return ImageFont.truetype(cand, size)
+ except OSError:
+ continue
+ return ImageFont.load_default()
+
+
+def _cache_key(src: Path, max_px: int, label: str) -> str:
+ st = src.stat()
+ h = hashlib.sha1(f"{src.resolve()}|{st.st_mtime_ns}|{st.st_size}|{max_px}|{label}".encode())
+ return h.hexdigest()[:20]
+
+
+def prepare_image(
+ src: str | Path, *, label: str = "", max_px: int = 768, cache_dir: Path | None = None
+) -> Path:
+ """Downscale ``src`` to ≤ ``max_px`` on its long side and burn ``label`` into a top strip.
+
+ Returns the cached PNG path. Raises ``JudgeImageError`` if the source is missing.
+ """
+ src = Path(src)
+ if not src.is_file():
+ raise JudgeImageError(f"judge image missing: {src}")
+ cache = Path(cache_dir) if cache_dir else default_cache_dir()
+ cache.mkdir(parents=True, exist_ok=True)
+ out = cache / f"{_cache_key(src, max_px, label)}.png"
+ if out.is_file():
+ return out
+ with Image.open(src) as im:
+ im = im.convert("RGB")
+ w, h = im.size
+ scale = min(1.0, max_px / max(w, h))
+ if scale < 1.0:
+ im = im.resize((max(1, round(w * scale)), max(1, round(h * scale))), Image.LANCZOS)
+ if label:
+ im = _with_label_strip(im, label)
+ tmp = out.with_suffix(".tmp.png")
+ im.save(tmp, format="PNG", optimize=True)
+ tmp.replace(out)
+ return out
+
+
+def _with_label_strip(im: Image.Image, label: str) -> Image.Image:
+ w, h = im.size
+ strip_h = max(22, int(h * 0.055))
+ font = _font(max(12, int(strip_h * 0.62)))
+ canvas = Image.new("RGB", (w, h + strip_h), (18, 18, 22))
+ canvas.paste(im, (0, strip_h))
+ draw = ImageDraw.Draw(canvas)
+ text = label
+ # truncate to fit
+ while text and draw.textlength(text, font=font) > w - 12 and len(text) > 8:
+ text = text[:-2]
+ font_px = getattr(font, "size", 11)
+ draw.text((6, max(2, (strip_h - font_px) // 2)), text, fill=(245, 245, 240), font=font)
+ return canvas
+
+
+def image_part(path: Path, label: str) -> ImagePart:
+ return ImagePart(path=str(path), mime="image/png", label=label)
diff --git a/harness/codeverse/judges/metrics.py b/harness/codeverse/judges/metrics.py
new file mode 100644
index 00000000..73a5e2bf
--- /dev/null
+++ b/harness/codeverse/judges/metrics.py
@@ -0,0 +1,60 @@
+"""Small, pure helpers over judgments and round scores (no I/O, no models)."""
+
+from __future__ import annotations
+
+import statistics
+from collections.abc import Sequence
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.judgment import Judgment
+
+
+class Agreement(BaseModel):
+ mean: float
+ std: float
+ per_criterion_std: dict[str, float] = Field(default_factory=dict)
+ n: int
+
+
+def judge_agreement(judgments: Sequence[Judgment]) -> Agreement:
+ """Mean/std of ``overall`` and per-criterion std across repeated judgments of the same thing."""
+ if not judgments:
+ raise ValueError("judge_agreement needs at least one judgment")
+ overalls = [j.overall for j in judgments]
+ crit: dict[str, list[float]] = {}
+ for j in judgments:
+ for k, v in j.scores.items():
+ crit.setdefault(k, []).append(float(v))
+ return Agreement(
+ mean=round(statistics.fmean(overalls), 4),
+ std=round(statistics.pstdev(overalls), 4) if len(overalls) > 1 else 0.0,
+ per_criterion_std={k: (round(statistics.pstdev(v), 4) if len(v) > 1 else 0.0) for k, v in crit.items()},
+ n=len(judgments),
+ )
+
+
+def plateau(scores: Sequence[float], window: int = 2, min_delta: float = 0.02) -> bool:
+ """True when the best of the last ``window`` scores did not beat the best before them by ≥ ``min_delta``.
+
+ Needs at least ``window + 1`` scores; fewer → False (keep going).
+ """
+ if window < 1:
+ raise ValueError("window must be ≥ 1")
+ if len(scores) < window + 1:
+ return False
+ before = max(scores[:-window])
+ recent = max(scores[-window:])
+ return (recent - before) < min_delta
+
+
+def best_index(rounds: Sequence[tuple[float, int]]) -> int:
+ """Index of the best round: higher score, tie → fewer errors, tie → later round."""
+ if not rounds:
+ raise ValueError("best_index needs at least one round")
+ best = 0
+ for i, (score, n_err) in enumerate(rounds):
+ bs, be = rounds[best]
+ if score > bs or (score == bs and n_err < be) or (score == bs and n_err == be):
+ best = i
+ return best
diff --git a/harness/codeverse/judges/output_schema.py b/harness/codeverse/judges/output_schema.py
new file mode 100644
index 00000000..fe9f71d1
--- /dev/null
+++ b/harness/codeverse/judges/output_schema.py
@@ -0,0 +1,194 @@
+"""The judge's wire format: a pydantic model built per rubric (+ acceptance ids).
+
+The model forces the VLM to score EVERY visual criterion and to answer EVERY
+acceptance item; ``overall`` is deliberately absent — it is computed in code.
+Parsing is lenient about shape (dict-of-records or list-of-records, fenced
+JSON in plain text) but strict about content: a missing criterion is a
+``JudgeParseError`` so the caller can retry instead of scoring a hole as 0.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Any
+
+from pydantic import BaseModel, Field, ValidationError, create_model
+
+from codeverse.contracts.judgment import ImprovementItem, JudgeIssue
+from codeverse.judges.rubrics import Rubric
+
+
+class JudgeParseError(ValueError):
+ """The model's reply could not be turned into a complete JudgeOutput."""
+
+
+class CriterionScore(BaseModel):
+ score: float = Field(ge=0.0, le=1.0, description="0..1 against the anchors")
+ evidence: str = Field(description="what you saw, citing VIEW labels / measurements")
+
+
+class AcceptanceVerdict(BaseModel):
+ verified: bool = Field(description="true only if the renders/measurements prove it")
+ evidence: str = Field(default="", description="which view / number proves or disproves it")
+
+
+class JudgeOutput(BaseModel):
+ """Provider-neutral parsed judge reply (criteria + acceptance as dicts)."""
+
+ criteria: dict[str, CriterionScore]
+ summary: str = ""
+ strengths: list[str] = Field(default_factory=list)
+ issues: list[JudgeIssue] = Field(default_factory=list)
+ improvement_plan: list[ImprovementItem] = Field(default_factory=list)
+ acceptance: dict[str, AcceptanceVerdict] = Field(default_factory=dict)
+
+ @property
+ def scores(self) -> dict[str, float]:
+ return {k: v.score for k, v in self.criteria.items()}
+
+ @property
+ def acceptance_bools(self) -> dict[str, bool]:
+ return {k: v.verified for k, v in self.acceptance.items()}
+
+
+def build_wire_model(rubric: Rubric, acceptance_ids: list[str]) -> type[BaseModel]:
+ """A pydantic model whose ``criteria`` / ``acceptance`` objects have FIXED keys.
+
+ Criterion ids are valid identifiers (enforced by the rubric). Acceptance ids
+ are arbitrary strings → fields ``acc_<i>`` aliased to the id.
+ """
+ crit_fields: dict[str, Any] = {
+ c.id: (CriterionScore, Field(description=f"{c.label}: {c.description.strip()[:200]}"))
+ for c in rubric.visual_criteria()
+ }
+ Criteria = create_model("Criteria", **crit_fields)
+ fields: dict[str, Any] = {
+ "criteria": (Criteria, Field(description="one entry per criterion id")),
+ "summary": (str, Field(description="2-4 sentences: what it is, what is right, what is most wrong")),
+ "strengths": (list[str], Field(default_factory=list, description="≤ 5 short bullets")),
+ "issues": (list[JudgeIssue], Field(default_factory=list, description="observable defects, most severe first")),
+ "improvement_plan": (
+ list[ImprovementItem],
+ Field(default_factory=list, description="≤ 6 concrete instructions for the builder, priority 1 first"),
+ ),
+ }
+ if acceptance_ids:
+ acc_fields: dict[str, Any] = {
+ f"acc_{i}": (AcceptanceVerdict, Field(alias=aid, description=f"acceptance item {aid}"))
+ for i, aid in enumerate(acceptance_ids)
+ }
+ Acceptance = create_model("Acceptance", **acc_fields)
+ fields["acceptance"] = (Acceptance, Field(description="one entry per acceptance item id"))
+ return create_model("JudgeReply", **fields)
+
+
+def wire_schema(rubric: Rubric, acceptance_ids: list[str]) -> dict[str, Any]:
+ return build_wire_model(rubric, acceptance_ids).model_json_schema(by_alias=True)
+
+
+# --------------------------------------------------------------------------- parsing
+_FENCE = re.compile(r"```(?:json)?\s*(.*?)```", re.DOTALL)
+
+
+def extract_json(text: str) -> Any:
+ """Parse JSON from a reply: raw, fenced, or the first balanced ``{...}`` block."""
+ text = text.strip()
+ for cand in (text, *(m.strip() for m in _FENCE.findall(text))):
+ try:
+ return json.loads(cand)
+ except json.JSONDecodeError:
+ continue
+ start = text.find("{")
+ if start >= 0:
+ depth = 0
+ for i, ch in enumerate(text[start:], start):
+ if ch == "{":
+ depth += 1
+ elif ch == "}":
+ depth -= 1
+ if depth == 0:
+ try:
+ return json.loads(text[start : i + 1])
+ except json.JSONDecodeError:
+ break
+ raise JudgeParseError(f"no JSON object in reply (first 200 chars): {text[:200]!r}")
+
+
+def _records_to_dict(value: Any, key_names: tuple[str, ...]) -> dict[str, Any]:
+ """Accept ``{id: {...}}`` or ``[{id: ..., ...}, ...]`` and return ``{id: {...}}``."""
+ if isinstance(value, dict):
+ return value
+ if isinstance(value, list):
+ out: dict[str, Any] = {}
+ for rec in value:
+ if not isinstance(rec, dict):
+ raise JudgeParseError(f"record is not an object: {rec!r}")
+ key = next((rec[k] for k in key_names if k in rec), None)
+ if key is None:
+ raise JudgeParseError(f"record lacks an id field {key_names}: {rec!r}")
+ out[str(key)] = {k: v for k, v in rec.items() if k not in key_names}
+ return out
+ raise JudgeParseError(f"expected object or list, got {type(value).__name__}")
+
+
+def _coerce_acceptance(value: Any) -> dict[str, Any]:
+ recs = _records_to_dict(value, ("id", "item_id", "item"))
+ out: dict[str, Any] = {}
+ for k, v in recs.items():
+ if isinstance(v, bool):
+ out[k] = {"verified": v, "evidence": ""}
+ elif isinstance(v, dict):
+ vv = dict(v)
+ if "verified" not in vv and "passed" in vv:
+ vv["verified"] = vv.pop("passed")
+ out[k] = vv
+ else:
+ raise JudgeParseError(f"acceptance item {k!r}: unexpected value {v!r}")
+ return out
+
+
+def parse_judge_output(
+ payload: Any, rubric: Rubric, acceptance_ids: list[str], *, measured_scores: dict[str, float] | None = None
+) -> JudgeOutput:
+ """Validate a parsed reply (dict) or raw text into a complete ``JudgeOutput``.
+
+ ``measured_scores`` (criterion id → score) are injected for ``kind: measured``
+ criteria so the output always covers the full rubric.
+ """
+ if isinstance(payload, str):
+ payload = extract_json(payload)
+ if not isinstance(payload, dict):
+ raise JudgeParseError(f"reply is not a JSON object: {type(payload).__name__}")
+ data = dict(payload)
+ if "criteria" not in data and "per_criterion" in data:
+ data["criteria"] = data.pop("per_criterion")
+ try:
+ criteria = _records_to_dict(data.get("criteria", {}), ("id", "criterion", "name"))
+ criteria = {
+ k: ({"score": v, "evidence": ""} if isinstance(v, (int, float)) else v) for k, v in criteria.items()
+ }
+ acceptance = _coerce_acceptance(data.get("acceptance", {}))
+ out = JudgeOutput(
+ criteria=criteria,
+ summary=str(data.get("summary", "") or ""),
+ strengths=[str(s) for s in data.get("strengths", []) or []],
+ issues=data.get("issues", []) or [],
+ improvement_plan=data.get("improvement_plan", []) or [],
+ acceptance=acceptance,
+ )
+ except ValidationError as e:
+ raise JudgeParseError(f"judge reply failed validation: {e}") from e
+ measured = measured_scores or {}
+ for cid, s in measured.items():
+ out.criteria[cid] = CriterionScore(score=max(0.0, min(1.0, float(s))), evidence="measured in code")
+ missing = [c.id for c in rubric.criteria if c.id not in out.criteria]
+ if missing:
+ raise JudgeParseError(f"judge reply missing criteria {missing}")
+ extra = [k for k in out.criteria if k not in rubric.weights]
+ for k in extra: # unknown criteria are ignored, not scored
+ out.criteria.pop(k)
+ missing_acc = [a for a in acceptance_ids if a not in out.acceptance]
+ for a in missing_acc: # unanswered acceptance items count as NOT verified
+ out.acceptance[a] = AcceptanceVerdict(verified=False, evidence="not answered by judge")
+ return out
diff --git a/harness/codeverse/judges/pairwise.py b/harness/codeverse/judges/pairwise.py
new file mode 100644
index 00000000..d8b41342
--- /dev/null
+++ b/harness/codeverse/judges/pairwise.py
@@ -0,0 +1,187 @@
+"""``PairwiseJudge``: which of two candidates better satisfies the spec?
+
+Position bias is real, so the comparison runs TWICE with A/B swapped; the
+winner is declared only when both orderings agree, otherwise ``tie``. Each
+call sees the brief, the rubric's criteria (titles + descriptions) and each
+candidate's contact sheet (or up to 4 views when there is no sheet).
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+import statistics
+from pathlib import Path
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import RenderSet
+from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart, TextPart
+from codeverse.contracts.common import Usage
+from codeverse.contracts.spec import Spec
+from codeverse.judges.images import image_part, prepare_image, view_label
+from codeverse.judges.output_schema import JudgeParseError, extract_json
+from codeverse.judges.prompt_builder import brief_section
+from codeverse.judges.rubrics import Rubric, load_rubric
+from codeverse.models.base import ChatModel, ModelError
+
+log = logging.getLogger(__name__)
+
+Winner = Literal["a", "b", "tie"]
+
+
+class CriterionWinner(BaseModel):
+ criterion: str
+ winner: Literal["A", "B", "tie"]
+
+
+class PairwiseReply(BaseModel):
+ """Wire schema for one ordering (lists, not dicts: provider schemas dislike free-form keys)."""
+
+ winner: Literal["A", "B", "tie"] = Field(description="which candidate better satisfies the brief overall")
+ confidence: float = Field(ge=0.0, le=1.0, description="0.5 = coin flip, 1.0 = certain")
+ reasons: list[str] = Field(description="2-5 short, evidence-based reasons citing candidate and view")
+ criteria_won: list[CriterionWinner] = Field(default_factory=list, description="one entry per rubric criterion")
+
+
+class PairwiseResult(BaseModel):
+ winner: Winner
+ confidence: float = Field(ge=0.0, le=1.0)
+ reasons: list[str] = Field(default_factory=list)
+ orderings: list[dict] = Field(default_factory=list, description="per-ordering raw verdicts (mapped to a/b)")
+ usage: Usage = Field(default_factory=Usage)
+ error: str = ""
+
+
+_SYSTEM = """You are a BLIND comparative judge for a 3D-code harness. You see a brief, a rubric and renders of TWO candidates, labelled A and B. Decide which candidate better satisfies the brief, judging ONLY what is visible. Position carries no information: A is not better for being first.
+Compare criterion by criterion (intent, structure, detail, proportions, fit, materials, cleanliness as listed), then decide overall. Prefer the candidate with no major defect over the one with more detail but a floating or broken part. Say 'tie' only when the two are genuinely equivalent. Reply with one JSON object: winner ('A'|'B'|'tie'), confidence 0..1, reasons[], criteria_won[{criterion, winner}]."""
+
+
+class PairwiseJudge:
+ name = "pairwise"
+
+ def __init__(
+ self,
+ model_id: str | None = None,
+ *,
+ temperature: float = 0.2,
+ max_px: int = 768,
+ views_per_side: int = 4,
+ chat_model: ChatModel | None = None,
+ cache_dir: Path | None = None,
+ ):
+ self.model_id = model_id or get_settings().default_judge
+ self.temperature = temperature
+ self.max_px = max_px
+ self.views_per_side = views_per_side
+ self._model = chat_model
+ self.cache_dir = cache_dir
+
+ @property
+ def model(self) -> ChatModel:
+ if self._model is None:
+ from codeverse.models import get_chat_model
+
+ self._model = get_chat_model(self.model_id)
+ return self._model
+
+ # ------------------------------------------------------------------ API
+ def compare(
+ self, spec: Spec, renders_a: RenderSet, renders_b: RenderSet, *, rubric: str | Rubric = "static_object_v1"
+ ) -> PairwiseResult:
+ rub = rubric if isinstance(rubric, Rubric) else load_rubric(rubric)
+ usage = Usage()
+ verdicts: list[tuple[Winner, float, list[str]]] = []
+ orderings: list[dict] = []
+ errors: list[str] = []
+ for swapped in (False, True):
+ first, second = (renders_b, renders_a) if swapped else (renders_a, renders_b)
+ req = self._request(spec, rub, first, second)
+ try:
+ resp = self.model.generate(req)
+ except ModelError as e:
+ errors.append(f"ModelError: {e}")
+ continue
+ usage = usage + resp.usage
+ try:
+ payload = resp.parsed if resp.parsed is not None else extract_json(resp.text)
+ reply = PairwiseReply.model_validate(payload)
+ except (JudgeParseError, ValueError) as e:
+ errors.append(f"parse: {e}")
+ continue
+ winner = _map_winner(reply.winner, swapped)
+ reasons = [_unswap_text(r, swapped) for r in reply.reasons]
+ verdicts.append((winner, reply.confidence, reasons))
+ orderings.append({"swapped": swapped, "winner": winner, "confidence": reply.confidence,
+ "reasons": reasons,
+ "criteria_won": {c.criterion: _map_winner(c.winner, swapped) for c in reply.criteria_won}})
+ if not verdicts:
+ return PairwiseResult(winner="tie", confidence=0.0, usage=usage, error=" || ".join(errors))
+ return _combine(verdicts, orderings, usage, errors)
+
+ # ------------------------------------------------------------------ prompt
+ def _request(self, spec: Spec, rub: Rubric, first: RenderSet, second: RenderSet) -> ChatRequest:
+ crit = "\n".join(f"- {c.id}: {c.description.strip()}" for c in rub.visual_criteria())
+ text = (
+ brief_section(spec)
+ + "\n\nCRITERIA (from rubric " + rub.name + "):\n" + crit
+ + "\n\nImages follow: CANDIDATE A first, then CANDIDATE B. Each image is labelled."
+ )
+ parts: list[TextPart | ImagePart] = [TextPart(text=text)]
+ for tag, rs in (("A", first), ("B", second)):
+ for lbl, ip in self._side_images(tag, rs):
+ parts.append(TextPart(text=lbl))
+ parts.append(ip)
+ parts.append(TextPart(text="Compare A and B and return the JSON object."))
+ return ChatRequest(
+ messages=[ChatMessage(role="user", parts=parts)], system=_SYSTEM,
+ response_schema=PairwiseReply.model_json_schema(), temperature=self.temperature, label="pairwise",
+ )
+
+ def _side_images(self, tag: str, rs: RenderSet) -> list[tuple[str, ImagePart]]:
+ out: list[tuple[str, ImagePart]] = []
+ if rs.contact_sheet:
+ lbl = f"CANDIDATE {tag} — contact sheet ({len(rs.views)} views)"
+ out.append((lbl, image_part(prepare_image(rs.contact_sheet, label=lbl, max_px=max(self.max_px, 1024), cache_dir=self.cache_dir), lbl)))
+ return out
+ views = rs.views[: self.views_per_side]
+ for i, v in enumerate(views, 1):
+ lbl = f"CANDIDATE {tag} — " + view_label(v, i, len(views))
+ out.append((lbl, image_part(prepare_image(v.path, label=lbl, max_px=self.max_px, cache_dir=self.cache_dir), lbl)))
+ return out
+
+
+_CAND = re.compile(r"\b([Cc]andidate)\s+([AB])\b")
+
+
+def _unswap_text(text: str, swapped: bool) -> str:
+ """Rewrite 'Candidate A/B' mentions from a swapped ordering back to the caller's a/b labels."""
+ if not swapped:
+ return text
+ return _CAND.sub(lambda m: f"{m.group(1)} {'B' if m.group(2) == 'A' else 'A'}", text)
+
+
+def _map_winner(w: str, swapped: bool) -> Winner:
+ if w == "tie":
+ return "tie"
+ if not swapped:
+ return "a" if w == "A" else "b"
+ return "b" if w == "A" else "a"
+
+
+def _combine(
+ verdicts: list[tuple[Winner, float, list[str]]], orderings: list[dict], usage: Usage, errors: list[str]
+) -> PairwiseResult:
+ winners = {v[0] for v in verdicts}
+ reasons = [r for v in verdicts for r in v[2]][:8]
+ conf = statistics.fmean(v[1] for v in verdicts)
+ if len(verdicts) == 1: # only one ordering succeeded → downgrade confidence, keep winner
+ return PairwiseResult(winner=verdicts[0][0], confidence=round(conf * 0.5, 3), reasons=reasons,
+ orderings=orderings, usage=usage, error=" || ".join(errors))
+ if len(winners) == 1:
+ return PairwiseResult(winner=verdicts[0][0], confidence=round(conf, 3), reasons=reasons, orderings=orderings, usage=usage)
+ # disagreement (position bias or genuine ambiguity) → tie, low confidence
+ return PairwiseResult(winner="tie", confidence=round(min(0.4, 1.0 - conf), 3), reasons=reasons, orderings=orderings,
+ usage=usage, error="orderings disagree")
diff --git a/harness/codeverse/judges/prompt_builder.py b/harness/codeverse/judges/prompt_builder.py
new file mode 100644
index 00000000..108bfe55
--- /dev/null
+++ b/harness/codeverse/judges/prompt_builder.py
@@ -0,0 +1,278 @@
+"""Build the judge conversation: system (role + rubric + output rules) and ONE
+user message (brief, plan digest, acceptance checklist, measurement table, gate
+digest, previous-verdict framing, view-rig paragraph, then labelled images).
+
+Text is budgeted to ≈6k tokens; images to ≤ ``max_images`` at ≤ ``max_px``.
+The builder's code and reasoning are never included (blind judge).
+"""
+
+from __future__ import annotations
+
+import random
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+from codeverse.contracts.artifacts import GateReport, Measurement, RenderSet, RenderView, Severity
+from codeverse.contracts.chat import ChatMessage, ImagePart, TextPart
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.contracts.spec import Spec
+from codeverse.judges.images import image_part, prepare_image, view_label
+from codeverse.judges.rubrics import Rubric
+
+if TYPE_CHECKING: # pragma: no cover
+ from codeverse.judges.base import JudgeInput
+
+TEXT_BUDGET_CHARS = 24_000 # ≈ 6k tokens
+MAX_IMAGES = 10
+MAX_PX = 768
+
+_ROLE = """You are the BLIND JUDGE of a 3D-code harness: exacting but fair.
+You see only the brief, a plan digest, measured numbers, deterministic gate findings and labelled renders of the result — never the builder's code or reasoning. Judge what is visible and measured; do not invent faults and do not credit what you cannot see.
+
+SCORING RULES
+- Score each criterion 0..1 against its anchors (interpolate between anchors). Use the whole range: competent work sits at 0.8+, one clearly visible major defect pulls the affected criterion to ~0.4, broken work sits at 0.1-0.3. Do not compress everything into 0.5-0.7.
+- Every score needs evidence that cites the VIEW label(s) and/or the measurement that shows it (e.g. "VIEW 4 (right): rear leg ends 3 cm above ground; measurement ground_gap 0.03").
+- Do NOT compute an overall or decide pass/fail; the harness computes the weighted overall, applies floors and caps.
+- Issues: observable defects, most severe first, with target = the part / zone / joint / asset name from the plan digest (or "overall"), a kind, a severity and evidence.
+- Improvement plan: at most 6 concrete, imperative instructions for the builder ("taper the four legs from 45 mm at the seat to 30 mm at the foot and extend them to touch y=0"), priority 1 first, each with a target name from the plan digest and an expected_gain estimate. Give items even for passing work if a named change would raise the score; leave empty only when nothing would.
+- Acceptance items: answer verified=true ONLY when the renders or measurements prove the item; otherwise false with what is missing.
+- Reply with ONE JSON object matching the requested schema; no prose outside it."""
+
+
+def _rubric_block(rubric: Rubric) -> str:
+ lines = [f"RUBRIC {rubric.name} v{rubric.version} (pass threshold {rubric.pass_threshold:.2f}, for information only)"]
+ for i, c in enumerate(rubric.criteria, 1):
+ if c.kind == "measured":
+ lines.append(f"{i}. {c.id} (weight {c.weight:.2f}) — MEASURED BY THE HARNESS, shown for calibration; do not score it.")
+ continue
+ floor = f", hard floor {c.floor:.2f}" if c.floor is not None else ""
+ lines.append(f"{i}. {c.id} (weight {c.weight:.2f}{floor}) — {c.label}: {c.description.strip()}")
+ for lvl in ("1.0", "0.7", "0.4", "0.1"):
+ lines.append(f" {lvl}: {c.anchors[lvl]}")
+ if rubric.extra_instructions.strip():
+ lines.append("")
+ lines.append("RUBRIC NOTES: " + rubric.extra_instructions.strip())
+ return "\n".join(lines)
+
+
+def build_system_prompt(rubric: Rubric) -> str:
+ return _ROLE + "\n\n" + _rubric_block(rubric)
+
+
+# --------------------------------------------------------------------------- text sections
+def _clip(text: str, limit: int) -> str:
+ text = text.strip()
+ return text if len(text) <= limit else text[: limit - 12].rstrip() + " …[clipped]"
+
+
+def brief_section(spec: Spec) -> str:
+ lines = [f"BRIEF (track {spec.track.value}, language {spec.language.value}):", _clip(spec.prompt, 3000)]
+ c = spec.constraints
+ cons = []
+ if c.dimensions_m:
+ cons.append("dimensions_m: " + ", ".join(f"{k}={v:g}" for k, v in c.dimensions_m.items()))
+ if c.max_triangles:
+ cons.append(f"max_triangles: {c.max_triangles}")
+ if c.style:
+ cons.append(f"style: {c.style}")
+ if c.must_have:
+ cons.append("must_have: " + "; ".join(c.must_have))
+ if c.must_not:
+ cons.append("must_not: " + "; ".join(c.must_not))
+ if cons:
+ lines.append("CONSTRAINTS: " + " | ".join(cons))
+ return "\n".join(lines)
+
+
+def acceptance_section(items: list[AcceptanceItem]) -> str:
+ if not items:
+ return "ACCEPTANCE CHECKLIST: (none)"
+ lines = ["ACCEPTANCE CHECKLIST (answer every id):"]
+ for a in items[:40]:
+ lines.append(f"- {a.id} [{a.priority}, via {a.how}]: {_clip(a.text, 240)}")
+ if len(items) > 40:
+ lines.append(f"- … {len(items) - 40} more items omitted")
+ return "\n".join(lines)
+
+
+def measurement_section(m: Measurement | None) -> str:
+ if m is None:
+ return "MEASUREMENTS: (none available)"
+ try:
+ from codeverse.spatial.measure import measure_summary_table # type: ignore[attr-defined]
+ except (ImportError, AttributeError):
+ measure_summary_table = None
+ if measure_summary_table is not None:
+ return "MEASUREMENTS (harness, Y-up meters):\n" + _clip(str(measure_summary_table(m)), 6000)
+ return "MEASUREMENTS (harness, Y-up meters):\n" + _local_measure_table(m)
+
+
+def _fmt3(v: tuple[float, float, float]) -> str:
+ return f"({v[0]:.3f}, {v[1]:.3f}, {v[2]:.3f})"
+
+
+def _local_measure_table(m: Measurement) -> str:
+ ex = m.extents
+ lines = [
+ f"overall extents x/y/z = {ex[0]:.3f} × {ex[1]:.3f} × {ex[2]:.3f} m; bbox min {_fmt3(m.bbox_min)} max {_fmt3(m.bbox_max)}; centre {_fmt3(m.center)}",
+ f"triangles {m.tri_count}; meshes {m.n_meshes}; islands {m.n_islands}; materials {m.materials}; ground_gap {m.ground_gap_m:+.4f} m; footprint_offset {m.footprint_offset_m:.4f} m",
+ ]
+ if m.parts:
+ lines.append("part | size x×y×z (m) | min y | tris | islands | watertight")
+ for p in m.parts[:40]:
+ sx, sy, sz = (p.bbox_max[i] - p.bbox_min[i] for i in range(3))
+ wt = "-" if p.watertight is None else ("yes" if p.watertight else "no")
+ lines.append(f"{p.name} | {sx:.3f}×{sy:.3f}×{sz:.3f} | {p.bbox_min[1]:.3f} | {p.tri_count} | {p.islands} | {wt}")
+ if len(m.parts) > 40:
+ lines.append(f"… {len(m.parts) - 40} more parts")
+ for k, v in list(m.extra.items())[:8]:
+ lines.append(f"{k}: {_clip(str(v), 200)}")
+ return "\n".join(lines)
+
+
+def gates_section(gates: list[GateReport], *, max_errors: int = 12, max_warns: int = 8) -> str:
+ if not gates:
+ return "GATE FINDINGS: (no gates run)"
+ errs, warns = [], []
+ for g in gates:
+ for f in g.findings:
+ tgt = f" [{f.target}]" if f.target else ""
+ line = f"- {g.gate}{tgt}: {_clip(f.message, 220)}"
+ (errs if f.severity == Severity.ERROR else warns if f.severity == Severity.WARN else []).append(line)
+ status = ", ".join(f"{g.gate}={'pass' if g.passed else 'FAIL'}" for g in gates)
+ lines = [f"GATE FINDINGS (deterministic; treat as facts): {status}"]
+ if errs:
+ lines.append(f"errors ({len(errs)}):")
+ lines.extend(errs[:max_errors])
+ if len(errs) > max_errors:
+ lines.append(f"- … {len(errs) - max_errors} more errors")
+ if warns:
+ lines.append(f"warnings ({len(warns)}):")
+ lines.extend(warns[:max_warns])
+ if len(warns) > max_warns:
+ lines.append(f"- … {len(warns) - max_warns} more warnings")
+ if not errs and not warns:
+ lines.append("no errors or warnings — parts are connected and contracts hold.")
+ return "\n".join(lines)
+
+
+def previous_section(prev: Judgment | None, round_index: int) -> str:
+ if prev is None:
+ return ""
+ lines = [
+ f"PREVIOUS VERDICT (round {max(round_index - 1, 0)}): overall {prev.overall:.2f}, "
+ f"{'passed' if prev.passed else 'not passed'}. The builder was then asked to:"
+ ]
+ for it in prev.improvement_plan[:6]:
+ lines.append(f"- [{it.target}/{it.kind}] {_clip(it.instruction, 200)}")
+ if not prev.improvement_plan:
+ lines.append("- (no plan items)")
+ lines.append(
+ "Judge THIS round on its own merits (do not anchor on the old numbers), but say in the summary which of "
+ "those items are now fixed, which are STILL present, and whether anything regressed."
+ )
+ return "\n".join(lines)
+
+
+def view_rig_section(renders: RenderSet, n_views: int, *, scene: bool) -> str:
+ bits = [
+ "VIEW RIG: the first image is a CONTACT SHEET of all views (tiles are labelled); it is followed by the individual views, each with a burnt-in label 'VIEW k/N — name · az/el'." if renders.contact_sheet else
+ "VIEW RIG: each image carries a burnt-in label 'VIEW k/N — name · az/el'.",
+ "Azimuth 0° = looking at the FRONT of the object, increasing counter-clockwise seen from above (90° = the object's right side, 180° = back); elevation is degrees above the horizon (negative = looking up from below the ground plane, which reveals undersides and ground contact).",
+ ]
+ if scene:
+ bits.append("Views named overview_* are harness cameras fitted to the scene bounds (layout X-ray); views named cam_* are the scene's own authored cameras (grade composition/lighting on those); 't=' is the animation time.")
+ else:
+ bits.append("All views show the same object; cite the view label when you report a defect. Use top + low views for symmetry, footprint and ground contact.")
+ if renders.console_errors:
+ bits.append(f"PROBE: {len(renders.console_errors)} console error(s) during rendering, first: {_clip(renders.console_errors[0], 200)}")
+ if renders.fps is not None:
+ bits.append(f"PROBE: measured {renders.fps:.0f} fps.")
+ bits.append(f"{n_views} view(s) follow.")
+ return "\n".join(bits)
+
+
+# --------------------------------------------------------------------------- images
+def select_views(views: list[RenderView], max_views: int, *, shuffle_seed: int | None) -> list[RenderView]:
+ """Evenly sub-sample to ``max_views`` (keeps rig diversity) then optionally shuffle the order."""
+ chosen = list(views)
+ if len(chosen) > max_views:
+ step = len(chosen) / max_views
+ chosen = [chosen[int(i * step)] for i in range(max_views)]
+ if shuffle_seed is not None:
+ random.Random(shuffle_seed).shuffle(chosen)
+ return chosen
+
+
+def image_parts_for_renders(
+ renders: RenderSet,
+ *,
+ max_images: int = MAX_IMAGES,
+ max_px: int = MAX_PX,
+ shuffle_seed: int | None = None,
+ cache_dir: Path | None = None,
+ reserved: int = 0,
+) -> tuple[list[tuple[str, ImagePart]], list[RenderView]]:
+ """(label, ImagePart) pairs: contact sheet first, then labelled views; plus the chosen views."""
+ budget = max_images - reserved
+ out: list[tuple[str, ImagePart]] = []
+ if renders.contact_sheet and budget > 0:
+ lbl = f"CONTACT SHEET — all {len(renders.views)} views"
+ out.append((lbl, image_part(prepare_image(renders.contact_sheet, label=lbl, max_px=max(max_px, 1024), cache_dir=cache_dir), lbl)))
+ budget -= 1
+ chosen = select_views(renders.views, max(budget, 0), shuffle_seed=shuffle_seed)
+ n = len(chosen)
+ for i, v in enumerate(chosen, 1):
+ lbl = view_label(v, i, n)
+ out.append((lbl, image_part(prepare_image(v.path, label=lbl, max_px=max_px, cache_dir=cache_dir), lbl)))
+ return out, chosen
+
+
+# --------------------------------------------------------------------------- assembly
+def build_judge_messages(
+ inp: JudgeInput,
+ rubric: Rubric,
+ *,
+ shuffle_seed: int | None = None,
+ max_images: int = MAX_IMAGES,
+ max_px: int = MAX_PX,
+ cache_dir: Path | None = None,
+ extra_images: list[tuple[str, str | Path]] | None = None,
+ extra_text: str = "",
+) -> tuple[str, list[ChatMessage]]:
+ """Return ``(system, [user_message])`` for a rubric judge call.
+
+ ``extra_images`` (label, path) are placed BEFORE the renders (e.g. reference
+ images); ``extra_text`` is appended to the text block (e.g. measured silhouette).
+ """
+ system = build_system_prompt(rubric)
+ is_scene = inp.spec.track.value == "scene"
+ sections = [
+ brief_section(inp.spec),
+ ("PLAN DIGEST:\n" + _clip(inp.plan_summary, 5000)) if inp.plan_summary.strip() else "PLAN DIGEST: (none)",
+ acceptance_section(inp.acceptance),
+ measurement_section(inp.measurement),
+ gates_section(inp.gates),
+ previous_section(inp.previous, inp.round_index),
+ _clip(inp.extra_context, 2500) if inp.extra_context.strip() else "",
+ _clip(extra_text, 2500) if extra_text.strip() else "",
+ ]
+ extras = extra_images or []
+ images, chosen = image_parts_for_renders(
+ inp.renders, max_images=max_images, max_px=max_px, shuffle_seed=shuffle_seed, cache_dir=cache_dir,
+ reserved=len(extras),
+ )
+ sections.append(view_rig_section(inp.renders, len(chosen), scene=is_scene))
+ text = "\n\n".join(s for s in sections if s)
+ if len(text) > TEXT_BUDGET_CHARS:
+ text = _clip(text, TEXT_BUDGET_CHARS)
+ parts: list[TextPart | ImagePart] = [TextPart(text=text)]
+ for lbl, p in extras:
+ parts.append(TextPart(text=lbl))
+ parts.append(image_part(prepare_image(p, label=lbl, max_px=max_px, cache_dir=cache_dir), lbl))
+ for lbl, ip in images:
+ parts.append(TextPart(text=lbl))
+ parts.append(ip)
+ parts.append(TextPart(text="Now score every criterion with evidence, answer every acceptance item, and return the JSON object."))
+ return system, [ChatMessage(role="user", parts=parts)]
diff --git a/harness/codeverse/judges/reference.py b/harness/codeverse/judges/reference.py
new file mode 100644
index 00000000..2df59fc1
--- /dev/null
+++ b/harness/codeverse/judges/reference.py
@@ -0,0 +1,110 @@
+"""``ReferenceJudge``: image-conditioned judging (rubric ``reference_v1``).
+
+Adds the spec's reference images BEFORE the renders (labelled ``REFERENCE k``)
+and scores ``silhouette_match`` IN CODE from the front-render-vs-reference
+outline IoU (``codeverse.spatial.silhouette.compare_silhouette`` when present)
+— the VLM only scores the perceptual criteria.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+from codeverse.contracts.artifacts import RenderView
+from codeverse.judges.base import JudgeInput
+from codeverse.judges.rubrics import Rubric
+from codeverse.judges.vlm_judge import JudgeContext, VlmJudge
+
+log = logging.getLogger(__name__)
+
+SilhouetteFn = Callable[[str, str], dict[str, Any]]
+
+#: IoU → score mapping: ≤ 0.25 → 0, ≥ 0.85 → 1, linear in between (matches the rubric anchors).
+IOU_LOW, IOU_HIGH = 0.25, 0.85
+
+
+def iou_to_score(iou: float) -> float:
+ return max(0.0, min(1.0, (float(iou) - IOU_LOW) / (IOU_HIGH - IOU_LOW)))
+
+
+def _default_silhouette_fn() -> SilhouetteFn | None:
+ try:
+ from codeverse.spatial.silhouette import compare_silhouette # type: ignore[attr-defined]
+ except (ImportError, AttributeError):
+ return None
+ return compare_silhouette
+
+
+class ReferenceJudge(VlmJudge):
+ """VlmJudge + reference images + measured silhouette criterion."""
+
+ name = "reference"
+
+ def __init__(
+ self,
+ model_id: str | None = None,
+ n_samples: int = 1,
+ temperature: float = 0.2,
+ *,
+ rubric: str | Rubric = "reference_v1",
+ silhouette_fn: SilhouetteFn | None = None,
+ front_view_names: tuple[str, ...] = ("front", "front_right_34"),
+ **kwargs: Any,
+ ):
+ super().__init__(rubric, model_id, n_samples, temperature, **kwargs)
+ self.silhouette_fn = silhouette_fn or _default_silhouette_fn()
+ self.front_view_names = front_view_names
+
+ # ------------------------------------------------------------------ hook
+ def context(self, inp: JudgeInput) -> JudgeContext:
+ refs = [r for r in inp.spec.references if Path(r.path).is_file()]
+ images: list[tuple[str, str]] = []
+ for i, r in enumerate(refs[:3], 1):
+ note = f" — {r.note}" if r.note else ""
+ images.append((f"REFERENCE {i}/{min(len(refs), 3)} ({r.role}){note}", r.path))
+ measured_ids = [c.id for c in self.rubric.measured_criteria()]
+ if not measured_ids:
+ return JudgeContext(extra_images=images)
+ info = self.measure_silhouette(inp)
+ if "iou" not in info:
+ raise ReferenceJudgeError(f"cannot score measured criteria {measured_ids}: {info.get('error', 'no iou')}")
+ score = iou_to_score(info["iou"])
+ text = (
+ f"MEASURED SILHOUETTE (harness): front render {info['render']} vs reference {info['reference']}: "
+ f"IoU {info['iou']:.3f} → silhouette_match score {score:.2f}."
+ + (f" extra: {info['extra']}" if info.get("extra") else "")
+ )
+ return JudgeContext(measured_scores={cid: score for cid in measured_ids}, extra_text=text, extra_images=images)
+
+ # ------------------------------------------------------------------ silhouette
+ def pick_front_view(self, views: list[RenderView]) -> RenderView | None:
+ for name in self.front_view_names:
+ for v in views:
+ if v.name == name:
+ return v
+ return views[0] if views else None
+
+ def measure_silhouette(self, inp: JudgeInput) -> dict[str, Any]:
+ """{iou, render, reference, extra} or {error}."""
+ targets = [r for r in inp.spec.references if r.role == "target" and Path(r.path).is_file()] or [
+ r for r in inp.spec.references if Path(r.path).is_file()
+ ]
+ if not targets:
+ return {"error": "spec has no readable reference images"}
+ view = self.pick_front_view(inp.renders.views)
+ if view is None:
+ return {"error": "render set has no views"}
+ if self.silhouette_fn is None:
+ return {"error": "compare_silhouette unavailable (codeverse.spatial.silhouette not importable)"}
+ res = self.silhouette_fn(view.path, targets[0].path)
+ if not isinstance(res, dict) or "iou" not in res:
+ return {"error": f"compare_silhouette returned no iou: {res!r}"}
+ extra = {k: v for k, v in res.items() if k != "iou" and isinstance(v, (int, float, str, bool))}
+ return {"iou": float(res["iou"]), "render": view.name, "reference": Path(targets[0].path).name, "extra": extra}
+
+
+class ReferenceJudgeError(RuntimeError):
+ """The reference judge cannot compute its measured criteria."""
diff --git a/harness/codeverse/judges/rubrics.py b/harness/codeverse/judges/rubrics.py
new file mode 100644
index 00000000..829ec0d7
--- /dev/null
+++ b/harness/codeverse/judges/rubrics.py
@@ -0,0 +1,172 @@
+"""Rubrics: typed criteria + weights + floors + deterministic caps, loaded from YAML.
+
+A rubric is data, not prose: every criterion carries *anchored* descriptions
+(what 1.0 / 0.7 / 0.4 / 0.1 look like) so two judges read the same scale, an
+optional hard ``floor`` (a criterion below its floor fails the verdict no matter
+the weighted mean) and a ``kind`` (``visual`` = scored by the VLM,
+``measured`` = scored in code and merely *shown* to the VLM).
+
+``caps`` are rules that bound the overall score from deterministic gate
+findings (build error → 0.0, floating part → ≤ 0.6 ...) — see ``caps.py``.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+from functools import lru_cache
+from pathlib import Path
+from typing import Literal
+
+import yaml
+from pydantic import BaseModel, Field, field_validator, model_validator
+
+from codeverse.contracts.artifacts import Severity
+
+RUBRICS_DIR = Path(__file__).resolve().parent / "rubrics"
+ANCHOR_LEVELS = ("1.0", "0.7", "0.4", "0.1")
+_IDENT = re.compile(r"^[a-z][a-z0-9_]*$")
+
+
+class RubricError(ValueError):
+ """Raised for unknown / malformed rubrics."""
+
+
+class Criterion(BaseModel):
+ id: str
+ weight: float = Field(gt=0.0, le=1.0)
+ title: str = ""
+ description: str = Field(description="what this criterion judges, one paragraph")
+ anchors: dict[str, str] = Field(description="score level → what it looks like; keys 1.0/0.7/0.4/0.1")
+ floor: float | None = Field(default=None, ge=0.0, le=1.0, description="hard floor: below → verdict fails")
+ kind: Literal["visual", "measured"] = "visual"
+
+ @field_validator("id")
+ @classmethod
+ def _ident(cls, v: str) -> str:
+ if not _IDENT.match(v):
+ raise ValueError(f"criterion id must be snake_case identifier, got {v!r}")
+ return v
+
+ @field_validator("anchors")
+ @classmethod
+ def _anchors(cls, v: dict[str, str]) -> dict[str, str]:
+ v = {str(k): str(t).strip() for k, t in v.items()}
+ missing = [lvl for lvl in ANCHOR_LEVELS if lvl not in v]
+ if missing:
+ raise ValueError(f"anchors missing levels {missing}; need {ANCHOR_LEVELS}")
+ return v
+
+ @property
+ def label(self) -> str:
+ return self.title or self.id.replace("_", " ")
+
+
+class CapRule(BaseModel):
+ """Bounds the overall score when a deterministic signal fires.
+
+ ``when="gate"`` rules match ``GateFinding`` records: ``gate`` is an fnmatch
+ pattern on the gate name (``"build*"``), ``severity`` the minimum severity,
+ ``kinds`` a list of tokens any of which must appear in ``finding.data.kind``
+ / ``finding.data.code`` or, as a fallback, in the lower-cased message.
+ ``when="acceptance"`` fires when any ``must`` acceptance item is not verified.
+ ``when="console"`` fires when the render set reports console errors (scenes).
+ """
+
+ id: str
+ cap: float = Field(ge=0.0, le=1.0)
+ when: Literal["gate", "acceptance", "console"] = "gate"
+ gate: str = Field(default="*", description="fnmatch pattern on GateFinding.gate")
+ severity: Severity = Severity.ERROR
+ kinds: list[str] = Field(default_factory=list)
+ note: str = ""
+
+
+class Rubric(BaseModel):
+ name: str
+ version: int = 1
+ track_hint: str = Field(default="", description="static_object | articulated_object | scene | asset | reference")
+ pass_threshold: float = Field(ge=0.0, le=1.0)
+ criteria: list[Criterion] = Field(min_length=1)
+ caps: list[CapRule] = Field(default_factory=list)
+ extra_instructions: str = ""
+ description: str = ""
+
+ @model_validator(mode="after")
+ def _consistent(self) -> Rubric:
+ ids = [c.id for c in self.criteria]
+ if len(ids) != len(set(ids)):
+ raise ValueError(f"duplicate criterion ids in rubric {self.name}")
+ total = sum(c.weight for c in self.criteria)
+ if abs(total - 1.0) > 0.02:
+ raise ValueError(f"rubric {self.name}: weights sum to {total:.3f}, expected 1.0")
+ cap_ids = [c.id for c in self.caps]
+ if len(cap_ids) != len(set(cap_ids)):
+ raise ValueError(f"duplicate cap ids in rubric {self.name}")
+ return self
+
+ # ------------------------------------------------------------------ helpers
+ @property
+ def weights(self) -> dict[str, float]:
+ return {c.id: c.weight for c in self.criteria}
+
+ def criterion(self, cid: str) -> Criterion:
+ for c in self.criteria:
+ if c.id == cid:
+ return c
+ raise KeyError(f"rubric {self.name} has no criterion {cid!r}")
+
+ def visual_criteria(self) -> list[Criterion]:
+ return [c for c in self.criteria if c.kind == "visual"]
+
+ def measured_criteria(self) -> list[Criterion]:
+ return [c for c in self.criteria if c.kind == "measured"]
+
+ def weighted_overall(self, scores: dict[str, float]) -> float:
+ """Σ w·s / Σ w over the rubric's criteria. Every criterion must be present."""
+ missing = [c.id for c in self.criteria if c.id not in scores]
+ if missing:
+ raise RubricError(f"cannot score rubric {self.name}: missing criteria {missing}")
+ num = sum(c.weight * float(scores[c.id]) for c in self.criteria)
+ den = sum(c.weight for c in self.criteria)
+ return max(0.0, min(1.0, num / den))
+
+ def floors_hit(self, scores: dict[str, float]) -> list[tuple[str, float, float]]:
+ """(criterion id, score, floor) for every criterion scored below its floor."""
+ out = []
+ for c in self.criteria:
+ if c.floor is not None and c.id in scores and float(scores[c.id]) < c.floor:
+ out.append((c.id, float(scores[c.id]), c.floor))
+ return out
+
+ def content_hash(self) -> str:
+ payload = json.dumps(self.model_dump(mode="json"), sort_keys=True)
+ return hashlib.sha256(payload.encode()).hexdigest()[:12]
+
+
+def list_rubrics() -> list[str]:
+ return sorted(p.stem for p in RUBRICS_DIR.glob("*.yaml"))
+
+
+def rubric_from_dict(data: dict, *, name_hint: str = "") -> Rubric:
+ try:
+ return Rubric(**data)
+ except Exception as e: # pydantic ValidationError / TypeError
+ raise RubricError(f"invalid rubric {name_hint or data.get('name')!r}: {e}") from e
+
+
+@lru_cache(maxsize=32)
+def load_rubric(name: str) -> Rubric:
+ """Load ``rubrics/<name>.yaml`` (or a path to a yaml file) into a validated ``Rubric``."""
+ path = Path(name)
+ if not (path.suffix in (".yaml", ".yml") and path.is_file()):
+ path = RUBRICS_DIR / f"{name}.yaml"
+ if not path.is_file():
+ raise RubricError(f"unknown rubric {name!r}; available: {list_rubrics()}")
+ with path.open() as fh:
+ data = yaml.safe_load(fh) or {}
+ if not isinstance(data, dict):
+ raise RubricError(f"rubric file {path} must be a mapping")
+ data.setdefault("name", path.stem)
+ return rubric_from_dict(data, name_hint=path.stem)
diff --git a/harness/codeverse/judges/rubrics/articulated_v1.yaml b/harness/codeverse/judges/rubrics/articulated_v1.yaml
new file mode 100644
index 00000000..af3f4b39
--- /dev/null
+++ b/harness/codeverse/judges/rubrics/articulated_v1.yaml
@@ -0,0 +1,182 @@
+name: articulated_v1
+version: 1
+track_hint: articulated_object
+pass_threshold: 0.7
+description: 'Rubric for an ARTICULATED object (cabinet with doors/drawers, laptop, folding chair, robot arm, scissors...)
+ judged on the rest-pose render rig PLUS a pose sheet: views of the object with joints swept to sampled values
+ (labelled with joint names and values). Static criteria are inherited from static_object_v1 at reduced weight;
+ articulation criteria score whether the joints are real, placed right and move plausibly.
+
+ '
+extra_instructions: 'Views whose label says POSE or names a joint value show the SAME object with joints moved by
+ the harness (forward kinematics from the authored URDF). Judge articulation ONLY from those views and the joint
+ table: a door that swings through its frame, a drawer that slides sideways, a lid that rotates about the wrong
+ edge, or a hinge placed in mid-air are articulation defects even when the rest pose looks perfect. Judge static
+ criteria from the rest-pose views. Links are named in the plan digest; use link and joint names as targets.
+
+ '
+criteria:
+- id: intent_fidelity
+ weight: 0.16
+ floor: 0.3
+ title: Intent fidelity
+ description: 'Is this the object the brief asked for — category, named attributes, and the named moving parts
+ (doors, drawers, lid, arm links)?
+
+ '
+ anchors:
+ '1.0': Right category; every named attribute and every named moving part is present.
+ '0.7': Right category; one attribute or moving part is weak or generic.
+ '0.4': A named attribute or moving part is missing or clearly wrong.
+ '0.1': Wrong category or unrecognisable.
+- id: structure_plausibility
+ weight: 0.14
+ floor: 0.25
+ title: Structural plausibility
+ description: 'In the rest pose, is the assembly coherent — links attached where they should be, nothing floating,
+ the object stands and would function?
+
+ '
+ anchors:
+ '1.0': Every link is where a real example has it and visibly supported.
+ '0.7': One link slightly misplaced; nothing floats.
+ '0.4': One link visibly floats or is clearly misplaced.
+ '0.1': Several links float or the assembly is implausible.
+- id: articulation_plausibility
+ weight: 0.18
+ floor: 0.3
+ title: Articulation plausibility
+ description: 'In the pose sheet, does each joint move the way the real mechanism moves — the right TYPE of motion
+ (swing vs slide), the right direction, and a believable amount? A drawer must slide out along its depth; a
+ door must swing about its hinge edge; a lid must open upward; an arm link must rotate about its pivot.
+
+ '
+ anchors:
+ '1.0': Every joint moves like the real mechanism; posed views look like photographs of the object in use.
+ '0.7': All joints move the right way; one moves a little too far / too little or looks slightly stiff.
+ '0.4': One joint moves the wrong way (slides instead of swings, opens into the body) or in the wrong direction.
+ '0.1': Joints do nothing visible, move the wrong links, or the object falls apart when posed.
+- id: joint_placement_and_range
+ weight: 0.12
+ title: Joint placement and range
+ description: 'Are the pivots/axes placed where the physical hinge or rail is (the hinge edge of a door, the rail
+ of a drawer, the knuckle of an arm), and are the limits sane (no self-penetration at the extremes, no over-rotation
+ through the frame)? Use the joint table (axis, pivot, limits) together with the posed views.
+
+ '
+ anchors:
+ '1.0': Every pivot sits on the real hinge/rail line; extremes are collision-free and natural.
+ '0.7': A pivot is slightly off its edge or a limit is a bit generous, without visible clipping.
+ '0.4': A pivot is clearly off (door rotates about its centre, drawer pivots), or an extreme pose clips through
+ the body.
+ '0.1': Pivots in mid-air, joints on the wrong links, or poses that explode the object.
+- id: geometry_detail
+ weight: 0.12
+ title: Geometry detail
+ description: 'Are part shapes refined beyond primitives — handles, hinges, bevels, panel insets, thickness — visible
+ in the renders?
+
+ '
+ anchors:
+ '1.0': Multiple refinements including visible mechanism details (handles, hinge leaves, rails).
+ '0.7': At least two refinements; the rest plain.
+ '0.4': Primitive stack, at most one token detail.
+ '0.1': Blobs or a single lump.
+- id: proportions_scale
+ weight: 0.1
+ title: Proportions and scale
+ description: 'Overall dimensions and part ratios are right for the object (measurement table, stated dimensions),
+ including moving-part thickness and clearances.
+
+ '
+ anchors:
+ '1.0': Size and ratios believable; stated dimensions met.
+ '0.7': One ratio somewhat off; size within ~20%.
+ '0.4': A clearly wrong ratio or size off by >20%.
+ '0.1': Absurd proportions or wrong order of magnitude.
+- id: assembly_fit
+ weight: 0.1
+ title: Assembly fit
+ description: 'Do joined links meet cleanly in the rest pose (tight joins, no penetration) while leaving the clearance
+ a moving part needs?
+
+ '
+ anchors:
+ '1.0': Clean tight joins; sensible clearances around moving parts.
+ '0.7': One small gap or shallow overlap.
+ '0.4': A visible gap or penetration, or a moving part fused into its frame.
+ '0.1': Multiple gaps/penetrations.
+- id: craftsmanship_no_artifacts
+ weight: 0.08
+ floor: 0.3
+ title: Craftsmanship and artefacts
+ description: 'No z-fighting, black faces, holes, stretched geometry, stray slivers, or duplicated shells in rest
+ or posed views.
+
+ '
+ anchors:
+ '1.0': No artefacts in any view.
+ '0.7': One minor artefact in one view.
+ '0.4': A clearly visible artefact.
+ '0.1': Artefacts dominate.
+caps:
+- id: build_error
+ when: gate
+ gate: build*
+ severity: error
+ cap: 0.0
+- id: urdf_error
+ when: gate
+ gate: '*urdf*'
+ severity: error
+ cap: 0.3
+ note: URDF does not parse / links unresolved / joint tree invalid
+- id: contract_violation
+ when: gate
+ gate: contract*
+ severity: error
+ cap: 0.75
+ note: plan part missing or measured bbox broken beyond tolerance
+- id: joint_collision
+ when: gate
+ gate: '*'
+ severity: error
+ kinds:
+ - collision
+ - penetration
+ - intersect
+ - self_collision
+ cap: 0.6
+ note: a swept pose collides link-vs-link
+- id: floating_part
+ when: gate
+ gate: '*'
+ severity: error
+ kinds:
+ - floating
+ - unattached
+ - no_contact
+ - disconnected
+ - unsupported
+ - island
+ cap: 0.6
+- id: penetration_error
+ when: gate
+ gate: '*'
+ severity: error
+ kinds:
+ - penetration
+ - intersect
+ - overlap
+ cap: 0.7
+- id: missing_must_acceptance
+ when: acceptance
+ cap: 0.6
+- id: unattached_link
+ when: gate
+ gate: '*'
+ severity: error
+ kinds:
+ - unattached
+ cap: 0.6
+ note: a link is not physically attached to its parent as its joint type requires
diff --git a/harness/codeverse/judges/rubrics/asset_v1.yaml b/harness/codeverse/judges/rubrics/asset_v1.yaml
new file mode 100644
index 00000000..ed324dfc
--- /dev/null
+++ b/harness/codeverse/judges/rubrics/asset_v1.yaml
@@ -0,0 +1,127 @@
+name: asset_v1
+version: 1
+track_hint: asset
+pass_threshold: 0.70
+description: >
+ Per-asset rubric used inside scenes: ONE asset (a building, a tree, a boat, a lamp
+ post...) isolated and rendered on the object rig. Stricter on silhouette / all-sides
+ completeness than the static-object rubric, lighter on the brief because the asset
+ is only described by a one-line plan entry.
+
+extra_instructions: >
+ The asset is judged as a scene ingredient: it must read correctly at a distance
+ (silhouette) AND be finished on every side because cameras will see it from
+ anywhere. Credit only visible detail. A plain-but-correct asset scores ~0.7;
+ an asset that is a single box or that is unfinished on its back/underside scores low.
+
+criteria:
+ - id: identity_silhouette
+ weight: 0.22
+ floor: 0.30
+ title: Identity and silhouette
+ description: >
+ Does the asset read as the thing its plan entry names, from its silhouette alone
+ (the contact sheet at a glance) as well as up close?
+ anchors:
+ "1.0": Instantly recognisable from every view; the silhouette alone names it.
+ "0.7": Recognisable from the 3/4 views; one view is ambiguous.
+ "0.4": Only recognisable with the plan entry in hand; silhouette is generic.
+ "0.1": Not recognisable; a box or blob.
+
+ - id: all_sides_finished
+ weight: 0.16
+ title: All sides finished
+ description: >
+ Is the asset complete on the back, sides, top and underside — not a façade?
+ Windows/doors/details continue around; the underside is closed; the top has a roof
+ or cap where it should.
+ anchors:
+ "1.0": Every side is finished to the same standard as the front.
+ "0.7": The back or top is plainer than the front but not empty or open.
+ "0.4": One side is blank, open, or missing detail the front has.
+ "0.1": A façade — open back, missing faces, or unfinished underside.
+
+ - id: sub_part_structure
+ weight: 0.16
+ floor: 0.25
+ title: Sub-part structure
+ description: >
+ Are the asset's constituent parts present and assembled correctly (trunk + canopy,
+ hull + mast + sail, base + pole + lamp head), attached where they should be, with
+ nothing floating?
+ anchors:
+ "1.0": All expected sub-parts are present, placed and attached correctly.
+ "0.7": One sub-part is simplified or slightly misplaced; none floating.
+ "0.4": A sub-part is missing or visibly floating / misplaced.
+ "0.1": No meaningful sub-structure or parts are scattered.
+
+ - id: proportions
+ weight: 0.14
+ title: Proportions
+ description: >
+ Are the asset's overall dimensions (see measurement table and plan size) and part
+ ratios right for its kind?
+ anchors:
+ "1.0": Size matches the plan and every ratio is believable.
+ "0.7": One ratio is a bit off; size is within ~15% of plan.
+ "0.4": A clearly wrong ratio, or size off by more than ~30%.
+ "0.1": Absurd proportions or wrong order of magnitude.
+
+ - id: detail_level
+ weight: 0.12
+ title: Detail level
+ description: >
+ Is there enough shape refinement for the asset's role — edges, insets, thickness,
+ trim, hardware — beyond primitives? Do not credit detail you cannot see.
+ anchors:
+ "1.0": Several visible refinements; reads as a crafted asset.
+ "0.7": Two visible refinements; otherwise plain.
+ "0.4": Primitive stack with one token detail.
+ "0.1": A single primitive or a blob.
+
+ - id: material_truth
+ weight: 0.10
+ title: Material truth
+ description: >
+ Do the surfaces read as the right materials (stone, wood, glass, foliage, metal)
+ with sensible colour and roughness and no placeholder or contradictory surfaces?
+ anchors:
+ "1.0": Every surface reads as its real material with some character.
+ "0.7": Sensible flat materials, correctly assigned.
+ "0.4": One wrong or placeholder material.
+ "0.1": Placeholder/default materials throughout.
+
+ - id: cleanliness
+ weight: 0.10
+ floor: 0.30
+ title: Cleanliness
+ description: >
+ No z-fighting, black (inverted) faces, holes, stretched geometry, stray slivers
+ or duplicate shells.
+ anchors:
+ "1.0": No artefacts in any view.
+ "0.7": One minor artefact in one view.
+ "0.4": A clearly visible artefact.
+ "0.1": Artefacts dominate.
+
+caps:
+ - id: build_error
+ when: gate
+ gate: "build*"
+ severity: error
+ cap: 0.0
+ - id: floating_part
+ when: gate
+ gate: "*"
+ severity: error
+ kinds: [floating, no_contact, disconnected, unsupported, island]
+ cap: 0.6
+ - id: penetration_error
+ when: gate
+ gate: "*"
+ severity: error
+ kinds: [penetration, intersect, overlap, collision]
+ cap: 0.7
+ - id: missing_must_acceptance
+ when: acceptance
+ cap: 0.6
diff --git a/harness/codeverse/judges/rubrics/reference_v1.yaml b/harness/codeverse/judges/rubrics/reference_v1.yaml
new file mode 100644
index 00000000..b66c4c39
--- /dev/null
+++ b/harness/codeverse/judges/rubrics/reference_v1.yaml
@@ -0,0 +1,115 @@
+name: reference_v1
+version: 1
+track_hint: reference
+pass_threshold: 0.70
+description: >
+ Image-conditioned rubric: the object must match one or more REFERENCE images. The
+ silhouette criterion is MEASURED in code (IoU of the front render vs the target
+ reference) and shown to the judge; the judge scores the perceptual criteria by
+ comparing reference images to renders side by side.
+
+extra_instructions: >
+ Images labelled REFERENCE are the target the object must reproduce; images labelled
+ VIEW are renders of the generated object. Compare like with like (the front render
+ against the reference's viewpoint). The silhouette IoU in the measurement block is a
+ fact computed by the harness — do not re-estimate it; use it to calibrate your
+ proportion judgement. Ignore background, lighting style and camera framing
+ differences unless the brief asks for them.
+
+criteria:
+ - id: silhouette_match
+ weight: 0.25
+ kind: measured
+ title: Silhouette match (measured)
+ description: >
+ Outline IoU between the front render and the target reference image, computed
+ by the harness; mapped to 0..1 in code. Shown for calibration only.
+ anchors:
+ "1.0": IoU ≥ 0.85.
+ "0.7": IoU ≈ 0.65.
+ "0.4": IoU ≈ 0.45.
+ "0.1": IoU ≤ 0.27.
+
+ - id: proportions
+ weight: 0.20
+ floor: 0.25
+ title: Proportions vs reference
+ description: >
+ Do the part ratios and overall aspect match the reference — heights, widths,
+ thicknesses, spacing of repeated elements?
+ anchors:
+ "1.0": Ratios match the reference within a few percent everywhere.
+ "0.7": One ratio is visibly off but the object still reads like the reference.
+ "0.4": A clearly wrong ratio changes the character of the object.
+ "0.1": Proportions have little to do with the reference.
+
+ - id: parts_coverage
+ weight: 0.20
+ floor: 0.25
+ title: Parts coverage
+ description: >
+ Is every visible part of the reference present in the render (and no invented
+ extra parts), placed and attached as in the reference?
+ anchors:
+ "1.0": Every reference part is present and correctly placed; nothing invented.
+ "0.7": One minor part is missing or simplified.
+ "0.4": A major part is missing, or an invented part changes the object.
+ "0.1": Most reference parts are missing.
+
+ - id: material_color
+ weight: 0.15
+ title: Material and colour
+ description: >
+ Do the colours and material types match the reference per part (wood vs metal,
+ matte vs glossy, the actual hues)?
+ anchors:
+ "1.0": Per-part colours and material types match the reference.
+ "0.7": Colours close; one part's material type differs.
+ "0.4": A prominent part has a clearly wrong colour or material.
+ "0.1": Colours/materials unrelated to the reference.
+
+ - id: detail
+ weight: 0.10
+ title: Detail fidelity
+ description: >
+ Are the reference's visible details (mouldings, hardware, patterns, edges)
+ reproduced rather than smoothed away?
+ anchors:
+ "1.0": Reference details reproduced convincingly.
+ "0.7": Major details present, fine ones smoothed.
+ "0.4": Only the gross form; details absent.
+ "0.1": A primitive approximation.
+
+ - id: cleanliness
+ weight: 0.10
+ floor: 0.30
+ title: Cleanliness
+ description: >
+ No artefacts — z-fighting, black faces, holes, slivers, floating parts.
+ anchors:
+ "1.0": No artefacts in any view.
+ "0.7": One minor artefact.
+ "0.4": A clearly visible artefact.
+ "0.1": Artefacts dominate.
+
+caps:
+ - id: build_error
+ when: gate
+ gate: "build*"
+ severity: error
+ cap: 0.0
+ - id: floating_part
+ when: gate
+ gate: "*"
+ severity: error
+ kinds: [floating, no_contact, disconnected, unsupported, island]
+ cap: 0.6
+ - id: penetration_error
+ when: gate
+ gate: "*"
+ severity: error
+ kinds: [penetration, intersect, overlap, collision]
+ cap: 0.7
+ - id: missing_must_acceptance
+ when: acceptance
+ cap: 0.6
diff --git a/harness/codeverse/judges/rubrics/scene_v1.yaml b/harness/codeverse/judges/rubrics/scene_v1.yaml
new file mode 100644
index 00000000..8ac2662d
--- /dev/null
+++ b/harness/codeverse/judges/rubrics/scene_v1.yaml
@@ -0,0 +1,162 @@
+name: scene_v1
+version: 1
+track_hint: scene
+pass_threshold: 0.70
+description: >
+ Rubric for a procedural 3D SCENE (a place) judged on its authored cameras plus a
+ fitted overview rig, at one or more animation times, with a probe digest (fps,
+ console/shader errors, census). The scene owns its lighting, sky and fog: grade
+ the picture it makes, and the place it depicts.
+
+extra_instructions: >
+ Views labelled OVERVIEW are harness cameras fitted to the scene bounds — use them for
+ layout, coverage, floating/sunken objects and scale. Views labelled CAM are the
+ scene's own authored cameras — grade composition, lighting, atmosphere and effects
+ on those. Views at different times (t=...) show animation: compare them for what
+ moves. The probe digest lists console/shader errors and fps measured by the harness;
+ treat those as facts. Use zone and asset names from the plan digest as targets.
+ A scene a person would screenshot belongs at 0.8+; a recognisable place with one
+ dead zone / flat lighting / floating asset sits near 0.5; an unlit, empty or
+ unreadable scene sits at 0.1-0.3.
+
+criteria:
+ - id: brief_fidelity
+ weight: 0.18
+ floor: 0.30
+ title: Brief fidelity
+ description: >
+ Does the scene depict the place the brief describes, with every named element
+ (landmarks, zones, weather, time of day, activity) present and recognisable,
+ arranged as the brief implies?
+ anchors:
+ "1.0": Every named element is present and recognisable; setting, era, weather and time of day are unmistakable.
+ "0.7": The place reads right; one named element is token or hard to find.
+ "0.4": The place reads right but named elements are missing, or the time of day / weather contradicts the brief.
+ "0.1": Wrong kind of place, or an unreadable world.
+
+ - id: composition_and_camera
+ weight: 0.14
+ floor: 0.25
+ title: Composition and camera
+ description: >
+ Do the authored cameras make readable, well-framed pictures — a focal subject,
+ foreground/midground/background, horizon placed deliberately, nothing clipped by
+ the near plane, no camera inside geometry, no shot that shows only sky or ground?
+ anchors:
+ "1.0": Every authored camera is a composed shot with depth layering and a clear subject.
+ "0.7": Shots are readable; one is a bit flat or off-centre.
+ "0.4": One authored camera shows nothing useful (sky, ground, the inside of a wall) or is badly clipped.
+ "0.1": Most shots are unusable or the camera is inside geometry.
+
+ - id: lighting_atmosphere
+ weight: 0.14
+ floor: 0.25
+ title: Lighting and atmosphere
+ description: >
+ Is the lighting readable and atmospheric — a consistent sun/moon direction,
+ present soft shadows, sky that matches the mood, aerial perspective / fog giving
+ depth, exposure neither blown nor crushed, coloured (sky-lit) shade rather than
+ black?
+ anchors:
+ "1.0": Clear mood executed consistently; shadows, sky, fog and exposure all agree; shade carries sky colour.
+ "0.7": Good lighting with one weakness (slightly flat shadows or slightly heavy fog).
+ "0.4": Flat shadowless light, or noticeably under/over-exposed, or sky contradicting the light.
+ "0.1": Near-black, blown white, or unlit.
+
+ - id: asset_quality_detail
+ weight: 0.14
+ title: Asset quality and detail
+ description: >
+ Are the individual assets refined beyond primitives and varied — buildings with
+ roofs/windows/setbacks, trees with trunk and canopy, vehicles and street
+ furniture where the place calls for them — without copy-paste monotony?
+ anchors:
+ "1.0": Assets are crafted and varied; closeups hold up.
+ "0.7": Assets are decent with some repetition or a few plain ones.
+ "0.4": Mostly plain boxes / cones, or one shape stamped everywhere.
+ "0.1": Primitive blobs or an empty world.
+
+ - id: spatial_coherence_scale
+ weight: 0.12
+ floor: 0.25
+ title: Spatial coherence and scale
+ description: >
+ Is the layout believable as a place (streets connect, shoreline continuous,
+ buildings face roads, spacing realistic), everything sits ON the ground/terrain
+ (nothing floating or sunken), and relative sizes agree on what a metre is?
+ anchors:
+ "1.0": Layout reads as a real place; everything grounded; sizes agree.
+ "0.7": Minor oddities (a slightly floating prop, a slightly large car) that do not break the read.
+ "0.4": A clearly floating/sunken asset, an intersection of objects, or one glaring scale error.
+ "0.1": Uniform scatter, many floating objects, or scale chaos.
+
+ - id: materials_shaders_effects
+ weight: 0.12
+ title: Materials, shaders and effects
+ description: >
+ Do surfaces read as materials (water with specular life, glass, foliage,
+ concrete) and do the planned effects (custom shaders, particles, post-processing)
+ visibly exist and look intentional — not magenta, not noise, not a flat tint?
+ anchors:
+ "1.0": Materials convincing; every planned effect is visible and adds to the picture.
+ "0.7": Materials sensible; effects present but subtle or slightly crude.
+ "0.4": A planned effect is missing or broken (flat water, no particles, a black shader), or a placeholder material is visible.
+ "0.1": Placeholder surfaces throughout or broken shaders dominate.
+
+ - id: animation_life
+ weight: 0.08
+ title: Animation and life
+ description: >
+ Comparing frames at different times, does something move as the plan says
+ (water, foliage, vehicles, lights, characters) in a plausible way, and is the
+ scene alive rather than frozen?
+ anchors:
+ "1.0": Planned motion is visible and natural across the time samples.
+ "0.7": Some planned motion visible; subtle or partial.
+ "0.4": Frames are identical although motion was planned, or motion is implausible (rigid glide, clipping).
+ "0.1": Nothing moves and/or motion breaks the scene.
+
+ - id: technical_cleanliness
+ weight: 0.08
+ floor: 0.30
+ title: Technical cleanliness
+ description: >
+ No z-fighting, no magenta/default materials, no missing faces, no visible world
+ edge cliff, no console or shader errors in the probe digest, acceptable fps.
+ anchors:
+ "1.0": Clean renders, zero console/shader errors, healthy fps.
+ "0.7": A minor artefact or a single non-fatal warning.
+ "0.4": Visible z-fighting / missing faces / hard world edge, or a console error.
+ "0.1": Broken renders, shader failures, or the scene does not run.
+
+caps:
+ - id: build_error
+ when: gate
+ gate: "build*"
+ severity: error
+ cap: 0.0
+ - id: shader_error
+ when: gate
+ gate: "*"
+ severity: error
+ kinds: [shader, glsl, webgl, compile]
+ cap: 0.5
+ - id: console_error
+ when: console
+ cap: 0.6
+ note: runtime JS errors seen while rendering
+ - id: camera_in_geometry
+ when: gate
+ gate: "*"
+ severity: error
+ kinds: [camera_in_geometry, camera_clipped, camera_inside, point_blank, blank_view, dead_render]
+ cap: 0.5
+ - id: floating_part
+ when: gate
+ gate: "*"
+ severity: error
+ kinds: [floating, sunken, unsupported]
+ cap: 0.6
+ - id: missing_must_acceptance
+ when: acceptance
+ cap: 0.6
diff --git a/harness/codeverse/judges/rubrics/static_object_v1.yaml b/harness/codeverse/judges/rubrics/static_object_v1.yaml
new file mode 100644
index 00000000..b278a6d6
--- /dev/null
+++ b/harness/codeverse/judges/rubrics/static_object_v1.yaml
@@ -0,0 +1,145 @@
+name: static_object_v1
+version: 1
+track_hint: static_object
+pass_threshold: 0.72
+description: >
+ Assembly-level rubric for ONE static object (furniture, tool, vehicle, appliance,
+ plant, creature, building...) judged on a labelled multi-view render rig plus a
+ measurement table. Scores are per criterion; the overall is computed in code.
+
+extra_instructions: >
+ Judge what is VISIBLE in the renders and what the measurement table states; do not
+ credit detail you cannot see and do not invent faults. Use the underside / low
+ views for ground contact and hidden gaps, the top view for symmetry and footprint,
+ and the 3/4 views for overall read. Hidden connectors (a bracket inside a shade, a
+ dowel inside a joint) are NOT defects when the parts visibly meet. Spread scores
+ across the range: a competent, correct object belongs at 0.8+, one clearly visible
+ major defect pulls the affected criterion to ~0.4, several major defects or a wrong
+ object sit at 0.1-0.3.
+
+criteria:
+ - id: intent_fidelity
+ weight: 0.22
+ floor: 0.30
+ title: Intent fidelity
+ description: >
+ Is this the object the brief asked for — category first, then every named
+ attribute (counts, style, features, materials named in the brief)? A stranger
+ shown only these renders should describe the object the way the brief does.
+ anchors:
+ "1.0": Right category and every named attribute is present and unmistakable; nothing the brief asked for is missing or contradicted.
+ "0.7": Right category; one named attribute is weak, generic or hard to confirm, none is contradicted.
+ "0.4": Right category but a named attribute is missing or clearly wrong (wrong count of legs, no armrests when asked, wrong style).
+ "0.1": Wrong category or unrecognisable; the renders would not be described as the brief.
+
+ - id: structure_plausibility
+ weight: 0.18
+ floor: 0.25
+ title: Structural plausibility
+ description: >
+ Does the assembly hold together the way a real example of this object does?
+ Every part attaches where it should, is oriented correctly, reaches what it must
+ reach (legs reach the ground, a shade sits on its harp, wheels sit at the hubs),
+ and nothing floats, hovers, or points the wrong way.
+ anchors:
+ "1.0": Every part is where a real example has it, correctly oriented, visibly supported; the object would stand and function.
+ "0.7": One part is slightly misplaced or ambiguous in support, but nothing floats and the object clearly stands.
+ "0.4": One part visibly floats, hovers off its mount, or is clearly in the wrong place or orientation.
+ "0.1": Several parts float, are exploded apart, or the assembly is not a plausible object.
+
+ - id: geometry_detail
+ weight: 0.16
+ title: Geometry detail
+ description: >
+ Are part shapes refined beyond naive primitives where the real object is refined?
+ Look for bevels/chamfers, tapers, curves, wall thickness, cut-outs, profiles,
+ mouldings, hardware. Credit only what is visible in the renders.
+ anchors:
+ "1.0": Multiple refinements at once — profiles, bevels, tapers, thickness, hardware — the object reads as a designed product or natural form.
+ "0.7": At least two visible refinements (e.g. bevelled edges and a tapered leg), the rest is plain but acceptable.
+ "0.4": A stack of plain boxes/cylinders with sharp 90° corners; at most one token detail.
+ "0.1": Primitive blobs or a single lump; parts are not individually shaped.
+
+ - id: proportions_scale
+ weight: 0.12
+ title: Proportions and scale
+ description: >
+ Are the relative sizes of parts and the overall dimensions right for the object
+ (use the measurement table and any stated dimensions)? Seat height, leg
+ thickness, wheel diameter, handle size must read as real-world correct.
+ anchors:
+ "1.0": Overall size and every part ratio are believable; stated dimensions are met within tolerance.
+ "0.7": One part is somewhat thick/thin/short/long but the object still reads correctly at the stated size.
+ "0.4": A clearly wrong proportion (legs twice as thick as they should be, a tiny seat on a huge frame) or the size is off by more than ~20%.
+ "0.1": Proportions are absurd or the object is the wrong order of magnitude.
+
+ - id: assembly_fit
+ weight: 0.12
+ title: Assembly fit
+ description: >
+ Do parts that are meant to meet actually meet — tightly and without visible
+ interpenetration? Judge at object scale: a few millimetres of tolerance is fine;
+ a finger-wide gap, a part jammed through another, or a sunken/protruding join
+ is not.
+ anchors:
+ "1.0": All joins are clean and tight; no visible gaps, no visible penetration, no z-fighting at contacts.
+ "0.7": One small gap or shallow overlap at a join; the rest is clean.
+ "0.4": A visible gap a part should not have, or an obvious penetration of one part through another.
+ "0.1": Multiple gaps/penetrations; parts clearly not fitted to each other.
+
+ - id: materials
+ weight: 0.10
+ title: Materials
+ description: >
+ Do surfaces read as sensible materials for each part (colour, roughness,
+ metal/dielectric, and character such as wood grain or fabric where it matters)?
+ A clean flat-colour look with correct assignments is acceptable; wrong or
+ placeholder surfaces are not.
+ anchors:
+ "1.0": Every part has a convincing material; visible character (grain, brushed metal, fabric) where the real object has it.
+ "0.7": Sensible flat or lightly-shaded materials on every part, correctly assigned; little character.
+ "0.4": One part has a wrong or contradictory material (metal legs that look like plastic foam, one default grey part).
+ "0.1": Placeholder magenta/default grey everywhere, garbage noise, or materials that contradict the object.
+
+ - id: craftsmanship_no_artifacts
+ weight: 0.10
+ floor: 0.30
+ title: Craftsmanship and artefacts
+ description: >
+ Is the model clean — no z-fighting stripes, inverted normals (black faces),
+ missing faces / see-through walls, stretched or torn geometry, stray
+ slivers, duplicated shells, or degenerate triangles?
+ anchors:
+ "1.0": No visible artefacts in any view; shading is smooth and consistent.
+ "0.7": One small artefact (a sliver, a minor shading seam) visible only in one view.
+ "0.4": A clearly visible artefact — black faces, a hole in a surface, obvious z-fighting.
+ "0.1": Artefacts dominate; the object is torn, inside-out, or visibly broken.
+
+caps:
+ - id: build_error
+ when: gate
+ gate: "build*"
+ severity: error
+ cap: 0.0
+ note: the code did not build or export; nothing to score
+ - id: floating_part
+ when: gate
+ gate: "*"
+ severity: error
+ kinds: [floating, unattached, no_contact, disconnected, unsupported, island]
+ cap: 0.6
+ - id: penetration_error
+ when: gate
+ gate: "*"
+ severity: error
+ kinds: [penetration, intersect, overlap, collision]
+ cap: 0.7
+ - id: contract_violation
+ when: gate
+ gate: "contract*"
+ severity: error
+ cap: 0.75
+ note: measured bbox/part contract broken beyond tolerance
+ - id: missing_must_acceptance
+ when: acceptance
+ cap: 0.6
diff --git a/harness/codeverse/judges/scoring.py b/harness/codeverse/judges/scoring.py
new file mode 100644
index 00000000..02ee0a7f
--- /dev/null
+++ b/harness/codeverse/judges/scoring.py
@@ -0,0 +1,182 @@
+"""Turn N parsed judge samples into ONE ``Judgment`` — all arithmetic in code.
+
+* per-criterion score = mean over samples; overall = rubric-weighted mean;
+ ``score_std`` = std of the per-sample overalls;
+* floors: any criterion mean below its floor → verdict fails;
+* caps: deterministic bounds from gate findings / acceptance (``caps.py``);
+* acceptance: majority vote over samples (ties → False);
+* narrative (summary / issues / plan / strengths) is taken from the sample whose
+ overall is closest to the mean (the *representative* sample) so it is coherent.
+"""
+
+from __future__ import annotations
+
+import json
+import statistics
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import GateReport
+from codeverse.contracts.common import Usage
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.judges.caps import CapResult, apply_caps, missing_must_items
+from codeverse.judges.output_schema import JudgeOutput
+from codeverse.judges.rubrics import Rubric
+
+
+class ScoreBreakdown(BaseModel):
+ """Everything the pass/fail decision used (serialised into ``Judgment.raw``)."""
+
+ status: str = Field(default="ok", description="ok | degraded")
+ per_criterion_mean: dict[str, float]
+ per_criterion_std: dict[str, float]
+ per_sample_overall: list[float]
+ overall_uncapped: float
+ overall: float
+ floors_hit: list[dict[str, Any]] = Field(default_factory=list)
+ caps: CapResult
+ must_missing: list[str] = Field(default_factory=list)
+ acceptance_votes: dict[str, list[bool]] = Field(default_factory=dict)
+ n_requested: int
+ n_used: int
+ sample_errors: list[str] = Field(default_factory=list)
+ rubric_hash: str = ""
+ samples: list[dict[str, Any]] = Field(default_factory=list)
+
+
+def _std(vals: list[float]) -> float:
+ return float(statistics.pstdev(vals)) if len(vals) > 1 else 0.0
+
+
+def _representative(samples: list[JudgeOutput], overalls: list[float]) -> JudgeOutput:
+ mean = statistics.fmean(overalls)
+ return min(zip(samples, overalls, strict=True), key=lambda so: abs(so[1] - mean))[0]
+
+
+def aggregate_samples(
+ rubric: Rubric,
+ samples: list[JudgeOutput],
+ *,
+ gates: list[GateReport],
+ acceptance_items: list[AcceptanceItem],
+ console_errors: list[str] | None = None,
+ usage: Usage | None = None,
+ judge_backend: str = "",
+ n_requested: int | None = None,
+ sample_errors: list[str] | None = None,
+) -> Judgment:
+ """Combine ≥ 1 parsed samples into a Judgment (raises ValueError on zero samples)."""
+ if not samples:
+ raise ValueError("aggregate_samples needs at least one sample")
+ per_crit: dict[str, list[float]] = {c.id: [] for c in rubric.criteria}
+ overalls: list[float] = []
+ for s in samples:
+ sc = s.scores
+ for cid in per_crit:
+ per_crit[cid].append(float(sc[cid]))
+ overalls.append(rubric.weighted_overall(sc))
+ mean_scores = {cid: round(statistics.fmean(v), 4) for cid, v in per_crit.items()}
+ std_scores = {cid: round(_std(v), 4) for cid, v in per_crit.items()}
+ overall_uncapped = rubric.weighted_overall(mean_scores)
+
+ floors = [
+ {"criterion": cid, "score": round(sc, 4), "floor": fl} for cid, sc, fl in rubric.floors_hit(mean_scores)
+ ]
+ votes: dict[str, list[bool]] = {}
+ for s in samples:
+ for aid, ok in s.acceptance_bools.items():
+ votes.setdefault(aid, []).append(bool(ok))
+ for a in acceptance_items:
+ votes.setdefault(a.id, [False])
+ acceptance = {aid: (sum(v) * 2 > len(v)) for aid, v in votes.items()}
+ must_missing = missing_must_items(acceptance_items, acceptance)
+
+ caps = apply_caps(rubric, overall_uncapped, gates, acceptance, acceptance_items, console_errors=console_errors)
+ overall = caps.overall
+ passed = overall >= rubric.pass_threshold and not floors and not must_missing
+
+ rep = _representative(samples, overalls)
+ summary = rep.summary.strip()
+ tail = _verdict_tail(rubric, overall, passed, floors, caps, must_missing)
+ if tail:
+ summary = (summary + " " if summary else "") + tail
+
+ breakdown = ScoreBreakdown(
+ per_criterion_mean=mean_scores,
+ per_criterion_std=std_scores,
+ per_sample_overall=[round(o, 4) for o in overalls],
+ overall_uncapped=round(overall_uncapped, 4),
+ overall=round(overall, 4),
+ floors_hit=floors,
+ caps=caps,
+ must_missing=must_missing,
+ acceptance_votes=votes,
+ n_requested=n_requested or len(samples),
+ n_used=len(samples),
+ sample_errors=sample_errors or [],
+ rubric_hash=rubric.content_hash(),
+ samples=[s.model_dump(mode="json") for s in samples],
+ )
+ return Judgment(
+ rubric=rubric.name,
+ judge_backend=judge_backend,
+ scores=mean_scores,
+ overall=round(overall, 4),
+ passed=passed,
+ summary=summary,
+ strengths=list(rep.strengths),
+ issues=list(rep.issues),
+ improvement_plan=sorted(rep.improvement_plan, key=lambda it: it.priority),
+ acceptance_results=acceptance,
+ n_samples=len(samples),
+ score_std=round(_std(overalls), 4),
+ usage=usage or Usage(),
+ raw=json.dumps(breakdown.model_dump(mode="json"), ensure_ascii=False),
+ )
+
+
+def _verdict_tail(
+ rubric: Rubric, overall: float, passed: bool, floors: list[dict[str, Any]], caps: CapResult, must_missing: list[str]
+) -> str:
+ bits = [f"[verdict: overall {overall:.2f} vs threshold {rubric.pass_threshold:.2f} → {'PASS' if passed else 'FAIL'}"]
+ if caps.caps_applied:
+ bits.append("caps: " + "; ".join(f"{c.rule}≤{c.cap:.2f} ({c.evidence})" for c in caps.caps_applied))
+ if floors:
+ bits.append("floors: " + "; ".join(f"{f['criterion']} {f['score']:.2f}<{f['floor']:.2f}" for f in floors))
+ if must_missing:
+ bits.append("must items unverified: " + ", ".join(must_missing))
+ return " | ".join(bits) + "]"
+
+
+def degraded_judgment(rubric: Rubric, error: str, *, usage: Usage, judge_backend: str, n_requested: int) -> Judgment:
+ """A verdict the orchestrator must treat as a GLITCH (not a score): ``raw.status == 'degraded'``."""
+ breakdown = {
+ "status": "degraded",
+ "error": error,
+ "n_requested": n_requested,
+ "n_used": 0,
+ "rubric_hash": rubric.content_hash(),
+ }
+ return Judgment(
+ rubric=rubric.name,
+ judge_backend=judge_backend,
+ scores={c.id: 0.0 for c in rubric.criteria},
+ overall=0.0,
+ passed=False,
+ summary=f"judge_error: {error}",
+ n_samples=0,
+ usage=usage,
+ raw=json.dumps(breakdown, ensure_ascii=False),
+ )
+
+
+def is_degraded(j: Judgment) -> bool:
+ """True when a Judgment is a judge glitch rather than a score."""
+ if j.summary.startswith("judge_error:"):
+ return True
+ try:
+ return json.loads(j.raw).get("status") == "degraded"
+ except (json.JSONDecodeError, AttributeError, TypeError):
+ return False
diff --git a/harness/codeverse/judges/vlm_judge.py b/harness/codeverse/judges/vlm_judge.py
new file mode 100644
index 00000000..8a9092ec
--- /dev/null
+++ b/harness/codeverse/judges/vlm_judge.py
@@ -0,0 +1,166 @@
+"""``VlmJudge``: rubric YAML + labelled renders + measurements → ``Judgment``.
+
+Per sample: one ``ChatRequest`` with a per-rubric JSON schema (criteria scored
+0..1 with evidence, issues, improvement plan, acceptance verdicts); samples
+differ by view order (shuffle seed) so n-sample mean/std measures judge noise.
+Score/floors/caps/pass are computed in code (``scoring.py``). Retries: up to
+``max_attempts`` per sample on ``ModelError`` / parse failure; if no sample
+succeeds, a *degraded* Judgment (``passed=False, overall=0, summary
+'judge_error: …'``, ``raw.status='degraded'``) is returned for the orchestrator
+to treat as a glitch, never as a score.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Literal
+
+from codeverse.config import get_settings
+from codeverse.contracts.chat import ChatRequest, ChatResponse
+from codeverse.contracts.common import Usage
+from codeverse.contracts.judgment import Judgment
+from codeverse.judges.base import JudgeInput
+from codeverse.judges.output_schema import (
+ JudgeOutput,
+ JudgeParseError,
+ parse_judge_output,
+ wire_schema,
+)
+from codeverse.judges.prompt_builder import build_judge_messages
+from codeverse.judges.rubrics import Rubric, load_rubric
+from codeverse.judges.scoring import aggregate_samples, degraded_judgment
+from codeverse.models.base import ChatModel, ModelError
+
+log = logging.getLogger(__name__)
+
+
+@dataclass
+class JudgeContext:
+ """Per-call extras a subclass may supply (see ``VlmJudge.context``)."""
+
+ measured_scores: dict[str, float] = field(default_factory=dict)
+ extra_text: str = ""
+ extra_images: list[tuple[str, str]] = field(default_factory=list)
+
+
+class VlmJudge:
+ """Rubric judge over a ``ChatModel``. Thread-safe (stateless between calls)."""
+
+ name = "vlm"
+
+ def __init__(
+ self,
+ rubric: str | Rubric = "static_object_v1",
+ model_id: str | None = None,
+ n_samples: int = 1,
+ temperature: float = 0.2,
+ *,
+ thinking: Literal["off", "low", "medium", "high"] = "low",
+ max_attempts: int = 3,
+ max_images: int = 10,
+ max_px: int = 768,
+ chat_model: ChatModel | None = None,
+ cache_dir: Path | None = None,
+ label: str = "judge",
+ ):
+ self.rubric: Rubric = rubric if isinstance(rubric, Rubric) else load_rubric(rubric)
+ self.model_id = model_id or get_settings().default_judge
+ self.n_samples = max(1, int(n_samples))
+ self.temperature = temperature
+ self.thinking = thinking
+ self.max_attempts = max(1, int(max_attempts))
+ self.max_images = max_images
+ self.max_px = max_px
+ self._model = chat_model
+ self.cache_dir = cache_dir
+ self.label = label
+
+ # ------------------------------------------------------------------ model
+ @property
+ def model(self) -> ChatModel:
+ if self._model is None:
+ from codeverse.models import get_chat_model
+
+ self._model = get_chat_model(self.model_id)
+ return self._model
+
+ # ------------------------------------------------------------------ API
+ def judge(self, inp: JudgeInput) -> Judgment:
+ acceptance_ids = [a.id for a in inp.acceptance]
+ schema = wire_schema(self.rubric, acceptance_ids)
+ ctx = self.context(inp)
+ measured, extra_text, extra_images = ctx.measured_scores, ctx.extra_text, ctx.extra_images
+ usage = Usage()
+ samples: list[JudgeOutput] = []
+ errors: list[str] = []
+ for k in range(self.n_samples):
+ seed = None if (self.n_samples == 1 and k == 0) else (inp.round_index * 1000 + k)
+ # a missing render is a pipeline bug, not a judge glitch → JudgeImageError propagates
+ system, messages = build_judge_messages(
+ inp, self.rubric, shuffle_seed=seed, max_images=self.max_images, max_px=self.max_px,
+ cache_dir=self.cache_dir, extra_images=extra_images, extra_text=extra_text,
+ )
+ req = ChatRequest(
+ messages=messages, system=system, response_schema=schema, temperature=self.temperature,
+ thinking=self.thinking, label=f"{self.label}:{self.rubric.name}:s{k}",
+ )
+ out, u, err = self._sample(req, acceptance_ids, measured)
+ usage = usage + u
+ if out is not None:
+ samples.append(out)
+ else:
+ errors.append(err)
+ if not samples:
+ return degraded_judgment(
+ self.rubric, " || ".join(errors)[:2000], usage=usage, judge_backend=self.model_id, n_requested=self.n_samples
+ )
+ return aggregate_samples(
+ self.rubric, samples, gates=inp.gates, acceptance_items=inp.acceptance,
+ console_errors=inp.renders.console_errors, usage=usage, judge_backend=self.model_id,
+ n_requested=self.n_samples, sample_errors=errors,
+ )
+
+ # ------------------------------------------------------------------ hook (ReferenceJudge overrides)
+ def context(self, inp: JudgeInput) -> JudgeContext:
+ """Per-call extras: measured-criterion scores (code), extra text and extra images.
+
+ The base judge computes no measured criteria, so a rubric that declares
+ some cannot be used with it (use ``ReferenceJudge`` or a subclass).
+ """
+ if self.rubric.measured_criteria():
+ raise ValueError(
+ f"rubric {self.rubric.name} has measured criteria "
+ f"{[c.id for c in self.rubric.measured_criteria()]} but VlmJudge computes none; use a specialised judge"
+ )
+ return JudgeContext()
+
+ # ------------------------------------------------------------------ one sample with retries
+ def _sample(
+ self, req: ChatRequest, acceptance_ids: list[str], measured: dict[str, float]
+ ) -> tuple[JudgeOutput | None, Usage, str]:
+ usage = Usage()
+ last = ""
+ for attempt in range(1, self.max_attempts + 1):
+ t0 = time.time()
+ try:
+ resp: ChatResponse = self.model.generate(req)
+ except ModelError as e:
+ last = f"ModelError(attempt {attempt}): {e}"
+ log.warning("judge %s: %s", req.label, last)
+ if not e.retryable and attempt >= 2:
+ break
+ continue
+ usage = usage + resp.usage
+ payload = resp.parsed if resp.parsed is not None else resp.text
+ try:
+ out = parse_judge_output(payload, self.rubric, acceptance_ids, measured_scores=measured)
+ log.debug("judge %s ok in %.1fs", req.label, time.time() - t0)
+ return out, usage, ""
+ except JudgeParseError as e:
+ last = f"parse(attempt {attempt}): {e}"
+ log.warning("judge %s: %s", req.label, last[:300])
+ req = req.model_copy(update={"temperature": min(1.0, self.temperature + 0.1 * attempt)})
+ return None, usage, last or "unknown judge failure"
diff --git a/harness/codeverse/languages/__init__.py b/harness/codeverse/languages/__init__.py
new file mode 100644
index 00000000..a6c476bb
--- /dev/null
+++ b/harness/codeverse/languages/__init__.py
@@ -0,0 +1,5 @@
+"""Per-language runtimes: lint → build/export → census. Raw languages only."""
+
+from codeverse.languages.base import LanguageRuntime, get_runtime
+
+__all__ = ["LanguageRuntime", "get_runtime"]
diff --git a/harness/codeverse/languages/_common.py b/harness/codeverse/languages/_common.py
new file mode 100644
index 00000000..ca7dd216
--- /dev/null
+++ b/harness/codeverse/languages/_common.py
@@ -0,0 +1,223 @@
+"""Shared helpers for python-language runtimes (blender, cadquery, urdf).
+
+Runtimes execute a *wrapper script* in a subprocess (Blender's python or the
+harness python). The wrapper writes ``artifacts/build.json`` (+ ``census.json``)
+and the runtime turns those into a :class:`BuildResult`. This module owns:
+
+* :func:`run_subprocess` — timeout, process-group kill, captured output;
+* :func:`tail` — bounded log tails for BuildResult;
+* :func:`read_json_file` / :func:`write_json_atomic`;
+* :func:`compose_build_result` — wrapper json + process outcome → BuildResult,
+ failing loud when the wrapper did not report.
+
+Wrappers themselves are standalone scripts (they never import ``codeverse``;
+Blender's bundled python cannot see this package).
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import signal
+import subprocess
+import time
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from codeverse.contracts.artifacts import BuildResult
+
+# lines Blender prints on every headless run that carry no signal for the agent
+_BLENDER_NOISE_PREFIXES = (
+ "Blender ",
+ "Read prefs",
+ "Color management",
+ "Warning: Falling back",
+ "ALSA lib",
+ "libEGL",
+ "MESA",
+ "glx:",
+ "Xlib:",
+ "Unable to open a display",
+ "Blender quit",
+ "Saved session recovery",
+ "Info: ",
+ "INFO Draco",
+ "Timer '",
+)
+_BLENDER_NOISE_SUBSTR = ("| INFO: ", "| WARNING: Draco")
+
+
+class WrapperError(RuntimeError):
+ """The wrapper process did not produce a readable ``build.json`` (harness bug or crash)."""
+
+
+@dataclass(frozen=True)
+class ProcResult:
+ """Outcome of one subprocess run."""
+
+ returncode: int
+ stdout: str
+ stderr: str
+ timed_out: bool
+ duration_ms: int
+
+
+def run_subprocess(
+ cmd: list[str],
+ *,
+ cwd: Path | str,
+ timeout_s: float,
+ env: Mapping[str, str] | None = None,
+ stdin_text: str | None = None,
+) -> ProcResult:
+ """Run ``cmd`` in its own process group; kill the whole group on timeout.
+
+ Never raises on non-zero exit — callers inspect :attr:`ProcResult.returncode`.
+ """
+ t0 = time.monotonic()
+ proc = subprocess.Popen(
+ cmd,
+ cwd=str(cwd),
+ env=dict(env) if env is not None else None,
+ stdin=subprocess.PIPE if stdin_text is not None else subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ start_new_session=True,
+ )
+ timed_out = False
+ try:
+ out, err = proc.communicate(input=stdin_text, timeout=timeout_s)
+ except subprocess.TimeoutExpired:
+ timed_out = True
+ _kill_group(proc)
+ out, err = proc.communicate()
+ return ProcResult(
+ returncode=proc.returncode if proc.returncode is not None else -1,
+ stdout=out or "",
+ stderr=err or "",
+ timed_out=timed_out,
+ duration_ms=int((time.monotonic() - t0) * 1000),
+ )
+
+
+def _kill_group(proc: subprocess.Popen[str]) -> None:
+ try:
+ os.killpg(proc.pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ proc.kill()
+
+
+def tail(text: str, *, max_lines: int = 40, max_chars: int = 4000) -> str:
+ """Last ``max_lines`` lines of ``text``, capped at ``max_chars`` characters."""
+ lines = text.splitlines()[-max_lines:]
+ s = "\n".join(lines)
+ return s[-max_chars:] if len(s) > max_chars else s
+
+
+def strip_blender_noise(text: str) -> str:
+ """Drop Blender's boilerplate stderr/stdout lines so the agent sees signal only."""
+ keep = [
+ ln for ln in text.splitlines()
+ if ln.strip() and not ln.startswith(_BLENDER_NOISE_PREFIXES) and not any(s in ln for s in _BLENDER_NOISE_SUBSTR)
+ ]
+ return "\n".join(keep)
+
+
+def write_json_atomic(path: Path, data: Any) -> None:
+ """tmp + rename so readers never see a partial file."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(path.suffix + ".tmp")
+ tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False, default=str))
+ tmp.replace(path)
+
+
+def read_json_file(path: Path) -> dict[str, Any]:
+ """Parse a JSON object file; raise :class:`WrapperError` if missing/invalid."""
+ if not path.is_file():
+ raise WrapperError(f"expected wrapper output missing: {path}")
+ try:
+ data = json.loads(path.read_text())
+ except ValueError as e:
+ raise WrapperError(f"invalid JSON in {path}: {e}") from e
+ if not isinstance(data, dict):
+ raise WrapperError(f"{path}: expected a JSON object")
+ return data
+
+
+def remove_stale(*paths: Path) -> None:
+ """Delete previous wrapper outputs so a crashed run cannot be mistaken for a fresh one."""
+ for p in paths:
+ p.unlink(missing_ok=True)
+
+
+def compose_build_result(
+ *,
+ language: str,
+ proc: ProcResult,
+ build_json: Path,
+ census_json: Path,
+ glb_path: Path,
+ extra_paths: Mapping[str, Path],
+ output_filter: Callable[[str], str] | None = None,
+) -> BuildResult:
+ """Merge the wrapper's ``build.json`` with the process outcome.
+
+ Contract: success requires the wrapper to say ``ok`` AND a non-empty GLB on
+ disk. Timeouts / crashes before ``build.json`` exists become a failed
+ BuildResult with a typed error (``BuildTimeout`` / ``WrapperCrash``) — never
+ an exception — so the orchestrator can route them to repair.
+ """
+ stdout_tail = tail(output_filter(proc.stdout) if output_filter else proc.stdout)
+ stderr_tail = tail(output_filter(proc.stderr) if output_filter else proc.stderr)
+ base = dict(language=language, stdout_tail=stdout_tail, stderr_tail=stderr_tail, duration_ms=proc.duration_ms)
+
+ if proc.timed_out:
+ return BuildResult(
+ ok=False,
+ error_type="BuildTimeout",
+ error_message=f"build exceeded the time limit ({proc.duration_ms // 1000}s); "
+ "reduce geometry (subdivisions, array counts, boolean ops) so the script finishes quickly",
+ **base,
+ )
+ if not build_json.is_file():
+ return BuildResult(
+ ok=False,
+ error_type="WrapperCrash",
+ error_message=(
+ f"the build wrapper exited with code {proc.returncode} before reporting; "
+ "see stderr_tail (memory cap hit / interpreter crash / missing dependency)"
+ ),
+ **base,
+ )
+ data = read_json_file(build_json)
+ census: dict[str, Any] = {}
+ if census_json.is_file():
+ try:
+ census = read_json_file(census_json)
+ except WrapperError:
+ census = {}
+ # keep the wrapper's extra diagnostics (traceback, warnings …) next to the census
+ census["build_report"] = {k: data[k] for k in ("traceback", "error_source", "warnings", "exported", "exec_ms") if k in data}
+ glb_ok = glb_path.is_file() and glb_path.stat().st_size > 0
+ ok = bool(data.get("ok")) and glb_ok
+ error_type = str(data.get("error_type") or "")
+ error_message = str(data.get("error_message") or "")
+ if data.get("ok") and not glb_ok:
+ error_type = error_type or "ExportEmpty"
+ error_message = error_message or "the script ran but no mesh geometry was exported (object.glb empty)"
+ extras = {k: str(p) for k, p in extra_paths.items() if p.is_file() and p.stat().st_size > 0}
+ line = data.get("error_line")
+ return BuildResult(
+ ok=ok,
+ glb_path=str(glb_path) if glb_ok else None,
+ extra_paths=extras,
+ error_type=error_type,
+ error_message=error_message,
+ error_file=str(data.get("error_file") or ""),
+ error_line=int(line) if isinstance(line, int) else None,
+ census=census,
+ **{**base, "duration_ms": int(data.get("duration_ms") or proc.duration_ms)},
+ )
diff --git a/harness/codeverse/languages/base.py b/harness/codeverse/languages/base.py
new file mode 100644
index 00000000..ebf78dc9
--- /dev/null
+++ b/harness/codeverse/languages/base.py
@@ -0,0 +1,65 @@
+"""LanguageRuntime protocol + registry.
+
+A runtime knows how to (1) lay down starter files for a plan, (2) statically
+lint agent code for known pitfalls, (3) execute it in a sandboxed subprocess
+and export the canonical artifact(s), (4) describe its authoring contract to
+prompts. Runtimes never import agent code into the harness process.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Protocol, runtime_checkable
+
+from codeverse.contracts.artifacts import BuildResult, GateReport
+from codeverse.contracts.common import Language
+from codeverse.contracts.plan import Plan
+from codeverse.workspace import Workspace
+
+
+@runtime_checkable
+class LanguageRuntime(Protocol):
+ language: Language
+ #: files the agent is expected to author (globs relative to workspace root)
+ entry_globs: tuple[str, ...]
+
+ def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
+ """Write starter files (contract comments, stubs) into ws.src; return paths."""
+ ...
+
+ def lint(self, ws: Workspace) -> GateReport:
+ """Static checks (syntax, forbidden APIs, known pitfalls, missing entry points)."""
+ ...
+
+ def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
+ """Execute the code in a subprocess; export ``artifacts/object.glb`` (+extras)."""
+ ...
+
+ def contract_doc(self) -> str:
+ """Prompt text: the authoring contract for this language (from prompts/<lang>/)."""
+ ...
+
+ def cookbook_path(self) -> Path: ...
+
+
+def get_runtime(language: Language | str) -> LanguageRuntime:
+ lang = Language(language)
+ if lang is Language.BLENDER:
+ from codeverse.languages.blender.runtime import BlenderRuntime
+
+ return BlenderRuntime()
+ if lang is Language.CADQUERY:
+ from codeverse.languages.cadquery.runtime import CadQueryRuntime
+
+ return CadQueryRuntime()
+ if lang is Language.THREEJS:
+ from codeverse.languages.threejs.runtime import ThreeJsRuntime
+
+ return ThreeJsRuntime()
+ if lang is Language.URDF_BLENDER:
+ from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
+
+ return UrdfBlenderRuntime()
+ from codeverse.languages.scene_threejs.runtime import SceneThreeJsRuntime
+
+ return SceneThreeJsRuntime()
diff --git a/harness/codeverse/languages/blender/CONTRACT.md b/harness/codeverse/languages/blender/CONTRACT.md
new file mode 100644
index 00000000..2574e18e
--- /dev/null
+++ b/harness/codeverse/languages/blender/CONTRACT.md
@@ -0,0 +1,65 @@
+# Blender (bpy) authoring contract
+
+You write ONE file, `src/model.py`, in **raw bpy** (Blender 5.x Python API). The harness runs it with
+`blender -b --factory-startup --python run_bpy.py -- --script src/model.py` in an **EMPTY scene**
+(no Cube/Camera/Light) and then exports `artifacts/object.glb` (+ `object.stl`) itself.
+
+## Frame, units, placement
+* **Z is up, -Y is the front** of the object, +X is its right. **Units are meters.**
+* The object **stands on z = 0** (lowest point at z = 0) and its footprint is **centred on the Z axis**.
+* Dimensions come from the plan's bboxes: respect them to ±1 cm; parts that "attach" must touch (no gaps).
+
+## Objects and names
+* One mesh object per part, **named exactly as the plan's PascalCase part name** (`SeatCushion`).
+ Instances: `Leg_0 … Leg_3`, optionally parented to an Empty named `Legs`.
+* Helper objects (boolean cutters) must be removed or hidden
+ (`cutter.hide_set(True); cutter.hide_render = True`) — visible objects are exported as-is.
+* Modifiers (bevel, subdivision, boolean, array, solidify, mirror) may stay unapplied:
+ the exporter applies them. Keep the total under **500 k triangles** and finish in **< 120 s**.
+
+## Materials
+* Every visible mesh gets a material: `mat = bpy.data.materials.new(name)`;
+ `bsdf = mat.node_tree.nodes["Principled BSDF"]`; set `inputs["Base Color"]`, `["Roughness"]`, `["Metallic"]`.
+ (Blender 4+/5 input names: "Specular IOR Level", "Subsurface Weight", "Transmission Weight",
+ "Coat Weight", "Sheen Weight", "Emission Color" / "Emission Strength".)
+* The GLB keeps only **flat PBR values + image textures + vertex colours**. Procedural node textures
+ (Noise, Voronoi, Wave …) are NOT exported — express detail with geometry and flat PBR per part.
+
+## Forbidden (the harness owns these; the lint rejects them)
+* cameras, lights, world/background, render settings, `bpy.ops.render.*`
+* `bpy.ops.export_*`, `bpy.ops.import_*`, `bpy.ops.wm.*`, `bpy.data.libraries`, `open()`, os/shutil/subprocess/network
+* imports other than `bpy, bmesh, mathutils, math, random (seeded), numpy` (+ stdlib data helpers)
+
+## Headless pitfalls (these cause most build failures)
+* `bpy.ops.*` act on the **selection/active object**: grab `obj = bpy.context.object` right after
+ `primitive_*_add`; do not rely on `bpy.context.selected_objects`.
+* `primitive_cube_add(size=1, scale=(sx,sy,sz))` then
+ `bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)` — pass all three flags.
+* bmesh: call `bm.verts.ensure_lookup_table()` (and edges/faces) before `bm.verts[i]`; finish with
+ `bm.to_mesh(me); bm.free(); me.update()`.
+* `modifier_apply` needs the object active + selected in OBJECT mode — or leave modifiers to the exporter.
+* `bpy.ops.object.join` inherits the ACTIVE object's transform — prefer separate named parts.
+* `use_auto_smooth` is gone: use `bpy.ops.object.shade_smooth_by_angle(angle=0.52)` or `shade_smooth()`.
+* Context dict overrides `bpy.ops.x({...})` are gone: `with bpy.context.temp_override(object=obj): ...`.
+* World AABB: `[obj.matrix_world @ Vector(c) for c in obj.bound_box]` after `bpy.context.view_layer.update()`.
+
+## Minimal example (copy the pattern)
+```python
+import bpy
+import math
+
+def make_material(name, rgb, roughness=0.5, metallic=0.0):
+ mat = bpy.data.materials.new(name)
+ bsdf = mat.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (*rgb, 1.0)
+ bsdf.inputs["Roughness"].default_value = roughness
+ bsdf.inputs["Metallic"].default_value = metallic
+ return mat
+
+bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 0.02), scale=(0.4, 0.3, 0.04))
+top = bpy.context.object
+top.name = "TableTop"
+bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+top.data.materials.append(make_material("Oak", (0.55, 0.36, 0.2), roughness=0.6))
+bev = top.modifiers.new("Bevel", "BEVEL"); bev.width = 0.005; bev.segments = 3
+```
diff --git a/harness/codeverse/languages/blender/__init__.py b/harness/codeverse/languages/blender/__init__.py
new file mode 100644
index 00000000..f9a2acbc
--- /dev/null
+++ b/harness/codeverse/languages/blender/__init__.py
@@ -0,0 +1,14 @@
+"""Blender (bpy) language: runtime, lint, skeleton; wrappers run inside Blender."""
+
+from codeverse.languages.blender.lint import lint_blender_file, lint_blender_source
+from codeverse.languages.blender.runtime import BlenderNotFoundError, BlenderRuntime
+from codeverse.languages.blender.skeleton import blender_skeleton_source, write_blender_skeleton
+
+__all__ = [
+ "BlenderNotFoundError",
+ "BlenderRuntime",
+ "blender_skeleton_source",
+ "lint_blender_file",
+ "lint_blender_source",
+ "write_blender_skeleton",
+]
diff --git a/harness/codeverse/languages/blender/lint.py b/harness/codeverse/languages/blender/lint.py
new file mode 100644
index 00000000..b97b839d
--- /dev/null
+++ b/harness/codeverse/languages/blender/lint.py
@@ -0,0 +1,283 @@
+"""Static lint for agent-authored bpy scripts (``src/model.py``).
+
+AST based, offline, milliseconds. Catches what the build would only reveal
+after a 2-10 s Blender round-trip — and the contract violations the build
+cannot see (file IO, render calls). Findings carry a concrete ``fix_hint``.
+
+Severity policy: ERROR = will fail at runtime or violates the contract;
+WARN = fragile in headless Blender / likely wrong; INFO = advice.
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+import time
+from pathlib import Path
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+
+GATE = "lint:blender"
+
+ALLOWED_IMPORTS = {
+ "bpy", "bmesh", "mathutils", "math", "random", "numpy", "np", "itertools", "functools",
+ "collections", "typing", "dataclasses", "colorsys", "statistics", "operator", "enum", "copy",
+ "sys", "os", "__future__", "bpy_extras",
+}
+FORBIDDEN_IMPORTS = {
+ "subprocess", "urllib", "requests", "socket", "http", "shutil", "ctypes", "pickle",
+ "multiprocessing", "threading", "webbrowser", "ftplib", "smtplib", "importlib", "pathlib",
+}
+# dotted-name prefixes of calls that violate the contract (harness owns them)
+FORBIDDEN_CALL_PREFIXES: tuple[tuple[str, str], ...] = (
+ ("bpy.ops.render.", "rendering is done by the harness; delete all bpy.ops.render.* calls"),
+ ("bpy.ops.export_", "export is done by the harness; delete all bpy.ops.export_* calls"),
+ ("bpy.ops.import_", "no imports of external files; build geometry procedurally"),
+ ("bpy.ops.wm.", "no bpy.ops.wm.* (file open/save/append/link/quit); the harness owns the file"),
+ ("bpy.ops.image.save", "no image file writes"),
+ ("bpy.data.libraries.", "no linking/appending external .blend data"),
+ ("os.system", "no shell commands"),
+ ("os.remove", "no file IO"), ("os.unlink", "no file IO"), ("os.rmdir", "no file IO"),
+ ("os.makedirs", "no file IO"), ("os.mkdir", "no file IO"), ("os.rename", "no file IO"),
+ ("subprocess.", "no subprocesses"),
+ ("urllib.", "no network"), ("requests.", "no network"),
+ ("shutil.", "no file IO"),
+)
+WARN_CALL_PREFIXES: tuple[tuple[str, str], ...] = (
+ ("bpy.data.cameras.new", "the harness owns cameras; remove camera creation"),
+ ("bpy.ops.object.camera_add", "the harness owns cameras; remove camera creation"),
+ ("bpy.data.lights.new", "the harness owns lighting; remove light creation"),
+ ("bpy.ops.object.light_add", "the harness owns lighting; remove light creation"),
+ ("bpy.data.worlds.new", "the harness owns the world/background; remove world code"),
+ ("bpy.ops.view3d.", "view3d operators fail in background mode (no 3D viewport)"),
+ ("bpy.ops.screen.", "screen operators fail in background mode"),
+ ("sys.exit", "do not exit; let the script fall off the end"),
+)
+REMOVED_BSDF_INPUTS = {
+ "Specular": "Specular IOR Level", "Subsurface": "Subsurface Weight", "Transmission": "Transmission Weight",
+ "Emission": "Emission Color (+ 'Emission Strength')", "Subsurface Color": "Base Color (subsurface tint removed)",
+ "Clearcoat": "Coat Weight", "Clearcoat Roughness": "Coat Roughness", "Sheen": "Sheen Weight",
+ "Transmission Roughness": "(removed) use Roughness", "Anisotropic": "Anisotropic", "Specular Tint": "Specular Tint (now a color)",
+}
+KNOWN_BINDINGS = ("Vector", "Matrix", "Euler", "Quaternion", "bmesh", "math", "random", "np", "numpy", "bpy")
+PASCAL_RE = re.compile(r"^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)*(?:_\d+)?$")
+
+
+def dotted(node: ast.AST) -> str:
+ """``bpy.ops.render.render`` for an Attribute/Name chain; '' otherwise."""
+ parts: list[str] = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if isinstance(node, ast.Name):
+ parts.append(node.id)
+ return ".".join(reversed(parts))
+ if parts: # method on an expression result, e.g. ``wp.box(1).rotate`` → ``<expr>.rotate``
+ return "<expr>." + ".".join(reversed(parts))
+ return ""
+
+
+class _Collector(ast.NodeVisitor):
+ """One pass over the tree; rules read the collected facts."""
+
+ def __init__(self) -> None:
+ self.imports: dict[str, int] = {} # top-level module → line
+ self.bound: set[str] = set()
+ self.calls: list[tuple[str, ast.Call]] = []
+ self.attr_stores: list[tuple[str, int]] = [] # dotted target of assignments
+ self.name_loads: list[tuple[str, int]] = []
+ self.bm_subscripts: list[int] = []
+ self.bsdf_inputs: list[tuple[str, int]] = []
+ self.names_assigned: list[str] = [] # string constants assigned to .name / name=
+ self.constants: list[tuple[str, int]] = []
+ self.has_temp_override = False
+ self.keywords: list[tuple[str, int]] = []
+
+ def visit_Import(self, node: ast.Import) -> None:
+ for a in node.names:
+ top = a.name.split(".")[0]
+ self.imports.setdefault(top, node.lineno)
+ self.bound.add((a.asname or a.name).split(".")[0])
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ top = (node.module or "").split(".")[0]
+ self.imports.setdefault(top, node.lineno)
+ for a in node.names:
+ self.bound.add(a.asname or a.name)
+
+ def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
+ self.bound.add(node.name)
+ for a in node.args.args + node.args.kwonlyargs + node.args.posonlyargs:
+ self.bound.add(a.arg)
+ if node.args.vararg:
+ self.bound.add(node.args.vararg.arg)
+ if node.args.kwarg:
+ self.bound.add(node.args.kwarg.arg)
+ self.generic_visit(node)
+
+ visit_AsyncFunctionDef = visit_FunctionDef # type: ignore[assignment]
+
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
+ self.bound.add(node.name)
+ self.generic_visit(node)
+
+ def visit_Name(self, node: ast.Name) -> None:
+ if isinstance(node.ctx, ast.Load):
+ self.name_loads.append((node.id, node.lineno))
+ else:
+ self.bound.add(node.id)
+
+ def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
+ if node.name:
+ self.bound.add(node.name)
+ self.generic_visit(node)
+
+ def visit_Call(self, node: ast.Call) -> None:
+ name = dotted(node.func)
+ self.calls.append((name, node))
+ if name.endswith("temp_override"):
+ self.has_temp_override = True
+ for a in node.args:
+ if isinstance(a, ast.Constant) and isinstance(a.value, str):
+ self.names_assigned.append(a.value)
+ for kw in node.keywords:
+ if kw.arg:
+ self.keywords.append((kw.arg, node.lineno))
+ if kw.arg == "name" and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
+ self.names_assigned.append(kw.value.value)
+ self.generic_visit(node)
+
+ def visit_Assign(self, node: ast.Assign) -> None:
+ for t in node.targets:
+ d = dotted(t)
+ if d:
+ self.attr_stores.append((d, node.lineno))
+ v = node.value
+ if isinstance(v, ast.Constant) and isinstance(v.value, str):
+ self.names_assigned.append(v.value)
+ elif isinstance(v, ast.JoinedStr) and v.values and isinstance(v.values[0], ast.Constant):
+ self.names_assigned.append(str(v.values[0].value).rstrip("_"))
+ self.generic_visit(node)
+
+ def visit_Subscript(self, node: ast.Subscript) -> None:
+ if isinstance(node.value, ast.Attribute):
+ if node.value.attr in ("verts", "edges", "faces") and not isinstance(node.slice, ast.Slice):
+ self.bm_subscripts.append(node.lineno)
+ if node.value.attr == "inputs" and isinstance(node.slice, ast.Constant) and isinstance(node.slice.value, str):
+ self.bsdf_inputs.append((node.slice.value, node.lineno))
+ self.generic_visit(node)
+
+ def visit_Constant(self, node: ast.Constant) -> None:
+ if isinstance(node.value, str):
+ self.constants.append((node.value, node.lineno))
+
+
+def _f(sev: Severity, msg: str, line: int | None = None, hint: str = "", target: str = "src/model.py") -> GateFinding:
+ data = {"line": line} if line else {}
+ return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data=data)
+
+
+def _rules(c: _Collector, source: str) -> list[GateFinding]:
+ out: list[GateFinding] = []
+ E, W, I = Severity.ERROR, Severity.WARN, Severity.INFO # noqa: E741
+ if "bpy" not in c.imports:
+ out.append(_f(E, "model.py never imports bpy", 1, "start the file with `import bpy`"))
+ for mod, line in c.imports.items():
+ if mod in FORBIDDEN_IMPORTS:
+ out.append(_f(E, f"forbidden import `{mod}`", line, "only bpy/bmesh/mathutils/math/random/numpy (+stdlib data helpers) are allowed"))
+ elif mod not in ALLOWED_IMPORTS:
+ out.append(_f(W, f"unexpected import `{mod}` (not available / not allowed in the build sandbox)", line, "use only bpy, bmesh, mathutils, math, random, numpy"))
+ for name, call in c.calls:
+ for prefix, hint in FORBIDDEN_CALL_PREFIXES:
+ if name.startswith(prefix):
+ out.append(_f(E, f"forbidden call `{name}`", call.lineno, hint))
+ for prefix, hint in WARN_CALL_PREFIXES:
+ if name.startswith(prefix):
+ out.append(_f(W, f"`{name}` — {hint}", call.lineno, hint))
+ if name == "open":
+ out.append(_f(E, "file IO via open() is forbidden", call.lineno, "no file reads/writes; the harness exports for you"))
+ if name.startswith("bpy.ops.") and call.args and isinstance(call.args[0], ast.Dict):
+ out.append(_f(E, f"`{name}({{...}})` context-dict override was removed in Blender 4.0", call.lineno,
+ "use `with bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj]): bpy.ops....()`"))
+ if name.endswith("primitive_cube_add"):
+ kws = {k.arg for k in call.keywords}
+ if "scale" in kws and "size" not in kws:
+ out.append(_f(W, "primitive_cube_add(scale=...) without size=1 makes a 2 m cube × scale (extents doubled)", call.lineno,
+ "pass `size=1, scale=(sx, sy, sz)` then `bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)`"))
+ if name.endswith("transform_apply"):
+ kws = {k.arg for k in call.keywords}
+ if kws and not {"location", "rotation", "scale"} <= kws:
+ out.append(_f(W, "transform_apply with partial kwargs: unspecified ones default to True (bakes location into mesh data)", call.lineno,
+ "always pass all three: transform_apply(location=False, rotation=False, scale=True)"))
+ if name.endswith("modifier_apply") and not c.has_temp_override:
+ out.append(_f(W, "bpy.ops.object.modifier_apply needs the object active+selected in OBJECT mode", call.lineno,
+ "either leave modifiers unapplied (the exporter applies them) or wrap: `with bpy.context.temp_override(object=obj): bpy.ops.object.modifier_apply(modifier=mod.name)`"))
+ if name.endswith("bpy.ops.object.join") or name == "bpy.ops.object.join":
+ out.append(_f(W, "bpy.ops.object.join needs all parts selected + an active object; the result inherits the ACTIVE object's transform", call.lineno,
+ "select all, set `bpy.context.view_layer.objects.active = main_obj` (identity transform) before join — or keep parts separate (preferred: named parts)"))
+ if name.endswith("shade_smooth") and any(k.arg == "use_auto_smooth" for k in call.keywords):
+ out.append(_f(E, "shade_smooth(use_auto_smooth=...) was removed in 4.1", call.lineno, "use `bpy.ops.object.shade_smooth_by_angle(angle=0.523599)` or `bpy.ops.object.shade_auto_smooth()`"))
+ if name.endswith(".calc_normals"):
+ out.append(_f(E, "Mesh.calc_normals() was removed in 4.0 (normals are computed automatically)", call.lineno, "delete the call (use me.update() if needed)"))
+ if name == "bpy.ops.wm.redraw_timer":
+ pass
+ for target, line in c.attr_stores:
+ if target.endswith(".use_auto_smooth") or target.endswith(".auto_smooth_angle"):
+ out.append(_f(E, f"`{target}` was removed in Blender 4.1", line, "use bpy.ops.object.shade_smooth_by_angle(angle=...) or mark sharp edges; or just shade_smooth()"))
+ if ".render." in target or target.endswith(".render"):
+ out.append(_f(W, f"render settings touched: `{target}`", line, "the harness owns rendering; delete render/engine/resolution code"))
+ if target.endswith("scene.camera") or target.endswith(".world"):
+ out.append(_f(W, f"`{target}` assignment — cameras/world are owned by the harness", line, "remove camera/world code"))
+ if target.endswith(".use_nodes"):
+ out.append(_f(I, "`use_nodes = True` is a no-op in Blender 5.x (materials always have a node tree); harmless", line, ""))
+ for key, line in c.bsdf_inputs:
+ if key in REMOVED_BSDF_INPUTS:
+ out.append(_f(E, f"Principled BSDF input '{key}' does not exist in Blender 4.x/5.x (KeyError at runtime)", line,
+ f"use inputs['{REMOVED_BSDF_INPUTS[key]}']"))
+ has_lookup = any(n.endswith("ensure_lookup_table") for n, _ in c.calls)
+ if "bmesh" in c.imports and c.bm_subscripts and not has_lookup:
+ out.append(_f(E, "bmesh verts/edges/faces indexed with [] but ensure_lookup_table() is never called → IndexError", c.bm_subscripts[0],
+ "after bm.from_mesh()/any topology change call `bm.verts.ensure_lookup_table(); bm.edges.ensure_lookup_table(); bm.faces.ensure_lookup_table()` before indexing"))
+ for name, line in c.name_loads:
+ if name in KNOWN_BINDINGS and name not in c.bound:
+ hint = {"Vector": "from mathutils import Vector", "Matrix": "from mathutils import Matrix", "Euler": "from mathutils import Euler",
+ "Quaternion": "from mathutils import Quaternion", "np": "import numpy as np", "numpy": "import numpy"}.get(name, f"import {name}")
+ out.append(_f(E, f"`{name}` is used but never imported (NameError at runtime)", line, hint))
+ break
+ if "bpy.context.selected_objects" in source:
+ out.append(_f(W, "bpy.context.selected_objects is unreliable in background mode (often empty)", None,
+ "keep references to the objects you create (`obj = bpy.context.object` right after primitive_*_add) instead of re-reading the selection"))
+ for const, line in c.constants:
+ if const == "BLENDER_EEVEE_NEXT":
+ out.append(_f(W, "'BLENDER_EEVEE_NEXT' is not a valid engine id in Blender 5.0", line, "render settings are owned by the harness; delete the line"))
+ pascal = [n for n in c.names_assigned if PASCAL_RE.match(n) and n not in ("Cube", "Cylinder", "Sphere", "Plane")]
+ if not pascal:
+ out.append(_f(W, "no PascalCase object names found (e.g. obj.name = 'SeatCushion')", None,
+ "name every visible mesh after its part: `obj.name = 'SeatCushion'`; instances `Leg_0..Leg_3`"))
+ else:
+ out.append(_f(I, f"named objects: {sorted(set(pascal))[:12]}", None, ""))
+ return out
+
+
+def lint_blender_source(source: str, *, target: str = "src/model.py") -> GateReport:
+ """Lint one bpy script; returns ``GateReport(gate='lint:blender')``."""
+ t0 = time.monotonic()
+ findings: list[GateFinding] = []
+ try:
+ tree = ast.parse(source, filename=target)
+ except SyntaxError as e:
+ findings.append(_f(Severity.ERROR, f"SyntaxError: {e.msg}", e.lineno, f"fix the syntax near line {e.lineno}: {(e.text or '').strip()!r}", target))
+ return GateReport(gate=GATE, passed=False, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
+ c = _Collector()
+ c.visit(tree)
+ findings = _rules(c, source)
+ for f in findings:
+ f.target = target
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
+
+
+def lint_blender_file(path: Path, *, target: str = "src/model.py") -> GateReport:
+ if not path.is_file():
+ return GateReport(gate=GATE, passed=False, findings=[_f(Severity.ERROR, f"{target} is missing", None, "create src/model.py (see the skeleton)", target)])
+ return lint_blender_source(path.read_text(), target=target)
diff --git a/harness/codeverse/languages/blender/runtime.py b/harness/codeverse/languages/blender/runtime.py
new file mode 100644
index 00000000..7bdd2440
--- /dev/null
+++ b/harness/codeverse/languages/blender/runtime.py
@@ -0,0 +1,126 @@
+"""BlenderRuntime: lint → build (headless Blender subprocess) → BuildResult.
+
+The agent's ``src/model.py`` is never imported here; ``wrappers/run_bpy.py`` runs
+it inside Blender, writes ``artifacts/build.json`` + ``census.json`` and exports
+``artifacts/object.glb`` (Y-up, +Z front) and ``object.stl`` (Z-up).
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+from codeverse.config import Settings, get_settings
+from codeverse.contracts.artifacts import BuildResult, GateReport
+from codeverse.contracts.common import Language
+from codeverse.contracts.plan import Plan, StaticPlan
+from codeverse.conventions import MAX_TRIS_OBJECT
+from codeverse.languages._common import (
+ compose_build_result,
+ remove_stale,
+ run_subprocess,
+ strip_blender_noise,
+)
+from codeverse.languages.blender.lint import lint_blender_file
+from codeverse.languages.blender.skeleton import write_blender_skeleton
+from codeverse.prompts import PROMPTS_DIR
+from codeverse.workspace import Workspace
+
+_PKG_DIR = Path(__file__).resolve().parent
+WRAPPER = _PKG_DIR / "wrappers" / "run_bpy.py"
+RENDER_WRAPPER = _PKG_DIR / "wrappers" / "render_bpy.py"
+
+
+class BlenderNotFoundError(RuntimeError):
+ """No usable Blender binary (configure ``C3V_BINARIES__BLENDER`` or put blender on PATH)."""
+
+
+def blender_env() -> dict[str, str]:
+ """Environment for a headless Blender child: keep the user's env but make sure the
+ host python (conda) cannot leak into Blender's bundled interpreter."""
+ env = dict(os.environ)
+ for k in ("PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP"):
+ env.pop(k, None)
+ env["PYTHONNOUSERSITE"] = "1"
+ return env
+
+
+class BlenderRuntime:
+ """LanguageRuntime for ``Language.BLENDER``."""
+
+ language = Language.BLENDER
+ entry_globs: tuple[str, ...] = ("src/model.py",)
+
+ def __init__(self, *, blender: str | None = None, settings: Settings | None = None):
+ self._settings = settings or get_settings()
+ self._blender = blender
+
+ # ------------------------------------------------------------------ helpers
+ def blender_binary(self) -> str:
+ b = self._blender or self._settings.resolve_blender()
+ if not b or not Path(b).exists():
+ raise BlenderNotFoundError("Blender binary not found; set C3V_BINARIES__BLENDER=/path/to/blender")
+ return b
+
+ def entry_file(self, ws: Workspace) -> Path:
+ return ws.src / "model.py"
+
+ def build_command(
+ self, ws: Workspace, *, stl: bool = True, blend: bool = False, seed: int = 0,
+ tri_limit: int = MAX_TRIS_OBJECT, rlimit_gb: float | None = None,
+ ) -> list[str]:
+ cmd = [
+ self.blender_binary(), "-b", "--factory-startup", "--python", str(WRAPPER), "--",
+ "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts),
+ "--rlimit-gb", str(rlimit_gb if rlimit_gb is not None else self._settings.limits.bpy_rlimit_gb),
+ "--tri-limit", str(tri_limit), "--seed", str(seed),
+ ]
+ if stl:
+ cmd.append("--stl")
+ if blend:
+ cmd.append("--blend")
+ return cmd
+
+ # ------------------------------------------------------------------ protocol
+ def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
+ if not isinstance(plan, StaticPlan): # ArticulatedPlan is a StaticPlan subclass → allowed
+ raise TypeError(f"BlenderRuntime.skeleton needs a StaticPlan/ArticulatedPlan, got {type(plan).__name__}")
+ return write_blender_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_blender_file(self.entry_file(ws))
+
+ def build(
+ self, ws: Workspace, *, timeout_s: int | None = None, stl: bool = True, blend: bool = False,
+ seed: int = 0, tri_limit: int = MAX_TRIS_OBJECT,
+ ) -> BuildResult:
+ """Run the wrapper; never raises for agent-code failures (typed BuildResult instead)."""
+ entry = self.entry_file(ws)
+ if not entry.is_file():
+ return BuildResult(ok=False, language=self.language.value, error_type="MissingEntryFile",
+ error_message="src/model.py does not exist", error_file="src/model.py")
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ build_json = ws.artifacts / "build.json"
+ census_json = ws.artifacts / "census.json"
+ glb = ws.artifacts / "object.glb"
+ stl_path = ws.artifacts / "object.stl"
+ blend_path = ws.artifacts / "object.blend"
+ remove_stale(build_json, census_json, glb, stl_path, blend_path)
+ cmd = self.build_command(ws, stl=stl, blend=blend, seed=seed, tri_limit=tri_limit)
+ proc = run_subprocess(
+ cmd, cwd=ws.root, env=blender_env(),
+ timeout_s=timeout_s or self._settings.limits.build_timeout_s,
+ )
+ return compose_build_result(
+ language=self.language.value, proc=proc, build_json=build_json, census_json=census_json,
+ glb_path=glb, extra_paths={"stl": stl_path, "blend": blend_path}, output_filter=strip_blender_noise,
+ )
+
+ def contract_doc(self) -> str:
+ p = PROMPTS_DIR / "blender" / "contract.md"
+ if p.is_file():
+ return p.read_text()
+ return (_PKG_DIR / "CONTRACT.md").read_text()
+
+ def cookbook_path(self) -> Path:
+ return PROMPTS_DIR / "blender" / "cookbook.md"
diff --git a/harness/codeverse/languages/blender/skeleton.py b/harness/codeverse/languages/blender/skeleton.py
new file mode 100644
index 00000000..6d19d4a5
--- /dev/null
+++ b/harness/codeverse/languages/blender/skeleton.py
@@ -0,0 +1,200 @@
+"""Starter ``src/model.py`` for the blender language, generated from a plan.
+
+The skeleton is *buildable as written*: every part is a placeholder box at its
+plan bbox (instances laid out by the plan's symmetry), with a Principled BSDF
+material, so the agent starts from a passing build and replaces bodies one
+function at a time. Only raw bpy in the output — no harness imports.
+"""
+
+from __future__ import annotations
+
+import math
+from pathlib import Path
+
+from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
+from codeverse.conventions import to_pascal, to_snake
+from codeverse.workspace import Workspace
+
+# keyword → (rgb, roughness, metallic) placeholder finishes so the first render is not all-grey
+_FINISHES: tuple[tuple[tuple[str, ...], tuple[float, float, float], float, float], ...] = (
+ (("wood", "oak", "walnut", "pine", "timber", "birch"), (0.55, 0.36, 0.20), 0.55, 0.0),
+ (("steel", "chrome", "aluminium", "aluminum", "metal", "iron", "brass"), (0.75, 0.75, 0.78), 0.35, 1.0),
+ (("fabric", "cloth", "cushion", "upholster", "velvet", "linen"), (0.45, 0.30, 0.30), 0.9, 0.0),
+ (("leather",), (0.30, 0.16, 0.10), 0.6, 0.0),
+ (("glass", "acrylic"), (0.85, 0.9, 0.95), 0.05, 0.0),
+ (("rubber", "tire", "tyre"), (0.05, 0.05, 0.05), 0.9, 0.0),
+ (("plastic", "abs", "nylon"), (0.9, 0.9, 0.9), 0.4, 0.0),
+ (("black",), (0.05, 0.05, 0.05), 0.5, 0.0),
+ (("white",), (0.9, 0.9, 0.9), 0.5, 0.0),
+ (("red",), (0.7, 0.1, 0.1), 0.5, 0.0),
+ (("blue",), (0.1, 0.2, 0.7), 0.5, 0.0),
+ (("green",), (0.1, 0.5, 0.2), 0.5, 0.0),
+)
+
+
+def finish_for(text: str) -> tuple[tuple[float, float, float], float, float]:
+ """Placeholder (rgb, roughness, metallic) from material words; neutral grey otherwise."""
+ low = text.lower()
+ for words, rgb, rough, metal in _FINISHES:
+ if any(w in low for w in words):
+ return rgb, rough, metal
+ return (0.6, 0.6, 0.6), 0.5, 0.0
+
+
+def instance_centers(bbox: BBox, n: int, symmetry: str) -> list[tuple[float, float, float]]:
+ """Placeholder centres for ``n`` instances of a part using the plan's symmetry hint."""
+ cx, cy, cz = bbox.center
+ if n <= 1:
+ return [(cx, cy, cz)]
+ if n == 2 and symmetry == "mirror_x":
+ return [(abs(cx), cy, cz), (-abs(cx), cy, cz)]
+ if n == 2 and symmetry == "mirror_y":
+ return [(cx, abs(cy), cz), (cx, -abs(cy), cz)]
+ if n == 4 and symmetry in ("mirror_x", "mirror_y"):
+ ax, ay = abs(cx), abs(cy)
+ return [(ax, -ay, cz), (-ax, -ay, cz), (-ax, ay, cz), (ax, ay, cz)]
+ if symmetry == "radial":
+ r = math.hypot(cx, cy)
+ a0 = math.atan2(cy, cx)
+ return [(r * math.cos(a0 + 2 * math.pi * i / n), r * math.sin(a0 + 2 * math.pi * i / n), cz) for i in range(n)]
+ return [(cx, cy, cz) for _ in range(n)]
+
+
+def _fmt(v: tuple[float, float, float]) -> str:
+ return "(" + ", ".join(f"{x:.3f}" for x in v) + ")"
+
+
+def _part_function(p: PartPlan) -> str:
+ pascal, snake = to_pascal(p.name), to_snake(p.name)
+ rgb, rough, metal = finish_for(f"{p.material} {p.description}")
+ mn, mx = p.bbox.min, p.bbox.max
+ lines = [
+ f"def build_{snake}(index=0, center={_fmt(p.bbox.center)}):",
+ f' """{pascal} — {p.role}',
+ f" {p.description}",
+ f" Material: {p.material or 'n/a'}",
+ f" Plan bbox: center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}",
+ f" x in [{mn[0]:.3f}, {mx[0]:.3f}] y in [{mn[1]:.3f}, {mx[1]:.3f}] z in [{mn[2]:.3f}, {mx[2]:.3f}]",
+ ]
+ if p.attach_to:
+ lines.append(f" Attaches to: {to_pascal(p.attach_to)} (surfaces must touch, no gap)")
+ if p.instances > 1:
+ lines.append(f" Instances: {p.instances} ({p.symmetry}) -> named {pascal}_0..{pascal}_{p.instances - 1}, parented to Empty '{pascal}s'")
+ lines += [
+ ' """',
+ f' name = "{pascal}"' if p.instances == 1 else f' name = f"{pascal}_{{index}}"',
+ f" mat = make_material(name + \"Mat\", {_fmt(rgb)}, roughness={rough}, metallic={metal})",
+ " # TODO: replace this placeholder box with the real geometry (keep the name + bbox)",
+ f" return add_box(name, center, {_fmt(p.bbox.extents)}, mat, bevel={_bevel(p.bbox):.4f})",
+ "",
+ "",
+ ]
+ return "\n".join(lines)
+
+
+def _bevel(bbox: BBox) -> float:
+ return max(0.0, min(0.01, 0.08 * min(bbox.extents)))
+
+
+def _main_body(plan: StaticPlan) -> str:
+ lines = ["def main():"]
+ for p in plan.parts:
+ pascal, snake = to_pascal(p.name), to_snake(p.name)
+ if p.instances == 1:
+ lines.append(f" build_{snake}()")
+ continue
+ centers = instance_centers(p.bbox, p.instances, p.symmetry)
+ lines.append(f" {snake}_parent = add_empty(\"{pascal}s\")")
+ lines.append(f" for i, c in enumerate({[tuple(round(x, 4) for x in c) for c in centers]}): # TODO: exact placement")
+ lines.append(f" obj = build_{snake}(i, c)")
+ lines.append(f" obj.parent = {snake}_parent")
+ lines += ["", "", "main()", ""]
+ return "\n".join(lines)
+
+
+def blender_skeleton_source(plan: StaticPlan) -> str:
+ """Return the complete starter ``model.py`` text for ``plan``."""
+ ob = plan.overall_bbox
+ parts_doc = "\n".join(
+ f" - {to_pascal(p.name)}{'' if p.instances == 1 else f' x{p.instances}'}: {p.role}; bbox center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}"
+ for p in plan.parts
+ )
+ accept = "\n".join(f" - [{a.id}] {a.text}" for a in plan.acceptance) or " (none listed)"
+ header = f'''"""{plan.object_name} — Blender (bpy) model.
+
+{plan.summary}
+Style: {plan.style_notes or "n/a"}
+
+CONTRACT (the harness runs this file in an EMPTY scene with `blender -b --factory-startup`):
+ * Z is up, -Y is the FRONT, units are METERS. Object stands on z=0, footprint centred on Z.
+ * Overall bbox: center {_fmt(ob.center)} extents {_fmt(ob.extents)}
+ -> x in [{ob.min[0]:.3f}, {ob.max[0]:.3f}] y in [{ob.min[1]:.3f}, {ob.max[1]:.3f}] z in [{ob.min[2]:.3f}, {ob.max[2]:.3f}]
+ * One mesh object per part, named EXACTLY as below (PascalCase); instances Name_0..Name_N-1.
+ * Materials: Principled BSDF (Base Color / Roughness / Metallic). GLB keeps flat PBR + image
+ textures only (procedural node textures are NOT exported) — rely on geometry + flat PBR.
+ * Modifiers may stay unapplied (the exporter applies them). Keep < 500k triangles, < 120 s.
+ * NEVER: cameras, lights, world, render settings, export/import, file IO, bpy.ops.wm.*.
+ * Only bpy / bmesh / mathutils / math / random (seeded). No other imports.
+
+PARTS:
+{parts_doc}
+
+ACCEPTANCE:
+{accept}
+"""
+import math
+import random
+
+import bpy
+import bmesh # noqa: F401 (available for custom meshes: bm = bmesh.new(); ... bm.to_mesh(me))
+from mathutils import Vector, Matrix # noqa: F401
+
+random.seed(0)
+
+
+# ----------------------------------------------------------------------------- helpers (plain bpy)
+def make_material(name, rgb, roughness=0.5, metallic=0.0):
+ """Principled BSDF material with flat PBR values (what the GLB keeps)."""
+ mat = bpy.data.materials.new(name)
+ bsdf = mat.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (rgb[0], rgb[1], rgb[2], 1.0)
+ bsdf.inputs["Roughness"].default_value = roughness
+ bsdf.inputs["Metallic"].default_value = metallic
+ return mat
+
+
+def add_box(name, center, extents, material=None, bevel=0.0):
+ """Axis-aligned box: size=1 cube scaled to `extents`, scale baked into the mesh."""
+ bpy.ops.mesh.primitive_cube_add(size=1, location=center, scale=extents)
+ obj = bpy.context.object
+ obj.name = name
+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+ if material is not None:
+ obj.data.materials.append(material)
+ if bevel > 0:
+ mod = obj.modifiers.new("Bevel", "BEVEL")
+ mod.width = bevel
+ mod.segments = 3
+ mod.limit_method = "ANGLE"
+ return obj
+
+
+def add_empty(name):
+ """Parent Empty for instance groups (exported as a named node)."""
+ empty = bpy.data.objects.new(name, None)
+ bpy.context.collection.objects.link(empty)
+ return empty
+
+
+# ----------------------------------------------------------------------------- parts
+'''
+ body = "".join(_part_function(p) for p in plan.parts)
+ return header + body + _main_body(plan)
+
+
+def write_blender_skeleton(ws: Workspace, plan: StaticPlan) -> list[Path]:
+ """Write ``src/model.py`` (overwrites) and return the written paths."""
+ ws.src.mkdir(parents=True, exist_ok=True)
+ path = ws.src / "model.py"
+ path.write_text(blender_skeleton_source(plan))
+ return [path]
diff --git a/harness/codeverse/languages/blender/wrappers/render_bpy.py b/harness/codeverse/languages/blender/wrappers/render_bpy.py
new file mode 100644
index 00000000..445b3b44
--- /dev/null
+++ b/harness/codeverse/languages/blender/wrappers/render_bpy.py
@@ -0,0 +1,199 @@
+"""Optional native Blender renderer (EEVEE / Cycles-CPU) for "native material" previews.
+
+ blender -b --factory-startup --python render_bpy.py -- \
+ (--glb object.glb | --script model.py) --out renders/ \
+ [--views front_right_34:35:22,front:0:8,...] [--engine eevee|cycles] \
+ [--size 768] [--samples 16]
+
+Neutral 3-point light rig + shadow-catcher ground, camera framed from the world bbox
+(azimuth 0 = front = -Y, CCW from above; elevation above the horizon). Writes one PNG
+per view and ``renders.json``. The judge normally uses the three.js renderer; this
+exists for previews of Blender-only material features. Standalone: no ``codeverse``.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import math
+import os
+import runpy
+import sys
+import time
+
+DEFAULT_VIEWS = "front_right_34:35:22,back_left_34:215:22,front:0:8,top:0:88"
+
+
+def parse_args(argv: list[str]) -> argparse.Namespace:
+ p = argparse.ArgumentParser(prog="render_bpy.py")
+ p.add_argument("--glb")
+ p.add_argument("--script")
+ p.add_argument("--out", required=True)
+ p.add_argument("--views", default=DEFAULT_VIEWS)
+ p.add_argument("--engine", choices=("eevee", "cycles", "workbench"), default="eevee")
+ p.add_argument("--size", type=int, default=768)
+ p.add_argument("--samples", type=int, default=16)
+ p.add_argument("--fov", type=float, default=40.0)
+ a = p.parse_args(argv)
+ if not a.glb and not a.script:
+ p.error("one of --glb / --script is required")
+ return a
+
+
+def clear_scene(bpy) -> None:
+ for obj in list(bpy.data.objects):
+ bpy.data.objects.remove(obj, do_unlink=True)
+ for coll in list(bpy.data.collections):
+ bpy.data.collections.remove(coll)
+ for block in (bpy.data.meshes, bpy.data.materials, bpy.data.cameras, bpy.data.lights, bpy.data.images):
+ for item in list(block):
+ block.remove(item)
+ bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection
+
+
+def load_subject(bpy, args) -> list:
+ """Import the GLB or run the model script; return the subject objects."""
+ if args.glb:
+ bpy.ops.import_scene.gltf(filepath=os.path.abspath(args.glb))
+ else:
+ sys.argv = [args.script]
+ runpy.run_path(os.path.abspath(args.script), run_name="__main__")
+ subject = [o for o in bpy.context.scene.objects if o.type in ("MESH", "CURVE", "FONT", "SURFACE", "META", "EMPTY")]
+ for o in list(bpy.context.scene.objects): # the subject must not bring cameras/lights
+ if o.type in ("CAMERA", "LIGHT"):
+ bpy.data.objects.remove(o, do_unlink=True)
+ return subject
+
+
+def scene_bounds(bpy, objects):
+ from mathutils import Vector
+
+ bpy.context.view_layer.update()
+ dg = bpy.context.evaluated_depsgraph_get()
+ mins, maxs = [1e9] * 3, [-1e9] * 3
+ for o in objects:
+ if o.type == "EMPTY":
+ continue
+ oe = o.evaluated_get(dg)
+ for c in oe.bound_box:
+ w = oe.matrix_world @ Vector(c)
+ for i in range(3):
+ mins[i], maxs[i] = min(mins[i], w[i]), max(maxs[i], w[i])
+ if mins[0] > maxs[0]:
+ raise RuntimeError("nothing to render: no mesh geometry")
+ return Vector(mins), Vector(maxs)
+
+
+def setup_world_and_lights(bpy, center, radius) -> None:
+ from mathutils import Vector
+
+ scene = bpy.context.scene
+ world = bpy.data.worlds.get("World") or bpy.data.worlds.new("World")
+ scene.world = world
+ bg = world.node_tree.nodes.get("Background")
+ if bg:
+ bg.inputs[0].default_value = (0.92, 0.92, 0.92, 1.0)
+ bg.inputs[1].default_value = 0.6
+ # ground shadow catcher at the lowest point
+ bpy.ops.mesh.primitive_plane_add(size=radius * 12, location=(center.x, center.y, 0.0))
+ ground = bpy.context.object
+ ground.name = "_Ground"
+ ground.is_shadow_catcher = True
+ gmat = bpy.data.materials.new("_GroundMat")
+ gmat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (0.85, 0.85, 0.85, 1)
+ gmat.node_tree.nodes["Principled BSDF"].inputs["Roughness"].default_value = 1.0
+ ground.data.materials.append(gmat)
+ # 3-point area rig; energy scales with size (W for area lights)
+ e = 40.0 * radius * radius
+ for name, (ax, ay, az), energy, size in (
+ ("_Key", (-1.0, -1.2, 1.6), e * 1.0, radius * 1.5),
+ ("_Fill", (1.6, -0.8, 0.8), e * 0.4, radius * 2.5),
+ ("_Rim", (0.4, 1.6, 1.2), e * 0.6, radius * 1.0),
+ ):
+ ldata = bpy.data.lights.new(name, "AREA")
+ ldata.energy = energy
+ ldata.size = size
+ light = bpy.data.objects.new(name, ldata)
+ bpy.context.collection.objects.link(light)
+ light.location = center + Vector((ax, ay, az)) * radius * 2.2
+ light.rotation_euler = (center - light.location).to_track_quat("-Z", "Y").to_euler()
+
+
+def setup_render(bpy, args) -> None:
+ scene = bpy.context.scene
+ r = scene.render
+ r.resolution_x = r.resolution_y = args.size
+ r.resolution_percentage = 100
+ r.film_transparent = False
+ if hasattr(r.image_settings, "media_type"):
+ r.image_settings.media_type = "IMAGE"
+ r.image_settings.file_format = "PNG"
+ r.image_settings.color_mode = "RGB"
+ scene.view_settings.view_transform = "Standard"
+ if args.engine == "cycles":
+ r.engine = "CYCLES"
+ scene.cycles.device = "CPU"
+ scene.cycles.samples = args.samples
+ scene.cycles.use_denoising = True
+ elif args.engine == "workbench":
+ r.engine = "BLENDER_WORKBENCH"
+ else:
+ r.engine = "BLENDER_EEVEE" if "BLENDER_EEVEE" in _engine_ids(bpy) else "BLENDER_EEVEE_NEXT"
+ scene.eevee.taa_render_samples = max(4, args.samples)
+
+
+def _engine_ids(bpy) -> set[str]:
+ prop = bpy.types.RenderSettings.bl_rna.properties["engine"]
+ return {e.identifier for e in prop.enum_items}
+
+
+def place_camera(bpy, cam, center, radius, az_deg, el_deg, fov_deg) -> None:
+ from mathutils import Vector
+
+ az, el = math.radians(az_deg), math.radians(el_deg)
+ dist = radius / math.sin(math.radians(fov_deg) / 2) * 1.15
+ d = Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el)))
+ cam.location = center + d * dist
+ cam.rotation_euler = (center - cam.location).to_track_quat("-Z", "Y").to_euler()
+ cam.data.clip_start, cam.data.clip_end = dist * 0.01, dist * 10
+
+
+def main() -> int:
+ argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
+ args = parse_args(argv)
+ import bpy
+
+ t0 = time.monotonic()
+ out = os.path.abspath(args.out)
+ os.makedirs(out, exist_ok=True)
+ clear_scene(bpy)
+ subject = load_subject(bpy, args)
+ mn, mx = scene_bounds(bpy, subject)
+ center = (mn + mx) / 2
+ radius = max((mx - mn).length / 2, 1e-3)
+ setup_world_and_lights(bpy, center, radius)
+ setup_render(bpy, args)
+ cam_data = bpy.data.cameras.new("_Cam")
+ cam_data.angle = math.radians(args.fov)
+ cam = bpy.data.objects.new("_Cam", cam_data)
+ bpy.context.collection.objects.link(cam)
+ bpy.context.scene.camera = cam
+ views = []
+ for spec in args.views.split(","):
+ name, az, el = spec.split(":")
+ place_camera(bpy, cam, center, radius, float(az), float(el), args.fov)
+ path = os.path.join(out, f"view_{name}.png")
+ bpy.context.scene.render.filepath = path
+ bpy.ops.render.render(write_still=True)
+ views.append({"name": name, "path": path, "azimuth_deg": float(az), "elevation_deg": float(el),
+ "camera_position": [round(v, 4) for v in cam.location], "look_at": [round(v, 4) for v in center]})
+ manifest = {"views": views, "engine": bpy.context.scene.render.engine, "width": args.size, "height": args.size,
+ "bbox_min": [round(v, 4) for v in mn], "bbox_max": [round(v, 4) for v in mx],
+ "duration_ms": int((time.monotonic() - t0) * 1000)}
+ with open(os.path.join(out, "renders.json"), "w", encoding="utf-8") as fh:
+ json.dump(manifest, fh, indent=2)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/harness/codeverse/languages/blender/wrappers/run_bpy.py b/harness/codeverse/languages/blender/wrappers/run_bpy.py
new file mode 100644
index 00000000..01174d27
--- /dev/null
+++ b/harness/codeverse/languages/blender/wrappers/run_bpy.py
@@ -0,0 +1,418 @@
+"""Blender build wrapper — executed BY Blender, never imported by the harness.
+
+ blender -b --factory-startup --python run_bpy.py -- \
+ --script /abs/src/model.py --out /abs/artifacts [--stl] [--blend] \
+ [--rlimit-gb 12] [--tri-limit 600000] [--seed 0]
+
+What it does (in order):
+ 1. caps the address space (RLIMIT_AS) so geometry bombs die in-process;
+ 2. empties the factory scene (Cube/Camera/Light + orphan data), sets metric units;
+ 3. seeds ``random`` / numpy / mathutils.noise;
+ 4. runs the agent script with ``runpy`` and maps any exception to a line of model.py;
+ 5. collects a census (evaluated tri counts, world bboxes, materials, parents);
+ 6. warns on leftovers (cameras, lights, touched render settings, visible cutters);
+ 7. exports ``object.glb`` (Y-up, +Z front) and optionally ``object.stl`` (Z-up);
+ 8. writes ``build.json`` + ``census.json`` atomically and exits 0.
+
+Exit codes: 0 = reported (even if the script failed); 2 = wrapper bug (no report).
+This file must stay standalone: Blender's python cannot import ``codeverse``.
+"""
+
+from __future__ import annotations
+
+import argparse
+import contextlib
+import json
+import os
+import random
+import re
+import runpy
+import sys
+import time
+import traceback
+from typing import Any
+
+GLB_NAME = "object.glb"
+STL_NAME = "object.stl"
+BLEND_NAME = "object.blend"
+EXPORT_TYPES = {"MESH", "CURVE", "SURFACE", "FONT", "META", "EMPTY"}
+DEFAULT_NAME_RE = re.compile(r"^(Cube|Cylinder|Sphere|Plane|Cone|Torus|Icosphere|Circle|Grid|Monkey|Mesh|Text|Curve)(\.\d+)?$")
+
+
+# ----------------------------------------------------------------------------- args / io
+def parse_args(argv: list[str]) -> argparse.Namespace:
+ p = argparse.ArgumentParser(prog="run_bpy.py")
+ p.add_argument("--script", required=True)
+ p.add_argument("--out", required=True)
+ p.add_argument("--stl", action="store_true")
+ p.add_argument("--blend", action="store_true")
+ p.add_argument("--rlimit-gb", type=float, default=12.0)
+ p.add_argument("--tri-limit", type=int, default=600_000)
+ p.add_argument("--seed", type=int, default=0)
+ return p.parse_args(argv)
+
+
+def write_json_atomic(path: str, data: Any) -> None:
+ tmp = path + ".tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(data, fh, indent=2, default=str)
+ os.replace(tmp, path)
+
+
+def apply_rlimit(gb: float) -> str:
+ """Cap virtual memory; returns a note for build.json."""
+ if gb <= 0:
+ return "rlimit disabled"
+ try:
+ import resource
+
+ cap = int(gb * 1024**3)
+ _soft, hard = resource.getrlimit(resource.RLIMIT_AS)
+ lim = cap if hard == resource.RLIM_INFINITY else min(cap, hard)
+ resource.setrlimit(resource.RLIMIT_AS, (lim, hard))
+ return f"RLIMIT_AS={lim // 1024**2} MB"
+ except (ImportError, ValueError, OSError) as e:
+ return f"rlimit not applied: {e}"
+
+
+# ----------------------------------------------------------------------------- scene prep
+def clear_scene(bpy: Any) -> None:
+ """Remove every object + datablock of the factory scene; keep scene/world."""
+ for obj in list(bpy.data.objects):
+ bpy.data.objects.remove(obj, do_unlink=True)
+ for coll in list(bpy.data.collections):
+ bpy.data.collections.remove(coll)
+ for attr in ("meshes", "materials", "cameras", "lights", "curves", "images", "node_groups", "textures"):
+ block = getattr(bpy.data, attr)
+ for item in list(block):
+ with contextlib.suppress(RuntimeError): # data still used by a linked library
+ block.remove(item)
+ scene = bpy.context.scene
+ # removing "Collection" leaves the view layer's active collection dangling → bpy.context.collection
+ # would be None; point it back at the scene master collection so `.objects.link()` works.
+ bpy.context.view_layer.active_layer_collection = bpy.context.view_layer.layer_collection
+ scene.unit_settings.system = "METRIC"
+ scene.unit_settings.scale_length = 1.0
+ scene.unit_settings.length_unit = "METERS"
+
+
+def seed_everything(seed: int) -> None:
+ random.seed(seed)
+ try:
+ import numpy as np
+
+ np.random.seed(seed)
+ except ImportError:
+ pass
+ try:
+ from mathutils import noise
+
+ noise.seed_set(seed)
+ except (ImportError, AttributeError):
+ pass
+
+
+def render_fingerprint(bpy: Any) -> dict[str, Any]:
+ r = bpy.context.scene.render
+ return {
+ "engine": r.engine,
+ "resolution": [r.resolution_x, r.resolution_y],
+ "filepath": r.filepath,
+ "frame_range": [bpy.context.scene.frame_start, bpy.context.scene.frame_end],
+ }
+
+
+# ----------------------------------------------------------------------------- exec + error mapping
+def map_exception(exc: BaseException, script_path: str) -> dict[str, Any]:
+ """Traceback → {error_type, error_message, error_file, error_line, error_source, traceback}."""
+ real = os.path.realpath(script_path)
+ info: dict[str, Any] = {
+ "error_type": type(exc).__name__,
+ "error_message": str(exc) or type(exc).__name__,
+ "error_file": "",
+ "error_line": None,
+ "error_source": "",
+ }
+ if isinstance(exc, SyntaxError) and exc.filename and os.path.realpath(exc.filename) == real:
+ info.update(error_file=os.path.basename(script_path), error_line=exc.lineno, error_source=(exc.text or "").strip())
+ else:
+ for frame in reversed(traceback.extract_tb(exc.__traceback__)):
+ if os.path.realpath(frame.filename) == real:
+ info.update(error_file=os.path.basename(script_path), error_line=frame.lineno, error_source=(frame.line or "").strip())
+ break
+ if isinstance(exc, MemoryError):
+ info["error_message"] = (
+ "MemoryError: the script hit the memory cap — a geometry bomb (tiny remesh voxel_size, "
+ "huge subdivision/array counts, nested loops creating millions of faces). Reduce it."
+ )
+ tb = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
+ info["traceback"] = tb[-6000:]
+ return info
+
+
+def run_script(script_path: str) -> dict[str, Any] | None:
+ """Execute the agent script as ``__main__``; return error info or None."""
+ script_dir = os.path.dirname(os.path.abspath(script_path))
+ if script_dir not in sys.path:
+ sys.path.insert(0, script_dir)
+ saved_argv = sys.argv
+ sys.argv = [script_path]
+ try:
+ runpy.run_path(script_path, run_name="__main__")
+ except SystemExit as e: # sys.exit(0) in a script is not a failure
+ if e.code not in (None, 0):
+ return map_exception(e, script_path)
+ except BaseException as e: # noqa: BLE001 — every failure must be reported, never propagate
+ return map_exception(e, script_path)
+ finally:
+ sys.argv = saved_argv
+ return None
+
+
+# ----------------------------------------------------------------------------- census
+def world_bbox(obj_eval: Any, Vector: Any) -> tuple[list[float], list[float]] | None:
+ corners = [obj_eval.matrix_world @ Vector(c) for c in obj_eval.bound_box]
+ if not corners:
+ return None
+ mn = [min(c[i] for c in corners) for i in range(3)]
+ mx = [max(c[i] for c in corners) for i in range(3)]
+ return [round(v, 5) for v in mn], [round(v, 5) for v in mx]
+
+
+def is_hidden(obj: Any) -> bool:
+ try:
+ return bool(obj.hide_render or obj.hide_viewport or obj.hide_get())
+ except RuntimeError: # object not in the view layer
+ return True
+
+
+def collect_census(bpy: Any, tri_limit: int) -> dict[str, Any]:
+ from mathutils import Vector
+
+ bpy.context.view_layer.update()
+ dg = bpy.context.evaluated_depsgraph_get()
+ scene_objects = set(bpy.context.scene.objects.keys())
+ boolean_operands: dict[str, list[str]] = {}
+ objects: list[dict[str, Any]] = []
+ total_tris = 0
+ mins: list[list[float]] = []
+ maxs: list[list[float]] = []
+ for obj in bpy.data.objects:
+ rec: dict[str, Any] = {
+ "name": obj.name,
+ "type": obj.type,
+ "parent": obj.parent.name if obj.parent else None,
+ "in_scene": obj.name in scene_objects,
+ "hidden": is_hidden(obj),
+ "materials": [s.material.name for s in obj.material_slots if s.material],
+ "modifiers": [m.type for m in obj.modifiers],
+ "location": [round(v, 5) for v in obj.matrix_world.translation],
+ }
+ for m in obj.modifiers:
+ if m.type == "BOOLEAN" and getattr(m, "object", None) is not None:
+ boolean_operands.setdefault(m.object.name, []).append(obj.name)
+ if obj.type in ("MESH", "CURVE", "SURFACE", "FONT", "META"):
+ try:
+ ob_eval = obj.evaluated_get(dg)
+ me = ob_eval.to_mesh()
+ me.calc_loop_triangles()
+ rec["tri_count"] = len(me.loop_triangles)
+ rec["vert_count"] = len(me.vertices)
+ rec["has_uv"] = bool(me.uv_layers)
+ rec["has_vertex_colors"] = bool(me.color_attributes)
+ bb = world_bbox(ob_eval, Vector)
+ ob_eval.to_mesh_clear()
+ except RuntimeError as e:
+ rec["tri_count"] = 0
+ rec["census_error"] = str(e)
+ bb = None
+ if bb:
+ rec["bbox_min"], rec["bbox_max"] = bb
+ if rec["in_scene"] and not rec["hidden"]:
+ mins.append(bb[0])
+ maxs.append(bb[1])
+ if rec["in_scene"] and not rec["hidden"]:
+ total_tris += rec["tri_count"]
+ objects.append(rec)
+ warnings: list[str] = []
+ cams = [o.name for o in bpy.data.objects if o.type == "CAMERA"]
+ lights = [o.name for o in bpy.data.objects if o.type == "LIGHT"]
+ if cams:
+ warnings.append(f"script created camera(s) {cams}: not exported; remove camera code (the harness owns cameras)")
+ if lights:
+ warnings.append(f"script created light(s) {lights}: not exported; remove light code (the harness owns lighting)")
+ for cutter, users in boolean_operands.items():
+ o = bpy.data.objects.get(cutter)
+ if o is not None and not is_hidden(o) and o.name in scene_objects:
+ warnings.append(
+ f"object '{cutter}' is a boolean operand of {users} but is still visible and WILL be exported as "
+ f"geometry; hide it: obj.hide_set(True); obj.hide_render = True (or bpy.data.objects.remove(obj))"
+ )
+ visible = [o for o in objects if o["in_scene"] and not o["hidden"] and o["type"] == "MESH"]
+ if not visible:
+ warnings.append("no visible mesh objects in the scene — nothing to export")
+ for o in visible:
+ if not o["materials"]:
+ warnings.append(f"mesh '{o['name']}' has no material (will export grey)")
+ if DEFAULT_NAME_RE.match(o["name"]):
+ warnings.append(f"mesh '{o['name']}' keeps a default primitive name; set obj.name = '<PartName>'")
+ unlinked = [o["name"] for o in objects if o["type"] == "MESH" and not o["in_scene"]]
+ if unlinked:
+ warnings.append(f"mesh object(s) {unlinked} were created but never linked to the scene → not exported; "
+ "call bpy.context.collection.objects.link(obj)")
+ if total_tris > tri_limit:
+ warnings.append(f"triangle budget exceeded: {total_tris} > {tri_limit}")
+ census = {
+ "objects": objects,
+ "n_mesh_objects": len(visible),
+ "tri_count": total_tris,
+ "tri_limit": tri_limit,
+ "materials": [m.name for m in bpy.data.materials],
+ "cameras": cams,
+ "lights": lights,
+ "warnings": warnings,
+ "frame": "z_up_neg_y_front",
+ }
+ if mins:
+ census["scene_bbox_min"] = [round(min(m[i] for m in mins), 5) for i in range(3)]
+ census["scene_bbox_max"] = [round(max(m[i] for m in maxs), 5) for i in range(3)]
+ return census
+
+
+# ----------------------------------------------------------------------------- export
+def select_exportables(bpy: Any) -> list[Any]:
+ bpy.ops.object.select_all(action="DESELECT")
+ chosen = []
+ for obj in bpy.context.scene.objects:
+ if obj.type in EXPORT_TYPES and not is_hidden(obj):
+ with contextlib.suppress(RuntimeError): # not in the view layer (excluded collection)
+ obj.select_set(True)
+ chosen.append(obj)
+ if chosen:
+ bpy.context.view_layer.objects.active = chosen[0]
+ return chosen
+
+
+def export_glb(bpy: Any, path: str) -> None:
+ """Kwargs verified on Blender 5.0.1 (io_scene_gltf2)."""
+ bpy.ops.export_scene.gltf(
+ filepath=path,
+ export_format="GLB",
+ use_selection=True,
+ use_visible=False,
+ export_apply=True,
+ export_yup=True,
+ export_materials="EXPORT",
+ export_image_format="AUTO",
+ export_cameras=False,
+ export_lights=False,
+ export_animations=False,
+ export_extras=False,
+ export_normals=True,
+ export_texcoords=True,
+ )
+
+
+def export_stl(bpy: Any, path: str) -> None:
+ if hasattr(bpy.ops.wm, "stl_export"): # Blender 4.2+ native exporter (Z-up, -Y... forward 'Y' default)
+ bpy.ops.wm.stl_export(filepath=path, export_selected_objects=True, apply_modifiers=True, ascii_format=False, global_scale=1.0)
+ else: # legacy add-on
+ bpy.ops.export_mesh.stl(filepath=path, use_selection=True, use_mesh_modifiers=True, ascii=False)
+
+
+# ----------------------------------------------------------------------------- main
+def main() -> int:
+ argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
+ args = parse_args(argv)
+ import bpy # noqa: PLC0415 — only available inside Blender
+
+ out_dir = os.path.abspath(args.out)
+ os.makedirs(out_dir, exist_ok=True)
+ script = os.path.abspath(args.script)
+ build_path = os.path.join(out_dir, "build.json")
+ census_path = os.path.join(out_dir, "census.json")
+ for stale in (build_path, census_path, os.path.join(out_dir, GLB_NAME), os.path.join(out_dir, STL_NAME)):
+ if os.path.exists(stale):
+ os.remove(stale)
+
+ t0 = time.monotonic()
+ report: dict[str, Any] = {
+ "ok": False, "language": "blender", "error_type": "", "error_message": "", "error_file": "",
+ "error_line": None, "error_source": "", "traceback": "", "warnings": [], "exported": {},
+ "blender_version": bpy.app.version_string, "rlimit": apply_rlimit(args.rlimit_gb),
+ }
+ if not os.path.isfile(script):
+ report.update(error_type="FileNotFoundError", error_message=f"script not found: {script}")
+ write_json_atomic(build_path, report)
+ return 0
+
+ clear_scene(bpy)
+ seed_everything(args.seed)
+ render_before = render_fingerprint(bpy)
+
+ t_exec = time.monotonic()
+ err = run_script(script)
+ report["exec_ms"] = int((time.monotonic() - t_exec) * 1000)
+ if err:
+ report.update(err)
+
+ # the script may have left edit mode / odd selection states behind
+ try:
+ if bpy.context.object and bpy.context.object.mode != "OBJECT":
+ bpy.ops.object.mode_set(mode="OBJECT")
+ except RuntimeError:
+ pass
+
+ census = collect_census(bpy, args.tri_limit)
+ if render_fingerprint(bpy) != render_before:
+ census["warnings"].append("script changed render settings (engine/resolution/filepath/frames): remove that code")
+ report["warnings"] = census["warnings"]
+ write_json_atomic(census_path, census)
+
+ if not err and census["tri_count"] > args.tri_limit:
+ report.update(
+ error_type="TriangleBudgetExceeded",
+ error_message=f"{census['tri_count']} triangles > limit {args.tri_limit}; lower subdivision levels / segment counts",
+ )
+
+ chosen = select_exportables(bpy)
+ if chosen:
+ glb = os.path.join(out_dir, GLB_NAME)
+ try:
+ export_glb(bpy, glb)
+ report["exported"]["glb"] = glb
+ except Exception as e: # noqa: BLE001
+ if not report["error_type"]:
+ report.update(error_type="ExportError", error_message=f"glTF export failed: {e}")
+ report["traceback"] = report["traceback"] or traceback.format_exc()[-4000:]
+ if args.stl:
+ stl = os.path.join(out_dir, STL_NAME)
+ try:
+ select_exportables(bpy)
+ export_stl(bpy, stl)
+ report["exported"]["stl"] = stl
+ except Exception as e: # noqa: BLE001
+ report["warnings"].append(f"STL export failed: {e}")
+ if args.blend:
+ blend = os.path.join(out_dir, BLEND_NAME)
+ try:
+ bpy.ops.wm.save_as_mainfile(filepath=blend, copy=True)
+ report["exported"]["blend"] = blend
+ except Exception as e: # noqa: BLE001
+ report["warnings"].append(f".blend save failed: {e}")
+ elif not report["error_type"]:
+ report.update(error_type="EmptyScene", error_message="the script created no visible mesh objects")
+
+ report["ok"] = not report["error_type"] and "glb" in report["exported"]
+ report["duration_ms"] = int((time.monotonic() - t0) * 1000)
+ write_json_atomic(build_path, report)
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ code = main()
+ except Exception: # wrapper bug: no report, loud exit
+ traceback.print_exc()
+ code = 2
+ sys.exit(code)
diff --git a/harness/codeverse/languages/cadquery/CONTRACT.md b/harness/codeverse/languages/cadquery/CONTRACT.md
new file mode 100644
index 00000000..5e699960
--- /dev/null
+++ b/harness/codeverse/languages/cadquery/CONTRACT.md
@@ -0,0 +1,52 @@
+# CadQuery authoring contract
+
+You write ONE file, `src/model.py`, in **raw CadQuery** (`import cadquery as cq`, plus `math` /
+`random`). The harness imports it in a sandboxed subprocess, reads the module-level `result` and
+exports `artifacts/object.glb` (Y-up, named nodes, part colours), `object.step` and `object.stl` itself.
+
+## Frame, units, placement
+* **Z is up, -Y is the front**, +X is the right. **Units are meters.**
+* The object **stands on z = 0** and its footprint is **centred on the Z axis**.
+* Respect the plan bboxes to ±1 cm; attached parts must touch (tiny overlaps are fine, gaps are not).
+
+## `result`
+* **Preferred**: `result = cq.Assembly()` with one `.add(shape, name="PascalName", color=cq.Color(r, g, b))`
+ per part. Names are the plan's PascalCase part names; instances `Leg_0 … Leg_3`.
+ Place instances with `loc=cq.Location(cq.Vector(x, y, z))` (shape built at the origin), or translate the shape.
+ Sub-assemblies are allowed (`legs = cq.Assembly(); ... ; result.add(legs, name="Legs")`).
+* Acceptable: `result = <cq.Workplane>` — exported as ONE grey node (no part names → weaker judging).
+* `result` must exist **at module level after import** (not only under `if __name__ == "__main__":`).
+
+## Forbidden (lint rejects)
+* file IO, `open()`, `cq.exporters.*`, `cq.importers.*`, `.save()` / `.export()`, `show_object()`, `exit()`
+* imports other than `cadquery`, `math`, `random`, `numpy` (+ stdlib data helpers)
+
+## CadQuery pitfalls (most build failures)
+* `cq.Workplane("XY").box(x, y, z)` is **centred** at the origin; `.cylinder(height, radius)` — height first;
+ `.circle(r).extrude(h)` starts at the workplane (z = 0) and goes +Z.
+* `.translate()`, `.rotate()`, `.mirror()` return **new** objects — always reassign.
+* `.rotate(axisStart, axisEnd, angle)` and `cq.Location(vec, axis, angle)` take **degrees**.
+* Fillets/chamfers fail with `BRep_API: command not done` when the radius ≥ the adjacent wall thickness
+ or neighbouring fillets conflict: keep radius < 0.45 × min thickness, fillet few edges
+ (`.edges("|Z")`, `.edges(">Z")`), fillet before booleans, wrap cosmetic fillets in `try/except`.
+* String selectors (`|Z`, `>X`, `%CIRCLE`) are axis aligned; after booleans re-select by geometry, never by index.
+* `cq.Solid.makeSphere(r)` → use `cq.Workplane().sphere(r)`; `makeCone(r1, r2, h)` has its base at z = 0.
+* Sweeps/lofts: profile perpendicular to the path start; `sweep(path, isFrenet=True)`; loft wires same orientation.
+* Revolve on `"XZ"`: `cq.Workplane("XZ").polyline(pts).close().revolve(360, (0, 0, 0), (0, 1, 0))` —
+ the axis is in workplane-local coordinates (local Y = world Z); the profile must not cross the axis.
+* Keep features ≥ 1e-4 m (OCC tolerance is 1e-7); avoid zero-thickness faces; `.clean()` after unions.
+* Patterns: `.rarray()`, `.polarArray()`, `.pushPoints()` beat Python loops of `.union()`.
+
+## Minimal example (copy the pattern)
+```python
+import cadquery as cq
+
+top = cq.Workplane("XY").box(0.5, 0.5, 0.04).edges("|Z").fillet(0.02).translate((0, 0, 0.58))
+leg = cq.Workplane("XY").box(0.04, 0.04, 0.56)
+
+result = cq.Assembly(name="SideTable")
+result.add(top, name="TableTop", color=cq.Color(0.55, 0.36, 0.2))
+for i, (sx, sy) in enumerate([(1, -1), (-1, -1), (-1, 1), (1, 1)]):
+ result.add(leg, name=f"Leg_{i}", loc=cq.Location(cq.Vector(sx * 0.21, sy * 0.21, 0.28)),
+ color=cq.Color(0.55, 0.36, 0.2))
+```
diff --git a/harness/codeverse/languages/cadquery/__init__.py b/harness/codeverse/languages/cadquery/__init__.py
new file mode 100644
index 00000000..f56796bf
--- /dev/null
+++ b/harness/codeverse/languages/cadquery/__init__.py
@@ -0,0 +1,13 @@
+"""CadQuery language: runtime, lint, skeleton; wrapper runs in a python subprocess."""
+
+from codeverse.languages.cadquery.lint import lint_cadquery_file, lint_cadquery_source
+from codeverse.languages.cadquery.runtime import CadQueryRuntime
+from codeverse.languages.cadquery.skeleton import cadquery_skeleton_source, write_cadquery_skeleton
+
+__all__ = [
+ "CadQueryRuntime",
+ "cadquery_skeleton_source",
+ "lint_cadquery_file",
+ "lint_cadquery_source",
+ "write_cadquery_skeleton",
+]
diff --git a/harness/codeverse/languages/cadquery/lint.py b/harness/codeverse/languages/cadquery/lint.py
new file mode 100644
index 00000000..80da23cd
--- /dev/null
+++ b/harness/codeverse/languages/cadquery/lint.py
@@ -0,0 +1,177 @@
+"""Static lint for agent-authored CadQuery scripts (``src/model.py``).
+
+AST based, offline. Enforces the import allow-list, forbids file IO / export /
+``show_object``, requires a module-level ``result`` and flags the known OCC
+pitfalls (degree/radian confusion, hemisphere ``makeSphere``, unnamed parts …).
+"""
+
+from __future__ import annotations
+
+import ast
+import re
+import time
+from pathlib import Path
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+
+GATE = "lint:cadquery"
+ALLOWED_IMPORTS = {"cadquery", "cq", "math", "random", "numpy", "np", "itertools", "functools", "collections",
+ "typing", "dataclasses", "enum", "copy", "statistics", "operator", "__future__"}
+FORBIDDEN_IMPORTS = {"os", "sys", "subprocess", "shutil", "pathlib", "urllib", "requests", "socket", "http", "pickle",
+ "ctypes", "multiprocessing", "threading", "importlib", "OCP", "OCC", "ocp_vscode", "cq_editor", "cq_warehouse", "build123d"}
+FORBIDDEN_CALLS: tuple[tuple[str, str], ...] = (
+ ("show_object", "show_object() exists only in CQ-editor; delete it — the harness renders for you"),
+ ("show", "show() is for notebooks/CQ-editor; delete it"),
+ ("open", "no file IO; the harness exports STEP/STL/GLB from `result`"),
+ ("cq.exporters.export", "no exporting; assign the model to `result` and the harness exports"),
+ ("exporters.export", "no exporting; assign the model to `result` and the harness exports"),
+ ("cq.importers.", "no importing external geometry; build it procedurally"),
+ ("importers.", "no importing external geometry; build it procedurally"),
+ ("exit", "never exit; `result` must be readable after the module runs"),
+ ("quit", "never exit"),
+)
+FORBIDDEN_METHODS = {"save": "no .save()/.export() on the assembly — the harness exports", "export": "no .export() — the harness exports",
+ "exportStep": "no export calls", "exportStl": "no export calls", "exportSvg": "no export calls"}
+PASCAL_RE = re.compile(r"^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)*(?:_\d+)?$")
+
+
+def dotted(node: ast.AST) -> str:
+ parts: list[str] = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if isinstance(node, ast.Name):
+ parts.append(node.id)
+ return ".".join(reversed(parts))
+ if parts: # method on an expression result, e.g. ``wp.box(1).rotate`` → ``<expr>.rotate``
+ return "<expr>." + ".".join(reversed(parts))
+ return ""
+
+
+def _f(sev: Severity, msg: str, line: int | None = None, hint: str = "", target: str = "src/model.py") -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data={"line": line} if line else {})
+
+
+class _Collector(ast.NodeVisitor):
+ def __init__(self) -> None:
+ self.imports: dict[str, int] = {}
+ self.calls: list[tuple[str, ast.Call]] = []
+ self.add_calls: list[ast.Call] = []
+ self.name_kw: list[str] = []
+
+ def visit_Import(self, node: ast.Import) -> None:
+ for a in node.names:
+ top = a.name.split(".")[0]
+ self.imports.setdefault(top, node.lineno)
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ self.imports.setdefault((node.module or "").split(".")[0], node.lineno)
+
+ def visit_Call(self, node: ast.Call) -> None:
+ name = dotted(node.func)
+ self.calls.append((name, node))
+ if name.endswith(".add"):
+ self.add_calls.append(node)
+ for kw in node.keywords:
+ if kw.arg == "name" and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
+ self.name_kw.append(kw.value.value)
+ self.generic_visit(node)
+
+
+def _top_level_assigned(tree: ast.Module) -> tuple[set[str], set[str]]:
+ """Names bound at module level; names bound only under ``if __name__ == '__main__'``."""
+ top: set[str] = set()
+ guarded: set[str] = set()
+
+ def targets(stmt: ast.stmt) -> list[str]:
+ out = []
+ if isinstance(stmt, (ast.Assign,)):
+ for t in stmt.targets:
+ out += [n.id for n in ast.walk(t) if isinstance(n, ast.Name)]
+ elif isinstance(stmt, (ast.AnnAssign, ast.AugAssign)) and isinstance(stmt.target, ast.Name):
+ out.append(stmt.target.id)
+ elif isinstance(stmt, (ast.For, ast.With, ast.If, ast.Try)):
+ for sub in ast.iter_child_nodes(stmt):
+ if isinstance(sub, ast.stmt):
+ out += targets(sub)
+ return out
+
+ for stmt in tree.body:
+ if isinstance(stmt, ast.If) and "__main__" in ast.dump(stmt.test):
+ for sub in stmt.body:
+ guarded.update(targets(sub))
+ else:
+ top.update(targets(stmt))
+ return top, guarded
+
+
+def _rules(c: _Collector, tree: ast.Module, source: str) -> list[GateFinding]:
+ E, W, I = Severity.ERROR, Severity.WARN, Severity.INFO # noqa: E741
+ out: list[GateFinding] = []
+ if "cadquery" not in c.imports:
+ out.append(_f(E, "model.py never imports cadquery", 1, "start with `import cadquery as cq`"))
+ for mod, line in c.imports.items():
+ if mod in FORBIDDEN_IMPORTS:
+ out.append(_f(E, f"forbidden import `{mod}`", line, "only `cadquery`, `math`, `random`, `numpy` (+ stdlib data helpers) are allowed"))
+ elif mod not in ALLOWED_IMPORTS:
+ out.append(_f(W, f"unexpected import `{mod}` (may not exist in the build sandbox)", line, "stick to cadquery / math / random / numpy"))
+ top, guarded = _top_level_assigned(tree)
+ if "result" not in top:
+ hint = "assign `result = cq.Assembly(...)` (or a Workplane) at module level, NOT under `if __name__ == '__main__':`" if "result" in guarded \
+ else "end the file with a module-level `result = <cq.Assembly or cq.Workplane>`"
+ out.append(_f(E, "no module-level `result` assignment", None, hint))
+ for name, call in c.calls:
+ for pat, hint in FORBIDDEN_CALLS:
+ if name == pat or (pat.endswith(".") and name.startswith(pat)):
+ out.append(_f(E, f"forbidden call `{name}()`", call.lineno, hint))
+ last = name.rsplit(".", 1)[-1] if "." in name else ""
+ if last in FORBIDDEN_METHODS and not name.startswith("cq."):
+ out.append(_f(E, f"forbidden call `{name}()`", call.lineno, FORBIDDEN_METHODS[last]))
+ if name.endswith("Solid.makeSphere") and not any(k.arg and k.arg.startswith("angle") for k in call.keywords):
+ out.append(_f(W, "cq.Solid.makeSphere(r) without angle args builds a partial sphere in some versions", call.lineno,
+ "use `cq.Workplane('XY').sphere(r)` or pass angleDegrees1=-90, angleDegrees2=90, angleDegrees3=360"))
+ if name.endswith(".rotate") and len(call.args) == 3 and isinstance(call.args[2], ast.BinOp) and "pi" in ast.dump(call.args[2]).lower():
+ out.append(_f(E, ".rotate(...) takes DEGREES; this argument looks like radians (math.pi expression)", call.lineno,
+ "pass degrees: `.rotate((0,0,0), (0,0,1), 90)` or `math.degrees(angle_rad)`"))
+ if name.endswith(".fillet") or name.endswith(".chamfer"):
+ out.append(_f(I, f"{last}: OCC fails ('BRep_API: command not done') when radius >= wall thickness or edges conflict", call.lineno,
+ "keep radius < 0.45 x min thickness; select few edges (`.edges('|Z')`); wrap cosmetic fillets in try/except"))
+ if c.add_calls:
+ unnamed = [a.lineno for a in c.add_calls if not any(k.arg == "name" for k in a.keywords)]
+ if unnamed:
+ out.append(_f(W, f"assembly .add() without name= at line(s) {unnamed[:6]} → auto uuid node names", unnamed[0],
+ "give every part a PascalCase name: `.add(shape, name='SeatCushion', color=cq.Color(r, g, b))`"))
+ uncol = [a.lineno for a in c.add_calls if not any(k.arg == "color" for k in a.keywords)]
+ if uncol:
+ out.append(_f(I, f".add() without color= at line(s) {uncol[:6]} (exports grey)", uncol[0], "add `color=cq.Color(r, g, b)` (0-1 floats)"))
+ bad = [n for n in c.name_kw if not PASCAL_RE.match(n)]
+ if bad:
+ out.append(_f(W, f"part names not PascalCase: {bad[:6]}", None, "use PascalCase part names, instances Name_0..Name_N"))
+ elif "Assembly" not in source:
+ out.append(_f(W, "result is not a cq.Assembly: the model exports as ONE unnamed part", None,
+ "prefer `result = cq.Assembly(); result.add(part, name='PartName', color=cq.Color(...))` per part"))
+ if re.search(r"\.cylinder\(\s*[0-9.]+\s*,\s*[0-9.]+\s*\)", source):
+ out.append(_f(I, "Workplane.cylinder(height, radius): height comes FIRST", None, "check the argument order: .cylinder(height, radius)"))
+ return out
+
+
+def lint_cadquery_source(source: str, *, target: str = "src/model.py") -> GateReport:
+ t0 = time.monotonic()
+ try:
+ tree = ast.parse(source, filename=target)
+ except SyntaxError as e:
+ f = _f(Severity.ERROR, f"SyntaxError: {e.msg}", e.lineno, f"fix the syntax near line {e.lineno}: {(e.text or '').strip()!r}", target)
+ return GateReport(gate=GATE, passed=False, findings=[f], duration_ms=int((time.monotonic() - t0) * 1000))
+ c = _Collector()
+ c.visit(tree)
+ findings = _rules(c, tree, source)
+ for f in findings:
+ f.target = target
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.monotonic() - t0) * 1000))
+
+
+def lint_cadquery_file(path: Path, *, target: str = "src/model.py") -> GateReport:
+ if not path.is_file():
+ return GateReport(gate=GATE, passed=False, findings=[_f(Severity.ERROR, f"{target} is missing", None, "create src/model.py (see the skeleton)", target)])
+ return lint_cadquery_source(path.read_text(), target=target)
diff --git a/harness/codeverse/languages/cadquery/runtime.py b/harness/codeverse/languages/cadquery/runtime.py
new file mode 100644
index 00000000..f887bd04
--- /dev/null
+++ b/harness/codeverse/languages/cadquery/runtime.py
@@ -0,0 +1,89 @@
+"""CadQueryRuntime: lint → build (python subprocess running ``wrappers/run_cq.py``) → BuildResult.
+
+The wrapper needs ``cadquery`` + ``trimesh`` importable by the interpreter it runs
+under (``sys.executable`` by default; override with ``python`` for a dedicated env).
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+from pathlib import Path
+
+from codeverse.config import Settings, get_settings
+from codeverse.contracts.artifacts import BuildResult, GateReport
+from codeverse.contracts.common import Language
+from codeverse.contracts.plan import Plan, StaticPlan
+from codeverse.conventions import MAX_TRIS_OBJECT
+from codeverse.languages._common import compose_build_result, remove_stale, run_subprocess
+from codeverse.languages.cadquery.lint import lint_cadquery_file
+from codeverse.languages.cadquery.skeleton import write_cadquery_skeleton
+from codeverse.prompts import PROMPTS_DIR
+from codeverse.workspace import Workspace
+
+_PKG_DIR = Path(__file__).resolve().parent
+WRAPPER = _PKG_DIR / "wrappers" / "run_cq.py"
+
+
+def cadquery_env() -> dict[str, str]:
+ env = dict(os.environ)
+ env.pop("PYTHONSTARTUP", None)
+ env.setdefault("OMP_NUM_THREADS", "4")
+ env.setdefault("PYTHONUNBUFFERED", "1")
+ return env
+
+
+class CadQueryRuntime:
+ """LanguageRuntime for ``Language.CADQUERY``."""
+
+ language = Language.CADQUERY
+ entry_globs: tuple[str, ...] = ("src/model.py",)
+
+ def __init__(self, *, python: str | None = None, settings: Settings | None = None, rlimit_gb: float = 8.0):
+ self._settings = settings or get_settings()
+ self._python = python or sys.executable
+ self._rlimit_gb = rlimit_gb
+
+ def entry_file(self, ws: Workspace) -> Path:
+ return ws.src / "model.py"
+
+ def build_command(self, ws: Workspace, *, seed: int = 0, tri_limit: int = MAX_TRIS_OBJECT,
+ tolerance: float = 0.001, angular_tolerance: float = 0.15) -> list[str]:
+ return [
+ self._python, str(WRAPPER), "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts),
+ "--rlimit-gb", str(self._rlimit_gb), "--tri-limit", str(tri_limit), "--seed", str(seed),
+ "--tolerance", str(tolerance), "--angular-tolerance", str(angular_tolerance),
+ ]
+
+ # ------------------------------------------------------------------ protocol
+ def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
+ if not isinstance(plan, StaticPlan):
+ raise TypeError(f"CadQueryRuntime.skeleton needs a StaticPlan, got {type(plan).__name__}")
+ return write_cadquery_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_cadquery_file(self.entry_file(ws))
+
+ def build(self, ws: Workspace, *, timeout_s: int | None = None, seed: int = 0,
+ tri_limit: int = MAX_TRIS_OBJECT) -> BuildResult:
+ entry = self.entry_file(ws)
+ if not entry.is_file():
+ return BuildResult(ok=False, language=self.language.value, error_type="MissingEntryFile",
+ error_message="src/model.py does not exist", error_file="src/model.py")
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ build_json, census_json = ws.artifacts / "build.json", ws.artifacts / "census.json"
+ glb, step, stl = ws.artifacts / "object.glb", ws.artifacts / "object.step", ws.artifacts / "object.stl"
+ remove_stale(build_json, census_json, glb, step, stl)
+ proc = run_subprocess(self.build_command(ws, seed=seed, tri_limit=tri_limit), cwd=ws.root, env=cadquery_env(),
+ timeout_s=timeout_s or self._settings.limits.build_timeout_s)
+ return compose_build_result(language=self.language.value, proc=proc, build_json=build_json, census_json=census_json,
+ glb_path=glb, extra_paths={"step": step, "stl": stl})
+
+ def contract_doc(self) -> str:
+ p = PROMPTS_DIR / "cadquery" / "contract.md"
+ if p.is_file():
+ return p.read_text()
+ return (_PKG_DIR / "CONTRACT.md").read_text()
+
+ def cookbook_path(self) -> Path:
+ return PROMPTS_DIR / "cadquery" / "cookbook.md"
diff --git a/harness/codeverse/languages/cadquery/skeleton.py b/harness/codeverse/languages/cadquery/skeleton.py
new file mode 100644
index 00000000..9273ee2d
--- /dev/null
+++ b/harness/codeverse/languages/cadquery/skeleton.py
@@ -0,0 +1,109 @@
+"""Starter ``src/model.py`` for the cadquery language, generated from a plan.
+
+Buildable as written: a ``cq.Assembly`` of placeholder boxes at the plan bboxes
+(instances laid out by symmetry), each named and coloured, so the agent starts
+from a green build and replaces ``build_<part>()`` bodies. Raw cadquery only.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.contracts.plan import PartPlan, StaticPlan
+from codeverse.conventions import to_pascal, to_snake
+from codeverse.languages.blender.skeleton import finish_for, instance_centers
+from codeverse.workspace import Workspace
+
+
+def _fmt(v: tuple[float, float, float]) -> str:
+ return "(" + ", ".join(f"{x:.3f}" for x in v) + ")"
+
+
+def _part_function(p: PartPlan) -> str:
+ pascal, snake = to_pascal(p.name), to_snake(p.name)
+ mn, mx = p.bbox.min, p.bbox.max
+ ex, ey, ez = p.bbox.extents
+ lines = [
+ f"def build_{snake}():",
+ f' """{pascal} — {p.role}',
+ f" {p.description}",
+ f" Material: {p.material or 'n/a'}",
+ f" Plan bbox (world, Z-up): center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}",
+ f" x in [{mn[0]:.3f}, {mx[0]:.3f}] y in [{mn[1]:.3f}, {mx[1]:.3f}] z in [{mn[2]:.3f}, {mx[2]:.3f}]",
+ ]
+ if p.attach_to:
+ lines.append(f" Attaches to: {to_pascal(p.attach_to)} (faces must touch; small overlaps are fine)")
+ if p.instances > 1:
+ lines.append(f" Instances: {p.instances} ({p.symmetry}); build ONE centred at the origin, main() places each copy.")
+ lines.append(' """')
+ lines.append(" # TODO: replace the placeholder box (keep it centred on the origin; placement happens in main())")
+ lines.append(f" return cq.Workplane(\"XY\").box({ex:.3f}, {ey:.3f}, {ez:.3f})")
+ else:
+ lines.append(' """')
+ lines.append(" # TODO: replace the placeholder box with the real geometry (keep the name + bbox)")
+ lines.append(f" return cq.Workplane(\"XY\").box({ex:.3f}, {ey:.3f}, {ez:.3f}).translate({_fmt(p.bbox.center)})")
+ lines += ["", ""]
+ return "\n".join(lines)
+
+
+def _main_body(plan: StaticPlan) -> str:
+ lines = [f'result = cq.Assembly(name="{to_pascal(plan.object_name)}")', ""]
+ for p in plan.parts:
+ pascal, snake = to_pascal(p.name), to_snake(p.name)
+ rgb, _r, _m = finish_for(f"{p.material} {p.description}")
+ color = f"cq.Color({rgb[0]:.2f}, {rgb[1]:.2f}, {rgb[2]:.2f})"
+ if p.instances == 1:
+ lines.append(f'result.add(build_{snake}(), name="{pascal}", color={color})')
+ continue
+ centers = instance_centers(p.bbox, p.instances, p.symmetry)
+ lines.append(f"_{snake} = build_{snake}()")
+ lines.append(f"for _i, _c in enumerate({[tuple(round(x, 4) for x in c) for c in centers]}): # TODO: exact placement")
+ lines.append(f' result.add(_{snake}, name=f"{pascal}_{{_i}}", loc=cq.Location(cq.Vector(*_c)), color={color})')
+ lines.append("")
+ return "\n".join(lines)
+
+
+def cadquery_skeleton_source(plan: StaticPlan) -> str:
+ """Return the complete starter ``model.py`` text for ``plan``."""
+ ob = plan.overall_bbox
+ parts_doc = "\n".join(
+ f" - {to_pascal(p.name)}{'' if p.instances == 1 else f' x{p.instances}'}: {p.role}; bbox center {_fmt(p.bbox.center)} extents {_fmt(p.bbox.extents)}"
+ for p in plan.parts
+ )
+ accept = "\n".join(f" - [{a.id}] {a.text}" for a in plan.acceptance) or " (none listed)"
+ header = f'''"""{plan.object_name} — CadQuery model.
+
+{plan.summary}
+Style: {plan.style_notes or "n/a"}
+
+CONTRACT (the harness imports this file and exports `result` to GLB/STEP/STL itself):
+ * Z is up, -Y is the FRONT, units are METERS. Object stands on z=0, footprint centred on Z.
+ * Overall bbox: center {_fmt(ob.center)} extents {_fmt(ob.extents)}
+ -> x in [{ob.min[0]:.3f}, {ob.max[0]:.3f}] y in [{ob.min[1]:.3f}, {ob.max[1]:.3f}] z in [{ob.min[2]:.3f}, {ob.max[2]:.3f}]
+ * `result` = cq.Assembly; one `.add(shape, name="PascalName", color=cq.Color(r, g, b))` per part,
+ instances Name_0..Name_N-1 (a shape built at the origin + `loc=cq.Location(cq.Vector(x, y, z))`).
+ * Only `import cadquery as cq` (+ math / random). No file IO, no export, no show_object.
+ * `.box(x, y, z)` is centred; `.cylinder(height, radius)`; `.rotate(p1, p2, DEGREES)`;
+ `.translate()/.rotate()` return NEW objects (reassign). Keep fillet radius < 0.45 x wall thickness.
+
+PARTS:
+{parts_doc}
+
+ACCEPTANCE:
+{accept}
+"""
+import math # noqa: F401
+
+import cadquery as cq
+
+
+'''
+ body = "".join(_part_function(p) for p in plan.parts)
+ return header + body + _main_body(plan)
+
+
+def write_cadquery_skeleton(ws: Workspace, plan: StaticPlan) -> list[Path]:
+ ws.src.mkdir(parents=True, exist_ok=True)
+ path = ws.src / "model.py"
+ path.write_text(cadquery_skeleton_source(plan))
+ return [path]
diff --git a/harness/codeverse/languages/cadquery/wrappers/run_cq.py b/harness/codeverse/languages/cadquery/wrappers/run_cq.py
new file mode 100644
index 00000000..e250aa2f
--- /dev/null
+++ b/harness/codeverse/languages/cadquery/wrappers/run_cq.py
@@ -0,0 +1,290 @@
+"""CadQuery build wrapper — run by the harness in a subprocess, never imported.
+
+ python run_cq.py --script /abs/src/model.py --out /abs/artifacts \
+ [--rlimit-gb 8] [--tri-limit 600000] [--tolerance 0.001] [--angular-tolerance 0.15] [--seed 0]
+
+Steps: RLIMIT_AS → exec model.py (runpy) with traceback→line mapping → read the
+module-level ``result`` (cq.Assembly preferred, or Workplane / Shape) → tessellate
+each part (world location applied) → ``object.glb`` (Y-up, +Z front, named nodes,
+PBR base colour from cq.Color) + ``object.step`` + ``object.stl`` → ``census.json``
++ ``build.json`` (atomic). Exit 0 whenever a report was written; 2 on wrapper bugs.
+Standalone: imports cadquery / numpy / trimesh only (never ``codeverse``).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import random
+import re
+import runpy
+import sys
+import time
+import traceback
+from typing import Any
+
+GLB_NAME, STEP_NAME, STL_NAME = "object.glb", "object.step", "object.stl"
+PASCAL_RE = re.compile(r"^[A-Z][A-Za-z0-9]*(?:_\d+)?$")
+DEFAULT_RGBA = (0.7, 0.7, 0.7, 1.0)
+
+
+def parse_args(argv: list[str]) -> argparse.Namespace:
+ p = argparse.ArgumentParser(prog="run_cq.py")
+ p.add_argument("--script", required=True)
+ p.add_argument("--out", required=True)
+ p.add_argument("--rlimit-gb", type=float, default=8.0)
+ p.add_argument("--tri-limit", type=int, default=600_000)
+ p.add_argument("--tolerance", type=float, default=0.001)
+ p.add_argument("--angular-tolerance", type=float, default=0.15)
+ p.add_argument("--seed", type=int, default=0)
+ return p.parse_args(argv)
+
+
+def write_json_atomic(path: str, data: Any) -> None:
+ tmp = path + ".tmp"
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(data, fh, indent=2, default=str)
+ os.replace(tmp, path)
+
+
+def apply_rlimit(gb: float) -> str:
+ if gb <= 0:
+ return "rlimit disabled"
+ try:
+ import resource
+
+ cap = int(gb * 1024**3)
+ _soft, hard = resource.getrlimit(resource.RLIMIT_AS)
+ lim = cap if hard == resource.RLIM_INFINITY else min(cap, hard)
+ resource.setrlimit(resource.RLIMIT_AS, (lim, hard))
+ return f"RLIMIT_AS={lim // 1024**2} MB"
+ except (ImportError, ValueError, OSError) as e:
+ return f"rlimit not applied: {e}"
+
+
+# ----------------------------------------------------------------------------- exec + errors
+def map_exception(exc: BaseException, script_path: str) -> dict[str, Any]:
+ real = os.path.realpath(script_path)
+ info: dict[str, Any] = {"error_type": type(exc).__name__, "error_message": str(exc) or type(exc).__name__,
+ "error_file": "", "error_line": None, "error_source": ""}
+ if isinstance(exc, SyntaxError) and exc.filename and os.path.realpath(exc.filename) == real:
+ info.update(error_file=os.path.basename(script_path), error_line=exc.lineno, error_source=(exc.text or "").strip())
+ else:
+ for fr in reversed(traceback.extract_tb(exc.__traceback__)):
+ if os.path.realpath(fr.filename) == real:
+ info.update(error_file=os.path.basename(script_path), error_line=fr.lineno, error_source=(fr.line or "").strip())
+ break
+ msg = info["error_message"]
+ if "BRep_API: command not done" in msg or "StdFail_NotDone" in info["error_type"]:
+ info["error_message"] = msg + (
+ " — OCC kernel refused the operation: fillet/chamfer radius >= adjacent wall/face size, conflicting adjacent "
+ "fillets, or degenerate geometry. Clamp radii (< 0.45 x min thickness), select fewer edges, fillet before booleans.")
+ if isinstance(exc, MemoryError):
+ info["error_message"] = "MemoryError: memory cap hit — reduce boolean/pattern counts or tessellation density."
+ info["traceback"] = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))[-6000:]
+ return info
+
+
+def run_script(script_path: str) -> tuple[dict[str, Any] | None, dict[str, Any]]:
+ script_dir = os.path.dirname(os.path.abspath(script_path))
+ if script_dir not in sys.path:
+ sys.path.insert(0, script_dir)
+ saved = sys.argv
+ sys.argv = [script_path]
+ try:
+ ns = runpy.run_path(script_path, run_name="__main__")
+ return None, ns
+ except SystemExit as e:
+ if e.code in (None, 0):
+ return {"error_type": "SystemExit", "error_message": "script called sys.exit() before `result` could be read; remove it",
+ "error_file": os.path.basename(script_path), "error_line": None, "error_source": "", "traceback": ""}, {}
+ return map_exception(e, script_path), {}
+ except BaseException as e: # noqa: BLE001
+ return map_exception(e, script_path), {}
+ finally:
+ sys.argv = saved
+
+
+# ----------------------------------------------------------------------------- parts
+def _as_shape(cq: Any, obj: Any) -> Any:
+ """Workplane / Shape → one Shape (compound when several solids)."""
+ if isinstance(obj, cq.Workplane):
+ vals = [v for v in obj.vals() if isinstance(v, cq.Shape)]
+ if not vals:
+ raise ValueError("Workplane holds no shapes (did you forget .extrude()/.box()?)")
+ return vals[0] if len(vals) == 1 else cq.Compound.makeCompound(vals)
+ if isinstance(obj, cq.Shape):
+ return obj
+ raise TypeError(f"unsupported object of type {type(obj).__name__}; expected cq.Workplane or cq.Shape")
+
+
+def flatten_assembly(cq: Any, assy: Any) -> list[dict[str, Any]]:
+ """Depth-first leaves: {name, shape (world-located), rgba, path}."""
+ out: list[dict[str, Any]] = []
+
+ def walk(node: Any, parent_loc: Any, parent_rgba: Any, path: list[str]) -> None:
+ loc = parent_loc * node.loc
+ rgba = node.color.toTuple() if node.color is not None else parent_rgba
+ if node.obj is not None:
+ shape = _as_shape(cq, node.obj).moved(loc)
+ out.append({"name": node.name, "shape": shape, "rgba": rgba, "path": "/".join(path + [node.name])})
+ for child in node.children:
+ walk(child, loc, rgba, path + [node.name])
+
+ walk(assy, cq.Location(), None, [])
+ return out
+
+
+def collect_parts(cq: Any, result: Any) -> tuple[list[dict[str, Any]], str]:
+ if isinstance(result, cq.Assembly):
+ return flatten_assembly(cq, result), "assembly"
+ shape = _as_shape(cq, result)
+ return [{"name": "Object", "shape": shape, "rgba": None, "path": "Object"}], "single"
+
+
+def tessellate(part: dict[str, Any], tol: float, ang: float) -> tuple[list[list[float]], list[list[int]]]:
+ verts, tris = part["shape"].tessellate(tol, ang)
+ return [list(v.toTuple()) for v in verts], [list(t) for t in tris]
+
+
+def part_census(part: dict[str, Any], n_tris: int) -> dict[str, Any]:
+ shape = part["shape"]
+ bb = shape.BoundingBox()
+ rec: dict[str, Any] = {
+ "name": part["name"], "path": part["path"], "tri_count": n_tris,
+ "bbox_min": [round(bb.xmin, 5), round(bb.ymin, 5), round(bb.zmin, 5)],
+ "bbox_max": [round(bb.xmax, 5), round(bb.ymax, 5), round(bb.zmax, 5)],
+ "rgba": [round(c, 4) for c in part["rgba"]] if part["rgba"] else None,
+ }
+ try:
+ rec["volume_m3"] = round(float(shape.Volume()), 9)
+ rec["n_solids"] = len(shape.Solids())
+ rec["valid"] = bool(shape.isValid())
+ except Exception as e: # noqa: BLE001 — census must not kill the build
+ rec["census_error"] = str(e)
+ return rec
+
+
+# ----------------------------------------------------------------------------- export
+def build_glb(parts_meshes: list[tuple[dict[str, Any], list[list[float]], list[list[int]]]], path: str) -> int:
+ """trimesh Scene with one named node per part; Z-up → Y-up (x, y, z) → (x, z, -y)."""
+ import numpy as np
+ import trimesh
+
+ scene = trimesh.Scene()
+ total = 0
+ for part, verts, tris in parts_meshes:
+ if not tris:
+ continue
+ v = np.asarray(verts, dtype=np.float64)
+ v = np.column_stack([v[:, 0], v[:, 2], -v[:, 1]])
+ mesh = trimesh.Trimesh(vertices=v, faces=np.asarray(tris, dtype=np.int64), process=False)
+ rgba = part["rgba"] or DEFAULT_RGBA
+ mesh.visual = trimesh.visual.TextureVisuals(
+ material=trimesh.visual.material.PBRMaterial(
+ name=f"{part['name']}Mat", baseColorFactor=[float(c) for c in rgba[:4]],
+ metallicFactor=0.0, roughnessFactor=0.6))
+ scene.add_geometry(mesh, node_name=part["name"], geom_name=part["name"])
+ total += len(tris)
+ if total == 0:
+ raise ValueError("no triangles to export")
+ with open(path, "wb") as fh:
+ fh.write(scene.export(file_type="glb"))
+ return total
+
+
+def export_step_stl(cq: Any, result: Any, parts: list[dict[str, Any]], out_dir: str, tol: float, ang: float,
+ report: dict[str, Any]) -> None:
+ step, stl = os.path.join(out_dir, STEP_NAME), os.path.join(out_dir, STL_NAME)
+ try:
+ if isinstance(result, cq.Assembly):
+ result.export(step) if hasattr(result, "export") else result.save(step)
+ else:
+ cq.exporters.export(_as_shape(cq, result), step)
+ report["exported"]["step"] = step
+ except Exception as e: # noqa: BLE001
+ report["warnings"].append(f"STEP export failed: {e}")
+ try:
+ compound = cq.Compound.makeCompound([p["shape"] for p in parts])
+ cq.exporters.export(compound, stl, tolerance=tol, angularTolerance=ang)
+ report["exported"]["stl"] = stl
+ except Exception as e: # noqa: BLE001
+ report["warnings"].append(f"STL export failed: {e}")
+
+
+# ----------------------------------------------------------------------------- main
+def main() -> int:
+ args = parse_args(sys.argv[1:])
+ out_dir = os.path.abspath(args.out)
+ os.makedirs(out_dir, exist_ok=True)
+ build_path, census_path = os.path.join(out_dir, "build.json"), os.path.join(out_dir, "census.json")
+ for stale in (build_path, census_path, *(os.path.join(out_dir, n) for n in (GLB_NAME, STEP_NAME, STL_NAME))):
+ if os.path.exists(stale):
+ os.remove(stale)
+ t0 = time.monotonic()
+ report: dict[str, Any] = {"ok": False, "language": "cadquery", "error_type": "", "error_message": "", "error_file": "",
+ "error_line": None, "error_source": "", "traceback": "", "warnings": [], "exported": {},
+ "rlimit": apply_rlimit(args.rlimit_gb)}
+ random.seed(args.seed)
+ import cadquery as cq # noqa: PLC0415 — after the rlimit, before the script
+
+ report["cadquery_version"] = getattr(cq, "__version__", "?")
+ script = os.path.abspath(args.script)
+ err, ns = (None, {}) if os.path.isfile(script) else ({"error_type": "FileNotFoundError", "error_message": f"script not found: {script}"}, {})
+ if err is None:
+ t_exec = time.monotonic()
+ err, ns = run_script(script)
+ report["exec_ms"] = int((time.monotonic() - t_exec) * 1000)
+ census: dict[str, Any] = {"parts": [], "tri_count": 0, "warnings": report["warnings"], "frame": "z_up_neg_y_front"}
+ if err is None and "result" not in ns:
+ err = {"error_type": "MissingResult", "error_file": os.path.basename(script),
+ "error_message": "model.py must assign a module-level `result` (cq.Assembly or cq.Workplane); "
+ "it must exist at import time, not only under `if __name__ == '__main__':`"}
+ if err is None:
+ try:
+ parts, kind = collect_parts(cq, ns["result"])
+ census["result_kind"] = kind
+ if kind == "single":
+ report["warnings"].append("result is a bare Workplane/Shape: exported as ONE node 'Object' — prefer cq.Assembly with named, coloured parts")
+ meshes = []
+ for p in parts:
+ verts, tris = tessellate(p, args.tolerance, args.angular_tolerance)
+ meshes.append((p, verts, tris))
+ census["parts"].append(part_census(p, len(tris)))
+ if not PASCAL_RE.match(p["name"]):
+ report["warnings"].append(f"part name {p['name']!r} is not PascalCase (give every .add(...) a name='PartName')")
+ if not tris:
+ report["warnings"].append(f"part {p['name']!r} tessellated to 0 triangles (empty/degenerate shape)")
+ census["tri_count"] = sum(len(m[2]) for m in meshes)
+ if census["parts"]:
+ census["scene_bbox_min"] = [min(p["bbox_min"][i] for p in census["parts"]) for i in range(3)]
+ census["scene_bbox_max"] = [max(p["bbox_max"][i] for p in census["parts"]) for i in range(3)]
+ if census["tri_count"] > args.tri_limit:
+ err = {"error_type": "TriangleBudgetExceeded",
+ "error_message": f"{census['tri_count']} triangles > limit {args.tri_limit}; simplify (fewer pattern copies / coarser curves)"}
+ glb = os.path.join(out_dir, GLB_NAME)
+ build_glb(meshes, glb)
+ report["exported"]["glb"] = glb
+ export_step_stl(cq, ns["result"], parts, out_dir, args.tolerance, args.angular_tolerance, report)
+ except Exception as e: # noqa: BLE001 — export-time failure in agent geometry
+ err = map_exception(e, script)
+ if not err["error_file"]:
+ err["error_type"], err["error_message"] = "ExportError", f"{type(e).__name__}: {e}"
+ if err:
+ report.update({k: v for k, v in err.items() if k in report or k == "traceback"})
+ census["n_parts"] = len(census["parts"])
+ write_json_atomic(census_path, census)
+ report["ok"] = not report["error_type"] and "glb" in report["exported"]
+ report["duration_ms"] = int((time.monotonic() - t0) * 1000)
+ write_json_atomic(build_path, report)
+ return 0
+
+
+if __name__ == "__main__":
+ try:
+ code = main()
+ except Exception: # wrapper bug
+ traceback.print_exc()
+ code = 2
+ sys.exit(code)
diff --git a/harness/codeverse/languages/scene_threejs/CONTRACT.md b/harness/codeverse/languages/scene_threejs/CONTRACT.md
new file mode 100644
index 00000000..5b5f9083
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/CONTRACT.md
@@ -0,0 +1,72 @@
+# scene_threejs — authoring contract
+
+You write a **multi-file three.js scene in raw ESM + GLSL**. The harness owns the
+page, the renderer, cameras rigs, rendering, probes and judging. Your code never
+imports anything but `three`, `three/addons/*` and your own relative files.
+
+## Frame & units
+Y is **up**, +Z is the **front**, units are **meters**. Ground is around y = 0
+(your `heightAt(x, z)` decides the exact surface). A person is 1.7 m; a door 2.1 m;
+a car 4.5 m long. Authored bounds are declared by the plan (`bounds`).
+
+## Entry: `src/scene.js`
+```js
+import * as THREE from 'three';
+export function createScene({ THREE, renderer, loaders }) { // may be async
+ const scene = new THREE.Scene();
+ // ... build env + zones, add them to scene ...
+ return {
+ scene,
+ cameras: [ { name: 'overview', position: [26, 14, 34], lookAt: [0, 1.5, 0], fov: 50 } ], // 1-6
+ update(t, dt) { /* animate: t seconds since start, dt step */ },
+ };
+}
+```
+* The scene **owns its lights, sky/env and fog** (`scene.fog`, `scene.background`).
+ No lights → MeshStandardMaterial renders black.
+* `cameras`: 1–6 authored shots. Eye ≥ 0.5 m from any surface, above ground,
+ looking at real content; name them by what they show (`harbour_low`, `overview`).
+* `update(t, dt)`: all animation happens here (the host steps it deterministically).
+ **Never** call `requestAnimationFrame`, create a `WebGLRenderer`, or call
+ `renderer.render` yourself. `renderer` is passed only for capability checks.
+* `loaders.gltf` is a `GLTFLoader`; `loaders.texture` a `TextureLoader`. Assets built
+ with Blender live in `public/assets/<name>.glb` and are loaded with
+ `await loaders.gltf.loadAsync('/assets/<name>.glb')` (make `createScene` async).
+
+## Files
+| path | export | role |
+|---|---|---|
+| `src/scene.js` | `createScene(ctx)` | entry; imports env + zones; returns `{scene, cameras, update}` |
+| `src/env.js` | `buildEnv(ctx) → {ground, sky, sun, ...}`, `heightAt(x, z)` | ground/terrain, sky, sun + hemisphere light, fog |
+| `src/zones/<snake>.js` | `build(ctx) → THREE.Group` | one zone = one **named** group (`group.name = 'PascalCase'`), animated via `group.userData.update(t, dt)` |
+| `src/assets/<snake>.js` | `build<Pascal>(THREE) → THREE.Group` | reusable asset factories (origin at the base, +Y up); optionally `<asset>Parts(THREE)` for instancing |
+| `src/shaders/<name>.js` | GLSL strings / material factories | `ShaderMaterial` or `onBeforeCompile` patches — raw GLSL |
+| `src/fx/<name>.js` | effect helpers | particles, `three/addons/postprocessing/*` |
+
+`ctx` passed to env/zones: `{ THREE, scene, renderer, loaders, env, heightAt }`
+(you build it in `scene.js`; keep zones independent of each other).
+
+## GLSL rules (the ones that fail silently)
+* `#include <chunk>` **alone on its line**. No `#version`, no `precision` lines
+ (three prepends them). Use `gl_FragColor` (no `glslVersion`), or set
+ `glslVersion: THREE.GLSL3` and write your own `out vec4 fragColor` — never both.
+* Every uniform you read must be declared in the GLSL **and** bound in JS
+ (`uniforms: { uTime: { value: 0 } }`, set `.value` in `update`).
+* ShaderMaterial gets no lights and no fog unless you add them: for fog,
+ `fog: true`, `THREE.UniformsUtils.merge([THREE.UniformsLib.fog, {...}])` and the
+ `fog_pars_vertex / fog_vertex / fog_pars_fragment / fog_fragment` chunks.
+* `onBeforeCompile` patches must keep the chunk they extend:
+ `shader.fragmentShader = shader.fragmentShader.replace('#include <output_fragment>', '#include <output_fragment>\n gl_FragColor.rgb += glow;')`.
+* Do not redeclare `position / normal / uv / projectionMatrix / modelViewMatrix / cameraPosition`.
+
+## Performance & hygiene
+* Repeats → `InstancedMesh` (trees, posts, windows). Budget ≤ 3 M triangles total.
+* Seed your own PRNG (no `Math.random()`) so every render is reproducible.
+* `castShadow/receiveShadow` on meshes that matter; one shadow-casting sun.
+* Name things: zone groups PascalCase; important meshes too (the census/judge use names).
+* No network, no CDN, no DOM besides `document.createElement('canvas')` for procedural textures.
+
+## Harness tools you can call
+`build` (probe + shader preflight), `scene_probe` (census: meshes, tris, lights,
+zone bboxes, overlaps), `shader_probe` (does your shader actually change the frame?),
+`render_views` / `render_sheet` (authored + overview cameras at t = 0 and 1.5 s).
diff --git a/harness/codeverse/languages/scene_threejs/__init__.py b/harness/codeverse/languages/scene_threejs/__init__.py
new file mode 100644
index 00000000..377ea136
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/__init__.py
@@ -0,0 +1,5 @@
+"""scene_threejs: multi-file three.js scenes (+GLSL, +GLB assets) — lint, probe-build, skeleton, assembler."""
+
+from codeverse.languages.scene_threejs.runtime import SceneThreeJsRuntime
+
+__all__ = ["SceneThreeJsRuntime"]
diff --git a/harness/codeverse/languages/scene_threejs/assemble.py b/harness/codeverse/languages/scene_threejs/assemble.py
new file mode 100644
index 00000000..644ac575
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/assemble.py
@@ -0,0 +1,326 @@
+"""Deterministic scene assembler for the scene track's parallel mode.
+
+Zone agents write ``src/zones/<snake>.js`` (``build(ctx) → Group``) and an env
+agent writes ``src/env.js``; this module (code, not an LLM) then:
+
+1. probes every zone module in the browser host (``probe_zone_modules``):
+ does it import, does ``build(ctx)`` return an Object3D, what is its bbox;
+2. derives cameras from the measured zone bboxes (``derive_cameras``):
+ eye on the sun side (``SUN_AZIMUTH_DEG`` from env.js), overview + per-zone;
+3. writes ``src/scene.js`` importing only the healthy zones, naming groups,
+ preloading ``public/assets/*.glb`` into ``ctx.assets`` and fanning
+ ``update(t, dt)`` out to env + zones (``assemble``).
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import re
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.plan import CameraPlan, ScenePlan
+from codeverse.conventions import to_pascal, to_snake
+from codeverse.workspace import Workspace
+
+PROBE_REL = "src/_c3v_assemble_probe.js"
+_PREFIX = "[c3v-assemble]"
+_SUN_RE = re.compile(r"export\s+const\s+SUN_AZIMUTH_DEG\s*=\s*(-?\d+(?:\.\d+)?)")
+
+
+class ZoneProbe(BaseModel):
+ name: str
+ file: str
+ ok: bool
+ error: str = ""
+ bbox: dict[str, Any] | None = None
+ meshes: int = 0
+ triangles: int = 0
+
+
+class AssembleResult(BaseModel):
+ scene_path: str
+ zones_included: list[str] = Field(default_factory=list)
+ zones_failed: dict[str, str] = Field(default_factory=dict)
+ env_ok: bool = True
+ cameras: list[CameraPlan] = Field(default_factory=list)
+ warnings: list[str] = Field(default_factory=list)
+ census: dict[str, Any] = Field(default_factory=dict)
+
+
+def zone_files(ws: Workspace) -> list[Path]:
+ d = ws.src / "zones"
+ return sorted(p for p in d.glob("*.js") if not p.name.startswith("_")) if d.is_dir() else []
+
+
+def glb_assets(ws: Workspace) -> list[str]:
+ d = ws.public / "assets"
+ return sorted(p.stem for p in d.glob("*.glb")) if d.is_dir() else []
+
+
+def sun_azimuth(ws: Workspace, default: float = 45.0) -> float:
+ env = ws.src / "env.js"
+ if env.is_file():
+ m = _SUN_RE.search(env.read_text(errors="replace"))
+ if m:
+ return float(m.group(1))
+ return default
+
+
+# --------------------------------------------------------------------------- probing
+def _probe_module(zones: list[Path], glbs: list[str]) -> str:
+ entries = ",\n".join(f" ['{to_snake(p.stem)}', './zones/{p.name}']" for p in zones)
+ glb_lines = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
+ return f"""// generated by codeverse assembler — probes env + zone modules independently; deleted after use
+import * as THREE from 'three';
+const ZONES = [
+{entries}
+];
+export async function createScene({{ renderer, loaders }}) {{
+ const scene = new THREE.Scene();
+ const ctx = {{ THREE, scene, renderer, loaders, heightAt: () => 0, assets: {{}}, env: {{}} }};
+ const assetFiles = {{ {glb_lines} }};
+ for (const [k, url] of Object.entries(assetFiles)) {{
+ try {{ ctx.assets[k] = (await loaders.gltf.loadAsync(url)).scene; }}
+ catch (e) {{ console.error('{_PREFIX} asset ' + k + ' failed: ' + ((e && e.message) || e)); }}
+ }}
+ let env = null;
+ try {{
+ const m = await import('./env.js');
+ if (typeof m.heightAt === 'function') ctx.heightAt = m.heightAt;
+ if (typeof m.buildEnv === 'function') env = await m.buildEnv(ctx);
+ ctx.env = env || {{}};
+ }} catch (e) {{ console.error('{_PREFIX} env failed: ' + ((e && e.stack) || e)); }}
+ const wraps = [];
+ for (const [name, rel] of ZONES) {{
+ try {{
+ const m = await import(rel);
+ if (typeof m.build !== 'function') throw new Error('module has no export build(ctx)');
+ const g = await m.build(ctx);
+ if (!g || !g.isObject3D) throw new Error('build(ctx) did not return a THREE.Object3D');
+ const wrap = new THREE.Group();
+ wrap.name = '__zone__' + name;
+ wrap.add(g);
+ scene.add(wrap);
+ wraps.push(wrap);
+ }} catch (e) {{ console.error('{_PREFIX} zone ' + name + ' failed: ' + ((e && e.stack) || e)); }}
+ }}
+ return {{
+ scene,
+ cameras: [{{ name: 'probe', position: [30, 20, 30], lookAt: [0, 0, 0], fov: 50 }}],
+ update(t, dt) {{
+ try {{ if (env && env.update) env.update(t, dt); }} catch (e) {{ console.error('{_PREFIX} env update failed: ' + e); }}
+ for (const w of wraps) {{
+ const z = w.children[0];
+ try {{ if (z && z.userData.update) z.userData.update(t, dt); }} catch (e) {{ console.error('{_PREFIX} zone ' + w.name.slice(8) + ' update failed: ' + e); }}
+ }}
+ }},
+ }};
+}}
+"""
+
+
+def probe_zone_modules(ws: Workspace, *, timeout_s: float = 90.0) -> tuple[dict[str, ZoneProbe], dict[str, Any], list[str]]:
+ """Probe env + every zone module independently in the browser host.
+
+ Returns (zone probes by snake name, census of the probe scene, other console errors).
+ """
+ from codeverse.spatial.render_scene import run_scene_script
+
+ zones = zone_files(ws)
+ probe_path = ws.root / PROBE_REL
+ probe_path.write_text(_probe_module(zones, glb_assets(ws)))
+ try:
+ res = run_scene_script(
+ "probe_scene.mjs", ["--ws", str(ws.root), "--scene", PROBE_REL, "--timeout-ms", str(int(timeout_s * 1000))],
+ timeout_s=timeout_s + 20,
+ )
+ finally:
+ probe_path.unlink(missing_ok=True)
+ s = res.summary
+ boot = s.get("boot") or {}
+ errors: list[str] = list(s.get("console_errors", []))
+ if not boot.get("ok"):
+ errors.insert(0, f"probe scene did not boot [{boot.get('stage')}]: {boot.get('error', '')}")
+ failed: dict[str, str] = {}
+ other: list[str] = []
+ for e in errors:
+ m = re.match(rf"(?:console: )?{re.escape(_PREFIX)} zone (\S+) failed: (.*)", e, re.S)
+ if m:
+ failed[m.group(1)] = m.group(2).strip()[:600]
+ else:
+ other.append(e)
+ census = s.get("census") or {}
+ groups = {g["name"]: g for g in census.get("groups", [])}
+ probes: dict[str, ZoneProbe] = {}
+ for p in zones:
+ name = to_snake(p.stem)
+ g = groups.get(f"__zone__{name}")
+ if name in failed or g is None:
+ probes[name] = ZoneProbe(name=name, file=f"src/zones/{p.name}", ok=False,
+ error=failed.get(name, "zone not present after probe (build returned nothing visible?)"))
+ else:
+ probes[name] = ZoneProbe(name=name, file=f"src/zones/{p.name}", ok=True, bbox=g.get("bbox"),
+ meshes=g.get("meshes", 0), triangles=g.get("triangles", 0))
+ return probes, census, other
+
+
+# --------------------------------------------------------------------------- cameras
+def _dir(az_deg: float, el_deg: float) -> tuple[float, float, float]:
+ az, el = math.radians(az_deg), math.radians(el_deg)
+ return (math.sin(az) * math.cos(el), math.sin(el), math.cos(az) * math.cos(el))
+
+
+def _union(boxes: list[dict[str, Any]]) -> dict[str, Any] | None:
+ boxes = [b for b in boxes if b and b.get("min") and b.get("max")]
+ if not boxes:
+ return None
+ mn = [min(b["min"][i] for b in boxes) for i in range(3)]
+ mx = [max(b["max"][i] for b in boxes) for i in range(3)]
+ return {"min": mn, "max": mx, "size": [mx[i] - mn[i] for i in range(3)]}
+
+
+def fit_overview(bbox: dict[str, Any], *, azimuth: float, elevation: float = 30.0, fov: float = 50.0, aspect: float = 16 / 9,
+ floor: float | None = None, name: str = "overview") -> CameraPlan:
+ """Eye on the sun side, fitted to the bbox bounding sphere (ground-aware)."""
+ size = bbox["size"]
+ center = [bbox["min"][i] + size[i] / 2 for i in range(3)]
+ radius = max(0.5, math.hypot(*size) / 2)
+ fov_v = math.radians(fov)
+ fov_h = 2 * math.atan(math.tan(fov_v / 2) * aspect)
+ dist = radius / math.sin(min(fov_v, fov_h) / 2) * 0.95
+ d = _dir(azimuth, elevation)
+ eye = [center[i] + d[i] * dist for i in range(3)]
+ fl = bbox["min"][1] if floor is None else floor
+ eye[1] = max(eye[1], fl + 0.5)
+ return CameraPlan(name=name, position=tuple(round(v, 3) for v in eye), look_at=tuple(round(v, 3) for v in center), fov=fov,
+ purpose="overview fitted to measured content bounds, sun side")
+
+
+def fit_zone_camera(name: str, bbox: dict[str, Any], *, azimuth: float, floor: float | None = None, fov: float = 50.0) -> CameraPlan:
+ """Eye-level shot standing just outside the zone footprint on the sun side."""
+ size = bbox["size"]
+ center = [bbox["min"][i] + size[i] / 2 for i in range(3)]
+ dx, _, dz = _dir(azimuth, 0.0)
+ hx, hz = size[0] / 2, size[2] / 2
+ tx = hx / abs(dx) if abs(dx) > 1e-6 else math.inf
+ tz = hz / abs(dz) if abs(dz) > 1e-6 else math.inf
+ back = min(tx, tz) + max(2.0, 0.25 * max(size[0], size[2]))
+ fl = bbox["min"][1] if floor is None else floor
+ eye_h = fl + 1.7 + min(4.0, 0.15 * size[1])
+ eye = (center[0] + dx * back, eye_h, center[2] + dz * back)
+ look = (center[0], min(center[1], fl + 0.4 * size[1] + 0.5), center[2])
+ return CameraPlan(name=f"{to_snake(name)}_view", position=tuple(round(v, 3) for v in eye), look_at=tuple(round(v, 3) for v in look),
+ fov=fov, purpose=f"zone {to_pascal(name)} from the sun side")
+
+
+def derive_cameras(probes: dict[str, ZoneProbe], *, sun_azimuth_deg: float, ground_y: float | None = None, max_cameras: int = 6) -> list[CameraPlan]:
+ """Overview + per-zone cameras (largest footprints first), eye on the sun side."""
+ healthy = [p for p in probes.values() if p.ok and p.bbox]
+ if not healthy:
+ return [CameraPlan(name="overview", position=(30.0, 18.0, 30.0), look_at=(0.0, 1.0, 0.0), fov=50.0, purpose="fallback: no measurable zones")]
+ union = _union([p.bbox for p in healthy])
+ cams = [fit_overview(union, azimuth=sun_azimuth_deg, floor=ground_y)]
+ by_area = sorted(healthy, key=lambda p: -(p.bbox["size"][0] * p.bbox["size"][2]))
+ for p in by_area[: max_cameras - 1]:
+ cams.append(fit_zone_camera(p.name, p.bbox, azimuth=sun_azimuth_deg, floor=ground_y))
+ return cams
+
+
+# --------------------------------------------------------------------------- scene.js
+def _cam_literal(c: CameraPlan) -> str:
+ p, la = c.position, c.look_at
+ return (f" {{ name: '{to_snake(c.name)}', position: [{p[0]:g}, {p[1]:g}, {p[2]:g}], "
+ f"lookAt: [{la[0]:g}, {la[1]:g}, {la[2]:g}], fov: {c.fov:g} }},")
+
+
+def render_scene_js(zones: list[str], cameras: list[CameraPlan], glbs: list[str], *, env_ok: bool = True) -> str:
+ """Deterministic src/scene.js source for the given healthy zone snake names."""
+ imports = "\n".join(f"import {{ build as build{to_pascal(z)} }} from './zones/{z}.js';" for z in zones)
+ calls = "\n".join(f" addZone(build{to_pascal(z)}, '{to_pascal(z)}');" for z in zones)
+ env_import = "import { buildEnv, heightAt } from './env.js';" if env_ok else ""
+ env_build = " const env = buildEnv(ctx) || {};\n ctx.env = env;" if env_ok else " const env = {};"
+ height = "heightAt" if env_ok else "() => 0"
+ glb_lines = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
+ cams = "\n".join(_cam_literal(c) for c in cameras)
+ return f"""// src/scene.js — ASSEMBLED BY THE HARNESS (codeverse assembler). Edit zones/env instead; re-assembly overwrites this file.
+import * as THREE from 'three';
+{env_import}
+{imports}
+
+export async function createScene({{ renderer, loaders }}) {{
+ const scene = new THREE.Scene();
+ const ctx = {{ THREE, scene, renderer, loaders, heightAt: {height}, assets: {{}} }};
+ const assetFiles = {{ {glb_lines} }};
+ for (const [key, url] of Object.entries(assetFiles)) {{
+ try {{ ctx.assets[key] = (await loaders.gltf.loadAsync(url)).scene; }}
+ catch (e) {{ console.error(`[assets] failed to load ${{url}}: ${{e && e.message}}`); }}
+ }}
+{env_build}
+
+ const zones = [];
+ const addZone = (build, name) => {{
+ const g = build(ctx);
+ if (!g || !g.isObject3D) throw new Error(`zone ${{name}}: build(ctx) must return a THREE.Group`);
+ if (!g.name) g.name = name;
+ scene.add(g);
+ zones.push(g);
+ }};
+{calls}
+
+ const cameras = [
+{cams}
+ ];
+
+ function update(t, dt) {{
+ if (env.update) env.update(t, dt);
+ for (const z of zones) if (z.userData.update) z.userData.update(t, dt);
+ }}
+ return {{ scene, cameras, update }};
+}}
+"""
+
+
+def assemble(ws: Workspace, plan: ScenePlan | None = None, *, cameras: str = "derive", probe: bool = True,
+ timeout_s: float = 90.0) -> AssembleResult:
+ """Probe zones, derive cameras, write ``src/scene.js``. ``cameras='plan'`` keeps the plan's."""
+ warnings: list[str] = []
+ zones = zone_files(ws)
+ if not zones:
+ raise FileNotFoundError(f"no zone modules under {ws.src / 'zones'}")
+ env_ok = (ws.src / "env.js").is_file()
+ if not env_ok:
+ warnings.append("src/env.js missing: scene assembled without env (flat ground at y=0, no lights unless zones add them)")
+ probes: dict[str, ZoneProbe] = {}
+ census: dict[str, Any] = {}
+ if probe:
+ probes, census, other = probe_zone_modules(ws, timeout_s=timeout_s)
+ for o in other:
+ if _PREFIX in o and "env failed" in o:
+ env_ok = False
+ warnings.append(f"env.js failed in probe; assembled without it: {o[:300]}")
+ else:
+ warnings.append(o[:300])
+ else:
+ probes = {to_snake(p.stem): ZoneProbe(name=to_snake(p.stem), file=f"src/zones/{p.name}", ok=True) for p in zones}
+ healthy = [n for n, p in probes.items() if p.ok]
+ failed = {n: p.error for n, p in probes.items() if not p.ok}
+ if not healthy:
+ warnings.append("no zone module survived probing; scene.js assembled with zero zones")
+ ground_y = census.get("ground_y") if census else None
+ if cameras == "plan" and plan is not None and plan.cameras:
+ cams = list(plan.cameras[:6])
+ else:
+ cams = derive_cameras(probes, sun_azimuth_deg=sun_azimuth(ws), ground_y=ground_y)
+ text = render_scene_js(healthy, cams, glb_assets(ws), env_ok=env_ok)
+ out = ws.src / "scene.js"
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(text)
+ (ws.artifacts).mkdir(parents=True, exist_ok=True)
+ result = AssembleResult(scene_path=str(out), zones_included=healthy, zones_failed=failed, env_ok=env_ok,
+ cameras=cams, warnings=warnings, census=census)
+ (ws.artifacts / "assemble.json").write_text(json.dumps(result.model_dump(mode="json"), indent=1))
+ return result
diff --git a/harness/codeverse/languages/scene_threejs/lint.py b/harness/codeverse/languages/scene_threejs/lint.py
new file mode 100644
index 00000000..c007e7ce
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/lint.py
@@ -0,0 +1,138 @@
+"""Static lint for ``scene_threejs`` workspaces (no browser).
+
+Checks: ``node --check`` syntax per file, import allowlist ('three',
+'three/addons/*', relative), forbidden network/DOM/render-loop usage, required
+exports (``createScene`` in src/scene.js, ``build`` in zones), removed three.js
+APIs, oversized files. Returns a GateReport ``lint:scene_threejs``.
+"""
+
+from __future__ import annotations
+
+import re
+import subprocess
+import time
+from pathlib import Path
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.workspace import Workspace
+
+GATE = "lint:scene_threejs"
+MAX_LINES = 800
+
+_IMPORT_RE = re.compile(r"""(?:^|\n)\s*(?:import|export)\s[^;'"\n]*?from\s*['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)""")
+_CREATE_SCENE_RE = re.compile(r"export\s+(?:async\s+)?function\s+createScene\b|export\s+(?:const|let)\s+createScene\b|export\s*\{[^}]*\bcreateScene\b[^}]*\}")
+_BUILD_RE = re.compile(r"export\s+(?:async\s+)?function\s+build\b|export\s+(?:const|let)\s+build\b|export\s*\{[^}]*\bbuild\b[^}]*\}")
+_BUILD_ANY_RE = re.compile(r"export\s+(?:async\s+)?function\s+build[A-Za-z0-9_]*\b|export\s+(?:const|let)\s+build[A-Za-z0-9_]*\b")
+
+#: (regex, severity, message, hint)
+_PATTERNS: list[tuple[re.Pattern[str], Severity, str, str]] = [
+ (re.compile(r"\brequestAnimationFrame\s*\("), Severity.ERROR, "requestAnimationFrame: the host drives update(t, dt)", "delete your render loop; animate inside update(t, dt)"),
+ (re.compile(r"\bsetAnimationLoop\s*\("), Severity.ERROR, "renderer.setAnimationLoop: the host drives rendering", "remove it; animate inside update(t, dt)"),
+ (re.compile(r"new\s+THREE\.WebGLRenderer\b|new\s+WebGLRenderer\b|new\s+THREE\.WebGPURenderer\b"), Severity.ERROR, "creating a renderer: the host owns the WebGLRenderer", "use the `renderer` passed to createScene only for capability checks"),
+ (re.compile(r"\brenderer\.render\s*\("), Severity.ERROR, "renderer.render(): the host renders", "remove; return {scene, cameras, update} and let the host render"),
+ (re.compile(r"\bfetch\s*\(\s*['\"]https?://|XMLHttpRequest|new\s+WebSocket\b|['\"]https?://[^'\"]+\.(?:js|mjs|glb|gltf|png|jpg|hdr)['\"]"), Severity.ERROR, "network / CDN access", "no network: import 'three' / 'three/addons/*' and load assets from '/assets/<name>.glb'"),
+ (re.compile(r"\bdocument\.(?:body|getElementById|querySelector|querySelectorAll|head)\b|\bwindow\.addEventListener\b|\.innerHTML\b|\blocalStorage\b"), Severity.ERROR, "DOM/page access outside the host contract", "the host owns the page; only document.createElement('canvas') for procedural textures is allowed"),
+ (re.compile(r"\bTHREE\.Geometry\b|\bFace3\b|\bexamples/js/"), Severity.ERROR, "removed three.js API (Geometry/Face3/examples/js)", "use BufferGeometry and 'three/addons/...' imports"),
+ (re.compile(r"\b(?:Box|Plane|Sphere|Cylinder|Cone|Torus|Circle|Ring|Shape|Extrude|Lathe|Tube|Icosahedron|Dodecahedron|Octahedron|Tetrahedron|Polyhedron|Edges|Wireframe)BufferGeometry\b"), Severity.ERROR, "*BufferGeometry aliases were removed (r144)", "drop the 'Buffer' infix: THREE.BoxGeometry"),
+ (re.compile(r"\.outputEncoding\b|\bsRGBEncoding\b|\bLinearEncoding\b|\.encoding\s*="), Severity.ERROR, "texture/renderer .encoding was removed (r152)", "use texture.colorSpace = THREE.SRGBColorSpace (colour maps only)"),
+ (re.compile(r"\bMath\.random\s*\("), Severity.WARN, "Math.random makes renders non-reproducible", "use a seeded PRNG (e.g. mulberry32) so rounds can be compared"),
+ (re.compile(r"\brequire\s*\(|\bprocess\.env\b|\bmodule\.exports\b"), Severity.ERROR, "CommonJS / node globals in browser ESM", "use ESM import/export only"),
+ (re.compile(r"\bTHREE\.ImageUtils\b|\bTHREE\.SceneUtils\b|\bMeshFaceMaterial\b|\bMultiMaterial\b"), Severity.ERROR, "removed three.js helper", "use TextureLoader / material arrays"),
+]
+
+
+def _f(sev: Severity, msg: str, *, target: str, hint: str = "", **data: object) -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data=dict(data))
+
+
+def _js_files(ws: Workspace) -> list[Path]:
+ if not ws.src.is_dir():
+ return []
+ return sorted(p for p in ws.src.rglob("*.js") if "node_modules" not in p.parts) + sorted(ws.src.rglob("*.mjs"))
+
+
+def _node_check(path: Path, rel: str) -> GateFinding | None:
+ node = get_settings().binaries.node or "node"
+ try:
+ # ESM syntax check via stdin: `node --check file.js` treats a bare .js as CommonJS-or-detect
+ proc = subprocess.run([node, "--input-type=module", "--check"], input=path.read_text(errors="replace"),
+ capture_output=True, text=True, timeout=30)
+ except (OSError, subprocess.TimeoutExpired) as e:
+ return _f(Severity.ERROR, f"node --check could not run: {e}", target=rel, hint="harness problem (node missing?)")
+ if proc.returncode == 0:
+ return None
+ err = proc.stderr.strip()
+ line = None
+ m = re.search(r"\[stdin\]:(\d+)", err) or re.search(r":(\d+)\n", err)
+ if m:
+ line = int(m.group(1))
+ msg = next((ln for ln in err.splitlines() if "Error" in ln), err.splitlines()[0] if err else "syntax error")
+ return _f(Severity.ERROR, f"syntax: {msg}", target=f"{rel}:{line}" if line else rel,
+ hint="fix the syntax error at the quoted line (node --check)", line=line, detail=err[-600:])
+
+
+def _check_imports(rel: str, text: str, ws: Workspace, path: Path) -> list[GateFinding]:
+ out: list[GateFinding] = []
+ for m in _IMPORT_RE.finditer(text):
+ spec = m.group(1) or m.group(2)
+ line = text.count("\n", 0, m.start()) + 1
+ tgt = f"{rel}:{line}"
+ if spec == "three" or spec.startswith("three/addons/") or spec.startswith("three/examples/jsm/"):
+ continue
+ if spec.startswith("./") or spec.startswith("../"):
+ dest = (path.parent / spec).resolve()
+ if not dest.is_file():
+ out.append(_f(Severity.ERROR, f"import of missing file '{spec}'", target=tgt,
+ hint="create the file or fix the path (relative imports need the .js extension)"))
+ elif not str(dest).startswith(str(ws.src.resolve())):
+ out.append(_f(Severity.ERROR, f"import '{spec}' escapes src/", target=tgt, hint="keep all code under src/"))
+ continue
+ if spec.startswith("/"):
+ out.append(_f(Severity.ERROR, f"absolute import '{spec}'", target=tgt, hint="use relative imports ('./x.js')"))
+ continue
+ out.append(_f(Severity.ERROR, f"import '{spec}' is not allowed (only 'three', 'three/addons/*', relative files)", target=tgt,
+ hint="no CDN / npm packages; write the helper yourself in src/"))
+ return out
+
+
+def lint(ws: Workspace) -> GateReport:
+ """Run all static checks; passed iff no ERROR findings."""
+ t0 = time.time()
+ findings: list[GateFinding] = []
+ files = _js_files(ws)
+ scene = ws.src / "scene.js"
+ if not scene.is_file():
+ findings.append(_f(Severity.ERROR, "src/scene.js is missing", target="src/scene.js",
+ hint="create src/scene.js exporting createScene({THREE, renderer, loaders})"))
+ big: list[str] = []
+ for path in files:
+ rel = path.relative_to(ws.root).as_posix()
+ text = path.read_text(errors="replace")
+ syntax = _node_check(path, rel)
+ if syntax:
+ findings.append(syntax)
+ continue
+ findings.extend(_check_imports(rel, text, ws, path))
+ for pat, sev, msg, hint in _PATTERNS:
+ m = pat.search(text)
+ if m:
+ line = text.count("\n", 0, m.start()) + 1
+ findings.append(_f(sev, msg, target=f"{rel}:{line}", hint=hint))
+ n_lines = text.count("\n") + 1
+ if n_lines > MAX_LINES:
+ big.append(f"{rel} ({n_lines} lines)")
+ if path == scene and not _CREATE_SCENE_RE.search(text):
+ findings.append(_f(Severity.ERROR, "src/scene.js does not export createScene", target=rel,
+ hint="export function createScene({ THREE, renderer, loaders }) { ... return { scene, cameras, update } }"))
+ if path.parent == ws.src / "zones" and not _BUILD_RE.search(text):
+ findings.append(_f(Severity.ERROR, "zone module does not export build(ctx)", target=rel,
+ hint="export function build(ctx) { const g = new THREE.Group(); g.name = 'ZoneName'; ...; return g; }"))
+ if path.parent == ws.src / "assets" and not _BUILD_ANY_RE.search(text):
+ findings.append(_f(Severity.WARN, "asset module exports no build<Pascal>(THREE) factory", target=rel,
+ hint="export function buildLamp(THREE) { ... return group; }"))
+ for b in big:
+ findings.append(_f(Severity.WARN, f"large file {b} > {MAX_LINES} lines", target=b.split(" ")[0],
+ hint="split into zones/assets/shaders modules"))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse/languages/scene_threejs/runtime.py b/harness/codeverse/languages/scene_threejs/runtime.py
new file mode 100644
index 00000000..c374fd4f
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/runtime.py
@@ -0,0 +1,107 @@
+"""``SceneThreeJsRuntime``: the LanguageRuntime for multi-file three.js scenes.
+
+build(ws) = ``probe_scene`` (module loads, shape, cameras, update, census) +
+``check_shaders`` (static GLSL audits + GPU compile preflight). A scene has no
+GLB deliverable — ``BuildResult.glb_path`` stays None; the census, probe and
+preflight JSONs are in ``extra_paths``.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+
+from codeverse.contracts.artifacts import BuildResult, GateReport, Severity
+from codeverse.contracts.common import Language
+from codeverse.contracts.plan import Plan
+from codeverse.languages.scene_threejs.lint import lint as _lint
+from codeverse.languages.scene_threejs.skeleton import write_skeleton
+from codeverse.workspace import Workspace
+
+_HERE = Path(__file__).resolve().parent
+_PROMPTS = _HERE.parent.parent / "prompts" / "scene_threejs"
+
+
+class SceneThreeJsRuntime:
+ language = Language.SCENE_THREEJS
+ entry_globs: tuple[str, ...] = ("src/scene.js", "src/zones/*.js", "src/assets/*.js", "src/env.js", "src/shaders/*.js")
+
+ def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
+ return write_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return _lint(ws)
+
+ def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
+ """Probe + shader preflight; ok iff the module loads and no shader errors."""
+ from codeverse.config import get_settings
+ from codeverse.spatial.probes import check_shaders, probe_scene
+
+ t0 = time.time()
+ tmo = float(timeout_s or get_settings().limits.build_timeout_s)
+ probe, census = probe_scene(ws, timeout_s=min(tmo, 120.0))
+ shaders = check_shaders(ws, timeout_s=min(tmo, 120.0)) if probe.passed or _module_loaded(probe) else GateReport(
+ gate="shader_preflight", passed=False, findings=[])
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ gates_dir = ws.artifacts / "gates"
+ gates_dir.mkdir(exist_ok=True)
+ (gates_dir / "scene_probe.json").write_text(probe.model_dump_json(indent=1))
+ (gates_dir / "shader_preflight.json").write_text(shaders.model_dump_json(indent=1))
+ errors = sorted(probe.errors + shaders.errors, key=lambda f: 0 if _target_line(f.target) else 1)
+ first = errors[0] if errors else None
+ res = BuildResult(
+ ok=probe.passed and shaders.passed,
+ language=self.language.value,
+ glb_path=None,
+ extra_paths={
+ "census": str(ws.artifacts / "census.json"),
+ "scene_probe": str(gates_dir / "scene_probe.json"),
+ "shader_preflight": str(gates_dir / "shader_preflight.json"),
+ },
+ stdout_tail=_summary_text(probe, shaders),
+ error_type=(first.data.get("kind") or first.gate) if first else "",
+ error_message=first.message if first else "",
+ error_file=_target_file(first.target) if first else "",
+ error_line=_target_line(first.target) if first else None,
+ duration_ms=int((time.time() - t0) * 1000),
+ census=census,
+ )
+ (ws.artifacts / "build.json").write_text(json.dumps(res.model_dump(mode="json"), indent=1))
+ return res
+
+ def contract_doc(self) -> str:
+ p = _PROMPTS / "contract.md"
+ if p.is_file():
+ return p.read_text()
+ return (_HERE / "CONTRACT.md").read_text()
+
+ def cookbook_path(self) -> Path:
+ return _PROMPTS / "cookbook.md"
+
+
+def _module_loaded(probe: GateReport) -> bool:
+ """Run the shader preflight even when the probe failed for non-boot reasons."""
+ return not any(f.data.get("stage") for f in probe.findings if f.severity == Severity.ERROR)
+
+
+def _summary_text(probe: GateReport, shaders: GateReport) -> str:
+ lines = [f"scene_probe: {'ok' if probe.passed else 'FAILED'} ({len(probe.errors)} errors)"]
+ lines += [f" - {f.target or ''}: {f.message}"[:400] for f in probe.findings if f.severity != Severity.INFO][:12]
+ lines.append(f"shader_preflight: {'ok' if shaders.passed else 'FAILED'} ({len(shaders.errors)} errors)")
+ lines += [f" - {f.target or ''}: {f.message}"[:400] for f in shaders.findings if f.severity != Severity.INFO][:12]
+ return "\n".join(lines)
+
+
+def _target_file(target: str | None) -> str:
+ if not target:
+ return ""
+ head, sep, tail = target.rpartition(":")
+ return head if sep and tail.isdigit() else target
+
+
+def _target_line(target: str | None) -> int | None:
+ if not target:
+ return None
+ _, sep, tail = target.rpartition(":")
+ return int(tail) if sep and tail.isdigit() else None
diff --git a/harness/codeverse/languages/scene_threejs/skeleton.py b/harness/codeverse/languages/scene_threejs/skeleton.py
new file mode 100644
index 00000000..84c87c91
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/skeleton.py
@@ -0,0 +1,197 @@
+"""Starter files for ``scene_threejs`` workspaces.
+
+Without a plan: the complete example scene from ``starter/src`` (ground + sky
+gradient shader + instanced pine trees + animated windmill/lantern + GLSL water)
+— a concrete, working pattern the agent can run immediately.
+
+With a ``ScenePlan``: the same env/shader/asset pattern files plus one stub per
+planned zone (named group, plan bbox + contents in comments, a seated
+placeholder of each listed asset), one stub per ``threejs`` asset (blockout box
+at the planned size), GLB preloading for ``blender_glb`` assets, and a
+``src/scene.js`` wired to all zones with the plan's cameras.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from codeverse.contracts.plan import AssetPlan, Plan, ScenePlan, ZonePlan
+from codeverse.conventions import to_pascal, to_snake
+from codeverse.workspace import Workspace
+
+STARTER_DIR = Path(__file__).resolve().parent / "starter" / "src"
+#: pattern files copied verbatim in plan mode (shown as reusable examples)
+PATTERN_FILES = ("shaders/sky.js", "shaders/water.js", "assets/pine_tree.js", "assets/windmill.js")
+
+
+def _write(path: Path, text: str, written: list[Path]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+ written.append(path)
+
+
+def write_example(ws: Workspace) -> list[Path]:
+ """Copy the full example scene into ws.src (overwrites)."""
+ written: list[Path] = []
+ for src in sorted(STARTER_DIR.rglob("*.js")):
+ rel = src.relative_to(STARTER_DIR)
+ _write(ws.src / rel, src.read_text(), written)
+ return written
+
+
+def _env_for_plan(plan: ScenePlan) -> str:
+ text = (STARTER_DIR / "env.js").read_text()
+ ex = plan.bounds.extents
+ span = max(ex[0], ex[2], 40.0)
+ ground = int(max(120, span * 2.5))
+ fog_near, fog_far = int(span * 0.8), int(max(span * 3.0, 200))
+ text = re.sub(r"export const GROUND_SIZE = \d+;", f"export const GROUND_SIZE = {ground};", text)
+ text = re.sub(r"const FOG_NEAR = \d+, FOG_FAR = \d+;", f"const FOG_NEAR = {fog_near}, FOG_FAR = {fog_far};", text)
+ text = re.sub(r"const SKY_RADIUS = \d+;", f"const SKY_RADIUS = {int(max(600, ground * 3))};", text)
+ header = (
+ f"// ENV PLAN: {plan.environment.strip()}\n"
+ f"// setting: {plan.setting.strip()} mood: {plan.mood.strip()}\n"
+ f"// bounds: centre {tuple(round(c, 1) for c in plan.bounds.center)} extents {tuple(round(e, 1) for e in ex)} m\n"
+ "// Rewrite the ground/sky/fog/sun below to match the plan; keep buildEnv/heightAt exports.\n"
+ )
+ return header + text
+
+
+def _asset_stub(a: AssetPlan) -> str:
+ snake, pascal = to_snake(a.name), to_pascal(a.name)
+ w, h, d = (max(0.05, float(v)) for v in a.approx_size_m)
+ return f'''// src/assets/{snake}.js — asset "{pascal}": {a.description.strip()}
+// approx size {w:g} x {h:g} x {d:g} m (w x h x d); expected instances: ~{a.instances_hint}
+// CONTRACT: export function build{pascal}(THREE) → THREE.Group, origin at the base (y = 0), +Y up, +Z front, meters.
+// Build it from several parts with distinct materials (see assets/pine_tree.js, assets/windmill.js);
+// for many instances also export {snake}Parts(THREE) → [{{ geometry, material, castShadow }}].
+import * as THREE from 'three';
+
+export function build{pascal}(T = THREE) {{
+ const g = new T.Group();
+ g.name = '{pascal}';
+ // PLACEHOLDER blockout at the planned size — REPLACE with real construction.
+ const box = new T.Mesh(new T.BoxGeometry({w:g}, {h:g}, {d:g}), new T.MeshStandardMaterial({{ color: 0x9a9a9a, roughness: 0.8 }}));
+ box.position.y = {h / 2:g};
+ box.castShadow = box.receiveShadow = true;
+ g.add(box);
+ return g;
+}}
+'''
+
+
+def _zone_stub(z: ZonePlan, assets: dict[str, AssetPlan]) -> str:
+ snake, pascal = to_snake(z.name), to_pascal(z.name)
+ c, e = z.bbox.center, z.bbox.extents
+ imports, places = [], []
+ for i, name in enumerate(z.contents):
+ a = assets.get(to_snake(name))
+ if a is None:
+ continue
+ asn, asp = to_snake(a.name), to_pascal(a.name)
+ ox = (-e[0] / 4 + (i % 3) * e[0] / 4) if len(z.contents) > 1 else 0.0
+ oz = (-e[2] / 4 + (i // 3) * e[2] / 4) if len(z.contents) > 3 else 0.0
+ x, zz = round(c[0] + ox, 2), round(c[2] + oz, 2)
+ if a.kind == "threejs":
+ imports.append(f"import {{ build{asp} }} from '../assets/{asn}.js';")
+ places.append(f" place(build{asp}(THREE), {x}, {zz});")
+ else:
+ places.append(
+ f" if (ctx.assets && ctx.assets.{asn}) place(ctx.assets.{asn}.clone(), {x}, {zz});"
+ f" // GLB built in Blender → public/assets/{asn}.glb (preloaded by scene.js)"
+ )
+ imp = "\n".join(imports)
+ body = "\n".join(places) if places else " // TODO: build this zone's content here (use ctx.heightAt to seat objects)."
+ return f'''// src/zones/{snake}.js — zone "{pascal}": {z.description.strip()}
+// PLAN bbox: centre ({c[0]:g}, {c[1]:g}, {c[2]:g}) extents ({e[0]:g} x {e[1]:g} x {e[2]:g}) m. Contents: {", ".join(z.contents) or "-"}
+// CONTRACT: export function build(ctx) → THREE.Group named '{pascal}'. ctx = {{ THREE, scene, renderer, loaders, env, heightAt, assets }}
+// • seat objects on the ground with ctx.heightAt(x, z); keep everything inside the plan bbox
+// • repeats → THREE.InstancedMesh (see the pattern in assets/pine_tree.js: <asset>Parts(THREE))
+// • animation → zone.userData.update = (t, dt) => {{ ... }} (scene.js fans update() out to every zone)
+import * as THREE from 'three';
+{imp}
+
+export function build(ctx) {{
+ const {{ heightAt }} = ctx;
+ const zone = new THREE.Group();
+ zone.name = '{pascal}';
+ const place = (obj, x, z, ry = 0) => {{ obj.position.set(x, heightAt(x, z), z); obj.rotation.y = ry; zone.add(obj); return obj; }};
+{body}
+ zone.userData.update = (t, dt) => {{ /* animate zone elements here */ }};
+ return zone;
+}}
+'''
+
+
+def _scene_for_plan(plan: ScenePlan) -> str:
+ zones = [(to_snake(z.name), to_pascal(z.name)) for z in plan.zones]
+ glbs = [to_snake(a.name) for a in plan.assets if a.kind == "blender_glb"]
+ zone_imports = "\n".join(f"import {{ build as build{p} }} from './zones/{s}.js';" for s, p in zones)
+ zone_calls = ", ".join(f"build{p}(ctx)" for _, p in zones)
+ cams = ",\n".join(
+ f" {{ name: '{to_snake(c.name)}', position: [{c.position[0]:g}, {c.position[1]:g}, {c.position[2]:g}], "
+ f"lookAt: [{c.look_at[0]:g}, {c.look_at[1]:g}, {c.look_at[2]:g}], fov: {c.fov:g} }}"
+ + (f" // {c.purpose}" if c.purpose else "")
+ for c in plan.cameras[:6]
+ )
+ glb_block = ""
+ if glbs:
+ files = ", ".join(f"{g}: '/assets/{g}.glb'" for g in glbs)
+ glb_block = f'''
+ // Blender-built assets (public/assets/*.glb) are preloaded once; zones clone ctx.assets.<name>.
+ const assetFiles = {{ {files} }};
+ const assets = {{}};
+ for (const [key, url] of Object.entries(assetFiles)) {{
+ try {{ assets[key] = (await loaders.gltf.loadAsync(url)).scene; }}
+ catch (e) {{ console.warn(`[assets] missing ${{url}} (${{e && e.message}}) — build it with Blender into public/assets/`); }}
+ }}
+ ctx.assets = assets;
+'''
+ async_kw = "async " if glbs else ""
+ header = (STARTER_DIR / "scene.js").read_text().split("import * as THREE")[0]
+ return f'''{header}// PLAN: {plan.title} — {plan.summary.strip()}
+// setting: {plan.setting.strip()} animation: {"; ".join(plan.animation) or "-"}
+import * as THREE from 'three';
+import {{ buildEnv, heightAt, SUN_AZIMUTH_DEG }} from './env.js';
+{zone_imports}
+
+export {async_kw}function createScene({{ THREE: T = THREE, renderer, loaders }}) {{
+ const scene = new THREE.Scene();
+ const ctx = {{ THREE, scene, renderer, loaders, heightAt, sunAzimuthDeg: SUN_AZIMUTH_DEG, assets: {{}} }};
+ const env = buildEnv(ctx);
+ ctx.env = env;
+{glb_block}
+ const zones = [{zone_calls}];
+ for (const z of zones) scene.add(z);
+
+ const cameras = [
+{cams}
+ ];
+
+ function update(t, dt) {{
+ if (env.update) env.update(t, dt);
+ for (const z of zones) if (z.userData.update) z.userData.update(t, dt);
+ }}
+ return {{ scene, cameras, update }};
+}}
+'''
+
+
+def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:
+ """Write starter files into ``ws.src``; returns the written paths."""
+ if plan is None or not isinstance(plan, ScenePlan):
+ return write_example(ws)
+ written: list[Path] = []
+ for rel in PATTERN_FILES:
+ _write(ws.src / rel, (STARTER_DIR / rel).read_text(), written)
+ _write(ws.src / "env.js", _env_for_plan(plan), written)
+ assets = {to_snake(a.name): a for a in plan.assets}
+ for a in plan.assets:
+ if a.kind == "threejs":
+ _write(ws.src / "assets" / f"{to_snake(a.name)}.js", _asset_stub(a), written)
+ for z in plan.zones:
+ _write(ws.src / "zones" / f"{to_snake(z.name)}.js", _zone_stub(z, assets), written)
+ _write(ws.src / "scene.js", _scene_for_plan(plan), written)
+ (ws.public / "assets").mkdir(parents=True, exist_ok=True)
+ return written
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/assets/pine_tree.js b/harness/codeverse/languages/scene_threejs/starter/src/assets/pine_tree.js
new file mode 100644
index 00000000..940a7064
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/assets/pine_tree.js
@@ -0,0 +1,33 @@
+// src/assets/pine_tree.js — reusable asset factory.
+// export function buildPineTree(THREE) → THREE.Group (origin at the base, +Y up, meters)
+// export function pineTreeParts(THREE) → [{ geometry, material, castShadow }] for InstancedMesh use
+// Geometry/material are created once per call and shared by the instancing zone.
+import * as THREE from 'three';
+
+export function pineTreeParts(T = THREE) {
+ const trunkGeo = new T.CylinderGeometry(0.12, 0.22, 1.6, 7);
+ trunkGeo.translate(0, 0.8, 0);
+ const trunkMat = new T.MeshStandardMaterial({ color: 0x5a3a22, roughness: 0.9 });
+ const canopy = new T.ConeGeometry(1.25, 3.0, 9);
+ canopy.translate(0, 2.6, 0);
+ const canopy2 = new T.ConeGeometry(0.9, 2.2, 9);
+ canopy2.translate(0, 3.9, 0);
+ const leafMat = new T.MeshStandardMaterial({ color: 0x2f6b2a, roughness: 0.85 });
+ return [
+ { geometry: trunkGeo, material: trunkMat, castShadow: true },
+ { geometry: canopy, material: leafMat, castShadow: true },
+ { geometry: canopy2, material: leafMat, castShadow: true },
+ ];
+}
+
+export function buildPineTree(T = THREE) {
+ const g = new T.Group();
+ g.name = 'PineTree';
+ for (const p of pineTreeParts(T)) {
+ const m = new T.Mesh(p.geometry, p.material);
+ m.castShadow = true;
+ m.receiveShadow = true;
+ g.add(m);
+ }
+ return g;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/assets/windmill.js b/harness/codeverse/languages/scene_threejs/starter/src/assets/windmill.js
new file mode 100644
index 00000000..6c57b905
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/assets/windmill.js
@@ -0,0 +1,30 @@
+// src/assets/windmill.js — an asset with a moving part: the returned group
+// carries userData.update(t, dt) so the owning zone can fan animation out.
+import * as THREE from 'three';
+
+export function buildWindmill(T = THREE) {
+ const g = new T.Group();
+ g.name = 'Windmill';
+ const stone = new T.MeshStandardMaterial({ color: 0xb9a58a, roughness: 0.9 });
+ const wood = new T.MeshStandardMaterial({ color: 0x6b4a2b, roughness: 0.8 });
+ const tower = new T.Mesh(new T.CylinderGeometry(1.1, 1.6, 5.0, 12), stone);
+ tower.position.y = 2.5;
+ tower.castShadow = tower.receiveShadow = true;
+ const cap = new T.Mesh(new T.ConeGeometry(1.4, 1.2, 12), wood);
+ cap.position.y = 5.6;
+ cap.castShadow = true;
+ const hub = new T.Group();
+ hub.position.set(0, 4.6, 1.35);
+ for (let i = 0; i < 4; i++) {
+ const blade = new T.Mesh(new T.BoxGeometry(0.25, 3.2, 0.06), wood);
+ blade.position.y = 1.6;
+ blade.castShadow = true;
+ const arm = new T.Group();
+ arm.rotation.z = (i * Math.PI) / 2;
+ arm.add(blade);
+ hub.add(arm);
+ }
+ g.add(tower, cap, hub);
+ g.userData.update = (t) => { hub.rotation.z = t * 0.9; };
+ return g;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/env.js b/harness/codeverse/languages/scene_threejs/starter/src/env.js
new file mode 100644
index 00000000..1c22d2b0
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/env.js
@@ -0,0 +1,73 @@
+// src/env.js — environment owned by the scene: ground, sky, sun, fog, heightAt.
+// export function buildEnv(ctx) → { ground, sky, sun, hemi, update(t, dt) }
+// export function heightAt(x, z) → ground height (m) so zones can seat objects.
+import * as THREE from 'three';
+import { makeSkyMaterial } from './shaders/sky.js';
+
+export const SUN_AZIMUTH_DEG = 60; // where the sun is (0 = +Z front, CCW from above); cameras on the sun side are front-lit
+export const SUN_ELEVATION_DEG = 38;
+export const GROUND_SIZE = 160; // ground plane extent (m); fog is tuned to it
+const FOG_NEAR = 60, FOG_FAR = 260;
+const SKY_RADIUS = 600;
+
+/** Gentle rolling meadow; deterministic, cheap (called per placed object). */
+export function heightAt(x, z) {
+ return 0.35 * Math.sin(x * 0.13) * Math.cos(z * 0.11) + 0.18 * Math.sin((x + z) * 0.27);
+}
+
+function groundGeometry(size, segs) {
+ const g = new THREE.PlaneGeometry(size, size, segs, segs);
+ g.rotateX(-Math.PI / 2); // PlaneGeometry lies in XY → rotate to XZ
+ const pos = g.attributes.position;
+ for (let i = 0; i < pos.count; i++) pos.setY(i, heightAt(pos.getX(i), pos.getZ(i)));
+ g.computeVertexNormals();
+ return g;
+}
+
+export function buildEnv(ctx) {
+ const { scene } = ctx;
+ const group = new THREE.Group();
+ group.name = 'Environment';
+
+ // --- ground (receives shadows; vertex colour variation = cheap "grass")
+ const ground = new THREE.Mesh(
+ groundGeometry(GROUND_SIZE, 96),
+ new THREE.MeshStandardMaterial({ color: 0x5f8a3c, roughness: 0.95, metalness: 0.0 }),
+ );
+ ground.name = 'Ground';
+ ground.receiveShadow = true;
+ group.add(ground);
+
+ const az = (SUN_AZIMUTH_DEG * Math.PI) / 180, el = (SUN_ELEVATION_DEG * Math.PI) / 180;
+
+ // --- sky: big inverted sphere with a gradient ShaderMaterial (custom GLSL, no lighting needed)
+ const skyMat = makeSkyMaterial(THREE);
+ skyMat.uniforms.uSunDir.value.set(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el));
+ const sky = new THREE.Mesh(new THREE.SphereGeometry(SKY_RADIUS, 32, 16), skyMat);
+ sky.name = 'Sky';
+ sky.frustumCulled = false;
+ group.add(sky);
+
+ // --- lights: one shadow-casting sun + hemisphere fill (sky/ground colours)
+ const sun = new THREE.DirectionalLight(0xfff1d6, 2.6);
+ sun.position.set(Math.sin(az) * Math.cos(el) * 80, Math.sin(el) * 80, Math.cos(az) * Math.cos(el) * 80);
+ sun.castShadow = true;
+ sun.shadow.mapSize.set(2048, 2048);
+ sun.shadow.camera.near = 10; sun.shadow.camera.far = 220;
+ sun.shadow.camera.left = -45; sun.shadow.camera.right = 45;
+ sun.shadow.camera.top = 45; sun.shadow.camera.bottom = -45;
+ sun.shadow.bias = -0.0005; sun.shadow.normalBias = 0.02;
+ sun.target.position.set(0, 0, 0);
+ group.add(sun, sun.target);
+ const hemi = new THREE.HemisphereLight(0xbcd7ff, 0x4a5a2a, 0.9);
+ group.add(hemi);
+
+ // --- fog + background matched to the sky horizon colour
+ scene.fog = new THREE.Fog(0xcfdcec, FOG_NEAR, FOG_FAR);
+ scene.background = new THREE.Color(0xcfdcec);
+ scene.add(group);
+
+ const update = (t) => { skyMat.uniforms.uTime.value = t; };
+ const sunDir = sun.position.clone().normalize();
+ return { ground, sky, sun, sunDir, hemi, group, update };
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/scene.js b/harness/codeverse/languages/scene_threejs/starter/src/scene.js
new file mode 100644
index 00000000..a0527361
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/scene.js
@@ -0,0 +1,41 @@
+// src/scene.js — the ONE entry the harness loads.
+//
+// CONTRACT (scene_threejs):
+// export function createScene({ THREE, renderer, loaders })
+// → { scene, cameras: [{ name, position: [x,y,z], lookAt: [x,y,z], fov }], update(t, dt) }
+// • Y is up, +Z is front, units are meters. The scene owns its lights, sky/env and fog.
+// • cameras: 1-6 authored shots (eye ≥ 0.3 m from any surface, above ground).
+// • update(t, dt): t = seconds since start, dt = step; animate here (no requestAnimationFrame).
+// • loaders.gltf is a GLTFLoader: loaders.gltf.loadAsync('/assets/<name>.glb') for Blender-built assets.
+// • Imports allowed: 'three', 'three/addons/*', relative files. No CDN, no network, no DOM access.
+// • Raw three.js + GLSL only: never import any helper SDK.
+import * as THREE from 'three';
+import { buildEnv, heightAt, SUN_AZIMUTH_DEG } from './env.js';
+import { build as buildMeadow } from './zones/meadow.js';
+import { build as buildPondside } from './zones/pondside.js';
+
+export function createScene({ THREE: T = THREE, renderer, loaders }) {
+ const scene = new THREE.Scene();
+ const ctx = { THREE, scene, renderer, loaders, heightAt, sunAzimuthDeg: SUN_AZIMUTH_DEG };
+
+ const env = buildEnv(ctx); // ground, sky, sun, hemi light, fog
+ ctx.env = env;
+
+ // Each zone returns ONE named THREE.Group (PascalCase = zone name in the census/judge).
+ const zones = [buildMeadow(ctx), buildPondside(ctx)];
+ for (const z of zones) scene.add(z);
+
+ const cameras = [
+ { name: 'overview', position: [26, 14, 34], lookAt: [0, 1.5, 0], fov: 50 },
+ { name: 'pond_low', position: [-4.5, heightAt(-4.5, 13) + 1.4, 13], lookAt: [-8, 0.3, 4], fov: 45 },
+ { name: 'windmill', position: [9, heightAt(9, 9) + 1.7, 9], lookAt: [12, 4.5, -2], fov: 50 },
+ ];
+
+ // Animation fan-out: env first (sun/sky), then zones. Keep update cheap.
+ function update(t, dt) {
+ if (env.update) env.update(t, dt);
+ for (const z of zones) if (z.userData.update) z.userData.update(t, dt);
+ }
+
+ return { scene, cameras, update };
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/shaders/sky.js b/harness/codeverse/languages/scene_threejs/starter/src/shaders/sky.js
new file mode 100644
index 00000000..c7c71bd1
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/shaders/sky.js
@@ -0,0 +1,46 @@
+// src/shaders/sky.js — gradient sky dome (raw GLSL in a ShaderMaterial).
+// Pattern: uniforms object + vertex/fragment strings + `#include` chunks ALONE on their line.
+// No #version / precision lines (three.js prepends them). gl_FragColor is fine (no glslVersion).
+import * as THREE from 'three';
+
+const vertexShader = /* glsl */ `
+varying vec3 vWorldDir;
+void main() {
+ vec4 wp = modelMatrix * vec4(position, 1.0);
+ vWorldDir = normalize(wp.xyz - cameraPosition);
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
+}
+`;
+
+const fragmentShader = /* glsl */ `
+uniform vec3 uZenith;
+uniform vec3 uHorizon;
+uniform vec3 uSunDir;
+uniform float uTime;
+varying vec3 vWorldDir;
+void main() {
+ float h = clamp(vWorldDir.y, -0.2, 1.0);
+ vec3 col = mix(uHorizon, uZenith, pow(max(h, 0.0), 0.55));
+ float sun = pow(max(dot(normalize(vWorldDir), normalize(uSunDir)), 0.0), 180.0);
+ col += vec3(1.0, 0.9, 0.7) * sun * 1.5;
+ // slow drifting haze band so the sky is visibly alive in update(t)
+ col += 0.04 * sin(vWorldDir.x * 6.0 + uTime * 0.15) * (1.0 - h);
+ gl_FragColor = vec4(col, 1.0);
+}
+`;
+
+export function makeSkyMaterial(T = THREE) {
+ return new T.ShaderMaterial({
+ uniforms: {
+ uZenith: { value: new T.Color(0x3f74c9) },
+ uHorizon: { value: new T.Color(0xcfdcec) },
+ uSunDir: { value: new T.Vector3(-0.45, 0.6, -0.65) },
+ uTime: { value: 0 },
+ },
+ vertexShader,
+ fragmentShader,
+ side: T.BackSide,
+ depthWrite: false,
+ fog: false,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/shaders/water.js b/harness/codeverse/languages/scene_threejs/starter/src/shaders/water.js
new file mode 100644
index 00000000..367661bc
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/shaders/water.js
@@ -0,0 +1,60 @@
+// src/shaders/water.js — animated water: ShaderMaterial WITH scene fog support.
+// makeWaterMaterial(THREE) → ShaderMaterial (uniforms.uTime driven from update)
+// Copyable boilerplate for "a custom material that still fogs":
+// fog: true + UniformsUtils.merge([UniformsLib.fog, {...}]) + fog chunks in both stages.
+import * as THREE from 'three';
+
+const vertexShader = /* glsl */ `
+#include <fog_pars_vertex>
+uniform float uTime;
+varying vec2 vUv;
+varying vec3 vWorldPos;
+varying vec3 vNormalW;
+void main() {
+ vUv = uv;
+ vec3 p = position;
+ float w = sin(p.x * 1.7 + uTime * 1.3) * 0.04 + cos(p.z * 2.3 - uTime * 1.1) * 0.03;
+ p.y += w;
+ vec4 wp = modelMatrix * vec4(p, 1.0);
+ vWorldPos = wp.xyz;
+ vNormalW = normalize(mat3(modelMatrix) * vec3(-cos(p.x * 1.7 + uTime * 1.3) * 0.07, 1.0, sin(p.z * 2.3 - uTime * 1.1) * 0.07));
+ vec4 mvPosition = viewMatrix * wp;
+ gl_Position = projectionMatrix * mvPosition;
+ #include <fog_vertex>
+}
+`;
+
+const fragmentShader = /* glsl */ `
+#include <fog_pars_fragment>
+uniform float uTime;
+uniform vec3 uDeep;
+uniform vec3 uShallow;
+uniform vec3 uSunDir;
+varying vec2 vUv;
+varying vec3 vWorldPos;
+varying vec3 vNormalW;
+void main() {
+ vec3 V = normalize(cameraPosition - vWorldPos);
+ vec3 N = normalize(vNormalW);
+ float fres = pow(1.0 - max(dot(N, V), 0.0), 3.0);
+ float ripple = 0.5 + 0.5 * sin((vUv.x + vUv.y) * 40.0 + uTime * 2.0);
+ vec3 col = mix(uDeep, uShallow, 0.35 * ripple + 0.65 * fres);
+ vec3 H = normalize(V + normalize(uSunDir));
+ col += vec3(1.0, 0.95, 0.85) * pow(max(dot(N, H), 0.0), 120.0) * 0.8;
+ gl_FragColor = vec4(col, 0.92);
+ #include <fog_fragment>
+}
+`;
+
+export function makeWaterMaterial(T = THREE) {
+ const uniforms = T.UniformsUtils.merge([
+ T.UniformsLib.fog,
+ {
+ uTime: { value: 0 },
+ uDeep: { value: new T.Color(0x1a4d6b) },
+ uShallow: { value: new T.Color(0x6fb3c9) },
+ uSunDir: { value: new T.Vector3(-0.45, 0.6, -0.65) },
+ },
+ ]);
+ return new T.ShaderMaterial({ uniforms, vertexShader, fragmentShader, transparent: true, fog: true, side: T.DoubleSide });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/zones/meadow.js b/harness/codeverse/languages/scene_threejs/starter/src/zones/meadow.js
new file mode 100644
index 00000000..16cf1f1a
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/zones/meadow.js
@@ -0,0 +1,66 @@
+// src/zones/meadow.js — one zone = one named THREE.Group.
+// export function build(ctx) → THREE.Group (ctx: { THREE, scene, env, heightAt, renderer, loaders })
+// Shows: instanced trees from an asset factory (pineTreeParts), seating on heightAt, a windmill
+// with its own update, and fan-out of animation through group.userData.update(t, dt).
+import * as THREE from 'three';
+import { pineTreeParts } from '../assets/pine_tree.js';
+import { buildWindmill } from '../assets/windmill.js';
+
+// deterministic PRNG: same layout every run (the harness diffs renders between rounds)
+function rng(seed) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
+
+export function build(ctx) {
+ const { heightAt } = ctx;
+ const zone = new THREE.Group();
+ zone.name = 'Meadow';
+
+ // --- instanced pine trees (one InstancedMesh per part; shared matrices)
+ const rand = rng(7);
+ const N = 140;
+ const mats = [];
+ for (let i = 0; i < N; i++) {
+ const a = rand() * Math.PI * 2, r = 14 + rand() * 30;
+ const x = Math.cos(a) * r, z = Math.sin(a) * r;
+ if (x < -2 && z > 0 && x > -18 && z < 18) continue; // keep the pond clear
+ const s = 0.7 + rand() * 0.9;
+ const m = new THREE.Matrix4().compose(
+ new THREE.Vector3(x, heightAt(x, z) - 0.05, z),
+ new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), rand() * Math.PI * 2),
+ new THREE.Vector3(s, s, s),
+ );
+ mats.push(m);
+ }
+ for (const part of pineTreeParts(THREE)) {
+ const im = new THREE.InstancedMesh(part.geometry, part.material, mats.length);
+ mats.forEach((m, i) => im.setMatrixAt(i, m));
+ im.instanceMatrix.needsUpdate = true;
+ im.castShadow = part.castShadow;
+ im.receiveShadow = true;
+ im.name = 'PineTrees';
+ zone.add(im);
+ }
+
+ // --- a few rocks
+ const rock = new THREE.MeshStandardMaterial({ color: 0x7b7b78, roughness: 0.95 });
+ for (let i = 0; i < 12; i++) {
+ const x = -20 + rand() * 40, z = -20 + rand() * 40;
+ if (x < -2 && z > 0 && x > -18 && z < 18) continue;
+ const s = 0.3 + rand() * 0.7;
+ const mesh = new THREE.Mesh(new THREE.DodecahedronGeometry(s, 1), rock);
+ mesh.position.set(x, heightAt(x, z) + s * 0.4, z);
+ mesh.scale.set(1, 0.6 + rand() * 0.3, 1);
+ mesh.rotation.y = rand() * 3;
+ mesh.castShadow = mesh.receiveShadow = true;
+ mesh.name = 'Rock';
+ zone.add(mesh);
+ }
+
+ // --- windmill (animated asset)
+ const mill = buildWindmill(THREE);
+ mill.position.set(12, heightAt(12, -2), -2);
+ mill.rotation.y = Math.PI * 0.15;
+ zone.add(mill);
+
+ zone.userData.update = (t, dt) => { mill.userData.update(t, dt); };
+ return zone;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/zones/pondside.js b/harness/codeverse/languages/scene_threejs/starter/src/zones/pondside.js
new file mode 100644
index 00000000..44611834
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/zones/pondside.js
@@ -0,0 +1,65 @@
+// src/zones/pondside.js — pond with the custom water shader + a bobbing lantern (animated).
+import * as THREE from 'three';
+import { makeWaterMaterial } from '../shaders/water.js';
+
+export function build(ctx) {
+ const { heightAt } = ctx;
+ const zone = new THREE.Group();
+ zone.name = 'Pondside';
+
+ // water plane slightly below the meadow surface; pond centre (-10, 9)
+ const waterMat = makeWaterMaterial(THREE);
+ if (ctx.env && ctx.env.sunDir) waterMat.uniforms.uSunDir.value.copy(ctx.env.sunDir);
+ const water = new THREE.Mesh(new THREE.CircleGeometry(7.5, 48), waterMat);
+ water.rotation.x = -Math.PI / 2;
+ water.position.set(-10, -0.05, 9);
+ water.name = 'PondWater';
+ zone.add(water);
+
+ // dark basin under the water so the pond reads as depth, not a disc on grass
+ const basin = new THREE.Mesh(
+ new THREE.CylinderGeometry(7.8, 5.5, 1.2, 48, 1, false),
+ new THREE.MeshStandardMaterial({ color: 0x23321f, roughness: 1.0 }),
+ );
+ basin.position.set(-10, -0.66, 9);
+ basin.receiveShadow = true;
+ basin.name = 'PondBasin';
+ zone.add(basin);
+
+ // a wooden jetty
+ const wood = new THREE.MeshStandardMaterial({ color: 0x7a5a35, roughness: 0.85 });
+ const jetty = new THREE.Group();
+ jetty.name = 'Jetty';
+ const deck = new THREE.Mesh(new THREE.BoxGeometry(1.4, 0.12, 5.0), wood);
+ deck.position.set(0, 0.35, 0);
+ deck.castShadow = deck.receiveShadow = true;
+ jetty.add(deck);
+ for (const [px, pz] of [[-0.55, -2.2], [0.55, -2.2], [-0.55, 0], [0.55, 0], [-0.55, 2.2], [0.55, 2.2]]) {
+ const post = new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.07, 1.1, 8), wood);
+ post.position.set(px, -0.15, pz);
+ post.castShadow = true;
+ jetty.add(post);
+ }
+ jetty.position.set(-3.6, heightAt(-3.6, 9) - 0.25, 9);
+ jetty.rotation.y = Math.PI / 2;
+ zone.add(jetty);
+
+ // bobbing lantern: emissive + a small point light = the "glow" element
+ const lantern = new THREE.Group();
+ lantern.name = 'Lantern';
+ const glass = new THREE.Mesh(
+ new THREE.SphereGeometry(0.22, 16, 12),
+ new THREE.MeshStandardMaterial({ color: 0xffc070, emissive: 0xff9a30, emissiveIntensity: 2.2, roughness: 0.4 }),
+ );
+ const light = new THREE.PointLight(0xffa040, 6, 12, 2);
+ lantern.add(glass, light);
+ lantern.position.set(-9, 0.25, 7);
+ zone.add(lantern);
+
+ zone.userData.update = (t) => {
+ waterMat.uniforms.uTime.value = t;
+ lantern.position.y = 0.25 + Math.sin(t * 1.4) * 0.08;
+ lantern.position.x = -9 + Math.sin(t * 0.3) * 0.6;
+ };
+ return zone;
+}
diff --git a/harness/codeverse/languages/threejs/__init__.py b/harness/codeverse/languages/threejs/__init__.py
new file mode 100644
index 00000000..2648dae5
--- /dev/null
+++ b/harness/codeverse/languages/threejs/__init__.py
@@ -0,0 +1,6 @@
+"""three.js (static object) language runtime: raw ESM authored by the agent,
+GLB export + census by ``runtime_js/export_glb.mjs``."""
+
+from codeverse.languages.threejs.runtime import ThreeJsRuntime
+
+__all__ = ["ThreeJsRuntime"]
diff --git a/harness/codeverse/languages/threejs/contract.py b/harness/codeverse/languages/threejs/contract.py
new file mode 100644
index 00000000..1a5c3abe
--- /dev/null
+++ b/harness/codeverse/languages/threejs/contract.py
@@ -0,0 +1,35 @@
+"""Built-in fallback for the three.js authoring contract (prompts/threejs/contract.md wins)."""
+
+from __future__ import annotations
+
+CONTRACT_FALLBACK = """\
+# three.js static-object contract (raw ESM, no SDK)
+
+Files (all under `src/`):
+* `src/parts/<snake_name>.js` — one file per part:
+ `export function build<PascalName>(THREE) { ...; return group; }`
+ The returned `THREE.Group` is named `<PascalName>` and already sits at its WORLD pose
+ (no re-positioning happens in object.js).
+* `src/object.js` — `export function build(THREE) { ... return root; }` imports every part
+ builder, adds each part group to one root `THREE.Group` whose `.name` is the object name,
+ and returns it. Optional: `root.userData.tick = (t, dt) => { ... }` for idle animation.
+
+Frame & units: Y is UP, +Z is the FRONT (towards the default camera), +X is the right.
+Meters. The object stands on the ground: lowest point at y = 0, footprint centred on
+the Y axis. Real-world sizes (a chair seat is ~0.45 m high, not 45).
+
+Imports allowed: `import * as THREE from 'three'`, `three/addons/...` (e.g.
+`three/addons/utils/BufferGeometryUtils.js`, `three/addons/geometries/RoundedBoxGeometry.js`),
+and relative `./` files inside `src/`. Nothing else: no CDN/http URLs, no npm packages,
+no `fetch`, no `document`/`window`, no WebGLRenderer/cameras/lights/scenes in object code —
+the harness renders and exports for you.
+
+Geometry & materials: BufferGeometry only; `MeshStandardMaterial`/`MeshPhysicalMaterial`
+with explicit `color`, `roughness`, `metalness`. Textures are NOT exportable from node —
+use materials and vertex detail. Every mesh gets a meaningful `.name`. Keep total
+triangles well under 600k. Parts must physically touch (no floating pieces) and must not
+interpenetrate visibly.
+
+Build: the harness runs `build(THREE)` in node, validates the group (≥1 mesh, finite
+bbox, no NaN), and exports `artifacts/object.glb` with one named node per part.
+"""
diff --git a/harness/codeverse/languages/threejs/lint.py b/harness/codeverse/languages/threejs/lint.py
new file mode 100644
index 00000000..c48f17c3
--- /dev/null
+++ b/harness/codeverse/languages/threejs/lint.py
@@ -0,0 +1,223 @@
+"""Static lint for three.js static-object code (no execution of agent code).
+
+Checks: ESM syntax (``node --check``), allowed imports (``three``,
+``three/addons/*``, relative files that exist), forbidden browser/network/node
+APIs, the ``build`` / ``build<Pascal>`` entry points, and (when a plan exists)
+that every planned part has a file and is assembled by ``object.js``.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import subprocess
+import time
+from pathlib import Path
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.contracts.plan import StaticPlan
+from codeverse.conventions import to_pascal, to_snake
+from codeverse.workspace import Workspace
+
+GATE = "lint:threejs"
+
+_IMPORT_RE = re.compile(
+ r"""(?:^|\n)\s*(?:import\s+(?:[^'";]*?\s+from\s+)?|export\s+(?:\*|\{[^}]*\})\s+from\s+)['"]([^'"]+)['"]"""
+)
+_DYN_IMPORT_RE = re.compile(r"""\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)""")
+_EXPORT_BUILD_RE = re.compile(r"\bexport\s+(?:async\s+)?function\s+(build[A-Za-z0-9_]*)\s*\(")
+_EXPORT_CONST_BUILD_RE = re.compile(r"\bexport\s+(?:const|let|var)\s+(build[A-Za-z0-9_]*)\s*=")
+_EXPORT_LIST_RE = re.compile(r"\bexport\s*\{([^}]*)\}")
+# strings and comments in ONE alternation so a '//' inside a string is not a comment
+_TOKEN_RE = re.compile(
+ r"""'(?:\\.|[^'\\\n])*'|"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`|//[^\n]*|/\*.*?\*/""", re.S
+)
+
+# token -> (severity, message, fix hint)
+_FORBIDDEN: dict[str, tuple[Severity, str, str]] = {
+ r"\bfetch\s*\(": (Severity.ERROR, "network access (fetch) is not allowed in object code", "build geometry procedurally; no downloads"),
+ r"\bXMLHttpRequest\b": (Severity.ERROR, "network access (XMLHttpRequest) is not allowed", "remove it"),
+ r"\bWebSocket\b": (Severity.ERROR, "network access (WebSocket) is not allowed", "remove it"),
+ r"\bdocument\b": (Severity.ERROR, "DOM access (document) is not available: code runs in node", "remove DOM/canvas usage; no textures"),
+ r"\bwindow\b": (Severity.ERROR, "DOM access (window) is not available: code runs in node", "remove it"),
+ r"\bnavigator\b": (Severity.ERROR, "navigator is not available in node", "remove it"),
+ r"\blocalStorage\b": (Severity.ERROR, "localStorage is not available", "remove it"),
+ r"\brequire\s*\(": (Severity.ERROR, "CommonJS require() is not allowed; use ESM imports of 'three' only", "import * as THREE from 'three'"),
+ r"\bprocess\.": (Severity.ERROR, "node process access is not allowed in object code", "remove it"),
+ r"\beval\s*\(": (Severity.ERROR, "eval is not allowed", "remove it"),
+ r"\bWebGLRenderer\b": (Severity.ERROR, "do not create renderers: the harness renders", "return the Group from build(THREE); delete renderer code"),
+ r"\brequestAnimationFrame\b": (Severity.ERROR, "no render loops: put idle motion in root.userData.tick = (t, dt) => {}", "move per-frame logic into userData.tick"),
+ r"\bTextureLoader\b|\bImageLoader\b|\bFileLoader\b": (Severity.ERROR, "loaders/textures cannot be exported from node", "use MeshStandardMaterial colour/roughness/metalness instead"),
+ r"\bnew\s+THREE\.(?:Perspective|Orthographic)Camera\b": (Severity.WARN, "cameras in object code are ignored (harness owns the camera)", "delete it"),
+ r"\bnew\s+THREE\.[A-Za-z]*Light\s*\(": (Severity.WARN, "lights in object code are exported as extras and ignored by the harness lighting", "delete them"),
+ r"\bnew\s+THREE\.Scene\s*\(": (Severity.WARN, "do not build a Scene; return a Group", "replace Scene with Group"),
+}
+
+
+def _strip(src: str) -> str:
+ """Blank out comments and string contents (keeps newlines so line numbers survive)."""
+ def repl(m: re.Match[str]) -> str:
+ tok = m.group(0)
+ nl = "\n" * tok.count("\n")
+ return nl if tok.startswith("/") else '""' + nl
+ return _TOKEN_RE.sub(repl, src)
+
+
+def _line_of(text: str, pos: int) -> int:
+ return text.count("\n", 0, pos) + 1
+
+
+def _rel(ws: Workspace, p: Path) -> str:
+ try:
+ return str(p.relative_to(ws.root))
+ except ValueError:
+ return str(p)
+
+
+def list_sources(ws: Workspace) -> list[Path]:
+ if not ws.src.is_dir():
+ return []
+ return sorted(p for p in ws.src.rglob("*.js") if "node_modules" not in p.parts and not p.name.startswith("."))
+
+
+def check_syntax(path: Path, node_bin: str) -> tuple[int | None, str] | None:
+ """``None`` when the file parses as ESM, else ``(line, message)``."""
+ try:
+ proc = subprocess.run(
+ [node_bin, "--input-type=module", "--check"],
+ input=path.read_bytes(), capture_output=True, timeout=30,
+ )
+ except (OSError, subprocess.TimeoutExpired) as e:
+ return (None, f"syntax check could not run: {e}")
+ if proc.returncode == 0:
+ return None
+ err = proc.stderr.decode(errors="replace")
+ m = re.search(r"\[stdin\]:(\d+)", err)
+ msg = re.search(r"^(SyntaxError:.*)$", err, re.M)
+ return (int(m.group(1)) if m else None, msg.group(1) if msg else err.strip().splitlines()[-1:] or "syntax error")
+
+
+def _lint_imports(ws: Workspace, path: Path, src: str, findings: list[GateFinding]) -> set[Path]:
+ """Validate import specifiers; return the set of resolved relative targets."""
+ targets: set[Path] = set()
+ specs = [(m.group(1), m.start(1)) for m in _IMPORT_RE.finditer(src)]
+ specs += [(m.group(1), m.start(1)) for m in _DYN_IMPORT_RE.finditer(src)]
+ rel = _rel(ws, path)
+ for spec, pos in specs:
+ line = _line_of(src, pos)
+ if spec == "three" or spec.startswith("three/addons/") or spec.startswith("three/examples/jsm/"):
+ continue
+ if spec.startswith("./") or spec.startswith("../"):
+ target = (path.parent / spec).resolve()
+ if not target.is_relative_to(ws.src.resolve()):
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
+ message=f"{rel}:{line}: import '{spec}' escapes src/", fix_hint="keep all files under src/"))
+ elif not target.is_file():
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
+ message=f"{rel}:{line}: imported file does not exist: '{spec}'",
+ fix_hint=f"create {_rel(ws, target)} or fix the path (extension '.js' is required)"))
+ else:
+ targets.add(target)
+ continue
+ kind = "URL" if re.match(r"https?://", spec) else "package"
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
+ message=f"{rel}:{line}: import of {kind} '{spec}' is not allowed",
+ fix_hint="only 'three', 'three/addons/...' and relative './' imports are available"))
+ return targets
+
+
+def _lint_forbidden(ws: Workspace, path: Path, src: str, findings: list[GateFinding]) -> None:
+ stripped = _strip(src)
+ rel = _rel(ws, path)
+ for pattern, (sev, msg, hint) in _FORBIDDEN.items():
+ m = re.search(pattern, stripped)
+ if m:
+ findings.append(GateFinding(gate=GATE, severity=sev, target=rel,
+ message=f"{rel}:{_line_of(stripped, m.start())}: {msg}", fix_hint=hint))
+
+
+def _exports(src: str) -> set[str]:
+ names = {m.group(1) for m in _EXPORT_BUILD_RE.finditer(src)}
+ names |= {m.group(1) for m in _EXPORT_CONST_BUILD_RE.finditer(src)}
+ for m in _EXPORT_LIST_RE.finditer(src):
+ for item in m.group(1).split(","):
+ item = item.strip()
+ if not item:
+ continue
+ alias = item.split(" as ")[-1].strip()
+ if alias.startswith("build"):
+ names.add(alias)
+ return names
+
+
+def _load_plan(ws: Workspace) -> StaticPlan | None:
+ if not ws.plan_path.is_file():
+ return None
+ try:
+ data = json.loads(ws.plan_path.read_text())
+ if isinstance(data, dict) and "parts" in data and "joints" not in data:
+ return StaticPlan.model_validate(data)
+ except (ValueError, OSError):
+ return None
+ return None
+
+
+def lint_workspace(ws: Workspace) -> GateReport:
+ """Run every static check and return the ``lint:threejs`` GateReport."""
+ t0 = time.time()
+ findings: list[GateFinding] = []
+ node_bin = get_settings().binaries.node
+ entry = ws.src / "object.js"
+ sources = list_sources(ws)
+
+ if not entry.is_file():
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target="src/object.js",
+ message="src/object.js is missing", fix_hint="create src/object.js with `export function build(THREE) { ... return root; }`"))
+
+ imported: set[Path] = set()
+ for path in sources:
+ src = path.read_text(errors="replace")
+ rel = _rel(ws, path)
+ syn = check_syntax(path, node_bin)
+ if syn is not None:
+ line, msg = syn
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
+ message=f"{rel}:{line or '?'}: {msg}", fix_hint="fix the syntax error at that line"))
+ continue # other checks are noise on a file that does not parse
+ imported |= _lint_imports(ws, path, src, findings)
+ _lint_forbidden(ws, path, src, findings)
+ exports = _exports(src)
+ if path == entry:
+ if "build" not in exports:
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=rel,
+ message="src/object.js must `export function build(THREE)`", fix_hint="add `export function build(THREE) { const root = new THREE.Group(); ...; return root; }`"))
+ elif path.parent == ws.src / "parts":
+ expected = "build" + to_pascal(path.stem)
+ if expected not in exports:
+ sev = Severity.WARN if any(e != "build" for e in exports) else Severity.ERROR
+ findings.append(GateFinding(gate=GATE, severity=sev, target=rel,
+ message=f"{rel}: expected `export function {expected}(THREE)` (found {sorted(exports) or 'no build export'})",
+ fix_hint=f"rename the export to {expected} or the file to parts/{to_snake(exports.pop()[5:]) if exports else path.stem}.js"))
+
+ part_files = [p for p in sources if p.parent == ws.src / "parts"]
+ for p in part_files:
+ if p not in imported:
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=_rel(ws, p),
+ message=f"{_rel(ws, p)} is not imported by any module (dead part file?)", fix_hint="import and add it in src/object.js or delete it"))
+
+ plan = _load_plan(ws)
+ if plan is not None:
+ for part in plan.parts:
+ pf = ws.src / "parts" / f"{to_snake(part.name)}.js"
+ if not pf.is_file():
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=part.name,
+ message=f"planned part {part.name} has no file src/parts/{to_snake(part.name)}.js",
+ fix_hint=f"create it with `export function build{to_pascal(part.name)}(THREE)`"))
+ elif pf not in imported and entry.is_file():
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=part.name,
+ message=f"planned part {part.name} is not assembled by src/object.js",
+ fix_hint=f"import {{ build{to_pascal(part.name)} }} from './parts/{to_snake(part.name)}.js' and root.add(...)"))
+
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse/languages/threejs/runtime.py b/harness/codeverse/languages/threejs/runtime.py
new file mode 100644
index 00000000..d9ec5af7
--- /dev/null
+++ b/harness/codeverse/languages/threejs/runtime.py
@@ -0,0 +1,128 @@
+"""ThreeJsRuntime: skeleton → lint → build (node GLTFExporter) for static objects."""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+from typing import Any
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import BuildResult, GateReport
+from codeverse.contracts.common import Language
+from codeverse.contracts.plan import Plan
+from codeverse.languages.threejs.contract import CONTRACT_FALLBACK
+from codeverse.languages.threejs.lint import lint_workspace
+from codeverse.languages.threejs.skeleton import write_skeleton
+from codeverse.languages.threejs.templates import PACKAGE_JSON
+from codeverse.prompts import PROMPTS_DIR, load_text
+from codeverse.spatial.node import NodeError, NodeResult, run_node, runtime_js_dir
+from codeverse.workspace import Workspace
+
+ENTRY = "src/object.js"
+GLB_NAME = "object.glb"
+CENSUS_NAME = "census.json"
+BUILD_JSON = "build.json"
+NODE_MEM_LIMIT_GB = 8.0 # RLIMIT_AS for the export process (geometry-bomb protection)
+
+
+class ThreeJsRuntime:
+ """LanguageRuntime for ``Language.THREEJS`` (raw ESM three.js, exported via node)."""
+
+ language = Language.THREEJS
+ entry_globs: tuple[str, ...] = ("src/object.js", "src/parts/*.js")
+
+ # ------------------------------------------------------------------ contract
+ def contract_doc(self) -> str:
+ try:
+ return load_text("threejs/contract.md")
+ except FileNotFoundError:
+ return CONTRACT_FALLBACK
+
+ def cookbook_path(self) -> Path:
+ return PROMPTS_DIR / "threejs" / "cookbook.md"
+
+ # ------------------------------------------------------------------ skeleton / lint
+ def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
+ return write_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_workspace(ws)
+
+ # ------------------------------------------------------------------ build
+ def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
+ """Run ``runtime_js/export_glb.mjs`` on ``src/object.js`` → ``artifacts/object.glb``.
+
+ Never raises for agent-code failures: they come back as ``ok=False`` with
+ ``error_type/message/file/line`` and the stdout/stderr tails. Harness
+ misconfiguration (missing node, missing script) still raises.
+ """
+ settings = get_settings()
+ timeout_s = timeout_s or settings.limits.build_timeout_s
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ glb = ws.artifacts / GLB_NAME
+ census = ws.artifacts / CENSUS_NAME
+ for stale in (glb, census, ws.artifacts / "export_error.json"):
+ stale.unlink(missing_ok=True)
+ self._ensure_module_type(ws)
+
+ t0 = time.time()
+ args = ["--ws", str(ws.root), "--entry", ENTRY, "--out", str(glb), "--census", str(census)]
+ try:
+ res = run_node(
+ runtime_js_dir() / "export_glb.mjs", args, cwd=ws.root, timeout_s=timeout_s,
+ three_hook=True, node_args=["--max-old-space-size=4096"], check=False,
+ mem_limit_gb=NODE_MEM_LIMIT_GB,
+ )
+ except NodeError as e:
+ if e.result is None:
+ raise # harness problem (no node binary / script)
+ result = self._failure(e.result, "Timeout" if e.result.timed_out else "NodeError", str(e))
+ self._write_build_json(ws, result)
+ return result
+
+ if res.rc != 0 or not (res.last_json or {}).get("ok") or not glb.is_file():
+ result = self._from_error_record(res)
+ else:
+ census_data: dict[str, Any] = {}
+ if census.is_file():
+ census_data = json.loads(census.read_text())
+ result = BuildResult(
+ ok=True, language=self.language.value, glb_path=str(glb),
+ stdout_tail=res.stdout_tail, stderr_tail=res.stderr_tail,
+ duration_ms=int((time.time() - t0) * 1000), census=census_data,
+ extra_paths={"census": str(census)},
+ )
+ self._write_build_json(ws, result)
+ return result
+
+ # ------------------------------------------------------------------ helpers
+ @staticmethod
+ def _ensure_module_type(ws: Workspace) -> None:
+ """``src/package.json`` {type: module} so ``.js`` files are parsed as ESM."""
+ ws.src.mkdir(parents=True, exist_ok=True)
+ pj = ws.src / "package.json"
+ if not pj.is_file():
+ pj.write_text(PACKAGE_JSON)
+
+ def _failure(self, res: NodeResult, etype: str, message: str) -> BuildResult:
+ return BuildResult(
+ ok=False, language=self.language.value, stdout_tail=res.stdout_tail, stderr_tail=res.stderr_tail,
+ error_type=etype, error_message=message[:2000], duration_ms=res.duration_ms,
+ )
+
+ def _from_error_record(self, res: NodeResult) -> BuildResult:
+ rec = res.last_json or {}
+ err = rec.get("error") if isinstance(rec.get("error"), dict) else None
+ if err is None:
+ tail = res.stderr_tail.strip().splitlines()
+ return self._failure(res, "ExportError", tail[-1] if tail else f"export_glb exited {res.rc} without an error record")
+ result = self._failure(res, str(err.get("type", "Error")), str(err.get("message", "")))
+ result.error_file = str(err.get("file", "") or ("" if err.get("frames") else ENTRY))
+ result.error_line = err.get("line") if isinstance(err.get("line"), int) else None
+ result.census = {"frames": err.get("frames", []), "stack": err.get("stack", "")}
+ return result
+
+ @staticmethod
+ def _write_build_json(ws: Workspace, result: BuildResult) -> None:
+ ws.write_json(ws.artifacts / BUILD_JSON, result)
diff --git a/harness/codeverse/languages/threejs/skeleton.py b/harness/codeverse/languages/threejs/skeleton.py
new file mode 100644
index 00000000..2f8c1783
--- /dev/null
+++ b/harness/codeverse/languages/threejs/skeleton.py
@@ -0,0 +1,82 @@
+"""Starter files for a three.js static object from a StaticPlan.
+
+Every part gets a stub that already BUILDS (a rounded-box placeholder at the
+planned bbox) so the skeleton exports and renders before the agent touches it;
+the agent replaces placeholders part by part and the gates show what is left.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.contracts.plan import Plan, StaticPlan
+from codeverse.conventions import to_pascal, to_snake
+from codeverse.languages.threejs.templates import (
+ OBJECT_HEADER,
+ PACKAGE_JSON,
+ PART_TEMPLATE,
+ PLACEHOLDER_COLORS,
+)
+from codeverse.workspace import Workspace
+
+
+def part_file(ws: Workspace, part_name: str) -> Path:
+ """``src/parts/<snake>.js`` for a plan part name."""
+ return ws.src / "parts" / f"{to_snake(part_name)}.js"
+
+
+def _fmt(v: float) -> str:
+ return f"{float(v):.4g}"
+
+
+def render_part_stub(part, index: int) -> str:
+ """JS source of one placeholder part file."""
+ c, e = part.bbox.center, part.bbox.extents
+ material_line = f"\n// Material: {part.material}" if part.material else ""
+ return PART_TEMPLATE.format(
+ pascal=to_pascal(part.name),
+ role=part.role,
+ description=part.description.replace("\n", " "),
+ center=f"({_fmt(c[0])}, {_fmt(c[1])}, {_fmt(c[2])})",
+ extents=f"({_fmt(e[0])}, {_fmt(e[1])}, {_fmt(e[2])})",
+ material_line=material_line,
+ ex=_fmt(max(e[0], 0.001)),
+ ey=_fmt(max(e[1], 0.001)),
+ ez=_fmt(max(e[2], 0.001)),
+ cx=_fmt(c[0]),
+ cy=_fmt(c[1]),
+ cz=_fmt(c[2]),
+ color=PLACEHOLDER_COLORS[index % len(PLACEHOLDER_COLORS)],
+ )
+
+
+def render_object(plan: StaticPlan) -> str:
+ imports = "\n".join(
+ f"import {{ build{to_pascal(p.name)} }} from './parts/{to_snake(p.name)}.js';" for p in plan.parts
+ )
+ adds = "\n".join(f" root.add(build{to_pascal(p.name)}(THREE));" for p in plan.parts)
+ return OBJECT_HEADER.format(object_name=to_pascal(plan.object_name), imports=imports, adds=adds)
+
+
+def write_skeleton(ws: Workspace, plan: Plan, *, overwrite: bool = False) -> list[Path]:
+ """Write ``src/package.json``, ``src/object.js`` and ``src/parts/*.js``; return written paths.
+
+ Existing files are kept unless ``overwrite`` (so re-running on a refined
+ workspace never clobbers agent work).
+ """
+ if not isinstance(plan, StaticPlan):
+ raise TypeError(f"threejs skeleton needs a StaticPlan, got {type(plan).__name__}")
+ written: list[Path] = []
+ (ws.src / "parts").mkdir(parents=True, exist_ok=True)
+
+ def _put(path: Path, text: str) -> None:
+ if path.exists() and not overwrite:
+ return
+ path.write_text(text)
+ written.append(path)
+
+ _put(ws.src / "package.json", PACKAGE_JSON)
+ _put(ws.src / "object.js", render_object(plan))
+ for i, part in enumerate(plan.parts):
+ _put(part_file(ws, part.name), render_part_stub(part, i))
+ return written
diff --git a/harness/codeverse/languages/threejs/templates.py b/harness/codeverse/languages/threejs/templates.py
new file mode 100644
index 00000000..df56d966
--- /dev/null
+++ b/harness/codeverse/languages/threejs/templates.py
@@ -0,0 +1,65 @@
+"""String templates for the three.js skeleton (object.js + one stub per part)."""
+
+from __future__ import annotations
+
+PACKAGE_JSON = '{ "type": "module", "private": true }\n'
+
+OBJECT_HEADER = """\
+// {object_name} — three.js static object (raw ESM). Harness contract:
+// export function build(THREE) -> THREE.Group (root.name = object name)
+// Y up, +Z front, meters; object stands on y=0, footprint centred on the Y axis.
+// Parts live in ./parts/<snake>.js, each `export function build<Pascal>(THREE)`
+// returning a Group already at its WORLD pose. object.js only assembles.
+// Optional idle animation: root.userData.tick = (t, dt) => {{ ... }}
+// Allowed imports: 'three', 'three/addons/...', relative './'. No network, no DOM.
+import * as THREE from 'three';
+{imports}
+
+export function build(THREE_) {{
+ const root = new THREE.Group();
+ root.name = '{object_name}';
+{adds}
+ return root;
+}}
+"""
+
+PART_TEMPLATE = """\
+// Part: {pascal} ({role})
+// {description}
+// Plan bbox (world, meters): centre {center} extents {extents}{material_line}
+// Contract: export function build{pascal}(THREE) -> THREE.Group named '{pascal}', at WORLD pose.
+// Y up, +Z front. Use real sizes in meters. Name every mesh. No lights/cameras/renderers.
+import * as THREE from 'three';
+import {{ RoundedBoxGeometry }} from 'three/addons/geometries/RoundedBoxGeometry.js';
+
+export function build{pascal}(THREE_) {{
+ const group = new THREE.Group();
+ group.name = '{pascal}';
+
+ // ---- PLACEHOLDER (replace with real construction; keep the group name) ----
+ // A rounded box filling the planned bbox. Copyable recipes:
+ // box: new THREE.BoxGeometry(w, h, d)
+ // bevelled: new RoundedBoxGeometry(w, h, d, 4, Math.min(w, h, d) * 0.08)
+ // cylinder: new THREE.CylinderGeometry(rTop, rBottom, h, 32)
+ // lathe: new THREE.LatheGeometry(points /* Vector2[] (x=radius, y=height) */, 48)
+ // extrude w/ bevel:
+ // const shape = new THREE.Shape(); shape.moveTo(-w/2, -d/2); shape.lineTo(w/2, -d/2);
+ // shape.lineTo(w/2, d/2); shape.lineTo(-w/2, d/2); shape.closePath();
+ // const geo = new THREE.ExtrudeGeometry(shape, {{ depth: h, bevelEnabled: true,
+ // bevelThickness: 0.004, bevelSize: 0.004, bevelSegments: 3 }});
+ // geo.rotateX(-Math.PI / 2); // extrude along +Y instead of +Z
+ // merge many: import {{ mergeGeometries }} from 'three/addons/utils/BufferGeometryUtils.js';
+ const size = [{ex}, {ey}, {ez}];
+ const geometry = new RoundedBoxGeometry(size[0], size[1], size[2], 3, Math.min(...size) * 0.08);
+ const material = new THREE.MeshStandardMaterial({{ color: {color}, roughness: 0.6, metalness: 0.05 }});
+ const mesh = new THREE.Mesh(geometry, material);
+ mesh.name = '{pascal}Body';
+ mesh.position.set({cx}, {cy}, {cz}); // world pose (bbox centre)
+ group.add(mesh);
+ // ---- END PLACEHOLDER ----
+
+ return group;
+}}
+"""
+
+PLACEHOLDER_COLORS = ("0x9aa5b1", "0xb08968", "0x7f8c8d", "0xc0a080", "0x6c7a89", "0xa0522d", "0x8fa3ad", "0xbfa27a")
diff --git a/harness/codeverse/languages/threejs/wrappers/README.md b/harness/codeverse/languages/threejs/wrappers/README.md
new file mode 100644
index 00000000..289eb0a6
--- /dev/null
+++ b/harness/codeverse/languages/threejs/wrappers/README.md
@@ -0,0 +1,5 @@
+The three.js build/export wrappers are node scripts and live in `runtime_js/`
+(`export_glb.mjs`, `render_glb.mjs`, `lib/*.mjs`). They are invoked through
+`codeverse.spatial.node.run_node` with the `--import lib/resolve_three.mjs`
+hook so agent code can `import 'three'` without a node_modules of its own.
+Agent code never imports anything from here.
diff --git a/harness/codeverse/languages/urdf/CONTRACT.md b/harness/codeverse/languages/urdf/CONTRACT.md
new file mode 100644
index 00000000..06c05942
--- /dev/null
+++ b/harness/codeverse/languages/urdf/CONTRACT.md
@@ -0,0 +1,127 @@
+# Authoring contract — language `urdf_blender` (articulated objects)
+
+You write exactly TWO raw files. No SDK, no imports from the harness.
+
+```
+src/model.py pure bpy — one mesh object per LINK, at its rest-pose WORLD placement
+src/robot.urdf native URDF — links + joints; meshes referenced as meshes/<link>.glb
+```
+
+The harness runs `model.py` headless, exports `meshes/<link>.glb` per link, lints the
+URDF, checks that the URDF frames reproduce your geometry, sweeps every joint through
+its range looking for collisions / floating parts, and renders an articulation sheet
+(rest + every joint at both limits) for the judge.
+
+## 1. Frame, units, naming
+
+* Z is UP, **-Y is the FRONT** of the object, +X its right. Meters. Radians.
+* The object stands on the ground: lowest point at z = 0, footprint centred on the Z axis.
+* Link names are `snake_case` part names: `base`, `door`, `drawer`, `lid`, `handle_left`.
+ Never state words (`door_open`): states come from joints.
+* The bpy object for a link is named **exactly** like the link (case-sensitive).
+
+## 2. `src/model.py` — the meshes (pure bpy)
+
+* The scene is EMPTY when your script starts (no default cube). Build geometry with
+ `bpy.ops.mesh.primitive_*`, `bmesh`, modifiers, booleans — anything in bpy.
+* ONE mesh object per URDF link, named exactly `<link>`, placed where the part sits in the
+ **authored rest pose** (world coordinates). Extra helper objects must be parented under a
+ link object (`ob.parent = link_obj`) — the wrapper joins every descendant into that link.
+ Any mesh object that is not a link (or under one) is a build error.
+* Visible detail lives in the meshes (panels, bevels, handles, rails, hinge barrels).
+ Materials are welcome (`ob.data.materials.append(...)`, Principled BSDF colours).
+* Do NOT: create cameras/lights, render, export, import files, `bpy.ops.wm.*`, `sys.exit`,
+ network/subprocess, infinite loops. The harness owns all of that.
+* The wrapper exports each link with world-space geometry baked in (`meshes/<link>.glb`,
+ Z-up raw coordinates — NOT glTF Y-up — so any URDF loader places them correctly).
+
+Copyable helper (raw bpy; keep it in your file if you like):
+
+```python
+import bpy
+
+def box(name, center, size):
+ bpy.ops.mesh.primitive_cube_add(size=1.0, location=center)
+ ob = bpy.context.active_object
+ ob.name = name
+ ob.scale = size
+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+ return ob
+
+body = box("body", (0, 0, 0.40), (0.60, 0.40, 0.80)) # carcass, on the ground
+door = box("door", (0, -0.21, 0.40), (0.58, 0.02, 0.78)) # front panel (front = -Y)
+```
+
+## 3. `src/robot.urdf` — links and joints (native URDF)
+
+URDF semantics (standard): a joint's `<origin>` places the joint frame in the PARENT link
+frame; `<axis>` is in the joint frame; the CHILD link frame coincides with the joint frame at
+`q = 0`; `q = 0` is YOUR authored rest pose. Positive revolute `q` rotates by the right-hand
+rule about `<axis>`; positive prismatic `q` slides along `<axis>`.
+
+### The recipe we enforce (link frames at pivots, meshes authored in world)
+
+1. The **root link frame = world origin** (`0 0 0`).
+2. Every other **link frame = its parent joint's pivot point (world, rest pose)**, no
+ rotation (`rpy="0 0 0"`); express the joint direction with `<axis>`, not with rpy.
+3. Joint `<origin xyz>` = `pivot_world(child) − link_frame_world(parent)` (accumulate down the
+ chain; for a joint whose parent is the root this is just the pivot).
+4. Visual AND collision `<origin xyz>` = `−link_frame_world(link)` (the inverse transform,
+ because `meshes/<link>.glb` holds world coordinates). Root link: `0 0 0`.
+5. One `<visual>` + one identical `<collision>` per link; geometry is always
+ `<mesh filename="meshes/<link>.glb"/>`.
+6. `revolute` / `prismatic` need `<limit lower upper effort velocity>` (rad / m) with
+ `lower ≤ 0 ≤ upper`; `continuous` has no lower/upper; `fixed` has no axis/limit.
+ If positive motion goes the wrong way, **negate the axis — never swap the limits**.
+
+The harness VERIFIES step 4 numerically (FK at q=0 must reproduce your model.py bboxes
+within 1 mm) and tells you the exact corrected numbers if it is wrong.
+
+### Worked example — cabinet with a front door hinged on its left edge
+
+Door panel authored at x ∈ [-0.29, 0.29], y ∈ [-0.22, -0.20], z ∈ [0.01, 0.79]. Hinge axis is
+vertical along the door's left edge: pivot world = `(-0.29, -0.20, 0)`. A door opening toward
+the viewer (-Y) from a left hinge swings clockwise seen from above ⇒ axis `0 0 -1`.
+
+```xml
+<?xml version="1.0"?>
+<robot name="cabinet">
+ <link name="body">
+ <visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/body.glb"/></geometry></visual>
+ <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/body.glb"/></geometry></collision>
+ </link>
+ <link name="door"> <!-- link frame at the hinge pivot (-0.29 -0.20 0) → visual origin is its negation -->
+ <visual><origin xyz="0.29 0.20 0" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></visual>
+ <collision><origin xyz="0.29 0.20 0" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></collision>
+ </link>
+ <joint name="hinge" type="revolute">
+ <parent link="body"/>
+ <child link="door"/>
+ <origin xyz="-0.29 -0.20 0" rpy="0 0 0"/> <!-- pivot_world(door) - frame_world(body) -->
+ <axis xyz="0 0 -1"/>
+ <limit lower="0" upper="1.7" effort="10" velocity="1"/>
+ </joint>
+</robot>
+```
+
+Drawer (prismatic, slides out of the front): pivot anywhere on the drawer, e.g. its rest
+centre `(0, -0.05, 0.3)`; `<axis xyz="0 -1 0"/>`, `<limit lower="0" upper="0.35" .../>`;
+visual origin `0 0.05 -0.3`. Chain: a handle on the door → parent `door`, pivot = handle
+centre, joint `fixed`, joint origin = `handle_pivot − door_pivot`, visual origin = `−handle_pivot`.
+
+## 4. What the harness checks (and tells you, with numbers)
+
+* lint: XML, one root, tree, names, limits, axis, mesh paths, collision twins;
+ model.py: forbidden calls, every link name present as a string.
+* build: `model.py` runs; each link has an object; no stray objects.
+* FK consistency: URDF frames reproduce model.py placement (corrected `<origin>` reported).
+* pose sweep: rest + each joint at lower/mid/upper + random combos → link pairs must not
+ interpenetrate (> 2 mm), nothing may float (each link touches the grounded assembly,
+ ≤ 2 mm gap; hinge clearance ≤ 1 cm is only a warning), per-link islands counted.
+ Penetration > 5 mm at REST fails the build.
+* motion direction (when the plan states it): the child centroid must move the stated way.
+* renders: rest and limit poses on one sheet — the judge sees your articulation.
+
+Design advice: give parts 2-5 mm clearance where they move; pivots sit on real hinge lines
+(door edge, lid back edge); drawers keep ≥ 1/3 of their depth inside at full extension;
+continuous joints only for wheels/knobs; model visible hinges, rails and handles so nothing floats.
diff --git a/harness/codeverse/languages/urdf/__init__.py b/harness/codeverse/languages/urdf/__init__.py
new file mode 100644
index 00000000..debefbe6
--- /dev/null
+++ b/harness/codeverse/languages/urdf/__init__.py
@@ -0,0 +1,6 @@
+"""``urdf_blender``: bpy link meshes + hand-written URDF (package E).
+
+Modules: ``runtime`` (UrdfBlenderRuntime), ``lint``, ``skeleton``, ``consistency``
+(FK ↔ authored geometry), ``wrappers/run_bpy_links.py`` (Blender-side build),
+``wrappers/render_glb_bpy.py`` (fallback renderer). Contract: ``CONTRACT.md``.
+"""
diff --git a/harness/codeverse/languages/urdf/consistency.py b/harness/codeverse/languages/urdf/consistency.py
new file mode 100644
index 00000000..a2d6e9f6
--- /dev/null
+++ b/harness/codeverse/languages/urdf/consistency.py
@@ -0,0 +1,78 @@
+"""FK ↔ authored-geometry consistency check for ``urdf_blender`` builds.
+
+``model.py`` authors every link mesh at its rest-pose WORLD placement; the
+wrapper exports those world coordinates into ``meshes/<link>.glb`` and records
+the world bbox per link in ``census.json``. The URDF must then place each mesh
+back exactly where it was authored at ``q = 0``:
+
+ T_link_rest(q=0) · T_visual · mesh_world == mesh_world
+ ⇒ T_visual == inv(T_link_rest)
+
+We verify this numerically (bbox of the FK-posed mesh vs the census bbox, 1 mm)
+and report the exact corrected ``<origin>`` when it is wrong.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import numpy as np
+
+from codeverse.contracts.artifacts import GateFinding, Severity
+from codeverse.spatial.joints_model import Robot, fk, invert_transform, matrix_to_rpy
+
+GATE = "fk_consistency"
+
+
+def _fmt(v: float) -> str:
+ s = f"{v:.6f}".rstrip("0").rstrip(".")
+ return "0" if s in ("", "-0") else s
+
+
+def _vec(v) -> str:
+ return " ".join(_fmt(float(x)) for x in v)
+
+
+def check_fk_consistency(robot: Robot, census_links: dict[str, dict[str, Any]], *, tol_m: float = 0.001) -> list[GateFinding]:
+ """Compare every link's FK-posed mesh bbox at rest with the authored census bbox.
+
+ Returns one ERROR finding per inconsistent link carrying the corrected visual
+ origin (``fix_hint`` is copy-pasteable XML) and an INFO summary otherwise."""
+ T = fk(robot, {})
+ out: list[GateFinding] = []
+ for name, link in robot.links.items():
+ if link.mesh is None:
+ continue
+ row = census_links.get(name)
+ if row is None:
+ out.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=name,
+ message=f"link '{name}' has no authored mesh in census (wrapper exported nothing for it)",
+ fix_hint=f"Create a mesh object named exactly '{name}' in model.py."))
+ continue
+ pts = np.asarray(link.mesh.vertices) @ T[name][:3, :3].T + T[name][:3, 3]
+ fk_min, fk_max = pts.min(axis=0), pts.max(axis=0)
+ au_min, au_max = np.asarray(row["bbox_min"], dtype=float), np.asarray(row["bbox_max"], dtype=float)
+ err = float(max(np.abs(fk_min - au_min).max(), np.abs(fk_max - au_max).max()))
+ if err <= tol_m:
+ continue
+ T_fix = invert_transform(T[name])
+ xyz_fix = T_fix[:3, 3]
+ rpy_fix = matrix_to_rpy(T_fix[:3, :3])
+ cur_xyz = link.visual_origin[:3, 3]
+ cur_rpy = matrix_to_rpy(link.visual_origin[:3, :3])
+ frame_xyz = T[name][:3, 3]
+ out.append(GateFinding(
+ gate=GATE, severity=Severity.ERROR, target=name,
+ message=(f"link '{name}': FK at q=0 puts the mesh at bbox [{_vec(fk_min)}]..[{_vec(fk_max)}] but model.py authored it at "
+ f"[{_vec(au_min)}]..[{_vec(au_max)}] (max error {err*1000:.1f} mm). Its link frame is at world "
+ f"[{_vec(frame_xyz)}] so the visual origin must be the inverse: xyz=\"{_vec(xyz_fix)}\" "
+ f"(you wrote xyz=\"{_vec(cur_xyz)}\" rpy=\"{_vec(cur_rpy)}\")."),
+ fix_hint=(f"In robot.urdf, link '{name}': set BOTH <visual> and <collision> to "
+ f"<origin xyz=\"{_vec(xyz_fix)}\" rpy=\"{_vec(rpy_fix)}\"/> "
+ f"(= -(joint pivot world) when joints have rpy=0; or move the joint origin so the pivot is where you meant)."),
+ data={"error_m": err, "fk_bbox": [fk_min.tolist(), fk_max.tolist()], "authored_bbox": [au_min.tolist(), au_max.tolist()],
+ "corrected_visual_origin": {"xyz": [float(v) for v in xyz_fix], "rpy": [float(v) for v in rpy_fix]},
+ "current_visual_origin": {"xyz": [float(v) for v in cur_xyz], "rpy": [float(v) for v in cur_rpy]},
+ "link_frame_world_xyz": [float(v) for v in frame_xyz]},
+ ))
+ return out
diff --git a/harness/codeverse/languages/urdf/lint.py b/harness/codeverse/languages/urdf/lint.py
new file mode 100644
index 00000000..bbb50af3
--- /dev/null
+++ b/harness/codeverse/languages/urdf/lint.py
@@ -0,0 +1,364 @@
+"""Static lint for the ``urdf_blender`` language: ``src/robot.urdf`` (URDF rules)
+and ``src/model.py`` (bpy pitfalls + link-name coverage). Gate ``lint:urdf``.
+
+Every finding carries a copyable ``fix_hint``. Errors block the build; warnings
+are shown to the agent/judge.
+"""
+
+from __future__ import annotations
+
+import ast
+import math
+import re
+import time
+import xml.etree.ElementTree as ET
+from pathlib import Path
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.conventions import to_snake
+from codeverse.spatial.joints_model import JOINT_TYPES, MOVABLE_TYPES
+from codeverse.workspace import Workspace
+
+GATE = "lint:urdf"
+URDF_REL = "src/robot.urdf"
+MODEL_REL = "src/model.py"
+_STATE_WORDS = ("open", "closed", "opened", "extended", "retracted", "raised", "lowered", "folded", "unfolded")
+_SNAKE = re.compile(r"^[a-z][a-z0-9]*(_[a-z0-9]+)*$")
+
+#: attribute chains that must not appear in model.py (harness owns these)
+FORBIDDEN_BPY_PREFIXES: tuple[tuple[str, str], ...] = (
+ ("bpy.ops.wm.", "file/session operators (open/save/quit/read_factory_settings) — the harness owns the session"),
+ ("bpy.ops.render.", "rendering — the harness renders"),
+ ("bpy.ops.export_scene.", "exporting — the harness exports meshes/<link>.glb"),
+ ("bpy.ops.export_mesh.", "exporting — the harness exports"),
+ ("bpy.ops.import_scene.", "importing external files — build geometry procedurally"),
+ ("bpy.ops.import_mesh.", "importing external files — build geometry procedurally"),
+)
+FORBIDDEN_MODULES: tuple[str, ...] = ("subprocess", "socket", "urllib", "requests", "http", "shutil", "ctypes", "multiprocessing")
+FORBIDDEN_CALLS: dict[str, str] = {
+ "os.system": "shell access", "os.remove": "file deletion", "os.unlink": "file deletion", "os.rmdir": "file deletion",
+ "sys.exit": "exits Blender before the export — just return/raise instead", "exit": "exits Blender", "quit": "exits Blender",
+ "input": "blocks headless Blender forever",
+}
+WARN_CALLS: dict[str, str] = {
+ "bpy.ops.object.camera_add": "cameras are ignored (and stripped) by the wrapper",
+ "bpy.ops.object.light_add": "lights are ignored (and stripped) by the wrapper",
+ "time.sleep": "pointless in a build script",
+}
+
+
+def _f(sev: Severity, msg: str, *, target: str | None = None, fix: str = "", **data) -> GateFinding:
+ return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=fix, data=data)
+
+
+def _floats(text: str | None) -> list[float] | None:
+ try:
+ return [float(v) for v in (text or "").split()]
+ except ValueError:
+ return None
+
+
+# ------------------------------------------------------------------ URDF
+def lint_urdf_text(text: str, *, label: str = URDF_REL) -> tuple[list[GateFinding], list[str]]:
+ """Lint URDF source. Returns (findings, link_names)."""
+ out: list[GateFinding] = []
+ try:
+ root = ET.fromstring(text)
+ except ET.ParseError as e:
+ line = getattr(e, "position", (None, None))[0]
+ out.append(_f(Severity.ERROR, f"{label} is not well-formed XML: {e}", target=label,
+ fix="Fix the XML (every <tag> closed, attributes quoted, one <robot> root element).", line=line))
+ return out, []
+ if root.tag != "robot":
+ out.append(_f(Severity.ERROR, f"root element must be <robot>, got <{root.tag}>", target=label,
+ fix='Wrap everything in <robot name="..."> ... </robot>.'))
+ return out, []
+ if not root.get("name"):
+ out.append(_f(Severity.WARN, "<robot> has no name attribute", target=label, fix='<robot name="my_object">'))
+
+ links = root.findall("link")
+ joints = root.findall("joint")
+ link_names: list[str] = []
+ for el in links:
+ name = el.get("name", "")
+ if not name:
+ out.append(_f(Severity.ERROR, "<link> without name", target=label, fix='<link name="base">'))
+ continue
+ if name in link_names:
+ out.append(_f(Severity.ERROR, f"duplicate link name '{name}'", target=name, fix="Link names must be unique."))
+ link_names.append(name)
+ _lint_link(el, name, out)
+ if not link_names:
+ out.append(_f(Severity.ERROR, "URDF has no <link> elements", target=label, fix="Add one <link> per mesh object in model.py."))
+ return out, []
+
+ joint_names: list[str] = []
+ parent_of: dict[str, str] = {}
+ for el in joints:
+ jname = el.get("name", "")
+ if not jname:
+ out.append(_f(Severity.ERROR, "<joint> without name", target=label, fix='<joint name="hinge" type="revolute">'))
+ continue
+ if jname in joint_names:
+ out.append(_f(Severity.ERROR, f"duplicate joint name '{jname}'", target=jname, fix="Joint names must be unique."))
+ joint_names.append(jname)
+ _lint_joint(el, jname, link_names, parent_of, out)
+
+ # tree structure
+ children = set(parent_of)
+ roots = [n for n in link_names if n not in children]
+ if len(roots) != 1:
+ out.append(_f(Severity.ERROR, f"expected exactly one root link (no parent joint), found {roots}", target=label,
+ fix="Every link except the root must be the <child> of exactly one joint; connect extra roots with a fixed joint."))
+ else:
+ for link in link_names:
+ seen, cur = set(), link
+ while cur in parent_of and cur not in seen:
+ seen.add(cur)
+ cur = parent_of[cur]
+ if cur != roots[0]:
+ out.append(_f(Severity.ERROR, f"link '{link}' does not reach the root '{roots[0]}' (cycle or detached)", target=link,
+ fix="Joints must form a single tree rooted at the base link."))
+ return out, link_names
+
+
+def _lint_link(el: ET.Element, name: str, out: list[GateFinding]) -> None:
+ if not _SNAKE.match(name):
+ out.append(_f(Severity.WARN, f"link name '{name}' is not snake_case", target=name,
+ fix=f"Rename to '{to_snake(name)}' in BOTH robot.urdf and model.py (object names are case-sensitive)."))
+ if any(w in to_snake(name).split("_") for w in _STATE_WORDS):
+ out.append(_f(Severity.WARN, f"link name '{name}' contains a state word — links are parts, states come from joints", target=name,
+ fix="Name the part (door, drawer, lid), not its state."))
+ visuals = el.findall("visual")
+ expected = f"meshes/{name}.glb"
+ if len(visuals) != 1:
+ out.append(_f(Severity.ERROR, f"link '{name}' has {len(visuals)} <visual> elements; exactly one is required", target=name,
+ fix=f'<visual><origin xyz="..." rpy="0 0 0"/><geometry><mesh filename="{expected}"/></geometry></visual>'))
+ for vis in visuals:
+ geom = vis.find("geometry")
+ mesh = geom.find("mesh") if geom is not None else None
+ if geom is None or mesh is None:
+ kinds = [c.tag for c in geom] if geom is not None else []
+ out.append(_f(Severity.ERROR, f"link '{name}': visual geometry must be a <mesh> (found {kinds or 'nothing'})", target=name,
+ fix=f'Build the shape in model.py and reference <mesh filename="{expected}"/>.'))
+ else:
+ fn = mesh.get("filename", "")
+ if fn != expected:
+ out.append(_f(Severity.ERROR, f"link '{name}': mesh filename '{fn}' must be '{expected}'", target=name,
+ fix=f'<mesh filename="{expected}"/>'))
+ sc = _floats(mesh.get("scale")) if mesh.get("scale") else None
+ if sc is not None and any(abs(s - 1) > 1e-9 for s in sc):
+ out.append(_f(Severity.WARN, f"link '{name}': mesh scale {sc} — model in meters in model.py instead", target=name,
+ fix="Drop the scale attribute and size the geometry in model.py."))
+ _lint_origin(vis.find("origin"), f"link '{name}' visual", name, out)
+ col = el.find("collision")
+ if col is None:
+ out.append(_f(Severity.WARN, f"link '{name}' has no <collision> twin of its visual", target=name,
+ fix="Copy the <visual> block as <collision> (same origin + geometry)."))
+ else:
+ if _sig(col.find("geometry")) != _sig(geom) or _origin_sig(col.find("origin")) != _origin_sig(vis.find("origin")):
+ out.append(_f(Severity.WARN, f"link '{name}': <collision> differs from <visual>; the harness collides the VISUAL mesh", target=name,
+ fix="Make <collision> an identical copy of <visual>."))
+
+
+def _sig(el: ET.Element | None) -> str:
+ return "" if el is None else ET.tostring(el).decode().strip()
+
+
+def _origin_sig(o: ET.Element | None) -> tuple[tuple[float, ...], tuple[float, ...]]:
+ if o is None:
+ return ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0))
+ return (tuple(_floats(o.get("xyz")) or (0.0, 0.0, 0.0)), tuple(_floats(o.get("rpy")) or (0.0, 0.0, 0.0)))
+
+
+def _lint_origin(o: ET.Element | None, what: str, target: str, out: list[GateFinding]) -> None:
+ if o is None:
+ return
+ for attr in ("xyz", "rpy"):
+ if o.get(attr) is None:
+ continue
+ vals = _floats(o.get(attr))
+ if vals is None or len(vals) != 3 or any(not math.isfinite(v) for v in vals):
+ out.append(_f(Severity.ERROR, f"{what}: origin {attr}='{o.get(attr)}' must be 3 finite numbers", target=target,
+ fix=f'<origin {attr}="0 0 0"/>'))
+
+
+def _lint_joint(el: ET.Element, jname: str, link_names: list[str], parent_of: dict[str, str], out: list[GateFinding]) -> None:
+ jtype = el.get("type", "")
+ if jtype not in JOINT_TYPES:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': type '{jtype}' must be one of {JOINT_TYPES}", target=jname,
+ fix='type="revolute" (hinge) | "prismatic" (slide) | "continuous" (wheel) | "fixed"'))
+ p = el.find("parent")
+ c = el.find("child")
+ parent = p.get("link", "") if p is not None else ""
+ child = c.get("link", "") if c is not None else ""
+ for role, lk in (("parent", parent), ("child", child)):
+ if not lk:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': missing <{role} link=...>", target=jname, fix=f'<{role} link="base"/>'))
+ elif lk not in link_names:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': {role} link '{lk}' does not exist (links: {link_names})", target=jname,
+ fix="Reference an existing <link name>."))
+ if parent and child and parent == child:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': parent == child", target=jname, fix="A joint connects two different links."))
+ if child:
+ if child in parent_of:
+ out.append(_f(Severity.ERROR, f"link '{child}' is the child of two joints ('{jname}' and another)", target=jname,
+ fix="Each link has exactly one parent joint (tree)."))
+ parent_of[child] = parent
+ _lint_origin(el.find("origin"), f"joint '{jname}'", jname, out)
+ o = el.find("origin")
+ if o is not None and o.get("rpy") and any(abs(v) > 1e-9 for v in (_floats(o.get("rpy")) or [])):
+ out.append(_f(Severity.INFO, f"joint '{jname}' uses a rotated origin (rpy); allowed, but point the <axis> instead where possible", target=jname))
+ ax = el.find("axis")
+ if jtype in MOVABLE_TYPES:
+ if ax is None or ax.get("xyz") is None:
+ out.append(_f(Severity.WARN, f"joint '{jname}': no <axis>; URDF defaults to '1 0 0'", target=jname, fix='<axis xyz="0 0 1"/>'))
+ else:
+ vals = _floats(ax.get("xyz"))
+ if vals is None or len(vals) != 3:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': axis '{ax.get('xyz')}' must be 3 numbers", target=jname, fix='<axis xyz="0 0 1"/>'))
+ else:
+ n = math.sqrt(sum(v * v for v in vals))
+ if n < 1e-9:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': zero axis", target=jname, fix='<axis xyz="0 0 1"/>'))
+ elif abs(n - 1) > 1e-3:
+ unit = " ".join(f"{v / n:.6g}" for v in vals)
+ out.append(_f(Severity.WARN, f"joint '{jname}': axis not unit length (|a|={n:.4g}); auto-normalised", target=jname,
+ fix=f'<axis xyz="{unit}"/>'))
+ lim = el.find("limit")
+ if jtype in ("revolute", "prismatic"):
+ lo = _floats(lim.get("lower")) if lim is not None and lim.get("lower") is not None else None
+ hi = _floats(lim.get("upper")) if lim is not None and lim.get("upper") is not None else None
+ if lim is None or not lo or not hi:
+ unit = "rad" if jtype == "revolute" else "m"
+ out.append(_f(Severity.ERROR, f"joint '{jname}': {jtype} joints need <limit lower upper effort velocity> ({unit})", target=jname,
+ fix='<limit lower="0" upper="1.57" effort="10" velocity="1"/>'))
+ else:
+ if hi[0] < lo[0]:
+ out.append(_f(Severity.ERROR, f"joint '{jname}': upper {hi[0]} < lower {lo[0]}", target=jname,
+ fix="Swap lower/upper; if the motion should go the other way, negate the <axis> instead."))
+ if abs(hi[0] - lo[0]) < 1e-9:
+ out.append(_f(Severity.WARN, f"joint '{jname}': lower == upper (joint cannot move)", target=jname,
+ fix="Give the joint a range, or make it type=fixed."))
+ if jtype == "revolute" and hi[0] - lo[0] > 2 * math.pi + 1e-6:
+ out.append(_f(Severity.WARN, f"joint '{jname}': revolute range > 2π — use type=continuous", target=jname))
+ if lim is not None and (lim.get("effort") is None or lim.get("velocity") is None):
+ out.append(_f(Severity.WARN, f"joint '{jname}': <limit> should carry effort and velocity", target=jname,
+ fix='effort="10" velocity="1"'))
+ elif jtype == "continuous" and lim is not None and (lim.get("lower") is not None or lim.get("upper") is not None):
+ out.append(_f(Severity.WARN, f"joint '{jname}': continuous joints have no lower/upper (ignored)", target=jname,
+ fix='<limit effort="10" velocity="1"/> or use type=revolute'))
+ if el.find("mimic") is not None:
+ out.append(_f(Severity.WARN, f"joint '{jname}': <mimic> is ignored by the harness (sweeps move it independently)", target=jname))
+
+
+# ------------------------------------------------------------------ model.py
+class _Visitor(ast.NodeVisitor):
+ def __init__(self) -> None:
+ self.findings: list[GateFinding] = []
+ self.has_bpy = False
+ self.strings: set[str] = set()
+
+ def _chain(self, node: ast.AST) -> str:
+ parts: list[str] = []
+ while isinstance(node, ast.Attribute):
+ parts.append(node.attr)
+ node = node.value
+ if isinstance(node, ast.Name):
+ parts.append(node.id)
+ return ".".join(reversed(parts))
+
+ def visit_Import(self, node: ast.Import) -> None:
+ for a in node.names:
+ top = a.name.split(".")[0]
+ if top == "bpy":
+ self.has_bpy = True
+ if top in FORBIDDEN_MODULES:
+ self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: import of '{a.name}' is not allowed in model.py",
+ target=MODEL_REL, fix="Build geometry with bpy/bmesh/mathutils/math only.", line=node.lineno))
+ self.generic_visit(node)
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ top = (node.module or "").split(".")[0]
+ if top == "bpy":
+ self.has_bpy = True
+ if top in FORBIDDEN_MODULES:
+ self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: import from '{node.module}' is not allowed in model.py",
+ target=MODEL_REL, fix="Build geometry with bpy/bmesh/mathutils/math only.", line=node.lineno))
+ if top == "codeverse":
+ self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: model.py must not import the harness", target=MODEL_REL,
+ fix="Raw bpy only.", line=node.lineno))
+ self.generic_visit(node)
+
+ def visit_Call(self, node: ast.Call) -> None:
+ chain = self._chain(node.func)
+ for prefix, why in FORBIDDEN_BPY_PREFIXES:
+ if chain.startswith(prefix):
+ self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: {chain}() is forbidden: {why}", target=MODEL_REL,
+ fix="Delete this call; the harness owns sessions/exports/renders.", line=node.lineno))
+ if chain in FORBIDDEN_CALLS:
+ self.findings.append(_f(Severity.ERROR, f"line {node.lineno}: {chain}() is forbidden: {FORBIDDEN_CALLS[chain]}",
+ target=MODEL_REL, fix="Remove the call.", line=node.lineno))
+ if chain in WARN_CALLS:
+ self.findings.append(_f(Severity.WARN, f"line {node.lineno}: {chain}(): {WARN_CALLS[chain]}", target=MODEL_REL, line=node.lineno))
+ if chain == "open" and len(node.args) > 1 and isinstance(node.args[1], ast.Constant) and "w" in str(node.args[1].value):
+ self.findings.append(_f(Severity.WARN, f"line {node.lineno}: writing files from model.py is ignored by the harness",
+ target=MODEL_REL, line=node.lineno))
+ self.generic_visit(node)
+
+ def visit_While(self, node: ast.While) -> None:
+ if isinstance(node.test, ast.Constant) and node.test.value is True:
+ self.findings.append(_f(Severity.WARN, f"line {node.lineno}: 'while True' in a build script risks a hang", target=MODEL_REL, line=node.lineno))
+ self.generic_visit(node)
+
+ def visit_Constant(self, node: ast.Constant) -> None:
+ if isinstance(node.value, str):
+ self.strings.add(node.value)
+
+
+def lint_model_text(text: str, link_names: list[str], *, label: str = MODEL_REL) -> list[GateFinding]:
+ """AST lint of model.py: forbidden APIs + every URDF link name appears as a string literal."""
+ try:
+ tree = ast.parse(text, filename=label)
+ except SyntaxError as e:
+ return [_f(Severity.ERROR, f"{label}:{e.lineno}: SyntaxError: {e.msg}", target=label, fix=str(e.text or "").strip(), line=e.lineno)]
+ v = _Visitor()
+ v.visit(tree)
+ out = v.findings
+ if not v.has_bpy:
+ out.append(_f(Severity.ERROR, f"{label} never imports bpy", target=label, fix="import bpy"))
+ for link in link_names:
+ if link not in v.strings and not any(link in s for s in v.strings):
+ out.append(_f(Severity.WARN, f"link '{link}' never appears as a string in {label} — the wrapper looks for an object named exactly '{link}'",
+ target=link, fix=f'obj.name = "{link}"'))
+ return out
+
+
+# ------------------------------------------------------------------ workspace
+def lint_workspace(ws: Workspace) -> GateReport:
+ t0 = time.time()
+ findings: list[GateFinding] = []
+ urdf_p = ws.root / URDF_REL
+ model_p = ws.root / MODEL_REL
+ link_names: list[str] = []
+ if not urdf_p.is_file():
+ findings.append(_f(Severity.ERROR, f"missing {URDF_REL}", target=URDF_REL, fix="Write src/robot.urdf (see the contract)."))
+ else:
+ f, link_names = lint_urdf_text(urdf_p.read_text())
+ findings.extend(f)
+ if not model_p.is_file():
+ findings.append(_f(Severity.ERROR, f"missing {MODEL_REL}", target=MODEL_REL, fix="Write src/model.py (pure bpy, one object per link)."))
+ else:
+ findings.extend(lint_model_text(model_p.read_text(), link_names))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
+
+
+def lint_files(urdf_path: Path, model_path: Path | None = None) -> GateReport:
+ """Lint arbitrary file paths (CLI / tests)."""
+ t0 = time.time()
+ findings, links = lint_urdf_text(Path(urdf_path).read_text(), label=str(urdf_path))
+ if model_path is not None:
+ findings.extend(lint_model_text(Path(model_path).read_text(), links, label=str(model_path)))
+ return GateReport(gate=GATE, passed=not any(f.severity == Severity.ERROR for f in findings), findings=findings,
+ duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse/languages/urdf/runtime.py b/harness/codeverse/languages/urdf/runtime.py
new file mode 100644
index 00000000..ad9471bc
--- /dev/null
+++ b/harness/codeverse/languages/urdf/runtime.py
@@ -0,0 +1,190 @@
+"""``urdf_blender`` LanguageRuntime: bpy link meshes + hand-written URDF.
+
+build(ws):
+ lint URDF/model.py → Blender wrapper (exec model.py, export meshes/<link>.glb,
+ census) → load_urdf → FK consistency (authored bbox == FK bbox at q=0) →
+ pose sweep (overlaps / floating) → artifacts/object.glb (hierarchical, Y-up)
+ + artifacts/robot.urdf + artifacts/meshes/ + artifacts/articulation.json.
+
+``ok`` iff the script ran, the URDF is valid, FK is consistent and nothing
+interpenetrates by more than ``REST_PENETRATION_MAX_M`` at rest. Overlaps in
+moved poses and floating links are reported in ``census["articulation"]`` for
+the gate layer (``sweep_findings``).
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import shutil
+import signal
+import subprocess
+import time
+from pathlib import Path
+from typing import Any
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import BuildResult, GateReport
+from codeverse.contracts.common import Language
+from codeverse.contracts.plan import ArticulatedPlan, Plan
+from codeverse.languages.urdf.consistency import check_fk_consistency
+from codeverse.languages.urdf.lint import lint_workspace
+from codeverse.languages.urdf.skeleton import write_skeleton
+from codeverse.spatial.joints import (
+ UrdfError,
+ load_urdf,
+ pose_samples,
+ sweep_collisions,
+ sweep_findings,
+ urdf_to_glb,
+)
+from codeverse.workspace import Workspace
+
+WRAPPER = Path(__file__).resolve().parent / "wrappers" / "run_bpy_links.py"
+CONTRACT_MD = Path(__file__).resolve().parent / "CONTRACT.md"
+REST_PENETRATION_MAX_M = 0.005
+FK_TOL_M = 0.001
+
+
+def _tail(s: str, n: int = 3000) -> str:
+ return s[-n:] if s else ""
+
+
+class UrdfBlenderRuntime:
+ language = Language.URDF_BLENDER
+ entry_globs = ("src/model.py", "src/robot.urdf")
+
+ # ------------------------------------------------------------ protocol
+ def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
+ if not isinstance(plan, ArticulatedPlan):
+ raise TypeError(f"urdf_blender skeleton needs an ArticulatedPlan, got {type(plan).__name__}")
+ return write_skeleton(ws, plan)
+
+ def lint(self, ws: Workspace) -> GateReport:
+ return lint_workspace(ws)
+
+ def contract_doc(self) -> str:
+ try:
+ from codeverse.prompts import load_text
+
+ return load_text("urdf/contract.md")
+ except FileNotFoundError:
+ return CONTRACT_MD.read_text()
+
+ def cookbook_path(self) -> Path:
+ from codeverse.prompts import PROMPTS_DIR
+
+ return PROMPTS_DIR / "urdf" / "cookbook.md"
+
+ # ------------------------------------------------------------ build
+ def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
+ t0 = time.time()
+ settings = get_settings()
+ timeout_s = timeout_s or settings.limits.build_timeout_s
+ art = ws.artifacts
+ art.mkdir(parents=True, exist_ok=True)
+
+ def fail(error_type: str, message: str, *, file: str = "src/robot.urdf", line: int | None = None,
+ census: dict[str, Any] | None = None, **kw: Any) -> BuildResult:
+ return BuildResult(ok=False, language=self.language.value, error_type=error_type, error_message=message,
+ error_file=file, error_line=line, duration_ms=int((time.time() - t0) * 1000),
+ census=census or {}, **kw)
+
+ # 1. lint (cheap, no Blender)
+ lint = self.lint(ws)
+ census: dict[str, Any] = {"lint": [f.model_dump(mode="json") for f in lint.findings]}
+ if not lint.passed:
+ errs = lint.errors
+ msg = "\n".join(f"- {f.message}" + (f" → {f.fix_hint}" if f.fix_hint else "") for f in errs[:12])
+ return fail("LintError", f"{len(errs)} lint error(s):\n{msg}", file=str(errs[0].target or "src/robot.urdf"),
+ line=errs[0].data.get("line"), census=census)
+
+ # 2. Blender wrapper
+ blender = settings.resolve_blender()
+ if not blender:
+ return fail("BlenderNotFound", "no Blender binary (set C3V_BINARIES__BLENDER)", file="", census=census)
+ for stale in ("build.json", "census.json"):
+ (art / stale).unlink(missing_ok=True)
+ shutil.rmtree(art / "meshes", ignore_errors=True)
+ proc = _run_blender(blender, ws, art, timeout_s, settings.limits.bpy_rlimit_gb)
+ build_json = art / "build.json"
+ if proc["timed_out"]:
+ return fail("Timeout", f"Blender build exceeded {timeout_s}s (killed)", file="src/model.py", census=census,
+ stdout_tail=_tail(proc["stdout"]), stderr_tail=_tail(proc["stderr"]))
+ if not build_json.is_file():
+ return fail("WrapperCrash", f"wrapper produced no build.json (exit {proc['returncode']})", file="src/model.py",
+ census=census, stdout_tail=_tail(proc["stdout"]), stderr_tail=_tail(proc["stderr"]))
+ wb = json.loads(build_json.read_text())
+ wcensus = json.loads((art / "census.json").read_text()) if (art / "census.json").is_file() else {}
+ census.update({k: wcensus.get(k) for k in ("objects", "links", "unmatched_objects", "missing_links", "hints") if k in wcensus})
+ if not wb.get("ok"):
+ hints = "\n".join(f" hint: {h}" for h in (wcensus.get("hints") or {}).values())
+ return fail(wb.get("error_type") or "ScriptError", (wb.get("error_message") or "") + ("\n" + hints if hints else ""),
+ file=wb.get("error_file") or "src/model.py", line=wb.get("error_line"), census=census,
+ stdout_tail=_tail(wb.get("stdout_tail", "") or proc["stdout"]),
+ stderr_tail=_tail(wb.get("stderr_tail", "") or proc["stderr"]))
+
+ # 3. URDF copy + load
+ urdf_out = art / "robot.urdf"
+ shutil.copyfile(ws.root / "src" / "robot.urdf", urdf_out)
+ extra = {"urdf": str(urdf_out), "meshes_dir": str(art / "meshes")}
+ try:
+ robot = load_urdf(urdf_out, art / "meshes")
+ except UrdfError as e:
+ return fail("UrdfError", str(e), census=census, extra_paths=extra)
+
+ # 4. FK consistency
+ fk_findings = check_fk_consistency(robot, census.get("links") or {}, tol_m=FK_TOL_M)
+ census["fk_check"] = [f.model_dump(mode="json") for f in fk_findings]
+ if fk_findings:
+ msg = "\n".join(f"- {f.message}\n FIX: {f.fix_hint}" for f in fk_findings)
+ return fail("FkInconsistent", f"URDF frames do not reproduce the authored geometry:\n{msg}", census=census,
+ extra_paths=extra)
+
+ # 5. pose sweep
+ report = sweep_collisions(robot, pose_samples(robot, n_random=8, seed=0))
+ findings = sweep_findings(report, rest_max_m=REST_PENETRATION_MAX_M)
+ art_json = art / "articulation.json"
+ art_json.write_text(json.dumps({"report": report.model_dump(mode="json"),
+ "findings": [f.model_dump(mode="json") for f in findings]}, indent=1))
+ extra["articulation"] = str(art_json)
+ for name, n in report.summary.link_islands.items():
+ census.setdefault("links", {}).setdefault(name, {})["islands"] = n
+ census["articulation"] = {"summary": report.summary.model_dump(mode="json"),
+ "findings": [f.model_dump(mode="json") for f in findings],
+ "n_joints": len(robot.joints), "movable_joints": [j.name for j in robot.movable_joints()]}
+
+ # 6. canonical GLB at rest
+ glb = urdf_to_glb(robot, art / "object.glb", None)
+ extra["object_glb"] = str(glb)
+ res = BuildResult(ok=True, language=self.language.value, glb_path=str(glb), extra_paths=extra,
+ stdout_tail=_tail(wb.get("stdout_tail", "")), duration_ms=int((time.time() - t0) * 1000), census=census)
+ if report.summary.rest_max_penetration_m > REST_PENETRATION_MAX_M:
+ worst = [f for f in findings if f.data.get("pose") == {} and f.severity == "error"]
+ res.ok = False
+ res.error_type = "RestPenetration"
+ res.error_file = "src/model.py"
+ res.error_message = (f"links interpenetrate by {report.summary.rest_max_penetration_m*1000:.1f} mm at the rest pose "
+ f"(max {REST_PENETRATION_MAX_M*1000:.0f} mm):\n" +
+ "\n".join(f"- {f.message}\n FIX: {f.fix_hint}" for f in worst[:8]))
+ return res
+
+
+def _run_blender(blender: str, ws: Workspace, art: Path, timeout_s: int, rlimit_gb: int) -> dict[str, Any]:
+ cmd = [blender, "-b", "--factory-startup", "--python", str(WRAPPER), "--",
+ "--script", str(ws.root / "src" / "model.py"), "--urdf", str(ws.root / "src" / "robot.urdf"),
+ "--out", str(art), "--rlimit-gb", str(rlimit_gb)]
+ env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "HOME": os.environ.get("HOME", str(ws.root)),
+ "PYTHONDONTWRITEBYTECODE": "1", "BLENDER_USER_CONFIG": str(art / ".blender_config")}
+ p = subprocess.Popen(cmd, cwd=ws.root, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
+ start_new_session=True)
+ timed_out = False
+ try:
+ out, err = p.communicate(timeout=timeout_s)
+ except subprocess.TimeoutExpired:
+ timed_out = True
+ with contextlib.suppress(ProcessLookupError):
+ os.killpg(p.pid, signal.SIGKILL)
+ out, err = p.communicate()
+ return {"returncode": p.returncode, "stdout": out or "", "stderr": err or "", "timed_out": timed_out}
diff --git a/harness/codeverse/languages/urdf/skeleton.py b/harness/codeverse/languages/urdf/skeleton.py
new file mode 100644
index 00000000..e15e5bcb
--- /dev/null
+++ b/harness/codeverse/languages/urdf/skeleton.py
@@ -0,0 +1,206 @@
+"""Starter files for ``urdf_blender`` from an :class:`ArticulatedPlan`.
+
+Writes a RUNNABLE ``src/model.py`` (one placeholder box per link at the plan
+bbox, named exactly like the link) and a CORRECT ``src/robot.urdf`` whose joint
+origins / visual origins follow the enforced convention (see CONTRACT.md):
+
+* root link frame = world origin;
+* every other link frame = its parent joint's pivot (world), no rotation;
+* joint ``<origin xyz>`` = pivot_world(child) − link_frame_world(parent);
+* visual ``<origin xyz>`` = −link_frame_world(link) (meshes are exported in
+ world coordinates at the authored rest pose);
+* URDF ``q = 0`` is the authored rest pose, so plan limits are shifted by ``rest``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from pathlib import Path
+
+from codeverse.contracts.plan import ArticulatedPlan, JointPlan, PartPlan
+from codeverse.conventions import to_snake
+from codeverse.workspace import Workspace
+
+DEFAULT_EFFORT = 10.0
+DEFAULT_VELOCITY = 1.0
+
+
+@dataclass(frozen=True)
+class LinkFrame:
+ """World placement of one link frame at rest + its plan bbox."""
+
+ name: str
+ frame_xyz: tuple[float, float, float]
+ bbox_center: tuple[float, float, float]
+ bbox_extents: tuple[float, float, float]
+ parent_joint: str | None
+
+
+@dataclass(frozen=True)
+class JointRow:
+ name: str
+ type: str
+ parent: str
+ child: str
+ origin_xyz: tuple[float, float, float]
+ axis: tuple[float, float, float]
+ lower: float | None
+ upper: float | None
+
+
+@dataclass
+class UrdfFrames:
+ robot_name: str
+ root: str
+ links: dict[str, LinkFrame]
+ joints: list[JointRow]
+
+
+def _fmt(v: float) -> str:
+ s = f"{v:.6f}".rstrip("0").rstrip(".")
+ return "0" if s in ("", "-0") else s
+
+
+def _vec(v: tuple[float, float, float]) -> str:
+ return " ".join(_fmt(x) for x in v)
+
+
+def _expand_parts(plan: ArticulatedPlan) -> list[tuple[str, PartPlan, tuple[float, float, float]]]:
+ """(link_name, part, bbox_center) — parts with ``instances > 1`` become ``<name>_1..n``
+ spread along +x so the baseline has no overlaps (the agent repositions them)."""
+ out = []
+ for p in plan.parts:
+ base = to_snake(p.name)
+ if p.instances <= 1:
+ out.append((base, p, tuple(p.bbox.center)))
+ continue
+ cx, cy, cz = p.bbox.center
+ step = p.bbox.extents[0] * 1.5
+ for i in range(p.instances):
+ out.append((f"{base}_{i + 1}", p, (cx + i * step, cy, cz)))
+ return out
+
+
+def compute_urdf_frames(plan: ArticulatedPlan) -> UrdfFrames:
+ """Pure function: plan → link frames + joint rows in the enforced convention."""
+ parts = _expand_parts(plan)
+ base_names = {to_snake(p.name) for p in plan.parts}
+ instance_links = {n for n, p, _ in parts if p.instances > 1}
+ root = to_snake(plan.root_link)
+ links: dict[str, LinkFrame] = {}
+ pivot_of: dict[str, tuple[float, float, float]] = {}
+ parent_of: dict[str, str] = {}
+ joints: list[JointRow] = []
+
+ offsets = {n: tuple(c - o for c, o in zip(center, p.bbox.center, strict=True)) for n, p, center in parts}
+
+ def add_joint(j: JointPlan, child: str, parent: str, suffix: str = "") -> None:
+ pivot_of[child] = tuple(float(v) + o for v, o in zip(j.pivot, offsets[child], strict=True))
+ parent_of[child] = parent
+ lower = upper = None
+ if j.type in ("revolute", "prismatic"):
+ lower, upper = j.lower - j.rest, j.upper - j.rest
+ joints.append(JointRow(name=to_snake(j.name) + suffix, type=j.type, parent=parent, child=child,
+ origin_xyz=(0.0, 0.0, 0.0), axis=tuple(float(v) for v in j.axis), lower=lower, upper=upper))
+
+ for j in plan.joints:
+ parent, child = to_snake(j.parent), to_snake(j.child)
+ if parent in base_names and parent not in {n for n, _, _ in parts}:
+ parent = f"{parent}_1" # joint to an instanced parent → first instance
+ children = [n for n, p, _ in parts if n == child or (n in instance_links and n.rsplit("_", 1)[0] == child)]
+ for k, c in enumerate(children):
+ add_joint(j, c, parent, "" if len(children) == 1 else f"_{k + 1}")
+
+ # link frames: root at origin, others at their pivot
+ for name, p, center in parts:
+ frame = (0.0, 0.0, 0.0) if name == root else pivot_of.get(name, (0.0, 0.0, 0.0))
+ pj = next((jr.name for jr in joints if jr.child == name), None)
+ links[name] = LinkFrame(name=name, frame_xyz=frame, bbox_center=center,
+ bbox_extents=tuple(float(v) for v in p.bbox.extents), parent_joint=pj)
+ # joint origins relative to the parent link frame
+ fixed: list[JointRow] = []
+ for jr in joints:
+ pf = links[jr.parent].frame_xyz
+ cf = links[jr.child].frame_xyz
+ fixed.append(JointRow(name=jr.name, type=jr.type, parent=jr.parent, child=jr.child,
+ origin_xyz=tuple(c - p for c, p in zip(cf, pf, strict=True)), axis=jr.axis,
+ lower=jr.lower, upper=jr.upper))
+ return UrdfFrames(robot_name=to_snake(plan.object_name), root=root, links=links, joints=fixed)
+
+
+# ------------------------------------------------------------------ text renderers
+def render_urdf(frames: UrdfFrames) -> str:
+ lines = ['<?xml version="1.0"?>', f'<robot name="{frames.robot_name}">']
+ lines.append(" <!-- link frames: root at the world origin; every other link frame sits at its joint pivot (world, rest pose). -->")
+ lines.append(" <!-- visual/collision origin = -(link frame world) because meshes/<link>.glb hold WORLD coordinates at rest. -->")
+ for name, lf in frames.links.items():
+ vis = tuple(-v for v in lf.frame_xyz)
+ lines.append(f' <link name="{name}"> <!-- frame at world {_vec(lf.frame_xyz)} -->')
+ for tag in ("visual", "collision"):
+ lines.append(f' <{tag}><origin xyz="{_vec(vis)}" rpy="0 0 0"/><geometry><mesh filename="meshes/{name}.glb"/></geometry></{tag}>')
+ lines.append(" </link>")
+ for jr in frames.joints:
+ lines.append(f' <joint name="{jr.name}" type="{jr.type}">')
+ lines.append(f' <parent link="{jr.parent}"/>')
+ lines.append(f' <child link="{jr.child}"/>')
+ lines.append(f' <origin xyz="{_vec(jr.origin_xyz)}" rpy="0 0 0"/> <!-- pivot_world(child) - frame_world(parent) -->')
+ if jr.type != "fixed":
+ lines.append(f' <axis xyz="{_vec(jr.axis)}"/>')
+ lim = f'effort="{_fmt(DEFAULT_EFFORT)}" velocity="{_fmt(DEFAULT_VELOCITY)}"'
+ if jr.lower is not None and jr.upper is not None:
+ lim = f'lower="{_fmt(jr.lower)}" upper="{_fmt(jr.upper)}" ' + lim
+ lines.append(f" <limit {lim}/>")
+ lines.append(" </joint>")
+ lines.append("</robot>")
+ return "\n".join(lines) + "\n"
+
+
+def render_model_py(plan: ArticulatedPlan, frames: UrdfFrames) -> str:
+ parts_by_link = {n: p for n, p, _ in _expand_parts(plan)}
+ head = f'''"""{plan.object_name} — link meshes for robot.urdf (pure bpy, Z-up, -Y front, meters).
+
+CONTRACT: build ONE mesh object per URDF link, named EXACTLY like the link, placed
+at its REST-POSE WORLD position. Extra helper objects must be parented under a
+link object (they are joined into it). No cameras / lights / render / export calls.
+Replace every placeholder box below with real, detailed geometry; keep the names.
+"""
+import bpy
+import bmesh # noqa: F401 (handy for detail)
+import math # noqa: F401
+from mathutils import Vector # noqa: F401
+
+
+def box(name, center, size):
+ """Axis-aligned box helper: center/size in world meters; returns the object."""
+ bpy.ops.mesh.primitive_cube_add(size=1.0, location=center)
+ ob = bpy.context.active_object
+ ob.name = name
+ ob.scale = size
+ bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+ return ob
+
+
+'''
+ body = []
+ for name, lf in frames.links.items():
+ p = parts_by_link[name]
+ role = (p.role or "").replace("\n", " ")
+ desc = (p.description or "").replace("\n", " ")
+ body.append(f"# link '{name}': {role}\n# {desc}")
+ if lf.parent_joint:
+ body.append(f"# joint '{lf.parent_joint}' pivot (world) = {lf.frame_xyz}")
+ body.append(f"{name} = box({name!r}, center={tuple(round(v, 4) for v in lf.bbox_center)}, "
+ f"size={tuple(round(v, 4) for v in lf.bbox_extents)})\n")
+ tail = f"\n# Sanity: every link object exists\nfor _n in {list(frames.links)!r}:\n assert _n in bpy.data.objects, _n\n"
+ return head + "\n".join(body) + tail
+
+
+def write_skeleton(ws: Workspace, plan: ArticulatedPlan) -> list[Path]:
+ """Write src/model.py + src/robot.urdf; returns the written paths."""
+ frames = compute_urdf_frames(plan)
+ ws.src.mkdir(parents=True, exist_ok=True)
+ model = ws.src / "model.py"
+ urdf = ws.src / "robot.urdf"
+ model.write_text(render_model_py(plan, frames))
+ urdf.write_text(render_urdf(frames))
+ return [model, urdf]
diff --git a/harness/codeverse/languages/urdf/wrappers/render_glb_bpy.py b/harness/codeverse/languages/urdf/wrappers/render_glb_bpy.py
new file mode 100644
index 00000000..93ba9e22
--- /dev/null
+++ b/harness/codeverse/languages/urdf/wrappers/render_glb_bpy.py
@@ -0,0 +1,87 @@
+"""Headless-Blender fallback renderer (Workbench, studio light) for a GLB.
+
+Usage (run BY THE HARNESS, never by agent code)::
+
+ blender -b --factory-startup --python render_glb_bpy.py -- spec.json
+
+``spec.json``: ``{"glb", "out_dir", "width", "height", "views":[{"name","az","el"}]}``.
+Azimuth 0 = front (camera on -Y looking +Y in Blender's Z-up world), CCW from
+above; elevation in degrees above the horizon. Writes ``out_dir/view_<name>.png``.
+"""
+
+import json
+import math
+import sys
+from pathlib import Path
+
+import bpy
+from mathutils import Vector
+
+
+def _clear_scene() -> None:
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+
+
+def _scene_bounds():
+ lo = Vector((math.inf,) * 3)
+ hi = Vector((-math.inf,) * 3)
+ for ob in bpy.data.objects:
+ if ob.type != "MESH":
+ continue
+ for c in ob.bound_box:
+ w = ob.matrix_world @ Vector(c)
+ lo = Vector(min(a, b) for a, b in zip(lo, w, strict=True))
+ hi = Vector(max(a, b) for a, b in zip(hi, w, strict=True))
+ if not math.isfinite(lo.x):
+ lo, hi = Vector((-0.5,) * 3), Vector((0.5,) * 3)
+ return lo, hi
+
+
+def _look_at(cam, target: Vector) -> None:
+ direction = target - cam.location
+ cam.rotation_euler = direction.to_track_quat("-Z", "Y").to_euler()
+
+
+def main() -> None:
+ argv = sys.argv[sys.argv.index("--") + 1 :]
+ spec = json.loads(Path(argv[0]).read_text())
+ out_dir = Path(spec["out_dir"])
+ out_dir.mkdir(parents=True, exist_ok=True)
+ _clear_scene()
+ bpy.ops.import_scene.gltf(filepath=spec["glb"])
+ lo, hi = _scene_bounds()
+ center = (lo + hi) / 2
+ radius = max((hi - lo).length / 2, 1e-3)
+
+ scene = bpy.context.scene
+ scene.render.engine = "BLENDER_WORKBENCH"
+ shading = scene.display.shading
+ shading.light = "STUDIO"
+ shading.color_type = "MATERIAL"
+ shading.show_cavity = True
+ scene.display.render_aa = "8"
+ scene.render.resolution_x = int(spec.get("width", 512))
+ scene.render.resolution_y = int(spec.get("height", 512))
+ scene.render.film_transparent = False
+ scene.world = bpy.data.worlds.new("World")
+ scene.world.color = (0.92, 0.92, 0.92)
+
+ cam_data = bpy.data.cameras.new("Cam")
+ cam_data.lens_unit = "FOV"
+ cam_data.angle = math.radians(40.0)
+ cam = bpy.data.objects.new("Cam", cam_data)
+ scene.collection.objects.link(cam)
+ scene.camera = cam
+ dist = radius / math.sin(cam_data.angle / 2) * 1.15
+
+ for v in spec["views"]:
+ az, el = math.radians(v["az"]), math.radians(v["el"])
+ direction = Vector((math.sin(az) * math.cos(el), -math.cos(az) * math.cos(el), math.sin(el)))
+ cam.location = center + direction * dist
+ _look_at(cam, center)
+ scene.render.filepath = str(out_dir / f"view_{v['name']}.png")
+ bpy.ops.render.render(write_still=True)
+ print(f"[render] {scene.render.filepath}")
+
+
+main()
diff --git a/harness/codeverse/languages/urdf/wrappers/run_bpy_links.py b/harness/codeverse/languages/urdf/wrappers/run_bpy_links.py
new file mode 100644
index 00000000..cc013f77
--- /dev/null
+++ b/harness/codeverse/languages/urdf/wrappers/run_bpy_links.py
@@ -0,0 +1,250 @@
+"""Blender-side build wrapper for the ``urdf_blender`` language (run BY THE HARNESS).
+
+ blender -b --factory-startup --python run_bpy_links.py -- \
+ --script src/model.py --urdf src/robot.urdf --out artifacts/ [--rlimit-gb 12]
+
+1. empties the scene, executes ``model.py`` (errors mapped to its line numbers),
+2. takes a census of every mesh-like object (name, tris, WORLD bbox, Z-up),
+3. matches URDF link names to objects (an object named exactly ``<link>`` plus
+ anything parented under it forms that link's mesh),
+4. exports ``<out>/meshes/<link>.glb`` per link with the geometry baked in WORLD
+ coordinates at the authored rest pose, Z-up (``export_yup=False`` — the file
+ holds URDF-frame coordinates, NOT glTF Y-up), then
+5. writes ``<out>/census.json`` and ``<out>/build.json``.
+
+Self-contained on purpose: Blender's bundled python cannot import ``codeverse``.
+"""
+
+import argparse
+import io
+import json
+import math
+import re
+import sys
+import time
+import traceback
+import xml.etree.ElementTree as ET
+from contextlib import redirect_stdout
+from pathlib import Path
+
+import bpy
+from mathutils import Matrix, Vector
+
+MESH_LIKE = {"MESH", "CURVE", "FONT", "SURFACE", "META"}
+
+
+def _snake(name: str) -> str:
+ s = re.sub(r"[^0-9A-Za-z]+", "_", name.strip())
+ s = re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "_", s)
+ return re.sub(r"_+", "_", s).strip("_").lower()
+
+
+def _set_rlimit(gb: float) -> None:
+ try:
+ import resource
+
+ lim = int(gb * 1024**3)
+ resource.setrlimit(resource.RLIMIT_AS, (lim, lim))
+ except Exception as e: # pragma: no cover
+ print(f"[wrapper] rlimit not applied: {e}")
+
+
+def _urdf_links(urdf_path: Path) -> list[str]:
+ root = ET.parse(urdf_path).getroot()
+ return [el.get("name", "") for el in root.findall("link")]
+
+
+def _exec_script(script: Path) -> dict:
+ """Run the agent script; return an error dict (empty on success) + captured stdout."""
+ code = compile(script.read_text(), str(script), "exec")
+ g = {"__name__": "__main__", "__file__": str(script), "__builtins__": __builtins__}
+ buf = io.StringIO()
+ err: dict = {}
+ try:
+ with redirect_stdout(buf):
+ exec(code, g)
+ except BaseException as e: # noqa: BLE001 — we report everything, including SystemExit
+ tb = traceback.extract_tb(e.__traceback__)
+ line = None
+ for fr in tb:
+ if Path(fr.filename).resolve() == script.resolve():
+ line = fr.lineno
+ err = {
+ "error_type": type(e).__name__,
+ "error_message": str(e)[:2000],
+ "error_line": line,
+ "traceback": "".join(traceback.format_exception(type(e), e, e.__traceback__))[-3000:],
+ }
+ err["script_stdout"] = buf.getvalue()[-4000:]
+ return err
+
+
+def _world_bbox(ob) -> tuple[list, list]:
+ lo = [math.inf] * 3
+ hi = [-math.inf] * 3
+ for c in ob.bound_box:
+ w = ob.matrix_world @ Vector(c)
+ for i in range(3):
+ lo[i] = min(lo[i], w[i])
+ hi[i] = max(hi[i], w[i])
+ return lo, hi
+
+
+def _evaluated_world_mesh(ob, depsgraph):
+ """New bpy Mesh datablock of ``ob`` (modifiers applied) in WORLD coordinates."""
+ ev = ob.evaluated_get(depsgraph)
+ me = bpy.data.meshes.new_from_object(ev, preserve_all_data_layers=True, depsgraph=depsgraph)
+ me.transform(ob.matrix_world)
+ return me
+
+
+def _descendants(ob) -> list:
+ out = []
+ stack = list(ob.children)
+ while stack:
+ c = stack.pop()
+ out.append(c)
+ stack.extend(c.children)
+ return out
+
+
+def _census(depsgraph) -> list[dict]:
+ rows = []
+ for ob in bpy.data.objects:
+ if ob.type not in MESH_LIKE:
+ continue
+ ev = ob.evaluated_get(depsgraph)
+ me = ev.to_mesh()
+ try:
+ n_verts = len(me.vertices)
+ me.calc_loop_triangles()
+ n_tris = len(me.loop_triangles)
+ finally:
+ ev.to_mesh_clear()
+ lo, hi = _world_bbox(ob)
+ rows.append({
+ "name": ob.name, "type": ob.type, "verts": n_verts, "tris": n_tris,
+ "bbox_min": [round(v, 6) for v in lo], "bbox_max": [round(v, 6) for v in hi],
+ "parent": ob.parent.name if ob.parent else None,
+ "materials": [m.name for m in ob.material_slots if m.material] if hasattr(ob, "material_slots") else [],
+ })
+ return rows
+
+
+def _export_link(link: str, objects: list, out_glb: Path, depsgraph) -> dict:
+ """Join ``objects`` (world space) into one temp object and export it as GLB."""
+ meshes = [_evaluated_world_mesh(ob, depsgraph) for ob in objects]
+ temp_objs = []
+ for i, me in enumerate(meshes):
+ o = bpy.data.objects.new(f"__c3v_{link}_{i}", me)
+ bpy.context.scene.collection.objects.link(o)
+ temp_objs.append(o)
+ bpy.ops.object.select_all(action="DESELECT")
+ for o in temp_objs:
+ o.select_set(True)
+ bpy.context.view_layer.objects.active = temp_objs[0]
+ if len(temp_objs) > 1:
+ bpy.ops.object.join()
+ joined = bpy.context.view_layer.objects.active
+ joined.name = link
+ joined.matrix_world = Matrix.Identity(4)
+ bpy.ops.object.select_all(action="DESELECT")
+ joined.select_set(True)
+ joined.data.calc_loop_triangles()
+ lo, hi = _world_bbox(joined)
+ info = {
+ "mesh": f"meshes/{link}.glb", "tris": len(joined.data.loop_triangles), "verts": len(joined.data.vertices),
+ "bbox_min": [round(v, 6) for v in lo], "bbox_max": [round(v, 6) for v in hi],
+ "objects": [o.name for o in objects],
+ }
+ out_glb.parent.mkdir(parents=True, exist_ok=True)
+ bpy.ops.export_scene.gltf(
+ filepath=str(out_glb), export_format="GLB", use_selection=True, export_yup=False, export_apply=True,
+ export_materials="EXPORT", export_extras=False, export_animations=False, export_cameras=False,
+ export_lights=False, export_normals=True, export_texcoords=True, export_skins=False, export_morph=False,
+ )
+ bpy.data.objects.remove(joined, do_unlink=True)
+ return info
+
+
+def main() -> None:
+ argv = sys.argv[sys.argv.index("--") + 1 :] if "--" in sys.argv else []
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--script", required=True)
+ ap.add_argument("--urdf", required=True)
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--rlimit-gb", type=float, default=12.0)
+ args = ap.parse_args(argv)
+ t0 = time.time()
+ script, urdf, out = Path(args.script).resolve(), Path(args.urdf).resolve(), Path(args.out).resolve()
+ out.mkdir(parents=True, exist_ok=True)
+ _set_rlimit(args.rlimit_gb)
+ build: dict = {"ok": False, "language": "urdf_blender", "error_type": "", "error_message": "",
+ "error_file": "src/model.py", "error_line": None, "extra_paths": {}}
+ census: dict = {"objects": [], "links": {}, "unmatched_objects": [], "missing_links": [], "hints": {}}
+
+ def finish() -> None:
+ build["duration_ms"] = int((time.time() - t0) * 1000)
+ (out / "census.json").write_text(json.dumps(census, indent=1))
+ (out / "build.json").write_text(json.dumps(build, indent=1))
+ print(f"[wrapper] done ok={build['ok']} in {build['duration_ms']} ms")
+
+ try:
+ links = _urdf_links(urdf)
+ except ET.ParseError as e:
+ build.update(error_type="UrdfParseError", error_message=str(e), error_file="src/robot.urdf")
+ finish()
+ return
+
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ err = _exec_script(script)
+ build["stdout_tail"] = err.pop("script_stdout", "")
+ if err:
+ build.update(error_type=err["error_type"], error_message=err["error_message"], error_line=err["error_line"],
+ stderr_tail=err["traceback"])
+ finish()
+ return
+
+ depsgraph = bpy.context.evaluated_depsgraph_get()
+ census["objects"] = _census(depsgraph)
+ by_name = {ob.name: ob for ob in bpy.data.objects if ob.type in MESH_LIKE or ob.type == "EMPTY"}
+ claimed: set[str] = set()
+ for link in links:
+ ob = by_name.get(link)
+ if ob is None:
+ census["missing_links"].append(link)
+ near = [o.name for o in bpy.data.objects if o.type in MESH_LIKE and _snake(o.name) == _snake(link)]
+ if near:
+ census["hints"][link] = f"no object named exactly '{link}' — did you mean {near}? names are case-sensitive"
+ continue
+ group = [ob] + _descendants(ob)
+ group = [o for o in group if o.type in MESH_LIKE]
+ if not group:
+ census["missing_links"].append(link)
+ census["hints"][link] = f"object '{link}' has no mesh geometry (type {ob.type})"
+ continue
+ claimed.update(o.name for o in group)
+ try:
+ census["links"][link] = _export_link(link, group, out / "meshes" / f"{link}.glb", depsgraph)
+ except Exception as e: # export failure is a build failure
+ build.update(error_type="ExportError", error_message=f"link {link}: {e}", error_file="src/model.py")
+ finish()
+ return
+ census["unmatched_objects"] = [r["name"] for r in census["objects"] if r["name"] not in claimed]
+ if census["missing_links"]:
+ build.update(error_type="MissingLinkObjects", error_file="src/model.py",
+ error_message="URDF links without a mesh object in model.py: " + ", ".join(census["missing_links"]))
+ finish()
+ return
+ if census["unmatched_objects"]:
+ build.update(error_type="UnmatchedObjects", error_file="src/model.py",
+ error_message="mesh objects that are not URDF links (parent them under a link object or add a <link>): "
+ + ", ".join(census["unmatched_objects"]))
+ finish()
+ return
+ build["ok"] = True
+ build["extra_paths"] = {"meshes_dir": str(out / "meshes")}
+ finish()
+
+
+main()
diff --git a/harness/codeverse/models/__init__.py b/harness/codeverse/models/__init__.py
new file mode 100644
index 00000000..b950118b
--- /dev/null
+++ b/harness/codeverse/models/__init__.py
@@ -0,0 +1,6 @@
+"""ChatModel backends (API). Use ``get_chat_model("gemini:gemini-3.7-flash")``."""
+
+from codeverse.models.base import ChatModel
+from codeverse.models.registry import get_chat_model, parse_model_id
+
+__all__ = ["ChatModel", "get_chat_model", "parse_model_id"]
diff --git a/harness/codeverse/models/anthropic.py b/harness/codeverse/models/anthropic.py
new file mode 100644
index 00000000..06674b5d
--- /dev/null
+++ b/harness/codeverse/models/anthropic.py
@@ -0,0 +1,183 @@
+"""``AnthropicModel`` — Messages API backend (images, tools, JSON via ``submit``
+tool, adaptive / budgeted thinking, cache-aware usage + cost, typed errors).
+
+Retries (429 / 529 / 5xx / connection / timeouts) use ``with_retries``; the
+SDK's own retry is disabled so back-off is governed here.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import threading
+import time
+from collections.abc import Callable
+from typing import Any
+
+from codeverse.contracts.chat import ChatRequest, ChatResponse
+from codeverse.contracts.common import Usage
+from codeverse.models.anthropic_convert import THINKING_BLOCKS, build_kwargs, parse_content
+from codeverse.models.base import ModelError
+from codeverse.models.parts import Stopwatch
+from codeverse.models.pricing import cache_write_surcharge, estimate_cost
+from codeverse.models.retry import with_retries
+from codeverse.models.schema_utils import JsonParseError, parse_json_lenient
+
+log = logging.getLogger(__name__)
+
+
+def classify_exception(exc: BaseException) -> ModelError:
+ """Map anthropic SDK exceptions onto ``ModelError``."""
+ if isinstance(exc, ModelError):
+ return exc
+ import anthropic
+
+ if isinstance(exc, anthropic.APIStatusError):
+ status = int(getattr(exc, "status_code", 0) or 0)
+ retry = status in (408, 409, 429, 529) or status >= 500
+ return ModelError(
+ f"Anthropic API error {status}: {exc.message}", retryable=retry, status=status
+ )
+ if isinstance(exc, anthropic.APITimeoutError):
+ return ModelError(f"Anthropic request timed out: {exc}", retryable=True, status=408)
+ if isinstance(exc, anthropic.APIConnectionError):
+ return ModelError(f"Anthropic connection error: {exc}", retryable=True)
+ if isinstance(exc, anthropic.APIError):
+ return ModelError(f"Anthropic API error: {exc}", retryable=False)
+ return ModelError(f"Anthropic unexpected error: {type(exc).__name__}: {exc}", retryable=False)
+
+
+class AnthropicModel:
+ """ChatModel for ``anthropic:<model>``."""
+
+ provider = "anthropic"
+
+ def __init__(
+ self,
+ model: str,
+ *,
+ api_key: str | None = None,
+ timeout_s: float = 600.0,
+ max_attempts: int = 6,
+ base_delay: float = 2.0,
+ max_delay: float = 30.0,
+ json_mode: str = "tool",
+ sleep: Callable[[float], None] = time.sleep,
+ client: Any | None = None,
+ ) -> None:
+ self.model = model
+ self.timeout_s = timeout_s
+ self.max_attempts = max(1, max_attempts)
+ self.base_delay = base_delay
+ self.max_delay = max_delay
+ self.json_mode = json_mode
+ self._sleep = sleep
+ self._client = client
+ self._api_key = api_key
+ self._lock = threading.Lock()
+
+ @property
+ def id(self) -> str:
+ return f"anthropic:{self.model}"
+
+ def supports_vision(self) -> bool:
+ return True
+
+ # ---------------------------------------------------------------- client
+ def client(self) -> Any:
+ with self._lock:
+ if self._client is None:
+ import anthropic
+
+ from codeverse.config import get_settings
+
+ key = self._api_key or get_settings().anthropic_api_key
+ if not key:
+ raise ModelError("ANTHROPIC_API_KEY is not configured")
+ self._client = anthropic.Anthropic(
+ api_key=key, max_retries=0, timeout=self.timeout_s
+ )
+ return self._client
+
+ # -------------------------------------------------------------- generate
+ def generate(self, request: ChatRequest) -> ChatResponse:
+ kwargs = build_kwargs(request, self.model, json_mode=self.json_mode)
+
+ def attempt() -> ChatResponse:
+ try:
+ return self._once(kwargs, request)
+ except Exception as exc: # noqa: BLE001 - classified
+ raise classify_exception(exc) from exc
+
+ def on_retry(n: int, exc: BaseException, delay: float) -> None:
+ log.warning(
+ "anthropic %s attempt %d/%d failed (%s); retrying in %.1fs",
+ self.model,
+ n,
+ self.max_attempts,
+ exc,
+ delay,
+ )
+
+ return with_retries(
+ attempt,
+ is_retryable=lambda e: isinstance(e, ModelError) and e.retryable,
+ attempts=self.max_attempts,
+ base_delay=self.base_delay,
+ max_delay=self.max_delay,
+ on_retry=on_retry,
+ sleep=self._sleep,
+ )
+
+ def _once(self, kwargs: dict[str, Any], request: ChatRequest) -> ChatResponse:
+ client = self.client()
+ with Stopwatch() as sw:
+ msg = client.messages.create(model=self.model, **kwargs)
+ text, calls, submit, thinking_blocks = parse_content(msg.content)
+ stop = str(msg.stop_reason or "")
+ if calls and thinking_blocks:
+ THINKING_BLOCKS.put(calls[0].id, thinking_blocks)
+ usage = self._usage(msg.usage, sw.ms, len(calls))
+ if stop == "refusal":
+ raise ModelError(
+ f"Anthropic refused the request: {getattr(msg, 'stop_details', None)}",
+ retryable=False,
+ )
+ parsed: Any = None
+ if request.response_schema is not None:
+ if submit is not None:
+ parsed = submit
+ if not text:
+ text = json.dumps(parsed)
+ elif not calls:
+ try:
+ parsed = parse_json_lenient(text)
+ except JsonParseError as exc:
+ raise ModelError(
+ f"structured output missing (stop_reason={stop}): {exc}",
+ retryable=stop != "max_tokens",
+ ) from exc
+ if not text and not calls and parsed is None:
+ raise ModelError(f"Anthropic returned no content (stop_reason={stop})", retryable=True)
+ raw: dict[str, Any] = {"stop_reason": stop, "id": msg.id, "model": msg.model}
+ return ChatResponse(
+ text=text, parsed=parsed, tool_calls=calls, finish_reason=stop, usage=usage, raw=raw
+ )
+
+ def _usage(self, u: Any, latency_ms: int, n_calls: int) -> Usage:
+ cache_read = int(getattr(u, "cache_read_input_tokens", 0) or 0)
+ cache_write = int(getattr(u, "cache_creation_input_tokens", 0) or 0)
+ usage = Usage(
+ backend="anthropic",
+ model=self.model,
+ input_tokens=int(u.input_tokens or 0) + cache_read + cache_write,
+ output_tokens=int(u.output_tokens or 0),
+ cached_tokens=cache_read,
+ thoughts_tokens=0, # thinking is billed inside output_tokens
+ tool_calls=n_calls,
+ latency_ms=latency_ms,
+ )
+ usage.cost_usd = estimate_cost("anthropic", self.model, usage) + cache_write_surcharge(
+ "anthropic", self.model, cache_write
+ )
+ return usage
diff --git a/harness/codeverse/models/anthropic_convert.py b/harness/codeverse/models/anthropic_convert.py
new file mode 100644
index 00000000..96080370
--- /dev/null
+++ b/harness/codeverse/models/anthropic_convert.py
@@ -0,0 +1,242 @@
+"""ChatRequest ⇄ Anthropic Messages API dicts (messages, tools, thinking, parse).
+
+Model-family rules (Anthropic API, 2026-08):
+* 4.6+ family (opus-5, sonnet-5, fable-5, mythos, opus-4-6/7/8, sonnet-4-6):
+ ``thinking={"type":"adaptive"}`` + ``output_config.effort``; ``budget_tokens``
+ is rejected; sampling params are rejected on opus-5/sonnet-5/fable/4.7/4.8.
+* older models (haiku-4-5, sonnet-4-5, opus-4-1 …): ``thinking={"type":
+ "enabled","budget_tokens":N}`` (N < max_tokens), temperature must be left
+ at default while thinking is on.
+"""
+
+from __future__ import annotations
+
+import json
+import threading
+from collections import OrderedDict
+from typing import Any
+
+from codeverse.contracts.chat import (
+ ChatMessage,
+ ChatRequest,
+ ImagePart,
+ TextPart,
+ ToolCallPart,
+ ToolResultPart,
+ ToolSpec,
+)
+from codeverse.models.base import ModelError
+from codeverse.models.parts import image_b64
+from codeverse.models.schema_utils import to_anthropic_schema
+
+SUBMIT_TOOL = "submit"
+THINKING_BUDGET: dict[str, int] = {"off": 0, "low": 1024, "medium": 4096, "high": 16000}
+EFFORT: dict[str, str] = {"off": "low", "low": "low", "medium": "medium", "high": "high"}
+
+_ADAPTIVE_MARKERS = (
+ "opus-5",
+ "sonnet-5",
+ "fable-5",
+ "mythos",
+ "opus-4-6",
+ "opus-4-7",
+ "opus-4-8",
+ "sonnet-4-6",
+)
+_ALWAYS_THINKING = ("fable-5", "mythos")
+_NO_SAMPLING = ("opus-5", "sonnet-5", "fable-5", "mythos", "opus-4-7", "opus-4-8")
+
+
+def uses_adaptive_thinking(model: str) -> bool:
+ m = model.lower()
+ return any(tok in m for tok in _ADAPTIVE_MARKERS)
+
+
+def thinking_always_on(model: str) -> bool:
+ m = model.lower()
+ return any(tok in m for tok in _ALWAYS_THINKING)
+
+
+def sampling_allowed(model: str) -> bool:
+ m = model.lower()
+ return not any(tok in m for tok in _NO_SAMPLING)
+
+
+class _ThinkingCache:
+ """Assistant turns that contain tool calls must be replayed WITH their
+ thinking blocks on the next request. ``ToolCallPart`` cannot carry them,
+ so we remember the blocks under the first tool-call id (bounded LRU)."""
+
+ def __init__(self, capacity: int = 2048) -> None:
+ self._d: OrderedDict[str, list[dict[str, Any]]] = OrderedDict()
+ self._cap = capacity
+ self._lock = threading.Lock()
+
+ def put(self, call_id: str, blocks: list[dict[str, Any]]) -> None:
+ if not blocks:
+ return
+ with self._lock:
+ self._d[call_id] = blocks
+ self._d.move_to_end(call_id)
+ while len(self._d) > self._cap:
+ self._d.popitem(last=False)
+
+ def get(self, call_id: str) -> list[dict[str, Any]]:
+ with self._lock:
+ return list(self._d.get(call_id, []))
+
+
+THINKING_BLOCKS = _ThinkingCache()
+
+
+# ------------------------------------------------------------------ messages
+def _image_block(p: ImagePart) -> dict[str, Any]:
+ data, mime = image_b64(p)
+ return {"type": "image", "source": {"type": "base64", "media_type": mime, "data": data}}
+
+
+def to_messages(messages: list[ChatMessage]) -> list[dict[str, Any]]:
+ """ChatMessages → Anthropic ``messages``. ``tool`` role → user turn of
+ ``tool_result`` blocks; consecutive same-role turns are merged."""
+ out: list[dict[str, Any]] = []
+ for msg in messages:
+ role = "assistant" if msg.role == "assistant" else "user"
+ blocks: list[dict[str, Any]] = []
+ first_call_id: str | None = None
+ for p in msg.parts:
+ if isinstance(p, TextPart):
+ if p.text:
+ blocks.append({"type": "text", "text": p.text})
+ elif isinstance(p, ImagePart):
+ if p.label:
+ blocks.append({"type": "text", "text": f"[image: {p.label}]"})
+ blocks.append(_image_block(p))
+ elif isinstance(p, ToolCallPart):
+ first_call_id = first_call_id or p.id
+ blocks.append(
+ {"type": "tool_use", "id": p.id, "name": p.name, "input": dict(p.arguments)}
+ )
+ elif isinstance(p, ToolResultPart):
+ content: list[dict[str, Any]] = [
+ {"type": "text", "text": p.content or "(no output)"}
+ ]
+ for img in p.images:
+ if img.label:
+ content.append({"type": "text", "text": f"[image: {img.label}]"})
+ content.append(_image_block(img))
+ block: dict[str, Any] = {
+ "type": "tool_result",
+ "tool_use_id": p.call_id,
+ "content": content,
+ }
+ if p.is_error:
+ block["is_error"] = True
+ blocks.append(block)
+ if not blocks:
+ continue
+ if role == "assistant" and first_call_id:
+ blocks = THINKING_BLOCKS.get(first_call_id) + blocks
+ if out and out[-1]["role"] == role:
+ out[-1]["content"].extend(blocks)
+ else:
+ out.append({"role": role, "content": blocks})
+ if not out:
+ raise ModelError("ChatRequest has no content to send")
+ if out[0]["role"] != "user":
+ out.insert(0, {"role": "user", "content": [{"type": "text", "text": "(continue)"}]})
+ return out
+
+
+# --------------------------------------------------------------------- tools
+def to_tool(t: ToolSpec) -> dict[str, Any]:
+ schema = (
+ to_anthropic_schema(t.parameters) if t.parameters else {"type": "object", "properties": {}}
+ )
+ return {"name": t.name, "description": t.description, "input_schema": schema}
+
+
+def submit_tool(schema: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "name": SUBMIT_TOOL,
+ "description": "Submit the final answer. Call exactly once with the complete JSON object.",
+ "input_schema": to_anthropic_schema(schema),
+ }
+
+
+# ------------------------------------------------------------------- request
+def build_kwargs(request: ChatRequest, model: str, *, json_mode: str = "tool") -> dict[str, Any]:
+ """Build ``client.messages.create(**kwargs)`` (without ``model``/``timeout``).
+ ``json_mode``: ``"tool"`` forces a ``submit`` tool; ``"output_config"`` uses
+ ``output_config.format`` json_schema."""
+ kw: dict[str, Any] = {
+ "messages": to_messages(request.messages),
+ "max_tokens": request.max_output_tokens,
+ }
+ system = request.system
+ thinking_on = request.thinking != "off" or thinking_always_on(model)
+
+ if uses_adaptive_thinking(model):
+ if request.thinking != "off":
+ kw["thinking"] = {"type": "adaptive"}
+ kw["output_config"] = {"effort": EFFORT[request.thinking]}
+ elif not thinking_always_on(model):
+ kw["thinking"] = {"type": "disabled"}
+ else:
+ kw["output_config"] = {"effort": "low"}
+ elif request.thinking != "off":
+ budget = THINKING_BUDGET[request.thinking]
+ kw["thinking"] = {"type": "enabled", "budget_tokens": budget}
+ kw["max_tokens"] = max(request.max_output_tokens, budget + 2048)
+
+ if sampling_allowed(model) and not thinking_on:
+ kw["temperature"] = request.temperature
+
+ tools = [to_tool(t) for t in request.tools] if request.tools else []
+ if request.response_schema is not None:
+ if json_mode == "output_config":
+ kw.setdefault("output_config", {})["format"] = {
+ "type": "json_schema",
+ "schema": to_anthropic_schema(request.response_schema),
+ }
+ else:
+ tools.append(submit_tool(request.response_schema))
+ if not request.tools and not thinking_on:
+ kw["tool_choice"] = {"type": "tool", "name": SUBMIT_TOOL}
+ else:
+ # forced tool_choice is incompatible with thinking; nudge instead
+ system = (
+ (system + "\n\n" if system else "")
+ + f"When you have the final answer, call the `{SUBMIT_TOOL}` tool exactly once with the complete JSON object."
+ )
+ if tools:
+ kw["tools"] = tools
+ if system:
+ kw["system"] = system
+ return kw
+
+
+# ------------------------------------------------------------------ response
+def parse_content(content: list[Any]) -> tuple[str, list[ToolCallPart], Any, list[dict[str, Any]]]:
+ """→ ``(text, tool_calls, submit_input, thinking_blocks)`` from response blocks."""
+ texts: list[str] = []
+ calls: list[ToolCallPart] = []
+ submit: Any = None
+ thinking: list[dict[str, Any]] = []
+ for block in content:
+ btype = getattr(block, "type", None)
+ if btype == "text":
+ texts.append(block.text)
+ elif btype == "tool_use":
+ args = (
+ block.input
+ if isinstance(block.input, dict)
+ else json.loads(json.dumps(block.input))
+ )
+ if block.name == SUBMIT_TOOL:
+ submit = args
+ else:
+ calls.append(ToolCallPart(id=block.id, name=block.name, arguments=dict(args)))
+ elif btype in ("thinking", "redacted_thinking"):
+ dump = block.model_dump() if hasattr(block, "model_dump") else dict(block)
+ thinking.append(dump)
+ return "".join(texts), calls, submit, thinking
diff --git a/harness/codeverse/models/base.py b/harness/codeverse/models/base.py
new file mode 100644
index 00000000..ce7b187c
--- /dev/null
+++ b/harness/codeverse/models/base.py
@@ -0,0 +1,38 @@
+"""The ChatModel protocol every API backend implements."""
+
+from __future__ import annotations
+
+from typing import Protocol, runtime_checkable
+
+from codeverse.contracts.chat import ChatRequest, ChatResponse
+
+
+@runtime_checkable
+class ChatModel(Protocol):
+ """One provider+model. Implementations must be thread-safe (the
+ orchestrator fans out judge/caption calls across threads)."""
+
+ provider: str # gemini | anthropic | openai
+ model: str
+
+ @property
+ def id(self) -> str: ...
+
+ def generate(self, request: ChatRequest) -> ChatResponse:
+ """Blocking call. Must:
+ * honour ``request.response_schema`` (return ``parsed`` as a dict/list),
+ * attach images (``ImagePart``) inline in order,
+ * return tool calls when ``request.tools`` is given and the model calls one,
+ * fill ``usage`` including ``cost_usd`` (see ``pricing.py``),
+ * raise ``ModelError`` (retryable=True/False) rather than provider exceptions.
+ """
+ ...
+
+ def supports_vision(self) -> bool: ...
+
+
+class ModelError(RuntimeError):
+ def __init__(self, message: str, *, retryable: bool = False, status: int | None = None):
+ super().__init__(message)
+ self.retryable = retryable
+ self.status = status
diff --git a/harness/codeverse/models/gemini.py b/harness/codeverse/models/gemini.py
new file mode 100644
index 00000000..bb75b26f
--- /dev/null
+++ b/harness/codeverse/models/gemini.py
@@ -0,0 +1,276 @@
+"""``GeminiModel`` — google-genai backend with key rotation + retries.
+
+* one ``genai.Client`` per API key (cached, thread-safe),
+* ``KeyPool`` shared by every GeminiModel built on the same key list,
+* up to ``max_attempts`` tries: 429 → rotate key (short pause), 5xx / timeouts
+ / empty candidates → exponential backoff with jitter,
+* ``thinking`` → ``ThinkingConfig(thinking_budget=…)``; models that reject the
+ field get one retry without it and a warning in ``response.raw["warnings"]``.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+import threading
+import time
+from collections.abc import Callable
+from typing import Any
+
+import httpx
+from google import genai
+from google.genai import errors as genai_errors
+from google.genai import types
+
+from codeverse.contracts.chat import ChatRequest, ChatResponse
+from codeverse.models.base import ModelError
+from codeverse.models.gemini_convert import (
+ FATAL_FINISH,
+ RETRYABLE_FINISH,
+ build_config,
+ extract_candidate,
+ parse_usage,
+ to_contents,
+)
+from codeverse.models.keypool import KeyPool, KeyPoolExhausted
+from codeverse.models.parts import Stopwatch
+from codeverse.models.pricing import estimate_cost
+from codeverse.models.retry import backoff_delay
+from codeverse.models.schema_utils import JsonParseError, parse_json_lenient
+
+log = logging.getLogger(__name__)
+
+_RETRY_DELAY_RE = re.compile(r"retryDelay['\"]?\s*:\s*['\"]?(\d+(?:\.\d+)?)s")
+
+_pools: dict[tuple[str, ...], KeyPool] = {}
+_clients: dict[tuple[str, int], genai.Client] = {}
+_registry_lock = threading.Lock()
+
+
+def shared_pool(keys: list[str], *, rpm_per_key: int = 900) -> KeyPool:
+ """One ``KeyPool`` per distinct key list so limiters are process-wide."""
+ sig = tuple(keys)
+ with _registry_lock:
+ pool = _pools.get(sig)
+ if pool is None:
+ pool = KeyPool(keys, rpm_per_key=rpm_per_key)
+ _pools[sig] = pool
+ return pool
+
+
+def _default_keys() -> list[str]:
+ from codeverse.config import get_settings
+
+ return list(get_settings().gemini_api_keys)
+
+
+def classify_exception(exc: BaseException) -> ModelError:
+ """Map provider / transport exceptions onto ``ModelError``."""
+ if isinstance(exc, ModelError):
+ return exc
+ if isinstance(exc, genai_errors.APIError):
+ code = int(exc.code or 0)
+ msg = f"Gemini API error {code}: {exc.message}"
+ if code == 429 or code == 408 or code >= 500:
+ return ModelError(msg, retryable=True, status=code)
+ return ModelError(msg, retryable=False, status=code)
+ if isinstance(exc, (httpx.TimeoutException, TimeoutError)):
+ return ModelError(f"Gemini request timed out: {exc}", retryable=True, status=408)
+ if isinstance(exc, (httpx.TransportError, ConnectionError)):
+ return ModelError(f"Gemini transport error: {exc}", retryable=True)
+ if isinstance(exc, KeyPoolExhausted):
+ return ModelError(f"Gemini key pool exhausted: {exc}", retryable=False, status=429)
+ return ModelError(f"Gemini unexpected error: {type(exc).__name__}: {exc}", retryable=False)
+
+
+def _retry_after_s(exc: BaseException) -> float | None:
+ """Gemini 429 bodies carry ``details[].retryDelay: "7s"``; honour it (capped)."""
+ m = _RETRY_DELAY_RE.search(str(exc))
+ return min(float(m.group(1)), 120.0) if m else None
+
+
+class GeminiModel:
+ """ChatModel for ``gemini:<model>``. See module docstring."""
+
+ provider = "gemini"
+
+ def __init__(
+ self,
+ model: str,
+ *,
+ keys: list[str] | None = None,
+ pool: KeyPool | None = None,
+ timeout_s: float = 300.0,
+ max_attempts: int = 6,
+ base_delay: float = 1.0,
+ max_delay: float = 30.0,
+ rpm_per_key: int = 900,
+ sleep: Callable[[float], None] = time.sleep,
+ client_factory: Callable[[str], Any] | None = None,
+ ) -> None:
+ self.model = model
+ keys = list(keys) if keys is not None else _default_keys()
+ if pool is None and not keys:
+ raise ModelError(
+ "no Gemini API keys configured (GEMINI_API_KEYS / ~/.config/astra3d/gemini_keys.env)"
+ )
+ self.pool = pool or shared_pool(keys, rpm_per_key=rpm_per_key)
+ self.timeout_s = timeout_s
+ self.max_attempts = max(1, max_attempts)
+ self.base_delay = base_delay
+ self.max_delay = max_delay
+ self._sleep = sleep
+ self._client_factory = client_factory
+ self._thinking_ok = True # flipped when the model rejects ThinkingConfig
+ self._lock = threading.Lock()
+
+ # ------------------------------------------------------------------ proto
+ @property
+ def id(self) -> str:
+ return f"gemini:{self.model}"
+
+ def supports_vision(self) -> bool:
+ return True
+
+ # ---------------------------------------------------------------- clients
+ def _client(self, key: str) -> Any:
+ if self._client_factory is not None:
+ return self._client_factory(key)
+ ck = (key, int(self.timeout_s * 1000))
+ with _registry_lock:
+ client = _clients.get(ck)
+ if client is None:
+ client = genai.Client(api_key=key, http_options=types.HttpOptions(timeout=ck[1]))
+ _clients[ck] = client
+ return client
+
+ # --------------------------------------------------------------- generate
+ def generate(self, request: ChatRequest) -> ChatResponse:
+ contents = to_contents(request.messages)
+ warnings: list[str] = []
+ failed_keys: set[str] = set()
+ last_err: ModelError | None = None
+ attempt = 0
+ config = self._config(request, warnings)
+ while attempt < self.max_attempts:
+ attempt += 1
+ try:
+ key = self.pool.acquire(
+ exclude=failed_keys if len(failed_keys) < len(self.pool) else None
+ )
+ except KeyPoolExhausted as exc:
+ raise classify_exception(exc) from exc
+ try:
+ resp = self._once(key, contents, config, request, warnings)
+ self.pool.report(
+ key, "ok", tokens=resp.usage.input_tokens + resp.usage.output_tokens
+ )
+ return resp
+ except Exception as exc: # noqa: BLE001 - classified below
+ err = classify_exception(exc)
+ last_err = err
+ if self._thinking_ok and err.status == 400 and "thinking" in str(err).lower():
+ # model rejects ThinkingConfig: retry without it, once, for free
+ with self._lock:
+ self._thinking_ok = False
+ warnings.append(
+ f"{self.model} rejected thinking config; retrying without it: {err}"
+ )
+ config = self._config(request, warnings)
+ attempt -= 1
+ continue
+ # content-level failures (bad JSON, empty candidates) are not the key's fault
+ outcome = (
+ "429"
+ if err.status == 429
+ else "5xx"
+ if (err.status or 0) >= 500
+ else "error"
+ if err.status
+ else "ok"
+ )
+ self.pool.report(
+ key, outcome, retry_after_s=_retry_after_s(exc) if outcome == "429" else None
+ )
+ if not err.retryable or attempt >= self.max_attempts:
+ raise err from exc
+ if outcome == "429":
+ failed_keys.add(key)
+ delay = (
+ 0.5
+ if len(self.pool) > 1
+ else backoff_delay(
+ attempt, base_delay=self.base_delay, max_delay=self.max_delay
+ )
+ )
+ else:
+ delay = backoff_delay(
+ attempt, base_delay=self.base_delay, max_delay=self.max_delay
+ )
+ log.warning(
+ "gemini %s attempt %d/%d failed (%s); retrying in %.1fs",
+ self.model,
+ attempt,
+ self.max_attempts,
+ err,
+ delay,
+ )
+ self._sleep(delay)
+ assert last_err is not None
+ raise last_err
+
+ def _config(self, request: ChatRequest, warnings: list[str]) -> types.GenerateContentConfig:
+ return build_config(
+ request,
+ timeout_ms=int(self.timeout_s * 1000),
+ use_thinking=self._thinking_ok,
+ warnings=warnings,
+ )
+
+ def _once(
+ self,
+ key: str,
+ contents: list[types.Content],
+ config: types.GenerateContentConfig,
+ request: ChatRequest,
+ warnings: list[str],
+ ) -> ChatResponse:
+ client = self._client(key)
+ with Stopwatch() as sw:
+ resp = client.models.generate_content(
+ model=self.model, contents=contents, config=config
+ )
+ text, calls, finish = extract_candidate(resp)
+ usage = parse_usage(resp, self.model)
+ usage.latency_ms = sw.ms
+ usage.tool_calls = len(calls)
+ usage.cost_usd = estimate_cost("gemini", self.model, usage)
+ parsed: Any = None
+ if request.response_schema is not None and not calls:
+ try:
+ parsed = parse_json_lenient(text)
+ except JsonParseError as exc:
+ if finish in FATAL_FINISH or finish == "MAX_TOKENS":
+ # blocked, or truncated: retrying the same request cannot help
+ raise ModelError(
+ f"structured output unavailable (finish_reason={finish}; "
+ f"raise max_output_tokens if truncated): {exc}",
+ retryable=False,
+ ) from exc
+ raise ModelError(
+ f"structured output is not valid JSON (finish_reason={finish}): {exc}",
+ retryable=True,
+ ) from exc
+ elif finish in RETRYABLE_FINISH and not calls and not text.strip():
+ raise ModelError(f"Gemini finish_reason={finish}", retryable=True)
+ raw: dict[str, Any] = {
+ "finish_reason": finish,
+ "model_version": resp.model_version,
+ "response_id": resp.response_id,
+ "key": f"…{key[-4:]}",
+ }
+ if warnings:
+ raw["warnings"] = list(warnings)
+ return ChatResponse(
+ text=text, parsed=parsed, tool_calls=calls, finish_reason=finish, usage=usage, raw=raw
+ )
diff --git a/harness/codeverse/models/gemini_convert.py b/harness/codeverse/models/gemini_convert.py
new file mode 100644
index 00000000..e3505415
--- /dev/null
+++ b/harness/codeverse/models/gemini_convert.py
@@ -0,0 +1,236 @@
+"""ChatRequest ⇄ google-genai types (contents, config, tools, response parsing).
+
+Kept separate from ``gemini.py`` (which owns clients, keys, retries) so each
+module stays small and the conversions are unit-testable offline.
+"""
+
+from __future__ import annotations
+
+import json
+import threading
+from collections import OrderedDict
+from typing import Any
+
+from google.genai import types
+
+from codeverse.contracts.chat import (
+ ChatMessage,
+ ChatRequest,
+ ImagePart,
+ TextPart,
+ ToolCallPart,
+ ToolResultPart,
+ ToolSpec,
+)
+from codeverse.contracts.common import Usage
+from codeverse.models.base import ModelError
+from codeverse.models.parts import image_bytes
+from codeverse.models.schema_utils import to_gemini_schema
+
+#: INTERFACES.md mapping; ``off`` → 0 where the model allows it
+THINKING_BUDGET: dict[str, int] = {"off": 0, "low": 1024, "medium": 4096, "high": 16384}
+
+#: finish reasons that are worth one more attempt (transient model glitches)
+RETRYABLE_FINISH = {"RECITATION", "MALFORMED_FUNCTION_CALL", "OTHER", "UNEXPECTED_TOOL_CALL"}
+#: finish reasons that will not improve by retrying
+FATAL_FINISH = {"SAFETY", "PROHIBITED_CONTENT", "BLOCKLIST", "SPII", "IMAGE_SAFETY"}
+
+
+class _SignatureCache:
+ """Gemini 3 function calls carry an opaque ``thought_signature`` that MUST be
+ echoed back with the call on the next turn. ``ToolCallPart`` has no slot for
+ it, so we remember signatures by our synthetic call id (bounded LRU)."""
+
+ def __init__(self, capacity: int = 4096) -> None:
+ self._d: OrderedDict[str, bytes] = OrderedDict()
+ self._cap = capacity
+ self._lock = threading.Lock()
+
+ def put(self, call_id: str, sig: bytes | None) -> None:
+ if not sig:
+ return
+ with self._lock:
+ self._d[call_id] = sig
+ self._d.move_to_end(call_id)
+ while len(self._d) > self._cap:
+ self._d.popitem(last=False)
+
+ def get(self, call_id: str) -> bytes | None:
+ with self._lock:
+ return self._d.get(call_id)
+
+
+SIGNATURES = _SignatureCache()
+_call_counter = [0]
+_call_lock = threading.Lock()
+
+
+def _next_call_id() -> str:
+ with _call_lock:
+ _call_counter[0] += 1
+ return f"call_{_call_counter[0]:06d}"
+
+
+# ------------------------------------------------------------------ contents
+def to_contents(messages: list[ChatMessage]) -> list[types.Content]:
+ """ChatMessages → Gemini ``Content`` list. ``tool`` messages become a user
+ turn of ``function_response`` parts (images attached as extra parts)."""
+ out: list[types.Content] = []
+ for msg in messages:
+ role = "model" if msg.role == "assistant" else "user"
+ parts: list[types.Part] = []
+ for p in msg.parts:
+ if isinstance(p, TextPart):
+ if p.text:
+ parts.append(types.Part.from_text(text=p.text))
+ elif isinstance(p, ImagePart):
+ raw, mime = image_bytes(p)
+ if p.label:
+ parts.append(types.Part.from_text(text=f"[image: {p.label}]"))
+ parts.append(types.Part.from_bytes(data=raw, mime_type=mime))
+ elif isinstance(p, ToolCallPart):
+ part = types.Part(
+ function_call=types.FunctionCall(name=p.name, args=dict(p.arguments))
+ )
+ sig = SIGNATURES.get(p.id)
+ if sig:
+ part.thought_signature = sig
+ parts.append(part)
+ elif isinstance(p, ToolResultPart):
+ parts.append(_function_response_part(p))
+ for img in p.images:
+ raw, mime = image_bytes(img)
+ if img.label:
+ parts.append(types.Part.from_text(text=f"[image: {img.label}]"))
+ parts.append(types.Part.from_bytes(data=raw, mime_type=mime))
+ if not parts:
+ continue
+ # merge consecutive same-role turns (Gemini wants strict alternation)
+ if out and out[-1].role == role:
+ out[-1].parts.extend(parts) # type: ignore[union-attr]
+ else:
+ out.append(types.Content(role=role, parts=parts))
+ if not out:
+ raise ModelError("ChatRequest has no content to send")
+ return out
+
+
+def _function_response_part(p: ToolResultPart) -> types.Part:
+ payload: dict[str, Any]
+ try:
+ parsed = json.loads(p.content)
+ payload = parsed if isinstance(parsed, dict) else {"result": parsed}
+ except (json.JSONDecodeError, TypeError):
+ payload = {"result": p.content}
+ if p.is_error:
+ payload = {"error": payload.get("result", payload)} if "error" not in payload else payload
+ return types.Part(function_response=types.FunctionResponse(name=p.name, response=payload))
+
+
+# -------------------------------------------------------------------- config
+def to_tools(tools: list[ToolSpec]) -> list[types.Tool]:
+ decls = [
+ types.FunctionDeclaration(
+ name=t.name,
+ description=t.description,
+ parameters=to_gemini_schema(t.parameters) if t.parameters else None,
+ )
+ for t in tools
+ ]
+ return [types.Tool(function_declarations=decls)]
+
+
+def build_config(
+ request: ChatRequest,
+ *,
+ timeout_ms: int,
+ use_thinking: bool = True,
+ warnings: list[str] | None = None,
+) -> types.GenerateContentConfig:
+ """Map a ChatRequest onto ``GenerateContentConfig``. Function calling and
+ JSON mode are mutually exclusive on Gemini: with tools, the schema is
+ dropped (the text is still parsed leniently) and a warning is recorded."""
+ cfg: dict[str, Any] = {
+ "temperature": request.temperature,
+ "max_output_tokens": request.max_output_tokens,
+ "http_options": types.HttpOptions(timeout=timeout_ms),
+ }
+ if request.system:
+ cfg["system_instruction"] = request.system
+ if use_thinking:
+ cfg["thinking_config"] = types.ThinkingConfig(
+ thinking_budget=THINKING_BUDGET[request.thinking], include_thoughts=False
+ )
+ if request.tools:
+ cfg["tools"] = to_tools(request.tools)
+ cfg["tool_config"] = types.ToolConfig(
+ function_calling_config=types.FunctionCallingConfig(mode="AUTO")
+ )
+ cfg["automatic_function_calling"] = types.AutomaticFunctionCallingConfig(disable=True)
+ if request.response_schema is not None and warnings is not None:
+ warnings.append(
+ "response_schema ignored: Gemini cannot combine function calling with JSON mode"
+ )
+ elif request.response_schema is not None:
+ cfg["response_mime_type"] = "application/json"
+ cfg["response_schema"] = to_gemini_schema(request.response_schema)
+ return types.GenerateContentConfig(**cfg)
+
+
+# ------------------------------------------------------------------ response
+def parse_usage(resp: types.GenerateContentResponse, model: str) -> Usage:
+ um = resp.usage_metadata
+ if um is None:
+ return Usage(backend="gemini", model=model)
+ return Usage(
+ backend="gemini",
+ model=resp.model_version or model,
+ input_tokens=(um.prompt_token_count or 0) + (um.tool_use_prompt_token_count or 0),
+ output_tokens=um.candidates_token_count or 0,
+ cached_tokens=um.cached_content_token_count or 0,
+ thoughts_tokens=um.thoughts_token_count or 0,
+ )
+
+
+def extract_candidate(resp: types.GenerateContentResponse) -> tuple[str, list[ToolCallPart], str]:
+ """→ ``(text, tool_calls, finish_reason)``. Raises ``ModelError`` on blocked
+ prompts (non-retryable) or empty candidates (retryable)."""
+ pf = resp.prompt_feedback
+ if pf is not None and pf.block_reason:
+ raise ModelError(
+ f"prompt blocked by Gemini: {pf.block_reason} {pf.block_reason_message or ''}".strip(),
+ retryable=False,
+ )
+ if not resp.candidates:
+ raise ModelError("Gemini returned no candidates", retryable=True)
+ cand = resp.candidates[0]
+ finish = str(cand.finish_reason.value if cand.finish_reason else "") or "UNKNOWN"
+ texts: list[str] = []
+ calls: list[ToolCallPart] = []
+ for part in cand.content.parts if cand.content and cand.content.parts else []:
+ if part.function_call is not None:
+ fc = part.function_call
+ call_id = fc.id or _next_call_id()
+ SIGNATURES.put(call_id, part.thought_signature)
+ calls.append(
+ ToolCallPart(id=call_id, name=fc.name or "", arguments=dict(fc.args or {}))
+ )
+ elif part.text and not part.thought:
+ texts.append(part.text)
+ text = "".join(texts)
+ if not text and not calls:
+ if finish in FATAL_FINISH:
+ raise ModelError(
+ f"Gemini produced no content (finish_reason={finish})", retryable=False
+ )
+ if finish == "MAX_TOKENS":
+ # Gemini 3 models always think (budget 0 is accepted but ignored); a tiny
+ # max_output_tokens is eaten by thoughts. Retrying cannot help.
+ thoughts = resp.usage_metadata.thoughts_token_count if resp.usage_metadata else None
+ raise ModelError(
+ f"Gemini produced no content: max_output_tokens exhausted by thinking "
+ f"(thoughts_tokens={thoughts}); raise max_output_tokens",
+ retryable=False,
+ )
+ raise ModelError(f"Gemini produced no content (finish_reason={finish})", retryable=True)
+ return text, calls, finish
diff --git a/harness/codeverse/models/keypool.py b/harness/codeverse/models/keypool.py
new file mode 100644
index 00000000..c0974ece
--- /dev/null
+++ b/harness/codeverse/models/keypool.py
@@ -0,0 +1,256 @@
+"""Multi-key pool with per-key rate limiting, 429 cooldown and a health score.
+
+Used by ``GeminiModel`` (22 keys on the owner's box) but provider-neutral.
+
+* ``acquire()`` picks the next healthy key round-robin, honouring per-key
+ RPM / TPM token buckets and 429 cool-downs; it blocks (bounded) when every
+ key is throttled and raises ``KeyPoolExhausted`` after ``timeout_s``.
+* ``report(key, outcome)`` feeds back ``ok | 429 | 5xx | error`` so the pool
+ can cool a key down and adjust its health score.
+* ``stats()`` exposes counters for logs / ``c3v doctor``.
+
+Thread-safe; ``clock`` / ``sleep`` are injectable for deterministic tests.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from typing import Any, Literal
+
+Outcome = Literal["ok", "429", "5xx", "error"]
+
+
+class KeyPoolExhausted(RuntimeError):
+ """Every key is cooling down / throttled and the wait budget ran out."""
+
+
+@dataclass
+class TokenBucket:
+ """Classic token bucket: ``capacity`` tokens, refilled at ``rate`` per second."""
+
+ capacity: float
+ rate: float
+ tokens: float = field(default=0.0)
+ updated: float = field(default=0.0)
+
+ def __post_init__(self) -> None:
+ self.tokens = self.capacity
+
+ def _refill(self, now: float) -> None:
+ if now > self.updated:
+ self.tokens = min(self.capacity, self.tokens + (now - self.updated) * self.rate)
+ self.updated = now
+
+ def try_take(self, n: float, now: float) -> bool:
+ self._refill(now)
+ if self.tokens >= n:
+ self.tokens -= n
+ return True
+ return False
+
+ def wait_for(self, n: float, now: float) -> float:
+ """Seconds until ``n`` tokens are available (0 if already)."""
+ self._refill(now)
+ if self.tokens >= n:
+ return 0.0
+ return (n - self.tokens) / self.rate if self.rate > 0 else float("inf")
+
+
+@dataclass
+class _KeyState:
+ key: str
+ rpm: TokenBucket
+ tpm: TokenBucket | None
+ health: float = 1.0
+ cooldown_until: float = 0.0
+ n_ok: int = 0
+ n_429: int = 0
+ n_5xx: int = 0
+ n_error: int = 0
+ n_acquired: int = 0
+ last_used: float = 0.0
+ health_ts: float = 0.0
+
+ def recover(self, now: float, rate: float = 0.01) -> None:
+ """Passive health recovery: +``rate`` per idle second, capped at 1.0."""
+ if now > self.health_ts:
+ self.health = min(1.0, self.health + (now - self.health_ts) * rate)
+ self.health_ts = now
+
+ def available_at(self, now: float, tokens_hint: int) -> float:
+ """Earliest time this key can be used (``now`` if ready)."""
+ t = max(now, self.cooldown_until)
+ t = max(t, now + self.rpm.wait_for(1.0, now))
+ if self.tpm is not None and tokens_hint > 0:
+ t = max(t, now + self.tpm.wait_for(float(tokens_hint), now))
+ return t
+
+
+class KeyPool:
+ """Round-robin key pool with per-key limiters. See module docstring."""
+
+ def __init__(
+ self,
+ keys: list[str] | tuple[str, ...],
+ *,
+ rpm_per_key: int = 900,
+ tpm_per_key: int | None = None,
+ cooldown_s: float = 30.0,
+ min_health: float = 0.3,
+ clock: Callable[[], float] = time.monotonic,
+ sleep: Callable[[float], None] = time.sleep,
+ ) -> None:
+ uniq = [k for i, k in enumerate(keys) if k and k not in keys[:i]]
+ if not uniq:
+ raise ValueError("KeyPool needs at least one non-empty key")
+ self._clock = clock
+ self._sleep = sleep
+ self._cooldown_s = float(cooldown_s)
+ self._min_health = min_health
+ self._lock = threading.Lock()
+ self._rr = 0
+ now = clock()
+ self._states: list[_KeyState] = []
+ for k in uniq:
+ rpm = TokenBucket(capacity=float(rpm_per_key), rate=rpm_per_key / 60.0, updated=now)
+ tpm = None
+ if tpm_per_key:
+ tpm = TokenBucket(capacity=float(tpm_per_key), rate=tpm_per_key / 60.0, updated=now)
+ self._states.append(_KeyState(key=k, rpm=rpm, tpm=tpm, health_ts=now))
+ self._by_key = {s.key: s for s in self._states}
+
+ # ------------------------------------------------------------------ public
+ def __len__(self) -> int:
+ return len(self._states)
+
+ @property
+ def keys(self) -> list[str]:
+ return [s.key for s in self._states]
+
+ def acquire(
+ self,
+ *,
+ tokens_hint: int = 0,
+ exclude: set[str] | frozenset[str] | None = None,
+ timeout_s: float | None = 120.0,
+ ) -> str:
+ """Return the next usable key, blocking (bounded by ``timeout_s``) while all
+ keys are throttled. ``exclude`` skips keys that already failed this call."""
+ deadline = None if timeout_s is None else self._clock() + timeout_s
+ while True:
+ with self._lock:
+ now = self._clock()
+ chosen = self._pick(now, tokens_hint, exclude or ())
+ if chosen is not None:
+ chosen.rpm.try_take(1.0, now)
+ if chosen.tpm is not None and tokens_hint > 0:
+ chosen.tpm.try_take(float(tokens_hint), now)
+ chosen.n_acquired += 1
+ chosen.last_used = now
+ return chosen.key
+ soonest = min(
+ (
+ s.available_at(now, tokens_hint)
+ for s in self._states
+ if s.key not in (exclude or ())
+ ),
+ default=float("inf"),
+ )
+ if soonest == float("inf"):
+ raise KeyPoolExhausted("all keys excluded")
+ wait = max(0.01, min(soonest - now, 5.0))
+ if deadline is not None and self._clock() + wait > deadline:
+ raise KeyPoolExhausted(
+ f"all {len(self._states)} keys throttled; waited {timeout_s}s"
+ )
+ self._sleep(wait)
+
+ def report(
+ self,
+ key: str,
+ outcome: Outcome,
+ *,
+ tokens: int = 0,
+ retry_after_s: float | None = None,
+ ) -> None:
+ """Feed back the result of a call made with ``key``."""
+ with self._lock:
+ st = self._by_key.get(key)
+ if st is None:
+ return
+ now = self._clock()
+ st.recover(now)
+ if outcome == "ok":
+ st.n_ok += 1
+ st.health = min(1.0, st.health + 0.2 * (1.0 - st.health))
+ elif outcome == "429":
+ st.n_429 += 1
+ st.health *= 0.5
+ cool = retry_after_s if retry_after_s and retry_after_s > 0 else self._cooldown_s
+ st.cooldown_until = max(st.cooldown_until, now + cool)
+ elif outcome == "5xx":
+ st.n_5xx += 1
+ st.health *= 0.8
+ else:
+ st.n_error += 1
+ st.health *= 0.9
+ if tokens > 0 and st.tpm is not None:
+ # charge actual usage (callers that pass a tokens_hint at acquire
+ # should report tokens=0 to avoid double charging)
+ st.tpm.try_take(float(tokens), now)
+
+ def stats(self) -> dict[str, Any]:
+ """Counters per key (keys are redacted to their last 4 chars)."""
+ with self._lock:
+ now = self._clock()
+ per_key = [
+ {
+ "key": f"…{s.key[-4:]}",
+ "health": round(s.health, 3),
+ "cooldown_s": round(max(0.0, s.cooldown_until - now), 1),
+ "rpm_tokens": round(s.rpm.tokens, 1),
+ "acquired": s.n_acquired,
+ "ok": s.n_ok,
+ "429": s.n_429,
+ "5xx": s.n_5xx,
+ "error": s.n_error,
+ }
+ for s in self._states
+ ]
+ return {
+ "n_keys": len(self._states),
+ "n_cooling": sum(1 for s in self._states if s.cooldown_until > now),
+ "acquired": sum(s.n_acquired for s in self._states),
+ "ok": sum(s.n_ok for s in self._states),
+ "429": sum(s.n_429 for s in self._states),
+ "5xx": sum(s.n_5xx for s in self._states),
+ "error": sum(s.n_error for s in self._states),
+ "keys": per_key,
+ }
+
+ # ----------------------------------------------------------------- private
+ def _pick(self, now: float, tokens_hint: int, exclude) -> _KeyState | None:
+ """Round-robin scan; prefer the first healthy, ready key; otherwise the
+ healthiest ready key. Advances the RR cursor past the chosen key."""
+ n = len(self._states)
+ best: _KeyState | None = None
+ best_idx = -1
+ for step in range(n):
+ idx = (self._rr + step) % n
+ st = self._states[idx]
+ if st.key in exclude:
+ continue
+ st.recover(now)
+ if st.available_at(now, tokens_hint) > now:
+ continue
+ if st.health >= self._min_health:
+ self._rr = (idx + 1) % n
+ return st
+ if best is None or st.health > best.health:
+ best, best_idx = st, idx
+ if best is not None:
+ self._rr = (best_idx + 1) % n
+ return best
diff --git a/harness/codeverse/models/openai.py b/harness/codeverse/models/openai.py
new file mode 100644
index 00000000..8d63bd2e
--- /dev/null
+++ b/harness/codeverse/models/openai.py
@@ -0,0 +1,208 @@
+"""``OpenAIModel`` — Chat Completions backend (images as data URLs, function
+tools, ``json_schema`` response_format with strict→non-strict fallback,
+``reasoning_effort`` for o*/gpt-5* models, usage/cost, ``OPENAI_BASE_URL``).
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+import time
+from collections.abc import Callable
+from typing import Any
+
+from codeverse.contracts.chat import ChatRequest, ChatResponse
+from codeverse.contracts.common import Usage
+from codeverse.models.base import ModelError
+from codeverse.models.openai_convert import build_kwargs, parse_choice
+from codeverse.models.parts import Stopwatch
+from codeverse.models.pricing import estimate_cost
+from codeverse.models.retry import with_retries
+from codeverse.models.schema_utils import JsonParseError, parse_json_lenient
+
+log = logging.getLogger(__name__)
+
+
+def classify_exception(exc: BaseException) -> ModelError:
+ """Map openai SDK exceptions onto ``ModelError``."""
+ if isinstance(exc, ModelError):
+ return exc
+ import openai
+
+ if isinstance(exc, openai.APIStatusError):
+ status = int(getattr(exc, "status_code", 0) or 0)
+ retry = status in (408, 409, 429) or status >= 500
+ return ModelError(
+ f"OpenAI API error {status}: {exc.message}", retryable=retry, status=status
+ )
+ if isinstance(exc, openai.APITimeoutError):
+ return ModelError(f"OpenAI request timed out: {exc}", retryable=True, status=408)
+ if isinstance(exc, openai.APIConnectionError):
+ return ModelError(f"OpenAI connection error: {exc}", retryable=True)
+ if isinstance(exc, openai.APIError):
+ return ModelError(f"OpenAI API error: {exc}", retryable=False)
+ return ModelError(f"OpenAI unexpected error: {type(exc).__name__}: {exc}", retryable=False)
+
+
+def _is_schema_rejection(err: ModelError) -> bool:
+ s = str(err).lower()
+ return err.status == 400 and ("schema" in s or "response_format" in s or "strict" in s)
+
+
+class OpenAIModel:
+ """ChatModel for ``openai:<model>`` (and OpenAI-compatible endpoints)."""
+
+ provider = "openai"
+
+ def __init__(
+ self,
+ model: str,
+ *,
+ api_key: str | None = None,
+ base_url: str | None = None,
+ timeout_s: float = 600.0,
+ max_attempts: int = 6,
+ base_delay: float = 2.0,
+ max_delay: float = 30.0,
+ sleep: Callable[[float], None] = time.sleep,
+ client: Any | None = None,
+ ) -> None:
+ self.model = model
+ self.timeout_s = timeout_s
+ self.max_attempts = max(1, max_attempts)
+ self.base_delay = base_delay
+ self.max_delay = max_delay
+ self._sleep = sleep
+ self._client = client
+ self._api_key = api_key
+ self._base_url = base_url
+ self._strict_ok = True # flipped when the endpoint rejects strict schemas
+ self._lock = threading.Lock()
+
+ @property
+ def id(self) -> str:
+ return f"openai:{self.model}"
+
+ def supports_vision(self) -> bool:
+ return True
+
+ # ---------------------------------------------------------------- client
+ def client(self) -> Any:
+ with self._lock:
+ if self._client is None:
+ import openai
+
+ from codeverse.config import get_settings
+
+ s = get_settings()
+ key = self._api_key or s.openai_api_key
+ base_url = self._base_url or s.openai_base_url or None
+ if not key and not base_url:
+ raise ModelError("OPENAI_API_KEY is not configured")
+ self._client = openai.OpenAI(
+ api_key=key or "sk-local",
+ base_url=base_url,
+ max_retries=0,
+ timeout=self.timeout_s,
+ )
+ return self._client
+
+ # -------------------------------------------------------------- generate
+ def generate(self, request: ChatRequest) -> ChatResponse:
+ def attempt() -> ChatResponse:
+ strict = self._strict_ok and request.response_schema is not None
+ kwargs = build_kwargs(request, self.model, strict_schema=strict)
+ try:
+ return self._once(kwargs, request)
+ except Exception as exc: # noqa: BLE001 - classified
+ err = classify_exception(exc)
+ if strict and _is_schema_rejection(err):
+ log.warning(
+ "openai %s rejected strict json_schema (%s); falling back to strict=false",
+ self.model,
+ err,
+ )
+ with self._lock:
+ self._strict_ok = False
+ kwargs = build_kwargs(request, self.model, strict_schema=False)
+ try:
+ return self._once(kwargs, request)
+ except Exception as exc2: # noqa: BLE001
+ raise classify_exception(exc2) from exc2
+ raise err from exc
+
+ def on_retry(n: int, exc: BaseException, delay: float) -> None:
+ log.warning(
+ "openai %s attempt %d/%d failed (%s); retrying in %.1fs",
+ self.model,
+ n,
+ self.max_attempts,
+ exc,
+ delay,
+ )
+
+ return with_retries(
+ attempt,
+ is_retryable=lambda e: isinstance(e, ModelError) and e.retryable,
+ attempts=self.max_attempts,
+ base_delay=self.base_delay,
+ max_delay=self.max_delay,
+ on_retry=on_retry,
+ sleep=self._sleep,
+ )
+
+ def _once(self, kwargs: dict[str, Any], request: ChatRequest) -> ChatResponse:
+ client = self.client()
+ with Stopwatch() as sw:
+ completion = client.chat.completions.create(model=self.model, **kwargs)
+ if not completion.choices:
+ raise ModelError("OpenAI returned no choices", retryable=True)
+ text, calls, finish = parse_choice(completion.choices[0])
+ usage = self._usage(completion.usage, sw.ms, len(calls))
+ parsed: Any = None
+ if request.response_schema is not None and not calls:
+ try:
+ parsed = parse_json_lenient(text)
+ except JsonParseError as exc:
+ raise ModelError(
+ f"structured output is not valid JSON (finish_reason={finish}): {exc}",
+ retryable=finish != "length",
+ ) from exc
+ if not text and not calls:
+ raise ModelError(
+ f"OpenAI returned no content (finish_reason={finish})",
+ retryable=finish != "content_filter",
+ )
+ raw: dict[str, Any] = {
+ "finish_reason": finish,
+ "id": completion.id,
+ "model": completion.model,
+ }
+ return ChatResponse(
+ text=text, parsed=parsed, tool_calls=calls, finish_reason=finish, usage=usage, raw=raw
+ )
+
+ def _usage(self, u: Any, latency_ms: int, n_calls: int) -> Usage:
+ if u is None:
+ usage = Usage(
+ backend="openai", model=self.model, tool_calls=n_calls, latency_ms=latency_ms
+ )
+ else:
+ ptd = getattr(u, "prompt_tokens_details", None)
+ ctd = getattr(u, "completion_tokens_details", None)
+ cached = int(getattr(ptd, "cached_tokens", 0) or 0) if ptd else 0
+ reasoning = int(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0
+ completion = int(u.completion_tokens or 0)
+ usage = Usage(
+ backend="openai",
+ model=self.model,
+ input_tokens=int(u.prompt_tokens or 0),
+ # completion_tokens already includes reasoning; split so the sum stays exact
+ output_tokens=max(0, completion - reasoning),
+ cached_tokens=cached,
+ thoughts_tokens=reasoning,
+ tool_calls=n_calls,
+ latency_ms=latency_ms,
+ )
+ usage.cost_usd = estimate_cost("openai", self.model, usage)
+ return usage
diff --git a/harness/codeverse/models/openai_convert.py b/harness/codeverse/models/openai_convert.py
new file mode 100644
index 00000000..a9c08c04
--- /dev/null
+++ b/harness/codeverse/models/openai_convert.py
@@ -0,0 +1,182 @@
+"""ChatRequest ⇄ OpenAI Chat Completions dicts (messages, tools, response_format).
+
+Chat Completions (not Responses) was chosen because every OpenAI-compatible
+endpoint (``OPENAI_BASE_URL``: vLLM, OpenRouter, Ollama, …) speaks it, while
+the Responses API is OpenAI-only.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+from codeverse.contracts.chat import (
+ ChatMessage,
+ ChatRequest,
+ ImagePart,
+ TextPart,
+ ToolCallPart,
+ ToolResultPart,
+ ToolSpec,
+)
+from codeverse.models.base import ModelError
+from codeverse.models.parts import image_b64
+from codeverse.models.schema_utils import inline_refs, to_openai_strict_schema
+
+SCHEMA_NAME = "response"
+
+
+# ------------------------------------------------------------- model families
+def is_reasoning_model(model: str) -> bool:
+ m = model.lower()
+ return m.startswith(("o1", "o3", "o4", "gpt-5"))
+
+
+def reasoning_effort(model: str, thinking: str) -> str | None:
+ """Map ``thinking`` onto ``reasoning_effort`` (None for non-reasoning models)."""
+ if not is_reasoning_model(model):
+ return None
+ m = model.lower()
+ if thinking == "off":
+ if m.startswith("gpt-5.") and not m.startswith("gpt-5.0"):
+ return "none" # gpt-5.1+ accept "none"
+ if m.startswith("gpt-5"):
+ return "minimal"
+ return "low" # o-series has no off switch
+ return thinking
+
+
+# ------------------------------------------------------------------ messages
+def _image_block(p: ImagePart) -> dict[str, Any]:
+ data, mime = image_b64(p)
+ return {
+ "type": "image_url",
+ "image_url": {"url": f"data:{mime};base64,{data}", "detail": "auto"},
+ }
+
+
+def to_messages(messages: list[ChatMessage], system: str) -> list[dict[str, Any]]:
+ """ChatMessages → Chat Completions messages. Tool results become ``role:
+ tool`` messages; images inside tool results (unsupported there) are sent as
+ a follow-up user message."""
+ out: list[dict[str, Any]] = []
+ if system:
+ out.append({"role": "system", "content": system})
+ for msg in messages:
+ if msg.role == "assistant":
+ out.append(_assistant_message(msg))
+ continue
+ trailing_images: list[dict[str, Any]] = []
+ content: list[dict[str, Any]] = []
+ for p in msg.parts:
+ if isinstance(p, TextPart):
+ if p.text:
+ content.append({"type": "text", "text": p.text})
+ elif isinstance(p, ImagePart):
+ if p.label:
+ content.append({"type": "text", "text": f"[image: {p.label}]"})
+ content.append(_image_block(p))
+ elif isinstance(p, ToolResultPart):
+ if content:
+ out.append({"role": "user", "content": content})
+ content = []
+ out.append(
+ {
+ "role": "tool",
+ "tool_call_id": p.call_id,
+ "content": p.content or "(no output)",
+ }
+ )
+ for img in p.images:
+ if img.label:
+ trailing_images.append(
+ {"type": "text", "text": f"[image from {p.name}: {img.label}]"}
+ )
+ trailing_images.append(_image_block(img))
+ elif isinstance(p, ToolCallPart):
+ raise ModelError("ToolCallPart is only valid in assistant messages")
+ if content:
+ out.append({"role": "user", "content": content})
+ if trailing_images:
+ out.append({"role": "user", "content": trailing_images})
+ if not out or all(m["role"] == "system" for m in out):
+ raise ModelError("ChatRequest has no content to send")
+ return out
+
+
+def _assistant_message(msg: ChatMessage) -> dict[str, Any]:
+ text = "".join(p.text for p in msg.parts if isinstance(p, TextPart))
+ calls = [
+ {
+ "id": p.id,
+ "type": "function",
+ "function": {"name": p.name, "arguments": json.dumps(p.arguments)},
+ }
+ for p in msg.parts
+ if isinstance(p, ToolCallPart)
+ ]
+ m: dict[str, Any] = {"role": "assistant", "content": text or None}
+ if calls:
+ m["tool_calls"] = calls
+ return m
+
+
+# --------------------------------------------------------------------- tools
+def to_tool(t: ToolSpec) -> dict[str, Any]:
+ params = inline_refs(t.parameters) if t.parameters else {"type": "object", "properties": {}}
+ return {
+ "type": "function",
+ "function": {"name": t.name, "description": t.description, "parameters": params},
+ }
+
+
+def response_format(schema: dict[str, Any], *, strict: bool) -> dict[str, Any]:
+ body = to_openai_strict_schema(schema) if strict else inline_refs(schema)
+ return {
+ "type": "json_schema",
+ "json_schema": {"name": SCHEMA_NAME, "schema": body, "strict": strict},
+ }
+
+
+# ------------------------------------------------------------------- request
+def build_kwargs(request: ChatRequest, model: str, *, strict_schema: bool) -> dict[str, Any]:
+ """``client.chat.completions.create(**kwargs)`` minus ``model``."""
+ kw: dict[str, Any] = {
+ "messages": to_messages(request.messages, request.system),
+ "max_completion_tokens": request.max_output_tokens,
+ }
+ effort = reasoning_effort(model, request.thinking)
+ if effort is not None:
+ kw["reasoning_effort"] = effort
+ else:
+ kw["temperature"] = request.temperature
+ if request.tools:
+ kw["tools"] = [to_tool(t) for t in request.tools]
+ kw["tool_choice"] = "auto"
+ if request.response_schema is not None:
+ kw["response_format"] = response_format(request.response_schema, strict=strict_schema)
+ return kw
+
+
+# ------------------------------------------------------------------ response
+def parse_choice(choice: Any) -> tuple[str, list[ToolCallPart], str]:
+ """→ ``(text, tool_calls, finish_reason)``; bad tool-call JSON → ModelError(retryable)."""
+ msg = choice.message
+ text = msg.content or ""
+ if getattr(msg, "refusal", None):
+ raise ModelError(f"OpenAI refusal: {msg.refusal}", retryable=False)
+ calls: list[ToolCallPart] = []
+ for tc in msg.tool_calls or []:
+ fn = getattr(tc, "function", None)
+ if fn is None:
+ continue
+ try:
+ args = json.loads(fn.arguments or "{}")
+ except json.JSONDecodeError as exc:
+ raise ModelError(
+ f"tool call {fn.name} has invalid JSON arguments: {exc}", retryable=True
+ ) from exc
+ if not isinstance(args, dict):
+ args = {"value": args}
+ calls.append(ToolCallPart(id=tc.id, name=fn.name, arguments=args))
+ return text, calls, str(choice.finish_reason or "")
diff --git a/harness/codeverse/models/parts.py b/harness/codeverse/models/parts.py
new file mode 100644
index 00000000..4619e66f
--- /dev/null
+++ b/harness/codeverse/models/parts.py
@@ -0,0 +1,60 @@
+"""Small helpers shared by the provider backends (images, timing, usage)."""
+
+from __future__ import annotations
+
+import base64
+import mimetypes
+import time
+from pathlib import Path
+
+from codeverse.contracts.chat import ImagePart
+from codeverse.models.base import ModelError
+
+_MIME_BY_SUFFIX = {
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".webp": "image/webp",
+ ".gif": "image/gif",
+}
+
+
+def image_bytes(part: ImagePart) -> tuple[bytes, str]:
+ """Return ``(raw_bytes, mime)`` for an ``ImagePart`` (path or base64).
+ Raises ``ModelError(retryable=False)`` when the part carries no data."""
+ if part.data_b64:
+ try:
+ return base64.b64decode(part.data_b64), part.mime or "image/png"
+ except (ValueError, TypeError) as exc:
+ raise ModelError(f"ImagePart.data_b64 is not valid base64: {exc}") from exc
+ if part.path:
+ p = Path(part.path)
+ if not p.is_file():
+ raise ModelError(f"ImagePart.path does not exist: {part.path}")
+ mime = part.mime
+ if not mime or mime == "image/png" and p.suffix.lower() not in ("", ".png"):
+ mime = (
+ _MIME_BY_SUFFIX.get(p.suffix.lower())
+ or mimetypes.guess_type(p.name)[0]
+ or "image/png"
+ )
+ return p.read_bytes(), mime
+ raise ModelError("ImagePart has neither path nor data_b64")
+
+
+def image_b64(part: ImagePart) -> tuple[str, str]:
+ """``(base64_string, mime)`` for providers that want base64 (Anthropic, OpenAI data URLs)."""
+ raw, mime = image_bytes(part)
+ return base64.b64encode(raw).decode("ascii"), mime
+
+
+class Stopwatch:
+ """``with Stopwatch() as sw: ...; sw.ms``"""
+
+ def __enter__(self) -> Stopwatch:
+ self._t0 = time.perf_counter()
+ self.ms = 0
+ return self
+
+ def __exit__(self, *exc: object) -> None:
+ self.ms = int((time.perf_counter() - self._t0) * 1000)
diff --git a/harness/codeverse/models/pricing.py b/harness/codeverse/models/pricing.py
new file mode 100644
index 00000000..b5399767
--- /dev/null
+++ b/harness/codeverse/models/pricing.py
@@ -0,0 +1,145 @@
+"""USD price table (per 1M tokens) + ``estimate_cost``.
+
+Providers never return USD, so every ``Usage`` is priced here. Prices are the
+latest published rates known to the author at the time of writing (2026-08);
+entries marked *approximate* were taken from secondary sources or inferred
+from the closest sibling model — refresh when the official pages change.
+
+Only the standard (short-context) tier is modelled; long-context surcharges
+and cache *storage* fees are not. Unknown models price at 0.0 and log a
+warning once per (provider, model).
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+from dataclasses import dataclass
+
+from codeverse.contracts.common import Usage
+
+log = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class Price:
+ """USD per 1M tokens. ``cached`` = cache-read input; ``cache_write`` = cache
+ creation (Anthropic/OpenAI explicit caching); ``thoughts`` defaults to output."""
+
+ input: float
+ output: float
+ cached: float = 0.0
+ cache_write: float | None = None
+ approximate: bool = False
+
+
+# fmt: off
+PRICES: dict[tuple[str, str], Price] = {
+ # ---------------------------------------------------------------- gemini
+ # 3.6 / 3.7 flash: introductory rates valid through 2026-12-31; they double
+ # on 2027-01-01 ($1.50 / $7.50 / $0.15). Update then.
+ ("gemini", "gemini-3.7-flash"): Price(0.75, 3.75, 0.075),
+ ("gemini", "gemini-3.6-flash"): Price(0.75, 3.75, 0.075),
+ ("gemini", "gemini-3.5-flash"): Price(1.50, 9.00, 0.15),
+ ("gemini", "gemini-3.1-pro-preview"): Price(2.00, 12.00, 0.20),
+ ("gemini", "gemini-3.1-flash-lite"): Price(0.25, 1.50, 0.025),
+ ("gemini", "gemini-3.1-flash-image"): Price(0.25, 1.50, 0.025, approximate=True), # + per-image fees
+ ("gemini", "gemini-3-pro-preview"): Price(2.00, 12.00, 0.20),
+ ("gemini", "gemini-3-flash-preview"): Price(0.50, 3.00, 0.05),
+ ("gemini", "gemini-2.5-pro"): Price(1.25, 10.00, 0.125),
+ ("gemini", "gemini-2.5-flash"): Price(0.30, 2.50, 0.075),
+ ("gemini", "gemini-2.5-flash-lite"): Price(0.10, 0.40, 0.025),
+ # ------------------------------------------------------------- anthropic
+ ("anthropic", "claude-fable-5"): Price(10.00, 50.00, 1.00, cache_write=12.50),
+ ("anthropic", "claude-opus-5"): Price(5.00, 25.00, 0.50, cache_write=6.25),
+ ("anthropic", "claude-opus-4-8"): Price(5.00, 25.00, 0.50, cache_write=6.25),
+ ("anthropic", "claude-opus-4-7"): Price(5.00, 25.00, 0.50, cache_write=6.25),
+ ("anthropic", "claude-opus-4-6"): Price(5.00, 25.00, 0.50, cache_write=6.25),
+ ("anthropic", "claude-opus-4-5"): Price(5.00, 25.00, 0.50, cache_write=6.25),
+ ("anthropic", "claude-opus-4-1"): Price(15.00, 75.00, 1.50, cache_write=18.75),
+ ("anthropic", "claude-opus-4"): Price(15.00, 75.00, 1.50, cache_write=18.75),
+ # sonnet-5 standard rate; an intro rate ($2 / $10) applies through 2026-08-31
+ ("anthropic", "claude-sonnet-5"): Price(3.00, 15.00, 0.30, cache_write=3.75),
+ ("anthropic", "claude-sonnet-4-6"): Price(3.00, 15.00, 0.30, cache_write=3.75),
+ ("anthropic", "claude-sonnet-4-5"): Price(3.00, 15.00, 0.30, cache_write=3.75),
+ ("anthropic", "claude-sonnet-4"): Price(3.00, 15.00, 0.30, cache_write=3.75),
+ ("anthropic", "claude-haiku-4-5"): Price(1.00, 5.00, 0.10, cache_write=1.25),
+ ("anthropic", "claude-haiku-4"): Price(1.00, 5.00, 0.10, cache_write=1.25, approximate=True),
+ # ---------------------------------------------------------------- openai
+ ("openai", "gpt-5.6-sol"): Price(5.00, 30.00, 0.50, cache_write=6.25, approximate=True),
+ ("openai", "gpt-5.6"): Price(5.00, 30.00, 0.50, approximate=True),
+ ("openai", "gpt-5.5"): Price(5.00, 30.00, 0.50, approximate=True),
+ ("openai", "gpt-5.4"): Price(2.50, 15.00, 0.25, approximate=True),
+ ("openai", "gpt-5.3-codex"): Price(1.75, 14.00, 0.175, approximate=True),
+ ("openai", "gpt-5.2"): Price(1.75, 14.00, 0.175, approximate=True),
+ ("openai", "gpt-5.1"): Price(1.25, 10.00, 0.125),
+ ("openai", "gpt-5-mini"): Price(0.25, 2.00, 0.025),
+ ("openai", "gpt-5-nano"): Price(0.05, 0.40, 0.005),
+ ("openai", "gpt-5"): Price(1.25, 10.00, 0.125),
+ ("openai", "gpt-4.1"): Price(2.00, 8.00, 0.50),
+ ("openai", "gpt-4.1-mini"): Price(0.40, 1.60, 0.10),
+ ("openai", "gpt-4o"): Price(2.50, 10.00, 1.25),
+ ("openai", "gpt-4o-mini"): Price(0.15, 0.60, 0.075),
+ ("openai", "o3"): Price(2.00, 8.00, 0.50),
+ ("openai", "o4-mini"): Price(1.10, 4.40, 0.275),
+}
+# fmt: on
+
+_warned: set[tuple[str, str]] = set()
+_warned_lock = threading.Lock()
+
+
+def _normalise(model: str) -> str:
+ return model.strip().lower()
+
+
+def lookup_price(provider: str, model: str) -> Price | None:
+ """Exact match first, then the longest table key that is a prefix of ``model``
+ (so ``claude-opus-5-20260301`` or ``gemini-3.7-flash-preview-xx`` still price)."""
+ m = _normalise(model)
+ exact = PRICES.get((provider, m))
+ if exact is not None:
+ return exact
+ best: tuple[int, Price] | None = None
+ for (prov, key), price in PRICES.items():
+ if prov != provider or not m.startswith(key):
+ continue
+ # require a boundary so "gpt-5" doesn't swallow "gpt-5.5" when a longer key exists
+ if len(m) > len(key) and m[len(key)] not in "-_.@:":
+ continue
+ if best is None or len(key) > best[0]:
+ best = (len(key), price)
+ return best[1] if best else None
+
+
+def estimate_cost(provider: str, model: str, usage: Usage) -> float:
+ """USD for one call. ``usage.input_tokens`` is the TOTAL prompt size (cached
+ tokens included); cached tokens are re-priced at the cache-read rate.
+ ``usage.thoughts_tokens`` are billed as output when the provider reports
+ them separately from ``output_tokens`` (Gemini); Anthropic/OpenAI fold
+ reasoning into ``output_tokens`` already, so callers must not double count."""
+ price = lookup_price(provider, model)
+ if price is None:
+ key = (provider, _normalise(model))
+ with _warned_lock:
+ if key not in _warned:
+ _warned.add(key)
+ log.warning("pricing: unknown model %s:%s — cost reported as 0.0", provider, model)
+ return 0.0
+ m = 1_000_000.0
+ cached = max(0, min(usage.cached_tokens, usage.input_tokens))
+ uncached = max(0, usage.input_tokens - cached)
+ cost = uncached * price.input / m
+ cost += cached * price.cached / m
+ cost += (usage.output_tokens + usage.thoughts_tokens) * price.output / m
+ return cost
+
+
+def cache_write_surcharge(provider: str, model: str, cache_write_tokens: int) -> float:
+ """Extra USD (on top of the normal input rate already charged by
+ ``estimate_cost``) for explicit cache creation, e.g. Anthropic's
+ ``cache_creation_input_tokens`` billed at 1.25× input."""
+ price = lookup_price(provider, model)
+ if price is None or cache_write_tokens <= 0 or price.cache_write is None:
+ return 0.0
+ return cache_write_tokens * max(0.0, price.cache_write - price.input) / 1_000_000.0
diff --git a/harness/codeverse/models/registry.py b/harness/codeverse/models/registry.py
new file mode 100644
index 00000000..69dc710e
--- /dev/null
+++ b/harness/codeverse/models/registry.py
@@ -0,0 +1,34 @@
+"""Model id parsing + factory. Ids: ``<provider>:<model>``."""
+
+from __future__ import annotations
+
+from functools import lru_cache
+
+from codeverse.models.base import ChatModel
+
+PROVIDERS = ("gemini", "anthropic", "openai")
+
+
+def parse_model_id(model_id: str) -> tuple[str, str]:
+ if ":" not in model_id:
+ raise ValueError(f"model id must be '<provider>:<model>', got {model_id!r}")
+ provider, model = model_id.split(":", 1)
+ if provider not in PROVIDERS:
+ raise ValueError(f"unknown provider {provider!r}; known: {PROVIDERS}")
+ return provider, model
+
+
+@lru_cache(maxsize=32)
+def get_chat_model(model_id: str) -> ChatModel:
+ provider, model = parse_model_id(model_id)
+ if provider == "gemini":
+ from codeverse.models.gemini import GeminiModel
+
+ return GeminiModel(model)
+ if provider == "anthropic":
+ from codeverse.models.anthropic import AnthropicModel
+
+ return AnthropicModel(model)
+ from codeverse.models.openai import OpenAIModel
+
+ return OpenAIModel(model)
diff --git a/harness/codeverse/models/retry.py b/harness/codeverse/models/retry.py
new file mode 100644
index 00000000..07d12535
--- /dev/null
+++ b/harness/codeverse/models/retry.py
@@ -0,0 +1,65 @@
+"""Generic retry helper with exponential backoff + full jitter.
+
+Provider modules use it for 429/5xx/timeouts; it is deliberately tiny and has
+no provider knowledge. ``sleep`` is injectable so unit tests run instantly.
+"""
+
+from __future__ import annotations
+
+import random
+import time
+from collections.abc import Callable
+from typing import TypeVar
+
+T = TypeVar("T")
+
+OnRetry = Callable[[int, BaseException, float], None]
+
+
+def backoff_delay(
+ attempt: int, *, base_delay: float, max_delay: float, jitter: bool = True
+) -> float:
+ """Delay before retry number ``attempt`` (1-based): ``base * 2**(attempt-1)`` capped,
+ with full jitter (uniform in ``[delay/2, delay]``) when ``jitter`` is on."""
+ raw = min(max_delay, base_delay * (2 ** max(0, attempt - 1)))
+ if not jitter:
+ return raw
+ return random.uniform(raw / 2.0, raw)
+
+
+def with_retries(
+ fn: Callable[[], T],
+ *,
+ is_retryable: Callable[[BaseException], bool],
+ attempts: int = 6,
+ base_delay: float = 1.0,
+ max_delay: float = 30.0,
+ on_retry: OnRetry | None = None,
+ sleep: Callable[[float], None] = time.sleep,
+ jitter: bool = True,
+) -> T:
+ """Call ``fn`` up to ``attempts`` times.
+
+ Re-raises the last exception when it is not retryable (per ``is_retryable``)
+ or when attempts are exhausted. ``on_retry(attempt, exc, delay)`` is called
+ before each sleep (attempt is the 1-based index of the attempt that failed).
+ """
+ if attempts < 1:
+ raise ValueError("attempts must be >= 1")
+ last: BaseException | None = None
+ for attempt in range(1, attempts + 1):
+ try:
+ return fn()
+ except BaseException as exc: # noqa: BLE001 - classification is delegated
+ last = exc
+ if attempt >= attempts or not is_retryable(exc):
+ raise
+ delay = backoff_delay(
+ attempt, base_delay=base_delay, max_delay=max_delay, jitter=jitter
+ )
+ if on_retry is not None:
+ on_retry(attempt, exc, delay)
+ sleep(delay)
+ # unreachable, but keeps type-checkers happy
+ assert last is not None
+ raise last
diff --git a/harness/codeverse/models/schema_utils.py b/harness/codeverse/models/schema_utils.py
new file mode 100644
index 00000000..187d41b1
--- /dev/null
+++ b/harness/codeverse/models/schema_utils.py
@@ -0,0 +1,302 @@
+"""JSON-schema adapters for the three providers + a fence-tolerant JSON parser.
+
+Pydantic v2 emits ``$defs``/``$ref``, ``title``, ``default``, ``const``,
+``prefixItems`` (tuples), ``anyOf [.., {"type":"null"}]`` and so on. Each
+provider accepts a different subset:
+
+* Gemini ``response_schema`` / function ``parameters``: OpenAPI-ish subset —
+ no ``$ref``, no ``additionalProperties``, no ``const``, no ``prefixItems``;
+ ``nullable`` instead of null unions; ``propertyOrdering`` controls key order.
+* OpenAI strict ``json_schema``: every object needs ``additionalProperties:
+ false`` and ``required`` listing every property; ``$defs`` are fine.
+* Anthropic tool ``input_schema`` / ``output_config.format``: standard JSON
+ schema; we inline refs to be safe and set ``additionalProperties: false``.
+
+All functions are pure and return new dicts (inputs are never mutated).
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+import re
+from typing import Any
+
+# keys Gemini's Schema type rejects or ignores
+_GEMINI_DROP = {
+ "title",
+ "default",
+ "examples",
+ "example",
+ "$schema",
+ "$id",
+ "additionalProperties",
+ "exclusiveMinimum",
+ "exclusiveMaximum",
+ "discriminator",
+ "readOnly",
+ "writeOnly",
+ "deprecated",
+ "uniqueItems",
+ "multipleOf",
+ "contentMediaType",
+ "contentEncoding",
+}
+
+
+# ----------------------------------------------------------------- $ref inline
+def inline_refs(schema: dict[str, Any]) -> dict[str, Any]:
+ """Return a copy with every local ``$ref`` (``#/$defs/X`` / ``#/definitions/X``)
+ replaced by the referenced definition and the defs tables removed.
+ Recursive schemas raise ``ValueError`` (providers can't express them anyway)."""
+ root = copy.deepcopy(schema)
+ defs: dict[str, Any] = {}
+ for table in ("$defs", "definitions"):
+ defs.update(root.pop(table, {}) or {})
+
+ def resolve(node: Any, stack: tuple[str, ...]) -> Any:
+ if isinstance(node, list):
+ return [resolve(n, stack) for n in node]
+ if not isinstance(node, dict):
+ return node
+ if "$ref" in node:
+ ref = node["$ref"]
+ name = ref.rsplit("/", 1)[-1]
+ if name not in defs:
+ raise ValueError(f"unresolvable $ref {ref!r}")
+ if name in stack:
+ raise ValueError(f"recursive $ref {ref!r} cannot be inlined")
+ merged = dict(defs[name])
+ # siblings of $ref (e.g. description) override the definition's
+ for k, v in node.items():
+ if k != "$ref":
+ merged[k] = v
+ return resolve(merged, stack + (name,))
+ return {k: resolve(v, stack) for k, v in node.items()}
+
+ return resolve(root, ())
+
+
+# ------------------------------------------------------------------- helpers
+def _is_null(s: Any) -> bool:
+ return (
+ isinstance(s, dict) and s.get("type") == "null" and len([k for k in s if k != "type"]) == 0
+ )
+
+
+def _merge_prefix_items(node: dict[str, Any]) -> dict[str, Any]:
+ """Tuples → arrays: ``prefixItems`` becomes ``items`` (union if heterogeneous)."""
+ items = node.pop("prefixItems")
+ if not isinstance(items, list) or not items:
+ return node
+ uniq: list[dict[str, Any]] = []
+ for it in items:
+ if it not in uniq:
+ uniq.append(it)
+ node["items"] = uniq[0] if len(uniq) == 1 else {"anyOf": uniq}
+ node.setdefault("minItems", len(items))
+ node.setdefault("maxItems", len(items))
+ return node
+
+
+# --------------------------------------------------------------------- gemini
+def to_gemini_schema(schema: dict[str, Any]) -> dict[str, Any]:
+ """Sanitise a pydantic JSON schema for ``GenerateContentConfig.response_schema``
+ / ``FunctionDeclaration.parameters`` (see module docstring)."""
+ root = inline_refs(schema)
+
+ def walk(node: Any) -> Any:
+ if isinstance(node, list):
+ return [walk(n) for n in node]
+ if not isinstance(node, dict):
+ return node
+ node = {k: v for k, v in node.items() if k not in _GEMINI_DROP}
+ # const → enum
+ if "const" in node:
+ node["enum"] = [node.pop("const")]
+ node.setdefault("type", _json_type(node["enum"][0]))
+ # type: ["string","null"] → type + nullable
+ if isinstance(node.get("type"), list):
+ types = [t for t in node["type"] if t != "null"]
+ if len(types) != len(node["type"]):
+ node["nullable"] = True
+ node["type"] = types[0] if len(types) == 1 else types
+ # anyOf/oneOf with null → nullable
+ for key in ("anyOf", "oneOf"):
+ if key in node:
+ variants = [v for v in node[key] if not _is_null(v)]
+ if len(variants) != len(node[key]):
+ node["nullable"] = True
+ if len(variants) == 1:
+ inner = walk(variants[0])
+ merged = {**inner, **{k: v for k, v in node.items() if k != key}}
+ node = merged
+ else:
+ node.pop(key)
+ node["anyOf"] = [walk(v) for v in variants]
+ if "allOf" in node and len(node["allOf"]) == 1:
+ inner = walk(node.pop("allOf")[0])
+ node = {**inner, **node}
+ if "prefixItems" in node:
+ node = _merge_prefix_items(node)
+ # enum values must be strings for Gemini; keep type consistent
+ if "enum" in node:
+ node["enum"] = [str(v) if not isinstance(v, str) else v for v in node["enum"]]
+ node["type"] = "string"
+ node.pop("format", None)
+ # format: only a few are accepted
+ if (
+ "format" in node
+ and node.get("type") == "string"
+ and node["format"] not in ("date-time", "enum")
+ ):
+ node.pop("format")
+ if "properties" in node:
+ props = {k: walk(v) for k, v in node["properties"].items()}
+ node["properties"] = props
+ node.setdefault("type", "object")
+ if props:
+ node["propertyOrdering"] = list(props.keys())
+ else:
+ # Gemini rejects empty OBJECT properties; describe as free-form
+ node.pop("properties")
+ node.pop("propertyOrdering", None)
+ if "items" in node:
+ node["items"] = walk(node["items"])
+ return node
+
+ return walk(root)
+
+
+def _json_type(value: Any) -> str:
+ if isinstance(value, bool):
+ return "boolean"
+ if isinstance(value, int):
+ return "integer"
+ if isinstance(value, float):
+ return "number"
+ if isinstance(value, str):
+ return "string"
+ if isinstance(value, list):
+ return "array"
+ return "object"
+
+
+# --------------------------------------------------------------------- openai
+def to_openai_strict_schema(schema: dict[str, Any]) -> dict[str, Any]:
+ """OpenAI *strict* structured outputs: every object gets
+ ``additionalProperties: false`` and ``required`` = all properties; optional
+ fields become nullable (``anyOf [T, null]``) so the contract still holds.
+ ``$defs`` are kept (supported) but inlined when a sibling ``$ref`` exists."""
+ root = inline_refs(schema)
+
+ def walk(node: Any) -> Any:
+ if isinstance(node, list):
+ return [walk(n) for n in node]
+ if not isinstance(node, dict):
+ return node
+ node = {
+ k: v for k, v in node.items() if k not in ("title", "default", "examples", "example")
+ }
+ if "prefixItems" in node:
+ node = _merge_prefix_items(node)
+ if "properties" in node:
+ props = {k: walk(v) for k, v in node["properties"].items()}
+ required = set(node.get("required", []))
+ for name, sub in props.items():
+ if name not in required:
+ props[name] = _nullable_union(sub)
+ node["properties"] = props
+ node["required"] = list(props.keys())
+ node["additionalProperties"] = False
+ node.setdefault("type", "object")
+ for key in ("anyOf", "oneOf", "allOf"):
+ if key in node:
+ node[key] = [walk(v) for v in node[key]]
+ if "items" in node:
+ node["items"] = walk(node["items"])
+ return node
+
+ return walk(root)
+
+
+def _nullable_union(sub: dict[str, Any]) -> dict[str, Any]:
+ if "anyOf" in sub:
+ if any(_is_null(v) for v in sub["anyOf"]):
+ return sub
+ return {**sub, "anyOf": sub["anyOf"] + [{"type": "null"}]}
+ if isinstance(sub.get("type"), list):
+ return sub if "null" in sub["type"] else {**sub, "type": sub["type"] + ["null"]}
+ if "type" in sub:
+ return {**sub, "type": [sub["type"], "null"]}
+ return {"anyOf": [sub, {"type": "null"}]}
+
+
+# ------------------------------------------------------------------ anthropic
+def to_anthropic_schema(schema: dict[str, Any]) -> dict[str, Any]:
+ """Standard JSON schema with refs inlined, tuples flattened and
+ ``additionalProperties: false`` on objects (tool ``input_schema`` / format)."""
+ root = inline_refs(schema)
+
+ def walk(node: Any) -> Any:
+ if isinstance(node, list):
+ return [walk(n) for n in node]
+ if not isinstance(node, dict):
+ return node
+ node = {
+ k: v for k, v in node.items() if k not in ("title", "default", "examples", "example")
+ }
+ if "prefixItems" in node:
+ node = _merge_prefix_items(node)
+ if "properties" in node:
+ node["properties"] = {k: walk(v) for k, v in node["properties"].items()}
+ node.setdefault("type", "object")
+ node.setdefault("additionalProperties", False)
+ for key in ("anyOf", "oneOf", "allOf"):
+ if key in node:
+ node[key] = [walk(v) for v in node[key]]
+ if "items" in node:
+ node["items"] = walk(node["items"])
+ return node
+
+ return walk(root)
+
+
+# ------------------------------------------------------------------ JSON parse
+_FENCE_RE = re.compile(r"```(?:json|JSON|javascript|js)?\s*\n?(.*?)```", re.DOTALL)
+
+
+class JsonParseError(ValueError):
+ """The model's text does not contain a parseable JSON value."""
+
+
+def parse_json_lenient(text: str) -> Any:
+ """Parse JSON from model text tolerating code fences, leading prose and
+ trailing chatter. Tries: whole text → fenced block → outermost {...} / [...]
+ span. Raises ``JsonParseError`` when nothing parses."""
+ if text is None:
+ raise JsonParseError("empty response")
+ s = text.strip()
+ if not s:
+ raise JsonParseError("empty response")
+ candidates: list[str] = [s]
+ for m in _FENCE_RE.finditer(s):
+ candidates.append(m.group(1).strip())
+ for opener, closer in (("{", "}"), ("[", "]")):
+ i, j = s.find(opener), s.rfind(closer)
+ if i != -1 and j > i:
+ candidates.append(s[i : j + 1])
+ last_err: Exception | None = None
+ for cand in candidates:
+ try:
+ return json.loads(cand)
+ except json.JSONDecodeError as exc:
+ last_err = exc
+ # tolerate trailing commas
+ fixed = re.sub(r",\s*([}\]])", r"\1", cand)
+ if fixed != cand:
+ try:
+ return json.loads(fixed)
+ except json.JSONDecodeError:
+ pass
+ raise JsonParseError(f"no JSON value found: {last_err} — head={s[:120]!r}")
diff --git a/harness/codeverse/orchestrator/__init__.py b/harness/codeverse/orchestrator/__init__.py
new file mode 100644
index 00000000..b4ae0da2
--- /dev/null
+++ b/harness/codeverse/orchestrator/__init__.py
@@ -0,0 +1 @@
+"""Orchestration primitives: stage runner with resume, round loop, fan-out, budget."""
diff --git a/harness/codeverse/orchestrator/budget.py b/harness/codeverse/orchestrator/budget.py
new file mode 100644
index 00000000..a28b6b40
--- /dev/null
+++ b/harness/codeverse/orchestrator/budget.py
@@ -0,0 +1,90 @@
+"""Budget guard: hard per-run ceilings on cost and wall time.
+
+Every model / agent call yields a ``Usage``; the track charges it here. When
+either ceiling is crossed ``BudgetExceeded`` is raised so the round loop can
+stop cleanly (status ``budget``) instead of silently overspending.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+
+from codeverse.contracts.common import Budget, Usage
+
+
+class BudgetExceeded(RuntimeError):
+ """Raised when a run crosses its USD or wall-clock ceiling."""
+
+ def __init__(self, reason: str, *, spent_usd: float, elapsed_min: float):
+ super().__init__(reason)
+ self.reason = reason
+ self.spent_usd = spent_usd
+ self.elapsed_min = elapsed_min
+
+
+class BudgetGuard:
+ """Thread-safe accumulator of ``Usage`` against a ``Budget``.
+
+ ``charge`` adds usage and then calls ``check``; ``check`` raises
+ ``BudgetExceeded`` when ``max_usd`` or ``max_minutes`` is exceeded.
+ """
+
+ def __init__(self, budget: Budget, start_time: float | None = None):
+ self.budget = budget
+ self.start_time = time.time() if start_time is None else start_time
+ self.spent = Usage()
+ self._lock = threading.Lock()
+ self.calls = 0
+
+ # ----------------------------------------------------------------- accounting
+ def charge(self, usage: Usage | None) -> None:
+ """Add ``usage`` to the running total, then enforce the ceilings."""
+ if usage is not None:
+ with self._lock:
+ self.spent = self.spent + usage
+ self.calls += 1
+ self.check()
+
+ def elapsed_minutes(self) -> float:
+ return (time.time() - self.start_time) / 60.0
+
+ def check(self) -> None:
+ """Raise ``BudgetExceeded`` if any ceiling has been crossed."""
+ spent = self.spent.cost_usd
+ elapsed = self.elapsed_minutes()
+ if spent > self.budget.max_usd:
+ raise BudgetExceeded(
+ f"cost ${spent:.3f} exceeds max_usd ${self.budget.max_usd:.2f}",
+ spent_usd=spent, elapsed_min=elapsed,
+ )
+ if elapsed > self.budget.max_minutes:
+ raise BudgetExceeded(
+ f"elapsed {elapsed:.1f} min exceeds max_minutes {self.budget.max_minutes:.1f}",
+ spent_usd=spent, elapsed_min=elapsed,
+ )
+
+ def ok(self) -> bool:
+ """True when no ceiling is crossed (non-raising variant of ``check``)."""
+ try:
+ self.check()
+ except BudgetExceeded:
+ return False
+ return True
+
+ def remaining(self) -> dict[str, float]:
+ """Remaining headroom: ``{"usd": ..., "minutes": ..., "fraction": ...}``."""
+ usd = max(0.0, self.budget.max_usd - self.spent.cost_usd)
+ minutes = max(0.0, self.budget.max_minutes - self.elapsed_minutes())
+ frac_usd = usd / self.budget.max_usd if self.budget.max_usd > 0 else 0.0
+ frac_min = minutes / self.budget.max_minutes if self.budget.max_minutes > 0 else 0.0
+ return {"usd": usd, "minutes": minutes, "fraction": min(frac_usd, frac_min)}
+
+ def summary(self) -> dict[str, float | int]:
+ return {
+ "spent_usd": round(self.spent.cost_usd, 4),
+ "elapsed_min": round(self.elapsed_minutes(), 2),
+ "calls": self.calls,
+ "input_tokens": self.spent.input_tokens,
+ "output_tokens": self.spent.output_tokens,
+ }
diff --git a/harness/codeverse/orchestrator/fanout.py b/harness/codeverse/orchestrator/fanout.py
new file mode 100644
index 00000000..f111d18d
--- /dev/null
+++ b/harness/codeverse/orchestrator/fanout.py
@@ -0,0 +1,102 @@
+"""Bounded parallel fan-out with per-item timing and error capture.
+
+``fan_out`` never raises for a failing item: the result list holds either the
+item's return value or the exception, in input order, so callers decide what a
+partial failure means (a failed asset is skipped; a failed part task is
+retried). Exceptions that are ``BaseException`` but not ``Exception``
+(KeyboardInterrupt, SystemExit) propagate.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from collections.abc import Callable, Iterable, Sequence
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass, field
+from typing import Any, TypeVar
+
+log = logging.getLogger(__name__)
+
+T = TypeVar("T")
+R = TypeVar("R")
+
+
+@dataclass
+class FanOutReport:
+ """Timing/outcome per item, for events and logs."""
+
+ label: str
+ n_items: int
+ n_ok: int
+ n_failed: int
+ durations_s: list[float] = field(default_factory=list)
+ total_s: float = 0.0
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "label": self.label, "n_items": self.n_items, "n_ok": self.n_ok,
+ "n_failed": self.n_failed, "total_s": round(self.total_s, 2),
+ "max_item_s": round(max(self.durations_s), 2) if self.durations_s else 0.0,
+ }
+
+
+def fan_out(
+ items: Sequence[T] | Iterable[T],
+ fn: Callable[[T], R],
+ max_workers: int = 4,
+ *,
+ label: str = "fanout",
+ item_name: Callable[[T], str] | None = None,
+ on_done: Callable[[int, T, R | Exception, float], None] | None = None,
+) -> list[R | Exception]:
+ """Run ``fn`` over ``items`` in a thread pool; return results in input order.
+
+ Each result is the return value or the raised ``Exception``. ``on_done``
+ (if given) is called from the worker thread with ``(index, item, result,
+ seconds)`` — keep it cheap and thread-safe (e.g. an EventLog.emit).
+ """
+ items = list(items)
+ results: list[R | Exception] = [None] * len(items) # type: ignore[list-item]
+ if not items:
+ return results
+ workers = max(1, min(max_workers, len(items)))
+ t_all = time.time()
+ durations = [0.0] * len(items)
+
+ def _run(i: int) -> None:
+ item = items[i]
+ name = item_name(item) if item_name else str(i)
+ t0 = time.time()
+ try:
+ out: R | Exception = fn(item)
+ except Exception as e: # noqa: BLE001 — captured per item by design
+ out = e
+ log.warning("%s[%s] failed: %s: %s", label, name, type(e).__name__, e)
+ dt = time.time() - t0
+ durations[i] = dt
+ results[i] = out
+ log.info("%s[%s] done in %.1fs (%s)", label, name, dt, "error" if isinstance(out, Exception) else "ok")
+ if on_done is not None:
+ on_done(i, item, out, dt)
+
+ if workers == 1:
+ for i in range(len(items)):
+ _run(i)
+ else:
+ with ThreadPoolExecutor(max_workers=workers, thread_name_prefix=label) as pool:
+ list(pool.map(_run, range(len(items))))
+
+ n_failed = sum(1 for r in results if isinstance(r, Exception))
+ report = FanOutReport(label, len(items), len(items) - n_failed, n_failed, durations, time.time() - t_all)
+ log.info("%s: %d/%d ok in %.1fs", label, report.n_ok, report.n_items, report.total_s)
+ return results
+
+
+def split_results(results: Sequence[R | Exception]) -> tuple[list[R], list[Exception]]:
+ """Separate successes from failures (order preserved within each list)."""
+ ok: list[R] = []
+ bad: list[Exception] = []
+ for r in results:
+ (bad if isinstance(r, Exception) else ok).append(r) # type: ignore[arg-type]
+ return ok, bad
diff --git a/harness/codeverse/orchestrator/rounds.py b/harness/codeverse/orchestrator/rounds.py
new file mode 100644
index 00000000..75dc9296
--- /dev/null
+++ b/harness/codeverse/orchestrator/rounds.py
@@ -0,0 +1,259 @@
+"""Round loop policy: when to stop, which round is best, what to refine next.
+
+All thresholds live in ``RoundPolicy`` (one calibrated object, no scattered
+ifs). ``StopPolicy.decide`` is a pure function of the round history;
+``BestSelector.pick`` is a pure function of the rounds; ``build_refine_
+instructions`` compiles gate errors + failed acceptance + the judge's
+improvement plan into typed ``RefineTask``s, and ``plan_parallel_groups``
+decides which tasks may run concurrently from file ownership.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import GateReport
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import AcceptanceItem, Plan
+from codeverse.contracts.run import RoundRecord
+from codeverse.conventions import to_snake
+
+log = logging.getLogger(__name__)
+
+StopReason = Literal["pass", "plateau", "budget", "continue", "max_rounds"]
+
+
+@dataclass(frozen=True)
+class RoundPolicy:
+ """Calibrated knobs for the refine loop."""
+
+ max_rounds: int = 4 # refine rounds AFTER the baseline
+ plateau_window: int = 2 # consecutive scored rounds without min_delta gain
+ min_delta: float = 0.02
+ target: float = 0.8 # rubric pass threshold (overridden from the rubric when known)
+ judge_on_gate_errors: bool = True # still judge when gates (not build) fail
+ max_refine_tasks: int = 6
+ parallel_min_tasks: int = 3 # fan out only when >= this many file-disjoint groups
+
+
+class StopPolicy:
+ """Decide whether the loop goes on. ``history`` = rounds so far (baseline first)."""
+
+ def __init__(self, policy: RoundPolicy):
+ self.policy = policy
+
+ def decide(self, history: Sequence[RoundRecord], *, budget_ok: bool = True) -> StopReason:
+ if not budget_ok:
+ return "budget"
+ if not history:
+ return "continue"
+ last = history[-1]
+ if last.judgment is not None and last.judgment.passed and last.judgment.overall >= self.policy.target:
+ return "pass"
+ refine_rounds = len(history) - 1
+ if refine_rounds >= self.policy.max_rounds:
+ return "max_rounds"
+ if self._plateaued(history):
+ return "plateau"
+ return "continue"
+
+ def _plateaued(self, history: Sequence[RoundRecord]) -> bool:
+ """True when the last ``plateau_window`` scored rounds did not raise the best
+ score by ``min_delta``. Rounds without a judgment (build failures) do not
+ count as evidence of a plateau: a pending repair explains a flat score."""
+ scored = [r for r in history if r.score is not None]
+ w = self.policy.plateau_window
+ if len(scored) < w + 1:
+ return False
+ before = max(r.score for r in scored[:-w]) # type: ignore[type-var]
+ after = max(r.score for r in scored[-w:]) # type: ignore[type-var]
+ return (after - before) < self.policy.min_delta
+
+
+class BestSelector:
+ """Best round = highest score, then fewer gate errors, then earlier.
+
+ Delegates to ``codeverse.judges.metrics.best_index`` when that exists so the
+ judge package owns the ranking rule; falls back to the local rule.
+ """
+
+ def pick(self, rounds: Sequence[RoundRecord]) -> int | None:
+ if not rounds:
+ return None
+ try:
+ from codeverse.judges.metrics import best_index # type: ignore[import-not-found]
+ except Exception: # noqa: BLE001 — optional dependency during bootstrap
+ best_index = None
+ scored = [(i, r) for i, r in enumerate(rounds) if r.score is not None]
+ if best_index is not None and scored:
+ try:
+ k = best_index([(float(r.score), gate_error_count(r)) for _, r in scored]) # type: ignore[arg-type]
+ return scored[int(k)][0]
+ except Exception: # noqa: BLE001 — never let a ranking helper kill a run
+ log.warning("judges.metrics.best_index failed; using local rule", exc_info=True)
+ return self._local_pick(rounds)
+
+ @staticmethod
+ def _local_pick(rounds: Sequence[RoundRecord]) -> int | None:
+ scored = [(i, r) for i, r in enumerate(rounds) if r.score is not None]
+ if scored:
+ return max(scored, key=lambda ir: (ir[1].score, -gate_error_count(ir[1]), -ir[0]))[0]
+ built = [i for i, r in enumerate(rounds) if r.build is not None and r.build.ok]
+ return built[-1] if built else None
+
+
+def gate_error_count(r: RoundRecord) -> int:
+ return sum(len(g.errors) for g in r.gates)
+
+
+# ----------------------------------------------------------------------------- refine tasks
+class RefineTask(BaseModel):
+ """One targeted change request compiled for the next round."""
+
+ target: str = Field(description="part / zone / asset / joint / camera / 'overall'")
+ kind: str = Field(description="geometry | assembly | material | articulation | bug | acceptance | ...")
+ instruction: str
+ priority: int = Field(ge=0, le=9, description="0 = gate error, 1 = failed must item, 2+ = judge")
+ files: list[str] = Field(default_factory=list, description="files this task may edit ([] = unknown/whole)")
+ source: Literal["gate", "acceptance", "judge"] = "judge"
+
+ def line(self) -> str:
+ files = f" (files: {', '.join(self.files)})" if self.files else ""
+ return f"[{self.source}/{self.kind}] {self.target}: {self.instruction}{files}"
+
+
+class TaskGroup(BaseModel):
+ """Tasks that must run together (they touch the same files)."""
+
+ tasks: list[RefineTask]
+ files: list[str] = Field(default_factory=list)
+
+ @property
+ def targets(self) -> list[str]:
+ seen: list[str] = []
+ for t in self.tasks:
+ if t.target not in seen:
+ seen.append(t.target)
+ return seen
+
+ @property
+ def label(self) -> str:
+ return "+".join(to_snake(t) for t in self.targets[:3]) or "refine"
+
+
+FileForTarget = Callable[[str], list[str]]
+
+
+def build_refine_instructions(
+ judgment: Judgment | None,
+ gates: Sequence[GateReport],
+ acceptance_failures: Sequence[AcceptanceItem],
+ plan: Plan | None,
+ *,
+ file_for_target: FileForTarget | None = None,
+ max_tasks: int = 6,
+) -> list[RefineTask]:
+ """Gate ERRORS first (with fix hints), then failed *must* acceptance items,
+ then the judge's improvement plan; de-duplicated by (target, kind), capped.
+ Gate/acceptance tasks are never dropped by the cap unless they alone exceed it."""
+ known = _known_targets(plan)
+ tasks: list[RefineTask] = []
+ seen: set[tuple[str, str]] = set()
+
+ def _add(t: RefineTask) -> None:
+ key = (to_snake(t.target), t.kind)
+ if key in seen:
+ return
+ seen.add(key)
+ t.target = _canon_target(t.target, known)
+ if file_for_target is not None and not t.files:
+ t.files = list(file_for_target(t.target))
+ tasks.append(t)
+
+ for g in gates:
+ for f in g.errors:
+ text = f.message if not f.fix_hint else f"{f.message} FIX: {f.fix_hint}"
+ _add(RefineTask(target=f.target or "overall", kind=f"gate:{g.gate}", instruction=text,
+ priority=0, source="gate"))
+ for a in acceptance_failures:
+ if a.priority != "must":
+ continue
+ _add(RefineTask(target=_acceptance_target(a, known), kind="acceptance",
+ instruction=f"Acceptance item {a.id} NOT met: {a.text}", priority=1,
+ source="acceptance"))
+ if judgment is not None:
+ for item in sorted(judgment.improvement_plan, key=lambda i: (i.priority, -i.expected_gain)):
+ _add(RefineTask(target=item.target or "overall", kind=item.kind, instruction=item.instruction,
+ priority=min(9, 1 + item.priority), source="judge"))
+ tasks.sort(key=lambda t: t.priority)
+ if len(tasks) > max_tasks:
+ protected = [t for t in tasks if t.source != "judge"]
+ rest = [t for t in tasks if t.source == "judge"]
+ tasks = (protected + rest)[:max(max_tasks, len(protected))]
+ return tasks
+
+
+def plan_parallel_groups(tasks: Sequence[RefineTask]) -> list[TaskGroup]:
+ """Group tasks by file ownership. Tasks with unknown files (``[]``) cannot
+ be isolated, so if any exists everything collapses into ONE group (a single
+ whole-object task). Otherwise groups are the connected components of the
+ "shares a file" relation — each group may run concurrently with the others."""
+ if not tasks:
+ return []
+ if any(not t.files for t in tasks):
+ files = sorted({f for t in tasks for f in t.files})
+ return [TaskGroup(tasks=list(tasks), files=files)]
+ parent = list(range(len(tasks)))
+
+ def find(i: int) -> int:
+ while parent[i] != i:
+ parent[i] = parent[parent[i]]
+ i = parent[i]
+ return i
+
+ owner: dict[str, int] = {}
+ for i, t in enumerate(tasks):
+ for f in t.files:
+ if f in owner:
+ parent[find(i)] = find(owner[f])
+ else:
+ owner[f] = i
+ groups: dict[int, list[RefineTask]] = {}
+ for i, t in enumerate(tasks):
+ groups.setdefault(find(i), []).append(t)
+ out = []
+ for members in groups.values():
+ files = sorted({f for t in members for f in t.files})
+ out.append(TaskGroup(tasks=members, files=files))
+ out.sort(key=lambda g: min(t.priority for t in g.tasks))
+ return out
+
+
+# ----------------------------------------------------------------------------- helpers
+def _known_targets(plan: Plan | None) -> dict[str, str]:
+ """snake → canonical name for every part/zone/asset/joint/camera in the plan."""
+ names: dict[str, str] = {}
+ if plan is None:
+ return names
+ for attr in ("parts", "joints", "zones", "assets", "cameras", "effects"):
+ for item in getattr(plan, attr, None) or []:
+ names[to_snake(item.name)] = item.name
+ return names
+
+
+def _canon_target(target: str, known: dict[str, str]) -> str:
+ return known.get(to_snake(target), target)
+
+
+def _acceptance_target(item: AcceptanceItem, known: dict[str, str]) -> str:
+ """Route a failed acceptance item to the part it names, else 'overall'."""
+ words = item.text.lower()
+ for snake, name in known.items():
+ if snake.replace("_", " ") in words or snake in words:
+ return name
+ return "overall"
diff --git a/harness/codeverse/orchestrator/runner.py b/harness/codeverse/orchestrator/runner.py
new file mode 100644
index 00000000..abbc8e99
--- /dev/null
+++ b/harness/codeverse/orchestrator/runner.py
@@ -0,0 +1,122 @@
+"""StageRunner: named, resumable stages with input-hash caching.
+
+A *stage* is ``fn() -> result``. The runner hashes the declared ``inputs``;
+when the hash matches the one recorded in ``RunState`` and the stage's result
+file (``<ws>/stages/<name>.json``) exists, the cached result is returned
+without running ``fn`` (content-addressed skip — no mtime heuristics).
+Results may be pydantic models, lists of models, plain JSON values, or
+``Path``s; pass ``model=`` to re-validate a cached JSON into its type.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+import time
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any, TypeVar
+
+from pydantic import BaseModel
+
+from codeverse.events import EventLog
+from codeverse.orchestrator.state import RunState, StageState
+from codeverse.workspace import Workspace
+
+T = TypeVar("T")
+
+_SAFE = re.compile(r"[^0-9A-Za-z._-]+")
+
+
+def hash_inputs(inputs: Any) -> str:
+ """Stable sha256 (12 hex) of arbitrary JSON-able inputs (pydantic ok)."""
+ payload = _jsonable(inputs)
+ blob = json.dumps(payload, sort_keys=True, default=str, ensure_ascii=False)
+ return hashlib.sha256(blob.encode()).hexdigest()[:12]
+
+
+def _jsonable(obj: Any) -> Any:
+ if isinstance(obj, BaseModel):
+ return obj.model_dump(mode="json")
+ if isinstance(obj, Path):
+ return str(obj)
+ if isinstance(obj, dict):
+ return {str(k): _jsonable(v) for k, v in obj.items()}
+ if isinstance(obj, (list, tuple, set)):
+ return [_jsonable(v) for v in obj]
+ return obj
+
+
+class StageError(RuntimeError):
+ """A stage function raised; the original exception is ``__cause__``."""
+
+
+class StageRunner:
+ """Runs stages with resume semantics on top of ``RunState`` + ``EventLog``."""
+
+ def __init__(self, ws: Workspace, events: EventLog, state: RunState | None = None):
+ self.ws = ws
+ self.events = events
+ self.state = state if state is not None else RunState()
+
+ # ----------------------------------------------------------------- paths
+ def result_path(self, name: str) -> Path:
+ return self.ws.root / "stages" / f"{_SAFE.sub('_', name)}.json"
+
+ # ----------------------------------------------------------------- api
+ def stage(
+ self,
+ name: str,
+ fn: Callable[[], T],
+ *,
+ inputs: Any = "",
+ force: bool = False,
+ model: type[BaseModel] | None = None,
+ list_of: type[BaseModel] | None = None,
+ ) -> T:
+ """Run ``fn`` unless a cached result for the same ``inputs`` exists."""
+ h = hash_inputs(inputs)
+ path = self.result_path(name)
+ prior = self.state.stages.get(name)
+ if not force and prior is not None and prior.inputs_hash == h and path.is_file():
+ data = json.loads(path.read_text())
+ result = _revive(data, model, list_of)
+ self.events.emit("stage.cached", stage=name, inputs_hash=h, path=str(path))
+ return result # type: ignore[return-value]
+
+ self.events.emit("stage.start", stage=name, inputs_hash=h)
+ t0 = time.time()
+ try:
+ result = fn()
+ except Exception as e:
+ self.events.emit("stage.failed", stage=name, error=f"{type(e).__name__}: {e}",
+ duration_s=round(time.time() - t0, 2))
+ raise
+ dt = time.time() - t0
+ path.parent.mkdir(parents=True, exist_ok=True)
+ self.ws.write_json(path, {"stage": name, "inputs_hash": h, "result": _jsonable(result)})
+ self.state.stages[name] = StageState(name=name, inputs_hash=h, result_path=str(path), duration_s=dt)
+ self.state.save(self.ws)
+ self.events.emit("stage.done", stage=name, inputs_hash=h, duration_s=round(dt, 2))
+ return result
+
+ def is_done(self, name: str, inputs: Any = "") -> bool:
+ prior = self.state.stages.get(name)
+ return prior is not None and prior.inputs_hash == hash_inputs(inputs) and self.result_path(name).is_file()
+
+ def invalidate(self, name: str) -> None:
+ self.state.stages.pop(name, None)
+ p = self.result_path(name)
+ if p.exists():
+ p.unlink()
+ self.state.save(self.ws)
+
+
+def _revive(data: dict[str, Any], model: type[BaseModel] | None, list_of: type[BaseModel] | None) -> Any:
+ result = data.get("result")
+ if model is not None and isinstance(result, dict):
+ return model.model_validate(result)
+ if list_of is not None and isinstance(result, list):
+ return [list_of.model_validate(r) for r in result]
+ return result
diff --git a/harness/codeverse/orchestrator/state.py b/harness/codeverse/orchestrator/state.py
new file mode 100644
index 00000000..d73f77fd
--- /dev/null
+++ b/harness/codeverse/orchestrator/state.py
@@ -0,0 +1,88 @@
+"""Persistent run state (``run_state.json``): what is done, what is best.
+
+The state is the resume anchor. It records, per stage, the hash of the inputs
+it ran with (so ``StageRunner`` can reuse a cached result), the rounds that
+completed, and the best round/commit seen so far. Writes are atomic
+(tmp + rename via ``Workspace.write_json``).
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from typing import Any
+
+from pydantic import BaseModel, Field, ValidationError
+
+from codeverse.contracts.run import RunStatus
+from codeverse.workspace import Workspace
+
+
+class StageState(BaseModel):
+ """One completed stage: inputs hash + where its result JSON lives."""
+
+ name: str
+ inputs_hash: str
+ result_path: str = ""
+ finished_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
+ duration_s: float = 0.0
+
+
+class RunState(BaseModel):
+ """Everything the orchestrator needs to resume a run."""
+
+ status: RunStatus = RunStatus.PLANNING
+ stages: dict[str, StageState] = Field(default_factory=dict)
+ current_round: int = Field(default=0, description="index of the round in progress / next to run")
+ completed_rounds: list[int] = Field(default_factory=list)
+ round_commits: dict[int, str] = Field(default_factory=dict)
+ best_round: int | None = None
+ best_commit: str = ""
+ best_score: float | None = None
+ materialized_for: str = Field(default="", description="agent kind the workspace was materialised for")
+ stop_reason: str = ""
+ error: str = ""
+ started_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
+ updated_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
+ extra: dict[str, Any] = Field(default_factory=dict)
+
+ # ----------------------------------------------------------------- persistence
+ @classmethod
+ def load(cls, ws: Workspace) -> RunState | None:
+ """Return the saved state or ``None`` when the file is absent."""
+ if not ws.state_path.is_file():
+ return None
+ try:
+ return cls.model_validate(ws.read_json(ws.state_path))
+ except (ValidationError, ValueError) as e:
+ raise StateCorrupt(f"{ws.state_path}: {e}") from e
+
+ @classmethod
+ def load_or_new(cls, ws: Workspace, *, resume: bool) -> RunState:
+ if resume:
+ st = cls.load(ws)
+ if st is not None:
+ return st
+ return cls()
+
+ def save(self, ws: Workspace) -> None:
+ self.updated_at = datetime.now(UTC)
+ ws.write_json(ws.state_path, self)
+
+ # ----------------------------------------------------------------- helpers
+ def mark_round_done(self, index: int, commit: str, ws: Workspace | None = None) -> None:
+ if index not in self.completed_rounds:
+ self.completed_rounds.append(index)
+ self.round_commits[index] = commit
+ self.current_round = index + 1
+ if ws is not None:
+ self.save(ws)
+
+ def update_best(self, index: int, commit: str, score: float | None) -> bool:
+ """Record ``index`` as best; returns True when it changed."""
+ changed = self.best_round != index
+ self.best_round, self.best_commit, self.best_score = index, commit, score
+ return changed
+
+
+class StateCorrupt(RuntimeError):
+ """``run_state.json`` exists but does not validate — refuse to guess."""
diff --git a/harness/codeverse/prompts/__init__.py b/harness/codeverse/prompts/__init__.py
new file mode 100644
index 00000000..e8fee67e
--- /dev/null
+++ b/harness/codeverse/prompts/__init__.py
@@ -0,0 +1,43 @@
+"""Prompt loader: markdown + jinja2 templates, content-hashed for provenance."""
+
+from __future__ import annotations
+
+import hashlib
+from functools import lru_cache
+from pathlib import Path
+from typing import Any
+
+from jinja2 import Environment, FileSystemLoader, StrictUndefined
+
+PROMPTS_DIR = Path(__file__).resolve().parent
+
+_env = Environment(
+ loader=FileSystemLoader(str(PROMPTS_DIR)),
+ undefined=StrictUndefined,
+ trim_blocks=True,
+ lstrip_blocks=True,
+ keep_trailing_newline=True,
+ autoescape=False,
+)
+
+
+@lru_cache(maxsize=256)
+def load_text(rel_path: str) -> str:
+ """Raw prompt text, e.g. ``load_text("blender/cookbook.md")``."""
+ p = PROMPTS_DIR / rel_path
+ if not p.is_file():
+ raise FileNotFoundError(f"prompt not found: {rel_path}")
+ return p.read_text()
+
+
+def render(rel_path: str, **ctx: Any) -> str:
+ """Render a jinja template under prompts/ with ``ctx``."""
+ return _env.get_template(rel_path).render(**ctx)
+
+
+def prompt_hash(text: str) -> str:
+ return hashlib.sha256(text.encode()).hexdigest()[:12]
+
+
+def list_prompts() -> list[str]:
+ return sorted(str(p.relative_to(PROMPTS_DIR)) for p in PROMPTS_DIR.rglob("*") if p.suffix in (".md", ".j2", ".txt", ".py", ".js"))
diff --git a/harness/codeverse/prompts/blender/contract.md b/harness/codeverse/prompts/blender/contract.md
new file mode 100644
index 00000000..f7607270
--- /dev/null
+++ b/harness/codeverse/prompts/blender/contract.md
@@ -0,0 +1,101 @@
+# Blender (bpy) authoring contract — track `static_object`, language `blender`
+
+## Files
+* `src/model.py` — ONE pure-bpy script. The harness runs it with
+ `blender -b --factory-startup --python wrappers/run_bpy.py -- --script src/model.py`
+ inside an **emptied scene**, then applies transforms, takes a census, exports
+ `artifacts/object.glb` (Y-up) and `object.stl`. You never export or render.
+
+## Frame, units, placement
+* **Z is up, -Y is the front, +X is the right. Meters.** (glTF export maps this to
+ Y-up / +Z-front automatically — do not pre-rotate.)
+* The object stands on z = 0 (lowest vertex at z = 0 ± 1 mm), footprint centred on the
+ Z axis. Real-world dimensions (a chair seat at z ≈ 0.45, a table top at z ≈ 0.75).
+
+## Naming and structure
+* One Blender **object per plan part**, `obj.name = "<PartName>"` in PascalCase exactly
+ as the plan says (`SeatCushion`, `LeftFrontLeg`). Blender auto-suffixes duplicates
+ (`Leg.001`) — that is a contract violation: give every instance its own unique plan name
+ (`LegFrontLeft`, `LegFrontRight`, …) or the plan's `<Name>1..N`.
+* Meshes only (no empties as parts, no curves left un-converted, no cameras/lights).
+ Link every object to `bpy.context.scene.collection` (or a child collection).
+* Put part-local helpers in functions: `build_<snake>() -> bpy.types.Object`; call them
+ from a `main()` at the bottom; `main()` is executed at import time (module level call).
+
+## Allowed imports
+`bpy`, `bmesh`, `mathutils`, `math`, `random`, `itertools`, `functools`, `typing`,
+`dataclasses`. Nothing else (no numpy loops over vertices, no os/sys/subprocess/
+urllib/socket/pathlib, no `import codeverse`).
+
+## Forbidden calls
+`bpy.ops.render.*`, `bpy.ops.export_*`, `bpy.ops.import_*`, `bpy.ops.wm.*`,
+`bpy.ops.image.*`, `bpy.ops.screen.*`, `bpy.ops.view3d.*`, `bpy.data.libraries`,
+`bpy.app.timers`, `open(`, `exec(`, `eval(`, `__import__`, any camera / light creation,
+any `input()` / network / file write. Do not touch `bpy.context.scene.render` or
+`scene.world` — the harness owns render settings.
+
+## Limits
+≤ 600 k triangles total (aim 20–150 k); subdivision levels ≤ 2; no boolean chains > 12
+cutters per object; script finishes in < 120 s headless.
+
+## Self-check (do this at the end of `main()`)
+```python
+import bpy
+def _selfcheck() -> None:
+ meshes = [o for o in bpy.data.objects if o.type == 'MESH']
+ assert meshes, "no mesh objects built"
+ for o in meshes:
+ assert '.' not in o.name, f"auto-suffixed name {o.name!r}: rename the instance"
+```
+
+## COMPLETE minimal example (verified with Blender 5.0 headless)
+```python
+import bpy, bmesh, math
+
+SEAT_D, SEAT_T, SEAT_Z = 0.34, 0.04, 0.45 # metres, from the plan
+LEG_R, LEG_N, LEG_RING = 0.02, 3, 0.12
+
+def _link(obj: bpy.types.Object) -> bpy.types.Object:
+ bpy.context.scene.collection.objects.link(obj)
+ return obj
+
+def make_cylinder(name: str, radius: float, depth: float, location, segments: int = 32):
+ """Cylinder along Z centred at `location` via bmesh (no operator/context needed)."""
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=segments,
+ radius1=radius, radius2=radius, depth=depth)
+ me = bpy.data.meshes.new(name)
+ bm.to_mesh(me); bm.free()
+ obj = bpy.data.objects.new(name, me)
+ obj.location = location
+ return _link(obj)
+
+def make_material(name: str, rgb, roughness=0.5, metallic=0.0) -> bpy.types.Material:
+ mat = bpy.data.materials.new(name)
+ bsdf = mat.node_tree.nodes["Principled BSDF"] # nodes exist by default (4.x/5.x)
+ bsdf.inputs["Base Color"].default_value = (*rgb, 1.0)
+ bsdf.inputs["Roughness"].default_value = roughness
+ bsdf.inputs["Metallic"].default_value = metallic
+ return mat
+
+def build_seat() -> bpy.types.Object:
+ seat = make_cylinder("Seat", SEAT_D / 2, SEAT_T, (0, 0, SEAT_Z - SEAT_T / 2), 48)
+ bev = seat.modifiers.new("Bevel", 'BEVEL'); bev.width = 0.006; bev.segments = 3
+ seat.data.materials.append(make_material("Wood", (0.55, 0.33, 0.16), 0.6))
+ return seat
+
+def build_leg(i: int) -> bpy.types.Object:
+ a = 2 * math.pi * i / LEG_N
+ x, y = LEG_RING * math.cos(a), LEG_RING * math.sin(a)
+ h = SEAT_Z - SEAT_T + 0.004 # overlaps the seat by 4 mm (weld)
+ leg = make_cylinder(f"Leg{i + 1}", LEG_R, h, (x, y, h / 2), 24)
+ leg.data.materials.append(make_material(f"Steel{i + 1}", (0.6, 0.6, 0.62), 0.35, 1.0))
+ return leg
+
+def main() -> None:
+ build_seat()
+ for i in range(LEG_N):
+ build_leg(i)
+
+main()
+```
diff --git a/harness/codeverse/prompts/blender/cookbook.md b/harness/codeverse/prompts/blender/cookbook.md
new file mode 100644
index 00000000..c8ca5ee5
--- /dev/null
+++ b/harness/codeverse/prompts/blender/cookbook.md
@@ -0,0 +1,601 @@
+# Blender (bpy) cookbook — static objects, Blender 4.2–5.x headless
+
+Every snippet below runs as-is in `blender -b --factory-startup` (they are executed in
+order by the harness test suite). Z-up, −Y front, meters, PascalCase object names.
+Use `read_cookbook(section="<heading>")` to fetch one chapter.
+
+## Skeleton
+
+A well-structured `src/model.py`: constants on top, tiny data-API helpers, one
+`build_<part>()` per plan part returning the object, `main()` at the bottom.
+
+```python
+import bpy, bmesh, math, random
+from mathutils import Vector, Matrix
+
+random.seed(0) # deterministic everywhere
+
+# ---- plan numbers (metres) --------------------------------------------------
+MUG_R, MUG_H, WALL = 0.042, 0.095, 0.004
+HANDLE_R, HANDLE_TUBE = 0.030, 0.007
+
+# ---- helpers ----------------------------------------------------------------
+def link(obj: bpy.types.Object) -> bpy.types.Object:
+ """Link into the scene collection (data-API objects are not linked by default)."""
+ bpy.context.scene.collection.objects.link(obj)
+ return obj
+
+def obj_from_bmesh(name: str, bm: bmesh.types.BMesh, location=(0, 0, 0)) -> bpy.types.Object:
+ """bmesh → mesh → object, freed and linked. Name is the PLAN part name."""
+ me = bpy.data.meshes.new(name)
+ bm.to_mesh(me); bm.free(); me.update()
+ o = bpy.data.objects.new(name, me)
+ o.location = location
+ return link(o)
+
+def activate(obj: bpy.types.Object) -> None:
+ """Make `obj` the only selected + active object (needed before ANY bpy.ops)."""
+ bpy.ops.object.select_all(action='DESELECT')
+ obj.select_set(True)
+ bpy.context.view_layer.objects.active = obj
+
+def apply_modifiers(obj: bpy.types.Object) -> None:
+ """Apply every modifier in stack order (headless-safe via temp_override)."""
+ if obj.data.users > 1: # linked duplicates cannot be applied
+ obj.data = obj.data.copy()
+ for m in list(obj.modifiers):
+ with bpy.context.temp_override(object=obj, active_object=obj,
+ selected_objects=[obj], selected_editable_objects=[obj]):
+ bpy.ops.object.modifier_apply(modifier=m.name)
+
+def apply_transforms(obj: bpy.types.Object) -> None:
+ """Bake location+rotation+scale into the mesh (all three explicit!)."""
+ activate(obj)
+ bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)
+```
+
+## Primitives (data API, no operator context)
+
+`bmesh.ops.create_*` never depends on selection/active object, so it is safe in loops.
+Primitives are centred on their origin; translate with `location`.
+
+```python
+def make_box(name, size, location=(0, 0, 0)) -> bpy.types.Object:
+ """Axis-aligned box, size=(sx, sy, sz) full extents, centred at `location`."""
+ bm = bmesh.new()
+ bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.scale(bm, vec=size, verts=bm.verts)
+ return obj_from_bmesh(name, bm, location)
+
+def make_cylinder(name, radius, depth, location=(0, 0, 0), segments=32, radius2=None, rings=1):
+ """Cylinder (or cone when radius2 given) along local Z, centred at `location`.
+ rings > 1 subdivides the length (needed before bending / lattice deforms)."""
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, cap_tris=False, segments=segments,
+ radius1=radius, radius2=radius if radius2 is None else radius2, depth=depth)
+ if rings > 1:
+ side = [e for e in bm.edges if abs(e.verts[0].co.z - e.verts[1].co.z) > 1e-9]
+ bmesh.ops.subdivide_edges(bm, edges=side, cuts=rings - 1, use_grid_fill=True)
+ return obj_from_bmesh(name, bm, location)
+
+def make_sphere(name, radius, location=(0, 0, 0), segments=32, rings=16):
+ bm = bmesh.new()
+ bmesh.ops.create_uvsphere(bm, u_segments=segments, v_segments=rings, radius=radius)
+ return obj_from_bmesh(name, bm, location)
+
+def make_torus(name, major_r, minor_r, location=(0, 0, 0), major_seg=48, minor_seg=16):
+ """Torus in the XY plane (operator version — fine headless, then we capture the object)."""
+ bpy.ops.mesh.primitive_torus_add(major_radius=major_r, minor_radius=minor_r,
+ major_segments=major_seg, minor_segments=minor_seg,
+ location=location)
+ o = bpy.context.active_object
+ o.name = name
+ return o
+
+def make_tube(name, radius, wall, depth, location=(0, 0, 0), segments=48):
+ """Hollow open tube: outer cylinder minus inner, via bmesh solidify of a shell."""
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=False, segments=segments,
+ radius1=radius, radius2=radius, depth=depth)
+ bmesh.ops.solidify(bm, geom=bm.faces[:], thickness=wall)
+ return obj_from_bmesh(name, bm, location)
+
+# quick demo (the harness test runs this): a mug body + ring handle
+body = make_cylinder("MugBody", MUG_R, MUG_H, (0, 0, MUG_H / 2), 48)
+handle = make_torus("MugHandle", HANDLE_R, HANDLE_TUBE, (MUG_R + HANDLE_R - 0.004, 0, MUG_H * 0.55))
+handle.rotation_euler = (math.radians(90), 0, 0) # stand the ring up in the XZ plane
+```
+
+Why: operators (`bpy.ops.mesh.primitive_cube_add`) change selection, need a context and
+use `size=2` by default (a 2 m cube!) — data-API primitives avoid all three traps.
+Numbers: 24–48 segments for visible cylinders, 8–12 for thin rods/bolts.
+
+## Origins and placement
+
+```python
+def set_origin_to_bottom(obj: bpy.types.Object) -> None:
+ """Move the origin to the bottom-centre of the mesh (world pose unchanged)."""
+ me = obj.data
+ xs = [v.co.x for v in me.vertices]; ys = [v.co.y for v in me.vertices]; zs = [v.co.z for v in me.vertices]
+ c = Vector(((min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, min(zs)))
+ me.transform(Matrix.Translation(-c))
+ obj.matrix_world = obj.matrix_world @ Matrix.Translation(c)
+
+def world_bbox(obj: bpy.types.Object):
+ """(min, max) Vectors of the evaluated world-space bbox."""
+ bpy.context.view_layer.update()
+ pts = [obj.matrix_world @ Vector(c) for c in obj.bound_box]
+ return (Vector(map(min, zip(*pts))), Vector(map(max, zip(*pts))))
+
+def drop_to_ground(objs) -> None:
+ """Translate the whole assembly so its lowest point is z = 0."""
+ zmin = min(world_bbox(o)[0].z for o in objs)
+ for o in objs:
+ o.location.z -= zmin
+
+set_origin_to_bottom(body)
+print("mug bbox", world_bbox(body))
+```
+
+Why: `obj.dimensions` ignores rotation; `bound_box` is object-space — always go through
+`matrix_world` and `view_layer.update()` after changing transforms.
+
+## Modifiers (bevel, boolean, array, mirror, solidify, screw, subsurf)
+
+Add with `obj.modifiers.new(name, TYPE)`, set properties, then `apply_modifiers(obj)`
+when you need the final mesh (booleans, joins, exports all behave better applied).
+
+```python
+def add_bevel(obj, width=0.003, segments=3, angle_deg=30.0):
+ """Rounded edges: the single cheapest realism upgrade. width < half the thinnest wall."""
+ b = obj.modifiers.new("Bevel", 'BEVEL')
+ b.width = width; b.segments = segments
+ b.limit_method = 'ANGLE'; b.angle_limit = math.radians(angle_deg)
+ b.harden_normals = False
+ return b
+
+def boolean_cut(obj, cutter, solver='MANIFOLD') -> None:
+ """obj -= cutter, applied, cutter deleted. MANIFOLD (5.0+) is fast + robust on closed
+ meshes; fall back to EXACT when inputs are not watertight. Cutter must overshoot the
+ face it pierces by ≥ 5 mm, never be coplanar with it."""
+ m = obj.modifiers.new("Cut", 'BOOLEAN')
+ m.operation = 'DIFFERENCE'; m.object = cutter
+ solvers = m.bl_rna.properties["solver"].enum_items.keys() # 4.2: FAST/EXACT; 5.0: +MANIFOLD
+ m.solver = solver if solver in solvers else 'EXACT'
+ try:
+ apply_modifiers(obj)
+ except RuntimeError: # MANIFOLD refused (non-manifold input)
+ m = obj.modifiers.new("Cut", 'BOOLEAN'); m.operation = 'DIFFERENCE'; m.object = cutter
+ m.solver = 'EXACT'; apply_modifiers(obj)
+ bpy.data.objects.remove(cutter, do_unlink=True)
+
+def boolean_union(obj, other) -> None:
+ m = obj.modifiers.new("Union", 'BOOLEAN'); m.operation = 'UNION'; m.object = other
+ m.solver = 'EXACT'; apply_modifiers(obj)
+ bpy.data.objects.remove(other, do_unlink=True)
+
+def add_array(obj, count, offset_xyz):
+ a = obj.modifiers.new("Array", 'ARRAY'); a.count = count
+ a.use_relative_offset = False; a.use_constant_offset = True
+ a.constant_offset_displace = offset_xyz
+ return a
+
+def add_mirror(obj, axis='X', bisect=False):
+ """Mirror across the OBJECT ORIGIN plane (put the origin on the symmetry plane!)."""
+ m = obj.modifiers.new("Mirror", 'MIRROR')
+ idx = 'XYZ'.index(axis)
+ m.use_axis = [i == idx for i in range(3)]
+ m.use_bisect_axis = [bisect and i == idx for i in range(3)]
+ m.use_clip = True; m.merge_threshold = 0.0005
+ return m
+
+def add_solidify(obj, thickness=0.003, inward=True):
+ s = obj.modifiers.new("Solidify", 'SOLIDIFY')
+ s.thickness = thickness; s.offset = -1 if inward else 1; s.use_even_offset = True
+ return s
+
+def add_subsurf(obj, levels=1):
+ s = obj.modifiers.new("Subsurf", 'SUBSURF'); s.levels = levels; s.render_levels = levels
+ return s
+
+# demo: hollow the mug with a boolean, bevel the rim, mirror a pair of feet
+cutter = make_cylinder("MugCutter", MUG_R - WALL, MUG_H, (0, 0, MUG_H / 2 + WALL + 0.005), 48)
+boolean_cut(body, cutter)
+add_bevel(body, 0.0015, 2)
+apply_modifiers(body)
+foot = make_box("FootL", (0.02, 0.02, 0.01), (0, 0, 0.005))
+foot.data.transform(Matrix.Translation((-0.03, 0, 0))) # mesh offset so the origin stays on x=0
+add_mirror(foot, 'X'); apply_modifiers(foot); foot.name = "Feet"
+```
+
+Why: `MANIFOLD` is ~10× faster and never produces slivers but needs watertight inputs;
+`EXACT` is the universal fallback; never use `FLOAT`/`FAST` (self-intersections).
+Array/mirror/screw results are *one object* — correct for repeated detail that belongs to one part.
+
+## Screw and lathe (rotational parts: bottles, vases, knobs, threads)
+
+```python
+def lathe(name, profile_xz, segments=48, location=(0, 0, 0)) -> bpy.types.Object:
+ """Revolve a polyline profile [(r, z), ...] about Z into a closed solid.
+ Profile runs from the axis (r = 0) at the bottom up and back to the axis at the top."""
+ bm = bmesh.new()
+ verts = [bm.verts.new((r, 0.0, z)) for r, z in profile_xz]
+ edges = [bm.edges.new((a, b)) for a, b in zip(verts, verts[1:])] # spin needs EDGES
+ bmesh.ops.spin(bm, geom=verts + edges, cent=(0, 0, 0), axis=(0, 0, 1),
+ angle=2 * math.pi, steps=segments, use_merge=True)
+ bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-6) # weld the seam + axis points
+ bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
+ return obj_from_bmesh(name, bm, location)
+
+bottle = lathe("Bottle", [(0.0, 0.0), (0.032, 0.0), (0.034, 0.010), (0.034, 0.16),
+ (0.014, 0.21), (0.014, 0.25), (0.0, 0.25)])
+bottle.data.shade_smooth()
+
+def add_screw_thread(profile_obj, turns=6, pitch=0.002, steps=24):
+ """Thread from a small profile polygon placed at radius r: SCREW modifier."""
+ s = profile_obj.modifiers.new("Screw", 'SCREW')
+ s.angle = math.radians(360 * turns); s.screw_offset = pitch * turns
+ s.steps = steps; s.render_steps = steps; s.iterations = 1; s.axis = 'Z'
+ s.use_merge_vertices = True
+ return s
+```
+
+Why: revolved profiles give smooth, correct silhouettes for anything round; one list of
+(r, z) points is the whole shape. Segments 48 for hero parts, 24 for small knobs.
+
+## Curves → tubes, ropes, cables, rails
+
+```python
+def make_tube_along(name, points, radius, resolution=12, smooth=True) -> bpy.types.Object:
+ """Round tube following `points` (world coords), converted to a real mesh."""
+ cu = bpy.data.curves.new(name, 'CURVE')
+ cu.dimensions = '3D'; cu.bevel_depth = radius; cu.bevel_resolution = resolution // 2
+ cu.use_fill_caps = True; cu.resolution_u = 12
+ sp = cu.splines.new('NURBS' if smooth else 'POLY')
+ sp.points.add(len(points) - 1)
+ for p, (x, y, z) in zip(sp.points, points):
+ p.co = (x, y, z, 1.0)
+ if smooth:
+ sp.use_endpoint_u = True; sp.order_u = min(4, len(points))
+ o = link(bpy.data.objects.new(name, cu))
+ with bpy.context.temp_override(object=o, active_object=o, selected_objects=[o],
+ selected_editable_objects=[o]):
+ bpy.ops.object.convert(target='MESH')
+ bm = bmesh.new(); bm.from_mesh(o.data) # weld the bevel seam (else 1 island per strip)
+ bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-6)
+ bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
+ bm.to_mesh(o.data); bm.free(); o.data.update()
+ return o
+
+cable = make_tube_along("Cable", [(0.05, 0, 0.30), (0.10, 0.02, 0.20), (0.18, 0.0, 0.08),
+ (0.30, -0.03, 0.01)], radius=0.004)
+```
+
+Why: a NURBS curve with `bevel_depth` is the cheapest correct pipe/rope; convert to mesh
+so the exporter sees geometry. Radius 3–6 mm cables, 10–25 mm rails, 20–40 mm pipes.
+
+## Deformation (bend, taper, lattice)
+
+```python
+def bend(obj, angle_deg, axis='X'):
+ """Bend a Z-long part (pipe elbow, bow, hook) AROUND `axis` (X or Y, perpendicular to
+ its length). The bend starts at the OBJECT ORIGIN: put the origin at one end and
+ give the mesh ≥ 16 rings along its length (make_cylinder(..., rings=24))."""
+ d = obj.modifiers.new("Bend", 'SIMPLE_DEFORM'); d.deform_method = 'BEND'
+ d.angle = math.radians(angle_deg); d.deform_axis = axis
+ return d
+
+def taper(obj, factor=0.5, axis='Z'):
+ d = obj.modifiers.new("Taper", 'SIMPLE_DEFORM'); d.deform_method = 'TAPER'
+ d.factor = factor; d.deform_axis = axis
+ return d
+
+def lattice_squash(obj, scale_xyz, points=3):
+ """Free-form squash/stretch via a lattice fitted to the object's bbox."""
+ lat = bpy.data.lattices.new(obj.name + "Lat")
+ lat.points_u = lat.points_v = lat.points_w = points
+ lo = link(bpy.data.objects.new(obj.name + "Lat", lat))
+ lo.location = obj.location; lo.scale = obj.dimensions
+ m = obj.modifiers.new("Lattice", 'LATTICE'); m.object = lo
+ return lo, m
+
+pipe = make_cylinder("Elbow", 0.012, 0.20, (0.2, 0.2, 0.0), 24, rings=24)
+pipe.data.transform(Matrix.Translation((0, 0, 0.10))) # mesh now spans z 0..0.2 from the origin
+bend(pipe, 90, 'X'); apply_modifiers(pipe) # quarter-circle elbow, r ≈ 0.127
+```
+
+Why: SIMPLE_DEFORM bends relative to the object origin and needs ≥ 16 loops along the
+length; a centred origin gives a symmetric "C" (±angle/2), an end origin a clean arc.
+
+## Subdivision + creases (smooth organic parts with sharp seams)
+
+```python
+def crease_edges(obj, predicate, value=1.0):
+ """Set crease on edges where predicate(v1, v2) is True (data attribute API, 4.x+)."""
+ me = obj.data
+ attr = me.attributes.get("crease_edge") or me.attributes.new("crease_edge", 'FLOAT', 'EDGE')
+ for e, slot in zip(me.edges, attr.data):
+ v1, v2 = me.vertices[e.vertices[0]].co, me.vertices[e.vertices[1]].co
+ slot.value = value if predicate(v1, v2) else 0.0
+
+cushion = make_box("Cushion", (0.40, 0.40, 0.08), (0.6, 0, 0.04))
+crease_edges(cushion, lambda a, b: abs(a.z - b.z) < 1e-6 and a.z > 0.0) # keep the top rim crisp
+add_subsurf(cushion, 2); apply_modifiers(cushion); cushion.data.shade_smooth()
+```
+
+Why: a box + subsurf 2 + creases = cushion/pillow/soft shell in four lines; without the
+crease it becomes a blob.
+
+## Materials (Principled BSDF; flat PBR survives GLB export)
+
+GLB keeps ONLY base colour, metallic, roughness, emission, alpha and normal *textures*.
+Procedural node trees (noise, wave) are NOT exported — use them only for your own
+preview, and prefer flat PBR + geometry detail + vertex colours for anything judged.
+
+```python
+def make_pbr(name, rgb, roughness=0.5, metallic=0.0, emission=None, alpha=1.0):
+ mat = bpy.data.materials.new(name) # node tree exists by default
+ bsdf = mat.node_tree.nodes["Principled BSDF"]
+ bsdf.inputs["Base Color"].default_value = (*rgb, 1.0)
+ bsdf.inputs["Roughness"].default_value = roughness
+ bsdf.inputs["Metallic"].default_value = metallic
+ if emission:
+ bsdf.inputs["Emission Color"].default_value = (*emission, 1.0)
+ bsdf.inputs["Emission Strength"].default_value = 3.0
+ if alpha < 1.0:
+ bsdf.inputs["Alpha"].default_value = alpha
+ mat.surface_render_method = 'BLENDED' # 4.2+; blend_method is gone
+ return mat
+
+PALETTE = { # rgb 0-1 linear, roughness, metallic
+ "oak": ((0.55, 0.36, 0.18), 0.55, 0.0),
+ "walnut": ((0.28, 0.17, 0.09), 0.50, 0.0),
+ "steel": ((0.62, 0.63, 0.65), 0.30, 1.0),
+ "brass": ((0.83, 0.62, 0.28), 0.35, 1.0),
+ "black_plastic": ((0.02, 0.02, 0.02), 0.45, 0.0),
+ "white_ceramic": ((0.92, 0.92, 0.90), 0.15, 0.0),
+ "fabric": ((0.35, 0.40, 0.55), 0.95, 0.0),
+ "glass": ((0.85, 0.90, 0.95), 0.05, 0.0), # + alpha 0.25
+ "rubber": ((0.05, 0.05, 0.05), 0.85, 0.0),
+}
+def assign(obj, key):
+ rgb, rough, metal = PALETTE[key]
+ obj.data.materials.append(make_pbr(f"{obj.name}_{key}", rgb, rough, metal))
+
+assign(body, "white_ceramic"); assign(handle, "white_ceramic"); assign(bottle, "glass")
+
+def vertex_color_by_height(obj, low_rgb, high_rgb, name="Col"):
+ """Per-vertex colour gradient (exported to GLB as COLOR_0; set vertexColors in viewers)."""
+ me = obj.data
+ zs = [v.co.z for v in me.vertices]; z0, z1 = min(zs), max(zs) or 1e-6
+ col = me.color_attributes.new(name, 'FLOAT_COLOR', 'POINT')
+ for v, slot in zip(me.vertices, col.data):
+ t = (v.co.z - z0) / max(z1 - z0, 1e-6)
+ slot.color = tuple(a + (b - a) * t for a, b in zip(low_rgb, high_rgb)) + (1.0,)
+
+vertex_color_by_height(bottle, (0.2, 0.5, 0.2), (0.8, 0.9, 0.8))
+
+# procedural wood (preview-only; judge renders via GLB will show the flat base colour)
+def make_wood_nodes(name="WoodProcedural"):
+ mat = bpy.data.materials.new(name); nt = mat.node_tree
+ bsdf = nt.nodes["Principled BSDF"]
+ wave = nt.nodes.new("ShaderNodeTexWave"); wave.inputs["Scale"].default_value = 40.0
+ wave.inputs["Distortion"].default_value = 6.0
+ ramp = nt.nodes.new("ShaderNodeValToRGB")
+ ramp.color_ramp.elements[0].color = (0.45, 0.28, 0.13, 1); ramp.color_ramp.elements[1].color = (0.62, 0.42, 0.22, 1)
+ nt.links.new(wave.outputs["Fac"], ramp.inputs["Fac"]); nt.links.new(ramp.outputs["Color"], bsdf.inputs["Base Color"])
+ bsdf.inputs["Roughness"].default_value = 0.55
+ return mat
+```
+
+Why: Principled inputs since 4.0 are named `"Specular IOR Level"`, `"Transmission Weight"`,
+`"Coat Weight"`, `"Sheen Weight"`, `"Emission Color"` + `"Emission Strength"` — the old
+`"Specular"`, `"Transmission"`, `"Emission"` keys raise KeyError.
+
+## Structure: names, collections, parenting, instancing, join/separate
+
+```python
+def collection(name: str) -> bpy.types.Collection:
+ col = bpy.data.collections.get(name)
+ if col is None:
+ col = bpy.data.collections.new(name); bpy.context.scene.collection.children.link(col)
+ return col
+
+def move_to(obj, col):
+ for c in list(obj.users_collection):
+ c.objects.unlink(obj)
+ col.objects.link(obj)
+
+def linked_copy(src: bpy.types.Object, name: str, location) -> bpy.types.Object:
+ """Instance: shares mesh data (cheap, identical detail). Give each its own plan name."""
+ o = bpy.data.objects.new(name, src.data)
+ o.location = location; o.rotation_euler = src.rotation_euler; o.scale = src.scale
+ return link(o)
+
+def join(objs, name: str) -> bpy.types.Object:
+ """Join into the FIRST object (its transform wins); result renamed to `name`."""
+ target = objs[0]
+ bpy.ops.object.select_all(action='DESELECT')
+ for o in objs:
+ o.select_set(True)
+ bpy.context.view_layer.objects.active = target
+ bpy.ops.object.join()
+ target.name = name
+ return target
+
+def separate_loose(obj) -> list:
+ """Split an object into its mesh islands (returns all resulting objects)."""
+ before = set(bpy.data.objects)
+ with bpy.context.temp_override(object=obj, active_object=obj, selected_objects=[obj],
+ selected_editable_objects=[obj]):
+ bpy.ops.object.mode_set(mode='EDIT'); bpy.ops.mesh.separate(type='LOOSE')
+ bpy.ops.object.mode_set(mode='OBJECT')
+ return [obj] + sorted(set(bpy.data.objects) - before, key=lambda o: o.name)
+
+legs = collection("Legs")
+leg0 = make_cylinder("Leg1", 0.02, 0.42, (0.18, 0.18, 0.21), 16)
+for i, (sx, sy) in enumerate([(-1, 1), (-1, -1), (1, -1)], start=2):
+ linked_copy(leg0, f"Leg{i}", (sx * 0.18, sy * 0.18, 0.21))
+for o in bpy.data.objects:
+ if o.name.startswith("Leg"): move_to(o, legs)
+```
+
+Why: parenting is fine for organisation but the exporter bakes world transforms —
+**never leave a part as a child of an empty with a non-identity scale**. `join()` inherits
+the ACTIVE object's transform; make the largest/identity object active.
+
+## Proportions and detail (how to look good cheaply)
+
+| feature | recipe | size |
+|---|---|---|
+| rounded edges | `add_bevel(width=t/4, segments=2–3)` | furniture 2–4 mm, devices 0.5–1 mm, vehicles 5–15 mm |
+| chamfer | bevel `segments=1` | 1–3 mm |
+| panel seam / gap | boolean-cut a 1 mm × 2 mm groove, or build panels 1 mm apart | 0.8–1.5 mm |
+| inset panel | `bmesh.ops.inset_region(thickness=…, depth=−…)` on the face | inset 5–10 mm, depth 1–3 mm |
+| fillet at a joint | small torus/cylinder collar overlapping both parts | r 3–8 mm |
+| fasteners | `make_cylinder(r=2–4 mm, depth=1–2 mm)` pressed 0.5 mm into the surface, arrayed | head Ø 5–8 mm |
+| rims / lips | lathe profile with a 2 mm bump | |
+| feet / glides | short cylinders Ø 15–25 mm, h 5–10 mm, under each leg | |
+| handles / knobs | torus or lathe, overlapping the panel ≥ 2 mm | knob Ø 25–35 mm |
+| cushions | box + subsurf 2 + creases + scale 0.98 | 60–120 mm thick |
+| spokes / slats / louvres | one part + `add_array` or a polar loop of `linked_copy` | slat 10–15 mm thick |
+
+```python
+def inset_top(obj, thickness=0.008, depth=-0.002):
+ """Recessed top panel: inset the +Z face (bmesh on the real mesh)."""
+ bm = bmesh.new(); bm.from_mesh(obj.data)
+ bm.faces.ensure_lookup_table()
+ top = max(bm.faces, key=lambda f: f.calc_center_median().z)
+ bmesh.ops.inset_region(bm, faces=[top], thickness=thickness, depth=depth, use_even_offset=True)
+ bm.to_mesh(obj.data); bm.free(); obj.data.update()
+
+def polar_copies(src, n, radius, center, name_fmt="{base}{i}"):
+ """src + n-1 linked copies evenly on a circle (bolts, spokes, chair legs).
+ center=(cx, cy, z); copies are named <Base>2..N, src itself is moved to slot 1."""
+ cx, cy, z = center
+ base = src.name.rstrip("0123456789")
+ out = [src]
+ for i in range(n):
+ a = 2 * math.pi * i / n
+ loc = (cx + radius * math.cos(a), cy + radius * math.sin(a), z)
+ o = src if i == 0 else linked_copy(src, name_fmt.format(base=base, i=i + 1), loc)
+ o.location = loc; o.rotation_euler.z = a
+ if i: out.append(o)
+ return out
+
+lid = make_box("Lid", (0.30, 0.20, 0.012), (0.9, 0, 0.306))
+inset_top(lid, 0.01, -0.002); add_bevel(lid, 0.002, 2); apply_modifiers(lid)
+bolt = make_cylinder("Bolt1", 0.003, 0.002, (0, 0, 0), 12)
+polar_copies(bolt, 6, 0.06, (0.9, 0, 0.3125)) # 6 bolt heads on a Ø 0.12 circle, sunk 0.5 mm into the lid
+```
+
+Rules of thumb: a silhouette needs ≥ 3 distinct masses; every large flat face needs one
+break (seam, inset, bevel, trim); thin things (blades, sheet, glass) are 1–3 mm, never 0;
+every part that a human would touch has a rounded edge.
+
+## Common objects — dimensions (metres) and decomposition
+
+| object | overall (W × D × H) | parts (plan names) | key numbers |
+|---|---|---|---|
+| dining chair | 0.45 × 0.50 × 0.90 | Seat, Backrest, LegFrontLeft/Right, LegBackLeft/Right, Stretchers | seat h 0.45, seat t 0.04, leg Ø/□ 0.035, back top 0.90, back rake 8° |
+| armchair / sofa seat | 0.85 × 0.90 × 0.85 (sofa W 1.8–2.2) | Base, SeatCushion(s), BackCushion(s), ArmLeft, ArmRight, Legs | seat h 0.42, cushion 0.10–0.12, arm h 0.60, arm w 0.15–0.25 |
+| dining table | 1.6 × 0.9 × 0.75 | Top, Apron, Leg1..4 | top t 0.03–0.04, leg 0.07 □ at 0.05 inset |
+| coffee table | 1.2 × 0.6 × 0.45 | Top, Leg1..4 or Base | top t 0.025 |
+| desk lamp | 0.18 Ø base, H 0.45–0.60 | Base, ArmLower, ArmUpper, Shade, Bulb | base t 0.02, arm Ø 0.012, shade Ø 0.15 h 0.12 |
+| floor lamp | 0.30 Ø base, H 1.6 | Base, Pole, Shade | pole Ø 0.025, shade Ø 0.40 |
+| mug | Ø 0.085 × 0.095 | MugBody, MugHandle | wall 4 mm, bottom 6 mm, handle tube Ø 12 mm |
+| bottle (wine) | Ø 0.075 × 0.30 | Body, Neck, Cap | neck Ø 0.028, shoulder at 0.20 |
+| bicycle | 1.75 × 0.60 × 1.05 | Frame, FrontWheel, RearWheel, Fork, Handlebar, Saddle, SeatPost, Crank, PedalLeft/Right, Chain | wheel Ø 0.70 (700c), tyre w 0.03, BB height 0.27, saddle h 0.95 |
+| car (sedan) | 4.6 × 1.85 × 1.45 | Body, Cabin(glass), WheelFL/FR/RL/RR, Bumpers, Mirrors, Lights | wheel Ø 0.65, wheelbase 2.7, ground clearance 0.15 |
+| house (small) | 10 × 8 × 7 | Walls, Roof, Door, Windows, Chimney, Steps | wall h 2.8/storey, roof pitch 30–40°, door 0.9 × 2.1, window 1.2 × 1.2 at sill 0.9 |
+| tree (deciduous) | crown Ø 6–9, H 10–14 | Trunk, Branches, Crown(s) | trunk Ø 0.4 at base, first branch at 2.5, crown = 3–6 overlapping spheres |
+| door | 0.9 × 0.045 × 2.05 | Leaf, Frame, Handle, Hinges | handle h 1.05, frame 0.07 wide |
+| bookshelf | 0.80 × 0.30 × 1.80 | SideLeft, SideRight, Top, Bottom, Shelf1..4, Back | panel 18 mm, shelf pitch 0.33 |
+| kitchen cabinet | 0.60 × 0.58 × 0.87 | Carcass, Door(s)/Drawer(s), Handle(s), Plinth | plinth h 0.10, front 18 mm, handle proud 30 mm |
+| monitor | 0.62 × 0.20 × 0.45 | Panel, Stand, Base | panel t 0.02, bezel 8 mm, base 0.25 × 0.20 |
+| keyboard | 0.44 × 0.14 × 0.03 | Body, Keys(instanced) | key 0.018 pitch 0.019 |
+
+Decomposition recipe (any object): 1 main mass → 2–6 secondary masses that TOUCH it →
+attachments (handles, feet, trim) that overlap ≥ 2 mm → detail pass (bevels, seams,
+fasteners). Name every mass as the plan does; instances by `linked_copy`.
+
+## Pitfalls (symptom → cause → fix)
+
+1. **`bm.verts[i]` raises "outdated internal index table"** → call
+ `bm.verts.ensure_lookup_table()` (also `edges`/`faces`) after `from_mesh` or any
+ topology op before indexing.
+2. **"context is incorrect" / poll() failed in background** → the operator needs an active +
+ selected object or edit mode: use `activate(obj)` or `bpy.context.temp_override(...)`
+ as in `apply_modifiers`; prefer data API (`bmesh`, `me.transform`) over `bpy.ops`.
+3. **`bpy.ops.object.transform_apply(scale=True)` moved my part to the origin** → the other
+ flags default True and baked location. Always pass `location=, rotation=, scale=`
+ explicitly (see `apply_transforms`).
+4. **Modifier apply fails "Modifier cannot be applied to a multi-user mesh"** →
+ `obj.data = obj.data.copy()` first (`apply_modifiers` does it).
+5. **Names like `Leg.001`** → you created two objects/meshes with the same name; give every
+ instance its plan name (`Leg2`); rename meshes too if you care (`o.data.name = o.name`).
+6. **Boolean does nothing / leaves holes** → cutter coplanar with a face or not closed.
+ Overshoot the cutter by ≥ 5 mm, make it watertight (`cap_ends=True`), use `EXACT`.
+7. **Dark/inverted shading, inside-out parts** → flipped normals after `bmesh.ops.scale`
+ with negative factors or after mirroring: `bmesh.ops.recalc_face_normals(bm, faces=bm.faces)`
+ or `bpy.ops.mesh.normals_make_consistent` in edit mode.
+8. **`mesh.use_auto_smooth` AttributeError** (removed 4.1) → `obj.data.shade_smooth()` then
+ `bpy.ops.object.shade_smooth_by_angle(angle=math.radians(30))` under `temp_override`.
+9. **`bsdf.inputs["Specular"]` KeyError** → 4.x names: `"Specular IOR Level"`,
+ `"Transmission Weight"`, `"Emission Color"`/`"Emission Strength"`, `"Coat Weight"`.
+10. **`mat.use_nodes = True`** is a no-op/deprecated in 5.0 — the node tree already exists.
+11. **Object scaled with `obj.scale` looks right but exports wrong / bevels uneven** → bake
+ with `apply_transforms(obj)` before bevel/boolean; keep scale (1,1,1) on export.
+12. **`bpy.ops.mesh.primitive_cube_add(size=1, scale=(…))`** — default size is 2 m; with
+ `scale=` and `size=1` you get exact extents, but still bake the scale afterwards.
+13. **Degenerate geometry** (zero-area faces, zero-thickness walls, coincident faces of two
+ parts) → z-fighting and boolean failures. Offset coincident faces by 0.5 mm or overlap
+ parts by 2 mm; remove doubles `bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-5)`.
+14. **Units**: the scene is in meters; a 450 mm seat is `0.45`, never `450`. If you see a
+ bbox of 450 × 500 × 900 the plan numbers were typed in mm.
+15. **`bpy.context.object` is None in background** → do not rely on it; keep your own refs.
+16. **Deprecated in 4.x/5.x (do not use)**: `mesh.calc_normals()`, `mesh.calc_normals_split()`,
+ `edge.crease` / `edge.bevel_weight` (use attributes `crease_edge`, `bevel_weight_edge`),
+ `bpy.ops.*({'object': o})` dict overrides, `mat.blend_method`, `scene.node_tree`,
+ `BLENDER_EEVEE_NEXT` (5.0 is `BLENDER_EEVEE`), `bgl`, `gpu.types.GPUShader(...)`.
+17. **`bmesh.ops.create_cone` with `radius2=0`** makes a cone with a degenerate cap — fine
+ for visuals; for booleans use `radius2=1e-4`.
+18. **A curve object left un-converted** exports nothing (the harness converts meshes
+ only) → always `convert(target='MESH')` as in `make_tube_along`.
+19. **Huge scripts / per-vertex Python loops over 500 k verts** time out → use modifiers,
+ `foreach_set`, or fewer segments.
+20. **Parenting with scaled parents** → children inherit scale; export bakes it, bevels go
+ elliptical. Parent only to identity-scale empties, or not at all.
+
+## Self-check (before you call it done)
+
+```python
+def selfcheck(expected_names, bbox_hint=None, tol=0.01):
+ """Print a census the way the harness measures it; raise on contract violations."""
+ bpy.context.view_layer.update()
+ meshes = [o for o in bpy.data.objects if o.type == 'MESH']
+ names = sorted(o.name for o in meshes)
+ missing = [n for n in expected_names if n not in names]
+ extra = [n for n in names if n not in expected_names]
+ assert not missing, f"missing parts: {missing}"
+ assert not extra, f"unexpected objects: {extra}"
+ assert all('.' not in n for n in names), f"auto-suffixed names: {[n for n in names if '.' in n]}"
+ lo = Vector((min(world_bbox(o)[0].x for o in meshes), min(world_bbox(o)[0].y for o in meshes),
+ min(world_bbox(o)[0].z for o in meshes)))
+ hi = Vector((max(world_bbox(o)[1].x for o in meshes), max(world_bbox(o)[1].y for o in meshes),
+ max(world_bbox(o)[1].z for o in meshes)))
+ assert abs(lo.z) < tol, f"lowest point z={lo.z:.4f}, expected 0"
+ tris = sum(sum(len(p.vertices) - 2 for p in o.data.polygons) for o in meshes)
+ assert tris < 600_000, f"too many triangles: {tris}"
+ print(f"[selfcheck] parts={len(meshes)} tris={tris} extents={tuple(round(v, 3) for v in (hi - lo))}")
+ if bbox_hint:
+ for a, b in zip(hi - lo, bbox_hint):
+ assert abs(a - b) < 0.05, f"extents {tuple(hi - lo)} vs plan {bbox_hint}"
+
+# (the demo objects above are not one coherent object, so only run the census part here)
+print(len([o for o in bpy.data.objects if o.type == 'MESH']), "mesh objects")
+```
+
+Then use the tools: `build` → `render_sheet` → `check_connectivity` → `isolate` the part
+you doubt → `cross_section` through cavities → `check_contract`. Fix the worst finding,
+rebuild, repeat. Done = all green and the sheet reads as the object from every view.
diff --git a/harness/codeverse/prompts/cadquery/contract.md b/harness/codeverse/prompts/cadquery/contract.md
new file mode 100644
index 00000000..4569a0d8
--- /dev/null
+++ b/harness/codeverse/prompts/cadquery/contract.md
@@ -0,0 +1,80 @@
+# CadQuery authoring contract — track `static_object`, language `cadquery`
+
+## Files
+* `src/model.py` — ONE script, `import cadquery as cq` (+ stdlib `math`). The harness
+ imports it in a subprocess and reads the module-level variable **`result`**.
+ It exports STEP + STL per part and a GLB with one named node per part. You never
+ export, print to files, or call `show_object`.
+
+## `result`
+* Preferred: `result = cq.Assembly(name="<ObjectName>")` with one `assy.add(solid,
+ name="<PartName>", color=cq.Color(r, g, b), loc=cq.Location(...))` per plan part.
+ Part names PascalCase, unique, exactly as in the plan.
+* Allowed for a single-part object: `result = <cq.Workplane>` (one solid).
+* `result` must exist at import time (module level, NOT under `if __name__ == "__main__"`).
+
+## Frame, units, placement
+* **Z up, -Y front, +X right, meters** (the harness converts to Y-up GLB). Author each
+ part in world coordinates (leave `loc` identity) OR author at the origin and place with
+ `loc=cq.Location(cq.Vector(x, y, z))` — pick one style per file.
+* Lowest point at z = 0, footprint centred on Z. Real-world dimensions.
+* Angles: `.rotate(p0, p1, deg)` and `cq.Location(v, axis, deg)` take **degrees**; `math`
+ functions take radians.
+
+## Allowed imports
+`cadquery` (as `cq`), `math`, `itertools`, `functools`, `typing`, `dataclasses`.
+No `OCP`/`OCC` direct calls, no numpy, no file I/O, no `cq.exporters`, no
+`cq.importers`, no `import codeverse`.
+
+## Forbidden / limits
+* No `show_object`, `exporters.export`, `open(`, `os`, `sys`, `subprocess`, network.
+* ≤ 40 parts; each part a valid solid (`.val().isValid()`), no empty Workplanes; fillets
+ < 0.45 × thinnest adjacent wall; feature sizes ≥ 0.5 mm; build < 120 s.
+* Do not union parts across plan boundaries (keep one solid per part); small intentional
+ overlap (≥ 2 mm) between touching parts is required — that is how they "weld".
+
+## Self-check (put at the end of the file)
+```python
+def _selfcheck(assy) -> None:
+ names = [c.name for c in assy.children]
+ assert names and len(names) == len(set(names)), f"duplicate/missing part names {names}"
+ for c in assy.children:
+ assert c.obj.val().isValid(), f"invalid solid in {c.name}"
+```
+
+## COMPLETE minimal example (verified with CadQuery 2.8)
+```python
+import cadquery as cq
+import math
+
+# --- plan numbers (metres) -------------------------------------------------
+TOP_W, TOP_D, TOP_T, TOP_Z = 0.60, 0.40, 0.025, 0.45 # table top, its top face at 0.45
+LEG_S, LEG_INSET = 0.035, 0.04 # square leg side, inset from edge
+WELD = 0.003 # legs poke 3 mm into the top
+
+def build_top() -> cq.Workplane:
+ return (cq.Workplane("XY")
+ .box(TOP_W, TOP_D, TOP_T, centered=(True, True, False)) # z from 0 up
+ .edges("|Z").fillet(0.02) # round the 4 vertical corners
+ .edges(">Z").chamfer(0.003) # soften the top rim
+ .translate((0, 0, TOP_Z - TOP_T)))
+
+def build_leg(sx: int, sy: int) -> cq.Workplane:
+ x = sx * (TOP_W / 2 - LEG_INSET - LEG_S / 2)
+ y = sy * (TOP_D / 2 - LEG_INSET - LEG_S / 2)
+ h = TOP_Z - TOP_T + WELD
+ leg = cq.Workplane("XY").rect(LEG_S, LEG_S).extrude(h) # z 0 → h
+ try:
+ leg = leg.edges("|Z").fillet(0.004) # cosmetic: may fail
+ except Exception:
+ pass
+ return leg.translate((x, y, 0))
+
+assy = cq.Assembly(name="SideTable")
+assy.add(build_top(), name="Top", color=cq.Color(0.55, 0.33, 0.16))
+for i, (sx, sy) in enumerate([(1, 1), (-1, 1), (-1, -1), (1, -1)]):
+ assy.add(build_leg(sx, sy), name=f"Leg{i + 1}", color=cq.Color(0.2, 0.2, 0.22))
+
+_selfcheck(assy)
+result = assy
+```
diff --git a/harness/codeverse/prompts/cadquery/cookbook.md b/harness/codeverse/prompts/cadquery/cookbook.md
new file mode 100644
index 00000000..58fa400c
--- /dev/null
+++ b/harness/codeverse/prompts/cadquery/cookbook.md
@@ -0,0 +1,412 @@
+# CadQuery cookbook — static objects, CadQuery 2.4–2.8
+
+Every snippet runs as-is (the harness test suite executes them in order with plain
+`python3`). Z-up, −Y front, meters, PascalCase part names, `result = cq.Assembly`.
+Use `read_cookbook(section="<heading>")` to fetch one chapter.
+
+## Skeleton
+
+```python
+import cadquery as cq
+import math
+
+# ---- plan numbers (metres) --------------------------------------------------
+BODY_W, BODY_D, BODY_H, WALL = 0.120, 0.080, 0.040, 0.002
+LID_T, LIP = 0.003, 0.0015
+WELD = 0.002 # parts overlap by this to "weld"
+
+def safe_fillet(wp: cq.Workplane, selector: str, r: float) -> cq.Workplane:
+ """Cosmetic fillet that never breaks the build: shrink, then give up."""
+ for rr in (r, r * 0.5, r * 0.25):
+ try:
+ return wp.edges(selector).fillet(rr)
+ except Exception:
+ continue
+ return wp
+
+def safe_chamfer(wp: cq.Workplane, selector: str, d: float) -> cq.Workplane:
+ try:
+ return wp.edges(selector).chamfer(d)
+ except Exception:
+ return wp
+
+def bbox(wp: cq.Workplane):
+ """(xmin, ymin, zmin, xmax, ymax, zmax) of the FIRST solid — use to self-check."""
+ b = wp.val().BoundingBox()
+ return (b.xmin, b.ymin, b.zmin, b.xmax, b.ymax, b.zmax)
+
+def build_body() -> cq.Workplane:
+ outer = (cq.Workplane("XY").box(BODY_W, BODY_D, BODY_H, centered=(True, True, False))
+ .edges("|Z").fillet(0.006)) # z from 0 upward
+ body = outer.faces(">Z").shell(-WALL) # open-top box, 2 mm walls
+ return safe_fillet(body, "<Z", 0.001) # soften the bottom rim LAST (r < wall/2)
+
+def build_lid() -> cq.Workplane:
+ top = (cq.Workplane("XY").box(BODY_W, BODY_D, LID_T, centered=(True, True, False))
+ .edges("|Z").fillet(0.006).translate((0, 0, BODY_H)))
+ lip = (cq.Workplane("XY").rect(BODY_W - 2 * WALL - 0.0004, BODY_D - 2 * WALL - 0.0004)
+ .rect(BODY_W - 2 * WALL - 0.0004 - 2 * LIP, BODY_D - 2 * WALL - 0.0004 - 2 * LIP)
+ .extrude(0.004 + WELD).translate((0, 0, BODY_H - 0.004))) # lip drops into the box
+ return top.union(lip)
+
+assy = cq.Assembly(name="Enclosure")
+assy.add(build_body(), name="Body", color=cq.Color(0.25, 0.25, 0.27))
+assy.add(build_lid(), name="Lid", color=cq.Color(0.85, 0.55, 0.15))
+result = assy
+print("body bbox", [round(v, 4) for v in bbox(build_body())])
+```
+
+Why: every part is a function returning one solid; `safe_*` keep cosmetic edge work from
+killing the build; the lid's lip overlaps the body (weld) so the assembly is connected.
+
+## Workplane idioms (the few you need)
+
+```python
+# Workplane names: "XY" (normal +Z, up), "XZ" (normal -Y: the FRONT elevation), "YZ" (normal +X)
+# .box(x, y, z) is CENTRED unless centered=(…); .extrude(h) goes along the plane normal from z=0
+plate = cq.Workplane("XY").box(0.10, 0.06, 0.004, centered=(True, True, False)) # bottom at z=0
+# workplane offset + faces: stack features relative to the last face
+boss = (plate.faces(">Z").workplane() # plane on the top face
+ .center(0.03, 0.0) # local offset (resets per workplane)
+ .circle(0.008).extrude(0.012)) # boss grows UP from the face
+# hole through everything from the top face
+boss = boss.faces(">Z").workplane().center(-0.03, 0).hole(0.005) # hole() is a THROUGH hole
+# cboreHole / cskHole for counterbores; .hole(d, depth) for blind
+# rotate(p0, p1, deg) about an arbitrary axis, translate(v): both RETURN NEW objects
+tilted = boss.rotate((0, 0, 0), (1, 0, 0), 15).translate((0, 0.2, 0))
+# pushPoints: put features at several local points
+grid = (cq.Workplane("XY").box(0.08, 0.08, 0.005, centered=(True, True, False))
+ .faces(">Z").workplane().pushPoints([(-0.02, -0.02), (0.02, 0.02)]).hole(0.004))
+# selectors: "|Z" edges parallel Z, ">Z" max-Z face/edges, "<Y" min-Y, "%CIRCLE" round edges,
+# "#Z" edges perpendicular to Z, "not(|Z)". Combine: .edges("|Z and >X")
+print("boss bbox", [round(v, 4) for v in bbox(boss)])
+```
+
+Why: offset workplanes + `faces(">Z").workplane()` build features where they belong
+without hand-computing z; `centered=(True, True, False)` makes z = 0 the base so objects
+stand on the ground by construction.
+
+## 2D profiles: polyline, spline, slots, text, sketches
+
+```python
+# closed polyline profile (in metres) extruded; points in plane-local coords
+bracket_profile = [(0, 0), (0.06, 0), (0.06, 0.004), (0.004, 0.004), (0.004, 0.05), (0, 0.05)]
+lbracket = cq.Workplane("XZ").polyline(bracket_profile).close().extrude(-0.03) # XZ normal is -Y: negative = towards +Y
+# spline through points (smooth organic outline), mirrored for symmetry
+half = [(0, 0), (0.02, 0.003), (0.04, 0.012), (0.05, 0.03), (0.045, 0.05), (0.03, 0.06), (0, 0.062)]
+leaf = (cq.Workplane("XY").spline(half, includeCurrent=False).mirrorY().extrude(0.002))
+# slot and rounded rect via Sketch API
+s = cq.Sketch().rect(0.06, 0.03).vertices().fillet(0.006)
+tag = cq.Workplane("XY").placeSketch(s).extrude(0.003)
+slot = cq.Workplane("XY").slot2D(0.03, 0.006).extrude(0.002) # length 30 mm, width 6 mm
+# text (embossed label), font size in metres; fonts may be missing headless → wrap it
+try:
+ label = cq.Workplane("XY").text("C3V", 0.012, 0.001, halign="center", valign="center")
+except Exception:
+ label = None
+print("lbracket bbox", [round(v, 4) for v in bbox(lbracket)], "leaf ok", leaf.val().isValid())
+```
+
+Why: `Sketch().rect().vertices().fillet()` is the robust rounded rectangle; polylines need
+`.close()`; `mirrorY()` mirrors the pending wire about the plane's Y axis.
+
+## Extrude, revolve, loft, sweep (the solid makers)
+
+```python
+# revolve: profile in the XZ plane, axis = local Y of XZ plane = world Z; r >= 0 always
+vase_profile = [(0.0, 0.0), (0.035, 0.0), (0.045, 0.05), (0.03, 0.12), (0.02, 0.18), (0.025, 0.20), (0.0, 0.20)]
+vase = cq.Workplane("XZ").polyline(vase_profile).close().revolve(360, (0, 0, 0), (0, 1, 0))
+# loft between sections on parallel workplanes (same edge count/orientation is safest: circle→circle, rect→rect)
+funnel = (cq.Workplane("XY").circle(0.04)
+ .workplane(offset=0.05).circle(0.015)
+ .workplane(offset=0.03).circle(0.015).loft(ruled=False))
+# sweep a circle along a 3D path (tube / handle / pipe); profile plane must be perpendicular to the path start
+path = cq.Workplane("XZ").spline([(0, 0), (0.03, 0.02), (0.06, 0.06), (0.06, 0.10)])
+handle = (cq.Workplane("XY").circle(0.005).sweep(path, isFrenet=True))
+# twisted / tapered extrude
+twist = cq.Workplane("XY").rect(0.02, 0.02).twistExtrude(0.06, 90)
+taper = cq.Workplane("XY").circle(0.03).extrude(0.05, taper=10)
+print("vase ok", vase.val().isValid(), "funnel ok", funnel.val().isValid(), "handle ok", handle.val().isValid())
+```
+
+Why: these four make 90 % of non-boxy shapes; the classic failures are revolve profiles
+crossing the axis (r < 0), lofts between wires with different vertex counts, and sweep
+profiles not perpendicular to the path start. Verify with `.val().isValid()`.
+
+## Shell, fillet, chamfer — robustly
+
+```python
+cup = (cq.Workplane("XY").circle(0.04).extrude(0.09, taper=-3) # flared cup (taper < 0 widens)
+ .faces(">Z").shell(-0.003)) # open top, 3 mm wall
+cup = safe_fillet(cup, ">Z", 0.001) # rim round-over; may legally fail on thin walls
+# shell() REFUSES lofted round bodies: hollow those by subtracting an inner loft instead
+shade = (cq.Workplane("XY").circle(0.06).workplane(offset=0.12).circle(0.10).loft()
+ .cut(cq.Workplane("XY").circle(0.057).workplane(offset=0.12).circle(0.097).loft()
+ .translate((0, 0, 0.003)))) # 3 mm wall, 3 mm floor
+box_ = (cq.Workplane("XY").box(0.06, 0.04, 0.03, centered=(True, True, False))
+ .edges("|Z").fillet(0.008) # vertical corners first (big radius)
+ .edges(">Z").chamfer(0.002)) # then the top rim (small)
+print("cup ok", cup.val().isValid(), "shade ok", shade.val().isValid(), "box ok", box_.val().isValid())
+```
+
+Rules: fillet BEFORE booleans that would split the edge; radius < 0.45 × the thinnest
+adjacent wall; biggest fillets first; shell from a single open face; if `BRep_API:
+command not done` appears, halve the radius or fillet fewer edges (`"|Z"` only).
+
+## Booleans (union / cut / intersect) and cavities
+
+```python
+block = cq.Workplane("XY").box(0.08, 0.05, 0.03, centered=(True, True, False))
+cutter = (cq.Workplane("XY").box(0.06, 0.03, 0.03, centered=(True, True, False))
+ .translate((0, 0, 0.006 + 0.0001))) # cutter overshoots the top face by 6 mm+
+pocketed = block.cut(cutter) # 6 mm floor left
+pin = cq.Workplane("XY").circle(0.004).extrude(0.05).translate((0.03, 0, 0.02))
+joined = pocketed.union(pin).clean() # clean() merges coplanar faces
+core = block.intersect(cq.Workplane("XY").sphere(0.045).translate((0, 0, 0.015)))
+print("pocket solids", len(pocketed.solids().vals()), "joined valid", joined.val().isValid())
+```
+
+Why: booleans fail on exactly coplanar faces — always overshoot cutters by ≥ 0.1 mm;
+check `len(result.solids().vals()) == 1` after a cut (a cut that splits a part is a bug).
+
+## Assemblies: names, colours, locations
+
+```python
+def place(part: cq.Workplane, xyz=(0, 0, 0), rz_deg: float = 0.0) -> cq.Location:
+ """Location = translation + yaw (degrees). Compose bigger rotations via .rotate() on the solid."""
+ return cq.Location(cq.Vector(*xyz), cq.Vector(0, 0, 1), rz_deg)
+
+stool = cq.Assembly(name="Stool")
+seat = cq.Workplane("XY").circle(0.17).extrude(0.04).translate((0, 0, 0.41))
+stool.add(seat, name="Seat", color=cq.Color(0.55, 0.34, 0.16))
+leg = cq.Workplane("XY").circle(0.015).extrude(0.41 + WELD) # authored at the origin
+for i in range(3):
+ a = math.radians(90 + 120 * i)
+ stool.add(leg, name=f"Leg{i + 1}", color=cq.Color(0.3, 0.3, 0.32),
+ loc=place(leg, (0.12 * math.cos(a), 0.12 * math.sin(a), 0)))
+# sub-assemblies nest: stool.add(other_assy, name="Footrest", loc=...)
+names = [c.name for c in stool.children]
+print("stool parts", names, "valid", all(c.obj.val().isValid() for c in stool.children))
+```
+
+Why: one authored solid + N locations = instances that stay identical; names must be
+unique (the GLB node names come from them); `cq.Color` takes 0–1 floats.
+
+## Patterns: rect arrays, polar arrays, point lists
+
+```python
+grille = (cq.Workplane("XY").box(0.10, 0.06, 0.002, centered=(True, True, False))
+ .faces(">Z").workplane().rarray(0.008, 0.008, 10, 6).hole(0.004)) # 10×6 holes
+flange = (cq.Workplane("XY").circle(0.05).extrude(0.006)
+ .faces(">Z").workplane().polarArray(0.04, 0, 360, 6).hole(0.005)) # 6 bolt holes
+spokes = cq.Workplane("XY")
+for i in range(8):
+ a = 360 / 8 * i
+ spokes = spokes.union(cq.Workplane("XY").box(0.08, 0.004, 0.004, centered=(False, True, False))
+ .rotate((0, 0, 0), (0, 0, 1), a))
+print("grille holes ok", grille.val().isValid(), "spokes valid", spokes.val().isValid())
+```
+
+Why: `rarray`/`polarArray` + one cut are 10× faster than loops of cuts and never produce
+slivers; loops of `.union` are fine for ≤ 12 items.
+
+## Mechanical parts (recipes with numbers)
+
+```python
+def l_bracket(w=0.06, h=0.05, depth=0.03, t=0.004, hole_d=0.005) -> cq.Workplane:
+ """Steel L-bracket with two slots; t 3–5 mm, fillet inside corner r = t."""
+ prof = [(0, 0), (w, 0), (w, t), (t, t), (t, h), (0, h)]
+ b = cq.Workplane("XZ").polyline(prof).close().extrude(-depth)
+ b = safe_fillet(b, "|Y", t * 0.8)
+ b = b.faces(">Z").workplane().center(0, 0).hole(hole_d)
+ return b
+
+def enclosure(w=0.12, d=0.08, h=0.04, wall=0.002, lid_t=0.003):
+ """Two parts: open box + lid with a drop-in lip (1.5 mm)."""
+ body = (cq.Workplane("XY").box(w, d, h, centered=(True, True, False))
+ .edges("|Z").fillet(0.005).faces(">Z").shell(-wall))
+ lid = (cq.Workplane("XY").box(w, d, lid_t, centered=(True, True, False)).edges("|Z").fillet(0.005)
+ .translate((0, 0, h)))
+ lip = (cq.Workplane("XY").rect(w - 2 * wall - 0.0004, d - 2 * wall - 0.0004)
+ .rect(w - 2 * wall - 0.0034, d - 2 * wall - 0.0034).extrude(0.005).translate((0, 0, h - 0.003)))
+ return body, lid.union(lip)
+
+def spur_gear(module=0.002, teeth=20, thickness=0.008, bore=0.006) -> cq.Workplane:
+ """Visual-grade gear: trapezoid teeth on a disc (not an involute; fine for renders)."""
+ r_p = module * teeth / 2; r_o = r_p + module; r_r = r_p - 1.25 * module
+ gear = cq.Workplane("XY").circle(r_r).extrude(thickness)
+ tooth = (cq.Workplane("XY").polyline([(r_r - 0.0005, -module * 0.9), (r_o, -module * 0.45),
+ (r_o, module * 0.45), (r_r - 0.0005, module * 0.9)]).close()
+ .extrude(thickness))
+ for i in range(teeth):
+ gear = gear.union(tooth.rotate((0, 0, 0), (0, 0, 1), 360 / teeth * i))
+ return gear.faces(">Z").workplane().hole(bore)
+
+def knob(d=0.03, h=0.018, ribs=12) -> cq.Workplane:
+ """Rotary knob: tapered cylinder, rib grooves, domed top, D-shaft bore."""
+ k = cq.Workplane("XY").circle(d / 2).extrude(h, taper=6)
+ k = safe_fillet(k, ">Z", 0.003)
+ groove = cq.Workplane("XY").box(0.0015, 0.004, h * 0.7, centered=(True, True, False)).translate((0, d / 2, h * 0.35))
+ for i in range(ribs):
+ k = k.cut(groove.rotate((0, 0, 0), (0, 0, 1), 360 / ribs * i))
+ return k.faces("<Z").workplane().hole(0.006, 0.010)
+
+parts = [l_bracket(), *enclosure(), spur_gear(), knob()]
+print("mech valid", [p.val().isValid() for p in parts])
+```
+
+Dimensions (m): bracket t 3–5 mm, holes Ø 4–6 mm; enclosure walls 1.5–2.5 mm, lid 2–3 mm;
+gear module 1–3 mm, 12–40 teeth; knob Ø 20–35 mm, h 15–20 mm, shaft Ø 6 mm; handles
+Ø 10–14 mm tube; table legs 35–70 mm square; shelf panels 18 mm; plinths 100 mm.
+
+## Common objects — decomposition (CadQuery flavour)
+
+| object | parts | build with |
+|---|---|---|
+| mug | Body (revolve + shell), Handle (sweep circle along spline, overlap 2 mm) | revolve, sweep |
+| bottle | Body (revolve), Cap (cylinder + knurl polarArray cuts) | revolve, polarArray |
+| chair | Seat (box + fillets), Legs ×4 (extrude, located), Backrest (box + rotate 8°), Stretchers | box, rotate, Location |
+| table | Top (box + fillet), Apron ×4, Legs ×4 | box, translate |
+| lamp | Base (revolve), Pole (cylinder), Shade (taper extrude + shell, or loft − inner loft) | extrude(taper), shell |
+| enclosure | Body (shell), Lid (lip), Buttons (cylinders), Screws (polarArray) | shell, rarray |
+| wheel | Rim (revolve), Tyre (torus via revolve of circle), Spokes (polar union), Hub | revolve, polar |
+| bracket | L-profile polyline extrude + slots | polyline, cutThruAll |
+
+## Measure while you build (numbers beat squinting)
+
+```python
+def report(wp: cq.Workplane, name: str = "part") -> dict:
+ """Print the facts the harness will measure — call it after building each part."""
+ shp = wp.val()
+ bb = shp.BoundingBox()
+ info = {
+ "name": name,
+ "extents_m": (round(bb.xlen, 4), round(bb.ylen, 4), round(bb.zlen, 4)),
+ "zmin": round(bb.zmin, 4),
+ "solids": len(wp.solids().vals()),
+ "valid": shp.isValid(),
+ "volume_m3": round(shp.Volume(), 8),
+ "faces": len(wp.faces().vals()),
+ }
+ print(f"[report] {info}")
+ return info
+
+r = report(build_body(), "Body")
+assert r["solids"] == 1 and r["valid"]
+assert abs(r["extents_m"][2] - BODY_H) < 1e-6 # plan number check, in code
+```
+
+Why: `Volume()` catches hollow-when-it-should-be-solid (and vice versa) instantly;
+`solids == 1` catches a cut that split the part; `zmin` catches floaters — all before
+spending a render.
+
+## Pitfalls (symptom → cause → fix)
+
+1. **`.cylinder(height, radius)`** — height FIRST; `.box(x, y, z)` is centred unless
+ `centered=(…)`; `.circle(r).extrude(h)` starts at the workplane (z = 0).
+2. **Degrees vs radians**: `.rotate(..., deg)`, `cq.Location(v, axis, deg)`,
+ `revolve(deg)`, `twistExtrude(h, deg)` are DEGREES; `math.sin` wants radians.
+3. **`rotate/translate/mirror` return new objects** — assign the result (`wp = wp.rotate(...)`).
+4. **`BRep_API: command not done`** → fillet radius ≥ wall, a fillet radius EQUAL to a
+ later shell thickness (inner radius 0), fillet after a boolean that split the edge, or
+ a degenerate edge. Halve the radius, shell first and fillet last, select fewer edges,
+ use `safe_fillet`.
+5. **`ValueError: No edges selected` / "Fillets requires that edges be selected"** →
+ the selector matched nothing (rotated features are invisible to `|Z`-style selectors).
+ Print `len(wp.edges(sel).vals())`; use `cq.selectors.BoxSelector(p0, p1)` or
+ `NearestToPointSelector(p)`.
+6. **Shell fails** → pick ONE open face (`.faces(">Z").shell(-t)`), keep t < smallest
+ feature, fillet outside corners first. Shell never works on lofted round bodies:
+ use `extrude(h, taper=…)` + shell, `outer.cut(inner_loft)`, or revolve a profile that
+ already contains the wall.
+7. **Two solids in one Workplane** (`len(wp.solids().vals()) > 1`) → a cut split your part
+ or a union did not touch; overlap parts by ≥ 0.5 mm, check bounds.
+8. **Coplanar boolean faces** → invalid/empty result; overshoot cutters 0.1–5 mm; `.clean()`.
+9. **`cq.Solid.makeSphere(r)` gives a hemisphere** without angle args; use
+ `cq.Workplane().sphere(r)`.
+10. **Revolve axis**: in `cq.Workplane("XZ")` the axis `(0,1,0)` is plane-LOCAL = world Z.
+ Profile must stay at r ≥ 0.
+11. **`centered=False` on `.box`** puts the MIN corner at the origin on all three axes;
+ use the tuple form `(True, True, False)` for "centred in XY, base on z = 0".
+12. **Tiny features (< 0.3 mm)** at OCC's 1e-7 tolerance produce invalid shapes; keep
+ features ≥ 0.5 mm, or model in mm and scale at the end (`.val().scale(0.001)`).
+13. **`result` under `if __name__ == "__main__":`** → the harness never sees it. Module level.
+14. **`show_object`, `exporters.export`, file writes** → forbidden; the harness exports.
+15. **Selectors after booleans** — edge indices reshuffle; re-select by geometry
+ (`">Z"`, `BoxSelector`), never by cached index.
+16. **Euler `cq.Location(x, y, z, rx, ry, rz)`** is easy to get wrong — build the solid
+ in place with `.rotate(...).translate(...)` and use `Location` only for translation +
+ one yaw.
+17. **Very slow builds** → long loops of `.union` with fillets inside; fillet once at the
+ end, use `rarray`/`polarArray`, keep ≤ 40 parts.
+18. **`hole()` on the wrong side** → it cuts in the −normal direction of the workplane;
+ stand on the top face (`faces(">Z").workplane()`).
+
+## Self-check (before you call it done)
+
+```python
+def selfcheck(assy: cq.Assembly, expected_parts, overall_hint=None, tol=0.01) -> None:
+ names = [c.name for c in assy.children]
+ assert names == list(dict.fromkeys(names)), f"duplicate part names: {names}"
+ missing = [n for n in expected_parts if n not in names]
+ assert not missing, f"missing parts: {missing}"
+ for c in assy.children:
+ shp = c.obj.val() if hasattr(c.obj, "val") else c.obj
+ assert shp.isValid(), f"invalid solid: {c.name}"
+ assert len(c.obj.solids().vals()) == 1, f"{c.name} is {len(c.obj.solids().vals())} solids (must be 1)"
+ bb = assy.toCompound().BoundingBox()
+ assert abs(bb.zmin) < tol, f"lowest point z={bb.zmin:.4f}, expected 0"
+ ext = (bb.xlen, bb.ylen, bb.zlen)
+ print(f"[selfcheck] parts={len(names)} extents={tuple(round(e, 3) for e in ext)}")
+ if overall_hint:
+ for a, b in zip(ext, overall_hint):
+ assert abs(a - b) < 0.05, f"extents {ext} vs plan {overall_hint}"
+
+selfcheck(stool, ["Seat", "Leg1", "Leg2", "Leg3"], (0.34, 0.34, 0.45))
+selfcheck(result, ["Body", "Lid"])
+```
+
+Then: `build` → `render_sheet` → `check_connectivity` → `cross_section` through shells
+→ `check_contract`. Fix the worst finding, rebuild, repeat.
+
+## Worked example: dining chair (8 parts, welded, on the ground)
+
+```python
+SEAT_W, SEAT_D, SEAT_T, SEAT_H = 0.44, 0.44, 0.035, 0.45
+LEG, BACK_H, RAKE_DEG = 0.035, 0.92, 8.0
+
+def chair_seat():
+ return (cq.Workplane("XY").box(SEAT_W, SEAT_D, SEAT_T, centered=(True, True, False))
+ .edges("|Z").fillet(0.02).edges(">Z").fillet(0.006).translate((0, 0, SEAT_H - SEAT_T)))
+
+def chair_leg(h):
+ return cq.Workplane("XY").rect(LEG, LEG).extrude(h + WELD).edges("|Z").chamfer(0.003)
+
+def chair_back():
+ """Two raked posts + 3 slats; built upright then raked back by RAKE_DEG about the seat rear edge."""
+ post_h = BACK_H - SEAT_H
+ posts = cq.Workplane("XY")
+ for sx in (-1, 1):
+ posts = posts.union(cq.Workplane("XY").rect(LEG, LEG * 0.8).extrude(post_h + WELD)
+ .translate((sx * (SEAT_W / 2 - LEG / 2), 0, SEAT_H - WELD)))
+ for i in range(3):
+ z = SEAT_H + 0.14 + i * 0.10
+ posts = posts.union(cq.Workplane("XY").box(SEAT_W - LEG, 0.012, 0.05).translate((0, 0, z)))
+ pivot = (0, SEAT_D / 2 - LEG / 2, SEAT_H - WELD)
+ return posts.translate((0, SEAT_D / 2 - LEG / 2, 0)).rotate(pivot, (pivot[0] + 1, pivot[1], pivot[2]), RAKE_DEG)
+
+chair = cq.Assembly(name="DiningChair")
+chair.add(chair_seat(), name="Seat", color=cq.Color(0.6, 0.4, 0.2))
+for i, (sx, sy) in enumerate([(1, 1), (-1, 1), (-1, -1), (1, -1)]):
+ chair.add(chair_leg(SEAT_H - SEAT_T), name=f"Leg{i + 1}", color=cq.Color(0.45, 0.3, 0.15),
+ loc=cq.Location(cq.Vector(sx * (SEAT_W / 2 - LEG / 2 - 0.01), sy * (SEAT_D / 2 - LEG / 2 - 0.01), 0)))
+chair.add(chair_back(), name="Backrest", color=cq.Color(0.45, 0.3, 0.15))
+stretch = cq.Workplane("XY").box(SEAT_W - LEG - 0.02 + 2 * WELD, 0.02, 0.02).translate((0, 0, 0.20))
+chair.add(stretch.translate((0, SEAT_D / 2 - LEG / 2 - 0.01, 0)), name="StretcherBack", color=cq.Color(0.45, 0.3, 0.15))
+chair.add(stretch.translate((0, -(SEAT_D / 2 - LEG / 2 - 0.01), 0)), name="StretcherFront", color=cq.Color(0.45, 0.3, 0.15))
+selfcheck(chair, ["Seat", "Leg1", "Leg2", "Leg3", "Leg4", "Backrest", "StretcherBack", "StretcherFront"])
+```
+
+Why: the plan's numbers appear once as constants; legs are one solid placed four times;
+the backrest is built upright and raked as a whole so its slats stay attached; every
+part overlaps a neighbour by `WELD`.
diff --git a/harness/codeverse/prompts/scene_threejs/contract.md b/harness/codeverse/prompts/scene_threejs/contract.md
new file mode 100644
index 00000000..ef6ec268
--- /dev/null
+++ b/harness/codeverse/prompts/scene_threejs/contract.md
@@ -0,0 +1,122 @@
+# Scene (multi-file three.js + GLSL) authoring contract — track `scene`, language `scene_threejs`
+
+## Files (ES modules, three r182; Y-up, +Z front, meters)
+```
+src/scene.js export async function createScene({ THREE, renderer, loaders })
+ → { scene, cameras, update(t, dt) }
+src/env.js export const BOUNDS; export function heightAt(x, z); export function buildEnv(THREE, scene) → { update(t, dt) }
+src/zones/<snake>.js export function build<Zone>(THREE, ctx) → THREE.Group (ctx = { heightAt, loaders, ... })
+src/assets/<snake>.js export function build<Asset>(THREE, opts = {}) → THREE.Group (procedural, Y-up, on y = 0)
+src/shaders/<snake>.js export function make<Name>Material(THREE, opts = {}) → THREE.ShaderMaterial | patched material
+public/assets/<snake>.glb (optional) Blender-built assets, loaded via loaders.gltf.loadAsync('/assets/<snake>.glb')
+```
+The harness serves the workspace root over http (`public/assets/` is mounted at
+`/assets/`), imports `src/scene.js` in headless Chrome with the real `THREE`, a configured
+`WebGLRenderer` (shadows on, ACES tone mapping, sRGB output; logarithmic depth may be on
+or off — write shaders that work either way) and `loaders = { gltf, texture, cube,
+manager }` (GLTFLoader etc.). It awaits `createScene`, validates the return value, then
+for each camera renders at t ∈ {0, 1.5} s (calling `update`) and takes probes (tris, draw
+calls, console/shader errors, camera-inside-geometry, black/blown frames, fps).
+
+## createScene return value
+* `scene`: `THREE.Scene` with `scene.fog` set and a background colour or sky dome.
+* `cameras`: 3–5 **plain objects** `{ name, position: [x, y, z], lookAt: [x, y, z], fov }`
+ (the harness builds the PerspectiveCameras: aspect 16/9, near 0.1, far from bounds).
+ Names PascalCase from the plan (`Establishing`, `HarbourMid`, `LanternDetail`); fov
+ 35–60; eye height ≈ 1.6 m for human views; never inside or within 0.5 m of geometry; the
+ first camera is the establishing shot showing ≥ 70 % of the bounds.
+* `update(t, dt)`: advance animation (t seconds since start, dt seconds). MUST be cheap
+ (no allocations, no traversals — cache lists of animated objects / materials at build
+ time). Deterministic: the same t always gives the same frame.
+
+## Imports (only these resolve)
+`three`, `three/addons/*` (GLTFLoader, BufferGeometryUtils, Sky, Water, EffectComposer…).
+Relative imports between your own files. No CDN, no other packages, no `three/webgpu`,
+no `three/tsl`. Post-processing (EffectComposer) is optional and described in the
+cookbook; the default harness renders the scene directly, so lighting and emissives must
+look right WITHOUT bloom.
+
+## Forbidden
+`document.*` / `window.*` except `window.innerWidth` — never create canvases or DOM;
+`fetch`/XHR (use `loaders.gltf`); `Math.random()` (use a seeded hash `rand(i)`);
+`Date.now()`/`performance.now()` (use `t`); `requestAnimationFrame`; creating a renderer;
+changing renderer settings; environment sniffing (`navigator.userAgent`, headless checks).
+
+## Budget
+≤ 2 M triangles, ≤ 200 draw calls (InstancedMesh for anything repeated > 5×), ≤ 40
+materials, textures only procedural (DataTexture / CanvasTexture is NOT available), GLB
+assets ≤ 5 MB each, `createScene` resolves in < 15 s, `update` < 4 ms.
+
+## Naming
+Zones are Groups named PascalCase (plan zone names); assets Groups PascalCase; every
+animated object has a stable `.name`; ShaderMaterials `mat.name = 'Water'`.
+
+## COMPLETE minimal example (verified in node: module evaluates, createScene resolves, cameras valid)
+`src/env.js`
+```js
+import * as THREE from 'three';
+export const BOUNDS = { min: [-40, 0, -40], max: [40, 25, 40] };
+export function heightAt(x, z) { // gentle rolling ground, deterministic
+ return 0.6 * Math.sin(x * 0.12) * Math.cos(z * 0.09) + 0.2 * Math.sin((x + z) * 0.31);
+}
+export function buildEnv(THREE, scene) {
+ scene.background = new THREE.Color(0x9fc4e8);
+ scene.fog = new THREE.Fog(0x9fc4e8, 40, 140);
+ scene.add(new THREE.HemisphereLight(0xbfd8ff, 0x6b5a3a, 0.6));
+ const sun = new THREE.DirectionalLight(0xfff1d6, 2.8);
+ sun.position.set(30, 40, 20); sun.castShadow = true;
+ sun.shadow.mapSize.set(2048, 2048);
+ Object.assign(sun.shadow.camera, { left: -45, right: 45, top: 45, bottom: -45, near: 1, far: 150 });
+ scene.add(sun, sun.target);
+ const geo = new THREE.PlaneGeometry(80, 80, 80, 80); geo.rotateX(-Math.PI / 2);
+ const pos = geo.attributes.position;
+ for (let i = 0; i < pos.count; i++) pos.setY(i, heightAt(pos.getX(i), pos.getZ(i)));
+ geo.computeVertexNormals();
+ const ground = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0x5e7a3a, roughness: 1 }));
+ ground.name = 'Ground'; ground.receiveShadow = true; scene.add(ground);
+ return { update(t, dt) {} };
+}
+```
+`src/zones/grove.js`
+```js
+import * as THREE from 'three';
+const rand = (i) => { const s = Math.sin(i * 12.9898 + 78.233) * 43758.5453; return s - Math.floor(s); };
+export function buildGrove(THREE, { heightAt }) {
+ const zone = new THREE.Group(); zone.name = 'Grove';
+ const N = 40;
+ const trunk = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.12, 0.18, 2.4, 8),
+ new THREE.MeshStandardMaterial({ color: 0x5a3b22, roughness: 0.9 }), N);
+ const crown = new THREE.InstancedMesh(new THREE.ConeGeometry(1.4, 3.2, 9),
+ new THREE.MeshStandardMaterial({ color: 0x2f6b2a, roughness: 0.8 }), N);
+ const m = new THREE.Matrix4(), q = new THREE.Quaternion(), s = new THREE.Vector3(), p = new THREE.Vector3();
+ for (let i = 0; i < N; i++) {
+ const x = -18 + 36 * rand(i), z = -18 + 36 * rand(i + 100), y = heightAt(x, z);
+ const k = 0.8 + 0.5 * rand(i + 200);
+ p.set(x, y + 1.2 * k, z); s.set(k, k, k); m.compose(p, q, s); trunk.setMatrixAt(i, m);
+ p.set(x, y + 2.4 * k + 1.4 * k, z); m.compose(p, q, s); crown.setMatrixAt(i, m);
+ }
+ trunk.castShadow = crown.castShadow = true;
+ trunk.computeBoundingSphere(); crown.computeBoundingSphere();
+ zone.add(trunk, crown);
+ zone.userData.update = (t) => { crown.rotation.y = 0.0; }; // hook for per-zone motion
+ return zone;
+}
+```
+`src/scene.js`
+```js
+import * as THREE from 'three';
+import { buildEnv, heightAt, BOUNDS } from './env.js';
+import { buildGrove } from './zones/grove.js';
+export async function createScene({ THREE, renderer, loaders }) {
+ const scene = new THREE.Scene();
+ const env = buildEnv(THREE, scene);
+ const grove = buildGrove(THREE, { heightAt, loaders });
+ scene.add(grove);
+ const cameras = [ // plain objects; the harness builds the cameras
+ { name: 'Establishing', position: [38, 14, 42], lookAt: [0, 2, 0], fov: 40 },
+ { name: 'GroveWalk', position: [6, heightAt(6, 20) + 1.6, 20], lookAt: [0, 2, 0], fov: 55 },
+ ];
+ const movers = [grove];
+ return { scene, cameras, update(t, dt) { env.update(t, dt); for (const m of movers) m.userData.update?.(t, dt); } };
+}
+```
diff --git a/harness/codeverse/prompts/scene_threejs/cookbook.md b/harness/codeverse/prompts/scene_threejs/cookbook.md
new file mode 100644
index 00000000..c6571404
--- /dev/null
+++ b/harness/codeverse/prompts/scene_threejs/cookbook.md
@@ -0,0 +1,364 @@
+# Scene cookbook — multi-file three.js scenes (r182), headless-rendered by the harness
+
+Every `js` snippet runs as-is in node (the harness test suite concatenates them with
+`THREE` and the named addons in scope). Y-up, +Z front, meters. GLSL lives in
+`glsl_cookbook.md` — use its `makeShaderMaterial` for every custom shader.
+Use `read_cookbook(section="<heading>")` for one chapter.
+
+## Assembly skeleton (`src/scene.js` orchestrates, builds nothing itself)
+
+```js
+// scene.js: build env → zones → cameras; cache everything update() needs. Never traverse per frame.
+const rand = (i) => { const s = Math.sin(i * 12.9898 + 78.233) * 43758.5453; return s - Math.floor(s); };
+
+async function exampleCreateScene({ THREE, renderer, loaders }) {
+ const scene = new THREE.Scene();
+ const env = buildEnv(THREE, scene); // sky, sun, fog, ground (below)
+ const zones = [buildOrchard(THREE, { heightAt })]; // every zone: PascalCase Group
+ for (const z of zones) scene.add(z);
+ const movers = zones.filter(z => z.userData.update); // cached ONCE
+ const mats = collectAnimatedMaterials(scene); // from glsl_cookbook wire-up
+ const cameras = planCameras(THREE, scene); // measured, not guessed (below)
+ return {
+ scene, cameras,
+ update(t, dt) {
+ env.update(t, dt);
+ for (const z of movers) z.userData.update(t, dt);
+ for (const m of mats) m.userData.update(t, dt);
+ },
+ };
+}
+```
+
+## Environment (`src/env.js`): sun + sky + fog + ground — the scene's floor comes first
+
+```js
+const BOUNDS = { min: [-50, 0, -50], max: [50, 30, 50] }; // export const in real env.js
+const SUN_DIR = new THREE.Vector3(0.55, 0.62, 0.35).normalize(); // one sun direction, reused everywhere
+
+function heightAt(x, z) {
+ // deterministic analytic terrain — EVERY placement must call this, or things float
+ return 0.8 * Math.sin(x * 0.09) * Math.cos(z * 0.07) + 0.35 * Math.sin((x * 0.31 + z * 0.23));
+}
+
+function buildEnv(THREE, scene) {
+ // fog + matching background: the single biggest depth cue
+ scene.fog = new THREE.Fog(0xa8c4dd, 45, 160); // near ≈ bounds/2, far ≈ 1.6 × diagonal
+ scene.background = new THREE.Color(0xa8c4dd);
+ // sky dome gradient (cheap, always works; the Sky addon is the fancy alternative)
+ const skyGeo = new THREE.SphereGeometry(240, 24, 12);
+ const skyMat = new THREE.ShaderMaterial({
+ side: THREE.BackSide, fog: false, depthWrite: false,
+ uniforms: { uTop: { value: new THREE.Color(0x4e7fb8) }, uHorizon: { value: new THREE.Color(0xd8e4ec) } },
+ vertexShader: 'varying vec3 vP; void main() { vP = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
+ fragmentShader: `uniform vec3 uTop; uniform vec3 uHorizon; varying vec3 vP;
+ void main() { float h = clamp(normalize(vP).y, 0.0, 1.0); gl_FragColor = vec4(mix(uHorizon, uTop, pow(h, 0.55)), 1.0);
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ }`,
+ });
+ const sky = new THREE.Mesh(skyGeo, skyMat); sky.name = 'SkyDome'; scene.add(sky);
+ // lights: hemisphere fill + ONE shadow-casting sun. Physical intensities (no legacy lights).
+ scene.add(new THREE.HemisphereLight(0xbfd6f0, 0x5e5442, 0.55));
+ const sun = new THREE.DirectionalLight(0xfff0d8, 2.6);
+ sun.position.copy(SUN_DIR).multiplyScalar(80); sun.castShadow = true;
+ sun.shadow.mapSize.set(2048, 2048); sun.shadow.bias = -0.0005;
+ Object.assign(sun.shadow.camera, { left: -55, right: 55, top: 55, bottom: -55, near: 5, far: 200 });
+ scene.add(sun, sun.target);
+ // ground displaced by heightAt, vertex-coloured by slope/height (no textures)
+ const g = new THREE.PlaneGeometry(100, 100, 128, 128); g.rotateX(-Math.PI / 2);
+ const pos = g.attributes.position, col = new Float32Array(pos.count * 3);
+ const grass = new THREE.Color(0x5d7c3a), dirt = new THREE.Color(0x77644a), c = new THREE.Color();
+ for (let i = 0; i < pos.count; i++) {
+ const y = heightAt(pos.getX(i), pos.getZ(i));
+ pos.setY(i, y);
+ c.copy(dirt).lerp(grass, THREE.MathUtils.clamp(0.5 + y * 0.5, 0, 1));
+ col.set([c.r, c.g, c.b], i * 3);
+ }
+ g.setAttribute('color', new THREE.BufferAttribute(col, 3));
+ g.computeVertexNormals();
+ const ground = new THREE.Mesh(g, new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 1.0 }));
+ ground.name = 'Ground'; ground.receiveShadow = true; scene.add(ground);
+ return { update(t, dt) {} };
+}
+```
+
+Numbers: sun 2.2–3.2, hemisphere 0.4–0.7 (never both high — washed out); shadow map 2048,
+frustum just past the bounds; fog near ≈ half the bounds, far ≈ 1.5–2 × the diagonal;
+128 × 128 ground segments for 100 m (≈ 0.8 m resolution).
+
+## Water plane (use makeWaterMaterial from the GLSL cookbook)
+
+```js
+function buildLake(THREE, waterMat, x, z, r, level) {
+ const lake = new THREE.Mesh(new THREE.CircleGeometry(r, 48).rotateX(-Math.PI / 2), waterMat);
+ lake.name = 'Lake'; lake.position.set(x, level, z); lake.renderOrder = 2; // after opaque terrain
+ return lake; // carve the terrain BELOW level around (x, z) in heightAt, or the shore z-fights
+}
+```
+
+Why: water is a flat plane + the shader; the terrain function must dip below the water
+level inside the shoreline (add a radial depression term to `heightAt`).
+
+## Instanced vegetation and deterministic scatter
+
+```js
+function scatterMatrices(THREE, n, area, heightAt, seed = 1) {
+ // hash-based, deterministic; NEVER Math.random(). area = {x, z, w, d}
+ const out = []; const m = new THREE.Matrix4(), q = new THREE.Quaternion(), up = new THREE.Vector3(0, 1, 0);
+ for (let i = 0; i < n; i++) {
+ const x = area.x + (rand(seed + i) - 0.5) * area.w;
+ const z = area.z + (rand(seed + i + 5000) - 0.5) * area.d;
+ const s = 0.7 + 0.6 * rand(seed + i + 9000);
+ q.setFromAxisAngle(up, rand(seed + i + 13000) * Math.PI * 2);
+ m.compose(new THREE.Vector3(x, heightAt(x, z), z), q, new THREE.Vector3(s, s, s));
+ out.push(m.clone());
+ }
+ return out;
+}
+
+function buildOrchard(THREE, { heightAt }) {
+ const zone = new THREE.Group(); zone.name = 'Orchard';
+ const N = 60;
+ const trunkGeo = new THREE.CylinderGeometry(0.09, 0.16, 2.2, 7).translate(0, 1.1, 0); // origin at the ROOT
+ const crownGeo = new THREE.IcosahedronGeometry(1.3, 1).translate(0, 3.1, 0);
+ const trunks = new THREE.InstancedMesh(trunkGeo, new THREE.MeshStandardMaterial({ color: 0x5a4028, roughness: 0.9 }), N);
+ const crowns = new THREE.InstancedMesh(crownGeo, new THREE.MeshStandardMaterial({ color: 0x4a7a2e, roughness: 0.85 }), N);
+ const mats = scatterMatrices(THREE, N, { x: 0, z: -12, w: 36, d: 24 }, heightAt, 7);
+ const tint = new THREE.Color();
+ mats.forEach((m, i) => {
+ trunks.setMatrixAt(i, m); crowns.setMatrixAt(i, m);
+ crowns.setColorAt(i, tint.setHSL(0.26 + 0.05 * rand(i + 33), 0.45, 0.32 + 0.1 * rand(i + 66))); // per-instance variety
+ });
+ trunks.castShadow = crowns.castShadow = true;
+ trunks.instanceMatrix.needsUpdate = crowns.instanceMatrix.needsUpdate = true;
+ crowns.instanceColor.needsUpdate = true;
+ trunks.computeBoundingSphere(); crowns.computeBoundingSphere();
+ trunks.name = 'OrchardTrunks'; crowns.name = 'OrchardCrowns';
+ zone.add(trunks, crowns);
+ return zone;
+}
+const orchardDemo = buildOrchard(THREE, { heightAt });
+console.log('orchard instances', orchardDemo.children.map(c => c.count));
+```
+
+Why: geometry origin at the root + `heightAt` in the matrix = nothing floats; one
+InstancedMesh per organ = 2 draw calls for a forest; `setColorAt` breaks the clone look.
+For wind, give the crowns `makeSwayMaterial` from the GLSL cookbook.
+
+## Zones (`src/zones/*.js`): Groups with a bbox discipline
+
+```js
+// Each zone owns a rectangle of the plan; everything it adds stays inside it and sits on
+// heightAt (or on a structure the zone built). Naming: zone Group = plan zone name.
+function buildCampfire(THREE, { heightAt }) {
+ const zone = new THREE.Group(); zone.name = 'Campfire';
+ const cx = -14, cz = 10, cy = heightAt(-14, 10);
+ const stoneGeo = new THREE.IcosahedronGeometry(0.22, 0);
+ const stones = new THREE.InstancedMesh(stoneGeo, new THREE.MeshStandardMaterial({ color: 0x8b8b90, roughness: 0.95 }), 9);
+ const m = new THREE.Matrix4();
+ for (let i = 0; i < 9; i++) {
+ const a = i / 9 * Math.PI * 2;
+ m.makeTranslation(cx + Math.cos(a) * 0.8, heightAt(cx + Math.cos(a) * 0.8, cz + Math.sin(a) * 0.8) + 0.08, cz + Math.sin(a) * 0.8);
+ stones.setMatrixAt(i, m);
+ }
+ stones.computeBoundingSphere(); zone.add(stones);
+ const fire = new THREE.PointLight(0xff8033, 8.0, 12, 2); // physical falloff; small radius
+ fire.position.set(cx, cy + 0.5, cz); zone.add(fire);
+ zone.userData.update = (t) => { fire.intensity = 7.0 + Math.sin(t * 9.0) * 1.2 + Math.sin(t * 23.0) * 0.6; };
+ return zone;
+}
+const campfireDemo = buildCampfire(THREE, { heightAt }); campfireDemo.userData.update(1.0);
+```
+
+Rules: ≤ 3 shadow-casting lights per scene (the sun + 1–2 heroes); decorative lights get
+`castShadow = false` and distance-limited falloff.
+
+## Assets (`src/assets/*.js`) and GLB assets from Blender
+
+```js
+// Procedural asset factory: exactly like a static object part — Y-up, on y = 0, PascalCase.
+function buildLantern(THREE, opts = {}) {
+ const g = new THREE.Group(); g.name = 'Lantern';
+ const metal = new THREE.MeshStandardMaterial({ color: 0x2c2c30, roughness: 0.5, metalness: 0.8 });
+ const post = new THREE.Mesh(new THREE.CylinderGeometry(0.03, 0.04, 2.2, 10), metal);
+ post.position.y = 1.1; g.add(post);
+ const cage = new THREE.Mesh(new THREE.CylinderGeometry(0.12, 0.14, 0.26, 6), metal);
+ cage.position.y = 2.2 + 0.13 - 0.004; g.add(cage);
+ const glow = new THREE.Mesh(new THREE.SphereGeometry(0.08, 12, 8),
+ new THREE.MeshStandardMaterial({ color: 0xffe6b0, emissive: 0xffc46a, emissiveIntensity: 3.0 }));
+ glow.position.y = 2.33; g.add(glow);
+ return g;
+}
+// GLB asset (built by src/assets/<name>.py in Blender, compiled to public/assets/<name>.glb):
+async function loadAsset(loaders, name) {
+ const gltf = await loaders.gltf.loadAsync(`/assets/${name}.glb`);
+ const root = gltf.scene; root.name = name;
+ root.traverse(o => { if (o.isMesh) { o.castShadow = o.receiveShadow = true; } });
+ return root; // clone() per placement; GLB is Y-up meters already
+}
+console.log('lantern ok', buildLantern(THREE).children.length);
+```
+
+Why: a scene mixes cheap instanced fillers with a few hero assets; GLBs come in Y-up
+meters (same frame), so a loaded asset is placed exactly like a procedural one.
+
+## Animation: update(t, dt) patterns + particles
+
+```js
+function buildBoat(THREE) {
+ const boat = new THREE.Group(); boat.name = 'Boat';
+ const hull = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.2, 2.6, 8).rotateZ(Math.PI / 2).rotateY(Math.PI / 2),
+ new THREE.MeshStandardMaterial({ color: 0x7a4a26, roughness: 0.7 }));
+ boat.add(hull);
+ const home = new THREE.Vector3(6, 0.0, 8);
+ boat.position.copy(home);
+ boat.userData.update = (t) => { // bobbing + slow drift; pure function of t
+ boat.position.y = home.y + Math.sin(t * 0.9) * 0.06;
+ boat.rotation.z = Math.sin(t * 0.7 + 1.0) * 0.04;
+ boat.rotation.x = Math.sin(t * 1.1) * 0.03;
+ };
+ return boat;
+}
+// Particles: THREE.Points + PointsMaterial is enough for dust/fireflies/snow (custom
+// point shaders only if the plan demands). Recycle positions inside update.
+function buildFireflies(THREE, n = 120, area = { x: 0, z: 0, w: 30, d: 30 }) {
+ const pos = new Float32Array(n * 3);
+ for (let i = 0; i < n; i++) pos.set([area.x + (rand(i) - 0.5) * area.w, 0.6 + rand(i + 300) * 2.2, area.z + (rand(i + 600) - 0.5) * area.d], i * 3);
+ const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ const pts = new THREE.Points(geo, new THREE.PointsMaterial({ color: 0xd9f76e, size: 0.06, sizeAttenuation: true, transparent: true, opacity: 0.9 }));
+ pts.name = 'Fireflies';
+ const base = pos.slice();
+ pts.userData.update = (t) => {
+ const p = geo.attributes.position.array;
+ for (let i = 0; i < n; i++) {
+ p[i * 3] = base[i * 3] + Math.sin(t * 0.7 + i) * 0.4;
+ p[i * 3 + 1] = base[i * 3 + 1] + Math.sin(t * 1.3 + i * 2.1) * 0.25;
+ p[i * 3 + 2] = base[i * 3 + 2] + Math.cos(t * 0.5 + i * 0.7) * 0.4;
+ }
+ geo.attributes.position.needsUpdate = true;
+ };
+ return pts;
+}
+const ff = buildFireflies(THREE); ff.userData.update(2.0);
+console.log('fireflies', ff.geometry.attributes.position.count);
+```
+
+Rules: `update` mutates cached objects only — no `new`, no `traverse`, no material
+creation per frame. Everything is a function of `t` (deterministic renders at t = 1.5).
+
+## Cameras: measured, never guessed
+
+```js
+function planCameras(THREE, scene) {
+ const box = new THREE.Box3(); // measure CONTENT, not the 240 m sky dome
+ scene.traverse(o => { if (o.isMesh && o.name !== 'SkyDome') box.expandByObject(o); });
+ if (box.isEmpty()) box.set(new THREE.Vector3(-20, 0, -20), new THREE.Vector3(20, 10, 20));
+ const size = box.getSize(new THREE.Vector3()), c = box.getCenter(new THREE.Vector3());
+ const d = Math.max(size.x, size.z);
+ return [
+ // 1) establishing: high 3/4, sees ≥70% of bounds, sun BEHIND the camera shoulder
+ { name: 'Establishing', position: [c.x + d * 0.55, size.y * 1.1 + 6, c.z + d * 0.6], lookAt: [c.x, 2, c.z], fov: 42 },
+ // 2) mid: inside the scene at eye height, aimed at a zone's focal point
+ { name: 'OrchardMid', position: [8, heightAt(8, 6) + 1.6, 6], lookAt: [0, heightAt(0, -10) + 2.0, -10], fov: 50 },
+ // 3) detail: 2-4 m from a hero object, slightly above eye line
+ { name: 'CampfireDetail', position: [-11, heightAt(-11, 8) + 1.8, 8], lookAt: [-14, heightAt(-14, 10) + 0.6, 10], fov: 45 },
+ ];
+}
+console.log('cameras', planCameras(THREE, new THREE.Scene()).map(c => c.name));
+```
+
+Rules: eye height 1.6 m (+ terrain!), fov 35–60, look at a focal POINT (an object, not
+the horizon), never inside geometry and ≥ 0.5 m from any surface, 3–5 cameras:
+establishing → mid → detail. Compute positions from measured bounds/heightAt, not vibes.
+
+## Post-processing (optional; the default pipeline renders WITHOUT it)
+
+```js
+import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
+import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
+import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
+import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
+
+// Export from scene.js ONLY if the plan asks for bloom; harness support is optional, so
+// the scene must also look right without it (emissiveIntensity ≤ 3, no white-out).
+function makeComposer(THREE, renderer, scene, camera, width, height) {
+ const composer = new EffectComposer(renderer);
+ composer.setSize(width, height);
+ composer.addPass(new RenderPass(scene, camera));
+ const bloom = new UnrealBloomPass(new THREE.Vector2(width, height), 0.35, 0.6, 0.85);
+ composer.addPass(bloom); // strength ≤ 0.5, threshold ≥ 0.8: glow, not soup
+ composer.addPass(new OutputPass()); // ALWAYS last: tone mapping + sRGB live here
+ return composer;
+}
+console.log('composer factory ready', typeof makeComposer);
+```
+
+## Performance budget
+
+* ≤ 2 M triangles, ≤ 200 draw calls, ≤ 40 materials, ≤ 3 shadow casting lights.
+* Anything placed > 5 × = InstancedMesh; static clutter of one material = `mergeGeometries`.
+* Ground 128² segments max; trees 300–800 tris each (instanced), hero assets ≤ 40 k.
+* `update` < 4 ms: cache lists, mutate in place, no per-frame allocation.
+* `scene_probe` reports draws/tris/fps — run it before polishing.
+
+## Pitfalls (symptom → cause → fix)
+
+1. **Everything floats / sinks on a slope** → placement ignored `heightAt`; every position
+ is `(x, heightAt(x, z) + halfHeightOrRootOffset, z)`.
+2. **Black frame** → no lights, or fog far < camera distance, or camera inside a hill.
+ **White frame** → sun + hemisphere both high + fog colour white + bloom.
+3. **Scene washed out** → ambient/hemisphere too strong; contrast comes from the sun/shadow
+ ratio (sun ≈ 4–6 × hemisphere).
+4. **Shadows missing** → `castShadow` on the light AND meshes, `receiveShadow` on ground,
+ shadow camera frustum too small, or light too far (increase `far`).
+5. **Shadow acne / peter-panning** → `sun.shadow.bias = -0.0005`, keep mapSize 2048.
+6. **`Math.random()` anywhere** → different geometry every build; renders not reproducible;
+ use `rand(i)` hashes with explicit seeds.
+7. **fps < 20** → count draw calls first (`scene_probe`); the usual criminals: hundreds of
+ Meshes that should be instances, per-frame `traverse`, 4096 shadow maps, fog off with a
+ 500 m far plane.
+8. **Fog hides everything** → `Fog(near, far)` in metres — near 45/far 160 for a 100 m
+ scene; never near 1/far 10.
+9. **Sky dome black or fogged** → sky material needs `fog: false`, `side: BackSide`,
+ `depthWrite: false`, and the tonemap/colorspace includes (see the env recipe).
+10. **GLB asset invisible** → wrong URL (must be `/assets/<name>.glb`), or its pivot is not
+ at the base; re-export from Blender with the object on z = 0.
+11. **Camera inside a tree / wall** → positions are guesses; compute from `heightAt` +
+ known object positions, then check with `render_sheet` (the harness flags
+ camera-inside-geometry).
+12. **update() allocates** (`new Vector3` per frame, `getSize` per frame) → GC hitches;
+ hoist scratch objects to module scope.
+13. **Zones overlap / fight** → each zone stays in its plan rectangle; shared borders
+ belong to the env (paths, fences).
+14. **Lights per lantern** → 30 PointLights kill the frame; ONE emissive material + 1–2
+ real lights near the camera path.
+
+## Self-check (before you call it done)
+
+```js
+function sceneSelfcheck(THREE, scene, cameras) {
+ let tris = 0, draws = 0, lights = 0, shadowLights = 0;
+ scene.traverse(o => {
+ if (o.isLight) { lights++; if (o.castShadow) shadowLights++; }
+ if (o.isMesh || o.isPoints) {
+ draws++;
+ const g = o.geometry, n = g.index ? g.index.count / 3 : g.attributes.position.count / 3;
+ tris += n * (o.isInstancedMesh ? o.count : 1);
+ }
+ });
+ if (tris > 2e6) throw new Error(`tri budget blown: ${tris}`);
+ if (draws > 200) throw new Error(`draw calls: ${draws} > 200`);
+ if (shadowLights > 3) throw new Error(`${shadowLights} shadow lights (max 3)`);
+ if (!scene.fog) throw new Error('scene.fog not set');
+ if (!cameras || cameras.length < 2) throw new Error('need 3-5 cameras');
+ console.log(`[selfcheck] draws=${draws} tris=${Math.round(tris)} lights=${lights} cameras=${cameras.length}`);
+}
+const demoScene = new THREE.Scene(); buildEnv(THREE, demoScene);
+demoScene.add(orchardDemo, campfireDemo, ff);
+sceneSelfcheck(THREE, demoScene, planCameras(THREE, demoScene));
+```
+
+Then: `build` → `scene_probe` (draws/tris/fps/console) → `render_sheet` per camera →
+`shader_probe` if you wrote GLSL → fix the worst → repeat. Look at every camera's frame:
+no black, no white-out, nothing floating, the subject actually in frame.
diff --git a/harness/codeverse/prompts/scene_threejs/glsl_cookbook.md b/harness/codeverse/prompts/scene_threejs/glsl_cookbook.md
new file mode 100644
index 00000000..5f4d2d9d
--- /dev/null
+++ b/harness/codeverse/prompts/scene_threejs/glsl_cookbook.md
@@ -0,0 +1,382 @@
+# GLSL cookbook — custom shaders that SURVIVE this renderer (three r182, WebGL2)
+
+Three ways a shader "fails" with no error: missing log-depth chunks (discarded behind
+opaque geometry when the renderer uses a logarithmic depth buffer), missing fog chunks
+(the effect keeps full contrast while the world recedes — the sticker look), missing
+tonemap/colorspace output (dark, wrong colours). The boilerplate below carries all of
+them. Every factory here is `export function make<Name>Material(THREE, opts)` and the
+harness test suite compiles each one in headless Chrome, on a Mesh AND an InstancedMesh.
+
+Conventions: uniforms `uTime` (seconds) driven via `mat.userData.update(t, dt)`;
+`varying` spelling for interstage declarations (three defines it for both GLSL dialects);
+never write `#version` or `precision` lines; every `#include <...>` alone on its line.
+
+## Shared GLSL library (hash, noise, fbm, fresnel)
+
+```js
+// src/shaders/lib.js — prepend GLSL_LIB into any shader head that needs it.
+export const GLSL_LIB = /* glsl */ `
+float c3vHash11(float p) { p = fract(p * 0.1031); p *= p + 33.33; return fract(p * (p + p)); }
+float c3vHash21(vec2 p) {
+ vec3 p3 = fract(vec3(p.xyx) * 0.1031);
+ p3 += dot(p3, p3.yzx + 33.33);
+ return fract((p3.x + p3.y) * p3.z);
+}
+float c3vNoise2(vec2 p) {
+ vec2 i = floor(p), f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ float a = c3vHash21(i), b = c3vHash21(i + vec2(1.0, 0.0));
+ float c = c3vHash21(i + vec2(0.0, 1.0)), d = c3vHash21(i + vec2(1.0, 1.0));
+ return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);
+}
+float c3vFbm2(vec2 p) { // 4 octaves, range ~0..1
+ float s = 0.0, a = 0.5;
+ for (int i = 0; i < 4; i++) { s += a * c3vNoise2(p); p *= 2.03; a *= 0.5; }
+ return s;
+}
+float c3vFresnel(vec3 n, vec3 viewDir, float power) {
+ return pow(1.0 - clamp(dot(normalize(n), normalize(viewDir)), 0.0, 1.0), power);
+}
+`;
+```
+
+Why: value noise over a hash — no textures, no extensions; `c3vFbm2` is the workhorse for
+water, fog, dirt, wood grain. Loop bounds are constant (GLSL requires it).
+
+## The boilerplate: makeShaderMaterial (fog + log-depth + uTime + tonemap, copy whole)
+
+```js
+// src/shaders/base.js — the ONE way to build a ShaderMaterial here. Write only the
+// bodies of main(); the wrapper owns the chunks that make it a good citizen.
+function uniformDecl(THREE, name, u) { // custom uniforms are NOT auto-declared in GLSL
+ const v = u.value;
+ const t = v && v.isColor ? 'vec3' : v && v.isVector2 ? 'vec2' : v && v.isVector3 ? 'vec3'
+ : v && v.isVector4 ? 'vec4' : v && v.isMatrix4 ? 'mat4' : v && v.isTexture ? 'sampler2D'
+ : typeof v === 'number' ? 'float' : null;
+ return t ? `uniform ${t} ${name};` : '';
+}
+
+export function makeShaderMaterial(THREE, opts = {}) {
+ const { uniforms = {}, varyings = '', vertexHead = '', fragmentHead = '',
+ vertexMain = '', fragmentMain = 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);',
+ fog = true, additive = false, name = 'C3vShader', ...rest } = opts;
+ const decls = ['uniform float uTime;',
+ ...Object.entries(uniforms).map(([k, u]) => uniformDecl(THREE, k, u))].join('\n');
+ const vs = [
+ '#include <common>',
+ '#include <logdepthbuf_pars_vertex>',
+ fog ? '#include <fog_pars_vertex>' : '',
+ decls, varyings, vertexHead,
+ 'void main() {',
+ ' vec3 transformed = position;',
+ vertexMain,
+ ' vec4 mvPosition = modelViewMatrix * vec4(transformed, 1.0);',
+ '#ifdef USE_INSTANCING',
+ ' mvPosition = modelViewMatrix * instanceMatrix * vec4(transformed, 1.0);',
+ '#endif',
+ ' gl_Position = projectionMatrix * mvPosition;',
+ '#include <logdepthbuf_vertex>',
+ fog ? '#include <fog_vertex>' : '',
+ '}',
+ ].filter(Boolean).join('\n');
+ const fs = [
+ '#include <common>',
+ '#include <logdepthbuf_pars_fragment>',
+ fog ? '#include <fog_pars_fragment>' : '',
+ decls, varyings, fragmentHead,
+ 'void main() {',
+ '#include <logdepthbuf_fragment>',
+ fragmentMain,
+ '#include <tonemapping_fragment>',
+ '#include <colorspace_fragment>',
+ // fog LAST, matching three's own materials; additive light must FADE, not tint:
+ fog ? (additive ? 'gl_FragColor.a *= 1.0 - smoothstep(fogNear, fogFar, vFogDepth);'
+ : '#include <fog_fragment>') : '',
+ '}',
+ ].filter(Boolean).join('\n');
+ const mat = new THREE.ShaderMaterial({
+ // fog uniforms MUST exist in the map or the scene fog has nowhere to land:
+ uniforms: THREE.UniformsUtils.merge([
+ fog ? THREE.UniformsLib.fog : {}, { uTime: { value: 0 } }, uniforms]),
+ vertexShader: vs, fragmentShader: fs, fog, ...(additive
+ ? { transparent: true, depthWrite: false, blending: THREE.AdditiveBlending } : {}), ...rest });
+ mat.name = name;
+ mat.userData.update = (t) => { mat.uniforms.uTime.value = t; };
+ return mat;
+}
+```
+
+Wire-up in `scene.js` (once, at build time — never traverse inside `update`):
+
+```js
+export function collectAnimatedMaterials(scene) {
+ const mats = [];
+ scene.traverse((o) => {
+ const list = Array.isArray(o.material) ? o.material : (o.material ? [o.material] : []);
+ for (const m of list) if (m.userData && typeof m.userData.update === 'function' && !mats.includes(m)) mats.push(m);
+ });
+ return mats; // in update(t, dt): for (const m of mats) m.userData.update(t, dt);
+}
+```
+
+## Scrolling water (plane at the water level)
+
+```js
+export function makeWaterMaterial(THREE, opts = {}) {
+ const shallow = new THREE.Color(opts.shallow ?? 0x3fa8b8), deep = new THREE.Color(opts.deep ?? 0x0b3446);
+ return makeShaderMaterial(THREE, {
+ name: 'Water', transparent: true, depthWrite: false, side: THREE.DoubleSide,
+ uniforms: { uShallow: { value: shallow }, uDeep: { value: deep }, uOpacity: { value: opts.opacity ?? 0.85 } },
+ varyings: 'varying vec2 vWuv; varying vec3 vN; varying vec3 vV;',
+ vertexHead: GLSL_LIB,
+ vertexMain: `
+ vWuv = (modelMatrix * vec4(transformed, 1.0)).xz * 0.35;
+ // small ripple displacement so the sun break-up reads at grazing angles
+ transformed.y += 0.03 * (c3vNoise2(vWuv * 2.0 + uTime * 0.35) - 0.5);
+ vN = normalize(normalMatrix * normal);
+ vV = -(modelViewMatrix * vec4(transformed, 1.0)).xyz;`,
+ fragmentHead: GLSL_LIB,
+ fragmentMain: `
+ // two noise fields scrolling AGAINST each other never look like a conveyor belt
+ float n1 = c3vFbm2(vWuv * 3.0 + vec2(uTime * 0.06, uTime * 0.028));
+ float n2 = c3vFbm2(vWuv * 5.0 - vec2(uTime * 0.043, uTime * 0.07) + 17.0);
+ float ripple = n1 * 0.6 + n2 * 0.4;
+ vec3 col = mix(uDeep, uShallow, smoothstep(0.35, 0.75, ripple));
+ float f = c3vFresnel(vN, vV, 3.0);
+ col += vec3(0.9, 0.95, 1.0) * f * 0.35; // sky glint at grazing angles
+ col += vec3(1.0) * smoothstep(0.72, 0.78, ripple) * 0.25; // sparse crest sparkle
+ gl_FragColor = vec4(col, uOpacity);`,
+ });
+}
+```
+
+Numbers: scroll speeds 0.03–0.08 (m-ish units per second), two layers at scales 3 and 5,
+opacity 0.8–0.9, `depthWrite: false` so shorelines don't z-fight.
+
+## Waterfall (falling water accelerates: ride features on sqrt(drop))
+
+```js
+export function makeWaterfallMaterial(THREE, opts = {}) {
+ return makeShaderMaterial(THREE, {
+ name: 'Waterfall', transparent: true, depthWrite: false, side: THREE.DoubleSide,
+ uniforms: { uColor: { value: new THREE.Color(opts.color ?? 0xcfe8f2) }, uHeight: { value: opts.height ?? 6.0 } },
+ varyings: 'varying vec2 vUvw;',
+ vertexMain: 'vUvw = uv;',
+ fragmentHead: GLSL_LIB,
+ fragmentMain: `
+ float drop = 1.0 - vUvw.y; // 0 at the lip, 1 at the pool
+ float age = sqrt(max(drop, 1e-4)); // free fall: distance ~ time^2
+ float lane = vUvw.x * 14.0;
+ float streak = c3vNoise2(vec2(lane, age * 6.0 - uTime * 1.6 + c3vHash11(floor(lane)) * 7.0));
+ float body = smoothstep(0.35, 0.75, streak) * (0.55 + 0.45 * drop);
+ float foam = smoothstep(0.8, 1.0, drop) * c3vFbm2(vec2(lane, uTime * 2.0));
+ float a = clamp(body * 0.75 + foam * 0.9, 0.0, 1.0) * 0.9;
+ gl_FragColor = vec4(uColor, a);`,
+ });
+}
+```
+
+Why: scrolling `uv.y` linearly reads as a conveyor; sampling on `sqrt(drop)` makes the
+sheet visibly accelerate. Per-lane hash offsets stop the herringbone weave.
+
+## Glow / pulse emissive (lanterns, runes, portals, coals)
+
+```js
+export function makeGlowMaterial(THREE, opts = {}) {
+ return makeShaderMaterial(THREE, {
+ name: 'Glow', additive: true, side: THREE.DoubleSide,
+ uniforms: { uColor: { value: new THREE.Color(opts.color ?? 0xffa64d) },
+ uStrength: { value: opts.strength ?? 1.2 }, uSpeed: { value: opts.speed ?? 2.0 } },
+ varyings: 'varying vec3 vN; varying vec3 vV;',
+ vertexMain: `
+ vN = normalize(normalMatrix * normal);
+ vV = -(modelViewMatrix * vec4(transformed, 1.0)).xyz;`,
+ fragmentHead: GLSL_LIB,
+ fragmentMain: `
+ float pulse = 0.75 + 0.25 * sin(uTime * uSpeed);
+ float rim = c3vFresnel(vN, vV, 2.0);
+ float core = 1.0 - rim;
+ gl_FragColor = vec4(uColor * uStrength * pulse * (0.35 + 0.65 * core), core * 0.9 + 0.1);`,
+ });
+}
+```
+
+Why: `additive: true` sets AdditiveBlending + `depthWrite:false` + distance fade through
+ALPHA (ordinary fog would make added light brighter with distance). Strength ≤ 1.5
+without bloom; the harness renders without a bloom pass.
+
+## God-ray billboard (light shafts through trees / windows)
+
+```js
+export function makeGodRayMaterial(THREE, opts = {}) {
+ return makeShaderMaterial(THREE, {
+ name: 'GodRay', additive: true, side: THREE.DoubleSide,
+ uniforms: { uColor: { value: new THREE.Color(opts.color ?? 0xfff2cc) }, uStrength: { value: opts.strength ?? 0.35 } },
+ varyings: 'varying vec2 vRuv;',
+ vertexMain: 'vRuv = uv;',
+ fragmentHead: GLSL_LIB,
+ fragmentMain: `
+ float across = 1.0 - abs(vRuv.x - 0.5) * 2.0; // soft at both side edges
+ float along = smoothstep(0.0, 0.25, vRuv.y) * (1.0 - smoothstep(0.55, 1.0, vRuv.y));
+ float shimmer = 0.8 + 0.2 * c3vNoise2(vec2(vRuv.x * 6.0, uTime * 0.15));
+ gl_FragColor = vec4(uColor, uStrength * across * across * along * shimmer);`,
+ });
+}
+// Use on tall thin planes (e.g. 0.6 × 8 m), tilted to the sun azimuth, uv.y = down the shaft.
+// 2–4 shafts maximum; they ADD light, so keep uStrength 0.2–0.5.
+```
+
+## Height fog curtain (valley mist, dawn haze — no postprocessing needed)
+
+```js
+export function makeHeightFogMaterial(THREE, opts = {}) {
+ return makeShaderMaterial(THREE, {
+ name: 'HeightFog', transparent: true, depthWrite: false, side: THREE.DoubleSide, fog: false,
+ uniforms: { uColor: { value: new THREE.Color(opts.color ?? 0xcdd8e4) },
+ uTop: { value: opts.top ?? 3.0 }, uDensity: { value: opts.density ?? 0.45 } },
+ varyings: 'varying vec3 vW;',
+ vertexMain: 'vW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ fragmentHead: GLSL_LIB,
+ fragmentMain: `
+ float h = clamp(1.0 - vW.y / max(uTop, 0.01), 0.0, 1.0); // thick low, gone at uTop
+ float drift = c3vFbm2(vW.xz * 0.08 + vec2(uTime * 0.02, uTime * 0.013));
+ gl_FragColor = vec4(uColor, h * h * uDensity * (0.55 + 0.45 * drift));`,
+ });
+}
+// Mount on 2-3 huge vertical planes (or a cylinder shell) between the camera and the far zone.
+```
+
+## Wind sway on a built-in material (onBeforeCompile patch, instancing-safe)
+
+```js
+// Patch a MeshStandardMaterial so lighting/shadows/fog stay; inject sway into begin_vertex.
+export function makeSwayMaterial(THREE, opts = {}) {
+ const mat = new THREE.MeshStandardMaterial({ color: opts.color ?? 0x3f7a2f, roughness: 0.9 });
+ const u = { uTime: { value: 0 }, uSway: { value: opts.sway ?? 0.12 }, uSwayFreq: { value: opts.freq ?? 1.4 } };
+ mat.onBeforeCompile = (shader) => {
+ Object.assign(shader.uniforms, u);
+ shader.vertexShader = shader.vertexShader
+ .replace('#include <common>', '#include <common>\nuniform float uTime; uniform float uSway; uniform float uSwayFreq;')
+ .replace('#include <begin_vertex>', `
+ #include <begin_vertex>
+ {
+ // phase differs per instance so a field never waves in lockstep
+ float c3vPhase = 0.0;
+ #ifdef USE_INSTANCING
+ c3vPhase = instanceMatrix[3].x * 1.7 + instanceMatrix[3].z * 2.3;
+ #endif
+ float c3vBend = pow(clamp(transformed.y / 2.0, 0.0, 1.0), 1.5); // roots stay planted
+ transformed.x += sin(uTime * uSwayFreq + c3vPhase) * uSway * c3vBend;
+ transformed.z += cos(uTime * uSwayFreq * 0.83 + c3vPhase) * uSway * 0.6 * c3vBend;
+ }`);
+ };
+ // three caches programs by material type: two differently-patched Standards would share
+ // one program without a distinct key.
+ mat.customProgramCacheKey = () => 'c3v_sway_v1';
+ mat.userData.update = (t) => { u.uTime.value = t; };
+ return mat;
+}
+```
+
+Why: patching keeps PBR lighting and shadows; the ONLY safe injection points are chunk
+markers (`begin_vertex` for positions, `color_fragment` for albedo). Shadows are cast
+from the unswayed mesh (the depth material is not patched) — invisible at sway ≤ 0.15 m.
+
+## Triplanar procedural surface (cliffs, terrain — no UVs needed)
+
+```js
+export function makeTriplanarMaterial(THREE, opts = {}) {
+ const a = new THREE.Color(opts.rock ?? 0x6b6258), b = new THREE.Color(opts.moss ?? 0x4a5d33);
+ return makeShaderMaterial(THREE, {
+ name: 'Triplanar',
+ uniforms: { uRock: { value: a }, uMoss: { value: b }, uScale: { value: opts.scale ?? 0.6 } },
+ varyings: 'varying vec3 vWp; varying vec3 vWn; varying vec3 vNv; varying vec3 vVv;',
+ vertexMain: `
+ vWp = (modelMatrix * vec4(transformed, 1.0)).xyz;
+ vWn = normalize(mat3(modelMatrix) * normal);
+ vNv = normalize(normalMatrix * normal);
+ vVv = -(modelViewMatrix * vec4(transformed, 1.0)).xyz;`,
+ fragmentHead: GLSL_LIB,
+ fragmentMain: `
+ vec3 w = abs(vWn); w = w / (w.x + w.y + w.z + 1e-5); // blend weights
+ float tx = c3vFbm2(vWp.zy * uScale), ty = c3vFbm2(vWp.xz * uScale), tz = c3vFbm2(vWp.xy * uScale);
+ float g = tx * w.x + ty * w.y + tz * w.z; // seam-free grain
+ vec3 col = mix(uRock, uRock * (0.55 + 0.9 * g), 1.0); // value break-up
+ col = mix(col, uMoss, smoothstep(0.55, 0.9, vWn.y) * smoothstep(0.35, 0.7, g)); // moss on up-faces
+ float lambert = 0.35 + 0.65 * clamp(dot(vNv, normalize(vec3(0.4, 0.8, 0.3))), 0.0, 1.0);
+ gl_FragColor = vec4(col * lambert, 1.0);`,
+ });
+}
+```
+
+Why: three fbm samples blended by |normal| kill UV stretching on steep faces; moss grows
+on up-facing surfaces (`vWn.y`). This material fakes its own lambert — use it on set
+dressing, not on hero objects (or patch a Standard material instead).
+
+## Toon + outline
+
+```js
+export function makeToonMaterial(THREE, opts = {}) {
+ return makeShaderMaterial(THREE, {
+ name: 'Toon',
+ uniforms: { uColor: { value: new THREE.Color(opts.color ?? 0xcc5533) },
+ uSun: { value: (opts.sun ?? new THREE.Vector3(0.4, 0.8, 0.3)).clone().normalize() } },
+ varyings: 'varying vec3 vTn;',
+ vertexMain: 'vTn = normalize(mat3(modelMatrix) * normal);',
+ fragmentMain: `
+ float d = clamp(dot(normalize(vTn), uSun), 0.0, 1.0);
+ float band = d > 0.66 ? 1.0 : (d > 0.33 ? 0.62 : 0.34); // 3 hard bands
+ gl_FragColor = vec4(uColor * band, 1.0);`,
+ });
+}
+// Outline: add a slightly inflated BackSide copy — no shader needed:
+export function addOutline(THREE, mesh, thickness = 0.02, color = 0x101014) {
+ const out = new THREE.Mesh(mesh.geometry,
+ new THREE.MeshBasicMaterial({ color, side: THREE.BackSide }));
+ out.scale.setScalar(1 + thickness); out.name = mesh.name + 'Outline';
+ mesh.add(out); return out;
+}
+```
+
+## Pitfalls (symptom → cause → fix)
+
+1. **Effect invisible behind objects, no error** → missing `logdepthbuf_*` chunks while the
+ renderer runs a logarithmic depth buffer. Use `makeShaderMaterial` (chunks included).
+2. **Effect stays full-contrast while the world fogs out** → missing fog chunks / `fog:
+ true` / fog uniforms. All three are required; the boilerplate does them.
+3. **"redefinition of 'vUv'"** → the varying is declared in `varyings` AND in your head
+ string, or you redeclared a built-in (`position`, `normal`, `uv`, `projectionMatrix`,
+ `modelViewMatrix`, `normalMatrix`, `cameraPosition`). Declare each varying once; never
+ redeclare built-ins.
+4. **"'#version' must occur first" / "unsupported shader version"** → you wrote `#version`
+ or `precision` in a ShaderMaterial; three prepends its own header. Delete them.
+5. **`out vec4` + `gl_FragColor` conflict** → GLSL3 syntax in a GLSL1 material. Use
+ `varying` + `gl_FragColor` + `texture2D` everywhere; do not set `glslVersion`.
+6. **`#include` sharing a line** (`{ #include <fog_fragment> }`) → silent compile failure.
+ Every include alone on its own line.
+7. **`pow(x, 2)` / `mod(i, 2)` / `vec3(v2)`** → no int↔float promotion: `2.0`, `float(i)`,
+ matching constructors. Loops need constant bounds (`for (int i = 0; i < 4; i++)`).
+8. **"'uName' : undeclared identifier"** → ShaderMaterial does NOT auto-declare custom
+ uniforms in GLSL; `makeShaderMaterial` generates the declarations from the uniforms
+ map — do not redeclare them (or uTime) in your head strings. A uniform that never
+ moves: you replaced the uniforms object instead of mutating `uniforms.uTime.value`;
+ drive time from `update(t, dt)` via `mat.userData.update(t)` — never `Date.now()`.
+9. **Instanced mesh: all copies at the origin / no sway variation** → ShaderMaterial must
+ apply `instanceMatrix` under `#ifdef USE_INSTANCING` (the boilerplate does);
+ `onBeforeCompile` code that needs world position must read `instanceMatrix[3]`.
+10. **Two patched Standard materials render identically** → shared program cache; give each
+ patch flavour its own `customProgramCacheKey`.
+11. **Transparent water z-fights the shore / hides particles** → `transparent: true` needs
+ `depthWrite: false`; large transparent planes render in draw order, so keep water
+ slightly below the bank top.
+12. **Glow gets BRIGHTER with distance** → additive material with the normal fog mix; fade
+ through alpha (the boilerplate's `additive: true` path).
+13. **Black output with tone mapping** → colours built in [0,1] then multiplied down twice;
+ remember output passes through ACES + sRGB: author linear colours ~[0, 1.5] and check
+ a mid-grey renders mid-grey.
+14. **`fwidth`/`dFdx` "extension" errors** → they are core in WebGL2; delete any
+ `#extension GL_OES_standard_derivatives` line.
+15. **`Material.clone()` loses the patch** → `onBeforeCompile` is not cloned; build a fresh
+ material from the factory instead of cloning patched ones.
+16. **Shadow acne / wrong shadows on displaced vertices** → the depth pass is not patched;
+ keep vertex displacement small (≤ 0.15 m) or set `castShadow = false` on the mesh.
diff --git a/harness/codeverse/prompts/system/harness_contract.md b/harness/codeverse/prompts/system/harness_contract.md
new file mode 100644
index 00000000..5bd9962f
--- /dev/null
+++ b/harness/codeverse/prompts/system/harness_contract.md
@@ -0,0 +1,88 @@
+# 3dcodeverse harness contract (read once, obey always)
+
+You are a **3D code author** working inside the `3dcodeverse` harness (CLI `c3v`).
+You write RAW executable code in one language (bpy / CadQuery / three.js / URDF+bpy /
+multi-file three.js+GLSL). The harness — not you — builds, exports, measures, renders
+and judges. Your code is the deliverable; every GLB / PNG / URDF export is derived from it.
+
+## 1. Where you may write
+
+```
+src/ your code. ONLY place you create or edit files.
+public/ (scene track only) compiled assets such as public/assets/<name>.glb.
+artifacts/ harness output (object.glb, renders/, gates/, measurement.json). READ-ONLY.
+```
+* Never write under `artifacts/`, never create files outside `src/` and `public/`.
+* Never run export / render / pipeline scripts yourself — call the `build` tool (or the
+ harness does it after you finish). Do not copy wrapper scripts into `src/`.
+* Never import from `codeverse`, the harness, `runtime_js/`, or any helper SDK. Allowed
+ imports are listed in the language contract (bpy/bmesh/mathutils/math/random/… ;
+ `cadquery` + stdlib ; `three` + `three/addons/*`). Nothing else. No network, no DOM,
+ no file I/O from generated code (except `src/robot.urdf` for the articulated track).
+
+## 2. Code is truth
+
+* The plan (`plan.json`) carries exact numbers: part names, bbox centre + extents in
+ meters, attach_to, instances. **Use those numbers literally** in your code (as named
+ constants at the top of the file). If you disagree with a number, keep the plan's value
+ and note why in a comment — do not silently drift.
+* Part names are PascalCase and unique (`SeatCushion`, `LeftFrontLeg`); object / node /
+ link names in the exported artifact must equal the plan's part names exactly.
+* Deterministic: seed every random source (`random.seed(0)`, a hash-based `rand(i)`), no
+ time-dependent geometry. Two builds of the same code must produce identical geometry.
+* Real-world scale: a chair seat is 0.45 m high, a door 2.0 m, a mug 0.09 m. Check your
+ overall bbox against the plan's `overall_bbox` before you finish.
+
+## 3. Physical plausibility (what gates will reject)
+
+* **Touch or overlap, never float**: every part must share volume with (or sit flush
+ against) at least one other part; seams overlap by ≥ 2 mm (`CONTACT_GAP_M = 0.002`).
+ No piece may hover. The connectivity gate hard-fails on any island with a positive gap.
+* **Weld by overlap, not by rods**: fix a floating piece by extending / embedding it
+ ≥ 2 mm into its neighbour, never by adding thin connector sticks.
+* **Ground contact**: the lowest point of the object is at up = 0 (± 1 mm); footprint
+ centred on the up-axis. Scenes: bounds as declared in the plan.
+* **No concealed interpenetration**: neighbours that are not welded keep ≥ 15 mm
+ clearance; limbs do not sink into bodies; rings wrap cores, they do not intersect them.
+* **Hollow things are hollow** (mugs, bowls, boxes, drawers): cut the cavity; walls
+ 1–6 mm for small objects, 12–20 mm for furniture.
+* **Symmetry by construction**: mirror / instance identical parts from one builder
+ instead of writing the same geometry twice.
+
+## 4. You have eyes — use them
+
+Before declaring done you MUST look at what you built: `build` → `render_sheet` (4 views)
+→ `check_connectivity` → fix → `isolate` a doubtful part → `cross_section` for cavities
+→ `compare_silhouette` if a reference image exists. Read the numbers (bbox, islands,
+tri count) and the images. "It should be fine" is not evidence; a render is.
+
+## 5. Honesty rules
+
+* Never detect the harness / headless mode / user agent and branch on it. One code path.
+* Never special-case a check to make it pass (e.g. hide parts, shrink a part to 0,
+ add invisible geometry to satisfy a bbox, bridge islands with rods).
+* Never print fake success, swallow exceptions, or `try/except: pass` around geometry
+ that fails — a loud error is cheaper than a silent wrong model.
+* Do not edit `plan.json`, `spec.json` or anything under `artifacts/`.
+
+## 6. Performance limits
+
+* Static objects ≤ 600 k triangles (aim 20–150 k); scenes ≤ 2 M triangles and ≤ 200
+ draw calls (instancing for repeats); URDF ≤ 60 links.
+* Build must finish in < 120 s (bpy / CadQuery) or < 20 s (node). No infinite loops,
+ no per-vertex Python loops over > 200 k vertices, no subdivision level > 3.
+
+## 7. Definition of done (all boxes, in order)
+
+1. [ ] `build` succeeds with zero errors (exit 0, GLB written).
+2. [ ] Every plan part exists by exact name; no extra junk objects (`Cube`, `Camera`).
+3. [ ] Measured overall bbox within ± 1 cm (objects) / declared bounds (scenes).
+4. [ ] `check_connectivity`: 1 connected assembly, no floating islands, lowest point at 0.
+5. [ ] `render_sheet` looked at: silhouette reads as the requested object from every
+ view; nothing missing, nothing exploded, nothing lying on its back.
+6. [ ] Hollow / articulated / animated behaviour verified (`cross_section`,
+ `joint_sweep`, `scene_probe` as applicable).
+7. [ ] Materials / colours assigned per plan (no grey default everywhere).
+8. [ ] Code is tidy: constants on top, one function per part, no dead code, no debug
+ prints left, no forbidden imports.
+9. [ ] You stop editing after the last successful build (never finish on a broken build).
diff --git a/harness/codeverse/prompts/system/singleshot_format.md b/harness/codeverse/prompts/system/singleshot_format.md
new file mode 100644
index 00000000..4066e9a9
--- /dev/null
+++ b/harness/codeverse/prompts/system/singleshot_format.md
@@ -0,0 +1,63 @@
+# Single-shot response format (API backends without tools)
+
+You cannot run tools in this mode. Return the COMPLETE code for every file you create
+or change, using this exact multi-file block format. The harness parses it mechanically;
+anything outside the blocks is discarded.
+
+## Format
+
+```text
+=== FILE: src/model.py ===
+<full file contents, no truncation, no "..." placeholders>
+=== END FILE ===
+=== FILE: src/parts/seat.js ===
+<full file contents>
+=== END FILE ===
+```
+
+Rules (all MUST):
+
+1. Header line is exactly `=== FILE: <path> ===` with a path relative to the workspace
+ root, always starting with `src/` (or `public/` for scene assets). Footer line is
+ exactly `=== END FILE ===`. Both on their own line, no indentation, no code fences
+ around them.
+2. Put the **entire** file between header and footer — not a diff, not a fragment, not
+ "rest unchanged". A file you do not emit stays as it was.
+3. No prose between blocks. If you must explain something, put it in a code comment
+ inside the file. No markdown fences inside the block (write raw code, not ```python).
+4. One block per path; if you emit the same path twice the LAST block wins.
+5. Emit every file that the language contract requires (e.g. `src/model.py`;
+ `src/object.js` + `src/parts/*.js`; `src/model.py` + `src/robot.urdf`;
+ `src/scene.js` + `src/env.js` + …). A missing required file = build failure.
+6. Start your reply with the first `=== FILE:` line. End it with the last
+ `=== END FILE ===` line. Nothing after it.
+
+## Fallback (legacy one-file parse)
+
+If — and only if — the task asks for exactly one file and you do not use the block
+format, the harness takes the first fenced code block (```python / ```js / ```xml) in your
+reply as that file. Do not rely on this; use the block format.
+
+## Worked example (two-file three.js object)
+
+```text
+=== FILE: src/parts/seat.js ===
+import * as THREE from 'three';
+export function buildSeat(THREE) {
+ const g = new THREE.Group(); g.name = 'Seat';
+ const m = new THREE.Mesh(new THREE.BoxGeometry(0.45, 0.04, 0.45),
+ new THREE.MeshStandardMaterial({ color: 0x8b5a2b }));
+ m.position.y = 0.45; g.add(m);
+ return g;
+}
+=== END FILE ===
+=== FILE: src/object.js ===
+import * as THREE from 'three';
+import { buildSeat } from './parts/seat.js';
+export function build(THREE) {
+ const root = new THREE.Group(); root.name = 'Stool';
+ root.add(buildSeat(THREE));
+ return root;
+}
+=== END FILE ===
+```
diff --git a/harness/codeverse/prompts/system/tools_usage.md b/harness/codeverse/prompts/system/tools_usage.md
new file mode 100644
index 00000000..6aee2e37
--- /dev/null
+++ b/harness/codeverse/prompts/system/tools_usage.md
@@ -0,0 +1,65 @@
+# Using the c3v spatial tools (look before you leap)
+
+The tools are the harness's instruments. They are cheap, deterministic and honest —
+trust their numbers over your mental model. Observations come back as
+`{text, numbers, images[]}`; images are small labelled PNGs / contact sheets.
+
+## The standard loop
+
+```
+1. build → errors first (file:line + traceback tail) or key numbers
+2. render_sheet → 4 labelled views (front_right_34, back_left_34, front, top)
+3. check_connectivity → islands, floating parts, ground gap, per-part touch graph
+4. fix the worst finding → rebuild (repeat 1–3 until clean)
+5. isolate <part> → the one part you doubt, alone, 4 views + its bbox
+6. cross_section → axis=y at the cavity height: is the mug actually hollow?
+7. compare_silhouette → only when a reference image exists (IoU per view)
+8. joint_sweep / scene_probe / shader_probe → articulated / scene tracks
+9. check_contract → plan bbox vs measured, per part (last, before done)
+```
+Always `build` after an edit; never reason about stale renders.
+
+## Tool cards (arguments are validated; read the error if you get one)
+
+* `build()` — lint + execute + export + measure. On error: fix that file:line first.
+ On success: overall bbox/extents, tri count, n_meshes, n_islands, part table.
+* `measure(parts=[...])` — bbox/extents/islands/volume per part; use it to check a
+ dimension numerically instead of eyeballing a render.
+* `render_views(views=[...], mode="shaded"|"wire"|"normals"|"clay", isolate=[...],
+ explode=0.0)` — named views from the preset list (front, right, back, left, top,
+ front_right_34, back_left_34, low_front_left). `explode=0.3` separates parts to see
+ what is where. `wire` shows density; `clay` removes colour so shape is judged alone.
+* `render_sheet()` — the quick 4-view contact sheet. One image, always look at it.
+* `isolate(part="SeatCushion")` — that part alone, framed; everything else hidden.
+* `cross_section(axis="y", at=0.05)` — slice at height `at` (meters, in the GLB Y-up
+ frame); shows walls, cavities, interpenetration. Slice where the detail is.
+* `check_connectivity(gap_m=0.002)` — hard facts: islands, floating pieces (with the
+ nearest neighbour and the gap in mm), ground gap. A positive gap = you must weld.
+* `check_contract(tol_m=0.01)` — plan bbox vs measured per part; lists the offenders
+ with the translation / scale that would fix them.
+* `compare_silhouette(view="front")` — IoU of your render vs the reference image.
+* `joint_sweep(joint="DoorHinge")` — FK over [lower, mid, upper]; renders + collision
+ pairs per pose; "child does not move" or "penetrates parent at q=1.2" is the finding.
+* `scene_probe()` — census (draw calls, tris, instanced meshes), cameras inside geometry,
+ console errors, fps, black/blown frames.
+* `shader_probe()` — compiles every ShaderMaterial / onBeforeCompile patch with the real
+ renderer; reports GLSL errors with the author's line number.
+* `read_cookbook(section="Booleans")` — fetch one cookbook chapter by its heading.
+
+## Reading the outputs
+
+* `n_islands > n_parts` → something is split or floating; `check_connectivity` names it.
+* `ground_gap_m < 0` → buried; `> 0.002` → hovering. Translate the whole object.
+* `extents` far from plan → wrong unit (mm vs m) or a scale you forgot to apply.
+* `footprint_offset_m > 0.01` → not centred on the up-axis.
+* In renders: identical grey everywhere = materials missing; a part present in `top`
+ but absent in `front` = it is inside something else; thin white lines at seams = gaps.
+
+## Image budget etiquette
+
+* One `render_sheet` per build cycle (not per edit). Use `isolate` / `cross_section`
+ only for the part you are about to change. Prefer `measure` (numbers, no image) for
+ dimension questions.
+* Do not request all 8 views + wire + normals at once; the sheet is enough to decide.
+* Re-render after a fix, and compare with the previous sheet before moving on.
+* Stop when the definition-of-done list is green, not when you run out of ideas.
diff --git a/harness/codeverse/prompts/threejs/contract.md b/harness/codeverse/prompts/threejs/contract.md
new file mode 100644
index 00000000..838fef18
--- /dev/null
+++ b/harness/codeverse/prompts/threejs/contract.md
@@ -0,0 +1,97 @@
+# three.js (static object) authoring contract — track `static_object`, language `threejs`
+
+## Files (ES modules, three r182)
+```
+src/object.js export function build(THREE) → THREE.Group (the whole object)
+src/parts/<snake>.js export function build<Pascal>(THREE) → THREE.Group (one per plan part)
+```
+`build()` imports the part builders with relative paths (`./parts/seat_cushion.js`),
+adds each returned Group to a root Group named after the object, and returns the root.
+The harness loads `src/object.js` in node, calls `build(THREE)`, and exports
+`artifacts/object.glb` with `GLTFExporter`. No renderer, scene, camera, light, DOM,
+`requestAnimationFrame`, `fetch`, texture loading or file I/O in your code.
+
+## Frame, units, placement
+* **Y is up, +Z is the front, +X is the right. Meters.** `BoxGeometry(w, h, d)` is
+ x-width, y-height, z-depth; `CylinderGeometry` axis is Y; `PlaneGeometry` lies in XY.
+* Each part Group is returned **at its world pose** (position set on the Group or the
+ meshes — geometry in meters, root scale (1,1,1), never `root.scale.set(...)` to resize).
+* Lowest point at y = 0, footprint centred on the Y axis. Real-world dimensions.
+
+## Naming
+* Part Group: `g.name = "<PartName>"` — PascalCase exactly as the plan (`SeatCushion`);
+ meshes inside may be unnamed or `<PartName>_<detail>`. Unique names; instances get
+ their own names (`Leg1`…`Leg4`) even if built by one function.
+* Optional animation hook: `root.userData.tick = (dt) => { ... }` on a pivot Group
+ (position + rotation only; identity scale). No other userData contract.
+
+## Imports (only these resolve)
+```js
+import * as THREE from 'three';
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
+import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';
+```
+No CDN URLs, no `three/examples/js/*`, no `three/webgpu`, no `three/tsl`, no npm
+packages other than `three`, no `import ... from 'codeverse'` / `../runtime_js`.
+
+## Forbidden / limits
+* No `document`, `window`, `canvas`, `Image`, `TextureLoader`, `fetch`, `XMLHttpRequest`,
+ `Math.random()` (use a seeded hash), `Date`, `performance`.
+* ShaderMaterial is NOT exported to GLB — use `MeshStandardMaterial` /
+ `MeshPhysicalMaterial` only. Colours via `new THREE.Color(0xRRGGBB)`; vertex colours
+ allowed (`geometry.setAttribute('color', …)` + `vertexColors: true`).
+* ≤ 600 k triangles (aim 20–150 k); ≤ 300 meshes (use `InstancedMesh` or merged
+ geometries for repeats); module evaluates + builds in < 20 s.
+
+## Self-check (optional, keep it tiny, at the end of object.js)
+```js
+export function selfcheck(THREE, root) {
+ const box = new THREE.Box3().setFromObject(root);
+ if (!(box.min.y > -0.002 && box.min.y < 0.002)) throw new Error(`object not on ground: min.y=${box.min.y}`);
+ return box;
+}
+```
+
+## COMPLETE minimal example (verified in node with [email protected] + GLTFExporter)
+
+`src/parts/seat.js`
+```js
+import * as THREE from 'three';
+const SEAT_W = 0.40, SEAT_D = 0.40, SEAT_T = 0.04, SEAT_Y = 0.45; // plan numbers (m)
+export function buildSeat(THREE) {
+ const g = new THREE.Group(); g.name = 'Seat';
+ const mat = new THREE.MeshStandardMaterial({ color: 0x8b5a2b, roughness: 0.6 });
+ const mesh = new THREE.Mesh(new THREE.BoxGeometry(SEAT_W, SEAT_T, SEAT_D), mat);
+ mesh.position.set(0, SEAT_Y - SEAT_T / 2, 0); // top face at 0.45
+ g.add(mesh);
+ return g;
+}
+```
+`src/parts/legs.js`
+```js
+import * as THREE from 'three';
+const LEG_R = 0.018, LEG_H = 0.45 - 0.04 + 0.004; // reaches 4 mm into the seat (weld)
+const LEG_XZ = 0.15;
+export function buildLegs(THREE) {
+ const g = new THREE.Group(); g.name = 'Legs';
+ const geo = new THREE.CylinderGeometry(LEG_R, LEG_R, LEG_H, 24);
+ const mat = new THREE.MeshStandardMaterial({ color: 0x555a60, roughness: 0.35, metalness: 0.9 });
+ [[1, 1], [-1, 1], [-1, -1], [1, -1]].forEach(([sx, sz], i) => {
+ const m = new THREE.Mesh(geo, mat); m.name = `Leg${i + 1}`;
+ m.position.set(sx * LEG_XZ, LEG_H / 2, sz * LEG_XZ);
+ g.add(m);
+ });
+ return g;
+}
+```
+`src/object.js`
+```js
+import * as THREE from 'three';
+import { buildSeat } from './parts/seat.js';
+import { buildLegs } from './parts/legs.js';
+export function build(THREE) {
+ const root = new THREE.Group(); root.name = 'Stool';
+ root.add(buildSeat(THREE), buildLegs(THREE));
+ return root;
+}
+```
diff --git a/harness/codeverse/prompts/threejs/cookbook.md b/harness/codeverse/prompts/threejs/cookbook.md
new file mode 100644
index 00000000..601652f0
--- /dev/null
+++ b/harness/codeverse/prompts/threejs/cookbook.md
@@ -0,0 +1,361 @@
+# three.js cookbook — static objects, three r182 (ESM), exported to GLB by the harness
+
+Every `js` snippet runs as-is in node (the harness test suite concatenates them with
+`THREE`, `mergeGeometries` and `RoundedBoxGeometry` in scope). Y-up, +Z front, meters,
+PascalCase Group names. Use `read_cookbook(section="<heading>")` for one chapter.
+
+## Module structure (skeleton)
+
+`src/parts/<snake>.js` — one builder per plan part, returns a Group **at world pose**:
+
+```js
+import * as THREE from 'three';
+// ---- plan numbers (metres) ---------------------------------------------------
+const SEAT_W = 0.44, SEAT_D = 0.44, SEAT_T = 0.035, SEAT_H = 0.45;
+const LEG = 0.035, WELD = 0.003; // parts overlap by WELD so they touch
+
+// ---- tiny helpers (copy into every part file; no shared helper module is allowed) ----
+const rand = (i) => { const s = Math.sin(i * 12.9898 + 78.233) * 43758.5453; return s - Math.floor(s); };
+function mesh(geo, mat, name, x = 0, y = 0, z = 0) {
+ const m = new THREE.Mesh(geo, mat); m.name = name; m.position.set(x, y, z);
+ m.castShadow = m.receiveShadow = true; return m;
+}
+const MAT = {
+ oak: () => new THREE.MeshStandardMaterial({ color: 0x8a5a2b, roughness: 0.6, metalness: 0.0 }),
+ steel: () => new THREE.MeshStandardMaterial({ color: 0x9a9da2, roughness: 0.3, metalness: 1.0 }),
+};
+
+export function buildSeat(THREE) {
+ const g = new THREE.Group(); g.name = 'Seat';
+ g.add(mesh(new RoundedBoxGeometry(SEAT_W, SEAT_T, SEAT_D, 3, 0.006), MAT.oak(), 'SeatSlab',
+ 0, SEAT_H - SEAT_T / 2, 0));
+ return g;
+}
+export function buildLegs(THREE) {
+ const g = new THREE.Group(); g.name = 'Legs';
+ const geo = new THREE.BoxGeometry(LEG, SEAT_H - SEAT_T + WELD, LEG);
+ [[1, 1], [-1, 1], [-1, -1], [1, -1]].forEach(([sx, sz], i) =>
+ g.add(mesh(geo, MAT.oak(), `Leg${i + 1}`, sx * (SEAT_W / 2 - LEG / 2 - 0.01),
+ (SEAT_H - SEAT_T + WELD) / 2, sz * (SEAT_D / 2 - LEG / 2 - 0.01))));
+ return g;
+}
+```
+
+`src/object.js` — assembles parts; nothing else:
+
+```js
+export function build(THREE) {
+ const root = new THREE.Group(); root.name = 'Chair';
+ root.add(buildSeat(THREE), buildLegs(THREE));
+ return root; // Y-up, lowest point y = 0, no root.scale
+}
+```
+
+Why: the GLB node names come from Group/Mesh names; geometry in metres at world pose
+means `Box3().setFromObject(root)` equals what the harness measures.
+
+## Geometry toolkit
+
+```js
+// BoxGeometry(w, h, d): x, y, z extents. CylinderGeometry(rTop, rBottom, h, radial, heightSeg): axis Y.
+// SphereGeometry(r, w, h). TorusGeometry(R, r, radial, tubular): ring in the XY plane (rotateX(PI/2) to lay flat).
+// ConeGeometry(r, h, seg). PlaneGeometry(w, h): XY plane, faces +Z (rotateX(-PI/2) for a floor).
+const ring = new THREE.TorusGeometry(0.03, 0.006, 12, 32).rotateX(Math.PI / 2); // flat ring, axis Y
+
+// LatheGeometry: revolve a profile of Vector2(radius, y) around Y — bottles, vases, knobs, legs
+const profile = [[0, 0], [0.032, 0], [0.034, 0.01], [0.034, 0.16], [0.014, 0.21], [0.014, 0.25], [0, 0.25]]
+ .map(([r, y]) => new THREE.Vector2(r, y));
+const bottle = new THREE.LatheGeometry(profile, 48); // normals point outward when r goes 0→R→0 bottom-up
+
+// ExtrudeGeometry from a Shape (+ holes) with bevel: plates, brackets, letters, panels
+const shp = new THREE.Shape();
+shp.moveTo(-0.05, 0); shp.lineTo(0.05, 0); shp.lineTo(0.05, 0.03); shp.lineTo(-0.05, 0.03); shp.closePath();
+const hole = new THREE.Path(); hole.absarc(0.03, 0.015, 0.006, 0, Math.PI * 2, true); shp.holes.push(hole);
+const plate = new THREE.ExtrudeGeometry(shp, { depth: 0.004, bevelEnabled: true, bevelThickness: 0.0008,
+ bevelSize: 0.0008, bevelSegments: 2, curveSegments: 16 });
+plate.rotateX(-Math.PI / 2); // extrude goes +Z; lay it flat (thickness along Y)
+
+// Rounded rectangle shape helper (use for table tops, seats, screens)
+function roundedRectShape(w, h, r) {
+ const s = new THREE.Shape(); const x = -w / 2, y = -h / 2;
+ s.moveTo(x + r, y); s.lineTo(x + w - r, y); s.quadraticCurveTo(x + w, y, x + w, y + r);
+ s.lineTo(x + w, y + h - r); s.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
+ s.lineTo(x + r, y + h); s.quadraticCurveTo(x, y + h, x, y + h - r);
+ s.lineTo(x, y + r); s.quadraticCurveTo(x, y, x + r, y); return s;
+}
+const top = new THREE.ExtrudeGeometry(roundedRectShape(0.6, 0.4, 0.02), { depth: 0.03, bevelEnabled: false }).rotateX(-Math.PI / 2);
+
+// TubeGeometry along a CatmullRomCurve3: cables, handles, pipes, railings
+const curve = new THREE.CatmullRomCurve3([new THREE.Vector3(0.05, 0.3, 0), new THREE.Vector3(0.1, 0.2, 0.02),
+ new THREE.Vector3(0.18, 0.08, 0), new THREE.Vector3(0.3, 0.01, -0.03)]);
+const cable = new THREE.TubeGeometry(curve, 48, 0.004, 10, false);
+
+// RoundedBoxGeometry(w, h, d, segments, radius) — the default box for anything touched by hands
+const cushion = new RoundedBoxGeometry(0.4, 0.1, 0.4, 4, 0.03);
+
+// mergeGeometries: many static pieces → ONE mesh (fewer draw calls; keep per-part Groups for naming)
+function placed(geo, x, y, z, ry = 0) { const g = geo.clone(); g.rotateY(ry); g.translate(x, y, z); return g; }
+const slats = mergeGeometries([0, 1, 2, 3].map(i => placed(new THREE.BoxGeometry(0.4, 0.012, 0.05), 0, 0.6 + i * 0.08, -0.2)));
+slats.computeVertexNormals(); // always after merges / manual edits
+
+// InstancedMesh for N identical small parts (bolts, balusters, spokes)
+const bolt = new THREE.InstancedMesh(new THREE.CylinderGeometry(0.004, 0.004, 0.002, 12),
+ new THREE.MeshStandardMaterial({ color: 0x333333, metalness: 1, roughness: 0.4 }), 8);
+const M = new THREE.Matrix4();
+for (let i = 0; i < 8; i++) { const a = i / 8 * Math.PI * 2; M.makeTranslation(0.1 * Math.cos(a), 0.031, 0.1 * Math.sin(a)); bolt.setMatrixAt(i, M); }
+bolt.instanceMatrix.needsUpdate = true; bolt.computeBoundingSphere(); bolt.name = 'Bolts';
+console.log('toolkit ok', bottle.attributes.position.count, plate.attributes.position.count, slats.attributes.position.count);
+```
+
+Why: these are the only geometry makers you need; everything else is position/rotation.
+Segments: 24–48 radial for visible cylinders, 8–12 for rods; tube radial 8–12.
+
+## Pivots and animation (optional `userData.tick`)
+
+```js
+// Rotate/translate a Group placed at the joint, never the mesh itself; identity scale on pivots.
+function buildFan(THREE) {
+ const g = new THREE.Group(); g.name = 'Fan';
+ const hub = new THREE.Group(); hub.name = 'FanHub'; hub.position.set(0, 1.2, 0.05); // pivot at the axle
+ const bladeGeo = new THREE.BoxGeometry(0.02, 0.4, 0.004).translate(0, 0.25, 0); // blade root at the hub
+ for (let i = 0; i < 3; i++) {
+ const b = new THREE.Mesh(bladeGeo, new THREE.MeshStandardMaterial({ color: 0xdddddd }));
+ b.name = `Blade${i + 1}`; b.rotation.z = i * Math.PI * 2 / 3; hub.add(b);
+ }
+ g.add(hub);
+ g.userData.tick = (dt) => { hub.rotation.z += dt * 2.0; }; // rad/s; harness calls tick(dt) when animating
+ return g;
+}
+const fan = buildFan(THREE); fan.userData.tick(0.016);
+```
+
+Why: a pivot Group makes the rotation axis explicit and keeps geometry static;
+geometry `.translate()` moves the blade root to the pivot so it spins correctly.
+
+## Materials (plain-object presets; only Standard/Physical export to GLB)
+
+```js
+const PRESETS = {
+ oak: { color: 0x8a5a2b, roughness: 0.60, metalness: 0.0 },
+ walnut: { color: 0x4a2c17, roughness: 0.55, metalness: 0.0 },
+ steel: { color: 0x9a9da2, roughness: 0.30, metalness: 1.0 },
+ brass: { color: 0xd4a24c, roughness: 0.35, metalness: 1.0 },
+ black_plastic: { color: 0x111111, roughness: 0.45, metalness: 0.0 },
+ white_ceramic: { color: 0xf0efe8, roughness: 0.15, metalness: 0.0 },
+ fabric: { color: 0x5a6a8c, roughness: 0.95, metalness: 0.0 },
+ rubber: { color: 0x151515, roughness: 0.85, metalness: 0.0 },
+ glass: { color: 0xdfe9f2, roughness: 0.05, metalness: 0.0, transparent: true, opacity: 0.35 },
+ emissive: { color: 0xfff1c0, emissive: 0xffe08a, emissiveIntensity: 2.0, roughness: 0.4 },
+};
+const mat = (key, extra = {}) => new THREE.MeshStandardMaterial({ ...PRESETS[key], ...extra });
+const glassMat = new THREE.MeshPhysicalMaterial({ color: 0xffffff, transmission: 0.9, roughness: 0.05, thickness: 0.005, transparent: true });
+
+// vertex colours (exported as COLOR_0): cheap variation without textures
+function colorByHeight(geo, lo = new THREE.Color(0x2b5a1f), hi = new THREE.Color(0x9bd65a)) {
+ const pos = geo.attributes.position, col = new Float32Array(pos.count * 3), c = new THREE.Color();
+ geo.computeBoundingBox(); const y0 = geo.boundingBox.min.y, y1 = geo.boundingBox.max.y || 1e-6;
+ for (let i = 0; i < pos.count; i++) { c.copy(lo).lerp(hi, (pos.getY(i) - y0) / (y1 - y0)); col.set([c.r, c.g, c.b], i * 3); }
+ geo.setAttribute('color', new THREE.BufferAttribute(col, 3));
+ return new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.8 });
+}
+const leafMat = colorByHeight(new THREE.SphereGeometry(0.5, 16, 12));
+console.log('materials ok', mat('oak').color.getHexString(), leafMat.vertexColors);
+```
+
+Why: `MeshStandardMaterial` maps 1:1 to glTF PBR; `ShaderMaterial`, `MeshToonMaterial` and
+procedural textures are lost on export. Colours given as hex are sRGB (correct);
+`material.color.r` is linear internally — don't compare it with hex.
+
+## Detail (how to look good cheaply)
+
+| feature | recipe | size |
+|---|---|---|
+| rounded edges | `RoundedBoxGeometry(w,h,d, 3, r)` | r 2–6 mm furniture, 0.5–1 mm devices |
+| chamfered plate | `ExtrudeGeometry(shape, {bevelEnabled, bevelSize 1 mm, bevelSegments 1})` | |
+| seams / panel gaps | build panels 1 mm apart, darker material in the gap OR a thin dark box | 0.8–1.5 mm |
+| inset panel | a slightly smaller box 1–2 mm proud/sunk into the face | inset 5–10 mm |
+| fasteners | `InstancedMesh` of 12-seg cylinders, head Ø 5–8 mm, h 1–2 mm, sunk 0.5 mm | |
+| trim / edge band | `TubeGeometry` along the outline or a thin `TorusGeometry` | Ø 4–10 mm |
+| feet / glides | cylinders Ø 15–25 mm, h 5–10 mm under legs | |
+| cushions | `RoundedBoxGeometry(w, 0.08–0.12, d, 4, 0.03)` | |
+| handles / knobs | `TorusGeometry` / `LatheGeometry`, overlapping the panel 2 mm | knob Ø 25–35 mm |
+| fabric / wood variation | `colorByHeight` or per-instance colour via `setColorAt` | |
+
+Rules: ≥ 3 distinct masses in the silhouette; break every large flat face once; thin
+things are 1–3 mm, never 0; anything hands touch gets a radius.
+
+## Common objects — dimensions (metres, Y-up) and decomposition
+
+| object | W × D × H | parts | key numbers |
+|---|---|---|---|
+| dining chair | 0.45 × 0.50 × 0.90 | Seat, Backrest, Leg1..4, Stretchers | seat y 0.45, t 0.035, leg 0.035, rake 8° |
+| sofa | 2.0 × 0.9 × 0.85 | Base, SeatCushion1..3, BackCushion1..3, ArmLeft/Right, Legs | seat y 0.42, arm y 0.60, cushion 0.11 |
+| table | 1.6 × 0.9 × 0.75 | Top, Apron, Leg1..4 | top t 0.035, legs 0.07 at 0.05 inset |
+| desk lamp | Ø 0.18 × 0.55 | Base, ArmLower, ArmUpper, Shade, Bulb | arm Ø 0.012, shade Ø 0.15 |
+| mug | Ø 0.085 × 0.095 | Body (Lathe), Handle (Tube) | wall 4 mm, handle Ø 12 mm |
+| bottle | Ø 0.075 × 0.30 | Body (Lathe), Cap | neck Ø 0.028 |
+| bicycle | 1.75 × 0.6 × 1.05 | Frame(Tubes), FrontWheel/RearWheel(Torus + spokes), Fork, Handlebar, Saddle, Crank, Pedals, Chain | wheel Ø 0.70, tyre 0.03, BB y 0.27 |
+| car | 4.6 × 1.85 × 1.45 | Body(Extrude side profile), Cabin, Wheel×4, Bumpers, Mirrors, Lights | wheel Ø 0.65, wheelbase 2.7, clearance 0.15 |
+| house | 10 × 8 × 7 | Walls, Roof(Extrude triangle), Door, Windows, Chimney | storey 2.8, pitch 35°, door 0.9 × 2.1 |
+| tree | crown Ø 7 × H 12 | Trunk(Cylinder taper), Branches(Tube), Crown(3–6 spheres, vertex colours) | trunk Ø 0.4 |
+| bookshelf | 0.8 × 0.3 × 1.8 | SideLeft/Right, Top, Bottom, Shelf1..4, Back | panel 18 mm |
+| monitor | 0.62 × 0.2 × 0.45 | Panel, Stand, Base | bezel 8 mm |
+
+Decomposition: 1 main mass → 2–6 secondary masses touching it → attachments overlapping
+≥ 2 mm → detail pass. Z is the FRONT: the chair's backrest sits at −Z, seat front at +Z.
+
+## Raw BufferGeometry and a spoked wheel (when no primitive fits)
+
+```js
+// Custom BufferGeometry: positions (+ index) → computeVertexNormals(). A ramp wedge:
+function wedgeGeometry(w, h, d) {
+ const g = new THREE.BufferGeometry();
+ const v = [ -w/2,0,d/2, w/2,0,d/2, w/2,0,-d/2, -w/2,0,-d/2, // base quad
+ -w/2,h,-d/2, w/2,h,-d/2 ]; // top back edge
+ const idx = [0,2,1, 0,3,2, 0,1,5, 0,5,4, 1,2,5, 3,4,2, 4,5,2, 0,4,3];
+ g.setAttribute('position', new THREE.Float32BufferAttribute(v, 3));
+ g.setIndex(idx);
+ g.computeVertexNormals(); // ALWAYS, or it shades black
+ return g;
+}
+const ramp = new THREE.Mesh(wedgeGeometry(0.6, 0.25, 0.5), new THREE.MeshStandardMaterial({ color: 0x777777 }));
+
+// Spoked wheel: torus tyre + lathed rim + instanced spokes + hub — the bicycle staple
+function buildWheel(THREE, R = 0.35, tyreR = 0.017, spokes = 18) {
+ const g = new THREE.Group(); g.name = 'Wheel';
+ const tyre = new THREE.Mesh(new THREE.TorusGeometry(R, tyreR, 10, 48),
+ new THREE.MeshStandardMaterial({ color: 0x151515, roughness: 0.85 }));
+ tyre.name = 'Tyre'; g.add(tyre);
+ // the torus lies in the XY plane, so this wheel's axle is the LOCAL Z axis; build the
+ // whole wheel that way and let the parent orient it (axle along X: wheel.rotateY(PI/2)).
+ const hub = new THREE.Mesh(new THREE.CylinderGeometry(0.02, 0.02, 0.08, 16).rotateX(Math.PI / 2),
+ new THREE.MeshStandardMaterial({ color: 0x8a8d92, metalness: 1, roughness: 0.3 }));
+ hub.name = 'Hub'; g.add(hub);
+ const spokeGeo = new THREE.CylinderGeometry(0.0012, 0.0012, R - 0.02, 5).translate(0, (R - 0.02) / 2 + 0.015, 0);
+ const spoke = new THREE.InstancedMesh(spokeGeo, hub.material, spokes);
+ const m = new THREE.Matrix4(), q = new THREE.Quaternion(), z = new THREE.Vector3(0, 0, 1);
+ for (let i = 0; i < spokes; i++) {
+ q.setFromAxisAngle(z, i / spokes * Math.PI * 2);
+ m.makeRotationFromQuaternion(q);
+ spoke.setMatrixAt(i, m);
+ }
+ spoke.computeBoundingSphere(); spoke.name = 'Spokes'; g.add(spoke);
+ return g; // parent: wheel.rotateY(Math.PI/2) to put the axle along X, then position it
+}
+const wheel = buildWheel(THREE);
+console.log('wheel parts', wheel.children.map(c => c.name), 'ramp tris', ramp.geometry.index.count / 3);
+```
+
+Why: an indexed position buffer plus `computeVertexNormals()` covers any faceted shape a
+primitive cannot; a wheel is 3 draw calls at any spoke count thanks to the InstancedMesh.
+
+## Pitfalls (symptom → cause → fix)
+
+1. **Object lies on its side in the render** → you built Z-up. three.js/glTF are Y-up;
+ height is Y, front is +Z. `CylinderGeometry` axis is Y; floors are `PlaneGeometry` rotated
+ `-PI/2` about X.
+2. **`mesh.position` vs `geometry.translate`** — position moves the pivot (animation-
+ friendly), `geometry.translate()` bakes the offset (needed before `mergeGeometries` and
+ for blade-root pivots). Pick deliberately; never do both by accident.
+3. **"All geometries must have compatible attributes"** in `mergeGeometries` → one input
+ has `uv`/`color` or an index and another not. Delete extra attributes
+ (`geo.deleteAttribute('uv')`) or `toNonIndexed()` all; then `computeVertexNormals()`.
+4. **Faceted / black shading after edits** → call `geometry.computeVertexNormals()`; for
+ flipped faces use `geometry.scale(-1,1,1)` carefully or rebuild the profile order.
+5. **`userData.tick` never runs** → it must be a function `(dt) => void` on the ROOT
+ returned by `build`, or on a part Group (the harness traverses); don't animate scale.
+6. **Renderer / Scene / Camera / Light / OrbitControls in object code** → forbidden; the
+ module is imported in node with no WebGL. `document`/`canvas`/`Image`/`TextureLoader`
+ crash the build (Mode 13 in the failure catalogue).
+7. **Imports that do not exist in r182**: `three/examples/js/*`, `BufferGeometryUtils.
+ mergeBufferGeometries` (now `mergeGeometries`), `Geometry`/`Face3`, `THREE.sRGBEncoding`,
+ `outputEncoding`. Use `three/addons/utils/BufferGeometryUtils.js`,
+ `three/addons/geometries/RoundedBoxGeometry.js`.
+8. **`root.scale.set(0.01, …)` to convert mm → m** → bounds/gates see scaled geometry
+ inconsistently; author in metres, root scale stays (1,1,1).
+9. **Floating parts** → overlap neighbours by ≥ 2 mm along the contact normal; legs reach
+ INTO the seat, handles INTO the body.
+10. **Hidden parts via tiny scale** → use `visible = false` or don't add them; never
+ `scale.set(0,0,0)` (NaN normals in the exporter).
+11. **`InstancedMesh` disappears** → `computeBoundingSphere()` after setting matrices, or
+ `frustumCulled = false`; set `instanceMatrix.needsUpdate = true`.
+12. **Math.random()** → non-reproducible builds; use the `rand(i)` hash.
+13. **ShaderMaterial / textures** → not in GLB; use Standard/Physical + vertex colours.
+14. **Huge triangle counts** → `SphereGeometry(r, 64, 64)` ×100 = 800 k tris; use 16×12 for
+ small spheres, instancing for repeats, merged geometries for static detail.
+15. **Mixed three copies** (`instanceof` failures) → import only from `'three'` and
+ `'three/addons/…'`; never copy three sources into `src/`.
+
+## Self-check (before you call it done)
+
+```js
+export function selfcheck(THREE, root, expectedNames = [], extentsHint = null) {
+ const names = new Set(); let tris = 0;
+ root.traverse(o => {
+ if (o.name) names.add(o.name);
+ if (o.isMesh) { const g = o.geometry; const n = g.index ? g.index.count / 3 : g.attributes.position.count / 3;
+ tris += n * (o.isInstancedMesh ? o.count : 1); }
+ });
+ const missing = expectedNames.filter(n => !names.has(n));
+ if (missing.length) throw new Error(`missing parts: ${missing.join(', ')}`);
+ const box = new THREE.Box3().setFromObject(root); const size = box.getSize(new THREE.Vector3());
+ if (Math.abs(box.min.y) > 0.002) throw new Error(`lowest point y=${box.min.y.toFixed(4)} (expected 0)`);
+ if (tris > 600000) throw new Error(`too many triangles: ${tris}`);
+ if (extentsHint) extentsHint.forEach((e, i) => { if (Math.abs(size.getComponent(i) - e) > 0.05) throw new Error(`extents ${size.toArray()} vs plan ${extentsHint}`); });
+ console.log(`[selfcheck] parts=${names.size} tris=${tris} extents=${size.toArray().map(v => v.toFixed(3))}`);
+ return { tris, size };
+}
+selfcheck(THREE, build(THREE), ['Seat', 'Legs', 'Leg1', 'Leg4'], [0.44, 0.45, 0.44]);
+```
+
+Then use the tools: `build` → `render_sheet` → `check_connectivity` → `isolate` → `check_contract`.
+
+## Worked example: mug (Lathe body + Tube handle, welded) and desk lamp (pivots)
+
+```js
+export function buildMug(THREE) {
+ const R = 0.042, H = 0.095, WALL = 0.004, FLOOR = 0.006;
+ const g = new THREE.Group(); g.name = 'Mug';
+ // profile goes: outside bottom → outside top → inside top → inside floor → axis (closed, outward normals)
+ const pts = [[0, 0], [R - 0.006, 0], [R, 0.006], [R, H - 0.004], [R - 0.002, H], [R - WALL, H],
+ [R - WALL, FLOOR], [0, FLOOR]].map(([r, y]) => new THREE.Vector2(r, y));
+ const body = new THREE.Mesh(new THREE.LatheGeometry(pts, 48), new THREE.MeshStandardMaterial({ color: 0xf0efe8, roughness: 0.2 }));
+ body.name = 'MugBody'; g.add(body);
+ // handle: a C-curve that starts and ends 3 mm INSIDE the wall (weld), tube Ø 12 mm
+ const c = new THREE.CatmullRomCurve3([
+ new THREE.Vector3(R - 0.003, H * 0.78, 0), new THREE.Vector3(R + 0.028, H * 0.72, 0),
+ new THREE.Vector3(R + 0.034, H * 0.45, 0), new THREE.Vector3(R + 0.022, H * 0.22, 0),
+ new THREE.Vector3(R - 0.003, H * 0.20, 0)]);
+ const handle = new THREE.Mesh(new THREE.TubeGeometry(c, 32, 0.006, 12, false), body.material);
+ handle.name = 'MugHandle'; g.add(handle);
+ return g;
+}
+
+export function buildDeskLamp(THREE) {
+ const g = new THREE.Group(); g.name = 'DeskLamp';
+ const metal = new THREE.MeshStandardMaterial({ color: 0x2a2d33, roughness: 0.35, metalness: 0.9 });
+ const base = new THREE.Mesh(new THREE.CylinderGeometry(0.09, 0.10, 0.02, 48), metal); base.name = 'Base'; base.position.y = 0.01;
+ // lower arm pivots at the base top; upper arm pivots at the elbow; shade pivots at the wrist
+ const shoulder = new THREE.Group(); shoulder.name = 'Shoulder'; shoulder.position.set(0, 0.02 - 0.003, 0); shoulder.rotation.z = -0.35;
+ const armLo = new THREE.Mesh(new THREE.CylinderGeometry(0.007, 0.007, 0.30, 16).translate(0, 0.15, 0), metal); armLo.name = 'ArmLower';
+ const elbow = new THREE.Group(); elbow.name = 'Elbow'; elbow.position.y = 0.30 - 0.004; elbow.rotation.z = 1.25;
+ const armUp = new THREE.Mesh(new THREE.CylinderGeometry(0.006, 0.006, 0.26, 16).translate(0, 0.13, 0), metal); armUp.name = 'ArmUpper';
+ const wrist = new THREE.Group(); wrist.name = 'Wrist'; wrist.position.y = 0.26 - 0.004; wrist.rotation.z = -1.2;
+ const shade = new THREE.Mesh(new THREE.CylinderGeometry(0.03, 0.075, 0.12, 32, 1, true).translate(0, -0.05, 0),
+ new THREE.MeshStandardMaterial({ color: 0xc8c8c8, roughness: 0.4, metalness: 0.6, side: THREE.DoubleSide }));
+ shade.name = 'Shade';
+ const bulb = new THREE.Mesh(new THREE.SphereGeometry(0.02, 16, 12), new THREE.MeshStandardMaterial({ color: 0xfff4d0, emissive: 0xffe3a0, emissiveIntensity: 2 }));
+ bulb.name = 'Bulb'; bulb.position.y = -0.06;
+ wrist.add(shade, bulb); armUp.add(wrist); elbow.add(armUp); armLo.add(elbow); shoulder.add(armLo);
+ g.add(base, shoulder);
+ g.userData.tick = (dt) => { elbow.rotation.z = 1.25 + 0.15 * Math.sin((elbow.userData.t = (elbow.userData.t || 0) + dt) * 0.8); };
+ return g;
+}
+const lamp = buildDeskLamp(THREE); lamp.userData.tick(0.1);
+selfcheck(THREE, buildMug(THREE), ['MugBody', 'MugHandle'], [0.118, 0.095, 0.084]);
+const lampBox = new THREE.Box3().setFromObject(lamp); console.log('lamp height', lampBox.max.y.toFixed(3));
+```
+
+Why: the mug profile contains the wall (no boolean needed); the handle curve ends inside
+the wall so `check_connectivity` sees one island; the lamp's three pivot Groups sit at the
+joints so `tick` can articulate it without touching geometry.
diff --git a/harness/codeverse/prompts/tracks/generate_articulated.j2 b/harness/codeverse/prompts/tracks/generate_articulated.j2
new file mode 100644
index 00000000..64492062
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/generate_articulated.j2
@@ -0,0 +1,79 @@
+# Build the articulated `{{ object_name }}`: bpy links + hand-written URDF
+
+You write TWO files: `src/model.py` (raw bpy — one mesh object per LINK, authored in WORLD
+coordinates at the rest pose) and `src/robot.urdf` (native URDF describing the joints). The harness
+exports each link to `meshes/<link>.glb`, lints the URDF, runs forward kinematics, sweeps every joint
+between its limits and checks for penetrations, then renders rest + limit poses for a judge.
+
+## Request
+{{ spec_prompt }}
+Constraints:
+{{ constraints }}
+
+## The contract (hard rules)
+{{ frame_doc }}
+{{ contract }}
+{% if cookbook_rel %}Copyable snippets live in `{{ cookbook_rel }}`.{% endif %}
+{% if cookbook_excerpt %}
+Cookbook excerpt:
+{{ cookbook_excerpt }}
+{% endif %}
+
+## Plan
+{{ plan_summary }}
+Overall bbox (rest pose): {{ overall_bbox }}
+Style: {{ style_notes }}
+
+Links (one bpy object each, named EXACTLY like the `part` column):
+{{ parts_table }}
+
+Link construction notes:
+{{ part_details }}
+
+Joints (the URDF must realise EXACTLY these; pivots are WORLD points at rest):
+{{ joints_table }}
+
+## Acceptance checklist
+{{ acceptance }}
+
+## DO
+- Build every link at its WORLD rest pose with the plan's bbox centre/extents (±0.01 m); each link is
+ ONE object (join sub-shapes into it) named exactly as the link.
+- Joint origins: for a joint with world pivot P and the parent's world origin O_parent, the URDF
+ `<origin xyz>` is P − O_parent expressed in the parent frame; the child's visual `<origin>` is the
+ child mesh offset relative to P. Keep the numbers consistent with the bbox centres in the table —
+ write them out explicitly as comments in the URDF before the joint.
+- Use the axis vectors from the table verbatim; limits = lower/upper from the table; `effort`/
+ `velocity` any positive numbers.
+- Keep ≥ 0.003 m clearance along each joint's motion direction between the child link and the
+ links it moves past (drawer vs cabinet walls, door vs frame); fixed neighbours overlap ≥ 0.002 m.
+- Hinged lids/doors pivot at their EDGE (the hinge line), drawers slide along the cabinet depth.
+
+## DON'T
+- No camera/light/render/export calls in bpy; no imports beyond bpy/bmesh/math/mathutils/random.
+- No links that float (every non-root link touches its parent at rest, or is attached by its joint
+ at a pivot that lies ON the child link's geometry ± 0.01 m).
+- No joint whose child passes through another link anywhere in [lower, upper].
+- No renaming of links/joints; no extra root links; one tree rooted at `{{ root_link }}` as planned.
+
+{% if skeleton_files %}
+## Current files (skeleton in src/ — keep the structure, fill every stub)
+{% for path, body in skeleton_files.items() %}
+--- {{ path }} ---
+```
+{{ body }}
+```
+{% endfor %}
+{% endif %}
+{% if previous_error %}
+## The previous attempt failed to build — fix the cause while rebuilding
+{{ previous_error }}
+{% endif %}
+
+{% if tool_cards and not single_shot %}
+## Tools available to you
+{{ tool_cards }}
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/generate_static.j2 b/harness/codeverse/prompts/tracks/generate_static.j2
new file mode 100644
index 00000000..06cb0e2f
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/generate_static.j2
@@ -0,0 +1,78 @@
+# Build `{{ object_name }}` in raw {{ language }}
+
+You write the COMPLETE code for one static 3D object from the plan below. A harness will execute
+your code, export a GLB, measure every part against the plan and render it for a judge. You never
+see the harness: make the code correct by construction, with the plan's exact numbers.
+
+## Request
+{{ spec_prompt }}
+Constraints:
+{{ constraints }}
+
+## The contract (hard rules — the build fails or the gate rejects when broken)
+{{ frame_doc }}
+{{ contract }}
+
+Files you must produce: {% for f in expected_files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}.
+{% if cookbook_rel %}Copyable snippets live in `{{ cookbook_rel }}` (read it before writing if you can).{% endif %}
+{% if cookbook_excerpt %}
+Cookbook excerpt:
+{{ cookbook_excerpt }}
+{% endif %}
+
+## Plan
+{{ plan_summary }}
+Overall bbox: {{ overall_bbox }}
+Style: {{ style_notes }}
+
+Parts (build EVERY row; names must match exactly — they become node names in the export):
+{{ parts_table }}
+
+Construction notes per part:
+{{ part_details }}
+
+## Acceptance checklist (the judge verifies each item; build so every item is visibly true)
+{{ acceptance }}
+
+## DO
+- Place each part so its bounding box CENTRE and EXTENTS equal the plan row (±0.01 m). Compute
+ positions from the numbers in the table; do not re-invent the layout.
+- Weld touching parts: overlap neighbours by ≥ 0.002 m (push a leg 2-5 mm into the seat). Never
+ bridge gaps with thin rods; no part may float.
+- Use `instances` + `symmetry` from the table: mirror pairs at ±x, radial sets around the up axis.
+- Put real detail where the plan says: chamfers/bevels 2-6 mm, tapers, grooves, slats, bolts —
+ with the stated radii and counts. Primitives alone are not enough; combine and shape them.
+- Materials per part with the stated colour (sRGB hex or 0-1 floats); roughness/metalness sensible.
+- Keep triangle counts sane (object ≤ 300k tris); segments 24-48 for round things.
+- Name parts EXACTLY as in the table (PascalCase). One named node/object per part (instances may
+ be `Name`, `Name_2`, … or a single parent named `Name`).
+
+## DON'T
+- No environment sniffing, no `typeof window`, no headless branches — one code path.
+- No DOM, canvas textures, image/texture loading, network, file IO, camera/light/render/export calls.
+- No helper SDKs or imports beyond the contract's allow-list.
+- No placeholders ("TODO", "simplified"); no part smaller than 50% of its planned extents; no
+ unit-cube stand-ins; no parts outside the overall bbox.
+- Do not change part names, counts or the overall size to "simplify".
+
+{% if skeleton_files %}
+## Current files (skeleton already in src/ — keep its structure, fill in every stub)
+{% for path, body in skeleton_files.items() %}
+--- {{ path }} ---
+```
+{{ body }}
+```
+{% endfor %}
+{% endif %}
+{% if previous_error %}
+## The previous attempt failed to build — fix the cause while rebuilding
+{{ previous_error }}
+{% endif %}
+
+{% if tool_cards and not single_shot %}
+## Tools available to you
+{{ tool_cards }}
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/plan_articulated.j2 b/harness/codeverse/prompts/tracks/plan_articulated.j2
new file mode 100644
index 00000000..b98c5884
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/plan_articulated.j2
@@ -0,0 +1,40 @@
+You are the DESIGN PLANNER for an ARTICULATED object (links + joints) that will be built in
+`{{ language }}`: Blender bpy meshes for the links and a hand-written URDF for the joints. You write
+the plan once; a builder model follows it without seeing you. Everything must be exact numbers.
+
+{{ frame_doc }}
+
+LANGUAGE CONTRACT THE BUILDER WILL FOLLOW:
+{{ contract }}
+
+WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
+1. `object_name` PascalCase; `summary` two sentences incl. overall size in meters and what moves.
+2. `overall_bbox` — real-world dimensions in meters, authored at the REST pose; bottom at up=0.
+3. `parts` = LINKS, 4 to 12. One part per rigid body that moves as a unit (a drawer is ONE link even
+ if it has a front, a box and a handle — describe those sub-shapes in `description`). Each part:
+ PascalCase `name`, `role`, `description` with construction numbers, `bbox` (centre + extents, meters,
+ rest pose, WORLD coordinates), `attach_to` = the parent link, `material` with colour.
+ Moving links must NOT penetrate their neighbours at rest: leave ≥ 0.003 m clearance in the motion
+ direction (drawer vs cabinet opening, door vs frame); fixed neighbours overlap ≥ 0.002 m.
+4. `root_link` — the grounded/base link (cabinet, base, chassis).
+5. `joints` — one per moving link, forming a single tree from `root_link`:
+ * `type` revolute (hinges, lids, doors; radians) · prismatic (drawers, slides; meters) ·
+ continuous (wheels, fans) · fixed (rigid attachments you still want as separate links).
+ * `axis` unit vector in the frame above; `pivot` a WORLD point on the axis at rest (the hinge line,
+ the slide direction through the drawer centre).
+ * `lower`/`upper` realistic limits (door 0..1.57 rad, lid 0..1.9 rad, drawer 0..0.8 × depth m);
+ `rest` within the limits (usually 0 = closed).
+ * `motion` one line: "lid opens upward about its back edge".
+6. `acceptance` — 6 to 12 items: dimensions (`measure`), ground contact, each key feature
+ (`visual`), and ONE `articulation` item per joint ("drawer slides out 0.35 m without touching the
+ cabinet", "door swings 90° about the left edge, no penetration through the range").
+
+RULES
+- Sweep-safe design: imagine each joint at lower, mid and upper — no link passes through another.
+ Hinged lids pivot at their back edge, NOT their centre; drawers slide along the cabinet depth.
+- Pivot and axis are the contract the URDF will be checked against; choose them to 3 decimals.
+- Every link except `root_link` is the child of exactly one joint; parent/child names are part names.
+- No prose outside the JSON.
+
+WORKED EXAMPLE (shape only — do not copy its values):
+{{ example_json }}
diff --git a/harness/codeverse/prompts/tracks/plan_scene.j2 b/harness/codeverse/prompts/tracks/plan_scene.j2
new file mode 100644
index 00000000..00f21d61
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/plan_scene.j2
@@ -0,0 +1,43 @@
+You are the SCENE DIRECTOR for a real-time three.js scene that several code-writing models will
+build in parallel from your plan alone (one per asset, one per zone, one for the environment).
+Write the plan as exact numbers and concrete nouns; keep it lean (cost matters).
+
+{{ frame_doc }}
+The scene uses the same frame: Y up, meters; the ground is around y=0 unless you say otherwise.
+
+LANGUAGE CONTRACT THE BUILDERS WILL FOLLOW:
+{{ contract }}
+
+WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
+1. `title`, `summary` (two sentences), `setting` (place, era, weather, time of day), `mood`.
+2. `bounds` — centre + extents in meters of the whole playable area (a garden 30 × 10 × 30 m; a
+ harbour 120 × 30 × 120 m). Keep it as small as the brief allows: detail beats acreage.
+3. `environment` — ONE paragraph with numbers: sky colours (hex), sun/moon direction as azimuth +
+ elevation in degrees, light colour/intensity, fog colour + density, ground material and height,
+ water plane height if any.
+4. `zones` — 3 to 8 spatial regions with PascalCase names, a description of what is there and how it
+ is laid out (paths, clusters, spacing in meters), a `bbox`, and `contents` = asset names placed
+ there. Zone bboxes tile the bounds without overlapping by more than 1 m.
+5. `assets` — 4 to 12 reusable things placed in zones. PascalCase `name`; `kind` = `threejs` for
+ procedural shapes (fences, lanterns, rocks, benches, trees, boats) or `blender_glb` ONLY for 1-3
+ hero objects that need sculpted/bevelled detail; `description` with construction numbers and
+ colours; `approx_size_m` = width × height × depth in meters (a stone lantern 0.5 × 1.6 × 0.5;
+ a bench 1.6 × 0.9 × 0.6; a pine 3 × 7 × 3); `instances_hint` = how many appear in total.
+ Ground cover, terrain, water and sky are NOT assets — they belong to the environment / zones.
+6. `effects` — 1 to 4: `glsl_material` (water ripple, lantern glow, wind-swayed foliage),
+ `particles` (petals, sparks, snow), `animated_geometry`, or `postprocess`; say which zone/asset.
+7. `animation` — 2 to 6 lines of what moves: amplitude + frequency in numbers.
+8. `cameras` — 2 to 4 authored cameras: `position`, `look_at` (meters), `fov` 35-70, `purpose`
+ (establishing shot from outside the bounds looking in; eye level at 1.6-1.8 m inside a zone; a
+ detail shot of the hero asset). Every camera must see at least two zones or a hero asset.
+9. `acceptance` — 6 to 12 items: each must-have from the brief, the hero assets visible from the
+ establishing camera, time-of-day lighting reads correctly, animation visible between t=0 and
+ t=1.5 s, no floating or sunken assets (`how: probe`), fps ≥ 30 at 1024×576.
+
+RULES
+- Every name in `zones[].contents` must be an asset name; asset names unique; zone names unique.
+- Realistic scale: people 1.7 m, doors 2.1 m, steps 0.17 m, benches 0.45 m seat height.
+- Prefer ≤ 8 assets and 3-5 zones for modest briefs. No prose outside the JSON.
+
+WORKED EXAMPLE (shape only — do not copy its values):
+{{ example_json }}
diff --git a/harness/codeverse/prompts/tracks/plan_static.j2 b/harness/codeverse/prompts/tracks/plan_static.j2
new file mode 100644
index 00000000..89e0f187
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/plan_static.j2
@@ -0,0 +1,40 @@
+You are the DESIGN PLANNER for a 3D modelling harness. You decompose ONE static object into a
+machine-readable plan that a code-writing model will build in `{{ language }}` without seeing
+you again. Everything the builder needs must be in the plan as exact numbers.
+
+{{ frame_doc }}
+
+LANGUAGE CONTRACT THE BUILDER WILL FOLLOW (so your plan must fit it):
+{{ contract }}
+
+WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
+1. `object_name` — PascalCase (e.g. `DiningChair`).
+2. `summary` — two sentences: what it is, overall size in meters, the 3-5 most recognisable features.
+3. `overall_bbox` — REAL-WORLD dimensions in meters (a dining chair is ~0.45 × 0.50 × 0.85 m, a
+ car ~4.5 × 1.8 × 1.45 m, a coffee mug ~0.09 × 0.09 × 0.10 m). Never unit cubes. Centre the
+ footprint on the up axis; the bottom sits at up=0, so the bbox centre's up-coordinate equals half
+ the height.
+4. `parts` — 6 to 14 parts (use `instances` for identical copies: 4 legs = ONE part, instances=4,
+ bbox of ONE copy; `symmetry` says how copies are laid out). For EACH part:
+ * `name` PascalCase, unique, descriptive (`SeatCushion`, `FrontLeg`, `Backrest`).
+ * `role` one line; `description` the construction recipe in numbers: primitive(s), thickness,
+ radii, taper, angles, edge treatment, visible detail (slats, grooves, bolts …).
+ * `bbox` centre + full extents in meters IN THE FRAME ABOVE; parts that touch must OVERLAP by at
+ least 0.002 m (2 mm) — never leave a gap between a leg and the seat.
+ * `attach_to` the part it is physically joined to (one parent; the main body has none).
+ * `material` plain words incl. colour (`oiled oak, warm brown`, `brushed steel`, `matte black plastic`).
+5. `style_notes` — era/style cues and the exact proportions that make it read as THAT object.
+6. `acceptance` — 6 to 12 checklist items, each verifiable from renders or measurements:
+ one per user constraint and must-have, one for overall dimensions (`how: measure`), one for
+ ground contact, one per key visible feature (`how: visual`). Ids `a1`, `a2`, …; `priority: must`
+ for things whose absence makes it the wrong object, `should` for polish.
+
+RULES
+- Real proportions over invention: think of a real reference product and its catalogue dimensions.
+- Parts must tile the object: the union of part bboxes ≈ the overall bbox; no part larger than the object.
+- Mirror pairs share one part with `symmetry: mirror_x` (or `mirror_y`) and `instances: 2`.
+- Every part name appears once; every `attach_to` names an existing part.
+- Numbers with 3 decimals (meters). No prose outside the JSON.
+
+WORKED EXAMPLE (shape only — do not copy its values):
+{{ example_json }}
diff --git a/harness/codeverse/prompts/tracks/refine_object.j2 b/harness/codeverse/prompts/tracks/refine_object.j2
new file mode 100644
index 00000000..3c0f6e39
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/refine_object.j2
@@ -0,0 +1,57 @@
+# Refine `{{ object_name }}` — round {{ round_index }}
+
+The object already builds. Renders + measurements were judged; below are the targeted changes for
+THIS round. Make exactly these changes, keep everything else as it is, and keep the code building.
+
+## Changes to make (in priority order; `[gate/...]` items are hard failures — fix them first)
+{% for t in tasks %}
+{{ loop.index }}. {{ t }}
+{% endfor %}
+
+Targets: {{ targets | join(', ') }}
+{% if edit_only_these %}
+EDIT ONLY THESE FILES (other tasks edit other files in parallel — touching anything else causes conflicts):
+{% for f in files %}- `{{ f }}`
+{% endfor %}
+{% else %}
+Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}
+{% endif %}
+
+## What the judge saw
+{{ judge_summary }}
+
+## Measured vs planned (exact numbers; the contract gate checks these)
+{{ measurement_notes }}
+
+## Plan rows for the targets (bbox centre/extents in meters — the truth to converge to)
+{{ parts_table }}
+
+## Acceptance checklist (unchanged)
+{{ acceptance }}
+
+## Contract reminders
+{{ frame_doc }}
+- Parts keep their exact names; instances/symmetry as planned.
+- Touching parts overlap ≥ 0.002 m; nothing floats; no connector rods.
+- Move a part by changing its placement numbers to the plan's centre; do not rebuild unrelated parts.
+- A "material" change = colour/roughness/metalness of that part only.
+- One code path: no environment sniffing, no DOM/texture loading/network.
+{% if current_files %}
+
+## Current file contents (edit these; return each edited file COMPLETE)
+{% for path, body in current_files.items() %}
+--- {{ path }} ---
+```
+{{ body }}
+```
+{% endfor %}
+{% endif %}
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+Run `build` after editing and fix any error before finishing.
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/repair.j2 b/harness/codeverse/prompts/tracks/repair.j2
new file mode 100644
index 00000000..5b4b49b5
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/repair.j2
@@ -0,0 +1,45 @@
+# Repair: the {{ language }} build failed (attempt {{ attempt }})
+
+Fix ONLY the error below with the smallest correct change. Keep every part, name, dimension and
+material exactly as they are. Do not refactor, do not "simplify" the model, do not remove parts.
+
+## Error report
+{{ error_report }}
+{% if repeats > 0 %}
+
+THIS IS THE SAME ERROR AS THE PREVIOUS ATTEMPT ({{ repeats }}× repeated). Your last edit did not
+touch the cause. Re-read the failing line, check the exact API name/signature against the contract
+and cookbook, and change a DIFFERENT thing this time (e.g. replace the failing call with the
+cookbook's copyable snippet instead of patching arguments).
+{% endif %}
+
+## Response rules
+- Locate the exact file:line named above; read the surrounding 20 lines mentally before editing.
+- Runtime error (exception / TypeError / missing export): fix the call or the import; the contract's
+ allow-list is the only set of modules you may use.
+- Lint error (forbidden API, missing entry point, wrong frame/units): replace the construct with the
+ one the fix hint names; do not argue with the linter.
+- Syntax error: fix the syntax at the line; check brackets/indentation in that function only.
+- Geometry bombs (out of memory / timeout): reduce segment counts or loop counts; never exceed 300k tris.
+- Keep one code path: no environment sniffing (`typeof window`, `isHeadless`, user agent checks).
+
+Failing file(s): {% for f in failing_files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}
+{% if files %}
+
+## Current contents of the failing file(s) — return each one COMPLETE and corrected
+{% for path, body in files.items() %}
+--- {{ path }} ---
+```
+{{ body }}
+```
+{% endfor %}
+{% endif %}
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+Run `build` after your edit; finish only when it succeeds.
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/scene_asset.j2 b/harness/codeverse/prompts/tracks/scene_asset.j2
new file mode 100644
index 00000000..d0bf3427
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/scene_asset.j2
@@ -0,0 +1,61 @@
+# Scene asset `{{ asset_name }}` ({{ asset_kind }}) — write `{{ asset_file }}`
+
+Scene: {{ spec_prompt }}
+{% if fix_instructions %}
+## FIX PASS — the asset was judged; apply exactly these changes and keep the rest
+{% for i in fix_instructions %}
+{{ i }}
+{% endfor %}
+{% endif %}
+
+## The asset
+- Name: `{{ asset_name }}`
+- Size (width × height × depth, meters): {{ '%.2f' % asset_size[0] }} × {{ '%.2f' % asset_size[1] }} × {{ '%.2f' % asset_size[2] }}
+- Description: {{ asset_description }}
+- Style of the whole scene: {{ style_notes or constraints }}
+
+{% if asset_language == 'blender' %}
+## Contract (raw bpy; the harness exports a GLB that the scene loads)
+{{ frame_doc }}
+{{ contract }}
+- Build the asset standing on the ground (lowest point at z=0), footprint centred on the origin,
+ total size as stated (±5%). Several named objects are fine; join sub-shapes that touch.
+- Materials with colours (Principled BSDF base colour), roughness 0.4-0.8 for wood/stone.
+- Keep it light: ≤ 40k triangles. No camera/light/render/export calls.
+{% else %}
+## Contract (raw three.js ESM module)
+{{ frame_doc }}
+{{ contract }}
+- `{{ asset_file }}` must `export function build{{ asset_name }}(THREE, opts = {}) { ... return group; }`
+ where `group` is a `THREE.Group` whose lowest point is at y=0 and whose footprint is centred on
+ the origin, sized as stated (±5%). `opts.seed` (number) and `opts.variant` (0..n) may vary
+ details deterministically (use a tiny mulberry32 PRNG inside the file — never Math.random).
+- Build from primitives (Box/Cylinder/Cone/Sphere/Lathe/Extrude/Tube) with MeshStandardMaterial
+ colours in hex; merge repeated pieces with InstancedMesh when > 20 copies.
+- Set `group.userData.size = [w, h, d]` to the measured size. Optional
+ `group.userData.tick = (t, dt) => {...}` for subtle motion.
+- No DOM, no texture/image loading, no fetch, no imports except `import * as THREE from 'three'`.
+- ≤ 15k triangles per instance; segments 12-24.
+{% endif %}
+
+## DO / DON'T
+- DO use the exact size numbers above; the zone builders rely on them.
+- DO give it the 3-4 recognisable features a person would name (a stone lantern: base, post, light
+ box with 4 windows, curved roof, finial).
+- DON'T leave floating pieces: every sub-shape overlaps a neighbour by ≥ 2 mm.
+- DON'T write anything but the asset file.
+{% if current_code %}
+
+## Current file (edit and return COMPLETE)
+```
+{{ current_code }}
+```
+{% endif %}
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/scene_compose.j2 b/harness/codeverse/prompts/tracks/scene_compose.j2
new file mode 100644
index 00000000..4682aa69
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/scene_compose.j2
@@ -0,0 +1,43 @@
+# Compose `{{ title }}` — write `src/scene.js`
+
+The environment (`src/env.js`), zones (`src/zones/*.js`) and assets (`src/assets/*.js`,
+`public/assets/*.glb`) exist. Write the entry module that wires them together.
+
+## Contract
+{{ frame_doc }}
+{{ contract }}
+`src/scene.js` must `export function createScene({ THREE, renderer, loaders }) → { scene, cameras, update }`:
+- `scene`: a `THREE.Scene`; call `buildEnv(THREE, scene)` from `./env.js`, then add every zone group
+ (`build<Zone>(ctx)` from `./zones/<zone>.js` with `ctx = { THREE, env, heightAt, MATS, rand }`),
+ each zone group named after the zone.
+- `cameras`: an array of `THREE.PerspectiveCamera` named after the planned cameras, positioned at the
+ planned `position` and `lookAt` numbers, `fov` as planned, aspect 16:9, near 0.1, far ≥ 2 × bounds.
+ `cameras[0]` is the establishing shot.
+- `update(t, dt)`: calls `tickEnv(t, dt)` and every `userData.tick(t, dt)` found on zone/asset groups
+ (traverse once at creation and cache the list; never traverse per frame).
+- Wrap each zone build in try/catch: a failing zone logs `console.error('[zone <name>] ' + err)` and is skipped.
+- Use a seeded mulberry32 `rand` (seed 1) so frames are reproducible.
+- GLB assets load via `loaders.gltf.loadAsync('public/assets/<snake>.glb')` — if you load any, keep the
+ scene buildable before they resolve (add to the group on resolve).
+
+## Plan
+Bounds: {{ bounds }}
+Zones:
+{{ zones_table }}
+Cameras (author EXACTLY these):
+{{ cameras }}
+Assets:
+{{ asset_api }}
+Animation: {{ animation }}
+
+## DON'T
+- No DOM, no window/document, no fetch, no CDN imports, no Math.random.
+- Do not rebuild env/zones/assets here; only import and place them.
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/scene_env.j2 b/harness/codeverse/prompts/tracks/scene_env.j2
new file mode 100644
index 00000000..3082e582
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/scene_env.j2
@@ -0,0 +1,46 @@
+# Environment module for `{{ title }}` — write `src/env.js`
+
+Scene: {{ spec_prompt }}
+Setting: {{ setting }}. Mood: {{ mood }}.
+Bounds: {{ bounds }}
+
+## Environment plan (realise these numbers)
+{{ environment }}
+
+## Contract
+{{ frame_doc }}
+{{ contract }}
+
+`src/env.js` must export:
+- `export function buildEnv(THREE, scene) → env` where `env = { sun, ambient, sky, ground, water, fog, heightAt }`
+ (fields may be null when absent). It adds sky (a large inverted sphere or a gradient ShaderMaterial
+ dome), the key light (`THREE.DirectionalLight` placed along the planned azimuth/elevation at ≥ 0.6 ×
+ the bounds' extent, `castShadow` with a shadow camera covering the bounds), an ambient/hemisphere
+ light, scene fog (`THREE.Fog` or `FogExp2` with the planned colour/density), the ground (plane or
+ subdivided terrain covering the bounds), and water if planned.
+- `export function heightAt(x, z) → y` (terrain height; 0 for flat ground). Zones call it to place
+ assets on the ground — it must be deterministic and cheap.
+- `export const MATS = { ... }` a small registry of shared `MeshStandardMaterial`s (stone, wood, leaf,
+ water, metal …) with hex colours so zones look coherent.
+- `export function tickEnv(t, dt) {}` for animated sky/water/fog (may be empty).
+
+## DO
+- Use the planned numbers literally: sun azimuth/elevation → `sun.position.set(cos(el)*sin(az), sin(el), cos(el)*cos(az)) * R`.
+- Colour-manage: `renderer.outputColorSpace` is set by the harness; author colours as sRGB hex.
+- Make it read at the planned time of day in ONE frame: exposure via light intensities (sun 1.5-3.0
+ at noon, 0.3-0.8 at dusk with warm colour; ambient 0.2-0.6).
+- Keep the whole module ≤ 250 lines; no textures, no DOM, no fetch.
+
+## DON'T
+- No assets/zones here (they come from other modules). No cameras. No `scene.background` image loads.
+
+## Effects planned (only the ones targeting the environment)
+{{ effects }}
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/scene_refine.j2 b/harness/codeverse/prompts/tracks/scene_refine.j2
new file mode 100644
index 00000000..db40f02d
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/scene_refine.j2
@@ -0,0 +1,65 @@
+# Refine `{{ title }}` — round {{ round_index }}
+
+The scene builds and was rendered from the authored cameras at t=0 and t=1.5 s, then judged. Make
+exactly the changes below, keep everything else, keep the build clean (no console errors).
+
+## Changes to make (priority order; `[gate/...]` items are hard failures — fix them first)
+{% for t in tasks %}
+{{ loop.index }}. {{ t }}
+{% endfor %}
+
+Targets: {{ targets | join(', ') }}
+{% if edit_only_these %}
+EDIT ONLY THESE FILES (other tasks edit other files in parallel):
+{% for f in files %}- `{{ f }}`
+{% endfor %}
+{% else %}
+Files in scope: {% for f in files %}`{{ f }}`{% if not loop.last %}, {% endif %}{% endfor %}
+{% endif %}
+
+## What the judge saw
+{{ judge_summary }}
+
+## Plan (unchanged truth)
+Bounds: {{ bounds }} · Setting: {{ setting }} · Mood: {{ mood }}
+Environment: {{ environment }}
+Zones:
+{{ zones_table }}
+Cameras:
+{{ cameras }}
+Assets:
+{{ asset_api }}
+Effects:
+{{ effects }}
+Animation: {{ animation }}
+
+## Acceptance checklist
+{{ acceptance }}
+
+## Reminders
+{{ frame_doc }}
+- A lighting/mood change lives in `src/env.js` (sun colour/intensity/azimuth, fog density, sky hex).
+- A composition/camera change lives in `src/scene.js` (camera position/look_at numbers only).
+- A zone change lives in its `src/zones/<zone>.js`; an asset change in `src/assets/<asset>.js`.
+- Console/shader errors: fix the named module; never wrap in try/catch to hide them.
+- Everything rests on `heightAt(x, z)`; nothing floats or sinks > 2 cm; keep fps ≥ 30 (InstancedMesh for repeats).
+- No DOM, no textures, no fetch, no Math.random, no CDN imports.
+{% if current_files %}
+
+## Current file contents (edit and return each COMPLETE)
+{% for path, body in current_files.items() %}
+--- {{ path }} ---
+```
+{{ body }}
+```
+{% endfor %}
+{% endif %}
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+Run `build` (and `scene_probe`) after editing; finish only when clean.
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/scene_zone.j2 b/harness/codeverse/prompts/tracks/scene_zone.j2
new file mode 100644
index 00000000..12033732
--- /dev/null
+++ b/harness/codeverse/prompts/tracks/scene_zone.j2
@@ -0,0 +1,44 @@
+# Zone `{{ zone_name }}` of `{{ title }}` — write `{{ zone_file }}`
+
+Scene: {{ spec_prompt }} · Setting: {{ setting }} · Mood: {{ mood }}
+
+## This zone
+- Description: {{ zone_description }}
+- Bbox: {{ zone_bbox }} — place EVERYTHING inside it (x/z), on the ground via `heightAt`.
+- Contents (asset names to place): {{ zone_contents | join(', ') if zone_contents else '(none — build local detail from primitives)' }}
+
+Neighbouring zones (do not build into them):
+{% for n in neighbours %}- {{ n }}
+{% endfor %}
+
+## Assets available (import exactly as shown; sizes are measured, meters w×h×d)
+{{ asset_api }}
+
+## Contract
+{{ frame_doc }}
+{{ contract }}
+`{{ zone_file }}` must `export function build{{ zone_name }}(ctx) → THREE.Group` where
+`ctx = { THREE, env, heightAt, MATS, rand }` (`rand()` is a seeded PRNG in [0,1)). Name the returned
+group `"{{ zone_name }}"`. Add instances of the listed assets at sensible real-world spacings
+(paths 1.2-2 m wide, trees ≥ 3 m apart, benches facing the view), rotate them for variety, and add
+zone-local detail from primitives (kerbs, gravel patches, planters, ropes, steps). Everything rests
+on `heightAt(x, z)` (lowest point touching the ground, never sunk > 2 cm, never floating).
+Optional `group.userData.tick = (t, dt) => {...}` to animate local things (lantern flicker, sway).
+
+## DO
+- Use the asset sizes above to avoid overlaps: keep ≥ 0.3 m between footprints unless stacking is intended.
+- Prefer `InstancedMesh` or reuse of one built asset group (`.clone()`) for ≥ 5 copies.
+- Keep the zone ≤ 250 lines and ≤ 400k triangles.
+
+## DON'T
+- No lights except small point lights for lanterns (≤ 4 per zone); no cameras; no sky/ground here.
+- No DOM, no textures, no fetch, no Math.random (use `ctx.rand`).
+- Do not import assets marked NOT AVAILABLE; do not edit other files.
+{% if tool_cards and not single_shot %}
+
+## Tools
+{{ tool_cards }}
+{% endif %}
+
+## Output
+{{ output_format }}
diff --git a/harness/codeverse/prompts/urdf/contract.md b/harness/codeverse/prompts/urdf/contract.md
new file mode 100644
index 00000000..a075e32b
--- /dev/null
+++ b/harness/codeverse/prompts/urdf/contract.md
@@ -0,0 +1,100 @@
+# URDF + bpy authoring contract — track `articulated_object`, language `urdf_blender`
+
+## Files
+```
+src/model.py pure bpy (same rules as the blender contract): ONE mesh object per link,
+ obj.name == link name, built in WORLD coordinates at the ZERO configuration.
+src/robot.urdf hand-written URDF: links + joints; every link's visual is
+ <mesh filename="meshes/<link>.glb"/> with <origin xyz="0 0 0" rpy="0 0 0"/>.
+```
+The harness runs `model.py` headless, exports `artifacts/meshes/<link>.glb` **in the
+link frame** (it translates your world mesh by −(link origin in world) — translation
+only, see the frame rule), lints the URDF, runs FK, sweeps every joint over its range
+for collisions, renders the rest/showcase pose and builds `object.glb` with one node
+per link. You never export.
+
+## Frame rule (the whole trick — follow it literally)
+* Z up, −Y front, +X right, meters, radians. Object on z = 0, centred on Z.
+* **Zero configuration = what you build** = doors closed, drawers in, lids down, arms at
+ home. The harness shows articulation by rendering at the plan's `rest` values
+ (e.g. door 0.3 rad ajar) and by `joint_sweep` — do not bake an ajar pose into geometry.
+* **Every joint `rpy="0 0 0"`.** All link frames stay axis-aligned with the world; a
+ link frame differs from the world frame only by a translation to its pivot.
+* `<joint><origin xyz>` = `pivot_child_world − pivot_parent_world` (plain subtraction),
+ where `pivot_root_world = (0,0,0)` and a pivot is a point ON the joint axis (hinge line
+ / slide axis / wheel axle). Fixed joints: the child's attachment point.
+* `<axis xyz>` is therefore the axis in WORLD coordinates (unit vector). Sign: positive
+ q must move the child the way a user expects (door swings OPEN, drawer pulls OUT
+ towards −Y front, lid lifts UP). If positive q closes it, negate the axis — never swap
+ lower/upper.
+* Child visuals: `<origin xyz="0 0 0" rpy="0 0 0"/>` ALWAYS (the harness already placed
+ the mesh in the link frame). No `scale`, no `package://`, no inline primitives.
+* Limits: `revolute`/`prismatic` MUST have `<limit lower upper effort velocity/>`
+ with `lower < upper`, lower ≤ 0 ≤ upper (zero config inside the range);
+ `continuous` has `<limit effort velocity/>` only; `fixed` none.
+* Single-root tree: exactly one link that is no joint's child (the base); every other
+ link is the child of exactly one joint; no cycles; ≤ 60 links. Moving parts that carry
+ hardware (handle on a door, knob on a drawer) attach with a `fixed` joint to the moving
+ link, not to the base.
+* Clearance: 1–3 mm between a moving part and its housing over the WHOLE range
+ (drawer vs cabinet walls, door vs frame); no penetration at any q in [lower, upper].
+* Names: link names == Blender object names == plan part names (PascalCase). Joint names
+ `<Parent>To<Child>` or the plan's joint names; all unique.
+
+## Allowed / forbidden
+Same as the blender contract for `model.py` (bpy, bmesh, mathutils, math, random).
+URDF: no `<gazebo>`, `<transmission>`, `<sensor>`, xacro, `package://`, mesh scale,
+`mimic` (unless the plan has it). Inertial blocks are optional (harness fills defaults).
+
+## COMPLETE minimal example (verified: bpy build + URDF parse + FK)
+A pedal bin: body + lid hinged at the back edge, knob fixed on the lid. Zero config =
+lid closed; the plan's `rest` (e.g. 0.5 rad) is what renders show.
+`src/model.py`
+```python
+import bpy, bmesh
+from mathutils import Vector
+
+W, D, H, T = 0.25, 0.25, 0.35, 0.010 # bin outer size, wall/lid thickness (m)
+PIVOT = {"Body": Vector((0, 0, 0))}
+
+def make_box(name, size, center):
+ bm = bmesh.new(); bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.scale(bm, vec=size, verts=bm.verts)
+ me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
+ o = bpy.data.objects.new(name, me); o.location = center
+ bpy.context.scene.collection.objects.link(o)
+ return o
+
+body = make_box("Body", (W, D, H), (0, 0, H / 2)) # root link, on the ground
+lid = make_box("Lid", (W, D, T), (0, 0, H + 0.001 + T / 2)) # 1 mm above the rim, closed
+knob = make_box("Knob", (0.03, 0.03, 0.02), (0, -D / 2 + 0.04, H + 0.001 + T + 0.008)) # 2 mm into lid
+PIVOT["Lid"] = Vector((0, D / 2, H + 0.001)) # hinge line = back top edge
+PIVOT["Knob"] = Vector((0, -D / 2 + 0.04, H + 0.001 + T)) # its attach point
+for child, parent in (("Lid", "Body"), ("Knob", "Lid")):
+ d = PIVOT[child] - PIVOT[parent]
+ print(child, f'<origin xyz="{d.x:.4f} {d.y:.4f} {d.z:.4f}" rpy="0 0 0"/>')
+```
+`src/robot.urdf` — lid opens UP: +q about +X at the back edge would push the front edge
+DOWN into the body, so the axis is −X (never fix a sign by swapping limits):
+```xml
+<?xml version="1.0"?>
+<robot name="PedalBin">
+ <link name="Body"><visual><origin xyz="0 0 0" rpy="0 0 0"/>
+ <geometry><mesh filename="meshes/Body.glb"/></geometry></visual></link>
+ <link name="Lid"><visual><origin xyz="0 0 0" rpy="0 0 0"/>
+ <geometry><mesh filename="meshes/Lid.glb"/></geometry></visual></link>
+ <link name="Knob"><visual><origin xyz="0 0 0" rpy="0 0 0"/>
+ <geometry><mesh filename="meshes/Knob.glb"/></geometry></visual></link>
+ <joint name="BodyToLid" type="revolute">
+ <parent link="Body"/><child link="Lid"/>
+ <origin xyz="0 0.125 0.351" rpy="0 0 0"/>
+ <axis xyz="-1 0 0"/>
+ <limit lower="0" upper="1.5" effort="5" velocity="2"/>
+ </joint>
+ <joint name="LidToKnob" type="fixed">
+ <parent link="Lid"/><child link="Knob"/>
+ <origin xyz="0 -0.21 0.01" rpy="0 0 0"/>
+ </joint>
+</robot>
+```
+See the cookbook for full cabinet (door + handle + drawer), laptop and cart examples.
diff --git a/harness/codeverse/prompts/urdf/cookbook.md b/harness/codeverse/prompts/urdf/cookbook.md
new file mode 100644
index 00000000..a5903601
--- /dev/null
+++ b/harness/codeverse/prompts/urdf/cookbook.md
@@ -0,0 +1,387 @@
+# URDF + bpy cookbook — articulated objects (`urdf_blender`)
+
+Every `python` snippet runs as-is in `blender -b --factory-startup`; every `xml` snippet is
+valid URDF (the harness test suite checks both). Z-up, −Y front, meters, radians.
+Use `read_cookbook(section="<heading>")` for one chapter.
+
+## The frame recipe (memorise this, it is the whole trick)
+
+```text
+1. Build every link's mesh in WORLD coordinates at the ZERO configuration (closed/home).
+2. One Blender object per link, obj.name == link name == plan part name.
+3. Pick a PIVOT for every non-root link: a point on its joint axis, in world coords
+ (hinge line, slide axis, axle). Root pivot = (0, 0, 0).
+4. URDF: every joint has rpy="0 0 0"; origin xyz = pivot_child − pivot_parent;
+ axis xyz = the joint axis in WORLD coords; every visual origin = "0 0 0".
+5. The harness exports meshes/<link>.glb already shifted by −pivot_link, so a link's
+ visual mesh is simply its world mesh in a frame parented at its pivot.
+```
+
+Pivot arithmetic is plain vector subtraction — do it in Python and print it:
+
+```python
+import bpy, bmesh, math
+from mathutils import Vector
+
+PIVOT = { # world-space pivots, filled while building
+ "Base": Vector((0, 0, 0)),
+}
+def urdf_origin(child: str, parent: str) -> str:
+ d = PIVOT[child] - PIVOT[parent]
+ return f'<origin xyz="{d.x:.4f} {d.y:.4f} {d.z:.4f}" rpy="0 0 0"/>'
+```
+
+## Skeleton (`src/model.py` for articulated objects)
+
+```python
+def link_obj(o):
+ bpy.context.scene.collection.objects.link(o); return o
+
+def make_box(name, size, center):
+ """Axis-aligned box; size = full extents, centre in world."""
+ bm = bmesh.new(); bmesh.ops.create_cube(bm, size=1.0)
+ bmesh.ops.scale(bm, vec=size, verts=bm.verts)
+ me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
+ o = bpy.data.objects.new(name, me); o.location = center
+ return link_obj(o)
+
+def make_cyl(name, radius, depth, center, axis='Z', segments=32):
+ """Cylinder along `axis` ('X'|'Y'|'Z'), centred at `center` (wheels: axis 'X')."""
+ bm = bmesh.new()
+ bmesh.ops.create_cone(bm, cap_ends=True, segments=segments, radius1=radius, radius2=radius, depth=depth)
+ me = bpy.data.meshes.new(name); bm.to_mesh(me); bm.free()
+ o = bpy.data.objects.new(name, me); o.location = center
+ if axis == 'X': o.rotation_euler = (0, math.radians(90), 0)
+ elif axis == 'Y': o.rotation_euler = (math.radians(90), 0, 0)
+ return link_obj(o)
+
+def join_as(name, objs):
+ """Several pieces → ONE link object (mesh islands are fine, but weld them ≥ 2 mm)."""
+ bpy.ops.object.select_all(action='DESELECT')
+ for o in objs: o.select_set(True)
+ bpy.context.view_layer.objects.active = objs[0]
+ bpy.ops.object.join()
+ objs[0].name = name
+ return objs[0]
+
+def material(obj, rgb, rough=0.5, metal=0.0):
+ m = bpy.data.materials.new(obj.name + "Mat")
+ b = m.node_tree.nodes["Principled BSDF"]
+ b.inputs["Base Color"].default_value = (*rgb, 1); b.inputs["Roughness"].default_value = rough
+ b.inputs["Metallic"].default_value = metal
+ obj.data.materials.append(m)
+```
+
+## Worked example 0: cabinet (door revolute + handle fixed + drawer prismatic)
+
+```python
+W, D, H, T = 0.50, 0.40, 0.70, 0.018 # cabinet outer size + panel thickness (m)
+DOOR_T, GAP = 0.018, 0.002 # front panel thickness, clearance
+FRONT_Y = -D / 2 - DOOR_T / 2 - 0.001 # front panels sit 1 mm proud of the carcass
+DRAWER_Z0, DRAWER_Z1 = 0.021, 0.156 # drawer box bottom/top (4 mm under the shelf)
+SHELF_Z0, DOOR_Z0 = 0.160, 0.184 # shelf above the drawer; door bottom edge
+
+# --- Carcass (root): 6 panels joined into ONE link object; opening faces -Y (front)
+panels = [
+ make_box("Carcass", (T, D, H), (-(W / 2 - T / 2), 0, H / 2)), # left side
+ make_box("Carcass_R", (T, D, H), ((W / 2 - T / 2), 0, H / 2)), # right side
+ make_box("Carcass_Top", (W - 2 * T, D, T), (0, 0, H - T / 2)),
+ make_box("Carcass_Floor", (W - 2 * T, D, T), (0, 0, T / 2)),
+ make_box("Carcass_Shelf", (W - 2 * T, D - T, T), (0, -T / 2, SHELF_Z0 + T / 2)),
+ make_box("Carcass_Back", (W - 2 * T, T, H - 2 * T), (0, D / 2 - T / 2, H / 2)),
+]
+carcass = join_as("Carcass", panels); material(carcass, (0.72, 0.68, 0.62))
+PIVOT["Carcass"] = Vector((0, 0, 0))
+
+# --- Door: hinged on its LEFT edge, closed at q = 0; +q about -Z swings it open (to -Y)
+door_h = H - DOOR_Z0 - GAP
+door = make_box("Door", (W - 2 * GAP, DOOR_T, door_h), (0, FRONT_Y, DOOR_Z0 + door_h / 2))
+material(door, (0.55, 0.35, 0.2))
+PIVOT["Door"] = Vector((-(W / 2 - GAP), FRONT_Y, 0)) # vertical hinge line (z arbitrary → 0)
+
+# --- DoorHandle: vertical bar on the door's free side, sunk 2 mm into the door (weld)
+handle = make_box("DoorHandle", (0.012, 0.034, 0.12), (W / 2 - 0.05, FRONT_Y - DOOR_T / 2 - 0.015, 0.45))
+material(handle, (0.8, 0.78, 0.74), 0.3, 1.0)
+PIVOT["DoorHandle"] = Vector((W / 2 - 0.05, FRONT_Y - DOOR_T / 2 - 0.015, 0.45))
+
+# --- Drawer: box + front panel joined; slides out towards -Y (front)
+hb = DRAWER_Z1 - DRAWER_Z0
+drawer = join_as("Drawer", [
+ make_box("Drawer", (W - 2 * T - 2 * GAP, 0.382, hb), (0, -0.011, DRAWER_Z0 + hb / 2)),
+ make_box("Drawer_Front", (W - 2 * GAP, DOOR_T, DOOR_Z0 - 0.005), (0, FRONT_Y, (0.002 + DOOR_Z0 - 0.003) / 2)),
+])
+material(drawer, (0.55, 0.35, 0.2))
+PIVOT["Drawer"] = Vector((0, -0.011, DRAWER_Z0 + hb / 2)) # any point on the slide axis
+
+for child, parent in (("Door", "Carcass"), ("DoorHandle", "Door"), ("Drawer", "Carcass")):
+ print(child, urdf_origin(child, parent))
+```
+
+```xml
+<?xml version="1.0"?>
+<robot name="Cabinet">
+ <link name="Carcass"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Carcass.glb"/></geometry></visual></link>
+ <link name="Door"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Door.glb"/></geometry></visual></link>
+ <link name="DoorHandle"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/DoorHandle.glb"/></geometry></visual></link>
+ <link name="Drawer"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Drawer.glb"/></geometry></visual></link>
+ <!-- hinge on the left front edge; +q about -Z swings the free edge to -Y (open) -->
+ <joint name="CarcassToDoor" type="revolute">
+ <parent link="Carcass"/><child link="Door"/>
+ <origin xyz="-0.248 -0.210 0" rpy="0 0 0"/>
+ <axis xyz="0 0 -1"/>
+ <limit lower="0" upper="1.6" effort="10" velocity="1"/>
+ </joint>
+ <joint name="DoorToDoorHandle" type="fixed">
+ <parent link="Door"/><child link="DoorHandle"/>
+ <origin xyz="0.448 -0.024 0.45" rpy="0 0 0"/>
+ </joint>
+ <!-- +q pulls the drawer out towards the front (-Y) -->
+ <joint name="CarcassToDrawer" type="prismatic">
+ <parent link="Carcass"/><child link="Drawer"/>
+ <origin xyz="0 -0.011 0.0885" rpy="0 0 0"/>
+ <axis xyz="0 -1 0"/>
+ <limit lower="0" upper="0.30" effort="10" velocity="0.5"/>
+ </joint>
+</robot>
+```
+
+`joint_sweep` sanity: at door q = 1.2 the free edge is well in front (y < −0.5); at
+drawer q = 0.3 the drawer front sits 0.3 m out; nothing collides at any sampled q.
+
+## Worked example 1: laptop (base + lid hinge + two-part screen)
+
+```python
+BW, BD, BT = 0.33, 0.23, 0.018 # base footprint + thickness
+LT, GAP = 0.006, 0.002 # lid thickness, hinge clearance
+
+# --- Base link (root) ---------------------------------------------------------
+base = make_box("Base", (BW, BD, BT), (0, 0, BT / 2))
+keys = make_box("Base_Keys", (BW - 0.04, BD * 0.45, 0.002), (0, -0.02, BT + 0.001 - 0.0005)) # 0.5 mm sunk
+pad = make_box("Base_Pad", (0.10, 0.06, 0.001), (0, -BD / 2 + 0.045, BT + 0.0005 - 0.0003))
+base = join_as("Base", [base, keys, pad]); material(base, (0.15, 0.15, 0.17), 0.4, 0.6)
+PIVOT["Base"] = Vector((0, 0, 0))
+
+# --- Lid link: hinge axis along X, 8 mm in from the back edge, 6.5 mm above the base top.
+# The hinge barrel belongs to the LID (it turns with it); closed (lying flat) at q = 0.
+hinge_y, hinge_z = BD / 2 - 0.008, BT + 0.0065
+LID_L = BD - 0.008 - GAP # plate runs from the axis to the front
+lid = make_box("Lid", (BW, LID_L, LT), (0, hinge_y - LID_L / 2, hinge_z))
+screen = make_box("Lid_Screen", (BW - 0.02, LID_L - 0.03, 0.0005), (0, hinge_y - LID_L / 2, hinge_z + LT / 2 - 0.0002))
+barrel = make_cyl("Lid_Hinge", 0.006, BW * 0.9, (0, hinge_y, hinge_z), axis='X', segments=24)
+lid = join_as("Lid", [lid, screen, barrel]); material(lid, (0.2, 0.2, 0.22), 0.3, 0.6)
+PIVOT["Lid"] = Vector((0, hinge_y, hinge_z))
+
+print("BaseToLid", urdf_origin("Lid", "Base")) # → <origin xyz="0.0000 0.1070 0.0245" rpy="0 0 0"/>
+```
+
+Axis sign check: a lid point at (0, −0.1, 0) relative to the hinge rotated by +q about
++X goes to (0, −0.1 cos q, −0.1 sin q) → z NEGATIVE → that closes INTO the base. So the
+axis is **−X** (`axis xyz="-1 0 0"`), limits 0 … 2.1 rad (120°). The lid plate sits 3.5 mm
+above the base top at q = 0 (keys are 1 mm below it): clearance, not contact.
+
+```xml
+<?xml version="1.0"?>
+<robot name="Laptop">
+ <link name="Base"><visual><origin xyz="0 0 0" rpy="0 0 0"/>
+ <geometry><mesh filename="meshes/Base.glb"/></geometry></visual></link>
+ <link name="Lid"><visual><origin xyz="0 0 0" rpy="0 0 0"/>
+ <geometry><mesh filename="meshes/Lid.glb"/></geometry></visual></link>
+ <joint name="BaseToLid" type="revolute">
+ <parent link="Base"/><child link="Lid"/>
+ <origin xyz="0 0.107 0.0245" rpy="0 0 0"/>
+ <axis xyz="-1 0 0"/>
+ <limit lower="0" upper="2.1" effort="5" velocity="2"/>
+ </joint>
+</robot>
+```
+
+## Worked example 2: hand cart (continuous wheels + prismatic telescopic handle)
+
+```python
+CW, CD, CH = 0.45, 0.35, 0.03 # deck
+WR, WT = 0.10, 0.03 # wheel radius / width
+
+POST_Y, POST_Z0, POST_H, POST_W, WALL = CD / 2 - 0.016, WR + CH, 0.60, 0.032, 0.003
+deck = make_box("Deck", (CW, CD, CH), (0, 0, WR + CH / 2)) # deck rides above the axle height
+# the handle post is a HOLLOW square tube (4 walls) so the telescopic grip can slide inside it
+walls = [make_box(f"Deck_PostW{i}", s, c) for i, (s, c) in enumerate([
+ ((POST_W, WALL, POST_H), (0, POST_Y - POST_W / 2 + WALL / 2, POST_Z0 + POST_H / 2)),
+ ((POST_W, WALL, POST_H), (0, POST_Y + POST_W / 2 - WALL / 2, POST_Z0 + POST_H / 2)),
+ ((WALL, POST_W - 2 * WALL, POST_H), (-POST_W / 2 + WALL / 2, POST_Y, POST_Z0 + POST_H / 2)),
+ ((WALL, POST_W - 2 * WALL, POST_H), (POST_W / 2 - WALL / 2, POST_Y, POST_Z0 + POST_H / 2))])]
+deck = join_as("Deck", [deck, *walls]); material(deck, (0.5, 0.33, 0.18))
+PIVOT["Deck"] = Vector((0, 0, 0))
+
+for i, sx in enumerate((-1, 1)):
+ name = f"Wheel{i + 1}"
+ cx = sx * (CW / 2 + WT / 2 + 0.002) # 2 mm outside the deck side
+ w = make_cyl(name, WR, WT, (cx, -CD / 2 + 0.06, WR), axis='X')
+ cap = make_cyl(name + "_Cap", 0.02, 0.012, (cx + sx * (WT / 2 + 0.003), -CD / 2 + 0.06, WR), axis='X')
+ w = join_as(name, [w, cap]); material(w, (0.05, 0.05, 0.05), 0.85) # cap overlaps the wheel 3 mm (same link)
+ PIVOT[name] = Vector((cx, -CD / 2 + 0.06, WR)) # on the axle
+
+# axle stubs belong to the Deck; they stop 1 mm short of each wheel's inner face (no penetration, "touching")
+axle = make_cyl("Deck_Axle", 0.008, CW + 0.002, (0, -CD / 2 + 0.06, WR), axis='X', segments=16)
+deck = join_as("Deck", [deck, axle])
+
+# telescopic handle slides UP (+Z) inside the post: zero config = fully retracted.
+# grip 24 mm square inside the 26 mm bore (1 mm clearance), bottom 70 mm above the deck, top 20 mm above the post
+grip = make_box("Handle", (0.024, 0.024, 0.55), (0, POST_Y, POST_Z0 + 0.07 + 0.275))
+bar = make_box("Handle_Bar", (0.30, 0.024, 0.024), (0, POST_Y, POST_Z0 + 0.07 + 0.55 + 0.012 - 0.004)) # 4 mm weld
+handle = join_as("Handle", [grip, bar]); material(handle, (0.7, 0.7, 0.72), 0.3, 1.0)
+PIVOT["Handle"] = Vector((0, POST_Y, POST_Z0 + POST_H / 2)) # any point on the slide axis
+
+for child, parent in (("Wheel1", "Deck"), ("Wheel2", "Deck"), ("Handle", "Deck")):
+ print(child, urdf_origin(child, parent))
+```
+
+```xml
+<?xml version="1.0"?>
+<robot name="HandCart">
+ <link name="Deck"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Deck.glb"/></geometry></visual></link>
+ <link name="Wheel1"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Wheel1.glb"/></geometry></visual></link>
+ <link name="Wheel2"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Wheel2.glb"/></geometry></visual></link>
+ <link name="Handle"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/Handle.glb"/></geometry></visual></link>
+ <joint name="DeckToWheel1" type="continuous">
+ <parent link="Deck"/><child link="Wheel1"/>
+ <origin xyz="-0.242 -0.115 0.1" rpy="0 0 0"/><axis xyz="1 0 0"/>
+ <limit effort="1" velocity="20"/>
+ </joint>
+ <joint name="DeckToWheel2" type="continuous">
+ <parent link="Deck"/><child link="Wheel2"/>
+ <origin xyz="0.242 -0.115 0.1" rpy="0 0 0"/><axis xyz="1 0 0"/>
+ <limit effort="1" velocity="20"/>
+ </joint>
+ <joint name="DeckToHandle" type="prismatic">
+ <parent link="Deck"/><child link="Handle"/>
+ <origin xyz="0 0.159 0.43" rpy="0 0 0"/><axis xyz="0 0 1"/>
+ <limit lower="0" upper="0.35" effort="10" velocity="0.5"/>
+ </joint>
+</robot>
+```
+
+Why: wheels are cylinders along X (`axis='X'`), their pivot is the axle point; the
+telescopic handle's zero config is retracted (inside the post), q pulls it up.
+
+## Joint types, axes, limits (what to write)
+
+| joint | use | `<axis>` sign rule | `<limit>` |
+|---|---|---|---|
+| `revolute` | doors, lids, hinges, levers, knobs with stops | +q = opens / lifts / the "interact" direction | `lower upper effort velocity` all required |
+| `prismatic` | drawers, slides, telescopes, pistons, buttons | +q = pulls OUT / extends | `lower="0" upper=<travel>` |
+| `continuous` | wheels, fans, spinners, casters' roll | right-hand about axis | `effort velocity` only (NO lower/upper) |
+| `fixed` | handles, knobs, feet, labels on a moving link | — | none |
+
+Plausible ranges (SI):
+
+| mechanism | type | lower | upper | notes |
+|---|---|---|---|---|
+| cabinet / room door | revolute | 0 | 1.6–1.9 rad | axis vertical through the hinge edge |
+| laptop / lid / chest lid | revolute | 0 | 1.6–2.1 rad | axis along the back edge |
+| toilet seat / piano fallboard | revolute | 0 | 1.5 rad | |
+| oven / dishwasher door | revolute | 0 | 1.57 rad | axis along the bottom edge |
+| drawer | prismatic | 0 | 0.35–0.45 m (≈ 0.8 × depth) | axis −Y (front) |
+| keyboard tray / telescopic | prismatic | 0 | 0.2–0.4 m | |
+| button / key | prismatic | 0 | 0.002–0.01 m | axis into the body |
+| wheel / caster roll | continuous | — | — | axis = axle (usually X) |
+| caster swivel | continuous | — | — | vertical axis above the wheel |
+| knob / dial | revolute or continuous | −2.6 | 2.6 rad | |
+| lever / switch | revolute | 0 | 0.5–0.9 rad | |
+| faucet handle | revolute | 0 | 1.57 rad | |
+| scissor / tongs | revolute | 0 | 0.6–1.0 rad | one joint; the other leg is the root |
+| robot arm joint | revolute | −2.9 | 2.9 rad | |
+| gripper finger | prismatic | 0 | 0.04 m | |
+
+The harness renders the showcase pose at the plan's `rest` (e.g. door 0.3 rad, drawer
+0.12 m) so the articulation is visible — you still build q = 0.
+
+## Clearances, rest pose, hardware
+
+* Moving part vs housing: 1–3 mm all round over the WHOLE range (drawer box inside the
+ cabinet: 2 mm each side, 4 mm above; door leaf vs frame: 2 mm). Test mentally at
+ `upper`: does the door corner sweep through the side panel? Put the hinge ON the edge.
+* Zero config must not self-intersect: a closed door touches the carcass face
+ (flush, 0–1 mm), never sinks into it.
+* Handles / knobs / pulls: `fixed` joint to the MOVING link, welded 2 mm into it, pivot =
+ handle centre. Hinge barrels and drawer runners belong to the housing link (or to the
+ moving link) — they are geometry, not joints.
+* One mechanism per joint. Doubles (two doors, four wheels) = separate links with their
+ own pivots; identical meshes are fine.
+* Runners/rails for drawers: two thin boxes on the cabinet sides + two on the drawer box;
+ drawer box bottom 3 mm above the rail.
+
+## URDF skeleton (copy, then fill)
+
+```xml
+<?xml version="1.0"?>
+<robot name="ObjectName">
+ <!-- one <link> per Blender object, names identical -->
+ <link name="Base">
+ <visual><origin xyz="0 0 0" rpy="0 0 0"/>
+ <geometry><mesh filename="meshes/Base.glb"/></geometry></visual>
+ <!-- optional but welcome: <inertial><mass value="5"/><inertia ixx="0.1" iyy="0.1" izz="0.1" ixy="0" ixz="0" iyz="0"/></inertial> -->
+ </link>
+ <link name="Child">
+ <visual><origin xyz="0 0 0" rpy="0 0 0"/>
+ <geometry><mesh filename="meshes/Child.glb"/></geometry></visual>
+ </link>
+ <joint name="BaseToChild" type="revolute">
+ <parent link="Base"/><child link="Child"/>
+ <origin xyz="PX PY PZ" rpy="0 0 0"/> <!-- pivot_child - pivot_parent -->
+ <axis xyz="0 0 1"/> <!-- unit, WORLD direction, +q = open -->
+ <limit lower="0" upper="1.6" effort="10" velocity="1"/>
+ </joint>
+</robot>
+```
+
+## Pitfalls (symptom → cause → fix)
+
+1. **Door swings into the cabinet** → axis sign. Flip the axis (`0 0 1` ↔ `0 0 -1`);
+ never make `lower` negative to compensate.
+2. **Child jumps when q changes / orbits around the wrong point** → pivot not on the
+ hinge line: the pivot must be a point ON the axis (edge of the door, the axle), not
+ the part's centre.
+3. **Lid/door geometry shifted after export** → you wrote a non-zero visual `<origin>` or
+ `rpy` on a joint. Everything is `0 0 0`; the harness does the shifting.
+4. **"link X has two parent joints" / "not connected to root"** → every non-root link is
+ the child of exactly one joint; handles attach to the door, not to the base AND door.
+5. **Penetration at upper limit** (`joint_sweep` says `Drawer` hits `Base` at q = 0.4) →
+ travel too long or clearance zero. Shorten `upper` to 0.8 × depth, add 2 mm gaps.
+6. **Parts float** (`check_connectivity`): hinge barrels, runners, knobs not overlapping.
+ Weld 2 mm.
+7. **`continuous` with `<limit lower upper>`** or `revolute` without limits → lint error.
+8. **Blender object names ≠ link names** (`Door.001`, `door`) → mesh not found. Exact
+ PascalCase, unique, no suffix; join sub-pieces with `join_as`.
+9. **Object not on the ground** → wheels' bottom / feet at z = 0 in the zero config.
+10. **Mesh scale in URDF** (`scale="0.001 …"`) → forbidden; author in metres.
+11. **Non-unit axis** (`0 0 2`) → lint error; also avoid `0.7 0.7 0` unless intended.
+12. **Zero config is the open pose** → renders at rest look closed/odd and collision at
+ `lower` fails; build closed, let the harness open it.
+13. **Articulation invisible in renders** → plan `rest` 0 on every joint; ask for a
+ non-zero showcase (door 0.3 rad, drawer 0.12 m) — that is the plan's job, not geometry's.
+14. **Handles built in world but parented to the wrong link** → their pivot must be
+ subtracted from the DOOR pivot (`urdf_origin("Handle", "Door")`), not from the base.
+
+## Self-check (before you call it done)
+
+```python
+def urdf_selfcheck(expected_links):
+ names = sorted(o.name for o in bpy.data.objects if o.type == 'MESH')
+ missing = [n for n in expected_links if n not in names]
+ extra = [n for n in names if n not in expected_links]
+ assert not missing and not extra, f"links mismatch: missing={missing} extra={extra}"
+ assert all("." not in n for n in names), f"auto-suffixed: {[n for n in names if '.' in n]}"
+ for n in expected_links:
+ assert n in PIVOT, f"no pivot recorded for {n}"
+ bpy.context.view_layer.update()
+ zmin = min((o.matrix_world @ Vector(c)).z for o in bpy.data.objects if o.type == 'MESH' for c in o.bound_box)
+ assert abs(zmin) < 0.002, f"lowest point z={zmin:.4f}"
+ print("[selfcheck] links", names, "pivots ok")
+
+urdf_selfcheck(["Carcass", "Door", "DoorHandle", "Drawer", "Base", "Lid",
+ "Deck", "Wheel1", "Wheel2", "Handle"])
+```
+
+Then: `build` → `render_sheet` → `check_connectivity` → `joint_sweep` on EVERY joint
+(look at q = lower / mid / upper renders: does the right part move, the right way, without
+penetration?) → `check_contract`.
diff --git a/harness/codeverse/spatial/__init__.py b/harness/codeverse/spatial/__init__.py
new file mode 100644
index 00000000..5837e9a9
--- /dev/null
+++ b/harness/codeverse/spatial/__init__.py
@@ -0,0 +1,10 @@
+"""Language-agnostic spatial tools (on GLB / URDF / scene bundles).
+
+Tools are registered with ``@tool`` (see ``registry.py``) so ONE definition
+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
+
+__all__ = ["Observation", "ToolDef", "ToolUsageError", "get_tool", "list_tools", "tool"]
diff --git a/harness/codeverse/spatial/connectivity.py b/harness/codeverse/spatial/connectivity.py
new file mode 100644
index 00000000..6d75bcff
--- /dev/null
+++ b/harness/codeverse/spatial/connectivity.py
@@ -0,0 +1,288 @@
+"""Connectivity gate: are all parts of the GLB physically attached?
+
+Mechanism
+---------
+1. Load one world-space mesh per top-level node (``measure.part_meshes``).
+2. For every part pair whose AABBs come within ``gap_m`` of each other compute
+ the exact minimum surface distance (python-fcl via ``trimesh.collision``;
+ sampled closest-point fallback when fcl is missing) and the closest points.
+3. Contact graph: edge when distance ≤ ``gap_m``. The *support component* is
+ the connected component holding the ground-touching parts (lowest point at
+ y ≤ gap) — or the largest component when nothing touches the ground.
+4. Parts outside the support component are **floating** → ERROR with the
+ nearest supported part and the exact translation vector that closes the gap.
+5. Overlapping AABB pairs are probed for mutual containment of surface samples;
+ a depth above ``PENETRATION_WARN_M`` → WARN, above ``PENETRATION_ERROR_M``
+ → ERROR (parts are allowed to overlap by a hair for welding, not to pass
+ through each other).
+6. Tiny disconnected islands inside a single part → WARN (stray geometry).
+
+All thresholds are module constants (meters) and keyword-overridable.
+"""
+
+from __future__ import annotations
+
+import itertools
+import time
+from dataclasses import dataclass
+from pathlib import Path
+
+import numpy as np
+import trimesh
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.conventions import CONTACT_GAP_M
+from codeverse.spatial.measure import GlbLoadError, load_scene, part_meshes
+
+GATE = "connectivity"
+#: parts smaller than this (max extent) are ignored for floating checks (INFO only)
+MIN_PART_SIZE_M = 0.01
+#: penetration depth that is reported as WARN / ERROR
+PENETRATION_WARN_M = 0.002
+PENETRATION_ERROR_M = 0.010
+#: fraction of one part's samples inside the other before we call it penetration
+PENETRATION_MIN_FRACTION = 0.02
+#: surface samples per part for containment / fallback distance tests
+N_SAMPLES = 600
+#: an island is "tiny" when its largest extent is below this fraction of the part's
+TINY_ISLAND_FRACTION = 0.05
+_RNG_SEED = 7
+
+
+@dataclass(frozen=True)
+class PairDistance:
+ a: str
+ b: str
+ distance: float
+ point_a: tuple[float, float, float]
+ point_b: tuple[float, float, float]
+
+ @property
+ def gap_vector(self) -> tuple[float, float, float]:
+ """Translation to apply to ``a`` so that it touches ``b``."""
+ return tuple(float(pb - pa) for pa, pb in zip(self.point_a, self.point_b, strict=True)) # type: ignore[return-value]
+
+
+def _aabb_gap(a: trimesh.Trimesh, b: trimesh.Trimesh) -> float:
+ """Axis-aligned lower bound of the distance between two meshes."""
+ lo = np.maximum(a.bounds[0] - b.bounds[1], b.bounds[0] - a.bounds[1])
+ return float(np.linalg.norm(np.maximum(lo, 0.0)))
+
+
+def _fcl_available() -> bool:
+ try:
+ import fcl # noqa: F401
+
+ return True
+ except Exception:
+ return False
+
+
+def pair_distance(name_a: str, a: trimesh.Trimesh, name_b: str, b: trimesh.Trimesh) -> PairDistance:
+ """Exact (fcl) or sampled minimum distance between two meshes with closest points."""
+ if _fcl_available():
+ try:
+ from trimesh.collision import CollisionManager
+
+ cm = CollisionManager()
+ cm.add_object("a", a)
+ d, _name, data = cm.min_distance_single(b, return_name=True, return_data=True)
+ pa, pb = data.point("a"), data.point("__external")
+ return PairDistance(name_a, name_b, float(max(d, 0.0)), tuple(map(float, pa)), tuple(map(float, pb)))
+ except Exception:
+ pass # fall through to the sampled estimate
+ rng = np.random.default_rng(_RNG_SEED)
+ best: PairDistance | None = None
+ for src, dst, flip in ((a, b, False), (b, a, True)):
+ pts = np.vstack([src.vertices, _sample(src, N_SAMPLES, rng)])
+ closest, dist, _ = trimesh.proximity.closest_point(dst, pts)
+ i = int(np.argmin(dist))
+ p_src, p_dst = tuple(map(float, pts[i])), tuple(map(float, closest[i]))
+ cand = PairDistance(name_a, name_b, float(dist[i]), *((p_dst, p_src) if flip else (p_src, p_dst)))
+ if best is None or cand.distance < best.distance:
+ best = cand
+ assert best is not None
+ return best
+
+
+def _sample(mesh: trimesh.Trimesh, n: int, rng: np.random.Generator) -> np.ndarray:
+ """Deterministic surface samples (seeded)."""
+ pts, _ = trimesh.sample.sample_surface(mesh, n, seed=int(rng.integers(1 << 30)))
+ return np.asarray(pts, dtype=float)
+
+
+def penetration_depth(a: trimesh.Trimesh, b: trimesh.Trimesh, n: int = N_SAMPLES) -> tuple[float, float]:
+ """(max depth, fraction of samples inside) of ``a``'s surface inside ``b`` and vice versa."""
+ rng = np.random.default_rng(_RNG_SEED)
+ worst_depth, worst_frac = 0.0, 0.0
+ for src, dst in ((a, b), (b, a)):
+ if not dst.is_watertight: # containment is meaningless on open shells
+ continue
+ pts = _sample(src, n, rng)
+ try:
+ inside = dst.contains(pts)
+ except Exception:
+ continue
+ frac = float(np.mean(inside)) if len(inside) else 0.0
+ if frac <= 0.0:
+ continue
+ _, dist, _ = trimesh.proximity.closest_point(dst, pts[inside])
+ worst_depth = max(worst_depth, float(np.max(dist)))
+ worst_frac = max(worst_frac, frac)
+ return worst_depth, worst_frac
+
+
+def _components(names: list[str], edges: set[tuple[str, str]]) -> list[set[str]]:
+ parent = {n: n for n in names}
+
+ def find(x: str) -> str:
+ while parent[x] != x:
+ parent[x] = parent[parent[x]]
+ x = parent[x]
+ return x
+
+ for a, b in edges:
+ parent[find(a)] = find(b)
+ comps: dict[str, set[str]] = {}
+ for n in names:
+ comps.setdefault(find(n), set()).add(n)
+ return list(comps.values())
+
+
+def _fmt_vec(v: tuple[float, float, float]) -> str:
+ return "(" + ", ".join(f"{x:+.4f}" for x in v) + ")"
+
+
+def _island_findings(name: str, mesh: trimesh.Trimesh) -> list[GateFinding]:
+ try:
+ islands = mesh.split(only_watertight=False)
+ except Exception:
+ return []
+ if len(islands) <= 1:
+ return []
+ ext = float(np.max(mesh.extents))
+ tiny = [i for i in islands if float(np.max(i.extents)) < TINY_ISLAND_FRACTION * ext]
+ out = []
+ if tiny:
+ out.append(GateFinding(
+ gate=GATE, severity=Severity.WARN, target=name,
+ message=f"part '{name}' contains {len(tiny)} tiny disconnected island(s) (< {TINY_ISLAND_FRACTION:.0%} of the part size) — stray geometry",
+ fix_hint=f"remove the stray pieces or merge them into '{name}'; the part should be {len(islands) - len(tiny)} solid piece(s)",
+ data={"islands": len(islands), "tiny_islands": len(tiny)},
+ ))
+ return out
+
+
+def check_connectivity(
+ glb: Path | str,
+ *,
+ gap_m: float = CONTACT_GAP_M,
+ min_part_size_m: float = MIN_PART_SIZE_M,
+ penetration_warn_m: float = PENETRATION_WARN_M,
+ penetration_error_m: float = PENETRATION_ERROR_M,
+) -> GateReport:
+ """Run the connectivity gate on ``glb`` (see module docstring)."""
+ t0 = time.time()
+ findings: list[GateFinding] = []
+ try:
+ parts = {k: v for k, v in part_meshes(load_scene(glb)).items() if v is not None and len(v.faces)}
+ except GlbLoadError as e:
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, message=str(e), fix_hint="run `build` first"))
+ return GateReport(gate=GATE, passed=False, findings=findings, duration_ms=int((time.time() - t0) * 1000))
+ if not parts:
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, message="GLB has no mesh parts",
+ fix_hint="the build exported nothing — check the code creates geometry"))
+ return GateReport(gate=GATE, passed=False, findings=findings, duration_ms=int((time.time() - t0) * 1000))
+
+ names = list(parts)
+ sizes = {n: float(np.max(parts[n].extents)) for n in names}
+ big = [n for n in names if sizes[n] >= min_part_size_m]
+ for n in names:
+ if n not in big:
+ findings.append(GateFinding(gate=GATE, severity=Severity.INFO, target=n,
+ message=f"part '{n}' is tiny ({sizes[n] * 1000:.1f} mm) — skipped for contact checks"))
+ # ---- pairwise distances (AABB prefilter) + penetration
+ edges: set[tuple[str, str]] = set()
+ exact: dict[tuple[str, str], PairDistance] = {}
+ for a, b in itertools.combinations(big, 2):
+ lower = _aabb_gap(parts[a], parts[b])
+ if lower > gap_m:
+ continue
+ pd = pair_distance(a, parts[a], b, parts[b])
+ exact[(a, b)] = pd
+ if pd.distance <= gap_m:
+ edges.add((a, b))
+ if lower == 0.0: # AABBs overlap → possible penetration
+ depth, frac = penetration_depth(parts[a], parts[b])
+ if frac >= PENETRATION_MIN_FRACTION and depth > penetration_warn_m:
+ sev = Severity.ERROR if depth > penetration_error_m else Severity.WARN
+ findings.append(GateFinding(
+ gate=GATE, severity=sev, target=a,
+ message=f"'{a}' and '{b}' interpenetrate by ≈{depth * 1000:.1f} mm ({frac:.0%} of surface samples inside)",
+ fix_hint=f"shrink or move '{a}'/'{b}' so they overlap by ≤ {penetration_warn_m * 1000:.0f} mm (a hairline overlap is fine for welding)",
+ data={"other": b, "depth_m": depth, "fraction_inside": frac},
+ ))
+ # ---- components → floating parts
+ comps = _components(big, edges)
+ grounded = {n for n in big if float(parts[n].bounds[0][1]) <= gap_m}
+ support_sets = [c for c in comps if c & grounded]
+ if support_sets:
+ support = max(support_sets, key=lambda c: sum(len(parts[n].faces) for n in c))
+ for c in support_sets:
+ support |= c
+ else:
+ support = max(comps, key=lambda c: sum(len(parts[n].faces) for n in c)) if comps else set()
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, message="no part touches the ground (y=0)",
+ fix_hint="move the whole object down so its lowest point sits at y=0"))
+ for n in big:
+ if n in support:
+ continue
+ near = _nearest_supported(n, parts, support, exact)
+ if near is None:
+ findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, target=n,
+ message=f"part '{n}' is floating: touches nothing", fix_hint=f"attach '{n}' to a neighbouring part"))
+ continue
+ other = near.b if near.a == n else near.a
+ vec = near.gap_vector if near.a == n else tuple(-x for x in near.gap_vector)
+ p_self = near.point_a if near.a == n else near.point_b
+ p_other = near.point_b if near.a == n else near.point_a
+ findings.append(GateFinding(
+ gate=GATE, severity=Severity.ERROR, target=n,
+ message=f"part '{n}' is floating: nearest supported part is '{other}' at {near.distance * 1000:.1f} mm",
+ fix_hint=f"translate '{n}' by {_fmt_vec(vec)} m (or extend it by {near.distance * 1000:.1f} mm towards '{other}') so the surfaces touch",
+ data={"nearest": other, "gap_m": near.distance, "gap_vector_m": list(vec),
+ "closest_point_self": list(p_self), "closest_point_other": list(p_other)},
+ ))
+ # ---- stray islands inside parts
+ for n in big:
+ findings.extend(_island_findings(n, parts[n]))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ if passed and len(big) > 1:
+ findings.append(GateFinding(gate=GATE, severity=Severity.INFO,
+ message=f"all {len(big)} parts are connected ({len(edges)} contacts, gap ≤ {gap_m * 1000:.0f} mm)"))
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
+
+
+def _nearest_supported(
+ n: str,
+ parts: dict[str, trimesh.Trimesh],
+ support: set[str],
+ exact: dict[tuple[str, str], PairDistance],
+ n_candidates: int = 3,
+) -> PairDistance | None:
+ """Exact distance from floating part ``n`` to its nearest supported part.
+
+ Candidates are ranked by AABB lower bound; the closest few get an exact test.
+ """
+ if not support:
+ return None
+ ranked = sorted(support, key=lambda o: _aabb_gap(parts[n], parts[o]))[:n_candidates]
+ best: PairDistance | None = None
+ for o in ranked:
+ pd = exact.get((n, o)) or exact.get((o, n))
+ if pd is None:
+ pd = pair_distance(n, parts[n], o, parts[o])
+ exact[(n, o)] = pd
+ if best is None or pd.distance < best.distance:
+ best = pd
+ return best
diff --git a/harness/codeverse/spatial/contract.py b/harness/codeverse/spatial/contract.py
new file mode 100644
index 00000000..c050b175
--- /dev/null
+++ b/harness/codeverse/spatial/contract.py
@@ -0,0 +1,217 @@
+"""Contract gate: does the built GLB honour the plan's part list and boxes?
+
+Plans are authored in the language's *native* frame (see ``conventions``):
+blender / cadquery / urdf are Z-up with -Y front, three.js is Y-up. The GLB is
+always Y-up, so plan boxes are converted with the glTF mapping
+``(x, y, z) → (x, z, -y)`` before comparison.
+
+Severity policy (``tol = max(tol_m, REL_TOL × plan extent)`` per axis):
+* plan part missing in the GLB → ERROR
+* bbox centre / extents off by > tol → WARN (exact delta in the hint);
+ > ``ERROR_FACTOR × tol`` → ERROR
+* overall bbox vs ``overall_bbox`` → same policy
+* not standing on the ground / footprint off-centre → WARN
+* GLB parts the plan never mentioned → INFO
+* ScenePlan: zone groups missing → WARN; model outside ``bounds`` → WARN
+"""
+
+from __future__ import annotations
+
+import re
+import time
+from dataclasses import dataclass
+
+import numpy as np
+
+from codeverse.contracts.artifacts import (
+ GateFinding,
+ GateReport,
+ Measurement,
+ PartMeasure,
+ Severity,
+)
+from codeverse.contracts.plan import BBox, PartPlan, Plan, ScenePlan, StaticPlan
+from codeverse.conventions import BBOX_TOLERANCE_M, LANGUAGE_FRAME, Frame, to_snake
+
+GATE = "contract"
+#: relative tolerance on extents (fraction of the plan's extent)
+REL_TOL = 0.10
+#: a delta beyond ERROR_FACTOR × tolerance is an error, not a warning
+ERROR_FACTOR = 3.0
+_AXES = ("x", "y", "z")
+
+
+# --------------------------------------------------------------------------- frames
+def plan_bbox_to_glb(bbox: BBox, language: str) -> BBox:
+ """Convert a plan-frame box to the canonical GLB frame (Y-up, +Z front)."""
+ frame = LANGUAGE_FRAME.get(str(language), Frame.Y_UP_POS_Z_FRONT)
+ if frame is Frame.Y_UP_POS_Z_FRONT:
+ return bbox
+ cx, cy, cz = bbox.center
+ ex, ey, ez = bbox.extents
+ return BBox(center=(cx, cz, -cy), extents=(ex, ez, ey))
+
+
+# --------------------------------------------------------------------------- matching
+def _instance_re(snake: str) -> re.Pattern[str]:
+ return re.compile(rf"^{re.escape(snake)}(?:[_.-]?\d{{1,3}})?$")
+
+
+def match_parts(plan_parts: list[PartPlan], measured: list[PartMeasure]) -> tuple[dict[str, list[PartMeasure]], list[PartMeasure]]:
+ """Map each plan part → measured rows (``Name``, ``Name_0``… accepted); plus unmatched rows."""
+ remaining = {m.name: m for m in measured}
+ matched: dict[str, list[PartMeasure]] = {}
+ for pp in plan_parts:
+ pat = _instance_re(to_snake(pp.name))
+ hits = [m for n, m in list(remaining.items()) if pat.match(to_snake(n))]
+ for m in hits:
+ remaining.pop(m.name, None)
+ matched[pp.name] = hits
+ return matched, list(remaining.values())
+
+
+@dataclass
+class _BoxDelta:
+ center: np.ndarray
+ extents: np.ndarray
+ tol: np.ndarray
+
+ @property
+ def worst_ratio(self) -> float:
+ return float(np.max(np.maximum(np.abs(self.center), np.abs(self.extents)) / self.tol))
+
+
+def _box_delta(meas_min: np.ndarray, meas_max: np.ndarray, plan: BBox, tol_m: float) -> _BoxDelta:
+ p_ext = np.asarray(plan.extents, dtype=float)
+ p_ctr = np.asarray(plan.center, dtype=float)
+ tol = np.maximum(tol_m, REL_TOL * p_ext)
+ m_ext = meas_max - meas_min
+ m_ctr = (meas_max + meas_min) / 2
+ return _BoxDelta(center=m_ctr - p_ctr, extents=m_ext - p_ext, tol=tol)
+
+
+def _fmt_delta(v: np.ndarray) -> str:
+ return ", ".join(f"{a}{d * 100:+.1f}cm" for a, d in zip(_AXES, v, strict=True))
+
+
+def _fmt_ext(v) -> str:
+ return "×".join(f"{float(x) * 100:.1f}" for x in v)
+
+
+def _box_findings(target: str, d: _BoxDelta, plan: BBox, *, what: str, check_center: bool = True) -> list[GateFinding]:
+ """WARN/ERROR findings for one box comparison (empty when within tolerance)."""
+ out: list[GateFinding] = []
+ ext_bad = np.abs(d.extents) > d.tol
+ ctr_bad = check_center and np.any(np.abs(d.center) > d.tol)
+ if not ext_bad.any() and not ctr_bad:
+ return out
+ ratio = d.worst_ratio if check_center else float(np.max(np.abs(d.extents) / d.tol))
+ sev = Severity.ERROR if ratio > ERROR_FACTOR else Severity.WARN
+ bits = []
+ if ext_bad.any():
+ bits.append(f"size {_fmt_ext(np.asarray(plan.extents) + d.extents)} vs planned {_fmt_ext(plan.extents)} cm (Δ {_fmt_delta(d.extents)})")
+ if ctr_bad:
+ bits.append(f"centre off by ({_fmt_delta(d.center)})")
+ hint = f"{what}: " + ("; ".join(bits))
+ out.append(GateFinding(
+ gate=GATE, severity=sev, target=target,
+ message=f"{what} bbox deviates from the plan (worst {ratio:.1f}× tolerance)",
+ fix_hint=hint + f"; planned centre ({', '.join(f'{c:.3f}' for c in plan.center)}) m in the GLB frame (Y-up)",
+ data={"delta_center_m": d.center.tolist(), "delta_extents_m": d.extents.tolist(), "tol_m": d.tol.tolist()},
+ ))
+ return out
+
+
+# --------------------------------------------------------------------------- gate
+def _check_object_plan(m: Measurement, plan: StaticPlan, language: str, tol_m: float) -> list[GateFinding]:
+ findings: list[GateFinding] = []
+ matched, extra = match_parts(plan.parts, m.parts)
+ for pp in plan.parts:
+ rows = matched[pp.name]
+ target = pp.name
+ if not rows:
+ findings.append(GateFinding(
+ gate=GATE, severity=Severity.ERROR, target=target,
+ message=f"plan part '{pp.name}' is missing from the GLB",
+ fix_hint=f"create a part named exactly '{pp.name}'" + (f" (×{pp.instances} as {pp.name}_0..{pp.instances - 1})" if pp.instances > 1 else "")
+ + f" — {pp.role}; planned size {_fmt_ext(pp.bbox.extents)} cm",
+ data={"expected_instances": pp.instances},
+ ))
+ continue
+ box = plan_bbox_to_glb(pp.bbox, language)
+ if pp.instances > 1 and len(rows) != pp.instances:
+ findings.append(GateFinding(
+ gate=GATE, severity=Severity.WARN, target=target,
+ message=f"'{pp.name}': found {len(rows)} instance(s), plan asks for {pp.instances}",
+ fix_hint=f"name the copies {pp.name}_0 .. {pp.name}_{pp.instances - 1}",
+ data={"found": len(rows), "expected": pp.instances},
+ ))
+ if len(rows) == 1 and pp.instances == 1:
+ d = _box_delta(np.asarray(rows[0].bbox_min), np.asarray(rows[0].bbox_max), box, tol_m)
+ findings.extend(_box_findings(target, d, box, what=f"part '{pp.name}'"))
+ else:
+ # instances: each copy should have the planned extents; the centre is unknowable
+ per = [_box_delta(np.asarray(r.bbox_min), np.asarray(r.bbox_max), box, tol_m) for r in rows]
+ union = _box_delta(np.min([r.bbox_min for r in rows], axis=0), np.max([r.bbox_max for r in rows], axis=0), box, tol_m)
+ worst_each = max(per, key=lambda d: float(np.max(np.abs(d.extents) / d.tol)))
+ # accept whichever reading (per-instance or union) fits the plan better
+ if float(np.max(np.abs(union.extents) / union.tol)) < float(np.max(np.abs(worst_each.extents) / worst_each.tol)):
+ findings.extend(_box_findings(target, union, box, what=f"'{pp.name}' (all instances)", check_center=False))
+ else:
+ findings.extend(_box_findings(target, worst_each, box, what=f"'{pp.name}' (each instance)", check_center=False))
+ # overall bbox
+ ob = plan_bbox_to_glb(plan.overall_bbox, language)
+ d = _box_delta(np.asarray(m.bbox_min), np.asarray(m.bbox_max), ob, tol_m)
+ findings.extend(_box_findings("overall", d, ob, what="overall"))
+ # ground + footprint
+ if abs(m.ground_gap_m) > tol_m:
+ where = "above" if m.ground_gap_m > 0 else "below"
+ findings.append(GateFinding(
+ gate=GATE, severity=Severity.WARN if abs(m.ground_gap_m) <= ERROR_FACTOR * tol_m else Severity.ERROR,
+ target="overall", message=f"object floats {abs(m.ground_gap_m) * 1000:.1f} mm {where} the ground",
+ fix_hint=f"translate everything by {-m.ground_gap_m:+.4f} m along the up axis so the lowest point is at 0",
+ data={"ground_gap_m": m.ground_gap_m},
+ ))
+ if m.footprint_offset_m > max(tol_m, REL_TOL * max(m.extents[0], m.extents[2], 1e-9)):
+ findings.append(GateFinding(
+ gate=GATE, severity=Severity.WARN, target="overall",
+ message=f"footprint centre is {m.footprint_offset_m * 100:.1f} cm off the up axis",
+ fix_hint=f"translate everything by ({-m.center[0]:+.3f}, 0, {-m.center[2]:+.3f}) m (GLB frame) to centre the footprint",
+ data={"footprint_offset_m": m.footprint_offset_m},
+ ))
+ for r in extra:
+ findings.append(GateFinding(gate=GATE, severity=Severity.INFO, target=r.name,
+ message=f"GLB part '{r.name}' is not in the plan ({_fmt_ext(np.subtract(r.bbox_max, r.bbox_min))} cm)"))
+ return findings
+
+
+def _check_scene_plan(m: Measurement, plan: ScenePlan, language: str, tol_m: float) -> list[GateFinding]:
+ findings: list[GateFinding] = []
+ names = {to_snake(p.name) for p in m.parts}
+ for z in plan.zones:
+ if to_snake(z.name) not in names:
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target=z.name,
+ message=f"zone group '{z.name}' not found in the exported scene",
+ fix_hint=f"put the zone's objects under a THREE.Group named '{z.name}'"))
+ b = plan_bbox_to_glb(plan.bounds, language)
+ lo, hi = np.asarray(b.min), np.asarray(b.max)
+ over = np.maximum(lo - np.asarray(m.bbox_min), 0) + np.maximum(np.asarray(m.bbox_max) - hi, 0)
+ if float(np.max(over)) > max(tol_m, REL_TOL * float(np.max(b.extents))):
+ findings.append(GateFinding(gate=GATE, severity=Severity.WARN, target="bounds",
+ message=f"scene geometry exceeds the planned bounds by {_fmt_delta(over)}",
+ fix_hint=f"keep everything inside centre {b.center}, extents {b.extents} m (GLB frame)",
+ data={"overshoot_m": over.tolist()}))
+ return findings
+
+
+def check_contract(measurement: Measurement, plan: Plan, *, language: str, tol_m: float = BBOX_TOLERANCE_M) -> GateReport:
+ """Compare ``measurement`` (from the GLB) with ``plan`` authored in ``language``'s frame."""
+ t0 = time.time()
+ if isinstance(plan, ScenePlan):
+ findings = _check_scene_plan(measurement, plan, language, tol_m)
+ else:
+ findings = _check_object_plan(measurement, plan, language, tol_m)
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ if passed and not findings:
+ findings.append(GateFinding(gate=GATE, severity=Severity.INFO, message="all plan parts present and within tolerance"))
+ return GateReport(gate=GATE, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse/spatial/cookbook_tool.py b/harness/codeverse/spatial/cookbook_tool.py
new file mode 100644
index 00000000..41733f9e
--- /dev/null
+++ b/harness/codeverse/spatial/cookbook_tool.py
@@ -0,0 +1,125 @@
+"""``read_cookbook`` tool: serve the language cookbook (or a section of it).
+
+Source order: ``prompts/<language>/cookbook.md`` (via ``codeverse.prompts.load_text``)
+→ the runtime's ``contract_doc()`` → a clear "no cookbook" message. Sections
+are markdown headings (``#``…``###``); matching is case-insensitive substring.
+Output is capped at ``MAX_CHARS`` and always lists the available sections.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+from pydantic import BaseModel, Field
+
+from codeverse.spatial.observe import truncate
+from codeverse.spatial.registry import Observation, ToolContext, tool
+from codeverse.spatial.tool_common import ToolUnavailable, language_of, lazy
+
+MAX_CHARS = 6000
+_HEADING = re.compile(r"^(#{1,3})\s+(.+?)\s*$", re.MULTILINE)
+_FENCE = re.compile(r"^(`{3,}|~{3,}).*?^\1[ \t]*$", re.MULTILINE | re.DOTALL)
+
+#: prompts/<dir> per language id (urdf_blender's docs live under prompts/urdf)
+_PROMPT_DIR = {"urdf_blender": "urdf"}
+
+
+@dataclass
+class Section:
+ level: int
+ title: str
+ body: str # heading line included
+
+
+def _heading_matches(md: str) -> list[re.Match[str]]:
+ """Headings outside fenced code blocks (``# comment`` lines in snippets are not headings)."""
+ out: list[re.Match[str]] = []
+ fence_spans: list[tuple[int, int]] = []
+ for m in _FENCE.finditer(md):
+ fence_spans.append((m.start(), m.end()))
+ for m in _HEADING.finditer(md):
+ if not any(a <= m.start() < b for a, b in fence_spans):
+ out.append(m)
+ return out
+
+
+def split_sections(md: str) -> list[Section]:
+ """Split markdown into heading-delimited sections (text before the first heading is 'preamble')."""
+ matches = _heading_matches(md)
+ if not matches:
+ return [Section(0, "preamble", md)]
+ out: list[Section] = []
+ if matches[0].start() > 0 and md[: matches[0].start()].strip():
+ out.append(Section(0, "preamble", md[: matches[0].start()]))
+ for i, m in enumerate(matches):
+ end = matches[i + 1].start() if i + 1 < len(matches) else len(md)
+ out.append(Section(len(m.group(1)), m.group(2), md[m.start(): end]))
+ return out
+
+
+def find_section(sections: list[Section], query: str) -> Section | None:
+ """Case-insensitive match: exact title first, then substring, then word overlap."""
+ q = query.strip().lower()
+ if not q:
+ return None
+ for s in sections:
+ if s.title.lower() == q:
+ return s
+ for s in sections:
+ if q in s.title.lower():
+ return s
+ words = set(re.findall(r"[a-z0-9]+", q))
+ best, best_n = None, 0
+ for s in sections:
+ n = len(words & set(re.findall(r"[a-z0-9]+", s.title.lower())))
+ if n > best_n:
+ best, best_n = s, n
+ return best
+
+
+def load_cookbook(language: str) -> tuple[str, str]:
+ """(markdown, source) for ``language``; raises ToolUnavailable when nothing exists."""
+ rel = f"{_PROMPT_DIR.get(language, language)}/cookbook.md"
+ try:
+ load_text = lazy("codeverse.prompts", "load_text")
+ return load_text(rel), f"prompts/{rel}"
+ except (ToolUnavailable, FileNotFoundError):
+ pass
+ try:
+ get_runtime = lazy("codeverse.languages", "get_runtime")
+ doc = get_runtime(language).contract_doc()
+ if doc and doc.strip():
+ return doc, f"{language} runtime contract_doc()"
+ except Exception as e: # runtime missing / contract missing
+ raise ToolUnavailable(f"no cookbook for {language}: {type(e).__name__}: {e}") from e
+ raise ToolUnavailable(f"no cookbook or contract doc for {language}")
+
+
+class ReadCookbookArgs(BaseModel):
+ section: str = Field(default="", description="heading to return (case-insensitive substring); empty = whole cookbook (truncated)")
+
+
+@tool("read_cookbook", ReadCookbookArgs, "Read the language cookbook (copyable snippets, pitfalls, export contract) — whole or one section.")
+def read_cookbook(ctx: ToolContext, args: ReadCookbookArgs) -> Observation:
+ language = language_of(ctx)
+ try:
+ md, source = load_cookbook(language)
+ except ToolUnavailable as e:
+ return Observation.error(f"read_cookbook: {e}")
+ sections = split_sections(md)
+ titles = [s.title for s in sections if s.level > 0]
+ listing = "sections: " + (" | ".join(titles) if titles else "(no headings)")
+ if args.section:
+ sec = find_section(sections, args.section)
+ if sec is None:
+ return Observation.error(f"no section matching {args.section!r} in {source}\n{listing}",
+ available=titles)
+ body = sec.body
+ head = f"[{source} › {sec.title}]"
+ else:
+ body = md
+ head = f"[{source}]"
+ text = f"{head}\n{truncate(body, MAX_CHARS, tail_ratio=0.1)}\n\n{listing}"
+ return Observation(ok=True, text=text, numbers={"source": source, "chars": len(body), "sections": titles[:60],
+ "truncated": len(body) > MAX_CHARS})
diff --git a/harness/codeverse/spatial/joints.py b/harness/codeverse/spatial/joints.py
new file mode 100644
index 00000000..5e7c6fc0
--- /dev/null
+++ b/harness/codeverse/spatial/joints.py
@@ -0,0 +1,51 @@
+"""Articulation tools on URDF robots (package E facade).
+
+Import from here::
+
+ from codeverse.spatial.joints import load_urdf, fk, pose_samples, sweep_collisions, urdf_to_glb
+
+* :mod:`codeverse.spatial.joints_model` — ``Robot``/``Link``/``Joint``, ``load_urdf``,
+ ``fk``, ``pose_samples``, ``limit_poses``, URDF frame math.
+* :mod:`codeverse.spatial.joints_sweep` — ``sweep_collisions`` (FCL + trimesh),
+ ``sweep_findings`` (→ GateFindings), ``motion_direction_check``.
+* :mod:`codeverse.spatial.joints_export` — ``urdf_to_glb`` (hierarchical GLB with joint
+ extras), ``render_poses`` (+ ``articulation_sheet.png``), ``joint_sweep_observation``.
+"""
+
+from codeverse.spatial.joints_export import (
+ ARTICULATION_SHEET_NAME,
+ ZUP_TO_YUP,
+ blender_render_glb,
+ joint_sweep_observation,
+ render_poses,
+ robot_scene,
+ urdf_to_glb,
+)
+from codeverse.spatial.joints_model import (
+ Joint,
+ Link,
+ Robot,
+ UrdfError,
+ fk,
+ link_world_meshes,
+ load_urdf,
+ world_bboxes,
+)
+from codeverse.spatial.joints_poses import limit_poses, pose_label, pose_samples
+from codeverse.spatial.joints_sweep import (
+ MotionCheck,
+ Overlap,
+ SweepReport,
+ SweepSummary,
+ motion_direction_check,
+ summary_text,
+ sweep_collisions,
+ sweep_findings,
+)
+
+__all__ = [
+ "ARTICULATION_SHEET_NAME", "ZUP_TO_YUP", "Joint", "Link", "MotionCheck", "Overlap", "Robot", "SweepReport",
+ "SweepSummary", "UrdfError", "blender_render_glb", "fk", "joint_sweep_observation", "limit_poses",
+ "link_world_meshes", "load_urdf", "motion_direction_check", "pose_label", "pose_samples", "render_poses",
+ "robot_scene", "summary_text", "sweep_collisions", "sweep_findings", "urdf_to_glb", "world_bboxes",
+]
diff --git a/harness/codeverse/spatial/joints_export.py b/harness/codeverse/spatial/joints_export.py
new file mode 100644
index 00000000..2b013cb5
--- /dev/null
+++ b/harness/codeverse/spatial/joints_export.py
@@ -0,0 +1,231 @@
+"""Export a posed :class:`Robot` to the canonical GLB (node hierarchy mirroring
+links, joint extras) and render articulation sheets.
+
+GLB convention: Y-up, +Z front (``codeverse.conventions.GLB_FRAME``). The
+URDF world (Z-up, -Y front) is rotated by ``Rx(-90°)`` at the ``<robot name>``
+node; every link is a child node (name = link name) whose local matrix is the
+joint transform ``T_origin · Motion(q)``; geometry lives in the link frame.
+Non-root link nodes carry ``extras.joint`` and the scene carries
+``extras.joints / links / pose`` (same keys as the owner's dataset builder).
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import subprocess
+import sys
+import time
+from collections.abc import Callable, Sequence
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import trimesh
+
+from codeverse.contracts.artifacts import RenderSet, RenderView
+from codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPreset
+from codeverse.spatial.joints_model import Joint, Robot, UrdfError, fk
+from codeverse.spatial.joints_poses import limit_poses
+
+ARTICULATION_SHEET_NAME = "articulation_sheet.png"
+#: URDF (Z-up, -Y front) → glTF (Y-up, +Z front): (x, y, z) → (x, z, -y)
+ZUP_TO_YUP = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]], dtype=float)
+YUP_TO_ZUP = ZUP_TO_YUP.T.copy()
+
+Renderer = Callable[..., RenderSet]
+
+
+def joint_extras(j: Joint) -> dict[str, Any]:
+ return {
+ "name": j.name, "type": j.type, "axis": [float(v) for v in j.axis],
+ "lower": j.lower if j.lower is not None else 0.0, "upper": j.upper if j.upper is not None else 0.0,
+ "effort": j.effort, "velocity": j.velocity, "parent": j.parent, "child": j.child,
+ "origin_xyz": [float(v) for v in j.origin[:3, 3]],
+ }
+
+
+def robot_scene(robot: Robot, pose: dict[str, float] | None = None, *, joint_extras_on: bool = True) -> trimesh.Scene:
+ """Build the trimesh.Scene (hierarchical, Y-up) for ``robot`` at ``pose``."""
+ pose = pose or {}
+ T = fk(robot, pose) # validates joint names
+ scene = trimesh.Scene()
+ robot_node = robot.name or "robot"
+ meta = {"links": robot.link_order(), "frame": "y_up_pos_z_front", "pose": dict(pose), "units": "meters"}
+ if joint_extras_on:
+ meta["joints"] = [joint_extras(j) for j in robot.joints.values()]
+ scene.graph.update(frame_to=robot_node, frame_from=scene.graph.base_frame, matrix=ZUP_TO_YUP,
+ metadata=meta if joint_extras_on else None)
+ for name in robot.link_order():
+ link = robot.links[name]
+ j = robot.parent_joint(name)
+ if j is None:
+ parent_node, local = robot_node, np.eye(4)
+ else:
+ parent_node, local = j.parent, j.origin @ j.motion(float(pose.get(j.name, 0.0)))
+ extras = {"joint": joint_extras(j)} if (j is not None and joint_extras_on) else None
+ pieces = link.submeshes or ([link.mesh] if link.mesh is not None else [])
+ if len(pieces) == 1:
+ scene.add_geometry(pieces[0].copy(), node_name=name, geom_name=name, parent_node_name=parent_node,
+ transform=local, metadata=extras)
+ else: # several materials: link node + one geometry child per piece (names stay unique)
+ scene.graph.update(frame_to=name, frame_from=parent_node, matrix=local, metadata=extras)
+ for i, piece in enumerate(pieces):
+ scene.add_geometry(piece.copy(), node_name=f"{name}__{i}", geom_name=f"{name}__{i}", parent_node_name=name,
+ transform=np.eye(4))
+ scene.metadata.update(meta)
+ del T
+ return scene
+
+
+def urdf_to_glb(robot: Robot, out_glb: Path | str, pose: dict[str, float] | None = None, *, joint_extras: bool = True) -> Path:
+ """Write the canonical hierarchical GLB for ``robot`` at ``pose`` (default rest)."""
+ out = Path(out_glb)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ scene = robot_scene(robot, pose, joint_extras_on=joint_extras)
+ out.write_bytes(scene.export(file_type="glb"))
+ return out
+
+
+# ------------------------------------------------------------------ rendering
+def _default_renderer() -> Renderer:
+ """``codeverse.spatial.render.render_glb`` when available, else the Blender fallback."""
+ try:
+ from codeverse.spatial.render import render_glb # package C1
+
+ return render_glb
+ except Exception:
+ return blender_render_glb
+
+
+def blender_render_glb(glb: Path, out_dir: Path, *, views: Sequence[ViewPreset] | None = None, width: int = 512,
+ height: int = 512, sheet: bool = False, timeout_s: int = 180, **_: Any) -> RenderSet:
+ """Minimal headless-Blender (Workbench) renderer used when the GPU renderer
+ (package C1) is not importable. Same signature subset as ``render_glb``."""
+ from codeverse.config import get_settings
+
+ blender = get_settings().resolve_blender()
+ if not blender:
+ raise RuntimeError("no Blender binary found for the fallback renderer")
+ views = tuple(views or OBJECT_VIEWS_QUICK)
+ out_dir = Path(out_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ script = Path(__file__).resolve().parent.parent / "languages" / "urdf" / "wrappers" / "render_glb_bpy.py"
+ spec = {"glb": str(glb), "out_dir": str(out_dir), "width": width, "height": height,
+ "views": [{"name": v.name, "az": v.azimuth_deg, "el": v.elevation_deg} for v in views]}
+ spec_path = out_dir / "_render_spec.json"
+ spec_path.write_text(json.dumps(spec))
+ t0 = time.time()
+ cmd = [blender, "-b", "--factory-startup", "--python", str(script), "--", str(spec_path)]
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout_s, start_new_session=True)
+ if proc.returncode != 0:
+ raise RuntimeError(f"blender fallback render failed: {proc.stderr[-2000:] or proc.stdout[-2000:]}")
+ rs = RenderSet(renderer="blender-workbench", duration_ms=int((time.time() - t0) * 1000))
+ for v in views:
+ p = out_dir / f"view_{v.name}.png"
+ if not p.is_file():
+ raise RuntimeError(f"blender fallback render produced no {p.name}; stdout tail: {proc.stdout[-800:]}")
+ rs.views.append(RenderView(name=v.name, path=str(p), width=width, height=height))
+ if sheet:
+ rs.contact_sheet = str(make_sheet([(v.name, Path(v.path)) for v in rs.views], out_dir / "sheet.png"))
+ return rs
+
+
+def make_sheet(images: list[tuple[str, Path]], out: Path, *, cols: int = 4, tile: int = 384) -> Path:
+ """Labelled grid of PNGs (PIL only; stand-in for ``codeverse.spatial.sheet.contact_sheet``)."""
+ from PIL import Image, ImageDraw
+
+ if not images:
+ raise ValueError("make_sheet: no images")
+ cols = max(1, min(cols, len(images)))
+ rows = math.ceil(len(images) / cols)
+ label_h = 22
+ sheet = Image.new("RGB", (cols * tile, rows * (tile + label_h)), "white")
+ draw = ImageDraw.Draw(sheet)
+ for i, (label, path) in enumerate(images):
+ im = Image.open(path).convert("RGB")
+ im.thumbnail((tile, tile))
+ x, y = (i % cols) * tile, (i // cols) * (tile + label_h)
+ sheet.paste(im, (x + (tile - im.width) // 2, y + label_h + (tile - im.height) // 2))
+ draw.rectangle([x, y, x + tile - 1, y + label_h - 1], fill=(30, 30, 30))
+ draw.text((x + 6, y + 4), label[:60], fill="white")
+ out.parent.mkdir(parents=True, exist_ok=True)
+ sheet.save(out)
+ return out
+
+
+def render_poses(
+ robot: Robot,
+ out_dir: Path | str,
+ poses: list[tuple[str, dict[str, float]]] | None = None,
+ *,
+ renderer: Renderer | None = None,
+ views: Sequence[ViewPreset] | None = None,
+ width: int = 512,
+ height: int = 512,
+ sheet_view: str | None = None,
+) -> list[tuple[str, RenderSet]]:
+ """Export one GLB per pose, render ``views`` for each (default: 3 quick views)
+ and write ``out_dir/articulation_sheet.png`` (rest / each joint at lower & upper
+ by default — the image the judge sees). Returns ``[(pose_name, RenderSet)]``."""
+ out_dir = Path(out_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ poses = poses if poses is not None else limit_poses(robot)
+ views = tuple(views or OBJECT_VIEWS_QUICK[:3])
+ render = renderer or _default_renderer()
+ results: list[tuple[str, RenderSet]] = []
+ tiles: list[tuple[str, Path]] = []
+ for label, q in poses:
+ safe = "".join(c if c.isalnum() or c in "-_@." else "_" for c in label)
+ glb = urdf_to_glb(robot, out_dir / f"pose_{safe}.glb", q)
+ rs = render(glb, out_dir / f"pose_{safe}", views=views, width=width, height=height, sheet=False)
+ results.append((label, rs))
+ for v in rs.views:
+ if sheet_view is None or v.name == sheet_view:
+ tiles.append((f"{label} · {v.name}", Path(v.path)))
+ make_sheet(tiles, out_dir / ARTICULATION_SHEET_NAME, cols=len(views) if sheet_view is None else 4)
+ return results
+
+
+# ------------------------------------------------------------------ tool-shaped entry point
+def joint_sweep_observation(ws, *, n_random: int = 8, seed: int = 0, render: bool = True, out_dir: Path | None = None,
+ joint: str | None = None, expected_direction: str | None = None):
+ """Run the pose sweep on ``ws.artifacts/robot.urdf`` (+ ``meshes/``) and return an
+ ``Observation`` (package F wraps this as the ``joint_sweep`` tool)."""
+ from codeverse.spatial.joints_model import load_urdf
+ from codeverse.spatial.joints_poses import pose_samples
+ from codeverse.spatial.joints_sweep import (
+ motion_direction_check,
+ report_numbers,
+ summary_text,
+ sweep_collisions,
+ )
+ from codeverse.spatial.registry import Observation
+
+ urdf = Path(ws.artifacts) / "robot.urdf"
+ if not urdf.is_file():
+ return Observation.error("joint_sweep: artifacts/robot.urdf not found — run `build` first")
+ try:
+ robot = load_urdf(urdf, Path(ws.artifacts) / "meshes")
+ report = sweep_collisions(robot, pose_samples(robot, n_random=n_random, seed=seed))
+ except UrdfError as e:
+ return Observation.error(f"joint_sweep: {e}")
+ text = summary_text(report)
+ numbers = report_numbers(report)
+ if joint and expected_direction:
+ mc = motion_direction_check(robot, joint, expected_direction)
+ text += "\n" + mc.message
+ numbers["motion_check"] = mc.model_dump(mode="json")
+ images: list[str] = []
+ if render:
+ d = Path(out_dir) if out_dir else Path(ws.artifacts) / "tool_scratch" / "joint_sweep"
+ render_poses(robot, d)
+ images.append(str(d / ARTICULATION_SHEET_NAME))
+ ok = report.summary.max_penetration_m <= report.tol_m and not report.summary.floating_links
+ return Observation(ok=ok, text=text, numbers=numbers, images=images)
+
+
+if __name__ == "__main__": # tiny manual CLI: python -m codeverse.spatial.joints_export robot.urdf out.glb
+ from codeverse.spatial.joints_model import load_urdf
+
+ urdf_to_glb(load_urdf(sys.argv[1]), sys.argv[2])
diff --git a/harness/codeverse/spatial/joints_model.py b/harness/codeverse/spatial/joints_model.py
new file mode 100644
index 00000000..93a8274a
--- /dev/null
+++ b/harness/codeverse/spatial/joints_model.py
@@ -0,0 +1,394 @@
+"""URDF data model + loader + forward kinematics (numpy, trimesh).
+
+Conventions (see ``codeverse/languages/urdf/CONTRACT.md``):
+
+* URDF frames are Z-up, -Y front, meters. ``<origin xyz rpy>`` uses the URDF
+ rotation order ``R = Rz(yaw) · Ry(pitch) · Rx(roll)``.
+* A joint's ``<origin>`` places the joint frame in the PARENT link frame; the
+ child link frame coincides with the joint frame at ``q = 0``; ``<axis>`` is
+ expressed in the joint frame. ``T_child = T_parent · T_origin · Motion(q)``.
+* Mesh files referenced by ``<mesh filename>`` are taken in RAW coordinates
+ (standard URDF semantics). Our wrapper writes ``meshes/<link>.glb`` with
+ vertices in URDF (Z-up) coordinates (``export_yup=False``), so no axis
+ conversion happens on load. ``Link.mesh`` is stored in the LINK frame (the
+ visual origin is already applied).
+"""
+
+from __future__ import annotations
+
+import math
+import xml.etree.ElementTree as ET
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import numpy as np
+import trimesh
+
+MOVABLE_TYPES = ("revolute", "prismatic", "continuous")
+JOINT_TYPES = MOVABLE_TYPES + ("fixed",)
+
+
+class UrdfError(ValueError):
+ """Raised when a URDF cannot be turned into a kinematic tree (use lint for details)."""
+
+
+# ------------------------------------------------------------------ small math
+def parse_floats(text: str | None, n: int, what: str) -> tuple[float, ...]:
+ """Parse ``"a b c"`` → floats; raises ``UrdfError`` with ``what`` on bad input."""
+ parts = (text or "").split()
+ if len(parts) != n:
+ raise UrdfError(f"{what}: expected {n} numbers, got {text!r}")
+ try:
+ return tuple(float(p) for p in parts)
+ except ValueError as e:
+ raise UrdfError(f"{what}: not numeric: {text!r}") from e
+
+
+def rpy_to_matrix(rpy: tuple[float, float, float] | np.ndarray) -> np.ndarray:
+ """URDF fixed-axis roll/pitch/yaw → 3x3 rotation (Rz·Ry·Rx)."""
+ r, p, y = (float(v) for v in rpy)
+ cr, sr, cp, sp, cy, sy = math.cos(r), math.sin(r), math.cos(p), math.sin(p), math.cos(y), math.sin(y)
+ rx = np.array([[1, 0, 0], [0, cr, -sr], [0, sr, cr]])
+ ry = np.array([[cp, 0, sp], [0, 1, 0], [-sp, 0, cp]])
+ rz = np.array([[cy, -sy, 0], [sy, cy, 0], [0, 0, 1]])
+ return rz @ ry @ rx
+
+
+def matrix_to_rpy(R: np.ndarray) -> tuple[float, float, float]:
+ """Inverse of :func:`rpy_to_matrix` (pitch in (-pi/2, pi/2) branch)."""
+ sy = -R[2, 0]
+ sy = max(-1.0, min(1.0, float(sy)))
+ pitch = math.asin(sy)
+ if abs(math.cos(pitch)) < 1e-9: # gimbal lock: fold yaw into roll
+ roll = math.atan2(-R[1, 2], R[1, 1])
+ yaw = 0.0
+ else:
+ roll = math.atan2(R[2, 1], R[2, 2])
+ yaw = math.atan2(R[1, 0], R[0, 0])
+ return (roll, pitch, yaw)
+
+
+def make_transform(xyz=(0.0, 0.0, 0.0), rpy=(0.0, 0.0, 0.0)) -> np.ndarray:
+ T = np.eye(4)
+ T[:3, :3] = rpy_to_matrix(rpy)
+ T[:3, 3] = np.asarray(xyz, dtype=float)
+ return T
+
+
+def invert_transform(T: np.ndarray) -> np.ndarray:
+ R = T[:3, :3]
+ out = np.eye(4)
+ out[:3, :3] = R.T
+ out[:3, 3] = -R.T @ T[:3, 3]
+ return out
+
+
+def rotation_about_axis(axis: np.ndarray, angle: float) -> np.ndarray:
+ """Rodrigues rotation matrix (axis must be unit)."""
+ x, y, z = (float(v) for v in axis)
+ c, s, C = math.cos(angle), math.sin(angle), 1.0 - math.cos(angle)
+ return np.array(
+ [
+ [c + x * x * C, x * y * C - z * s, x * z * C + y * s],
+ [y * x * C + z * s, c + y * y * C, y * z * C - x * s],
+ [z * x * C - y * s, z * y * C + x * s, c + z * z * C],
+ ]
+ )
+
+
+def parse_origin(elem: ET.Element | None, what: str) -> np.ndarray:
+ """``<origin xyz rpy>`` child of ``elem`` → 4x4 (identity when absent)."""
+ if elem is None:
+ return np.eye(4)
+ o = elem.find("origin")
+ if o is None:
+ return np.eye(4)
+ xyz = parse_floats(o.get("xyz"), 3, f"{what} origin xyz") if o.get("xyz") is not None else (0.0, 0.0, 0.0)
+ rpy = parse_floats(o.get("rpy"), 3, f"{what} origin rpy") if o.get("rpy") is not None else (0.0, 0.0, 0.0)
+ return make_transform(xyz, rpy)
+
+
+# ------------------------------------------------------------------ model
+@dataclass
+class Joint:
+ name: str
+ type: str
+ parent: str
+ child: str
+ origin: np.ndarray = field(default_factory=lambda: np.eye(4)) # joint frame in parent frame
+ axis: np.ndarray = field(default_factory=lambda: np.array([1.0, 0.0, 0.0])) # unit, joint frame
+ lower: float | None = None
+ upper: float | None = None
+ effort: float = 0.0
+ velocity: float = 0.0
+
+ @property
+ def movable(self) -> bool:
+ return self.type in MOVABLE_TYPES
+
+ def motion(self, q: float) -> np.ndarray:
+ """Local motion transform for joint value ``q`` (identity for fixed)."""
+ T = np.eye(4)
+ if self.type in ("revolute", "continuous"):
+ T[:3, :3] = rotation_about_axis(self.axis, q)
+ elif self.type == "prismatic":
+ T[:3, 3] = self.axis * q
+ return T
+
+ def clamp(self, q: float) -> float:
+ if self.type in ("revolute", "prismatic") and self.lower is not None and self.upper is not None:
+ return min(max(q, self.lower), self.upper)
+ return q
+
+
+@dataclass
+class Link:
+ name: str
+ mesh: trimesh.Trimesh | None = None # merged, in LINK frame (visual origin applied) — used for QC
+ submeshes: list[trimesh.Trimesh] = field(default_factory=list) # per-material pieces, LINK frame — used for export
+ visual_origin: np.ndarray = field(default_factory=lambda: np.eye(4))
+ mesh_file: str | None = None
+ has_collision: bool = False
+
+ @property
+ def tri_count(self) -> int:
+ return 0 if self.mesh is None else int(len(self.mesh.faces))
+
+
+@dataclass
+class Robot:
+ name: str
+ links: dict[str, Link]
+ joints: dict[str, Joint]
+ root: str
+ urdf_path: str = ""
+
+ # -------------------------------------------------------------- topology
+ def parent_joint(self, link: str) -> Joint | None:
+ for j in self.joints.values():
+ if j.child == link:
+ return j
+ return None
+
+ def child_joints(self, link: str) -> list[Joint]:
+ return [j for j in self.joints.values() if j.parent == link]
+
+ def movable_joints(self) -> list[Joint]:
+ return [j for j in self.joints.values() if j.movable]
+
+ def link_order(self) -> list[str]:
+ """Links in parent-before-child order (DFS from root)."""
+ out: list[str] = []
+ stack = [self.root]
+ while stack:
+ cur = stack.pop()
+ out.append(cur)
+ stack.extend(j.child for j in reversed(self.child_joints(cur)))
+ return out
+
+ def chain(self, link: str) -> list[Joint]:
+ """Joints from the root down to ``link`` (empty for the root)."""
+ chain: list[Joint] = []
+ cur = link
+ while cur != self.root:
+ j = self.parent_joint(cur)
+ if j is None:
+ raise UrdfError(f"link {link!r} is not connected to root {self.root!r}")
+ chain.append(j)
+ cur = j.parent
+ return list(reversed(chain))
+
+ def meshed_links(self) -> list[str]:
+ return [n for n, link in self.links.items() if link.mesh is not None]
+
+
+# ------------------------------------------------------------------ parsing
+def _primitive_mesh(geom: ET.Element, what: str) -> trimesh.Trimesh:
+ if (b := geom.find("box")) is not None:
+ return trimesh.creation.box(parse_floats(b.get("size"), 3, f"{what} box size"))
+ if (c := geom.find("cylinder")) is not None:
+ return trimesh.creation.cylinder(radius=float(c.get("radius", 0)), height=float(c.get("length", 0)))
+ if (s := geom.find("sphere")) is not None:
+ return trimesh.creation.icosphere(subdivisions=3, radius=float(s.get("radius", 0)))
+ raise UrdfError(f"{what}: unsupported geometry {[e.tag for e in geom]}")
+
+
+def _load_mesh_file(filename: str, urdf_dir: Path, meshes_dir: Path | None, scale: tuple[float, ...] | None) -> list[trimesh.Trimesh]:
+ """Load a mesh file as a list of per-material sub-meshes (transforms baked, raw coords)."""
+ candidates = []
+ fn = filename.replace("package://", "").replace("file://", "")
+ if meshes_dir is not None:
+ candidates.append(meshes_dir / Path(fn).name)
+ candidates.append(meshes_dir.parent / fn)
+ candidates.append(urdf_dir / fn)
+ candidates.append(Path(fn))
+ for p in candidates:
+ if p.is_file():
+ loaded = trimesh.load(p)
+ subs = loaded.dump() if isinstance(loaded, trimesh.Scene) else [loaded]
+ subs = [m for m in subs if isinstance(m, trimesh.Trimesh) and len(m.faces) > 0]
+ if not subs:
+ raise UrdfError(f"mesh {p} has no triangles")
+ for m in subs:
+ if scale is not None and any(abs(s - 1.0) > 1e-12 for s in scale):
+ m.apply_scale(scale)
+ return subs
+ raise UrdfError(f"mesh file not found: {filename!r} (tried {[str(c) for c in candidates]})")
+
+
+def _link_from_xml(el: ET.Element, urdf_dir: Path, meshes_dir: Path | None, *, load_meshes: bool) -> Link:
+ name = el.get("name", "")
+ link = Link(name=name, has_collision=el.find("collision") is not None)
+ parts: list[trimesh.Trimesh] = []
+ first_origin: np.ndarray | None = None
+ for vis in el.findall("visual"):
+ T_vis = parse_origin(vis, f"link {name} visual")
+ geom = vis.find("geometry")
+ if geom is None:
+ raise UrdfError(f"link {name}: visual without <geometry>")
+ if first_origin is None:
+ first_origin = T_vis
+ mesh_el = geom.find("mesh")
+ if mesh_el is not None:
+ link.mesh_file = mesh_el.get("filename", "")
+ if not load_meshes:
+ continue
+ scale = parse_floats(mesh_el.get("scale"), 3, f"link {name} mesh scale") if mesh_el.get("scale") else None
+ pieces = _load_mesh_file(link.mesh_file, urdf_dir, meshes_dir, scale)
+ else:
+ pieces = [_primitive_mesh(geom, f"link {name}")]
+ for m in pieces:
+ m = m.copy()
+ m.apply_transform(T_vis)
+ parts.append(m)
+ if first_origin is not None:
+ link.visual_origin = first_origin
+ if parts:
+ link.submeshes = parts
+ merged = parts[0].copy() if len(parts) == 1 else trimesh.util.concatenate(parts)
+ # exporters split vertices per normal/uv; merge them back so topology (watertight, islands) is real
+ merged.merge_vertices(merge_tex=True, merge_norm=True)
+ link.mesh = merged
+ return link
+
+
+def _joint_from_xml(el: ET.Element) -> Joint:
+ name = el.get("name", "")
+ jtype = el.get("type", "")
+ if jtype not in JOINT_TYPES:
+ raise UrdfError(f"joint {name}: unsupported type {jtype!r}")
+ parent = el.find("parent")
+ child = el.find("child")
+ if parent is None or child is None or not parent.get("link") or not child.get("link"):
+ raise UrdfError(f"joint {name}: needs <parent link> and <child link>")
+ j = Joint(name=name, type=jtype, parent=parent.get("link", ""), child=child.get("link", ""))
+ j.origin = parse_origin(el, f"joint {name}")
+ ax = el.find("axis")
+ if ax is not None and ax.get("xyz") is not None:
+ a = np.asarray(parse_floats(ax.get("xyz"), 3, f"joint {name} axis"), dtype=float)
+ n = float(np.linalg.norm(a))
+ if n < 1e-9:
+ raise UrdfError(f"joint {name}: zero axis")
+ j.axis = a / n
+ lim = el.find("limit")
+ if lim is not None:
+ j.effort = float(lim.get("effort", 0) or 0)
+ j.velocity = float(lim.get("velocity", 0) or 0)
+ if lim.get("lower") is not None:
+ j.lower = float(lim.get("lower"))
+ if lim.get("upper") is not None:
+ j.upper = float(lim.get("upper"))
+ if jtype in ("revolute", "prismatic"):
+ if j.lower is None or j.upper is None:
+ raise UrdfError(f"joint {name}: {jtype} joints need <limit lower upper>")
+ if j.upper < j.lower:
+ raise UrdfError(f"joint {name}: upper {j.upper} < lower {j.lower}")
+ return j
+
+
+def load_urdf(urdf_path: Path | str, meshes_dir: Path | str | None = None, *, load_meshes: bool = True) -> Robot:
+ """Parse a URDF file into a :class:`Robot` (strict: raises ``UrdfError``).
+
+ ``meshes_dir`` overrides where ``<mesh filename>`` basenames are looked up
+ (default: relative to the URDF file). Mesh coordinates are taken raw.
+ """
+ urdf_path = Path(urdf_path)
+ try:
+ root_el = ET.parse(urdf_path).getroot()
+ except ET.ParseError as e:
+ raise UrdfError(f"{urdf_path.name}: XML parse error: {e}") from e
+ if root_el.tag != "robot":
+ raise UrdfError(f"{urdf_path.name}: root element must be <robot>, got <{root_el.tag}>")
+ meshes = Path(meshes_dir) if meshes_dir is not None else None
+ links = {}
+ for el in root_el.findall("link"):
+ link = _link_from_xml(el, urdf_path.parent, meshes, load_meshes=load_meshes)
+ if link.name in links:
+ raise UrdfError(f"duplicate link name {link.name!r}")
+ links[link.name] = link
+ joints = {}
+ for el in root_el.findall("joint"):
+ j = _joint_from_xml(el)
+ if j.name in joints:
+ raise UrdfError(f"duplicate joint name {j.name!r}")
+ if j.parent not in links or j.child not in links:
+ raise UrdfError(f"joint {j.name}: unknown parent/child link ({j.parent!r}/{j.child!r})")
+ joints[j.name] = j
+ if not links:
+ raise UrdfError("URDF has no links")
+ children = [j.child for j in joints.values()]
+ if len(set(children)) != len(children):
+ dup = sorted({c for c in children if children.count(c) > 1})
+ raise UrdfError(f"links with more than one parent joint: {dup}")
+ roots = [n for n in links if n not in children]
+ if len(roots) != 1:
+ raise UrdfError(f"expected exactly one root link, found {roots}")
+ robot = Robot(name=root_el.get("name", "robot"), links=links, joints=joints, root=roots[0], urdf_path=str(urdf_path))
+ if len(robot.link_order()) != len(links):
+ raise UrdfError("joint graph contains a cycle or unreachable links")
+ return robot
+
+
+# ------------------------------------------------------------------ FK
+def fk(robot: Robot, q: dict[str, float] | None = None, *, clamp: bool = False) -> dict[str, np.ndarray]:
+ """World transform of every link frame for joint values ``q`` (missing → 0)."""
+ q = q or {}
+ unknown = set(q) - set(robot.joints)
+ if unknown:
+ raise UrdfError(f"fk: unknown joints {sorted(unknown)}; known: {sorted(robot.joints)}")
+ out: dict[str, np.ndarray] = {robot.root: np.eye(4)}
+ for name in robot.link_order():
+ if name == robot.root:
+ continue
+ j = robot.parent_joint(name)
+ assert j is not None
+ val = float(q.get(j.name, 0.0))
+ if clamp:
+ val = j.clamp(val)
+ out[name] = out[j.parent] @ j.origin @ j.motion(val)
+ return out
+
+
+def link_world_meshes(robot: Robot, q: dict[str, float] | None = None) -> dict[str, trimesh.Trimesh]:
+ """Posed copies of every link mesh in world coordinates."""
+ T = fk(robot, q)
+ out = {}
+ for name, link in robot.links.items():
+ if link.mesh is None:
+ continue
+ m = link.mesh.copy()
+ m.apply_transform(T[name])
+ out[name] = m
+ return out
+
+
+def world_bboxes(robot: Robot, q: dict[str, float] | None = None) -> dict[str, tuple[np.ndarray, np.ndarray]]:
+ """Per-link world AABB (min, max) at pose ``q``."""
+ T = fk(robot, q)
+ out = {}
+ for name, link in robot.links.items():
+ if link.mesh is None:
+ continue
+ pts = trimesh.transform_points(link.mesh.vertices, T[name])
+ out[name] = (pts.min(axis=0), pts.max(axis=0))
+ return out
diff --git a/harness/codeverse/spatial/joints_poses.py b/harness/codeverse/spatial/joints_poses.py
new file mode 100644
index 00000000..aef4a76c
--- /dev/null
+++ b/harness/codeverse/spatial/joints_poses.py
@@ -0,0 +1,78 @@
+"""Deterministic pose sampling for sweeps and articulation sheets."""
+
+from __future__ import annotations
+
+import math
+
+import numpy as np
+
+from codeverse.spatial.joints_model import Joint, Robot
+
+
+def _joint_values(j: Joint) -> list[float]:
+ if j.type == "continuous":
+ return [0.0, -math.pi / 2, math.pi / 2, math.pi]
+ assert j.lower is not None and j.upper is not None
+ vals = [0.0, j.lower, 0.5 * (j.lower + j.upper), j.upper]
+ out: list[float] = []
+ for v in vals:
+ if all(abs(v - o) > 1e-9 for o in out):
+ out.append(v)
+ return out
+
+
+def pose_samples(robot: Robot, n_random: int = 8, seed: int = 0) -> list[dict[str, float]]:
+ """Deterministic pose set: rest, each joint at lower/mid/upper (others at 0),
+ then ``n_random`` seeded random combinations within limits.
+ Continuous joints sample 0, ±π/2, π and random in [-π, π]."""
+ movable = robot.movable_joints()
+ poses: list[dict[str, float]] = [{}]
+ for j in movable:
+ for v in _joint_values(j):
+ if abs(v) < 1e-12:
+ continue
+ poses.append({j.name: v})
+ rng = np.random.default_rng(seed)
+ for _ in range(n_random if len(movable) > 1 else 0):
+ q: dict[str, float] = {}
+ for j in movable:
+ if j.type == "continuous":
+ q[j.name] = float(rng.uniform(-math.pi, math.pi))
+ else:
+ assert j.lower is not None and j.upper is not None
+ q[j.name] = float(rng.uniform(j.lower, j.upper))
+ poses.append(q)
+ return poses
+
+
+def pose_label(robot: Robot, q: dict[str, float]) -> str:
+ """Short deterministic label: ``rest`` · ``hinge@upper`` · ``hinge=0.52,slide=0.10``."""
+ active = {k: v for k, v in q.items() if abs(v) > 1e-12}
+ if not active:
+ return "rest"
+ if len(active) == 1:
+ (name, v), = active.items()
+ j = robot.joints.get(name)
+ if j is not None:
+ for tag, ref in (("lower", j.lower), ("upper", j.upper)):
+ if ref is not None and abs(v - ref) < 1e-9:
+ return f"{name}@{tag}"
+ if j.lower is not None and j.upper is not None and abs(v - 0.5 * (j.lower + j.upper)) < 1e-9:
+ return f"{name}@mid"
+ return f"{name}={v:.3g}"
+ return ",".join(f"{k}={v:.3g}" for k, v in sorted(active.items()))
+
+
+def limit_poses(robot: Robot) -> list[tuple[str, dict[str, float]]]:
+ """``rest`` + every movable joint at its lower and upper limit (deduped) —
+ the pose set used for the articulation contact sheet."""
+ out: list[tuple[str, dict[str, float]]] = [("rest", {})]
+ for j in robot.movable_joints():
+ if j.type == "continuous":
+ cands = [("half", math.pi / 2)]
+ else:
+ cands = [("lower", j.lower or 0.0), ("upper", j.upper or 0.0)]
+ for tag, v in cands:
+ if abs(v) > 1e-9:
+ out.append((f"{j.name}@{tag}", {j.name: float(v)}))
+ return out
diff --git a/harness/codeverse/spatial/joints_sweep.py b/harness/codeverse/spatial/joints_sweep.py
new file mode 100644
index 00000000..b31ef262
--- /dev/null
+++ b/harness/codeverse/spatial/joints_sweep.py
@@ -0,0 +1,416 @@
+"""Pose sweep QC on a :class:`Robot`: overlaps, contacts, floating links, motion
+direction. FCL (``python-fcl``) does the boolean collide / distance queries on
+BVH models; penetration depth is measured with trimesh signed distances of
+surface samples (FCL's mesh-mesh contact depths are per-triangle artefacts).
+Falls back to trimesh proximity when FCL is unavailable.
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Any
+
+import numpy as np
+import trimesh
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import GateFinding, Severity
+from codeverse.conventions import CONTACT_GAP_M
+from codeverse.spatial.joints_model import Robot, UrdfError, fk
+from codeverse.spatial.joints_poses import pose_label
+
+try: # optional accelerator
+ import fcl as _fcl
+except Exception: # pragma: no cover - depends on the environment
+ _fcl = None
+
+_MAX_SAMPLE_POINTS = 1500
+
+
+# ------------------------------------------------------------------ report types
+class Overlap(BaseModel):
+ a: str
+ b: str
+ depth_m: float = Field(description="max distance of a penetrating surface point from the other surface")
+ volume_m3: float | None = None
+ approx: bool = Field(default=False, description="depth estimated on non-watertight meshes")
+
+
+class FloatingLink(BaseModel):
+ """A link that is not physically attached to its PARENT link the way its
+ joint type requires (fixed → touching; revolute/continuous → hinge edge
+ within ``hinge_clearance_m``; prismatic → inserted into / touching the parent)."""
+
+ link: str
+ nearest: str = Field(default="", description="the parent link it should attach to")
+ gap_m: float = Field(default=math.inf, description="closest distance to the parent link")
+ joint_type: str = ""
+
+
+class PoseReport(BaseModel):
+ label: str
+ q: dict[str, float]
+ overlaps: list[Overlap] = Field(default_factory=list)
+ floating: list[FloatingLink] = Field(default_factory=list)
+ n_contacts: int = 0
+
+
+class SweepSummary(BaseModel):
+ n_poses: int
+ n_links: int
+ max_penetration_m: float = 0.0
+ worst_pose: str = ""
+ worst_pair: tuple[str, str] | None = None
+ rest_max_penetration_m: float = 0.0
+ overlapping_poses: list[str] = Field(default_factory=list)
+ floating_links: list[str] = Field(default_factory=list, description="floating in ANY sampled pose")
+ floating_at_rest: list[str] = Field(default_factory=list)
+ link_islands: dict[str, int] = Field(default_factory=dict)
+ backend: str = "fcl"
+
+
+class SweepReport(BaseModel):
+ tol_m: float
+ contact_gap_m: float
+ per_pose: list[PoseReport]
+ summary: SweepSummary
+
+
+class MotionCheck(BaseModel):
+ joint: str
+ expected: str
+ observed_dir: tuple[float, float, float]
+ ok: bool
+ message: str
+
+
+# ------------------------------------------------------------------ collision backends
+def _sample_points(mesh: trimesh.Trimesh) -> np.ndarray:
+ pts = np.asarray(mesh.vertices)
+ if len(pts) > _MAX_SAMPLE_POINTS:
+ idx = np.linspace(0, len(pts) - 1, _MAX_SAMPLE_POINTS).astype(int)
+ pts = pts[idx]
+ n_surf = max(64, _MAX_SAMPLE_POINTS - len(pts))
+ surf, _ = trimesh.sample.sample_surface(mesh, n_surf, seed=0)
+ return np.vstack([pts, surf])
+
+
+class _LinkBody:
+ """Per-link collision state reused across poses."""
+
+ def __init__(self, name: str, mesh: trimesh.Trimesh):
+ self.name = name
+ self.mesh = mesh
+ self.local_points = _sample_points(mesh)
+ self.watertight = bool(mesh.is_watertight)
+ self.obj = None
+ if _fcl is not None:
+ model = _fcl.BVHModel()
+ model.beginModel(len(mesh.vertices), len(mesh.faces))
+ model.addSubModel(np.asarray(mesh.vertices, dtype=float), np.asarray(mesh.faces, dtype=np.int64))
+ model.endModel()
+ self.obj = _fcl.CollisionObject(model, _fcl.Transform())
+ self.T = np.eye(4)
+ self.T_inv = np.eye(4)
+ self._pq = trimesh.proximity.ProximityQuery(mesh) # built once, queried in the LOCAL frame
+
+ def set_pose(self, T: np.ndarray) -> None:
+ self.T = T
+ self.T_inv = np.linalg.inv(T)
+ if self.obj is not None:
+ self.obj.setTransform(_fcl.Transform(np.ascontiguousarray(T[:3, :3]), np.ascontiguousarray(T[:3, 3])))
+
+ @property
+ def posed(self) -> trimesh.Trimesh:
+ m = self.mesh.copy()
+ m.apply_transform(self.T)
+ return m
+
+ def signed_distance(self, points_world: np.ndarray) -> np.ndarray:
+ """trimesh convention: > 0 inside this body."""
+ return self._pq.signed_distance(trimesh.transform_points(points_world, self.T_inv))
+
+ def contains(self, points_world: np.ndarray) -> np.ndarray:
+ return self.mesh.contains(trimesh.transform_points(points_world, self.T_inv))
+
+ @property
+ def points(self) -> np.ndarray:
+ return trimesh.transform_points(self.local_points, self.T)
+
+ @property
+ def aabb(self) -> np.ndarray:
+ corners = trimesh.bounds.corners(self.mesh.bounds)
+ pts = trimesh.transform_points(corners, self.T)
+ return np.vstack([pts.min(axis=0), pts.max(axis=0)])
+
+
+def _aabb_gap(a: np.ndarray, b: np.ndarray) -> float:
+ """Largest per-axis separation of two AABBs (≤ 0 when they intersect)."""
+ gaps = np.maximum(a[0] - b[1], b[0] - a[1])
+ return float(gaps.max())
+
+
+def _collide(a: _LinkBody, b: _LinkBody) -> bool:
+ if a.obj is not None and b.obj is not None:
+ req = _fcl.CollisionRequest(num_max_contacts=1, enable_contact=False)
+ res = _fcl.CollisionResult()
+ return int(_fcl.collide(a.obj, b.obj, req, res)) > 0
+ # trimesh fallback: any surface sample of one inside the other, or AABB overlap + near-zero distance
+ return _penetration(a, b)[0] > 0.0
+
+
+def _contained(a: _LinkBody, b: _LinkBody, n: int = 24) -> bool:
+ """True when a few surface samples of one body lie inside the other (FCL's
+ surface-only collide misses a part fully swallowed by another)."""
+ pa = a.points[:: max(1, len(a.points) // n)][:n]
+ pb = b.points[:: max(1, len(b.points) // n)][:n]
+ return bool(b.contains(pa).any() or a.contains(pb).any())
+
+
+def _distance(a: _LinkBody, b: _LinkBody) -> float:
+ if a.obj is not None and b.obj is not None:
+ req = _fcl.DistanceRequest()
+ res = _fcl.DistanceResult()
+ return max(0.0, float(_fcl.distance(a.obj, b.obj, req, res)))
+ d_ab = b.signed_distance(a.points)
+ d_ba = a.signed_distance(b.points)
+ return max(0.0, float(min(-d_ab.max(), -d_ba.max())))
+
+
+def _depth_into(points_world: np.ndarray, other: _LinkBody, cap: int = 400) -> float:
+ """Max distance-to-surface of the ``points_world`` that lie INSIDE ``other``.
+ contains() first (cheap) so exact distances run only on the contained few."""
+ inside = other.contains(points_world)
+ if not inside.any():
+ return 0.0
+ pts = points_world[inside]
+ if len(pts) > cap:
+ pts = pts[np.linspace(0, len(pts) - 1, cap).astype(int)]
+ return max(0.0, float(other.signed_distance(pts).max()))
+
+
+def _penetration(a: _LinkBody, b: _LinkBody) -> tuple[float, bool]:
+ """Max penetration depth (m) of A's surface into B or B's into A; ``approx``
+ when a mesh is not watertight (inside test is then heuristic)."""
+ depth = max(_depth_into(a.points, b), _depth_into(b.points, a))
+ return depth, not (a.watertight and b.watertight)
+
+
+def _intersection_volume(a: _LinkBody, b: _LinkBody) -> float | None:
+ if not (a.watertight and b.watertight):
+ return None
+ try:
+ inter = trimesh.boolean.intersection([a.posed, b.posed], engine="manifold")
+ return float(abs(inter.volume)) if isinstance(inter, trimesh.Trimesh) and not inter.is_empty else 0.0
+ except Exception:
+ return None
+
+
+# ------------------------------------------------------------------ sweep
+def _components(links: list[str], edges: set[tuple[str, str]]) -> dict[str, int]:
+ parent = {n: n for n in links}
+
+ def find(x: str) -> str:
+ while parent[x] != x:
+ parent[x] = parent[parent[x]]
+ x = parent[x]
+ return x
+
+ for a, b in edges:
+ ra, rb = find(a), find(b)
+ if ra != rb:
+ parent[ra] = rb
+ roots = {}
+ out = {}
+ for n in links:
+ r = find(n)
+ out[n] = roots.setdefault(r, len(roots))
+ return out
+
+
+def sweep_collisions(
+ robot: Robot,
+ poses: list[dict[str, float]],
+ *,
+ tol_m: float = 0.002,
+ contact_gap_m: float = CONTACT_GAP_M,
+ allow_pairs: tuple[tuple[str, str], ...] = (),
+ volumes: bool = True,
+ hinge_clearance_m: float = 0.01,
+) -> SweepReport:
+ """Collide every link pair in every pose. Overlaps deeper than ``tol_m``
+ are reported; at the rest pose every link is checked for attachment to its
+ PARENT link according to its joint type (``floating`` = not attached)."""
+ names = robot.meshed_links()
+ if not names:
+ raise UrdfError("sweep_collisions: robot has no link meshes")
+ bodies = {n: _LinkBody(n, robot.links[n].mesh) for n in names} # type: ignore[arg-type]
+ allowed = {tuple(sorted(p)) for p in allow_pairs}
+ per_pose: list[PoseReport] = []
+ islands = {n: max(1, len(robot.links[n].mesh.split(only_watertight=False))) for n in names} # type: ignore[union-attr]
+
+ for q in poses:
+ T = fk(robot, q)
+ for n, body in bodies.items():
+ body.set_pose(T[n])
+ overlaps: list[Overlap] = []
+ touching: set[tuple[str, str]] = set()
+ nearest: dict[str, dict[str, float]] = {n: {} for n in names}
+ for i, a in enumerate(names):
+ for b in names[i + 1 :]:
+ ba, bb = bodies[a], bodies[b]
+ gap_aabb = _aabb_gap(ba.aabb, bb.aabb)
+ if gap_aabb > max(contact_gap_m, hinge_clearance_m * 3):
+ nearest[a][b] = nearest[b][a] = gap_aabb # lower bound is enough this far apart
+ continue
+ if _collide(ba, bb) or (gap_aabb <= 0.0 and _contained(ba, bb)):
+ depth, approx = _penetration(ba, bb)
+ dist = 0.0
+ if depth > tol_m and tuple(sorted((a, b))) not in allowed:
+ overlaps.append(
+ Overlap(a=a, b=b, depth_m=round(depth, 6), approx=approx,
+ volume_m3=_intersection_volume(ba, bb) if volumes else None)
+ )
+ else:
+ dist = _distance(ba, bb)
+ nearest[a][b] = nearest[b][a] = dist
+ if dist <= contact_gap_m:
+ touching.add((a, b))
+ floating: list[FloatingLink] = []
+ if pose_label(robot, q) == "rest": # attachment is a structural (rest-pose) property
+ for n in names:
+ j = robot.parent_joint(n)
+ if j is None or j.parent not in bodies:
+ continue
+ d = nearest[n].get(j.parent, math.inf)
+ if j.type == "fixed":
+ thr = contact_gap_m
+ elif j.type == "prismatic":
+ if _aabb_gap(bodies[n].aabb, bodies[j.parent].aabb) <= 0.0:
+ continue # inserted into the parent's envelope (drawer in cavity)
+ thr = hinge_clearance_m
+ else: # revolute / continuous / planar / floating
+ thr = hinge_clearance_m
+ if d > thr:
+ floating.append(FloatingLink(link=n, nearest=j.parent, joint_type=j.type,
+ gap_m=round(d, 6) if math.isfinite(d) else math.inf))
+ per_pose.append(PoseReport(label=pose_label(robot, q), q=dict(q), overlaps=overlaps, floating=floating,
+ n_contacts=len(touching)))
+
+ summary = _summarise(per_pose, len(names), islands)
+ return SweepReport(tol_m=tol_m, contact_gap_m=contact_gap_m, per_pose=per_pose, summary=summary)
+
+
+def _summarise(per_pose: list[PoseReport], n_links: int, islands: dict[str, int]) -> SweepSummary:
+ s = SweepSummary(n_poses=len(per_pose), n_links=n_links, link_islands=islands,
+ backend="fcl" if _fcl is not None else "trimesh")
+ floating_any: set[str] = set()
+ for pr in per_pose:
+ for o in pr.overlaps:
+ if o.depth_m > s.max_penetration_m:
+ s.max_penetration_m, s.worst_pose, s.worst_pair = o.depth_m, pr.label, (o.a, o.b)
+ if pr.label == "rest":
+ s.rest_max_penetration_m = max(s.rest_max_penetration_m, o.depth_m)
+ if pr.overlaps:
+ s.overlapping_poses.append(pr.label)
+ floating_any.update(f.link for f in pr.floating)
+ if pr.label == "rest":
+ s.floating_at_rest = [f.link for f in pr.floating]
+ s.floating_links = sorted(floating_any)
+ return s
+
+
+# ------------------------------------------------------------------ gate findings
+def sweep_findings(report: SweepReport, *, rest_max_m: float = 0.005, hinge_clearance_m: float = 0.01) -> list[GateFinding]:
+ """Turn a sweep report into gate findings (ERROR for rest penetration > ``rest_max_m``,
+ overlaps in moved poses and floating links beyond ``hinge_clearance_m``; WARN otherwise)."""
+ gate = "articulation"
+ out: list[GateFinding] = []
+ for pr in report.per_pose:
+ for o in pr.overlaps:
+ at_rest = pr.label == "rest"
+ sev = Severity.ERROR if (not at_rest or o.depth_m > rest_max_m) else Severity.WARN
+ out.append(GateFinding(
+ gate=gate, severity=sev, target=f"{o.a}|{o.b}",
+ message=f"links '{o.a}' and '{o.b}' overlap by {o.depth_m*1000:.1f} mm at pose {pr.label}"
+ + (f" (pose q={pr.q})" if pr.q else "") + (" [approx: non-watertight mesh]" if o.approx else ""),
+ fix_hint=(f"At q=0 the meshes in model.py interpenetrate: shrink/move one of '{o.a}', '{o.b}' so they touch (≤ {report.tol_m*1000:.0f} mm) instead of overlapping."
+ if at_rest else
+ f"Moving joint(s) {sorted(pr.q)} drives '{o.a}' into '{o.b}'. Either move the pivot/axis in robot.urdf so the part swings/slides clear, shrink the limits, or carve the clearance in model.py."),
+ data={"kind": "penetration", "pose": pr.q, "depth_m": o.depth_m, "volume_m3": o.volume_m3},
+ ))
+ for f in pr.floating:
+ fixed = f.joint_type == "fixed"
+ sev = Severity.ERROR if (fixed or f.gap_m > hinge_clearance_m * 3) else Severity.WARN
+ what = {"fixed": "is rigidly attached to", "prismatic": "slides in", "revolute": "hinges on",
+ "continuous": "rotates on"}.get(f.joint_type, "attaches to")
+ out.append(GateFinding(
+ gate=gate, severity=sev, target=f.link,
+ message=f"link '{f.link}' {what} '{f.nearest}' ({f.joint_type} joint) but the meshes are "
+ f"{f.gap_m*1000:.1f} mm apart at rest — nothing physically connects them",
+ fix_hint=(f"Extend '{f.link}' so it touches/overlaps '{f.nearest}' by ≥ {report.contact_gap_m*1000:.0f} mm (a fixed child must sit on its parent)."
+ if fixed else
+ f"Move the hinge/rail edge of '{f.link}' within {hinge_clearance_m*1000:.0f} mm of '{f.nearest}' (or model the hinge/bracket/runner) and put the joint pivot on that edge in robot.urdf."),
+ data={"kind": "unattached", "pose": pr.q, "gap_m": f.gap_m, "parent": f.nearest, "joint_type": f.joint_type},
+ ))
+ return out
+
+
+# ------------------------------------------------------------------ motion direction
+_DIRS: dict[str, tuple[float, float, float]] = {
+ "+x": (1, 0, 0), "-x": (-1, 0, 0), "+y": (0, 1, 0), "-y": (0, -1, 0), "+z": (0, 0, 1), "-z": (0, 0, -1),
+ "right": (1, 0, 0), "left": (-1, 0, 0), "back": (0, 1, 0), "front": (0, -1, 0), "up": (0, 0, 1), "down": (0, 0, -1),
+ "open_up": (0, 0, 1), "open_down": (0, 0, -1), "open_front": (0, -1, 0), "out": (0, -1, 0), "in": (0, 1, 0),
+}
+
+
+def motion_direction_check(robot: Robot, joint: str, expected: str, *, probe: float | None = None) -> MotionCheck:
+ """Does the child's centroid move along ``expected`` (``'+z'``, ``'-y'``, ``'up'``,
+ ``'front'``, ``'open_up'`` ...) when ``joint`` moves positively from rest?
+ Revolute joints are probed with a small angle so the initial tangent direction is tested."""
+ key = expected.strip().lower()
+ if key not in _DIRS:
+ raise UrdfError(f"motion_direction_check: unknown direction {expected!r}; use one of {sorted(_DIRS)}")
+ j = robot.joints.get(joint)
+ if j is None or not j.movable:
+ raise UrdfError(f"motion_direction_check: {joint!r} is not a movable joint")
+ mesh = robot.links[j.child].mesh
+ if mesh is None:
+ raise UrdfError(f"motion_direction_check: link {j.child!r} has no mesh")
+ if probe is None:
+ hi = j.upper if j.upper is not None else math.pi
+ lo = j.lower if j.lower is not None else -math.pi
+ probe = hi if abs(hi) >= abs(lo) else lo
+ if j.type != "prismatic":
+ probe = math.copysign(min(abs(probe), 0.35), probe) if probe else 0.35
+ c0 = trimesh.transform_points([mesh.centroid], fk(robot, {})[j.child])[0]
+ c1 = trimesh.transform_points([mesh.centroid], fk(robot, {joint: probe})[j.child])[0]
+ delta = c1 - c0
+ n = float(np.linalg.norm(delta))
+ d = delta / n if n > 1e-9 else delta
+ want = np.asarray(_DIRS[key], dtype=float)
+ cos = float(d @ want)
+ ok = cos > 0.5
+ return MotionCheck(joint=joint, expected=expected, observed_dir=tuple(round(float(v), 4) for v in d), ok=ok,
+ message=(f"{joint}: child '{j.child}' moves {tuple(round(float(v),3) for v in d)} for q={probe:+.3g}; "
+ f"expected {expected} ({'ok' if ok else 'WRONG — flip the axis sign or swap limits'})"))
+
+
+def summary_text(report: SweepReport) -> str:
+ """Compact human/LLM-readable summary of a sweep."""
+ s = report.summary
+ lines = [f"pose sweep: {s.n_poses} poses, {s.n_links} links, backend={s.backend}"]
+ if s.max_penetration_m > 0:
+ lines.append(f"max penetration {s.max_penetration_m*1000:.1f} mm at pose {s.worst_pose} between {s.worst_pair}; overlapping poses: {s.overlapping_poses}")
+ else:
+ lines.append("no overlaps deeper than tolerance in any pose")
+ if s.floating_links:
+ lines.append(f"floating links (not touching the grounded assembly): {s.floating_links}")
+ multi = {k: v for k, v in s.link_islands.items() if v > 1}
+ if multi:
+ lines.append(f"links made of several disconnected islands: {multi}")
+ return "\n".join(lines)
+
+
+def report_numbers(report: SweepReport) -> dict[str, Any]:
+ return report.summary.model_dump(mode="json")
diff --git a/harness/codeverse/spatial/mcp_server.py b/harness/codeverse/spatial/mcp_server.py
new file mode 100644
index 00000000..6ccae541
--- /dev/null
+++ b/harness/codeverse/spatial/mcp_server.py
@@ -0,0 +1,135 @@
+"""stdio MCP server exposing the spatial tool registry to coding agents.
+
+ python -m codeverse.spatial.mcp_server --workspace <ws> [--track X] [--language Y] [--round N]
+
+One MCP tool per registry tool (name, description, JSON schema from
+``ToolDef.schema()``). Results are content blocks: one ``TextContent`` with the
+observation text (+ compact numbers when small) and one ``ImageContent`` per
+observation image (base64 PNG, long side ≤ 1024 px, at most ``MAX_IMAGES``).
+Track / language default to ``<ws>/spec.json`` so agents need no flags.
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import base64
+import io
+import json
+import sys
+from pathlib import Path
+from typing import Any
+
+from PIL import Image
+
+from codeverse.spatial.observe import fmt_numbers
+from codeverse.spatial.registry import Observation, ToolContext, ToolDef, list_tools
+from codeverse.workspace import Workspace
+
+MAX_IMAGES = 4
+MAX_IMAGE_SIDE = 1024
+MAX_NUMBERS_CHARS = 1200
+SERVER_NAME = "c3v"
+
+
+def build_context(workspace: Path, *, track: str = "", language: str = "", round_index: int = 0) -> ToolContext:
+ """ToolContext for ``workspace``; track/language fall back to spec.json."""
+ ws = Workspace(workspace)
+ if (not track or not language) and ws.spec_path.is_file():
+ try:
+ spec = json.loads(ws.spec_path.read_text())
+ except json.JSONDecodeError:
+ spec = {}
+ track = track or str(spec.get("track", ""))
+ language = language or str(spec.get("language", ""))
+ return ToolContext(workspace=ws, round_index=round_index, language=language, track=track)
+
+
+def encode_image(path: str, max_side: int = MAX_IMAGE_SIDE) -> str | None:
+ """PNG → base64 (downscaled so the long side is ≤ ``max_side``); None if unreadable."""
+ try:
+ img = Image.open(path)
+ img.load()
+ except Exception:
+ return None
+ if max(img.size) > max_side:
+ img.thumbnail((max_side, max_side), Image.LANCZOS)
+ buf = io.BytesIO()
+ img.convert("RGBA" if img.mode in ("RGBA", "LA", "P") else "RGB").save(buf, format="PNG", optimize=True)
+ return base64.b64encode(buf.getvalue()).decode("ascii")
+
+
+def observation_content(obs: Observation) -> list[Any]:
+ """Observation → MCP content blocks (text first, then images)."""
+ from mcp import types
+
+ text = obs.text
+ if obs.numbers:
+ nums = json.dumps(obs.numbers, default=str)
+ text += "\n" + (nums if len(nums) <= MAX_NUMBERS_CHARS else fmt_numbers(obs.numbers))
+ blocks: list[Any] = [types.TextContent(type="text", text=text)]
+ for p in obs.images[:MAX_IMAGES]:
+ b64 = encode_image(p)
+ if b64:
+ blocks.append(types.ImageContent(type="image", data=b64, mime_type="image/png"))
+ return blocks
+
+
+def mcp_tools(ctx: ToolContext) -> list[ToolDef]:
+ return list_tools(track=ctx.track, language=ctx.language)
+
+
+def make_server(ctx: ToolContext):
+ """Low-level MCP ``Server`` wired to the registry for ``ctx``."""
+ from mcp import types
+ from mcp.server.lowlevel import Server
+
+ defs = {t.name: t for t in mcp_tools(ctx)}
+
+ async def on_list_tools(_req_ctx: Any, _params: Any) -> types.ListToolsResult:
+ tools = [types.Tool(name=t.name, description=f"({t.cost_hint}) {t.description}", input_schema=t.schema())
+ for t in defs.values()]
+ return types.ListToolsResult(tools=tools)
+
+ async def on_call_tool(_req_ctx: Any, params: types.CallToolRequestParams) -> types.CallToolResult:
+ tdef = defs.get(params.name)
+ if tdef is None:
+ return types.CallToolResult(content=[types.TextContent(type="text", text=f"unknown tool {params.name!r}; known: {sorted(defs)}")], is_error=True)
+ obs = await asyncio.to_thread(tdef.call, ctx, params.arguments or {})
+ return types.CallToolResult(content=observation_content(obs), is_error=not obs.ok)
+
+ return Server(SERVER_NAME, version="0.1.0",
+ instructions="3dcodeverse spatial tools: build, measure, render and check the 3D object in this workspace.",
+ on_list_tools=on_list_tools, on_call_tool=on_call_tool)
+
+
+async def serve_stdio(ctx: ToolContext) -> None:
+ from mcp.server.stdio import stdio_server
+
+ server = make_server(ctx)
+ async with stdio_server() as (read, write):
+ await server.run(read, write, server.create_initialization_options())
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(prog="codeverse.spatial.mcp_server", description=__doc__)
+ ap.add_argument("--workspace", required=True, help="run workspace directory")
+ ap.add_argument("--track", default="")
+ ap.add_argument("--language", default="")
+ ap.add_argument("--round", type=int, default=0, dest="round_index")
+ ap.add_argument("--list", action="store_true", help="print the tool list as JSON and exit")
+ ns = ap.parse_args(argv)
+ ws = Path(ns.workspace)
+ if not ws.is_dir():
+ print(f"workspace not found: {ws}", file=sys.stderr)
+ return 2
+ ctx = build_context(ws, track=ns.track, language=ns.language, round_index=ns.round_index)
+ if ns.list:
+ print(json.dumps([{"name": t.name, "description": t.description, "schema": t.schema()} for t in mcp_tools(ctx)], indent=1))
+ return 0
+ asyncio.run(serve_stdio(ctx))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/harness/codeverse/spatial/measure.py b/harness/codeverse/spatial/measure.py
new file mode 100644
index 00000000..236ee9ed
--- /dev/null
+++ b/harness/codeverse/spatial/measure.py
@@ -0,0 +1,303 @@
+"""Measure the canonical GLB (Y-up, meters, one named top-level node per part).
+
+``measure_glb`` turns a GLB into a :class:`Measurement` (bbox, extents, per-part
+rows, islands, ground gap, footprint offset, materials). Degenerate input
+(empty meshes, parts without geometry) becomes findings in ``Measurement.extra``
+— never an exception — so agents see *what* is wrong instead of a traceback.
+
+``part_meshes`` is the shared loader other spatial modules use: it returns one
+world-space ``trimesh.Trimesh`` per top-level node (all child meshes merged).
+"""
+
+from __future__ import annotations
+
+import re
+from collections import OrderedDict
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import trimesh
+
+from codeverse.contracts.artifacts import Measurement, PartMeasure
+
+__all__ = [
+ "load_scene",
+ "part_meshes",
+ "measure_glb",
+ "measure_summary_table",
+ "instance_groups",
+ "merged_mesh",
+]
+
+_INSTANCE_RE = re.compile(r"^(?P<base>.+?)[_.-](?P<idx>\d{1,3})$")
+
+
+class GlbLoadError(RuntimeError):
+ """The GLB could not be loaded or contains no mesh geometry."""
+
+
+def load_scene(glb: Path | str) -> trimesh.Scene:
+ """Load ``glb`` as a ``trimesh.Scene`` (always a scene, even for one mesh)."""
+ p = Path(glb)
+ if not p.is_file():
+ raise GlbLoadError(f"GLB not found: {p.name}")
+ try:
+ scene = trimesh.load(str(p), force="scene", process=False)
+ except Exception as e: # trimesh raises many types
+ raise GlbLoadError(f"cannot load {p.name}: {type(e).__name__}: {e}") from e
+ if not isinstance(scene, trimesh.Scene):
+ raise GlbLoadError(f"{p.name}: unexpected load result {type(scene).__name__}")
+ return scene
+
+
+def _subtree_nodes(scene: trimesh.Scene, root: str) -> list[str]:
+ """All nodes under ``root`` (inclusive), depth first."""
+ children = scene.graph.transforms.children
+ out, stack = [], [root]
+ while stack:
+ n = stack.pop()
+ out.append(n)
+ stack.extend(children.get(n, ()))
+ return out
+
+
+def _world_mesh(scene: trimesh.Scene, node: str) -> trimesh.Trimesh | None:
+ """Geometry at ``node`` transformed to world space (None if not a mesh)."""
+ try:
+ transform, geom_name = scene.graph.get(node)
+ except Exception:
+ return None
+ if geom_name is None:
+ return None
+ geom = scene.geometry.get(geom_name)
+ if not isinstance(geom, trimesh.Trimesh) or geom.faces is None or len(geom.faces) == 0:
+ return None
+ m = geom.copy()
+ m.apply_transform(transform)
+ # exporters split vertices along hard edges / UV seams; topology queries
+ # (islands, watertightness) need positions merged back together
+ try:
+ m.merge_vertices(merge_tex=True, merge_norm=True)
+ except Exception:
+ pass
+ return m
+
+
+def _children(scene: trimesh.Scene, node: str) -> list[str]:
+ return list(scene.graph.transforms.children.get(node, []))
+
+
+def _node_has_geometry(scene: trimesh.Scene, node: str) -> bool:
+ try:
+ return scene.graph[node][1] is not None
+ except Exception:
+ return False
+
+
+def effective_top_nodes(scene: trimesh.Scene) -> list[str]:
+ """Direct children of the scene root, descending through single wrapper
+ nodes that carry no geometry themselves (a three.js root Group, a URDF
+ ``<robot>`` node) so that parts are found at the first meaningful level."""
+ tops = _children(scene, scene.graph.base_frame)
+ seen = 0
+ while len(tops) == 1 and not _node_has_geometry(scene, tops[0]) and _children(scene, tops[0]) and seen < 4:
+ tops = _children(scene, tops[0])
+ seen += 1
+ return tops
+
+
+def part_meshes(scene: trimesh.Scene) -> OrderedDict[str, trimesh.Trimesh | None]:
+ """One world-space mesh per part, in scene order.
+
+ Flat scenes: a part is an effective top-level node (see
+ :func:`effective_top_nodes`) and its whole subtree is merged.
+ Hierarchical link exports (scene ``metadata['links']`` present, as written
+ by ``spatial.joints_export``): every link node is its own part; only its
+ own geometry (the node itself or ``<link>__<i>`` pieces) is merged, child
+ links stay separate. A part with no geometry maps to ``None``.
+ """
+ out: OrderedDict[str, trimesh.Trimesh | None] = OrderedDict()
+ links = scene.metadata.get("links") if isinstance(scene.metadata, dict) else None
+ nodes = set(scene.graph.nodes)
+ if isinstance(links, list) and links and all(str(l) in nodes for l in links):
+ for link in links:
+ link = str(link)
+ own = [n for n in _subtree_nodes(scene, link) if n == link or str(n).startswith(link + "__")]
+ meshes = [m for n in own if (m := _world_mesh(scene, n)) is not None]
+ out[link] = trimesh.util.concatenate(meshes) if meshes else None
+ return out
+ tops = effective_top_nodes(scene)
+ for top in tops:
+ meshes = [m for n in _subtree_nodes(scene, top) if (m := _world_mesh(scene, n)) is not None]
+ name = str(top)
+ if name in out: # duplicate node names: suffix so nothing is silently merged
+ k = 2
+ while f"{name}~{k}" in out:
+ k += 1
+ name = f"{name}~{k}"
+ out[name] = trimesh.util.concatenate(meshes) if meshes else None
+ # geometry that hangs directly on the root (no named node) — keep it visible
+ if not tops and scene.geometry:
+ for gname, geom in scene.geometry.items():
+ if isinstance(geom, trimesh.Trimesh) and len(geom.faces):
+ out[str(gname)] = geom.copy()
+ return out
+
+
+def merged_mesh(parts: dict[str, trimesh.Trimesh | None]) -> trimesh.Trimesh | None:
+ """All part meshes concatenated (None if nothing has faces)."""
+ meshes = [m for m in parts.values() if m is not None]
+ return trimesh.util.concatenate(meshes) if meshes else None
+
+
+def _count_islands(mesh: trimesh.Trimesh) -> int:
+ try:
+ return max(1, len(mesh.split(only_watertight=False)))
+ except Exception:
+ try:
+ return max(1, len(trimesh.graph.connected_components(mesh.face_adjacency, nodes=np.arange(len(mesh.faces)))))
+ except Exception:
+ return 1
+
+
+def _vec3(a: Any) -> tuple[float, float, float]:
+ return (float(a[0]), float(a[1]), float(a[2]))
+
+
+def _measure_part(name: str, mesh: trimesh.Trimesh) -> PartMeasure:
+ bmin, bmax = mesh.bounds
+ watertight = bool(mesh.is_watertight)
+ volume: float | None = None
+ if watertight:
+ try:
+ volume = abs(float(mesh.volume))
+ except Exception:
+ volume = None
+ return PartMeasure(
+ name=name,
+ bbox_min=_vec3(bmin),
+ bbox_max=_vec3(bmax),
+ tri_count=int(len(mesh.faces)),
+ islands=_count_islands(mesh),
+ volume_m3=volume,
+ watertight=watertight,
+ )
+
+
+def measure_glb(glb: Path | str) -> Measurement:
+ """Compute the language-agnostic census of the canonical GLB.
+
+ Raises :class:`GlbLoadError` only when the file is unreadable; an empty or
+ degenerate model yields a zero-extent ``Measurement`` with findings in
+ ``extra["findings"]``.
+ """
+ scene = load_scene(glb)
+ parts = part_meshes(scene)
+ findings: list[str] = []
+ rows: list[PartMeasure] = []
+ for name, mesh in parts.items():
+ if mesh is None:
+ findings.append(f"part '{name}' has no mesh geometry (empty node)")
+ continue
+ if len(mesh.vertices) == 0 or len(mesh.faces) == 0:
+ findings.append(f"part '{name}' has no triangles")
+ continue
+ ext = mesh.bounds[1] - mesh.bounds[0]
+ if float(np.max(ext)) < 1e-6:
+ findings.append(f"part '{name}' is degenerate (zero extent)")
+ rows.append(_measure_part(name, mesh))
+
+ whole = merged_mesh(parts)
+ materials = len({id(g.visual.material) for g in scene.geometry.values()
+ if hasattr(g, "visual") and hasattr(g.visual, "material")})
+ if whole is None or len(whole.faces) == 0:
+ findings.append("model has no triangles at all")
+ return Measurement(
+ bbox_min=(0.0, 0.0, 0.0), bbox_max=(0.0, 0.0, 0.0), extents=(0.0, 0.0, 0.0),
+ center=(0.0, 0.0, 0.0), tri_count=0, n_meshes=len(parts), n_islands=0, parts=rows,
+ ground_gap_m=0.0, footprint_offset_m=0.0, materials=materials,
+ extra={"findings": findings, "n_parts": len(parts)},
+ )
+ bmin, bmax = whole.bounds
+ ext = bmax - bmin
+ center = (bmin + bmax) / 2.0
+ return Measurement(
+ bbox_min=_vec3(bmin),
+ bbox_max=_vec3(bmax),
+ extents=_vec3(ext),
+ center=_vec3(center),
+ tri_count=int(len(whole.faces)),
+ n_meshes=sum(1 for m in parts.values() if m is not None),
+ n_islands=int(sum(r.islands for r in rows)),
+ parts=rows,
+ ground_gap_m=float(bmin[1]),
+ footprint_offset_m=float(np.hypot(center[0], center[2])),
+ materials=materials,
+ extra={"findings": findings, "n_parts": len(parts),
+ "part_names": [r.name for r in rows]},
+ )
+
+
+# --------------------------------------------------------------------------- table
+def instance_groups(names: list[str]) -> OrderedDict[str, list[str]]:
+ """Group ``Leg_0, Leg_1, Leg_2`` → ``{"Leg": [...]}``; singletons keep their name."""
+ groups: OrderedDict[str, list[str]] = OrderedDict()
+ for n in names:
+ m = _INSTANCE_RE.match(n)
+ key = m.group("base") if m else n
+ groups.setdefault(key, []).append(n)
+ # a "group" with a single member is just the part itself
+ out: OrderedDict[str, list[str]] = OrderedDict()
+ for key, members in groups.items():
+ if len(members) > 1:
+ members = sorted(members, key=lambda n: int(_INSTANCE_RE.match(n).group("idx"))) # type: ignore[union-attr]
+ out[key if len(members) > 1 else members[0]] = members
+ return out
+
+
+def _fmt_ext(ext: tuple[float, float, float] | np.ndarray) -> str:
+ return "×".join(f"{v * 100:.1f}" for v in ext)
+
+
+def measure_summary_table(m: Measurement, max_rows: int = 30) -> str:
+ """Compact markdown table for prompts (judge/agent): totals + per-part rows.
+
+ Instances (``Leg_0..3``) collapse to one row with their union bbox; rows are
+ capped at ``max_rows`` (largest parts first, then an "… n more" line).
+ """
+ lines = [
+ f"overall: {_fmt_ext(m.extents)} cm (W×H×D, Y-up) · centre ({m.center[0]:.3f}, {m.center[1]:.3f}, {m.center[2]:.3f}) m"
+ f" · {m.tri_count} tris · {len(m.parts)} parts · {m.n_islands} islands"
+ f" · ground gap {m.ground_gap_m * 1000:.1f} mm · footprint offset {m.footprint_offset_m * 1000:.1f} mm",
+ "",
+ "| part | size W×H×D (cm) | y range (m) | tris | islands | watertight |",
+ "|---|---|---|---|---|---|",
+ ]
+ by_name = {p.name: p for p in m.parts}
+ rows: list[tuple[float, str]] = []
+ for key, members in instance_groups([p.name for p in m.parts]).items():
+ ps = [by_name[n] for n in members]
+ mins = np.min([p.bbox_min for p in ps], axis=0)
+ maxs = np.max([p.bbox_max for p in ps], axis=0)
+ ext = maxs - mins
+ if len(ps) == 1:
+ label, size_txt = key, _fmt_ext(ext)
+ else:
+ label = f"{key} ×{len(ps)} ({members[0]}..{members[-1].rsplit('_', 1)[-1]})"
+ each = np.max([np.subtract(p.bbox_max, p.bbox_min) for p in ps], axis=0)
+ size_txt = f"{_fmt_ext(each)} each, span {_fmt_ext(ext)}"
+ tris = sum(p.tri_count for p in ps)
+ islands = sum(p.islands for p in ps)
+ wt = "yes" if all(p.watertight for p in ps) else ("no" if not any(p.watertight for p in ps) else "some")
+ size = float(np.prod(np.maximum(ext, 1e-9)))
+ rows.append((size, f"| {label} | {size_txt} | {mins[1]:.3f}..{maxs[1]:.3f} | {tris} | {islands} | {wt} |"))
+ rows.sort(key=lambda r: -r[0])
+ lines.extend(r[1] for r in rows[:max_rows])
+ if len(rows) > max_rows:
+ lines.append(f"| … {len(rows) - max_rows} more parts | | | | | |")
+ finds = m.extra.get("findings") or []
+ if finds:
+ lines.append("")
+ lines.extend(f"- finding: {f}" for f in finds[:10])
+ return "\n".join(lines)
diff --git a/harness/codeverse/spatial/node.py b/harness/codeverse/spatial/node.py
new file mode 100644
index 00000000..65d90c22
--- /dev/null
+++ b/harness/codeverse/spatial/node.py
@@ -0,0 +1,188 @@
+"""Run harness-owned node scripts (``runtime_js/*.mjs``) as subprocesses.
+
+All node work in the harness goes through :func:`run_node`: it sets
+``NODE_PATH`` to ``runtime_js/node_modules`` (CommonJS resolution), optionally
+adds the ESM ``--import`` hook that lets agent code outside ``runtime_js``
+import ``three`` / ``three/addons/*``, enforces a timeout, kills the whole
+process group on expiry and parses the *last JSON line* of stdout (the
+convention every runtime_js script follows).
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import resource
+import signal
+import subprocess
+import time
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from codeverse.config import get_settings
+
+TAIL_CHARS = 4000
+
+
+class NodeError(RuntimeError):
+ """A node script failed (non-zero exit, timeout or missing binary).
+
+ ``result`` carries whatever was captured so callers can turn it into a
+ ``BuildResult`` / ``GateReport`` without losing the tail.
+ """
+
+ def __init__(self, message: str, result: NodeResult | None = None):
+ super().__init__(message)
+ self.result = result
+
+
+@dataclass
+class NodeResult:
+ rc: int
+ stdout: str
+ stderr: str
+ last_json: dict[str, Any] | None
+ duration_ms: int
+ timed_out: bool = False
+ cmd: list[str] = field(default_factory=list)
+
+ @property
+ def stdout_tail(self) -> str:
+ return self.stdout[-TAIL_CHARS:]
+
+ @property
+ def stderr_tail(self) -> str:
+ return self.stderr[-TAIL_CHARS:]
+
+
+def runtime_js_dir() -> Path:
+ return get_settings().runtime_js_dir()
+
+
+def node_modules_dir() -> Path:
+ return runtime_js_dir() / "node_modules"
+
+
+def three_import_hook() -> Path:
+ """The ``--import`` hook that redirects bare ``three`` specifiers to runtime_js."""
+ return runtime_js_dir() / "lib" / "resolve_three.mjs"
+
+
+def parse_last_json(stdout: str) -> dict[str, Any] | None:
+ """Return the last line of ``stdout`` that parses as a JSON object, else None."""
+ for line in reversed(stdout.splitlines()):
+ line = line.strip()
+ if not line.startswith("{"):
+ continue
+ try:
+ obj = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(obj, dict):
+ return obj
+ return None
+
+
+def _limit_memory(limit_gb: float | None):
+ if not limit_gb:
+ return None
+ limit = int(limit_gb * 1024**3)
+
+ def _pre() -> None:
+ with contextlib.suppress(ValueError, OSError):
+ resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
+
+ return _pre
+
+
+def run_node(
+ script: Path | str,
+ args: list[str] | None = None,
+ *,
+ cwd: Path | str | None = None,
+ timeout_s: float = 300.0,
+ env_extra: dict[str, str] | None = None,
+ node_args: list[str] | None = None,
+ three_hook: bool = False,
+ mem_limit_gb: float | None = None,
+ check: bool = True,
+) -> NodeResult:
+ """Run ``node [node_args] script [args]`` and return a :class:`NodeResult`.
+
+ * ``three_hook=True`` adds ``--import runtime_js/lib/resolve_three.mjs`` so the
+ script (and anything it imports, e.g. agent code) can ``import 'three'``.
+ * On timeout the process group is killed and ``NodeError`` is raised.
+ * With ``check=True`` (default) a non-zero exit raises ``NodeError`` whose
+ ``.result`` has the tails and ``last_json`` (a structured error record when
+ the script emitted one).
+ """
+ settings = get_settings()
+ node_bin = settings.binaries.node
+ script = Path(script)
+ if not script.is_file():
+ raise NodeError(f"node script not found: {script}")
+ cmd = [node_bin, *(node_args or [])]
+ if three_hook:
+ cmd += ["--import", str(three_import_hook())]
+ cmd += [str(script), *(args or [])]
+
+ env = dict(os.environ)
+ env["NODE_PATH"] = str(node_modules_dir())
+ env.setdefault("C3V_CACHE_DIR", str(settings.cache_dir))
+ env.setdefault("NODE_OPTIONS", "")
+ env["NODE_NO_WARNINGS"] = "1"
+ if env_extra:
+ env.update(env_extra)
+
+ t0 = time.time()
+ try:
+ proc = subprocess.Popen(
+ cmd,
+ cwd=str(cwd) if cwd else None,
+ env=env,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ text=True,
+ start_new_session=True,
+ preexec_fn=_limit_memory(mem_limit_gb),
+ )
+ except FileNotFoundError as e:
+ raise NodeError(f"node binary not found ({node_bin}): {e}") from e
+
+ timed_out = False
+ try:
+ out, err = proc.communicate(timeout=timeout_s)
+ except subprocess.TimeoutExpired:
+ timed_out = True
+ _kill_group(proc)
+ out, err = proc.communicate()
+ duration_ms = int((time.time() - t0) * 1000)
+ result = NodeResult(
+ rc=proc.returncode if not timed_out else -9,
+ stdout=out or "",
+ stderr=err or "",
+ last_json=parse_last_json(out or ""),
+ duration_ms=duration_ms,
+ timed_out=timed_out,
+ cmd=cmd,
+ )
+ if timed_out:
+ raise NodeError(f"node script {script.name} timed out after {timeout_s:.0f}s\n{result.stderr_tail}", result)
+ if check and result.rc != 0:
+ msg = f"node script {script.name} exited {result.rc}"
+ if result.last_json and isinstance(result.last_json.get("error"), (dict, str)):
+ e = result.last_json["error"]
+ msg += ": " + (e.get("message", "") if isinstance(e, dict) else str(e))
+ raise NodeError(msg + "\n" + result.stderr_tail, result)
+ return result
+
+
+def _kill_group(proc: subprocess.Popen) -> None:
+ try:
+ os.killpg(proc.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ except PermissionError:
+ proc.kill()
diff --git a/harness/codeverse/spatial/observe.py b/harness/codeverse/spatial/observe.py
new file mode 100644
index 00000000..8938d32d
--- /dev/null
+++ b/harness/codeverse/spatial/observe.py
@@ -0,0 +1,154 @@
+"""Helpers that keep tool Observations compact and workspace-safe.
+
+* ``fmt_numbers`` – one-line ``k=v`` rendering with sane float precision.
+* ``truncate`` – head/tail truncation with a marker (never mid-line when possible).
+* ``tail_lines`` – last ``n`` lines of a log.
+* ``image_budget`` – cap image lists (contact sheet kept first).
+* ``rel_path`` – workspace-relative display path (never leak host paths in text).
+* ``gate_observation`` / ``render_observation`` – standard Observation builders.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Sequence
+from pathlib import Path
+from typing import Any
+
+from codeverse.contracts.artifacts import GateReport, RenderSet, Severity
+from codeverse.spatial.registry import Observation
+
+MAX_IMAGES = 6
+MAX_TEXT = 2400
+
+
+def fmt_float(v: float, digits: int = 4) -> str:
+ if v == 0:
+ return "0"
+ if abs(v) >= 1000 or abs(v) < 1e-3:
+ return f"{v:.3g}"
+ return f"{v:.{digits}f}".rstrip("0").rstrip(".")
+
+
+def fmt_numbers(numbers: dict[str, Any], max_items: int = 24) -> str:
+ """``a=1.5 b=[0.1, 0.2] c=ok`` — nested dicts/lists are compacted, long ones elided."""
+ bits = []
+ for i, (k, v) in enumerate(numbers.items()):
+ if i >= max_items:
+ bits.append(f"…+{len(numbers) - max_items}")
+ break
+ bits.append(f"{k}={_fmt_value(v)}")
+ return " ".join(bits)
+
+
+def _fmt_value(v: Any, depth: int = 0) -> str:
+ if isinstance(v, bool):
+ return "yes" if v else "no"
+ if isinstance(v, float):
+ return fmt_float(v)
+ if isinstance(v, (list, tuple)):
+ if len(v) > 8:
+ return "[" + ", ".join(_fmt_value(x, depth + 1) for x in v[:8]) + f", …+{len(v) - 8}]"
+ return "[" + ", ".join(_fmt_value(x, depth + 1) for x in v) + "]"
+ if isinstance(v, dict):
+ if depth >= 2:
+ return f"{{{len(v)} keys}}"
+ return "{" + ", ".join(f"{k}:{_fmt_value(x, depth + 1)}" for k, x in list(v.items())[:12]) + "}"
+ s = str(v)
+ return s if len(s) <= 80 else s[:77] + "…"
+
+
+def truncate(text: str, n: int = MAX_TEXT, tail_ratio: float = 0.3) -> str:
+ """Keep the head and the tail of ``text`` (tail-biased errors survive)."""
+ if len(text) <= n:
+ return text
+ tail_n = int(n * tail_ratio)
+ head_n = n - tail_n - 24
+ head, tail = text[:head_n], text[-tail_n:] if tail_n else ""
+ return f"{head}\n… [{len(text) - head_n - tail_n} chars omitted] …\n{tail}"
+
+
+def tail_lines(text: str, n: int = 30) -> str:
+ lines = text.rstrip("\n").splitlines()
+ return "\n".join(lines[-n:])
+
+
+def image_budget(images: Sequence[str], max_n: int = MAX_IMAGES) -> list[str]:
+ """Keep at most ``max_n`` images; the first (contact sheet) always survives."""
+ imgs = [str(p) for p in images if p]
+ if len(imgs) <= max_n:
+ return imgs
+ return imgs[:max_n]
+
+
+def rel_path(path: Path | str | None, root: Path) -> str:
+ """Display path relative to the workspace root (falls back to the file name)."""
+ if path is None:
+ return ""
+ p = Path(path)
+ try:
+ return str(p.resolve().relative_to(Path(root).resolve()))
+ except ValueError:
+ return p.name
+
+
+def sanitize_text(text: str, root: Path) -> str:
+ """Replace absolute workspace paths in free text with workspace-relative ones."""
+ r = str(Path(root).resolve())
+ return text.replace(r + "/", "").replace(r, ".")
+
+
+# --------------------------------------------------------------------------- builders
+_SEV_ORDER = {Severity.ERROR: 0, Severity.WARN: 1, Severity.INFO: 2}
+_SEV_TAG = {Severity.ERROR: "ERROR", Severity.WARN: "WARN", Severity.INFO: "info"}
+
+
+def gate_observation(report: GateReport, *, title: str = "", max_findings: int = 20, images: Iterable[str] = ()) -> Observation:
+ """Errors first, each with its fix hint; counts in ``numbers``."""
+ findings = sorted(report.findings, key=lambda f: _SEV_ORDER.get(f.severity, 3))
+ n_err = sum(1 for f in findings if f.severity == Severity.ERROR)
+ n_warn = sum(1 for f in findings if f.severity == Severity.WARN)
+ head = title or f"{report.gate}: {'PASS' if report.passed else 'FAIL'}"
+ lines = [f"{head} — {n_err} error(s), {n_warn} warning(s)"]
+ for f in findings[:max_findings]:
+ tgt = f" [{f.target}]" if f.target else ""
+ lines.append(f"- {_SEV_TAG[f.severity]}{tgt}: {f.message}")
+ if f.fix_hint and f.severity != Severity.INFO:
+ lines.append(f" fix: {f.fix_hint}")
+ if len(findings) > max_findings:
+ lines.append(f"- … {len(findings) - max_findings} more finding(s)")
+ numbers: dict[str, Any] = {"passed": report.passed, "errors": n_err, "warnings": n_warn}
+ for f in findings:
+ if f.severity == Severity.ERROR and f.data:
+ numbers.setdefault("error_data", {})[f.target or f.message[:40]] = f.data
+ return Observation(ok=report.passed, text=truncate("\n".join(lines)), numbers=numbers, images=list(images))
+
+
+def render_observation(rs: RenderSet, root: Path, *, note: str = "", max_individual: int = 4) -> Observation:
+ """Contact sheet first, individual views when few; text lists views + cameras."""
+ images: list[str] = []
+ if rs.contact_sheet:
+ images.append(rs.contact_sheet)
+ if len(rs.views) <= max_individual:
+ images.extend(v.path for v in rs.views)
+ lines = [note] if note else []
+ lines.append(f"{len(rs.views)} view(s)" + (f" via {rs.renderer}" if rs.renderer else "") + (", contact sheet first" if rs.contact_sheet else ""))
+ for v in rs.views:
+ cam = ""
+ if v.camera_position is not None:
+ cam = " cam=(" + ", ".join(fmt_float(c, 2) for c in v.camera_position) + ")"
+ if v.fov:
+ cam += f" fov={v.fov:g}"
+ t = f" t={v.time_s:g}s" if v.time_s is not None else ""
+ lines.append(f"- {v.name} [{v.mode}{t}]{cam} → {rel_path(v.path, root)}")
+ if rs.console_errors:
+ lines.append(f"console errors ({len(rs.console_errors)}):")
+ lines.extend(f" ! {e[:200]}" for e in rs.console_errors[:8])
+ if rs.fps is not None:
+ lines.append(f"fps ≈ {rs.fps:.0f}")
+ numbers: dict[str, Any] = {"n_views": len(rs.views), "views": [v.name for v in rs.views]}
+ if rs.fps is not None:
+ numbers["fps"] = rs.fps
+ if rs.console_errors:
+ numbers["console_errors"] = len(rs.console_errors)
+ return Observation(ok=not rs.console_errors, text=truncate("\n".join(lines)), numbers=numbers,
+ images=image_budget(images))
diff --git a/harness/codeverse/spatial/probes.py b/harness/codeverse/spatial/probes.py
new file mode 100644
index 00000000..b6ac0260
--- /dev/null
+++ b/harness/codeverse/spatial/probes.py
@@ -0,0 +1,228 @@
+"""Scene probes: import/census gate, shader compile preflight, shader presence.
+
+* ``probe_scene(ws)`` → (GateReport 'scene_probe', census) — the scene build gate
+* ``check_shaders(ws)`` → GateReport 'shader_preflight' (file:line + fix hints)
+* ``shader_presence(ws)``→ Observation: counterfactual render (custom shaders
+ stripped) vs normal; pixel-diff fraction proves the effect is in the frame.
+
+All three drive the node host (``runtime_js/*.mjs``) via ``run_scene_script``.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.contracts.plan import CameraPlan
+from codeverse.conventions import MAX_TRIS_SCENE
+from codeverse.spatial.registry import Observation
+from codeverse.spatial.render_scene import (
+ SceneRenderError,
+ read_metrics,
+ render_scene,
+ run_scene_script,
+)
+from codeverse.workspace import Workspace
+
+PROBE_GATE = "scene_probe"
+SHADER_GATE = "shader_preflight"
+
+_BOOT_HINTS = {
+ "import": "src/scene.js failed to import: fix the syntax/import error quoted above (imports must be 'three', 'three/addons/*' or relative paths that exist)",
+ "createScene": "createScene({THREE, renderer, loaders}) threw or returned the wrong shape; it must return {scene: THREE.Scene, cameras: [...], update(t, dt)}",
+ "loads": "an asset failed to load; check the '/assets/<name>.glb' path exists under public/assets",
+ "first_update": "update(0, 0) threw; guard against undefined handles before animating",
+}
+
+
+class SceneProbeResult(BaseModel):
+ """``probe_scene`` result: unpacks as ``gate, census = probe_scene(ws)`` and also
+ dumps to a dict with ``errors`` so generic tool adapters can read it."""
+
+ gate: GateReport
+ census: dict[str, Any] = Field(default_factory=dict)
+ errors: list[str] = Field(default_factory=list)
+ ok: bool = False
+
+ def __iter__(self): # type: ignore[override]
+ yield self.gate
+ yield self.census
+
+
+def _result(gate: GateReport, census: dict[str, Any]) -> SceneProbeResult:
+ return SceneProbeResult(gate=gate, census=census, ok=gate.passed,
+ errors=[f"{f.target or ''}: {f.message}" for f in gate.errors])
+
+
+def _f(gate: str, sev: Severity, msg: str, *, target: str | None = None, hint: str = "", **data: Any) -> GateFinding:
+ return GateFinding(gate=gate, severity=sev, target=target, message=msg, fix_hint=hint, data=data)
+
+
+def probe_scene(ws: Workspace, *, timeout_s: float = 60.0, write_census: bool = True) -> SceneProbeResult:
+ """Import-only probe: module loads, shape valid, cameras valid, update runs, census."""
+ t0 = time.time()
+ gate = PROBE_GATE
+ findings: list[GateFinding] = []
+ census: dict[str, Any] = {}
+ out_json = ws.artifacts / "scene_probe.json"
+ try:
+ res = run_scene_script(
+ "probe_scene.mjs", ["--ws", str(ws.root), "--out", str(out_json), "--timeout-ms", str(int(timeout_s * 1000))],
+ timeout_s=timeout_s + 20,
+ )
+ except SceneRenderError as e:
+ findings.append(_f(gate, Severity.ERROR, f"scene probe could not run: {e}", target="src/scene.js",
+ hint="this is a harness/driver failure, not your code; retry or report"))
+ return _result(GateReport(gate=gate, passed=False, findings=findings, duration_ms=int((time.time() - t0) * 1000)), census)
+ s = res.summary
+ boot = s.get("boot") or {}
+ if not boot.get("ok"):
+ stage = boot.get("stage", "?")
+ msg = boot.get("error") or "scene did not boot"
+ if "Failed to fetch dynamically imported module" in msg:
+ missing = [e for e in s.get("console_errors", []) if "404 not found" in e or "request failed" in e]
+ if missing:
+ msg += " — " + "; ".join(missing[:4])
+ findings.append(_f(gate, Severity.ERROR, f"[{stage}] {msg}"[:1500], target="src/scene.js",
+ hint=_BOOT_HINTS.get(stage, "fix the quoted error"), stage=stage))
+ for p in boot.get("camera_problems", []):
+ sev = Severity.ERROR if ("no valid cameras" in p or "not an array" in p or "must be" in p) else Severity.WARN
+ findings.append(_f(gate, sev, f"cameras: {p}", target="src/scene.js",
+ hint="cameras: [{name:'overview', position:[x,y,z], lookAt:[x,y,z], fov:50}, ...] (1-6 entries)"))
+ if boot.get("ok") and s.get("update_ok") is False:
+ findings.append(_f(gate, Severity.ERROR, f"update(t, dt) threw: {s.get('update_error', '')[:800]}", target="src/scene.js",
+ hint="update must run every frame without throwing; guard optional handles"))
+ for e in s.get("console_errors", []):
+ if e.startswith("boot["):
+ continue
+ findings.append(_f(gate, Severity.ERROR, f"console: {e}"[:1000], target="src/scene.js",
+ hint="the browser console must stay clean: fix the quoted error"))
+ for w in s.get("console_warnings", []):
+ if "404 not found" in w or w.startswith("load: "):
+ findings.append(_f(gate, Severity.WARN, w[:500], target="public/assets",
+ hint="compile the Blender asset to public/assets/<name>.glb (the scene renders without it until then)"))
+ for e in s.get("shader_errors", []):
+ findings.append(_f(gate, Severity.ERROR, f"shader {e.get('stage')}: {e.get('message')} at: {e.get('source_line', '')}",
+ target=e.get("material") or "shader", hint="run check_shaders for file:line mapping"))
+ if boot.get("raf_calls"):
+ findings.append(_f(gate, Severity.WARN, f"scene called requestAnimationFrame {boot['raf_calls']}x; animation must live in update(t, dt)",
+ target="src/scene.js", hint="delete your own render loop; the host drives update()"))
+ census = s.get("census") or {}
+ findings.extend(_census_findings(census))
+ cam0 = s.get("first_camera") or {}
+ if cam0.get("camera_in_geometry"):
+ findings.append(_f(gate, Severity.WARN,
+ f"camera '{cam0.get('name')}' is inside/too close to geometry (nearest hit {cam0.get('nearest_hit_m')} m, inside {cam0.get('inside_mesh_bbox')})",
+ target=str(cam0.get("name")), hint="move the eye ≥ 0.5 m away from surfaces and above ground"))
+ if cam0 and cam0.get("dark_frac", 0) > 0.85:
+ findings.append(_f(gate, Severity.WARN, f"camera '{cam0.get('name')}' frame is {cam0['dark_frac']:.0%} black — no lights or nothing in view?",
+ target=str(cam0.get("name")), hint="add a DirectionalLight + HemisphereLight in env, aim the camera at the content"))
+ if write_census and census:
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ (ws.artifacts / "census.json").write_text(json.dumps(census, indent=1))
+ passed = not any(f.severity == Severity.ERROR for f in findings)
+ return _result(GateReport(gate=gate, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000)), census)
+
+
+def _census_findings(c: dict[str, Any]) -> list[GateFinding]:
+ gate = PROBE_GATE
+ out: list[GateFinding] = []
+ if not c:
+ return out
+ tot = c.get("totals", {})
+ if tot.get("lights", 0) == 0:
+ out.append(_f(gate, Severity.WARN, "scene has no lights (MeshStandardMaterial renders black)", target="src/env.js",
+ hint="add new THREE.DirectionalLight (castShadow) + new THREE.HemisphereLight in buildEnv"))
+ if tot.get("meshes", 0) == 0:
+ out.append(_f(gate, Severity.ERROR, "scene has no meshes", target="src/scene.js", hint="add zones to the scene in createScene"))
+ if tot.get("triangles", 0) > MAX_TRIS_SCENE:
+ out.append(_f(gate, Severity.WARN, f"{tot['triangles']:,} triangles exceeds the {MAX_TRIS_SCENE:,} budget", target="scene",
+ hint="lower segment counts, use InstancedMesh for repeats, merge static geometry"))
+ unnamed = [g["name"] for g in c.get("groups", []) if not g.get("named") and g.get("kind") == "content"]
+ if unnamed:
+ out.append(_f(gate, Severity.WARN, f"{len(unnamed)} top-level content object(s) without a name: {unnamed[:5]}", target="src/scene.js",
+ hint="group each zone in a THREE.Group with group.name = 'ZoneName' (PascalCase)"))
+ for o in c.get("overlaps", [])[:5]:
+ if o.get("footprint_overlap", 0) >= 0.5:
+ out.append(_f(gate, Severity.INFO, f"zones {o['a']} and {o['b']} footprints overlap {o['footprint_overlap']:.0%}",
+ target=o["a"], hint="fine if intended (nested zones); otherwise move one"))
+ return out
+
+
+def check_shaders(ws: Workspace, *, module: str | None = None, timeout_s: float = 90.0) -> GateReport:
+ """Static GLSL audits + GPU compile preflight with file:line mapped errors."""
+ t0 = time.time()
+ gate = SHADER_GATE
+ out_json = ws.artifacts / "shader_preflight.json"
+ args = ["--ws", str(ws.root), "--out", str(out_json), "--timeout-ms", str(int(timeout_s * 1000))]
+ if module:
+ args += ["--module", module]
+ findings: list[GateFinding] = []
+ try:
+ res = run_scene_script("check_shaders.mjs", args, timeout_s=timeout_s + 20)
+ except SceneRenderError as e:
+ findings.append(_f(gate, Severity.ERROR, f"shader preflight could not run: {e}", target="src/scene.js",
+ hint="harness/driver failure; retry or report"))
+ return GateReport(gate=gate, passed=False, findings=findings, duration_ms=int((time.time() - t0) * 1000))
+ rep = res.summary
+ for e in rep.get("errors", []):
+ target = f"{e.get('file', '?')}:{e['line']}" if e.get("line") else str(e.get("file", "?"))
+ findings.append(_f(gate, Severity.ERROR, e.get("message", "shader error"), target=target,
+ hint=e.get("fix_hint", ""), kind=e.get("kind"), stage=e.get("stage"), material=e.get("material"),
+ source_line=e.get("source_line"), context=e.get("context")))
+ for w in rep.get("warnings", []):
+ target = f"{w.get('file', '?')}:{w['line']}" if w.get("line") else str(w.get("file", "?"))
+ findings.append(_f(gate, Severity.WARN, w.get("message", ""), target=target, hint=w.get("fix_hint", ""), kind=w.get("kind")))
+ comp = rep.get("compile") or {}
+ if comp:
+ findings.append(_f(gate, Severity.INFO, f"compiled {comp.get('programs')} programs ({comp.get('custom_materials')} custom) in {comp.get('ms')} ms",
+ target="scene", **comp))
+ passed = bool(rep.get("ok")) and not any(f.severity == Severity.ERROR for f in findings)
+ return GateReport(gate=gate, passed=passed, findings=findings, duration_ms=int((time.time() - t0) * 1000))
+
+
+def shader_presence(
+ ws: Workspace,
+ *,
+ out_dir: Path | None = None,
+ camera: CameraPlan | None = None,
+ time_s: float = 0.7,
+ width: int = 512,
+ height: int = 288,
+ threshold: float = 0.01,
+) -> Observation:
+ """Counterfactual probe: render normally and with custom-shader materials
+ stripped; the fraction of changed pixels says whether the effect is visible.
+ ``present`` when diff ≥ ``threshold`` (calibrate with fixtures; 0.0 = invisible)."""
+ import numpy as np
+ from PIL import Image
+
+ out = Path(out_dir) if out_dir else ws.artifacts / "tool_scratch" / "shader_presence"
+ rs = render_scene(ws, out, cameras=[camera] if camera else None, orbit=False, times=(time_s,),
+ width=width, height=height, sheet=False, fps_seconds=0, counterfactual=True)
+ metrics = read_metrics(out)
+ custom = (metrics.get("census") or {}).get("custom_materials", [])
+ pairs = [(v, nv) for v in rs.views if "_nocustom" not in v.name for nv in rs.views if nv.name == f"{v.name}_nocustom"]
+ if not pairs:
+ return Observation.error("shader_presence: no render pairs produced; is the scene booting? " + "; ".join(rs.console_errors[:3]))
+ results = []
+ images: list[str] = []
+ for v, nv in pairs:
+ a = np.asarray(Image.open(v.path).convert("RGB")).astype(int)
+ b = np.asarray(Image.open(nv.path).convert("RGB")).astype(int)
+ frac = float((np.abs(a - b).max(axis=2) > 12).mean())
+ results.append({"camera": v.name, "diff_frac": round(frac, 4), "present": frac >= threshold})
+ images += [v.path, nv.path]
+ best = max(r["diff_frac"] for r in results)
+ text = (f"custom-shader materials: {len(custom)} ({', '.join(m.get('on', '?') for m in custom[:6])}); "
+ f"pixel change when stripped: " + ", ".join(f"{r['camera']}={r['diff_frac']:.1%}" for r in results)
+ + (". PRESENT: the shader changes the frame." if best >= threshold else
+ ". NOT VISIBLE: stripping the custom shader changes nothing — it is not in any camera's frame (or is hidden/occluded)."))
+ if not custom:
+ text = "no custom shader materials found (ShaderMaterial / onBeforeCompile). " + text
+ return Observation(ok=True, text=text, numbers={"custom_materials": len(custom), "max_diff_frac": best, "per_camera": results, "threshold": threshold}, images=images)
diff --git a/harness/codeverse/spatial/registry.py b/harness/codeverse/spatial/registry.py
new file mode 100644
index 00000000..a57f33f9
--- /dev/null
+++ b/harness/codeverse/spatial/registry.py
@@ -0,0 +1,173 @@
+"""Tool registry: one definition → python fn + JSON schema + MCP + prompt card.
+
+Usage::
+
+ class MeasureArgs(BaseModel):
+ parts: list[str] = Field(default_factory=list, description="limit to these part names")
+
+ @tool("measure", MeasureArgs, "Measure bbox/extents/islands of the built object (and per part).")
+ def measure(ctx: ToolContext, args: MeasureArgs) -> Observation: ...
+
+``ToolContext`` carries the workspace and settings; tools never touch globals.
+Observations: ``text`` (what the agent reads), ``numbers`` (machine-readable),
+``images`` (paths, small PNGs the agent may view), ``ok``.
+"""
+
+from __future__ import annotations
+
+import inspect
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Callable
+
+from pydantic import BaseModel, Field
+
+from codeverse.workspace import Workspace
+
+
+class Observation(BaseModel):
+ ok: bool = True
+ text: str = Field(description="human/LLM-readable summary (≤ ~2k chars)")
+ numbers: dict[str, Any] = Field(default_factory=dict)
+ images: list[str] = Field(default_factory=list, description="PNG paths (small, labelled)")
+ duration_ms: int = 0
+
+ @classmethod
+ def error(cls, text: str, **numbers: Any) -> Observation:
+ return cls(ok=False, text=text, numbers=numbers)
+
+
+class ToolUsageError(ValueError):
+ """Raised by tools on caller mistakes; ``fix_example`` is shown to the agent."""
+
+ def __init__(self, message: str, fix_example: str = ""):
+ super().__init__(message)
+ self.fix_example = fix_example
+
+
+@dataclass
+class ToolContext:
+ workspace: Workspace
+ round_index: int = 0
+ language: str = ""
+ track: str = ""
+ scratch: Path | None = None
+ extra: dict[str, Any] = field(default_factory=dict)
+
+ @property
+ def scratch_dir(self) -> Path:
+ d = self.scratch or (self.workspace.artifacts / "tool_scratch")
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+@dataclass(frozen=True)
+class ToolDef:
+ name: str
+ args_model: type[BaseModel]
+ description: str
+ fn: Callable[[ToolContext, BaseModel], Observation]
+ tracks: tuple[str, ...] = () # empty = all
+ languages: tuple[str, ...] = () # empty = all
+ cost_hint: str = "fast" # fast | slow
+
+ def schema(self) -> dict[str, Any]:
+ """JSON schema of the arguments object (for native tool calling / MCP)."""
+ s = self.args_model.model_json_schema()
+ s.pop("title", None)
+ return s
+
+ def card(self) -> str:
+ """Prompt card: name, one-line purpose, args with descriptions."""
+ props = self.schema().get("properties", {})
+ req = set(self.schema().get("required", []))
+ lines = [f"- `{self.name}` ({self.cost_hint}): {self.description}"]
+ for k, v in props.items():
+ typ = v.get("type", "any")
+ d = v.get("description", "")
+ mark = "required" if k in req else f"default={v.get('default')!r}"
+ lines.append(f" · {k}: {typ} — {d} ({mark})")
+ return "\n".join(lines)
+
+ def call(self, ctx: ToolContext, arguments: dict[str, Any] | BaseModel | None = None) -> Observation:
+ import time
+
+ t0 = time.time()
+ try:
+ args = arguments if isinstance(arguments, BaseModel) else self.args_model(**(arguments or {}))
+ except Exception as e: # pydantic ValidationError → usage error for the agent
+ return Observation.error(f"{self.name}: invalid arguments: {e}\nSchema: {self.schema()}")
+ try:
+ obs = self.fn(ctx, args)
+ except ToolUsageError as e:
+ obs = Observation.error(f"{self.name}: {e}" + (f"\nExample: {e.fix_example}" if e.fix_example else ""))
+ except Exception as e: # never crash the agent loop
+ obs = Observation.error(f"{self.name} failed: {type(e).__name__}: {e}")
+ obs.duration_ms = int((time.time() - t0) * 1000)
+ return obs
+
+
+_REGISTRY: dict[str, ToolDef] = {}
+
+
+def tool(
+ name: str,
+ args_model: type[BaseModel],
+ description: str,
+ *,
+ tracks: tuple[str, ...] = (),
+ languages: tuple[str, ...] = (),
+ cost_hint: str = "fast",
+) -> Callable[[Callable[[ToolContext, Any], Observation]], Callable[[ToolContext, Any], Observation]]:
+ def deco(fn: Callable[[ToolContext, Any], Observation]) -> Callable[[ToolContext, Any], Observation]:
+ sig = inspect.signature(fn)
+ if len(sig.parameters) != 2:
+ raise TypeError(f"tool {name}: fn must be fn(ctx, args)")
+ if name in _REGISTRY:
+ raise ValueError(f"tool {name} registered twice")
+ _REGISTRY[name] = ToolDef(name, args_model, description, fn, tracks, languages, cost_hint)
+ return fn
+
+ return deco
+
+
+def get_tool(name: str) -> ToolDef:
+ _ensure_loaded()
+ if name not in _REGISTRY:
+ raise KeyError(f"unknown tool {name!r}; known: {sorted(_REGISTRY)}")
+ return _REGISTRY[name]
+
+
+def list_tools(*, track: str = "", language: str = "") -> list[ToolDef]:
+ _ensure_loaded()
+ out = []
+ for t in _REGISTRY.values():
+ if track and t.tracks and track not in t.tracks:
+ continue
+ if language and t.languages and language not in t.languages:
+ continue
+ out.append(t)
+ return sorted(out, key=lambda t: t.name)
+
+
+def tool_cards(*, track: str = "", language: str = "") -> str:
+ return "\n".join(t.card() for t in list_tools(track=track, language=language))
+
+
+_LOADED = False
+
+
+def _ensure_loaded() -> None:
+ """Import the modules that register tools (idempotent)."""
+ global _LOADED
+ if _LOADED:
+ return
+ _LOADED = True
+ import importlib
+
+ for mod in ("codeverse.spatial.tools",):
+ try:
+ importlib.import_module(mod)
+ except ModuleNotFoundError as e: # during bootstrap only
+ if mod not in str(e):
+ raise
diff --git a/harness/codeverse/spatial/render.py b/harness/codeverse/spatial/render.py
new file mode 100644
index 00000000..35247a82
--- /dev/null
+++ b/harness/codeverse/spatial/render.py
@@ -0,0 +1,258 @@
+"""Headless renders of the canonical GLB (three.js in headless Chrome, GPU when available).
+
+``render_glb`` is the one entry point the tracks/judges/tools use. Results are
+cached under ``<cache_dir>/renders/<sha256(glb)+params>/`` so repeated judge
+calls on the same artifact do not re-render; cached PNGs are copied into the
+requested ``out_dir`` so every call still yields a self-contained directory.
+
+``render_scene`` delegates to ``codeverse.spatial.render_scene`` (package C2).
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import shutil
+import time
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import RenderSet, RenderView
+from codeverse.contracts.plan import CameraPlan
+from codeverse.conventions import OBJECT_VIEWS, ViewPreset
+from codeverse.spatial.node import NodeError, run_node, runtime_js_dir
+from codeverse.spatial.sheet import contact_sheet
+from codeverse.workspace import Workspace
+
+MODES = ("shaded", "wire", "normals", "silhouette", "clay")
+BACKGROUNDS = ("studio", "white", "transparent")
+CACHE_VERSION = 3 # bump when the rig changes in a way that invalidates cached PNGs
+
+
+class RenderError(RuntimeError):
+ """Rendering failed (node/puppeteer error, bad GLB, bad arguments)."""
+
+
+def _sha256_file(path: Path) -> str:
+ h = hashlib.sha256()
+ with path.open("rb") as fh:
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def _views_payload(views: Sequence[ViewPreset]) -> list[dict[str, Any]]:
+ return [{"name": v.name, "azimuth": float(v.azimuth_deg), "elevation": float(v.elevation_deg)} for v in views]
+
+
+def _cache_key(glb: Path, params: dict[str, Any]) -> str:
+ blob = json.dumps({"v": CACHE_VERSION, "glb": _sha256_file(glb), **params}, sort_keys=True)
+ return hashlib.sha256(blob.encode()).hexdigest()[:24]
+
+
+def _rig_signature() -> str:
+ """Hash of the JS rig files so editing the rig invalidates the cache."""
+ rt = runtime_js_dir()
+ h = hashlib.sha256()
+ for rel in ("render_glb.mjs", "lib/browser/render_rig.js", "lib/browser/studio.js", "lib/browser/camera_fit.js"):
+ p = rt / rel
+ if p.is_file():
+ h.update(p.read_bytes())
+ return h.hexdigest()[:12]
+
+
+def render_glb(
+ glb: Path | str,
+ out_dir: Path | str,
+ *,
+ views: Sequence[ViewPreset] | None = None,
+ mode: str = "shaded",
+ width: int = 768,
+ height: int = 768,
+ isolate: list[str] | None = None,
+ explode: float = 0.0,
+ sheet: bool = True,
+ background: str = "studio",
+ anim_time: float | None = None,
+ shadow: bool = True,
+ gpu: str | None = None,
+ timeout_s: float | None = None,
+ use_cache: bool = True,
+) -> RenderSet:
+ """Render ``glb`` from ``views`` (default :data:`OBJECT_VIEWS`) into ``out_dir``.
+
+ Writes ``view_<name>.png`` per view, ``views.json`` (camera data) and, when
+ ``sheet`` is true, ``sheet.png`` (labelled contact sheet). Raises
+ :class:`RenderError` on failure — never returns a partial RenderSet.
+ """
+ glb = Path(glb).resolve()
+ out_dir = Path(out_dir).resolve()
+ if not glb.is_file():
+ raise RenderError(f"GLB not found: {glb}")
+ if mode not in MODES:
+ raise RenderError(f"mode must be one of {MODES}, got {mode!r}")
+ if background not in BACKGROUNDS:
+ raise RenderError(f"background must be one of {BACKGROUNDS}, got {background!r}")
+ view_list = list(views) if views is not None else list(OBJECT_VIEWS)
+ if not view_list:
+ raise RenderError("no views requested")
+ settings = get_settings()
+ gpu = gpu or settings.render.gpu
+ timeout_s = timeout_s or settings.limits.render_timeout_s
+ params: dict[str, Any] = {
+ "views": _views_payload(view_list),
+ "mode": mode,
+ "width": int(width),
+ "height": int(height),
+ "isolate": sorted(isolate or []),
+ "explode": float(explode),
+ "background": background,
+ "anim_time": anim_time,
+ "shadow": bool(shadow),
+ "rig": _rig_signature(),
+ }
+ t0 = time.time()
+ cache_dir = settings.cache_dir / "renders" / _cache_key(glb, params)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ record: dict[str, Any] | None = None
+ if use_cache and (cache_dir / "views.json").is_file():
+ record = _restore_from_cache(cache_dir, out_dir)
+ if record is None:
+ record = _run_render(glb, out_dir, params, gpu=gpu, timeout_s=timeout_s)
+ if use_cache:
+ _store_in_cache(cache_dir, out_dir, record)
+
+ rviews = [
+ RenderView(
+ name=v["name"],
+ path=str(out_dir / f"view_{v['name']}.png"),
+ mode=mode,
+ width=int(v.get("width", width)),
+ height=int(v.get("height", height)),
+ camera_position=tuple(v["camera_position"]) if v.get("camera_position") else None,
+ look_at=tuple(v["look_at"]) if v.get("look_at") else None,
+ fov=v.get("fov"),
+ time_s=anim_time,
+ )
+ for v in record["views"]
+ ]
+ sheet_path = None
+ if sheet:
+ sheet_path = str(
+ contact_sheet(
+ [(v.name, v.path) for v in rviews],
+ out_dir / "sheet.png",
+ cols=settings.render.sheet_cols,
+ tile=settings.render.sheet_tile,
+ )
+ )
+ return RenderSet(
+ views=rviews,
+ contact_sheet=sheet_path,
+ renderer=str(record.get("renderer", "")),
+ duration_ms=int((time.time() - t0) * 1000),
+ console_errors=[str(e) for e in record.get("console_errors", [])],
+ )
+
+
+def _run_render(glb: Path, out_dir: Path, params: dict[str, Any], *, gpu: str, timeout_s: float) -> dict[str, Any]:
+ args = [
+ "--glb", str(glb), "--out", str(out_dir), "--views", json.dumps(params["views"]),
+ "--mode", params["mode"], "--width", str(params["width"]), "--height", str(params["height"]),
+ "--explode", str(params["explode"]), "--background", params["background"],
+ "--gpu", gpu, "--shadow", "1" if params["shadow"] else "0", "--timeout-s", str(int(timeout_s)),
+ ]
+ if params["isolate"]:
+ args += ["--isolate", ",".join(params["isolate"])]
+ if params["anim_time"] is not None:
+ args += ["--anim-time", str(params["anim_time"])]
+ try:
+ res = run_node(runtime_js_dir() / "render_glb.mjs", args, timeout_s=timeout_s + 30)
+ except NodeError as e:
+ detail = ""
+ if e.result and e.result.last_json:
+ detail = json.dumps(e.result.last_json)[:2000]
+ raise RenderError(f"render_glb failed: {e}\n{detail}") from e
+ record = res.last_json
+ if not record or not record.get("ok"):
+ raise RenderError(f"render_glb produced no result record; stderr tail:\n{res.stderr_tail}")
+ for v in record["views"]:
+ if not (out_dir / f"view_{v['name']}.png").is_file():
+ raise RenderError(f"render_glb reported view {v['name']} but the PNG is missing")
+ return record
+
+
+def _store_in_cache(cache_dir: Path, out_dir: Path, record: dict[str, Any]) -> None:
+ tmp = cache_dir.parent / f".{cache_dir.name}.{os.getpid()}.tmp"
+ if tmp.exists():
+ shutil.rmtree(tmp)
+ tmp.mkdir(parents=True)
+ for v in record["views"]:
+ shutil.copy2(out_dir / f"view_{v['name']}.png", tmp / f"view_{v['name']}.png")
+ (tmp / "views.json").write_text(json.dumps(record, indent=1))
+ if cache_dir.exists(): # another process won the race; keep theirs
+ shutil.rmtree(tmp)
+ return
+ tmp.replace(cache_dir)
+
+
+def _restore_from_cache(cache_dir: Path, out_dir: Path) -> dict[str, Any] | None:
+ try:
+ record = json.loads((cache_dir / "views.json").read_text())
+ for v in record["views"]:
+ shutil.copy2(cache_dir / f"view_{v['name']}.png", out_dir / f"view_{v['name']}.png")
+ except (OSError, KeyError, json.JSONDecodeError):
+ return None
+ record["from_cache"] = True
+ (out_dir / "views.json").write_text(json.dumps(record, indent=1))
+ return record
+
+
+def render_turntable(
+ glb: Path | str,
+ out: Path | str,
+ *,
+ n: int = 24,
+ elevation_deg: float = 18.0,
+ mode: str = "shaded",
+ width: int = 512,
+ height: int = 512,
+ fps: int = 12,
+) -> Path:
+ """Render ``n`` azimuth steps and assemble ``out`` (.mp4 via ffmpeg, or .gif via PIL)."""
+ from codeverse.spatial.turntable import assemble_turntable
+
+ out = Path(out)
+ frames_dir = out.parent / f".{out.stem}_frames"
+ frames_dir.mkdir(parents=True, exist_ok=True)
+ views = [ViewPreset(f"tt{i:03d}", 360.0 * i / n, elevation_deg) for i in range(n)]
+ rs = render_glb(glb, frames_dir, views=views, mode=mode, width=width, height=height, sheet=False)
+ return assemble_turntable([Path(v.path) for v in rs.views], out, fps=fps)
+
+
+def render_scene(
+ ws: Workspace,
+ out_dir: Path | str,
+ *,
+ cameras: list[CameraPlan] | None = None,
+ orbit: bool = True,
+ times: Sequence[float] = (0.0, 1.5),
+ width: int = 1024,
+ height: int = 576,
+ sheet: bool = True,
+) -> RenderSet:
+ """Scene renders: delegates to ``codeverse.spatial.render_scene`` (package C2)."""
+ try:
+ from codeverse.spatial.render_scene import render_scene as _impl
+ except ImportError as e: # pragma: no cover - until C2 lands
+ raise NotImplementedError(
+ "render_scene is implemented by codeverse.spatial.render_scene (runtime_js/render_scene.mjs); "
+ f"module not importable: {e}"
+ ) from e
+ return _impl(ws, Path(out_dir), cameras=cameras, orbit=orbit, times=times, width=width, height=height, sheet=sheet)
+
+
+__all__ = ["render_glb", "render_turntable", "render_scene", "RenderError", "MODES", "BACKGROUNDS"]
diff --git a/harness/codeverse/spatial/render_scene.py b/harness/codeverse/spatial/render_scene.py
new file mode 100644
index 00000000..239328a8
--- /dev/null
+++ b/harness/codeverse/spatial/render_scene.py
@@ -0,0 +1,234 @@
+"""Render a ``scene_threejs`` workspace through the node host (headless GPU Chrome).
+
+``render_scene(ws, out_dir, ...)`` drives ``runtime_js/render_scene.mjs``:
+authored cameras + an overview orbit rig (``conventions.SCENE_VIEWS``) at one
+or more animation times, deterministic instruments (console/shader errors,
+fps, census, camera checks) and a labelled contact sheet. Returns a
+``RenderSet``; the full instrument payload is left at ``out_dir/metrics.json``.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import signal
+import subprocess
+import time
+from collections.abc import Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import RenderSet, RenderView
+from codeverse.contracts.plan import CameraPlan
+from codeverse.conventions import SCENE_VIEWS, ViewPreset
+from codeverse.workspace import Workspace
+
+
+class SceneRenderError(RuntimeError):
+ """The node driver could not run (missing node/deps, timeout, crash)."""
+
+
+@dataclass
+class NodeResult:
+ """Outcome of one node driver run; ``summary`` is the last stdout JSON line."""
+
+ returncode: int
+ stdout: str
+ stderr: str
+ summary: dict[str, Any]
+ duration_ms: int
+
+
+def runtime_js_dir() -> Path:
+ return get_settings().runtime_js_dir()
+
+
+def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd: Path | None = None) -> NodeResult:
+ """Run ``runtime_js/<script>`` with node; kill the whole process group on timeout.
+
+ Goes through ``codeverse.spatial.node.run_node`` (package C1) when it is
+ importable, else a local equivalent. The driver prints a JSON summary as
+ its LAST stdout line; exit code 2/3 means the driver itself failed →
+ ``SceneRenderError``.
+ """
+ rt = runtime_js_dir()
+ path = rt / script
+ if not path.is_file():
+ raise SceneRenderError(f"missing node driver {path}")
+ env_extra: dict[str, str] = {}
+ gpu = get_settings().render.gpu
+ if gpu and "C3V_RENDER_GPU" not in os.environ:
+ env_extra["C3V_RENDER_GPU"] = gpu
+ try:
+ from codeverse.spatial.node import NodeError, run_node
+ except ImportError: # pragma: no cover - C1 not present
+ rc, out, err, dur = _run_node_local(path, args, timeout_s=timeout_s, cwd=cwd or rt, env_extra=env_extra)
+ else:
+ try:
+ r = run_node(path, list(map(str, args)), cwd=cwd or rt, timeout_s=timeout_s, env_extra=env_extra, check=False)
+ except NodeError as e:
+ raise SceneRenderError(f"{script} could not run: {e}") from e
+ if r.timed_out:
+ raise SceneRenderError(f"{script} timed out after {timeout_s:.0f}s\n{r.stderr_tail}")
+ rc, out, err, dur = r.rc, r.stdout, r.stderr, r.duration_ms
+ summary = _last_json_line(out)
+ if rc in (2, 3) or (rc != 0 and not summary):
+ raise SceneRenderError(
+ f"{script} failed (exit {rc}): {summary.get('error') if summary else ''}\n"
+ f"stderr tail: {(err or '')[-2000:]}\nstdout tail: {(out or '')[-1000:]}"
+ )
+ return NodeResult(rc, out, err, summary, dur)
+
+
+def _run_node_local(path: Path, args: Sequence[str], *, timeout_s: float, cwd: Path, env_extra: dict[str, str]) -> tuple[int, str, str, int]:
+ node = get_settings().binaries.node or "node"
+ env = dict(os.environ)
+ env.setdefault("NODE_PATH", str(path.parent / "node_modules"))
+ env.update(env_extra)
+ t0 = time.time()
+ proc = subprocess.Popen(
+ [node, str(path), *map(str, args)], cwd=str(cwd), env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+ text=True, start_new_session=True,
+ )
+ try:
+ out, err = proc.communicate(timeout=timeout_s)
+ except subprocess.TimeoutExpired:
+ with contextlib.suppress(ProcessLookupError):
+ os.killpg(proc.pid, signal.SIGKILL)
+ out, err = proc.communicate()
+ raise SceneRenderError(f"{path.name} timed out after {timeout_s:.0f}s\n{(err or '')[-2000:]}") from None
+ return proc.returncode, out, err, int((time.time() - t0) * 1000)
+
+
+def _last_json_line(stdout: str) -> dict[str, Any]:
+ for line in reversed((stdout or "").splitlines()):
+ line = line.strip()
+ if line.startswith("{") and line.endswith("}"):
+ try:
+ return json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ return {}
+
+
+def _camera_json(cams: Sequence[CameraPlan]) -> str:
+ return json.dumps([
+ {"name": c.name, "position": list(c.position), "lookAt": list(c.look_at), "fov": c.fov} for c in cams
+ ])
+
+
+def _views_json(views: Sequence[ViewPreset]) -> str:
+ return json.dumps([{"name": v.name, "azimuth": v.azimuth_deg, "elevation": v.elevation_deg} for v in views])
+
+
+def _contact_sheet(images: list[tuple[str, Path]], out: Path, cols: int, tile: int) -> Path | None:
+ """Use ``codeverse.spatial.sheet.contact_sheet`` when present, else a local PIL grid."""
+ if not images:
+ return None
+ try:
+ from codeverse.spatial.sheet import contact_sheet # package C1
+
+ return Path(contact_sheet(images, out, cols=cols, tile=tile))
+ except ImportError:
+ return _local_contact_sheet(images, out, cols=cols, tile=tile)
+
+
+def _local_contact_sheet(images: list[tuple[str, Path]], out: Path, *, cols: int = 4, tile: int = 384) -> Path:
+ from PIL import Image, ImageDraw
+
+ cols = max(1, min(cols, len(images)))
+ rows = (len(images) + cols - 1) // cols
+ th = int(tile * 9 / 16) + 18
+ sheet = Image.new("RGB", (cols * tile, rows * th), (24, 24, 24))
+ draw = ImageDraw.Draw(sheet)
+ for i, (label, p) in enumerate(images):
+ x, y = (i % cols) * tile, (i // cols) * th
+ try:
+ im = Image.open(p).convert("RGB")
+ im.thumbnail((tile, th - 18))
+ sheet.paste(im, (x + (tile - im.width) // 2, y + 18))
+ except OSError:
+ draw.rectangle([x, y + 18, x + tile, y + th], fill=(60, 0, 0))
+ draw.rectangle([x, y, x + tile, y + 18], fill=(0, 0, 0))
+ draw.text((x + 4, y + 3), label[: tile // 7], fill=(255, 255, 255))
+ out.parent.mkdir(parents=True, exist_ok=True)
+ sheet.save(out)
+ return out
+
+
+def render_scene(
+ ws: Workspace,
+ out_dir: Path,
+ *,
+ cameras: list[CameraPlan] | None = None,
+ orbit: bool = True,
+ times: Sequence[float] = (0.0, 1.5),
+ width: int = 1024,
+ height: int = 576,
+ sheet: bool = True,
+ orbit_views: Sequence[ViewPreset] = SCENE_VIEWS,
+ fps_seconds: float = 2.0,
+ counterfactual: bool = False,
+ timeout_s: float | None = None,
+) -> RenderSet:
+ """Render authored (+ orbit) views at ``times``; returns a RenderSet.
+
+ ``cameras=None`` uses the cameras authored in ``createScene()``. A scene
+ that fails to boot yields an empty RenderSet whose ``console_errors`` say
+ why (the build gate normally catches that earlier); a driver failure raises
+ ``SceneRenderError``.
+ """
+ out_dir = Path(out_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ settings = get_settings()
+ args: list[str] = [
+ "--ws", str(ws.root), "--out", str(out_dir),
+ "--cameras", _camera_json(cameras) if cameras else "authored",
+ "--orbit-views", _views_json(orbit_views) if orbit else "none",
+ "--times", ",".join(f"{t:g}" for t in times),
+ "--width", str(width), "--height", str(height),
+ "--fps-seconds", f"{fps_seconds:g}",
+ ]
+ if counterfactual:
+ args.append("--counterfactual")
+ tmo = timeout_s or settings.limits.render_timeout_s
+ args += ["--timeout-ms", str(int(tmo * 1000))]
+ res = run_scene_script("render_scene.mjs", args, timeout_s=tmo + 30)
+ metrics = _read_json(out_dir / "metrics.json")
+ views: list[RenderView] = []
+ for v in metrics.get("views", []):
+ views.append(RenderView(
+ name=v["name"], path=str(out_dir / v["path"]), mode="shaded", width=width, height=height,
+ camera_position=tuple(v["position"]), look_at=tuple(v["lookAt"]), fov=v.get("fov"),
+ time_s=v.get("time_s"),
+ ))
+ sheet_path = None
+ if sheet and views:
+ labelled = [(f"{v.name} t={v.time_s:g}", Path(v.path)) for v in views if "_nocustom" not in v.name]
+ sheet_path = _contact_sheet(labelled, out_dir / "sheet.png", settings.render.sheet_cols, settings.render.sheet_tile)
+ fps = (metrics.get("fps") or {}).get("fps")
+ errors = list(metrics.get("console_errors", []))
+ for e in metrics.get("shader_errors", []):
+ errors.append(f"shader[{e.get('stage')}]: {e.get('message')} — {e.get('source_line', '')}".strip())
+ if not metrics and res.summary.get("error"):
+ errors.append(str(res.summary["error"]))
+ return RenderSet(
+ views=views, contact_sheet=str(sheet_path) if sheet_path else None,
+ renderer=str(metrics.get("renderer") or res.summary.get("renderer") or ""),
+ duration_ms=res.duration_ms, console_errors=errors,
+ fps=float(fps) if fps is not None else None,
+ )
+
+
+def _read_json(p: Path) -> dict[str, Any]:
+ if not p.is_file():
+ return {}
+ return json.loads(p.read_text())
+
+
+def read_metrics(out_dir: Path) -> dict[str, Any]:
+ """Full instrument payload written by the driver (census, camera_checks, ...)."""
+ return _read_json(Path(out_dir) / "metrics.json")
diff --git a/harness/codeverse/spatial/sections.py b/harness/codeverse/spatial/sections.py
new file mode 100644
index 00000000..b39ebde7
--- /dev/null
+++ b/harness/codeverse/spatial/sections.py
@@ -0,0 +1,268 @@
+"""Cross-sections of the canonical GLB: a labelled PNG + loop/area numbers.
+
+``cross_section`` slices every (selected) part with an axis-aligned plane,
+projects the resulting loops onto the two remaining axes and rasterises them
+with PIL — one colour per part, a scale bar, axis labels and a legend. The
+numbers use shapely (even-odd fill) so a hollow tube reports its hollow ratio.
+
+``slices_sheet`` tiles ``n`` evenly spaced sections along an axis into one grid
+image — the cheap way to inspect interiors along a whole object.
+"""
+
+from __future__ import annotations
+
+import time
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import numpy as np
+import trimesh
+from PIL import Image, ImageDraw, ImageFont
+
+from codeverse.spatial.measure import GlbLoadError, load_scene, merged_mesh, part_meshes
+from codeverse.spatial.registry import Observation
+
+_AXIS_INDEX = {"x": 0, "y": 1, "z": 2}
+#: which two axes are drawn (horizontal, vertical) for a slicing axis
+_PLANE_AXES = {"x": ("z", "y"), "y": ("x", "z"), "z": ("x", "y")}
+_PALETTE = [
+ (230, 80, 60), (60, 130, 230), (50, 170, 90), (240, 160, 30), (150, 80, 200),
+ (30, 180, 190), (200, 60, 150), (120, 120, 40), (90, 90, 90), (250, 110, 140),
+]
+
+
+@dataclass
+class SectionData:
+ axis: str
+ at_m: float
+ loops: dict[str, list[np.ndarray]] = field(default_factory=dict) # part → list of (N,2) loops
+ n_loops: int = 0
+ total_area_m2: float = 0.0
+ hollow_ratio: float = 0.0
+ bbox_min: np.ndarray | None = None
+ bbox_max: np.ndarray | None = None
+
+
+def _font(size: int = 13) -> ImageFont.ImageFont:
+ try:
+ return ImageFont.truetype("DejaVuSans.ttf", size)
+ except Exception:
+ return ImageFont.load_default()
+
+
+def _section_loops(mesh: trimesh.Trimesh, axis: str, at: float) -> list[np.ndarray]:
+ """Closed 2D loops (in plane axes) of ``mesh`` cut at ``axis = at``."""
+ normal = np.zeros(3)
+ normal[_AXIS_INDEX[axis]] = 1.0
+ origin = normal * at
+ try:
+ path = mesh.section(plane_origin=origin, plane_normal=normal)
+ except Exception:
+ return []
+ if path is None:
+ return []
+ h, v = (_AXIS_INDEX[a] for a in _PLANE_AXES[axis])
+ loops = []
+ for poly in path.discrete:
+ pts = np.asarray(poly)[:, [h, v]]
+ if len(pts) >= 3:
+ loops.append(pts)
+ return loops
+
+
+def _even_odd_area(loops: Sequence[np.ndarray]) -> tuple[float, float]:
+ """(filled area, hollow ratio) using even-odd fill of all loops (shapely)."""
+ from shapely.geometry import Polygon
+ from shapely.ops import unary_union
+
+ polys = []
+ for lp in loops:
+ try:
+ p = Polygon(lp)
+ if not p.is_valid:
+ p = p.buffer(0)
+ if p.area > 0:
+ polys.append(p)
+ except Exception:
+ continue
+ if not polys:
+ return 0.0, 0.0
+ polys.sort(key=lambda p: -p.area)
+ filled = polys[0]
+ for p in polys[1:]:
+ filled = filled.symmetric_difference(p)
+ outer = unary_union(polys).area
+ hollow = 1.0 - filled.area / outer if outer > 0 else 0.0
+ return float(filled.area), float(max(0.0, min(1.0, hollow)))
+
+
+def compute_section(parts: dict[str, trimesh.Trimesh], axis: str, at_m: float) -> SectionData:
+ """Slice ``parts`` (world-space meshes) at ``axis = at_m``."""
+ data = SectionData(axis=axis, at_m=at_m)
+ whole = merged_mesh(parts) # type: ignore[arg-type]
+ if whole is not None:
+ data.bbox_min, data.bbox_max = whole.bounds
+ all_loops: list[np.ndarray] = []
+ for name, mesh in parts.items():
+ loops = _section_loops(mesh, axis, at_m)
+ if loops:
+ data.loops[name] = loops
+ all_loops.extend(loops)
+ data.n_loops = len(all_loops)
+ data.total_area_m2, data.hollow_ratio = _even_odd_area(all_loops)
+ return data
+
+
+def draw_section(data: SectionData, out_png: Path, *, size: int = 512, title: str = "") -> Path:
+ """Rasterise ``data`` to a labelled PNG (plane axes, scale bar, legend)."""
+ h_ax, v_ax = _PLANE_AXES[data.axis]
+ hi, vi = _AXIS_INDEX[h_ax], _AXIS_INDEX[v_ax]
+ img = Image.new("RGB", (size, size), (250, 250, 250))
+ d = ImageDraw.Draw(img, "RGBA")
+ font, small = _font(13), _font(11)
+ margin = 36
+ if data.bbox_min is None:
+ d.text((margin, margin), "empty model", fill=(0, 0, 0), font=font)
+ img.save(out_png)
+ return out_png
+ lo = np.array([data.bbox_min[hi], data.bbox_min[vi]])
+ hi_ = np.array([data.bbox_max[hi], data.bbox_max[vi]])
+ span = float(max(np.max(hi_ - lo), 1e-6))
+ scale = (size - 2 * margin) / span
+ centre = (lo + hi_) / 2
+
+ def to_px(p: np.ndarray) -> tuple[float, float]:
+ x = size / 2 + (p[0] - centre[0]) * scale
+ y = size / 2 - (p[1] - centre[1]) * scale
+ return (float(x), float(y))
+
+ # ground/axes reference (dashed bbox of the whole object in this plane)
+ (x0b, y0b), (x1b, y1b) = to_px(lo), to_px(hi_)
+ d.rectangle([min(x0b, x1b), min(y0b, y1b), max(x0b, x1b), max(y0b, y1b)], outline=(190, 190, 190), width=1)
+ legend = []
+ for i, (name, loops) in enumerate(data.loops.items()):
+ col = _PALETTE[i % len(_PALETTE)]
+ for lp in loops:
+ pts = [to_px(p) for p in lp]
+ if len(pts) >= 3:
+ d.polygon(pts, fill=col + (70,), outline=col + (255,))
+ legend.append((name, col))
+ # legend (top-left), capped
+ y = 6
+ for name, col in legend[:12]:
+ d.rectangle([6, y + 2, 16, y + 12], fill=col)
+ d.text((20, y), name, fill=(20, 20, 20), font=small)
+ y += 14
+ if len(legend) > 12:
+ d.text((20, y), f"… +{len(legend) - 12} parts", fill=(20, 20, 20), font=small)
+ # title + axes
+ ttl = title or f"section {data.axis} = {data.at_m:.3f} m"
+ d.text((size - 6 - d.textlength(ttl, font=font), 6), ttl, fill=(0, 0, 0), font=font)
+ d.text((size - 16, size / 2 - 8), h_ax, fill=(120, 0, 0), font=font)
+ d.text((size / 2 - 4, 20), v_ax, fill=(0, 90, 0), font=font)
+ # scale bar: nice length ≈ 1/4 of span
+ nice = 10 ** np.floor(np.log10(span / 4))
+ bar = float(nice * max(1, round(span / 4 / nice)))
+ x0, y0 = margin, size - margin / 2
+ d.line([(x0, y0), (x0 + bar * scale, y0)], fill=(0, 0, 0), width=2)
+ d.text((x0, y0 - 16), f"{bar * 100:g} cm", fill=(0, 0, 0), font=small)
+ stats = f"{data.n_loops} loops · area {data.total_area_m2 * 1e4:.1f} cm² · hollow {data.hollow_ratio:.0%}"
+ d.text((size - 6 - d.textlength(stats, font=small), size - 18), stats, fill=(0, 0, 0), font=small)
+ out_png.parent.mkdir(parents=True, exist_ok=True)
+ img.save(out_png)
+ return out_png
+
+
+def _resolve_at(parts: dict[str, trimesh.Trimesh], axis: str, at: float, absolute: bool) -> float:
+ whole = merged_mesh(parts) # type: ignore[arg-type]
+ if whole is None:
+ return at
+ i = _AXIS_INDEX[axis]
+ lo, hi = float(whole.bounds[0][i]), float(whole.bounds[1][i])
+ if absolute:
+ return at
+ return lo + (hi - lo) * float(np.clip(at, 0.0, 1.0))
+
+
+def _load_parts(glb: Path | str, parts: Sequence[str] | None) -> dict[str, trimesh.Trimesh]:
+ all_parts = {k: v for k, v in part_meshes(load_scene(glb)).items() if v is not None and len(v.faces)}
+ if parts:
+ sel = {k: v for k, v in all_parts.items() if k in set(parts)}
+ missing = [p for p in parts if p not in all_parts]
+ if missing:
+ raise KeyError(f"unknown part(s) {missing}; available: {sorted(all_parts)}")
+ return sel
+ return all_parts
+
+
+def cross_section(
+ glb: Path | str,
+ axis: str,
+ at: float,
+ out_png: Path | str,
+ *,
+ parts: Sequence[str] | None = None,
+ absolute: bool = False,
+ size: int = 512,
+) -> Observation:
+ """Slice the GLB at ``axis = at`` (fraction of the bbox, or meters if ``absolute``)."""
+ t0 = time.time()
+ axis = axis.lower()
+ if axis not in _AXIS_INDEX:
+ return Observation.error(f"axis must be one of x|y|z, got {axis!r}")
+ try:
+ sel = _load_parts(glb, parts)
+ except (GlbLoadError, KeyError) as e:
+ return Observation.error(f"cross_section: {e}")
+ if not sel:
+ return Observation.error("cross_section: no mesh parts in the GLB")
+ at_m = _resolve_at(sel, axis, at, absolute)
+ data = compute_section(sel, axis, at_m)
+ out = draw_section(data, Path(out_png), size=size)
+ per_part = {n: len(loops) for n, loops in data.loops.items()}
+ cut = ", ".join(f"{n}({k})" for n, k in list(per_part.items())[:12]) or "nothing"
+ text = (
+ f"cross-section {axis}={at_m:.3f} m ({'absolute' if absolute else f'{at:.2f} of bbox'}): "
+ f"{data.n_loops} loop(s), filled area {data.total_area_m2 * 1e4:.1f} cm², hollow ratio {data.hollow_ratio:.0%}. "
+ f"Parts cut (loops): {cut}. Plane axes: {_PLANE_AXES[axis][0]} horizontal, {_PLANE_AXES[axis][1]} vertical."
+ )
+ numbers = {"axis": axis, "at_m": round(at_m, 4), "n_loops": data.n_loops,
+ "total_area_m2": round(data.total_area_m2, 6), "hollow_ratio": round(data.hollow_ratio, 3),
+ "parts_cut": per_part}
+ return Observation(ok=True, text=text, numbers=numbers, images=[str(out)], duration_ms=int((time.time() - t0) * 1000))
+
+
+def slices_sheet(glb: Path | str, axis: str, n: int, out_png: Path | str, *, parts: Sequence[str] | None = None, tile: int = 320) -> Observation:
+ """``n`` evenly spaced sections along ``axis`` tiled into one labelled grid."""
+ t0 = time.time()
+ axis = axis.lower()
+ if axis not in _AXIS_INDEX:
+ return Observation.error(f"axis must be one of x|y|z, got {axis!r}")
+ n = int(max(1, min(n, 12)))
+ try:
+ sel = _load_parts(glb, parts)
+ except (GlbLoadError, KeyError) as e:
+ return Observation.error(f"slices_sheet: {e}")
+ if not sel:
+ return Observation.error("slices_sheet: no mesh parts in the GLB")
+ out = Path(out_png)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ cols = min(n, 4)
+ rows = int(np.ceil(n / cols))
+ sheet = Image.new("RGB", (cols * tile, rows * tile), (255, 255, 255))
+ numbers: dict[str, object] = {"axis": axis, "n": n, "slices": []}
+ for i in range(n):
+ frac = (i + 0.5) / n
+ at_m = _resolve_at(sel, axis, frac, False)
+ data = compute_section(sel, axis, at_m)
+ tmp = out.with_name(f"{out.stem}_{i}.png")
+ draw_section(data, tmp, size=tile, title=f"{axis}={at_m:.3f} m ({frac:.2f})")
+ sheet.paste(Image.open(tmp), ((i % cols) * tile, (i // cols) * tile))
+ tmp.unlink(missing_ok=True)
+ numbers["slices"].append({"at_m": round(at_m, 4), "n_loops": data.n_loops, # type: ignore[attr-defined]
+ "area_m2": round(data.total_area_m2, 6), "hollow_ratio": round(data.hollow_ratio, 3)})
+ sheet.save(out)
+ summary = "; ".join(f"{s['at_m']:.3f}m: {s['n_loops']} loops, hollow {s['hollow_ratio']:.0%}" for s in numbers["slices"]) # type: ignore[index]
+ return Observation(ok=True, text=f"{n} sections along {axis}: {summary}", numbers=numbers, images=[str(out)],
+ duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse/spatial/sheet.py b/harness/codeverse/spatial/sheet.py
new file mode 100644
index 00000000..9284a767
--- /dev/null
+++ b/harness/codeverse/spatial/sheet.py
@@ -0,0 +1,84 @@
+"""Contact sheets: a deterministic labelled grid of PNGs (PIL only).
+
+Used for judge inputs and agent observations: one image, every view labelled
+under its tile, fixed tile size so the VLM sees consistent scale.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Sequence
+from pathlib import Path
+
+from PIL import Image, ImageDraw, ImageFont
+
+LABEL_H = 28
+PAD = 6
+BG = (250, 250, 250)
+LABEL_BG = (34, 34, 38)
+LABEL_FG = (240, 240, 240)
+
+
+def _font(size: int = 15) -> ImageFont.ImageFont | ImageFont.FreeTypeFont:
+ for name in ("DejaVuSans.ttf", "DejaVuSansMono.ttf", "LiberationSans-Regular.ttf", "Arial.ttf"):
+ try:
+ return ImageFont.truetype(name, size)
+ except OSError:
+ continue
+ return ImageFont.load_default()
+
+
+def _fit(im: Image.Image, tile: int) -> Image.Image:
+ """Letterbox ``im`` into a tile x tile square on the sheet background."""
+ im = im.convert("RGBA")
+ scale = min(tile / im.width, tile / im.height)
+ w, h = max(1, round(im.width * scale)), max(1, round(im.height * scale))
+ im = im.resize((w, h), Image.LANCZOS)
+ canvas = Image.new("RGBA", (tile, tile), BG + (255,))
+ canvas.alpha_composite(im, ((tile - w) // 2, (tile - h) // 2))
+ return canvas.convert("RGB")
+
+
+def contact_sheet(
+ images: Sequence[tuple[str, str | Path]],
+ out: Path | str,
+ cols: int = 4,
+ tile: int = 384,
+ label: bool = True,
+) -> Path:
+ """Write a grid of ``(label, png_path)`` tiles to ``out`` and return it.
+
+ Missing/unreadable images become a grey tile with the label so the sheet
+ never silently drops a view. Output is deterministic for identical inputs.
+ """
+ if not images:
+ raise ValueError("contact_sheet: no images")
+ cols = max(1, min(cols, len(images)))
+ rows = math.ceil(len(images) / cols)
+ cell_h = tile + (LABEL_H if label else 0)
+ sheet = Image.new("RGB", (cols * (tile + PAD) + PAD, rows * (cell_h + PAD) + PAD), BG)
+ draw = ImageDraw.Draw(sheet)
+ font = _font()
+ for i, (text, path) in enumerate(images):
+ x = PAD + (i % cols) * (tile + PAD)
+ y = PAD + (i // cols) * (cell_h + PAD)
+ p = Path(path)
+ try:
+ with Image.open(p) as im:
+ tile_im = _fit(im, tile)
+ except (OSError, ValueError):
+ tile_im = Image.new("RGB", (tile, tile), (200, 200, 200))
+ ImageDraw.Draw(tile_im).text((8, 8), "missing image", fill=(90, 0, 0), font=font)
+ sheet.paste(tile_im, (x, y))
+ if label:
+ draw.rectangle([x, y + tile, x + tile - 1, y + tile + LABEL_H - 1], fill=LABEL_BG)
+ txt = str(text)
+ tw = draw.textlength(txt, font=font)
+ while tw > tile - 8 and len(txt) > 4:
+ txt = txt[:-2] + "…"
+ tw = draw.textlength(txt, font=font)
+ draw.text((x + (tile - tw) / 2, y + tile + 6), txt, fill=LABEL_FG, font=font)
+ out = Path(out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ sheet.save(out, format="PNG", optimize=False)
+ return out
diff --git a/harness/codeverse/spatial/silhouette.py b/harness/codeverse/spatial/silhouette.py
new file mode 100644
index 00000000..3d517aa1
--- /dev/null
+++ b/harness/codeverse/spatial/silhouette.py
@@ -0,0 +1,192 @@
+"""Silhouette comparison between a render and a reference image.
+
+Foreground mask (documented limits):
+* PNG with an alpha channel → ``alpha > 0`` (renders on transparent background).
+* Otherwise the background colour is the median of the border pixels; pixels
+ farther than ``tol`` from it are "object-coloured", and the background region
+ is the flood fill from the image border through non-object pixels. Enclosed
+ pockets therefore count as *foreground* (a chair's back is one silhouette),
+ which is what we want for shape comparison but hides interior holes.
+* Works for silhouette-mode renders and product photos on a plain backdrop.
+ Shaded renders with a contact shadow include the shadow in the mask (pale
+ objects on pale studio backdrops are the weak case — always render the
+ *render* side in ``silhouette`` mode); textured / gradient backgrounds
+ over-segment (``reliable`` becomes False when a fill is < 0.2 % or > 95 %).
+
+IoU is computed on **bbox-normalised** masks at 256² (each silhouette cropped
+to its bounding box and scaled to fit, aspect preserved), so framing and scale
+differences do not dominate — ``aspect_ratio_err`` carries the shape-proportion
+signal separately.
+"""
+
+from __future__ import annotations
+
+from collections import deque
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+from PIL import Image
+
+from codeverse.contracts.artifacts import RenderView
+
+MASK_SIZE = 256
+#: colour-distance tolerance (0-441) from the border colour: adaptive between these bounds
+#: (≈ BORDER_TOL_BASE + BORDER_TOL_K × border std), so flat backdrops get a tight threshold
+BORDER_TOL_MIN = 10.0
+BORDER_TOL_MAX = 40.0
+BORDER_TOL_K = 4.0
+_MIN_FILL = 0.002
+
+
+def _load_rgba(path: Path | str, size: int) -> np.ndarray:
+ img = Image.open(path).convert("RGBA")
+ img.thumbnail((size, size), Image.LANCZOS)
+ return np.asarray(img, dtype=np.float32)
+
+
+def _flood_outside(bg_like: np.ndarray) -> np.ndarray:
+ """Pixels reachable from the border through ``bg_like`` (4-connected)."""
+ try:
+ from scipy import ndimage
+
+ labels, _ = ndimage.label(bg_like)
+ border = np.unique(np.concatenate([labels[0], labels[-1], labels[:, 0], labels[:, -1]]))
+ border = border[border > 0]
+ return np.isin(labels, border)
+ except Exception:
+ pass
+ h, w = bg_like.shape
+ seen = np.zeros_like(bg_like, dtype=bool)
+ q: deque[tuple[int, int]] = deque()
+ for x in range(w):
+ for y in (0, h - 1):
+ if bg_like[y, x] and not seen[y, x]:
+ seen[y, x] = True
+ q.append((y, x))
+ for y in range(h):
+ for x in (0, w - 1):
+ if bg_like[y, x] and not seen[y, x]:
+ seen[y, x] = True
+ q.append((y, x))
+ while q:
+ y, x = q.popleft()
+ for ny, nx in ((y - 1, x), (y + 1, x), (y, x - 1), (y, x + 1)):
+ if 0 <= ny < h and 0 <= nx < w and bg_like[ny, nx] and not seen[ny, nx]:
+ seen[ny, nx] = True
+ q.append((ny, nx))
+ return seen
+
+
+def foreground_mask(path: Path | str, size: int = MASK_SIZE, tol: float | None = None) -> np.ndarray:
+ """Boolean foreground mask (≤ size², aspect preserved). See module docstring.
+
+ ``tol`` overrides the adaptive colour tolerance (useful for tests).
+ """
+ rgba = _load_rgba(path, size)
+ alpha = rgba[..., 3]
+ if alpha.min() < 250: # has real transparency → trust it
+ return alpha > 8
+ rgb = rgba[..., :3]
+ border = np.concatenate([rgb[0], rgb[-1], rgb[:, 0], rgb[:, -1]], axis=0)
+ bg = np.median(border, axis=0)
+ if tol is None:
+ spread = float(np.linalg.norm(border - bg, axis=-1).std())
+ tol = float(np.clip(BORDER_TOL_MIN + BORDER_TOL_K * spread, BORDER_TOL_MIN, BORDER_TOL_MAX))
+ dist = np.linalg.norm(rgb - bg, axis=-1)
+ bg_like = dist <= tol
+ outside = _flood_outside(bg_like)
+ return ~outside
+
+
+def _normalise(mask: np.ndarray, size: int = MASK_SIZE) -> tuple[np.ndarray, float]:
+ """Crop to the mask bbox and scale into a size² canvas; returns (canvas, aspect w/h)."""
+ ys, xs = np.nonzero(mask)
+ canvas = np.zeros((size, size), dtype=bool)
+ if len(ys) == 0:
+ return canvas, 0.0
+ crop = mask[ys.min(): ys.max() + 1, xs.min(): xs.max() + 1]
+ h, w = crop.shape
+ aspect = w / h if h else 0.0
+ s = (size - 2) / max(h, w)
+ nh, nw = max(1, int(round(h * s))), max(1, int(round(w * s)))
+ img = Image.fromarray((crop * 255).astype(np.uint8)).resize((nw, nh), Image.BILINEAR)
+ arr = np.asarray(img) > 127
+ y0, x0 = (size - nh) // 2, (size - nw) // 2
+ canvas[y0: y0 + nh, x0: x0 + nw] = arr
+ return canvas, aspect
+
+
+def _diff_image(a: np.ndarray, b: np.ndarray, out: Path) -> Path:
+ """Overlay: red = reference only, blue = render only, grey = both."""
+ h, w = a.shape
+ img = np.full((h, w, 3), 255, dtype=np.uint8)
+ both = a & b
+ img[both] = (150, 150, 150)
+ img[a & ~b] = (220, 60, 60)
+ img[b & ~a] = (60, 90, 220)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ Image.fromarray(img).save(out)
+ return out
+
+
+def compare_silhouette(render_png: Path | str, reference_png: Path | str, *, diff_png: Path | str | None = None) -> dict[str, Any]:
+ """IoU + fills + aspect error between a render and a reference image.
+
+ Returns ``{iou, ref_fill, render_fill, aspect_ratio_err, ref_aspect, render_aspect,
+ reliable, diff_png_path?}``. ``reliable`` is False when either mask is
+ empty or fills the whole frame (background estimate failed).
+ """
+ ref_mask = foreground_mask(reference_png)
+ ren_mask = foreground_mask(render_png)
+ ref_fill = float(ref_mask.mean())
+ ren_fill = float(ren_mask.mean())
+ ref_n, ref_aspect = _normalise(ref_mask)
+ ren_n, ren_aspect = _normalise(ren_mask)
+ inter = float(np.logical_and(ref_n, ren_n).sum())
+ union = float(np.logical_or(ref_n, ren_n).sum())
+ iou = inter / union if union > 0 else 0.0
+ aspect_err = abs(ren_aspect - ref_aspect) / ref_aspect if ref_aspect > 0 else 1.0
+ reliable = _MIN_FILL < ref_fill < 0.95 and _MIN_FILL < ren_fill < 0.95
+ out: dict[str, Any] = {
+ "iou": round(iou, 4), "ref_fill": round(ref_fill, 4), "render_fill": round(ren_fill, 4),
+ "aspect_ratio_err": round(aspect_err, 4), "ref_aspect": round(ref_aspect, 4),
+ "render_aspect": round(ren_aspect, 4), "reliable": reliable,
+ }
+ if diff_png is not None:
+ out["diff_png_path"] = str(_diff_image(ref_n, ren_n, Path(diff_png)))
+ return out
+
+
+def silhouette_series(
+ renders: Sequence[RenderView],
+ reference_imgs: Sequence[Path | str],
+ *,
+ diff_dir: Path | str | None = None,
+) -> list[dict[str, Any]]:
+ """For each reference image pick the best-matching render view (by IoU).
+
+ Returns one dict per reference: ``{reference, best_view, iou, aspect_ratio_err,
+ all: {view: iou}}`` (+ ``diff_png_path`` when ``diff_dir`` is given).
+ """
+ out: list[dict[str, Any]] = []
+ for i, ref in enumerate(reference_imgs):
+ scores: dict[str, dict[str, Any]] = {}
+ for rv in renders:
+ try:
+ scores[rv.name] = compare_silhouette(rv.path, ref)
+ except Exception as e: # unreadable image → skip that view
+ scores[rv.name] = {"iou": 0.0, "error": f"{type(e).__name__}: {e}"}
+ if not scores:
+ out.append({"reference": str(ref), "best_view": None, "iou": 0.0, "all": {}})
+ continue
+ best = max(scores, key=lambda k: scores[k].get("iou", 0.0))
+ rec: dict[str, Any] = {"reference": str(ref), "best_view": best, "iou": scores[best].get("iou", 0.0),
+ "aspect_ratio_err": scores[best].get("aspect_ratio_err"),
+ "all": {k: v.get("iou", 0.0) for k, v in scores.items()}}
+ if diff_dir is not None:
+ rv = next(r for r in renders if r.name == best)
+ rec.update(compare_silhouette(rv.path, ref, diff_png=Path(diff_dir) / f"silhouette_diff_ref{i}_{best}.png"))
+ out.append(rec)
+ return out
diff --git a/harness/codeverse/spatial/tool_common.py b/harness/codeverse/spatial/tool_common.py
new file mode 100644
index 00000000..78b34798
--- /dev/null
+++ b/harness/codeverse/spatial/tool_common.py
@@ -0,0 +1,177 @@
+"""Shared plumbing for the spatial tools: context lookups, lazy imports of
+sibling packages (render / joints / probes / runtimes) with a typed
+``ToolUnavailable`` failure, render-output caching and plan/spec loading.
+
+Tools never touch globals: everything flows through :class:`ToolContext`.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import importlib
+import inspect
+import json
+from collections.abc import Callable, Sequence
+from pathlib import Path
+from typing import Any
+
+from pydantic import ValidationError
+
+from codeverse.contracts.artifacts import RenderSet
+from codeverse.contracts.plan import ArticulatedPlan, Plan, ScenePlan, StaticPlan
+from codeverse.conventions import OBJECT_VIEWS, ViewPreset
+from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError
+
+VIEW_BY_NAME: dict[str, ViewPreset] = {v.name: v for v in OBJECT_VIEWS}
+RENDER_MODES = ("shaded", "wire", "normals", "silhouette", "depth", "clay")
+
+
+class ToolUnavailable(RuntimeError):
+ """A sibling package this tool depends on is not importable / not built yet."""
+
+
+def unavailable_obs(tool: str, e: BaseException) -> Observation:
+ return Observation.error(f"tool {tool} unavailable: {type(e).__name__}: {e}")
+
+
+def lazy(module: str, attr: str) -> Callable[..., Any]:
+ """Import ``module.attr`` now; raise :class:`ToolUnavailable` with a clear reason."""
+ try:
+ mod = importlib.import_module(module)
+ except Exception as e: # ModuleNotFoundError, SyntaxError in a sibling, ...
+ raise ToolUnavailable(f"{module} not importable ({type(e).__name__}: {e})") from e
+ fn = getattr(mod, attr, None)
+ if fn is None:
+ raise ToolUnavailable(f"{module} has no '{attr}'")
+ return fn
+
+
+def call_adaptive(fn: Callable[..., Any], /, *args: Any, **kwargs: Any) -> Any:
+ """Call ``fn`` passing only the keyword arguments its signature accepts.
+
+ Sibling packages are written in parallel; this keeps us robust to optional
+ keywords they may not have (required ones still raise loudly).
+ """
+ try:
+ sig = inspect.signature(fn)
+ except (TypeError, ValueError):
+ return fn(*args, **kwargs)
+ if any(p.kind is inspect.Parameter.VAR_KEYWORD for p in sig.parameters.values()):
+ return fn(*args, **kwargs)
+ accepted = {k: v for k, v in kwargs.items() if k in sig.parameters}
+ return fn(*args, **accepted)
+
+
+# --------------------------------------------------------------------------- context
+def spec_dict(ctx: ToolContext) -> dict[str, Any]:
+ spec = ctx.extra.get("spec")
+ if spec is not None:
+ return spec.model_dump(mode="json") if hasattr(spec, "model_dump") else dict(spec)
+ p = ctx.workspace.spec_path
+ if p.is_file():
+ try:
+ return json.loads(p.read_text())
+ except json.JSONDecodeError:
+ return {}
+ return {}
+
+
+def language_of(ctx: ToolContext) -> str:
+ lang = ctx.language or str(spec_dict(ctx).get("language", ""))
+ if not lang:
+ raise ToolUsageError("language unknown: pass --language or put it in spec.json")
+ return lang
+
+
+def track_of(ctx: ToolContext) -> str:
+ return ctx.track or str(spec_dict(ctx).get("track", ""))
+
+
+def glb_path(ctx: ToolContext) -> Path:
+ p = ctx.workspace.artifacts / "object.glb"
+ if not p.is_file():
+ raise ToolUsageError("artifacts/object.glb does not exist yet — run `build` first", "build()")
+ return p
+
+
+def load_plan(path: Path) -> Plan:
+ """Read plan.json and validate it as the right plan type (by shape)."""
+ if not path.is_file():
+ raise ToolUsageError("plan.json not found in the workspace")
+ data = json.loads(path.read_text())
+ model: type[StaticPlan] | type[ArticulatedPlan] | type[ScenePlan]
+ if "zones" in data:
+ model = ScenePlan
+ elif "joints" in data:
+ model = ArticulatedPlan
+ else:
+ model = StaticPlan
+ try:
+ return model.model_validate(data)
+ except ValidationError as e:
+ raise ToolUsageError(f"plan.json is not a valid {model.__name__}: {e}") from e
+
+
+# --------------------------------------------------------------------------- views
+def resolve_views(names: Sequence[str]) -> list[ViewPreset]:
+ """Map view names → presets; unknown names are a usage error listing the options."""
+ out = []
+ for n in names:
+ v = VIEW_BY_NAME.get(n)
+ if v is None:
+ raise ToolUsageError(f"unknown view {n!r}; choose from {list(VIEW_BY_NAME)}", "render_views(views=['front', 'top'])")
+ out.append(v)
+ if not out:
+ raise ToolUsageError("views must not be empty", "render_views(views=['front_right_34'])")
+ return out
+
+
+def check_mode(mode: str) -> str:
+ if mode not in RENDER_MODES:
+ raise ToolUsageError(f"unknown mode {mode!r}; choose from {list(RENDER_MODES)}", "render_views(mode='shaded')")
+ return mode
+
+
+# --------------------------------------------------------------------------- render cache
+def _file_stamp(p: Path) -> str:
+ st = p.stat()
+ return f"{st.st_size}:{st.st_mtime_ns}"
+
+
+def render_cache_dir(ctx: ToolContext, glb: Path, **key_parts: Any) -> Path:
+ """Deterministic output dir under artifacts/tool_renders keyed by glb stamp + args."""
+ raw = json.dumps({"glb": _file_stamp(glb), **key_parts}, sort_keys=True, default=str)
+ key = hashlib.sha1(raw.encode()).hexdigest()[:8]
+ return ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_{key}"
+
+
+def cached_render_glb(
+ ctx: ToolContext,
+ glb: Path,
+ *,
+ views: Sequence[ViewPreset],
+ mode: str = "shaded",
+ size: int = 512,
+ isolate: Sequence[str] | None = None,
+ explode: float = 0.0,
+ sheet: bool = True,
+) -> RenderSet:
+ """``render_glb`` with an on-disk RenderSet cache (same args → same files)."""
+ out_dir = render_cache_dir(ctx, glb, views=[v.name for v in views], mode=mode, size=size,
+ isolate=list(isolate or []), explode=explode, sheet=sheet)
+ marker = out_dir / "renderset.json"
+ if marker.is_file():
+ try:
+ rs = RenderSet.model_validate_json(marker.read_text())
+ if all(Path(v.path).is_file() for v in rs.views) and (not rs.contact_sheet or Path(rs.contact_sheet).is_file()):
+ return rs
+ except ValidationError:
+ pass
+ render_glb = lazy("codeverse.spatial.render", "render_glb")
+ out_dir.mkdir(parents=True, exist_ok=True)
+ rs = call_adaptive(render_glb, glb, out_dir, views=list(views), mode=mode, width=size, height=size,
+ isolate=list(isolate) if isolate else None, explode=explode, sheet=sheet)
+ if not isinstance(rs, RenderSet):
+ raise ToolUnavailable(f"render_glb returned {type(rs).__name__}, expected RenderSet")
+ marker.write_text(rs.model_dump_json())
+ return rs
diff --git a/harness/codeverse/spatial/tools.py b/harness/codeverse/spatial/tools.py
new file mode 100644
index 00000000..be870b97
--- /dev/null
+++ b/harness/codeverse/spatial/tools.py
@@ -0,0 +1,206 @@
+"""Core spatial tools registered with ``@tool``: build, measure, check_connectivity,
+check_contract, cross_section. Rendering tools live in ``tools_render``, scene /
+articulation tools in ``tools_scene`` and the cookbook reader in ``cookbook_tool``
+(all imported at the bottom so ``import codeverse.spatial.tools`` registers every
+tool).
+
+House rules: observations are compact (errors first, fix hints attached), text
+never contains absolute host paths (images are absolute — the harness converts),
+and every tool is cheap to call repeatedly.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, Severity
+from codeverse.spatial.connectivity import check_connectivity as _check_connectivity
+from codeverse.spatial.contract import check_contract as _check_contract
+from codeverse.spatial.measure import GlbLoadError, measure_glb, measure_summary_table
+from codeverse.spatial.observe import (
+ gate_observation,
+ rel_path,
+ sanitize_text,
+ tail_lines,
+ truncate,
+)
+from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError, tool
+from codeverse.spatial.sections import cross_section as _cross_section
+from codeverse.spatial.tool_common import (
+ ToolUnavailable,
+ call_adaptive,
+ glb_path,
+ language_of,
+ lazy,
+ load_plan,
+ unavailable_obs,
+)
+
+_STDERR_TAIL_LINES = 30
+
+
+class NoArgs(BaseModel):
+ """This tool takes no arguments."""
+
+
+# --------------------------------------------------------------------------- build
+def _lint_lines(report: GateReport, root, *, errors_only: bool) -> list[str]:
+ out = []
+ for f in report.findings:
+ if errors_only and f.severity != Severity.ERROR:
+ continue
+ if not errors_only and f.severity == Severity.ERROR:
+ continue
+ if f.severity == Severity.INFO:
+ continue
+ loc = f" ({rel_path(f.target, root)})" if f.target else ""
+ out.append(f"- {f.severity.value.upper()}{loc}: {sanitize_text(f.message, root)}")
+ if f.fix_hint:
+ out.append(f" fix: {sanitize_text(f.fix_hint, root)}")
+ return out
+
+
+def _measure_after_build(ctx: ToolContext, br: BuildResult) -> tuple[Measurement | None, str]:
+ if not br.glb_path:
+ return None, "build reported success but no GLB path"
+ try:
+ m = measure_glb(br.glb_path)
+ except GlbLoadError as e:
+ return None, f"GLB unreadable: {e}"
+ ctx.workspace.write_json(ctx.workspace.artifacts / "measurement.json", m)
+ return m, measure_summary_table(m)
+
+
+@tool("build", NoArgs, "Lint + build the code in src/ with the language runtime, export artifacts/object.glb and measure it. Call after every edit.", cost_hint="slow")
+def build(ctx: ToolContext, args: NoArgs) -> Observation:
+ ws = ctx.workspace
+ t0 = time.time()
+ try:
+ language = language_of(ctx)
+ get_runtime = lazy("codeverse.languages", "get_runtime")
+ rt = get_runtime(language)
+ except ToolUnavailable as e:
+ return unavailable_obs("build", e)
+ lint: GateReport = rt.lint(ws)
+ lint_errors = _lint_lines(lint, ws.root, errors_only=True)
+ lint_warns = _lint_lines(lint, ws.root, errors_only=False)
+ if lint_errors:
+ text = "LINT FAILED — fix these before building:\n" + "\n".join(lint_errors)
+ if lint_warns:
+ text += "\nwarnings:\n" + "\n".join(lint_warns[:10])
+ return Observation(ok=False, text=truncate(text), numbers={"stage": "lint", "lint_errors": len(lint_errors)},
+ duration_ms=int((time.time() - t0) * 1000))
+ br: BuildResult = call_adaptive(rt.build, ws, timeout_s=get_settings().limits.build_timeout_s)
+ ws.write_json(ws.artifacts / "build_last.json", br)
+ numbers: dict[str, Any] = {"stage": "build", "ok": br.ok, "duration_ms": br.duration_ms}
+ if not br.ok:
+ where = f" at {rel_path(br.error_file, ws.root)}:{br.error_line}" if br.error_file else ""
+ lines = [f"BUILD FAILED: {br.error_type or 'Error'}: {sanitize_text(br.error_message, ws.root)}{where}"]
+ tail = tail_lines(sanitize_text(br.stderr_tail, ws.root), _STDERR_TAIL_LINES)
+ if tail:
+ lines.append("stderr (tail):\n" + tail)
+ if lint_warns:
+ lines.append("lint hints:\n" + "\n".join(lint_warns[:10]))
+ numbers.update({"error_type": br.error_type, "error_file": rel_path(br.error_file, ws.root), "error_line": br.error_line})
+ return Observation(ok=False, text=truncate("\n".join(lines), 3000), numbers=numbers,
+ duration_ms=int((time.time() - t0) * 1000))
+ m, table = _measure_after_build(ctx, br)
+ lines = [f"BUILD OK ({br.duration_ms} ms) → {rel_path(br.glb_path, ws.root)}"]
+ if br.extra_paths:
+ lines.append("extras: " + ", ".join(f"{k}={rel_path(v, ws.root)}" for k, v in br.extra_paths.items()))
+ lines.append(table)
+ if m is not None:
+ numbers.update({"extents_m": list(m.extents), "tri_count": m.tri_count, "n_parts": len(m.parts),
+ "n_islands": m.n_islands, "ground_gap_m": m.ground_gap_m,
+ "footprint_offset_m": m.footprint_offset_m, "parts": [p.name for p in m.parts]})
+ if m.extra.get("findings"):
+ numbers["findings"] = m.extra["findings"]
+ if lint_warns:
+ lines.append("lint warnings:\n" + "\n".join(lint_warns[:10]))
+ census_warn = br.census.get("warnings") if isinstance(br.census, dict) else None
+ if census_warn:
+ lines.append("build warnings:\n" + "\n".join(f"- {sanitize_text(str(w), ws.root)}" for w in list(census_warn)[:10]))
+ return Observation(ok=m is not None, text=truncate("\n".join(lines), 3000), numbers=numbers,
+ duration_ms=int((time.time() - t0) * 1000))
+
+
+# --------------------------------------------------------------------------- measure
+class MeasureArgs(BaseModel):
+ parts: list[str] = Field(default=[], description="limit the table to these part names (empty = all)")
+
+
+@tool("measure", MeasureArgs, "Measure the built object: overall bbox/extents, ground gap, per-part size/tris/islands (Y-up meters).")
+def measure(ctx: ToolContext, args: MeasureArgs) -> Observation:
+ glb = glb_path(ctx)
+ try:
+ m = measure_glb(glb)
+ except GlbLoadError as e:
+ return Observation.error(f"measure: {e}")
+ if args.parts:
+ known = {p.name for p in m.parts}
+ missing = [p for p in args.parts if p not in known]
+ if missing:
+ raise ToolUsageError(f"unknown part(s) {missing}; available: {sorted(known)}", "measure(parts=['Seat'])")
+ m = m.model_copy(update={"parts": [p for p in m.parts if p.name in set(args.parts)]})
+ numbers = {"extents_m": list(m.extents), "center_m": list(m.center), "bbox_min_m": list(m.bbox_min),
+ "bbox_max_m": list(m.bbox_max), "tri_count": m.tri_count, "n_parts": len(m.parts),
+ "n_islands": m.n_islands, "ground_gap_m": m.ground_gap_m, "footprint_offset_m": m.footprint_offset_m,
+ "parts": {p.name: {"min": list(p.bbox_min), "max": list(p.bbox_max), "tris": p.tri_count,
+ "islands": p.islands, "watertight": p.watertight} for p in m.parts[:40]}}
+ return Observation(ok=True, text=truncate(measure_summary_table(m)), numbers=numbers)
+
+
+# --------------------------------------------------------------------------- gates
+@tool("check_connectivity", NoArgs, "Contact graph of all parts: floating parts (with the exact gap vector to close), interpenetration, stray islands.")
+def check_connectivity(ctx: ToolContext, args: NoArgs) -> Observation:
+ glb = glb_path(ctx)
+ report = _check_connectivity(glb)
+ ctx.workspace.write_json(ctx.workspace.gates_dir(ctx.round_index) / "connectivity_tool.json", report)
+ return gate_observation(report)
+
+
+@tool("check_contract", NoArgs, "Compare the built object with plan.json: missing parts, bbox deltas per part, overall size, ground contact.")
+def check_contract(ctx: ToolContext, args: NoArgs) -> Observation:
+ glb = glb_path(ctx)
+ plan = load_plan(ctx.workspace.plan_path)
+ language = language_of(ctx)
+ try:
+ m = measure_glb(glb)
+ except GlbLoadError as e:
+ return Observation.error(f"check_contract: {e}")
+ report = _check_contract(m, plan, language=language)
+ ctx.workspace.write_json(ctx.workspace.gates_dir(ctx.round_index) / "contract_tool.json", report)
+ return gate_observation(report)
+
+
+# --------------------------------------------------------------------------- sections
+class CrossSectionArgs(BaseModel):
+ axis: str = Field(default="y", description="slicing axis in the GLB frame: x | y (up) | z (front)")
+ at: float = Field(default=0.5, description="position along the axis as a fraction of the bbox (0..1)")
+ parts: list[str] = Field(default=[], description="only slice these parts (empty = all)")
+
+
+@tool("cross_section", CrossSectionArgs, "Slice the object with an axis-aligned plane → labelled section image + loops/area/hollow ratio.")
+def cross_section(ctx: ToolContext, args: CrossSectionArgs) -> Observation:
+ glb = glb_path(ctx)
+ axis = args.axis.lower()
+ if axis not in ("x", "y", "z"):
+ raise ToolUsageError(f"axis must be x|y|z, got {args.axis!r}", "cross_section(axis='y', at=0.5)")
+ if not 0.0 <= args.at <= 1.0:
+ raise ToolUsageError("at must be a bbox fraction in 0..1", "cross_section(axis='y', at=0.25)")
+ out_dir = ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_sections"
+ out_dir.mkdir(parents=True, exist_ok=True)
+ tag = f"{axis}_{int(round(args.at * 100)):03d}" + (f"_{len(args.parts)}p" if args.parts else "")
+ obs = _cross_section(glb, axis, args.at, out_dir / f"section_{tag}.png", parts=args.parts or None)
+ return obs
+
+
+# register the remaining tool modules (order matters only for the prompt card listing)
+import codeverse.spatial.cookbook_tool # noqa: E402,F401
+import codeverse.spatial.tools_render # noqa: E402,F401
+import codeverse.spatial.tools_scene # noqa: E402,F401
+
diff --git a/harness/codeverse/spatial/tools_render.py b/harness/codeverse/spatial/tools_render.py
new file mode 100644
index 00000000..d79ccce1
--- /dev/null
+++ b/harness/codeverse/spatial/tools_render.py
@@ -0,0 +1,140 @@
+"""Rendering tools: render_views, render_sheet, isolate, compare_silhouette.
+
+All rendering goes through ``tool_common.cached_render_glb`` (→ ``render_glb``
+from package C1, imported lazily) so repeated calls with the same arguments are
+free. Images returned are absolute paths; text only shows workspace-relative
+paths.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from pydantic import BaseModel, Field
+
+from codeverse.conventions import OBJECT_VIEWS, OBJECT_VIEWS_QUICK
+from codeverse.spatial.measure import GlbLoadError, measure_glb, measure_summary_table
+from codeverse.spatial.observe import fmt_numbers, image_budget, render_observation
+from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError, tool
+from codeverse.spatial.silhouette import compare_silhouette as _compare_silhouette
+from codeverse.spatial.tool_common import (
+ VIEW_BY_NAME,
+ ToolUnavailable,
+ cached_render_glb,
+ check_mode,
+ glb_path,
+ render_cache_dir,
+ resolve_views,
+ spec_dict,
+ unavailable_obs,
+)
+
+_DEFAULT_VIEWS = [v.name for v in OBJECT_VIEWS_QUICK]
+_MAX_SIZE = 1024
+
+
+class RenderViewsArgs(BaseModel):
+ views: list[str] = Field(default=list(_DEFAULT_VIEWS),
+ description=f"view names from {[v.name for v in OBJECT_VIEWS]}")
+ mode: str = Field(default="shaded", description="shaded | wire | normals | silhouette | depth | clay")
+ isolate: list[str] = Field(default=[], description="render only these parts (others hidden)")
+ explode: float = Field(default=0.0, ge=0.0, le=3.0, description="exploded view factor (0 = assembled)")
+ size: int = Field(default=512, ge=128, le=_MAX_SIZE, description="image size in px (square)")
+
+
+def _render(ctx: ToolContext, tool_name: str, *, views: list[str], mode: str, isolate: list[str], explode: float, size: int, sheet: bool = True, note: str = "") -> Observation:
+ glb = glb_path(ctx)
+ presets = resolve_views(views)
+ check_mode(mode)
+ try:
+ rs = cached_render_glb(ctx, glb, views=presets, mode=mode, size=size, isolate=isolate or None, explode=explode, sheet=sheet)
+ except ToolUnavailable as e:
+ return unavailable_obs(tool_name, e)
+ return render_observation(rs, ctx.workspace.root, note=note)
+
+
+@tool("render_views", RenderViewsArgs, "Render the built object from named camera views (contact sheet + views). Use to SEE what you built.", cost_hint="slow")
+def render_views(ctx: ToolContext, args: RenderViewsArgs) -> Observation:
+ note = f"{args.mode} render" + (f", isolate={args.isolate}" if args.isolate else "") + (f", explode={args.explode:g}" if args.explode else "")
+ return _render(ctx, "render_views", views=args.views, mode=args.mode, isolate=args.isolate, explode=args.explode, size=args.size, note=note)
+
+
+class RenderSheetArgs(BaseModel):
+ mode: str = Field(default="shaded", description="shaded | wire | normals | silhouette | depth | clay")
+
+
+@tool("render_sheet", RenderSheetArgs, "One labelled 8-view contact sheet of the built object (all canonical views).", cost_hint="slow")
+def render_sheet(ctx: ToolContext, args: RenderSheetArgs) -> Observation:
+ obs = _render(ctx, "render_sheet", views=[v.name for v in OBJECT_VIEWS], mode=args.mode, isolate=[], explode=0.0, size=512,
+ note=f"{args.mode} 8-view sheet")
+ if obs.ok and obs.images:
+ obs.images = obs.images[:1] # the sheet alone is the deliverable here
+ return obs
+
+
+class IsolateArgs(BaseModel):
+ part: str = Field(description="exact part (node) name to show alone")
+ views: list[str] = Field(default=list(_DEFAULT_VIEWS), description="view names")
+
+
+@tool("isolate", IsolateArgs, "Render ONE part alone (others hidden) + its measurement row — inspect a single part's shape and placement.", cost_hint="slow")
+def isolate(ctx: ToolContext, args: IsolateArgs) -> Observation:
+ glb = glb_path(ctx)
+ try:
+ m = measure_glb(glb)
+ except GlbLoadError as e:
+ return Observation.error(f"isolate: {e}")
+ names = [p.name for p in m.parts]
+ if args.part not in names:
+ raise ToolUsageError(f"unknown part {args.part!r}; available: {names}", f"isolate(part='{names[0] if names else 'Seat'}')")
+ row = m.model_copy(update={"parts": [p for p in m.parts if p.name == args.part]})
+ obs = _render(ctx, "isolate", views=args.views, mode="shaded", isolate=[args.part], explode=0.0, size=512,
+ note=f"isolated part '{args.part}'")
+ if not obs.ok and not obs.images:
+ return obs
+ obs.text = obs.text + "\n" + measure_summary_table(row)
+ p = row.parts[0]
+ obs.numbers.update({"part": p.name, "bbox_min_m": list(p.bbox_min), "bbox_max_m": list(p.bbox_max),
+ "tris": p.tri_count, "islands": p.islands})
+ return obs
+
+
+class CompareSilhouetteArgs(BaseModel):
+ view: str = Field(default="front", description="view to render in silhouette mode")
+ reference_index: int = Field(default=0, ge=0, description="index into spec.references")
+
+
+@tool("compare_silhouette", CompareSilhouetteArgs, "Silhouette IoU / aspect-ratio error between a rendered view and a reference image (+ diff image).", cost_hint="slow")
+def compare_silhouette(ctx: ToolContext, args: CompareSilhouetteArgs) -> Observation:
+ glb = glb_path(ctx)
+ refs = spec_dict(ctx).get("references") or []
+ if not refs:
+ raise ToolUsageError("the spec has no reference images — nothing to compare against")
+ if args.reference_index >= len(refs):
+ raise ToolUsageError(f"reference_index {args.reference_index} out of range (have {len(refs)})", "compare_silhouette(reference_index=0)")
+ ref = refs[args.reference_index]
+ ref_path = Path(ref["path"] if isinstance(ref, dict) else ref.path)
+ if not ref_path.is_absolute():
+ ref_path = ctx.workspace.root / ref_path
+ if not ref_path.is_file():
+ return Observation.error(f"reference image {ref_path.name} not found")
+ if args.view not in VIEW_BY_NAME:
+ raise ToolUsageError(f"unknown view {args.view!r}; choose from {list(VIEW_BY_NAME)}", "compare_silhouette(view='front')")
+ preset = VIEW_BY_NAME[args.view]
+ try:
+ rs = cached_render_glb(ctx, glb, views=[preset], mode="silhouette", size=512, sheet=False)
+ except ToolUnavailable as e:
+ return unavailable_obs("compare_silhouette", e)
+ if not rs.views:
+ return Observation.error("compare_silhouette: renderer produced no view")
+ out_dir = render_cache_dir(ctx, glb, silhouette=args.view, ref=args.reference_index)
+ diff = out_dir / f"silhouette_diff_{args.view}_ref{args.reference_index}.png"
+ res = _compare_silhouette(rs.views[0].path, ref_path, diff_png=diff)
+ verdict = ("good match" if res["iou"] >= 0.8 else "rough match" if res["iou"] >= 0.6 else "poor match")
+ if not res["reliable"]:
+ verdict += " (UNRELIABLE: background mask failed on one image — judge visually)"
+ text = (f"silhouette '{args.view}' vs reference #{args.reference_index} ({ref_path.name}): IoU {res['iou']:.2f} → {verdict}; "
+ f"aspect w/h render {res['render_aspect']:.2f} vs ref {res['ref_aspect']:.2f} (err {res['aspect_ratio_err']:.0%}). "
+ f"Diff image: red = reference only, blue = render only. " + fmt_numbers({k: v for k, v in res.items() if k != "diff_png_path"}))
+ images = image_budget([str(diff), rs.views[0].path])
+ return Observation(ok=True, text=text, numbers={"view": args.view, **res}, images=images)
diff --git a/harness/codeverse/spatial/tools_scene.py b/harness/codeverse/spatial/tools_scene.py
new file mode 100644
index 00000000..41f44258
--- /dev/null
+++ b/harness/codeverse/spatial/tools_scene.py
@@ -0,0 +1,127 @@
+"""Track/language-specific tools: joint_sweep (articulated), shader_probe /
+scene_probe / scene_views (scene_threejs). All delegate lazily to sibling
+modules (``spatial.joints``, ``spatial.probes``, ``spatial.render``) written in
+parallel; a missing sibling degrades to a clear ``tool X unavailable`` Observation.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import GateReport, RenderSet
+from codeverse.contracts.common import Language, Track
+from codeverse.spatial.observe import fmt_numbers, gate_observation, render_observation, truncate
+from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError, tool
+from codeverse.spatial.tool_common import (
+ ToolUnavailable,
+ call_adaptive,
+ lazy,
+ load_plan,
+ unavailable_obs,
+)
+
+
+def _as_observation(result: Any, root, *, title: str) -> Observation:
+ """Normalise whatever a sibling returns (Observation / GateReport / RenderSet / dict / str)."""
+ if isinstance(result, Observation):
+ return result
+ if isinstance(result, GateReport):
+ return gate_observation(result, title=title)
+ if isinstance(result, RenderSet):
+ return render_observation(result, root, note=title)
+ if isinstance(result, BaseModel):
+ result = result.model_dump(mode="json")
+ if isinstance(result, dict):
+ images = [str(p) for p in (result.get("images") or []) if p]
+ errors = result.get("errors") or result.get("console_errors") or []
+ text = title + ": " + fmt_numbers({k: v for k, v in result.items() if k not in ("images",)}, max_items=40)
+ if errors:
+ text += "\nerrors:\n" + "\n".join(f" ! {str(e)[:200]}" for e in list(errors)[:10])
+ return Observation(ok=not errors, text=truncate(text), numbers=result, images=images[:6])
+ return Observation(ok=True, text=truncate(f"{title}: {result}"))
+
+
+# --------------------------------------------------------------------------- articulated
+class JointSweepArgs(BaseModel):
+ joints: list[str] = Field(default=[], description="joint names to sweep (empty = all)")
+ n_samples: int = Field(default=8, ge=2, le=32, description="poses per joint across its range")
+
+
+@tool("joint_sweep", JointSweepArgs, "Sweep URDF joints through their ranges: pose renders + self-collision / limit findings.",
+ tracks=(Track.ARTICULATED_OBJECT.value,), cost_hint="slow")
+def joint_sweep(ctx: ToolContext, args: JointSweepArgs) -> Observation:
+ try:
+ fn = lazy("codeverse.spatial.joints", "joint_sweep_observation")
+ except ToolUnavailable as e:
+ return unavailable_obs("joint_sweep", e)
+ out_dir = ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_joints"
+ out_dir.mkdir(parents=True, exist_ok=True)
+ # package E's signature: (ws, *, n_random, seed, render, out_dir, joint, expected_direction)
+ res = call_adaptive(fn, ctx.workspace, joints=args.joints or None, n_samples=args.n_samples,
+ n_random=args.n_samples, joint=args.joints[0] if len(args.joints) == 1 else None,
+ out_dir=out_dir, round_index=ctx.round_index)
+ return _as_observation(res, ctx.workspace.root, title="joint sweep")
+
+
+# --------------------------------------------------------------------------- scenes
+class NoArgs(BaseModel):
+ """This tool takes no arguments."""
+
+
+@tool("shader_probe", NoArgs, "Compile every GLSL/ShaderMaterial in the scene headlessly and report shader errors with line numbers.",
+ languages=(Language.SCENE_THREEJS.value,), cost_hint="slow")
+def shader_probe(ctx: ToolContext, args: NoArgs) -> Observation:
+ try:
+ fn = lazy("codeverse.spatial.probes", "check_shaders")
+ except ToolUnavailable as e:
+ return unavailable_obs("shader_probe", e)
+ res = call_adaptive(fn, ctx.workspace, round_index=ctx.round_index)
+ return _as_observation(res, ctx.workspace.root, title="shader probe")
+
+
+@tool("scene_probe", NoArgs, "Load the scene headlessly: object/material/light census, triangle count, fps, console errors.",
+ languages=(Language.SCENE_THREEJS.value,), cost_hint="slow")
+def scene_probe(ctx: ToolContext, args: NoArgs) -> Observation:
+ try:
+ fn = lazy("codeverse.spatial.probes", "probe_scene")
+ except ToolUnavailable as e:
+ return unavailable_obs("scene_probe", e)
+ res = call_adaptive(fn, ctx.workspace, round_index=ctx.round_index)
+ obs = _as_observation(res, ctx.workspace.root, title="scene probe")
+ census = obs.numbers.get("census") if isinstance(obs.numbers, dict) else None
+ if isinstance(census, dict) and census:
+ obs.text = obs.text + "\ncensus: " + fmt_numbers(census, max_items=30)
+ return obs
+
+
+class SceneViewsArgs(BaseModel):
+ cameras: str = Field(default="authored", description="authored = the plan/scene cameras · orbit = overview rig · all = both")
+ times: list[float] = Field(default=[0.0, 1.5], description="animation times (s) to capture")
+
+
+@tool("scene_views", SceneViewsArgs, "Render the scene from its authored cameras and/or the overview rig at given times (contact sheet + views).",
+ languages=(Language.SCENE_THREEJS.value,), cost_hint="slow")
+def scene_views(ctx: ToolContext, args: SceneViewsArgs) -> Observation:
+ if args.cameras not in ("authored", "orbit", "all"):
+ raise ToolUsageError("cameras must be authored | orbit | all", "scene_views(cameras='authored')")
+ if not args.times or len(args.times) > 6:
+ raise ToolUsageError("times must hold 1..6 values", "scene_views(times=[0.0, 1.5])")
+ try:
+ render_scene = lazy("codeverse.spatial.render", "render_scene")
+ except ToolUnavailable as e:
+ return unavailable_obs("scene_views", e)
+ cams = None
+ if args.cameras in ("authored", "all") and ctx.workspace.plan_path.is_file():
+ try:
+ plan = load_plan(ctx.workspace.plan_path)
+ cams = list(getattr(plan, "cameras", []) or []) or None
+ except ToolUsageError:
+ cams = None
+ orbit = args.cameras in ("orbit", "all") or (args.cameras == "authored" and cams is None)
+ key = f"{args.cameras}_{'_'.join(f'{t:g}' for t in args.times)}".replace(".", "p")
+ out_dir = ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_scene_{key}"
+ out_dir.mkdir(parents=True, exist_ok=True)
+ rs = call_adaptive(render_scene, ctx.workspace, out_dir, cameras=cams, orbit=orbit, times=tuple(args.times), sheet=True)
+ return _as_observation(rs, ctx.workspace.root, title=f"scene views ({args.cameras}, t={args.times})")
diff --git a/harness/codeverse/spatial/turntable.py b/harness/codeverse/spatial/turntable.py
new file mode 100644
index 00000000..e9f15533
--- /dev/null
+++ b/harness/codeverse/spatial/turntable.py
@@ -0,0 +1,45 @@
+"""Assemble rendered frames into a turntable video (ffmpeg) or animated GIF (PIL)."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+from pathlib import Path
+
+from PIL import Image
+
+from codeverse.config import get_settings
+
+
+def assemble_turntable(frames: list[Path], out: Path, *, fps: int = 12) -> Path:
+ """Write ``out`` from ``frames``; ``.mp4`` needs ffmpeg (else falls back to ``.gif``)."""
+ if not frames:
+ raise ValueError("assemble_turntable: no frames")
+ out = Path(out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ ffmpeg = get_settings().binaries.ffmpeg
+ if out.suffix.lower() == ".mp4" and shutil.which(ffmpeg):
+ return _mp4(frames, out, fps, ffmpeg)
+ if out.suffix.lower() == ".mp4":
+ out = out.with_suffix(".gif")
+ return _gif(frames, out, fps)
+
+
+def _mp4(frames: list[Path], out: Path, fps: int, ffmpeg: str) -> Path:
+ listing = out.parent / f".{out.stem}_frames.txt"
+ listing.write_text("".join(f"file '{f.resolve()}'\nduration {1 / fps:.4f}\n" for f in frames))
+ cmd = [
+ ffmpeg, "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", str(listing),
+ "-vf", "pad=ceil(iw/2)*2:ceil(ih/2)*2,format=yuv420p", "-r", str(fps), "-c:v", "libx264", "-crf", "22", str(out),
+ ]
+ proc = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
+ listing.unlink(missing_ok=True)
+ if proc.returncode != 0 or not out.is_file():
+ raise RuntimeError(f"ffmpeg failed ({proc.returncode}): {proc.stderr[-1500:]}")
+ return out
+
+
+def _gif(frames: list[Path], out: Path, fps: int) -> Path:
+ images = [Image.open(f).convert("RGB").convert("P", palette=Image.ADAPTIVE, colors=128) for f in frames]
+ images[0].save(out, save_all=True, append_images=images[1:], duration=int(1000 / fps), loop=0, optimize=False)
+ return out
diff --git a/harness/codeverse/tracks/__init__.py b/harness/codeverse/tracks/__init__.py
new file mode 100644
index 00000000..70e9cb22
--- /dev/null
+++ b/harness/codeverse/tracks/__init__.py
@@ -0,0 +1,5 @@
+"""Tracks: static_object · articulated_object · scene. ``get_track(Track.X)``."""
+
+from codeverse.tracks.base import TrackPipeline, get_track
+
+__all__ = ["TrackPipeline", "get_track"]
diff --git a/harness/codeverse/tracks/articulated_object.py b/harness/codeverse/tracks/articulated_object.py
new file mode 100644
index 00000000..8d084b34
--- /dev/null
+++ b/harness/codeverse/tracks/articulated_object.py
@@ -0,0 +1,125 @@
+"""ArticulatedObjectTrack: the static pipeline + URDF pose sweep + pose views.
+
+Language: urdf_blender (bpy link meshes + hand-written URDF). After the build
+the harness loads ``artifacts/robot.urdf``, samples joint poses, sweeps for
+penetrations / floating links (→ gate ERRORS with concrete fix hints) and
+renders a pose sheet which is appended to the judge's views.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from pathlib import Path
+
+from codeverse.contracts.artifacts import (
+ BuildResult,
+ GateFinding,
+ GateReport,
+ Measurement,
+ RenderSet,
+ RenderView,
+ Severity,
+)
+from codeverse.contracts.common import Track
+from codeverse.contracts.plan import ArticulatedPlan, Plan
+from codeverse.tracks.common import RunContext
+from codeverse.tracks.static_object import ObjectPipeline, StaticObjectTrack
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+SWEEP_GATE = "joint_sweep"
+
+
+class ArticulatedPipeline(ObjectPipeline):
+ """Object gates + joint sweep; object views + pose views."""
+
+ def gates(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> list[GateReport]:
+ out = super().gates(ctx, round_index, build, measurement)
+ out_dir = ctx.ws.renders_dir(round_index) / "poses"
+ report, views = ctx.services.joint_sweep(ctx.ws, ctx.plan, out_dir)
+ ctx.extra["pose_views"] = views
+ ctx.extra["sweep_report"] = report
+ out.append(report)
+ return out
+
+ def render(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> RenderSet:
+ rs = super().render(ctx, round_index, build, measurement)
+ pose_views: list[RenderView] = ctx.extra.pop("pose_views", []) or []
+ if pose_views:
+ rs.views = list(rs.views) + pose_views
+ return rs
+
+ def plan_summary(self, ctx: RunContext) -> str:
+ base = super().plan_summary(ctx)
+ plan = ctx.plan
+ if not isinstance(plan, ArticulatedPlan):
+ return base
+ joints = "; ".join(f"{j.name} ({j.type} {j.parent}→{j.child}, [{j.lower:.2f},{j.upper:.2f}])" for j in plan.joints)
+ return f"{base} Root link {plan.root_link}. Joints: {joints}."
+
+ def judge_context(self, ctx: RunContext, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
+ report: GateReport | None = ctx.extra.pop("sweep_report", None)
+ lines = ["Articulation sheet: the pose_* views show the object at rest, each joint at its lower and upper limit."]
+ if report is not None:
+ errs = [f"- {f.target or 'joint'}: {f.message}" for f in report.errors]
+ lines.append(f"Joint sweep: {'no penetrations' if not errs else str(len(errs)) + ' problems'}")
+ lines.extend(errs[:10])
+ return "\n".join(lines)
+
+
+class ArticulatedObjectTrack(StaticObjectTrack):
+ track = Track.ARTICULATED_OBJECT
+ rubric = "articulated_v1"
+ plan_model = ArticulatedPlan
+ generate_template = "tracks/generate_articulated.j2"
+
+ def make_pipeline(self, ctx: RunContext) -> ArticulatedPipeline:
+ return ArticulatedPipeline()
+
+ def system_prompt(self, ctx: RunContext) -> str:
+ return ("You are an expert in Blender bpy and URDF writing RAW code (no SDKs). Links are bpy objects named exactly "
+ "as the URDF links; joints are native URDF with origins/axes in the parent link frame. Exact numbers beat adjectives.")
+
+
+# ----------------------------------------------------------------------------- sweep adapter
+def default_joint_sweep(ws: Workspace, plan: Plan | None, out_dir: Path) -> tuple[GateReport, list[RenderView]]:
+ """Adapter to ``codeverse.spatial.joints`` (package E): load → pose samples →
+ ``sweep_collisions`` → ``sweep_findings`` (gate) and ``render_poses`` (pose views +
+ ``articulation_sheet.png`` for the judge)."""
+ from codeverse.spatial import joints
+
+ urdf = _find_urdf(ws)
+ if urdf is None:
+ return GateReport(gate=SWEEP_GATE, passed=False, findings=[GateFinding(
+ gate=SWEEP_GATE, severity=Severity.ERROR, target="robot.urdf", message="no robot.urdf found after build",
+ fix_hint="write src/robot.urdf (native URDF) referencing meshes/<link>.glb for every link")]), []
+ t0 = time.time()
+ try:
+ robot = joints.load_urdf(urdf, ws.artifacts / "meshes")
+ report = joints.sweep_collisions(robot, joints.pose_samples(robot))
+ except joints.UrdfError as e:
+ return GateReport(gate=SWEEP_GATE, passed=False, findings=[GateFinding(
+ gate=SWEEP_GATE, severity=Severity.ERROR, target="robot.urdf", message=f"URDF sweep failed: {e}",
+ fix_hint="fix robot.urdf so every link has a mesh under meshes/<link>.glb and joints form one tree")]), []
+ findings = [f.model_copy(update={"gate": SWEEP_GATE}) for f in joints.sweep_findings(report)]
+ gate = GateReport(gate=SWEEP_GATE, passed=not any(f.severity == Severity.ERROR for f in findings), findings=findings,
+ duration_ms=int((time.time() - t0) * 1000))
+ views: list[RenderView] = []
+ out_dir.mkdir(parents=True, exist_ok=True)
+ for label, rs in joints.render_poses(robot, out_dir):
+ if rs.views:
+ v = rs.views[0]
+ views.append(RenderView(name=f"pose_{label}", path=v.path, mode=v.mode, width=v.width, height=v.height))
+ sheet = out_dir / joints.ARTICULATION_SHEET_NAME
+ if sheet.is_file():
+ views.insert(0, RenderView(name="articulation_sheet", path=str(sheet), mode="shaded"))
+ return gate, views
+
+
+def _find_urdf(ws: Workspace) -> Path | None:
+ for cand in (ws.artifacts / "robot.urdf", ws.src / "robot.urdf"):
+ if cand.is_file():
+ return cand
+ return None
diff --git a/harness/codeverse/tracks/base.py b/harness/codeverse/tracks/base.py
new file mode 100644
index 00000000..d4e2932d
--- /dev/null
+++ b/harness/codeverse/tracks/base.py
@@ -0,0 +1,39 @@
+"""Track protocol: what every pipeline must provide to the orchestrator."""
+
+from __future__ import annotations
+
+from typing import Protocol
+
+from codeverse.contracts.common import Track
+from codeverse.contracts.plan import Plan
+from codeverse.contracts.run import RunRecord
+from codeverse.contracts.spec import Spec
+from codeverse.workspace import Workspace
+
+
+class TrackPipeline(Protocol):
+ track: Track
+ rubric: str # judges/rubrics/<rubric>.yaml
+
+ def plan(self, spec: Spec, ws: Workspace) -> Plan:
+ """Planner model call(s) → validated Plan (re-asked on validation errors)."""
+ ...
+
+ def run(self, spec: Spec, ws: Workspace, *, resume: bool = False) -> RunRecord:
+ """Full pipeline: plan → baseline → rounds → finalise. Must be resumable."""
+ ...
+
+
+def get_track(track: Track | str) -> TrackPipeline:
+ t = Track(track)
+ if t is Track.STATIC_OBJECT:
+ from codeverse.tracks.static_object import StaticObjectTrack
+
+ return StaticObjectTrack()
+ if t is Track.ARTICULATED_OBJECT:
+ from codeverse.tracks.articulated_object import ArticulatedObjectTrack
+
+ return ArticulatedObjectTrack()
+ from codeverse.tracks.scene import SceneTrack
+
+ return SceneTrack()
diff --git a/harness/codeverse/tracks/common.py b/harness/codeverse/tracks/common.py
new file mode 100644
index 00000000..89f80665
--- /dev/null
+++ b/harness/codeverse/tracks/common.py
@@ -0,0 +1,363 @@
+"""Shared track machinery: the run context, lazily-bound services, prompt context.
+
+``Services`` is the single seam between the tracks and the other packages
+(models, agents, runtimes, spatial tools, judges, flywheel). Every method
+imports lazily and raises a clear ``ServiceUnavailable`` when the package is
+missing; tests subclass it with fakes. Nothing here touches a network.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from codeverse.config import Settings
+from codeverse.contracts.artifacts import GateReport, Measurement, RenderSet, RenderView
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.plan import CameraPlan, Plan, StaticPlan
+from codeverse.contracts.run import RunRecord
+from codeverse.conventions import LANGUAGE_FRAME, Frame, ViewPreset, frame_doc, to_snake
+from codeverse.events import EventLog
+from codeverse.orchestrator.budget import BudgetGuard
+from codeverse.orchestrator.rounds import RoundPolicy
+from codeverse.orchestrator.state import RunState
+from codeverse.prompts import load_text, prompt_hash
+from codeverse.tracks.generation import SINGLE_SHOT_FORMAT, is_single_shot
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+
+class ServiceUnavailable(RuntimeError):
+ """A sibling package this track depends on is not importable / not configured."""
+
+
+def _import(path: str, name: str) -> Any:
+ import importlib
+
+ try:
+ mod = importlib.import_module(path)
+ except ImportError as e:
+ raise ServiceUnavailable(f"{path} is not available ({e}); cannot call {name}") from e
+ try:
+ return getattr(mod, name)
+ except AttributeError as e:
+ raise ServiceUnavailable(f"{path}.{name} does not exist") from e
+
+
+class Services:
+ """Lazy adapters to sibling packages. Override any method in tests."""
+
+ # ---- models / agents / judges / runtimes
+ def chat_model(self, model_id: str) -> Any:
+ return _import("codeverse.models", "get_chat_model")(model_id)
+
+ def coding_agent(self, agent_id: str) -> Any:
+ return _import("codeverse.agents", "get_coding_agent")(agent_id)
+
+ def judge(self, rubric: str, model_id: str, n_samples: int = 1) -> Any:
+ return _import("codeverse.judges.vlm_judge", "VlmJudge")(rubric=rubric, model_id=model_id, n_samples=n_samples)
+
+ def runtime(self, language: Language) -> Any:
+ return _import("codeverse.languages", "get_runtime")(language)
+
+ def rubric_threshold(self, rubric: str) -> float | None:
+ try:
+ r = _import("codeverse.judges.rubrics", "load_rubric")(rubric)
+ except ServiceUnavailable:
+ return None
+ return getattr(r, "pass_threshold", None)
+
+ # ---- spatial
+ def measure(self, glb: Path) -> Measurement:
+ return _import("codeverse.spatial.measure", "measure_glb")(glb)
+
+ def connectivity(self, glb: Path) -> GateReport:
+ return _import("codeverse.spatial.connectivity", "check_connectivity")(glb)
+
+ def contract(self, measurement: Measurement, plan: Plan, tol_m: float, language: str = "") -> GateReport:
+ return _import("codeverse.spatial.contract", "check_contract")(measurement, plan, language=language, tol_m=tol_m)
+
+ def render_object(self, glb: Path, out_dir: Path, *, views: Sequence[ViewPreset], width: int, height: int) -> RenderSet:
+ return _import("codeverse.spatial.render", "render_glb")(glb, out_dir, views=list(views), width=width, height=height, sheet=True)
+
+ def render_scene(self, ws: Workspace, out_dir: Path, *, cameras: list[CameraPlan] | None, times: Sequence[float],
+ width: int, height: int) -> RenderSet:
+ return _import("codeverse.spatial.render", "render_scene")(ws, out_dir, cameras=cameras, orbit=True, times=tuple(times),
+ width=width, height=height, sheet=True)
+
+ def contact_sheet(self, images: list[tuple[str, Path]], out: Path) -> Path:
+ return _import("codeverse.spatial.sheet", "contact_sheet")(images, out)
+
+ def joint_sweep(self, ws: Workspace, plan: Plan, out_dir: Path) -> tuple[GateReport, list[RenderView]]:
+ """Pose sweep on the built URDF → (gate report, pose views). See articulated_object."""
+ from codeverse.tracks.articulated_object import default_joint_sweep
+
+ return default_joint_sweep(ws, plan, out_dir)
+
+ # ---- agents' workspace materialisation + tool cards
+ def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, cookbook_rel: str, spatial_tools: bool,
+ mcp_command: list[str]) -> None:
+ _import("codeverse.agents.materialize", "materialize_workspace")(
+ ws, agent_kind=agent_kind, contract_md=contract_md, cookbook_rel=cookbook_rel,
+ spatial_tools=spatial_tools, mcp_command=mcp_command)
+
+ def tool_cards(self, track: str, language: str) -> str:
+ try:
+ return _import("codeverse.spatial.registry", "tool_cards")(track=track, language=language)
+ except Exception as e: # noqa: BLE001 — tool registry may be empty during bootstrap
+ log.warning("tool cards unavailable: %s", e)
+ return ""
+
+ # ---- scene assembly + record
+ def assemble_scene(self, ws: Workspace, plan: Plan) -> Any:
+ fn = _import("codeverse.languages.scene_threejs.assemble", "assemble")
+ return fn(ws, plan, cameras="plan" if getattr(plan, "cameras", None) else "derive")
+
+ def finalize_record(self, ws: Workspace, record: RunRecord) -> None:
+ try:
+ fn = _import("codeverse.flywheel.record", "finalize_record")
+ except ServiceUnavailable:
+ ws.write_json(ws.record_path, record)
+ return
+ fn(ws, record)
+
+
+# ----------------------------------------------------------------------------- context
+@dataclass
+class RunContext:
+ """Everything a round needs. Built once per run by the track."""
+
+ spec: Any
+ ws: Workspace
+ events: EventLog
+ settings: Settings
+ budget: BudgetGuard
+ runtime: Any
+ services: Services
+ state: RunState
+ policy: RoundPolicy
+ track: Track
+ rubric: str
+ agent_id: str
+ plan: Plan | None = None
+ judge: Any | None = None
+ agent: Any | None = None # CodingAgent instance (agent path)
+ model: Any | None = None # ChatModel (single-shot path)
+ contract_text: str = ""
+ cookbook_text: str = ""
+ cookbook_rel: str = ""
+ tool_cards: str = ""
+ prompt_hashes: dict[str, str] = field(default_factory=dict)
+ extra: dict[str, Any] = field(default_factory=dict)
+
+ @property
+ def language(self) -> Language:
+ return self.spec.language
+
+ @property
+ def single_shot(self) -> bool:
+ return is_single_shot(self.agent_id)
+
+ def record_prompt(self, name: str, text: str) -> None:
+ self.prompt_hashes[name] = prompt_hash(text)
+
+
+# ----------------------------------------------------------------------------- prompt helpers
+def load_prompt_or(rel: str, fallback: str) -> str:
+ """``prompts/<rel>`` if it exists (package K writes those), else ``fallback``."""
+ try:
+ return load_text(rel)
+ except FileNotFoundError:
+ return fallback
+
+
+def language_contract(ctx_language: Language, runtime: Any) -> str:
+ """The language authoring contract: prompts/<lang>/contract.md → runtime.contract_doc() → minimal."""
+ text = load_prompt_or(f"{ctx_language.value}/contract.md", "")
+ if text.strip():
+ return text
+ doc = ""
+ if runtime is not None and hasattr(runtime, "contract_doc"):
+ try:
+ doc = runtime.contract_doc() or ""
+ except Exception as e: # noqa: BLE001
+ log.warning("runtime.contract_doc failed: %s", e)
+ return doc.strip() or _MINIMAL_CONTRACT.get(ctx_language, "Write raw code in the language's native frame; meters; named parts.")
+
+
+_MINIMAL_CONTRACT: dict[Language, str] = {
+ Language.BLENDER: "src/model.py — pure bpy; Z-up, -Y front, meters; one named object per part (PascalCase); "
+ "no camera/light/render/export calls; do not import anything but bpy, bmesh, math, mathutils, random.",
+ Language.CADQUERY: "src/model.py — `import cadquery as cq` only; module-level `result` = cq.Assembly with named parts "
+ "(PascalCase) or a Workplane; Z-up, -Y front, meters.",
+ Language.THREEJS: "src/parts/<snake>.js each `export function build<Pascal>(THREE) → THREE.Group` at world pose; "
+ "src/object.js `export function build(THREE) → THREE.Group` adding every part; Y-up, +Z front, meters; "
+ "no DOM, no texture loading, no environment sniffing.",
+ Language.URDF_BLENDER: "src/model.py — pure bpy, one object per link named exactly as the link (PascalCase), Z-up, -Y front, "
+ "meters, authored at rest pose in WORLD coordinates; src/robot.urdf — native URDF, meshes as "
+ "meshes/<link>.glb, joint origins/axes in parent-link frames.",
+ Language.SCENE_THREEJS: "src/scene.js `export function createScene({THREE, renderer, loaders}) → {scene, cameras, update(t,dt)}`; "
+ "src/env.js, src/zones/*.js, src/assets/*.js (`export function build<Pascal>(THREE, opts)`), "
+ "src/shaders/*.js; Y-up, meters; `import * as THREE from 'three'` only; no DOM, no fetch.",
+}
+
+
+def cookbook_rel_for(language: Language) -> str:
+ return f"{language.value}/cookbook.md"
+
+
+def parts_table(plan: Plan) -> str:
+ """Markdown table of parts with exact bboxes (meters, 3 decimals)."""
+ parts = getattr(plan, "parts", None)
+ if not parts:
+ return "(no parts)"
+ rows = ["| part | role | bbox centre (x,y,z) m | extents (x,y,z) m | attach_to | inst | material |",
+ "|---|---|---|---|---|---|---|"]
+ for p in parts:
+ c = ", ".join(f"{v:.3f}" for v in p.bbox.center)
+ e = ", ".join(f"{v:.3f}" for v in p.bbox.extents)
+ rows.append(f"| {p.name} | {p.role} | ({c}) | ({e}) | {p.attach_to or '-'} | {p.instances} | {p.material or '-'} |")
+ return "\n".join(rows)
+
+
+def part_details(plan: Plan) -> str:
+ parts = getattr(plan, "parts", None) or []
+ return "\n".join(f"- **{p.name}** ({p.symmetry if p.symmetry != 'none' else 'no symmetry'}): {p.description}" for p in parts)
+
+
+def joints_table(plan: Plan) -> str:
+ joints = getattr(plan, "joints", None)
+ if not joints:
+ return "(no joints)"
+ rows = ["| joint | type | parent | child | axis | pivot (world, m) | lower | upper | rest | motion |",
+ "|---|---|---|---|---|---|---|---|---|---|"]
+ for j in joints:
+ ax = ", ".join(f"{v:.3f}" for v in j.axis)
+ pv = ", ".join(f"{v:.3f}" for v in j.pivot)
+ rows.append(f"| {j.name} | {j.type} | {j.parent} | {j.child} | ({ax}) | ({pv}) | {j.lower:.3f} | {j.upper:.3f} | {j.rest:.3f} | {j.motion} |")
+ return "\n".join(rows)
+
+
+def acceptance_lines(plan: Plan | None) -> str:
+ items = getattr(plan, "acceptance", None) or []
+ if not items:
+ return "(none)"
+ return "\n".join(f"- [{a.id}] ({a.priority}, {a.how}) {a.text}" for a in items)
+
+
+def bbox_line(bbox: Any) -> str:
+ c = ", ".join(f"{v:.3f}" for v in bbox.center)
+ e = ", ".join(f"{v:.3f}" for v in bbox.extents)
+ return f"centre ({c}) m, extents ({e}) m"
+
+
+def glb_to_plan_frame(v: Sequence[float], language: Language, *, extents: bool = False) -> tuple[float, float, float]:
+ """Map a GLB-frame (Y-up, +Z front) vector into the language's authoring frame.
+ Blender/CadQuery/URDF plans are Z-up with -Y front: glb (x, y, z) → (x, -z, y)."""
+ x, y, z = float(v[0]), float(v[1]), float(v[2])
+ if LANGUAGE_FRAME[language.value] is Frame.Z_UP_NEG_Y_FRONT:
+ return (x, abs(z) if extents else -z, y)
+ return (x, y, z)
+
+
+def constraints_text(spec: Any) -> str:
+ c = spec.constraints
+ lines = []
+ if c.dimensions_m:
+ lines.append("Dimensions (m): " + ", ".join(f"{k}={v:.3f}" for k, v in c.dimensions_m.items()))
+ if c.max_triangles:
+ lines.append(f"Max triangles: {c.max_triangles}")
+ if c.style:
+ lines.append(f"Style: {c.style}")
+ for m in c.must_have:
+ lines.append(f"MUST HAVE: {m}")
+ for m in c.must_not:
+ lines.append(f"MUST NOT: {m}")
+ return "\n".join(lines) or "(none)"
+
+
+def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
+ """Variables every tracks/*.j2 template may use (StrictUndefined → all present)."""
+ plan = ctx.plan
+ object_name = getattr(plan, "object_name", None) or getattr(plan, "title", None) or "Object"
+ d: dict[str, Any] = {
+ "track": ctx.track.value,
+ "language": ctx.language.value,
+ "frame_doc": frame_doc(LANGUAGE_FRAME[ctx.language.value]),
+ "contract": ctx.contract_text,
+ "cookbook_rel": ctx.cookbook_rel,
+ "cookbook_excerpt": ctx.cookbook_text[:6000],
+ "tool_cards": ctx.tool_cards,
+ "single_shot": ctx.single_shot,
+ "output_format": SINGLE_SHOT_FORMAT if ctx.single_shot else AGENT_OUTPUT_RULES,
+ "spec_prompt": ctx.spec.prompt,
+ "constraints": constraints_text(ctx.spec),
+ "object_name": object_name,
+ "plan_summary": getattr(plan, "summary", "") if plan else "",
+ "style_notes": getattr(plan, "style_notes", "") if plan else "",
+ "overall_bbox": bbox_line(plan.overall_bbox) if isinstance(plan, StaticPlan) else "",
+ "parts_table": parts_table(plan) if plan else "",
+ "part_details": part_details(plan) if plan else "",
+ "joints_table": joints_table(plan) if plan else "",
+ "acceptance": acceptance_lines(plan),
+ "entry_files": ", ".join(getattr(ctx.runtime, "entry_globs", ()) or ()),
+ "n_parts": len(getattr(plan, "parts", []) or []) if plan else 0,
+ "root_link": getattr(plan, "root_link", "") if plan else "",
+ }
+ d.update(extra)
+ return d
+
+
+AGENT_OUTPUT_RULES = """HOW TO FINISH (agent mode): edit files under src/ only (and public/ for compiled assets).
+Before you finish you MUST run the `build` tool and fix every error it reports; then run `measure`
+(objects) or `scene_probe` (scenes) once and compare the numbers with the plan. Do not write
+reports, READMEs or notes — only the code files. Stop when the build is clean."""
+
+
+def file_for_target_factory(ctx: RunContext):
+ """Return ``target → [files]`` for the current language, or ``None`` when the
+ language is whole-object (one file). Prefers ``runtime.file_for_part``."""
+ rt = ctx.runtime
+ plan = ctx.plan
+ custom = getattr(rt, "file_for_part", None)
+ part_names = {to_snake(p.name): p.name for p in (getattr(plan, "parts", None) or [])}
+ lang = ctx.language
+
+ if lang is Language.THREEJS or callable(custom):
+ def _threejs(target: str) -> list[str]:
+ key = to_snake(target)
+ if key in part_names:
+ if callable(custom):
+ try:
+ out = custom(part_names[key])
+ return [str(out)] if isinstance(out, (str, Path)) else [str(p) for p in out]
+ except Exception as e: # noqa: BLE001
+ log.warning("runtime.file_for_part failed for %s: %s", target, e)
+ return [f"src/parts/{key}.js"]
+ if key in ("overall", "assembly", "object", ""):
+ return ["src/object.js"]
+ return []
+ return _threejs
+
+ if lang is Language.SCENE_THREEJS:
+ zones = {to_snake(z.name) for z in (getattr(plan, "zones", None) or [])}
+ assets = {to_snake(a.name) for a in (getattr(plan, "assets", None) or [])}
+ cameras = {to_snake(c.name) for c in (getattr(plan, "cameras", None) or [])}
+
+ def _scene(target: str) -> list[str]:
+ key = to_snake(target)
+ if key in zones:
+ return [f"src/zones/{key}.js"]
+ if key in assets:
+ return [f"src/assets/{key}.js"]
+ if key in cameras or key in ("camera", "cameras", "composition"):
+ return ["src/scene.js"]
+ if key in ("env", "environment", "lighting", "sky", "fog", "ground", "water", "light"):
+ return ["src/env.js"]
+ return []
+ return _scene
+ return None
diff --git a/harness/codeverse/tracks/generation.py b/harness/codeverse/tracks/generation.py
new file mode 100644
index 00000000..10656e2f
--- /dev/null
+++ b/harness/codeverse/tracks/generation.py
@@ -0,0 +1,357 @@
+"""Code generation: one entry point, two strategies.
+
+* **CodingAgent path** — ``agent_id`` is any id ``codeverse.agents`` knows
+ (``gemini-cli:*``, ``claude-code:*``, ``codex:*``, ``agy:*``, ``api-agent:*``):
+ the workspace is materialised once per run (AGENTS.md + MCP config), then
+ ``agent.run(AgentJob)``. Truth is on disk: ``ok`` means files changed.
+* **Single-shot path** — ``agent_id = "single-shot:<provider>:<model>"``: one
+ ``ChatRequest`` whose answer is a multi-file envelope (``SINGLE_SHOT_FORMAT``),
+ parsed by ``parse_multifile`` and written under the allowed roots. This is
+ handled here (not in the agents registry) because it is not an agent.
+
+Neither path commits; the round commits once after all (possibly parallel)
+tasks finished. Neither path builds; see ``tracks/repair.py``.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+import subprocess
+import threading
+import time
+from collections.abc import Callable
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.agent import AgentJob, AgentResult, FileChange
+from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart
+from codeverse.contracts.common import Usage
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+SINGLE_SHOT_PREFIX = "single-shot:"
+ALLOWED_ROOTS: tuple[str, ...] = ("src/", "public/")
+
+SINGLE_SHOT_FORMAT = """OUTPUT FORMAT (exactly this, nothing else around it):
+For EVERY file you create or fully rewrite, emit one block:
+
+=== FILE: <relative path, e.g. src/parts/seat.js> ===
+<complete file contents — the whole file, not a diff>
+=== END FILE ===
+
+Rules: paths are relative to the workspace root and must start with src/ (or public/);
+emit the COMPLETE contents of each file (no "...rest unchanged"); no prose outside the blocks;
+no markdown fences inside a block (plain code). Files you do not emit are left untouched."""
+
+
+class GenerationError(RuntimeError):
+ """Raised when the generator cannot produce usable files (bad envelope, agent crash)."""
+
+
+class MultiFileParseError(GenerationError):
+ """The single-shot answer did not contain a parseable file envelope."""
+
+
+class GenerationTask(BaseModel):
+ """One unit of code-writing work (baseline, refine group, asset, zone, repair)."""
+
+ label: str
+ prompt: str
+ system: str = Field(default="", description="system prompt (single-shot) / system_append (agent)")
+ files_hint: list[str] = Field(default_factory=list, description="files this task should produce/edit")
+ round: int = 0
+ kind: str = "generate"
+ images: list[ImagePart] = Field(default_factory=list)
+ temperature: float = 0.6
+ thinking: str = "medium"
+ max_output_tokens: int = 32000
+ timeout_s: int | None = None
+ write_roots: list[str] = Field(default_factory=lambda: ["src", "public"])
+
+
+class GenerationResult(BaseModel):
+ ok: bool
+ usage: Usage = Field(default_factory=Usage)
+ files_changed: list[FileChange] = Field(default_factory=list)
+ commit: str = ""
+ notes: str = ""
+ text: str = Field(default="", description="model/agent final text (truncated)")
+ transcript_path: str = ""
+ label: str = ""
+
+
+# ----------------------------------------------------------------------------- envelope parsing
+_BLOCK = re.compile(
+ r"^[ \t]*===\s*FILE:\s*(?P<path>[^\n=]+?)\s*===[ \t]*\r?\n(?P<body>.*?)(?:\r?\n)?^[ \t]*===\s*END FILE\s*===[ \t]*$",
+ re.S | re.M,
+)
+_FENCE = re.compile(r"```[a-zA-Z0-9_+\-]*[ \t]*(?:\r?\n)(?P<body>.*?)```", re.S)
+_FENCE_PATH_HINT = re.compile(
+ r"(?:^|\n)[^\n]*?(?P<path>(?:src|public)/[A-Za-z0-9_./\-]+\.[a-z]{1,5})[^\n]*\n[ \t]*```", re.S
+)
+
+
+def parse_multifile(text: str, *, expected_files: list[str] | None = None) -> dict[str, str]:
+ """Parse ``SINGLE_SHOT_FORMAT`` → ``{path: content}``.
+
+ Tolerant to: a fenced block wrapping a file body; an answer that is ONE fenced
+ block when exactly one entry file is expected; fenced blocks preceded by a line
+ naming the path. Raises ``MultiFileParseError`` otherwise.
+ """
+ files: dict[str, str] = {}
+ for m in _BLOCK.finditer(text):
+ path = _clean_path(m.group("path"))
+ files[path] = _strip_fence(m.group("body"))
+ if files:
+ return files
+ fences = list(_FENCE.finditer(text))
+ expected = [_clean_path(p) for p in (expected_files or [])]
+ if fences:
+ # fenced blocks preceded by a path mention
+ for m in fences:
+ probe = text[: m.start()][-400:].rstrip(" \t")
+ probe += ("" if probe.endswith("\n") else "\n") + "```"
+ hint = _FENCE_PATH_HINT.findall(probe)
+ if hint:
+ files[_clean_path(hint[-1])] = m.group("body").rstrip("\n")
+ if files and (not expected or set(files) <= set(expected) or len(files) == len(fences)):
+ return files
+ if len(expected) == 1:
+ largest = max(fences, key=lambda m: len(m.group("body")))
+ return {expected[0]: largest.group("body").rstrip("\n")}
+ if len(expected) == 1 and _looks_like_code(text):
+ return {expected[0]: text.strip("\n")}
+ raise MultiFileParseError(
+ "no '=== FILE: <path> ===' blocks found" + (f"; expected {expected}" if expected else "")
+ )
+
+
+def _clean_path(p: str) -> str:
+ p = p.strip().strip("`'\"").replace("\\", "/")
+ while p.startswith("./"):
+ p = p[2:]
+ return p.lstrip("/")
+
+
+def _strip_fence(body: str) -> str:
+ s = body.strip("\n")
+ m = re.fullmatch(r"```[a-zA-Z0-9_+\-]*[ \t]*\n(.*?)\n?```", s, re.S)
+ return (m.group(1) if m else body).rstrip("\n")
+
+
+def _looks_like_code(text: str) -> bool:
+ t = text.strip()
+ return bool(t) and ("\n" in t) and not t.lower().startswith(("i ", "here", "sure", "sorry"))
+
+
+def safe_relpath(path: str, allowed_roots: tuple[str, ...] = ALLOWED_ROOTS) -> str:
+ """Validate a model-provided relative path: inside the workspace + allowed roots."""
+ p = _clean_path(path)
+ if not p or p.startswith("/") or ".." in Path(p).parts or re.match(r"^[A-Za-z]:", p):
+ raise GenerationError(f"refusing to write outside the workspace: {path!r}")
+ if not any(p.startswith(root) for root in allowed_roots):
+ raise GenerationError(f"path {p!r} is outside the allowed roots {allowed_roots}")
+ return p
+
+
+def write_files(ws: Workspace, files: dict[str, str], *, allowed_roots: tuple[str, ...] = ALLOWED_ROOTS) -> list[FileChange]:
+ """Write parsed files under the workspace; returns git-style FileChange rows."""
+ changes: list[FileChange] = []
+ for raw, content in files.items():
+ rel = safe_relpath(raw, allowed_roots)
+ dest = ws.root / rel
+ existed = dest.exists()
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_text(content if content.endswith("\n") else content + "\n")
+ changes.append(FileChange(path=rel, status="modified" if existed else "added",
+ lines_added=content.count("\n") + 1))
+ return changes
+
+
+# ----------------------------------------------------------------------------- git helpers
+_GIT_LOCKS: dict[str, threading.Lock] = {}
+_GIT_LOCKS_GUARD = threading.Lock()
+
+
+def workspace_lock(ws: Workspace) -> threading.Lock:
+ """One lock per workspace root: git index operations from parallel tasks must serialise."""
+ key = str(ws.root)
+ with _GIT_LOCKS_GUARD:
+ lock = _GIT_LOCKS.get(key)
+ if lock is None:
+ lock = _GIT_LOCKS[key] = threading.Lock()
+ return lock
+
+
+def changed_files_safe(ws: Workspace, since: str | None = None, *, retries: int = 6) -> list[FileChange]:
+ """``ws.changed_files`` serialised per workspace and retried on transient git index locks."""
+ with workspace_lock(ws):
+ for attempt in range(retries):
+ try:
+ return ws.changed_files(since)
+ except subprocess.CalledProcessError as e:
+ if attempt == retries - 1:
+ raise
+ log.warning("git diff failed (attempt %d): %s", attempt + 1, (e.stderr or "")[:200])
+ time.sleep(0.2 * (attempt + 1))
+ return []
+
+
+# ----------------------------------------------------------------------------- strategies
+def is_single_shot(agent_id: str) -> bool:
+ return agent_id.startswith(SINGLE_SHOT_PREFIX)
+
+
+def single_shot_model_id(agent_id: str) -> str:
+ if not is_single_shot(agent_id):
+ raise ValueError(f"not a single-shot id: {agent_id!r}")
+ return agent_id[len(SINGLE_SHOT_PREFIX):]
+
+
+def single_shot_format_text() -> str:
+ """The canonical format doc (package K's ``system/singleshot_format.md`` when present)."""
+ try:
+ from codeverse.prompts import load_text
+
+ return load_text("system/singleshot_format.md")
+ except FileNotFoundError:
+ return SINGLE_SHOT_FORMAT
+
+
+def generate_files(
+ ws: Workspace,
+ *,
+ model: Any,
+ task: GenerationTask,
+ budget: Any | None = None,
+ events: Any | None = None,
+ allowed_roots: tuple[str, ...] = ALLOWED_ROOTS,
+) -> GenerationResult:
+ """Single-shot API codegen: ChatRequest → envelope → files on disk (no commit)."""
+ system = task.system + ("\n\n" if task.system else "") + single_shot_format_text()
+ req = ChatRequest(
+ messages=[ChatMessage.user(task.prompt, images=task.images or None)],
+ system=system,
+ temperature=task.temperature,
+ thinking=task.thinking, # type: ignore[arg-type]
+ max_output_tokens=task.max_output_tokens,
+ label=task.label,
+ )
+ resp = model.generate(req)
+ usage = resp.usage
+ if budget is not None:
+ budget.charge(usage)
+ traj = ws.trajectory_dir(task.label.replace("/", "_"), task.round)
+ (traj / "prompt.md").write_text(f"# system\n{system}\n\n# user\n{task.prompt}\n")
+ (traj / "response.md").write_text(resp.text or "")
+ try:
+ files = parse_multifile(resp.text or "", expected_files=task.files_hint or None)
+ except MultiFileParseError as e:
+ if events is not None:
+ events.emit("generate.parse_failed", label=task.label, error=str(e))
+ return GenerationResult(ok=False, usage=usage, notes=f"parse failed: {e}", text=(resp.text or "")[:2000],
+ transcript_path=str(traj / "response.md"), label=task.label)
+ changes = write_files(ws, files, allowed_roots=allowed_roots)
+ if events is not None:
+ events.emit("generate.done", label=task.label, strategy="single-shot", files=[c.path for c in changes],
+ cost_usd=round(usage.cost_usd, 4))
+ return GenerationResult(ok=bool(changes), usage=usage, files_changed=changes, text=(resp.text or "")[:2000],
+ transcript_path=str(traj / "response.md"), label=task.label)
+
+
+def run_agent_task(
+ ws: Workspace,
+ *,
+ agent: Any,
+ task: GenerationTask,
+ settings: Any | None = None,
+ budget: Any | None = None,
+ events: Any | None = None,
+ retry_silent_bail: bool = True,
+) -> GenerationResult:
+ """CodingAgent path. ``ok`` = the agent changed files (envelope-vs-disk truth)."""
+ before = ws.head()
+ timeout = task.timeout_s or (settings.limits.agent_timeout_s if settings is not None else 1800)
+ # job.extra is honoured by every CodingAgent: round → trajectory dir + ToolContext,
+ # language/track → spatial tool filtering (see agents/*).
+ extra = {"round": task.round, "kind": task.kind}
+ spec_path = ws.spec_path
+ if spec_path.is_file():
+ try:
+ spec_d = ws.read_json(spec_path)
+ extra["language"] = spec_d.get("language", "")
+ extra["track"] = spec_d.get("track", "")
+ except Exception: # noqa: BLE001 — best effort context only
+ pass
+ job = AgentJob(workspace=str(ws.root), prompt=task.prompt, system_append=task.system,
+ model=getattr(agent, "model", ""), label=task.label, timeout_s=timeout,
+ spatial_tools=True, write_roots=task.write_roots, extra=extra)
+ res: AgentResult = agent.run(job)
+ usage = res.usage
+ if budget is not None:
+ budget.charge(res.usage)
+ changes = res.files_changed or changed_files_safe(ws, before)
+ if retry_silent_bail and not changes and res.exit_reason not in ("timeout", "budget"):
+ if events is not None:
+ events.emit("generate.silent_bail", label=task.label, exit_reason=res.exit_reason)
+ job2 = job.model_copy(update={"prompt": (
+ "Your previous attempt ended WITHOUT writing any file. You must create/edit the files "
+ "described below and run the build tool before finishing.\n\n" + task.prompt)})
+ res = agent.run(job2)
+ usage = usage + res.usage
+ if budget is not None:
+ budget.charge(res.usage)
+ changes = res.files_changed or changed_files_safe(ws, before)
+ notes = f"exit={res.exit_reason}" + (f"; errors={res.errors[:3]}" if res.errors else "")
+ if events is not None:
+ events.emit("generate.done", label=task.label, strategy=getattr(agent, "kind", "agent"),
+ files=[c.path for c in changes], ok=bool(changes), exit_reason=res.exit_reason,
+ cost_usd=round(usage.cost_usd, 4))
+ return GenerationResult(ok=bool(changes), usage=usage, files_changed=changes, notes=notes,
+ text=(res.text or "")[:2000], transcript_path=res.transcript_path, label=task.label)
+
+
+def generate(
+ ws: Workspace,
+ *,
+ agent_id: str,
+ task: GenerationTask,
+ agent: Any | None = None,
+ model: Any | None = None,
+ settings: Any | None = None,
+ budget: Any | None = None,
+ events: Any | None = None,
+ model_factory: Callable[[str], Any] | None = None,
+ agent_factory: Callable[[str], Any] | None = None,
+) -> GenerationResult:
+ """Dispatch to the single-shot or the coding-agent strategy by ``agent_id``.
+
+ ``agent`` / ``model`` may be injected (tests, reuse); otherwise they are
+ resolved lazily through ``codeverse.agents`` / ``codeverse.models``.
+ """
+ if is_single_shot(agent_id):
+ if model is None:
+ factory = model_factory or _default_model_factory
+ model = factory(single_shot_model_id(agent_id))
+ return generate_files(ws, model=model, task=task, budget=budget, events=events,
+ allowed_roots=tuple(r.rstrip("/") + "/" for r in task.write_roots))
+ if agent is None:
+ factory = agent_factory or _default_agent_factory
+ agent = factory(agent_id)
+ return run_agent_task(ws, agent=agent, task=task, settings=settings, budget=budget, events=events)
+
+
+def _default_model_factory(model_id: str) -> Any:
+ from codeverse.models import get_chat_model
+
+ return get_chat_model(model_id)
+
+
+def _default_agent_factory(agent_id: str) -> Any:
+ from codeverse.agents import get_coding_agent
+
+ return get_coding_agent(agent_id)
diff --git a/harness/codeverse/tracks/lifecycle.py b/harness/codeverse/tracks/lifecycle.py
new file mode 100644
index 00000000..9f2364b7
--- /dev/null
+++ b/harness/codeverse/tracks/lifecycle.py
@@ -0,0 +1,293 @@
+"""BaseTrack: the resumable plan → prepare → rounds → finalise lifecycle.
+
+Concrete tracks (static / articulated / scene) override the hooks
+(``plan_model``, ``make_pipeline``, ``prepare``, ``baseline_tasks``,
+``refine_tasks``). All bookkeeping — workspace, events, budget, run state,
+stage cache, best tracking, stop policy, record — lives here once.
+"""
+
+from __future__ import annotations
+
+import logging
+import platform
+import traceback
+from collections.abc import Sequence
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any
+
+from codeverse.config import Settings, get_settings
+from codeverse.contracts.common import Track, Usage
+from codeverse.contracts.plan import Plan
+from codeverse.contracts.run import RoundRecord, RunRecord, RunStatus
+from codeverse.contracts.spec import Spec
+from codeverse.events import EventLog
+from codeverse.orchestrator.budget import BudgetExceeded, BudgetGuard
+from codeverse.orchestrator.rounds import BestSelector, RoundPolicy, StopPolicy, StopReason
+from codeverse.orchestrator.runner import StageRunner
+from codeverse.orchestrator.state import RunState
+from codeverse.tracks.common import (
+ RunContext,
+ Services,
+ cookbook_rel_for,
+ language_contract,
+ load_prompt_or,
+)
+from codeverse.tracks.generation import GenerationTask, is_single_shot, single_shot_model_id
+from codeverse.tracks.planner import plan as run_planner
+from codeverse.tracks.steps import RoundFailed, RoundPipeline, load_round_records, run_round, sum_usage
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+_STATUS: dict[str, RunStatus] = {
+ "pass": RunStatus.PASSED, "plateau": RunStatus.PLATEAU, "max_rounds": RunStatus.PLATEAU,
+ "budget": RunStatus.BUDGET,
+}
+
+
+class BaseTrack:
+ """Shared lifecycle. Subclasses set ``track``, ``rubric``, ``plan_model``."""
+
+ track: Track
+ rubric: str
+ plan_model: type[Plan]
+
+ def __init__(
+ self,
+ *,
+ services: Services | None = None,
+ judge: Any | None = None,
+ agent: Any | None = None,
+ model: Any | None = None,
+ runtime: Any | None = None,
+ policy: RoundPolicy | None = None,
+ settings: Settings | None = None,
+ planner_model: Any | None = None,
+ ):
+ self.services = services or Services()
+ self._judge = judge
+ self._agent = agent
+ self._model = model
+ self._runtime = runtime
+ self._policy = policy
+ self._settings = settings
+ self._planner_model = planner_model
+
+ # ------------------------------------------------------------------ hooks
+ def make_pipeline(self, ctx: RunContext) -> RoundPipeline:
+ raise NotImplementedError
+
+ def prepare(self, ctx: RunContext, runner: StageRunner) -> None:
+ """Stages between plan and baseline (skeleton; scene assets/env/zones/assemble)."""
+ self.stage_skeleton(ctx, runner)
+
+ def baseline_tasks(self, ctx: RunContext) -> list[GenerationTask]:
+ raise NotImplementedError
+
+ def refine_tasks(self, ctx: RunContext, last: RoundRecord, history: Sequence[RoundRecord]) -> tuple[list[GenerationTask], list[str]]:
+ raise NotImplementedError
+
+ def round_files_hint(self, ctx: RunContext) -> list[str]:
+ return []
+
+ # ------------------------------------------------------------------ public API
+ def plan(self, spec: Spec, ws: Workspace) -> Plan:
+ ws.create()
+ events = EventLog(ws.events_path)
+ runtime = self._runtime or self.services.runtime(spec.language)
+ return run_planner(spec, spec.backends.planner, self.plan_model, ws, model=self._planner_model,
+ events=events, runtime=runtime)
+
+ def run(self, spec: Spec, ws: Workspace, *, resume: bool = False) -> RunRecord:
+ ws.create()
+ if not ws.spec_path.is_file() or not resume:
+ ws.write_json(ws.spec_path, spec)
+ events = EventLog(ws.events_path)
+ state = RunState.load_or_new(ws, resume=resume)
+ ctx = self.build_context(spec, ws, events, state)
+ runner = StageRunner(ws, events, state)
+ events.emit("run.start", track=self.track.value, language=spec.language.value, resume=resume,
+ agent=ctx.agent_id, planner=spec.backends.planner, judge=spec.backends.judge)
+ rounds: list[RoundRecord] = []
+ stop: StopReason | str = "failed"
+ error = ""
+ try:
+ ctx.plan = runner.stage("plan", lambda: self._plan_stage(ctx), inputs={"spec": spec, "track": self.track.value},
+ model=self.plan_model)
+ self.after_plan(ctx)
+ self.prepare(ctx, runner)
+ rounds = load_round_records(ctx) if resume else []
+ stop = self._round_loop(ctx, rounds)
+ except BudgetExceeded as e:
+ events.emit("budget.exceeded", reason=e.reason, spent_usd=round(e.spent_usd, 4))
+ stop, error = "budget", e.reason
+ except Exception as e: # noqa: BLE001 — persist a FAILED record, then fail loud
+ error = f"{type(e).__name__}: {e}"
+ events.emit("run.failed", error=error, traceback=traceback.format_exc()[-3000:])
+ state.status, state.error = RunStatus.FAILED, error
+ state.save(ws)
+ rec = self._record(ctx, rounds, RunStatus.FAILED, error=error, stop_reason="failed")
+ self.services.finalize_record(ws, rec)
+ raise
+ status = _STATUS.get(stop, RunStatus.FAILED)
+ rec = self.finalise(ctx, rounds, status, stop_reason=str(stop), error=error)
+ return rec
+
+ # ------------------------------------------------------------------ context
+ def build_context(self, spec: Spec, ws: Workspace, events: EventLog, state: RunState) -> RunContext:
+ settings = self._settings or get_settings()
+ runtime = self._runtime or self.services.runtime(spec.language)
+ budget = BudgetGuard(spec.budget)
+ spent = state.extra.get("spent_usage")
+ if spent:
+ budget.spent = Usage.model_validate(spent)
+ policy = self._policy or RoundPolicy(max_rounds=spec.budget.max_rounds)
+ ctx = RunContext(spec=spec, ws=ws, events=events, settings=settings, budget=budget, runtime=runtime,
+ services=self.services, state=state, policy=policy, track=self.track, rubric=self.rubric,
+ agent_id=spec.backends.generator, agent=self._agent, model=self._model)
+ ctx.contract_text = language_contract(spec.language, runtime)
+ ctx.cookbook_rel = cookbook_rel_for(spec.language)
+ ctx.cookbook_text = load_prompt_or(ctx.cookbook_rel, "")
+ ctx.tool_cards = self.services.tool_cards(self.track.value, spec.language.value)
+ for name, text in (("contract", ctx.contract_text), ("cookbook", ctx.cookbook_text)):
+ ctx.record_prompt(name, text)
+ return ctx
+
+ def after_plan(self, ctx: RunContext) -> None:
+ """Bind judge / generator backends once the plan exists (rubric threshold → policy target)."""
+ if ctx.judge is None:
+ ctx.judge = self._judge if self._judge is not None else self.services.judge(self.rubric, ctx.spec.backends.judge, n_samples=2)
+ if self._policy is None:
+ thr = self.services.rubric_threshold(self.rubric)
+ if thr is not None:
+ ctx.policy = RoundPolicy(max_rounds=ctx.spec.budget.max_rounds, target=float(thr))
+ if ctx.single_shot:
+ if ctx.model is None:
+ ctx.model = self.services.chat_model(single_shot_model_id(ctx.agent_id))
+ elif ctx.agent is None:
+ ctx.agent = self.services.coding_agent(ctx.agent_id)
+
+ def _plan_stage(self, ctx: RunContext) -> Plan:
+ ctx.state.status = RunStatus.PLANNING
+ ctx.state.save(ctx.ws)
+ plan = run_planner(ctx.spec, ctx.spec.backends.planner, self.plan_model, ctx.ws, model=self._planner_model,
+ events=ctx.events, budget=ctx.budget, runtime=ctx.runtime)
+ self._save_spent(ctx)
+ return plan
+
+ # ------------------------------------------------------------------ stages
+ def stage_skeleton(self, ctx: RunContext, runner: StageRunner) -> list[str]:
+ def _do() -> list[str]:
+ paths = ctx.runtime.skeleton(ctx.ws, ctx.plan)
+ ctx.ws.commit("skeleton")
+ return [str(Path(p).relative_to(ctx.ws.root)) if Path(p).is_absolute() else str(p) for p in paths]
+
+ return runner.stage("skeleton", _do, inputs={"plan": ctx.plan, "language": ctx.language.value})
+
+ def ensure_materialized(self, ctx: RunContext) -> None:
+ """Materialise AGENTS.md/MCP config once per run for agent generators."""
+ if ctx.single_shot:
+ return
+ kind = ctx.agent_id.split(":", 1)[0]
+ if ctx.state.materialized_for == kind:
+ return
+ mcp = ["python", "-m", "codeverse.spatial.mcp_server", "--workspace", str(ctx.ws.root)]
+ self.services.materialize(ctx.ws, agent_kind=kind, contract_md=self.agent_contract_md(ctx), cookbook_rel=ctx.cookbook_rel,
+ spatial_tools=True, mcp_command=mcp)
+ ctx.state.materialized_for = kind
+ ctx.state.save(ctx.ws)
+ ctx.events.emit("workspace.materialized", agent_kind=kind)
+
+ def agent_contract_md(self, ctx: RunContext) -> str:
+ harness = load_prompt_or("system/harness_contract.md", "")
+ return (harness + "\n\n" + ctx.contract_text).strip()
+
+ # ------------------------------------------------------------------ round loop
+ def _round_loop(self, ctx: RunContext, rounds: list[RoundRecord]) -> StopReason:
+ self.ensure_materialized(ctx)
+ pipeline = self.make_pipeline(ctx)
+ stop_policy = StopPolicy(ctx.policy)
+ selector = BestSelector()
+ while True:
+ decision = stop_policy.decide(rounds, budget_ok=ctx.budget.ok()) if rounds else "continue"
+ if decision != "continue":
+ ctx.events.emit("stop", reason=decision, rounds=len(rounds), best=ctx.state.best_round)
+ return decision
+ index = len(rounds)
+ previous = rounds[-1].judgment if rounds else None
+ if index == 0:
+ ctx.state.status = RunStatus.GENERATING
+ tasks, instructions, kind = self.baseline_tasks(ctx), [], "baseline"
+ else:
+ ctx.state.status = RunStatus.REFINING
+ tasks, instructions = self.refine_tasks(ctx, rounds[-1], rounds)
+ kind = "refine"
+ if not tasks:
+ ctx.events.emit("stop", reason="no_refine_tasks", rounds=len(rounds))
+ return "plateau"
+ ctx.state.current_round = index
+ ctx.state.save(ctx.ws)
+ try:
+ rec = run_round(ctx, index=index, kind=kind, tasks=tasks, pipeline=pipeline, instructions=instructions,
+ previous=previous, files_hint=self.round_files_hint(ctx))
+ except RoundFailed as e:
+ if index == 0:
+ raise
+ # A refine round in which no task changed any file is not a crash: the
+ # agents judged the requested edits unnecessary (or bailed). Treat it as
+ # a plateau signal so the best round so far is delivered.
+ ctx.events.emit("round.no_change", round=index, detail=str(e)[:500])
+ ctx.events.emit("stop", reason="no_change", rounds=len(rounds), best=ctx.state.best_round)
+ return "plateau"
+ rounds.append(rec)
+ ctx.state.mark_round_done(index, rec.commit)
+ best = selector.pick(rounds)
+ if best is not None and ctx.state.update_best(best, rounds[best].commit, rounds[best].score):
+ ctx.events.emit("best.updated", round=best, score=rounds[best].score)
+ self._save_spent(ctx)
+
+ def _save_spent(self, ctx: RunContext) -> None:
+ ctx.state.extra["spent_usage"] = ctx.budget.spent.model_dump(mode="json")
+ ctx.state.save(ctx.ws)
+
+ # ------------------------------------------------------------------ finalise
+ def finalise(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, stop_reason: str, error: str = "") -> RunRecord:
+ best = ctx.state.best_round
+ if best is not None and rounds and rounds[best].commit and ctx.ws.head() != rounds[best].commit:
+ ctx.ws.restore(rounds[best].commit)
+ ctx.ws.commit(f"restore best round r{best:02d}")
+ try:
+ build = ctx.runtime.build(ctx.ws, timeout_s=ctx.settings.limits.build_timeout_s)
+ ctx.events.emit("finalise.rebuild", round=best, ok=build.ok)
+ except Exception as e: # noqa: BLE001 — the best round already built once; report, don't fail
+ ctx.events.emit("finalise.rebuild_failed", error=f"{type(e).__name__}: {e}")
+ ctx.state.status, ctx.state.stop_reason, ctx.state.error = status, stop_reason, error
+ ctx.state.save(ctx.ws)
+ rec = self._record(ctx, rounds, status, error=error, stop_reason=stop_reason)
+ self.services.finalize_record(ctx.ws, rec)
+ ctx.events.emit("run.done", status=status.value, stop=stop_reason, best_round=rec.best_round,
+ final_score=rec.final_score, cost_usd=round(rec.total_usage.cost_usd, 4))
+ return rec
+
+ def _record(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, error: str, stop_reason: str) -> RunRecord:
+ best = ctx.state.best_round
+ baseline = rounds[0].score if rounds else None
+ final = rounds[best].score if best is not None and best < len(rounds) else None
+ total = sum_usage(rounds)
+ # planner + other non-round calls are in the budget guard but not in rounds
+ if ctx.budget.spent.cost_usd > total.cost_usd:
+ total = ctx.budget.spent
+ return RunRecord(
+ spec=ctx.spec, plan=ctx.plan, workspace=str(ctx.ws.root), status=status, rounds=rounds, best_round=best,
+ baseline_score=baseline, final_score=final, total_usage=total,
+ environment={"python": platform.python_version(), "host": platform.node(), "track": self.track.value,
+ "language": ctx.language.value, "generator": ctx.agent_id},
+ prompt_hashes=dict(ctx.prompt_hashes), started_at=ctx.state.started_at,
+ finished_at=datetime.now(UTC), error=error,
+ extra={"stop_reason": stop_reason, "rubric": self.rubric, "budget": ctx.budget.summary()},
+ )
+
+
+def generator_label(agent_id: str) -> str:
+ return "single-shot" if is_single_shot(agent_id) else agent_id.split(":", 1)[0]
diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.py
new file mode 100644
index 00000000..4ad59fa2
--- /dev/null
+++ b/harness/codeverse/tracks/planner.py
@@ -0,0 +1,245 @@
+"""Planner: spec → validated Plan (StaticPlan / ArticulatedPlan / ScenePlan).
+
+One structured ``ChatRequest`` (system prompt from ``prompts/tracks/plan_<track>.j2``,
+``response_schema`` = the plan model's JSON schema, reference images inline),
+validated IN CODE by the pydantic plan models; on failure the model is re-asked
+once with the exact validation errors, then ``PlanningError``. The harness
+then appends deterministic acceptance items derived from the spec constraints
+(generated artifacts are weak links — framework-owned requirements never rely
+on the model remembering them).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Any, TypeVar
+
+from pydantic import BaseModel, ValidationError
+
+from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart
+from codeverse.contracts.common import Language, Track, Usage
+from codeverse.contracts.plan import AcceptanceItem, ArticulatedPlan, ScenePlan, StaticPlan
+from codeverse.contracts.spec import Spec
+from codeverse.conventions import LANGUAGE_FRAME, frame_doc, to_pascal
+from codeverse.prompts import prompt_hash, render
+from codeverse.tracks.common import constraints_text, language_contract, load_prompt_or
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+P = TypeVar("P", bound=BaseModel)
+
+PLAN_TEMPLATES: dict[Track, str] = {
+ Track.STATIC_OBJECT: "tracks/plan_static.j2",
+ Track.ARTICULATED_OBJECT: "tracks/plan_articulated.j2",
+ Track.SCENE: "tracks/plan_scene.j2",
+}
+
+
+class PlanningError(RuntimeError):
+ """The planner could not produce a valid plan after one re-ask."""
+
+
+def plan(spec: Spec, model_id: str, plan_model: type[P], ws: Workspace, *, model: Any | None = None,
+ events: Any | None = None, budget: Any | None = None, runtime: Any | None = None) -> P:
+ """Plan and write ``ws.plan_path``. ``model`` may be injected (tests)."""
+ result, usage = plan_with_usage(spec, model_id, plan_model, ws, model=model, events=events, runtime=runtime)
+ if budget is not None:
+ budget.charge(usage)
+ return result
+
+
+def plan_with_usage(spec: Spec, model_id: str, plan_model: type[P], ws: Workspace, *, model: Any | None = None,
+ events: Any | None = None, runtime: Any | None = None) -> tuple[P, Usage]:
+ if model is None:
+ from codeverse.models import get_chat_model
+
+ model = get_chat_model(model_id)
+ system = build_system_prompt(spec, plan_model, runtime=runtime)
+ user = build_user_prompt(spec)
+ images = [ImagePart(path=r.path, label=f"{r.role}: {r.note}".strip(": ")) for r in spec.references]
+ messages = [ChatMessage.user(user, images=images or None)]
+ schema = plan_model.model_json_schema()
+ usage = Usage()
+ last_error = ""
+ for attempt in range(2):
+ req = ChatRequest(messages=messages, system=system, response_schema=schema, temperature=0.4,
+ thinking="medium", max_output_tokens=24000, label=f"planner{'-retry' if attempt else ''}")
+ resp = model.generate(req)
+ usage = usage + resp.usage
+ raw = resp.parsed if resp.parsed is not None else _parse_json(resp.text)
+ try:
+ if not isinstance(raw, dict):
+ raise ValueError(f"planner returned {type(raw).__name__}, expected a JSON object")
+ result = plan_model.model_validate(raw)
+ except (ValidationError, ValueError) as e:
+ last_error = str(e)[:4000]
+ if events is not None:
+ events.emit("plan.invalid", attempt=attempt, error=last_error[:500])
+ messages = messages + [
+ ChatMessage.assistant(json.dumps(raw)[:20000] if raw is not None else (resp.text or "")[:20000]),
+ ChatMessage.user("Your plan failed validation. Fix EXACTLY these problems and return the full corrected "
+ f"plan JSON again (same schema):\n{last_error}"),
+ ]
+ continue
+ result = ensure_acceptance(normalise_names(result), spec)
+ ws.write_json(ws.plan_path, result)
+ if events is not None:
+ events.emit("plan.done", model=model_id, attempt=attempt, n_parts=len(getattr(result, "parts", []) or []),
+ n_zones=len(getattr(result, "zones", []) or []), n_acceptance=len(result.acceptance),
+ cost_usd=round(usage.cost_usd, 4), prompt_hash=prompt_hash(system))
+ return result, usage
+ raise PlanningError(f"plan did not validate after re-ask: {last_error}")
+
+
+# ----------------------------------------------------------------------------- prompts
+def build_system_prompt(spec: Spec, plan_model: type[BaseModel], *, runtime: Any | None = None) -> str:
+ template = PLAN_TEMPLATES[spec.track]
+ lang: Language = spec.language
+ return render(
+ template,
+ track=spec.track.value,
+ language=lang.value,
+ frame_doc=frame_doc(LANGUAGE_FRAME[lang.value]),
+ contract=language_contract(lang, runtime)[:6000],
+ example_json=json.dumps(plan_example(spec.track), indent=1),
+ schema_fields=", ".join(plan_model.model_json_schema().get("properties", {}).keys()),
+ )
+
+
+def build_user_prompt(spec: Spec) -> str:
+ lines = [f"REQUEST: {spec.prompt}", "", "CONSTRAINTS:", constraints_text(spec)]
+ if spec.references:
+ lines += ["", f"REFERENCE IMAGES: {len(spec.references)} attached — match their shape, proportions and visible details; "
+ "give real-world dimensions in meters consistent with what they show."]
+ lines += ["", "Return the plan as JSON matching the schema."]
+ return "\n".join(lines)
+
+
+def _parse_json(text: str) -> Any:
+ t = (text or "").strip()
+ if t.startswith("```"):
+ t = t.strip("`")
+ t = t[t.find("\n") + 1:] if "\n" in t else t
+ try:
+ return json.loads(t)
+ except json.JSONDecodeError:
+ start, end = t.find("{"), t.rfind("}")
+ if 0 <= start < end:
+ try:
+ return json.loads(t[start:end + 1])
+ except json.JSONDecodeError:
+ return None
+ return None
+
+
+# ----------------------------------------------------------------------------- deterministic acceptance
+def ensure_acceptance(plan_obj: P, spec: Spec) -> P:
+ """Append acceptance items derived from the spec constraints when missing."""
+ items: list[AcceptanceItem] = list(plan_obj.acceptance)
+ have = {a.text.strip().lower() for a in items}
+ ids = {a.id for a in items}
+
+ def _add(prefix: str, text: str, how: str) -> None:
+ if text.strip().lower() in have:
+ return
+ n = 1
+ while f"{prefix}{n}" in ids:
+ n += 1
+ ids.add(f"{prefix}{n}")
+ items.append(AcceptanceItem(id=f"{prefix}{n}", text=text, how=how, priority="must")) # type: ignore[arg-type]
+
+ c = spec.constraints
+ if c.dimensions_m:
+ dims = ", ".join(f"{k} = {v:.3f} m" for k, v in c.dimensions_m.items())
+ _add("dim", f"Overall dimensions match the request within 5%: {dims}", "measure")
+ if c.max_triangles:
+ _add("tri", f"Triangle count ≤ {c.max_triangles}", "measure")
+ for m in c.must_have:
+ _add("must", f"Includes: {m}", "visual")
+ for m in c.must_not:
+ _add("not", f"Does NOT include: {m}", "visual")
+ if spec.track is not Track.SCENE and not any(a.how == "measure" for a in items):
+ _add("ground", "Object stands on the ground plane (lowest point at up=0) with its footprint centred", "measure")
+ plan_obj.acceptance = items
+ return plan_obj
+
+
+# ----------------------------------------------------------------------------- worked examples
+def plan_example(track: Track) -> dict[str, Any]:
+ """Compact, valid worked example per track (concrete beats abstract)."""
+ if track is Track.SCENE:
+ return {
+ "title": "Harbour at dusk", "summary": "Small fishing harbour: quay, two boats, lighthouse, calm water.",
+ "setting": "Breton coast, 1960s, clear dusk", "mood": "calm, warm low sun",
+ "bounds": {"center": [0, 5, 0], "extents": [120, 30, 120]},
+ "environment": "Sky gradient orange→indigo, sun at azimuth 250° elevation 8°, light fog density 0.004, flat sea plane y=0, stone quay at y=1.2.",
+ "zones": [
+ {"name": "Quay", "description": "L-shaped granite quay with bollards and crates", "bbox": {"center": [-20, 1.2, 0], "extents": [40, 3, 60]}, "contents": ["Bollard", "Crate"]},
+ {"name": "Water", "description": "calm harbour basin with two moored boats", "bbox": {"center": [20, 0, 0], "extents": [60, 1, 80]}, "contents": ["FishingBoat"]},
+ ],
+ "assets": [
+ {"name": "FishingBoat", "kind": "threejs", "description": "8 m wooden boat, wheelhouse aft, red hull", "approx_size_m": [8, 3.5, 3], "instances_hint": 2},
+ {"name": "Bollard", "kind": "threejs", "description": "cast-iron mooring bollard", "approx_size_m": [0.3, 0.5, 0.3], "instances_hint": 6},
+ {"name": "Crate", "kind": "blender_glb", "description": "wooden fish crate, slatted", "approx_size_m": [0.6, 0.3, 0.4], "instances_hint": 8},
+ ],
+ "effects": [{"name": "WaterRipple", "kind": "glsl_material", "description": "animated normal ripples on the sea plane", "target": "Water"}],
+ "animation": ["boats bob ±0.05 m at 0.3 Hz", "water ripples scroll"],
+ "cameras": [{"name": "Overview", "position": [45, 18, 55], "look_at": [0, 1, 0], "fov": 50, "purpose": "establishing shot"},
+ {"name": "QuayEye", "position": [-5, 2.8, 25], "look_at": [15, 1, -10], "fov": 60, "purpose": "eye level along the quay"}],
+ "acceptance": [{"id": "a1", "text": "Two boats float on the water inside the basin", "how": "visual", "priority": "must"},
+ {"id": "a2", "text": "Quay top at y≈1.2 m, boats' waterline at y≈0", "how": "probe", "priority": "must"}],
+ }
+ parts = [
+ {"name": "Seat", "role": "horizontal seat board", "description": "solid oak board, 40 mm thick, rounded front edge (r=10 mm)",
+ "bbox": {"center": [0, 0, 0.43], "extents": [0.42, 0.40, 0.04]}, "material": "oiled oak", "attach_to": None, "symmetry": "mirror_x", "instances": 1},
+ {"name": "FrontLeg", "role": "front leg", "description": "tapered round leg 35→25 mm, splayed 6° outward",
+ "bbox": {"center": [0.17, -0.16, 0.205], "extents": [0.035, 0.035, 0.41]}, "material": "oiled oak", "attach_to": "Seat", "symmetry": "mirror_x", "instances": 2},
+ ]
+ base: dict[str, Any] = {
+ "object_name": "DiningChair", "summary": "Mid-century oak dining chair, 0.45 × 0.50 × 0.82 m.",
+ "overall_bbox": {"center": [0, 0, 0.41], "extents": [0.45, 0.50, 0.82]},
+ "style_notes": "Danish mid-century: tapered legs, thin spindles, warm oak, no ornament.",
+ "parts": parts,
+ "acceptance": [{"id": "a1", "text": "Seat top at 0.45 m ± 0.02 m above the ground", "how": "measure", "priority": "must"},
+ {"id": "a2", "text": "Four legs, all touching the ground, splayed outward", "how": "visual", "priority": "must"}],
+ }
+ if track is Track.ARTICULATED_OBJECT:
+ base["object_name"] = "DeskDrawerUnit"
+ base["parts"] = [
+ {"name": "Cabinet", "role": "fixed carcass", "description": "box with open front", "bbox": {"center": [0, 0, 0.3], "extents": [0.4, 0.5, 0.6]},
+ "material": "painted MDF", "attach_to": None, "symmetry": "none", "instances": 1},
+ {"name": "Drawer", "role": "sliding drawer", "description": "open-top box with front panel and handle", "bbox": {"center": [0, -0.02, 0.45], "extents": [0.36, 0.46, 0.2]},
+ "material": "painted MDF", "attach_to": "Cabinet", "symmetry": "none", "instances": 1},
+ ]
+ base["root_link"] = "Cabinet"
+ base["joints"] = [{"name": "DrawerSlide", "type": "prismatic", "parent": "Cabinet", "child": "Drawer", "axis": [0, -1, 0],
+ "pivot": [0, -0.02, 0.45], "lower": 0.0, "upper": 0.35, "rest": 0.0, "motion": "drawer pulls out towards -Y"}]
+ base["acceptance"].append({"id": "j1", "text": "Drawer slides out 0.35 m along -Y without penetrating the cabinet", "how": "articulation", "priority": "must"})
+ return base
+
+
+def plan_model_for(track: Track) -> type[StaticPlan] | type[ArticulatedPlan] | type[ScenePlan]:
+ return {Track.STATIC_OBJECT: StaticPlan, Track.ARTICULATED_OBJECT: ArticulatedPlan, Track.SCENE: ScenePlan}[track]
+
+
+def normalise_names(plan_obj: P) -> P:
+ """PascalCase part/link/zone/asset names in place — prompts ask for it; code guarantees it.
+ Normalisation keeps the snake key, so validated uniqueness/tree properties are preserved."""
+ for attr in ("parts", "zones", "assets"):
+ for item in getattr(plan_obj, attr, None) or []:
+ item.name = to_pascal(item.name)
+ if getattr(item, "attach_to", None):
+ item.attach_to = to_pascal(item.attach_to)
+ for z in getattr(plan_obj, "zones", None) or []:
+ z.contents = [to_pascal(c) for c in z.contents]
+ if hasattr(plan_obj, "root_link"):
+ plan_obj.root_link = to_pascal(plan_obj.root_link)
+ for j in plan_obj.joints:
+ j.parent, j.child = to_pascal(j.parent), to_pascal(j.child)
+ return plan_obj
+
+
+__all__ = ["PlanningError", "plan", "plan_with_usage", "plan_model_for", "plan_example", "ensure_acceptance",
+ "normalise_names", "build_system_prompt", "build_user_prompt", "load_prompt_or"]
diff --git a/harness/codeverse/tracks/repair.py b/harness/codeverse/tracks/repair.py
new file mode 100644
index 00000000..e4769ad0
--- /dev/null
+++ b/harness/codeverse/tracks/repair.py
@@ -0,0 +1,197 @@
+"""Build → error-focused repair loop (no judge, no renders: cheap first).
+
+``build_with_repair`` runs ``runtime.lint`` + ``runtime.build``; while the
+build fails (or lint reports ERRORs) and attempts remain, it dispatches ONE
+repair task carrying a structured error report (file:line, message, traceback
+tail, lint findings with fix hints, the cookbook section matching the error
+keywords). Identical consecutive error signatures escalate (higher
+temperature/thinking for single-shot; an explicit "same error again" notice
+for agents) — the tell that the previous edit did not touch the cause.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.artifacts import BuildResult, GateReport
+from codeverse.contracts.common import Usage
+from codeverse.prompts import render
+from codeverse.tracks.common import RunContext, base_prompt_context
+from codeverse.tracks.generation import GenerationResult, GenerationTask, generate
+
+log = logging.getLogger(__name__)
+
+MAX_REPAIR_CONTEXT_CHARS = 40_000
+_TRACEBACK_TAIL_LINES = 40
+
+
+class RepairOutcome(BaseModel):
+ build: BuildResult
+ lint: GateReport
+ attempts: list[GenerationResult] = Field(default_factory=list)
+ usage: Usage = Field(default_factory=Usage)
+ repaired: bool = False
+
+ @property
+ def ok(self) -> bool:
+ return self.build.ok and not self.lint.errors
+
+
+def error_signature(build: BuildResult, lint: GateReport) -> str:
+ """Stable key for "is this the same failure as last time?"."""
+ if not build.ok:
+ first = (build.error_message or build.stderr_tail or "").strip().splitlines()
+ head = first[0][:160] if first else ""
+ return f"{build.error_type}|{build.error_file}|{build.error_line}|{head}"
+ return "lint|" + "|".join(sorted(f"{f.target}:{f.message[:80]}" for f in lint.errors))
+
+
+def format_error_report(build: BuildResult, lint: GateReport, cookbook: str = "") -> str:
+ """Compact, structured error report for the fixer (the ONLY thing it must fix)."""
+ lines: list[str] = []
+ if not build.ok:
+ loc = build.error_file + (f":{build.error_line}" if build.error_line else "") if build.error_file else "(unknown file)"
+ lines.append(f"BUILD FAILED — {build.error_type or 'Error'} at {loc}")
+ if build.error_message:
+ lines.append(f"message: {build.error_message.strip()[:1500]}")
+ tail = (build.stderr_tail or build.stdout_tail or "").strip().splitlines()[-_TRACEBACK_TAIL_LINES:]
+ if tail:
+ lines.append("traceback / log tail:")
+ lines.append("```")
+ lines.extend(line[:300] for line in tail)
+ lines.append("```")
+ if lint.errors:
+ lines.append(f"LINT ERRORS ({lint.gate}):")
+ for f in lint.errors:
+ tgt = f" [{f.target}]" if f.target else ""
+ hint = f" → FIX: {f.fix_hint}" if f.fix_hint else ""
+ lines.append(f"- {f.message}{tgt}{hint}")
+ section = relevant_cookbook_section(cookbook, " ".join([build.error_type, build.error_message, build.stderr_tail[-2000:]]))
+ if section:
+ lines.append("\nRelevant cookbook section:\n" + section)
+ return "\n".join(lines)
+
+
+_HEADING = re.compile(r"^##+ .+$", re.M)
+_WORD = re.compile(r"[A-Za-z_][A-Za-z0-9_]{3,}")
+
+
+def relevant_cookbook_section(cookbook: str, error_text: str, *, max_chars: int = 3000) -> str:
+ """Pick the cookbook ``##`` section sharing the most identifiers with the error."""
+ if not cookbook or not error_text:
+ return ""
+ heads = list(_HEADING.finditer(cookbook))
+ if not heads:
+ return ""
+ err_words = {w.lower() for w in _WORD.findall(error_text)}
+ err_words -= {"error", "line", "file", "traceback", "most", "recent", "call", "last", "module"}
+ best, best_score = "", 0
+ for i, h in enumerate(heads):
+ end = heads[i + 1].start() if i + 1 < len(heads) else len(cookbook)
+ body = cookbook[h.start():end]
+ words = {w.lower() for w in _WORD.findall(body)}
+ score = len(words & err_words)
+ if score > best_score:
+ best, best_score = body, score
+ if best_score < 2:
+ return ""
+ return best[:max_chars].rstrip()
+
+
+def files_for_repair(ctx: RunContext, build: BuildResult, lint: GateReport, files_hint: list[str]) -> dict[str, str]:
+ """Current contents of the failing file(s) (≤ 40k chars total) for single-shot repair."""
+ cands: list[str] = []
+ if build.error_file:
+ cands.append(_rel(ctx, build.error_file))
+ for f in lint.errors:
+ if f.target and "." in f.target:
+ cands.append(_rel(ctx, f.target))
+ cands.extend(files_hint)
+ if not cands:
+ for glob in getattr(ctx.runtime, "entry_globs", ()) or ():
+ cands.extend(str(p.relative_to(ctx.ws.root)) for p in sorted(ctx.ws.root.glob(glob)))
+ out: dict[str, str] = {}
+ total = 0
+ for rel in dict.fromkeys(cands):
+ p = ctx.ws.root / rel
+ if not p.is_file():
+ continue
+ text = p.read_text(errors="replace")
+ if total + len(text) > MAX_REPAIR_CONTEXT_CHARS:
+ text = text[: max(0, MAX_REPAIR_CONTEXT_CHARS - total)] + "\n// ... truncated ..."
+ out[rel] = text
+ total += len(text)
+ if total >= MAX_REPAIR_CONTEXT_CHARS:
+ break
+ return out
+
+
+def _rel(ctx: RunContext, path: str) -> str:
+ p = path.replace("\\", "/")
+ root = str(ctx.ws.root).replace("\\", "/").rstrip("/") + "/"
+ if p.startswith(root):
+ return p[len(root):]
+ return p.lstrip("./")
+
+
+def build_once(ctx: RunContext) -> tuple[BuildResult, GateReport]:
+ lint = ctx.runtime.lint(ctx.ws)
+ build = ctx.runtime.build(ctx.ws, timeout_s=ctx.settings.limits.build_timeout_s)
+ return build, lint
+
+
+def build_with_repair(ctx: RunContext, *, round_index: int, label: str, files_hint: list[str] | None = None,
+ max_attempts: int | None = None) -> RepairOutcome:
+ """Lint+build; on failure run up to ``max_repair_attempts`` error-focused repairs."""
+ files_hint = list(files_hint or [])
+ max_attempts = ctx.spec.budget.max_repair_attempts if max_attempts is None else max_attempts
+ build, lint = build_once(ctx)
+ ctx.events.emit("build.done", round=round_index, ok=build.ok, lint_errors=len(lint.errors),
+ error=build.error_message[:200], duration_ms=build.duration_ms)
+ outcome = RepairOutcome(build=build, lint=lint)
+ prev_sig = ""
+ repeats = 0
+ attempt = 0
+ while not outcome.ok and attempt < max_attempts:
+ attempt += 1
+ sig = error_signature(build, lint)
+ repeats = repeats + 1 if sig == prev_sig else 0
+ prev_sig = sig
+ task = make_repair_task(ctx, build, lint, round_index=round_index, attempt=attempt, repeats=repeats,
+ label=f"{label}_repair{attempt}", files_hint=files_hint)
+ ctx.events.emit("repair.attempt", round=round_index, attempt=attempt, repeats=repeats, signature=sig[:200])
+ res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model,
+ settings=ctx.settings, budget=ctx.budget, events=ctx.events)
+ outcome.attempts.append(res)
+ outcome.usage = outcome.usage + res.usage
+ if not res.ok:
+ log.warning("repair attempt %d produced no files (%s)", attempt, res.notes)
+ build, lint = build_once(ctx)
+ outcome.build, outcome.lint = build, lint
+ ctx.events.emit("build.done", round=round_index, ok=build.ok, lint_errors=len(lint.errors), attempt=attempt,
+ error=build.error_message[:200], duration_ms=build.duration_ms)
+ outcome.repaired = outcome.ok and attempt > 0
+ return outcome
+
+
+def make_repair_task(ctx: RunContext, build: BuildResult, lint: GateReport, *, round_index: int, attempt: int,
+ repeats: int, label: str, files_hint: list[str]) -> GenerationTask:
+ """Render prompts/tracks/repair.j2 for the current strategy."""
+ report = format_error_report(build, lint, ctx.cookbook_text)
+ files = files_for_repair(ctx, build, lint, files_hint) if ctx.single_shot else {}
+ prompt = render("tracks/repair.j2", **base_prompt_context(
+ ctx, error_report=report, files=files, repeats=repeats, attempt=attempt,
+ failing_files=sorted(files) if files else [build.error_file] if build.error_file else files_hint))
+ ctx.record_prompt("repair", prompt)
+ temperature = min(1.0, 0.3 + 0.25 * repeats)
+ thinking = ("medium", "high", "high")[min(repeats, 2)]
+ return GenerationTask(label=label, prompt=prompt, system=_repair_system(ctx), files_hint=sorted(files) or files_hint,
+ round=round_index, kind="repair", temperature=temperature, thinking=thinking)
+
+
+def _repair_system(ctx: RunContext) -> str:
+ return (f"You repair {ctx.language.value} code that failed to build. Fix only the reported error(s) with the smallest "
+ f"correct change; keep every part, name and dimension. {ctx.contract_text[:4000]}")
diff --git a/harness/codeverse/tracks/scene.py b/harness/codeverse/tracks/scene.py
new file mode 100644
index 00000000..4cf0072a
--- /dev/null
+++ b/harness/codeverse/tracks/scene.py
@@ -0,0 +1,266 @@
+"""SceneTrack: plan → skeleton → assets → env → zones → assemble → rounds.
+
+Language: scene_threejs. Generation is staged (each stage cached by
+``StageRunner`` for resume); the round loop then builds (probe + shaders),
+renders authored cameras + orbit at t=0 and t=1.5, judges with ``scene_v1``
+(console/shader errors become gate ERRORS) and dispatches refine tasks per
+zone / asset / env / camera, in parallel when file-disjoint.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Sequence
+from typing import Any
+
+from codeverse.contracts.artifacts import (
+ BuildResult,
+ GateFinding,
+ GateReport,
+ Measurement,
+ RenderSet,
+ Severity,
+)
+from codeverse.contracts.common import Track
+from codeverse.contracts.plan import ScenePlan, ZonePlan
+from codeverse.contracts.run import RoundRecord
+from codeverse.conventions import to_snake
+from codeverse.orchestrator.fanout import fan_out
+from codeverse.orchestrator.rounds import TaskGroup, build_refine_instructions, plan_parallel_groups
+from codeverse.orchestrator.runner import StageRunner
+from codeverse.prompts import render
+from codeverse.tracks.common import (
+ RunContext,
+ ServiceUnavailable,
+ base_prompt_context,
+ bbox_line,
+ file_for_target_factory,
+)
+from codeverse.tracks.generation import GenerationResult, GenerationTask, generate
+from codeverse.tracks.lifecycle import BaseTrack
+from codeverse.tracks.scene_assets import AssetResult, asset_api_summary, run_asset_stage
+from codeverse.tracks.static_object import current_files, judge_digest
+from codeverse.tracks.steps import failed_acceptance
+
+log = logging.getLogger(__name__)
+
+SCENE_TIMES: tuple[float, float] = (0.0, 1.5)
+MAX_CONSOLE_ERRORS = 8
+
+
+class ScenePipeline:
+ """No GLB measurement; gates from the build census + runtime; render_scene; console caps."""
+
+ def measure(self, ctx: RunContext, build: BuildResult) -> Measurement | None:
+ return None
+
+ def gates(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> list[GateReport]:
+ out: list[GateReport] = []
+ extra = getattr(ctx.runtime, "extra_gates", None)
+ if callable(extra):
+ out.extend(extra(ctx.ws, build))
+ census_gate = census_gate_report(build)
+ if census_gate is not None:
+ out.append(census_gate)
+ return out
+
+ def render(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> RenderSet:
+ r = ctx.settings.render
+ plan: ScenePlan = ctx.plan # type: ignore[assignment]
+ return ctx.services.render_scene(ctx.ws, ctx.ws.renders_dir(round_index), cameras=list(plan.cameras), times=SCENE_TIMES,
+ width=r.scene_width, height=r.scene_height)
+
+ def post_render_gates(self, ctx: RunContext, round_index: int, renders: RenderSet) -> list[GateReport]:
+ errs = [e for e in renders.console_errors if e.strip()]
+ findings = [GateFinding(gate="render_console", severity=Severity.ERROR, target=_guess_target(e, ctx.plan), message=e[:300],
+ fix_hint="open the named module, fix the thrown error; run the build/probe tool until no console errors")
+ for e in errs[:MAX_CONSOLE_ERRORS]]
+ if renders.fps is not None and renders.fps < 20:
+ findings.append(GateFinding(gate="render_console", severity=Severity.WARN, target="overall",
+ message=f"low frame rate {renders.fps:.0f} fps", fix_hint="reduce triangle/draw counts: merge geometries, use InstancedMesh"))
+ return [GateReport(gate="render_console", passed=not errs, findings=findings)]
+
+ def plan_summary(self, ctx: RunContext) -> str:
+ plan: ScenePlan = ctx.plan # type: ignore[assignment]
+ zones = ", ".join(z.name for z in plan.zones)
+ assets = ", ".join(a.name for a in plan.assets)
+ return f"{plan.title}: {plan.summary} Setting: {plan.setting}. Zones: {zones}. Assets: {assets}. Cameras: {', '.join(c.name for c in plan.cameras)}."
+
+ def judge_context(self, ctx: RunContext, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
+ plan: ScenePlan = ctx.plan # type: ignore[assignment]
+ lines = [f"Environment plan: {plan.environment}", "Animation plan: " + "; ".join(plan.animation)]
+ lines.append("Cameras: " + "; ".join(f"{c.name} ({c.purpose})" for c in plan.cameras))
+ return "\n".join(lines)
+
+
+class SceneTrack(BaseTrack):
+ track = Track.SCENE
+ rubric = "scene_v1"
+ plan_model = ScenePlan
+
+ def make_pipeline(self, ctx: RunContext) -> ScenePipeline:
+ return ScenePipeline()
+
+ # ------------------------------------------------------------------ stages
+ def prepare(self, ctx: RunContext, runner: StageRunner) -> None:
+ self.stage_skeleton(ctx, runner)
+ self.ensure_materialized(ctx)
+ plan: ScenePlan = ctx.plan # type: ignore[assignment]
+ assets = runner.stage("assets", lambda: run_asset_stage(ctx), inputs={"assets": plan.assets, "agent": ctx.agent_id})
+ assets = {k: AssetResult.model_validate(v) if isinstance(v, dict) else v for k, v in (assets or {}).items()}
+ ctx.extra["assets"] = assets
+ ctx.extra["asset_api"] = asset_api_summary(plan, assets)
+ runner.stage("env", lambda: self._env_stage(ctx), inputs={"plan_env": plan.environment, "setting": plan.setting, "agent": ctx.agent_id})
+ runner.stage("zones", lambda: self._zones_stage(ctx), inputs={"zones": plan.zones, "asset_api": ctx.extra["asset_api"], "agent": ctx.agent_id})
+ runner.stage("assemble", lambda: self._assemble_stage(ctx), inputs={"cameras": plan.cameras, "zones": [z.name for z in plan.zones]})
+
+ def _env_stage(self, ctx: RunContext) -> dict[str, Any]:
+ prompt = render("tracks/scene_env.j2", **self._ctx(ctx))
+ ctx.record_prompt("scene_env", prompt)
+ task = GenerationTask(label="env", prompt=prompt, system=self.system_prompt(ctx), files_hint=["src/env.js"], round=0, kind="env",
+ temperature=0.5)
+ res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
+ budget=ctx.budget, events=ctx.events)
+ ctx.ws.commit("env")
+ return {"ok": res.ok, "files": [c.path for c in res.files_changed], "notes": res.notes}
+
+ def _zones_stage(self, ctx: RunContext) -> dict[str, Any]:
+ plan: ScenePlan = ctx.plan # type: ignore[assignment]
+
+ def _one(zone: ZonePlan) -> GenerationResult:
+ task = self._zone_task(ctx, zone)
+ return generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
+ budget=ctx.budget, events=ctx.events)
+
+ results = fan_out(list(plan.zones), _one, max_workers=ctx.settings.limits.max_parallel_agents, label="zones",
+ item_name=lambda z: z.name)
+ out: dict[str, Any] = {}
+ for zone, r in zip(plan.zones, results, strict=True):
+ if isinstance(r, Exception):
+ from codeverse.orchestrator.budget import BudgetExceeded
+
+ if isinstance(r, BudgetExceeded):
+ raise r
+ out[zone.name] = {"ok": False, "notes": f"{type(r).__name__}: {r}"}
+ else:
+ out[zone.name] = {"ok": r.ok, "files": [c.path for c in r.files_changed], "notes": r.notes}
+ ctx.ws.commit("zones")
+ ctx.events.emit("zones.done", ok=[k for k, v in out.items() if v["ok"]], failed=[k for k, v in out.items() if not v["ok"]])
+ return out
+
+ def _zone_task(self, ctx: RunContext, zone: ZonePlan) -> GenerationTask:
+ plan: ScenePlan = ctx.plan # type: ignore[assignment]
+ rel = f"src/zones/{to_snake(zone.name)}.js"
+ neighbours = [f"{z.name}: {bbox_line(z.bbox)}" for z in plan.zones if z.name != zone.name]
+ prompt = render("tracks/scene_zone.j2", **self._ctx(ctx, zone_name=zone.name, zone_description=zone.description,
+ zone_bbox=bbox_line(zone.bbox), zone_contents=zone.contents,
+ zone_file=rel, neighbours=neighbours))
+ ctx.record_prompt("scene_zone", prompt)
+ return GenerationTask(label=f"zone_{to_snake(zone.name)}", prompt=prompt, system=self.system_prompt(ctx), files_hint=[rel],
+ round=0, kind="zone", temperature=0.5)
+
+ def _assemble_stage(self, ctx: RunContext) -> dict[str, Any]:
+ try:
+ result = ctx.services.assemble_scene(ctx.ws, ctx.plan)
+ ctx.ws.commit("assemble")
+ ctx.events.emit("assemble.done", deterministic=True)
+ return {"ok": True, "deterministic": True, "result": _jsonable(result)}
+ except ServiceUnavailable as e:
+ ctx.events.emit("assemble.fallback", reason=str(e))
+ prompt = render("tracks/scene_compose.j2", **self._ctx(ctx))
+ ctx.record_prompt("scene_compose", prompt)
+ task = GenerationTask(label="compose", prompt=prompt, system=self.system_prompt(ctx), files_hint=["src/scene.js"], round=0,
+ kind="compose", temperature=0.4)
+ res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
+ budget=ctx.budget, events=ctx.events)
+ ctx.ws.commit("compose")
+ return {"ok": res.ok, "deterministic": False, "files": [c.path for c in res.files_changed], "notes": res.notes}
+
+ # ------------------------------------------------------------------ rounds
+ def baseline_tasks(self, ctx: RunContext) -> list[GenerationTask]:
+ return [] # generation happened in the stages; round 0 = build → render → judge
+
+ def round_files_hint(self, ctx: RunContext) -> list[str]:
+ return ["src/scene.js", "src/env.js"]
+
+ def refine_tasks(self, ctx: RunContext, last: RoundRecord, history: Sequence[RoundRecord]) -> tuple[list[GenerationTask], list[str]]:
+ index = len(history)
+ fft = file_for_target_factory(ctx)
+ tasks = build_refine_instructions(last.judgment, last.gates, failed_acceptance(ctx, last.judgment), ctx.plan,
+ file_for_target=fft, max_tasks=ctx.policy.max_refine_tasks)
+ if not tasks and last.build is not None and not last.build.ok:
+ tasks = build_refine_instructions(None, last.gates, [], ctx.plan, file_for_target=fft)
+ if not tasks:
+ return [], []
+ groups = plan_parallel_groups(tasks)
+ parallel = len(groups) >= ctx.policy.parallel_min_tasks and all(g.files for g in groups)
+ if not parallel:
+ groups = [TaskGroup(tasks=tasks, files=sorted({f for t in tasks for f in t.files}))]
+ gen = []
+ for g in groups:
+ files = g.files or ["src/scene.js", "src/env.js"]
+ prompt = render("tracks/scene_refine.j2", **self._ctx(ctx, round_index=index, tasks=[t.line() for t in g.tasks],
+ targets=g.targets, files=files, edit_only_these=parallel,
+ judge_summary=judge_digest(last),
+ current_files=current_files(ctx, files) if ctx.single_shot else {}))
+ ctx.record_prompt("scene_refine", prompt)
+ gen.append(GenerationTask(label=f"refine_{g.label}" if parallel else "refine", prompt=prompt, system=self.system_prompt(ctx),
+ files_hint=files, round=index, kind="refine", temperature=0.4))
+ ctx.events.emit("refine.planned", round=index, n_tasks=len(tasks), n_groups=len(groups), parallel=parallel)
+ return gen, [t.line() for t in tasks]
+
+ # ------------------------------------------------------------------ helpers
+ def system_prompt(self, ctx: RunContext) -> str:
+ return ("You are an expert three.js + GLSL graphics programmer writing RAW ESM modules for a multi-file scene. "
+ "No SDKs, no DOM, no fetch, no CDN imports: `import * as THREE from 'three'` only. Exact numbers beat adjectives.")
+
+ def _ctx(self, ctx: RunContext, **extra: Any) -> dict[str, Any]:
+ plan: ScenePlan = ctx.plan # type: ignore[assignment]
+ zones_table = "\n".join(f"- {z.name}: {z.description} — {bbox_line(z.bbox)}; contents: {', '.join(z.contents) or '-'}" for z in plan.zones)
+ cameras = "\n".join(f"- {c.name}: position ({c.position[0]:.1f}, {c.position[1]:.1f}, {c.position[2]:.1f}) look_at "
+ f"({c.look_at[0]:.1f}, {c.look_at[1]:.1f}, {c.look_at[2]:.1f}) fov {c.fov:.0f} — {c.purpose}" for c in plan.cameras)
+ effects = "\n".join(f"- {e.name} ({e.kind}, on {e.target or 'scene'}): {e.description}" for e in plan.effects) or "(none)"
+ return base_prompt_context(
+ ctx, title=plan.title, setting=plan.setting, mood=plan.mood, bounds=bbox_line(plan.bounds), environment=plan.environment,
+ zones_table=zones_table, cameras=cameras, effects=effects, animation="; ".join(plan.animation) or "(none)",
+ asset_api=ctx.extra.get("asset_api", "(no assets)"), **extra)
+
+
+# ----------------------------------------------------------------------------- helpers
+def census_gate_report(build: BuildResult) -> GateReport | None:
+ """Turn scene census error lists (console/shader) into a gate, when present."""
+ c = build.census or {}
+ findings: list[GateFinding] = []
+ for key, gate in (("console_errors", "scene_probe"), ("shader_errors", "shader_probe"), ("errors", "scene_probe")):
+ for e in c.get(key, []) or []:
+ text = e if isinstance(e, str) else str(e)
+ findings.append(GateFinding(gate=gate, severity=Severity.ERROR, message=text[:300],
+ fix_hint="fix the module named in the error; rerun the build tool until the probe is clean"))
+ if not findings and not c:
+ return None
+ return GateReport(gate="scene_census", passed=not findings, findings=findings)
+
+
+def _guess_target(error: str, plan: Any) -> str:
+ low = error.lower()
+ for attr in ("zones", "assets"):
+ for item in getattr(plan, attr, None) or []:
+ if to_snake(item.name) in low:
+ return item.name
+ if "env.js" in low:
+ return "env"
+ if "scene.js" in low:
+ return "composition"
+ return "overall"
+
+
+def _jsonable(obj: Any) -> Any:
+ if hasattr(obj, "model_dump"):
+ return obj.model_dump(mode="json")
+ if isinstance(obj, (str, int, float, bool)) or obj is None:
+ return obj
+ if isinstance(obj, (list, tuple)):
+ return [_jsonable(o) for o in obj]
+ if isinstance(obj, dict):
+ return {str(k): _jsonable(v) for k, v in obj.items()}
+ return str(obj)
diff --git a/harness/codeverse/tracks/scene_assets.py b/harness/codeverse/tracks/scene_assets.py
new file mode 100644
index 00000000..f65ce9e8
--- /dev/null
+++ b/harness/codeverse/tracks/scene_assets.py
@@ -0,0 +1,267 @@
+"""Scene asset stage: one generation task per asset, fanned out.
+
+* ``threejs`` assets → ``src/assets/<snake>.js`` exporting ``build<Pascal>``.
+* ``blender_glb`` assets → a sub-workspace under ``<ws>/_assets/<snake>`` runs
+ the Blender runtime (skeleton → generate → build+repair) and the GLB is
+ copied to ``public/assets/<snake>.glb``.
+
+Each asset is optionally judged with ``asset_v1`` on a quick 4-view sheet and
+gets at most ONE fix pass (cost target ≤ $2 / scene).
+"""
+
+from __future__ import annotations
+
+import logging
+import shutil
+from dataclasses import replace
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import AssetPlan, BBox, PartPlan, ScenePlan, StaticPlan
+from codeverse.contracts.spec import Spec
+from codeverse.conventions import OBJECT_VIEWS_QUICK, to_pascal, to_snake
+from codeverse.orchestrator.fanout import fan_out
+from codeverse.prompts import render
+from codeverse.tracks.common import (
+ RunContext,
+ base_prompt_context,
+ language_contract,
+ load_prompt_or,
+)
+from codeverse.tracks.generation import GenerationTask, generate
+from codeverse.tracks.repair import build_with_repair
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+MAX_ASSETS = 8
+ASSET_RUBRIC = "asset_v1"
+
+
+class AssetResult(BaseModel):
+ name: str
+ kind: str
+ ok: bool
+ path: str = Field(default="", description="src/assets/<snake>.js or public/assets/<snake>.glb")
+ size_m: tuple[float, float, float] | None = None
+ score: float | None = None
+ fixed: bool = False
+ notes: str = ""
+
+
+def asset_file(asset: AssetPlan) -> str:
+ snake = to_snake(asset.name)
+ return f"src/assets/{snake}.js" if asset.kind == "threejs" else f"public/assets/{snake}.glb"
+
+
+def asset_api_summary(plan: ScenePlan, results: dict[str, AssetResult]) -> str:
+ """What zone/composer tasks need to know about each asset (names + sizes + how to get it)."""
+ lines = []
+ for a in plan.assets:
+ r = results.get(a.name)
+ size = (r.size_m if r and r.size_m else a.approx_size_m)
+ s = f"{size[0]:.2f}×{size[1]:.2f}×{size[2]:.2f} m (w×h×d)"
+ status = "" if (r and r.ok) else " [NOT AVAILABLE — do not reference]"
+ if a.kind == "threejs":
+ lines.append(f"- {a.name}: `import {{ build{to_pascal(a.name)} }} from './assets/{to_snake(a.name)}.js'` → Group, base at y=0, {s}{status}")
+ else:
+ lines.append(f"- {a.name}: GLB at `public/assets/{to_snake(a.name)}.glb` (load via loaders.gltf), base at y=0, {s}{status}")
+ return "\n".join(lines) or "(no assets)"
+
+
+def run_asset_stage(ctx: RunContext, *, judge_assets: bool = True) -> dict[str, AssetResult]:
+ """Generate every asset (parallel) and return results keyed by asset name."""
+ plan: ScenePlan = ctx.plan # type: ignore[assignment]
+ assets = list(plan.assets)
+ if len(assets) > MAX_ASSETS:
+ ctx.events.emit("assets.capped", n=len(assets), cap=MAX_ASSETS)
+ assets = assets[:MAX_ASSETS]
+ if not assets:
+ return {}
+ _ignore_sub_workspaces(ctx.ws)
+
+ def _one(asset: AssetPlan) -> AssetResult:
+ if asset.kind == "blender_glb":
+ return build_blender_asset(ctx, asset, judge=judge_assets)
+ return build_threejs_asset(ctx, asset, judge=judge_assets)
+
+ workers = ctx.settings.limits.max_parallel_agents
+ if any(a.kind == "blender_glb" for a in assets):
+ workers = min(workers, ctx.settings.limits.max_parallel_builds)
+ results = fan_out(assets, _one, max_workers=workers, label="assets", item_name=lambda a: a.name)
+ out: dict[str, AssetResult] = {}
+ for asset, r in zip(assets, results, strict=True):
+ if isinstance(r, Exception):
+ from codeverse.orchestrator.budget import BudgetExceeded
+
+ if isinstance(r, BudgetExceeded):
+ raise r
+ out[asset.name] = AssetResult(name=asset.name, kind=asset.kind, ok=False, notes=f"{type(r).__name__}: {r}")
+ ctx.events.emit("asset.failed", asset=asset.name, error=f"{type(r).__name__}: {r}")
+ else:
+ out[asset.name] = r
+ ctx.ws.commit("assets")
+ ctx.events.emit("assets.done", ok=[n for n, r in out.items() if r.ok], failed=[n for n, r in out.items() if not r.ok])
+ return out
+
+
+# ----------------------------------------------------------------------------- threejs asset
+def build_threejs_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> AssetResult:
+ rel = asset_file(asset)
+ task = GenerationTask(label=f"asset_{to_snake(asset.name)}", prompt=_asset_prompt(ctx, asset, rel, language=Language.SCENE_THREEJS),
+ system="You write ONE self-contained three.js ESM asset module. Raw three.js only; no DOM; no texture loading.",
+ files_hint=[rel], round=0, kind="asset", temperature=0.5)
+ res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
+ budget=ctx.budget, events=ctx.events)
+ ok = res.ok and (ctx.ws.root / rel).is_file()
+ result = AssetResult(name=asset.name, kind=asset.kind, ok=ok, path=rel if ok else "", notes=res.notes)
+ render_asset = getattr(ctx.runtime, "render_asset", None)
+ if ok and judge and callable(render_asset):
+ result = _judge_and_fix(ctx, asset, result, lambda out_dir: render_asset(ctx.ws, asset.name, out_dir), files=[rel],
+ language=Language.SCENE_THREEJS)
+ return result
+
+
+# ----------------------------------------------------------------------------- blender asset
+def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> AssetResult:
+ """Sub-workspace → Blender runtime → GLB → public/assets/<snake>.glb."""
+ snake = to_snake(asset.name)
+ sub_ws = Workspace(ctx.ws.root / "_assets" / snake).create()
+ runtime = ctx.services.runtime(Language.BLENDER)
+ sub_spec = Spec(id=f"{ctx.spec.id}-asset-{snake}", track=Track.STATIC_OBJECT, language=Language.BLENDER,
+ prompt=asset.description, budget=ctx.spec.budget, backends=ctx.spec.backends)
+ sub_plan = asset_plan(asset)
+ sub_ws.write_json(sub_ws.spec_path, sub_spec)
+ sub_ws.write_json(sub_ws.plan_path, sub_plan)
+ sub = replace(ctx, spec=sub_spec, ws=sub_ws, runtime=runtime, plan=sub_plan, track=Track.STATIC_OBJECT,
+ contract_text=language_contract(Language.BLENDER, runtime), cookbook_rel="blender/cookbook.md",
+ cookbook_text=load_prompt_or("blender/cookbook.md", ""), extra={})
+ runtime.skeleton(sub_ws, sub_plan)
+ sub_ws.commit("skeleton")
+ if not ctx.single_shot:
+ kind = ctx.agent_id.split(":", 1)[0]
+ ctx.services.materialize(sub_ws, agent_kind=kind, contract_md=sub.contract_text, cookbook_rel=sub.cookbook_rel,
+ spatial_tools=True,
+ mcp_command=["python", "-m", "codeverse.spatial.mcp_server", "--workspace", str(sub_ws.root)])
+ task = GenerationTask(label=f"asset_{snake}", prompt=_asset_prompt(sub, asset, "src/model.py", language=Language.BLENDER),
+ system="You write ONE raw bpy script (src/model.py) that builds a single scene asset. No SDKs, no render/export calls.",
+ files_hint=["src/model.py"], round=0, kind="asset", temperature=0.5)
+ res = generate(sub_ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
+ budget=ctx.budget, events=ctx.events)
+ if not res.ok:
+ return AssetResult(name=asset.name, kind=asset.kind, ok=False, notes=f"generation failed: {res.notes}")
+ sub_ws.commit("asset generated")
+ outcome = build_with_repair(sub, round_index=0, label=f"asset_{snake}", files_hint=["src/model.py"])
+ if not outcome.build.ok or not outcome.build.glb_path:
+ return AssetResult(name=asset.name, kind=asset.kind, ok=False,
+ notes=f"build failed: {outcome.build.error_type}: {outcome.build.error_message[:200]}")
+ rel = asset_file(asset)
+ dest = _copy_glb(ctx.ws, Path(outcome.build.glb_path), rel)
+ size = _measure_size(ctx, dest)
+ result = AssetResult(name=asset.name, kind=asset.kind, ok=True, path=rel, size_m=size)
+ if judge:
+ def _render(out_dir: Path):
+ return ctx.services.render_object(dest, out_dir, views=OBJECT_VIEWS_QUICK, width=512, height=512)
+
+ def _after_fix() -> bool:
+ oc = build_with_repair(sub, round_index=1, label=f"asset_{snake}_fix", files_hint=["src/model.py"])
+ if oc.build.ok and oc.build.glb_path:
+ _copy_glb(ctx.ws, Path(oc.build.glb_path), rel)
+ return True
+ return False
+
+ result = _judge_and_fix(sub, asset, result, _render, files=["src/model.py"], language=Language.BLENDER,
+ after_fix=_after_fix, parent_events=ctx.events)
+ result.size_m = _measure_size(ctx, dest) or size
+ return result
+
+
+def asset_plan(asset: AssetPlan) -> StaticPlan:
+ """A one-part StaticPlan for the asset in Blender's Z-up frame (scene sizes are Y-up w×h×d)."""
+ w, h, d = asset.approx_size_m
+ bbox = BBox(center=(0.0, 0.0, h / 2), extents=(w, d, h))
+ return StaticPlan(object_name=to_pascal(asset.name), summary=asset.description, overall_bbox=bbox,
+ parts=[PartPlan(name=to_pascal(asset.name), role="whole asset", description=asset.description, bbox=bbox)],
+ acceptance=[])
+
+
+# ----------------------------------------------------------------------------- judge + fix
+def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, render_fn: Any, *, files: list[str],
+ language: Language, after_fix: Any | None = None, parent_events: Any | None = None) -> AssetResult:
+ """Quick-sheet judge with asset_v1; ONE fix pass when below threshold."""
+ from codeverse.judges.base import JudgeInput
+
+ events = parent_events or ctx.events
+ try:
+ judge = ctx.services.judge(ASSET_RUBRIC, ctx.spec.backends.judge, n_samples=1)
+ except Exception as e: # noqa: BLE001 — asset judging is optional polish
+ events.emit("asset.judge_unavailable", asset=asset.name, error=str(e))
+ return result
+ out_dir = ctx.ws.renders_dir(0) / "assets" / to_snake(asset.name)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ try:
+ renders = render_fn(out_dir)
+ verdict: Judgment = judge.judge(JudgeInput(spec=ctx.spec, renders=renders, round_index=0,
+ plan_summary=f"{asset.name}: {asset.description}",
+ extra_context=f"Expected size ≈ {asset.approx_size_m} m (w×h×d)."))
+ except Exception as e: # noqa: BLE001
+ events.emit("asset.judge_failed", asset=asset.name, error=f"{type(e).__name__}: {e}")
+ return result
+ ctx.budget.charge(verdict.usage)
+ result.score = verdict.overall
+ events.emit("asset.judged", asset=asset.name, score=round(verdict.overall, 3), passed=verdict.passed)
+ if verdict.passed or not verdict.improvement_plan:
+ return result
+ instructions = [f"- {i.target}: {i.instruction}" for i in verdict.improvement_plan[:4]]
+ prompt = render("tracks/scene_asset.j2", **base_prompt_context(
+ ctx, asset_name=asset.name, asset_kind=asset.kind, asset_description=asset.description,
+ asset_size=asset.approx_size_m, asset_file=files[0], asset_language=language.value, fix_instructions=instructions,
+ current_code=_read(ctx.ws, files[0]) if ctx.single_shot else ""))
+ task = GenerationTask(label=f"asset_{to_snake(asset.name)}_fix", prompt=prompt, files_hint=files, round=1, kind="asset_fix",
+ temperature=0.4)
+ res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
+ budget=ctx.budget, events=ctx.events)
+ if res.ok:
+ result.fixed = after_fix() if after_fix is not None else True
+ return result
+
+
+# ----------------------------------------------------------------------------- helpers
+def _asset_prompt(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language) -> str:
+ prompt = render("tracks/scene_asset.j2", **base_prompt_context(
+ ctx, asset_name=asset.name, asset_kind=asset.kind, asset_description=asset.description, asset_size=asset.approx_size_m,
+ asset_file=rel, asset_language=language.value, fix_instructions=[], current_code=""))
+ ctx.record_prompt("scene_asset", prompt)
+ return prompt
+
+
+def _copy_glb(ws: Workspace, src: Path, rel: str) -> Path:
+ dest = ws.root / rel
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copyfile(src, dest)
+ return dest
+
+
+def _measure_size(ctx: RunContext, glb: Path) -> tuple[float, float, float] | None:
+ try:
+ m = ctx.services.measure(glb)
+ except Exception as e: # noqa: BLE001 — size is advisory for zone prompts
+ log.warning("measure_glb failed for %s: %s", glb, e)
+ return None
+ return (round(m.extents[0], 3), round(m.extents[1], 3), round(m.extents[2], 3))
+
+
+def _read(ws: Workspace, rel: str, limit: int = 30_000) -> str:
+ p = ws.root / rel
+ return p.read_text(errors="replace")[:limit] if p.is_file() else ""
+
+
+def _ignore_sub_workspaces(ws: Workspace) -> None:
+ gi = ws.root / ".gitignore"
+ text = gi.read_text() if gi.is_file() else ""
+ if "_assets/" not in text:
+ gi.write_text(text.rstrip("\n") + "\n_assets/\n")
diff --git a/harness/codeverse/tracks/static_object.py b/harness/codeverse/tracks/static_object.py
new file mode 100644
index 00000000..cf0807d4
--- /dev/null
+++ b/harness/codeverse/tracks/static_object.py
@@ -0,0 +1,220 @@
+"""StaticObjectTrack: plan → skeleton → baseline → refine rounds → finalise.
+
+Languages: blender (bpy) · cadquery · threejs. Per-part parallel refinement
+is used when the language owns one file per part (threejs) and ≥ 3
+file-disjoint task groups exist; otherwise one whole-object refine task.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections.abc import Sequence
+from pathlib import Path
+
+from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, RenderSet
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.plan import Plan, StaticPlan
+from codeverse.contracts.run import RoundRecord
+from codeverse.conventions import BBOX_TOLERANCE_M, OBJECT_VIEWS, to_snake
+from codeverse.orchestrator.rounds import (
+ RefineTask,
+ TaskGroup,
+ build_refine_instructions,
+ plan_parallel_groups,
+)
+from codeverse.prompts import render
+from codeverse.tracks.common import (
+ RunContext,
+ base_prompt_context,
+ file_for_target_factory,
+ glb_to_plan_frame,
+)
+from codeverse.tracks.generation import GenerationTask
+from codeverse.tracks.lifecycle import BaseTrack
+from codeverse.tracks.repair import format_error_report
+from codeverse.tracks.steps import failed_acceptance
+
+log = logging.getLogger(__name__)
+
+MAX_SKELETON_CHARS = 14_000
+
+
+class ObjectPipeline:
+ """Measure → connectivity + contract (+ runtime extra gates) → 8-view render."""
+
+ views = OBJECT_VIEWS
+
+ def measure(self, ctx: RunContext, build: BuildResult) -> Measurement | None:
+ return ctx.services.measure(Path(build.glb_path)) if build.glb_path else None
+
+ def gates(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> list[GateReport]:
+ out: list[GateReport] = []
+ glb = Path(build.glb_path) if build.glb_path else None
+ if glb is not None:
+ out.append(ctx.services.connectivity(glb))
+ if measurement is not None and ctx.plan is not None:
+ out.append(ctx.services.contract(measurement, ctx.plan, BBOX_TOLERANCE_M, ctx.language.value))
+ extra = getattr(ctx.runtime, "extra_gates", None)
+ if callable(extra):
+ out.extend(extra(ctx.ws, build))
+ return out
+
+ def render(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> RenderSet:
+ r = ctx.settings.render
+ return ctx.services.render_object(Path(build.glb_path), ctx.ws.renders_dir(round_index), views=self.views,
+ width=r.width, height=r.height)
+
+ def plan_summary(self, ctx: RunContext) -> str:
+ plan = ctx.plan
+ if plan is None:
+ return ""
+ parts = ", ".join(f"{p.name}×{p.instances}" if p.instances > 1 else p.name for p in plan.parts)
+ e = plan.overall_bbox.extents
+ return f"{plan.object_name}: {plan.summary} Overall {e[0]:.2f}×{e[1]:.2f}×{e[2]:.2f} m. Parts: {parts}."
+
+ def judge_context(self, ctx: RunContext, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
+ return ""
+
+
+class StaticObjectTrack(BaseTrack):
+ track = Track.STATIC_OBJECT
+ rubric = "static_object_v1"
+ plan_model = StaticPlan
+ generate_template = "tracks/generate_static.j2"
+ refine_template = "tracks/refine_object.j2"
+
+ def make_pipeline(self, ctx: RunContext) -> ObjectPipeline:
+ return ObjectPipeline()
+
+ # ------------------------------------------------------------------ baseline
+ def baseline_tasks(self, ctx: RunContext) -> list[GenerationTask]:
+ files = expected_files(ctx)
+ prompt = render(self.generate_template, **base_prompt_context(
+ ctx, expected_files=files, skeleton_files=skeleton_files(ctx) if ctx.single_shot else {}, previous_error=""))
+ ctx.record_prompt("generate", prompt)
+ return [GenerationTask(label="baseline", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=0,
+ kind="baseline", temperature=0.5, thinking="medium")]
+
+ def system_prompt(self, ctx: RunContext) -> str:
+ return (f"You are an expert {ctx.language.value} 3D modeller writing RAW code (no SDKs, no helper libraries). "
+ f"Follow the contract exactly; exact numbers beat adjectives.")
+
+ def round_files_hint(self, ctx: RunContext) -> list[str]:
+ return expected_files(ctx)
+
+ # ------------------------------------------------------------------ refine
+ def refine_tasks(self, ctx: RunContext, last: RoundRecord, history: Sequence[RoundRecord]) -> tuple[list[GenerationTask], list[str]]:
+ index = len(history)
+ if last.build is None or not last.build.ok:
+ return [self._rebuild_task(ctx, last, index)], ["rebuild: previous round did not build"]
+ fft = file_for_target_factory(ctx)
+ tasks = build_refine_instructions(last.judgment, last.gates, failed_acceptance(ctx, last.judgment), ctx.plan,
+ file_for_target=fft, max_tasks=ctx.policy.max_refine_tasks)
+ if not tasks:
+ return [], []
+ groups = plan_parallel_groups(tasks)
+ parallel = len(groups) >= ctx.policy.parallel_min_tasks and all(g.files for g in groups)
+ if not parallel:
+ groups = [TaskGroup(tasks=tasks, files=sorted({f for t in tasks for f in t.files}))]
+ gen_tasks = [self._refine_task(ctx, g, last, index, parallel=parallel) for g in groups]
+ ctx.events.emit("refine.planned", round=index, n_tasks=len(tasks), n_groups=len(groups), parallel=parallel,
+ targets=[g.targets for g in groups])
+ return gen_tasks, [t.line() for t in tasks]
+
+ def _refine_task(self, ctx: RunContext, group: TaskGroup, last: RoundRecord, index: int, *, parallel: bool) -> GenerationTask:
+ files = group.files if parallel else (group.files or expected_files(ctx))
+ prompt = render(self.refine_template, **base_prompt_context(
+ ctx, round_index=index, tasks=[t.line() for t in group.tasks], targets=group.targets, files=files,
+ edit_only_these=parallel, judge_summary=judge_digest(last), measurement_notes=measurement_vs_plan(last, ctx.plan, ctx.language),
+ current_files=current_files(ctx, files) if ctx.single_shot else {}))
+ ctx.record_prompt("refine", prompt)
+ return GenerationTask(label=f"refine_{group.label}" if parallel else "refine", prompt=prompt, system=self.system_prompt(ctx),
+ files_hint=files, round=index, kind="refine", temperature=0.4, thinking="medium")
+
+ def _rebuild_task(self, ctx: RunContext, last: RoundRecord, index: int) -> GenerationTask:
+ files = expected_files(ctx)
+ lint = next((g for g in last.gates if g.gate.startswith("lint")), GateReport(gate="lint", passed=True))
+ report = format_error_report(last.build, lint, ctx.cookbook_text) if last.build else "build did not run"
+ prompt = render(self.generate_template, **base_prompt_context(
+ ctx, expected_files=files, skeleton_files=current_files(ctx, files) if ctx.single_shot else {},
+ previous_error=report))
+ return GenerationTask(label="rebuild", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=index,
+ kind="rebuild", temperature=0.7, thinking="high")
+
+
+# ----------------------------------------------------------------------------- helpers
+def expected_files(ctx: RunContext) -> list[str]:
+ """Files the generator is expected to produce for this language + plan."""
+ lang = ctx.language
+ parts = getattr(ctx.plan, "parts", None) or []
+ if lang is Language.THREEJS:
+ return ["src/object.js"] + [f"src/parts/{to_snake(p.name)}.js" for p in parts]
+ if lang is Language.URDF_BLENDER:
+ return ["src/model.py", "src/robot.urdf"]
+ if lang is Language.SCENE_THREEJS:
+ return ["src/scene.js", "src/env.js"]
+ return ["src/model.py"]
+
+
+def skeleton_files(ctx: RunContext, max_chars: int = MAX_SKELETON_CHARS) -> dict[str, str]:
+ """Current src/ files (the skeleton), trimmed, for single-shot prompts."""
+ return current_files(ctx, [str(p.relative_to(ctx.ws.root)) for p in sorted(ctx.ws.src.rglob("*")) if p.is_file()], max_chars)
+
+
+def current_files(ctx: RunContext, rels: Sequence[str], max_chars: int = MAX_SKELETON_CHARS) -> dict[str, str]:
+ out: dict[str, str] = {}
+ total = 0
+ for rel in rels:
+ p = ctx.ws.root / rel
+ if not p.is_file():
+ continue
+ text = p.read_text(errors="replace")
+ room = max_chars - total
+ if room <= 0:
+ break
+ if len(text) > room:
+ text = text[:room] + "\n# ... truncated ...\n"
+ out[rel] = text
+ total += len(text)
+ return out
+
+
+def judge_digest(last: RoundRecord, max_issues: int = 8) -> str:
+ j = last.judgment
+ if j is None:
+ return "(no judgment for the previous round)"
+ lines = [f"Previous score {j.overall:.2f} ({'passed' if j.passed else 'not passed'}). {j.summary}".strip()]
+ for k, v in sorted(j.scores.items(), key=lambda kv: kv[1])[:6]:
+ lines.append(f"- {k}: {v:.2f}")
+ for i in j.issues[:max_issues]:
+ lines.append(f"- [{i.severity}/{i.kind}] {i.target}: {i.detail}" + (f" (seen in {i.evidence})" if i.evidence else ""))
+ return "\n".join(lines)
+
+
+def measurement_vs_plan(last: RoundRecord, plan: Plan | None, language: Language = Language.THREEJS) -> str:
+ """Exact numbers (in the plan's frame): measured overall/part bboxes vs planned ones."""
+ m = last.measurement
+ if m is None or plan is None or not hasattr(plan, "overall_bbox"):
+ return ""
+ pe = plan.overall_bbox.extents
+ me = glb_to_plan_frame(m.extents, language, extents=True)
+ lines = [f"Measured overall extents {me[0]:.3f}×{me[1]:.3f}×{me[2]:.3f} m vs plan "
+ f"{pe[0]:.3f}×{pe[1]:.3f}×{pe[2]:.3f} m; ground gap {m.ground_gap_m:+.3f} m; footprint offset {m.footprint_offset_m:.3f} m; "
+ f"{m.tri_count} tris, {m.n_meshes} meshes, {m.n_islands} islands."]
+ planned = {to_snake(p.name): p for p in getattr(plan, "parts", [])}
+ for pm in m.parts[:24]:
+ p = planned.get(to_snake(pm.name))
+ if p is None:
+ continue
+ ext = glb_to_plan_frame([b - a for a, b in zip(pm.bbox_min, pm.bbox_max, strict=True)], language, extents=True)
+ cen = glb_to_plan_frame([(a + b) / 2 for a, b in zip(pm.bbox_min, pm.bbox_max, strict=True)], language)
+ lines.append(f"- {p.name}: measured centre ({cen[0]:.3f}, {cen[1]:.3f}, {cen[2]:.3f}) extents ({ext[0]:.3f}, {ext[1]:.3f}, {ext[2]:.3f})"
+ f" | plan centre ({p.bbox.center[0]:.3f}, {p.bbox.center[1]:.3f}, {p.bbox.center[2]:.3f}) extents "
+ f"({p.bbox.extents[0]:.3f}, {p.bbox.extents[1]:.3f}, {p.bbox.extents[2]:.3f})")
+ gate_lines = [f"- GATE {g.gate}: {f.message}" + (f" FIX: {f.fix_hint}" if f.fix_hint else "")
+ for g in last.gates for f in g.errors][:12]
+ return "\n".join(lines + gate_lines)
+
+
+def refine_task_lines(tasks: Sequence[RefineTask]) -> list[str]:
+ return [t.line() for t in tasks]
diff --git a/harness/codeverse/tracks/steps.py b/harness/codeverse/tracks/steps.py
new file mode 100644
index 00000000..0dd25885
--- /dev/null
+++ b/harness/codeverse/tracks/steps.py
@@ -0,0 +1,212 @@
+"""One round = generate → build(+repair) → gates → measure → render → judge → commit.
+
+``run_round`` is track-agnostic; a ``RoundPipeline`` supplies the track-specific
+gates / measurement / rendering. Every step writes its artifact under the
+workspace (gates/rNN, renders/rNN, judge/rNN.json, rounds/rNN.json) so a run
+can be resumed and the flywheel can replay it.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+from collections.abc import Sequence
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, Protocol
+
+from codeverse.contracts.artifacts import BuildResult, GateReport, Measurement, RenderSet
+from codeverse.contracts.common import Usage
+from codeverse.contracts.judgment import Judgment
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.contracts.run import RoundRecord
+from codeverse.orchestrator.fanout import fan_out
+from codeverse.tracks.common import RunContext
+from codeverse.tracks.generation import GenerationResult, GenerationTask, generate
+from codeverse.tracks.repair import RepairOutcome, build_with_repair
+
+log = logging.getLogger(__name__)
+
+
+class RoundPipeline(Protocol):
+ """Track-specific steps after a successful build."""
+
+ def measure(self, ctx: RunContext, build: BuildResult) -> Measurement | None: ...
+ def gates(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> list[GateReport]: ...
+ def render(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> RenderSet: ...
+ def plan_summary(self, ctx: RunContext) -> str: ...
+ def judge_context(self, ctx: RunContext, round_index: int, build: BuildResult, gates: list[GateReport]) -> str: ...
+
+
+class RoundFailed(RuntimeError):
+ """Every generation task of a round failed — nothing to build."""
+
+
+def round_record_path(ctx: RunContext, index: int) -> Path:
+ return ctx.ws.root / "rounds" / f"r{index:02d}.json"
+
+
+def load_round_records(ctx: RunContext) -> list[RoundRecord]:
+ """Rounds persisted so far (sorted by index, contiguous prefix only)."""
+ d = ctx.ws.root / "rounds"
+ if not d.is_dir():
+ return []
+ out: list[RoundRecord] = []
+ for i, p in enumerate(sorted(d.glob("r*.json"))):
+ rec = RoundRecord.model_validate(ctx.ws.read_json(p))
+ if rec.index != i:
+ break
+ out.append(rec)
+ return out
+
+
+def run_generation_tasks(ctx: RunContext, tasks: Sequence[GenerationTask]) -> list[GenerationResult]:
+ """Run tasks (parallel when > 1). Raises ``RoundFailed`` when none succeeded."""
+ if not tasks:
+ return []
+
+ def _one(task: GenerationTask) -> GenerationResult:
+ return generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model,
+ settings=ctx.settings, budget=ctx.budget, events=ctx.events)
+
+ if len(tasks) == 1:
+ results: list[GenerationResult | Exception] = [_one(tasks[0])]
+ else:
+ results = fan_out(list(tasks), _one, max_workers=ctx.settings.limits.max_parallel_agents,
+ label="generate", item_name=lambda t: t.label)
+ out: list[GenerationResult] = []
+ for task, r in zip(tasks, results, strict=True):
+ if isinstance(r, Exception):
+ from codeverse.orchestrator.budget import BudgetExceeded
+
+ if isinstance(r, BudgetExceeded):
+ raise r
+ ctx.events.emit("generate.failed", label=task.label, error=f"{type(r).__name__}: {r}")
+ out.append(GenerationResult(ok=False, notes=f"{type(r).__name__}: {r}", label=task.label))
+ else:
+ out.append(r)
+ if not any(r.ok for r in out):
+ raise RoundFailed("; ".join(f"{r.label}: {r.notes}" for r in out) or "no generation task succeeded")
+ return out
+
+
+def run_round(
+ ctx: RunContext,
+ *,
+ index: int,
+ kind: str,
+ tasks: Sequence[GenerationTask],
+ pipeline: RoundPipeline,
+ instructions: Sequence[str] = (),
+ previous: Judgment | None = None,
+ files_hint: Sequence[str] = (),
+) -> RoundRecord:
+ """Execute one round and persist its record. Budget is charged as it goes."""
+ t0 = time.time()
+ ctx.events.emit("round.start", round=index, kind=kind, n_tasks=len(tasks))
+ rec = RoundRecord(index=index, kind=kind, agent_backend=ctx.agent_id, instructions=list(instructions),
+ started_at=datetime.now(UTC))
+ usage = Usage()
+ notes: list[str] = []
+
+ gens = run_generation_tasks(ctx, tasks)
+ for g in gens:
+ usage = usage + g.usage
+ if not g.ok:
+ notes.append(f"{g.label}: {g.notes}")
+ ctx.ws.commit(f"r{index:02d} {kind}: generated")
+
+ outcome: RepairOutcome = build_with_repair(ctx, round_index=index, label=f"r{index:02d}_{kind}",
+ files_hint=list(files_hint))
+ usage = usage + outcome.usage
+ rec.build = outcome.build
+ gates: list[GateReport] = [outcome.lint]
+ if outcome.attempts:
+ notes.append(f"repair attempts: {len(outcome.attempts)} ({'fixed' if outcome.ok else 'still failing'})")
+
+ if outcome.build.ok:
+ rec.measurement = pipeline.measure(ctx, outcome.build)
+ gates.extend(pipeline.gates(ctx, index, outcome.build, rec.measurement))
+ rec.renders = pipeline.render(ctx, index, outcome.build, rec.measurement)
+ post = getattr(pipeline, "post_render_gates", None)
+ if callable(post) and rec.renders is not None:
+ gates.extend(post(ctx, index, rec.renders))
+ n_err = sum(len(g.errors) for g in gates)
+ ctx.events.emit("gates.done", round=index, n_gates=len(gates), n_errors=n_err,
+ tri_count=rec.measurement.tri_count if rec.measurement else None)
+ if ctx.judge is not None and rec.renders is not None and rec.renders.views and (n_err == 0 or ctx.policy.judge_on_gate_errors):
+ rec.judgment = _judge(ctx, pipeline, index, outcome.build, gates, rec, previous)
+ if rec.judgment is not None:
+ usage = usage + rec.judgment.usage
+ ctx.budget.charge(rec.judgment.usage)
+ elif ctx.judge is None:
+ notes.append("no judge configured")
+ else:
+ notes.append("judge skipped (gate errors)")
+ else:
+ notes.append(f"build failed: {outcome.build.error_type}: {outcome.build.error_message[:200]}")
+ rec.gates = gates
+ _write_gate_reports(ctx, index, gates)
+
+ rec.commit = ctx.ws.commit(f"r{index:02d} {kind}")
+ rec.usage = usage
+ rec.duration_s = round(time.time() - t0, 2)
+ rec.notes = "; ".join(notes)
+ ctx.ws.write_json(round_record_path(ctx, index), rec)
+ ctx.events.emit("round.done", round=index, kind=kind, commit=rec.commit[:10], score=rec.score,
+ build_ok=outcome.build.ok, duration_s=rec.duration_s, cost_usd=round(usage.cost_usd, 4))
+ return rec
+
+
+def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildResult, gates: list[GateReport],
+ rec: RoundRecord, previous: Judgment | None) -> Judgment | None:
+ from codeverse.judges.base import JudgeInput
+
+ inp = JudgeInput(
+ spec=ctx.spec, renders=rec.renders, measurement=rec.measurement, gates=gates,
+ acceptance=list(getattr(ctx.plan, "acceptance", []) or []), plan_summary=pipeline.plan_summary(ctx),
+ round_index=index, previous=previous, extra_context=pipeline.judge_context(ctx, index, build, gates),
+ )
+ t0 = time.time()
+ try:
+ judgment: Judgment = ctx.judge.judge(inp)
+ except Exception as e: # noqa: BLE001 — a judge outage must not destroy the run's code/commits
+ log.exception("judge failed in round %d", index)
+ ctx.events.emit("judge.failed", round=index, error=f"{type(e).__name__}: {e}")
+ rec.notes = (rec.notes + "; " if rec.notes else "") + f"judge failed: {type(e).__name__}: {e}"
+ return None
+ ctx.ws.write_json(ctx.ws.judge_path(index), judgment)
+ ctx.events.emit("judge.done", round=index, overall=round(judgment.overall, 3), passed=judgment.passed,
+ n_issues=len(judgment.issues), n_plan=len(judgment.improvement_plan),
+ duration_s=round(time.time() - t0, 1), cost_usd=round(judgment.usage.cost_usd, 4))
+ return judgment
+
+
+def _write_gate_reports(ctx: RunContext, index: int, gates: list[GateReport]) -> None:
+ d = ctx.ws.gates_dir(index)
+ d.mkdir(parents=True, exist_ok=True)
+ for g in gates:
+ name = g.gate.replace(":", "_").replace("/", "_")
+ ctx.ws.write_json(d / f"{name}.json", g)
+
+
+def failed_acceptance(ctx: RunContext, judgment: Judgment | None) -> list[AcceptanceItem]:
+ """Acceptance items the judge marked as not verified."""
+ if judgment is None:
+ return []
+ items = {a.id: a for a in (getattr(ctx.plan, "acceptance", []) or [])}
+ return [items[k] for k, ok in judgment.acceptance_results.items() if not ok and k in items]
+
+
+def sum_usage(rounds: Sequence[RoundRecord], *extra: Usage) -> Usage:
+ total = Usage()
+ for r in rounds:
+ total = total + r.usage
+ for u in extra:
+ total = total + u
+ return total
+
+
+def describe_round(rec: RoundRecord) -> dict[str, Any]:
+ return {"index": rec.index, "kind": rec.kind, "score": rec.score, "build_ok": bool(rec.build and rec.build.ok),
+ "gate_errors": sum(len(g.errors) for g in rec.gates), "commit": rec.commit[:10]}
diff --git a/harness/codeverse/workspace.py b/harness/codeverse/workspace.py
new file mode 100644
index 00000000..7b43d2da
--- /dev/null
+++ b/harness/codeverse/workspace.py
@@ -0,0 +1,197 @@
+"""Run workspace: fixed directory layout + git snapshots of ``src/``.
+
+A workspace is a directory under ``runs/<slug>/`` (see docs/ARCHITECTURE.md §3).
+``src/`` (and ``public/``) is a git repository so every round is a commit:
+diffs, rollback and "files changed by the agent" come for free and the
+flywheel can replay any round.
+"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+import threading
+import time
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel
+
+from codeverse.contracts.agent import FileChange
+
+_DIRS = ("src", "public", "artifacts", "artifacts/renders", "artifacts/gates", "artifacts/judge", "trajectories")
+
+
+class Workspace:
+ """Paths + snapshot helpers for one run. Cheap to construct; no I/O until used."""
+
+ def __init__(self, root: Path | str):
+ self.root = Path(root).resolve()
+
+ # ----------------------------------------------------------------- paths
+ @property
+ def src(self) -> Path:
+ return self.root / "src"
+
+ @property
+ def public(self) -> Path:
+ return self.root / "public"
+
+ @property
+ def artifacts(self) -> Path:
+ return self.root / "artifacts"
+
+ @property
+ def trajectories(self) -> Path:
+ return self.root / "trajectories"
+
+ def renders_dir(self, round_index: int) -> Path:
+ return self.artifacts / "renders" / f"r{round_index:02d}"
+
+ def gates_dir(self, round_index: int) -> Path:
+ return self.artifacts / "gates" / f"r{round_index:02d}"
+
+ def judge_path(self, round_index: int, suffix: str = "") -> Path:
+ return self.artifacts / "judge" / f"r{round_index:02d}{suffix}.json"
+
+ def trajectory_dir(self, stage: str, round_index: int) -> Path:
+ d = self.trajectories / f"{stage}_r{round_index:02d}"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+ @property
+ def spec_path(self) -> Path:
+ return self.root / "spec.json"
+
+ @property
+ def plan_path(self) -> Path:
+ return self.root / "plan.json"
+
+ @property
+ def state_path(self) -> Path:
+ return self.root / "run_state.json"
+
+ @property
+ def record_path(self) -> Path:
+ return self.root / "record.json"
+
+ @property
+ def events_path(self) -> Path:
+ return self.root / "events.jsonl"
+
+ # ----------------------------------------------------------------- lifecycle
+ def create(self) -> Workspace:
+ for d in _DIRS:
+ (self.root / d).mkdir(parents=True, exist_ok=True)
+ self._git_init()
+ return self
+
+ def exists(self) -> bool:
+ return self.spec_path.is_file()
+
+ # ----------------------------------------------------------------- json io
+ def write_json(self, path: Path, model: BaseModel | dict[str, Any]) -> None:
+ """Atomic JSON write (tmp + rename)."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(path.suffix + ".tmp")
+ data = model.model_dump(mode="json") if isinstance(model, BaseModel) else model
+ tmp.write_text(json.dumps(data, indent=2, ensure_ascii=False))
+ tmp.replace(path)
+
+ def read_json(self, path: Path) -> dict[str, Any]:
+ return json.loads(path.read_text())
+
+ # ----------------------------------------------------------------- git
+ _LOCKS: dict[str, threading.RLock] = {}
+ _LOCKS_GUARD = threading.Lock()
+
+ @property
+ def _lock(self) -> threading.RLock:
+ """One in-process lock per workspace root: parallel agent/tool threads
+ must not race on .git/index."""
+ key = str(self.root)
+ with Workspace._LOCKS_GUARD:
+ return Workspace._LOCKS.setdefault(key, threading.RLock())
+
+ def _git(self, *args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
+ with self._lock:
+ for attempt in range(4):
+ proc = subprocess.run(
+ ["git", *args], cwd=self.root, text=True, capture_output=True, check=False,
+ env={"GIT_AUTHOR_NAME": "c3v", "GIT_AUTHOR_EMAIL": "c3v@local",
+ "GIT_COMMITTER_NAME": "c3v", "GIT_COMMITTER_EMAIL": "c3v@local",
+ "PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": str(self.root)},
+ )
+ if proc.returncode == 0 or "index.lock" not in (proc.stderr or ""):
+ break
+ time.sleep(0.2 * (attempt + 1)) # another process holds .git/index.lock
+ if check and proc.returncode != 0:
+ raise subprocess.CalledProcessError(proc.returncode, proc.args, proc.stdout, proc.stderr)
+ return proc
+
+ def _git_init(self) -> None:
+ if (self.root / ".git").exists():
+ return
+ self._git("init", "-q")
+ (self.root / ".gitignore").write_text(
+ "# harness-owned run state is never part of the code snapshot\n"
+ "artifacts/\ntrajectories/\nstages/\nrounds/\n_assets/\n.c3v/\n.gemini/\n.claude/\n"
+ "events.jsonl\nrun_state.json\nrecord.json\n*.log\nnode_modules/\n*.tmp\n__pycache__/\n"
+ )
+ self._git("add", "-A")
+ self._git("commit", "-q", "-m", "init", "--allow-empty")
+
+ def commit(self, message: str) -> str:
+ """Commit everything tracked (src/, public/, plan, ...) and return the sha."""
+ self._git("add", "-A")
+ self._git("commit", "-q", "-m", message, "--allow-empty")
+ return self._git("rev-parse", "HEAD").stdout.strip()
+
+ def head(self) -> str:
+ return self._git("rev-parse", "HEAD").stdout.strip()
+
+ def changed_files(self, since: str | None = None) -> list[FileChange]:
+ """Files changed vs ``since`` (a commit) or vs HEAD (uncommitted work)."""
+ self._git("add", "-A", "-N") # register untracked so they show up in diff
+ args = ["diff", "--numstat", "--diff-filter=ADM"] + ([since] if since else ["HEAD"])
+ out = self._git(*args).stdout
+ status = {}
+ for line in self._git("diff", "--name-status", since or "HEAD").stdout.splitlines():
+ if "\t" in line:
+ st, path = line.split("\t", 1)
+ status[path] = {"A": "added", "D": "deleted"}.get(st[0], "modified")
+ changes = []
+ for line in out.splitlines():
+ parts = line.split("\t")
+ if len(parts) != 3:
+ continue
+ add, rem, path = parts
+ changes.append(FileChange(path=path, status=status.get(path, "modified"),
+ lines_added=int(add) if add.isdigit() else 0,
+ lines_removed=int(rem) if rem.isdigit() else 0))
+ return changes
+
+ def restore(self, commit: str) -> None:
+ """Make src/ + public/ exactly match ``commit`` (artifacts untouched)."""
+ tracked = self._git("ls-tree", "--name-only", commit).stdout.split()
+ roots = [r for r in ("src", "public") if r in tracked]
+ # remove current tracked+untracked content of the roots, then check out the target
+ self._git("rm", "-r", "-q", "--cached", "--ignore-unmatch", "--", "src", "public")
+ for r in ("src", "public"):
+ d = self.root / r
+ if d.exists():
+ shutil.rmtree(d)
+ d.mkdir(parents=True, exist_ok=True)
+ if roots:
+ self._git("checkout", "-q", commit, "--", *roots)
+ self._git("add", "-A")
+
+ def diff(self, a: str, b: str = "HEAD") -> str:
+ return self._git("diff", a, b, "--", "src", "public").stdout
+
+ def snapshot_src(self, dest: Path) -> None:
+ """Copy src/ (raw code only) to ``dest`` — used by the flywheel exporter."""
+ if dest.exists():
+ shutil.rmtree(dest)
+ shutil.copytree(self.src, dest, ignore=shutil.ignore_patterns("node_modules", "__pycache__"))
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
new file mode 100644
index 00000000..9b2e62d1
--- /dev/null
+++ b/harness/docs/ARCHITECTURE.md
@@ -0,0 +1,172 @@
+# 3dcodeverse harness — architecture
+
+Package `codeverse`, CLI `c3v`. Backend only. Python 3.11+ and a small Node
+runtime (`runtime_js/`) for everything Three.js / headless-Chrome.
+
+## 0. What it is
+
+A data-flywheel harness in which LLMs write **raw executable 3D code** — no SDK
+layered on top of the language — for three **tracks**:
+
+| track | languages | deliverable |
+|---|---|---|
+| `static_object` | `blender` (bpy), `cadquery`, `threejs` | code + canonical `object.glb` (+stl/step) |
+| `articulated_object` | `urdf_blender` (bpy link meshes + hand-written URDF) | code + `robot.urdf` + `meshes/*.glb` + `object.glb` (node hierarchy) |
+| `scene` | `scene_threejs` (multi-file three.js + GLSL; optional bpy-built GLB assets) | `src/**` + renders + probes |
+
+…driven by **any** of these backends behind two protocols:
+
+* `ChatModel` (API): `gemini:*`, `anthropic:*`, `openai:*` — used by the planner,
+ the judge, the captioner, and by the in-process `api-agent`.
+* `CodingAgent` (agentic session on a workspace): `gemini-cli:*`, `claude-code:*`,
+ `codex:*`, `agy:*` (Antigravity), and `api-agent:<chat-model>` (our own
+ tool loop so API-only users get parity).
+
+Every run is: **spec → plan → generate → lint → build → gates → measure →
+render → judge → refine… → record**. The record (plus git history of `src/`)
+is the flywheel unit.
+
+## 1. Design laws (from the reference post-mortems)
+
+1. **Code is truth; artifacts are derived.** Raw code in `src/` is the
+ deliverable; GLB/renders are regenerated from it.
+2. **Concrete beats abstract.** Compliance of flash-class models is
+ probabilistic and set by concreteness: contracts are delivered as *skeleton
+ code, exact numbers, copyable snippets* (cookbooks), never as clauses.
+3. **Code answers when code can answer.** Deterministic gates / measurements
+ / normalisers run by the harness (never pasted by the agent) catch the
+ residue; the VLM is used only for perception and judgement.
+4. **Move responsibility out of agent code** where possible: export wrappers,
+ camera rigs, placement validation, URDF composition math, scene assembly.
+5. **Evidence-based acceptance.** Every plan carries an acceptance checklist;
+ items are proved by measurements/probes/judge evidence, not by prose.
+6. **Typed everything.** One contracts package; no regex-on-id control flow,
+ no stringly-typed dict conventions, no god files (target ≤ 400 lines).
+7. **Cheap first.** Static lint → build → deterministic gates → quick 4-view
+ sheet → VLM. Never call a VLM on something a gate already rejected.
+8. **Separate generator from judge.** The judge sees spec + renders +
+ measurements + acceptance list; never the generator's reasoning.
+9. **Cost is a budget, not a log.** Hard per-run ceilings; key pools with
+ per-key limiters; every call yields a `Usage`.
+10. **Reproducible.** Prompt/rubric/cookbook hashes and tool versions are
+ recorded on every round.
+
+## 2. Package map
+
+```
+codeverse/
+ conventions.py frames, units, view presets, name normalisation (THE source)
+ config.py Settings (keys, binaries, dirs, defaults) from env/yaml
+ contracts/ pydantic: Spec, Plan(s), BuildResult, Measurement, RenderSet,
+ GateReport, Judgment, RoundRecord/RunRecord, Chat*, Agent*
+ workspace.py run-dir layout + git snapshots
+ events.py JSONL event log per run
+ models/ ChatModel protocol; gemini.py anthropic.py openai.py;
+ keypool.py (RPM/TPM buckets, rotate on 429); pricing.py; registry.py
+ agents/ CodingAgent protocol; gemini_cli.py claude_code.py codex.py
+ antigravity.py api_agent.py (tool loop); materialize.py
+ (AGENTS.md/GEMINI.md/CLAUDE.md + MCP config per workspace);
+ watchdog.py (activity-aware subprocess); registry.py
+ languages/ LanguageRuntime protocol; blender/ cadquery/ threejs/ urdf/
+ scene_threejs/ — each: runtime.py (build+export), lint.py,
+ skeleton.py (starter files from plan), wrappers/ (bpy/node
+ scripts the harness runs — NOT imported by agent code)
+ spatial/ language-agnostic tools on GLB/URDF/scene: measure.py,
+ connectivity.py, render.py (three headless GPU), sections.py,
+ silhouette.py, joints.py (FK, pose sweep, collisions),
+ probes.py (scene census/fps/errors), registry.py (@tool →
+ python fn + JSON schema + prompt card), mcp_server.py
+ judges/ vlm_judge.py (rubric yaml → Judgment, n-sample, code-computed
+ score, floors), pairwise.py, reference.py, metrics.py, rubrics/
+ tracks/ base.py (Track protocol), static_object.py,
+ articulated_object.py, scene.py — each composes stages
+ orchestrator/ runner.py (stages+resume), rounds.py (refine loop, stop
+ policy, best selection), fanout.py, budget.py
+ flywheel/ record.py, export.py (sample folders + parquet), pairs.py
+ (preference/repair pairs), captions.py, dedupe.py
+ prompts/ system/*.md, <language>/cookbook.md + skeletons, tracks/*.j2
+ cli/main.py c3v make | resume | judge | render | tools | flywheel | bench | doctor
+runtime_js/ node package: export_glb.mjs, render_glb.mjs, render_scene.mjs,
+ probe_scene.mjs, check_shaders.mjs, gpu_launch.cjs, serve.cjs
+```
+
+## 3. Workspace layout (one run)
+
+```
+runs/<slug>/
+ spec.json plan.json run_state.json record.json events.jsonl
+ src/ agent-authored RAW code (git repo; one commit per round)
+ public/ (scene) compiled assets e.g. GLBs built from bpy
+ artifacts/ object.glb object.stl robot.urdf meshes/ measurement.json
+ renders/rNN/ view_*.png sheet.png turntable.mp4
+ gates/rNN/ *.json
+ judge/rNN.json
+ trajectories/<stage>_rNN/ prompt.md transcript.jsonl result.json
+ AGENTS.md GEMINI.md CLAUDE.md .mcp.json .gemini/settings.json (materialised)
+```
+
+## 4. Per-language authoring contracts (raw code; the harness owns export)
+
+* **blender**: `src/model.py` — pure bpy, Z-up, -Y front, meters; builds named
+ objects (PascalCase = part names) into the current scene; no camera/lights/
+ render/export calls. Harness: `blender -b --factory-startup --python
+ wrappers/run_bpy.py -- --script src/model.py --out artifacts/` → clears scene,
+ runs script with RLIMIT, collects census, applies transforms, exports GLB+STL.
+* **cadquery**: `src/model.py` — `import cadquery as cq` only; module-level
+ `result` = `cq.Assembly` (named parts) or `Workplane`. Harness exports
+ STEP/STL per part → GLB with named nodes.
+* **threejs** (static): `src/parts/<snake>.js` each `export function
+ build<Pascal>(THREE) → THREE.Group` at world pose (Y-up, +Z front, meters);
+ `src/object.js` `export function build(THREE) → THREE.Group` assembling parts;
+ optional `userData.tick(dt)`. Harness exports GLB via node GLTFExporter.
+* **urdf_blender**: `src/model.py` (bpy) builds one object per link named
+ `<link>`; `src/robot.urdf` written by the agent (native URDF, meshes as
+ `meshes/<link>.glb`, joint frames per URDF semantics). Harness exports per-link
+ meshes, lints URDF, composes FK, sweeps poses, builds `object.glb` with nodes.
+* **scene_threejs**: `src/scene.js` `export function createScene({THREE, renderer,
+ loaders}) → {scene, cameras, update(t,dt)}`; `src/env.js`, `src/zones/*.js`,
+ `src/assets/*.js`, `src/shaders/*.js`; Blender-built assets compiled to
+ `public/assets/<name>.glb` and loaded via GLTFLoader; GLSL inline via
+ ShaderMaterial / onBeforeCompile using the cookbook's copyable boilerplate.
+
+## 5. Spatial tool registry
+
+`@tool` registers a python function with a pydantic args model → (a) direct
+call from tracks, (b) MCP server for gemini-cli / claude-code / codex, (c) native
+tool schema for `api-agent`, (d) a prompt card. Observations are structured
+(`{text, numbers, images[]}`); images are small labelled PNGs / contact sheets.
+
+Core tools: `build`, `measure`, `render_views`, `render_sheet`, `isolate`,
+`cross_section`, `check_connectivity`, `check_contract`, `compare_silhouette`,
+`joint_sweep`, `shader_probe`, `scene_probe`, `read_cookbook`.
+
+## 6. Judging
+
+`VlmJudge(rubric)`: contact sheet + labelled views + measurement table +
+acceptance checklist → JSON (criterion scores, issues, improvement plan,
+acceptance verdicts). Score is **computed in code** from rubric weights with
+hard floors; n-sample (view-order shuffled) mean/std; deterministic caps from
+gate findings are listed in the verdict. Rubrics: `static_object_v1`,
+`articulated_v1`, `scene_v1`, `asset_v1`, `reference_v1`. `PairwiseJudge`
+(position-swapped) for best-of-N and preference data.
+
+## 7. Round loop (all tracks)
+
+```
+baseline → build/gates/measure/render/judge (the "raw model" delta)
+repeat ≤ max_rounds:
+ plan = judge.improvement_plan ∪ gate.errors ∪ failed acceptance
+ dispatch targeted tasks (per part / zone / asset; parallel when file-disjoint)
+ build → repair loop on build errors (≤ max_repair_attempts, error-focused)
+ gates → measure → render → judge
+ keep best (score, then fewer errors); stop on pass / plateau / budget
+finalise: restore best commit, export, caption, record
+```
+
+## 8. Flywheel
+
+`record.json` per run + git history; `c3v flywheel export` writes sample
+folders (`code.<ext>` / multi-file, `meta.json`, `captions.json`, `renders/`)
+compatible with the owner's STORAGE_RULES, a parquet index, preference pairs
+(round i < round j by judge Δ ≥ τ), repair pairs (error → fix diff), and
+cross-backend best-of pairs.
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
new file mode 100644
index 00000000..e88f7e3e
--- /dev/null
+++ b/harness/docs/INTERFACES.md
@@ -0,0 +1,121 @@
+# Cross-package interfaces (binding for parallel development)
+
+All types live in `codeverse/contracts/` (read them first). Protocols live in
+`models/base.py`, `agents/base.py`, `languages/base.py`, `spatial/registry.py`,
+`judges/base.py`, `tracks/base.py`. Do not change those files; if you need a
+field, add it in your own module or propose it in your final report.
+
+## models/ (package A)
+```python
+from codeverse.models import get_chat_model # (model_id) -> ChatModel
+m = get_chat_model("gemini:gemini-3.7-flash")
+resp = m.generate(ChatRequest(messages=[ChatMessage.user("...", images=[ImagePart(path=...)])],
+ system="...", response_schema=StaticPlan.model_json_schema(),
+ temperature=0.4, thinking="medium", label="planner"))
+resp.parsed # dict when response_schema given
+resp.text # always
+resp.tool_calls # when request.tools given
+resp.usage # Usage with cost_usd
+from codeverse.models.keypool import KeyPool # KeyPool(keys, rpm=..) .acquire() -> key, .report(key, ok|429|5xx)
+from codeverse.models.pricing import estimate_cost # (provider, model, usage) -> usd
+```
+Structured output: Gemini via `response_mime_type="application/json"` + `response_schema`
+(strip unsupported keywords: `$defs` → inline, `anyOf` with null → nullable, `const`,
+`title`, `default` removed). Anthropic: force a `submit` tool with `input_schema` or JSON
+prefill; OpenAI: `response_format={"type":"json_schema", ...}` (Responses or Chat API).
+Retries: 429/5xx/timeouts with jittered backoff, rotating Gemini keys via KeyPool. Provider
+exceptions → `ModelError(retryable=...)`. Gemini `thinking` map: off→budget 0 (where allowed),
+low→1024, medium→4096, high→16384 (`ThinkingConfig(thinking_budget=...)`; for models that
+reject the field, omit it and record a warning).
+
+## agents/ (package B)
+```python
+from codeverse.agents import get_coding_agent # (agent_id) -> CodingAgent
+from codeverse.agents.materialize import materialize_workspace
+# materialize_workspace(ws: Workspace, *, agent_kind: str, contract_md: str, cookbook_rel: str,
+# spatial_tools: bool, mcp_command: list[str]) -> None
+# writes AGENTS.md + GEMINI.md + CLAUDE.md (same body) and MCP configs:
+# gemini-cli → ws/.gemini/settings.json {"mcpServers": {"c3v": {"command": ..., "args": [...]}}}
+# claude-code → ws/.mcp.json {"mcpServers": {"c3v": {...}}}
+# codex → returned via config overrides (-c mcp_servers.c3v.command=... -c mcp_servers.c3v.args=[...])
+# agy → ~/.gemini/antigravity-cli? (investigate; fall back to no MCP + prompt-described CLI `c3v tools ...`)
+res = agent.run(AgentJob(workspace=str(ws.root), prompt=..., model="gemini-3.7-flash", timeout_s=1200,
+ spatial_tools=True, label="baseline"))
+res.files_changed, res.usage, res.transcript_path, res.ok, res.exit_reason
+from codeverse.agents.watchdog import run_with_watchdog # (cmd, cwd, env, soft_timeout_s, idle_grace_s, hard_timeout_s, on_line=...) -> CompletedProc
+```
+MCP command to expose spatial tools: `["python", "-m", "codeverse.spatial.mcp_server", "--workspace", str(ws.root)]`
+(package F implements the server; B just wires the config).
+`api-agent` tool set (ApiAgent): `read_file`, `write_file`, `edit_file` (exact-string replace),
+`list_files`, `run_build` (= spatial tool `build`), plus every `spatial.registry.list_tools()`
+tool; loop until the model stops calling tools or max_turns; writes transcript JSONL.
+
+## languages/ (packages C1, C2, D, E)
+```python
+from codeverse.languages import get_runtime # (Language) -> LanguageRuntime
+rt.lint(ws) -> GateReport # gate="lint:<language>"
+rt.build(ws, timeout_s=None) -> BuildResult # glb_path = ws.artifacts/"object.glb" on success
+rt.skeleton(ws, plan) -> list[Path]
+rt.contract_doc() -> str # from prompts/<lang>/contract.md (package K writes it; provide a
+ # minimal built-in fallback string if the file is missing)
+```
+Build wrappers live in `codeverse/languages/<lang>/wrappers/` and are invoked via
+subprocess; they write `artifacts/build.json` (BuildResult fields) + `artifacts/census.json`.
+Canonical GLB: Y-up, +Z front, meters, named nodes per part (node name = PascalCase part).
+
+Threejs ESM resolution: agent code does `import * as THREE from 'three'`; the harness provides
+`three` via an import map (browser) or `NODE_PATH=runtime_js/node_modules` (node). Never CDN.
+
+## spatial/ (packages C1 render, E joints, F the rest)
+```python
+from codeverse.spatial.render import render_glb, render_scene
+render_glb(glb: Path, out_dir: Path, *, views: Sequence[ViewPreset] | None = None, mode: str = "shaded",
+ width: int = 768, height: int = 768, isolate: list[str] | None = None, explode: float = 0.0,
+ sheet: bool = True, background: str = "studio") -> RenderSet
+render_scene(ws: Workspace, out_dir: Path, *, cameras: list[CameraPlan] | None, orbit: bool = True,
+ times: Sequence[float] = (0.0, 1.5), width: int = 1024, height: int = 576,
+ sheet: bool = True) -> RenderSet # also fills console_errors, fps
+from codeverse.spatial.sheet import contact_sheet # (images: list[tuple[label, path]], out: Path, cols=4, tile=384) -> Path
+from codeverse.spatial.measure import measure_glb # (glb: Path) -> Measurement
+from codeverse.spatial.connectivity import check_connectivity # (glb, gap_m=CONTACT_GAP_M) -> GateReport
+from codeverse.spatial.contract import check_contract # (measurement, plan, tol_m) -> GateReport
+from codeverse.spatial.sections import cross_section # (glb, axis, at, out_png) -> Observation
+from codeverse.spatial.silhouette import compare_silhouette # (render_png, reference_png) -> dict(iou=..., ...)
+from codeverse.spatial.joints import load_urdf, fk, pose_samples, sweep_collisions, urdf_to_glb # package E
+from codeverse.spatial.tools import * # registers @tool: build, measure, render_views, render_sheet, isolate,
+ # cross_section, check_connectivity, check_contract, compare_silhouette,
+ # joint_sweep, shader_probe, scene_probe, read_cookbook
+python -m codeverse.spatial.mcp_server --workspace <ws> # stdio MCP server over the registry
+```
+`build` tool = `get_runtime(ctx.language).lint+build` then `measure_glb`; returns a compact
+Observation (errors first, with file:line + traceback tail; on success the key numbers).
+
+## judges/ (package G)
+```python
+from codeverse.judges.vlm_judge import VlmJudge # VlmJudge(rubric="static_object_v1", model_id=..., n_samples=1)
+j = VlmJudge(...); verdict: Judgment = j.judge(JudgeInput(...))
+from codeverse.judges.pairwise import PairwiseJudge # .compare(spec, renders_a, renders_b) -> PairwiseResult{winner, confidence, reasons}
+from codeverse.judges.reference import ReferenceJudge
+from codeverse.judges.rubrics import load_rubric # (name) -> Rubric{name, criteria[{id, weight, description, floor}], pass_threshold}
+```
+Rubric YAMLs: `static_object_v1`, `articulated_v1`, `scene_v1`, `asset_v1`, `reference_v1`.
+
+## orchestrator/ + tracks/ (package H)
+```python
+from codeverse.tracks import get_track
+rec = get_track(spec.track).run(spec, ws, resume=False) # RunRecord
+from codeverse.orchestrator.runner import StageRunner # .stage(name, fn, inputs_hash) with run_state.json cache
+from codeverse.orchestrator.rounds import RoundPolicy, StopPolicy, BestSelector
+from codeverse.orchestrator.fanout import fan_out # (items, fn, max_workers) -> list[result | Exception]
+from codeverse.orchestrator.budget import BudgetGuard # .charge(usage) raises BudgetExceeded
+from codeverse.tracks.generation import generate_files, SINGLE_SHOT_FORMAT, parse_multifile # API single-shot codegen
+```
+
+## flywheel/ + cli/ (package I)
+```python
+from codeverse.flywheel.record import finalize_record # (ws, RunRecord) -> writes record.json
+from codeverse.flywheel.export import export_samples # (runs_dir, out_dir, min_score) -> ExportReport
+from codeverse.flywheel.pairs import build_pairs # (runs_dir, out_jsonl, min_delta) -> n
+from codeverse.flywheel.captions import caption_sample # (ws, model_id) -> Captions{detailed, instruction, factory}
+c3v make|resume|status|render|judge|tools|mcp|flywheel|bench|doctor
+```
diff --git a/harness/pyproject.toml b/harness/pyproject.toml
new file mode 100644
index 00000000..17aa2d7b
--- /dev/null
+++ b/harness/pyproject.toml
@@ -0,0 +1,58 @@
+[build-system]
+requires = ["setuptools>=69", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+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"
+license = { text = "Apache-2.0" }
+dependencies = [
+ "pydantic>=2.7",
+ "pydantic-settings>=2.3",
+ "typer>=0.12",
+ "rich>=13",
+ "jinja2>=3.1",
+ "pyyaml>=6",
+ "numpy>=1.26",
+ "trimesh>=4.4",
+ "pillow>=10",
+ "google-genai>=1.0",
+ "anthropic>=0.40",
+ "openai>=1.40",
+ "playwright>=1.45",
+]
+
+[project.optional-dependencies]
+cad = ["cadquery>=2.4"]
+urdf = ["yourdfpy>=0.0.56", "scipy>=1.11"]
+dev = ["pytest>=8", "pytest-timeout>=2.3", "ruff>=0.5"]
+
+[project.scripts]
+c3v = "codeverse.cli.main:app"
+3dcodeverse = "codeverse.cli.main:app"
+
+[tool.setuptools.packages.find]
+include = ["codeverse*"]
+
+[tool.setuptools.package-data]
+codeverse = ["prompts/**/*", "judges/rubrics/*.yaml", "languages/**/wrappers/*", "spatial/js/*"]
+
+[tool.ruff]
+line-length = 100
+target-version = "py311"
+
+[tool.ruff.lint]
+select = ["E", "F", "I", "B", "UP", "SIM"]
+ignore = ["E501"]
+
+[tool.pytest.ini_options]
+testpaths = ["tests"]
+timeout = 600
+markers = [
+ "live: needs network + API keys (deselect with -m 'not live')",
+ "blender: needs a Blender binary",
+ "node: needs node + runtime_js deps",
+]
diff --git a/harness/runtime_js/README.md b/harness/runtime_js/README.md
new file mode 100644
index 00000000..99b9aa6b
--- /dev/null
+++ b/harness/runtime_js/README.md
@@ -0,0 +1,45 @@
+# runtime_js — harness-owned node runtime
+
+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.
+
+```
+gpu_launch.cjs launchBrowser({gpu:'auto'|'on'|'off'}) → {browser, gpu, renderer}; rendererInfo(browser)
+ WSL2 hardware WebGL (ANGLE gl-egl + Mesa d3d12 env), UNMASKED_RENDERER probe,
+ negative verdict cached 20 min in ~/.cache/codeverse/gpu_probe.json, SwiftShader fallback
+serve.cjs serveDirs({root, mounts, routes}) loopback static server (MIME table, CORS);
+ runtime_js is always mounted at /__runtime/; importMapHtml() maps 'three' +
+ 'three/addons/' onto it — nothing is ever fetched from the internet
+export_glb.mjs node --import lib/resolve_three.mjs export_glb.mjs --ws <ws> [--entry src/object.js]
+ [--out artifacts/object.glb] [--census artifacts/census.json]
+ imports the agent module, build(THREE) (awaits promises), validates, normalises
+ (stands on y=0, xz-centred; offset recorded), strips textures (warning), writes GLB
+ + census.json; on failure export_error.json + {ok:false,error:{type,message,file,line,frames}}
+render_glb.mjs --glb --out --views '[{name,azimuth,elevation}]' [--mode shaded|wire|normals|silhouette|clay]
+ [--width --height] [--isolate A,B] [--explode 0.3] [--background studio|white|transparent]
+ [--anim-time t] [--gpu auto|on|off] [--shadow 0|1] [--fill 0.85]
+ writes view_<name>.png + views.json; last stdout line = JSON record
+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)
+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 (node + browser)
+lib/stack.mjs Error → {type,message,file,line,frames} with workspace-relative src/ paths
+lib/syntax_check.mjs `node --input-type=module --check` per file to locate ESM SyntaxErrors
+lib/browser/*.js page-side ESM (served through /__runtime/): camera_fit.js (azimuth/elevation →
+ tight bbox fit), studio.js (RoomEnvironment PMREM + key/fill/rim, ACES, sRGB,
+ shadow catcher, render modes), render_rig.js (load GLB, isolate/explode/anim, views)
+```
+
+Conventions (from `codeverse/conventions.py`): Y up, +Z front, meters; azimuth 0 = front,
+counter-clockwise seen from above (90 = camera on +X); elevation above the horizon. Views are
+fitted per camera so the projected bbox fills ~85 % of the frame.
+
+Python entry points: `codeverse.spatial.node.run_node`, `codeverse.spatial.render.render_glb`,
+`codeverse.languages.threejs.ThreeJsRuntime`.
+
+Quick checks:
+```
+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/check_shaders.mjs b/harness/runtime_js/check_shaders.mjs
new file mode 100644
index 00000000..a4342af3
--- /dev/null
+++ b/harness/runtime_js/check_shaders.mjs
@@ -0,0 +1,106 @@
+#!/usr/bin/env node
+/**
+ * Shader compile preflight for a scene_threejs workspace.
+ *
+ * node check_shaders.mjs --ws <ws> [--module src/shaders/x.js] [--gpu auto] [--out report.json]
+ *
+ * 1. Static audits over src/**\/*.js GLSL strings (no browser): #include not
+ * alone on a line, #version directives, gl_FragColor + custom `out`,
+ * GLSL3 + gl_FragColor, uTime read but undeclared/unbound, patches that
+ * drop the chunk they replace, fog-less ShaderMaterials in fogged scenes.
+ * 2. Compile preflight: boot the scene, force-compile every material
+ * (renderer.compile + one frame), collect GPU info logs and map the
+ * offending source line back to file:line.
+ * Output (last stdout line): {ok, errors:[{file,line,message,...}], warnings:[...]}.
+ * Exit 0 clean, 1 errors, 2 could not run.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { armWatchdog, fail, finish, parseCli, writeJson } from './lib/cli.mjs';
+import { auditFile, fixHintFor, hasGlsl, locateSourceLine } from './lib/glsl_audit.mjs';
+import { errorSummary, openHost } from './lib/host_page.mjs';
+
+const args = parseCli({
+ ws: {}, module: {}, out: {}, gpu: { default: process.env.C3V_RENDER_GPU || 'auto' },
+ 'timeout-ms': { default: '90000' }, 'no-compile': { type: 'boolean', default: false },
+});
+
+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;
+}
+
+async function main() {
+ if (!args.ws) throw new Error('--ws is required');
+ const ws = path.resolve(args.ws);
+ const watchdog = armWatchdog(parseInt(args['timeout-ms'], 10));
+ const t0 = Date.now();
+ let files = listSources(ws);
+ const sceneUsesFog = files.some((f) => /new\s+THREE\.(Fog|FogExp2)\b|\.fog\s*=/.test(f.text));
+ const auditTargets = args.module ? files.filter((f) => f.file === args.module.replace(/^\.?\//, '')) : files;
+ if (args.module && !auditTargets.length) throw new Error(`--module ${args.module} not found under ${ws}`);
+ const errors = [], warnings = [];
+ for (const f of auditTargets) {
+ for (const fd of auditFile(f.file, f.text, { sceneUsesFog })) {
+ (fd.severity === 'error' ? errors : warnings).push({ file: fd.file, line: fd.line, kind: fd.kind, message: fd.message, fix_hint: fd.severity === 'error' ? fd.message : '' });
+ }
+ }
+ const report = { ok: false, ws, module: args.module || null, static: { files: auditTargets.length, glsl_files: auditTargets.filter((f) => hasGlsl(f.text)).length }, compile: null, errors, warnings };
+
+ if (!args['no-compile']) {
+ let host = null;
+ try {
+ host = await openHost(ws, { width: 256, height: 144, gpu: args.gpu });
+ const { page, boot } = host;
+ if (!boot.ok) {
+ errors.push({ file: 'src/scene.js', line: null, kind: 'boot', message: `scene did not boot at stage '${boot.stage}': ${boot.error}`.slice(0, 1200), fix_hint: 'fix the import/runtime error first; then re-run check_shaders' });
+ } else {
+ const comp = await page.evaluate((spec) => window.__c3v.compileAll(spec || undefined), null);
+ const shaderErrors = comp.shader_errors.map(({ _key, ...e }) => e);
+ for (const e of shaderErrors) {
+ const loc = locateSourceLine(files, e.source_line);
+ errors.push({
+ file: loc.file || (e.material ? `(material ${e.material})` : '(assembled shader)'),
+ line: loc.line, kind: 'compile', stage: e.stage, material: e.material || '', material_type: e.material_type || '',
+ message: `${e.stage} shader: ${e.message}` + (e.source_line ? ` — at: ${e.source_line}` : '') + (loc.candidates > 1 ? ` (${loc.candidates} identical lines; first shown)` : ''),
+ assembled_line: e.assembled_line, source_line: e.source_line, context: e.context, fix_hint: fixHintFor(e.message),
+ });
+ }
+ for (const a of comp.material_audit) {
+ (a.severity === 'error' ? errors : warnings).push({ file: '(runtime material)', line: null, kind: a.kind, material: a.material, message: a.message, fix_hint: a.severity === 'error' ? a.message : '' });
+ }
+ report.compile = { ms: comp.compile_ms, programs: comp.programs, custom_materials: comp.custom_materials, renderer: boot.renderer, gpu: host.gpu };
+ }
+ const es = errorSummary(host.errors, boot);
+ for (const c of es.shader_console) {
+ if (!errors.some((e) => e.kind === 'compile')) errors.push({ file: '(console)', line: null, kind: 'shader_console', message: c, fix_hint: 'search your GLSL for the quoted ERROR line' });
+ }
+ for (const c of es.console_errors) if (!boot.error || !c.startsWith('boot[')) warnings.push({ file: '(console)', line: null, kind: 'console', message: c });
+ await host.close();
+ } catch (e) {
+ if (host) await host.close().catch(() => {});
+ return fail(`compile preflight failed: ${e.message}`, { errors, warnings });
+ }
+ }
+ report.ok = errors.length === 0;
+ report.duration_ms = Date.now() - t0;
+ clearTimeout(watchdog);
+ if (args.out) writeJson(path.resolve(args.out), report);
+ // human summary first, JSON last
+ for (const e of errors) process.stdout.write(`ERROR ${e.file}${e.line ? ':' + e.line : ''}: ${e.message}\n`);
+ for (const w of warnings) process.stdout.write(`WARN ${w.file}${w.line ? ':' + w.line : ''}: ${w.message}\n`);
+ process.stdout.write(report.ok ? 'OK every program compiled\n' : `${errors.length} shader error(s)\n`);
+ return finish(report, report.ok ? 0 : 1);
+}
+
+main().catch((e) => fail(e.stack || String(e)));
diff --git a/harness/runtime_js/export_glb.mjs b/harness/runtime_js/export_glb.mjs
new file mode 100644
index 00000000..450bd0cd
--- /dev/null
+++ b/harness/runtime_js/export_glb.mjs
@@ -0,0 +1,205 @@
+#!/usr/bin/env node
+// Export an agent-authored three.js object module to a canonical GLB + census.
+//
+// node --import runtime_js/lib/resolve_three.mjs runtime_js/export_glb.mjs \
+// --ws <workspace> [--entry src/object.js] [--out artifacts/object.glb] [--census artifacts/census.json]
+//
+// Runs in plain node (no browser). The agent module must `export function build(THREE)`
+// returning a THREE.Group (or a Promise of one). Last stdout line is a JSON record:
+// ok:true -> {ok, glb, census, duration_ms}
+// ok:false -> {ok:false, error:{type,message,file,line,frames,stack}, warnings}
+// and the same error record is written next to the census as export_error.json.
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { parseArgs } from 'node:util';
+import { pathToFileURL } from 'node:url';
+
+import { installExporterPolyfills } from './lib/node_polyfills.mjs';
+import { objectCensus, hasNonFinitePositions } from './lib/census.mjs';
+import { errorRecord } from './lib/stack.mjs';
+import { findSyntaxError } from './lib/syntax_check.mjs';
+
+const TEXTURE_SLOTS = ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap',
+ 'bumpMap', 'displacementMap', 'alphaMap', 'envMap', 'lightMap', 'specularMap', 'clearcoatMap',
+ 'clearcoatNormalMap', 'clearcoatRoughnessMap', 'sheenColorMap', 'transmissionMap', 'thicknessMap'];
+const NORMALISE_THRESHOLD_M = 0.01;
+
+function cli() {
+ const { values } = parseArgs({
+ options: {
+ ws: { type: 'string' },
+ entry: { type: 'string', default: 'src/object.js' },
+ out: { type: 'string', default: 'artifacts/object.glb' },
+ census: { type: 'string', default: 'artifacts/census.json' },
+ normalise: { type: 'string', default: '1' },
+ },
+ });
+ if (!values.ws) throw new Error('--ws <workspace dir> is required');
+ const ws = path.resolve(values.ws);
+ const abs = (p) => (path.isAbsolute(p) ? p : path.join(ws, p));
+ return {
+ ws,
+ entry: abs(values.entry),
+ out: abs(values.out),
+ census: abs(values.census),
+ normalise: values.normalise !== '0',
+ };
+}
+
+function emit(obj) {
+ process.stdout.write(JSON.stringify(obj) + '\n');
+}
+
+/** Capture console.warn/error from three (e.g. unsupported materials) as warnings. */
+function captureWarnings(sink) {
+ const origWarn = console.warn;
+ const origError = console.error;
+ console.warn = (...a) => {
+ sink.push(a.map(String).join(' '));
+ origWarn.apply(console, a);
+ };
+ console.error = (...a) => {
+ sink.push(a.map(String).join(' '));
+ origError.apply(console, a);
+ };
+}
+
+async function loadBuild(entry) {
+ if (!fs.existsSync(entry)) {
+ const e = new Error(`entry module not found: ${entry}`);
+ e.name = 'MissingEntry';
+ throw e;
+ }
+ const mod = await import(pathToFileURL(entry).href);
+ if (typeof mod.build !== 'function') {
+ const e = new Error(`${path.basename(entry)} must 'export function build(THREE)' (got ${typeof mod.build})`);
+ e.name = 'ContractError';
+ throw e;
+ }
+ return mod.build;
+}
+
+function validateGroup(THREE, group, entry) {
+ const fail = (msg) => {
+ const e = new Error(msg);
+ e.name = 'ContractError';
+ throw e;
+ };
+ if (!group || !group.isObject3D) fail(`build(THREE) must return a THREE.Group (got ${group && group.constructor ? group.constructor.name : typeof group})`);
+ let meshes = 0;
+ group.traverse((o) => {
+ if (o.isMesh || o.isInstancedMesh || o.isSkinnedMesh) meshes += 1;
+ });
+ if (meshes === 0) fail('build(THREE) returned a group with no meshes');
+ if (hasNonFinitePositions(group)) fail('geometry contains NaN/Infinity vertex positions (check divisions by zero, radius 0, empty shapes)');
+ const box = new THREE.Box3().setFromObject(group, true);
+ if (box.isEmpty() || !Number.isFinite(box.min.x) || !Number.isFinite(box.max.x)) fail('object has an empty or non-finite bounding box');
+ if (!group.name) group.name = path.basename(path.dirname(entry)) === 'src' ? 'Object' : path.basename(entry, '.js');
+}
+
+/** Shift the group so it stands on y=0 centred on the Y axis; returns the applied offset or null. */
+function normalise(THREE, group, enabled) {
+ const box = new THREE.Box3().setFromObject(group, true);
+ const c = box.getCenter(new THREE.Vector3());
+ const offset = new THREE.Vector3(-c.x, -box.min.y, -c.z);
+ if (!enabled || offset.length() <= NORMALISE_THRESHOLD_M) return null;
+ group.position.add(offset);
+ group.updateWorldMatrix(true, true);
+ return offset.toArray().map((v) => +v.toFixed(5));
+}
+
+function stripTextures(group, warnings) {
+ let stripped = 0;
+ group.traverse((o) => {
+ const mats = Array.isArray(o.material) ? o.material : o.material ? [o.material] : [];
+ for (const m of mats) {
+ for (const slot of TEXTURE_SLOTS) {
+ if (m[slot]) {
+ m[slot] = null;
+ stripped += 1;
+ }
+ }
+ }
+ });
+ if (stripped) warnings.push(`stripped ${stripped} texture slot(s): textures are not exportable from node (use vertex colours / materials)`);
+}
+
+let ARGS = null;
+
+async function main() {
+ const t0 = Date.now();
+ const args = cli();
+ ARGS = args;
+ const warnings = [];
+ captureWarnings(warnings);
+ installExporterPolyfills();
+
+ const THREE = await import('three');
+ const { GLTFExporter } = await import('three/addons/exporters/GLTFExporter.js');
+
+ const build = await loadBuild(args.entry);
+ let group = build(THREE);
+ if (group && typeof group.then === 'function') group = await group;
+ validateGroup(THREE, group, args.entry);
+
+ const tickPresent = typeof (group.userData && group.userData.tick) === 'function';
+ if (tickPresent) delete group.userData.tick; // functions cannot be serialised into glTF extras
+
+ const normalisedOffset = normalise(THREE, group, args.normalise);
+ if (normalisedOffset) warnings.push(`object was off ground/centre by ${JSON.stringify(normalisedOffset)} m; translated so min.y=0 and xz-centre=0 (fix the source: the object must stand on y=0 centred on the Y axis)`);
+ stripTextures(group, warnings);
+
+ const census = objectCensus(THREE, group);
+ census.normalised_offset = normalisedOffset;
+ census.tick_present = tickPresent;
+ let unnamed = 0;
+ group.traverse((o) => {
+ if ((o.isMesh || o.isInstancedMesh) && !o.name) unnamed += 1;
+ });
+ census.unnamed_meshes = unnamed;
+ if (unnamed) warnings.push(`${unnamed} mesh(es) have no .name; name every mesh (e.g. 'SeatCushion') so the census and judge can refer to them`);
+
+ const exporter = new GLTFExporter();
+ const glb = await exporter.parseAsync(group, { binary: true, onlyVisible: true, trs: false });
+ if (!(glb instanceof ArrayBuffer) || glb.byteLength < 20) {
+ const e = new Error('GLTFExporter produced no binary output');
+ e.name = 'ExportError';
+ throw e;
+ }
+ fs.mkdirSync(path.dirname(args.out), { recursive: true });
+ fs.writeFileSync(args.out, Buffer.from(glb));
+
+ census.warnings = warnings;
+ census.glb_bytes = glb.byteLength;
+ census.three_revision = THREE.REVISION;
+ fs.mkdirSync(path.dirname(args.census), { recursive: true });
+ fs.writeFileSync(args.census, JSON.stringify(census, null, 2));
+
+ emit({ ok: true, glb: args.out, census: args.census, duration_ms: Date.now() - t0,
+ tri_count: census.tri_count, parts: census.parts.length, warnings });
+}
+
+main().catch((err) => {
+ const ws = ARGS ? ARGS.ws : '';
+ const record = { ok: false, error: errorRecord(err, ws) };
+ // ESM SyntaxErrors from import() carry no location: find the offending file ourselves.
+ if (record.error.type === 'SyntaxError' && !record.error.file && ARGS) {
+ const hit = findSyntaxError(path.dirname(ARGS.entry));
+ if (hit) {
+ record.error.file = path.relative(ws, hit.file);
+ record.error.line = hit.line;
+ record.error.message = `${hit.message} (in ${record.error.file}:${hit.line})`;
+ }
+ }
+ try {
+ if (ARGS) {
+ fs.mkdirSync(path.dirname(ARGS.census), { recursive: true });
+ fs.writeFileSync(path.join(path.dirname(ARGS.census), 'export_error.json'), JSON.stringify(record, null, 2));
+ }
+ } catch (_e) {
+ /* reporting must never mask the original failure */
+ }
+ emit(record);
+ process.exit(1);
+});
diff --git a/harness/runtime_js/gpu_launch.cjs b/harness/runtime_js/gpu_launch.cjs
new file mode 100644
index 00000000..87ae60ba
--- /dev/null
+++ b/harness/runtime_js/gpu_launch.cjs
@@ -0,0 +1,147 @@
+// Headless-Chrome launcher for the WebGL renderers (render_glb / render_scene / probes).
+//
+// On this WSL2 box hardware WebGL needs BOTH the ANGLE gl-egl flags AND the
+// Mesa d3d12 env trio; either alone silently lands on llvmpipe. So every GPU
+// attempt is verified through UNMASKED_RENDERER_WEBGL before it is trusted,
+// and a negative verdict is cached (with a TTL) so the slow-to-fail GPU launch
+// is not repeated on every render.
+//
+// const { launchBrowser, rendererInfo } = require('./gpu_launch.cjs');
+// const { browser, gpu, renderer } = await launchBrowser({ gpu: 'auto' });
+//
+// gpu: 'auto' (probe, cached) | 'on' (require hardware; throw otherwise) | 'off' (CPU).
+'use strict';
+
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+
+const CACHE_DIR = process.env.C3V_CACHE_DIR || path.join(os.homedir(), '.cache', 'codeverse');
+const CACHE_PATH = path.join(CACHE_DIR, 'gpu_probe.json');
+const NEGATIVE_TTL_MS = 20 * 60 * 1000; // how long a "no GPU" verdict is trusted
+const PROTOCOL_TIMEOUT_MS = 15 * 60 * 1000; // big frame batches exceed puppeteer's 180 s default
+
+const BASE_ARGS = ['--no-sandbox', '--disable-setuid-sandbox', '--enable-webgl', '--ignore-gpu-blocklist'];
+const GPU_ARGS = [...BASE_ARGS, '--enable-gpu-rasterization', '--use-angle=gl-egl'];
+const CPU_ARGS = [...BASE_ARGS, '--enable-unsafe-swiftshader', '--use-angle=swiftshader'];
+const GPU_ENV = {
+ GALLIUM_DRIVER: 'd3d12',
+ MESA_LOADER_DRIVER_OVERRIDE: 'd3d12',
+ MESA_D3D12_DEFAULT_ADAPTER_NAME: 'NVIDIA',
+};
+const SOFTWARE_RE = /swiftshader|llvmpipe|softpipe|software|basic render/i;
+
+function readCache() {
+ try {
+ return JSON.parse(fs.readFileSync(CACHE_PATH, 'utf8'));
+ } catch (_e) {
+ return null;
+ }
+}
+
+function writeCache(decision) {
+ try {
+ fs.mkdirSync(CACHE_DIR, { recursive: true });
+ fs.writeFileSync(CACHE_PATH, JSON.stringify({ ...decision, at: Date.now() }, null, 2));
+ } catch (_e) {
+ /* cache is an optimisation only */
+ }
+}
+
+/**
+ * Probe the browser's WebGL backend. Returns the UNMASKED_RENDERER string or null
+ * when no WebGL context can be created.
+ */
+async function rendererInfo(browser) {
+ const page = await browser.newPage();
+ try {
+ return await page.evaluate(() => {
+ const canvas = document.createElement('canvas');
+ const gl = canvas.getContext('webgl2') || canvas.getContext('webgl');
+ if (!gl) return null;
+ const ext = gl.getExtension('WEBGL_debug_renderer_info');
+ const r = ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER);
+ return String(r);
+ });
+ } finally {
+ await page.close().catch(() => {});
+ }
+}
+
+function loadPuppeteer(puppeteer) {
+ return puppeteer || require('puppeteer');
+}
+
+async function launchCpu(puppeteer) {
+ const env = { ...process.env };
+ for (const k of Object.keys(GPU_ENV)) delete env[k];
+ const browser = await puppeteer.launch({
+ headless: true,
+ args: CPU_ARGS,
+ env,
+ protocolTimeout: PROTOCOL_TIMEOUT_MS,
+ });
+ let renderer = 'SwiftShader (CPU)';
+ try {
+ renderer = (await rendererInfo(browser)) || renderer;
+ } catch (_e) {
+ /* keep the default label */
+ }
+ return { browser, gpu: false, renderer };
+}
+
+async function tryGpu(puppeteer) {
+ let browser = null;
+ try {
+ browser = await puppeteer.launch({
+ headless: true,
+ args: GPU_ARGS,
+ env: { ...process.env, ...GPU_ENV },
+ protocolTimeout: PROTOCOL_TIMEOUT_MS,
+ });
+ const renderer = await rendererInfo(browser);
+ if (!renderer || SOFTWARE_RE.test(renderer)) {
+ await browser.close().catch(() => {});
+ return { browser: null, renderer: renderer || 'no WebGL context' };
+ }
+ return { browser, renderer };
+ } catch (e) {
+ if (browser) await browser.close().catch(() => {});
+ return { browser: null, renderer: `launch failed: ${e.message}` };
+ }
+}
+
+/**
+ * Launch headless Chrome on the best available WebGL backend.
+ * @param {{gpu?: 'auto'|'on'|'off', puppeteer?: object}} opts
+ * @returns {Promise<{browser: object, gpu: boolean, renderer: string}>}
+ */
+async function launchBrowser(opts = {}) {
+ const mode = String(opts.gpu || process.env.C3V_RENDER_GPU || 'auto').toLowerCase();
+ const puppeteer = loadPuppeteer(opts.puppeteer);
+ if (!['auto', 'on', 'off'].includes(mode)) throw new Error(`gpu must be auto|on|off, got ${mode}`);
+
+ if (mode === 'off') return launchCpu(puppeteer);
+
+ if (mode === 'on') {
+ const attempt = await tryGpu(puppeteer);
+ if (!attempt.browser) throw new Error(`gpu=on but no hardware WebGL: ${attempt.renderer}`);
+ return { browser: attempt.browser, gpu: true, renderer: attempt.renderer };
+ }
+
+ // auto: a fresh negative verdict skips the slow GPU attempt; a positive one is
+ // always re-verified live (cheap, and the GPU can go away).
+ const cached = readCache();
+ const fresh = cached && typeof cached.at === 'number' && Date.now() - cached.at < NEGATIVE_TTL_MS;
+ if (cached && cached.use_gpu === false && fresh) return launchCpu(puppeteer);
+
+ const attempt = await tryGpu(puppeteer);
+ if (attempt.browser) {
+ writeCache({ use_gpu: true, renderer: attempt.renderer });
+ return { browser: attempt.browser, gpu: true, renderer: attempt.renderer };
+ }
+ writeCache({ use_gpu: false, renderer: attempt.renderer });
+ return launchCpu(puppeteer);
+}
+
+module.exports = { launchBrowser, rendererInfo, GPU_ARGS, CPU_ARGS, GPU_ENV, CACHE_PATH };
diff --git a/harness/runtime_js/lib/_compat.mjs b/harness/runtime_js/lib/_compat.mjs
new file mode 100644
index 00000000..6cf5108e
--- /dev/null
+++ b/harness/runtime_js/lib/_compat.mjs
@@ -0,0 +1,186 @@
+/**
+ * Thin node-side fallbacks for what package C1 provides
+ * (`runtime_js/gpu_launch.cjs` → launchBrowser, `runtime_js/serve.cjs` →
+ * static server with import-map injection). Each helper first tries the C1
+ * module and uses it when it exposes the expected function; otherwise a local
+ * implementation with the same behaviour is used so this package runs alone.
+ */
+
+import fs from 'node:fs';
+import http from 'node:http';
+import path from 'node:path';
+import { createRequire } from 'node:module';
+import { fileURLToPath } from 'node:url';
+
+const require_ = createRequire(import.meta.url);
+export const RUNTIME_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+const BASE_ARGS = ['--no-sandbox', '--disable-setuid-sandbox', '--enable-webgl', '--ignore-gpu-blocklist'];
+const GPU_ARGS = [...BASE_ARGS, '--enable-gpu-rasterization', '--use-angle=gl-egl'];
+const CPU_ARGS = [...BASE_ARGS, '--enable-unsafe-swiftshader', '--use-angle=swiftshader'];
+const GPU_ENV = {
+ GALLIUM_DRIVER: 'd3d12',
+ MESA_LOADER_DRIVER_OVERRIDE: 'd3d12',
+ MESA_D3D12_DEFAULT_ADAPTER_NAME: 'NVIDIA',
+};
+const SOFTWARE_RE = /swiftshader|llvmpipe|softpipe|software|basic render/i;
+
+function tryRequire(rel) {
+ try {
+ return require_(path.join(RUNTIME_ROOT, rel));
+ } catch (e) {
+ if (e && e.code === 'MODULE_NOT_FOUND' && String(e.message).includes(rel.replace('./', ''))) return null;
+ throw e;
+ }
+}
+
+async function probeRenderer(browser) {
+ const page = await browser.newPage();
+ try {
+ return await page.evaluate(() => {
+ const c = document.createElement('canvas');
+ const gl = c.getContext('webgl2') || c.getContext('webgl');
+ if (!gl) return null;
+ const ext = gl.getExtension('WEBGL_debug_renderer_info');
+ return String(ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER));
+ });
+ } finally {
+ await page.close();
+ }
+}
+
+async function launchWith(puppeteer, args, env) {
+ const saved = {};
+ for (const k of Object.keys(GPU_ENV)) {
+ saved[k] = process.env[k];
+ if (env[k] !== undefined) process.env[k] = env[k];
+ else delete process.env[k];
+ }
+ try {
+ return await puppeteer.launch({ headless: true, args, protocolTimeout: 600000 });
+ } finally {
+ for (const k of Object.keys(saved)) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ }
+}
+
+/**
+ * Local launcher: GPU attempt (WSL2 d3d12 + gl-egl) verified via the
+ * unmasked renderer string, else SwiftShader CPU.
+ * @param {{gpu?: 'auto'|'on'|'off'}} opts
+ * @returns {Promise<{browser: object, gpu: boolean, renderer: string}>}
+ */
+async function localLaunchBrowser({ gpu = 'auto' } = {}) {
+ const puppeteer = require_('puppeteer');
+ if (gpu !== 'off') {
+ let browser = null;
+ try {
+ browser = await launchWith(puppeteer, GPU_ARGS, GPU_ENV);
+ const renderer = await probeRenderer(browser);
+ if (renderer && !SOFTWARE_RE.test(renderer)) return { browser, gpu: true, renderer };
+ await browser.close().catch(() => {});
+ if (gpu === 'on') throw new Error(`gpu=on but WebGL renderer is software/none: ${renderer}`);
+ } catch (e) {
+ if (browser) await browser.close().catch(() => {});
+ if (gpu === 'on') throw e;
+ }
+ }
+ const browser = await launchWith(puppeteer, CPU_ARGS, {});
+ const renderer = (await probeRenderer(browser)) || 'SwiftShader (CPU)';
+ return { browser, gpu: false, renderer };
+}
+
+/** Launch a headless browser; C1's gpu_launch.cjs when present. */
+export async function launchBrowser(opts = {}) {
+ const mod = tryRequire('./gpu_launch.cjs');
+ if (mod && typeof mod.launchBrowser === 'function') {
+ const res = await mod.launchBrowser(opts);
+ if (res && res.browser) return { browser: res.browser, gpu: !!res.gpu, renderer: String(res.renderer || '') };
+ }
+ return localLaunchBrowser(opts);
+}
+
+const MIME = {
+ '.js': 'text/javascript', '.mjs': 'text/javascript', '.cjs': 'text/javascript', '.json': 'application/json',
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.hdr': 'application/octet-stream',
+ '.glb': 'model/gltf-binary', '.gltf': 'model/gltf+json', '.html': 'text/html', '.css': 'text/css', '.wasm': 'application/wasm',
+ '.ktx2': 'image/ktx2', '.svg': 'image/svg+xml', '.mp3': 'audio/mpeg', '.ogg': 'audio/ogg', '.txt': 'text/plain',
+};
+
+const LOCAL_MOUNT = '/__rt/';
+
+/** URL prefix under which runtime_js is served ('/__runtime/' with C1's serve.cjs). */
+export function runtimeMount() {
+ const mod = tryRequire('./serve.cjs');
+ return mod && typeof mod.RUNTIME_MOUNT === 'string' ? mod.RUNTIME_MOUNT : LOCAL_MOUNT;
+}
+
+/** Import map that resolves 'three' and 'three/addons/*' to the local runtime copy. */
+export function importMapHtml() {
+ const mod = tryRequire('./serve.cjs');
+ if (mod && typeof mod.importMapHtml === 'function') return mod.importMapHtml();
+ const m = LOCAL_MOUNT;
+ const map = {
+ imports: {
+ three: `${m}node_modules/three/build/three.module.js`,
+ 'three/addons/': `${m}node_modules/three/examples/jsm/`,
+ 'three/examples/jsm/': `${m}node_modules/three/examples/jsm/`,
+ },
+ };
+ return `<script type="importmap">${JSON.stringify(map)}</script>`;
+}
+
+function safeJoin(root, rel) {
+ const abs = path.resolve(root, '.' + rel);
+ if (abs !== root && !abs.startsWith(root + path.sep)) return null;
+ return abs;
+}
+
+/**
+ * Serve a workspace on 127.0.0.1:0 with these mounts:
+ * /src/** /public/** → <ws>/src, <ws>/public
+ * /assets/** → <ws>/public/assets (contract: '/assets/x.glb')
+ * <runtimeMount()>/** → runtime_js (node_modules/three, lib/*.mjs)
+ * /__host.html → generated host page (import map + scene_host.mjs)
+ * Uses C1's serve.cjs when present (same mounts); returns { server, base, close() }.
+ */
+export async function serveWorkspace(wsRoot, { runtimeRoot = RUNTIME_ROOT, hostHtml = '' } = {}) {
+ wsRoot = path.resolve(wsRoot);
+ runtimeRoot = path.resolve(runtimeRoot);
+ const c1 = tryRequire('./serve.cjs');
+ if (c1 && typeof c1.serveDirs === 'function') {
+ const srv = await c1.serveDirs({
+ root: wsRoot,
+ mounts: { '/assets/': path.join(wsRoot, 'public', 'assets') },
+ routes: { '/__host.html': { body: hostHtml, type: 'text/html; charset=utf-8' } },
+ });
+ return { server: srv.server, base: srv.base, close: srv.close };
+ }
+ const server = http.createServer((req, res) => {
+ const rel = decodeURIComponent((req.url || '/').split('?')[0]);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Cache-Control', 'no-store');
+ if (rel === '/favicon.ico') { res.statusCode = 204; res.end(); return; }
+ if (rel === '/__host.html') {
+ res.setHeader('Content-Type', 'text/html');
+ res.end(hostHtml);
+ return;
+ }
+ let abs = null;
+ if (rel.startsWith(LOCAL_MOUNT)) abs = safeJoin(runtimeRoot, rel.slice(LOCAL_MOUNT.length - 1));
+ else if (rel.startsWith('/assets/')) abs = safeJoin(path.join(wsRoot, 'public'), rel);
+ else abs = safeJoin(wsRoot, rel);
+ if (!abs || !fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
+ res.statusCode = 404;
+ res.end('not found: ' + rel);
+ return;
+ }
+ res.setHeader('Content-Type', MIME[path.extname(abs).toLowerCase()] || 'application/octet-stream');
+ fs.createReadStream(abs).pipe(res);
+ });
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const base = `http://127.0.0.1:${server.address().port}`;
+ return { server, base, close: () => new Promise((r) => server.close(() => r())) };
+}
diff --git a/harness/runtime_js/lib/browser/camera_fit.js b/harness/runtime_js/lib/browser/camera_fit.js
new file mode 100644
index 00000000..11720c89
--- /dev/null
+++ b/harness/runtime_js/lib/browser/camera_fit.js
@@ -0,0 +1,74 @@
+// Camera fitting shared by the object and scene renderers (browser ESM; imports 'three'
+// through the page's import map).
+//
+// import { viewDirection, fitCameraToBox } from '/__runtime/lib/browser/camera_fit.js';
+//
+// Convention (codeverse.conventions): azimuth 0 = front (+Z), counter-clockwise seen
+// from above (90 = camera on +X = the object's right side); elevation above the horizon.
+
+import * as THREE from 'three';
+
+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));
+}
+
+/** The 8 corners of a Box3. */
+export function boxCorners(box) {
+ const out = [];
+ for (const x of [box.min.x, box.max.x])
+ for (const y of [box.min.y, box.max.y])
+ for (const z of [box.min.z, box.max.z]) out.push(new THREE.Vector3(x, y, z));
+ return out;
+}
+
+/**
+ * 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.
+ * Returns {position, lookAt, distance}.
+ */
+export function fitCameraToBox(camera, box, azimuthDeg, elevationDeg, { fill = 0.85, iterations = 8, 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 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 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;
+ }
+ 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);
+ return { position: camera.position.toArray(), lookAt: center.toArray(), distance: d };
+}
diff --git a/harness/runtime_js/lib/browser/render_rig.js b/harness/runtime_js/lib/browser/render_rig.js
new file mode 100644
index 00000000..66cfcd7a
--- /dev/null
+++ b/harness/runtime_js/lib/browser/render_rig.js
@@ -0,0 +1,131 @@
+// Browser-side object render rig: load a GLB, apply mode/isolate/explode, fit the
+// camera per view, return PNGs as base64. Driven by render_glb.mjs via puppeteer.
+//
+// import { renderGlbViews } from '/__runtime/lib/browser/render_rig.js';
+// const result = await renderGlbViews({ glbUrl, views, mode, width, height, isolate, explode, background, animTime, shadow, fill });
+
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { fitCameraToBox } from './camera_fit.js';
+import { makeRenderer, buildStudio, applyMode, rendererString } from './studio.js';
+
+const FOV_DEG = 35;
+
+function loadGlb(url) {
+ return new Promise((resolve, reject) => {
+ new GLTFLoader().load(url, resolve, undefined, (e) => reject(new Error(`GLTFLoader failed for ${url}: ${e && e.message ? e.message : e}`)));
+ });
+}
+
+/** The object root: the single child of the glTF scene if there is one, else the scene itself. */
+function objectRoot(scene) {
+ const kids = scene.children.filter((c) => !c.isLight && !c.isCamera);
+ return kids.length === 1 && kids[0].children.length > 0 ? kids[0] : scene;
+}
+
+function norm(name) {
+ return String(name || '').toLowerCase().replace(/[^a-z0-9]/g, '');
+}
+
+/** Hide every mesh that is not (under) a node whose name is in `names`. Returns missing names. */
+function isolate(root, names) {
+ const wanted = new Map(names.map((n) => [norm(n), n]));
+ const found = new Set();
+ const keep = new Set();
+ root.traverse((o) => {
+ if (o.name && wanted.has(norm(o.name))) {
+ found.add(norm(o.name));
+ o.traverse((d) => keep.add(d));
+ }
+ });
+ root.traverse((o) => {
+ if ((o.isMesh || o.isInstancedMesh || o.isSkinnedMesh) && !keep.has(o)) o.visible = false;
+ });
+ return [...wanted.entries()].filter(([k]) => !found.has(k)).map(([, n]) => n);
+}
+
+/** Push each part (direct child of the object root) radially from the object centre. */
+function explode(root, factor) {
+ root.updateWorldMatrix(true, true);
+ const whole = new THREE.Box3().setFromObject(root, true);
+ const center = whole.getCenter(new THREE.Vector3());
+ // linear part of root's inverse world matrix: world-space delta -> root-local delta
+ const toLocal = new THREE.Matrix3().setFromMatrix4(root.matrixWorld.clone().invert());
+ for (const part of root.children) {
+ const box = new THREE.Box3().setFromObject(part, true);
+ if (box.isEmpty()) continue;
+ const delta = box.getCenter(new THREE.Vector3()).sub(center).multiplyScalar(factor);
+ part.position.add(delta.applyMatrix3(toLocal));
+ }
+ root.updateWorldMatrix(true, true);
+}
+
+function visibleBox(root) {
+ root.updateWorldMatrix(true, true);
+ const box = new THREE.Box3();
+ root.traverseVisible((o) => {
+ if ((o.isMesh || o.isInstancedMesh || o.isSkinnedMesh) && o.name !== '__wire') {
+ box.expandByObject(o, true);
+ }
+ });
+ return box;
+}
+
+/**
+ * Render all views. Resolves to
+ * {ok, renderer, views:[{name, b64, camera_position, look_at, fov, width, height}], warnings, timing}
+ */
+export async function renderGlbViews(cfg) {
+ const t0 = performance.now();
+ const warnings = [];
+ const width = cfg.width || 768;
+ const height = cfg.height || 768;
+ const mode = cfg.mode || 'shaded';
+ const background = mode === 'silhouette' ? 'white' : cfg.background || 'studio';
+
+ const canvas = document.getElementById('c') || document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ const renderer = makeRenderer(canvas, width, height, { transparent: background === 'transparent' });
+ if (mode === 'silhouette' || mode === 'normals') renderer.toneMapping = THREE.NoToneMapping;
+
+ const gltf = await loadGlb(cfg.glbUrl);
+ const tLoad = performance.now();
+ const scene = new THREE.Scene();
+ scene.add(gltf.scene);
+ const root = objectRoot(gltf.scene);
+
+ if (cfg.animTime != null && gltf.animations && gltf.animations.length) {
+ const mixer = new THREE.AnimationMixer(gltf.scene);
+ for (const clip of gltf.animations) mixer.clipAction(clip).play();
+ mixer.update(Number(cfg.animTime));
+ }
+ if (cfg.isolate && cfg.isolate.length) {
+ const missing = isolate(root, cfg.isolate);
+ if (missing.length) warnings.push(`isolate: no node named ${missing.join(', ')}`);
+ }
+ if (cfg.explode) explode(root, Number(cfg.explode));
+
+ const look = applyMode(root, mode);
+ const box = visibleBox(root);
+ if (box.isEmpty()) throw new Error('nothing visible to render (empty GLB or isolate hid everything)');
+ buildStudio(renderer, scene, box, { background, shadow: look.shadow && cfg.shadow !== false, lights: look.lights });
+
+ const camera = new THREE.PerspectiveCamera(FOV_DEG, width / height, 0.01, 100);
+ const views = [];
+ for (const v of cfg.views) {
+ const fit = fitCameraToBox(camera, box, v.azimuth, v.elevation, { fill: cfg.fill || 0.85 });
+ renderer.render(scene, camera);
+ const b64 = canvas.toDataURL('image/png').split(',')[1];
+ views.push({ name: v.name, b64, camera_position: fit.position, look_at: fit.lookAt, fov: FOV_DEG, width, height, azimuth: v.azimuth, elevation: v.elevation });
+ }
+ const tEnd = performance.now();
+ return {
+ ok: true,
+ renderer: rendererString(renderer),
+ views,
+ warnings,
+ bbox: { min: box.min.toArray(), max: box.max.toArray() },
+ timing: { load_ms: Math.round(tLoad - t0), render_ms: Math.round(tEnd - tLoad) },
+ };
+}
diff --git a/harness/runtime_js/lib/browser/studio.js b/harness/runtime_js/lib/browser/studio.js
new file mode 100644
index 00000000..4006235a
--- /dev/null
+++ b/harness/runtime_js/lib/browser/studio.js
@@ -0,0 +1,125 @@
+// Neutral studio look for object renders: RoomEnvironment PMREM + key/fill/rim
+// directionals, ACES tone mapping, sRGB output, optional shadow catcher.
+//
+// import { makeRenderer, buildStudio, applyMode } from '/__runtime/lib/browser/studio.js';
+
+import * as THREE from 'three';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.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;
+}
+
+/** 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));
+}
+
+/**
+ * Add environment + lights (+ shadow catcher) to `scene`, scaled to `box`.
+ * Returns the shadow-catcher mesh (or null) so callers can exclude it from framing.
+ */
+export function buildStudio(renderer, scene, box, { background = 'studio', shadow = true, lights = true } = {}) {
+ const bg = BACKGROUNDS[background];
+ if (bg === undefined) throw new Error(`unknown background '${background}' (studio|white|transparent)`);
+ if (bg === null) renderer.setClearColor(0x000000, 0);
+ else renderer.setClearColor(bg, 1);
+
+ const center = box.getCenter(new THREE.Vector3());
+ const radius = Math.max(box.getSize(new THREE.Vector3()).length() / 2, 1e-3);
+
+ if (lights) {
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+ scene.environmentIntensity = 0.8;
+
+ const key = new THREE.DirectionalLight(0xffffff, 2.2);
+ key.position.copy(center).add(new THREE.Vector3(1.0, 1.6, 1.3).normalize().multiplyScalar(radius * 4));
+ key.target.position.copy(center);
+ key.castShadow = shadow;
+ key.shadow.mapSize.set(2048, 2048);
+ key.shadow.bias = -0.0005;
+ key.shadow.normalBias = radius * 0.01;
+ const cam = key.shadow.camera;
+ cam.left = cam.bottom = -radius * 1.6;
+ cam.right = cam.top = radius * 1.6;
+ cam.near = radius * 0.5;
+ cam.far = radius * 8;
+ scene.add(key, key.target);
+
+ const fill = new THREE.DirectionalLight(0xffffff, 0.8);
+ fill.position.copy(center).add(new THREE.Vector3(-1.2, 0.8, 0.6).normalize().multiplyScalar(radius * 4));
+ fill.target.position.copy(center);
+ scene.add(fill, fill.target);
+
+ const rim = new THREE.DirectionalLight(0xffffff, 1.0);
+ rim.position.copy(center).add(new THREE.Vector3(-0.5, 1.2, -1.4).normalize().multiplyScalar(radius * 4));
+ rim.target.position.copy(center);
+ scene.add(rim, rim.target);
+ }
+
+ let catcher = null;
+ if (shadow && lights) {
+ const geo = new THREE.PlaneGeometry(radius * 20, radius * 20);
+ const mat = new THREE.ShadowMaterial({ opacity: 0.22 });
+ catcher = new THREE.Mesh(geo, mat);
+ catcher.name = '__shadow_catcher';
+ catcher.rotation.x = -Math.PI / 2;
+ catcher.position.set(center.x, box.min.y - radius * 1e-3, center.z);
+ catcher.receiveShadow = true;
+ scene.add(catcher);
+ }
+ return catcher;
+}
+
+const CLAY = new THREE.MeshStandardMaterial({ color: 0x9c9c9c, roughness: 0.85, metalness: 0.0 });
+const NORMALS = new THREE.MeshNormalMaterial();
+const SILHOUETTE = new THREE.MeshBasicMaterial({ color: 0x000000 });
+const WIRE = new THREE.MeshBasicMaterial({ color: 0x1a1a1a, wireframe: true, transparent: true, opacity: 0.45, depthTest: true });
+
+/**
+ * Apply a render mode to every mesh under `root`:
+ * shaded original materials
+ * clay uniform grey MeshStandardMaterial (geometry stays readable)
+ * wire clay + wireframe overlay
+ * normals MeshNormalMaterial
+ * silhouette unlit black (caller uses a white background, no lights)
+ * Returns {lights, shadow} hints for buildStudio.
+ */
+export function applyMode(root, mode) {
+ const meshes = [];
+ root.traverse((o) => {
+ if (o.isMesh || o.isInstancedMesh || o.isSkinnedMesh) meshes.push(o);
+ });
+ for (const m of meshes) {
+ m.castShadow = true;
+ m.receiveShadow = true;
+ if (mode === 'shaded') continue;
+ if (mode === 'clay' || mode === 'wire') m.material = CLAY;
+ else if (mode === 'normals') m.material = NORMALS;
+ else if (mode === 'silhouette') m.material = SILHOUETTE;
+ else throw new Error(`unknown mode '${mode}' (shaded|clay|wire|normals|silhouette)`);
+ }
+ if (mode === 'wire') {
+ for (const m of meshes) {
+ const w = new THREE.Mesh(m.geometry, WIRE);
+ w.name = '__wire';
+ m.add(w);
+ }
+ }
+ const lit = mode === 'shaded' || mode === 'clay' || mode === 'wire';
+ return { lights: lit, shadow: lit };
+}
diff --git a/harness/runtime_js/lib/census.mjs b/harness/runtime_js/lib/census.mjs
new file mode 100644
index 00000000..8fd7d30e
--- /dev/null
+++ b/harness/runtime_js/lib/census.mjs
@@ -0,0 +1,118 @@
+// Census of a THREE.Object3D tree: per-part triangle counts, world bboxes,
+// materials, NaN checks. Pure three.js math — usable in node and browser.
+//
+// import { objectCensus, triangleCount, worldBox } from './census.mjs';
+
+/** Triangles of one mesh geometry (index or non-indexed), honouring draw range. */
+export function geometryTriangles(geometry) {
+ if (!geometry || !geometry.attributes || !geometry.attributes.position) return 0;
+ const count = geometry.index ? geometry.index.count : geometry.attributes.position.count;
+ const range = geometry.drawRange ? Math.min(geometry.drawRange.count, count) : count;
+ return Math.floor(range / 3);
+}
+
+function isMeshLike(obj) {
+ return !!(obj.isMesh || obj.isSkinnedMesh || obj.isInstancedMesh);
+}
+
+/** Triangle count of a subtree (InstancedMesh multiplied by its instance count). */
+export function triangleCount(root) {
+ let n = 0;
+ root.traverseVisible((o) => {
+ if (!isMeshLike(o)) return;
+ const tris = geometryTriangles(o.geometry);
+ n += o.isInstancedMesh ? tris * o.count : tris;
+ });
+ return n;
+}
+
+/** World-space AABB of a subtree as [[minx,miny,minz],[maxx,maxy,maxz]] or null if empty. */
+export function worldBox(THREE, root) {
+ root.updateWorldMatrix(true, true);
+ const box = new THREE.Box3().setFromObject(root, true);
+ if (box.isEmpty()) return null;
+ const r = (v) => +v.toFixed(5);
+ return [box.min.toArray().map(r), box.max.toArray().map(r)];
+}
+
+/** True when any position attribute contains a non-finite value. */
+export function hasNonFinitePositions(root) {
+ let bad = false;
+ root.traverse((o) => {
+ if (bad || !isMeshLike(o) || !o.geometry || !o.geometry.attributes.position) return;
+ const a = o.geometry.attributes.position.array;
+ for (let i = 0; i < a.length; i++) {
+ if (!Number.isFinite(a[i])) {
+ bad = true;
+ return;
+ }
+ }
+ });
+ return bad;
+}
+
+function materialSummary(m) {
+ const out = { name: m.name || '', type: m.type };
+ if (m.color && m.color.isColor) out.color = '#' + m.color.getHexString();
+ if (typeof m.roughness === 'number') out.roughness = +m.roughness.toFixed(3);
+ if (typeof m.metalness === 'number') out.metalness = +m.metalness.toFixed(3);
+ if (m.transparent) out.opacity = +(m.opacity ?? 1).toFixed(3);
+ if (m.map) out.map = true;
+ return out;
+}
+
+/** Unique materials used under `root` (by object identity). */
+export function materialsOf(root) {
+ const seen = new Set();
+ const out = [];
+ root.traverse((o) => {
+ if (!isMeshLike(o) || !o.material) return;
+ const mats = Array.isArray(o.material) ? o.material : [o.material];
+ for (const m of mats) {
+ if (!m || seen.has(m)) continue;
+ seen.add(m);
+ out.push(materialSummary(m));
+ }
+ });
+ return out;
+}
+
+function namedDescendants(part) {
+ const names = [];
+ part.traverse((o) => {
+ if (o !== part && o.name) names.push(o.name);
+ });
+ return names;
+}
+
+/**
+ * Census of an object group: each direct child is a "part".
+ * @returns {{object_name, parts, tri_count, bbox, materials, n_meshes}}
+ */
+export function objectCensus(THREE, group) {
+ group.updateWorldMatrix(true, true);
+ const parts = group.children.map((child) => {
+ const box = worldBox(THREE, child);
+ return {
+ name: child.name || '',
+ type: child.type,
+ tri_count: triangleCount(child),
+ bbox_min: box ? box[0] : null,
+ bbox_max: box ? box[1] : null,
+ children: namedDescendants(child),
+ };
+ });
+ let nMeshes = 0;
+ group.traverse((o) => {
+ if (isMeshLike(o)) nMeshes += 1;
+ });
+ const box = worldBox(THREE, group);
+ return {
+ object_name: group.name || '',
+ parts,
+ tri_count: triangleCount(group),
+ bbox: box ? { min: box[0], max: box[1] } : null,
+ materials: materialsOf(group),
+ n_meshes: nMeshes,
+ };
+}
diff --git a/harness/runtime_js/lib/cli.mjs b/harness/runtime_js/lib/cli.mjs
new file mode 100644
index 00000000..23fa621f
--- /dev/null
+++ b/harness/runtime_js/lib/cli.mjs
@@ -0,0 +1,63 @@
+/** Small CLI helpers shared by the scene drivers: args, JSON summary, exits. */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { parseArgs } from 'node:util';
+
+/** Parse argv with `node:util.parseArgs`; every option is a string unless boolean. */
+export function parseCli(spec, argv = process.argv.slice(2)) {
+ const options = {};
+ for (const [k, v] of Object.entries(spec)) options[k] = { type: v.type || 'string', default: v.default };
+ const { values } = parseArgs({ options, args: argv, allowPositionals: false });
+ return values;
+}
+
+/** Print the final JSON summary as the LAST stdout line and exit. */
+export function finish(summary, code = 0) {
+ process.stdout.write(JSON.stringify(summary) + '\n');
+ process.exit(code);
+}
+
+/** Fail loudly with a JSON summary line (code 2 = could not run). */
+export function fail(message, extra = {}) {
+ process.stderr.write(`error: ${message}\n`);
+ finish({ ok: false, error: message, ...extra }, 2);
+}
+
+export function readJsonArg(value, label) {
+ if (value === undefined || value === null || value === '') return null;
+ try {
+ return JSON.parse(value);
+ } catch (e) {
+ if (fs.existsSync(value)) return JSON.parse(fs.readFileSync(value, 'utf8'));
+ throw new Error(`--${label} is neither JSON nor a file: ${String(e.message)}`);
+ }
+}
+
+export function ensureDir(p) {
+ fs.mkdirSync(p, { recursive: true });
+ return p;
+}
+
+export function writeJson(p, data) {
+ fs.mkdirSync(path.dirname(p), { recursive: true });
+ fs.writeFileSync(p, JSON.stringify(data, null, 2));
+}
+
+export function dataUrlToPng(dataUrl, outPath) {
+ const b64 = String(dataUrl).replace(/^data:image\/png;base64,/, '');
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
+ fs.writeFileSync(outPath, Buffer.from(b64, 'base64'));
+}
+
+/** Wall-clock guard: kills the process if the driver exceeds its budget. */
+export function armWatchdog(ms, onFire) {
+ const t = setTimeout(() => {
+ try { onFire && onFire(); } catch (e) { /* ignore */ }
+ process.stderr.write(`error: driver exceeded ${ms} ms budget\n`);
+ process.stdout.write(JSON.stringify({ ok: false, error: `timeout after ${ms} ms` }) + '\n');
+ process.exit(3);
+ }, ms);
+ t.unref();
+ return t;
+}
diff --git a/harness/runtime_js/lib/glsl_audit.mjs b/harness/runtime_js/lib/glsl_audit.mjs
new file mode 100644
index 00000000..8f26b0c6
--- /dev/null
+++ b/harness/runtime_js/lib/glsl_audit.mjs
@@ -0,0 +1,139 @@
+/**
+ * Static GLSL audits over agent source files (node-side, pure functions).
+ *
+ * Finds GLSL string literals in JS sources, then flags the traps that compile
+ * silently-wrong or not at all in three.js ShaderMaterial / onBeforeCompile:
+ * #include not alone on a line, a #version directive, gl_FragColor next to a
+ * custom `out vec4`, GLSL3 + gl_FragColor, uTime read but never declared or
+ * bound, patches that drop the chunk they replace, precision directives.
+ * Also maps compiler "source line" text back to file:line.
+ */
+
+const GLSL_MARK_RE = /\b(void\s+main|gl_FragColor|gl_Position|#include\s*<|uniform\s+\w+|varying\s+\w+|vec[234]\s+\w+|csm_|gl_FragCoord)\b/;
+const INCLUDE_OK_RE = /^\s*#include\s*<[A-Za-z0-9_]+>\s*;?\s*$/;
+const OUT_VEC4_RE = /^\s*(layout\s*\([^)]*\)\s*)?out\s+(lowp\s+|mediump\s+|highp\s+)?vec4\s+\w+\s*;/m;
+const REPLACE_RE = /\.replace\(\s*(['"`])#include\s*<([A-Za-z0-9_]+)>\1\s*,\s*([`'"])([\s\S]*?)\3\s*\)/g;
+
+/** Extract template/quoted string literals that look like GLSL: [{text, line}]. */
+export function extractGlslStrings(source) {
+ const out = [];
+ const re = /`([^`\\]*(?:\\.[^`\\]*)*)`/g;
+ let m;
+ while ((m = re.exec(source))) {
+ const text = m[1];
+ if (!GLSL_MARK_RE.test(text)) continue;
+ const line = source.slice(0, m.index).split('\n').length; // line of the opening backtick
+ out.push({ text, line, start: m.index });
+ }
+ // Single/double quoted multi-statement GLSL (rare; one-liners with \n)
+ const re2 = /(['"])((?:\\.|(?!\1)[^\\\n])*)\1/g;
+ while ((m = re2.exec(source))) {
+ const text = m[2].replace(/\\n/g, '\n');
+ if (text.length < 40 || !GLSL_MARK_RE.test(text)) continue;
+ const line = source.slice(0, m.index).split('\n').length;
+ out.push({ text, line, start: m.index });
+ }
+ return out;
+}
+
+function finding(file, line, kind, message, severity = 'error') {
+ return { file, line, kind, message, severity };
+}
+
+/** Audit one file; returns findings. */
+export function auditFile(file, source, { sceneUsesFog = false } = {}) {
+ const findings = [];
+ const strings = extractGlslStrings(source);
+ if (!strings.length) return findings;
+ const isRaw = /RawShaderMaterial/.test(source);
+ const glsl3 = /glslVersion\s*:\s*(THREE\.)?GLSL3/.test(source);
+ let usesUTime = false;
+ let declaresUTime = false;
+ let firstUTimeLine = 0;
+ for (const s of strings) {
+ const lines = s.text.split('\n');
+ lines.forEach((ln, i) => {
+ const fileLine = s.line + i;
+ if (/#include/.test(ln) && !INCLUDE_OK_RE.test(ln) && !/\$\{/.test(ln)) {
+ findings.push(finding(file, fileLine, 'include_not_alone', `'#include <chunk>' must be ALONE on its line (found: ${ln.trim().slice(0, 80)})`));
+ }
+ if (/^\s*#version/.test(ln)) {
+ findings.push(finding(file, fileLine, 'version_directive', isRaw
+ ? '#version inside RawShaderMaterial must be the very first line of the string'
+ : 'three.js prepends its own #version line to ShaderMaterial shaders; a second one is a compile error — delete it', isRaw ? 'warn' : 'error'));
+ }
+ if (/^\s*precision\s+(lowp|mediump|highp)\s+float\s*;/.test(ln) && !isRaw) {
+ findings.push(finding(file, fileLine, 'precision_directive', 'three.js prepends precision for ShaderMaterial; remove your own precision line', 'warn'));
+ }
+ if (/\buTime\b/.test(ln) && !firstUTimeLine) firstUTimeLine = fileLine;
+ });
+ const isFragment = /gl_FragColor|gl_FragCoord|csm_FragColor|pc_fragColor|fragColor|output_fragment|discard/.test(s.text) && !/gl_Position/.test(s.text);
+ if (OUT_VEC4_RE.test(s.text) && /gl_FragColor/.test(s.text)) {
+ findings.push(finding(file, s.line, 'fragment_out_and_gl_fragcolor', 'fragment declares its own `out vec4` AND writes gl_FragColor — use one: keep gl_FragColor (no out) or set glslVersion: THREE.GLSL3 and write your out variable'));
+ }
+ if (glsl3 && /gl_FragColor/.test(s.text) && isFragment) {
+ findings.push(finding(file, s.line, 'glsl3_gl_fragcolor', 'glslVersion: THREE.GLSL3 removes gl_FragColor — declare `out vec4 fragColor;` and write fragColor (or drop glslVersion)'));
+ }
+ if (/\buTime\b/.test(s.text)) usesUTime = true;
+ if (/uniform\s+float\s+uTime\s*;/.test(s.text)) declaresUTime = true;
+ }
+ if (usesUTime && !declaresUTime) {
+ findings.push(finding(file, firstUTimeLine, 'undeclared_uniform', 'GLSL reads uTime but no string declares `uniform float uTime;` — a JS uniforms entry is not a GLSL declaration'));
+ }
+ if (usesUTime && !/\buTime\s*[:=]/.test(source.replace(/`[^`]*`/g, ''))) {
+ findings.push(finding(file, firstUTimeLine, 'unbound_uniform', 'GLSL declares/reads uTime but JS never binds it (uniforms: { uTime: { value: 0 } } and update .value in update(t))'));
+ }
+ // onBeforeCompile patches dropping the chunk they replace
+ let rm;
+ REPLACE_RE.lastIndex = 0;
+ while ((rm = REPLACE_RE.exec(source))) {
+ const chunk = rm[2];
+ const replacement = rm[4];
+ const line = source.slice(0, rm.index).split('\n').length;
+ if (!new RegExp(`#include\\s*<${chunk}>`).test(replacement)) {
+ findings.push(finding(file, line, 'chunk_dropped', `patch replaces '#include <${chunk}>' without keeping it — prepend the original include so fog/logdepth/shadow code still runs: '#include <${chunk}>\\n' + yourCode`, 'warn'));
+ }
+ }
+ // Full ShaderMaterial fragment without fog chunks while the scene uses fog
+ const fogOptOut = /fog\s*:\s*false|c3v:\s*no-fog|\bsky\b/i.test(source);
+ if (sceneUsesFog && /ShaderMaterial/.test(source) && !isRaw && !fogOptOut) {
+ for (const s of strings) {
+ if (/void\s+main/.test(s.text) && /gl_FragColor|fragColor/.test(s.text) && !/fog_fragment|USE_FOG|fogColor/.test(s.text)) {
+ findings.push(finding(file, s.line, 'no_fog', 'custom fragment shader ignores scene.fog: add `#include <fog_pars_fragment>` / `#include <fog_fragment>` (+ fog: true and UniformsLib.fog) so it recedes like the rest of the scene', 'warn'));
+ }
+ }
+ }
+ return findings;
+}
+
+/** True when the file contains at least one GLSL-looking string. */
+export function hasGlsl(source) {
+ return extractGlslStrings(source).length > 0;
+}
+
+/** Locate `sourceLine` (trimmed text) in GLSL strings of files: unique → {file, line}. */
+export function locateSourceLine(files, sourceLine) {
+ const needle = String(sourceLine || '').trim();
+ if (needle.length < 3) return { file: '', line: null, candidates: 0 };
+ const hits = [];
+ for (const { file, text } of files) {
+ for (const s of extractGlslStrings(text)) {
+ s.text.split('\n').forEach((ln, i) => { if (ln.trim() === needle) hits.push({ file, line: s.line + i }); });
+ }
+ }
+ if (!hits.length) return { file: '', line: null, candidates: 0 };
+ return { ...hits[0], candidates: hits.length };
+}
+
+/** Fix hint for a compile error message (common WebGL GLSL diagnostics). */
+export function fixHintFor(message) {
+ const m = String(message);
+ if (/undeclared identifier/i.test(m)) return 'declare it (uniform/varying/local) or check spelling/case; uniforms must be declared in the GLSL string too';
+ if (/syntax error/i.test(m)) return 'check the quoted source line for a missing semicolon/brace or a ${} template that expanded badly';
+ if (/no matching overloaded function/i.test(m)) return 'argument types differ (e.g. mix(vec3, vec3, vec3) vs float): cast with float()/vec3()';
+ if (/cannot convert|wrong operand types|dimension mismatch/i.test(m)) return 'GLSL has no implicit int↔float or vec size conversion: write 1.0 not 1, vec3(x) not x';
+ if (/redefinition|already defined|redeclaration/i.test(m)) return 'you declared something three.js already injects (position, uv, normal, projectionMatrix, modelViewMatrix, cameraPosition, or a chunk varying); delete your declaration';
+ if (/l-value|constant expression/i.test(m)) return 'assigning to a read-only/attribute; copy it to a local first';
+ if (/gl_FragColor/i.test(m)) return 'with glslVersion GLSL3 write to your own `out vec4`; otherwise drop glslVersion';
+ return 'fix the quoted GLSL line; run check_shaders again';
+}
diff --git a/harness/runtime_js/lib/host_census.mjs b/harness/runtime_js/lib/host_census.mjs
new file mode 100644
index 00000000..e5ced1b5
--- /dev/null
+++ b/harness/runtime_js/lib/host_census.mjs
@@ -0,0 +1,169 @@
+/**
+ * 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
+ * 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);
+}
+
+export function isCustomShader(mat, THREE) {
+ if (!mat) return false;
+ if (mat.isShaderMaterial || mat.isRawShaderMaterial) return true;
+ if (Object.prototype.hasOwnProperty.call(mat, 'onBeforeCompile')) return true;
+ return mat.onBeforeCompile !== THREE.Material.prototype.onBeforeCompile;
+}
+
+function boxToJson(box) {
+ if (!box || box.isEmpty()) return null;
+ return {
+ min: [box.min.x, box.min.y, box.min.z].map((v) => +v.toFixed(3)),
+ max: [box.max.x, box.max.y, box.max.z].map((v) => +v.toFixed(3)),
+ size: [box.max.x - box.min.x, box.max.y - box.min.y, box.max.z - box.min.z].map((v) => +v.toFixed(3)),
+ };
+}
+
+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 };
+ const box = new THREE.Box3(); // content only
+ const boxAll = new THREE.Box3(); // everything drawable
+ const groundBox = new THREE.Box3();
+ const tmp = new THREE.Box3();
+ root.updateMatrixWorld(true);
+ root.traverse((o) => {
+ if (!o.visible) return;
+ if (o.isLight) lights += 1;
+ if (!(o.isMesh || o.isPoints || o.isLine || o.isSprite)) return;
+ const count = o.isInstancedMesh ? o.count : 1;
+ if (o.isMesh) { meshes += 1; instances += count; }
+ tris += triCount(o.geometry) * count;
+ const mats = Array.isArray(o.material) ? o.material : [o.material];
+ if (mats.some((m) => isCustomShader(m, THREE))) custom += 1;
+ if (!o.geometry) return;
+ if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();
+ const gb = o.geometry.boundingBox;
+ if (!gb || gb.isEmpty()) return;
+ const mb = new THREE.Box3();
+ if (o.isInstancedMesh) {
+ const m = new THREE.Matrix4();
+ const n = Math.min(o.count, 4096);
+ for (let i = 0; i < n; i++) {
+ o.getMatrixAt(i, m);
+ tmp.copy(gb).applyMatrix4(m).applyMatrix4(o.matrixWorld);
+ mb.union(tmp);
+ }
+ } else {
+ mb.copy(gb).applyMatrix4(o.matrixWorld);
+ }
+ if (mb.isEmpty()) return;
+ const kind = classifyMesh(o, mb);
+ kinds[kind] += 1;
+ boxAll.union(mb);
+ if (kind === 'content') box.union(mb);
+ if (kind === 'ground') groundBox.union(mb);
+ });
+ const kind = kinds.content ? 'content' : kinds.ground ? 'ground' : kinds.sky ? 'sky' : (lights && !meshes ? 'light' : 'empty');
+ return { meshes, instances, tris, lights, custom, box, boxAll, groundBox, kind, kinds };
+}
+
+function overlapStats(groups) {
+ const out = [];
+ const content = groups.filter((g) => g.kind === 'content' && g.bbox);
+ for (let i = 0; i < content.length; i++) {
+ for (let j = i + 1; j < content.length; j++) {
+ const a = content[i].bbox, b = content[j].bbox;
+ const ix = Math.min(a.max[0], b.max[0]) - Math.max(a.min[0], b.min[0]);
+ const iz = Math.min(a.max[2], b.max[2]) - Math.max(a.min[2], b.min[2]);
+ if (ix <= 0 || iz <= 0) continue;
+ const areaA = Math.max(1e-6, a.size[0] * a.size[2]);
+ const areaB = Math.max(1e-6, b.size[0] * b.size[2]);
+ const frac = (ix * iz) / Math.min(areaA, areaB);
+ if (frac > 0.05) out.push({ a: content[i].name, b: content[j].name, footprint_overlap: +frac.toFixed(3) });
+ }
+ }
+ return out.sort((x, y) => y.footprint_overlap - x.footprint_overlap).slice(0, 20);
+}
+
+/** Walk `scene` and return the census JSON. */
+export function sceneCensus(scene, THREE) {
+ scene.updateMatrixWorld(true);
+ const groups = [];
+ const totals = { meshes: 0, instances: 0, triangles: 0, lights: 0, custom_shader_meshes: 0 };
+ const lightTypes = {};
+ const materials = new Set();
+ const customMaterials = [];
+ scene.traverse((o) => {
+ if (o.isLight) lightTypes[o.type] = (lightTypes[o.type] || 0) + 1;
+ if (o.material) {
+ for (const m of Array.isArray(o.material) ? o.material : [o.material]) {
+ if (!m || materials.has(m.uuid)) continue;
+ materials.add(m.uuid);
+ if (isCustomShader(m, THREE)) {
+ customMaterials.push({
+ name: m.name || '', type: m.type, on: o.name || o.type,
+ kind: m.isShaderMaterial || m.isRawShaderMaterial ? 'ShaderMaterial' : 'onBeforeCompile',
+ has_time_uniform: !!(m.uniforms && (m.uniforms.uTime || m.uniforms.time)),
+ });
+ }
+ }
+ }
+ });
+ const unionAll = new THREE.Box3();
+ const content = new THREE.Box3();
+ const groundAll = new THREE.Box3();
+ for (const child of scene.children) {
+ const g = walkGroup(child, THREE);
+ const name = child.name || `${child.type}_${groups.length}`;
+ groups.push({
+ name, named: !!child.name, type: child.type, kind: g.kind, meshes: g.meshes, instances: g.instances,
+ triangles: g.tris, lights: g.lights, custom_shader_meshes: g.custom, mesh_kinds: g.kinds,
+ bbox: boxToJson(g.kind === 'content' ? g.box : g.boxAll),
+ });
+ totals.meshes += g.meshes; totals.instances += g.instances; totals.triangles += g.tris; totals.lights += g.lights; totals.custom_shader_meshes += g.custom;
+ if (!g.boxAll.isEmpty()) unionAll.union(g.boxAll);
+ if (!g.box.isEmpty()) content.union(g.box);
+ if (!g.groundBox.isEmpty()) groundAll.union(g.groundBox);
+ }
+ const groundY = groundAll.isEmpty() ? null : groundAll.max.y;
+ const contentBox = boxToJson(content.isEmpty() ? unionAll : content);
+ return {
+ totals,
+ light_types: lightTypes,
+ materials: materials.size,
+ custom_materials: customMaterials,
+ fog: scene.fog ? { type: scene.fog.type, near: scene.fog.near, far: scene.fog.far, density: scene.fog.density } : null,
+ background: scene.background ? (scene.background.isColor ? '#' + scene.background.getHexString() : scene.background.type || 'texture') : null,
+ environment: !!scene.environment,
+ groups,
+ bbox: boxToJson(unionAll),
+ content_bbox: contentBox,
+ ground_y: groundY !== null ? +groundY.toFixed(3) : (contentBox ? contentBox.min[1] : 0),
+ has_ground: groundY !== null,
+ overlaps: overlapStats(groups),
+ };
+}
diff --git a/harness/runtime_js/lib/host_compile.mjs b/harness/runtime_js/lib/host_compile.mjs
new file mode 100644
index 00000000..34af4ded
--- /dev/null
+++ b/harness/runtime_js/lib/host_compile.mjs
@@ -0,0 +1,109 @@
+/**
+ * Compile-time material machinery (page-side): capture the FINAL GLSL sources
+ * of every custom material (ShaderMaterial directly; onBeforeCompile via a
+ * cache-key-preserving wrapper), attribute compiler errors to materials by
+ * source-line match, audit runtime materials (fog/uTime), and swap custom
+ * shaders for plain ones for the counterfactual presence probe.
+ */
+
+import { isCustomShader } from './host_census.mjs';
+
+export const captured = []; // {name, type, vs, fs} final shader sources per custom material
+
+export function captureMaterialSources(scene, THREE) {
+ const seen = new Set();
+ scene.traverse((o) => {
+ if (!o.material) return;
+ for (const m of Array.isArray(o.material) ? o.material : [o.material]) {
+ if (!m || seen.has(m.uuid) || m.__c3vCaptured) continue;
+ seen.add(m.uuid);
+ const name = m.name || `${m.type} on ${o.name || o.type}`;
+ if (m.isShaderMaterial || m.isRawShaderMaterial) {
+ captured.push({ name, type: m.type, vs: m.vertexShader, fs: m.fragmentShader, uuid: m.uuid });
+ m.__c3vCaptured = true;
+ continue;
+ }
+ if (!Object.prototype.hasOwnProperty.call(m, 'onBeforeCompile')) continue;
+ // Wrap the patch to record the FINAL sources. Keep the program cache key
+ // identical so wrapped materials never share a program by accident.
+ const orig = m.onBeforeCompile;
+ const origKey = m.customProgramCacheKey();
+ m.onBeforeCompile = function (shader, renderer) {
+ orig.call(this, shader, renderer);
+ captured.push({ name, type: m.type, vs: shader.vertexShader, fs: shader.fragmentShader, uuid: m.uuid });
+ };
+ m.customProgramCacheKey = () => origKey;
+ m.__c3vCaptured = true;
+ }
+ });
+}
+
+export function attributeErrors(errs) {
+ for (const e of errs) {
+ if (e.material || !e.source_line) continue;
+ const needle = e.source_line.trim();
+ const hits = captured.filter((c) => (e.stage === 'vertex' ? c.vs : c.fs).split('\n').some((l) => l.trim() === needle));
+ if (hits.length === 1) { e.material = hits[0].name; e.material_type = hits[0].type; }
+ else if (hits.length > 1) { e.material = hits.map((h) => h.name).slice(0, 3).join(' | '); e.material_type = 'ambiguous'; }
+ }
+}
+
+export function materialAudit(scene, THREE) {
+ const out = [];
+ const fog = !!scene.fog;
+ const seen = new Set();
+ scene.traverse((o) => {
+ if (!o.material) return;
+ for (const m of Array.isArray(o.material) ? o.material : [o.material]) {
+ if (!m || seen.has(m.uuid) || !m.isShaderMaterial) continue;
+ seen.add(m.uuid);
+ const name = m.name || `${m.type} on ${o.name || o.type}`;
+ const fs = String(m.fragmentShader || '');
+ const skyLike = /sky|dome|stars|cloud|sun|moon/i.test(`${o.name} ${m.name}`) || (m.side === THREE.BackSide && m.depthWrite === false);
+ if (fog && !skyLike && !(m.fog && m.uniforms && m.uniforms.fogColor) && !/fog_fragment|fogColor/.test(fs)) {
+ out.push({ kind: 'no_fog', severity: 'warn', material: name, message: `ShaderMaterial '${name}' ignores scene.fog (set fog: true, merge THREE.UniformsLib.fog, include fog_pars_fragment/fog_fragment)` });
+ }
+ if (/\buTime\b/.test(fs + String(m.vertexShader || '')) && !(m.uniforms && m.uniforms.uTime)) {
+ out.push({ kind: 'unbound_uniform', severity: 'error', material: name, message: `ShaderMaterial '${name}' reads uTime but uniforms.uTime is missing` });
+ }
+ }
+ });
+ return out;
+}
+
+
+
+/**
+ * Counterfactual: swap custom-shader materials for plain ones (ShaderMaterial →
+ * grey MeshStandardMaterial, onBeforeCompile → unpatched clone). Returns an
+ * undo function. Used by the shader-presence probe (pixel diff vs normal).
+ */
+export function stripCustomShaders(scene, THREE) {
+ const undo = [];
+ const cloneCache = new Map();
+ scene.traverse((o) => {
+ if (!o.material) return;
+ const mats = Array.isArray(o.material) ? o.material : [o.material];
+ const swapped = mats.map((m) => {
+ if (!m || !isCustomShader(m, THREE)) return m;
+ if (cloneCache.has(m.uuid)) return cloneCache.get(m.uuid);
+ let rep;
+ if (m.isShaderMaterial || m.isRawShaderMaterial) {
+ rep = new THREE.MeshStandardMaterial({ color: 0x808080, roughness: 0.8, side: m.side, transparent: m.transparent, opacity: m.opacity, depthWrite: m.depthWrite });
+ } else {
+ rep = m.clone();
+ delete rep.onBeforeCompile; // clone() does not copy the own patch, but be explicit
+ rep.customProgramCacheKey = THREE.Material.prototype.customProgramCacheKey;
+ }
+ cloneCache.set(m.uuid, rep);
+ return rep;
+ });
+ if (swapped.some((m, i) => m !== mats[i])) {
+ const orig = o.material;
+ o.material = Array.isArray(orig) ? swapped : swapped[0];
+ undo.push(() => { o.material = orig; });
+ }
+ });
+ return () => { for (const u of undo) u(); for (const m of cloneCache.values()) m.dispose(); };
+}
+
diff --git a/harness/runtime_js/lib/host_metrics.mjs b/harness/runtime_js/lib/host_metrics.mjs
new file mode 100644
index 00000000..dc66ff10
--- /dev/null
+++ b/harness/runtime_js/lib/host_metrics.mjs
@@ -0,0 +1,93 @@
+/**
+ * Page-side frame/camera instruments: luminance statistics from a downscaled
+ * readback of the render canvas and near-geometry tests for a camera.
+ */
+
+const SAMPLE_W = 96;
+const SAMPLE_H = 54;
+
+/** Mean luminance and dark/blown fractions of the current canvas. */
+export function frameStats(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;
+ let sum = 0, sumSq = 0, dark = 0, blown = 0;
+ let top = 0, bottom = 0;
+ const hist = new Uint32Array(8);
+ for (let i = 0; i < n; i++) {
+ const r = data[i * 4], g = data[i * 4 + 1], b = data[i * 4 + 2];
+ const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
+ sum += lum; sumSq += lum * lum;
+ if (lum < 10) dark += 1;
+ if (r > 250 && g > 250 && b > 250) blown += 1;
+ hist[Math.min(7, Math.floor(lum / 32))] += 1;
+ if (i < n / 2) top += lum; else bottom += lum;
+ }
+ const mean = sum / n;
+ const std = Math.sqrt(Math.max(0, sumSq / n - mean * mean));
+ // "flat" frames: one luminance bucket holds almost everything (void / wall)
+ let modal = 0;
+ for (const h of hist) modal = Math.max(modal, h);
+ return {
+ mean_lum: +(mean / 255).toFixed(4),
+ lum_std: +(std / 255).toFixed(4),
+ dark_frac: +(dark / n).toFixed(4),
+ blown_frac: +(blown / n).toFixed(4),
+ modal_frac: +(modal / n).toFixed(4),
+ top_bottom_ratio: +((top + 1) / (bottom + 1)).toFixed(3),
+ };
+}
+
+/**
+ * Near-geometry test: centre + 3x3 grid rays from the camera; nearest hit
+ * distance, plus meshes whose world bbox contains the eye (closed rooms,
+ * back-face culled interiors).
+ */
+export function nearGeometry(scene, camera, THREE, limitM = 0.3) {
+ const rc = new THREE.Raycaster();
+ rc.far = 50;
+ let nearest = Infinity;
+ let nearestName = '';
+ const targets = [];
+ scene.traverse((o) => { if ((o.isMesh || o.isInstancedMesh) && o.visible) targets.push(o); });
+ const pts = [];
+ for (let gy = -1; gy <= 1; gy++) for (let gx = -1; gx <= 1; gx++) pts.push([gx * 0.6, gy * 0.6]);
+ let hits = 0;
+ for (const [x, y] of pts) {
+ rc.setFromCamera(new THREE.Vector2(x, y), camera);
+ let hit = null;
+ try { hit = rc.intersectObjects(targets, false)[0]; } catch (e) { hit = null; }
+ if (hit) {
+ hits += 1;
+ if (hit.distance < nearest) { nearest = hit.distance; nearestName = hit.object.name || hit.object.parent?.name || hit.object.type; }
+ }
+ }
+ const inside = [];
+ const eye = camera.position;
+ const box = new THREE.Box3();
+ for (const o of targets) {
+ if (o.isInstancedMesh) continue;
+ if (!o.geometry) continue;
+ if (!o.geometry.boundingBox) o.geometry.computeBoundingBox();
+ box.copy(o.geometry.boundingBox).applyMatrix4(o.matrixWorld);
+ const s = box.getSize(new THREE.Vector3());
+ if (Math.max(s.x, s.y, s.z) > 60 || Math.min(s.x, s.y, s.z) < 0.05) continue; // ground/sky/flat decals
+ if (box.containsPoint(eye)) inside.push(o.name || o.parent?.name || o.type);
+ }
+ const center = new THREE.Vector3();
+ camera.getWorldDirection(center);
+ return {
+ nearest_hit_m: Number.isFinite(nearest) ? +nearest.toFixed(3) : null,
+ nearest_hit_name: nearestName,
+ rays_hit: hits,
+ rays_total: pts.length,
+ inside_mesh_bbox: inside.slice(0, 5),
+ camera_in_geometry: (Number.isFinite(nearest) && nearest < limitM) || inside.length > 0,
+ eye_height_m: +eye.y.toFixed(3),
+ look_dir: [center.x, center.y, center.z].map((v) => +v.toFixed(3)),
+ };
+}
diff --git a/harness/runtime_js/lib/host_page.mjs b/harness/runtime_js/lib/host_page.mjs
new file mode 100644
index 00000000..66f2a843
--- /dev/null
+++ b/harness/runtime_js/lib/host_page.mjs
@@ -0,0 +1,102 @@
+/**
+ * Node-side driver around the page host: serve the workspace, launch the
+ * browser, open the host page, boot the scene, collect console / page errors.
+ * All three scene CLIs (render / probe / check_shaders) go through here.
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { importMapHtml, launchBrowser, runtimeMount, serveWorkspace } from './_compat.mjs';
+
+const SHADER_NOISE_RE = /shader|program not valid|glsl|WebGL|compile|THREE\.WebGLProgram/i;
+const MAX_CONSOLE = 60;
+const CONTROL_RE = new RegExp('[\\u0000-\\u001f]+', 'g');
+
+function hostHtml() {
+ return [
+ '<!doctype html><html><head><meta charset="utf-8"><title>c3v scene host</title>',
+ importMapHtml(),
+ '<style>html,body{margin:0;background:#000;overflow:hidden}</style></head><body>',
+ `<script type="module" src="${runtimeMount()}lib/scene_host.mjs"></script></body></html>`,
+ ].join('\n');
+}
+
+function clean(s) {
+ return String(s).replace(CONTROL_RE, ' ').trim();
+}
+
+/**
+ * Open the host for workspace `wsRoot`.
+ * @returns {Promise<{page, browser, base, gpu, renderer, errors, boot, close}>}
+ */
+export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js' } = {}) {
+ wsRoot = path.resolve(wsRoot);
+ if (!fs.existsSync(path.join(wsRoot, sceneRel))) {
+ throw new Error(`missing ${sceneRel} in workspace ${wsRoot}`);
+ }
+ const srv = await serveWorkspace(wsRoot, { hostHtml: hostHtml() });
+ const errors = { console: [], page: [], shader_console: [], warnings: [] };
+ let launched = null;
+ try {
+ launched = await launchBrowser({ gpu });
+ const page = await launched.browser.newPage();
+ await page.setViewport({ width, height, deviceScaleFactor: 1 });
+ page.on('console', (m) => {
+ const type = m.type();
+ if (type !== 'error' && type !== 'warning') return;
+ const text = clean(m.text());
+ if (!text) return;
+ const isShader = SHADER_NOISE_RE.test(text);
+ // Chrome's bare resource-load line duplicates the 404 the response handler
+ // already reported with the URL and a hint; keep it out of the error bucket.
+ const isResourceNoise = /Failed to load resource/.test(text);
+ const bucket = type === 'warning' || isResourceNoise ? errors.warnings : (isShader ? errors.shader_console : errors.console);
+ if (bucket.length < MAX_CONSOLE && !bucket.includes(text)) bucket.push(text.slice(0, 600));
+ });
+ page.on('pageerror', (e) => {
+ const text = clean((e && (e.stack || e.message)) || e);
+ if (errors.page.length < MAX_CONSOLE) errors.page.push(text.slice(0, 800));
+ });
+ page.on('requestfailed', (req) => {
+ const url = req.url();
+ if (url.startsWith(srv.base)) errors.console.push(`request failed: ${url.slice(srv.base.length)} (${req.failure()?.errorText || '?'})`);
+ });
+ page.on('response', (res) => {
+ if (res.status() === 404 && res.url().startsWith(srv.base)) {
+ const rel = res.url().slice(srv.base.length);
+ // a missing GLB/texture is a WARNING (the scene still boots and renders
+ // without it — the judge sees the absence); a missing MODULE is fatal.
+ const bucket = rel.startsWith('/assets/') || rel.startsWith('/public/') ? errors.warnings : errors.console;
+ bucket.push(`404 not found: ${rel}` + (bucket === errors.console ? " (imports must be 'three', 'three/addons/*' or relative; assets under public/assets → '/assets/...')" : ' (build/copy the asset into public/assets/)'));
+ }
+ });
+ await page.goto(`${srv.base}/__host.html`, { waitUntil: 'load', timeout: 60000 });
+ await page.waitForFunction('window.__c3v_ready === true', { timeout: 60000 });
+ const boot = await page.evaluate(
+ (o) => window.__c3v.boot(o),
+ { sceneUrl: `/${sceneRel}`, width, height, logDepth },
+ );
+ const close = async () => {
+ try { await launched.browser.close(); } catch (e) { /* ignore */ }
+ await srv.close();
+ };
+ return { page, browser: launched.browser, base: srv.base, gpu: launched.gpu, renderer: launched.renderer, errors, boot, close };
+ } catch (e) {
+ if (launched && launched.browser) await launched.browser.close().catch(() => {});
+ await srv.close();
+ throw e;
+ }
+}
+
+/** Flatten the collected errors into the summary shape used by all drivers. */
+export function errorSummary(errors, boot) {
+ const consoleErrors = [...errors.console, ...errors.page.map((p) => `pageerror: ${p}`)];
+ if (boot && boot.error) consoleErrors.unshift(`boot[${boot.stage}]: ${boot.error}`);
+ const warnings = [...errors.warnings];
+ for (const le of (boot && boot.load_errors) || []) warnings.push(`load: ${le}`);
+ return {
+ console_errors: consoleErrors,
+ console_warnings: warnings,
+ shader_console: errors.shader_console,
+ };
+}
diff --git a/harness/runtime_js/lib/host_shader_errors.mjs b/harness/runtime_js/lib/host_shader_errors.mjs
new file mode 100644
index 00000000..8a55d925
--- /dev/null
+++ b/harness/runtime_js/lib/host_shader_errors.mjs
@@ -0,0 +1,52 @@
+/**
+ * WebGL shader compile/link error capture through `renderer.debug.onShaderError`.
+ * Records every `ERROR: n:m: msg` with the assembled source line text so the
+ * node side can map it back to the author's file:line (three expands
+ * #includes and prepends hundreds of lines, so compiler line numbers alone
+ * point nowhere useful).
+ */
+
+const ERR_RE = /ERROR:\s*(\d+):(\d+):\s*([^\n]*)/g;
+
+function stageErrors(gl, shader, stage, materialInfo) {
+ let log = '';
+ try { log = (gl.getShaderInfoLog(shader) || '').trim(); } catch (e) { log = ''; }
+ if (!log) return [];
+ let lines = [];
+ try { lines = (gl.getShaderSource(shader) || '').split('\n'); } catch (e) { lines = []; }
+ const out = [];
+ let m;
+ ERR_RE.lastIndex = 0;
+ while ((m = ERR_RE.exec(log))) {
+ const ln = parseInt(m[2], 10);
+ out.push({
+ stage,
+ message: m[3].trim(),
+ assembled_line: ln,
+ source_line: (lines[ln - 1] || '').trim(),
+ context: lines.slice(Math.max(0, ln - 3), ln + 2).map((s) => s.trim()),
+ ...materialInfo,
+ });
+ }
+ if (!out.length) out.push({ stage, message: log.slice(0, 400), assembled_line: null, source_line: '', context: [], ...materialInfo });
+ return out;
+}
+
+/** Install the hook; errors are appended to `sink` (array) and deduped. */
+export function installShaderErrorHook(renderer, sink) {
+ renderer.debug.checkShaderErrors = true;
+ renderer.debug.onShaderError = (gl, program, glVS, glFS) => {
+ let matInfo = { material: '', material_type: '' };
+ try {
+ // three keeps the material name/type in the program's cacheKey; parse defensively
+ const pl = gl.getProgramInfoLog(program) || '';
+ matInfo.program_log = pl.trim().slice(0, 300);
+ } catch (e) { /* ignore */ }
+ const errs = [...stageErrors(gl, glVS, 'vertex', matInfo), ...stageErrors(gl, glFS, 'fragment', matInfo)];
+ if (!errs.length) errs.push({ stage: 'program', message: matInfo.program_log || 'program not valid', assembled_line: null, source_line: '', context: [] });
+ for (const e of errs) {
+ const key = `${e.stage}|${e.assembled_line}|${e.message}|${e.source_line}`;
+ if (!sink.some((s) => s._key === key)) sink.push({ ...e, _key: key });
+ }
+ };
+}
diff --git a/harness/runtime_js/lib/node_polyfills.mjs b/harness/runtime_js/lib/node_polyfills.mjs
new file mode 100644
index 00000000..64c1f45f
--- /dev/null
+++ b/harness/runtime_js/lib/node_polyfills.mjs
@@ -0,0 +1,62 @@
+// Minimal browser-API shims so three's GLTFExporter can write a binary GLB in
+// plain node (no DOM). Node 18+ already has Blob/TextEncoder/URL; the exporter
+// additionally reads Blobs back through FileReader. We do NOT shim canvases:
+// texture images are stripped by the exporter wrapper (with a warning) so the
+// exporter never reaches the canvas path.
+//
+// import { installExporterPolyfills } from './node_polyfills.mjs';
+
+import { Blob as NodeBlob } from 'node:buffer';
+
+class FileReaderShim {
+ constructor() {
+ this.result = null;
+ this.onload = null;
+ this.onloadend = null;
+ this.onerror = null;
+ }
+
+ _finish(result) {
+ this.result = result;
+ if (typeof this.onload === 'function') this.onload({ target: this });
+ if (typeof this.onloadend === 'function') this.onloadend({ target: this });
+ }
+
+ _fail(err) {
+ if (typeof this.onerror === 'function') this.onerror(err);
+ else throw err;
+ }
+
+ readAsArrayBuffer(blob) {
+ blob.arrayBuffer().then((buf) => this._finish(buf), (e) => this._fail(e));
+ }
+
+ readAsDataURL(blob) {
+ blob.arrayBuffer().then((buf) => {
+ const b64 = Buffer.from(buf).toString('base64');
+ this._finish(`data:${blob.type || 'application/octet-stream'};base64,${b64}`);
+ }, (e) => this._fail(e));
+ }
+
+ readAsText(blob) {
+ blob.text().then((t) => this._finish(t), (e) => this._fail(e));
+ }
+}
+
+/** Install the shims once (idempotent); returns the list of names installed. */
+export function installExporterPolyfills() {
+ const installed = [];
+ if (typeof globalThis.self === 'undefined') {
+ globalThis.self = globalThis;
+ installed.push('self');
+ }
+ if (typeof globalThis.Blob === 'undefined') {
+ globalThis.Blob = NodeBlob;
+ installed.push('Blob');
+ }
+ if (typeof globalThis.FileReader === 'undefined') {
+ globalThis.FileReader = FileReaderShim;
+ installed.push('FileReader');
+ }
+ return installed;
+}
diff --git a/harness/runtime_js/lib/orbit.mjs b/harness/runtime_js/lib/orbit.mjs
new file mode 100644
index 00000000..bbe2acf7
--- /dev/null
+++ b/harness/runtime_js/lib/orbit.mjs
@@ -0,0 +1,57 @@
+/**
+ * Overview orbit rig fitted to a census bbox (pure). Scenes sit on ground,
+ * so the rig is ground-aware: eyes never go below ground, low "eye level"
+ * views are lifted to ~1.6 m above ground. Azimuth 0 = front (+Z), CCW from
+ * above; elevation in degrees above the horizon (see codeverse/conventions.py).
+ */
+
+const DEG = Math.PI / 180;
+
+/** Unit direction from azimuth/elevation (Y-up, +Z front). */
+export function orbitDirection(azimuthDeg, elevationDeg) {
+ const az = azimuthDeg * DEG, el = elevationDeg * DEG;
+ return [Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el)];
+}
+
+/**
+ * Build camera specs for `views` around `bbox` ({min:[..], max:[..]}).
+ * @returns {Array<{name, position, lookAt, fov, kind:'orbit'}>}
+ */
+export function fitOrbitCameras(bbox, views, { fov = 50, aspect = 16 / 9, groundY = null, margin = 1.15, noFog = true } = {}) {
+ if (!bbox || !bbox.min || !bbox.max) return [];
+ const size = bbox.max.map((v, i) => v - bbox.min[i]);
+ const center = bbox.min.map((v, i) => v + size[i] / 2);
+ const radius = Math.max(0.5, Math.hypot(size[0], size[1], size[2]) / 2);
+ const fovV = fov * DEG;
+ const fovH = 2 * Math.atan(Math.tan(fovV / 2) * aspect);
+ const dist = (radius / Math.sin(Math.min(fovV, fovH) / 2)) * margin;
+ const floor = groundY === null || groundY === undefined ? bbox.min[1] : groundY;
+ const out = [];
+ const horizDist = (dx, dz) => {
+ // distance from the centre to the bbox's xz boundary along (dx, dz)
+ const hx = size[0] / 2, hz = size[2] / 2;
+ const tx = Math.abs(dx) > 1e-6 ? hx / Math.abs(dx) : Infinity;
+ const tz = Math.abs(dz) > 1e-6 ? hz / Math.abs(dz) : Infinity;
+ return Math.min(tx, tz);
+ };
+ for (const v of views) {
+ const el = Math.max(3, Math.min(89, v.elevation));
+ const d = orbitDirection(v.azimuth, el);
+ let eye, lookAt;
+ if (el <= 20) {
+ // eye-level: a person standing just outside the content footprint, looking in
+ const dh = orbitDirection(v.azimuth, 0);
+ const edge = horizDist(dh[0], dh[2]);
+ const back = edge + Math.max(2, 0.12 * Math.max(size[0], size[2]));
+ const eyeH = floor + 1.6 + Math.min(4, 0.1 * size[1]);
+ eye = [center[0] + dh[0] * back, eyeH, center[2] + dh[2] * back];
+ lookAt = [center[0], Math.min(center[1], floor + 0.35 * size[1] + 0.5), center[2]];
+ } else {
+ eye = center.map((c, i) => c + d[i] * dist);
+ lookAt = center.slice();
+ }
+ if (eye[1] < floor + 0.5) eye[1] = floor + 0.5;
+ out.push({ name: v.name, position: eye.map((x) => +x.toFixed(3)), lookAt: lookAt.map((x) => +x.toFixed(3)), fov, kind: 'orbit', noFog: !!noFog && el > 20 });
+ }
+ return out;
+}
diff --git a/harness/runtime_js/lib/resolve_three.mjs b/harness/runtime_js/lib/resolve_three.mjs
new file mode 100644
index 00000000..832c6371
--- /dev/null
+++ b/harness/runtime_js/lib/resolve_three.mjs
@@ -0,0 +1,32 @@
+// Module-resolution hook: lets agent code that lives OUTSIDE runtime_js/
+// `import ... from 'three'` / 'three/addons/*' without a node_modules of its own.
+//
+// NODE_PATH only affects CommonJS resolution, so ESM needs a loader hook.
+// Usage: node --import <runtime_js>/lib/resolve_three.mjs script.mjs
+// 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.
+
+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'];
+
+function isRedirected(spec) {
+ return REDIRECTED.some((p) => spec === p || spec.startsWith(p + '/'));
+}
+
+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/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjs
new file mode 100644
index 00000000..c4ab62d9
--- /dev/null
+++ b/harness/runtime_js/lib/scene_host.mjs
@@ -0,0 +1,330 @@
+/**
+ * Page-side host for `scene_threejs` workspaces (runs in headless Chrome).
+ *
+ * Boots a WebGLRenderer with the harness's fixed settings (antialias, ACES,
+ * sRGB, shadow maps), imports the agent's `src/scene.js` through the import
+ * map, calls `createScene({THREE, renderer, loaders})`, validates the returned
+ * shape and exposes `window.__c3v` with deterministic instruments:
+ * boot(opts) · renderAt(cameraSpec, t) · census() · fps(seconds)
+ * cameraChecks(cameraSpec) · compileAll(cameraSpec) · shaderErrors()
+ * Node drivers (render_scene / probe_scene / check_shaders) call these via
+ * page.evaluate. Agent code never imports this file.
+ */
+
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { sceneCensus } from './host_census.mjs';
+import { frameStats, nearGeometry } from './host_metrics.mjs';
+import { installShaderErrorHook } from './host_shader_errors.mjs';
+import { attributeErrors, captured, captureMaterialSources, materialAudit, stripCustomShaders } from './host_compile.mjs';
+
+const FIXED_DT = 1 / 30;
+const LOAD_IDLE_TIMEOUT_MS = 30000;
+
+const state = {
+ booted: false,
+ renderer: null,
+ canvas: null,
+ scene: null,
+ cameras: [],
+ update: null,
+ simTime: 0,
+ width: 1024,
+ height: 576,
+ rafCalls: 0,
+ shaderErrors: [],
+ loadErrors: [],
+ hostWarnings: [],
+ bootInfo: null,
+ contentBox: null,
+ fullBox: null,
+};
+
+function makeRenderer(width, height, opts) {
+ const canvas = document.createElement('canvas');
+ canvas.width = width;
+ canvas.height = height;
+ canvas.id = 'c3v-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 };
+}
+
+function validateCameras(raw) {
+ const out = [];
+ const problems = [];
+ if (!Array.isArray(raw)) {
+ problems.push('createScene().cameras is not an array');
+ return { cameras: out, problems };
+ }
+ raw.forEach((c, i) => {
+ const p = c && c.position;
+ const l = c && c.lookAt;
+ const okVec = (v) => Array.isArray(v) && v.length === 3 && v.every((x) => Number.isFinite(x));
+ if (!c || typeof c !== 'object') { problems.push(`cameras[${i}] is not an object`); return; }
+ if (!okVec(p)) { problems.push(`cameras[${i}] position must be [x,y,z] finite numbers`); return; }
+ if (!okVec(l)) { problems.push(`cameras[${i}] lookAt must be [x,y,z] finite numbers`); return; }
+ const fov = Number.isFinite(c.fov) ? c.fov : 50;
+ if (fov < 5 || fov > 150) problems.push(`cameras[${i}] fov ${fov} outside [5,150]`);
+ if (p.every((x, k) => Math.abs(x - l[k]) < 1e-6)) problems.push(`cameras[${i}] position equals lookAt`);
+ out.push({ name: String(c.name || `cam_${i}`), position: p.map(Number), lookAt: l.map(Number), fov });
+ });
+ if (out.length === 0) problems.push('no valid cameras (author 1-6 {name, position, lookAt, fov})');
+ if (out.length > 6) problems.push(`too many cameras (${out.length} > 6)`);
+ return { cameras: out, problems };
+}
+
+function makeLoaders(manager) {
+ const gltf = new GLTFLoader(manager);
+ const texture = new THREE.TextureLoader(manager);
+ const cube = new THREE.CubeTextureLoader(manager);
+ return { gltf, texture, cube, manager };
+}
+
+function waitForLoads(manager, timeoutMs) {
+ return new Promise((resolve) => {
+ let done = false;
+ const finish = (why) => { if (!done) { done = true; resolve(why); } };
+ // If nothing is loading the manager never fires onLoad; check idle flag.
+ const t0 = performance.now();
+ const tick = () => {
+ if (done) return;
+ if (!manager.__c3vPending) return finish('idle');
+ if (performance.now() - t0 > timeoutMs) return finish('timeout');
+ setTimeout(tick, 50);
+ };
+ tick();
+ });
+}
+
+/**
+ * Boot the host: renderer → import module → createScene → wait loads.
+ * @param {{sceneUrl:string,width?:number,height?:number,logDepth?:boolean}} opts
+ */
+async function boot(opts) {
+ const t0 = performance.now();
+ const info = { ok: false, stage: 'init', error: '', cameras: [], camera_problems: [], shape: {}, timings_ms: {}, renderer: '' };
+ state.bootInfo = info;
+ try {
+ state.width = opts.width || 1024;
+ state.height = opts.height || 576;
+ window.requestAnimationFrame = () => { state.rafCalls += 1; return 0; };
+ window.cancelAnimationFrame = () => {};
+ const { renderer, canvas } = makeRenderer(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));
+ } catch (e) { info.renderer = 'unknown'; }
+
+ info.stage = 'import';
+ const tImp = performance.now();
+ const mod = await import(opts.sceneUrl);
+ info.timings_ms.import = Math.round(performance.now() - tImp);
+ if (typeof mod.createScene !== 'function') {
+ throw new Error(`src/scene.js must export function createScene({THREE, renderer, loaders}); exports found: [${Object.keys(mod).join(', ')}]`);
+ }
+
+ info.stage = 'createScene';
+ const manager = new THREE.LoadingManager();
+ manager.__c3vPending = false;
+ manager.onStart = () => { manager.__c3vPending = true; };
+ manager.onLoad = () => { manager.__c3vPending = false; };
+ manager.onError = (url) => { const m = `failed to load ${url}`; if (!state.loadErrors.includes(m)) state.loadErrors.push(m); };
+ const loaders = makeLoaders(manager);
+ const tCs = performance.now();
+ const result = await mod.createScene({ THREE, renderer, loaders });
+ info.timings_ms.create_scene = Math.round(performance.now() - tCs);
+ if (!result || typeof result !== 'object') throw new Error('createScene() must return {scene, cameras, update}');
+ info.shape = {
+ has_scene: !!(result.scene && result.scene.isScene),
+ has_cameras: Array.isArray(result.cameras),
+ has_update: typeof result.update === 'function',
+ };
+ if (!info.shape.has_scene) throw new Error('createScene().scene is not a THREE.Scene');
+ const { cameras, problems } = validateCameras(result.cameras);
+ info.cameras = cameras;
+ info.camera_problems = problems;
+ state.scene = result.scene;
+ state.cameras = cameras;
+ state.update = typeof result.update === 'function' ? result.update : null;
+ if (!state.update) info.camera_problems.push('createScene().update(t, dt) is not a function (scene will be static)');
+
+ info.stage = 'loads';
+ const tLd = performance.now();
+ info.load_wait = await waitForLoads(manager, LOAD_IDLE_TIMEOUT_MS);
+ info.timings_ms.loads = Math.round(performance.now() - tLd);
+ if (info.load_wait === 'timeout') state.hostWarnings.push('asset loads still pending after timeout');
+
+ info.stage = 'first_update';
+ if (state.update) state.update(0, 0);
+ state.simTime = 0;
+ state.scene.updateMatrixWorld(true);
+ state.booted = true;
+ info.ok = cameras.length > 0;
+ info.stage = 'ready';
+ } catch (e) {
+ info.error = formatError(e);
+ }
+ info.timings_ms.total = Math.round(performance.now() - t0);
+ info.raf_calls = state.rafCalls;
+ info.load_errors = state.loadErrors.slice();
+ info.host_warnings = state.hostWarnings.slice();
+ return info;
+}
+
+function formatError(e) {
+ if (!e) return 'unknown error';
+ const msg = String(e.message || e);
+ const stack = String(e.stack || '').split('\n').slice(0, 6).join('\n');
+ return stack && stack.includes(msg) ? stack : `${msg}\n${stack}`;
+}
+
+function buildCamera(spec) {
+ const aspect = state.width / state.height;
+ if (!state.fullBox) { const c = sceneCensus(state.scene, THREE); state.fullBox = c.bbox; state.contentBox = c.content_bbox; }
+ const fb = state.fullBox;
+ let farCorner = 1000;
+ if (fb) {
+ farCorner = 0;
+ for (const x of [fb.min[0], fb.max[0]]) for (const y of [fb.min[1], fb.max[1]]) for (const z of [fb.min[2], fb.max[2]]) {
+ farCorner = Math.max(farCorner, Math.hypot(x - spec.position[0], y - spec.position[1], z - spec.position[2]));
+ }
+ }
+ const far = Number.isFinite(spec.far) ? spec.far : Math.max(1000, farCorner * 1.25 + 10);
+ const near = Number.isFinite(spec.near) ? spec.near : Math.max(0.05, Math.min(0.5, far / 20000));
+ const cam = new THREE.PerspectiveCamera(spec.fov || 50, aspect, near, far);
+ cam.position.set(...spec.position);
+ cam.lookAt(...spec.lookAt);
+ cam.updateMatrixWorld(true);
+ cam.updateProjectionMatrix();
+ return cam;
+}
+
+/** Advance the simulation deterministically to time t (fixed steps). */
+function advanceTo(t) {
+ if (!state.update) return;
+ if (t < state.simTime - 1e-9) throw new Error(`cannot rewind time: at ${state.simTime}, asked ${t}`);
+ let steps = 0;
+ while (state.simTime + FIXED_DT <= t + 1e-9) {
+ state.simTime += FIXED_DT;
+ state.update(state.simTime, FIXED_DT);
+ steps += 1;
+ if (steps > 100000) throw new Error('too many update steps');
+ }
+ const rem = t - state.simTime;
+ if (rem > 1e-6) {
+ state.simTime = t;
+ state.update(t, rem);
+ }
+}
+
+function renderOnce(cam) {
+ state.renderer.render(state.scene, cam);
+ try { const gl = state.renderer.getContext(); if (gl && gl.finish) gl.finish(); } catch (e) { /* ignore */ }
+}
+
+/** Render camera spec at time t; returns {dataUrl, ms}. */
+function renderAt(spec, t, opts = {}) {
+ if (!state.booted) throw new Error('host not booted');
+ advanceTo(t);
+ state.scene.updateMatrixWorld(true);
+ const cam = buildCamera(spec);
+ const t0 = performance.now();
+ const savedFog = state.scene.fog;
+ if (spec.noFog) state.scene.fog = null; // overview rig: structure over atmosphere
+ const undo = opts.stripCustom ? stripCustomShaders(state.scene, THREE) : null;
+ try {
+ renderOnce(cam);
+ } finally {
+ state.scene.fog = savedFog;
+ if (undo) undo();
+ }
+ const ms = Math.round(performance.now() - t0);
+ return { dataUrl: state.canvas.toDataURL('image/png'), ms, sim_time: state.simTime };
+}
+
+/** Camera instruments: near geometry + frame luminance stats (renders). */
+function cameraChecks(spec) {
+ const cam = buildCamera(spec);
+ state.scene.updateMatrixWorld(true);
+ const near = nearGeometry(state.scene, cam, THREE);
+ renderOnce(cam);
+ const stats = frameStats(state.canvas);
+ return { name: spec.name, ...near, ...stats };
+}
+
+/** Force-compile every material as seen from spec (or the first camera). */
+function compileAll(spec) {
+ const cam = buildCamera(spec || state.cameras[0] || { position: [10, 10, 10], lookAt: [0, 0, 0], fov: 50 });
+ captureMaterialSources(state.scene, THREE);
+ const t0 = performance.now();
+ state.renderer.compile(state.scene, cam);
+ renderOnce(cam);
+ // shadow + depth programs compile lazily; a second frame from another spot
+ if (state.cameras.length > 1) renderOnce(buildCamera(state.cameras[state.cameras.length - 1]));
+ const ms = Math.round(performance.now() - t0);
+ attributeErrors(state.shaderErrors);
+ const programs = state.renderer.info.programs ? state.renderer.info.programs.length : null;
+ return { compile_ms: ms, programs, shader_errors: state.shaderErrors.slice(), material_audit: materialAudit(state.scene, THREE), custom_materials: captured.length };
+}
+
+/** Measure update+render throughput over ~seconds (advances sim time). */
+function fps(seconds, spec) {
+ const cam = buildCamera(spec || state.cameras[0]);
+ const deadline = performance.now() + seconds * 1000;
+ let frames = 0;
+ const t0 = performance.now();
+ while (performance.now() < deadline) {
+ state.simTime += FIXED_DT;
+ if (state.update) state.update(state.simTime, FIXED_DT);
+ state.renderer.render(state.scene, cam);
+ frames += 1;
+ }
+ try { state.renderer.getContext().finish(); } catch (e) { /* ignore */ }
+ const elapsed = (performance.now() - t0) / 1000;
+ const r = state.renderer.info.render;
+ return { fps: frames / Math.max(elapsed, 1e-3), frames, seconds: elapsed, draw_calls: r.calls, triangles: r.triangles };
+}
+
+function census() {
+ const c = sceneCensus(state.scene, THREE);
+ state.contentBox = c.content_bbox;
+ state.fullBox = c.bbox;
+ c.cameras = state.cameras.length;
+ c.raf_calls = state.rafCalls;
+ return c;
+}
+
+window.__c3v = {
+ boot,
+ renderAt,
+ cameraChecks,
+ compileAll,
+ census,
+ fps,
+ setViewport(w, h) { state.width = w; state.height = h; state.renderer.setSize(w, h, false); },
+ shaderErrors: () => state.shaderErrors.slice(),
+ loadErrors: () => state.loadErrors.slice(),
+ cameras: () => state.cameras.slice(),
+ simTime: () => state.simTime,
+ THREE,
+ get scene() { return state.scene; },
+};
+window.__c3v_ready = true;
diff --git a/harness/runtime_js/lib/stack.mjs b/harness/runtime_js/lib/stack.mjs
new file mode 100644
index 00000000..d2f339b1
--- /dev/null
+++ b/harness/runtime_js/lib/stack.mjs
@@ -0,0 +1,64 @@
+// Turn a JS Error into a structured, workspace-relative error record so the
+// python side can route "file:line" to the repair agent.
+//
+// import { errorRecord } from './stack.mjs';
+// errorRecord(err, wsDir) -> { type, message, file, line, column, frames: [{file,line,column,fn}], stack }
+
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const FRAME_RE = /^\s*at\s+(?:(.*?)\s+\()?((?:file:\/\/|\/|[A-Za-z]:\\)[^:)]+):(\d+):(\d+)\)?\s*$/;
+
+function relativeTo(file, wsDir) {
+ let p = file;
+ if (p.startsWith('file://')) {
+ try {
+ p = fileURLToPath(p);
+ } catch (_e) {
+ return file;
+ }
+ }
+ if (wsDir) {
+ const rel = path.relative(wsDir, p);
+ if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) return rel;
+ }
+ return p;
+}
+
+/** Parse V8 stack frames into {file,line,column,fn}, workspace-relative where possible. */
+export function parseFrames(stack, wsDir, maxFrames = 12) {
+ const frames = [];
+ for (const line of String(stack || '').split('\n')) {
+ const m = FRAME_RE.exec(line);
+ if (!m) continue;
+ frames.push({ fn: m[1] || '', file: relativeTo(m[2], wsDir), line: Number(m[3]), column: Number(m[4]) });
+ if (frames.length >= maxFrames) break;
+ }
+ return frames;
+}
+
+/** Pick the first frame that lives inside the workspace's src/ (the agent's code). */
+function firstSrcFrame(frames) {
+ return frames.find((f) => !path.isAbsolute(f.file) && !f.file.startsWith('node:')) || null;
+}
+
+/** Structured record for an exception (SyntaxError from node has no src frame: parse its message). */
+export function errorRecord(err, wsDir) {
+ const e = err instanceof Error ? err : new Error(String(err));
+ const frames = parseFrames(e.stack, wsDir);
+ let src = firstSrcFrame(frames);
+ // Node reports ESM syntax errors as "file:///abs/path.js:LINE\n<code>\n ^^^\nSyntaxError: ..."
+ if (!src && e.stack) {
+ const m = /^(file:\/\/\S+?|\/\S+?):(\d+)\s*$/m.exec(e.stack);
+ if (m) src = { fn: '', file: relativeTo(m[1], wsDir), line: Number(m[2]), column: 0 };
+ }
+ return {
+ type: e.name || e.constructor.name || 'Error',
+ message: e.message,
+ file: src ? src.file : '',
+ line: src ? src.line : null,
+ column: src ? src.column : null,
+ frames,
+ stack: String(e.stack || '').split('\n').slice(0, 20).join('\n'),
+ };
+}
diff --git a/harness/runtime_js/lib/syntax_check.mjs b/harness/runtime_js/lib/syntax_check.mjs
new file mode 100644
index 00000000..000eef16
--- /dev/null
+++ b/harness/runtime_js/lib/syntax_check.mjs
@@ -0,0 +1,45 @@
+// Locate ESM syntax errors file-by-file. V8 SyntaxErrors thrown by a dynamic
+// import() carry no file/line, so we re-check each candidate source file with
+// `node --input-type=module --check` (stdin) and parse "[stdin]:LINE".
+//
+// import { checkSyntax, findSyntaxError } from './syntax_check.mjs';
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { spawnSync } from 'node:child_process';
+
+/** Check one file; returns null when it parses, else {file, line, message}. */
+export function checkSyntax(file) {
+ const src = fs.readFileSync(file);
+ const r = spawnSync(process.execPath, ['--input-type=module', '--check'], { input: src, encoding: 'utf8', timeout: 20000 });
+ if (r.status === 0) return null;
+ const err = r.stderr || '';
+ const m = /\[stdin\]:(\d+)/.exec(err);
+ const msg = (/^(SyntaxError:.*)$/m.exec(err) || [])[1] || err.trim().split('\n').pop() || 'syntax error';
+ return { file, line: m ? Number(m[1]) : null, message: msg };
+}
+
+/** Recursively list *.js / *.mjs under dir (skipping node_modules). */
+export function listJsFiles(dir) {
+ const out = [];
+ if (!fs.existsSync(dir)) return out;
+ const walk = (d) => {
+ for (const ent of fs.readdirSync(d, { withFileTypes: true })) {
+ if (ent.name === 'node_modules' || ent.name.startsWith('.')) continue;
+ const p = path.join(d, ent.name);
+ if (ent.isDirectory()) walk(p);
+ else if (/\.(m?js)$/.test(ent.name)) out.push(p);
+ }
+ };
+ walk(dir);
+ return out.sort();
+}
+
+/** First file under srcDir that fails to parse, or null. */
+export function findSyntaxError(srcDir) {
+ for (const f of listJsFiles(srcDir)) {
+ const r = checkSyntax(f);
+ if (r) return r;
+ }
+ return null;
+}
diff --git a/harness/runtime_js/package-lock.json b/harness/runtime_js/package-lock.json
new file mode 100644
index 00000000..c9c18c5d
--- /dev/null
+++ b/harness/runtime_js/package-lock.json
@@ -0,0 +1,1152 @@
+{
+ "name": "codeverse-runtime-js",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "codeverse-runtime-js",
+ "version": "0.1.0",
+ "dependencies": {
+ "puppeteer": "^24.43.1",
+ "three": "^0.182.0",
+ "three-mesh-bvh": "^0.9.0"
+ }
+ },
+ "node_modules/@babel/code-frame": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",
+ "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/helper-validator-identifier": "^7.29.7",
+ "js-tokens": "^4.0.0",
+ "picocolors": "^1.1.1"
+ },
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@babel/helper-validator-identifier": {
+ "version": "7.29.7",
+ "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
+ "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.9.0"
+ }
+ },
+ "node_modules/@puppeteer/browsers": {
+ "version": "2.13.2",
+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.13.2.tgz",
+ "integrity": "sha512-5EUZSUIc37H6aIXyWO0Z4y8NlF8NnjgmqeQgOGiswAU7pY0HOo16ho4+alIWmSfdZnjqBRawMsP3I5YqLSn6kw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "extract-zip": "^2.0.1",
+ "progress": "^2.0.3",
+ "proxy-agent": "^6.5.0",
+ "semver": "^7.7.4",
+ "tar-fs": "^3.1.1",
+ "yargs": "^17.7.2"
+ },
+ "bin": {
+ "browsers": "lib/cjs/main-cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@tootallnate/quickjs-emscripten": {
+ "version": "0.23.0",
+ "resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz",
+ "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "26.2.0",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz",
+ "integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "undici-types": "~8.3.0"
+ }
+ },
+ "node_modules/@types/yauzl": {
+ "version": "2.10.3",
+ "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz",
+ "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/agent-base": {
+ "version": "7.1.4",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
+ "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/argparse": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
+ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
+ "license": "Python-2.0"
+ },
+ "node_modules/ast-types": {
+ "version": "0.13.4",
+ "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz",
+ "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/b4a": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.1.tgz",
+ "integrity": "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "react-native-b4a": "*"
+ },
+ "peerDependenciesMeta": {
+ "react-native-b4a": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-events": {
+ "version": "2.9.1",
+ "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.1.tgz",
+ "integrity": "sha512-Z0oHEHAFDZkffN8Qc39zNZjQlMDkPJRyyyZieU1VH7u8c5S+qHZ2S8ixdKIAxEjfHO7FJxXmJWgteOghVanIsg==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "bare-abort-controller": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-fs": {
+ "version": "4.8.0",
+ "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.0.tgz",
+ "integrity": "sha512-fM+MhCvdQhZ7NV6S95a07gPSqjIYKn6mFaXfx266wN3ajZGl/+1AzH+ubkXQ0fFZvOe2nk9VHkzdYkQE5zMV3Q==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.5.4",
+ "bare-path": "^3.0.0",
+ "bare-stream": "^2.6.4",
+ "bare-url": "^2.2.2",
+ "fast-fifo": "^1.3.2"
+ },
+ "engines": {
+ "bare": ">=1.28.0"
+ },
+ "peerDependencies": {
+ "bare-buffer": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-buffer": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-path": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.1.tgz",
+ "integrity": "sha512-JprUlveX3QjApC1cTpsUOiscADftCGVWkzitbHsRqv84hzYwYHw2mbluddsq5TvI8mH/8Ov1f4BiMAdcB0oYnQ==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/bare-stream": {
+ "version": "2.13.3",
+ "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.3.tgz",
+ "integrity": "sha512-Kc+brLqvEqGkjyfiwJmImAOqLZL7OsoLKuavx+hJjgVV3nLTOjloJyPMFxjUPerGGHrNH0fLU06jjykMLWrERQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.8.1",
+ "streamx": "^2.25.0",
+ "teex": "^1.0.1"
+ },
+ "peerDependencies": {
+ "bare-abort-controller": "*",
+ "bare-buffer": "*",
+ "bare-events": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ },
+ "bare-buffer": {
+ "optional": true
+ },
+ "bare-events": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-url": {
+ "version": "2.5.2",
+ "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.2.tgz",
+ "integrity": "sha512-L13PCJzKG8RGvx8V1/DdMi12ERhC3tprr7/8a94BxpmnRsFqxh5XZNdhtMxu5HPkRshYOOWRGY8lDP7ZhpG9Cg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-path": "^3.0.0"
+ }
+ },
+ "node_modules/basic-ftp": {
+ "version": "5.3.1",
+ "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.3.1.tgz",
+ "integrity": "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/buffer-crc32": {
+ "version": "0.2.13",
+ "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
+ "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==",
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/callsites": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
+ "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/chromium-bidi": {
+ "version": "14.0.0",
+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-14.0.0.tgz",
+ "integrity": "sha512-9gYlLtS6tStdRWzrtXaTMnqcM4dudNegMXJxkR0I/CXObHalYeYcAMPrL19eroNZHtJ8DQmu1E+ZNOYu/IXMXw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "mitt": "^3.0.1",
+ "zod": "^3.24.1"
+ },
+ "peerDependencies": {
+ "devtools-protocol": "*"
+ }
+ },
+ "node_modules/cliui": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
+ "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
+ "license": "ISC",
+ "dependencies": {
+ "string-width": "^4.2.0",
+ "strip-ansi": "^6.0.1",
+ "wrap-ansi": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "~1.1.4"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ }
+ },
+ "node_modules/color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "license": "MIT"
+ },
+ "node_modules/cosmiconfig": {
+ "version": "9.0.2",
+ "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.2.tgz",
+ "integrity": "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg==",
+ "license": "MIT",
+ "dependencies": {
+ "env-paths": "^2.2.1",
+ "import-fresh": "^3.3.0",
+ "js-yaml": "^4.1.0",
+ "parse-json": "^5.2.0"
+ },
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/d-fischer"
+ },
+ "peerDependencies": {
+ "typescript": ">=4.9.5"
+ },
+ "peerDependenciesMeta": {
+ "typescript": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/data-uri-to-buffer": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz",
+ "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/degenerator": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz",
+ "integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ast-types": "^0.13.4",
+ "escodegen": "^2.1.0",
+ "esprima": "^4.0.1"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/devtools-protocol": {
+ "version": "0.0.1608973",
+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1608973.tgz",
+ "integrity": "sha512-Tpm17fxYzt+J7VrGdc1k8YdRqS3YV7se/M6KeemEqvUbq/n7At1rWVuXMxQgpWkdwSdIEKYbU//Bve+Shm4YNQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "license": "MIT"
+ },
+ "node_modules/end-of-stream": {
+ "version": "1.4.5",
+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
+ "license": "MIT",
+ "dependencies": {
+ "once": "^1.4.0"
+ }
+ },
+ "node_modules/env-paths": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/env-paths/-/env-paths-2.2.1.tgz",
+ "integrity": "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/error-ex": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.4.tgz",
+ "integrity": "sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==",
+ "license": "MIT",
+ "dependencies": {
+ "is-arrayish": "^0.2.1"
+ }
+ },
+ "node_modules/escalade": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/escodegen": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz",
+ "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "esprima": "^4.0.1",
+ "estraverse": "^5.2.0",
+ "esutils": "^2.0.2"
+ },
+ "bin": {
+ "escodegen": "bin/escodegen.js",
+ "esgenerate": "bin/esgenerate.js"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "optionalDependencies": {
+ "source-map": "~0.6.1"
+ }
+ },
+ "node_modules/esprima": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
+ "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
+ "license": "BSD-2-Clause",
+ "bin": {
+ "esparse": "bin/esparse.js",
+ "esvalidate": "bin/esvalidate.js"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/estraverse": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/esutils": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/events-universal": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
+ "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.7.0"
+ }
+ },
+ "node_modules/extract-zip": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz",
+ "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "debug": "^4.1.1",
+ "get-stream": "^5.1.0",
+ "yauzl": "^2.10.0"
+ },
+ "bin": {
+ "extract-zip": "cli.js"
+ },
+ "engines": {
+ "node": ">= 10.17.0"
+ },
+ "optionalDependencies": {
+ "@types/yauzl": "^2.9.1"
+ }
+ },
+ "node_modules/fast-fifo": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
+ "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",
+ "license": "MIT"
+ },
+ "node_modules/fd-slicer": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz",
+ "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==",
+ "license": "MIT",
+ "dependencies": {
+ "pend": "~1.2.0"
+ }
+ },
+ "node_modules/get-caller-file": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
+ "license": "ISC",
+ "engines": {
+ "node": "6.* || 8.* || >= 10.*"
+ }
+ },
+ "node_modules/get-stream": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
+ "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",
+ "license": "MIT",
+ "dependencies": {
+ "pump": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/get-uri": {
+ "version": "6.0.5",
+ "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.5.tgz",
+ "integrity": "sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==",
+ "license": "MIT",
+ "dependencies": {
+ "basic-ftp": "^5.0.2",
+ "data-uri-to-buffer": "^6.0.2",
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/http-proxy-agent": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
+ "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.0",
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/https-proxy-agent": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/import-fresh": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
+ "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==",
+ "license": "MIT",
+ "dependencies": {
+ "parent-module": "^1.0.0",
+ "resolve-from": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/ip-address": {
+ "version": "10.5.0",
+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.5.0.tgz",
+ "integrity": "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/is-arrayish": {
+ "version": "0.2.1",
+ "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz",
+ "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==",
+ "license": "MIT"
+ },
+ "node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/js-tokens": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
+ "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
+ "license": "MIT"
+ },
+ "node_modules/js-yaml": {
+ "version": "4.3.1",
+ "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",
+ "integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/puzrin"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/nodeca"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "argparse": "^2.0.1"
+ },
+ "bin": {
+ "js-yaml": "bin/js-yaml.js"
+ }
+ },
+ "node_modules/json-parse-even-better-errors": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz",
+ "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==",
+ "license": "MIT"
+ },
+ "node_modules/lines-and-columns": {
+ "version": "1.2.4",
+ "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
+ "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==",
+ "license": "MIT"
+ },
+ "node_modules/lru-cache": {
+ "version": "7.18.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz",
+ "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/mitt": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
+ "license": "MIT"
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/netmask": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.1.1.tgz",
+ "integrity": "sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/pac-proxy-agent": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz",
+ "integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==",
+ "license": "MIT",
+ "dependencies": {
+ "@tootallnate/quickjs-emscripten": "^0.23.0",
+ "agent-base": "^7.1.2",
+ "debug": "^4.3.4",
+ "get-uri": "^6.0.1",
+ "http-proxy-agent": "^7.0.0",
+ "https-proxy-agent": "^7.0.6",
+ "pac-resolver": "^7.0.1",
+ "socks-proxy-agent": "^8.0.5"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/pac-resolver": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz",
+ "integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==",
+ "license": "MIT",
+ "dependencies": {
+ "degenerator": "^5.0.0",
+ "netmask": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/parent-module": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
+ "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==",
+ "license": "MIT",
+ "dependencies": {
+ "callsites": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/parse-json": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz",
+ "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/code-frame": "^7.0.0",
+ "error-ex": "^1.3.1",
+ "json-parse-even-better-errors": "^2.3.0",
+ "lines-and-columns": "^1.1.6"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/pend": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
+ "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",
+ "license": "MIT"
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "license": "ISC"
+ },
+ "node_modules/progress": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
+ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/proxy-agent": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz",
+ "integrity": "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "^4.3.4",
+ "http-proxy-agent": "^7.0.1",
+ "https-proxy-agent": "^7.0.6",
+ "lru-cache": "^7.14.1",
+ "pac-proxy-agent": "^7.1.0",
+ "proxy-from-env": "^1.1.0",
+ "socks-proxy-agent": "^8.0.5"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/proxy-from-env": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
+ "license": "MIT"
+ },
+ "node_modules/pump": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
+ "license": "MIT",
+ "dependencies": {
+ "end-of-stream": "^1.1.0",
+ "once": "^1.3.1"
+ }
+ },
+ "node_modules/puppeteer": {
+ "version": "24.43.1",
+ "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-24.43.1.tgz",
+ "integrity": "sha512-/FSOViCrqRdb1HDocpsM9Z1giA71gTQPUt3SpHGVRALKAy/rJr1fLFYZW9F23qPxqVxTHQnbh/5B5opJST3kAw==",
+ "hasInstallScript": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@puppeteer/browsers": "2.13.2",
+ "chromium-bidi": "14.0.0",
+ "cosmiconfig": "^9.0.0",
+ "devtools-protocol": "0.0.1608973",
+ "puppeteer-core": "24.43.1",
+ "typed-query-selector": "^2.12.2"
+ },
+ "bin": {
+ "puppeteer": "lib/cjs/puppeteer/node/cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/puppeteer-core": {
+ "version": "24.43.1",
+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-24.43.1.tgz",
+ "integrity": "sha512-T5ScUMAsmhdNbgDR41AGESYeS6V9MSgetkSnVhhW+gXvzC42VesKCn5ld87gAZDJ6vLHL9GkRvY9WtQWSnwFbw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@puppeteer/browsers": "2.13.2",
+ "chromium-bidi": "14.0.0",
+ "debug": "^4.4.3",
+ "devtools-protocol": "0.0.1608973",
+ "typed-query-selector": "^2.12.2",
+ "webdriver-bidi-protocol": "0.4.1",
+ "ws": "^8.20.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/require-directory": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/resolve-from": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
+ "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/smart-buffer": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
+ "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6.0.0",
+ "npm": ">= 3.0.0"
+ }
+ },
+ "node_modules/socks": {
+ "version": "2.8.9",
+ "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.9.tgz",
+ "integrity": "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw==",
+ "license": "MIT",
+ "dependencies": {
+ "ip-address": "^10.1.1",
+ "smart-buffer": "^4.2.0"
+ },
+ "engines": {
+ "node": ">= 10.0.0",
+ "npm": ">= 3.0.0"
+ }
+ },
+ "node_modules/socks-proxy-agent": {
+ "version": "8.0.5",
+ "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz",
+ "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "^4.3.4",
+ "socks": "^2.8.3"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "license": "BSD-3-Clause",
+ "optional": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/streamx": {
+ "version": "2.28.0",
+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.0.tgz",
+ "integrity": "sha512-1Yowhzjf0ivGMrTIkY9hav5TxobO9qIVqUE41fiCGMGgc3CLlf4MY+9AHmZqBWgDTue0fY9zWjYFVyf6Diuobw==",
+ "license": "MIT",
+ "dependencies": {
+ "events-universal": "^1.0.0",
+ "fast-fifo": "^1.3.2",
+ "text-decoder": "^1.1.0"
+ }
+ },
+ "node_modules/string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/tar-fs": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.3.tgz",
+ "integrity": "sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "pump": "^3.0.0",
+ "tar-stream": "^3.1.5"
+ },
+ "optionalDependencies": {
+ "bare-fs": "^4.0.1",
+ "bare-path": "^3.0.0"
+ }
+ },
+ "node_modules/tar-stream": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.0.tgz",
+ "integrity": "sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg==",
+ "license": "MIT",
+ "dependencies": {
+ "b4a": "^1.6.4",
+ "bare-fs": "^4.5.5",
+ "fast-fifo": "^1.2.0",
+ "streamx": "^2.15.0"
+ }
+ },
+ "node_modules/teex": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",
+ "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==",
+ "license": "MIT",
+ "dependencies": {
+ "streamx": "^2.12.5"
+ }
+ },
+ "node_modules/text-decoder": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz",
+ "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.6.4"
+ }
+ },
+ "node_modules/three": {
+ "version": "0.182.0",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.182.0.tgz",
+ "integrity": "sha512-GbHabT+Irv+ihI1/f5kIIsZ+Ef9Sl5A1Y7imvS5RQjWgtTPfPnZ43JmlYI7NtCRDK9zir20lQpfg8/9Yd02OvQ==",
+ "license": "MIT"
+ },
+ "node_modules/three-mesh-bvh": {
+ "version": "0.9.14",
+ "resolved": "https://registry.npmjs.org/three-mesh-bvh/-/three-mesh-bvh-0.9.14.tgz",
+ "integrity": "sha512-xJzfUXnLYjgw5tRKGxjfJW3Pcx0IbwNskvpdwRryhK07SYrKrYB4W8zAaPxu784gK7G4lCBgG+vfG3YeYn95kg==",
+ "license": "MIT",
+ "peerDependencies": {
+ "three": ">= 0.159.0"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "license": "0BSD"
+ },
+ "node_modules/typed-query-selector": {
+ "version": "2.12.2",
+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.2.tgz",
+ "integrity": "sha512-EOPFbyIub4ngnEdqi2yOcNeDLaX/0jcE1JoAXQDDMIthap7FoN795lc/SHfIq2d416VufXpM8z/lD+WRm2gfOQ==",
+ "license": "MIT"
+ },
+ "node_modules/undici-types": {
+ "version": "8.3.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
+ "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/webdriver-bidi-protocol": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.1.tgz",
+ "integrity": "sha512-ARrjNjtWRRs2w4Tk7nqrf2gBI0QXWuOmMCx2hU+1jUt6d00MjMxURrhxhGbrsoiZKJrhTSTzbIrc554iKI10qw==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/wrap-ansi": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^4.0.0",
+ "string-width": "^4.1.0",
+ "strip-ansi": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+ }
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "license": "ISC"
+ },
+ "node_modules/ws": {
+ "version": "8.21.3",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
+ "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/y18n": {
+ "version": "5.0.8",
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/yargs": {
+ "version": "17.7.3",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz",
+ "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==",
+ "license": "MIT",
+ "dependencies": {
+ "cliui": "^8.0.1",
+ "escalade": "^3.1.1",
+ "get-caller-file": "^2.0.5",
+ "require-directory": "^2.1.1",
+ "string-width": "^4.2.3",
+ "y18n": "^5.0.5",
+ "yargs-parser": "^21.1.1"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/yargs-parser": {
+ "version": "21.1.1",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
+ "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/yauzl": {
+ "version": "2.10.0",
+ "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz",
+ "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer-crc32": "~0.2.3",
+ "fd-slicer": "~1.1.0"
+ }
+ },
+ "node_modules/zod": {
+ "version": "3.25.76",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ }
+ }
+}
diff --git a/harness/runtime_js/package.json b/harness/runtime_js/package.json
new file mode 100644
index 00000000..aa9322bf
--- /dev/null
+++ b/harness/runtime_js/package.json
@@ -0,0 +1,12 @@
+{
+ "name": "codeverse-runtime-js",
+ "private": true,
+ "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",
+ "dependencies": {
+ "three": "^0.182.0",
+ "puppeteer": "^24.43.1",
+ "three-mesh-bvh": "^0.9.0"
+ }
+}
diff --git a/harness/runtime_js/probe_scene.mjs b/harness/runtime_js/probe_scene.mjs
new file mode 100644
index 00000000..dd8655d5
--- /dev/null
+++ b/harness/runtime_js/probe_scene.mjs
@@ -0,0 +1,67 @@
+#!/usr/bin/env node
+/**
+ * Fast import-only probe of a scene_threejs workspace (the scene 'build' gate):
+ * does src/scene.js load, does createScene() return {scene, cameras, update},
+ * are cameras valid, does update(t, dt) run — plus the census and all
+ * console/page/shader errors. No screenshots.
+ *
+ * node probe_scene.mjs --ws <ws> [--scene src/scene.js] [--gpu auto] [--timeout-ms 60000] [--out probe.json]
+ * Last stdout line = JSON {ok, boot, census, console_errors, shader_errors, ...}.
+ */
+
+import path from 'node:path';
+import { armWatchdog, fail, finish, parseCli, writeJson } from './lib/cli.mjs';
+import { errorSummary, openHost } from './lib/host_page.mjs';
+
+const args = parseCli({
+ ws: {}, out: {}, gpu: { default: process.env.C3V_RENDER_GPU || 'auto' }, 'timeout-ms': { default: '60000' },
+ 'update-steps': { default: '10' }, scene: { default: 'src/scene.js' },
+});
+
+async function main() {
+ if (!args.ws) throw new Error('--ws is required');
+ const watchdog = armWatchdog(parseInt(args['timeout-ms'], 10));
+ const t0 = Date.now();
+ let host;
+ try {
+ host = await openHost(args.ws, { width: 320, height: 180, gpu: args.gpu, sceneRel: args.scene.replace(/^\.?\//, '') });
+ } catch (e) {
+ return fail(`host failed: ${e.message}`);
+ }
+ const { page, boot } = host;
+ const result = { ok: false, renderer: boot.renderer || host.renderer, gpu: host.gpu, boot, census: null, update_ok: null, update_error: '', shader_errors: [] };
+ try {
+ if (boot.ok) {
+ result.census = await page.evaluate(() => window.__c3v.census());
+ // exercise update() for a few fixed steps and one tiny render (lazy programs compile)
+ const steps = parseInt(args['update-steps'], 10);
+ const upd = await page.evaluate((n) => {
+ try {
+ const cam = window.__c3v.cameras()[0];
+ const r = window.__c3v.renderAt(cam, n / 30);
+ return { ok: true, sim_time: r.sim_time, ms: r.ms };
+ } catch (e) {
+ return { ok: false, error: String((e && e.stack) || e).slice(0, 800) };
+ }
+ }, steps);
+ result.update_ok = upd.ok;
+ result.update_error = upd.error || '';
+ result.first_render_ms = upd.ms;
+ const frame = await page.evaluate(() => { const c = window.__c3v.cameras()[0]; return window.__c3v.cameraChecks(c); });
+ result.first_camera = frame;
+ }
+ result.shader_errors = (await page.evaluate(() => window.__c3v.shaderErrors())).map(({ _key, ...e }) => e);
+ Object.assign(result, errorSummary(host.errors, boot));
+ result.ok = boot.ok && result.update_ok === true && result.console_errors.length === 0 && result.shader_errors.length === 0;
+ result.duration_ms = Date.now() - t0;
+ clearTimeout(watchdog);
+ await host.close();
+ if (args.out) writeJson(path.resolve(args.out), result);
+ return finish(result, result.ok ? 0 : 1);
+ } catch (e) {
+ await host.close();
+ return fail(`probe failed: ${e.message}`);
+ }
+}
+
+main().catch((e) => fail(e.stack || String(e)));
diff --git a/harness/runtime_js/render_glb.mjs b/harness/runtime_js/render_glb.mjs
new file mode 100644
index 00000000..02c3212b
--- /dev/null
+++ b/harness/runtime_js/render_glb.mjs
@@ -0,0 +1,152 @@
+#!/usr/bin/env node
+// Render a GLB from fixed views with headless Chrome (GPU when available).
+//
+// node runtime_js/render_glb.mjs --glb <path> --out <dir> --views '<json [{name,azimuth,elevation}]>'
+// [--mode shaded|wire|normals|silhouette|clay] [--width 768] [--height 768]
+// [--isolate Name1,Name2] [--explode 0.3] [--background studio|white|transparent]
+// [--anim-time t] [--gpu auto|on|off] [--shadow 1|0] [--fill 0.85] [--timeout-s 240]
+//
+// 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.
+
+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');
+
+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' },
+ },
+ });
+ 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('|')}`);
+ const views = JSON.parse(values.views);
+ if (!Array.isArray(views) || views.length === 0) throw new Error('--views must be a non-empty JSON list');
+ for (const v of views) {
+ if (typeof v.name !== 'string' || !/^[A-Za-z0-9_\-]+$/.test(v.name)) throw new Error(`bad view name: ${JSON.stringify(v.name)}`);
+ if (typeof v.azimuth !== 'number' || typeof v.elevation !== 'number') throw new Error(`view ${v.name}: azimuth/elevation must be numbers`);
+ }
+ return {
+ glb: path.resolve(values.glb),
+ out: path.resolve(values.out),
+ views,
+ mode: values.mode,
+ width: Number(values.width),
+ height: Number(values.height),
+ isolate: values.isolate ? values.isolate.split(',').map((s) => s.trim()).filter(Boolean) : [],
+ explode: Number(values.explode) || 0,
+ background: values.background,
+ animTime: values['anim-time'] != null ? Number(values['anim-time']) : null,
+ gpu: values.gpu,
+ shadow: values.shadow !== '0',
+ fill: Number(values.fill) || 0.85,
+ timeoutMs: Number(values['timeout-s']) * 1000,
+ };
+}
+
+function pageHtml(cfg) {
+ 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';
+window.__c3v_result = null;
+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();
+ if (!fs.existsSync(cfg.glb)) throw new Error(`GLB not found: ${cfg.glb}`);
+ fs.mkdirSync(cfg.out, { recursive: true });
+
+ const srv = await serveDirs({ root: path.dirname(cfg.glb), routes: { '/__render.html': { body: pageHtml(cfg) } } });
+ const consoleErrors = [];
+ let browser = null;
+ let gpu = false;
+ let launchRenderer = '';
+ const timing = {};
+ try {
+ const launched = await launchBrowser({ gpu: cfg.gpu });
+ browser = launched.browser;
+ gpu = launched.gpu;
+ launchRenderer = launched.renderer;
+ timing.launch_ms = Date.now() - t0;
+
+ const page = await browser.newPage();
+ await page.setViewport({ width: cfg.width, height: cfg.height, deviceScaleFactor: 1 });
+ page.on('console', (msg) => {
+ if (msg.type() === 'error' || msg.type() === 'warning') consoleErrors.push(`${msg.type()}: ${msg.text()}`);
+ });
+ page.on('pageerror', (e) => consoleErrors.push(`pageerror: ${e.message}`));
+ await page.goto(srv.url('/__render.html'), { waitUntil: 'load', timeout: cfg.timeoutMs });
+ await page.waitForFunction('window.__c3v_result !== null', { timeout: cfg.timeoutMs, polling: 100 });
+ const result = await page.evaluate(() => window.__c3v_result);
+ if (!result || !result.ok) {
+ const err = new Error(result ? result.error : 'render produced no result');
+ err.details = { stack: result && result.stack, console: consoleErrors };
+ throw err;
+ }
+ const views = [];
+ for (const v of result.views) {
+ const file = path.join(cfg.out, `view_${v.name}.png`);
+ fs.writeFileSync(file, Buffer.from(v.b64, 'base64'));
+ const { b64: _b64, ...meta } = v;
+ views.push({ ...meta, path: file, mode: cfg.mode });
+ }
+ const record = {
+ ok: true,
+ renderer: result.renderer || launchRenderer,
+ gpu,
+ mode: cfg.mode,
+ bbox: result.bbox,
+ views,
+ warnings: result.warnings || [],
+ 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);
+ } finally {
+ if (browser) await browser.close().catch(() => {});
+ await srv.close();
+ }
+}
+
+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);
+});
diff --git a/harness/runtime_js/render_scene.mjs b/harness/runtime_js/render_scene.mjs
new file mode 100644
index 00000000..0ae94953
--- /dev/null
+++ b/harness/runtime_js/render_scene.mjs
@@ -0,0 +1,116 @@
+#!/usr/bin/env node
+/**
+ * Render a scene_threejs workspace: authored cameras + an overview orbit rig,
+ * at one or more animation times, with deterministic instruments.
+ *
+ * node render_scene.mjs --ws <ws> --out <dir> [--cameras authored|<json>]
+ * [--orbit-views '<json list of {name,azimuth,elevation}>'|none]
+ * [--times 0,1.5] [--width 1024] [--height 576] [--gpu auto|on|off]
+ * [--fps-seconds 2] [--timeout-ms 240000]
+ *
+ * Writes PNG per (camera, time), views.json, metrics.json
+ * {console_errors, shader_errors, fps, census, camera_checks, ...}.
+ * Last stdout line = JSON summary. Exit 0 ok, 1 scene failed, 2 driver error.
+ */
+
+import path from 'node:path';
+import { armWatchdog, dataUrlToPng, ensureDir, fail, finish, parseCli, readJsonArg, writeJson } from './lib/cli.mjs';
+import { errorSummary, openHost } from './lib/host_page.mjs';
+import { fitOrbitCameras } from './lib/orbit.mjs';
+
+const args = parseCli({
+ ws: {}, out: {}, cameras: { default: 'authored' }, 'orbit-views': { default: 'none' },
+ times: { default: '0,1.5' }, width: { default: '1024' }, height: { default: '576' },
+ gpu: { default: process.env.C3V_RENDER_GPU || 'auto' }, 'fps-seconds': { default: '2' },
+ 'timeout-ms': { default: '240000' }, 'log-depth': { type: 'boolean', default: false },
+ 'orbit-fog': { type: 'boolean', default: false }, counterfactual: { type: 'boolean', default: false },
+});
+
+function tag(t) {
+ return 't' + t.toFixed(2).replace(/0+$/, '').replace(/\.$/, '').replace('.', 'p');
+}
+
+async function main() {
+ if (!args.ws || !args.out) throw new Error('--ws and --out are required');
+ const width = parseInt(args.width, 10), height = parseInt(args.height, 10);
+ const times = String(args.times).split(',').map((s) => parseFloat(s)).filter((x) => Number.isFinite(x) && x >= 0).sort((a, b) => a - b);
+ if (!times.length) throw new Error('--times must list non-negative numbers');
+ const outDir = ensureDir(path.resolve(args.out));
+ const watchdog = armWatchdog(parseInt(args['timeout-ms'], 10));
+ const t0 = Date.now();
+
+ let host;
+ try {
+ host = await openHost(args.ws, { width, height, gpu: args.gpu, logDepth: args['log-depth'] });
+ } catch (e) {
+ return fail(`host failed: ${e.message}`);
+ }
+ const { page, boot } = host;
+ const metrics = { ok: false, renderer: boot.renderer || host.renderer, gpu: host.gpu, boot, views: [], camera_checks: [], fps: null, census: null, shader_errors: [] };
+ try {
+ if (!boot.ok) {
+ Object.assign(metrics, errorSummary(host.errors, boot));
+ writeJson(path.join(outDir, 'metrics.json'), metrics);
+ writeJson(path.join(outDir, 'views.json'), []);
+ return finish({ ok: false, error: boot.error || 'scene did not boot', stage: boot.stage, out: outDir, ...counts(metrics) }, 1);
+ }
+ metrics.census = await page.evaluate(() => window.__c3v.census());
+
+ // camera list
+ let cams = [];
+ if (args.cameras === 'authored') cams = boot.cameras.map((c) => ({ ...c, kind: 'authored' }));
+ else if (args.cameras !== 'none') cams = (readJsonArg(args.cameras, 'cameras') || []).map((c) => ({ ...c, kind: c.kind || 'authored' }));
+ if (args['orbit-views'] !== 'none') {
+ const views = readJsonArg(args['orbit-views'], 'orbit-views') || [];
+ const bbox = metrics.census.content_bbox || metrics.census.bbox;
+ cams.push(...fitOrbitCameras(bbox, views, { aspect: width / height, groundY: metrics.census.ground_y, noFog: !args['orbit-fog'] }));
+ }
+ const seen = new Set();
+ cams = cams.filter((c) => { const k = c.name; if (seen.has(k)) return false; seen.add(k); return true; });
+ if (!cams.length) throw new Error('no cameras to render (authored list empty and no orbit views)');
+
+ // instruments per camera (at t=0, before any stepping)
+ for (const c of cams) {
+ const chk = await page.evaluate((spec) => window.__c3v.cameraChecks(spec), c);
+ metrics.camera_checks.push({ kind: c.kind, ...chk });
+ }
+ // renders: times ascending (sim time cannot rewind)
+ for (const t of times) {
+ for (const c of cams) {
+ const r = await page.evaluate((spec, tt) => window.__c3v.renderAt(spec, tt), c, t);
+ const file = `${c.name}_${tag(t)}.png`;
+ dataUrlToPng(r.dataUrl, path.join(outDir, file));
+ metrics.views.push({ name: c.name, kind: c.kind, path: file, time_s: t, position: c.position, lookAt: c.lookAt, fov: c.fov, render_ms: r.ms });
+ if (args.counterfactual) {
+ const cf = await page.evaluate((spec, tt) => window.__c3v.renderAt(spec, tt, { stripCustom: true }), c, t);
+ const cfFile = `${c.name}_${tag(t)}_nocustom.png`;
+ dataUrlToPng(cf.dataUrl, path.join(outDir, cfFile));
+ metrics.views.push({ name: `${c.name}_nocustom`, kind: 'counterfactual', path: cfFile, time_s: t, position: c.position, lookAt: c.lookAt, fov: c.fov, render_ms: cf.ms, counterfactual_of: file });
+ }
+ }
+ }
+ const fpsSec = parseFloat(args['fps-seconds']);
+ if (fpsSec > 0) metrics.fps = await page.evaluate((s) => window.__c3v.fps(s), fpsSec);
+ metrics.shader_errors = (await page.evaluate(() => window.__c3v.shaderErrors())).map(({ _key, ...e }) => e);
+ Object.assign(metrics, errorSummary(host.errors, boot));
+ metrics.ok = metrics.console_errors.length === 0 && metrics.shader_errors.length === 0;
+ metrics.duration_ms = Date.now() - t0;
+ writeJson(path.join(outDir, 'metrics.json'), metrics);
+ writeJson(path.join(outDir, 'views.json'), metrics.views);
+ clearTimeout(watchdog);
+ await host.close();
+ return finish({ ok: metrics.ok, out: outDir, n_views: metrics.views.length, renderer: metrics.renderer, gpu: host.gpu, fps: metrics.fps ? +metrics.fps.fps.toFixed(1) : null, duration_ms: metrics.duration_ms, ...counts(metrics) }, metrics.ok ? 0 : 1);
+ } catch (e) {
+ Object.assign(metrics, errorSummary(host.errors, boot));
+ metrics.console_errors.push(`driver: ${e.message}`);
+ writeJson(path.join(outDir, 'metrics.json'), metrics);
+ await host.close();
+ return fail(`render failed: ${e.message}`, { out: outDir });
+ }
+}
+
+function counts(m) {
+ return { console_errors: (m.console_errors || []).length, shader_errors: (m.shader_errors || []).length };
+}
+
+main().catch((e) => fail(e.stack || String(e)));
diff --git a/harness/runtime_js/serve.cjs b/harness/runtime_js/serve.cjs
new file mode 100644
index 00000000..5d06a58a
--- /dev/null
+++ b/harness/runtime_js/serve.cjs
@@ -0,0 +1,151 @@
+// Tiny loopback static server for the headless renderers. Nothing is ever
+// fetched from the internet: `three` and `three/addons/` are served from
+// runtime_js/node_modules through the import map returned by importMapHtml().
+//
+// const { serveDirs, importMapHtml, RUNTIME_MOUNT } = require('./serve.cjs');
+// const srv = await serveDirs({ root: '/path/to/workspace', routes: { '/__page.html': { body, type: 'text/html' } } });
+// srv.base -> 'http://127.0.0.1:PORT'
+// srv.url('/x.glb') -> absolute URL
+// srv.close()
+//
+// runtime_js/ itself is always mounted at RUNTIME_MOUNT ('/__runtime/').
+'use strict';
+
+const fs = require('fs');
+const http = require('http');
+const path = require('path');
+
+const RUNTIME_DIR = __dirname;
+const RUNTIME_MOUNT = '/__runtime/';
+
+const MIME = {
+ '.js': 'text/javascript',
+ '.mjs': 'text/javascript',
+ '.cjs': 'text/javascript',
+ '.json': 'application/json',
+ '.html': 'text/html; charset=utf-8',
+ '.css': 'text/css',
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.webp': 'image/webp',
+ '.gif': 'image/gif',
+ '.svg': 'image/svg+xml',
+ '.glb': 'model/gltf-binary',
+ '.gltf': 'model/gltf+json',
+ '.bin': 'application/octet-stream',
+ '.hdr': 'application/octet-stream',
+ '.exr': 'application/octet-stream',
+ '.ktx2': 'image/ktx2',
+ '.wasm': 'application/wasm',
+ '.txt': 'text/plain',
+ '.glsl': 'text/plain',
+ '.vert': 'text/plain',
+ '.frag': 'text/plain',
+ '.mp4': 'video/mp4',
+ '.webm': 'video/webm',
+ '.mp3': 'audio/mpeg',
+ '.ogg': 'audio/ogg',
+ '.wav': 'audio/wav',
+ '.ttf': 'font/ttf',
+ '.woff': 'font/woff',
+ '.woff2': 'font/woff2',
+};
+
+function mimeFor(file) {
+ return MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
+}
+
+/** Resolve a URL path inside `rootAbs`; null when it escapes the root or is not a file. */
+function resolveInside(rootAbs, relUrlPath) {
+ const abs = path.resolve(rootAbs, '.' + path.posix.normalize('/' + relUrlPath));
+ if (abs !== rootAbs && !abs.startsWith(rootAbs + path.sep)) return null;
+ let st;
+ try {
+ st = fs.statSync(abs);
+ } catch (_e) {
+ return null;
+ }
+ return st.isFile() ? abs : null;
+}
+
+/**
+ * Serve one or more directories on 127.0.0.1:<random port>.
+ * @param {{root?: string, mounts?: Record<string,string>, routes?: Record<string,{body:string|Buffer,type?:string}>, log?: boolean}} opts
+ * root - directory served at '/'
+ * mounts - url prefix ('/name/') -> directory; checked before root. runtime_js is always mounted at RUNTIME_MOUNT.
+ * routes - exact url path -> in-memory response (e.g. a generated HTML page).
+ */
+async function serveDirs(opts = {}) {
+ const root = opts.root ? path.resolve(opts.root) : null;
+ const mounts = { [RUNTIME_MOUNT]: RUNTIME_DIR, ...(opts.mounts || {}) };
+ for (const [prefix, dir] of Object.entries(mounts)) {
+ if (!prefix.startsWith('/') || !prefix.endsWith('/')) throw new Error(`mount prefix must look like '/name/': ${prefix}`);
+ mounts[prefix] = path.resolve(dir);
+ }
+ const routes = opts.routes || {};
+ const requests = [];
+
+ const server = http.createServer((req, res) => {
+ const urlPath = decodeURIComponent((req.url || '/').split('?')[0]);
+ if (opts.log) requests.push(urlPath);
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ res.setHeader('Cache-Control', 'no-store');
+
+ if (urlPath === '/favicon.ico' && !routes[urlPath]) {
+ res.statusCode = 204;
+ res.end();
+ return;
+ }
+ const route = routes[urlPath];
+ if (route) {
+ res.setHeader('Content-Type', route.type || 'text/html; charset=utf-8');
+ res.end(route.body);
+ return;
+ }
+ let file = null;
+ for (const [prefix, dir] of Object.entries(mounts)) {
+ if (urlPath.startsWith(prefix)) {
+ file = resolveInside(dir, urlPath.slice(prefix.length));
+ if (file) break;
+ }
+ }
+ if (!file && root) file = resolveInside(root, urlPath);
+ if (!file) {
+ res.statusCode = 404;
+ res.end(`not found: ${urlPath}`);
+ return;
+ }
+ res.setHeader('Content-Type', mimeFor(file));
+ fs.createReadStream(file).pipe(res);
+ });
+ await new Promise((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, '127.0.0.1', resolve);
+ });
+ const base = `http://127.0.0.1:${server.address().port}`;
+ return {
+ server,
+ base,
+ requests,
+ url: (p) => base + (p.startsWith('/') ? p : '/' + p),
+ close: () => new Promise((resolve) => server.close(() => resolve())),
+ };
+}
+
+/**
+ * `<script type="importmap">` that maps 'three' and 'three/addons/' onto the
+ * locally served runtime (no CDN). `extra` adds more bare specifiers.
+ */
+function importMapHtml(extra = {}) {
+ const imports = {
+ three: `${RUNTIME_MOUNT}node_modules/three/build/three.module.js`,
+ 'three/addons/': `${RUNTIME_MOUNT}node_modules/three/examples/jsm/`,
+ 'three/examples/jsm/': `${RUNTIME_MOUNT}node_modules/three/examples/jsm/`,
+ 'three-mesh-bvh': `${RUNTIME_MOUNT}node_modules/three-mesh-bvh/build/index.module.js`,
+ ...extra,
+ };
+ return `<script type="importmap">${JSON.stringify({ imports })}</script>`;
+}
+
+module.exports = { MIME, RUNTIME_DIR, RUNTIME_MOUNT, mimeFor, serveDirs, importMapHtml };
diff --git a/harness/tests/__init__.py b/harness/tests/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/agents/__init__.py b/harness/tests/agents/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/agents/conftest.py b/harness/tests/agents/conftest.py
new file mode 100644
index 00000000..0ed88b30
--- /dev/null
+++ b/harness/tests/agents/conftest.py
@@ -0,0 +1,37 @@
+"""Fixtures for agent tests: fake CLI binaries that mimic each tool's output."""
+
+from __future__ import annotations
+
+import stat
+import sys
+from pathlib import Path
+
+import pytest
+
+
+def write_fake_cli(path: Path, body: str) -> Path:
+ """Write an executable python script ``path`` whose main body is ``body``.
+
+ The script receives argv like the real CLI and must print to stdout.
+ """
+ path.write_text("#!" + sys.executable + "\nimport sys, os, json, time\n" + body)
+ path.chmod(path.stat().st_mode | stat.S_IXUSR)
+ return path
+
+
+def fake_bin(tmp_path: Path):
+ d = tmp_path / "bin"
+ d.mkdir()
+
+ def make(name: str, body: str) -> str:
+ return str(write_fake_cli(d / name, body))
+
+ return make
+
+
[email protected](autouse=True)
+def _clean_agent_env(monkeypatch):
+ """Make sure host secrets in the test process do not leak assumptions into tests."""
+ monkeypatch.setenv("FAKE_SERVICE_API_KEY", "leak-me")
+ yield
diff --git a/harness/tests/agents/test_antigravity.py b/harness/tests/agents/test_antigravity.py
new file mode 100644
index 00000000..ade4a154
--- /dev/null
+++ b/harness/tests/agents/test_antigravity.py
@@ -0,0 +1,69 @@
+"""AntigravityAgent: envelope parsing, argv, fake binary, live smoke."""
+
+from __future__ import annotations
+
+import json
+import shutil
+
+import pytest
+
+from codeverse.agents.antigravity import AntigravityAgent, parse_agy_json, usage_from_agy
+from codeverse.agents.cli_common import begin_session
+from codeverse.contracts.agent import AgentJob
+from codeverse.workspace import Workspace
+
+ENVELOPE = {"conversation_id": "c1", "status": "SUCCESS", "response": "DONE\n", "duration_seconds": 3.0, "num_turns": 1,
+ "usage": {"input_tokens": 18589, "output_tokens": 494, "thinking_tokens": 413, "cache_read_tokens": 12199, "total_tokens": 19083}}
+
+FAKE_AGY = r'''
+args = sys.argv[1:]
+prompt = args[args.index("--print") + 1]
+assert "--dangerously-skip-permissions" in args and "--add-dir" in args
+assert "FAKE_SERVICE_API_KEY" not in os.environ
+os.makedirs("src", exist_ok=True)
+open("src/hello.txt", "w").write("hi")
+mode = os.environ.get("FAKE_MODE", "ok")
+if mode == "text":
+ print("plain text answer")
+else:
+ print(''' + repr(json.dumps(ENVELOPE)) + r''')
+'''
+
+
+def test_parse_and_usage():
+ env = parse_agy_json(json.dumps(ENVELOPE))
+ assert env["status"] == "SUCCESS"
+ assert parse_agy_json("just text") is None
+ u = usage_from_agy(env, "gemini-3.6-flash-high")
+ assert (u.input_tokens, u.output_tokens, u.thoughts_tokens, u.cached_tokens) == (18589, 494, 413, 12199)
+ assert u.cost_usd == 0.0 and u.latency_ms == 3000
+
+
+def test_argv(tmp_ws: Workspace):
+ a = AntigravityAgent("gemini-3.6-flash-high", binary="agy")
+ s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", timeout_s=1800), "agy")
+ argv = a.build_argv(s, "p")
+ assert argv[:3] == ["agy", "--print", "p"] and argv[argv.index("--print-timeout") + 1] == "31m"
+ assert argv[argv.index("--model") + 1] == "gemini-3.6-flash-high" and argv[argv.index("--add-dir") + 1] == str(tmp_ws.root)
+ assert argv[argv.index("--output-format") + 1] == "json"
+
+
+def test_fake_run_json_and_text(tmp_ws: Workspace, fake_bin, monkeypatch):
+ a = AntigravityAgent("gemini-3.6-flash-high", binary=fake_bin("agy", FAKE_AGY))
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="a", timeout_s=30))
+ assert res.ok and res.text.strip() == "DONE" and res.usage.input_tokens == 18589, res.errors
+ assert [f.path for f in res.files_changed] == ["src/hello.txt"]
+ monkeypatch.setenv("FAKE_MODE", "text")
+ res2 = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="b", timeout_s=30))
+ assert res2.ok and res2.text == "plain text answer" and res2.usage.input_tokens == 0
+
+
+def test_live_agy_tiny(tmp_ws: Workspace):
+ if not shutil.which("agy"):
+ pytest.skip("agy not installed")
+ a = AntigravityAgent("gemini-3.6-flash-low")
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="Use your file-writing tool to create src/hello.txt containing exactly 'hi'. Reply DONE.",
+ timeout_s=300, label="live", spatial_tools=False))
+ assert res.ok, res.errors
+ assert (tmp_ws.src / "hello.txt").read_text().strip() == "hi"
diff --git a/harness/tests/agents/test_api_agent.py b/harness/tests/agents/test_api_agent.py
new file mode 100644
index 00000000..c243c1f4
--- /dev/null
+++ b/harness/tests/agents/test_api_agent.py
@@ -0,0 +1,210 @@
+"""ApiAgent loop with a scripted FakeChatModel (+ one live gemini test)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from codeverse.agents.api_agent import FRESHNESS_NUDGE, ApiAgent
+from codeverse.agents.api_tools import ToolOutcome
+from codeverse.agents.context import FACTS_TAG, compact_messages, message_chars
+from codeverse.config import get_settings
+from codeverse.contracts.agent import AgentJob
+from codeverse.contracts.chat import (
+ ChatMessage,
+ ChatRequest,
+ ChatResponse,
+ TextPart,
+ ToolCallPart,
+ ToolResultPart,
+ ToolSpec,
+)
+from codeverse.contracts.common import Usage
+
+
+class FakeChatModel:
+ """Replays scripted responses; records every request."""
+
+ provider, model = "fake", "fake-1"
+
+ def __init__(self, script: list[ChatResponse]):
+ self.script = list(script)
+ self.requests: list[ChatRequest] = []
+
+ @property
+ def id(self) -> str:
+ return "fake:fake-1"
+
+ def supports_vision(self) -> bool:
+ return True
+
+ def generate(self, request: ChatRequest) -> ChatResponse:
+ self.requests.append(request)
+ if not self.script:
+ return ChatResponse(text="out of script", usage=Usage(input_tokens=1, output_tokens=1, cost_usd=0.001))
+ r = self.script.pop(0)
+ if isinstance(r, Exception):
+ raise r
+ return r
+
+
+def call(name: str, **args) -> ToolCallPart:
+ return ToolCallPart(id=f"c{abs(hash((name, json.dumps(args, sort_keys=True)))) % 10000}", name=name, arguments=args)
+
+
+def resp(text: str = "", *calls: ToolCallPart) -> ChatResponse:
+ return ChatResponse(text=text, tool_calls=list(calls), usage=Usage(input_tokens=10, output_tokens=5, cost_usd=0.01))
+
+
+class FakeSpatial:
+ """Stands in for the registry bridge: one `build` tool that records calls."""
+
+ def __init__(self, *a, **k):
+ self.calls: list[dict] = []
+ self.tools = {"build": True}
+
+ def specs(self):
+ return [ToolSpec(name="build", description="build it", parameters={"type": "object", "properties": {}})]
+
+ def names(self):
+ return {"build"}
+
+ def call(self, name, args):
+ self.calls.append(args)
+ return ToolOutcome("build ok: 12 tris", numbers={"tris": 12})
+
+
+def _job(ws, **kw) -> AgentJob:
+ base = dict(workspace=str(ws.root), prompt="make src/hello.txt say hi", label="api", timeout_s=60, max_turns=8,
+ spatial_tools=False)
+ base.update(kw)
+ return AgentJob(**base)
+
+
+def test_loop_writes_file_and_finishes(tmp_ws):
+ fake = FakeChatModel([
+ resp("let me look", call("list_files", glob="src/**/*")),
+ resp("", call("write_file", path="src/hello.txt", content="hi\n")),
+ resp("Done: wrote src/hello.txt"),
+ ])
+ res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws))
+ assert res.ok and res.exit_reason == "completed" and res.text.startswith("Done"), res.errors
+ assert (tmp_ws.src / "hello.txt").read_text() == "hi\n"
+ assert [f.path for f in res.files_changed] == ["src/hello.txt"] and res.tool_calls == 2
+ assert res.usage.input_tokens == 30 and res.usage.cost_usd == pytest.approx(0.03)
+ # tool results fed back as role=tool messages
+ last_req = fake.requests[-1]
+ 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()]
+ 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"]
+
+
+def test_system_prompt_uses_agents_md_and_append(tmp_ws):
+ (tmp_ws.root / "AGENTS.md").write_text("RULES HERE")
+ fake = FakeChatModel([resp("done")])
+ ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, system_append="APPEND"))
+ assert fake.requests[0].system.startswith("RULES HERE") and fake.requests[0].system.endswith("APPEND")
+
+
+def test_freshness_nudge_once(tmp_ws, monkeypatch):
+ monkeypatch.setattr("codeverse.agents.api_agent.SpatialTools", FakeSpatial)
+ fake = FakeChatModel([
+ resp("", call("write_file", path="src/a.txt", content="x")),
+ resp("all done"), # claims done without build → nudge
+ resp("", call("build")), # obeys
+ resp("", call("edit_file", path="src/a.txt", old="x", new="y")),
+ resp("really done"), # edited after build again, but nudged already → accept
+ ])
+ res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, spatial_tools=True))
+ assert res.ok and res.text == "really done"
+ nudges = [m for r in fake.requests for m in r.messages if m.role == "user" and m.text == FRESHNESS_NUDGE]
+ assert nudges # nudge was injected
+ rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
+ assert rec["nudged"] is True and "build" in rec["tools"]
+
+
+def test_run_build_alias_and_unknown_tool(tmp_ws, monkeypatch):
+ monkeypatch.setattr("codeverse.agents.api_agent.SpatialTools", FakeSpatial)
+ fake = FakeChatModel([resp("", call("run_build"), call("bogus", x=1)), resp("done")])
+ res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, spatial_tools=True))
+ assert res.ok
+ tool_msg = fake.requests[1].messages[-1]
+ parts = {p.name: p for p in tool_msg.parts}
+ assert "build ok" in parts["run_build"].content and parts["bogus"].is_error
+
+
+def test_max_turns_and_budget(tmp_ws):
+ fake = FakeChatModel([resp("", call("list_files")) for _ in range(20)])
+ res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, max_turns=3))
+ assert not res.ok and res.exit_reason == "budget" and "max_turns" in res.errors[0]
+ fake = FakeChatModel([resp("", call("list_files")) for _ in range(20)])
+ res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws, extra={"max_usd": 0.015}))
+ assert not res.ok and res.exit_reason == "budget" and "max_usd" in res.errors[0]
+
+
+def test_model_error_retry_then_fail(tmp_ws):
+ class Boom(RuntimeError):
+ retryable = True
+
+ fake = FakeChatModel([Boom("503"), resp("", call("list_files")), Boom("bad"), Boom("bad"), Boom("bad")])
+ fake.script[2].retryable = False
+ import codeverse.agents.api_agent as mod
+
+ orig = mod.time.sleep
+ mod.time.sleep = lambda s: None
+ try:
+ res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws))
+ finally:
+ mod.time.sleep = orig
+ assert not res.ok and res.exit_reason == "error" and "model error" in res.errors[0]
+
+
+def test_write_outside_roots_is_refused(tmp_ws):
+ fake = FakeChatModel([resp("", call("write_file", path="artifacts/x.glb", content="z")), resp("ok")])
+ res = ApiAgent("fake:fake-1", chat_model=fake).run(_job(tmp_ws))
+ assert res.ok and not (tmp_ws.artifacts / "x.glb").exists()
+ assert fake.requests[1].messages[-1].parts[0].is_error
+
+
+def test_compaction():
+ msgs = [ChatMessage.user("task")]
+ for i in range(12):
+ msgs.append(ChatMessage(role="assistant", parts=[TextPart(text=f"t{i}"), call("read_file", path=f"f{i}")]))
+ msgs.append(ChatMessage(role="tool", parts=[ToolResultPart(call_id=f"c{i}", name="read_file", content="X" * 1000)]))
+ before = message_chars(msgs)
+ out = compact_messages(msgs, keep_recent=4, facts="- nothing yet")
+ assert message_chars(out) < before / 2
+ assert out[0].text == "task" and out[1].text.startswith(FACTS_TAG)
+ assert out[-1] is msgs[-1] and "compacted" in out[3].parts[0].content
+ again = compact_messages(out, keep_recent=4, facts="- new facts")
+ assert sum(1 for m in again if m.role == "user" and m.text.startswith(FACTS_TAG)) == 1
+
+
+def test_compaction_triggers_in_loop(tmp_ws, monkeypatch):
+ monkeypatch.setattr("codeverse.agents.api_agent.COMPACT_AT_CHARS", 2000)
+ (tmp_ws.src / "big.txt").write_text("Z" * 1500)
+ 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()]
+ assert "compact" in kinds
+ assert any(m.text.startswith(FACTS_TAG) for m in fake.requests[-1].messages if m.role == "user")
+
+
+def test_live_api_agent_gemini(tmp_ws):
+ if not get_settings().gemini_api_keys:
+ pytest.skip("no gemini keys")
+ agent = ApiAgent("gemini:gemini-3.7-flash")
+ res = agent.run(AgentJob(workspace=str(tmp_ws.root), label="live", timeout_s=240, max_turns=8, spatial_tools=False,
+ prompt="Create the file src/hello.txt containing exactly the word 'hi' (use write_file), "
+ "then read it back to verify, then reply DONE."))
+ assert res.ok, res.errors
+ assert (tmp_ws.src / "hello.txt").read_text().strip() == "hi"
+ assert res.usage.input_tokens > 0 and res.tool_calls >= 1
diff --git a/harness/tests/agents/test_api_tools.py b/harness/tests/agents/test_api_tools.py
new file mode 100644
index 00000000..5457740a
--- /dev/null
+++ b/harness/tests/agents/test_api_tools.py
@@ -0,0 +1,62 @@
+"""FileTools sandbox + run_shell allowlist."""
+
+from __future__ import annotations
+
+import os
+
+from codeverse.agents.api_tools import FileTools
+from codeverse.workspace import Workspace
+
+
+def _tools(ws: Workspace) -> FileTools:
+ return FileTools(ws, ["src", "public"])
+
+
+def test_write_read_edit_list(tmp_ws: Workspace):
+ t = _tools(tmp_ws)
+ out = t.call("write_file", {"path": "src/a.txt", "content": "hello world\n"})
+ assert not out.is_error and "created src/a.txt" in out.text
+ assert t.call("read_file", {"path": "src/a.txt"}).text == "hello world\n"
+ e = t.call("edit_file", {"path": "src/a.txt", "old": "world", "new": "there"})
+ assert not e.is_error and t.call("read_file", {"path": "src/a.txt"}).text == "hello there\n"
+ assert t.call("edit_file", {"path": "src/a.txt", "old": "nope", "new": "x"}).is_error
+ t.call("write_file", {"path": "src/b.txt", "content": "aa aa"})
+ assert t.call("edit_file", {"path": "src/b.txt", "old": "aa", "new": "b"}).is_error # ambiguous
+ assert not t.call("edit_file", {"path": "src/b.txt", "old": "aa", "new": "b", "all": True}).is_error
+ listing = t.call("list_files", {"glob": "src/*.txt"}).text
+ assert "src/a.txt" in listing and "src/b.txt" in listing
+ assert t.writes == ["src/a.txt", "src/a.txt", "src/b.txt", "src/b.txt"]
+
+
+def test_path_sandbox(tmp_ws: Workspace):
+ t = _tools(tmp_ws)
+ assert t.call("write_file", {"path": "../escape.txt", "content": "x"}).is_error
+ assert t.call("write_file", {"path": "artifacts/x.txt", "content": "x"}).is_error
+ assert t.call("write_file", {"path": "/etc/passwd", "content": "x"}).is_error
+ assert t.call("read_file", {"path": ".git/HEAD"}).is_error
+ assert t.call("read_file", {"path": "../../etc/hostname"}).is_error
+ (tmp_ws.artifacts / "build.json").write_text("{}")
+ assert t.call("read_file", {"path": "artifacts/build.json"}).text == "{}" # reads outside write roots are fine
+ # symlink escape
+ os.symlink("/etc", tmp_ws.src / "etc_link")
+ assert t.call("write_file", {"path": "src/etc_link/x", "content": "x"}).is_error
+
+
+def test_run_shell_allowlist(tmp_ws: Workspace):
+ t = _tools(tmp_ws)
+ (tmp_ws.src / "ok.py").write_text("x = 1\n")
+ out = t.call("run_shell", {"cmd": "python -m py_compile src/ok.py"})
+ assert not out.is_error and "rc=0" in out.text
+ assert t.call("run_shell", {"cmd": "rm -rf src"}).is_error
+ assert t.call("run_shell", {"cmd": "ls src | cat"}).is_error
+ assert t.call("run_shell", {"cmd": "cat /etc/passwd"}).is_error
+ bad = t.call("run_shell", {"cmd": "python -c 'import sys; sys.exit(3)'"})
+ assert bad.is_error and "rc=3" in bad.text
+ slow = t.call("run_shell", {"cmd": "python -c 'import time; time.sleep(30)'", "timeout_s": 5})
+ assert slow.is_error and "timeout" in slow.text
+
+
+def test_unknown_tool_and_bad_args(tmp_ws: Workspace):
+ t = _tools(tmp_ws)
+ assert t.call("nope", {}).is_error
+ assert t.call("read_file", {"wrong": 1}).is_error
diff --git a/harness/tests/agents/test_claude_code.py b/harness/tests/agents/test_claude_code.py
new file mode 100644
index 00000000..f99a463f
--- /dev/null
+++ b/harness/tests/agents/test_claude_code.py
@@ -0,0 +1,89 @@
+"""ClaudeCodeAgent: argv, envelope parsing, fake binary, one live smoke test."""
+
+from __future__ import annotations
+
+import json
+import shutil
+from pathlib import Path
+
+import pytest
+
+from codeverse.agents.claude_code import ClaudeCodeAgent, parse_claude_json, usage_from_envelope
+from codeverse.agents.cli_common import begin_session
+from codeverse.agents.materialize import materialize_workspace
+from codeverse.contracts.agent import AgentJob
+from codeverse.workspace import Workspace
+
+ENVELOPE = {
+ "type": "result", "subtype": "success", "is_error": False, "duration_ms": 4200, "duration_api_ms": 3900,
+ "num_turns": 3, "result": "Created src/hello.txt", "session_id": "abc", "total_cost_usd": 0.0123,
+ "usage": {"input_tokens": 10, "cache_creation_input_tokens": 200, "cache_read_input_tokens": 5000, "output_tokens": 40},
+ "modelUsage": {"claude-sonnet-4-6": {"inputTokens": 10, "outputTokens": 40, "costUSD": 0.0123}},
+}
+
+FAKE_CLAUDE = r'''
+args = sys.argv[1:]
+prompt = args[args.index("-p") + 1]
+assert "--dangerously-skip-permissions" in args and "--output-format" in args
+assert "--strict-mcp-config" in args
+assert "FAKE_SERVICE_API_KEY" not in os.environ
+mode = os.environ.get("FAKE_MODE", "ok")
+os.makedirs("src", exist_ok=True)
+open("src/hello.txt", "w").write("hi")
+env = json.loads(''' + repr(json.dumps(ENVELOPE)) + r''')
+if mode == "error":
+ env["is_error"] = True; env["subtype"] = "error_max_turns"
+if "--append-system-prompt" in args:
+ env["result"] += " | sys=" + args[args.index("--append-system-prompt") + 1]
+print("some log line")
+print(json.dumps(env))
+'''
+
+
+def test_parse_envelope_variants():
+ assert parse_claude_json(json.dumps(ENVELOPE))["session_id"] == "abc"
+ assert parse_claude_json("noise\n" + json.dumps(ENVELOPE))["num_turns"] == 3
+ assert parse_claude_json(json.dumps([{"type": "assistant"}, ENVELOPE]))["type"] == "result"
+ assert parse_claude_json("") is None
+ u = usage_from_envelope(ENVELOPE, "sonnet")
+ assert u.input_tokens == 10 and u.cached_tokens == 5000 and u.cost_usd == 0.0123 and u.model == "claude-sonnet-4-6"
+
+
+def test_argv_includes_mcp_when_materialized(tmp_ws: Workspace):
+ materialize_workspace(tmp_ws, agent_kind="claude-code", contract_md="c", cookbook_rel="", spatial_tools=True,
+ mcp_command=["python", "-m", "codeverse.spatial.mcp_server", "--workspace", str(tmp_ws.root)])
+ a = ClaudeCodeAgent("sonnet", binary="claude")
+ s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", system_append="S", max_turns=7), "claude-code")
+ argv = a.build_argv(s, "p")
+ assert argv[:3] == ["claude", "-p", "p"]
+ assert "--mcp-config" in argv and argv[argv.index("--mcp-config") + 1].endswith(".mcp.json")
+ assert "--strict-mcp-config" in argv and argv[argv.index("--max-turns") + 1] == "7"
+ assert argv[argv.index("--append-system-prompt") + 1] == "S" and argv[argv.index("--model") + 1] == "sonnet"
+ assert "mcp__c3v__*" in argv[argv.index("--allowedTools") + 1]
+ s2 = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", spatial_tools=False), "claude-code")
+ assert "--mcp-config" not in a.build_argv(s2, "p")
+
+
+def test_fake_run_success_and_error(tmp_ws: Workspace, fake_bin, monkeypatch):
+ a = ClaudeCodeAgent("sonnet", binary=fake_bin("claude", FAKE_CLAUDE))
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="c", system_append="SYS", timeout_s=30))
+ assert res.ok and res.exit_reason == "completed", res.errors
+ assert res.text.endswith("sys=SYS") and res.usage.cost_usd == 0.0123 and res.tool_calls == 2
+ assert [f.path for f in res.files_changed] == ["src/hello.txt"]
+ rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
+ assert rec["num_turns"] == 3 and rec["session_id"] == "abc"
+ monkeypatch.setenv("FAKE_MODE", "error")
+ res2 = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="c2", timeout_s=30))
+ assert not res2.ok and res2.exit_reason == "budget" and "error_max_turns" in res2.errors[0]
+
+
+def test_live_claude_tiny(tmp_ws: Workspace):
+ if not shutil.which("claude"):
+ pytest.skip("claude not installed")
+ a = ClaudeCodeAgent("haiku")
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="Create src/hello.txt containing exactly 'hi'. Reply DONE.",
+ timeout_s=300, label="live", spatial_tools=False, max_turns=6))
+ assert res.ok, res.errors
+ assert (tmp_ws.src / "hello.txt").read_text().strip() == "hi"
+ assert res.usage.output_tokens > 0
diff --git a/harness/tests/agents/test_cli_common.py b/harness/tests/agents/test_cli_common.py
new file mode 100644
index 00000000..bdbe018c
--- /dev/null
+++ b/harness/tests/agents/test_cli_common.py
@@ -0,0 +1,101 @@
+"""cli_common + transcript helpers."""
+
+from __future__ import annotations
+
+import json
+import os
+
+from codeverse.agents.cli_common import (
+ begin_session,
+ deliver_prompt,
+ finish_session,
+ hardened_env,
+ is_quota_failure,
+ is_secret_env,
+ is_transient_failure,
+)
+from codeverse.agents.transcript import Trajectory
+from codeverse.contracts.agent import AgentJob
+from codeverse.contracts.common import Usage
+from codeverse.workspace import Workspace
+
+
+def test_secret_detection():
+ assert is_secret_env("OPENAI_API_KEY") and is_secret_env("FOO_TOKEN") and is_secret_env("GEMINI_API_KEYS")
+ assert not is_secret_env("PATH") and not is_secret_env("HOME") and not is_secret_env("NODE_OPTIONS")
+
+
+def test_hardened_env_strips_secrets_and_adds_guards(tmp_ws: Workspace, monkeypatch):
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-x")
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-y")
+ monkeypatch.setenv("KEEPME", "1")
+ job = AgentJob(workspace=str(tmp_ws.root), prompt="p", env={"EXTRA": "2"})
+ env = hardened_env(tmp_ws, job, keep={"ANTHROPIC_API_KEY"})
+ assert "OPENAI_API_KEY" not in env and "FAKE_SERVICE_API_KEY" not in env
+ assert env["ANTHROPIC_API_KEY"] == "sk-y" and env["KEEPME"] == "1" and env["EXTRA"] == "2"
+ assert env["C3V_AGENT_CONTEXT"] == "1" and env["GIT_CEILING_DIRECTORIES"] == str(tmp_ws.root.parent)
+
+
+def test_session_roundtrip_tracks_files_and_writes_result(tmp_ws: Workspace):
+ job = AgentJob(workspace=str(tmp_ws.root), prompt="do it", label="baseline", extra={"round": 2})
+ s = begin_session(job, "fake")
+ assert s.traj.dir.name == "baseline_r02" and s.traj.prompt_path.read_text() == "do it"
+ (tmp_ws.src / "model.py").write_text("print(1)\n")
+ res = finish_session(s, ok=True, exit_reason="completed", text="done", usage=Usage(input_tokens=5), tool_calls=1)
+ assert res.ok and [f.path for f in res.files_changed] == ["src/model.py"]
+ assert res.files_changed[0].status == "added" and res.files_changed[0].lines_added == 1
+ data = json.loads(s.traj.result_path.read_text())
+ assert data["exit_reason"] == "completed" and data["head_before"] != data["head_after"]
+ assert tmp_ws.head() == data["head_after"]
+
+
+def test_deliver_prompt_uses_file_when_long(tmp_ws: Workspace):
+ job = AgentJob(workspace=str(tmp_ws.root), prompt="x")
+ s = begin_session(job, "fake")
+ short = deliver_prompt(s, "hello")
+ assert short == "hello"
+ long = "y" * 200_001
+ stub = deliver_prompt(s, long)
+ assert "task_prompt.md" in stub and (s.traj.dir / "task_prompt.md").read_text() == long
+ assert os.path.isabs(s.traj.dir.as_posix())
+
+
+def test_transient_markers():
+ assert is_transient_failure("Error: 429 RESOURCE_EXHAUSTED")
+ assert is_transient_failure("", "got an empty response from the model")
+ assert is_quota_failure("quota exceeded") and not is_quota_failure("503 UNAVAILABLE")
+ assert not is_transient_failure("SyntaxError: bad code")
+
+
+def test_trajectory_jsonl_and_result(tmp_path):
+ t = Trajectory(tmp_path / "traj")
+ t.append("a", x=1)
+ t.append("b", y="z")
+ recs = t.read_transcript()
+ assert [r["kind"] for r in recs] == ["a", "b"] and recs[1]["y"] == "z" and "t" in recs[0]
+ t.write_result(Usage(input_tokens=3), note="n")
+ assert json.loads(t.result_path.read_text()) == {**Usage(input_tokens=3).model_dump(), "note": "n"}
+
+
+def test_mcp_command_resolution(tmp_ws: Workspace):
+ from codeverse.agents.cli_common import default_mcp_command, mcp_command_for
+ from codeverse.agents.materialize import materialize_workspace
+
+ job = AgentJob(workspace=str(tmp_ws.root), prompt="p", extra={"language": "blender", "track": "static_object", "round": 2})
+ cmd = mcp_command_for(tmp_ws, job)
+ assert cmd[1:3] == ["-m", "codeverse.spatial.mcp_server"] and "--language" in cmd and cmd[cmd.index("--round") + 1] == "2"
+ job2 = AgentJob(workspace=str(tmp_ws.root), prompt="p", extra={"mcp_command": ["python", "-m", "x"]})
+ assert mcp_command_for(tmp_ws, job2) == ["python", "-m", "x"]
+ materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", cookbook_rel="", spatial_tools=True,
+ mcp_command=default_mcp_command(tmp_ws, language="cadquery"))
+ assert "cadquery" in mcp_command_for(tmp_ws, job2) # materialised .mcp.json wins
+
+
+def test_gemini_system_settings_disable_folder_trust(tmp_path):
+ from codeverse.agents.gemini_cli import write_system_settings
+
+ p = write_system_settings(tmp_path / "s.json")
+ data = json.loads(p.read_text())
+ assert data["security"]["folderTrust"]["enabled"] is False
+ assert data["security"]["auth"]["selectedType"] == "gemini-api-key"
+ assert data["experimental"]["dynamicModelConfiguration"] is True
diff --git a/harness/tests/agents/test_codex.py b/harness/tests/agents/test_codex.py
new file mode 100644
index 00000000..8a9206dc
--- /dev/null
+++ b/harness/tests/agents/test_codex.py
@@ -0,0 +1,93 @@
+"""CodexAgent: JSONL parsing, argv with MCP overrides, fake binary, live smoke."""
+
+from __future__ import annotations
+
+import json
+import shutil
+from pathlib import Path
+
+import pytest
+
+from codeverse.agents.cli_common import begin_session
+from codeverse.agents.codex import CodexAgent, parse_codex_jsonl
+from codeverse.contracts.agent import AgentJob
+from codeverse.workspace import Workspace
+
+EVENTS = [
+ {"type": "thread.started", "thread_id": "th1"},
+ {"type": "turn.started"},
+ {"type": "item.completed", "item": {"id": "i0", "type": "reasoning", "text": "thinking"}},
+ {"type": "item.completed", "item": {"id": "i1", "type": "command_execution", "command": "ls", "exit_code": 0, "status": "completed"}},
+ {"type": "item.completed", "item": {"id": "i2", "type": "file_change", "changes": [{"path": "src/hello.txt", "kind": "add"}], "status": "completed"}},
+ {"type": "item.completed", "item": {"id": "i3", "type": "agent_message", "text": "Done."}},
+ {"type": "turn.completed", "usage": {"input_tokens": 1000, "cached_input_tokens": 600, "output_tokens": 50}},
+]
+
+FAKE_CODEX = r'''
+args = sys.argv[1:]
+assert args[0] == "exec" and "--json" in args and "-C" in args
+ws = args[args.index("-C") + 1]
+prompt = args[-1]
+if prompt == "-":
+ prompt = sys.stdin.read()
+assert "FAKE_SERVICE_API_KEY" not in os.environ
+os.makedirs(os.path.join(ws, "src"), exist_ok=True)
+open(os.path.join(ws, "src", "hello.txt"), "w").write(prompt[:5])
+mode = os.environ.get("FAKE_MODE", "ok")
+events = json.loads(''' + repr(json.dumps(EVENTS)) + r''')
+if mode == "fail":
+ events = events[:2] + [{"type": "turn.failed", "error": {"message": "boom"}}]
+for e in events:
+ print(json.dumps(e)); sys.stdout.flush()
+'''
+
+
+def test_parse_jsonl():
+ ev = parse_codex_jsonl("\n".join(json.dumps(e) for e in EVENTS) + "\nnot json\n")
+ assert ev.thread_id == "th1" and ev.messages == ["Done."] and ev.tool_calls == 2 and ev.turns_completed == 1
+ u = ev.usage("gpt-5.6-sol")
+ assert u.input_tokens == 1000 and u.cached_tokens == 600 and u.output_tokens == 50 and u.tool_calls == 2
+
+
+def test_argv_with_mcp_overrides(tmp_ws: Workspace):
+ a = CodexAgent("gpt-5.6-sol", binary="codex")
+ s = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p"), "codex")
+ argv = a.build_argv(s, "p")
+ assert argv[:3] == ["codex", "exec", "--json"] and argv[argv.index("-C") + 1] == str(tmp_ws.root)
+ assert argv[argv.index("--sandbox") + 1] == "workspace-write" and "--skip-git-repo-check" in argv
+ joined = " ".join(argv)
+ assert 'mcp_servers.c3v.command="' in joined and "mcp_servers.c3v.args=[" in joined and argv[-1] == "p"
+ assert argv[argv.index("--model") + 1] == "gpt-5.6-sol"
+ s2 = begin_session(AgentJob(workspace=str(tmp_ws.root), prompt="p", spatial_tools=False), "codex")
+ assert "mcp_servers" not in " ".join(a.build_argv(s2, None)) and a.build_argv(s2, None)[-1] == "-"
+
+
+def test_fake_run(tmp_ws: Workspace, fake_bin, monkeypatch):
+ a = CodexAgent("gpt-5.6-sol", binary=fake_bin("codex", FAKE_CODEX))
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="x", timeout_s=30))
+ assert res.ok and res.exit_reason == "completed" and res.text == "Done." and res.tool_calls == 2, res.errors
+ assert [f.path for f in res.files_changed] == ["src/hello.txt"]
+ assert res.usage.input_tokens == 1000
+ assert (Path(res.transcript_path).parent / "stdout.jsonl").exists()
+ monkeypatch.setenv("FAKE_MODE", "fail")
+ res2 = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="y", timeout_s=30))
+ assert not res2.ok and res2.exit_reason == "error" and "boom" in res2.errors[0]
+
+
+def test_long_prompt_goes_via_stdin(tmp_ws: Workspace, fake_bin, monkeypatch):
+ monkeypatch.setattr("codeverse.agents.codex.STDIN_PROMPT_BYTES", 10)
+ a = CodexAgent("gpt-5.6-sol", binary=fake_bin("codex", FAKE_CODEX))
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello world this is long", label="z", timeout_s=30))
+ assert res.ok and (tmp_ws.src / "hello.txt").read_text() == "hello"
+
+
+def test_live_codex_tiny(tmp_ws: Workspace):
+ if not shutil.which("codex"):
+ pytest.skip("codex not installed")
+ a = CodexAgent("gpt-5.6-sol")
+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="Create src/hello.txt containing exactly 'hi'. Reply DONE.",
+ timeout_s=300, label="live", spatial_tools=False))
+ assert res.ok, res.errors
+ assert (tmp_ws.src / "hello.txt").read_text().strip() == "hi"
+ assert res.usage.input_tokens > 0
diff --git a/harness/tests/agents/test_gemini_cli.py b/harness/tests/agents/test_gemini_cli.py
new file mode 100644
index 00000000..2268e892
--- /dev/null
+++ b/harness/tests/agents/test_gemini_cli.py
@@ -0,0 +1,133 @@
+"""GeminiCliAgent with a fake `gemini` binary + one live smoke test."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from codeverse.agents.gemini_cli import GeminiCliAgent, parse_gemini_json, usage_from_stats
+from codeverse.config import get_settings
+from codeverse.contracts.agent import AgentJob
+from codeverse.workspace import Workspace
+
+FAKE_GEMINI = r'''
+args = sys.argv[1:]
+model = args[args.index("-m") + 1]
+prompt = args[args.index("-p") + 1]
+mode = os.environ.get("FAKE_MODE", "ok")
+assert os.environ.get("GEMINI_API_KEY"), "no key in env"
+assert "GEMINI_API_KEYS" not in os.environ
+assert "FAKE_SERVICE_API_KEY" not in os.environ, "secret leaked"
+assert os.path.isfile(os.environ["GEMINI_CLI_SYSTEM_SETTINGS_PATH"])
+if mode == "fail_once":
+ marker = "attempts.txt"
+ n = int(open(marker).read()) if os.path.exists(marker) else 0
+ open(marker, "w").write(str(n + 1))
+ if n == 0:
+ print("Error: 429 RESOURCE_EXHAUSTED quota", file=sys.stderr)
+ sys.exit(1)
+if mode == "hang":
+ time.sleep(60)
+served = "gemini-9-pro" if mode == "substitute" else model
+os.makedirs("src", exist_ok=True)
+open("src/hello.txt", "w").write(prompt[:20])
+out = {"session_id": "s1", "response": "DONE: " + prompt[:10],
+ "stats": {"models": {served: {"tokens": {"input": 100, "candidates": 20, "cached": 5, "thoughts": 7}}},
+ "tools": {"totalCalls": 1}}}
+print(json.dumps(out, indent=2))
+'''
+
+
+def agent(fake_bin, monkeypatch):
+ binary = fake_bin("gemini", FAKE_GEMINI)
+ s = get_settings()
+ monkeypatch.setattr(s, "gemini_api_keys", ["k1", "k2"])
+ monkeypatch.setattr(s, "cache_dir", Path(binary).parent / "cache")
+ monkeypatch.delenv("GEMINI_API_KEYS", raising=False)
+ return GeminiCliAgent("gemini-3.7-flash", binary=binary)
+
+
+def _job(ws: Workspace, **kw) -> AgentJob:
+ base = dict(workspace=str(ws.root), prompt="write hello", model="gemini-3.7-flash", timeout_s=20, label="t")
+ base.update(kw)
+ return AgentJob(**base)
+
+
+def test_success_path(tmp_ws: Workspace, agent: GeminiCliAgent):
+ res = agent.run(_job(tmp_ws))
+ assert res.ok and res.exit_reason == "completed", res.errors
+ assert res.text.startswith("DONE")
+ assert [f.path for f in res.files_changed] == ["src/hello.txt"]
+ assert res.usage.input_tokens == 100 and res.usage.output_tokens == 20 and res.usage.thoughts_tokens == 7
+ assert res.usage.tool_calls == 1 and res.tool_calls == 1
+ traj = Path(res.transcript_path).parent
+ assert (traj / "stdout.json").exists() and (traj / "prompt.md").exists() and (traj / "result.json").exists()
+ rec = json.loads((traj / "result.json").read_text())
+ assert rec["attempts"] == 1 and rec["session_id"] == "s1"
+ # commits: pre + agent
+ assert "agent:t" in tmp_ws._git("log", "--oneline").stdout
+
+
+def test_model_substitution_detected(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
+ monkeypatch.setenv("FAKE_MODE", "substitute")
+ res = agent.run(_job(tmp_ws))
+ assert not res.ok and res.exit_reason == "model_substituted"
+ assert "gemini-9-pro" in res.errors[0]
+
+
+def test_transient_failure_retries_once_with_other_key(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
+ monkeypatch.setenv("FAKE_MODE", "fail_once")
+ res = agent.run(_job(tmp_ws))
+ assert res.ok, res.errors
+ 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"]
+ assert keys == ["k1", "k2"]
+
+
+def test_timeout_is_reported(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
+ monkeypatch.setenv("FAKE_MODE", "hang")
+ monkeypatch.setattr("codeverse.agents.gemini_cli.IDLE_GRACE_S", 1.0)
+ res = agent.run(_job(tmp_ws, timeout_s=1))
+ assert not res.ok and res.exit_reason == "timeout" and res.duration_s < 30
+
+
+def test_unavailable_when_no_keys(tmp_ws: Workspace, agent: GeminiCliAgent, monkeypatch):
+ monkeypatch.setattr(get_settings(), "gemini_api_keys", [])
+ ok, why = agent.available()
+ assert not ok and "key" in why
+ res = agent.run(_job(tmp_ws))
+ assert not res.ok and res.exit_reason == "error"
+
+
+def test_parse_helpers():
+ assert parse_gemini_json("noise\n{\"response\": \"x\"}") == {"response": "x"}
+ assert parse_gemini_json("") is None
+ u = usage_from_stats({"models": {"m": {"tokens": {"input": 1, "candidates": 2, "cached": 3, "thoughts": 4}}},
+ "tools": {"totalCalls": 9}}, "m")
+ assert (u.input_tokens, u.output_tokens, u.cached_tokens, u.thoughts_tokens, u.tool_calls) == (1, 2, 3, 4, 9)
+
+
+def test_system_append_is_prepended(tmp_ws: Workspace, agent: GeminiCliAgent):
+ res = agent.run(_job(tmp_ws, system_append="BE BRIEF"))
+ assert res.ok
+ assert (tmp_ws.src / "hello.txt").read_text().startswith("<harness_instr")
+
+
+def test_live_gemini_cli_creates_file(tmp_ws: Workspace):
+ if not get_settings().gemini_api_keys:
+ pytest.skip("no gemini keys")
+ agent = GeminiCliAgent("gemini-3.7-flash")
+ job = AgentJob(workspace=str(tmp_ws.root), prompt="Create the file src/hello.txt containing exactly the word 'hi'. "
+ "Then reply with the single word DONE.", timeout_s=240, label="live", spatial_tools=False)
+ res = agent.run(job)
+ assert res.ok, res.errors
+ assert (tmp_ws.src / "hello.txt").read_text().strip() == "hi"
+ assert res.usage.input_tokens > 0 and res.usage.model == "gemini-3.7-flash"
+ assert any(f.path == "src/hello.txt" for f in res.files_changed)
diff --git a/harness/tests/agents/test_materialize.py b/harness/tests/agents/test_materialize.py
new file mode 100644
index 00000000..69d13818
--- /dev/null
+++ b/harness/tests/agents/test_materialize.py
@@ -0,0 +1,90 @@
+"""materialize_workspace: bodies, MCP configs, ignore files, cookbook, codex overrides."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from codeverse.agents.cli_common import default_mcp_command
+from codeverse.agents.materialize import C3V_DIR, codex_mcp_overrides, materialize_workspace
+from codeverse.workspace import Workspace
+
+CONTRACT = "## blender contract\nWrite pure bpy into src/model.py."
+
+
+def _mat(ws: Workspace, kind: str = "gemini-cli", spatial: bool = True, cookbook: str = "missing/cookbook.md"):
+ return materialize_workspace(ws, agent_kind=kind, contract_md=CONTRACT, cookbook_rel=cookbook,
+ spatial_tools=spatial, mcp_command=default_mcp_command(ws))
+
+
+def test_writes_three_bodies_same_content(tmp_ws: Workspace):
+ res = _mat(tmp_ws)
+ bodies = [(tmp_ws.root / n).read_text() for n in ("AGENTS.md", "GEMINI.md", "CLAUDE.md")]
+ assert bodies[0] == bodies[1] == bodies[2]
+ body = bodies[0]
+ assert "ONLY under `src/` and `public/`" in body
+ assert "never import from `codeverse`" in body.lower() or "Never import from `codeverse`" in body
+ assert CONTRACT.splitlines()[0] in body
+ assert "Spatial tools (c3v)" in body
+ assert len(res.body_files) == 3
+
+
+def test_mcp_configs_written_and_merged(tmp_ws: Workspace):
+ gs = tmp_ws.root / ".gemini" / "settings.json"
+ gs.parent.mkdir(parents=True)
+ gs.write_text(json.dumps({"mcpServers": {"other": {"command": "x"}}, "ui": {"theme": "dark"}}))
+ res = _mat(tmp_ws)
+ data = json.loads(gs.read_text())
+ assert data["ui"]["theme"] == "dark" and "other" in data["mcpServers"]
+ c3v = data["mcpServers"]["c3v"]
+ assert c3v["command"] == default_mcp_command(tmp_ws)[0]
+ assert c3v["args"][:2] == ["-m", "codeverse.spatial.mcp_server"] and c3v["timeout"] == 600000
+ mcp = json.loads((tmp_ws.root / ".mcp.json").read_text())
+ assert mcp["mcpServers"]["c3v"]["type"] == "stdio"
+ assert res.codex_overrides[1].startswith("mcp_servers.c3v.command=")
+ assert "mcp_servers.c3v.args=[" in res.codex_overrides[3]
+ assert "global" in res.agy_mcp.lower()
+ for f in (".geminiignore", ".aiexclude"):
+ assert "artifacts/" in (tmp_ws.root / f).read_text()
+
+
+def test_spatial_disabled_drops_server_and_documents_absence(tmp_ws: Workspace):
+ _mat(tmp_ws)
+ res = _mat(tmp_ws, spatial=False)
+ assert res.mcp_files == []
+ assert "c3v" not in json.loads((tmp_ws.root / ".gemini" / "settings.json").read_text())["mcpServers"]
+ assert "No spatial tools are available" in (tmp_ws.root / "AGENTS.md").read_text()
+
+
+def test_cookbook_copied_when_found(tmp_ws: Workspace, tmp_path):
+ cb = tmp_path / "cookbook.md"
+ cb.write_text("# cookbook\nsnippet")
+ res = _mat(tmp_ws, cookbook=str(cb))
+ assert res.cookbook_path.endswith(f"{C3V_DIR}/cookbook.md")
+ assert (tmp_ws.root / C3V_DIR / "cookbook.md").read_text().startswith("# cookbook")
+ assert f"{C3V_DIR}/cookbook.md" in (tmp_ws.root / "AGENTS.md").read_text()
+ assert not res.warnings
+
+
+def test_missing_cookbook_is_a_warning(tmp_ws: Workspace):
+ res = _mat(tmp_ws, cookbook="nope/cookbook.md")
+ assert any("cookbook not found" in w for w in res.warnings)
+
+
+def test_kind_specific_tool_hint(tmp_ws: Workspace):
+ _mat(tmp_ws, kind="claude-code")
+ assert "mcp__c3v__" in (tmp_ws.root / "CLAUDE.md").read_text()
+ _mat(tmp_ws, kind="agy")
+ assert "codeverse.cli.main tools" in (tmp_ws.root / "AGENTS.md").read_text()
+
+
+def test_codex_overrides_are_valid_toml_fragments():
+ ov = codex_mcp_overrides(["python", "-m", "x", "--workspace", "/a b/c"])
+ assert ov[0] == "-c" and ov[1] == 'mcp_servers.c3v.command="python"'
+ assert ov[3] == 'mcp_servers.c3v.args=["-m", "x", "--workspace", "/a b/c"]'
+
+
+def test_spatial_requires_mcp_command(tmp_ws: Workspace):
+ with pytest.raises(ValueError):
+ materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", cookbook_rel="", spatial_tools=True, mcp_command=[])
diff --git a/harness/tests/agents/test_watchdog.py b/harness/tests/agents/test_watchdog.py
new file mode 100644
index 00000000..c2068735
--- /dev/null
+++ b/harness/tests/agents/test_watchdog.py
@@ -0,0 +1,94 @@
+"""run_with_watchdog: streaming, idle kill, hard kill, process-group kill, stdin."""
+
+from __future__ import annotations
+
+import os
+import sys
+import time
+from pathlib import Path
+
+from codeverse.agents.watchdog import run_with_watchdog
+
+PY = sys.executable
+
+
+def test_normal_run_streams_lines(tmp_path: Path):
+ seen = []
+ 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)),
+ )
+ assert res.rc == 0 and not res.timed_out
+ assert res.stdout.splitlines() == ["a", "c"]
+ assert res.stderr.strip() == "b"
+ assert ("stdout", "a") in seen and ("stderr", "b") in seen
+
+
+def test_stdin_is_delivered(tmp_path: Path):
+ res = run_with_watchdog([PY, "-c", "import sys; print(sys.stdin.read().upper())"], cwd=tmp_path, env=None,
+ soft_timeout_s=10, idle_grace_s=5, stdin="hello")
+ assert res.stdout.strip() == "HELLO"
+
+
+def test_idle_kill_after_soft_timeout(tmp_path: Path):
+ t0 = time.time()
+ res = run_with_watchdog([PY, "-c", "import time; time.sleep(60)"], cwd=tmp_path, env=None,
+ soft_timeout_s=1, idle_grace_s=1, hard_timeout_s=30, poll_s=0.2)
+ assert res.timed_out and res.killed_reason == "idle"
+ assert time.time() - t0 < 15
+
+
+def test_activity_extends_past_soft_timeout(tmp_path: Path):
+ # prints every 0.3s for ~2.5s: soft=1, grace=1 → must NOT be killed (activity keeps it alive)
+ code = "import time,sys\nfor i in range(8):\n print(i); sys.stdout.flush(); time.sleep(0.3)\nprint('done')"
+ res = run_with_watchdog([PY, "-c", code], cwd=tmp_path, env=None, soft_timeout_s=1, idle_grace_s=1,
+ hard_timeout_s=30, poll_s=0.2)
+ assert not res.timed_out and res.stdout.strip().endswith("done")
+
+
+def test_hard_timeout_kills_active_process(tmp_path: Path):
+ code = "import time,sys\nwhile True:\n print('tick'); sys.stdout.flush(); time.sleep(0.2)"
+ t0 = time.time()
+ res = run_with_watchdog([PY, "-c", code], cwd=tmp_path, env=None, soft_timeout_s=1, idle_grace_s=60,
+ hard_timeout_s=2, poll_s=0.2)
+ assert res.timed_out and res.killed_reason == "hard_timeout"
+ assert time.time() - t0 < 15
+
+
+def test_process_group_is_killed(tmp_path: Path):
+ """A grandchild (sleep) must die with the parent on timeout."""
+ marker = tmp_path / "child.pid"
+ code = (
+ "import subprocess, time, sys\n"
+ f"p = subprocess.Popen(['sleep', '300']); open({str(marker)!r}, 'w').write(str(p.pid)); sys.stdout.flush()\n"
+ "time.sleep(300)"
+ )
+ res = run_with_watchdog([PY, "-c", code], cwd=tmp_path, env=None, soft_timeout_s=1, idle_grace_s=1,
+ hard_timeout_s=30, poll_s=0.2)
+ assert res.timed_out
+ pid = int(marker.read_text())
+ time.sleep(0.5)
+ alive = True
+ try:
+ os.kill(pid, 0)
+ # zombie check: /proc/<pid>/status State
+ st = Path(f"/proc/{pid}/status").read_text() if Path(f"/proc/{pid}/status").exists() else "State:\tZ"
+ alive = "State:\tZ" not in st
+ except ProcessLookupError:
+ alive = False
+ assert not alive
+
+
+def test_file_mtime_counts_as_activity(tmp_path: Path):
+ src = tmp_path / "src"
+ src.mkdir()
+ # silent process that touches a file every 0.5s for 3s; soft=1 grace=1.5 → alive until done
+ code = (
+ "import time\n"
+ f"p = {str(src / 'a.txt')!r}\n"
+ "for i in range(6):\n open(p, 'a').write('x'); time.sleep(0.5)\n"
+ )
+ res = run_with_watchdog([PY, "-c", code], cwd=tmp_path, env=None, soft_timeout_s=1, idle_grace_s=1.5,
+ hard_timeout_s=30, poll_s=0.2, scan_s=0.3, activity_dirs=[src])
+ assert res.rc == 0 and not res.timed_out
diff --git a/harness/tests/blender_cadquery/__init__.py b/harness/tests/blender_cadquery/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/blender_cadquery/conftest.py b/harness/tests/blender_cadquery/conftest.py
new file mode 100644
index 00000000..0447a47c
--- /dev/null
+++ b/harness/tests/blender_cadquery/conftest.py
@@ -0,0 +1,48 @@
+"""Fixtures for the blender / cadquery language packages."""
+
+from __future__ import annotations
+
+import shutil
+
+import pytest
+
+from codeverse.config import get_settings
+from codeverse.contracts.plan import AcceptanceItem, BBox, PartPlan, StaticPlan
+
+
+def table_plan() -> StaticPlan:
+ """3-part plan (one part with 4 instances) used by skeleton/build tests."""
+ return StaticPlan(
+ object_name="SideTable",
+ summary="A small oak side table with four legs and a lower shelf.",
+ overall_bbox=BBox(center=(0, 0, 0.3), extents=(0.5, 0.5, 0.6)),
+ style_notes="mid-century",
+ parts=[
+ PartPlan(name="TableTop", role="top surface", description="rounded-corner slab",
+ bbox=BBox(center=(0, 0, 0.58), extents=(0.5, 0.5, 0.04)), material="oak wood"),
+ PartPlan(name="Leg", role="support", description="tapered square leg",
+ bbox=BBox(center=(0.21, 0.21, 0.28), extents=(0.04, 0.04, 0.56)), material="oak",
+ attach_to="TableTop", symmetry="mirror_x", instances=4),
+ PartPlan(name="Shelf", role="lower shelf", description="thin slab",
+ bbox=BBox(center=(0, 0, 0.15), extents=(0.42, 0.42, 0.02)), material="painted steel",
+ attach_to="Leg"),
+ ],
+ acceptance=[AcceptanceItem(id="a1", text="overall height 0.60 m", how="measure")],
+ )
+
+
+def blender_bin() -> str:
+ b = get_settings().resolve_blender()
+ if not b or not shutil.which(b) and not b.startswith("/"):
+ pytest.skip("no Blender binary")
+ return b
+
+
+def has_cadquery() -> bool:
+ try:
+ import cadquery # noqa: F401
+ except ImportError:
+ return False
+ return True
diff --git a/harness/tests/blender_cadquery/test_blender_lint.py b/harness/tests/blender_cadquery/test_blender_lint.py
new file mode 100644
index 00000000..7df02b5b
--- /dev/null
+++ b/harness/tests/blender_cadquery/test_blender_lint.py
@@ -0,0 +1,110 @@
+"""Offline tests for the bpy lint."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.languages.blender.lint import lint_blender_file, lint_blender_source
+
+GOOD = '''
+import bpy
+import bmesh
+from mathutils import Vector
+
+bpy.ops.mesh.primitive_cube_add(size=1, location=(0, 0, 0.5), scale=(1, 1, 1))
+obj = bpy.context.object
+obj.name = "Body"
+bpy.ops.object.transform_apply(location=False, rotation=False, scale=True)
+mat = bpy.data.materials.new("BodyMat")
+mat.node_tree.nodes["Principled BSDF"].inputs["Base Color"].default_value = (1, 0, 0, 1)
+obj.data.materials.append(mat)
+bm = bmesh.new()
+bm.from_mesh(obj.data)
+bm.verts.ensure_lookup_table()
+v = bm.verts[0]
+bm.free()
+'''
+
+
+def _msgs(report, sev=None):
+ return [f.message for f in report.findings if sev is None or f.severity == sev]
+
+
+def test_good_script_passes() -> None:
+ r = lint_blender_source(GOOD)
+ assert r.gate == "lint:blender" and r.passed, _msgs(r)
+ assert not _msgs(r, Severity.ERROR)
+ assert any("Body" in m for m in _msgs(r, Severity.INFO))
+
+
+def test_syntax_error() -> None:
+ r = lint_blender_source("import bpy\nx = (\n")
+ assert not r.passed and r.findings[0].data["line"] == 2 and "SyntaxError" in r.findings[0].message
+
+
+def test_missing_bpy_import_and_forbidden_calls() -> None:
+ src = "import os\nimport subprocess\nbpy.ops.render.render()\nbpy.ops.export_scene.gltf(filepath='x')\nbpy.ops.wm.save_mainfile()\nopen('f').read()\nos.system('ls')\n"
+ r = lint_blender_source(src)
+ errs = _msgs(r, Severity.ERROR)
+ assert any("never imports bpy" in m for m in errs)
+ assert any("bpy.ops.render.render" in m for m in errs)
+ assert any("bpy.ops.export_scene.gltf" in m for m in errs)
+ assert any("bpy.ops.wm.save_mainfile" in m for m in errs)
+ assert any("open()" in m for m in errs)
+ assert any("os.system" in m for m in errs)
+ assert any("subprocess" in m for m in errs)
+
+
+def test_bmesh_lookup_table_missing_is_error_even_if_mentioned_in_comment() -> None:
+ src = "import bpy, bmesh\nbm = bmesh.new()\nv = bm.verts[0] # forgot ensure_lookup_table\n"
+ r = lint_blender_source(src)
+ f = [x for x in r.findings if "ensure_lookup_table" in x.message]
+ assert f and f[0].severity == Severity.ERROR and f[0].data["line"] == 3 and "ensure_lookup_table()" in f[0].fix_hint
+
+
+def test_vector_without_import() -> None:
+ r = lint_blender_source("import bpy\nv = Vector((1, 2, 3))\n")
+ f = [x for x in r.findings if "Vector" in x.message]
+ assert f and f[0].severity == Severity.ERROR and f[0].fix_hint == "from mathutils import Vector"
+
+
+def test_removed_bsdf_inputs() -> None:
+ r = lint_blender_source("import bpy\nm = bpy.data.materials.new('x')\nm.node_tree.nodes['Principled BSDF'].inputs['Specular'].default_value = 0.5\n")
+ f = [x for x in r.findings if "Specular" in x.message]
+ assert f and f[0].severity == Severity.ERROR and "Specular IOR Level" in f[0].fix_hint
+
+
+def test_camera_light_and_render_settings_warn() -> None:
+ src = "import bpy\nbpy.ops.object.light_add(type='SUN')\ncam = bpy.data.cameras.new('c')\nbpy.context.scene.render.engine = 'CYCLES'\nbpy.context.scene.camera = None\n"
+ r = lint_blender_source(src)
+ assert r.passed # warnings only
+ w = _msgs(r, Severity.WARN)
+ assert any("light_add" in m for m in w) and any("cameras.new" in m for m in w) and any("render settings" in m for m in w)
+
+
+def test_headless_pitfalls() -> None:
+ src = ("import bpy\nbpy.ops.mesh.primitive_cube_add(scale=(1, 2, 3))\nbpy.ops.object.transform_apply(scale=True)\n"
+ "bpy.ops.object.modifier_apply(modifier='Bevel')\nbpy.ops.object.join()\nsel = bpy.context.selected_objects\n"
+ "bpy.ops.object.delete({'selected_objects': sel})\nobj = bpy.context.object\nobj.data.use_auto_smooth = True\n")
+ r = lint_blender_source(src)
+ w = _msgs(r, Severity.WARN)
+ e = _msgs(r, Severity.ERROR)
+ assert any("size=1" in m for m in w)
+ assert any("transform_apply" in m for m in w)
+ assert any("modifier_apply" in m for m in w)
+ assert any("join" in m for m in w)
+ assert any("selected_objects" in m for m in w)
+ assert any("context-dict" in m for m in e)
+ assert any("use_auto_smooth" in m for m in e)
+
+
+def test_modifier_apply_with_temp_override_is_fine() -> None:
+ src = "import bpy\nobj = bpy.context.object\nwith bpy.context.temp_override(object=obj):\n bpy.ops.object.modifier_apply(modifier='Bevel')\nobj.name = 'Body'\n"
+ r = lint_blender_source(src)
+ assert not any("modifier_apply" in m for m in _msgs(r, Severity.WARN))
+
+
+def test_missing_file(tmp_path: Path) -> None:
+ r = lint_blender_file(tmp_path / "model.py")
+ assert not r.passed and "missing" in r.findings[0].message
diff --git a/harness/tests/blender_cadquery/test_blender_runtime.py b/harness/tests/blender_cadquery/test_blender_runtime.py
new file mode 100644
index 00000000..24e2bac2
--- /dev/null
+++ b/harness/tests/blender_cadquery/test_blender_runtime.py
@@ -0,0 +1,171 @@
+"""BlenderRuntime: offline tests with a fake blender + integration tests on the real binary."""
+
+from __future__ import annotations
+
+import json
+import os
+import stat
+import time
+from pathlib import Path
+
+import pytest
+
+from codeverse.contracts.artifacts import BuildResult
+from codeverse.languages import get_runtime
+from codeverse.languages.base import LanguageRuntime
+from codeverse.languages.blender.lint import lint_blender_file
+from codeverse.languages.blender.runtime import (
+ WRAPPER,
+ BlenderNotFoundError,
+ BlenderRuntime,
+ blender_env,
+)
+
+FAKE_BLENDER = """#!/usr/bin/env python3
+import json, os, sys
+args = sys.argv[sys.argv.index("--") + 1:]
+out = args[args.index("--out") + 1]
+os.makedirs(out, exist_ok=True)
+open(os.path.join(out, "object.glb"), "wb").write(b"glTF" + b"\\0" * 16)
+json.dump({"ok": True, "error_type": "", "error_message": "", "duration_ms": 7, "warnings": []}, open(os.path.join(out, "build.json"), "w"))
+json.dump({"tri_count": 12, "objects": []}, open(os.path.join(out, "census.json"), "w"))
+print("fake blender ran", " ".join(args))
+"""
+
+
+def _fake_blender(tmp_path: Path) -> str:
+ p = tmp_path / "blender"
+ p.write_text(FAKE_BLENDER)
+ p.chmod(p.stat().st_mode | stat.S_IEXEC)
+ return str(p)
+
+
+def test_protocol_and_registry() -> None:
+ rt = get_runtime("blender")
+ assert isinstance(rt, BlenderRuntime) and isinstance(rt, LanguageRuntime)
+ assert rt.entry_globs == ("src/model.py",) and rt.language.value == "blender"
+ assert "bpy" in rt.contract_doc() and "Z is up" in rt.contract_doc()
+ assert rt.cookbook_path().name == "cookbook.md"
+
+
+def test_missing_binary_raises(tmp_ws) -> None:
+ rt = BlenderRuntime(blender="/nonexistent/blender")
+ (tmp_ws.src / "model.py").write_text("import bpy\n")
+ with pytest.raises(BlenderNotFoundError):
+ rt.build(tmp_ws)
+
+
+def test_missing_entry_file(tmp_ws, tmp_path) -> None:
+ rt = BlenderRuntime(blender=_fake_blender(tmp_path))
+ r = rt.build(tmp_ws)
+ assert not r.ok and r.error_type == "MissingEntryFile"
+
+
+def test_build_command_and_env(tmp_ws, tmp_path) -> None:
+ rt = BlenderRuntime(blender=_fake_blender(tmp_path))
+ cmd = rt.build_command(tmp_ws, stl=True, seed=3, tri_limit=1000)
+ assert cmd[1:5] == ["-b", "--factory-startup", "--python", str(WRAPPER)] and "--" in cmd
+ assert cmd[cmd.index("--script") + 1] == str(tmp_ws.src / "model.py") and "--stl" in cmd and "--seed" in cmd
+ os.environ["PYTHONPATH"] = "/tmp/x"
+ try:
+ assert "PYTHONPATH" not in blender_env() and blender_env()["PYTHONNOUSERSITE"] == "1"
+ finally:
+ del os.environ["PYTHONPATH"]
+
+
+def test_build_with_fake_blender(tmp_ws, tmp_path) -> None:
+ rt = BlenderRuntime(blender=_fake_blender(tmp_path))
+ (tmp_ws.src / "model.py").write_text("import bpy\n")
+ r = rt.build(tmp_ws, timeout_s=30)
+ assert isinstance(r, BuildResult) and r.ok and r.glb_path == str(tmp_ws.artifacts / "object.glb")
+ assert r.census["tri_count"] == 12 and r.duration_ms == 7 and "fake blender ran" in r.stdout_tail
+
+
+# --------------------------------------------------------------------------- real Blender
+def test_live_skeleton_builds_and_exports_canonical_glb(tmp_ws, table_plan, blender_bin) -> None:
+ trimesh = pytest.importorskip("trimesh")
+ rt = BlenderRuntime(blender=blender_bin)
+ rt.skeleton(tmp_ws, table_plan)
+ assert rt.lint(tmp_ws).passed
+ t0 = time.monotonic()
+ r = rt.build(tmp_ws, timeout_s=120)
+ dt = time.monotonic() - t0
+ assert r.ok, (r.error_type, r.error_message, r.stderr_tail)
+ assert dt < 60
+ assert Path(r.extra_paths["stl"]).stat().st_size > 0
+ scene = trimesh.load(r.glb_path)
+ names = set(scene.graph.nodes_geometry)
+ assert names == {"TableTop", "Shelf", "Leg_0", "Leg_1", "Leg_2", "Leg_3"}
+ assert "Legs" in scene.graph.nodes # parent empty exported as a node
+ lo, hi = scene.bounds
+ assert abs(lo[1]) < 1e-4 and abs(hi[1] - 0.6) < 1e-3 # Y-up, ground contact, height 0.6
+ assert abs(lo[0] + 0.25) < 1e-3 and abs(hi[2] - 0.25) < 1e-3
+ leg0 = scene.geometry[scene.graph["Leg_0"][1]]
+ assert len(leg0.faces) > 12 # bevel modifier applied on export
+ assert leg0.visual.material.baseColorFactor[0] > leg0.visual.material.baseColorFactor[2] # oak-ish
+ c = r.census
+ assert c["tri_count"] == sum(o["tri_count"] for o in c["objects"] if o["type"] == "MESH")
+ assert c["n_mesh_objects"] == 6 and c["frame"] == "z_up_neg_y_front" and not c["cameras"]
+ assert abs(c["scene_bbox_min"][2]) < 1e-4 and abs(c["scene_bbox_max"][2] - 0.6) < 1e-3
+
+
+BROKEN = '''import bpy
+import bmesh
+
+bpy.ops.mesh.primitive_cube_add(size=1)
+body = bpy.context.object
+body.name = "Body"
+bpy.ops.object.light_add(type="SUN")
+bm = bmesh.new()
+bm.from_mesh(body.data)
+v = bm.verts[0]
+bm.free()
+'''
+
+
+def test_live_error_maps_to_line_and_lint_catches_it(tmp_ws, blender_bin) -> None:
+ rt = BlenderRuntime(blender=blender_bin)
+ (tmp_ws.src / "model.py").write_text(BROKEN)
+ lint = lint_blender_file(tmp_ws.src / "model.py")
+ assert not lint.passed and any("ensure_lookup_table" in f.message and f.data.get("line") == 10 for f in lint.errors)
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert not r.ok and r.error_type == "IndexError" and r.error_file == "model.py" and r.error_line == 10
+ assert "ensure_lookup_table" in r.error_message
+ assert r.census["build_report"]["error_source"] == "v = bm.verts[0]"
+ assert any("light" in w for w in r.census["warnings"])
+ assert r.glb_path is None or Path(r.glb_path).stat().st_size > 0 # partial export may still exist
+ build_json = json.loads((tmp_ws.artifacts / "build.json").read_text())
+ assert build_json["error_line"] == 10
+
+
+def test_live_timeout_and_memory_cap(tmp_ws, blender_bin) -> None:
+ rt = BlenderRuntime(blender=blender_bin)
+ (tmp_ws.src / "model.py").write_text("import bpy, time\nbpy.ops.mesh.primitive_cube_add(size=1)\nwhile True:\n time.sleep(0.1)\n")
+ t0 = time.monotonic()
+ r = rt.build(tmp_ws, timeout_s=4)
+ assert not r.ok and r.error_type == "BuildTimeout" and time.monotonic() - t0 < 20
+ (tmp_ws.src / "model.py").write_text("import bpy\nimport numpy as np\nbpy.ops.mesh.primitive_cube_add(size=1)\nbig = np.ones((3_000_000_000,))\n")
+ r = rt.build(tmp_ws, timeout_s=60)
+ assert not r.ok and r.error_type == "MemoryError" and r.error_line == 4
+
+
+def test_live_native_render(tmp_ws, table_plan, blender_bin, tmp_path) -> None:
+ from codeverse.languages._common import run_subprocess
+ from codeverse.languages.blender.runtime import RENDER_WRAPPER, blender_env
+
+ rt = BlenderRuntime(blender=blender_bin)
+ rt.skeleton(tmp_ws, table_plan)
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok
+ out = tmp_path / "renders"
+ proc = run_subprocess([blender_bin, "-b", "--factory-startup", "--python", str(RENDER_WRAPPER), "--", "--glb", r.glb_path,
+ "--out", str(out), "--size", "256", "--views", "front_right_34:35:22,top:0:88"],
+ cwd=tmp_ws.root, env=blender_env(), timeout_s=180)
+ assert proc.returncode == 0, proc.stderr[-2000:]
+ manifest = json.loads((out / "renders.json").read_text())
+ assert [v["name"] for v in manifest["views"]] == ["front_right_34", "top"]
+ assert all(Path(v["path"]).stat().st_size > 1000 for v in manifest["views"])
diff --git a/harness/tests/blender_cadquery/test_blender_skeleton.py b/harness/tests/blender_cadquery/test_blender_skeleton.py
new file mode 100644
index 00000000..22900dcf
--- /dev/null
+++ b/harness/tests/blender_cadquery/test_blender_skeleton.py
@@ -0,0 +1,47 @@
+"""Offline tests for the bpy skeleton generator."""
+
+from __future__ import annotations
+
+import ast
+
+from codeverse.contracts.plan import BBox
+from codeverse.languages.blender.lint import lint_blender_source
+from codeverse.languages.blender.skeleton import (
+ blender_skeleton_source,
+ finish_for,
+ instance_centers,
+ write_blender_skeleton,
+)
+
+
+def test_skeleton_parses_lints_and_names_parts(table_plan) -> None:
+ src = blender_skeleton_source(table_plan)
+ ast.parse(src)
+ assert "import codeverse" not in src and "from codeverse" not in src
+ for fn in ("def build_table_top(", "def build_leg(", "def build_shelf(", "def main():"):
+ assert fn in src
+ assert 'name = "TableTop"' in src and 'name = f"Leg_{index}"' in src and 'add_empty("Legs")' in src
+ assert "Z is up, -Y is the FRONT" in src and "[a1]" in src
+ r = lint_blender_source(src)
+ assert r.passed, [f.message for f in r.findings]
+
+
+def test_write_skeleton(tmp_ws, table_plan) -> None:
+ paths = write_blender_skeleton(tmp_ws, table_plan)
+ assert paths == [tmp_ws.src / "model.py"] and paths[0].is_file()
+
+
+def test_instance_centers_symmetry() -> None:
+ bb = BBox(center=(0.2, 0.3, 0.5), extents=(0.1, 0.1, 1.0))
+ assert instance_centers(bb, 1, "none") == [(0.2, 0.3, 0.5)]
+ assert instance_centers(bb, 2, "mirror_x") == [(0.2, 0.3, 0.5), (-0.2, 0.3, 0.5)]
+ four = instance_centers(bb, 4, "mirror_y")
+ assert len(four) == 4 and {(round(x, 3), round(y, 3)) for x, y, _ in four} == {(0.2, -0.3), (-0.2, -0.3), (-0.2, 0.3), (0.2, 0.3)}
+ rad = instance_centers(BBox(center=(0.5, 0.0, 0.1), extents=(0.1, 0.1, 0.1)), 3, "radial")
+ assert len(rad) == 3 and all(abs((x * x + y * y) ** 0.5 - 0.5) < 1e-9 for x, y, _ in rad)
+
+
+def test_finish_for_keywords() -> None:
+ assert finish_for("brushed steel")[2] == 1.0
+ assert finish_for("oak wood")[0] == (0.55, 0.36, 0.20)
+ assert finish_for("something unknown")[0] == (0.6, 0.6, 0.6)
diff --git a/harness/tests/blender_cadquery/test_cadquery_lint.py b/harness/tests/blender_cadquery/test_cadquery_lint.py
new file mode 100644
index 00000000..e3119855
--- /dev/null
+++ b/harness/tests/blender_cadquery/test_cadquery_lint.py
@@ -0,0 +1,63 @@
+"""Offline tests for the cadquery lint."""
+
+from __future__ import annotations
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.languages.cadquery.lint import lint_cadquery_source
+
+GOOD = '''
+import cadquery as cq
+import math
+
+top = cq.Workplane("XY").box(0.5, 0.5, 0.04).translate((0, 0, 0.58))
+result = cq.Assembly(name="Table")
+result.add(top, name="TableTop", color=cq.Color(0.5, 0.3, 0.2))
+'''
+
+
+def _msgs(r, sev=None):
+ return [f.message for f in r.findings if sev is None or f.severity == sev]
+
+
+def test_good_passes() -> None:
+ r = lint_cadquery_source(GOOD)
+ assert r.gate == "lint:cadquery" and r.passed, _msgs(r)
+
+
+def test_missing_result_and_guarded_result() -> None:
+ r = lint_cadquery_source("import cadquery as cq\nx = cq.Workplane().box(1, 1, 1)\n")
+ assert not r.passed and any("module-level `result`" in m for m in _msgs(r, Severity.ERROR))
+ r = lint_cadquery_source("import cadquery as cq\nif __name__ == '__main__':\n result = cq.Workplane().box(1, 1, 1)\n")
+ f = [x for x in r.findings if "result" in x.message][0]
+ assert f.severity == Severity.ERROR and "NOT under" in f.fix_hint
+
+
+def test_forbidden_imports_and_calls() -> None:
+ src = ("import cadquery as cq\nimport os\nfrom OCP.BRepPrimAPI import BRepPrimAPI_MakeBox\nresult = cq.Workplane().box(1, 1, 1)\n"
+ "show_object(result)\ncq.exporters.export(result, 'x.step')\nresult.save('x.step')\nopen('f', 'w')\n")
+ r = lint_cadquery_source(src)
+ e = _msgs(r, Severity.ERROR)
+ assert any("`os`" in m for m in e) and any("`OCP`" in m for m in e)
+ assert any("show_object" in m for m in e) and any("cq.exporters.export" in m for m in e)
+ assert any("result.save" in m for m in e) and any("open()" in m for m in e)
+
+
+def test_pitfalls() -> None:
+ src = ("import cadquery as cq\nimport math\ns = cq.Solid.makeSphere(1)\nw = cq.Workplane().box(1, 1, 1).rotate((0, 0, 0), (0, 0, 1), math.pi / 2)\n"
+ "result = cq.Assembly()\nresult.add(w)\nresult.add(s, name='my_part')\n")
+ r = lint_cadquery_source(src)
+ w, e = _msgs(r, Severity.WARN), _msgs(r, Severity.ERROR)
+ assert any("makeSphere" in m for m in w)
+ assert any("DEGREES" in m for m in e)
+ assert any("without name=" in m for m in w)
+ assert any("not PascalCase" in m and "my_part" in m for m in w)
+
+
+def test_bare_workplane_warns() -> None:
+ r = lint_cadquery_source("import cadquery as cq\nresult = cq.Workplane().box(1, 1, 1)\n")
+ assert r.passed and any("ONE unnamed part" in m for m in _msgs(r, Severity.WARN))
+
+
+def test_syntax_error() -> None:
+ r = lint_cadquery_source("import cadquery as cq\nresult = (\n")
+ assert not r.passed and "SyntaxError" in r.findings[0].message
diff --git a/harness/tests/blender_cadquery/test_cadquery_runtime.py b/harness/tests/blender_cadquery/test_cadquery_runtime.py
new file mode 100644
index 00000000..74dd076e
--- /dev/null
+++ b/harness/tests/blender_cadquery/test_cadquery_runtime.py
@@ -0,0 +1,121 @@
+"""CadQueryRuntime: skeleton + build (real cadquery when importable; fake interpreter otherwise)."""
+
+from __future__ import annotations
+
+import ast
+import json
+import stat
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+from codeverse.languages import get_runtime
+from codeverse.languages.base import LanguageRuntime
+from codeverse.languages.cadquery.lint import lint_cadquery_source
+from codeverse.languages.cadquery.runtime import WRAPPER, CadQueryRuntime
+from codeverse.languages.cadquery.skeleton import cadquery_skeleton_source
+from tests.blender_cadquery.conftest import has_cadquery
+
+needs_cq = pytest.mark.skipif(not has_cadquery(), reason="cadquery not importable")
+
+
+def test_protocol_and_contract() -> None:
+ rt = get_runtime("cadquery")
+ assert isinstance(rt, CadQueryRuntime) and isinstance(rt, LanguageRuntime)
+ assert "cq.Assembly" in rt.contract_doc() and rt.entry_globs == ("src/model.py",)
+ cmd = rt.build_command(__import__("codeverse.workspace", fromlist=["Workspace"]).Workspace("/tmp/x"), seed=1)
+ assert cmd[0] == sys.executable and cmd[1] == str(WRAPPER) and "--seed" in cmd
+
+
+def test_skeleton_source_parses_and_lints(table_plan) -> None:
+ src = cadquery_skeleton_source(table_plan)
+ ast.parse(src)
+ assert "codeverse" not in src
+ assert 'name="TableTop"' in src and 'name=f"Leg_{_i}"' in src and "result = cq.Assembly(" in src
+ assert lint_cadquery_source(src).passed
+
+
+def test_missing_entry(tmp_ws) -> None:
+ r = CadQueryRuntime().build(tmp_ws)
+ assert not r.ok and r.error_type == "MissingEntryFile"
+
+
+def test_fake_python_wrapper_crash(tmp_ws, tmp_path) -> None:
+ fake = tmp_path / "py"
+ fake.write_text("#!/bin/sh\necho 'ImportError: no cadquery' >&2\nexit 1\n")
+ fake.chmod(fake.stat().st_mode | stat.S_IEXEC)
+ (tmp_ws.src / "model.py").write_text("import cadquery as cq\nresult = cq.Workplane().box(1, 1, 1)\n")
+ r = CadQueryRuntime(python=str(fake)).build(tmp_ws, timeout_s=20)
+ assert not r.ok and r.error_type == "WrapperCrash" and "no cadquery" in r.stderr_tail
+
+
+@needs_cq
+def test_skeleton_builds_named_coloured_glb(tmp_ws, table_plan) -> None:
+ trimesh = pytest.importorskip("trimesh")
+ rt = CadQueryRuntime()
+ rt.skeleton(tmp_ws, table_plan)
+ assert rt.lint(tmp_ws).passed
+ t0 = time.monotonic()
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message, r.stderr_tail)
+ assert time.monotonic() - t0 < 60
+ assert set(r.extra_paths) == {"step", "stl"} and Path(r.extra_paths["step"]).stat().st_size > 0
+ scene = trimesh.load(r.glb_path)
+ assert set(scene.graph.nodes_geometry) == {"TableTop", "Shelf", "Leg_0", "Leg_1", "Leg_2", "Leg_3"}
+ lo, hi = scene.bounds
+ assert abs(lo[1]) < 1e-6 and abs(hi[1] - 0.6) < 1e-6 # Y-up, on the ground
+ assert abs(lo[2] + 0.25) < 1e-6 and abs(hi[0] - 0.25) < 1e-6
+ top = scene.geometry[scene.graph["TableTop"][1]]
+ assert top.visual.material.baseColorFactor[0] > top.visual.material.baseColorFactor[2]
+ c = r.census
+ assert c["result_kind"] == "assembly" and c["n_parts"] == 6 and c["tri_count"] == 6 * 12
+ leg = next(p for p in c["parts"] if p["name"] == "Leg_1")
+ assert leg["valid"] and abs(leg["volume_m3"] - 0.04 * 0.04 * 0.56) < 1e-9 and leg["bbox_min"][2] == 0.0
+
+
+@needs_cq
+def test_assembly_with_subassembly_locations_and_errors(tmp_ws) -> None:
+ trimesh = pytest.importorskip("trimesh")
+ src = '''import cadquery as cq
+base = cq.Workplane("XY").box(0.4, 0.4, 0.02).translate((0, 0, 0.01))
+peg = cq.Workplane("XY").cylinder(0.1, 0.02).translate((0, 0, 0.05))
+result = cq.Assembly(name="Board")
+result.add(base, name="Base", color=cq.Color(0.2, 0.2, 0.8))
+pegs = cq.Assembly(name="Pegs", loc=cq.Location(cq.Vector(0, 0, 0.02)))
+pegs.add(peg, name="Peg_0", loc=cq.Location(cq.Vector(0.1, -0.1, 0)), color=cq.Color(1, 0, 0))
+pegs.add(peg, name="Peg_1", loc=cq.Location(cq.Vector(-0.1, 0.1, 0)))
+result.add(pegs, name="Pegs", color=cq.Color(0, 1, 0))
+'''
+ (tmp_ws.src / "model.py").write_text(src)
+ rt = CadQueryRuntime()
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok, (r.error_type, r.error_message)
+ scene = trimesh.load(r.glb_path)
+ assert set(scene.graph.nodes_geometry) == {"Base", "Peg_0", "Peg_1"}
+ p0 = scene.geometry[scene.graph["Peg_0"][1]]
+ lo, hi = p0.bounds
+ # world: x=0.1, y=-0.1 → glb z=+0.1; z from 0.02 (sub-assembly loc) to 0.12
+ assert abs((lo[0] + hi[0]) / 2 - 0.1) < 1e-6 and abs((lo[2] + hi[2]) / 2 - 0.1) < 1e-6
+ assert abs(lo[1] - 0.02) < 1e-6 and abs(hi[1] - 0.12) < 1e-6
+ assert list(p0.visual.material.baseColorFactor[:3]) == [255, 0, 0]
+ p1 = scene.geometry[scene.graph["Peg_1"][1]]
+ assert list(p1.visual.material.baseColorFactor[:3]) == [0, 255, 0] # inherited from parent assembly
+
+ # error mapping: bad fillet → OCC error mapped to line with hint
+ (tmp_ws.src / "model.py").write_text("import cadquery as cq\n\nresult = cq.Workplane('XY').box(0.1, 0.1, 0.01).edges('|Z').fillet(0.2)\n")
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert not r.ok and r.error_line == 3 and "fillet" in r.error_message.lower()
+ # missing result
+ (tmp_ws.src / "model.py").write_text("import cadquery as cq\nx = cq.Workplane('XY').box(1, 1, 1)\n")
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert not r.ok and r.error_type == "MissingResult"
+ # bare workplane → single node 'Object' + warning
+ (tmp_ws.src / "model.py").write_text("import cadquery as cq\nresult = cq.Workplane('XY').box(1, 1, 1)\n")
+ r = rt.build(tmp_ws, timeout_s=120)
+ assert r.ok and r.census["result_kind"] == "single"
+ assert trimesh.load(r.glb_path).graph.nodes_geometry == ["Object"]
+ assert any("bare Workplane" in w for w in r.census["build_report"]["warnings"])
+ build_json = json.loads((tmp_ws.artifacts / "build.json").read_text())
+ assert build_json["ok"] is True
diff --git a/harness/tests/blender_cadquery/test_common.py b/harness/tests/blender_cadquery/test_common.py
new file mode 100644
index 00000000..beca7afe
--- /dev/null
+++ b/harness/tests/blender_cadquery/test_common.py
@@ -0,0 +1,87 @@
+"""Unit tests for codeverse.languages._common (offline)."""
+
+from __future__ import annotations
+
+import json
+import sys
+import time
+from pathlib import Path
+
+from codeverse.languages._common import (
+ ProcResult,
+ compose_build_result,
+ run_subprocess,
+ strip_blender_noise,
+ tail,
+ write_json_atomic,
+)
+
+
+def test_run_subprocess_captures_output(tmp_path: Path) -> None:
+ r = run_subprocess([sys.executable, "-c", "import sys; print('out'); print('err', file=sys.stderr); sys.exit(3)"],
+ cwd=tmp_path, timeout_s=10)
+ assert r.returncode == 3 and r.stdout.strip() == "out" and r.stderr.strip() == "err" and not r.timed_out
+
+
+def test_run_subprocess_timeout_kills_group(tmp_path: Path) -> None:
+ code = "import subprocess, sys, time; p = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(30)']); print(p.pid, flush=True); time.sleep(30)"
+ t0 = time.monotonic()
+ r = run_subprocess([sys.executable, "-c", code], cwd=tmp_path, timeout_s=1.5)
+ assert r.timed_out and time.monotonic() - t0 < 6
+ child_pid = int(r.stdout.strip())
+ time.sleep(0.3)
+ assert not Path(f"/proc/{child_pid}").exists() or "zombie" in (Path(f"/proc/{child_pid}/status").read_text().lower())
+
+
+def test_tail_limits() -> None:
+ text = "\n".join(str(i) for i in range(100))
+ t = tail(text, max_lines=5)
+ assert t.splitlines() == ["95", "96", "97", "98", "99"]
+ assert len(tail("x" * 10_000, max_chars=100)) == 100
+
+
+def test_strip_blender_noise() -> None:
+ raw = "Blender 5.0.1 (hash x)\nRead prefs: ...\n12:00:00 | INFO: Starting glTF 2.0 export\nTraceback (most recent call last):\n boom\nBlender quit"
+ assert strip_blender_noise(raw).splitlines() == ["Traceback (most recent call last):", " boom"]
+
+
+def _proc(**kw) -> ProcResult:
+ base = dict(returncode=0, stdout="", stderr="", timed_out=False, duration_ms=10)
+ base.update(kw)
+ return ProcResult(**base)
+
+
+def test_compose_timeout(tmp_path: Path) -> None:
+ r = compose_build_result(language="blender", proc=_proc(timed_out=True, returncode=-9), build_json=tmp_path / "b.json",
+ census_json=tmp_path / "c.json", glb_path=tmp_path / "o.glb", extra_paths={})
+ assert not r.ok and r.error_type == "BuildTimeout"
+
+
+def test_compose_wrapper_crash(tmp_path: Path) -> None:
+ r = compose_build_result(language="blender", proc=_proc(returncode=2, stderr="Traceback: bad"), build_json=tmp_path / "b.json",
+ census_json=tmp_path / "c.json", glb_path=tmp_path / "o.glb", extra_paths={})
+ assert not r.ok and r.error_type == "WrapperCrash" and "bad" in r.stderr_tail
+
+
+def test_compose_ok_requires_glb(tmp_path: Path) -> None:
+ b = tmp_path / "build.json"
+ write_json_atomic(b, {"ok": True, "error_type": "", "error_message": "", "duration_ms": 42, "warnings": ["w"]})
+ write_json_atomic(tmp_path / "census.json", {"tri_count": 12})
+ r = compose_build_result(language="blender", proc=_proc(), build_json=b, census_json=tmp_path / "census.json",
+ glb_path=tmp_path / "o.glb", extra_paths={"stl": tmp_path / "o.stl"})
+ assert not r.ok and r.error_type == "ExportEmpty"
+ (tmp_path / "o.glb").write_bytes(b"glTF" + b"\0" * 20)
+ (tmp_path / "o.stl").write_bytes(b"solid")
+ r = compose_build_result(language="blender", proc=_proc(), build_json=b, census_json=tmp_path / "census.json",
+ glb_path=tmp_path / "o.glb", extra_paths={"stl": tmp_path / "o.stl", "blend": tmp_path / "nope.blend"})
+ assert r.ok and r.glb_path == str(tmp_path / "o.glb") and r.duration_ms == 42
+ assert r.extra_paths == {"stl": str(tmp_path / "o.stl")}
+ assert r.census["tri_count"] == 12 and r.census["build_report"]["warnings"] == ["w"]
+
+
+def test_compose_script_error_fields(tmp_path: Path) -> None:
+ b = tmp_path / "build.json"
+ b.write_text(json.dumps({"ok": False, "error_type": "IndexError", "error_message": "boom", "error_file": "model.py", "error_line": 15}))
+ r = compose_build_result(language="blender", proc=_proc(), build_json=b, census_json=tmp_path / "none.json",
+ glb_path=tmp_path / "o.glb", extra_paths={})
+ assert not r.ok and r.error_type == "IndexError" and r.error_line == 15 and r.error_file == "model.py"
diff --git a/harness/tests/conftest.py b/harness/tests/conftest.py
new file mode 100644
index 00000000..23b8184a
--- /dev/null
+++ b/harness/tests/conftest.py
@@ -0,0 +1,15 @@
+"""Shared pytest fixtures."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from codeverse.workspace import Workspace
+
+
+def tmp_ws(tmp_path: Path) -> Workspace:
+ """A fresh, git-initialised workspace under a temp dir."""
+ return Workspace(tmp_path / "run").create()
diff --git a/harness/tests/core/test_contracts.py b/harness/tests/core/test_contracts.py
new file mode 100644
index 00000000..eb368eed
--- /dev/null
+++ b/harness/tests/core/test_contracts.py
@@ -0,0 +1,109 @@
+"""Contract + convention tests (the spine)."""
+
+from __future__ import annotations
+
+import math
+
+import pytest
+from pydantic import ValidationError
+
+from codeverse.contracts import (
+ ArticulatedPlan,
+ BBox,
+ Budget,
+ ChatMessage,
+ JointPlan,
+ Language,
+ PartPlan,
+ ScenePlan,
+ Spec,
+ StaticPlan,
+ Track,
+ Usage,
+)
+from codeverse.contracts.plan import AssetPlan, CameraPlan, ZonePlan
+from codeverse.conventions import OBJECT_VIEWS, slugify, to_pascal, to_snake
+
+
+def _box(cx=0.0, cy=0.0, cz=0.5, ex=1.0, ey=1.0, ez=1.0) -> BBox:
+ return BBox(center=(cx, cy, cz), extents=(ex, ey, ez))
+
+
+def test_names_normalise_consistently():
+ assert to_snake("SeatCushion") == "seat_cushion"
+ assert to_snake("seat cushion") == "seat_cushion"
+ assert to_snake("LPCompressor") == "lp_compressor"
+ assert to_pascal("seat_cushion") == "SeatCushion"
+ assert to_pascal(to_snake("Leg_0")) == "Leg0"
+ assert slugify("A mid-century wooden dining chair!") == "a_mid_century_wooden_dining_chair"
+
+
+def test_view_presets_unique():
+ names = [v.name for v in OBJECT_VIEWS]
+ assert len(names) == len(set(names)) == 8
+
+
+def test_spec_rejects_language_outside_track():
+ with pytest.raises(ValidationError):
+ Spec(id="x", track=Track.SCENE, language=Language.BLENDER, prompt="p")
+ s = Spec(id="x", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="p")
+ assert s.budget == Budget()
+
+
+def test_usage_addition_sums_cost():
+ u = Usage(model="m", input_tokens=10, cost_usd=0.1) + Usage(model="m", output_tokens=5, cost_usd=0.2)
+ assert u.input_tokens == 10 and u.output_tokens == 5 and math.isclose(u.cost_usd, 0.3)
+
+
+def test_static_plan_validates_attach_and_duplicates():
+ with pytest.raises(ValidationError):
+ StaticPlan(object_name="o", summary="s", overall_bbox=_box(),
+ parts=[PartPlan(name="Seat", role="r", description="d", bbox=_box()),
+ PartPlan(name="seat", role="r", description="d", bbox=_box())])
+ with pytest.raises(ValidationError):
+ StaticPlan(object_name="o", summary="s", overall_bbox=_box(),
+ parts=[PartPlan(name="Seat", role="r", description="d", bbox=_box(), attach_to="Ghost")])
+
+
+def test_articulated_plan_requires_single_root_tree_and_sane_joints():
+ parts = [PartPlan(name="Base", role="r", description="d", bbox=_box()),
+ PartPlan(name="Door", role="r", description="d", bbox=_box(0.4, -0.5)),
+ PartPlan(name="Handle", role="r", description="d", bbox=_box(0.45, -0.55, 0.5, 0.05, 0.05, 0.1))]
+ good = ArticulatedPlan(object_name="cab", summary="s", overall_bbox=_box(), parts=parts, root_link="Base",
+ joints=[JointPlan(name="hinge", type="revolute", parent="Base", child="Door", axis=(0, 0, 2),
+ pivot=(-0.5, -0.5, 0.5), lower=0, upper=1.5, rest=0.3),
+ JointPlan(name="h2", type="fixed", parent="Door", child="Handle", axis=(0, 0, 1),
+ pivot=(0, 0, 0))])
+ assert math.isclose(sum(a * a for a in good.joints[0].axis), 1.0, abs_tol=1e-6) # axis normalised
+ with pytest.raises(ValidationError): # Handle not connected
+ ArticulatedPlan(object_name="cab", summary="s", overall_bbox=_box(), parts=parts, root_link="Base",
+ joints=[good.joints[0]])
+ with pytest.raises(ValidationError): # rest outside limits
+ JointPlan(name="j", type="revolute", parent="A", child="B", axis=(0, 0, 1), pivot=(0, 0, 0), lower=0, upper=1, rest=2)
+
+
+def test_scene_plan_zone_contents_must_be_assets():
+ z = ZonePlan(name="Pond", description="d", bbox=_box(), contents=["Lantern"])
+ cam = CameraPlan(name="c", position=(0, 1.6, 5), look_at=(0, 0, 0))
+ with pytest.raises(ValidationError):
+ ScenePlan(title="t", summary="s", setting="x", bounds=_box(), environment="e", zones=[z], cameras=[cam])
+ ok = ScenePlan(title="t", summary="s", setting="x", bounds=_box(), environment="e", zones=[z], cameras=[cam],
+ assets=[AssetPlan(name="Lantern", kind="threejs", description="d", approx_size_m=(0.3, 0.3, 1.2))])
+ assert ok.zones[0].contents == ["Lantern"]
+
+
+def test_chat_message_helpers():
+ m = ChatMessage.user("hi")
+ assert m.text == "hi" and m.role == "user"
+
+
+def test_workspace_git_roundtrip(tmp_ws):
+ (tmp_ws.src / "a.py").write_text("x = 1\n")
+ c0 = tmp_ws.commit("r0")
+ (tmp_ws.src / "a.py").write_text("x = 2\n")
+ changed = tmp_ws.changed_files()
+ assert [c.path for c in changed] == ["src/a.py"]
+ c1 = tmp_ws.commit("r1")
+ assert c0 != c1
+ tmp_ws.restore(c0)
+ assert (tmp_ws.src / "a.py").read_text() == "x = 1\n"
diff --git a/harness/tests/flywheel_cli/__init__.py b/harness/tests/flywheel_cli/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/flywheel_cli/conftest.py b/harness/tests/flywheel_cli/conftest.py
new file mode 100644
index 00000000..1a2dd040
--- /dev/null
+++ b/harness/tests/flywheel_cli/conftest.py
@@ -0,0 +1,127 @@
+"""Shared fixtures: a synthetic run (git repo with two commits, tiny PNGs,
+record.json with two judged rounds) — no models, Blender or node required."""
+
+from __future__ import annotations
+
+import struct
+import zlib
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+
+from codeverse.contracts.artifacts import (
+ BuildResult,
+ GateFinding,
+ GateReport,
+ RenderSet,
+ RenderView,
+ Severity,
+)
+from codeverse.contracts.common import Backends, Language, Track, Usage
+from codeverse.contracts.judgment import ImprovementItem, JudgeIssue, Judgment
+from codeverse.contracts.run import RoundRecord, RunRecord, RunStatus
+from codeverse.contracts.spec import Spec
+from codeverse.workspace import Workspace
+
+
+def tiny_png(path: Path, rgb: tuple[int, int, int] = (200, 30, 30), size: int = 4) -> Path:
+ """Write a valid size×size RGB PNG without PIL."""
+ raw = b"".join(b"\x00" + bytes(rgb) * size for _ in range(size))
+
+ def chunk(tag: bytes, data: bytes) -> bytes:
+ return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
+
+ png = (b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", size, size, 8, 2, 0, 0, 0))
+ + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b""))
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(png)
+ return path
+
+
+def _judgment(score: float, passed: bool, plan: list[str]) -> Judgment:
+ return Judgment(
+ rubric="static_object_v1", judge_backend="gemini:gemini-3.7-flash",
+ scores={"fidelity": score, "geometry": score}, overall=score, passed=passed, summary=f"score {score}",
+ issues=[JudgeIssue(target="Leg", kind="geometry", severity="major", detail="legs too thin")] if not passed else [],
+ improvement_plan=[ImprovementItem(target="Leg", kind="geometry", instruction=s, priority=1) for s in plan],
+ acceptance_results={"a1": passed}, usage=Usage(backend="gemini", model="gemini-3.7-flash", cost_usd=0.01),
+ )
+
+
+def make_fake_run(
+ runs_dir: Path, slug: str = "wooden_chair_ab12cd34", *, prompt: str = "a wooden dining chair",
+ language: Language = Language.BLENDER, generator: str = "api-agent:gemini:gemini-3.7-flash",
+ scores: tuple[float, float] = (0.55, 0.80), with_repair: bool = False, code_v2: str | None = None,
+) -> tuple[Workspace, RunRecord]:
+ ws = Workspace(runs_dir / slug).create()
+ track = Track.SCENE if language is Language.SCENE_THREEJS else (
+ Track.ARTICULATED_OBJECT if language is Language.URDF_BLENDER else Track.STATIC_OBJECT)
+ spec = Spec(id=slug, track=track, language=language, prompt=prompt, backends=Backends(generator=generator))
+ ws.write_json(ws.spec_path, spec)
+ entry = {"blender": "src/model.py", "cadquery": "src/model.py", "urdf_blender": "src/model.py",
+ "threejs": "src/object.js", "scene_threejs": "src/scene.js"}[language.value]
+ e = ws.root / entry
+ e.parent.mkdir(parents=True, exist_ok=True)
+ e.write_text("# round 0\nimport bpy # comment\n\nbpy.ops.mesh.primitive_cube_add(size=1.0)\n")
+ if language is Language.URDF_BLENDER:
+ (ws.src / "robot.urdf").write_text("<robot name='x'><link name='base'/></robot>")
+ c0 = ws.commit("round 0")
+ rounds = []
+ for i, sc in enumerate(scores):
+ if i == 1:
+ e.write_text(code_v2 or "# round 1\nimport bpy\n\nbpy.ops.mesh.primitive_cube_add(size=2.0)\n")
+ (ws.src / "parts").mkdir(exist_ok=True)
+ (ws.src / "parts" / "leg.py").write_text("LEG = 0.04\n")
+ commit = c0 if i == 0 else ws.commit(f"round {i}")
+ rd = ws.renders_dir(i)
+ views = [RenderView(name=n, path=str(tiny_png(rd / f"view_{n}.png"))) for n in ("front", "top")]
+ sheet = tiny_png(rd / "sheet.png", (0, 0, 200))
+ rounds.append(RoundRecord(
+ index=i, kind="baseline" if i == 0 else "refine", commit=commit, agent_backend=generator,
+ instructions=[] if i == 0 else ["thicken the legs"],
+ build=BuildResult(ok=True, language=language.value, glb_path=str(ws.artifacts / "object.glb")),
+ gates=[GateReport(gate="lint", passed=True)],
+ renders=RenderSet(views=views, contact_sheet=str(sheet)),
+ judgment=_judgment(sc, sc >= 0.75, ["thicken the legs", "add a back rail"]),
+ usage=Usage(backend="gemini", model="gemini-3.7-flash", input_tokens=1000, output_tokens=500, cost_usd=0.02),
+ duration_s=12.0,
+ ))
+ if with_repair:
+ e.write_text("import bpy\nbpy.ops.mesh.primitive_cube_add(size=\n")
+ bad = ws.commit("broken")
+ rounds.append(RoundRecord(
+ index=len(rounds), kind="refine", commit=bad,
+ build=BuildResult(ok=False, language=language.value, error_type="SyntaxError",
+ error_message="unexpected EOF", error_file="src/model.py", error_line=2,
+ stderr_tail="SyntaxError: unexpected EOF while parsing"),
+ gates=[GateReport(gate="lint", passed=False, findings=[GateFinding(gate="lint", severity=Severity.ERROR, message="syntax")])],
+ ))
+ e.write_text("import bpy\nbpy.ops.mesh.primitive_cube_add(size=3.0)\n")
+ fixed = ws.commit("repair")
+ rounds.append(RoundRecord(
+ index=len(rounds), kind="repair", commit=fixed, instructions=["fix the syntax error at line 2"],
+ build=BuildResult(ok=True, language=language.value),
+ ))
+ (ws.artifacts / "object.glb").write_bytes(b"glTF\x02\x00\x00\x00" + b"\0" * 16)
+ rec = RunRecord(spec=spec, workspace=str(ws.root), status=RunStatus.PASSED if scores[-1] >= 0.75 else RunStatus.PLATEAU,
+ rounds=rounds, best_round=1, baseline_score=scores[0], final_score=scores[1],
+ total_usage=Usage(cost_usd=0.06, input_tokens=2000, output_tokens=1000),
+ finished_at=datetime.now(UTC),
+ environment={"blender": "Blender 5.0.1"})
+ ws.write_json(ws.record_path, rec)
+ return ws, rec
+
+
+def fake_run(tmp_path: Path) -> tuple[Workspace, RunRecord]:
+ return make_fake_run(tmp_path / "runs")
+
+
+def runs_dir(tmp_path: Path) -> Path:
+ d = tmp_path / "runs"
+ make_fake_run(d)
+ make_fake_run(d, "wooden_chair_codex", generator="codex:gpt-5.6-sol", scores=(0.5, 0.6), with_repair=True)
+ make_fake_run(d, "lamp_three", prompt="a desk lamp", language=Language.THREEJS, scores=(0.7, 0.72))
+ return d
diff --git a/harness/tests/flywheel_cli/test_bench.py b/harness/tests/flywheel_cli/test_bench.py
new file mode 100644
index 00000000..a6e8f093
--- /dev/null
+++ b/harness/tests/flywheel_cli/test_bench.py
@@ -0,0 +1,81 @@
+"""Bench runner + report with a fake track (offline)."""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+REPO = Path(__file__).resolve().parents[2]
+if str(REPO) not in sys.path:
+ sys.path.insert(0, str(REPO))
+
+from bench.report import build_report, load_results # noqa: E402
+from bench.run_bench import Battery, BenchOptions, run_battery # noqa: E402
+from codeverse.contracts.run import RunRecord, RunStatus # noqa: E402
+from codeverse.workspace import Workspace # noqa: E402
+from tests.flywheel_cli.conftest import make_fake_run # noqa: E402
+
+BATTERIES = sorted((REPO / "bench" / "prompts").glob("*.yaml"))
+
+
[email protected]("path", BATTERIES, ids=[p.stem for p in BATTERIES])
+def test_batteries_are_valid(path: Path):
+ b = Battery.load(path)
+ ids = [p.id for p in b.prompts]
+ assert len(ids) == len(set(ids))
+ tiers = {p.tier for p in b.prompts}
+ assert tiers <= {"easy", "medium", "hard"} and len(tiers) == 3
+ assert all(p.must_have for p in b.prompts)
+ expected = {"static_objects_v1": 24, "articulated_v1": 12, "scenes_v1": 12}
+ assert len(b.prompts) == expected[b.name]
+
+
+def _fake_run_fn(scores_by_id: dict[str, tuple[float, float]], fail_ids: set[str] = frozenset()):
+ def run(spec, ws: Workspace, resume: bool) -> RunRecord:
+ pid = spec.id.split("/")[-1]
+ if pid in fail_ids:
+ raise RuntimeError("boom")
+ # reuse the synthetic record builder in the bench workspace (slug = prompt id)
+ _ws, rec = make_fake_run(ws.root.parent, ws.root.name, prompt=spec.prompt, language=spec.language,
+ scores=scores_by_id.get(pid, (0.5, 0.7)))
+ rec.spec = spec
+ ws.write_json(ws.spec_path, spec)
+ rec.status = RunStatus.PASSED if rec.final_score and rec.final_score >= 0.75 else RunStatus.PLATEAU
+ ws.write_json(ws.record_path, rec)
+ return rec
+ return run
+
+
+def test_run_battery_resume_and_report(tmp_path: Path):
+ battery = REPO / "bench" / "prompts" / "static_objects_v1.yaml"
+ out = tmp_path / "bench_out"
+ scores = {"furn_easy_stool": (0.6, 0.85), "furn_med_dining_chair": (0.5, 0.7), "furn_hard_rolltop_desk": (0.4, 0.6)}
+ opts = BenchOptions(parallel=2, limit=4, judge="gemini:gemini-3.7-flash", generator="api-agent:gemini:gemini-3.7-flash")
+ res = run_battery(battery, out, opts, run_fn=_fake_run_fn(scores, fail_ids={"veh_easy_toy_car"}))
+ assert len(res) == 4
+ by_id = {r.id: r for r in res}
+ assert by_id["furn_easy_stool"].score_final == 0.85 and by_id["furn_easy_stool"].passed is True
+ assert by_id["veh_easy_toy_car"].status == "error" and "boom" in by_id["veh_easy_toy_car"].errors
+ assert (out / "results.csv").is_file() and len(load_results(out)) == 4
+ assert (out / "runs" / "furn_easy_stool" / "spec.json").is_file()
+ spec = json.loads((out / "runs" / "furn_easy_stool" / "spec.json").read_text())
+ assert spec["backends"]["judge"] == "gemini:gemini-3.7-flash" and "bench" in spec["tags"]
+ # resume: already-done prompts are not re-run; the failed one is re-run (it is in results → also skipped)
+ calls = []
+
+ def counting(spec, ws, resume):
+ calls.append(spec.id)
+ return _fake_run_fn(scores)(spec, ws, resume)
+
+ res2 = run_battery(battery, out, BenchOptions(parallel=1, limit=5), run_fn=counting)
+ assert calls == ["static_objects_v1/veh_med_pickup"] and len(res2) == 5
+ rep = build_report(out)
+ assert rep.n == 5 and (out / "report.md").is_file() and (out / "report.html").is_file()
+ tiers = {g.group: g for g in rep.by_tier}
+ assert tiers["easy"].n == 2 and tiers["easy"].final_mean == pytest.approx(0.85) # toy car errored → unscored
+ assert rep.overall is not None and rep.overall.errors == 1
+ assert "| furn_easy_stool | easy |" in rep.markdown
+ assert (out / "report_assets").is_dir() and any((out / "report_assets").iterdir())
diff --git a/harness/tests/flywheel_cli/test_captions.py b/harness/tests/flywheel_cli/test_captions.py
new file mode 100644
index 00000000..6502c918
--- /dev/null
+++ b/harness/tests/flywheel_cli/test_captions.py
@@ -0,0 +1,87 @@
+"""Captioner: fake ChatModel (offline) + one optional live Gemini call."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from codeverse.contracts.chat import ChatRequest, ChatResponse, ImagePart
+from codeverse.contracts.common import Usage
+from codeverse.flywheel.captions import CaptionError, Captions, caption_sample, validate_captions
+from codeverse.flywheel.record import load_record
+
+GOOD = {
+ "detailed": "A four-legged wooden dining chair with a flat square seat and a tall slatted backrest.",
+ "instruction": "Write a Blender Python script that builds a simple wooden dining chair with four legs and a slatted back.",
+ "factory": "Create a box for the seat, four tapered box legs under its corners, two uprights and three horizontal slats for the back, then apply a wood material.",
+}
+
+
+class FakeModel:
+ provider, model = "fake", "fake"
+
+ def __init__(self, replies):
+ self.replies = list(replies)
+ self.requests: list[ChatRequest] = []
+
+ @property
+ def id(self):
+ return "fake:fake"
+
+ def supports_vision(self):
+ return True
+
+ def generate(self, request: ChatRequest) -> ChatResponse:
+ self.requests.append(request)
+ data = self.replies.pop(0)
+ return ChatResponse(text=json.dumps(data), parsed=data, usage=Usage(cost_usd=0.001))
+
+
+def test_caption_sample_stores_and_writes(fake_run):
+ ws, rec = fake_run
+ m = FakeModel([GOOD])
+ caps = caption_sample(ws, rec, "fake:fake", model=m)
+ assert caps.detailed.startswith("A four-legged")
+ req = m.requests[0]
+ assert req.response_schema is not None and "Blender Python script" in req.system
+ imgs = [p for p in req.messages[0].parts if isinstance(p, ImagePart)]
+ assert len(imgs) == 3 # sheet + 2 views
+ assert "round 1" in req.messages[0].text # best-round code
+ assert (ws.root / "captions.json").is_file()
+ again = load_record(ws)
+ assert again.extra["captions"]["factory"] == GOOD["factory"]
+ assert again.extra["captions"]["provenance"]["captioner"] == "fake:fake"
+ assert again.extra["captions"]["provenance"]["cost_usd"] == pytest.approx(0.001)
+
+
+def test_caption_retry_then_fail(fake_run):
+ ws, rec = fake_run
+ bad = dict(GOOD, detailed="Made with bpy.ops primitives: a chair with four legs and a backrest.")
+ m = FakeModel([bad, GOOD])
+ caps = caption_sample(ws, rec, "fake:fake", model=m)
+ assert caps.detailed == GOOD["detailed"] and len(m.requests) == 2
+ assert "bpy" in m.requests[1].messages[-1].text
+ m2 = FakeModel([bad, bad])
+ with pytest.raises(CaptionError):
+ caption_sample(ws, rec, "fake:fake", model=m2)
+
+
+def test_validate_rules():
+ from codeverse.contracts.common import Language
+
+ c = Captions(**GOOD)
+ assert validate_captions(c, Language.BLENDER) == []
+ c2 = Captions(**dict(GOOD, instruction="Please model a wooden chair with four legs for me."))
+ assert any("target language" in p for p in validate_captions(c2, Language.BLENDER))
+
+
+def test_caption_live_gemini(fake_run):
+ from codeverse.config import get_settings
+
+ if not get_settings().gemini_api_keys:
+ pytest.skip("no gemini keys")
+ ws, rec = fake_run
+ caps = caption_sample(ws, rec, "gemini:gemini-3.7-flash")
+ assert len(caps.detailed) > 20 and "blender" in caps.instruction.lower()
diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.py
new file mode 100644
index 00000000..8112ccf5
--- /dev/null
+++ b/harness/tests/flywheel_cli/test_cli.py
@@ -0,0 +1,88 @@
+"""CLI tests (typer CliRunner, offline): make --no-run, status, flywheel, doctor pieces, tools list."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from typer.testing import CliRunner
+
+from codeverse.cli import _common as C
+from codeverse.cli.main import app
+from codeverse.contracts.spec import Spec
+
+runner = CliRunner()
+
+
+def test_help_and_version():
+ r = runner.invoke(app, ["--help"])
+ assert r.exit_code == 0 and "flywheel" in r.output and "doctor" in r.output
+ r = runner.invoke(app, ["--version"])
+ assert r.exit_code == 0 and "c3v" in r.output
+
+
+def test_make_no_run_creates_valid_workspace(tmp_path: Path):
+ runs = tmp_path / "runs"
+ r = runner.invoke(app, ["make", "a wooden dining chair", "--track", "static_object", "--language", "blender",
+ "--runs-dir", str(runs), "--no-run", "--dim", "width=0.5", "--must", "four legs",
+ "--rounds", "2", "--max-usd", "1.5", "--generator", "gemini-cli:gemini-3.7-flash"])
+ assert r.exit_code == 0, r.output
+ dirs = [d for d in runs.iterdir() if d.is_dir()]
+ assert len(dirs) == 1
+ ws = dirs[0]
+ assert ws.name.startswith("a_wooden_dining_chair_") and (ws / "spec.json").is_file() and (ws / ".git").is_dir()
+ spec = Spec.model_validate_json((ws / "spec.json").read_text())
+ assert spec.constraints.dimensions_m == {"width": 0.5} and spec.constraints.must_have == ["four legs"]
+ assert spec.budget.max_rounds == 2 and spec.budget.max_usd == 1.5
+ assert spec.backends.generator == "gemini-cli:gemini-3.7-flash"
+ assert (ws / "src").is_dir() and (ws / "artifacts" / "renders").is_dir()
+ # same prompt again → same slug → refuse without --force
+ r2 = runner.invoke(app, ["make", "a wooden dining chair", "--runs-dir", str(runs), "--no-run"])
+ assert r2.exit_code == 1 and "already exists" in (r2.output + str(r2.stderr if hasattr(r2, "stderr") else ""))
+ r3 = runner.invoke(app, ["make", "a wooden dining chair", "--runs-dir", str(runs), "--no-run", "--force"])
+ assert r3.exit_code == 0
+ # invalid language/track combination → typed error
+ r4 = runner.invoke(app, ["make", "x", "--track", "scene", "--language", "blender", "--runs-dir", str(runs), "--no-run", "--slug", "bad"])
+ assert r4.exit_code == 1
+
+
+def test_status_on_fake_run(runs_dir: Path):
+ r = runner.invoke(app, ["status", "wooden_chair_ab12cd34", "--runs-dir", str(runs_dir)])
+ assert r.exit_code == 0, r.output
+ assert "passed" in r.output and "0.800" in r.output and "rounds" in r.output
+ r = runner.invoke(app, ["status", "nope", "--runs-dir", str(runs_dir)])
+ assert r.exit_code == 1
+
+
+def test_flywheel_commands(runs_dir: Path, tmp_path: Path):
+ out = tmp_path / "ds"
+ r = runner.invoke(app, ["flywheel", "export", str(runs_dir), str(out), "--pack"])
+ assert r.exit_code == 0, r.output
+ assert (out / "metadata.parquet").is_file() and (out / "samples-000.tar").is_file()
+ r = runner.invoke(app, ["flywheel", "pairs", str(runs_dir), str(tmp_path / "p.jsonl")])
+ assert r.exit_code == 0 and "pairs" in r.output
+ r = runner.invoke(app, ["flywheel", "index", str(runs_dir), str(tmp_path / "i.sqlite")])
+ assert r.exit_code == 0 and "indexed 3 runs" in r.output
+ r = runner.invoke(app, ["flywheel", "dedupe", str(out), "--no-mesh"])
+ assert r.exit_code == 0 and "3 samples" in r.output
+
+
+def test_tools_list_and_unknown(tmp_path: Path):
+ r = runner.invoke(app, ["tools", "list"])
+ # spatial tools may or may not be installed yet; either a table or a clear message, never a traceback
+ assert r.exit_code in (0, 2), r.output
+ assert "Traceback" not in r.output
+
+
+def test_lazy_import_message():
+ with pytest.raises(C.CliError):
+ C.lazy("codeverse.definitely_missing_module")
+
+
+def test_doctor_json(tmp_path: Path):
+ r = runner.invoke(app, ["doctor", "--no-gpu", "--json"])
+ assert r.exit_code in (0, 1), r.output
+ rows = json.loads(r.output[r.output.index("["):])
+ checks = {row["check"] for row in rows}
+ assert {"python", "python deps", "blender", "node", "three", "gemini keys", "git", "mcp"} <= checks
diff --git a/harness/tests/flywheel_cli/test_flywheel.py b/harness/tests/flywheel_cli/test_flywheel.py
new file mode 100644
index 00000000..70ab1acd
--- /dev/null
+++ b/harness/tests/flywheel_cli/test_flywheel.py
@@ -0,0 +1,230 @@
+"""Unit tests for flywheel record / export / pack / pairs / dedupe / index (offline)."""
+
+from __future__ import annotations
+
+import io
+import json
+import sqlite3
+import tarfile
+from pathlib import Path
+
+import pytest
+
+from codeverse.contracts.run import RunRecord
+from codeverse.flywheel import _git
+from codeverse.flywheel.dedupe import (
+ DedupeItem,
+ MeshFingerprint,
+ code_fingerprint,
+ near_duplicates,
+ normalise_code,
+)
+from codeverse.flywheel.export import export_samples
+from codeverse.flywheel.index import build_index, round_curve, summary, top_runs
+from codeverse.flywheel.pack import pack_samples, verify_locators
+from codeverse.flywheel.pairs import build_pairs
+from codeverse.flywheel.record import (
+ RecordError,
+ best_round_index,
+ finalize_record,
+ iter_runs,
+ load_record,
+)
+from codeverse.workspace import Workspace
+
+# --------------------------------------------------------------------------- record
+
+
+def test_finalize_and_load_record(fake_run):
+ ws, rec = fake_run
+ rec.best_round = None
+ rec.final_score = None
+ rec.environment = {}
+ path = finalize_record(ws, rec)
+ assert path == ws.record_path and path.is_file()
+ loaded = load_record(ws)
+ assert loaded.best_round == 1 and loaded.final_score == 0.80 and loaded.baseline_score == 0.55
+ assert loaded.environment["python"] and loaded.environment["codeverse"]
+ assert "three" in loaded.environment and "node" in loaded.environment
+ assert len(loaded.extra["rounds_summary"]) == 2
+ assert loaded.extra["rounds_summary"][1]["score"] == 0.80
+
+
+def test_best_round_fallbacks(fake_run):
+ ws, rec = fake_run
+ rec.best_round = None
+ assert best_round_index(rec) == 1
+ for r in rec.rounds:
+ r.judgment = None
+ assert best_round_index(rec) == 1 # last built round
+ rec.rounds = []
+ assert best_round_index(rec) is None
+
+
+def test_iter_runs_and_errors(runs_dir: Path):
+ (runs_dir / "broken").mkdir()
+ (runs_dir / "broken" / "record.json").write_text("{not json")
+ with pytest.raises(RecordError):
+ list(iter_runs(runs_dir))
+ bad = []
+ runs = list(iter_runs(runs_dir, on_error=lambda d, e: bad.append(d.name)))
+ assert len(runs) == 3 and bad == ["broken"]
+
+
+# --------------------------------------------------------------------------- git helpers
+
+
+def test_git_tree_at_commit(fake_run):
+ ws, rec = fake_run
+ c0, c1 = rec.rounds[0].commit, rec.rounds[1].commit
+ t0 = _git.read_tree_at(ws, c0)
+ t1 = _git.read_tree_at(ws, c1)
+ assert set(t0) == {"src/model.py"}
+ assert set(t1) == {"src/model.py", "src/parts/leg.py"}
+ assert b"round 0" in t0["src/model.py"] and b"round 1" in t1["src/model.py"]
+ with pytest.raises(_git.GitReadError):
+ _git.read_tree_at(ws, "deadbeef")
+
+
+# --------------------------------------------------------------------------- export + pack
+
+
+def test_export_samples(runs_dir: Path, tmp_path: Path):
+ out = tmp_path / "dataset"
+ rep = export_samples(runs_dir, out)
+ assert rep.n_runs == 3 and rep.n_exported == 3 and not rep.skipped
+ sdir = out / "static_object" / "blender" / "wooden_chair_ab12cd34"
+ assert (sdir / "code.py").read_text().startswith("# round 1") # best round = 1
+ assert (sdir / "src" / "parts" / "leg.py").is_file()
+ meta = json.loads((sdir / "meta.json").read_text())
+ assert meta["id"] == "3dcodeverse/static_object/blender/wooden_chair_ab12cd34"
+ assert meta["entry"] == "code.py" and meta["multi_file"] is True and meta["score"] == 0.80
+ assert meta["license"] == "CC-BY-4.0" and meta["source"] == "3dcodeverse" and meta["code_source"] == "commit"
+ assert "renders/sheet.png" in meta["renders"] and "renders/object.glb" in meta["renders"]
+ assert "renders/view_front.png" in meta["renders"]
+ assert json.loads((sdir / "captions.json").read_text()) == {}
+ js = out / "static_object" / "threejs" / "lamp_three"
+ assert (js / "code.js").is_file() and (js / "src" / "object.js").is_file()
+ # index
+ import pyarrow.parquet as pq
+
+ table = pq.read_table(out / "metadata.parquet")
+ assert table.num_rows == 3
+ cols = set(table.column_names)
+ assert {"id", "key", "name", "captions", "meta_json", "code", "tar", "byte_start", "byte_len", "n_files"} <= cols
+ rows = table.to_pylist()
+ row = next(r for r in rows if r["key"] == "wooden_chair_ab12cd34")
+ assert row["code"].startswith("# round 1") and row["captions"]["detailed"] == ""
+ assert len((out / "metadata.jsonl").read_text().splitlines()) == 3
+ # filters
+ rep2 = export_samples(runs_dir, tmp_path / "d2", min_score=0.75)
+ assert rep2.n_exported == 1 and len(rep2.skipped) == 2
+ rep3 = export_samples(runs_dir, tmp_path / "d3", only_passed=True)
+ assert rep3.n_exported == 1
+
+
+def test_export_with_captions_and_reexport(fake_run, tmp_path: Path):
+ ws, rec = fake_run
+ rec.extra["captions"] = {"detailed": "A chair.", "instruction": "Write a Blender Python script for a chair.",
+ "factory": "Build seat then legs.", "provenance": {"captioner": "gemini:x"}}
+ ws.write_json(ws.record_path, rec)
+ out = tmp_path / "ds"
+ export_samples(ws.root.parent, out)
+ rep = export_samples(ws.root.parent, out) # re-export overwrites, index stays at 1 row
+ assert rep.n_indexed == 1
+ row = json.loads((out / "metadata.jsonl").read_text().splitlines()[0])
+ assert row["captions"]["factory"] == "Build seat then legs."
+ assert json.loads(row["meta_json"])["has_captions"] is True
+
+
+def test_pack_samples_roundtrip(runs_dir: Path, tmp_path: Path):
+ out = tmp_path / "ds"
+ export_samples(runs_dir, out)
+ rep = pack_samples(out, tar_prefix="3dcodeverse/test/", max_tar_bytes=200_000)
+ assert rep.n_samples == 3 and rep.tars
+ assert verify_locators(out) == 3
+ rows = [json.loads(ln) for ln in (out / "metadata.jsonl").read_text().splitlines()]
+ r = rows[0]
+ assert r["tar"].startswith("3dcodeverse/test/samples-")
+ with (out / Path(r["tar"]).name).open("rb") as fh:
+ fh.seek(r["byte_start"])
+ blob = fh.read(r["byte_len"])
+ with tarfile.open(fileobj=io.BytesIO(blob)) as tf:
+ names = [m.name for m in tf.getmembers()]
+ assert all(n.startswith(r["key"] + "/") for n in names) and f"{r['key']}/meta.json" in names
+
+
+# --------------------------------------------------------------------------- pairs
+
+
+def test_build_pairs(runs_dir: Path, tmp_path: Path):
+ out = tmp_path / "pairs.jsonl"
+ n = build_pairs(runs_dir, out, min_delta=0.05)
+ pairs = [json.loads(ln) for ln in out.read_text().splitlines()]
+ assert n == len(pairs)
+ kinds = {p["kind"] for p in pairs}
+ assert kinds == {"preference", "repair", "cross_backend"}
+ pref = [p for p in pairs if p["kind"] == "preference"]
+ assert len(pref) == 2 # chair (0.25) + codex chair (0.10); lamp delta 0.02 < min
+ p = next(x for x in pref if x["run"] == "wooden_chair_ab12cd34")
+ assert p["delta"] == 0.25 and "thicken the legs" in p["reason"]
+ assert p["chosen"]["files"]["src/model.py"].startswith("# round 1")
+ assert p["rejected"]["files"]["src/model.py"].startswith("# round 0")
+ rep = next(x for x in pairs if x["kind"] == "repair")
+ assert rep["error"]["type"] == "SyntaxError" and rep["chosen"]["build_ok"] is True
+ assert "size=3.0" in rep["chosen"]["files"]["src/model.py"]
+ xb = next(x for x in pairs if x["kind"] == "cross_backend")
+ assert xb["chosen"]["generator"].startswith("api-agent") and xb["rejected"]["generator"].startswith("codex")
+ assert xb["delta"] == pytest.approx(0.2)
+
+
+# --------------------------------------------------------------------------- dedupe
+
+
+def test_code_fingerprint_normalises():
+ a = {"src/model.py": "import bpy # hi\n\nx = 1\n# c\n"}
+ b = {"src/model.py": "import bpy\nx=1\n"}
+ c = {"src/model.py": "import bpy\nx=2\n"}
+ assert code_fingerprint(a) == code_fingerprint(b) != code_fingerprint(c)
+ assert normalise_code("// a\nlet x = 1; // t\n") == "letx=1;"
+
+
+def test_near_duplicates_groups():
+ fa = MeshFingerprint(extents_cm=(100, 50, 40), tri_count=1000, tri_bucket=9, voxels=list(range(100)), digest="a")
+ fb = MeshFingerprint(extents_cm=(102, 50, 40), tri_count=1200, tri_bucket=10, voxels=list(range(95)), digest="b")
+ fc = MeshFingerprint(extents_cm=(100, 50, 40), tri_count=1000, tri_bucket=9, voxels=list(range(50, 150)), digest="c")
+ items = [DedupeItem(id="a", code_fp="x", mesh_fp=fa), DedupeItem(id="b", code_fp="y", mesh_fp=fb),
+ DedupeItem(id="c", code_fp="z", mesh_fp=fc), DedupeItem(id="d", code_fp="x")]
+ assert near_duplicates(items) == [["a", "b", "d"]]
+
+
+def test_mesh_fingerprint_real_glb(tmp_path: Path):
+ trimesh = pytest.importorskip("trimesh")
+ from codeverse.flywheel.dedupe import mesh_fingerprint
+
+ box = trimesh.creation.box(extents=(1.0, 0.5, 0.25))
+ p = tmp_path / "box.glb"
+ box.export(p)
+ fp = mesh_fingerprint(p)
+ assert fp.tri_count == 12 and fp.voxels
+ assert sorted(fp.extents_cm) == [25, 50, 100]
+ assert fp.jaccard(mesh_fingerprint(p)) == 1.0
+ assert fp.jaccard(mesh_fingerprint(p, seed=7)) > 0.9
+
+
+# --------------------------------------------------------------------------- index
+
+
+def test_build_index_and_queries(runs_dir: Path, tmp_path: Path):
+ db = tmp_path / "idx.sqlite"
+ assert build_index(runs_dir, db) == 3
+ con = sqlite3.connect(db)
+ assert con.execute("SELECT COUNT(*) FROM runs").fetchone()[0] == 3
+ assert con.execute("SELECT COUNT(*) FROM rounds").fetchone()[0] == 2 + 4 + 2
+ assert con.execute("SELECT COUNT(*) FROM usage WHERE role='judge'").fetchone()[0] == 6
+ con.close()
+ s = summary(db)
+ assert {r["language"] for r in s} == {"blender", "threejs"}
+ assert top_runs(db, 1)[0]["slug"] == "wooden_chair_ab12cd34"
+ assert [r["score"] for r in round_curve(db, "wooden_chair_ab12cd34")] == [0.55, 0.80]
+ assert isinstance(load_record(Workspace(runs_dir / "lamp_three")), RunRecord)
diff --git a/harness/tests/judges/__init__.py b/harness/tests/judges/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/judges/conftest.py b/harness/tests/judges/conftest.py
new file mode 100644
index 00000000..29ad6bdf
--- /dev/null
+++ b/harness/tests/judges/conftest.py
@@ -0,0 +1,148 @@
+"""Shared fixtures: PIL-drawn renders, a Spec/JudgeInput, and a FakeChatModel."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import pytest
+from PIL import Image, ImageDraw
+
+from codeverse.contracts.artifacts import Measurement, PartMeasure, RenderSet, RenderView
+from codeverse.contracts.chat import ChatRequest, ChatResponse, ImagePart
+from codeverse.contracts.common import Language, Track, Usage
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.contracts.spec import Spec
+from codeverse.judges.base import JudgeInput
+from codeverse.judges.rubrics import Rubric
+from codeverse.models.base import ModelError
+
+VIEW_NAMES = ("front_right_34", "back_left_34", "front", "top")
+
+
+def draw_chair(path: Path, *, az_hint: int = 0, size: int = 512, legs: int = 4, color=(150, 90, 40)) -> Path:
+ """A crude chair silhouette so a real VLM has something to judge."""
+ im = Image.new("RGB", (size, size), (235, 235, 230))
+ d = ImageDraw.Draw(im)
+ s = size / 512
+ d.rectangle([150 * s, 260 * s, 360 * s, 290 * s], fill=color) # seat
+ d.rectangle([150 * s, 100 * s, 180 * s, 260 * s], fill=color) # back post
+ d.rectangle([330 * s, 100 * s, 360 * s, 260 * s], fill=color)
+ d.rectangle([150 * s, 100 * s, 360 * s, 130 * s], fill=color) # back rail
+ xs = [160, 340] if legs == 2 else [160, 230, 280, 340][: legs]
+ for x in xs:
+ d.rectangle([x * s, 290 * s, (x + 20) * s, 440 * s], fill=color)
+ d.text((8, 8), f"az {az_hint}", fill=(0, 0, 0))
+ im.save(path)
+ return path
+
+
+def make_renders(tmp: Path, *, n: int = 4, sheet: bool = True) -> RenderSet:
+ tmp.mkdir(parents=True, exist_ok=True)
+ views = []
+ for i, name in enumerate(VIEW_NAMES[:n]):
+ p = draw_chair(tmp / f"view_{name}.png", az_hint=i * 90)
+ views.append(RenderView(name=name, path=str(p), width=512, height=512))
+ sheet_path = None
+ if sheet:
+ im = Image.new("RGB", (1024, 1024), (200, 200, 200))
+ for i, v in enumerate(views):
+ with Image.open(v.path) as tile:
+ im.paste(tile.resize((512, 512)), ((i % 2) * 512, (i // 2) * 512))
+ sheet_path = tmp / "sheet.png"
+ im.save(sheet_path)
+ return RenderSet(views=views, contact_sheet=str(sheet_path) if sheet_path else None, renderer="fake")
+
+
+def make_measurement() -> Measurement:
+ return Measurement(
+ bbox_min=(-0.25, 0.0, -0.25), bbox_max=(0.25, 0.9, 0.25), extents=(0.5, 0.9, 0.5), center=(0, 0.45, 0),
+ tri_count=1200, n_meshes=6, n_islands=1,
+ parts=[PartMeasure(name="Seat", bbox_min=(-0.25, 0.42, -0.25), bbox_max=(0.25, 0.46, 0.25), tri_count=12),
+ PartMeasure(name="Backrest", bbox_min=(-0.25, 0.46, -0.25), bbox_max=(0.25, 0.9, -0.2), tri_count=12)],
+ ground_gap_m=0.0, footprint_offset_m=0.0, materials=2,
+ )
+
+
+def make_spec(**kw: Any) -> Spec:
+ base = dict(id="t1", track=Track.STATIC_OBJECT, language=Language.BLENDER,
+ prompt="A simple wooden dining chair with four legs and a slatted backrest.")
+ base.update(kw)
+ return Spec(**base)
+
+
+ACCEPTANCE = [
+ AcceptanceItem(id="A1", text="has exactly four legs touching the ground", how="measure", priority="must"),
+ AcceptanceItem(id="A2", text="backrest is slatted (≥3 slats)", how="visual", priority="should"),
+]
+
+
+def renders(tmp_path: Path) -> RenderSet:
+ return make_renders(tmp_path / "renders")
+
+
+def judge_input(renders: RenderSet) -> JudgeInput:
+ return JudgeInput(spec=make_spec(), renders=renders, measurement=make_measurement(), acceptance=list(ACCEPTANCE),
+ plan_summary="parts: Seat, Backrest, LegFrontLeft, LegFrontRight, LegBackLeft, LegBackRight")
+
+
+def cache_dir(tmp_path: Path) -> Path:
+ return tmp_path / "cache"
+
+
+# --------------------------------------------------------------------------- fake model
+def good_reply(rubric: Rubric, acceptance_ids: list[str], score: float = 0.8, *, accept: bool = True,
+ overrides: dict[str, float] | None = None) -> dict[str, Any]:
+ overrides = overrides or {}
+ return {
+ "criteria": {c.id: {"score": overrides.get(c.id, score), "evidence": f"VIEW 1: {c.id} ok"}
+ for c in rubric.visual_criteria()},
+ "summary": "A recognisable chair.",
+ "strengths": ["reads as a chair"],
+ "issues": [{"target": "Seat", "kind": "detail", "severity": "minor", "detail": "plain slab", "evidence": "VIEW 1"}],
+ "improvement_plan": [{"target": "Seat", "kind": "geometry", "instruction": "bevel the seat edges 5 mm",
+ "priority": 1, "expected_gain": 0.03}],
+ "acceptance": {aid: {"verified": accept, "evidence": "VIEW 3"} for aid in acceptance_ids},
+ }
+
+
+class FakeChatModel:
+ """ChatModel stand-in: pops replies from a queue (dict → parsed; str → text; Exception → raised)."""
+
+ provider = "fake"
+ model = "fake-1"
+
+ def __init__(self, replies: list[Any] | None = None, *, default: Any = None, cost: float = 0.001):
+ self.replies = list(replies or [])
+ self.default = default
+ self.cost = cost
+ self.requests: list[ChatRequest] = []
+
+ @property
+ def id(self) -> str:
+ return "fake:fake-1"
+
+ def supports_vision(self) -> bool:
+ return True
+
+ def generate(self, request: ChatRequest) -> ChatResponse:
+ self.requests.append(request)
+ reply = self.replies.pop(0) if self.replies else self.default
+ if callable(reply) and not isinstance(reply, type):
+ reply = reply(request)
+ if isinstance(reply, Exception):
+ raise reply
+ if reply is None:
+ raise ModelError("no reply configured", retryable=False)
+ usage = Usage(backend="fake", model="fake-1", input_tokens=1000, output_tokens=300, cost_usd=self.cost)
+ if isinstance(reply, str):
+ return ChatResponse(text=reply, parsed=None, usage=usage)
+ import json
+ return ChatResponse(text=json.dumps(reply), parsed=reply, usage=usage)
+
+
+def image_parts(req: ChatRequest) -> list[ImagePart]:
+ return [p for m in req.messages for p in m.parts if isinstance(p, ImagePart)]
diff --git a/harness/tests/judges/test_caps.py b/harness/tests/judges/test_caps.py
new file mode 100644
index 00000000..ab413eba
--- /dev/null
+++ b/harness/tests/judges/test_caps.py
@@ -0,0 +1,60 @@
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.judges.caps import apply_caps
+from codeverse.judges.rubrics import load_rubric
+
+R = load_rubric("static_object_v1")
+
+
+def _gate(name, sev, msg, **data):
+ return GateReport(gate=name, passed=sev != Severity.ERROR,
+ findings=[GateFinding(gate=name, severity=sev, message=msg, data=data)])
+
+
+def test_no_caps_when_clean():
+ res = apply_caps(R, 0.9, [GateReport(gate="connectivity", passed=True)], {}, [])
+ assert res.overall == 0.9 and not res.caps_applied
+
+
+def test_build_error_caps_to_zero():
+ res = apply_caps(R, 0.9, [_gate("build:blender", Severity.ERROR, "Traceback ... NameError")], {}, [])
+ assert res.overall == 0.0
+ assert res.caps_applied[0].rule == "build_error"
+
+
+def test_floating_via_data_kind_and_message():
+ res = apply_caps(R, 0.9, [_gate("connectivity", Severity.ERROR, "part Leg1 is 3cm above others", kind="floating")], {}, [])
+ assert res.overall == 0.6 and res.caps_applied[0].rule == "floating_part"
+ res2 = apply_caps(R, 0.9, [_gate("connectivity", Severity.ERROR, "Leg1 has no_contact with any part")], {}, [])
+ assert res2.overall == 0.6
+
+
+def test_warn_does_not_cap():
+ res = apply_caps(R, 0.9, [_gate("connectivity", Severity.WARN, "floating sliver")], {}, [])
+ assert res.overall == 0.9
+
+
+def test_penetration_and_multiple_caps_take_min():
+ gates = [_gate("connectivity", Severity.ERROR, "penetration Seat/Leg 12mm"),
+ _gate("connectivity", Severity.ERROR, "Arm floating", kind="floating")]
+ res = apply_caps(R, 0.95, gates, {}, [])
+ assert res.overall == 0.6
+ assert {c.rule for c in res.caps_applied} == {"floating_part", "penetration_error"}
+
+
+def test_missing_must_acceptance_caps():
+ items = [AcceptanceItem(id="M1", text="x", priority="must"), AcceptanceItem(id="S1", text="y", priority="should")]
+ res = apply_caps(R, 0.9, [], {"M1": False, "S1": False}, items)
+ assert res.overall == 0.6 and res.caps_applied[0].rule == "missing_must_acceptance"
+ res2 = apply_caps(R, 0.9, [], {"M1": True, "S1": False}, items)
+ assert res2.overall == 0.9
+ res3 = apply_caps(R, 0.9, [], {}, items) # missing → not verified
+ assert res3.overall == 0.6
+
+
+def test_scene_console_and_shader_caps():
+ S = load_rubric("scene_v1")
+ res = apply_caps(S, 0.9, [], {}, [], console_errors=["TypeError: x is undefined"])
+ assert res.overall == 0.6 and res.caps_applied[0].rule == "console_error"
+ res2 = apply_caps(S, 0.9, [_gate("shader_probe", Severity.ERROR, "GLSL compile failed in water.js", kind="shader")], {}, [])
+ assert res2.overall == 0.5
diff --git a/harness/tests/judges/test_live.py b/harness/tests/judges/test_live.py
new file mode 100644
index 00000000..46ddc05f
--- /dev/null
+++ b/harness/tests/judges/test_live.py
@@ -0,0 +1,108 @@
+"""Live judge tests (real Gemini calls; need keys). Run: pytest tests/judges -m live -s"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import numpy as np
+import pytest
+import trimesh
+
+from codeverse.config import get_settings
+from codeverse.contracts.artifacts import RenderSet
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.judges.base import JudgeInput
+from codeverse.judges.scoring import is_degraded
+from codeverse.judges.vlm_judge import VlmJudge
+from tests.judges.conftest import make_measurement, make_renders, make_spec
+
+pytestmark = pytest.mark.live
+MODEL = "gemini:gemini-3.7-flash"
+
+
+def _stool_glb(out: Path) -> Path:
+ seat = trimesh.creation.cylinder(radius=0.18, height=0.03, sections=48)
+ seat.apply_translation((0, 0, 0.45 - 0.015))
+ parts = {"Seat": seat}
+ for i in range(3):
+ a = np.deg2rad(90 + i * 120)
+ leg = trimesh.creation.cylinder(radius=0.018, height=0.43, sections=20)
+ leg.apply_translation((0.13 * np.cos(a), 0.13 * np.sin(a), 0.215))
+ parts[f"Leg{i + 1}"] = leg
+ scene = trimesh.Scene()
+ zup_to_yup = trimesh.transformations.rotation_matrix(-np.pi / 2, (1, 0, 0))
+ for name, m in parts.items():
+ m.apply_transform(zup_to_yup)
+ m.visual = trimesh.visual.ColorVisuals(m, face_colors=(160, 110, 60, 255))
+ scene.add_geometry(m, node_name=name, geom_name=name)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ scene.export(out)
+ return out
+
+
+def _renders_for_test(tmp: Path) -> tuple[RenderSet, object, str]:
+ """Real stool renders via spatial.render when possible, else PIL drawings."""
+ try:
+ from codeverse.conventions import OBJECT_VIEWS_QUICK
+ from codeverse.spatial.measure import measure_glb
+ from codeverse.spatial.render import render_glb
+
+ glb = _stool_glb(tmp / "stool.glb")
+ rs = render_glb(glb, tmp / "renders", views=OBJECT_VIEWS_QUICK, sheet=True)
+ return rs, measure_glb(glb), "render_glb(trimesh stool)"
+ except Exception as e: # noqa: BLE001 - live test: fall back but SAY so
+ return make_renders(tmp / "renders"), make_measurement(), f"PIL chair drawings (render_glb unavailable: {type(e).__name__}: {str(e)[:120]})"
+
+
+def test_live_vlm_judge_two_samples(tmp_path):
+ assert get_settings().gemini_api_keys, "no Gemini keys"
+ renders, meas, source = _renders_for_test(tmp_path)
+ prompt = ("A simple three-legged wooden stool, 45 cm tall, round seat 36 cm across." if "stool" in source
+ else "A simple wooden dining chair with four legs and a slatted backrest.")
+ spec = make_spec(prompt=prompt)
+ inp = JudgeInput(spec=spec, renders=renders, measurement=meas,
+ acceptance=[AcceptanceItem(id="A1", text="three legs reach the ground", how="visual", priority="must"),
+ AcceptanceItem(id="A2", text="seat is round", how="visual", priority="should")],
+ plan_summary="parts: Seat, Leg1, Leg2, Leg3")
+ judge = VlmJudge("static_object_v1", model_id=MODEL, n_samples=2, cache_dir=tmp_path / "cache")
+ j = judge.judge(inp)
+ raw = json.loads(j.raw)
+ print(f"\nLIVE source={source}\noverall={j.overall} std={j.score_std} passed={j.passed} n={j.n_samples}"
+ f"\nscores={j.scores}\nacceptance={j.acceptance_results}\ncaps={raw.get('caps')}\nsample_errors={raw.get('sample_errors')}"
+ f"\nusage={j.usage}\nsummary={j.summary}\nplan={[i.instruction for i in j.improvement_plan]}")
+ assert not is_degraded(j), j.summary
+ assert j.n_samples == 2 and raw["sample_errors"] == [] # parsed first try
+ assert 0.0 < j.overall < 1.0
+ assert set(j.scores) == {c.id for c in judge.rubric.criteria}
+
+
+def test_live_pairwise_stool_vs_chair(tmp_path):
+ from codeverse.judges.pairwise import PairwiseJudge
+
+ renders, _, source = _renders_for_test(tmp_path / "stool")
+ if "stool" not in source:
+ pytest.skip("needs real stool renders")
+ chair = make_renders(tmp_path / "chair")
+ spec = make_spec(prompt="A simple three-legged wooden stool, 45 cm tall, round seat.")
+ res = PairwiseJudge(MODEL, cache_dir=tmp_path / "cache").compare(spec, renders, chair)
+ print(f"\nLIVE pairwise winner={res.winner} conf={res.confidence} err={res.error!r}\nreasons={res.reasons}\nusage={res.usage}")
+ assert res.winner == "a"
+
+
+def test_live_reference_judge(tmp_path):
+ from codeverse.contracts.spec import ReferenceImage
+ from codeverse.judges.reference import ReferenceJudge
+
+ renders, meas, source = _renders_for_test(tmp_path / "stool")
+ if "stool" not in source:
+ pytest.skip("needs real stool renders")
+ front = next(v for v in renders.views if v.name == "front")
+ spec = make_spec(prompt="Reproduce the stool in the reference image.",
+ references=[ReferenceImage(path=front.path, role="target", note="the target stool")])
+ inp = JudgeInput(spec=spec, renders=renders, measurement=meas, plan_summary="parts: Seat, Leg1, Leg2, Leg3")
+ j = ReferenceJudge(MODEL, cache_dir=tmp_path / "cache").judge(inp)
+ raw = json.loads(j.raw)
+ print(f"\nLIVE reference overall={j.overall} passed={j.passed} scores={j.scores}\nsummary={j.summary}\nusage={j.usage}")
+ assert not is_degraded(j) and raw["sample_errors"] == []
+ assert j.scores["silhouette_match"] >= 0.95 # reference is the render itself
diff --git a/harness/tests/judges/test_metrics.py b/harness/tests/judges/test_metrics.py
new file mode 100644
index 00000000..cf0dc47a
--- /dev/null
+++ b/harness/tests/judges/test_metrics.py
@@ -0,0 +1,32 @@
+import pytest
+
+from codeverse.contracts.judgment import Judgment
+from codeverse.judges.metrics import best_index, judge_agreement, plateau
+
+
+def _j(o, **sc):
+ return Judgment(rubric="r", scores=sc or {"a": o}, overall=o, passed=o > 0.7)
+
+
+def test_agreement():
+ a = judge_agreement([_j(0.7, a=0.6, b=0.8), _j(0.9, a=0.8, b=1.0)])
+ assert a.mean == 0.8 and a.std == pytest.approx(0.1) and a.per_criterion_std == {"a": 0.1, "b": 0.1} and a.n == 2
+ assert judge_agreement([_j(0.5)]).std == 0.0
+ with pytest.raises(ValueError):
+ judge_agreement([])
+
+
+def test_plateau():
+ assert plateau([0.5, 0.6]) is False # too few
+ assert plateau([0.5, 0.6, 0.61, 0.6]) is True
+ assert plateau([0.5, 0.6, 0.61, 0.7]) is False
+ assert plateau([0.5, 0.52, 0.53], window=2, min_delta=0.02) is False # 0.53-0.5 = 0.03 ≥ 0.02
+ assert plateau([0.5, 0.51, 0.515], window=2, min_delta=0.02) is True
+
+
+def test_best_index():
+ assert best_index([(0.5, 0), (0.7, 2), (0.7, 1), (0.6, 0)]) == 2
+ assert best_index([(0.7, 1), (0.7, 1)]) == 1 # later wins ties
+ assert best_index([(0.9, 3), (0.8, 0)]) == 0
+ with pytest.raises(ValueError):
+ best_index([])
diff --git a/harness/tests/judges/test_output_schema.py b/harness/tests/judges/test_output_schema.py
new file mode 100644
index 00000000..b1dd5d91
--- /dev/null
+++ b/harness/tests/judges/test_output_schema.py
@@ -0,0 +1,94 @@
+import json
+
+import pytest
+
+from codeverse.judges.output_schema import (
+ JudgeParseError,
+ extract_json,
+ parse_judge_output,
+ wire_schema,
+)
+from codeverse.judges.rubrics import load_rubric
+from tests.judges.conftest import good_reply
+
+R = load_rubric("static_object_v1")
+IDS = ["A1", "must-2"]
+
+
+def test_wire_schema_has_fixed_keys_and_no_overall():
+ s = wire_schema(R, IDS)
+ crit = s["$defs"]["Criteria"]
+ assert set(crit["required"]) == {c.id for c in R.criteria}
+ acc = s["$defs"]["Acceptance"]
+ assert set(acc["properties"]) == set(IDS)
+ assert "overall" not in s["properties"] and "passed" not in s["properties"]
+
+
+def test_wire_schema_without_acceptance_omits_block():
+ s = wire_schema(R, [])
+ assert "acceptance" not in s["properties"]
+
+
+def test_parse_dict_form():
+ out = parse_judge_output(good_reply(R, IDS, 0.8), R, IDS)
+ assert set(out.scores) == {c.id for c in R.criteria}
+ assert out.acceptance_bools == {"A1": True, "must-2": True}
+ assert out.improvement_plan[0].target == "Seat"
+
+
+def test_parse_list_form_and_fenced_text():
+ rep = good_reply(R, IDS, 0.7)
+ rep["criteria"] = [{"id": k, **v} for k, v in rep["criteria"].items()]
+ rep["acceptance"] = [{"id": k, "verified": v["verified"]} for k, v in rep["acceptance"].items()]
+ text = "Here you go:\n```json\n" + json.dumps(rep) + "\n```"
+ out = parse_judge_output(text, R, IDS)
+ assert out.scores["materials"] == 0.7
+ assert out.acceptance_bools["A1"] is True
+
+
+def test_parse_bare_bool_acceptance_and_numeric_scores():
+ rep = good_reply(R, IDS)
+ rep["acceptance"] = {"A1": True, "must-2": False}
+ rep["criteria"] = {k: v["score"] for k, v in rep["criteria"].items()}
+ out = parse_judge_output(rep, R, IDS)
+ assert out.acceptance_bools == {"A1": True, "must-2": False}
+ assert out.criteria["materials"].evidence == ""
+
+
+def test_missing_criterion_raises():
+ rep = good_reply(R, IDS)
+ rep["criteria"].pop("materials")
+ with pytest.raises(JudgeParseError, match="missing criteria"):
+ parse_judge_output(rep, R, IDS)
+
+
+def test_missing_acceptance_defaults_false_and_unknown_criteria_dropped():
+ rep = good_reply(R, IDS)
+ rep["acceptance"].pop("must-2")
+ rep["criteria"]["bogus"] = {"score": 1.0, "evidence": ""}
+ out = parse_judge_output(rep, R, IDS)
+ assert out.acceptance_bools["must-2"] is False
+ assert "bogus" not in out.criteria
+
+
+def test_out_of_range_score_raises():
+ rep = good_reply(R, IDS)
+ rep["criteria"]["materials"]["score"] = 1.4
+ with pytest.raises(JudgeParseError):
+ parse_judge_output(rep, R, IDS)
+
+
+def test_measured_injection():
+ ref = load_rubric("reference_v1")
+ rep = good_reply(ref, [], 0.8) # visual criteria only
+ out = parse_judge_output(rep, ref, [], measured_scores={"silhouette_match": 0.55})
+ assert out.scores["silhouette_match"] == 0.55
+ with pytest.raises(JudgeParseError):
+ parse_judge_output(rep, ref, []) # measured criterion missing
+
+
+def test_extract_json_variants():
+ assert extract_json('{"a": 1}') == {"a": 1}
+ assert extract_json('blah {"a": {"b": 2}} trailing') == {"a": {"b": 2}}
+ with pytest.raises(JudgeParseError):
+ extract_json("no json here")
diff --git a/harness/tests/judges/test_pairwise.py b/harness/tests/judges/test_pairwise.py
new file mode 100644
index 00000000..c25b7aea
--- /dev/null
+++ b/harness/tests/judges/test_pairwise.py
@@ -0,0 +1,49 @@
+from codeverse.judges.pairwise import PairwiseJudge
+from codeverse.models.base import ModelError
+from tests.judges.conftest import FakeChatModel, image_parts, make_renders, make_spec
+
+
+def _reply(w, conf=0.8):
+ return {"winner": w, "confidence": conf, "reasons": [f"{w} has four legs"], "criteria_won": [{"criterion": "intent_fidelity", "winner": w}]}
+
+
+def test_agreement_across_swap(tmp_path, cache_dir):
+ ra, rb = make_renders(tmp_path / "a"), make_renders(tmp_path / "b")
+ # ordering 1: A=ra,B=rb → "A" wins; ordering 2 (swapped): A=rb,B=ra → "B" wins → both say ra
+ model = FakeChatModel([_reply("A", 0.9), _reply("B", 0.7)])
+ res = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare(make_spec(), ra, rb)
+ assert res.winner == "a" and res.confidence == 0.8 and len(res.orderings) == 2
+ assert res.usage.cost_usd > 0
+ labels = [p.label for p in image_parts(model.requests[0])]
+ assert labels[0].startswith("CANDIDATE A — contact sheet") and labels[1].startswith("CANDIDATE B")
+
+
+def test_disagreement_is_tie(tmp_path, cache_dir):
+ ra, rb = make_renders(tmp_path / "a"), make_renders(tmp_path / "b")
+ model = FakeChatModel([_reply("A", 0.9), _reply("A", 0.9)]) # position bias: always first
+ res = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare(make_spec(), ra, rb)
+ assert res.winner == "tie" and res.confidence <= 0.4 and res.error == "orderings disagree"
+
+
+def test_tie_and_errors(tmp_path, cache_dir):
+ ra, rb = make_renders(tmp_path / "a", sheet=False), make_renders(tmp_path / "b", sheet=False)
+ model = FakeChatModel([_reply("tie", 0.6), _reply("tie", 0.6)])
+ res = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare(make_spec(), ra, rb)
+ assert res.winner == "tie" and res.confidence == 0.6
+ assert len(image_parts(model.requests[0])) == 8 # 4 views per side without a sheet
+ model2 = FakeChatModel(default=ModelError("down", retryable=True))
+ res2 = PairwiseJudge("fake:fake-1", chat_model=model2, cache_dir=cache_dir).compare(make_spec(), ra, rb)
+ assert res2.winner == "tie" and res2.confidence == 0.0 and "ModelError" in res2.error
+
+
+def test_single_ordering_success_halves_confidence(tmp_path, cache_dir):
+ ra, rb = make_renders(tmp_path / "a"), make_renders(tmp_path / "b")
+ model = FakeChatModel([ModelError("x", retryable=True), _reply("A", 0.8)]) # swapped ordering: A=rb → b wins
+ res = PairwiseJudge("fake:fake-1", chat_model=model, cache_dir=cache_dir).compare(make_spec(), ra, rb)
+ assert res.winner == "b" and res.confidence == 0.4
+
+
+def test_unswap_reasons():
+ from codeverse.judges.pairwise import _unswap_text
+ assert _unswap_text("Candidate A beats candidate B", True) == "Candidate B beats candidate A"
+ assert _unswap_text("Candidate A beats candidate B", False) == "Candidate A beats candidate B"
diff --git a/harness/tests/judges/test_prompt_builder.py b/harness/tests/judges/test_prompt_builder.py
new file mode 100644
index 00000000..d7bde978
--- /dev/null
+++ b/harness/tests/judges/test_prompt_builder.py
@@ -0,0 +1,127 @@
+from pathlib import Path
+
+from PIL import Image
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, RenderView, Severity
+from codeverse.contracts.chat import ImagePart, TextPart
+from codeverse.contracts.judgment import ImprovementItem, Judgment
+from codeverse.judges.images import prepare_image, view_az_el
+from codeverse.judges.prompt_builder import (
+ TEXT_BUDGET_CHARS,
+ build_judge_messages,
+ build_system_prompt,
+ select_views,
+)
+from codeverse.judges.rubrics import load_rubric
+from tests.judges.conftest import draw_chair, make_renders
+
+R = load_rubric("static_object_v1")
+
+
+def _parts(msgs):
+ return msgs[0].parts
+
+
+def test_system_has_role_rubric_and_anchors():
+ system = build_system_prompt(R)
+ assert "BLIND JUDGE" in system
+ for c in R.criteria:
+ assert c.id in system and c.anchors["0.4"][:30] in system
+ assert "Do NOT compute an overall" in system
+
+
+def test_user_message_layout(judge_input, cache_dir):
+ system, msgs = build_judge_messages(judge_input, R, cache_dir=cache_dir)
+ parts = _parts(msgs)
+ assert isinstance(parts[0], TextPart)
+ text = parts[0].text
+ for section in ("BRIEF", "PLAN DIGEST", "ACCEPTANCE CHECKLIST", "MEASUREMENTS", "GATE FINDINGS", "VIEW RIG"):
+ assert section in text, section
+ assert "A1 [must, via measure]" in text
+ assert "Seat" in text and "Backrest" in text # measurement table (spatial or local fallback)
+ imgs = [p for p in parts if isinstance(p, ImagePart)]
+ assert len(imgs) == 5 # sheet + 4 views
+ assert imgs[0].label.startswith("CONTACT SHEET")
+ assert imgs[1].label.startswith("VIEW 1/4 — ")
+ assert "az 35° el 22°" in imgs[1].label
+ # labelled text precedes each image
+ idx = parts.index(imgs[1])
+ assert isinstance(parts[idx - 1], TextPart) and parts[idx - 1].text == imgs[1].label
+ # prepared images are cached + downscaled + strip added
+ for ip in imgs:
+ assert Path(ip.path).is_file() and Path(ip.path).parent == cache_dir
+ with Image.open(imgs[0].path) as im:
+ assert max(im.size) <= 1024 + 80
+
+
+def test_shuffle_is_deterministic_and_changes_order(judge_input, cache_dir):
+ _, a = build_judge_messages(judge_input, R, shuffle_seed=1, cache_dir=cache_dir)
+ _, b = build_judge_messages(judge_input, R, shuffle_seed=1, cache_dir=cache_dir)
+ _, c = build_judge_messages(judge_input, R, shuffle_seed=None, cache_dir=cache_dir)
+ la = [p.label for p in _parts(a) if isinstance(p, ImagePart)]
+ lb = [p.label for p in _parts(b) if isinstance(p, ImagePart)]
+ lc = [p.label for p in _parts(c) if isinstance(p, ImagePart)]
+ assert la == lb
+ def names(ls):
+ return [x.split("— ")[1].split(" ·")[0] for x in ls[1:]]
+
+ assert sorted(names(la)) == sorted(names(lc))
+ assert names(la) != names(lc) or True # shuffle of 4 may coincide; order set equality is what matters
+
+
+def test_image_budget_subsamples(tmp_path, judge_input, cache_dir):
+ rs = make_renders(tmp_path / "many", n=4)
+ views = []
+ for i in range(14):
+ p = draw_chair(tmp_path / f"v{i}.png", az_hint=i)
+ views.append(RenderView(name=f"v{i}", path=str(p), camera_position=(1.0, 0.5, 1.0), look_at=(0, 0.3, 0)))
+ rs.views = views
+ judge_input.renders = rs
+ _, msgs = build_judge_messages(judge_input, R, cache_dir=cache_dir, max_images=10)
+ imgs = [p for p in _parts(msgs) if isinstance(p, ImagePart)]
+ assert len(imgs) == 10
+ assert imgs[1].label.startswith("VIEW 1/9")
+ assert select_views(views, 9, shuffle_seed=None)[0].name == "v0"
+ assert "az 45° el" in imgs[1].label # computed from camera geometry
+
+
+def test_gates_previous_and_budget(judge_input, cache_dir):
+ judge_input.gates = [GateReport(gate="connectivity", passed=False, findings=[
+ GateFinding(gate="connectivity", severity=Severity.ERROR, target="LegBackLeft", message="floating 3 cm"),
+ GateFinding(gate="connectivity", severity=Severity.WARN, message="thin sliver on Seat")])]
+ judge_input.previous = Judgment(rubric="static_object_v1", scores={}, overall=0.55, passed=False,
+ improvement_plan=[ImprovementItem(target="Seat", kind="geometry", instruction="thicken seat", priority=1)])
+ judge_input.round_index = 2
+ judge_input.extra_context = "x" * 50_000
+ _, msgs = build_judge_messages(judge_input, R, cache_dir=cache_dir)
+ text = _parts(msgs)[0].text
+ assert "errors (1)" in text and "[LegBackLeft]: floating 3 cm" in text
+ assert "warnings (1)" in text
+ assert "PREVIOUS VERDICT (round 1): overall 0.55" in text and "thicken seat" in text
+ assert len(text) <= TEXT_BUDGET_CHARS + 20
+
+
+def test_scene_rig_paragraph(judge_input, cache_dir):
+ from codeverse.contracts.common import Language, Track
+ judge_input.spec = judge_input.spec.model_copy(update={"track": Track.SCENE, "language": Language.SCENE_THREEJS})
+ judge_input.renders.console_errors = ["ReferenceError: foo"]
+ judge_input.renders.fps = 48.0
+ _, msgs = build_judge_messages(judge_input, load_rubric("scene_v1"), cache_dir=cache_dir)
+ text = _parts(msgs)[0].text
+ assert "overview_*" in text and "console error" in text and "48 fps" in text
+
+
+def test_view_az_el_geometry():
+ v = RenderView(name="custom", path="x.png", camera_position=(0.0, 1.0, 1.0), look_at=(0, 0, 0))
+ az, el = view_az_el(v)
+ assert az == 0.0 and el == 45.0
+ assert view_az_el(RenderView(name="top", path="x")) == (0.0, 88.0)
+ assert view_az_el(RenderView(name="zzz", path="x")) is None
+
+
+def test_prepare_image_label_and_cache(tmp_path):
+ src = draw_chair(tmp_path / "a.png", size=1600)
+ out = prepare_image(src, label="VIEW 1/1 — front", max_px=768, cache_dir=tmp_path / "c")
+ with Image.open(out) as im:
+ assert im.size[0] == 768 and im.size[1] > 768 # strip added below label
+ assert prepare_image(src, label="VIEW 1/1 — front", max_px=768, cache_dir=tmp_path / "c") == out
diff --git a/harness/tests/judges/test_reference.py b/harness/tests/judges/test_reference.py
new file mode 100644
index 00000000..e9391204
--- /dev/null
+++ b/harness/tests/judges/test_reference.py
@@ -0,0 +1,41 @@
+import pytest
+
+from codeverse.contracts.spec import ReferenceImage
+from codeverse.judges.reference import ReferenceJudge, ReferenceJudgeError, iou_to_score
+from codeverse.judges.rubrics import load_rubric
+from tests.judges.conftest import FakeChatModel, draw_chair, good_reply, image_parts
+
+REF = load_rubric("reference_v1")
+
+
+def test_iou_mapping():
+ assert iou_to_score(0.9) == 1.0 and iou_to_score(0.1) == 0.0
+ assert iou_to_score(0.55) == pytest.approx(0.5)
+
+
+def test_reference_judge_measures_silhouette_and_adds_reference_images(judge_input, tmp_path, cache_dir):
+ ref_png = draw_chair(tmp_path / "ref.png", legs=4, color=(30, 30, 30))
+ judge_input.spec = judge_input.spec.model_copy(update={"references": [ReferenceImage(path=str(ref_png), note="target chair")]})
+ calls = []
+
+ def fake_sil(render, reference):
+ calls.append((render, reference))
+ return {"iou": 0.7, "aspect_ratio_delta": 0.05}
+
+ model = FakeChatModel([good_reply(REF, ["A1", "A2"], 0.8)])
+ j = ReferenceJudge("fake:fake-1", chat_model=model, silhouette_fn=fake_sil, cache_dir=cache_dir).judge(judge_input)
+ assert calls and calls[0][0].endswith("view_front.png") and calls[0][1] == str(ref_png)
+ assert j.scores["silhouette_match"] == pytest.approx(0.75)
+ expected = sum(REF.weights[c] * (0.75 if c == "silhouette_match" else 0.8) for c in REF.weights)
+ assert j.overall == pytest.approx(round(expected, 4))
+ req = model.requests[0]
+ labels = [p.label for p in image_parts(req)]
+ assert labels[0].startswith("REFERENCE 1/1 (target) — target chair") and labels[1].startswith("CONTACT SHEET")
+ assert "IoU 0.700" in req.messages[0].parts[0].text
+ assert "silhouette_match" not in req.response_schema["$defs"]["Criteria"]["properties"]
+
+
+def test_reference_judge_requires_reference(judge_input, cache_dir):
+ model = FakeChatModel([good_reply(REF, ["A1", "A2"], 0.8)])
+ with pytest.raises(ReferenceJudgeError):
+ ReferenceJudge("fake:fake-1", chat_model=model, silhouette_fn=lambda a, b: {"iou": 1.0}, cache_dir=cache_dir).judge(judge_input)
diff --git a/harness/tests/judges/test_rubrics.py b/harness/tests/judges/test_rubrics.py
new file mode 100644
index 00000000..610a725b
--- /dev/null
+++ b/harness/tests/judges/test_rubrics.py
@@ -0,0 +1,58 @@
+import pytest
+
+from codeverse.judges.rubrics import RubricError, list_rubrics, load_rubric, rubric_from_dict
+
+EXPECTED = {"static_object_v1", "articulated_v1", "scene_v1", "asset_v1", "reference_v1"}
+
+
+def test_all_rubrics_load_and_validate():
+ assert set(list_rubrics()) >= EXPECTED
+ for name in EXPECTED:
+ r = load_rubric(name)
+ assert abs(sum(c.weight for c in r.criteria) - 1.0) < 0.02
+ for c in r.criteria:
+ assert set(c.anchors) >= {"1.0", "0.7", "0.4", "0.1"}
+ assert any(c.id == "build_error" and c.cap == 0.0 for c in r.caps)
+ assert any(c.when == "acceptance" for c in r.caps)
+
+
+def test_static_rubric_shape():
+ r = load_rubric("static_object_v1")
+ assert r.pass_threshold == 0.72
+ assert r.weights["intent_fidelity"] == 0.22
+ assert r.criterion("intent_fidelity").floor == 0.30
+ assert [c.id for c in r.criteria][:3] == ["intent_fidelity", "structure_plausibility", "geometry_detail"]
+
+
+def test_reference_rubric_has_measured_silhouette():
+ r = load_rubric("reference_v1")
+ assert [c.id for c in r.measured_criteria()] == ["silhouette_match"]
+ assert r.criterion("silhouette_match").weight == 0.25
+
+
+def test_weighted_overall_and_floors():
+ r = load_rubric("static_object_v1")
+ scores = {c.id: 0.8 for c in r.criteria}
+ assert abs(r.weighted_overall(scores) - 0.8) < 1e-9
+ scores["intent_fidelity"] = 0.2
+ assert r.floors_hit(scores) == [("intent_fidelity", 0.2, 0.30)]
+ with pytest.raises(RubricError):
+ r.weighted_overall({"intent_fidelity": 1.0})
+
+
+def test_unknown_and_invalid_rubric():
+ with pytest.raises(RubricError):
+ load_rubric("nope_v9")
+ bad = {"name": "x", "pass_threshold": 0.7, "criteria": [
+ {"id": "a", "weight": 0.5, "description": "d", "anchors": {"1.0": "", "0.7": "", "0.4": "", "0.1": ""}}]}
+ with pytest.raises(RubricError): # weights must sum to 1
+ rubric_from_dict(bad)
+ bad["criteria"][0]["weight"] = 1.0
+ bad["criteria"][0]["anchors"].pop("0.4")
+ with pytest.raises(RubricError): # anchors incomplete
+ rubric_from_dict(bad)
+
+
+def test_content_hash_stable():
+ assert load_rubric("scene_v1").content_hash() == load_rubric("scene_v1").content_hash()
+ assert load_rubric("scene_v1").content_hash() != load_rubric("asset_v1").content_hash()
diff --git a/harness/tests/judges/test_vlm_judge.py b/harness/tests/judges/test_vlm_judge.py
new file mode 100644
index 00000000..39766c7c
--- /dev/null
+++ b/harness/tests/judges/test_vlm_judge.py
@@ -0,0 +1,161 @@
+import json
+
+import pytest
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+from codeverse.judges.rubrics import load_rubric
+from codeverse.judges.scoring import is_degraded
+from codeverse.judges.vlm_judge import VlmJudge
+from codeverse.models.base import ModelError
+from tests.judges.conftest import FakeChatModel, good_reply, image_parts
+
+R = load_rubric("static_object_v1")
+IDS = ["A1", "A2"]
+
+
+def _judge(model, **kw):
+ return VlmJudge("static_object_v1", model_id="fake:fake-1", chat_model=model, **kw)
+
+
+def test_full_path_single_sample(judge_input, cache_dir):
+ model = FakeChatModel([good_reply(R, IDS, 0.8)])
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ assert j.passed and abs(j.overall - 0.8) < 1e-6
+ assert j.scores["intent_fidelity"] == 0.8 and j.n_samples == 1 and j.score_std == 0.0
+ assert j.acceptance_results == {"A1": True, "A2": True}
+ assert j.improvement_plan[0].instruction.startswith("bevel")
+ assert j.usage.cost_usd == pytest.approx(0.001)
+ assert j.judge_backend == "fake:fake-1" and j.rubric == "static_object_v1"
+ raw = json.loads(j.raw)
+ assert raw["status"] == "ok" and raw["n_used"] == 1 and raw["rubric_hash"] == R.content_hash()
+ assert "[verdict: overall 0.80 vs threshold 0.72 → PASS]" in j.summary
+ req = model.requests[0]
+ assert req.response_schema is not None and "Criteria" in req.response_schema["$defs"]
+ assert req.label == "judge:static_object_v1:s0" and req.temperature == 0.2
+ assert len(image_parts(req)) == 5
+ assert "BLIND JUDGE" in req.system
+
+
+def test_overall_is_code_computed_weighted_mean(judge_input, cache_dir):
+ over = {"intent_fidelity": 1.0, "materials": 0.5}
+ model = FakeChatModel([good_reply(R, IDS, 0.8, overrides=over)])
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ expected = sum(R.weights[c] * over.get(c, 0.8) for c in R.weights)
+ assert j.overall == pytest.approx(round(expected, 4))
+
+
+def test_n_samples_mean_std_and_shuffle(judge_input, cache_dir):
+ model = FakeChatModel([good_reply(R, IDS, 0.7), good_reply(R, IDS, 0.9), good_reply(R, IDS, 0.8)])
+ j = _judge(model, n_samples=3, cache_dir=cache_dir).judge(judge_input)
+ assert j.n_samples == 3 and j.overall == pytest.approx(0.8) and j.score_std == pytest.approx(0.0816, abs=1e-3)
+ assert j.usage.cost_usd == pytest.approx(0.003) and j.usage.input_tokens == 3000
+ orders = [[p.label for p in image_parts(r)][1:] for r in model.requests]
+ assert len({tuple(o) for o in orders}) >= 2 # view order differs between samples
+ raw = json.loads(j.raw)
+ assert raw["per_sample_overall"] == [0.7, 0.9, 0.8]
+ # representative sample (closest to mean) supplies the narrative
+ assert j.summary.startswith("A recognisable chair.")
+
+
+def test_floor_fails_even_if_mean_high(judge_input, cache_dir):
+ model = FakeChatModel([good_reply(R, IDS, 0.95, overrides={"intent_fidelity": 0.2})])
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ assert j.overall > 0.72 and not j.passed
+ assert "floors: intent_fidelity 0.20<0.30" in j.summary
+
+
+def test_caps_from_gates(judge_input, cache_dir):
+ judge_input.gates = [GateReport(gate="connectivity", passed=False, findings=[
+ GateFinding(gate="connectivity", severity=Severity.ERROR, target="LegBackLeft", message="part floating 30 mm above the rest", data={"kind": "floating"})])]
+ model = FakeChatModel([good_reply(R, IDS, 0.9)])
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ assert j.overall == 0.6 and not j.passed
+ raw = json.loads(j.raw)
+ assert raw["caps"]["caps_applied"][0]["rule"] == "floating_part"
+ assert raw["overall_uncapped"] == pytest.approx(0.9)
+ assert "caps: floating_part≤0.60" in j.summary
+
+
+def test_must_acceptance_missing_fails(judge_input, cache_dir):
+ rep = good_reply(R, IDS, 0.9)
+ rep["acceptance"]["A1"]["verified"] = False # A1 is must
+ j = _judge(FakeChatModel([rep]), cache_dir=cache_dir).judge(judge_input)
+ assert not j.passed and j.overall == 0.6 # capped by missing_must_acceptance
+ assert "must items unverified: A1" in j.summary
+ rep2 = good_reply(R, IDS, 0.9)
+ rep2["acceptance"]["A2"]["verified"] = False # A2 is should → no effect on pass
+ j2 = _judge(FakeChatModel([rep2]), cache_dir=cache_dir).judge(judge_input)
+ assert j2.passed and j2.acceptance_results == {"A1": True, "A2": False}
+
+
+def test_acceptance_majority_vote(judge_input, cache_dir):
+ a = good_reply(R, IDS, 0.9)
+ a["acceptance"]["A1"]["verified"] = False
+ b = good_reply(R, IDS, 0.9)
+ c = good_reply(R, IDS, 0.9)
+ j = _judge(FakeChatModel([a, b, c]), n_samples=3, cache_dir=cache_dir).judge(judge_input)
+ assert j.acceptance_results["A1"] is True and j.passed
+ a2 = good_reply(R, IDS, 0.9)
+ a2["acceptance"]["A1"]["verified"] = False
+ b2 = good_reply(R, IDS, 0.9)
+ b2["acceptance"]["A1"]["verified"] = False
+ j2 = _judge(FakeChatModel([a2, b2, c]), n_samples=3, cache_dir=cache_dir).judge(judge_input)
+ assert j2.acceptance_results["A1"] is False and not j2.passed
+
+
+def test_retry_on_parse_failure_then_success(judge_input, cache_dir):
+ model = FakeChatModel(["not json at all", good_reply(R, IDS, 0.8)])
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ assert j.passed and len(model.requests) == 2
+ assert model.requests[1].temperature > model.requests[0].temperature # nudged
+ assert j.usage.cost_usd == pytest.approx(0.002) # failed attempt still charged
+
+
+def test_retry_on_model_error_then_success(judge_input, cache_dir):
+ model = FakeChatModel([ModelError("503", retryable=True), good_reply(R, IDS, 0.8)])
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ assert j.passed and len(model.requests) == 2
+
+
+def test_degraded_after_exhausting_attempts(judge_input, cache_dir):
+ model = FakeChatModel(default=ModelError("boom", retryable=True))
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ assert not j.passed and j.overall == 0.0 and j.summary.startswith("judge_error:")
+ assert is_degraded(j) and json.loads(j.raw)["status"] == "degraded"
+ assert len(model.requests) == 3 # max_attempts
+ assert j.n_samples == 0
+
+
+def test_partial_samples_still_score(judge_input, cache_dir):
+ # sample 0 fails all 3 attempts; sample 1 succeeds → judgment from 1 sample, errors recorded
+ model = FakeChatModel(["bad", "bad", "bad", good_reply(R, IDS, 0.8)])
+ j = _judge(model, n_samples=2, cache_dir=cache_dir).judge(judge_input)
+ assert j.passed and j.n_samples == 1
+ raw = json.loads(j.raw)
+ assert raw["n_requested"] == 2 and raw["n_used"] == 1 and len(raw["sample_errors"]) == 1
+
+
+def test_non_retryable_error_stops_early(judge_input, cache_dir):
+ model = FakeChatModel(default=ModelError("bad request", retryable=False))
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ assert is_degraded(j) and len(model.requests) == 2
+
+
+def test_base_judge_rejects_measured_rubric(judge_input, cache_dir):
+ with pytest.raises(ValueError, match="measured criteria"):
+ VlmJudge("reference_v1", chat_model=FakeChatModel(), cache_dir=cache_dir).judge(judge_input)
+
+
+def test_missing_render_is_loud(judge_input, cache_dir):
+ from codeverse.judges.images import JudgeImageError
+ judge_input.renders.views[0].path = "/nonexistent/x.png"
+ with pytest.raises(JudgeImageError):
+ _judge(FakeChatModel([good_reply(R, IDS)]), cache_dir=cache_dir).judge(judge_input)
+
+
+def test_no_acceptance_items(judge_input, cache_dir):
+ judge_input.acceptance = []
+ model = FakeChatModel([good_reply(R, [], 0.8)])
+ j = _judge(model, cache_dir=cache_dir).judge(judge_input)
+ assert j.passed and j.acceptance_results == {}
+ assert "acceptance" not in model.requests[0].response_schema["properties"]
diff --git a/harness/tests/models/__init__.py b/harness/tests/models/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/models/test_anthropic.py b/harness/tests/models/test_anthropic.py
new file mode 100644
index 00000000..086471d3
--- /dev/null
+++ b/harness/tests/models/test_anthropic.py
@@ -0,0 +1,301 @@
+"""AnthropicModel with a fake anthropic client (offline)."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace as NS
+from typing import Any
+
+import httpx
+import pytest
+
+from codeverse.contracts.chat import (
+ ChatMessage,
+ ChatRequest,
+ ImagePart,
+ ToolCallPart,
+ ToolResultPart,
+ ToolSpec,
+)
+from codeverse.models.anthropic import AnthropicModel, classify_exception
+from codeverse.models.anthropic_convert import THINKING_BLOCKS, build_kwargs, to_messages
+from codeverse.models.base import ModelError
+
+PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
+
+
+def msg(blocks: list[Any], *, stop="end_turn", in_tok=100, out_tok=20, cache_read=0, cache_write=0):
+ return NS(
+ id="msg_1",
+ model="claude-opus-5",
+ content=blocks,
+ stop_reason=stop,
+ stop_details=None,
+ usage=NS(
+ input_tokens=in_tok,
+ output_tokens=out_tok,
+ cache_read_input_tokens=cache_read,
+ cache_creation_input_tokens=cache_write,
+ ),
+ )
+
+
+def text(t: str):
+ return NS(type="text", text=t)
+
+
+def tool_use(id_: str, name: str, inp: dict):
+ return NS(type="tool_use", id=id_, name=name, input=inp)
+
+
+class Thinking:
+ type = "thinking"
+
+ def model_dump(self):
+ return {"type": "thinking", "thinking": "hmm", "signature": "sig"}
+
+
+class FakeClient:
+ def __init__(self, script: list[Any]):
+ self.script, self.calls = script, []
+ self.messages = NS(create=self._create)
+
+ def _create(self, **kw):
+ self.calls.append(kw)
+ item = self.script.pop(0)
+ if isinstance(item, BaseException):
+ raise item
+ return item
+
+
+def make(script, model="claude-opus-5", **kw):
+ fc = FakeClient(script)
+ return AnthropicModel(model, client=fc, sleep=lambda s: None, **kw), fc
+
+
+def api_error(status: int, message: str = "err"):
+ import anthropic
+
+ req = httpx.Request("POST", "https://api.anthropic.com/v1/messages")
+ resp = httpx.Response(status, request=req, json={"error": {"message": message}})
+ cls = {
+ 429: anthropic.RateLimitError,
+ 400: anthropic.BadRequestError,
+ 500: anthropic.InternalServerError,
+ 529: anthropic.OverloadedError,
+ }.get(status, anthropic.APIStatusError)
+ return cls(message, response=resp, body=None)
+
+
+def test_text_thinking_adaptive_and_usage_cost():
+ m, fc = make([msg([text("hi")], cache_read=30, cache_write=10)])
+ r = m.generate(
+ ChatRequest(
+ messages=[ChatMessage.user("x")], system="sys", thinking="medium", temperature=0.3
+ )
+ )
+ assert r.text == "hi" and r.finish_reason == "end_turn"
+ kw = fc.calls[0]
+ assert (
+ kw["system"] == "sys"
+ and kw["thinking"] == {"type": "adaptive"}
+ and kw["output_config"] == {"effort": "medium"}
+ )
+ assert "temperature" not in kw # opus-5 rejects sampling params
+ u = r.usage
+ assert (
+ u.input_tokens == 140
+ and u.cached_tokens == 30
+ and u.output_tokens == 20
+ and u.thoughts_tokens == 0
+ )
+ # 100*5 + 30*0.5 + 10*5 + 20*25 + surcharge 10*1.25 (per 1M)
+ assert abs(u.cost_usd - (500 + 15 + 50 + 500 + 12.5) / 1e6) < 1e-12
+
+
+def test_budget_thinking_for_older_models_and_temperature_rules():
+ kw = build_kwargs(
+ ChatRequest(
+ messages=[ChatMessage.user("x")],
+ thinking="high",
+ max_output_tokens=2000,
+ temperature=0.5,
+ ),
+ "claude-haiku-4-5",
+ )
+ assert (
+ kw["thinking"] == {"type": "enabled", "budget_tokens": 16000}
+ and kw["max_tokens"] >= 16000 + 2048
+ )
+ assert "temperature" not in kw
+ kw = build_kwargs(
+ ChatRequest(messages=[ChatMessage.user("x")], thinking="off", temperature=0.5),
+ "claude-haiku-4-5",
+ )
+ assert "thinking" not in kw and kw["temperature"] == 0.5
+ kw = build_kwargs(
+ ChatRequest(messages=[ChatMessage.user("x")], thinking="off"), "claude-opus-4-8"
+ )
+ assert kw["thinking"] == {"type": "disabled"}
+ kw = build_kwargs(
+ ChatRequest(messages=[ChatMessage.user("x")], thinking="off"), "claude-fable-5"
+ )
+ assert "thinking" not in kw and kw["output_config"] == {"effort": "low"}
+
+
+def test_structured_output_via_forced_submit_tool():
+ schema = {"type": "object", "properties": {"a": {"type": "integer"}}, "required": ["a"]}
+ m, fc = make([msg([tool_use("tu_1", "submit", {"a": 1})], stop="tool_use")])
+ r = m.generate(
+ ChatRequest(messages=[ChatMessage.user("x")], response_schema=schema, thinking="off")
+ )
+ assert r.parsed == {"a": 1} and json.loads(r.text) == {"a": 1} and r.tool_calls == []
+ kw = fc.calls[0]
+ assert kw["tool_choice"] == {"type": "tool", "name": "submit"}
+ assert (
+ kw["tools"][0]["name"] == "submit"
+ and kw["tools"][0]["input_schema"]["additionalProperties"] is False
+ )
+
+
+def test_structured_output_with_thinking_uses_auto_and_text_fallback():
+ schema = {"type": "object"}
+ m, fc = make([msg([text('```json\n{"b": 2}\n```')])])
+ r = m.generate(
+ ChatRequest(messages=[ChatMessage.user("x")], response_schema=schema, thinking="low")
+ )
+ assert r.parsed == {"b": 2}
+ kw = fc.calls[0]
+ assert "tool_choice" not in kw and "submit" in kw["system"]
+
+
+def test_output_config_json_mode():
+ m, fc = make([msg([text('{"c": 3}')])], json_mode="output_config")
+ r = m.generate(
+ ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"})
+ )
+ assert r.parsed == {"c": 3}
+ assert fc.calls[0]["output_config"]["format"]["type"] == "json_schema"
+
+
+def test_tool_roundtrip_with_thinking_blocks_replayed():
+ tool = ToolSpec(
+ name="measure",
+ description="d",
+ parameters={"type": "object", "properties": {"part": {"type": "string"}}},
+ )
+ m, fc = make(
+ [
+ msg([Thinking(), tool_use("tu_9", "measure", {"part": "all"})], stop="tool_use"),
+ msg([text("45 cm")]),
+ ]
+ )
+ req = ChatRequest(messages=[ChatMessage.user("measure")], tools=[tool])
+ r = m.generate(req)
+ call = r.tool_calls[0]
+ assert call.id == "tu_9" and call.arguments == {"part": "all"} and r.finish_reason == "tool_use"
+ assert THINKING_BLOCKS.get("tu_9")
+ msgs = [
+ *req.messages,
+ ChatMessage(role="assistant", parts=[call]),
+ ChatMessage(
+ role="tool",
+ parts=[
+ ToolResultPart(
+ call_id="tu_9",
+ name="measure",
+ content="0.45",
+ images=[ImagePart(data_b64=PNG_B64)],
+ )
+ ],
+ ),
+ ]
+ r2 = m.generate(ChatRequest(messages=msgs, tools=[tool]))
+ assert r2.text == "45 cm"
+ sent = fc.calls[1]["messages"]
+ assert (
+ sent[1]["role"] == "assistant"
+ and sent[1]["content"][0]["type"] == "thinking"
+ and sent[1]["content"][1]["type"] == "tool_use"
+ )
+ tr = sent[2]["content"][0]
+ assert (
+ tr["type"] == "tool_result"
+ and tr["tool_use_id"] == "tu_9"
+ and tr["content"][1]["type"] == "image"
+ )
+ assert fc.calls[0]["tools"][0]["input_schema"]["properties"]["part"]["type"] == "string"
+
+
+def test_images_base64_and_message_merging():
+ msgs = to_messages(
+ [
+ ChatMessage.user(
+ "a", images=[ImagePart(data_b64=PNG_B64, mime="image/png", label="L")]
+ ),
+ ChatMessage.user("b"),
+ ]
+ )
+ assert len(msgs) == 1 and [b["type"] for b in msgs[0]["content"]] == [
+ "text",
+ "text",
+ "image",
+ "text",
+ ]
+ assert msgs[0]["content"][2]["source"]["media_type"] == "image/png"
+
+
+def test_retry_on_429_529_5xx_and_not_on_400():
+ m, fc = make([api_error(429), api_error(529), api_error(500), msg([text("ok")])])
+ assert (
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"
+ and len(fc.calls) == 4
+ )
+ m, fc = make([api_error(400, "bad"), msg([text("never")])])
+ with pytest.raises(ModelError) as ei:
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert not ei.value.retryable and ei.value.status == 400 and len(fc.calls) == 1
+
+
+def test_exhaustion_raises_retryable():
+ m, fc = make([api_error(429)] * 6)
+ with pytest.raises(ModelError) as ei:
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert ei.value.retryable and len(fc.calls) == 6
+
+
+def test_refusal_and_empty():
+ m, _ = make([msg([], stop="refusal")])
+ with pytest.raises(ModelError) as ei:
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert not ei.value.retryable
+ m, fc = make([msg([], stop="end_turn"), msg([text("ok")])])
+ assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"
+
+
+def test_classify_connection_errors():
+ import anthropic
+
+ req = httpx.Request("POST", "https://api.anthropic.com")
+ assert classify_exception(anthropic.APITimeoutError(request=req)).retryable
+ assert classify_exception(anthropic.APIConnectionError(request=req)).retryable
+ assert not classify_exception(RuntimeError("x")).retryable
+
+
+def test_missing_key_is_loud(monkeypatch):
+ monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
+ from codeverse.config import get_settings
+
+ get_settings.cache_clear()
+ m = AnthropicModel("claude-opus-5")
+ if not get_settings().anthropic_api_key:
+ with pytest.raises(ModelError):
+ m.client()
+ get_settings.cache_clear()
+
+
+def test_tool_call_part_in_user_message_ignored_but_assistant_first_gets_user_prefix():
+ msgs = to_messages(
+ [ChatMessage(role="assistant", parts=[ToolCallPart(id="t", name="n", arguments={})])]
+ )
+ assert msgs[0]["role"] == "user" and msgs[1]["role"] == "assistant"
diff --git a/harness/tests/models/test_gemini.py b/harness/tests/models/test_gemini.py
new file mode 100644
index 00000000..0ddc2b5c
--- /dev/null
+++ b/harness/tests/models/test_gemini.py
@@ -0,0 +1,370 @@
+"""GeminiModel with a fake google-genai client (offline)."""
+
+from __future__ import annotations
+
+import base64
+import json
+from typing import Any
+
+import pytest
+from google.genai import errors as genai_errors
+from google.genai import types
+
+from codeverse.contracts.chat import (
+ ChatMessage,
+ ChatRequest,
+ ImagePart,
+ TextPart,
+ ToolResultPart,
+ ToolSpec,
+)
+from codeverse.contracts.plan import StaticPlan
+from codeverse.models.base import ModelError
+from codeverse.models.gemini import GeminiModel, classify_exception
+from codeverse.models.gemini_convert import SIGNATURES, build_config, to_contents
+from codeverse.models.keypool import KeyPool
+
+PNG_1PX = base64.b64decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
+)
+
+
+def text_response(
+ text: str, *, finish: str = "STOP", thoughts: int = 3
+) -> types.GenerateContentResponse:
+ return types.GenerateContentResponse(
+ model_version="gemini-3.7-flash",
+ candidates=[
+ types.Candidate(
+ content=types.Content(role="model", parts=[types.Part.from_text(text=text)]),
+ finish_reason=finish,
+ )
+ ],
+ usage_metadata=types.GenerateContentResponseUsageMetadata(
+ prompt_token_count=100,
+ candidates_token_count=20,
+ thoughts_token_count=thoughts,
+ cached_content_token_count=40,
+ ),
+ )
+
+
+def call_response(
+ name: str, args: dict, sig: bytes | None = b"sig-bytes"
+) -> types.GenerateContentResponse:
+ part = types.Part(function_call=types.FunctionCall(name=name, args=args))
+ part.thought_signature = sig
+ return types.GenerateContentResponse(
+ candidates=[
+ types.Candidate(content=types.Content(role="model", parts=[part]), finish_reason="STOP")
+ ],
+ usage_metadata=types.GenerateContentResponseUsageMetadata(
+ prompt_token_count=10, candidates_token_count=5
+ ),
+ )
+
+
+class FakeModels:
+ def __init__(self, script: list[Any], key: str, log: list[dict]):
+ self.script, self.key, self.log = script, key, log
+
+ def generate_content(self, *, model: str, contents, config):
+ self.log.append({"key": self.key, "model": model, "contents": contents, "config": config})
+ item = self.script.pop(0)
+ if isinstance(item, BaseException):
+ raise item
+ return item
+
+
+class FakeClient:
+ def __init__(self, script, key, log):
+ self.models = FakeModels(script, key, log)
+
+
+def make_model(script: list[Any], keys=("k1", "k2", "k3"), **kw):
+ """Shared script across keys (each call pops the next item); log records which key was used."""
+ log: list[dict] = []
+ pool = KeyPool(list(keys), cooldown_s=30)
+ m = GeminiModel(
+ "gemini-3.7-flash",
+ pool=pool,
+ sleep=lambda s: None,
+ client_factory=lambda key: FakeClient(script, key, log),
+ **kw,
+ )
+ return m, log, pool
+
+
+def test_text_usage_cost_and_raw():
+ m, log, _ = make_model([text_response("hello")])
+ r = m.generate(
+ ChatRequest(
+ messages=[ChatMessage.user("hi")], system="sys", thinking="medium", temperature=0.2
+ )
+ )
+ assert r.text == "hello" and r.finish_reason == "STOP" and r.parsed is None
+ u = r.usage
+ assert (u.input_tokens, u.output_tokens, u.thoughts_tokens, u.cached_tokens) == (100, 20, 3, 40)
+ assert u.cost_usd > 0 and u.backend == "gemini" and u.model == "gemini-3.7-flash"
+ cfg = log[0]["config"]
+ assert cfg.system_instruction == "sys" and cfg.temperature == 0.2
+ assert cfg.thinking_config.thinking_budget == 4096
+ assert r.raw["key"] == "…k1"
+
+
+def test_structured_output_parsed_and_schema_sanitised():
+ payload = {
+ "object_name": "Stool",
+ "summary": "s",
+ "overall_bbox": {"center": [0, 0, 0.25], "extents": [0.4, 0.4, 0.5]},
+ "parts": [
+ {
+ "name": "Seat",
+ "role": "r",
+ "description": "d",
+ "bbox": {"center": [0, 0, 0.45], "extents": [0.4, 0.4, 0.05]},
+ }
+ ],
+ }
+ m, log, _ = make_model([text_response("```json\n" + json.dumps(payload) + "\n```")])
+ r = m.generate(
+ ChatRequest(
+ messages=[ChatMessage.user("plan")], response_schema=StaticPlan.model_json_schema()
+ )
+ )
+ assert StaticPlan.model_validate(r.parsed).object_name == "Stool"
+ cfg = log[0]["config"]
+ assert cfg.response_mime_type == "application/json"
+ assert "$defs" not in json.dumps(
+ cfg.response_schema
+ if isinstance(cfg.response_schema, dict)
+ else cfg.response_schema.model_dump()
+ )
+
+
+def test_bad_json_is_retried_then_raises():
+ m, log, _ = make_model([text_response("not json"), text_response('{"ok": true}')])
+ r = m.generate(
+ ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"})
+ )
+ assert r.parsed == {"ok": True} and len(log) == 2
+ m2, _, _ = make_model([text_response("nope")] * 6)
+ with pytest.raises(ModelError) as ei:
+ m2.generate(
+ ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"})
+ )
+ assert ei.value.retryable
+
+
+def test_429_rotates_keys_and_cools_down():
+ err = genai_errors.APIError(
+ 429,
+ {
+ "error": {
+ "message": "quota",
+ "status": "RESOURCE_EXHAUSTED",
+ "details": [{"retryDelay": "7s"}],
+ }
+ },
+ )
+ m, log, pool = make_model([err, err, text_response("third time lucky")])
+ r = m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert r.text == "third time lucky"
+ assert [e["key"] for e in log] == ["k1", "k2", "k3"]
+ st = pool.stats()
+ assert st["429"] == 2 and st["ok"] == 1 and st["n_cooling"] == 2
+ cooling = {k["key"]: k["cooldown_s"] for k in st["keys"]}
+ assert 0 < cooling["…k1"] <= 7.0 # retryDelay honoured
+
+
+def test_5xx_retries_then_gives_up_with_retryable_error():
+ err = genai_errors.APIError(503, {"error": {"message": "high demand", "status": "UNAVAILABLE"}})
+ slept: list[float] = []
+ m, log, _ = make_model([err] * 6)
+ m._sleep = slept.append
+ with pytest.raises(ModelError) as ei:
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert ei.value.retryable and ei.value.status == 503
+ assert len(log) == 6 and len(slept) == 5 and slept[1] > slept[0] / 2
+
+
+def test_400_is_not_retried():
+ err = genai_errors.APIError(
+ 400, {"error": {"message": "Invalid argument", "status": "INVALID_ARGUMENT"}}
+ )
+ m, log, _ = make_model([err, text_response("never")])
+ with pytest.raises(ModelError) as ei:
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert not ei.value.retryable and len(log) == 1
+
+
+def test_thinking_rejected_falls_back_without_thinking_config():
+ err = genai_errors.APIError(
+ 400,
+ {
+ "error": {
+ "message": "Thinking level is not supported for this model",
+ "status": "INVALID_ARGUMENT",
+ }
+ },
+ )
+ m, log, _ = make_model([err, text_response("ok")])
+ r = m.generate(ChatRequest(messages=[ChatMessage.user("x")], thinking="high"))
+ assert r.text == "ok"
+ assert log[0]["config"].thinking_config is not None and log[1]["config"].thinking_config is None
+ assert any("thinking" in w for w in r.raw["warnings"])
+ # sticky for the next call
+ m.pool # noqa: B018
+ log.clear()
+ m._client_factory = lambda key: FakeClient([text_response("again")], key, log)
+ m.generate(ChatRequest(messages=[ChatMessage.user("y")]))
+ assert log[0]["config"].thinking_config is None
+
+
+def test_tool_call_roundtrip_and_signature_cache():
+ tool = ToolSpec(
+ name="measure",
+ description="m",
+ parameters={"type": "object", "properties": {"part": {"type": "string"}}},
+ )
+ m, log, _ = make_model([call_response("measure", {"part": "all"}), text_response("45 cm")])
+ req = ChatRequest(messages=[ChatMessage.user("measure it")], tools=[tool])
+ r = m.generate(req)
+ assert (
+ r.tool_calls
+ and r.tool_calls[0].name == "measure"
+ and r.tool_calls[0].arguments == {"part": "all"}
+ )
+ assert r.usage.tool_calls == 1 and r.text == ""
+ cfg = log[0]["config"]
+ assert cfg.tools[0].function_declarations[0].name == "measure"
+ assert cfg.response_mime_type is None
+ call = r.tool_calls[0]
+ assert SIGNATURES.get(call.id) == b"sig-bytes"
+ msgs = [
+ *req.messages,
+ ChatMessage(role="assistant", parts=[call]),
+ ChatMessage(
+ role="tool",
+ parts=[
+ ToolResultPart(call_id=call.id, name="measure", content=json.dumps({"h": 0.45}))
+ ],
+ ),
+ ]
+ r2 = m.generate(ChatRequest(messages=msgs, tools=[tool]))
+ assert r2.text == "45 cm" and not r2.tool_calls
+ contents = log[1]["contents"]
+ assert [c.role for c in contents] == ["user", "model", "user"]
+ fc_part = contents[1].parts[0]
+ assert fc_part.function_call.name == "measure" and fc_part.thought_signature == b"sig-bytes"
+ fr = contents[2].parts[0].function_response
+ assert fr.name == "measure" and fr.response == {"h": 0.45}
+
+
+def test_tools_plus_schema_warns_and_drops_json_mode():
+ tool = ToolSpec(name="t", description="d", parameters={"type": "object", "properties": {}})
+ m, log, _ = make_model([text_response('{"a": 1}')])
+ r = m.generate(
+ ChatRequest(
+ messages=[ChatMessage.user("x")], tools=[tool], response_schema={"type": "object"}
+ )
+ )
+ assert r.parsed == {"a": 1}
+ assert log[0]["config"].response_mime_type is None
+ assert any("response_schema ignored" in w for w in r.raw["warnings"])
+
+
+def test_images_inline_in_order(tmp_path):
+ p = tmp_path / "img.png"
+ p.write_bytes(PNG_1PX)
+ m, log, _ = make_model([text_response("red")])
+ msg = ChatMessage.user(
+ "look",
+ images=[
+ ImagePart(path=str(p), label="view1"),
+ ImagePart(data_b64=base64.b64encode(PNG_1PX).decode(), mime="image/png"),
+ ],
+ )
+ m.generate(ChatRequest(messages=[msg]))
+ parts = log[0]["contents"][0].parts
+ kinds = [("img" if pt.inline_data else "txt") for pt in parts]
+ assert kinds == ["txt", "txt", "img", "img"]
+ assert parts[2].inline_data.data == PNG_1PX and parts[2].inline_data.mime_type == "image/png"
+
+
+def test_missing_image_is_loud():
+ m, _, _ = make_model([text_response("x")])
+ with pytest.raises(ModelError):
+ m.generate(
+ ChatRequest(
+ messages=[ChatMessage.user("look", images=[ImagePart(path="/nonexistent.png")])]
+ )
+ )
+
+
+def test_empty_candidates_and_blocked_prompt():
+ empty = types.GenerateContentResponse(candidates=[], usage_metadata=None)
+ m, log, _ = make_model([empty, text_response("ok")])
+ assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"
+ blocked = types.GenerateContentResponse(
+ candidates=[],
+ prompt_feedback=types.GenerateContentResponsePromptFeedback(block_reason="SAFETY"),
+ )
+ m2, log2, _ = make_model([blocked, text_response("never")])
+ with pytest.raises(ModelError) as ei:
+ m2.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert not ei.value.retryable and len(log2) == 1
+
+
+def test_classify_exception_transport():
+ import httpx
+
+ assert classify_exception(httpx.ReadTimeout("t")).retryable
+ assert classify_exception(httpx.ConnectError("c")).retryable
+ assert not classify_exception(ValueError("v")).retryable
+
+
+def test_to_contents_merges_same_role_and_requires_content():
+ msgs = [
+ ChatMessage.user("a"),
+ ChatMessage(role="user", parts=[TextPart(text="b")]),
+ ChatMessage.assistant("c"),
+ ]
+ c = to_contents(msgs)
+ assert [x.role for x in c] == ["user", "model"] and len(c[0].parts) == 2
+ with pytest.raises(ModelError):
+ to_contents([ChatMessage(role="user", parts=[])])
+
+
+def test_build_config_thinking_off_budget_zero():
+ cfg = build_config(
+ ChatRequest(messages=[ChatMessage.user("x")], thinking="off"), timeout_ms=1000
+ )
+ assert cfg.thinking_config.thinking_budget == 0
+ cfg = build_config(
+ ChatRequest(messages=[ChatMessage.user("x")]), timeout_ms=1000, use_thinking=False
+ )
+ assert cfg.thinking_config is None
+
+
+def test_no_keys_is_loud():
+ with pytest.raises(ModelError):
+ GeminiModel("gemini-3.7-flash", keys=[])
+
+
+def test_truncated_json_is_not_retried():
+ m, log, _ = make_model(
+ [text_response('{"a": [1, 2', finish="MAX_TOKENS"), text_response("never")]
+ )
+ with pytest.raises(ModelError) as ei:
+ m.generate(
+ ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"})
+ )
+ assert not ei.value.retryable and len(log) == 1 and "max_output_tokens" in str(ei.value)
+
+
+def test_empty_max_tokens_is_not_retried():
+ m, log, _ = make_model([text_response("", finish="MAX_TOKENS", thoughts=49), text_response("never")])
+ with pytest.raises(ModelError) as ei:
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_output_tokens=50))
+ assert not ei.value.retryable and len(log) == 1 and "thinking" in str(ei.value)
diff --git a/harness/tests/models/test_keypool.py b/harness/tests/models/test_keypool.py
new file mode 100644
index 00000000..d641b61a
--- /dev/null
+++ b/harness/tests/models/test_keypool.py
@@ -0,0 +1,133 @@
+"""KeyPool: rotation, 429 cooldown, buckets, health, exhaustion, stats."""
+
+from __future__ import annotations
+
+import threading
+
+import pytest
+
+from codeverse.models.keypool import KeyPool, KeyPoolExhausted, TokenBucket
+
+
+class Clock:
+ def __init__(self) -> None:
+ self.t = 1000.0
+
+ def __call__(self) -> float:
+ return self.t
+
+ def sleep(self, s: float) -> None:
+ self.t += s
+
+
+def make(keys=("k1", "k2", "k3"), **kw) -> tuple[KeyPool, Clock]:
+ c = Clock()
+ return KeyPool(list(keys), clock=c, sleep=c.sleep, **kw), c
+
+
+def test_round_robin_order():
+ pool, _ = make()
+ assert [pool.acquire() for _ in range(4)] == ["k1", "k2", "k3", "k1"]
+
+
+def test_dedupes_and_rejects_empty():
+ pool, _ = make(keys=("a", "a", "", "b"))
+ assert pool.keys == ["a", "b"]
+ with pytest.raises(ValueError):
+ KeyPool([])
+
+
+def test_429_cools_key_down_and_rotates():
+ pool, clock = make(cooldown_s=30)
+ k = pool.acquire()
+ assert k == "k1"
+ pool.report(k, "429")
+ # next acquires skip k1 while it cools
+ assert [pool.acquire() for _ in range(4)] == ["k2", "k3", "k2", "k3"]
+ clock.t += 31
+ assert "k1" in [pool.acquire() for _ in range(3)]
+ st = pool.stats()
+ assert st["429"] == 1 and st["n_keys"] == 3
+
+
+def test_exclude_skips_failed_keys():
+ pool, _ = make()
+ assert pool.acquire(exclude={"k1", "k2"}) == "k3"
+ with pytest.raises(KeyPoolExhausted):
+ pool.acquire(exclude={"k1", "k2", "k3"})
+
+
+def test_rpm_bucket_blocks_then_refills():
+ pool, clock = make(keys=("solo",), rpm_per_key=60) # 1 token / s, capacity 60
+ for _ in range(60):
+ pool.acquire(timeout_s=0.0)
+ with pytest.raises(KeyPoolExhausted):
+ pool.acquire(timeout_s=0.0)
+ # blocking acquire advances the fake clock until a token refills
+ t0 = clock.t
+ assert pool.acquire(timeout_s=10.0) == "solo"
+ assert clock.t > t0
+
+
+def test_all_cooling_blocks_until_cooldown_ends():
+ pool, clock = make(keys=("a", "b"), cooldown_s=5)
+ for k in ("a", "b"):
+ pool.report(k, "429")
+ t0 = clock.t
+ assert pool.acquire(timeout_s=60) in ("a", "b")
+ assert clock.t - t0 >= 5 - 1e-6
+ with pytest.raises(KeyPoolExhausted):
+ pool.report("a", "429")
+ pool.report("b", "429")
+ pool.acquire(timeout_s=1.0)
+
+
+def test_health_score_prefers_healthy_keys():
+ pool, clock = make(keys=("bad", "good"), cooldown_s=0.0)
+ for _ in range(3):
+ pool.report("bad", "429") # health 0.125, cooldown 0 → still "available"
+ picks = [pool.acquire() for _ in range(4)]
+ assert picks == ["good"] * 4
+ pool.report("good", "ok")
+ s = {k["key"]: k for k in pool.stats()["keys"]}
+ assert s["…good"]["health"] == 1.0 and s["…bad"]["health"] < 0.3
+ # passive recovery over time
+ clock.t += 200
+ assert pool.acquire() in ("bad", "good")
+ s = {k["key"]: k for k in pool.stats()["keys"]}
+ assert s["…bad"]["health"] > 0.9
+
+
+def test_tpm_bucket_honours_hint():
+ pool, _ = make(keys=("a", "b"), tpm_per_key=1000)
+ assert pool.acquire(tokens_hint=800) == "a"
+ assert pool.acquire(tokens_hint=800) == "b" # a has only 200 left
+ with pytest.raises(KeyPoolExhausted):
+ pool.acquire(tokens_hint=800, timeout_s=0.0)
+
+
+def test_thread_safety_smoke():
+ pool = KeyPool([f"k{i}" for i in range(5)], rpm_per_key=100000)
+ counts: dict[str, int] = {}
+ lock = threading.Lock()
+
+ def worker():
+ for _ in range(200):
+ k = pool.acquire()
+ pool.report(k, "ok")
+ with lock:
+ counts[k] = counts.get(k, 0) + 1
+
+ ts = [threading.Thread(target=worker) for _ in range(8)]
+ for t in ts:
+ t.start()
+ for t in ts:
+ t.join()
+ assert sum(counts.values()) == 1600 and len(counts) == 5
+
+
+def test_token_bucket_math():
+ b = TokenBucket(capacity=10, rate=1.0, updated=0.0)
+ assert b.try_take(10, 0.0) and not b.try_take(1, 0.0)
+ assert b.wait_for(5, 0.0) == 5.0
+ assert b.try_take(5, 5.0)
diff --git a/harness/tests/models/test_live_gemini.py b/harness/tests/models/test_live_gemini.py
new file mode 100644
index 00000000..56a97455
--- /dev/null
+++ b/harness/tests/models/test_live_gemini.py
@@ -0,0 +1,127 @@
+"""Live Gemini checks (need keys + network): ``pytest -m live tests/models``."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from codeverse.contracts.chat import (
+ ChatMessage,
+ ChatRequest,
+ ImagePart,
+ TextPart,
+ ToolResultPart,
+ ToolSpec,
+)
+from codeverse.contracts.plan import StaticPlan
+from codeverse.models import get_chat_model
+
+pytestmark = pytest.mark.live
+
+MODEL = "gemini:gemini-3.7-flash"
+
+
[email protected](scope="module")
+def model():
+ from codeverse.config import get_settings
+
+ if not get_settings().gemini_api_keys:
+ pytest.skip("no gemini keys")
+ return get_chat_model(MODEL)
+
+
+def test_text(model):
+ r = model.generate(
+ ChatRequest(
+ messages=[ChatMessage.user("Reply with exactly: pong")],
+ thinking="off",
+ max_output_tokens=200,
+ )
+ )
+ assert "pong" in r.text.lower()
+ assert r.usage.input_tokens > 0 and r.usage.output_tokens > 0 and r.usage.cost_usd > 0
+ assert r.finish_reason == "STOP"
+
+
+def test_structured_static_plan(model):
+ r = model.generate(
+ ChatRequest(
+ messages=[
+ ChatMessage.user(
+ "Plan 'a simple wooden stool' (round seat, 4 legs, ring stretcher). Z-up, meters, stands on ground. PascalCase part names; attach_to names another part."
+ )
+ ],
+ system="You are a 3D planner. Output JSON matching the schema only.",
+ response_schema=StaticPlan.model_json_schema(),
+ temperature=0.4,
+ thinking="medium",
+ max_output_tokens=8000,
+ label="planner",
+ )
+ )
+ plan = StaticPlan.model_validate(r.parsed)
+ assert len(plan.parts) >= 3 and plan.overall_bbox.extents[2] > 0
+ assert r.usage.thoughts_tokens >= 0 and r.usage.cost_usd > 0
+
+
+def test_vision(model, tmp_path):
+ from PIL import Image, ImageDraw
+
+ img = Image.new("RGB", (128, 128), "white")
+ ImageDraw.Draw(img).ellipse((24, 24, 104, 104), fill="red")
+ p = tmp_path / "red.png"
+ img.save(p)
+ r = model.generate(
+ ChatRequest(
+ messages=[
+ ChatMessage.user(
+ "What colour is the shape? One word.",
+ images=[ImagePart(path=str(p), label="probe")],
+ )
+ ],
+ thinking="off",
+ max_output_tokens=200,
+ )
+ )
+ assert "red" in r.text.lower()
+
+
+def test_tool_roundtrip(model):
+ tool = ToolSpec(
+ name="measure",
+ description="Measure the bounding box (meters) of the built object; returns extents x,y,z.",
+ parameters={
+ "type": "object",
+ "properties": {"part": {"type": "string", "description": "part name or 'all'"}},
+ "required": ["part"],
+ },
+ )
+ msgs = [
+ ChatMessage.user(
+ "Use the measure tool on the whole object, then report its height in cm. Never guess."
+ )
+ ]
+ r = model.generate(
+ ChatRequest(messages=msgs, tools=[tool], thinking="low", max_output_tokens=2000)
+ )
+ assert r.tool_calls and r.tool_calls[0].name == "measure"
+ call = r.tool_calls[0]
+ parts = ([TextPart(text=r.text)] if r.text else []) + [call]
+ msgs.append(ChatMessage(role="assistant", parts=parts))
+ msgs.append(
+ ChatMessage(
+ role="tool",
+ parts=[
+ ToolResultPart(
+ call_id=call.id,
+ name="measure",
+ content=json.dumps({"extents_m": [0.35, 0.35, 0.45]}),
+ )
+ ],
+ )
+ )
+ r2 = model.generate(
+ ChatRequest(messages=msgs, tools=[tool], thinking="low", max_output_tokens=2000)
+ )
+ assert "45" in r2.text and not r2.tool_calls
diff --git a/harness/tests/models/test_openai.py b/harness/tests/models/test_openai.py
new file mode 100644
index 00000000..df956017
--- /dev/null
+++ b/harness/tests/models/test_openai.py
@@ -0,0 +1,275 @@
+"""OpenAIModel with a fake openai client (offline)."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace as NS
+from typing import Any
+
+import httpx
+import pytest
+
+from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart, ToolResultPart, ToolSpec
+from codeverse.models.base import ModelError
+from codeverse.models.openai import OpenAIModel, classify_exception
+from codeverse.models.openai_convert import build_kwargs, reasoning_effort, to_messages
+
+PNG_B64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
+
+
+def completion(
+ content: str | None,
+ *,
+ tool_calls=None,
+ finish="stop",
+ prompt=100,
+ comp=30,
+ cached=20,
+ reasoning=10,
+):
+ return NS(
+ id="cmpl_1",
+ model="gpt-5.6-sol",
+ choices=[
+ NS(
+ message=NS(content=content, tool_calls=tool_calls, refusal=None),
+ finish_reason=finish,
+ )
+ ],
+ usage=NS(
+ prompt_tokens=prompt,
+ completion_tokens=comp,
+ prompt_tokens_details=NS(cached_tokens=cached),
+ completion_tokens_details=NS(reasoning_tokens=reasoning),
+ ),
+ )
+
+
+def tc(id_, name, args: dict):
+ return NS(id=id_, type="function", function=NS(name=name, arguments=json.dumps(args)))
+
+
+class FakeClient:
+ def __init__(self, script: list[Any]):
+ self.script, self.calls = script, []
+ self.chat = NS(completions=NS(create=self._create))
+
+ def _create(self, **kw):
+ self.calls.append(kw)
+ item = self.script.pop(0)
+ if isinstance(item, BaseException):
+ raise item
+ return item
+
+
+def make(script, model="gpt-5.6-sol", **kw):
+ fc = FakeClient(script)
+ return OpenAIModel(model, client=fc, sleep=lambda s: None, **kw), fc
+
+
+def api_error(status: int, message: str = "err"):
+ import openai
+
+ req = httpx.Request("POST", "https://api.openai.com/v1/chat/completions")
+ resp = httpx.Response(status, request=req, json={"error": {"message": message}})
+ cls = {
+ 429: openai.RateLimitError,
+ 400: openai.BadRequestError,
+ 500: openai.InternalServerError,
+ }.get(status, openai.APIStatusError)
+ return cls(message, response=resp, body={"error": {"message": message}})
+
+
+def test_text_reasoning_effort_usage_cost():
+ m, fc = make([completion("hello")])
+ r = m.generate(
+ ChatRequest(
+ messages=[ChatMessage.user("x")], system="sys", thinking="high", temperature=0.3
+ )
+ )
+ assert r.text == "hello" and r.finish_reason == "stop"
+ kw = fc.calls[0]
+ assert kw["messages"][0] == {"role": "system", "content": "sys"}
+ assert (
+ kw["reasoning_effort"] == "high"
+ and "temperature" not in kw
+ and kw["max_completion_tokens"] == 16000
+ )
+ u = r.usage
+ assert (u.input_tokens, u.cached_tokens, u.output_tokens, u.thoughts_tokens) == (
+ 100,
+ 20,
+ 20,
+ 10,
+ )
+ # 80*5 + 20*0.5 + 30*30 per 1M
+ assert abs(u.cost_usd - (400 + 10 + 900) / 1e6) < 1e-12
+
+
+def test_reasoning_effort_mapping_and_temperature_for_non_reasoning():
+ assert reasoning_effort("gpt-5", "off") == "minimal"
+ assert reasoning_effort("gpt-5.5", "off") == "none"
+ assert reasoning_effort("o3", "off") == "low"
+ assert reasoning_effort("gpt-5.6-sol", "medium") == "medium"
+ assert reasoning_effort("gpt-4.1", "high") is None
+ kw = build_kwargs(
+ ChatRequest(messages=[ChatMessage.user("x")], temperature=0.1),
+ "gpt-4.1",
+ strict_schema=False,
+ )
+ assert kw["temperature"] == 0.1 and "reasoning_effort" not in kw
+
+
+def test_json_schema_strict_then_fallback_to_non_strict():
+ schema = {
+ "type": "object",
+ "properties": {"a": {"type": "integer"}, "b": {"type": "string", "default": "x"}},
+ "required": ["a"],
+ }
+ m, fc = make(
+ [
+ api_error(400, "Invalid schema for response_format 'response': strict mode ..."),
+ completion('{"a": 1}'),
+ ]
+ )
+ r = m.generate(ChatRequest(messages=[ChatMessage.user("x")], response_schema=schema))
+ assert r.parsed == {"a": 1} and len(fc.calls) == 2
+ first, second = (
+ fc.calls[0]["response_format"]["json_schema"],
+ fc.calls[1]["response_format"]["json_schema"],
+ )
+ assert (
+ first["strict"] is True
+ and first["schema"]["additionalProperties"] is False
+ and set(first["schema"]["required"]) == {"a", "b"}
+ )
+ assert second["strict"] is False and second["schema"]["required"] == ["a"]
+ # sticky: later calls go straight to strict=false
+ fc.script.append(completion('{"a": 2}'))
+ m.generate(ChatRequest(messages=[ChatMessage.user("y")], response_schema=schema))
+ assert fc.calls[2]["response_format"]["json_schema"]["strict"] is False
+
+
+def test_bad_json_retried():
+ m, fc = make([completion("garbage"), completion('{"ok": 1}')])
+ r = m.generate(
+ ChatRequest(messages=[ChatMessage.user("x")], response_schema={"type": "object"})
+ )
+ assert r.parsed == {"ok": 1} and len(fc.calls) == 2
+
+
+def test_tool_roundtrip_and_images_in_tool_results():
+ tool = ToolSpec(
+ name="measure",
+ description="d",
+ parameters={"type": "object", "properties": {"part": {"type": "string"}}},
+ )
+ m, fc = make(
+ [
+ completion(
+ None, tool_calls=[tc("call_1", "measure", {"part": "all"})], finish="tool_calls"
+ ),
+ completion("45 cm"),
+ ]
+ )
+ req = ChatRequest(messages=[ChatMessage.user("measure")], tools=[tool])
+ r = m.generate(req)
+ call = r.tool_calls[0]
+ assert (
+ call.id == "call_1"
+ and call.arguments == {"part": "all"}
+ and r.finish_reason == "tool_calls"
+ and r.text == ""
+ )
+ assert (
+ fc.calls[0]["tools"][0]["function"]["name"] == "measure"
+ and fc.calls[0]["tool_choice"] == "auto"
+ )
+ msgs = [
+ *req.messages,
+ ChatMessage(role="assistant", parts=[call]),
+ ChatMessage(
+ role="tool",
+ parts=[
+ ToolResultPart(
+ call_id="call_1",
+ name="measure",
+ content="0.45",
+ images=[ImagePart(data_b64=PNG_B64)],
+ )
+ ],
+ ),
+ ]
+ r2 = m.generate(ChatRequest(messages=msgs, tools=[tool]))
+ assert r2.text == "45 cm"
+ sent = fc.calls[1]["messages"]
+ assert (
+ sent[1]["role"] == "assistant"
+ and sent[1]["tool_calls"][0]["function"]["arguments"] == '{"part": "all"}'
+ )
+ assert sent[2] == {"role": "tool", "tool_call_id": "call_1", "content": "0.45"}
+ assert sent[3]["role"] == "user" and sent[3]["content"][0]["type"] == "image_url"
+ assert sent[3]["content"][0]["image_url"]["url"].startswith("data:image/png;base64,")
+
+
+def test_bad_tool_arguments_retryable():
+ bad = NS(id="c", type="function", function=NS(name="f", arguments="{not json"))
+ m, fc = make([completion(None, tool_calls=[bad], finish="tool_calls"), completion("fine")])
+ assert (
+ m.generate(
+ ChatRequest(
+ messages=[ChatMessage.user("x")],
+ tools=[ToolSpec(name="f", description="d", parameters={})],
+ )
+ ).text
+ == "fine"
+ )
+
+
+def test_images_data_urls():
+ msgs = to_messages(
+ [
+ ChatMessage.user(
+ "look", images=[ImagePart(data_b64=PNG_B64, mime="image/png", label="v")]
+ )
+ ],
+ "",
+ )
+ c = msgs[0]["content"]
+ assert [b["type"] for b in c] == ["text", "text", "image_url"]
+
+
+def test_retry_matrix():
+ m, fc = make([api_error(429), api_error(500), completion("ok")])
+ assert (
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"
+ and len(fc.calls) == 3
+ )
+ m, fc = make([api_error(400, "nope")])
+ with pytest.raises(ModelError) as ei:
+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))
+ assert not ei.value.retryable and ei.value.status == 400
+
+
+def test_empty_and_classify():
+ import openai
+
+ m, fc = make([completion(None), completion("ok")])
+ assert m.generate(ChatRequest(messages=[ChatMessage.user("x")])).text == "ok"
+ req = httpx.Request("POST", "https://api.openai.com")
+ assert classify_exception(openai.APITimeoutError(request=req)).retryable
+ assert not classify_exception(KeyError("k")).retryable
+
+
+def test_base_url_from_settings(monkeypatch):
+ from codeverse.config import get_settings
+
+ monkeypatch.setenv("C3V_OPENAI_BASE_URL", "http://localhost:8000/v1")
+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)
+ get_settings.cache_clear()
+ try:
+ m = OpenAIModel("local-model")
+ c = m.client()
+ assert str(c.base_url).startswith("http://localhost:8000/v1")
+ finally:
+ get_settings.cache_clear()
diff --git a/harness/tests/models/test_pricing.py b/harness/tests/models/test_pricing.py
new file mode 100644
index 00000000..5c362fd6
--- /dev/null
+++ b/harness/tests/models/test_pricing.py
@@ -0,0 +1,61 @@
+"""pricing.estimate_cost + lookup."""
+
+from __future__ import annotations
+
+import logging
+
+from codeverse.contracts.common import Usage
+from codeverse.models.pricing import PRICES, cache_write_surcharge, estimate_cost, lookup_price
+
+
+def test_known_models_present():
+ for prov, m in [
+ ("gemini", "gemini-3.7-flash"),
+ ("gemini", "gemini-3.6-flash"),
+ ("gemini", "gemini-3.5-flash"),
+ ("gemini", "gemini-3.1-pro-preview"),
+ ("gemini", "gemini-3.1-flash-lite"),
+ ("anthropic", "claude-opus-5"),
+ ("anthropic", "claude-sonnet-5"),
+ ("anthropic", "claude-haiku-4-5"),
+ ("openai", "gpt-5.6-sol"),
+ ("openai", "gpt-5.5"),
+ ("openai", "gpt-5"),
+ ]:
+ assert (prov, m) in PRICES, m
+
+
+def test_gemini_cost_math():
+ u = Usage(
+ input_tokens=1_000_000, cached_tokens=400_000, output_tokens=100_000, thoughts_tokens=50_000
+ )
+ # 600k*0.75 + 400k*0.075 + 150k*3.75 (per 1M)
+ assert abs(estimate_cost("gemini", "gemini-3.7-flash", u) - (0.45 + 0.03 + 0.5625)) < 1e-9
+
+
+def test_prefix_match_and_boundary():
+ assert (
+ lookup_price("anthropic", "claude-opus-5-20260301")
+ is PRICES[("anthropic", "claude-opus-5")]
+ )
+ assert lookup_price("openai", "gpt-5.5-2026") is PRICES[("openai", "gpt-5.5")]
+ assert lookup_price("openai", "gpt-5") is PRICES[("openai", "gpt-5")]
+ assert lookup_price("openai", "gpt-55") is None
+ assert (
+ lookup_price("gemini", "gemini-3.7-flash-preview-09")
+ is PRICES[("gemini", "gemini-3.7-flash")]
+ )
+
+
+def test_unknown_model_zero_and_warns_once(caplog):
+ caplog.set_level(logging.WARNING)
+ u = Usage(input_tokens=10, output_tokens=10)
+ assert estimate_cost("gemini", "nope-model-x", u) == 0.0
+ assert estimate_cost("gemini", "nope-model-x", u) == 0.0
+ assert sum("nope-model-x" in r.message for r in caplog.records) == 1
+
+
+def test_cache_write_surcharge():
+ # opus-5: write 6.25 vs input 5.00 → 1.25 per 1M extra
+ assert abs(cache_write_surcharge("anthropic", "claude-opus-5", 1_000_000) - 1.25) < 1e-9
+ assert cache_write_surcharge("gemini", "gemini-3.7-flash", 1000) == 0.0
diff --git a/harness/tests/models/test_retry.py b/harness/tests/models/test_retry.py
new file mode 100644
index 00000000..7a542f0b
--- /dev/null
+++ b/harness/tests/models/test_retry.py
@@ -0,0 +1,61 @@
+"""with_retries / backoff_delay."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.models.retry import backoff_delay, with_retries
+
+
+def test_backoff_grows_and_caps():
+ d = [backoff_delay(i, base_delay=1.0, max_delay=8.0, jitter=False) for i in range(1, 7)]
+ assert d == [1.0, 2.0, 4.0, 8.0, 8.0, 8.0]
+ j = backoff_delay(3, base_delay=1.0, max_delay=8.0)
+ assert 2.0 <= j <= 4.0
+
+
+def test_retries_until_success_and_reports():
+ calls: list[int] = []
+ slept: list[float] = []
+ seen: list[tuple[int, float]] = []
+
+ def fn():
+ calls.append(1)
+ if len(calls) < 3:
+ raise TimeoutError("flaky")
+ return "ok"
+
+ out = with_retries(
+ fn,
+ is_retryable=lambda e: isinstance(e, TimeoutError),
+ attempts=5,
+ base_delay=0.5,
+ max_delay=2.0,
+ on_retry=lambda n, e, d: seen.append((n, d)),
+ sleep=slept.append,
+ jitter=False,
+ )
+ assert out == "ok" and len(calls) == 3
+ assert slept == [0.5, 1.0]
+ assert [n for n, _ in seen] == [1, 2]
+
+
+def test_non_retryable_raises_immediately():
+ n = 0
+
+ def fn():
+ nonlocal n
+ n += 1
+ raise ValueError("bad")
+
+ with pytest.raises(ValueError):
+ with_retries(fn, is_retryable=lambda e: False, attempts=5, sleep=lambda s: None)
+ assert n == 1
+
+
+def test_exhausted_raises_last():
+ def fn():
+ raise TimeoutError("always")
+
+ with pytest.raises(TimeoutError):
+ with_retries(fn, is_retryable=lambda e: True, attempts=3, sleep=lambda s: None)
diff --git a/harness/tests/models/test_schema_utils.py b/harness/tests/models/test_schema_utils.py
new file mode 100644
index 00000000..8f3a628a
--- /dev/null
+++ b/harness/tests/models/test_schema_utils.py
@@ -0,0 +1,137 @@
+"""Schema sanitisers + lenient JSON parsing."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from google.genai import types
+from pydantic import BaseModel
+
+from codeverse.contracts.plan import ArticulatedPlan, ScenePlan, StaticPlan
+from codeverse.models.schema_utils import (
+ JsonParseError,
+ inline_refs,
+ parse_json_lenient,
+ to_anthropic_schema,
+ to_gemini_schema,
+ to_openai_strict_schema,
+)
+
+
+def _walk(node, fn):
+ """Visit schema nodes only (values of a ``properties`` map are schemas, the map is not)."""
+ fn(node)
+ if isinstance(node, dict):
+ for k, v in node.items():
+ if k == "properties" and isinstance(v, dict):
+ for sub in v.values():
+ _walk(sub, fn)
+ else:
+ _walk(v, fn)
+ elif isinstance(node, list):
+ for v in node:
+ _walk(v, fn)
+
+
[email protected]("model", [StaticPlan, ArticulatedPlan, ScenePlan])
+def test_gemini_schema_is_clean_and_sdk_valid(model):
+ g = to_gemini_schema(model.model_json_schema())
+
+ def check(n):
+ if isinstance(n, dict):
+ for bad in (
+ "$ref",
+ "$defs",
+ "title",
+ "default",
+ "const",
+ "prefixItems",
+ "additionalProperties",
+ ):
+ assert bad not in n, (bad, n)
+ if "anyOf" in n:
+ assert all(v.get("type") != "null" for v in n["anyOf"])
+ if n.get("type") == "object" and "properties" in n:
+ assert n["propertyOrdering"] == list(n["properties"].keys())
+
+ _walk(g, check)
+ types.Schema.model_validate(g) # the SDK accepts it
+
+
+def test_gemini_specifics():
+ class M(BaseModel):
+ vec: tuple[float, float, float]
+ opt: str | None = None
+ kind: str = "x"
+
+ g = to_gemini_schema(M.model_json_schema())
+ assert g["properties"]["vec"] == {
+ "type": "array",
+ "items": {"type": "number"},
+ "minItems": 3,
+ "maxItems": 3,
+ }
+ assert g["properties"]["opt"] == {"type": "string", "nullable": True}
+ assert g["required"] == ["vec"]
+ # const → enum, int enums → strings
+ g2 = to_gemini_schema(
+ {"type": "object", "properties": {"a": {"const": "only"}, "n": {"enum": [1, 2]}}}
+ )
+ assert g2["properties"]["a"] == {"enum": ["only"], "type": "string"}
+ assert g2["properties"]["n"] == {"enum": ["1", "2"], "type": "string"}
+
+
+def test_inline_refs_and_recursion_guard():
+ s = {
+ "$defs": {"A": {"type": "string"}},
+ "properties": {"x": {"$ref": "#/$defs/A", "description": "d"}},
+ }
+ assert inline_refs(s) == {"properties": {"x": {"type": "string", "description": "d"}}}
+ rec = {"$defs": {"N": {"properties": {"child": {"$ref": "#/$defs/N"}}}}, "$ref": "#/$defs/N"}
+ with pytest.raises(ValueError):
+ inline_refs(rec)
+
+
+def test_openai_strict_schema_shape():
+ s = to_openai_strict_schema(StaticPlan.model_json_schema())
+
+ def check(n):
+ if isinstance(n, dict) and "properties" in n:
+ assert n["additionalProperties"] is False
+ assert set(n["required"]) == set(n["properties"].keys())
+
+ _walk(s, check)
+ # optional field became nullable
+ part = s["properties"]["parts"]["items"]["properties"]
+ assert part["material"]["type"] == ["string", "null"]
+ assert {"type": "null"} in part["attach_to"]["anyOf"]
+
+
+def test_anthropic_schema_shape():
+ s = to_anthropic_schema(ScenePlan.model_json_schema())
+ assert "$defs" not in s and s["additionalProperties"] is False
+ assert s["properties"]["bounds"]["properties"]["center"]["items"] == {"type": "number"}
+
+
+ "text",
+ [
+ '{"a": 1}',
+ 'Sure! ```json\n{"a": 1}\n```',
+ 'prefix text {"a": 1} trailing',
+ '{"a": 1,}',
+ '```\n{"a": 1}\n```',
+ ],
+)
+def test_parse_json_lenient(text):
+ assert parse_json_lenient(text) == {"a": 1}
+
+
+def test_parse_json_lenient_array_and_failure():
+ assert parse_json_lenient("[1, 2]") == [1, 2]
+ with pytest.raises(JsonParseError):
+ parse_json_lenient("no json here")
+ with pytest.raises(JsonParseError):
+ parse_json_lenient("")
+ assert json.dumps(parse_json_lenient('{"n": {"x": [1]}}')) == '{"n": {"x": [1]}}'
diff --git a/harness/tests/orchestrator_tracks/__init__.py b/harness/tests/orchestrator_tracks/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/orchestrator_tracks/conftest.py b/harness/tests/orchestrator_tracks/conftest.py
new file mode 100644
index 00000000..aa2c9aec
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/conftest.py
@@ -0,0 +1,47 @@
+"""Fixtures shared by orchestrator/tracks tests."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.config import Settings
+from codeverse.contracts.common import Backends, Budget, Language, Track
+from codeverse.contracts.plan import AcceptanceItem, BBox, PartPlan, StaticPlan
+from codeverse.contracts.spec import Constraints, Spec
+
+
+def settings(tmp_path) -> Settings:
+ return Settings(runs_dir=tmp_path / "runs", cache_dir=tmp_path / "cache")
+
+
+def chair_plan() -> StaticPlan:
+ return StaticPlan(
+ object_name="DiningChair", summary="Mid-century oak dining chair, 0.45 x 0.50 x 0.82 m.",
+ overall_bbox=BBox(center=(0, 0.41, 0), extents=(0.45, 0.82, 0.50)), style_notes="Danish, tapered legs",
+ parts=[
+ PartPlan(name="Seat", role="seat", description="40 mm oak board", bbox=BBox(center=(0, 0.43, 0), extents=(0.42, 0.04, 0.40))),
+ PartPlan(name="FrontLeg", role="front leg", description="tapered", bbox=BBox(center=(0.17, 0.205, 0.16), extents=(0.035, 0.41, 0.035)),
+ attach_to="Seat", symmetry="mirror_x", instances=2),
+ PartPlan(name="BackLeg", role="back leg", description="tapered, continues into backrest", bbox=BBox(center=(0.17, 0.41, -0.16), extents=(0.035, 0.82, 0.035)),
+ attach_to="Seat", symmetry="mirror_x", instances=2),
+ PartPlan(name="Backrest", role="backrest", description="curved slat", bbox=BBox(center=(0, 0.72, -0.17), extents=(0.40, 0.12, 0.03)), attach_to="BackLeg"),
+ PartPlan(name="Armrest", role="armrest", description="flat", bbox=BBox(center=(0.2, 0.65, 0), extents=(0.04, 0.03, 0.35)), attach_to="BackLeg",
+ symmetry="mirror_x", instances=2),
+ ],
+ acceptance=[AcceptanceItem(id="a1", text="Seat top at 0.45 m", how="measure"), AcceptanceItem(id="a2", text="Four legs touch the ground", how="visual")],
+ )
+
+
+def make_spec(track: Track = Track.STATIC_OBJECT, language: Language = Language.THREEJS, *, generator: str = "fake:fake-model",
+ max_rounds: int = 3, max_usd: float = 5.0, prompt: str = "a mid-century wooden dining chair", **kw) -> Spec:
+ return Spec(id="t1", track=track, language=language, prompt=prompt,
+ constraints=Constraints(dimensions_m={"height": 0.82}, must_have=["armrests"]),
+ budget=Budget(max_rounds=max_rounds, max_usd=max_usd, max_minutes=10, max_repair_attempts=2),
+ backends=Backends(planner="fake:planner", generator=generator, judge="fake:judge"), **kw)
+
+
+def spec() -> Spec:
+ return make_spec()
diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.py
new file mode 100644
index 00000000..ed6e8da5
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/fakes.py
@@ -0,0 +1,327 @@
+"""Offline fakes for models / agents / runtimes / judges / spatial services."""
+
+from __future__ import annotations
+
+import json
+import threading
+import time
+from collections.abc import Callable, Sequence
+from pathlib import Path
+from typing import Any
+
+import numpy as np
+import trimesh
+from PIL import Image
+
+from codeverse.contracts.agent import AgentJob, AgentResult
+from codeverse.contracts.artifacts import (
+ BuildResult,
+ GateFinding,
+ GateReport,
+ Measurement,
+ PartMeasure,
+ RenderSet,
+ RenderView,
+ Severity,
+)
+from codeverse.contracts.chat import ChatRequest, ChatResponse
+from codeverse.contracts.common import Language, Usage
+from codeverse.contracts.judgment import ImprovementItem, JudgeIssue, Judgment
+from codeverse.contracts.plan import Plan
+from codeverse.contracts.run import RunRecord
+from codeverse.conventions import to_snake
+from codeverse.tracks.common import Services, ServiceUnavailable
+from codeverse.tracks.generation import changed_files_safe, workspace_lock
+from codeverse.workspace import Workspace
+
+FAIL_MARK = "RAISE_BUILD_ERROR"
+
+
+# ----------------------------------------------------------------------------- runtime
+class FakeRuntime:
+ """Writes a tiny GLB (one box per part) on build; fails when a src file contains FAIL_MARK."""
+
+ def __init__(self, language: Language = Language.THREEJS, *, lint_error_mark: str = "LINT_ERROR"):
+ self.language = language
+ self.entry_globs = ("src/**/*.js",) if language in (Language.THREEJS, Language.SCENE_THREEJS) else ("src/model.py",)
+ self.lint_error_mark = lint_error_mark
+ self.builds = 0
+ self.lock = threading.Lock()
+
+ def skeleton(self, ws: Workspace, plan: Plan) -> list[Path]:
+ out = []
+ if self.language is Language.THREEJS:
+ for p in getattr(plan, "parts", []):
+ f = ws.src / "parts" / f"{to_snake(p.name)}.js"
+ f.parent.mkdir(parents=True, exist_ok=True)
+ f.write_text(f"// skeleton for {p.name}\nexport function build{p.name}(THREE) {{ return new THREE.Group(); }}\n")
+ out.append(f)
+ f = ws.src / "object.js"
+ f.write_text("// skeleton object.js\nexport function build(THREE) { return new THREE.Group(); }\n")
+ out.append(f)
+ elif self.language is Language.SCENE_THREEJS:
+ for rel in ("src/scene.js", "src/env.js"):
+ f = ws.root / rel
+ f.parent.mkdir(parents=True, exist_ok=True)
+ f.write_text(f"// skeleton {rel}\n")
+ out.append(f)
+ (ws.src / "zones").mkdir(exist_ok=True)
+ (ws.src / "assets").mkdir(exist_ok=True)
+ else:
+ f = ws.src / "model.py"
+ f.write_text("# skeleton model.py\nimport bpy\n")
+ out.append(f)
+ if self.language is Language.URDF_BLENDER:
+ u = ws.src / "robot.urdf"
+ u.write_text("<robot name='skeleton'/>\n")
+ out.append(u)
+ return out
+
+ def _src_text(self, ws: Workspace) -> str:
+ return "\n".join(p.read_text() for p in sorted(ws.src.rglob("*")) if p.is_file())
+
+ def lint(self, ws: Workspace) -> GateReport:
+ text = self._src_text(ws)
+ findings = []
+ if self.lint_error_mark in text:
+ findings.append(GateFinding(gate=f"lint:{self.language.value}", severity=Severity.ERROR, target="src/model.py",
+ message="forbidden construct", fix_hint="remove LINT_ERROR"))
+ return GateReport(gate=f"lint:{self.language.value}", passed=not findings, findings=findings)
+
+ def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
+ with self.lock:
+ self.builds += 1
+ text = self._src_text(ws)
+ if FAIL_MARK in text:
+ return BuildResult(ok=False, language=self.language.value, error_type="RuntimeError", error_message="boom: RAISE_BUILD_ERROR",
+ error_file="src/model.py", error_line=3, stderr_tail="Traceback...\nRuntimeError: boom")
+ ws.artifacts.mkdir(parents=True, exist_ok=True)
+ glb = ws.artifacts / "object.glb"
+ plan = json.loads(ws.plan_path.read_text()) if ws.plan_path.is_file() else {}
+ scene = trimesh.Scene()
+ parts = plan.get("parts") or [{"name": "Body", "bbox": {"center": [0, 0, 0.25], "extents": [0.5, 0.5, 0.5]}}]
+ for p in parts:
+ c, e = p["bbox"]["center"], p["bbox"]["extents"]
+ box = trimesh.creation.box(extents=e)
+ box.apply_translation(c)
+ scene.add_geometry(box, node_name=p["name"], geom_name=p["name"])
+ glb.write_bytes(scene.export(file_type="glb"))
+ extras = {}
+ if self.language is Language.URDF_BLENDER:
+ u = ws.artifacts / "robot.urdf"
+ u.write_text((ws.src / "robot.urdf").read_text() if (ws.src / "robot.urdf").is_file() else "<robot/>")
+ extras["urdf"] = str(u)
+ return BuildResult(ok=True, language=self.language.value, glb_path=str(glb), extra_paths=extras,
+ census={"objects": [p["name"] for p in parts]})
+
+ def contract_doc(self) -> str:
+ return f"FAKE CONTRACT for {self.language.value}"
+
+ def cookbook_path(self) -> Path:
+ return Path("/dev/null")
+
+
+# ----------------------------------------------------------------------------- agent / model
+class FakeAgent:
+ """``writer(job, ws) -> dict[path, content]``; None → no files (silent bail)."""
+
+ kind = "fake"
+ model = "fake-model"
+
+ def __init__(self, writer: Callable[[AgentJob, Workspace], dict[str, str] | None], cost: float = 0.01):
+ self.writer = writer
+ self.cost = cost
+ self.jobs: list[AgentJob] = []
+
+ @property
+ def id(self) -> str:
+ return "fake:fake-model"
+
+ def available(self) -> tuple[bool, str]:
+ return True, "ok"
+
+ def run(self, job: AgentJob) -> AgentResult:
+ self.jobs.append(job)
+ ws = Workspace(job.workspace)
+ with workspace_lock(ws):
+ before = ws.head()
+ files = self.writer(job, ws)
+ for rel, content in (files or {}).items():
+ p = ws.root / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(content)
+ traj = ws.trajectory_dir(job.label or "job", 0)
+ (traj / "transcript.jsonl").write_text(json.dumps({"prompt": job.prompt[:200]}) + "\n")
+ return AgentResult(ok=bool(files), exit_reason="completed" if files else "no_changes", files_changed=changed_files_safe(ws, before),
+ transcript_path=str(traj / "transcript.jsonl"), usage=Usage(backend="fake", cost_usd=self.cost, input_tokens=100))
+
+
+class FakeChatModel:
+ """``responder(request) -> str | dict``; dict is returned as ``parsed`` (structured output)."""
+
+ provider = "fake"
+ model = "fake-model"
+
+ def __init__(self, responder: Callable[[ChatRequest], Any], cost: float = 0.002):
+ self.responder = responder
+ self.cost = cost
+ self.requests: list[ChatRequest] = []
+
+ @property
+ def id(self) -> str:
+ return "fake:fake-model"
+
+ def supports_vision(self) -> bool:
+ return True
+
+ def generate(self, request: ChatRequest) -> ChatResponse:
+ self.requests.append(request)
+ out = self.responder(request)
+ usage = Usage(backend="fake", model="fake-model", cost_usd=self.cost, input_tokens=500, output_tokens=200)
+ if isinstance(out, (dict, list)):
+ return ChatResponse(text=json.dumps(out), parsed=out, usage=usage)
+ return ChatResponse(text=str(out), usage=usage)
+
+
+# ----------------------------------------------------------------------------- judge
+class FakeJudge:
+ name = "fake"
+
+ def __init__(self, scores: Sequence[float] = (0.55, 0.7, 0.85), *, targets: Sequence[str] = ("Seat", "FrontLeg", "Backrest", "Armrest"),
+ acceptance_fail: Sequence[str] = (), cost: float = 0.003):
+ self.scores = list(scores)
+ self.targets = list(targets)
+ self.acceptance_fail = list(acceptance_fail)
+ self.cost = cost
+ self.calls: list[Any] = []
+
+ def judge(self, inp: Any) -> Judgment:
+ i = min(len(self.calls), len(self.scores) - 1)
+ self.calls.append(inp)
+ s = self.scores[i]
+ plan = [ImprovementItem(target=t, kind="geometry", instruction=f"make {t} match plan bbox", priority=k + 1, expected_gain=0.05)
+ for k, t in enumerate(self.targets)]
+ acc = {a.id: (a.id not in self.acceptance_fail) for a in inp.acceptance}
+ return Judgment(rubric="fake_v1", judge_backend="fake", scores={"geometry": s, "material": s}, overall=s, passed=s >= 0.8,
+ summary=f"round {inp.round_index} score {s}", issues=[JudgeIssue(target=self.targets[0], kind="geometry", severity="major",
+ detail="too thin", evidence="front")],
+ improvement_plan=plan, acceptance_results=acc, usage=Usage(backend="fake", cost_usd=self.cost))
+
+
+# ----------------------------------------------------------------------------- services
+def _png(path: Path, size: int = 32) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ Image.new("RGB", (size, size), (120, 120, 200)).save(path)
+
+
+class FakeServices(Services):
+ def __init__(self, *, runtime_factory: Callable[[Language], Any] | None = None, judge: Any | None = None,
+ contract_errors: int = 0, assemble: bool = False, sweep_errors: int = 0):
+ self.runtime_factory = runtime_factory or (lambda lang: FakeRuntime(lang))
+ self._judge = judge
+ self.contract_errors = contract_errors
+ self.assemble = assemble
+ self.sweep_errors = sweep_errors
+ self.materialized: list[str] = []
+ self.records: list[RunRecord] = []
+
+ def chat_model(self, model_id: str) -> Any:
+ raise ServiceUnavailable("no chat model in tests")
+
+ def coding_agent(self, agent_id: str) -> Any:
+ raise ServiceUnavailable("no coding agent in tests")
+
+ def judge(self, rubric: str, model_id: str, n_samples: int = 1) -> Any:
+ return self._judge if self._judge is not None else FakeJudge()
+
+ def runtime(self, language: Language) -> Any:
+ return self.runtime_factory(language)
+
+ def rubric_threshold(self, rubric: str) -> float | None:
+ return 0.8
+
+ def measure(self, glb: Path) -> Measurement:
+ scene = trimesh.load(str(glb), force="scene")
+ bounds = scene.bounds
+ parts = []
+ for name, geom in scene.geometry.items():
+ b = geom.bounds
+ parts.append(PartMeasure(name=name, bbox_min=tuple(map(float, b[0])), bbox_max=tuple(map(float, b[1])),
+ tri_count=int(len(geom.faces))))
+ ext = (bounds[1] - bounds[0]).tolist()
+ cen = ((bounds[1] + bounds[0]) / 2).tolist()
+ return Measurement(bbox_min=tuple(map(float, bounds[0])), bbox_max=tuple(map(float, bounds[1])), extents=tuple(ext),
+ center=tuple(cen), tri_count=sum(p.tri_count for p in parts), n_meshes=len(parts), n_islands=len(parts),
+ parts=parts, ground_gap_m=float(bounds[0][1]), footprint_offset_m=float(np.hypot(cen[0], cen[2])))
+
+ def connectivity(self, glb: Path) -> GateReport:
+ return GateReport(gate="connectivity", passed=True)
+
+ def contract(self, measurement: Measurement, plan: Plan, tol_m: float, language: str = "") -> GateReport:
+ findings = [GateFinding(gate="contract", severity=Severity.ERROR, target=p.name, message=f"{p.name} bbox off by 0.03 m",
+ fix_hint=f"move {p.name} to its plan centre") for p in list(getattr(plan, "parts", []))[: self.contract_errors]]
+ return GateReport(gate="contract", passed=not findings, findings=findings)
+
+ def render_object(self, glb: Path, out_dir: Path, *, views, width: int, height: int) -> RenderSet:
+ vs = []
+ for v in views:
+ p = out_dir / f"view_{v.name}.png"
+ _png(p)
+ vs.append(RenderView(name=v.name, path=str(p), width=32, height=32))
+ sheet = out_dir / "sheet.png"
+ _png(sheet)
+ return RenderSet(views=vs, contact_sheet=str(sheet), renderer="fake")
+
+ def render_scene(self, ws: Workspace, out_dir: Path, *, cameras, times, width: int, height: int) -> RenderSet:
+ vs = []
+ for c in cameras or []:
+ for t in times:
+ p = out_dir / f"cam_{to_snake(c.name)}_t{t}.png"
+ _png(p)
+ vs.append(RenderView(name=f"{c.name}@{t}", path=str(p), time_s=t))
+ sheet = out_dir / "sheet.png"
+ _png(sheet)
+ errs = ["TypeError: boom in src/zones/pond.js"] if (ws.src / "zones" / "pond.js").is_file() and "CONSOLE_ERROR" in (ws.src / "zones" / "pond.js").read_text() else []
+ return RenderSet(views=vs, contact_sheet=str(sheet), renderer="fake", console_errors=errs, fps=60.0)
+
+ def contact_sheet(self, images, out: Path) -> Path:
+ _png(out)
+ return out
+
+ def joint_sweep(self, ws: Workspace, plan: Plan, out_dir: Path) -> tuple[GateReport, list[RenderView]]:
+ out_dir.mkdir(parents=True, exist_ok=True)
+ views = []
+ for j in getattr(plan, "joints", []):
+ for pose in ("lower", "upper"):
+ p = out_dir / f"pose_{to_snake(j.name)}_{pose}.png"
+ _png(p)
+ views.append(RenderView(name=f"pose_{j.name}_{pose}", path=str(p)))
+ findings = [GateFinding(gate="joint_sweep", severity=Severity.ERROR, target=j.name, message=f"{j.child} penetrates {j.parent} by 12.0 mm at upper",
+ fix_hint=f"shrink {j.child} by 17 mm along the axis") for j in list(getattr(plan, "joints", []))[: self.sweep_errors]]
+ return GateReport(gate="joint_sweep", passed=not findings, findings=findings), views
+
+ def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, cookbook_rel: str, spatial_tools: bool, mcp_command: list[str]) -> None:
+ (ws.root / "AGENTS.md").write_text(contract_md)
+ self.materialized.append(agent_kind)
+
+ def tool_cards(self, track: str, language: str) -> str:
+ return "- `build` (slow): lint+build+measure\n- `measure` (fast): bbox per part"
+
+ def assemble_scene(self, ws: Workspace, plan: Plan) -> Any:
+ if not self.assemble:
+ raise ServiceUnavailable("no assembler in tests")
+ (ws.src / "scene.js").write_text("// assembled by fake\nexport function createScene(){}\n")
+ return {"zones": [z.name for z in plan.zones]}
+
+ def finalize_record(self, ws: Workspace, record: RunRecord) -> None:
+ self.records.append(record)
+ ws.write_json(ws.record_path, record)
+
+
+def wait_for(pred: Callable[[], bool], timeout: float = 5.0) -> bool:
+ t0 = time.time()
+ while time.time() - t0 < timeout:
+ if pred():
+ return True
+ time.sleep(0.01)
+ return False
diff --git a/harness/tests/orchestrator_tracks/test_generation_planner_repair.py b/harness/tests/orchestrator_tracks/test_generation_planner_repair.py
new file mode 100644
index 00000000..44610ecf
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_generation_planner_repair.py
@@ -0,0 +1,225 @@
+"""generation (envelope parsing, single-shot, agent path), planner, repair loop."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.plan import ScenePlan, StaticPlan
+from codeverse.events import EventLog
+from codeverse.orchestrator.budget import BudgetGuard
+from codeverse.orchestrator.rounds import RoundPolicy
+from codeverse.orchestrator.state import RunState
+from codeverse.tracks.common import RunContext
+from codeverse.tracks.generation import (
+ SINGLE_SHOT_FORMAT,
+ GenerationError,
+ GenerationTask,
+ MultiFileParseError,
+ generate,
+ parse_multifile,
+ safe_relpath,
+ write_files,
+)
+from codeverse.tracks.planner import (
+ PlanningError,
+ build_system_prompt,
+ ensure_acceptance,
+ plan,
+ plan_example,
+)
+from codeverse.tracks.repair import (
+ build_with_repair,
+ format_error_report,
+ relevant_cookbook_section,
+)
+from tests.orchestrator_tracks.conftest import make_spec
+from tests.orchestrator_tracks.fakes import (
+ FAIL_MARK,
+ FakeAgent,
+ FakeChatModel,
+ FakeRuntime,
+ FakeServices,
+)
+
+
+# ----------------------------------------------------------------------------- envelope
+def test_parse_multifile_blocks_and_fences():
+ text = """Here you go.
+=== FILE: src/object.js ===
+```js
+export function build(THREE) { return new THREE.Group(); }
+```
+=== END FILE ===
+=== FILE: ./src/parts/seat.js ===
+export function buildSeat(THREE) {}
+=== END FILE ===
+"""
+ files = parse_multifile(text)
+ assert set(files) == {"src/object.js", "src/parts/seat.js"}
+ assert files["src/object.js"].startswith("export function build") and "```" not in files["src/object.js"]
+
+
+def test_parse_multifile_single_fence_fallback_and_errors():
+ assert parse_multifile("```python\nimport bpy\nprint(1)\n```", expected_files=["src/model.py"]) == {"src/model.py": "import bpy\nprint(1)"}
+ hinted = "**src/env.js**\n```js\nexport const A=1;\n```\nand `src/scene.js`:\n```js\nexport const B=2;\n```"
+ files = parse_multifile(hinted)
+ assert files == {"src/env.js": "export const A=1;", "src/scene.js": "export const B=2;"}
+ with pytest.raises(MultiFileParseError):
+ parse_multifile("Sorry, I cannot do that.", expected_files=["src/a.js", "src/b.js"])
+ with pytest.raises(MultiFileParseError):
+ parse_multifile("", expected_files=["src/a.js"])
+
+
+def test_safe_relpath_and_write_files(tmp_ws):
+ assert safe_relpath("./src/x.js") == "src/x.js"
+ for bad in ("../etc/passwd", "/abs/src/x.js", "docs/readme.md", "src/../../x"):
+ with pytest.raises(GenerationError):
+ safe_relpath(bad)
+ changes = write_files(tmp_ws, {"src/a.js": "x", "public/b.txt": "y\n"})
+ assert [c.path for c in changes] == ["src/a.js", "public/b.txt"] and (tmp_ws.src / "a.js").read_text() == "x\n"
+ assert "=== FILE:" in SINGLE_SHOT_FORMAT
+
+
+# ----------------------------------------------------------------------------- strategies
+def test_generate_single_shot_writes_files_and_charges(tmp_ws):
+ model = FakeChatModel(lambda req: "=== FILE: src/model.py ===\nimport bpy\n=== END FILE ===")
+ budget = BudgetGuard(make_spec().budget)
+ events = EventLog(tmp_ws.events_path)
+ task = GenerationTask(label="baseline", prompt="build it", system="sys", files_hint=["src/model.py"])
+ res = generate(tmp_ws, agent_id="single-shot:gemini:x", task=task, model=model, budget=budget, events=events)
+ assert res.ok and [c.path for c in res.files_changed] == ["src/model.py"] and (tmp_ws.src / "model.py").read_text() == "import bpy\n"
+ assert budget.spent.cost_usd == pytest.approx(0.002)
+ assert "=== FILE:" in model.requests[0].system and model.requests[0].label == "baseline"
+ assert (tmp_ws.trajectories / "baseline_r00" / "response.md").is_file()
+ # parse failure → ok=False, no raise
+ bad = FakeChatModel(lambda req: "nope")
+ res2 = generate(tmp_ws, agent_id="single-shot:gemini:x", task=GenerationTask(label="b", prompt="p", files_hint=["src/a.js", "src/b.js"]), model=bad)
+ assert not res2.ok and "parse failed" in res2.notes
+
+
+def test_generate_agent_path_silent_bail_retry(tmp_ws):
+ calls = []
+
+ def writer(job, ws):
+ calls.append(job.prompt[:40])
+ return None if len(calls) == 1 else {"src/model.py": "import bpy\n"}
+
+ agent = FakeAgent(writer)
+ res = generate(tmp_ws, agent_id="fake:fake-model", task=GenerationTask(label="baseline", prompt="build it"), agent=agent,
+ events=EventLog(tmp_ws.events_path))
+ assert res.ok and len(calls) == 2 and calls[1].startswith("Your previous attempt ended WITHOUT")
+ assert res.usage.cost_usd == pytest.approx(0.02)
+ assert agent.jobs[0].write_roots == ["src", "public"] and agent.jobs[0].label == "baseline"
+
+
+# ----------------------------------------------------------------------------- planner
+def _valid_plan_dict() -> dict:
+ return plan_example(Track.STATIC_OBJECT)
+
+
+def test_planner_validates_retries_and_writes(tmp_ws):
+ spec = make_spec()
+ answers = [{"object_name": "X"}, _valid_plan_dict()]
+ model = FakeChatModel(lambda req: answers.pop(0))
+ events = EventLog(tmp_ws.events_path)
+ budget = BudgetGuard(spec.budget)
+ p = plan(spec, "fake:planner", StaticPlan, tmp_ws, model=model, events=events, budget=budget, runtime=FakeRuntime(Language.THREEJS))
+ assert isinstance(p, StaticPlan) and p.object_name == "DiningChair" and tmp_ws.plan_path.is_file()
+ assert len(model.requests) == 2 and "failed validation" in model.requests[1].messages[-1].text
+ assert model.requests[0].response_schema is not None and "PascalCase" in model.requests[0].system
+ # deterministic acceptance items from constraints were appended
+ texts = " ".join(a.text for a in p.acceptance)
+ assert "height = 0.820" in texts and "Includes: armrests" in texts
+ assert budget.spent.cost_usd == pytest.approx(0.004)
+ kinds = [e["event"] for e in events.read()]
+ assert "plan.invalid" in kinds and "plan.done" in kinds
+
+
+def test_planner_gives_up_after_reask(tmp_ws):
+ model = FakeChatModel(lambda req: {"bad": 1})
+ with pytest.raises(PlanningError):
+ plan(make_spec(), "fake:planner", StaticPlan, tmp_ws, model=model)
+
+
+def test_planner_scene_example_validates_and_prompts_render():
+ assert isinstance(ScenePlan.model_validate(plan_example(Track.SCENE)), ScenePlan)
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS)
+ s = build_system_prompt(spec, ScenePlan)
+ assert "zones" in s and "Y is UP" in s
+ from codeverse.contracts.plan import ArticulatedPlan
+
+ assert isinstance(ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT)), ArticulatedPlan)
+ assert "pivot" in build_system_prompt(make_spec(Track.ARTICULATED_OBJECT, Language.URDF_BLENDER), ArticulatedPlan)
+
+
+def test_ensure_acceptance_is_idempotent():
+ p = StaticPlan.model_validate(_valid_plan_dict())
+ spec = make_spec()
+ n1 = len(ensure_acceptance(p, spec).acceptance)
+ n2 = len(ensure_acceptance(p, spec).acceptance)
+ assert n1 == n2 and any(a.how == "measure" for a in p.acceptance)
+
+
+# ----------------------------------------------------------------------------- repair
+def _ctx(tmp_ws, settings, agent_id: str, agent=None, model=None, cookbook: str = "") -> RunContext:
+ spec = make_spec(generator=agent_id)
+ rt = FakeRuntime(Language.THREEJS)
+ return RunContext(spec=spec, ws=tmp_ws, events=EventLog(tmp_ws.events_path), settings=settings, budget=BudgetGuard(spec.budget),
+ runtime=rt, services=FakeServices(), state=RunState(), policy=RoundPolicy(), track=Track.STATIC_OBJECT,
+ rubric="r", agent_id=agent_id, agent=agent, model=model, cookbook_text=cookbook,
+ contract_text="CONTRACT")
+
+
+def test_build_with_repair_agent_path_escalates_on_same_error(tmp_ws, settings):
+ (tmp_ws.src / "model.py").write_text(f"import bpy\n# {FAIL_MARK}\nprint(1)\n")
+ tmp_ws.write_json(tmp_ws.plan_path, {"parts": []})
+ prompts = []
+
+ def writer(job, ws):
+ prompts.append(job.prompt)
+ if len(prompts) == 1:
+ return {"src/model.py": f"import bpy\n# still {FAIL_MARK}\n"} # same error again
+ return {"src/model.py": "import bpy\nprint('fixed')\n"}
+
+ ctx = _ctx(tmp_ws, settings, "fake:x", agent=FakeAgent(writer), cookbook="## Intro\nhello\n## RuntimeError boom\nuse boom fix snippet\n")
+ out = build_with_repair(ctx, round_index=0, label="r00")
+ assert out.ok and out.repaired and len(out.attempts) == 2
+ assert "BUILD FAILED" in prompts[0] and "src/model.py:3" in prompts[0] and "boom fix snippet" in prompts[0]
+ assert "SAME ERROR AS THE PREVIOUS ATTEMPT" in prompts[1] and "SAME ERROR" not in prompts[0]
+ kinds = [e["event"] for e in ctx.events.read()]
+ assert kinds.count("repair.attempt") == 2 and kinds.count("build.done") == 3
+
+
+def test_build_with_repair_single_shot_sends_file_contents_and_stops_at_max(tmp_ws, settings):
+ (tmp_ws.src / "model.py").write_text(f"import bpy\n# {FAIL_MARK}\n")
+ tmp_ws.write_json(tmp_ws.plan_path, {"parts": []})
+ seen = []
+
+ def responder(req):
+ seen.append(req)
+ return f"=== FILE: src/model.py ===\nimport bpy\n# {FAIL_MARK} again\n=== END FILE ==="
+
+ ctx = _ctx(tmp_ws, settings, "single-shot:gemini:x", model=FakeChatModel(responder))
+ out = build_with_repair(ctx, round_index=1, label="r01", files_hint=["src/model.py"])
+ assert not out.ok and len(out.attempts) == 2 # max_repair_attempts=2 in make_spec
+ assert "--- src/model.py ---" in seen[0].messages[0].text and "import bpy" in seen[0].messages[0].text
+ assert seen[1].temperature > seen[0].temperature # escalation on identical signature
+ assert ctx.budget.spent.cost_usd == pytest.approx(0.004)
+
+
+def test_format_error_report_and_cookbook_section():
+ from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+
+ b = BuildResult(ok=False, language="threejs", error_type="TypeError", error_message="Cannot read properties of null (reading 'fillStyle')",
+ error_file="src/parts/base.js", error_line=12, stderr_tail="\n".join(f"line{i}" for i in range(60)))
+ lint = GateReport(gate="lint:threejs", passed=False, findings=[GateFinding(gate="lint:threejs", severity=Severity.ERROR, target="src/parts/base.js",
+ message="document.createElement is forbidden", fix_hint="use vertex colours")])
+ cb = "## Materials\nuse MeshStandardMaterial\n## Canvas textures are not available\nfillStyle getContext canvas null properties → procedural colours\n"
+ rep = format_error_report(b, lint, cb)
+ assert "src/parts/base.js:12" in rep and "line59" in rep and "line5\n" not in rep.split("traceback")[1][:20]
+ assert "FIX: use vertex colours" in rep and "Canvas textures" in rep
+ assert relevant_cookbook_section(cb, "totally unrelated words") == ""
+ assert json.dumps(rep) # serialisable
diff --git a/harness/tests/orchestrator_tracks/test_orchestrator.py b/harness/tests/orchestrator_tracks/test_orchestrator.py
new file mode 100644
index 00000000..44a4ea74
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_orchestrator.py
@@ -0,0 +1,178 @@
+"""budget / fanout / state / runner / rounds unit tests."""
+
+from __future__ import annotations
+
+import time
+
+import pytest
+
+from codeverse.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
+from codeverse.contracts.common import Budget, Usage
+from codeverse.contracts.judgment import ImprovementItem, Judgment
+from codeverse.contracts.plan import AcceptanceItem
+from codeverse.contracts.run import RoundRecord
+from codeverse.events import EventLog
+from codeverse.orchestrator.budget import BudgetExceeded, BudgetGuard
+from codeverse.orchestrator.fanout import fan_out, split_results
+from codeverse.orchestrator.rounds import (
+ BestSelector,
+ RefineTask,
+ RoundPolicy,
+ StopPolicy,
+ build_refine_instructions,
+ plan_parallel_groups,
+)
+from codeverse.orchestrator.runner import StageRunner, hash_inputs
+from codeverse.orchestrator.state import RunState
+
+
+# ----------------------------------------------------------------------------- budget
+def test_budget_guard_charges_and_raises():
+ g = BudgetGuard(Budget(max_usd=0.05, max_minutes=60))
+ g.charge(Usage(cost_usd=0.02))
+ g.charge(Usage(cost_usd=0.02))
+ assert g.ok() and g.remaining()["usd"] == pytest.approx(0.01)
+ with pytest.raises(BudgetExceeded) as ei:
+ g.charge(Usage(cost_usd=0.02))
+ assert "max_usd" in ei.value.reason and g.spent.cost_usd == pytest.approx(0.06)
+
+
+def test_budget_guard_time_ceiling():
+ g = BudgetGuard(Budget(max_usd=10, max_minutes=0.0001), start_time=time.time() - 10)
+ with pytest.raises(BudgetExceeded):
+ g.check()
+ assert g.remaining()["minutes"] == 0.0
+
+
+# ----------------------------------------------------------------------------- fanout
+def test_fan_out_preserves_order_and_captures_exceptions():
+ def fn(x: int) -> int:
+ if x == 2:
+ raise ValueError("two")
+ time.sleep(0.01 * (4 - x))
+ return x * 10
+
+ res = fan_out([0, 1, 2, 3], fn, max_workers=4, label="t")
+ assert res[0] == 0 and res[1] == 10 and res[3] == 30 and isinstance(res[2], ValueError)
+ ok, bad = split_results(res)
+ assert ok == [0, 10, 30] and len(bad) == 1
+ assert fan_out([], fn, 2) == []
+
+
+# ----------------------------------------------------------------------------- state + runner
+def test_run_state_roundtrip(tmp_ws):
+ st = RunState()
+ st.mark_round_done(0, "abc", tmp_ws)
+ st.update_best(0, "abc", 0.5)
+ st.extra["spent_usage"] = Usage(cost_usd=0.1).model_dump()
+ st.save(tmp_ws)
+ again = RunState.load(tmp_ws)
+ assert again is not None and again.best_round == 0 and again.current_round == 1 and again.round_commits[0] == "abc"
+ assert RunState.load_or_new(tmp_ws, resume=False).best_round is None
+
+
+def test_stage_runner_caches_by_input_hash(tmp_ws):
+ events = EventLog(tmp_ws.events_path)
+ runner = StageRunner(tmp_ws, events)
+ calls = []
+
+ def fn():
+ calls.append(1)
+ return {"x": 1}
+
+ assert runner.stage("s1", fn, inputs={"a": 1}) == {"x": 1}
+ assert runner.stage("s1", fn, inputs={"a": 1}) == {"x": 1}
+ assert len(calls) == 1
+ assert runner.stage("s1", fn, inputs={"a": 2}) == {"x": 1}
+ assert len(calls) == 2
+ runner.stage("s1", fn, inputs={"a": 2}, force=True)
+ assert len(calls) == 3
+ kinds = [e["event"] for e in events.read()]
+ assert kinds.count("stage.cached") == 1 and kinds.count("stage.done") == 3
+ # resume from disk with a fresh runner + state
+ st = RunState.load(tmp_ws)
+ r2 = StageRunner(tmp_ws, events, st)
+ assert r2.stage("s1", fn, inputs={"a": 2}) == {"x": 1} and len(calls) == 3
+ assert runner.result_path("a:b/c").name == "a_b_c.json"
+
+
+def test_stage_runner_revives_models_and_raises(tmp_ws):
+ runner = StageRunner(tmp_ws, EventLog(tmp_ws.events_path))
+ r = runner.stage("rounds", lambda: [RoundRecord(index=0, kind="baseline")], inputs="x", list_of=RoundRecord)
+ r2 = runner.stage("rounds", lambda: None, inputs="x", list_of=RoundRecord)
+ assert isinstance(r2[0], RoundRecord) and r2[0].kind == r[0].kind
+
+ def boom():
+ raise RuntimeError("nope")
+
+ with pytest.raises(RuntimeError):
+ runner.stage("bad", boom, inputs="y")
+ assert "bad" not in runner.state.stages
+ assert hash_inputs({"a": [1, 2]}) == hash_inputs({"a": (1, 2)})
+
+
+# ----------------------------------------------------------------------------- stop policy
+def _round(i: int, score: float | None, errors: int = 0, build_ok: bool = True) -> RoundRecord:
+ j = Judgment(rubric="r", scores={"a": score}, overall=score, passed=score >= 0.8) if score is not None else None
+ gates = [GateReport(gate="g", passed=errors == 0, findings=[GateFinding(gate="g", severity=Severity.ERROR, message="e")] * errors)]
+ return RoundRecord(index=i, kind="x", judgment=j, gates=gates, build=BuildResult(ok=build_ok, language="l"), commit=f"c{i}")
+
+
+def test_stop_policy_decisions():
+ sp = StopPolicy(RoundPolicy(max_rounds=3, plateau_window=2, min_delta=0.02, target=0.8))
+ assert sp.decide([]) == "continue"
+ assert sp.decide([_round(0, 0.5)]) == "continue"
+ assert sp.decide([_round(0, 0.5)], budget_ok=False) == "budget"
+ assert sp.decide([_round(0, 0.5), _round(1, 0.85)]) == "pass"
+ assert sp.decide([_round(0, 0.5), _round(1, 0.51), _round(2, 0.515)]) == "plateau"
+ assert sp.decide([_round(0, 0.5), _round(1, 0.6), _round(2, 0.7)]) == "continue"
+ assert sp.decide([_round(0, 0.5), _round(1, 0.6), _round(2, 0.7), _round(3, 0.75)]) == "max_rounds"
+ # unscored rounds (build failed) do not count as plateau evidence
+ assert sp.decide([_round(0, 0.5), _round(1, None, build_ok=False), _round(2, None, build_ok=False)]) == "continue"
+
+
+def test_best_selector_prefers_score_then_fewer_errors():
+ rounds = [_round(0, 0.5), _round(1, 0.7, errors=2), _round(2, 0.7, errors=0), _round(3, 0.6)]
+ assert BestSelector().pick(rounds) == 2
+ assert BestSelector().pick([]) is None
+ assert BestSelector().pick([_round(0, None, build_ok=False), _round(1, None, build_ok=True)]) == 1
+
+
+# ----------------------------------------------------------------------------- refine instructions
+def test_build_refine_instructions_merges_and_groups(chair_plan):
+ judgment = Judgment(rubric="r", scores={}, overall=0.6, passed=False, improvement_plan=[
+ ImprovementItem(target="seat", kind="geometry", instruction="thicker seat", priority=2),
+ ImprovementItem(target="Backrest", kind="material", instruction="warmer oak", priority=1),
+ ImprovementItem(target="Seat", kind="geometry", instruction="duplicate kind", priority=3),
+ ImprovementItem(target="overall", kind="assembly", instruction="tighten joints", priority=4),
+ ])
+ gates = [GateReport(gate="contract", passed=False, findings=[
+ GateFinding(gate="contract", severity=Severity.ERROR, target="FrontLeg", message="FrontLeg 30 mm too short", fix_hint="scale y by 1.07"),
+ GateFinding(gate="contract", severity=Severity.WARN, target="Seat", message="ignored warn"),
+ ])]
+ failed = [AcceptanceItem(id="a2", text="Four legs touch the ground", how="visual", priority="must"),
+ AcceptanceItem(id="a3", text="should item", how="visual", priority="should")]
+ fft = lambda t: [f"src/parts/{t.lower()}.js"] if t not in ("overall",) else ["src/object.js"] # noqa: E731
+ tasks = build_refine_instructions(judgment, gates, failed, chair_plan, file_for_target=fft, max_tasks=6)
+ assert [t.source for t in tasks][:2] == ["gate", "acceptance"]
+ assert tasks[0].target == "FrontLeg" and "FIX: scale y" in tasks[0].instruction and tasks[0].files == ["src/parts/frontleg.js"]
+ assert tasks[1].target == "overall" # acceptance item not naming a part
+ kinds = [(t.target, t.kind) for t in tasks]
+ assert ("Seat", "geometry") in kinds and kinds.count(("Seat", "geometry")) == 1 # dedupe + canonical name
+ assert len(tasks) <= 6
+ groups = plan_parallel_groups(tasks)
+ assert len(groups) >= 3 and all(g.files for g in groups)
+ files = [f for g in groups for f in g.files]
+ assert len(files) == len(set(files)) # file-disjoint
+ # unknown files collapse to one group
+ one = plan_parallel_groups(tasks + [RefineTask(target="x", kind="geometry", instruction="i", priority=3)])
+ assert len(one) == 1
+ assert build_refine_instructions(None, [], [], chair_plan) == []
+
+
+def test_refine_cap_protects_gate_tasks(chair_plan):
+ gates = [GateReport(gate="g", passed=False, findings=[GateFinding(gate="g", severity=Severity.ERROR, target=f"P{i}", message=f"e{i}") for i in range(8)])]
+ judgment = Judgment(rubric="r", scores={}, overall=0.5, passed=False, improvement_plan=[
+ ImprovementItem(target=f"J{i}", kind="geometry", instruction="x", priority=1) for i in range(5)])
+ tasks = build_refine_instructions(judgment, gates, [], chair_plan, max_tasks=6)
+ assert len(tasks) == 8 and all(t.source == "gate" for t in tasks)
diff --git a/harness/tests/orchestrator_tracks/test_prompts_assets.py b/harness/tests/orchestrator_tracks/test_prompts_assets.py
new file mode 100644
index 00000000..16ca9e1f
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_prompts_assets.py
@@ -0,0 +1,88 @@
+"""Every tracks/*.j2 renders with the context the tracks build; scene asset stage incl. blender_glb."""
+
+from __future__ import annotations
+
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.plan import ArticulatedPlan, ScenePlan
+from codeverse.events import EventLog
+from codeverse.orchestrator.budget import BudgetGuard
+from codeverse.orchestrator.rounds import RoundPolicy
+from codeverse.orchestrator.state import RunState
+from codeverse.prompts import list_prompts, render
+from codeverse.tracks.common import RunContext, base_prompt_context
+from codeverse.tracks.generation import SINGLE_SHOT_FORMAT
+from codeverse.tracks.planner import plan_example
+from codeverse.tracks.scene_assets import asset_api_summary, asset_plan, run_asset_stage
+from tests.orchestrator_tracks.conftest import make_spec
+from tests.orchestrator_tracks.fakes import FakeAgent, FakeJudge, FakeRuntime, FakeServices
+
+TEMPLATES = {"plan_static", "plan_articulated", "plan_scene", "generate_static", "generate_articulated", "refine_object", "repair",
+ "scene_asset", "scene_env", "scene_zone", "scene_compose", "scene_refine"}
+
+
+def _ctx(tmp_ws, settings, spec, plan, *, agent_id="single-shot:gemini:x", services=None, agent=None) -> RunContext:
+ lang = spec.language
+ return RunContext(spec=spec, ws=tmp_ws, events=EventLog(tmp_ws.events_path), settings=settings, budget=BudgetGuard(spec.budget),
+ runtime=FakeRuntime(lang), services=services or FakeServices(), state=RunState(), policy=RoundPolicy(),
+ track=spec.track, rubric="r", agent_id=agent_id, plan=plan, agent=agent, contract_text="CONTRACT TEXT",
+ cookbook_rel=f"{lang.value}/cookbook.md", tool_cards="- `build`: builds")
+
+
+def test_all_track_templates_exist_and_render(tmp_ws, settings, chair_plan):
+ names = {p.split("/")[-1][:-3] for p in list_prompts() if p.startswith("tracks/") and p.endswith(".j2")}
+ assert names >= TEMPLATES
+ spec = make_spec()
+ ctx = _ctx(tmp_ws, settings, spec, chair_plan)
+ base = base_prompt_context(ctx)
+ assert base["output_format"] == SINGLE_SHOT_FORMAT and "| Seat |" in base["parts_table"]
+ g = render("tracks/generate_static.j2", **base_prompt_context(ctx, expected_files=["src/object.js"], skeleton_files={"src/object.js": "// s"}, previous_error=""))
+ assert "Y is UP" in g and "0.430" in g and "[a1]" in g and "=== FILE:" in g and "--- src/object.js ---" in g
+ r = render("tracks/refine_object.j2", **base_prompt_context(ctx, round_index=1, tasks=["[gate/contract] Seat: off"], targets=["Seat"],
+ files=["src/parts/seat.js"], edit_only_these=True, judge_summary="js", measurement_notes="mn",
+ current_files={"src/parts/seat.js": "x"}))
+ assert "EDIT ONLY THESE FILES" in r and "[gate/contract] Seat" in r
+ rp = render("tracks/repair.j2", **base_prompt_context(ctx, error_report="BUILD FAILED", files={}, repeats=1, attempt=2, failing_files=["src/model.py"]))
+ assert "SAME ERROR" in rp
+ art = ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT))
+ actx = _ctx(tmp_ws, settings, make_spec(Track.ARTICULATED_OBJECT, Language.URDF_BLENDER), art, agent_id="fake:x")
+ a = render("tracks/generate_articulated.j2", **base_prompt_context(actx, expected_files=["src/model.py", "src/robot.urdf"], skeleton_files={}, previous_error=""))
+ assert "| DrawerSlide |" in a and "rooted at `Cabinet`" in a and "HOW TO FINISH (agent mode)" in a and "Tools available" in a
+ # agent mode does not carry the single-shot format
+ assert "=== FILE:" not in a
+
+
+def test_scene_templates_render_and_asset_stage_with_blender(tmp_ws, settings):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS)
+ judge = FakeJudge(scores=(0.5, 0.9))
+ services = FakeServices(judge=judge)
+ agent = FakeAgent(lambda job, ws: {job.prompt.split("write `")[1].split("`")[0] if "write `" in job.prompt else "src/x.js": f"// {job.label}\n"})
+ ctx = _ctx(tmp_ws, settings, spec, plan, agent_id="fake:x", services=services, agent=agent)
+ ctx.runtime.skeleton(tmp_ws, plan)
+ tmp_ws.commit("skeleton")
+ results = run_asset_stage(ctx)
+ assert set(results) == {"FishingBoat", "Bollard", "Crate"}
+ crate = results["Crate"]
+ assert crate.ok and crate.path == "public/assets/crate.glb" and (tmp_ws.public / "assets" / "crate.glb").is_file()
+ assert crate.size_m is not None and crate.score is not None
+ # the blender asset was judged (0.5 < 0.8) and got exactly one fix pass
+ crate_jobs = [j.label for j in agent.jobs if j.label.startswith("asset_crate")]
+ assert crate_jobs == ["asset_crate", "asset_crate_fix"] and crate.fixed
+ assert (tmp_ws.root / "_assets" / "crate" / "src" / "model.py").is_file() and "_assets/" in (tmp_ws.root / ".gitignore").read_text()
+ assert results["FishingBoat"].ok and results["FishingBoat"].path == "src/assets/fishing_boat.js"
+ api = asset_api_summary(plan, results)
+ assert "buildFishingBoat" in api and "public/assets/crate.glb" in api
+ sub = asset_plan(plan.assets[2])
+ assert sub.parts[0].name == "Crate" and sub.overall_bbox.extents == (0.6, 0.4, 0.3) # Y-up w×h×d → Z-up (w, d, h)
+ ctx.extra["asset_api"] = api
+ from codeverse.tracks.scene import SceneTrack
+
+ st = SceneTrack(services=services)
+ for tpl, extra in (("scene_env", {}), ("scene_compose", {}),
+ ("scene_zone", dict(zone_name="Quay", zone_description="d", zone_bbox="b", zone_contents=["Bollard"], zone_file="src/zones/quay.js", neighbours=["Water: x"])),
+ ("scene_refine", dict(round_index=1, tasks=["t"], targets=["Quay"], files=["src/zones/quay.js"], edit_only_these=False, judge_summary="j", current_files={}))):
+ out = render(f"tracks/{tpl}.j2", **st._ctx(ctx, **extra))
+ assert "Harbour at dusk" in out and "DOM" in out
+ sa = render("tracks/scene_asset.j2", **base_prompt_context(ctx, asset_name="Bollard", asset_kind="threejs", asset_description="d", asset_size=(0.3, 0.5, 0.3),
+ asset_file="src/assets/bollard.js", asset_language="scene_threejs", fix_instructions=["- x"], current_code=""))
+ assert "buildBollard" in sa and "FIX PASS" in sa
diff --git a/harness/tests/orchestrator_tracks/test_tracks.py b/harness/tests/orchestrator_tracks/test_tracks.py
new file mode 100644
index 00000000..d03bc41f
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_tracks.py
@@ -0,0 +1,245 @@
+"""End-to-end track runs with fakes (no network, no Blender, no node)."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from codeverse.contracts.common import Language, Track
+from codeverse.contracts.plan import ArticulatedPlan, ScenePlan
+from codeverse.contracts.run import RunRecord, RunStatus
+from codeverse.events import EventLog
+from codeverse.orchestrator.rounds import RoundPolicy
+from codeverse.orchestrator.state import RunState
+from codeverse.tracks import get_track
+from codeverse.tracks.articulated_object import ArticulatedObjectTrack
+from codeverse.tracks.planner import plan_example
+from codeverse.tracks.scene import SceneTrack
+from codeverse.tracks.static_object import StaticObjectTrack
+from codeverse.workspace import Workspace
+from tests.orchestrator_tracks.conftest import make_spec
+from tests.orchestrator_tracks.fakes import (
+ FAIL_MARK,
+ FakeAgent,
+ FakeChatModel,
+ FakeJudge,
+ FakeRuntime,
+ FakeServices,
+)
+
+
+def _planner(plan_dict):
+ return FakeChatModel(lambda req: plan_dict)
+
+
+def _agent_writer(job, ws):
+ """Writes every file named in files_hint-ish prompt: we just write object.js + parts from the prompt table."""
+ files = {}
+ for line in job.prompt.splitlines():
+ if "| " in line and line.startswith("| ") and not line.startswith("| part") and not line.startswith("|---"):
+ name = line.split("|")[1].strip()
+ if name:
+ from codeverse.conventions import to_snake
+
+ files[f"src/parts/{to_snake(name)}.js"] = f"export function build{name}(THREE) {{ /* {job.label} r{job.extra.get('round', 0)} */ return new THREE.Group(); }}\n"
+ # every round edits something (a real refine agent changes code; identical output = plateau)
+ files["src/object.js"] = f"// {job.label} r{job.extra.get('round', 0)}\nexport function build(THREE) {{ return new THREE.Group(); }}\n"
+ return files
+
+
+def test_static_track_end_to_end_agent_path(tmp_path, chair_plan, settings):
+ spec = make_spec(max_rounds=3)
+ ws = Workspace(tmp_path / "runs" / "chair")
+ judge = FakeJudge(scores=(0.55, 0.7, 0.85))
+ services = FakeServices(contract_errors=1)
+ agent = FakeAgent(_agent_writer)
+ track = StaticObjectTrack(services=services, judge=judge, agent=agent, planner_model=_planner(chair_plan.model_dump(mode="json")),
+ settings=settings, runtime=FakeRuntime(Language.THREEJS))
+ rec = track.run(spec, ws)
+ assert isinstance(rec, RunRecord) and rec.status is RunStatus.PASSED
+ assert [r.kind for r in rec.rounds] == ["baseline", "refine", "refine"]
+ assert rec.baseline_score == pytest.approx(0.55) and rec.final_score == pytest.approx(0.85) and rec.best_round == 2
+ assert rec.total_usage.cost_usd > 0 and rec.extra["stop_reason"] == "pass"
+ assert ws.record_path.is_file() and ws.plan_path.is_file() and ws.state_path.is_file()
+ state = RunState.load(ws)
+ assert state.status is RunStatus.PASSED and state.best_round == 2 and state.completed_rounds == [0, 1, 2]
+ assert services.materialized == ["fake"] and (ws.root / "AGENTS.md").is_file()
+ kinds = [e["event"] for e in EventLog(ws.events_path).read()]
+ for k in ("run.start", "stage.done", "plan.done", "round.start", "build.done", "gates.done", "judge.done", "round.done", "best.updated", "stop", "run.done"):
+ assert k in kinds, k
+ # per-round artifacts
+ assert (ws.root / "rounds" / "r00.json").is_file() and ws.judge_path(2).is_file() and (ws.gates_dir(1) / "contract.json").is_file()
+ assert (ws.renders_dir(0) / "sheet.png").is_file()
+ # refine rounds carried gate + judge instructions; the contract error was the first instruction
+ assert rec.rounds[1].instructions and rec.rounds[1].instructions[0].startswith("[gate/gate:contract] Seat")
+ # baseline prompt is concrete: parts table + acceptance + contract + skeleton reminder
+ p0 = agent.jobs[0].prompt
+ assert "| Seat |" in p0 and "Acceptance checklist" in p0 and "Y is UP" in p0 and "overlap" in p0
+ # the refine round fanned out per part (≥3 file-disjoint groups, threejs)
+ labels = [j.label for j in agent.jobs]
+ assert sum(1 for lb in labels if lb.startswith("refine_")) >= 3
+ assert all("EDIT ONLY THESE FILES" in j.prompt for j in agent.jobs if j.label.startswith("refine_"))
+ # git history: one commit per round
+ assert len({r.commit for r in rec.rounds}) == 3 and ws.head() == rec.rounds[2].commit
+
+
+def test_static_track_single_shot_with_repair_and_budget_stop(tmp_path, chair_plan, settings):
+ spec = make_spec(generator="single-shot:gemini:fake", max_rounds=4, max_usd=0.03)
+ ws = Workspace(tmp_path / "runs" / "chair2")
+ n = {"gen": 0}
+
+ def responder(req):
+ n["gen"] += 1
+ if req.label == "baseline": # first build fails, the repair fixes it
+ return f"=== FILE: src/object.js ===\n// {FAIL_MARK}\nexport function build(){{}}\n=== END FILE ==="
+ return "=== FILE: src/object.js ===\nexport function build(THREE) { return new THREE.Group(); }\n=== END FILE ==="
+
+ model = FakeChatModel(responder, cost=0.004)
+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.5, 0.55, 0.6, 0.62)), model=model,
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.THREEJS))
+ rec = track.run(spec, ws)
+ assert rec.status is RunStatus.BUDGET and rec.rounds[0].build.ok and "repair attempts: 1 (fixed)" in rec.rounds[0].notes
+ assert rec.rounds[0].score == pytest.approx(0.5)
+ assert any(r.label.startswith("r00_baseline_repair") for r in model.requests) or any("Repair" in r.messages[0].text for r in model.requests)
+ assert rec.total_usage.cost_usd > 0.03 and ws.record_path.is_file()
+
+
+def test_static_track_resume_continues_from_saved_rounds(tmp_path, chair_plan, settings):
+ spec = make_spec(max_rounds=2)
+ ws = Workspace(tmp_path / "runs" / "chair3")
+ judge = FakeJudge(scores=(0.5, 0.6, 0.9))
+ services = FakeServices()
+ planner = _planner(chair_plan.model_dump(mode="json"))
+ rt = FakeRuntime(Language.THREEJS)
+ # first run: policy with max_rounds=0 → stops after the baseline (max_rounds)
+ t1 = StaticObjectTrack(services=services, judge=judge, agent=FakeAgent(_agent_writer), planner_model=planner, settings=settings,
+ runtime=rt, policy=RoundPolicy(max_rounds=0, target=0.8))
+ rec1 = t1.run(spec, ws)
+ assert len(rec1.rounds) == 1 and rec1.status is RunStatus.PLATEAU and rec1.extra["stop_reason"] == "max_rounds"
+ # resume with the full policy: planner must NOT be called again, baseline not re-run
+ planner.requests.clear()
+ t2 = StaticObjectTrack(services=services, judge=judge, agent=FakeAgent(_agent_writer), planner_model=planner, settings=settings,
+ runtime=rt, policy=RoundPolicy(max_rounds=2, target=0.8))
+ rec2 = t2.run(spec, ws, resume=True)
+ assert planner.requests == [] and [r.kind for r in rec2.rounds] == ["baseline", "refine", "refine"]
+ assert rec2.rounds[0].commit == rec1.rounds[0].commit and rec2.status is RunStatus.PASSED
+ kinds = [e["event"] for e in EventLog(ws.events_path).read()]
+ assert kinds.count("stage.cached") >= 2 # plan + skeleton cached on resume
+
+
+def test_static_track_failure_writes_failed_record_and_raises(tmp_path, chair_plan, settings):
+ spec = make_spec()
+ ws = Workspace(tmp_path / "runs" / "chair4")
+
+ class BoomRuntime(FakeRuntime):
+ def skeleton(self, ws, plan):
+ raise RuntimeError("skeleton exploded")
+
+ track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(), agent=FakeAgent(_agent_writer),
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=BoomRuntime(Language.THREEJS))
+ with pytest.raises(RuntimeError, match="skeleton exploded"):
+ track.run(spec, ws)
+ rec = RunRecord.model_validate(json.loads(ws.record_path.read_text()))
+ assert rec.status is RunStatus.FAILED and "skeleton exploded" in rec.error
+ assert RunState.load(ws).status is RunStatus.FAILED
+
+
+def test_static_track_blender_whole_object_refine(tmp_path, chair_plan, settings):
+ """blender = whole-object language: refine is ONE task; prompt carries measured-vs-plan numbers in Z-up."""
+ spec = make_spec(language=Language.BLENDER, max_rounds=1)
+ ws = Workspace(tmp_path / "runs" / "chair5")
+ agent = FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # {job.label}\n"})
+ track = StaticObjectTrack(services=FakeServices(contract_errors=2), judge=FakeJudge(scores=(0.5, 0.6)), agent=agent,
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.BLENDER))
+ rec = track.run(spec, ws)
+ assert [j.label for j in agent.jobs] == ["baseline", "refine"]
+ p = agent.jobs[1].prompt
+ assert "Measured overall extents" in p and "EDIT ONLY" not in p and "Files in scope: `src/model.py`" in p
+ assert rec.status is RunStatus.PLATEAU
+
+
+# ----------------------------------------------------------------------------- articulated
+def test_articulated_track_adds_pose_views_and_sweep_gate(tmp_path, settings):
+ spec = make_spec(Track.ARTICULATED_OBJECT, Language.URDF_BLENDER, max_rounds=1)
+ ws = Workspace(tmp_path / "runs" / "drawer")
+ plan = ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT))
+ agent = FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # {job.label}\n", "src/robot.urdf": "<robot name='x'/>\n"})
+ services = FakeServices(sweep_errors=1)
+ track = ArticulatedObjectTrack(services=services, judge=FakeJudge(scores=(0.6, 0.9), targets=("Drawer",)), agent=agent,
+ planner_model=_planner(plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.URDF_BLENDER))
+ rec = track.run(spec, ws)
+ assert rec.status is RunStatus.PASSED
+ r0 = rec.rounds[0]
+ assert any(v.name.startswith("pose_") for v in r0.renders.views)
+ sweep = next(g for g in r0.gates if g.gate == "joint_sweep")
+ assert not sweep.passed and rec.rounds[1].instructions[0].startswith("[gate/gate:joint_sweep] DrawerSlide")
+ assert "Joints (the URDF must realise EXACTLY these" in agent.jobs[0].prompt and "| DrawerSlide |" in agent.jobs[0].prompt
+ assert "Articulation sheet" in services._judge.calls[0].extra_context if services._judge else True
+
+
+# ----------------------------------------------------------------------------- scene
+def _scene_writer(job, ws):
+ label = job.label
+ if label.startswith("asset_"):
+ return {f"src/assets/{label[6:]}.js": f"export function build(){{}} // {label}\n"}
+ if label == "env":
+ return {"src/env.js": "export function buildEnv(){}\n"}
+ if label.startswith("zone_"):
+ return {f"src/zones/{label[5:]}.js": f"export function build(){{}} // {label}\n"}
+ if label == "compose":
+ return {"src/scene.js": "export function createScene(){}\n"}
+ if label.startswith("refine"):
+ return {f: f"// refined by {label}\n" for f in job.prompt.split("EDIT ONLY THESE FILES")[-1].splitlines() if False} or {"src/scene.js": f"// {label}\n"}
+ return {"src/scene.js": "// x\n"}
+
+
+def test_scene_track_stages_and_rounds(tmp_path, settings):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ plan.assets = [a for a in plan.assets if a.kind == "threejs"] # blender assets need a Blender runtime → covered separately
+ for z in plan.zones:
+ z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=1, prompt="a small harbour at dusk")
+ ws = Workspace(tmp_path / "runs" / "harbour")
+ agent = FakeAgent(_scene_writer)
+ services = FakeServices(assemble=False)
+ track = SceneTrack(services=services, judge=FakeJudge(scores=(0.6, 0.7), targets=("Quay", "Water")), agent=agent,
+ planner_model=_planner(plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.SCENE_THREEJS))
+ rec = track.run(spec, ws)
+ labels = [j.label for j in agent.jobs]
+ assert set(labels[:2]) == {"asset_fishing_boat", "asset_bollard"} and "env" in labels and "zone_quay" in labels and "zone_water" in labels
+ assert "compose" in labels # assembler unavailable → composer agent fallback
+ assert labels.index("env") < labels.index("zone_quay") < labels.index("compose")
+ assert (ws.src / "assets" / "fishing_boat.js").is_file() and (ws.src / "zones" / "quay.js").is_file() and (ws.src / "scene.js").is_file()
+ zone_prompt = next(j.prompt for j in agent.jobs if j.label == "zone_quay")
+ assert "buildFishingBoat" in zone_prompt and "8.00×3.50×3.00" in zone_prompt and "Neighbouring zones" in zone_prompt
+ assert [r.kind for r in rec.rounds] == ["baseline", "refine"] and rec.rounds[0].renders is not None
+ assert rec.rounds[0].renders.views and rec.status in (RunStatus.PLATEAU, RunStatus.PASSED)
+ st = RunState.load(ws)
+ assert {"plan", "skeleton", "assets", "env", "zones", "assemble"} <= set(st.stages)
+ # scene refine tasks route by file ownership: zone → src/zones/<zone>.js
+ assert any("src/zones/quay.js" in i for i in rec.rounds[1].instructions)
+
+
+def test_scene_track_deterministic_assembler_and_resume(tmp_path, settings):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ plan.assets = [a for a in plan.assets if a.kind == "threejs"]
+ for z in plan.zones:
+ z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0)
+ ws = Workspace(tmp_path / "runs" / "harbour2")
+ agent = FakeAgent(_scene_writer)
+ services = FakeServices(assemble=True)
+ mk = lambda: SceneTrack(services=services, judge=FakeJudge(scores=(0.6,)), agent=agent, planner_model=_planner(plan.model_dump(mode="json")), # noqa: E731
+ settings=settings, runtime=FakeRuntime(Language.SCENE_THREEJS))
+ rec = mk().run(spec, ws)
+ assert "compose" not in [j.label for j in agent.jobs] and "assembled by fake" in (ws.src / "scene.js").read_text()
+ n_jobs = len(agent.jobs)
+ rec2 = mk().run(spec, ws, resume=True)
+ assert len(agent.jobs) == n_jobs # all stages + baseline cached / loaded
+ assert len(rec2.rounds) == 1 and rec2.rounds[0].commit == rec.rounds[0].commit
+
+
+def test_get_track_dispatch():
+ assert isinstance(get_track("static_object"), StaticObjectTrack)
+ assert isinstance(get_track(Track.SCENE), SceneTrack)
diff --git a/harness/tests/prompts/conftest.py b/harness/tests/prompts/conftest.py
new file mode 100644
index 00000000..fe2e84dc
--- /dev/null
+++ b/harness/tests/prompts/conftest.py
@@ -0,0 +1,115 @@
+"""Shared helpers for the prompt-pack tests.
+
+The cookbooks promise that their fenced snippets RUN. These helpers extract the
+fenced blocks per language and execute them the way the cookbook headers say they
+are executed (concatenated in order, with the documented prelude in scope).
+"""
+
+from __future__ import annotations
+
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from codeverse.config import get_settings
+
+PROMPTS_DIR = Path(__file__).resolve().parents[2] / "codeverse" / "prompts"
+RUNTIME_JS = Path(__file__).resolve().parents[2] / "runtime_js"
+HELPERS = Path(__file__).resolve().parent / "helpers"
+
+#: every file this package owns (relative to codeverse/prompts/)
+PROMPT_FILES = [
+ "system/harness_contract.md",
+ "system/singleshot_format.md",
+ "system/tools_usage.md",
+ "blender/contract.md",
+ "blender/cookbook.md",
+ "cadquery/contract.md",
+ "cadquery/cookbook.md",
+ "threejs/contract.md",
+ "threejs/cookbook.md",
+ "urdf/contract.md",
+ "urdf/cookbook.md",
+ "scene_threejs/contract.md",
+ "scene_threejs/cookbook.md",
+ "scene_threejs/glsl_cookbook.md",
+]
+
+_FENCE = re.compile(r"```(\w[\w-]*)\n(.*?)```", re.DOTALL)
+
+
+def read_prompt(rel: str) -> str:
+ return (PROMPTS_DIR / rel).read_text()
+
+
+def blocks(rel: str, lang: str) -> list[str]:
+ """All fenced blocks tagged ``lang`` in prompt file ``rel``, in order."""
+ return [body for tag, body in _FENCE.findall(read_prompt(rel)) if tag == lang]
+
+
+def strip_imports_exports(js: str) -> str:
+ js = re.sub(r"^\s*import .*?;\s*$", "", js, flags=re.MULTILINE)
+ return re.sub(r"^export (default )?", "", js, flags=re.MULTILINE)
+
+
+def labelled_files(rel: str, tag: str = "js") -> dict[str, str]:
+ """Blocks preceded by a `src/...` label line → {path: content} (contract examples)."""
+ out: dict[str, str] = {}
+ pattern = re.compile(r"`((?:src|public)/[^`]+)`\n```" + tag + r"\n(.*?)```", re.DOTALL)
+ for path, body in pattern.findall(read_prompt(rel)):
+ out[path] = body
+ return out
+
+
+# ----------------------------------------------------------------------- runners
+def run_node_module(tmp_path: Path, code: str, timeout: int = 120) -> str:
+ """Write ``code`` as an ES module next to a node_modules symlink and run it."""
+ node = shutil.which(get_settings().binaries.node) or shutil.which("node")
+ if node is None:
+ pytest.skip("node not available")
+ link = tmp_path / "node_modules"
+ if not link.exists():
+ link.symlink_to(RUNTIME_JS / "node_modules")
+ mod = tmp_path / "run.mjs"
+ mod.write_text(code)
+ proc = subprocess.run(
+ [node, "run.mjs"], cwd=tmp_path, capture_output=True, text=True, timeout=timeout
+ )
+ assert proc.returncode == 0, f"node failed:\nSTDOUT:{proc.stdout[-3000:]}\nSTDERR:{proc.stderr[-3000:]}"
+ return proc.stdout
+
+
+def run_blender_script(tmp_path: Path, code: str, timeout: int = 240) -> str:
+ """Run python ``code`` inside Blender headless with an emptied factory scene."""
+ blender = get_settings().resolve_blender()
+ if not blender:
+ pytest.skip("no Blender binary configured")
+ script = tmp_path / "run_bpy.py"
+ script.write_text(
+ "import bpy\n"
+ "for _o in list(bpy.data.objects): bpy.data.objects.remove(_o, do_unlink=True)\n"
+ + code
+ + "\nprint('BPY_SNIPPETS_OK')\n"
+ )
+ proc = subprocess.run(
+ [str(blender), "-b", "--factory-startup", "--python", str(script)],
+ capture_output=True, text=True, timeout=timeout,
+ )
+ out = proc.stdout + proc.stderr
+ assert "BPY_SNIPPETS_OK" in out, f"blender snippets failed (rc={proc.returncode}):\n{out[-4000:]}"
+ return out
+
+
+def js_prelude(extra: str = "") -> str:
+ return (
+ "import * as THREE from 'three';\n"
+ "import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';\n"
+ "import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';\n"
+ "import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';\n"
+ "import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';\n"
+ "import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';\n"
+ "import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';\n" + extra
+ )
diff --git a/harness/tests/prompts/helpers/glsl_compile.mjs b/harness/tests/prompts/helpers/glsl_compile.mjs
new file mode 100644
index 00000000..0b0a878d
--- /dev/null
+++ b/harness/tests/prompts/helpers/glsl_compile.mjs
@@ -0,0 +1,101 @@
+// Compile every `make*Material(THREE, opts)` export of a module in headless Chrome (real WebGL)
+// and report shader errors. Usage: node glsl_compile.mjs <dir-with-node_modules-and-module> <module.mjs>
+// Prints one JSON line: {ok, gpu, results:[{name, mesh:{ok, errors}, instanced:{ok, errors}}]}
+import http from 'node:http';
+import fs from 'node:fs';
+import path from 'node:path';
+import { createRequire } from 'node:module';
+import url from 'node:url';
+
+const RUNTIME = process.env.C3V_RUNTIME_JS
+ || path.resolve(path.dirname(url.fileURLToPath(import.meta.url)), '../../../runtime_js');
+const require_ = createRequire(path.join(RUNTIME, 'package.json'));
+const puppeteer = require_('puppeteer');
+
+const [,, rootArg, moduleRel] = process.argv;
+const root = path.resolve(rootArg);
+const MIME = { '.js': 'text/javascript', '.mjs': 'text/javascript', '.html': 'text/html', '.json': 'application/json', '.glb': 'model/gltf-binary' };
+
+const html = `<!doctype html><html><head><meta charset="utf-8">
+<script type="importmap">{"imports":{"three":"/node_modules/three/build/three.module.js","three/addons/":"/node_modules/three/examples/jsm/"}}</script>
+</head><body><script type="module">
+import * as THREE from 'three';
+import * as mod from '/${moduleRel}';
+const out = { results: [], gpu: '' };
+const canvas = document.createElement('canvas'); canvas.width = 256; canvas.height = 256; document.body.appendChild(canvas);
+const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, logarithmicDepthBuffer: true });
+renderer.setSize(256, 256, false);
+renderer.outputColorSpace = THREE.SRGBColorSpace; renderer.toneMapping = THREE.ACESFilmicToneMapping;
+renderer.shadowMap.enabled = true;
+const gl = renderer.getContext(); const ext = gl.getExtension('WEBGL_debug_renderer_info');
+out.gpu = ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : 'unknown';
+let errs = [];
+renderer.debug.onShaderError = (gl, program, vs, fs) => {
+ const vlog = gl.getShaderInfoLog(vs) || '', flog = gl.getShaderInfoLog(fs) || '', plog = gl.getProgramInfoLog(program) || '';
+ errs.push(('VS:' + vlog + ' FS:' + flog + ' P:' + plog).slice(0, 1500));
+};
+const camera = new THREE.PerspectiveCamera(50, 1, 0.1, 500); camera.position.set(3, 3, 5); camera.lookAt(0, 0, 0);
+const names = Object.keys(mod).filter(k => /^make\\w*Material$/.test(k) && typeof mod[k] === 'function');
+for (const name of names) {
+ const res = { name };
+ for (const kind of ['mesh', 'instanced']) {
+ errs = [];
+ const scene = new THREE.Scene(); scene.fog = new THREE.Fog(0x8899aa, 5, 50);
+ scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 1), new THREE.DirectionalLight(0xffffff, 1));
+ let mat;
+ try { mat = mod[name](THREE, {}); } catch (e) { res[kind] = { ok: false, errors: ['factory threw: ' + (e && e.message)] }; continue; }
+ const geo = new THREE.PlaneGeometry(2, 2, 4, 4);
+ const obj = kind === 'mesh' ? new THREE.Mesh(geo, mat) : new THREE.InstancedMesh(geo, mat, 4);
+ if (kind === 'instanced') { const m = new THREE.Matrix4(); for (let i = 0; i < 4; i++) { m.makeTranslation(i, 0, 0); obj.setMatrixAt(i, m); } }
+ scene.add(obj);
+ try {
+ if (mat.uniforms && mat.uniforms.uTime) mat.uniforms.uTime.value = 1.0;
+ if (typeof mat.userData?.update === 'function') mat.userData.update(1.0, 0.016);
+ renderer.compile(scene, camera); renderer.render(scene, camera);
+ } catch (e) { errs.push('render threw: ' + (e && e.message)); }
+ res[kind] = { ok: errs.length === 0, errors: errs.slice() };
+ }
+ out.results.push(res);
+}
+out.ok = out.results.every(r => r.mesh.ok && r.instanced.ok) && out.results.length > 0;
+window.__result = out;
+</script></body></html>`;
+
+const server = http.createServer((req, res) => {
+ const url = decodeURIComponent(req.url.split('?')[0]);
+ if (url === '/' || url === '/index.html') { res.writeHead(200, { 'content-type': 'text/html' }); res.end(html); return; }
+ const abs = path.join(root, url);
+ if (!abs.startsWith(root) || !fs.existsSync(abs) || !fs.statSync(abs).isFile()) { res.writeHead(404); res.end('nf'); return; }
+ res.writeHead(200, { 'content-type': MIME[path.extname(abs)] || 'application/octet-stream' }); res.end(fs.readFileSync(abs));
+});
+await new Promise(r => server.listen(0, '127.0.0.1', r));
+const base = `http://127.0.0.1:${server.address().port}`;
+const GPU_ENV = { GALLIUM_DRIVER: 'd3d12', MESA_LOADER_DRIVER_OVERRIDE: 'd3d12', MESA_D3D12_DEFAULT_ADAPTER_NAME: 'NVIDIA' };
+const BASE = ['--no-sandbox', '--disable-setuid-sandbox', '--enable-webgl', '--ignore-gpu-blocklist'];
+async function launch(gpu) {
+ return puppeteer.launch({ headless: true, protocolTimeout: 120000,
+ args: gpu ? [...BASE, '--enable-gpu-rasterization', '--use-angle=gl-egl'] : [...BASE, '--enable-unsafe-swiftshader', '--use-angle=swiftshader'],
+ env: gpu ? { ...process.env, ...GPU_ENV } : process.env });
+}
+let result = null, lastErr = '';
+for (const gpu of [true, false]) {
+ let browser;
+ try {
+ browser = await launch(gpu);
+ const page = await browser.newPage();
+ const consoleErrs = [];
+ page.on('console', m => { if (m.type() === 'error') consoleErrs.push(m.text().slice(0, 400)); });
+ page.on('pageerror', e => consoleErrs.push('pageerror: ' + e.message));
+ await page.goto(base + '/', { waitUntil: 'load', timeout: 60000 });
+ await page.waitForFunction('window.__result !== undefined', { timeout: 90000 });
+ result = await page.evaluate(() => window.__result);
+ result.console = consoleErrs.filter(t => !/GL_INVALID|THREE\.WebGLProgram/.test(t));
+ result.mode = gpu ? 'gpu' : 'cpu';
+ if (!result.gpu || /swiftshader|llvmpipe|software/i.test(result.gpu)) { if (gpu) { await browser.close(); continue; } }
+ break;
+ } catch (e) { lastErr = String(e && e.message); } finally { if (browser) await browser.close().catch(() => {}); }
+}
+server.close();
+if (!result) { console.log(JSON.stringify({ ok: false, error: lastErr || 'no result' })); process.exit(2); }
+console.log(JSON.stringify(result));
+process.exit(result.ok ? 0 : 1);
diff --git a/harness/tests/prompts/test_files.py b/harness/tests/prompts/test_files.py
new file mode 100644
index 00000000..18ce595e
--- /dev/null
+++ b/harness/tests/prompts/test_files.py
@@ -0,0 +1,88 @@
+"""Every prompt file exists, renders through the loader, and keeps its promises."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.prompts import load_text, prompt_hash, render
+from tests.prompts.conftest import PROMPT_FILES, PROMPTS_DIR, read_prompt
+
+
[email protected]("rel", PROMPT_FILES)
+def test_file_exists_and_nonempty(rel: str) -> None:
+ p = PROMPTS_DIR / rel
+ assert p.is_file(), f"missing prompt file {rel}"
+ assert len(p.read_text()) > 500, f"{rel} suspiciously small"
+
+
[email protected]("rel", PROMPT_FILES)
+def test_loads_and_renders(rel: str) -> None:
+ raw = load_text(rel)
+ assert prompt_hash(raw)
+ # markdown prompts must be jinja-inert: render() with no context must be a no-op
+ rendered = render(rel)
+ assert rendered == raw, f"{rel} contains live jinja syntax; keep prompt .md files static"
+
+
[email protected]("rel", PROMPT_FILES)
+def test_jinja_safe(rel: str) -> None:
+ text = read_prompt(rel)
+ for seq in ("{{", "{%", "{#"):
+ assert seq not in text, f"{rel} contains {seq!r} which breaks jinja rendering"
+
+
+ "rel",
+ [f for f in PROMPT_FILES if f.endswith("cookbook.md")],
+)
+def test_cookbook_structure(rel: str) -> None:
+ text = read_prompt(rel)
+ headings = [line[3:].strip() for line in text.splitlines() if line.startswith("## ")]
+ assert len(headings) >= 5, f"{rel}: cookbooks are chaptered with '## ' headings"
+ assert len(headings) == len(set(headings)), f"{rel}: duplicate section headings"
+ joined = " | ".join(headings)
+ assert "Pitfalls" in joined, f"{rel}: needs a Pitfalls chapter"
+ lines = len(text.splitlines())
+ assert 250 <= lines <= 950, f"{rel}: {lines} lines (want a substantial but bounded cookbook)"
+
+
+ "rel", [f for f in PROMPT_FILES if f.endswith("contract.md") and not f.startswith("system/")]
+)
+def test_contract_size_and_content(rel: str) -> None:
+ text = read_prompt(rel)
+ lines = len(text.splitlines())
+ assert lines <= 150, f"{rel}: {lines} lines — contracts must stay short"
+ assert "COMPLETE minimal example" in text, f"{rel}: must carry a complete runnable example"
+ low = text.lower()
+ assert "meter" in low or "metre" in low, f"{rel}: units must be stated"
+
+
+def test_frames_consistent_with_conventions() -> None:
+ """Contracts restate the frame; they must agree with conventions.py (Z-up −Y-front
+ for blender/cadquery/urdf, Y-up +Z-front for the three.js languages)."""
+ for rel in ("blender/contract.md", "cadquery/contract.md", "urdf/contract.md"):
+ text = read_prompt(rel).replace("\u2212", "-")
+ assert "Z up" in text or "Z is up" in text, f"{rel}: must state Z up"
+ assert "-Y front" in text or "-Y is the front" in text, f"{rel}: must state -Y front"
+ for rel in ("threejs/contract.md", "scene_threejs/contract.md"):
+ text = read_prompt(rel).replace("\u2212", "-")
+ assert "Y is up" in text or "Y-up" in text, f"{rel}: must state Y up"
+ assert "+Z front" in text or "+Z is the front" in text, f"{rel}: must state +Z front"
+
+
+def test_singleshot_format_matches_parser_contract() -> None:
+ text = read_prompt("system/singleshot_format.md")
+ assert "=== FILE: " in text and "=== END FILE ===" in text
+
+
+def test_system_prompts_cover_the_laws() -> None:
+ hc = read_prompt("system/harness_contract.md")
+ for needle in ("artifacts/", "render_sheet", "check_connectivity", "2 mm",
+ "Definition of done", "ground", "seed"):
+ assert needle.lower() in hc.lower(), f"harness_contract.md must mention {needle!r}"
+ tu = read_prompt("system/tools_usage.md")
+ for tool in ("build", "measure", "render_views", "render_sheet", "isolate", "cross_section",
+ "check_connectivity", "check_contract", "compare_silhouette", "joint_sweep",
+ "shader_probe", "scene_probe", "read_cookbook"):
+ assert f"`{tool}" in tu, f"tools_usage.md must document {tool!r}"
diff --git a/harness/tests/prompts/test_snippets_run.py b/harness/tests/prompts/test_snippets_run.py
new file mode 100644
index 00000000..478f9ff2
--- /dev/null
+++ b/harness/tests/prompts/test_snippets_run.py
@@ -0,0 +1,275 @@
+"""The cookbooks' promise: every snippet RUNS.
+
+* cadquery blocks run in-process (cadquery is a plain library).
+* bpy blocks run in real headless Blender (marker: blender).
+* js blocks run in real node against runtime_js/node_modules (marker: node).
+* GLSL factories compile in real headless-Chrome WebGL (marker: node).
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import shutil
+import subprocess
+
+import pytest
+
+from tests.prompts.conftest import (
+ HELPERS,
+ blocks,
+ js_prelude,
+ labelled_files,
+ run_blender_script,
+ run_node_module,
+ strip_imports_exports,
+)
+
+
+# --------------------------------------------------------------------- cadquery
+def _exec_python_blocks(rel: str) -> dict:
+ pytest.importorskip("cadquery")
+ ns: dict = {}
+ for i, body in enumerate(blocks(rel, "python")):
+ try:
+ exec(compile(body, f"{rel}:block{i}", "exec"), ns) # noqa: S102 - our own docs
+ except Exception as e: # pragma: no cover - failure path
+ pytest.fail(f"{rel} python block {i} failed: {type(e).__name__}: {e}")
+ return ns
+
+
+def test_cadquery_cookbook_runs() -> None:
+ ns = _exec_python_blocks("cadquery/cookbook.md")
+ assert "selfcheck" in ns and "result" in ns
+
+
+def test_cadquery_contract_example_runs() -> None:
+ import cadquery as cq # noqa: F401
+
+ ns = _exec_python_blocks("cadquery/contract.md")
+ result = ns["result"]
+ bb = result.toCompound().BoundingBox()
+ assert abs(bb.zmin) < 1e-6 and abs(bb.zmax - 0.45) < 1e-3
+ assert [c.name for c in result.children] == ["Top", "Leg1", "Leg2", "Leg3", "Leg4"]
+
+
+# --------------------------------------------------------------------- blender
+def test_blender_cookbook_runs(tmp_path) -> None:
+ code = "\n".join(blocks("blender/cookbook.md", "python"))
+ out = run_blender_script(tmp_path, code)
+ assert "mesh objects" in out
+
+
+def test_blender_contract_example_builds_and_exports(tmp_path) -> None:
+ code = "\n".join(blocks("blender/contract.md", "python"))
+ glb = tmp_path / "object.glb"
+ code += (
+ "\n_selfcheck()\nimport bpy\n"
+ f"bpy.ops.export_scene.gltf(filepath={str(glb)!r}, export_format='GLB', "
+ "export_yup=True, export_apply=True)\n"
+ "print('PARTS', sorted(o.name for o in bpy.data.objects))\n"
+ )
+ out = run_blender_script(tmp_path, code)
+ assert "PARTS ['Leg1', 'Leg2', 'Leg3', 'Seat']" in out
+ assert glb.stat().st_size > 1000
+ trimesh = pytest.importorskip("trimesh")
+ scene = trimesh.load(str(glb))
+ lo, hi = scene.bounds
+ assert abs(lo[1]) < 1e-3 and abs(hi[1] - 0.45) < 1e-3 # Y-up GLB, on the ground
+
+
+def test_urdf_cookbook_runs(tmp_path) -> None:
+ code = "\n".join(blocks("urdf/cookbook.md", "python"))
+ out = run_blender_script(tmp_path, code)
+ assert "[selfcheck] links" in out
+
+
+def test_urdf_contract_example_fk_and_clearance(tmp_path) -> None:
+ """Full pipeline: build in Blender, export per-link meshes in link frames,
+ load the URDF with yourdfpy, sweep the lid — it must open upward, no penetration."""
+ yourdfpy = pytest.importorskip("yourdfpy")
+ trimesh = pytest.importorskip("trimesh")
+ pytest.importorskip("fcl")
+ code = "\n".join(blocks("urdf/contract.md", "python"))
+ meshes = tmp_path / "meshes"
+ meshes.mkdir()
+ code += (
+ "\nimport mathutils, bpy\n"
+ "for _o in [o for o in bpy.data.objects if o.type == 'MESH']:\n"
+ " bpy.ops.object.select_all(action='DESELECT'); _o.select_set(True)\n"
+ " bpy.context.view_layer.objects.active = _o\n"
+ " bpy.ops.object.transform_apply(location=True, rotation=True, scale=True)\n"
+ " _o.data.transform(mathutils.Matrix.Translation(-PIVOT[_o.name]))\n"
+ f" bpy.ops.export_scene.gltf(filepath={str(meshes)!r} + '/' + _o.name + '.glb',\n"
+ " export_format='GLB', use_selection=True, export_yup=False, export_apply=True)\n"
+ )
+ run_blender_script(tmp_path, code)
+ urdf_text = blocks("urdf/contract.md", "xml")[0]
+ (tmp_path / "robot.urdf").write_text(urdf_text)
+ u = yourdfpy.URDF.load(
+ str(tmp_path / "robot.urdf"), build_scene_graph=True, load_meshes=True, mesh_dir=str(tmp_path)
+ )
+ tops = {}
+ for q in (0.0, 0.75, 1.5):
+ u.update_cfg({"BodyToLid": q})
+ s = u.scene
+ cm = trimesh.collision.CollisionManager()
+ world = {}
+ for name, geom in s.geometry.items():
+ node = next(n for n in s.graph.nodes_geometry if s.graph[n][1] == name)
+ m = geom.copy()
+ m.apply_transform(s.graph[node][0])
+ world[node] = m
+ cm.add_object(node, m)
+ _, pairs = cm.in_collision_internal(return_names=True)
+ # only the intended weld (Knob into Lid, fixed joint) may touch
+ unexpected = {p for p in pairs if set(x.split(".glb")[0] for x in p) != {"Knob", "Lid"}}
+ assert not unexpected, f"unexpected penetration at q={q}: {unexpected}"
+ tops[q] = world[next(k for k in world if k.startswith("Lid"))].bounds[1][2]
+ assert tops[1.5] > tops[0.75] > tops[0.0] + 0.05, f"lid does not open upward: {tops}"
+
+
+# ------------------------------------------------------------------------ node
+def test_threejs_cookbook_runs(tmp_path) -> None:
+ body = "".join(
+ f"\nconsole.log('--- block {i} ---');\n" + strip_imports_exports(b)
+ for i, b in enumerate(blocks("threejs/cookbook.md", "js"))
+ )
+ out = run_node_module(tmp_path, js_prelude() + body + "\nconsole.log('JS_BLOCKS_OK');\n")
+ assert "JS_BLOCKS_OK" in out and "[selfcheck]" in out
+
+
+def test_threejs_contract_example_builds_glb(tmp_path) -> None:
+ files = labelled_files("threejs/contract.md")
+ assert set(files) == {"src/parts/seat.js", "src/parts/legs.js", "src/object.js"}
+ for rel, body in files.items():
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(body)
+ runner = """
+import * as THREE from 'three';
+import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
+import { writeFileSync } from 'node:fs';
+import { build } from './src/object.js';
+globalThis.FileReader = class {
+ readAsArrayBuffer(b) { b.arrayBuffer().then((x) => { this.result = x; this.onloadend && this.onloadend(); }); }
+};
+const root = build(THREE);
+let verts = 0; root.traverse((o) => { if (o.isMesh) verts += o.geometry.attributes.position.count; });
+const box = new THREE.Box3().setFromObject(root);
+if (verts < 100) throw new Error('too few vertices: ' + verts);
+if (Math.abs(box.min.y) > 1e-3) throw new Error('not on ground: ' + box.min.y);
+const buf = await new GLTFExporter().parseAsync(root, { binary: true });
+writeFileSync('object.glb', Buffer.from(buf));
+console.log('GLB_OK', verts, buf.byteLength);
+"""
+ out = run_node_module(tmp_path, runner)
+ assert "GLB_OK" in out
+ assert (tmp_path / "object.glb").stat().st_size > 1000
+
+
+def test_scene_cookbook_runs(tmp_path) -> None:
+ stub = (
+ "function collectAnimatedMaterials(scene){const mats=[];scene.traverse(o=>{"
+ "const l=Array.isArray(o.material)?o.material:(o.material?[o.material]:[]);"
+ "for(const m of l) if(m.userData&&typeof m.userData.update==='function'&&!mats.includes(m))"
+ "mats.push(m);});return mats;}\n"
+ )
+ body = "".join(
+ f"\nconsole.log('--- block {i} ---');\n" + strip_imports_exports(b)
+ for i, b in enumerate(blocks("scene_threejs/cookbook.md", "js"))
+ )
+ out = run_node_module(tmp_path, js_prelude(stub) + body + "\nconsole.log('JS_BLOCKS_OK');\n")
+ assert "JS_BLOCKS_OK" in out and "[selfcheck]" in out
+
+
+def test_scene_contract_example_shape(tmp_path) -> None:
+ files = labelled_files("scene_threejs/contract.md")
+ assert set(files) == {"src/env.js", "src/zones/grove.js", "src/scene.js"}
+ for rel, body in files.items():
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(body)
+ runner = """
+import * as THREE from 'three';
+import { createScene } from './src/scene.js';
+const r = await createScene({ THREE, renderer: null, loaders: {} });
+if (!r.scene || !r.scene.isScene) throw new Error('no scene');
+if (!r.scene.fog) throw new Error('no fog');
+if (!Array.isArray(r.cameras) || r.cameras.length < 2) throw new Error('cameras');
+for (const c of r.cameras) {
+ if (typeof c.name !== 'string' || !Array.isArray(c.position) || !Array.isArray(c.lookAt))
+ throw new Error('camera shape: ' + JSON.stringify(c));
+}
+r.update(0, 0); r.update(1.5, 0.016);
+console.log('SCENE_OK', r.cameras.map((c) => c.name).join(','));
+"""
+ out = run_node_module(tmp_path, runner)
+ assert "SCENE_OK" in out
+
+
+def test_glsl_cookbook_compiles_in_chrome(tmp_path) -> None:
+ """Every make*Material factory compiles in a real WebGL context (GPU or SwiftShader),
+ on a Mesh and on an InstancedMesh, with fog + log-depth renderer settings."""
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node not available")
+ mod = "import * as THREE from 'three';\n" + "".join(
+ "\n" + strip_imports_exports(b) for b in blocks("scene_threejs/glsl_cookbook.md", "js")
+ )
+ names = sorted(set(re.findall(r"function (make\w*Material)\(", mod)))
+ assert len(names) >= 8, f"expected the GLSL factories, found {names}"
+ mod += "\nexport { " + ", ".join(names) + " };\n"
+ link = tmp_path / "node_modules"
+ if not link.exists():
+ from tests.prompts.conftest import RUNTIME_JS
+
+ link.symlink_to(RUNTIME_JS / "node_modules")
+ (tmp_path / "glsl_mod.mjs").write_text(mod)
+ proc = subprocess.run(
+ [node, str(HELPERS / "glsl_compile.mjs"), str(tmp_path), "glsl_mod.mjs"],
+ capture_output=True, text=True, timeout=300,
+ )
+ assert proc.stdout.strip(), f"no output: {proc.stderr[-2000:]}"
+ report = json.loads(proc.stdout.strip().splitlines()[-1])
+ assert report.get("ok"), f"GLSL compile failures: {json.dumps(report, indent=2)[:4000]}"
+ checked = {r["name"] for r in report["results"]}
+ assert set(names) <= checked
+
+
+def test_scene_cookbook_sky_shader_compiles(tmp_path) -> None:
+ """The inline sky-dome ShaderMaterial from the scene cookbook must also compile."""
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node not available")
+ body = "".join("\n" + strip_imports_exports(b) for b in blocks("scene_threejs/cookbook.md", "js")[:2])
+ mod = (
+ "import * as THREE from 'three';\n" + body
+ + "\nexport function makeSkyMaterial(THREE_) {\n"
+ " const s = new THREE_.Scene();\n"
+ " buildEnv(THREE_, s);\n"
+ " return s.getObjectByName('SkyDome').material;\n"
+ "}\n"
+ )
+ link = tmp_path / "node_modules"
+ if not link.exists():
+ from tests.prompts.conftest import RUNTIME_JS
+
+ link.symlink_to(RUNTIME_JS / "node_modules")
+ (tmp_path / "sky_mod.mjs").write_text(mod)
+ proc = subprocess.run(
+ [node, str(HELPERS / "glsl_compile.mjs"), str(tmp_path), "sky_mod.mjs"],
+ capture_output=True, text=True, timeout=300,
+ )
+ report = json.loads(proc.stdout.strip().splitlines()[-1])
+ assert report.get("ok"), f"sky shader failed to compile: {json.dumps(report)[:3000]}"
diff --git a/harness/tests/prompts/test_snippets_static.py b/harness/tests/prompts/test_snippets_static.py
new file mode 100644
index 00000000..85ebcff6
--- /dev/null
+++ b/harness/tests/prompts/test_snippets_static.py
@@ -0,0 +1,127 @@
+"""Static validity of every fenced snippet: python parses, XML/URDF parses, JS parses."""
+
+from __future__ import annotations
+
+import ast
+import re
+import shutil
+import subprocess
+import xml.etree.ElementTree as ET
+
+import pytest
+
+from tests.prompts.conftest import PROMPT_FILES, blocks, read_prompt
+
+PY_FILES = [f for f in PROMPT_FILES if f.split("/")[0] in ("blender", "cadquery", "urdf")]
+JS_FILES = [f for f in PROMPT_FILES if f.split("/")[0] in ("threejs", "scene_threejs")]
+JS_FILES.append("system/singleshot_format.md")
+XML_FILES = ["urdf/contract.md", "urdf/cookbook.md"]
+
+
[email protected]("rel", PY_FILES)
+def test_python_blocks_parse(rel: str) -> None:
+ found = 0
+ for i, body in enumerate(blocks(rel, "python")):
+ try:
+ ast.parse(body)
+ except SyntaxError as e: # pragma: no cover - failure path
+ pytest.fail(f"{rel} python block {i} does not parse: {e}")
+ found += 1
+ assert found > 0, f"{rel}: expected at least one python block"
+
+
[email protected]("rel", XML_FILES)
+def test_xml_blocks_are_valid_urdf(rel: str) -> None:
+ found = 0
+ for i, body in enumerate(blocks(rel, "xml")):
+ root = ET.fromstring(body)
+ assert root.tag == "robot" and root.get("name"), f"{rel} xml block {i}: not a <robot>"
+ links = {ln.get("name") for ln in root.findall("link")}
+ children = set()
+ for j in root.findall("joint"):
+ jtype = j.get("type")
+ parent = j.find("parent").get("link")
+ child = j.find("child").get("link")
+ assert parent in links and child in links, f"{rel} block {i}: joint {j.get('name')} references unknown link"
+ assert child not in children, f"{rel} block {i}: link {child} has two parents"
+ children.add(child)
+ origin = j.find("origin")
+ assert origin is not None and origin.get("rpy", "0 0 0").split() == ["0", "0", "0"], \
+ f"{rel} block {i}: joint {j.get('name')} must have rpy='0 0 0' (frame recipe)"
+ limit = j.find("limit")
+ if jtype in ("revolute", "prismatic"):
+ assert limit is not None and limit.get("lower") is not None and limit.get("upper") is not None, \
+ f"{rel} block {i}: {jtype} joint {j.get('name')} needs lower/upper"
+ assert float(limit.get("lower")) < float(limit.get("upper"))
+ if jtype == "continuous":
+ assert limit is None or (limit.get("lower") is None and limit.get("upper") is None)
+ axis = j.find("axis")
+ if jtype != "fixed":
+ v = [float(x) for x in axis.get("xyz").split()]
+ assert abs(sum(a * a for a in v) - 1.0) < 1e-6, f"{rel} block {i}: non-unit axis on {j.get('name')}"
+ roots = links - children
+ assert len(roots) == 1, f"{rel} block {i}: expected a single root link, got {roots}"
+ for v in root.iter("visual"):
+ o = v.find("origin")
+ assert o is not None and o.get("xyz") == "0 0 0", f"{rel} block {i}: visual origins must be 0 0 0"
+ mesh = v.find("geometry/mesh")
+ assert mesh is not None and mesh.get("filename", "").startswith("meshes/"), \
+ f"{rel} block {i}: visuals must reference meshes/<link>.glb"
+ assert mesh.get("scale") is None, f"{rel} block {i}: mesh scale is forbidden"
+ found += 1
+ assert found > 0, f"{rel}: expected at least one xml block"
+
+
[email protected]("rel", [f for f in JS_FILES if f != "system/singleshot_format.md"])
+def test_js_blocks_syntax(rel: str, tmp_path) -> None:
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node not available")
+ bs = blocks(rel, "js")
+ assert bs, f"{rel}: expected at least one js block"
+ for i, body in enumerate(bs):
+ p = tmp_path / f"block_{i}.mjs"
+ p.write_text(body)
+ proc = subprocess.run([node, "--check", str(p)], capture_output=True, text=True, timeout=30)
+ assert proc.returncode == 0, f"{rel} js block {i} syntax error:\n{proc.stderr[-1500:]}"
+
+
+def test_glsl_strings_are_sane() -> None:
+ """GLSL lives inside JS template strings; audit the obvious silent killers
+ INSIDE the js code blocks (prose may mention them as pitfalls)."""
+ for rel in ("scene_threejs/glsl_cookbook.md", "scene_threejs/cookbook.md"):
+ for b, body in enumerate(blocks(rel, "js")):
+ assert not re.search(r"^\s*#version", body, re.MULTILINE), \
+ f"{rel} js block {b}: never write #version in ShaderMaterial GLSL"
+ for m in re.finditer(r"^(.*#include <\w+>.*)$", body, re.MULTILINE):
+ line = m.group(1).strip()
+ if "'" in line:
+ # JS source line: inside every quoted chunk, each (escaped-\n separated)
+ # GLSL line holding an include must be ONLY the include
+ for chunk in re.findall(r"'([^']*#include[^']*)'", line):
+ for glsl_line in re.split(r"\\+n", chunk):
+ if "#include" not in glsl_line:
+ continue
+ assert re.fullmatch(r"\s*#include <\w+>\s*", glsl_line), \
+ f"{rel} js block {b}: include shares a line with code: {line!r}"
+ else:
+ # raw GLSL line inside a template literal: must stand alone
+ assert re.fullmatch(r"#include <\w+>", line), \
+ f"{rel} js block {b}: #include must be alone on its line: {line!r}"
+ lib = read_prompt("scene_threejs/glsl_cookbook.md")
+ for fn in ("c3vHash21", "c3vNoise2", "c3vFbm2", "c3vFresnel"):
+ assert fn in lib
+
+
+def test_singleshot_example_parses_with_harness_parser() -> None:
+ gen = pytest.importorskip("codeverse.tracks.generation")
+ text = read_prompt("system/singleshot_format.md")
+ example = blocks("system/singleshot_format.md", "text")[-1]
+ files = gen.parse_multifile(example)
+ assert set(files) == {"src/parts/seat.js", "src/object.js"}
+ assert "buildSeat" in files["src/parts/seat.js"]
+ assert "=== FILE" not in "".join(files.values())
+ assert "SINGLE_SHOT_FORMAT" in dir(gen)
+ # the format doc and the parser must agree on the markers
+ assert "=== FILE: " in text and "=== END FILE ===" in text
diff --git a/harness/tests/scene_runtime/__init__.py b/harness/tests/scene_runtime/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/scene_runtime/conftest.py b/harness/tests/scene_runtime/conftest.py
new file mode 100644
index 00000000..5540e802
--- /dev/null
+++ b/harness/tests/scene_runtime/conftest.py
@@ -0,0 +1,51 @@
+"""Fixtures for the scene runtime tests (C2)."""
+
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from codeverse.config import get_settings
+from codeverse.languages.scene_threejs.skeleton import write_example
+from codeverse.workspace import Workspace
+
+RUNTIME_JS = get_settings().runtime_js_dir()
+
+
+def node_available() -> bool:
+ return shutil.which(get_settings().binaries.node or "node") is not None and (RUNTIME_JS / "node_modules" / "three").is_dir()
+
+
+def browser_available() -> bool:
+ return node_available() and (RUNTIME_JS / "node_modules" / "puppeteer").is_dir()
+
+
+needs_node = pytest.mark.skipif(not node_available(), reason="node + runtime_js/node_modules required")
+needs_browser = pytest.mark.skipif(not browser_available(), reason="puppeteer/chrome required")
+
+
+def ws(tmp_path: Path) -> Workspace:
+ """Empty workspace."""
+ return Workspace(tmp_path / "run").create()
+
+
+def starter_ws(tmp_path: Path) -> Workspace:
+ """Workspace with the complete example scene."""
+ w = Workspace(tmp_path / "run").create()
+ write_example(w)
+ return w
+
+
+def run_node_json(script_body: str, *, cwd: Path = RUNTIME_JS, timeout: int = 60) -> dict | list:
+ """Run an inline ESM snippet under runtime_js and parse its last stdout line as JSON."""
+ proc = subprocess.run(
+ ["node", "--input-type=module", "-e", script_body], cwd=str(cwd), capture_output=True, text=True, timeout=timeout,
+ )
+ assert proc.returncode == 0, proc.stderr
+ return json.loads(proc.stdout.strip().splitlines()[-1])
diff --git a/harness/tests/scene_runtime/test_assemble.py b/harness/tests/scene_runtime/test_assemble.py
new file mode 100644
index 00000000..e6d1a42b
--- /dev/null
+++ b/harness/tests/scene_runtime/test_assemble.py
@@ -0,0 +1,102 @@
+"""Deterministic assembler: pure parts + browser-probed assembly."""
+
+from __future__ import annotations
+
+import math
+
+import pytest
+
+from codeverse.contracts.plan import CameraPlan
+from codeverse.languages.scene_threejs.assemble import (
+ ZoneProbe,
+ assemble,
+ derive_cameras,
+ fit_zone_camera,
+ probe_zone_modules,
+ render_scene_js,
+ sun_azimuth,
+)
+from codeverse.languages.scene_threejs.lint import lint
+from tests.scene_runtime.conftest import needs_browser, needs_node
+
+BOX_A = {"min": [-10, 0, -10], "max": [10, 6, 10], "size": [20, 6, 20]}
+BOX_B = {"min": [20, 0, -5], "max": [30, 3, 5], "size": [10, 3, 10]}
+
+
+def test_derive_cameras_sun_side_and_order():
+ probes = {
+ "harbour": ZoneProbe(name="harbour", file="src/zones/harbour.js", ok=True, bbox=BOX_A),
+ "market": ZoneProbe(name="market", file="src/zones/market.js", ok=True, bbox=BOX_B),
+ "broken": ZoneProbe(name="broken", file="src/zones/broken.js", ok=False, error="boom"),
+ }
+ cams = derive_cameras(probes, sun_azimuth_deg=90, ground_y=0.0)
+ assert [c.name for c in cams] == ["overview", "harbour_view", "market_view"]
+ ov = cams[0]
+ # sun at azimuth 90 → eye on +X side of the union centre, above ground, looking at the centre
+ assert ov.position[0] > ov.look_at[0] and ov.position[1] > 0.5
+ hv = cams[1]
+ assert hv.position[0] > 10 and 1.5 < hv.position[1] < 4.5 and abs(hv.position[2]) < 1e-6
+ assert math.dist(hv.position, hv.look_at) > 10
+
+
+def test_derive_cameras_fallback_without_zones():
+ cams = derive_cameras({}, sun_azimuth_deg=45)
+ assert len(cams) == 1 and cams[0].name == "overview"
+
+
+def test_fit_zone_camera_respects_floor():
+ c = fit_zone_camera("pier", BOX_B, azimuth=0, floor=2.0)
+ assert c.position[1] >= 3.7
+ assert c.name == "pier_view"
+
+
+def test_render_scene_js_contents():
+ cams = [CameraPlan(name="overview", position=(1, 2, 3), look_at=(0, 0, 0), fov=50)]
+ src = render_scene_js(["harbour", "fish_market"], cams, ["crane"], env_ok=True)
+ assert "import { build as buildHarbour } from './zones/harbour.js';" in src
+ assert "addZone(buildFishMarket, 'FishMarket');" in src
+ assert "crane: '/assets/crane.glb'" in src
+ assert "name: 'overview', position: [1, 2, 3]" in src
+ assert "import { buildEnv, heightAt } from './env.js';" in src
+ src2 = render_scene_js([], cams, [], env_ok=False)
+ assert "env.js" not in src2 and "heightAt: () => 0" in src2
+
+
+def test_sun_azimuth_reads_env(starter_ws):
+ assert sun_azimuth(starter_ws) == 60.0
+
+
+@needs_node
+def test_assemble_without_probe_writes_all_zones(starter_ws):
+ res = assemble(starter_ws, probe=False)
+ assert set(res.zones_included) == {"meadow", "pondside"}
+ assert (starter_ws.src / "scene.js").read_text().startswith("// src/scene.js — ASSEMBLED")
+ assert lint(starter_ws).passed
+ assert (starter_ws.artifacts / "assemble.json").is_file()
+
+
+@needs_browser
+def test_probe_zone_modules_reports_failures_and_bboxes(starter_ws):
+ (starter_ws.src / "zones" / "broken.js").write_text("export function build(ctx) { throw new Error('kaboom'); }\n")
+ (starter_ws.src / "zones" / "nobuild.js").write_text("export const x = 1;\n")
+ probes, census, other = probe_zone_modules(starter_ws)
+ assert probes["meadow"].ok and probes["meadow"].bbox and probes["meadow"].meshes > 5
+ assert probes["pondside"].ok
+ assert not probes["broken"].ok and "kaboom" in probes["broken"].error
+ assert not probes["nobuild"].ok and "no export build" in probes["nobuild"].error
+ assert census.get("ground_y") is not None
+ assert not (starter_ws.root / "src" / "_c3v_assemble_probe.js").exists()
+
+
+@needs_browser
+def test_assemble_end_to_end_excludes_broken_zone(starter_ws):
+ (starter_ws.src / "zones" / "broken.js").write_text("export function build(ctx) { throw new Error('kaboom'); }\n")
+ res = assemble(starter_ws)
+ assert set(res.zones_included) == {"meadow", "pondside"}
+ assert "broken" in res.zones_failed
+ assert res.cameras[0].name == "overview" and len(res.cameras) == 3
+ src = (starter_ws.src / "scene.js").read_text()
+ assert "broken" not in src
+ assert lint(starter_ws).passed
diff --git a/harness/tests/scene_runtime/test_glsl_audit.py b/harness/tests/scene_runtime/test_glsl_audit.py
new file mode 100644
index 00000000..416c0f39
--- /dev/null
+++ b/harness/tests/scene_runtime/test_glsl_audit.py
@@ -0,0 +1,110 @@
+"""Static GLSL audits + source-line mapping (node-side pure functions)."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from tests.scene_runtime.conftest import needs_node, run_node_json
+
+pytestmark = [pytest.mark.node, needs_node]
+
+
+def audit(source: str, **opts) -> list[dict]:
+ body = f"""
+import {{ auditFile }} from './lib/glsl_audit.mjs';
+const src = {json.dumps(source)};
+console.log(JSON.stringify(auditFile('src/shaders/x.js', src, {json.dumps(opts)})));
+"""
+ return run_node_json(body)
+
+
+def kinds(findings: list[dict]) -> set[str]:
+ return {f["kind"] for f in findings}
+
+
+def test_clean_shader_has_no_findings():
+ src = """
+const frag = `
+uniform float uTime;
+varying vec2 vUv;
+void main() {
+ gl_FragColor = vec4(vUv, sin(uTime), 1.0);
+}`;
+export const mat = { uniforms: { uTime: { value: 0 } }, fragmentShader: frag };
+"""
+ assert audit(src) == []
+
+
+def test_include_not_alone_and_version_and_precision():
+ src = """const vs = `
+#version 300 es
+precision highp float;
+#include <common> uniform float uTime;
+void main() { gl_Position = vec4(position, 1.0); }`;
+const u = { uTime: { value: 0 } };"""
+ f = audit(src)
+ k = kinds(f)
+ assert {"include_not_alone", "version_directive", "precision_directive"} <= k
+ inc = next(x for x in f if x["kind"] == "include_not_alone")
+ assert inc["line"] == 4 # line 1 is `const vs = \``, the include is on file line 4
+ assert inc["severity"] == "error"
+ assert next(x for x in f if x["kind"] == "version_directive")["severity"] == "error"
+
+
+def test_fragment_out_plus_gl_fragcolor_and_glsl3():
+ src = """import * as THREE from 'three';
+const frag = `
+out vec4 fragColor;
+void main() { gl_FragColor = vec4(1.0); }`;
+new THREE.ShaderMaterial({ glslVersion: THREE.GLSL3, fragmentShader: frag });"""
+ k = kinds(audit(src))
+ assert "fragment_out_and_gl_fragcolor" in k
+ assert "glsl3_gl_fragcolor" in k
+
+
+def test_utime_undeclared_and_unbound():
+ src = """const frag = `
+void main() { gl_FragColor = vec4(sin(uTime)); }`;"""
+ f = audit(src)
+ assert {"undeclared_uniform", "unbound_uniform"} <= kinds(f)
+ # declared + bound → clean
+ src2 = """const frag = `
+uniform float uTime;
+void main() { gl_FragColor = vec4(sin(uTime)); }`;
+mat.uniforms.uTime = { value: 0 };"""
+ assert kinds(audit(src2)) == set()
+
+
+def test_chunk_dropped_warning_only_when_include_missing():
+ good = """m.onBeforeCompile = (s) => { s.fragmentShader = s.fragmentShader.replace('#include <output_fragment>', `#include <output_fragment>
+gl_FragColor.rgb += vec3(0.1);`); };"""
+ bad = """m.onBeforeCompile = (s) => { s.vertexShader = s.vertexShader.replace('#include <begin_vertex>', `vec3 transformed = position * 2.0;`); };"""
+ assert kinds(audit(good)) == set()
+ f = audit(bad)
+ assert kinds(f) == {"chunk_dropped"}
+ assert f[0]["severity"] == "warn"
+
+
+def test_no_fog_warning_respects_scene_fog_and_opt_out():
+ src = """import * as THREE from 'three';
+const frag = `
+void main() { gl_FragColor = vec4(1.0); }`;
+export const m = new THREE.ShaderMaterial({ fragmentShader: frag });"""
+ assert "no_fog" not in kinds(audit(src, sceneUsesFog=False))
+ assert "no_fog" in kinds(audit(src, sceneUsesFog=True))
+ assert "no_fog" not in kinds(audit(src + "\n// c3v: no-fog", sceneUsesFog=True))
+
+
+def test_locate_source_line_maps_to_file_and_line():
+ files = [
+ {"file": "src/shaders/a.js", "text": "const f = `\nvoid main() {\n float x = undefinedThing;\n}`;"},
+ {"file": "src/shaders/b.js", "text": "const g = `\nvoid main() { gl_FragColor = vec4(1.0); }`;"},
+ ]
+ body = f"""
+import {{ locateSourceLine }} from './lib/glsl_audit.mjs';
+console.log(JSON.stringify(locateSourceLine({json.dumps(files)}, 'float x = undefinedThing;')));
+"""
+ loc = run_node_json(body)
+ assert loc == {"file": "src/shaders/a.js", "line": 3, "candidates": 1}
diff --git a/harness/tests/scene_runtime/test_lint.py b/harness/tests/scene_runtime/test_lint.py
new file mode 100644
index 00000000..fd131be3
--- /dev/null
+++ b/harness/tests/scene_runtime/test_lint.py
@@ -0,0 +1,86 @@
+"""Static lint for scene_threejs workspaces."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.languages.scene_threejs.lint import lint
+from tests.scene_runtime.conftest import needs_node
+
+pytestmark = [pytest.mark.node, needs_node]
+
+
+def _msgs(report, sev=None):
+ return [(f.target, f.message) for f in report.findings if sev is None or f.severity == sev]
+
+
+def test_example_scene_lints_clean(starter_ws):
+ rep = lint(starter_ws)
+ assert rep.gate == "lint:scene_threejs"
+ assert rep.passed, _msgs(rep)
+ assert not [f for f in rep.findings if f.severity == Severity.ERROR]
+
+
+def test_missing_scene_js_is_an_error(ws):
+ rep = lint(ws)
+ assert not rep.passed
+ assert any("src/scene.js is missing" in m for _, m in _msgs(rep, Severity.ERROR))
+
+
+def test_forbidden_imports_and_globals(ws):
+ (ws.src / "scene.js").write_text(
+ "import * as THREE from 'three';\n"
+ "import gsap from 'gsap';\n"
+ "import { x } from 'https://unpkg.com/foo@1/foo.js';\n"
+ "import { y } from './missing.js';\n"
+ "export function createScene() {\n"
+ " requestAnimationFrame(() => {});\n"
+ " const r = new THREE.WebGLRenderer();\n"
+ " document.body.appendChild(r.domElement);\n"
+ " const g = new THREE.BoxBufferGeometry(1, 1, 1);\n"
+ " return { scene: new THREE.Scene(), cameras: [], update() {} };\n"
+ "}\n"
+ )
+ rep = lint(ws)
+ errs = _msgs(rep, Severity.ERROR)
+ text = " | ".join(m for _, m in errs)
+ assert "import 'gsap' is not allowed" in text
+ assert "https://unpkg.com" in text or "not allowed" in text
+ assert "missing file './missing.js'" in text
+ assert "requestAnimationFrame" in text
+ assert "creating a renderer" in text
+ assert "DOM/page access" in text
+ assert "BufferGeometry aliases" in text
+ # targets carry file:line
+ assert any(t and t.startswith("src/scene.js:") for t, _ in errs)
+
+
+def test_syntax_error_maps_to_line(ws):
+ (ws.src / "scene.js").write_text("import * as THREE from 'three';\nexport function createScene() {\n const = 3;\n}\n")
+ rep = lint(ws)
+ f = next(f for f in rep.findings if f.message.startswith("syntax"))
+ assert f.target == "src/scene.js:3"
+
+
+def test_zone_without_build_and_asset_without_factory(ws):
+ (ws.src / "scene.js").write_text("export function createScene() { return {}; }\n")
+ (ws.src / "zones").mkdir()
+ (ws.src / "zones" / "dock.js").write_text("export function make() {}\n")
+ (ws.src / "assets").mkdir()
+ (ws.src / "assets" / "crate.js").write_text("export function crate() {}\n")
+ rep = lint(ws)
+ assert any("zone module does not export build" in m for _, m in _msgs(rep, Severity.ERROR))
+ assert any("asset module exports no build" in m for _, m in _msgs(rep, Severity.WARN))
+
+
+def test_missing_create_scene_export(ws):
+ (ws.src / "scene.js").write_text("import * as THREE from 'three';\nexport function makeScene() {}\n")
+ rep = lint(ws)
+ assert any("does not export createScene" in m for _, m in _msgs(rep, Severity.ERROR))
+
+
+def test_large_file_warning(ws):
+ (ws.src / "scene.js").write_text("export function createScene() { return {}; }\n" + "// pad\n" * 900)
+ rep = lint(ws)
+ assert any("large file" in m for _, m in _msgs(rep, Severity.WARN))
diff --git a/harness/tests/scene_runtime/test_orbit.py b/harness/tests/scene_runtime/test_orbit.py
new file mode 100644
index 00000000..09e72098
--- /dev/null
+++ b/harness/tests/scene_runtime/test_orbit.py
@@ -0,0 +1,61 @@
+"""Orbit rig fitting (pure node function)."""
+
+from __future__ import annotations
+
+import json
+import math
+
+import pytest
+
+from tests.scene_runtime.conftest import needs_node, run_node_json
+
+pytestmark = [pytest.mark.node, needs_node]
+
+BBOX = {"min": [-40, -1, -40], "max": [40, 9, 40], "size": [80, 10, 80]}
+VIEWS = [
+ {"name": "overview_front_right", "azimuth": 40, "elevation": 32},
+ {"name": "overview_top", "azimuth": 0, "elevation": 87},
+ {"name": "eye_front", "azimuth": 0, "elevation": 10},
+]
+
+
+def fit(bbox=BBOX, views=VIEWS, **opts):
+ body = f"""
+import {{ fitOrbitCameras, orbitDirection }} from './lib/orbit.mjs';
+console.log(JSON.stringify(fitOrbitCameras({json.dumps(bbox)}, {json.dumps(views)}, {json.dumps(opts)})));
+"""
+ return run_node_json(body)
+
+
+def test_direction_convention_front_is_plus_z_and_ccw():
+ body = """
+import { orbitDirection } from './lib/orbit.mjs';
+console.log(JSON.stringify([orbitDirection(0, 0), orbitDirection(90, 0)]));
+"""
+ front, right = run_node_json(body)
+ assert front[2] == pytest.approx(1.0) and abs(front[0]) < 1e-9
+ assert right[0] == pytest.approx(1.0) and abs(right[2]) < 1e-9
+
+
+def test_orbit_cameras_are_above_ground_and_fitted():
+ cams = fit(groundY=0.0)
+ by = {c["name"]: c for c in cams}
+ assert set(by) == {"overview_front_right", "overview_top", "eye_front"}
+ for c in cams:
+ assert c["position"][1] > 0.5, c
+ assert c["kind"] == "orbit"
+ ov = by["overview_front_right"]
+ dist = math.dist(ov["position"], ov["lookAt"])
+ assert 80 < dist < 200
+ assert ov["noFog"] is True
+ eye = by["eye_front"]
+ # eye-level: stands just outside the footprint (z > 40), ~1.6-3 m high, fog kept
+ assert 40 < eye["position"][2] < 60
+ assert 1.5 < eye["position"][1] < 4
+ assert eye["noFog"] is False
+ top = by["overview_top"]
+ assert top["position"][1] > 100
+
+
+def test_empty_bbox_returns_no_cameras():
+ assert fit(None) == []
diff --git a/harness/tests/scene_runtime/test_probes.py b/harness/tests/scene_runtime/test_probes.py
new file mode 100644
index 00000000..3fd8a083
--- /dev/null
+++ b/harness/tests/scene_runtime/test_probes.py
@@ -0,0 +1,134 @@
+"""Browser-backed probes: scene probe, shader preflight, shader presence."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.spatial.probes import check_shaders, probe_scene, shader_presence
+from tests.scene_runtime.conftest import needs_browser
+
+pytestmark = [pytest.mark.node, needs_browser]
+
+
+def test_probe_scene_passes_on_example(starter_ws):
+ res = probe_scene(starter_ws)
+ gate, census = res
+ assert gate.gate == "scene_probe" and gate.passed, [(f.target, f.message) for f in gate.findings]
+ assert res.ok and res.errors == []
+ assert census["totals"]["meshes"] > 10 and census["totals"]["lights"] == 3
+ assert {g["name"] for g in census["groups"]} == {"Environment", "Meadow", "Pondside"}
+ assert census["content_bbox"]["size"][0] > 50
+ assert (starter_ws.artifacts / "census.json").is_file()
+ assert gate.duration_ms < 15000
+
+
+def test_probe_scene_reports_import_error_with_stage(starter_ws):
+ (starter_ws.src / "scene.js").write_text("import * as THREE from 'three';\nimport { nope } from './does_not_exist.js';\nexport function createScene() {}\n")
+ gate, census = probe_scene(starter_ws)
+ assert not gate.passed
+ err = gate.errors[0]
+ assert err.data.get("stage") == "import" and err.target == "src/scene.js"
+ assert "fix the syntax/import error" in err.fix_hint
+
+
+def test_probe_scene_flags_bad_shape_and_cameras(starter_ws):
+ (starter_ws.src / "scene.js").write_text(
+ "import * as THREE from 'three';\n"
+ "export function createScene() { const scene = new THREE.Scene(); scene.add(new THREE.Mesh(new THREE.BoxGeometry(1,1,1), new THREE.MeshBasicMaterial()));\n"
+ " return { scene, cameras: [{ name: 'x', position: [1, 1], lookAt: [0, 0, 0] }], update(t) { if (t > 0.1) throw new Error('update boom'); } }; }\n"
+ )
+ gate, census = probe_scene(starter_ws)
+ msgs = " | ".join(f.message for f in gate.findings)
+ assert not gate.passed
+ assert "position must be [x,y,z]" in msgs and "no valid cameras" in msgs
+ assert census == {} or census.get("totals", {}).get("meshes") == 1 # census only when booted; boot fails on cameras here
+
+
+def test_probe_scene_catches_update_throw_and_console_errors(starter_ws):
+ (starter_ws.src / "scene.js").write_text(
+ "import * as THREE from 'three';\n"
+ "export function createScene() { const scene = new THREE.Scene(); scene.add(new THREE.AmbientLight()); scene.add(new THREE.Mesh(new THREE.BoxGeometry(1,1,1), new THREE.MeshBasicMaterial()));\n"
+ " console.error('custom failure 42');\n"
+ " return { scene, cameras: [{ name: 'x', position: [3, 3, 3], lookAt: [0, 0, 0], fov: 50 }], update(t) { if (t > 0.1) throw new Error('update boom'); } }; }\n"
+ )
+ gate, _ = probe_scene(starter_ws)
+ msgs = " | ".join(f.message for f in gate.errors)
+ assert "update boom" in msgs and "custom failure 42" in msgs
+
+
+def test_check_shaders_clean_on_example(starter_ws):
+ rep = check_shaders(starter_ws)
+ assert rep.gate == "shader_preflight" and rep.passed, [(f.target, f.message) for f in rep.findings]
+ info = [f for f in rep.findings if f.severity == Severity.INFO]
+ assert info and info[0].data.get("programs", 0) >= 3
+
+
+def test_check_shaders_maps_compile_error_to_file_line(starter_ws):
+ p = starter_ws.src / "shaders" / "water.js"
+ text = p.read_text()
+ needle = "float fres = pow(1.0 - max(dot(N, V), 0.0), 3.0);"
+ assert needle in text
+ text = text.replace(needle, "float fres = pow(1.0 - max(dot(N, V), 0.0), 3.0) * undefinedThing;")
+ p.write_text(text)
+ line = next(i for i, ln in enumerate(text.splitlines(), 1) if "undefinedThing" in ln)
+ rep = check_shaders(starter_ws)
+ assert not rep.passed
+ err = rep.errors[0]
+ assert err.target == f"src/shaders/water.js:{line}", err
+ assert "undeclared identifier" in err.message and "undefinedThing" in err.message
+ assert err.data.get("material") and "PondWater" in err.data["material"]
+ assert err.fix_hint
+
+
+def test_check_shaders_on_before_compile_patch_error(starter_ws):
+ (starter_ws.src / "shaders" / "glow.js").write_text(
+ "import * as THREE from 'three';\n"
+ "export function makeGlow(T = THREE) {\n"
+ " const m = new T.MeshStandardMaterial({ color: 0xff8800 });\n"
+ " m.onBeforeCompile = (shader) => {\n"
+ " shader.fragmentShader = shader.fragmentShader.replace('#include <dithering_fragment>', `#include <dithering_fragment>\n"
+ " gl_FragColor.rgb += vec3(0.2) * missingUniform;`);\n"
+ " };\n"
+ " return m;\n"
+ "}\n"
+ )
+ p = starter_ws.src / "zones" / "meadow.js"
+ text = p.read_text().replace(
+ "import { buildWindmill } from '../assets/windmill.js';",
+ "import { buildWindmill } from '../assets/windmill.js';\nimport { makeGlow } from '../shaders/glow.js';",
+ ).replace(
+ "const rock = new THREE.MeshStandardMaterial({ color: 0x7b7b78, roughness: 0.95 });",
+ "const rock = makeGlow(THREE);",
+ )
+ assert "makeGlow(THREE)" in text
+ p.write_text(text)
+ rep = check_shaders(starter_ws)
+ assert not rep.passed
+ err = rep.errors[0]
+ assert err.target == "src/shaders/glow.js:6", err
+ assert "missingUniform" in err.message
+
+
+def test_check_shaders_static_audit_without_compile(starter_ws):
+ (starter_ws.src / "shaders" / "bad.js").write_text(
+ "export const frag = `\n#version 300 es\nvoid main() { gl_FragColor = vec4(uTime); }`;\n"
+ )
+ rep = check_shaders(starter_ws)
+ kinds = {f.data.get("kind") for f in rep.errors}
+ assert {"version_directive", "undeclared_uniform", "unbound_uniform"} <= kinds
+ assert any(f.target == "src/shaders/bad.js:2" for f in rep.errors)
+
+
+def test_shader_presence_on_example_and_when_hidden(starter_ws):
+ obs = shader_presence(starter_ws)
+ assert obs.ok and obs.numbers["custom_materials"] == 2
+ assert obs.numbers["max_diff_frac"] > 0.05 and "PRESENT" in obs.text
+ assert len(obs.images) >= 2
+ # hide the custom-shader meshes → stripping changes nothing
+ p = starter_ws.src / "zones" / "pondside.js"
+ p.write_text(p.read_text().replace(" water.name = 'PondWater';", " water.name = 'PondWater';\n water.visible = false;"))
+ e = starter_ws.src / "env.js"
+ e.write_text(e.read_text().replace(" sky.name = 'Sky';", " sky.name = 'Sky';\n sky.visible = false;"))
+ obs2 = shader_presence(starter_ws)
+ assert obs2.numbers["max_diff_frac"] == 0.0 and "NOT VISIBLE" in obs2.text
diff --git a/harness/tests/scene_runtime/test_render_scene.py b/harness/tests/scene_runtime/test_render_scene.py
new file mode 100644
index 00000000..b6805ec6
--- /dev/null
+++ b/harness/tests/scene_runtime/test_render_scene.py
@@ -0,0 +1,129 @@
+"""render_scene: offline parsing with a fake node driver + real browser render."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from codeverse.contracts.plan import CameraPlan
+from codeverse.conventions import SCENE_VIEWS
+from codeverse.spatial import render_scene as rs_mod
+from codeverse.spatial.render_scene import (
+ SceneRenderError,
+ read_metrics,
+ render_scene,
+ run_scene_script,
+)
+from tests.scene_runtime.conftest import needs_browser, needs_node
+
+FAKE_DRIVER = r"""
+import fs from 'node:fs';
+import path from 'node:path';
+const a = process.argv.slice(2);
+const get = (k) => { const i = a.indexOf(k); return i >= 0 ? a[i + 1] : undefined; };
+const out = get('--out');
+fs.mkdirSync(out, { recursive: true });
+const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64');
+const cams = get('--cameras');
+const names = cams === 'authored' ? ['authored_a'] : JSON.parse(cams).map((c) => c.name);
+if (get('--orbit-views') !== 'none') for (const v of JSON.parse(get('--orbit-views'))) names.push(v.name);
+const times = get('--times').split(',').map(Number);
+const views = [];
+for (const t of times) for (const n of names) {
+ const file = `${n}_t${t}.png`;
+ fs.writeFileSync(path.join(out, file), png);
+ views.push({ name: n, kind: 'authored', path: file, time_s: t, position: [1, 2, 3], lookAt: [0, 0, 0], fov: 50 });
+}
+const metrics = { ok: true, renderer: 'FakeGL', gpu: false, views, console_errors: ['oops'], shader_errors: [{stage: 'fragment', message: 'bad', source_line: 'x = y;'}], fps: { fps: 42.5 }, census: { totals: { meshes: 1 } }, camera_checks: [] };
+fs.writeFileSync(path.join(out, 'metrics.json'), JSON.stringify(metrics));
+console.log('noise line');
+console.log(JSON.stringify({ ok: true, n_views: views.length, renderer: 'FakeGL' }));
+"""
+
+
+def fake_runtime(tmp_path, monkeypatch):
+ rt = tmp_path / "runtime_js"
+ rt.mkdir()
+ (rt / "render_scene.mjs").write_text(FAKE_DRIVER)
+ (rt / "crash.mjs").write_text("console.log(JSON.stringify({ok:false,error:'driver exploded'})); process.exit(2);")
+ (rt / "slow.mjs").write_text("setTimeout(() => {}, 60000);")
+ monkeypatch.setattr(rs_mod, "runtime_js_dir", lambda: rt)
+ # C1's run_node resolves the script path we pass, but sets NODE_PATH from settings; fine for a fake
+ return rt
+
+
+@needs_node
+def test_render_scene_parses_driver_output(fake_runtime, ws, tmp_path):
+ out = tmp_path / "out"
+ cams = [CameraPlan(name="cam_a", position=(1, 2, 3), look_at=(0, 0, 0), fov=45)]
+ rs = render_scene(ws, out, cameras=cams, orbit=True, times=(0.0, 1.5), orbit_views=SCENE_VIEWS[:2], sheet=True)
+ assert len(rs.views) == 2 * 3
+ assert {v.name for v in rs.views} == {"cam_a", SCENE_VIEWS[0].name, SCENE_VIEWS[1].name}
+ assert rs.views[0].time_s == 0.0 and rs.views[-1].time_s == 1.5
+ assert rs.views[0].camera_position == (1.0, 2.0, 3.0) and rs.views[0].fov == 50
+ assert rs.fps == 42.5 and rs.renderer == "FakeGL"
+ assert rs.console_errors[0] == "oops" and rs.console_errors[1].startswith("shader[fragment]")
+ assert rs.contact_sheet and Path(rs.contact_sheet).is_file()
+ assert Image.open(rs.contact_sheet).size[0] > 100
+ assert read_metrics(out)["census"]["totals"]["meshes"] == 1
+
+
+@needs_node
+def test_driver_crash_raises(fake_runtime):
+ with pytest.raises(SceneRenderError, match="driver exploded"):
+ run_scene_script("crash.mjs", [], timeout_s=30)
+
+
+@needs_node
+def test_driver_timeout_raises(fake_runtime):
+ with pytest.raises(SceneRenderError, match="timed out"):
+ run_scene_script("slow.mjs", [], timeout_s=1)
+
+
+def test_missing_driver_raises(fake_runtime):
+ with pytest.raises(SceneRenderError, match="missing node driver"):
+ run_scene_script("nope.mjs", [], timeout_s=5)
+
+
+@needs_browser
+def test_real_render_of_example_scene(starter_ws):
+ out = starter_ws.renders_dir(0)
+ rs = render_scene(starter_ws, out, times=(0.0, 1.5), width=640, height=360, fps_seconds=0.5)
+ assert rs.console_errors == []
+ names = {v.name for v in rs.views}
+ assert {"overview", "pond_low", "windmill"} <= names
+ assert {v.name for v in SCENE_VIEWS} <= names
+ assert len(rs.views) == 2 * (3 + len(SCENE_VIEWS))
+ assert rs.fps and rs.fps > 5
+ assert rs.renderer
+ im = Image.open(rs.views[0].path)
+ assert im.size == (640, 360)
+ # not black, not blown: a lit scene
+ px = list(im.convert("L").resize((32, 18)).getdata())
+ assert 20 < sum(px) / len(px) < 235
+ assert rs.contact_sheet and Path(rs.contact_sheet).is_file()
+ m = read_metrics(out)
+ assert m["census"]["totals"]["triangles"] > 1000
+ checks = {c["name"]: c for c in m["camera_checks"]}
+ assert not checks["overview"]["camera_in_geometry"]
+ assert checks["overview"]["dark_frac"] < 0.2 and checks["overview"]["blown_frac"] < 0.2
+ # animation actually changes the frame between t=0 and t=1.5
+ a = Image.open(next(v.path for v in rs.views if v.name == "windmill" and v.time_s == 0.0)).convert("L")
+ b = Image.open(next(v.path for v in rs.views if v.name == "windmill" and v.time_s == 1.5)).convert("L")
+ diff = sum(1 for x, y in zip(a.getdata(), b.getdata(), strict=True) if abs(x - y) > 12)
+ assert diff > 100
+
+
+@needs_browser
+def test_camera_in_geometry_is_detected(starter_ws):
+ cams = [CameraPlan(name="buried", position=(12.0, 2.0, -2.0), look_at=(12.0, 2.0, -10.0), fov=50)] # inside the windmill tower
+ out = starter_ws.renders_dir(1)
+ render_scene(starter_ws, out, cameras=cams, orbit=False, times=(0.0,), fps_seconds=0, sheet=False)
+ m = read_metrics(out)
+ chk = m["camera_checks"][0]
+ assert chk["camera_in_geometry"] is True
diff --git a/harness/tests/scene_runtime/test_runtime.py b/harness/tests/scene_runtime/test_runtime.py
new file mode 100644
index 00000000..0a492566
--- /dev/null
+++ b/harness/tests/scene_runtime/test_runtime.py
@@ -0,0 +1,67 @@
+"""SceneThreeJsRuntime: protocol conformance + build gate."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from codeverse.contracts.common import Language
+from codeverse.languages import get_runtime
+from codeverse.languages.base import LanguageRuntime
+from codeverse.languages.scene_threejs.runtime import SceneThreeJsRuntime
+from tests.scene_runtime.conftest import needs_browser
+
+
+def test_runtime_registered_and_conforms():
+ rt = get_runtime(Language.SCENE_THREEJS)
+ assert isinstance(rt, SceneThreeJsRuntime)
+ assert isinstance(rt, LanguageRuntime)
+ assert rt.language == Language.SCENE_THREEJS
+ assert "src/scene.js" in rt.entry_globs and "src/zones/*.js" in rt.entry_globs
+ doc = rt.contract_doc()
+ assert "createScene" in doc and "update(t, dt)" in doc
+ # the built-in fallback contract is always available and carries the GLSL rules
+ from codeverse.languages.scene_threejs import runtime as rt_mod
+ fallback = (rt_mod._HERE / "CONTRACT.md").read_text()
+ assert "createScene" in fallback and "#include" in fallback
+ assert rt.cookbook_path().name == "cookbook.md"
+
+
+def test_skeleton_writes_example(ws):
+ rt = SceneThreeJsRuntime()
+ paths = rt.skeleton(ws, None)
+ assert (ws.src / "scene.js") in paths
+
+
+@needs_browser
+def test_build_ok_on_example(starter_ws):
+ rt = SceneThreeJsRuntime()
+ res = rt.build(starter_ws)
+ assert res.ok, res.stdout_tail
+ assert res.language == "scene_threejs" and res.glb_path is None
+ assert res.census["totals"]["meshes"] > 10
+ assert (starter_ws.artifacts / "build.json").is_file() and (starter_ws.artifacts / "census.json").is_file()
+ assert json.loads((starter_ws.artifacts / "gates" / "shader_preflight.json").read_text())["passed"]
+
+
+@needs_browser
+def test_build_fails_with_file_line_on_shader_error(starter_ws):
+ p = starter_ws.src / "shaders" / "sky.js"
+ text = p.read_text().replace("float h = clamp(vWorldDir.y, -0.2, 1.0);", "float h = clamp(vWorldDir.y, -0.2, 1.0) + nope;")
+ p.write_text(text)
+ res = SceneThreeJsRuntime().build(starter_ws)
+ assert not res.ok
+ assert res.error_file == "src/shaders/sky.js" and res.error_line
+ assert "nope" in res.error_message
+ assert "shader_preflight: FAILED" in res.stdout_tail
+
+
+@needs_browser
+def test_build_fails_on_import_error(starter_ws):
+ (starter_ws.src / "scene.js").write_text("import { x } from './nope.js';\nexport function createScene() {}\n")
+ res = SceneThreeJsRuntime().build(starter_ws)
+ assert not res.ok and res.error_file == "src/scene.js" and "nope.js" in res.error_message
diff --git a/harness/tests/scene_runtime/test_skeleton.py b/harness/tests/scene_runtime/test_skeleton.py
new file mode 100644
index 00000000..ffd9cf51
--- /dev/null
+++ b/harness/tests/scene_runtime/test_skeleton.py
@@ -0,0 +1,68 @@
+"""Skeleton / starter files."""
+
+from __future__ import annotations
+
+from codeverse.contracts.plan import AssetPlan, BBox, CameraPlan, ScenePlan, ZonePlan
+from codeverse.languages.scene_threejs.lint import lint
+from codeverse.languages.scene_threejs.skeleton import STARTER_DIR, write_example, write_skeleton
+from tests.scene_runtime.conftest import needs_node
+
+
+def make_plan() -> ScenePlan:
+ return ScenePlan(
+ title="Harbour at dusk", summary="a small fishing harbour", setting="coast, dusk, clear",
+ bounds=BBox(center=(0, 5, 0), extents=(80, 20, 60)),
+ environment="calm sea, low sun, light haze",
+ zones=[
+ ZonePlan(name="Pier", description="wooden pier with crates", bbox=BBox(center=(0, 1, 10), extents=(20, 4, 8)), contents=["Crate", "Crane"]),
+ ZonePlan(name="Fish Market", description="stalls", bbox=BBox(center=(-20, 1, -5), extents=(15, 4, 15)), contents=["Crate"]),
+ ],
+ assets=[
+ AssetPlan(name="Crate", kind="threejs", description="wooden crate", approx_size_m=(1, 1, 1), instances_hint=12),
+ AssetPlan(name="Crane", kind="blender_glb", description="dockside crane", approx_size_m=(4, 9, 4)),
+ ],
+ cameras=[CameraPlan(name="pier_low", position=(8, 2, 22), look_at=(0, 1, 10), fov=45, purpose="pier")],
+ )
+
+
+def test_example_files_exist_and_are_complete():
+ names = {p.relative_to(STARTER_DIR).as_posix() for p in STARTER_DIR.rglob("*.js")}
+ assert {"scene.js", "env.js", "zones/meadow.js", "zones/pondside.js", "assets/pine_tree.js", "assets/windmill.js", "shaders/water.js", "shaders/sky.js"} <= names
+ scene = (STARTER_DIR / "scene.js").read_text()
+ assert "export function createScene" in scene and "cameras" in scene and "update(t, dt)" in scene
+ assert "ShaderMaterial" in (STARTER_DIR / "shaders" / "water.js").read_text()
+ assert "InstancedMesh" in (STARTER_DIR / "zones" / "meadow.js").read_text()
+
+
+def test_write_example_copies_all(ws):
+ paths = write_example(ws)
+ assert len(paths) >= 8
+ assert (ws.src / "scene.js").is_file()
+
+
+@needs_node
+def test_plan_skeleton_writes_zone_and_asset_stubs_and_lints(ws):
+ plan = make_plan()
+ paths = write_skeleton(ws, plan)
+ rel = {p.relative_to(ws.src).as_posix() for p in paths}
+ assert {"scene.js", "env.js", "zones/pier.js", "zones/fish_market.js", "assets/crate.js", "shaders/water.js"} <= rel
+ assert "assets/crane.js" not in rel # blender_glb assets are loaded, not stubbed
+ scene = (ws.src / "scene.js").read_text()
+ assert "export async function createScene" in scene
+ assert "'/assets/crane.glb'" in scene
+ assert "buildPier(ctx)" in scene and "buildFishMarket(ctx)" in scene
+ assert "name: 'pier_low'" in scene
+ pier = (ws.src / "zones" / "pier.js").read_text()
+ assert "zone.name = 'Pier'" in pier and "buildCrate" in pier and "ctx.assets.crane" in pier
+ crate = (ws.src / "assets" / "crate.js").read_text()
+ assert "export function buildCrate" in crate
+ env = (ws.src / "env.js").read_text()
+ assert "GROUND_SIZE = 200" in env # 80 m span * 2.5
+ assert (ws.public / "assets").is_dir()
+ rep = lint(ws)
+ assert rep.passed, [(f.target, f.message) for f in rep.errors]
+
+
+def test_non_scene_plan_falls_back_to_example(ws):
+ paths = write_skeleton(ws, None)
+ assert (ws.src / "zones" / "meadow.js") in paths
diff --git a/harness/tests/spatial_tools/__init__.py b/harness/tests/spatial_tools/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/spatial_tools/conftest.py b/harness/tests/spatial_tools/conftest.py
new file mode 100644
index 00000000..db2d2579
--- /dev/null
+++ b/harness/tests/spatial_tools/conftest.py
@@ -0,0 +1,54 @@
+"""Fixtures for the spatial tools tests: synthetic GLBs built with trimesh."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import numpy as np
+import pytest
+import trimesh
+
+from codeverse.spatial.registry import ToolContext
+from codeverse.workspace import Workspace
+
+LEG_XZ = [(-0.15, -0.15), (0.15, -0.15), (-0.15, 0.15), (0.15, 0.15)]
+FLOAT_GAP_M = 0.005
+
+
+def build_stool(path: Path, *, floating_leg: int | None = 3, gap_m: float = FLOAT_GAP_M) -> Path:
+ """Seat box (0.4×0.04×0.4 at y 0.41..0.45) + 4 leg cylinders (r 0.02, h 0.41).
+
+ ``floating_leg`` is shortened by ``gap_m`` at both ends and shifted up by
+ ``gap_m``: it neither touches the ground nor the seat (gap to seat = gap_m).
+ """
+ sc = trimesh.Scene()
+ seat = trimesh.creation.box(extents=(0.4, 0.04, 0.4))
+ seat.apply_translation((0, 0.43, 0))
+ sc.add_geometry(seat, node_name="Seat", geom_name="Seat")
+ for i, (x, z) in enumerate(LEG_XZ):
+ h = 0.41 - 2 * gap_m if i == floating_leg else 0.41
+ leg = trimesh.creation.cylinder(radius=0.02, height=h, sections=24)
+ leg.apply_transform(trimesh.transformations.rotation_matrix(np.pi / 2, (1, 0, 0)))
+ leg.apply_translation((x, h / 2 + (gap_m if i == floating_leg else 0.0), z))
+ sc.add_geometry(leg, node_name=f"Leg_{i}", geom_name=f"Leg_{i}")
+ sc.export(str(path))
+ return path
+
+
+def stool_glb(tmp_path: Path) -> Path:
+ return build_stool(tmp_path / "stool.glb")
+
+
+def solid_stool_glb(tmp_path: Path) -> Path:
+ return build_stool(tmp_path / "stool_ok.glb", floating_leg=None)
+
+
+def stool_ctx(tmp_ws: Workspace, stool_glb: Path) -> ToolContext:
+ """Workspace with the floating-leg stool as artifacts/object.glb and a blender spec."""
+ (tmp_ws.artifacts / "object.glb").write_bytes(stool_glb.read_bytes())
+ tmp_ws.spec_path.write_text(json.dumps({"id": "t", "track": "static_object", "language": "blender", "prompt": "a stool"}))
+ return ToolContext(workspace=tmp_ws, language="blender", track="static_object")
diff --git a/harness/tests/spatial_tools/test_connectivity.py b/harness/tests/spatial_tools/test_connectivity.py
new file mode 100644
index 00000000..5a95dfb0
--- /dev/null
+++ b/harness/tests/spatial_tools/test_connectivity.py
@@ -0,0 +1,99 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import numpy as np
+import pytest
+import trimesh
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.spatial.connectivity import check_connectivity, pair_distance, penetration_depth
+from tests.spatial_tools.conftest import FLOAT_GAP_M
+
+
+def test_floating_leg_found_with_exact_gap(stool_glb: Path) -> None:
+ r = check_connectivity(stool_glb)
+ assert r.gate == "connectivity" and not r.passed
+ errs = r.errors
+ assert len(errs) == 1 and errs[0].target == "Leg_3"
+ d = errs[0].data
+ assert d["nearest"] == "Seat"
+ assert d["gap_m"] == pytest.approx(FLOAT_GAP_M, abs=1e-4)
+ assert np.allclose(d["gap_vector_m"], (0.0, FLOAT_GAP_M, 0.0), atol=1e-4)
+ assert "translate 'Leg_3' by (+0.0000, +0.0050, +0.0000)" in errs[0].fix_hint
+
+
+def test_solid_stool_passes(solid_stool_glb: Path) -> None:
+ r = check_connectivity(solid_stool_glb)
+ assert r.passed and not r.errors
+ assert any("connected" in f.message for f in r.findings)
+
+
+def test_penetration_is_flagged(tmp_path: Path) -> None:
+ sc = trimesh.Scene()
+ a = trimesh.creation.box(extents=(0.2, 0.2, 0.2))
+ a.apply_translation((0, 0.1, 0))
+ b = trimesh.creation.box(extents=(0.2, 0.2, 0.2))
+ b.apply_translation((0, 0.1 + 0.2 - 0.03, 0)) # 30 mm deep into A
+ sc.add_geometry(a, node_name="A", geom_name="A")
+ sc.add_geometry(b, node_name="B", geom_name="B")
+ p = tmp_path / "pen.glb"
+ sc.export(str(p))
+ r = check_connectivity(p)
+ pen = [f for f in r.findings if "interpenetrate" in f.message]
+ assert pen and pen[0].severity == Severity.ERROR
+ assert pen[0].data["depth_m"] == pytest.approx(0.03, abs=0.004)
+
+
+def test_hairline_overlap_is_fine(tmp_path: Path) -> None:
+ sc = trimesh.Scene()
+ a = trimesh.creation.box(extents=(0.2, 0.2, 0.2))
+ a.apply_translation((0, 0.1, 0))
+ b = trimesh.creation.box(extents=(0.1, 0.1, 0.1))
+ b.apply_translation((0, 0.2 + 0.05 - 0.001, 0)) # 1 mm weld overlap
+ sc.add_geometry(a, node_name="A", geom_name="A")
+ sc.add_geometry(b, node_name="B", geom_name="B")
+ p = tmp_path / "weld.glb"
+ sc.export(str(p))
+ r = check_connectivity(p)
+ assert r.passed
+ assert not [f for f in r.findings if "interpenetrate" in f.message]
+
+
+def test_tiny_island_warns(tmp_path: Path) -> None:
+ body = trimesh.creation.box(extents=(0.3, 0.3, 0.3))
+ body.apply_translation((0, 0.15, 0))
+ crumb = trimesh.creation.box(extents=(0.004, 0.004, 0.004))
+ crumb.apply_translation((0.5, 0.5, 0.5))
+ part = trimesh.util.concatenate([body, crumb])
+ sc = trimesh.Scene()
+ sc.add_geometry(part, node_name="Body", geom_name="Body")
+ p = tmp_path / "crumb.glb"
+ sc.export(str(p))
+ r = check_connectivity(p)
+ warns = [f for f in r.findings if f.severity == Severity.WARN]
+ assert warns and "tiny disconnected island" in warns[0].message
+
+
+def test_missing_glb_is_error(tmp_path: Path) -> None:
+ r = check_connectivity(tmp_path / "none.glb")
+ assert not r.passed and r.errors
+
+
+def test_pair_distance_sampled_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
+ import codeverse.spatial.connectivity as c
+
+ monkeypatch.setattr(c, "_fcl_available", lambda: False)
+ a = trimesh.creation.box(extents=(1, 1, 1))
+ b = trimesh.creation.box(extents=(1, 1, 1))
+ b.apply_translation((1.02, 0, 0))
+ pd = pair_distance("a", a, "b", b)
+ assert pd.distance == pytest.approx(0.02, abs=1e-6)
+ assert pd.gap_vector[0] == pytest.approx(0.02, abs=1e-6)
+
+
+def test_penetration_depth_zero_when_apart() -> None:
+ a = trimesh.creation.box(extents=(1, 1, 1))
+ b = trimesh.creation.box(extents=(1, 1, 1))
+ b.apply_translation((2, 0, 0))
+ assert penetration_depth(a, b) == (0.0, 0.0)
diff --git a/harness/tests/spatial_tools/test_contract.py b/harness/tests/spatial_tools/test_contract.py
new file mode 100644
index 00000000..2d24dec2
--- /dev/null
+++ b/harness/tests/spatial_tools/test_contract.py
@@ -0,0 +1,96 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.contracts.artifacts import Measurement, PartMeasure, Severity
+from codeverse.contracts.plan import BBox, CameraPlan, PartPlan, ScenePlan, StaticPlan, ZonePlan
+from codeverse.spatial.contract import check_contract, match_parts, plan_bbox_to_glb
+from codeverse.spatial.measure import measure_glb
+
+
+def _stool_plan(**overrides) -> StaticPlan:
+ """Blender-frame (Z-up) plan matching the synthetic stool."""
+ parts = [
+ PartPlan(name="Seat", role="seat", description="d", bbox=BBox(center=(0, 0, 0.43), extents=(0.4, 0.4, 0.04))),
+ PartPlan(name="Leg", role="leg", description="d", bbox=BBox(center=(0, 0, 0.205), extents=(0.04, 0.04, 0.41)), instances=4),
+ ]
+ data = dict(object_name="Stool", summary="s", overall_bbox=BBox(center=(0, 0, 0.225), extents=(0.4, 0.4, 0.45)), parts=parts)
+ data.update(overrides)
+ return StaticPlan(**data)
+
+
+def test_frame_conversion() -> None:
+ b = plan_bbox_to_glb(BBox(center=(1, 2, 3), extents=(4, 5, 6)), "blender")
+ assert b.center == (1, 3, -2) and b.extents == (4, 6, 5)
+ same = plan_bbox_to_glb(BBox(center=(1, 2, 3), extents=(4, 5, 6)), "threejs")
+ assert same.center == (1, 2, 3)
+
+
+def test_stool_matches_plan(solid_stool_glb: Path) -> None:
+ r = check_contract(measure_glb(solid_stool_glb), _stool_plan(), language="blender")
+ assert r.passed, [f.message for f in r.findings]
+ assert not [f for f in r.findings if f.severity == Severity.WARN]
+
+
+def test_missing_part_is_error(solid_stool_glb: Path) -> None:
+ plan = _stool_plan()
+ plan.parts.append(PartPlan(name="Backrest", role="back", description="d", bbox=BBox(center=(0, 0.18, 0.6), extents=(0.4, 0.03, 0.3))))
+ r = check_contract(measure_glb(solid_stool_glb), plan, language="blender")
+ assert not r.passed
+ miss = [f for f in r.errors if f.target == "Backrest"]
+ assert miss and "missing" in miss[0].message and "40.0×3.0×30.0" in miss[0].fix_hint
+
+
+def test_bbox_deviation_warn_then_error(solid_stool_glb: Path) -> None:
+ m = measure_glb(solid_stool_glb)
+ plan = _stool_plan()
+ plan.parts[0].bbox = BBox(center=(0, 0, 0.43), extents=(0.46, 0.4, 0.04)) # 6 cm wider than built (tol 4.6 cm)
+ r = check_contract(m, plan, language="blender")
+ seat = [f for f in r.findings if f.target == "Seat"]
+ assert seat and seat[0].severity == Severity.WARN and "x-6.0cm" in seat[0].fix_hint
+ plan.parts[0].bbox = BBox(center=(0, 0, 0.43), extents=(1.2, 0.4, 0.04))
+ r = check_contract(m, plan, language="blender")
+ seat = [f for f in r.findings if f.target == "Seat"]
+ assert seat and seat[0].severity == Severity.ERROR
+
+
+def test_instance_count_and_extras(solid_stool_glb: Path) -> None:
+ m = measure_glb(solid_stool_glb)
+ plan = _stool_plan()
+ plan.parts[1].instances = 3
+ r = check_contract(m, plan, language="blender")
+ inst = [f for f in r.findings if f.target == "Leg" and "instance" in f.message]
+ assert inst and inst[0].severity == Severity.WARN
+ # extra part → INFO
+ plan2 = _stool_plan(parts=[_stool_plan().parts[0]])
+ r2 = check_contract(m, plan2, language="blender")
+ assert [f for f in r2.findings if f.severity == Severity.INFO and "not in the plan" in f.message]
+
+
+def test_ground_and_footprint_warnings() -> None:
+ m = Measurement(bbox_min=(0.1, 0.02, 0.1), bbox_max=(0.5, 0.47, 0.5), extents=(0.4, 0.45, 0.4), center=(0.3, 0.245, 0.3),
+ tri_count=10, n_meshes=1, n_islands=1, ground_gap_m=0.02, footprint_offset_m=0.42,
+ parts=[PartMeasure(name="Seat", bbox_min=(0.1, 0.41, 0.1), bbox_max=(0.5, 0.45, 0.5)),
+ *[PartMeasure(name=f"Leg_{i}", bbox_min=(0.1, 0.02, 0.1), bbox_max=(0.14, 0.43, 0.14)) for i in range(4)]])
+ r = check_contract(m, _stool_plan(), language="blender")
+ msgs = " | ".join(f.message for f in r.findings)
+ assert "above the ground" in msgs and "footprint centre" in msgs
+
+
+def test_match_parts_instances() -> None:
+ rows = [PartMeasure(name=n, bbox_min=(0, 0, 0), bbox_max=(1, 1, 1)) for n in ("Leg_0", "Leg_1", "leg2", "Seat", "Extra")]
+ matched, extra = match_parts(_stool_plan().parts, rows)
+ assert {m.name for m in matched["Leg"]} == {"Leg_0", "Leg_1", "leg2"}
+ assert [e.name for e in extra] == ["Extra"]
+
+
+def test_scene_plan_bounds() -> None:
+ plan = ScenePlan(title="t", summary="s", setting="x", bounds=BBox(center=(0, 0, 0), extents=(10, 10, 10)), environment="e",
+ zones=[ZonePlan(name="Harbour", description="d", bbox=BBox(center=(0, 0, 0), extents=(5, 5, 5)))],
+ cameras=[CameraPlan(name="main", position=(0, 2, 10), look_at=(0, 0, 0))])
+ m = Measurement(bbox_min=(-3, 0, -3), bbox_max=(12, 3, 3), extents=(15, 3, 6), center=(4.5, 1.5, 0), tri_count=1, n_meshes=1, n_islands=1,
+ parts=[PartMeasure(name="Harbour", bbox_min=(-3, 0, -3), bbox_max=(3, 3, 3))])
+ r = check_contract(m, plan, language="scene_threejs")
+ assert r.passed # scene findings are warnings
+ assert any("exceeds the planned bounds" in f.message for f in r.findings)
+ assert not any("zone group" in f.message for f in r.findings)
diff --git a/harness/tests/spatial_tools/test_live_render.py b/harness/tests/spatial_tools/test_live_render.py
new file mode 100644
index 00000000..434c9a3e
--- /dev/null
+++ b/harness/tests/spatial_tools/test_live_render.py
@@ -0,0 +1,33 @@
+"""End-to-end through the real renderer (node + headless Chrome). Marked ``node``."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from codeverse.spatial.registry import ToolContext, get_tool
+
+pytestmark = pytest.mark.node
+
+
+def test_render_views_and_silhouette_live(stool_ctx: ToolContext) -> None:
+ pytest.importorskip("codeverse.spatial.render")
+ obs = get_tool("render_views").call(stool_ctx, {"views": ["front", "top"], "size": 256})
+ assert obs.ok, obs.text
+ assert Path(obs.images[0]).is_file() and obs.numbers["views"] == ["front", "top"]
+ sheet = Image.open(obs.images[0])
+ assert sheet.size[0] > sheet.size[1]
+ # the silhouette of the front view is its own perfect reference
+ sil = get_tool("render_views").call(stool_ctx, {"views": ["front"], "mode": "silhouette", "size": 256})
+ assert sil.ok, sil.text
+ ref = stool_ctx.workspace.root / "ref.png"
+ Image.open(sil.images[-1]).convert("RGB").save(ref)
+ spec = json.loads(stool_ctx.workspace.spec_path.read_text())
+ spec["references"] = [{"path": "ref.png"}]
+ stool_ctx.workspace.spec_path.write_text(json.dumps(spec))
+ cmp_ = get_tool("compare_silhouette").call(stool_ctx, {"view": "front"})
+ assert cmp_.ok, cmp_.text
+ assert cmp_.numbers["iou"] > 0.97 and cmp_.numbers["reliable"]
diff --git a/harness/tests/spatial_tools/test_mcp_server.py b/harness/tests/spatial_tools/test_mcp_server.py
new file mode 100644
index 00000000..a0c233c2
--- /dev/null
+++ b/harness/tests/spatial_tools/test_mcp_server.py
@@ -0,0 +1,71 @@
+"""In-process MCP client ↔ our stdio server (spawned as a subprocess)."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+from codeverse.spatial.mcp_server import build_context, encode_image, main, observation_content
+from codeverse.spatial.registry import Observation, ToolContext
+
+
+def test_build_context_infers_from_spec(stool_ctx: ToolContext) -> None:
+ ctx = build_context(stool_ctx.workspace.root)
+ assert ctx.language == "blender" and ctx.track == "static_object"
+ ctx = build_context(stool_ctx.workspace.root, language="threejs", round_index=2)
+ assert ctx.language == "threejs" and ctx.round_index == 2
+
+
+def test_observation_content_blocks(tmp_path: Path) -> None:
+ from PIL import Image
+
+ big = tmp_path / "big.png"
+ Image.new("RGB", (2048, 1024), (10, 20, 30)).save(big)
+ obs = Observation(ok=True, text="hello", numbers={"a": 1}, images=[str(big), str(tmp_path / "missing.png")])
+ blocks = observation_content(obs)
+ assert blocks[0].type == "text" and blocks[0].text.startswith("hello\n{\"a\": 1}")
+ assert len(blocks) == 2 and blocks[1].type == "image" and blocks[1].mime_type == "image/png"
+ import base64
+ import io
+
+ im = Image.open(io.BytesIO(base64.b64decode(blocks[1].data)))
+ assert max(im.size) == 1024
+ assert encode_image(str(tmp_path / "missing.png")) is None
+
+
+def test_cli_list(stool_ctx: ToolContext, capsys: pytest.CaptureFixture[str]) -> None:
+ assert main(["--workspace", str(stool_ctx.workspace.root), "--list"]) == 0
+ data = json.loads(capsys.readouterr().out)
+ names = {d["name"] for d in data}
+ assert {"build", "measure", "read_cookbook", "render_views"} <= names and "shader_probe" not in names
+ assert main(["--workspace", str(stool_ctx.workspace.root / "nope")]) == 2
+
+
+def test_stdio_roundtrip(stool_ctx: ToolContext) -> None:
+ from mcp import ClientSession
+ from mcp.client.stdio import StdioServerParameters, stdio_client
+
+ 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:
+ await s.initialize()
+ tools = await s.list_tools()
+ by_name = {t.name: t for t in tools.tools}
+ assert "read_cookbook" in by_name and "measure" in by_name and "check_connectivity" in by_name
+ assert by_name["render_views"].input_schema["properties"]["views"]["type"] == "array"
+ cb = await s.call_tool("read_cookbook", {"section": "export"})
+ assert cb.content and cb.content[0].type == "text"
+ meas = await s.call_tool("measure", {})
+ assert not meas.is_error and "Leg ×4" in meas.content[0].text
+ sec = await s.call_tool("cross_section", {"axis": "y", "at": 0.5})
+ assert [c.type for c in sec.content] == ["text", "image"]
+ bad = await s.call_tool("measure", {"parts": 3})
+ assert bad.is_error and "invalid arguments" in bad.content[0].text
+ unknown = await s.call_tool("nope", {})
+ assert unknown.is_error
+
+ asyncio.run(asyncio.wait_for(run(), timeout=120))
diff --git a/harness/tests/spatial_tools/test_measure.py b/harness/tests/spatial_tools/test_measure.py
new file mode 100644
index 00000000..683215ee
--- /dev/null
+++ b/harness/tests/spatial_tools/test_measure.py
@@ -0,0 +1,66 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import trimesh
+
+from codeverse.spatial.measure import (
+ GlbLoadError,
+ instance_groups,
+ measure_glb,
+ measure_summary_table,
+)
+
+
+def test_measure_stool(stool_glb: Path) -> None:
+ m = measure_glb(stool_glb)
+ assert {p.name for p in m.parts} == {"Seat", "Leg_0", "Leg_1", "Leg_2", "Leg_3"}
+ assert m.extents == pytest.approx((0.4, 0.45, 0.4), abs=1e-6)
+ assert m.ground_gap_m == pytest.approx(0.0, abs=1e-6)
+ assert m.footprint_offset_m == pytest.approx(0.0, abs=1e-6)
+ assert m.n_islands == 5 and m.n_meshes == 5
+ seat = next(p for p in m.parts if p.name == "Seat")
+ assert seat.tri_count == 12 and seat.watertight and seat.volume_m3 == pytest.approx(0.4 * 0.04 * 0.4, rel=1e-6)
+ assert m.frame == "y_up_pos_z_front"
+ assert m.extra["findings"] == []
+
+
+def test_summary_table_groups_instances(stool_glb: Path) -> None:
+ table = measure_summary_table(measure_glb(stool_glb))
+ assert "Leg ×4 (Leg_0..3)" in table
+ assert "| Seat |" in table
+ assert "40.0×45.0×40.0" in table
+ assert table.count("\n") < 40
+
+
+def test_instance_groups() -> None:
+ g = instance_groups(["Leg_3", "Leg_0", "Seat", "Bolt.1", "Bolt.2", "Rail_1"])
+ assert g["Leg"] == ["Leg_0", "Leg_3"]
+ assert g["Bolt"] == ["Bolt.1", "Bolt.2"]
+ assert g["Seat"] == ["Seat"]
+ assert g["Rail_1"] == ["Rail_1"] # singleton keeps its full name
+
+
+def test_missing_file_raises(tmp_path: Path) -> None:
+ with pytest.raises(GlbLoadError):
+ measure_glb(tmp_path / "nope.glb")
+
+
+def test_degenerate_mesh_is_a_finding(tmp_path: Path) -> None:
+ sc = trimesh.Scene()
+ flat = trimesh.Trimesh(vertices=[[0, 0, 0], [1, 0, 0], [1, 0, 1]], faces=[[0, 1, 2]]) # zero height, open
+ sc.add_geometry(flat, node_name="Sheet", geom_name="Sheet")
+ p = tmp_path / "flat.glb"
+ sc.export(str(p))
+ m = measure_glb(p)
+ assert m.tri_count == 1
+ assert m.parts[0].watertight is False and m.parts[0].volume_m3 is None
+ assert m.extents[1] == 0.0
+
+
+def test_unnamed_single_mesh(tmp_path: Path) -> None:
+ p = tmp_path / "box.glb"
+ trimesh.creation.box(extents=(1, 1, 1)).export(str(p))
+ m = measure_glb(p)
+ assert len(m.parts) == 1 and m.tri_count == 12
diff --git a/harness/tests/spatial_tools/test_observe.py b/harness/tests/spatial_tools/test_observe.py
new file mode 100644
index 00000000..d589113e
--- /dev/null
+++ b/harness/tests/spatial_tools/test_observe.py
@@ -0,0 +1,64 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.contracts.artifacts import GateFinding, GateReport, RenderSet, RenderView, Severity
+from codeverse.spatial.observe import (
+ fmt_numbers,
+ gate_observation,
+ image_budget,
+ rel_path,
+ render_observation,
+ sanitize_text,
+ tail_lines,
+ truncate,
+)
+
+
+def test_fmt_numbers_compact() -> None:
+ s = fmt_numbers({"a": 1.23456789, "b": [0.1, 0.2], "c": True, "d": {"x": 1, "y": {"z": {"deep": 1}}}, "e": "x" * 100})
+ assert "a=1.2346" in s and "b=[0.1, 0.2]" in s and "c=yes" in s and "{1 keys}" in s and "…" in s
+
+
+def test_truncate_keeps_head_and_tail() -> None:
+ text = "\n".join(f"line {i}" for i in range(500))
+ t = truncate(text, 400)
+ assert t.startswith("line 0") and t.endswith("line 499") and "chars omitted" in t
+ assert truncate("short") == "short"
+ assert tail_lines("a\nb\nc\nd", 2) == "c\nd"
+
+
+def test_image_budget_keeps_sheet_first() -> None:
+ imgs = [f"/x/{i}.png" for i in range(10)]
+ out = image_budget(imgs, max_n=3)
+ assert out == imgs[:3]
+
+
+def test_paths_are_workspace_relative(tmp_path: Path) -> None:
+ p = tmp_path / "artifacts" / "object.glb"
+ assert rel_path(p, tmp_path) == "artifacts/object.glb"
+ assert rel_path("/elsewhere/file.py", tmp_path) == "file.py"
+ assert sanitize_text(f"error in {tmp_path}/src/model.py:3", tmp_path) == "error in src/model.py:3"
+
+
+def test_gate_observation_errors_first() -> None:
+ rep = GateReport(gate="g", passed=False, findings=[
+ GateFinding(gate="g", severity=Severity.INFO, message="fyi"),
+ GateFinding(gate="g", severity=Severity.WARN, target="A", message="warnish", fix_hint="do x"),
+ GateFinding(gate="g", severity=Severity.ERROR, target="B", message="bad", fix_hint="do y", data={"gap_m": 0.01}),
+ ])
+ obs = gate_observation(rep)
+ assert not obs.ok
+ lines = obs.text.splitlines()
+ assert "FAIL" in lines[0] and "1 error(s), 1 warning(s)" in lines[0]
+ assert lines[1].startswith("- ERROR [B]") and "fix: do y" in lines[2]
+ assert obs.numbers["errors"] == 1 and obs.numbers["error_data"]["B"]["gap_m"] == 0.01
+
+
+def test_render_observation(tmp_path: Path) -> None:
+ rs = RenderSet(views=[RenderView(name="front", path=str(tmp_path / "a/view_front.png"), camera_position=(0, 1, 2), fov=35)],
+ contact_sheet=str(tmp_path / "a/sheet.png"), renderer="swiftshader")
+ obs = render_observation(rs, tmp_path, note="hello")
+ assert obs.ok and obs.images[0].endswith("sheet.png") and len(obs.images) == 2
+ assert "a/view_front.png" in obs.text and str(tmp_path) not in obs.text
+ assert "cam=(0, 1, 2)" in obs.text
diff --git a/harness/tests/spatial_tools/test_sections.py b/harness/tests/spatial_tools/test_sections.py
new file mode 100644
index 00000000..d14beca4
--- /dev/null
+++ b/harness/tests/spatial_tools/test_sections.py
@@ -0,0 +1,47 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import trimesh
+from PIL import Image
+
+from codeverse.spatial.sections import cross_section, slices_sheet
+
+
+def test_cross_section_stool(stool_glb: Path, tmp_path: Path) -> None:
+ out = tmp_path / "sec.png"
+ o = cross_section(stool_glb, "y", 0.5, out)
+ assert o.ok and o.images == [str(out)] and out.is_file()
+ assert o.numbers["n_loops"] == 4
+ assert o.numbers["total_area_m2"] == pytest.approx(4 * 3.14159 * 0.02**2, rel=0.05)
+ assert set(o.numbers["parts_cut"]) == {"Leg_0", "Leg_1", "Leg_2", "Leg_3"}
+ assert Image.open(out).size == (512, 512)
+
+
+def test_cross_section_parts_and_absolute(stool_glb: Path, tmp_path: Path) -> None:
+ o = cross_section(stool_glb, "y", 0.43, tmp_path / "s.png", parts=["Seat"], absolute=True)
+ assert o.ok and o.numbers["parts_cut"] == {"Seat": 1}
+ assert o.numbers["total_area_m2"] == pytest.approx(0.16, rel=1e-3)
+
+
+def test_hollow_ratio(tmp_path: Path) -> None:
+ p = tmp_path / "tube.glb"
+ trimesh.creation.annulus(r_min=0.04, r_max=0.05, height=0.3).export(str(p))
+ o = cross_section(p, "z", 0.5, tmp_path / "t.png")
+ assert o.numbers["n_loops"] == 2
+ assert o.numbers["hollow_ratio"] == pytest.approx(0.64, abs=0.03)
+
+
+def test_bad_inputs(stool_glb: Path, tmp_path: Path) -> None:
+ assert not cross_section(stool_glb, "w", 0.5, tmp_path / "x.png").ok
+ o = cross_section(stool_glb, "y", 0.5, tmp_path / "x.png", parts=["Nope"])
+ assert not o.ok and "Nope" in o.text and "Seat" in o.text
+ assert not cross_section(tmp_path / "missing.glb", "y", 0.5, tmp_path / "x.png").ok
+
+
+def test_slices_sheet(stool_glb: Path, tmp_path: Path) -> None:
+ out = tmp_path / "slices.png"
+ o = slices_sheet(stool_glb, "y", 5, out)
+ assert o.ok and out.is_file() and len(o.numbers["slices"]) == 5
+ assert all(s["n_loops"] == 4 for s in o.numbers["slices"][:4])
diff --git a/harness/tests/spatial_tools/test_silhouette.py b/harness/tests/spatial_tools/test_silhouette.py
new file mode 100644
index 00000000..c100ebe7
--- /dev/null
+++ b/harness/tests/spatial_tools/test_silhouette.py
@@ -0,0 +1,68 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from PIL import Image, ImageDraw
+
+from codeverse.contracts.artifacts import RenderView
+from codeverse.spatial.silhouette import compare_silhouette, foreground_mask, silhouette_series
+
+
+def _disc(path: Path, size: tuple[int, int], box: tuple[int, int, int, int], bg=(240, 240, 240), fg=(30, 30, 30)) -> Path:
+ im = Image.new("RGB", size, bg)
+ ImageDraw.Draw(im).ellipse(box, fill=fg)
+ im.save(path)
+ return path
+
+
+def test_same_shape_different_framing(tmp_path: Path) -> None:
+ a = _disc(tmp_path / "a.png", (400, 300), (100, 50, 300, 250))
+ b = _disc(tmp_path / "b.png", (512, 512), (56, 56, 456, 456), fg=(80, 20, 20))
+ r = compare_silhouette(b, a, diff_png=tmp_path / "diff.png")
+ assert r["iou"] > 0.95 and r["aspect_ratio_err"] < 0.02 and r["reliable"]
+ assert (tmp_path / "diff.png").is_file()
+
+
+def test_different_aspect(tmp_path: Path) -> None:
+ a = _disc(tmp_path / "a.png", (400, 400), (100, 100, 300, 300))
+ b = _disc(tmp_path / "b.png", (400, 400), (50, 150, 350, 250)) # wide ellipse
+ r = compare_silhouette(b, a)
+ assert r["aspect_ratio_err"] > 1.0 and r["iou"] < 0.8
+
+
+def test_alpha_mask_and_enclosed_pockets(tmp_path: Path) -> None:
+ im = Image.new("RGBA", (200, 200), (0, 0, 0, 0))
+ d = ImageDraw.Draw(im)
+ d.rectangle([20, 20, 180, 180], fill=(200, 200, 200, 255))
+ d.rectangle([80, 80, 120, 120], fill=(0, 0, 0, 0)) # a hole
+ p = tmp_path / "alpha.png"
+ im.save(p)
+ m = foreground_mask(p)
+ assert m.sum() == pytest.approx(161 * 161 - 41 * 41, rel=0.01)
+ # opaque version: the pocket is enclosed → counted as foreground
+ im2 = Image.new("RGB", (200, 200), (255, 255, 255))
+ d2 = ImageDraw.Draw(im2)
+ d2.rectangle([20, 20, 180, 180], fill=(40, 40, 40))
+ d2.rectangle([80, 80, 120, 120], fill=(255, 255, 255))
+ p2 = tmp_path / "opaque.png"
+ im2.save(p2)
+ assert foreground_mask(p2).sum() == pytest.approx(161 * 161, rel=0.01)
+
+
+def test_unreliable_when_empty(tmp_path: Path) -> None:
+ blank = tmp_path / "blank.png"
+ Image.new("RGB", (100, 100), (250, 250, 250)).save(blank)
+ a = _disc(tmp_path / "a.png", (100, 100), (20, 20, 80, 80))
+ r = compare_silhouette(blank, a)
+ assert r["iou"] == 0.0 and not r["reliable"]
+
+
+def test_series_picks_best_view(tmp_path: Path) -> None:
+ ref = _disc(tmp_path / "ref.png", (300, 300), (50, 50, 250, 250))
+ good = _disc(tmp_path / "good.png", (300, 300), (40, 40, 260, 260))
+ bad = _disc(tmp_path / "bad.png", (300, 300), (20, 120, 280, 180))
+ views = [RenderView(name="front", path=str(bad)), RenderView(name="top", path=str(good))]
+ res = silhouette_series(views, [ref], diff_dir=tmp_path)
+ assert res[0]["best_view"] == "top" and res[0]["iou"] > 0.9
+ assert Path(res[0]["diff_png_path"]).is_file()
diff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.py
new file mode 100644
index 00000000..c12c3b83
--- /dev/null
+++ b/harness/tests/spatial_tools/test_tools.py
@@ -0,0 +1,288 @@
+"""Tool-level tests with fakes for the sibling packages (runtime, renderer)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image, ImageDraw
+
+import codeverse.spatial.tools # noqa: F401 (registers all tools)
+from codeverse.contracts.artifacts import (
+ BuildResult,
+ GateFinding,
+ GateReport,
+ RenderSet,
+ RenderView,
+ Severity,
+)
+from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
+from codeverse.spatial.registry import ToolContext, get_tool, list_tools
+from codeverse.workspace import Workspace
+
+EXPECTED_TOOLS = {"build", "measure", "render_views", "render_sheet", "isolate", "cross_section", "check_connectivity",
+ "check_contract", "compare_silhouette", "joint_sweep", "shader_probe", "scene_probe", "scene_views", "read_cookbook"}
+
+
+def test_registry_has_every_tool() -> None:
+ assert {t.name for t in list_tools()} == EXPECTED_TOOLS
+ assert "joint_sweep" not in {t.name for t in list_tools(track="static_object", language="blender")}
+ assert "shader_probe" in {t.name for t in list_tools(track="scene", language="scene_threejs")}
+ for t in list_tools():
+ assert t.schema()["type"] == "object" and t.description
+
+
+def test_measure_tool(stool_ctx: ToolContext) -> None:
+ obs = get_tool("measure").call(stool_ctx, {})
+ assert obs.ok and "Leg ×4" in obs.text and obs.numbers["n_parts"] == 5
+ obs = get_tool("measure").call(stool_ctx, {"parts": ["Seat"]})
+ assert obs.ok and list(obs.numbers["parts"]) == ["Seat"]
+ obs = get_tool("measure").call(stool_ctx, {"parts": ["Nope"]})
+ assert not obs.ok and "Seat" in obs.text # didactic: lists available parts
+
+
+def test_tools_without_glb(tmp_ws: Workspace) -> None:
+ ctx = ToolContext(workspace=tmp_ws, language="blender")
+ for name in ("measure", "check_connectivity", "cross_section", "render_views", "isolate"):
+ obs = get_tool(name).call(ctx, {"part": "x"} if name == "isolate" else {})
+ assert not obs.ok and "run `build` first" in obs.text, name
+
+
+def test_connectivity_and_section_tools(stool_ctx: ToolContext) -> None:
+ obs = get_tool("check_connectivity").call(stool_ctx, {})
+ assert not obs.ok and "Leg_3" in obs.text and "translate 'Leg_3' by (+0.0000, +0.0050, +0.0000)" in obs.text
+ assert (stool_ctx.workspace.gates_dir(0) / "connectivity_tool.json").is_file()
+ obs = get_tool("cross_section").call(stool_ctx, {"axis": "y", "at": 0.5})
+ assert obs.ok and len(obs.images) == 1 and Path(obs.images[0]).is_file() and obs.numbers["n_loops"] == 4
+ assert str(stool_ctx.workspace.root) not in obs.text
+ obs = get_tool("cross_section").call(stool_ctx, {"axis": "q"})
+ assert not obs.ok and "x|y|z" in obs.text
+
+
+def test_check_contract_tool(stool_ctx: ToolContext) -> None:
+ obs = get_tool("check_contract").call(stool_ctx, {})
+ assert not obs.ok and "plan.json not found" in obs.text
+ plan = StaticPlan(object_name="Stool", summary="s", overall_bbox=BBox(center=(0, 0, 0.225), extents=(0.4, 0.4, 0.45)),
+ parts=[PartPlan(name="Seat", role="r", description="d", bbox=BBox(center=(0, 0, 0.43), extents=(0.4, 0.4, 0.04))),
+ PartPlan(name="Leg", role="r", description="d", bbox=BBox(center=(0, 0, 0.205), extents=(0.04, 0.04, 0.41)), instances=4),
+ PartPlan(name="Backrest", role="r", description="d", bbox=BBox(center=(0, 0.18, 0.6), extents=(0.4, 0.03, 0.3)))])
+ stool_ctx.workspace.write_json(stool_ctx.workspace.plan_path, plan)
+ obs = get_tool("check_contract").call(stool_ctx, {})
+ assert not obs.ok and "Backrest" in obs.text and "missing" in obs.text
+
+
+# --------------------------------------------------------------------------- build with a fake runtime
+class _FakeRuntime:
+ def __init__(self, *, lint_errors: bool = False, build_ok: bool = True, glb: Path | None = None, root: Path | None = None):
+ self.lint_errors, self.build_ok, self.glb, self.root = lint_errors, build_ok, glb, root
+
+ def lint(self, ws):
+ f = [GateFinding(gate="lint:blender", severity=Severity.WARN, target=str(ws.src / "model.py"), message="uses bpy.ops.render", fix_hint="delete it")]
+ if self.lint_errors:
+ f.append(GateFinding(gate="lint:blender", severity=Severity.ERROR, target=str(ws.src / "model.py"), message="SyntaxError line 3", fix_hint="close the bracket"))
+ return GateReport(gate="lint:blender", passed=not self.lint_errors, findings=f)
+
+ def build(self, ws, *, timeout_s=None):
+ if self.build_ok:
+ return BuildResult(ok=True, language="blender", glb_path=str(self.glb), duration_ms=12, census={"warnings": ["[EXPORT_WARN] no materials"]})
+ return BuildResult(ok=False, language="blender", error_type="NameError", error_message="name 'bpyx' is not defined",
+ error_file=str(ws.src / "model.py"), error_line=7, stderr_tail="\n".join(f"l{i}" for i in range(60)) + f"\n File \"{ws.src}/model.py\", line 7")
+
+ def contract_doc(self):
+ return "# Fake contract\n\n## Export\nthe harness exports.\n"
+
+
+def _patch_runtime(monkeypatch: pytest.MonkeyPatch, rt: _FakeRuntime) -> None:
+ import codeverse.languages as langs
+
+ monkeypatch.setattr(langs, "get_runtime", lambda language: rt)
+
+
+def test_build_tool_success(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ glb = stool_ctx.workspace.artifacts / "object.glb"
+ _patch_runtime(monkeypatch, _FakeRuntime(glb=glb))
+ obs = get_tool("build").call(stool_ctx, {})
+ assert obs.ok and obs.text.startswith("BUILD OK") and "Leg ×4" in obs.text
+ assert "lint warnings" in obs.text and "uses bpy.ops.render" in obs.text and "build warnings" in obs.text
+ assert str(stool_ctx.workspace.root) not in obs.text
+ assert (stool_ctx.workspace.artifacts / "build_last.json").is_file()
+ assert json.loads((stool_ctx.workspace.artifacts / "build_last.json").read_text())["ok"] is True
+ assert (stool_ctx.workspace.artifacts / "measurement.json").is_file()
+
+
+def test_build_tool_failure_is_error_first(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_runtime(monkeypatch, _FakeRuntime(build_ok=False))
+ obs = get_tool("build").call(stool_ctx, {})
+ assert not obs.ok
+ first = obs.text.splitlines()[0]
+ assert first.startswith("BUILD FAILED: NameError: name 'bpyx' is not defined at src/model.py:7")
+ assert "l59" in obs.text and "l10" not in obs.text # ≤ 30-line stderr tail
+ assert str(stool_ctx.workspace.root) not in obs.text
+ assert obs.numbers["error_line"] == 7
+
+
+def test_build_tool_lint_blocks(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_runtime(monkeypatch, _FakeRuntime(lint_errors=True))
+ obs = get_tool("build").call(stool_ctx, {})
+ assert not obs.ok and obs.text.startswith("LINT FAILED") and "close the bracket" in obs.text
+ assert obs.numbers["stage"] == "lint"
+
+
+def test_build_unavailable_runtime(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ import codeverse.spatial.tool_common as tc
+
+ def boom(module, attr):
+ raise tc.ToolUnavailable(f"{module} not importable")
+
+ monkeypatch.setattr(tc, "lazy", boom)
+ monkeypatch.setattr("codeverse.spatial.tools.lazy", boom)
+ obs = get_tool("build").call(stool_ctx, {})
+ assert not obs.ok and obs.text.startswith("tool build unavailable:")
+
+
+# --------------------------------------------------------------------------- rendering with a fake renderer
+def _fake_render_glb(glb, out_dir, *, views=None, mode="shaded", width=768, height=768, isolate=None, explode=0.0, sheet=True, background="studio", **_):
+ out_dir = Path(out_dir)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ rviews = []
+ for v in views or []:
+ p = out_dir / f"view_{v.name}.png"
+ im = Image.new("RGB", (width, height), (255, 255, 255))
+ ImageDraw.Draw(im).rectangle([width // 4, height // 4, 3 * width // 4, 3 * height // 4], fill=(0, 0, 0))
+ im.save(p)
+ rviews.append(RenderView(name=v.name, path=str(p), mode=mode, width=width, height=height, camera_position=(1.0, 1.0, 1.0), fov=35))
+ sheet_p = None
+ if sheet:
+ sheet_p = out_dir / "sheet.png"
+ Image.new("RGB", (64, 64), (200, 200, 200)).save(sheet_p)
+ _fake_render_glb.calls += 1
+ return RenderSet(views=rviews, contact_sheet=str(sheet_p) if sheet_p else None, renderer="fake")
+
+
+_fake_render_glb.calls = 0
+
+
+def fake_renderer(monkeypatch: pytest.MonkeyPatch):
+ import codeverse.spatial.render as render
+
+ _fake_render_glb.calls = 0
+ monkeypatch.setattr(render, "render_glb", _fake_render_glb)
+ return _fake_render_glb
+
+
+def test_render_views_cached(stool_ctx: ToolContext, fake_renderer) -> None:
+ obs = get_tool("render_views").call(stool_ctx, {})
+ assert obs.ok and obs.images[0].endswith("sheet.png") and len(obs.images) == 5 # sheet + 4 views
+ assert obs.numbers["views"] == ["front_right_34", "back_left_34", "front", "top"]
+ assert "artifacts/tool_renders/r00_" in obs.text and str(stool_ctx.workspace.root) not in obs.text
+ get_tool("render_views").call(stool_ctx, {})
+ assert fake_renderer.calls == 1 # second call served from the on-disk cache
+ obs = get_tool("render_views").call(stool_ctx, {"views": ["front", "back", "left", "right", "top"]})
+ assert obs.ok and len(obs.images) == 1 # > 4 views → sheet only
+ obs = get_tool("render_views").call(stool_ctx, {"views": ["frontal"]})
+ assert not obs.ok and "front_right_34" in obs.text
+ obs = get_tool("render_views").call(stool_ctx, {"mode": "xray"})
+ assert not obs.ok and "shaded" in obs.text
+
+
+def test_render_sheet_and_isolate(stool_ctx: ToolContext, fake_renderer) -> None:
+ obs = get_tool("render_sheet").call(stool_ctx, {"mode": "wire"})
+ assert obs.ok and len(obs.images) == 1 and obs.numbers["n_views"] == 8
+ obs = get_tool("isolate").call(stool_ctx, {"part": "Leg_3"})
+ assert obs.ok and obs.numbers["part"] == "Leg_3" and "| Leg_3 |" in obs.text
+ obs = get_tool("isolate").call(stool_ctx, {"part": "Nope"})
+ assert not obs.ok and "Leg_3" in obs.text
+
+
+def test_compare_silhouette_tool(stool_ctx: ToolContext, fake_renderer) -> None:
+ obs = get_tool("compare_silhouette").call(stool_ctx, {})
+ assert not obs.ok and "no reference images" in obs.text
+ ref = stool_ctx.workspace.root / "ref.png"
+ im = Image.new("RGB", (300, 300), (250, 250, 250))
+ ImageDraw.Draw(im).rectangle([60, 60, 240, 240], fill=(20, 20, 20))
+ im.save(ref)
+ spec = json.loads(stool_ctx.workspace.spec_path.read_text())
+ spec["references"] = [{"path": "ref.png"}]
+ stool_ctx.workspace.spec_path.write_text(json.dumps(spec))
+ obs = get_tool("compare_silhouette").call(stool_ctx, {"view": "front"})
+ assert obs.ok and obs.numbers["iou"] > 0.95 and len(obs.images) == 2 and Path(obs.images[0]).is_file()
+ obs = get_tool("compare_silhouette").call(stool_ctx, {"reference_index": 3})
+ assert not obs.ok and "out of range" in obs.text
+
+
+def test_renderer_unavailable(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ import codeverse.spatial.tool_common as tc
+
+ def boom(module, attr):
+ raise tc.ToolUnavailable(f"{module} not importable")
+
+ monkeypatch.setattr(tc, "lazy", boom)
+ obs = get_tool("render_views").call(stool_ctx, {})
+ assert not obs.ok and obs.text.startswith("tool render_views unavailable:")
+
+
+# --------------------------------------------------------------------------- cookbook + scene tools
+def test_read_cookbook(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ import codeverse.prompts as prompts
+
+ md = "# Blender cookbook\n\nintro\n\n## Export\nharness exports\n\n## Pitfalls\n- no bpy.ops\n" + "x" * 7000
+ monkeypatch.setattr(prompts, "load_text", lambda rel: md if rel == "blender/cookbook.md" else (_ for _ in ()).throw(FileNotFoundError(rel)))
+ obs = get_tool("read_cookbook").call(stool_ctx, {})
+ assert obs.ok and obs.text.startswith("[prompts/blender/cookbook.md]") and obs.numbers["truncated"] and "sections: Blender cookbook | Export | Pitfalls" in obs.text
+ assert len(obs.text) < 6500
+ obs = get_tool("read_cookbook").call(stool_ctx, {"section": "pitfalls"})
+ assert obs.ok and "- no bpy.ops" in obs.text and "harness exports" not in obs.text
+ obs = get_tool("read_cookbook").call(stool_ctx, {"section": "materials"})
+ assert not obs.ok and "Export" in obs.text
+
+
+def test_read_cookbook_falls_back_to_contract(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ import codeverse.prompts as prompts
+
+ monkeypatch.setattr(prompts, "load_text", lambda rel: (_ for _ in ()).throw(FileNotFoundError(rel)))
+ _patch_runtime(monkeypatch, _FakeRuntime())
+ obs = get_tool("read_cookbook").call(stool_ctx, {"section": "export"})
+ assert obs.ok and "the harness exports" in obs.text and "contract_doc()" in obs.text
+
+
+def test_scene_tools_degrade_when_unavailable(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ import codeverse.spatial.tool_common as tc
+ import codeverse.spatial.tools_scene as ts
+
+ def boom(module, attr):
+ raise tc.ToolUnavailable(f"{module} not importable")
+
+ monkeypatch.setattr(ts, "lazy", boom)
+ for name in ("joint_sweep", "shader_probe", "scene_probe", "scene_views"):
+ obs = get_tool(name).call(stool_ctx, {})
+ assert not obs.ok and obs.text.startswith(f"tool {name} unavailable:"), name
+
+
+def test_scene_tools_with_fake_siblings(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ import codeverse.spatial.tools_scene as ts
+
+ calls = {}
+
+ def fake_check_shaders(ws):
+ return GateReport(gate="shaders", passed=False, findings=[GateFinding(gate="shaders", severity=Severity.ERROR, target="src/shaders/water.js", message="ERROR: 0:12: 'vUv' undeclared", fix_hint="declare varying vec2 vUv")])
+
+ def fake_probe_scene(ws, **kw):
+ return {"census": {"meshes": 12, "lights": 2}, "fps": 58.0, "errors": []}
+
+ def fake_joint_sweep(ws, *, n_random=8, seed=0, render=True, out_dir=None, joint=None, expected_direction=None):
+ calls["n_random"], calls["joint"] = n_random, joint
+ from codeverse.spatial.registry import Observation
+ return Observation(ok=True, text="sweep ok", numbers={"poses": n_random})
+
+ def fake_lazy(module, attr):
+ return {"check_shaders": fake_check_shaders, "probe_scene": fake_probe_scene, "joint_sweep_observation": fake_joint_sweep}[attr]
+
+ monkeypatch.setattr(ts, "lazy", fake_lazy)
+ obs = get_tool("shader_probe").call(stool_ctx, {})
+ assert not obs.ok and "vUv" in obs.text and "declare varying" in obs.text
+ obs = get_tool("scene_probe").call(stool_ctx, {})
+ assert obs.ok and "meshes=12" in obs.text and obs.numbers["fps"] == 58.0
+ obs = get_tool("joint_sweep").call(stool_ctx, {"joints": ["hinge"], "n_samples": 5})
+ assert obs.ok and calls == {"n_random": 5, "joint": "hinge"}
diff --git a/harness/tests/threejs_render/conftest.py b/harness/tests/threejs_render/conftest.py
new file mode 100644
index 00000000..37c95c32
--- /dev/null
+++ b/harness/tests/threejs_render/conftest.py
@@ -0,0 +1,111 @@
+"""Fixtures: a four-legged stool authored per the three.js contract (one part file per part)."""
+
+from __future__ import annotations
+
+import shutil
+from pathlib import Path
+
+import pytest
+
+from codeverse.workspace import Workspace
+
+SEAT_JS = """\
+import * as THREE from 'three';
+import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';
+export function buildSeat(THREE_) {
+ const g = new THREE.Group(); g.name = 'Seat';
+ const mesh = new THREE.Mesh(new RoundedBoxGeometry(0.34, 0.04, 0.34, 3, 0.01),
+ new THREE.MeshStandardMaterial({ color: 0x8b5a2b, roughness: 0.6 }));
+ mesh.name = 'SeatTop';
+ mesh.position.set(0, 0.43, 0);
+ g.add(mesh);
+ return g;
+}
+"""
+
+LEGS_JS = """\
+import * as THREE from 'three';
+export function buildLegs(THREE_) {
+ const g = new THREE.Group(); g.name = 'Legs';
+ const mat = new THREE.MeshStandardMaterial({ color: 0x333333, roughness: 0.4, metalness: 0.6 });
+ const geo = new THREE.CylinderGeometry(0.015, 0.018, 0.41, 16);
+ const off = 0.13;
+ for (const [x, z] of [[-off, -off], [off, -off], [-off, off], [off, off]]) {
+ const m = new THREE.Mesh(geo, mat);
+ m.name = `Leg_${x < 0 ? 'L' : 'R'}${z < 0 ? 'B' : 'F'}`;
+ m.position.set(x, 0.205, z);
+ g.add(m);
+ }
+ return g;
+}
+"""
+
+STRETCHERS_JS = """\
+import * as THREE from 'three';
+export function buildStretchers(THREE_) {
+ const g = new THREE.Group(); g.name = 'Stretchers';
+ const mat = new THREE.MeshStandardMaterial({ color: 0x333333, roughness: 0.4, metalness: 0.6 });
+ const geo = new THREE.CylinderGeometry(0.008, 0.008, 0.26, 12);
+ for (let i = 0; i < 4; i++) {
+ const m = new THREE.Mesh(geo, mat);
+ m.name = `Stretcher_${i}`;
+ const a = (i * Math.PI) / 2;
+ m.position.set(0.13 * Math.cos(a), 0.15, 0.13 * Math.sin(a));
+ m.rotateY(-a); m.rotateX(Math.PI / 2);
+ g.add(m);
+ }
+ return g;
+}
+"""
+
+OBJECT_JS = """\
+import * as THREE from 'three';
+import { buildSeat } from './parts/seat.js';
+import { buildLegs } from './parts/legs.js';
+import { buildStretchers } from './parts/stretchers.js';
+export function build(THREE_) {
+ const root = new THREE.Group(); root.name = 'Stool';
+ root.add(buildSeat(THREE), buildLegs(THREE), buildStretchers(THREE));
+ root.userData.tick = (t, dt) => { root.rotation.y = t * 0.2; };
+ return root;
+}
+"""
+
+STOOL_FILES = {
+ "src/object.js": OBJECT_JS,
+ "src/parts/seat.js": SEAT_JS,
+ "src/parts/legs.js": LEGS_JS,
+ "src/parts/stretchers.js": STRETCHERS_JS,
+}
+
+
+def write_stool(root: Path) -> Workspace:
+ ws = Workspace(root)
+ for d in ("src/parts", "artifacts"):
+ (root / d).mkdir(parents=True, exist_ok=True)
+ for rel, text in STOOL_FILES.items():
+ (root / rel).write_text(text)
+ return ws
+
+
+def stool_ws(tmp_path: Path) -> Workspace:
+ return write_stool(tmp_path / "stool")
+
+
+def node_available() -> bool:
+ return shutil.which("node") is not None
+
+
[email protected](scope="session")
+def stool_glb(tmp_path_factory: pytest.TempPathFactory) -> Path:
+ """Build the stool once per session (needs node); skipped when node is missing."""
+ if shutil.which("node") is None:
+ pytest.skip("node not available")
+ from codeverse.languages.threejs.runtime import ThreeJsRuntime
+
+ ws = write_stool(tmp_path_factory.mktemp("stool_session"))
+ res = ThreeJsRuntime().build(ws)
+ assert res.ok, res.error_message
+ return Path(res.glb_path)
diff --git a/harness/tests/threejs_render/test_build.py b/harness/tests/threejs_render/test_build.py
new file mode 100644
index 00000000..76c006ae
--- /dev/null
+++ b/harness/tests/threejs_render/test_build.py
@@ -0,0 +1,95 @@
+"""ThreeJsRuntime.build through runtime_js/export_glb.mjs (needs node)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import numpy as np
+import pytest
+import trimesh
+
+from codeverse.languages.threejs.runtime import ThreeJsRuntime
+from codeverse.workspace import Workspace
+
+pytestmark = pytest.mark.node
+
+
+def test_build_stool_glb_and_census(stool_ws: Workspace):
+ rt = ThreeJsRuntime()
+ res = rt.build(stool_ws)
+ assert res.ok, (res.error_type, res.error_message, res.stderr_tail)
+ assert Path(res.glb_path).is_file() and Path(res.glb_path).stat().st_size > 1000
+ assert (stool_ws.artifacts / "build.json").is_file()
+ c = res.census
+ assert c["object_name"] == "Stool"
+ assert [p["name"] for p in c["parts"]] == ["Seat", "Legs", "Stretchers"]
+ assert c["tri_count"] > 500 and c["n_meshes"] == 9
+ assert c["tick_present"] is True
+ assert c["normalised_offset"] is None
+ assert c["unnamed_meshes"] == 0
+ assert "Leg_LB" in c["parts"][1]["children"]
+ assert len(c["materials"]) == 3 # seat + legs + stretchers (distinct objects)
+ # the GLB carries named nodes per part and the bbox matches the authored sizes
+ scene = trimesh.load(res.glb_path, force="scene")
+ names = set(scene.graph.nodes)
+ assert {"Stool", "Seat", "Legs", "Stretchers", "Leg_LB", "Leg_RF"} <= names
+ lo, hi = scene.bounds
+ assert np.allclose(lo, [-0.17, 0.0, -0.17], atol=2e-3)
+ assert np.allclose(hi, [0.17, 0.45, 0.17], atol=2e-3)
+
+
+def test_build_runtime_error_maps_to_file_line(stool_ws: Workspace):
+ p = stool_ws.src / "parts" / "legs.js"
+ p.write_text(p.read_text().replace("const off = 0.13;", "const off = undefinedThing();"))
+ res = ThreeJsRuntime().build(stool_ws)
+ assert not res.ok
+ assert res.error_type == "ReferenceError"
+ assert "undefinedThing" in res.error_message
+ assert res.error_file == "src/parts/legs.js" and res.error_line == 6
+ assert not (stool_ws.artifacts / "object.glb").exists()
+ assert (stool_ws.artifacts / "export_error.json").is_file()
+ assert json.loads((stool_ws.artifacts / "build.json").read_text())["ok"] is False
+
+
+def test_build_syntax_error_located(stool_ws: Workspace):
+ p = stool_ws.src / "parts" / "seat.js"
+ p.write_text(p.read_text() + "\nlet = 1;\n")
+ res = ThreeJsRuntime().build(stool_ws)
+ assert not res.ok and res.error_type == "SyntaxError"
+ assert res.error_file == "src/parts/seat.js" and res.error_line == 13
+
+
+def test_build_contract_error_no_meshes(stool_ws: Workspace):
+ (stool_ws.src / "object.js").write_text("import * as THREE from 'three';\nexport function build(T) { const g = new THREE.Group(); g.name='Empty'; return g; }\n")
+ res = ThreeJsRuntime().build(stool_ws)
+ assert not res.ok and res.error_type == "ContractError" and "no meshes" in res.error_message
+
+
+def test_build_missing_build_export(stool_ws: Workspace):
+ (stool_ws.src / "object.js").write_text("export const x = 1;\n")
+ res = ThreeJsRuntime().build(stool_ws)
+ assert not res.ok and res.error_type == "ContractError" and "export function build" in res.error_message
+
+
+def test_build_normalises_and_records_offset(stool_ws: Workspace):
+ p = stool_ws.src / "object.js"
+ p.write_text(p.read_text().replace("return root;", "root.position.set(0.5, 0.2, 0); return root;"))
+ res = ThreeJsRuntime().build(stool_ws)
+ assert res.ok
+ off = res.census["normalised_offset"]
+ assert off is not None and abs(off[0] + 0.5) < 1e-4 and abs(off[1] + 0.2) < 1e-4
+ assert any("off ground/centre" in w for w in res.census["warnings"])
+ lo, _ = trimesh.load(res.glb_path, force="scene").bounds
+ assert abs(lo[1]) < 2e-3 and abs(lo[0] + 0.17) < 2e-3
+
+
+def test_build_async_build_and_texture_strip(stool_ws: Workspace):
+ (stool_ws.src / "object.js").write_text(
+ "import * as THREE from 'three';\nexport async function build(T) { const g = new THREE.Group(); g.name='Async';\n"
+ " const m = new THREE.Mesh(new THREE.BoxGeometry(0.2,0.2,0.2), new THREE.MeshStandardMaterial({map: new THREE.Texture()}));\n"
+ " m.name='Box'; m.position.y = 0.1; g.add(m); return g; }\n")
+ res = ThreeJsRuntime().build(stool_ws)
+ assert res.ok, res.error_message
+ assert any("texture" in w for w in res.census["warnings"])
+ assert res.census["object_name"] == "Async"
diff --git a/harness/tests/threejs_render/test_lint.py b/harness/tests/threejs_render/test_lint.py
new file mode 100644
index 00000000..6bd5160f
--- /dev/null
+++ b/harness/tests/threejs_render/test_lint.py
@@ -0,0 +1,100 @@
+"""Static lint of three.js object code."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
+from codeverse.languages.threejs import lint as lint_mod
+from codeverse.languages.threejs.lint import lint_workspace
+from codeverse.workspace import Workspace
+
+
+def no_node_syntax(monkeypatch):
+ """Run lint offline: pretend every file parses."""
+ monkeypatch.setattr(lint_mod, "check_syntax", lambda path, node_bin: None)
+
+
+def _msgs(rep, sev=None):
+ return [f.message for f in rep.findings if sev is None or f.severity == sev]
+
+
+def test_clean_workspace_passes(stool_ws: Workspace, no_node_syntax):
+ rep = lint_workspace(stool_ws)
+ assert rep.gate == "lint:threejs"
+ assert rep.passed, rep.findings
+ assert rep.findings == []
+
+
+def test_missing_object_js(tmp_path: Path, no_node_syntax):
+ ws = Workspace(tmp_path)
+ (ws.src / "parts").mkdir(parents=True)
+ rep = lint_workspace(ws)
+ assert not rep.passed
+ assert any("object.js is missing" in m for m in _msgs(rep, Severity.ERROR))
+
+
+def test_forbidden_apis_and_imports(stool_ws: Workspace, no_node_syntax):
+ (stool_ws.src / "parts" / "legs.js").write_text(
+ "import * as THREE from 'three';\nimport x from 'https://cdn.example.com/x.js';\nimport y from 'lodash';\n"
+ "import { q } from './nope.js';\n// document in a comment is fine\nconst s = 'window in a string is fine';\n"
+ "export function buildLegs(THREE_) { fetch('http://x'); const c = document.createElement('canvas');\n"
+ " const r = new THREE.WebGLRenderer(); const cam = new THREE.PerspectiveCamera(); return new THREE.Group(); }\n"
+ )
+ rep = lint_workspace(stool_ws)
+ errs = _msgs(rep, Severity.ERROR)
+ assert not rep.passed
+ assert any("URL 'https://cdn.example.com/x.js'" in m for m in errs)
+ assert any("package 'lodash'" in m for m in errs)
+ assert any("does not exist: './nope.js'" in m for m in errs)
+ assert any("fetch" in m and "legs.js:7" in m for m in errs)
+ assert any("document" in m and "legs.js:7" in m for m in errs)
+ assert any("renderers" in m and "legs.js:8" in m for m in errs)
+ assert any("cameras" in m for m in _msgs(rep, Severity.WARN))
+ # comment/string mentions must not trigger
+ assert not any("legs.js:5" in m or "legs.js:6" in m for m in errs)
+
+
+def test_part_export_name_and_dead_file(stool_ws: Workspace, no_node_syntax):
+ (stool_ws.src / "parts" / "extra.js").write_text("import * as THREE from 'three';\nexport function buildWrong(THREE_) { return new THREE.Group(); }\n")
+ rep = lint_workspace(stool_ws)
+ warns = _msgs(rep, Severity.WARN)
+ assert any("expected `export function buildExtra(THREE)`" in m for m in warns)
+ assert any("not imported by any module" in m for m in warns)
+ (stool_ws.src / "parts" / "extra.js").write_text("export const nothing = 1;\n")
+ rep = lint_workspace(stool_ws)
+ assert any("buildExtra" in m for m in _msgs(rep, Severity.ERROR))
+
+
+def test_object_without_build_export(stool_ws: Workspace, no_node_syntax):
+ (stool_ws.src / "object.js").write_text("import * as THREE from 'three';\nexport function make() {}\n")
+ rep = lint_workspace(stool_ws)
+ assert any("must `export function build(THREE)`" in m for m in _msgs(rep, Severity.ERROR))
+
+
+def test_plan_parts_missing_are_warned(stool_ws: Workspace, no_node_syntax):
+ plan = StaticPlan(object_name="Stool", summary="s", overall_bbox=BBox(center=(0, 0.2, 0), extents=(0.4, 0.45, 0.4)),
+ parts=[PartPlan(name="Seat", role="r", description="d", bbox=BBox(center=(0, 0.43, 0), extents=(0.34, 0.04, 0.34))),
+ PartPlan(name="FootRing", role="r", description="d", bbox=BBox(center=(0, 0.1, 0), extents=(0.3, 0.02, 0.3)))])
+ stool_ws.write_json(stool_ws.plan_path, plan)
+ rep = lint_workspace(stool_ws)
+ assert rep.passed
+ assert any("FootRing has no file src/parts/foot_ring.js" in m for m in _msgs(rep, Severity.WARN))
+
+
+def test_syntax_error_reported_with_line(stool_ws: Workspace):
+ p = stool_ws.src / "parts" / "seat.js"
+ p.write_text(p.read_text() + "\nconst = 5;\n")
+ rep = lint_workspace(stool_ws)
+ assert not rep.passed
+ assert any("seat.js:13" in m and "SyntaxError" in m for m in _msgs(rep, Severity.ERROR))
+
+
+def test_real_syntax_check_on_clean_stool(stool_ws: Workspace):
+ assert lint_workspace(stool_ws).passed
diff --git a/harness/tests/threejs_render/test_node.py b/harness/tests/threejs_render/test_node.py
new file mode 100644
index 00000000..494e3ea3
--- /dev/null
+++ b/harness/tests/threejs_render/test_node.py
@@ -0,0 +1,63 @@
+"""run_node: last-JSON parsing, timeouts, error propagation."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from codeverse.spatial.node import NodeError, parse_last_json, run_node, runtime_js_dir
+
+
+def test_parse_last_json_picks_last_object():
+ out = 'noise\n{"a": 1}\nmore noise\n{"ok": true, "n": 2}\n[1,2]\n'
+ assert parse_last_json(out) == {"ok": True, "n": 2}
+ assert parse_last_json("nothing here") is None
+ assert parse_last_json('{"broken": \n') is None
+
+
+def test_missing_script_raises(tmp_path: Path):
+ with pytest.raises(NodeError):
+ run_node(tmp_path / "nope.mjs", [], timeout_s=5)
+
+
+def test_run_node_echo(tmp_path: Path):
+ script = tmp_path / "echo.mjs"
+ script.write_text("console.log('hello'); console.log(JSON.stringify({ok: true, argv: process.argv.slice(2), np: process.env.NODE_PATH}));")
+ res = run_node(script, ["--x", "1"], timeout_s=20)
+ assert res.rc == 0
+ assert res.last_json["argv"] == ["--x", "1"]
+ assert res.last_json["np"].endswith("runtime_js/node_modules")
+ assert res.duration_ms >= 0
+
+
+def test_run_node_timeout_kills(tmp_path: Path):
+ script = tmp_path / "hang.mjs"
+ script.write_text("setInterval(() => {}, 1000); console.log('started');")
+ with pytest.raises(NodeError) as ei:
+ run_node(script, [], timeout_s=1.5)
+ assert ei.value.result is not None and ei.value.result.timed_out
+
+
+def test_run_node_nonzero_exit(tmp_path: Path):
+ script = tmp_path / "fail.mjs"
+ script.write_text("console.log(JSON.stringify({ok:false, error:{message:'bad thing'}})); process.exit(3);")
+ with pytest.raises(NodeError) as ei:
+ run_node(script, [], timeout_s=20)
+ assert "bad thing" in str(ei.value)
+ assert ei.value.result.rc == 3
+ res = run_node(script, [], timeout_s=20, check=False)
+ assert res.rc == 3 and res.last_json["ok"] is False
+
+
+def test_three_hook_resolves_bare_three(tmp_path: Path):
+ script = tmp_path / "t.mjs"
+ script.write_text("import * as THREE from 'three'; import { RoundedBoxGeometry } from 'three/addons/geometries/RoundedBoxGeometry.js';"
+ "console.log(JSON.stringify({rev: THREE.REVISION, rb: typeof RoundedBoxGeometry}));")
+ res = run_node(script, [], timeout_s=30, three_hook=True)
+ assert res.last_json["rev"] == "182" and res.last_json["rb"] == "function"
+ assert (runtime_js_dir() / "lib" / "resolve_three.mjs").is_file()
diff --git a/harness/tests/threejs_render/test_render.py b/harness/tests/threejs_render/test_render.py
new file mode 100644
index 00000000..ac9b3a38
--- /dev/null
+++ b/harness/tests/threejs_render/test_render.py
@@ -0,0 +1,91 @@
+"""render_glb / render_turntable (node + headless Chrome) and offline guards."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPreset
+from codeverse.spatial import render as render_mod
+from codeverse.spatial.render import RenderError, render_glb, render_turntable
+
+
+def test_render_glb_offline_validation(tmp_path: Path):
+ with pytest.raises(RenderError):
+ render_glb(tmp_path / "missing.glb", tmp_path / "out")
+ fake = tmp_path / "x.glb"
+ fake.write_bytes(b"glTF" + b"\0" * 16)
+ with pytest.raises(RenderError, match="mode"):
+ render_glb(fake, tmp_path / "out", mode="xray")
+ with pytest.raises(RenderError, match="background"):
+ render_glb(fake, tmp_path / "out", background="blue")
+ with pytest.raises(RenderError, match="no views"):
+ render_glb(fake, tmp_path / "out", views=[])
+
+
+def test_cache_key_depends_on_params(tmp_path: Path):
+ glb = tmp_path / "a.glb"
+ glb.write_bytes(b"abc")
+ k1 = render_mod._cache_key(glb, {"mode": "shaded", "w": 1})
+ k2 = render_mod._cache_key(glb, {"mode": "clay", "w": 1})
+ glb.write_bytes(b"abd")
+ k3 = render_mod._cache_key(glb, {"mode": "shaded", "w": 1})
+ assert len({k1, k2, k3}) == 3
+
+
+def test_render_scene_delegates_or_raises(tmp_path: Path):
+ from codeverse.workspace import Workspace
+ try:
+ import codeverse.spatial.render_scene # noqa: F401
+ except ImportError:
+ with pytest.raises(NotImplementedError):
+ render_mod.render_scene(Workspace(tmp_path), tmp_path / "o")
+
+
+def test_render_views_modes_isolate_and_cache(stool_glb: Path, tmp_path: Path):
+ out = tmp_path / "shaded"
+ rs = render_glb(stool_glb, out, views=OBJECT_VIEWS_QUICK, width=256, height=256, use_cache=True)
+ assert [v.name for v in rs.views] == [v.name for v in OBJECT_VIEWS_QUICK]
+ assert rs.renderer and rs.contact_sheet and Path(rs.contact_sheet).is_file()
+ for v in rs.views:
+ assert Path(v.path).is_file() and v.mode == "shaded" and v.camera_position is not None and v.fov == 35
+ with Image.open(v.path) as im:
+ assert im.size == (256, 256)
+ meta = json.loads((out / "views.json").read_text())
+ assert meta["ok"] and len(meta["views"]) == 4
+ # the front view: camera on +Z, looking at the bbox centre
+ front = next(v for v in rs.views if v.name == "front")
+ assert front.camera_position[2] > 0.5 and abs(front.camera_position[0]) < 1e-6
+ # cached re-render lands in a new directory without calling node
+ out2 = tmp_path / "shaded2"
+ rs2 = render_glb(stool_glb, out2, views=OBJECT_VIEWS_QUICK, width=256, height=256)
+ assert json.loads((out2 / "views.json").read_text()).get("from_cache") is True
+ assert rs2.views[0].camera_position == rs.views[0].camera_position
+
+ sil = render_glb(stool_glb, tmp_path / "sil", views=[ViewPreset("front", 0, 8)], mode="silhouette", width=128, height=128, sheet=False)
+ with Image.open(sil.views[0].path) as im:
+ px = list(im.convert("RGB").get_flattened_data()) if hasattr(im, "get_flattened_data") else list(im.convert("RGB").getdata())
+ blacks = sum(1 for p in px if p == (0, 0, 0))
+ whites = sum(1 for p in px if p == (255, 255, 255))
+ assert blacks > 300 and whites > 3000 and blacks + whites > 0.97 * 128 * 128
+ assert sil.contact_sheet is None
+
+ iso = render_glb(stool_glb, tmp_path / "iso", views=[ViewPreset("front", 0, 8)], isolate=["Legs"], width=128, height=128, sheet=False)
+ assert Path(iso.views[0].path).is_file()
+ with pytest.raises(RenderError, match="isolate hid everything|nothing visible"):
+ render_glb(stool_glb, tmp_path / "iso_bad", views=[ViewPreset("front", 0, 8)], isolate=["NotAPart"], width=64, height=64, sheet=False)
+
+ ex = render_glb(stool_glb, tmp_path / "explode", views=[ViewPreset("front", 0, 8)], explode=0.5, mode="clay", width=128, height=128, sheet=False)
+ assert Path(ex.views[0].path).is_file()
+
+
+def test_render_turntable_gif(stool_glb: Path, tmp_path: Path):
+ out = render_turntable(stool_glb, tmp_path / "tt.gif", n=6, width=96, height=96)
+ assert out.suffix == ".gif" and out.is_file()
+ with Image.open(out) as im:
+ assert getattr(im, "n_frames", 1) == 6
diff --git a/harness/tests/threejs_render/test_runtime_js.py b/harness/tests/threejs_render/test_runtime_js.py
new file mode 100644
index 00000000..32bfba2d
--- /dev/null
+++ b/harness/tests/threejs_render/test_runtime_js.py
@@ -0,0 +1,84 @@
+"""Direct tests of the node scripts: export CLI, serve.cjs, gpu_launch.cjs (need node)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from codeverse.spatial.node import NodeError, run_node, runtime_js_dir
+from codeverse.workspace import Workspace
+
+pytestmark = pytest.mark.node
+
+
+def test_export_cli_writes_census_and_error_json(stool_ws: Workspace, tmp_path: Path):
+ rt = runtime_js_dir()
+ res = run_node(rt / "export_glb.mjs", ["--ws", str(stool_ws.root), "--out", "artifacts/o.glb", "--census", "artifacts/c.json"], three_hook=True, timeout_s=60)
+ rec = res.last_json
+ assert rec["ok"] and rec["parts"] == 3 and (stool_ws.root / "artifacts/o.glb").is_file()
+ census = json.loads((stool_ws.root / "artifacts/c.json").read_text())
+ assert set(census) >= {"object_name", "parts", "tri_count", "bbox", "materials", "normalised_offset", "warnings", "tick_present"}
+ assert census["three_revision"] == "182"
+ # error path: unknown entry
+ with pytest.raises(NodeError) as ei:
+ run_node(rt / "export_glb.mjs", ["--ws", str(stool_ws.root), "--entry", "src/nope.js"], three_hook=True, timeout_s=60)
+ err = ei.value.result.last_json["error"]
+ assert err["type"] == "MissingEntry"
+ assert (stool_ws.artifacts / "export_error.json").is_file()
+
+
+def test_serve_and_importmap(tmp_path: Path):
+ script = tmp_path / "s.cjs"
+ root = tmp_path / "root"
+ root.mkdir()
+ (root / "a.glb").write_bytes(b"glTF1234")
+ (root / "sub").mkdir()
+ (root / "sub" / "b.json").write_text("{}")
+ script.write_text(f"""
+const {{ serveDirs, importMapHtml }} = require({json.dumps(str(runtime_js_dir() / 'serve.cjs'))});
+(async () => {{
+ const srv = await serveDirs({{ root: {json.dumps(str(root))}, routes: {{ '/__p.html': {{ body: '<html>hi</html>' }} }} }});
+ const get = async (p) => {{ const r = await fetch(srv.url(p)); return {{ status: r.status, type: r.headers.get('content-type'), len: (await r.arrayBuffer()).byteLength }}; }};
+ const out = {{
+ glb: await get('/a.glb'), json: await get('/sub/b.json'), page: await get('/__p.html'),
+ three: await get('/__runtime/node_modules/three/build/three.module.js'),
+ escape: await get('/../s.cjs'), missing: await get('/nope.png'), fav: await get('/favicon.ico'),
+ importmap: importMapHtml(),
+ }};
+ await srv.close();
+ console.log(JSON.stringify(out));
+}})().catch((e) => {{ console.error(e); process.exit(1); }});
+""")
+ out = run_node(script, [], timeout_s=60).last_json
+ assert out["glb"] == {"status": 200, "type": "model/gltf-binary", "len": 8}
+ assert out["json"]["type"] == "application/json"
+ assert out["page"]["status"] == 200 and "text/html" in out["page"]["type"]
+ assert out["three"]["status"] == 200 and out["three"]["len"] > 100000 and out["three"]["type"] == "text/javascript"
+ assert out["escape"]["status"] == 404 and out["missing"]["status"] == 404 and out["fav"]["status"] == 204
+ im = json.loads(out["importmap"].split(">", 1)[1].rsplit("<", 1)[0])["imports"]
+ assert im["three"].startswith("/__runtime/") and im["three/addons/"].endswith("/examples/jsm/")
+ assert "http" not in json.dumps(im)
+
+
+def test_gpu_launch_probe(tmp_path: Path):
+ script = tmp_path / "g.cjs"
+ script.write_text(f"""
+const {{ launchBrowser, rendererInfo }} = require({json.dumps(str(runtime_js_dir() / 'gpu_launch.cjs'))});
+(async () => {{
+ const t0 = Date.now();
+ const {{ browser, gpu, renderer }} = await launchBrowser({{ gpu: process.env.T_GPU || 'auto' }});
+ const probe = await rendererInfo(browser);
+ await browser.close();
+ console.log(JSON.stringify({{ gpu, renderer, probe, ms: Date.now() - t0 }}));
+}})().catch((e) => {{ console.error(e); process.exit(1); }});
+""")
+ auto = run_node(script, [], timeout_s=120).last_json
+ assert auto["renderer"] and auto["probe"]
+ if auto["gpu"]:
+ assert "swiftshader" not in auto["renderer"].lower()
+ off = run_node(script, [], timeout_s=120, env_extra={"T_GPU": "off"}).last_json
+ assert off["gpu"] is False and "swiftshader" in off["probe"].lower()
+ with pytest.raises(NodeError):
+ run_node(script, [], timeout_s=60, env_extra={"T_GPU": "bogus"})
diff --git a/harness/tests/threejs_render/test_sheet.py b/harness/tests/threejs_render/test_sheet.py
new file mode 100644
index 00000000..806e0a59
--- /dev/null
+++ b/harness/tests/threejs_render/test_sheet.py
@@ -0,0 +1,50 @@
+"""contact_sheet: layout, labels, missing tiles, determinism."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from codeverse.spatial.sheet import LABEL_H, PAD, contact_sheet
+
+
+def _png(path: Path, color, size=(120, 80)):
+ Image.new("RGB", size, color).save(path)
+ return path
+
+
+def test_sheet_layout_and_labels(tmp_path: Path):
+ imgs = [(f"v{i}", _png(tmp_path / f"{i}.png", (i * 40, 100, 200))) for i in range(5)]
+ out = contact_sheet(imgs, tmp_path / "sheet.png", cols=3, tile=100)
+ with Image.open(out) as im:
+ assert im.size == (3 * (100 + PAD) + PAD, 2 * (100 + LABEL_H + PAD) + PAD)
+ # label strip under the first tile is dark
+ assert im.getpixel((PAD + 2, PAD + 100 + 2))[0] < 60
+ # the first tile centre carries the first image colour (letterboxed)
+ assert im.getpixel((PAD + 50, PAD + 50)) == (0, 100, 200)
+
+
+def test_sheet_missing_image_is_grey_tile(tmp_path: Path):
+ out = contact_sheet([("ok", _png(tmp_path / "a.png", (10, 200, 10))), ("gone", tmp_path / "missing.png")], tmp_path / "s.png", cols=2, tile=64)
+ with Image.open(out) as im:
+ assert im.getpixel((PAD + 64 + PAD + 40, PAD + 40)) == (200, 200, 200)
+
+
+def test_sheet_deterministic(tmp_path: Path):
+ imgs = [("a", _png(tmp_path / "a.png", (1, 2, 3))), ("b", _png(tmp_path / "b.png", (3, 2, 1)))]
+ a = contact_sheet(imgs, tmp_path / "s1.png", cols=2, tile=64).read_bytes()
+ b = contact_sheet(imgs, tmp_path / "s2.png", cols=2, tile=64).read_bytes()
+ assert a == b
+
+
+def test_sheet_no_label(tmp_path: Path):
+ out = contact_sheet([("a", _png(tmp_path / "a.png", (1, 2, 3)))], tmp_path / "s.png", cols=4, tile=50, label=False)
+ with Image.open(out) as im:
+ assert im.size == (50 + 2 * PAD, 50 + 2 * PAD)
+
+
+def test_sheet_empty_raises(tmp_path: Path):
+ with pytest.raises(ValueError):
+ contact_sheet([], tmp_path / "s.png")
diff --git a/harness/tests/threejs_render/test_skeleton.py b/harness/tests/threejs_render/test_skeleton.py
new file mode 100644
index 00000000..73791090
--- /dev/null
+++ b/harness/tests/threejs_render/test_skeleton.py
@@ -0,0 +1,62 @@
+"""Skeleton generation from a StaticPlan."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from codeverse.contracts.plan import BBox, PartPlan, StaticPlan
+from codeverse.languages.threejs.runtime import ThreeJsRuntime
+from codeverse.languages.threejs.skeleton import write_skeleton
+from codeverse.workspace import Workspace
+
+
+def _plan() -> StaticPlan:
+ return StaticPlan(
+ object_name="bar stool", summary="s", overall_bbox=BBox(center=(0, 0.35, 0), extents=(0.4, 0.7, 0.4)),
+ parts=[
+ PartPlan(name="Seat Cushion", role="seat", description="round seat", bbox=BBox(center=(0, 0.68, 0), extents=(0.36, 0.04, 0.36)), material="leather"),
+ PartPlan(name="LegFrame", role="legs", description="four legs", bbox=BBox(center=(0, 0.33, 0), extents=(0.34, 0.66, 0.34)), attach_to="Seat Cushion"),
+ ],
+ )
+
+
+def test_skeleton_files_and_contents(tmp_path: Path):
+ ws = Workspace(tmp_path / "ws")
+ written = write_skeleton(ws, _plan())
+ rel = sorted(str(p.relative_to(ws.root)) for p in written)
+ assert rel == ["src/object.js", "src/package.json", "src/parts/leg_frame.js", "src/parts/seat_cushion.js"]
+ obj = (ws.src / "object.js").read_text()
+ assert "export function build(THREE_)" in obj
+ assert "import { buildSeatCushion } from './parts/seat_cushion.js';" in obj
+ assert "root.name = 'BarStool';" in obj
+ seat = (ws.src / "parts" / "seat_cushion.js").read_text()
+ assert "export function buildSeatCushion(THREE_)" in seat
+ assert "group.name = 'SeatCushion';" in seat
+ assert "RoundedBoxGeometry" in seat and "ExtrudeGeometry" in seat
+ assert "Material: leather" in seat
+ assert '"type": "module"' in (ws.src / "package.json").read_text()
+
+
+def test_skeleton_never_overwrites(tmp_path: Path):
+ ws = Workspace(tmp_path / "ws")
+ write_skeleton(ws, _plan())
+ (ws.src / "parts" / "seat_cushion.js").write_text("// mine\n")
+ again = write_skeleton(ws, _plan())
+ assert again == []
+ assert (ws.src / "parts" / "seat_cushion.js").read_text() == "// mine\n"
+
+
+def test_runtime_protocol_surface():
+ rt = ThreeJsRuntime()
+ assert rt.language.value == "threejs"
+ assert rt.entry_globs == ("src/object.js", "src/parts/*.js")
+ doc = rt.contract_doc()
+ assert "build" in doc and "three" in doc.lower()
+ assert rt.cookbook_path().name == "cookbook.md"
+
+
+def test_skeleton_rejects_non_static_plan(tmp_path: Path):
+ with pytest.raises(TypeError):
+ write_skeleton(Workspace(tmp_path), object()) # type: ignore[arg-type]
diff --git a/harness/tests/urdf_joints/__init__.py b/harness/tests/urdf_joints/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/urdf_joints/conftest.py b/harness/tests/urdf_joints/conftest.py
new file mode 100644
index 00000000..8ffadc20
--- /dev/null
+++ b/harness/tests/urdf_joints/conftest.py
@@ -0,0 +1,86 @@
+"""Shared fixtures: synthetic robots (box primitives or trimesh-written GLBs) and plans."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+import trimesh
+
+from codeverse.contracts.plan import ArticulatedPlan, BBox, JointPlan, PartPlan
+
+CABINET_PRIMS = """<robot name="cab">
+<link name="body"><visual><origin xyz="0 0 0.4"/><geometry><box size="0.6 0.4 0.8"/></geometry></visual></link>
+<link name="door"><visual><origin xyz="0.29 -0.01 0.4"/><geometry><box size="0.58 0.02 0.78"/></geometry></visual></link>
+<joint name="hinge" type="revolute"><parent link="body"/><child link="door"/>
+ <origin xyz="-0.29 -0.2 0" rpy="0 0 0"/><axis xyz="0 0 {axis_z}"/><limit lower="0" upper="1.57" effort="10" velocity="1"/></joint>
+</robot>"""
+
+
+def write_prims_robot(path: Path, *, axis_z: int = -1) -> Path:
+ path.write_text(CABINET_PRIMS.format(axis_z=axis_z))
+ return path
+
+
+def box_glb(path: Path, center, size) -> Path:
+ m = trimesh.creation.box(size)
+ m.apply_translation(center)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(m.export(file_type="glb"))
+ return path
+
+
+def write_mesh_robot(root: Path, *, door_visual_xyz: str = "0.29 0.2 0", handle: bool = False) -> tuple[Path, Path]:
+ """URDF in the enforced convention + world-coordinate GLB meshes (like the wrapper writes)."""
+ meshes = root / "meshes"
+ box_glb(meshes / "body.glb", (0, 0, 0.4), (0.6, 0.4, 0.8))
+ box_glb(meshes / "door.glb", (0, -0.21, 0.4), (0.58, 0.02, 0.78))
+ links = f"""
+<link name="body"><visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/body.glb"/></geometry></visual>
+ <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/body.glb"/></geometry></collision></link>
+<link name="door"><visual><origin xyz="{door_visual_xyz}" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></visual>
+ <collision><origin xyz="{door_visual_xyz}" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></collision></link>
+<joint name="hinge" type="revolute"><parent link="body"/><child link="door"/>
+ <origin xyz="-0.29 -0.2 0" rpy="0 0 0"/><axis xyz="0 0 -1"/><limit lower="0" upper="1.57" effort="10" velocity="1"/></joint>"""
+ if handle:
+ box_glb(meshes / "handle.glb", (0.2, -0.24, 0.4), (0.02, 0.04, 0.1))
+ links += """
+<link name="handle"><visual><origin xyz="-0.2 0.24 -0.4" rpy="0 0 0"/><geometry><mesh filename="meshes/handle.glb"/></geometry></visual>
+ <collision><origin xyz="-0.2 0.24 -0.4" rpy="0 0 0"/><geometry><mesh filename="meshes/handle.glb"/></geometry></collision></link>
+<joint name="handle_mount" type="fixed"><parent link="door"/><child link="handle"/><origin xyz="0.49 -0.04 0.4" rpy="0 0 0"/></joint>"""
+ urdf = root / "robot.urdf"
+ urdf.write_text(f'<robot name="cab">{links}\n</robot>\n')
+ return urdf, meshes
+
+
+def cabinet_plan() -> ArticulatedPlan:
+ return ArticulatedPlan(
+ object_name="Cabinet", summary="cabinet with a hinged door",
+ overall_bbox=BBox(center=(0, -0.01, 0.4), extents=(0.6, 0.42, 0.8)), root_link="Body",
+ parts=[
+ PartPlan(name="Body", role="carcass", description="hollow box", bbox=BBox(center=(0, 0, 0.4), extents=(0.6, 0.4, 0.8))),
+ PartPlan(name="Door", role="front door", description="panel", bbox=BBox(center=(0, -0.21, 0.4), extents=(0.58, 0.02, 0.78))),
+ PartPlan(name="Handle", role="door handle", description="bar", bbox=BBox(center=(0.2, -0.24, 0.4), extents=(0.02, 0.04, 0.1)),
+ attach_to="Door"),
+ ],
+ joints=[
+ JointPlan(name="hinge", type="revolute", parent="Body", child="Door", axis=(0, 0, -1), pivot=(-0.29, -0.2, 0),
+ lower=0.0, upper=1.57, motion="door swings open to the front"),
+ JointPlan(name="handle_mount", type="fixed", parent="Door", child="Handle", axis=(0, 0, 1), pivot=(0.2, -0.24, 0.4)),
+ ],
+ )
+
+
+def drawer_plan() -> ArticulatedPlan:
+ return ArticulatedPlan(
+ object_name="Nightstand", summary="nightstand with a drawer",
+ overall_bbox=BBox(center=(0, 0, 0.3), extents=(0.5, 0.5, 0.6)), root_link="Carcass",
+ parts=[
+ PartPlan(name="Carcass", role="body", description="box", bbox=BBox(center=(0, 0.025, 0.3), extents=(0.5, 0.45, 0.6))),
+ PartPlan(name="Drawer", role="drawer", description="front panel (placeholder)", bbox=BBox(center=(0, -0.21, 0.45), extents=(0.44, 0.02, 0.2))),
+ ],
+ joints=[JointPlan(name="slide", type="prismatic", parent="Carcass", child="Drawer", axis=(0, -1, 0),
+ pivot=(0, -0.21, 0.45), lower=0.0, upper=0.3, motion="slides out the front")],
+ )
diff --git a/harness/tests/urdf_joints/test_consistency.py b/harness/tests/urdf_joints/test_consistency.py
new file mode 100644
index 00000000..d0fe8565
--- /dev/null
+++ b/harness/tests/urdf_joints/test_consistency.py
@@ -0,0 +1,31 @@
+"""FK ↔ authored bbox consistency check."""
+
+from __future__ import annotations
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.languages.urdf.consistency import check_fk_consistency
+from codeverse.spatial.joints import load_urdf
+from tests.urdf_joints.conftest import write_mesh_robot
+
+CENSUS = {"body": {"bbox_min": [-0.3, -0.2, 0.0], "bbox_max": [0.3, 0.2, 0.8]},
+ "door": {"bbox_min": [-0.29, -0.22, 0.01], "bbox_max": [0.29, -0.2, 0.79]}}
+
+
+def test_consistent(tmp_path):
+ urdf, meshes = write_mesh_robot(tmp_path)
+ assert check_fk_consistency(load_urdf(urdf, meshes), CENSUS) == []
+
+
+def test_sign_error_reports_exact_fix(tmp_path):
+ urdf, meshes = write_mesh_robot(tmp_path, door_visual_xyz="-0.29 -0.2 0")
+ f = check_fk_consistency(load_urdf(urdf, meshes), CENSUS)
+ assert len(f) == 1 and f[0].severity == Severity.ERROR and f[0].target == "door"
+ assert 'xyz="0.29 0.2 0"' in f[0].fix_hint
+ assert f[0].data["corrected_visual_origin"]["xyz"] == [0.29, 0.2, 0.0]
+ assert f[0].data["error_m"] > 0.5
+
+
+def test_missing_census_row(tmp_path):
+ urdf, meshes = write_mesh_robot(tmp_path)
+ f = check_fk_consistency(load_urdf(urdf, meshes), {"body": CENSUS["body"]})
+ assert [x.target for x in f] == ["door"] and "no authored mesh" in f[0].message
diff --git a/harness/tests/urdf_joints/test_export.py b/harness/tests/urdf_joints/test_export.py
new file mode 100644
index 00000000..b0f0b20b
--- /dev/null
+++ b/harness/tests/urdf_joints/test_export.py
@@ -0,0 +1,113 @@
+"""urdf_to_glb hierarchy/extras and the articulation sheet composer."""
+
+from __future__ import annotations
+
+import json
+import struct
+
+import trimesh
+from PIL import Image
+
+from codeverse.contracts.artifacts import RenderSet, RenderView
+from codeverse.spatial.joints import ARTICULATION_SHEET_NAME, load_urdf, render_poses, urdf_to_glb
+from codeverse.spatial.joints_export import make_sheet
+from tests.urdf_joints.conftest import write_mesh_robot
+
+
+def _gltf_json(path):
+ data = path.read_bytes()
+ ln = struct.unpack("<I", data[12:16])[0]
+ return json.loads(data[20:20 + ln])
+
+
+def test_urdf_to_glb_hierarchy_and_extras(tmp_path):
+ urdf, meshes = write_mesh_robot(tmp_path, handle=True)
+ r = load_urdf(urdf, meshes)
+ glb = urdf_to_glb(r, tmp_path / "object.glb")
+ js = _gltf_json(glb)
+ names = {n["name"]: n for n in js["nodes"]}
+ assert {"cab", "body", "door", "handle"} <= set(names)
+ assert "joint" in names["door"]["extras"] and names["door"]["extras"]["joint"]["type"] == "revolute"
+ assert "extras" not in names["body"] or "joint" not in names["body"].get("extras", {})
+ scene_extras = js["scenes"][0]["extras"]
+ assert [j["name"] for j in scene_extras["joints"]] == ["hinge", "handle_mount"]
+ assert scene_extras["links"] == ["body", "door", "handle"]
+ # hierarchy: cab → body → door → handle
+ idx = {n["name"]: i for i, n in enumerate(js["nodes"])}
+ assert idx["door"] in names["body"]["children"] and idx["handle"] in names["door"]["children"]
+ # canonical frame: Y-up (ground at y=0), door at +z front
+ s = trimesh.load(glb)
+ assert abs(s.bounds[0][1]) < 1e-6 and s.bounds[1][1] > 0.79
+ assert s.bounds[1][2] > 0.2
+ # posed export moves the door
+ glb2 = urdf_to_glb(r, tmp_path / "open.glb", {"hinge": 1.57})
+ s2 = trimesh.load(glb2)
+ assert s2.bounds[1][2] > 0.7 # door swung out to +z (front)
+ assert _gltf_json(glb2)["scenes"][0]["extras"]["pose"] == {"hinge": 1.57}
+
+
+def test_make_sheet_and_render_poses_with_fake_renderer(tmp_path):
+ urdf, meshes = write_mesh_robot(tmp_path)
+ r = load_urdf(urdf, meshes)
+ calls = []
+
+ def fake_renderer(glb, out_dir, *, views, width, height, sheet):
+ out_dir.mkdir(parents=True, exist_ok=True)
+ calls.append(glb)
+ rs = RenderSet(renderer="fake")
+ for v in views:
+ p = out_dir / f"view_{v.name}.png"
+ Image.new("RGB", (32, 32), "gray").save(p)
+ rs.views.append(RenderView(name=v.name, path=str(p)))
+ return rs
+
+ out = render_poses(r, tmp_path / "ren", renderer=fake_renderer)
+ assert [label for label, _ in out] == ["rest", "hinge@upper"]
+ assert len(calls) == 2 and all(c.exists() for c in calls)
+ sheet = tmp_path / "ren" / ARTICULATION_SHEET_NAME
+ assert sheet.is_file() and Image.open(sheet).size[0] > 32
+
+
+def test_make_sheet_labels(tmp_path):
+ imgs = []
+ for i in range(3):
+ p = tmp_path / f"{i}.png"
+ Image.new("RGB", (64, 48), (i * 50, 0, 0)).save(p)
+ imgs.append((f"img{i}", p))
+ out = make_sheet(imgs, tmp_path / "s.png", cols=2, tile=64)
+ im = Image.open(out)
+ assert im.size == (128, 2 * (64 + 22))
+
+
+def test_multi_material_link_keeps_materials(tmp_path):
+ from tests.urdf_joints.conftest import write_mesh_robot
+
+ urdf, meshes = write_mesh_robot(tmp_path)
+ a = trimesh.creation.box((0.1, 0.1, 0.1))
+ a.visual = trimesh.visual.TextureVisuals(material=trimesh.visual.material.PBRMaterial(name="wood", baseColorFactor=[200, 150, 100, 255]))
+ b = trimesh.creation.box((0.05, 0.05, 0.3))
+ b.apply_translation((0, 0, 0.3))
+ b.visual = trimesh.visual.TextureVisuals(material=trimesh.visual.material.PBRMaterial(name="metal", baseColorFactor=[200, 200, 210, 255]))
+ (meshes / "body.glb").write_bytes(trimesh.Scene([a, b]).export(file_type="glb"))
+ from codeverse.spatial.joints import load_urdf as _load
+
+ r = _load(urdf, meshes)
+ assert len(r.links["body"].submeshes) == 2 and len(r.links["body"].mesh.split(only_watertight=False)) == 2
+ glb = urdf_to_glb(r, tmp_path / "mm.glb")
+ s = trimesh.load(glb)
+ names = {k: getattr(getattr(g.visual, "material", None), "name", None) for k, g in s.geometry.items()}
+ assert {names["body__0"], names["body__1"]} == {"wood", "metal"}
+ assert sorted(n for n in [e[1] for e in s.graph.to_edgelist()] if n.startswith("body")) == ["body", "body__0", "body__1"]
+
+
+def test_joint_sweep_observation_offline(tmp_path):
+ from codeverse.spatial.joints import joint_sweep_observation
+ from codeverse.workspace import Workspace
+ from tests.urdf_joints.conftest import write_mesh_robot
+
+ ws = Workspace(tmp_path / "ws").create()
+ obs = joint_sweep_observation(ws, render=False)
+ assert not obs.ok and "run `build`" in obs.text
+ write_mesh_robot(ws.artifacts)
+ obs = joint_sweep_observation(ws, render=False, joint="hinge", expected_direction="front")
+ assert obs.ok and obs.numbers["max_penetration_m"] == 0.0 and obs.numbers["motion_check"]["ok"]
diff --git a/harness/tests/urdf_joints/test_joints_model.py b/harness/tests/urdf_joints/test_joints_model.py
new file mode 100644
index 00000000..9aa91916
--- /dev/null
+++ b/harness/tests/urdf_joints/test_joints_model.py
@@ -0,0 +1,95 @@
+"""load_urdf / fk / pose sampling (offline, primitives + trimesh-written GLBs)."""
+
+from __future__ import annotations
+
+import math
+
+import numpy as np
+import pytest
+
+from codeverse.spatial.joints import (
+ UrdfError,
+ fk,
+ limit_poses,
+ link_world_meshes,
+ load_urdf,
+ pose_label,
+ pose_samples,
+)
+from codeverse.spatial.joints_model import (
+ invert_transform,
+ make_transform,
+ matrix_to_rpy,
+ rpy_to_matrix,
+)
+from tests.urdf_joints.conftest import write_mesh_robot, write_prims_robot
+
+
+def test_rpy_roundtrip_and_inverse():
+ for rpy in [(0, 0, 0), (0.3, -0.2, 1.1), (-1.0, 0.5, -2.0)]:
+ R = rpy_to_matrix(rpy)
+ assert np.allclose(R @ R.T, np.eye(3))
+ assert np.allclose(rpy_to_matrix(matrix_to_rpy(R)), R, atol=1e-9)
+ T = make_transform((1, 2, 3), (0.3, 0.2, 0.1))
+ assert np.allclose(T @ invert_transform(T), np.eye(4))
+
+
+def test_load_prims_and_fk(tmp_path):
+ r = load_urdf(write_prims_robot(tmp_path / "cab.urdf"))
+ assert r.root == "body" and r.link_order() == ["body", "door"]
+ assert r.joints["hinge"].type == "revolute" and r.joints["hinge"].upper == 1.57
+ T = fk(r, {"hinge": math.pi / 2})["door"]
+ # axis -z: +90° about -z maps +x → -y
+ assert np.allclose(T[:3, 3], [-0.29, -0.2, 0])
+ assert np.allclose(T[:3, :3] @ [1, 0, 0], [0, -1, 0], atol=1e-9)
+ with pytest.raises(UrdfError):
+ fk(r, {"nope": 1.0})
+
+
+def test_mesh_robot_world_placement(tmp_path):
+ urdf, meshes = write_mesh_robot(tmp_path, handle=True)
+ r = load_urdf(urdf, meshes)
+ wm = link_world_meshes(r)
+ assert np.allclose(wm["door"].bounds, [[-0.29, -0.22, 0.01], [0.29, -0.2, 0.79]], atol=1e-6)
+ assert np.allclose(wm["handle"].bounds, [[0.19, -0.26, 0.35], [0.21, -0.22, 0.45]], atol=1e-6)
+ # merged vertices → real topology
+ assert r.links["body"].mesh.is_watertight
+ # the handle follows the door
+ wm2 = link_world_meshes(r, {"hinge": math.pi / 2})
+ assert wm2["handle"].centroid[1] < -0.5
+
+
+def test_load_errors(tmp_path):
+ p = tmp_path / "bad.urdf"
+ p.write_text("<robot name='x'><link name='a'/><link name='b'/></robot>")
+ with pytest.raises(UrdfError, match="exactly one root"):
+ load_urdf(p)
+ p.write_text("<robot name='x'><link name='a'/><link name='b'/><joint name='j' type='revolute'><parent link='a'/><child link='b'/></joint></robot>")
+ with pytest.raises(UrdfError, match="limit"):
+ load_urdf(p)
+ p.write_text("<robot name='x'><link name='a'/><link name='b'/><joint name='j' type='fixed'><parent link='a'/><child link='zz'/></joint></robot>")
+ with pytest.raises(UrdfError, match="unknown"):
+ load_urdf(p)
+ p.write_text("<robot name='x'><link name='a'><visual><geometry><mesh filename='meshes/nope.glb'/></geometry></visual></link></robot>")
+ with pytest.raises(UrdfError, match="not found"):
+ load_urdf(p)
+
+
+def test_pose_samples_and_labels(tmp_path):
+ r = load_urdf(write_prims_robot(tmp_path / "cab.urdf"))
+ poses = pose_samples(r, n_random=4, seed=1)
+ labels = [pose_label(r, q) for q in poses]
+ assert labels[:3] == ["rest", "hinge@mid", "hinge@upper"] # single joint → no random combos
+ assert [label for label, _ in limit_poses(r)] == ["rest", "hinge@upper"]
+ # continuous joint sampling
+ p = tmp_path / "wheel.urdf"
+ p.write_text("<robot name='w'><link name='a'/><link name='b'/><joint name='spin' type='continuous'><parent link='a'/><child link='b'/><axis xyz='0 1 0'/></joint>"
+ "<link name='c'/><joint name='s' type='prismatic'><parent link='a'/><child link='c'/><axis xyz='1 0 0'/><limit lower='-0.1' upper='0.2' effort='1' velocity='1'/></joint></robot>")
+ r2 = load_urdf(p)
+ poses2 = pose_samples(r2, n_random=3, seed=0)
+ vals = sorted(q["spin"] for q in poses2 if set(q) == {"spin"})
+ assert np.allclose(vals, [-math.pi / 2, math.pi / 2, math.pi])
+ assert sum(1 for q in poses2 if len(q) == 2) == 3
+ for q in poses2:
+ if "s" in q:
+ assert -0.1 - 1e-9 <= q["s"] <= 0.2 + 1e-9
diff --git a/harness/tests/urdf_joints/test_lint.py b/harness/tests/urdf_joints/test_lint.py
new file mode 100644
index 00000000..749c8870
--- /dev/null
+++ b/harness/tests/urdf_joints/test_lint.py
@@ -0,0 +1,128 @@
+"""URDF + model.py lint rules."""
+
+from __future__ import annotations
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.languages.urdf.lint import lint_model_text, lint_urdf_text, lint_workspace
+from codeverse.workspace import Workspace
+
+GOOD = """<?xml version="1.0"?>
+<robot name="cab">
+ <link name="body">
+ <visual><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/body.glb"/></geometry></visual>
+ <collision><origin xyz="0 0 0" rpy="0 0 0"/><geometry><mesh filename="meshes/body.glb"/></geometry></collision>
+ </link>
+ <link name="door">
+ <visual><origin xyz="0.29 0.2 0" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></visual>
+ <collision><origin xyz="0.29 0.2 0" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></collision>
+ </link>
+ <joint name="hinge" type="revolute">
+ <parent link="body"/><child link="door"/>
+ <origin xyz="-0.29 -0.2 0" rpy="0 0 0"/><axis xyz="0 0 -1"/>
+ <limit lower="0" upper="1.57" effort="10" velocity="1"/>
+ </joint>
+</robot>
+"""
+MODEL = 'import bpy\nbpy.ops.mesh.primitive_cube_add()\nbpy.context.active_object.name = "body"\nd = bpy.data.objects.new("door", None)\n'
+
+
+def _msgs(findings, sev=None):
+ return [f.message for f in findings if sev is None or f.severity == sev]
+
+
+def test_good_urdf_is_clean():
+ f, links = lint_urdf_text(GOOD)
+ assert f == [] and links == ["body", "door"]
+
+
+def test_xml_and_structure_errors():
+ f, _ = lint_urdf_text("<robot name='x'><link name='a'>")
+ assert f[0].severity == Severity.ERROR and "well-formed" in f[0].message and f[0].data.get("line") == 1
+ f, _ = lint_urdf_text("<model/>")
+ assert "must be <robot>" in f[0].message
+ f, links = lint_urdf_text("<robot name='x'></robot>")
+ assert "no <link>" in f[0].message and links == []
+
+
+def test_tree_rules():
+ two_roots = GOOD.replace('<joint name="hinge"', '<link name="x"/><joint name="hinge"')
+ f, _ = lint_urdf_text(two_roots)
+ assert any("exactly one root" in m for m in _msgs(f, Severity.ERROR))
+ dup = GOOD.replace("</robot>", '<joint name="j2" type="fixed"><parent link="body"/><child link="door"/></joint></robot>')
+ f, _ = lint_urdf_text(dup)
+ assert any("child of two joints" in m for m in _msgs(f, Severity.ERROR))
+ cyc = GOOD.replace("</robot>", '<link name="c"><visual><geometry><mesh filename="meshes/c.glb"/></geometry></visual></link>'
+ '<link name="d"><visual><geometry><mesh filename="meshes/d.glb"/></geometry></visual></link>'
+ '<joint name="j3" type="fixed"><parent link="c"/><child link="d"/></joint>'
+ '<joint name="j4" type="fixed"><parent link="d"/><child link="c"/></joint></robot>')
+ f, _ = lint_urdf_text(cyc)
+ assert any("does not reach the root" in m for m in _msgs(f, Severity.ERROR))
+ unknown = GOOD.replace('<child link="door"/>', '<child link="dor"/>')
+ f, _ = lint_urdf_text(unknown)
+ assert any("does not exist" in m for m in _msgs(f, Severity.ERROR))
+ same = GOOD.replace('<parent link="body"/>', '<parent link="door"/>')
+ f, _ = lint_urdf_text(same)
+ assert any("parent == child" in m for m in _msgs(f, Severity.ERROR))
+
+
+def test_joint_rules():
+ f, _ = lint_urdf_text(GOOD.replace('<limit lower="0" upper="1.57" effort="10" velocity="1"/>', ""))
+ assert any("need <limit" in m for m in _msgs(f, Severity.ERROR))
+ f, _ = lint_urdf_text(GOOD.replace('lower="0" upper="1.57"', 'lower="1" upper="0"'))
+ assert any("upper 0.0 < lower 1.0" in m for m in _msgs(f, Severity.ERROR))
+ f, _ = lint_urdf_text(GOOD.replace('<axis xyz="0 0 -1"/>', '<axis xyz="0 0 0"/>'))
+ assert any("zero axis" in m for m in _msgs(f, Severity.ERROR))
+ f, _ = lint_urdf_text(GOOD.replace('<axis xyz="0 0 -1"/>', '<axis xyz="0 0 -2"/>'))
+ w = [x for x in f if "not unit" in x.message]
+ assert w and w[0].severity == Severity.WARN and 'xyz="0 0 -1"' in w[0].fix_hint
+ f, _ = lint_urdf_text(GOOD.replace('type="revolute"', 'type="continuous"'))
+ assert any("continuous joints have no lower/upper" in m for m in _msgs(f, Severity.WARN))
+ f, _ = lint_urdf_text(GOOD.replace('type="revolute"', 'type="hinge"'))
+ assert any("must be one of" in m for m in _msgs(f, Severity.ERROR))
+ f, _ = lint_urdf_text(GOOD.replace('<origin xyz="-0.29 -0.2 0" rpy="0 0 0"/>', '<origin xyz="-0.29 -0.2" rpy="0 0 0"/>'))
+ assert any("3 finite numbers" in m for m in _msgs(f, Severity.ERROR))
+ f, _ = lint_urdf_text(GOOD.replace('<axis xyz="0 0 -1"/>', ""))
+ assert any("no <axis>" in m for m in _msgs(f, Severity.WARN))
+
+
+def test_link_rules():
+ f, _ = lint_urdf_text(GOOD.replace('filename="meshes/door.glb"', 'filename="door.glb"'))
+ e = [x for x in f if "mesh filename" in x.message]
+ assert e and e[0].severity == Severity.ERROR and "meshes/door.glb" in e[0].fix_hint
+ f, _ = lint_urdf_text(GOOD.replace('<mesh filename="meshes/door.glb"/>', '<box size="1 1 1"/>'))
+ assert any("must be a <mesh>" in m for m in _msgs(f, Severity.ERROR))
+ f, _ = lint_urdf_text(GOOD.replace('<collision><origin xyz="0.29 0.2 0" rpy="0 0 0"/><geometry><mesh filename="meshes/door.glb"/></geometry></collision>', ""))
+ assert any("no <collision>" in m for m in _msgs(f, Severity.WARN))
+ f, _ = lint_urdf_text(GOOD.replace('<collision><origin xyz="0.29 0.2 0"', '<collision><origin xyz="0.3 0.2 0"'))
+ assert any("differs from <visual>" in m for m in _msgs(f, Severity.WARN))
+ f, _ = lint_urdf_text(GOOD.replace('name="door"', 'name="DoorOpen"').replace('link="door"', 'link="DoorOpen"').replace("meshes/door.glb", "meshes/DoorOpen.glb"))
+ msgs = _msgs(f, Severity.WARN)
+ assert any("snake_case" in m for m in msgs) and any("state word" in m for m in msgs)
+ f, _ = lint_urdf_text(GOOD.replace('<link name="door">', '<link name="door"><visual><geometry><mesh filename="meshes/door.glb"/></geometry></visual>'))
+ assert any("2 <visual>" in m for m in _msgs(f, Severity.ERROR))
+
+
+def test_model_lint():
+ f = lint_model_text(MODEL, ["body", "door", "lid"])
+ assert [x.severity for x in f] == [Severity.WARN] and "lid" in f[0].message
+ f = lint_model_text("import bpy, subprocess\nbpy.ops.wm.save_mainfile()\nbpy.ops.render.render()\nsys.exit()\nbpy.ops.object.camera_add()\n", [])
+ msgs = _msgs(f, Severity.ERROR)
+ assert any("subprocess" in m for m in msgs) and any("bpy.ops.wm.save_mainfile" in m for m in msgs)
+ assert any("render" in m for m in msgs) and any("sys.exit" in m for m in msgs)
+ assert any("camera" in m for m in _msgs(f, Severity.WARN))
+ f = lint_model_text("x = (1,\n", [])
+ assert f[0].severity == Severity.ERROR and "SyntaxError" in f[0].message and f[0].data["line"] == 1
+ f = lint_model_text("import math\n", [])
+ assert any("never imports bpy" in m for m in _msgs(f, Severity.ERROR))
+ f = lint_model_text("import bpy\nfrom codeverse.x import y\n", [])
+ assert any("harness" in m for m in _msgs(f, Severity.ERROR))
+
+
+def test_lint_workspace(tmp_path):
+ ws = Workspace(tmp_path / "ws").create()
+ rep = lint_workspace(ws)
+ assert not rep.passed and rep.gate == "lint:urdf" and len(rep.errors) == 2
+ (ws.src / "robot.urdf").write_text(GOOD)
+ (ws.src / "model.py").write_text(MODEL)
+ rep = lint_workspace(ws)
+ assert rep.passed and rep.findings == []
diff --git a/harness/tests/urdf_joints/test_live_blender.py b/harness/tests/urdf_joints/test_live_blender.py
new file mode 100644
index 00000000..cc5dc5fe
--- /dev/null
+++ b/harness/tests/urdf_joints/test_live_blender.py
@@ -0,0 +1,94 @@
+"""Real Blender builds (marked ``blender``): cabinet+door, drawer, bad pivot, yourdfpy, sheet."""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+
+from codeverse.config import get_settings
+from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
+from codeverse.spatial.joints import (
+ ARTICULATION_SHEET_NAME,
+ blender_render_glb,
+ fk,
+ link_world_meshes,
+ load_urdf,
+ motion_direction_check,
+ render_poses,
+)
+from codeverse.workspace import Workspace
+
+pytestmark = pytest.mark.blender
+needs_blender = pytest.mark.skipif(not get_settings().resolve_blender(), reason="no Blender binary")
+
+
+@needs_blender
+def test_cabinet_door_end_to_end(tmp_path, cabinet_plan):
+ ws = Workspace(tmp_path / "cab").create()
+ rt = UrdfBlenderRuntime()
+ rt.skeleton(ws, cabinet_plan)
+ assert rt.lint(ws).passed
+ res = rt.build(ws)
+ assert res.ok, res.error_message
+ assert res.duration_ms < 30_000
+ r = load_urdf(ws.artifacts / "robot.urdf", ws.artifacts / "meshes")
+ assert r.link_order() == ["body", "door", "handle"]
+ # door + handle swing to the front-left at the upper limit
+ wm = link_world_meshes(r, {"hinge": 1.57})
+ assert wm["door"].centroid[1] < -0.4 and wm["handle"].centroid[1] < -0.4
+ assert motion_direction_check(r, "hinge", "front").ok
+ art = res.census["articulation"]["summary"]
+ assert art["max_penetration_m"] == 0.0 and art["floating_links"] == []
+ # loads in yourdfpy with the same FK
+ yourdfpy = pytest.importorskip("yourdfpy")
+ u = yourdfpy.URDF.load(str(ws.artifacts / "robot.urdf"), load_meshes=True)
+ u.update_cfg({"hinge": 1.0})
+ assert np.allclose(u.get_transform("door", "body"), fk(r, {"hinge": 1.0})["door"], atol=1e-6)
+
+
+@needs_blender
+def test_drawer_prismatic(tmp_path, drawer_plan):
+ ws = Workspace(tmp_path / "drawer").create()
+ rt = UrdfBlenderRuntime()
+ rt.skeleton(ws, drawer_plan)
+ res = rt.build(ws)
+ assert res.ok, res.error_message
+ r = load_urdf(ws.artifacts / "robot.urdf", ws.artifacts / "meshes")
+ c0 = link_world_meshes(r)["drawer"].centroid
+ c1 = link_world_meshes(r, {"slide": 0.3})["drawer"].centroid
+ assert np.allclose(c1 - c0, [0, -0.3, 0], atol=1e-6)
+ assert res.census["articulation"]["summary"]["max_penetration_m"] == 0.0
+
+
+@needs_blender
+def test_bad_pivot_is_caught_and_sheet_renders(tmp_path, cabinet_plan):
+ ws = Workspace(tmp_path / "bad").create()
+ rt = UrdfBlenderRuntime()
+ rt.skeleton(ws, cabinet_plan)
+ u = ws.src / "robot.urdf"
+ # hinge moved to the door's middle: the door must sweep into the body
+ u.write_text(u.read_text().replace('<origin xyz="-0.29 -0.2 0" rpy="0 0 0"/> <!-- pivot', '<origin xyz="0 -0.2 0" rpy="0 0 0"/> <!-- pivot')
+ .replace('xyz="0.29 0.2 0"', 'xyz="0 0.2 0"').replace('xyz="0.49 -0.04 0.4"', 'xyz="0.2 -0.04 0.4"'))
+ res = rt.build(ws)
+ assert res.ok # rest pose is still fine; the sweep reports the defect for the gate layer
+ art = res.census["articulation"]
+ assert art["summary"]["max_penetration_m"] > 0.05 and "hinge@upper" in art["summary"]["overlapping_poses"]
+ assert any(f["severity"] == "error" and "body|door" in f["target"] for f in art["findings"])
+ r = load_urdf(ws.artifacts / "robot.urdf", ws.artifacts / "meshes")
+ out = render_poses(r, ws.artifacts / "renders" / "articulation", renderer=blender_render_glb)
+ assert [label for label, _ in out] == ["rest", "hinge@upper"]
+ assert (ws.artifacts / "renders" / "articulation" / ARTICULATION_SHEET_NAME).is_file()
+
+
+@needs_blender
+def test_script_error_and_missing_object(tmp_path, cabinet_plan):
+ ws = Workspace(tmp_path / "err").create()
+ rt = UrdfBlenderRuntime()
+ rt.skeleton(ws, cabinet_plan)
+ m = ws.src / "model.py"
+ m.write_text(m.read_text() + "\nraise RuntimeError('boom')\n")
+ res = rt.build(ws)
+ assert not res.ok and res.error_type == "RuntimeError" and res.error_line == len(m.read_text().splitlines())
+ m.write_text(m.read_text().replace("raise RuntimeError('boom')\n", "").replace("'handle'", "'Handle'"))
+ res = rt.build(ws)
+ assert not res.ok and res.error_type == "MissingLinkObjects" and "Handle" in res.error_message
diff --git a/harness/tests/urdf_joints/test_runtime_offline.py b/harness/tests/urdf_joints/test_runtime_offline.py
new file mode 100644
index 00000000..cc5b45fc
--- /dev/null
+++ b/harness/tests/urdf_joints/test_runtime_offline.py
@@ -0,0 +1,119 @@
+"""UrdfBlenderRuntime.build with the Blender step faked (offline)."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from codeverse.contracts.common import Language
+from codeverse.languages import get_runtime
+from codeverse.languages.urdf import runtime as rt_mod
+from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
+from codeverse.workspace import Workspace
+from tests.urdf_joints.conftest import box_glb
+
+BODY = ((0, 0, 0.4), (0.6, 0.4, 0.8))
+DOOR = ((0, -0.21, 0.4), (0.58, 0.02, 0.78))
+
+
+def _census_row(center, size):
+ lo = [c - s / 2 for c, s in zip(center, size, strict=True)]
+ hi = [c + s / 2 for c, s in zip(center, size, strict=True)]
+ return {"mesh": "", "tris": 12, "verts": 8, "bbox_min": lo, "bbox_max": hi, "objects": []}
+
+
+def fake_blender(monkeypatch):
+ """Replace the Blender subprocess with a writer of meshes/census/build.json."""
+ state = {"door": DOOR, "ok": True, "error": None}
+
+ def run(blender, ws, art, timeout_s, rlimit_gb):
+ (art / "meshes").mkdir(parents=True, exist_ok=True)
+ if state["error"]:
+ (art / "build.json").write_text(json.dumps({"ok": False, **state["error"]}))
+ (art / "census.json").write_text(json.dumps({"objects": [], "links": {}, "hints": {"door": "did you mean ['Door']?"}}))
+ return {"returncode": 0, "stdout": "", "stderr": "", "timed_out": False}
+ box_glb(art / "meshes" / "body.glb", *BODY)
+ box_glb(art / "meshes" / "door.glb", *state["door"])
+ (art / "census.json").write_text(json.dumps({"objects": [], "links": {"body": _census_row(*BODY), "door": _census_row(*state["door"])},
+ "unmatched_objects": [], "missing_links": [], "hints": {}}))
+ (art / "build.json").write_text(json.dumps({"ok": True, "stdout_tail": "built\n"}))
+ return {"returncode": 0, "stdout": "", "stderr": "", "timed_out": False}
+
+ monkeypatch.setattr(rt_mod, "_run_blender", run)
+ monkeypatch.setattr(rt_mod, "get_settings", lambda: SimpleNamespace(
+ resolve_blender=lambda: "/fake/blender", limits=SimpleNamespace(build_timeout_s=60, bpy_rlimit_gb=4)))
+ return state
+
+
+def _ws(tmp_path, cabinet_plan):
+ ws = Workspace(tmp_path / "ws").create()
+ UrdfBlenderRuntime().skeleton(ws, _two_link(cabinet_plan))
+ return ws
+
+
+def _two_link(plan):
+ return plan.model_copy(update={"parts": plan.parts[:2], "joints": plan.joints[:1]})
+
+
+def test_registry_and_contract():
+ rt = get_runtime(Language.URDF_BLENDER)
+ assert isinstance(rt, UrdfBlenderRuntime) and rt.entry_globs == ("src/model.py", "src/robot.urdf")
+ doc = rt.contract_doc()
+ assert "meshes/<link>.glb" in doc and "pivot" in doc
+ assert rt.cookbook_path().name == "cookbook.md"
+
+
+def test_build_ok(tmp_path, cabinet_plan, fake_blender):
+ ws = _ws(tmp_path, cabinet_plan)
+ res = UrdfBlenderRuntime().build(ws)
+ assert res.ok, res.error_message
+ assert res.glb_path and (ws.artifacts / "object.glb").is_file()
+ assert (ws.artifacts / "robot.urdf").is_file() and (ws.artifacts / "articulation.json").is_file()
+ art = res.census["articulation"]
+ assert art["summary"]["max_penetration_m"] == 0.0 and art["movable_joints"] == ["hinge"]
+ assert res.census["links"]["door"]["islands"] == 1
+ assert res.stdout_tail == "built\n"
+
+
+def test_build_lint_error_short_circuits(tmp_path, cabinet_plan, fake_blender):
+ ws = _ws(tmp_path, cabinet_plan)
+ (ws.src / "robot.urdf").write_text("<robot name='x'><link name='a'>")
+ res = UrdfBlenderRuntime().build(ws)
+ assert not res.ok and res.error_type == "LintError" and "well-formed" in res.error_message
+ assert not (ws.artifacts / "meshes").exists()
+
+
+def test_build_script_error_maps_line(tmp_path, cabinet_plan, fake_blender):
+ fake_blender["error"] = {"error_type": "NameError", "error_message": "name 'bpyy' is not defined", "error_file": "src/model.py",
+ "error_line": 7, "stderr_tail": "Traceback..."}
+ ws = _ws(tmp_path, cabinet_plan)
+ res = UrdfBlenderRuntime().build(ws)
+ assert not res.ok and res.error_type == "NameError" and res.error_line == 7 and res.error_file == "src/model.py"
+ assert "hint: did you mean" in res.error_message
+
+
+def test_build_fk_inconsistent(tmp_path, cabinet_plan, fake_blender):
+ ws = _ws(tmp_path, cabinet_plan)
+ u = ws.src / "robot.urdf"
+ u.write_text(u.read_text().replace('xyz="0.29 0.2 0"', 'xyz="-0.29 -0.2 0"'))
+ res = UrdfBlenderRuntime().build(ws)
+ assert not res.ok and res.error_type == "FkInconsistent"
+ assert 'xyz="0.29 0.2 0"' in res.error_message and res.census["fk_check"][0]["target"] == "door"
+
+
+def test_build_rest_penetration_fails(tmp_path, cabinet_plan, fake_blender):
+ fake_blender["door"] = ((0, -0.19, 0.4), (0.58, 0.02, 0.78)) # authored 10 mm inside the body
+ ws = _ws(tmp_path, cabinet_plan)
+ res = UrdfBlenderRuntime().build(ws)
+ assert not res.ok and res.error_type == "RestPenetration"
+ assert res.glb_path and res.census["articulation"]["summary"]["rest_max_penetration_m"] > 0.005
+
+
+def test_build_timeout(tmp_path, cabinet_plan, fake_blender, monkeypatch):
+ monkeypatch.setattr(rt_mod, "_run_blender", lambda *a, **k: {"returncode": -9, "stdout": "", "stderr": "", "timed_out": True})
+ ws = _ws(tmp_path, cabinet_plan)
+ res = UrdfBlenderRuntime().build(ws, timeout_s=1)
+ assert not res.ok and res.error_type == "Timeout"
diff --git a/harness/tests/urdf_joints/test_skeleton.py b/harness/tests/urdf_joints/test_skeleton.py
new file mode 100644
index 00000000..118b6b6f
--- /dev/null
+++ b/harness/tests/urdf_joints/test_skeleton.py
@@ -0,0 +1,92 @@
+"""Skeleton: plan → correct URDF frames + runnable model.py text."""
+
+from __future__ import annotations
+
+import ast
+
+import numpy as np
+import pytest
+
+from codeverse.contracts.plan import ArticulatedPlan, BBox, JointPlan, PartPlan
+from codeverse.languages.urdf.lint import lint_model_text, lint_urdf_text
+from codeverse.languages.urdf.skeleton import (
+ compute_urdf_frames,
+ render_model_py,
+ render_urdf,
+ write_skeleton,
+)
+from codeverse.spatial.joints import fk, load_urdf
+from codeverse.workspace import Workspace
+
+
+def test_frames_chain(cabinet_plan):
+ fr = compute_urdf_frames(cabinet_plan)
+ assert fr.root == "body" and list(fr.links) == ["body", "door", "handle"]
+ assert fr.links["door"].frame_xyz == (-0.29, -0.2, 0.0)
+ assert fr.links["handle"].frame_xyz == (0.2, -0.24, 0.4)
+ by = {j.name: j for j in fr.joints}
+ assert by["hinge"].origin_xyz == (-0.29, -0.2, 0.0)
+ # handle joint origin is relative to the DOOR frame (accumulated)
+ assert np.allclose(by["handle_mount"].origin_xyz, (0.49, -0.04, 0.4))
+ assert by["handle_mount"].type == "fixed" and by["handle_mount"].lower is None
+
+
+def test_rest_shift():
+ plan = ArticulatedPlan(
+ object_name="Box", summary="s", overall_bbox=BBox(center=(0, 0, 0.1), extents=(0.2, 0.2, 0.2)), root_link="Base",
+ parts=[PartPlan(name="Base", role="r", description="d", bbox=BBox(center=(0, 0, 0.05), extents=(0.2, 0.2, 0.1))),
+ PartPlan(name="Lid", role="r", description="d", bbox=BBox(center=(0, 0, 0.11), extents=(0.2, 0.2, 0.02)))],
+ joints=[JointPlan(name="lid_hinge", type="revolute", parent="Base", child="Lid", axis=(1, 0, 0), pivot=(0, 0.1, 0.1),
+ lower=0.0, upper=1.5, rest=0.5)],
+ )
+ fr = compute_urdf_frames(plan)
+ j = fr.joints[0]
+ assert (j.lower, j.upper) == (-0.5, 1.0) # q=0 is the authored rest
+
+
+def test_rendered_files_lint_clean_and_load(tmp_path, cabinet_plan):
+ fr = compute_urdf_frames(cabinet_plan)
+ urdf_text = render_urdf(fr)
+ findings, links = lint_urdf_text(urdf_text)
+ assert findings == [] and links == ["body", "door", "handle"]
+ model_text = render_model_py(cabinet_plan, fr)
+ ast.parse(model_text)
+ assert lint_model_text(model_text, links) == []
+ p = tmp_path / "robot.urdf"
+ p.write_text(urdf_text)
+ r = load_urdf(p, load_meshes=False)
+ T = fk(r, {})
+ # visual origin is the inverse of the link frame → meshes land where authored
+ for name in fr.links:
+ assert np.allclose(T[name] @ r.links[name].visual_origin, np.eye(4), atol=1e-9), name
+
+
+def test_instances_expand():
+ plan = ArticulatedPlan(
+ object_name="Cart", summary="s", overall_bbox=BBox(center=(0, 0, 0.3), extents=(1, 1, 0.6)), root_link="Frame",
+ parts=[PartPlan(name="Frame", role="r", description="d", bbox=BBox(center=(0, 0, 0.4), extents=(0.8, 0.5, 0.1))),
+ PartPlan(name="Wheel", role="r", description="d", bbox=BBox(center=(-0.3, 0, 0.1), extents=(0.2, 0.05, 0.2)), instances=2)],
+ joints=[JointPlan(name="axle", type="continuous", parent="Frame", child="Wheel", axis=(0, 1, 0), pivot=(-0.3, 0, 0.1))],
+ )
+ fr = compute_urdf_frames(plan)
+ assert list(fr.links) == ["frame", "wheel_1", "wheel_2"]
+ assert [j.name for j in fr.joints] == ["axle_1", "axle_2"]
+ assert fr.links["wheel_2"].frame_xyz[0] > fr.links["wheel_1"].frame_xyz[0]
+ assert lint_urdf_text(render_urdf(fr))[0] == []
+
+
+def test_write_skeleton(tmp_path, drawer_plan):
+ ws = Workspace(tmp_path / "ws").create()
+ paths = write_skeleton(ws, drawer_plan)
+ assert [p.name for p in paths] == ["model.py", "robot.urdf"]
+ assert "prismatic" in paths[1].read_text() and 'box(\'drawer\'' in paths[0].read_text()
+
+
+def test_skeleton_rejects_static_plan(tmp_path):
+ from codeverse.contracts.plan import StaticPlan
+ from codeverse.languages.urdf.runtime import UrdfBlenderRuntime
+
+ sp = StaticPlan(object_name="x", summary="s", overall_bbox=BBox(center=(0, 0, 0), extents=(1, 1, 1)),
+ parts=[PartPlan(name="A", role="r", description="d", bbox=BBox(center=(0, 0, 0), extents=(1, 1, 1)))])
+ with pytest.raises(TypeError):
+ UrdfBlenderRuntime().skeleton(Workspace(tmp_path / "ws").create(), sp)
diff --git a/harness/tests/urdf_joints/test_sweep.py b/harness/tests/urdf_joints/test_sweep.py
new file mode 100644
index 00000000..aa3a1557
--- /dev/null
+++ b/harness/tests/urdf_joints/test_sweep.py
@@ -0,0 +1,99 @@
+"""Collision sweep: good design clean, bad pivot penetrates, floating detection, motion direction."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.contracts.artifacts import Severity
+from codeverse.spatial.joints import (
+ UrdfError,
+ load_urdf,
+ motion_direction_check,
+ pose_samples,
+ summary_text,
+ sweep_collisions,
+ sweep_findings,
+)
+from tests.urdf_joints.conftest import write_mesh_robot, write_prims_robot
+
+
+def test_good_design_has_no_overlaps(tmp_path):
+ r = load_urdf(write_prims_robot(tmp_path / "cab.urdf", axis_z=-1))
+ rep = sweep_collisions(r, pose_samples(r))
+ assert rep.summary.max_penetration_m == 0.0
+ assert rep.summary.floating_links == []
+ assert rep.per_pose[0].n_contacts == 1 # door touches body at rest
+ assert "no overlaps" in summary_text(rep)
+ assert sweep_findings(rep) == []
+
+
+def test_bad_axis_swings_door_into_body(tmp_path):
+ r = load_urdf(write_prims_robot(tmp_path / "cab.urdf", axis_z=+1))
+ rep = sweep_collisions(r, pose_samples(r))
+ assert rep.summary.rest_max_penetration_m == 0.0
+ assert rep.summary.max_penetration_m > 0.1
+ assert set(rep.summary.overlapping_poses) == {"hinge@mid", "hinge@upper"}
+ assert rep.summary.worst_pair == ("body", "door")
+ f = sweep_findings(rep)
+ assert all(x.severity == Severity.ERROR for x in f) and len(f) == 2
+ assert "pivot" in f[0].fix_hint
+ ov = rep.per_pose[-1].overlaps[0]
+ assert ov.volume_m3 is not None and ov.volume_m3 > 1e-4 and not ov.approx
+
+
+def test_rest_penetration_and_floating(tmp_path):
+ # door 30 mm inside the body at rest (fully swallowed: FCL surface collide misses it);
+ # handle (fixed child of the door) pushed 20 mm off the door face → not attached
+ urdf, meshes = write_mesh_robot(tmp_path, handle=True)
+ text = urdf.read_text().replace('<origin xyz="0.29 0.2 0" rpy="0 0 0"/>', '<origin xyz="0.29 0.23 0" rpy="0 0 0"/>')
+ text = text.replace('<origin xyz="-0.2 0.24 -0.4" rpy="0 0 0"/>', '<origin xyz="-0.2 0.22 -0.4" rpy="0 0 0"/>')
+ urdf.write_text(text)
+ r = load_urdf(urdf, meshes)
+ rep = sweep_collisions(r, [{}])
+ assert 0.028 < rep.summary.rest_max_penetration_m < 0.032
+ assert rep.summary.floating_at_rest == ["handle"]
+ fl = rep.per_pose[0].floating[0]
+ # attachment is judged against the PARENT link (door), not the grounded body
+ assert fl.nearest == "door" and fl.joint_type == "fixed" and 0.03 < fl.gap_m < 0.06
+ sev = {x.target: x.severity for x in sweep_findings(rep)}
+ assert sev["body|door"] == Severity.ERROR and sev["handle"] == Severity.ERROR
+
+
+def test_hinged_child_near_parent_is_only_a_warning(tmp_path):
+ # door hinged 6 mm in front of the body face: within 3x hinge clearance → WARN, not ERROR
+ urdf, meshes = write_mesh_robot(tmp_path, handle=False)
+ text = urdf.read_text().replace('<origin xyz="0.29 0.2 0" rpy="0 0 0"/>', '<origin xyz="0.29 0.194 0" rpy="0 0 0"/>')
+ urdf.write_text(text)
+ r = load_urdf(urdf, meshes)
+ rep = sweep_collisions(r, [{}], hinge_clearance_m=0.004)
+ assert rep.summary.floating_at_rest == ["door"]
+ fl = rep.per_pose[0].floating[0]
+ assert fl.nearest == "body" and fl.joint_type == "revolute" and 0.004 < fl.gap_m < 0.008
+ finds = sweep_findings(rep, hinge_clearance_m=0.004)
+ assert finds[-1].target == "door" and finds[-1].severity == Severity.WARN
+ # an inserted prismatic child (AABB overlap) is never reported as unattached
+ rep_ok = sweep_collisions(load_urdf(*write_mesh_robot(tmp_path / "ok")), [{}])
+ assert rep_ok.summary.floating_at_rest == []
+
+
+def test_motion_direction(tmp_path):
+ r = load_urdf(write_prims_robot(tmp_path / "cab.urdf", axis_z=-1))
+ ok = motion_direction_check(r, "hinge", "front")
+ assert ok.ok and ok.observed_dir[1] < -0.9
+ bad = motion_direction_check(r, "hinge", "back")
+ assert not bad.ok and "WRONG" in bad.message
+ with pytest.raises(UrdfError):
+ motion_direction_check(r, "hinge", "sideways")
+ with pytest.raises(UrdfError):
+ motion_direction_check(r, "nope", "front")
+
+
+def test_trimesh_fallback_backend(tmp_path, monkeypatch):
+ import codeverse.spatial.joints_sweep as js
+
+ monkeypatch.setattr(js, "_fcl", None)
+ r = load_urdf(write_prims_robot(tmp_path / "cab.urdf", axis_z=+1))
+ rep = js.sweep_collisions(r, pose_samples(r), volumes=False)
+ assert rep.summary.backend == "trimesh"
+ assert rep.summary.max_penetration_m > 0.1 and rep.summary.rest_max_penetration_m == 0.0
+ assert rep.summary.floating_links == []