Skip to content

Official Codebase of 3DCodeVerse

Python

plugin code lane: 3dcode CLI replaces the pipeline, the vendor agents and the MCP server

gaoypeng6750f248c666
diff --git a/harness/bin/3dcode b/harness/bin/3dcode
new file mode 100755
index 00000000..ca863d6c
--- /dev/null
+++ b/harness/bin/3dcode
@@ -0,0 +1,9 @@
+#!/usr/bin/env bash
+# 3dcode launcher: $C3D_PYTHON, else <plugin>/.venv/bin/python, else python3; the plugin root on PYTHONPATH.
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+PY="${C3D_PYTHON:-}"
+if [ -z "$PY" ] && [ -x "$HERE/.venv/bin/python" ]; then PY="$HERE/.venv/bin/python"; fi
+if [ -z "$PY" ]; then PY="python3"; fi
+export PYTHONPATH="$HERE${PYTHONPATH:+:$PYTHONPATH}"
+exec "$PY" -m codeverse3d.cli "$@"
diff --git a/harness/codeverse3d/__init__.py b/harness/codeverse3d/__init__.py
index 8d1616f2..0d0ca7dd 100644
--- a/harness/codeverse3d/__init__.py
+++ b/harness/codeverse3d/__init__.py
@@ -1,17 +1,17 @@
-"""codeverse3d — the 3dcodeverse harness.
+"""codeverse3d — the 3dcodeverse plugin's instruments.
-A backend harness in which LLMs write RAW, executable 3D code (Blender ``bpy``, CadQuery,
-Three.js, URDF, GLSL) for four tracks (static objects, articulated objects, scenes, graphics).
+Deterministic tools for a host coding agent writing RAW 3D code (Blender ``bpy``, CadQuery, Three.js,
+URDF, GLSL / OpenGL) across four tracks (static objects, articulated objects, scenes, graphics),
+driven from the ``3dcode`` command line.
Package map:
-- ``conventions`` frames, units, naming. - ``config`` typed layered settings.
-- ``contracts`` shared pydantic models. - ``models`` ChatModel backends + key pool.
-- ``agents`` vendor CLI coding agents. - ``languages`` per-language lint / build / export.
-- ``spatial`` 3D tools on GLB / scene, also an MCP server.
-- ``judges`` VLM judges + rubrics. - ``tracks`` the four pipelines.
-- ``orchestrator`` stage runner, round loop. - ``record`` record.json, deliverable/, telemetry.
-- ``addons`` tools that read finished runs. - ``cli`` the ``3dcodeverse`` command line.
+- ``conventions`` frames, units, naming. - ``config`` typed layered settings.
+- ``contracts`` shared pydantic models. - ``languages`` per-language lint / build / export.
+- ``spatial`` measurement, gates and renders on GLB / scene / frames; the tool registry.
+- ``gates`` per-track gate assembly and render rig. - ``plan_checks`` plan validation.
+- ``judges`` rubrics, score arithmetic, the judge brief. - ``workflow`` init / validate-plan / check / judge-pack / score.
+- ``cli`` the ``3dcode`` command line. - ``doctor`` environment checks.
"""
-__version__ = "0.0.1"
+__version__ = "0.1.0"
diff --git a/harness/codeverse3d/cli.py b/harness/codeverse3d/cli.py
new file mode 100644
index 00000000..3bc464d8
--- /dev/null
+++ b/harness/codeverse3d/cli.py
@@ -0,0 +1,212 @@
+"""``3dcode`` — the command line of every instrument: one subcommand per registered tool, generated from its
+typed arguments.
+
+ 3dcode <tool> [--workspace DIR] [--round N] [--json] [--<arg> value ...]
+ 3dcode list · 3dcode doctor [--no-gpu] [--json]
+
+A tool prints its verdict first (PASS / FAIL / ERROR), then its numbers and the absolute paths of the PNGs it
+wrote. Exit 0 = the tool ran (a FAIL verdict is still 0); 2 = it could not run or the arguments were wrong.
+``--json`` prints the Observation as JSON instead.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import types
+import typing
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel
+
+from codeverse3d import __version__
+from codeverse3d.spatial.observe import fmt_numbers
+from codeverse3d.spatial.registry import Observation, ToolContext, ToolDef, list_tools
+from codeverse3d.spatial.tool_common import spec_dict
+from codeverse3d.workspace import Workspace
+
+PROG = "3dcode"
+EXIT_FAILED = 2
+MAX_NUMBERS_CHARS = 1500
+
+
+def cli_name(tool: str) -> str:
+ """``validate_plan`` → ``validate-plan`` (the underscore spelling stays an alias)."""
+ return tool.replace("_", "-")
+
+
+# --------------------------------------------------------------------------- arguments from the pydantic model
+def _kv_float(text: str) -> tuple[str, float]:
+ key, sep, val = text.partition("=")
+ if not sep or not key.strip():
+ raise argparse.ArgumentTypeError(f"expected key=value, got {text!r}")
+ try:
+ return key.strip(), float(val)
+ except ValueError as e:
+ raise argparse.ArgumentTypeError(f"{key}: {val!r} is not a number") from e
+
+
+def _unwrap(annotation: Any) -> Any:
+ """``X | None`` / ``Optional[X]`` → ``X``."""
+ if typing.get_origin(annotation) in (typing.Union, types.UnionType):
+ inner = [a for a in typing.get_args(annotation) if a is not type(None)]
+ return inner[0] if len(inner) == 1 else annotation
+ return annotation
+
+
+def add_model_arguments(parser: argparse.ArgumentParser, model: type[BaseModel]) -> None:
+ """One ``--field`` option per model field: bools as ``--x/--no-x``, lists repeatable, ``dict[str, float]`` as
+ repeatable ``key=value``."""
+ for name, field in model.model_fields.items():
+ flag = "--" + name.replace("_", "-")
+ ann = _unwrap(field.annotation)
+ origin = typing.get_origin(ann)
+ help_text = field.description or ""
+ required = field.is_required()
+ if ann is bool:
+ parser.add_argument(flag, dest=name, action=argparse.BooleanOptionalAction, default=argparse.SUPPRESS,
+ help=help_text)
+ elif origin is list:
+ (item,) = typing.get_args(ann) or (str,)
+ parser.add_argument(flag, dest=name, action="append", type=item if item in (int, float, str) else str,
+ default=argparse.SUPPRESS, required=required, metavar=item.__name__.upper(),
+ help=help_text + " (repeatable)")
+ elif origin is dict:
+ parser.add_argument(flag, dest=name, action="append", type=_kv_float, default=argparse.SUPPRESS,
+ required=required, metavar="KEY=VALUE", help=help_text + " (repeatable)")
+ else:
+ typ = ann if ann in (int, float, str) else str
+ parser.add_argument(flag, dest=name, type=typ, default=argparse.SUPPRESS, required=required,
+ metavar=typ.__name__.upper(), help=help_text)
+
+
+def model_arguments(ns: argparse.Namespace, model: type[BaseModel]) -> dict[str, Any]:
+ """The namespace's tool arguments as the dict the args model takes (dict fields merged from key=value pairs)."""
+ out: dict[str, Any] = {}
+ for name, field in model.model_fields.items():
+ if not hasattr(ns, name):
+ continue
+ value = getattr(ns, name)
+ if typing.get_origin(_unwrap(field.annotation)) is dict and isinstance(value, list):
+ value = dict(value)
+ out[name] = value
+ return out
+
+
+# --------------------------------------------------------------------------- the parser
+def _common(parser: argparse.ArgumentParser) -> None:
+ parser.add_argument("--workspace", "-w", default=None, metavar="DIR",
+ help="the project directory (default: $C3D_WORKSPACE, else the current directory)")
+ parser.add_argument("--round", dest="round_index", type=int, default=0, metavar="N",
+ help="the round this call belongs to (judge/rNN, artifacts/renders/rNN); default 0")
+ parser.add_argument("--json", dest="as_json", action="store_true", help="print the result as JSON")
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(prog=PROG, description="3dcodeverse instruments: build, measure, render and check "
+ "the 3D code in a project workspace.")
+ parser.add_argument("--version", action="version", version=f"{PROG} {__version__}")
+ sub = parser.add_subparsers(dest="command", metavar="<tool>")
+ sub.required = True
+ p_list = sub.add_parser("list", help="list every tool with its arguments")
+ p_list.add_argument("--json", dest="as_json", action="store_true")
+ p_doc = sub.add_parser("doctor", help="check python deps, Blender, node / three / puppeteer, the GPU probe")
+ p_doc.add_argument("--gpu", action=argparse.BooleanOptionalAction, default=True, help="probe headless Chrome WebGL")
+ p_doc.add_argument("--json", dest="as_json", action="store_true")
+ for t in list_tools():
+ p = sub.add_parser(cli_name(t.name), aliases=[t.name] if "_" in t.name else [],
+ help=f"({t.cost_hint}) {t.description}", description=t.description)
+ _common(p)
+ add_model_arguments(p, t.args_model)
+ p.set_defaults(tool=t)
+ return parser
+
+
+def resolve_workspace(arg: str | None) -> Workspace:
+ root = Path(arg or os.environ.get("C3D_WORKSPACE") or Path.cwd()).expanduser()
+ return Workspace(root)
+
+
+def build_context(ws: Workspace, round_index: int) -> ToolContext:
+ """ToolContext for ``ws``; track / language come from spec.json, re-read on every call."""
+ ctx = ToolContext(workspace=ws, round_index=round_index)
+ spec = spec_dict(ctx)
+ ctx.track = str(spec.get("track", ""))
+ ctx.language = str(spec.get("language", ""))
+ return ctx
+
+
+# --------------------------------------------------------------------------- output
+def format_observation(obs: Observation) -> str:
+ lines = [obs.text.rstrip()]
+ if obs.numbers:
+ nums = json.dumps(obs.numbers, default=str)
+ lines.append("numbers: " + (nums if len(nums) <= MAX_NUMBERS_CHARS else fmt_numbers(obs.numbers)))
+ if obs.images:
+ lines.append("images:")
+ lines += [f" {Path(p).resolve()}" for p in obs.images]
+ return "\n".join(lines)
+
+
+def run_tool(tdef: ToolDef, ns: argparse.Namespace) -> int:
+ ws = resolve_workspace(ns.workspace)
+ if not ws.root.is_dir():
+ if tdef.name == "init":
+ ws.root.mkdir(parents=True, exist_ok=True)
+ else:
+ print(f"ERROR: workspace not found: {ws.root}", file=sys.stderr)
+ return EXIT_FAILED
+ ctx = build_context(ws, ns.round_index)
+ obs = tdef.call(ctx, model_arguments(ns, tdef.args_model))
+ if ns.as_json:
+ print(json.dumps(obs.model_dump(mode="json"), indent=1, default=str))
+ else:
+ print(format_observation(obs))
+ return EXIT_FAILED if obs.failed else 0
+
+
+def list_command(as_json: bool) -> int:
+ tools = list_tools()
+ if as_json:
+ print(json.dumps([{"name": cli_name(t.name), "cost": t.cost_hint, "description": t.description,
+ "tracks": list(t.tracks), "languages": list(t.languages), "schema": t.schema()} for t in tools],
+ indent=1))
+ return 0
+ for t in tools:
+ scope = ""
+ if t.tracks:
+ scope = f" [tracks: {', '.join(t.tracks)}]"
+ elif t.languages:
+ scope = f" [languages: {', '.join(t.languages)}]"
+ print(f"{cli_name(t.name)} ({t.cost_hint}){scope}: {t.description}")
+ props = t.schema().get("properties", {})
+ req = set(t.schema().get("required", []))
+ for k, v in props.items():
+ mark = "required" if k in req else f"default={v.get('default')!r}"
+ print(f" --{k.replace('_', '-')}: {v.get('type', 'any')} — {v.get('description', '')} ({mark})")
+ return 0
+
+
+def doctor_command(gpu: bool, as_json: bool) -> int:
+ from codeverse3d.doctor import format_rows, run_doctor
+
+ rows = run_doctor(gpu=gpu)
+ print(json.dumps([{"check": c, "status": s, "detail": d} for c, s, d in rows], indent=1) if as_json else format_rows(rows))
+ return 1 if any(s == "FAIL" for _, s, _ in rows) else 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = build_parser()
+ ns = parser.parse_args(argv)
+ if ns.command == "list":
+ return list_command(ns.as_json)
+ if ns.command == "doctor":
+ return doctor_command(ns.gpu, ns.as_json)
+ return run_tool(ns.tool, ns)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/harness/codeverse3d/cli/__init__.py b/harness/codeverse3d/cli/__init__.py
deleted file mode 100644
index 38184625..00000000
--- a/harness/codeverse3d/cli/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-"""``3dcodeverse`` command line."""
diff --git a/harness/codeverse3d/cli/_common.py b/harness/codeverse3d/cli/_common.py
deleted file mode 100644
index 0eb33187..00000000
--- a/harness/codeverse3d/cli/_common.py
+++ /dev/null
@@ -1,245 +0,0 @@
-"""Shared CLI plumbing: Rich formatting, the run mutex and workspace opening / creation."""
-
-from __future__ import annotations
-
-import hashlib
-import math
-import shutil
-from collections.abc import Iterator
-from contextlib import ExitStack, contextmanager
-from pathlib import Path
-from typing import TYPE_CHECKING, Annotated, Any
-
-import typer
-from rich.console import Console
-from rich.panel import Panel
-from rich.table import Table
-
-from codeverse3d.config import get_settings
-from codeverse3d.contracts.run import RunRecord
-from codeverse3d.contracts.spec import Spec
-from codeverse3d.conventions import slugify
-from codeverse3d.workspace import Workspace
-
-if TYPE_CHECKING:
- from c3d_flywheel.select import RoundRow
-
-console = Console(emoji=False)
-err_console = Console(stderr=True, style="bold red", emoji=False)
-
-RunsDirOpt = Annotated[Path | None, typer.Option("--runs-dir", help="runs root (default: settings.runs_dir)")]
-
-
-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(rows: list[RoundRow], picked: int | None) -> Table:
- t = Table(title="rounds (* = picked)", show_lines=False)
- for col in ("#", "kind", "build", "gate err", "score", "passed", "cost", "min", "commit"):
- t.add_column(col, justify="right" if col in ("#", "gate err", "score", "cost", "min") else "left")
- for r in rows:
- build = "-" if r.build_ok is None else ("ok" if r.build_ok else "[red]FAIL[/red]")
- passed = "-" if r.passed is None else ("[green]yes[/green]" if r.passed else "no")
- t.add_row(f"{r.index}{'*' if r.index == picked else ''}", r.kind, build, str(r.gate_errors), fmt_score(r.score),
- passed, fmt_usd(r.cost_usd), f"{r.minutes:.1f}", r.commit[:8])
- return t
-
-
-def print_record_summary(record: RunRecord, ws_root: Path | None = None) -> None:
- from c3d_flywheel import select
-
- spec = record.spec
- root = Path(ws_root or record.workspace)
- s = select.summarise(root, record=record)
- status_col = {"failed": "red", "budget": "yellow", "agent_quota": "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"judge={spec.backends.judge}",
- f"stop=[{status_col}]{s.stop_reason}[/{status_col}] baseline={fmt_score(s.baseline_score)} "
- f"picked={fmt_score(s.picked_score)} (round {s.round}, "
- f"{f'by {s.method}' if s.picked_round is not None else 'nothing judged: the latest built round with renders'}) rounds={s.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:
- ws = Workspace(ws_root)
- lines.append(f"workspace: {ws_root}")
- picked = next((r for r in record.rounds if r.index == s.round), None)
- if picked is not None and picked.renders is not None and picked.renders.contact_sheet:
- # record.json stores absolute paths of the producing host; rebase onto this root
- lines.append(f"sheet: {ws.rebase(picked.renders.contact_sheet)}")
- if ws.deliverable_manifest_path.is_file():
- lines.append(f"deliverable: {ws.deliverable}")
- console.print(Panel("\n".join(lines), title="run", expand=False))
- if record.rounds:
- console.print(rounds_table(select.round_rows(root, record=record), s.round))
-
-
-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
- # FAIL is a computed verdict; error is a tool that could not run
- state, style = ("ok", "green") if obs.ok else (("error", "red") if obs.failed else ("FAIL", "yellow"))
- console.print(Panel(obs.text, title=f"[{style}]{state}[/{style}] ({obs.duration_ms} ms)", expand=False))
- if obs.numbers:
- 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:
- t = Table(title="3dcodeverse 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
-
-
-# ===================================================================== _common
-REPO_ROOT = Path(__file__).resolve().parents[2]
-
-
-class CliError(typer.Exit):
-
- def __init__(self, message: str, code: int = 1):
- err(message)
- super().__init__(code=code)
-
-
-#: ``<repo>/eval``, never imported by the harness
-EVAL_ROOT = REPO_ROOT.parent / "eval"
-
-
-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:
- 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}"
-
-
-@contextmanager
-def mutating(target: Any, *, what: str, action: str = "enter") -> Iterator[None]:
- """The run mutex around anything that writes into a run directory; ``target`` is a
- Workspace or a run root."""
- from codeverse3d.proc import RunLocked, exclusive
-
- root = target if isinstance(target, (str, Path)) else target.root # NB: Path.root is "/"
- stack = ExitStack()
- try:
- stack.enter_context(exclusive(root, what=what, action=action))
- except RunLocked as e:
- raise CliError(str(e), code=2) from None
- with stack:
- yield
-
-
-def create_workspace(root: Path, *, force: bool) -> Workspace:
- """Create (or ``--force``-replace) a run directory; the caller holds the run mutex."""
- ws = Workspace(root)
- if ws.root.exists() and any(ws.root.iterdir()):
- if not force:
- 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]:
- """``key=value`` pairs of positive, finite floats (``--dim``: metres)."""
- out: dict[str, float] = {}
- for it in items:
- if "=" not in it:
- raise CliError(f"{flag} expects key=value, got {it!r}")
- k, v = (s.strip() for s in it.split("=", 1))
- if not k:
- raise CliError(f"{flag} expects key=value, got {it!r} (no key)")
- try:
- out[k] = float(v)
- except ValueError as e:
- raise CliError(f"{flag} {k}: not a number: {v!r}") from e
- if not math.isfinite(out[k]) or out[k] <= 0:
- raise CliError(f"{flag} {k}: must be a positive number, got {v!r}")
- return out
-
-
-def check_minutes(max_minutes: float | None) -> None:
- """``--max-minutes`` must be a finite number above 0."""
- if max_minutes is not None and max_minutes <= 0:
- raise CliError(f"--max-minutes must be above 0 (got {max_minutes:g}): a run with no time builds nothing", code=2)
- if max_minutes is not None and not math.isfinite(max_minutes):
- raise CliError(f"--max-minutes must be a finite number of minutes (got {max_minutes:g})", code=2)
-
-
-def check_backends(backends: Any) -> None:
- """Refuse a backend id this build cannot construct, before a run directory exists."""
- from codeverse3d.agents.registry import parse_agent_id
- from c3d_flywheel.models.registry import parse_model_id
- from codeverse3d.tracks.generation import is_single_shot, single_shot_model_id
-
- for role in ("generator", "planner", "judge"):
- value = getattr(backends, role)
- try:
- if role != "generator":
- parse_model_id(value)
- elif is_single_shot(value):
- parse_model_id(single_shot_model_id(value))
- else:
- parse_agent_id(value)
- except ValueError as e:
- raise CliError(f"--{role} {value!r}: {e}", code=2) from None
-
-
-
diff --git a/harness/codeverse3d/cli/main.py b/harness/codeverse3d/cli/main.py
deleted file mode 100644
index 060be4ff..00000000
--- a/harness/codeverse3d/cli/main.py
+++ /dev/null
@@ -1,541 +0,0 @@
-"""``3dcodeverse`` — the command line: the typer app, every registration, and ``make`` /
-``resume`` / ``pick`` / ``mcp``. Commands import the harness lazily so ``--help`` stays fast."""
-
-from __future__ import annotations
-
-import contextlib
-import faulthandler
-import json
-import os
-import signal
-import sys
-from pathlib import Path
-from typing import Annotated
-
-import typer
-
-from codeverse3d import __version__
-from codeverse3d.cli import _common as C
-from codeverse3d.cli._common import (
- RunsDirOpt,
- console,
- err_console,
- kv_table,
- ok,
- print_observation,
- print_record_summary,
- warn,
-)
-from c3d_flywheel.cli.cost_cmd import cost_app
-from c3d_flywheel.cli.flywheel_cmd import flywheel_app
-from codeverse3d.cli.skills_cmd import skills_app
-from codeverse3d.config import get_settings
-from codeverse3d.contracts.common import TRACK_LANGUAGES, Budget, Language, Track
-from codeverse3d.contracts.spec import Constraints, ReferenceImage, Spec
-
-
-# ===================================================================== doctor
-def doctor(
- live: Annotated[bool, typer.Option("--live", help="make one tiny Gemini call")] = False,
- gpu: Annotated[bool, typer.Option("--gpu/--no-gpu", help="probe headless Chrome WebGL")] = True,
- as_json: Annotated[bool, typer.Option("--json")] = False,
-) -> None:
- """Check python deps, Blender, node/three/puppeteer, keys, CLIs and MCP."""
- from codeverse3d.doctor import run_doctor
-
- rows = run_doctor(live=live, gpu=gpu)
- if as_json:
- console.print_json(json.dumps([{"check": c, "status": s, "detail": d} for c, s, d in rows]))
- else:
- console.print(C.doctor_table(rows))
- if any(s == "FAIL" for _, s, _ in rows):
- raise typer.Exit(code=1)
-
-
-# ===================================================================== tools_cmd
-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:
- from codeverse3d.spatial import 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)
-
-
-# ===================================================================== gallery_cmd
-gallery_app = typer.Typer(no_args_is_help=True)
-
-RootsArg = Annotated[list[Path] | None, typer.Argument(
- help="run roots (default: ./runs, every ./eval/bench/out/*/runs and every <repo>/eval/bench/out/*/runs that exists)")]
-
-
-def resolve_roots(roots: list[Path] | None) -> list[Path]:
- """Explicit roots (validated) or the defaults; a clear error when there are none."""
- from c3d_flywheel.gallery.index import default_roots
-
- if roots:
- missing = [r for r in roots if not Path(r).is_dir()]
- if missing:
- raise C.CliError("not a directory: " + ", ".join(str(m) for m in missing))
- return [Path(r) for r in roots]
- found = default_roots(Path.cwd())
- seen = {p.resolve() for p in found}
- found += [p for p in sorted((C.EVAL_ROOT / "bench" / "out").glob("*/runs")) if p.is_dir() and p.resolve() not in seen]
- if not found:
- fallback = Path(get_settings().runs_dir)
- if fallback.is_dir():
- return [fallback]
- raise C.CliError(f"no run roots found (looked for runs/ and eval/bench/out/*/runs under {Path.cwd()}, "
- f"and {C.EVAL_ROOT / 'bench' / 'out'}/*/runs); "
- f"pass one explicitly: `3dcodeverse gallery serve path/to/runs`")
- return found
-
-
-@gallery_app.command("serve")
-def serve_cmd(
- roots: RootsArg = None,
- port: Annotated[int, typer.Option("--port", min=0, max=65535, help="0 = pick a free port")] = 8765,
- host: Annotated[str | None, typer.Option("--host", help="default 127.0.0.1; any non-loopback address must be "
- "typed here explicitly")] = None,
- open_browser: Annotated[bool, typer.Option("--open/--no-open", help="open the page in a browser")] = True,
- reload: Annotated[bool, typer.Option("--reload", help="re-scan the roots on every page load "
- "(cheap: records only, images stay lazy)")] = False,
- title: Annotated[str, typer.Option("--title")] = "3dcodeverse gallery",
-) -> None:
- """Serve the gallery (and the run directories) on localhost."""
- from c3d_flywheel.gallery.server import GalleryError, serve
-
- root_paths = resolve_roots(roots)
-
- def announce(app, url: str) -> None:
- ix = app.index
- console.print(kv_table("gallery", {
- "url": url, "runs": len(ix.entries()), "roots": len(ix.sections),
- "index built in": f"{ix.build_ms} ms", "reload": reload,
- "sections": ", ".join(f"{s.label}({len(s.entries)})" for s in ix.sections)}))
- console.print("[dim]Ctrl-C to stop[/dim]")
-
- try:
- serve(root_paths, host=host, port=port, reload=reload,
- open_browser=open_browser, title=title, on_start=announce)
- except GalleryError as e:
- raise C.CliError(str(e)) from e
- ok("gallery stopped")
-
-
-@gallery_app.command("build")
-def build_cmd(
- roots: RootsArg = None,
- out: Annotated[Path, typer.Option("--out", help="output .html")] = Path("gallery.html"),
- embed: Annotated[bool, typer.Option("--embed", help="inline the contact sheets as data: URIs so the page can "
- "be shared (much bigger; links still point here)")] = False,
- title: Annotated[str | None, typer.Option("--title")] = None,
- thumb_px: Annotated[int, typer.Option("--thumb-px", min=128, help="embedded thumbnail long edge")] = 720,
-) -> None:
- """Write the gallery as one self-contained HTML file."""
- from c3d_flywheel.gallery.page import build_static
-
- path, n, index = build_static(resolve_roots(roots), out, title=title, embed=embed, thumb_px=thumb_px)
- broken = sum(1 for e in index.entries() if e.state != "ok")
- if broken:
- warn(f"{broken} run(s) have no usable record.json (shown as broken cards)")
- ok(f"gallery of {n} runs → {path} ({path.stat().st_size // 1024} KB)")
- if not embed:
- console.print("[dim]file:// links; `--embed` inlines the images, `3dcodeverse gallery serve` makes them clickable[/dim]")
-
-
-app = typer.Typer(
- name="3dcodeverse",
- 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 / refine / captions.")
-app.add_typer(
- gallery_app,
- name="gallery",
- help="Look at runs locally: `serve` on localhost, `build` one shareable HTML file.",
-)
-app.add_typer(
- cost_app, name="cost", help="Cost audit: per stage/role/model, waste, $ per run."
-)
-app.add_typer(
- skills_app, name="skills", help="The skill library: list / show / validate / read-rate report."
-)
-app.command("doctor", help="Environment checks.")(doctor)
-app.command(
- "tools",
- help="List spatial tools or run one: `3dcodeverse tools list` | `3dcodeverse tools <name> --json '{...}' --workspace ws`.",
-)(tools)
-
[email protected](invoke_without_command=True)
-def _root(
- ctx: typer.Context, version: Annotated[bool, typer.Option("--version", is_eager=True)] = False
-) -> None:
- # `kill -USR1 <pid>` dumps every thread's stack to stderr (py-spy needs ptrace, which WSL denies)
- if hasattr(signal, "SIGUSR1") and sys.__stderr__ is not None:
- # best-effort: a captured stderr (CliRunner's StringIO) has no fileno
- with contextlib.suppress(Exception):
- faulthandler.register(signal.SIGUSR1, file=sys.__stderr__, all_threads=True)
- if version:
- console.print(f"3dcodeverse {__version__}")
- raise typer.Exit()
- if ctx.invoked_subcommand is None:
- console.print(ctx.get_help())
- raise typer.Exit()
- # build the settings here so a bad value is one typed error, not a traceback from any command
- try:
- get_settings()
- except ValueError as e:
- raise C.CliError(f"bad configuration: {e}", code=2) from e
-
-
-# --------------------------------------------------------------------------- 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 | None,
- typer.Option(
- "--language",
- help="default: the track's first language "
- "(blender / urdf_blender / scene_threejs / glsl_shader)",
- ),
- ] = None,
- generator: Annotated[
- str | None,
- typer.Option(
- help="agy:gemini-4-argon[-low|-medium|-high] | claude-code:... | codex:... | single-shot:gemini:..."
- ),
- ] = None,
- planner: Annotated[str | None, typer.Option()] = None,
- judge: Annotated[str | None, typer.Option()] = None,
- image: Annotated[list[Path] | None, typer.Option("--image", help="reference image(s)")] = None,
- rounds: Annotated[
- int | None,
- typer.Option(
- "--rounds", min=0, help="refine rounds after the baseline (default: 4)"
- ),
- ] = None,
- max_minutes: Annotated[float | None, typer.Option("--max-minutes", min=0)] = None,
- 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,
- no_pick: Annotated[
- bool,
- typer.Option(
- "--no-pick",
- help="stop after the rounds: no round is picked, no deliverable/ is written "
- "(`3dcodeverse pick <slug>` does it later)",
- ),
- ] = False,
- 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 and stop",
- ),
- ] = 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 []
- if not prompt.strip():
- raise C.CliError("the prompt is empty: say what to build", code=2)
- C.check_minutes(max_minutes)
- for p in image:
- if not p.is_file():
- raise C.CliError(f"reference image not found: {p}")
- from PIL import Image, UnidentifiedImageError
-
- try:
- with Image.open(p) as im:
- im.verify()
- except (UnidentifiedImageError, OSError, SyntaxError) as e:
- raise C.CliError(f"reference image is not a readable image: {p} ({e})") from None
- if language is None:
- language = TRACK_LANGUAGES[track][0]
- run_slug = C.make_slug(prompt, track.value, language.value, slug)
- settings = get_settings()
- backends = settings.backends(generator=generator, planner=planner, judge=judge)
- C.check_backends(backends)
- # validate the whole Spec before touching the filesystem (no orphan run directory)
- 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(**{k: v for k, v in
- {"max_rounds": rounds, "max_minutes": max_minutes}.items() if v is not None}),
- backends=backends,
- tags=tag,
- )
- except ValueError as e:
- raise C.CliError(f"invalid run spec: {e}") from e
- # the run mutex: taken before the workspace is created (or --force wipes one), held through the run
- with C.mutating(C.runs_root(runs_dir) / run_slug, what=f"3dcodeverse make {run_slug}", action="create"):
- ws = C.create_workspace(C.runs_root(runs_dir) / run_slug, force=force)
- ws.write_json(ws.spec_path, spec)
- ws.commit("spec")
- console.print(
- kv_table(
- "run",
- {
- "slug": run_slug,
- "workspace": ws.root,
- "track": track.value,
- "language": language.value,
- "generator": backends.generator,
- "judge": f"{backends.judge} n={settings.judge.samples} "
- f"({settings.judge.max_px}px/{settings.judge.detail_crops}crop)",
- "rounds": spec.budget.max_rounds,
- },
- )
- )
- if no_run:
- ok(f"spec written: {ws.spec_path} (not run; `3dcodeverse resume {run_slug}` to start)")
- return
- _run_track(spec, ws, resume=False, pick=not no_pick)
-
-
-def _run_track(spec: Spec, ws, *, resume: bool, force: bool = False, pick: bool = True) -> None:
- from c3d_flywheel.cost.instrument import run_ledger
- from codeverse3d.proc import install_stop_handlers
- from codeverse3d.tracks import get_track
-
- install_stop_handlers()
- try:
- with run_ledger(ws.root, run=ws.root.name):
- record = get_track(spec.track).run(spec, ws, resume=resume, force=force)
- except KeyboardInterrupt:
- raise C.CliError(
- f"interrupted; resume with `3dcodeverse resume {ws.root.name}`", code=130
- ) from None
- except Exception as e: # the track failed outside its own error handling
- from codeverse3d.orchestrator import StateCorrupt
- from codeverse3d.tracks.lifecycle import SpecChanged
-
- if isinstance(e, SpecChanged):
- raise C.CliError(str(e), code=2) from None
- if isinstance(e, StateCorrupt):
- raise C.CliError(f"{e} — unreadable run state; move run_state.json aside and resume from the "
- f"round journal (rounds/)", code=2) from None
- err_console.print_exception(max_frames=8)
- raise C.CliError(
- f"run failed: {type(e).__name__}: {e} (workspace {ws.root}; see events.jsonl)"
- ) from e
- if pick:
- with run_ledger(ws.root, run=ws.root.name):
- _pick_and_package(ws)
- print_record_summary(record, ws.root)
- if record.status.value == "failed":
- raise typer.Exit(code=1)
-
-
-def _pick_and_package(ws, *, round_index: int | None = None) -> int | None:
- """Choose the round (or take ``round_index``) and package it."""
- from c3d_flywheel import select
-
- idx = round_index if round_index is not None else select.pick(ws.root)
- if idx is None:
- warn("no round was judged, so none was picked: name one with `3dcodeverse pick <slug> --round N`")
- return None
- try:
- select.package(ws.root, idx, method="round" if round_index is not None else "score")
- except ValueError as e:
- raise C.CliError(str(e), code=2) from e
- ok(f"picked round {idx} ({'named' if round_index is not None else 'by score'}) → {ws.deliverable}")
- return idx
-
-
-def _finished_reason(ws, raised: dict) -> str:
- """Why this run must not be re-entered, or "" when resuming it is meaningful.
-
- A finished run is refused (re-entering re-runs the paid plan stage), except BUDGET and
- MAX_ROUNDS stops whose cap was raised, and AGENT_QUOTA / JUDGE_UNAVAILABLE stops.
- """
- from codeverse3d.contracts.run import RunStatus
- from codeverse3d.orchestrator import RunState, StateCorrupt
-
- try:
- state = RunState.load(ws)
- except StateCorrupt:
- return ""
- if state is None:
- return ""
- status = state.status
- detail = f"status={status.value}"
- if status is RunStatus.BUDGET:
- return "" if raised else f"{detail}: raise a cap to continue it (--max-minutes / --rounds)"
- if status is RunStatus.MAX_ROUNDS:
- return "" if "max_rounds" in raised else f"{detail}: raise --rounds to continue it"
- finished = (RunStatus.NO_CHANGE, RunStatus.NO_REFINE_TASKS)
- return detail if status in finished else ""
-
-
-def _clock_spent(ws, max_minutes: float) -> str:
- """Why a resume would stop at once, or "": the active minutes (kept across ``--force``) are at the cap."""
- from codeverse3d.orchestrator import BudgetSnapshot, RunState, StateCorrupt
-
- try:
- state = RunState.load(ws)
- except StateCorrupt:
- return ""
- snap = (state.extra.get("budget_snapshot") if state is not None else None) or {}
- used = BudgetSnapshot.model_validate(snap).active_s / 60.0
- return f"its clock is spent ({used:.1f} of {max_minutes:g} active minutes)" if used >= max_minutes else ""
-
-
-def resume(
- slug: str,
- runs_dir: RunsDirOpt = None,
- max_minutes: Annotated[
- float | None,
- typer.Option("--max-minutes", min=0, help="raise the time cap before resuming"),
- ] = None,
- rounds: Annotated[
- int | None,
- typer.Option("--rounds", min=0, help="new max refine rounds (rewrites spec.json)"),
- ] = None,
- force: Annotated[
- bool,
- typer.Option(
- "--force",
- help="start the run again from round 0: the old rounds and record are ALWAYS archived "
- "under rounds/pre_force/ (so drifted pre-round stages regenerate); also re-enters a "
- "finished run and allows resuming after a spec edit (the run then re-plans)",
- ),
- ] = False,
- no_pick: Annotated[bool, typer.Option("--no-pick", help="do not pick + package a round afterwards")] = False,
-) -> None:
- """Resume an interrupted / partial run (or start a `--no-run` one); a finished run needs --force."""
- C.check_minutes(max_minutes)
- ws = C.open_workspace(slug, runs_dir)
- # the run mutex, before the spec is rewritten
- with C.mutating(ws, what=f"3dcodeverse resume {ws.root.name}"):
- spec = C.load_spec(ws)
- raised = {
- k: v
- for k, v in {"max_minutes": max_minutes, "max_rounds": rounds}.items()
- if v is not None
- }
- if spent := _clock_spent(ws, raised.get("max_minutes", spec.budget.max_minutes)):
- raise C.CliError(f"run {ws.root.name}: {spent} — raise --max-minutes to continue it"
- + (" (--force keeps the clock: it would archive every round and stop at once)" if force else ""))
- if not force and (why := _finished_reason(ws, raised)):
- raise C.CliError(
- f"run {ws.root.name} already finished ({why}); nothing to resume. "
- f"`3dcodeverse status {ws.root.name}` to look at it, or --force to re-enter it "
- f"(that re-plans, re-scores and overwrites the final state)."
- )
- if raised:
- from codeverse3d.proc import EventLog
-
- spec = spec.model_copy(update={"budget": spec.budget.model_copy(update=raised)})
- ws.write_json(ws.spec_path, spec)
- EventLog(ws.events_path).emit("budget.raised", **raised)
- _run_track(spec, ws, resume=True, force=force, pick=not no_pick)
-
-
-def pick(
- slug: str,
- round_index: Annotated[int | None, typer.Option("--round", min=0, help="hand over this round instead")] = None,
- runs_dir: RunsDirOpt = None,
-) -> None:
- """Choose the round of a finished run to hand over and package it: deliverable/ + selection.json."""
- from c3d_flywheel import select
- from c3d_flywheel.cost.instrument import run_ledger
- from c3d_flywheel.record.record import RecordError
-
- ws = C.open_workspace(slug, runs_dir)
- # writes deliverable/ + selection.json: one writer per run dir
- with (C.mutating(ws, what=f"3dcodeverse pick {ws.root.name}", action="pick"),
- run_ledger(ws.root, run=ws.root.name, create=False)):
- try:
- idx = _pick_and_package(ws, round_index=round_index)
- rows = select.round_rows(ws.root)
- except RecordError as e:
- raise C.CliError(str(e), code=2) from e
- if idx is None:
- raise typer.Exit(code=1)
- console.print(C.rounds_table(rows, idx))
-
-
-# --------------------------------------------------------------------------- judge
-from c3d_flywheel.cli.inspect_cmd import judge # noqa: E402
-
-app.command()(judge)
-
-
-# --------------------------------------------------------------------------- mcp
-def mcp(workspace: Annotated[Path, typer.Option("--workspace")]) -> None:
- """Serve the spatial tools over stdio MCP."""
- if not workspace.is_dir():
- raise C.CliError(f"workspace not found: {workspace}")
- os.execvp(
- sys.executable,
- [sys.executable, "-m", "codeverse3d.spatial.mcp_server", "--workspace", str(workspace)],
- )
-
-
-# --------------------------------------------------------------------------- the single-run view (show, status)
-from c3d_flywheel.cli.layout_cmd import show, status # noqa: E402
-
-app.command()(show)
-app.command()(status)
-
-
-if __name__ == "__main__": # pragma: no cover
- app()
diff --git a/harness/codeverse3d/config.py b/harness/codeverse3d/config.py
index f00b6184..61058d32 100644
--- a/harness/codeverse3d/config.py
+++ b/harness/codeverse3d/config.py
@@ -1,10 +1,7 @@
-"""Harness settings: keys, binaries, directories, defaults.
+"""Instrument settings: binaries, directories, render and gate knobs.
Resolution order (later wins): built-in defaults < ``~/.config/3dcodeverse/config.yaml``
-< ``./3dcodeverse.yaml`` < environment variables (``C3D_*``). Secrets are never
-written to run records.
-
-Gemini keys: ``GEMINI_API_KEYS`` (csv), ``GEMINI_API_KEY`` or ``~/.config/astra3d/gemini_keys.env``.
+< ``./3dcodeverse.yaml`` < environment variables (``C3D_*``).
Every ``C3D_*`` knob is a field here, read through ``get_settings()``. A field ``x`` is
``C3D_X`` (nested ``section.x`` is ``C3D_SECTION__X``, plus :data:`Settings.FLAT`); an on/off
@@ -15,7 +12,6 @@ from __future__ import annotations
import logging
import os
-import re
import shutil
from functools import lru_cache
from pathlib import Path
@@ -36,10 +32,6 @@ from pydantic import (
from pydantic_core import PydanticUseDefault
from pydantic_settings import BaseSettings, SettingsConfigDict
-from codeverse3d.contracts.agent import AGENT_TIMEOUT_S
-from codeverse3d.contracts.common import Backends
-
-_LEGACY_KEYS_FILE = Path.home() / ".config" / "astra3d" / "gemini_keys.env"
_USER_CONFIG = Path.home() / ".config" / "3dcodeverse" / "config.yaml"
@@ -56,31 +48,15 @@ def _or_default(value: Any, handler: ValidatorFunctionWrapHandler, info: Validat
#: an on/off switch (on/off, 1/0, true/false, yes/no); anything else keeps the default
Flag = Annotated[bool, WrapValidator(_or_default)]
-Count = Annotated[int, Field(ge=0), WrapValidator(_or_default)]
-#: the supported Blender (5.2 LTS); ``3dcodeverse doctor`` fails anything older.
+#: the supported Blender (5.2 LTS); ``3dcode doctor`` fails anything older.
BLENDER_MIN: tuple[int, int] = (5, 2)
class Binaries(BaseModel):
blender: str = Field(default="", description="path to the Blender 5.2 LTS binary (headless capable)")
node: str = "node"
- claude_cli: str = "claude"
- codex_cli: str = "codex"
- agy_cli: str = "agy"
-
-
-class Agents(BaseModel):
- codex_reasoning_effort: str = Field(
- default="high",
- description="`-c model_reasoning_effort=` passed to every `codex:` call (agent and one-shot). "
- "One of minimal|low|medium|high|xhigh, or '' to leave the choice to ~/.codex/config.toml. "
- "Override per id with `codex:<model>@<effort>`.")
- claude_effort: str = Field(
- default="xhigh",
- description="`--effort` passed to every `claude-code:` session (low|medium|high|xhigh|max; '' leaves it "
- "to the CLI). A harness session reads no user settings, so the effort is stated here.")
class Render(BaseModel):
@@ -114,45 +90,20 @@ class Render(BaseModel):
class Limits(BaseModel):
build_timeout_s: int = 300
render_timeout_s: int = 300
- agent_timeout_s: int = AGENT_TIMEOUT_S
bpy_rlimit_gb: int = 12
- # These size the subprocess side (blender / node / chrome, bound by cores); the model-call
- # ceiling is Rate.max_in_flight.
- max_parallel_agents: int = Field(default=12, ge=1, description="thread fan-out for agent tasks (>= 1)")
- max_parallel_builds: int = Field(default=8, ge=1, description="concurrent build subprocesses (>= 1)")
-
-
-class Rate(BaseModel):
- """The model-call ceiling.
-
- ``max_in_flight`` is machine-wide (flock'd slot files under ``<cache_dir>/slots/``), separate
- from the core-bound ``Limits`` fan-outs. 0 = unlimited. A vendor CLI session takes a key
- but no slot.
- """
-
- max_in_flight: int = Field(
- default=96,
- ge=0, # negative is not "unlimited" (0 is); a negative would poison the slot accounting
- description="machine-wide cap on concurrent model calls (0 = off): every process draws from the same "
- "N slot files. Measured knee with 22 keys: 72.9 calls/min at 64 in flight, 47.2 at 128; 96 serves "
- "the 30-key pool.")
class Judge(BaseModel):
- max_px: int = Field(default=1024, description="longest edge of a montage / crop sent to the judge")
- montages: int = Field(default=5, description="max 2x2 montages per verdict (14-view rig, D47)")
- detail_crops: int = Field(default=2, description="max zoomed detail crops per verdict")
- samples: int = Field(default=1, description="default VLM samples per verdict")
+ """What the judge pack contains (``judge_pack``)."""
+
+ max_px: int = Field(default=1024, description="longest edge of a montage / crop in the judge pack")
+ montages: int = Field(default=5, description="max 2x2 montages per pack (14-view rig)")
+ detail_crops: int = Field(default=2, description="max zoomed detail crops per pack")
slices: Literal["on-error", "off"] = Field(
default="on-error",
- description="conditional cross-section slices (C3D_JUDGE__SLICES): 'on-error' appends ≤2 interior "
- "slice images + one provenance sentence to an object-track verdict whose connectivity gate carries "
- "an ERROR; clean rounds build a byte-identical payload either way.")
- thinking: Annotated[Literal["off", "low", "medium", "high"], BeforeValidator(lambda v: str(v).strip().lower())] = Field(
- default="medium",
- description="VLM judge thinking level (C3D_JUDGE__THINKING; models/gemini.THINKING_BUDGET). "
- "gemini-4-argon thinks only from 'medium' (4096): within-sd .012 vs .029 at low, same cost. "
- "`3dcodeverse judge --thinking` replays with another level.")
+ description="conditional cross-section slices (C3D_JUDGE__SLICES): 'on-error' appends up to 2 interior "
+ "slice images + one provenance sentence to an object-track pack whose connectivity gate carries "
+ "an ERROR; clean rounds get a byte-identical pack either way.")
class Placement(BaseModel):
@@ -180,7 +131,6 @@ class Settings(BaseSettings):
#: nested knobs with a flat spelling; the flat one wins
FLAT: ClassVar[dict[str, tuple[str, str]]] = {
- "C3D_MAX_IN_FLIGHT": ("rate", "max_in_flight"),
"C3D_RENDER_GPU": ("render", "gpu"),
}
@@ -210,25 +160,13 @@ class Settings(BaseSettings):
"(CONTACT_TOL_M / FLOATING_M / SUNK_M); change both together")
return v
- runs_dir: Path = Field(default=Path("runs"))
cache_dir: Path = Field(default=Path.home() / ".cache" / "codeverse3d")
binaries: Binaries = Field(default_factory=Binaries)
- agents: Agents = Field(default_factory=Agents)
render: Render = Field(default_factory=Render)
limits: Limits = Field(default_factory=Limits)
- rate: Rate = Field(default_factory=Rate)
judge: Judge = Field(default_factory=Judge)
placement: Placement = Field(default_factory=Placement)
- gemini_api_keys: list[str] = Field(default_factory=list)
- anthropic_api_key: str = ""
- openai_api_key: str = ""
- openai_base_url: str = ""
-
- default_planner: str = Field(default_factory=lambda: Backends().planner)
- default_generator: str = Field(default_factory=lambda: Backends().generator)
- default_judge: str = Field(default_factory=lambda: Backends().judge)
- default_captioner: str = Field(default_factory=lambda: Backends().captioner)
ray_engine: Literal["numpy", "embree"] = Field(
default="embree",
description="ray engine of the deterministic inside tests (connectivity penetration, pose sweep): Embree via "
@@ -236,27 +174,7 @@ class Settings(BaseSettings):
"triangles) for a GLB on which embreex 4 segfaults. C3D_RAY_ENGINE.",
)
- model_timeout_s: float = Field(
- default=1200.0,
- description="HTTP read timeout for ONE API model call (per attempt): a ceiling, generous on purpose "
- "(a 55k-token plan streams for ~930 s at p10; time may be generous, errors may not).")
-
# ------------------------------------------------------------------ switches
- # tracks/plan_features.py derives the live C3D_* names from these fields.
- skills: Flag = Field(default=True, description="route, materialise and measure skill bundles "
- "(D81, on since 2026-09-22); C3D_SKILLS=0 is an A/B's no-skills arm")
- skills_only: str = Field(default="", description="comma list: the router considers ONLY these "
- "bundles, so an effect A/B can attribute its delta to one; an unknown name "
- "routes nothing")
- skills_dir: Path | None = Field(default=None, description="another skill library (tests, the live "
- "CLI smoke)")
- plan_brief: Flag = Field(default=True, description="expand the engineering brief before planning "
- "(object tracks)")
- plan_restart: Flag = Field(default=True, description="re-sample a degenerate plan from the original "
- "prompt instead of editing it in context (docs/COST.md §30)")
- zone_layouts: Flag = Field(default=True, description="scene track: the L2 zone-layout planner calls")
- axis_repair: Flag = Field(default=True, description="articulated track: rewrite a joint axis the "
- "measured motion proves wrong, before the sweep renders")
settle: Flag = Field(default=True, description="scene driver: the boot-time auto-seat")
camera_repair: Flag = Field(default=True, description="scene driver: move a camera out of geometry "
"(zero triggers on a healthy battery; the case it exists for is fatal)")
@@ -265,21 +183,6 @@ class Settings(BaseSettings):
"non-editable install must point this at a checkout")
# ------------------------------------------------------------------ helpers
- def backends(self, **overrides: str | None) -> Backends:
- base: dict[str, str] = {
- "planner": self.default_planner,
- "generator": self.default_generator,
- "judge": self.default_judge,
- "captioner": self.default_captioner,
- }
- unknown = set(overrides) - set(base)
- if unknown:
- raise TypeError(f"unknown backend role(s): {sorted(unknown)} (roles: {sorted(base)})")
- for role, value in overrides.items():
- if value:
- base[role] = value
- return Backends(**base)
-
def resolve_blender(self) -> str:
"""The configured binary, else the first Blender on PATH; a configured-but-missing one is ``""``."""
if self.binaries.blender:
@@ -295,7 +198,7 @@ class Settings(BaseSettings):
d = self.runtime_js.expanduser() if self.runtime_js else Path(__file__).resolve().parent.parent / "runtime_js"
if not d.is_dir():
raise RuntimeError(
- f"runtime_js not found at {d} — install the harness editable (pip install -e harness) "
+ f"runtime_js not found at {d} — install the plugin editable (pip install -e harness) "
"or set C3D_RUNTIME_JS to a 3dcodeverse/harness/runtime_js checkout (with node_modules installed)"
)
return d
@@ -315,24 +218,6 @@ def _load_yaml(path: Path) -> dict:
return data
-def _legacy_gemini_keys() -> list[str]:
- 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
-
-
def _deep_merge(base: dict, overlay: dict) -> dict:
out = dict(base)
for k, v in overlay.items():
@@ -348,14 +233,4 @@ def get_settings() -> Settings:
data: dict = {}
for p in (_USER_CONFIG, Path("3dcodeverse.yaml")):
data = _deep_merge(data, _load_yaml(p))
- 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
+ return Settings(**data)
diff --git a/harness/codeverse3d/contracts/__init__.py b/harness/codeverse3d/contracts/__init__.py
index 0588bac9..8141f4f9 100644
--- a/harness/codeverse3d/contracts/__init__.py
+++ b/harness/codeverse3d/contracts/__init__.py
@@ -1,14 +1,10 @@
-"""Typed contracts shared across the harness. Data + validators — no I/O, no model calls.
+"""Typed contracts shared by every instrument. Data + validators — no I/O.
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) and
- 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.
+- ``common`` enums (track, language), the entry files, joint-coupling rules.
+- ``spec`` what the project asks for (``spec.json``).
+- ``plan`` the agent's plan (parts / joints / zones / passes / acceptance), validated in code.
+- ``artifacts`` what instruments produce (builds, measurements, renders, gate reports) and the judgment shape.
Every name is imported from its module; the package itself re-exports nothing.
"""
diff --git a/harness/codeverse3d/contracts/agent.py b/harness/codeverse3d/contracts/agent.py
deleted file mode 100644
index 9e896635..00000000
--- a/harness/codeverse3d/contracts/agent.py
+++ /dev/null
@@ -1,151 +0,0 @@
-"""CodingAgent job/result — one headless agentic session on a workspace.
-
-Trust model (cooperative, by design): generated code and agent sessions run with local
-filesystem access and no network sandbox; the mitigation is that secrets are scrubbed
-from their environment (``codeverse3d.proc.scrub_secrets`` for the generated-code
-runtimes, ``agents/cli_common.hardened_env`` for the coding-agent CLIs).
-"""
-
-from __future__ import annotations
-
-from typing import Literal
-
-from pydantic import BaseModel, Field, model_validator
-
-from codeverse3d.contracts.common import Usage
-
-#: one agent session's wall clock — ``Settings.limits.agent_timeout_s`` defaults to it
-AGENT_TIMEOUT_S = 1800
-
-#: the thinking effort a caller may ask an agent session for (``AgentJob.effort``)
-AgentEffort = Literal["low", "medium", "high"]
-
-
-class FileChange(BaseModel):
- path: str
- status: str # added | modified | deleted
-
-
-class AgentJob(BaseModel):
- workspace: str
- prompt: str
- system_append: str = ""
- label: str = ""
- timeout_s: int = AGENT_TIMEOUT_S
- hard_deadline_s: float | None = Field(
- default=None, ge=0, allow_inf_nan=False,
- description="absolute time.monotonic() deadline on this host, derived from the run's "
- "remaining hard clock before queuing. Shared by retries; recomputed on resume. "
- "None preserves the standalone CLI's session grace",
- )
- effort: AgentEffort | None = Field(
- default=None,
- description="the thinking effort a caller explicitly asked for (GenerationTask.thinking); None = the "
- "backend's own default. Read by agy only (``--effort``; a ``-low/-medium/-high`` model suffix still "
- "wins, and with neither the session runs at AGY_API_EFFORT = high — owner, 2026-10-15). claude-code "
- "and codex take their effort from Settings.agents (claude_effort / codex_reasoning_effort) and ignore it",
- )
- #: consumed only by claude-code (``--max-turns``); codex / agy have no
- #: turn flag and run unbounded except by ``timeout_s`` and the run's wall clock
- max_turns: int = 60
- spatial_tools: bool = Field(
- default=True, description="expose the 3dcode 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)
- # ------------------------------------------------------------- typed job context
- round: int = Field(default=0, description="round index → trajectory dir + ToolContext")
- kind: str = Field(
- default="", description="task kind: baseline | refine | repair | asset | zone ..."
- )
- language: str = Field(default="", description="spec language (spatial tool filtering)")
- track: str = Field(default="", description="spec track (spatial tool filtering)")
- files_hint: list[str] = Field(
- default_factory=list,
- description="workspace-relative files/dirs this task is expected to touch (the "
- "``edit_only`` scope)",
- )
- edit_only: bool = Field(
- default=False,
- description="ENFORCE files_hint: an existing file outside it cannot be overwritten (new files "
- "and the language entry file stay allowed). Refine tasks set this so a session fixing one "
- "part cannot rewrite its neighbours.",
- )
- always_writable: list[str] = Field(
- default_factory=list,
- description="files exempt from edit_only (the entry file, and only when the task OWNS it — "
- "see GenerationTask.owns_entry: adding a part means importing it there)",
- )
- read_only: list[str] = Field(
- default_factory=list,
- description="harness-owned files inside write_roots the agent may read but never write "
- "(scene_threejs's src/lib/: contracts.common.HARNESS_OWNED_SRC); enforced "
- "post-session: a write to one is reverted and the session failed",
- )
- shared_tree: bool = Field(
- default=False,
- description="other harness writers change this workspace WHILE the session runs (the scene env stage "
- "beside the asset single-shots, which take no session lock — D111): ``files_changed`` counts only "
- "``files_hint`` and only a write to a ``files_hint`` path (or a step the CLI records, D112) is watchdog activity. Needs a ``files_hint``; "
- "never with ``edit_only`` (a sibling's write cannot be told from an out-of-scope one, so the scope "
- "revert would undo the sibling's work)",
- )
-
- @model_validator(mode="after")
- def _shared_tree_scope(self) -> AgentJob:
- if self.shared_tree and (self.edit_only or not any(str(h).strip() for h in self.files_hint)):
- raise ValueError("shared_tree needs a files_hint and excludes edit_only")
- return self
-
-
-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
- provider_wait_s: float = Field(
- default=0.0, ge=0.0,
- description="seconds of ``duration_s`` the session lost to provider errors — 503 / 429 / "
- "overloaded / token-limit retries and their back-off inside the CLI — read from the CLI's "
- "own log; 0.0 when none were seen or the CLI does not expose them. A step's effective "
- "time is ``duration_s - provider_wait_s`` (owner, 2026-09-22). Sources "
- "(cli_common.provider_wait): claude-code its stream-json ``api_retry`` events; agy the retry lines of its ``--log-file``; "
- "codex none (its HTTP client retries without an event)",
- )
- usage_estimated: bool = Field(
- default=False, description="``usage`` is an estimate, not the vendor's count: a codex session "
- "killed before its turn completed reports none (backends.CodexEvents.estimated_usage); its ledger "
- "row says source=\"estimate\"",
- )
- effort: str = Field(
- default="", description="the effort the backend actually passed its CLI (agy ``--effort``, claude-code "
- "``--effort``, codex ``model_reasoning_effort``); '' = none passed, the CLI's own default")
- tool_calls: int = 0
- turns: int = Field(
- default=0, description="model turns as the backend counts them (claude-code num_turns, codex "
- "turn.completed events, agy num_turns)",
- )
- errors: list[str] = Field(default_factory=list)
- transient: bool = Field(
- default=False,
- description="the session died of a provider failure a retry may get through — 5xx / UNAVAILABLE / "
- "overloaded / a 429 rate limit / a dropped connection, as the CLI itself reported it — not of "
- "the task: the round loop re-runs such a round once",
- )
- stalled: bool = Field(
- default=False,
- description="the watchdog killed the session as IDLE (no output, no workspace write, no recorded "
- "step for the idle grace past its window) and it produced nothing: a hang, not the task's pace — "
- "one more session when the clock allows a minimum window (D112; cli_common.classify_end)",
- )
- quota: bool = Field(
- default=False,
- description="the vendor's usage limit or credits are spent (codex 'You've hit your usage limit', "
- "claude 'usage limit reached', an OpenAI insufficient_quota): nothing gets through until it "
- "resets, so the round loop stops the run as agent_quota instead of retrying the round",
- )
diff --git a/harness/codeverse3d/contracts/artifacts.py b/harness/codeverse3d/contracts/artifacts.py
index dd5cabb8..6167032a 100644
--- a/harness/codeverse3d/contracts/artifacts.py
+++ b/harness/codeverse3d/contracts/artifacts.py
@@ -9,7 +9,7 @@ from typing import Any, Literal
from pydantic import BaseModel, Field
-from codeverse3d.contracts.common import Usage, Vec3
+from codeverse3d.contracts.common import Vec3
class Severity(StrEnum):
@@ -19,8 +19,7 @@ class Severity(StrEnum):
class LintKind(StrEnum):
- """``data.kind`` of a ``lint:<language>`` finding. Read by ``skills.registry`` (``lint/*`` skill routing, ``lint/part_not_imported``)
- and the shader rubric's kind-less ``lint*`` cap; the rest are labels for the agent and the record."""
+ """``data.kind`` of a ``lint:<language>`` finding (the shader rubric's kind-less ``lint*`` cap reads them; the rest are labels)."""
SYNTAX = "syntax" # the file does not parse
MISSING_FILE = "missing_file" # an entry / planned part file is absent
@@ -42,8 +41,7 @@ class LintKind(StrEnum):
NONDETERMINISM = "nondeterminism" # an unseeded random source
-#: ``GateFinding.data["kind"]`` of a plan part that is still the skeleton's placeholder box;
-#: the next refine round puts it ahead of every other gate error.
+#: ``GateFinding.data["kind"]`` of a plan part that is still a placeholder box.
PLACEHOLDER_PART = "placeholder_part"
@@ -111,12 +109,12 @@ class BuildResult(BaseModel):
gates: list[GateReport] = Field(
default_factory=list,
description="the build's own gate reports (scene_threejs: scene_probe + shader_preflight; the graphics "
- "languages: gl_frames) — tracks/steps appends them to the round's gates, built or not",
+ "languages: gl_frames) — ``check`` appends them to the gates, built or not",
)
harness_failure: bool = Field(
default=False,
- description="the build did not fail on the model's code — the harness could not run it "
- "(driver output lost, browser gone). Never handed to the agent as a repair.",
+ description="the build did not fail on the agent's code — the instrument could not run it "
+ "(driver output lost, browser gone).",
)
@@ -164,7 +162,7 @@ class RenderView(BaseModel):
time_s: float | None = Field(default=None, description="animation time for scenes")
judge: bool | None = Field(
default=None,
- description="True/False once the judge subset is stamped at render time; None = not stamped (legacy rounds)",
+ description="True/False once the judge subset is stamped at render time; None = not stamped",
)
@@ -175,7 +173,7 @@ class RenderSet(BaseModel):
duration_ms: int = 0
console_errors: list[str] = Field(default_factory=list, description="(scenes) JS/WebGL errors seen")
fps: float | None = Field(default=None, description="(scenes) measured frame rate: a record only — it swings with "
- "the machine's load and renderer, so no gate or judge reads it (D99)")
+ "the machine's load and renderer, so no gate or judge reads it")
out_dir: str = Field(default="", description="directory the views (+ views.json/metrics.json) were written to")
# ===================================================================== judgment
@@ -211,12 +209,11 @@ class Judgment(BaseModel):
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 = ""
@property
def degraded(self) -> bool:
- """A judge glitch (outage, unparseable verdict), never a score: must not reach a pick or refine plan."""
+ """A judge glitch (unparseable verdict), never a score."""
if self.summary.startswith("judge_error:"):
return True
try:
diff --git a/harness/codeverse3d/contracts/chat.py b/harness/codeverse3d/contracts/chat.py
deleted file mode 100644
index b9b616fa..00000000
--- a/harness/codeverse3d/contracts/chat.py
+++ /dev/null
@@ -1,69 +0,0 @@
-"""ChatModel request/response shapes — provider-neutral."""
-
-from __future__ import annotations
-
-from typing import Any, Literal
-
-from pydantic import BaseModel, Field
-
-from codeverse3d.contracts.common import Usage
-
-
-class TextPart(BaseModel):
- type: Literal["text"] = "text"
- text: str
-
-
-class ImagePart(BaseModel):
- type: Literal["image"] = "image"
- path: str | None = None
- mime: str = "image/png"
- label: str = ""
-
-
-Part = TextPart | ImagePart
-
-
-class ChatMessage(BaseModel):
- role: Literal["user", "assistant"]
- 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 ChatRequest(BaseModel):
- messages: list[ChatMessage]
- system: str = ""
- response_schema: dict[str, Any] | None = Field(default=None, description="force JSON matching this schema")
- temperature: float = 0.7
- #: A ceiling, not a reservation: a low one truncates a thinking model mid-answer.
- max_output_tokens: int = 65_536
- thinking: Literal["off", "low", "medium", "high"] = "low"
- label: str = Field(default="", description="for logs/cost ledger: planner / judge / generate ...")
- max_wait_s: float | None = Field(
- default=None,
- gt=0,
- description="the longest this ONE logical call may spend, retries and their waits included; "
- "None = the model's default (models.retry.RETRY_DEADLINE_S). A caller clips it to what it "
- "can still afford (owner 2026-08-27: judge-sample and planner floors are 900 s).",
- )
-
-
-class ChatResponse(BaseModel):
- text: str = ""
- parsed: Any = None
- finish_reason: str = ""
- usage: Usage = Field(default_factory=Usage)
- raw: dict[str, Any] = Field(default_factory=dict)
diff --git a/harness/codeverse3d/contracts/common.py b/harness/codeverse3d/contracts/common.py
index c4080dc9..d718ef79 100644
--- a/harness/codeverse3d/contracts/common.py
+++ b/harness/codeverse3d/contracts/common.py
@@ -41,24 +41,12 @@ TRACK_LANGUAGES: dict[Track, tuple[Language, ...]] = {
Track.GRAPHICS: (Language.GLSL_SHADER, Language.OPENGL_PYTHON),
}
-
-class TrackInfo(BaseModel):
- """Per-track registry row: default judge rubric + human label."""
-
- model_config = ConfigDict(frozen=True)
-
- rubric: str = Field(description="rubric name under judges/rubrics/, e.g. 'static_object'")
- label: str = Field(description="human label for galleries / captions / reports")
- likeness_refs: bool = Field(default=False, description="reference images are a look to match (LikenessJudge, "
- "the likeness prompt note), not a silhouette to measure")
-
-
-#: one registry row per track
-TRACK_INFO: dict[Track, TrackInfo] = {
- Track.STATIC_OBJECT: TrackInfo(rubric="static_object", label="3D Objects"),
- Track.ARTICULATED_OBJECT: TrackInfo(rubric="articulated", label="Articulated Objects"),
- Track.SCENE: TrackInfo(rubric="scene", label="3D Scenes", likeness_refs=True),
- Track.GRAPHICS: TrackInfo(rubric="shader", label="Procedural Graphics", likeness_refs=True),
+#: the rubric (``judges/rubrics/<name>.yaml``) each track is judged on
+TRACK_RUBRIC: dict[Track, str] = {
+ Track.STATIC_OBJECT: "static_object",
+ Track.ARTICULATED_OBJECT: "articulated",
+ Track.SCENE: "scene",
+ Track.GRAPHICS: "shader",
}
#: entry file inside the workspace per language — the file a build starts from.
@@ -73,97 +61,6 @@ ENTRY_FILE: dict[Language, str] = {
Language.OPENGL_PYTHON: "src/program.py",
}
-#: source files the HARNESS writes under ``src/``: the agent reads and calls them, never writes them.
-#: An entry ending in ``/`` is a directory prefix; otherwise an exact file.
-HARNESS_OWNED_SRC: dict[Language, tuple[str, ...]] = {
- Language.SCENE_THREEJS: ("src/lib/",),
-}
-
-
-def is_harness_owned(rel: str, owned: Collection[str]) -> bool:
- """Is ``rel`` a harness-owned source file, given a language's ``HARNESS_OWNED_SRC``?
-
- Exact match, or under a directory entry (one ending in ``/``).
- """
- return any(rel == o or (o.endswith("/") and rel.startswith(o)) for o in owned)
-
-#: human label per language (galleries, captions, reports)
-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)",
- Language.SCENE_BLENDER: "Blender scene (multi-file bpy)",
- Language.GLSL_SHADER: "GLSL fragment shader",
- Language.OPENGL_PYTHON: "OpenGL (moderngl Python + GLSL)",
-}
-
-
-def code_file(language: Language) -> str:
- """Top-level flywheel copy of the entry file: ``code`` + the entry suffix."""
- entry = ENTRY_FILE[language]
- return "code" + entry[entry.rfind(".") :]
-
-
-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 (rounds, minutes); the orchestrator stops cleanly when one is hit.
-
- Ceilings are non-negative by construction (a negative one is an unrunnable budget).
- Cost is recorded but never gates anything. ``extra="forbid"`` makes unknown keys raise.
- """
-
- model_config = ConfigDict(extra="forbid")
-
- max_rounds: int = Field(default=4, ge=0)
- max_minutes: float = Field(default=60.0, ge=0, allow_inf_nan=False)
- max_repair_attempts: int = Field(default=3, ge=0) # per build failure before escalating
-
-
-class Backends(BaseModel):
- """Which model/agent does which job. Ids are ``<kind>:<model>``:
-
- * API chat models: ``gemini:gemini-4-argon`` · ``anthropic:claude-opus-5-5``
- · ``openai:gpt-6.1-sol``
- * Coding agents: ``agy:gemini-4-argon`` (``-low``/``-medium``/``-high``; Gemini models only) · ``claude-code:sonnet``
- · ``codex:gpt-6.1-sol``
-
- The coding agent is always a vendor agent: the harness supplies the workspace, prompt
- and 3D tools (over MCP) and reads the result.
- """
-
- planner: str = "gemini:gemini-4-argon"
- generator: str = "agy:gemini-4-argon"
- judge: str = "gemini:gemini-4-argon"
- captioner: str = "gemini:gemini-4-argon"
-
# ------------------------------------------------------------------ joint coupling
#: |multiplier| below this is a coupling that transmits no motion (shared by plan, lint and loader).
diff --git a/harness/codeverse3d/contracts/plan.py b/harness/codeverse3d/contracts/plan.py
index 74caeb95..bc67685f 100644
--- a/harness/codeverse3d/contracts/plan.py
+++ b/harness/codeverse3d/contracts/plan.py
@@ -1,7 +1,6 @@
-"""Plans: the planner's structured decomposition, each with an acceptance checklist.
+"""Plans: the agent's structured decomposition, each with an acceptance checklist.
-Written by an LLM under a JSON schema, then validated in code; invalid plans are re-asked
-with the validation errors."""
+Written by the host agent as ``plan.json``, then validated in code (``3dcode validate-plan``)."""
from __future__ import annotations
@@ -253,7 +252,7 @@ class ArticulatedPlan(StaticPlan):
joints: list[JointPlan] = Field(min_length=1)
normalisations: list[str] = Field(
default_factory=list,
- description="filled by the harness, leave empty: automatic corrections applied to the planner's answer "
+ description="filled by validate-plan, leave empty: automatic corrections applied to the plan "
"before validation (a sub-part promoted to a link because a joint moves it, revolute limits "
"written in degrees converted to radians or a > 2π radian range made continuous, swapped "
"or out-of-range limits clamped, a parent bbox grown around a sub-part)")
@@ -624,92 +623,6 @@ def scene_plan_schema(language: Language | str) -> dict[str, Any]:
return schema
-class ZonePlacement(BaseModel):
- """One asset's placement inside a zone, decided by the L2 zone director.
-
- Typed rows with concrete numbers on purpose (the RefDimension lesson: an
- open-ended dict maps to a property-less schema and the model answers ``{}``)."""
-
- asset: str = Field(description="asset name from the plan")
- count: int = Field(ge=1, description="how many instances in this zone")
- cluster: tuple[float, float] = Field(description="cluster centre (x, z) in WORLD meters, inside the zone bbox")
- spread_m: float = Field(ge=0, description="radius the instances scatter within (0 = exactly at the centre)")
- faces: str = Field(default="", description="what the instances face, e.g. 'the path', 'azimuth 220'")
- support: str = Field(default="ground", description="'ground' or the asset they stand on")
-
-
-class ZoneLayout(BaseModel):
- """The L2 layout for ONE zone: where its planned contents actually go.
-
- Produced by a cheap structured call per zone (parallel, never an agent),
- validated deterministically against the zone bbox and the plan before it is
- handed to the zone builder — the builder realises a layout instead of
- inventing one."""
-
- zone: str = Field(description="the zone's name, exactly as planned")
- placements: list[ZonePlacement] = Field(default_factory=list)
- path_points: list[tuple[float, float]] = Field(
- default_factory=list, description="(x, z) polyline of the walkway through this zone, if any")
- mid_props: int = Field(default=0, ge=0, description="loose mid props (0.3-1.5 m) beyond the placements; 0 for a bare place")
- small_props: int = Field(default=0, ge=0, description="small props (< 0.3 m); 0 for a bare place")
- ground_cover: int = Field(default=0, ge=0, description="instanced tufts / pebbles; 0 where the ground is bare")
- notes: str = Field(default="", description="one line of layout intent, e.g. 'stalls face the lane'")
-
-
-class RefDimension(BaseModel):
- """One reference dimension of the real object. A LIST of typed rows, not a free
- ``dict[str, float]``: an open-ended object maps to a property-less ``{"type":
- "object"}`` in the Gemini structured-output schema, and the model then answers ``{}``
- every time (measured on the first live run of this wave)."""
-
- name: str = Field(description="width | depth | height | length | diameter | wall_thickness | …")
- meters: float = Field(description="the real-world size in METERS")
-
-
-class SubAssembly(BaseModel):
- """One sub-assembly a real instance of the requested object has."""
-
- name: str = Field(description="what a catalogue would call it, e.g. 'burr mechanism'")
- purpose: str = Field(default="", description="what it does, one line")
- parts: list[str] = Field(default_factory=list, max_length=10,
- description="the parts it is made of, named as a fitter would name them")
- material: str = Field(default="", description="dominant material / finish")
-
-
-class EngineeringBrief(BaseModel):
- """The expanded engineering brief for ONE request: what a person who has actually held
- the object knows about it. Produced by a cheap model call *before* planning
- and folded into the plan; never a deliverable of its own.
-
- The load-bearing fields are REQUIRED on purpose. Measured on the first live run: with
- every field defaulted, gemini-3.7-flash answered three of four requests with
- ``sub_assemblies: []`` and ``signature_features: []`` — a schema that lets the model
- say nothing gets nothing. Only the two genuinely-sometimes-empty lists keep defaults.
- """
-
- object_name: str = Field(description="PascalCase name of the thing")
- reference: str = Field(description="the real-world reference instance the numbers come from")
- one_line: str = Field(description="what it is, one sentence")
- dimensions_m: list[RefDimension] = Field(
- max_length=12, description="up to 12 real-world reference dimensions in METERS, the small ones included")
- sub_assemblies: list[SubAssembly] = Field(max_length=10, description="up to 10 assemblies a fitter would name")
- mechanism: str = Field(description="how it works / how force or material moves through it")
- visible_from_outside: list[str] = Field(
- max_length=16, description="up to 16 things a viewer actually sees from outside — the only things worth modelling")
- signature_features: list[str] = Field(
- max_length=6, description="up to 6 features a viewer uses to recognise it — absence makes it the wrong object")
- materials: list[str] = Field(max_length=12, description="'<part>: <material, colour, finish>' lines, up to 12")
- hidden_inside: list[str] = Field(default_factory=list, max_length=10,
- description="real parts that are NOT visible and must not be modelled")
- not_present: list[str] = Field(default_factory=list, max_length=10,
- description="things a naive model would wrongly add")
-
- @property
- def is_useful(self) -> bool:
- """False when the brief tells the planner nothing and should be discarded."""
- return len(self.sub_assemblies) >= 2 or len(self.signature_features) >= 2
-
-
class PassPlan(BaseModel):
name: str = Field(description="PascalCase pass name, e.g. Clouds, Bloom")
kind: Literal["fullscreen", "geometry", "postprocess", "feedback"] = "fullscreen"
diff --git a/harness/codeverse3d/contracts/run.py b/harness/codeverse3d/contracts/run.py
deleted file mode 100644
index 07aeff86..00000000
--- a/harness/codeverse3d/contracts/run.py
+++ /dev/null
@@ -1,281 +0,0 @@
-"""The run record (``record.json``) and everything stored inside it: ``RunRecord``, ``RunId``,
-per-round skills usage, and the ``telemetry/`` + ``deliverable/`` blocks."""
-
-from __future__ import annotations
-
-from datetime import UTC, datetime
-from enum import StrEnum
-from pathlib import PurePosixPath
-from typing import Any, Literal
-
-from pydantic import BaseModel, ConfigDict, Field
-
-from codeverse3d.contracts.artifacts import (
- BuildResult,
- GateReport,
- Judgment,
- Measurement,
- RenderSet,
-)
-from codeverse3d.contracts.common import Usage
-from codeverse3d.contracts.plan import ArticulatedPlan, GraphicsPlan, ScenePlan, StaticPlan
-from codeverse3d.contracts.spec import Spec
-
-
-class SkillRead(BaseModel):
- """The read probe's verdict for one materialised skill bundle."""
-
- name: str
- surfaced: bool = Field(default=False, description="transcript: the agent activated the skill or opened its "
- "SKILL.md; atime fallback: SKILL.md atime > mtime (a discovery scan counts)")
- deep: bool = Field(default=False, description="transcript: the agent opened a file under its references/ (or "
- "its atime says so while the control's references/ are untouched — a shell read the "
- "trace cannot parse); atime fallback: a references/*.md atime > mtime")
- body_tokens: int = 0
- reason: str = Field(default="", description="which route attached it, and which finding")
-
-
-class SkillsUsage(BaseModel):
- """``RoundRecord.skills``: skills listed vs read vs what it cost, per round."""
-
- listed: list[str] = Field(default_factory=list)
- reads: list[SkillRead] = Field(default_factory=list)
- index_tokens: int = 0
- body_tokens_read: int = Field(default=0, description="tokens of the bodies the probe says were read deep")
- inlined: str = Field(default="", description="single-shot: the body inlined into the prompt, '' otherwise")
- control_read: bool = Field(
- default=False,
- description="the never-routed control bundle was 'read' too. Under atime evidence that "
- "means the probe was blind (every rate below is an upper bound); under "
- "transcript evidence it means the AGENT itself opened a bundle that matches "
- "nothing — a real read, and a sign it reads skills indiscriminately")
- control_present: bool = Field(default=False, description="a control bundle was materialised at all")
- evidence: Literal["atime", "transcript"] = Field(
- default="atime",
- description="where the reads came from: 'transcript' = the CLI's own tool calls, recorded by "
- "its backend in trajectories/*/transcript.jsonl (exact); 'atime' = the file-access "
- "probe, the fallback when a session left no tool trace")
-
- @property
- def surfaced(self) -> list[str]:
- return [r.name for r in self.reads if r.surfaced]
-
- @property
- def deep(self) -> list[str]:
- return [r.name for r in self.reads if r.deep]
-
- @property
- def deep_read_rate(self) -> float | None:
- """None when nothing is listed or the atime control shows the probe is blind (git and CLI
- activation touch files nobody chose to read). Transcript evidence is trusted as is."""
- if not self.listed or (self.evidence == "atime" and self.control_present and self.control_read):
- return None
- return len(self.deep) / len(self.listed)
-
-
-# ===================================================================== run
-# --------------------------------------------------------------------------- identity
-#: battery-layout path segments that are pure plumbing, never part of a run's identity
-RUN_PATH_NOISE = frozenset({"arms", "cells", "runs"})
-
-
-class RunId(BaseModel):
- """Where a run directory sits inside its scan root, and the one name to call it.
-
- ``battery`` labels the scan root; ``rel`` is the run dir's posix path relative to it.
- Only the scanner knows the root, so only it mints one (``record.record.run_id_for``)."""
-
- model_config = ConfigDict(frozen=True)
-
- battery: str = Field(description="label of the scan root this run was found under")
- rel: str = Field(description="posix path of the run dir relative to the scan root")
-
- def _parts(self) -> tuple[str, ...]:
- return PurePosixPath(self.rel).parts
-
- @property
- def slug(self) -> str:
- """The stable, filesystem-safe name of this run.
-
- A flat ``rel`` keeps its basename; a nested one joins its meaningful segments with ``__``
- (dropping :data:`RUN_PATH_NOISE` and a trailing ``run``)."""
- parts = self._parts()
- if len(parts) <= 1:
- return parts[0] if parts else self.battery
- meaningful = [p for p in parts if p not in RUN_PATH_NOISE]
- if len(meaningful) > 1 and meaningful[-1] == "run":
- meaningful.pop() # the literal `run` dir a battery cell wraps its harness run in
- if not meaningful:
- meaningful = [parts[-1]]
- return "__".join(meaningful)
-
-
-class RunStatus(StrEnum):
- """Where a run is, and once stopped, why it stopped. Never a verdict."""
-
- PLANNING = "planning"
- GENERATING = "generating"
- REFINING = "refining"
- MAX_ROUNDS = "max_rounds" # every round the budget asked for ran
- BUDGET = "budget" # the wall clock (``max_minutes``) ran out
- AGENT_QUOTA = "agent_quota" # the vendor's usage limit, not ours
- NO_CHANGE = "no_change" # a refine round's sessions all failed / changed nothing
- NO_REFINE_TASKS = "no_refine_tasks" # the last round left nothing to ask for
- JUDGE_UNAVAILABLE = "judge_unavailable" # the last round has no verdict, even after a re-judge
- FAILED = "failed"
-
-
-class StepTime(BaseModel):
- """One timed step: its wall clock and the part lost to provider errors (503 / 429 / timeouts).
-
- Parallel work is ONE step, so no second is counted twice."""
-
- step: str = Field(description="plan | skeleton | assets+env+layouts | zones | assemble"
- " | generate | build | gates | render | judge")
- round: int | None = Field(default=None, description="the round the step belongs to; None = a run-level stage")
- wall_s: float = 0.0
- lost_s: float = Field(default=0.0, description="seconds of wall_s lost to provider errors")
-
- @property
- def active_s(self) -> float:
- return max(0.0, self.wall_s - self.lost_s)
-
-
-class RoundRecord(BaseModel):
- index: int
- kind: str = Field(description="baseline | refine | repair | 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)
- skills: SkillsUsage | None = Field(
- default=None, description="skills attached to this round's sessions, and which were actually read")
- started_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
- duration_s: float = Field(default=0.0, description="the round's clock, provider errors included")
- steps: list[StepTime] = Field(
- default_factory=list, description="the round's timed steps (generate / build / gates / render / judge); "
- "empty until timing is recorded")
- notes: str = ""
-
- @property
- def score(self) -> float | None:
- return self.judgment.overall if self.judgment else None
-
- @property
- def minutes(self) -> float:
- """The round's timed steps, excluding provider wait."""
- return sum(s.active_s for s in self.steps) / 60.0
-
-
-# --------------------------------------------------------------------------- telemetry (settings + cost)
-class RoleSettings(BaseModel):
- """Resolved model settings for ONE role of a run.
-
- ``source``: ``run`` (stamped as it ran) or ``spec`` (only the model is known)."""
-
- role: str
- model: str = ""
- backend: str = Field(default="", description="gemini | anthropic | agy | claude-code | codex | …")
- thinking: str = Field(default="", description="off | low | medium | high; '' = not recorded")
- temperature: float | None = None
- n_samples: int | None = Field(default=None, description="judge samples per verdict")
- source: str = "spec"
-
-
-class SettingsSnapshot(BaseModel):
- """Everything that decided how the run ran."""
-
- roles: list[RoleSettings] = Field(default_factory=list)
- budget: dict[str, Any] = Field(default_factory=dict, description="max_rounds / max_minutes / max_repair_attempts")
- rubric: str = ""
- rubric_hash: str = Field(default="", description="content hash of the judge rubric YAML")
- prompt_hashes: dict[str, str] = Field(default_factory=dict, description="contract / generate / refine / repair / skill:<name> / judge …")
- tool_versions: dict[str, str] = Field(default_factory=dict, description="python / blender / node / three / chrome / harness sha")
- harness_version: str = ""
- harness_git_sha: str = ""
- key_pool_size: int = Field(default=0, description="number of API keys in the rotating pool")
- price_table_version: str = Field(default="", description="content hash of c3d_flywheel.models.pricing.PRICES")
- render: dict[str, Any] = Field(default_factory=dict, description="resolved render settings (size, gpu, sheet)")
-
-
-class StageCost(BaseModel):
-
- stage: str
- calls: int = 0
- input_tokens: int = 0
- output_tokens: int = 0
- cached_tokens: int = 0
- thoughts_tokens: int = 0
- cost_usd: float = 0.0
- seconds: float = 0.0
-
-
-class CostSummary(BaseModel):
- """The run's ledger rows summarised (``record.telemetry.cost``)."""
-
- total_usd: float = Field(default=0.0, description="the ledger's sum at list price = record.total_usage")
- minutes: float | None = Field(default=None, description="RunRecord.minutes when the record was written")
- max_minutes: float = 0.0
- n_calls: int = 0
- tokens: Usage = Field(default_factory=Usage, description="run totals (record.total_usage)")
- by_stage: list[StageCost] = Field(default_factory=list)
- by_role: dict[str, float] = Field(default_factory=dict, description="planner/generator/judge/… → USD")
- by_model: dict[str, float] = Field(default_factory=dict, description="model → USD")
- by_round: list[dict[str, Any]] = Field(default_factory=list, description="index / kind / cost_usd / minutes / score")
-
-
-class RunTelemetry(BaseModel):
-
- settings: SettingsSnapshot | None = None
- cost: CostSummary | None = None
-
-
-# --------------------------------------------------------------------------- deliverable
-class DeliverableFile(BaseModel):
-
- path: str = Field(description="run-relative path (under deliverable/)")
- role: str = Field(description="code | model | urdf | mesh | sheet | preview | frames | captions | bundle | manifest")
- bytes: int = 0
- sha256: str = ""
-
-
-class RunDeliverable(BaseModel):
- """``deliverable/manifest.json``: the handed-over round as paths + hashes + sizes."""
-
- round: int | None = Field(default=None, description="the packaged round")
- commit: str = ""
- entry: str = Field(default="", description="run-relative entry file of the code snapshot")
- files: list[DeliverableFile] = Field(default_factory=list)
-
-
-class RunRecord(BaseModel):
- """One run."""
-
- spec: Spec
- plan: StaticPlan | ArticulatedPlan | ScenePlan | GraphicsPlan | None = None
- workspace: str
- status: RunStatus = RunStatus.PLANNING
- rounds: list[RoundRecord] = Field(default_factory=list)
- 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(UTC))
- finished_at: datetime | None = None
- error: str = ""
- telemetry: RunTelemetry | None = Field(
- default=None, description="settings snapshot + cost summary (written by finalize_record)")
- steps: list[StepTime] = Field(
- default_factory=list, description="the run-level timed steps (plan, the pre-round stages, best-of-N, the part of "
- "an aborted round that ran)")
- extra: dict[str, Any] = Field(default_factory=dict)
-
- @property
- def minutes(self) -> float:
- """The run's minutes: ``wall_s - lost_s`` over every step. A statistic, not the budget
- clock (``BudgetGuard`` counts provider errors too)."""
- return sum(s.active_s for s in self.steps) / 60.0 + sum(r.minutes for r in self.rounds)
diff --git a/harness/codeverse3d/contracts/spec.py b/harness/codeverse3d/contracts/spec.py
index a59c840c..7fd6238f 100644
--- a/harness/codeverse3d/contracts/spec.py
+++ b/harness/codeverse3d/contracts/spec.py
@@ -1,4 +1,4 @@
-"""The Spec: everything the user asked for, frozen at run start."""
+"""The Spec: what the project asks for (``spec.json``, written by ``3dcode init``)."""
from __future__ import annotations
@@ -8,7 +8,7 @@ from typing import Any
from pydantic import BaseModel, Field, model_validator
-from codeverse3d.contracts.common import TRACK_LANGUAGES, Backends, Budget, Language, Track, Vec3
+from codeverse3d.contracts.common import TRACK_LANGUAGES, Language, Track, Vec3
class ReferenceImage(BaseModel):
@@ -19,7 +19,7 @@ class ReferenceImage(BaseModel):
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."""
+ acceptance item the plan 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}"
@@ -30,10 +30,9 @@ class Constraints(BaseModel):
class FixedPart(BaseModel):
- """A file the PROJECT seeds into ``src/`` that no session may rewrite: measured geometry (a survey shell), the
- data it reads, a shared library. The planner is told it is given and does not plan it; the agent imports it
- unchanged (an edit is reverted, like a language's ``HARNESS_OWNED_SRC``); the skeleton keeps it; and when it
- builds a part, the ``contract_fixed`` gate measures that part against ``bbox_min``/``bbox_max``."""
+ """A file the PROJECT seeds into ``src/`` that the agent may not rewrite: measured geometry (a survey shell), the
+ data it reads, a shared library. ``validate_plan`` refuses a plan that lists it as a part of its own, and when it
+ builds a part the ``contract_fixed`` gate measures that part against ``bbox_min``/``bbox_max``."""
path: str = Field(description="workspace-relative file under src/, e.g. 'src/parts/survey_shell.js'")
name: str = Field(default="", description="the GLB part it builds (a child of the root, e.g. 'SurveyShell'); "
@@ -51,10 +50,10 @@ FIXED_PARTS_GATE = "contract_fixed"
class ProjectCheck(BaseModel):
"""A deterministic check the PROJECT registers (``Spec.checks``): ``entry`` names a function
- (``package.module:function``, importable where the harness runs) that measures each round's GLB against
+ (``package.module:function``, importable where ``3dcode`` runs) that measures the built GLB against
what the project knows — survey geometry, catalogue dimensions — and returns ``GateReport``s. They take part
- exactly like the built-in gates under the name ``project:<name>``: ERRORs become refine tasks, the judge reads
- them, and a rubric ``CapRule(when="gate", gate="project:*")`` caps on them (``tracks/project_checks.py``)."""
+ exactly like the built-in gates under the name ``project:<name>``: the judge reads them and a rubric
+ ``CapRule(when="gate", gate="project:*")`` caps on them (``gates.run_project_checks``)."""
name: str = Field(pattern=r"^[a-z0-9][a-z0-9_]*$", description="gate suffix: reports are named project:<name>")
entry: str = Field(pattern=r"^[A-Za-z_][\w.]*:[A-Za-z_]\w*$", description="'package.module:function'")
@@ -62,20 +61,17 @@ class ProjectCheck(BaseModel):
class Spec(BaseModel):
- id: str
+ id: str = ""
track: Track
language: Language
prompt: str
references: list[ReferenceImage] = Field(default_factory=list)
constraints: Constraints = Field(default_factory=Constraints)
- # left out of spec.json while empty, so every spec without one serialises exactly as before
+ # left out of spec.json while empty
fixed_parts: list[FixedPart] = Field(default_factory=list, exclude_if=lambda v: not v,
- description="project-seeded files no session may rewrite (FixedPart)")
+ description="project-seeded files the agent may not rewrite (FixedPart)")
checks: list[ProjectCheck] = Field(default_factory=list, exclude_if=lambda v: not v,
- description="project checks run on every round's GLB (ProjectCheck)")
- budget: Budget = Field(default_factory=Budget)
- backends: Backends = Field(default_factory=Backends)
- tags: list[str] = Field(default_factory=list)
+ description="project checks run on every check's GLB (ProjectCheck)")
created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
@model_validator(mode="after")
diff --git a/harness/codeverse3d/conventions.py b/harness/codeverse3d/conventions.py
index f6ccbf7c..f578fff4 100644
--- a/harness/codeverse3d/conventions.py
+++ b/harness/codeverse3d/conventions.py
@@ -1,4 +1,4 @@
-"""Single source of truth for 3D conventions used by prompts, tools and gates.
+"""Single source of truth for 3D conventions used by the instruments, gates and skills.
Everything that talks about axes, units, frames, view presets or naming imports
from here — never restate a convention inline.
@@ -236,7 +236,7 @@ def fmt3(vec: Sequence[float]) -> str:
# --------------------------------------------------------------------------- limits
-#: Triangle ceilings; the object one is the depth gate's upper clamp (``tracks/depth.budget_gate``).
+#: Triangle ceilings; the object one is the depth gate's upper clamp (``gates.budget_gate``).
MAX_TRIS_OBJECT = 600_000
MAX_TRIS_SCENE = 3_000_000
#: Scene draw budget on the probe census's ``totals.draws``: ``scene_probe`` WARNs above the
diff --git a/harness/codeverse3d/doctor.py b/harness/codeverse3d/doctor.py
index 279adaad..ae769d7f 100644
--- a/harness/codeverse3d/doctor.py
+++ b/harness/codeverse3d/doctor.py
@@ -1,26 +1,26 @@
-"""Environment checks behind ``3dcodeverse doctor`` — python deps, Blender, node/three/
-puppeteer, the GPU probe, keys, the machine-wide in-flight slots, the vendor CLIs, MCP.
+"""Environment checks behind ``3dcode doctor`` / ``python -m codeverse3d.doctor``: python deps, Blender (+ Cycles),
+node / three / puppeteer, the headless-Chrome GPU probe. No keys, no model calls.
"""
from __future__ import annotations
import importlib
+import json
import re
import shutil
+import sys
from pathlib import Path
from codeverse3d.config import BLENDER_MIN, get_settings
from codeverse3d.proc import read_json_or_none, run_subprocess, version_line
Row = tuple[str, str, str]
-_PY_DEPS = ("pydantic", "pydantic_settings", "typer", "rich", "jinja2", "yaml", "numpy", "trimesh", "fcl", "PIL", "pyarrow",
- "scipy", "shapely", "networkx", "matplotlib", "google.genai", "anthropic", "openai",
- "yourdfpy", "mcp", "moderngl", "cadquery")
+_PY_DEPS = ("pydantic", "pydantic_settings", "yaml", "numpy", "trimesh", "fcl", "PIL",
+ "scipy", "shapely", "networkx", "matplotlib", "yourdfpy", "moderngl", "cadquery")
#: modules from an OPTIONAL extra: missing is a WARN naming the extra, not a broken install.
#: Every module of every extra must be listed here or the base install misreports itself.
_OPTIONAL_DEPS = {"shapely": "mesh", "networkx": "mesh", "matplotlib": "mesh",
- "yourdfpy": "urdf", "scipy": "urdf", "mcp": "mcp",
- "moderngl": "graphics", "cadquery": "cad", "pyarrow": "flywheel"}
+ "yourdfpy": "urdf", "scipy": "urdf", "moderngl": "graphics", "cadquery": "cad"}
def _ver(cmd: list[str]) -> tuple[bool, str]:
@@ -40,8 +40,6 @@ def check_python_deps() -> list[Row]:
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) <= set(_OPTIONAL_DEPS) else "FAIL")
detail = f"{len(present)}/{len(_PY_DEPS)} importable" + (f"; missing: {', '.join(missing)}" if missing else "")
@@ -103,8 +101,6 @@ print("C3D_DOCTOR " + json.dumps(out))
def check_blender_render(*, timeout_s: int = 120) -> list[Row]:
"""What scene_blender's judged frames render on: Cycles CUDA / CPU, GPU slots."""
- import json
-
from codeverse3d.languages.blender import blender_env
from codeverse3d.spatial.render_blender import gpu_slots
@@ -210,55 +206,7 @@ def check_gpu_probe(timeout_s: int = 120) -> list[Row]:
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)")]
- if n:
- from c3d_flywheel.models.gemini import shared_pool
-
- slots = shared_pool(list(s.gemini_api_keys)).slots
- if slots is None:
- rows.append(("in-flight slots", "WARN", "max_in_flight=0: no cap on concurrent model calls"))
- else:
- busy = slots.busy()
- rows.append(("in-flight slots", "WARN" if busy >= slots.n else "OK",
- f"{busy}/{slots.n} busy machine-wide ({slots.root}; docs/COST.md §23)"))
- 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:
- from c3d_flywheel.models.health import probe
-
- h = probe(sample=1) # one workload-sized call, no retries; never raises
- rows.append(("gemini live call", "OK" if h.ok else "FAIL", str(h)))
- return rows
-
-
-def check_clis() -> list[Row]:
- s = get_settings()
- rows: list[Row] = []
- for name, binary in (("agy", s.binaries.agy_cli), ("claude", s.binaries.claude_cli),
- ("codex", s.binaries.codex_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))
- 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("codeverse3d.spatial.mcp_server")
- return [("mcp", "OK", "mcp + codeverse3d.spatial.mcp_server importable")]
- except ImportError as e:
- return [("mcp", "WARN", f"codeverse3d.spatial.mcp_server not importable ({e})")]
-
-
-def run_doctor(*, live: bool = False, gpu: bool = True) -> list[Row]:
+def run_doctor(*, gpu: bool = True) -> list[Row]:
rows: list[Row] = []
rows += check_python_deps()
rows += check_blender()
@@ -266,7 +214,27 @@ def run_doctor(*, live: bool = False, gpu: bool = True) -> list[Row]:
rows += check_node()
if gpu:
rows += check_gpu_probe()
- rows += check_keys(live)
- rows += check_clis()
- rows += check_mcp()
+ okk, v = _ver(["git", "--version"])
+ rows.append(("git", "OK" if okk else "WARN", v))
return rows
+
+
+def format_rows(rows: list[Row]) -> str:
+ width = max(len(c) for c, _, _ in rows)
+ return "\n".join(f"{c.ljust(width)} {s:<4} {d}" for c, s, d in rows)
+
+
+def main(argv: list[str] | None = None) -> int:
+ import argparse
+
+ ap = argparse.ArgumentParser(prog="python -m codeverse3d.doctor", description=__doc__)
+ ap.add_argument("--gpu", action=argparse.BooleanOptionalAction, default=True, help="probe headless Chrome WebGL")
+ ap.add_argument("--json", dest="as_json", action="store_true")
+ ns = ap.parse_args(argv)
+ rows = run_doctor(gpu=ns.gpu)
+ print(json.dumps([{"check": c, "status": s, "detail": d} for c, s, d in rows], indent=1) if ns.as_json else format_rows(rows))
+ return 1 if any(s == "FAIL" for _, s, _ in rows) else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/harness/codeverse3d/gates.py b/harness/codeverse3d/gates.py
new file mode 100644
index 00000000..f06a562b
--- /dev/null
+++ b/harness/codeverse3d/gates.py
@@ -0,0 +1,777 @@
+"""Per-track gate assembly and render rig: what ``3dcode check`` runs and what ``3dcode judge-pack`` renders.
+
+Everything here is deterministic measurement on the built artifacts; no model is called.
+"""
+
+from __future__ import annotations
+
+import importlib
+import logging
+import shutil
+import time
+from collections.abc import Sequence
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field
+
+from codeverse3d.config import get_settings
+from codeverse3d.contracts.artifacts import (
+ BuildResult,
+ GateFinding,
+ GateReport,
+ Measurement,
+ RenderSet,
+ RenderView,
+ Severity,
+)
+from codeverse3d.contracts.common import Language, Track
+from codeverse3d.contracts.plan import ArticulatedPlan, GraphicsPlan, Plan, ScenePlan, StaticPlan
+from codeverse3d.contracts.spec import PROJECT_GATE_PREFIX, ProjectCheck, Spec
+from codeverse3d.conventions import (
+ BBOX_TOLERANCE_M,
+ MAX_TRIS_OBJECT,
+ OBJECT_CLAY_VIEWS,
+ OBJECT_VIEWS,
+ SCENE_TIMES,
+ to_pascal,
+ to_snake,
+)
+from codeverse3d.languages import get_runtime
+from codeverse3d.languages._gl_common import METRICS_NAME, SHEET_NAME, read_metrics
+from codeverse3d.spatial.contract import check_contract, check_fixed_parts, planned_joins
+from codeverse3d.spatial.frame_metrics import frame_gate_from_renders
+from codeverse3d.spatial.frame_motion import motion_text_for
+from codeverse3d.spatial.joints_sweep import SWEEP_GATE, sweep_gate
+from codeverse3d.spatial.measure import GlbLoadError, measure_glb
+from codeverse3d.spatial.render import RenderError, render_glb
+from codeverse3d.spatial.scene_placement import placement_gate_safe
+from codeverse3d.spatial.silhouette import compare_silhouette, measure_reference
+from codeverse3d.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+OBJECT_TRACKS = (Track.STATIC_OBJECT, Track.ARTICULATED_OBJECT)
+
+
+# ===================================================================== detail budget
+#: triangles a well-detailed single part is worth. Corpus: median tri/part ≈ 430, and the
+#: highest-scoring hard run (garden arch, 0.929) sits at 1936. Target the good end.
+TRIS_PER_UNIT_TARGET = 2_000
+TRIS_PER_UNIT_FLOOR = 350
+TRIS_PER_UNIT_MAX = 20_000
+
+BUILD_S_PER_UNIT = 3.0
+MIN_BUILD_S = 20
+BUDGET_GATE = "detail_budget"
+
+
+@dataclass(frozen=True)
+class DepthBudget:
+ """What THIS object is allowed to spend, sized from its own plan."""
+
+ n_units: int
+ min_tris: int
+ target_tris: int
+ max_tris: int
+ max_build_s: int
+
+
+def _clamp(v: float, lo: float, hi: float) -> int:
+ return int(max(lo, min(hi, v)))
+
+
+def depth_budget(plan: StaticPlan, build_timeout_s: int) -> DepthBudget:
+ """Triangle + build-time budget sized from the plan's part/instance count."""
+ n_units = plan.leaf_count
+ target = _clamp(TRIS_PER_UNIT_TARGET * n_units, 6_000, 200_000)
+ return DepthBudget(
+ n_units=n_units,
+ min_tris=_clamp(TRIS_PER_UNIT_FLOOR * n_units, 1_500, 40_000),
+ target_tris=target,
+ max_tris=_clamp(TRIS_PER_UNIT_MAX * n_units, 60_000, MAX_TRIS_OBJECT),
+ # the subprocess is killed at build_timeout_s, so never allow more than
+ # that minus the exporter's share, and never less than MIN_BUILD_S
+ max_build_s=int(_clamp(int(BUILD_S_PER_UNIT * n_units), MIN_BUILD_S, max(MIN_BUILD_S, build_timeout_s - 30))),
+ )
+
+
+def budget_gate(measurement: Measurement, build: BuildResult, budget: DepthBudget) -> GateReport:
+ """``detail_budget`` gate: is this object as dense as its own plan says it should be?"""
+ findings: list[GateFinding] = []
+ tris = int(measurement.tri_count or 0)
+ per_unit = tris / max(1, budget.n_units)
+ if tris > budget.max_tris:
+ findings.append(GateFinding(
+ gate=BUDGET_GATE, severity=Severity.ERROR, target="overall",
+ message=f"{tris:,} triangles exceeds this object's ceiling of {budget.max_tris:,} "
+ f"({budget.n_units} built objects × {TRIS_PER_UNIT_MAX:,})",
+ fix_hint=f"over this object's ceiling of {budget.max_tris:,}: reduce the segment / subdivision "
+ f"counts on the heaviest parts",
+ data={"kind": "over_tri_budget", "tris": tris, "max": budget.max_tris}))
+ elif tris < budget.min_tris:
+ findings.append(GateFinding(
+ gate=BUDGET_GATE, severity=Severity.WARN, target="overall",
+ message=f"{tris:,} triangles ({per_unit:.0f} per built object) is below this object's detail floor "
+ f"of {budget.min_tris:,} — it is a stack of primitives, not a modelled object",
+ fix_hint=f"{tris:,} triangles is under this object's floor of {budget.min_tris:,} (target "
+ f"{budget.target_tris:,}): add the detail the real object carries INSIDE the parts the "
+ f"plan names, not as new parts",
+ data={"kind": "under_tri_budget", "tris": tris, "floor": budget.min_tris,
+ "target": budget.target_tris, "per_unit": round(per_unit, 1)}))
+ ms = int(build.duration_ms or 0)
+ if ms > budget.max_build_s * 1000:
+ findings.append(GateFinding(
+ gate=BUDGET_GATE, severity=Severity.WARN, target="overall",
+ message=f"the build took {ms / 1000:.1f} s, over this object's {budget.max_build_s} s budget",
+ fix_hint="find the part with the most segments/subdivision/booleans and simplify it",
+ data={"kind": "slow_build", "ms": ms, "budget_s": budget.max_build_s}))
+ if not findings:
+ findings.append(GateFinding(
+ gate=BUDGET_GATE, severity=Severity.INFO, target="overall",
+ message=f"{tris:,} triangles ({per_unit:.0f} per built object) inside the "
+ f"{budget.min_tris:,}–{budget.max_tris:,} budget",
+ data={"kind": "tri_budget_ok", "tris": tris, "target": budget.target_tris}))
+ return GateReport.of(BUDGET_GATE, findings)
+
+
+# ===================================================================== project checks
+def _named(report: GateReport, check: ProjectCheck) -> GateReport:
+ """``report`` under ``project:<name>`` (a check returning several reports keeps them apart as
+ ``project:<name>.<its gate>``), its findings renamed with it, so caps see one namespace."""
+ own = report.gate or ""
+ if own.startswith(PROJECT_GATE_PREFIX):
+ gate = own
+ elif own in ("", check.name):
+ gate = PROJECT_GATE_PREFIX + check.name
+ else:
+ gate = f"{PROJECT_GATE_PREFIX}{check.name}.{own}"
+ findings = [f.model_copy(update={"gate": gate}) for f in report.findings]
+ return report.model_copy(update={"gate": gate, "findings": findings})
+
+
+def run_project_checks(spec: Spec, workspace: Path, glb: Path, measurement: Measurement | None,
+ round_index: int) -> list[GateReport]:
+ """Every ``Spec.checks`` entry (``package.module:function``) on this GLB, in the spec's order. A check that
+ raises costs nothing but a WARN saying so: a project's bug must not fail or cap the verdict."""
+ out: list[GateReport] = []
+ for check in spec.checks:
+ t0 = time.time()
+ try:
+ module, _, attr = check.entry.partition(":")
+ fn = getattr(importlib.import_module(module), attr)
+ got = fn(glb=glb, workspace=workspace, spec=spec, measurement=measurement, round_index=round_index,
+ args=dict(check.args))
+ reports = [got] if isinstance(got, GateReport) else list(got)
+ out += [_named(r, check) for r in reports]
+ except Exception as e: # noqa: BLE001 — a project's bug must not fail or cap the verdict
+ log.warning("project check %s failed: %s", check.entry, e)
+ gate = PROJECT_GATE_PREFIX + check.name
+ out.append(GateReport.of(gate, [GateFinding(
+ gate=gate, severity=Severity.WARN,
+ message=f"project check {check.entry} raised {type(e).__name__}: {str(e)[:300]}")],
+ duration_ms=int((time.time() - t0) * 1000)))
+ return out
+
+
+# ===================================================================== planned-motion gate
+MOTION_GATE = "motion_direction"
+#: its findings' ``data.kind``: the joint moves the way the plan says / the other way / not measured
+MOTION_OK, MOTION_WRONG, MOTION_SKIPPED = "as_planned", "wrong_direction", "skipped"
+
+#: phrase → direction key understood by ``spatial.joints_sweep.motion_direction_check``.
+#: Longer phrases first so "pulls out" wins over "out"; explicit axes first of all.
+_PHRASES: tuple[tuple[str, str], ...] = (
+ ("-y", "-y"), ("+y", "+y"), ("-z", "-z"), ("+z", "+z"), ("-x", "-x"), ("+x", "+x"),
+ ("towards the front", "front"), ("toward the front", "front"), ("to the front", "front"),
+ ("opens to the front", "front"), ("opens out", "front"), ("pulls out", "front"), ("slides out", "front"),
+ ("pull out", "front"), ("slide out", "front"), ("swings out", "front"), ("outward", "front"), ("forward", "front"),
+ ("towards the viewer", "front"), ("toward the viewer", "front"), ("frontward", "front"),
+ ("towards the back", "back"), ("toward the back", "back"), ("to the back", "back"), ("pushes in", "back"),
+ ("slides in", "back"), ("backward", "back"), ("rearward", "back"), ("inward", "back"),
+ ("upward", "up"), ("upwards", "up"), ("opens up", "up"), ("lifts", "up"), ("lift", "up"), ("raises", "up"),
+ ("raise", "up"), ("rises", "up"),
+ ("downward", "down"), ("downwards", "down"), ("lowers", "down"), ("drops", "down"),
+ ("folds down", "down"), ("opens down", "down"),
+ ("to the left", "left"), ("leftward", "left"), ("swings left", "left"),
+ ("to the right", "right"), ("rightward", "right"), ("swings right", "right"),
+ ("front", "front"), ("back", "back"), ("up", "up"), ("down", "down"), ("left", "left"), ("right", "right"),
+ ("out", "front"),
+)
+
+_SKIP_MARKERS = ("not ", "n't", "either", "both", "around", "rotates about", "spins")
+_DIR_GROUPS = {"front": "y", "back": "y", "-y": "y", "+y": "y", "up": "z", "down": "z", "+z": "z", "-z": "z",
+ "left": "x", "right": "x", "-x": "x", "+x": "x"}
+
+
+def _contains_word(padded: str, phrase: str) -> bool:
+ """Whole-word containment (phrase boundaries are spaces or punctuation)."""
+ i = padded.find(phrase)
+ while i >= 0:
+ before = padded[i - 1] if i > 0 else " "
+ after = padded[i + len(phrase)] if i + len(phrase) < len(padded) else " "
+ if not before.isalnum() and not after.isalnum():
+ return True
+ i = padded.find(phrase, i + 1)
+ return False
+
+
+def expected_direction(motion: str) -> str | None:
+ """Direction key for an obvious motion description, else ``None``."""
+ text = " ".join((motion or "").lower().replace("_", " ").split())
+ if not text or any(m in text for m in _SKIP_MARKERS):
+ return None
+ padded = f" {text} "
+ hits: list[str] = []
+ for phrase, key in _PHRASES:
+ if _contains_word(padded, phrase):
+ hits.append(key)
+ if key in ("-y", "+y", "-z", "+z", "-x", "+x"):
+ return key
+ if not hits:
+ return None
+ axes = {_DIR_GROUPS[h] for h in hits}
+ if len(axes) > 1:
+ # "opens up and out" — up/front conflict: the longest phrase decides only if one axis dominates
+ first_axis = _DIR_GROUPS[hits[0]]
+ if any(_DIR_GROUPS[h] != first_axis for h in hits[1:]):
+ return None
+ return hits[0]
+
+
+def axis_fix_hint(joint_name: str, axis: Sequence[float] | None, expected: str) -> str:
+ if axis is not None and len(axis) == 3:
+ neg = tuple(-float(a) for a in axis)
+ return (f"in src/robot.urdf set joint '{joint_name}' <axis xyz=\"{neg[0]:g} {neg[1]:g} {neg[2]:g}\"/> "
+ f"(negate the axis; keep lower/upper as they are, q=0 stays the rest pose) so positive motion goes {expected}")
+ return f"negate the <axis> of joint '{joint_name}' in src/robot.urdf (keep lower/upper as they are) so motion goes {expected}"
+
+
+def motion_checks(ws: Workspace, plan: Plan | None) -> GateReport | None:
+ """``motion_direction``: the plan's motion text ("pulls out to the front") vs the built URDF's real direction,
+ for every joint with an obvious direction; ``None`` when nothing is measurable."""
+ joints = list(getattr(plan, "joints", None) or [])
+ wanted = [(j, expected_direction(j.motion)) for j in joints]
+ wanted = [(j, d) for j, d in wanted if d is not None]
+ if not wanted:
+ return None
+ from codeverse3d.spatial.joints_model import UrdfError, load_urdf
+ from codeverse3d.spatial.joints_sweep import find_urdf, motion_direction_check
+
+ urdf = find_urdf(ws)
+ if urdf is None:
+ return None
+ t0 = time.time()
+ findings: list[GateFinding] = []
+ try:
+ robot = load_urdf(urdf, ws.artifacts / "meshes")
+ except UrdfError as e:
+ return GateReport.of(MOTION_GATE, [GateFinding(
+ gate=MOTION_GATE, severity=Severity.WARN, target="robot.urdf", message=f"motion checks skipped: {e}",
+ data={"kind": MOTION_SKIPPED})])
+ urdf_names = {to_snake(n): n for n in getattr(robot, "joints", {})}
+ for j, expected in wanted:
+ name = urdf_names.get(to_snake(j.name), j.name) # URDF joint named like the plan joint (any casing)
+ try:
+ chk = motion_direction_check(robot, name, expected)
+ except UrdfError as e:
+ findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.WARN, target=j.name,
+ message=f"motion check skipped: {e}", data={"kind": MOTION_SKIPPED, "expected": expected}))
+ continue
+ data = {"kind": MOTION_OK if chk.ok else MOTION_WRONG, "expected": expected, "observed_dir": list(chk.observed_dir),
+ "motion": j.motion, "cos": chk.cos, "suggested_axis": list(chk.suggested_axis) if chk.suggested_axis else None}
+ if chk.ok:
+ findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.INFO, target=j.name, message=chk.message, data=data))
+ else:
+ # anti-parallel: the sign is wrong, negate; orthogonal: the geometry admits an exact axis, state it.
+ if chk.cos >= -0.5 and chk.suggested_axis is not None:
+ sx, sy, sz = chk.suggested_axis
+ hint = (f"in src/robot.urdf set joint '{j.name}' <axis xyz=\"{sx:g} {sy:g} {sz:g}\"/> "
+ f"— computed from the pivot so positive motion goes {expected}")
+ else:
+ hint = axis_fix_hint(j.name, getattr(j, "axis", None), expected)
+ findings.append(GateFinding(
+ gate=MOTION_GATE, severity=Severity.ERROR, target=j.name,
+ message=f"{chk.message}. Plan says: \"{j.motion}\"",
+ fix_hint=hint, data=data))
+ return GateReport.of(MOTION_GATE, findings, duration_ms=int((time.time() - t0) * 1000))
+
+
+# ===================================================================== reference silhouette
+SILHOUETTE_GATE = "reference_silhouette"
+IOU_REFINE_THRESHOLD = 0.6
+
+
+def silhouette_gate(spec: Spec, renders: RenderSet) -> GateReport | None:
+ """Reference-image projects: outline IoU vs the target image (a WARN below :data:`IOU_REFINE_THRESHOLD`)."""
+ if not spec.references:
+ return None
+ try:
+ m = measure_reference(renders.views, spec, compare=compare_silhouette)
+ except Exception as e: # noqa: BLE001 — advisory measurement; never fails the pack
+ log.warning("compare_silhouette failed: %s", e)
+ return GateReport.of(SILHOUETTE_GATE, [GateFinding(
+ gate=SILHOUETTE_GATE, severity=Severity.INFO, target="overall", message=f"silhouette comparison unavailable: {e}")])
+ if m is None:
+ return None
+ low = m.scorable and m.iou < IOU_REFINE_THRESHOLD
+ msg = (f"outline IoU vs reference = {m.iou:.3f} (best-matching view: {m.view})"
+ + ("" if m.reliable else " (unreliable mask)")
+ + (" (the reference's proportions contradict the brief: not a shape verdict)" if m.conflict else "")
+ + (f" — below {IOU_REFINE_THRESHOLD:.1f}" if low else ""))
+ finding = GateFinding(gate=SILHOUETTE_GATE, severity=Severity.WARN if low else Severity.INFO, target="overall",
+ message=msg, data=m.model_dump(exclude={"per_view"}),
+ fix_hint=("match the reference outline: compare proportions (aspect ratio), overall extents and the "
+ "silhouette of each major part against the reference image" if low else ""))
+ return GateReport.of(SILHOUETTE_GATE, [finding])
+
+
+# ===================================================================== scene asset modules
+ASSET_GATE = "scene_assets"
+#: max triangles for ONE asset instance (the scene contract's budget)
+ASSET_MAX_TRIS = 15_000
+#: probe zone of a bpy asset check: one collection instance at the origin, so the census GLB carries exactly the asset's geometry
+BPY_CHECK_ZONE = "check"
+
+
+class AssetCheck(BaseModel):
+ """Result of importing an asset module and calling its builder."""
+
+ ok: bool = False
+ ran: bool = Field(default=False, description="False = the checker itself could not run (node missing)")
+ fatal: bool = Field(default=False, description="the module does not import / build at all — zones must not use it")
+ errors: list[str] = Field(default_factory=list)
+ warnings: list[str] = Field(default_factory=list)
+ size_m: tuple[float, float, float] | None = None
+ min_y: float | None = None
+ tris: int = Field(default=0, description="triangles the asset built itself (the per-asset budget)")
+ lib_tris: int = Field(default=0, description="triangles the effect-library factories it composes built")
+ meshes: int = 0
+ materials: int = 0
+
+
+def _soft_findings(chk: AssetCheck, expected: tuple[float, float, float] | None, *, max_tris: int = ASSET_MAX_TRIS) -> None:
+ """Findings that make the asset WRONG but not broken."""
+ if not chk.ok:
+ return
+ if chk.min_y is not None and chk.min_y < -0.02:
+ chk.errors.append(f"the group sinks {abs(chk.min_y):.2f} m below y=0 — its lowest point must sit at y=0")
+ if chk.tris > max_tris:
+ chk.errors.append(f"{chk.tris} triangles exceeds the {max_tris} budget per asset — lower the segment counts")
+ if chk.tris + chk.lib_tris > MAX_TRIS_OBJECT:
+ chk.errors.append(f"the effect-library factories it calls build {chk.lib_tris} triangles, past the {MAX_TRIS_OBJECT} "
+ "ceiling for one object — pass their lighter options (fewer leaves, fewer leaf segments) or call fewer")
+ if chk.meshes == 1 and chk.materials <= 1 and chk.tris + chk.lib_tris < 200:
+ chk.errors.append("the asset is still a single low-poly box (one mesh, one material): build it from several "
+ "parts with distinct materials so it reads as the described object")
+ if expected and chk.size_m:
+ for axis, got, want in zip("whd", chk.size_m, expected, strict=False):
+ if want > 0.05 and (got > want * 2.5 or got < want * 0.4):
+ chk.errors.append(f"measured {axis}={got:.2f} m but the plan says {want:.2f} m — rescale to the planned size (±5 %)")
+ break
+ chk.ok = not chk.errors
+
+
+def check_threejs_asset(ws: Workspace, rel: str, pascal: str, *, timeout_s: float = 60.0,
+ expected_size_m: tuple[float, float, float] | None = None) -> AssetCheck:
+ """Import ``rel`` in node, call ``build<Pascal>(THREE, {})`` and inspect the group."""
+ path = ws.root / rel
+ if not path.is_file():
+ return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"{rel} was not written"])
+ try:
+ from codeverse3d.spatial.node import run_node, runtime_js_dir
+
+ lifecycle = ws.src / "lib" / "lifecycle.js"
+ args = [path.resolve().as_uri(), f"build{pascal}"] + ([lifecycle.resolve().as_uri()] if lifecycle.is_file() else [])
+ res = run_node(runtime_js_dir() / "lib" / "asset_check.mjs", args, cwd=ws.root,
+ three_hook=True, timeout_s=timeout_s, check=False)
+ data = res.last_json
+ if data is None:
+ tail = (res.stderr or res.stdout or "").strip().splitlines()[-3:]
+ return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"the module failed to load: {' / '.join(tail)[:300]}"])
+ chk = AssetCheck(ok=bool(data.get("ok")), ran=True, errors=list(data.get("errors") or []),
+ warnings=list(data.get("warnings") or []),
+ size_m=tuple(data["size_m"]) if data.get("size_m") else None, # type: ignore[arg-type]
+ min_y=data.get("min_y"), tris=int(data.get("tris") or 0), lib_tris=int(data.get("lib_tris") or 0),
+ meshes=int(data.get("meshes") or 0), materials=int(data.get("materials") or 0))
+ except Exception as e: # noqa: BLE001 — the checker is an optimisation, never a blocker
+ log.warning("asset check could not run for %s: %s", rel, e)
+ return AssetCheck(ok=True, ran=False, warnings=[f"checker unavailable: {type(e).__name__}"])
+ chk.fatal = not chk.ok # everything the JS side reports is a hard failure to import/build
+ _soft_findings(chk, expected_size_m) # …the rest is wrong-but-usable
+ return chk
+
+
+def _bpy_check_workspace(ws: Workspace, rel: str, snake: str) -> Workspace:
+ from codeverse3d.contracts.common import ENTRY_FILE
+ from codeverse3d.languages.scene_blender import render_scene_py
+
+ scratch = Workspace(ws.artifacts / "asset_check" / snake)
+ if scratch.root.exists():
+ shutil.rmtree(scratch.root)
+ for sub in ("assets", "zones"):
+ (scratch.src / sub).mkdir(parents=True, exist_ok=True)
+ scratch.artifacts.mkdir(parents=True, exist_ok=True)
+ (scratch.root / ENTRY_FILE[Language.SCENE_BLENDER]).write_text(render_scene_py([], [snake], [], []))
+ shutil.copyfile(ws.root / rel, scratch.src / "assets" / f"{snake}.py")
+ (scratch.src / "zones" / f"{BPY_CHECK_ZONE}.py").write_text(
+ f'"""The probe zone: one instance of {snake}, so the census GLB measures it."""\n'
+ "import bpy\n\n\n"
+ "def build(ctx):\n"
+ f" ob = bpy.data.objects.new({to_pascal(snake)!r}, None)\n"
+ ' ob.instance_type = "COLLECTION"\n'
+ f" ob.instance_collection = ctx.assets[{snake!r}]\n"
+ " ctx.collection.objects.link(ob)\n"
+ " return ctx.collection\n")
+ return scratch
+
+
+def check_bpy_asset(ws: Workspace, runtime: Any, rel: str, snake: str, *,
+ expected_size_m: tuple[float, float, float] | None = None, timeout_s: float | None = None) -> AssetCheck:
+ """Build ``src/assets/<snake>.py`` alone in Blender and inspect what it made."""
+ path = ws.root / rel
+ if not path.is_file():
+ return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"{rel} was not written"])
+ try:
+ scratch = _bpy_check_workspace(ws, rel, snake)
+ run = runtime.run_wrapper(scratch, scratch.artifacts, zones={BPY_CHECK_ZONE: to_pascal(BPY_CHECK_ZONE)}, blend=False,
+ timeout_s=float(timeout_s or get_settings().limits.build_timeout_s))
+ except Exception as e: # noqa: BLE001 — the checker is an optimisation, never a blocker
+ log.warning("bpy asset check could not run for %s: %s", rel, e)
+ return AssetCheck(ok=True, ran=False, warnings=[f"checker unavailable: {type(e).__name__}"])
+ report = run.report or {}
+ for e in report.get("errors") or []:
+ if e.get("stage") == "asset" and e.get("name") == snake:
+ where = f"{e.get('error_file') or rel}:{e.get('error_line')}" if e.get("error_line") else str(e.get("error_file") or rel)
+ return AssetCheck(ok=False, ran=True, fatal=True,
+ errors=[f"{where}: {e.get('error_type')}: {str(e.get('error_message'))[:300]}"])
+ if run.result.harness_failure:
+ log.warning("bpy asset check could not finish for %s: %s", rel, run.result.error_type)
+ return AssetCheck(ok=True, ran=False, warnings=[f"checker unavailable: {run.result.error_type}"])
+ if report.get("nonfinite"):
+ return AssetCheck(ok=False, ran=True, fatal=True,
+ errors=[f"{report.get('error_file') or rel}: {report.get('error_type')}: "
+ f"{str(report.get('error_message'))[:600]}"])
+ if not run.result.ok:
+ return AssetCheck(ok=False, ran=True, fatal=True,
+ errors=[f"the module's build did not finish: {run.result.error_type}: {run.result.error_message}"[:300]])
+ if any(e.get("stage") == "zone" for e in report.get("errors") or []):
+ return AssetCheck(ok=False, ran=True, fatal=True,
+ errors=[f"build_{snake}(ctx) returned no Collection the scene could instance (ctx.assets[{snake!r}] is missing)"])
+ chk = AssetCheck(ok=True, ran=True, tris=int((run.facts or {}).get("unique_tris") or 0))
+ try:
+ m = measure_glb(scratch.artifacts / "census.glb")
+ except Exception as e: # noqa: BLE001 — a module that built but cannot be measured is still usable
+ chk.warnings.append(f"measure unavailable: {type(e).__name__}")
+ return chk
+ chk.size_m = (round(m.extents[0], 3), round(m.extents[1], 3), round(m.extents[2], 3))
+ chk.min_y, chk.meshes, chk.materials = round(m.bbox_min[1], 3), m.n_meshes, m.materials
+ chk.tris = chk.tris or m.tri_count
+ _soft_findings(chk, expected_size_m)
+ return chk
+
+
+def asset_gate(ws: Workspace, runtime: Any, plan: ScenePlan, language: Language) -> GateReport | None:
+ """``scene_assets``: every planned MODULE asset (``threejs`` / ``bpy``) imported and built alone — a fatal module
+ is an ERROR, a wrong-but-usable one (sunk, over budget, a single box, off the planned size) a WARN."""
+ modules = [a for a in plan.assets if a.kind in ("threejs", "bpy")]
+ if not modules:
+ return None
+ t0 = time.time()
+ findings: list[GateFinding] = []
+ for a in modules:
+ rel = runtime.asset_file(a)
+ if a.kind == "threejs":
+ chk = check_threejs_asset(ws, rel, to_pascal(a.name), expected_size_m=a.approx_size_m)
+ else:
+ chk = check_bpy_asset(ws, runtime, rel, to_snake(a.name), expected_size_m=a.approx_size_m)
+ data = {"kind": "asset_fatal" if chk.fatal else "asset_soft" if chk.errors else "asset_ok", "file": rel,
+ "tris": chk.tris, "size_m": list(chk.size_m) if chk.size_m else None, "ran": chk.ran}
+ if not chk.ran:
+ findings.append(GateFinding(gate=ASSET_GATE, severity=Severity.INFO, target=a.name,
+ message=f"{rel}: not checked ({'; '.join(chk.warnings)[:200]})", data=data))
+ elif chk.fatal:
+ findings.append(GateFinding(gate=ASSET_GATE, severity=Severity.ERROR, target=a.name,
+ message=f"{rel} does not build: " + "; ".join(chk.errors)[:400],
+ fix_hint=f"fix {rel} so its builder imports and returns the asset; zones placing it get nothing until then",
+ data=data))
+ elif chk.errors:
+ findings.append(GateFinding(gate=ASSET_GATE, severity=Severity.WARN, target=a.name,
+ message=f"{rel}: " + "; ".join(chk.errors)[:400],
+ fix_hint=f"rewrite {rel} so the deterministic asset check passes", data=data))
+ else:
+ size = f"{chk.size_m[0]:.2f}×{chk.size_m[1]:.2f}×{chk.size_m[2]:.2f} m" if chk.size_m else "size unmeasured"
+ findings.append(GateFinding(gate=ASSET_GATE, severity=Severity.INFO, target=a.name,
+ message=f"{rel}: builds, {chk.tris} tris, {size}", data=data))
+ return GateReport.of(ASSET_GATE, findings, duration_ms=int((time.time() - t0) * 1000))
+
+
+# ===================================================================== the check
+class CheckResult(BaseModel):
+ """What ``3dcode check`` found: the build, the measurement and every gate, written to ``artifacts/gates.json``."""
+
+ ok: bool
+ track: str
+ language: str
+ round_index: int = 0
+ src_hash: str = ""
+ build: BuildResult
+ measurement: Measurement | None = None
+ gates: list[GateReport] = Field(default_factory=list)
+
+ @property
+ def errors(self) -> list[tuple[str, GateFinding]]:
+ return [(g.gate, f) for g in self.gates for f in g.errors]
+
+
+def lint_and_build(ws: Workspace, language: Language, *, timeout_s: int | None = None) -> tuple[GateReport, BuildResult]:
+ """Lint, then build when the lint has no ERROR (a lint error is recorded as the build status)."""
+ rt = get_runtime(language)
+ lint: GateReport = rt.lint(ws)
+ if lint.errors:
+ br = BuildResult(ok=False, language=language.value, error_type="LintError",
+ error_message="\n".join(f.as_line(with_target=True) for f in lint.errors)[:4000])
+ ws.write_json(ws.artifacts / "build.json", br)
+ return lint, br
+ return lint, rt.build(ws, timeout_s=timeout_s or get_settings().limits.build_timeout_s)
+
+
+def run_check(ws: Workspace, spec: Spec, plan: Plan | None, *, round_index: int = 0) -> CheckResult:
+ """Lint → build → measure → every gate of the track; the result is also written to ``artifacts/gates.json``."""
+ lint, build = lint_and_build(ws, spec.language)
+ gates: list[GateReport] = [lint]
+ measurement: Measurement | None = None
+ if build.ok:
+ if spec.track in OBJECT_TRACKS:
+ measurement, more = object_gates(ws, spec, plan, build, round_index=round_index)
+ gates += more
+ elif spec.track is Track.SCENE:
+ gates += scene_gates(ws, spec, plan, build)
+ gates += build.gates
+ result = CheckResult(ok=build.ok and not any(g.errors for g in gates), track=spec.track.value,
+ language=spec.language.value, round_index=round_index, src_hash=ws.src_hash(),
+ build=build, measurement=measurement, gates=gates)
+ ws.write_json(ws.gates_path, result)
+ d = ws.gates_dir(round_index)
+ d.mkdir(parents=True, exist_ok=True)
+ for g in gates:
+ ws.write_json(d / f"{g.gate.replace(':', '_').replace('/', '_')}.json", g)
+ return result
+
+
+def object_gates(ws: Workspace, spec: Spec, plan: Plan | None, build: BuildResult, *,
+ round_index: int) -> tuple[Measurement | None, list[GateReport]]:
+ """Measure the GLB, then connectivity, contract, detail budget, fixed parts, project checks; articulated adds
+ the joint sweep and the motion-direction gate."""
+ settings = get_settings()
+ out: list[GateReport] = []
+ glb = Path(build.glb_path) if build.glb_path else None
+ if glb is None or not glb.is_file():
+ return None, [GateReport.of("measure", [GateFinding(
+ gate="measure", severity=Severity.ERROR, target="artifacts/object.glb",
+ message="the build reported success but wrote no object.glb", fix_hint="build again; the exporter wrote nothing")])]
+ try:
+ measurement = measure_glb(glb)
+ except GlbLoadError as e:
+ return None, [GateReport.of("measure", [GateFinding(
+ gate="measure", severity=Severity.ERROR, target="artifacts/object.glb", message=f"GLB unreadable: {e}")])]
+ ws.write_json(ws.artifacts / "measurement.json", measurement)
+ from codeverse3d.spatial.connectivity import check_connectivity
+
+ object_plan = plan if isinstance(plan, StaticPlan) else None
+ out.append(check_connectivity(glb, language=spec.language.value,
+ planned_edges=tuple(planned_joins(object_plan, measurement)) if object_plan else ()))
+ if object_plan is not None:
+ out.append(check_contract(measurement, object_plan, language=spec.language.value, tol_m=BBOX_TOLERANCE_M))
+ out.append(budget_gate(measurement, build, depth_budget(object_plan, settings.limits.build_timeout_s)))
+ if spec.fixed_parts:
+ out.append(check_fixed_parts(measurement, spec.fixed_parts))
+ if spec.checks:
+ out += run_project_checks(spec, ws.root, glb, measurement, round_index)
+ if spec.track is Track.ARTICULATED_OBJECT:
+ sweep, _robot = sweep_gate(ws)
+ out.append(sweep)
+ try:
+ motion = motion_checks(ws, plan)
+ except Exception as e: # noqa: BLE001 — advisory gate; the sweep gate is the hard one
+ log.warning("motion direction checks failed: %s", e)
+ motion = None
+ if motion is not None:
+ out.append(motion)
+ return measurement, out
+
+
+def scene_gates(ws: Workspace, spec: Spec, plan: Plan | None, build: BuildResult) -> list[GateReport]:
+ """Placement gate (+ the plan checks) on the build's census, then the asset-module checks."""
+ out: list[GateReport] = []
+ placement = placement_gate_safe(build.census if isinstance(build.census, dict) else None, plan=plan)
+ if placement is not None:
+ out.append(placement)
+ if isinstance(plan, ScenePlan):
+ assets = asset_gate(ws, get_runtime(spec.language), plan, spec.language)
+ if assets is not None:
+ out.append(assets)
+ return out
+
+
+# ===================================================================== the judged renders
+#: the 4 clay views judged for holes/intersections; their own cameras, not a name filter over OBJECT_VIEWS
+GEOMETRY_VIEWS = OBJECT_CLAY_VIEWS
+
+
+@dataclass
+class JudgeRenders:
+ """What the judge sees of one round: the judged views, the clay geometry views, the gates the renders added
+ and the track's own context lines."""
+
+ renders: RenderSet
+ geometry: RenderSet | None = None
+ post_gates: list[GateReport] | None = None
+ extra_context: str = ""
+
+
+def render_for_judge(ws: Workspace, spec: Spec, plan: Plan | None, check: CheckResult, *, round_index: int) -> JudgeRenders:
+ """The track's judged views into ``artifacts/renders/rNN``, plus its post-render gates and context."""
+ if spec.track in OBJECT_TRACKS:
+ return _object_renders(ws, spec, plan, check, round_index=round_index)
+ if spec.track is Track.SCENE:
+ return _scene_renders(ws, spec, plan, check, round_index=round_index)
+ return _graphics_renders(ws, check, round_index=round_index)
+
+
+def _object_renders(ws: Workspace, spec: Spec, plan: Plan | None, check: CheckResult, *, round_index: int) -> JudgeRenders:
+ r = get_settings().render
+ glb = Path(check.build.glb_path or "")
+ out_dir = ws.renders_dir(round_index)
+ rs = render_glb(glb, out_dir, views=list(OBJECT_VIEWS), width=r.width, height=r.height, sheet=True)
+ geometry: RenderSet | None = None
+ try:
+ geometry = render_glb(glb, out_dir / "clay", views=list(GEOMETRY_VIEWS), mode="clay", sheet=False)
+ except RenderError as e: # optional judge context, never fatal
+ log.warning("clay geometry render failed: %s", e)
+ post: list[GateReport] = []
+ sil = silhouette_gate(spec, rs)
+ if sil is not None:
+ post.append(sil)
+ context = ""
+ if spec.track is Track.ARTICULATED_OBJECT:
+ rs, context = _pose_renders(ws, rs, check, out_dir)
+ return JudgeRenders(renders=rs, geometry=geometry, post_gates=post, extra_context=context)
+
+
+def _pose_renders(ws: Workspace, rs: RenderSet, check: CheckResult, out_dir: Path) -> tuple[RenderSet, str]:
+ """Pose sheet + pose views appended to the object views, and the articulation context lines."""
+ from codeverse3d.spatial.joints_export import ARTICULATION_SHEET_NAME, render_poses
+ from codeverse3d.spatial.joints_model import UrdfError, load_urdf
+ from codeverse3d.spatial.joints_sweep import find_urdf
+
+ views: list[RenderView] = []
+ urdf = find_urdf(ws)
+ if urdf is not None:
+ poses_dir = out_dir / "poses"
+ try:
+ robot = load_urdf(urdf, ws.artifacts / "meshes")
+ for label, prs in render_poses(robot, poses_dir):
+ if prs.views:
+ v = prs.views[0]
+ views.append(RenderView(name=f"pose_{label}", path=v.path, mode=v.mode, width=v.width, height=v.height))
+ sheet = poses_dir / ARTICULATION_SHEET_NAME
+ if sheet.is_file():
+ views.insert(0, RenderView(name="articulation_sheet", path=str(sheet), mode="shaded"))
+ except (UrdfError, RenderError) as e:
+ log.warning("pose renders failed; the judge sees no articulation sheet: %s", e)
+ rs = rs.model_copy(update={"views": list(rs.views) + views})
+ sweep = next((g for g in check.gates if g.gate == SWEEP_GATE), None)
+ motion = next((g for g in check.gates if g.gate == MOTION_GATE), None)
+ lines = ["Articulation sheet: the pose_* views show the object at rest, each joint at its lower and upper limit."]
+ if sweep is not None:
+ errs = [f"- {f.target or 'joint'}: {f.message}" for f in sweep.errors]
+ lines.append(f"Joint sweep: {'no penetrations' if not errs else str(len(errs)) + ' problems'}")
+ lines.extend(errs[:10])
+ if motion is not None:
+ wrong = [f"- {f.target}: {f.message}" for f in motion.errors]
+ lines.append("Motion direction (measured FK check): " + ("all planned directions realised" if not wrong else f"{len(wrong)} WRONG"))
+ lines.extend(wrong[:6])
+ return rs, "\n".join(lines)
+
+
+def _scene_renders(ws: Workspace, spec: Spec, plan: Plan | None, check: CheckResult, *, round_index: int) -> JudgeRenders:
+ r = get_settings().render
+ runtime = get_runtime(spec.language)
+ cameras = list(plan.cameras) if isinstance(plan, ScenePlan) else None
+ out_dir = ws.renders_dir(round_index)
+ rs = runtime.render_scene(ws, out_dir, cameras=cameras, orbit=True, times=SCENE_TIMES, # type: ignore[attr-defined]
+ width=r.scene_width, height=r.scene_height, sheet=True)
+ post: list[GateReport] = []
+ try:
+ post.append(frame_gate_from_renders(rs)) # scene_frames: exposure / coverage / motion from metrics.json
+ except Exception as e: # noqa: BLE001 — advisory instrumentation
+ log.warning("scene frame gate failed: %s", e)
+ judged = rs if not any(v.judge is not None for v in rs.views) else rs.model_copy(update={"views": [v for v in rs.views if v.judge]})
+ lines = [t for t in (motion_text_for(out_dir),) if t]
+ if isinstance(plan, ScenePlan):
+ lines.append(f"Environment plan: {plan.environment}"[:1200])
+ lines.append("Animation plan: " + "; ".join(plan.animation))
+ lines.append("Cameras: " + "; ".join(f"{c.name} ({c.purpose})" for c in plan.cameras))
+ return JudgeRenders(renders=judged, post_gates=post, extra_context="\n".join(lines))
+
+
+def frames_render_set(ws: Workspace, build: BuildResult, round_index: int) -> RenderSet:
+ """Copy the judged frames + sheet into renders/rNN and describe them as a RenderSet (views ``t=<s>s``)."""
+ out = ws.renders_dir(round_index)
+ out.mkdir(parents=True, exist_ok=True)
+ frames_dir = Path(build.extra_paths.get("frames", ws.artifacts / "frames"))
+ metrics = read_metrics(ws)
+ if metrics is not None:
+ shutil.copy2(ws.artifacts / METRICS_NAME, out / METRICS_NAME)
+ stats = metrics[0] if metrics else None
+ views: list[RenderView] = []
+ for f in (stats.frames if stats else []):
+ src = Path(f.path)
+ if not src.is_file():
+ continue
+ dst = out / f"frame_t{f.time:05.2f}.png"
+ shutil.copy2(src, dst)
+ views.append(RenderView(name=f"t={f.time:g}s", path=str(dst), time_s=f.time))
+ if not views and frames_dir.is_dir(): # metrics missing: fall back to the raw frame files
+ for p in sorted(frames_dir.glob("f*_t*.png")):
+ dst = out / p.name
+ shutil.copy2(p, dst)
+ views.append(RenderView(name=p.stem.split("_t", 1)[-1] + "s", path=str(dst)))
+ sheet_src = Path(build.extra_paths.get("sheet", ws.artifacts / SHEET_NAME))
+ sheet = None
+ if sheet_src.is_file():
+ sheet = out / "sheet.png"
+ shutil.copy2(sheet_src, sheet)
+ renderer = str(build.census.get("renderer", "")) if isinstance(build.census, dict) else ""
+ return RenderSet(views=views, contact_sheet=str(sheet) if sheet else None, renderer=renderer or "moderngl",
+ duration_ms=build.duration_ms, out_dir=str(out))
+
+
+def frame_stats_text(ws: Workspace) -> str:
+ """The frame metrics as judge text."""
+ m = read_metrics(ws)
+ if m is None:
+ return "(no frame metrics)"
+ stats, gate = m
+ lines = stats.summary_lines()
+ for f in gate.findings:
+ lines.append(f"- GATE gl_frames {f.as_line(with_severity=True, with_hint=f.severity is not Severity.INFO)}")
+ return "\n".join(lines)
+
+
+def _graphics_renders(ws: Workspace, check: CheckResult, *, round_index: int) -> JudgeRenders:
+ rs = frames_render_set(ws, check.build, round_index)
+ renderer = check.build.census.get("renderer", "") if isinstance(check.build.census, dict) else ""
+ return JudgeRenders(renders=rs, post_gates=[],
+ extra_context=f"FRAME METRICS (measured, renderer {renderer or 'moderngl'}):\n{frame_stats_text(ws)}")
+
+
+#: the plan a track expects in ``plan.json``
+PLAN_MODELS: dict[Track, type[BaseModel]] = {
+ Track.STATIC_OBJECT: StaticPlan,
+ Track.ARTICULATED_OBJECT: ArticulatedPlan,
+ Track.SCENE: ScenePlan,
+ Track.GRAPHICS: GraphicsPlan,
+}
diff --git a/harness/codeverse3d/judges/base.py b/harness/codeverse3d/judges/base.py
deleted file mode 100644
index 3a882384..00000000
--- a/harness/codeverse3d/judges/base.py
+++ /dev/null
@@ -1,105 +0,0 @@
-"""``JudgeInput`` and the one place a round becomes one (``round_input``), plus the pure replay helpers."""
-
-from __future__ import annotations
-
-from collections.abc import Sequence
-
-from pydantic import BaseModel, Field
-
-from codeverse3d.contracts.artifacts import GateReport, Judgment, Measurement, RenderSet
-from codeverse3d.contracts.common import TRACK_INFO, Track
-from codeverse3d.contracts.plan import (
- AcceptanceItem,
- ArticulatedPlan,
- GraphicsPlan,
- Plan,
- ScenePlan,
- StaticPlan,
-)
-from codeverse3d.contracts.run import RoundRecord
-from codeverse3d.contracts.spec import Spec
-from codeverse3d.conventions import to_authoring_frame
-from codeverse3d.workspace import Workspace
-
-#: tracks whose rounds have one canonical GLB the judge slice channel may cut
-SLICE_TRACKS = ("static_object", "articulated_object")
-#: rubric for a static object judged against reference images (adds the silhouette criterion)
-REFERENCE_RUBRIC = "reference"
-
-
-def run_rubric(spec: Spec, default: str = "") -> str:
- """The rubric a run of ``spec`` is judged on: :data:`REFERENCE_RUBRIC` for a static object with
- references, else ``default`` or the track's own."""
- if spec.references and spec.track is Track.STATIC_OBJECT:
- return REFERENCE_RUBRIC
- return default or TRACK_INFO[spec.track].rubric
-
-
-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 = ""
- geometry_views: RenderSet | None = Field(
- default=None, description="clay/normals renders for the geometry-only montage (holes, intersections)"
- )
- glb_path: str | None = Field(
- default=None,
- description="the round's canonical GLB (object tracks fill it; `3dcodeverse judge` fills it from the stored "
- "build) — the D48 slice channel cuts it on gate-ERROR rounds; None disables the channel",
- )
-
-
-def plan_summary(plan: Plan | None, language: str) -> str:
- """The plan digest the judge reads. An object's size is written W×H×D in the GLB frame (Y-up),
- so a Z-up plan's (W, D, H) is permuted first."""
- if isinstance(plan, GraphicsPlan):
- passes = ", ".join(f"{p.name} ({p.kind})" for p in plan.passes)
- return (f"{plan.title}: {plan.summary} Style: {plan.style}. Passes: {passes}. Key visuals: {'; '.join(plan.key_visuals)}. "
- f"Motion: {plan.motion or '(none planned)'}. {plan.resolution[0]}x{plan.resolution[1]}, loop {plan.duration_s:g}s.")
- if isinstance(plan, ScenePlan):
- return (f"{plan.title}: {plan.summary} Setting: {plan.setting}. Zones: {', '.join(z.name for z in plan.zones)}. "
- f"Assets: {', '.join(a.name for a in plan.assets)}. Cameras: {', '.join(c.name for c in plan.cameras)}.")
- if not isinstance(plan, StaticPlan):
- return ""
- parts = ", ".join(f"{p.name}×{p.instances}" if p.instances > 1 else p.name for p in plan.parts)
- e = to_authoring_frame(plan.overall_bbox.extents, language, extents=True)
- text = f"{plan.object_name}: {plan.summary} Overall {e[0]:.2f}×{e[1]:.2f}×{e[2]:.2f} m (W×H×D). Parts: {parts}."
- if isinstance(plan, ArticulatedPlan):
- joints = "; ".join(f"{j.name} ({j.type} {j.parent}→{j.child}, [{j.lower:.2f},{j.upper:.2f}])" for j in plan.joints)
- text += f" Root link {plan.root_link}. Joints: {joints}."
- return text
-
-
-def round_input(spec: Spec, plan: Plan | None, rnd: RoundRecord, *, renders: RenderSet, gates: Sequence[GateReport],
- previous: Judgment | None, extra_context: str, geometry_views: RenderSet | None,
- glb_path: str | None) -> JudgeInput:
- """The judge payload of one round, built from the round in hand or replayed from disk."""
- return JudgeInput(
- spec=spec, renders=renders, measurement=rnd.measurement, gates=list(gates),
- acceptance=list(getattr(plan, "acceptance", None) or []), plan_summary=plan_summary(plan, spec.language),
- round_index=rnd.index, previous=previous, extra_context=extra_context, geometry_views=geometry_views,
- glb_path=glb_path if spec.track.value in SLICE_TRACKS else None,
- )
-
-
-def resolve_paths(ws: Workspace, rs: RenderSet | None) -> RenderSet | None:
- """Render paths out of a round record, resolved against THIS workspace."""
- if rs is None:
- return None
- fixed = [v.model_copy(update={"path": str(ws.rebase(v.path))}) for v in rs.views]
- sheet = str(ws.rebase(rs.contact_sheet)) if rs.contact_sheet else rs.contact_sheet
- out_dir = str(ws.rebase(rs.out_dir)) if rs.out_dir else rs.out_dir
- return rs.model_copy(update={"views": fixed, "contact_sheet": sheet, "out_dir": out_dir})
-
-
-def judged_subset(rs: RenderSet | None) -> RenderSet | None:
- """The views the in-run judge saw (per-view ``judge`` flags); rounds without flags keep every view."""
- if rs is None or not any(v.judge is not None for v in rs.views):
- return rs
- return rs.model_copy(update={"views": [v for v in rs.views if v.judge]})
diff --git a/harness/codeverse3d/judges/prompt_builder.py b/harness/codeverse3d/judges/prompt_builder.py
index 2d207ed2..b4468617 100644
--- a/harness/codeverse3d/judges/prompt_builder.py
+++ b/harness/codeverse3d/judges/prompt_builder.py
@@ -1,7 +1,8 @@
-"""What the judge sees: image prep, montage planning and message assembly.
+"""What the judge sees: image prep, montage planning and the brief.
``prepare_image`` downscales and labels every image; ``plan_montages`` / ``render_montage`` pack ranked views
-into ≤2×2 sheets; ``build_judge_messages`` assembles the request; ``judge_prompt_hash`` stamps a verdict.
+into ≤2×2 sheets; ``build_brief`` assembles the judge's text (the role, the rubric as a checklist, the measured
+facts, the view rig, the exact JSON to return) for ``judge/rNN/brief.md``.
"""
from __future__ import annotations
@@ -9,11 +10,10 @@ from __future__ import annotations
import hashlib
import json
import math
-import random
from collections.abc import Sequence
-from dataclasses import dataclass, replace
+from dataclasses import dataclass
from pathlib import Path
-from typing import TYPE_CHECKING, Literal
+from typing import Literal
from PIL import Image, ImageDraw
@@ -28,19 +28,25 @@ from codeverse3d.contracts.artifacts import (
RenderView,
Severity,
)
-from codeverse3d.contracts.chat import ChatMessage, ImagePart, TextPart
-from codeverse3d.contracts.plan import AcceptanceItem
+from codeverse3d.contracts.plan import (
+ AcceptanceItem,
+ ArticulatedPlan,
+ GraphicsPlan,
+ Plan,
+ ScenePlan,
+ StaticPlan,
+)
from codeverse3d.contracts.spec import Spec
from codeverse3d.conventions import (
OBJECT_CLAY_VIEWS,
OBJECT_VIEWS,
SCENE_VIEWS,
ViewPreset,
+ to_authoring_frame,
view_key,
)
from codeverse3d.judges.rubrics import VETO_PENETRATION_DEPTH_M, Rubric, wire_schema
from codeverse3d.proc import unique_tmp
-from codeverse3d.prompts import prompt_hash
from codeverse3d.spatial.connectivity import PENETRATION_ERROR_M, PENETRATION_WARN_M
from codeverse3d.spatial.measure import measure_summary_table
from codeverse3d.spatial.sheet import crop_region, load_font, montage_2x2
@@ -117,10 +123,6 @@ def _with_label_strip(im: Image.Image, label: str) -> Image.Image:
return canvas
-def image_part(path: Path, label: str) -> ImagePart:
- return ImagePart(path=str(path), mime="image/png", label=label)
-
-
MontageKind = Literal["shaded", "geometry", "poses", "pose_sheet", "detail"]
GEOMETRY_MODES = tuple(m for m in RENDER_MODES if m != "shaded")
@@ -225,14 +227,14 @@ def plan_montages(
if sheets:
candidates.append(Montage("pose_sheet", (sheets[0],), "POSE SHEET (rows = poses, columns = views; tile labels name the joint and its value)", passthrough=True))
elif poses:
- candidates.append(Montage("poses", tuple(poses[:MAX_TILES]), "POSED views (joints moved by the harness; tile label = pose)"))
+ candidates.append(Montage("poses", tuple(poses[:MAX_TILES]), "POSED views (joints moved by the instruments; tile label = pose)"))
if geometry:
geo = _match_geometry(geometry, candidates[0].tiles if candidates else ())
candidates.append(Montage("geometry", tuple(geo), f"GEOMETRY-ONLY views ({geo[0].mode}: no materials — look for holes, black/inverted faces, intersections, gaps)"))
for extra in shaded_groups[1:]:
candidates.append(Montage("shaded", tuple(extra), "SHADED views (remaining)"))
if sheets and poses:
- candidates.append(Montage("poses", tuple(poses[:MAX_TILES]), "POSED views (joints moved by the harness; tile label = pose)"))
+ candidates.append(Montage("poses", tuple(poses[:MAX_TILES]), "POSED views (joints moved by the instruments; tile label = pose)"))
chosen = candidates[: max(0, max_montages)]
chosen.extend(plan_detail_crops(shaded, scene=scene, gates=gates, limit=max(0, detail_crops)))
return chosen
@@ -435,25 +437,6 @@ def plan_contact_crops(shaded: list[RenderView], gates: Sequence[GateReport]) ->
return out
-def shuffle_montages(montages: list[Montage], seed: int | None) -> list[Montage]:
- """Permute montage order and the tile order inside each grid; detail crops stay last."""
- if seed is None:
- return list(montages)
- rng = random.Random(seed)
- grids = [m for m in montages if not m.is_detail]
- details = [m for m in montages if m.is_detail]
- rng.shuffle(grids)
- out = []
- for m in grids:
- if m.passthrough or len(m.tiles) < 2:
- out.append(m)
- continue
- tiles = list(m.tiles)
- rng.shuffle(tiles)
- out.append(replace(m, tiles=tuple(tiles)))
- return out + details
-
-
def tile_label(v: RenderView) -> str:
bits = [v.name]
azel = view_az_el(v)
@@ -527,28 +510,30 @@ def describe_montages(montages: list[Montage]) -> str:
return "\n".join(lines)
-if TYPE_CHECKING: # pragma: no cover
- from codeverse3d.judges.base import JudgeInput
+#: tracks whose rounds have one canonical GLB the judge slice channel may cut
+SLICE_TRACKS = ("static_object", "articulated_object")
+#: rubric for a static object judged against reference images (adds the measured silhouette criterion)
+REFERENCE_RUBRIC = "reference"
TEXT_BUDGET_CHARS = 24_000
MAX_PX = 1024
MONTAGE_TILE_PX = 512
SLICE_MAX_PX = 1024
-_ROLE = """You are the BLIND JUDGE of a 3D-code harness: exacting but fair.
-You see only the brief, a plan digest, measured numbers, deterministic gate findings and labelled renders of the result — never the builder's code or reasoning. Judge what is visible and measured; do not invent faults and do not credit what you cannot see.
+_ROLE = """You are the BLIND JUDGE of a 3D-code project: 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 (you read ONLY this brief and the images it lists). Judge what is visible and measured; do not invent faults and do not credit what you cannot see.
Gate findings describe the exported FILE (names, node hierarchy, contacts); the renders show the actual geometry. When they seem to disagree about something VISIBLE (a part moves in a posed tile, a part is present), trust the images for the visual criteria and report the file-level fact as an issue — never infer "nothing moves" or "part missing" from text alone when the tiles show otherwise.
Work in this order: observe (summary, strengths, issues), answer the defect checklist and the acceptance items, and only THEN score the criteria against their anchors.
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 — a primitive box-stack and a crafted product must be 0.4 apart, not 0.1.
- Every score needs evidence that cites the image and tile (e.g. "MONTAGE 1 top-left (front_right_high): rear leg ends 3 cm above ground; measurement ground_gap 0.03").
-- DEFECT CHECKLIST: answer EVERY item with present=true/false. true ONLY when the defect is visible in an image, or a gate finding of severity ERROR / a measurement states it; gate WARNINGS (e.g. a few-mm weld overlap) are informational and never make a defect present. Cite where. These answers drive penalties and caps computed by the harness, so be literal: do not mark a defect to "be safe", and do not hide one to be kind.
-- Do NOT compute an overall or decide pass/fail; the harness computes the weighted overall, subtracts defect penalties, applies floors and caps.
+- DEFECT CHECKLIST: answer EVERY item with present=true/false. true ONLY when the defect is visible in an image, or a gate finding of severity ERROR / a measurement states it; gate WARNINGS (e.g. a few-mm weld overlap) are informational and never make a defect present. Cite where. These answers drive penalties and caps computed in code, so be literal: do not mark a defect to "be safe", and do not hide one to be kind.
+- Do NOT compute an overall or decide pass/fail; `3dcode score` computes the weighted overall, subtracts defect penalties, 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 ("rear_leg_left: ends 3 cm above y=0 in the ground-contact crop — extend it to touch the ground"; "seat: measured 62 mm thick against the brief's 25 mm — thin it to the stated size"), 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."""
+- Write ONE JSON object matching the schema at the end of this brief to the judgment file it names; no prose outside it."""
#: end of the DEFECT CHECKLIST scoring-rule bullet in ``_ROLE``; the provenance sentence is appended after it
@@ -564,7 +549,7 @@ 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.")
+ lines.append(f"{i}. {c.id} (weight {c.weight:.2f}) — MEASURED IN CODE, 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()}")
@@ -633,7 +618,7 @@ def acceptance_section(items: list[AcceptanceItem]) -> str:
def measurement_section(m: Measurement | None) -> str:
if m is None:
return "MEASUREMENTS: (none available)"
- return "MEASUREMENTS (harness, Y-up meters):\n" + _clip(str(measure_summary_table(m)), 6000)
+ return "MEASUREMENTS (measured, Y-up meters):\n" + _clip(str(measure_summary_table(m)), 6000)
#: MEASURED STRUCTURE clips: contacts and planned joins are cut with an "… n more"
@@ -992,8 +977,8 @@ RIG_RULES: dict[str, str] = {
"elevation is degrees above the horizon (negative = looking up from below the ground plane, which reveals undersides and ground contact)."
),
"geometry": "The GEOMETRY-ONLY montage shows the same object without materials/lighting: use it for holes, inverted (black) faces, intersections and floating parts; use the SHADED montage for materials and detail.",
- "poses": "POSE tiles show the SAME object with joints moved by the harness (tile label = joint@value or rest). Judge articulation only from them and the joint table.",
- "scene_cams": "Views named overview_* and eye_* are harness cameras fitted to the scene bounds (layout X-ray); every other view is one of the scene's own authored cameras (grade composition/lighting on those); 't=' is the animation time.",
+ "poses": "POSE tiles show the SAME object with joints moved by the instruments (tile label = joint@value or rest). Judge articulation only from them and the joint table.",
+ "scene_cams": "Views named overview_* and eye_* are rig cameras fitted to the scene bounds (layout X-ray); every other view is one of the scene's own authored cameras (grade composition/lighting on those); 't=' is the animation time.",
"scene_craft": "On the authored cameras also read the CRAFT of the picture, not only its contents: depth readable for what each shot frames, surfaces that read as the brief's materials rather than one flat colour, variety among repeated elements, the secondary detail the brief's place implies, and distance softened where the brief's weather would soften it — each judged against what THIS place would have, not a fixed recipe. The same camera at two times appears as separate tiles; nothing_moves is answered from the MEASURED MOTION line only, never by comparing tiles.",
"scene_contact": "The high overview_* tiles (overview_front_right / overview_back_left / overview_top) are rendered with the fog removed and room ceilings lifted: a missing roof, lid or haze in them is never a defect. overview_low_front stands at ground level just outside the content, where daylight under a base shows. CONTACT CROP images are diagnostic close-ups cut from an overview tile around a placement finding the gate measured (the label names the asset, the kind and the number): judge the contact they show — base meets ground, part through neighbour — never their composition, lighting or dressing. Every floating / sunken / clipping / scale claim must name its view and its asset.",
"object": "All views show the same object. Use top + low views for symmetry, footprint and ground contact.",
@@ -1039,105 +1024,105 @@ def slice_rig_section(labels: list[str]) -> str:
+ lines)
-def judge_prompt_hash(rubric: Rubric) -> str:
- """Hash of everything the judge is told that is constant for a rubric: the system prompt, the fixed
- view-rig rules and the wire schema's structure. Per-run content is excluded."""
- payload = "\n".join([
- build_system_prompt(rubric),
- *(RIG_RULES[k] for k in sorted(RIG_RULES)),
- json.dumps(wire_schema(rubric, []), sort_keys=True),
- ])
- return prompt_hash(payload)
+def plan_summary(plan: Plan | None, language: str) -> str:
+ """The plan digest the judge reads. An object's size is written W×H×D in the GLB frame (Y-up),
+ so a Z-up plan's (W, D, H) is permuted first."""
+ if isinstance(plan, GraphicsPlan):
+ passes = ", ".join(f"{p.name} ({p.kind})" for p in plan.passes)
+ return (f"{plan.title}: {plan.summary} Style: {plan.style}. Passes: {passes}. Key visuals: {'; '.join(plan.key_visuals)}. "
+ f"Motion: {plan.motion or '(none planned)'}. {plan.resolution[0]}x{plan.resolution[1]}, loop {plan.duration_s:g}s.")
+ if isinstance(plan, ScenePlan):
+ return (f"{plan.title}: {plan.summary} Setting: {plan.setting}. Zones: {', '.join(z.name for z in plan.zones)}. "
+ f"Assets: {', '.join(a.name for a in plan.assets)}. Cameras: {', '.join(c.name for c in plan.cameras)}.")
+ if not isinstance(plan, StaticPlan):
+ return ""
+ parts = ", ".join(f"{p.name}×{p.instances}" if p.instances > 1 else p.name for p in plan.parts)
+ e = to_authoring_frame(plan.overall_bbox.extents, language, extents=True)
+ text = f"{plan.object_name}: {plan.summary} Overall {e[0]:.2f}×{e[1]:.2f}×{e[2]:.2f} m (W×H×D). Parts: {parts}."
+ if isinstance(plan, ArticulatedPlan):
+ joints = "; ".join(f"{j.name} ({j.type} {j.parent}→{j.child}, [{j.lower:.2f},{j.upper:.2f}])" for j in plan.joints)
+ text += f" Root link {plan.root_link}. Joints: {joints}."
+ return text
-def montage_image_parts(
+def montage_images(
renders: RenderSet,
*,
geometry_views: RenderSet | None = None,
scene: bool = False,
- shuffle_seed: int | None = None,
max_montages: int = MAX_MONTAGES,
detail_crops: int = MAX_DETAIL_CROPS,
max_px: int = MAX_PX,
cache_dir: Path | None = None,
gates: Sequence[GateReport] = (),
-) -> tuple[list[tuple[str, ImagePart]], list[Montage]]:
- """(label, ImagePart) pairs for the montages of a render set, plus the montage plan in send order."""
- montages = shuffle_montages(
- plan_montages(renders, geometry_views=geometry_views, scene=scene, max_montages=max_montages, detail_crops=detail_crops,
- gates=gates),
- shuffle_seed,
- )
+) -> tuple[list[tuple[str, Path]], list[Montage]]:
+ """``(label, labelled PNG)`` pairs for the montages of a render set, plus the montage plan in send order."""
+ montages = plan_montages(renders, geometry_views=geometry_views, scene=scene, max_montages=max_montages,
+ detail_crops=detail_crops, gates=gates)
grids = [m for m in montages if not m.is_detail]
details = [m for m in montages if m.is_detail]
- out: list[tuple[str, ImagePart]] = []
+ out: list[tuple[str, Path]] = []
for i, m in enumerate(grids, 1):
lbl, strip = montage_label(m, i, len(grids)), montage_strip(m, i, len(grids))
png = render_montage(m, cache_dir=cache_dir, tile_px=MONTAGE_TILE_PX)
- out.append((lbl, image_part(prepare_image(png, label=strip, max_px=max_px, cache_dir=cache_dir), lbl)))
+ out.append((lbl, prepare_image(png, label=strip, max_px=max_px, cache_dir=cache_dir)))
for i, m in enumerate(details, 1):
lbl, strip = montage_label(m, i, len(details)), montage_strip(m, i, len(details))
png = render_montage(m, cache_dir=cache_dir, tile_px=MONTAGE_TILE_PX)
- out.append((lbl, image_part(prepare_image(png, label=strip, max_px=min(max_px, 768), cache_dir=cache_dir), lbl)))
+ out.append((lbl, prepare_image(png, label=strip, max_px=min(max_px, 768), cache_dir=cache_dir)))
return out, montages
-def build_judge_messages(
- inp: JudgeInput,
- rubric: Rubric,
+def build_brief(
*,
- shuffle_seed: int | None = None,
- geometry_views: RenderSet | None = None,
- max_montages: int = MAX_MONTAGES,
- detail_crops: int = MAX_DETAIL_CROPS,
- max_px: int = MAX_PX,
- cache_dir: Path | None = None,
- extra_images: list[tuple[str, str | Path]] | None = None,
- extra_text: str = "",
- slice_images: list[tuple[str, str | Path]] | None = None,
- provenance_elicitation: bool = False,
-) -> tuple[str, list[ChatMessage]]:
- """Return ``(system, [user_message])`` for a rubric judge call.
-
- ``geometry_views`` is an optional clay/normals RenderSet; ``shuffle_seed`` permutes montage and tile order;
- ``extra_images`` go BEFORE the montages and ``slice_images`` AFTER the montages and crops; ``extra_text``
- is appended to the text block; ``provenance_elicitation`` adds one sentence to the system prompt.
- """
- system = build_system_prompt(rubric, provenance_elicitation=provenance_elicitation)
- is_scene = inp.spec.track.value == "scene"
+ spec: Spec,
+ plan: Plan | None,
+ rubric: Rubric,
+ renders: RenderSet,
+ measurement: Measurement | None,
+ gates: list[GateReport],
+ round_index: int,
+ previous: Judgment | None,
+ extra_context: str,
+ extra_text: str,
+ geometry_views: RenderSet | None,
+ images: list[tuple[str, Path]],
+ montages: list[Montage],
+ extra_images: Sequence[tuple[str, Path]] = (),
+ slice_images: Sequence[tuple[str, Path]] = (),
+ judgment_path: Path,
+) -> str:
+ """The whole judge brief as Markdown: role + rubric, the measured sections, the view rig, every image with its
+ label and absolute path (in viewing order), and the exact JSON object to write to ``judgment_path``."""
+ is_scene = spec.track.value == "scene"
+ system = build_system_prompt(rubric, provenance_elicitation=bool(slice_images))
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, scene=is_scene),
- previous_section(inp.previous, inp.round_index),
- _clip(inp.extra_context, 2500) if inp.extra_context.strip() else "",
+ brief_section(spec),
+ ("PLAN DIGEST:\n" + _clip(plan_summary(plan, spec.language.value), 5000)) if plan is not None else "PLAN DIGEST: (none)",
+ acceptance_section(list(getattr(plan, "acceptance", None) or [])),
+ measurement_section(measurement),
+ gates_section(gates, scene=is_scene),
+ previous_section(previous, round_index),
+ _clip(extra_context, 2500) if extra_context.strip() else "",
_clip(extra_text, 2500) if extra_text.strip() else "",
]
- extras = extra_images or []
- images, montages = montage_image_parts(
- inp.renders, geometry_views=geometry_views, scene=is_scene, shuffle_seed=shuffle_seed,
- max_montages=max_montages, detail_crops=detail_crops, max_px=max_px, cache_dir=cache_dir,
- gates=inp.gates if is_scene else (),
- )
- slices = slice_images or []
- rig = view_rig_section(inp.renders, montages, scene=is_scene)
- if slices:
- rig = rig + "\n" + slice_rig_section([lbl for lbl, _ in slices])
+ rig = view_rig_section(renders, montages, scene=is_scene)
+ if slice_images:
+ rig = rig + "\n" + slice_rig_section([lbl for lbl, _ in slice_images])
sections.append(rig)
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=min(max_px, 768), cache_dir=cache_dir), lbl))
- for lbl, ip in images:
- parts.append(TextPart(text=lbl))
- parts.append(ip)
- for lbl, p in slices:
- parts.append(TextPart(text=lbl))
- parts.append(image_part(prepare_image(p, label=lbl, max_px=SLICE_MAX_PX, cache_dir=cache_dir), lbl))
- parts.append(TextPart(text="Now score every criterion with evidence, answer every defect-checklist item and every acceptance item, and return the JSON object."))
- return system, [ChatMessage(role="user", parts=parts)]
+ acceptance_ids = [a.id for a in (getattr(plan, "acceptance", None) or [])]
+ schema = json.dumps(wire_schema(rubric, acceptance_ids), indent=1)
+ listing = "\n".join(f"{i}. {lbl}\n {p}" for i, (lbl, p) in enumerate([*extra_images, *images, *slice_images], 1))
+ return (
+ f"# Judge brief — round {round_index}\n\n"
+ "## Your role\n\n" + system + "\n\n"
+ "## The case\n\n" + text + "\n\n"
+ "## Images (open each with your image viewer, in this order)\n\n" + listing + "\n\n"
+ "## Return exactly this JSON\n\n"
+ f"Write ONE JSON object matching this schema to `{judgment_path}` (nothing else in the file). Score every "
+ "criterion with evidence, answer every defect-checklist item and every acceptance item.\n\n"
+ "```json\n" + schema + "\n```\n"
+ )
diff --git a/harness/codeverse3d/judges/rubrics.py b/harness/codeverse3d/judges/rubrics.py
index ca44db70..0d052253 100644
--- a/harness/codeverse3d/judges/rubrics.py
+++ b/harness/codeverse3d/judges/rubrics.py
@@ -36,7 +36,6 @@ from codeverse3d.contracts.artifacts import (
RenderView,
Severity,
)
-from codeverse3d.contracts.common import Usage
from codeverse3d.contracts.plan import AcceptanceItem
from codeverse3d.jsonparse import JsonParseError, parse_json_lenient
@@ -560,13 +559,11 @@ SCORING_VERSION = 4
"""The arithmetic downstream of the model, stamped into every ``ScoreBreakdown``.
A stored verdict is reproducible from its samples only under the version that wrote
-it (``eval/bench/rejudge_offline.py --identity`` compares nothing else); an older stamp is
-drift to report, not a fault.
+it; an older stamp is drift to report, not a fault.
Versions: 1 veto of checklist defects a passed gate measured absent · 2 ``CapRule.measures``, a defect
vote tie is absent, graded ``missing_must_acceptance`` · 3 cap ``kinds`` match the typed ``data.kind`` /
-``data.code`` (a replay of 1 229 judged rounds moved no cap and no veto) · 4 the veto is scoped to the
-rule's ``kinds`` and its WARN magnitude is ``veto_warn_keys`` (history: ``eval/docs/EVAL.md``).
+``data.code`` · 4 the veto is scoped to the rule's ``kinds`` and its WARN magnitude is ``veto_warn_keys``.
"""
@@ -623,7 +620,6 @@ def aggregate_samples(
acceptance_items: list[AcceptanceItem],
console_errors: list[str] | None = None,
views: list[RenderView] | None = None,
- usage: Usage | None = None,
judge_backend: str = "",
n_requested: int | None = None,
sample_errors: list[str] | None = None,
@@ -727,7 +723,6 @@ def aggregate_samples(
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),
)
@@ -767,28 +762,3 @@ def _verdict_tail(
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, judge_prompt_hash: str = ""
-) -> Judgment:
- """A verdict the orchestrator must treat as a GLITCH (not a score): ``raw.status == 'degraded'``."""
- breakdown = {
- "status": "degraded",
- "scoring_version": SCORING_VERSION,
- "error": error,
- "n_requested": n_requested,
- "rubric_hash": rubric.content_hash(),
- "judge_prompt_hash": judge_prompt_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),
- )
diff --git a/harness/codeverse3d/languages/base.py b/harness/codeverse3d/languages/base.py
index 14e126bb..9855cae3 100644
--- a/harness/codeverse3d/languages/base.py
+++ b/harness/codeverse3d/languages/base.py
@@ -1,42 +1,27 @@
-"""LanguageRuntime protocol + registry: starter files, static lint, sandboxed build, file ownership."""
+"""LanguageRuntime protocol + registry: static lint, sandboxed build, the files a language expects."""
from __future__ import annotations
from collections.abc import Callable, Sequence
from importlib import import_module
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Protocol
-
-from pydantic import BaseModel, Field
+from typing import TYPE_CHECKING, Protocol
from codeverse3d.contracts.artifacts import BuildResult, GateReport, RenderSet
from codeverse3d.contracts.common import ENTRY_FILE, Language
-from codeverse3d.contracts.plan import AssetPlan, CameraPlan, Plan, ScenePlan
-from codeverse3d.conventions import SCENE_TIMES, to_snake
+from codeverse3d.contracts.plan import AssetPlan, CameraPlan, Plan
+from codeverse3d.conventions import SCENE_TIMES
from codeverse3d.workspace import Workspace
if TYPE_CHECKING:
from codeverse3d.spatial.probes import SceneProbeResult
-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
- warnings: list[str] = Field(default_factory=list)
- census: dict[str, Any] = Field(default_factory=dict)
-
-
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)."""
...
@@ -46,18 +31,14 @@ class LanguageRuntime(Protocol):
...
def expected_files(self, plan: Plan | None) -> list[str]:
- """The files a whole-artifact session writes for ``plan``, entry first."""
- ...
-
- def files_for(self, plan: Plan | None, target: str) -> list[str]:
- """The files that own a refine target (part, zone, asset, camera, env word); ``[]`` leaves the task whole-artifact."""
+ """The files the agent writes for ``plan``, entry first."""
...
class SceneRuntime(LanguageRuntime, Protocol):
- """What the scene track asks of its language: zone / asset locations, entry assembly, probe and render."""
+ """What the scene track asks of its language: zone / asset locations, probe and render."""
-#: the environment module the env stage writes (``src/env.js`` / ``src/env.py``)
+ #: the environment module (``src/env.js`` / ``src/env.py``)
env_file: str
def zone_file(self, name: str) -> str:
@@ -68,19 +49,6 @@ class SceneRuntime(LanguageRuntime, Protocol):
"""The file an asset ships as: its factory module, or a hero's GLB."""
...
- def assemble(self, ws: Workspace, plan: ScenePlan) -> BaseModel:
- """Write the entry file from the zones that load (the plan's cameras, else derived ones);
- the result lands in ``artifacts/assemble.json``."""
- ...
-
- def lib_interface(self, ws: Workspace) -> str:
- """The harness-owned ``src/lib/`` as one fact line per module (exports and parameters); ``""`` if none."""
- ...
-
- def check_env(self, ws: Workspace) -> str:
- """The env module alone: ``""`` when it lints, builds and lights clean; else the failure, quoted for a repair prompt."""
- ...
-
def probe(self, ws: Workspace, *, timeout_s: float | None = None) -> SceneProbeResult:
"""Load the built scene headlessly: the ``scene_probe`` gate + the census."""
...
@@ -93,10 +61,10 @@ class SceneRuntime(LanguageRuntime, Protocol):
class RuntimeLayout:
- """``expected_files`` / ``files_for`` for a runtime whose entry file (+ ``extra_files``) owns the whole artifact."""
+ """``expected_files`` for a runtime whose entry file (+ ``extra_files``) owns the whole artifact."""
language: Language
- #: files a whole-artifact session owns besides the entry (urdf: robot.urdf; glsl_shader: common.glsl)
+ #: files the agent owns besides the entry (urdf: robot.urdf; glsl_shader: common.glsl)
extra_files: tuple[str, ...] = ()
#: plan part name → the file that builds it, in a language with one file per part (blender, three.js)
part_file: Callable[[str], str] | None = None
@@ -105,14 +73,6 @@ class RuntimeLayout:
parts = [self.part_file(p.name) for p in getattr(plan, "parts", None) or ()] if self.part_file else []
return [ENTRY_FILE[self.language], *self.extra_files, *parts]
- def files_for(self, plan: Plan | None, target: str) -> list[str]:
- if self.part_file is None:
- return []
- key = to_snake(target)
- if key in {to_snake(p.name) for p in getattr(plan, "parts", None) or ()}:
- return [self.part_file(target)]
- return [ENTRY_FILE[self.language]] if key in ("overall", "assembly", "object", "") else []
-
#: Language → (module, class); the import is lazy.
_RUNTIMES: dict[Language, tuple[str, str]] = {
@@ -130,26 +90,3 @@ _RUNTIMES: dict[Language, tuple[str, str]] = {
def get_runtime(language: Language | str) -> LanguageRuntime:
module, cls = _RUNTIMES[Language(language)]
return getattr(import_module(module), cls)()
-
-
-def scene_files_for(plan: Plan | None, target: str, *, zone_file: Callable[[str], str], asset_file: Callable[[AssetPlan], str],
- entry: str, env_file: str, env_words: frozenset[str]) -> list[str]:
- """The files that own a scene refine target: a module asset in its own file, a hero where it is placed, cameras in the
- entry, env words in the env file, ``Zone/..`` in the zone."""
- zone_plans = list(getattr(plan, "zones", None) or [])
- zones = {to_snake(z.name) for z in zone_plans}
- assets = {to_snake(a.name): a for a in (getattr(plan, "assets", None) or [])}
- key = to_snake(target)
- if key in zones:
- return [zone_file(key)]
- if key in assets:
- if asset_file(assets[key]).startswith("src/"):
- return [asset_file(assets[key])]
- return [zone_file(z.name) for z in zone_plans if key in {to_snake(c) for c in z.contents}]
- if key in {to_snake(c.name) for c in (getattr(plan, "cameras", None) or [])} or key in ("camera", "cameras", "composition"):
- return [entry]
- if key in env_words:
- return [env_file]
- if "/" in target and to_snake(target.split("/", 1)[0]) in zones:
- return [zone_file(target.split("/", 1)[0])]
- return []
diff --git a/harness/codeverse3d/languages/blender/__init__.py b/harness/codeverse3d/languages/blender/__init__.py
index 02786a51..3aaf80a6 100644
--- a/harness/codeverse3d/languages/blender/__init__.py
+++ b/harness/codeverse3d/languages/blender/__init__.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import ast
-import math
import os
import time
from pathlib import Path
@@ -11,8 +10,7 @@ from pathlib import Path
from codeverse3d.config import Settings, get_settings
from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, LintKind, Severity
from codeverse3d.contracts.common import ENTRY_FILE, Language
-from codeverse3d.contracts.plan import BBox, PartPlan, Plan, StaticPlan
-from codeverse3d.conventions import GROUND_TOL_M, PASCAL_RE, fmt3, to_pascal, to_snake
+from codeverse3d.conventions import PASCAL_RE, to_snake
from codeverse3d.languages._ast_lint import (
BASE_FORBIDDEN_IMPORTS,
check_imports,
@@ -22,7 +20,6 @@ from codeverse3d.languages._ast_lint import (
)
from codeverse3d.languages._common import run_wrapper_build, strip_blender_noise, ws_rel
from codeverse3d.languages.base import RuntimeLayout
-from codeverse3d.languages.blender._pbr import family_for, pbr_for
from codeverse3d.proc import scrub_secrets
from codeverse3d.workspace import Workspace
@@ -205,7 +202,6 @@ def _f(kind: LintKind, sev: Severity, msg: str, line: int | None = None, hint: s
return GateFinding(gate=GATE, severity=sev, target=target, message=msg, fix_hint=hint, data=data)
-
# API traps of bpy itself, shared by the object lint and the scene lint.
def call_traps(c: BpyCollector, name: str, call: ast.Call) -> list[GateFinding]:
out: list[GateFinding] = []
@@ -469,229 +465,10 @@ _COLOUR_WORDS: tuple[tuple[str, tuple[float, float, float]], ...] = (
)
-def finish_for(text: str) -> tuple[tuple[float, float, float], float, float]:
- """Placeholder (rgb, roughness, metallic) from the material family, else a bare colour word, else grey."""
- hit = family_for(text)
- pbr = pbr_for(hit.family) if hit else None
- if pbr is not None:
- return pbr.base_hint, pbr.roughness, pbr.metallic
- low = text.lower()
- return next((rgb for word, rgb in _COLOUR_WORDS if word in low), (0.6, 0.6, 0.6)), 0.5, 0.0
-
-
-def instance_centers(bbox: BBox, n: int, symmetry: str) -> list[tuple[float, float, float]]:
- 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)]
-
-
# ----------------------------------------------------------------------------- shared text blocks
-IMPORTS = '''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 = '''
-# ----------------------------------------------------------------------------- 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):
- """PLACEHOLDER helper (replace freely): an axis-aligned box of exactly `extents`, scale baked."""
- 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)
- return obj
-
-'''
-
-SELFCHECK = '''
-def _selfcheck():
- """Optional: meshes exist, no auto-suffixed names, lowest point — over the meshes that
- export (a hidden boolean cutter does not). Fails only past the ground gate's ERROR line."""
- bpy.context.view_layer.update()
- shown = set(bpy.context.view_layer.objects.keys())
- meshes = [o for o in bpy.data.objects if o.type == "MESH" and o.name in shown
- and not (o.hide_render or o.hide_viewport or o.hide_get())]
- assert meshes, "no mesh objects built"
- for o in meshes:
- assert "." not in o.name, f"auto-suffixed name {o.name!r}: give every instance its own name"
- z_min = min((o.matrix_world @ Vector(c)).z for o in meshes for c in o.bound_box)
- assert abs(z_min) < 3 * __GROUND_TOL__, f"lowest point z={z_min:.4f}: check_contract reports this as an ERROR"
- print(f"[selfcheck] {len(meshes)} mesh objects, z_min={z_min:.4f}")
-
-'''
-
-
-def _constants(p: PartPlan) -> str:
- mn, mx = p.bbox.min, p.bbox.max
- pre = to_snake(p.name).upper()
- return (
- f"# ---- plan bbox (metres) for {to_pascal(p.name)}: the built AABB must match it within max(1 cm, 10 %) "
- f"per axis (check_contract)\n"
- f"{pre}_CENTER = ({fmt3(p.bbox.center)})\n"
- f"{pre}_EXTENTS = ({fmt3(p.bbox.extents)})\n"
- f"{pre}_MIN = ({fmt3(mn)})\n"
- f"{pre}_MAX = ({fmt3(mx)})\n"
- f"{pre}_INSTANCES = {p.instances}\n"
- )
-
-
-def _part_function(p: PartPlan) -> str:
- pascal, snake, fn = to_pascal(p.name), to_snake(p.name), build_fn_name(p.name)
- pre = snake.upper()
- rgb, rough, metal = finish_for(f"{p.material} {p.description}")
- mn, mx = p.bbox.min, p.bbox.max
- lines = [
- f"def {fn}():",
- f' """{pascal} — {p.role}',
- f" {p.description}",
- f" Material: {p.material or 'n/a'}",
- f" Plan bbox: center ({fmt3(p.bbox.center)}) extents ({fmt3(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)} (surface gap <= 2 mm, overlap <= 2 mm: check_connectivity)")
- if p.instances > 1:
- lines.append(f" Instances: {p.instances} ({p.symmetry}) -> named {pascal}_0..{pascal}_{p.instances - 1}, "
- f"each TOP-LEVEL (no parent Empty — it would merge them into one measured part); returns the list")
- lines += [' Returns the object(s) at WORLD pose (Z up, -Y front, metres).', ' """']
- lines.append(f" mat = make_material(\"{pascal}Mat\", ({fmt3(rgb)}), roughness={rough}, metallic={metal})")
- if p.instances == 1:
- lines += [
- " # TODO: replace this placeholder box with the real geometry (keep the name + bbox)",
- f" return add_box(\"{pascal}\", {pre}_CENTER, {pre}_EXTENTS, mat)",
- ]
- else:
- centers = [tuple(round(x, 4) for x in c) for c in instance_centers(p.bbox, p.instances, p.symmetry)]
- lines += [
- " objs = []",
- f" for i, c in enumerate({centers}): # TODO: exact placement",
- " # TODO: replace this placeholder box with the real geometry (keep the names + bbox)",
- f" objs.append(add_box(f\"{pascal}_{{i}}\", c, {pre}_EXTENTS, mat))",
- " return objs",
- ]
- return "\n".join(lines) + "\n"
-
-
-def _plan_header(plan: StaticPlan) -> str:
- 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 ({fmt3(p.bbox.center)}) "
- f"extents ({fmt3(p.bbox.extents)}) [{part_file_rel(p.name)}]"
- for p in plan.parts
- )
- accept = "\n".join(f" - [{a.id}] {a.text}" for a in plan.acceptance) or " (none listed)"
- layout = (
- f" * LAYOUT: this file is the ENTRY. Each part lives in src/{PARTS_DIR}/<snake>.py and exports\n"
- f" build_<snake>() -> bpy.types.Object; main() below imports and calls each once.\n"
- " The lint checks that every part file is imported here; the rest of this file is yours.\n"
- )
- return 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 ({fmt3(ob.center)}) extents ({fmt3(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,
- each TOP-LEVEL (never parented under an Empty — that merges them into ONE measured part).
-{layout} * 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.
- * Each part's built AABB matches its row within max(1 cm, 10 %) per axis (3x that is an ERROR);
- touching parts: surface gap <= 2 mm, overlap <= 2 mm; every part reaches the ground through
- its neighbours (check_contract, check_connectivity).
- * Modifiers may stay unapplied (the exporter applies them).
- * NEVER: cameras, lights, world, render settings, export/import, file IO, bpy.ops.wm.*.
- * Imports: the contract's allow-list (bpy, bmesh, mathutils, math, random, numpy, ...); seed random.
-
-PARTS:
-{parts_doc}
-
-ACCEPTANCE:
-{accept}
-"""
-'''
# ----------------------------------------------------------------------------- public renderers
-def part_file_source(p: PartPlan) -> str:
- pascal, fn = to_pascal(p.name), build_fn_name(p.name)
- doc = (
- f'"""{pascal} — {p.role} (part module; imported by src/model.py).\n\n'
- f"{p.description}\n"
- f"Material: {p.material or 'n/a'}. Instances: {p.instances}"
- + (f" ({p.symmetry})" if p.instances > 1 else "")
- + (f". Attaches to: {to_pascal(p.attach_to)} (gap <= 2 mm, overlap <= 2 mm)" if p.attach_to else "")
- + f".\n\nExports `{fn}() -> bpy.types.Object`: builds the part at its WORLD pose (Z up, -Y front,\n"
- "metres) with the exact object name(s) and returns it (list of TOP-LEVEL objects when\n"
- "instanced — never parent instances under an Empty). Do NOT call it here — model.py does.\n"
- "Shared helpers may live in src/parts/_<name>.py (not a part); imports per the contract's allow-list.\n"
- '"""\n'
- )
- return doc + IMPORTS + "\n" + _constants(p) + HELPERS + "\n# ----------------------------------------------------------------------------- part\n" + _part_function(p)
-
-
-def selfcheck_source(ground_tol_m: float = GROUND_TOL_M) -> str:
- return SELFCHECK.replace("__GROUND_TOL__", f"{ground_tol_m:g}")
-
-
-def model_file_source(plan: StaticPlan, *, ground_tol_m: float = GROUND_TOL_M) -> str:
- imports = "\n".join(f"from {PARTS_DIR}.{to_snake(p.name)} import {build_fn_name(p.name)}" for p in plan.parts)
- calls = "\n".join(f" {build_fn_name(p.name)}()" for p in plan.parts)
- return (
- _plan_header(plan)
- + "import bpy\nfrom mathutils import Vector\n\n"
- + imports + "\n\n"
- + selfcheck_source(ground_tol_m)
- + "\ndef main():\n # build every part (order = plan order); parts are placed at world pose by their builders\n"
- + calls + "\n _selfcheck()\n\n\nmain()\n"
- )
-
-
-def write_blender_skeleton(ws: Workspace, plan: StaticPlan, *, ground_tol_m: float = GROUND_TOL_M) -> list[Path]:
- """Write the starter files (overwrites) and return the written paths (entry first).
-
- ``ground_tol_m`` is the self-check's "stands on z=0" tolerance."""
- ws.src.mkdir(parents=True, exist_ok=True)
- entry = ws.src / "model.py"
- entry.write_text(model_file_source(plan, ground_tol_m=ground_tol_m))
- written = [entry]
- for p in plan.parts:
- path = ws.root / part_file_rel(p.name)
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(part_file_source(p))
- written.append(path)
- return written
# ===================================================================== runtime
@@ -733,11 +510,6 @@ class BlenderRuntime(RuntimeLayout):
def entry_file(self, ws: Workspace) -> Path:
return ws.root / ENTRY_REL
- # ------------------------------------------------------------------ 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_workspace(ws)
diff --git a/harness/codeverse3d/languages/blender/_pbr.py b/harness/codeverse3d/languages/blender/_pbr.py
deleted file mode 100644
index 5fd294e1..00000000
--- a/harness/codeverse3d/languages/blender/_pbr.py
+++ /dev/null
@@ -1,247 +0,0 @@
-"""The material-family table: PBR factors (metallic, roughness, IOR, clear-coat) per finish.
-
-``languages/blender`` reads it (``family_for`` / ``pbr_for``). Data + pure functions only.
-"""
-
-from __future__ import annotations
-
-from typing import NamedTuple
-
-from pydantic import BaseModel, Field
-
-from codeverse3d.conventions import to_snake
-
-
-class Pbr(BaseModel):
- """One material family's physically-plausible factors."""
-
- family: str
- metallic: float = Field(ge=0.0, le=1.0)
- roughness: float = Field(ge=0.0, le=1.0)
- ior: float = 1.5
- clearcoat: float = 0.0
- clearcoat_roughness: float = 0.1
- sheen: float = 0.0
- transmission: float = 0.0
-#: base colour a real sample of this finish sits near (a hint, never forced)
- base_hint: tuple[float, float, float] = (0.5, 0.5, 0.5)
-#: plausible roughness spread (the normaliser's confidence band)
- roughness_band: tuple[float, float] = (0.0, 1.0)
- metallic_band: tuple[float, float] = (0.0, 1.0)
- note: str = ""
-
-
-def _m(
- family: str, metallic: float, roughness: float, *, ior: float = 1.5, clearcoat: float = 0.0,
- ccr: float = 0.1, sheen: float = 0.0, transmission: float = 0.0,
- base: tuple[float, float, float] = (0.5, 0.5, 0.5),
- rband: tuple[float, float] = (0.0, 1.0), mband: tuple[float, float] = (0.0, 1.0), note: str = "",
-) -> Pbr:
- return Pbr(family=family, metallic=metallic, roughness=roughness, ior=ior, clearcoat=clearcoat,
- clearcoat_roughness=ccr, sheen=sheen, transmission=transmission, base_hint=base,
- roughness_band=rband, metallic_band=mband, note=note)
-
-
-#: family -> PBR factors with plausible bands
-MATERIALS: dict[str, Pbr] = {
- "painted_metal": _m("painted_metal", 0.0, 0.35, clearcoat=0.35, ccr=0.10, base=(0.30, 0.32, 0.36),
- rband=(0.08, 0.7), mband=(0.0, 0.35),
- note="appliance / machine enamel: a DIELECTRIC coat over steel, metallic 0 + clearcoat"),
- "brushed_metal": _m("brushed_metal", 1.0, 0.32, base=(0.62, 0.63, 0.65), rband=(0.15, 0.6), mband=(0.6, 1.0),
- note="stainless / brushed aluminium; grain is anisotropic — fake it with a streaked roughness map"),
- "chrome": _m("chrome", 1.0, 0.06, base=(0.83, 0.85, 0.88), rband=(0.0, 0.3), mband=(0.7, 1.0),
- note="mirror plating: needs an environment with SHAPE to reflect or it reads as flat grey"),
- "machined_steel": _m("machined_steel", 1.0, 0.22, base=(0.56, 0.57, 0.60), rband=(0.05, 0.5), mband=(0.6, 1.0),
- note="tool steel, bright bar, drill bits"),
- "cast_iron": _m("cast_iron", 1.0, 0.62, base=(0.11, 0.11, 0.12), rband=(0.3, 0.95), mband=(0.5, 1.0),
- note="sand-cast surface: dark, rough, still metallic — pebbly roughness map sells it"),
- "brass": _m("brass", 1.0, 0.25, base=(0.85, 0.65, 0.28), rband=(0.05, 0.6), mband=(0.6, 1.0),
- note="lacquered brass hardware"),
- "copper_patina": _m("copper_patina", 0.20, 0.72, base=(0.36, 0.56, 0.50), rband=(0.4, 1.0), mband=(0.0, 0.6),
- note="verdigris is an oxide CRUST: mostly dielectric, only the worn edges stay metallic"),
- "hardwood": _m("hardwood", 0.0, 0.45, clearcoat=0.25, ccr=0.15, base=(0.34, 0.20, 0.10),
- rband=(0.15, 0.85), mband=(0.0, 0.2),
- note="oak / walnut / teak with a satin varnish; grain must modulate roughness, not just colour"),
- "softwood": _m("softwood", 0.0, 0.72, base=(0.55, 0.40, 0.24), rband=(0.4, 1.0), mband=(0.0, 0.2),
- note="raw pine / construction timber: no coat, high roughness"),
- "glossy_plastic": _m("glossy_plastic", 0.0, 0.22, ior=1.46, clearcoat=0.20, base=(0.45, 0.45, 0.48),
- rband=(0.02, 0.5), mband=(0.0, 0.25), note="injection-moulded ABS/PC housing"),
- "rough_plastic": _m("rough_plastic", 0.0, 0.62, ior=1.46, base=(0.40, 0.40, 0.42),
- rband=(0.25, 1.0), mband=(0.0, 0.25), note="textured / bead-blasted tool housing, nylon"),
- "rubber": _m("rubber", 0.0, 0.88, ior=1.52, base=(0.06, 0.06, 0.06), rband=(0.55, 1.0), mband=(0.0, 0.2),
- note="grips, tyres, feet: nearly no specular lobe"),
- "fabric": _m("fabric", 0.0, 0.92, sheen=0.30, base=(0.48, 0.44, 0.40), rband=(0.6, 1.0), mband=(0.0, 0.15),
- note="woven upholstery: sheen at grazing angles is what says 'cloth'"),
- "leather": _m("leather", 0.0, 0.58, ior=1.45, clearcoat=0.10, base=(0.24, 0.13, 0.08),
- rband=(0.25, 0.9), mband=(0.0, 0.15), note="pores + a faint coat; never mirror-smooth"),
- "glass": _m("glass", 0.0, 0.03, ior=1.52, transmission=1.0, base=(0.94, 0.96, 0.96),
- rband=(0.0, 0.25), mband=(0.0, 0.3), note="transmissive; roughness > 0.15 turns it to frosted"),
- "ceramic": _m("ceramic", 0.0, 0.12, ior=1.60, clearcoat=0.50, ccr=0.03, base=(0.85, 0.84, 0.80),
- rband=(0.0, 0.60), mband=(0.0, 0.2),
- note="glaze is a thick clear coat over a matte body; unglazed terracotta goes to 0.6"),
- "concrete": _m("concrete", 0.0, 0.90, base=(0.52, 0.51, 0.49), rband=(0.5, 1.0), mband=(0.0, 0.2),
- note="also render / plaster / unglazed terracotta"),
- "stone": _m("stone", 0.0, 0.42, base=(0.45, 0.44, 0.42), rband=(0.05, 1.0), mband=(0.0, 0.2),
- note="polished marble 0.20, granite 0.45, slate 0.70"),
- "paper": _m("paper", 0.0, 0.85, base=(0.82, 0.80, 0.76), rband=(0.5, 1.0), mband=(0.0, 0.15),
- note="card, book pages, lampshade paper"),
- "painted_wood": _m("painted_wood", 0.0, 0.42, clearcoat=0.12, ccr=0.20, base=(0.72, 0.71, 0.68),
- rband=(0.15, 0.85), mband=(0.0, 0.25),
- note="paint on timber: flatter than car enamel, and the grain still shows through"),
-}
-
-#: substrate keywords (what the part is made of), checked before finishes
-SUBSTRATE_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
- ("wood_hard", ("oak", "walnut", "teak", "maple", "beech", "birch", "mahogany", "cherry", "ash",
- "hardwood", "veneer", "plywood", "bamboo", "rosewood")),
- ("wood_soft", ("pine", "spruce", "fir", "cedar", "timber", "softwood", "lumber", "plank", "batten")),
- ("glass", ("glass", "acrylic", "perspex", "crystal", "lens", "glazing", "pane", "windscreen")),
- ("ceramic", ("ceramic", "porcelain", "china", "earthenware", "stoneware")),
- ("fabric", ("fabric", "cloth", "textile", "linen", "cotton", "canvas", "wool", "felt", "velvet",
- "upholstery", "upholstered", "boucle", "webbing", "denim", "burlap")),
- ("leather", ("leather", "suede", "hide", "saddle")),
- ("rubber", ("rubber", "silicone", "neoprene", "tyre", "tire", "grip", "gasket", "grommet")),
- ("copper", ("copper", "verdigris")),
- ("brass", ("brass", "bronze", "gilt")),
- ("cast_iron", ("castiron", "cast", "wrought", "iron")),
- ("light_metal", ("aluminium", "aluminum", "stainless", "nickel", "pewter", "zinc", "titanium",
- "galvanised", "galvanized")),
- ("steel", ("steel", "machined", "hardened", "gunmetal", "metal", "metallic", "alloy")),
- ("concrete", ("concrete", "cement", "plaster", "render", "stucco", "terracotta", "brick", "mortar")),
- ("stone", ("stone", "marble", "granite", "slate", "terrazzo", "rock", "pebble", "gravel")),
- ("paper", ("paper", "card", "cardboard", "parchment", "lampshade")),
- ("plastic", ("plastic", "abs", "polycarbonate", "polypropylene", "nylon", "resin", "vinyl", "pvc",
- "melamine", "bakelite", "composite", "acrylonitrile", "laminate")),
- ("wood", ("wood", "wooden", "woodgrain")),
-)
-
-#: finish keywords — HOW the substrate is surfaced.
-FINISH_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
- ("plated", ("chrome", "chromed", "plated", "mirrored")),
- ("brushed", ("brushed", "satin", "anodised", "anodized", "sandblasted", "beadblasted")),
- ("painted", ("painted", "paint", "enamel", "enamelled", "enameled", "lacquer", "lacquered",
- "powdercoated", "powdercoat", "coated", "sprayed", "primed")),
- ("varnished", ("varnished", "varnish", "oiled", "waxed", "shellac", "stained", "glazed")),
- ("patina", ("patina", "verdigris", "oxidised", "oxidized", "weathered", "rusted", "rusty", "aged",
- "tarnished", "corroded")),
- ("matte", ("matte", "matt", "textured", "rough", "gritty")),
- ("gloss", ("gloss", "glossy", "shiny", "high-gloss", "highgloss")),
-)
-
-#: (substrate, finish) -> family; ``None`` finish = bare
-_RESOLVE: dict[tuple[str, str | None], str] = {
- ("wood_hard", None): "hardwood", ("wood_hard", "painted"): "painted_wood",
- ("wood_soft", None): "softwood", ("wood_soft", "painted"): "painted_wood",
- ("wood_soft", "varnished"): "hardwood",
- ("wood", None): "hardwood", ("wood", "painted"): "painted_wood", ("wood", "matte"): "softwood",
- ("cast_iron", None): "cast_iron", ("cast_iron", "painted"): "painted_metal",
- ("cast_iron", "plated"): "chrome", ("cast_iron", "brushed"): "brushed_metal",
- ("steel", None): "machined_steel", ("steel", "plated"): "chrome", ("steel", "brushed"): "brushed_metal",
- ("steel", "painted"): "painted_metal", ("steel", "patina"): "cast_iron", ("steel", "matte"): "cast_iron",
- ("brass", None): "brass", ("brass", "painted"): "painted_metal",
- ("copper", None): "brass", ("copper", "patina"): "copper_patina",
- ("light_metal", None): "brushed_metal", ("light_metal", "plated"): "chrome",
- ("light_metal", "painted"): "painted_metal", ("light_metal", "patina"): "copper_patina",
- ("glass", None): "glass",
- ("ceramic", None): "ceramic",
- ("rubber", None): "rubber",
- ("fabric", None): "fabric",
- ("leather", None): "leather",
- ("concrete", None): "concrete", ("concrete", "painted"): "painted_wood",
- ("stone", None): "stone",
- ("paper", None): "paper",
- ("plastic", None): "rough_plastic", ("plastic", "gloss"): "glossy_plastic",
- ("plastic", "plated"): "glossy_plastic", ("plastic", "matte"): "rough_plastic",
-}
-
-#: a finish with no substrate named at all
-_FINISH_ONLY: dict[str, str] = {
- "plated": "chrome", "brushed": "brushed_metal", "painted": "painted_metal",
- "varnished": "hardwood", "patina": "copper_patina", "matte": "rough_plastic",
- "gloss": "glossy_plastic",
-}
-
-#: the coarse families (wood, metal, ...) -> a representative fine family, for ``pbr_for``.
-COARSE_TO_FINE: dict[str, str] = {
- "wood": "hardwood", "metal": "machined_steel", "fabric": "fabric", "stone": "stone",
- "plastic": "rough_plastic", "leather": "leather", "glass": "glass", "ceramic": "ceramic",
- "painted": "painted_metal", "rubber": "rubber", "other": "rough_plastic",
-}
-
-
-class FamilyMatch(NamedTuple):
- family: str
- keyword: str
-
-
-def _tokens(text: str) -> set[str]:
- """Whole words of ``text`` as ``to_snake`` splits them, plus the words joined."""
- s = str(text or "")
- parts = [w for w in to_snake(s).split("_") if w] if any(c.isascii() and c.isalnum() for c in s) else []
- joined = "".join(parts)
- return {*parts, joined} if joined else set(parts)
-
-
-#: word ENDINGS that name a substrate on their own ("basswood", "sandstone", "plexiglass")
-SUBSTRATE_SUFFIXES: tuple[tuple[str, str], ...] = (
- ("wood", "wood_hard"), ("stone", "stone"), ("glass", "glass"), ("leather", "leather"),
- ("board", "wood"), ("brick", "concrete"),
-)
-
-
-def _first_hit(table: tuple[tuple[str, tuple[str, ...]], ...], toks: set[str]) -> tuple[str, str] | None:
- for key, keywords in table:
- for kw in keywords:
- if kw in toks:
- return key, kw
- return None
-
-
-def _substrate(toks: set[str]) -> tuple[str, str] | None:
- hit = _first_hit(SUBSTRATE_KEYWORDS, toks)
- if hit is not None:
- return hit
- for tok in sorted(toks):
- for suffix, key in SUBSTRATE_SUFFIXES:
- if len(tok) > len(suffix) and tok.endswith(suffix):
- return key, tok
- return None
-
-
-def family_for(*texts: str) -> FamilyMatch | None:
- """Resolve a material family from free text; ``None`` when nothing matches.
-
- The first argument that resolves wins; within one text, substrate before finish."""
- for text in texts: # material name beats node name beats the plan's prose
- hit = _resolve_one(_tokens(text))
- if hit is not None:
- return hit
- return _resolve_one({t for text in texts for t in _tokens(text)})
-
-
-def _resolve_one(toks: set[str]) -> FamilyMatch | None:
- if not toks:
- return None
- sub = _substrate(toks)
- fin = _first_hit(FINISH_KEYWORDS, toks)
- if sub is not None:
- key, kw = sub
- if fin is not None and (key, fin[0]) in _RESOLVE:
- return FamilyMatch(_RESOLVE[(key, fin[0])], f"{kw}+{fin[1]}")
- fam = _RESOLVE.get((key, None))
- if fam:
- return FamilyMatch(fam, kw)
- if fin is not None and fin[0] in _FINISH_ONLY:
- return FamilyMatch(_FINISH_ONLY[fin[0]], fin[1])
- return None
-
-
-def pbr_for(family: str) -> Pbr | None:
- """Factors for a fine family, or for one of the coarse ``plan.py`` families."""
- if family in MATERIALS:
- return MATERIALS[family]
- fine = COARSE_TO_FINE.get(family)
- return MATERIALS.get(fine) if fine else None
-
-
-__all__ = ["COARSE_TO_FINE", "FINISH_KEYWORDS", "MATERIALS", "SUBSTRATE_KEYWORDS", "FamilyMatch", "Pbr", "family_for", "pbr_for"]
diff --git a/harness/codeverse3d/languages/cadquery/__init__.py b/harness/codeverse3d/languages/cadquery/__init__.py
index f1d0b097..1f1f5095 100644
--- a/harness/codeverse3d/languages/cadquery/__init__.py
+++ b/harness/codeverse3d/languages/cadquery/__init__.py
@@ -12,8 +12,7 @@ from pathlib import Path
from codeverse3d.config import Settings, get_settings
from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
from codeverse3d.contracts.common import ENTRY_FILE, Language
-from codeverse3d.contracts.plan import PartPlan, Plan, StaticPlan
-from codeverse3d.conventions import PASCAL_RE, fmt3, to_pascal, to_snake
+from codeverse3d.conventions import PASCAL_RE
from codeverse3d.languages._ast_lint import (
BASE_FORBIDDEN_IMPORTS,
ImportCollector,
@@ -24,7 +23,6 @@ from codeverse3d.languages._ast_lint import (
)
from codeverse3d.languages._common import run_wrapper_build
from codeverse3d.languages.base import RuntimeLayout
-from codeverse3d.languages.blender import finish_for, instance_centers
from codeverse3d.proc import scrub_secrets
from codeverse3d.workspace import Workspace
@@ -205,97 +203,6 @@ def lint_cadquery_file(path: Path, *, target: str = "src/model.py") -> GateRepor
# ===================================================================== skeleton
-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 ({fmt3(p.bbox.center)}) extents ({fmt3(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)} — surface gap <= 2 mm, overlap <= 2 mm (check_connectivity)")
- if p.instances > 1:
- lines.append(f" Instances: {p.instances} ({p.symmetry}) — exported as {pascal}_0..{pascal}_{p.instances - 1}; the placeholder builds")
- lines.append(" one at the origin and places each copy with `loc` below (authoring each in world coordinates is fine too).")
- lines.append(' """')
- lines.append(" # TODO: replace the placeholder box (keep the name + bbox)")
- 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(({fmt3(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 ({fmt3(p.bbox.center)}) extents ({fmt3(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. Lowest point at z=0, footprint centred on Z (check_contract).
- * Overall bbox: center ({fmt3(ob.center)}) extents ({fmt3(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))`).
- * Imports: cadquery, math, random, numpy and the stdlib data helpers (the lint's list). 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). OCC refuses a fillet whose radius reaches
- the adjacent wall (the build's hint says < 0.45 x).
-
-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]
# ===================================================================== runtime
@@ -328,11 +235,6 @@ class CadQueryRuntime(RuntimeLayout):
"""The wrapper's own constants are the tessellation and the seed."""
return [self._python, str(WRAPPER), "--script", str(self.entry_file(ws)), "--out", str(ws.artifacts)]
- # ------------------------------------------------------------------ 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))
diff --git a/harness/codeverse3d/languages/glsl_shader/__init__.py b/harness/codeverse3d/languages/glsl_shader/__init__.py
index dd3d1b5b..50abb9e4 100644
--- a/harness/codeverse3d/languages/glsl_shader/__init__.py
+++ b/harness/codeverse3d/languages/glsl_shader/__init__.py
@@ -4,11 +4,9 @@ from __future__ import annotations
import re
from dataclasses import dataclass
-from pathlib import Path
from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
from codeverse3d.contracts.common import ENTRY_FILE, Language
-from codeverse3d.contracts.plan import GraphicsPlan, Plan
from codeverse3d.languages._common import line_of, missing_entry, ws_rel
from codeverse3d.languages._gl_common import (
GlslMessage,
@@ -252,66 +250,6 @@ def lint_workspace(ws: Workspace) -> GateReport:
# ===================================================================== skeleton
-COMMON_GLSL = """// src/common.glsl — pasted above shader.frag (and buffer_a.frag) by the harness; no #include.
-// Functions and constants only: no main(), no uniforms, no #version. What goes here is yours.
-#define PI 3.14159265359
-#define TAU 6.28318530718
-"""
-
-_SHADER_TEMPLATE = """// src/shader.frag — {title}
-// CONTRACT: the harness prepends `#version 330 core`, the uniforms (u_time u_resolution u_mouse u_frame
-// u_prev u_noise u_buffer_a; iTime / iResolution / iFrame / iMouse / iChannel0 / iChannel1 for Shadertoy ports)
-// and `out vec4 fragColor` — do not redeclare them.
-// Entry: void mainImage(out vec4 fragColor, in vec2 fragCoord) — fragCoord in pixels, origin BOTTOM-LEFT.
-// src/common.glsl is pasted above this file (it starts with PI and TAU only); what goes in it is yours.
-// MEASURED on the frames at t = 0, 1, 2.5, 4, 6 s (loop {duration:g} s): no NaN / Inf pixel (score cap 0);
-// no frame essentially black or blown out (cap 0.5); when motion is planned, consecutive frames must differ
-// (mean |delta| >= 0.002, else `static`, cap 0.5) and never jump (> 0.35 is `flicker`, cap 0.7); any lint
-// ERROR caps the score at 0.6. What the frames show is the plan's business, not this file's.
-//
-// PLAN — {summary}
-// Style: {style}
-{passes}
-{visuals}
-// Motion: {motion}
-
-void mainImage(out vec4 fragColor, in vec2 fragCoord) {{
- vec2 uv = fragCoord / u_resolution.xy; // 0..1: the coordinate u_prev / u_buffer_a are sampled at
- vec2 p = (fragCoord - 0.5 * u_resolution.xy) / u_resolution.y; // centred, aspect-correct, y up
- // PLACEHOLDER — a flat grey the static gate rejects: replace this write with the plan's passes
- fragColor = vec4(vec3(0.5), 1.0);
-}}
-"""
-
-
-def _comment_lines(prefix: str, items: list[str]) -> str:
- if not items:
- return f"// {prefix}: (none)"
- return "\n".join(f"// TODO {prefix} {i + 1}: {x}" for i, x in enumerate(items))
-
-
-def shader_source(plan: GraphicsPlan | None) -> str:
- title = plan.title if plan else "untitled shader"
- summary = plan.summary if plan else ""
- style = plan.style if plan else ""
- motion = plan.motion if plan else "animate with u_time"
- duration = plan.duration_s if plan else 8.0
- passes = [f"{p.name} ({p.kind}): {p.description}" for p in plan.passes] if plan else []
- visuals = list(plan.key_visuals) if plan else []
- return _SHADER_TEMPLATE.format(
- title=title, summary=summary, style=style, motion=motion, duration=duration,
- passes=_comment_lines("pass", passes), visuals=_comment_lines("key visual", visuals),
- )
-
-
-def write_skeleton(ws: Workspace, plan: Plan | None) -> list[Path]:
- gplan = plan if isinstance(plan, GraphicsPlan) else None
- ws.src.mkdir(parents=True, exist_ok=True)
- common = ws.src / "common.glsl"
- shader = ws.src / "shader.frag"
- common.write_text(COMMON_GLSL)
- shader.write_text(shader_source(gplan))
- return [common, shader]
# ===================================================================== runtime
@@ -323,9 +261,6 @@ class GlslShaderRuntime(RuntimeLayout):
def __init__(self, *, host: GlHost | None = None):
self._host = host
- # ------------------------------------------------------------------ skeleton / lint
- def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
- return write_skeleton(ws, plan)
def lint(self, ws: Workspace) -> GateReport:
return lint_workspace(ws)
diff --git a/harness/codeverse3d/languages/opengl_python/__init__.py b/harness/codeverse3d/languages/opengl_python/__init__.py
index cd8dd7dc..657cdb18 100644
--- a/harness/codeverse3d/languages/opengl_python/__init__.py
+++ b/harness/codeverse3d/languages/opengl_python/__init__.py
@@ -4,11 +4,9 @@ from __future__ import annotations
import ast
import re
-from pathlib import Path
from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
from codeverse3d.contracts.common import ENTRY_FILE, Language
-from codeverse3d.contracts.plan import GraphicsPlan, Plan
from codeverse3d.languages._ast_lint import (
BASE_FORBIDDEN_IMPORTS,
check_imports,
@@ -181,84 +179,6 @@ def lint_workspace(ws: Workspace) -> GateReport:
# ===================================================================== skeleton
-_TEMPLATE = '''"""src/program.py — {title}
-
-CONTRACT (the harness imports this module in a headless moderngl process; the full text is the
-language contract):
- def setup(ctx, width, height) -> state create programs / VAOs / textures / FBOs ONCE; return any object
- def render(ctx, state, t, frame, fbo) draw the frame at time t (seconds) into `fbo` (already bound + cleared)
-* `ctx` is a moderngl.Context (GL 3.3 core). Never create a context or window; never read the clock.
-* The final draw of every call goes into `fbo` (bind it and reset ctx.viewport first if you used your own FBOs).
-* Same t → same frame, whatever was rendered before; `frame` is a schedule index, not time. Seed randomness
- in setup. GLSL strings start with `#version 330 core`.
-Judged frames at t = 0, 1, 2.5, 4, 6 s (clipped to the {duration:g} s duration). Measured on them: largest
-frame-to-frame mean |Δ| below 0.002 → static (cap 0.5); above 0.35 → flicker (cap 0.7); NaN/Inf → cap 0;
-every frame black or blown → cap 0.5; mean edge density below 0.002 → reported as a near-flat gradient.
-
-PLAN — {summary}
-Style: {style}
-{passes}
-{visuals}
-Motion: {motion}
-"""
-import moderngl
-import numpy as np
-
-# This stub only proves the interface: one full-screen pass whose output depends on t.
-STUB_VERT = """#version 330 core
-in vec2 in_pos;
-out vec2 v_uv;
-void main() {{ v_uv = in_pos * 0.5 + 0.5; gl_Position = vec4(in_pos, 0.0, 1.0); }}
-"""
-STUB_FRAG = """#version 330 core
-uniform float u_time;
-in vec2 v_uv;
-out vec4 fragColor;
-void main() {{ fragColor = vec4(vec3(0.5 + 0.5 * sin(6.2832 * (v_uv.x - 0.05 * u_time))), 1.0); }}
-"""
-
-
-def setup(ctx: moderngl.Context, width: int, height: int):
- prog = ctx.program(vertex_shader=STUB_VERT, fragment_shader=STUB_FRAG)
- quad = ctx.buffer(np.array([-1, -1, 1, -1, -1, 1, 1, 1], dtype="f4").tobytes())
- vao = ctx.vertex_array(prog, [(quad, "2f", "in_pos")])
- # TODO build the plan's passes here (programs, buffers, textures, your own FBOs)
- return {{"prog": prog, "vao": vao, "size": (width, height)}}
-
-
-def render(ctx: moderngl.Context, state, t: float, frame: int, fbo: moderngl.Framebuffer) -> None:
- fbo.use()
- ctx.disable(moderngl.DEPTH_TEST)
- ctx.viewport = (0, 0, *state["size"])
- state["prog"]["u_time"].value = t
- state["vao"].render(mode=moderngl.TRIANGLE_STRIP)
- # TODO the plan's passes; the final draw goes into `fbo` (bind it and reset ctx.viewport first)
-'''
-
-
-def _comment_lines(prefix: str, items: list[str]) -> str:
- if not items:
- return f"{prefix}: (none)"
- return "\n".join(f" TODO {prefix} {i + 1}: {x}" for i, x in enumerate(items))
-
-
-def program_source(plan: GraphicsPlan | None) -> str:
- title = plan.title if plan else "untitled program"
- passes = [f"{p.name} ({p.kind}): {p.description}" for p in plan.passes] if plan else []
- visuals = list(plan.key_visuals) if plan else []
- return _TEMPLATE.format(
- title=title, summary=plan.summary if plan else "", style=plan.style if plan else "",
- motion=plan.motion if plan else "animate with t", duration=plan.duration_s if plan else 8.0,
- passes=_comment_lines("pass", passes), visuals=_comment_lines("key visual", visuals),
- )
-
-
-def write_skeleton(ws: Workspace, plan: Plan | None) -> list[Path]:
- gplan = plan if isinstance(plan, GraphicsPlan) else None
- ws.src.mkdir(parents=True, exist_ok=True)
- p = ws.src / "program.py"
- p.write_text(program_source(gplan))
- return [p]
# ===================================================================== runtime
@@ -269,9 +189,6 @@ class OpenGLPythonRuntime(RuntimeLayout):
def __init__(self, *, host: GlHost | None = None):
self._host = host
- # ------------------------------------------------------------------ skeleton / lint
- def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
- return write_skeleton(ws, plan)
def lint(self, ws: Workspace) -> GateReport:
return lint_workspace(ws)
diff --git a/harness/codeverse3d/languages/scene_blender/__init__.py b/harness/codeverse3d/languages/scene_blender/__init__.py
index 32c8c8ca..b3f03619 100644
--- a/harness/codeverse3d/languages/scene_blender/__init__.py
+++ b/harness/codeverse3d/languages/scene_blender/__init__.py
@@ -28,7 +28,7 @@ from codeverse3d.contracts.artifacts import (
Severity,
)
from codeverse3d.contracts.common import ENTRY_FILE, Language
-from codeverse3d.contracts.plan import AssetPlan, CameraPlan, Plan, ScenePlan, ZonePlan
+from codeverse3d.contracts.plan import AssetPlan, CameraPlan, Plan
from codeverse3d.conventions import (
SCENE_TIMES,
ZONE_ROOT_KEY,
@@ -53,14 +53,11 @@ from codeverse3d.languages._common import (
target_line,
ws_rel,
)
-from codeverse3d.languages.base import AssembleResult, scene_files_for
from codeverse3d.languages.blender import (
- BlenderNotFoundError,
BpyCollector,
blender_binary,
blender_env,
call_traps,
- finish_for,
source_traps,
store_traps,
use_nodes_trap,
@@ -82,8 +79,6 @@ FPS = 30
# ===================================================================== layout
#: what a whole-scene session edits
SCENE_FILES: tuple[str, ...] = (ENTRY_REL, "src/env.py")
-#: refine targets that are the environment's, whatever the plan calls its zones
-ENV_WORDS = frozenset({"env", "environment", "lighting", "sky", "fog", "ground", "water", "light", "world", "sun"})
def zone_file(name: str) -> str:
@@ -95,16 +90,6 @@ def asset_file(asset: AssetPlan) -> str:
return f"public/assets/{snake}.glb" if asset.kind == "blender_glb" else f"src/assets/{snake}.py"
-def module_files(ws: Workspace, sub: str) -> list[Path]:
- d = ws.src / sub
- return sorted(p for p in d.glob("*.py") if not p.name.startswith("_")) if d.is_dir() else []
-
-
-def hero_files(ws: Workspace) -> list[Path]:
- d = ws.public / "assets"
- return sorted(d.glob("*.glb")) if d.is_dir() else []
-
-
# ===================================================================== lint
ALLOWED_IMPORTS = frozenset({
"bpy", "bmesh", "mathutils", "math", "random", "numpy", "itertools", "functools", "collections", "typing",
@@ -367,112 +352,10 @@ def lint(ws: Workspace) -> GateReport:
ENV_FILE = "src/env.py"
-#: the env check's data entry (deleted after use): only build_env runs
-ENV_CHECK_REL = "src/_c3d_env_check.py"
-
-
_TB_FRAME_RE = re.compile(r'File "(?P<file>[^"]+)", line (?P<line>\d+)')
-def env_frame(traceback_text: str) -> str:
- """``src/env.py:N`` of the deepest traceback frame in the env module (with its source line), or ``""``."""
- lines = traceback_text.splitlines()
- found = ""
- for i, text in enumerate(lines):
- m = _TB_FRAME_RE.search(text)
- if m is None or not m.group("file").replace("\\", "/").endswith("/" + ENV_FILE):
- continue
- code = lines[i + 1].strip() if i + 1 < len(lines) and not _TB_FRAME_RE.search(lines[i + 1]) else ""
- found = f"{ENV_FILE}:{m.group('line')}" + (f" `{code[:160]}`" if code else "")
- return found
-
-
-def _put(path: Path, text: str, written: list[Path]) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(text)
- written.append(path)
-
-
# ===================================================================== skeleton
-def _v(v: Sequence[float], *, extents: bool = False) -> tuple[float, float, float]:
- return tuple(round(c, 3) for c in to_authoring_frame(v, LANGUAGE.value, extents=extents))
-
-
-def _env_source(plan: ScenePlan) -> str:
- """``src/env.py`` as an interface stub: the plan's data, the two exports the wrapper calls and a
- placeholder ground plate. No world, lamp or atmosphere, so it fails the probe until the author writes them."""
- from codeverse3d.languages.scene_threejs import PLACEHOLDER_GROUND_SPANS, sun_from_plan
-
- c, e = _v(plan.bounds.center), _v(plan.bounds.extents, extents=True)
- span = max(e[0], e[1], 1.0)
- ground = round(span * PLACEHOLDER_GROUND_SPANS, 1)
- interior = "True" if plan.interior else "False"
- glazed = bool(getattr(plan, "glazed", False))
- az, el = sun_from_plan(plan)
- az_line = (f"SUN_AZIMUTH_DEG = {az:g} # the plan's light: compass 0 = +X, 90 = +Y (the sky and the lamp share it; zones may import it)"
- if az is not None else
- "SUN_AZIMUTH_DEG = None # the plan states no azimuth: set the brief's (compass 0 = +X, 90 = +Y; zones may import it)")
- el_line = (f"SUN_ELEVATION_DEG = {el:g}" if el is not None else "SUN_ELEVATION_DEG = None # the plan states none: set the brief's")
- return f'''"""src/env.py — the environment: the ground every zone seats on, the light, the sky / backdrop, the
-atmosphere{" and the enclosure" if plan.interior else ""}.
-
-ENV PLAN: {plan.environment.strip()}
-setting: {plan.setting.strip()} mood: {plan.mood.strip()}
-Frame: Z up, -Y front, metres. BOUNDS below are the plan's, in this frame: the extent of the PLANNED
-content and the cameras' subject, not the edge of the world — land, backdrop and scenery continue beyond
-it as the brief implies.
-CONTRACT (the wrapper calls exactly these two):
- height_at(x, y) -> z: the ONE ground function — the ground mesh samples it and every zone seats on it
- (measured: scene_placement floating > 0.05 m outdoors / 0.02 m indoors, sunken > 0.10 m); the plan's
- cameras expect the ground near their look_at at the height the plan states, and each eye above it
- (camera_underground, cap 0.50).
- build_env(ctx) -> dict: builds the world, the lamps, the ground and the atmosphere the plan describes into
- ctx.collection and returns what zones may share (materials, water level, sun direction ...) — ctx.env to them.
-MEASURED: a world exists and an atmosphere exists — a world Volume or a bounded fog volume (no_fog, ERROR) —
- with 1 / density >= the plan span / 1.5 (fog_short); the judged frames sit in the exposure band
- (scene_frames: dark_frame / blown_frame / flat_frame); whatever the zones seat on is named Ground... /
- Terrain... (the census finds the ground by name and shape); backdrop geometry is named Sky...; no world
- edge in any authored frame (judged; the census: standing geometry past 1.25 x the bounds' half-extent).
-PLACEHOLDER below: ONE level plate named Ground past the plan span, so the census has a surface — and NO
- world, NO lamp, NO atmosphere: as written this module fails the probe and renders black until build_env
- builds the brief's. The landform, the sky, the light and the atmosphere are yours. Keep build_env and height_at.
-"""
-import bmesh
-import bpy
-
-BOUNDS = {{"center": ({fmt3(c)}), "extents": ({fmt3(e)})}}
-INTERIOR = {interior} # the plan's: an interior needs the enclosure the brief describes (openings, materials as
- # named; it reads black without openings or practical lights)
-GLAZED = {glazed} # the plan says the enclosure is glazed; its construction is the brief's
-GROUND_SIZE = {ground} # the placeholder plate's side (m): 3 x the plan span, past the reach the fog gate measures
-{az_line}
-{el_line}
-SEED = 0
-
-
-def height_at(x, y):
- """z of the ground at (x, y): the one function every zone seats on and the ground mesh follows. PLACEHOLDER: level."""
- return 0.0
-
-
-def build_env(ctx):
- # PLACEHOLDER ground: a level plate following height_at — REPLACE with the brief's land (named Ground... / Terrain...)
- ground_mat = bpy.data.materials.new("GroundMat")
- bsdf = ground_mat.node_tree.nodes["Principled BSDF"]
- bsdf.inputs["Base Color"].default_value = (0.159, 0.144, 0.117, 1.0)
- bsdf.inputs["Roughness"].default_value = 0.95
- bm = bmesh.new()
- bmesh.ops.create_grid(bm, x_segments=32, y_segments=32, size=GROUND_SIZE / 2)
- for v in bm.verts:
- v.co.z = height_at(v.co.x, v.co.y)
- me = bpy.data.meshes.new("Ground")
- bm.to_mesh(me)
- bm.free()
- me.materials.append(ground_mat)
- ctx.collection.objects.link(bpy.data.objects.new("Ground", me))
- # NO world, lamp or atmosphere here: the brief's go in this function (the docstring says what is measured)
- return {{"ground_material": ground_mat}}
-'''
_ASSET_BODY = """import bmesh
@@ -500,57 +383,8 @@ def build_{snake}(ctx, variant=0):
"""
-def _asset_source(a: AssetPlan) -> str:
- snake, pascal = to_snake(a.name), to_pascal(a.name)
- w, h, d = (max(0.05, float(v)) for v in a.approx_size_m)
- rgb, rough, metal = finish_for(a.description)
- return f'''"""src/assets/{snake}.py — asset "{pascal}": {a.description.strip()}
-
-approx size {w:g} x {d:g} x {h:g} m (x = width, y = depth, z = height); expected instances: ~{a.instances_hint}
-CONTRACT: build_{snake}(ctx, variant=0) -> bpy.types.Collection — link every part into ctx.collection
- (named '{pascal}'), built ONCE at the origin with its base on z = 0, front facing -Y. Zones place
- collection instances of it (ctx.assets['{snake}']); link it nowhere else. It must read as the plan
- describes it at the judge's camera distance (judged) and measure about the size above (the asset check);
- parts, materials and construction are yours.
-"""
-{_ASSET_BODY.format(snake=snake, pascal=pascal, rgb=fmt3(rgb), rough=rough, metal=metal,
- w=f"{w:g}", d=f"{d:g}", h=f"{h:g}", h2=f"{h / 2:g}")}'''
-
-
-def _zone_source(z: ZonePlan, assets: dict[str, AssetPlan]) -> str:
- snake, pascal = to_snake(z.name), to_pascal(z.name)
- c, e = _v(z.bbox.center), _v(z.bbox.extents, extents=True)
- todo = []
- for name in z.contents:
- a = assets.get(to_snake(name))
- if a is None:
- todo.append(f" - {name}: not an asset of the plan — built here")
- elif a.kind == "blender_glb":
- todo.append(f" - {a.name}: ctx.assets['{to_snake(a.name)}'] — the hero GLB public/assets/{to_snake(a.name)}.glb imported by the harness")
- else:
- todo.append(f" - {a.name}: ctx.assets['{to_snake(a.name)}'] — built by src/assets/{to_snake(a.name)}.py; ~{a.instances_hint} planned")
- todo_block = "\n".join(todo) if todo else " (the plan lists no contents)"
- return f'''"""src/zones/{snake}.py — zone "{pascal}": {z.description.strip()}
-
-PLAN bbox (Z up, -Y front, metres): centre ({fmt3(c)}) extents ({fmt3(e)}).
-CONTRACT: build(ctx) -> bpy.types.Collection — ctx.collection is this zone's (named '{pascal}', active): link
- everything into it and return it. Every PLACED thing is ONE root object in it, named <Name>_<i> (object
- names are global in Blender: never reuse one another zone uses). Seat things on ctx.height_at(x, y)
- (measured: scene_placement floating > 0.05 m outdoors / 0.02 m indoors, sunken > 0.10 m). The planned
- contents are measured against the plan bounds and this bbox (scene_placement: present, at the plan's size,
- not outside the bounds); scenery may continue past the bbox as the brief implies.
- Assets: ctx.assets['<snake>'] is a Collection — place collection-instance Empties of it (instance_type
- 'COLLECTION', seated on ctx.height_at). Animation: keyframes or simple drivers (the build samples frames 1 and
- 46 = t 0 / 1.5 s; motion between them is measured).
-TODO — this zone's planned contents, none placed yet:
-{todo_block}
-"""
-
-
-def build(ctx):
- # TODO: build the contents listed above (seat everything with ctx.height_at)
- return ctx.collection
-'''
+def _v(v: Sequence[float], *, extents: bool = False) -> tuple[float, float, float]:
+ return tuple(round(c, 3) for c in to_authoring_frame(v, LANGUAGE.value, extents=extents))
def _cam(c: CameraPlan) -> str:
@@ -582,27 +416,6 @@ CAMERAS = [
'''
-def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:
- """Starter files for a scene plan; none without one."""
- if plan is None:
- return []
- if not isinstance(plan, ScenePlan):
- raise TypeError(f"scene_blender needs a ScenePlan, got {type(plan).__name__}")
- written: list[Path] = []
- _put(ws.root / ENV_FILE, _env_source(plan), written)
- assets = {to_snake(a.name): a for a in plan.assets}
- for a in plan.assets:
- if a.kind != "blender_glb":
- _put(ws.root / asset_file(a), _asset_source(a), written)
- for z in plan.zones:
- _put(ws.root / zone_file(z.name), _zone_source(z, assets), written)
- _put(ws.root / ENTRY_REL, render_scene_py([to_snake(z.name) for z in plan.zones],
- [to_snake(a.name) for a in plan.assets if a.kind != "blender_glb"], [],
- list(plan.cameras[:6]), title=plan.title, summary=plan.summary), written)
- (ws.public / "assets").mkdir(parents=True, exist_ok=True)
- return written
-
-
# ===================================================================== build
WRAPPER = Path(__file__).resolve().parent.parent / "wrappers" / "run_bpy_scene.py"
#: what a build (re)writes under ``artifacts/``; wiped first
@@ -637,55 +450,10 @@ class SceneBlenderRuntime:
def expected_files(self, plan: Plan | None) -> list[str]:
return list(SCENE_FILES)
- def files_for(self, plan: Plan | None, target: str) -> list[str]:
- return scene_files_for(plan, target, zone_file=zone_file, asset_file=asset_file, entry=ENTRY_REL, env_file="src/env.py",
- env_words=ENV_WORDS)
-
- 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 lib_interface(self, ws: Workspace) -> str:
- return ""
-
- def check_env(self, ws: Workspace) -> str:
- """``""`` when ``src/env.py`` lints clean, runs ``build_env`` alone and lights what it builds;
- else the first failure, quoted. A Blender that cannot run gives ``""``."""
- from codeverse3d.spatial.probes import unlit
-
- env = ws.root / ENV_FILE
- if not env.is_file():
- return f"{ENV_FILE} does not exist"
- own = [f for f in lint_scene_source(env.read_text(errors="replace"), target=ENV_FILE, role="env")
- if f.severity == Severity.ERROR]
- if own:
- return "\n".join(f"{f.target}: {f.message}" + (f" ({f.fix_hint})" if f.fix_hint else "") for f in own[:6])
- entry = ws.root / ENV_CHECK_REL
- entry.write_text(render_scene_py([], [], [], []))
- try:
- run = self.run_wrapper(ws, ws.artifacts / "env_check", zones={}, blend=False, entry=ENV_CHECK_REL)
- except BlenderNotFoundError as e:
- log.warning("env check could not run: %s", e)
- return ""
- finally:
- entry.unlink(missing_ok=True)
- raised = [e for e in run.report.get("errors") or [] if e.get("stage") == "env"]
- if raised:
- e = raised[0]
- at = f"{e.get('error_file') or ENV_FILE}:{e.get('error_line')}" if e.get("error_line") else ENV_FILE
- if (e.get("error_file") or ENV_FILE) != ENV_FILE and (own_at := env_frame(str(e.get("traceback") or ""))):
- # the raise surfaced in a helper the env called: lead with the env's own call line
- at = f"{own_at} (raised in {at})"
- return f"{at}: build_env raised {e.get('error_type')}: {str(e.get('error_message'))[:600]}"
- if not run.result.ok:
- if run.result.harness_failure:
- return ""
- return f"{ENV_FILE}: the env-only build failed: {run.result.error_type}: {run.result.error_message}"[:900]
- facts = run.facts
- dark = unlit({"totals": {"lights": int(facts.get("lights") or 0)}, "background": facts.get("background")}, offline=True)
- return f"{ENV_FILE}: {dark.message}" if dark is not None else ""
# ------------------------------------------------------------------ the Blender process
def run_wrapper(self, ws: Workspace, out_dir: Path, *, zones: dict[str, str] | None = None, blend: bool = True,
@@ -782,8 +550,6 @@ class SceneBlenderRuntime:
return probe_result(GateReport.of(PROBE_GATE, [finding]), {})
return probe_result(gate, census)
- def assemble(self, ws: Workspace, plan: ScenePlan) -> AssembleResult:
- return assemble(self, ws, plan)
def render_scene(self, ws: Workspace, out_dir: Path, *, cameras: list[CameraPlan] | None = None, orbit: bool = True,
times: Sequence[float] = SCENE_TIMES, width: int = 1024, height: int = 576, sheet: bool = True) -> RenderSet:
@@ -821,46 +587,6 @@ def stage_findings(report: dict[str, Any]) -> list[GateFinding]:
# ===================================================================== assemble
-_ASSEMBLE_OUT = "assemble_probe"
-
-
-def assemble(runtime: SceneBlenderRuntime, ws: Workspace, plan: ScenePlan, *, timeout_s: float | None = None) -> AssembleResult:
- zones = [p.stem for p in module_files(ws, "zones")]
- if not zones:
- raise FileNotFoundError(f"no zone modules under {ws.src / 'zones'}")
- assets = [p.stem for p in module_files(ws, "assets")]
- heroes = [p.stem for p in hero_files(ws)]
- cams = list(plan.cameras[:6])
- warnings: list[str] = []
- env_ok = (ws.src / "env.py").is_file()
- if not env_ok:
- warnings.append("src/env.py missing: scene assembled without env (flat ground at z = 0, no world or lamps)")
- healthy, failed = list(zones), {}
- census: dict[str, Any] = {}
- out = ws.root / ENTRY_REL
- # the probe run's entry lists every asset and hero; zones come from --zones
- out.parent.mkdir(parents=True, exist_ok=True)
- out.write_text(render_scene_py([], assets, heroes, cams))
- run = runtime.run_wrapper(ws, ws.artifacts / _ASSEMBLE_OUT, zones={z: to_pascal(z) for z in zones}, blend=False,
- timeout_s=timeout_s)
- if run.result.ok or run.report.get("zones_ok") is not None:
- healthy = [z for z in zones if z in set(run.report.get("zones_ok") or [])]
- failed = {z: str(m) for z, m in (run.report.get("zones_failed") or {}).items()}
- else:
- warnings.append(f"assembler probe did not run: {run.result.error_type}: {run.result.error_message}"[:300])
- for e in run.report.get("errors") or []:
- if e.get("stage") == "env":
- env_ok = False
- warnings.append(f"env.py failed in probe: {e.get('error_type')}: {e.get('error_message')}"[:300])
- census = {k: run.facts[k] for k in ("lights", "fog", "background", "unique_tris", "instanced_tris") if k in run.facts}
- if not healthy:
- warnings.append("no zone module survived probing; scene.py assembled with zero zones")
- out.write_text(render_scene_py(healthy, assets, heroes, cams, title=plan.title,
- summary=plan.summary))
- result = AssembleResult(scene_path=str(out), zones_included=healthy, zones_failed=failed, env_ok=env_ok,
- warnings=warnings, census=census)
- ws.write_json(ws.artifacts / "assemble.json", result)
- return result
# ===================================================================== helpers
diff --git a/harness/codeverse3d/languages/scene_threejs/__init__.py b/harness/codeverse3d/languages/scene_threejs/__init__.py
index e9205b3d..a71c2b30 100644
--- a/harness/codeverse3d/languages/scene_threejs/__init__.py
+++ b/harness/codeverse3d/languages/scene_threejs/__init__.py
@@ -6,9 +6,7 @@ import re
import time
from collections.abc import Sequence
from pathlib import Path
-from typing import TYPE_CHECKING, Any
-
-from pydantic import BaseModel, Field
+from typing import TYPE_CHECKING
from codeverse3d.contracts.artifacts import (
BuildResult,
@@ -19,12 +17,9 @@ from codeverse3d.contracts.artifacts import (
Severity,
)
from codeverse3d.contracts.common import ENTRY_FILE, Language
-from codeverse3d.contracts.plan import AssetPlan, CameraPlan, Plan, ScenePlan, ZonePlan
+from codeverse3d.contracts.plan import AssetPlan, CameraPlan, Plan
from codeverse3d.conventions import (
- OBJECT_VIEWS_QUICK,
SCENE_TIMES,
- ZONE_ROOT_KEY,
- to_pascal,
to_snake,
)
from codeverse3d.languages._common import line_of, missing_entry, target_file, target_line, ws_rel
@@ -40,7 +35,6 @@ from codeverse3d.languages._js_lint import (
node_check_syntax,
strip_js,
)
-from codeverse3d.languages.base import AssembleResult, scene_files_for
from codeverse3d.workspace import Workspace
if TYPE_CHECKING:
@@ -163,130 +157,17 @@ def _write(path: Path, text: str, written: list[Path]) -> None:
written.append(path)
-def _write_lib(ws: Workspace, written: list[Path]) -> None:
+def write_lib(ws: Workspace) -> list[Path]:
+ """Ship the effect library into ``ws.src/lib`` (``3dcode init``); returns the written paths."""
+ written: list[Path] = []
for src in lib_files():
_write(ws.src / "lib" / src.name, src.read_text(), written)
-
-
-def write_example(ws: Workspace) -> list[Path]:
- """Copy the full example scene into ws.src (overwrites); raises when the starter tree is missing
- (an rglob over an absent directory would silently write nothing)."""
- if not STARTER_DIR.is_dir():
- raise FileNotFoundError(
- f"scene_threejs starter tree missing: {STARTER_DIR} — this install has no package data "
- f"(a non-editable install needs [tool.setuptools.package-data] to ship languages/**/starter/**/*)")
- 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)
- if not written:
- raise FileNotFoundError(f"scene_threejs starter tree at {STARTER_DIR} contains no .js files")
return written
-#: the stub plate's side as a multiple of the plan span
-PLACEHOLDER_GROUND_SPANS = 3.0
-
-_AZIMUTH_RE = re.compile(r"azimuth[^0-9\-]{0,12}(-?\d+(?:\.\d+)?)", re.I)
-_ELEVATION_RE = re.compile(r"elevation[^0-9\-]{0,12}(-?\d+(?:\.\d+)?)", re.I)
-#: the overview rig's guess when a scene states no sun azimuth
-SUN_AZIMUTH_GUESS_DEG = 45.0
-
-
-def sun_from_plan(plan: ScenePlan) -> tuple[float | None, float | None]:
- """The sun azimuth and elevation (degrees) the plan's ``environment`` paragraph states, ``None`` for each it does not."""
- text = plan.environment
- az = _AZIMUTH_RE.search(text)
- el = _ELEVATION_RE.search(text)
- return (float(az.group(1)) if az else None, float(el.group(1)) if el else None)
-
-
-_ENV_STUB = """// src/env.js — the environment: the ground every zone seats on, the light, the sky / backdrop, the atmosphere.
-// export function heightAt(x, z) → ground height (m): the ONE function every zone seats on.
-// export function buildEnv(ctx) → {{ update?(t, dt), ...whatever zones may share as ctx.env (sunDir, materials, a water level …) }}
-// export const SUN_AZIMUTH_DEG → where the light comes from (0 = +X, 90 = +Z); the assembler reads it (regex) to fit cameras on the lit side.
-//
-// PLACEHOLDER: nothing below decides the brief's world. It ships ONE thing — a level plate named Ground reaching past
-// the plan span, so the census has a surface to seat on and to measure the fog against — and NO light, NO sky and NO
-// atmosphere: as written this module FAILS the gates (no_fog / no_background on the census, dark_frame on every frame)
-// until buildEnv builds the brief's. What is measured:
-// • every zone seats on heightAt, so the ground mesh and heightAt must agree (scene_placement: floating > 0.05 m
-// outdoors / 0.02 m indoors, sunken > 0.10 m); the plan's cameras expect the ground near their look_at at the
-// height the plan states, and each eye above heightAt at its own (x, z) (camera_underground, cap 0.50).
-// • scene.fog and scene.background set (no_fog / no_background, ERROR); fog far ≥ 2 × the plan span or
-// 1/density ≥ span / 1.5 (fog_short); the land reaches past the fog from every authored camera; no world edge
-// in any authored frame (judged world_edge_visible; the census: standing geometry past 1.25 × the half-extent).
-// • scene.environment is an environment texture (PBR metals and glass render near black without one).
-// • the judged frames sit in the exposure band (scene_frames: dark_frame / blown_frame / flat_frame).
-// • the ground mesh is named 'Ground…' / 'Terrain…' (the census classifies the ground by name; the placement gate
-// seats on it); backdrop geometry is named 'Sky…' (it then never inflates the content bounds).
-// Raw three.js is the baseline. src/lib is an OPTIONAL toolbox the effects catalog lists: lib/terrain.js ground()
-// displaces and textures a ground from a height field, lib/sky.js makeSky, lib/environment.js sunRig / roomShell —
-// use a call when it fits the brief, write your own when it does not.
-import * as THREE from 'three';
-
-export const SUN_AZIMUTH_DEG = {azimuth}; // 0 = +X, 90 = +Z — {azimuth_note}
-export const SUN_ELEVATION_DEG = {elevation}; // {elevation_note}
-export const GROUND_SIZE = {ground}; // the placeholder plate's side (m): 3 × the plan span, past the 2 × the fog gate measures
-// An INTERIOR plan (filled from the plan): the room box the plan gives, {{ center, extents, openings, glazed? }}. The
-// enclosure the brief describes — walls, openings, ceiling, materials as named — is yours; lib/environment.js
-// roomShell(INTERIOR) is one way to build it. An interior reads black without openings or practical lights (dark_frame).
-export const INTERIOR = {interior};
-
-/** Ground height at (x, z) — every placement seats on this. PLACEHOLDER: level; the brief's landform is yours. */
-export function heightAt(x, z) {{
- return 0;
-}}
-
-export function buildEnv(ctx) {{
- const {{ scene }} = ctx;
- // PLACEHOLDER ground: a level plate following heightAt — REPLACE with the brief's land (named Ground… / Terrain…)
- const ground = new THREE.Mesh(new THREE.PlaneGeometry(GROUND_SIZE, GROUND_SIZE, 1, 1),
- new THREE.MeshStandardMaterial({{ color: 0x6f6a60, roughness: 0.95 }}));
- ground.rotation.x = -Math.PI / 2;
- ground.receiveShadow = true;
- ground.name = 'Ground';
- scene.add(ground);
- // NO light, sky, fog or scene.environment here: the brief's go in this function (see the header for what is measured)
- return {{ ground, update(t, dt) {{}} }};
-}}
-"""
-
-
-def _env_for_plan(plan: ScenePlan) -> str:
- """``src/env.js`` as an interface stub under the plan's data: plate side, stated sun angles, the
- room box for an interior; no light, sky or atmosphere."""
- ex = plan.bounds.extents
- span = max(ex[0], ex[2], 1.0)
- az, el = sun_from_plan(plan)
- interior = "null"
- if plan.interior:
- c = [round(float(v), 2) for v in plan.bounds.center]
- e = [round(float(v), 2) for v in ex]
- glazed = ", glazed: true" if plan.glazed else ""
- interior = f"{{ center: {c}, extents: {e}, openings: []{glazed} }}"
- 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 — the extent\n"
- "// of the PLANNED content and the cameras' subject, not the edge of the world: land, backdrop and scenery\n"
- "// continue beyond it as the brief implies.\n"
- "// Keep the buildEnv(ctx), heightAt(x, z) and SUN_AZIMUTH_DEG exports; everything else is yours to write for the plan above.\n"
- )
- body = _ENV_STUB.format(
- azimuth=f"{az:g}" if az is not None else f"{SUN_AZIMUTH_GUESS_DEG:g}",
- azimuth_note="the plan's light" if az is not None else "the plan states none: this is only the rig's guess — set the brief's",
- elevation=f"{el:g}" if el is not None else "null",
- elevation_note="the plan's" if el is not None else "the plan states none: set the brief's (a number)",
- ground=int(span * PLACEHOLDER_GROUND_SPANS), interior=interior)
- return header + body
-
-
# ===================================================================== layout
#: what a whole-scene session edits: the entry and the environment
SCENE_FILES: tuple[str, ...] = ("src/scene.js", "src/env.js")
-#: refine targets that are the environment's, whatever the plan calls its zones
-ENV_WORDS = frozenset({"env", "environment", "lighting", "sky", "fog", "ground", "water", "light"})
def zone_file(name: str) -> str:
@@ -298,246 +179,10 @@ def asset_file(asset: AssetPlan) -> str:
return f"src/assets/{snake}.js" if asset.kind == "threejs" else f"public/assets/{snake}.glb"
-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.
-// It must read as the plan describes it at the judge's camera distance (judged) and measure about the size
-// above (scene_placement: scale). Parts, materials and construction are yours.
-// OPTIONAL: export {snake}Parts(THREE) → [{{ geometry, material, castShadow }}] if a zone wants to instance
-// repeats of it (the triangle budget is measured on the census; THREE.InstancedMesh is one way to afford them).
-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 the real thing (a single box fails the asset check).
- 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, todo = [], []
- for name in z.contents:
- a = assets.get(to_snake(name))
- if a is None:
- todo.append(f"// - {name}: not an asset of the plan — built here")
- elif a.kind == "threejs":
- asn, asp = to_snake(a.name), to_pascal(a.name)
- imports.append(f"import {{ build{asp} }} from '../assets/{asn}.js';")
- todo.append(f"// - {a.name}: build{asp}(THREE) → a Group with its origin at the base; ~{a.instances_hint} planned")
- else:
- asn = to_snake(a.name)
- todo.append(f"// - {a.name}: ctx.assets.{asn} — the hero GLB public/assets/{asn}.glb preloaded by scene.js; place .clone()s")
- imp = ("\n".join(imports) + "\n") if imports else ""
- todo_block = "\n".join(todo) if todo else "// (the plan lists no contents)"
- 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.
-// CONTRACT: export function build(ctx) → THREE.Group named '{pascal}'. ctx = {{ THREE, scene, renderer, loaders, env, heightAt, assets }}
-// • seat things on ctx.heightAt(x, z) (measured: scene_placement floating > 0.05 m outdoors / 0.02 m indoors, sunken > 0.10 m)
-// • the planned contents are measured against the plan bounds and this bbox (scene_placement: present, at the plan's
-// size, not outside the bounds); scenery may continue past the bbox as the brief implies
-// • animation → zone.userData.update = (t, dt) => {{ ... }} (scene.js fans update() out; motion between t = 0 and 1.5 s is measured)
-// • the triangle budget is measured on the census; THREE.InstancedMesh is one way to afford repeats
-// TODO — this zone's planned contents, none placed yet:
-{todo_block}
-import * as THREE from 'three';
-{imp}
-export function build(ctx) {{
- const zone = new THREE.Group();
- zone.name = '{pascal}';
- // TODO: build the contents listed above (seat everything with ctx.heightAt)
- zone.userData.update = (t, dt) => {{}}; // the animation hook; delete it if the zone is still
- return zone;
-}}
-'''
-
-
-def _scene_for_plan(plan: ScenePlan) -> str:
- """The skeleton's entry is the assembled shape under the starter's contract header."""
- header = (STARTER_DIR / "scene.js").read_text().split("import * as THREE")[0]
- glbs = [to_snake(a.name) for a in plan.assets if a.kind == "blender_glb"]
- body = render_scene_js([to_snake(z.name) for z in plan.zones], list(plan.cameras[:6]), glbs, env_ok=True)
- return (f"{header}// PLAN: {plan.title} — {plan.summary.strip()}\n"
- f"// setting: {plan.setting.strip()} animation: {'; '.join(plan.animation) or '-'}\n" + body)
-
-
-def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:
- if plan is None or not isinstance(plan, ScenePlan):
- return write_example(ws)
- written: list[Path] = []
- _write_lib(ws, 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.root / asset_file(a), _asset_stub(a), written)
- for z in plan.zones:
- _write(ws.root / zone_file(z.name), _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
-
-
# ===================================================================== assemble
-PROBE_REL = "src/_c3v_assemble_probe.js"
-_PREFIX = "[3dcode-assemble]"
-
-
-class ZoneProbe(BaseModel):
- name: str
- file: str
- ok: bool
- error: str = ""
-
-
-class ZoneProbeReport(BaseModel):
-
- probes: dict[str, ZoneProbe] = Field(default_factory=dict)
- census: dict[str, Any] = Field(default_factory=dict)
- other_errors: list[str] = Field(default_factory=list)
-
-
-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 []
-
-
-#: How a Blender-built asset is preloaded in every assembled entry point. The loaded root is
-#: NAMED after its asset (``to_pascal`` of the file key): a glTF root arrives as "Scene", which
-#: name-based checks cannot see.
-def _glb_preload_js(glbs: list[str], *, target: str, on_error: str, indent: str = " ") -> str:
- """The `assetFiles` literal + preload loop, or "" when the plan has no GLB asset; ``on_error`` is the JS catch statement."""
- if not glbs:
- return ""
- files = ", ".join(f"{g}: {{ name: '{to_pascal(g)}', url: '/assets/{g}.glb' }}" for g in glbs)
- body = [
- f"const assetFiles = {{ {files} }};",
- "for (const [key, a] of Object.entries(assetFiles)) {",
- " try {",
- " const gltf = await loaders.gltf.loadAsync(a.url);",
- " const root = gltf.scene;",
- " root.animations = gltf.animations || []; // a keyframed Blender part is a clip; .clone() keeps it",
- " root.name = a.name; // a glTF root is called 'Scene' until someone names it",
- # GLTFLoader leaves castShadow / receiveShadow false; set them like procedural assets
- " root.traverse((o) => { if (o.isMesh) o.castShadow = o.receiveShadow = true; });",
- f" {target}[key] = root;",
- " } catch (e) { " + on_error + " }",
- "}",
- ]
- return "\n".join(indent + line for line in body)
-
-
-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_preload = _glb_preload_js(
- glbs, target="ctx.assets",
- on_error=f"console.error('{_PREFIX} asset ' + key + ' failed: ' + ((e && e.message) || e));",
- )
- return f"""// generated by codeverse3d 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: {{}} }};
-{glb_preload}
- 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;
- g.userData['{ZONE_ROOT_KEY}'] = name; // as createScene marks it: the settle at boot moves zone assets only
- 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) -> ZoneProbeReport:
- from codeverse3d.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)))
- from codeverse3d.spatial.render_scene import probe_env_args
-
- args = ["--ws", str(ws.root), "--scene", PROBE_REL, "--timeout-ms", str(int(timeout_s * 1000))]
- args += probe_env_args()
- try:
- res = run_scene_script("probe_scene.mjs", args, 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)
- return ZoneProbeReport(probes=probes, census=census, other_errors=other)
# --------------------------------------------------------------------------- the env module alone
-#: the env check's probe entry (deleted after use)
-ENV_PROBE_REL = "src/_c3v_env_probe.js"
def lib_interface(ws: Workspace) -> str:
@@ -550,137 +195,7 @@ def lib_interface(ws: Workspace) -> str:
return "\n".join(rows)
-def check_env(ws: Workspace, *, timeout_s: float = 90.0) -> str:
- """``""`` when ``src/env.js`` lints clean, runs ``buildEnv`` alone in the browser host and lights what
- it builds; else the first failure, quoted. A probe that cannot run gives ``""`` (logged)."""
- import logging
-
- from codeverse3d.spatial.probes import unlit
- from codeverse3d.spatial.render_scene import SceneRenderError, probe_env_args, run_scene_script
-
- rel = SCENE_FILES[1]
- if not (ws.root / rel).is_file():
- return f"{rel} does not exist"
- own = [f for f in lint(ws).errors if (f.target or "").split(":")[0] == rel]
- if own:
- return "\n".join(f"{f.target}: {f.message}" + (f" ({f.fix_hint})" if f.fix_hint else "") for f in own[:6])
- probe_path = ws.root / ENV_PROBE_REL
- probe_path.write_text(_probe_module([], []))
- args = ["--ws", str(ws.root), "--scene", ENV_PROBE_REL, "--timeout-ms", str(int(timeout_s * 1000)), *probe_env_args()]
- try:
- res = run_scene_script("probe_scene.mjs", args, timeout_s=timeout_s + 20)
- except SceneRenderError as e:
- if e.scene_timed_out:
- return f"{rel}: buildEnv did not finish inside the {timeout_s:.0f} s probe budget"
- logging.getLogger(__name__).warning("env check could not run: %s", e)
- return ""
- finally:
- probe_path.unlink(missing_ok=True)
- s = res.summary
- # only the env module and its library run here: every console error is the env's
- errors = [e for e in s.get("console_errors", []) if not e.startswith("boot[")]
- boot = s.get("boot") or {}
- if not boot.get("ok"):
- errors.insert(0, f"the env probe did not boot [{boot.get('stage')}]: {boot.get('error', '')}")
- if errors:
- return "\n".join(e[:900] for e in errors[:3])
- dark = unlit(s.get("census") or {}, offline=False)
- return f"{rel}: {dark.message}" if dark is not None else ""
-
-
# --------------------------------------------------------------------------- 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:
- imports = "\n".join(f"import {{ build as build{to_pascal(z)} }} from './zones/{z}.js';" for z in zones)
- calls = "\n".join(f" await addZone(build{to_pascal(z)}, '{to_pascal(z)}');" for z in zones)
- env_import = "import { buildEnv, heightAt } from './env.js';" if env_ok else ""
- env_build = " const env = (await buildEnv(ctx)) || {};\n ctx.env = env;" if env_ok else " const env = {};"
- height = "heightAt" if env_ok else "() => 0"
- glb_preload = _glb_preload_js(
- glbs, target="ctx.assets",
- on_error="console.error(`[assets] failed to load ${a.url}: ${e && e.message}`);",
- )
- cams = "\n".join(_cam_literal(c) for c in cameras)
- return f"""// src/scene.js — ASSEMBLED BY THE HARNESS (codeverse3d 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: {{}} }};
-{glb_preload}
-{env_build}
-
- const zones = [];
- const addZone = async (build, name) => {{
- const g = await build(ctx);
- if (!g || !g.isObject3D) throw new Error(`zone ${{name}}: build(ctx) must return a THREE.Group`);
- if (!g.name) g.name = name;
- g.userData['{ZONE_ROOT_KEY}'] = name; // the harness's zone mark: the placement table measures its children
- scene.add(g);
- zones.push(g);
- }};
-{calls}
-
- // a placed GLB clone that carries clips (a keyframed Blender part; `.clone()` copies them)
- // plays them here, driven by ABSOLUTE time so t=0 / t=1.5 are deterministic frames; a zone
- // de-phases copies with `clone.userData.clipOffset` (seconds). Measured 2026-09-07: told
- // how to play a clip itself, the windmill zone placed the clone and played nothing.
- const players = [];
- scene.traverse((o) => {{
- if (!o.animations || !o.animations.length) return;
- const mixer = new THREE.AnimationMixer(o);
- for (const clip of o.animations) mixer.clipAction(clip).play();
- players.push([mixer, +(o.userData.clipOffset || 0)]);
- }});
-
- 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);
- for (const [mixer, offset] of players) mixer.setTime(t + offset);
- }}
- return {{ scene, cameras, update }};
-}}
-"""
-
-
-def assemble(ws: Workspace, plan: ScenePlan, *, timeout_s: float = 90.0) -> AssembleResult:
- 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)")
- report = probe_zone_modules(ws, timeout_s=timeout_s)
- for o in report.other_errors:
- 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])
- healthy = [n for n, p in report.probes.items() if p.ok]
- failed = {n: p.error for n, p in report.probes.items() if not p.ok}
- if not healthy:
- warnings.append("no zone module survived probing; scene.js assembled with zero zones")
- text = render_scene_js(healthy, list(plan.cameras[:6]), glb_assets(ws), env_ok=env_ok)
- out = ws.src / "scene.js"
- out.parent.mkdir(parents=True, exist_ok=True)
- out.write_text(text)
- result = AssembleResult(scene_path=str(out), zones_included=healthy, zones_failed=failed, env_ok=env_ok,
- warnings=warnings, census=report.census)
- ws.write_json(ws.artifacts / "assemble.json", result)
- return result
# ===================================================================== runtime
@@ -697,8 +212,6 @@ class SceneThreeJsRuntime:
def expected_files(self, plan: Plan | None) -> list[str]:
return list(SCENE_FILES)
- def assemble(self, ws: Workspace, plan: ScenePlan) -> AssembleResult:
- return assemble(ws, plan)
def probe(self, ws: Workspace, *, timeout_s: float | None = None) -> SceneProbeResult:
from codeverse3d.spatial.probes import probe_scene
@@ -712,12 +225,6 @@ class SceneThreeJsRuntime:
return render_scene(ws, out_dir, cameras=cameras, orbit=orbit, times=tuple(times), width=width, height=height, sheet=sheet)
- def files_for(self, plan: Plan | None, target: str) -> list[str]:
- return scene_files_for(plan, target, zone_file=zone_file, asset_file=asset_file, entry="src/scene.js", env_file="src/env.js",
- env_words=ENV_WORDS)
-
- def skeleton(self, ws: Workspace, plan: Plan | None) -> list[Path]:
- return write_skeleton(ws, plan)
def lint(self, ws: Workspace) -> GateReport:
return lint(ws)
@@ -725,26 +232,6 @@ class SceneThreeJsRuntime:
def lib_interface(self, ws: Workspace) -> str:
return lib_interface(ws)
- def check_env(self, ws: Workspace) -> str:
- return check_env(ws)
-
- def render_asset(self, ws: Workspace, name: str, out_dir: Path, *, timeout_s: float = 180.0) -> RenderSet:
- """Quick sheet of ONE procedural asset module: exported to a GLB by the object track's build
- on a scratch workspace and rendered like a hero GLB."""
- from codeverse3d.languages.threejs import ThreeJsRuntime
- from codeverse3d.spatial.render import RenderError, render_glb
-
- snake, pascal = to_snake(name), to_pascal(name)
- tmp = Workspace(ws.artifacts / "asset_export" / snake)
- tmp.src.mkdir(parents=True, exist_ok=True)
- module = (ws.src / "assets" / f"{snake}.js").resolve().as_posix()
- (tmp.src / "object.js").write_text(
- f"import {{ build{pascal} }} from '{module}';\n"
- f"export function build(THREE) {{ return build{pascal}(THREE, {{}}); }}\n")
- res = ThreeJsRuntime().build(tmp, timeout_s=int(timeout_s))
- if not res.ok or not res.glb_path:
- raise RenderError(f"asset export failed for {name}: {res.error_type}: {res.error_message}")
- return render_glb(res.glb_path, out_dir, views=list(OBJECT_VIEWS_QUICK), width=512, height=512, sheet=True)
def build(self, ws: Workspace, *, timeout_s: int | None = None) -> BuildResult:
"""Probe + shader preflight (one browser boot); ok iff the module loads and no shader errors."""
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/assets/pine_tree.js b/harness/codeverse3d/languages/scene_threejs/starter/src/assets/pine_tree.js
deleted file mode 100644
index 940a7064..00000000
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/assets/pine_tree.js
+++ /dev/null
@@ -1,33 +0,0 @@
-// 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/codeverse3d/languages/scene_threejs/starter/src/assets/windmill.js b/harness/codeverse3d/languages/scene_threejs/starter/src/assets/windmill.js
deleted file mode 100644
index 6c57b905..00000000
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/assets/windmill.js
+++ /dev/null
@@ -1,30 +0,0 @@
-// 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/codeverse3d/languages/scene_threejs/starter/src/env.js b/harness/codeverse3d/languages/scene_threejs/starter/src/env.js
deleted file mode 100644
index ff8e6407..00000000
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/env.js
+++ /dev/null
@@ -1,61 +0,0 @@
-// src/env.js — the environment of the EXAMPLE scene (the plan-less skeleton the tests build): the ground every zone
-// seats on, the light, the sky / backdrop, the atmosphere. A plan skeleton gets an interface STUB here instead
-// (languages/scene_threejs/_env_for_plan): the plan's data, a plate, and no light or atmosphere until the author writes them.
-// export function heightAt(x, z) → ground height (m): the ONE function every zone seats on.
-// export function buildEnv(ctx) → { update?(t, dt), ...whatever zones may share as ctx.env (sunDir, materials, a water level …) }
-// export const SUN_AZIMUTH_DEG → where the light comes from (0 = +X, 90 = +Z); the assembler reads it to fit cameras on the lit side.
-// What is measured on any env:
-// • every zone seats on heightAt, so the ground mesh and heightAt must agree (scene_placement: floating > 0.05 m
-// outdoors / 0.02 m indoors, sunken > 0.10 m); each camera's eye stays above heightAt at its (x, z).
-// • scene.fog and scene.background set (no_fog / no_background); fog far ≥ 2 × the plan span or 1/density ≥ span / 1.5
-// (fog_short); the land reaches past the fog from every authored camera; no world edge in any authored frame (judged).
-// • the judged frames sit in the exposure band (scene_frames: dark_frame / blown_frame / flat_frame).
-// • the ground mesh is named 'Ground…' / 'Terrain…' (the census classifies the ground by name); backdrop geometry 'Sky…'.
-// Raw three.js is the baseline; src/lib is an OPTIONAL toolbox (the effects catalog lists it).
-import * as THREE from 'three';
-import { sunRig } from './lib/environment.js';
-
-export const SUN_AZIMUTH_DEG = 60; // 0 = +X, 90 = +Z — this example's light
-export const SUN_ELEVATION_DEG = 38;
-export const MOOD = 'day'; // this example's time of day (sunRig's rigs: day | golden | night | overcast)
-export const GROUND_SIZE = 160; // the example meadow's plate (m): past 2 × its span, so the fog has land to read
-export const SHADOW_RADIUS = 45; // half-size (m) of the sun's shadow frustum: shadows are crisp inside it
-// An interior's room box, { center, extents, openings, glazed? } (null: this example is outdoors).
-export const INTERIOR = null;
-const SEED = 7;
-
-/** Ground height at (x, z) — every placement seats on this. This example: level. */
-export function heightAt(x, z) {
- return 0;
-}
-
-export function buildEnv(ctx) {
- const { scene } = ctx;
- const group = new THREE.Group();
- group.name = 'Environment';
-
- // the example's ground: a level plate following heightAt, named Ground
- const ground = new THREE.Mesh(new THREE.PlaneGeometry(GROUND_SIZE, GROUND_SIZE, 1, 1),
- new THREE.MeshStandardMaterial({ color: 0x6f6a60, roughness: 0.95 }));
- ground.rotation.x = -Math.PI / 2;
- ground.receiveShadow = true;
- ground.name = 'Ground';
- group.add(ground);
-
- // the example's light: the library's rig (sun + hemisphere fill + the baked environment map PBR materials read
- // from — a metal with no scene.environment renders near black)
- const rig = sunRig({ mood: MOOD, azimuth: SUN_AZIMUTH_DEG, elevation: SUN_ELEVATION_DEG, bounds: SHADOW_RADIUS });
- const sun = rig.sun, hemi = rig.fill;
- group.add(sun, sun.target, hemi);
- if (rig.sunDisc) group.add(rig.sunDisc);
- scene.environment = rig.envTex;
-
- // the example's atmosphere: a fog reaching past the plate, the background its colour
- scene.fog = new THREE.Fog(0xbfc6cc, GROUND_SIZE * 0.25, GROUND_SIZE * 0.9);
- scene.background = new THREE.Color(scene.fog.color);
- scene.add(group);
-
- const update = () => {};
- const sunDir = sun.position.clone().normalize();
- return { ground, sun, sunDir, hemi, group, seed: SEED, update };
-}
diff --git a/harness/codeverse3d/languages/scene_threejs/starter/src/scene.js b/harness/codeverse3d/languages/scene_threejs/starter/src/scene.js
deleted file mode 100644
index ce7c6638..00000000
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/scene.js
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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: the plan's authored shots, 1–6; each is measured (eye above the ground, nothing within 0.5 m of the lens,
-// the first one as the establishing shot: ≥ 20 % of its frame is content).
-// • 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 a helper SDK or any npm package.
-// ./lib/ is the ONE exception and is not an SDK: harness-owned effect modules
-// shipped INTO this workspace, already compiled and rendered on this renderer.
-// Import and call them (`import { makeGrass } from './lib/grass.js'`) when they help; do not
-// rewrite them — writes to src/lib/ are reverted. Table: prompts effects_catalog.
-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); // whatever env.js shares with the zones
- 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/codeverse3d/languages/scene_threejs/starter/src/shaders/water.js b/harness/codeverse3d/languages/scene_threejs/starter/src/shaders/water.js
deleted file mode 100644
index 367661bc..00000000
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/shaders/water.js
+++ /dev/null
@@ -1,60 +0,0 @@
-// 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/codeverse3d/languages/scene_threejs/starter/src/zones/meadow.js b/harness/codeverse3d/languages/scene_threejs/starter/src/zones/meadow.js
deleted file mode 100644
index 88f7e1bd..00000000
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/zones/meadow.js
+++ /dev/null
@@ -1,64 +0,0 @@
-// 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';
-import { mulberry32 } from '../lib/noise.js';
-
-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 = mulberry32(7); // seeded: the same layout every run (the harness diffs rounds)
- 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/codeverse3d/languages/scene_threejs/starter/src/zones/pondside.js b/harness/codeverse3d/languages/scene_threejs/starter/src/zones/pondside.js
deleted file mode 100644
index 44611834..00000000
--- a/harness/codeverse3d/languages/scene_threejs/starter/src/zones/pondside.js
+++ /dev/null
@@ -1,65 +0,0 @@
-// 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/codeverse3d/languages/threejs/__init__.py b/harness/codeverse3d/languages/threejs/__init__.py
index 413eaad0..3bd26d00 100644
--- a/harness/codeverse3d/languages/threejs/__init__.py
+++ b/harness/codeverse3d/languages/threejs/__init__.py
@@ -9,7 +9,7 @@ from pathlib import Path
from codeverse3d.config import get_settings
from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, LintKind, Severity
from codeverse3d.contracts.common import ENTRY_FILE, Language
-from codeverse3d.contracts.plan import Plan, StaticPlan
+from codeverse3d.contracts.plan import StaticPlan
from codeverse3d.conventions import to_pascal, to_snake
from codeverse3d.languages._common import BUILD_TIMEOUT, line_of, missing_entry, ws_rel
from codeverse3d.languages._js_lint import (
@@ -35,57 +35,6 @@ from codeverse3d.workspace import Workspace
# ===================================================================== templates
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.
-// root.userData.tick is recorded by the census but never called or exported on this track.
-// Imports that resolve: 'three', 'three/addons/...', relative './' under src/. 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, metres. The Group's name '{pascal}' is how the gates find this part; a mesh
-// with no name is a build warning. Lights / cameras / renderers are lint findings.
-// Measured on this part: bbox centre + extents within max(10 mm, 10 % of the plan extent) per
-// axis; one connected shell (tiny islands are stray geometry); contact (surface gap <= 2 mm) with
-// its planned neighbours; penetration <= 2 mm; the whole object's lowest point within 10 mm of y = 0.
-import * as THREE from 'three';
-
-export function build{pascal}(THREE_) {{
- const group = new THREE.Group();
- group.name = '{pascal}';
-
- // ---- PLACEHOLDER: a plain box at the plan bbox so the first build passes. Replace it with the
- // part the brief describes (keep the group name); what it is made of is yours to decide. ----
- const size = [{ex}, {ey}, {ez}];
- const mesh = new THREE.Mesh(new THREE.BoxGeometry(size[0], size[1], size[2]),
- new THREE.MeshStandardMaterial({{ color: {color} }}));
- 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")
-
# ===================================================================== lint
GATE = "lint:threejs"
@@ -224,63 +173,6 @@ def part_file_rel(part_name: str) -> str:
return f"src/parts/{to_snake(part_name)}.js"
-def part_file(ws: Workspace, part_name: str) -> Path:
- return ws.root / part_file_rel(part_name)
-
-
-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) -> list[Path]:
- """Write ``src/package.json``, ``src/object.js`` and ``src/parts/*.js``; existing files are kept."""
- 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():
- 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
-
-
# ===================================================================== runtime
ENTRY = ENTRY_FILE[Language.THREEJS]
GLB_NAME = "object.glb"
@@ -296,9 +188,6 @@ class ThreeJsRuntime(RuntimeLayout):
entry_globs: tuple[str, ...] = (ENTRY_FILE[Language.THREEJS], "src/parts/*.js")
part_file = staticmethod(part_file_rel)
- # ------------------------------------------------------------------ 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)
diff --git a/harness/codeverse3d/languages/urdf/__init__.py b/harness/codeverse3d/languages/urdf/__init__.py
index d280ae27..a6790a8d 100644
--- a/harness/codeverse3d/languages/urdf/__init__.py
+++ b/harness/codeverse3d/languages/urdf/__init__.py
@@ -10,7 +10,6 @@ import os
import shutil
import time
import xml.etree.ElementTree as ET
-from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any
@@ -19,7 +18,6 @@ import numpy as np
from codeverse3d.config import Settings, get_settings
from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, LintKind, Severity
from codeverse3d.contracts.common import ENTRY_FILE, Language, MimicSpec, mimic_issues
-from codeverse3d.contracts.plan import ArticulatedPlan, JointPlan, PartPlan, Plan
from codeverse3d.conventions import LINK_NAME_RE, to_snake
from codeverse3d.languages._ast_lint import dotted, safe_parse
from codeverse3d.languages._common import compose_build_result, missing_entry, strip_blender_noise
@@ -53,6 +51,10 @@ from codeverse3d.workspace import ArtifactStage, Workspace
FK_GATE = "fk_consistency"
+def _vec(v: tuple[float, float, float]) -> str:
+ return " ".join(f"{x:g}" if abs(x) >= 1e-9 else "0" 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; ERROR per inconsistent link with a corrected origin."""
T = fk(robot, {})
@@ -404,223 +406,9 @@ def lint_workspace(ws: Workspace) -> GateReport:
# ===================================================================== skeleton
-DEFAULT_EFFORT = 10.0
-DEFAULT_VELOCITY = 1.0
-
-
-@dataclass(frozen=True)
-class LinkFrame:
-
- 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
- rest: float = 0.0 # plan rest value the limits were shifted by (0 → limits == plan limits)
- mimic: tuple[str, float, float] | None = None # (driving joint, multiplier, offset)
- mimic_note: str = "" # written beside the <mimic> as a comment (an instanced driver's other copies)
-
-
-@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:
- parts = _expand_parts(plan)
- base_names = {to_snake(p.name) for p in plan.parts}
- 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
- mim = None
- if j.mimic is not None:
- # every copy of an instanced follower follows the same driver; resolved after emission
- mim = (to_snake(j.mimic.joint), float(j.mimic.multiplier), float(j.mimic.offset))
- joints.append(JointRow(name=to_snake(j.name) + suffix, type=j.type, parent=parent, child=child,
- origin_xyz=(0.0, 0.0, 0.0), axis=tuple(float(v) for v in j.axis), lower=lower, upper=upper,
- rest=float(j.rest) if lower is not None else 0.0, mimic=mim))
-
- 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
- # one instance link by its own name, else the part and every instance link it expanded to
- children = [n for n, p, _ in parts if n == child or to_snake(p.name) == child]
- for k, c in enumerate(children):
- add_joint(j, c, parent, "" if len(children) == 1 else f"_{k + 1}")
-
- # A driver whose child is instanced exists only as <name>_1..._n: follow the first instance.
- emitted = {jr.name for jr in joints}
- for i, jr in enumerate(joints):
- if jr.mimic is None or jr.mimic[0] in emitted:
- continue
- target, mult, off = jr.mimic
- if f"{target}_1" not in emitted:
- raise ValueError(f"joint {jr.name}: mimic target {target!r} was not emitted; joints are {sorted(emitted)}")
- # the other instances stay independent inputs; say so in the file
- others = sorted(n for n in emitted if n.startswith(f"{target}_") and n != f"{target}_1")
- joints[i] = replace(jr, mimic=(f"{target}_1", mult, off),
- mimic_note=f"follows {target}_1 only; {', '.join(others)} stay independent inputs "
- "(add a <mimic> per instance if they move together)")
-
- 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)
- 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, rest=jr.rest, mimic=jr.mimic,
- mimic_note=jr.mimic_note))
- return UrdfFrames(robot_name=to_snake(plan.object_name), root=root, links=links, joints=fixed)
# ------------------------------------------------------------------ text renderers
-def _limit_note(jr: JointRow) -> str:
- if jr.lower is None or jr.upper is None or abs(jr.rest) < 1e-12:
- return ""
- return (f" <!-- plan lower={_fmt(jr.lower + jr.rest)} upper={_fmt(jr.upper + jr.rest)} rest={_fmt(jr.rest)}: "
- f"the mesh is authored at rest, so q=0 = plan {_fmt(jr.rest)} and the limits are shifted by -rest -->")
-
-
-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. -->")
- lines.append(" <!-- q=0 is the authored pose (the plan's rest pose); limits are the plan's lower-rest .. upper-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}/>" + _limit_note(jr))
- if jr.mimic is not None:
- src, mult, off = jr.mimic
- lines.append(f' <mimic joint="{src}" multiplier="{_fmt(mult)}" offset="{_fmt(off)}"/>'
- f" <!-- driven: the sweep moves the driver, this joint follows"
- f"{'; ' + jr.mimic_note if jr.mimic_note else ''} -->")
- 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 (= URDF q=0, the pose the plan's bboxes describe).
-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):
- """Placeholder box so the skeleton builds (center/size in world metres) — not a helper to build the object with."""
- 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:
- jr = next(j for j in frames.joints if j.name == lf.parent_joint)
- note = f" (plan rest={_fmt(jr.rest)} → this pose is URDF q=0)" if abs(jr.rest) > 1e-12 else ""
- body.append(f"# joint '{lf.parent_joint}' pivot (world) = {lf.frame_xyz}{note}")
- 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]:
- 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]
# ===================================================================== runtime
@@ -636,11 +424,6 @@ class UrdfBlenderRuntime(RuntimeLayout):
entry_globs = (ENTRY_FILE[Language.URDF_BLENDER], "src/robot.urdf")
extra_files = ("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)
diff --git a/harness/codeverse3d/plan_checks.py b/harness/codeverse3d/plan_checks.py
new file mode 100644
index 00000000..0a1509ce
--- /dev/null
+++ b/harness/codeverse3d/plan_checks.py
@@ -0,0 +1,330 @@
+"""``3dcode validate-plan``: ``plan.json`` against the track's plan model plus the deterministic plan checks
+(placeholder echo, the size / detail budget derived from the request, fixed-part clash), then the normalisation
+every accepted plan gets (PascalCase names, the acceptance items the spec implies)."""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import Any
+
+from pydantic import BaseModel, ValidationError
+
+from codeverse3d.contracts.common import Language, Track
+from codeverse3d.contracts.plan import SCENE_ASSET_KINDS, AcceptanceItem
+from codeverse3d.contracts.spec import Spec
+from codeverse3d.conventions import to_pascal, to_snake
+
+# ===================================================================== plan budgets
+#: practical ceiling on TOP-LEVEL plan parts per language. Blender/three.js own one
+#: file per part so they scale; cadquery is one file; urdf links cost a joint each and
+#: the collision sweep is O(links² × poses), so depth there goes into sub-parts.
+PART_CAP: dict[str, int] = {
+ Language.BLENDER.value: 20,
+ Language.THREEJS.value: 20,
+ Language.CADQUERY.value: 14,
+ Language.URDF_BLENDER.value: 10,
+}
+DEFAULT_PART_CAP = 14
+MIN_PARTS = 6
+#: a checklist this long is EVIDENCE that the request really needs the target part count; below it the
+#: target is an aspiration the check must not enforce
+EVIDENCE_MIN_CHECKLIST = 4
+GRAPHICS_CAP = 6
+GRAPHICS_MIN = 1
+
+# --------------------------------------------------------------------- "is this a box?"
+#: construction verbs / counted repeated features that make a part description more than
+#: "a box of size X". Stems, not bare words: `taper` alone never matches "tapered", which
+#: is how every real plan writes it.
+_CRAFT = re.compile(
+ r"\b(bevel\w*|chamfer\w*|fillet\w*|round(?:ed)?[- ](?:edge|corner|over)\w*|bullnose\w*|taper\w*|groove\w*"
+ r"|flute\w*|thread(?:ed|s)?|helix|helical|spline\w*|loft\w*|revolv\w*|extrud\w*|bezier|swept|sweep\w*"
+ r"|profile[ds]?|inset\w*|boolean\w*|subdivi\w*|smooth[- ]shad\w*|array\w*|lattice\w*|slot(?:s|ted)?"
+ r"|notch\w*|ribs?|louvre\w*|louver\w*|knurl\w*|serrat\w*|scallop\w*|hollow\w*|shell(?:ed)?|cut-?out\w*"
+ r"|recess\w*|emboss\w*|moulding\w*|molding\w*|curv\w*|arc\b|arch\w*|spiral\w*|dome[ds]?|domed|ogee"
+ r"|scroll\w*|pierc\w*|perforat\w*|crown\w*|swage\w*|bulg\w*|waist\w*|concave|convex|rebate[ds]?|dovetail\w*"
+ r"|mortise\w*|tenon\w*|splay\w*|conical|tapering|beading|reeded|turned|rounded|radius|radii)\b"
+ r"|\br\s*=\s*\d",
+ re.I)
+_COUNTED = re.compile(
+ r"\b\d+\s*(x|×)?\s*(slats?|spokes?|teeth|dentils?|panes?|rafters?|bolts?|screws?|rivets?|holes?|segments?"
+ r"|facets?|ribs?|flutes?|turns?|steps?|rings?|wires?|bars?|louvres?|louvers?|vents?|grooves?|studs?|pads?)\b",
+ re.I)
+_GFX_CRAFT = re.compile(
+ r"\b(fbm|noise|hash|sdf|raymarch|ray[- ]?march|march|domain[- ]?warp|voronoi|worley|curl|advect|feedback"
+ r"|parallax|refract|reflect|fresnel|bokeh|blur|bloom|vignette|aberration|tonemap|gamma|dither|grain"
+ r"|particle|instanc|scatter|caustic|godray|god[- ]ray|volumetric|shadow|ao\b|ambient occlusion|palette"
+ r"|gradient|dissolve|erosion|turbulen|flow[- ]?map|displac|tessell|subsurface|halftone|posteris|posteriz)\b",
+ re.I)
+_NUMBER = re.compile(r"\d+(?:\.\d+)?")
+
+
+def has_real_detail(text: str) -> bool:
+ """True when a part description says something a box cannot say."""
+ return bool(_CRAFT.search(text) or _COUNTED.search(text))
+
+
+def has_pass_detail(text: str) -> bool:
+ """True when a graphics pass description names a technique or carries a recipe."""
+ return bool(_GFX_CRAFT.search(text)) or len(_NUMBER.findall(text)) >= 2
+
+
+@dataclass(frozen=True)
+class PlanBudget:
+ """What this request is worth, in plan units (parts, or passes for graphics)."""
+
+ target_parts: int
+ min_parts: int
+ cap_parts: int
+ min_detail_parts: int
+ min_assemblies: int
+ reason: str = ""
+ evidence: bool = False
+
+ def as_dict(self) -> dict[str, int | str | bool]:
+ return {"target_parts": self.target_parts, "min_parts": self.min_parts, "cap_parts": self.cap_parts,
+ "min_detail_parts": self.min_detail_parts, "min_assemblies": self.min_assemblies,
+ "budget_evidence": self.evidence, "reason": self.reason}
+
+
+def plan_budget(spec: Spec) -> PlanBudget:
+ """Derive the plan's size budget from the REQUEST, not from a constant."""
+ n_must = len(spec.constraints.must_have)
+ if spec.track is Track.GRAPHICS:
+ target = max(GRAPHICS_MIN, min(GRAPHICS_CAP, GRAPHICS_MIN + (n_must + 1) // 3))
+ return PlanBudget(target_parts=target, min_parts=max(GRAPHICS_MIN, target - 1), cap_parts=GRAPHICS_CAP,
+ min_detail_parts=max(1, target - 1), min_assemblies=0,
+ reason=f"{n_must} checklist items" if n_must else "no checklist",
+ evidence=n_must >= EVIDENCE_MIN_CHECKLIST)
+ cap = PART_CAP.get(spec.language.value, DEFAULT_PART_CAP)
+ want = n_must
+ target = max(MIN_PARTS, min(cap, want))
+ floor = max(2, int(round(0.85 * min(cap, want))))
+ return PlanBudget(
+ target_parts=target, min_parts=floor, cap_parts=cap,
+ min_detail_parts=min(floor, max(2, int(round(0.35 * target)))),
+ min_assemblies=1 if target >= 10 else 0,
+ reason=f"{n_must} checklist items" if n_must else "no checklist",
+ evidence=n_must >= EVIDENCE_MIN_CHECKLIST,
+ )
+
+
+def plan_quality_complaints(plan_obj: Any, budget: PlanBudget, *, unit: str = "parts") -> tuple[list[str], list[str]]:
+ """``(hard, soft)`` complaints about a VALID plan: hard ones fail the check, soft ones are warnings."""
+ parts: list[Any] = list(getattr(plan_obj, "parts", None) or getattr(plan_obj, "passes", None) or [])
+ if not parts:
+ return [], []
+ nest = "elements" if unit == "passes" else "children"
+ hard: list[str] = []
+ soft: list[str] = []
+ if budget.evidence and len(parts) < budget.min_parts:
+ hard.append(
+ f"Only {len(parts)} {unit} for a request that needs at least {budget.min_parts} "
+ f"({budget.reason}). Split the ones that are really assemblies and add the features you skipped — "
+ f"do NOT pad with duplicates.")
+ detector = has_pass_detail if unit == "passes" else has_real_detail
+ detailed = [p for p in parts if detector(f"{p.description} {getattr(p, 'detail_hint', '')}")
+ or getattr(p, "children", None) or getattr(p, "elements", None)]
+ if len(detailed) < budget.min_detail_parts:
+ plain = [p.name for p in parts if p not in detailed][:8]
+ # enforced only on EVIDENCE (a long checklist): without it the request never said the object has
+ # shaping a primitive cannot express — "a stool" may be four boxes
+ (hard if budget.evidence else soft).append(
+ f"This plan is boxes at different sizes: only {len(detailed)} of {len(parts)} {unit} describe anything a "
+ f"plain primitive cannot express, and this request needs at least {budget.min_detail_parts}. Rewrite "
+ f"{', '.join(plain)} where the real thing has it: a profile, a stated radius or edge "
+ f"treatment, a counted repeat, or the sub-shapes it is actually made of.")
+ if budget.min_assemblies:
+ n_nested = sum(1 for p in parts if getattr(p, nest, None))
+ if n_nested < budget.min_assemblies:
+ soft.append(
+ f"{n_nested} of the {unit} use `{nest}`, but this request has at least {budget.min_assemblies} real "
+ f"sub-assemblies. Give each of them its `{nest}`" +
+ ("" if unit == "passes" else " with their own bboxes (inside the parent's) and materials") +
+ f"; leave the simple {unit} alone.")
+ materials = {(getattr(p, "material", "") or "").strip().lower() for p in parts} - {""}
+ if unit == "parts" and len(parts) >= 5 and len(materials) <= 1:
+ soft.append("Every part has the same material (or none). Real objects mix materials — give each part its "
+ "own material with a colour.")
+ return hard, soft
+
+
+# ===================================================================== deterministic checks on the raw plan
+_PLACEHOLDERS = {"string", "str", "name", "text", "..."}
+
+
+def schema_echo(raw: dict[str, Any]) -> str:
+ """"" or what in ``raw`` is a JSON-schema placeholder (``"name": "string"``) rather than content."""
+ bad: list[str] = []
+ if str(raw.get("object_name", "")).strip().lower() in _PLACEHOLDERS:
+ bad.append("object_name")
+ for key in ("parts", "joints", "zones", "assets", "passes"):
+ for i, item in enumerate(raw.get(key) or []):
+ if isinstance(item, dict) and str(item.get("name", "")).strip().lower() in _PLACEHOLDERS:
+ bad.append(f"{key}[{i}].name")
+ return ", ".join(bad[:6])
+
+
+def missing_link_names(raw: Any) -> list[str]:
+ """Link names the joints reference that ``parts`` does not define (snake-compared)."""
+ if not isinstance(raw, dict):
+ return []
+ parts = raw.get("parts")
+ joints = raw.get("joints")
+ if not isinstance(parts, list) or not isinstance(joints, list):
+ return []
+ known = {to_snake(str(p.get("name", ""))) for p in parts if isinstance(p, dict)}
+ known |= {to_snake(str(c.get("name", ""))) for p in parts if isinstance(p, dict)
+ for c in (p.get("children") or []) if isinstance(c, dict)}
+ missing: list[str] = []
+ for j in joints:
+ if not isinstance(j, dict):
+ continue
+ for side in ("parent", "child"):
+ name = str(j.get(side, "")).strip()
+ if name and to_snake(name) not in known and name not in missing:
+ missing.append(name)
+ return missing
+
+
+def fixed_part_clash(plan_obj: BaseModel, spec: Spec) -> str:
+ """'' unless the plan lists one of the spec's fixed parts (``Spec.fixed_parts``) as a part of its own: the
+ project builds those, so a planned one invites the agent to author it."""
+ fixed = {to_snake(f.name): f for f in spec.fixed_parts if f.name}
+ if not fixed:
+ return ""
+ names = [p.name for p in getattr(plan_obj, "parts", None) or []]
+ hits = [n for n in names if to_snake(n) in fixed]
+ if not hits:
+ return ""
+ return (f"the plan lists fixed parts {hits} as its own parts: they are given by the project (FIXED PARTS) — "
+ "remove them from the plan and plan only the parts around them")
+
+
+def asset_kind_errors(raw: Any, language: Language) -> list[str]:
+ """Scene assets whose ``kind`` is not one this scene language builds (``SCENE_ASSET_KINDS``)."""
+ kinds = SCENE_ASSET_KINDS.get(language.value)
+ if not kinds or not isinstance(raw, dict):
+ return []
+ out = []
+ for i, a in enumerate(raw.get("assets") or []):
+ if isinstance(a, dict) and a.get("kind") not in kinds:
+ out.append(f"assets[{i}].kind: {a.get('kind')!r} is not one of {list(kinds)} for {language.value}")
+ return out
+
+
+def validation_errors(e: ValidationError) -> list[str]:
+ """One ``path: message`` line per pydantic error."""
+ out = []
+ for err in e.errors():
+ path = ".".join(str(p) for p in err.get("loc", ())) or "(root)"
+ out.append(f"{path}: {err.get('msg', '')}")
+ return out
+
+
+# ===================================================================== normalisation
+def _fold_pass(ps: Any) -> None:
+ """Fold a graphics pass's ``elements`` + ``detail_hint`` into its ``description``."""
+ if not (ps.elements or ps.detail_hint) or " · " in ps.description:
+ return
+ bits = [ps.description.rstrip().rstrip(".")]
+ if ps.elements:
+ bits.append("draws: " + " · ".join(e.strip() for e in ps.elements))
+ if ps.detail_hint:
+ bits.append(f"what makes it real: {ps.detail_hint.strip()}")
+ ps.description = " · ".join(bits).replace("\n", " ").replace("|", "/")
+
+
+def add_acceptance_item(items: list[AcceptanceItem], prefix: str, text: str, how: str, *,
+ priority: str = "must") -> bool:
+ """Append a derived acceptance item (*must* unless told otherwise) unless an equal text exists."""
+ if text.strip().lower() in {a.text.strip().lower() for a in items}:
+ return False
+ ids = {a.id for a in items}
+ n = 1
+ while f"{prefix}{n}" in ids:
+ n += 1
+ items.append(AcceptanceItem(id=f"{prefix}{n}", text=text, how=how, priority=priority)) # type: ignore[arg-type]
+ return True
+
+
+def ensure_acceptance(plan_obj: Any, spec: Spec) -> list[str]:
+ """Append the acceptance items the spec constraints imply; returns the ids added."""
+ items: list[AcceptanceItem] = list(plan_obj.acceptance)
+ before = {a.id for a in items}
+ if spec.track is Track.SCENE:
+ items = [a if a.priority == "should" else a.model_copy(update={"priority": "should"}) for a in items]
+ c = spec.constraints
+ solid = spec.track is not Track.GRAPHICS
+ if solid and c.dimensions_m:
+ dims = ", ".join(f"{k} = {v:.3f} m" for k, v in c.dimensions_m.items())
+ add_acceptance_item(items, "dim", f"Overall dimensions match the request within 5%: {dims}", "measure")
+ for m in c.must_have:
+ add_acceptance_item(items, "must", f"Includes: {m}", "visual")
+ for m in c.must_not:
+ add_acceptance_item(items, "not", f"Does NOT include: {m}", "visual")
+ if not solid:
+ planned_motion = getattr(plan_obj, "motion", "").strip()
+ if planned_motion and not any(w in a.text.lower() for a in items for w in ("static", "motion", "change over time")):
+ add_acceptance_item(items, "motion", "Frames change over time as planned (not a static image)", "probe")
+ elif spec.track is not Track.SCENE and not any(a.how == "measure" for a in items):
+ add_acceptance_item(items, "ground", "Object stands on the ground plane (lowest point at up=0) with its footprint centred", "measure")
+ items.extend(articulation_acceptance(plan_obj, items))
+ plan_obj.acceptance = items
+ return [a.id for a in items if a.id not in before]
+
+
+def articulation_acceptance(plan_obj: Any, items: list[AcceptanceItem]) -> list[AcceptanceItem]:
+ """One ``articulation`` item per moving joint the plan's own checklist does not cover."""
+ joints = [j for j in (getattr(plan_obj, "joints", None) or []) if j.type != "fixed"]
+ if not joints:
+ return []
+ covered = " ".join(a.text.lower() for a in items if a.how == "articulation")
+ words = set(re.findall(r"[a-z0-9]+", covered.replace("_", " ")))
+ out: list[AcceptanceItem] = []
+ for j in joints:
+ # whole-word match on the joint's or the child's name ("lid" must not match "slides")
+ keys = {j.name.lower(), to_snake(j.child).replace("_", " "), j.child.lower()}
+ if any(k and all(w in words for w in re.findall(r"[a-z0-9]+", k)) for k in keys):
+ continue
+ unit = "m" if j.type == "prismatic" else "rad"
+ rest = "closed / stowed" if abs(j.rest) < 1e-9 else f"at {j.rest:.2f} {unit}"
+ rng = "turns freely" if j.type == "continuous" else f"moves over [{j.lower:.2f}, {j.upper:.2f}] {unit}"
+ out.append(AcceptanceItem(
+ id=f"art_{to_snake(j.child)}"[:40], how="articulation", priority="should",
+ text=f"Joint {j.name}: at rest {j.child} sits {rest} against {j.parent}; it {rng} — {j.motion} — "
+ f"without passing through {j.parent} or any other link (pose_* views)"))
+ return out
+
+
+def normalise_names(plan_obj: Any) -> None:
+ """PascalCase part/link/zone/asset names in place."""
+ 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)
+
+
+def normalise_plan(plan_obj: Any, spec: Spec) -> list[str]:
+ """Every normalisation an accepted plan gets, as human lines (``[]`` when nothing changed)."""
+ notes: list[str] = list(getattr(plan_obj, "normalisations", None) or [])
+ before = [p.name for p in getattr(plan_obj, "parts", None) or []]
+ normalise_names(plan_obj)
+ after = [p.name for p in getattr(plan_obj, "parts", None) or []]
+ renamed = [f"{a} → {b}" for a, b in zip(before, after, strict=True) if a != b]
+ if renamed:
+ notes.append("part names made PascalCase: " + ", ".join(renamed[:8]))
+ for ps in getattr(plan_obj, "passes", None) or []:
+ _fold_pass(ps)
+ added = ensure_acceptance(plan_obj, spec)
+ if added:
+ notes.append("acceptance items added from the spec: " + ", ".join(added))
+ return notes
diff --git a/harness/codeverse3d/proc.py b/harness/codeverse3d/proc.py
index a04f1d9d..619f253e 100644
--- a/harness/codeverse3d/proc.py
+++ b/harness/codeverse3d/proc.py
@@ -1,18 +1,15 @@
-"""Process-level primitives shared across the harness.
+"""Process-level primitives shared by the instruments.
-Run-a-child-process (:class:`ManagedProcess`, :func:`run_subprocess`), atomic JSON writes, tolerant
-JSON / JSONL readers, the event stream (:class:`EventLog`), the per-run mutex (:func:`exclusive`)
-and the context-carrying :func:`fan_out`. Stdlib-only: imports nothing from ``codeverse3d``.
+Run-a-child-process (:class:`ManagedProcess`, :func:`run_subprocess`), atomic JSON writes, a tolerant
+JSON reader and the machine-wide :class:`Slots`. Stdlib-only: imports nothing from ``codeverse3d``.
"""
from __future__ import annotations
import contextlib
-import contextvars
import fcntl
import hashlib
import json
-import logging
import os
import random
import signal
@@ -20,9 +17,7 @@ import subprocess
import threading
import time
from collections import deque
-from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
-from concurrent.futures import ThreadPoolExecutor
-from contextlib import contextmanager
+from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import IO, Any
@@ -132,7 +127,7 @@ class _BoundedSink:
class ManagedProcess:
"""A ``Popen`` in its own session whose process group cannot outlive the ``with`` block.
- Shared core of :func:`run_subprocess` and ``agents/cli_common.run_with_watchdog``: two pump
+ Core of :func:`run_subprocess`: two pump
threads feed a bounded sink per stream, an optional ``on_line(stream, line)`` observer sees
each line (exceptions suppressed), and stdin is written from its own thread. ``__exit__``
on any exception, or with the child still running, SIGTERMs the group (SIGKILL after
@@ -153,21 +148,16 @@ class ManagedProcess:
self._stop = threading.Event() # tells an abandoned pump to quit feeding
self._abandoned = "" # the truncation note to append, once we know which one
self._sinks = {"stdout": _BoundedSink(STREAM_BUDGET_BYTES), "stderr": _BoundedSink(STREAM_BUDGET_BYTES)}
- # started and registered under the guard so a stop can neither miss this group nor race a new one
- with _LIVE_GUARD:
- if _STOPPING.is_set():
- raise ProcessStopping(f"not starting {cmd[0]!r}: this process is stopping")
- self.proc: subprocess.Popen[bytes] = subprocess.Popen(
- list(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,
- start_new_session=True,
- preexec_fn=preexec_fn,
- )
- _LIVE.add(self)
+ self.proc: subprocess.Popen[bytes] = subprocess.Popen(
+ list(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,
+ start_new_session=True,
+ preexec_fn=preexec_fn,
+ )
assert self.proc.stdout is not None and self.proc.stderr is not None
self._pumps = [
threading.Thread(target=self._pump, args=(self.proc.stdout, "stdout"), daemon=True),
@@ -260,14 +250,10 @@ class ManagedProcess:
# start_new_session children never see Ctrl-C, so the group dies here on any exception or
# if still alive. Ask whether the GROUP exists, not the leader (it may exit 0 with
# grandchildren running).
- try:
- self.proc.poll()
- if _group_alive(self.proc.pid):
- self.terminate()
- self._drain_and_reap()
- finally:
- with _LIVE_GUARD:
- _LIVE.discard(self)
+ self.proc.poll()
+ if _group_alive(self.proc.pid):
+ self.terminate()
+ self._drain_and_reap()
def _drain_and_reap(self) -> None:
deadline = time.monotonic() + DRAIN_TIMEOUT_S # module global on purpose: tests dial it down
@@ -282,49 +268,8 @@ class ManagedProcess:
self._abandoned = _STILL_HELD if _group_alive(self.proc.pid) else _ABANDONED
-#: every :class:`ManagedProcess` whose group may still be alive; a stop signal kills these
-#: (signals reach only the main thread, so worker-thread ``__exit__`` never runs).
-_LIVE: set[ManagedProcess] = set()
-_LIVE_GUARD = threading.Lock()
-_STOPPING = threading.Event()
-STOP_GRACE_S = 30.0
-
-
-class ProcessStopping(RuntimeError):
- """A child was requested after this process began to stop."""
-
-
-def kill_live_children() -> int:
- with _LIVE_GUARD:
- _STOPPING.set()
- live = list(_LIVE)
- for mp in live:
- mp.kill()
- return len(live)
-
-
-def install_stop_handlers() -> None:
- """SIGTERM / SIGINT kill every live child group, refuse new ones, then end the process
- (``KeyboardInterrupt`` / exit 143), outright after :data:`STOP_GRACE_S`. Main thread only."""
- if threading.current_thread() is not threading.main_thread():
- return
-
- def stop(signum: int, _frame: object) -> None:
- kill_live_children()
- status = 130 if signum == signal.SIGINT else 128 + signum
- backstop = threading.Timer(STOP_GRACE_S, os._exit, args=(status,))
- backstop.daemon = True
- backstop.start()
- if signum == signal.SIGINT:
- raise KeyboardInterrupt
- raise SystemExit(status)
-
- for sig in (signal.SIGTERM, signal.SIGINT):
- signal.signal(sig, stop)
-
-
# ------------------------------------------------------------------ env scrubbing
-#: The one owner of the credential patterns (``agents/cli_common.clean_env`` uses :func:`scrub_secrets`).
+#: The one owner of the credential patterns.
_SECRET_EXACT: frozenset[str] = frozenset({
"GEMINI_API_KEYS", "GEMINI_API_KEY", "GOOGLE_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY",
"OPENAI_ORG_ID", "HF_TOKEN", "HUGGINGFACE_TOKEN", "GITHUB_TOKEN", "GH_TOKEN",
@@ -410,228 +355,6 @@ def read_json_or_none(path: Path | str, *, errors: str | None = None) -> dict[st
return data if isinstance(data, dict) else None
-def iter_jsonl_lines(path: Path | str) -> Iterator[tuple[int, str]]:
- """``(line_no, line)`` for every non-blank line of a JSONL file, 1-based.
-
- Missing file → nothing; invalid bytes are replaced so one bad byte costs at most that line.
- """
- p = Path(path)
- if not p.is_file():
- return
- for i, line in enumerate(p.read_text(encoding="utf-8", errors="replace").splitlines()):
- if line.strip():
- yield i + 1, line
-
-
-def read_jsonl_lenient(
- path: Path | str, *, log: logging.Logger | None = None, dicts_only: bool = False
-) -> list[Any]:
- """Every parseable JSON line of ``path``; unparseable lines are skipped (debug-logged
- to ``log`` when given), ``dicts_only`` also drops non-object rows.
- """
- out: list[Any] = []
- for i, line in iter_jsonl_lines(path):
- try:
- row = json.loads(line)
- except ValueError as e:
- if log is not None:
- log.debug("%s:%d unreadable: %s", path, i, e)
- continue
- if dicts_only and not isinstance(row, dict):
- continue
- out.append(row)
- return out
-
-
-def append_jsonl_line(path: Path | str, rec: Any, lock: threading.Lock) -> None:
- line = json.dumps(rec, ensure_ascii=False, default=str)
- with lock, Path(path).open("a", encoding="utf-8") as fh:
- fh.write(line + "\n")
-
-
-# ===================================================================== events
-log = logging.getLogger(__name__)
-
-
-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_jsonl_line(self.path, {"t": round(time.time(), 3), "event": event, **data}, self._lock)
-
- def read(self) -> list[dict[str, Any]]:
- return read_jsonl_lenient(self.path, log=log, dicts_only=True)
-
-
-class _NullEvents:
- """An event sink that drops everything."""
-
- def emit(self, event: str, **data: Any) -> None:
- pass
-
-
-#: use ``NULL_EVENTS if events is None else events``, never ``events or NULL_EVENTS`` (an empty fake log is falsy)
-NULL_EVENTS = _NullEvents()
-
-
-# ===================================================================== runlock
-LOCKS_DIR = ".locks"
-
-
-class RunLocked(RuntimeError):
- """Another process or thread is already running this run."""
-
-
-def _held_message(run_root: Path | str, held: dict, *, action: str) -> str:
- started = time.strftime("%H:%M:%S", time.localtime(held.get("started", 0)))
- name = Path(run_root).name
- return (
- f"refusing to {action} run {name}: it is being run right now by pid {held.get('pid', '?')} "
- f"(started {started}: {held.get('what') or '3dcodeverse'}). Two processes on one run "
- f"corrupt each other's state. Look at it with `3dcodeverse status {name}`, or stop that "
- f"ONE process with `kill {held.get('pid', '?')}` — never `pkill -f 3dcodeverse`, which kills every "
- f"other run on this machine too."
- )
-
-
-def flock_path(run_root: Path | str) -> Path:
- root = Path(run_root).resolve()
- return root.parent / LOCKS_DIR / f"{root.name}.lock"
-
-
-_HELD: dict[str, list] = {} # flock path -> [fd, owning thread ident] held by THIS process
-_HELD_GUARD = threading.Lock()
-
-
-def _record_of(fd: int) -> dict | None:
- try:
- os.lseek(fd, 0, os.SEEK_SET)
- raw = os.read(fd, 4096).decode("utf-8", "replace").strip()
- rec = json.loads(raw) if raw else None
- except (OSError, ValueError):
- return None
- return rec if isinstance(rec, dict) else None
-
-
-def _write_record(fd: int, rec: dict) -> None:
- os.ftruncate(fd, 0)
- os.lseek(fd, 0, os.SEEK_SET)
- os.write(fd, json.dumps(rec).encode())
- os.fsync(fd)
-
-
-def holder_of(run_root: Path | str) -> dict | None:
- """The ``{pid, started, what}`` of whoever holds this run, without taking it; ``None`` if nobody
- does (a stale record left by a SIGKILL is detected by probing the flock)."""
- try:
- fd = os.open(flock_path(run_root), os.O_RDONLY)
- except OSError:
- return None
- try:
- try:
- fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
- except OSError:
- return _record_of(fd) # refused: somebody is holding it right now
- fcntl.flock(fd, fcntl.LOCK_UN)
- return None
- finally:
- os.close(fd)
-
-
-@contextmanager
-def exclusive(run_root: Path | str, *, what: str = "", action: str = "enter") -> Iterator[None]:
- """THE mutex for one run: hold it around every mutation of the run directory.
-
- Raises :class:`RunLocked` when another process or thread holds it; the same thread re-enters."""
- key, me = str(flock_path(run_root)), threading.get_ident()
- with _HELD_GUARD:
- entry = _HELD.get(key)
- if entry is not None:
- if entry[1] != me:
- raise RunLocked(_held_message(run_root, holder_of(run_root) or {}, action=action))
- yield # re-entry: the outermost `with` owns the release
- return
- path = Path(key)
- path.parent.mkdir(parents=True, exist_ok=True)
- fd = os.open(path, os.O_CREAT | os.O_RDWR, 0o644)
- try:
- fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
- except OSError:
- held = _record_of(fd) or {}
- os.close(fd)
- raise RunLocked(_held_message(run_root, held, action=action)) from None
- except BaseException:
- os.close(fd)
- raise
- try: # a failed write must not leak the lock
- _write_record(fd, {"pid": os.getpid(), "started": time.time(), "what": what})
- with _HELD_GUARD:
- _HELD[key] = [fd, me]
- yield
- finally:
- with _HELD_GUARD:
- _HELD.pop(key, None)
- try:
- os.ftruncate(fd, 0) # the file stays (unlinking it races a waiter's open)
- fcntl.flock(fd, fcntl.LOCK_UN)
- except OSError:
- pass
- finally:
- os.close(fd)
-
-
-# ===================================================================== fanout
-
-
-def fan_out[T, R](
- items: Sequence[T] | Iterable[T],
- fn: Callable[[T], R],
- max_workers: int,
- *,
- label: str = "fanout",
- item_name: Callable[[T], str] | 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``.
- """
- items = list(items)
- ctx_snapshot = contextvars.copy_context()
- 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()
-
- 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
- results[i] = out
- log.info("%s[%s] done in %.1fs (%s)", label, name, dt, "error" if isinstance(out, Exception) else "ok")
-
- if workers == 1:
- for i in range(len(items)):
- _run(i)
- else:
- with ThreadPoolExecutor(max_workers=workers, thread_name_prefix=label) as pool:
- list(pool.map(lambda i: ctx_snapshot.copy().run(_run, i),
- range(len(items))))
-
- n_failed = sum(1 for r in results if isinstance(r, Exception))
- log.info("%s: %d/%d ok in %.1fs", label, len(items) - n_failed, len(items), time.time() - t_all)
- return results
-
-
class SlotsBusy(RuntimeError):
"""Every slot stayed busy past the wait budget."""
@@ -692,7 +415,7 @@ class Slots:
os.close(fd)
def busy(self) -> int:
- """How many slots are held machine-wide (``3dcodeverse doctor``); never takes one."""
+ """How many slots are held machine-wide (``3dcode doctor``); never takes one."""
n = 0
for i in range(self.n):
try:
diff --git a/harness/codeverse3d/prompts/__init__.py b/harness/codeverse3d/prompts/__init__.py
deleted file mode 100644
index 07ffbdfa..00000000
--- a/harness/codeverse3d/prompts/__init__.py
+++ /dev/null
@@ -1,37 +0,0 @@
-"""Prompt loader: markdown + jinja2 templates, content-hashed for provenance.
-
-Plain files under ``prompts/``; ``render`` runs a jinja template with strict undefined variables.
-"""
-
-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
-
-_FLAGS: dict[str, Any] = {"undefined": StrictUndefined, "trim_blocks": True, "lstrip_blocks": True,
- "keep_trailing_newline": True, "autoescape": False}
-
-_env = Environment(loader=FileSystemLoader(str(PROMPTS_DIR)), **_FLAGS)
-
-
-@lru_cache(maxsize=512)
-def load_text(rel_path: str) -> str:
- 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``; a missing name raises (StrictUndefined)."""
- return _env.get_template(rel_path).render(**ctx)
-
-
-def prompt_hash(text: str) -> str:
- return hashlib.sha256(text.encode()).hexdigest()[:12]
diff --git a/harness/codeverse3d/prompts/catalog.py b/harness/codeverse3d/prompts/catalog.py
deleted file mode 100644
index 2aed8262..00000000
--- a/harness/codeverse3d/prompts/catalog.py
+++ /dev/null
@@ -1,42 +0,0 @@
-"""What prompt material exists and how each piece reaches the model.
-
-* PROMPT material: what the harness writes into a message; lives under ``codeverse3d/prompts/`` and
- is found through :func:`language_prompt`.
-* AGENT-read bundles: ``codeverse3d/skills/c3d-*/``, which the agent chooses to read.
-"""
-
-from __future__ import annotations
-
-from collections.abc import Sequence
-
-from codeverse3d.contracts.common import Language
-from codeverse3d.prompts import load_text
-
-PROMPT_DIRS: dict[Language, str] = {Language.URDF_BLENDER: "urdf"}
-
-
-def language_prompt(language: Language, name: str) -> str:
- """``<dir>/<name>`` under ``prompts/``: the path of a language's ``contract.md`` / ``system.md`` etc."""
- return f"{PROMPT_DIRS.get(language, language.value)}/{name}"
-
-
-def language_text(language: Language, name: str) -> str:
- """The text of :func:`language_prompt`, or ``""`` for a file the language does not ship."""
- try:
- return load_text(language_prompt(language, name))
- except FileNotFoundError:
- return ""
-
-
-def contract_sections(text: str, headings: Sequence[str]) -> str:
- """The ``## `` sections of a contract whose heading starts with one of ``headings``, in the
- contract's order, under its preamble."""
- out: list[str] = []
- keep = True
- for line in text.splitlines():
- if line.startswith("## "):
- title = line[3:].strip()
- keep = any(title.startswith(h) for h in headings)
- if keep:
- out.append(line)
- return "\n".join(out).rstrip() + "\n"
diff --git a/harness/codeverse3d/reference.py b/harness/codeverse3d/reference.py
deleted file mode 100644
index a9d5b8f9..00000000
--- a/harness/codeverse3d/reference.py
+++ /dev/null
@@ -1,73 +0,0 @@
-"""Reference comparison: the brief's dimension band vs the outline of the user's own ``--image``
-picture (:func:`dimension_conflict`; the BRIEF wins on a conflict)."""
-
-from __future__ import annotations
-
-from pathlib import Path
-from typing import Any
-
-from codeverse3d.contracts.spec import Spec
-
-# ===================================================================== proportions
-
-#: relative aspect disagreement above which the picture's proportions are not a target
-ASPECT_TOL = 0.25
-
-#: brief keys that describe a HORIZONTAL extent of the object
-_WIDTH_KEYS = ("width", "length", "depth", "diameter")
-
-
-def expected_aspect_range(spec: Spec) -> tuple[float, float] | None:
- """The width/height band any straight-on elevation of the brief could show (a RANGE, since the
- brief does not say which face a photograph shows)."""
- dims = spec.constraints.dimensions_m or {}
- height = dims.get("height")
- if not height or height <= 0:
- return None
- widths = [float(dims[k]) for k in _WIDTH_KEYS if dims.get(k) and float(dims[k]) > 0]
- if not widths:
- return None
- return min(widths) / float(height), max(widths) / float(height)
-
-
-def expected_front_aspect(spec: Spec) -> float | None:
- rng = expected_aspect_range(spec)
- return None if rng is None else (rng[0] + rng[1]) / 2
-
-
-def dimension_conflict(spec: Spec, image: Path | str) -> dict[str, Any]:
- """``{conflict, expected_aspect, image_aspect, error}`` — never raises; conflict only when the
- image's silhouette aspect is off the brief's band by more than :data:`ASPECT_TOL`."""
- rng = expected_aspect_range(spec)
- out: dict[str, Any] = {"conflict": False, "expected_aspect": expected_front_aspect(spec),
- "expected_range": list(rng) if rng else None, "image_aspect": None, "error": ""}
- if rng is None:
- return out
- low, high = rng
- try:
- from codeverse3d.spatial.silhouette import silhouette_aspect
-
- got = float(silhouette_aspect(image))
- except Exception as e: # noqa: BLE001 — an advisory check must never fail a run
- out["error"] = f"{type(e).__name__}: {e}"
- return out
- out["image_aspect"] = round(got, 4)
- if got <= 0:
- out["error"] = "empty foreground mask"
- return out
- off = 0.0 if low <= got <= high else (low - got) / low if got < low else (got - high) / high
- out["relative_error"] = round(off, 4)
- out["conflict"] = off > ASPECT_TOL
- return out
-
-
-def conflict_note(info: dict[str, Any]) -> str:
- if not info.get("conflict"):
- return ""
- lo, hi = info.get("expected_range") or (0.0, 0.0)
- return (f"REFERENCE PROPORTIONS DISAGREE WITH THE BRIEF: the picture's outline is "
- f"{info['image_aspect']:.2f} wide/high, outside the {lo:.2f}-{hi:.2f} band the stated dimensions "
- f"allow ({info['relative_error']:.0%} outside it) — usually a part reaching outside the stated box, "
- f"or the object resting in a different orientation. The BRIEF's dimensions are correct; use the "
- f"reference for the part inventory and the shape of each part, NOT for the overall proportions. "
- f"The measured silhouette score is therefore neutral and must not be read as a proportion verdict.")
diff --git a/harness/codeverse3d/spatial/mcp_server.py b/harness/codeverse3d/spatial/mcp_server.py
deleted file mode 100644
index eacd42f9..00000000
--- a/harness/codeverse3d/spatial/mcp_server.py
+++ /dev/null
@@ -1,189 +0,0 @@
-"""stdio MCP server exposing the spatial tool registry to coding agents.
-
- python -m codeverse3d.spatial.mcp_server --workspace <ws> [--track X] [--language Y] [--round N]
-
-One MCP tool per registry tool; a result is one bounded text block plus bounded base64 PNG images. ``is_error`` means the tool could not run, never a FAIL verdict. Track / language default to ``<ws>/spec.json``.
-"""
-
-from __future__ import annotations
-
-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 codeverse3d import __version__
-from codeverse3d.spatial.observe import fmt_numbers, truncate
-from codeverse3d.spatial.registry import Observation, ToolContext, list_tools
-from codeverse3d.spatial.tool_common import spec_dict
-from codeverse3d.workspace import Workspace
-
-MAX_IMAGES = 4
-MAX_IMAGE_SIDE = 1024
-MAX_NUMBERS_CHARS = 1200
-#: ceiling on the text block of one result (text + numbers)
-MAX_TEXT_CHARS = 6000
-#: ceiling on the encoded image bytes of one result; an over-budget sheet is downscaled, not dropped
-MAX_IMAGE_BYTES = 400_000
-#: long sides tried when the first image does not fit
-IMAGE_FALLBACK_SIDES = (768, 512, 384)
-SERVER_NAME = "3dcode"
-
-
-def build_context(workspace: Path, *, track: str = "", language: str = "", round_index: int = 0) -> ToolContext:
- """ToolContext for ``workspace``; track/language fall back to spec.json."""
- ctx = ToolContext(workspace=Workspace(workspace), round_index=round_index, language=language, track=track)
- if not track or not language:
- spec = spec_dict(ctx)
- ctx.track = track or str(spec.get("track", ""))
- ctx.language = language or str(spec.get("language", ""))
- return ctx
-
-
-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 max_images_for(obs: Observation) -> int:
- """Image budget: none for a failed call (vendor CLIs stringify ``is_error`` results, base64 included), one for FAIL, ``MAX_IMAGES`` for a pass."""
- if obs.failed:
- return 0
- return MAX_IMAGES if obs.ok else 1
-
-
-def _fit_first(path: str, budget: int) -> tuple[str | None, int]:
- """The first image (the contact sheet), re-encoded smaller until it fits ``budget``: ``(base64, long side)`` or ``(None, 0)``."""
- b64 = encode_image(path)
- if b64 is not None and len(b64) <= budget:
- return b64, MAX_IMAGE_SIDE
- for side in IMAGE_FALLBACK_SIDES:
- smaller = encode_image(path, max_side=side)
- if smaller is not None and len(smaller) <= budget:
- return smaller, side
- return None, 0
-
-
-def observation_content(obs: Observation) -> list[Any]:
- """Observation → bounded MCP content blocks (text first, then images)."""
- from mcp import types
-
- text = obs.text
- if obs.numbers:
- nums = json.dumps(obs.numbers, default=str)
- text += "\n" + (nums if len(nums) <= MAX_NUMBERS_CHARS else fmt_numbers(obs.numbers))
- # the slice makes the ceiling hard: truncate's omitted-marker overshoots its budget
- blocks: list[Any] = [types.TextContent(type="text", text=truncate(text, MAX_TEXT_CHARS)[:MAX_TEXT_CHARS])]
- # images[0] is the contact sheet; later images repeat it per view, so the budget stops at
- # the first that does not fit. Dropped images are always said in the text.
- wanted = obs.images[:max_images_for(obs)]
- kept, spent, dropped, shrunk = [], 0, 0, 0
- for i, p in enumerate(wanted):
- b64 = encode_image(p)
- if i == 0 and b64 is not None and len(b64) > MAX_IMAGE_BYTES:
- b64, side = _fit_first(p, MAX_IMAGE_BYTES)
- shrunk = side
- if b64 is None:
- dropped += 1
- continue
- if spent + len(b64) > MAX_IMAGE_BYTES:
- dropped += len(wanted) - len(kept) - dropped
- break
- spent += len(b64)
- kept.append(b64)
- notes = []
- if shrunk:
- notes.append(f"[the sheet was re-encoded at {shrunk} px to fit the "
- f"{MAX_IMAGE_BYTES}-byte payload bound]")
- if dropped:
- notes.append(f"[{dropped} image(s) not attached: over the {MAX_IMAGE_BYTES}-byte "
- "payload bound or unreadable; the files are in the workspace]")
- if notes:
- # the note takes room from the body so the text ceiling holds
- tail = "\n" + "\n".join(notes)
- body = blocks[0].text[:max(0, MAX_TEXT_CHARS - len(tail))]
- blocks[0] = types.TextContent(type="text", text=body + tail)
- for b64 in kept:
- blocks.append(types.ImageContent(type="image", data=b64, mime_type="image/png"))
- return blocks
-
-
-async def call_tool(ctx: ToolContext, defs: dict[str, Any], params: Any) -> Any:
- """One MCP tool call → ``CallToolResult``; ``is_error`` is ``Observation.failed``, not ``not ok`` (vendors retry MCP errors)."""
- from mcp import types
-
- tdef = defs.get(params.name)
- 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=obs.failed)
-
-
-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 list_tools(track=ctx.track, language=ctx.language)}
-
- 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:
- return await call_tool(ctx, defs, params)
-
- return Server(SERVER_NAME, version=__version__,
- 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="codeverse3d.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 list_tools(track=ctx.track, language=ctx.language)], indent=1))
- return 0
- asyncio.run(serve_stdio(ctx))
- return 0
-
-
-if __name__ == "__main__":
- sys.exit(main())
diff --git a/harness/codeverse3d/spatial/registry.py b/harness/codeverse3d/spatial/registry.py
index 09571c8b..fd3a3fe7 100644
--- a/harness/codeverse3d/spatial/registry.py
+++ b/harness/codeverse3d/spatial/registry.py
@@ -1,4 +1,4 @@
-"""Tool registry: one ``@tool(name, ArgsModel, description)`` definition → python fn + JSON schema + MCP + prompt card.
+"""Tool registry: one ``@tool(name, ArgsModel, description)`` definition → python fn + typed args + a ``3dcode`` subcommand.
``ToolDef.call`` is the one error boundary: tool bodies never need try/except.
"""
@@ -22,7 +22,7 @@ class NoArgs(BaseModel):
class Observation(BaseModel):
"""A tool's answer: ``ok`` is the VERDICT, ``failed`` says the tool could not run.
- Only ``failed`` becomes MCP ``is_error``; a negative verdict is a result, not a broken call.
+ Only ``failed`` makes ``3dcode`` exit non-zero; a negative verdict is a result, not a broken call.
"""
# validate_assignment: the failed-implies-not-ok invariant must hold on later assignment too
@@ -31,9 +31,9 @@ class Observation(BaseModel):
ok: bool = True
failed: bool = Field(default=False, description="the tool could not run: exception, missing "
"artefact, unusable arguments (NOT a negative verdict)")
- text: str = Field(description="human/LLM-readable summary (≤ ~2k chars)")
+ text: str = Field(description="human/LLM-readable summary (verdict first)")
numbers: dict[str, Any] = Field(default_factory=dict)
- images: list[str] = Field(default_factory=list, description="PNG paths (small, labelled)")
+ images: list[str] = Field(default_factory=list, description="PNG paths the agent opens with its own viewer")
duration_ms: int = 0
@model_validator(mode="after")
@@ -84,18 +84,6 @@ class ToolDef:
s.pop("title", None)
return s
- def card(self) -> str:
- """Prompt card: name, purpose, args with descriptions."""
- props = self.schema().get("properties", {})
- req = set(self.schema().get("required", []))
- lines = [f"- `{self.name}` ({self.cost_hint}): {self.description}"]
- 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
@@ -108,7 +96,7 @@ class ToolDef:
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
+ except Exception as e: # the CLI reports it; it never tracebacks at the agent
obs = Observation.error(f"{self.name} failed: {type(e).__name__}: {e}")
obs.duration_ms = int((time.time() - t0) * 1000)
return obs
@@ -157,10 +145,7 @@ def list_tools(*, track: str = "", language: str = "") -> list[ToolDef]:
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))
-
-
def _ensure_loaded() -> None:
- """Import the module that registers every tool."""
+ """Import the modules that register every tool."""
import codeverse3d.spatial.tools # noqa: F401 — its @tool decorators fill _REGISTRY
+ import codeverse3d.workflow # noqa: F401 — init / validate_plan / check / judge_pack / score
diff --git a/harness/codeverse3d/spatial/render_blender.py b/harness/codeverse3d/spatial/render_blender.py
index f44b9b79..20db9173 100644
--- a/harness/codeverse3d/spatial/render_blender.py
+++ b/harness/codeverse3d/spatial/render_blender.py
@@ -26,8 +26,14 @@ from codeverse3d.conventions import (
from_authoring_frame,
to_authoring_frame,
)
-from codeverse3d.proc import Slots, SlotsBusy
-from codeverse3d.proc import ProcResult, read_json_or_none, run_subprocess, write_json_atomic
+from codeverse3d.proc import (
+ ProcResult,
+ Slots,
+ SlotsBusy,
+ read_json_or_none,
+ run_subprocess,
+ write_json_atomic,
+)
from codeverse3d.spatial._render_common import out_directory, view_specs
from codeverse3d.spatial.render_scene import (
MAX_JUDGE_OVERVIEWS,
diff --git a/harness/codeverse3d/spatial/scene_placement.py b/harness/codeverse3d/spatial/scene_placement.py
index ccd753de..4b16116d 100644
--- a/harness/codeverse3d/spatial/scene_placement.py
+++ b/harness/codeverse3d/spatial/scene_placement.py
@@ -682,20 +682,6 @@ def setting_text(plan: Any) -> str:
return " ".join(str(getattr(plan, k, "") or "") for k in ("setting", "environment", "title"))
-def placement_gate(ws: Workspace, census: dict[str, Any] | None, plan: Any) -> GateReport | None:
- """THE ``scene_placement`` verdict."""
- assets = _stage_result(ws, "assets")
- unavailable = [name for name, r in assets.items() if isinstance(r, dict) and not r.get("ok", True)]
- return placement_gate_safe(census, plan=plan, layouts=_stage_result(ws, "layouts"), unavailable=unavailable)
-
-
-def _stage_result(ws: Workspace, name: str) -> dict[str, Any]:
- """A cached stage's result (``orchestrator.StageRunner`` writes ``stages/<name>.json``),
- ``{}`` when absent."""
- res = (read_json_or_none(ws.stages / f"{name}.json") or {}).get("result")
- return res if isinstance(res, dict) else {}
-
-
def placement_gate_safe(census: dict[str, Any] | None, *, plan: Any = None,
layouts: dict[str, Any] | None = None, unavailable: Sequence[str] = ()) -> GateReport | None:
"""Round-gate entry."""
diff --git a/harness/codeverse3d/spatial/silhouette.py b/harness/codeverse3d/spatial/silhouette.py
index f902e78f..cb1a4029 100644
--- a/harness/codeverse3d/spatial/silhouette.py
+++ b/harness/codeverse3d/spatial/silhouette.py
@@ -231,8 +231,6 @@ def measure_reference(renders: Sequence[RenderView], spec: Spec, *, compare: Com
""":class:`ReferenceMatch` of ``renders`` against ``spec``'s target reference, or ``None``
when the spec has no readable reference or no render view could be compared. ``conflict`` is
the caller's own :func:`dimension_conflict` of the same reference, when it already has it."""
- from codeverse3d.reference import dimension_conflict # reference.py imports this module
-
ref = target_reference(spec.references)
if ref is None:
return None
@@ -242,3 +240,46 @@ def measure_reference(renders: Sequence[RenderView], spec: Spec, *, compare: Com
num = {k: float(res[k]) for k in ("ref_fill", "render_fill", "aspect_ratio_err", "ref_aspect", "render_aspect") if isinstance(res.get(k), int | float)}
return ReferenceMatch(iou=float(res["iou"]), view=str(res.get("view", "")), reference=ref, reliable=bool(res.get("reliable", True)),
conflict=bool((conflict if conflict is not None else dimension_conflict(spec, ref)).get("conflict")), per_view=res.get("per_view") or {}, **num)
+
+
+# ===================================================================== brief vs picture
+#: relative aspect disagreement above which the picture's proportions are not a target
+ASPECT_TOL = 0.25
+#: brief keys that describe a HORIZONTAL extent of the object
+_WIDTH_KEYS = ("width", "length", "depth", "diameter")
+
+
+def expected_aspect_range(spec: Spec) -> tuple[float, float] | None:
+ """The width/height band any straight-on elevation of the brief could show (a RANGE, since the
+ brief does not say which face a photograph shows)."""
+ dims = spec.constraints.dimensions_m or {}
+ height = dims.get("height")
+ if not height or height <= 0:
+ return None
+ widths = [float(dims[k]) for k in _WIDTH_KEYS if dims.get(k) and float(dims[k]) > 0]
+ if not widths:
+ return None
+ return min(widths) / float(height), max(widths) / float(height)
+
+
+def dimension_conflict(spec: Spec, image: Path | str) -> dict[str, Any]:
+ """``{conflict, expected_range, image_aspect, error}`` — never raises; conflict only when the
+ image's silhouette aspect is off the brief's band by more than :data:`ASPECT_TOL` (the BRIEF wins)."""
+ rng = expected_aspect_range(spec)
+ out: dict[str, Any] = {"conflict": False, "expected_range": list(rng) if rng else None, "image_aspect": None, "error": ""}
+ if rng is None:
+ return out
+ low, high = rng
+ try:
+ got = float(silhouette_aspect(image))
+ except Exception as e: # noqa: BLE001 — an advisory check must never fail a verdict
+ out["error"] = f"{type(e).__name__}: {e}"
+ return out
+ out["image_aspect"] = round(got, 4)
+ if got <= 0:
+ out["error"] = "empty foreground mask"
+ return out
+ off = 0.0 if low <= got <= high else (low - got) / low if got < low else (got - high) / high
+ out["relative_error"] = round(off, 4)
+ out["conflict"] = off > ASPECT_TOL
+ return out
diff --git a/harness/codeverse3d/spatial/tools.py b/harness/codeverse3d/spatial/tools.py
index 13332337..ef32000c 100644
--- a/harness/codeverse3d/spatial/tools.py
+++ b/harness/codeverse3d/spatial/tools.py
@@ -1,6 +1,6 @@
-"""Every spatial tool registered with ``@tool``; importing this module registers them all.
+"""Every spatial instrument registered with ``@tool``; importing this module registers them all.
-Observations are compact (errors first, fix hints attached) and their text never carries absolute host paths.
+Observations are compact (errors first, fix hints attached); image paths are absolute so the agent can open them.
"""
from __future__ import annotations
@@ -39,7 +39,7 @@ from codeverse3d.spatial.observe import (
from codeverse3d.spatial.probes import run_probe
from codeverse3d.spatial.registry import NoArgs, Observation, ToolContext, ToolUsageError, tool
from codeverse3d.spatial.scene_placement import placement_census as _placement_census
-from codeverse3d.spatial.scene_placement import placement_gate, placement_table_text
+from codeverse3d.spatial.scene_placement import placement_gate_safe, placement_table_text
from codeverse3d.spatial.sections import cross_section as _cross_section
from codeverse3d.spatial.sheet import contact_sheet
from codeverse3d.spatial.silhouette import compare_silhouette as _compare_silhouette
@@ -493,7 +493,7 @@ def check_placement(ctx: ToolContext, args: CheckPlacementArgs) -> Observation:
plan = load_plan(ws.plan_path)
except ToolUsageError:
plan = None
- report = placement_gate(ws, census, plan)
+ report = placement_gate_safe(census, plan=plan)
if report is None:
return Observation.error("check_placement: the census carries no placement table")
obs = gate_observation(report, title="placement check")
diff --git a/harness/codeverse3d/tracks/__init__.py b/harness/codeverse3d/tracks/__init__.py
deleted file mode 100644
index 5ad74ff0..00000000
--- a/harness/codeverse3d/tracks/__init__.py
+++ /dev/null
@@ -1,39 +0,0 @@
-"""Tracks: static_object · articulated_object · scene · graphics.
-
-``get_track(Track.X)`` builds the track: a ``lifecycle.BaseTrack``, whose ``run()`` the
-orchestrator drives. (Formerly ``tracks/base.py`` — folded into the package root
-2026-08-28: its only importer was this ``__init__``.)
-"""
-
-from __future__ import annotations
-
-from typing import TYPE_CHECKING, Any
-
-from codeverse3d.contracts.common import Track
-
-if TYPE_CHECKING:
- from codeverse3d.tracks.lifecycle import BaseTrack
-
-
-def get_track(track: Track | str, **options: Any) -> BaseTrack:
- """Track instance for ``track``. ``options`` are forwarded to the track
- constructor (e.g. ``policy=``)."""
- t = Track(track)
- if t is Track.STATIC_OBJECT:
- from codeverse3d.tracks.static_object import StaticObjectTrack
-
- return StaticObjectTrack(**options)
- if t is Track.ARTICULATED_OBJECT:
- from codeverse3d.tracks.articulated_object import ArticulatedObjectTrack
-
- return ArticulatedObjectTrack(**options)
- if t is Track.GRAPHICS:
- from codeverse3d.tracks.graphics import GraphicsTrack
-
- return GraphicsTrack(**options)
- from codeverse3d.tracks.scene import SceneTrack
-
- return SceneTrack(**options)
-
-
-__all__ = ["get_track"]
diff --git a/harness/codeverse3d/tracks/articulated_object.py b/harness/codeverse3d/tracks/articulated_object.py
deleted file mode 100644
index 2c15d809..00000000
--- a/harness/codeverse3d/tracks/articulated_object.py
+++ /dev/null
@@ -1,354 +0,0 @@
-"""ArticulatedObjectTrack."""
-
-from __future__ import annotations
-
-import logging
-import time
-import xml.etree.ElementTree as ET
-from collections.abc import Sequence
-from pathlib import Path
-
-from codeverse3d.config import get_settings
-from codeverse3d.contracts.artifacts import (
- BuildResult,
- GateFinding,
- GateReport,
- Measurement,
- RenderSet,
- RenderView,
- Severity,
-)
-from codeverse3d.contracts.common import TRACK_INFO, Track
-from codeverse3d.contracts.plan import ArticulatedPlan, Plan
-from codeverse3d.conventions import to_snake
-from codeverse3d.spatial.render import RenderError
-from codeverse3d.tracks.common import RunContext
-from codeverse3d.tracks.static_object import ObjectPipeline, StaticObjectTrack
-from codeverse3d.workspace import Workspace
-
-log = logging.getLogger(__name__)
-
-
-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)
- repaired, pre = self._axis_repair(ctx)
- 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
- out.append(report)
- motion = pre if pre is not None and not repaired else self._motion_gate(ctx) # the file changed only if repaired
- if motion is not None:
- if repaired:
- motion.findings.append(GateFinding(
- gate=MOTION_GATE, severity=Severity.INFO, target=", ".join(repaired),
- message=(f"harness axis repair rewrote <axis xyz> of {', '.join(repaired)} in src/robot.urdf "
- "(measured motion was provably wrong) — build on it, do not undo it")))
- out.append(motion)
- return out
-
- @staticmethod
- def _axis_repair(ctx: RunContext) -> tuple[list[str], GateReport | None]:
- """(joints repaired, the motion report measured before the repair); ``(…, None)`` when it did not run."""
- if not get_settings().axis_repair:
- return [], None
- try:
- pre = ctx.services.motion_checks(ctx.ws, ctx.plan)
- repaired = repair_motion_axes(ctx.ws, pre)
- except Exception as e: # noqa: BLE001 — advisory repair; the gate still reports truth
- log.warning("axis repair skipped: %s", e)
- return [], None
- if repaired:
- ctx.events.emit("gate.axis_repaired", joints=repaired)
- return repaired, pre
-
- @staticmethod
- def _motion_gate(ctx: RunContext) -> GateReport | None:
- """Planned motion text ("pulls out to the front") vs the URDF's real direction."""
- try:
- return ctx.services.motion_checks(ctx.ws, ctx.plan)
- except Exception as e: # noqa: BLE001 — advisory gate; the sweep gate is the hard one
- log.warning("motion direction checks failed: %s", e)
- ctx.events.emit("gate.motion_failed", error=f"{type(e).__name__}: {e}")
- return None
-
- 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 judge_context(self, ws: Workspace, plan: Plan | None, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
- from codeverse3d.spatial.joints_sweep import SWEEP_GATE
-
- report = next((g for g in gates if g.gate == SWEEP_GATE), None)
- motion = next((g for g in gates if g.gate == MOTION_GATE), 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])
- if motion is not None:
- wrong = [f"- {f.target}: {f.message}" for f in motion.errors]
- lines.append("Motion direction (harness FK check): " + ("all planned directions realised" if not wrong else f"{len(wrong)} WRONG"))
- lines.extend(wrong[:6])
- return "\n".join(lines)
-
-
-class ArticulatedObjectTrack(StaticObjectTrack):
- track = Track.ARTICULATED_OBJECT
- rubric = TRACK_INFO[Track.ARTICULATED_OBJECT].rubric
- plan_model = ArticulatedPlan
- generate_template = "tracks/generate_articulated.j2"
-
- def make_pipeline(self) -> ArticulatedPipeline:
- return ArticulatedPipeline()
-
-
-# ----------------------------------------------------------------------------- sweep adapter
-def default_joint_sweep(ws: Workspace, plan: Plan | None, out_dir: Path) -> tuple[GateReport, list[RenderView]]:
- # ``plan`` is unread here (the sweep reads the URDF off disk); it stays for the Services signature.
- from codeverse3d.spatial.joints_export import ARTICULATION_SHEET_NAME, render_poses
- from codeverse3d.spatial.joints_sweep import SWEEP_GATE, sweep_gate
-
- gate, robot = sweep_gate(ws)
- views: list[RenderView] = []
- if robot is None:
- return gate, views
- out_dir.mkdir(parents=True, exist_ok=True)
- try:
- for label, rs in 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))
- except RenderError as e:
- # pose renders are the judge's evidence, not the gate's: a render failure must not fail the round
- log.warning("pose renders failed; the sweep gate stands without a sheet: %s", e)
- gate.findings.append(GateFinding(gate=SWEEP_GATE, severity=Severity.WARN, target="poses",
- message=f"pose renders failed ({str(e)[:160]}); the judge sees no articulation sheet this round",
- fix_hint="nothing to fix in the code: a render timeout under load"))
- sheet = out_dir / ARTICULATION_SHEET_NAME
- if sheet.is_file():
- views.insert(0, RenderView(name="articulation_sheet", path=str(sheet), mode="shaded"))
- return gate, views
-
-
-# ===================================================================== planned-motion gate
-MOTION_GATE = "motion_direction"
-#: its findings' ``data.kind``: the joint moves the way the plan says / the other way / not measured
-MOTION_OK, MOTION_WRONG, MOTION_SKIPPED = "as_planned", "wrong_direction", "skipped"
-
-#: phrase → direction key understood by ``spatial.joints_sweep.motion_direction_check``.
-#: Longer phrases first so "pulls out" wins over "out"; explicit axes first of all.
-_PHRASES: tuple[tuple[str, str], ...] = (
- ("-y", "-y"), ("+y", "+y"), ("-z", "-z"), ("+z", "+z"), ("-x", "-x"), ("+x", "+x"),
- ("towards the front", "front"), ("toward the front", "front"), ("to the front", "front"),
- ("opens to the front", "front"), ("opens out", "front"), ("pulls out", "front"), ("slides out", "front"),
- ("pull out", "front"), ("slide out", "front"), ("swings out", "front"), ("outward", "front"), ("forward", "front"),
- ("towards the viewer", "front"), ("toward the viewer", "front"), ("frontward", "front"),
- ("towards the back", "back"), ("toward the back", "back"), ("to the back", "back"), ("pushes in", "back"),
- ("slides in", "back"), ("backward", "back"), ("rearward", "back"), ("inward", "back"),
- ("upward", "up"), ("upwards", "up"), ("opens up", "up"), ("lifts", "up"), ("lift", "up"), ("raises", "up"),
- ("raise", "up"), ("rises", "up"),
- ("downward", "down"), ("downwards", "down"), ("lowers", "down"), ("drops", "down"),
- ("folds down", "down"), ("opens down", "down"),
- ("to the left", "left"), ("leftward", "left"), ("swings left", "left"),
- ("to the right", "right"), ("rightward", "right"), ("swings right", "right"),
- ("front", "front"), ("back", "back"), ("up", "up"), ("down", "down"), ("left", "left"), ("right", "right"),
- ("out", "front"),
-)
-
-_SKIP_MARKERS = ("not ", "n't", "either", "both", "around", "rotates about", "spins")
-_DIR_GROUPS = {"front": "y", "back": "y", "-y": "y", "+y": "y", "up": "z", "down": "z", "+z": "z", "-z": "z",
- "left": "x", "right": "x", "-x": "x", "+x": "x"}
-
-
-def expected_direction(motion: str) -> str | None:
- """Direction key for an obvious motion description, else ``None``."""
- text = " ".join((motion or "").lower().replace("_", " ").split())
- if not text or any(m in text for m in _SKIP_MARKERS):
- return None
- padded = f" {text} "
- hits: list[str] = []
- for phrase, key in _PHRASES:
- if _contains_word(padded, phrase):
- hits.append(key)
- if key in ("-y", "+y", "-z", "+z", "-x", "+x"):
- return key
- if not hits:
- return None
- axes = {_DIR_GROUPS[h] for h in hits}
- if len(axes) > 1:
- # "opens up and out" — up/front conflict: the longest phrase decides only if one axis dominates
- first_axis = _DIR_GROUPS[hits[0]]
- if any(_DIR_GROUPS[h] != first_axis for h in hits[1:]):
- return None
- return hits[0]
-
-
-def _contains_word(padded: str, phrase: str) -> bool:
- """Whole-word containment (phrase boundaries are spaces or punctuation)."""
- i = padded.find(phrase)
- while i >= 0:
- before = padded[i - 1] if i > 0 else " "
- after = padded[i + len(phrase)] if i + len(phrase) < len(padded) else " "
- if not before.isalnum() and not after.isalnum():
- return True
- i = padded.find(phrase, i + 1)
- return False
-
-
-def axis_fix_hint(joint_name: str, axis: Sequence[float] | None, expected: str) -> str:
- if axis is not None and len(axis) == 3:
- neg = tuple(-float(a) for a in axis)
- return (f"in src/robot.urdf set joint '{joint_name}' <axis xyz=\"{neg[0]:g} {neg[1]:g} {neg[2]:g}\"/> "
- f"(negate the axis; keep lower/upper as they are, q=0 stays the rest pose) so positive motion goes {expected}")
- return f"negate the <axis> of joint '{joint_name}' in src/robot.urdf (keep lower/upper as they are) so motion goes {expected}"
-
-
-def _set_axis_in_urdf_text(text: str, urdf_joint: str, axis: tuple[float, float, float]) -> str | None:
- """``text`` with joint ``urdf_joint``'s ``<axis xyz>`` replaced (inserted when missing)."""
- xyz = f"{axis[0]:g} {axis[1]:g} {axis[2]:g}"
- start = -1
- pos = 0
- while (jpos := text.find("<joint", pos)) != -1:
- head_end = text.find(">", jpos)
- if head_end == -1:
- return None
- head = text[jpos:head_end]
- if f'name="{urdf_joint}"' in head or f"name='{urdf_joint}'" in head:
- start = jpos
- break
- pos = jpos + 6
- if start == -1:
- return None
- end = text.find("</joint>", start)
- if end == -1:
- return None
- block = text[start:end]
- a0 = block.find("<axis")
- if a0 != -1:
- gt = block.find(">", a0)
- if gt == -1:
- return None
- if block[gt - 1] == "/": # <axis .../>
- axis_end = gt + 1
- else: # <axis ...>...</axis> — "/>" never occurs
- close_pair = block.find("</axis>", gt) # in "</axis>", so searching for it would
- if close_pair == -1: # land on the NEXT self-closing tag and
- return None # splice away the joint's <limit/>
- axis_end = close_pair + len("</axis>")
- new_block = block[:a0] + f'<axis xyz="{xyz}"/>' + block[axis_end:]
- else:
- head_end = block.find(">")
- if head_end == -1:
- return None
- new_block = block[: head_end + 1] + f'\n <axis xyz="{xyz}"/>' + block[head_end + 1:]
- return text[:start] + new_block + text[start + len(block):]
-
-
-def repair_motion_axes(ws: Workspace, report: GateReport | None) -> list[str]:
- """Deterministically rewrite provably-wrong ``<axis xyz>`` in ``src/robot.urdf``."""
- if report is None or not get_settings().axis_repair:
- return []
- src = ws.src / "robot.urdf"
- if not src.is_file():
- return []
- text = src.read_text()
- try:
- root = ET.fromstring(text)
- except ET.ParseError:
- return []
- joints: dict[str, ET.Element] = {j.get("name", ""): j for j in root.findall("joint")}
- by_snake = {to_snake(n): n for n in joints}
- repaired: list[str] = []
- for f in report.findings:
- if f.severity != Severity.ERROR:
- continue
- data = f.data or {}
- cos = data.get("cos")
- if cos is None:
- continue
- urdf_name = by_snake.get(to_snake(f.target or ""))
- if urdf_name is None:
- continue
- if cos <= -0.5:
- ax_el = joints[urdf_name].find("axis")
- cur = [float(v) for v in (ax_el.get("xyz") or "1 0 0").split()] if ax_el is not None else [1.0, 0.0, 0.0]
- target_axis = (-cur[0], -cur[1], -cur[2])
- elif data.get("suggested_axis"):
- sx, sy, sz = data["suggested_axis"]
- target_axis = (float(sx), float(sy), float(sz))
- else:
- continue
- new_text = _set_axis_in_urdf_text(text, urdf_name, target_axis)
- if new_text is None:
- continue
- try: # the repair must never ship a file it cannot prove well-formed and applied
- got = ET.fromstring(new_text).findall("joint")
- el = next(j for j in got if j.get("name") == urdf_name).find("axis")
- assert el is not None
- vals = [float(v) for v in el.get("xyz").split()]
- assert all(abs(a - b) < 1e-9 for a, b in zip(vals, target_axis, strict=True))
- except Exception:
- continue
- text = new_text
- repaired.append(f.target or urdf_name)
- if repaired:
- src.write_text(text)
- art = ws.artifacts / "robot.urdf"
- if art.is_file():
- art.write_text(text)
- return repaired
-
-
-def default_motion_checks(ws: Workspace, plan: Plan | None) -> GateReport | None:
- """Run ``motion_direction_check`` for every plan joint with an obvious motion direction."""
- joints = list(getattr(plan, "joints", None) or [])
- wanted = [(j, expected_direction(j.motion)) for j in joints]
- wanted = [(j, d) for j, d in wanted if d is not None]
- if not wanted:
- return None
- from codeverse3d.spatial.joints_model import UrdfError, load_urdf
- from codeverse3d.spatial.joints_sweep import find_urdf, motion_direction_check
-
- urdf = find_urdf(ws)
- if urdf is None:
- return None
- t0 = time.time()
- findings: list[GateFinding] = []
- try:
- robot = load_urdf(urdf, ws.artifacts / "meshes")
- except UrdfError as e:
- return GateReport.of(MOTION_GATE, [GateFinding(
- gate=MOTION_GATE, severity=Severity.WARN, target="robot.urdf", message=f"motion checks skipped: {e}",
- data={"kind": MOTION_SKIPPED})])
- urdf_names = {to_snake(n): n for n in getattr(robot, "joints", {})}
- for j, expected in wanted:
- name = urdf_names.get(to_snake(j.name), j.name) # URDF joint named like the plan joint (any casing)
- try:
- chk = motion_direction_check(robot, name, expected)
- except UrdfError as e:
- findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.WARN, target=j.name,
- message=f"motion check skipped: {e}", data={"kind": MOTION_SKIPPED, "expected": expected}))
- continue
- data = {"kind": MOTION_OK if chk.ok else MOTION_WRONG, "expected": expected, "observed_dir": list(chk.observed_dir), "motion": j.motion,
- "cos": chk.cos, "suggested_axis": list(chk.suggested_axis) if chk.suggested_axis else None}
- if chk.ok:
- findings.append(GateFinding(gate=MOTION_GATE, severity=Severity.INFO, target=j.name, message=chk.message, data=data))
- else:
- # anti-parallel: the sign is wrong, negate; orthogonal: the geometry admits an exact axis, state it.
- if chk.cos >= -0.5 and chk.suggested_axis is not None:
- sx, sy, sz = chk.suggested_axis
- hint = (f"in src/robot.urdf set joint '{j.name}' <axis xyz=\"{sx:g} {sy:g} {sz:g}\"/> "
- f"— computed from the pivot so positive motion goes {expected}")
- else:
- hint = axis_fix_hint(j.name, getattr(j, "axis", None), expected)
- findings.append(GateFinding(
- gate=MOTION_GATE, severity=Severity.ERROR, target=j.name,
- message=f"{chk.message}. Plan says: \"{j.motion}\"",
- fix_hint=hint, data=data))
- return GateReport.of(MOTION_GATE, findings, duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse3d/tracks/common.py b/harness/codeverse3d/tracks/common.py
deleted file mode 100644
index 8e18918b..00000000
--- a/harness/codeverse3d/tracks/common.py
+++ /dev/null
@@ -1,181 +0,0 @@
-"""Shared track machinery: the run context, the services seam, the single-shot path."""
-
-from __future__ import annotations
-
-import importlib
-import logging
-from collections.abc import Sequence
-from dataclasses import dataclass, field, replace
-from pathlib import Path
-from typing import TYPE_CHECKING, Any
-
-from codeverse3d.config import Settings
-from codeverse3d.contracts.artifacts import GateReport, Measurement, RenderSet, RenderView
-from codeverse3d.contracts.common import Language, Track
-from codeverse3d.contracts.plan import CameraPlan, Plan, ScenePlan
-from codeverse3d.contracts.run import RunRecord
-from codeverse3d.conventions import ViewPreset
-from codeverse3d.orchestrator import BudgetGuard, RoundPolicy, RunState
-from codeverse3d.proc import EventLog
-from codeverse3d.prompts import prompt_hash
-from codeverse3d.tracks.generation import (
- SINGLE_SHOT_PREFIX,
- GenerationResult,
- GenerationTask,
- generate,
- is_single_shot,
-)
-from codeverse3d.workspace import Workspace
-
-if TYPE_CHECKING:
- from codeverse3d.languages.base import SceneRuntime
-
-log = logging.getLogger(__name__)
-
-
-def _import(path: str, name: str) -> Any:
- return getattr(importlib.import_module(path), name)
-
-
-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("c3d_flywheel.models", "get_chat_model")(model_id)
-
- def coding_agent(self, agent_id: str) -> Any:
- return _import("codeverse3d.agents", "get_coding_agent")(agent_id)
-
- def judge(self, track: Track, rubric: str, model_id: str, n_samples: int = 1, *, references: bool = False) -> Any:
- """The judge that scores a round: the class ``judge_for`` picks, shared with every replay."""
- judges = importlib.import_module("c3d_flywheel.vlm_judge")
- cls = judges.judge_for(track, rubric, references=references)
- return cls(model_id=model_id, n_samples=n_samples, rubric=rubric)
-
- def runtime(self, language: Language) -> Any:
- return _import("codeverse3d.languages", "get_runtime")(language)
-
- # ---- spatial
- def measure(self, glb: Path) -> Measurement:
- return _import("codeverse3d.spatial.measure", "measure_glb")(glb)
-
- def connectivity(self, glb: Path, language: str = "", planned_edges: Sequence[tuple[str, str | Sequence[str]]] = ()) -> GateReport:
- """Connectivity gate; ``language`` selects the frame of the fix hints (the author's frame, not the GLB's)."""
- return _import("codeverse3d.spatial.connectivity", "check_connectivity")(
- glb, language=language, planned_edges=tuple(planned_edges))
-
- def contract(self, measurement: Measurement, plan: Plan, tol_m: float, language: str = "") -> GateReport:
- return _import("codeverse3d.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("codeverse3d.spatial.render", "render_glb")(glb, out_dir, views=list(views), width=width, height=height, sheet=True)
-
- def render_scene(self, runtime: SceneRuntime, ws: Workspace, out_dir: Path, *, cameras: list[CameraPlan] | None,
- times: Sequence[float], width: int, height: int) -> RenderSet:
- return runtime.render_scene(ws, out_dir, cameras=cameras, orbit=True, times=tuple(times), width=width, height=height, sheet=True)
-
- def render_geometry(self, glb: Path, out_dir: Path, *, views: Sequence[ViewPreset]) -> RenderSet:
- """Clay renders (no materials/textures) exposing holes/intersections for the judge's"""
- return _import("codeverse3d.spatial.render", "render_glb")(glb, out_dir, views=list(views), mode="clay", sheet=False)
-
- def frame_gate(self, renders: RenderSet) -> GateReport:
- """``scene_frames`` gate from a scene RenderSet's metrics.json (missing metrics → passing empty report)."""
- return _import("codeverse3d.spatial.frame_metrics", "frame_gate_from_renders")(renders)
-
- def silhouette(self, render_png: Path | str, reference_png: Path | str) -> dict[str, Any]:
- """Outline IoU of a render vs a reference image (``{iou, reliable, ...}``)."""
- return _import("codeverse3d.spatial.silhouette", "compare_silhouette")(render_png, reference_png)
-
- def motion_checks(self, ws: Workspace, plan: Plan) -> GateReport | None:
- """Planned joint motion text vs the built URDF's actual motion direction."""
- return _import("codeverse3d.tracks.articulated_object", "default_motion_checks")(ws, plan)
-
- 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."""
- return _import("codeverse3d.tracks.articulated_object", "default_joint_sweep")(ws, plan, out_dir)
-
- # ---- agents' workspace materialisation + tool cards
- def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str) -> None:
- _import("codeverse3d.agents.materialize", "materialize_workspace")(
- ws, agent_kind=agent_kind, contract_md=contract_md)
-
- def tool_cards(self, track: str, language: str) -> str:
- return _import("codeverse3d.spatial.registry", "tool_cards")(track=track, language=language)
-
- # ---- scene assembly + record
- def assemble_scene(self, runtime: SceneRuntime, ws: Workspace, plan: ScenePlan) -> Any:
- return runtime.assemble(ws, plan)
-
- def finalize_record(self, ws: Workspace, record: RunRecord) -> None:
- _import("c3d_flywheel.record.record", "finalize_record")(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
- model: Any | None = None
- contract_text: str = ""
- tool_cards: str = ""
- prompt_hashes: dict[str, str] = field(default_factory=dict)
- extra: dict[str, Any] = field(default_factory=dict)
-
- @property
- def language(self) -> Language:
- return self.spec.language
-
- @property
- def single_shot(self) -> bool:
- return is_single_shot(self.agent_id)
-
- @property
- def agent_kind(self) -> str:
- """``agy`` of ``agy:gemini-4-argon``."""
- return self.agent_id.split(":", 1)[0]
-
- def record_prompt(self, name: str, text: str) -> None:
- self.prompt_hashes[name] = prompt_hash(text)
-
-
-# ----------------------------------------------------------------------------- strategy
-def single_shot_ctx(ctx: RunContext) -> RunContext | None:
- """A copy of ``ctx`` bound to the single-shot strategy, or None when none is available."""
- cached = ctx.extra.get("_single_shot_ctx")
- if cached is not None:
- return cached or None
- planner = ctx.spec.backends.planner
- sid = ctx.agent_id if is_single_shot(ctx.agent_id) else (SINGLE_SHOT_PREFIX + planner if ":" in planner else "")
- sub: RunContext | None = None
- if sid:
- try:
- model = ctx.model if is_single_shot(ctx.agent_id) else ctx.services.chat_model(sid[len(SINGLE_SHOT_PREFIX):])
- except Exception as e: # noqa: BLE001 — no chat model → keep the agent path
- log.info("single-shot generation unavailable for %s: %s", ctx.agent_id, e)
- model = None
- if model is not None:
- sub = replace(ctx, agent_id=sid, model=model, agent=None)
- ctx.extra["_single_shot_ctx"] = sub or False
- return sub
-
-
-def generate_for(ctx: RunContext, task: GenerationTask) -> GenerationResult:
- """``generate()`` with everything ``ctx`` knows — the one call every stage makes. A session"""
- return generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
- budget=ctx.budget, events=ctx.events)
diff --git a/harness/codeverse3d/tracks/depth.py b/harness/codeverse3d/tracks/depth.py
deleted file mode 100644
index a6af9654..00000000
--- a/harness/codeverse3d/tracks/depth.py
+++ /dev/null
@@ -1,103 +0,0 @@
-"""Generation depth: complexity budgets."""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any
-
-from codeverse3d.conventions import MAX_TRIS_OBJECT
-
-if TYPE_CHECKING:
- from codeverse3d.contracts.plan import StaticPlan
-
-# --------------------------------------------------------------------------- triangle / time budget
-#: triangles a well-detailed single part is worth. Corpus: median tri/part ≈ 430, and the
-#: highest-scoring hard run (garden arch, 0.929) sits at 1936. Target the good end.
-TRIS_PER_UNIT_TARGET = 2_000
-TRIS_PER_UNIT_FLOOR = 350
-TRIS_PER_UNIT_MAX = 20_000
-
-BUILD_S_PER_UNIT = 3.0
-MIN_BUILD_S = 20
-
-
-@dataclass(frozen=True)
-class DepthBudget:
- """What THIS object is allowed to spend, sized from its own plan."""
-
- n_units: int
- min_tris: int
- target_tris: int
- max_tris: int
- max_build_s: int
-
-
-DETAIL_ADVICE = (
- "- Spend detail INSIDE the parts the plan already names — the edges, profiles, seams and repeats the "
- "real object carries — not on new parts the plan does not list. Measured on this harness: detail "
- "inside a part is neutral-to-positive for the score, extra un-planned parts are strongly negative."
-)
-
-
-def depth_budget(plan: StaticPlan, build_timeout_s: int) -> DepthBudget:
- """Triangle + build-time budget sized from the plan's part/instance count."""
- n_units = plan.leaf_count
- target = _clamp(TRIS_PER_UNIT_TARGET * n_units, 6_000, 200_000)
- return DepthBudget(
- n_units=n_units,
- min_tris=_clamp(TRIS_PER_UNIT_FLOOR * n_units, 1_500, 40_000),
- target_tris=target,
- max_tris=_clamp(TRIS_PER_UNIT_MAX * n_units, 60_000, MAX_TRIS_OBJECT),
- # the subprocess is killed at build_timeout_s, so never allow more than
- # that minus the exporter's share, and never less than MIN_BUILD_S
- max_build_s=int(_clamp(int(BUILD_S_PER_UNIT * n_units), MIN_BUILD_S, max(MIN_BUILD_S, build_timeout_s - 30))),
- )
-
-
-def _clamp(v: float, lo: float, hi: float) -> int:
- return int(max(lo, min(hi, v)))
-
-
-# --------------------------------------------------------------------------- the budget gate
-BUDGET_GATE = "detail_budget"
-
-
-def budget_gate(measurement: Any, build: Any, budget: DepthBudget) -> Any:
- """``detail_budget`` gate: is this object as dense as its own plan says it should be?"""
- from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severity
-
- findings: list[Any] = []
- tris = int(getattr(measurement, "tri_count", 0) or 0)
- per_unit = tris / max(1, budget.n_units)
- if tris > budget.max_tris:
- findings.append(GateFinding(
- gate=BUDGET_GATE, severity=Severity.ERROR, target="overall",
- message=f"{tris:,} triangles exceeds this object's ceiling of {budget.max_tris:,} "
- f"({budget.n_units} built objects × {TRIS_PER_UNIT_MAX:,})",
- fix_hint=f"over this object's ceiling of {budget.max_tris:,}: reduce the segment / subdivision "
- f"counts on the heaviest parts",
- data={"kind": "over_tri_budget", "tris": tris, "max": budget.max_tris}))
- elif tris < budget.min_tris:
- findings.append(GateFinding(
- gate=BUDGET_GATE, severity=Severity.WARN, target="overall",
- message=f"{tris:,} triangles ({per_unit:.0f} per built object) is below this object's detail floor "
- f"of {budget.min_tris:,} — it is a stack of primitives, not a modelled object",
- fix_hint=f"{tris:,} triangles is under this object's floor of {budget.min_tris:,} (target "
- f"{budget.target_tris:,}): add the detail the real object carries INSIDE the parts the "
- f"plan names, not as new parts",
- data={"kind": "under_tri_budget", "tris": tris, "floor": budget.min_tris,
- "target": budget.target_tris, "per_unit": round(per_unit, 1)}))
- ms = int(getattr(build, "duration_ms", 0) or 0)
- if ms > budget.max_build_s * 1000:
- findings.append(GateFinding(
- gate=BUDGET_GATE, severity=Severity.WARN, target="overall",
- message=f"the build took {ms / 1000:.1f} s, over this object's {budget.max_build_s} s budget",
- fix_hint="find the part with the most segments/subdivision/booleans and simplify it",
- data={"kind": "slow_build", "ms": ms, "budget_s": budget.max_build_s}))
- if not findings:
- findings.append(GateFinding(
- gate=BUDGET_GATE, severity=Severity.INFO, target="overall",
- message=f"{tris:,} triangles ({per_unit:.0f} per built object) inside the "
- f"{budget.min_tris:,}–{budget.max_tris:,} budget",
- data={"kind": "tri_budget_ok", "tris": tris, "target": budget.target_tris}))
- return GateReport.of(BUDGET_GATE, findings)
diff --git a/harness/codeverse3d/tracks/generation.py b/harness/codeverse3d/tracks/generation.py
deleted file mode 100644
index 05d21fde..00000000
--- a/harness/codeverse3d/tracks/generation.py
+++ /dev/null
@@ -1,581 +0,0 @@
-"""Code generation: one entry point, two strategies."""
-
-from __future__ import annotations
-
-import logging
-import re
-import shutil
-import time
-from collections.abc import Callable, Collection
-from pathlib import Path, PurePosixPath
-from typing import Any, Literal, get_args
-
-from pydantic import BaseModel, Field
-
-from codeverse3d.config import get_settings
-from codeverse3d.contracts.agent import AgentEffort, AgentJob, AgentResult, FileChange
-from codeverse3d.contracts.chat import ChatMessage, ChatRequest, ImagePart
-from codeverse3d.contracts.common import (
- ENTRY_FILE,
- HARNESS_OWNED_SRC,
- Language,
- Usage,
- is_harness_owned,
-)
-from c3d_flywheel.cost.context import call_context
-from c3d_flywheel.cost.types import stage_for_label
-from c3d_flywheel.models import get_chat_model
-from codeverse3d.orchestrator import BudgetExceeded, BudgetGuard
-from codeverse3d.proc import NULL_EVENTS, read_json_or_none
-from codeverse3d.workspace import C3D_DIR, Workspace
-
-log = logging.getLogger(__name__)
-
-ALLOWED_ROOTS: tuple[str, ...] = ("src/", "public/")
-#: where an out-of-workspace task image is copied so a vendor CLI can read it
-IMAGES_DIR = f"{C3D_DIR}/images"
-
-
-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."""
-
-
-_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 the ``system/singleshot_format.md`` envelope → ``{path: content}``."""
- 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:
- 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]: _strip_envelope_header(text.strip("\n"))}
- raise MultiFileParseError(
- "no '=== FILE: <path> ===' blocks found" + (f"; expected {expected}" if expected else "")
- )
-
-
-_HEADER_LINE = re.compile(r"^[ \t]*===\s*FILE:\s*[^\n=]+?\s*===[ \t]*\r?\n")
-
-
-def _strip_envelope_header(body: str) -> str:
- m = _HEADER_LINE.match(body)
- return body[m.end():] if m else body
-
-
-def _clean_path(p: str) -> str:
- """Normalised path with ``//`` and ``./`` collapsed, so ``src//lib/x.js`` is ``src/lib/x.js``."""
- p = p.strip().strip("`'\"").replace("\\", "/").lstrip("/")
- if not p:
- return p
- norm = PurePosixPath(p).as_posix().lstrip("/")
- return f"{norm}/" if p.endswith("/") and norm != "." else norm
-
-
-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) -> str:
- """Validate a model-provided relative path: inside the workspace + allowed roots."""
- p = _clean_path(path)
- if not p or p.startswith("/") or ".." in Path(p).parts or re.match(r"^[A-Za-z]:", p):
- raise GenerationError(f"refusing to write outside the workspace: {path!r}")
- if p.endswith("/"):
- raise GenerationError(f"path {path!r} is a directory, not a file")
- if not any(p.startswith(root) for root in ALLOWED_ROOTS):
- raise GenerationError(f"path {p!r} is outside the allowed roots {ALLOWED_ROOTS}")
- return p
-
-
-def write_files(
- ws: Workspace,
- files: dict[str, str],
- *,
- only: Collection[str] | None = None,
- frozen: Collection[str] = (),
- on_skip: Callable[[str, str], None] | None = None,
-) -> list[FileChange]:
- """Write parsed files under the workspace; returns git-style FileChange rows."""
- scope = {_clean_path(p) for p in only} if only is not None else None
- owned = {_clean_path(p) for p in frozen}
- changes: list[FileChange] = []
- for raw, content in files.items():
- try:
- rel = safe_relpath(raw)
- except GenerationError as e:
- if on_skip is not None:
- on_skip(raw, str(e))
- log.warning("skipping out-of-root file from generator: %s", e)
- continue
- dest = ws.root / rel
- existed = dest.exists()
- if is_harness_owned(rel, owned):
- reason = "harness-owned: call its functions, never rewrite it"
- if on_skip is not None:
- on_skip(raw, reason)
- log.warning("skipping harness-owned file from generator: %s", rel)
- continue
- if scope is not None and existed and rel not in scope:
- reason = f"out of scope: {rel} already exists and is not in this task's file list"
- if on_skip is not None:
- on_skip(raw, reason)
- log.warning("skipping out-of-scope file from generator: %s", rel)
- continue
- try:
- dest.parent.mkdir(parents=True, exist_ok=True)
- dest.write_text(content if content.endswith("\n") else content + "\n")
- except OSError as e:
- if on_skip is not None:
- on_skip(raw, str(e))
- log.warning("skipping unwritable file from generator: %s: %s", rel, e)
- continue
- changes.append(FileChange(path=rel, status="modified" if existed else "added"))
- return changes
-
-SINGLE_SHOT_PREFIX = "single-shot:"
-
-SINGLE_SHOT_THINKING = "medium"
-
-
-def session_effort(task: GenerationTask) -> AgentEffort | None:
- """``AgentJob.effort`` for ``task``: its ``thinking`` when the caller explicitly asked for an"""
- return task.thinking if task.thinking in get_args(AgentEffort) else None # type: ignore[return-value]
-
-
-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: Literal["", "off", "low", "medium", "high"] = Field(
- default="",
- description="'' = the caller asks for nothing: a single-shot call thinks at SINGLE_SHOT_THINKING, an "
- "agent session runs at its backend's default (agy: high, owner 2026-10-15). Anything else is an "
- "explicit ask — the single-shot call uses it, and an agent session gets it as AgentJob.effort "
- "(``off`` reaches no agent). No track asks for less than high today (D110)",
- )
- max_output_tokens: int = 65_536
- timeout_s: int | None = None
- edit_only: bool = Field(
- default=False,
- description="enforce files_hint as the only existing files this session may overwrite",
- )
- shared_tree: bool = Field(
- default=False,
- description="other harness writers change the workspace while this task's session runs: it is "
- "credited with its files_hint only (AgentJob.shared_tree, D111 — the scene env stage beside the "
- "asset single-shots)",
- )
- reserve_s: float = Field(
- default=0.0,
- description="seconds of the run's HARD clock this task's session leaves untouched for the round's "
- "build, gates, render and judge (a refine / rebuild: RoundPolicy.judge_reserve_s, D112) — its "
- "deadline ends that much before the budget does",
- )
- owns_entry: bool = Field(
- default=False,
- description="this task may write the language entry file even under edit_only (assembly / "
- "whole-object / single-file tasks, and scoped refines whose prompt promises entry access). "
- "A task whose files_hint names the entry owns it implicitly; part / zone / detail / asset "
- "tasks default to False so parallel scoped sessions cannot race on the entry file",
- )
-
-
-class GenerationResult(BaseModel):
- ok: bool
- usage: Usage = Field(default_factory=Usage)
- files_changed: list[FileChange] = Field(default_factory=list)
- notes: str = ""
- label: str = ""
- transient: bool = Field(
- default=False,
- description="the last session died of a provider failure (AgentResult.transient), or the call "
- "raised one (a ModelError the retry layer marks retryable or answers 429/5xx: is_model_outage) — "
- "whatever it wrote before the wall is in files_changed",
- )
- quota: bool = Field(
- default=False,
- description="the last session met the vendor's usage limit (AgentResult.quota): no retry gets "
- "through until it resets",
- )
- stalled: bool = Field(
- default=False,
- description="the last session hung — killed as idle with nothing produced (AgentResult.stalled, "
- "D112): one more session when the clock still holds a minimum window",
- )
-
- @classmethod
- def from_error(cls, label: str, e: BaseException) -> GenerationResult:
- """The failed result of a generation call that RAISED, classified by the error's type"""
- return cls(ok=False, notes=f"{type(e).__name__}: {e}", label=label, transient=is_model_outage(e))
-
-
-def is_model_outage(e: BaseException) -> bool:
- """Is this a *service* failure (the model is down) rather than a bad answer?"""
- from c3d_flywheel.models.base import ModelError
- from c3d_flywheel.models.parts import retryable_status
-
- if isinstance(e, ModelError):
- return bool(e.retryable) or retryable_status(e.status)
- return False
-
-
-# ----------------------------------------------------------------------------- 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) :]
-
-
-SINGLE_SHOT_MIN_WAIT_S = 420.0
-
-
-def single_shot_wait_s(timeout_s: float | None, retry_deadline_s: float) -> float:
- """The longest one single-shot generation may wait: the retry ceiling, capped by the task's own"""
- if timeout_s is None:
- return retry_deadline_s
- return min(retry_deadline_s, max(float(timeout_s), SINGLE_SHOT_MIN_WAIT_S))
-
-
-def generate_files(
- ws: Workspace,
- *,
- model: Any,
- task: GenerationTask,
- budget: BudgetGuard | None = None,
- events: Any | None = None,
-
-) -> GenerationResult:
- """Single-shot API codegen: ChatRequest → envelope → files on disk (no commit)."""
- events = NULL_EVENTS if events is None else events
- from c3d_flywheel.models.retry import RETRY_DEADLINE_S
- from codeverse3d.prompts import load_text
-
- system = task.system + ("\n\n" if task.system else "") + load_text("system/singleshot_format.md")
- req = ChatRequest(
- messages=[ChatMessage.user(task.prompt, images=task.images or None)],
- system=system,
- temperature=task.temperature,
- thinking=task.thinking or SINGLE_SHOT_THINKING,
- max_output_tokens=task.max_output_tokens,
- max_wait_s=_deadline_preflight(budget, single_shot_wait_s(task.timeout_s, RETRY_DEADLINE_S)),
- label=f"{task.label}:r{task.round:02d}",
- )
-
- def ask(r: ChatRequest) -> Any:
- with call_context(round=task.round, stage=stage_for_label(task.kind or task.label)):
- return model.generate(r)
-
- resp = ask(req)
- usage = resp.usage
- 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 "")
-
- def _result(notes: str, changes: list[FileChange] | None = None) -> GenerationResult:
- return GenerationResult(ok=bool(changes), usage=usage, files_changed=changes or [], notes=notes,
- label=task.label)
-
- if _is_truncated(resp):
- events.emit("generate.truncated", label=task.label, finish_reason=str(resp.finish_reason))
- return _result(f"truncated: finish_reason={resp.finish_reason}")
- try:
- files = parse_multifile(resp.text or "", expected_files=task.files_hint or None)
- except MultiFileParseError as e:
- events.emit("generate.parse_failed", label=task.label, error=str(e))
- return _result(f"parse failed: {e}")
- skipped: list[str] = []
-
- def _skip(path: str, reason: str) -> None:
- skipped.append(path)
- events.emit("generate.skipped_path", label=task.label, path=path, reason=reason[:200])
-
- only, frozen = _envelope_scope(ws, task)
- changes = write_files(ws, files, only=only, frozen=frozen, on_skip=_skip)
- 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 _result(f"skipped out-of-root paths: {', '.join(skipped)}" if skipped else "", changes)
-
-
-def _deadline_preflight(budget: BudgetGuard | None, wait_s: float, *, soft: bool = False,
- floor_s: float = 120.0) -> float:
- """Gate a session on the run clock: refuse to start past the hard ceiling, else return the wait to use."""
- if budget is None:
- return wait_s
- budget.check()
- return budget.timeout_s(wait_s, floor_s=floor_s, soft=soft)
-
-
-_TRUNCATED_FINISH = {"max_tokens", "max_output_tokens", "length"}
-
-
-def _is_truncated(resp: Any) -> bool:
- return str(getattr(resp, "finish_reason", "") or "").lower() in _TRUNCATED_FINISH
-
-
-def run_agent_task(
- ws: Workspace,
- *,
- agent: Any,
- task: GenerationTask,
- settings: Any | None = None,
- budget: BudgetGuard | None = None,
- events: Any | None = None,
-) -> GenerationResult:
- """CodingAgent path. ``ok`` = the agent changed files (envelope-vs-disk truth)."""
- events = NULL_EVENTS if events is None else events
- timeout = task.timeout_s or (settings or get_settings()).limits.agent_timeout_s
- timeout = _deadline_preflight(budget, timeout, soft=task.timeout_s is None)
- hard_deadline = None
- if budget is not None:
- hard_deadline = time.monotonic() + max(0.0, budget.timeout_s(float("inf"), floor_s=0, soft=False) - task.reserve_s)
- # typed job context honoured by every CodingAgent: round → trajectory dir + ToolContext,
- # language/track → spatial tool filtering, files_hint → the edit_only scope.
- language, track = _spec_lang_track(ws)
- prompt = task.prompt + _images_block(task.images, ws)
- job = AgentJob(
- workspace=str(ws.root),
- prompt=prompt,
- system_append=task.system,
- label=task.label,
- timeout_s=timeout,
- hard_deadline_s=hard_deadline,
- spatial_tools=True,
- round=task.round,
- kind=task.kind,
- language=language,
- track=track,
- files_hint=list(task.files_hint),
- edit_only=task.edit_only,
- shared_tree=task.shared_tree,
- effort=session_effort(task),
- always_writable=_always_writable(language, task),
- read_only=_read_only(language, ws),
- )
- acc = _SessionAcc(task=task, budget=budget)
- res = acc.run(agent, job)
- changes = res.files_changed
-
- if (
- not changes
- and res.exit_reason not in ("timeout", "budget")
- and not (res.transient or res.quota)
- ):
- 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" + prompt
- )
- }
- )
- res = acc.run(agent, job2, optional=True) or res
- changes = res.files_changed
-
- notes = f"exit={res.exit_reason}" + (f"; errors={res.errors[:3]}" if res.errors else "")
- notes += ("; " + "; ".join(acc.errors)) if acc.errors else ""
- 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,
- turns=acc.turns,
- sessions=acc.sessions,
- cost_usd=round(acc.usage.cost_usd, 4),
- )
- return GenerationResult(
- ok=bool(changes),
- usage=acc.usage,
- files_changed=changes,
- notes=notes,
- label=task.label,
- transient=bool(res.transient),
- quota=bool(res.quota),
- stalled=bool(res.stalled) and not changes,
- )
-
-
-class _SessionAcc:
- """Runs the agent sessions of ONE task and keeps their accounting."""
-
- def __init__(self, *, task: GenerationTask, budget: BudgetGuard | None):
- self.task = task
- self.budget = budget
- self.usage = Usage()
- self.turns = 0
- self.sessions = 0
- self.errors: list[str] = []
-
- def run(self, agent: Any, job: AgentJob, *, optional: bool = False) -> AgentResult | None:
- """One session. ``optional`` sessions (the silent-bail retry) never"""
- self.sessions += 1
- label = self.task.label + (f".a{self.sessions}" if self.sessions > 1 else "")
- try:
- if self.budget is not None:
- self.budget.check()
- res: AgentResult = agent.run(job)
- except Exception as e: # noqa: BLE001 — a budget stop still propagates (see below)
- self.sessions -= 1
- if not optional or isinstance(e, BudgetExceeded):
- raise
- log.warning("optional agent session %s failed: %s: %s", label, type(e).__name__, e)
- self.errors.append(f"{label}: {type(e).__name__}: {e}")
- return None
- self.usage = self.usage + res.usage
- self.turns += res.turns
- if self.budget is not None:
- self.budget.check()
- return res
-
-
-def _images_block(images: list[ImagePart], ws: Workspace) -> str:
- """The task's images (reference photos, the judged contact sheet) as a prompt"""
- paths: list[tuple[str, str]] = []
- for i in images:
- if not i.path:
- continue
- src = Path(i.path)
- dest = ws.root / IMAGES_DIR / f"{len(paths):02d}_{src.name}"
- try:
- dest.parent.mkdir(parents=True, exist_ok=True)
- shutil.copy2(src, dest)
- except OSError as e:
- log.warning("task image %s could not be copied into %s: %s", src, dest, e)
- paths.append((i.label or "image", str(src)))
- continue
- paths.append((i.label or "image", dest.relative_to(ws.root).as_posix()))
- if not paths:
- return ""
- lines = ["", "", "## Images for this task",
- "They are NOT attached to this message: open each file with your image/file-reading tool.",
- "Paths are relative to the workspace root."]
- lines += [f"- {label}: `{path}`" for label, path in paths]
- return "\n".join(lines)
-
-
-def _spec_lang_track(ws: Workspace) -> tuple[str, str]:
- """Best-effort ``(language, track)`` from the workspace's spec.json ("" when absent)."""
- spec_d = read_json_or_none(ws.spec_path) or {}
- return str(spec_d.get("language", "")), str(spec_d.get("track", ""))
-
-
-def _always_writable(language: str, task: GenerationTask) -> list[str]:
- """The entry file, exempt from ``edit_only`` — but only for a task that OWNS it."""
- try:
- entry = ENTRY_FILE[Language(language)]
- except (ValueError, KeyError):
- return []
- return [entry] if task.owns_entry or entry in task.files_hint else []
-
-
-def _envelope_scope(ws: Workspace, task: GenerationTask) -> tuple[set[str] | None, list[str]]:
- """The ``only`` set for ``write_files`` (an ``edit_only`` task's files plus the always-writable ones, else ``None``) and the frozen files."""
- language, _ = _spec_lang_track(ws)
- frozen = _read_only(language, ws)
- if not task.edit_only or not task.files_hint:
- return None, frozen
- return {f for f in task.files_hint if f} | set(_always_writable(language, task)), frozen
-
-
-def _read_only(language: str, ws: Workspace) -> list[str]:
- """The harness-owned files of the language (scene_threejs's ``src/lib/``) and the spec's fixed parts: every session"""
- spec_d = read_json_or_none(ws.spec_path) or {}
- fixed = [str(f.get("path", "")).replace("\\", "/") for f in spec_d.get("fixed_parts") or [] if f.get("path")]
- try:
- return list(HARNESS_OWNED_SRC.get(Language(language), ())) + fixed
- except ValueError:
- return fixed
-
-
-def generate(
- ws: Workspace,
- *,
- agent_id: str,
- task: GenerationTask,
- agent: Any | None = None,
- model: Any | None = None,
- settings: Any | None = None,
- budget: BudgetGuard | None = None,
- events: Any | None = None,
-) -> GenerationResult:
- """Dispatch to the single-shot or the coding-agent strategy by ``agent_id``."""
- if is_single_shot(agent_id):
- if model is None:
- model = get_chat_model(single_shot_model_id(agent_id))
- return generate_files(
- ws,
- model=model,
- task=task,
- budget=budget,
- events=events,
- )
- if agent is None:
- from codeverse3d.agents import get_coding_agent
-
- agent = get_coding_agent(agent_id)
- return run_agent_task(
- ws,
- agent=agent,
- task=task,
- settings=settings,
- budget=budget,
- events=events,
- )
diff --git a/harness/codeverse3d/tracks/graphics.py b/harness/codeverse3d/tracks/graphics.py
deleted file mode 100644
index 108db544..00000000
--- a/harness/codeverse3d/tracks/graphics.py
+++ /dev/null
@@ -1,155 +0,0 @@
-"""GraphicsTrack."""
-
-from __future__ import annotations
-
-import logging
-import shutil
-from pathlib import Path
-from typing import Any
-
-from codeverse3d.contracts.artifacts import (
- BuildResult,
- GateReport,
- Measurement,
- RenderSet,
- RenderView,
- Severity,
-)
-from codeverse3d.contracts.common import TRACK_INFO, Track
-from codeverse3d.contracts.plan import GraphicsPlan, Plan
-from codeverse3d.contracts.run import RoundRecord
-from codeverse3d.languages._gl_common import JUDGE_TIMES, METRICS_NAME, SHEET_NAME, read_metrics
-from codeverse3d.orchestrator import TaskGroup
-from codeverse3d.prompts import render
-from codeverse3d.tracks.common import RunContext
-from codeverse3d.tracks.generation import GenerationTask
-from codeverse3d.tracks.lifecycle import BaseTrack
-from codeverse3d.tracks.prompting import (
- base_prompt_context,
- judge_digest,
- judged_sheet,
- reference_images,
- refine_inline_files,
-)
-from codeverse3d.workspace import Workspace
-
-log = logging.getLogger(__name__)
-
-
-# ===================================================================== prompt context + frames
-def passes_table(plan: GraphicsPlan | None) -> str:
- if plan is None or not plan.passes:
- return "(no passes)"
- rows = ["| pass | kind | what it draws / computes |", "|---|---|---|"]
- rows += [f"| {p.name} | {p.kind} | {p.description} |" for p in plan.passes]
- return "\n".join(rows)
-
-
-def graphics_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
- """Every variable the graphics templates may reference (StrictUndefined)."""
- plan = ctx.plan if isinstance(ctx.plan, GraphicsPlan) else None
- res = plan.resolution if plan else (1280, 720)
- return base_prompt_context(ctx, **{
- "title": plan.title if plan else "Untitled effect",
- "style": plan.style if plan else "", "resolution": f"{res[0]}x{res[1]}", "duration": f"{plan.duration_s:g}" if plan else "8",
- "passes_table": passes_table(plan), "motion": plan.motion if plan else "", "key_visuals": list(plan.key_visuals) if plan else [],
- "uniforms": ", ".join(plan.uniforms) if plan and plan.uniforms else "u_time, u_resolution",
- "expected_files": ctx.runtime.expected_files(ctx.plan), "judge_times": ", ".join(f"{t:g}" for t in JUDGE_TIMES) + " s", **extra})
-
-
-# ----------------------------------------------------------------------------- renders / gates
-def frames_render_set(ws: Workspace, build: BuildResult, round_index: int) -> RenderSet:
- """Copy the judged frames + sheet into renders/rNN and describe them as a RenderSet (views ``t=<s>s``)."""
- out = ws.renders_dir(round_index)
- out.mkdir(parents=True, exist_ok=True)
- frames_dir = Path(build.extra_paths.get("frames", ws.artifacts / "frames"))
- metrics = read_metrics(ws)
- if metrics is not None: # the round's own copy: what a replay of THIS round quotes (frame_stats_text)
- shutil.copy2(ws.artifacts / METRICS_NAME, out / METRICS_NAME)
- stats = metrics[0] if metrics else None
- views: list[RenderView] = []
- frames = stats.frames if stats else []
- for f in frames:
- src = Path(f.path)
- if not src.is_file():
- continue
- dst = out / f"frame_t{f.time:05.2f}.png"
- shutil.copy2(src, dst)
- views.append(RenderView(name=f"t={f.time:g}s", path=str(dst), time_s=f.time))
- if not views and frames_dir.is_dir(): # metrics missing: fall back to the raw frame files
- for p in sorted(frames_dir.glob("f*_t*.png")):
- dst = out / p.name
- shutil.copy2(p, dst)
- views.append(RenderView(name=p.stem.split("_t", 1)[-1] + "s", path=str(dst)))
- sheet_src = Path(build.extra_paths.get("sheet", ws.artifacts / SHEET_NAME))
- sheet = None
- if sheet_src.is_file():
- sheet = out / "sheet.png"
- shutil.copy2(sheet_src, sheet)
- renderer = str(build.census.get("renderer", "")) if isinstance(build.census, dict) else ""
- return RenderSet(views=views, contact_sheet=str(sheet) if sheet else None, renderer=renderer or "moderngl",
- duration_ms=build.duration_ms)
-
-
-def frame_stats_text(ws: Workspace, round_index: int | None = None) -> str:
- """The frame metrics as judge / refine text."""
- where = ws.renders_dir(round_index) if round_index is not None else None
- if round_index is not None and where is not None and not (where / METRICS_NAME).is_file():
- later = any(int(p.stem[1:]) > round_index for p in (ws.root / "rounds").glob("r[0-9][0-9].json"))
- if later:
- return "(not kept for this round: the metrics on disk are a later build's; judge motion from the frames)"
- where = None
- m = read_metrics(ws, where)
- if m is None:
- return "(no frame metrics)"
- stats, gate = m
- lines = stats.summary_lines()
- for f in gate.findings:
- lines.append(f"- GATE gl_frames {f.as_line(with_severity=True, with_hint=f.severity is not Severity.INFO)}")
- return "\n".join(lines)
-
-
-class GraphicsPipeline:
- """No measurement."""
-
- def measure(self, ctx: RunContext, build: BuildResult) -> Measurement | None:
- return None
-
- def gates(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> list[GateReport]:
- return []
-
- def render(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> RenderSet:
- return frames_render_set(ctx.ws, build, round_index)
-
- def judge_context(self, ws: Workspace, plan: Plan | None, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
- renderer = build.census.get("renderer", "") if isinstance(build.census, dict) else ""
- return f"FRAME METRICS (harness-measured, renderer {renderer or 'moderngl'}):\n{frame_stats_text(ws, round_index)}"
-
-
-class GraphicsTrack(BaseTrack):
- track = Track.GRAPHICS
- rubric = TRACK_INFO[Track.GRAPHICS].rubric
- plan_model = GraphicsPlan
- generate_template = "tracks/generate_graphics.j2"
- refine_template = "tracks/refine_graphics.j2"
- # refinement is always ONE whole-program task
- allow_refine_fanout = False
- baseline_temperature = 0.6
-
- def make_pipeline(self) -> GraphicsPipeline:
- return GraphicsPipeline()
-
- def generate_context(self, ctx: RunContext, **extra: Any) -> dict[str, Any]:
- return graphics_prompt_context(ctx, **extra)
-
- # ------------------------------------------------------------------ refine (scaffold hook; never fans out)
- def _refine_task(self, ctx: RunContext, group: TaskGroup, last: RoundRecord, index: int, *, parallel: bool) -> GenerationTask:
- files = ctx.runtime.expected_files(ctx.plan)
- prompt = render(self.refine_template, **graphics_prompt_context(
- ctx, round_index=index, tasks=[t.line() for t in group.tasks], targets=group.targets, files=files,
- judge_summary=judge_digest(last), frame_notes=frame_stats_text(ctx.ws),
- current_files=refine_inline_files(ctx, files)))
- ctx.record_prompt("refine", prompt)
- return GenerationTask(label="refine", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=index,
- kind="refine", temperature=0.5, owns_entry=True,
- images=reference_images(ctx) + judged_sheet(last))
diff --git a/harness/codeverse3d/tracks/lifecycle.py b/harness/codeverse3d/tracks/lifecycle.py
deleted file mode 100644
index d3f0a464..00000000
--- a/harness/codeverse3d/tracks/lifecycle.py
+++ /dev/null
@@ -1,634 +0,0 @@
-"""BaseTrack: the resumable plan → pre-round stages → rounds → finalise lifecycle."""
-
-from __future__ import annotations
-
-import logging
-import platform
-import traceback
-from collections.abc import Callable, Sequence
-from dataclasses import dataclass
-from datetime import UTC, datetime
-from pathlib import Path
-from typing import Any
-
-from codeverse3d.config import Settings, get_settings
-from codeverse3d.contracts.artifacts import GateReport
-from codeverse3d.contracts.common import Track
-from codeverse3d.contracts.plan import Plan
-from codeverse3d.contracts.run import RoundRecord, RunRecord, RunStatus
-from codeverse3d.contracts.spec import Spec
-from c3d_flywheel.cost.context import run_binding
-from c3d_flywheel.cost.instrument import metered_agent, metered_chat_model, run_ledger
-from c3d_flywheel.cost.ledger import ledger_usage, load_ledger
-from c3d_flywheel.cost.tally import timed
-from codeverse3d.judges.base import run_rubric
-from codeverse3d.orchestrator import (
- BudgetExceeded,
- BudgetGuard,
- BudgetSnapshot,
- RoundPolicy,
- RunState,
- StageRunner,
- TaskGroup,
- build_refine_instructions,
- hash_inputs,
- plan_refine_groups,
-)
-from codeverse3d.proc import EventLog, fan_out, read_json_or_none
-from codeverse3d.prompts import load_text, render
-from codeverse3d.prompts.catalog import language_text
-from c3d_flywheel.record.record import previous_verdict
-from codeverse3d.tracks.common import RunContext, Services
-from codeverse3d.tracks.generation import ALLOWED_ROOTS, GenerationTask, single_shot_model_id
-from codeverse3d.tracks.planner import plan as run_planner
-from codeverse3d.tracks.planner import plan_temperature
-from codeverse3d.tracks.prompting import (
- base_prompt_context,
- language_system_prompt,
- reference_images,
- refine_inline_files,
- skeleton_files,
-)
-from codeverse3d.tracks.repair import format_error_report
-from codeverse3d.tracks.steps import (
- RoundFailed,
- RoundPipeline,
- failed_acceptance,
- load_round_journal,
- rejudge_round,
- run_round,
-)
-from codeverse3d.workspace import Workspace
-
-log = logging.getLogger(__name__)
-
-
-def plan_stage_inputs(spec: Spec) -> dict[str, Any]:
- """Only the spec fields the PLAN depends on: hashing the whole Spec meant that"""
- inputs: dict[str, Any] = {
- "prompt": spec.prompt,
- "track": spec.track.value,
- "language": spec.language.value,
- "constraints": spec.constraints,
- "references": spec.references,
- "planner": spec.backends.planner,
- }
- if spec.fixed_parts: # only when set, so every existing run's plan key stays put
- inputs["fixed_parts"] = spec.fixed_parts
- return inputs
-
-
-def plan_stage_key(spec: Spec, track: Track) -> dict[str, Any]:
- return {"spec": plan_stage_inputs(spec), "track": track.value}
-
-
-def spec_fingerprint(spec: Spec) -> str:
- """Identity of the spec THE PLAN depends on (hash of :func:`plan_stage_inputs`)."""
- return hash_inputs(plan_stage_inputs(spec))
-
-
-class SpecChanged(RuntimeError):
- """spec.json's plan inputs changed under an existing run."""
-
-
-# ============================================================================ the pre-round graph
-@dataclass(frozen=True)
-class StageNode:
- """One pre-round stage of a track's declared graph (``BaseTrack.stages``)."""
-
- name: str
- run: Callable[[Any, RunContext], Any]
- key: Callable[[RunContext], dict[str, Any]] | None = None
- when: Callable[[Settings], bool] | None = None
- seeds_src: bool = False
-
-
-Stages = tuple[StageNode | tuple[StageNode, ...], ...]
-
-
-def run_stages(track: BaseTrack, ctx: RunContext, runner: StageRunner, stages: Stages) -> None:
- """Walk ``stages``. Siblings run side by side as ONE timed step of the run's minutes, each"""
- def one(node: StageNode, *, timed_step: bool = True) -> Any:
- if node.key is None:
- return node.run(track, ctx)
- key = node.key(ctx)
- if node.seeds_src and runner.frozen and not runner.is_done(node.name, key):
- # a drifted key or a lost state entry under existing rounds: re-running the writer
- # would overwrite agent-authored src/ — never do that
- ctx.events.emit("stage.skipped", stage=node.name, reason="rounds_exist")
- return None
- return runner.stage(node.name, lambda: node.run(track, ctx), inputs=key, timed_step=timed_step)
-
- for item in stages:
- live = [n for n in (item if isinstance(item, tuple) else (item,)) if n.when is None or n.when(get_settings())]
- if not live:
- continue
- if len(live) == 1:
- results = [one(live[0])]
- else:
- group = "+".join(n.name for n in live)
- with timed(group, ctx.state.steps):
- results = fan_out(live, lambda n: one(n, timed_step=False), max_workers=len(live), label=group,
- item_name=lambda n: n.name)
- if (exc := next((r for r in results if isinstance(r, Exception)), None)) is not None:
- raise exc
- ctx.extra.update(zip((n.name for n in live), results, strict=True))
-
-
-def _skeleton(track: BaseTrack, ctx: RunContext) -> list[str]:
- # the project's fixed parts (Spec.fixed_parts) were seeded before the run: a language whose skeleton
- # rewrites src/ must not replace them, and a run whose seed is missing must stop here, not later
- fixed = {f.path: ctx.ws.root / f.path for f in ctx.spec.fixed_parts}
- missing = [p for p, f in fixed.items() if not f.is_file()]
- if missing:
- raise FileNotFoundError(f"fixed parts not seeded in the workspace: {missing}")
- kept = {p: f.read_bytes() for p, f in fixed.items()}
- paths = ctx.runtime.skeleton(ctx.ws, ctx.plan)
- for p, data in kept.items():
- if fixed[p].read_bytes() != data:
- fixed[p].write_bytes(data)
- 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]
-
-
-def _skeleton_key(ctx: RunContext) -> dict[str, Any]:
- """The plan and language."""
- return {"plan": ctx.plan, "language": ctx.language.value}
-
-
-SKELETON = StageNode("skeleton", _skeleton, key=_skeleton_key, seeds_src=True)
-MATERIALIZE = StageNode("materialize", lambda t, c: t.ensure_materialized(c))
-CLOCK = StageNode("clock", lambda t, c: c.budget.check())
-
-
-class BaseTrack:
- """Shared lifecycle. Subclasses set ``track``, ``rubric``, ``plan_model``, their pre-round"""
-
- track: Track
- rubric: str
- plan_model: type[Plan]
- stages: Stages = (SKELETON, MATERIALIZE)
- generate_template: str = ""
- refine_template: str = ""
- allow_refine_fanout: bool = True
- soft_budget_fraction: float = 1.0
- baseline_temperature: float = 0.5
-
- 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) -> RoundPipeline:
- raise NotImplementedError
-
- def baseline_tasks(self, ctx: RunContext) -> list[GenerationTask]:
- files = ctx.runtime.expected_files(ctx.plan)
- prompt = render(self.generate_template, **self.generate_context(
- ctx, skeleton_files=skeleton_files(ctx) if ctx.single_shot else {}, previous_error=""))
- ctx.record_prompt("generate", prompt)
- return [GenerationTask(label="baseline", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=0,
- kind="baseline", temperature=self.baseline_temperature, owns_entry=True,
- images=reference_images(ctx))]
-
- def system_prompt(self, ctx: RunContext) -> str:
- return language_system_prompt(ctx.language, tools=not ctx.single_shot)
-
- def round_extra_notes(self, ctx: RunContext) -> list[str]:
- return list(ctx.extra.get("degraded") or [])
-
- def prepare_salvage(self, ctx: RunContext) -> bool:
- """Make the workspace buildable after a stage tripped the budget before"""
- prepared = ctx.extra.get("prepared_commit")
- return bool(prepared) and any(c.path.startswith(ALLOWED_ROOTS) for c in ctx.ws.changed_files(since=prepared))
-
- # ---- refine hooks (the scaffold below is shared; tracks fill in the task)
- def refine_file_for_target(self, ctx: RunContext) -> Callable[[str], list[str]]:
- return lambda target: ctx.runtime.files_for(ctx.plan, target)
-
- def extra_refine_tasks(self, ctx: RunContext, last: RoundRecord) -> Sequence[Any]:
- """Harness-derived tasks prepended to the judge's (e.g. reference IoU)."""
- return ()
-
- def generate_context(self, ctx: RunContext, **extra: Any) -> dict[str, Any]:
- """Template context for ``generate_template`` (baseline / rebuild prompts)."""
- extra.setdefault("expected_files", ctx.runtime.expected_files(ctx.plan))
- return base_prompt_context(ctx, **extra)
-
- def _refine_task(self, ctx: RunContext, group: TaskGroup, last: RoundRecord, index: int, *, parallel: bool) -> GenerationTask:
- raise NotImplementedError
-
- # ------------------------------------------------------------------ refine scaffold
- def refine_tasks(self, ctx: RunContext, last: RoundRecord) -> tuple[list[GenerationTask], list[str]]:
- """The round after ``last``: rebuild guard → instructions → groups → per-track ``_refine_task``."""
- index = last.index + 1
- if last.build is None or not last.build.ok:
- rebuild = self._rebuild_task(ctx, last, index).model_copy(update={"reserve_s": ctx.policy.judge_reserve_s})
- return [rebuild], ["rebuild: previous round did not build"]
- tasks = build_refine_instructions(last.judgment, last.gates, failed_acceptance(ctx, last.judgment), ctx.plan,
- file_for_target=self.refine_file_for_target(ctx),
- max_tasks=ctx.policy.max_refine_tasks,
- extra=self.extra_refine_tasks(ctx, last))
- if not tasks:
- return [], []
- groups, parallel = plan_refine_groups(tasks, allow_fanout=self.allow_refine_fanout,
- parallel_min_tasks=ctx.policy.parallel_min_tasks)
- gen_tasks = [self._refine_task(ctx, g, last, index, parallel=parallel).model_copy(
- update={"reserve_s": ctx.policy.judge_reserve_s}) 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 _rebuild_task(self, ctx: RunContext, last: RoundRecord, index: int) -> GenerationTask:
- """Regenerate after a failed build: the generate prompt + the error report."""
- files = ctx.runtime.expected_files(ctx.plan)
- lint = next((g for g in last.gates if g.gate.startswith("lint")), GateReport(gate="lint", passed=True))
- report = format_error_report(last.build, lint) if last.build else "build did not run"
- prompt = render(self.generate_template, **self.generate_context(
- ctx, skeleton_files=refine_inline_files(ctx, files), 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")
-
- # ------------------------------------------------------------------ public API
- def run(self, spec: Spec, ws: Workspace, *, resume: bool = False, force: bool = False) -> RunRecord:
- ws.create()
- with run_ledger(ws.root, run=run_binding().run or ws.root.name):
- 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)
- rounds: list[RoundRecord] = self.reconcile_resume(spec, ws, events, state, resume=resume, force=force)
- ctx = self.build_context(spec, ws, events, state)
- runner = StageRunner(ws, events, state, frozen=bool(rounds))
- 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)
- stop = RunStatus.FAILED
- error = ""
- try:
- ctx.plan = runner.stage("plan", lambda: self._plan_stage(ctx), inputs=plan_stage_key(spec, self.track),
- model=self.plan_model)
- self.after_plan(ctx)
- run_stages(self, ctx, runner, self.stages)
- ctx.extra["prepared_commit"] = ws.head()
- stop = self._round_loop(ctx, rounds)
- except BudgetExceeded as e:
- events.emit("budget.exceeded", reason=e.reason)
- stop, error = RunStatus.BUDGET, e.reason
- self._salvage(ctx, rounds)
- except Exception as e: # noqa: BLE001 — persist a FAILED record, then fail loud
- error = f"{type(e).__name__}: {e}"
- events.emit("run.failed", error=error, traceback=traceback.format_exc()[-3000:])
- self._save_budget(ctx)
- state.status, state.error = RunStatus.FAILED, error
- state.save(ws)
- rec = self._record(ctx, rounds, RunStatus.FAILED, error=error)
- self.services.finalize_record(ws, rec)
- raise
- return self.finalise(ctx, rounds, stop, error=error)
-
- # ------------------------------------------------------------------ resume reconciliation
- def reconcile_resume(self, spec: Spec, ws: Workspace, events: EventLog, state: RunState,
- *, resume: bool, force: bool) -> list[RoundRecord]:
- fp = spec_fingerprint(spec)
- stored = str(state.extra.get("spec_fingerprint") or "")
- if not resume:
- state.extra["spec_fingerprint"] = fp
- return []
- journal = load_round_journal(ws)
- if stored and stored != fp:
- if not force:
- raise SpecChanged(
- f"spec.json for run {ws.root.name} no longer matches the spec its "
- f"{len(journal)} recorded round(s) were built from (plan-input fingerprint "
- f"{stored} != {fp}: prompt/track/language/constraints/references/planner). "
- f"Resuming would record those rounds against the new spec. Fork a new run "
- f"(`3dcodeverse make`), or resume with --force to archive the old rounds under "
- f"rounds/pre_force/ and re-plan. Raising budget caps alone never trips this."
- )
- events.emit("resume.spec_changed", old_fingerprint=stored, new_fingerprint=fp,
- archived_rounds=len(journal))
- state.stages.pop("plan", None)
- if force and (journal or ws.record_path.is_file()):
- archived = self._archive_pre_force(ws)
- events.emit("resume.archived", dest=str(archived), rounds=len(journal))
- journal = []
- state.extra["spec_fingerprint"] = fp
- kept: list[RoundRecord] = []
- dropped: list[int] = []
- for rec in journal:
- if dropped or not rec.commit or not ws.has_commit(rec.commit):
- dropped.append(rec.index)
- else:
- kept.append(rec)
- if dropped:
- events.emit("resume.dropped_rounds", rounds=dropped,
- reason="round journal names commits git does not have")
- journal = kept
- restored = bool(journal) and self._needs_restore(ws, journal[-1].commit)
- if restored:
- ws.restore(journal[-1].commit)
- ws.commit(f"resume from the last round r{journal[-1].index:02d}")
- state.save(ws)
- events.emit("resume.reconciled", rounds=len(journal), dropped=dropped,
- restored_last_round=journal[-1].index if restored else None, spec_fingerprint=fp)
- return journal
-
-
- @staticmethod
- def _archive_pre_force(ws: Workspace) -> Path:
- rounds_dir = ws.root / "rounds"
- dest, n = rounds_dir / "pre_force", 1
- while dest.exists():
- n += 1
- dest = rounds_dir / f"pre_force_{n}"
- dest.mkdir(parents=True, exist_ok=True)
- for p in sorted(rounds_dir.iterdir()):
- if p.is_file():
- p.rename(dest / p.name)
- if ws.record_path.is_file():
- ws.record_path.rename(dest / ws.record_path.name)
- return dest
-
- # ------------------------------------------------------------------ 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, soft_fraction=self.soft_budget_fraction)
- snap = state.extra.get("budget_snapshot")
- if snap:
- # the active minutes keep counting, so a raised cap (--max-minutes / --rounds)
- # grants only the difference, never a fresh full cap
- budget.restore(BudgetSnapshot.model_validate(snap))
- policy = self._policy or RoundPolicy(max_rounds=spec.budget.max_rounds,
- judge_samples=max(1, int(settings.judge.samples or 1)))
- rubric = run_rubric(spec, self.rubric)
- ctx = RunContext(spec=spec, ws=ws, events=events, settings=settings, budget=budget, runtime=runtime,
- services=self.services, state=state, policy=policy, track=self.track, rubric=rubric,
- agent_id=spec.backends.generator,
- agent=metered_agent(self._agent), model=metered_chat_model(self._model))
- ctx.contract_text = language_text(spec.language, "contract.md")
- ctx.tool_cards = self.services.tool_cards(self.track.value, spec.language.value)
- ctx.record_prompt("contract", ctx.contract_text)
- return ctx
-
- def make_judge(self, ctx: RunContext, *, n_samples: int | None = None) -> Any:
- """The main judge: the injected one, else an instance of the class ``judge_for`` picks for this track."""
- if self._judge is not None:
- return self._judge
- return self.services.judge(ctx.track, ctx.rubric, ctx.spec.backends.judge,
- ctx.policy.judge_samples if n_samples is None else n_samples,
- references=bool(ctx.spec.references))
-
- def after_plan(self, ctx: RunContext) -> None:
- """Bind judge / generator backends once the plan exists."""
- if ctx.judge is None:
- ctx.judge = self.make_judge(ctx)
- judge_hash = getattr(ctx.judge, "prompt_hash", "")
- if isinstance(judge_hash, str) and judge_hash:
- ctx.prompt_hashes["judge"] = judge_hash
- 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)
- try:
- plan = run_planner(ctx.spec, ctx.spec.backends.planner, self.plan_model, ctx.ws,
- model=metered_chat_model(self._planner_model), events=ctx.events, budget=ctx.budget)
- finally:
- self._save_budget(ctx)
- return plan
-
- # ------------------------------------------------------------------ stages
- 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_kind
- if ctx.state.materialized_for == kind:
- return
- self.services.materialize(ctx.ws, agent_kind=kind, contract_md=self.agent_contract_md(ctx))
- 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_text("system/harness_contract.md")
- return (harness + "\n\n" + ctx.contract_text).strip()
-
- # ------------------------------------------------------------------ round loop
- def _round_loop(self, ctx: RunContext, rounds: list[RoundRecord]) -> RunStatus:
- pipeline = self.make_pipeline()
- rejudged: set[int] = set()
- transport_retried: set[int] = set()
-
- def _stop(reason: RunStatus) -> RunStatus:
- ctx.events.emit("stop", reason=reason.value, rounds=len(rounds))
- return reason
-
- def _unjudged(rec: RoundRecord | None) -> bool:
- return rec is not None and rec.judgment is None and rec.build is not None and rec.build.ok
-
- while True:
- index = len(rounds)
- last = rounds[-1] if rounds else None
- if _unjudged(last) and last.index not in rejudged and ctx.budget.ok():
- rejudged.add(last.index)
- if rejudge_round(ctx, pipeline, last, previous=previous_verdict(rounds, last.index)):
- self._save_budget(ctx)
- if index > ctx.policy.max_rounds:
- return _stop(RunStatus.JUDGE_UNAVAILABLE if _unjudged(last) else RunStatus.MAX_ROUNDS)
- if not ctx.budget.ok():
- if not rounds:
- ctx.budget.check()
- return _stop(RunStatus.BUDGET)
- previous = previous_verdict(rounds, index)
- if last is None:
- 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, last)
- kind = "refine"
- if not tasks:
- # no gate error, no failed must-item, no judge plan: nothing to ask for. When
- # that is only because the judge never scored the round, say so.
- return _stop(RunStatus.JUDGE_UNAVAILABLE if _unjudged(last) else RunStatus.NO_REFINE_TASKS)
- if last is not None and not ctx.policy.can_open(ctx.budget, single_shot=ctx.single_shot):
- ctx.events.emit("round.skipped_budget", round=index, left_s=round(ctx.budget.left_s(), 1),
- need_s=ctx.policy.need_s(single_shot=ctx.single_shot))
- return _stop(RunStatus.BUDGET)
- ctx.state.save(ctx.ws)
- try:
- rec = run_round(ctx, index=index, kind=kind, tasks=tasks, pipeline=pipeline, instructions=instructions,
- previous=previous, findings=rounds[-1].gates if rounds else (),
- files_hint=ctx.runtime.expected_files(ctx.plan),
- extra_notes=self.round_extra_notes(ctx))
- except RoundFailed as e:
- if e.quota:
- ctx.events.emit("round.agent_quota", round=index, detail=str(e)[:500])
- if index == 0:
- raise
- return _stop(RunStatus.AGENT_QUOTA)
- if index not in transport_retried and (e.transient or e.stalled):
- transport_retried.add(index)
- ctx.events.emit("round.transport_retry", round=index, stalled=e.stalled and not e.transient,
- detail=str(e)[:500])
- continue
- if index == 0:
- raise
- ctx.events.emit("round.no_change", round=index, detail=str(e)[:500])
- return _stop(RunStatus.NO_CHANGE)
- rounds.append(rec)
- self._save_budget(ctx)
-
- def _salvage(self, ctx: RunContext, rounds: list[RoundRecord]) -> None:
- """The budget stopped the run with work nobody has judged: give ONE bounded grace and run"""
- if ctx.plan is None:
- return
- last = rounds[-1] if rounds else None
- edits: list[str] = []
- if last is not None:
- if not last.commit:
- return
- edits = [f.path for f in ctx.ws.changed_files(last.commit) if f.path.split("/", 1)[0] in ("src", "public")]
- if not edits:
- return
- grace_min = max(5.0, ctx.spec.budget.max_minutes * 0.15)
- ctx.budget.grant_grace(minutes=grace_min)
- reason = ("no round completed before the clock stop" if last is None
- else f"the clock stopped a refine round after it changed {len(edits)} file(s)")
- ctx.events.emit("budget.salvage", reason=reason, grace_minutes=round(grace_min, 1), files=edits[:20])
- index = len(rounds)
- try:
- if last is None and not self.prepare_salvage(ctx):
- ctx.events.emit("budget.salvage_skipped", reason="nothing buildable to salvage")
- return
- note = ("salvaged: the budget stopped the run before round 0" if last is None
- else "salvaged: the budget stopped this round's sessions; their edits are judged as they stand")
- rec = run_round(ctx, index=index, kind="baseline" if last is None else "refine", tasks=[],
- pipeline=self.make_pipeline(), instructions=[], previous=previous_verdict(rounds, index),
- findings=last.gates if last is not None else (), files_hint=ctx.runtime.expected_files(ctx.plan),
- extra_notes=[note, *self.round_extra_notes(ctx)])
- except Exception as e: # noqa: BLE001 — the run is already stopping; never mask the budget stop
- log.warning("salvage round failed: %s", e)
- ctx.events.emit("budget.salvage_failed", error=f"{type(e).__name__}: {e}")
- return
- rounds.append(rec)
- self._save_budget(ctx)
-
- def _save_budget(self, ctx: RunContext) -> None:
- snap = ctx.budget.snapshot()
- ctx.state.extra["budget_snapshot"] = snap.model_dump(mode="json")
- ctx.state.save(ctx.ws)
-
- # ------------------------------------------------------------------ finalise
- def finalise(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, error: str = "") -> RunRecord:
- """Write the record. The workspace ENDS AT THE LAST ROUND: a round the budget or a crash"""
- self._save_budget(ctx)
- last = rounds[-1] if rounds else None
- rebuild_err = ""
- rebuild_ok = False
- if last is not None and last.commit and self._needs_restore(ctx.ws, last.commit):
- ctx.ws.restore(last.commit)
- ctx.ws.commit(f"back to the last round r{last.index:02d}")
- try:
- build = ctx.runtime.build(ctx.ws, timeout_s=ctx.settings.limits.build_timeout_s)
- ctx.events.emit("finalise.rebuild", round=last.index, ok=build.ok)
- if not build.ok:
- rebuild_err = f"{build.error_type or 'BuildFailed'}: {build.error_message}"[:300]
- else:
- rebuild_ok = True
- except Exception as e: # noqa: BLE001 — the round already built once; report, don't fail
- rebuild_err = f"{type(e).__name__}: {e}"[:300]
- ctx.events.emit("finalise.rebuild_failed", error=rebuild_err)
- if rebuild_err:
- ctx.extra["finalise_rebuild_failed"] = rebuild_err
- error = error or f"finalise rebuild failed: {rebuild_err}"
- elif rebuild_ok:
- ctx.extra["finalise_rebuild_failed"] = ""
- ctx.state.status, ctx.state.error = status, error
- self._save_budget(ctx)
- rec = self._record(ctx, rounds, status, error=error)
- self.services.finalize_record(ctx.ws, rec)
- ctx.events.emit("run.done", status=status.value, rounds=len(rounds),
- last_score=last.score if last is not None else None,
- cost_usd=round(rec.total_usage.cost_usd, 4), minutes=rec.minutes)
- return rec
-
- @staticmethod
- def _needs_restore(ws: Workspace, commit: str) -> bool:
- """src/ != ``commit``: HEAD moved on, OR an aborted round dirtied the tree"""
- if ws.head() != commit:
- return True
- try:
- return bool(ws.changed_files())
- except Exception as e: # noqa: BLE001 — a git hiccup must not block finalise
- log.warning("changed_files failed in finalise: %s", e)
- return False
-
- def _record(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, error: str) -> RunRecord:
- extra: dict[str, Any] = {"rubric": ctx.rubric, "sampling": self.sampling(ctx.judge)}
- if ctx.extra.get("finalise_rebuild_failed"):
- extra["finalise_rebuild_failed"] = ctx.extra["finalise_rebuild_failed"]
- if ctx.extra.get("aborted_rounds"):
- extra["aborted_rounds"] = ctx.extra["aborted_rounds"]
- prior_extra, prior_hashes = self._prior_record_fields(ctx.ws)
- if ctx.extra.get("finalise_rebuild_failed", None) == "":
- prior_extra.pop("finalise_rebuild_failed", None)
- prior_aborted = prior_extra.get("aborted_rounds")
- for k, v in prior_extra.items():
- if k not in extra or extra[k] is None:
- extra[k] = v
- if isinstance(prior_aborted, list) and ctx.extra.get("aborted_rounds"):
- extra["aborted_rounds"] = prior_aborted + [a for a in ctx.extra["aborted_rounds"]
- if a not in prior_aborted]
- hashes = {**prior_hashes, **dict(ctx.prompt_hashes)}
- return RunRecord(
- spec=ctx.spec, plan=ctx.plan, workspace=str(ctx.ws.root), status=status, rounds=rounds,
- total_usage=ledger_usage(load_ledger(ctx.ws.root)), steps=list(ctx.state.steps),
- environment={"python": platform.python_version(), "host": platform.node(), "track": self.track.value,
- "language": ctx.language.value, "generator": ctx.agent_id},
- prompt_hashes=hashes, started_at=ctx.state.started_at,
- finished_at=datetime.now(UTC), error=error,
- extra=extra,
- )
-
- def sampling(self, judge: Any) -> dict[str, dict[str, Any]]:
- """``record.extra["sampling"]``: the knobs this run's API roles sampled with."""
- knobs = {k: getattr(judge, k) for k in ("temperature", "thinking", "n_samples")
- if isinstance(getattr(judge, k, None), (int, float, str))}
- return {"planner": {"temperature": plan_temperature(self.track)}, **({"judge": knobs} if knobs else {})}
-
- @staticmethod
- def _prior_record_fields(ws: Workspace) -> tuple[dict[str, Any], dict[str, str]]:
- """``(extra, prompt_hashes)`` of the record.json a previous session wrote"""
- prior = read_json_or_none(ws.record_path)
- if prior is None:
- if ws.record_path.is_file():
- log.warning("prior record.json unreadable; post-hoc extra keys not carried over")
- return {}, {}
- extra = prior.get("extra")
- hashes = prior.get("prompt_hashes")
- return (dict(extra) if isinstance(extra, dict) else {},
- {str(k): str(v) for k, v in hashes.items()} if isinstance(hashes, dict) else {})
diff --git a/harness/codeverse3d/tracks/plan_features.py b/harness/codeverse3d/tracks/plan_features.py
deleted file mode 100644
index e83e5e20..00000000
--- a/harness/codeverse3d/tracks/plan_features.py
+++ /dev/null
@@ -1,35 +0,0 @@
-"""Plan-feature switches that change generation-side behaviour."""
-
-
-from __future__ import annotations
-
-from codeverse3d.config import Settings
-
-GENERATION_SIDE_ENV: frozenset[str] = frozenset({"C3D_SKILLS", "C3D_SKILLS_ONLY"})
-NODE_SIDE_ENV: frozenset[str] = frozenset({"C3D_BROWSER_REUSE", "C3D_PAGE_TTL_MS"})
-
-
-def _read(key: str) -> bool:
- """Does any ``Settings`` field — or the node side — read the environment variable ``key``?"""
- if key in Settings.FLAT or key in NODE_SIDE_ENV:
- return True
- section, _, name = key.removeprefix("C3D_").lower().partition("__")
- field = Settings.model_fields.get(section)
- if not name:
- return field is not None
- return field is not None and name in getattr(field.annotation, "model_fields", {})
-
-
-def dead_env_keys(env: dict[str, str]) -> list[str]:
- """The ``C3D_*`` keys of ``env`` that no Settings field reads — empty when the arm really"""
- return sorted(k for k in env if k.startswith("C3D_") and not _read(k))
-
-
-def pin_plan_blockers(variant_env: dict[str, str]) -> list[str]:
- """Which of ``variant_env``'s switches forbid sharing one plan between the arms."""
- dead = set(dead_env_keys(variant_env))
- return [f"{key} is not known to act after planning" for key in sorted(variant_env)
- if key not in GENERATION_SIDE_ENV and key not in dead]
-
-
-__all__ = ["GENERATION_SIDE_ENV", "NODE_SIDE_ENV", "dead_env_keys", "pin_plan_blockers"]
diff --git a/harness/codeverse3d/tracks/planner.py b/harness/codeverse3d/tracks/planner.py
deleted file mode 100644
index 7365e5d9..00000000
--- a/harness/codeverse3d/tracks/planner.py
+++ /dev/null
@@ -1,933 +0,0 @@
-"""Planner: spec → validated Plan (StaticPlan / ArticulatedPlan / ScenePlan / GraphicsPlan)."""
-
-from __future__ import annotations
-
-import hashlib
-import json
-import logging
-import re
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any, TypeVar
-
-from pydantic import BaseModel, ValidationError
-
-from codeverse3d.config import get_settings
-from codeverse3d.contracts.chat import ChatMessage, ChatRequest, ImagePart
-from codeverse3d.contracts.common import Language, Track, Usage
-from codeverse3d.contracts.plan import (
- AcceptanceItem,
- EngineeringBrief,
- ScenePlan,
- scene_plan_schema,
-)
-from codeverse3d.contracts.spec import Spec
-from codeverse3d.conventions import LANGUAGE_FRAME, frame_doc, to_pascal, to_snake
-from c3d_flywheel.models import get_chat_model
-from codeverse3d.schema_utils import ask_structured, parse_json_lenient
-from codeverse3d.proc import NULL_EVENTS, sha256_file, write_text_atomic
-from codeverse3d.prompts import load_text, prompt_hash, render
-from codeverse3d.prompts.catalog import contract_sections, language_text
-from codeverse3d.tracks.prompting import constraints_text
-from codeverse3d.workspace import Workspace
-
-log = logging.getLogger(__name__)
-
-
-# ===================================================================== the brief
-#: tracks the object-shaped brief applies to (graphics/scene get budgets only)
-BRIEF_TRACKS = (Track.STATIC_OBJECT, Track.ARTICULATED_OBJECT)
-BRIEF_TEMPLATE = "tracks/brief_object.j2"
-
-
-# ----------------------------------------------------------------------------- brief
-def brief_enabled(spec: Spec) -> bool:
- """Whether to expand the brief for this spec (``C3D_PLAN_BRIEF``; object tracks only)."""
- return get_settings().plan_brief and spec.track in BRIEF_TRACKS
-
-
-def brief_cache_dir() -> Path:
- """``Settings.cache_dir``/briefs: ``C3D_CACHE_DIR`` AND the config file's ``cache_dir:``."""
- return get_settings().cache_dir / "briefs"
-
-
-def _reference_digest(spec: Spec) -> list[dict[str, str]]:
- """Identify the reference images by path AND content hash."""
- out: list[dict[str, str]] = []
- for r in spec.references:
- try:
- digest = sha256_file(r.path)
- except OSError:
- digest = "(unreadable)"
- out.append({"path": r.path, "role": r.role, "note": r.note, "sha256": digest})
- return out
-
-
-def brief_cache_key(spec: Spec, model_id: str) -> str:
- """Every input to the call must be in the key (the call is the same for every track and language)."""
- c = spec.constraints
- payload = json.dumps({
- "prompt": spec.prompt.strip(),
- "must_have": list(c.must_have), "must_not": list(c.must_not), "style": c.style,
- "dimensions_m": c.dimensions_m or {}, "model": model_id,
- "references": _reference_digest(spec),
- "template": prompt_hash(load_text(BRIEF_TEMPLATE)),
- }, sort_keys=True)
- return hashlib.sha256(payload.encode()).hexdigest()[:20]
-
-
-def expand_brief(spec: Spec, model_id: str, *, model: Any | None = None, events: Any | None = None,
- cache_dir: Path | None = None) -> tuple[EngineeringBrief | None, Usage]:
- """One cheap structured call → :class:`EngineeringBrief`, cached by prompt hash."""
- events = NULL_EVENTS if events is None else events
- usage = Usage()
- cdir = cache_dir if cache_dir is not None else brief_cache_dir()
- key = brief_cache_key(spec, model_id)
- path = cdir / f"{key}.json"
- if path.is_file():
- try:
- brief = EngineeringBrief.model_validate_json(path.read_text())
- if not brief.is_useful:
- raise ValueError("cached brief has nothing to plan from")
- events.emit("plan.brief", cached=True, key=key, n_sub=len(brief.sub_assemblies),
- n_signature=len(brief.signature_features), cost_usd=0.0)
- return brief, usage
- except (ValidationError, ValueError, OSError) as e:
- log.warning("brief cache %s unusable (%s); regenerating", path, e)
- if model is None:
- model = get_chat_model(model_id)
- system = render(BRIEF_TEMPLATE)
- images = [ImagePart(path=r.path, label=f"{r.role}: {r.note}".strip(": ")) for r in spec.references]
- user = f"REQUEST: {spec.prompt.strip()}"
- if spec.constraints.must_have:
- user += "\n\nThe user also requires:\n" + "\n".join(f"- {m}" for m in spec.constraints.must_have)
- if spec.constraints.dimensions_m:
- user += "\n\nStated dimensions (m): " + ", ".join(f"{k}={v:.3f}" for k, v in spec.constraints.dimensions_m.items())
- if images:
- user += f"\n\n{len(images)} reference image(s) are attached — read the dimensions and features off them."
- try:
- brief, usage, error = ask_structured(model, EngineeringBrief, system=system, text=user, images=images,
- temperature=0.3, label="planner-brief")
- if brief is None:
- raise ValueError(error)
- if not brief.is_useful:
- raise ValueError(f"brief has {len(brief.sub_assemblies)} sub-assemblies and "
- f"{len(brief.signature_features)} signature features — nothing to plan from")
- except Exception as e: # noqa: BLE001 — the brief is an optional accelerator, never a failure mode
- log.warning("brief expansion failed (%s: %s); planning without it", type(e).__name__, e)
- events.emit("plan.brief_failed", error=f"{type(e).__name__}: {e}"[:300])
- return None, usage
- try:
- write_text_atomic(path, brief.model_dump_json(indent=1))
- except OSError as e:
- log.warning("could not cache brief at %s: %s", path, e)
- events.emit("plan.brief", cached=False, key=key, n_sub=len(brief.sub_assemblies),
- n_signature=len(brief.signature_features), cost_usd=round(usage.cost_usd, 5))
- return brief, usage
-
-
-def brief_block(brief: EngineeringBrief | None) -> str:
- """The brief as a prompt block for the planner's user message ("" when absent)."""
- if brief is None:
- return ""
- out = ["ENGINEERING BRIEF (researched for this request — treat it as ground truth about the real object):",
- f"- it is: {brief.one_line or brief.object_name}"]
- if brief.reference:
- out.append(f"- reference instance the numbers come from: {brief.reference}")
- if brief.dimensions_m:
- out.append("- real-world dimensions (m): " + ", ".join(f"{d.name} {d.meters:.3f}" for d in brief.dimensions_m))
- if brief.mechanism:
- out.append(f"- how it works: {brief.mechanism}")
- if brief.sub_assemblies:
- out.append(f"- sub-assemblies a real one has ({len(brief.sub_assemblies)}):")
- for s in brief.sub_assemblies:
- bits = f" · {s.name}"
- if s.purpose:
- bits += f" — {s.purpose}"
- if s.parts:
- bits += f"; made of: {', '.join(s.parts)}"
- if s.material:
- bits += f" [{s.material}]"
- out.append(bits)
- if brief.visible_from_outside:
- out.append("- visible from outside (model these): " + "; ".join(brief.visible_from_outside))
- if brief.hidden_inside:
- out.append("- inside, NOT visible (do not model): " + "; ".join(brief.hidden_inside))
- if brief.not_present:
- out.append("- it does NOT have: " + "; ".join(brief.not_present))
- if brief.materials:
- out.append("- materials: " + "; ".join(brief.materials))
- if brief.signature_features:
- out.append(f"- SIGNATURE FEATURES ({len(brief.signature_features)}) — a viewer recognises the object by these; "
- "every one of them must be a part, a sub-part or a named detail in your plan:")
- out += [f" {i}. {f}" for i, f in enumerate(brief.signature_features, 1)]
- return "\n".join(out)
-
-
-# ===================================================================== plan budgets
-#: practical ceiling on TOP-LEVEL plan parts per language. Blender/three.js own one
-#: file per part so they scale; cadquery is one file; urdf links cost a joint each and
-#: the collision sweep is O(links² × poses), so depth there goes into sub-parts.
-PART_CAP: dict[str, int] = {
- Language.BLENDER.value: 20,
- Language.THREEJS.value: 20,
- Language.CADQUERY.value: 14,
- Language.URDF_BLENDER.value: 10,
-}
-DEFAULT_PART_CAP = 14
-MIN_PARTS = 6
-#: a checklist this long (or a brief) is EVIDENCE that the request really needs the target
-#: part count; below it the target is an aspiration the gate must not enforce
-EVIDENCE_MIN_CHECKLIST = 4
-
-# --------------------------------------------------------------------- "is this a box?"
-#: construction verbs / counted repeated features that make a part description more than
-#: "a box of size X". Stems, not bare words: `taper` alone never matches "tapered", which
-#: is how every real plan writes it.
-_CRAFT = re.compile(
- r"\b(bevel\w*|chamfer\w*|fillet\w*|round(?:ed)?[- ](?:edge|corner|over)\w*|bullnose\w*|taper\w*|groove\w*"
- r"|flute\w*|thread(?:ed|s)?|helix|helical|spline\w*|loft\w*|revolv\w*|extrud\w*|bezier|swept|sweep\w*"
- r"|profile[ds]?|inset\w*|boolean\w*|subdivi\w*|smooth[- ]shad\w*|array\w*|lattice\w*|slot(?:s|ted)?"
- r"|notch\w*|ribs?|louvre\w*|louver\w*|knurl\w*|serrat\w*|scallop\w*|hollow\w*|shell(?:ed)?|cut-?out\w*"
- r"|recess\w*|emboss\w*|moulding\w*|molding\w*|curv\w*|arc\b|arch\w*|spiral\w*|dome[ds]?|domed|ogee"
- r"|scroll\w*|pierc\w*|perforat\w*|crown\w*|swage\w*|bulg\w*|waist\w*|concave|convex|rebate[ds]?|dovetail\w*"
- r"|mortise\w*|tenon\w*|splay\w*|conical|tapering|beading|reeded|turned|rounded|radius|radii)\b"
- r"|\br\s*=\s*\d",
- re.I)
-_COUNTED = re.compile(
- r"\b\d+\s*(x|×)?\s*(slats?|spokes?|teeth|dentils?|panes?|rafters?|bolts?|screws?|rivets?|holes?|segments?"
- r"|facets?|ribs?|flutes?|turns?|steps?|rings?|wires?|bars?|louvres?|louvers?|vents?|grooves?|studs?|pads?)\b",
- re.I)
-_GFX_CRAFT = re.compile(
- r"\b(fbm|noise|hash|sdf|raymarch|ray[- ]?march|march|domain[- ]?warp|voronoi|worley|curl|advect|feedback"
- r"|parallax|refract|reflect|fresnel|bokeh|blur|bloom|vignette|aberration|tonemap|gamma|dither|grain"
- r"|particle|instanc|scatter|caustic|godray|god[- ]ray|volumetric|shadow|ao\b|ambient occlusion|palette"
- r"|gradient|dissolve|erosion|turbulen|flow[- ]?map|displac|tessell|subsurface|halftone|posteris|posteriz)\b",
- re.I)
-_NUMBER = re.compile(r"\d+(?:\.\d+)?")
-
-
-def has_real_detail(text: str) -> bool:
- """True when a part description says something a box cannot say."""
- return bool(_CRAFT.search(text) or _COUNTED.search(text))
-
-
-def has_pass_detail(text: str) -> bool:
- """True when a graphics pass description names a technique or carries a recipe."""
- return bool(_GFX_CRAFT.search(text)) or len(_NUMBER.findall(text)) >= 2
-
-
-@dataclass(frozen=True)
-class PlanBudget:
- """What this request is worth, in plan units. ``target_parts`` is what the prompt"""
-
- target_parts: int
- min_parts: int
- cap_parts: int
- target_leaves: int
- min_detail_parts: int
- min_assemblies: int
- reason: str = ""
- evidence: bool = False
-
- def as_dict(self) -> dict[str, int | str | bool]:
- return {"target_parts": self.target_parts, "min_parts": self.min_parts, "cap_parts": self.cap_parts,
- "target_leaves": self.target_leaves, "min_detail_parts": self.min_detail_parts,
- "min_assemblies": self.min_assemblies, "budget_evidence": self.evidence, "reason": self.reason}
-
-
-GRAPHICS_CAP = 6
-GRAPHICS_MIN = 1
-
-
-def plan_budget(spec: Spec, brief: EngineeringBrief | None = None) -> PlanBudget:
- """Derive the plan's size budget from the REQUEST, not from a constant."""
- if spec.track is Track.GRAPHICS:
- return _graphics_budget(spec)
- cap = PART_CAP.get(spec.language.value, DEFAULT_PART_CAP)
- n_must = len(spec.constraints.must_have)
- reasons = []
- want = 0
- if n_must:
- want = max(want, n_must)
- reasons.append(f"{n_must} checklist items")
- n_visible = 0
- if brief is not None:
- n_sub, n_sig = len(brief.sub_assemblies), len(brief.signature_features)
- if n_sub + n_sig:
- want = max(want, n_sub + n_sig)
- reasons.append(f"{n_sub} sub-assemblies + {n_sig} signature features")
- n_visible = len(brief.visible_from_outside)
- target = max(MIN_PARTS, min(cap, int(want)))
- floor = max(2, int(round(0.85 * min(cap, int(want)))))
- min_assemblies = 0
- if brief is not None:
- min_assemblies = min(3, sum(1 for s in brief.sub_assemblies if len(s.parts) >= 3))
- elif target >= 10:
- min_assemblies = 1
- return PlanBudget(
- target_parts=target,
- min_parts=floor,
- cap_parts=cap,
- target_leaves=max(target + 4, int(round(1.8 * target)), n_visible + 2 * min_assemblies),
- min_detail_parts=min(floor, max(2, int(round(0.35 * target)))),
- min_assemblies=min_assemblies,
- reason="; ".join(reasons) or "no checklist",
- evidence=n_must >= EVIDENCE_MIN_CHECKLIST or brief is not None,
- )
-
-
-def _graphics_budget(spec: Spec) -> PlanBudget:
- """Pass budget for the graphics track (see :data:`GRAPHICS_CAP`)."""
- n_must = len(spec.constraints.must_have)
- target = max(GRAPHICS_MIN, min(GRAPHICS_CAP, GRAPHICS_MIN + (n_must + 1) // 3))
- return PlanBudget(
- target_parts=target, min_parts=max(GRAPHICS_MIN, target - 1), cap_parts=GRAPHICS_CAP,
- target_leaves=4 * target, min_detail_parts=max(1, target - 1), min_assemblies=0,
- reason=f"{n_must} checklist items" if n_must else "no checklist",
- evidence=n_must >= EVIDENCE_MIN_CHECKLIST)
-
-
-def budget_block(budget: PlanBudget, *, unit: str = "parts") -> str:
- """The budget as a prompt block for the planner's user message."""
- lines = [f"PLAN BUDGET (derived from this request: {budget.reason}):"]
- if budget.evidence:
- lines.append(f"- plan at least {budget.min_parts} top-level {unit} (ceiling {budget.cap_parts}); "
- "a plan under that is re-asked.")
- lines.append(f"- at least {budget.min_detail_parts} of them say what a plain "
- + ("fill cannot: the technique by name, or the pass's own quantities." if unit == "passes" else
- "primitive cannot, where the real object has it: a profile, an edge radius, a counted "
- "repeat, or the sub-shapes it is made of.")
- + " A plan with fewer is re-asked.")
- else:
- lines.append(f"- as many top-level {unit} as the " + ("effect" if unit == "passes" else "object")
- + f" really has (ceiling {budget.cap_parts}); nothing here sets a count.")
- if unit != "passes":
- lines.append("- `children` for a part a fitter would call an assembly rather than a shape.")
- return "\n".join(lines)
-
-
-# ----------------------------------------------------------------------------- quality gate
-def plan_quality_complaint(plan_obj: Any, budget: PlanBudget, *, unit: str = "parts") -> str:
- """"" when the plan is worth building; otherwise the SPECIFIC complaint to re-ask with."""
- parts: list[Any] = list(getattr(plan_obj, "parts", None) or getattr(plan_obj, "passes", None) or [])
- if not parts:
- return ""
- nest = "elements" if unit == "passes" else "children"
- hard: list[str] = []
- soft: list[str] = []
- if budget.evidence and len(parts) < budget.min_parts:
- hard.append(
- f"Only {len(parts)} {unit} for a request that needs at least {budget.min_parts} "
- f"({budget.reason}). Split the ones that are really assemblies and add the features you skipped — "
- f"do NOT pad with duplicates.")
- detector = has_pass_detail if unit == "passes" else has_real_detail
- detailed = [p for p in parts if detector(f"{p.description} {getattr(p, 'detail_hint', '')}")
- or getattr(p, "children", None) or getattr(p, "elements", None)]
- if len(detailed) < budget.min_detail_parts:
- plain = [p.name for p in parts if p not in detailed][:8]
- # enforced only on EVIDENCE (a brief, or a long checklist): without it the request never
- # said the object has shaping a primitive cannot express — "a stool" may be four boxes
- (hard if budget.evidence else soft).append(
- f"This plan is boxes at different sizes: only {len(detailed)} of {len(parts)} {unit} describe anything a "
- f"plain primitive cannot express, and this request needs at least {budget.min_detail_parts}. Rewrite "
- f"{', '.join(plain)} where the real thing has it: a profile, a stated radius or edge "
- f"treatment, a counted repeat, or the sub-shapes it is actually made of.")
- if budget.min_assemblies:
- n_nested = sum(1 for p in parts if getattr(p, nest, None))
- if n_nested < budget.min_assemblies:
- soft.append(
- f"{n_nested} of the {unit} use `{nest}`, but this request has at least {budget.min_assemblies} real "
- f"sub-assemblies. Give each of them its `{nest}`" +
- ("" if unit == "passes" else " with their own bboxes (inside the parent's) and materials") +
- f"; leave the simple {unit} alone.")
- materials = {(getattr(p, "material", "") or "").strip().lower() for p in parts} - {""}
- if unit == "parts" and len(parts) >= 5 and len(materials) <= 1:
- soft.append("Every part has the same material (or none). Real objects mix materials — give each part its "
- "own material with a colour.")
- if not hard:
- return ""
- return ("Your plan is valid but not worth building yet. Fix EXACTLY these problems and return the full corrected "
- "plan JSON again (same schema), keeping everything that was already good:\n- " + "\n- ".join(hard + soft))
-
-
-# ----------------------------------------------------------------------------- enrichment
-def _fold_pass(ps: Any) -> None:
- """Fold a graphics pass's ``elements`` + ``detail_hint`` into its ``description``."""
- if not (ps.elements or ps.detail_hint) or " · " in ps.description:
- return
- bits = [ps.description.rstrip().rstrip(".")]
- if ps.elements:
- bits.append("draws: " + " · ".join(e.strip() for e in ps.elements))
- if ps.detail_hint:
- bits.append(f"what makes it real: {ps.detail_hint.strip()}")
- ps.description = " · ".join(bits).replace("\n", " ").replace("|", "/")
-
-
-def enrich_plan(plan_obj: Any, brief: EngineeringBrief | None) -> Any:
- """Fold what the BRIEF knows back into the plan's own fields, after validation."""
- for ps in getattr(plan_obj, "passes", None) or []:
- _fold_pass(ps)
- if brief is None:
- return plan_obj
- items: list[AcceptanceItem] = list(plan_obj.acceptance)
- for feature in brief.signature_features:
- add_acceptance_item(items, "sig", f"Signature feature visible: {feature.strip()}", "visual", priority="should")
- plan_obj.acceptance = items
- notes = plan_obj.style_notes
- extra = []
- if brief.reference and brief.reference.lower() not in notes.lower():
- extra.append(f"Reference instance: {brief.reference}.")
- if brief.not_present:
- extra.append("Does NOT have: " + "; ".join(brief.not_present) + ".")
- if extra:
- plan_obj.style_notes = " ".join([notes.strip(), *extra]).strip()
- return plan_obj
-
-
-# ===================================================================== worked examples
-def plan_example(track: Track, language: Language | None = None) -> dict[str, Any]:
- """Compact, valid worked example per track (concrete beats abstract) — and, where a language"""
- if track is Track.SCENE and language is Language.SCENE_BLENDER:
- example = plan_example(Track.SCENE)
- for asset in example["assets"]:
- if asset["kind"] == "threejs":
- asset["kind"] = "bpy"
- return example
- if track is Track.GRAPHICS:
- return {
- "title": "Tide pool ripples", "summary": "Looking straight down into a shallow tide pool: pebbles and weed on "
- "the floor, rings spreading from drops that fall at irregular intervals; light shifts over the pebbles.",
- "style": "naturalistic: wet slate greys and ochre pebbles, olive weed, cold sky-blue reflections; soft, glossy",
- "resolution": [1280, 720], "duration_s": 8.0,
- "passes": [
- {"name": "PoolFloor", "kind": "fullscreen", "description": "rounded pebbles 0.03-0.08 of screen height packed "
- "over sand, a few olive weed strands, seen through the water and displaced by the surface's slope"},
- {"name": "SurfaceRipples", "kind": "fullscreen", "description": "rings expanding from drop points at about 0.15 "
- "screen heights per second and fading over 3 s; their slope bends the floor and carries the sky's reflection",
- "elements": ["drop rings, 1-3 alive at a time"],
- "detail_hint": "two rings that cross interfere instead of one overwriting the other"},
- ],
- "uniforms": ["u_time", "u_resolution"],
- "motion": "new drops land at irregular intervals and their rings spread and fade; the weed sways slowly; no hard cuts",
- "key_visuals": ["pebbles under shallow water", "expanding ripple rings", "light shifting over the floor"],
- "acceptance": [
- {"id": "a1", "text": "Ripple rings visibly expand between t=0 and t=1", "how": "visual", "priority": "must"},
- {"id": "a2", "text": "Pebbles are visible through the water and bend where a ring passes", "how": "visual", "priority": "must"},
- {"id": "a3", "text": "Frames change over time (no static image)", "how": "probe", "priority": "must"},
- ],
- }
- if track is Track.SCENE:
- return {
- "title": "Harbour at dusk", "summary": "Small fishing harbour: an L of granite quay on the west side, two boats "
- "moored against it, the basin opening east to the sea; the mole runs out of the bounds to the north-east.",
- "setting": "Breton coast, 1960s, clear dusk", "mood": "calm, warm low sun",
- "bounds": {"center": [0, 5, 0], "extents": [100, 30, 70]},
- "environment": "Sky zenith 0x2b3f6e to horizon 0xf0a060, sun azimuth 250° elevation 8°; fog 0xe8a070 near 60 m far "
- "320 m; sea plane y=0 colour 0x2f4a55 to the east horizon; the quay deck is flat at y=1.2 along x -40..0 and "
- "the village street climbs 3 m out of the bounds to the west; the mole continues 60 m past the bounds to the "
- "north-east with the lighthouse at its end; low headland 300 m off to the south.",
- "zones": [
- {"name": "Quay", "description": "L-shaped granite quay deck at y=1.2 along the west and north edges; bollards every "
- "6 m on the edge, crates stacked by the net shed; seen by Overview and QuayEye",
- "bbox": {"center": [-20, 1.2, 0], "extents": [40, 3, 60]}, "contents": ["Bollard", "Crate"]},
- {"name": "Water", "description": "the basin: two boats moored bow-in against the quay edge 12 m apart, open water "
- "east of them past the bounds to the sea (the zone runs out of the bounds on the east; the quay head "
- "north of z=-30 is open ground no zone covers)", "bbox": {"center": [30, 0, 5], "extents": [60, 1, 60]},
- "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": [38, 4, -30], "look_at": [-12, 1.5, 6], "fov": 48,
- "purpose": "establishing: low over the basin from the mole to the north-east, looking back along the quay "
- "at the two moored boats; the village street climbs out of frame behind them, open water right"},
- {"name": "QuayEye", "position": [-5, 2.8, 25], "look_at": [8, 1, -8], "fov": 60,
- "purpose": "eye level on the quay deck, looking along the edge at the nearer boat"}],
- "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": "Base", "role": "weighted foot", "description": "disc 400 mm dia, 30 mm thick, top edge rounded r=8 mm, "
- "four 20 mm square sockets for the uprights",
- "bbox": {"center": [0, 0, 0.015], "extents": [0.40, 0.40, 0.03]}, "material": "cast iron, satin black", "attach_to": None,
- "symmetry": "none", "instances": 1, "children": [], "detail_hint": "the rounded edge and the four sockets are what reads at floor level"},
- {"name": "Upright", "role": "vertical bar", "description": "square bar 20 mm, upper 100 mm tapered to 14 mm, foot seated in a base socket",
- "bbox": {"center": [0.16, 0, 0.455], "extents": [0.02, 0.02, 0.85]}, "material": "oiled ash, pale", "attach_to": "Base",
- "symmetry": "radial", "instances": 4, "children": [], "detail_hint": ""},
- {"name": "TopFrame", "role": "pegged ring the bunches hang from", "description": "flat ring on the upright tops, crossed by "
- "two bars, pegs round the rim and a finial at the crossing",
- "bbox": {"center": [0, 0, 0.905], "extents": [0.42, 0.42, 0.05]}, "material": "oiled ash, pale", "attach_to": "Upright",
- "symmetry": "radial", "instances": 1, "detail_hint": "an assembly, not a disc: the gaps between ring, bars and pegs show from every side",
- "children": [
- {"name": "Ring", "role": "flat ring", "description": "outer dia 340 mm, 20 mm wide, 12 mm thick, edges rounded r=3 mm",
- "bbox": {"center": [0, 0, 0.886], "extents": [0.34, 0.34, 0.012]}, "instances": 1},
- {"name": "CrossBar", "role": "bar across the ring", "description": "20 × 12 mm bar, ends halved into the ring",
- "bbox": {"center": [0, 0, 0.886], "extents": [0.34, 0.02, 0.012]}, "instances": 2},
- {"name": "Peg", "role": "hanging peg", "description": "12 turned pegs 10 mm dia, 40 mm proud of the rim, ends domed",
- "bbox": {"center": [0.19, 0, 0.886], "extents": [0.04, 0.01, 0.01]}, "instances": 12},
- {"name": "Finial", "role": "knob at the crossing", "description": "turned knob 40 mm dia on a 10 mm neck",
- "bbox": {"center": [0, 0, 0.911], "extents": [0.04, 0.04, 0.038]}, "instances": 1},
- ]},
- ]
- base: dict[str, Any] = {
- "object_name": "HerbDryingRack",
- "summary": "Free-standing herb drying rack: a round iron foot, four tapered uprights and a pegged top ring, 0.42 × 0.42 × 0.93 m.",
- "overall_bbox": {"center": [0, 0, 0.465], "extents": [0.42, 0.42, 0.93]},
- "style_notes": "Scandinavian kitchen craft: pale oiled ash on a black iron foot, rounded edges, no ornament.",
- "parts": parts,
- "acceptance": [{"id": "a1", "text": "Overall height 0.93 m ± 0.02 m", "how": "measure", "priority": "must"},
- {"id": "a2", "text": "Four uprights stand in the foot, which rests flat on the ground", "how": "visual", "priority": "must"}],
- }
- if track is Track.ARTICULATED_OBJECT:
- base["object_name"] = "DeskDrawerUnit"
- base["summary"] = "Painted desk drawer unit, 0.40 × 0.50 × 0.60 m: one drawer on side runners."
- base["overall_bbox"] = {"center": [0, 0, 0.3], "extents": [0.4, 0.5, 0.6]}
- base["style_notes"] = "Plain painted carcass, a shadow gap round the drawer, one metal pull."
- base["parts"] = [
- {"name": "Cabinet", "role": "fixed carcass", "description": "18 mm carcass, 6 mm rebated back, 3 mm shadow gap round the drawer opening",
- "bbox": {"center": [0, 0, 0.3], "extents": [0.4, 0.5, 0.6]}, "material": "painted MDF", "attach_to": None, "symmetry": "none", "instances": 1,
- "children": [], "detail_hint": "the opening's shadow gap is what makes the drawer read as a drawer"},
- {"name": "Drawer", "role": "sliding drawer (ONE link, four sub-parts)", "description": "drawer box running on side runners",
- "bbox": {"center": [0, -0.02, 0.45], "extents": [0.36, 0.46, 0.2]}, "material": "painted MDF", "attach_to": "Cabinet", "symmetry": "none", "instances": 1,
- "detail_hint": "one rigid body, but never one box",
- "children": [
- {"name": "Front", "role": "drawer face", "description": "18 mm face, 4 mm bullnose, overhangs the box 8 mm on every side",
- "bbox": {"center": [0, -0.24, 0.45], "extents": [0.36, 0.018, 0.19]}, "material": "painted MDF", "instances": 1},
- {"name": "Box", "role": "drawer body", "description": "12 mm sides, 8 mm base set into a 6 mm groove, open top",
- "bbox": {"center": [0, 0.0, 0.45], "extents": [0.33, 0.42, 0.17]}, "material": "birch ply", "instances": 1},
- {"name": "Knob", "role": "pull", "description": "turned knob 32 mm dia, 22 mm proud, on a 10 mm neck",
- "bbox": {"center": [0, -0.26, 0.45], "extents": [0.032, 0.032, 0.032]}, "material": "brushed steel", "instances": 1},
- {"name": "Runner", "role": "side runner", "description": "10 × 10 mm strip along each side, full depth",
- "bbox": {"center": [0.17, 0.0, 0.40], "extents": [0.01, 0.42, 0.01]}, "material": "birch ply", "instances": 2},
- ]},
- ]
- 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"] = [{"id": "a1", "text": "Cabinet top at 0.60 m ± 0.02 m above the ground", "how": "measure", "priority": "must"},
- {"id": "a2", "text": "Cabinet stands on the ground at rest", "how": "visual", "priority": "must"},
- {"id": "j1", "text": "Drawer slides out 0.35 m along -Y without penetrating the cabinet", "how": "articulation", "priority": "must"}]
- return base
-
-
-P = TypeVar("P", bound=BaseModel)
-
-MAX_VALIDATION_REASKS = 2
-MAX_QUALITY_REASKS = 1
-MAX_PLAN_RESTARTS = 1
-PLAN_TOKENS_PER_PART = 600
-PLAN_TOKENS_PER_LEAF = 400
-PLAN_TOKENS_MAX = 65_536
-TRUNCATION_GROWTH = 1.5
-PLAN_MAX_WAIT_S = 900.0
-PLAN_SLOW_TOKENS_PER_S = 60.0
-PLAN_WAIT_OVERHEAD_S = 60.0
-
-
-TRUNCATION_WAIT_SCALE = 1.5
-
-
-def plan_wait_s(tokens: int, guard: object | None = None, *, scale: float = 1.0) -> float:
- """How long one planner call may take, given the answer size it asked for."""
- want = max(PLAN_MAX_WAIT_S, tokens / PLAN_SLOW_TOKENS_PER_S + PLAN_WAIT_OVERHEAD_S) * scale
- fn = getattr(guard, "timeout_s", None)
- return float(fn(want)) if callable(fn) else want
-
-
-def plan_tokens(budget: PlanBudget, floor: int) -> int:
- """Output-token ceiling for a plan of this size (never below the caller's ``floor``)."""
- want = floor + PLAN_TOKENS_PER_PART * budget.target_parts + PLAN_TOKENS_PER_LEAF * budget.target_leaves
- return min(PLAN_TOKENS_MAX, max(floor, want))
-
-
-TRUNCATION_NOTE = ("\n\nCOMPACT ANSWER REQUIRED: your previous answer did not fit in the output budget "
- "({tokens} tokens). Return the same plan with every `description` at most 25 words, at most 6 "
- "`children` per part and nothing outside the JSON. Answer directly without long deliberation.")
-
-
-def _with_note(msg: ChatMessage, note: str) -> ChatMessage:
- """The same user message with ``note`` appended to its text (images kept)."""
- images = [p for p in msg.parts if isinstance(p, ImagePart)] or None
- return ChatMessage.user(msg.text + note, images=images)
-
-
-_PLACEHOLDERS = {"string", "str", "name", "text", "..."}
-
-
-def _schema_echo(raw: dict[str, Any]) -> str:
- """"" or what in ``raw`` is a JSON-schema placeholder (``"name": "string"``) rather than content."""
- bad: list[str] = []
- if str(raw.get("object_name", "")).strip().lower() in _PLACEHOLDERS:
- bad.append("object_name")
- for key in ("parts", "joints", "zones", "assets", "passes"):
- for i, item in enumerate(raw.get(key) or []):
- if isinstance(item, dict) and str(item.get("name", "")).strip().lower() in _PLACEHOLDERS:
- bad.append(f"{key}[{i}].name")
- return ", ".join(bad[:6])
-
-
-def missing_link_names(raw: Any) -> list[str]:
- """Link names the joints reference that ``parts`` does not define (snake-compared)."""
- if not isinstance(raw, dict):
- return []
- parts = raw.get("parts")
- joints = raw.get("joints")
- if not isinstance(parts, list) or not isinstance(joints, list):
- return []
- known = {to_snake(str(p.get("name", ""))) for p in parts if isinstance(p, dict)}
- known |= {to_snake(str(c.get("name", ""))) for p in parts if isinstance(p, dict)
- for c in (p.get("children") or []) if isinstance(c, dict)}
- missing: list[str] = []
- for j in joints:
- if not isinstance(j, dict):
- continue
- for side in ("parent", "child"):
- name = str(j.get(side, "")).strip()
- if name and to_snake(name) not in known and name not in missing:
- missing.append(name)
- return missing
-
-
-def restart_note(raw: Any, missing: list[str], budget: PlanBudget) -> str:
- """The user turn that replaces the whole conversation when a plan comes back degenerate."""
- n_parts = len(raw.get("parts") or []) if isinstance(raw, dict) else 0
- return (
- "\n\nYour previous attempt listed only "
- f"{n_parts} top-level part(s) and then referenced links it never defined: "
- f"{', '.join(missing[:10])}. Start again from this request. Rules that answer is missing:\n"
- f"- `parts` must contain EVERY link a joint names, each with its own name, bbox and material "
- f"(at least {budget.min_parts} parts for this request).\n"
- "- `joints[].parent` and `joints[].child` must be spelled exactly like those part names.\n"
- "- Nothing that a joint moves may live in `children`; sub-parts are rigid detail only."
- )
-
-
-def restart_enabled() -> bool:
- return get_settings().plan_restart
-
-
-INVALID_PLAN_DIR = "stages/plan/invalid"
-MAX_INVALID_PLAN_BYTES = 200_000
-
-
-def _record_invalid(ws: Workspace, attempt: int, raw: Any, text: str) -> None:
- """Write the rejected answer beside the run. Never raises: this is a diagnostic."""
- try:
- body = json.dumps(raw, indent=1, default=str) if isinstance(raw, dict) else (text or "")
- out = ws.root / INVALID_PLAN_DIR
- out.mkdir(parents=True, exist_ok=True)
- (out / f"attempt{attempt:02d}.json").write_text(body[:MAX_INVALID_PLAN_BYTES])
- except (OSError, TypeError, ValueError) as e: # noqa: BLE001 — a diagnostic never fails a run
- log.debug("could not record the invalid plan attempt: %s", e)
-
-
-def degenerate_plan(raw: Any, budget: PlanBudget) -> bool:
- """A plan too small to be an attempt at this request: a third of the floor or less."""
- parts = raw.get("parts") if isinstance(raw, dict) else None
- return isinstance(parts, list) and len(parts) <= max(2, budget.min_parts // 3)
-
-
-def _thin_plan_note(raw: Any, budget: PlanBudget) -> str:
- """A second line for the validation re-ask when the invalid plan is also far too small."""
- if not degenerate_plan(raw, budget):
- return ""
- parts = raw.get("parts")
- return (f"\nAlso: this plan lists only {len(parts)} part(s) but the request needs at least {budget.min_parts} "
- f"({budget.reason}). Put EVERY link a joint references under `parts` with its own bbox.")
-
-
-def _truncated(exc: Exception) -> bool:
- """Did this model error mean 'the answer did not fit'?"""
- return "MAX_TOKENS" in str(exc)
-
-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",
- Track.GRAPHICS: "tracks/plan_graphics.j2",
-}
-PLAN_OUTPUT_FLOOR = 24_000
-
-
-def plan_schema(spec: Spec, plan_model: type[BaseModel]) -> dict[str, Any]:
- """The response schema the planner call carries: a scene's names the asset kinds of ITS"""
- if issubclass(plan_model, ScenePlan):
- return scene_plan_schema(spec.language)
- return plan_model.model_json_schema()
-
-
-def plan_temperature(track: Track) -> float:
- """The planner sampling temperature: 0.5 for a shader brief, 0.4 otherwise."""
- return 0.5 if track is Track.GRAPHICS else 0.4
-
-
-class PlanningError(RuntimeError):
- """The planner could not produce a valid plan after MAX_VALIDATION_REASKS re-asks."""
-
-
-def plan_event_stats(plan_obj: Any) -> dict[str, Any]:
- """The ``plan.done`` payload: a graphics plan counts passes, every other plan parts and zones."""
- passes = getattr(plan_obj, "passes", None)
- if passes is not None:
- return {"n_passes": len(passes), "n_acceptance": len(plan_obj.acceptance)}
- parts = getattr(plan_obj, "parts", []) or []
- return {"n_parts": len(parts),
- "n_zones": len(getattr(plan_obj, "zones", []) or []),
- "n_nested_parts": sum(1 for p in parts if getattr(p, "children", None)),
- "n_subparts": sum(len(getattr(p, "children", None) or []) for p in parts),
- "n_leaves": getattr(plan_obj, "leaf_count", len(parts)),
- "n_acceptance": len(plan_obj.acceptance)}
-
-
-def plan[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P], ws: Workspace, *, model: Any | None = None,
- events: Any | None = None, budget: Any | None = None) -> P:
- """Plan and write ``ws.plan_path``: optional brief expansion → one structured planner"""
- guard = budget
- events = NULL_EVENTS if events is None else events
- if model is None:
- model = get_chat_model(model_id)
- brief, usage = (None, Usage())
- if brief_enabled(spec):
- if guard is not None:
- guard.check()
- brief, usage = expand_brief(spec, model_id, model=model, events=events)
- budget = plan_budget(spec, brief)
- unit = "passes" if spec.track is Track.GRAPHICS else "parts"
- system = build_system_prompt(spec, plan_model, budget=budget)
- user = build_user_prompt(spec, brief=brief, budget=budget, unit=unit)
- 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)]
- base_messages = list(messages)
- schema = plan_schema(spec, plan_model)
- last_error = ""
- invalid = requeried = restarts = 0
- tokens = plan_tokens(budget, PLAN_TOKENS_MAX if spec.track is Track.GRAPHICS else PLAN_OUTPUT_FLOOR)
- thinking = "medium"
- wait_scale = 1.0
- for attempt in range(4 + MAX_VALIDATION_REASKS + MAX_QUALITY_REASKS + MAX_PLAN_RESTARTS):
- if guard is not None:
- guard.check()
- req = ChatRequest(messages=messages, system=system, response_schema=schema, temperature=plan_temperature(spec.track),
- thinking=thinking, max_output_tokens=tokens, label=f"planner{'-retry' if attempt else ''}",
- max_wait_s=plan_wait_s(tokens, guard, scale=wait_scale))
- try:
- resp = model.generate(req)
- except Exception as e: # noqa: BLE001 — a truncated plan is retryable; anything else is not
- if not (_truncated(e) and tokens < PLAN_TOKENS_MAX):
- raise
- tokens = min(PLAN_TOKENS_MAX, int(tokens * TRUNCATION_GROWTH))
- thinking = "off"
- wait_scale = TRUNCATION_WAIT_SCALE
- messages = messages[:-1] + [_with_note(messages[-1], TRUNCATION_NOTE.format(tokens=tokens))]
- events.emit("plan.truncated", attempt=attempt, max_output_tokens=tokens, thinking=thinking)
- continue
- usage = usage + resp.usage
- try:
- raw = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text)
- except ValueError:
- raw = None
- try:
- if not isinstance(raw, dict):
- raise ValueError(f"planner returned {type(raw).__name__}, expected a JSON object")
- echoed = _schema_echo(raw)
- if echoed:
- raise ValueError(f"the plan echoes the schema's placeholders instead of describing the object: {echoed}. "
- "Write the REAL plan: actual part names, real numbers, a unit axis for every joint.")
- result = plan_model.model_validate(raw)
- clash = fixed_part_clash(result, spec)
- if clash:
- raise ValueError(clash)
- except (ValidationError, ValueError) as e:
- last_error = str(e)[:4000]
- _record_invalid(ws, attempt, raw, resp.text)
- events.emit("plan.invalid", attempt=attempt, error=last_error[:500])
- missing = missing_link_names(raw)
- if (missing and degenerate_plan(raw, budget)
- and restarts < MAX_PLAN_RESTARTS and restart_enabled()):
- restarts += 1
- events.emit("plan.restart", attempt=attempt, n_parts=len(raw.get("parts") or []),
- missing=missing[:10])
- note = TRUNCATION_NOTE.format(tokens=tokens) if thinking == "off" else ""
- messages = base_messages[:-1] + [
- ChatMessage.user(base_messages[-1].text + restart_note(raw, missing, budget) + note,
- images=images or None),
- ]
- continue
- invalid += 1
- if invalid > MAX_VALIDATION_REASKS:
- break
- messages = messages + [
- _echo(raw, resp.text),
- ChatMessage.user("Your plan failed validation. Fix EXACTLY these problems and return the full corrected "
- f"plan JSON again (same schema):\n{last_error}" + _thin_plan_note(raw, budget)),
- ]
- continue
- complaint = plan_quality_complaint(result, budget, unit=unit) if requeried < MAX_QUALITY_REASKS else ""
- if complaint:
- requeried += 1
- events.emit("plan.thin", attempt=attempt, n_parts=len(getattr(result, "parts", None) or getattr(result, "passes", None) or []),
- target_parts=budget.target_parts, complaint=complaint[:400])
- messages = messages + [_echo(raw, resp.text), ChatMessage.user(complaint)]
- continue
- normalised = list(getattr(result, "normalisations", None) or [])
- if normalised:
- events.emit("plan.normalised", attempt=attempt, n=len(normalised), items=normalised[:8])
- result = enrich_plan(ensure_acceptance(normalise_names(result), spec), brief)
- ws.write_json(ws.plan_path, result)
- events.emit("plan.done", model=model_id, **plan_event_stats(result),
- cost_usd=round(usage.cost_usd, 4), prompt_hash=prompt_hash(system), attempt=attempt,
- brief=brief is not None, quality_reasks=requeried, restarts=restarts, **budget.as_dict())
- if guard is not None:
- guard.check()
- return result
- raise PlanningError(f"plan did not validate after re-ask: {last_error}")
-
-
-def _echo(raw: Any, text: str) -> ChatMessage:
- """The model's own answer, echoed back so a re-ask edits it instead of restarting."""
- return ChatMessage.assistant(json.dumps(raw)[:20000] if raw is not None else (text or "")[:20000])
-
-
-# ----------------------------------------------------------------------------- prompts
-#: the ``## `` headings of a scene contract the PLANNER acts on: it writes JSON, so it reads the
-#: files the builders will own and what is measured on them — not the assembler wiring, the shader
-#: loading or the worked modules.
-PLANNER_CONTRACT_SECTIONS: dict[Language, tuple[str, ...]] = {
- Language.SCENE_THREEJS: ("Files", "createScene return value", "What is measured", "Naming"),
- Language.SCENE_BLENDER: ("Files", "Frame and units", "What the renderer does", "Motion", "Naming", "Placement",
- "What else the gates measure", "Interiors"),
-}
-
-
-def planner_contract(lang: Language) -> str:
- text = language_text(lang, "contract.md")
- headings = PLANNER_CONTRACT_SECTIONS.get(lang)
- return contract_sections(text, headings) if headings else text
-
-
-def build_system_prompt(spec: Spec, plan_model: type[BaseModel], *, budget: PlanBudget | None = None) -> str:
- lang: Language = spec.language
- budget = budget or plan_budget(spec)
- return render(
- PLAN_TEMPLATES[spec.track],
- track=spec.track.value,
- language=lang.value,
- frame_doc=frame_doc(LANGUAGE_FRAME[lang.value]),
- contract=planner_contract(lang),
- example_json=json.dumps(plan_example(spec.track, lang), indent=1),
- schema_fields=", ".join(plan_model.model_json_schema().get("properties", {}).keys()),
- target_parts=budget.target_parts,
- min_parts=budget.min_parts,
- cap_parts=budget.cap_parts,
- )
-
-
-def fixed_part_clash(plan_obj: BaseModel, spec: Spec) -> str:
- """'' unless the plan lists one of the spec's fixed parts (``Spec.fixed_parts``) as a part of its own: the
- project builds those, so a planned one invites the agent to author it — the re-ask says which."""
- fixed = {to_snake(f.name): f for f in spec.fixed_parts if f.name}
- if not fixed:
- return ""
- names = [p.name for p in getattr(plan_obj, "parts", None) or []]
- hits = [n for n in names if to_snake(n) in fixed]
- if not hits:
- return ""
- return (f"the plan lists fixed parts {hits} as its own parts: they are given by the project (FIXED PARTS) — "
- "remove them from the plan and plan only the parts around them")
-
-
-def build_user_prompt(spec: Spec, *, brief: Any | None = None, budget: PlanBudget | None = None,
- unit: str = "parts") -> str:
- lines = [f"REQUEST: {spec.prompt}", "", "CONSTRAINTS:", constraints_text(spec)]
- block = brief_block(brief)
- if block:
- lines += ["", block]
- if spec.track is not Track.SCENE:
- lines += ["", budget_block(budget or plan_budget(spec), unit=unit)]
- if spec.references:
- lines += ["", f"REFERENCE IMAGES: {len(spec.references)} attached — match their shape, proportions and visible details; "
- "give real-world dimensions in meters consistent with what they show."]
- lines += ["", "Return the plan as JSON matching the schema."]
- return "\n".join(lines)
-
-
-# ----------------------------------------------------------------------------- deterministic acceptance
-def add_acceptance_item(items: list[AcceptanceItem], prefix: str, text: str, how: str, *,
- priority: str = "must") -> None:
- """Append a framework-derived acceptance item (*must* unless told otherwise) unless an"""
- if text.strip().lower() in {a.text.strip().lower() for a in items}:
- return
- ids = {a.id for a in items}
- n = 1
- while f"{prefix}{n}" in ids:
- n += 1
- items.append(AcceptanceItem(id=f"{prefix}{n}", text=text, how=how, priority=priority)) # type: ignore[arg-type]
-
-
-def ensure_acceptance[P: BaseModel](plan_obj: P, spec: Spec) -> P:
- """Append acceptance items derived from the spec constraints when missing."""
- items: list[AcceptanceItem] = list(plan_obj.acceptance)
- if spec.track is Track.SCENE:
- items = [a if a.priority == "should" else a.model_copy(update={"priority": "should"}) for a in items]
- c = spec.constraints
- solid = spec.track is not Track.GRAPHICS
- if solid and c.dimensions_m:
- dims = ", ".join(f"{k} = {v:.3f} m" for k, v in c.dimensions_m.items())
- add_acceptance_item(items, "dim", f"Overall dimensions match the request within 5%: {dims}", "measure")
- for m in c.must_have:
- add_acceptance_item(items, "must", f"Includes: {m}", "visual")
- for m in c.must_not:
- add_acceptance_item(items, "not", f"Does NOT include: {m}", "visual")
- if not solid:
- planned_motion = getattr(plan_obj, "motion", "").strip()
- if planned_motion and not any(w in a.text.lower() for a in items for w in ("static", "motion", "change over time")):
- add_acceptance_item(items, "motion", "Frames change over time as planned (not a static image)", "probe")
- elif spec.track is not Track.SCENE and not any(a.how == "measure" for a in items):
- add_acceptance_item(items, "ground", "Object stands on the ground plane (lowest point at up=0) with its footprint centred", "measure")
- items.extend(articulation_acceptance(plan_obj, items))
- plan_obj.acceptance = items
- return plan_obj
-
-
-def articulation_acceptance(plan_obj: Any, items: list[AcceptanceItem]) -> list[AcceptanceItem]:
- """One ``articulation`` item per moving joint the planner's own checklist does not cover"""
- joints = [j for j in (getattr(plan_obj, "joints", None) or []) if j.type != "fixed"]
- if not joints:
- return []
- covered = " ".join(a.text.lower() for a in items if a.how == "articulation")
- words = set(re.findall(r"[a-z0-9]+", covered.replace("_", " ")))
- out: list[AcceptanceItem] = []
- for j in joints:
- # whole-word match on the joint's or the child's name ("lid" must not match "slides")
- keys = {j.name.lower(), to_snake(j.child).replace("_", " "), j.child.lower()}
- if any(k and all(w in words for w in re.findall(r"[a-z0-9]+", k)) for k in keys):
- continue
- unit = "m" if j.type == "prismatic" else "rad"
- rest = "closed / stowed" if abs(j.rest) < 1e-9 else f"at {j.rest:.2f} {unit}"
- rng = "turns freely" if j.type == "continuous" else f"moves over [{j.lower:.2f}, {j.upper:.2f}] {unit}"
- out.append(AcceptanceItem(
- id=f"art_{to_snake(j.child)}"[:40], how="articulation", priority="should",
- text=f"Joint {j.name}: at rest {j.child} sits {rest} against {j.parent}; it {rng} — {j.motion} — "
- f"without passing through {j.parent} or any other link (pose_* views)"))
- return out
-
-
-def normalise_names[P: BaseModel](plan_obj: P) -> P:
- """PascalCase part/link/zone/asset names in place — prompts ask for it; code guarantees it."""
- for attr in ("parts", "zones", "assets"):
- for item in getattr(plan_obj, attr, None) or []:
- item.name = to_pascal(item.name)
- 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
diff --git a/harness/codeverse3d/tracks/project_checks.py b/harness/codeverse3d/tracks/project_checks.py
deleted file mode 100644
index 8b15b3cd..00000000
--- a/harness/codeverse3d/tracks/project_checks.py
+++ /dev/null
@@ -1,77 +0,0 @@
-"""Project checks (``Spec.checks``): deterministic checks a project registers by import path, run on every round.
-
-The harness gates what it can know about any object — the build, the plan contract, connectivity, budgets. A
-project often knows more: the true geometry of the thing (a surveyed building, a catalogue part), definitions
-of its own (a building's eaves line) and thresholds. A registered check's reports join the round's gates under
-``project:<name>``: an ERROR becomes a refine task with its ``fix_hint``, the judge reads it in the gates section,
-and a rubric ``CapRule(when="gate", gate="project:*")`` caps the score.
-
-A check is ``fn(*, glb, workspace, spec, measurement, round_index, args) -> GateReport | list[GateReport]``. It
-must be deterministic and must not call a model (Law 3). A check that raises costs the round nothing but a WARN
-saying so: a project's bug must not fail or cap the run.
-"""
-
-from __future__ import annotations
-
-import importlib
-import logging
-import time
-from collections.abc import Sequence
-from pathlib import Path
-from typing import Any, Protocol
-
-from codeverse3d.contracts.artifacts import GateFinding, GateReport, Measurement, Severity
-from codeverse3d.contracts.spec import PROJECT_GATE_PREFIX as PREFIX
-from codeverse3d.contracts.spec import ProjectCheck, Spec
-
-log = logging.getLogger(__name__)
-
-
-
-class CheckFn(Protocol):
- def __call__(self, *, glb: Path, workspace: Path, spec: Spec, measurement: Measurement | None,
- round_index: int, args: dict[str, Any]) -> GateReport | Sequence[GateReport]: ...
-
-
-def load_check(entry: str) -> CheckFn:
- """The function ``entry`` (``package.module:function``) names."""
- module, _, attr = entry.partition(":")
- fn = getattr(importlib.import_module(module), attr)
- if not callable(fn):
- raise TypeError(f"{entry} is not callable")
- return fn
-
-
-def _named(report: GateReport, check: ProjectCheck) -> GateReport:
- """``report`` under ``project:<name>`` (a check returning several reports keeps them apart as
- ``project:<name>.<its gate>``), its findings renamed with it, so caps and refine keys see one namespace."""
- own = report.gate or ""
- if own.startswith(PREFIX):
- gate = own
- elif own in ("", check.name):
- gate = PREFIX + check.name
- else:
- gate = f"{PREFIX}{check.name}.{own}"
- findings = [f.model_copy(update={"gate": gate}) for f in report.findings]
- return report.model_copy(update={"gate": gate, "findings": findings})
-
-
-def run_project_checks(spec: Spec, workspace: Path, glb: Path, measurement: Measurement | None,
- round_index: int) -> list[GateReport]:
- """Every check of ``spec`` on this round's GLB, in the spec's order."""
- out: list[GateReport] = []
- for check in spec.checks:
- t0 = time.time()
- try:
- got = load_check(check.entry)(glb=glb, workspace=workspace, spec=spec, measurement=measurement,
- round_index=round_index, args=dict(check.args))
- reports = [got] if isinstance(got, GateReport) else list(got)
- out += [_named(r, check) for r in reports]
- except Exception as e: # a project's bug must not fail or cap the run
- log.warning("project check %s failed: %s", check.entry, e)
- gate = PREFIX + check.name
- out.append(GateReport.of(gate, [GateFinding(
- gate=gate, severity=Severity.WARN,
- message=f"project check {check.entry} raised {type(e).__name__}: {str(e)[:300]}")],
- duration_ms=int((time.time() - t0) * 1000)))
- return out
diff --git a/harness/codeverse3d/tracks/prompting.py b/harness/codeverse3d/tracks/prompting.py
deleted file mode 100644
index 1a75f495..00000000
--- a/harness/codeverse3d/tracks/prompting.py
+++ /dev/null
@@ -1,341 +0,0 @@
-"""Prompt context for the tracks' jinja templates (``prompts/tracks/*.j2``)."""
-
-from __future__ import annotations
-
-import logging
-from collections.abc import Sequence
-from pathlib import Path
-from typing import Any
-
-from codeverse3d.contracts.chat import ImagePart
-from codeverse3d.contracts.common import (
- HARNESS_OWNED_SRC,
- TRACK_INFO,
- Language,
- is_harness_owned,
-)
-from codeverse3d.contracts.plan import Plan, StaticPlan
-from codeverse3d.contracts.run import RoundRecord
-from codeverse3d.conventions import LANGUAGE_FRAME, fmt3, frame_doc, to_authoring_frame, to_snake
-from codeverse3d.prompts import render
-from codeverse3d.prompts.catalog import contract_sections, language_prompt, language_text
-from codeverse3d.tracks.common import RunContext
-from codeverse3d.tracks.depth import DETAIL_ADVICE
-
-log = logging.getLogger(__name__)
-
-MAX_SKELETON_CHARS = 14_000
-
-
-def parts_table(plan: Plan) -> str:
- """Markdown table of parts with exact bboxes (meters, 3 decimals)."""
- parts = getattr(plan, "parts", None) or ()
- 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:
- rows.append(
- f"| {p.name} | {p.role} | ({fmt3(p.bbox.center)}) | ({fmt3(p.bbox.extents)}) | {p.attach_to or '-'} | {p.instances} | {p.material or '-'} |"
- )
- return "\n".join(rows)
-
-
-def part_details(plan: Plan) -> str:
- """Per-part construction notes, including the sub-parts an ASSEMBLY part is made of."""
- out: list[str] = []
- for p in getattr(plan, "parts", None) or ():
- sym = p.symmetry if getattr(p, "symmetry", "none") != "none" else "no symmetry"
- line = f"- **{p.name}** ({sym}): {p.description}"
- hint = getattr(p, "detail_hint", "") or ""
- if hint:
- line += f" _{hint}_"
- out.append(line)
- for c in getattr(p, "children", None) or ():
- inst = f" ×{c.instances}" if getattr(c, "instances", 1) > 1 else ""
- mat = f" [{c.material}]" if getattr(c, "material", "") else ""
- out.append(
- f" - sub-part **{c.name}**{inst}{mat} — centre ({fmt3(c.bbox.center)}) extents ({fmt3(c.bbox.extents)}) m: {c.description}"
- )
- return "\n".join(out)
-
-
-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:
- rows.append(
- f"| {j.name} | {j.type} | {j.parent} | {j.child} | ({fmt3(j.axis)}) | ({fmt3(j.pivot)}) | {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:
- return f"centre ({fmt3(bbox.center)}) m, extents ({fmt3(bbox.extents)}) m"
-
-
-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.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}")
- lines += fixed_parts_lines(spec)
- return "\n".join(lines) or "(none)"
-
-
-def fixed_parts_lines(spec: Any) -> list[str]:
- """The spec's fixed parts (``FixedPart``) for the planner and the agent: given files, never planned, never
- edited, imported as they are. Empty for a spec without any, so its prompts stay byte-identical."""
- fixed = list(getattr(spec, "fixed_parts", None) or [])
- if not fixed:
- return []
- out = ["FIXED PARTS (given by the project: never plan them as parts, never edit, move, scale, recolour or "
- "rename them or what they return, never attach_to them, never assert their size in selfcheck; an edit "
- "is reverted):"]
- for f in fixed:
- what = f"{f.path}"
- if f.export:
- what += f" exports {f.export}"
- if f.name:
- what += f", builds the part '{f.name}'"
- if f.bbox_min is not None and f.bbox_max is not None:
- (x0, y0, z0), (x1, y1, z1) = f.bbox_min, f.bbox_max
- what += f" spanning x {x0:.2f}..{x1:.2f}, y {y0:.2f}..{y1:.2f}, z {z0:.2f}..{z1:.2f} m (GLB frame)"
- out.append(f"- {what}" + (f": {f.note}" if f.note else ""))
- return out
-
-
-def fixed_paths(spec: Any) -> list[str]:
- """The workspace-relative paths of the spec's fixed parts (read-only for every session)."""
- return [f.path.replace("\\", "/") for f in (getattr(spec, "fixed_parts", None) or [])]
-
-
-def language_system_prompt(language: Language, *, role: str = "", tools: bool = True, **vars: Any) -> str:
- """The generator's system prompt: ``prompts/<dir>/system.md``, or a role template."""
- base = render(language_prompt(language, "system.md"), tools=tools).strip()
- if not role:
- return base
- return base + "\n\n" + render(f"system/role_{role}.j2", language=language.value, **vars).strip()
-
-
-ASSET_CONTRACT_SECTIONS: tuple[str, ...] = ("Files", "The `ctx`", "Allowed imports", "FORBIDDEN", "Blender 5.2 API facts",
- "What the renderer does", "Naming")
-
-
-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,
- "asset_contract": contract_sections(ctx.contract_text, ASSET_CONTRACT_SECTIONS),
- "tool_cards": ctx.tool_cards,
- "single_shot": ctx.single_shot,
- "output_format": SINGLE_SHOT_OUTPUT if ctx.single_shot else AGENT_OUTPUT_RULES,
- "spec_prompt": ctx.spec.prompt,
- "constraints": constraints_text(ctx.spec),
- "fixed_parts": "\n".join(fixed_parts_lines(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),
- "detail_advice": DETAIL_ADVICE if plan and getattr(plan, "parts", None) else "",
- "root_link": getattr(plan, "root_link", "") if plan else "",
- "reference_note": reference_note(ctx),
- "effects_catalog": language_text(ctx.language, "effects_catalog.md"),
- }
- d.update(extra)
- return d
-
-
-def reference_images(ctx: RunContext, limit: int = 3) -> list[ImagePart]:
- """The spec's reference images as inline image parts (single-shot prompts)."""
- out: list[ImagePart] = []
- for r in list(ctx.spec.references)[:limit]:
- if Path(r.path).is_file():
- out.append(
- ImagePart(
- path=r.path, label=f"reference ({r.role}){': ' + r.note if r.note else ''}"
- )
- )
- return out
-
-
-def judged_sheet(last: Any) -> list[ImagePart]:
- """The contact sheet the judge scored last round, as ONE inline image for the refine session."""
- sheet = getattr(getattr(last, "renders", None), "contact_sheet", None)
- if not sheet or not Path(sheet).is_file():
- return []
- return [
- ImagePart(
- path=str(sheet),
- label=f"the contact sheet the judge scored (round {getattr(last, 'index', '?')})",
- )
- ]
-
-
-def _likeness_note(ctx: RunContext, refs: list[Any]) -> str:
- """Graphics / scene: the photos say what the REAL thing looks like, not what to compose."""
- lines = [
- f"REFERENCE PHOTOS ({len(refs)}) of the REAL thing come with this task. They are not a composition to copy; "
- "they show what the brief's subject actually looks like: its dominant colour and where the secondary "
- "colours sit, how its structure folds / layers / thins out, where the brightness concentrates and how "
- "much of the frame stays dark, its texture at fine scale. Match THAT — it outranks the brief's "
- "adjectives when the two disagree, and the judge scores your frames beside the same photos. A row of "
- "evenly spaced bars is not a curtain; a flat band is not a glow; cartoon saturation is not a night sky. "
- "Take the physics from the photo, not the postcard: foreground, framing and landscape stay as the brief says."
- ]
- for i, r in enumerate(refs, 1):
- lines.append(f"- reference {i}: `{r.path}`" + (f" — {r.note}" if r.note else ""))
- lines.append("The photos are attached to this message." if ctx.single_shot else
- "Their paths are listed under 'Images for this task' at the end of this message: open them with "
- "your image/file-reading tool, and look again before every `gl_frames` / `scene_views` comparison.")
- return "\n".join(lines)
-
-
-def reference_note(ctx: RunContext) -> str:
- """Prompt paragraph telling the generator how to use the reference images (empty when none)."""
- refs = [r for r in ctx.spec.references if Path(r.path).is_file()]
- if not refs:
- return ""
- if TRACK_INFO[ctx.track].likeness_refs:
- return _likeness_note(ctx, refs)
- lines = [
- f"REFERENCE IMAGES ({len(refs)}): match their silhouette, proportions and visible details — they "
- "outrank the text when the two disagree. A harness measures the outline IoU of the best-matching "
- "render view against the target reference."
- ]
- for i, r in enumerate(refs, 1):
- lines.append(f"- reference {i} ({r.role}): `{r.path}`" + (f" — {r.note}" if r.note else ""))
- if ctx.single_shot:
- lines.append("The images are attached to this message.")
- else:
- tgt = next((r for r in refs if r.role == "target"), refs[0])
- lines.append(
- f"Use the `compare_reference` tool (reference_index={ctx.spec.references.index(tgt)}) after building "
- f"to put `{tgt.path}` beside your model (outline IoU + a side-by-side sheet), and `render_views` to "
- "look at your model."
- )
- return "\n".join(lines)
-
-
-# ----------------------------------------------------------------------------- files + round digests
-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 refine_inline_files(ctx: RunContext, rels: Sequence[str]) -> dict[str, str]:
- """The files a refine task may edit, inlined for the prompt in single-shot mode and empty otherwise."""
- return current_files(ctx, rels) if ctx.single_shot else {}
-
-
-def current_files(
- ctx: RunContext, rels: Sequence[str], max_chars: int = MAX_SKELETON_CHARS
-) -> dict[str, str]:
- """``{rel: text}`` for the files that exist, trimmed to ``max_chars`` in total. The"""
- owned = set(HARNESS_OWNED_SRC.get(ctx.language, ())) | set(fixed_paths(ctx.spec))
- out: dict[str, str] = {}
- total = 0
- for rel in rels:
- p = ctx.ws.root / rel
- if not p.is_file() or is_harness_owned(rel, owned):
- 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:
- m = last.measurement
- if m is None or plan is None or not hasattr(plan, "overall_bbox"):
- return ""
- pe = plan.overall_bbox.extents
- me = to_authoring_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 = to_authoring_frame([b - a for a, b in zip(pm.bbox_min, pm.bbox_max, strict=True)], language, extents=True)
- cen = to_authoring_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"- {f.as_line(with_gate=True)}" for g in last.gates for f in g.errors][:12]
- return "\n".join(lines + gate_lines)
-
-
-#: the format itself is stated once, in the system prompt ``generate_files`` appends
-#: (``prompts/system/singleshot_format.md``); the brief only points at it
-SINGLE_SHOT_OUTPUT = "Reply with the file blocks exactly as the single-shot response format in your system prompt says."
-
-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."""
diff --git a/harness/codeverse3d/tracks/repair.py b/harness/codeverse3d/tracks/repair.py
deleted file mode 100644
index 6d2bbb6d..00000000
--- a/harness/codeverse3d/tracks/repair.py
+++ /dev/null
@@ -1,162 +0,0 @@
-"""Build → error-focused repair loop (no judge, no renders: cheap first)."""
-
-from __future__ import annotations
-
-import logging
-
-from pydantic import BaseModel, Field
-
-from codeverse3d.contracts.artifacts import BuildResult, GateReport
-from codeverse3d.prompts import render
-from codeverse3d.tracks import skills_hook
-from codeverse3d.tracks.common import RunContext, generate_for
-from codeverse3d.tracks.generation import GenerationResult, GenerationTask
-from codeverse3d.tracks.prompting import base_prompt_context, current_files, language_system_prompt
-
-log = logging.getLogger(__name__)
-
-MAX_HARNESS_REBUILDS = 2
-
-MAX_REPAIR_CONTEXT_CHARS = 40_000
-_TRACEBACK_TAIL_LINES = 40
-
-
-class RepairOutcome(BaseModel):
- build: BuildResult
- lint: GateReport
- attempts: list[GenerationResult] = Field(default_factory=list)
- max_attempts: int = Field(default=0, description="repair budget this outcome ran under")
-
- @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, skills: 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}):")
- lines.extend(f"- {f.as_line(with_target=True)}" for f in lint.errors)
- if skills.strip():
- lines.append("\n" + skills.strip())
- return "\n".join(lines)
-
-
-def files_for_repair(ctx: RunContext, build: BuildResult, lint: GateReport, files_hint: list[str]) -> dict[str, str]:
- """Current contents of the failing file(s), at most 40k chars in total, for single-shot repair."""
- cands: list[str] = []
- if build.error_file:
- cands.append(_rel(ctx, build.error_file))
- 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 ctx.runtime.entry_globs:
- cands.extend(str(p.relative_to(ctx.ws.root)) for p in sorted(ctx.ws.root.glob(glob)))
- return current_files(ctx, list(dict.fromkeys(cands)), MAX_REPAIR_CONTEXT_CHARS)
-
-
-def _rel(ctx: RunContext, path: str) -> str:
- """``path`` relative to the workspace, or ``""`` when it points outside it."""
- p = path.replace("\\", "/")
- root = str(ctx.ws.root).replace("\\", "/").rstrip("/") + "/"
- p = p.removeprefix(root)
- while p.startswith("./"):
- p = p[2:]
- return "" if p.startswith("/") or ".." in p.split("/") else p
-
-
-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, timeout_s: 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, max_attempts=max_attempts)
- prev_sig = ""
- repeats = 0
- attempt = 0
- rebuilds = 0
- while not outcome.ok and (attempt < max_attempts or build.harness_failure):
- if build.harness_failure:
- if rebuilds >= MAX_HARNESS_REBUILDS:
- log.warning("build kept failing in the harness (%s); giving up without a repair",
- build.error_message[:160])
- break
- rebuilds += 1
- ctx.events.emit("build.harness_retry", round=round_index, attempt=rebuilds,
- error=build.error_message[:200])
- 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),
- harness_retry=rebuilds, error=build.error_message[:200],
- duration_ms=build.duration_ms)
- continue
- 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, timeout_s=timeout_s)
- ctx.events.emit("repair.attempt", round=round_index, attempt=attempt, repeats=repeats, signature=sig[:200])
- res = generate_for(ctx, task)
- outcome.attempts.append(res)
- 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)
- if res.transient and not outcome.ok:
- ctx.events.emit("repair.storm", round=round_index, attempt=attempt, notes=res.notes[:200])
- break
- 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], timeout_s: int | None = None) -> GenerationTask:
- """Render prompts/tracks/repair.j2 for the current strategy."""
- report = format_error_report(build, lint, skills=skills_hook.repair_pointers(ctx, build, lint))
- 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 = ("", "high", "high")[min(repeats, 2)]
- return GenerationTask(label=label, prompt=prompt, system=_repair_system(ctx), files_hint=sorted(files) or files_hint,
- round=round_index, kind="repair", temperature=temperature, thinking=thinking, timeout_s=timeout_s)
-
-
-def _repair_system(ctx: RunContext) -> str:
- return language_system_prompt(ctx.language, role="repair", contract=ctx.contract_text)
diff --git a/harness/codeverse3d/tracks/scene.py b/harness/codeverse3d/tracks/scene.py
deleted file mode 100644
index 67f7f15d..00000000
--- a/harness/codeverse3d/tracks/scene.py
+++ /dev/null
@@ -1,479 +0,0 @@
-"""SceneTrack."""
-
-from __future__ import annotations
-
-import logging
-import time
-from collections.abc import Callable, Sequence
-from dataclasses import dataclass
-from typing import Any
-
-from codeverse3d.contracts.artifacts import (
- BuildResult,
- GateReport,
- Measurement,
- RenderSet,
-)
-from codeverse3d.contracts.common import ENTRY_FILE, TRACK_INFO, Language, Track
-from codeverse3d.contracts.plan import BBox, CameraPlan, Plan, ScenePlan, ZonePlan
-from codeverse3d.contracts.run import RoundRecord
-from codeverse3d.conventions import SCENE_TIMES, fmt3, to_authoring_frame, to_snake
-from codeverse3d.judges.base import judged_subset
-from c3d_flywheel.models import get_chat_model
-from codeverse3d.orchestrator import BudgetExceeded, TaskGroup, compact_instructions
-from codeverse3d.prompts import render
-from codeverse3d.spatial.frame_motion import motion_text_for
-from codeverse3d.spatial.scene_placement import placement_gate
-from codeverse3d.tracks import skills_hook
-from codeverse3d.tracks.common import RunContext, generate_for, single_shot_ctx
-from codeverse3d.tracks.generation import GenerationResult, GenerationTask
-from codeverse3d.tracks.lifecycle import CLOCK, MATERIALIZE, SKELETON, BaseTrack, StageNode
-from codeverse3d.tracks.prompting import (
- base_prompt_context,
- judge_digest,
- reference_images,
- refine_inline_files,
-)
-from codeverse3d.tracks.repair import format_error_report
-from codeverse3d.tracks.scene_assets import (
- AssetResult,
- asset_api_summary,
- run_asset_stage,
-)
-from codeverse3d.tracks.zone_layout import layout_block, layout_zones
-from codeverse3d.workspace import Workspace
-
-log = logging.getLogger(__name__)
-
-
-ENV_TIMEOUT_S = 420
-ZONE_TIMEOUT_S = 600
-#: what round 0 still needs once the zones are written; the zone window never eats into it
-ROUND0_RESERVE_S = 600.0
-#: the shortest zone window worth opening (a session spends its first minutes reading)
-ZONE_MIN_S = 300.0
-#: clips a refine session to what the hard budget still allows
-REFINE_TIMEOUT_S = 900
-
-
-@dataclass(frozen=True)
-class SceneTemplates:
- """The per-language prompt templates a scene session reads (``prompts/tracks/``); the plan and refine ones serve both."""
-
- env: str
- zone: str
- asset: str
-
-
-
-REFINE_TEMPLATE = "tracks/scene_refine.j2"
-SCENE_TEMPLATES: dict[Language, SceneTemplates] = {
- Language.SCENE_THREEJS: SceneTemplates("tracks/scene_env.j2", "tracks/scene_zone.j2", "tracks/scene_asset.j2"),
- Language.SCENE_BLENDER: SceneTemplates("tracks/scene_env_bpy.j2", "tracks/scene_zone_bpy.j2", "tracks/scene_asset_bpy.j2"),
-}
-#: fallback for a runtime that does not state ``SceneRuntime.env_file``
-ENV_FILES: dict[Language, str] = {Language.SCENE_THREEJS: "src/env.js", Language.SCENE_BLENDER: "src/env.py"}
-
-
-def scene_templates(language: Language) -> SceneTemplates:
- """The templates of a scene language (``KeyError`` for a language the scene track does not run)."""
- return SCENE_TEMPLATES[language]
-
-
-def env_file(ctx: RunContext) -> str:
- """The environment module of this run's scene language."""
- return getattr(ctx.runtime, "env_file", None) or ENV_FILES[ctx.language]
-
-
-def plan_vec(v: Sequence[float], language: Language, *, extents: bool = False) -> tuple[float, float, float]:
- x, y, z = to_authoring_frame(v, language.value, extents=extents)
- return (x + 0.0, y + 0.0, z + 0.0)
-
-
-def plan_bbox_line(bbox: BBox, language: Language) -> str:
- """``prompting.bbox_line`` in the authoring frame of ``language``."""
- return f"centre ({fmt3(plan_vec(bbox.center, language))}) m, extents ({fmt3(plan_vec(bbox.extents, language, extents=True))}) m"
-
-
-def plan_camera_line(c: CameraPlan, language: Language) -> str:
- """One authored camera as a prompt line, its points in the authoring frame of ``language``."""
- p, la = plan_vec(c.position, language), plan_vec(c.look_at, language)
- return (f"- {c.name}: position ({p[0]:.1f}, {p[1]:.1f}, {p[2]:.1f}) look_at ({la[0]:.1f}, {la[1]:.1f}, {la[2]:.1f}) "
- f"fov {c.fov:.0f} — {c.purpose}")
-
-
-class ScenePipeline:
- """No GLB measurement."""
-
- def measure(self, ctx: RunContext, build: BuildResult) -> Measurement | None:
- return None
-
- def gates(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> list[GateReport]:
- # placement gate (floating / sunken / interpenetrating assets) plus the plan checks;
- # advisory: a failure is a WARN finding, never an exception.
- placement = placement_gate(ctx.ws, build.census, ctx.plan)
- return [placement] if placement is not None else []
-
- 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.runtime, 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]:
- try:
- # scene_frames checks from metrics.json; ERROR findings carry fix hints into the next round
- return [ctx.services.frame_gate(renders)]
- except Exception as e: # noqa: BLE001 — the frame gate is advisory instrumentation
- log.warning("scene frame gate failed: %s", e)
- ctx.events.emit("gate.frames_failed", round=round_index, error=f"{type(e).__name__}: {e}")
- return []
-
- def judge_views(self, ctx: RunContext, renders: RenderSet) -> RenderSet:
- """The ≤ 10 views the judge sees (authored@t0 first)."""
- return judged_subset(renders) # type: ignore[return-value]
-
- def judge_context(self, ws: Workspace, plan: Plan | None, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
- if not isinstance(plan, ScenePlan):
- return ""
- # the measured motion goes FIRST: this block is clipped in the judge prompt
- lines = [t for t in (motion_text_for(ws.renders_dir(round_index)),) if t]
- lines.append(f"Environment plan: {plan.environment}"[:1200])
- lines.append("Animation plan: " + "; ".join(plan.animation))
- lines.append("Cameras: " + "; ".join(f"{c.name} ({c.purpose})" for c in plan.cameras))
- return "\n".join(lines)
-
-
-def _plan_agent(ctx: RunContext) -> dict[str, Any]:
- # the WHOLE plan (+ agent), not enumerated fields
- return {"plan": ctx.plan, "agent": ctx.agent_id}
-
-
-class SceneTrack(BaseTrack):
- track = Track.SCENE
- rubric = TRACK_INFO[Track.SCENE].rubric
- plan_model = ScenePlan
- #: the pre-round graph writes the whole baseline; round 0 builds, renders and judges it
- stages = (
- SKELETON, MATERIALIZE,
- # side by side; each is its OWN cached stage so a failing sibling never costs a succeeded one
- (StageNode("assets", lambda t, c: run_asset_stage(c), key=_plan_agent),
- StageNode("env", lambda t, c: t._env_stage(c), key=_plan_agent),
- StageNode("layouts", lambda t, c: t._layouts_stage(c), key=_plan_agent, when=lambda s: s.zone_layouts)),
- CLOCK, # stage boundary: stop only after the finished assets are cached
- StageNode("asset_api", lambda t, c: t._asset_api(c)),
- StageNode("zones", lambda t, c: t._zones_stage(c), key=lambda c: {
- "plan": c.plan, "asset_api": c.extra["asset_api"], "layouts": c.extra.get("layouts", {}), "agent": c.agent_id}),
- # after the zones are recorded: a clock stop here keeps them
- CLOCK,
- # scene.js, deterministic: no session
- StageNode("assemble", lambda t, c: t._assemble_stage(c), key=lambda c: {"plan": c.plan}),
- )
-
- def make_pipeline(self) -> ScenePipeline:
- return ScenePipeline()
-
- #: share of the run budget the baseline may use; the rest is for refine rounds
- soft_budget_fraction = 0.55
-
- # ------------------------------------------------------------------ stages
- def _layouts_stage(self, ctx: RunContext) -> dict[str, Any]:
- """L2 zone layouts (optional accelerator): planner-model calls, never fatal."""
- try:
- model = self._planner_model
- if model is None:
- model = get_chat_model(ctx.spec.backends.planner)
- layouts = layout_zones(ctx.plan, model, budget=ctx.budget, events=ctx.events)
- return {k: v.model_dump(mode="json") for k, v in layouts.items()}
- except Exception as e: # noqa: BLE001 — layouts accelerate, they must never kill
- ctx.events.emit("layout.stage_failed", error=f"{type(e).__name__}: {e}"[:300])
- return {}
-
- def _asset_api(self, ctx: RunContext) -> str:
- """What the zones are told about the assets."""
- plan: ScenePlan = ctx.plan # type: ignore[assignment]
- assets = {k: AssetResult.model_validate(v) if isinstance(v, dict) else v for k, v in (ctx.extra.get("assets") or {}).items()}
- ctx.extra["assets"] = assets
- return asset_api_summary(plan, assets, language=ctx.language)
-
- # ---- degradation ------------------------------------------------------
- def _strategy(self, ctx: RunContext, stage: str) -> RunContext:
- """The context a stage should generate with."""
- reason = ctx.budget.soft_exceeded()
- if not reason:
- return ctx
- sub = None if ctx.single_shot else single_shot_ctx(ctx)
- if sub is None:
- self.note_degraded(ctx, f"{stage}: soft budget spent ({reason}); already cheapest strategy")
- return ctx
- self.note_degraded(ctx, f"{stage}: soft budget spent ({reason}) → single-shot instead of an agent session")
- return sub
-
- def note_degraded(self, ctx: RunContext, note: str) -> None:
- notes: list[str] = ctx.extra.setdefault("degraded", [])
- if note not in notes:
- notes.append(note)
- ctx.events.emit("budget.degraded", note=note, elapsed_min=round(ctx.budget.elapsed_minutes(), 2))
-
- # ---- the stage session ------------------------------------------------
- def _stage_session(self, ctx: RunContext, stage: str, kind: str,
- task_for: Callable[[RunContext], GenerationTask]) -> GenerationResult:
- """The one way a baseline stage (env, zones) runs its session."""
- gen = self._strategy(ctx, stage)
- task = task_for(gen)
- skills_hook.attach_for_round(gen, index=0, kind=kind)
- try:
- task = skills_hook.with_inlined_skill(gen, [task])[0]
- res = generate_for(gen, task)
- if (res.transient or res.stalled) and not res.ok and ctx.policy.can_open(ctx.budget, single_shot=gen.single_shot):
- # ONE transport retry (transient / stalled only, never a quota wall) under the ``.a2``
- # label, and only when the clock holds a minimum window plus the judge reserve.
- ctx.events.emit("stage.transport_retry", stage=stage, label=task.label, stalled=res.stalled and not res.transient,
- detail=res.notes[:500])
- res = generate_for(gen, task.model_copy(update={"label": f"{task.label}.a2"}))
- return res
- finally:
- skills_hook.record_usage(gen, index=0, kind=kind)
- ctx.ws.commit(stage)
-
- def _env_stage(self, ctx: RunContext) -> dict[str, Any]:
- rel, t0 = env_file(ctx), time.time()
- res = self._stage_session(ctx, "env", "env", self._env_task)
- written = {c.path for c in res.files_changed}
- ok = res.ok and (rel in written or _touched(ctx.ws.root / rel, t0))
- out = {"ok": ok, "files": sorted(written) if ok else [], "notes": res.notes}
- if not ok and ctx.budget.ok():
- out = self._recover_env(ctx, out)
- return out
-
- def _recover_env(self, ctx: RunContext, failed: dict[str, Any]) -> dict[str, Any]:
- from codeverse3d.agents.cli_common import exclusive_workspace
-
- gen = ctx if ctx.single_shot else (single_shot_ctx(ctx) or ctx)
- rel = env_file(ctx)
- path = ctx.ws.root / rel
- ctx.events.emit("env.recover", file=rel, notes=str(failed.get("notes", ""))[:300])
- with exclusive_workspace(ctx.ws):
- before = path.read_text(errors="replace") if path.is_file() else None
- lib = ctx.runtime.lib_interface(ctx.ws)
- ok, error, previous, notes = False, "", "", ""
- for attempt in (1, 2): # the single-shot, then ONE repair with the check's words fed back
- t0 = time.time()
- try:
- task = self._env_task(gen, lib_interface=lib, env_check_error=error, env_previous=previous)
- label = f"{task.label}.recover" + (".repair" if attempt > 1 else "")
- res = generate_for(gen, task.model_copy(update={"label": label}))
- except Exception as e: # noqa: BLE001 — BudgetExceeded included: the boundary check after the stage stops the run
- notes = f"recover: {type(e).__name__}: {e}"
- break
- if not (res.ok and (rel in {c.path for c in res.files_changed} or _touched(path, t0))):
- notes = f"recovered single-shot wrote nothing: {res.notes}"
- break
- error = ctx.runtime.check_env(ctx.ws)
- ctx.events.emit("env.checked", attempt=attempt, ok=not error, error=error[:500])
- if not error:
- ok, notes = True, f"recovered single-shot{' + repair' if attempt > 1 else ''}: {res.notes}"
- break
- notes = f"recovered env failed its check: {error}"
- previous = path.read_text(errors="replace") if path.is_file() else ""
- if not ctx.budget.ok():
- break
- if not ok and before is not None and path.is_file() and path.read_text(errors="replace") != before:
- path.write_text(before) # a broken env breaks every zone that imports it; the placeholder does not
- ctx.ws.commit("env.recover")
- out = {"ok": ok, "files": [rel] if ok else [], "notes": notes[:500]}
- ctx.events.emit("env.recovered", ok=ok, file=rel)
- return out
-
- def _env_task(self, ctx: RunContext, **recovery: str) -> GenerationTask:
- """``recovery``."""
- prompt = render(scene_templates(ctx.language).env, **self._ctx(ctx, **recovery))
- ctx.record_prompt("scene_env", prompt)
- return GenerationTask(label="env", prompt=prompt, system=self.system_prompt(ctx), files_hint=[env_file(ctx)], round=0, kind="env",
- temperature=0.5, timeout_s=ctx.budget.timeout_s(ENV_TIMEOUT_S, floor_s=120),
- images=reference_images(ctx), shared_tree=True)
-
- def _zones_stage(self, ctx: RunContext) -> dict[str, Any]:
- plan: ScenePlan = ctx.plan # type: ignore[assignment]
- t0 = time.time()
- zones = list(plan.zones)
- try:
- r = self._stage_session(ctx, "zones", "zone", lambda gen: self._zone_task(gen, zones))
- except Exception as e: # noqa: BLE001 — BudgetExceeded included: the stage is still
- # recorded + committed; the boundary check after the stage stops the run
- log.warning("zones session failed: %s: %s", type(e).__name__, e)
- # a clock trip after a FINISHED session: what it wrote is recorded, the stop noted beside it
- stopped = isinstance(e, BudgetExceeded)
- out = {}
- for zone in zones:
- done = stopped and _touched(ctx.ws.root / ctx.runtime.zone_file(zone.name), t0)
- out[zone.name] = {"ok": done, "files": [ctx.runtime.zone_file(zone.name)] if done else [],
- "notes": f"{type(e).__name__}: {e}"}
- else:
- written = {c.path for c in r.files_changed}
- out = {}
- for zone in zones:
- rel = ctx.runtime.zone_file(zone.name)
- # existence proves nothing (the skeleton left stubs): the file must be reported changed or rewritten
- ok = r.ok and (len(zones) == 1 or rel in written or _touched(ctx.ws.root / rel, t0))
- out[zone.name] = {"ok": ok, "files": [rel] if ok else [], "notes": r.notes}
- failed = [z for z in zones if not out[z.name]["ok"]]
- if failed and ctx.budget.ok():
- out.update(self._recover_zones(ctx, failed))
- 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 _recover_zones(self, ctx: RunContext, failed: list[ZonePlan]) -> dict[str, dict[str, Any]]:
- """One single-shot generation per zone the batched session left unwritten, side by side."""
- from codeverse3d.proc import fan_out
-
- gen = ctx if ctx.single_shot else (single_shot_ctx(ctx) or ctx)
- ctx.events.emit("zones.recover", zones=[z.name for z in failed])
- t0 = time.time()
-
- def one(zone: ZonePlan) -> tuple[str, dict[str, Any]]:
- rel = ctx.runtime.zone_file(zone.name)
- task = self._zone_task(gen, [zone])
- task = task.model_copy(update={"label": f"{task.label}.recover", "timeout_s": zone_window_s(ctx, 1)})
- try:
- res = generate_for(gen, task)
- except Exception as e: # noqa: BLE001 — one zone's recovery must not cost the others
- return zone.name, {"ok": False, "files": [], "notes": f"recover: {type(e).__name__}: {e}"[:500]}
- ok = res.ok and (rel in {c.path for c in res.files_changed} or _touched(ctx.ws.root / rel, t0))
- return zone.name, {"ok": ok, "files": [rel] if ok else [], "notes": f"recovered single-shot: {res.notes}"[:500]}
-
- # fan_out returns each item's value or the exception it raised; ``one`` catches its own,
- # so anything else (a task that could not even be built) leaves that zone as it was
- results = dict(r for r in fan_out(failed, one, max_workers=len(failed), label="zones.recover",
- item_name=lambda z: z.name) if isinstance(r, tuple))
- ctx.ws.commit("zones.recover")
- ctx.events.emit("zones.recovered", ok=[k for k, v in results.items() if v["ok"]],
- failed=[k for k, v in results.items() if not v["ok"]])
- return results
-
- def _zone_task(self, ctx: RunContext, batch: list[ZonePlan]) -> GenerationTask:
- """One task for one zone, or for every zone of the scene in one session."""
- plan: ScenePlan = ctx.plan # type: ignore[assignment]
- names = [z.name for z in batch]
- files = [ctx.runtime.zone_file(z.name) for z in batch]
- template = scene_templates(ctx.language).zone
- briefs = []
- for i, zone in enumerate(batch):
- neighbours = [f"{z.name}: {plan_bbox_line(z.bbox, ctx.language)}" for z in plan.zones if z.name != zone.name]
- # per-zone head for every zone; the shared tail (cameras, assets, contract, tools, catalog) ONCE after the last head
- briefs.append(render(template, **self._ctx(ctx, zone_name=zone.name, zone_description=zone.description,
- zone_bbox=plan_bbox_line(zone.bbox, ctx.language), zone_contents=zone.contents,
- zone_file=ctx.runtime.zone_file(zone.name), neighbours=neighbours,
- layout=layout_block(ctx.extra.get("layouts", {}).get(zone.name), language=ctx.language),
- shared=(i == len(batch) - 1))))
- if len(batch) == 1:
- prompt, label = briefs[0], f"zone_{to_snake(names[0])}"
- else:
- header = (f"# {len(batch)} zone modules in ONE session — write ALL of: {', '.join(files)}\n\n"
- f"You own exactly these files and nothing else. {len(batch)} complete zone briefs follow, "
- "separated by a horizontal rule; implement each one in its own file as its brief says. "
- + "These are EVERY zone of the scene and you are its one author: keep scale, materials and "
- "placement coherent across them — nothing floats, nothing interpenetrates a neighbour "
- "(measured: scene_placement), every planned content at the plan's size (measured), and the "
- "zones read as ONE continuous place (judged): where the plan puts them side by side, nothing "
- "may stop dead at a zone edge. "
- f"This session covers {len(batch)} zones: finish EACH zone — every content its brief lists "
- "present and seated (measured: scene_placement) and the zone reading as the brief describes, "
- "not as a block-out (judged) — before you stop; one author measured 2026-09-08 finished four "
- "zones in 5 minutes as a block-out (\"missing stove\", \"shelves missing\", \"primitive tools\") "
- "and scored 0.32 where the brief-by-brief fan-out reached 0.60.\n")
- prompt = header + "\n\n---\n\n".join(briefs)
- label = "zones_" + "_".join(to_snake(n) for n in names)
- ctx.record_prompt("scene_zone", prompt) # the whole prompt the session read
- # the batch exclusively owns its zone files; env/scene/asset files belong to other sessions
- # the window grows with the batch: one author writing four zones is four zones of work
- return GenerationTask(label=label, prompt=prompt, system=self.system_prompt(ctx), files_hint=files,
- round=0, kind="zone", temperature=0.5, edit_only=True,
- timeout_s=zone_window_s(ctx, len(batch)))
-
- def _assemble_stage(self, ctx: RunContext) -> dict[str, Any]:
- result = ctx.services.assemble_scene(ctx.runtime, ctx.ws, ctx.plan)
- ctx.ws.commit("assemble")
- ctx.events.emit("assemble.done", deterministic=True)
- return {"ok": True, "deterministic": True, "result": result} # StageRunner.stage jsonables it
-
- def prepare_salvage(self, ctx: RunContext) -> bool:
- """The budget stopped a stage before round 0."""
- plan: ScenePlan = ctx.plan # type: ignore[assignment]
- zones = [z for z in plan.zones if (ctx.ws.root / ctx.runtime.zone_file(z.name)).is_file()]
- if not zones:
- return False
- self.note_degraded(ctx, f"salvage: assembled {len(zones)}/{len(plan.zones)} zones written before the budget stop")
- ctx.plan = plan.model_copy(update={"zones": zones})
- try:
- self._assemble_stage(ctx)
- finally:
- ctx.plan = plan
- return True
-
- # ------------------------------------------------------------------ rounds
- def baseline_tasks(self, ctx: RunContext) -> list[GenerationTask]:
- return [] # generation happened in the stages; round 0 = build → render → judge
-
- # ------------------------------------------------------------------ refine (scaffold hooks)
- def _refine_task(self, ctx: RunContext, group: TaskGroup, last: RoundRecord, index: int, *, parallel: bool) -> GenerationTask:
- files = group.files or ctx.runtime.expected_files(ctx.plan)
- lines = compact_instructions(group.tasks, max_lines=ctx.policy.max_instructions_per_task)
- prompt = render(REFINE_TEMPLATE, **self._ctx(ctx, round_index=index, tasks=lines,
- targets=group.targets, files=files, edit_only_these=parallel,
- judge_summary=judge_digest(last),
- current_files=refine_inline_files(ctx, files)))
- ctx.record_prompt("scene_refine", prompt)
- # parallel groups are file-disjoint by plan_refine_groups: enforce the split they promised
- 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, edit_only=parallel,
- timeout_s=ctx.budget.timeout_s(REFINE_TIMEOUT_S, floor_s=180, soft=False))
-
- def _rebuild_task(self, ctx: RunContext, last: RoundRecord, index: int) -> GenerationTask:
- """One repair task carrying the structured build and lint error report."""
- lint = next((g for g in last.gates if g.gate.startswith("lint")), GateReport(gate="lint", passed=True))
- report = format_error_report(last.build, lint) if last.build else "build did not run"
- files: list[str] = []
- if last.build is not None and last.build.error_file:
- rel = last.build.error_file.removeprefix(str(ctx.ws.root)).lstrip("/")
- if (ctx.ws.root / rel).is_file():
- files = [rel]
- files = files or ctx.runtime.expected_files(ctx.plan)
- prompt = render(REFINE_TEMPLATE, **self._ctx(ctx, round_index=index, tasks=[report], targets=["build"],
- files=files, edit_only_these=False,
- judge_summary="(no judgment: the scene did not build — fix the errors above first)",
- current_files=refine_inline_files(ctx, files)))
- ctx.record_prompt("scene_refine", prompt)
- return GenerationTask(label="rebuild", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=index,
- kind="rebuild", temperature=0.7, thinking="high",
- timeout_s=ctx.budget.timeout_s(REFINE_TIMEOUT_S, floor_s=180, soft=False))
-
- # ------------------------------------------------------------------ helpers
- def _ctx(self, ctx: RunContext, **extra: Any) -> dict[str, Any]:
- """The variables every scene template may use."""
- plan: ScenePlan = ctx.plan # type: ignore[assignment]
- lang = ctx.language
- zones_table = "\n".join(f"- {z.name}: {z.description} — {plan_bbox_line(z.bbox, lang)}; contents: {', '.join(z.contents) or '-'}"
- for z in plan.zones)
- cameras = "\n".join(plan_camera_line(c, lang) 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=plan_bbox_line(plan.bounds, lang), environment=plan.environment,
- interior=plan.interior, glazed=plan.glazed,
- zones_table=zones_table, cameras=cameras, effects=effects, animation="; ".join(plan.animation) or "(none)",
- asset_api=ctx.extra.get("asset_api", "(no assets)"),
- env_file=env_file(ctx), entry_file=ENTRY_FILE[lang], **extra)
-
-
-# ----------------------------------------------------------------------------- helpers
-def _touched(path: Any, since: float) -> bool:
- try:
- return path.is_file() and path.stat().st_mtime > since
- except OSError:
- return False
-
-
-def zone_window_s(ctx: RunContext, n_zones: int) -> int:
- """The zone session's window."""
- left = (ctx.budget.hard_minutes - ctx.budget.elapsed_minutes()) * 60.0 - ROUND0_RESERVE_S
- return int(max(ZONE_MIN_S, min(float(ZONE_TIMEOUT_S * max(1, n_zones)), left)))
diff --git a/harness/codeverse3d/tracks/scene_assets.py b/harness/codeverse3d/tracks/scene_assets.py
deleted file mode 100644
index a2dcf88b..00000000
--- a/harness/codeverse3d/tracks/scene_assets.py
+++ /dev/null
@@ -1,801 +0,0 @@
-"""Scene asset stage."""
-
-from __future__ import annotations
-
-import json
-import logging
-import re
-import shutil
-import struct
-from collections.abc import Callable
-from dataclasses import replace
-from pathlib import Path
-from typing import Any
-
-from pydantic import BaseModel, Field
-
-from codeverse3d.contracts.artifacts import Judgment
-from codeverse3d.contracts.common import ENTRY_FILE, TRACK_LANGUAGES, Language, Track
-from codeverse3d.contracts.plan import AssetPlan, BBox, PartPlan, ScenePlan, StaticPlan
-from codeverse3d.contracts.spec import Constraints, Spec
-from codeverse3d.conventions import MAX_TRIS_OBJECT, OBJECT_VIEWS_QUICK, to_pascal, to_snake
-from codeverse3d.orchestrator import BudgetExceeded
-from codeverse3d.proc import fan_out, write_json_atomic
-from codeverse3d.prompts import render
-from codeverse3d.prompts.catalog import language_text
-from codeverse3d.tracks.common import (
- RunContext,
- generate_for,
- single_shot_ctx,
-)
-from codeverse3d.tracks.generation import GenerationTask, is_model_outage, is_single_shot
-from codeverse3d.tracks.planner import plan as run_planner
-from codeverse3d.tracks.prompting import (
- base_prompt_context,
- constraints_text,
- current_files,
- language_system_prompt,
- reference_images,
- skeleton_files,
-)
-from codeverse3d.tracks.repair import build_with_repair
-from codeverse3d.workspace import Workspace
-
-log = logging.getLogger(__name__)
-
-MAX_ASSETS = 8
-#: cap once the baseline has spent its soft sub-budget
-DEGRADED_MAX_ASSETS = 4
-#: an asset smaller than this share of the scene bbox volume is not worth a judge call
-JUDGE_VOLUME_FRACTION = 0.05
-#: the plan's largest module is judged whatever its share, once at least this big
-JUDGE_MIN_VOLUME_M3 = 1.0
-ASSET_AGENT_TIMEOUT_S = 420
-#: no single asset session may take more than this share of the run (the stage waits for its slowest asset)
-ASSET_SESSION_SHARE = 0.15
-ASSET_RUBRIC = "asset"
-#: asset kinds that are a MODULE in the scene workspace; ``blender_glb`` is the hero, shipped as a GLB
-MODULE_KINDS: frozenset[str] = frozenset({"threejs", "bpy"})
-#: languages whose asset sessions share the scene workspace (tasks are ``edit_only``); a hero owns its sub-workspace
-SCENE_LANGUAGES: frozenset[Language] = frozenset(TRACK_LANGUAGES[Track.SCENE])
-
-
-def asset_timeout_s(ctx: Any, floor_s: int) -> int:
- share = ctx.budget.budget.max_minutes * 60.0 * ASSET_SESSION_SHARE
- return ctx.budget.timeout_s(min(ASSET_AGENT_TIMEOUT_S, share), floor_s=floor_s)
-
-
-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 = ""
- strategy: str = Field(default="", description="single-shot | single-shot+repair | agent | escalated")
- judged: bool = Field(default=False, description="a non-degraded verdict was recorded in `score`")
- score_before: float | None = Field(default=None, description="the verdict the fix pass improved on (score = after)")
- clips: int = Field(default=0, description="glTF animation clips the hero GLB carries (a keyframed Blender part)")
-
-
-
-
-def asset_api_summary(plan: ScenePlan, results: dict[str, AssetResult], *, language: Language = Language.SCENE_THREEJS) -> str:
- 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 language is Language.SCENE_BLENDER:
- lines.append(_bpy_api_line(a, r, s, status))
- elif 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:
- motion = f", carries {r.clips} motion clip(s) (played automatically; `clone.userData.clipOffset` de-phases copies)" if r and r.clips else ""
- lines.append(f"- {a.name}: preloaded at `ctx.assets['{to_snake(a.name)}']` (clone it; GLB public/assets/{to_snake(a.name)}.glb), "
- f"base at y=0, {s}{motion}{status}")
- if lines and language is Language.SCENE_BLENDER:
- place = ("place it as a collection-instance Empty (`bpy.data.objects.new(name, None)` with `instance_type = 'COLLECTION'` "
- "and `instance_collection = ctx.assets['<snake>']`), linked into ctx.collection and seated on "
- "ctx.height_at(x, y) = ONE placement row.")
- lines.insert(0, "Sizes are width × height × depth in metres, the plan's Y-up order: in your Blender frame x = width, "
- "y = depth, z = height. Every entry is a Collection built at the origin with its base on z = 0 and its "
- "front facing -Y; " + place)
- return "\n".join(lines) or "(no assets)"
-
-
-def _bpy_api_line(a: AssetPlan, r: AssetResult | None, size: str, status: str) -> str:
- """One asset's line of the bpy asset API (see ``asset_api_summary``)."""
- snake = to_snake(a.name)
- if a.kind == "blender_glb":
- motion = f", carries {r.clips} keyframed motion clip(s) (its action plays in every instance)" if r and r.clips else ""
- return (f"- {a.name}: `ctx.assets['{snake}']` — the hero GLB `public/assets/{snake}.glb` imported by the harness "
- f"into the Blender frame, {size}{motion}{status}")
- return f"- {a.name}: `ctx.assets['{snake}']` — built by the harness from `src/assets/{snake}.py` (`build_{snake}(ctx, variant=0)`), {size}{status}"
-
-
-def run_asset_stage(ctx: RunContext) -> dict[str, AssetResult]:
- """Generate every asset (parallel) and return results keyed by asset name."""
- plan: ScenePlan = ctx.plan # type: ignore[assignment]
- cap = MAX_ASSETS if ctx.budget.soft_ok() else DEGRADED_MAX_ASSETS
- planned = list(plan.assets)
- assets = planned[:cap]
- if len(planned) > len(assets):
- ctx.events.emit("assets.capped", n=len(planned), cap=cap, dropped=[a.name for a in planned[cap:]])
- if not assets:
- return {}
-
- def _one(asset: AssetPlan) -> AssetResult:
- if asset.kind == "blender_glb":
- return build_blender_asset(ctx, asset, judge=True)
- return build_module_asset(ctx, asset, judge=True)
-
- workers = ctx.settings.limits.max_parallel_agents
- if any(a.kind in ("blender_glb", "bpy") for a in assets): # both kinds check in a Blender process
- 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):
- # a failed worker is a failed asset: siblings' modules are still shimmed + committed before the boundary check stops the run
- out[asset.name] = AssetResult(name=asset.name, kind=asset.kind, ok=False, notes=f"{type(r).__name__}: {r}")
- ctx.events.emit("asset.failed", asset=asset.name, error=f"{type(r).__name__}: {r}")
- else:
- 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],
- strategies={n: r.strategy for n, r in out.items() if r.strategy})
- return out
-
-
-# ----------------------------------------------------------------------------- module asset
-def build_module_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> AssetResult:
- bpy = asset.kind == "bpy"
- rel = ctx.runtime.asset_file(asset)
- name = to_snake(asset.name) if bpy else to_pascal(asset.name)
- check_fn = check_bpy_asset if bpy else check_threejs_asset
- language = Language.SCENE_BLENDER if bpy else Language.SCENE_THREEJS
-
- def check(c: RunContext) -> AssetCheck:
- return check_fn(c, rel, name, expected_size_m=asset.approx_size_m)
-
- strategy, chk, notes = _ladder(ctx, asset, rel, language=language, files=[rel], check=check,
- timeout_s=asset_timeout_s(ctx, 120))
- return _module_result(ctx, asset, rel, strategy, chk, notes, check=check, language=language, judge=judge)
-
-
-def _module_result(ctx: RunContext, asset: AssetPlan, rel: str, strategy: str, chk: AssetCheck | None, notes: str, *,
- check: Callable[[RunContext], AssetCheck], language: Language, judge: bool) -> AssetResult:
- """What a MODULE asset's ladder outcome means (both module kinds)."""
- if strategy == "outage":
- return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy=strategy, notes=notes)
- ok = (ctx.ws.root / rel).is_file() and not (chk is not None and chk.ran and chk.fatal)
- result = AssetResult(name=asset.name, kind=asset.kind, ok=ok, path=rel if ok else "", notes=notes, strategy=strategy,
- size_m=chk.size_m if chk and chk.size_m else None)
- ctx.events.emit("asset.generated", asset=asset.name, strategy=strategy, ok=ok, tris=(chk.tris if chk else 0),
- errors=(chk.errors[:2] if chk and not chk.ok else []))
- render_asset = getattr(ctx.runtime, "render_asset", None)
- if ok and callable(render_asset) and _judge_wanted(ctx, asset, chk, judge=judge):
- def _after_fix(gen: RunContext) -> bool:
- # a fix that breaks the module makes it NOT AVAILABLE; a SOFT finding is no reason to revert
- c = check(ctx)
- if c.ran and c.fatal:
- result.ok, result.path = False, ""
- return not (c.ran and c.fatal)
-
- def _snapshot() -> Callable[[], None]:
- before = (ctx.ws.root / rel).read_text()
-
- def _restore() -> None:
- (ctx.ws.root / rel).write_text(before)
- result.ok, result.path = True, rel
-
- return _restore
-
- result = _judge_and_fix(ctx, asset, result, lambda out_dir: render_asset(ctx.ws, asset.name, out_dir), files=[rel],
- language=language, after_fix=_after_fix, snapshot=_snapshot)
- return result
-
-
-def _ladder(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language, files: list[str],
- check: Callable[[RunContext], AssetCheck], timeout_s: int | None) -> tuple[str, AssetCheck | None, str]:
- """The cheap-first ladder BOTH asset kinds climb."""
- sub = single_shot_ctx(ctx)
- chk: AssetCheck | None = None
- strategy, notes = "", ""
- outage = False
- if sub is not None:
- for attempt in range(2): # first shot + ONE error-feedback repair
- # after an outage the model wrote nothing: the second shot is the first again
- feedback = repair_feedback(chk, rel) if chk is not None and not outage else ""
- try:
- # the ladder's window bounds the single-shot call too
- res = _generate_asset(sub, asset, rel, language=language, attempt=attempt, files=files,
- feedback=feedback, timeout_s=timeout_s)
- except Exception as e: # noqa: BLE001 — a bad answer escalates; a dead model does not
- if isinstance(e, BudgetExceeded):
- raise
- outage = is_model_outage(e)
- log.warning("single-shot asset %s failed%s: %s", asset.name, " (model outage)" if outage else "", e)
- ctx.events.emit("asset.generate_failed", asset=asset.name, attempt=attempt, outage=outage,
- error=f"{type(e).__name__}: {e}"[:300])
- chk = AssetCheck(ok=False, ran=True, fatal=True, errors=[f"the generator failed: {type(e).__name__}: {e}"[:300]])
- if outage:
- continue # the answer is not bad, the model is down: try the cheap shot again
- break
- outage = False
- notes = res.notes
- chk = (check(sub) if res.ok
- else AssetCheck(ok=False, ran=True, fatal=True, errors=[f"no file was written ({res.notes or 'empty answer'})"]))
- if chk.ok:
- strategy = "single-shot+repair" if feedback else "single-shot"
- break
- if not strategy and not outage:
- ctx.events.emit("asset.escalated", asset=asset.name, errors=(chk.errors[:3] if chk else []))
- if not strategy and outage:
- # model down and retries exhausted: give the asset up cheaply; zones read "NOT AVAILABLE" and build around it
- ctx.events.emit("asset.skipped_outage", asset=asset.name, errors=(chk.errors[:2] if chk else []))
- return "outage", chk, "generator unavailable (model outage); asset skipped"
- if not strategy: # no chat model, or single-shot failed twice → the full agent session
- res = _generate_asset(ctx, asset, rel, language=language, attempt=0, files=files, timeout_s=timeout_s)
- notes = res.notes
- strategy = "escalated" if chk is not None else "agent"
- chk = check(ctx) if res.ok else chk
- return strategy, chk, notes
-
-
-def _generate_asset(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language, attempt: int,
- feedback: str = "", timeout_s: int | None = None, files: list[str] | None = None) -> Any:
- files = list(files or [rel])
- # pre-round work is round 0 (the ledger's round dimension); the attempt lives in the label
- label = f"asset_{to_snake(asset.name)}" + (f"_retry{attempt}" if attempt else "")
- prompt = _asset_prompt(ctx, asset, rel, language=language, files=files)
- if feedback:
- prompt = prompt + "\n\n" + feedback + "## Current file(s) (rewrite COMPLETELY)\n" + _inline(ctx, files)
- task = GenerationTask(label=label, prompt=prompt,
- system=_asset_system(ctx, language),
- files_hint=files, round=0, kind="asset", temperature=0.5, timeout_s=timeout_s,
- images=reference_images(ctx),
- # scene-language modules share the scene workspace (a stray write would
- # hit zones/env); blender heroes own their whole sub-workspace
- edit_only=language in SCENE_LANGUAGES)
- return generate_for(ctx, task)
-
-
-def _inline(ctx: RunContext, files: list[str]) -> str:
- return "".join(f"--- {rel} ---\n```\n{body}\n```\n" for rel, body in current_files(ctx, files, 24_000).items())
-
-
-# ----------------------------------------------------------------------------- blender asset (hero)
-#: a hero may spend more triangles than an instanced prop (the number the prompt states)
-HERO_MAX_TRIS = 40_000
-HERO_ENTRY = ENTRY_FILE[Language.BLENDER]
-HERO_GROUND_TOL_M = 0.02
-#: a hero plan with this many parts or fewer, for a sheet naming more features, is asked again once
-HERO_THIN_PLAN_PARTS = 2
-
-
-def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> AssetResult:
- snake = to_snake(asset.name)
- w, h, d = asset.approx_size_m
- sub_ws = Workspace(ctx.ws.root / "_assets" / snake).create()
- runtime = ctx.services.runtime(Language.BLENDER)
- # the sub-spec IS the asset sheet; the scene's brief and style travel in `extra`
- sub_spec = Spec(id=f"{ctx.spec.id}-asset-{snake}", track=Track.STATIC_OBJECT, language=Language.BLENDER,
- prompt=asset.description, references=list(ctx.spec.references),
- constraints=Constraints(style=ctx.spec.constraints.style,
- dimensions_m={"width": w, "height": h, "depth": d}),
- budget=ctx.spec.budget, backends=ctx.spec.backends)
- sub_ws.write_json(sub_ws.spec_path, sub_spec)
- sub = replace(ctx, spec=sub_spec, ws=sub_ws, runtime=runtime, plan=None, track=Track.STATIC_OBJECT,
- contract_text=language_text(Language.BLENDER, "contract.md"),
- tool_cards=ctx.services.tool_cards(Track.STATIC_OBJECT.value, Language.BLENDER.value),
- extra={"scene_brief": ctx.spec.prompt, "scene_style": constraints_text(ctx.spec)})
- sub.plan = hero_plan(sub, asset)
- sub_ws.write_json(sub_ws.plan_path, sub.plan) # the sub-run's plan.json IS this plan (tools, contract gate, build)
- if not (sub_ws.root / HERO_ENTRY).is_file(): # a re-entry keeps the previous session's work
- from codeverse3d.languages.blender import write_blender_skeleton
-
- # the hero's ground tolerance (20 mm sink rule, as its module twin)
- write_blender_skeleton(sub_ws, sub.plan, ground_tol_m=HERO_GROUND_TOL_M)
- sub_ws.commit("skeleton")
- if not ctx.single_shot:
- # language contract alone: harness_contract.md's acceptance list (overall bbox within max(10 mm, 10 %)) is not the asset prop-sheet's tolerance
- ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=sub.contract_text)
- files = sub.runtime.expected_files(sub.plan)
- timeout_s = asset_timeout_s(ctx, 180)
- label = f"asset_{snake}"
-
- def check(c: RunContext) -> AssetCheck:
- return _blender_check(c, asset, files, label=label, timeout_s=timeout_s)
-
- strategy, chk, notes = _ladder(sub, asset, HERO_ENTRY, language=Language.BLENDER, files=files, check=check,
- timeout_s=timeout_s)
- if strategy == "outage":
- return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy=strategy, notes=notes)
- ok = chk is not None and bool(chk.glb) and not chk.fatal
- ctx.events.emit("asset.generated", asset=asset.name, strategy=strategy, ok=ok, tris=(chk.tris if chk else 0),
- errors=(chk.errors[:2] if chk and not chk.ok else []))
- if not ok:
- why = "; ".join(chk.errors[:2]) if chk and chk.errors else (notes or "no build")
- return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy=strategy, notes=f"build failed: {why}"[:300])
- sub_ws.commit("asset built")
- rel = ctx.runtime.asset_file(asset)
- dest = _copy_glb(ctx.ws, Path(chk.glb), rel)
- result = _stamp_glb(AssetResult(name=asset.name, kind=asset.kind, ok=True, path=rel, size_m=chk.size_m, strategy=strategy,
- notes=notes), ctx, dest)
- if _judge_wanted(ctx, asset, chk, judge=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(gen: RunContext) -> bool:
- oc = build_with_repair(gen, round_index=1, label=f"{label}_fix", files_hint=files,
- max_attempts=0 if gen.single_shot else 1, timeout_s=timeout_s)
- if not (oc.build.ok and oc.build.glb_path):
- return False
- _copy_glb(ctx.ws, Path(oc.build.glb_path), rel)
- sub_ws.commit("asset fix")
- _stamp_glb(result, ctx, dest)
- return True
-
- def _snapshot() -> Callable[[], None]:
- keep = sub_ws.artifacts / "object.before_fix.glb"
- shutil.copyfile(dest, keep)
- src = {f: _read(sub_ws, f) for f in files}
-
- def _restore() -> None:
- shutil.copyfile(keep, dest)
- for f, body in src.items():
- if body:
- (sub_ws.root / f).write_text(body)
- sub_ws.commit("asset fix reverted")
- _stamp_glb(result, ctx, dest)
-
- return _restore
-
- result = _judge_and_fix(sub, asset, result, _render, files=files, language=Language.BLENDER, after_fix=_after_fix,
- measure_fn=lambda: ctx.services.measure(dest), snapshot=_snapshot)
- return result
-
-
-def hero_plan(sub: RunContext, asset: AssetPlan) -> StaticPlan:
- """The static-object planner's part list for a hero, or the one-part sheet when it fails."""
- try:
- model = sub.services.chat_model(sub.spec.backends.planner)
- plan = run_planner(sub.spec, sub.spec.backends.planner, StaticPlan, sub.ws, model=model, events=sub.events,
- budget=sub.budget)
- features = hero_features(asset.description)
- if len(plan.parts) <= HERO_THIN_PLAN_PARTS and len(features) > HERO_THIN_PLAN_PARTS:
- # a one-part answer for a multi-feature sheet: ask once more with the features as the checklist
- sub.events.emit("asset.plan_thin", asset=asset.name, n_parts=len(plan.parts), features=features)
- spec2 = sub.spec.model_copy(update={"constraints": sub.spec.constraints.model_copy(update={"must_have": features})})
- plan = run_planner(spec2, spec2.backends.planner, StaticPlan, sub.ws, model=model, events=sub.events,
- budget=sub.budget)
- except Exception as e: # noqa: BLE001 — PlanningError / outage: the sheet still says what the prop is
- if isinstance(e, BudgetExceeded):
- raise
- log.warning("hero planner failed for %s, using the one-part sheet: %s", asset.name, e)
- sub.events.emit("asset.plan_failed", asset=asset.name, error=f"{type(e).__name__}: {e}"[:300])
- return asset_plan(asset)
- sub.events.emit("asset.planned", asset=asset.name, n_parts=len(plan.parts))
- return plan
-
-
-def hero_features(description: str, limit: int = 8) -> list[str]:
- """The features an asset sheet names — its clauses of two words or more — as a checklist."""
- out: list[str] = []
- for clause in re.split(r"[;,]|\band\b|\bwith\b|\bplus\b", description):
- words = clause.strip(" .:()").split()
- if len(words) >= 2 and clause.strip() not in out:
- out.append(" ".join(words))
- if len(out) >= limit:
- break
- return out
-
-
-def _blender_check(ctx: RunContext, asset: AssetPlan, files: list[str], *, label: str, timeout_s: int) -> AssetCheck:
- outcome = build_with_repair(ctx, round_index=0, label=label, files_hint=files,
- max_attempts=0 if ctx.single_shot else 1, timeout_s=timeout_s)
- b = outcome.build
- if not b.ok or not b.glb_path:
- errors = [f"{b.error_type}: {b.error_message}"[:300] if b.error_message else "the build produced no GLB"]
- errors += [f"{f.target or 'lint'}: {f.message}"[:200] for f in outcome.lint.errors][:3]
- return AssetCheck(ok=False, ran=True, fatal=True, errors=errors)
- chk = AssetCheck(ok=True, ran=True, glb=str(b.glb_path))
- try:
- m = ctx.services.measure(Path(b.glb_path))
- except Exception as e: # noqa: BLE001 — a GLB that cannot be measured is still a GLB
- chk.warnings.append(f"measure unavailable: {type(e).__name__}")
- return chk
- chk.size_m = (round(m.extents[0], 3), round(m.extents[1], 3), round(m.extents[2], 3))
- chk.min_y, chk.tris, chk.meshes, chk.materials = round(m.bbox_min[1], 3), m.tri_count, m.n_meshes, m.materials
- _soft_findings(chk, asset.approx_size_m, max_tris=HERO_MAX_TRIS)
- return chk
-
-
-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_wanted(ctx: RunContext, asset: AssetPlan, chk: AssetCheck | None, *, judge: bool) -> bool:
- """Stop paying for what is already good."""
- if not judge:
- return False
- if not ctx.budget.soft_ok():
- ctx.events.emit("asset.judge_skipped", asset=asset.name, reason="soft_budget")
- return False
- if asset.kind == "blender_glb":
- return True
- frac = _volume_fraction(ctx, asset)
- # the plan's LARGEST module (at least JUDGE_MIN_VOLUME_M3) keeps its verdict whatever its share
- w, h, d = asset.approx_size_m
- dominant = asset.name == _largest_module(ctx) and w * h * d >= JUDGE_MIN_VOLUME_M3
- if chk is not None and chk.ok and chk.ran and frac < JUDGE_VOLUME_FRACTION and not dominant:
- ctx.events.emit("asset.judge_skipped", asset=asset.name, reason="gates_ok_and_small",
- volume_fraction=round(frac, 5), tris=chk.tris, meshes=chk.meshes)
- return False
- return True
-
-
-def _largest_module(ctx: RunContext) -> str:
- """The name of the plan's biggest module asset (``MODULE_KINDS``) by planned volume ('' when none)."""
- mods = [a for a in (getattr(ctx.plan, "assets", None) or []) if a.kind in MODULE_KINDS]
- if not mods:
- return ""
- return max(mods, key=lambda a: a.approx_size_m[0] * a.approx_size_m[1] * a.approx_size_m[2]).name
-
-
-def _volume_fraction(ctx: RunContext, asset: AssetPlan) -> float:
- """Asset bbox volume / scene bounds volume (1.0 when the scene bounds are unknown)."""
- bounds = getattr(ctx.plan, "bounds", None)
- if bounds is None:
- return 1.0
- scene_v = 1.0
- for e in bounds.extents:
- scene_v *= max(float(e), 1e-3)
- asset_v = 1.0
- for e in asset.approx_size_m:
- asset_v *= max(float(e), 1e-3)
- return asset_v / scene_v if scene_v > 0 else 1.0
-
-
-def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, render_fn: Any, *, files: list[str],
- language: Language, after_fix: Callable[[RunContext], bool] | None = None,
- measure_fn: Callable[[], Any] | None = None,
- snapshot: Callable[[], Callable[[], None]] | None = None) -> AssetResult:
- """Quick-sheet judge with asset (n_samples=1)."""
- from codeverse3d.judges.base import JudgeInput
-
- events = ctx.events
- try:
- judge = ctx.services.judge(ctx.track, 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)
-
- def _verdict(round_index: int) -> Judgment | None:
- d = out_dir if round_index == 0 else out_dir.with_name(out_dir.name + "_fix")
- d.mkdir(parents=True, exist_ok=True)
- try:
- renders = render_fn(d)
- # the measurement the rubric's proportions criterion reads; re-measured after a fix
- measurement = measure_fn() if measure_fn is not None else None
- verdict: Judgment = judge.judge(JudgeInput(spec=ctx.spec, renders=renders, round_index=round_index,
- measurement=measurement,
- 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 None
- write_json_atomic(d / "judge.json", verdict.model_dump(mode="json")) # replayable, like a round's judge/rNN.json
- if verdict.degraded:
- # a degraded verdict is no verdict: score stays None and the fix pass is skipped
- events.emit("asset.judge_degraded", asset=asset.name)
- return None
- events.emit("asset.judged", asset=asset.name, round=round_index, score=round(verdict.overall, 3), passed=verdict.passed)
- return verdict
-
- verdict = _verdict(0)
- if verdict is None:
- return result
- result.score = verdict.overall
- result.judged = True
- if verdict.passed or not verdict.improvement_plan:
- return result
- instructions = [f"- {i.target}: {i.instruction}" for i in verdict.improvement_plan[:4]]
- gen = single_shot_ctx(ctx) or ctx
- current = _inline(gen, files) if gen.single_shot else ""
- prompt = render(asset_template(language), **base_prompt_context(
- gen, asset_name=asset.name, asset_kind=asset.kind, asset_description=asset.description,
- asset_size=asset.approx_size_m, asset_file=files[0], asset_files=files, asset_language=language.value,
- fix_instructions=instructions, current_code=current, skeleton_files={}, library_rows="", **_scene_context(ctx)))
- task = GenerationTask(label=f"asset_{to_snake(asset.name)}_fix", prompt=prompt, system=_asset_system(gen, language),
- files_hint=files, round=0, kind="asset_fix", temperature=0.4,
- edit_only=language in SCENE_LANGUAGES, timeout_s=asset_timeout_s(ctx, 120))
- restore = snapshot() if snapshot is not None else None # BEFORE the fix rewrites the files
- res = generate_for(gen, task)
- if not res.ok:
- return result
- result.fixed = after_fix(gen) if after_fix is not None else True
- if not result.fixed:
- if restore is not None:
- restore() # a fix that does not build is undone too: the asset that was judged stays the asset
- return result
- again = _verdict(1)
- if again is None:
- return result
- if again.overall < (result.score or 0.0) and restore is not None:
- # a fix that judges WORSE is undone
- restore()
- result.fixed = False
- events.emit("asset.fix_reverted", asset=asset.name, before=round(result.score or 0.0, 3), after=round(again.overall, 3))
- return result
- result.score_before, result.score = result.score, again.overall
- return result
-
-
-# ----------------------------------------------------------------------------- helpers
-def asset_template(language: Language) -> str:
- """The asset-session template of a scene language (``tracks/scene.SCENE_TEMPLATES``)."""
- from codeverse3d.tracks.scene import (
- SCENE_TEMPLATES, # scene imports this module: resolved at call time
- )
-
- return SCENE_TEMPLATES.get(language, SCENE_TEMPLATES[Language.SCENE_THREEJS]).asset
-
-
-def _asset_system(ctx: RunContext, language: Language) -> str:
- """The system prompt for one asset generation — same language, DIFFERENT task."""
- if language is Language.SCENE_THREEJS:
- return language_text(Language.SCENE_THREEJS, "asset.md").strip()
- if language is Language.SCENE_BLENDER:
- return (language_text(Language.SCENE_BLENDER, "asset.md").strip() + "\n\n"
- + render("system/role_asset.j2", language=language.value).strip())
- return language_system_prompt(Language.BLENDER, role="asset", tools=not is_single_shot(ctx.agent_id))
-
-
-def _scene_context(ctx: RunContext) -> dict[str, Any]:
- """The SCENE's brief and style for an asset prompt, whichever spec ``ctx`` carries."""
- brief = ctx.extra.get("scene_brief")
- return {"spec_prompt": brief, "constraints": ctx.extra.get("scene_style") or "(none)"} if brief else {}
-
-
-#: what names a library row: a camelCase factory after a backtick (a bare lowercase word is ordinary prose), and the ``lib/`` module
-_CATALOG_RES: dict[Language, tuple[re.Pattern[str], re.Pattern[str]]] = {
- Language.SCENE_THREEJS: (re.compile(r"`([a-z]+[A-Z]\w*)[(`]"), re.compile(r"`lib/(\w+\.js)`")),
-}
-
-
-def library_rows(description: str, language: Language = Language.SCENE_THREEJS) -> str:
- if language not in _CATALOG_RES:
- return ""
- call_re, module_re = _CATALOG_RES[language]
- words = set(re.findall(r"\w+(?:\.\w+)*", description))
- return "\n".join(line for line in language_text(language, "effects_catalog.md").splitlines()
- if line.startswith("| ")
- and words & (set(call_re.findall(line)) | set(module_re.findall(line))))
-
-
-def _asset_prompt(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language, files: list[str] | None = None) -> str:
- files = list(files or [rel])
- prompt = render(asset_template(language), **base_prompt_context(
- ctx, asset_name=asset.name, asset_kind=asset.kind, asset_description=asset.description, asset_size=asset.approx_size_m,
- library_rows=library_rows(asset.description, language),
- asset_file=rel, asset_files=files, asset_language=language.value, fix_instructions=[], current_code="",
- # a single-shot hero has to see the multi-file skeleton it is filling in, like a static object
- skeleton_files=skeleton_files(ctx) if (ctx.single_shot and len(files) > 1) else {},
- **_scene_context(ctx)))
- ctx.record_prompt("scene_asset", prompt)
- return prompt
-
-
-def _stamp_glb(result: AssetResult, ctx: RunContext, glb: Path) -> AssetResult:
- """What the shipped GLB says about itself: its measured size and the clips it carries."""
- result.size_m = _measure_size(ctx, glb) or result.size_m
- result.clips = glb_clip_count(glb)
- return result
-
-
-def glb_clip_count(glb: Path) -> int:
- """How many animation clips a GLB carries (its JSON chunk; no loader needed)."""
- try:
- b = glb.read_bytes()
- if b[:4] != b"glTF":
- return 0
- (ln,) = struct.unpack_from("<I", b, 12)
- return len(json.loads(b[20:20 + ln]).get("animations") or [])
- except (OSError, ValueError, struct.error):
- return 0
-
-
-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 ""
-
-
-# ===================================================================== cheap asset generation
-#: max triangles for ONE asset instance (the scene contract's budget)
-ASSET_MAX_TRIS = 15_000
-
-
-# ----------------------------------------------------------------------------- deterministic check
-class AssetCheck(BaseModel):
- """Result of importing the asset module and calling its builder."""
-
- ok: bool = False
- ran: bool = Field(default=False, description="False = the checker itself could not run (node missing)")
- fatal: bool = Field(default=False, description="the module does not import / build at all — zones must not use it")
- errors: list[str] = Field(default_factory=list)
- warnings: list[str] = Field(default_factory=list)
- size_m: tuple[float, float, float] | None = None
- min_y: float | None = None
- tris: int = Field(default=0, description="triangles the asset built itself (the per-asset budget)")
- lib_tris: int = Field(default=0, description="triangles the effect-library factories it composes built (D100)")
- meshes: int = 0
- materials: int = 0
- glb: str = Field(default="", description="the built GLB (blender heroes), '' for a module")
-
- def report(self, limit: int = 6) -> str:
- return "\n".join(f"- {e}" for e in (self.errors + self.warnings)[:limit])
-
-
-def check_threejs_asset(ctx: RunContext, rel: str, pascal: str, *, timeout_s: float = 60.0,
- expected_size_m: tuple[float, float, float] | None = None) -> AssetCheck:
- """Import ``rel`` in node, call ``build<Pascal>(THREE, {})`` and inspect the group."""
- path = ctx.ws.root / rel
- if not path.is_file():
- return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"{rel} was not written"])
- try:
- from codeverse3d.spatial.node import run_node, runtime_js_dir
-
- lifecycle = ctx.ws.src / "lib" / "lifecycle.js"
- args = [path.resolve().as_uri(), f"build{pascal}"] + ([lifecycle.resolve().as_uri()] if lifecycle.is_file() else [])
- res = run_node(runtime_js_dir() / "lib" / "asset_check.mjs", args, cwd=ctx.ws.root,
- three_hook=True, timeout_s=timeout_s, check=False)
- data = res.last_json
- if data is None:
- tail = (res.stderr or res.stdout or "").strip().splitlines()[-3:]
- return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"the module failed to load: {' / '.join(tail)[:300]}"])
- chk = AssetCheck(ok=bool(data.get("ok")), ran=True, errors=list(data.get("errors") or []),
- warnings=list(data.get("warnings") or []),
- size_m=tuple(data["size_m"]) if data.get("size_m") else None, # type: ignore[arg-type]
- min_y=data.get("min_y"), tris=int(data.get("tris") or 0), lib_tris=int(data.get("lib_tris") or 0),
- meshes=int(data.get("meshes") or 0), materials=int(data.get("materials") or 0))
- except Exception as e: # noqa: BLE001 — the checker is an optimisation, never a blocker
- log.warning("asset check could not run for %s: %s", rel, e)
- return AssetCheck(ok=True, ran=False, warnings=[f"checker unavailable: {type(e).__name__}"])
- chk.fatal = not chk.ok # everything the JS side reports is a hard failure to import/build
- _soft_findings(chk, expected_size_m) # …the rest is wrong-but-usable: worth a repair, not a veto
- return chk
-
-
-#: probe zone of a bpy asset check: one collection instance at the origin, so the census GLB carries exactly the asset's geometry
-BPY_CHECK_ZONE = "check"
-
-
-def _bpy_check_workspace(ws: Workspace, rel: str, snake: str) -> Workspace:
- from codeverse3d.languages.scene_blender import render_scene_py
-
- scratch = Workspace(ws.root / "_assets" / f"{snake}_check")
- if scratch.root.exists():
- shutil.rmtree(scratch.root)
- for sub in ("assets", "zones"):
- (scratch.src / sub).mkdir(parents=True, exist_ok=True)
- scratch.artifacts.mkdir(parents=True, exist_ok=True)
- (scratch.root / ENTRY_FILE[Language.SCENE_BLENDER]).write_text(render_scene_py([], [snake], [], []))
- shutil.copyfile(ws.root / rel, scratch.src / "assets" / f"{snake}.py")
- (scratch.src / "zones" / f"{BPY_CHECK_ZONE}.py").write_text(
- f'"""The harness\'s probe zone: one instance of {snake}, so the census GLB measures it."""\n'
- "import bpy\n\n\n"
- "def build(ctx):\n"
- f" ob = bpy.data.objects.new({to_pascal(snake)!r}, None)\n"
- ' ob.instance_type = "COLLECTION"\n'
- f" ob.instance_collection = ctx.assets[{snake!r}]\n"
- " ctx.collection.objects.link(ob)\n"
- " return ctx.collection\n")
- return scratch
-
-
-def check_bpy_asset(ctx: RunContext, rel: str, snake: str, *, expected_size_m: tuple[float, float, float] | None = None,
- timeout_s: float | None = None) -> AssetCheck:
- """Build ``src/assets/<snake>.py`` alone in Blender and inspect what it made."""
- path = ctx.ws.root / rel
- if not path.is_file():
- return AssetCheck(ok=False, ran=True, fatal=True, errors=[f"{rel} was not written"])
- run_wrapper = getattr(ctx.runtime, "run_wrapper", None)
- if not callable(run_wrapper):
- return AssetCheck(ok=True, ran=False, warnings=["checker unavailable: the runtime builds no module on its own"])
- try:
- scratch = _bpy_check_workspace(ctx.ws, rel, snake)
- run = run_wrapper(scratch, scratch.artifacts, zones={BPY_CHECK_ZONE: to_pascal(BPY_CHECK_ZONE)}, blend=False,
- timeout_s=float(timeout_s or ctx.settings.limits.build_timeout_s))
- except Exception as e: # noqa: BLE001 — the checker is an optimisation, never a blocker
- log.warning("bpy asset check could not run for %s: %s", rel, e)
- return AssetCheck(ok=True, ran=False, warnings=[f"checker unavailable: {type(e).__name__}"])
- report = run.report or {}
- for e in report.get("errors") or []:
- if e.get("stage") == "asset" and e.get("name") == snake:
- where = f"{e.get('error_file') or rel}:{e.get('error_line')}" if e.get("error_line") else str(e.get("error_file") or rel)
- return AssetCheck(ok=False, ran=True, fatal=True,
- errors=[f"{where}: {e.get('error_type')}: {str(e.get('error_message'))[:300]}"])
- if run.result.harness_failure:
- # the wrapper's own instrumentation failed (``CensusGlbError``), not the module: never a blocker
- log.warning("bpy asset check could not finish for %s: %s", rel, run.result.error_type)
- return AssetCheck(ok=True, ran=False, warnings=[f"checker unavailable: {run.result.error_type}"])
- if report.get("nonfinite"):
- return AssetCheck(ok=False, ran=True, fatal=True,
- errors=[f"{report.get('error_file') or rel}: {report.get('error_type')}: "
- f"{str(report.get('error_message'))[:600]}"])
- if not run.result.ok:
- # the wrapper did not finish (unbounded loop, allocation past the rlimit): this module's doing
- return AssetCheck(ok=False, ran=True, fatal=True,
- errors=[f"the module's build did not finish: {run.result.error_type}: {run.result.error_message}"[:300]])
- if any(e.get("stage") == "zone" for e in report.get("errors") or []):
- return AssetCheck(ok=False, ran=True, fatal=True,
- errors=[f"build_{snake}(ctx) returned no Collection the scene could instance (ctx.assets[{snake!r}] is missing)"])
- chk = AssetCheck(ok=True, ran=True, tris=int((run.facts or {}).get("unique_tris") or 0))
- try:
- m = ctx.services.measure(scratch.artifacts / "census.glb")
- except Exception as e: # noqa: BLE001 — a module that built but cannot be measured is still usable
- chk.warnings.append(f"measure unavailable: {type(e).__name__}")
- return chk
- chk.size_m = (round(m.extents[0], 3), round(m.extents[1], 3), round(m.extents[2], 3))
- chk.min_y, chk.meshes, chk.materials = round(m.bbox_min[1], 3), m.n_meshes, m.materials
- chk.tris = chk.tris or m.tri_count
- _soft_findings(chk, expected_size_m)
- return chk
-
-
-def _soft_findings(chk: AssetCheck, expected: tuple[float, float, float] | None, *, max_tris: int = ASSET_MAX_TRIS) -> None:
- """Findings that make the asset WRONG but not broken → errors worth one repair."""
- if not chk.ok:
- return
- if chk.min_y is not None and chk.min_y < -0.02:
- chk.errors.append(f"the group sinks {abs(chk.min_y):.2f} m below y=0 — its lowest point must sit at y=0")
- if chk.tris > max_tris:
- chk.errors.append(f"{chk.tris} triangles exceeds the {max_tris} budget per asset — lower the segment counts")
- if chk.tris + chk.lib_tris > MAX_TRIS_OBJECT:
- chk.errors.append(f"the effect-library factories it calls build {chk.lib_tris} triangles, past the {MAX_TRIS_OBJECT} "
- "ceiling for one object — pass their lighter options (fewer leaves, fewer leaf segments) or call fewer")
- if chk.meshes == 1 and chk.materials <= 1 and chk.tris + chk.lib_tris < 200:
- chk.errors.append("the asset is still a single low-poly box (one mesh, one material): build it from several "
- "parts with distinct materials so it reads as the described object")
- if expected and chk.size_m:
- for axis, got, want in zip("whd", chk.size_m, expected, strict=False):
- if want > 0.05 and (got > want * 2.5 or got < want * 0.4):
- chk.errors.append(f"measured {axis}={got:.2f} m but the plan says {want:.2f} m — rescale to the planned size (±5 %)")
- break
- chk.ok = not chk.errors
-
-
-def repair_feedback(chk: AssetCheck, rel: str) -> str:
- """The error-feedback block for the ONE single-shot repair attempt."""
- return (f"## The file you wrote did NOT pass the deterministic asset check\n"
- f"The harness imported `{rel}` in node and called its builder. Fix exactly these, "
- f"return the COMPLETE file again:\n{chk.report()}\n")
diff --git a/harness/codeverse3d/tracks/skills_hook.py b/harness/codeverse3d/tracks/skills_hook.py
deleted file mode 100644
index ab7dfe44..00000000
--- a/harness/codeverse3d/tracks/skills_hook.py
+++ /dev/null
@@ -1,95 +0,0 @@
-"""Skills hook: attaches the selected skills to a track's prompts."""
-
-
-from __future__ import annotations
-
-import logging
-from collections.abc import Sequence
-from typing import Any
-
-from codeverse3d.config import get_settings
-from codeverse3d.contracts.artifacts import BuildResult, GateReport
-from codeverse3d.contracts.run import SkillsUsage
-from codeverse3d.tracks.common import RunContext
-
-log = logging.getLogger(__name__)
-
-CTX_KEY = "skills"
-
-
-def attach_for_round(ctx: RunContext, *, index: int, kind: str, findings: Sequence[GateReport] = ()) -> Any | None:
- """Route + materialise this round's skills. Returns the ``SkillsMaterialized``."""
- from codeverse3d.skills import attach_skills
-
- # drop the previous round's set first: a failure below must not leave this round
- # probing — and crediting — bundles it never attached
- ctx.extra.pop(CTX_KEY, None)
- if not get_settings().skills:
- return None
- try:
- got = attach_skills(
- ctx.ws.root,
- track=ctx.spec.track.value if hasattr(ctx.spec.track, "value") else str(ctx.spec.track),
- language=ctx.language.value,
- kind=kind,
- plan=ctx.plan,
- findings=list(findings),
- single_shot=ctx.single_shot,
- )
- except Exception as e: # noqa: BLE001 — never let the skill system break a round
- log.warning("skills not attached for round %d (%s): %s", index, kind, e)
- return None
- ctx.extra[CTX_KEY] = got
- for sel in got.selections:
- ctx.record_prompt(f"skill:{sel.name}", sel.skill.body)
- ctx.events.emit("skills.attached", round=index, kind=kind, skills=got.listed,
- index_tokens=got.index_tokens, inlined=got.inlined or None, reasons=got.reasons)
- return got
-
-
-def with_inlined_skill(ctx: RunContext, tasks: Sequence[Any]) -> list[Any]:
- """Single-shot only: prepend the one routed body to each task prompt."""
- got = ctx.extra.get(CTX_KEY)
- if not got or not getattr(got, "inlined", ""):
- return list(tasks)
- from codeverse3d.skills.prompting import inline_body
-
- _, text = inline_body(got.selections)
- if not text:
- return list(tasks)
- return [t.model_copy(update={"prompt": f"{text}\n---\n\n{t.prompt}"}) for t in tasks]
-
-
-def repair_pointers(ctx: RunContext, build: BuildResult, lint: GateReport) -> str:
- """Name the attached skills that answer the CURRENT failure: the lint and the build's own"""
- got = ctx.extra.get(CTX_KEY)
- if not got or not getattr(got, "selections", None):
- return ""
- from codeverse3d.skills.prompting import repair_pointers as _fmt
- from codeverse3d.skills.registry import ROUTES, finding_kinds
-
- kinds = finding_kinds([lint, *build.gates])
- answering = [s.name for s in got.selections if any(r.skill == s.name and r.matches_finding(kinds) for r in ROUTES)]
- return _fmt(got.selections, agent_kind=ctx.agent_kind, answering=answering)
-
-
-def record_usage(ctx: RunContext, *, index: int, kind: str) -> SkillsUsage | None:
- got = ctx.extra.get(CTX_KEY)
- if not got:
- return None
- try:
- from codeverse3d.skills.telemetry import append_usage, probe_reads
-
- usage = probe_reads(ctx.ws.root, got)
- append_usage(ctx.ws.root, usage, round=index, kind=kind, agent=ctx.agent_id,
- track=ctx.spec.track.value if hasattr(ctx.spec.track, "value") else str(ctx.spec.track),
- language=ctx.language.value)
- except Exception as e: # noqa: BLE001 — telemetry never costs a round
- log.warning("skills telemetry failed for round %d: %s", index, e)
- return None
- ctx.events.emit("skills.read", round=index, listed=usage.listed, deep=usage.deep,
- surfaced=usage.surfaced, body_tokens_read=usage.body_tokens_read)
- return usage
-
-
-__all__ = ["CTX_KEY", "attach_for_round", "record_usage", "repair_pointers", "with_inlined_skill"]
diff --git a/harness/codeverse3d/tracks/static_object.py b/harness/codeverse3d/tracks/static_object.py
deleted file mode 100644
index 7425ae3d..00000000
--- a/harness/codeverse3d/tracks/static_object.py
+++ /dev/null
@@ -1,249 +0,0 @@
-"""StaticObjectTrack."""
-
-from __future__ import annotations
-
-import logging
-from collections.abc import Sequence
-from pathlib import Path
-
-from codeverse3d.agents.cli_common import HARD_GRACE_S
-from codeverse3d.contracts.artifacts import (
- BuildResult,
- GateFinding,
- GateReport,
- Measurement,
- RenderSet,
- Severity,
-)
-from codeverse3d.contracts.common import TRACK_INFO, Track
-from codeverse3d.contracts.plan import Plan, StaticPlan
-from codeverse3d.contracts.run import RoundRecord
-from codeverse3d.conventions import (
- BBOX_TOLERANCE_M,
- OBJECT_CLAY_VIEWS,
- OBJECT_VIEWS,
-)
-from codeverse3d.orchestrator import RefineTask, TaskGroup, compact_instructions
-from codeverse3d.prompts import render
-from codeverse3d.spatial.contract import check_fixed_parts, planned_joins
-from codeverse3d.spatial.silhouette import measure_reference
-from codeverse3d.tracks.common import RunContext
-from codeverse3d.tracks.depth import budget_gate, depth_budget
-from codeverse3d.tracks.generation import GenerationTask
-from codeverse3d.tracks.lifecycle import BaseTrack
-from codeverse3d.tracks.prompting import (
- base_prompt_context,
- judge_digest,
- judged_sheet,
- measurement_vs_plan,
- reference_images,
- refine_inline_files,
-)
-from codeverse3d.workspace import Workspace
-
-log = logging.getLogger(__name__)
-
-#: the 4 clay views judged for holes/intersections; their own cameras, not a name filter over OBJECT_VIEWS
-GEOMETRY_VIEWS = OBJECT_CLAY_VIEWS
-
-
-class ObjectPipeline:
- """Measure → connectivity + contract → 14-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( # fix hints in the author's frame; planned joins measured into the ledger
- ctx.services.connectivity(glb, ctx.language.value, planned_edges=planned_joins(ctx.plan, measurement))
- )
- 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)
- )
- # deterministic density check against the plan; the judge is never asked about detail
- out.append(budget_gate(measurement, build, depth_budget(ctx.plan, ctx.settings.limits.build_timeout_s)))
- if measurement is not None and ctx.spec.fixed_parts:
- # the project's fixed parts (Spec.fixed_parts) built as declared: not moved, scaled or edited
- out.append(check_fixed_parts(measurement, ctx.spec.fixed_parts))
- 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 post_render_gates(
- self, ctx: RunContext, round_index: int, renders: RenderSet
- ) -> list[GateReport]:
- """Reference-image runs: outline IoU vs the target image (WARN finding with the number)."""
- gate = silhouette_gate(ctx, renders)
- return [gate] if gate is not None else []
-
- def geometry_views(
- self, ctx: RunContext, round_index: int, build: BuildResult
- ) -> RenderSet | None:
- """4 clay views for the judge's geometry montage (holes, intersections)."""
- if not build.glb_path:
- return None
- out_dir = ctx.ws.renders_dir(round_index) / "clay"
- try:
- return ctx.services.render_geometry(Path(build.glb_path), out_dir, views=GEOMETRY_VIEWS)
- except Exception as e: # noqa: BLE001 — optional judge context, never round-fatal
- log.warning("clay geometry render failed: %s", e)
- ctx.events.emit(
- "render.geometry_failed", round=round_index, error=f"{type(e).__name__}: {e}"
- )
- return None
-
- def judge_context(
- self,
- ws: Workspace,
- plan: Plan | None,
- round_index: int,
- build: BuildResult,
- gates: list[GateReport],
- ) -> str:
- """Nothing beyond ``gates_section``."""
- return ""
-
-
-class StaticObjectTrack(BaseTrack):
- track = Track.STATIC_OBJECT
- rubric = TRACK_INFO[Track.STATIC_OBJECT].rubric
- plan_model = StaticPlan
- generate_template = "tracks/generate_static.j2"
- refine_template = "tracks/refine_object.j2"
- #: the part files interlock: one whole-object refine session per round
- allow_refine_fanout = False
-
- def make_pipeline(self) -> ObjectPipeline:
- return ObjectPipeline()
-
- # ------------------------------------------------------------------ refine (scaffold hooks)
- def extra_refine_tasks(self, ctx: RunContext, last: RoundRecord) -> Sequence[RefineTask]:
- # the `detail_budget` WARN is deliberately NOT a refine task (adding triangles while assembly is open lowers the score)
- return reference_refine_tasks(ctx, last)
-
- def _refine_task(
- self, ctx: RunContext, group: TaskGroup, last: RoundRecord, index: int, *, parallel: bool
- ) -> GenerationTask:
- """The round's ONE whole-object session."""
- fenced = ctx.single_shot and bool(group.files)
- files = list(group.files) if fenced else ctx.runtime.expected_files(ctx.plan)
- lines = compact_instructions(group.tasks, max_lines=ctx.policy.max_instructions_per_task)
- prompt = render(
- self.refine_template,
- **base_prompt_context(
- ctx,
- round_index=index,
- tasks=lines,
- targets=group.targets,
- files=files,
- edit_only_these=fenced,
- judge_summary=judge_digest(last),
- measurement_notes=measurement_vs_plan(last, ctx.plan, ctx.language),
- # single-shot only: the files the tasks name (all of them for an "overall" task)
- current_files=refine_inline_files(ctx, files),
- ),
- )
- ctx.record_prompt("refine", prompt)
- return GenerationTask(
- label="refine",
- prompt=prompt,
- system=self.system_prompt(ctx),
- files_hint=files,
- round=index,
- kind="refine",
- temperature=0.4,
- images=reference_images(ctx) + judged_sheet(last),
- edit_only=fenced,
- owns_entry=True,
- timeout_s=None if ctx.single_shot else object_session_window_s(ctx),
- )
-
-
-REFINE_MIN_WINDOW_S = 120.0
-
-
-def object_session_window_s(ctx: RunContext) -> int:
- """A refine session's window."""
- left = ctx.budget.left_s() - ctx.policy.judge_reserve_s - HARD_GRACE_S
- return int(max(REFINE_MIN_WINDOW_S, min(float(ctx.settings.limits.agent_timeout_s), left)))
-
-
-# ===================================================================== reference images
-SILHOUETTE_GATE = "reference_silhouette"
-IOU_REFINE_THRESHOLD = 0.6
-
-
-def silhouette_gate(ctx: RunContext, renders: RenderSet) -> GateReport | None:
- try:
- m = measure_reference(renders.views, ctx.spec, compare=ctx.services.silhouette)
- except Exception as e: # noqa: BLE001 — advisory measurement; never fails a round
- log.warning("compare_silhouette failed: %s", e)
- return GateReport.of(SILHOUETTE_GATE, [GateFinding(
- gate=SILHOUETTE_GATE, severity=Severity.INFO, target="overall", message=f"silhouette comparison unavailable: {e}")])
- if m is None:
- return None
- low = m.scorable and m.iou < IOU_REFINE_THRESHOLD
- msg = (f"outline IoU vs reference = {m.iou:.3f} (best-matching view: {m.view})"
- + ("" if m.reliable else " (unreliable mask)")
- + (" (the reference's proportions contradict the brief: not a shape verdict)" if m.conflict else "")
- + (f" — below {IOU_REFINE_THRESHOLD:.1f}" if low else ""))
- finding = GateFinding(gate=SILHOUETTE_GATE, severity=Severity.WARN if low else Severity.INFO, target="overall",
- message=msg, data=m.model_dump(exclude={"per_view"}),
- fix_hint=("match the reference outline: compare proportions (aspect ratio), overall extents and the "
- "silhouette of each major part against the reference image" if low else ""))
- return GateReport.of(SILHOUETTE_GATE, [finding])
-
-
-def silhouette_iou(rec: RoundRecord) -> tuple[float, dict] | None:
- """(iou, data) recorded by ``silhouette_gate`` in a round, if any."""
- for g in rec.gates:
- if g.gate != SILHOUETTE_GATE:
- continue
- for f in g.findings:
- if "iou" in f.data:
- try:
- return float(f.data["iou"]), dict(f.data)
- except (TypeError, ValueError):
- return None
- return None
-
-
-def reference_refine_tasks(ctx: RunContext, last: RoundRecord) -> list[RefineTask]:
- """A priority-1 refine task when the last round's silhouette IoU was below threshold."""
- if not ctx.spec.references:
- return []
- hit = silhouette_iou(last)
- if hit is None:
- return []
- iou, data = hit
- if iou >= IOU_REFINE_THRESHOLD or data.get("reliable") is False or data.get("conflict"):
- return []
- seen = f" (best-matching view: {data['view']})" if data.get("view") else ""
- bits = [f"Silhouette IoU vs the reference image is {iou:.2f}{seen} (target ≥ {IOU_REFINE_THRESHOLD:.1f})."]
- aspect = data.get("aspect_ratio_err")
- if isinstance(aspect, (int, float)):
- ra, rr = data.get("ref_aspect"), data.get("render_aspect")
- if isinstance(ra, (int, float)) and isinstance(rr, (int, float)):
- bits.append(f"Aspect (w/h): reference {ra:.2f} vs model {rr:.2f} — " +
- ("make the object wider relative to its height" if rr < ra else "make the object taller relative to its width") + ".")
- bits.append("Re-read the reference: match the outline of every major part (overall proportions first, then part shapes), "
- "keeping names and the plan's dimensions unless the reference clearly disagrees.")
- return [RefineTask(target="overall", kind="reference", instruction=" ".join(bits), priority=1, source="gate")]
diff --git a/harness/codeverse3d/tracks/steps.py b/harness/codeverse3d/tracks/steps.py
deleted file mode 100644
index 75297d6e..00000000
--- a/harness/codeverse3d/tracks/steps.py
+++ /dev/null
@@ -1,296 +0,0 @@
-"""One round = generate → build(+repair) → gates → measure → render → judge → commit."""
-
-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 Protocol
-
-from codeverse3d.contracts.artifacts import (
- BuildResult,
- GateReport,
- Judgment,
- Measurement,
- RenderSet,
-)
-from codeverse3d.contracts.common import Usage
-from codeverse3d.contracts.plan import AcceptanceItem, Plan
-from codeverse3d.contracts.run import RoundRecord, StepTime
-from c3d_flywheel.cost.tally import tally, timed
-from codeverse3d.judges.base import round_input
-from codeverse3d.orchestrator import BudgetExceeded
-from codeverse3d.proc import fan_out
-from c3d_flywheel.record.deliverable import keep_round_artifacts
-from codeverse3d.spatial.render import RenderError
-from codeverse3d.tracks import skills_hook
-from codeverse3d.tracks.common import RunContext, generate_for
-from codeverse3d.tracks.generation import GenerationResult, GenerationTask
-from codeverse3d.tracks.project_checks import run_project_checks
-from codeverse3d.tracks.repair import RepairOutcome, build_with_repair
-from codeverse3d.workspace import Workspace
-
-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 judge_context(self, ws: Workspace, plan: Plan | None, round_index: int, build: BuildResult, gates: list[GateReport]) -> str:
- """Track-specific judge context. Deliberately ``RunContext``-free so"""
- ...
-
-
-class RoundFailed(RuntimeError):
- """Every generation task of a round failed — nothing to build."""
-
- def __init__(self, message: str, *, transient: bool = False, quota: bool = False, stalled: bool = False) -> None:
- super().__init__(message)
- self.transient = transient
- self.quota = quota
- self.stalled = stalled
-
- @classmethod
- def of(cls, results: Sequence[GenerationResult], default: str) -> RoundFailed:
- """The round's failure: every task's notes, and the typed flags of any of them — except"""
- return cls("; ".join(f"{r.label}: {r.notes}" for r in results) or default,
- transient=any(r.transient for r in results), quota=any(r.quota for r in results),
- stalled=any(r.stalled for r in results) and all(r.stalled or r.transient for r in results))
-
-
-def round_record_path(ctx: RunContext, index: int) -> Path:
- return ctx.ws.root / "rounds" / f"r{index:02d}.json"
-
-
-def load_round_journal(ws: Workspace) -> list[RoundRecord]:
- """The on-disk round journal: ``rounds/r*.json`` sorted, contiguous prefix only."""
- d = 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(ws.read_json(p))
- if rec.index != i:
- break
- out.append(rec)
- return out
-
-
-def run_generation_tasks(ctx: RunContext, tasks: Sequence[GenerationTask], *,
- steps: list[StepTime]) -> list[GenerationResult]:
- """Run tasks side by side — one ``generate`` step: its sessions share one clock. Raises"""
- if not tasks:
- return []
-
- def _one(task: GenerationTask) -> GenerationResult:
- return generate_for(ctx, task)
-
- # fan_out also for ONE task: a crashing generator (503 storm, parse error) becomes a failed
- # result → RoundFailed (a refine round then stops the run as no_change) instead of killing it.
- with timed("generate", steps, round_index=tasks[0].round):
- results = fan_out(list(tasks), _one, max_workers=ctx.settings.limits.max_parallel_agents,
- label="generate", item_name=lambda t: t.label)
- out: list[GenerationResult] = []
- budget_stop: Exception | None = None
- for task, r in zip(tasks, results, strict=True):
- if isinstance(r, Exception):
- if isinstance(r, BudgetExceeded) and budget_stop is None:
- budget_stop = r
- ctx.events.emit("generate.failed", label=task.label, error=f"{type(r).__name__}: {r}")
- out.append(GenerationResult.from_error(task.label, r))
- else:
- out.append(r)
- if not any(r.ok for r in out):
- if budget_stop is not None:
- raise budget_stop
- raise RoundFailed.of(out, "no generation task succeeded")
- ctx.budget.check()
- return out
-
-
-def run_round(
- ctx: RunContext,
- *,
- index: int,
- kind: str,
- tasks: Sequence[GenerationTask],
- pipeline: RoundPipeline,
- instructions: Sequence[str] = (),
- previous: Judgment | None = None,
- findings: Sequence[GateReport] = (),
- files_hint: Sequence[str] = (),
- extra_usage: Usage | None = None,
- extra_notes: Sequence[str] = (),
-) -> RoundRecord:
- """Execute one round and persist its record. Budget is charged as it goes."""
- steps: list[StepTime] = []
- with tally() as spent:
- try:
- 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))
- notes: list[str] = list(extra_notes)
-
- skills_hook.attach_for_round(ctx, index=index, kind=kind, findings=findings)
- gens = run_generation_tasks(ctx, skills_hook.with_inlined_skill(ctx, tasks), steps=steps)
- notes += [f"{g.label}: {g.notes}" for g in gens if not g.ok]
- ctx.ws.commit(f"r{index:02d} {kind}: generated")
-
- with timed("build", steps, round_index=index):
- outcome: RepairOutcome = build_with_repair(ctx, round_index=index, label=f"r{index:02d}_{kind}",
- files_hint=list(files_hint))
- rec.build = outcome.build
- gates: list[GateReport] = [outcome.lint]
- if outcome.attempts:
- notes.append(
- f"repair attempts: {len(outcome.attempts)}/{outcome.max_attempts} "
- f"({'fixed' if outcome.ok else 'still failing'})"
- )
-
- if outcome.build.ok:
- with timed("gates", steps, round_index=index):
- rec.measurement = pipeline.measure(ctx, outcome.build)
- gates.extend(pipeline.gates(ctx, index, outcome.build, rec.measurement))
- if ctx.spec.checks and outcome.build.glb_path: # the project's own checks (Spec.checks)
- gates.extend(run_project_checks(ctx.spec, ctx.ws.root, Path(outcome.build.glb_path),
- rec.measurement, index))
- try:
- with timed("render", steps, round_index=index):
- rec.renders = pipeline.render(ctx, index, outcome.build, rec.measurement)
- except RenderError as e:
- rec.renders = None
- notes.append(f"render failed: {str(e)[:200]}")
- ctx.events.emit("render.failed", round=index, error=str(e)[:400])
- post = getattr(pipeline, "post_render_gates", None)
- if callable(post) and rec.renders is not None:
- with timed("gates", steps, round_index=index):
- gates.extend(post(ctx, index, rec.renders))
- gates.extend(outcome.build.gates)
- n_err = sum(len(g.errors) for g in gates)
- ctx.events.emit("gates.done", round=index, n_gates=len(gates), n_errors=n_err,
- tri_count=rec.measurement.tri_count if rec.measurement else None)
- skip = skip_judge_reason(ctx, renders=rec.renders)
- if skip:
- notes.append(f"judge skipped ({skip})")
- ctx.events.emit("judge.skipped", round=index, reason=skip)
- else:
- with timed("judge", steps, round_index=index):
- rec.judgment = _judge(ctx, pipeline, index, outcome.build, gates, rec, previous, notes)
- else:
- gates.extend(outcome.build.gates)
- notes.append(f"build failed: {outcome.build.error_type}: {outcome.build.error_message[:200]}")
- rec.gates = gates
- rec.skills = skills_hook.record_usage(ctx, index=index, kind=kind)
- _write_gate_reports(ctx, index, gates)
-
- rec.commit = ctx.ws.commit(f"r{index:02d} {kind}")
- if outcome.build.ok:
- keep_round_artifacts(ctx.ws, index)
- rec.usage = spent.usage + (extra_usage or Usage())
- rec.duration_s = round(time.time() - t0, 2)
- rec.steps = steps
- 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(rec.usage.cost_usd, 4))
- return rec
- except BaseException as e:
- record_aborted_round(ctx, index=index, kind=kind, usage=spent.usage,
- error=f"{type(e).__name__}: {e}", steps=steps)
- raise
-
-
-# ----------------------------------------------------------------------------- cost of a round
-def skip_judge_reason(ctx: RunContext, *, renders: RenderSet | None) -> str:
- """Why this round must NOT be judged (``""`` = judge it)."""
- if ctx.judge is None:
- return "no judge configured"
- if renders is None or not renders.views:
- return "no renders"
- return ""
-
-
-def record_aborted_round(ctx: RunContext, *, index: int, kind: str, usage: Usage, error: str,
- steps: Sequence[StepTime] = ()) -> None:
- """A round that raised half-way still reports what it burned."""
- try:
- ctx.state.steps.extend(steps)
- aborted = ctx.extra.setdefault("aborted_rounds", [])
- aborted.append({"index": index, "kind": kind, "cost_usd": round(usage.cost_usd, 6), "error": error[:300]})
- except Exception as e: # noqa: BLE001 — never mask the exception that stopped the round
- log.warning("could not record aborted round r%02d: %s", index, e)
-
-
-def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildResult, gates: list[GateReport],
- rec: RoundRecord, previous: Judgment | None, notes: list[str]) -> Judgment | None:
- """Judge one round; ``None`` when the verdict is unusable."""
- renders = rec.renders
- jv = getattr(pipeline, "judge_views", None)
- if callable(jv) and renders is not None:
- renders = jv(ctx, renders) or renders
- geometry = None
- gv = getattr(pipeline, "geometry_views", None)
- if callable(gv):
- geometry = gv(ctx, index, build)
- inp = round_input(ctx.spec, ctx.plan, rec, renders=renders, gates=gates, previous=previous,
- extra_context=pipeline.judge_context(ctx.ws, ctx.plan, index, build, gates),
- geometry_views=geometry, glb_path=build.glb_path)
- 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)
- paid = getattr(e, "usage", None)
- ctx.events.emit("judge.failed", round=index, error=f"{type(e).__name__}: {e}",
- cost_usd=round(paid.cost_usd, 4) if isinstance(paid, Usage) else 0.0)
- notes.append(f"judge failed: {type(e).__name__}: {e}")
- return None
- ctx.ws.write_json(ctx.ws.judge_path(index), judgment)
- if judgment.degraded:
- # a glitch, never a score: keep the raw verdict on disk, but do not let 0.0
- # poison a pick or a refine plan (judges/rubrics.degraded_judgment contract)
- ctx.events.emit("judge.degraded", round=index, error=judgment.summary[:300],
- cost_usd=round(judgment.usage.cost_usd, 4))
- notes.append(f"judge degraded: {judgment.summary[:200]}")
- return None
- 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 rejudge_round(ctx: RunContext, pipeline: RoundPipeline, rec: RoundRecord, previous: Judgment | None = None) -> bool:
- if ctx.judge is None or rec.build is None or not rec.build.ok or rec.renders is None or not rec.renders.views:
- return False
- ctx.events.emit("judge.retry", round=rec.index)
- notes: list[str] = [rec.notes] if rec.notes else []
- with timed("judge", rec.steps, round_index=rec.index) as spent:
- judgment = _judge(ctx, pipeline, rec.index, rec.build, list(rec.gates), rec, previous, notes)
- rec.usage = rec.usage + spent.usage
- if judgment is not None:
- rec.judgment = judgment
- rec.notes = "; ".join(notes)
- ctx.ws.write_json(round_record_path(ctx, rec.index), rec)
- return judgment is not None
-
-
-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]
diff --git a/harness/codeverse3d/tracks/zone_layout.py b/harness/codeverse3d/tracks/zone_layout.py
deleted file mode 100644
index c0574562..00000000
--- a/harness/codeverse3d/tracks/zone_layout.py
+++ /dev/null
@@ -1,173 +0,0 @@
-"""L2 zone layouts."""
-
-from __future__ import annotations
-
-import logging
-import math
-from typing import Any
-
-from codeverse3d.contracts.chat import ChatMessage, ChatRequest
-from codeverse3d.contracts.common import Language
-from codeverse3d.contracts.plan import ScenePlan, ZoneLayout, ZonePlan
-from codeverse3d.conventions import Frame, authoring_frame, to_authoring_frame, to_snake
-from codeverse3d.schema_utils import parse_json_lenient
-from codeverse3d.orchestrator import BudgetExceeded
-from codeverse3d.proc import NULL_EVENTS, fan_out
-from codeverse3d.prompts import render
-from codeverse3d.tracks.generation import _deadline_preflight
-
-log = logging.getLogger(__name__)
-
-LAYOUT_TEMPLATE = "tracks/plan_zone_layout.j2"
-LAYOUT_MAX_TOKENS = 4000
-LAYOUT_WAIT_S = 300.0
-#: a placement may multiply the plan's instances_hint by at most this much
-COUNT_SLACK = 4
-#: cluster centres may sit this far outside the zone bbox (assets have radius)
-BBOX_MARGIN_M = 1.0
-#: lens margin beyond the asset's own reach; the validator rejects only a lens INSIDE the
-#: asset's reach (half footprint + half spread + this, floored), spacing stays in the prompt.
-CAMERA_CLEAR_M = 0.4
-CAMERA_CLEAR_FLOOR_M = 0.8
-#: two LARGE assets on nearly the same spot are stacked; small footprints and supported items are never rejected.
-STACK_DIST_M = 0.6
-STACK_MIN_FOOT_M = 0.8
-
-
-def validate_layout(layout: ZoneLayout, zone: ZonePlan, plan: ScenePlan) -> str:
- """"" when the layout is buildable; otherwise the exact complaint to re-ask with."""
- problems: list[str] = []
- known = {to_snake(a.name): a for a in plan.assets}
- hints = {to_snake(a.name): max(1, a.instances_hint) for a in plan.assets}
- lo, hi = zone.bbox.min, zone.bbox.max
- for p in layout.placements:
- k = to_snake(p.asset)
- if k not in known:
- problems.append(f"placement names unknown asset '{p.asset}' (plan assets: {', '.join(sorted(known))})")
- continue
- x, z = p.cluster
- if not (lo[0] - BBOX_MARGIN_M <= x <= hi[0] + BBOX_MARGIN_M and lo[2] - BBOX_MARGIN_M <= z <= hi[2] + BBOX_MARGIN_M):
- problems.append(f"{p.asset} cluster ({x:.1f}, {z:.1f}) is outside zone {zone.name} bbox "
- f"x {lo[0]:.1f}..{hi[0]:.1f}, z {lo[2]:.1f}..{hi[2]:.1f}")
- if p.count > COUNT_SLACK * hints[k]:
- problems.append(f"{p.asset} count {p.count} is over {COUNT_SLACK}x the plan's instances_hint {hints[k]}")
- # a cluster whose footprint reaches a camera puts geometry inside the lens
- foot = max(known[k].approx_size_m[0], known[k].approx_size_m[2])
- need = max(CAMERA_CLEAR_FLOOR_M, foot / 2 + p.spread_m / 2 + CAMERA_CLEAR_M)
- base = known[to_snake(p.support)].approx_size_m[1] if to_snake(p.support) in known else 0.0
- top = base + known[k].approx_size_m[1]
- for cam in plan.cameras:
- if cam.position[1] > top + CAMERA_CLEAR_M:
- # the check is 2D; a lens well above the cluster's top cannot be inside it
- continue
- dist = math.hypot(x - cam.position[0], z - cam.position[2])
- if dist < need:
- problems.append(f"{p.asset} cluster ({x:.1f}, {z:.1f}) reaches camera {cam.name} "
- f"({dist:.1f} m < {need:.1f} m = half its footprint+spread plus lens margin) — "
- f"move the cluster or shrink its spread so the lens stays outside it")
- placed = {to_snake(p.asset) for p in layout.placements}
- missing = [c for c in zone.contents if to_snake(c) not in placed]
- if missing:
- problems.append(f"no placement for planned contents: {', '.join(missing)}")
- # two large assets on the same spot = stacked into each other
- rows = [(p, known.get(to_snake(p.asset))) for p in layout.placements]
- for i, (a, pa) in enumerate(rows):
- for b, pb in rows[i + 1:]:
- if pa is None or pb is None or to_snake(a.asset) == to_snake(b.asset):
- continue
- if to_snake(a.support) == to_snake(b.asset) or to_snake(b.support) == to_snake(a.asset):
- continue # one stands on the other by design
- fa = max(pa.approx_size_m[0], pa.approx_size_m[2])
- fb = max(pb.approx_size_m[0], pb.approx_size_m[2])
- if fa < STACK_MIN_FOOT_M or fb < STACK_MIN_FOOT_M:
- continue
- dist = math.hypot(a.cluster[0] - b.cluster[0], a.cluster[1] - b.cluster[1])
- if dist < STACK_DIST_M:
- problems.append(f"{a.asset} and {b.asset} share one spot ({dist:.1f} m apart, footprints "
- f"{fa:.1f}/{fb:.1f} m) — they will interpenetrate; separate the clusters or "
- f"make one the other's support")
- return "; ".join(problems)
-
-
-def ground_point(xz: tuple[float, float], language: Language | str) -> tuple[float, float]:
- v = to_authoring_frame((xz[0], 0.0, xz[1]), str(language))
- x, y = (v[0], v[1]) if authoring_frame(str(language)) is Frame.Z_UP_NEG_Y_FRONT else (v[0], v[2])
- # ``+ 0.0`` folds ``-0.0`` so the brief never prints ``(3.0, -0.0)``
- return (x + 0.0, y + 0.0)
-
-
-def layout_block(layout: ZoneLayout | dict[str, Any] | None, *, language: Language | str = Language.SCENE_THREEJS) -> str:
- if layout is None:
- return ""
- lay = layout if isinstance(layout, ZoneLayout) else ZoneLayout.model_validate(layout)
- lines = []
- for p in lay.placements:
- faces = f", facing {p.faces}" if p.faces else ""
- support = f", on {p.support}" if p.support and p.support != "ground" else ""
- cx, cz = ground_point(p.cluster, language)
- lines.append(f"- {p.count}x {p.asset} around ({cx:.1f}, {cz:.1f}) "
- f"spread {p.spread_m:.1f} m{faces}{support}")
- if lay.path_points:
- pts = " -> ".join("({:.1f}, {:.1f})".format(*ground_point(pt, language)) for pt in lay.path_points)
- lines.append(f"- path polyline: {pts}")
- dress = [f"{n} {label}" for n, label in ((lay.mid_props, "mid props"), (lay.small_props, "small props"),
- (lay.ground_cover, "ground-cover instances")) if n]
- if dress:
- lines.append("- dressing beyond the placements: " + ", ".join(dress))
- if lay.notes:
- lines.append(f"- intent: {lay.notes}")
- return "\n".join(lines)
-
-
-def _one_layout(zone: ZonePlan, plan: ScenePlan, model: Any, budget: Any, events: Any) -> ZoneLayout | None:
- neighbours = [f"{z.name}: x {z.bbox.min[0]:.0f}..{z.bbox.max[0]:.0f}, z {z.bbox.min[2]:.0f}..{z.bbox.max[2]:.0f}"
- for z in plan.zones if z.name != zone.name]
- assets = [f"{a.name}: {a.approx_size_m[0]:g}x{a.approx_size_m[1]:g}x{a.approx_size_m[2]:g} m, ~{a.instances_hint} planned"
- for a in plan.assets if to_snake(a.name) in {to_snake(c) for c in zone.contents}] or ["(no planned assets — dressing only)"]
- cameras = [f"{c.name} at ({c.position[0]:.1f}, {c.position[2]:.1f}), fov {c.fov:.0f} — {c.purpose}"
- for c in plan.cameras]
- system = render(LAYOUT_TEMPLATE, title=plan.title, setting=plan.setting, mood=plan.mood,
- environment=plan.environment[:600], zone=zone, neighbours=neighbours, assets=assets,
- cameras=cameras, schema_fields=", ".join(ZoneLayout.model_fields))
- user = (f"Lay out zone {zone.name}. Description (the brief's facts in it are binding; its counts are intent): "
- f"{zone.description}\nContents to place: {', '.join(zone.contents) or '(none)'}")
- complaint = ""
- for attempt in (0, 1):
- # past the hard ceiling the layout is skipped; a call that goes out gets the wall clock left
- try:
- max_wait_s = _deadline_preflight(budget, LAYOUT_WAIT_S, soft=True, floor_s=20.0)
- except BudgetExceeded as e:
- events.emit("layout.skipped_budget", zone=zone.name, error=str(e)[:200])
- return None
- ask = user if not complaint else f"{user}\n\nYour previous layout was rejected: {complaint}. Fix exactly these problems."
- resp = model.generate(ChatRequest(messages=[ChatMessage.user(ask)], system=system,
- response_schema=ZoneLayout.model_json_schema(), temperature=0.3,
- thinking="low", max_output_tokens=LAYOUT_MAX_TOKENS,
- max_wait_s=max_wait_s, label="zone-layout"))
- raw = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text or "{}")
- layout = ZoneLayout.model_validate(raw)
- layout.zone = zone.name # the name is an input, never model-invented
- complaint = validate_layout(layout, zone, plan)
- if not complaint:
- events.emit("layout.done", zone=zone.name, placements=len(layout.placements), reasked=bool(attempt))
- return layout
- events.emit("layout.rejected", zone=zone.name, complaint=complaint[:300])
- log.warning("zone layout for %s rejected twice (%s); building without one", zone.name, complaint)
- return None
-
-
-def layout_zones(plan: ScenePlan, model: Any, *, budget: Any = None, events: Any = None,
- max_workers: int = 6) -> dict[str, ZoneLayout]:
- """One validated layout per zone, computed in parallel."""
- events = NULL_EVENTS if events is None else events
-
- results = fan_out(list(plan.zones), lambda z: _one_layout(z, plan, model, budget, events), max_workers=max_workers, label="layouts",
- item_name=lambda z: z.name)
- out: dict[str, ZoneLayout] = {}
- for zone, r in zip(plan.zones, results, strict=True):
- if isinstance(r, Exception):
- events.emit("layout.failed", zone=zone.name, error=f"{type(r).__name__}: {r}"[:300])
- log.warning("zone layout for %s failed (%s); building without one", zone.name, r)
- elif r is not None:
- out[zone.name] = r
- return out
diff --git a/harness/codeverse3d/workflow.py b/harness/codeverse3d/workflow.py
new file mode 100644
index 00000000..31df85ec
--- /dev/null
+++ b/harness/codeverse3d/workflow.py
@@ -0,0 +1,541 @@
+"""The workflow tools: ``init`` · ``validate_plan`` · ``check`` · ``judge_pack`` · ``score``.
+
+They tie the instruments to the workspace the host agent works in: ``init`` writes ``spec.json`` and what the
+language runtime owns, ``validate_plan`` validates and normalises ``plan.json``, ``check`` builds and runs every
+gate of the track, ``judge_pack`` renders the judged views and writes ``judge/rNN/brief.md`` + images for a
+fresh-context judge, ``score`` turns that judge's ``judgment.json`` into the rubric arithmetic.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import shutil
+from pathlib import Path
+from typing import Any
+
+from pydantic import BaseModel, Field, ValidationError
+
+from codeverse3d.config import get_settings
+from codeverse3d.contracts.artifacts import GateReport, Judgment, RenderSet, Severity
+from codeverse3d.contracts.common import ENTRY_FILE, TRACK_LANGUAGES, TRACK_RUBRIC, Language, Track
+from codeverse3d.contracts.spec import Constraints, ReferenceImage, Spec
+from codeverse3d.conventions import LANGUAGE_FRAME, frame_doc
+from codeverse3d.gates import PLAN_MODELS, CheckResult, render_for_judge, run_check
+from codeverse3d.jsonparse import JsonParseError, parse_json_lenient
+from codeverse3d.judges import prompt_builder as pb
+from codeverse3d.judges.rubrics import (
+ JudgeParseError,
+ aggregate_samples,
+ load_rubric,
+ parse_judge_output,
+)
+from codeverse3d.languages import get_runtime
+from codeverse3d.plan_checks import (
+ asset_kind_errors,
+ fixed_part_clash,
+ missing_link_names,
+ normalise_plan,
+ plan_budget,
+ plan_quality_complaints,
+ schema_echo,
+ validation_errors,
+)
+from codeverse3d.proc import read_json_or_none
+from codeverse3d.spatial.observe import rel_path, text_observation
+from codeverse3d.spatial.registry import NoArgs, Observation, ToolContext, ToolUsageError, tool
+from codeverse3d.spatial.silhouette import compare_silhouette, dimension_conflict, measure_reference
+from codeverse3d.spatial.tool_common import spec_dict
+from codeverse3d.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+
+def _spec(ctx: ToolContext) -> Spec:
+ raw = spec_dict(ctx)
+ if not raw:
+ raise ToolUsageError("no spec.json in the workspace — run `3dcode init` first",
+ "3dcode init --track static_object --language blender --prompt '...'")
+ try:
+ return Spec.model_validate(raw)
+ except ValidationError as e:
+ raise ToolUsageError(f"spec.json is not a valid spec: {e}") from e
+
+
+def _plan_raw(ws: Workspace) -> dict[str, Any]:
+ if not ws.plan_path.is_file():
+ raise ToolUsageError("plan.json not found in the workspace — write it first (see the 3d-director skill)")
+ try:
+ data = json.loads(ws.plan_path.read_text())
+ except ValueError as e:
+ raise ToolUsageError(f"plan.json is not valid JSON: {e}") from e
+ if not isinstance(data, dict):
+ raise ToolUsageError(f"plan.json must hold a JSON object, got {type(data).__name__}")
+ return data
+
+
+def _plan_or_none(ws: Workspace, track: Track) -> BaseModel | None:
+ """The validated plan, or ``None`` when there is none / it does not validate (the tools say which)."""
+ if not ws.plan_path.is_file():
+ return None
+ try:
+ return PLAN_MODELS[track].model_validate(json.loads(ws.plan_path.read_text()))
+ except (ValueError, ValidationError):
+ return None
+
+
+# ===================================================================== init
+class InitArgs(BaseModel):
+ track: str = Field(description=f"one of {[t.value for t in Track]}")
+ language: str = Field(description="one of " + ", ".join(f"{t.value}: {[la.value for la in ls]}" for t, ls in TRACK_LANGUAGES.items()))
+ prompt: str = Field(description="what to build, the user's words")
+ must_have: list[str] = Field(default=[], description="hard requirements (repeat the flag per item)")
+ must_not: list[str] = Field(default=[], description="things that must not appear (repeat per item)")
+ dims: dict[str, float] = Field(default={}, description="stated dimensions in metres, e.g. height=0.45 (repeat per key)")
+ references: list[str] = Field(default=[], description="reference image paths (the first is the silhouette target)")
+ style: str = Field(default="", description="style words the plan and the judge read")
+ force: bool = Field(default=False, description="overwrite an existing spec.json")
+
+
+@tool("init", InitArgs, "Create the project: write spec.json and the workspace layout, plus what the language runtime "
+ "owns (e.g. scene_threejs src/lib/). Prints the files the language expects and the skill to read.")
+def init(ctx: ToolContext, args: InitArgs) -> Observation:
+ ws = ctx.workspace
+ if ws.spec_path.is_file() and not args.force:
+ raise ToolUsageError(f"{ws.spec_path} exists — pass --force to overwrite it", "3dcode init ... --force")
+ try:
+ track, language = Track(args.track), Language(args.language)
+ except ValueError as e:
+ raise ToolUsageError(str(e), "3dcode init --track static_object --language blender --prompt '...'") from e
+ refs = []
+ for i, r in enumerate(args.references):
+ p = Path(r).expanduser()
+ if not p.is_file():
+ raise ToolUsageError(f"reference image not found: {r}")
+ refs.append(ReferenceImage(path=str(p.resolve()), role="target" if i == 0 else "detail"))
+ try:
+ spec = Spec(id=ws.root.name, track=track, language=language, prompt=args.prompt.strip(), references=refs,
+ constraints=Constraints(dimensions_m=args.dims or None, style=args.style, must_have=args.must_have,
+ must_not=args.must_not))
+ except ValidationError as e:
+ raise ToolUsageError(f"invalid spec: {e}") from e
+ ws.ensure_layout()
+ ws.write_json(ws.spec_path, spec)
+ owned = _language_owned_files(ws, language)
+ rt = get_runtime(language)
+ lines = [f"INIT OK: {ws.root} — track {track.value}, language {language.value}",
+ f"spec.json written: {len(args.must_have)} must-have, {len(args.must_not)} must-not, "
+ f"{len(args.dims)} dimension(s), {len(refs)} reference image(s)",
+ f"entry file: {ENTRY_FILE[language]}; the agent's files: {', '.join(rt.entry_globs)}",
+ f"frame: {frame_doc(LANGUAGE_FRAME[language.value])}"]
+ if owned:
+ lines.append("runtime-owned files written (read, never edit): " + ", ".join(rel_path(p, ws.root) for p in owned[:12])
+ + (f" … +{len(owned) - 12}" if len(owned) > 12 else ""))
+ lib = getattr(rt, "lib_interface", None)
+ if callable(lib) and (surface := lib(ws)):
+ lines.append("library surface (src/lib):\n" + surface)
+ lines.append(f"next: read the skill 3d-lang-{language.value}, write plan.json, run `3dcode validate-plan`")
+ return text_observation(lines, numbers={"track": track.value, "language": language.value, "workspace": str(ws.root),
+ "entry": ENTRY_FILE[language], "owned_files": [rel_path(p, ws.root) for p in owned]},
+ limit=6000)
+
+
+def _language_owned_files(ws: Workspace, language: Language) -> list[Path]:
+ """What the runtime, not the agent, puts in the workspace."""
+ written: list[Path] = []
+ if language is Language.SCENE_THREEJS:
+ from codeverse3d.languages.scene_threejs import write_lib
+
+ written += write_lib(ws)
+ (ws.public / "assets").mkdir(parents=True, exist_ok=True)
+ elif language is Language.SCENE_BLENDER:
+ (ws.public / "assets").mkdir(parents=True, exist_ok=True)
+ elif language is Language.THREEJS:
+ from codeverse3d.languages.threejs import PACKAGE_JSON
+
+ pj = ws.src / "package.json"
+ if not pj.is_file():
+ pj.write_text(PACKAGE_JSON)
+ written.append(pj)
+ return written
+
+
+# ===================================================================== validate_plan
+@tool("validate_plan", NoArgs, "Validate plan.json against the track's plan model and the deterministic plan checks "
+ "(placeholder echo, size/detail budget from the request, fixed-part clash); writes the normalised plan back. "
+ "FAIL lists each error with its JSON path.")
+def validate_plan(ctx: ToolContext, args: NoArgs) -> Observation:
+ ws = ctx.workspace
+ spec = _spec(ctx)
+ raw = _plan_raw(ws)
+ model = PLAN_MODELS[spec.track]
+ errors: list[str] = []
+ echoed = schema_echo(raw)
+ if echoed:
+ errors.append(f"the plan echoes schema placeholders instead of describing the object: {echoed} — "
+ "write real names, real numbers")
+ errors += asset_kind_errors(raw, spec.language)
+ plan: BaseModel | None = None
+ try:
+ plan = model.model_validate(raw)
+ except ValidationError as e:
+ errors += validation_errors(e)
+ missing = missing_link_names(raw)
+ if missing:
+ errors.append(f"joints reference links that `parts` does not define: {', '.join(missing[:10])} — every link a "
+ "joint names must be a top-level part with its own bbox")
+ if plan is not None:
+ clash = fixed_part_clash(plan, spec)
+ if clash:
+ errors.append(clash)
+ if errors:
+ text = [f"PLAN INVALID ({model.__name__}): {len(errors)} error(s)"] + [f"- {e}" for e in errors]
+ return text_observation(text, ok=False, numbers={"errors": len(errors), "model": model.__name__}, limit=6000)
+ assert plan is not None
+ budget = plan_budget(spec)
+ unit = "passes" if spec.track is Track.GRAPHICS else "parts"
+ hard, soft = plan_quality_complaints(plan, budget, unit=unit)
+ notes = normalise_plan(plan, spec)
+ ws.write_json(ws.plan_path, plan)
+ rt = get_runtime(spec.language)
+ files = rt.expected_files(plan)
+ units = list(getattr(plan, "parts", None) or getattr(plan, "passes", None) or [])
+ head = "PLAN FAIL (valid, but not worth building yet)" if hard else "PLAN OK"
+ lines = [f"{head}: {model.__name__}, {len(units)} {unit}, {len(plan.acceptance)} acceptance items"]
+ lines += [f"- ERROR: {h}" for h in hard]
+ lines += [f"- WARN: {s}" for s in soft]
+ if notes:
+ lines.append("normalised and written back: " + "; ".join(notes))
+ lines.append(f"files to write ({spec.language.value}): " + ", ".join(files[:16]) + (" …" if len(files) > 16 else ""))
+ lines.append("acceptance: " + "; ".join(f"{a.id} [{a.priority}/{a.how}] {a.text}"[:160] for a in plan.acceptance[:12]))
+ return text_observation(lines, ok=not hard,
+ numbers={"model": model.__name__, "n_units": len(units), "files": files,
+ "acceptance_ids": [a.id for a in plan.acceptance], "hard": len(hard), "soft": len(soft),
+ **budget.as_dict()}, limit=6000)
+
+
+# ===================================================================== check
+def _gate_lines(gates: list[GateReport], *, max_errors: int = 20, max_warns: int = 10) -> list[str]:
+ lines = []
+ status = ", ".join(f"{g.gate}={'pass' if g.passed else 'FAIL'}" for g in gates)
+ lines.append(f"gates: {status}")
+ errs = [(g, f) for g in gates for f in g.findings if f.severity == Severity.ERROR]
+ warns = [(g, f) for g in gates for f in g.findings if f.severity == Severity.WARN]
+ for g, f in errs[:max_errors]:
+ lines.append(f"- ERROR {g.gate}" + (f" [{f.target}]" if f.target else "") + f": {f.message}")
+ if f.fix_hint:
+ lines.append(f" fix: {f.fix_hint}")
+ if len(errs) > max_errors:
+ lines.append(f"- … {len(errs) - max_errors} more error(s) (artifacts/gates.json)")
+ for g, f in warns[:max_warns]:
+ lines.append(f"- WARN {g.gate}" + (f" [{f.target}]" if f.target else "") + f": {f.message}"
+ + (f" fix: {f.fix_hint}" if f.fix_hint else ""))
+ if len(warns) > max_warns:
+ lines.append(f"- … {len(warns) - max_warns} more warning(s) (artifacts/gates.json)")
+ return lines
+
+
+@tool("check", NoArgs, "Lint + build + measure + EVERY gate of the track (connectivity, contract, detail budget, fixed "
+ "parts, project checks; joint sweep + motion direction; scene placement + asset modules; frame gate), written to "
+ "artifacts/gates.json. PASS/FAIL with each ERROR and its fix. Run it after every edit; judge-pack needs it.",
+ cost_hint="slow")
+def check(ctx: ToolContext, args: NoArgs) -> Observation:
+ from codeverse3d.spatial.measure import measure_summary_table
+ from codeverse3d.spatial.observe import build_failure_lines, sanitize_text
+
+ ws = ctx.workspace
+ spec = _spec(ctx)
+ plan = _plan_or_none(ws, spec.track)
+ res = run_check(ws, spec, plan, round_index=ctx.round_index)
+ numbers: dict[str, Any] = {"ok": res.ok, "build_ok": res.build.ok, "duration_ms": res.build.duration_ms,
+ "errors": sum(len(g.errors) for g in res.gates),
+ "warnings": sum(1 for g in res.gates for f in g.findings if f.severity == Severity.WARN),
+ "gates": {g.gate: g.passed for g in res.gates}, "src_hash": res.src_hash}
+ if not res.build.ok:
+ lint = next((g for g in res.gates if g.gate.startswith("lint")), None)
+ if res.build.error_type == "LintError" and lint is not None:
+ lines = ["CHECK FAIL — lint errors (nothing was built):"]
+ lines += [f"- {f.as_line(with_target=True)}" for f in lint.errors]
+ else:
+ lines = ["CHECK FAIL — " + build_failure_lines(res.build, ws.root, [], tail_n=25)[0]]
+ lines += build_failure_lines(res.build, ws.root, [], tail_n=25)[1:]
+ lines += _gate_lines([g for g in res.gates if not g.gate.startswith("lint")])
+ return text_observation(lines, ok=False, numbers=numbers, limit=6000)
+ lines = [f"CHECK {'PASS' if res.ok else 'FAIL'} — build ok ({res.build.duration_ms} ms)"
+ + (f" → {rel_path(res.build.glb_path, ws.root)}" if res.build.glb_path else "")]
+ if plan is None and ws.plan_path.is_file():
+ lines.append("WARN: plan.json does not validate — the contract / budget gates did not run (3dcode validate-plan)")
+ elif plan is None:
+ lines.append("WARN: no plan.json — the contract / budget gates did not run")
+ lines += _gate_lines(res.gates)
+ if res.measurement is not None:
+ lines.append(measure_summary_table(res.measurement))
+ numbers.update({"extents_m": list(res.measurement.extents), "tri_count": res.measurement.tri_count,
+ "n_parts": len(res.measurement.parts), "ground_gap_m": res.measurement.ground_gap_m})
+ census_warn = res.build.census.get("warnings") if isinstance(res.build.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]))
+ lines.append(f"written: {rel_path(ws.gates_path, ws.root)}")
+ return text_observation(lines, ok=res.ok, numbers=numbers, limit=8000)
+
+
+# ===================================================================== judge_pack
+#: per-track montage ceilings under the ``Settings.judge.montages`` dial
+TRACK_MONTAGE_CAP: dict[str, int] = {"scene": 4, "graphics": 3}
+SLICE_LABELS = {
+ "front_back": "cross-section front-back · interior view",
+ "left_right": "cross-section left-right · interior view",
+}
+#: IoU → measured silhouette score: ≤ 0.25 → 0, ≥ 0.85 → 1, linear between
+IOU_LOW, IOU_HIGH = 0.25, 0.85
+#: score the measured criterion gets when the measurement cannot be trusted
+NEUTRAL_SCORE = 0.5
+LIKENESS_NOTE = (
+ "REAL-WORLD REFERENCE PHOTOS are attached (labelled REAL-WORLD REFERENCE n/N). They are not a "
+ "composition to copy; they are what the thing the brief names ACTUALLY looks like. Score "
+ "brief fidelity, colour/light and richness against them: dominant colour and where the "
+ "secondary colours sit, how the structure folds / layers / thins out, where the brightness "
+ "concentrates and how much of the frame stays dark, what the real texture is at fine scale. A "
+ "frame that ticks every noun in the brief but would never be mistaken for the photographed "
+ "thing (a row of evenly spaced bars standing in for curtains, a flat band standing in for a "
+ "gradient of light, cartoon-saturated colour where the photo is subtle) is a 0.4-0.5 on brief "
+ "fidelity, not a 1.0. Foreground, framing and landscape in the photos are incidental unless "
+ "the brief asks for them."
+)
+PACK_NAME = "pack.json"
+JUDGMENT_NAME = "judgment.json"
+SCORE_NAME = "score.json"
+
+
+def iou_to_score(iou: float) -> float:
+ return max(0.0, min(1.0, (float(iou) - IOU_LOW) / (IOU_HIGH - IOU_LOW)))
+
+
+def rubric_for(spec: Spec) -> str:
+ """The rubric a project is judged on: ``reference`` for a static object with reference images, else the track's."""
+ if spec.references and spec.track is Track.STATIC_OBJECT:
+ return pb.REFERENCE_RUBRIC
+ return TRACK_RUBRIC[spec.track]
+
+
+def _load_check(ws: Workspace) -> CheckResult:
+ raw = read_json_or_none(ws.gates_path)
+ if raw is None:
+ raise ToolUsageError("no artifacts/gates.json — run `3dcode check` first", "3dcode check")
+ res = CheckResult.model_validate(raw)
+ if res.src_hash != ws.src_hash():
+ raise ToolUsageError("src/ changed since the last `3dcode check` — run it again so the judge sees the code that built",
+ "3dcode check")
+ if not res.build.ok:
+ raise ToolUsageError("the last check did not build — nothing to judge; fix the build first", "3dcode check")
+ return res
+
+
+def _reference_material(spec: Spec, rubric, renders: RenderSet) -> tuple[list[tuple[str, Path]], str, dict[str, float]]:
+ """Reference photos, the measured-silhouette block and the measured scores (reference rubric), or the likeness
+ photos + note (scene / graphics with references)."""
+ refs = [r for r in spec.references if Path(r.path).is_file()]
+ if not refs:
+ return [], "", {}
+ measured_ids = [c.id for c in rubric.measured_criteria()]
+ if spec.track in (Track.SCENE, Track.GRAPHICS):
+ images = [(f"REAL-WORLD REFERENCE {i}/{min(len(refs), 3)} ({r.role})" + (f" — {r.note}" if r.note else ""), Path(r.path))
+ for i, r in enumerate(refs[:3], 1)]
+ return images, LIKENESS_NOTE, {}
+ images = [(f"REFERENCE {i}/{min(len(refs), 3)} ({r.role})" + (f" — {r.note}" if r.note else ""), Path(r.path))
+ for i, r in enumerate(refs[:3], 1)]
+ blocks: list[str] = []
+ targets = [r for r in refs if r.role == "target"] or refs
+ conflict = dimension_conflict(spec, targets[0].path)
+ if conflict.get("conflict"):
+ lo, hi = conflict.get("expected_range") or (0.0, 0.0)
+ blocks.append(f"REFERENCE PROPORTIONS DISAGREE WITH THE BRIEF: the picture's outline is {conflict['image_aspect']:.2f} "
+ f"wide/high, outside the {lo:.2f}-{hi:.2f} band the stated dimensions allow. The BRIEF's dimensions are "
+ "correct; use the reference for the part inventory and the shape of each part, NOT for the overall "
+ "proportions. The measured silhouette score is therefore neutral.")
+ scores: dict[str, float] = {}
+ if measured_ids:
+ match = measure_reference(renders.views, spec, compare=compare_silhouette, conflict=conflict)
+ if match is None:
+ score, why = NEUTRAL_SCORE, " (NEUTRAL: no render view could be compared)"
+ blocks.append(f"MEASURED SILHOUETTE: unavailable → silhouette_match score {score:.2f}{why}.")
+ else:
+ if match.conflict:
+ score, why = NEUTRAL_SCORE, " (NEUTRAL: the reference's proportions contradict the brief's dimensions)"
+ elif not match.reliable:
+ score, why = NEUTRAL_SCORE, " (NEUTRAL: the background mask was unreliable)"
+ else:
+ score, why = iou_to_score(match.iou), ""
+ extra = match.model_dump(exclude={"iou", "reference", "conflict", "per_view"}, exclude_none=True)
+ blocks.append(f"MEASURED SILHOUETTE: {match.view} render vs reference {Path(match.reference).name}: "
+ f"IoU {match.iou:.3f} → silhouette_match score {score:.2f}{why}. extra: {extra}")
+ scores = {cid: score for cid in measured_ids}
+ return images, "\n\n".join(blocks), scores
+
+
+def _slices(spec: Spec, check: CheckResult, gates: list[GateReport], out_dir: Path) -> list[tuple[str, Path]]:
+ """The slice channel: up to two interior cross-sections when the connectivity gate carries an ERROR."""
+ if get_settings().judge.slices != "on-error" or spec.track.value not in pb.SLICE_TRACKS or not check.build.glb_path:
+ return []
+ if not any(g.gate == "connectivity" and g.errors for g in gates):
+ return []
+ try:
+ from codeverse3d.spatial.sections import judge_slices
+
+ manifest = judge_slices(Path(check.build.glb_path), pb.connectivity_error_pairs(gates), out_dir)
+ except Exception as e: # noqa: BLE001 — the slice channel is optional (the 'mesh' extra)
+ log.warning("judge slices unavailable: %s", e)
+ return []
+ return [(SLICE_LABELS.get(s.name, s.name), out_dir / s.png) for s in manifest.slices if s.rendered]
+
+
+def _previous_verdict(ws: Workspace, round_index: int) -> Judgment | None:
+ for r in range(round_index - 1, -1, -1):
+ raw = read_json_or_none(ws.judge_dir(r) / SCORE_NAME)
+ if raw is not None:
+ try:
+ return Judgment.model_validate(raw)
+ except ValidationError:
+ return None
+ return None
+
+
+def _slug(label: str) -> str:
+ keep = "".join(c if c.isalnum() else "_" for c in label.split("—")[0].split("(")[0].strip().lower())
+ return keep.strip("_")[:40] or "image"
+
+
+@tool("judge_pack", NoArgs, "Render the track's judged views (14-view rig + clay + poses / authored cameras + rig / "
+ "judged frames), compose the montages and crops, and write judge/rNN/: brief.md (the case, the rubric as a "
+ "checklist, the EXACT JSON to return), the images and pack.json. A fresh-context judge reads ONLY that folder. "
+ "Requires a `check` of the current src/.", cost_hint="slow")
+def judge_pack(ctx: ToolContext, args: NoArgs) -> Observation:
+ ws = ctx.workspace
+ spec = _spec(ctx)
+ plan = _plan_or_none(ws, spec.track)
+ check = _load_check(ws)
+ settings = get_settings()
+ rubric_name = rubric_for(spec)
+ rubric = load_rubric(rubric_name)
+ out = ws.judge_dir(ctx.round_index)
+ if out.exists():
+ for p in out.iterdir():
+ if p.is_dir():
+ shutil.rmtree(p, ignore_errors=True)
+ elif p.name != JUDGMENT_NAME:
+ p.unlink()
+ out.mkdir(parents=True, exist_ok=True)
+ jr = render_for_judge(ws, spec, plan, check, round_index=ctx.round_index)
+ if not jr.renders.views:
+ errors = jr.renders.console_errors[:5]
+ return text_observation(["JUDGE PACK FAILED: the render produced no views"] + [f" ! {e[:300]}" for e in errors],
+ ok=False, failed=not errors, numbers={"console_errors": len(errors)})
+ gates = list(check.gates) + list(jr.post_gates or [])
+ is_scene = spec.track is Track.SCENE
+ cap = TRACK_MONTAGE_CAP.get(spec.track.value, settings.judge.montages)
+ images, montages = pb.montage_images(
+ jr.renders, geometry_views=jr.geometry, scene=is_scene, max_montages=min(settings.judge.montages, cap),
+ detail_crops=settings.judge.detail_crops, max_px=settings.judge.max_px, gates=gates if is_scene else ())
+ ref_images, ref_text, measured = _reference_material(spec, rubric, jr.renders)
+ slices = _slices(spec, check, gates, out / "slices")
+ # the pack is self-contained: every image the brief names lives in judge/rNN/
+ def _copy(items: list[tuple[str, Path]], prefix: str) -> list[tuple[str, Path]]:
+ copied = []
+ for i, (lbl, src) in enumerate(items, 1):
+ dst = out / f"{prefix}_{i:02d}_{_slug(lbl)}.png"
+ shutil.copyfile(src, dst)
+ copied.append((lbl, dst))
+ return copied
+
+ ref_images, images, slices = _copy(ref_images, "ref"), _copy(images, "img"), _copy(slices, "slice")
+ judgment_path = out / JUDGMENT_NAME
+ brief = pb.build_brief(spec=spec, plan=plan, rubric=rubric, renders=jr.renders, measurement=check.measurement,
+ gates=gates, round_index=ctx.round_index, previous=_previous_verdict(ws, ctx.round_index),
+ extra_context=jr.extra_context, extra_text=ref_text, geometry_views=jr.geometry,
+ images=images, montages=montages, extra_images=ref_images, slice_images=slices,
+ judgment_path=judgment_path)
+ (out / "brief.md").write_text(brief)
+ acceptance_ids = [a.id for a in (getattr(plan, "acceptance", None) or [])]
+ pack = {"round": ctx.round_index, "rubric": rubric_name, "src_hash": check.src_hash,
+ "renders": jr.renders.model_dump(mode="json"), "gates": [g.model_dump(mode="json") for g in gates],
+ "acceptance_ids": acceptance_ids, "measured_scores": measured,
+ "images": [{"label": lbl, "path": str(p)} for lbl, p in [*ref_images, *images, *slices]],
+ "judgment_path": str(judgment_path)}
+ ws.write_json(out / PACK_NAME, pack)
+ all_images = [str(p) for _, p in [*ref_images, *images, *slices]]
+ lines = [f"JUDGE PACK READY: {out}",
+ f"rubric {rubric_name}; {len(jr.renders.views)} judged view(s); {len(images)} montage/crop image(s)"
+ + (f", {len(ref_images)} reference photo(s)" if ref_images else "") + (f", {len(slices)} slice(s)" if slices else ""),
+ f"a fresh-context judge reads ONLY {out / 'brief.md'} and opens the images it lists, then writes {judgment_path}",
+ f"then run: 3dcode score --round {ctx.round_index}"]
+ n_err = sum(len(g.errors) for g in gates)
+ if n_err:
+ lines.append(f"note: {n_err} gate ERROR(s) go into the brief as facts and will cap the score")
+ return text_observation(lines, numbers={"dir": str(out), "brief": str(out / "brief.md"), "judgment_path": str(judgment_path),
+ "n_views": len(jr.renders.views), "n_images": len(all_images), "rubric": rubric_name},
+ images=all_images, limit=4000)
+
+
+# ===================================================================== score
+@tool("score", NoArgs, "Read judge/rNN/judgment.json (the judge's JSON), parse it strictly, apply the rubric's weights, "
+ "defect penalties, floors and gate caps, write judge/rNN/score.json. Prints overall, PASS/FAIL, the caps and the "
+ "improvement list for the next round (gate ERRORs first).")
+def score(ctx: ToolContext, args: NoArgs) -> Observation:
+ ws = ctx.workspace
+ spec = _spec(ctx)
+ plan = _plan_or_none(ws, spec.track)
+ out = ws.judge_dir(ctx.round_index)
+ pack = read_json_or_none(out / PACK_NAME)
+ if pack is None:
+ raise ToolUsageError(f"no {out / PACK_NAME} — run `3dcode judge-pack --round {ctx.round_index}` first")
+ jpath = out / JUDGMENT_NAME
+ if not jpath.is_file():
+ raise ToolUsageError(f"{jpath} does not exist — the judge has to write it first (see brief.md)")
+ rubric = load_rubric(str(pack["rubric"]))
+ acceptance_ids = [str(a) for a in pack.get("acceptance_ids") or []]
+ try:
+ payload = parse_json_lenient(jpath.read_text(errors="replace"))
+ parsed = parse_judge_output(payload, rubric, acceptance_ids, measured_scores=dict(pack.get("measured_scores") or {}))
+ except (JsonParseError, JudgeParseError) as e:
+ return Observation.error(f"judgment.json is not a complete verdict: {e}\n"
+ f"The judge must write ONE JSON object matching the schema at the end of {out / 'brief.md'}.")
+ gates = [GateReport.model_validate(g) for g in pack.get("gates") or []]
+ renders = RenderSet.model_validate(pack.get("renders") or {})
+ items = list(getattr(plan, "acceptance", None) or [])
+ judgment = aggregate_samples(rubric, [parsed], gates=gates, acceptance_items=items,
+ console_errors=renders.console_errors, views=renders.views, judge_backend="host")
+ ws.write_json(out / SCORE_NAME, judgment)
+ breakdown = json.loads(judgment.raw)
+ lines = [f"SCORE {judgment.overall:.2f} → {'PASS' if judgment.passed else 'FAIL'} (threshold {rubric.pass_threshold:.2f}; "
+ f"uncapped {breakdown.get('overall_uncapped', 0):.2f}, defects -{breakdown.get('defect_penalty', 0):.2f})"]
+ lines.append("criteria: " + ", ".join(f"{k} {v:.2f}" for k, v in judgment.scores.items()))
+ present = [d for d, on in (breakdown.get("defects") or {}).items() if on]
+ if present:
+ lines.append("defects present: " + ", ".join(present))
+ if breakdown.get("overridden"):
+ lines.append("checklist claims a passed gate contradicted (no penalty): " + ", ".join(breakdown["overridden"]))
+ caps = (breakdown.get("caps") or {}).get("caps_applied") or []
+ if caps:
+ lines.append("caps: " + "; ".join(f"{c['rule']}≤{c['cap']:.2f} ({c['evidence'][:120]})" for c in caps))
+ missing = [a.id for a in items if a.priority == "must" and not judgment.acceptance_results.get(a.id, False)]
+ if missing:
+ lines.append("must items unverified: " + ", ".join(missing))
+ if judgment.summary:
+ lines.append("summary: " + judgment.summary.split(" [verdict:")[0][:600])
+ improve: list[str] = []
+ for g in gates:
+ for f in g.errors:
+ improve.append(f"[{g.gate}" + (f"/{f.target}" if f.target else "") + f"] {f.message}" + (f" — fix: {f.fix_hint}" if f.fix_hint else ""))
+ for it in judgment.improvement_plan:
+ improve.append(f"[{it.target}/{it.kind}, p{it.priority}] {it.instruction}")
+ for a in items:
+ if a.id in missing:
+ improve.append(f"[acceptance {a.id}] not verified: {a.text}")
+ if improve:
+ lines.append("IMPROVE NEXT (gate errors first):")
+ lines += [f"{i}. {t}" for i, t in enumerate(improve[:12], 1)]
+ lines.append(f"written: {rel_path(out / SCORE_NAME, ws.root)}")
+ return text_observation(lines, ok=judgment.passed,
+ numbers={"overall": judgment.overall, "passed": judgment.passed, "scores": judgment.scores,
+ "defects": present, "caps": [c["rule"] for c in caps], "must_missing": missing,
+ "n_improvements": len(improve)}, limit=8000)
diff --git a/harness/codeverse3d/workspace.py b/harness/codeverse3d/workspace.py
index d89f6bed..a89de638 100644
--- a/harness/codeverse3d/workspace.py
+++ b/harness/codeverse3d/workspace.py
@@ -1,118 +1,35 @@
-"""Run workspace: fixed directory layout + git snapshots of ``src/``.
+"""Project workspace: the fixed directory layout every instrument reads and writes.
-A workspace is a directory under ``runs/<slug>/``; ``src/`` (and ``public/``) is a git
-repository so every round is a commit (diffs, rollback, "files changed by the agent").
+A workspace is a directory holding ``spec.json``, ``plan.json``, ``src/`` (+ ``public/``: the agent's raw
+code), ``artifacts/`` (build outputs, renders, gates) and ``judge/rNN/`` (brief, montages, judgment, score).
"""
from __future__ import annotations
import contextlib
+import hashlib
import json
import os
import shutil
-import subprocess
-import threading
-import time
from collections.abc import Sequence
from pathlib import Path
from typing import Any
from pydantic import BaseModel
-from codeverse3d.contracts.agent import FileChange
from codeverse3d.proc import write_json_atomic
-#: top-level buckets of a run directory
-DELIVERABLE_DIR = "deliverable" # (a) what the user asked for
-TELEMETRY_DIR = "telemetry" # (c) what it cost and how it was configured
-#: harness-owned read-only files inside the workspace
-C3D_DIR = ".3dcode"
-
-#: directories every run owns
-LAYOUT_DIRS = ("src", "public", "artifacts", "artifacts/renders", "artifacts/gates", "artifacts/judge",
- "trajectories", DELIVERABLE_DIR, TELEMETRY_DIR)
-
-#: harness-owned paths that never belong in the code snapshot
-_GITIGNORE_LINES = (
- "# harness-owned run state is never part of the code snapshot",
- "artifacts/", "trajectories/", "stages/", "rounds/", "_assets/", "_cand/", ".3dcode/", ".gemini/", ".claude/", ".agents/",
- "deliverable/", "telemetry/", "captions.json",
- "events.jsonl", "run_state.json", "record.json", "*.log", "node_modules/", "*.tmp", "__pycache__/",
-)
-
-
-#: prepended to every git argv run against a run workspace: an agent-planted hook, fsmonitor or
-#: global attributes file never runs. ``-c`` outranks ``.git/config``. ``diff.external`` is
-#: deliberately not set here: an empty value makes git try to execute it.
-GIT_SAFE_FLAGS = ("-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false",
- "-c", "core.attributesFile=/dev/null")
-#: added to every git command that renders file content: a named diff / textconv driver in the
-#: agent-writable .git/config is not reachable by ``-c`` and would execute without these.
-GIT_SAFE_DIFF_FLAGS = ("--no-ext-diff", "--no-textconv")
-#: a has_commit probe that has not answered by then answers no
-HAS_COMMIT_TIMEOUT_S = 60
-#: local (.git/config) keys that make git EXECUTE a program; unset in place before every commit.
-_GIT_EXEC_SECTIONS = ("filter", "diff", "alias", "gpg", "credential")
-_GIT_EXEC_KEYS = ("core.hookspath", "core.fsmonitor", "core.sshcommand", "core.pager", "commit.gpgsign")
-
-
-def _git_home() -> str:
- """HOME for workspace git: harness-owned, never the workspace. The cache_dir default, spelled
- out because this module may not import config."""
- d = Path.home() / ".cache" / "codeverse3d" / "githome"
- with contextlib.suppress(OSError): # a missing HOME is harmless; an unwritable one must not sink git
- d.mkdir(parents=True, exist_ok=True)
- return str(d)
-
-
-def git_safe_env(**extra: str) -> dict[str, str]:
- """Environment for git in an agent-writable repository: no system / global config, fixed PATH,
- no credential prompt. ``extra`` adds identity."""
- return {"PATH": "/usr/bin:/bin:/usr/local/bin", "HOME": _git_home(),
- "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_NOSYSTEM": "1",
- "GIT_TERMINAL_PROMPT": "0", **extra}
-
-
-class WorkspaceGitError(subprocess.CalledProcessError):
- """A failed git command that keeps git's own stderr in its message."""
-
- def __init__(self, root: Path, args: tuple[str, ...], returncode: int, stderr: str):
- super().__init__(returncode, ["git", *args], None, stderr)
- self.root = root
- self._detail = (stderr or "").strip()[-800:]
-
- def __str__(self) -> str:
- msg = f"git {' '.join(self.cmd[1:])} failed in {self.root} (exit {self.returncode})"
- if self._detail:
- msg += f": {self._detail}"
- if "index.lock" in (self.stderr or ""):
- msg += (f"\n a stale lock is left behind when a run is killed mid-commit; "
- f"if no other git is running here, remove it: rm {self.root / '.git' / 'index.lock'}")
- return msg
+#: directories every workspace owns
+LAYOUT_DIRS = ("src", "public", "artifacts", "artifacts/renders", "artifacts/gates", "judge")
+#: the agent's code: what ``src_hash`` fingerprints (``public/`` carries compiled assets)
+CODE_ROOTS = ("src", "public")
class Workspace:
def __init__(self, root: Path | str):
self.root = Path(root).resolve()
- self._cfg_mtime: int = -1 # .git/config mtime at the last _sanitise_git_config
# ----------------------------------------------------------------- paths
- def rebase(self, stored: str | Path) -> Path:
- """A stored (possibly foreign absolute) path resolved against THIS workspace.
-
- Relative paths join the root; an absolute path outside it is re-rooted by its longest
- trailing segment that exists here, else returned as-is."""
- p = Path(stored)
- if not p.is_absolute():
- return self.root / p
- if not p.is_relative_to(self.root):
- parts = p.parts
- for i in range(1, len(parts)):
- candidate = self.root.joinpath(*parts[i:])
- if candidate.exists():
- return candidate
- return p
-
@property
def src(self) -> Path:
return self.root / "src"
@@ -126,24 +43,17 @@ class Workspace:
return self.root / "artifacts"
@property
- def trajectories(self) -> Path:
- return self.root / "trajectories"
-
- @property
- def deliverable(self) -> Path:
- return self.root / DELIVERABLE_DIR
-
- @property
- def telemetry(self) -> Path:
- return self.root / TELEMETRY_DIR
+ def spec_path(self) -> Path:
+ return self.root / "spec.json"
@property
- def deliverable_manifest_path(self) -> Path:
- return self.deliverable / "manifest.json"
+ def plan_path(self) -> Path:
+ return self.root / "plan.json"
@property
- def stages(self) -> Path:
- return self.root / "stages"
+ def gates_path(self) -> Path:
+ """``artifacts/gates.json``: what the last ``check`` found (build, measurement, every gate)."""
+ return self.artifacts / "gates.json"
def renders_dir(self, round_index: int) -> Path:
return self.artifacts / "renders" / f"r{round_index:02d}"
@@ -151,43 +61,10 @@ class Workspace:
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 round_artifacts(self, round_index: int) -> Path:
- return self.artifacts / f"r{round_index:02d}"
-
- 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"
+ def judge_dir(self, round_index: int) -> Path:
+ return self.root / "judge" / f"r{round_index:02d}"
# ----------------------------------------------------------------- lifecycle
- def create(self) -> Workspace:
- self.ensure_layout()
- self._git_init()
- return self
-
def ensure_layout(self) -> None:
for d in LAYOUT_DIRS:
(self.root / d).mkdir(parents=True, exist_ok=True)
@@ -195,128 +72,32 @@ class Workspace:
def exists(self) -> bool:
return self.spec_path.is_file()
+ def src_hash(self) -> str:
+ """Content hash of the agent's code (``src/`` + ``public/``): the state a ``check`` verdict belongs to."""
+ h = hashlib.sha256()
+ for root in CODE_ROOTS:
+ base = self.root / root
+ if not base.is_dir():
+ continue
+ for p in sorted(x for x in base.rglob("*") if x.is_file() and "node_modules" not in x.parts
+ and "__pycache__" not in x.parts):
+ h.update(p.relative_to(self.root).as_posix().encode())
+ h.update(p.read_bytes())
+ return h.hexdigest()[:16]
+
# ----------------------------------------------------------------- json io
def write_json(self, path: Path, model: BaseModel | dict[str, Any]) -> None:
data = model.model_dump(mode="json") if isinstance(model, BaseModel) else model
write_json_atomic(path, data)
+ def read_json(self, path: Path) -> dict[str, Any]:
+ return json.loads(path.read_text())
+
# ----------------------------------------------------------------- artifact staging
def stage_artifacts(self, *names: str) -> ArtifactStage:
"""An :class:`ArtifactStage` over canonical ``artifacts/`` names (context manager, or a bare ``.invalidate()``)."""
return ArtifactStage(self, names)
- def read_json(self, path: Path) -> dict[str, Any]:
- return json.loads(path.read_text())
-
- # ----------------------------------------------------------------- git
- _LOCKS: dict[str, threading.RLock] = {}
- _LOCKS_GUARD = threading.Lock()
-
- @property
- def _lock(self) -> threading.RLock:
- key = str(self.root)
- with Workspace._LOCKS_GUARD:
- return Workspace._LOCKS.setdefault(key, threading.RLock())
-
- def _git(self, *args: str, check: bool = True, timeout: float | None = None) -> subprocess.CompletedProcess[str]:
- with self._lock:
- for attempt in range(4):
- proc = subprocess.run(
- ["git", *GIT_SAFE_FLAGS, *args], cwd=self.root, text=True, capture_output=True, check=False,
- timeout=timeout,
- env=git_safe_env(GIT_AUTHOR_NAME="3dcode", GIT_AUTHOR_EMAIL="3dcode@local",
- GIT_COMMITTER_NAME="3dcode", GIT_COMMITTER_EMAIL="3dcode@local"),
- )
- 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 WorkspaceGitError(self.root, args, proc.returncode, proc.stderr or "")
- return proc
-
- def _sanitise_git_config(self) -> None:
- cfg = self.root / ".git" / "config"
- mtime = cfg.stat().st_mtime_ns if cfg.is_file() else 0
- if mtime == self._cfg_mtime:
- return
- names = self._git("config", "--local", "--list", "--name-only", check=False).stdout.split()
- for name in {n for n in names if n.split(".", 1)[0] in _GIT_EXEC_SECTIONS or n in _GIT_EXEC_KEYS}:
- self._git("config", "--local", "--unset-all", name, check=False)
- self._cfg_mtime = cfg.stat().st_mtime_ns if cfg.is_file() else 0
-
- def _git_init(self) -> None:
- with self._lock: # init + config + first commit are one unit
- if (self.root / ".git").exists():
- self._sanitise_git_config() # a resumed run: the agent has had the repo since
- return
- self._git("init", "-q")
- self.ensure_gitignore()
- self._git("add", "-A")
- self._git("commit", "-q", "-m", "init", "--allow-empty")
-
- def ensure_gitignore(self) -> bool:
- path = self.root / ".gitignore"
- existing = path.read_text().splitlines() if path.is_file() else []
- have = {line.strip() for line in existing}
- missing = [line for line in _GITIGNORE_LINES if line not in have]
- if not missing:
- return False
- lines = existing + ([""] if existing and existing[-1].strip() else []) + missing
- path.write_text("\n".join(lines).rstrip("\n") + "\n")
- return True
-
- def commit(self, message: str) -> str:
- with self._lock:
- self._sanitise_git_config()
- 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 has_commit(self, commit: str) -> bool:
- if not commit:
- return False
- try:
- return self._git("cat-file", "-e", f"{commit}^{{commit}}", check=False,
- timeout=HAS_COMMIT_TIMEOUT_S).returncode == 0
- except (OSError, subprocess.TimeoutExpired):
- return False
-
- def changed_files(self, since: str | None = None) -> list[FileChange]:
- with self._lock: # add -N + the diff are one unit: a sibling commit between them mislabels a status
- self._sanitise_git_config() # `add` applies clean filters; -c cannot unset a local one
- self._git("add", "-A", "-N") # register untracked so they show up in diff
- out = self._git("diff", *GIT_SAFE_DIFF_FLAGS, "--name-status", "--no-renames", "--diff-filter=ADM",
- since or "HEAD").stdout
- changes = []
- for line in out.splitlines():
- st, sep, path = line.partition("\t")
- if sep:
- changes.append(FileChange(path=path, status={"A": "added", "D": "deleted"}.get(st[0], "modified")))
- return changes
-
- def restore(self, commit: str) -> None:
- with self._lock: # rm + rmtree + checkout + add: a sibling must never see the half-removed tree
- tracked = self._git("ls-tree", "--name-only", commit).stdout.split()
- roots = [r for r in ("src", "public") if r in tracked]
- # 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 restore_paths(self, commit: str, paths: Sequence[str]) -> None:
- if not paths:
- return
- self._git("checkout", "-q", commit, "--", *paths)
-
class ArtifactStage:
"""Stage-then-promote lifecycle for a fixed set of canonical ``artifacts/`` names.
diff --git a/harness/pyproject.toml b/harness/pyproject.toml
index b006e21d..a5cb5421 100644
--- a/harness/pyproject.toml
+++ b/harness/pyproject.toml
@@ -4,13 +4,10 @@ build-backend = "setuptools.build_meta"
[project]
name = "3dcodeverse"
-version = "0.0.1"
-description = "3dcodeverse: a data-flywheel harness for LLM-written 3D code (Blender / CadQuery / Three.js / URDF / GLSL) across static objects, articulated objects and scenes."
+version = "0.1.0"
+description = "3dcodeverse: deterministic instruments (build, measure, render, gate, judge brief, score) for a coding agent writing raw 3D code (Blender / CadQuery / Three.js / URDF / GLSL) — the `3dcode` command line of the 3dcodeverse plugin."
readme = "README.md"
-# One fixed version: 3.13 (owner's decision 2026-08-26 — no floor, no matrix; the
-# one fixed version, 3.13 (owner, 2026-08-26): developed and measured on it; no CI (tests run locally before a push).
-# Nothing in the package uses a 3.11+ stdlib name directly — the three that were used
-# old codeverse3d/_compat.py shims are gone: StrEnum, datetime.UTC, tomllib are stdlib here).
+# One fixed version: 3.13 (owner's decision 2026-08-26 — no floor, no matrix).
requires-python = ">=3.13"
license = { text = "Apache-2.0" }
classifiers = [
@@ -22,67 +19,39 @@ classifiers = [
dependencies = [
"pydantic>=2.12", # Field(exclude_if=...)
"pydantic-settings>=2.3",
- "typer>=0.12",
- "click>=8.1", # imported directly by cli/cost_cmd.py (typer re-exports it, but we use it by name)
- "rich>=13",
- "jinja2>=3.1",
"pyyaml>=6",
"numpy>=1.26",
"trimesh>=4.4",
"python-fcl>=0.7",
"pillow>=10",
- "google-genai>=1.0",
- "anthropic>=0.40",
- "openai>=1.40",
]
[project.optional-dependencies]
-# What each extra unlocks is documented in docs/INSTALL.md §4.
+# What each extra unlocks is documented in docs/INSTALL.md.
cad = ["cadquery>=2.4"] # language `cadquery`
urdf = ["yourdfpy>=0.0.56", "scipy>=1.11"] # track `articulated_object` (urdf_blender)
graphics = ["moderngl>=5.8"] # track `graphics` (glsl_shader / opengl_python)
-mesh = ["shapely>=2.0", "networkx>=3.2", "matplotlib>=3.8"] # cross_section area, mesh split, judge slices (D48)
-mcp = ["mcp>=1.0"] # `3dcodeverse mcp` spatial-tool server for the agentic CLIs
-flywheel = ["pyarrow>=15"] # `3dcodeverse flywheel export --pack` (parquet)
-all = ["3dcodeverse[cad,urdf,graphics,mesh,mcp,flywheel]"]
-dev = ["pytest>=8", "pytest-timeout>=2.3", "pytest-xdist>=3.6", "ruff>=0.5", "pyarrow>=15"]
+mesh = ["shapely>=2.0", "networkx>=3.2", "matplotlib>=3.8"] # cross_section area, mesh split, judge slices
+all = ["3dcodeverse[cad,urdf,graphics,mesh]"]
+dev = ["ruff>=0.5"]
[project.scripts]
-3dcodeverse = "codeverse3d.cli.main:app"
+3dcode = "codeverse3d.cli:main"
[tool.setuptools.packages.find]
include = ["codeverse3d*"]
[tool.setuptools.package-data]
-# Runtime data, including starter trees and skill bundles. tests/core/test_portability.py
-# checks that every data file matches a glob and every glob matches an existing file.
-codeverse3d = ["prompts/**/*", "judges/rubrics/*.yaml", "languages/**/wrappers/*",
- "languages/**/starter/**/*", "skills/**/*"]
+# Runtime data: the rubrics, the language wrappers and the scene_threejs effect library.
+codeverse3d = ["judges/rubrics/*.yaml", "languages/**/wrappers/*", "languages/**/starter/**/*", "spatial/*.json"]
[tool.setuptools.exclude-package-data]
codeverse3d = ["**/__pycache__/*"] # a wheel must not carry the build host's bytecode
[tool.ruff]
line-length = 100
-target-version = "py313" # == requires-python: one fixed version (owner, 2026-08-26)
+target-version = "py313" # == requires-python: one fixed version
[tool.ruff.lint]
select = ["E", "W", "F", "I", "B", "UP", "SIM"]
ignore = ["E501"]
-
-[tool.pytest.ini_options]
-testpaths = ["tests"]
-timeout = 600
-# Live tests are OPT-IN (`pytest -m live`). Without this, a bare `pytest` on a machine
-# that happens to have API keys configured fires real requests, and during a provider
-# outage it hangs instead of failing — which is exactly what happened on 2026-08-24.
-# Everyone's default run is the offline suite (run locally before every push; there is no CI).
-# xdist distributes test items with work stealing. Tests isolate mutable state with tmp_path;
-# nested pytest invocations must use -n0 to avoid launching another worker pool.
-addopts = ["-m", "not live", "-n", "auto", "--dist", "worksteal"]
-markers = [
- "live: needs network + API keys (deselect with -m 'not live')",
- "blender: needs a Blender binary",
- "node: needs node + runtime_js deps",
- "slow: builds or validates a distributable artifact (deselect with -m 'not slow')",
-]
diff --git a/harness/setup.sh b/harness/setup.sh
index ede0fe8b..5d8320ff 100755
--- a/harness/setup.sh
+++ b/harness/setup.sh
@@ -1,14 +1,11 @@
#!/usr/bin/env bash
-# 3dcodeverse harness — idempotent installer / updater.
+# 3dcodeverse plugin — idempotent installer / updater of the `3dcode` instruments.
#
# bash harness/setup.sh [options]
#
# Does, in order: version checks (python 3.13, node >= 20.6) -> `pip install -e
-# harness[<extras>]` -> `npm ci` in runtime_js *only when the lockfile moved* ->
-# puppeteer chrome download (no-op when cached) -> the coding-agent CLIs at their
-# latest release (`agy update`, or the installer when there is no agy; claude + codex via
-# `npm i -g` whenever the installed npm version differs from the registry's `latest`) ->
-# `3dcodeverse doctor`.
+# harness[<extras>]` (console script `3dcode`) -> `npm ci` in runtime_js *only when the
+# lockfile moved* -> puppeteer chrome download (no-op when cached) -> `3dcode doctor`.
# Re-running is safe: every step is a no-op when it is already satisfied.
# Full guide: docs/INSTALL.md
set -euo pipefail
@@ -24,11 +21,10 @@ HARNESS="$HERE"
RUNTIME_JS="$HARNESS/runtime_js"
PY="${PYTHON:-python3}"
-EXTRAS="all,dev"
+EXTRAS="all"
DO_PYTHON=1
DO_NODE=1
DO_CHROME=1
-DO_CLIS=1
DO_DOCTOR=1
FORCE_NPM=0
DOCTOR_ARGS=()
@@ -37,14 +33,12 @@ usage() {
cat <<'USAGE'
usage: setup.sh [options]
- --extras LIST pip extras to install (default: all,dev; "" = none)
+ --extras LIST pip extras to install (default: all; "" = none)
--python BIN python interpreter to install into (default: $PYTHON or python3)
--no-python skip the pip install step
--no-node skip `npm ci` in runtime_js
--no-chrome skip the puppeteer chrome download
- --no-clis skip the coding-agent CLIs: agy update (or Google's installer: ~/.local/bin/agy
- + a PATH line in your shell profile), claude + codex via `npm i -g`
- --no-doctor skip the final `3dcodeverse doctor`
+ --no-doctor skip the final `3dcode doctor`
--force-npm run `npm ci` even when node_modules looks up to date
(WARNING: npm ci deletes node_modules first — do not use
while renders/benches are running against this tree)
@@ -62,7 +56,6 @@ while [ $# -gt 0 ]; do
--no-python) DO_PYTHON=0; shift ;;
--no-node) DO_NODE=0; shift ;;
--no-chrome) DO_CHROME=0; shift ;;
- --no-clis) DO_CLIS=0; shift ;;
--no-doctor) DO_DOCTOR=0; shift ;;
--force-npm) FORCE_NPM=1; shift ;;
--no-gpu) DOCTOR_ARGS+=(--no-gpu); shift ;;
@@ -169,77 +162,16 @@ else
step "runtime_js (skipped: no usable node, or --no-node)"
fi
-# ------------------------------------------------------------- coding-agent CLIs
-# The generators are vendor CLIs (docs/INSTALL.md §8.2): agy is the default generator's
-# (D103), claude and codex are optional. Each is brought to its vendor's latest release on
-# every run — agy by its own updater (its installer when there is no binary at all), the two
-# npm globals whenever the installed version differs from the registry's `latest`. A claude
-# or codex that is on PATH but not an npm global (a native installer, Homebrew) is left to
-# its own updater. Nothing pins a version; the closing doctor prints the three it found.
-AGY_INSTALLER="https://antigravity.google/cli/install.sh"
-if [ "$DO_CLIS" -eq 1 ]; then
- step "coding-agent CLIs at their latest (agy, claude, codex)"
- AGY="$(command -v agy 2>/dev/null || true)"
- if [ -z "$AGY" ] && [ -x "${HOME:-}/.local/bin/agy" ]; then # installed; this shell has not re-read its profile
- AGY="${HOME:-}/.local/bin/agy"
- export PATH="${HOME:-}/.local/bin:$PATH"
- info "agy is at $AGY but not on this shell's PATH — open a new shell after this"
- fi
- if [ -n "$AGY" ]; then
- "$AGY" update || info "agy update failed (offline?) — keeping $("$AGY" --version 2>/dev/null || echo '?')"
- elif command -v curl >/dev/null 2>&1; then
- info "agy not found — running the Antigravity installer ($AGY_INSTALLER -> ~/.local/bin/agy + a PATH line in your shell profile)"
- if curl -fsSL "$AGY_INSTALLER" | bash; then
- export PATH="${HOME:-}/.local/bin:$PATH" # for the closing doctor
- else
- info "agy install failed — install it by hand (docs/INSTALL.md §8.2)"
- fi
- else
- info "agy not found and no curl — install it by hand (docs/INSTALL.md §8.2)"
- fi
- if command -v npm >/dev/null 2>&1; then
- for pkg in @anthropic-ai/claude-code @openai/codex; do
- bin="${pkg##*/}"; bin="${bin%-code}" # the binaries: claude, codex
- # `npm ls` prints `<path>:<name>@<version>[:<realpath>]`; keep the version field only
- # (`--no-json`: a `json=true` in the user's npm config would turn both listings into JSON)
- have="$(npm ls -g --depth=0 --long --parseable --no-json 2>/dev/null | sed -n "s|^[^:]*:$pkg@\([^:]*\).*$|\1|p" | head -n1 || true)"
- if [ -z "$have" ] && command -v "$bin" >/dev/null 2>&1; then
- info "$pkg $(command -v "$bin") is not an npm install — left to its own updater"
- continue
- fi
- latest="$(npm view "$pkg" version --no-json --fetch-retries=0 2>/dev/null || true)"
- if [ -z "$latest" ]; then
- info "$pkg ${have:-not installed} (npm registry unreachable — left as is)"
- elif [ "$have" = "$latest" ]; then
- info "$pkg $have (latest)"
- else
- info "$pkg ${have:-not installed} -> $latest"
- npm install -g "$pkg@$latest" || info "$pkg install failed — install it by hand (docs/INSTALL.md §8.2)"
- fi
- done
- else
- info "npm not found — claude and codex not installed (optional generators)"
- fi
-else
- step "coding-agent CLIs (skipped: --no-clis)"
-fi
-
# ----------------------------------------------------------------------- doctor
if [ "$DO_DOCTOR" -eq 1 ]; then
- step "3dcodeverse doctor"
- # Verify what we just INSTALLED, not whatever happens to be first on PATH. With
- # --python (the documented way to install into a non-activated interpreter) the venv's
- # own entry point is not on PATH, so the old `command -v 3dcodeverse` branch ran a
- # pre-existing install and printed an all-green table for an environment this script
- # never touched — the closing doctor is the installer's only verification.
+ step "3dcode doctor"
+ # Verify what we just INSTALLED, not whatever happens to be first on PATH: with --python the
+ # venv's entry point is not on PATH, so the doctor runs through the interpreter we installed into.
if "$PY" -c 'import codeverse3d' >/dev/null 2>&1; then
- "$PY" -m codeverse3d.cli.main doctor ${DOCTOR_ARGS[@]+"${DOCTOR_ARGS[@]}"} || true
- elif command -v 3dcodeverse >/dev/null 2>&1; then
- info "codeverse3d not importable by $PY — falling back to the 3dcodeverse on PATH"
- 3dcodeverse doctor ${DOCTOR_ARGS[@]+"${DOCTOR_ARGS[@]}"} || true
+ "$PY" -m codeverse3d.cli doctor ${DOCTOR_ARGS[@]+"${DOCTOR_ARGS[@]}"} || true
else
- info "codeverse3d not importable by $PY and 3dcodeverse not on PATH — skipping doctor"
+ info "codeverse3d not importable by $PY — skipping doctor (run: $HARNESS/bin/3dcode doctor)"
fi
fi
-printf '\n\033[1mdone.\033[0m Next: docs/INSTALL.md §10 (5-minute smoke).\n'
+printf '\n\033[1mdone.\033[0m Next: docs/INSTALL.md (install the plugin into your coding agent).\n'