Skip to content

Official Codebase of 3DCodeVerse

Python

harness: render-stack dedupe (one backdrop classifier / renderer factory / camera fit / sampling grid / sheet+gif writer / lazy-tool boundary), docs/INSTALL.md + scripts/setup.sh, docs/architecture.html (maintained, drift-guarded); compare_v1 full matrix: harness+flash 0.685 vs one-shot flash 0.162 (8/8 wins); 1157 tests

gaoypeng1c87141a9f7b
diff --git a/harness/bench/cost_report.py b/harness/bench/cost_report.py
new file mode 100644
index 00000000..12c9fabf
--- /dev/null
+++ b/harness/bench/cost_report.py
@@ -0,0 +1,51 @@
+"""Battery cost report: ``python bench/cost_report.py bench/out/<battery> [...]``.
+
+Writes ``cost_report.md`` next to the battery (or ``--out``) and prints the
+summary. Same audit as ``3dcv cost``; this entry point exists so a battery can
+be costed from a script without the CLI, and so the report lands beside
+``report.md`` / ``report.html``.
+
+ python bench/cost_report.py bench/out/static_v1_flash
+ python bench/cost_report.py runs bench/out/*_flash --out bench/out/cost_all.md --recheck
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+
+from codeverse.cost import audit_runs
+from codeverse.cost.report import console as text_report
+from codeverse.cost.report import markdown, runs_table
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description="Cost report for one or more run trees.")
+ ap.add_argument("paths", nargs="+", type=Path, help="run dirs or trees (bench/out/<battery>, runs/)")
+ ap.add_argument("--out", type=Path, default=None,
+ help="markdown output (default: <first path>/cost_report.md)")
+ ap.add_argument("--recheck", action="store_true",
+ help="re-price every call with today's table instead of what was billed")
+ ap.add_argument("--title", default="", help="report title")
+ ap.add_argument("--quiet", action="store_true")
+ args = ap.parse_args(argv)
+
+ audit = audit_runs(args.paths, recheck=args.recheck)
+ if not audit.runs:
+ print(f"no runs found under {', '.join(str(p) for p in args.paths)}", file=sys.stderr)
+ return 2
+ title = args.title or f"Cost report — {', '.join(p.name for p in args.paths)}"
+ out = args.out or (args.paths[0] / "cost_report.md" if args.paths[0].is_dir() else Path("cost_report.md"))
+ out.parent.mkdir(parents=True, exist_ok=True)
+ out.write_text(markdown(audit, title=title))
+ if not args.quiet:
+ print(text_report(audit))
+ print()
+ print(runs_table(audit, limit=15))
+ print(f"\nwrote {out}")
+ return 0
+
+
+if __name__ == "__main__": # pragma: no cover
+ raise SystemExit(main())
diff --git a/harness/codeverse/cli/cost_cmd.py b/harness/codeverse/cli/cost_cmd.py
new file mode 100644
index 00000000..aa2d5341
--- /dev/null
+++ b/harness/codeverse/cli/cost_cmd.py
@@ -0,0 +1,94 @@
+"""``3dcv cost`` — what the runs cost and where the money went.
+
+ 3dcv cost runs/ # audit a tree of runs
+ 3dcv cost runs/e2e_chair_blender # one run, stage by stage
+ 3dcv cost bench/out/static_v1_flash --md report.md
+ 3dcv cost runs/ --recheck # re-price with today's table (drift vs what was billed)
+ 3dcv cost prices # the price table + provenance
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Annotated
+
+import typer
+
+from codeverse.cli._fmt import console, ok, warn
+
+cost_app = typer.Typer(no_args_is_help=True)
+
+
+@cost_app.command("show")
+def show(
+ paths: Annotated[list[Path], typer.Argument(help="run dirs / trees of runs (runs/, bench/out/<battery>)")],
+ md: Annotated[Path | None, typer.Option("--md", help="also write the full markdown report here")] = None,
+ recheck: Annotated[bool, typer.Option("--recheck", help="re-price every call with today's table")] = False,
+ limit: Annotated[int, typer.Option("--limit", help="rows in the per-run table")] = 20,
+ per_run: Annotated[bool, typer.Option("--per-run/--no-per-run")] = True,
+) -> None:
+ """Cost breakdown: per stage, per role, per model, waste, $ per passing artifact."""
+ from codeverse.cost import audit_runs
+ from codeverse.cost.report import console as text_report
+ from codeverse.cost.report import markdown, runs_table
+
+ audit = audit_runs(paths, recheck=recheck)
+ if not audit.runs:
+ raise typer.BadParameter(f"no runs with a record.json under {', '.join(str(p) for p in paths)}")
+ console.print(text_report(audit), soft_wrap=True)
+ if per_run:
+ console.print("")
+ console.print(runs_table(audit, limit=limit), soft_wrap=True)
+ if recheck:
+ drift = audit.total_usd - audit.recorded_usd
+ warn(f"re-priced total ${audit.total_usd:.4f} vs recorded ${audit.recorded_usd:.4f} ({drift:+.4f})")
+ for run in audit.runs:
+ for note in run.notes:
+ console.print(f" {run.run}: {note}")
+ if md:
+ md.parent.mkdir(parents=True, exist_ok=True)
+ md.write_text(markdown(audit, title=f"Cost audit — {', '.join(str(p) for p in paths)}"))
+ ok(f"wrote {md}")
+
+
+@cost_app.command("prices")
+def prices(
+ provider: Annotated[str | None, typer.Option("--provider", help="gemini | anthropic | openai")] = None,
+ unverified: Annotated[bool, typer.Option("--unverified", help="only rows that are not verified")] = False,
+) -> None:
+ """The USD price table with its provenance (source + checked date + status)."""
+ from codeverse.models.pricing import PRICES, price_provenance
+
+ rows = []
+ for (prov, model) in sorted(PRICES):
+ if provider and prov != provider:
+ continue
+ row = price_provenance(prov, model)
+ if unverified and row.status == "verified":
+ continue
+ p = row.price
+ assert p is not None
+ rows.append((f"{prov}:{model}", f"{p.input:g}", f"{p.cached:g}", f"{p.output:g}",
+ f"{p.image_usd:g}" if p.image_usd else "-", row.status, row.checked,
+ (row.provenance.note if row.provenance else "")[:60]))
+ header = ("model", "in/M", "cached/M", "out/M", "$/img", "status", "checked", "note")
+ widths = [max(len(str(r[i])) for r in [header, *rows]) for i in range(len(header))]
+ console.print(" ".join(h.ljust(w) for h, w in zip(header, widths, strict=True)), soft_wrap=True)
+ for r in rows:
+ console.print(" ".join(str(c).ljust(w) for c, w in zip(r, widths, strict=True)), soft_wrap=True)
+
+
+@cost_app.command("estimate")
+def estimate(
+ model: Annotated[str, typer.Argument(help="model id, e.g. gemini:gemini-3.1-pro-preview")],
+ input_tokens: Annotated[int, typer.Option("--in", help="prompt tokens")] = 0,
+ output_tokens: Annotated[int, typer.Option("--out", help="expected output tokens")] = 0,
+ cached: Annotated[int, typer.Option("--cached")] = 0,
+ images: Annotated[int, typer.Option("--images", help="input images at 1024px")] = 0,
+) -> None:
+ """What one call would cost before you send it."""
+ from codeverse.cost import estimate_call
+
+ est = estimate_call(model, input_tokens=input_tokens, output_tokens=output_tokens,
+ cached_tokens=cached, n_images=images)
+ console.print(est.line())
diff --git a/harness/codeverse/cli/layout_cmd.py b/harness/codeverse/cli/layout_cmd.py
new file mode 100644
index 00000000..0b7a6a3a
--- /dev/null
+++ b/harness/codeverse/cli/layout_cmd.py
@@ -0,0 +1,261 @@
+"""``3dcv show`` + ``3dcv migrate-runs`` — the run directory, read and reorganised.
+
+``show`` prints one run as three clearly separated sections (docs/RUN_LAYOUT.md):
+
+* **DELIVERABLE** — what the run produced and where to find it;
+* **QUALITY EVIDENCE** — why we believe it is good (score, rubric, gates, acceptance);
+* **COST & SETTINGS** — tokens and dollars per stage, model ids, thinking levels,
+ rubric hash, budget vs spent, wall clock.
+
+Both commands work on the new layout and on runs written before it: the cost /
+settings block is computed on the fly when ``telemetry/`` is not there yet.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Annotated, Any
+
+import typer
+from rich.table import Table
+
+from codeverse.cli import _common as C
+from codeverse.cli._fmt import console, fmt_score, fmt_usd, kv_table, ok, warn
+from codeverse.contracts.run import (
+ CostSummary,
+ DeliverableFile,
+ RunDeliverable,
+ RunRecord,
+ SettingsSnapshot,
+)
+from codeverse.workspace import Workspace
+
+RunsDirOpt = Annotated[Path | None, typer.Option("--runs-dir", help="runs root (default: settings.runs_dir)")]
+
+
+def _human_bytes(n: int) -> str:
+ size = float(n)
+ for unit in ("B", "KB", "MB", "GB"):
+ if size < 1024.0 or unit == "GB":
+ return f"{size:,.0f} {unit}" if unit == "B" else f"{size:,.1f} {unit}"
+ size /= 1024.0
+ return f"{size:,.1f} GB"
+
+
+def _section(title: str) -> None:
+ console.rule(f"[bold]{title}[/bold]", align="left")
+
+
+# --------------------------------------------------------------------------- (a) deliverable
+MAX_ROWS_PER_ROLE = 6
+
+
+def _deliverable_table(d: RunDeliverable) -> Table:
+ """One row per file, except roles with many files (frame stacks, link meshes,
+ a multi-file source tree) which collapse into a single counted row."""
+ t = Table(title="files (deliverable/)", show_lines=False)
+ for col in ("role", "path", "size"):
+ t.add_column(col, justify="right" if col == "size" else "left")
+ by_role: dict[str, list[DeliverableFile]] = {}
+ for f in sorted(d.files, key=lambda f: (f.role, f.path)):
+ by_role.setdefault(f.role, []).append(f)
+ for role, files in by_role.items():
+ if len(files) <= MAX_ROWS_PER_ROLE:
+ for f in files:
+ t.add_row(role, f.path, _human_bytes(f.bytes))
+ continue
+ dirs = {f.path.rsplit("/", 1)[0] for f in files}
+ head = f"{dirs.pop()}/ " if len(dirs) == 1 else ""
+ t.add_row(role, f"{head}({len(files)} files)", _human_bytes(sum(f.bytes for f in files)))
+ return t
+
+
+def _legacy_deliverable_rows(ws: Workspace) -> dict[str, Any]:
+ """Old layout: point at the physical artifacts instead of ``deliverable/``."""
+ rows: dict[str, Any] = {}
+ for name in ("object.glb", "object.stl", "object.step", "robot.urdf", "object_textured.glb", "preview.gif"):
+ p = ws.artifacts / name
+ if p.is_file():
+ rows[name] = f"{p} ({_human_bytes(p.stat().st_size)})"
+ if ws.src.is_dir():
+ rows["src/"] = str(ws.src)
+ return rows
+
+
+def print_deliverable(ws: Workspace, record: RunRecord) -> None:
+ from codeverse.flywheel.deliverable import load_deliverable
+
+ _section("DELIVERABLE — what the run produced")
+ spec = record.spec
+ head = {"prompt": spec.prompt, "track": spec.track.value, "language": spec.language.value,
+ "status": record.status.value, "best round": record.best_round,
+ "score": fmt_score(record.final_score), "workspace": ws.root}
+ d = load_deliverable(ws, record)
+ if d is not None:
+ head["code"] = f"{d.entry or 'deliverable/src/'} @ {d.commit[:12] or '-'} ({d.code_source})"
+ head["total"] = f"{len(d.files)} files, {_human_bytes(d.total_bytes)}"
+ console.print(kv_table("deliverable", head))
+ if d is not None:
+ console.print(_deliverable_table(d))
+ for name, why in d.skipped.items():
+ warn(f"not packaged: {name} — {why}")
+ else:
+ console.print(kv_table("artifacts (old layout — run `3dcv migrate-runs` to build deliverable/)",
+ _legacy_deliverable_rows(ws)))
+
+
+# --------------------------------------------------------------------------- (b) evidence
+def print_evidence(ws: Workspace, record: RunRecord) -> None:
+ from codeverse.flywheel.record import effective_judgment
+ from codeverse.flywheel.sample import best_round_record, gate_error_summary
+
+ _section("QUALITY EVIDENCE — why we believe it")
+ rnd = best_round_record(record)
+ j = effective_judgment(rnd) if rnd is not None else None
+ gates = gate_error_summary(rnd)
+ rows: dict[str, Any] = {
+ "baseline → best": f"{fmt_score(record.baseline_score)} → {fmt_score(record.final_score)}",
+ "rubric": (j.rubric if j else "") or str(record.extra.get("rubric") or "-"),
+ "passed": "-" if j is None else j.passed,
+ "gate errors": f"{sum(gates.values())} ({', '.join(f'{g}:{n}' for g, n in gates.items() if n) or 'none'})",
+ "stop reason": str(record.extra.get("stop_reason") or "-"),
+ }
+ if j is not None:
+ acc = j.acceptance_results or {}
+ rows["acceptance"] = f"{sum(1 for v in acc.values() if v)}/{len(acc)} met" if acc else "-"
+ rows["judge summary"] = j.summary[:300]
+ if rnd is not None and rnd.renders is not None and rnd.renders.contact_sheet:
+ rows["contact sheet"] = rnd.renders.contact_sheet
+ if rnd is not None and rnd.measurement is not None:
+ mm = rnd.measurement
+ rows["measured"] = (f"extents {tuple(round(v, 3) for v in mm.extents)} m · {mm.tri_count} tris · "
+ f"{mm.n_meshes} meshes · ground gap {mm.ground_gap_m:.3f} m")
+ rows["evidence dir"] = f"{ws.evidence if ws.evidence.exists() else ws.artifacts} (renders/ gates/ judge/)"
+ console.print(kv_table("evidence", rows))
+ if j is not None and j.issues:
+ for issue in j.issues[:5]:
+ console.print(f" [yellow]{issue.severity}[/yellow] {issue.target}: {issue.detail[:160]}")
+
+
+# --------------------------------------------------------------------------- (c) cost & settings
+def _stage_table(cost: CostSummary) -> Table:
+ t = Table(title="cost by stage", show_lines=False)
+ for col in ("stage", "calls", "in tok", "out tok", "cached", "USD", "% run", "secs"):
+ t.add_column(col, justify="left" if col == "stage" else "right")
+ total = cost.total_usd or 1.0
+ for s in cost.by_stage:
+ t.add_row(s.stage, str(s.calls), f"{s.input_tokens:,}", f"{s.output_tokens:,}", f"{s.cached_tokens:,}",
+ fmt_usd(s.cost_usd), f"{100.0 * s.cost_usd / total:.0f}%", f"{s.seconds:.0f}")
+ return t
+
+
+def _roles_table(settings: SettingsSnapshot) -> Table:
+ t = Table(title="models per role", show_lines=False)
+ for col in ("role", "model", "thinking", "temp", "samples", "source"):
+ t.add_column(col)
+ for r in settings.roles:
+ t.add_row(r.role, r.model, r.thinking or "-", "-" if r.temperature is None else f"{r.temperature:g}",
+ "-" if r.n_samples is None else str(r.n_samples), r.source)
+ return t
+
+
+def print_cost_and_settings(ws: Workspace, record: RunRecord) -> None:
+ from codeverse.flywheel.telemetry import build_telemetry, load_telemetry
+
+ _section("COST & SETTINGS — token price and the key step settings")
+ tele = load_telemetry(ws, record)
+ computed = False
+ if tele is None or tele.cost is None:
+ tele = build_telemetry(ws, record, write=False) # old layout: compute, do not write
+ computed = True
+ cost, settings = tele.cost, tele.settings
+ if cost is not None:
+ u = cost.tokens
+ budget_line = (f"{fmt_usd(cost.total_usd)} of {fmt_usd(cost.budget_usd)}"
+ f"{'' if cost.budget_used_pct is None else f' ({cost.budget_used_pct:.0f}%)'}")
+ console.print(kv_table("cost", {
+ "spent / budget": budget_line,
+ "wall clock": f"{cost.wall_clock_s / 60:.1f} min of {cost.max_minutes:.0f} min",
+ "tokens": f"in {u.input_tokens:,} (cached {u.cached_tokens:,}) · out {u.output_tokens:,} · "
+ f"thoughts {u.thoughts_tokens:,} · {u.tool_calls} tool calls",
+ "model calls": cost.n_calls,
+ **({"post-run calls": f"{fmt_usd(cost.post_run_usd)} priced outside the run total (texture pass …)"}
+ if cost.post_run_usd >= 0.0005 else {}),
+ **({"unattributed": f"{fmt_usd(cost.unattributed_usd)} with no per-call row (ledger residual)"}
+ if cost.unattributed_usd >= 0.0005 else {}),
+ "by role": " · ".join(f"{r} {fmt_usd(v)}" for r, v in sorted(cost.by_role.items(), key=lambda kv: -kv[1])) or "-",
+ "by model": " · ".join(f"{m or '(unknown)'} {fmt_usd(v)}" for m, v in sorted(cost.by_model.items(), key=lambda kv: -kv[1])),
+ "rounds": " · ".join(f"r{r['index']} {r['kind']} {fmt_usd(r['cost_usd'])}" for r in cost.by_round),
+ }))
+ console.print(_stage_table(cost))
+ if settings is not None:
+ console.print(_roles_table(settings))
+ console.print(kv_table("settings", {
+ "budget": " · ".join(f"{k}={v}" for k, v in settings.budget.items()),
+ "candidates": settings.candidates or 1,
+ "texture pass": settings.texture,
+ "seed": settings.seed,
+ "rubric": f"{settings.rubric} (hash {settings.rubric_hash or '-'})",
+ "prompt hashes": " · ".join(f"{k}={v}" for k, v in settings.prompt_hashes.items()) or "-",
+ "tools": " · ".join(f"{k}={v}" for k, v in settings.tool_versions.items() if v and k != "platform"),
+ "harness": f"{settings.harness_version} @ {settings.harness_git_sha[:12] or 'no-sha'}",
+ "key pool": settings.key_pool_size,
+ "price table": settings.price_table_version or "-",
+ "render": " · ".join(f"{k}={v}" for k, v in settings.render.items()),
+ }))
+ if computed:
+ console.print("[dim]computed on the fly (no telemetry/ yet — `3dcv migrate-runs` writes it)[/dim]")
+ else:
+ console.print(f"[dim]telemetry: {ws.cost_path} · {ws.usage_path} · {ws.settings_path}[/dim]")
+
+
+# --------------------------------------------------------------------------- commands
+def show(
+ slug: str,
+ runs_dir: RunsDirOpt = None,
+ section: Annotated[str, typer.Option("--section", help="all | deliverable | evidence | cost")] = "all",
+) -> None:
+ """Show one run in three separated sections: DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS."""
+ from codeverse.flywheel.record import RecordError, load_record
+
+ ws = C.open_workspace(slug, runs_dir)
+ try:
+ record = load_record(ws)
+ except RecordError as e:
+ raise C.CliError(f"{e} (run `3dcv status {slug}` for a partial view)") from e
+ if section not in ("all", "deliverable", "evidence", "cost"):
+ raise C.CliError(f"unknown --section {section!r} (all | deliverable | evidence | cost)")
+ if section in ("all", "deliverable"):
+ print_deliverable(ws, record)
+ if section in ("all", "evidence"):
+ print_evidence(ws, record)
+ if section in ("all", "cost"):
+ print_cost_and_settings(ws, record)
+
+
+def migrate_runs_cmd(
+ runs_dir: Annotated[Path, typer.Argument(help="runs root (or a single run directory)")],
+ dry_run: Annotated[bool, typer.Option("--dry-run", help="report what would change; touch nothing")] = False,
+) -> None:
+ """Reorganise existing runs in place onto deliverable/ + evidence/ + telemetry/ (idempotent)."""
+ from codeverse.flywheel.migrate import MIGRATED, migrate_runs
+
+ try:
+ rep = migrate_runs(runs_dir, dry_run=dry_run)
+ except FileNotFoundError as e:
+ raise C.CliError(str(e)) from e
+ t = Table(title=f"{'would migrate' if dry_run else 'migrated'} {rep.runs_dir}")
+ for col in ("run", "status", "layout", "deliverable", "telemetry rows", "record", "note"):
+ t.add_column(col)
+ for m in rep.runs:
+ t.add_row(Path(m.run).name, m.status,
+ ", ".join(f"{k}:{v}" for k, v in list(m.layout.items())[:3]) or "-",
+ "-" if m.deliverable_files is None else f"{m.deliverable_files} files / {_human_bytes(m.deliverable_bytes)}",
+ "-" if m.telemetry_rows is None else str(m.telemetry_rows),
+ "updated" if m.record_updated else "-", m.reason[:60])
+ console.print(t)
+ summary = (f"{rep.n_runs} runs · {rep.n_migrated} {'to migrate' if dry_run else MIGRATED} · "
+ f"{rep.n_up_to_date} up to date · {rep.n_skipped} skipped · {rep.n_failed} failed")
+ (warn if rep.n_failed else ok)(summary)
+ if rep.n_failed:
+ raise typer.Exit(code=1)
diff --git a/harness/codeverse/cli/main.py b/harness/codeverse/cli/main.py
index 8aef9cd3..aad46fa6 100644
--- a/harness/codeverse/cli/main.py
+++ b/harness/codeverse/cli/main.py
@@ -19,6 +19,7 @@ from codeverse import __version__
from codeverse.cli import _common as C
from codeverse.cli._fmt import console, err_console, kv_table, ok, print_record_summary, warn
from codeverse.cli.bench_cmd import bench_app
+from codeverse.cli.cost_cmd import cost_app
from codeverse.cli.doctor import doctor_app
from codeverse.cli.flywheel_cmd import flywheel_app
from codeverse.cli.texture_cmd import texture_app
@@ -31,6 +32,7 @@ app = typer.Typer(name="3dcv", help="3dcodeverse: LLMs write raw 3D code; the ha
pretty_exceptions_enable=False)
app.add_typer(flywheel_app, name="flywheel", help="Dataset export / pairs / captions / index.")
app.add_typer(bench_app, name="bench", help="Prompt batteries: run + report.")
+app.add_typer(cost_app, name="cost", help="Cost audit: per stage/role/model, waste, $ per passing artifact.")
app.add_typer(doctor_app, name="doctor", help="Environment checks.")
app.add_typer(texture_app, name="texture", help="Text-to-image texturing: object pass / scene pack.")
app.command("tools", help="List spatial tools or run one: `3dcv tools list` | `3dcv tools <name> --json '{...}' --workspace ws`.")(tools)
@@ -182,6 +184,7 @@ def status(slug: str, runs_dir: RunsDirOpt = None, events: Annotated[int, typer.
"shipped": t.get("shipped"), "delta": t.get("delta"), "reason": t.get("reason", ""),
"textures": t.get("n_textures", len(t.get("textures", {}) or {})),
"glb": t.get("glb_textured", "") or "-"}))
+ console.print(f"[dim]`3dcv show {ws.root.name}` for the DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS view[/dim]")
evs = EventLog(ws.events_path).read()
if evs:
console.print(f"[dim]last {min(events, len(evs))} of {len(evs)} events:[/dim]")
@@ -334,5 +337,14 @@ def mcp(workspace: Annotated[Path, typer.Option("--workspace")]) -> None:
os.execvp(sys.executable, [sys.executable, "-m", "codeverse.spatial.mcp_server", "--workspace", str(workspace)])
+# --------------------------------------------------------------------------- run layout (show / migrate)
+# appended registration — see codeverse/cli/layout_cmd.py
+from codeverse.cli.layout_cmd import migrate_runs_cmd as _migrate_runs_cmd # noqa: E402
+from codeverse.cli.layout_cmd import show as _show # noqa: E402
+
+app.command("show", help="One run in three sections: DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS.")(_show)
+app.command("migrate-runs", help="Reorganise existing runs onto deliverable/ + evidence/ + telemetry/ (idempotent).")(_migrate_runs_cmd)
+
+
if __name__ == "__main__": # pragma: no cover
app()
diff --git a/harness/codeverse/contracts/run.py b/harness/codeverse/contracts/run.py
index ed7d4137..4cef3a4a 100644
--- a/harness/codeverse/contracts/run.py
+++ b/harness/codeverse/contracts/run.py
@@ -46,6 +46,119 @@ class RoundRecord(BaseModel):
return self.judgment.overall if self.judgment else None
+# --------------------------------------------------------------------------- telemetry (settings + cost)
+class RoleSettings(BaseModel):
+ """Resolved model settings for ONE role of a run (planner/generator/judge/…).
+
+ ``source`` says where the sampling knobs came from: ``spec`` (frozen on the
+ Spec), ``default`` (the harness default, read from the call site's typed
+ defaults) or ``unknown`` (the call site hard-codes it per task — the value
+ is left empty rather than guessed)."""
+
+ role: str
+ model: str = ""
+ backend: str = Field(default="", description="gemini | anthropic | api-agent | gemini-cli | 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 — the 'key step settings' block."""
+
+ schema_version: int = 1
+ roles: list[RoleSettings] = Field(default_factory=list)
+ budget: dict[str, Any] = Field(default_factory=dict, description="max_rounds / max_usd / max_minutes / max_repair_attempts")
+ candidates: int | None = Field(default=None, description="best-of-N baseline width, resolved")
+ texture: bool = False
+ seed: int = 0
+ 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 / cookbook / generate / refine …")
+ 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 codeverse.models.pricing.PRICES")
+ render: dict[str, Any] = Field(default_factory=dict, description="resolved render settings (size, gpu, sheet)")
+ limits: dict[str, Any] = Field(default_factory=dict, description="resolved timeouts / parallelism")
+
+
+class StageCost(BaseModel):
+ """Token + money subtotal for one stage of the run (plan / generate / judge / …)."""
+
+ 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 money ledger: what the run cost, where, and against which budget."""
+
+ schema_version: int = 1
+ total_usd: float = 0.0
+ budget_usd: float = 0.0
+ budget_used_pct: float | None = None
+ wall_clock_s: float = 0.0
+ 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 / seconds / score")
+ ledger_usd: float = Field(default=0.0, description="sum of the per-call rows in telemetry/usage.jsonl")
+ unattributed_usd: float = Field(
+ default=0.0, description="total_usd - ledger_usd when positive: money with no per-call row")
+ post_run_usd: float = Field(
+ default=0.0, description="ledger_usd - total_usd when positive: priced calls the run total does not "
+ "include (a texture pass that ran after the loop, …)")
+
+
+class RunTelemetry(BaseModel):
+ """``record.telemetry`` — accounting + settings, kept apart from the deliverable."""
+
+ schema_version: int = 1
+ settings: SettingsSnapshot | None = None
+ cost: CostSummary | None = None
+ environment: dict[str, str] = Field(default_factory=dict)
+ files: dict[str, str] = Field(default_factory=dict, description="label → run-relative path under telemetry/")
+
+
+# --------------------------------------------------------------------------- deliverable
+class DeliverableFile(BaseModel):
+ """One file handed to the user, with its identity."""
+
+ path: str = Field(description="run-relative path (under deliverable/)")
+ role: str = Field(description="code | model | urdf | mesh | sheet | preview | frames | captions | bundle | manifest")
+ bytes: int = 0
+ sha256: str = ""
+
+
+class RunDeliverable(BaseModel):
+ """``record.deliverable`` — what the run produced, as paths + hashes + sizes."""
+
+ schema_version: int = 1
+ dir: str = "deliverable"
+ best_round: int | None = None
+ commit: str = ""
+ code_source: str = Field(default="", description="commit | working_tree")
+ entry: str = Field(default="", description="run-relative entry file of the code snapshot")
+ files: list[DeliverableFile] = Field(default_factory=list)
+ total_bytes: int = 0
+ skipped: dict[str, str] = Field(default_factory=dict, description="name → why it is not in deliverable/")
+ generated_at: datetime | None = None
+
+ def by_role(self, role: str) -> list[DeliverableFile]:
+ return [f for f in self.files if f.role == role]
+
+
class RunRecord(BaseModel):
spec: Spec
plan: StaticPlan | ArticulatedPlan | ScenePlan | GraphicsPlan | None = None
@@ -61,4 +174,8 @@ class RunRecord(BaseModel):
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 ledger + environment (written by finalize_record)")
+ deliverable: RunDeliverable | None = Field(
+ default=None, description="what to hand over: paths + hashes + sizes under deliverable/")
extra: dict[str, Any] = Field(default_factory=dict)
diff --git a/harness/codeverse/cost/__init__.py b/harness/codeverse/cost/__init__.py
new file mode 100644
index 00000000..c47e887a
--- /dev/null
+++ b/harness/codeverse/cost/__init__.py
@@ -0,0 +1,52 @@
+"""Cost accounting: a typed ledger of every model call, a price-provenance layer
+on top of ``models/pricing.py``, an audit over recorded runs, and the two cheap
+helpers that keep the bill down (cache-friendly prompt ordering, a pre-send cost
+guard).
+
+Public API::
+
+ from codeverse.cost import record_call, load_ledger, summarise
+ from codeverse.cost import audit_runs, markdown # the audit + its report
+ from codeverse.cost import estimate_call, CostGuard # decide before you send
+ from codeverse.cost import Block, order_blocks # cache-friendly prompts
+ from codeverse.cost import default_route, pro_break_even # model routing
+
+Nothing here imports tracks/ or orchestrator/, so any layer may use it.
+"""
+
+from __future__ import annotations
+
+from codeverse.cost.audit import Audit, WasteItem, audit_dir, audit_runs
+from codeverse.cost.caching import (
+ Block,
+ PrefixReport,
+ cache_efficiency,
+ order_blocks,
+ prefix_report,
+ prefix_signature,
+ render_blocks,
+)
+from codeverse.cost.guard import CostEstimate, CostGuard, cheapest_affordable, estimate_call, text_tokens
+from codeverse.cost.ledger import (
+ CostLedger,
+ ledger_path,
+ load_ledger,
+ price_call,
+ record_call,
+ set_default_ledger,
+ summarise,
+)
+from codeverse.cost.reconstruct import RunLedger, find_runs, reconstruct, reconstruct_run
+from codeverse.cost.report import console, markdown
+from codeverse.cost.routing import ROUTES, Route, default_route, pro_break_even, samples_for_precision
+from codeverse.cost.types import CallCost, CostBucket, Role, Stage, Summary
+
+__all__ = [
+ "ROUTES", "Audit", "Block", "CallCost", "CostBucket", "CostEstimate", "CostGuard", "CostLedger",
+ "PrefixReport", "Role", "Route", "RunLedger", "Stage", "Summary", "WasteItem", "audit_dir",
+ "audit_runs", "cache_efficiency", "cheapest_affordable", "console", "default_route",
+ "estimate_call", "find_runs", "ledger_path", "load_ledger", "markdown", "order_blocks",
+ "prefix_report", "prefix_signature", "price_call", "pro_break_even", "reconstruct",
+ "reconstruct_run", "record_call", "render_blocks", "samples_for_precision",
+ "set_default_ledger", "summarise", "text_tokens",
+]
diff --git a/harness/codeverse/cost/audit.py b/harness/codeverse/cost/audit.py
new file mode 100644
index 00000000..972dd5dc
--- /dev/null
+++ b/harness/codeverse/cost/audit.py
@@ -0,0 +1,263 @@
+"""Cost audit over a directory of runs: where the money and the minutes go.
+
+``audit_runs(paths)`` reconstructs a ledger per run (``reconstruct.py``),
+stamps every row with its run's track / language / status, and aggregates:
+
+* $ per run, per track, per stage, per role, per backend, per model;
+* token composition (input / cached / output / thoughts) and the effective
+ $/1k-token rate each bucket actually paid;
+* latency next to the money — wall clock, model time, harness (non-model) time;
+* **waste**: rounds that scored worse than the round before, judge verdicts paid
+ for on rounds that were never promoted, repair loops that never converged,
+ degraded verdicts, best-of-N candidates that lost, and spend after the budget
+ was already blown.
+
+Everything is measured from the recorded telemetry; nothing is estimated except
+where a row says so (``price_source == "event-cost"`` — the event recorded a
+cost but no tokens).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from codeverse.cost.ledger import summarise
+from codeverse.cost.reconstruct import RunLedger, find_runs, reconstruct
+from codeverse.cost.types import CallCost, CostBucket, Role, Stage, Summary
+
+#: dimensions the audit always aggregates on
+AUDIT_DIMENSIONS = ("run", "track", "language", "stage", "role", "backend", "model", "provider",
+ "status", "outcome", "source")
+
+
+@dataclass
+class WasteItem:
+ """One dollar that bought nothing (or bought a worse artifact)."""
+
+ kind: str # regression | unpromoted_judge | repair_no_converge | degraded_judge |
+ # # lost_candidate | post_budget | zero_delta_round
+ run: str
+ usd: float
+ detail: str = ""
+ round: int | None = None
+
+ def as_row(self) -> tuple[str, str, str, float]:
+ return (self.kind, self.run, self.detail, self.usd)
+
+
+@dataclass
+class RoundCost:
+ run: str
+ index: int
+ kind: str
+ usd: float
+ score: float | None
+ prev_score: float | None
+ gate_errors: int = 0
+ promoted: bool = False
+
+ @property
+ def delta(self) -> float | None:
+ if self.score is None or self.prev_score is None:
+ return None
+ return self.score - self.prev_score
+
+
+@dataclass
+class Audit:
+ """Everything the report needs; ``summary`` holds the bucket maps."""
+
+ runs: list[RunLedger] = field(default_factory=list)
+ rows: list[CallCost] = field(default_factory=list)
+ summary: Summary = field(default_factory=Summary)
+ rounds: list[RoundCost] = field(default_factory=list)
+ waste: list[WasteItem] = field(default_factory=list)
+ recheck: bool = False
+
+ # ---------------------------------------------------------------- totals
+ @property
+ def total_usd(self) -> float:
+ return self.summary.total.cost_usd
+
+ @property
+ def recorded_usd(self) -> float:
+ return sum(r.recorded_usd for r in self.runs)
+
+ @property
+ def n_runs(self) -> int:
+ return len(self.runs)
+
+ @property
+ def n_passed(self) -> int:
+ return sum(1 for r in self.runs if r.passed)
+
+ @property
+ def usd_per_run(self) -> float:
+ return self.total_usd / self.n_runs if self.n_runs else 0.0
+
+ @property
+ def usd_per_passing_artifact(self) -> float:
+ """Total spend (including the runs that failed) divided by the artifacts
+ that actually passed — the only cost-per-unit that matters for a dataset."""
+ return self.total_usd / self.n_passed if self.n_passed else float("inf")
+
+ @property
+ def wall_s(self) -> float:
+ return sum(r.wall_s for r in self.runs)
+
+ @property
+ def model_s(self) -> float:
+ return sum(r.model_s for r in self.runs)
+
+ @property
+ def harness_s(self) -> float:
+ return sum(r.harness_s for r in self.runs)
+
+ def bucket(self, dim: str, key: str) -> CostBucket:
+ return self.summary.dimension(dim).get(key, CostBucket(key=key))
+
+ def waste_total(self) -> float:
+ return sum(w.usd for w in self.waste)
+
+ def waste_by_kind(self) -> dict[str, tuple[int, float]]:
+ out: dict[str, tuple[int, float]] = {}
+ for w in self.waste:
+ n, usd = out.get(w.kind, (0, 0.0))
+ out[w.kind] = (n + 1, usd + w.usd)
+ return dict(sorted(out.items(), key=lambda kv: -kv[1][1]))
+
+ def calls_per_round(self) -> float:
+ rounds = {(r.run, r.round) for r in self.rows if r.round is not None}
+ calls = sum(r.n_calls for r in self.rows if r.round is not None)
+ return calls / len(rounds) if rounds else 0.0
+
+
+def _round_costs(led: RunLedger) -> list[RoundCost]:
+ out: list[RoundCost] = []
+ best = None
+ for idx, score in enumerate(led.round_scores):
+ usd = sum(r.cost_usd for r in led.rows if r.round == idx)
+ kind = "baseline" if idx == 0 else "refine"
+ promoted = score is not None and (best is None or score > best)
+ rc = RoundCost(run=led.run, index=idx, kind=kind, usd=usd, score=score,
+ prev_score=best, gate_errors=led.gate_errors[idx] if idx < len(led.gate_errors) else 0,
+ promoted=promoted)
+ if promoted:
+ best = score
+ out.append(rc)
+ return out
+
+
+def _waste(led: RunLedger, rounds: Sequence[RoundCost]) -> list[WasteItem]:
+ items: list[WasteItem] = []
+ for rc in rounds:
+ if rc.index == 0:
+ continue
+ if rc.delta is not None and rc.delta < 0:
+ items.append(WasteItem("regression", led.run, rc.usd, round=rc.index,
+ detail=f"r{rc.index:02d} scored {rc.score:.3f} vs {rc.prev_score:.3f} "
+ f"({rc.delta:+.3f}) — the round was paid for and thrown away"))
+ elif rc.delta is not None and abs(rc.delta) < 0.005:
+ items.append(WasteItem("zero_delta_round", led.run, rc.usd, round=rc.index,
+ detail=f"r{rc.index:02d} moved the score by {rc.delta:+.3f}"))
+ # judge verdicts on rounds that never became best
+ for row in led.rows:
+ if row.stage is not Stage.JUDGE and row.role is not Role.JUDGE:
+ continue
+ rc = next((r for r in rounds if r.index == row.round), None)
+ if rc is not None and not rc.promoted and rc.index > 0:
+ items.append(WasteItem("unpromoted_judge", led.run, row.cost_usd, round=row.round,
+ detail=f"judge verdict for r{row.round:02d}, which never became best"))
+ if row.outcome == "degraded":
+ items.append(WasteItem("degraded_judge", led.run, row.cost_usd, round=row.round,
+ detail="degraded verdict (glitch, not a score) — paid for, not usable"))
+ # repair loops that never produced a passing run
+ repair = [r for r in led.rows if r.stage is Stage.REPAIR]
+ if repair and not led.passed:
+ items.append(WasteItem("repair_no_converge", led.run, sum(r.cost_usd for r in repair),
+ detail=f"{len(repair)} repair call(s) in a run that ended '{led.status}'"))
+ # best-of-N candidates that lost (their whole sub-workspace is thrown away)
+ won = led.selected_candidate
+ losers = [r for r in led.rows if r.stage is Stage.CANDIDATE and not (won and r.label.startswith(f"{won}:"))]
+ if losers:
+ names = sorted({r.label.split(":", 1)[0] for r in losers})
+ items.append(WasteItem("lost_candidate", led.run, sum(r.cost_usd for r in losers),
+ detail=f"best-of-N: {', '.join(names)} lost to {won or '(unknown)'}"))
+ # anything spent on a round that finished after the budget was blown
+ if led.stop_reason in ("budget",) or led.status == "budget":
+ last = rounds[-1] if rounds else None
+ extra = [r for r in led.rows if r.round is not None and last is not None and r.round > last.index]
+ if extra:
+ items.append(WasteItem("post_budget", led.run, sum(r.cost_usd for r in extra),
+ detail=f"round r{extra[0].round:02d} completed after the budget was already gone"))
+ return items
+
+
+def audit_runs(paths: Iterable[str | Path], *, recheck: bool = False) -> Audit:
+ """Reconstruct + aggregate every run under ``paths`` (files, run dirs or trees)."""
+ dirs: list[Path] = []
+ for p in paths:
+ dirs += find_runs(p)
+ audit = Audit(recheck=recheck)
+ for d in dirs:
+ led = reconstruct(d, recheck=recheck)
+ if not led.rows:
+ continue
+ for row in led.rows:
+ row.track = led.track or "?"
+ row.language = led.language or "?"
+ row.status = led.status or "?"
+ rounds = _round_costs(led)
+ audit.runs.append(led)
+ audit.rows += led.rows
+ audit.rounds += rounds
+ audit.waste += _waste(led, rounds)
+ audit.summary = summarise(audit.rows, dimensions=AUDIT_DIMENSIONS)
+ audit.runs.sort(key=lambda r: -r.ledger_usd)
+ audit.waste.sort(key=lambda w: -w.usd)
+ return audit
+
+
+def audit_dir(root: str | Path, *, recheck: bool = False) -> Audit:
+ return audit_runs([root], recheck=recheck)
+
+
+# --------------------------------------------------------------------------- derived views
+def cached_input_share(audit: Audit) -> tuple[int, int, float]:
+ """``(cached, total input, $ paid for cache reads)`` — how much of every prompt
+ is context we have already sent before."""
+ cached = audit.summary.total.cached_tokens
+ total = audit.summary.total.input_tokens
+ usd = sum(min(r.cached_tokens, r.input_tokens) * r.price_cached / 1e6 for r in audit.rows)
+ return cached, total, usd
+
+
+def uncached_if_no_cache(audit: Audit) -> float:
+ """What the same traffic would have cost with a 0% cache-hit rate — the
+ measured value of prompt caching as it stands today."""
+ extra = 0.0
+ for r in audit.rows:
+ cached = min(r.cached_tokens, r.input_tokens)
+ extra += cached * max(0.0, r.price_input - r.price_cached) / 1e6
+ return audit.total_usd + extra
+
+
+def stage_latency(audit: Audit) -> dict[str, tuple[float, float]]:
+ """stage → (model seconds, share of all model seconds)."""
+ per: dict[str, float] = {}
+ for r in audit.rows:
+ per[str(r.stage)] = per.get(str(r.stage), 0.0) + r.latency_ms / 1000.0
+ total = sum(per.values()) or 1.0
+ return {k: (v, v / total) for k, v in sorted(per.items(), key=lambda kv: -kv[1])}
+
+
+def price_confidence(audit: Audit) -> dict[str, float]:
+ """$ by how trustworthy the price row behind it is."""
+ out: dict[str, float] = {}
+ for r in audit.rows:
+ key = r.price_source if r.price_source in ("unknown", "provider-reported", "event-cost", "residual") \
+ else ("approximate" if r.price_approximate else "verified")
+ out[key] = out.get(key, 0.0) + r.cost_usd
+ return dict(sorted(out.items(), key=lambda kv: -kv[1]))
diff --git a/harness/codeverse/cost/caching.py b/harness/codeverse/cost/caching.py
new file mode 100644
index 00000000..67ec46d0
--- /dev/null
+++ b/harness/codeverse/cost/caching.py
@@ -0,0 +1,125 @@
+"""Cache-friendly prompt assembly + a measurement for whether it worked.
+
+Gemini's implicit cache (and Anthropic's explicit one) only ever matches a
+**prefix**: the shared part must be byte-identical *from token 0*. One
+variable line near the top — a timestamp, a round number, a shuffled view list —
+moves everything after it out of the cache. Cache reads cost 10% of input, so
+the whole difference between a $0.75/M prompt and a $0.075/M prompt is where the
+volatile blocks sit.
+
+Usage::
+
+ from codeverse.cost import order_blocks, Block
+ blocks = [Block("system rules", SYSTEM, stable=True),
+ Block("rubric", rubric_md, stable=True),
+ Block("round", f"round {i}", stable=False)]
+ prompt = render_blocks(order_blocks(blocks))
+
+:func:`prefix_report` measures a real sequence of prompts: how many tokens they
+share, and how many tokens each call pays full price for because of divergence.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from collections.abc import Sequence
+from dataclasses import dataclass, field
+
+from codeverse.cost.guard import text_tokens
+
+
+@dataclass(frozen=True)
+class Block:
+ """One labelled chunk of a prompt. ``stable`` blocks are identical across
+ every call in a family (system prompt, contract, cookbook, rubric, defect
+ checklist); everything else is volatile."""
+
+ name: str
+ text: str
+ stable: bool = False
+ order: int = 0 # tie-break inside the stable / volatile group
+
+ @property
+ def tokens(self) -> int:
+ return text_tokens(self.text)
+
+
+def order_blocks(blocks: Sequence[Block]) -> list[Block]:
+ """Stable blocks first (input order preserved), volatile blocks after.
+
+ This is the whole optimisation: the longest possible identical prefix, then
+ everything that changes per call."""
+ stable = [b for b in blocks if b.stable]
+ volatile = [b for b in blocks if not b.stable]
+ stable.sort(key=lambda b: b.order)
+ volatile.sort(key=lambda b: b.order)
+ return stable + volatile
+
+
+def render_blocks(blocks: Sequence[Block], *, sep: str = "\n\n") -> str:
+ return sep.join(b.text for b in blocks if b.text)
+
+
+def prefix_signature(blocks: Sequence[Block]) -> str:
+ """Hash of the stable prefix — log it per call; if it ever changes between
+ two calls that should share a cache, the cache was silently lost."""
+ h = hashlib.sha256()
+ for b in blocks:
+ if not b.stable:
+ break
+ h.update(b.text.encode("utf-8", "replace"))
+ return h.hexdigest()[:12]
+
+
+def common_prefix_chars(a: str, b: str) -> int:
+ n = min(len(a), len(b))
+ i = 0
+ while i < n and a[i] == b[i]:
+ i += 1
+ return i
+
+
+@dataclass
+class PrefixReport:
+ """What a family of prompts shares."""
+
+ n_prompts: int = 0
+ prefix_chars: int = 0
+ prefix_tokens: int = 0
+ mean_tokens: int = 0
+ divergent_tokens: int = 0 # mean tokens after the shared prefix
+ per_prompt: list[int] = field(default_factory=list)
+
+ @property
+ def shared_fraction(self) -> float:
+ return self.prefix_tokens / self.mean_tokens if self.mean_tokens else 0.0
+
+ def savings_usd(self, price_input: float, price_cached: float, *, calls: int | None = None) -> float:
+ """USD saved per ``calls`` calls by the shared prefix being a cache hit
+ instead of fresh input (the first call still pays full price)."""
+ n = (calls if calls is not None else self.n_prompts) - 1
+ return max(0, n) * self.prefix_tokens * max(0.0, price_input - price_cached) / 1e6
+
+
+def prefix_report(prompts: Sequence[str]) -> PrefixReport:
+ """Measure the common prefix of a real prompt sequence."""
+ if not prompts:
+ return PrefixReport()
+ shared = prompts[0]
+ for p in prompts[1:]:
+ shared = shared[: common_prefix_chars(shared, p)]
+ sizes = [text_tokens(p) for p in prompts]
+ prefix_tokens = text_tokens(shared)
+ return PrefixReport(
+ n_prompts=len(prompts), prefix_chars=len(shared), prefix_tokens=prefix_tokens,
+ mean_tokens=int(sum(sizes) / len(sizes)), per_prompt=sizes,
+ divergent_tokens=int(sum(sizes) / len(sizes)) - prefix_tokens,
+ )
+
+
+def cache_efficiency(usages: Sequence[object]) -> tuple[int, int, float]:
+ """``(cached, input, hit rate)`` over a sequence of ``Usage``-like objects —
+ the after-the-fact check that the ordering actually paid off."""
+ cached = sum(int(getattr(u, "cached_tokens", 0)) for u in usages)
+ total = sum(int(getattr(u, "input_tokens", 0)) for u in usages)
+ return cached, total, (cached / total if total else 0.0)
diff --git a/harness/codeverse/cost/guard.py b/harness/codeverse/cost/guard.py
new file mode 100644
index 00000000..986a28d5
--- /dev/null
+++ b/harness/codeverse/cost/guard.py
@@ -0,0 +1,162 @@
+"""Estimate what a call will cost **before** sending it, and pick a tier.
+
+The budget guard in ``orchestrator/budget.py`` stops a run *after* the money is
+gone. This is the cheap check that belongs in front of a call: how many tokens
+am I about to send, what will they cost on this model, and is there a cheaper
+model that still fits the job?
+
+Token counts are estimates (≈4 characters per token for prose/code, a flat
+per-image count for vision parts) — good to ±15% for prompt sizing, which is all
+a routing decision needs. When the exact number matters, price the ``Usage``
+the provider returns (``codeverse.cost.record_call``).
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass, field
+
+from codeverse.cost.types import normalise_ids
+from codeverse.models.pricing import per_image_usd, price_provenance, unit_prices
+
+#: characters per token — Gemini/OpenAI English prose and code both sit near 4
+CHARS_PER_TOKEN = 4.0
+
+#: tokens billed for one image part, by longest edge (Gemini bills 1290 for a
+#: 1024² tile; smaller images are cheaper, larger ones are tiled)
+IMAGE_TOKENS: dict[int, int] = {256: 258, 512: 258, 768: 1032, 1024: 1290, 2048: 5160}
+
+
+def text_tokens(text: str | Iterable[str]) -> int:
+ """Estimated prompt tokens for one string or a bag of blocks."""
+ if isinstance(text, str):
+ return int(len(text) / CHARS_PER_TOKEN + 0.5)
+ return sum(text_tokens(t) for t in text)
+
+
+def image_tokens(n: int = 1, *, px: int = 1024) -> int:
+ """Estimated input tokens for ``n`` images whose longest edge is ``px``."""
+ step = min(IMAGE_TOKENS, key=lambda k: abs(k - px))
+ return n * IMAGE_TOKENS[step]
+
+
+@dataclass(frozen=True)
+class CostEstimate:
+ """What one call is expected to cost, and how much to trust the number."""
+
+ model_id: str
+ provider: str
+ model: str
+ input_tokens: int
+ cached_tokens: int
+ output_tokens: int
+ n_images_out: int = 0
+ usd: float = 0.0
+ price_source: str = "unknown"
+ approximate: bool = True
+
+ @property
+ def known(self) -> bool:
+ return self.price_source != "unknown"
+
+ def line(self) -> str:
+ flag = " (approx)" if self.approximate else ""
+ return (f"{self.model_id}: ~{self.input_tokens:,} in ({self.cached_tokens:,} cached) "
+ f"+ {self.output_tokens:,} out ⇒ ${self.usd:.4f}{flag}")
+
+
+def estimate_call(
+ model_id: str,
+ *,
+ input_tokens: int = 0,
+ output_tokens: int = 0,
+ cached_tokens: int = 0,
+ prompt: str | Sequence[str] = "",
+ n_images: int = 0,
+ image_px: int = 1024,
+ n_images_out: int = 0,
+ image_out_px: int = 1024,
+) -> CostEstimate:
+ """Price a call that has not happened yet.
+
+ ``model_id`` is any harness id (``gemini:gemini-3.7-flash``,
+ ``api-agent:gemini:gemini-3.7-flash``). Give either token counts or the
+ ``prompt`` text (plus ``n_images`` vision parts)."""
+ kind, provider, model = normalise_ids("", model_id)
+ if not provider:
+ kind, provider, model = normalise_ids(model_id, model_id)
+ tokens_in = input_tokens or (text_tokens(prompt) + image_tokens(n_images, px=image_px) if prompt or n_images else 0)
+ cached = max(0, min(cached_tokens, tokens_in))
+ p_in, p_cached, p_out = unit_prices(provider, model, prompt_tokens=tokens_in)
+ usd = ((tokens_in - cached) * p_in + cached * p_cached + output_tokens * p_out) / 1e6
+ if n_images_out:
+ usd += n_images_out * per_image_usd(provider, model, size=image_out_px)
+ row = price_provenance(provider, model)
+ return CostEstimate(model_id=model_id, provider=provider, model=model, input_tokens=tokens_in,
+ cached_tokens=cached, output_tokens=output_tokens, n_images_out=n_images_out,
+ usd=usd, price_source=row.match if row.price else "unknown",
+ approximate=row.approximate)
+
+
+@dataclass
+class CostGuard:
+ """A per-run (or per-stage) allowance checked *before* each call.
+
+ ``spent`` is advanced by :meth:`commit` with what the call really cost, so
+ the guard converges on the truth even when the estimate was off."""
+
+ budget_usd: float
+ spent_usd: float = 0.0
+ reserve_usd: float = 0.0 # keep this much back for the judge / finalise
+ calls: int = 0
+ rejected: list[str] = field(default_factory=list)
+
+ @property
+ def remaining_usd(self) -> float:
+ return max(0.0, self.budget_usd - self.reserve_usd - self.spent_usd)
+
+ def affordable(self, estimate: CostEstimate) -> bool:
+ return estimate.usd <= self.remaining_usd
+
+ def check(self, estimate: CostEstimate) -> tuple[bool, str]:
+ """``(allow, reason)``. An unpriced model is allowed but flagged: refusing
+ to run because we cannot price a model would be worse than running it."""
+ if not estimate.known:
+ return True, f"no price row for {estimate.model_id}: cost unknown, not blocked"
+ if self.affordable(estimate):
+ return True, ""
+ msg = (f"{estimate.model_id} would cost ${estimate.usd:.4f} but only "
+ f"${self.remaining_usd:.4f} is left of ${self.budget_usd:.2f}")
+ self.rejected.append(msg)
+ return False, msg
+
+ def commit(self, usd: float) -> None:
+ self.spent_usd += max(0.0, usd)
+ self.calls += 1
+
+
+def cheapest_affordable(
+ model_ids: Sequence[str],
+ *,
+ input_tokens: int = 0,
+ output_tokens: int = 0,
+ cached_tokens: int = 0,
+ budget_usd: float | None = None,
+) -> tuple[str, CostEstimate] | None:
+ """Pick the cheapest model in ``model_ids`` that fits ``budget_usd``.
+
+ ``model_ids`` should be ordered best-quality-first; the caller decides how
+ much quality it is prepared to trade (see :mod:`codeverse.cost.routing`)."""
+ scored: list[tuple[float, str, CostEstimate]] = []
+ for mid in model_ids:
+ est = estimate_call(mid, input_tokens=input_tokens, output_tokens=output_tokens,
+ cached_tokens=cached_tokens)
+ if not est.known:
+ continue
+ if budget_usd is not None and est.usd > budget_usd:
+ continue
+ scored.append((est.usd, mid, est))
+ if not scored:
+ return None
+ scored.sort(key=lambda s: s[0])
+ return scored[0][1], scored[0][2]
diff --git a/harness/codeverse/cost/ledger.py b/harness/codeverse/cost/ledger.py
new file mode 100644
index 00000000..e88c7fd6
--- /dev/null
+++ b/harness/codeverse/cost/ledger.py
@@ -0,0 +1,265 @@
+"""Append-only cost ledger: one JSONL row per model / agent call.
+
+Writer (``record_call``) — callers hand it the ``Usage`` they already have; the
+ledger resolves the price row, records the unit prices it used and their
+provenance, and appends one line. It never raises and never blocks a run:
+accounting must not be able to fail a build.
+
+Reader (``load_ledger``) tolerates rows written by older/newer versions
+(unknown fields are kept, missing fields default).
+
+Aggregator (``summarise``) buckets rows by any of ``run / stage / role /
+backend / model / provider / round / outcome``.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import threading
+import time
+from collections.abc import Iterable, Sequence
+from pathlib import Path
+from typing import Any
+
+from codeverse.contracts.common import Usage
+from codeverse.cost.types import CallCost, CostBucket, Role, Stage, Summary, normalise_ids, stage_for_label
+from codeverse.models.pricing import cache_write_surcharge, estimate_cost, price_provenance, unit_prices
+
+log = logging.getLogger(__name__)
+
+#: default ledger file inside a run workspace
+LEDGER_NAME = "cost_ledger.jsonl"
+
+#: env var that points ``record_call`` at a ledger when no path is passed
+LEDGER_ENV = "CV3D_COST_LEDGER"
+
+DIMENSIONS = ("run", "stage", "role", "backend", "model", "provider", "round", "outcome")
+
+#: backends that bill us themselves (a subscription CLI reporting ``total_cost_usd``).
+#: Their dollar is authoritative and their reported model id is not — claude-code
+#: names one of the served models, not the one that did the work — so these rows
+#: are never re-priced from the token table.
+PROVIDER_PRICED_BACKENDS = frozenset({"claude-code"})
+
+
+class CostLedger:
+ """Append-only JSONL ledger. Thread-safe; one line per call, flushed on write."""
+
+ def __init__(self, path: str | Path):
+ self.path = Path(path)
+ self._lock = threading.Lock()
+
+ def append(self, row: CallCost) -> CallCost:
+ line = json.dumps(row.model_dump(mode="json"), ensure_ascii=False, default=str)
+ try:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ with self._lock, self.path.open("a", encoding="utf-8") as fh:
+ fh.write(line + "\n")
+ fh.flush()
+ except OSError as e: # pragma: no cover - disk full / read-only run dir
+ log.warning("cost ledger append failed (%s): %s", self.path, e)
+ return row
+
+ def read(self) -> list[CallCost]:
+ return load_ledger(self.path)
+
+ def summarise(self, **kw: Any) -> Summary:
+ return summarise(self.read(), **kw)
+
+
+_default_lock = threading.Lock()
+_default: CostLedger | None = None
+
+
+def set_default_ledger(path: str | Path | None) -> CostLedger | None:
+ """Point the module-level :func:`record_call` at ``path`` (``None`` disables it)."""
+ global _default
+ with _default_lock:
+ _default = CostLedger(path) if path is not None else None
+ return _default
+
+
+def default_ledger() -> CostLedger | None:
+ """The ledger :func:`record_call` writes to when no ``ledger=`` is given:
+ whatever :func:`set_default_ledger` set, else ``$CV3D_COST_LEDGER``."""
+ global _default
+ with _default_lock:
+ if _default is not None:
+ return _default
+ env = os.environ.get(LEDGER_ENV, "").strip()
+ if env:
+ _default = CostLedger(env)
+ return _default
+
+
+def ledger_path(workspace: str | Path) -> Path:
+ """The conventional ledger path of a run workspace (``<ws>/cost_ledger.jsonl``)."""
+ return Path(workspace) / LEDGER_NAME
+
+
+def price_call(
+ usage: Usage,
+ *,
+ backend: str = "",
+ model: str = "",
+ cache_write_tokens: int = 0,
+ reprice: bool = False,
+) -> tuple[float, dict[str, Any]]:
+ """``(cost_usd, price fields)`` for one call.
+
+ ``reprice=False`` keeps the cost the caller already computed (that is what
+ was actually billed at the time) and only *records* which price row would
+ explain it; ``reprice=True`` recomputes from the current table — how a cost
+ audit re-values an old run."""
+ prov_model = model or usage.model
+ kind, provider, name = normalise_ids(backend or usage.backend, prov_model)
+ row = price_provenance(provider, name)
+ p_in, p_cached, p_out = unit_prices(provider, name, prompt_tokens=usage.input_tokens)
+ cost = float(usage.cost_usd)
+ if kind in PROVIDER_PRICED_BACKENDS and cost:
+ return cost, {"backend": kind, "provider": provider, "model": name, "model_id": prov_model,
+ "price_input": 0.0, "price_cached": 0.0, "price_output": 0.0,
+ "price_source": "provider-reported", "price_approximate": True,
+ "price_checked": row.checked}
+ if reprice or not cost:
+ cost = estimate_cost(provider, name, usage)
+ if cache_write_tokens:
+ cost += cache_write_surcharge(provider, name, cache_write_tokens)
+ source = row.match if row.price is not None else "unknown"
+ if row.price is None and float(usage.cost_usd) > 0:
+ source = "provider-reported" # the backend billed us; our table cannot explain it
+ fields = {
+ "backend": kind,
+ "provider": provider,
+ "model": name,
+ "model_id": prov_model,
+ "price_input": p_in,
+ "price_cached": p_cached,
+ "price_output": p_out,
+ "price_source": source if source == "unknown" else (f"prefix:{row.key}" if source == "prefix" else source),
+ "price_approximate": row.approximate,
+ "price_checked": row.checked,
+ }
+ return cost, fields
+
+
+def record_call(
+ usage: Usage | None = None,
+ *,
+ run: str = "",
+ stage: Stage | str = Stage.OTHER,
+ role: Role | str | None = None,
+ round: int | None = None, # noqa: A002 - matches the record/round vocabulary
+ label: str = "",
+ backend: str = "",
+ model: str = "",
+ outcome: str = "ok",
+ latency_ms: int | None = None,
+ cache_write_tokens: int = 0,
+ n_calls: int = 1,
+ source: str = "live",
+ ledger: CostLedger | str | Path | None = None,
+ ts: float | None = None,
+ reprice: bool = False,
+ **extra: Any,
+) -> CallCost:
+ """Append one priced call to the ledger and return the row.
+
+ Callers pass the ``Usage`` they already hold::
+
+ from codeverse.cost import record_call
+ record_call(res.usage, run=ws.slug, round=idx, stage="baseline",
+ role="generator", ledger=ws.root / "cost_ledger.jsonl")
+
+ Never raises: a failure to account is logged, not propagated."""
+ u = usage or Usage()
+ try:
+ st = Stage(stage) if not isinstance(stage, Stage) else stage
+ except ValueError:
+ st = stage_for_label(str(stage))
+ if role is None:
+ from codeverse.cost.types import role_for_stage
+
+ rl = role_for_stage(st)
+ else:
+ try:
+ rl = Role(role) if not isinstance(role, Role) else role
+ except ValueError:
+ rl = Role.OTHER
+ try:
+ cost, price_fields = price_call(u, backend=backend, model=model,
+ cache_write_tokens=cache_write_tokens, reprice=reprice)
+ except Exception as e: # pragma: no cover - pricing must never break a run
+ log.warning("cost: pricing failed for %s/%s: %s", backend, model, e)
+ cost, price_fields = float(u.cost_usd), {}
+ row = CallCost(
+ ts=ts if ts is not None else time.time(),
+ run=run,
+ round=round,
+ stage=st,
+ role=rl,
+ label=label,
+ input_tokens=int(u.input_tokens),
+ cached_tokens=int(u.cached_tokens),
+ output_tokens=int(u.output_tokens),
+ thoughts_tokens=int(u.thoughts_tokens),
+ cache_write_tokens=int(cache_write_tokens),
+ tool_calls=int(u.tool_calls),
+ cost_usd=cost,
+ recorded_usd=float(u.cost_usd),
+ latency_ms=int(u.latency_ms if latency_ms is None else latency_ms),
+ cache_hit=int(u.cached_tokens) > 0,
+ outcome=outcome,
+ n_calls=max(1, int(n_calls)),
+ source=source,
+ **price_fields,
+ **extra,
+ )
+ target = ledger if isinstance(ledger, CostLedger) else (CostLedger(ledger) if ledger else default_ledger())
+ if target is not None:
+ target.append(row)
+ return row
+
+
+def load_ledger(path: str | Path) -> list[CallCost]:
+ """Read a ledger file (or a directory containing one). Bad lines are skipped
+ with a debug log — a truncated last line never loses the rest of the file."""
+ p = Path(path)
+ if p.is_dir():
+ p = p / LEDGER_NAME
+ if not p.is_file():
+ return []
+ rows: list[CallCost] = []
+ for i, line in enumerate(p.read_text(encoding="utf-8", errors="replace").splitlines()):
+ if not line.strip():
+ continue
+ try:
+ rows.append(CallCost.model_validate_json(line))
+ except Exception as e: # pragma: no cover - defensive
+ log.debug("cost ledger %s:%d unreadable: %s", p, i + 1, e)
+ return rows
+
+
+def _key(row: CallCost, dim: str) -> str:
+ if dim == "round":
+ return "-" if row.round is None else f"r{row.round:02d}"
+ value = getattr(row, dim, "")
+ return str(value) if value != "" else "(none)"
+
+
+def summarise(rows: Iterable[CallCost], *, dimensions: Sequence[str] = DIMENSIONS) -> Summary:
+ """Total + per-dimension buckets. ``dimensions`` may name any scalar field
+ of :class:`CallCost` (defaults to :data:`DIMENSIONS`)."""
+ out = Summary()
+ for row in rows:
+ out.total.add(row)
+ for dim in dimensions:
+ bucket = out.by.setdefault(dim, {}).setdefault(_key(row, dim), CostBucket(key=_key(row, dim)))
+ bucket.add(row)
+ return out
+
+
+def totals_by(rows: Iterable[CallCost], dim: str) -> dict[str, CostBucket]:
+ return summarise(rows, dimensions=(dim,)).dimension(dim)
diff --git a/harness/codeverse/cost/reconstruct.py b/harness/codeverse/cost/reconstruct.py
new file mode 100644
index 00000000..517886c6
--- /dev/null
+++ b/harness/codeverse/cost/reconstruct.py
@@ -0,0 +1,419 @@
+"""Rebuild a cost ledger from an EXISTING run directory.
+
+The harness has been recording ``Usage`` since day one, just not as a ledger:
+per-call rows live in ``trajectories/*/transcript.jsonl``, session totals in
+``result.json``, judge verdicts in ``record.rounds[].judgment.usage``, and the
+plan / texture / pairwise costs only in ``events.jsonl``. This module stitches
+those into :class:`~codeverse.cost.types.CallCost` rows so the audit and
+``3dcv cost`` work on runs recorded *before* the ledger existed.
+
+Nothing here validates against the pydantic ``RunRecord``: old records must keep
+loading even when the schema moves on, so everything is read as raw JSON.
+
+Double-counting rules (same order as the row sources):
+
+1. agent sessions — per-turn rows when a transcript has per-call usage, else one
+ aggregate row from ``result.json``; the label+round is then *covered*;
+2. gemini-cli sessions additionally carry the raw ``stats`` envelope in
+ ``stdout.json`` — with ``recheck=True`` the row is rebuilt from it (per served
+ model, correct cached/prompt split) instead of the stored ``Usage``;
+3. judge verdicts — from the record's rounds (``rNN_cli.json`` re-judges are
+ outside the run's budget and are skipped);
+4. priced events (``plan.done``, ``texture.*``, ``pairwise.done``) that no row
+ above covers — aggregates (``round.done`` / ``run.done`` / ``texture.done``)
+ are skipped;
+5. a final ``residual`` row for whatever ``record.total_usage`` still has left,
+ so the ledger always reconciles to the recorded total.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections.abc import Iterator
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from codeverse.contracts.common import Usage
+from codeverse.cost.ledger import price_call
+from codeverse.cost.types import CallCost, Role, Stage, role_for_stage, stage_for_label
+
+log = logging.getLogger(__name__)
+
+#: events whose cost duplicates rows we already emit
+_AGGREGATE_EVENTS = frozenset({"round.done", "run.done", "texture.done"})
+
+
+def _read_json(path: Path) -> dict[str, Any]:
+ try:
+ data = json.loads(path.read_text(errors="replace"))
+ except (OSError, ValueError):
+ return {}
+ return data if isinstance(data, dict) else {}
+
+
+def _read_jsonl(path: Path) -> Iterator[dict[str, Any]]:
+ try:
+ text = path.read_text(errors="replace")
+ except OSError:
+ return
+ for line in text.splitlines():
+ if not line.strip():
+ continue
+ try:
+ row = json.loads(line)
+ except ValueError:
+ continue
+ if isinstance(row, dict):
+ yield row
+
+
+def _usage(d: Any) -> Usage:
+ if isinstance(d, Usage):
+ return d
+ if not isinstance(d, dict):
+ return Usage()
+ return Usage(
+ backend=str(d.get("backend") or ""),
+ model=str(d.get("model") or ""),
+ input_tokens=int(d.get("input_tokens") or 0),
+ output_tokens=int(d.get("output_tokens") or 0),
+ cached_tokens=int(d.get("cached_tokens") or 0),
+ thoughts_tokens=int(d.get("thoughts_tokens") or 0),
+ tool_calls=int(d.get("tool_calls") or 0),
+ cost_usd=float(d.get("cost_usd") or 0.0),
+ latency_ms=int(d.get("latency_ms") or 0),
+ )
+
+
+@dataclass
+class RunLedger:
+ """Rows of one run plus the metadata a cost report needs."""
+
+ run: str = ""
+ path: Path = Path()
+ track: str = ""
+ language: str = ""
+ generator: str = ""
+ judge_model: str = ""
+ status: str = ""
+ stop_reason: str = ""
+ passed: bool = False
+ baseline_score: float | None = None
+ final_score: float | None = None
+ n_rounds: int = 0
+ round_scores: list[float | None] = field(default_factory=list)
+ gate_errors: list[int] = field(default_factory=list)
+ recorded_usd: float = 0.0
+ wall_s: float = 0.0 # time the run was actually working (budget elapsed / stage+round durations)
+ span_s: float = 0.0 # first to last event — includes time queued behind other runs
+ model_s: float = 0.0
+ budget_usd: float = 0.0
+ parallel: bool = False
+ resumed: bool = False
+ selected_candidate: str = "" # "c1" when the run ran best-of-N and c1 won
+ rows: list[CallCost] = field(default_factory=list)
+ notes: list[str] = field(default_factory=list)
+
+ @property
+ def ledger_usd(self) -> float:
+ return sum(r.cost_usd for r in self.rows)
+
+ @property
+ def harness_s(self) -> float:
+ """Wall clock not spent waiting on a model (build / gates / render / IO).
+ Clamped at 0: parallel stages can make ``model_s`` exceed the wall clock."""
+ return max(0.0, self.wall_s - self.model_s)
+
+
+def _row(usage: Usage, *, run: str, stage: Stage, label: str, rnd: int | None, source: str,
+ role: Role | None = None, ts: float = 0.0, outcome: str = "ok", n_calls: int = 1,
+ reprice: bool = False, backend: str = "", model: str = "") -> CallCost:
+ cost, price_fields = price_call(usage, backend=backend or usage.backend,
+ model=model or usage.model, reprice=reprice)
+ return CallCost(
+ ts=ts, run=run, round=rnd, stage=stage, role=role or role_for_stage(stage), label=label,
+ input_tokens=usage.input_tokens, cached_tokens=usage.cached_tokens,
+ output_tokens=usage.output_tokens, thoughts_tokens=usage.thoughts_tokens,
+ tool_calls=usage.tool_calls, cost_usd=cost, recorded_usd=float(usage.cost_usd),
+ latency_ms=usage.latency_ms,
+ cache_hit=usage.cached_tokens > 0, outcome=outcome, n_calls=n_calls, source=source,
+ **price_fields,
+ )
+
+
+# --------------------------------------------------------------------------- agent sessions
+def _gemini_cli_usages(stdout: dict[str, Any]) -> list[Usage]:
+ """Per served model from a gemini-cli ``stats`` envelope. ``tokens.prompt`` is
+ the TOTAL prompt (cached included) — sessions recorded before that fix stored
+ ``tokens.input`` and under-billed by ~3-4x."""
+ models = (((stdout.get("stats") or {}).get("models")) or {})
+ out: list[Usage] = []
+ for name, part in models.items():
+ tok = (part or {}).get("tokens") or {}
+ cached = int(tok.get("cached") or 0)
+ prompt = tok.get("prompt")
+ total = int(prompt) if prompt is not None else int(tok.get("input") or 0) + cached
+ api = (part or {}).get("api") or {}
+ out.append(Usage(
+ backend="gemini-cli", model=str(name), input_tokens=total, cached_tokens=cached,
+ output_tokens=int(tok.get("candidates") or 0), thoughts_tokens=int(tok.get("thoughts") or 0),
+ tool_calls=int(((stdout.get("stats") or {}).get("tools") or {}).get("totalCalls") or 0),
+ latency_ms=int(api.get("totalLatencyMs") or 0),
+ ))
+ return out
+
+
+def _session_rows(d: Path, run: str, *, recheck: bool,
+ candidate: str = "") -> tuple[list[CallCost], str, int | None, float]:
+ """Rows for one ``trajectories/<label>_rNN`` directory. ``candidate`` is the
+ ``_cand/c<k>`` sub-workspace this session belongs to (best-of-N), if any."""
+ result = _read_json(d / "result.json")
+ label = str(result.get("label") or d.name)
+ rnd = result.get("round")
+ rnd = int(rnd) if isinstance(rnd, (int, float)) else None
+ stage = stage_for_label(str(result.get("kind") or "") if "repair" in str(result.get("kind") or "") else label)
+ if candidate:
+ stage, label = Stage.CANDIDATE, f"{candidate}:{label}"
+ outcome = "ok" if result.get("ok") else str(result.get("exit_reason") or "error")
+ duration = float(result.get("duration_s") or 0.0)
+ session = _usage(result.get("usage"))
+ rows: list[CallCost] = []
+
+ if recheck and session.backend == "gemini-cli":
+ parts = _gemini_cli_usages(_read_json(d / "stdout.json"))
+ if parts:
+ for part in parts:
+ rows.append(_row(part, run=run, stage=stage, label=label, rnd=rnd,
+ source="stdout", outcome=outcome, reprice=True))
+ return rows, label, rnd, duration
+
+ turns = [r for r in _read_jsonl(d / "transcript.jsonl") if isinstance(r.get("usage"), dict)]
+ if turns:
+ for turn in turns:
+ rows.append(_row(_usage(turn["usage"]), run=run, stage=stage, label=label, rnd=rnd,
+ source="transcript", ts=float(turn.get("t") or 0.0), outcome=outcome,
+ reprice=recheck))
+ return rows, label, rnd, duration
+ if session.input_tokens or session.output_tokens or session.cost_usd:
+ n_calls = int(result.get("turns") or 0) or 1
+ rows.append(_row(session, run=run, stage=stage, label=label, rnd=rnd, source="trajectory",
+ outcome=outcome, n_calls=n_calls, reprice=recheck))
+ return rows, label, rnd, duration
+
+
+def _trajectory_dirs(root: Path) -> list[tuple[Path, str]]:
+ """Every session directory of a run as ``(dir, candidate)``, including scene
+ asset sub-workspaces (``_assets/<name>/trajectories/*``) and best-of-N
+ candidates (``_cand/c*``, whose sessions are tagged with the candidate id)."""
+ out: list[tuple[Path, str]] = []
+ for traj in sorted(root.glob("trajectories")) + sorted(root.glob("_assets/*/trajectories")):
+ out += [(p, "") for p in sorted(traj.iterdir()) if p.is_dir()]
+ for traj in sorted(root.glob("_cand/*/trajectories")):
+ cand = traj.parent.name
+ out += [(p, cand) for p in sorted(traj.iterdir()) if p.is_dir()]
+ return out
+
+
+# --------------------------------------------------------------------------- one run
+def reconstruct_run(run_dir: str | Path, *, recheck: bool = False) -> RunLedger:
+ """Build the ledger of one run directory.
+
+ ``recheck=True`` re-prices every row with the CURRENT price table (and rebuilds
+ gemini-cli rows from the raw CLI stats) — that is the audit view; the default
+ keeps the dollars the run was actually billed."""
+ root = Path(run_dir)
+ record = _read_json(root / "record.json")
+ spec = record.get("spec") or {}
+ backends = spec.get("backends") or {}
+ extra = record.get("extra") or {}
+ total = _usage(record.get("total_usage"))
+ run = root.name
+ led = RunLedger(
+ run=run, path=root,
+ track=str(spec.get("track") or ""), language=str(spec.get("language") or ""),
+ generator=str(backends.get("generator") or ""), judge_model=str(backends.get("judge") or ""),
+ status=str(record.get("status") or ""), stop_reason=str(extra.get("stop_reason") or ""),
+ baseline_score=record.get("baseline_score"), final_score=record.get("final_score"),
+ recorded_usd=float(total.cost_usd),
+ budget_usd=float(((spec.get("budget") or {}).get("max_usd")) or 0.0),
+ )
+ cands = _read_json(root / "rounds" / "candidates.json") or (extra.get("candidates") or {})
+ if isinstance(cands, dict) and cands.get("selected") is not None:
+ led.selected_candidate = f"c{cands['selected']}"
+ rounds = record.get("rounds") or []
+ led.n_rounds = len(rounds)
+ led.passed = bool(record.get("status") == "passed")
+
+ covered: dict[str, float] = {} # label -> $ already accounted for by its agent session(s);
+ # a ``generate.done`` event within that budget is a duplicate
+ model_s = 0.0
+
+ for d, cand in _trajectory_dirs(root):
+ rows, label, rnd, duration = _session_rows(d, run, recheck=recheck, candidate=cand)
+ if rows:
+ led.rows += rows
+ covered[label] = covered.get(label, 0.0) + sum(r.recorded_usd for r in rows)
+ model_s += duration
+
+ judged_rounds: set[int] = set()
+ for r in rounds:
+ idx = int(r.get("index") or 0)
+ judgment = r.get("judgment") or {}
+ led.round_scores.append((judgment or {}).get("overall"))
+ led.gate_errors.append(sum(1 for g in (r.get("gates") or [])
+ for f in (g.get("findings") or []) if f.get("severity") == "error"))
+ ju = _usage(judgment.get("usage"))
+ if ju.input_tokens or ju.cost_usd:
+ judged_rounds.add(idx)
+ n = int(judgment.get("n_samples") or 1)
+ degraded = bool((judgment.get("raw") or {}).get("degraded")) if isinstance(judgment.get("raw"), dict) else False
+ led.rows.append(_row(ju, run=run, stage=Stage.JUDGE, label=str(judgment.get("rubric") or "judge"),
+ rnd=idx, source="record", role=Role.JUDGE, n_calls=max(1, n),
+ outcome="degraded" if degraded else "ok", reprice=recheck,
+ backend=str(judgment.get("judge_backend") or ju.backend) or ju.backend,
+ model=str(judgment.get("judge_backend") or ju.model) or ju.model))
+ model_s += ju.latency_ms / 1000.0
+
+ # ------------------------------------------------------------------ events
+ first_t = last_t = 0.0
+ active_s = 0.0
+ n_finishes = 0
+ for ev in _read_jsonl(root / "events.jsonl"):
+ name = str(ev.get("event") or "")
+ t = float(ev.get("t") or 0.0)
+ first_t = first_t or t
+ if name in ("run.done", "run.failed"):
+ n_finishes += 1
+ if name in ("run.done", "run.failed", "stop", "budget.exceeded"):
+ last_t = max(last_t, t) # a post-hoc texture pass is not part of the run's wall clock
+ elif not last_t:
+ last_t = t
+ if name in ("stage.done", "round.done"):
+ active_s += float(ev.get("duration_s") or 0.0)
+ if name == "judge.done":
+ model_s += float(ev.get("duration_s") or 0.0) if int(ev.get("round", -1)) not in judged_rounds else 0.0
+ cost = ev.get("cost_usd")
+ if not isinstance(cost, (int, float)) or not cost or name in _AGGREGATE_EVENTS:
+ continue
+ rnd = ev.get("round")
+ rnd = int(rnd) if isinstance(rnd, (int, float)) else None
+ label = str(ev.get("label") or name.split(".")[0])
+ if name == "generate.done" and covered.get(label, 0.0) >= float(cost) - 0.0005:
+ covered[label] = covered.get(label, 0.0) - float(cost)
+ continue # a session already contributed this spend
+ if name == "judge.done" and rnd in judged_rounds:
+ continue
+ stage = Stage.TEXTURE if name.startswith("texture") else stage_for_label(label)
+ role = Role.IMAGE if name == "texture.generated" else role_for_stage(stage)
+ model = str(ev.get("model") or "")
+ usage = Usage(model=model, cost_usd=float(cost))
+ row = _row(usage, run=run, stage=stage, label=label, rnd=rnd, source=f"event:{name}",
+ role=role, ts=t, model=model)
+ row.price_source = "event-cost" # cost known, tokens are not recorded by the event
+ led.rows.append(row)
+ for ev in _read_jsonl(root / "events.jsonl"):
+ if str(ev.get("event")) == "stage.done" and str(ev.get("stage")) == "plan":
+ model_s += float(ev.get("duration_s") or 0.0)
+
+ led.resumed = n_finishes > 1
+ led.span_s = max(0.0, last_t - first_t)
+ elapsed_min = float(((extra.get("budget") or {}).get("elapsed_min")) or 0.0)
+ # events are emitted from run creation, so the span of a queued bench run counts
+ # hours it spent waiting for a worker slot; the stage/round clocks are the honest
+ # ones (the budget's own elapsed restarts on ``3dcv resume``).
+ led.wall_s = max(active_s, elapsed_min * 60.0) or led.span_s
+ led.model_s = model_s
+ led.parallel = model_s > led.wall_s > 0
+
+ # ------------------------------------------------------------------ residual
+ if total.cost_usd:
+ spent = sum(r.recorded_usd for r in led.rows)
+ tok_in = total.input_tokens - sum(r.input_tokens for r in led.rows)
+ tok_out = total.output_tokens - sum(r.output_tokens for r in led.rows)
+ tok_cached = total.cached_tokens - sum(r.cached_tokens for r in led.rows)
+ gap = total.cost_usd - spent
+ if gap < -0.005:
+ led.notes.append(f"${-gap:.4f} of ledger spend is outside record.total_usage "
+ "(post-run pass, or a round the budget cut before the total was written)")
+ if gap > 0.005 or tok_in > 5000:
+ usage = Usage(backend=total.backend, model=total.model,
+ input_tokens=max(0, tok_in), output_tokens=max(0, tok_out),
+ cached_tokens=max(0, tok_cached), cost_usd=max(0.0, gap))
+ row = _row(usage, run=run, stage=Stage.OTHER, label="unattributed", rnd=None,
+ source="residual", role=Role.OTHER)
+ row.cost_usd = row.recorded_usd = max(0.0, gap)
+ row.price_source = "residual"
+ led.rows.append(row)
+ drift = led.ledger_usd - led.recorded_usd
+ if recheck and abs(drift) > 0.005:
+ led.notes.append(f"re-priced total differs from record.total_usage by ${drift:+.4f}")
+ return led
+
+
+# --------------------------------------------------------------------------- compare cells
+def reconstruct_cell(cell_dir: str | Path, *, recheck: bool = False) -> RunLedger:
+ """A ``bench/compare_backends.py`` one-shot cell (``gen/attempt*`` + ``eval/eval.json``)."""
+ root = Path(cell_dir)
+ cell = _read_json(root / "cell.json")
+ run = f"{root.parent.name}/{root.name}"
+ led = RunLedger(run=run, path=root, track="static_object", language="blender",
+ generator=str(cell.get("arm") or root.name), judge_model=str(cell.get("judge") or ""),
+ status=str(cell.get("status") or ""), passed=bool(cell.get("passed")),
+ final_score=cell.get("score"), n_rounds=1,
+ wall_s=float(cell.get("wall_s") or 0.0), model_s=float(cell.get("gen_seconds") or 0.0))
+ for attempt in sorted(root.glob("gen/attempt*")):
+ result = _read_json(attempt / "result.json")
+ usage = _usage(result.get("usage"))
+ if usage.cost_usd or usage.output_tokens:
+ led.rows.append(_row(usage, run=run, stage=Stage.BASELINE, label="oneshot", rnd=0,
+ source="trajectory", outcome="ok" if result.get("ok") else "error",
+ reprice=recheck))
+ judgment = (_read_json(root / "eval" / "eval.json").get("judgment") or {})
+ ju = _usage(judgment.get("usage"))
+ if ju.cost_usd or ju.input_tokens:
+ led.rows.append(_row(ju, run=run, stage=Stage.JUDGE, label=str(judgment.get("rubric") or "judge"),
+ rnd=0, source="record", role=Role.JUDGE,
+ n_calls=int(judgment.get("n_samples") or 1), reprice=recheck))
+ led.recorded_usd = float(cell.get("gen_cost_usd") or 0.0) + float(cell.get("judge_cost_usd") or 0.0)
+ return led
+
+
+def find_runs(root: str | Path) -> list[Path]:
+ """Every run directory under ``root`` (a dir with ``record.json``), plus one-shot
+ compare cells (a dir with ``cell.json`` and no ``run/record.json``). Nested
+ sub-workspaces (``_assets/``, ``_cand/``) are part of their parent, not runs."""
+ base = Path(root)
+ if (base / "record.json").is_file():
+ return [base]
+ out: list[Path] = []
+ for path in sorted(base.rglob("record.json")):
+ rel = path.parent.relative_to(base).parts
+ if any(p in ("_assets", "_cand") for p in rel):
+ continue
+ d = path.parent
+ if d.name == "run" and (d.parent / "cell.json").is_file():
+ d = d.parent # a compare-battery cell: name it <prompt>/<arm>, not "run"
+ out.append(d)
+ known = {str(p) for p in out}
+ for cell in sorted(base.rglob("cell.json")):
+ d = cell.parent
+ if str(d) in known or (d / "run" / "record.json").is_file():
+ continue
+ if any(p in ("_assets", "_cand") for p in d.relative_to(base).parts):
+ continue
+ out.append(d)
+ return out
+
+
+def reconstruct(path: str | Path, *, recheck: bool = False) -> RunLedger:
+ """Dispatch on what the directory looks like (run record vs compare cell)."""
+ p = Path(path)
+ if (p / "record.json").is_file():
+ return reconstruct_run(p, recheck=recheck)
+ if (p / "run" / "record.json").is_file():
+ led = reconstruct_run(p / "run", recheck=recheck)
+ led.run = f"{p.parent.name}/{p.name}"
+ return led
+ return reconstruct_cell(p, recheck=recheck)
diff --git a/harness/codeverse/cost/report.py b/harness/codeverse/cost/report.py
new file mode 100644
index 00000000..df7dedda
--- /dev/null
+++ b/harness/codeverse/cost/report.py
@@ -0,0 +1,139 @@
+"""Render an :class:`~codeverse.cost.audit.Audit` as markdown or a console table.
+
+Pure formatting: every number comes from the audit, nothing is recomputed here.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+from codeverse.cost.audit import (
+ Audit,
+ cached_input_share,
+ price_confidence,
+ stage_latency,
+ uncached_if_no_cache,
+)
+from codeverse.cost.routing import pro_break_even, routing_table
+from codeverse.cost.types import CostBucket
+
+STAGE_ORDER = ("plan", "skeleton", "assets", "env", "zones", "assemble", "baseline", "candidate",
+ "repair", "refine", "gates", "render", "judge", "pairwise", "texture", "caption", "other")
+
+
+def _usd(x: float) -> str:
+ return f"${x:,.4f}" if abs(x) < 1 else f"${x:,.2f}"
+
+
+def _tok(n: int) -> str:
+ if n >= 1_000_000:
+ return f"{n / 1e6:.2f}M"
+ if n >= 1_000:
+ return f"{n / 1e3:.1f}k"
+ return str(n)
+
+
+def table(headers: Sequence[str], rows: Sequence[Sequence[object]]) -> str:
+ out = ["| " + " | ".join(headers) + " |",
+ "|" + "|".join("---" for _ in headers) + "|"]
+ for r in rows:
+ out.append("| " + " | ".join(str(c) for c in r) + " |")
+ return "\n".join(out)
+
+
+def bucket_rows(buckets: Sequence[CostBucket], total: float) -> list[list[object]]:
+ rows: list[list[object]] = []
+ for b in buckets:
+ rows.append([
+ b.key, _usd(b.cost_usd), f"{100 * b.cost_usd / total:.1f}%" if total else "-",
+ f"{b.n_calls:,}", _tok(b.input_tokens), f"{100 * b.cached_fraction:.0f}%",
+ _tok(b.output_tokens), f"${b.usd_per_1k_tokens:.5f}", f"{b.latency_ms / 3.6e6:.1f} h",
+ ])
+ return rows
+
+
+BUCKET_HEADERS = ("key", "USD", "share", "calls", "input", "cached", "output", "$/1k tok", "model time")
+
+
+def dimension_table(audit: Audit, dim: str, *, limit: int | None = None, order: Sequence[str] = ()) -> str:
+ buckets = audit.summary.ranked(dim, limit=limit)
+ if order:
+ rank = {k: i for i, k in enumerate(order)}
+ buckets.sort(key=lambda b: (rank.get(b.key, len(rank)), -b.cost_usd))
+ return table(BUCKET_HEADERS, bucket_rows(buckets, audit.total_usd))
+
+
+def runs_table(audit: Audit, *, limit: int = 20) -> str:
+ rows = []
+ for r in audit.runs[:limit]:
+ rows.append([r.run, r.track or "-", _usd(r.ledger_usd), r.n_rounds,
+ f"{r.baseline_score:.3f}" if r.baseline_score is not None else "-",
+ f"{r.final_score:.3f}" if r.final_score is not None else "-",
+ r.status, f"{r.wall_s / 60:.1f}", f"{r.model_s / 60:.1f}"])
+ return table(("run", "track", "USD", "rounds", "baseline", "final", "status", "wall min", "model min"), rows)
+
+
+def waste_table(audit: Audit) -> str:
+ rows = [[k, n, _usd(usd), f"{100 * usd / audit.total_usd:.1f}%"]
+ for k, (n, usd) in audit.waste_by_kind().items()]
+ rows.append(["**total**", sum(n for n, _ in audit.waste_by_kind().values()),
+ _usd(audit.waste_total()), f"{100 * audit.waste_total() / audit.total_usd:.1f}%"])
+ return table(("waste", "n", "USD", "share of spend"), rows)
+
+
+def summary_lines(audit: Audit) -> list[str]:
+ cached, total_in, cache_usd = cached_input_share(audit)
+ no_cache = uncached_if_no_cache(audit)
+ return [
+ f"- runs: **{audit.n_runs}** ({audit.n_passed} passed) — total **{_usd(audit.total_usd)}**, "
+ f"{_usd(audit.usd_per_run)} per run, **{_usd(audit.usd_per_passing_artifact)} per passing artifact**",
+ f"- tokens: {_tok(total_in)} input of which **{100 * cached / total_in:.0f}% cached** "
+ f"({_tok(audit.summary.total.output_tokens)} output, {_tok(audit.summary.total.thoughts_tokens)} thoughts)",
+ f"- prompt caching already saves **{_usd(no_cache - audit.total_usd)}** "
+ f"({100 * (1 - audit.total_usd / no_cache):.0f}% of what this traffic would cost uncached); "
+ f"cache reads still cost {_usd(cache_usd)}",
+ f"- clock: {audit.wall_s / 3600:.1f} h of run time, {audit.model_s / 3600:.1f} h of it waiting on models",
+ f"- calls: {audit.summary.total.n_calls:,} model calls, {audit.calls_per_round():.0f} per round",
+ f"- identified waste: **{_usd(audit.waste_total())}** ({100 * audit.waste_total() / audit.total_usd:.0f}% of spend)",
+ ]
+
+
+def markdown(audit: Audit, *, title: str = "Cost audit") -> str:
+ parts: list[str] = [f"# {title}", ""]
+ parts += summary_lines(audit)
+ for dim, heading, order in (("stage", "Per stage", STAGE_ORDER), ("role", "Per role", ()),
+ ("track", "Per track", ()), ("backend", "Per backend", ()),
+ ("model", "Per model", ())):
+ parts += ["", f"## {heading}", "", dimension_table(audit, dim, order=order)]
+ parts += ["", "## Most expensive runs", "", runs_table(audit)]
+ parts += ["", "## Where a dollar bought nothing", "", waste_table(audit)]
+ parts += ["", "## Model time per stage", "",
+ table(("stage", "model hours", "share"),
+ [[k, f"{v / 3600:.2f}", f"{share * 100:.1f}%"] for k, (v, share) in stage_latency(audit).items()])]
+ parts += ["", "## Price confidence", "",
+ table(("price source", "USD"), [[k, _usd(v)] for k, v in price_confidence(audit).items()])]
+ be = pro_break_even()
+ parts += ["", "## Routing", "",
+ table(("role", "model", "$/call", "measured quality", "when"), routing_table()),
+ "",
+ f"Matching the pro judge's precision (σ 0.030) with flash needs "
+ f"**{be['samples_needed']:.0f} samples** = ${be['cheap_matched_usd']:.3f} per verdict "
+ f"vs ${be['pro_usd']:.3f} for one pro verdict — pro is **{be['ratio']:.1f}x cheaper** "
+ f"at equal precision (and flash's rank is anti-correlated with the gates, which sampling cannot fix)."]
+ return "\n".join(parts) + "\n"
+
+
+def console(audit: Audit) -> str:
+ """Compact plain-text version for ``3dcv cost``."""
+ lines = [line.replace("**", "") for line in summary_lines(audit)]
+ lines += ["", "stage:"]
+ for b in audit.summary.ranked("stage"):
+ lines.append(f" {b.key:<12} {_usd(b.cost_usd):>10} {100 * b.cost_usd / audit.total_usd:5.1f}% "
+ f"{b.n_calls:>6,} calls cached {100 * b.cached_fraction:3.0f}%")
+ lines += ["", "role:"]
+ for b in audit.summary.ranked("role"):
+ lines.append(f" {b.key:<12} {_usd(b.cost_usd):>10} {100 * b.cost_usd / audit.total_usd:5.1f}%")
+ lines += ["", "waste:"]
+ for k, (n, usd) in audit.waste_by_kind().items():
+ lines.append(f" {k:<20} {n:>3} {_usd(usd):>10}")
+ return "\n".join(lines)
diff --git a/harness/codeverse/cost/routing.py b/harness/codeverse/cost/routing.py
new file mode 100644
index 00000000..4d25a2ec
--- /dev/null
+++ b/harness/codeverse/cost/routing.py
@@ -0,0 +1,127 @@
+"""Which model should do which job — with the measured trade-off behind it.
+
+Every number in :data:`ROUTES` was measured on this box (see ``docs/COST.md``):
+prices from ``models/pricing.py`` (checked 2026-08-23), $/call from the 61
+recorded runs, judge noise from ``judges/calibration.py`` (n=3 on the e2e
+rounds), generator quality from ``bench/out/compare_v1_live2``.
+
+The one non-obvious result: **a noisy cheap judge is not cheap.** Averaging
+flash to pro's precision needs ``(σ_flash/σ_pro)²`` samples — and even then it
+does not buy pro's *correlation* with the deterministic gates, so a biased rank
+stays biased. :func:`samples_for_precision` and :func:`pro_break_even` do that
+arithmetic for a caller that wants to decide at runtime.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from math import ceil
+
+from codeverse.cost.types import Role
+
+#: judge score noise (std of the overall score over n=3 samples) and the
+#: correlation of the score with deterministic gate errors, per judge model.
+#: Source: ``judges/calibration.py`` on the e2e rounds, 2026-08-23.
+JUDGE_NOISE: dict[str, tuple[float, float]] = {
+ "gemini-3.7-flash": (0.083, -0.33),
+ "gemini-3.1-pro-preview": (0.030, +0.63),
+}
+
+
+@dataclass(frozen=True)
+class Route:
+ """One recommended (role, model) pairing with its measured price and caveat."""
+
+ role: Role
+ model_id: str
+ usd_per_call: float # measured median from the recorded runs
+ quality: str
+ when: str
+ default: bool = False
+
+
+ROUTES: tuple[Route, ...] = (
+ # ---------------------------------------------------------------- planner
+ Route(Role.PLANNER, "gemini:gemini-3.7-flash", 0.013,
+ "plans are structured output; no measured failure attributable to the planner",
+ "always — the plan is 0.8% of a run; a pro planner would double that for no measured gain",
+ default=True),
+ # -------------------------------------------------------------- generator
+ Route(Role.GENERATOR, "api-agent:gemini:gemini-3.7-flash", 0.52,
+ "compare_v1: mean judge 0.835 on easy static objects (best arm measured)",
+ "default for every track that has tools (it is the loop, not the model, that scores)",
+ default=True),
+ Route(Role.GENERATOR, "single-shot:gemini:gemini-3.7-flash", 0.05,
+ "graphics track: 5/6 passed, median 0.810, $0.099 per run",
+ "glsl_shader / opengl_python — one file, compiler feedback, no tool loop needed"),
+ Route(Role.GENERATOR, "gemini-cli:gemini-3.7-flash", 0.73,
+ "compare_v1: 0.827 — statistically the same as api-agent at 2x the price and 2x the wall clock",
+ "only when you need the CLI's own tooling; the api-agent is cheaper for identical quality"),
+ Route(Role.GENERATOR, "codex:gpt-5.6-sol", 1.93,
+ "one-shot 0.786 for $0.20; inside the harness loop $1.93/run (long cached context at $0.40/M)",
+ "strong one-shot baseline; expensive as a loop generator"),
+ Route(Role.GENERATOR, "oneshot:claude-code", 1.04,
+ "compare_v1: 0.673 mean, 0/2 passed — the weakest score per dollar measured here",
+ "not recommended for bulk generation on this battery"),
+ # ------------------------------------------------------------------ judge
+ Route(Role.JUDGE, "gemini:gemini-3.1-pro-preview", 0.060,
+ "σ 0.030, pearson(gate errors, score) +0.63",
+ "every decision that persists: best-round selection, pass/fail, dataset tiering",
+ default=True),
+ Route(Role.JUDGE, "gemini:gemini-3.7-flash", 0.027,
+ "σ 0.083 and pearson −0.33 (anti-correlated with the gates)",
+ "in-loop refine hints only, where a wrong rank costs one round, never for pass/fail"),
+ # ------------------------------------------------------------------ image
+ Route(Role.IMAGE, "gemini:gemini-3.1-flash-image", 0.067,
+ "per 1024² tile; a texture pass is ~2 tiles + plan + gate ≈ $0.13",
+ "texture passes only, and only when the before/after gate can ship the result",
+ default=True),
+ Route(Role.CAPTIONER, "gemini:gemini-3.7-flash", 0.010,
+ "captions are post-hoc and cheap; no measured quality difference worth pro",
+ "always", default=True),
+)
+
+
+def routes_for(role: Role | str) -> list[Route]:
+ r = Role(role) if not isinstance(role, Role) else role
+ return [x for x in ROUTES if x.role is r]
+
+
+def default_route(role: Role | str) -> Route | None:
+ return next((x for x in routes_for(role) if x.default), None)
+
+
+def samples_for_precision(model: str, target_std: float, *, noise: dict[str, tuple[float, float]] | None = None) -> int:
+ """How many samples of ``model`` are needed to reach ``target_std``
+ (σ_eff = σ / √n). Returns 1 when the model is already precise enough."""
+ table = noise or JUDGE_NOISE
+ sigma = table.get(model, (0.0, 0.0))[0]
+ if sigma <= 0 or target_std <= 0 or sigma <= target_std:
+ return 1
+ return int(ceil((sigma / target_std) ** 2))
+
+
+def pro_break_even(
+ *,
+ cheap_model: str = "gemini-3.7-flash",
+ pro_model: str = "gemini-3.1-pro-preview",
+ cheap_usd: float = 0.027,
+ pro_usd: float = 0.060,
+) -> dict[str, float]:
+ """The arithmetic behind "use pro": what matching pro's precision with the
+ cheap judge would cost, per verdict."""
+ pro_sigma = JUDGE_NOISE.get(pro_model, (0.03, 0.0))[0]
+ n = samples_for_precision(cheap_model, pro_sigma)
+ return {
+ "samples_needed": float(n),
+ "cheap_matched_usd": n * cheap_usd,
+ "pro_usd": pro_usd,
+ "pro_is_cheaper_by": n * cheap_usd - pro_usd,
+ "ratio": (n * cheap_usd / pro_usd) if pro_usd else 0.0,
+ }
+
+
+def routing_table() -> list[tuple[str, str, str, str, str]]:
+ """Rows for the report: (role, model, $/call, quality, when)."""
+ return [(str(r.role), r.model_id + (" *" if r.default else ""), f"${r.usd_per_call:.3f}", r.quality, r.when)
+ for r in ROUTES]
diff --git a/harness/codeverse/cost/types.py b/harness/codeverse/cost/types.py
new file mode 100644
index 00000000..bb4dd2fc
--- /dev/null
+++ b/harness/codeverse/cost/types.py
@@ -0,0 +1,279 @@
+"""Typed rows and buckets for the cost ledger / audit.
+
+One :class:`CallCost` = one billable model or agent call. Rows are written
+append-only (``ledger.py``), reconstructed from old runs (``reconstruct.py``)
+and aggregated into :class:`Summary` buckets (``ledger.summarise``).
+
+Nothing here imports the orchestrator or the tracks: the cost package is a
+leaf so any caller (track, judge, texturing, bench script) can use it.
+"""
+
+from __future__ import annotations
+
+from enum import StrEnum
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from codeverse.contracts.common import Usage
+
+
+class Stage(StrEnum):
+ """Where in a run the money was spent. Mirrors the stage/round vocabulary
+ of ``events.jsonl`` (``stage.start``/``generate.done`` labels)."""
+
+ PLAN = "plan"
+ SKELETON = "skeleton"
+ ASSETS = "assets"
+ ENV = "env"
+ ZONES = "zones"
+ ASSEMBLE = "assemble"
+ BASELINE = "baseline"
+ CANDIDATE = "candidate"
+ REPAIR = "repair"
+ REFINE = "refine"
+ GATES = "gates"
+ RENDER = "render"
+ JUDGE = "judge"
+ PAIRWISE = "pairwise"
+ TEXTURE = "texture"
+ CAPTION = "caption"
+ OTHER = "other"
+
+
+class Role(StrEnum):
+ """Which job the model was doing (``Backends`` roles + the image model)."""
+
+ PLANNER = "planner"
+ GENERATOR = "generator"
+ JUDGE = "judge"
+ CAPTIONER = "captioner"
+ IMAGE = "image"
+ OTHER = "other"
+
+
+#: stages whose spend is *deterministic harness work* (no model call at all).
+#: Kept in the enum so latency can be attributed to them from events.
+FREE_STAGES: frozenset[Stage] = frozenset({Stage.SKELETON, Stage.ASSEMBLE, Stage.GATES, Stage.RENDER})
+
+#: label prefix → stage, longest prefix wins (``asset_stone_lantern`` → assets)
+_LABEL_STAGES: tuple[tuple[str, Stage], ...] = (
+ ("asset_", Stage.ASSETS),
+ ("zone_", Stage.ZONES),
+ ("env", Stage.ENV),
+ ("baseline", Stage.BASELINE),
+ ("refine", Stage.REFINE),
+ ("candidate", Stage.CANDIDATE),
+ ("cand", Stage.CANDIDATE),
+ ("plan", Stage.PLAN),
+ ("judge", Stage.JUDGE),
+ ("texture", Stage.TEXTURE),
+ ("caption", Stage.CAPTION),
+)
+
+
+def stage_for_label(label: str) -> Stage:
+ """Map a generation/trajectory label (``refine_drip_tray``, ``r00_baseline_repair1``,
+ ``asset_koi``) to its :class:`Stage`. Repair labels win over the label they repair."""
+ low = (label or "").strip().lower()
+ if not low:
+ return Stage.OTHER
+ if "repair" in low:
+ return Stage.REPAIR
+ best: tuple[int, Stage] | None = None
+ for prefix, stage in _LABEL_STAGES:
+ if low.startswith(prefix) and (best is None or len(prefix) > best[0]):
+ best = (len(prefix), stage)
+ return best[1] if best else Stage.OTHER
+
+
+def role_for_stage(stage: Stage) -> Role:
+ if stage is Stage.PLAN:
+ return Role.PLANNER
+ if stage in (Stage.JUDGE, Stage.PAIRWISE):
+ return Role.JUDGE
+ if stage is Stage.CAPTION:
+ return Role.CAPTIONER
+ if stage in (Stage.ASSETS, Stage.ENV, Stage.ZONES, Stage.BASELINE, Stage.REFINE,
+ Stage.REPAIR, Stage.CANDIDATE):
+ return Role.GENERATOR
+ return Role.OTHER
+
+
+#: agent/backend kind → pricing provider, when the model id carries no ``provider:`` prefix
+_BACKEND_PROVIDER: dict[str, str] = {
+ "gemini": "gemini",
+ "gemini-cli": "gemini",
+ "gemini-image": "gemini",
+ "codex": "openai",
+ "openai": "openai",
+ "claude-code": "anthropic",
+ "anthropic": "anthropic",
+ "agy": "gemini", # Antigravity serves gemini models by default
+ "antigravity": "gemini",
+}
+
+
+def split_model_id(backend: str, model: str) -> tuple[str, str]:
+ """``("api-agent", "gemini:gemini-3.7-flash") -> ("gemini", "gemini-3.7-flash")``.
+
+ Falls back to the backend kind when the id carries no provider prefix
+ (``("codex", "gpt-5.6-sol") -> ("openai", "gpt-5.6-sol")``); an unknown
+ backend yields provider ``""`` so pricing reports the model as unknown
+ instead of guessing a rate."""
+ m = (model or "").strip()
+ if ":" in m:
+ provider, _, rest = m.partition(":")
+ while ":" in rest: # api-agent:gemini:gemini-3.7-flash
+ provider, _, rest = rest.partition(":")
+ return provider.strip().lower(), rest.strip()
+ kind = (backend or "").strip().lower()
+ if kind.startswith("api-agent"):
+ kind = "gemini"
+ return _BACKEND_PROVIDER.get(kind, ""), m
+
+
+#: agent session kinds that are not themselves an API provider
+AGENT_KINDS = frozenset({"api-agent", "gemini-cli", "claude-code", "codex", "agy", "antigravity",
+ "single-shot", "gemini-image"})
+
+
+def normalise_ids(backend: str, model: str) -> tuple[str, str, str]:
+ """``("gemini:gemini-3.1-pro-preview", "")`` → ``(backend, provider, model)`` with
+ one canonical spelling per model, so ``gemini:gemini-3.7-flash`` (judge id) and
+ ``gemini-3.7-flash`` (per-call usage) bucket together."""
+ provider, bare = split_model_id(backend, model)
+ kind = (backend or "").strip().lower()
+ if ":" in kind:
+ kind = kind.split(":", 1)[0]
+ if kind not in AGENT_KINDS:
+ kind = provider or kind
+ return kind, provider, bare
+
+
+class CallCost(BaseModel):
+ """One priced call. Append-only ledger row; every field is JSON-scalar so
+ old rows keep loading when new fields are added (all have defaults)."""
+
+ model_config = ConfigDict(extra="allow") # forward-compatible with newer writers
+
+ ts: float = 0.0
+ run: str = ""
+ round: int | None = None
+ stage: Stage = Stage.OTHER
+ role: Role = Role.OTHER
+ label: str = ""
+ backend: str = ""
+ provider: str = ""
+ model: str = "" # bare model name, canonical (no provider prefix)
+ model_id: str = "" # as reported by the backend ("api-agent:gemini:gemini-3.7-flash")
+
+ input_tokens: int = 0
+ cached_tokens: int = 0
+ output_tokens: int = 0
+ thoughts_tokens: int = 0
+ cache_write_tokens: int = 0
+ tool_calls: int = 0
+
+ price_input: float = 0.0 # USD / 1M
+ price_cached: float = 0.0
+ price_output: float = 0.0
+ price_source: str = "unknown" # exact | prefix:<key> | unknown | provider-reported
+ price_approximate: bool = True
+ price_checked: str = ""
+
+ cost_usd: float = 0.0
+ recorded_usd: float = 0.0 # what the run was billed at the time (before any re-pricing)
+ latency_ms: int = 0
+ cache_hit: bool = False
+ outcome: str = "ok" # ok | error | timeout | budget | degraded | discarded
+ n_calls: int = 1 # >1 when a row aggregates a whole agent session
+ source: str = "live" # live | record | events | transcript | stdout | residual
+
+ @property
+ def uncached_tokens(self) -> int:
+ return max(0, self.input_tokens - min(self.cached_tokens, self.input_tokens))
+
+ @property
+ def total_tokens(self) -> int:
+ return self.input_tokens + self.output_tokens + self.thoughts_tokens
+
+ @property
+ def cached_fraction(self) -> float:
+ return (min(self.cached_tokens, self.input_tokens) / self.input_tokens) if self.input_tokens else 0.0
+
+
+class CostBucket(BaseModel):
+ """Aggregate of many :class:`CallCost` rows under one key."""
+
+ key: str = ""
+ n_calls: int = 0
+ n_rows: int = 0
+ input_tokens: int = 0
+ cached_tokens: int = 0
+ output_tokens: int = 0
+ thoughts_tokens: int = 0
+ tool_calls: int = 0
+ cost_usd: float = 0.0
+ latency_ms: int = 0
+ approximate_usd: float = 0.0 # spend priced from an approximate/unknown row
+
+ def add(self, row: CallCost) -> None:
+ self.n_calls += max(1, row.n_calls)
+ self.n_rows += 1
+ self.input_tokens += row.input_tokens
+ self.cached_tokens += min(row.cached_tokens, row.input_tokens) if row.input_tokens else row.cached_tokens
+ self.output_tokens += row.output_tokens
+ self.thoughts_tokens += row.thoughts_tokens
+ self.tool_calls += row.tool_calls
+ self.cost_usd += row.cost_usd
+ self.latency_ms += row.latency_ms
+ if row.price_approximate or row.price_source in ("unknown", "provider-reported"):
+ self.approximate_usd += row.cost_usd
+
+ @property
+ def uncached_tokens(self) -> int:
+ return max(0, self.input_tokens - self.cached_tokens)
+
+ @property
+ def cached_fraction(self) -> float:
+ return self.cached_tokens / self.input_tokens if self.input_tokens else 0.0
+
+ @property
+ def total_tokens(self) -> int:
+ return self.input_tokens + self.output_tokens + self.thoughts_tokens
+
+ @property
+ def usd_per_1k_tokens(self) -> float:
+ return 1000.0 * self.cost_usd / self.total_tokens if self.total_tokens else 0.0
+
+ @property
+ def usd_per_call(self) -> float:
+ return self.cost_usd / self.n_calls if self.n_calls else 0.0
+
+
+class Summary(BaseModel):
+ """``summarise()`` output: a total plus one bucket map per dimension."""
+
+ total: CostBucket = Field(default_factory=CostBucket)
+ by: dict[str, dict[str, CostBucket]] = Field(default_factory=dict)
+
+ def dimension(self, name: str) -> dict[str, CostBucket]:
+ return self.by.get(name, {})
+
+ def ranked(self, name: str, *, limit: int | None = None) -> list[CostBucket]:
+ rows = sorted(self.dimension(name).values(), key=lambda b: -b.cost_usd)
+ return rows[:limit] if limit else rows
+
+ def share(self, name: str, key: str) -> float:
+ b = self.dimension(name).get(key)
+ return (b.cost_usd / self.total.cost_usd) if b and self.total.cost_usd else 0.0
+
+
+def usage_to_tokens(usage: Usage) -> dict[str, int]:
+ return {
+ "input_tokens": int(usage.input_tokens),
+ "cached_tokens": int(usage.cached_tokens),
+ "output_tokens": int(usage.output_tokens),
+ "thoughts_tokens": int(usage.thoughts_tokens),
+ "tool_calls": int(usage.tool_calls),
+ }
diff --git a/harness/codeverse/flywheel/deliverable.py b/harness/codeverse/flywheel/deliverable.py
new file mode 100644
index 00000000..d6f5a3cc
--- /dev/null
+++ b/harness/codeverse/flywheel/deliverable.py
@@ -0,0 +1,248 @@
+"""``<run>/deliverable/`` — the hand-over folder: what the user actually asked for.
+
+Everything in here is a *copy*, regenerated from the run's own evidence, so the
+folder can be zipped and sent on its own:
+
+* ``src/**`` (+ ``public/**`` for scenes) — the raw code at the BEST round's commit;
+* the canonical artifact — ``object.glb`` (+ ``.stl`` / ``.step`` / textured GLB),
+ or ``robot.urdf`` + ``meshes/*.glb``, or ``frames/*.png`` + ``preview.gif``;
+* ``sheet.png`` — the best round's contact sheet (one picture of the result);
+* ``captions.json`` when the run is captioned;
+* ``manifest.json`` — every file with its role, size and sha256 (mirrored into
+ ``record.deliverable``).
+
+Renders per round, gates, judge verdicts and measurements stay in the evidence
+bucket (``artifacts/`` = ``evidence/``); tokens, prices and settings stay in
+``telemetry/``. Nothing else belongs here.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import os
+import shutil
+from datetime import UTC, datetime
+from pathlib import Path
+
+from codeverse.contracts.common import ENTRY_FILE, Language
+from codeverse.contracts.run import DeliverableFile, RoundRecord, RunDeliverable, RunRecord
+from codeverse.flywheel import _git
+from codeverse.proc import write_json_atomic
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+MAX_FILE_BYTES = 128 * 1024 * 1024
+MAX_TOTAL_BYTES = 512 * 1024 * 1024
+MANIFEST_NAME = "manifest.json"
+#: big binaries (frame stacks, GLBs, GIFs) are hard-linked to the evidence copy when the
+#: filesystem allows it — same bytes, one block on disk, and `cp`/`tar`/`rsync` still
+#: produce a standalone copy. Small files (all code) are always real copies so editing
+#: the hand-over folder can never touch the evidence.
+LINK_MIN_BYTES = 256 * 1024
+
+#: artifact file → role, copied when present (object tracks / articulated / graphics)
+_ARTIFACT_ROLES: tuple[tuple[str, str], ...] = (
+ ("object.glb", "model"),
+ ("object.stl", "model"),
+ ("object.step", "model"),
+ ("object_textured.glb", "model"),
+ ("robot.urdf", "urdf"),
+ ("preview.gif", "preview"),
+ ("frames_sheet.png", "sheet"),
+)
+
+
+class DeliverableError(RuntimeError):
+ """The run has nothing that can be handed over."""
+
+
+def _sha256(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+class _Writer:
+ """Collects files into ``deliverable/`` and remembers role/size/hash."""
+
+ def __init__(self, ws: Workspace):
+ self.ws = ws
+ self.files: list[DeliverableFile] = []
+ self.skipped: dict[str, str] = {}
+ self.total = 0
+
+ def add_bytes(self, rel: str, data: bytes, role: str) -> None:
+ if len(data) > MAX_FILE_BYTES:
+ self.skipped[rel] = f"file too large ({len(data)} bytes)"
+ return
+ if self.total + len(data) > MAX_TOTAL_BYTES:
+ self.skipped[rel] = "deliverable size cap reached"
+ return
+ dest = self.ws.deliverable / rel
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_bytes(data)
+ self.total += len(data)
+ self.files.append(DeliverableFile(path=f"deliverable/{rel}", role=role, bytes=len(data), sha256=_sha256(data)))
+
+ def add_file(self, src: Path, rel: str, role: str) -> bool:
+ if not src.is_file():
+ return False
+ size = src.stat().st_size
+ if size > MAX_FILE_BYTES:
+ self.skipped[rel] = f"file too large ({size} bytes)"
+ return False
+ if self.total + size > MAX_TOTAL_BYTES:
+ self.skipped[rel] = "deliverable size cap reached"
+ return False
+ dest = self.ws.deliverable / rel
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ _place(src, dest)
+ self.total += size
+ self.files.append(DeliverableFile(path=f"deliverable/{rel}", role=role, bytes=size,
+ sha256=_sha256(src.read_bytes())))
+ return True
+
+
+def _place(src: Path, dest: Path) -> None:
+ """Hard-link big binaries, copy everything else (see ``LINK_MIN_BYTES``)."""
+ if src.stat().st_size >= LINK_MIN_BYTES:
+ try:
+ os.link(src, dest)
+ return
+ except OSError: # cross-device, no hard links, already exists
+ pass
+ shutil.copy2(src, dest)
+
+
+def _resolve(ws: Workspace, path: str | None) -> Path | None:
+ if not path:
+ return None
+ p = Path(path)
+ if not p.is_absolute():
+ p = ws.root / p
+ return p if p.is_file() else None
+
+
+def _code_tree(ws: Workspace, rnd: RoundRecord | None) -> tuple[dict[str, bytes], str]:
+ """``src/**`` (+ ``public/**``) at the best round's commit, else the working tree."""
+ if rnd is not None and rnd.commit:
+ try:
+ if _git.commit_exists(ws, rnd.commit):
+ return _git.read_tree_at(ws, rnd.commit), "commit"
+ except _git.GitReadError as e:
+ log.warning("deliverable: git read failed in %s: %s", ws.root, e)
+ try:
+ return _git.read_working_tree(ws), "working_tree"
+ except OSError as e: # pragma: no cover - defensive
+ log.warning("deliverable: working tree unreadable in %s: %s", ws.root, e)
+ return {}, "working_tree"
+
+
+def _copy_artifacts(ws: Workspace, record: RunRecord, w: _Writer) -> None:
+ for name, role in _ARTIFACT_ROLES:
+ w.add_file(ws.artifacts / name, name, role)
+ meshes = ws.artifacts / "meshes"
+ if record.spec.language is Language.URDF_BLENDER and meshes.is_dir():
+ for p in sorted(meshes.glob("*.glb")):
+ w.add_file(p, f"meshes/{p.name}", "mesh")
+ frames = ws.artifacts / "frames"
+ if frames.is_dir():
+ for p in sorted(frames.glob("*.png")):
+ w.add_file(p, f"frames/{p.name}", "frames")
+ tex = record.extra.get("texturing") or {}
+ if tex.get("shipped"):
+ tex_dir = ws.root / str(tex.get("textures_dir") or "artifacts/textures")
+ for p in sorted(tex_dir.glob("*.png")) if tex_dir.is_dir() else []:
+ w.add_file(p, f"textures/{p.name}", "texture")
+
+
+def _copy_sheet(ws: Workspace, rnd: RoundRecord | None, w: _Writer) -> None:
+ sheet = _resolve(ws, rnd.renders.contact_sheet) if (rnd is not None and rnd.renders is not None) else None
+ if sheet is not None:
+ w.add_file(sheet, f"sheet{sheet.suffix or '.png'}", "sheet")
+
+
+def _copy_captions(ws: Workspace, record: RunRecord, w: _Writer) -> None:
+ caps = record.extra.get("captions") or {}
+ if not caps.get("detailed"):
+ side = ws.root / "captions.json"
+ if side.is_file():
+ w.add_file(side, "captions.json", "captions")
+ return
+ return
+ keys = ("detailed", "instruction", "factory")
+ w.add_bytes("captions.json", json.dumps({k: str(caps.get(k, "") or "") for k in keys},
+ indent=2, ensure_ascii=False).encode(), "captions")
+
+
+def _stable_timestamp(previous: RunDeliverable | None, current: RunDeliverable) -> datetime:
+ """Keep the old timestamp when the content is byte-identical, so re-running the
+ packager (or the migration) is a no-op instead of a diff."""
+ if previous is None or previous.generated_at is None:
+ return current.generated_at or datetime.now(UTC)
+ same = {(f.path, f.sha256) for f in previous.files if f.role != "manifest"} == {
+ (f.path, f.sha256) for f in current.files}
+ return previous.generated_at if same else (current.generated_at or datetime.now(UTC))
+
+
+def build_deliverable(ws: Workspace, record: RunRecord, *, clean: bool = True) -> RunDeliverable:
+ """(Re)build ``<run>/deliverable/`` and return the typed manifest.
+
+ Idempotent: the folder is rebuilt from scratch every time, so a second call
+ on an unchanged run produces byte-identical content."""
+ from codeverse.flywheel.record import best_round_index
+
+ idx = best_round_index(record)
+ rnd = next((r for r in record.rounds if r.index == idx), None)
+ previous = load_deliverable(ws) if ws.deliverable_manifest_path.is_file() else None
+ if clean and ws.deliverable.exists():
+ shutil.rmtree(ws.deliverable)
+ ws.ensure_layout()
+ w = _Writer(ws)
+ files, code_source = _code_tree(ws, rnd)
+ for rel, data in sorted(files.items()):
+ w.add_bytes(rel, data, "code" if rel.startswith("src/") else "bundle")
+ _copy_artifacts(ws, record, w)
+ _copy_sheet(ws, rnd, w)
+ _copy_captions(ws, record, w)
+ entry = ENTRY_FILE.get(record.spec.language, "")
+ manifest = RunDeliverable(
+ best_round=idx, commit=(rnd.commit if rnd is not None else ""), code_source=code_source,
+ entry=f"deliverable/{entry}" if entry in files else "",
+ files=sorted(w.files, key=lambda f: f.path), total_bytes=w.total, skipped=w.skipped,
+ generated_at=datetime.now(UTC),
+ )
+ manifest.generated_at = _stable_timestamp(previous, manifest)
+ payload = manifest.model_dump(mode="json")
+ write_json_atomic(ws.deliverable_manifest_path, payload)
+ manifest.files.append(DeliverableFile(
+ path=f"deliverable/{MANIFEST_NAME}", role="manifest",
+ bytes=ws.deliverable_manifest_path.stat().st_size,
+ sha256=_sha256(ws.deliverable_manifest_path.read_bytes())))
+ return manifest
+
+
+def load_deliverable(ws: Workspace, record: RunRecord | None = None) -> RunDeliverable | None:
+ """``record.deliverable`` when present, else ``deliverable/manifest.json``, else None."""
+ if record is not None and record.deliverable is not None:
+ return record.deliverable
+ path = ws.deliverable_manifest_path
+ if not path.is_file():
+ return None
+ try:
+ return RunDeliverable.model_validate_json(path.read_text())
+ except Exception as e:
+ log.warning("unreadable deliverable manifest in %s: %s", ws.root, e)
+ return None
+
+
+def deliverable_path(ws: Workspace, name: str) -> Path | None:
+ """``deliverable/<name>`` when it exists, else ``artifacts/<name>``, else None.
+
+ The one resolver every consumer (export, gallery, show) uses so both layouts
+ work: new runs answer from the hand-over folder, old runs from artifacts/."""
+ for candidate in (ws.deliverable / name, ws.artifacts / name):
+ if candidate.is_file():
+ return candidate
+ return None
diff --git a/harness/codeverse/flywheel/gallery.py b/harness/codeverse/flywheel/gallery.py
index dd9fe355..2c6affb2 100644
--- a/harness/codeverse/flywheel/gallery.py
+++ b/harness/codeverse/flywheel/gallery.py
@@ -20,9 +20,10 @@ from typing import Any
from pydantic import BaseModel, Field
from codeverse.contracts.run import RunRecord
+from codeverse.flywheel.deliverable import load_deliverable
from codeverse.flywheel.quality import quality_tier
from codeverse.flywheel.record import effective_judgment, iter_runs
-from codeverse.flywheel.sample import best_round_record, gate_error_summary
+from codeverse.flywheel.sample import best_round_record, gate_error_summary, telemetry_digest
from codeverse.workspace import Workspace
THUMB_PX = 640
@@ -50,6 +51,8 @@ class GalleryItem(BaseModel):
error: str = ""
group: str = Field(default="", description="bench tier / category label shown on the card")
caption: str = Field(default="", description="instruction caption when available")
+ cost_by_stage: dict[str, float] = Field(default_factory=dict, description="stage → USD (telemetry, when present)")
+ models: dict[str, str] = Field(default_factory=dict, description="role → model id (telemetry, when present)")
sheet: str | None = Field(default=None, description="contact sheet path (best round)")
links: dict[str, str] = Field(default_factory=dict, description="label → absolute path")
@@ -64,14 +67,23 @@ def item_from_run(ws: Workspace, rec: RunRecord) -> GalleryItem:
p = Path(rnd.renders.contact_sheet)
p = p if p.is_absolute() else ws.root / p
sheet = str(p) if p.is_file() else None
+ if sheet is None and (ws.deliverable / "sheet.png").is_file():
+ sheet = str(ws.deliverable / "sheet.png") # new layout: the packaged best sheet
links = {"workspace": str(ws.root), "record.json": str(ws.record_path)}
if sheet:
links["sheet"] = sheet
+ deliverable = load_deliverable(ws, rec)
+ if deliverable is not None and ws.deliverable.is_dir():
+ links["deliverable/"] = str(ws.deliverable)
for name in ("object.glb", "robot.urdf", "object.stl"):
- if (ws.artifacts / name).is_file():
- links[name] = str(ws.artifacts / name)
+ path = next((d / name for d in (ws.deliverable, ws.artifacts) if (d / name).is_file()), None)
+ if path is not None:
+ links[name] = str(path)
if (ws.root / "src").is_dir():
links["src/"] = str(ws.root / "src")
+ if ws.cost_path.is_file():
+ links["cost.json"] = str(ws.cost_path)
+ digest = telemetry_digest(ws, rec)
minutes = ((rec.finished_at - rec.started_at).total_seconds() / 60.0) if rec.finished_at else None
caps = rec.extra.get("captions") or {}
return GalleryItem(
@@ -84,7 +96,10 @@ def item_from_run(ws: Workspace, rec: RunRecord) -> GalleryItem:
quality_tier=quality_tier(passed=j.passed if j else None, gate_errors=n_err, score=j.overall if j else None),
gate_errors=n_err, cost_usd=rec.total_usage.cost_usd, rounds=len(rec.rounds), best_round=rec.best_round,
minutes=round(minutes, 1) if minutes is not None else None, status=rec.status.value, error=rec.error,
- caption=str(caps.get("instruction", "") or ""), sheet=sheet, links=links,
+ caption=str(caps.get("instruction", "") or ""),
+ cost_by_stage={k: round(v, 4) for k, v in (digest.get("by_stage") or {}).items()},
+ models=dict(digest.get("models") or {}),
+ sheet=sheet, links=links,
)
@@ -132,6 +147,9 @@ def _card(it: GalleryItem, *, thumb_px: int) -> str:
err = f'<div class="err">{html.escape(it.error[:300])}</div>' if it.error else ""
cap = f'<div class="cap">{html.escape(it.caption)}</div>' if it.caption else ""
mins = f" · {it.minutes:.1f} min" if it.minutes is not None else ""
+ stage_costs = " · ".join(f"{html.escape(k)} ${v:.3f}"
+ for k, v in sorted(it.cost_by_stage.items(), key=lambda kv: -kv[1]))
+ stages = f'<div class="kv">cost: {stage_costs}</div>' if stage_costs else ""
return (
f'<div class="card {badge}" data-track="{html.escape(it.track)}" data-tier="{it.quality_tier}" '
f'data-score="{it.score if it.score is not None else -1}" data-cost="{it.cost_usd}" data-key="{html.escape(it.key)}">'
@@ -142,7 +160,7 @@ def _card(it: GalleryItem, *, thumb_px: int) -> str:
f'<div class="kv">{html.escape(it.track)} · {html.escape(it.language)} · {html.escape(it.generator)}{grp}</div>'
f'<div class="kv">baseline {_fmt(it.baseline_score)} → best {_fmt(it.score)} (r{it.best_round if it.best_round is not None else "-"}) · '
f'rounds {it.rounds} · gate err {it.gate_errors} · ${it.cost_usd:.2f}{mins} · {html.escape(it.status)}</div>'
- f'{err}<div class="links">{links}</div></div></div>'
+ f'{stages}{err}<div class="links">{links}</div></div></div>'
)
diff --git a/harness/codeverse/flywheel/migrate.py b/harness/codeverse/flywheel/migrate.py
new file mode 100644
index 00000000..c072b8fa
--- /dev/null
+++ b/harness/codeverse/flywheel/migrate.py
@@ -0,0 +1,138 @@
+"""Move an existing run directory onto the three-bucket layout, in place.
+
+``migrate_runs(runs_dir)`` walks every run under ``runs_dir`` and, for each:
+
+1. creates the buckets + navigation aliases (``deliverable/``, ``telemetry/``,
+ ``evidence`` → ``artifacts``, ``telemetry/{events.jsonl,run_state.json,stages,
+ trajectories}`` → the root files) — nothing is moved, so every path stored in
+ an old ``record.json`` keeps resolving;
+2. builds ``deliverable/`` from the best round and ``telemetry/`` from the
+ trajectories + judge verdicts + events already on disk;
+3. adds the ``telemetry`` / ``deliverable`` blocks to ``record.json``.
+
+It never deletes evidence, never rewrites ``src/`` and never touches the git
+history. Running it twice is a no-op (second pass reports ``up_to_date``).
+"""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+
+from pydantic import BaseModel, Field
+
+from codeverse.flywheel.record import RecordError, load_record, package_run
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+MIGRATED = "migrated"
+UP_TO_DATE = "up_to_date"
+SKIPPED = "skipped"
+FAILED = "failed"
+
+
+class RunMigration(BaseModel):
+ """What happened to one run directory."""
+
+ run: str
+ status: str = UP_TO_DATE
+ layout: dict[str, str] = Field(default_factory=dict, description="path → created | relinked | kept | skipped:…")
+ gitignore: bool = False
+ deliverable_files: int | None = None
+ deliverable_bytes: int = 0
+ telemetry_rows: int | None = None
+ record_updated: bool = False
+ reason: str = ""
+
+
+class MigrationReport(BaseModel):
+ runs_dir: str
+ dry_run: bool = False
+ n_runs: int = 0
+ n_migrated: int = 0
+ n_up_to_date: int = 0
+ n_skipped: int = 0
+ n_failed: int = 0
+ runs: list[RunMigration] = Field(default_factory=list)
+
+ def add(self, m: RunMigration) -> RunMigration:
+ self.runs.append(m)
+ self.n_runs += 1
+ setattr(self, f"n_{m.status}", getattr(self, f"n_{m.status}") + 1)
+ return m
+
+
+def migrate_run(ws: Workspace, *, dry_run: bool = False) -> RunMigration:
+ """Reorganise one run in place; idempotent, additive, never destructive."""
+ m = RunMigration(run=str(ws.root))
+ if not ws.exists():
+ m.status = SKIPPED
+ m.reason = "no spec.json"
+ return m
+ changed = False
+ try:
+ m.layout = ws.ensure_layout(dry_run=dry_run)
+ m.gitignore = ws.ensure_gitignore(dry_run=dry_run)
+ except OSError as e:
+ m.status = FAILED
+ m.reason = f"{type(e).__name__}: {e}"
+ return m
+ changed = bool(m.layout) or m.gitignore
+ try:
+ record = load_record(ws)
+ except RecordError as e:
+ m.status = MIGRATED if changed else UP_TO_DATE
+ m.reason = str(e) # layout only: an unfinished run has no record yet
+ return m
+ if dry_run:
+ m.telemetry_rows = _row_count(ws, record)
+ m.deliverable_files = None
+ m.status = MIGRATED if (changed or record.telemetry is None or record.deliverable is None) else UP_TO_DATE
+ return m
+ before = ws.record_path.read_bytes()
+ package_run(ws, record)
+ if record.deliverable is not None:
+ m.deliverable_files = len(record.deliverable.files)
+ m.deliverable_bytes = record.deliverable.total_bytes
+ if record.telemetry is not None and record.telemetry.cost is not None:
+ m.telemetry_rows = record.telemetry.cost.n_calls
+ ws.write_json(ws.record_path, record)
+ m.record_updated = ws.record_path.read_bytes() != before
+ m.status = MIGRATED if (changed or m.record_updated) else UP_TO_DATE
+ return m
+
+
+def _row_count(ws: Workspace, record: object) -> int | None:
+ """Per-call rows the ledger would write (dry-run reporting only)."""
+ from codeverse.flywheel.telemetry import ledger_rows
+
+ try:
+ rows, _source = ledger_rows(ws)
+ except Exception as e: # noqa: BLE001
+ log.debug("row count failed for %s: %s", ws.root, e)
+ return None
+ return len(rows)
+
+
+def iter_run_dirs(runs_dir: Path | str) -> list[Path]:
+ """Run directories under ``runs_dir`` (a run = a dir with ``spec.json``);
+ ``runs_dir`` itself when it is a single run."""
+ root = Path(runs_dir)
+ if not root.is_dir():
+ raise FileNotFoundError(f"runs dir not found: {root}")
+ if (root / "spec.json").is_file():
+ return [root]
+ return sorted(d for d in root.iterdir() if d.is_dir() and (d / "spec.json").is_file())
+
+
+def migrate_runs(runs_dir: Path | str, *, dry_run: bool = False) -> MigrationReport:
+ """Migrate every run under ``runs_dir``; returns a per-run report."""
+ rep = MigrationReport(runs_dir=str(runs_dir), dry_run=dry_run)
+ for d in iter_run_dirs(runs_dir):
+ try:
+ rep.add(migrate_run(Workspace(d), dry_run=dry_run))
+ except Exception as e: # noqa: BLE001 - one bad run must not stop the batch
+ log.warning("migration failed for %s: %s", d, e)
+ rep.add(RunMigration(run=str(d), status=FAILED, reason=f"{type(e).__name__}: {e}"))
+ return rep
diff --git a/harness/codeverse/flywheel/record.py b/harness/codeverse/flywheel/record.py
index 49543b1f..f7a43ce5 100644
--- a/harness/codeverse/flywheel/record.py
+++ b/harness/codeverse/flywheel/record.py
@@ -3,8 +3,10 @@
``finalize_record`` is the last step of every track run: it fills the
environment (tool versions + harness git sha), derives best/baseline/final
scores and totals when the track left them empty, adds a compact per-round
-summary under ``record.extra["rounds_summary"]`` and writes ``record.json``
-atomically.
+summary under ``record.extra["rounds_summary"]``, packages the run
+(``deliverable/`` + ``telemetry/``, see docs/RUN_LAYOUT.md) and writes
+``record.json`` atomically. Packaging is best-effort: a run is never failed
+by it.
"""
from __future__ import annotations
@@ -57,8 +59,17 @@ def _harness_git_sha() -> str:
return proc.stdout.strip() if proc.returncode == 0 else ""
-def _three_version() -> str:
- pkg = get_settings().runtime_js_dir() / "node_modules" / "three" / "package.json"
+def _chrome_version() -> str:
+ """Chrome build from the puppeteer cache directory name (offline, no launch)."""
+ cache = Path.home() / ".cache" / "puppeteer" / "chrome"
+ if not cache.is_dir():
+ return ""
+ builds = sorted(p.name for p in cache.iterdir() if p.is_dir())
+ return builds[-1] if builds else ""
+
+
+def _node_pkg_version(name: str) -> str:
+ pkg = get_settings().runtime_js_dir() / "node_modules" / name / "package.json"
if not pkg.is_file():
return ""
try:
@@ -82,7 +93,9 @@ def environment_versions() -> dict[str, str]:
env["blender"] = _cmd_first_line([blender, "--version"]) if blender else ""
env["blender_path"] = blender
env["node"] = _cmd_first_line([s.binaries.node, "--version"])
- env["three"] = _three_version()
+ env["three"] = _node_pkg_version("three")
+ env["puppeteer"] = _node_pkg_version("puppeteer")
+ env["chrome"] = _chrome_version()
return env
@@ -178,10 +191,35 @@ def fill_derived(record: RunRecord) -> RunRecord:
# --------------------------------------------------------------------------- io
-def finalize_record(ws: Workspace, record: RunRecord) -> Path:
- """Fill derived fields + environment and write ``record.json`` atomically."""
+def package_run(ws: Workspace, record: RunRecord) -> None:
+ """Materialise ``deliverable/`` + ``telemetry/`` and mirror them onto the record.
+
+ Best-effort by contract: a packaging failure is logged and the run still
+ gets its ``record.json`` (the old layout is always enough to read a run)."""
+ from codeverse.flywheel.deliverable import build_deliverable
+ from codeverse.flywheel.telemetry import build_telemetry
+
+ try:
+ ws.ensure_layout()
+ except OSError as e: # read-only mount, exotic filesystem
+ log.warning("run layout not created in %s: %s", ws.root, e)
+ return
+ try:
+ record.deliverable = build_deliverable(ws, record)
+ except Exception as e: # noqa: BLE001 - never fail a finished run over packaging
+ log.warning("deliverable not built for %s: %s", ws.root, e)
+ try:
+ record.telemetry = build_telemetry(ws, record)
+ except Exception as e: # noqa: BLE001
+ log.warning("telemetry not written for %s: %s", ws.root, e)
+
+
+def finalize_record(ws: Workspace, record: RunRecord, *, package: bool = True) -> Path:
+ """Fill derived fields + environment, package the run and write ``record.json``."""
record.workspace = record.workspace or str(ws.root)
fill_derived(record)
+ if package:
+ package_run(ws, record)
ws.write_json(ws.record_path, record)
return ws.record_path
diff --git a/harness/codeverse/flywheel/sample.py b/harness/codeverse/flywheel/sample.py
index d161611c..0d1fab09 100644
--- a/harness/codeverse/flywheel/sample.py
+++ b/harness/codeverse/flywheel/sample.py
@@ -33,6 +33,7 @@ from codeverse.contracts.common import (
from codeverse.contracts.run import RoundRecord, RunRecord
from codeverse.flywheel import _git
from codeverse.flywheel.dedupe import code_fingerprint
+from codeverse.flywheel.deliverable import deliverable_path
from codeverse.flywheel.quality import QualityTier, prompt_hash, quality_tier
from codeverse.flywheel.record import best_round_index, effective_judgment, round_summary
from codeverse.workspace import Workspace
@@ -100,7 +101,7 @@ class SampleMeta(BaseModel):
rounds_summary: list[dict[str, Any]] = Field(default_factory=list, description="compact per-round digest")
stop_reason: str = ""
code_commit: str = ""
- code_source: str = Field(default="commit", description="commit | working_tree")
+ code_source: str = Field(default="commit", description="commit | deliverable | working_tree")
code_fingerprint: str = Field(default="", description="sha256 of the normalised src/** tree")
prompt_hash: str = ""
status: str = ""
@@ -111,6 +112,9 @@ class SampleMeta(BaseModel):
has_captions: bool = False
captioner: str = ""
prompt_hashes: dict[str, str] = Field(default_factory=dict)
+ telemetry: dict[str, Any] = Field(
+ default_factory=dict,
+ description="compact accounting digest from record.telemetry / telemetry/cost.json ({} when absent)")
def sample_key(ws: Workspace) -> str:
@@ -135,13 +139,30 @@ def _resolve(ws: Workspace, p: str | None) -> Path | None:
def code_files_for_round(ws: Workspace, rnd: RoundRecord | None) -> tuple[dict[str, bytes], str]:
- """Raw code tree for a round → ``(files, source)`` where source is
- ``commit`` or ``working_tree`` (fallback when the round has no usable commit)."""
+ """Raw code tree for a round → ``(files, source)`` where source is ``commit``,
+ ``deliverable`` (the packaged snapshot of the best round) or ``working_tree``."""
if rnd is not None and rnd.commit and _git.commit_exists(ws, rnd.commit):
return _git.read_tree_at(ws, rnd.commit), "commit"
+ packaged = _deliverable_code(ws)
+ if packaged:
+ return packaged, "deliverable"
return _git.read_working_tree(ws), "working_tree"
+def _deliverable_code(ws: Workspace) -> dict[str, bytes]:
+ """``deliverable/src|public/**`` — the snapshot kept when git is unreadable
+ (a run copied without its .git, an archived deliverable)."""
+ files: dict[str, bytes] = {}
+ for root in _git.CODE_ROOTS:
+ base = ws.deliverable / root
+ if not base.is_dir():
+ continue
+ for p in sorted(base.rglob("*")):
+ if p.is_file():
+ files[p.relative_to(ws.deliverable).as_posix()] = p.read_bytes()
+ return files
+
+
def write_code_tree(dest: Path, files: dict[str, bytes], language: Language) -> tuple[str, list[str]]:
"""Write ``src/**`` + ``code.<ext>`` (+ ``robot.urdf``); return (entry, written paths)."""
written: list[str] = []
@@ -192,11 +213,14 @@ def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str
tt = _resolve(ws, rnd.renders.turntable)
if tt is not None:
_cp(tt, f"turntable{tt.suffix or '.mp4'}")
- glb = ws.artifacts / "object.glb"
- if glb.is_file() and glb.stat().st_size < MAX_GLB_BYTES:
+ if not any(o.startswith("renders/sheet") for o in out):
+ packaged = ws.deliverable / "sheet.png" # new layout keeps the best sheet here
+ _cp(packaged if packaged.is_file() else None, "sheet.png")
+ glb = deliverable_path(ws, "object.glb")
+ if glb is not None and glb.stat().st_size < MAX_GLB_BYTES:
_cp(glb, "object.glb")
- gif = ws.artifacts / "preview.gif" # graphics runs: animated loop preview
- if gif.is_file() and gif.stat().st_size < MAX_GLB_BYTES:
+ gif = deliverable_path(ws, "preview.gif") # graphics runs: animated loop preview
+ if gif is not None and gif.stat().st_size < MAX_GLB_BYTES:
_cp(gif, "preview.gif")
return out
@@ -209,13 +233,14 @@ def copy_textured(ws: Workspace, record: RunRecord, dest: Path) -> list[str]:
return []
out: list[str] = []
tex_dir = ws.root / str(tex.get("textures_dir") or "artifacts/textures")
+ if not tex_dir.is_dir() and (ws.deliverable / "textures").is_dir():
+ tex_dir = ws.deliverable / "textures" # packaged copy (new layout)
if tex_dir.is_dir():
for p in sorted(tex_dir.glob("*.png")):
(dest / "textures").mkdir(parents=True, exist_ok=True)
shutil.copy2(p, dest / "textures" / p.name)
out.append(f"textures/{p.name}")
- glb = _resolve(ws, str(tex.get("glb_textured") or "")) or (
- ws.artifacts / "object_textured.glb" if (ws.artifacts / "object_textured.glb").is_file() else None)
+ glb = _resolve(ws, str(tex.get("glb_textured") or "")) or deliverable_path(ws, "object_textured.glb")
if glb is not None and glb.stat().st_size < MAX_GLB_BYTES:
(dest / "renders").mkdir(parents=True, exist_ok=True)
shutil.copy2(glb, dest / "renders" / "object_textured.glb")
@@ -224,9 +249,10 @@ def copy_textured(ws: Workspace, record: RunRecord, dest: Path) -> list[str]:
def copy_link_meshes(ws: Workspace, dest: Path) -> list[str]:
- """(urdf_blender) copy ``artifacts/meshes/*.glb`` so the sample's robot.urdf resolves."""
- src = ws.artifacts / "meshes"
- if not src.is_dir():
+ """(urdf_blender) copy the per-link meshes so the sample's robot.urdf resolves
+ (``deliverable/meshes/`` on the new layout, ``artifacts/meshes/`` on the old)."""
+ src = next((d for d in (ws.deliverable / "meshes", ws.artifacts / "meshes") if d.is_dir()), None)
+ if src is None:
return []
out: list[str] = []
total = 0
@@ -314,9 +340,38 @@ def build_meta(
has_captions=bool(caps.get("detailed")),
captioner=str((caps.get("provenance") or {}).get("captioner", "")),
prompt_hashes=dict(record.prompt_hashes),
+ telemetry=telemetry_digest(ws, record),
)
+def telemetry_digest(ws: Workspace, record: RunRecord) -> dict[str, Any]:
+ """The few accounting numbers a dataset consumer wants inline: total, per stage,
+ model + thinking level per role, rubric/price hashes. ``{}`` when a run has no
+ telemetry (old layout and nothing computable)."""
+ from codeverse.flywheel.telemetry import load_telemetry
+
+ tele = load_telemetry(ws, record)
+ if tele is None:
+ return {}
+ out: dict[str, Any] = {}
+ if tele.cost is not None:
+ out.update({
+ "total_usd": tele.cost.total_usd,
+ "wall_clock_s": tele.cost.wall_clock_s,
+ "n_calls": tele.cost.n_calls,
+ "by_stage": {s.stage: s.cost_usd for s in tele.cost.by_stage},
+ "by_model": dict(tele.cost.by_model),
+ })
+ if tele.settings is not None:
+ out.update({
+ "models": {r.role: r.model for r in tele.settings.roles},
+ "thinking": {r.role: r.thinking for r in tele.settings.roles if r.thinking},
+ "rubric_hash": tele.settings.rubric_hash,
+ "price_table_version": tele.settings.price_table_version,
+ })
+ return out
+
+
def best_round_record(record: RunRecord) -> RoundRecord | None:
idx = best_round_index(record)
return next((r for r in record.rounds if r.index == idx), None)
diff --git a/harness/codeverse/flywheel/telemetry.py b/harness/codeverse/flywheel/telemetry.py
new file mode 100644
index 00000000..f9ddda49
--- /dev/null
+++ b/harness/codeverse/flywheel/telemetry.py
@@ -0,0 +1,377 @@
+"""Run telemetry: the resolved settings snapshot + the money ledger.
+
+Three files under ``<run>/telemetry/`` (see docs/RUN_LAYOUT.md):
+
+* ``settings.json`` — how the run was configured: model id per role, thinking
+ level / temperature / judge samples, rounds + budget, rubric and its content
+ hash, prompt & cookbook hashes, tool versions, harness git sha, key-pool size,
+ price-table hash, render + limit settings.
+* ``usage.jsonl`` — one priced row per model call. The rows are
+ ``codeverse.cost`` ledger rows (``CallCost``): the live ledger of the run when
+ it has one, else ``cost.reconstruct.reconstruct_run`` rebuilds them from the
+ trajectories, judge verdicts and priced events. There is exactly one ledger
+ in the harness; this bucket only gives it a stable place in the run directory.
+* ``cost.json`` — the run-layout summary of those rows: totals, per stage, per
+ role, per model, per round, budget vs spent, wall clock.
+
+The same content is mirrored into ``record.telemetry`` so a consumer that only
+has ``record.json`` sees it too. Nothing here is required for a run to
+succeed: every builder degrades to "what could be read".
+"""
+
+from __future__ import annotations
+
+import hashlib
+import inspect
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any
+
+from codeverse.contracts.common import TRACK_INFO
+from codeverse.contracts.run import (
+ CostSummary,
+ RoleSettings,
+ RunRecord,
+ RunTelemetry,
+ SettingsSnapshot,
+ StageCost,
+)
+from codeverse.proc import write_json_atomic
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+
+# --------------------------------------------------------------------------- settings snapshot
+def price_table_version() -> str:
+ """Content hash of the USD price table — the run was costed with THIS table."""
+ try:
+ from codeverse.models.pricing import PRICES
+
+ payload = json.dumps(
+ {f"{p}/{m}": [v.input, v.output, v.cached, v.cache_write, v.approximate] for (p, m), v in sorted(PRICES.items())},
+ sort_keys=True,
+ )
+ except Exception as e: # pragma: no cover - defensive
+ log.debug("price table unavailable: %s", e)
+ return ""
+ return hashlib.sha256(payload.encode()).hexdigest()[:12]
+
+
+def backend_kind(model_id: str) -> str:
+ """``api-agent:gemini:gemini-3.7-flash`` → ``api-agent``; ``gemini:x`` → ``gemini``."""
+ return model_id.split(":", 1)[0] if ":" in model_id else model_id
+
+
+def _sig_default(fn: Any, name: str) -> Any:
+ try:
+ param = inspect.signature(fn).parameters[name]
+ except (TypeError, ValueError, KeyError): # pragma: no cover - defensive
+ return None
+ return None if param.default is inspect.Parameter.empty else param.default
+
+
+def _judge_defaults() -> dict[str, Any]:
+ try:
+ from codeverse.judges.vlm_judge import VlmJudge
+ except Exception: # pragma: no cover - sub-package missing
+ return {}
+ init = VlmJudge.__init__
+ return {"temperature": _sig_default(init, "temperature"), "thinking": _sig_default(init, "thinking"),
+ "n_samples": _sig_default(init, "n_samples")}
+
+
+def _planner_defaults() -> dict[str, Any]:
+ try:
+ from codeverse.tracks.planner import plan
+ except Exception: # pragma: no cover
+ return {}
+ return {"temperature": _sig_default(plan, "temperature")}
+
+
+def _generator_defaults(model_id: str) -> dict[str, Any]:
+ """Only the in-process ``api-agent`` exposes sampling knobs; CLI agents own theirs."""
+ if backend_kind(model_id) != "api-agent":
+ return {}
+ try:
+ from codeverse.contracts.agent import ApiAgentOptions
+ except Exception: # pragma: no cover
+ return {}
+ o = ApiAgentOptions()
+ return {"temperature": o.temperature, "thinking": o.thinking}
+
+
+def _rubric_name(record: RunRecord) -> str:
+ name = str(record.extra.get("rubric") or "")
+ if name:
+ return name
+ for r in reversed(record.rounds):
+ if r.judgment is not None and r.judgment.rubric:
+ return r.judgment.rubric
+ info = TRACK_INFO.get(record.spec.track)
+ return info.rubric if info else ""
+
+
+def rubric_hash(name: str) -> str:
+ if not name:
+ return ""
+ try:
+ from codeverse.judges.rubrics import load_rubric
+
+ return load_rubric(name).content_hash()
+ except Exception as e: # unknown rubric / package missing
+ log.debug("rubric hash unavailable for %s: %s", name, e)
+ return ""
+
+
+def _role_settings(record: RunRecord) -> list[RoleSettings]:
+ b = record.spec.backends
+ observed = record.extra.get("sampling") or {} # forward hook: a track may record real values
+ plan_d, judge_d = _planner_defaults(), _judge_defaults()
+ spec: list[tuple[str, str, dict[str, Any]]] = [
+ ("planner", b.planner, plan_d),
+ ("generator", b.generator, _generator_defaults(b.generator)),
+ ("judge", b.judge, judge_d),
+ ("captioner", b.captioner, {}),
+ ]
+ roles: list[RoleSettings] = []
+ for role, model_id, defaults in spec:
+ values = dict(defaults)
+ source = "default" if defaults else "spec"
+ if isinstance(observed.get(role), dict):
+ values.update(observed[role])
+ source = "observed"
+ temperature = values.get("temperature")
+ roles.append(RoleSettings(
+ role=role, model=model_id, backend=backend_kind(model_id),
+ thinking=str(values.get("thinking") or ""),
+ temperature=float(temperature) if isinstance(temperature, (int, float)) else None,
+ n_samples=values.get("n_samples") if role == "judge" else None,
+ source=source,
+ ))
+ return roles
+
+
+def settings_snapshot(record: RunRecord, *, key_pool_size: int | None = None) -> SettingsSnapshot:
+ """The resolved 'how was this run configured' block (no secrets, ever)."""
+ spec = record.spec
+ rubric = _rubric_name(record)
+ render: dict[str, Any] = {}
+ limits: dict[str, Any] = {}
+ keys = key_pool_size
+ try:
+ from codeverse.config import get_settings
+
+ s = get_settings()
+ render = s.render.model_dump(mode="json")
+ limits = s.limits.model_dump(mode="json")
+ if keys is None:
+ keys = len(s.gemini_api_keys)
+ except Exception as e: # pragma: no cover - settings should always load
+ log.debug("settings unavailable: %s", e)
+ env = dict(record.environment)
+ return SettingsSnapshot(
+ roles=_role_settings(record),
+ budget=spec.budget.model_dump(mode="json"),
+ candidates=spec.options.candidates,
+ texture=bool(spec.options.texture),
+ seed=spec.seed,
+ rubric=rubric,
+ rubric_hash=rubric_hash(rubric),
+ prompt_hashes=dict(record.prompt_hashes),
+ tool_versions={k: v for k, v in env.items() if k in _TOOL_KEYS},
+ harness_version=env.get("codeverse", ""),
+ harness_git_sha=env.get("harness_git_sha", ""),
+ key_pool_size=int(keys or 0),
+ price_table_version=price_table_version(),
+ render=render,
+ limits=limits,
+ )
+
+
+_TOOL_KEYS = frozenset({"python", "platform", "host", "blender", "blender_path", "node", "three",
+ "chrome", "puppeteer", "codeverse", "harness_git_sha"})
+
+
+# --------------------------------------------------------------------------- the ledger (codeverse.cost)
+#: fallback stage order when ``codeverse.cost`` is not importable
+_FALLBACK_STAGES = ("plan", "skeleton", "assets", "env", "zones", "assemble", "baseline", "candidate",
+ "repair", "refine", "gates", "render", "judge", "pairwise", "texture", "caption", "other")
+#: the live ledger a run may already carry at its root
+_FALLBACK_LEDGER_NAME = "cost_ledger.jsonl"
+
+
+def stage_order() -> tuple[str, ...]:
+ try:
+ from codeverse.cost.types import Stage
+
+ return tuple(s.value for s in Stage)
+ except Exception: # noqa: BLE001 - the cost package is optional here
+ return _FALLBACK_STAGES
+
+
+def live_ledger_path(ws: Workspace) -> Path:
+ """``<run>/cost_ledger.jsonl`` — the ledger written while the run happens, when there is one."""
+ try:
+ from codeverse.cost.ledger import LEDGER_NAME
+ except Exception: # noqa: BLE001
+ LEDGER_NAME = _FALLBACK_LEDGER_NAME # noqa: N806
+ return ws.root / LEDGER_NAME
+
+
+def ledger_rows(ws: Workspace) -> tuple[list[dict[str, Any]], str]:
+ """Priced per-call rows for the run → ``(rows, source)``.
+
+ Source is ``live`` (the run's own ``cost_ledger.jsonl``), ``reconstructed``
+ (rebuilt by ``codeverse.cost.reconstruct`` from trajectories / verdicts /
+ events) or ``unavailable``. The cost package owns the pricing and the
+ double-counting rules — this bucket never re-implements them."""
+ try:
+ live = live_ledger_path(ws)
+ if live.is_file():
+ from codeverse.cost.ledger import load_ledger
+
+ return [r.model_dump(mode="json") for r in load_ledger(live)], "live"
+ from codeverse.cost.reconstruct import reconstruct_run
+
+ return [r.model_dump(mode="json") for r in reconstruct_run(ws.root).rows], "reconstructed"
+ except Exception as e: # noqa: BLE001 - accounting must never fail a run
+ log.warning("cost ledger unavailable for %s: %s", ws.root, e)
+ return [], "unavailable"
+
+
+def _num(row: dict[str, Any], key: str) -> float:
+ v = row.get(key)
+ return float(v) if isinstance(v, (int, float)) else 0.0
+
+
+def cost_summary(record: RunRecord, rows: list[dict[str, Any]]) -> CostSummary:
+ """Money + tokens: totals, per stage, per role, per model, per round, budget, wall clock."""
+ by_stage: dict[str, StageCost] = {}
+ by_model: dict[str, float] = {}
+ by_role: dict[str, float] = {}
+ residual = 0.0
+ for row in rows:
+ stage = str(row.get("stage") or "other")
+ sc = by_stage.setdefault(stage, StageCost(stage=stage))
+ sc.calls += int(row.get("n_calls") or 1)
+ sc.input_tokens += int(_num(row, "input_tokens"))
+ sc.output_tokens += int(_num(row, "output_tokens"))
+ sc.cached_tokens += int(_num(row, "cached_tokens"))
+ sc.thoughts_tokens += int(_num(row, "thoughts_tokens"))
+ sc.cost_usd += _num(row, "cost_usd")
+ sc.seconds += _num(row, "latency_ms") / 1000.0
+ model = str(row.get("model") or row.get("model_id") or "(unknown)")
+ by_model[model] = round(by_model.get(model, 0.0) + _num(row, "cost_usd"), 6)
+ role = str(row.get("role") or "other")
+ by_role[role] = round(by_role.get(role, 0.0) + _num(row, "cost_usd"), 6)
+ if str(row.get("source")) == "residual" or str(row.get("label")) == "unattributed":
+ residual += _num(row, "cost_usd")
+ for sc in by_stage.values():
+ sc.cost_usd = round(sc.cost_usd, 6)
+ sc.seconds = round(sc.seconds, 1)
+ order = stage_order()
+ ordered = [by_stage[s] for s in order if s in by_stage]
+ ordered += [sc for s, sc in sorted(by_stage.items()) if s not in order]
+ total = float(record.total_usage.cost_usd)
+ ledger = round(sum(_num(r, "cost_usd") for r in rows), 6)
+ wall = 0.0
+ if record.finished_at is not None:
+ wall = max(0.0, (record.finished_at - record.started_at).total_seconds())
+ budget = record.spec.budget
+ return CostSummary(
+ total_usd=round(total, 6),
+ budget_usd=budget.max_usd,
+ budget_used_pct=round(100.0 * total / budget.max_usd, 1) if budget.max_usd else None,
+ wall_clock_s=round(wall, 1),
+ max_minutes=budget.max_minutes,
+ n_calls=sum(int(r.get("n_calls") or 1) for r in rows),
+ tokens=record.total_usage,
+ by_stage=ordered,
+ by_role=by_role,
+ by_model=by_model,
+ by_round=[{"index": r.index, "kind": r.kind, "cost_usd": round(r.usage.cost_usd, 6),
+ "seconds": round(r.duration_s, 1), "score": r.score} for r in record.rounds],
+ ledger_usd=ledger,
+ unattributed_usd=round(residual, 6),
+ post_run_usd=round(max(0.0, ledger - total - residual), 6),
+ )
+
+
+def read_json(path: Path) -> dict[str, Any] | None:
+ try:
+ data = json.loads(path.read_text())
+ except (OSError, ValueError):
+ return None
+ return data if isinstance(data, dict) else None
+
+
+# --------------------------------------------------------------------------- io
+def write_usage_jsonl(path: Path, rows: list[dict[str, Any]]) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_suffix(".jsonl.tmp")
+ tmp.write_text("".join(json.dumps(r, ensure_ascii=False, default=str) + "\n" for r in rows))
+ tmp.replace(path)
+ return path
+
+
+def _place_usage_rows(ws: Workspace, rows: list[dict[str, Any]], source: str) -> str:
+ """Write ``telemetry/usage.jsonl`` — or, when the run already carries a live
+ ledger at its root, alias it there so only one physical copy exists."""
+ if source == "live":
+ rel = live_ledger_path(ws).name
+ if ws.usage_path.exists() and not ws.usage_path.is_symlink():
+ ws.usage_path.unlink()
+ if not ws.usage_path.is_symlink():
+ try:
+ os.symlink(f"../{rel}", ws.usage_path)
+ except OSError: # no symlinks here: fall back to a copy
+ write_usage_jsonl(ws.usage_path, rows)
+ return rel
+ write_usage_jsonl(ws.usage_path, rows)
+ return ws.usage_path.name
+
+
+def build_telemetry(ws: Workspace, record: RunRecord, *, write: bool = True) -> RunTelemetry:
+ """Compute (and by default persist) ``telemetry/`` for one run."""
+ rows, source = ledger_rows(ws)
+ tele = RunTelemetry(
+ settings=settings_snapshot(record),
+ cost=cost_summary(record, rows),
+ environment=dict(record.environment),
+ files={"settings": "telemetry/settings.json",
+ "cost": "telemetry/cost.json",
+ "usage": "telemetry/usage.jsonl",
+ "usage_source": source,
+ "events": "telemetry/events.jsonl",
+ "run_state": "telemetry/run_state.json",
+ "stages": "telemetry/stages",
+ "trajectories": "telemetry/trajectories"},
+ )
+ if write:
+ ws.ensure_layout()
+ write_json_atomic(ws.settings_path, tele.settings.model_dump(mode="json") if tele.settings else {})
+ write_json_atomic(ws.cost_path, tele.cost.model_dump(mode="json") if tele.cost else {})
+ _place_usage_rows(ws, rows, source)
+ return tele
+
+
+def load_telemetry(ws: Workspace, record: RunRecord | None = None) -> RunTelemetry | None:
+ """``record.telemetry`` when present, else the files under ``telemetry/``, else None."""
+ if record is not None and record.telemetry is not None:
+ return record.telemetry
+ cost = read_json(ws.cost_path)
+ settings = read_json(ws.settings_path)
+ if cost is None and settings is None:
+ return None
+ try:
+ return RunTelemetry(
+ settings=SettingsSnapshot.model_validate(settings) if settings else None,
+ cost=CostSummary.model_validate(cost) if cost else None,
+ environment=dict(record.environment) if record is not None else {},
+ )
+ except Exception as e: # a hand-edited file must not break status/export
+ log.warning("unreadable telemetry in %s: %s", ws.root, e)
+ return None
diff --git a/harness/codeverse/judges/prompt_builder.py b/harness/codeverse/judges/prompt_builder.py
index 142bb27b..7cea3910 100644
--- a/harness/codeverse/judges/prompt_builder.py
+++ b/harness/codeverse/judges/prompt_builder.py
@@ -66,7 +66,9 @@ def _rubric_block(rubric: Rubric) -> str:
continue
floor = f", hard floor {c.floor:.2f}" if c.floor is not None else ""
lines.append(f"{i}. {c.id} (weight {c.weight:.2f}{floor}) — {c.label}: {c.description.strip()}")
- for lvl in ("1.0", "0.7", "0.4", "0.1"):
+ # every anchor the rubric declares, richest scale first (rubrics may add levels
+ # between the four required ones — e.g. scene_v1's 0.5 "diorama on a flat plane")
+ for lvl in sorted(c.anchors, key=lambda k: -float(k)):
lines.append(f" {lvl}: {c.anchors[lvl]}")
if rubric.defects:
lines.append("")
@@ -190,6 +192,7 @@ def view_rig_section(renders: RenderSet, montages: list[Montage], *, scene: bool
bits.append("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.")
if scene:
bits.append("Views named overview_* are harness cameras fitted to the scene bounds (layout X-ray); views named cam_* are the scene's own authored cameras (grade composition/lighting on those); 't=' is the animation time.")
+ bits.append("On the authored cameras also read the CRAFT of the picture, not only its contents: depth layering (is there anything within a few metres framing the shot, and anything on the horizon), ground variation (blended materials, paths, dressed edges vs one flat colour), variety among repeated natural elements, small-prop dressing, and aerial perspective (distant things hazier than near ones). The same camera at two times appears as separate tiles — compare them pixel-for-pixel before answering nothing_moves.")
else:
bits.append("All views show the same object. Use top + low views for symmetry, footprint and ground contact.")
if renders.console_errors:
diff --git a/harness/codeverse/judges/rubrics/scene_v1.yaml b/harness/codeverse/judges/rubrics/scene_v1.yaml
index c17a54a4..b4692dbd 100644
--- a/harness/codeverse/judges/rubrics/scene_v1.yaml
+++ b/harness/codeverse/judges/rubrics/scene_v1.yaml
@@ -18,6 +18,17 @@ extra_instructions: >
A scene a person would screenshot belongs at 0.8+; a recognisable place with one
dead zone / flat lighting / floating asset sits near 0.5; an unlit, empty or
unreadable scene sits at 0.1-0.3.
+ Craft on this track is mostly about five things, so look for each of them explicitly
+ before scoring: (1) the GROUND — is it several blended materials with paths, wear and
+ dressed edges, or one flat colour with a hard bbox line; (2) VEGETATION / repeated
+ natural elements — several silhouettes with size and hue variation in clusters, or one
+ shape stamped in a ring; (3) DEPTH — is there something in the near foreground framing
+ the shot, a subject in the midground and a horizon above, or is it a small diorama alone
+ on a big empty plane; (4) DRESSING — the small props (pebbles, leaves, tools, cups,
+ cables, litter) that make a place look used; (5) ATMOSPHERE — fog/haze giving aerial
+ perspective, coloured (sky-lit) shade, and a key light whose hue differs from the fill.
+ A scene can be entirely correct against the brief and still sit at 0.5 because it fails
+ all five; say so in the issues rather than inventing a fidelity complaint.
criteria:
- id: brief_fidelity
@@ -43,9 +54,10 @@ criteria:
foreground/midground/background, horizon placed deliberately, nothing clipped by
the near plane, no camera inside geometry, no shot that shows only sky or ground?
anchors:
- "1.0": Every authored camera is a composed shot with depth layering and a clear subject.
- "0.7": Shots are readable; one is a bit flat or off-centre.
- "0.4": One authored camera shows nothing useful (sky, ground, the inside of a wall) or is badly clipped.
+ "1.0": Every authored camera is a composed shot — a foreground element within a few metres frames the edge, the subject fills the middle distance, a horizon band sits above, and the subject is what the camera is aimed at.
+ "0.7": Shots are readable and aimed at the subject, but one layer is missing (no foreground, or a bare horizon) or one shot is flat / off-centre.
+ "0.5": The scene reads as a diorama photographed from outside — subject centred on a large empty plane, no foreground, nothing on the horizon.
+ "0.4": One authored camera shows nothing useful (sky, ground, the inside of a wall), or the establishing shot is aimed at the bounds centre rather than the subject, or a shot is badly clipped.
"0.1": Most shots are unusable or the camera is inside geometry.
- id: lighting_atmosphere
@@ -58,9 +70,10 @@ criteria:
depth, exposure neither blown nor crushed, coloured (sky-lit) shade rather than
black?
anchors:
- "1.0": Clear mood executed consistently; shadows, sky, fog and exposure all agree; shade carries sky colour.
- "0.7": Good lighting with one weakness (slightly flat shadows or slightly heavy fog).
- "0.4": Flat shadowless light, or noticeably under/over-exposed, or sky contradicting the light.
+ "1.0": Clear mood executed consistently; warm key against a cooler fill (or the reverse); soft accurate shadows with smooth edges; fog/haze gives visible aerial perspective with distance; shade carries sky colour.
+ "0.7": Good lighting with one weakness (slightly flat shadows, slightly heavy fog, or a horizon with no atmospheric falloff).
+ "0.5": Lit but airless — no haze or depth cue, key and fill share one hue so the frame is monochrome, or shadow edges are visibly stair-stepped.
+ "0.4": Flat shadowless light, or noticeably under/over-exposed, or sky contradicting the light, or black (unfilled) shadows.
"0.1": Near-black, blown white, or unlit.
- id: asset_quality_detail
@@ -71,9 +84,10 @@ criteria:
roofs/windows/setbacks, trees with trunk and canopy, vehicles and street
furniture where the place calls for them — without copy-paste monotony?
anchors:
- "1.0": Assets are crafted and varied; closeups hold up.
- "0.7": Assets are decent with some repetition or a few plain ones.
- "0.4": Mostly plain boxes / cones, or one shape stamped everywhere.
+ "1.0": Assets are crafted and varied — several silhouettes per family, per-instance size and hue variation, wear and small props everywhere; closeups hold up.
+ "0.7": Assets are decent with some repetition, a few plain ones, or thin set dressing.
+ "0.5": Hero assets are fine but everything around them is one repeated primitive and the place is undressed — no small props, no litter, no ground cover.
+ "0.4": Mostly plain boxes / cones, or one shape stamped everywhere, or a solid object faked as a flat coloured plane.
"0.1": Primitive blobs or an empty world.
- id: spatial_coherence_scale
@@ -159,6 +173,21 @@ defects:
- id: world_edge_visible
text: A hard world edge / terrain cliff / missing horizon is visible from an authored camera.
penalty: 0.04
+ - id: flat_ground
+ text: The ground is one flat untextured colour — no material blending, no paths or worn areas, and where objects meet it the seam is a hard undressed line.
+ penalty: 0.04
+ - id: monotonous_vegetation
+ text: A repeated natural element (trees, rocks, plants, crowd) is one shape stamped many times — no variation in silhouette, size or hue, and placed in a ring or a grid rather than clusters.
+ penalty: 0.04
+ - id: empty_midground
+ text: An authored camera has no depth layering — nothing in the near foreground and/or nothing on the horizon, so the subject sits alone on a large empty plane.
+ penalty: 0.04
+ - id: undressed_scene
+ text: The place has no small props or clutter (pebbles, leaves, tools, cups, cables, litter, ground cover) — it looks like a showroom of a few large objects.
+ penalty: 0.03
+ - id: thin_atmosphere
+ text: No visible aerial perspective — distant things are as saturated and contrasty as near things, there is no haze/fog falloff, and the key and fill light share one hue.
+ penalty: 0.03
caps:
- id: build_error
diff --git a/harness/codeverse/models/pricing.py b/harness/codeverse/models/pricing.py
index debfcaad..89d54f0d 100644
--- a/harness/codeverse/models/pricing.py
+++ b/harness/codeverse/models/pricing.py
@@ -1,13 +1,17 @@
-"""USD price table (per 1M tokens) + ``estimate_cost``.
+"""USD price table (per 1M tokens) + ``estimate_cost`` + price provenance.
-Providers never return USD, so every ``Usage`` is priced here. Prices are the
-latest published rates known to the author at the time of writing (2026-08);
-entries marked *approximate* were taken from secondary sources or inferred
-from the closest sibling model — refresh when the official pages change.
+Every ``Usage`` is priced here (providers never return USD). Each row carries a
+:class:`Provenance` entry — where the number came from and when it was last
+checked — so a cost report can say *which* price row produced a dollar and
+whether it was verified or merely inferred (``3dcv cost prices``).
-Only the standard (short-context) tier is modelled; long-context surcharges
-and cache *storage* fees are not. Unknown models price at 0.0 and log a
-warning once per (provider, model).
+Only the standard (short-context) tier is modelled, **except** the documented
+>200k-prompt tiers of the Gemini pro models, which ``estimate_cost`` applies
+automatically (``Price.long_context``). Cache *storage* fees (Gemini explicit
+caching, $/1M-tokens/hour), Anthropic 1h-cache writes, batch/flex discounts,
+data-residency and fast-mode multipliers are **not** modelled — see
+``docs/COST.md``. Unknown models price at 0.0 and log a warning once per
+(provider, model).
"""
from __future__ import annotations
@@ -20,40 +24,94 @@ from codeverse.contracts.common import Usage
log = logging.getLogger(__name__)
+#: date the tables below were last reconciled against the providers' pricing pages
+CHECKED = "2026-08-23"
+
+#: source ids used by :data:`PROVENANCE`
+SOURCES: dict[str, str] = {
+ "gemini": "https://ai.google.dev/gemini-api/docs/pricing",
+ "anthropic": "https://platform.claude.com/docs/en/about-claude/pricing",
+ "openai": "https://developers.openai.com/api/docs/pricing",
+ "inferred": "inferred from the closest sibling model (no published row)",
+ "provider-cost": "reproduced from a provider-reported cost in our own run telemetry",
+}
+
+
+@dataclass(frozen=True)
+class LongContext:
+ """Prices that replace the standard ones once the prompt exceeds ``threshold``."""
+
+ threshold: int
+ input: float
+ output: float
+ cached: float = 0.0
+
@dataclass(frozen=True)
class Price:
"""USD per 1M tokens. ``cached`` = cache-read input; ``cache_write`` = cache
- creation (Anthropic/OpenAI explicit caching); ``thoughts`` defaults to output."""
+ creation (Anthropic explicit caching, 5-minute TTL); ``thoughts`` are billed
+ at the output rate. ``image_usd`` = per generated 1024² image for
+ image-output models (their image tokens are billed per image, not per token).
+ """
input: float
output: float
cached: float = 0.0
cache_write: float | None = None
approximate: bool = False
+ image_usd: float = 0.0
+ long_context: LongContext | None = None
+
+
+@dataclass(frozen=True)
+class Provenance:
+ """Where one price row came from. ``status``:
+
+ * ``verified`` — read off the provider's public pricing page on ``checked``
+ * ``inferred`` — no published row; copied from the nearest sibling
+ * ``unverified`` — the model is not listed on the page (retired / alias / CLI-only)
+ """
+
+ source: str
+ checked: str = CHECKED
+ status: str = "verified"
+ note: str = ""
+
+ @property
+ def url(self) -> str:
+ return SOURCES.get(self.source, self.source)
+
+
+_V = Provenance # verified rows read straight off a pricing page
# fmt: off
PRICES: dict[tuple[str, str], Price] = {
# ---------------------------------------------------------------- gemini
# 3.6 / 3.7 flash: introductory rates valid through 2026-12-31; they double
- # on 2027-01-01 ($1.50 / $7.50 / $0.15). Update then.
+ # on 2027-01-01 ($1.50 / $7.50 / $0.15). Update then. No >200k surcharge.
("gemini", "gemini-3.7-flash"): Price(0.75, 3.75, 0.075),
("gemini", "gemini-3.6-flash"): Price(0.75, 3.75, 0.075),
("gemini", "gemini-3.5-flash"): Price(1.50, 9.00, 0.15),
- ("gemini", "gemini-3.1-pro-preview"): Price(2.00, 12.00, 0.20),
+ ("gemini", "gemini-3.1-pro-preview"): Price(2.00, 12.00, 0.20,
+ long_context=LongContext(200_000, 4.00, 18.00, 0.40)),
("gemini", "gemini-3.1-flash-lite"): Price(0.25, 1.50, 0.025),
- ("gemini", "gemini-3.1-flash-image"): Price(0.25, 1.50, 0.025, approximate=True), # + per-image fees
- ("gemini", "gemini-3-pro-preview"): Price(2.00, 12.00, 0.20),
+ # image-output model: text/thinking output $3/M, IMAGE output $60/M ≈ $0.067
+ # per 1K image (1290 tokens); 0.5K $0.045, 2K $0.134, 4K $0.151. No cache row.
+ ("gemini", "gemini-3.1-flash-image"): Price(0.50, 3.00, 0.05, image_usd=0.067),
+ ("gemini", "gemini-3-pro-preview"): Price(2.00, 12.00, 0.20,
+ long_context=LongContext(200_000, 4.00, 18.00, 0.40)),
("gemini", "gemini-3-flash-preview"): Price(0.50, 3.00, 0.05),
- ("gemini", "gemini-2.5-pro"): Price(1.25, 10.00, 0.125),
- ("gemini", "gemini-2.5-flash"): Price(0.30, 2.50, 0.075),
- ("gemini", "gemini-2.5-flash-lite"): Price(0.10, 0.40, 0.025),
- # (texturing) image-output model: output tokens ARE the image (~1.3k tokens ≈ $0.039 / image);
- # models/gemini_image.py additionally floors cost at IMAGE_USD per image. approximate.
- ("gemini", "gemini-2.5-flash-image"): Price(0.30, 30.00, 0.075, approximate=True),
+ ("gemini", "gemini-2.5-pro"): Price(1.25, 10.00, 0.125,
+ long_context=LongContext(200_000, 2.50, 15.00, 0.25)),
+ ("gemini", "gemini-2.5-flash"): Price(0.30, 2.50, 0.03),
+ ("gemini", "gemini-2.5-flash-lite"): Price(0.10, 0.40, 0.01),
+ # image tokens are billed per image: 1024² = 1290 tokens = $0.039 ⇒ $30.23/M
+ ("gemini", "gemini-2.5-flash-image"): Price(0.30, 30.00, 0.03, image_usd=0.039),
# ------------------------------------------------------------- anthropic
("anthropic", "claude-fable-5"): Price(10.00, 50.00, 1.00, cache_write=12.50),
+ ("anthropic", "claude-mythos-5"): Price(10.00, 50.00, 1.00, cache_write=12.50),
("anthropic", "claude-opus-5"): Price(5.00, 25.00, 0.50, cache_write=6.25),
("anthropic", "claude-opus-4-8"): Price(5.00, 25.00, 0.50, cache_write=6.25),
("anthropic", "claude-opus-4-7"): Price(5.00, 25.00, 0.50, cache_write=6.25),
@@ -61,24 +119,27 @@ PRICES: dict[tuple[str, str], Price] = {
("anthropic", "claude-opus-4-5"): Price(5.00, 25.00, 0.50, cache_write=6.25),
("anthropic", "claude-opus-4-1"): Price(15.00, 75.00, 1.50, cache_write=18.75),
("anthropic", "claude-opus-4"): Price(15.00, 75.00, 1.50, cache_write=18.75),
- # sonnet-5 standard rate; an intro rate ($2 / $10) applies through 2026-08-31
- ("anthropic", "claude-sonnet-5"): Price(3.00, 15.00, 0.30, cache_write=3.75),
+ # sonnet-5: the $2/$10 launch rate became the standard rate (the 2026-09-01
+ # increase to $3/$15 was cancelled) — was priced 50% too high here until 2026-08-23.
+ ("anthropic", "claude-sonnet-5"): Price(2.00, 10.00, 0.20, cache_write=2.50),
("anthropic", "claude-sonnet-4-6"): Price(3.00, 15.00, 0.30, cache_write=3.75),
("anthropic", "claude-sonnet-4-5"): Price(3.00, 15.00, 0.30, cache_write=3.75),
("anthropic", "claude-sonnet-4"): Price(3.00, 15.00, 0.30, cache_write=3.75),
("anthropic", "claude-haiku-4-5"): Price(1.00, 5.00, 0.10, cache_write=1.25),
("anthropic", "claude-haiku-4"): Price(1.00, 5.00, 0.10, cache_write=1.25, approximate=True),
+ ("anthropic", "claude-haiku-3-5"): Price(0.80, 4.00, 0.08, cache_write=1.00),
# ---------------------------------------------------------------- openai
- ("openai", "gpt-5.6-sol"): Price(5.00, 30.00, 0.50, cache_write=6.25, approximate=True),
- ("openai", "gpt-5.6"): Price(5.00, 30.00, 0.50, approximate=True),
- ("openai", "gpt-5.5"): Price(5.00, 30.00, 0.50, approximate=True),
- ("openai", "gpt-5.4"): Price(2.50, 15.00, 0.25, approximate=True),
- ("openai", "gpt-5.3-codex"): Price(1.75, 14.00, 0.175, approximate=True),
+ # gpt-5.6-sol is CHEAPER than gpt-5.6 (was priced as its equal until 2026-08-23).
+ ("openai", "gpt-5.6-sol"): Price(4.00, 20.00, 0.40),
+ ("openai", "gpt-5.6"): Price(5.00, 30.00, 0.50),
+ ("openai", "gpt-5.5"): Price(5.00, 30.00, 0.50),
+ ("openai", "gpt-5.4"): Price(2.50, 15.00, 0.25),
+ ("openai", "gpt-5.3-codex"): Price(1.75, 14.00, 0.175),
("openai", "gpt-5.2-codex"): Price(1.75, 14.00, 0.175, approximate=True),
- ("openai", "gpt-5.2"): Price(1.75, 14.00, 0.175, approximate=True),
- ("openai", "gpt-5.1-codex"): Price(1.25, 10.00, 0.125),
+ ("openai", "gpt-5.2"): Price(1.75, 14.00, 0.175),
+ ("openai", "gpt-5.1-codex"): Price(1.25, 10.00, 0.125, approximate=True),
("openai", "gpt-5.1"): Price(1.25, 10.00, 0.125),
- ("openai", "gpt-5-codex"): Price(1.25, 10.00, 0.125),
+ ("openai", "gpt-5-codex"): Price(1.25, 10.00, 0.125, approximate=True),
("openai", "gpt-5-mini"): Price(0.25, 2.00, 0.025),
("openai", "gpt-5-nano"): Price(0.05, 0.40, 0.005),
("openai", "gpt-5"): Price(1.25, 10.00, 0.125),
@@ -92,10 +153,76 @@ PRICES: dict[tuple[str, str], Price] = {
("openai", "o3-pro"): Price(20.00, 80.00),
("openai", "o4-mini"): Price(1.10, 4.40, 0.275),
("openai", "o1"): Price(15.00, 60.00, 7.50),
- ("openai", "o1-mini"): Price(1.10, 4.40, 0.55),
+ ("openai", "o1-mini"): Price(1.10, 4.40, 0.55, approximate=True),
+}
+
+#: per price row: where the number came from and when it was last checked.
+#: Every key of :data:`PRICES` must appear here (``tests/cost/test_price_hygiene.py``).
+PROVENANCE: dict[tuple[str, str], Provenance] = {
+ ("gemini", "gemini-3.7-flash"): _V("gemini", note="intro rate through 2026-12-31, then 1.50/7.50/0.15"),
+ ("gemini", "gemini-3.6-flash"): _V("gemini", note="intro rate through 2026-12-31"),
+ ("gemini", "gemini-3.5-flash"): _V("gemini"),
+ ("gemini", "gemini-3.1-pro-preview"): _V("gemini", note=">200k prompts: 4.00/18.00/0.40 (modelled)"),
+ ("gemini", "gemini-3.1-flash-lite"): _V("gemini", note="audio input is 2x; text/image/video modelled"),
+ ("gemini", "gemini-3.1-flash-image"): _V("gemini", note="image output $60/M ≈ $0.067 per 1K image; 0.5K $0.045, 4K $0.151"),
+ ("gemini", "gemini-3-pro-preview"): _V("gemini", note=">200k prompts: 4.00/18.00 (modelled)"),
+ ("gemini", "gemini-3-flash-preview"): _V("gemini"),
+ ("gemini", "gemini-2.5-pro"): _V("gemini", note=">200k prompts: 2.50/15.00/0.25 (modelled)"),
+ ("gemini", "gemini-2.5-flash"): _V("gemini", note="cached was 0.075 here until 2026-08-23; published 0.03"),
+ ("gemini", "gemini-2.5-flash-lite"): _V("gemini", note="cached was 0.025 here until 2026-08-23; published 0.01"),
+ ("gemini", "gemini-2.5-flash-image"): _V("gemini", status="inferred",
+ note="output/M derived from $0.039 per 1290-token 1024² image"),
+ ("anthropic", "claude-fable-5"): _V("anthropic", note="1h cache write 20.00 (not modelled)"),
+ ("anthropic", "claude-mythos-5"): _V("anthropic", note="limited availability"),
+ ("anthropic", "claude-opus-5"): _V("anthropic", note="fast mode is 10.00/50.00 (not modelled)"),
+ ("anthropic", "claude-opus-4-8"): _V("anthropic", note="fast mode is 10.00/50.00 (not modelled)"),
+ ("anthropic", "claude-opus-4-7"): _V("anthropic"),
+ ("anthropic", "claude-opus-4-6"): _V("anthropic"),
+ ("anthropic", "claude-opus-4-5"): _V("anthropic"),
+ ("anthropic", "claude-opus-4-1"): _V("anthropic", note="retired except on Bedrock / Google Cloud"),
+ ("anthropic", "claude-opus-4"): _V("anthropic", note="retired except on Google Cloud"),
+ ("anthropic", "claude-sonnet-5"): _V("anthropic", note="launch rate 2.00/10.00 is now standard; was 3.00/15.00 here"),
+ ("anthropic", "claude-sonnet-4-6"): _V("anthropic"),
+ ("anthropic", "claude-sonnet-4-5"): _V("anthropic"),
+ ("anthropic", "claude-sonnet-4"): _V("anthropic", note="retired except on Bedrock / Google Cloud"),
+ ("anthropic", "claude-haiku-4-5"): _V("anthropic"),
+ ("anthropic", "claude-haiku-4"): _V("inferred", status="unverified",
+ note="not listed on the pricing page; assumed = haiku-4.5"),
+ ("anthropic", "claude-haiku-3-5"): _V("anthropic", note="retired except on Bedrock / Google Cloud"),
+ ("openai", "gpt-5.6-sol"): _V("openai", note="4.00/20.00/0.40; was 5.00/30.00/0.50 here until 2026-08-23"),
+ ("openai", "gpt-5.6"): _V("openai"),
+ ("openai", "gpt-5.5"): _V("openai"),
+ ("openai", "gpt-5.4"): _V("openai"),
+ ("openai", "gpt-5.3-codex"): _V("openai"),
+ ("openai", "gpt-5.2-codex"): _V("inferred", status="inferred", note="not listed; assumed = gpt-5.2"),
+ ("openai", "gpt-5.2"): _V("openai"),
+ ("openai", "gpt-5.1-codex"): _V("inferred", status="inferred", note="not listed; assumed = gpt-5.1"),
+ ("openai", "gpt-5.1"): _V("openai"),
+ ("openai", "gpt-5-codex"): _V("inferred", status="inferred", note="not listed; assumed = gpt-5"),
+ ("openai", "gpt-5-mini"): _V("openai"),
+ ("openai", "gpt-5-nano"): _V("openai"),
+ ("openai", "gpt-5"): _V("openai"),
+ ("openai", "gpt-4.1"): _V("openai"),
+ ("openai", "gpt-4.1-mini"): _V("openai"),
+ ("openai", "gpt-4.1-nano"): _V("openai"),
+ ("openai", "gpt-4o"): _V("openai"),
+ ("openai", "gpt-4o-mini"): _V("openai"),
+ ("openai", "o3"): _V("openai"),
+ ("openai", "o3-mini"): _V("openai"),
+ ("openai", "o3-pro"): _V("openai", note="no cached-input rate published"),
+ ("openai", "o4-mini"): _V("openai"),
+ ("openai", "o1"): _V("openai"),
+ ("openai", "o1-mini"): _V("inferred", status="unverified", note="not listed; kept at the o3-mini rate"),
}
# fmt: on
+#: per-image USD by requested pixel size, for models whose image output is billed
+#: per image rather than per token (``Price.image_usd`` is the 1024² entry).
+IMAGE_USD_BY_SIZE: dict[tuple[str, str], dict[int, float]] = {
+ ("gemini", "gemini-3.1-flash-image"): {512: 0.045, 1024: 0.067, 2048: 0.134, 4096: 0.151},
+ ("gemini", "gemini-2.5-flash-image"): {512: 0.039, 1024: 0.039, 2048: 0.039, 4096: 0.039},
+}
+
_warned: set[tuple[str, str]] = set()
_warned_lock = threading.Lock()
@@ -119,22 +246,99 @@ def _is_version_suffix(rest: str) -> bool:
return all(seg.isdigit() or seg in _VERSION_WORDS for seg in segments)
-def lookup_price(provider: str, model: str) -> Price | None:
- """Exact match first, then the longest table key that ``model`` extends by a
- pure version/date suffix (``claude-opus-5-20260301``, ``gemini-3.7-flash-preview-09``).
- A different family name after the key (``gpt-4.1-nano`` vs ``gpt-4.1``) is NOT a
- match: unknown → ``None`` so the caller prices 0.0 and warns, never a sibling's rate."""
+def _match(provider: str, model: str) -> tuple[tuple[str, str], Price] | None:
m = _normalise(model)
exact = PRICES.get((provider, m))
if exact is not None:
- return exact
- best: tuple[int, Price] | None = None
+ return (provider, m), exact
+ best: tuple[int, tuple[str, str], Price] | None = None
for (prov, key), price in PRICES.items():
if prov != provider or not m.startswith(key) or not _is_version_suffix(m[len(key) :]):
continue
if best is None or len(key) > best[0]:
- best = (len(key), price)
- return best[1] if best else None
+ best = (len(key), (prov, key), price)
+ return (best[1], best[2]) if best else None
+
+
+def lookup_price(provider: str, model: str) -> Price | None:
+ """Exact match first, then the longest table key that ``model`` extends by a
+ pure version/date suffix (``claude-opus-5-20260301``, ``gemini-3.7-flash-preview-09``).
+ A different family name after the key (``gpt-4.1-nano`` vs ``gpt-4.1``) is NOT a
+ match: unknown → ``None`` so the caller prices 0.0 and warns, never a sibling's rate."""
+ found = _match(provider, model)
+ return found[1] if found else None
+
+
+@dataclass(frozen=True)
+class PriceRow:
+ """A resolved price plus its audit trail — what ``3dcv cost prices`` prints."""
+
+ provider: str
+ model: str
+ key: str # the PRICES key that matched ("" when unknown)
+ match: str # exact | prefix | unknown
+ price: Price | None
+ provenance: Provenance | None
+
+ @property
+ def approximate(self) -> bool:
+ """True when the dollar cannot be trusted to the cent: no row, an
+ inferred/unverified row, or a row flagged ``approximate``."""
+ if self.price is None or self.provenance is None:
+ return True
+ return self.price.approximate or self.provenance.status != "verified"
+
+ @property
+ def source(self) -> str:
+ return self.provenance.url if self.provenance else "unknown"
+
+ @property
+ def checked(self) -> str:
+ return self.provenance.checked if self.provenance else ""
+
+ @property
+ def status(self) -> str:
+ if self.price is None:
+ return "unknown"
+ return self.provenance.status if self.provenance else "unverified"
+
+
+def price_provenance(provider: str, model: str) -> PriceRow:
+ """Resolve ``provider:model`` to a price **and its source**. Never raises;
+ an unknown model comes back as ``match="unknown"``, ``price=None``."""
+ prov = (provider or "").strip().lower()
+ found = _match(prov, model)
+ if not found:
+ return PriceRow(prov, _normalise(model), "", "unknown", None, None)
+ key, price = found
+ match = "exact" if key[1] == _normalise(model) else "prefix"
+ return PriceRow(prov, _normalise(model), key[1], match, price, PROVENANCE.get(key))
+
+
+def unit_prices(provider: str, model: str, *, prompt_tokens: int = 0) -> tuple[float, float, float]:
+ """``(input, cached, output)`` USD per 1M actually charged for a prompt of
+ ``prompt_tokens`` — the long-context tier when the model has one and the
+ prompt crosses its threshold. Unknown model → ``(0, 0, 0)``."""
+ price = lookup_price(provider, model)
+ if price is None:
+ return (0.0, 0.0, 0.0)
+ lc = price.long_context
+ if lc is not None and prompt_tokens > lc.threshold:
+ return (lc.input, lc.cached, lc.output)
+ return (price.input, price.cached, price.output)
+
+
+def per_image_usd(provider: str, model: str, *, size: int = 1024) -> float:
+ """Per-generated-image price for image-output models (0.0 when the model
+ bills images as ordinary output tokens)."""
+ found = _match((provider or "").strip().lower(), model)
+ if not found:
+ return 0.0
+ key, price = found
+ by_size = IMAGE_USD_BY_SIZE.get(key)
+ if by_size:
+ return by_size.get(size, price.image_usd)
+ return price.image_usd
def estimate_cost(provider: str, model: str, usage: Usage) -> float:
@@ -152,11 +356,12 @@ def estimate_cost(provider: str, model: str, usage: Usage) -> float:
log.warning("pricing: unknown model %s:%s — cost reported as 0.0", provider, model)
return 0.0
m = 1_000_000.0
+ p_in, p_cached, p_out = unit_prices(provider, model, prompt_tokens=usage.input_tokens)
cached = max(0, min(usage.cached_tokens, usage.input_tokens))
uncached = max(0, usage.input_tokens - cached)
- cost = uncached * price.input / m
- cost += cached * price.cached / m
- cost += (usage.output_tokens + usage.thoughts_tokens) * price.output / m
+ cost = uncached * p_in / m
+ cost += cached * p_cached / m
+ cost += (usage.output_tokens + usage.thoughts_tokens) * p_out / m
return cost
diff --git a/harness/codeverse/orchestrator/budget.py b/harness/codeverse/orchestrator/budget.py
index a3f17381..e9ed6170 100644
--- a/harness/codeverse/orchestrator/budget.py
+++ b/harness/codeverse/orchestrator/budget.py
@@ -1,8 +1,16 @@
-"""Budget guard: hard per-run ceilings on cost and wall time.
+"""Budget guard: hard per-run ceilings on cost and wall time, plus a soft cap.
Every model / agent call yields a ``Usage``; the track charges it here. When
-either ceiling is crossed ``BudgetExceeded`` is raised so the round loop can
-stop cleanly (status ``budget``) instead of silently overspending.
+either **hard** ceiling is crossed ``BudgetExceeded`` is raised so the round
+loop can stop cleanly (status ``budget``) instead of silently overspending.
+
+On top of that a **soft** sub-budget (``soft_fraction`` of the hard ceilings)
+lets a track see the wall coming: ``soft_ok()`` / ``soft_exceeded()`` say
+"the baseline has used its share — degrade now (fewer assets, single-shot
+instead of an agent session) so the refine rounds still have money". Crossing
+the soft cap never raises; only the hard ceiling does. ``grant_grace`` raises
+the hard ceiling once so a budget-stopped run can still finalise (assemble +
+build + render + judge) instead of dying with no score at all.
"""
from __future__ import annotations
@@ -30,12 +38,17 @@ class BudgetGuard:
``BudgetExceeded`` when ``max_usd`` or ``max_minutes`` is exceeded.
"""
- def __init__(self, budget: Budget, start_time: float | None = None):
+ def __init__(self, budget: Budget, start_time: float | None = None, *, soft_fraction: float = 1.0):
self.budget = budget
self.start_time = time.time() if start_time is None else start_time
self.spent = Usage()
self._lock = threading.Lock()
self.calls = 0
+ #: fraction of the hard ceilings the *baseline* may use (1.0 = no soft cap)
+ self.soft_fraction = min(1.0, max(0.0, float(soft_fraction)))
+ #: one-off extension of the HARD ceilings (finalise/salvage headroom)
+ self.grace_usd = 0.0
+ self.grace_minutes = 0.0
# ----------------------------------------------------------------- accounting
def charge(self, usage: Usage | None) -> None:
@@ -58,21 +71,62 @@ class BudgetGuard:
def elapsed_minutes(self) -> float:
return (time.time() - self.start_time) / 60.0
+ # ----------------------------------------------------------------- ceilings
+ @property
+ def hard_usd(self) -> float:
+ return self.budget.max_usd + self.grace_usd
+
+ @property
+ def hard_minutes(self) -> float:
+ return self.budget.max_minutes + self.grace_minutes
+
+ def grant_grace(self, *, usd: float = 0.0, minutes: float = 0.0) -> None:
+ """Extend the HARD ceilings (never shrink them). Used once by finalise /
+ salvage so a run that tripped the budget mid-stage can still deliver a
+ judged round instead of no score at all."""
+ with self._lock:
+ self.grace_usd = max(self.grace_usd, max(0.0, float(usd)))
+ self.grace_minutes = max(self.grace_minutes, max(0.0, float(minutes)))
+
def check(self) -> None:
- """Raise ``BudgetExceeded`` if any ceiling has been crossed."""
+ """Raise ``BudgetExceeded`` if any hard ceiling has been crossed."""
spent = self.spent.cost_usd
elapsed = self.elapsed_minutes()
- if spent > self.budget.max_usd:
+ if spent > self.hard_usd:
raise BudgetExceeded(
- f"cost ${spent:.3f} exceeds max_usd ${self.budget.max_usd:.2f}",
+ f"cost ${spent:.3f} exceeds max_usd ${self.hard_usd:.2f}",
spent_usd=spent, elapsed_min=elapsed,
)
- if elapsed > self.budget.max_minutes:
+ if elapsed > self.hard_minutes:
raise BudgetExceeded(
- f"elapsed {elapsed:.1f} min exceeds max_minutes {self.budget.max_minutes:.1f}",
+ f"elapsed {elapsed:.1f} min exceeds max_minutes {self.hard_minutes:.1f}",
spent_usd=spent, elapsed_min=elapsed,
)
+ # ----------------------------------------------------------------- soft cap
+ def soft_limits(self) -> tuple[float, float]:
+ """(usd, minutes) the soft sub-budget allows (grace is hard-only)."""
+ return self.budget.max_usd * self.soft_fraction, self.budget.max_minutes * self.soft_fraction
+
+ def soft_exceeded(self) -> str:
+ """Reason string when the soft sub-budget is used up, else ``""``."""
+ usd, minutes = self.soft_limits()
+ spent, elapsed = self.spent.cost_usd, self.elapsed_minutes()
+ if spent > usd:
+ return f"cost ${spent:.3f} exceeds soft cap ${usd:.2f} ({self.soft_fraction:.0%} of ${self.budget.max_usd:.2f})"
+ if elapsed > minutes:
+ return f"elapsed {elapsed:.1f} min exceeds soft cap {minutes:.1f} min ({self.soft_fraction:.0%} of {self.budget.max_minutes:.1f})"
+ return ""
+
+ def soft_ok(self) -> bool:
+ """True while the baseline still has its share of the budget."""
+ return not self.soft_exceeded()
+
+ def soft_remaining(self) -> dict[str, float]:
+ """Headroom left inside the soft sub-budget (never negative)."""
+ usd, minutes = self.soft_limits()
+ return {"usd": max(0.0, usd - self.spent.cost_usd), "minutes": max(0.0, minutes - self.elapsed_minutes())}
+
def ok(self) -> bool:
"""True when no ceiling is crossed (non-raising variant of ``check``)."""
try:
@@ -83,16 +137,27 @@ class BudgetGuard:
def remaining(self) -> dict[str, float]:
"""Remaining headroom: ``{"usd": ..., "minutes": ..., "fraction": ...}``."""
- usd = max(0.0, self.budget.max_usd - self.spent.cost_usd)
- minutes = max(0.0, self.budget.max_minutes - self.elapsed_minutes())
- frac_usd = usd / self.budget.max_usd if self.budget.max_usd > 0 else 0.0
- frac_min = minutes / self.budget.max_minutes if self.budget.max_minutes > 0 else 0.0
+ usd = max(0.0, self.hard_usd - self.spent.cost_usd)
+ minutes = max(0.0, self.hard_minutes - self.elapsed_minutes())
+ frac_usd = usd / self.hard_usd if self.hard_usd > 0 else 0.0
+ frac_min = minutes / self.hard_minutes if self.hard_minutes > 0 else 0.0
return {"usd": usd, "minutes": minutes, "fraction": min(frac_usd, frac_min)}
+ def timeout_s(self, want_s: float, *, floor_s: float = 60.0, soft: bool = True) -> int:
+ """``want_s`` clipped to the wall-clock actually left (soft cap when ``soft``).
+
+ A generation session must never be allowed to outlive the run's budget:
+ the greenhouse scene lost 54 minutes to zone agents that kept working
+ after the ceiling had already been crossed."""
+ left = (self.soft_remaining()["minutes"] if soft else self.remaining()["minutes"]) * 60.0
+ return int(max(floor_s, min(float(want_s), left) if left > 0 else floor_s))
+
def summary(self) -> dict[str, float | int]:
return {
"spent_usd": round(self.spent.cost_usd, 4),
"elapsed_min": round(self.elapsed_minutes(), 2),
+ "soft_fraction": round(self.soft_fraction, 3),
+ "grace_usd": round(self.grace_usd, 4),
"calls": self.calls,
"input_tokens": self.spent.input_tokens,
"output_tokens": self.spent.output_tokens,
diff --git a/harness/codeverse/prompts/scene_threejs/cookbook.md b/harness/codeverse/prompts/scene_threejs/cookbook.md
index 7a43f43f..52669bc4 100644
--- a/harness/codeverse/prompts/scene_threejs/cookbook.md
+++ b/harness/codeverse/prompts/scene_threejs/cookbook.md
@@ -3,37 +3,26 @@
Every `js` snippet runs as-is in node (the harness test suite concatenates them with
`THREE` and the named addons in scope). Y-up, +Z front, meters. GLSL lives in
`glsl_cookbook.md` — use its `makeShaderMaterial` for every custom shader.
-Use `read_cookbook(section="<heading>")` for one chapter.
+Use `read_cookbook(section="<heading>")` for one chapter — reading the whole file
+truncates at 6000 characters, so ask for chapters by name.
-## Assembly skeleton (`src/scene.js` orchestrates, builds nothing itself)
+**The chapters that decide the score.** Scenes on this track lose most of their points to
+five repeatable defects, one chapter each:
-```js
-// scene.js: build env → zones → cameras; cache everything update() needs. Never traverse per frame.
-const rand = (i) => { const s = Math.sin(i * 12.9898 + 78.233) * 43758.5453; return s - Math.floor(s); };
-
-async function exampleCreateScene({ THREE, renderer, loaders }) {
- const scene = new THREE.Scene();
- const env = buildEnv(THREE, scene); // sky, sun, fog, ground (below)
- const zones = [buildOrchard(THREE, { heightAt })]; // every zone: PascalCase Group
- for (const z of zones) scene.add(z);
- const movers = zones.filter(z => z.userData.update); // cached ONCE
- const mats = collectAnimatedMaterials(scene); // from glsl_cookbook wire-up
- const cameras = planCameras(THREE, scene); // measured, not guessed (below)
- return {
- scene, cameras,
- update(t, dt) {
- env.update(t, dt);
- for (const z of movers) z.userData.update(t, dt);
- for (const m of mats) m.userData.update(t, dt);
- },
- };
-}
-```
+| the judge writes | read this chapter |
+|---|---|
+| "flat ground plane", "one colour", "no paths" | Ground that reads real |
+| "a hard world edge is visible against the sky" | Horizon: the world must not end |
+| "monotonous / identical cones", "primitive stacked shapes" | Vegetation that reads real · Rocks, cliffs and boulders |
+| "sparse", "a diorama on an empty plane", "no midground" | Scene layering · Set dressing |
+| "flat light", "too dark", "monochrome", "jagged shadows" | Atmosphere: time-of-day triads |
+| "frames at t=0 and t=1.5 are identical" | Motion you can SEE between t = 0 and t = 1.5 s |
## Environment (`src/env.js`): sun + sky + fog + ground — the scene's floor comes first
```js
const BOUNDS = { min: [-50, 0, -50], max: [50, 30, 50] }; // export const in real env.js
+const rand = (i) => { const s = Math.sin(i * 12.9898 + 78.233) * 43758.5453; return s - Math.floor(s); }; // seeded, never Math.random
const SUN_DIR = new THREE.Vector3(0.55, 0.62, 0.35).normalize(); // one sun direction, reused everywhere
function heightAt(x, z) {
@@ -83,50 +72,349 @@ function buildEnv(THREE, scene) {
}
```
-Numbers: sun 2.2–3.2, hemisphere 0.4–0.7 (never both high — washed out); shadow map 2048,
-frustum just past the bounds; fog near ≈ half the bounds, far ≈ 1.5–2 × the diagonal;
-128 × 128 ground segments for 100 m (≈ 0.8 m resolution).
+Numbers: sun 2.2–3.2, hemisphere 0.4–0.7 (never both high — washed out); shadow frustum
+just past the bounds; fog near ≈ half the bounds, far ≈ 2 × the diagonal; ground ≈ 1
+segment per metre. Full palettes per time of day are in the time-of-day chapter.
+
+## The exact contract the harness assembler enforces
+
+`src/scene.js` is **written by the harness**, not by you — it is regenerated from your
+`src/env.js` + `src/zones/*.js` and overwrites anything you put there during the stages.
+That generated file is the only caller of your modules, so these five signatures are the
+whole interface. Get one wrong and your module is silently dropped or your animation
+never runs.
+
+```js
+// This is (verbatim) what the assembler generates and calls:
+//
+// const ctx = { THREE, scene, renderer, loaders, heightAt, assets };
+// const env = (await buildEnv(ctx)) || {}; // src/env.js -> ONE argument: ctx
+// ctx.env = env;
+// const g = await build(ctx); // src/zones/<snake>.js -> export name is `build`
+// if (!g || !g.isObject3D) throw ... // must return a Group/Object3D
+// scene.add(g);
+// function update(t, dt) {
+// if (env.update) env.update(t, dt); // env animation ONLY via env.update
+// for (const z of zones) if (z.userData.update) z.userData.update(t, dt);
+// } // zone animation ONLY via userData.update
+//
+// So:
+// src/env.js export function buildEnv(ctx) -> { ..., update(t, dt) } (+ heightAt, BOUNDS,
+// SUN_AZIMUTH_DEG, MATS)
+// src/zones/<snake>.js export function build(ctx) -> THREE.Group with .userData.update
+// src/assets/<snake>.js export function build<Asset>(THREE, opts) -> THREE.Group (called by zones)
+//
+// `tickEnv`, `userData.tick`, `buildEnv(THREE, scene)` and `build<Zone>(ctx)` are NEVER called.
+// An asset's own hook is only run if its zone forwards it (pattern below).
+function assemblerContractDemo(THREE) {
+ const zone = new THREE.Group(); zone.name = 'Demo';
+ const asset = new THREE.Group(); // an asset that animates itself
+ asset.userData.update = (t) => { asset.rotation.y = t * 0.8; };
+ zone.add(asset);
+ const movers = [asset]; // cache ONCE at build time
+ zone.userData.update = (t, dt) => { for (const a of movers) a.userData.update(t, dt); };
+ return zone;
+}
+const contractDemo = assemblerContractDemo(THREE);
+contractDemo.userData.update(1.5, 0.016);
+console.log('assembler contract demo rotated to', contractDemo.children[0].rotation.y.toFixed(2));
+```
+
+`SUN_AZIMUTH_DEG` (a plain `export const`, degrees) is read out of `src/env.js` **by
+regex** and used to place the harness's overview cameras on the sun side. Export it or
+the overview rig guesses 45° and may shoot into the sun.
+
+If the assembler is unavailable the harness asks you to write `src/scene.js` by hand: then
+write exactly the code in the comment above — `createScene({THREE, renderer, loaders})`
+returning `{ scene, cameras, update }`, cameras as plain `{name, position, lookAt, fov}`
+objects, animation fanned out through `env.update` and `zone.userData.update`.
+
+## Ground that reads real (blend, paths, edges — never one flat colour)
+
+A single-colour plane is the #1 reason a scene reads as a toy. Real ground is
+**three or four materials blended by height, slope and noise**, with paths carved into
+the height function itself and dressed edges where anything meets it.
+
+```js
+// --- deterministic value noise (no textures, no Math.random) -----------------
+const gHash = (x, z) => { const s = Math.sin(x * 127.1 + z * 311.7) * 43758.5453; return s - Math.floor(s); };
+function gNoise(x, z) { // smooth, C1, cheap
+ const xi = Math.floor(x), zi = Math.floor(z), fx = x - xi, fz = z - zi;
+ const u = fx * fx * (3 - 2 * fx), v = fz * fz * (3 - 2 * fz);
+ return (gHash(xi, zi) * (1 - u) + gHash(xi + 1, zi) * u) * (1 - v)
+ + (gHash(xi, zi + 1) * (1 - u) + gHash(xi + 1, zi + 1) * u) * v;
+}
+function gFbm(x, z) { return 0.6 * gNoise(x, z) + 0.3 * gNoise(x * 2.1, z * 2.1) + 0.1 * gNoise(x * 4.3, z * 4.3); }
+
+// --- the path is part of heightAt, so everything placed on it lands on it -----
+const PATH = [[-26, -20], [-9, -7], [4, 2], [17, 15], [26, 26]]; // polyline in meters
+const PATH_HALF_W = 0.9; // 1.8 m wide path
+function distToPath(x, z) {
+ let best = 1e9;
+ for (let i = 0; i < PATH.length - 1; i++) {
+ const [ax, az] = PATH[i], [bx, bz] = PATH[i + 1];
+ const vx = bx - ax, vz = bz - az, wx = x - ax, wz = z - az;
+ const t = Math.max(0, Math.min(1, (wx * vx + wz * vz) / (vx * vx + vz * vz)));
+ const dx = wx - t * vx, dz = wz - t * vz;
+ best = Math.min(best, Math.sqrt(dx * dx + dz * dz));
+ }
+ return best;
+}
+function terrainHeight(x, z) {
+ const base = 1.1 * gFbm(x * 0.035, z * 0.035) - 0.55 + 0.25 * Math.sin(x * 0.08) * Math.cos(z * 0.06);
+ const d = distToPath(x, z);
+ const flat = 1 - Math.min(1, Math.max(0, (d - PATH_HALF_W) / 2.2)); // 1 on the path → 0 at 3.1 m
+ return base * (1 - 0.85 * flat) - 0.05 * flat; // path is flat and slightly sunken
+}
+
+// --- colour by height + slope + noise + path ----------------------------------
+const GROUND_PALETTE = {
+ grass: 0x54702f, // flat, low, wet
+ dry: 0x8a8148, // flat, high
+ dirt: 0x6b5334, // moderate slope
+ rock: 0x6e6a63, // steep slope
+ path: 0xa89a7c, // gravel / packed earth
+};
+function buildBlendedGround(THREE, opts = {}) {
+ const size = opts.size ?? 160, seg = opts.seg ?? 160, h = opts.heightAt ?? terrainHeight;
+ const P = Object.assign({}, GROUND_PALETTE, opts.palette);
+ const g = new THREE.PlaneGeometry(size, size, seg, seg); g.rotateX(-Math.PI / 2);
+ const pos = g.attributes.position, col = new Float32Array(pos.count * 3);
+ const grass = new THREE.Color(P.grass), dry = new THREE.Color(P.dry), dirt = new THREE.Color(P.dirt);
+ const rock = new THREE.Color(P.rock), path = new THREE.Color(P.path), c = new THREE.Color();
+ const e = size / seg;
+ for (let i = 0; i < pos.count; i++) {
+ const x = pos.getX(i), z = pos.getZ(i), y = h(x, z);
+ pos.setY(i, y);
+ const slope = Math.min(1, (Math.abs(h(x + e, z) - y) + Math.abs(h(x, z + e) - y)) / (e * 1.2));
+ const n = gFbm(x * 0.35, z * 0.35); // breaks every band into patches
+ c.copy(grass).lerp(dry, THREE.MathUtils.clamp(0.35 + y * 0.5 + (n - 0.5) * 0.9, 0, 1));
+ c.lerp(dirt, THREE.MathUtils.smoothstep(slope, 0.12, 0.45));
+ c.lerp(rock, THREE.MathUtils.smoothstep(slope, 0.45, 0.9));
+ const onPath = 1 - THREE.MathUtils.smoothstep(distToPath(x, z), PATH_HALF_W, PATH_HALF_W + 1.4);
+ c.lerp(path, onPath * (0.75 + 0.25 * n));
+ c.offsetHSL(0, 0, (n - 0.5) * 0.05); // last 5 % of tonal break-up
+ col.set([c.r, c.g, c.b], i * 3);
+ }
+ g.setAttribute('color', new THREE.BufferAttribute(col, 3));
+ g.computeVertexNormals();
+ const mesh = new THREE.Mesh(g, new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 1.0, metalness: 0.0 }));
+ mesh.name = 'Ground'; mesh.receiveShadow = true;
+ return mesh;
+}
+const groundDemo = buildBlendedGround(THREE, { size: 120, seg: 120 });
+console.log('ground verts', groundDemo.geometry.attributes.position.count, 'coloured', !!groundDemo.geometry.attributes.color);
+```
+
+**Edge dressing.** Where anything meets the ground (fence, wall, deck, raised bed) sink it
+3–5 cm in AND scatter 6–15 small pieces (tufts, pebbles, leaves, moss) along the seam;
+raised platforms get a chamfered kerb, never a naked box edge.
+
+```js
+function dressSeam(THREE, { path, n = 24, radius = 0.35, spread = 0.5, color = 0x4f6b2c, heightAt = terrainHeight, seed = 3 }) {
+ // path = [[x, z], ...] the seam polyline; returns ONE InstancedMesh of tufts hugging it
+ const geo = new THREE.IcosahedronGeometry(radius, 0);
+ const mesh = new THREE.InstancedMesh(geo, new THREE.MeshStandardMaterial({ color, roughness: 1, flatShading: true }), n);
+ const m = new THREE.Matrix4(), q = new THREE.Quaternion(), up = new THREE.Vector3(0, 1, 0), p = new THREE.Vector3(), s = new THREE.Vector3();
+ for (let i = 0; i < n; i++) {
+ const u = (i + 0.5) / n * (path.length - 1), k = Math.min(path.length - 2, Math.floor(u)), f = u - k;
+ const x = path[k][0] + (path[k + 1][0] - path[k][0]) * f + (gHash(seed + i, 1) - 0.5) * spread;
+ const z = path[k][1] + (path[k + 1][1] - path[k][1]) * f + (gHash(seed + i, 2) - 0.5) * spread;
+ const sc = 0.5 + 0.9 * gHash(seed + i, 3);
+ q.setFromAxisAngle(up, gHash(seed + i, 4) * 6.283);
+ p.set(x, heightAt(x, z) - radius * 0.35 * sc, z); s.set(sc, sc * 0.6, sc);
+ m.compose(p, q, s); mesh.setMatrixAt(i, m);
+ }
+ mesh.instanceMatrix.needsUpdate = true; mesh.computeBoundingSphere();
+ mesh.name = 'SeamTufts'; mesh.castShadow = false; mesh.receiveShadow = true;
+ return mesh;
+}
+console.log('seam tufts', dressSeam(THREE, { path: [[-6, -6], [6, -6], [6, 6]] }).count);
+```
+
+Numbers: ground segments ≈ 1 per metre (160 × 160 for 160 m); ≥ 3 blended colours, each
+with ≥ 8 % of the visible area; path 1.2–2.0 m wide; a ground plane that is one flat
+colour, or a raised bed that is a sharp box on top of grass, are both graded as defects
+(`flat_ground`, `undressed_scene`).
+
+## Horizon: the world must not end (fixing `world_edge_visible`)
+
+The single most repeated judge complaint on this track is *"a hard world edge is visible
+against the sky"*. Three cheap rules kill it for good:
+
+1. **Ground reaches past the fog.** Ground size ≥ `2.4 × fogFar`. Detail only needs to
+ exist inside the bounds; beyond that, one big low-resolution disc is enough.
+2. **Fog colour == sky colour at the horizon.** Then the ground fades into the sky
+ instead of ending at it — and `fogFar` must be scaled to the scene (see the
+ time-of-day chapter: the table is for a 100 m scene, multiply by `diag / 100`).
+3. **A silhouette ring** at `radius ≈ 0.6 × fogFar` (and ≥ 2 × the bounds half-diagonal):
+ 24–40 low-poly hills / treeline / rooftops / mesa blocks, height 0.06–0.12 × radius,
+ tinted **65–80 %** of the way toward the fog colour. At 0.6 × fogFar the fog itself
+ desaturates them into aerial perspective — measured on a 45 m garden with fog 16/77 m:
+ a ring at 46 m reads as distant hills, the same ring at 95 m reads as a spiky crater
+ wall and the same ring at 20 m reads as a stone circle.
+
+```js
+function buildHorizonRing(THREE, opts = {}) {
+ const r = opts.radius ?? (opts.fogFar ? opts.fogFar * 0.6 : 60); // 0.6 x fog far
+ const n = opts.count ?? 30, h0 = opts.minHeight ?? r * 0.06, h1 = opts.maxHeight ?? r * 0.12;
+ const base = new THREE.Color(opts.color ?? 0x3d5236), fog = new THREE.Color(opts.fogColor ?? 0xa8c4dd);
+ const shape = opts.shape ?? 'hill'; // 'hill' (cone) | 'block' (city) | 'mesa'
+ const geo = shape === 'hill' ? new THREE.ConeGeometry(1, 1, 7)
+ : shape === 'mesa' ? new THREE.CylinderGeometry(0.75, 1, 1, 6)
+ : new THREE.BoxGeometry(1, 1, 1);
+ geo.translate(0, 0.5, 0); // origin at the base
+ const mat = new THREE.MeshStandardMaterial({ color: base.clone().lerp(fog, opts.hazeMix ?? 0.7), roughness: 1, flatShading: true });
+ const mesh = new THREE.InstancedMesh(geo, mat, n);
+ const m = new THREE.Matrix4(), q = new THREE.Quaternion(), up = new THREE.Vector3(0, 1, 0), p = new THREE.Vector3(), s = new THREE.Vector3();
+ for (let i = 0; i < n; i++) {
+ const a = (i + 0.35 * gHash(i, 7)) / n * Math.PI * 2;
+ const rr = r * (0.82 + 0.3 * gHash(i, 11));
+ const hgt = h0 + (h1 - h0) * gHash(i, 13);
+ const wid = hgt * (1.1 + 1.6 * gHash(i, 17));
+ q.setFromAxisAngle(up, gHash(i, 19) * 6.283);
+ p.set(Math.cos(a) * rr, -1.5, Math.sin(a) * rr); s.set(wid, hgt, wid);
+ m.compose(p, q, s); mesh.setMatrixAt(i, m);
+ }
+ mesh.instanceMatrix.needsUpdate = true; mesh.computeBoundingSphere();
+ mesh.name = 'HorizonRing'; mesh.castShadow = false; mesh.receiveShadow = false;
+ return mesh; // add to the SCENE (env), never to a zone
+}
+console.log('horizon ring', buildHorizonRing(THREE, { shape: 'block', color: 0x2b3140 }).count);
+```
+
+Indoor scenes (greenhouse, cabin) need no ring — but the *outside* seen through the glass
+must still be something: a haze gradient plus 5–10 silhouette shapes.
## Dusk / night lighting recipe (dark scenes are the #1 gate failure)
"Dusk", "night", "moonlit", "lantern-lit" means COLOURED darkness, never black. The harness
-measures every camera's frame (mean luminance, % near-black pixels) and a frame with mean
-luminance < 0.12 or > 35 % near-black pixels is a gate ERROR (`scene_frames: dark_frame`),
-capping the score at 0.55. Numbers that pass (ACES tone mapping, exposure 1.0):
+measures every camera's frame; mean luminance < 0.12 or > 35 % near-black pixels is a gate
+ERROR (`scene_frames: dark_frame`) capping the score at 0.55. Take the `dusk` / `night`
+row of the time-of-day table below for sky, sun, fill and fog, then add **practicals** —
+every lantern, window and fire is an emissive surface plus a small PointLight:
```js
-function buildDuskEnv(THREE, scene) {
- const SKY = 0x3a2a55, HORIZON = 0xd9703a; // purple zenith, orange horizon — NOT black
- scene.background = new THREE.Color(0x52355a);
- scene.fog = new THREE.Fog(0x52355a, 30, 140); // fog colour == sky colour at the horizon
- // fill: the sky itself lights the shade. Keep ≥ 0.5 at dusk, ≥ 0.35 at night.
- scene.add(new THREE.HemisphereLight(0x7a5aa0, 0x3a2e22, 0.7));
- // key: low warm sun (dusk) 2.0–3.0, or a cool moon 0.8–1.5 (night); still casts shadows
- const key = new THREE.DirectionalLight(0xffa060, 2.4);
- key.position.set(-60, 18, 30); key.castShadow = true;
- key.shadow.mapSize.set(2048, 2048); key.shadow.bias = -0.0005;
- Object.assign(key.shadow.camera, { left: -55, right: 55, top: 55, bottom: -55, near: 5, far: 200 });
- scene.add(key, key.target);
- // practicals: every lantern / window / fire = emissive surface + a small PointLight
- const glow = new THREE.MeshStandardMaterial({ color: 0xffc070, emissive: 0xffa040, emissiveIntensity: 3.0 });
- const lantern = new THREE.Mesh(new THREE.SphereGeometry(0.15, 12, 8), glow); lantern.position.set(4, 1.8, 2);
- const light = new THREE.PointLight(0xffa040, 1.5, 9, 2); light.position.copy(lantern.position);
- scene.add(lantern, light); // ≤ 12 PointLights, none cast shadows
- return { update(t, dt) {} };
+function addPracticals(THREE, scene, spots) {
+ const glowMat = new THREE.MeshStandardMaterial({ color: 0xffc070, emissive: 0xffa040, emissiveIntensity: 3.0 });
+ const out = [];
+ for (const [i, [x, y, z]] of spots.entries()) {
+ const bulb = new THREE.Mesh(new THREE.SphereGeometry(0.15, 12, 8), glowMat);
+ bulb.position.set(x, y, z); bulb.name = `Practical${i}`;
+ const light = new THREE.PointLight(0xffa040, 1.5, 9, 2); // ≤ 12 of these, none cast shadows
+ light.position.set(x, y, z);
+ scene.add(bulb, light); out.push(light);
+ }
+ return out; // flicker them from update(): intensity ×0.75…×1.3
}
+console.log('practicals', addPracticals(THREE, new THREE.Scene(), [[4, 1.8, 2], [-3, 2.1, 5]]).length);
```
Rules of thumb: sun/moon + hemisphere together ≥ 2.5 at dusk (≥ 1.5 at night with ≥ 6
-practicals); hemisphere sky/ground colours carry the mood (purple, indigo, amber) — turning
-the key down is NOT how you make dusk, tinting it is; ground albedo ≥ 0.25 (a 0x0b0f08 lawn
-is black under any light); no black `scene.background` — the sky gradient's horizon band
-should be the brightest thing in the frame.
+practicals); hemisphere sky/ground colours carry the mood — turning the key down is NOT how
+you make dusk, tinting it is; ground albedo ≥ 0.25; no black `scene.background` (the sky
+gradient's horizon band is the brightest thing in the frame).
**Exposure self-check (after each build):** run `scene_views` and read the frame table
-(`camera_checks` in the render's metrics.json) for every authored camera: `mean_lum` ≥ 0.15, `dark_frac` ≤ 0.25,
-`blown_frac` ≤ 0.10, `content_frac` ≥ 0.25 on the establishing shot. If the establishing
-frame is below 0.15, raise HemisphereLight by +0.3 and the key by +0.8 and re-render — do not
-ship a frame you cannot read.
+(`camera_checks` in the render's metrics.json) for every authored camera: `mean_lum` ≥ 0.15,
+`dark_frac` ≤ 0.25, `blown_frac` ≤ 0.10, `content_frac` ≥ 0.25 on the establishing shot. If
+the establishing frame is below 0.15, raise HemisphereLight by +0.3 and the key by +0.8 and
+re-render — do not ship a frame you cannot read.
+
+## Atmosphere: time-of-day triads with numbers
+
+Pick the row, use the numbers, then only tune exposure. `hemi` = HemisphereLight
+(sky colour / ground colour / intensity), `sun` = DirectionalLight (colour / intensity /
+elevation°). Fog colour is always the sky's **horizon** colour — never white, never grey
+unless the brief says overcast.
+
+| time of day | sky zenith | sky horizon = fog | sun colour | sun int | sun elev | hemi sky / ground | hemi int | fog near/far (100 m scene) |
+|---|---|---|---|---|---|---|---|---|
+| dawn | 0x2f4a72 | 0xe8a06a | 0xffb073 | 2.2 | 8° | 0x7d94c4 / 0x4a3a2c | 0.75 | 25 / 150 |
+| morning | 0x3d76c2 | 0xbcd6ea | 0xfff1d0 | 3.0 | 35° | 0xbfd6f0 / 0x5e5442 | 0.60 | 45 / 190 |
+| noon | 0x2f6fd0 | 0xcfe2f2 | 0xfffaf0 | 3.4 | 70° | 0xcfe2f2 / 0x6b6152 | 0.55 | 60 / 220 |
+| golden hour | 0x3b5f96 | 0xf0a860 | 0xffc27a | 2.8 | 12° | 0x86a8d8 / 0x5c4630 | 0.85 | 35 / 170 |
+| overcast | 0x8e9aa6 | 0xc3cad1 | 0xd8dee4 | 1.4 | 45° | 0xc3cad1 / 0x6f6a62 | 1.10 | 30 / 160 |
+| dusk | 0x33285c | 0xd9703a | 0xffa060 | 2.4 | 6° | 0x7a5aa0 / 0x3a2e22 | 0.80 | 30 / 140 |
+| night (moon) | 0x0d1430 | 0x22305a | 0xa8c0ff | 1.2 | 40° | 0x36406e / 0x1a1c24 | 0.55 | 25 / 120 |
+
+**Colour temperature contrast is the whole trick**: the key light is warm, the fill is the
+*opposite* hue (cool blue sky bounce). A scene lit warm-on-warm — orange sun with an
+orange hemisphere — comes out as the monochrome-orange soup the rooftop run was marked
+down for. Keep `hemi.color` at least 60° of hue away from the sun colour.
+
+```js
+const TIME_OF_DAY = {
+ dawn: { zenith: 0x2f4a72, horizon: 0xe8a06a, sun: 0xffb073, sunI: 2.2, elev: 8, hemiSky: 0x7d94c4, hemiGround: 0x4a3a2c, hemiI: 0.75, fog: [25, 150] },
+ morning: { zenith: 0x3d76c2, horizon: 0xbcd6ea, sun: 0xfff1d0, sunI: 3.0, elev: 35, hemiSky: 0xbfd6f0, hemiGround: 0x5e5442, hemiI: 0.60, fog: [45, 190] },
+ noon: { zenith: 0x2f6fd0, horizon: 0xcfe2f2, sun: 0xfffaf0, sunI: 3.4, elev: 70, hemiSky: 0xcfe2f2, hemiGround: 0x6b6152, hemiI: 0.55, fog: [60, 220] },
+ goldenHour: { zenith: 0x3b5f96, horizon: 0xf0a860, sun: 0xffc27a, sunI: 2.8, elev: 12, hemiSky: 0x86a8d8, hemiGround: 0x5c4630, hemiI: 0.85, fog: [35, 170] },
+ overcast: { zenith: 0x8e9aa6, horizon: 0xc3cad1, sun: 0xd8dee4, sunI: 1.4, elev: 45, hemiSky: 0xc3cad1, hemiGround: 0x6f6a62, hemiI: 1.10, fog: [30, 160] },
+ dusk: { zenith: 0x33285c, horizon: 0xd9703a, sun: 0xffa060, sunI: 2.4, elev: 6, hemiSky: 0x7a5aa0, hemiGround: 0x3a2e22, hemiI: 0.80, fog: [30, 140] },
+ night: { zenith: 0x0d1430, horizon: 0x22305a, sun: 0xa8c0ff, sunI: 1.2, elev: 40, hemiSky: 0x36406e, hemiGround: 0x1a1c24, hemiI: 0.55, fog: [25, 120] },
+};
+
+function applyTimeOfDay(THREE, scene, key, opts = {}) {
+ const T = TIME_OF_DAY[key] || TIME_OF_DAY.morning;
+ const az = (opts.azimuthDeg ?? 135) * Math.PI / 180, el = (opts.elevationDeg ?? T.elev) * Math.PI / 180;
+ const R = opts.sunDistance ?? 120, span = opts.shadowSpan ?? 60;
+ // the table's fog is calibrated for a 100 m scene: scale it by the bounds diagonal or
+ // a 30 m garden disappears into soup (and its horizon ring never hazes).
+ const fs = opts.fogScale ?? Math.min(2.5, Math.max(0.3, (opts.boundsDiagonal ?? 100) / 100));
+ scene.fog = new THREE.Fog(T.horizon, T.fog[0] * fs, T.fog[1] * fs);
+ scene.background = new THREE.Color(T.horizon);
+ const hemi = new THREE.HemisphereLight(T.hemiSky, T.hemiGround, T.hemiI);
+ const sun = new THREE.DirectionalLight(T.sun, T.sunI);
+ sun.position.set(Math.cos(el) * Math.sin(az) * R, Math.sin(el) * R, Math.cos(el) * Math.cos(az) * R);
+ sun.castShadow = true;
+ // shadow texel = 2*span / mapSize. Keep it ≤ 0.05 m or the edges look like stairs.
+ const mapSize = span <= 30 ? 2048 : span <= 60 ? 3072 : 4096;
+ sun.shadow.mapSize.set(mapSize, mapSize);
+ sun.shadow.bias = -0.0004; sun.shadow.normalBias = 0.02;
+ Object.assign(sun.shadow.camera, { left: -span, right: span, top: span, bottom: -span, near: 1, far: R * 2.2 });
+ sun.shadow.camera.updateProjectionMatrix?.();
+ scene.add(hemi, sun, sun.target);
+ return { sun, hemi, palette: T, fogFar: scene.fog.far, shadowTexelM: (2 * span) / mapSize };
+}
+const todScene = new THREE.Scene();
+const tod = applyTimeOfDay(THREE, todScene, 'goldenHour', { azimuthDeg: 250, shadowSpan: 26, boundsDiagonal: 45 });
+console.log('golden hour shadow texel (m)', tod.shadowTexelM.toFixed(3), 'fog far', tod.fogFar.toFixed(1), 'ring radius', (tod.fogFar * 0.6).toFixed(1));
+```
+
+**Haze layering / light shafts.** Three or four horizontal haze quads at 1–6 m
+(`depthWrite: false`, opacity 0.04–0.10, tinted the fog colour) make distance read even in
+a flat scene; light shafts are thin additive cones along the sun, ≤ 0.12 opacity or milk.
+
+```js
+function buildHazeBands(THREE, opts = {}) {
+ const n = opts.count ?? 4, size = opts.size ?? 200, color = opts.color ?? 0xd9c7a8;
+ const g = new THREE.Group(); g.name = 'HazeBands';
+ for (let i = 0; i < n; i++) {
+ const q = new THREE.Mesh(new THREE.PlaneGeometry(size, size).rotateX(-Math.PI / 2),
+ new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.035 + 0.02 * i, depthWrite: false, fog: false, side: THREE.DoubleSide }));
+ q.position.y = (opts.base ?? 3.0) + i * (opts.step ?? 1.8); // clear of eye-level cameras
+ q.renderOrder = 5 + i; g.add(q);
+ }
+ return g;
+}
+function buildLightShaft(THREE, opts = {}) {
+ const len = opts.length ?? 14, r = opts.radius ?? 1.6;
+ const cone = new THREE.Mesh(new THREE.CylinderGeometry(r * 0.25, r, len, 12, 1, true),
+ new THREE.MeshBasicMaterial({ color: opts.color ?? 0xffe6b8, transparent: true, opacity: opts.opacity ?? 0.09,
+ depthWrite: false, fog: false, side: THREE.DoubleSide, blending: THREE.AdditiveBlending }));
+ cone.name = 'LightShaft'; cone.renderOrder = 9;
+ const dir = (opts.dir ?? new THREE.Vector3(-0.4, -1, -0.25)).clone().normalize();
+ cone.position.copy(opts.at ?? new THREE.Vector3(0, len * 0.5, 0));
+ cone.quaternion.setFromUnitVectors(new THREE.Vector3(0, -1, 0), dir);
+ return cone;
+}
+console.log('haze bands', buildHazeBands(THREE).children.length, 'shaft', buildLightShaft(THREE).name);
+```
+
+Camera safety: the harness raycasts from every authored camera and calls anything within
+0.3 m "camera inside geometry" (an ERROR). Keep haze bands and shafts at least 1 m clear
+of every eye-level camera, or — since these cards are not solid surfaces — give them
+`mesh.raycast = () => {};` so the probe ignores them. Never do that to real geometry.
## Water plane (use makeWaterMaterial from the GLSL cookbook)
@@ -138,54 +426,186 @@ function buildLake(THREE, waterMat, x, z, r, level) {
}
```
-Why: water is a flat plane + the shader; the terrain function must dip below the water
-level inside the shoreline (add a radial depression term to `heightAt`).
+Why: water is a flat plane + the shader; `heightAt` must dip below the water level inside
+the shoreline (a radial depression term) or the shore z-fights.
+
+## Vegetation that reads real (species, jitter, clusters, ground cover)
-## Instanced vegetation and deterministic scatter
+A ring of identical cones is the second most common complaint. Fix it with **three to
+five species**, per-instance **scale / hue / rotation jitter**, **clustered** placement and
+a **ground-cover** layer. Every one of these is instanced, so the whole forest is 6–10
+draw calls.
```js
-function scatterMatrices(THREE, n, area, heightAt, seed = 1) {
- // hash-based, deterministic; NEVER Math.random(). area = {x, z, w, d}
- const out = []; const m = new THREE.Matrix4(), q = new THREE.Quaternion(), up = new THREE.Vector3(0, 1, 0);
+// One species = one geometry pair (trunk + crown) with its own silhouette + hue band.
+function speciesGeometries(THREE) {
+ return {
+ conifer: { trunk: new THREE.CylinderGeometry(0.10, 0.20, 3.0, 6).translate(0, 1.5, 0),
+ crown: new THREE.ConeGeometry(1.15, 4.4, 8).translate(0, 4.4, 0), hue: 0.32, sat: 0.42, lum: 0.20, h: [0.8, 1.5] },
+ broadleaf: { trunk: new THREE.CylinderGeometry(0.14, 0.26, 2.4, 7).translate(0, 1.2, 0),
+ crown: new THREE.IcosahedronGeometry(1.7, 1).translate(0, 3.4, 0), hue: 0.24, sat: 0.45, lum: 0.28, h: [0.9, 1.6] },
+ scrub: { trunk: new THREE.CylinderGeometry(0.07, 0.11, 0.7, 5).translate(0, 0.35, 0),
+ crown: new THREE.DodecahedronGeometry(0.75, 0).translate(0, 1.0, 0), hue: 0.18, sat: 0.35, lum: 0.30, h: [0.7, 1.3] },
+ };
+}
+
+// Clustered scatter: pick K cluster seeds, then drop members around them (Poisson-ish).
+function clusteredPoints(n, area, seed = 5, clusters = 0, spread = 0) {
+ const K = clusters || Math.max(2, Math.round(n / 7));
+ const sp = spread || Math.min(area.w, area.d) * 0.13;
+ const out = [];
for (let i = 0; i < n; i++) {
- const x = area.x + (rand(seed + i) - 0.5) * area.w;
- const z = area.z + (rand(seed + i + 5000) - 0.5) * area.d;
- const s = 0.7 + 0.6 * rand(seed + i + 9000);
- q.setFromAxisAngle(up, rand(seed + i + 13000) * Math.PI * 2);
- m.compose(new THREE.Vector3(x, heightAt(x, z), z), q, new THREE.Vector3(s, s, s));
- out.push(m.clone());
+ const k = i % K;
+ const cx = area.x + (gHash(seed + k, 101) - 0.5) * area.w * 0.9;
+ const cz = area.z + (gHash(seed + k, 103) - 0.5) * area.d * 0.9;
+ const a = gHash(seed + i, 107) * 6.283, r = sp * Math.sqrt(gHash(seed + i, 109));
+ out.push([cx + Math.cos(a) * r, cz + Math.sin(a) * r, k]);
}
return out;
}
-function buildOrchard(THREE, { heightAt }) {
- const zone = new THREE.Group(); zone.name = 'Orchard';
- const N = 60;
- const trunkGeo = new THREE.CylinderGeometry(0.09, 0.16, 2.2, 7).translate(0, 1.1, 0); // origin at the ROOT
- const crownGeo = new THREE.IcosahedronGeometry(1.3, 1).translate(0, 3.1, 0);
- const trunks = new THREE.InstancedMesh(trunkGeo, new THREE.MeshStandardMaterial({ color: 0x5a4028, roughness: 0.9 }), N);
- const crowns = new THREE.InstancedMesh(crownGeo, new THREE.MeshStandardMaterial({ color: 0x4a7a2e, roughness: 0.85 }), N);
- const mats = scatterMatrices(THREE, N, { x: 0, z: -12, w: 36, d: 24 }, heightAt, 7);
- const tint = new THREE.Color();
- mats.forEach((m, i) => {
- trunks.setMatrixAt(i, m); crowns.setMatrixAt(i, m);
- crowns.setColorAt(i, tint.setHSL(0.26 + 0.05 * rand(i + 33), 0.45, 0.32 + 0.1 * rand(i + 66))); // per-instance variety
+function buildForest(THREE, opts = {}) {
+ const area = opts.area ?? { x: 0, z: 0, w: 70, d: 70 };
+ const mix = opts.mix ?? { conifer: 34, broadleaf: 22, scrub: 40 };
+ const heightAtFn = opts.heightAt ?? terrainHeight, seed = opts.seed ?? 5;
+ const SP = speciesGeometries(THREE), group = new THREE.Group(); group.name = opts.name ?? 'Vegetation';
+ const bark = new THREE.MeshStandardMaterial({ color: 0x53412c, roughness: 0.95 });
+ const m = new THREE.Matrix4(), q = new THREE.Quaternion(), up = new THREE.Vector3(0, 1, 0);
+ const p = new THREE.Vector3(), s = new THREE.Vector3(), tint = new THREE.Color();
+ let si = 0;
+ for (const [name, count] of Object.entries(mix)) {
+ const sp = SP[name]; if (!sp || count <= 0) continue;
+ const trunks = new THREE.InstancedMesh(sp.trunk, bark, count);
+ const crowns = new THREE.InstancedMesh(sp.crown, new THREE.MeshStandardMaterial({ roughness: 0.85, flatShading: name !== 'broadleaf' }), count);
+ const pts = clusteredPoints(count, area, seed + si * 37);
+ pts.forEach(([x, z], i) => {
+ const k = sp.h[0] + (sp.h[1] - sp.h[0]) * gHash(seed + si * 31 + i, 211); // 1) scale jitter
+ const lean = (gHash(seed + i, 213) - 0.5) * 0.10; // 2) a few degrees of lean
+ q.setFromAxisAngle(up, gHash(seed + i, 217) * 6.283); // 3) yaw jitter
+ const qq = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0.3).normalize(), lean).multiply(q);
+ p.set(x, heightAtFn(x, z), z); s.set(k * (0.85 + 0.3 * gHash(i, 219)), k, k * (0.85 + 0.3 * gHash(i, 221)));
+ m.compose(p, qq, s); trunks.setMatrixAt(i, m); crowns.setMatrixAt(i, m);
+ tint.setHSL(sp.hue + (gHash(seed + i, 223) - 0.5) * 0.055, // 4) hue jitter ±0.03
+ sp.sat + (gHash(seed + i, 227) - 0.5) * 0.18,
+ sp.lum + (gHash(seed + i, 229) - 0.5) * 0.10); // 5) value jitter
+ crowns.setColorAt(i, tint);
+ });
+ trunks.instanceMatrix.needsUpdate = crowns.instanceMatrix.needsUpdate = true;
+ if (crowns.instanceColor) crowns.instanceColor.needsUpdate = true;
+ trunks.castShadow = crowns.castShadow = true; crowns.receiveShadow = true;
+ trunks.computeBoundingSphere(); crowns.computeBoundingSphere();
+ trunks.name = `${name}Trunks`; crowns.name = `${name}Crowns`;
+ group.add(trunks, crowns); si++;
+ }
+ return group;
+}
+const forestDemo = buildForest(THREE, { area: { x: 0, z: 0, w: 60, d: 60 } });
+console.log('forest draw calls', forestDemo.children.length, 'names', forestDemo.children.map(c => c.name).join(','));
+```
+
+**Ground cover + litter** turns "objects on a plane" into "plants growing out of the
+ground": one InstancedMesh of small tapered blades (no textures needed).
+
+```js
+function buildGroundCover(THREE, opts = {}) {
+ const n = opts.count ?? 900, area = opts.area ?? { x: 0, z: 0, w: 40, d: 40 };
+ const heightAtFn = opts.heightAt ?? terrainHeight, seed = opts.seed ?? 9;
+ const blade = new THREE.ConeGeometry(0.09, 0.34, 3).translate(0, 0.17, 0); // 3-sided = 1 tri/face, cheap
+ const mesh = new THREE.InstancedMesh(blade, new THREE.MeshStandardMaterial({ roughness: 1, flatShading: true }), n);
+ const m = new THREE.Matrix4(), q = new THREE.Quaternion(), up = new THREE.Vector3(0, 1, 0);
+ const p = new THREE.Vector3(), s = new THREE.Vector3(), c = new THREE.Color();
+ const pts = clusteredPoints(n, area, seed, Math.round(n / 25));
+ pts.forEach(([x, z], i) => {
+ const k = 0.6 + 1.1 * gHash(seed + i, 307);
+ q.setFromAxisAngle(up, gHash(seed + i, 311) * 6.283);
+ p.set(x, heightAtFn(x, z) - 0.02, z); s.set(k, k * (0.7 + 0.8 * gHash(i, 313)), k);
+ m.compose(p, q, s); mesh.setMatrixAt(i, m);
+ c.setHSL(0.25 + (gHash(seed + i, 317) - 0.5) * 0.06, 0.40 + 0.2 * gHash(i, 319), 0.22 + 0.14 * gHash(i, 323));
+ mesh.setColorAt(i, c);
});
- trunks.castShadow = crowns.castShadow = true;
- trunks.instanceMatrix.needsUpdate = crowns.instanceMatrix.needsUpdate = true;
- crowns.instanceColor.needsUpdate = true;
- trunks.computeBoundingSphere(); crowns.computeBoundingSphere();
- trunks.name = 'OrchardTrunks'; crowns.name = 'OrchardCrowns';
- zone.add(trunks, crowns);
- return zone;
+ mesh.instanceMatrix.needsUpdate = true; if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
+ mesh.computeBoundingSphere(); mesh.name = opts.name ?? 'GroundCover';
+ mesh.castShadow = false; mesh.receiveShadow = true;
+ return mesh;
+}
+const coverDemo = buildGroundCover(THREE, { count: 400, area: { x: 0, z: 0, w: 24, d: 24 } });
+console.log('ground cover', coverDemo.count, 'tris', coverDemo.count * 3);
+```
+
+Density per 100 m² of planted zone: 2–5 trees, 8–20 shrubs, 250–600 ground-cover tufts,
+30–80 litter pieces. Less than that and the judge writes *"monotonous / undressed"*.
+
+## Rocks, cliffs and boulders that read organic (never a row of boxes)
+
+Stacked cuboids read as buildings — the desert-canyon run lost 0.2 to exactly that. A
+rock is a **noise-displaced polyhedron**; a cliff is a **ridge polyline of rotated,
+non-uniformly scaled rock chunks with jittered strata**, never an axis-aligned wall.
+
+```js
+function rockGeometry(THREE, { radius = 1, detail = 1, rough = 0.34, seed = 1 } = {}) {
+ const g = new THREE.IcosahedronGeometry(radius, detail);
+ const pos = g.attributes.position;
+ for (let i = 0; i < pos.count; i++) {
+ const x = pos.getX(i), y = pos.getY(i), z = pos.getZ(i);
+ const d = 1 + rough * (gFbm(x * 1.7 + seed * 13, z * 1.7 + y * 1.1) - 0.5) * 2;
+ pos.setXYZ(i, x * d, y * d * 0.8, z * d); // flatter than tall = looks weathered
+ }
+ g.computeVertexNormals(); return g;
}
-const orchardDemo = buildOrchard(THREE, { heightAt });
-console.log('orchard instances', orchardDemo.children.map(c => c.count));
+
+function buildCliffRidge(THREE, opts = {}) {
+ // ridge = [[x, z], ...]; chunks straddle it with random yaw/tilt and strata colour bands
+ const ridge = opts.ridge ?? [[-30, -14], [-12, -10], [2, -6], [18, -9], [30, -16]];
+ const n = opts.count ?? 26, height = opts.height ?? 9, seed = opts.seed ?? 21;
+ const heightAtFn = opts.heightAt ?? terrainHeight;
+ const strata = (opts.strata ?? [0x8c4a2f, 0xa8663c, 0xc08a5a, 0x7a3b26]).map(h => new THREE.Color(h));
+ const group = new THREE.Group(); group.name = opts.name ?? 'CliffRidge';
+ const geo = rockGeometry(THREE, { radius: 1, detail: 1, rough: 0.42, seed });
+ const mesh = new THREE.InstancedMesh(geo, new THREE.MeshStandardMaterial({ roughness: 0.95, flatShading: true }), n);
+ const m = new THREE.Matrix4(), e = new THREE.Euler(), q = new THREE.Quaternion(), p = new THREE.Vector3(), s = new THREE.Vector3();
+ for (let i = 0; i < n; i++) {
+ const u = i / (n - 1) * (ridge.length - 1), k = Math.min(ridge.length - 2, Math.floor(u)), f = u - k;
+ const bx = ridge[k][0] + (ridge[k + 1][0] - ridge[k][0]) * f;
+ const bz = ridge[k][1] + (ridge[k + 1][1] - ridge[k][1]) * f;
+ const layer = i % strata.length; // stack in strata bands
+ const y0 = heightAtFn(bx, bz);
+ const lift = height * (0.18 + 0.26 * layer) * (0.75 + 0.5 * gHash(seed + i, 401));
+ const jx = (gHash(seed + i, 403) - 0.5) * 3.4, jz = (gHash(seed + i, 407) - 0.5) * 3.4;
+ e.set((gHash(seed + i, 409) - 0.5) * 0.5, gHash(seed + i, 411) * 6.283, (gHash(seed + i, 413) - 0.5) * 0.5);
+ q.setFromEuler(e);
+ p.set(bx + jx, y0 + lift * 0.55, bz + jz);
+ s.set(2.6 + 3.4 * gHash(seed + i, 415), lift * (0.7 + 0.6 * gHash(seed + i, 417)), 2.2 + 3.0 * gHash(seed + i, 419));
+ m.compose(p, q, s); mesh.setMatrixAt(i, m);
+ mesh.setColorAt(i, strata[layer].clone().offsetHSL(0, 0, (gHash(seed + i, 421) - 0.5) * 0.08));
+ }
+ mesh.instanceMatrix.needsUpdate = true; if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
+ mesh.computeBoundingSphere(); mesh.castShadow = mesh.receiveShadow = true; mesh.name = 'CliffChunks';
+ group.add(mesh); return group;
+}
+const cliffDemo = buildCliffRidge(THREE);
+console.log('cliff chunks', cliffDemo.children[0].count);
```
-Why: geometry origin at the root + `heightAt` in the matrix = nothing floats; one
-InstancedMesh per organ = 2 draw calls for a forest; `setColorAt` breaks the clone look.
-For wind, give the crowns `makeSwayMaterial` from the GLSL cookbook.
+Rules: chunk yaw random over the full circle (an axis-aligned box gives it away); scale
+non-uniform (x ≠ y ≠ z by ≥ 20 %); strata luminance differing by ≥ 0.08; the ridge
+polyline bending ≥ 15° at least twice; floor boulders reuse `rockGeometry` at 0.3–1.6 m.
+
+## Set dressing: how many props a place needs
+
+Judges call a scene "sparse", "token" or "undressed" long before they call it wrong.
+Counts that read as *lived in*, per zone (a zone is typically 10 × 10 m to 30 × 30 m):
+
+| scene type | hero assets | mid props (0.3–1.5 m) | small props (< 0.3 m) | ground cover / litter |
+|---|---|---|---|---|
+| garden / park | 3–5 (lantern, bridge, bench) | 12–25 (rocks, planters, pots, stumps, buckets) | 25–60 (pebbles, leaves, tools, cups, twigs) | 300–800 tufts |
+| desert / canyon | 2–4 (hero boulder, arch, wreck) | 15–30 boulders in 3 size bands | 30–70 (pebbles, bones, dry brush) | 60–200 scrub clumps |
+| rooftop / urban | 3–6 (pergola, planters, lounge) | 15–30 (pots, crates, lamps, chairs, vents, ducts) | 30–80 (cups, books, cushions, cables, bottles) | 100–300 plant tufts |
+| interior | 3–6 (bench rows, water feature) | 15–30 (pots, tools, watering cans, crates) | 40–100 (labels, trowels, gloves, jars) | n/a |
+
+Cheap rules: 3 size bands per prop family, one InstancedMesh per band; place props
+**against something** (a wall base, a path edge, under a bench) — props alone in open
+ground read as scatter, not dressing; never a perfect grid or ring (≥ 20 % positional
+jitter, full yaw jitter).
## Zones (`src/zones/*.js`): Groups with a bbox discipline
@@ -241,26 +661,14 @@ async function loadAsset(loaders, name) {
console.log('lantern ok', buildLantern(THREE).children.length);
```
-Why: a scene mixes cheap instanced fillers with a few hero assets; GLBs come in Y-up
-meters (same frame), so a loaded asset is placed exactly like a procedural one.
+Why: a scene mixes cheap instanced fillers with a few hero assets; GLBs come in Y-up meters
+(same frame), so a loaded asset is placed exactly like a procedural one.
## Animation: update(t, dt) patterns + particles
```js
-function buildBoat(THREE) {
- const boat = new THREE.Group(); boat.name = 'Boat';
- const hull = new THREE.Mesh(new THREE.CylinderGeometry(0.5, 0.2, 2.6, 8).rotateZ(Math.PI / 2).rotateY(Math.PI / 2),
- new THREE.MeshStandardMaterial({ color: 0x7a4a26, roughness: 0.7 }));
- boat.add(hull);
- const home = new THREE.Vector3(6, 0.0, 8);
- boat.position.copy(home);
- boat.userData.update = (t) => { // bobbing + slow drift; pure function of t
- boat.position.y = home.y + Math.sin(t * 0.9) * 0.06;
- boat.rotation.z = Math.sin(t * 0.7 + 1.0) * 0.04;
- boat.rotation.x = Math.sin(t * 1.1) * 0.03;
- };
- return boat;
-}
+// Rigid movers: cache a `home` Vector3 at build time, then set (never accumulate) the
+// pose from t — `obj.position.y = home.y + Math.sin(t * 0.9) * 0.06` etc.
// Particles: THREE.Points + PointsMaterial is enough for dust/fireflies/snow (custom
// point shaders only if the plan demands). Recycle positions inside update.
function buildFireflies(THREE, n = 120, area = { x: 0, z: 0, w: 30, d: 30 }) {
@@ -288,6 +696,107 @@ console.log('fireflies', ff.geometry.attributes.position.count);
Rules: `update` mutates cached objects only — no `new`, no `traverse`, no material
creation per frame. Everything is a function of `t` (deterministic renders at t = 1.5).
+## Motion you can SEE between t = 0 and t = 1.5 s
+
+The harness renders every camera at t = 0 and t = 1.5 s and the judge diffs the two
+frames. Sub-centimetre sway is invisible at 1024 × 576 and scores as `nothing_moves`
+(−0.05 and the whole animation criterion). Amplitudes that actually read:
+
+| what moves | amplitude | period | note |
+|---|---|---|---|
+| foliage sway | ±0.10–0.20 rad (6–11°) | 1.6–3 s | rotate the crown/branch group, not the trunk base |
+| grass / reeds | ±0.15 rad | 1.2–2 s | phase-offset per instance |
+| water | wave height ≥ 0.04 m **and** a scrolling normal/uv at ≥ 0.15 m/s | 2–4 s | a still mirror reads as static |
+| falling leaves / petals / snow / dust | ≥ 0.6 m of travel in 1.5 s | recycle over 6–12 s | 60–250 particles |
+| flags / banners / string lights | ±0.12 rad | 1.2 s | the classic "the scene is alive" cue |
+| flame / lantern flicker | intensity ×0.75…×1.3 | 0.1–0.3 s | plus emissiveIntensity on the material |
+| vehicles / boats / birds | ≥ 1.5 m of travel in 1.5 s | loop | one hero mover beats ten twitchers |
+
+Give the scene **one unmistakable hero motion** (rotating beam, drifting boat, falling
+leaves, spinning wheel, flock) plus the ambient ones — all pure functions of `t`.
+
+```js
+function makeSwayGroup(THREE, child, opts = {}) {
+ // wrap anything in a pivot that sways visibly; pivot at the BASE so it bends, not slides
+ const pivot = new THREE.Group(); pivot.name = opts.name ?? 'Sway';
+ pivot.add(child);
+ const amp = opts.amp ?? 0.14, per = opts.period ?? 2.2, ph = opts.phase ?? 0;
+ pivot.userData.update = (t) => {
+ pivot.rotation.z = Math.sin((t / per) * 6.283 + ph) * amp;
+ pivot.rotation.x = Math.sin((t / (per * 1.37)) * 6.283 + ph * 1.7) * amp * 0.55;
+ };
+ return pivot;
+}
+const swayDemo = makeSwayGroup(THREE, new THREE.Mesh(new THREE.ConeGeometry(0.6, 2, 6), new THREE.MeshStandardMaterial({ color: 0x3f6b2a })));
+swayDemo.userData.update(0); const a0 = swayDemo.rotation.z;
+swayDemo.userData.update(1.5); const a1 = swayDemo.rotation.z;
+console.log('sway delta (rad) over 1.5s', Math.abs(a1 - a0).toFixed(3), (Math.abs(a1 - a0) > 0.05 ? 'VISIBLE' : 'TOO SMALL'));
+```
+
+Self-check: after `scene_views(times=[0, 1.5])`, look at the two sheets side by side. If
+you cannot point at what changed, the amplitude is too small — double it.
+
+## Scene layering: foreground, midground, background
+
+A "diorama on an empty plane" scores ~0.5 whatever else you do. Every authored camera
+must have **three depth layers**, and you build them on purpose:
+
+| layer | distance from camera | what lives there | how much of the frame |
+|---|---|---|---|
+| foreground frame | 1.5–5 m | a branch, a post, a parapet edge, a leaning tool, tall grass, an arch | 10–25 % of the frame area, usually at an edge/corner, may be partly cut off |
+| midground subject | 8–30 m | the hero assets: what the brief is about | fills the centre third |
+| background | 40 m–fog far | silhouette ring, distant treeline / skyline / mesas, sky gradient | the top third |
+
+```js
+// Place a framing element just off the camera's axis, at 2-4 m, so it brackets the shot.
+function frameForeground(THREE, cam, object, opts = {}) {
+ const dist = opts.dist ?? 3.0, side = opts.side ?? -1, lift = opts.lift ?? 0;
+ const eye = new THREE.Vector3().fromArray(cam.position);
+ const at = new THREE.Vector3().fromArray(cam.lookAt);
+ const fwd = at.clone().sub(eye).setY(0).normalize();
+ const right = new THREE.Vector3().crossVectors(fwd, new THREE.Vector3(0, 1, 0)).normalize();
+ const pos = eye.clone().add(fwd.multiplyScalar(dist)).add(right.multiplyScalar(side * dist * 0.75));
+ object.position.set(pos.x, (opts.heightAt ?? terrainHeight)(pos.x, pos.z) + lift, pos.z);
+ object.rotation.y = Math.atan2(eye.x - pos.x, eye.z - pos.z) + (opts.yaw ?? 0);
+ return object;
+}
+const camDemo = { name: 'Establishing', position: [24, 9, 26], lookAt: [0, 2, 0], fov: 42 };
+const framer = frameForeground(THREE, camDemo, new THREE.Mesh(rockGeometry(THREE, { radius: 1.4, seed: 4 }),
+ new THREE.MeshStandardMaterial({ color: 0x5b5348, roughness: 1, flatShading: true })), { side: -1 });
+console.log('foreground framer at', framer.position.toArray().map(v => +v.toFixed(2)).join(','));
+```
+
+**Keep the cameras' first metres clear.** Scatter is blind: it will happily plant a
+conifer 1 m in front of the establishing camera and turn the money shot into a wall of
+bark (measured — it cost a whole grade before the mask was added). Every scatter loop
+skips instances inside a clearance disc around each authored camera, and the establishing
+camera sits *above the canopy*: `y ≥ tallest thing in the shot + 0.30 × distance to the
+subject`, looking DOWN at the subject.
+
+```js
+// Give every zone the authored camera list, then mask the SCATTER with it (deliberate
+// foreground props are placed by hand afterwards and are not masked).
+function cameraMask(cameras, opts = {}) {
+ // 2.5-5 m is enough: bigger discs leave bald patches in a small scene
+ const r = opts.radius ?? 4, discs = cameras.map(c => [c.position[0], c.position[2], r]);
+ for (const c of cameras) { // also clear 25 % of the way to the subject
+ const dx = c.lookAt[0] - c.position[0], dz = c.lookAt[2] - c.position[2];
+ discs.push([c.position[0] + dx * 0.22, c.position[2] + dz * 0.22, r * 0.6]);
+ }
+ return (x, z) => discs.some(([cx, cz, rr]) => (x - cx) ** 2 + (z - cz) ** 2 < rr * rr);
+}
+const maskDemo = cameraMask([{ name: 'Establishing', position: [8, 10.5, 22], lookAt: [0, 1.4, -1], fov: 44 }]);
+console.log('camera mask blocks (8,22)?', maskDemo(8, 22), ' blocks (0,0)?', maskDemo(0, 0));
+```
+
+Skipped instances are not deleted — write a zero-scale matrix (`m.makeScale(0, 0, 0)`) so
+the instance count and every index stay stable.
+
+**Atmospheric perspective** does the rest: with fog matching the sky, a background object
+loses contrast and saturation with distance for free. Push it further by tinting distant
+materials 40–70 % toward the fog colour (`base.clone().lerp(fogColor, 0.5)`), as the
+horizon ring does.
+
## Cameras: measured, never guessed
```js
@@ -301,7 +810,7 @@ function planCameras(THREE, scene) {
// 1) establishing: high 3/4, sees ≥70% of bounds, sun BEHIND the camera shoulder
{ name: 'Establishing', position: [c.x + d * 0.55, size.y * 1.1 + 6, c.z + d * 0.6], lookAt: [c.x, 2, c.z], fov: 42 },
// 2) mid: inside the scene at eye height, aimed at a zone's focal point
- { name: 'OrchardMid', position: [8, heightAt(8, 6) + 1.6, 6], lookAt: [0, heightAt(0, -10) + 2.0, -10], fov: 50 },
+ { name: 'GroveMid', position: [8, heightAt(8, 6) + 1.6, 6], lookAt: [0, heightAt(0, -10) + 2.0, -10], fov: 50 },
// 3) detail: 2-4 m from a hero object, slightly above eye line
{ name: 'CampfireDetail', position: [-11, heightAt(-11, 8) + 1.8, 8], lookAt: [-14, heightAt(-14, 10) + 0.6, 10], fov: 45 },
];
@@ -315,12 +824,10 @@ establishing → mid → detail. Compute positions from measured bounds/heightA
## Post-processing (optional; the default pipeline renders WITHOUT it)
-```js
-import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
-import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
-import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
-import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
+Imports: `EffectComposer`, `RenderPass`, `UnrealBloomPass`, `OutputPass` from
+`three/addons/postprocessing/*.js`.
+```js
// Export from scene.js ONLY if the plan asks for bloom; harness support is optional, so
// the scene must also look right without it (emissiveIntensity ≤ 3, no white-out).
function makeComposer(THREE, renderer, scene, camera, width, height) {
@@ -337,11 +844,12 @@ console.log('composer factory ready', typeof makeComposer);
## Performance budget
-* ≤ 2 M triangles, ≤ 200 draw calls, ≤ 40 materials, ≤ 3 shadow casting lights.
-* Anything placed > 5 × = InstancedMesh; static clutter of one material = `mergeGeometries`.
-* Ground 128² segments max; trees 300–800 tris each (instanced), hero assets ≤ 40 k.
-* `update` < 4 ms: cache lists, mutate in place, no per-frame allocation.
-* `scene_probe` reports draws/tris/fps — run it before polishing.
+* ≤ 2 M triangles, ≤ 200 draw calls, ≤ 40 materials, ≤ 3 shadow-casting lights; anything
+ placed > 5 × is an InstancedMesh, static one-material clutter is `mergeGeometries`.
+* Ground ≤ 160² segments; trees 300–800 tris each (instanced), hero assets ≤ 40 k;
+ `update` < 4 ms (cache lists, mutate in place, no per-frame allocation).
+* `scene_probe` reports draws/tris/fps — run it before polishing. Under 20 fps the usual
+ criminals are un-instanced repeats, per-frame `traverse`, and 4096² shadow maps.
## Pitfalls (symptom → cause → fix)
@@ -374,6 +882,22 @@ console.log('composer factory ready', typeof makeComposer);
belong to the env (paths, fences).
14. **Lights per lantern** → 30 PointLights kill the frame; ONE emissive material + 1–2
real lights near the camera path.
+15. **`nothing_moves` although you animated things** → the hook is named `userData.tick`
+ (never called), or `tickEnv` (never called), or the amplitude is < 2 cm / < 0.05 rad so
+ t=0 and t=1.5 look identical. Hook = `userData.update`; amplitudes from
+ "Motion you can SEE".
+16. **A tree 1 m in front of the establishing camera** → the scatter loop had no camera
+ mask; see `cameraMask` in "Scene layering".
+17. **Distant hills look like bright orange spikes, not haze** → the silhouette ring sits
+ far inside `fog.far` (so fog never touches it) or its `hazeMix` is < 0.6. Ring radius
+ ≈ 0.6 × fog far; fog far itself must be scaled to the bounds diagonal.
+18. **Jagged / stair-stepped shadows** → shadow texel = `2 × shadowSpan / mapSize`; keep it
+ ≤ 0.05 m. A 60 m span needs 3072², a 100 m span needs 4096² — or shrink the span to
+ the bounds instead of the whole terrain.
+19. **Monochrome orange (or blue) frame** → key and fill share a hue. The fill
+ (HemisphereLight sky colour) must be ≥ 60° of hue away from the sun colour.
+20. **The scene is a diorama on a plane** → no foreground layer and no background layer.
+ Three depth layers per authored camera, always ("Scene layering").
## Self-check (before you call it done)
@@ -396,10 +920,20 @@ function sceneSelfcheck(THREE, scene, cameras) {
console.log(`[selfcheck] draws=${draws} tris=${Math.round(tris)} lights=${lights} cameras=${cameras.length}`);
}
const demoScene = new THREE.Scene(); buildEnv(THREE, demoScene);
-demoScene.add(orchardDemo, campfireDemo, ff);
+demoScene.add(forestDemo, coverDemo, campfireDemo, ff);
sceneSelfcheck(THREE, demoScene, planCameras(THREE, demoScene));
```
+Composition self-check on every authored frame (the judge grades exactly these):
+
+* three depth layers — something inside 5 m, the subject at 8–30 m, a silhouette/sky band above;
+* no hard world edge anywhere against the sky;
+* the ground shows ≥ 3 blended colours and at least one path / worn area;
+* vegetation shows ≥ 3 silhouettes and visible hue/scale variation, in clusters not a ring;
+* ≥ 12 mid props and ≥ 25 small props per dressed zone, placed against things;
+* shade is coloured (sky-tinted), not black; key and fill hues differ;
+* t=0 and t=1.5 are visibly different.
+
Then: `build` → `scene_probe` (draws/tris/fps/console) → `scene_views` (authored cameras +
overview rig, with `camera_checks`) → `shader_probe` if you wrote GLSL → fix the worst →
repeat. Look at every camera's frame AND its numbers: `mean_lum` ≥ 0.15 (no black frames),
diff --git a/harness/codeverse/prompts/tracks/plan_scene.j2 b/harness/codeverse/prompts/tracks/plan_scene.j2
index 00f21d61..63aaceed 100644
--- a/harness/codeverse/prompts/tracks/plan_scene.j2
+++ b/harness/codeverse/prompts/tracks/plan_scene.j2
@@ -8,36 +8,103 @@ The scene uses the same frame: Y up, meters; the ground is around y=0 unless you
LANGUAGE CONTRACT THE BUILDERS WILL FOLLOW:
{{ contract }}
+## What this track is graded on (write the plan that wins these points)
+A scene scores 0.8+ only when every authored camera makes a PICTURE: three depth layers
+(something within 5 m framing the shot, the subject at 8-30 m, a hazy horizon above), ground
+that is several blended materials with paths and worn edges, vegetation/rock in 3+ species with
+size and hue variation in clusters, a lived-in amount of small props, coloured atmosphere with
+warm key vs cool fill, and motion you can see between t=0 s and t=1.5 s. A correct-but-bare
+scene — a diorama of a few objects on one flat coloured plane, ringed by identical cones, under
+flat light — scores ~0.5 no matter how well it is coded. Your plan must make the bare version
+impossible: put the counts, the layers, the colours and the amplitudes in the text.
+
WHAT TO PRODUCE (JSON, fields: {{ schema_fields }}):
1. `title`, `summary` (two sentences), `setting` (place, era, weather, time of day), `mood`.
-2. `bounds` — centre + extents in meters of the whole playable area (a garden 30 × 10 × 30 m; a
- harbour 120 × 30 × 120 m). Keep it as small as the brief allows: detail beats acreage.
-3. `environment` — ONE paragraph with numbers: sky colours (hex), sun/moon direction as azimuth +
- elevation in degrees, light colour/intensity, fog colour + density, ground material and height,
- water plane height if any.
-4. `zones` — 3 to 8 spatial regions with PascalCase names, a description of what is there and how it
- is laid out (paths, clusters, spacing in meters), a `bbox`, and `contents` = asset names placed
- there. Zone bboxes tile the bounds without overlapping by more than 1 m.
-5. `assets` — 4 to 12 reusable things placed in zones. PascalCase `name`; `kind` = `threejs` for
- procedural shapes (fences, lanterns, rocks, benches, trees, boats) or `blender_glb` ONLY for 1-3
- hero objects that need sculpted/bevelled detail; `description` with construction numbers and
- colours; `approx_size_m` = width × height × depth in meters (a stone lantern 0.5 × 1.6 × 0.5;
- a bench 1.6 × 0.9 × 0.6; a pine 3 × 7 × 3); `instances_hint` = how many appear in total.
- Ground cover, terrain, water and sky are NOT assets — they belong to the environment / zones.
+2. `bounds` — centre + extents in meters of the whole playable area (a garden 30 x 10 x 30 m; a
+ harbour 120 x 30 x 120 m). Keep it as small as the brief allows: detail beats acreage.
+3. `environment` — ONE paragraph, all numbers, covering IN THIS ORDER:
+ (a) sky zenith + horizon hex and the sun/moon azimuth + elevation in degrees;
+ (b) key light hex + intensity AND fill (hemisphere) sky/ground hex + intensity — the fill hue
+ must be at least 60 degrees away from the key hue (warm sun, cool sky) or the frame comes
+ out monochrome;
+ (c) fog hex (= the sky HORIZON colour, never white or grey unless overcast) + near/far in
+ meters, scaled to this scene: near ~ 0.4 x the bounds diagonal, far ~ 2 x the diagonal;
+ (d) ground: the 3-4 material colours that blend across it (e.g. moss 0x4a602e, dry grass
+ 0x8a8148, packed dirt 0x6b5334, gravel 0xa89a7c), which drives the blend (height, slope,
+ noise), and where the PATH runs as a polyline of 3-5 (x, z) points, 1.2-2.0 m wide;
+ (e) the BACKDROP that hides the world edge: a silhouette ring (hills / treeline / rooftops /
+ mesas) at radius ~ 0.6 x fog far, 24-40 pieces, tinted 70 % toward the fog colour — or,
+ for an interior, what is seen through the glass;
+ (f) water plane height + colour, if any.
+4. `zones` — 3 to 6 spatial regions with PascalCase names, a `bbox`, and `contents` = asset names
+ placed there. Zone bboxes tile the bounds without overlapping by more than 1 m.
+ Each zone `description` MUST state, as numbers:
+ - its DEPTH ROLE for the cameras: `foreground frame`, `midground subject` or `background`;
+ - the layout (paths, clusters, spacing in meters, what faces what);
+ - DENSITY COUNTS: how many trees / shrubs / rocks / mid props (0.3-1.5 m) / small props
+ (< 0.3 m) / ground-cover tufts it contains. Target per zone: 12-25 mid props, 25-60 small
+ props, 300-800 ground-cover tufts for a planted zone (desert: 15-30 boulders in 3 size
+ bands, 60-200 scrub clumps; interior: 15-30 mid, 40-100 small);
+ - the VARIATION rule: at least 3 distinct silhouettes for any repeated natural element, with
+ +/-30 % scale jitter and +/-0.03 hue jitter — never one shape stamped in a ring or grid.
+5. `assets` — 4 to 8 reusable things placed in zones. PascalCase `name`; `kind` = `threejs` for
+ procedural shapes (fences, lanterns, rocks, benches, trees, boats) or `blender_glb` ONLY for
+ 1-2 hero objects that need sculpted/bevelled detail; `description` with construction numbers
+ and colours; `approx_size_m` = width x height x depth in meters (a stone lantern
+ 0.5 x 1.6 x 0.5; a bench 1.6 x 0.9 x 0.6; a pine 3 x 7 x 3); `instances_hint` = how many
+ appear in total. Prefer FEWER asset modules with a `variant` range (say "5 variants via
+ opts.variant: three trunk shapes, two crown shapes") over many near-duplicate modules —
+ variation belongs inside an asset, not in the asset list. Ground cover, terrain, water,
+ backdrop and sky are NOT assets — they belong to the environment / zones.
6. `effects` — 1 to 4: `glsl_material` (water ripple, lantern glow, wind-swayed foliage),
`particles` (petals, sparks, snow), `animated_geometry`, or `postprocess`; say which zone/asset.
-7. `animation` — 2 to 6 lines of what moves: amplitude + frequency in numbers.
-8. `cameras` — 2 to 4 authored cameras: `position`, `look_at` (meters), `fov` 35-70, `purpose`
- (establishing shot from outside the bounds looking in; eye level at 1.6-1.8 m inside a zone; a
- detail shot of the hero asset). Every camera must see at least two zones or a hero asset.
+7. `animation` — 2 to 6 lines of what moves, each with an amplitude that is VISIBLE in a
+ 1024x576 frame after 1.5 s: foliage sway +/-0.10-0.20 rad over 1.6-3 s; grass +/-0.15 rad;
+ water waves >= 0.04 m plus a scroll >= 0.15 m/s; particles travelling >= 0.6 m per 1.5 s;
+ vehicles/boats/beams >= 1.5 m or a full revolution per 1.5 s; light flicker x0.75-x1.3.
+ Exactly one of them is the HERO motion: the single thing a viewer cannot miss.
+8. `cameras` — 3 to 4 authored cameras. The harness uses your numbers LITERALLY, so compute them:
+ - `cameras[0]` is the establishing shot. Pick the SUBJECT (the hero asset or the zone the
+ brief is about) and its centre point S. Put the camera at distance
+ D = 1.5 x (subject radius) / tan(fov/2) from S, at height
+ y = (tallest thing between camera and subject) + 0.30 x D, looking AT S (not at the bounds
+ centre, not at the horizon). It must see 2+ zones and >= 20 % of the frame must be content
+ rather than empty sky/ground.
+ - one eye-level camera INSIDE the scene at y = ground + 1.6-1.8 m, aimed along a path or
+ across the subject so that something within 5 m frames one edge of the shot;
+ - one detail camera 2-4 m from the hero asset, slightly above its mid height.
+ - `purpose` must name the subject, the foreground framing element and what is on the horizon
+ for that shot ("establishing: the arched bridge at 14 m, framed by the maple on the right at
+ 3 m, cedar ridge on the horizon").
+ - No camera may be inside or within 0.5 m of geometry; fov 35-60.
9. `acceptance` — 6 to 12 items: each must-have from the brief, the hero assets visible from the
- establishing camera, time-of-day lighting reads correctly, animation visible between t=0 and
- t=1.5 s, no floating or sunken assets (`how: probe`), fps ≥ 30 at 1024×576.
+ establishing camera, time-of-day lighting reads correctly, the hero motion is visible between
+ t=0 and t=1.5 s, no floating or sunken assets (`how: probe`), no hard world edge visible from
+ any authored camera, fps >= 30 at 1024x576.
RULES
- Every name in `zones[].contents` must be an asset name; asset names unique; zone names unique.
- Realistic scale: people 1.7 m, doors 2.1 m, steps 0.17 m, benches 0.45 m seat height.
-- Prefer ≤ 8 assets and 3-5 zones for modest briefs. No prose outside the JSON.
+- Prefer <= 8 assets and 3-5 zones for modest briefs. No prose outside the JSON.
-WORKED EXAMPLE (shape only — do not copy its values):
+WORKED EXAMPLE (field SHAPE only — its prose is deliberately terse and does NOT meet the
+`environment` / zone-description / camera-purpose requirements above):
{{ example_json }}
+
+HOW THE THREE PROSE FIELDS MUST ACTUALLY READ (style, not values):
+- environment: "Sky zenith 0x3b5f96 to horizon 0xf0a860, sun azimuth 250 deg elevation 12 deg,
+ key 0xffc27a at 2.8, hemisphere sky 0x86a8d8 / ground 0x5c4630 at 0.85 (cool fill against the
+ warm key); fog 0xf0a860 near 16 m far 77 m (bounds diagonal 45 m); ground blends moss 0x4a602e,
+ dry grass 0x8a8148, packed dirt 0x6b5334 and gravel 0xa89a7c by slope and noise, with a 1.6 m
+ gravel path through (-14,-11), (-5,-4), (2,1), (9,8) flattened into heightAt; backdrop = 30
+ cedar-ridge silhouettes at radius 46 m, 3-6 m tall, tinted 70 % to the fog colour; pond plane
+ at y=-0.35, 0x2c4a52."
+- zone description: "MIDGROUND SUBJECT. The koi pond and arched bridge on the path's east bend.
+ 1 bridge, 2 stone lanterns 4 m apart facing the path, 3 pond rocks in 3 sizes, 18 mid props
+ (potted shrubs, a water basin, a stacked-stone kerb, a bucket, a bamboo scoop), 34 small props
+ (pebbles along the pond rim, fallen maple leaves, a rope coil, moss patches), 500 ground-cover
+ tufts outside the gravel. Vegetation uses 3 silhouettes (upright pine, low maple, round shrub)
+ with +/-30 % scale and +/-0.03 hue jitter, in 4 clusters, never a ring."
+- camera purpose: "establishing: the arched bridge (subject centre 1.5, 0.9, -0.8, radius 4.5 m)
+ from the south-east above the maples, framed by the lantern at 3 m on the left edge, cedar ridge
+ on the horizon; sees PondBasin and ZenGarden."
diff --git a/harness/codeverse/prompts/tracks/scene_asset.j2 b/harness/codeverse/prompts/tracks/scene_asset.j2
index d0bf3427..969bc0f0 100644
--- a/harness/codeverse/prompts/tracks/scene_asset.j2
+++ b/harness/codeverse/prompts/tracks/scene_asset.j2
@@ -32,8 +32,10 @@ Scene: {{ spec_prompt }}
details deterministically (use a tiny mulberry32 PRNG inside the file — never Math.random).
- Build from primitives (Box/Cylinder/Cone/Sphere/Lathe/Extrude/Tube) with MeshStandardMaterial
colours in hex; merge repeated pieces with InstancedMesh when > 20 copies.
-- Set `group.userData.size = [w, h, d]` to the measured size. Optional
- `group.userData.tick = (t, dt) => {...}` for subtle motion.
+- Set `group.userData.size = [w, h, d]` to the measured size. Optional animation hook:
+ `group.userData.update = (t, dt) => {...}` (the zone that places you caches it and calls it;
+ `userData.tick` is never called by anything). Amplitudes must be visible after 1.5 s:
+ >= 0.10 rad of rotation or >= 0.05 m of travel — not sub-centimetre jitter.
- No DOM, no texture/image loading, no fetch, no imports except `import * as THREE from 'three'`.
- ≤ 15k triangles per instance; segments 12-24.
{% endif %}
@@ -41,7 +43,15 @@ Scene: {{ spec_prompt }}
## DO / DON'T
- DO use the exact size numbers above; the zone builders rely on them.
- DO give it the 3-4 recognisable features a person would name (a stone lantern: base, post, light
- box with 4 windows, curved roof, finial).
+ box with 4 windows, curved roof, finial) — plus 2-3 pieces of wear or incident that make it look
+ used: a chipped corner, a leaning post, moss at the base, a rope, a hanging tool.
+- DO make `opts.variant` (0..n) change the SILHOUETTE, not just the scale: at least 3 visibly
+ different versions (a different crown shape, a different roof pitch, a broken vs whole rail).
+ Zones rely on this for variety, so a plain `variant` that only scales is a wasted asset.
+- DO give any repeated natural asset per-instance hue room: expose `opts.hue`/`opts.tint` (or
+ accept `opts.seed` and vary the colour from it) so 20 copies are not one colour.
+- DON'T model a flat plane with a colour where the thing has real thickness (a fence is stalks and
+ rails, not a textured quad) — closeups are judged.
- DON'T leave floating pieces: every sub-shape overlaps a neighbour by ≥ 2 mm.
- DON'T write anything but the asset file.
{% if current_code %}
diff --git a/harness/codeverse/prompts/tracks/scene_compose.j2 b/harness/codeverse/prompts/tracks/scene_compose.j2
index 4682aa69..aad76a5a 100644
--- a/harness/codeverse/prompts/tracks/scene_compose.j2
+++ b/harness/codeverse/prompts/tracks/scene_compose.j2
@@ -2,23 +2,28 @@
The environment (`src/env.js`), zones (`src/zones/*.js`) and assets (`src/assets/*.js`,
`public/assets/*.glb`) exist. Write the entry module that wires them together.
+(The harness normally generates this file itself; you are writing the fallback, so match the
+generated shape exactly.)
## Contract
{{ frame_doc }}
{{ contract }}
-`src/scene.js` must `export function createScene({ THREE, renderer, loaders }) → { scene, cameras, update }`:
-- `scene`: a `THREE.Scene`; call `buildEnv(THREE, scene)` from `./env.js`, then add every zone group
- (`build<Zone>(ctx)` from `./zones/<zone>.js` with `ctx = { THREE, env, heightAt, MATS, rand }`),
- each zone group named after the zone.
-- `cameras`: an array of `THREE.PerspectiveCamera` named after the planned cameras, positioned at the
- planned `position` and `lookAt` numbers, `fov` as planned, aspect 16:9, near 0.1, far ≥ 2 × bounds.
- `cameras[0]` is the establishing shot.
-- `update(t, dt)`: calls `tickEnv(t, dt)` and every `userData.tick(t, dt)` found on zone/asset groups
- (traverse once at creation and cache the list; never traverse per frame).
+`src/scene.js` must `export async function createScene({ THREE, renderer, loaders }) → { scene, cameras, update }`:
+- `scene`: a `THREE.Scene`; build `ctx = { THREE, scene, renderer, loaders, heightAt, assets: {} }`,
+ call `const env = (await buildEnv(ctx)) || {}` from `./env.js` (ONE argument: ctx), set
+ `ctx.env = env`, then add every zone group — `build(ctx)` imported from `./zones/<snake>.js`
+ (the export is named `build`, one argument) — naming each group after its zone.
+- `cameras`: an array of PLAIN OBJECTS `{ name, position: [x,y,z], lookAt: [x,y,z], fov }` (the
+ harness builds the PerspectiveCameras). Use the planned numbers literally. `cameras[0]` is the
+ establishing shot: it looks at the SUBJECT point, not at the bounds centre, and its height is
+ above anything standing between it and the subject.
+- `update(t, dt)`: calls `env.update(t, dt)` and every zone group's `userData.update(t, dt)`
+ (collect the list once at creation; never traverse per frame). `tickEnv` and `userData.tick`
+ are not part of the contract — do not call them.
- Wrap each zone build in try/catch: a failing zone logs `console.error('[zone <name>] ' + err)` and is skipped.
- Use a seeded mulberry32 `rand` (seed 1) so frames are reproducible.
-- GLB assets load via `loaders.gltf.loadAsync('public/assets/<snake>.glb')` — if you load any, keep the
- scene buildable before they resolve (add to the group on resolve).
+- GLB assets load via `loaders.gltf.loadAsync('/assets/<snake>.glb')` into `ctx.assets` before the
+ zones build.
## Plan
Bounds: {{ bounds }}
diff --git a/harness/codeverse/prompts/tracks/scene_env.j2 b/harness/codeverse/prompts/tracks/scene_env.j2
index 3082e582..94ac152b 100644
--- a/harness/codeverse/prompts/tracks/scene_env.j2
+++ b/harness/codeverse/prompts/tracks/scene_env.j2
@@ -11,28 +11,51 @@ Bounds: {{ bounds }}
{{ frame_doc }}
{{ contract }}
-`src/env.js` must export:
-- `export function buildEnv(THREE, scene) → env` where `env = { sun, ambient, sky, ground, water, fog, heightAt }`
- (fields may be null when absent). It adds sky (a large inverted sphere or a gradient ShaderMaterial
- dome), the key light (`THREE.DirectionalLight` placed along the planned azimuth/elevation at ≥ 0.6 ×
- the bounds' extent, `castShadow` with a shadow camera covering the bounds), an ambient/hemisphere
- light, scene fog (`THREE.Fog` or `FogExp2` with the planned colour/density), the ground (plane or
- subdivided terrain covering the bounds), and water if planned.
-- `export function heightAt(x, z) → y` (terrain height; 0 for flat ground). Zones call it to place
- assets on the ground — it must be deterministic and cheap.
-- `export const MATS = { ... }` a small registry of shared `MeshStandardMaterial`s (stone, wood, leaf,
- water, metal …) with hex colours so zones look coherent.
-- `export function tickEnv(t, dt) {}` for animated sky/water/fog (may be empty).
-
-## DO
-- Use the planned numbers literally: sun azimuth/elevation → `sun.position.set(cos(el)*sin(az), sin(el), cos(el)*cos(az)) * R`.
-- Colour-manage: `renderer.outputColorSpace` is set by the harness; author colours as sRGB hex.
-- Make it read at the planned time of day in ONE frame: exposure via light intensities (sun 1.5-3.0
- at noon, 0.3-0.8 at dusk with warm colour; ambient 0.2-0.6).
-- Keep the whole module ≤ 250 lines; no textures, no DOM, no fetch.
+### The harness assembles `src/scene.js` and calls YOUR module like this — nothing else runs
+```js
+const ctx = { THREE, scene, renderer, loaders, heightAt, assets };
+const env = (await buildEnv(ctx)) || {}; // ONE argument, and it is ctx (not THREE, not scene)
+function update(t, dt) { if (env.update) env.update(t, dt); /* then every zone */ }
+```
+So `src/env.js` must export exactly:
+- `export function buildEnv(ctx)` — reads `ctx.scene` / `ctx.THREE`, adds sky, lights, ground,
+ backdrop and water to `ctx.scene`, and **returns an object carrying `update(t, dt)`**:
+ `{ sun, hemi, sky, ground, water, heightAt, update(t, dt) {} }`. A separate `tickEnv` export is
+ NEVER called — animated sky/water/fog uniforms must be driven from the returned `update`.
+- `export function heightAt(x, z)` — terrain height (0 for flat ground), deterministic and cheap;
+ every zone places things with it. The PATH is part of this function (flatten it there) so props
+ on the path sit on the path.
+- `export const BOUNDS = { min: [x, y, z], max: [x, y, z] }` from the plan bounds.
+- `export const SUN_AZIMUTH_DEG = <number>` — read by the harness (regex) to put the overview
+ cameras on the sun side. Omit it and the overview rig shoots into the sun.
+- `export const MATS = { ... }` — shared `MeshStandardMaterial`s (stone, wood, leaf, water, metal)
+ with hex colours so zones look coherent.
+
+## What this module is graded on
+Read these cookbook chapters and copy their recipes (`read_cookbook(section="...")`):
+`"Ground that reads real"`, `"Horizon: the world must not end"`,
+`"Atmosphere: time-of-day triads with numbers"`.
+
+1. **Ground must not be one flat colour.** One displaced plane, ~1 segment per metre, vertex
+ colours blending 3-4 palette colours by height, slope and noise, plus the path carved by
+ `distToPath` in both height and colour. A single-colour `MeshStandardMaterial` plane is a
+ scored defect (`flat_ground`).
+2. **No world edge.** Ground size >= 2.4 x fog far; `scene.fog` colour == the sky's HORIZON
+ colour == `scene.background`; a silhouette ring (24-40 instanced hills / rooftops / mesas) at
+ radius ~ 0.6 x fog far, height 0.06-0.12 x that radius, tinted 70 % toward the fog colour.
+ Scale fog to THIS scene, not to a 100 m default.
+3. **Coloured atmosphere, not monochrome.** Warm key + cool fill (or the reverse) with >= 60
+ degrees of hue between them; shade must carry sky colour, never black. Add 3-4 haze bands
+ (`depthWrite:false`, opacity 0.04-0.10, fog colour) for aerial perspective, and light shafts
+ if the brief mentions sun through something.
+4. **Shadows must not be jagged.** Shadow texel = `2 x shadowSpan / mapSize` <= 0.05 m: fit the
+ shadow camera to the BOUNDS (not the whole ground), then pick mapSize 2048 (span <= 30 m) /
+ 3072 (<= 60 m) / 4096 (larger). `bias = -0.0004`, `normalBias = 0.02`.
+5. Keep the whole module <= 300 lines; no textures, no DOM, no fetch, no Math.random.
## DON'T
- No assets/zones here (they come from other modules). No cameras. No `scene.background` image loads.
+- Do not re-declare the path polyline in a zone: export it (or `distToPath`) from here.
## Effects planned (only the ones targeting the environment)
{{ effects }}
@@ -40,6 +63,8 @@ Bounds: {{ bounds }}
## Tools
{{ tool_cards }}
+After editing run `build`, then `scene_views` and LOOK: is the horizon hazy, is the ground
+multi-coloured, is the shade coloured rather than black?
{% endif %}
## Output
diff --git a/harness/codeverse/prompts/tracks/scene_refine.j2 b/harness/codeverse/prompts/tracks/scene_refine.j2
index db40f02d..1efdb190 100644
--- a/harness/codeverse/prompts/tracks/scene_refine.j2
+++ b/harness/codeverse/prompts/tracks/scene_refine.j2
@@ -38,12 +38,29 @@ Animation: {{ animation }}
## Reminders
{{ frame_doc }}
-- A lighting/mood change lives in `src/env.js` (sun colour/intensity/azimuth, fog density, sky hex).
-- A composition/camera change lives in `src/scene.js` (camera position/look_at numbers only).
-- A zone change lives in its `src/zones/<zone>.js`; an asset change in `src/assets/<asset>.js`.
+- A lighting/mood/ground/horizon change lives in `src/env.js` (sun colour/intensity/azimuth, fog
+ colour + near/far, sky hex, ground vertex colours, backdrop ring).
+- A composition/camera change lives in `src/scene.js` (camera position/lookAt/fov numbers only).
+- A zone change lives in its `src/zones/<zone>.js` (`export function build(ctx)`, animation on
+ `group.userData.update`); an asset change in `src/assets/<asset>.js`.
- Console/shader errors: fix the named module; never wrap in try/catch to hide them.
- Everything rests on `heightAt(x, z)`; nothing floats or sinks > 2 cm; keep fps ≥ 30 (InstancedMesh for repeats).
- No DOM, no textures, no fetch, no Math.random, no CDN imports.
+
+## The recurring defects on this track and the cookbook chapter that fixes each
+Do not re-explain the problem back — apply the recipe (`read_cookbook(section="...")`) and change
+the numbers. If the judge repeated an issue from the previous round, the earlier fix was too
+timid: double the amplitude / the count / the contrast this time.
+
+| what the judge wrote | fix it with |
+|---|---|
+| flat / one-colour ground, no paths, hard raised-bed edges | `"Ground that reads real"` — vertex-colour blend, carve the path into `heightAt`, dress the seams |
+| a hard world edge against the sky, missing horizon | `"Horizon: the world must not end"` — ground ≥ 2.4 × fog far, fog = sky horizon colour, silhouette ring at 0.6 × fog far |
+| identical cones / stacked blocks / primitive repetition | `"Vegetation that reads real"`, `"Rocks, cliffs and boulders that read organic"` — 3+ silhouettes, clustered, scale/hue jitter, no axis-aligned stacks |
+| sparse, token, "a diorama on a plane", empty midground | `"Set dressing"` + `"Scene layering"` — hit the per-zone prop counts, add a foreground element 2-4 m from each camera |
+| flat / dark / monochrome light, black shade, jagged shadows | `"Atmosphere: time-of-day triads with numbers"` — warm key vs cool fill ≥ 60° apart, shadow texel ≤ 0.05 m |
+| frames at t=0 and t=1.5 identical, "nothing moves" | `"Motion you can SEE between t = 0 and t = 1.5 s"` — the hook is `userData.update` (never `tick`), amplitudes from the table |
+| camera inside geometry / shows only sky or a wall | move the camera in `src/scene.js` and mask scatter within 6 m of it (`cameraMask`) |
{% if current_files %}
## Current file contents (edit and return each COMPLETE)
diff --git a/harness/codeverse/prompts/tracks/scene_zone.j2 b/harness/codeverse/prompts/tracks/scene_zone.j2
index 12033732..3747d34e 100644
--- a/harness/codeverse/prompts/tracks/scene_zone.j2
+++ b/harness/codeverse/prompts/tracks/scene_zone.j2
@@ -3,7 +3,7 @@
Scene: {{ spec_prompt }} · Setting: {{ setting }} · Mood: {{ mood }}
## This zone
-- Description: {{ zone_description }}
+- Description (density counts and depth role are binding): {{ zone_description }}
- Bbox: {{ zone_bbox }} — place EVERYTHING inside it (x/z), on the ground via `heightAt`.
- Contents (asset names to place): {{ zone_contents | join(', ') if zone_contents else '(none — build local detail from primitives)' }}
@@ -11,33 +11,74 @@ Neighbouring zones (do not build into them):
{% for n in neighbours %}- {{ n }}
{% endfor %}
-## Assets available (import exactly as shown; sizes are measured, meters w×h×d)
+Authored cameras that will photograph this scene (keep their first metres clear, and give the
+ones that look at this zone a foreground element):
+{{ cameras }}
+
+## Assets available (sizes are measured, meters w×h×d)
{{ asset_api }}
+Those paths are written relative to `src/`; **from `src/zones/` prefix them with `../`**
+(`import { buildStoneLantern } from '../assets/stone_lantern.js';`). Shared materials and the
+terrain come from the environment: `import { MATS, heightAt } from '../env.js';` (or use
+`ctx.heightAt`). A GLB asset is already loaded for you at `ctx.assets['<snake_name>']` — add
+`.clone()` of it, never `loaders.gltf` again. There is no `ctx.rand` and no `ctx.MATS`.
+
## Contract
{{ frame_doc }}
{{ contract }}
-`{{ zone_file }}` must `export function build{{ zone_name }}(ctx) → THREE.Group` where
-`ctx = { THREE, env, heightAt, MATS, rand }` (`rand()` is a seeded PRNG in [0,1)). Name the returned
-group `"{{ zone_name }}"`. Add instances of the listed assets at sensible real-world spacings
-(paths 1.2-2 m wide, trees ≥ 3 m apart, benches facing the view), rotate them for variety, and add
-zone-local detail from primitives (kerbs, gravel patches, planters, ropes, steps). Everything rests
-on `heightAt(x, z)` (lowest point touching the ground, never sunk > 2 cm, never floating).
-Optional `group.userData.tick = (t, dt) => {...}` to animate local things (lantern flicker, sway).
-
-## DO
-- Use the asset sizes above to avoid overlaps: keep ≥ 0.3 m between footprints unless stacking is intended.
-- Prefer `InstancedMesh` or reuse of one built asset group (`.clone()`) for ≥ 5 copies.
-- Keep the zone ≤ 250 lines and ≤ 400k triangles.
+
+### The harness assembles `src/scene.js` and calls YOUR module like this — nothing else runs
+```js
+const ctx = { THREE, scene, renderer, loaders, heightAt, env, assets };
+const g = await build(ctx); // the export MUST be named `build`, one argument
+scene.add(g); // g must be a THREE.Group / Object3D
+if (g.userData.update) g.userData.update(t, dt); // the ONLY animation hook that runs
+```
+So `{{ zone_file }}` exports `export function build(ctx) → THREE.Group` named `"{{ zone_name }}"`.
+`build{{ zone_name }}` and `userData.tick` are never called: if an asset carries its own
+`userData.update`, cache it at build time and call it from the zone's `userData.update`.
+`ctx` also gives you `ctx.env` (whatever `buildEnv` returned) and `ctx.heightAt`.
+
+## What this zone is graded on
+Copy the recipes from the cookbook (`read_cookbook(section="...")`):
+`"Vegetation that reads real"`, `"Rocks, cliffs and boulders that read organic"`,
+`"Set dressing: how many props a place needs"`, `"Scene layering: foreground, midground, background"`,
+`"Motion you can SEE between t = 0 and t = 1.5 s"`.
+
+1. **Hit the density counts in the description.** A zone with 5 objects in it reads as a token
+ gesture; the counts are the difference between 0.5 and 0.8. Props go **against** things
+ (path edges, wall bases, under benches, in corners), never in a grid or a perfect ring, with
+ >= 20 % positional jitter and full yaw jitter.
+2. **Variation, not clones.** Any repeated natural element needs >= 3 distinct silhouettes
+ (different geometry, not just scale), per-instance scale jitter +/-30 %, hue jitter +/-0.03
+ via `setColorAt`, full yaw jitter and a few degrees of lean. Clustered placement (cluster
+ seeds + members around them), never uniform scatter and never a ring of identical cones.
+3. **Blend into the ground.** Anything that meets the terrain sinks 3-5 cm into it and gets
+ 6-15 dressing pieces along the seam (tufts, pebbles, leaves). A raised bed gets a chamfered
+ kerb, not a naked box on grass. Add the zone's share of ground cover (300-800 instanced
+ tufts for a planted zone) unless the description says bare.
+4. **Serve the cameras.** Skip any SCATTER instance inside a ~4 m disc around an authored camera
+ (write a zero-scale matrix, keep the index; `cameraMask` in the cookbook) — a tree 1 m in front
+ of the establishing camera ruins the shot. Then, by hand (not scatter, so the mask does not
+ remove it), place ONE element 2.5-4 m from a camera that looks across this zone, off to one
+ side, as its foreground frame.
+5. **Motion that shows.** Amplitudes from the cookbook table (foliage +/-0.10-0.20 rad, particles
+ >= 0.6 m per 1.5 s). Sub-centimetre sway is invisible at 1024x576 and scores as
+ `nothing_moves`. Everything is a pure function of `t`.
+6. Use `InstancedMesh` for anything repeated > 5x; <= 400k triangles and <= 40 draw calls per zone;
+ the file stays <= 320 lines.
## DON'T
- No lights except small point lights for lanterns (≤ 4 per zone); no cameras; no sky/ground here.
-- No DOM, no textures, no fetch, no Math.random (use `ctx.rand`).
+- No DOM, no textures, no fetch, no Math.random (hash `rand(i)` with an explicit seed).
- Do not import assets marked NOT AVAILABLE; do not edit other files.
{% if tool_cards and not single_shot %}
## Tools
{{ tool_cards }}
+After editing run `build`, then `scene_views` and LOOK at the frames: count the silhouettes, look
+for a flat colour under your props, and compare t=0 with t=1.5.
{% endif %}
## Output
diff --git a/harness/codeverse/spatial/_render_common.py b/harness/codeverse/spatial/_render_common.py
new file mode 100644
index 00000000..dd3fb428
--- /dev/null
+++ b/harness/codeverse/spatial/_render_common.py
@@ -0,0 +1,60 @@
+"""Shared core of the three render flavours (object GLB, scene, GL frames).
+
+``render.py`` (objects, node + headless Chrome), ``render_scene.py`` (scene
+workspaces, same browser through the scene host) and the graphics build
+(``languages/_gl_common`` via ``gl_render``) all repeat the same four chores:
+resolve the output directory, turn ``ViewPreset``s into the driver's camera
+JSON, read a driver's JSON side-car back, and build the labelled contact sheet
+with the settings' grid. They live here once so the flavours differ only in
+what they actually drive.
+
+Nothing in here talks to node — see ``spatial.node.run_node`` (objects) and
+``spatial.render_scene.run_scene_script`` (scenes) for that.
+"""
+
+from __future__ import annotations
+
+import json
+from collections.abc import Sequence
+from pathlib import Path
+from typing import Any
+
+from codeverse.config import get_settings
+from codeverse.conventions import ViewPreset
+from codeverse.spatial.sheet import contact_sheet
+
+
+def out_directory(out_dir: Path | str, *, clean: Sequence[str] = ()) -> Path:
+ """Resolve + create ``out_dir``; ``clean`` names side-cars of a previous run
+ that must never be read as if they belonged to this one."""
+ d = Path(out_dir).resolve()
+ d.mkdir(parents=True, exist_ok=True)
+ for name in clean:
+ (d / name).unlink(missing_ok=True)
+ return d
+
+
+def view_specs(views: Sequence[ViewPreset]) -> list[dict[str, Any]]:
+ """``ViewPreset``s → the ``[{name, azimuth, elevation}]`` payload every
+ renderer driver takes (render_glb ``--views``, render_scene ``--orbit-views``)."""
+ return [{"name": v.name, "azimuth": float(v.azimuth_deg), "elevation": float(v.elevation_deg)} for v in views]
+
+
+def read_json(path: Path | str) -> dict[str, Any]:
+ """Parse a driver side-car (views.json / metrics.json); ``{}`` when absent."""
+ p = Path(path)
+ if not p.is_file():
+ return {}
+ try:
+ return json.loads(p.read_text())
+ except (OSError, ValueError):
+ return {}
+
+
+def build_sheet(images: Sequence[tuple[str, str | Path]], out: Path | str) -> str | None:
+ """Labelled contact sheet at the configured grid (``settings.render.sheet_cols``
+ / ``sheet_tile``); ``None`` when there is nothing to show."""
+ if not images:
+ return None
+ settings = get_settings()
+ return str(contact_sheet(list(images), Path(out), cols=settings.render.sheet_cols, tile=settings.render.sheet_tile))
diff --git a/harness/codeverse/spatial/connectivity.py b/harness/codeverse/spatial/connectivity.py
index 554a157a..224d23b8 100644
--- a/harness/codeverse/spatial/connectivity.py
+++ b/harness/codeverse/spatial/connectivity.py
@@ -2,7 +2,7 @@
Mechanism
---------
-1. Load one world-space mesh per top-level node (``measure.cached_parts``,
+1. Load one world-space mesh per top-level node (``measure.solid_parts``,
memoized on the file's stat so repeat gates on one GLB parse it once).
2. For every part pair whose AABBs come within ``gap_m`` of each other compute
the exact minimum surface distance (``fcl.distance`` on per-part BVHs that
@@ -40,7 +40,7 @@ from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
from codeverse.conventions import CONTACT_GAP_M, Frame
from codeverse.spatial.contract import frame_label, glb_vec_to_plan, language_frame
from codeverse.spatial.joints_collide import fcl_collision_object
-from codeverse.spatial.measure import GlbLoadError, cached_parts
+from codeverse.spatial.measure import GlbLoadError, fmt_vec, solid_parts
GATE = "connectivity"
#: parts smaller than this (max extent) are ignored for floating checks (INFO only)
@@ -186,7 +186,8 @@ def _components(names: list[str], edges: set[tuple[str, str]]) -> list[set[str]]
def _fmt_vec(v: tuple[float, float, float]) -> str:
- return "(" + ", ".join(f"{round(x, 4) + 0.0:+.4f}" for x in v) + ")" # + 0.0: no '-0.0000'
+ """Millimetre-precision translation vector (shared formatter, 4 decimals)."""
+ return fmt_vec(v, 4)
def _island_findings(name: str, mesh: trimesh.Trimesh) -> list[GateFinding]:
@@ -224,7 +225,7 @@ def check_connectivity(
up = "z" if language_frame(language) is Frame.Z_UP_NEG_Y_FRONT else "y"
findings: list[GateFinding] = []
try:
- parts = {k: v for k, v in cached_parts(glb).items() if v is not None and len(v.faces)}
+ parts = solid_parts(glb)
except GlbLoadError as e:
findings.append(GateFinding(gate=GATE, severity=Severity.ERROR, message=str(e), fix_hint="run `build` first"))
return GateReport(gate=GATE, passed=False, findings=findings, duration_ms=int((time.time() - t0) * 1000))
diff --git a/harness/codeverse/spatial/contract.py b/harness/codeverse/spatial/contract.py
index ed645fd1..1a56a79f 100644
--- a/harness/codeverse/spatial/contract.py
+++ b/harness/codeverse/spatial/contract.py
@@ -35,6 +35,7 @@ from codeverse.contracts.artifacts import (
)
from codeverse.contracts.plan import BBox, PartPlan, Plan, ScenePlan, StaticPlan
from codeverse.conventions import BBOX_TOLERANCE_M, LANGUAGE_FRAME, Frame, to_snake
+from codeverse.spatial.measure import fmt_extent_cm, fmt_vec
GATE = "contract"
#: relative tolerance on extents (fraction of the plan's extent)
@@ -118,12 +119,9 @@ def _fmt_delta(v: np.ndarray) -> str:
return ", ".join(f"{a}{d * 100:+.1f}cm" for a, d in zip(_AXES, v, strict=True))
-def _fmt_ext(v) -> str:
- return "×".join(f"{float(x) * 100:.1f}" for x in v)
-
-
-def _fmt_vec(v) -> str:
- return "(" + ", ".join(f"{round(float(x), 3) + 0.0:+.3f}" for x in v) + ")" # + 0.0: no '-0.000'
+#: shared formatters (``spatial.measure``): sizes in cm, translation vectors in m
+_fmt_ext = fmt_extent_cm
+_fmt_vec = fmt_vec
def _box_findings(target: str, d: _BoxDelta, plan: BBox, *, what: str, language: str,
diff --git a/harness/codeverse/spatial/gl_render.py b/harness/codeverse/spatial/gl_render.py
index dcca9c01..92f4cc05 100644
--- a/harness/codeverse/spatial/gl_render.py
+++ b/harness/codeverse/spatial/gl_render.py
@@ -188,54 +188,28 @@ class GlHost:
# --------------------------------------------------------------------------- derived artifacts
def write_contact_sheet(frames: Sequence[GlFrame], out: Path, *, cols: int = 3, tile_w: int = 480) -> Path:
- """Labelled grid of frames keeping their aspect ratio (``t=<s>`` under each tile)."""
- import math
+ """Labelled grid of frames keeping their aspect ratio (``t=<s>`` under each tile).
- from PIL import Image, ImageDraw
-
- from codeverse.spatial.sheet import BG, LABEL_BG, LABEL_FG, LABEL_H, PAD, load_font
+ Thin wrapper over :func:`codeverse.spatial.sheet.contact_sheet` (the one
+ sheet builder) with a 16:9-style cell derived from the first frame.
+ """
+ from codeverse.spatial.sheet import contact_sheet, tile_size
frames = list(frames)
if not frames:
raise ValueError("write_contact_sheet: no frames")
- first = Image.open(frames[0].path)
- tile_h = max(1, round(tile_w * first.height / first.width))
- cols = max(1, min(cols, len(frames)))
- rows = math.ceil(len(frames) / cols)
- cell_h = tile_h + LABEL_H
- sheet = Image.new("RGB", (cols * (tile_w + PAD) + PAD, rows * (cell_h + PAD) + PAD), BG)
- draw = ImageDraw.Draw(sheet)
- font = load_font(15)
- for i, f in enumerate(frames):
- x = PAD + (i % cols) * (tile_w + PAD)
- y = PAD + (i // cols) * (cell_h + PAD)
- im = Image.open(f.path).convert("RGB").resize((tile_w, tile_h), Image.LANCZOS)
- sheet.paste(im, (x, y))
- draw.rectangle([x, y + tile_h, x + tile_w, y + tile_h + LABEL_H], fill=LABEL_BG)
- label = f"t={f.time:g}s"
- tw = draw.textlength(label, font=font)
- draw.text((x + (tile_w - tw) / 2, y + tile_h + 6), label, fill=LABEL_FG, font=font)
- out = Path(out)
- out.parent.mkdir(parents=True, exist_ok=True)
- sheet.save(out)
- return out
+ return contact_sheet([(f"t={f.time:g}s", f.path) for f in frames], Path(out), cols=cols,
+ tile=tile_size(tile_w, sample=frames[0].path))
def write_gif(frames: Sequence[GlFrame], out: Path, *, width: int = 480, fps: int = 6) -> Path | None:
"""Animated GIF preview from ALL frames (judge + extra), resized to ``width``."""
- from PIL import Image
+ from codeverse.spatial.sheet import write_gif as _write_gif
ordered = sorted(frames, key=lambda f: f.time)
if len(ordered) < 2:
return None
- ims = []
- for f in ordered:
- im = Image.open(f.path).convert("RGB")
- h = max(1, round(im.height * width / im.width))
- ims.append(im.resize((width, h), Image.BILINEAR).convert("P", palette=Image.ADAPTIVE, colors=128))
- out.parent.mkdir(parents=True, exist_ok=True)
- ims[0].save(out, save_all=True, append_images=ims[1:], duration=int(1000 / fps), loop=0, optimize=False)
- return out
+ return _write_gif([f.path for f in ordered], out, fps=fps, width=width)
def gif_times(duration_s: float, n: int = 12) -> list[float]:
diff --git a/harness/codeverse/spatial/joints_export.py b/harness/codeverse/spatial/joints_export.py
index 0f100129..42c81319 100644
--- a/harness/codeverse/spatial/joints_export.py
+++ b/harness/codeverse/spatial/joints_export.py
@@ -24,6 +24,7 @@ import trimesh
from codeverse.contracts.artifacts import RenderSet, RenderView
from codeverse.conventions import OBJECT_VIEWS_QUICK, ViewPreset
from codeverse.proc import run_subprocess
+from codeverse.spatial._render_common import build_sheet, out_directory, view_specs
from codeverse.spatial.joints_model import Joint, Robot, UrdfError, fk
from codeverse.spatial.joints_poses import limit_poses
from codeverse.spatial.render import render_glb
@@ -114,11 +115,10 @@ def blender_render_glb(glb: Path, out_dir: Path, *, views: Sequence[ViewPreset]
if not blender:
raise RuntimeError("no Blender binary found for the fallback renderer")
views = tuple(views or OBJECT_VIEWS_QUICK)
- out_dir = Path(out_dir)
- out_dir.mkdir(parents=True, exist_ok=True)
+ out_dir = out_directory(out_dir)
script = Path(__file__).resolve().parent.parent / "languages" / "urdf" / "wrappers" / "render_glb_bpy.py"
spec = {"glb": str(glb), "out_dir": str(out_dir), "width": width, "height": height,
- "views": [{"name": v.name, "az": v.azimuth_deg, "el": v.elevation_deg} for v in views]}
+ "views": [{"name": v["name"], "az": v["azimuth"], "el": v["elevation"]} for v in view_specs(views)]}
spec_path = out_dir / "_render_spec.json"
spec_path.write_text(json.dumps(spec))
t0 = time.time()
@@ -135,7 +135,7 @@ def blender_render_glb(glb: Path, out_dir: Path, *, views: Sequence[ViewPreset]
raise RuntimeError(f"blender fallback render produced no {p.name}; stdout tail: {proc.stdout[-800:]}")
rs.views.append(RenderView(name=v.name, path=str(p), width=width, height=height))
if sheet:
- rs.contact_sheet = str(contact_sheet([(v.name, Path(v.path)) for v in rs.views], out_dir / "sheet.png"))
+ rs.contact_sheet = build_sheet([(v.name, v.path) for v in rs.views], out_dir / "sheet.png")
return rs
@@ -153,8 +153,7 @@ def render_poses(
"""Export one GLB per pose, render ``views`` for each (default: 3 quick views)
and write ``out_dir/articulation_sheet.png`` (rest / each joint at lower & upper
by default — the image the judge sees). Returns ``[(pose_name, RenderSet)]``."""
- out_dir = Path(out_dir)
- out_dir.mkdir(parents=True, exist_ok=True)
+ out_dir = out_directory(out_dir)
poses = poses if poses is not None else limit_poses(robot)
views = tuple(views or OBJECT_VIEWS_QUICK[:3])
render = renderer or render_glb
diff --git a/harness/codeverse/spatial/measure.py b/harness/codeverse/spatial/measure.py
index f3e9f51c..48ef503a 100644
--- a/harness/codeverse/spatial/measure.py
+++ b/harness/codeverse/spatial/measure.py
@@ -9,7 +9,8 @@ rows, islands, ground gap, footprint offset, materials). Degenerate input
world-space ``trimesh.Trimesh`` per top-level node (all child meshes merged).
``cached_parts`` is the memoized front door for gates that re-read the same
GLB (keyed on path + size + mtime_ns; ``load_scene`` itself is never cached —
-texturing mutates scenes).
+texturing mutates scenes), and ``solid_parts`` is that front door minus the
+empty parts — what connectivity / sections want.
"""
from __future__ import annotations
@@ -30,8 +31,11 @@ __all__ = [
"load_scene",
"part_meshes",
"cached_parts",
+ "solid_parts",
"measure_glb",
"measure_summary_table",
+ "fmt_extent_cm",
+ "fmt_vec",
"instance_groups",
"merged_mesh",
]
@@ -208,6 +212,13 @@ def cached_parts(glb: Path | str) -> OrderedDict[str, trimesh.Trimesh | None]:
return OrderedDict(entry.parts)
+def solid_parts(glb: Path | str) -> OrderedDict[str, trimesh.Trimesh]:
+ """:func:`cached_parts` without the empty ones — the loader every geometry
+ gate (connectivity, sections) starts from: one world-space mesh per part,
+ only parts that actually have faces. Meshes are SHARED (read-only)."""
+ return OrderedDict((k, v) for k, v in cached_parts(glb).items() if v is not None and len(v.faces))
+
+
def merged_mesh(parts: dict[str, trimesh.Trimesh | None]) -> trimesh.Trimesh | None:
"""All part meshes concatenated (None if nothing has faces)."""
meshes = [m for m in parts.values() if m is not None]
@@ -334,8 +345,19 @@ def instance_groups(names: list[str]) -> OrderedDict[str, list[str]]:
return out
-def _fmt_ext(ext: tuple[float, float, float] | np.ndarray) -> str:
- return "×".join(f"{v * 100:.1f}" for v in ext)
+def fmt_extent_cm(ext: Any) -> str:
+ """``34.0×47.0×34.0`` — a size in centimetres. THE extent formatter (measure
+ table, contract gate) so every prompt/finding states sizes the same way."""
+ return "×".join(f"{float(v) * 100:.1f}" for v in ext)
+
+
+def fmt_vec(v: Any, digits: int = 3) -> str:
+ """``(+0.010, -0.000, +0.250)`` — a signed metre vector. THE vector formatter
+ for gate hints (``+ 0.0`` keeps a rounded zero from printing as ``-0.000``)."""
+ return "(" + ", ".join(f"{round(float(x), digits) + 0.0:+.{digits}f}" for x in v) + ")"
+
+
+_fmt_ext = fmt_extent_cm # legacy private alias
def measure_summary_table(m: Measurement, max_rows: int = 30) -> str:
diff --git a/harness/codeverse/spatial/observe.py b/harness/codeverse/spatial/observe.py
index 8938d32d..88680106 100644
--- a/harness/codeverse/spatial/observe.py
+++ b/harness/codeverse/spatial/observe.py
@@ -5,7 +5,8 @@
* ``tail_lines`` – last ``n`` lines of a log.
* ``image_budget`` – cap image lists (contact sheet kept first).
* ``rel_path`` – workspace-relative display path (never leak host paths in text).
-* ``gate_observation`` / ``render_observation`` – standard Observation builders.
+* ``text_observation`` / ``gate_observation`` / ``render_observation`` – the
+ standard Observation builders (truncation + image budget applied once).
"""
from __future__ import annotations
@@ -98,6 +99,27 @@ def sanitize_text(text: str, root: Path) -> str:
# --------------------------------------------------------------------------- builders
+def text_observation(
+ lines: Sequence[str] | str,
+ *,
+ ok: bool = True,
+ numbers: dict[str, Any] | None = None,
+ images: Sequence[str | Path] = (),
+ limit: int = MAX_TEXT,
+) -> Observation:
+ """Observation from text lines: joined, truncated to ``limit``, images capped.
+
+ The plain-text counterpart of :func:`gate_observation` / :func:`render_observation`
+ — every tool that assembles its own report (build, gl_probe, gl_frames,
+ texture_pass, …) goes through here so truncation and the image budget are
+ applied exactly once, in one place.
+ """
+ body = lines if isinstance(lines, str) else "\n".join(str(x) for x in lines)
+ return Observation(ok=ok, text=truncate(body, limit), numbers=dict(numbers or {}),
+ images=image_budget([str(i) for i in images]))
+
+
+
_SEV_ORDER = {Severity.ERROR: 0, Severity.WARN: 1, Severity.INFO: 2}
_SEV_TAG = {Severity.ERROR: "ERROR", Severity.WARN: "WARN", Severity.INFO: "info"}
diff --git a/harness/codeverse/spatial/registry.py b/harness/codeverse/spatial/registry.py
index b2e5cff2..d0d7d338 100644
--- a/harness/codeverse/spatial/registry.py
+++ b/harness/codeverse/spatial/registry.py
@@ -9,6 +9,9 @@ Usage::
def measure(ctx: ToolContext, args: MeasureArgs) -> Observation: ...
``ToolContext`` carries the workspace and settings; tools never touch globals.
+``ToolDef.call`` is the one error boundary: ``ToolUsageError`` becomes a usage
+Observation, ``ToolUnavailable`` (a missing sibling package) an "unavailable"
+one, anything else a failed Observation — a tool body never needs try/except.
Observations: ``text`` (what the agent reads), ``numbers`` (machine-readable),
``images`` (paths, small PNGs the agent may view), ``ok``.
"""
@@ -38,6 +41,15 @@ class Observation(BaseModel):
return cls(ok=False, text=text, numbers=numbers)
+class ToolUnavailable(RuntimeError):
+ """A sibling package a tool depends on is not importable / not built yet.
+
+ Raised by ``tool_common.lazy`` (and anything built on it) and turned into a
+ ``tool <name> unavailable: ...`` Observation by :meth:`ToolDef.call` — tools
+ never have to catch it themselves.
+ """
+
+
class ToolUsageError(ValueError):
"""Raised by tools on caller mistakes; ``fix_example`` is shown to the agent."""
@@ -102,6 +114,8 @@ 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 ToolUnavailable as e: # a sibling package is missing → degrade, never crash
+ obs = Observation.error(f"tool {self.name} unavailable: {type(e).__name__}: {e}")
except Exception as e: # never crash the agent loop
obs = Observation.error(f"{self.name} failed: {type(e).__name__}: {e}")
obs.duration_ms = int((time.time() - t0) * 1000)
diff --git a/harness/codeverse/spatial/render.py b/harness/codeverse/spatial/render.py
index 31d7f794..4642ec9d 100644
--- a/harness/codeverse/spatial/render.py
+++ b/harness/codeverse/spatial/render.py
@@ -23,9 +23,9 @@ from codeverse.config import get_settings
from codeverse.contracts.artifacts import RenderSet, RenderView
from codeverse.contracts.plan import CameraPlan
from codeverse.conventions import OBJECT_VIEWS, ViewPreset
+from codeverse.spatial._render_common import build_sheet, out_directory, view_specs
from codeverse.spatial.node import NodeError, run_node, runtime_js_dir
from codeverse.spatial.render_scene import render_scene as _render_scene_impl
-from codeverse.spatial.sheet import contact_sheet
from codeverse.workspace import Workspace
MODES = ("shaded", "wire", "normals", "silhouette", "clay")
@@ -45,10 +45,6 @@ def _sha256_file(path: Path) -> str:
return h.hexdigest()
-def _views_payload(views: Sequence[ViewPreset]) -> list[dict[str, Any]]:
- return [{"name": v.name, "azimuth": float(v.azimuth_deg), "elevation": float(v.elevation_deg)} for v in views]
-
-
def _cache_key(glb: Path, params: dict[str, Any]) -> str:
blob = json.dumps({"v": CACHE_VERSION, "glb": _sha256_file(glb), **params}, sort_keys=True)
return hashlib.sha256(blob.encode()).hexdigest()[:24]
@@ -104,7 +100,7 @@ def render_glb(
gpu = gpu or settings.render.gpu
timeout_s = timeout_s or settings.limits.render_timeout_s
params: dict[str, Any] = {
- "views": _views_payload(view_list),
+ "views": view_specs(view_list),
"mode": mode,
"width": int(width),
"height": int(height),
@@ -117,7 +113,7 @@ def render_glb(
}
t0 = time.time()
cache_dir = settings.cache_dir / "renders" / _cache_key(glb, params)
- out_dir.mkdir(parents=True, exist_ok=True)
+ out_directory(out_dir)
record: dict[str, Any] | None = None
if use_cache and (cache_dir / "views.json").is_file():
record = _restore_from_cache(cache_dir, out_dir)
@@ -140,16 +136,7 @@ def render_glb(
)
for v in record["views"]
]
- sheet_path = None
- if sheet:
- sheet_path = str(
- contact_sheet(
- [(v.name, v.path) for v in rviews],
- out_dir / "sheet.png",
- cols=settings.render.sheet_cols,
- tile=settings.render.sheet_tile,
- )
- )
+ sheet_path = build_sheet([(v.name, v.path) for v in rviews], out_dir / "sheet.png") if sheet else None
return RenderSet(
views=rviews,
contact_sheet=sheet_path,
diff --git a/harness/codeverse/spatial/render_scene.py b/harness/codeverse/spatial/render_scene.py
index caeb87f3..bf0b844b 100644
--- a/harness/codeverse/spatial/render_scene.py
+++ b/harness/codeverse/spatial/render_scene.py
@@ -25,8 +25,9 @@ from codeverse.config import get_settings
from codeverse.contracts.artifacts import RenderSet, RenderView
from codeverse.contracts.plan import BBox, CameraPlan
from codeverse.conventions import SCENE_VIEWS, ViewPreset
-from codeverse.spatial.node import NodeError, run_node
-from codeverse.spatial.sheet import contact_sheet
+from codeverse.spatial._render_common import build_sheet, out_directory, view_specs
+from codeverse.spatial._render_common import read_json as _read_json
+from codeverse.spatial.node import NodeError, run_node, runtime_js_dir
from codeverse.workspace import Workspace
#: views the judge sees (contact sheet + individual images are built from these)
@@ -48,10 +49,6 @@ class NodeResult:
duration_ms: int
-def runtime_js_dir() -> Path:
- return get_settings().runtime_js_dir()
-
-
def run_scene_script(script: str, args: Sequence[str], *, timeout_s: float, cwd: Path | None = None) -> NodeResult:
"""Run ``runtime_js/<script>`` via ``codeverse.spatial.node.run_node`` (which
delegates to ``codeverse.proc.run_subprocess``: own process group, group kill
@@ -88,7 +85,7 @@ def _camera_json(cams: Sequence[CameraPlan]) -> str:
def _views_json(views: Sequence[ViewPreset]) -> str:
- return json.dumps([{"name": v.name, "azimuth": v.azimuth_deg, "elevation": v.elevation_deg} for v in views])
+ return json.dumps(view_specs(views))
def _bounds_json(bounds: BBox) -> str:
@@ -107,13 +104,6 @@ def plan_bounds(ws: Workspace) -> BBox | None:
return None
-def _contact_sheet(images: list[tuple[str, Path]], out: Path, cols: int, tile: int) -> Path | None:
- """``sheet.contact_sheet`` with an empty-list guard (it raises on no images)."""
- if not images:
- return None
- return Path(contact_sheet(images, out, cols=cols, tile=tile))
-
-
def render_scene(
ws: Workspace,
out_dir: Path,
@@ -141,10 +131,8 @@ def render_scene(
say why (the build gate normally catches that earlier); a driver failure
raises ``SceneRenderError``.
"""
- out_dir = Path(out_dir)
- out_dir.mkdir(parents=True, exist_ok=True)
- for stale in ("metrics.json", "views.json"):
- (out_dir / stale).unlink(missing_ok=True) # never read a previous run's instruments
+ # never read a previous run's instruments
+ out_dir = out_directory(out_dir, clean=("metrics.json", "views.json"))
settings = get_settings()
args: list[str] = [
"--ws", str(ws.root), "--out", str(out_dir),
@@ -201,8 +189,7 @@ def render_scene(
_mark_judge_views(out_dir / "views.json", rs.views)
if sheet and views:
labelled = [(f"{v.name} t={v.time_s:g}", Path(v.path)) for v in rs.views if v.judge]
- sheet_path = _contact_sheet(labelled, out_dir / "sheet.png", settings.render.sheet_cols, settings.render.sheet_tile)
- rs.contact_sheet = str(sheet_path) if sheet_path else None
+ rs.contact_sheet = build_sheet(labelled, out_dir / "sheet.png")
return rs
@@ -245,12 +232,6 @@ def _mark_judge_views(views_json: Path, views: Sequence[RenderView]) -> None:
views_json.write_text(json.dumps(entries, indent=1))
-def _read_json(p: Path) -> dict[str, Any]:
- if not p.is_file():
- return {}
- return json.loads(p.read_text())
-
-
def read_metrics(out_dir: Path) -> dict[str, Any]:
"""Full instrument payload written by the driver (census, camera_checks, ...)."""
return _read_json(Path(out_dir) / "metrics.json")
diff --git a/harness/codeverse/spatial/sections.py b/harness/codeverse/spatial/sections.py
index 6466afa6..3ea7e441 100644
--- a/harness/codeverse/spatial/sections.py
+++ b/harness/codeverse/spatial/sections.py
@@ -20,7 +20,7 @@ import numpy as np
import trimesh
from PIL import Image, ImageDraw
-from codeverse.spatial.measure import GlbLoadError, cached_parts, merged_mesh
+from codeverse.spatial.measure import GlbLoadError, merged_mesh, solid_parts
from codeverse.spatial.registry import Observation
from codeverse.spatial.sheet import load_font
@@ -180,7 +180,7 @@ def _resolve_at(parts: dict[str, trimesh.Trimesh], axis: str, at: float, absolut
def _load_parts(glb: Path | str, parts: Sequence[str] | None) -> dict[str, trimesh.Trimesh]:
- all_parts = {k: v for k, v in cached_parts(glb).items() if v is not None and len(v.faces)}
+ all_parts = solid_parts(glb)
if parts:
sel = {k: v for k, v in all_parts.items() if k in set(parts)}
missing = [p for p in parts if p not in all_parts]
diff --git a/harness/codeverse/spatial/sheet.py b/harness/codeverse/spatial/sheet.py
index 95052ac1..aacdd42f 100644
--- a/harness/codeverse/spatial/sheet.py
+++ b/harness/codeverse/spatial/sheet.py
@@ -3,10 +3,11 @@
Used for judge inputs and agent observations: one image, every view labelled
under its tile, fixed tile size so the VLM sees consistent scale.
-This module is also the one home for shared PIL drawing bits: ``load_font``
-and the sheet geometry/palette constants (``LABEL_H``, ``PAD``, ``BG``,
-``LABEL_BG``, ``LABEL_FG``) are public and reused by ``spatial.gl_render``,
-``spatial.sections`` and ``judges.images``.
+This module is also the one home for shared PIL drawing bits: ``load_font``,
+:func:`write_gif` and the sheet geometry/palette constants (``LABEL_H``,
+``PAD``, ``BG``, ``LABEL_BG``, ``LABEL_FG``) are public and reused by
+``spatial.gl_render``, ``spatial.turntable``, ``spatial.sections`` and
+``judges.images``.
"""
from __future__ import annotations
@@ -43,62 +44,103 @@ def load_font(size: int = 15, bold: bool = False) -> ImageFont.ImageFont | Image
return ImageFont.load_default()
-def _fit(im: Image.Image, tile: int) -> Image.Image:
- """Letterbox ``im`` into a tile x tile square on the sheet background."""
+def _fit(im: Image.Image, tile_w: int, tile_h: int) -> Image.Image:
+ """Letterbox ``im`` into a tile_w x tile_h cell on the sheet background."""
im = im.convert("RGBA")
- scale = min(tile / im.width, tile / im.height)
+ scale = min(tile_w / im.width, tile_h / im.height)
w, h = max(1, round(im.width * scale)), max(1, round(im.height * scale))
im = im.resize((w, h), Image.LANCZOS)
- canvas = Image.new("RGBA", (tile, tile), BG + (255,))
- canvas.alpha_composite(im, ((tile - w) // 2, (tile - h) // 2))
+ canvas = Image.new("RGBA", (tile_w, tile_h), BG + (255,))
+ canvas.alpha_composite(im, ((tile_w - w) // 2, (tile_h - h) // 2))
return canvas.convert("RGB")
+def tile_size(tile: int | tuple[int, int], sample: str | Path | None = None) -> tuple[int, int]:
+ """Resolve the ``tile`` argument: a square side, an explicit (w, h), or a
+ width plus ``sample`` — an image whose aspect ratio the cell should keep
+ (how the graphics-track frame sheets stay 16:9)."""
+ if isinstance(tile, tuple):
+ return max(1, int(tile[0])), max(1, int(tile[1]))
+ tile_w = max(1, int(tile))
+ if sample is None:
+ return tile_w, tile_w
+ try:
+ with Image.open(sample) as im:
+ return tile_w, max(1, round(tile_w * im.height / im.width))
+ except (OSError, ValueError):
+ return tile_w, tile_w
+
+
def contact_sheet(
images: Sequence[tuple[str, str | Path]],
out: Path | str,
cols: int = 4,
- tile: int = 384,
+ tile: int | tuple[int, int] = 384,
label: bool = True,
) -> Path:
"""Write a grid of ``(label, png_path)`` tiles to ``out`` and return it.
- Missing/unreadable images become a grey tile with the label so the sheet
- never silently drops a view. Output is deterministic for identical inputs.
+ THE sheet builder: object views, scene views and graphics frame sheets all
+ come through here. ``tile`` is a square side or an explicit ``(w, h)`` cell
+ (see :func:`tile_size`). Missing/unreadable images become a grey tile with
+ the label so the sheet never silently drops a view. Output is deterministic
+ for identical inputs.
"""
if not images:
raise ValueError("contact_sheet: no images")
+ tile_w, tile_h = tile_size(tile)
cols = max(1, min(cols, len(images)))
rows = math.ceil(len(images) / cols)
- cell_h = tile + (LABEL_H if label else 0)
- sheet = Image.new("RGB", (cols * (tile + PAD) + PAD, rows * (cell_h + PAD) + PAD), BG)
+ cell_h = tile_h + (LABEL_H if label else 0)
+ sheet = Image.new("RGB", (cols * (tile_w + PAD) + PAD, rows * (cell_h + PAD) + PAD), BG)
draw = ImageDraw.Draw(sheet)
font = load_font()
for i, (text, path) in enumerate(images):
- x = PAD + (i % cols) * (tile + PAD)
+ x = PAD + (i % cols) * (tile_w + PAD)
y = PAD + (i // cols) * (cell_h + PAD)
p = Path(path)
try:
with Image.open(p) as im:
- tile_im = _fit(im, tile)
+ tile_im = _fit(im, tile_w, tile_h)
except (OSError, ValueError):
- tile_im = Image.new("RGB", (tile, tile), (200, 200, 200))
+ tile_im = Image.new("RGB", (tile_w, tile_h), (200, 200, 200))
ImageDraw.Draw(tile_im).text((8, 8), "missing image", fill=(90, 0, 0), font=font)
sheet.paste(tile_im, (x, y))
if label:
- draw.rectangle([x, y + tile, x + tile - 1, y + tile + LABEL_H - 1], fill=LABEL_BG)
+ draw.rectangle([x, y + tile_h, x + tile_w - 1, y + tile_h + LABEL_H - 1], fill=LABEL_BG)
txt = str(text)
tw = draw.textlength(txt, font=font)
- while tw > tile - 8 and len(txt) > 4:
+ while tw > tile_w - 8 and len(txt) > 4:
txt = txt[:-2] + "…"
tw = draw.textlength(txt, font=font)
- draw.text((x + (tile - tw) / 2, y + tile + 6), txt, fill=LABEL_FG, font=font)
+ draw.text((x + (tile_w - tw) / 2, y + tile_h + 6), txt, fill=LABEL_FG, font=font)
out = Path(out)
out.parent.mkdir(parents=True, exist_ok=True)
sheet.save(out, format="PNG", optimize=False)
return out
+def write_gif(frames: Sequence[str | Path], out: Path | str, *, fps: int = 12, width: int | None = None) -> Path:
+ """Animated GIF from ``frames`` (adaptive 128-colour palette, looping).
+
+ THE gif writer: turntables (full-size frames) and the graphics preview
+ (``width`` downscales with BILINEAR) both use it. Raises ``ValueError``
+ without frames.
+ """
+ if not frames:
+ raise ValueError("write_gif: no frames")
+ ims = []
+ for f in frames:
+ im = Image.open(f).convert("RGB")
+ if width and im.width != width:
+ im = im.resize((width, max(1, round(im.height * width / im.width))), Image.BILINEAR)
+ ims.append(im.convert("P", palette=Image.ADAPTIVE, colors=128))
+ out = Path(out)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ ims[0].save(out, save_all=True, append_images=ims[1:], duration=int(1000 / fps), loop=0, optimize=False)
+ return out
+
+
# --------------------------------------------------------------------------- montage helpers (judge inputs)
MONTAGE_MAX_TILES = 4
diff --git a/harness/codeverse/spatial/tool_common.py b/harness/codeverse/spatial/tool_common.py
index 1d99d713..762ed53f 100644
--- a/harness/codeverse/spatial/tool_common.py
+++ b/harness/codeverse/spatial/tool_common.py
@@ -17,20 +17,33 @@ from typing import Any
from pydantic import ValidationError
-from codeverse.contracts.artifacts import RenderSet
+from codeverse.contracts.artifacts import RenderSet, Severity
from codeverse.contracts.plan import ArticulatedPlan, GraphicsPlan, Plan, ScenePlan, StaticPlan
from codeverse.conventions import OBJECT_VIEWS, ViewPreset
-from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError
+from codeverse.spatial.registry import Observation, ToolContext, ToolUnavailable, ToolUsageError
+from codeverse.workspace import Workspace
+
+__all__ = [
+ "ToolUnavailable", "unavailable_obs", "lazy", "call_adaptive", "spec_dict", "language_of", "track_of",
+ "glb_path", "load_plan", "resolve_views", "check_mode", "tool_out_dir", "render_cache_dir",
+ "cached_render_glb", "gl_metrics_summary", "VIEW_BY_NAME", "RENDER_MODES",
+]
VIEW_BY_NAME: dict[str, ViewPreset] = {v.name: v for v in OBJECT_VIEWS}
RENDER_MODES = ("shaded", "wire", "normals", "silhouette", "depth", "clay")
-class ToolUnavailable(RuntimeError):
- """A sibling package this tool depends on is not importable / not built yet."""
+#: ``ToolUnavailable`` now lives in ``registry`` (``ToolDef.call`` catches it for
+#: every tool); re-exported here because that is where tools import it from.
def unavailable_obs(tool: str, e: BaseException) -> Observation:
+ """The Observation ``ToolDef.call`` builds for a :class:`ToolUnavailable`.
+
+ Tools no longer need it — raise/propagate ``ToolUnavailable`` instead; it
+ stays for callers that catch the exception themselves (e.g. an optional
+ reader whose absence must not fail the whole tool).
+ """
return Observation.error(f"tool {tool} unavailable: {type(e).__name__}: {e}")
@@ -140,11 +153,19 @@ def _file_stamp(p: Path) -> str:
return f"{st.st_size}:{st.st_mtime_ns}"
+def tool_out_dir(ctx: ToolContext, name: str) -> Path:
+ """``artifacts/tool_renders/r<NN>_<name>`` (created) — THE output location for
+ anything a tool renders/writes for the agent, so every tool artifact is
+ round-stamped and lands in one place."""
+ d = ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_{name}"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
def render_cache_dir(ctx: ToolContext, glb: Path, **key_parts: Any) -> Path:
"""Deterministic output dir under artifacts/tool_renders keyed by glb stamp + args."""
raw = json.dumps({"glb": _file_stamp(glb), **key_parts}, sort_keys=True, default=str)
- key = hashlib.sha1(raw.encode()).hexdigest()[:8]
- return ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_{key}"
+ return tool_out_dir(ctx, hashlib.sha1(raw.encode()).hexdigest()[:8])
def cached_render_glb(
@@ -170,10 +191,47 @@ def cached_render_glb(
except ValidationError:
pass
render_glb = lazy("codeverse.spatial.render", "render_glb")
- out_dir.mkdir(parents=True, exist_ok=True)
rs = call_adaptive(render_glb, glb, out_dir, views=list(views), mode=mode, width=size, height=size,
isolate=list(isolate) if isolate else None, explode=explode, sheet=sheet)
if not isinstance(rs, RenderSet):
raise ToolUnavailable(f"render_glb returned {type(rs).__name__}, expected RenderSet")
marker.write_text(rs.model_dump_json())
return rs
+
+
+# --------------------------------------------------------------------------- graphics metrics
+def gl_metrics_summary(ws: Workspace, *, hints: bool = True, root: Path | None = None) -> tuple[list[str], dict[str, Any], bool]:
+ """Frame stats + ``gl_frames`` findings of a graphics build as (lines, numbers, ok).
+
+ Reads ``artifacts/metrics.json`` through ``languages._gl_common.read_metrics``
+ — the one reader — and formats it the same way for every caller (the ``build``
+ tool, ``gl_probe`` and ``gl_frames``). ``hints`` appends each finding's fix
+ hint; ``root`` sanitises workspace paths out of the messages. Returns
+ ``(["(no frame metrics)"], {}, True)`` when the build wrote none.
+ """
+ from codeverse.spatial.observe import sanitize_text
+
+ try:
+ read_metrics = lazy("codeverse.languages._gl_common", "read_metrics")
+ m = read_metrics(ws)
+ except ToolUnavailable:
+ m = None
+ if m is None:
+ return ["(no frame metrics)"], {}, True
+ stats, gate = m
+ clean = (lambda t: sanitize_text(t, root)) if root else (lambda t: t)
+ lines = list(stats.summary_lines())
+ for f in gate.findings:
+ if f.severity is Severity.INFO:
+ continue
+ line = f"- {f.severity.value.upper()} [{f.data.get('kind', '')}] {clean(f.message)}"
+ if hints and f.fix_hint:
+ line += f"\n fix: {clean(f.fix_hint)}"
+ lines.append(line)
+ numbers: dict[str, Any] = {
+ "mean_lum": stats.mean_lum, "colourfulness": stats.mean_colourfulness,
+ "edge_density": stats.mean_edge_density, "mean_diff": stats.mean_diff, "static": stats.static,
+ "any_nan": stats.any_nan, "gate_passed": gate.passed, "gate_errors": len(gate.errors),
+ "n_frames": len(stats.frames),
+ }
+ return lines, numbers, not gate.errors
diff --git a/harness/codeverse/spatial/tools.py b/harness/codeverse/spatial/tools.py
index 7dee5999..dc42b921 100644
--- a/harness/codeverse/spatial/tools.py
+++ b/harness/codeverse/spatial/tools.py
@@ -11,7 +11,6 @@ and every tool is cheap to call repeatedly.
from __future__ import annotations
-import time
from typing import Any
from pydantic import BaseModel, Field
@@ -26,18 +25,18 @@ from codeverse.spatial.observe import (
rel_path,
sanitize_text,
tail_lines,
- truncate,
+ text_observation,
)
from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError, tool
from codeverse.spatial.sections import cross_section as _cross_section
from codeverse.spatial.tool_common import (
- ToolUnavailable,
call_adaptive,
+ gl_metrics_summary,
glb_path,
language_of,
lazy,
load_plan,
- unavailable_obs,
+ tool_out_dir,
)
_STDERR_TAIL_LINES = 30
@@ -86,25 +85,8 @@ def _no_glb_summary(ctx: ToolContext, br: BuildResult, language: str) -> tuple[b
ws = ctx.workspace
census = dict(br.census) if isinstance(br.census, dict) else {}
if language in _GL_LANGS:
- lines, numbers = [], {}
- try:
- read_metrics = lazy("codeverse.languages.glsl_shader.gl_build", "read_metrics")
- m = read_metrics(ws)
- except ToolUnavailable:
- m = None
- if m is not None:
- stats, gate = m
- lines.extend(stats.summary_lines())
- for f in gate.findings:
- if f.severity == Severity.INFO:
- continue
- lines.append(f"- {f.severity.value.upper()} [{f.data.get('kind', '')}] {sanitize_text(f.message, ws.root)}")
- numbers.update({"n_frames": len(stats.frames), "static": stats.static, "any_nan": stats.any_nan,
- "gate_errors": len(gate.errors)})
- ok = not gate.errors
- else:
- lines.append("(no frame metrics)")
- ok = True
+ # same frame-stats formatter the gl_probe / gl_frames tools use
+ lines, numbers, ok = gl_metrics_summary(ws, hints=False, root=ws.root)
for key in ("frames", "sheet", "gif"):
p = br.extra_paths.get(key)
if p:
@@ -122,14 +104,10 @@ def _no_glb_summary(ctx: ToolContext, br: BuildResult, language: str) -> tuple[b
@tool("build", NoArgs, "Lint + build the code in src/ with the language runtime, export artifacts/object.glb and measure it. Call after every edit.", cost_hint="slow")
def build(ctx: ToolContext, args: NoArgs) -> Observation:
+ # ToolDef.call stamps Observation.duration_ms for every tool — no timing here
ws = ctx.workspace
- t0 = time.time()
- try:
- language = language_of(ctx)
- get_runtime = lazy("codeverse.languages", "get_runtime")
- rt = get_runtime(language)
- except ToolUnavailable as e:
- return unavailable_obs("build", e)
+ language = language_of(ctx)
+ rt = lazy("codeverse.languages", "get_runtime")(language)
lint: GateReport = rt.lint(ws)
lint_errors = _lint_lines(lint, ws.root, errors_only=True)
lint_warns = _lint_lines(lint, ws.root, errors_only=False)
@@ -137,8 +115,7 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
text = "LINT FAILED — fix these before building:\n" + "\n".join(lint_errors)
if lint_warns:
text += "\nwarnings:\n" + "\n".join(lint_warns[:10])
- return Observation(ok=False, text=truncate(text), numbers={"stage": "lint", "lint_errors": len(lint_errors)},
- duration_ms=int((time.time() - t0) * 1000))
+ return text_observation(text, ok=False, numbers={"stage": "lint", "lint_errors": len(lint_errors)})
br: BuildResult = call_adaptive(rt.build, ws, timeout_s=get_settings().limits.build_timeout_s)
ws.write_json(ws.artifacts / "build_last.json", br)
numbers: dict[str, Any] = {"stage": "build", "ok": br.ok, "duration_ms": br.duration_ms}
@@ -151,8 +128,7 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
if lint_warns:
lines.append("lint hints:\n" + "\n".join(lint_warns[:10]))
numbers.update({"error_type": br.error_type, "error_file": rel_path(br.error_file, ws.root), "error_line": br.error_line})
- return Observation(ok=False, text=truncate("\n".join(lines), 3000), numbers=numbers,
- duration_ms=int((time.time() - t0) * 1000))
+ return text_observation(lines, ok=False, numbers=numbers, limit=3000)
if not br.glb_path and language in _SCENE_LANGS + _GL_LANGS:
# languages without a GLB deliverable: report the language's own artifacts
ok, extra_lines, extra_numbers = _no_glb_summary(ctx, br, language)
@@ -177,8 +153,7 @@ def build(ctx: ToolContext, args: NoArgs) -> Observation:
census_warn = br.census.get("warnings") if isinstance(br.census, dict) else None
if census_warn:
lines.append("build warnings:\n" + "\n".join(f"- {sanitize_text(str(w), ws.root)}" for w in list(census_warn)[:10]))
- return Observation(ok=ok, text=truncate("\n".join(lines), 3000), numbers=numbers,
- duration_ms=int((time.time() - t0) * 1000))
+ return text_observation(lines, ok=ok, numbers=numbers, limit=3000)
# --------------------------------------------------------------------------- measure
@@ -204,7 +179,7 @@ def measure(ctx: ToolContext, args: MeasureArgs) -> Observation:
"n_islands": m.n_islands, "ground_gap_m": m.ground_gap_m, "footprint_offset_m": m.footprint_offset_m,
"parts": {p.name: {"min": list(p.bbox_min), "max": list(p.bbox_max), "tris": p.tri_count,
"islands": p.islands, "watertight": p.watertight} for p in m.parts[:40]}}
- return Observation(ok=True, text=truncate(measure_summary_table(m)), numbers=numbers)
+ return text_observation(measure_summary_table(m), numbers=numbers)
# --------------------------------------------------------------------------- gates
@@ -245,8 +220,7 @@ def cross_section(ctx: ToolContext, args: CrossSectionArgs) -> Observation:
raise ToolUsageError(f"axis must be x|y|z, got {args.axis!r}", "cross_section(axis='y', at=0.5)")
if not 0.0 <= args.at <= 1.0:
raise ToolUsageError("at must be a bbox fraction in 0..1", "cross_section(axis='y', at=0.25)")
- out_dir = ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_sections"
- out_dir.mkdir(parents=True, exist_ok=True)
+ out_dir = tool_out_dir(ctx, "sections")
tag = f"{axis}_{int(round(args.at * 100)):03d}" + (f"_{len(args.parts)}p" if args.parts else "")
obs = _cross_section(glb, axis, args.at, out_dir / f"section_{tag}.png", parts=args.parts or None)
return obs
diff --git a/harness/codeverse/spatial/tools_graphics.py b/harness/codeverse/spatial/tools_graphics.py
index f6fcbbda..cfed515e 100644
--- a/harness/codeverse/spatial/tools_graphics.py
+++ b/harness/codeverse/spatial/tools_graphics.py
@@ -13,9 +13,14 @@ from pydantic import BaseModel, Field
from codeverse.contracts.artifacts import BuildResult, GateReport, Severity
from codeverse.contracts.common import Language
-from codeverse.spatial.observe import rel_path, sanitize_text, tail_lines, truncate
+from codeverse.spatial.observe import (
+ rel_path,
+ sanitize_text,
+ tail_lines,
+ text_observation,
+)
from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError, tool
-from codeverse.spatial.tool_common import ToolUnavailable, language_of, lazy, unavailable_obs
+from codeverse.spatial.tool_common import gl_metrics_summary, language_of, lazy, tool_out_dir
GRAPHICS_LANGS = (Language.GLSL_SHADER.value, Language.OPENGL_PYTHON.value)
MAX_FRAMES = 8
@@ -64,55 +69,42 @@ def _failure_text(br: BuildResult, root: Path, lint_warns: list[str]) -> str:
def _run_build(ctx: ToolContext, *, times: list[float], preview: bool, width: int = 0, height: int = 0) -> tuple[Observation | None, BuildResult | None, list[str]]:
- """Lint → build; returns (error observation | None, build, lint warnings)."""
+ """Lint → build; returns (error observation | None, build, lint warnings).
+
+ A missing runtime raises ToolUnavailable — ``ToolDef.call`` reports it.
+ """
ws = ctx.workspace
- try:
- rt = _runtime(ctx)
- except ToolUnavailable as e:
- return unavailable_obs("gl_frames", e), None, []
+ rt = _runtime(ctx)
lint: GateReport = rt.lint(ws)
errs, warns = _lint_block(lint, ws.root)
if errs:
text = "LINT FAILED — fix these before rendering:\n" + "\n".join(errs)
if warns:
text += "\nwarnings:\n" + "\n".join(warns[:8])
- return Observation(ok=False, text=truncate(text), numbers={"stage": "lint", "lint_errors": len(errs)}), None, warns
+ return text_observation(text, ok=False, numbers={"stage": "lint", "lint_errors": len(errs)}), None, warns
kw = {"times": times, "preview": preview}
if width and height:
kw.update(width=width, height=height)
br: BuildResult = rt.build(ws, **kw)
ws.write_json(ws.artifacts / "build_last.json", br)
if not br.ok:
- return Observation(ok=False, text=truncate(_failure_text(br, ws.root, warns), 3000),
- numbers={"stage": "build", "error_type": br.error_type, "error_file": br.error_file,
- "error_line": br.error_line}), br, warns
+ return text_observation(_failure_text(br, ws.root, warns), ok=False, limit=3000,
+ numbers={"stage": "build", "error_type": br.error_type, "error_file": br.error_file,
+ "error_line": br.error_line}), br, warns
return None, br, warns
def _stats_text(ctx: ToolContext) -> tuple[str, dict]:
- read_metrics = lazy("codeverse.languages._gl_common", "read_metrics")
- m = read_metrics(ctx.workspace)
- if m is None:
- return "(no frame metrics)", {}
- stats, gate = m
- lines = stats.summary_lines()
- for f in gate.findings:
- if f.severity == Severity.INFO:
- continue
- lines.append(f"- {f.severity.value.upper()} [{f.data.get('kind', '')}] {f.message}" + (f"\n fix: {f.fix_hint}" if f.fix_hint else ""))
- numbers = {"mean_lum": stats.mean_lum, "colourfulness": stats.mean_colourfulness, "edge_density": stats.mean_edge_density,
- "mean_diff": stats.mean_diff, "static": stats.static, "any_nan": stats.any_nan, "gate_passed": gate.passed,
- "gate_errors": len(gate.errors), "n_frames": len(stats.frames)}
+ """Frame stats + gate findings as (text, numbers) — shared formatter."""
+ lines, numbers, _ok = gl_metrics_summary(ctx.workspace)
return "\n".join(lines), numbers
@tool("gl_probe", GlProbeArgs, "Compile the shader / import the program and render ONE frame (default t=1 s): errors with src line numbers, or the frame + its stats. Call after every edit.",
languages=GRAPHICS_LANGS, cost_hint="slow")
def gl_probe(ctx: ToolContext, args: GlProbeArgs) -> Observation:
- t0 = time.time()
err, br, warns = _run_build(ctx, times=[args.t], preview=False)
if err is not None:
- err.duration_ms = int((time.time() - t0) * 1000)
return err
assert br is not None
text, numbers = _stats_text(ctx)
@@ -121,8 +113,8 @@ def gl_probe(ctx: ToolContext, args: GlProbeArgs) -> Observation:
if warns:
lines.append("lint warnings:\n" + "\n".join(warns[:8]))
numbers.update({"stage": "probe", "t": args.t, "duration_ms": br.duration_ms})
- return Observation(ok=numbers.get("gate_errors", 0) == 0, text=truncate("\n".join(lines), 3000), numbers=numbers,
- images=[str(p) for p in frames[:1]], duration_ms=int((time.time() - t0) * 1000))
+ return text_observation(lines, ok=numbers.get("gate_errors", 0) == 0, numbers=numbers,
+ images=[str(p) for p in frames[:1]], limit=3000)
@tool("gl_frames", GlFramesArgs, "Render frames at the judged times (0,1,2.5,4,6 s by default) → labelled contact sheet + per-frame metrics (luminance, colour, detail, motion, NaN) + the gl_frames gate. LOOK at the sheet.",
@@ -130,15 +122,12 @@ def gl_probe(ctx: ToolContext, args: GlProbeArgs) -> Observation:
def gl_frames(ctx: ToolContext, args: GlFramesArgs) -> Observation:
if not args.times or len(args.times) > MAX_FRAMES:
raise ToolUsageError(f"times must hold 1..{MAX_FRAMES} values", "gl_frames(times=[0, 1, 2.5, 4, 6])")
- t0 = time.time()
err, br, warns = _run_build(ctx, times=sorted(set(float(t) for t in args.times)), preview=False, width=args.width, height=args.height)
if err is not None:
- err.duration_ms = int((time.time() - t0) * 1000)
return err
assert br is not None
text, numbers = _stats_text(ctx)
- out_dir = ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_gl_{int(time.time()) % 100000}"
- out_dir.mkdir(parents=True, exist_ok=True)
+ out_dir = tool_out_dir(ctx, f"gl_{int(time.time()) % 100000}")
images: list[str] = []
sheet = br.extra_paths.get("sheet")
if sheet and Path(sheet).is_file():
@@ -151,5 +140,4 @@ def gl_frames(ctx: ToolContext, args: GlFramesArgs) -> Observation:
if warns:
lines.append("lint warnings:\n" + "\n".join(warns[:8]))
numbers.update({"stage": "frames", "times": args.times, "duration_ms": br.duration_ms, "sheet": rel_path(images[0], ctx.workspace.root) if images else ""})
- return Observation(ok=numbers.get("gate_errors", 0) == 0, text=truncate("\n".join(lines), 3000), numbers=numbers, images=images,
- duration_ms=int((time.time() - t0) * 1000))
+ return text_observation(lines, ok=numbers.get("gate_errors", 0) == 0, numbers=numbers, images=images, limit=3000)
diff --git a/harness/codeverse/spatial/tools_render.py b/harness/codeverse/spatial/tools_render.py
index d79ccce1..93bba0ce 100644
--- a/harness/codeverse/spatial/tools_render.py
+++ b/harness/codeverse/spatial/tools_render.py
@@ -19,14 +19,12 @@ from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError,
from codeverse.spatial.silhouette import compare_silhouette as _compare_silhouette
from codeverse.spatial.tool_common import (
VIEW_BY_NAME,
- ToolUnavailable,
cached_render_glb,
check_mode,
glb_path,
render_cache_dir,
resolve_views,
spec_dict,
- unavailable_obs,
)
_DEFAULT_VIEWS = [v.name for v in OBJECT_VIEWS_QUICK]
@@ -43,13 +41,12 @@ class RenderViewsArgs(BaseModel):
def _render(ctx: ToolContext, tool_name: str, *, views: list[str], mode: str, isolate: list[str], explode: float, size: int, sheet: bool = True, note: str = "") -> Observation:
+ # a missing renderer raises ToolUnavailable → ToolDef.call turns it into the
+ # "tool <name> unavailable" Observation (one error boundary for every tool)
glb = glb_path(ctx)
presets = resolve_views(views)
check_mode(mode)
- try:
- rs = cached_render_glb(ctx, glb, views=presets, mode=mode, size=size, isolate=isolate or None, explode=explode, sheet=sheet)
- except ToolUnavailable as e:
- return unavailable_obs(tool_name, e)
+ rs = cached_render_glb(ctx, glb, views=presets, mode=mode, size=size, isolate=isolate or None, explode=explode, sheet=sheet)
return render_observation(rs, ctx.workspace.root, note=note)
@@ -121,10 +118,7 @@ def compare_silhouette(ctx: ToolContext, args: CompareSilhouetteArgs) -> Observa
if args.view not in VIEW_BY_NAME:
raise ToolUsageError(f"unknown view {args.view!r}; choose from {list(VIEW_BY_NAME)}", "compare_silhouette(view='front')")
preset = VIEW_BY_NAME[args.view]
- try:
- rs = cached_render_glb(ctx, glb, views=[preset], mode="silhouette", size=512, sheet=False)
- except ToolUnavailable as e:
- return unavailable_obs("compare_silhouette", e)
+ rs = cached_render_glb(ctx, glb, views=[preset], mode="silhouette", size=512, sheet=False)
if not rs.views:
return Observation.error("compare_silhouette: renderer produced no view")
out_dir = render_cache_dir(ctx, glb, silhouette=args.view, ref=args.reference_index)
diff --git a/harness/codeverse/spatial/tools_scene.py b/harness/codeverse/spatial/tools_scene.py
index 41f44258..bce4bb26 100644
--- a/harness/codeverse/spatial/tools_scene.py
+++ b/harness/codeverse/spatial/tools_scene.py
@@ -1,7 +1,8 @@
"""Track/language-specific tools: joint_sweep (articulated), shader_probe /
scene_probe / scene_views (scene_threejs). All delegate lazily to sibling
modules (``spatial.joints``, ``spatial.probes``, ``spatial.render``) written in
-parallel; a missing sibling degrades to a clear ``tool X unavailable`` Observation.
+parallel; a missing sibling raises ``ToolUnavailable``, which ``ToolDef.call``
+turns into a clear ``tool X unavailable`` Observation.
"""
from __future__ import annotations
@@ -14,13 +15,7 @@ from codeverse.contracts.artifacts import GateReport, RenderSet
from codeverse.contracts.common import Language, Track
from codeverse.spatial.observe import fmt_numbers, gate_observation, render_observation, truncate
from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError, tool
-from codeverse.spatial.tool_common import (
- ToolUnavailable,
- call_adaptive,
- lazy,
- load_plan,
- unavailable_obs,
-)
+from codeverse.spatial.tool_common import call_adaptive, lazy, load_plan, tool_out_dir
def _as_observation(result: Any, root, *, title: str) -> Observation:
@@ -52,12 +47,8 @@ class JointSweepArgs(BaseModel):
@tool("joint_sweep", JointSweepArgs, "Sweep URDF joints through their ranges: pose renders + self-collision / limit findings.",
tracks=(Track.ARTICULATED_OBJECT.value,), cost_hint="slow")
def joint_sweep(ctx: ToolContext, args: JointSweepArgs) -> Observation:
- try:
- fn = lazy("codeverse.spatial.joints", "joint_sweep_observation")
- except ToolUnavailable as e:
- return unavailable_obs("joint_sweep", e)
- out_dir = ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_joints"
- out_dir.mkdir(parents=True, exist_ok=True)
+ fn = lazy("codeverse.spatial.joints", "joint_sweep_observation")
+ out_dir = tool_out_dir(ctx, "joints")
# package E's signature: (ws, *, n_random, seed, render, out_dir, joint, expected_direction)
res = call_adaptive(fn, ctx.workspace, joints=args.joints or None, n_samples=args.n_samples,
n_random=args.n_samples, joint=args.joints[0] if len(args.joints) == 1 else None,
@@ -73,10 +64,7 @@ class NoArgs(BaseModel):
@tool("shader_probe", NoArgs, "Compile every GLSL/ShaderMaterial in the scene headlessly and report shader errors with line numbers.",
languages=(Language.SCENE_THREEJS.value,), cost_hint="slow")
def shader_probe(ctx: ToolContext, args: NoArgs) -> Observation:
- try:
- fn = lazy("codeverse.spatial.probes", "check_shaders")
- except ToolUnavailable as e:
- return unavailable_obs("shader_probe", e)
+ fn = lazy("codeverse.spatial.probes", "check_shaders")
res = call_adaptive(fn, ctx.workspace, round_index=ctx.round_index)
return _as_observation(res, ctx.workspace.root, title="shader probe")
@@ -84,10 +72,7 @@ def shader_probe(ctx: ToolContext, args: NoArgs) -> Observation:
@tool("scene_probe", NoArgs, "Load the scene headlessly: object/material/light census, triangle count, fps, console errors.",
languages=(Language.SCENE_THREEJS.value,), cost_hint="slow")
def scene_probe(ctx: ToolContext, args: NoArgs) -> Observation:
- try:
- fn = lazy("codeverse.spatial.probes", "probe_scene")
- except ToolUnavailable as e:
- return unavailable_obs("scene_probe", e)
+ fn = lazy("codeverse.spatial.probes", "probe_scene")
res = call_adaptive(fn, ctx.workspace, round_index=ctx.round_index)
obs = _as_observation(res, ctx.workspace.root, title="scene probe")
census = obs.numbers.get("census") if isinstance(obs.numbers, dict) else None
@@ -108,10 +93,7 @@ def scene_views(ctx: ToolContext, args: SceneViewsArgs) -> Observation:
raise ToolUsageError("cameras must be authored | orbit | all", "scene_views(cameras='authored')")
if not args.times or len(args.times) > 6:
raise ToolUsageError("times must hold 1..6 values", "scene_views(times=[0.0, 1.5])")
- try:
- render_scene = lazy("codeverse.spatial.render", "render_scene")
- except ToolUnavailable as e:
- return unavailable_obs("scene_views", e)
+ render_scene = lazy("codeverse.spatial.render", "render_scene")
cams = None
if args.cameras in ("authored", "all") and ctx.workspace.plan_path.is_file():
try:
@@ -121,7 +103,6 @@ def scene_views(ctx: ToolContext, args: SceneViewsArgs) -> Observation:
cams = None
orbit = args.cameras in ("orbit", "all") or (args.cameras == "authored" and cams is None)
key = f"{args.cameras}_{'_'.join(f'{t:g}' for t in args.times)}".replace(".", "p")
- out_dir = ctx.workspace.artifacts / "tool_renders" / f"r{ctx.round_index:02d}_scene_{key}"
- out_dir.mkdir(parents=True, exist_ok=True)
+ out_dir = tool_out_dir(ctx, f"scene_{key}")
rs = call_adaptive(render_scene, ctx.workspace, out_dir, cameras=cams, orbit=orbit, times=tuple(args.times), sheet=True)
return _as_observation(rs, ctx.workspace.root, title=f"scene views ({args.cameras}, t={args.times})")
diff --git a/harness/codeverse/spatial/tools_texture.py b/harness/codeverse/spatial/tools_texture.py
index 1f6aedaa..e3f76c6b 100644
--- a/harness/codeverse/spatial/tools_texture.py
+++ b/harness/codeverse/spatial/tools_texture.py
@@ -10,23 +10,14 @@ the ship gate) unless ``ctx.extra['texture_services']`` injects a
from __future__ import annotations
-from pathlib import Path
-
from pydantic import BaseModel, Field
from codeverse.contracts.common import Track
from codeverse.contracts.plan import StaticPlan
from codeverse.contracts.spec import Spec
-from codeverse.spatial.observe import rel_path
+from codeverse.spatial.observe import rel_path, text_observation
from codeverse.spatial.registry import Observation, ToolContext, ToolUsageError, tool
-from codeverse.spatial.tool_common import (
- ToolUnavailable,
- glb_path,
- lazy,
- load_plan,
- spec_dict,
- unavailable_obs,
-)
+from codeverse.spatial.tool_common import glb_path, lazy, load_plan, spec_dict
_OBJECT_TRACKS = (Track.STATIC_OBJECT.value, Track.ARTICULATED_OBJECT.value)
@@ -55,10 +46,7 @@ def _spec_plan(ctx: ToolContext) -> tuple[Spec, StaticPlan]:
def texture_pass_tool(ctx: ToolContext, args: TexturePassArgs) -> Observation:
glb = glb_path(ctx)
spec, plan = _spec_plan(ctx)
- try:
- texture_pass = lazy("codeverse.texturing.run", "texture_pass")
- except ToolUnavailable as e:
- return unavailable_obs("texture_pass", e)
+ texture_pass = lazy("codeverse.texturing.run", "texture_pass")
services = ctx.extra.get("texture_services") # the ONE injection point (TextureServices)
rep = texture_pass(ctx.workspace, spec, plan, model_id=args.model or spec.backends.planner,
judge=args.judge, glb_in=glb, size=args.size, services=services)
@@ -78,7 +66,7 @@ def texture_pass_tool(ctx: ToolContext, args: TexturePassArgs) -> Observation:
images = []
if rep.gate is not None and rep.gate.renders_after and rep.gate.renders_after.contact_sheet:
images.append(rep.gate.renders_after.contact_sheet)
- return Observation(ok=True, text="\n".join(lines), numbers=s, images=images)
+ return text_observation(lines, numbers=s, images=images)
class TexturePreviewArgs(BaseModel):
@@ -96,12 +84,9 @@ def texture_preview(ctx: ToolContext, args: TexturePreviewArgs) -> Observation:
if not glb.is_file():
raise ToolUsageError("artifacts/object_textured.glb does not exist — run texture_pass first", "texture_pass()")
presets = resolve_views(args.views)
- try:
- rs = cached_render_glb(ctx, glb, views=presets, mode="shaded", size=512, sheet=True)
- except ToolUnavailable as e:
- return unavailable_obs("texture_preview", e)
+ rs = cached_render_glb(ctx, glb, views=presets, mode="shaded", size=512, sheet=True)
tex_dir = ws.artifacts / "textures"
pngs = sorted(p.name for p in tex_dir.glob("*.png")) if tex_dir.is_dir() else []
text = f"textured GLB rendered ({len(rs.views)} views). textures: {', '.join(pngs) or 'none'}"
images = [rs.contact_sheet] if rs.contact_sheet else [v.path for v in rs.views]
- return Observation(ok=True, text=text, numbers={"n_textures": len(pngs)}, images=[str(Path(i)) for i in images])
+ return text_observation(text, numbers={"n_textures": len(pngs)}, images=images)
diff --git a/harness/codeverse/spatial/turntable.py b/harness/codeverse/spatial/turntable.py
index e9f15533..61d8b419 100644
--- a/harness/codeverse/spatial/turntable.py
+++ b/harness/codeverse/spatial/turntable.py
@@ -6,9 +6,8 @@ import shutil
import subprocess
from pathlib import Path
-from PIL import Image
-
from codeverse.config import get_settings
+from codeverse.spatial.sheet import write_gif
def assemble_turntable(frames: list[Path], out: Path, *, fps: int = 12) -> Path:
@@ -40,6 +39,5 @@ def _mp4(frames: list[Path], out: Path, fps: int, ffmpeg: str) -> Path:
def _gif(frames: list[Path], out: Path, fps: int) -> Path:
- images = [Image.open(f).convert("RGB").convert("P", palette=Image.ADAPTIVE, colors=128) for f in frames]
- images[0].save(out, save_all=True, append_images=images[1:], duration=int(1000 / fps), loop=0, optimize=False)
- return out
+ """Animated GIF via the shared writer (``spatial.sheet.write_gif``)."""
+ return write_gif(frames, out, fps=fps)
diff --git a/harness/codeverse/tracks/lifecycle.py b/harness/codeverse/tracks/lifecycle.py
index 006eea31..3b2a66ce 100644
--- a/harness/codeverse/tracks/lifecycle.py
+++ b/harness/codeverse/tracks/lifecycle.py
@@ -107,6 +107,9 @@ class BaseTrack:
plan_max_output_tokens: int = 24000
#: refine fan-out (graphics is always ONE whole-program task)
allow_refine_fanout: bool = True
+ #: share of the run budget the BASELINE may use (1.0 = no soft cap). The scene
+ #: track lowers it so the refine rounds always inherit money and minutes.
+ soft_budget_fraction: float = 1.0
def __init__(
self,
@@ -148,6 +151,15 @@ class BaseTrack:
def round_files_hint(self, ctx: RunContext) -> list[str]:
return []
+ def round_extra_notes(self, ctx: RunContext) -> list[str]:
+ """Notes folded into every round record (e.g. 'the baseline was degraded')."""
+ return list(ctx.extra.get("degraded") or [])
+
+ def prepare_salvage(self, ctx: RunContext) -> bool:
+ """Make the workspace buildable after a stage tripped the budget before
+ round 0. Return False (the default) when the track has nothing to salvage."""
+ return False
+
# ---- planner hooks (tracks/planner.py runs the one loop)
def plan_example(self, spec: Spec) -> dict[str, Any]:
"""Worked example JSON for the plan system prompt."""
@@ -238,6 +250,7 @@ class BaseTrack:
except BudgetExceeded as e:
events.emit("budget.exceeded", reason=e.reason, spent_usd=round(e.spent_usd, 4))
stop, error = "budget", e.reason
+ self._salvage_baseline(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:])
@@ -255,7 +268,7 @@ class BaseTrack:
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)
+ budget = BudgetGuard(spec.budget, soft_fraction=self.soft_budget_fraction)
spent = state.extra.get("spent_usage")
if spent:
budget.spent = Usage.model_validate(spent)
@@ -408,7 +421,8 @@ class BaseTrack:
rec = run_best_of_n(self, ctx, tasks, pipeline, files_hint=self.round_files_hint(ctx))
else:
rec = run_round(ctx, index=index, kind=kind, tasks=tasks, pipeline=pipeline, instructions=instructions,
- previous=previous, files_hint=self.round_files_hint(ctx))
+ previous=previous, files_hint=self.round_files_hint(ctx),
+ extra_notes=self.round_extra_notes(ctx))
except RoundFailed as e:
if index == 0:
raise
@@ -425,6 +439,41 @@ class BaseTrack:
ctx.events.emit("best.updated", round=best, score=rounds[best].score)
self._save_spent(ctx)
+ def _salvage_baseline(self, ctx: RunContext, rounds: list[RoundRecord]) -> None:
+ """A stage tripped the budget BEFORE round 0 ever ran (the greenhouse scene:
+ the zone fan-out crossed the ceiling, so the run finished with no build, no
+ render, no judge and no score at all).
+
+ The workspace still holds buildable code, and build → render → judge is a
+ fraction of a generation session, so grant an explicit one-off grace and
+ deliver ONE no-generation round. Any failure here is swallowed: the run is
+ already stopping on budget."""
+ if rounds or ctx.state.completed_rounds or ctx.plan is None:
+ return # nothing was built yet (the PLAN itself blew the budget) → nothing to salvage
+ if not ctx.budget.ok() and ctx.budget.spent.cost_usd > ctx.budget.hard_usd * 2:
+ return # runaway spend: do not throw good money after bad
+ grace_usd = max(0.15, ctx.spec.budget.max_usd * 0.10)
+ grace_min = max(5.0, ctx.spec.budget.max_minutes * 0.15)
+ ctx.budget.grant_grace(usd=grace_usd, minutes=grace_min)
+ ctx.events.emit("budget.salvage", reason="no round completed before the budget stop",
+ grace_usd=round(grace_usd, 3), grace_minutes=round(grace_min, 1))
+ try:
+ if not self.prepare_salvage(ctx):
+ ctx.events.emit("budget.salvage_skipped", reason="nothing buildable to salvage")
+ return
+ rec = run_round(ctx, index=0, kind="baseline", tasks=[], pipeline=self.make_pipeline(), instructions=[],
+ previous=None, files_hint=self.round_files_hint(ctx),
+ extra_notes=["salvaged: the budget stopped the run before round 0", *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)
+ ctx.state.mark_round_done(0, rec.commit)
+ if ctx.state.update_best(0, rec.commit, rec.score):
+ ctx.events.emit("best.updated", round=0, score=rec.score)
+ self._save_spent(ctx)
+
def _save_spent(self, ctx: RunContext) -> None:
ctx.state.extra["spent_usage"] = ctx.budget.spent.model_dump(mode="json")
ctx.state.save(ctx.ws)
diff --git a/harness/codeverse/tracks/scene.py b/harness/codeverse/tracks/scene.py
index de2ea602..66b04061 100644
--- a/harness/codeverse/tracks/scene.py
+++ b/harness/codeverse/tracks/scene.py
@@ -5,11 +5,24 @@ Language: scene_threejs. Generation is staged (each stage cached by
renders authored cameras + orbit at t=0 and t=1.5, judges with ``scene_v1``
(console/shader errors become gate ERRORS) and dispatches refine tasks per
zone / asset / env / camera, in parallel when file-disjoint.
+
+Cost/latency shaping (the baseline used to eat the whole budget, leaving the
+refine rounds nothing):
+
+* assets are single-shot by default (``scene_assets`` / ``scene_asset_gen``);
+* **small zones are batched** — a zone that places ≤ 3 assets is written
+ together with its neighbour in ONE session that exclusively owns both files,
+ while big zones keep the parallel fan-out;
+* every stage session gets a timeout clipped to the wall-clock actually left;
+* the baseline runs against a **soft sub-budget** (``soft_budget_fraction``);
+ when it is spent the stages degrade (single-shot instead of an agent session,
+ fewer assets, no asset judge) instead of dying at the hard cap.
"""
from __future__ import annotations
import logging
+import time
from typing import Any
from codeverse.contracts.artifacts import (
@@ -41,13 +54,28 @@ from codeverse.tracks.prompting import (
judge_digest,
)
from codeverse.tracks.repair import format_error_report
-from codeverse.tracks.scene_assets import AssetResult, asset_api_summary, run_asset_stage
+from codeverse.tracks.scene_asset_gen import select_assets, single_shot_ctx
+from codeverse.tracks.scene_assets import (
+ MAX_ASSETS,
+ AssetResult,
+ asset_api_summary,
+ run_asset_stage,
+)
from codeverse.workspace import Workspace
log = logging.getLogger(__name__)
SCENE_TIMES: tuple[float, float] = (0.0, 1.5)
MAX_CONSOLE_ERRORS = 8
+#: a zone placing at most this many assets is small enough to share a session
+SMALL_ZONE_CONTENTS = 3
+#: how many small zones may share one session (file ownership stays disjoint)
+MAX_ZONES_PER_BATCH = 2
+ENV_TIMEOUT_S = 420
+ZONE_TIMEOUT_S = 600
+#: a refine session that runs for half an hour (the desert-canyon round 1 did) spends the
+#: wall clock the NEXT round needed; clip it to what the hard budget still allows
+REFINE_TIMEOUT_S = 900
class ScenePipeline:
@@ -121,6 +149,10 @@ class SceneTrack(BaseTrack):
def make_pipeline(self) -> ScenePipeline:
return ScenePipeline()
+ #: the baseline (assets → env → zones → assemble → round 0) may use this share of
+ #: the run budget; the rest belongs to the refine rounds.
+ soft_budget_fraction = 0.55
+
# ------------------------------------------------------------------ stages
def prepare(self, ctx: RunContext, runner: StageRunner) -> None:
self.stage_skeleton(ctx, runner)
@@ -128,56 +160,111 @@ class SceneTrack(BaseTrack):
plan: ScenePlan = ctx.plan # type: ignore[assignment]
assets = runner.stage("assets", lambda: run_asset_stage(ctx), inputs={"assets": plan.assets, "agent": ctx.agent_id})
assets = {k: AssetResult.model_validate(v) if isinstance(v, dict) else v for k, v in (assets or {}).items()}
+ # the merge map is a pure function of the plan, so a RESUMED run (cached asset
+ # stage) still tells the zones which builder+variant to call
+ _, alias = select_assets(list(plan.assets), MAX_ASSETS)
ctx.extra["assets"] = assets
- ctx.extra["asset_api"] = asset_api_summary(plan, assets)
+ ctx.extra["asset_alias"] = alias
+ ctx.extra["asset_api"] = asset_api_summary(plan, assets, alias)
runner.stage("env", lambda: self._env_stage(ctx), inputs={"plan_env": plan.environment, "setting": plan.setting, "agent": ctx.agent_id})
runner.stage("zones", lambda: self._zones_stage(ctx), inputs={"zones": plan.zones, "asset_api": ctx.extra["asset_api"], "agent": ctx.agent_id})
runner.stage("assemble", lambda: self._assemble_stage(ctx), inputs={"cameras": plan.cameras, "zones": [z.name for z in plan.zones]})
+ # ---- degradation ------------------------------------------------------
+ def _strategy(self, ctx: RunContext, stage: str) -> RunContext:
+ """The context a stage should generate with: the agent normally, single-shot
+ once the baseline has spent its soft sub-budget (never dying at the hard cap)."""
+ 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, spent_usd=round(ctx.budget.spent.cost_usd, 4),
+ elapsed_min=round(ctx.budget.elapsed_minutes(), 2))
+
def _env_stage(self, ctx: RunContext) -> dict[str, Any]:
- prompt = render("tracks/scene_env.j2", **self._ctx(ctx))
+ gen = self._strategy(ctx, "env")
+ prompt = render("tracks/scene_env.j2", **self._ctx(gen))
ctx.record_prompt("scene_env", prompt)
task = GenerationTask(label="env", prompt=prompt, system=self.system_prompt(ctx), files_hint=["src/env.js"], round=0, kind="env",
- temperature=0.5)
- res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
+ temperature=0.5, timeout_s=ctx.budget.timeout_s(ENV_TIMEOUT_S, floor_s=120))
+ res = generate(ctx.ws, agent_id=gen.agent_id, task=task, agent=gen.agent, model=gen.model, settings=ctx.settings,
budget=ctx.budget, events=ctx.events)
ctx.ws.commit("env")
return {"ok": res.ok, "files": [c.path for c in res.files_changed], "notes": res.notes}
def _zones_stage(self, ctx: RunContext) -> dict[str, Any]:
plan: ScenePlan = ctx.plan # type: ignore[assignment]
-
- def _one(zone: ZonePlan) -> GenerationResult:
- task = self._zone_task(ctx, zone)
- return generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
+ t0 = time.time()
+ batches = plan_zone_batches(list(plan.zones))
+ if any(len(b) > 1 for b in batches):
+ ctx.events.emit("zones.batched", batches=[[z.name for z in b] for b in batches])
+
+ def _one(batch: list[ZonePlan]) -> GenerationResult:
+ gen = self._strategy(ctx, "zones")
+ task = self._zone_task(gen, batch)
+ return generate(ctx.ws, agent_id=gen.agent_id, task=task, agent=gen.agent, model=gen.model, settings=ctx.settings,
budget=ctx.budget, events=ctx.events)
- results = fan_out(list(plan.zones), _one, max_workers=ctx.settings.limits.max_parallel_agents, label="zones",
- item_name=lambda z: z.name)
+ results = fan_out(batches, _one, max_workers=ctx.settings.limits.max_parallel_agents, label="zones",
+ item_name=lambda b: "+".join(z.name for z in b))
out: dict[str, Any] = {}
- for zone, r in zip(plan.zones, results, strict=True):
+ for batch, r in zip(batches, results, strict=True):
if isinstance(r, Exception):
from codeverse.orchestrator.budget import BudgetExceeded
if isinstance(r, BudgetExceeded):
raise r
- out[zone.name] = {"ok": False, "notes": f"{type(r).__name__}: {r}"}
+ for zone in batch:
+ out[zone.name] = {"ok": False, "notes": f"{type(r).__name__}: {r}"}
else:
- out[zone.name] = {"ok": r.ok, "files": [c.path for c in r.files_changed], "notes": r.notes}
+ written = {c.path for c in r.files_changed}
+ for zone in batch:
+ rel = zone_file(zone)
+ # a batched session must have produced EVERY file it owns; the skeleton
+ # left a stub at every zone path, so existence proves nothing — the file
+ # must have been reported as changed or actually rewritten in this stage
+ ok = r.ok and (len(batch) == 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}
ctx.ws.commit("zones")
ctx.events.emit("zones.done", ok=[k for k, v in out.items() if v["ok"]], failed=[k for k, v in out.items() if not v["ok"]])
return out
- def _zone_task(self, ctx: RunContext, zone: ZonePlan) -> GenerationTask:
+ def _zone_task(self, ctx: RunContext, batch: list[ZonePlan]) -> GenerationTask:
+ """One task for one zone, or for a batch of small zones that shares a session.
+
+ A batched task exclusively owns every file it lists, so ``files_hint``
+ attribution and the refine fan-out stay file-disjoint."""
plan: ScenePlan = ctx.plan # type: ignore[assignment]
- rel = f"src/zones/{to_snake(zone.name)}.js"
- neighbours = [f"{z.name}: {bbox_line(z.bbox)}" for z in plan.zones if z.name != zone.name]
- prompt = render("tracks/scene_zone.j2", **self._ctx(ctx, zone_name=zone.name, zone_description=zone.description,
- zone_bbox=bbox_line(zone.bbox), zone_contents=zone.contents,
- zone_file=rel, neighbours=neighbours))
- ctx.record_prompt("scene_zone", prompt)
- return GenerationTask(label=f"zone_{to_snake(zone.name)}", prompt=prompt, system=self.system_prompt(ctx), files_hint=[rel],
- round=0, kind="zone", temperature=0.5)
+ names = [z.name for z in batch]
+ files = [zone_file(z) for z in batch]
+ briefs = []
+ for zone in batch:
+ neighbours = [f"{z.name}: {bbox_line(z.bbox)}" for z in plan.zones if z.name != zone.name]
+ briefs.append(render("tracks/scene_zone.j2", **self._ctx(ctx, zone_name=zone.name, zone_description=zone.description,
+ zone_bbox=bbox_line(zone.bbox), zone_contents=zone.contents,
+ zone_file=zone_file(zone), neighbours=neighbours)))
+ ctx.record_prompt("scene_zone", briefs[0])
+ 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 exactly as its brief says. "
+ "They are small neighbouring zones, so keep their styling consistent and do not build into each other.\n")
+ prompt = header + "\n\n---\n\n".join(briefs)
+ label = "zones_" + "_".join(to_snake(n) for n in names)
+ return GenerationTask(label=label, prompt=prompt, system=self.system_prompt(ctx), files_hint=files,
+ round=0, kind="zone", temperature=0.5, timeout_s=ctx.budget.timeout_s(ZONE_TIMEOUT_S, floor_s=180))
def _assemble_stage(self, ctx: RunContext) -> dict[str, Any]:
try:
@@ -196,6 +283,23 @@ class SceneTrack(BaseTrack):
ctx.ws.commit("compose")
return {"ok": res.ok, "deterministic": False, "files": [c.path for c in res.files_changed], "notes": res.notes}
+ def prepare_salvage(self, ctx: RunContext) -> bool:
+ """The budget stopped a stage before round 0: assemble whatever the stages DID
+ write (the skeleton guarantees a stub per zone) so the run still delivers a
+ built, rendered, judged scene instead of no score at all."""
+ plan: ScenePlan = ctx.plan # type: ignore[assignment]
+ zones = [z for z in plan.zones if (ctx.ws.root / zone_file(z)).is_file()]
+ if not zones:
+ return False
+ ctx.extra.setdefault("asset_api", asset_api_summary(plan, ctx.extra.get("assets") or {}, ctx.extra.get("asset_alias")))
+ 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
@@ -216,7 +320,8 @@ class SceneTrack(BaseTrack):
current_files=current_files(ctx, files) if ctx.single_shot else {}))
ctx.record_prompt("scene_refine", prompt)
return GenerationTask(label=f"refine_{group.label}" if parallel else "refine", prompt=prompt, system=self.system_prompt(ctx),
- files_hint=files, round=index, kind="refine", temperature=0.4)
+ files_hint=files, round=index, kind="refine", temperature=0.4,
+ timeout_s=ctx.budget.timeout_s(REFINE_TIMEOUT_S, floor_s=180, soft=False))
def _rebuild_task(self, ctx: RunContext, last: RoundRecord, index: int) -> GenerationTask:
"""One repair task carrying the structured error report (build + lint + census
@@ -237,7 +342,8 @@ class SceneTrack(BaseTrack):
current_files=current_files(ctx, files) if ctx.single_shot else {}))
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")
+ kind="rebuild", temperature=0.7, thinking="high",
+ timeout_s=ctx.budget.timeout_s(REFINE_TIMEOUT_S, floor_s=180, soft=False))
# ------------------------------------------------------------------ helpers
def system_prompt(self, ctx: RunContext) -> str:
@@ -257,6 +363,44 @@ class SceneTrack(BaseTrack):
# ----------------------------------------------------------------------------- helpers
+def zone_file(zone: ZonePlan) -> str:
+ return f"src/zones/{to_snake(zone.name)}.js"
+
+
+def _touched(path: Any, since: float) -> bool:
+ """Was ``path`` (re)written after ``since``? (mtime beats existence: every zone
+ path already holds a skeleton stub.)"""
+ try:
+ return path.is_file() and path.stat().st_mtime > since
+ except OSError:
+ return False
+
+
+def plan_zone_batches(zones: list[ZonePlan], *, small_max: int = SMALL_ZONE_CONTENTS,
+ max_per_batch: int = MAX_ZONES_PER_BATCH) -> list[list[ZonePlan]]:
+ """Group consecutive SMALL zones (≤ ``small_max`` asset placements) into shared
+ sessions; big zones keep a session of their own.
+
+ Plan order is preserved, so a batch is always a pair of neighbours and the
+ batching is deterministic (stage-hash stable across resumes)."""
+ batches: list[list[ZonePlan]] = []
+ pending: list[ZonePlan] = []
+ for z in zones:
+ if len(z.contents) > small_max:
+ if pending:
+ batches.append(pending)
+ pending = []
+ batches.append([z])
+ continue
+ pending.append(z)
+ if len(pending) >= max_per_batch:
+ batches.append(pending)
+ pending = []
+ if pending:
+ batches.append(pending)
+ return batches
+
+
def census_gate_report(build: BuildResult) -> GateReport | None:
"""Turn scene census error lists (console/shader) into a gate, when present."""
c = build.census or {}
diff --git a/harness/codeverse/tracks/scene_asset_gen.py b/harness/codeverse/tracks/scene_asset_gen.py
new file mode 100644
index 00000000..a99c396f
--- /dev/null
+++ b/harness/codeverse/tracks/scene_asset_gen.py
@@ -0,0 +1,332 @@
+"""Cheap scene-asset generation: single-shot first, deterministic check, dedupe.
+
+Measured on the 2026-08-23 scene battery: every asset was a full coding-agent
+session (26–44 turns, 3–4 whole-scene ``build`` + ``scene_probe`` calls each) —
+$0.11–0.25 and 1–8 minutes **per asset file**, 45 % of the whole run's cost. An
+asset module is one self-contained file; it does not need a tool loop.
+
+So the default here is:
+
+1. **single-shot** the file (one chat call), then
+2. run a deterministic node check (import the module, call the builder, inspect
+ the returned group: exports, NaN vertices, empty bbox, triangle budget) —
+ ~0.08 s, no browser, precise error text with line numbers, then
+3. **one** error-feedback single-shot repair, then
+4. only if that still fails: escalate to a real agent session.
+
+``blender_glb`` assets are heroes and keep their agent session.
+``select_assets`` caps the list by plan priority and, only when the plan is over
+that cap, folds near-identical props (two rock variants) into ONE factory that
+zones call with an ``opts.variant`` — a rescue for props truncation would drop.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import replace
+from pathlib import Path
+
+from pydantic import BaseModel, Field
+
+from codeverse.contracts.plan import AssetPlan
+from codeverse.conventions import to_pascal, to_snake
+from codeverse.proc import write_json_atomic
+from codeverse.tracks.common import RunContext
+from codeverse.tracks.generation import SINGLE_SHOT_PREFIX, is_single_shot
+from codeverse.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+#: max triangles for ONE asset instance (the scene contract's budget)
+ASSET_MAX_TRIS = 15_000
+
+
+# ----------------------------------------------------------------------------- strategy
+def single_shot_agent_id(agent_id: str) -> str:
+ """``api-agent:gemini:x`` → ``single-shot:gemini:x``; "" when not derivable.
+
+ Only API backends can be single-shot: a CLI agent (gemini-cli / claude-code /
+ codex / agy) runs on a local subscription and exposes no chat model."""
+ if is_single_shot(agent_id):
+ return agent_id
+ kind, _, rest = agent_id.partition(":")
+ if kind == "api-agent" and rest.count(":") >= 1:
+ return SINGLE_SHOT_PREFIX + rest
+ return ""
+
+
+def single_shot_ctx(ctx: RunContext) -> RunContext | None:
+ """A copy of ``ctx`` bound to the single-shot strategy, or None when the
+ generator has no usable chat model (CLI agents, tests with fake services)."""
+ cached = ctx.extra.get("_single_shot_ctx")
+ if cached is not None:
+ return cached or None # False = known-unavailable
+ sid = single_shot_agent_id(ctx.agent_id)
+ 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
+
+
+# ----------------------------------------------------------------------------- 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 = 0
+ meshes: int = 0
+ materials: int = 0
+
+ def report(self, limit: int = 6) -> str:
+ return "\n".join(f"- {e}" for e in (self.errors + self.warnings)[:limit])
+
+
+_CHECK_JS = r"""
+import * as THREE from 'three';
+const [, , fileUrl, exportName] = process.argv;
+const out = { ok: false, errors: [], warnings: [], size_m: null, tris: 0, meshes: 0, materials: 0 };
+try {
+ const mod = await import(fileUrl);
+ const fn = mod[exportName] ?? mod.default;
+ if (typeof fn !== 'function') {
+ out.errors.push(`missing export: this file must \`export function ${exportName}(THREE, opts = {})\` (found: ${Object.keys(mod).join(', ') || 'nothing'})`);
+ } else {
+ const g = fn(THREE, {});
+ if (!g || !g.isObject3D) {
+ out.errors.push(`${exportName}(THREE) must return a THREE.Group / Object3D (got ${Object.prototype.toString.call(g)})`);
+ } else {
+ const box = new THREE.Box3().setFromObject(g);
+ const mats = new Set();
+ let bad = 0;
+ g.traverse((o) => {
+ if (!o.isMesh) return;
+ out.meshes += 1;
+ mats.add(o.material?.uuid ?? o.material);
+ const pos = o.geometry?.attributes?.position;
+ if (!pos) return;
+ const arr = pos.array;
+ for (let i = 0; i < arr.length; i++) if (!Number.isFinite(arr[i])) { bad += 1; break; }
+ const idx = o.geometry.index;
+ out.tris += ((idx ? idx.count : pos.count) / 3) * (o.isInstancedMesh ? o.count : 1);
+ });
+ out.materials = mats.size;
+ if (bad) out.errors.push(`${bad} mesh(es) have NaN/Infinity vertex positions`);
+ if (out.meshes === 0) out.errors.push('the returned group contains no meshes');
+ if (box.isEmpty()) out.errors.push('the returned group has an empty bounding box');
+ else {
+ const s = new THREE.Vector3(); box.getSize(s);
+ if (!Number.isFinite(s.x + s.y + s.z)) out.errors.push('the bounding box is not finite');
+ else { out.size_m = [+s.x.toFixed(3), +s.y.toFixed(3), +s.z.toFixed(3)]; out.min_y = +box.min.y.toFixed(3); }
+ }
+ out.tris = Math.round(out.tris);
+ }
+ }
+} catch (e) {
+ out.errors.push(`${e?.name || 'Error'}: ${e?.message || String(e)}`);
+ const stack = String(e?.stack || '').split('\n').slice(1, 4).filter((l) => l.includes(fileUrl.replace('file://', '')));
+ if (stack.length) out.errors.push('at ' + stack.map((l) => l.trim()).join(' / '));
+}
+out.ok = out.errors.length === 0;
+console.log(JSON.stringify(out));
+"""
+
+
+def _checker_path(ctx: RunContext) -> Path:
+ """The checker script lives in the harness cache, never in the workspace."""
+ p = Path(ctx.settings.cache_dir) / "scene_asset_check.mjs"
+ if not p.is_file() or p.read_text() != _CHECK_JS:
+ p.parent.mkdir(parents=True, exist_ok=True)
+ tmp = p.with_suffix(".mjs.tmp")
+ tmp.write_text(_CHECK_JS)
+ tmp.replace(p)
+ return p
+
+
+def check_threejs_asset(ctx: RunContext, rel: str, pascal: str, *, timeout_s: float = 60.0,
+ expected_size_m: tuple[float, float, float] | None = None) -> AssetCheck:
+ """Import ``rel`` in node, call ``build<Pascal>(THREE, {})`` and inspect the group.
+
+ Never raises: an unavailable node runtime yields ``ran=False, ok=True`` so the
+ strategy falls back to "the scene build will catch it"."""
+ 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 codeverse.spatial.node import run_node
+
+ res = run_node(_checker_path(ctx), [path.resolve().as_uri(), f"build{pascal}"], 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),
+ 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
+
+
+def _soft_findings(chk: AssetCheck, expected: tuple[float, float, float] | None) -> 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 > ASSET_MAX_TRIS:
+ chk.errors.append(f"{chk.tris} triangles exceeds the {ASSET_MAX_TRIS} budget per asset — lower the segment counts")
+ if chk.meshes == 1 and chk.materials <= 1 and chk.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")
+
+
+# ----------------------------------------------------------------------------- dedupe
+#: head noun → canonical family (near-identical scene props collapse into one factory)
+_FAMILY = {
+ "rock": "rock", "boulder": "rock", "stone": "rock", "pebble": "rock", "rubble": "rock", "cobble": "rock",
+ "tree": "tree", "sapling": "tree", "pine": "tree", "conifer": "tree", "palm": "tree",
+ "bush": "bush", "shrub": "bush", "hedge": "bush", "scrub": "bush", "fern": "bush", "grass": "bush",
+ "planter": "planter", "pot": "planter", "urn": "planter", "trough": "planter", "tub": "planter",
+ "lamp": "lamp", "lantern": "lamp", "light": "lamp", "lightpost": "lamp", "sconce": "lamp",
+ "bench": "bench", "seat": "bench", "stool": "bench", "chair": "bench",
+ "crate": "crate", "box": "crate", "carton": "crate", "barrel": "crate",
+ "post": "post", "pole": "post", "pillar": "post", "column": "post", "bollard": "post", "stake": "post",
+ "fence": "fence", "railing": "fence", "rail": "fence", "balustrade": "fence",
+ "table": "table", "desk": "table",
+}
+
+
+def _family(name: str) -> str:
+ head = to_snake(name).split("_")[-1].rstrip("s") or to_snake(name)
+ return _FAMILY.get(head, head)
+
+
+def select_assets(assets: list[AssetPlan], cap: int) -> tuple[list[AssetPlan], dict[str, str]]:
+ """The assets to actually build, in plan (= priority) order, plus the merge map.
+
+ Dedupe is a *rescue*, not a default: while the plan fits under ``cap`` every planned
+ prop is built (single-shot assets are nearly free, and a distinct prop is worth more
+ than a variant flag). Only an over-long list is folded — turning "drop the 9th
+ asset" into "the 9th asset is a variant of the 3rd" — and whatever is still over the
+ cap is truncated by priority."""
+ alias: dict[str, str] = {}
+ if len(assets) > cap:
+ assets, alias = dedupe_assets(assets)
+ if len(assets) > cap:
+ kept = {a.name for a in assets[:cap]}
+ assets = assets[:cap]
+ alias = {k: v for k, v in alias.items() if v in kept}
+ return assets, alias
+
+
+def dedupe_assets(assets: list[AssetPlan]) -> tuple[list[AssetPlan], dict[str, str]]:
+ """Fold near-identical props into ONE parameterised factory.
+
+ Two assets merge when their head nouns belong to the same family AND their
+ largest dimensions are within 3× — "HeroBoulder" (2.5 m) and "TalusRock"
+ (0.5 m) are different props; "SteppingStone" and "PondRock" are one factory
+ with a variant. Plan order is priority: the first one survives.
+ Returns ``(kept_assets, {dropped_name: kept_name})``."""
+ kept: list[AssetPlan] = []
+ alias: dict[str, str] = {}
+ for a in assets:
+ fam = _family(a.name)
+ twin = next((k for k in kept if k.kind == a.kind and _family(k.name) == fam
+ and _ratio(max(k.approx_size_m), max(a.approx_size_m)) <= 3.0), None)
+ if twin is None:
+ kept.append(a)
+ continue
+ alias[a.name] = twin.name
+ if alias:
+ kept = [_with_variants(k, [n for n, t in alias.items() if t == k.name],
+ {n: a for n, a in ((x.name, x) for x in assets)}) for k in kept]
+ return kept, alias
+
+
+def _ratio(a: float, b: float) -> float:
+ lo, hi = sorted((abs(a) or 1e-6, abs(b) or 1e-6))
+ return hi / lo
+
+
+def _with_variants(asset: AssetPlan, dropped: list[str], by_name: dict[str, AssetPlan]) -> AssetPlan:
+ """Tell the kept asset it must also serve as its merged twins (opts.variant)."""
+ if not dropped:
+ return asset
+ lines = [f"variant {i + 1} = {n} ({by_name[n].description.strip()})" for i, n in enumerate(dropped) if n in by_name]
+ extra = (f" This ONE factory must also cover: {'; '.join(lines)}. Read `opts.variant` (integer, 0 = the base "
+ f"asset above, 1..{len(lines)} = the variants in that order) and `opts.scale` (number, default 1) and "
+ f"change proportions/detail/colour accordingly — zone code calls the same builder with different opts.")
+ return asset.model_copy(update={"description": asset.description.rstrip() + extra})
+
+
+def variant_index(alias: dict[str, str], name: str) -> int:
+ """1-based variant index of a merged asset within its surviving factory."""
+ kept = alias.get(name)
+ if not kept:
+ return 0
+ return sorted(n for n, t in alias.items() if t == kept).index(name) + 1
+
+
+def write_dedupe_note(ws: Workspace, alias: dict[str, str]) -> None:
+ """Persist the merge map next to the other stage artifacts (flywheel + debugging)."""
+ if alias:
+ write_json_atomic(ws.root / "stages" / "asset_aliases.json", {"alias": alias})
+
+
+def write_variant_shims(ws: Workspace, alias: dict[str, str], available: set[str]) -> list[str]:
+ """Replace a merged asset's skeleton stub with a shim onto the surviving factory.
+
+ Zone code is TOLD to call ``build<Kept>(THREE, {variant: n})``, but a zone that
+ imports the old name anyway must get the real prop, not the placeholder blockout
+ box the skeleton left behind."""
+ written: list[str] = []
+ for dropped, kept in sorted(alias.items()):
+ if kept not in available:
+ continue
+ rel = f"src/assets/{to_snake(dropped)}.js"
+ path = ws.root / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(
+ f"// {dropped} is a variant of {kept} (assets were merged into one factory).\n"
+ f"import {{ build{to_pascal(kept)} }} from './{to_snake(kept)}.js';\n\n"
+ f"export function build{to_pascal(dropped)}(THREE, opts = {{}}) {{\n"
+ f" return build{to_pascal(kept)}(THREE, {{ variant: {variant_index(alias, dropped)}, ...opts }});\n}}\n")
+ written.append(rel)
+ return written
+
+
+def asset_variant_call(kept: str, index: int) -> str:
+ """The call a zone should emit for a merged asset."""
+ return f"build{to_pascal(kept)}(THREE, {{ variant: {index} }})"
diff --git a/harness/codeverse/tracks/scene_assets.py b/harness/codeverse/tracks/scene_assets.py
index e5d5a196..19b6230e 100644
--- a/harness/codeverse/tracks/scene_assets.py
+++ b/harness/codeverse/tracks/scene_assets.py
@@ -1,12 +1,18 @@
-"""Scene asset stage: one generation task per asset, fanned out.
-
-* ``threejs`` assets → ``src/assets/<snake>.js`` exporting ``build<Pascal>``.
-* ``blender_glb`` assets → a sub-workspace under ``<ws>/_assets/<snake>`` runs
- the Blender runtime (skeleton → generate → build+repair) and the GLB is
- copied to ``public/assets/<snake>.glb``.
-
-Each asset is optionally judged with ``asset_v1`` on a quick 4-view sheet and
-gets at most ONE fix pass (cost target ≤ $2 / scene).
+"""Scene asset stage: cheap-first generation of one module per asset, fanned out.
+
+* ``threejs`` assets → ``src/assets/<snake>.js`` exporting ``build<Pascal>`` —
+ generated **single-shot** (one chat call) + a deterministic node check + ONE
+ error-feedback repair; a full agent session is the escalation, not the default
+ (see ``scene_asset_gen``: agent sessions cost 10× and 10 minutes per file).
+* ``blender_glb`` assets are **heroes**: a sub-workspace under ``<ws>/_assets/<snake>``
+ runs the Blender runtime (skeleton → generate → build+repair) with a real agent
+ session and the GLB is copied to ``public/assets/<snake>.glb``.
+
+Near-identical props are merged into one factory with an ``opts.variant``; the
+list is capped at ``MAX_ASSETS`` in plan (= priority) order, and harder when the
+soft budget is spent. Assets are judged only when the judge can tell us
+something the deterministic check cannot (heroes, or anything big enough to
+matter in frame).
"""
from __future__ import annotations
@@ -30,11 +36,26 @@ from codeverse.tracks.common import RunContext, language_contract, load_prompt_o
from codeverse.tracks.generation import GenerationTask, generate
from codeverse.tracks.prompting import base_prompt_context
from codeverse.tracks.repair import build_with_repair
+from codeverse.tracks.scene_asset_gen import (
+ AssetCheck,
+ check_threejs_asset,
+ repair_feedback,
+ select_assets,
+ single_shot_ctx,
+ variant_index,
+ write_dedupe_note,
+ write_variant_shims,
+)
from codeverse.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
+ASSET_AGENT_TIMEOUT_S = 420
ASSET_RUBRIC = "asset_v1"
@@ -47,6 +68,8 @@ class AssetResult(BaseModel):
score: float | None = None
fixed: bool = False
notes: str = ""
+ strategy: str = Field(default="", description="single-shot | single-shot+repair | agent | escalated")
+ judged: bool = False
def asset_file(asset: AssetPlan) -> str:
@@ -54,15 +77,23 @@ def asset_file(asset: AssetPlan) -> str:
return f"src/assets/{snake}.js" if asset.kind == "threejs" else f"public/assets/{snake}.glb"
-def asset_api_summary(plan: ScenePlan, results: dict[str, AssetResult]) -> str:
- """What zone/composer tasks need to know about each asset (names + sizes + how to get it)."""
+def asset_api_summary(plan: ScenePlan, results: dict[str, AssetResult], alias: dict[str, str] | None = None) -> str:
+ """What zone/composer tasks need to know about each asset (names + sizes + how to get it).
+
+ Merged assets (``alias``) point at the surviving factory and the ``opts.variant``
+ the zone must pass."""
+ alias = alias or {}
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)
+ kept = alias.get(a.name)
+ r = results.get(kept or a.name)
+ size = (r.size_m if r and r.size_m and not kept else a.approx_size_m)
s = f"{size[0]:.2f}×{size[1]:.2f}×{size[2]:.2f} m (w×h×d)"
status = "" if (r and r.ok) else " [NOT AVAILABLE — do not reference]"
- if a.kind == "threejs":
+ if kept:
+ lines.append(f"- {a.name}: use `build{to_pascal(kept)}(THREE, {{ variant: {variant_index(alias, a.name)} }})` "
+ f"from './assets/{to_snake(kept)}.js' (merged variant), base at y=0, {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:
lines.append(f"- {a.name}: GLB at `public/assets/{to_snake(a.name)}.glb` (load via loaders.gltf), base at y=0, {s}{status}")
@@ -72,10 +103,16 @@ def asset_api_summary(plan: ScenePlan, results: dict[str, AssetResult]) -> str:
def run_asset_stage(ctx: RunContext, *, judge_assets: bool = True) -> dict[str, AssetResult]:
"""Generate every asset (parallel) and return results keyed by asset name."""
plan: ScenePlan = ctx.plan # type: ignore[assignment]
- assets = list(plan.assets)
- if len(assets) > MAX_ASSETS:
- ctx.events.emit("assets.capped", n=len(assets), cap=MAX_ASSETS)
- assets = assets[:MAX_ASSETS]
+ cap = MAX_ASSETS if ctx.budget.soft_ok() else DEGRADED_MAX_ASSETS
+ planned = list(plan.assets)
+ assets, alias = select_assets(planned, cap)
+ if alias:
+ ctx.events.emit("assets.deduped", merged=alias, kept=[a.name for a in assets])
+ write_dedupe_note(ctx.ws, alias)
+ built = {a.name for a in assets} | set(alias)
+ if len(planned) > len(built):
+ ctx.events.emit("assets.capped", n=len(planned), cap=cap, dropped=[a.name for a in planned if a.name not in built])
+ ctx.extra["asset_alias"] = alias
if not assets:
return {}
_ignore_sub_workspaces(ctx.ws)
@@ -100,29 +137,78 @@ def run_asset_stage(ctx: RunContext, *, judge_assets: bool = True) -> dict[str,
ctx.events.emit("asset.failed", asset=asset.name, error=f"{type(r).__name__}: {r}")
else:
out[asset.name] = r
+ shims = write_variant_shims(ctx.ws, alias, {n for n, r in out.items() if r.ok})
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])
+ 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}, variant_shims=shims)
return out
# ----------------------------------------------------------------------------- threejs asset
def build_threejs_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> AssetResult:
- rel = asset_file(asset)
- task = GenerationTask(label=f"asset_{to_snake(asset.name)}", prompt=_asset_prompt(ctx, asset, rel, language=Language.SCENE_THREEJS),
- system="You write ONE self-contained three.js ESM asset module. Raw three.js only; no DOM; no texture loading.",
- files_hint=[rel], round=0, kind="asset", temperature=0.5)
- res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
- budget=ctx.budget, events=ctx.events)
- ok = res.ok and (ctx.ws.root / rel).is_file()
- result = AssetResult(name=asset.name, kind=asset.kind, ok=ok, path=rel if ok else "", notes=res.notes)
+ """Single-shot → deterministic check → ONE repair → (only then) an agent session."""
+ rel, pascal = asset_file(asset), to_pascal(asset.name)
+ sub = single_shot_ctx(ctx)
+ chk: AssetCheck | None = None
+ strategy, notes = "", ""
+ if sub is not None:
+ for attempt in range(2): # first shot + ONE error-feedback repair
+ try:
+ res = _generate_asset(sub, asset, rel, language=Language.SCENE_THREEJS, attempt=attempt,
+ feedback=repair_feedback(chk, rel) if chk is not None else "")
+ except Exception as e: # noqa: BLE001 — a model outage escalates, it does not lose the asset
+ from codeverse.orchestrator.budget import BudgetExceeded
+
+ if isinstance(e, BudgetExceeded):
+ raise
+ log.warning("single-shot asset %s failed: %s", asset.name, e)
+ ctx.events.emit("asset.generate_failed", asset=asset.name, attempt=attempt, 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]])
+ break
+ notes = res.notes
+ chk = (check_threejs_asset(ctx, rel, pascal, expected_size_m=asset.approx_size_m) 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" if attempt == 0 else "single-shot+repair"
+ break
+ if not strategy:
+ ctx.events.emit("asset.escalated", asset=asset.name, errors=(chk.errors[:3] if chk else []))
+ if not strategy: # no chat model, or single-shot failed twice → the full agent session
+ res = _generate_asset(ctx, asset, rel, language=Language.SCENE_THREEJS, attempt=0,
+ timeout_s=ctx.budget.timeout_s(ASSET_AGENT_TIMEOUT_S, floor_s=120))
+ notes = res.notes
+ strategy = "escalated" if chk is not None else "agent"
+ chk = check_threejs_asset(ctx, rel, pascal, expected_size_m=asset.approx_size_m) if res.ok else chk
+ # a module that will not import is NOT AVAILABLE to zones; a merely imperfect one
+ # (size off, still a bit plain) stays usable — we already spent a repair on it
+ 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 judge and callable(render_asset):
+ if ok and callable(render_asset) and _judge_wanted(ctx, asset, chk, judge=judge):
result = _judge_and_fix(ctx, asset, result, lambda out_dir: render_asset(ctx.ws, asset.name, out_dir), files=[rel],
language=Language.SCENE_THREEJS)
return result
-# ----------------------------------------------------------------------------- blender asset
+def _generate_asset(ctx: RunContext, asset: AssetPlan, rel: str, *, language: Language, attempt: int,
+ feedback: str = "", timeout_s: int | None = None) -> Any:
+ label = f"asset_{to_snake(asset.name)}" + ("_retry" if attempt else "")
+ prompt = _asset_prompt(ctx, asset, rel, language=language)
+ if feedback:
+ prompt = prompt + "\n\n" + feedback + "\n## Current file (rewrite it COMPLETELY)\n```\n" + _read(ctx.ws, rel, 24_000) + "\n```\n"
+ task = GenerationTask(label=label, prompt=prompt,
+ system=("You write ONE self-contained three.js ESM asset module. Raw three.js only; no DOM; no texture loading."
+ if language is Language.SCENE_THREEJS else
+ "You write ONE raw bpy script (src/model.py) that builds a single scene asset. No SDKs, no render/export calls."),
+ files_hint=[rel], round=attempt, kind="asset", temperature=0.5, timeout_s=timeout_s)
+ 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)
+
+
+# ----------------------------------------------------------------------------- blender asset (hero)
def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> AssetResult:
"""Sub-workspace → Blender runtime → GLB → public/assets/<snake>.glb."""
snake = to_snake(asset.name)
@@ -143,23 +229,20 @@ def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> As
ctx.services.materialize(sub_ws, agent_kind=kind, contract_md=sub.contract_text, cookbook_rel=sub.cookbook_rel,
spatial_tools=True,
mcp_command=["python", "-m", "codeverse.spatial.mcp_server", "--workspace", str(sub_ws.root)])
- task = GenerationTask(label=f"asset_{snake}", prompt=_asset_prompt(sub, asset, "src/model.py", language=Language.BLENDER),
- system="You write ONE raw bpy script (src/model.py) that builds a single scene asset. No SDKs, no render/export calls.",
- files_hint=["src/model.py"], round=0, kind="asset", temperature=0.5)
- res = generate(sub_ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
- budget=ctx.budget, events=ctx.events)
+ res = _generate_asset(sub, asset, "src/model.py", language=Language.BLENDER, attempt=0,
+ timeout_s=ctx.budget.timeout_s(ASSET_AGENT_TIMEOUT_S, floor_s=180))
if not res.ok:
- return AssetResult(name=asset.name, kind=asset.kind, ok=False, notes=f"generation failed: {res.notes}")
+ return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy="agent", notes=f"generation failed: {res.notes}")
sub_ws.commit("asset generated")
outcome = build_with_repair(sub, round_index=0, label=f"asset_{snake}", files_hint=["src/model.py"])
if not outcome.build.ok or not outcome.build.glb_path:
- return AssetResult(name=asset.name, kind=asset.kind, ok=False,
+ return AssetResult(name=asset.name, kind=asset.kind, ok=False, strategy="agent",
notes=f"build failed: {outcome.build.error_type}: {outcome.build.error_message[:200]}")
rel = asset_file(asset)
dest = _copy_glb(ctx.ws, Path(outcome.build.glb_path), rel)
size = _measure_size(ctx, dest)
- result = AssetResult(name=asset.name, kind=asset.kind, ok=True, path=rel, size_m=size)
- if judge:
+ result = AssetResult(name=asset.name, kind=asset.kind, ok=True, path=rel, size_m=size, strategy="agent")
+ if _judge_wanted(ctx, asset, None, judge=judge):
def _render(out_dir: Path):
return ctx.services.render_object(dest, out_dir, views=OBJECT_VIEWS_QUICK, width=512, height=512)
@@ -186,9 +269,44 @@ def asset_plan(asset: AssetPlan) -> StaticPlan:
# ----------------------------------------------------------------------------- judge + fix
+def _judge_wanted(ctx: RunContext, asset: AssetPlan, chk: AssetCheck | None, *, judge: bool) -> bool:
+ """Stop paying for what is already good.
+
+ A VLM verdict on a 0.3 m pebble that already passed the deterministic check
+ tells us nothing the scene judge will not see anyway. Heroes (blender_glb)
+ and anything big enough to dominate a frame keep their verdict."""
+ 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)
+ if chk is not None and chk.ok and chk.ran and frac < JUDGE_VOLUME_FRACTION:
+ 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 _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: Any | None = None, parent_events: Any | None = None) -> AssetResult:
- """Quick-sheet judge with asset_v1; ONE fix pass when below threshold."""
+ """Quick-sheet judge with asset_v1 (n_samples=1, cached renders); ONE fix pass when below threshold."""
from codeverse.judges.base import JudgeInput
events = parent_events or ctx.events
@@ -209,6 +327,7 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
return result
ctx.budget.charge(verdict.usage)
result.score = verdict.overall
+ result.judged = True
events.emit("asset.judged", asset=asset.name, score=round(verdict.overall, 3), passed=verdict.passed)
if verdict.passed or not verdict.improvement_plan:
return result
@@ -218,7 +337,7 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rende
asset_size=asset.approx_size_m, asset_file=files[0], asset_language=language.value, fix_instructions=instructions,
current_code=_read(ctx.ws, files[0]) if ctx.single_shot else ""))
task = GenerationTask(label=f"asset_{to_snake(asset.name)}_fix", prompt=prompt, files_hint=files, round=1, kind="asset_fix",
- temperature=0.4)
+ temperature=0.4, timeout_s=ctx.budget.timeout_s(ASSET_AGENT_TIMEOUT_S, floor_s=120))
res = generate(ctx.ws, agent_id=ctx.agent_id, task=task, agent=ctx.agent, model=ctx.model, settings=ctx.settings,
budget=ctx.budget, events=ctx.events)
if res.ok:
diff --git a/harness/codeverse/workspace.py b/harness/codeverse/workspace.py
index e35a6e79..37ea8df8 100644
--- a/harness/codeverse/workspace.py
+++ b/harness/codeverse/workspace.py
@@ -9,6 +9,7 @@ flywheel can replay any round.
from __future__ import annotations
import json
+import os
import shutil
import subprocess
import threading
@@ -21,7 +22,36 @@ from pydantic import BaseModel
from codeverse.contracts.agent import FileChange
from codeverse.proc import write_json_atomic
-_DIRS = ("src", "public", "artifacts", "artifacts/renders", "artifacts/gates", "artifacts/judge", "trajectories")
+#: the three top-level buckets of a run directory (docs/RUN_LAYOUT.md)
+DELIVERABLE_DIR = "deliverable" # (a) what the user asked for
+EVIDENCE_DIR = "evidence" # (b) why we believe it is good (alias of artifacts/)
+TELEMETRY_DIR = "telemetry" # (c) what it cost and how it was configured
+
+#: physical directories every run owns. ``artifacts/`` is the physical home of the
+#: evidence (six packages and ~50 recorded runs write paths into it); ``evidence/``
+#: is an alias for it — see docs/RUN_LAYOUT.md for why the alias points that way.
+LAYOUT_DIRS = ("src", "public", "artifacts", "artifacts/renders", "artifacts/gates", "artifacts/judge",
+ "trajectories", DELIVERABLE_DIR, TELEMETRY_DIR)
+
+#: navigation aliases: ``alias path`` → ``symlink target`` (relative to the alias's parent).
+#: The alias is always the symlink, never the physical file: writers (events.jsonl append,
+#: atomic run_state.json rewrite) keep using the paths they already use, and a tmp+rename
+#: on the physical path can never replace a symlink out from under a reader.
+LAYOUT_ALIASES: tuple[tuple[str, str], ...] = (
+ (EVIDENCE_DIR, "artifacts"),
+ (f"{TELEMETRY_DIR}/events.jsonl", "../events.jsonl"),
+ (f"{TELEMETRY_DIR}/run_state.json", "../run_state.json"),
+ (f"{TELEMETRY_DIR}/stages", "../stages"),
+ (f"{TELEMETRY_DIR}/trajectories", "../trajectories"),
+)
+
+#: 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/", ".3dcv/", ".gemini/", ".claude/",
+ "deliverable/", "telemetry/", "evidence", "captions.json",
+ "events.jsonl", "run_state.json", "record.json", "*.log", "node_modules/", "*.tmp", "__pycache__/",
+)
class Workspace:
@@ -47,6 +77,41 @@ class Workspace:
def trajectories(self) -> Path:
return self.root / "trajectories"
+ @property
+ def deliverable(self) -> Path:
+ """(a) the hand-over folder: best-round code + canonical artifact + sheet + captions."""
+ return self.root / DELIVERABLE_DIR
+
+ @property
+ def evidence(self) -> Path:
+ """(b) renders / gates / judge / measurements — the alias name for ``artifacts/``."""
+ return self.root / EVIDENCE_DIR
+
+ @property
+ def telemetry(self) -> Path:
+ """(c) cost ledger, per-call usage rows, resolved settings, stages, trajectories."""
+ return self.root / TELEMETRY_DIR
+
+ @property
+ def cost_path(self) -> Path:
+ return self.telemetry / "cost.json"
+
+ @property
+ def usage_path(self) -> Path:
+ return self.telemetry / "usage.jsonl"
+
+ @property
+ def settings_path(self) -> Path:
+ return self.telemetry / "settings.json"
+
+ @property
+ def deliverable_manifest_path(self) -> Path:
+ return self.deliverable / "manifest.json"
+
+ @property
+ def stages(self) -> Path:
+ return self.root / "stages"
+
def renders_dir(self, round_index: int) -> Path:
return self.artifacts / "renders" / f"r{round_index:02d}"
@@ -83,11 +148,48 @@ class Workspace:
# ----------------------------------------------------------------- lifecycle
def create(self) -> Workspace:
- for d in _DIRS:
- (self.root / d).mkdir(parents=True, exist_ok=True)
+ self.ensure_layout()
self._git_init()
return self
+ def ensure_layout(self, *, dry_run: bool = False) -> dict[str, str]:
+ """Create the directory buckets + navigation aliases. Idempotent, never
+ destructive: an alias path that already holds real data is left alone.
+
+ Returns ``{path: action}`` with action in ``created`` / ``relinked`` /
+ ``kept`` / ``skipped:<reason>`` — the migration helper prints it.
+ ``dry_run`` reports the same actions without touching the filesystem."""
+ actions: dict[str, str] = {}
+ for d in LAYOUT_DIRS:
+ p = self.root / d
+ if not p.exists():
+ if not dry_run:
+ p.mkdir(parents=True, exist_ok=True)
+ actions[d] = "created"
+ for name, target in LAYOUT_ALIASES:
+ actions.update(self._ensure_alias(name, target, dry_run=dry_run))
+ return actions
+
+ def _ensure_alias(self, name: str, target: str, *, dry_run: bool = False) -> dict[str, str]:
+ link = self.root / name
+ if link.is_symlink():
+ if os.readlink(link) == target:
+ return {}
+ if not dry_run:
+ link.unlink()
+ os.symlink(target, link)
+ return {name: "relinked"}
+ if link.exists(): # a real file/dir sits there — never clobber run data
+ return {name: "kept"}
+ if dry_run:
+ return {name: "created"}
+ link.parent.mkdir(parents=True, exist_ok=True)
+ try:
+ os.symlink(target, link)
+ except OSError as e: # filesystem without symlinks (some Windows shares)
+ return {name: f"skipped:{type(e).__name__}"}
+ return {name: "created"}
+
def exists(self) -> bool:
return self.spec_path.is_file()
@@ -132,14 +234,24 @@ class Workspace:
if (self.root / ".git").exists():
return
self._git("init", "-q")
- (self.root / ".gitignore").write_text(
- "# harness-owned run state is never part of the code snapshot\n"
- "artifacts/\ntrajectories/\nstages/\nrounds/\n_assets/\n.3dcv/\n.gemini/\n.claude/\n"
- "events.jsonl\nrun_state.json\nrecord.json\n*.log\nnode_modules/\n*.tmp\n__pycache__/\n"
- )
+ self.ensure_gitignore()
self._git("add", "-A")
self._git("commit", "-q", "-m", "init", "--allow-empty")
+ def ensure_gitignore(self, *, dry_run: bool = False) -> bool:
+ """Make sure every harness-owned path is ignored by the run's git repo.
+ Idempotent: missing lines are appended, existing ones are left in place.
+ Returns True when the file changed."""
+ path = self.root / ".gitignore"
+ existing = path.read_text().splitlines() if path.is_file() else []
+ have = {line.strip() for line in existing}
+ missing = [line for line in _GITIGNORE_LINES if line not in have]
+ if not missing or dry_run:
+ return bool(missing)
+ 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:
"""Commit everything tracked (src/, public/, plan, ...) and return the sha."""
self._git("add", "-A")
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
new file mode 100644
index 00000000..cc8deff8
--- /dev/null
+++ b/harness/docs/COST.md
@@ -0,0 +1,363 @@
+# Cost audit — where the money actually goes
+
+Measured on **61 recorded runs** (`runs/e2e_*` ×5, `bench/out/{static_v1_flash,
+articulated_v1_flash,graphics_v1_flash,scenes_v1_flash}` ×46, the 10 cells of
+`bench/out/compare_v1_live2`) on 2026-08-23. Every number below comes from the
+recorded telemetry, not from an estimate: `record.json`, `events.jsonl` and the
+per-call `usage` rows inside `trajectories/*/transcript.jsonl`.
+
+Reproduce:
+
+```
+3dcv cost show runs bench/out/static_v1_flash … # console
+3dcv cost show runs bench/out/* --md docs/cost_report.md # full tables
+3dcv cost show runs --recheck # re-price with today's table
+3dcv cost prices [--unverified] # the price table + provenance
+python bench/cost_report.py bench/out/<battery> # writes <battery>/cost_report.md
+```
+
+The audit is `codeverse/cost/audit.py`; it reconstructs a per-call ledger from
+old runs (`codeverse/cost/reconstruct.py`), so it works on every run recorded so
+far — no re-instrumentation needed. `bench/out/compare_v1_full` (a partial,
+superseded compare battery) is excluded.
+
+---
+
+## 1. Headline
+
+| | |
+|---|---|
+| total spend | **$89.88** over 61 runs (26.4 h of run time, 7,558 model calls) |
+| per run | $1.47 (median $0.95) |
+| **per passing artifact** | **$2.50** — 36 of 61 runs passed |
+| input tokens | 278.6M, of which **80% are cache reads** |
+| output tokens | 3.94M (+0.66M thoughts) |
+| generation : judging : planning | **90.3% : 7.2% : 0.8%** |
+| identified waste | **$27.35 (30%)** — see §5 |
+| recorded vs measured | `record.total_usage` says $85.08; the ledger finds **$89.88** (§6) |
+| re-priced with the corrected table | **$92.67** (+3.1%, §7) |
+
+**The money is generation, not judging.** Nine dollars in ten are the coding
+agent writing and rewriting code; the judge is a rounding error next to it
+(7.2%), the planner is noise (0.8%). Any cost programme that starts with "use a
+cheaper judge" is optimising 7% of the bill — and, as §8 shows, would lose money.
+
+---
+
+## 2. Per stage
+
+| key | USD | share | calls | input | cached | output | $/1k tok | model time |
+|---|---|---|---|---|---|---|---|---|
+| plan | $0.7234 | 0.8% | 56 | (not recorded) | – | – | – | 0.0 h |
+| assets (scene) | $5.61 | 6.2% | 587 | 13.24M | 61% | 236.8k | $0.00041 | 1.0 h |
+| env (scene) | $0.7762 | 0.9% | 92 | 1.96M | 62% | 19.1k | $0.00039 | 0.1 h |
+| zones (scene) | $4.75 | 5.3% | 452 | 15.55M | 76% | 140.8k | $0.00030 | 0.7 h |
+| baseline | $25.76 | 28.7% | 1,815 | 86.76M | 85% | 1.39M | $0.00029 | 4.0 h |
+| repair | $1.31 | 1.5% | 152 | 5.08M | 79% | 49.9k | $0.00026 | 0.2 h |
+| **refine** | **$42.94** | **47.8%** | 4,243 | 154.50M | 80% | 1.82M | $0.00027 | 8.4 h |
+| judge | $6.48 | 7.2% | 126 | 1.33M | 8% | 212.1k | $0.00383 | 1.2 h |
+| texture | $1.10 | 1.2% | 16 | (event only) | – | – | – | 0.0 h |
+| other / unattributed | $0.43 | 0.5% | 19 | 235.2k | 10% | 67.3k | $0.00142 | 0.0 h |
+
+`skeleton`, `assemble`, `gates` and `render` cost **$0.00**: they are
+deterministic harness work. Blender build 0.13 s, gates ~2 s, an 8-view GPU
+render ~1.5 s — the "cheap first" law is holding.
+
+## 3. Per role, track, backend, model
+
+| role | USD | share | calls | $/1k tokens |
+|---|---|---|---|---|
+| generator | $81.14 | 90.3% | 7,341 | $0.00029 |
+| judge | $6.48 | 7.2% | 126 | $0.00383 |
+| planner | $0.72 | 0.8% | 56 | – |
+| image (texturing) | $0.61 | 0.7% | 5 | – |
+
+| track | runs | USD | $/run | passed | **$/passing artifact** | median rounds |
+|---|---|---|---|---|---|---|
+| static_object | 37 | $55.95 | $1.51 | 23 | **$2.43** | 2 |
+| articulated_object | 13 | $19.19 | $1.48 | 8 | **$2.40** | 2 |
+| scene | 5 | $14.14 | $2.83 | **0** | **∞** | 2 |
+| graphics | 6 | $0.59 | $0.10 | 5 | **$0.12** | 1 |
+
+The graphics track is **20x cheaper per passing artifact** than the object
+tracks (one single-shot generation, compiler feedback, no tool loop). The scene
+track has not produced a single passing artifact in this data set at $2.83/run.
+
+| model | USD | share | calls | cached | note |
+|---|---|---|---|---|---|
+| gemini-3.7-flash | $74.08 | 82.4% | 7,400 | 80% | generator + planner + cheap judge |
+| gemini-3.1-pro-preview | $6.23 | 6.9% | 109 | 7% | default judge |
+| (event-only rows) | $5.40 | 6.0% | 44 | – | plan / texture / pairwise: cost recorded, tokens not |
+| gpt-5.6-sol (codex) | $2.26 | 2.5% | 3 | 92% | one telescope run |
+| claude-fable-5 (claude-code) | $1.90 | 2.1% | 2 | 0% | recorded as `claude-haiku-4-5` — see §7 |
+
+## 4. Tokens, caching and the clock
+
+**80% of every prompt is context we have already sent.** 259.8M of the agent
+loop's input tokens correspond to only 13.3M tokens of *final* context — the
+transcript is re-sent **19.5x** on average (median 22 model turns per session,
+p90 52). Implicit caching absorbs most of that: cache reads cost $16.98, and
+the same traffic with a 0% hit rate would have cost **$242.70 instead of $89.88**.
+Caching is already saving 63% of the bill.
+
+The uncached remainder is still ~$40 of that traffic, and the bill grows
+quadratically with session length (the 262 agent sessions that kept a per-turn
+transcript — $69.1 of the $81.1 generator spend):
+
+| model turns | USD | share of agent spend |
+|---|---|---|
+| 1–10 | $23.70 | 34.3% |
+| 11–20 | $18.26 | 26.4% |
+| 21–30 | $11.76 | 17.0% |
+| 31–40 | $7.65 | 11.1% |
+| 41–50 | $4.81 | 7.0% |
+| 51–60 | $2.90 | 4.2% |
+
+**39.3% of the agent bill is spent from turn 20 onwards.** 33 sessions ran ≥50
+model turns for $19.57 — and 19 of those 33 ended `exit_reason="budget"`, i.e.
+the money bought a session that was cut off rather than finished.
+
+**Measured cache behaviour (live, gemini-3.7-flash, 2026-08-23)** — the same
+content in two orders, 6 calls each, one key:
+
+| arrangement | prompt | cached tokens | $/call |
+|---|---|---|---|
+| stable prefix first, volatile tail last | 17.8k | 0 → **12,265 (69%)** | $0.0144 → **$0.0052** |
+| volatile first, same stable text after | 17.8k | **0 on every call** | $0.0134 |
+| stable first, fresh 29.7k corpus | 29.7k | 0 → **24,549 (83%)**, one miss in four | $0.0223 → **$0.0057** |
+| volatile first, fresh 29.7k corpus | 29.7k | **0 on all four calls** | $0.0223 |
+
+Same tokens, same model, **2.6–3.9x the price** for the wrong order (and the
+implicit cache is best-effort: one call in four missed even in the good arm). A second
+experiment sized the cache floor (fresh prefix per size, 3 calls each):
+
+| repeated prefix | cached on call 2–3 |
+|---|---|
+| 2.8k tokens | 0 |
+| 5.4k tokens | 0 |
+| 8.2k tokens | 4,080 once, then 0 (unreliable) |
+| 11.1k tokens | 0 |
+| 16.8k tokens | 12,264 (73%) |
+| 28.2k tokens | 24,548 (87%) |
+
+Implicit caching works in ~4,088-token blocks and only becomes reliable above
+~12–16k tokens of *identical* prefix. Key rotation does **not** break it (all 22
+keys share the cache).
+
+A third experiment used a **real judge payload** — `build_judge_messages` on
+`e2e_chair_blender` r01 (9,454 tokens: system + brief + plan + gates + three
+montages), sent to `gemini-3.1-pro-preview`:
+
+| judge call | cached | $/call |
+|---|---|---|
+| first send | 0 | $0.0333 |
+| identical resend (×2) | **4,079 (43%)** | **$0.0259 (−22%)** |
+| same content, montages shuffled — what `n_samples > 1` does today (×3) | **0** | $0.0333 |
+| next round (same images, changed gate/measurement text) | **0** | $0.0333 |
+
+So: the judge's stable head (system + rubric + defect checklist ≈ 3.5k) is just
+under one cache block, and every per-round or per-sample difference sits early
+enough to void it. Consequences:
+
+* the agent loop already sits far above the floor — that is why it gets 80%;
+* **judge and plan calls get almost nothing** (7% measured over 112 real
+ verdicts). Two cheap fixes exist (§9 #11–12), worth ~$1 on this data set —
+ the real lever on judging is *how many verdicts*, not *how cheap each prompt*.
+
+**Clock.** 26.4 h of run time against 35.5 h of model time (fan-out rounds run
+sessions in parallel). On the 37 runs with no parallel fan-out the split is 9.04 h wall vs 7.94 h
+model — **88% of the clock is waiting for a model**, 12% is the harness
+(build + gates + render + git). Cost and latency have the same owner.
+
+## 5. Where a dollar bought nothing
+
+| waste | n | USD | share |
+|---|---|---|---|
+| regression — a round scored **below** the best and was discarded | 19 | $14.23 | 15.8% |
+| post-budget — a round completed after the budget was already gone | 9 | $8.76 | 9.7% |
+| zero-delta round — score moved < 0.005 | 4 | $1.68 | 1.9% |
+| unpromoted judge — a verdict on a round that never became best | 23 | $1.37 | 1.5% |
+| repair loop that never converged (run did not pass) | 4 | $1.31 | 1.5% |
+| **total** | 59 | **$27.35** | **30.4%** |
+
+Concrete examples:
+
+* `tool_med_hand_drill` r01: **$2.48** to go from 0.576 to **0.560**.
+* `plant_hard_bonsai` r01: **$2.36** to go from 0.384 to **0.134**, then r02
+ spent another $1.29 *after* the budget was exhausted.
+* `tool_hard_bench_vise` r02: **$2.02** spent on a round that started after
+ `budget.exceeded` had already fired.
+
+Marginal economics of a refine round:
+
+| round | n | USD | median $ | rounds that improved | total score gained | **$ per score point** |
+|---|---|---|---|---|---|---|
+| r00 baseline | 54 | $35.58 | $0.557 | – | – | – |
+| r01 | 33 | $20.99 | $0.475 | 22/33 | +4.26 | **$4.93** |
+| r02 | 16 | $9.18 | $0.383 | 7/16 | +1.35 | **$6.80** |
+| r03 | 4 | $2.98 | $0.569 | 1/4 | +0.09 | **$33.49** |
+
+The first refine round is the good buy. r02 is a coin flip; r03 costs 7x r01
+per point of score.
+
+## 6. $4.80 of spend is invisible to `record.total_usage`
+
+On 14 of 61 runs the reconstructed ledger is **larger** than the run's own
+`total_usage` — $4.80 (5.6% of all spend) that the record, and therefore the
+`BudgetGuard`, never saw:
+
+* rounds the budget cut *after* the work was done (the round is not appended to
+ `record.rounds`, and its cost is not folded into the total);
+* retried agent sessions (`<label>.a2_rNN`) whose usage lands in the trajectory
+ but not in the round;
+* post-hoc texture passes (`furn_hard_rolltop_desk` ran four, $0.656).
+
+Worst case: `art_hard_door_handle`, $1.38 off-record on a $4.45 run.
+
+## 7. Price hygiene (checked 2026-08-23)
+
+`models/pricing.py` now carries a `PROVENANCE` row per price — source URL,
+`checked` date and a status of `verified` / `inferred` / `unverified` — exposed
+as `price_provenance(provider, model)` and printed by `3dcv cost prices`. Every
+row was reconciled against the providers' live pricing pages. **Corrections
+made:**
+
+| row | was | is | effect |
+|---|---|---|---|
+| `anthropic:claude-sonnet-5` | 3.00 / 15.00 / 0.30 | **2.00 / 10.00 / 0.20** | we were over-billing sonnet-5 by 50% (the launch rate became standard) |
+| `openai:gpt-5.6-sol` | 5.00 / 30.00 / 0.50 (approx) | **4.00 / 20.00 / 0.40** | the one codex run drops $1.86 → $1.42 |
+| `gemini:gemini-3.1-flash-image` | 0.25 / 1.50 / 0.025 | **0.50 / 3.00 / 0.05 + $0.067 per 1K image** | image output is billed per image ($60/M image tokens), not as text |
+| `gemini:gemini-2.5-flash` cached | 0.075 | **0.03** | 2.5x over-billing on cache reads |
+| `gemini:gemini-2.5-flash-lite` cached | 0.025 | **0.01** | idem |
+| `gemini:gemini-3.1-pro-preview`, `gemini-3-pro-preview`, `gemini-2.5-pro` | one tier | **+ >200k tier** (4.00 / 18.00 / 0.40) | `estimate_cost` now applies the long-context tier automatically |
+| added | – | `claude-haiku-3-5`, `claude-mythos-5` | were unknown ⇒ silently $0 |
+| verified (no change) | – | every other gemini / anthropic / openai row | now flagged `verified` rather than "approximate" |
+| still `inferred` / `unverified` | – | `claude-haiku-4`, `o1-mini`, `gpt-5-codex`, `gpt-5.1-codex`, `gpt-5.2-codex`, `gemini-2.5-flash-image` | not listed on the pricing pages; `3dcv cost prices --unverified` lists them |
+
+Per-image prices now live in the price table (`Price.image_usd`,
+`IMAGE_USD_BY_SIZE`, `per_image_usd()`), and a test asserts they never drift from
+`models/gemini_image.IMAGE_USD`.
+
+**Two costing bugs the audit surfaced** (both in files owned by other engineers —
+see the hand-off notes):
+
+1. **gemini-cli runs were under-billed ~3.7x.** `e2e_bench_threejs` recorded
+ $0.68; its own `stdout.json` stats say 14.19M prompt tokens (13.47M cached) +
+ 128.8k output ⇒ **$2.09**. The session was recorded before
+ `Usage.input_tokens` became `tokens.prompt`; the raw envelope is still on
+ disk, so `3dcv cost show --recheck` rebuilds the true number. Across the
+ three gemini-cli runs the correction is **+$3.43**.
+2. **claude-code attributes the cost to the wrong model.** The envelope's
+ `modelUsage` shows `claude-fable-5` did the work ($1.165) and
+ `claude-haiku-4-5` answered one utility call ($0.0015); the harness records
+ the *first* served model, so the run is filed as haiku with
+ `input_tokens=2`. The dollar is right (the CLI reports `total_cost_usd`), the
+ attribution is not. Rows from such backends are marked
+ `price_source="provider-reported"` and are never re-priced from the token
+ table.
+
+Re-pricing everything with the corrected table moves the total from $89.88 to
+**$92.67 (+3.1%)**: +$3.43 gemini-cli, −$0.50 codex, −$0.13 elsewhere.
+
+**Not modelled** (documented in `pricing.py`): cache *storage* fees for explicit
+Gemini caching, Anthropic 1-hour cache writes, batch/flex discounts, data
+residency (1.1x) and fast-mode multipliers, per-search server-tool fees.
+
+## 8. Model routing — what to run where
+
+| role | model | $/call | measured quality | when |
+|---|---|---|---|---|
+| planner | `gemini:gemini-3.7-flash` ★ | $0.013 | no failure attributable to the planner | always — the plan is 0.8% of a run |
+| generator | `api-agent:gemini:gemini-3.7-flash` ★ | $0.52 | compare_v1 mean 0.835 (best arm) | default for every track with tools |
+| generator | `single-shot:gemini:gemini-3.7-flash` | $0.05 | graphics: 5/6 passed, median 0.810 | glsl / opengl — one file, compiler feedback |
+| generator | `gemini-cli:gemini-3.7-flash` | $0.73 | 0.827 — same as api-agent, 2x price, 2x wall | only when you need the CLI itself |
+| generator | `codex:gpt-5.6-sol` | $1.93 in-loop / $0.20 one-shot | one-shot 0.786 | strong one-shot baseline, expensive loop |
+| generator | `oneshot:claude-code` | $1.04 | 0.673, 0/2 passed | not for bulk generation |
+| judge | `gemini:gemini-3.1-pro-preview` ★ | $0.060 | σ 0.030, pearson(gate errors, score) **+0.63** | every decision that persists |
+| judge | `gemini:gemini-3.7-flash` | $0.027 | σ 0.083, pearson **−0.33** | in-loop hints only |
+| image | `gemini:gemini-3.1-flash-image` ★ | $0.067/tile | a texture pass ≈ $0.13 | only behind the before/after gate |
+
+**When does the pro judge pay for itself?** Flash is 2.2x cheaper per verdict,
+but its noise is 2.8x larger. Matching pro's σ = 0.030 by sampling flash needs
+`(0.083/0.030)² = 8` samples = **$0.216 per verdict, 3.6x the price of one pro
+verdict** — and sampling still cannot fix the sign of flash's correlation with
+the deterministic gates (−0.33 vs +0.63), so a flash ranking stays biased no
+matter how many samples you buy. Pro is the cheap option for anything that
+persists. Concretely, the 112 verdicts in this data set cost $6.48 with the pro
+judge and would cost $24.2 as "cheap" flash at n=8.
+
+`codeverse/cost/routing.py` holds this table in code
+(`default_route(Role.JUDGE)`, `pro_break_even()`, `samples_for_precision()`).
+
+## 9. Ranked optimisation opportunities
+
+Savings are estimated **on this data set** (61 runs, $89.88) unless stated.
+
+| # | change | est. saving | confidence | where |
+|---|---|---|---|---|
+| 1 | **Stop refining after r01 unless the last delta ≥ 0.05.** r02+r03 cost $12.16 and bought +1.44 score points across 8 of 20 rounds. | **$9–12 (10–13%)** | high (measured) | `RoundPolicy` (min_delta 0.02 → 0.05 from r02, or plateau_window 1 after r01) |
+| 2 | **Check the budget *before* starting a round, against the estimated round cost**, not only between steps. | **$8.76 (9.7%)** | high (measured waste) | `orchestrator/budget.py` + `tracks/steps.py`; use `codeverse.cost.estimate_call` / median round cost |
+| 3 | **Cap agent turns at ~25 and compact old tool results.** 39.3% of the agent bill is turn ≥20; 19 of the 33 sessions that ran ≥50 turns were cut off by their own budget. | **$8–15 (9–17%)**, needs a quality check | medium | `AgentJob.max_turns`, `api_agent` transcript compaction |
+| 4 | **Fold the off-record spend into the budget** (retried sessions, cut rounds, texture passes). | $0 saved, **$4.80 of blindness removed** | high | §6; the ledger (`codeverse.cost.record_call`) makes it automatic |
+| 5 | **Scene track: 73% of scene spend is assets+zones, 0/5 passed.** Trim the per-zone context (each zone session re-sends the whole scene contract) and judge assets before zones start. | ~$1/run of $2.83 | medium | `tracks/scene*.py` |
+| 6 | **Drop `oneshot:claude-code` from default compare arms** ($1.04/artifact at 0.673 — the worst score per dollar measured). | bench-only | high | `bench/compare_backends.py` arms |
+| 7 | **Gate the texture pass on the materials criterion** (< 0.7) — 5 passes ran, 2 shipped, $1.10 spent. | ~$0.5 | medium | `texturing/run.py` |
+| 8 | **Keep the pro judge; do not "save" money there** (§8). | avoids a **$45** increase | high | – |
+| 9 | **Price-table corrections** (§7) — accuracy, not savings: the reported bill was 3.1% low overall and 3.7x low on gemini-cli runs. | – | done | `models/pricing.py` |
+| 10 | **Do not chase prompt caching on judge/plan calls in general** — measured below the cache floor (§4). | – | done (measured) | – |
+| 11 | **Grow the judge's stable head past one cache block** (system + rubric + defect checklist ≈ 3.5k → ≥ 4,088 tokens, e.g. by moving the shared scoring rules and a fixed worked example into the system block). Measured: one cached block = 4,079 tokens = $0.0073 per pro verdict. | ~$0.8 (112 verdicts) | medium | `judges/prompt_builder.py` |
+| 12 | **Know that `n_samples > 1` pays full price for every sample**: the montage shuffle voids the cache (measured 0 cached vs 4,079 on an identical resend, −22%/sample). Keep the shuffle — it is the noise control — but count it when choosing `n`. | – | measured | `judges/prompt_builder.py` |
+
+Not recommended on the evidence: cheaper generation models (a bare one-shot
+flash scored 0.14 and produced no buildable code in 3 of 5 cells — the loop, not
+the model, is what makes the artifact), and cheaper judges (§8).
+
+## 10. The cost ledger (`codeverse/cost/`)
+
+```python
+from codeverse.cost import record_call, load_ledger, summarise
+
+record_call(res.usage, run=ws.slug, round=idx, stage="refine", role="generator",
+ label=job.label, outcome=res.exit_reason,
+ ledger=ws.root / "cost_ledger.jsonl") # one append-only JSONL row
+
+rows = load_ledger(ws.root / "cost_ledger.jsonl")
+summarise(rows).dimension("stage")["judge"].cost_usd
+```
+
+One row per call: `ts, run, round, stage, role, backend, provider, model,
+input/cached/output/thoughts tokens, cache_write, tool_calls, the three unit
+prices actually used, price_source + price_approximate + price_checked
+(provenance), cost_usd, recorded_usd, latency_ms, cache_hit, outcome, n_calls,
+source`. Writing never raises and never blocks a run; unknown models are
+recorded at $0 **and flagged**, never silently dropped.
+
+Until the call sites are wired, `codeverse.cost.reconstruct` rebuilds the same
+rows from `record.json` + `events.jsonl` + `trajectories/**` — that is what this
+audit runs on, and it reconciles to `record.total_usage` on every run (or says
+why it does not, §6).
+
+Two helpers exist for the callers:
+
+* `estimate_call(model_id, prompt=…, n_images=…, output_tokens=…)` →
+ `CostEstimate` before the call; `CostGuard(budget_usd).check(est)` decides.
+ An unpriceable model is **allowed but flagged** — refusing to run because we
+ cannot price something would be worse than running it.
+* `Block(...)` + `order_blocks(...)` + `prefix_signature(...)` for cache-friendly
+ prompt assembly, and `prefix_report(prompts)` to measure whether a family of
+ prompts really shares a prefix (§4).
+
+## 11. Caveats
+
+* `plan`, `texture` and `pairwise` costs come from events that record a dollar
+ but no tokens, so those rows have no token composition ($6.13 of $89.88).
+ Wiring `record_call` at those call sites fixes it.
+* Wall clock per run is the sum of the stage/round clocks (the event span
+ includes hours a bench run spent queued behind other runs, and
+ `budget.elapsed_min` restarts on `3dcv resume`).
+* "Regression" waste is an upper bound: a round that scored worse still produced
+ the diff that informed the next refine task.
+* The compare battery is only 2 prompts × 5 arms; its per-arm numbers are
+ directional, not significant.
+* Prices were read from the providers' public pages on 2026-08-23 and are the
+ standard, non-batch, global-endpoint tiers.
diff --git a/harness/docs/RUN_LAYOUT.md b/harness/docs/RUN_LAYOUT.md
new file mode 100644
index 00000000..22bec101
--- /dev/null
+++ b/harness/docs/RUN_LAYOUT.md
@@ -0,0 +1,175 @@
+# Run directory layout
+
+One run = one directory (`runs/<slug>/`, `bench/out/<battery>/runs/<slug>/`).
+It answers three different questions, and since 2026-08-23 it keeps them in
+three separate buckets:
+
+| bucket | question | contents |
+|---|---|---|
+| `deliverable/` | **what did I get?** | the code snapshot of the best round, the canonical artifact (`object.glb` / `robot.urdf` + `meshes/` / `frames/` + `preview.gif` / the scene bundle), the best contact sheet, `captions.json`, `manifest.json` |
+| `evidence/` (= `artifacts/`) | **why should I believe it?** | `renders/rNN/`, `gates/rNN/`, `judge/rNN.json`, `measurement.json`, `articulation.json`, `census.json`, `textures/`, `tool_renders/` |
+| `telemetry/` | **what did it cost and how was it configured?** | `settings.json`, `cost.json`, `usage.jsonl`, plus `events.jsonl`, `run_state.json`, `stages/`, `trajectories/` |
+
+The run's **identity** stays at the root, where every tool has always looked for it:
+
+```
+runs/<slug>/
+ spec.json plan.json record.json identity: what was asked, planned, produced
+ run_state.json events.jsonl (physical home; also linked from telemetry/)
+ src/ live working tree (git; every round is a commit)
+ public/ (scene) compiled assets
+ deliverable/ (a) the hand-over
+ evidence/ -> artifacts/ (b) the proof
+ artifacts/ renders/ gates/ judge/ measurement.json …
+ telemetry/ (c) the accounting
+ settings.json cost.json usage.jsonl
+ events.jsonl -> ../events.jsonl
+ run_state.json -> ../run_state.json
+ stages -> ../stages
+ trajectories -> ../trajectories
+ stages/ rounds/ trajectories/ physical homes (unchanged)
+ _assets/ _cand/ AGENTS.md GEMINI.md CLAUDE.md .mcp.json …
+```
+
+## Why the aliases point that way
+
+Only **one** physical copy of anything exists; the second name is a relative
+symlink. Which side is physical was not a matter of taste:
+
+* **`artifacts/` stays physical, `evidence/` is the alias.** Six packages
+ (`spatial`, `languages`, `tracks`, `texturing`, `judges`, `flywheel`) write
+ into `ws.artifacts`, and ~50 completed runs have absolute `artifacts/...`
+ paths frozen inside `record.json`, `rounds/rNN.json` and `views.json`.
+ Moving the bytes would either break those paths or force a rewrite of files
+ we treat as immutable evidence. The alias costs nothing and gives the
+ directory listing the name that explains what is inside.
+* **`events.jsonl` / `run_state.json` / `stages/` / `trajectories/` stay at the
+ root, `telemetry/` links to them.** `events.jsonl` is opened in append mode
+ by long-lived writers and `run_state.json` is rewritten atomically
+ (tmp + rename) — a rename onto a *symlink* replaces the link, so the symlink
+ must be on the alias side, never on the side that gets written.
+* **`deliverable/`, `telemetry/settings.json` and `telemetry/cost.json` are real
+ files.** They are *derived*: rebuilt from the run's own git history,
+ artifacts, trajectories and events every time the run is finalised or
+ migrated. `deliverable/` is self-contained so it can be zipped and handed to
+ someone (the flywheel exporter only falls back to it when git cannot answer).
+ `telemetry/usage.jsonl` is the one file that can be either: a real
+ reconstructed ledger, or a symlink to the run's live `cost_ledger.jsonl` when
+ it has one — same rule as everywhere else, one physical copy.
+
+`.gitignore` inside the run ignores `deliverable/`, `telemetry/` and `evidence`
+(as well as `artifacts/`, `stages/`, `trajectories/`, …) so the derived buckets
+never enter the code snapshot.
+
+## `deliverable/`
+
+Built by `codeverse.flywheel.deliverable.build_deliverable(ws, record)` from the
+**best round** (`record.best_round`, else the highest judged score):
+
+```
+deliverable/
+ src/** raw code at the best round's commit (public/** too, for scenes)
+ object.glb object.stl object.step object_textured.glb
+ robot.urdf meshes/<link>.glb (articulated)
+ frames/fNN_tT.png frames_sheet.png preview.gif (graphics)
+ textures/<id>.png (when the texture pass shipped)
+ sheet.png the best round's contact sheet
+ captions.json {detailed, instruction, factory} when captioned
+ manifest.json every file with role, size, sha256
+```
+
+Every file is hashed with sha256. Small files (all code) are real copies, so
+editing the hand-over folder can never touch the evidence; binaries of 256 KB and
+up (frame stacks, GLBs, GIFs) are **hard-linked** to their evidence copy when the
+filesystem allows — same bytes, one block on disk, and `cp` / `tar` / `rsync`
+still produce a standalone copy (the six graphics bench runs grow from 140 MB to
+144 MB, not to 210 MB). A file over 128 MB (or a bucket over 512 MB) is left
+out and named in `manifest.skipped`. Rebuilding is idempotent: the manifest
+keeps its previous `generated_at` when the content is unchanged, so re-running
+the packager produces no diff.
+
+## `telemetry/`
+
+* **`settings.json`** (`SettingsSnapshot`) — model id, thinking level,
+ temperature and judge sample count per role; rounds + budget; candidates;
+ seed; texture flag; rubric name **and its content hash**; prompt / cookbook
+ hashes; tool versions (python, blender, node, three, chrome, puppeteer);
+ harness version + git sha; key-pool size; **price-table hash**; resolved
+ render and limit settings. Sampling values are read from the call sites'
+ typed defaults (`ApiAgentOptions`, `VlmJudge.__init__`, `planner.plan`); a
+ value a call site hard-codes per task is left empty with `source` saying so,
+ never guessed. A track may publish real values as
+ `record.extra["sampling"][<role>]` and they win (`source: observed`).
+* **`usage.jsonl`** — one priced row per model call, in the
+ **`codeverse.cost` ledger format** (`CallCost`: tokens, unit prices, price
+ provenance, stage, role, outcome). There is exactly one ledger in the
+ harness: when the run wrote a live one (`<run>/cost_ledger.jsonl`)
+ `telemetry/usage.jsonl` is a symlink to it, otherwise
+ `cost.reconstruct.reconstruct_run` rebuilds the rows from the trajectories,
+ the recorded judge verdicts and the priced events. This bucket never
+ re-implements pricing or the double-counting rules — it only gives the ledger
+ a stable place in the run directory (`telemetry.files["usage_source"]` says
+ `live` / `reconstructed` / `unavailable`).
+* **`cost.json`** (`CostSummary`) — the run-layout view of those rows: total vs
+ budget, wall clock vs `max_minutes`, tokens, per stage (`plan / assets / env /
+ zones / baseline / refine / repair / judge / pairwise / texture / …`), per
+ role, per model, per round, plus `ledger_usd`, `unattributed_usd` (the
+ ledger's residual row) and `post_run_usd` (priced calls outside the run total,
+ e.g. a texture pass that ran after the loop). `record.total_usage` stays the
+ authority on what the run cost.
+
+## `record.json`
+
+Two additive blocks, both `None` on older records:
+
+* `record.telemetry` — `RunTelemetry(settings, cost, environment, files)`;
+* `record.deliverable` — `RunDeliverable(best_round, commit, code_source, entry,
+ files[path, role, bytes, sha256], total_bytes, skipped, generated_at)`.
+
+Everything else is unchanged, so a `record.json` written before this layout
+still validates and every consumer keeps working.
+
+## Reading a run
+
+```
+3dcv show <slug> # DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS
+3dcv show <slug> --section cost # just the token price + key step settings
+3dcv status <slug> # unchanged (+ a pointer to `3dcv show`)
+```
+
+`3dcv show` works on both layouts: when a run has no `telemetry/` yet the cost
+and settings block is computed on the fly (read-only) from the trajectories,
+judge verdicts and events already on disk.
+
+For the money itself across many runs — waste, $ per passing artifact, price
+provenance — use the cost package's own command, `3dcv cost show <runs-dir>`.
+`3dcv show` is the single-run view; both read the same ledger rows.
+
+## Migrating existing runs
+
+```
+3dcv migrate-runs runs/ --dry-run # report only, touches nothing
+3dcv migrate-runs runs/ # in place, idempotent
+3dcv migrate-runs runs/<slug> # a single run directory
+```
+
+The migration only **adds**: it creates the buckets and aliases, builds
+`deliverable/` and `telemetry/`, and writes the two new record blocks. It never
+moves or deletes evidence, never rewrites `src/`, never touches git history. A
+second pass reports `up_to_date`. Runs without a `record.json` (interrupted
+runs) get the layout only.
+
+## Back-compatibility contract
+
+* Old runs load unchanged — `load_record`, `3dcv status`, `3dcv judge`,
+ `3dcv render`, `flywheel export/pairs/gallery/index` all work with no
+ `deliverable/` or `telemetry/` present.
+* Consumers resolve artifacts through
+ `flywheel.deliverable.deliverable_path(ws, name)`: `deliverable/<name>` first,
+ `artifacts/<name>` second.
+* `flywheel export` reads the packaged code snapshot only when git cannot answer
+ (`meta.code_source == "deliverable"`), and adds a compact `meta.telemetry`
+ digest when the run has one (`{}` otherwise).
+* `flywheel gallery` links `deliverable/` and `cost.json` when they exist and
+ falls back to `artifacts/` otherwise; the per-stage cost line appears only for
+ runs that carry telemetry.
diff --git a/harness/runtime_js/README.md b/harness/runtime_js/README.md
index 33f5001f..066cc166 100644
--- a/harness/runtime_js/README.md
+++ b/harness/runtime_js/README.md
@@ -54,7 +54,9 @@ export_glb.mjs node --import lib/resolve_three.mjs export_glb.mjs --ws <w
render_glb.mjs --glb --out --views '[{name,azimuth,elevation}]' [--mode shaded|wire|normals|silhouette|clay]
[--width --height] [--isolate A,B] [--explode 0.3] [--background studio|white|transparent]
[--anim-time t] [--gpu auto|on|off] [--shadow 0|1] [--fill 0.85]
- writes view_<name>.png + views.json; last stdout line = JSON record
+ writes view_<name>.png + views.json; last stdout line = JSON record. Thin entry:
+ args/JSON protocol from lib/cli.mjs, browser + server from lib/host_env.mjs,
+ browser release from lib/host_page.mjs, everything visual from lib/browser/
lib/resolve_three.mjs node --import hook: bare 'three' / 'three/addons/*' (and three-mesh-bvh) resolve
from runtime_js/node_modules for modules anywhere on disk (NODE_PATH is CJS-only)
lib/node_polyfills.mjs FileReader/Blob/self shims so GLTFExporter writes binary GLB without a DOM
@@ -62,9 +64,12 @@ lib/census.mjs per-part tri counts, world bboxes, materials, NaN check na
lib/instances.mjs bakeInstancedMeshes(THREE, root): InstancedMesh → Group of named plain meshes
lib/stack.mjs Error → {type,message,file,line,frames} with workspace-relative src/ paths
lib/syntax_check.mjs `node --input-type=module --check` per file to locate ESM SyntaxErrors
-lib/browser/*.js page-side ESM (served through /__runtime/): camera_fit.js (azimuth/elevation →
- tight bbox fit), studio.js (RoomEnvironment PMREM + key/fill/rim, ACES, sRGB,
- shadow catcher, render modes), render_rig.js (load GLB, isolate/explode/anim, views)
+lib/browser/*.js page-side ESM (served through /__runtime/): renderer.js (THE WebGLRenderer factory —
+ sRGB + ACES + PCF shadows + pixel ratio 1, used by the object rig AND the scene host),
+ camera_fit.js (azimuth/elevation → tight bbox fit; the distance math itself is
+ lib/orbit.mjs::fitDistance, shared with the scene orbit rig), studio.js
+ (RoomEnvironment PMREM + key/fill/rim, shadow catcher, render modes; re-exports
+ renderer.js), render_rig.js (load GLB, isolate/explode/anim, views)
probe_scene.mjs scene build gate: boot src/scene.js, census, update(t,dt), first-camera checks;
--compile folds the full shader preflight into the SAME boot (shader_report);
@@ -74,8 +79,13 @@ render_scene.mjs authored cameras + orbit rig renders at times, metrics.jso
lib/host_env.mjs ESM adapters over gpu_launch.cjs + serve.cjs (launchBrowser, serveWorkspace)
lib/host_page.mjs node-side page driver: serve ws, launch, boot scene, collect errors, releaseBrowser
lib/scene_host.mjs page-side host (window.__c3v): boot/renderAt/census/compileAll/fps/cameraChecks
-lib/orbit.mjs THE camera-fit owner: fitOverviewCamera (corner-frustum), fitZoneCamera (eye level),
- fitOrbitCameras, framingBox
+lib/orbit.mjs THE camera-fit owner: fitDistance (exact per-corner frustum fit — also used by the
+ object rig through lib/browser/camera_fit.js), fitOverviewCamera, fitZoneCamera
+ (eye level), fitOrbitCameras, framingBox
+lib/backdrop.mjs THE sky/ground/content classifier (name + world-box rules), shared by the census
+ (host_census.mjs) and the frame-coverage instrument (host_coverage.mjs)
+lib/host_metrics.mjs page-side frame instruments: sampleFrame (the shared 96x54 readback grid),
+ frameStats (luminance), nearGeometry (camera-in-geometry rays)
lib/shader_report.mjs shared shader-preflight report builder (static + compile stages)
lib/glsl_audit.mjs static GLSL audits + compiler-line → file:line mapping
```
diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.py
new file mode 100644
index 00000000..43160c64
--- /dev/null
+++ b/harness/tests/core/test_run_layout.py
@@ -0,0 +1,81 @@
+"""The three-bucket run layout (docs/RUN_LAYOUT.md): directories, aliases,
+.gitignore and the additive record blocks. Pure filesystem + pydantic."""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+from codeverse.contracts.run import RunDeliverable, RunRecord, RunTelemetry
+from codeverse.contracts.spec import Spec
+from codeverse.workspace import LAYOUT_ALIASES, Workspace
+
+
+def test_create_makes_the_three_buckets(tmp_path: Path):
+ ws = Workspace(tmp_path / "run").create()
+ assert ws.deliverable.is_dir() and ws.telemetry.is_dir() and ws.artifacts.is_dir()
+ # evidence/ is the alias, artifacts/ the physical home (see docs/RUN_LAYOUT.md)
+ assert ws.evidence.is_symlink() and os.readlink(ws.evidence) == "artifacts"
+ assert ws.evidence.resolve() == ws.artifacts.resolve()
+ assert ws.cost_path.parent == ws.telemetry and ws.usage_path.name == "usage.jsonl"
+
+
+def test_telemetry_aliases_point_at_the_root_files(tmp_path: Path):
+ ws = Workspace(tmp_path / "run").create()
+ for name, target in LAYOUT_ALIASES:
+ link = ws.root / name
+ assert link.is_symlink(), name
+ assert os.readlink(link) == target
+ ws.events_path.write_text('{"event": "run.start"}\n')
+ assert (ws.telemetry / "events.jsonl").read_text().strip().endswith("}")
+ # an atomic rewrite of the physical file must not disturb the alias
+ ws.write_json(ws.state_path, {"status": "passed"})
+ assert json.loads((ws.telemetry / "run_state.json").read_text())["status"] == "passed"
+ assert (ws.telemetry / "run_state.json").is_symlink()
+
+
+def test_ensure_layout_is_idempotent_and_dry_runnable(tmp_path: Path):
+ ws = Workspace(tmp_path / "run")
+ planned = ws.ensure_layout(dry_run=True)
+ assert planned and not ws.deliverable.exists()
+ first = ws.ensure_layout()
+ assert set(first) == set(planned)
+ assert ws.ensure_layout() == {} # nothing left to do
+ assert ws.ensure_layout(dry_run=True) == {}
+
+
+def test_ensure_layout_never_clobbers_real_data(tmp_path: Path):
+ ws = Workspace(tmp_path / "run")
+ (ws.root / "evidence").mkdir(parents=True)
+ (ws.root / "evidence" / "keep.txt").write_text("evidence")
+ actions = ws.ensure_layout()
+ assert actions["evidence"] == "kept"
+ assert (ws.root / "evidence" / "keep.txt").read_text() == "evidence"
+ assert not (ws.root / "evidence").is_symlink()
+
+
+def test_gitignore_covers_the_derived_buckets(tmp_path: Path):
+ ws = Workspace(tmp_path / "run").create()
+ text = (ws.root / ".gitignore").read_text()
+ for line in ("artifacts/", "deliverable/", "telemetry/", "evidence", "trajectories/"):
+ assert line in text.splitlines()
+ assert ws.ensure_gitignore() is False # idempotent
+ (ws.root / ".gitignore").write_text("src/nothing\n")
+ assert ws.ensure_gitignore(dry_run=True) is True
+ assert (ws.root / ".gitignore").read_text() == "src/nothing\n"
+ assert ws.ensure_gitignore() is True
+ assert "deliverable/" in (ws.root / ".gitignore").read_text()
+
+
+def test_record_blocks_are_additive(tmp_path: Path):
+ """An old record.json (no telemetry / deliverable) must still validate."""
+ spec = Spec(id="x", track="static_object", language="blender", prompt="a chair")
+ old = {"spec": spec.model_dump(mode="json"), "workspace": str(tmp_path), "status": "passed"}
+ rec = RunRecord.model_validate(old)
+ assert rec.telemetry is None and rec.deliverable is None
+ rec.telemetry = RunTelemetry()
+ rec.deliverable = RunDeliverable(best_round=1, commit="abc")
+ again = RunRecord.model_validate_json(rec.model_dump_json())
+ assert again.deliverable is not None and again.deliverable.best_round == 1
+ assert again.telemetry is not None and again.telemetry.schema_version == 1
diff --git a/harness/tests/cost/__init__.py b/harness/tests/cost/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/cost/conftest.py b/harness/tests/cost/conftest.py
new file mode 100644
index 00000000..a326e87d
--- /dev/null
+++ b/harness/tests/cost/conftest.py
@@ -0,0 +1,68 @@
+"""A tiny synthetic run directory — the shapes ``reconstruct`` must understand."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+
+def _write(path: Path, obj: object) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(obj))
+
+
+def _usage(**kw: object) -> dict[str, object]:
+ base = {"backend": "gemini", "model": "gemini-3.7-flash", "input_tokens": 0, "output_tokens": 0,
+ "cached_tokens": 0, "thoughts_tokens": 0, "tool_calls": 0, "cost_usd": 0.0, "latency_ms": 0}
+ base.update(kw)
+ return base
+
+
+def fake_run(tmp_path: Path) -> Path:
+ """plan (event only) + one api-agent baseline session (2 turns) + one judge verdict."""
+ ws = tmp_path / "fake_run"
+ turns = [
+ _usage(input_tokens=10_000, output_tokens=100, cost_usd=10_000 * 0.75e-6 + 100 * 3.75e-6),
+ _usage(input_tokens=20_000, cached_tokens=10_000, output_tokens=200,
+ cost_usd=10_000 * 0.75e-6 + 10_000 * 0.075e-6 + 200 * 3.75e-6),
+ ]
+ session = _usage(backend="api-agent", model="gemini:gemini-3.7-flash",
+ input_tokens=30_000, cached_tokens=10_000, output_tokens=300,
+ cost_usd=sum(float(t["cost_usd"]) for t in turns), latency_ms=1000)
+ d = ws / "trajectories" / "baseline_r00"
+ _write(d / "result.json", {"ok": True, "exit_reason": "completed", "label": "baseline", "round": 0,
+ "kind": "api-agent", "usage": session, "duration_s": 30.0, "turns": 2})
+ (d / "transcript.jsonl").write_text("\n".join(
+ json.dumps({"t": 100.0 + i, "kind": "assistant", "turn": i, "usage": u}) for i, u in enumerate(turns)))
+
+ judge_usage = _usage(model="gemini-3.1-pro-preview", input_tokens=12_000, output_tokens=1_000,
+ cost_usd=12_000 * 2e-6 + 1_000 * 12e-6, latency_ms=5000)
+ plan_cost = 0.01
+ total = _usage(input_tokens=42_000, cached_tokens=10_000, output_tokens=1_300,
+ cost_usd=float(session["cost_usd"]) + float(judge_usage["cost_usd"]) + plan_cost)
+ _write(ws / "record.json", {
+ "spec": {"track": "static_object", "language": "blender",
+ "backends": {"generator": "api-agent:gemini:gemini-3.7-flash",
+ "judge": "gemini:gemini-3.1-pro-preview"},
+ "budget": {"max_usd": 5.0}},
+ "status": "passed", "baseline_score": 0.6, "final_score": 0.8, "best_round": 0,
+ "total_usage": total, "extra": {"stop_reason": "pass", "budget": {"elapsed_min": 2.0}},
+ "rounds": [{"index": 0, "kind": "baseline", "usage": session, "gates": [],
+ "judgment": {"rubric": "static_object_v1", "judge_backend": "gemini:gemini-3.1-pro-preview",
+ "overall": 0.8, "passed": True, "n_samples": 1, "usage": judge_usage}}],
+ })
+ (ws / "events.jsonl").write_text("\n".join(json.dumps(e) for e in [
+ {"t": 1.0, "event": "run.start", "track": "static_object"},
+ {"t": 2.0, "event": "plan.done", "model": "gemini:gemini-3.7-flash", "cost_usd": plan_cost},
+ {"t": 3.0, "event": "stage.done", "stage": "plan", "duration_s": 2.0},
+ {"t": 40.0, "event": "generate.done", "label": "baseline", "cost_usd": round(float(session["cost_usd"]), 4)},
+ {"t": 50.0, "event": "judge.done", "round": 0, "cost_usd": round(float(judge_usage["cost_usd"]), 4),
+ "duration_s": 5.0},
+ {"t": 51.0, "event": "round.done", "round": 0, "kind": "baseline", "duration_s": 48.0,
+ "cost_usd": round(float(session["cost_usd"]) + float(judge_usage["cost_usd"]), 4)},
+ {"t": 52.0, "event": "run.done", "cost_usd": round(float(total["cost_usd"]), 4)},
+ ]))
+ return ws
diff --git a/harness/tests/cost/test_audit_report.py b/harness/tests/cost/test_audit_report.py
new file mode 100644
index 00000000..1e6dac88
--- /dev/null
+++ b/harness/tests/cost/test_audit_report.py
@@ -0,0 +1,61 @@
+"""The audit over a tree of runs and its report."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from codeverse.cost import audit_runs
+from codeverse.cost.audit import cached_input_share, price_confidence, stage_latency, uncached_if_no_cache
+from codeverse.cost.report import console, markdown
+
+
+def test_audit_of_one_run(fake_run: Path):
+ audit = audit_runs([fake_run.parent])
+ assert audit.n_runs == 1 and audit.n_passed == 1
+ assert audit.usd_per_passing_artifact == pytest.approx(audit.total_usd)
+ assert audit.bucket("track", "static_object").cost_usd == pytest.approx(audit.total_usd)
+ assert audit.calls_per_round() > 0
+ cached, total, usd = cached_input_share(audit)
+ assert 0 < cached < total and usd > 0
+ assert uncached_if_no_cache(audit) > audit.total_usd
+ assert sum(price_confidence(audit).values()) == pytest.approx(audit.total_usd)
+ assert stage_latency(audit)
+
+
+def test_waste_finds_a_regression(fake_run: Path, tmp_path: Path):
+ """A refine round that scores below the best is money spent on a worse artifact."""
+ import shutil
+
+ ws = tmp_path / "regressed"
+ shutil.copytree(fake_run, ws)
+ record = json.loads((ws / "record.json").read_text())
+ r0 = record["rounds"][0]
+ r1 = json.loads(json.dumps(r0))
+ r1["index"] = 1
+ r1["kind"] = "refine"
+ r1["judgment"]["overall"] = 0.5 # worse than r00's 0.8
+ record["rounds"].append(r1)
+ record["total_usage"]["cost_usd"] *= 2
+ (ws / "record.json").write_text(json.dumps(record))
+ audit = audit_runs([ws])
+ kinds = audit.waste_by_kind()
+ assert "regression" in kinds and kinds["regression"][1] > 0
+ assert any("scored 0.500 vs 0.800" in w.detail for w in audit.waste)
+
+
+def test_report_renders(fake_run: Path):
+ audit = audit_runs([fake_run])
+ md = markdown(audit)
+ for heading in ("Per stage", "Per role", "Where a dollar bought nothing", "Routing"):
+ assert f"## {heading}" in md
+ assert "per passing artifact" in md
+ assert "judge" in console(audit)
+
+
+def test_empty_tree_is_not_an_error(tmp_path: Path):
+ audit = audit_runs([tmp_path])
+ assert audit.n_runs == 0 and audit.total_usd == 0.0
+ assert audit.usd_per_passing_artifact == float("inf")
diff --git a/harness/tests/cost/test_cli.py b/harness/tests/cost/test_cli.py
new file mode 100644
index 00000000..c617772f
--- /dev/null
+++ b/harness/tests/cost/test_cli.py
@@ -0,0 +1,50 @@
+"""``3dcv cost`` and ``bench/cost_report.py``."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from typer.testing import CliRunner
+
+from codeverse.cli.main import app
+
+runner = CliRunner()
+
+
+def test_cost_is_registered():
+ r = runner.invoke(app, ["--help"])
+ assert r.exit_code == 0 and "cost" in r.stdout
+
+
+def test_cost_show(fake_run: Path, tmp_path: Path):
+ out = tmp_path / "report.md"
+ r = runner.invoke(app, ["cost", "show", str(fake_run), "--md", str(out)])
+ assert r.exit_code == 0, r.output
+ assert "passing" in r.stdout and "judge" in r.stdout
+ assert out.is_file() and "## Per stage" in out.read_text()
+
+
+def test_cost_show_recheck_reports_drift(fake_run: Path):
+ r = runner.invoke(app, ["cost", "show", str(fake_run), "--recheck"])
+ assert r.exit_code == 0 and "re-priced total" in r.output
+
+
+def test_cost_show_on_an_empty_tree_fails_cleanly(tmp_path: Path):
+ r = runner.invoke(app, ["cost", "show", str(tmp_path)])
+ assert r.exit_code != 0 and "no runs" in r.output
+
+
+def test_cost_prices_and_estimate():
+ r = runner.invoke(app, ["cost", "prices", "--provider", "gemini"])
+ assert r.exit_code == 0 and "gemini:gemini-3.7-flash" in r.stdout and "verified" in r.stdout
+ r = runner.invoke(app, ["cost", "estimate", "gemini:gemini-3.7-flash", "--in", "100000", "--out", "1000"])
+ assert r.exit_code == 0 and "$0.0788" in r.stdout
+
+
+def test_bench_cost_report_entry_point(fake_run: Path, tmp_path: Path):
+ from bench.cost_report import main
+
+ out = tmp_path / "cost.md"
+ assert main([str(fake_run), "--out", str(out), "--quiet"]) == 0
+ assert "# Cost report" in out.read_text()
+ assert main([str(tmp_path / "nothing"), "--quiet"]) == 2
diff --git a/harness/tests/cost/test_guard_caching_routing.py b/harness/tests/cost/test_guard_caching_routing.py
new file mode 100644
index 00000000..8f7c7306
--- /dev/null
+++ b/harness/tests/cost/test_guard_caching_routing.py
@@ -0,0 +1,117 @@
+"""The three optimisation helpers: pre-send estimate, cache-friendly ordering,
+model routing."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.contracts.common import Usage
+from codeverse.cost import (
+ Block,
+ CostGuard,
+ cache_efficiency,
+ cheapest_affordable,
+ estimate_call,
+ order_blocks,
+ prefix_report,
+ prefix_signature,
+ render_blocks,
+ text_tokens,
+)
+from codeverse.cost.guard import image_tokens
+from codeverse.cost.routing import ROUTES, default_route, pro_break_even, samples_for_precision
+from codeverse.cost.types import Role
+
+
+# ------------------------------------------------------------------ guard
+def test_estimate_matches_the_price_table():
+ est = estimate_call("gemini:gemini-3.7-flash", input_tokens=100_000, cached_tokens=80_000,
+ output_tokens=1_000)
+ assert abs(est.usd - (0.015 + 0.006 + 0.00375)) < 1e-9
+ assert est.provider == "gemini" and est.model == "gemini-3.7-flash" and not est.approximate
+
+
+def test_estimate_from_text_and_images():
+ est = estimate_call("gemini:gemini-3.1-pro-preview", prompt="x" * 4000, n_images=4, output_tokens=2000)
+ assert est.input_tokens == 1000 + image_tokens(4)
+ assert est.usd == pytest.approx((est.input_tokens * 2.0 + 2000 * 12.0) / 1e6)
+ assert text_tokens(["ab" * 2, "cd" * 2]) == 2
+
+
+def test_estimate_of_an_image_model_uses_the_per_image_price():
+ est = estimate_call("gemini:gemini-3.1-flash-image", input_tokens=500, n_images_out=2)
+ assert est.usd == pytest.approx(500 * 0.5 / 1e6 + 2 * 0.067)
+
+
+def test_guard_blocks_only_what_it_can_price():
+ guard = CostGuard(budget_usd=0.10, reserve_usd=0.02)
+ cheap = estimate_call("gemini:gemini-3.7-flash", input_tokens=10_000, output_tokens=500)
+ allow, why = guard.check(cheap)
+ assert allow and not why
+ guard.commit(cheap.usd)
+ dear = estimate_call("gemini:gemini-3.1-pro-preview", input_tokens=2_000_000, output_tokens=50_000)
+ allow, why = guard.check(dear)
+ assert not allow and "left of" in why and guard.rejected
+ unknown = estimate_call("gemini:no-such-model", input_tokens=10_000_000, output_tokens=1)
+ assert guard.check(unknown)[0] is True # unpriceable ≠ blocked
+
+
+def test_cheapest_affordable_picks_a_tier():
+ pick = cheapest_affordable(
+ ["gemini:gemini-3.1-pro-preview", "gemini:gemini-3.7-flash", "gemini:gemini-3.1-flash-lite"],
+ input_tokens=50_000, output_tokens=2_000)
+ assert pick is not None and pick[0] == "gemini:gemini-3.1-flash-lite"
+ assert cheapest_affordable(["gemini:gemini-3.1-pro-preview"], input_tokens=10_000_000,
+ output_tokens=0, budget_usd=0.001) is None
+
+
+# ------------------------------------------------------------------ caching
+def test_order_blocks_puts_the_stable_prefix_first():
+ blocks = [Block("round", "round 3 of 4", order=1),
+ Block("system", "SYSTEM RULES", stable=True, order=0),
+ Block("rubric", "RUBRIC", stable=True, order=1),
+ Block("renders", "<images>", order=0)]
+ ordered = order_blocks(blocks)
+ assert [b.name for b in ordered] == ["system", "rubric", "renders", "round"]
+ assert render_blocks(ordered).startswith("SYSTEM RULES\n\nRUBRIC")
+
+
+def test_prefix_signature_only_covers_the_stable_head():
+ a = order_blocks([Block("s", "SYS", stable=True), Block("v", "round 1")])
+ b = order_blocks([Block("s", "SYS", stable=True), Block("v", "round 2")])
+ assert prefix_signature(a) == prefix_signature(b)
+ c = order_blocks([Block("s", "SYS!", stable=True), Block("v", "round 1")])
+ assert prefix_signature(c) != prefix_signature(a)
+
+
+def test_prefix_report_measures_the_shared_head_and_its_value():
+ stable = "S" * 40_000 # 10k tokens
+ prompts = [stable + f"\nround {i}" for i in range(4)]
+ rep = prefix_report(prompts)
+ assert rep.prefix_tokens == pytest.approx(10_000, rel=0.01)
+ assert rep.shared_fraction > 0.99
+ # 3 later calls read 10k tokens from cache instead of paying full input price
+ assert rep.savings_usd(0.75, 0.075) == pytest.approx(3 * 10_000 * 0.675 / 1e6, rel=0.01)
+ volatile_first = [f"round {i}\n" + stable for i in range(4)]
+ assert prefix_report(volatile_first).prefix_tokens < 10 # the cache is gone
+
+
+def test_cache_efficiency_reads_usages():
+ us = [Usage(input_tokens=100, cached_tokens=0), Usage(input_tokens=100, cached_tokens=80)]
+ cached, total, rate = cache_efficiency(us)
+ assert (cached, total) == (80, 200) and rate == 0.4
+
+
+# ------------------------------------------------------------------ routing
+def test_routing_defaults_exist_for_every_role():
+ for role in (Role.PLANNER, Role.GENERATOR, Role.JUDGE, Role.IMAGE, Role.CAPTIONER):
+ route = default_route(role)
+ assert route is not None and route.model_id and route.when, role
+ assert all(r.usd_per_call > 0 for r in ROUTES)
+
+
+def test_pro_judge_pays_for_itself_at_equal_precision():
+ assert samples_for_precision("gemini-3.7-flash", 0.030) == 8
+ assert samples_for_precision("gemini-3.1-pro-preview", 0.030) == 1
+ be = pro_break_even()
+ assert be["ratio"] > 3 and be["pro_is_cheaper_by"] > 0.1
diff --git a/harness/tests/cost/test_ledger.py b/harness/tests/cost/test_ledger.py
new file mode 100644
index 00000000..d14c7a10
--- /dev/null
+++ b/harness/tests/cost/test_ledger.py
@@ -0,0 +1,87 @@
+"""The append-only ledger: writing, reading, pricing provenance, aggregation."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from codeverse.contracts.common import Usage
+from codeverse.cost import CostLedger, load_ledger, record_call, summarise
+from codeverse.cost.ledger import set_default_ledger
+from codeverse.cost.types import Role, Stage
+
+
+def _usage(**kw: object) -> Usage:
+ base = {"backend": "gemini", "model": "gemini-3.7-flash", "input_tokens": 100_000,
+ "cached_tokens": 80_000, "output_tokens": 1_000}
+ base.update(kw)
+ return Usage(**base) # type: ignore[arg-type]
+
+
+def test_record_call_prices_and_stamps_provenance(tmp_path: Path):
+ row = record_call(_usage(), run="r1", stage="judge", ledger=tmp_path / "l.jsonl")
+ # 20k uncached * 0.75 + 80k cached * 0.075 + 1k out * 3.75, per 1M
+ assert abs(row.cost_usd - (0.015 + 0.006 + 0.00375)) < 1e-9
+ assert row.role is Role.JUDGE and row.stage is Stage.JUDGE # role inferred from stage
+ assert row.provider == "gemini" and row.model == "gemini-3.7-flash"
+ assert row.price_source == "exact" and row.price_approximate is False and row.price_checked
+ assert row.cache_hit is True and row.n_calls == 1
+
+
+def test_keeps_the_billed_cost_but_can_reprice(tmp_path: Path):
+ billed = record_call(_usage(cost_usd=0.123), run="r", stage="baseline", ledger=tmp_path / "a.jsonl")
+ assert billed.cost_usd == 0.123 and billed.recorded_usd == 0.123
+ repriced = record_call(_usage(cost_usd=0.123), run="r", stage="baseline", reprice=True,
+ ledger=tmp_path / "a.jsonl")
+ assert abs(repriced.cost_usd - 0.02475) < 1e-9 and repriced.recorded_usd == 0.123
+
+
+def test_append_only_and_reload(tmp_path: Path):
+ led = CostLedger(tmp_path / "l.jsonl")
+ for i in range(3):
+ record_call(_usage(), run="r", round=i, stage="refine", ledger=led)
+ rows = load_ledger(tmp_path / "l.jsonl")
+ assert len(rows) == 3 and [r.round for r in rows] == [0, 1, 2]
+ record_call(_usage(), run="r", round=3, stage="refine", ledger=led)
+ assert len(load_ledger(tmp_path / "l.jsonl")) == 4 # nothing rewritten
+
+
+def test_bad_line_does_not_lose_the_file(tmp_path: Path):
+ p = tmp_path / "l.jsonl"
+ record_call(_usage(), run="r", stage="plan", ledger=p)
+ with p.open("a") as fh:
+ fh.write("{not json\n")
+ record_call(_usage(), run="r", stage="judge", ledger=p)
+ assert len(load_ledger(p)) == 2
+
+
+def test_unknown_model_is_recorded_not_raised(tmp_path: Path):
+ row = record_call(_usage(model="totally-made-up-9"), run="r", stage="plan", ledger=tmp_path / "l.jsonl")
+ assert row.cost_usd == 0.0 and row.price_source == "unknown" and row.price_approximate is True
+
+
+def test_provider_reported_cost_is_flagged(tmp_path: Path):
+ """A subscription CLI bills us a cost our table cannot reproduce: keep the
+ dollar, mark it unauditable."""
+ row = record_call(_usage(backend="claude-code", model="claude-not-a-model", cost_usd=1.17),
+ run="r", stage="baseline", ledger=tmp_path / "l.jsonl")
+ assert row.cost_usd == 1.17 and row.price_source == "provider-reported"
+
+
+def test_summarise_dimensions(tmp_path: Path):
+ p = tmp_path / "l.jsonl"
+ record_call(_usage(), run="a", stage="baseline", ledger=p)
+ record_call(_usage(model="gemini-3.1-pro-preview", cached_tokens=0), run="a", stage="judge", ledger=p)
+ s = summarise(load_ledger(p))
+ assert set(s.dimension("stage")) == {"baseline", "judge"}
+ assert abs(s.total.cost_usd - sum(b.cost_usd for b in s.dimension("role").values())) < 1e-12
+ assert s.dimension("stage")["baseline"].cached_fraction == 0.8
+ assert s.total.usd_per_1k_tokens > 0
+
+
+def test_default_ledger_env_and_setter(tmp_path: Path):
+ try:
+ set_default_ledger(tmp_path / "default.jsonl")
+ record_call(_usage(), run="r", stage="plan")
+ assert len(load_ledger(tmp_path / "default.jsonl")) == 1
+ finally:
+ set_default_ledger(None)
diff --git a/harness/tests/cost/test_live.py b/harness/tests/cost/test_live.py
new file mode 100644
index 00000000..662d286b
--- /dev/null
+++ b/harness/tests/cost/test_live.py
@@ -0,0 +1,76 @@
+"""LIVE (needs gemini keys): the two measurements docs/COST.md quotes.
+
+ python -m pytest tests/cost/test_live.py -q -m live
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from codeverse.contracts.chat import ChatMessage, ChatRequest
+from codeverse.cost import Block, cache_efficiency, order_blocks, render_blocks
+from codeverse.cost.guard import estimate_call, text_tokens
+
+pytestmark = pytest.mark.live
+
+REPO = Path(__file__).resolve().parents[2]
+
+
+def _stable_text() -> str:
+ from codeverse.judges.prompt_builder import build_system_prompt
+ from codeverse.judges.rubrics import load_rubric
+
+ return "\n".join([
+ build_system_prompt(load_rubric("static_object_v1")),
+ (REPO / "codeverse/prompts/blender/contract.md").read_text(),
+ (REPO / "codeverse/prompts/blender/cookbook.md").read_text(),
+ ])
+
+
+def _send(model, text: str):
+ return model.generate(ChatRequest(messages=[ChatMessage.user(text)], max_output_tokens=1100,
+ temperature=0.0, thinking="low", label="cost-test")).usage
+
+
[email protected]("arm", ["stable_first", "volatile_first"])
+def test_cache_friendly_ordering_is_measurably_cheaper(arm: str):
+ """A ≥12k-token stable prefix must cache when it comes FIRST and must not
+ when the volatile block precedes it (measured 2026-08-23: 69% vs 0%)."""
+ from codeverse.config import get_settings
+ from codeverse.models.gemini import GeminiModel
+
+ import uuid
+
+ keys = list(get_settings().gemini_api_keys)
+ if not keys:
+ pytest.skip("no gemini keys")
+ # a corpus no call has seen before: the two arms must not inherit each
+ # other's cache (the implicit cache is shared across the whole key pool).
+ stable = f"[corpus {uuid.uuid4().hex}]\n" + _stable_text() * 2
+ assert text_tokens(stable) > 12_000, "the experiment needs a prefix above the cache floor"
+ model = GeminiModel("gemini-3.7-flash", keys=[keys[0 if arm == "stable_first" else 1]])
+ usages = []
+ for i in range(4):
+ blocks = [Block("stable", stable, stable=(arm == "stable_first")),
+ Block("volatile", f"ROUND {i}\nReply with ONE JSON object {{\"n\": {i}}}.")]
+ text = render_blocks(order_blocks(blocks)) if arm == "stable_first" \
+ else f"ROUND {i}\nReply with ONE JSON object {{\"n\": {i}}}.\n\n{stable}"
+ usages.append(_send(model, text))
+ cached, total, rate = cache_efficiency(usages[1:]) # the first call warms the cache
+ if arm == "stable_first":
+ assert rate > 0.3, f"stable-first should cache; got {rate:.2f} (implicit cache is best-effort)"
+ else:
+ assert rate < 0.2, f"volatile-first must not cache; got {rate:.2f}"
+
+
+def test_estimate_is_within_15_percent_of_the_bill():
+ """The pre-send estimate has to be good enough to route on."""
+ from codeverse.models import get_chat_model
+
+ text = _stable_text()[:20_000]
+ est = estimate_call("gemini:gemini-3.7-flash", prompt=text, output_tokens=40)
+ usage = _send(get_chat_model("gemini:gemini-3.7-flash"),
+ text + "\n\nReply with ONE JSON object {\"ok\": true}.")
+ assert abs(est.input_tokens - usage.input_tokens) / usage.input_tokens < 0.15
diff --git a/harness/tests/cost/test_price_hygiene.py b/harness/tests/cost/test_price_hygiene.py
new file mode 100644
index 00000000..9892dac2
--- /dev/null
+++ b/harness/tests/cost/test_price_hygiene.py
@@ -0,0 +1,121 @@
+"""Price table hygiene: provenance for every row, and no silent $0 for any model
+id that appears in a recorded run."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from codeverse.contracts.common import Usage
+from codeverse.models.pricing import (
+ IMAGE_USD_BY_SIZE,
+ PRICES,
+ PROVENANCE,
+ estimate_cost,
+ per_image_usd,
+ price_provenance,
+ unit_prices,
+)
+
+REPO = Path(__file__).resolve().parents[2]
+
+#: model ids the harness uses by default (config/contracts defaults + the CLI
+#: backends we run here) — asserted even when no recorded run is present.
+CORE_MODEL_IDS = (
+ "gemini:gemini-3.7-flash",
+ "gemini:gemini-3.1-pro-preview",
+ "gemini:gemini-3.1-flash-image",
+ "gemini:gemini-2.5-flash-image",
+ "openai:gpt-5.6-sol",
+ "anthropic:claude-fable-5",
+ "anthropic:claude-haiku-4-5-20251001",
+)
+
+
+def test_every_price_row_has_provenance():
+ assert set(PRICES) == set(PROVENANCE), (
+ f"missing provenance: {sorted(set(PRICES) - set(PROVENANCE))}; "
+ f"stale provenance: {sorted(set(PROVENANCE) - set(PRICES))}")
+ for key, prov in PROVENANCE.items():
+ assert prov.checked and prov.checked[:2] == "20", key
+ assert prov.status in ("verified", "inferred", "unverified"), key
+ assert prov.url, key
+
+
+def test_provenance_flags_the_rows_we_cannot_stand_behind():
+ for key, price in PRICES.items():
+ row = price_provenance(*key)
+ if price.approximate:
+ assert row.approximate, key
+ assert price_provenance("gemini", "gemini-3.7-flash").approximate is False
+ assert price_provenance("anthropic", "claude-haiku-4").approximate is True
+ assert price_provenance("gemini", "not-a-model").status == "unknown"
+
+
+def test_image_models_have_a_per_image_price():
+ for provider, model in (("gemini", "gemini-3.1-flash-image"), ("gemini", "gemini-2.5-flash-image")):
+ assert PRICES[(provider, model)].image_usd > 0, model
+ assert per_image_usd(provider, model) == PRICES[(provider, model)].image_usd
+ assert per_image_usd(provider, model, size=512) > 0
+ assert (provider, model) in IMAGE_USD_BY_SIZE
+ # version suffixes resolve too (the image model is often pinned with -preview)
+ assert per_image_usd("gemini", "gemini-2.5-flash-image-preview") == 0.039
+
+
+def test_image_price_agrees_with_the_image_backend():
+ """``models/gemini_image.IMAGE_USD`` and the price table must not drift apart."""
+ from codeverse.models.gemini_image import IMAGE_USD
+
+ for model, usd in IMAGE_USD.items():
+ assert per_image_usd("gemini", model) == pytest.approx(usd), model
+
+
+def test_long_context_tier_is_applied():
+ small = Usage(input_tokens=100_000, output_tokens=1_000)
+ big = Usage(input_tokens=300_000, output_tokens=1_000)
+ assert unit_prices("gemini", "gemini-3.1-pro-preview", prompt_tokens=100_000)[0] == 2.0
+ assert unit_prices("gemini", "gemini-3.1-pro-preview", prompt_tokens=300_000)[0] == 4.0
+ assert estimate_cost("gemini", "gemini-3.1-pro-preview", big) > \
+ 3 * estimate_cost("gemini", "gemini-3.1-pro-preview", small)
+ # flash has no long-context tier
+ assert unit_prices("gemini", "gemini-3.7-flash", prompt_tokens=900_000)[0] == 0.75
+
+
+def _recorded_model_ids() -> set[tuple[str, str]]:
+ """Every (backend, model) pair that appears in a recorded run of this repo."""
+ from codeverse.cost.types import split_model_id
+
+ out: set[tuple[str, str]] = set()
+ for root in (REPO / "runs", REPO / "bench" / "out"):
+ if not root.is_dir():
+ continue
+ for record in root.rglob("record.json"):
+ try:
+ data = json.loads(record.read_text())
+ except (OSError, ValueError):
+ continue
+ usages = [data.get("total_usage")]
+ for rnd in data.get("rounds") or []:
+ usages.append(rnd.get("usage"))
+ usages.append((rnd.get("judgment") or {}).get("usage"))
+ for u in usages:
+ if isinstance(u, dict) and (u.get("model") or ""):
+ out.add(split_model_id(str(u.get("backend") or ""), str(u["model"])))
+ return out
+
+
[email protected]("model_id", CORE_MODEL_IDS)
+def test_core_model_ids_resolve_to_a_price(model_id: str):
+ provider, model = model_id.split(":", 1)
+ u = Usage(input_tokens=1_000, output_tokens=1_000)
+ assert price_provenance(provider, model).price is not None, model_id
+ assert estimate_cost(provider, model, u) > 0, model_id
+
+
+def test_every_recorded_model_id_resolves_to_a_price():
+ """No silent $0: a model that billed us in a recorded run must have a row."""
+ unknown = sorted(f"{p}:{m}" for p, m in _recorded_model_ids()
+ if p and price_provenance(p, m).price is None)
+ assert not unknown, f"models with no price row (they cost $0 in every report): {unknown}"
diff --git a/harness/tests/cost/test_reconstruct.py b/harness/tests/cost/test_reconstruct.py
new file mode 100644
index 00000000..729d6ac3
--- /dev/null
+++ b/harness/tests/cost/test_reconstruct.py
@@ -0,0 +1,110 @@
+"""Rebuilding a ledger from a run directory: reconcile, never double count."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from codeverse.cost import audit_runs, find_runs, reconstruct
+from codeverse.cost.types import Role, Stage
+
+REPO = Path(__file__).resolve().parents[2]
+
+
+def test_reconstructs_and_reconciles(fake_run: Path):
+ led = reconstruct(fake_run)
+ assert abs(led.ledger_usd - led.recorded_usd) < 1e-6, "rows must reconcile to record.total_usage"
+ stages = {r.stage for r in led.rows}
+ assert Stage.BASELINE in stages and Stage.JUDGE in stages and Stage.PLAN in stages
+ assert led.track == "static_object" and led.passed is True
+
+
+def test_generate_event_does_not_double_count_its_session(fake_run: Path):
+ led = reconstruct(fake_run)
+ gen = [r for r in led.rows if r.stage is Stage.BASELINE]
+ assert len(gen) == 2, "two transcript turns, not the session row and not the event"
+ assert all(r.source == "transcript" for r in gen)
+ assert not [r for r in led.rows if r.source == "event:generate.done"]
+
+
+def test_judge_row_carries_the_judge_model(fake_run: Path):
+ row = next(r for r in reconstruct(fake_run).rows if r.role is Role.JUDGE)
+ assert row.model == "gemini-3.1-pro-preview" and row.provider == "gemini"
+ assert row.price_source == "exact"
+
+
+def test_missing_session_falls_back_to_the_event(fake_run: Path, tmp_path: Path):
+ """A CLI backend that left no trajectory still shows up, from its event."""
+ import shutil
+
+ ws = tmp_path / "no_traj"
+ shutil.copytree(fake_run, ws)
+ shutil.rmtree(ws / "trajectories")
+ led = reconstruct(ws)
+ gen = [r for r in led.rows if r.stage is Stage.BASELINE]
+ assert len(gen) == 1 and gen[0].source == "event:generate.done"
+ assert abs(led.ledger_usd - led.recorded_usd) < 0.001
+
+
+def test_wall_clock_ignores_time_queued_before_the_run_started(fake_run: Path):
+ led = reconstruct(fake_run)
+ assert led.wall_s == pytest.approx(120.0) # budget elapsed_min=2.0, not the 51 s event span
+
+
+def test_find_runs_skips_sub_workspaces(tmp_path: Path):
+ (tmp_path / "a").mkdir()
+ (tmp_path / "a" / "record.json").write_text("{}")
+ sub = tmp_path / "a" / "_assets" / "x"
+ sub.mkdir(parents=True)
+ (sub / "record.json").write_text("{}")
+ assert find_runs(tmp_path) == [tmp_path / "a"]
+
+
[email protected](not (REPO / "runs" / "e2e_chair_blender" / "record.json").is_file(),
+ reason="recorded reference runs are not present")
+def test_reference_runs_reconcile():
+ """Every recorded run reconciles to its own record (or explains the gap)."""
+ audit = audit_runs([REPO / "runs"])
+ assert audit.n_runs >= 5
+ for led in audit.runs:
+ gap = led.ledger_usd - led.recorded_usd
+ assert gap > -0.01, f"{led.run}: ledger lost ${-gap:.4f}"
+ if gap > 0.01:
+ assert led.notes, f"{led.run}: unexplained extra ${gap:.4f}"
+
+
[email protected](not (REPO / "runs" / "e2e_chair_blender" / "record.json").is_file(),
+ reason="recorded reference runs are not present")
+def test_gemini_cli_recheck_finds_the_stale_parse():
+ """The threejs run was recorded before ``tokens.prompt`` was the total prompt:
+ re-pricing from the raw CLI stats must show the under-billing, not hide it."""
+ led = reconstruct(REPO / "runs" / "e2e_bench_threejs", recheck=True)
+ assert led.ledger_usd > 2.0 > led.recorded_usd
+ assert any("differs from record.total_usage" in n for n in led.notes)
+
+
+def test_best_of_n_losers_are_attributed_and_counted_as_waste(fake_run: Path, tmp_path: Path):
+ """A ``_cand/c<k>`` sub-workspace is the run's, not a run of its own; the
+ candidates that lost are money spent on artifacts nobody kept."""
+ import json
+ import shutil
+
+ ws = tmp_path / "cands"
+ shutil.copytree(fake_run, ws)
+ for k in (0, 1):
+ dst = ws / "_cand" / f"c{k}" / "trajectories" / "baseline_r00"
+ dst.parent.mkdir(parents=True)
+ shutil.copytree(fake_run / "trajectories" / "baseline_r00", dst)
+ (ws / "rounds").mkdir(exist_ok=True)
+ (ws / "rounds" / "candidates.json").write_text(json.dumps({"n": 2, "selected": 1}))
+
+ from codeverse.cost import audit_runs
+
+ led = reconstruct(ws)
+ assert find_runs(ws) == [ws], "a candidate sub-workspace is not a separate run"
+ cand_rows = [r for r in led.rows if r.stage is Stage.CANDIDATE]
+ assert len(cand_rows) == 4 and {r.label.split(":")[0] for r in cand_rows} == {"c0", "c1"}
+ waste = audit_runs([ws]).waste_by_kind()
+ assert "lost_candidate" in waste and waste["lost_candidate"][1] > 0
diff --git a/harness/tests/docs_html/__init__.py b/harness/tests/docs_html/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/docs_html/test_architecture_html.py b/harness/tests/docs_html/test_architecture_html.py
new file mode 100644
index 00000000..26038e3c
--- /dev/null
+++ b/harness/tests/docs_html/test_architecture_html.py
@@ -0,0 +1,217 @@
+"""``docs/architecture.html`` must stay valid, self-contained and true to the code.
+
+The page is hand-authored and hand-maintained (see its footer). These tests are the
+guard rails: it has to parse, work offline, keep every relative link and ``data:`` URI
+alive, cover every track and every backend id, and — the one that actually catches
+drift — list *exactly* the tools that ``codeverse.spatial.registry`` currently has.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import re
+from html.parser import HTMLParser
+from pathlib import Path
+
+import pytest
+
+import codeverse.spatial.tools # noqa: F401 — importing registers every tool
+from codeverse.agents.registry import KINDS as AGENT_KINDS
+from codeverse.contracts.common import Track
+from codeverse.models.registry import PROVIDERS
+from codeverse.spatial.registry import list_tools
+
+DOCS = Path(__file__).resolve().parents[2] / "docs"
+PAGE = DOCS / "architecture.html"
+MAX_BYTES = 8 * 1024 * 1024
+
+#: HTML void elements — never on the open-tag stack.
+VOID = frozenset("area base br col embed hr img input link meta param source track wbr".split())
+#: elements whose content is not markup (html.parser already treats these as CDATA)
+RAW_TEXT = frozenset({"script", "style"})
+#: mime types we allow inside a data: URI on this page
+DATA_MIME = frozenset({"image/jpeg", "image/png", "image/gif", "image/webp", "image/svg+xml"})
+#: the non-agent generation backends the page must document alongside AGENT_KINDS
+EXTRA_BACKEND_IDS = ("single-shot",)
+
+
+class Page(HTMLParser):
+ """Collects everything the assertions below need in one pass."""
+
+ def __init__(self) -> None:
+ super().__init__(convert_charrefs=True)
+ self.stack: list[str] = []
+ self.errors: list[str] = []
+ self.ids: set[str] = set()
+ self.links: list[str] = [] # href/src values worth resolving
+ self.data_uris: list[str] = []
+ self.imgs: list[dict[str, str]] = []
+ self.title = ""
+ self._in_title = False
+ # tool-table scraping
+ self._in_tool_table = False
+ self._in_tool_body = False
+ self._cell = 0
+ self._grab_code = False
+ self.tool_names: list[str] = []
+
+ # -- structure -------------------------------------------------------
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ a = {k: (v or "") for k, v in attrs}
+ if tag not in VOID and tag not in RAW_TEXT:
+ self.stack.append(tag)
+ self._note(tag, a)
+
+ def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+ self._note(tag, {k: (v or "") for k, v in attrs})
+
+ def handle_endtag(self, tag: str) -> None:
+ if tag in VOID or tag in RAW_TEXT:
+ return
+ if tag not in self.stack:
+ self.errors.append(f"stray </{tag}> at line {self.getpos()[0]}")
+ return
+ while self.stack:
+ open_tag = self.stack.pop()
+ if open_tag == tag:
+ break
+ self.errors.append(f"</{tag}> closes an unclosed <{open_tag}> at line {self.getpos()[0]}")
+ if tag == "title":
+ self._in_title = False
+ if tag == "table":
+ self._in_tool_table = False
+ if tag == "tbody":
+ self._in_tool_body = False
+
+ # -- content ---------------------------------------------------------
+ def _note(self, tag: str, a: dict[str, str]) -> None:
+ if "id" in a:
+ self.ids.add(a["id"])
+ for key in ("href", "src"):
+ val = a.get(key, "").strip()
+ if not val:
+ continue
+ if val.startswith("data:"):
+ self.data_uris.append(val)
+ elif not val.startswith(("#", "mailto:", "javascript:")):
+ self.links.append(val)
+ if tag == "img":
+ self.imgs.append(a)
+ if tag == "title" and not self.title:
+ self._in_title = True
+ if tag == "table" and a.get("id") == "tool-table":
+ self._in_tool_table = True
+ if tag == "tbody" and self._in_tool_table:
+ self._in_tool_body = True
+ if self._in_tool_body:
+ if tag == "tr":
+ self._cell = 0
+ elif tag in ("td", "th"):
+ self._cell += 1
+ elif tag == "code" and self._cell == 1:
+ self._grab_code = True
+
+ def handle_data(self, data: str) -> None:
+ if self._in_title:
+ self.title += data
+ if self._grab_code:
+ self.tool_names.append(data.strip())
+ self._grab_code = False
+
+
[email protected](scope="module")
+def raw() -> str:
+ assert PAGE.is_file(), f"{PAGE} is missing"
+ return PAGE.read_text(encoding="utf-8")
+
+
[email protected](scope="module")
+def page(raw: str) -> Page:
+ p = Page()
+ p.feed(raw)
+ p.close()
+ return p
+
+
+def test_exists_and_parses(page: Page) -> None:
+ assert not page.errors, "malformed HTML: " + "; ".join(page.errors[:5])
+ unclosed = [t for t in page.stack if t not in ("html", "body")]
+ assert not unclosed, f"unclosed tags: {unclosed}"
+ assert page.title.strip(), "the page needs a <title>"
+ assert "3dcodeverse" in page.title
+
+
+def test_file_stays_small() -> None:
+ size = PAGE.stat().st_size
+ assert size < MAX_BYTES, f"{size / 1e6:.1f} MB — keep the page under {MAX_BYTES / 1e6:.0f} MB"
+
+
+def test_works_offline_no_external_references(raw: str) -> None:
+ """No http(s) reference outside <code>/<pre> text — the page must open by double-click."""
+ stripped = re.sub(r"<(code|pre)\b.*?</\1>", " ", raw, flags=re.S | re.I)
+ hits = re.findall(r"https?://\S{0,60}", stripped)
+ assert not hits, f"external references outside code text: {hits[:5]}"
+
+
+def test_data_uris_are_well_formed(page: Page) -> None:
+ assert len(page.data_uris) >= 5, "the page should embed its screenshots as data: URIs"
+ for uri in page.data_uris:
+ m = re.fullmatch(r"data:([\w.+-]+/[\w.+-]+);base64,([A-Za-z0-9+/]+={0,2})", uri)
+ assert m, f"malformed data: URI (first 80 chars): {uri[:80]!r}"
+ mime, payload = m.group(1), m.group(2)
+ assert mime in DATA_MIME, f"unexpected data: URI mime {mime}"
+ try:
+ blob = base64.b64decode(payload, validate=True)
+ except binascii.Error as e: # pragma: no cover - only on a corrupted page
+ pytest.fail(f"data: URI is not valid base64 ({mime}): {e}")
+ assert len(blob) > 512, f"data: URI payload is suspiciously small ({len(blob)} B)"
+ if mime == "image/jpeg":
+ assert blob[:2] == b"\xff\xd8", "JPEG data: URI has no SOI marker"
+ elif mime == "image/png":
+ assert blob[:8] == b"\x89PNG\r\n\x1a\n", "PNG data: URI has no signature"
+
+
+def test_every_image_has_alt_text(page: Page) -> None:
+ missing = [i.get("src", "")[:40] for i in page.imgs if not i.get("alt", "").strip()]
+ assert not missing, f"{len(missing)} <img> without alt text"
+
+
+def test_relative_links_resolve(page: Page) -> None:
+ broken = []
+ for href in page.links:
+ target = (DOCS / href.split("#", 1)[0]).resolve()
+ if not target.exists():
+ broken.append(href)
+ assert not broken, f"relative links that do not resolve from docs/: {broken}"
+
+
+def test_in_page_anchors_resolve(raw: str, page: Page) -> None:
+ anchors = {m.group(1) for m in re.finditer(r'href="#([^"]+)"', raw)}
+ missing = sorted(a for a in anchors if a not in page.ids)
+ assert not missing, f"href=\"#…\" targets with no matching id: {missing}"
+
+
+def test_a_section_per_track(page: Page) -> None:
+ for track in Track:
+ assert f"track-{track.value}" in page.ids, f"no section for track {track.value}"
+
+
+def test_a_section_per_backend_id(page: Page) -> None:
+ expected = [*PROVIDERS, *AGENT_KINDS, *EXTRA_BACKEND_IDS]
+ for backend in expected:
+ assert f"backend-{backend}" in page.ids, f"no section for backend id {backend!r}"
+
+
+def test_tool_table_matches_the_registry(page: Page) -> None:
+ """The catalogue in the page must be exactly what the registry offers today."""
+ registered = sorted(t.name for t in list_tools())
+ documented = sorted(page.tool_names)
+ assert documented, "no rows found in <table id=\"tool-table\">"
+ missing = sorted(set(registered) - set(documented))
+ extra = sorted(set(documented) - set(registered))
+ assert not missing and not extra, (
+ "docs/architecture.html §06 has drifted from codeverse.spatial.registry — "
+ f"missing rows: {missing}; stale rows: {extra}"
+ )
+ assert len(documented) == len(registered), f"duplicate tool rows: {documented}"
diff --git a/harness/tests/flywheel_cli/test_run_layout_cli.py b/harness/tests/flywheel_cli/test_run_layout_cli.py
new file mode 100644
index 00000000..045fa7d5
--- /dev/null
+++ b/harness/tests/flywheel_cli/test_run_layout_cli.py
@@ -0,0 +1,286 @@
+"""deliverable/ + telemetry/ packaging, `3dcv show`, `3dcv migrate-runs`, and
+export / gallery on BOTH layouts (old runs must keep working)."""
+
+from __future__ import annotations
+
+import json
+import shutil
+from pathlib import Path
+
+from typer.testing import CliRunner
+
+from codeverse.cli.main import app
+from codeverse.contracts.run import RunRecord
+from codeverse.flywheel.deliverable import build_deliverable, deliverable_path, load_deliverable
+from codeverse.flywheel.export import export_samples
+from codeverse.flywheel.gallery import item_from_run, write_gallery
+from codeverse.flywheel.migrate import MIGRATED, UP_TO_DATE, migrate_run, migrate_runs
+from codeverse.flywheel.record import load_record, package_run
+from codeverse.flywheel.telemetry import (
+ build_telemetry,
+ ledger_rows,
+ live_ledger_path,
+ load_telemetry,
+ stage_order,
+)
+from codeverse.workspace import LAYOUT_ALIASES, Workspace
+
+from .conftest import make_fake_run
+
+runner = CliRunner()
+
+
+def strip_layout(ws: Workspace) -> Workspace:
+ """Turn a freshly created workspace back into a pre-2026-08-23 run directory."""
+ for name, _ in LAYOUT_ALIASES:
+ p = ws.root / name
+ if p.is_symlink():
+ p.unlink()
+ for d in (ws.deliverable, ws.telemetry):
+ shutil.rmtree(d, ignore_errors=True)
+ rec = json.loads(ws.record_path.read_text())
+ rec.pop("telemetry", None)
+ rec.pop("deliverable", None)
+ ws.record_path.write_text(json.dumps(rec, indent=2))
+ return ws
+
+
+def old_layout_run(tmp_path: Path, slug: str = "wooden_chair_ab12cd34") -> tuple[Workspace, RunRecord]:
+ ws, rec = make_fake_run(tmp_path / "runs", slug)
+ strip_layout(ws)
+ return ws, load_record(ws)
+
+
+# --------------------------------------------------------------------------- packaging
+def test_package_run_builds_deliverable_and_telemetry(fake_run):
+ ws, rec = fake_run
+ package_run(ws, rec)
+ assert rec.deliverable is not None and rec.telemetry is not None
+ d = rec.deliverable
+ roles = {f.role for f in d.files}
+ assert {"code", "model", "sheet", "manifest"} <= roles
+ assert d.best_round == 1 and d.code_source == "commit"
+ assert d.entry == "deliverable/src/model.py"
+ assert (ws.deliverable / "src" / "model.py").read_text().startswith("# round 1")
+ assert (ws.deliverable / "object.glb").is_file() and (ws.deliverable / "sheet.png").is_file()
+ for f in d.files:
+ assert (ws.root / f.path).is_file() and f.bytes > 0 and len(f.sha256) == 64
+ assert ws.settings_path.is_file() and ws.cost_path.is_file() and ws.usage_path.is_file()
+ cost = json.loads(ws.cost_path.read_text())
+ assert cost["total_usd"] == rec.total_usage.cost_usd
+ assert cost["by_round"] and cost["budget_usd"] == rec.spec.budget.max_usd
+ settings = json.loads(ws.settings_path.read_text())
+ assert {r["role"] for r in settings["roles"]} == {"planner", "generator", "judge", "captioner"}
+ assert settings["rubric"] and settings["rubric_hash"] and settings["price_table_version"]
+
+
+def test_deliverable_rebuild_is_idempotent(fake_run):
+ ws, rec = fake_run
+ first = build_deliverable(ws, rec)
+ files_before = sorted(p.relative_to(ws.deliverable).as_posix() for p in ws.deliverable.rglob("*") if p.is_file())
+ second = build_deliverable(ws, rec)
+ files_after = sorted(p.relative_to(ws.deliverable).as_posix() for p in ws.deliverable.rglob("*") if p.is_file())
+ assert files_before == files_after
+ assert first.generated_at == second.generated_at # unchanged content → no diff
+ assert [(f.path, f.sha256) for f in first.files] == [(f.path, f.sha256) for f in second.files]
+
+
+def test_deliverable_path_prefers_deliverable_then_artifacts(fake_run):
+ ws, rec = fake_run
+ assert deliverable_path(ws, "object.glb") == ws.artifacts / "object.glb"
+ build_deliverable(ws, rec)
+ assert deliverable_path(ws, "object.glb") == ws.deliverable / "object.glb"
+ assert deliverable_path(ws, "nope.glb") is None
+
+
+def test_cost_summary_reconciles_with_the_record_total(fake_run):
+ """The rows come from codeverse.cost (one ledger in the harness); the summary is
+ the run-layout view of them and must always add up to record.total_usage."""
+ ws, rec = fake_run
+ rows, source = ledger_rows(ws)
+ assert source == "reconstructed" # no live cost_ledger.jsonl in this run
+ assert rows and all("stage" in r and "cost_usd" in r for r in rows)
+ tele = build_telemetry(ws, rec, write=False)
+ cost = tele.cost
+ assert cost is not None
+ assert cost.total_usd == rec.total_usage.cost_usd
+ assert abs(cost.ledger_usd - cost.total_usd) < 1e-9
+ assert cost.by_role["judge"] > 0 and cost.unattributed_usd > 0 # judge verdicts + the residual
+ assert {s.stage for s in cost.by_stage} <= set(stage_order())
+ assert cost.budget_usd == rec.spec.budget.max_usd
+
+
+def test_usage_rows_alias_a_live_ledger_instead_of_copying_it(fake_run):
+ ws, rec = fake_run
+ live = live_ledger_path(ws)
+ live.write_text(json.dumps({"stage": "plan", "role": "planner", "label": "plan", "cost_usd": 0.5,
+ "model": "gemini-3.7-flash", "n_calls": 1}) + "\n")
+ tele = build_telemetry(ws, rec)
+ assert tele.files["usage_source"] == "live"
+ assert ws.usage_path.is_symlink() and ws.usage_path.resolve() == live.resolve()
+ assert tele.cost is not None and tele.cost.by_stage[0].stage == "plan"
+
+
+def test_telemetry_degrades_when_the_cost_package_is_unavailable(fake_run, monkeypatch):
+ ws, rec = fake_run
+ import codeverse.flywheel.telemetry as T
+
+ def boom(*_a, **_k):
+ raise ImportError("codeverse.cost is not installed")
+
+ monkeypatch.setattr(T, "live_ledger_path", boom)
+ rows, source = T.ledger_rows(ws)
+ assert rows == [] and source == "unavailable"
+ tele = T.build_telemetry(ws, rec, write=False)
+ assert tele.cost is not None and tele.cost.total_usd == rec.total_usage.cost_usd
+ assert tele.cost.n_calls == 0 and tele.settings is not None # settings never depend on the ledger
+
+
+# --------------------------------------------------------------------------- migration
+def test_migrate_run_is_additive_and_idempotent(tmp_path: Path):
+ ws, _ = old_layout_run(tmp_path)
+ evidence_before = sorted(p.relative_to(ws.root).as_posix() for p in ws.artifacts.rglob("*"))
+ src_before = (ws.src / "model.py").read_bytes()
+
+ plan = migrate_run(ws, dry_run=True)
+ assert plan.status == MIGRATED and plan.layout
+ assert not ws.deliverable.exists() and not ws.telemetry.exists()
+
+ first = migrate_run(ws)
+ assert first.status == MIGRATED and first.record_updated
+ assert ws.deliverable.is_dir() and ws.cost_path.is_file() and ws.evidence.is_symlink()
+ record = load_record(ws)
+ assert record.deliverable is not None and record.telemetry is not None
+
+ before = ws.record_path.read_bytes()
+ second = migrate_run(ws)
+ assert second.status == UP_TO_DATE and not second.record_updated
+ assert ws.record_path.read_bytes() == before
+ # nothing was moved or deleted
+ assert sorted(p.relative_to(ws.root).as_posix() for p in ws.artifacts.rglob("*")) == evidence_before
+ assert (ws.src / "model.py").read_bytes() == src_before
+
+
+def test_migrate_runs_batch_and_partial_runs(tmp_path: Path):
+ runs = tmp_path / "runs"
+ ws_a, _ = make_fake_run(runs, "run_a")
+ strip_layout(ws_a)
+ ws_b, _ = make_fake_run(runs, "run_b")
+ strip_layout(ws_b)
+ ws_b.record_path.unlink() # interrupted run: layout only, no packaging
+ (runs / "not_a_run").mkdir()
+ rep = migrate_runs(runs)
+ assert rep.n_runs == 2 and rep.n_failed == 0 # not_a_run has no spec.json
+ by_run = {Path(m.run).name: m for m in rep.runs}
+ assert by_run["run_a"].deliverable_files and by_run["run_a"].telemetry_rows is not None
+ assert by_run["run_b"].status == MIGRATED and "record.json" in by_run["run_b"].reason
+ assert (ws_b.telemetry).is_dir() and not (ws_b.deliverable / "manifest.json").exists()
+ assert migrate_runs(runs).n_migrated == 0
+
+
+def test_migrate_runs_cli(tmp_path: Path):
+ ws, _ = old_layout_run(tmp_path)
+ r = runner.invoke(app, ["migrate-runs", str(ws.root.parent), "--dry-run"])
+ assert r.exit_code == 0 and "would migrate" in r.output
+ assert not ws.deliverable.exists()
+ r = runner.invoke(app, ["migrate-runs", str(ws.root)]) # a single run directory works too
+ assert r.exit_code == 0 and "migrated" in r.output
+ assert ws.deliverable_manifest_path.is_file()
+
+
+# --------------------------------------------------------------------------- show
+def _show(slug: str, runs_dir: Path, *args: str):
+ return runner.invoke(app, ["show", slug, "--runs-dir", str(runs_dir), *args])
+
+
+def test_show_prints_three_separated_sections(fake_run):
+ ws, rec = fake_run
+ package_run(ws, rec)
+ r = _show(ws.root.name, ws.root.parent)
+ assert r.exit_code == 0, r.output
+ out = r.output
+ assert "DELIVERABLE" in out and "QUALITY EVIDENCE" in out and "COST & SETTINGS" in out
+ assert out.index("DELIVERABLE") < out.index("QUALITY EVIDENCE") < out.index("COST & SETTINGS")
+ assert "deliverable/object.glb" in out and "deliverable/src/model.py" in out
+ assert "static_object_v1" in out # evidence: rubric
+ assert "spent / budget" in out and "models per role" in out and "price table" in out
+ assert "api-agent" in out and "generator" in out # settings: model id per role
+
+
+def test_show_sections_can_be_selected(fake_run):
+ ws, rec = fake_run
+ package_run(ws, rec)
+ r = _show(ws.root.name, ws.root.parent, "--section", "cost")
+ assert r.exit_code == 0 and "COST & SETTINGS" in r.output and "DELIVERABLE" not in r.output
+ assert _show(ws.root.name, ws.root.parent, "--section", "bogus").exit_code == 1
+
+
+def test_status_still_works_and_points_at_show(fake_run):
+ """`3dcv status` keeps its own (unchanged) output and links to the new view."""
+ ws, rec = fake_run
+ package_run(ws, rec)
+ ws.write_json(ws.record_path, rec)
+ r = runner.invoke(app, ["status", ws.root.name, "--runs-dir", str(ws.root.parent)])
+ assert r.exit_code == 0, r.output
+ assert "rounds" in r.output and "passed" in r.output
+ assert f"3dcv show {ws.root.name}" in r.output
+
+
+def test_show_works_on_an_old_layout_run(tmp_path: Path):
+ ws, _ = old_layout_run(tmp_path)
+ r = _show(ws.root.name, ws.root.parent)
+ assert r.exit_code == 0, r.output
+ assert "old layout" in r.output and "computed on the fly" in r.output
+ assert "COST & SETTINGS" in r.output and "models per role" in r.output
+ assert not ws.telemetry.exists() # show never writes
+
+
+# --------------------------------------------------------------------------- export / gallery on both layouts
+def test_export_and_gallery_on_both_layouts(tmp_path: Path):
+ runs = tmp_path / "runs"
+ ws_new, rec_new = make_fake_run(runs, "run_new")
+ package_run(ws_new, rec_new)
+ ws_new.write_json(ws_new.record_path, rec_new)
+ ws_old, _ = make_fake_run(runs, "run_old")
+ strip_layout(ws_old)
+
+ rep = export_samples(runs, tmp_path / "ds")
+ assert rep.n_exported == 2 and not rep.skipped, rep.skipped
+ metas = {p.parent.name: json.loads(p.read_text()) for p in (tmp_path / "ds").rglob("meta.json")}
+ assert metas["run_new"]["telemetry"]["total_usd"] == rec_new.total_usage.cost_usd
+ assert metas["run_new"]["telemetry"]["models"]["judge"]
+ assert metas["run_old"]["telemetry"] == {}
+ for meta in metas.values():
+ assert meta["code_source"] == "commit" and "renders/sheet.png" in meta["renders"]
+
+ out_html = tmp_path / "g.html"
+ path, n = write_gallery(runs, out_html)
+ assert n == 2 and "deliverable" in path.read_text()
+ new_item = item_from_run(ws_new, load_record(ws_new))
+ old_item = item_from_run(ws_old, load_record(ws_old))
+ assert new_item.cost_by_stage == {} or isinstance(new_item.cost_by_stage, dict)
+ assert "deliverable/" in new_item.links and "deliverable/" not in old_item.links
+ assert old_item.links["object.glb"].endswith("artifacts/object.glb")
+ assert new_item.links["object.glb"].endswith("deliverable/object.glb")
+
+
+def test_export_falls_back_to_the_packaged_snapshot_without_git(tmp_path: Path):
+ runs = tmp_path / "runs"
+ ws, rec = make_fake_run(runs, "run_new")
+ package_run(ws, rec)
+ ws.write_json(ws.record_path, rec)
+ shutil.rmtree(ws.root / ".git") # a run copied without its history
+ rep = export_samples(runs, tmp_path / "ds")
+ assert rep.n_exported == 1, rep.skipped
+ meta = json.loads(next((tmp_path / "ds").rglob("meta.json")).read_text())
+ assert meta["code_source"] == "deliverable"
+ assert (next((tmp_path / "ds").rglob("meta.json")).parent / "src" / "model.py").is_file()
+
+
+def test_load_helpers_fall_back_to_files_then_none(fake_run):
+ ws, rec = fake_run
+ assert load_telemetry(ws, rec) is None and load_deliverable(ws, rec) is None
+ package_run(ws, rec)
+ bare = load_record(ws) # record.json on disk has no blocks yet (package_run only mutates in memory)
+ assert bare.telemetry is None
+ assert load_telemetry(ws, bare) is not None and load_deliverable(ws, bare) is not None
diff --git a/harness/tests/models/test_openai.py b/harness/tests/models/test_openai.py
index 28f0fb9c..3ebe905d 100644
--- a/harness/tests/models/test_openai.py
+++ b/harness/tests/models/test_openai.py
@@ -102,8 +102,8 @@ def test_text_reasoning_effort_usage_cost():
20,
10,
)
- # 80*5 + 20*0.5 + 30*30 per 1M
- assert abs(u.cost_usd - (400 + 10 + 900) / 1e6) < 1e-12
+ # gpt-5.6-sol: 80*4.00 + 20*0.40 + 30*20.00 per 1M (pricing checked 2026-08-23)
+ assert abs(u.cost_usd - (320 + 8 + 600) / 1e6) < 1e-12
def test_reasoning_effort_mapping_and_temperature_for_non_reasoning():
diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.py
index 89d2f12a..729b9914 100644
--- a/harness/tests/orchestrator_tracks/fakes.py
+++ b/harness/tests/orchestrator_tracks/fakes.py
@@ -67,6 +67,17 @@ class FakeRuntime:
out.append(f)
(ws.src / "zones").mkdir(exist_ok=True)
(ws.src / "assets").mkdir(exist_ok=True)
+ # like the real skeleton: a stub per planned zone/asset, so a stage that dies
+ # halfway still leaves a buildable workspace
+ for z in getattr(plan, "zones", []) or []:
+ f = ws.src / "zones" / f"{to_snake(z.name)}.js"
+ f.write_text(f"// skeleton zone {z.name}\nexport function build{z.name}(ctx) {{ return null; }}\n")
+ out.append(f)
+ for a in getattr(plan, "assets", []) or []:
+ if a.kind == "threejs":
+ f = ws.src / "assets" / f"{to_snake(a.name)}.js"
+ f.write_text(f"// skeleton asset {a.name}\nexport function build{a.name}(THREE) {{ return null; }}\n")
+ out.append(f)
else:
f = ws.src / "model.py"
f.write_text("# skeleton model.py\nimport bpy\n")
diff --git a/harness/tests/orchestrator_tracks/test_cost_latency.py b/harness/tests/orchestrator_tracks/test_cost_latency.py
new file mode 100644
index 00000000..0a58fb85
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_cost_latency.py
@@ -0,0 +1,466 @@
+"""Cost/latency shaping of the scene baseline: soft budget, single-shot assets,
+zone batching, judge skipping, and the salvage round that stops a budget-stopped
+run from finishing with no score at all."""
+
+from __future__ import annotations
+
+import json
+import shutil
+
+import pytest
+
+from codeverse.config import get_settings
+from codeverse.contracts.common import Budget, Language, Track
+from codeverse.contracts.plan import AssetPlan, ScenePlan, ZonePlan
+from codeverse.contracts.run import RunStatus
+from codeverse.events import EventLog
+from codeverse.orchestrator.budget import BudgetExceeded, BudgetGuard
+from codeverse.orchestrator.rounds import RoundPolicy
+from codeverse.orchestrator.state import RunState
+from codeverse.tracks.common import RunContext
+from codeverse.tracks.planner import plan_example
+from codeverse.tracks.scene import SceneTrack, plan_zone_batches, zone_file
+from codeverse.tracks.scene_asset_gen import (
+ check_threejs_asset,
+ dedupe_assets,
+ select_assets,
+ single_shot_agent_id,
+ single_shot_ctx,
+ variant_index,
+)
+from codeverse.tracks.scene_assets import asset_api_summary, run_asset_stage
+from codeverse.workspace import Workspace
+from tests.orchestrator_tracks.conftest import make_spec
+from tests.orchestrator_tracks.fakes import (
+ FakeAgent,
+ FakeChatModel,
+ FakeJudge,
+ FakeRuntime,
+ FakeServices,
+)
+
+RUNTIME_JS = get_settings().runtime_js_dir()
+needs_node = pytest.mark.skipif(
+ not (shutil.which(get_settings().binaries.node or "node") and (RUNTIME_JS / "node_modules" / "three").is_dir()),
+ reason="node + runtime_js/node_modules required")
+
+
+# ----------------------------------------------------------------------------- soft budget
+def test_soft_budget_degrades_before_the_hard_cap_and_grace_reopens_it():
+ g = BudgetGuard(Budget(max_usd=1.0, max_minutes=60.0), soft_fraction=0.55)
+ assert g.soft_ok() and g.soft_remaining()["usd"] == pytest.approx(0.55)
+ g.add(_usage(0.6))
+ assert not g.soft_ok() and "soft cap" in g.soft_exceeded()
+ assert g.ok() # the HARD ceiling is untouched: degrade, do not die
+ g.add(_usage(0.5))
+ assert not g.ok()
+ with pytest.raises(BudgetExceeded):
+ g.check()
+ g.grant_grace(usd=0.3, minutes=5.0)
+ assert g.ok() and g.hard_usd == pytest.approx(1.3)
+ g.grant_grace(usd=0.1) # never shrinks
+ assert g.hard_usd == pytest.approx(1.3)
+ assert g.summary()["soft_fraction"] == 0.55
+
+
+def test_timeout_is_clipped_to_the_wall_clock_left():
+ g = BudgetGuard(Budget(max_usd=5.0, max_minutes=10.0), soft_fraction=0.5)
+ assert g.timeout_s(1800, floor_s=60) == pytest.approx(300, abs=2) # 50 % of 10 min
+ assert g.timeout_s(120, floor_s=60) == pytest.approx(120, abs=2) # never inflates
+ g.start_time -= 600 # the run is already over its wall clock
+ assert g.timeout_s(1800, floor_s=90) == 90 # floor, never 0
+
+
+def _usage(cost: float):
+ from codeverse.contracts.common import Usage
+
+ return Usage(backend="fake", cost_usd=cost)
+
+
+# ----------------------------------------------------------------------------- dedupe
+def _asset(name: str, size: tuple[float, float, float], kind: str = "threejs") -> AssetPlan:
+ return AssetPlan(name=name, kind=kind, description=f"a {name}", approx_size_m=size)
+
+
+def test_dedupe_folds_near_identical_props_into_one_variant_factory():
+ assets = [_asset("SteppingStone", (0.4, 0.1, 0.4)), _asset("PondRock", (0.8, 0.5, 0.7)),
+ _asset("HeroBoulder", (2.5, 2.0, 2.4)), _asset("StoneLantern", (0.6, 1.4, 0.6))]
+ kept, alias = dedupe_assets(assets)
+ assert [k.name for k in kept] == ["SteppingStone", "HeroBoulder", "StoneLantern"]
+ assert alias == {"PondRock": "SteppingStone"} # same family, sizes within 3×
+ assert variant_index(alias, "PondRock") == 1 and variant_index(alias, "SteppingStone") == 0
+ assert "opts.variant" in kept[0].description and "variant 1 = PondRock" in kept[0].description
+ # HeroBoulder is 6× the stepping stone → a different prop, not a variant
+ assert "HeroBoulder" not in alias
+
+
+def test_dedupe_is_a_no_op_for_unrelated_assets_and_reaches_the_zone_prompt():
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ kept, alias = dedupe_assets(list(plan.assets))
+ assert not alias and len(kept) == len(plan.assets)
+ merged = {"PondRock": "SteppingStone"}
+ api = asset_api_summary(plan.model_copy(update={"assets": [_asset("SteppingStone", (0.4, 0.1, 0.4)),
+ _asset("PondRock", (0.8, 0.5, 0.7))]}), {}, merged)
+ assert "buildSteppingStone(THREE, { variant: 1 })" in api and "merged variant" in api
+
+
+# ----------------------------------------------------------------------------- zone batching
+def _zone(name: str, n: int) -> ZonePlan:
+ from codeverse.contracts.plan import BBox
+
+ return ZonePlan(name=name, description=name, bbox=BBox(center=(0, 0, 0), extents=(10, 5, 10)),
+ contents=[f"A{i}" for i in range(n)])
+
+
+def test_small_zones_share_a_session_and_big_ones_keep_the_fan_out():
+ zones = [_zone("Small1", 2), _zone("Small2", 1), _zone("Big", 6), _zone("Small3", 3)]
+ batches = plan_zone_batches(zones)
+ assert [[z.name for z in b] for b in batches] == [["Small1", "Small2"], ["Big"], ["Small3"]]
+ # deterministic: the same plan always batches the same way (stage hash stability)
+ assert plan_zone_batches(zones) == batches
+ assert zone_file(zones[0]) == "src/zones/small1.js"
+
+
+def test_every_zone_gets_exactly_one_owner_file():
+ zones = [_zone(f"Z{i}", i % 5) for i in range(9)]
+ batches = plan_zone_batches(zones)
+ files = [zone_file(z) for b in batches for z in b]
+ assert sorted(files) == sorted({zone_file(z) for z in zones}) and len(files) == 9
+
+
+# ----------------------------------------------------------------------------- single-shot assets
+def test_single_shot_agent_id_only_derives_from_api_backends():
+ assert single_shot_agent_id("api-agent:gemini:gemini-3.7-flash") == "single-shot:gemini:gemini-3.7-flash"
+ assert single_shot_agent_id("single-shot:gemini:x") == "single-shot:gemini:x"
+ assert single_shot_agent_id("gemini-cli:gemini-3.7-flash") == "" # CLI subscription: no chat model
+ assert single_shot_agent_id("claude-code:opus") == "" and single_shot_agent_id("fake:x") == ""
+
+
+class _ChatServices(FakeServices):
+ """FakeServices that CAN hand out a chat model (so single-shot is reachable)."""
+
+ def __init__(self, model, **kw):
+ super().__init__(**kw)
+ self._chat = model
+ self.chat_ids: list[str] = []
+
+ def chat_model(self, model_id: str):
+ self.chat_ids.append(model_id)
+ return self._chat
+
+
+def _module(pascal: str, w: float = 1.0, h: float = 1.0, d: float = 1.0) -> str:
+ return (f"import * as THREE from 'three';\nexport function build{pascal}(T = THREE, opts = {{}}) {{\n"
+ f" const g = new T.Group();\n"
+ f" const a = new T.Mesh(new T.BoxGeometry({w}, {h * 0.6}, {d}), new T.MeshStandardMaterial({{ color: 0x886644 }}));\n"
+ f" a.position.y = {h * 0.3}; g.add(a);\n"
+ f" const b = new T.Mesh(new T.ConeGeometry({w * 0.4}, {h * 0.4}, 10), new T.MeshStandardMaterial({{ color: 0x224466 }}));\n"
+ f" b.position.y = {h * 0.8}; g.add(b);\n return g;\n}}\n")
+
+
+def _envelope(rel: str, body: str) -> str:
+ return f"=== FILE: {rel} ===\n{body}\n=== END FILE ===\n"
+
+
+def _scene_ctx(tmp_path, settings, *, services, agent=None, plan=None, agent_id="api-agent:gemini:x",
+ max_usd=5.0) -> RunContext:
+ plan = plan or ScenePlan.model_validate(plan_example(Track.SCENE))
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, generator=agent_id, max_usd=max_usd)
+ ws = Workspace(tmp_path / "ws").create()
+ ws.write_json(ws.spec_path, spec)
+ rt = FakeRuntime(Language.SCENE_THREEJS)
+ ctx = RunContext(spec=spec, ws=ws, events=EventLog(ws.events_path), settings=settings,
+ budget=BudgetGuard(spec.budget, soft_fraction=0.55), runtime=rt, services=services,
+ state=RunState(), policy=RoundPolicy(), track=Track.SCENE, rubric="scene_v1",
+ agent_id=agent_id, plan=plan, agent=agent, contract_text="CONTRACT", cookbook_rel="x/cookbook.md")
+ rt.skeleton(ws, plan)
+ ws.commit("skeleton")
+ return ctx
+
+
+def _events(ctx) -> list[dict]:
+ return [json.loads(line) for line in ctx.ws.events_path.read_text().splitlines() if line.strip()]
+
+
+@needs_node
+def test_assets_are_single_shot_by_default_and_never_open_an_agent_session(tmp_path, settings):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ plan = plan.model_copy(update={"assets": [a for a in plan.assets if a.kind == "threejs"]})
+ calls: list[str] = []
+
+ def respond(req):
+ rel = req.messages[0].text.split("write `")[1].split("`")[0]
+ calls.append(rel)
+ pascal = "".join(w.capitalize() for w in rel.rsplit("/", 1)[-1][:-3].split("_"))
+ size = [float(x) for x in req.messages[0].text.split("meters): ")[1].split("\n")[0].split(" × ")]
+ return _envelope(rel, _module(pascal, *size))
+
+ agent = FakeAgent(lambda job, ws: {"src/nope.js": "// should not run\n"})
+ services = _ChatServices(FakeChatModel(respond, cost=0.02), judge=FakeJudge(scores=(0.4,)))
+ ctx = _scene_ctx(tmp_path, settings, services=services, agent=agent, plan=plan)
+ results = run_asset_stage(ctx)
+ assert set(results) == {a.name for a in plan.assets}
+ assert all(r.ok and r.strategy == "single-shot" for r in results.values())
+ assert not agent.jobs, "a single-shot asset must not open a coding-agent session"
+ assert sorted(calls) == sorted(f"src/assets/{n}" for n in ("bollard.js", "fishing_boat.js"))
+ # measured size comes from the deterministic check, not the plan guess
+ assert results["FishingBoat"].size_m is not None
+ ev = {e["event"] for e in _events(ctx)}
+ assert "asset.generated" in ev and "assets.done" in ev
+
+
+@needs_node
+def test_a_broken_asset_gets_one_error_feedback_repair_then_escalates_to_an_agent(tmp_path, settings):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ one = [a for a in plan.assets if a.kind == "threejs"][:1]
+ plan = plan.model_copy(update={"assets": one, "zones": []})
+ prompts: list[str] = []
+
+ def respond(req):
+ prompts.append(req.messages[0].text)
+ rel = "src/assets/fishing_boat.js"
+ # both single-shot attempts return a module with a removed-API call
+ return _envelope(rel, "import * as THREE from 'three';\n"
+ "export function buildFishingBoat(T = THREE) {\n"
+ " return new T.Mesh(new T.BoxBufferGeometry(1, 1, 1));\n}\n")
+
+ agent = FakeAgent(lambda job, ws: {"src/assets/fishing_boat.js": _module("FishingBoat", 8.0, 3.5, 3.0)})
+ services = _ChatServices(FakeChatModel(respond, cost=0.02), judge=FakeJudge(scores=(0.9,)))
+ ctx = _scene_ctx(tmp_path, settings, services=services, agent=agent, plan=plan)
+ results = run_asset_stage(ctx)
+ assert len(prompts) == 2, "exactly ONE error-feedback repair before escalating"
+ assert "did NOT pass the deterministic asset check" in prompts[1] and "BoxBufferGeometry" in prompts[1]
+ assert [j.label for j in agent.jobs] == ["asset_fishing_boat"]
+ assert results["FishingBoat"].ok and results["FishingBoat"].strategy == "escalated"
+ ev = [e for e in _events(ctx) if e["event"] == "asset.escalated"]
+ assert ev and ev[0]["asset"] == "FishingBoat"
+
+
+@needs_node
+def test_small_clean_assets_skip_the_judge_and_heroes_do_not(tmp_path, settings):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ small = _asset("Bollard", (0.3, 0.5, 0.3))
+ plan = plan.model_copy(update={"assets": [small], "zones": []})
+
+ def respond(req):
+ return _envelope("src/assets/bollard.js", _module("Bollard", 0.3, 0.5, 0.3))
+
+ judge = FakeJudge(scores=(0.2,))
+ services = _ChatServices(FakeChatModel(respond), judge=judge)
+ ctx = _scene_ctx(tmp_path, settings, services=services, agent=FakeAgent(lambda j, w: None), plan=plan)
+ # the scene runtime grows a render_asset hook: without the skip rule this would judge
+ ctx.runtime.render_asset = lambda ws, name, out_dir: services.render_object( # type: ignore[attr-defined]
+ ws.artifacts / "x.glb", out_dir, views=(), width=64, height=64)
+ run_asset_stage(ctx)
+ skipped = [e for e in _events(ctx) if e["event"] == "asset.judge_skipped"]
+ assert skipped and skipped[0]["reason"] == "gates_ok_and_small" and skipped[0]["volume_fraction"] < 0.05
+ assert not judge.calls
+
+
+def test_asset_check_names_the_file_that_was_never_written(tmp_path, settings):
+ services = FakeServices()
+ ctx = _scene_ctx(tmp_path, settings, services=services)
+ chk = check_threejs_asset(ctx, "src/assets/missing.js", "Missing")
+ assert not chk.ok and chk.ran and chk.fatal and "was not written" in chk.errors[0]
+
+
+def test_single_shot_ctx_is_none_for_cli_backends(tmp_path, settings):
+ ctx = _scene_ctx(tmp_path, settings, services=FakeServices(), agent_id="gemini-cli:gemini-3.7-flash")
+ assert single_shot_ctx(ctx) is None
+ ctx2 = _scene_ctx(tmp_path, settings, services=FakeServices(), agent_id="api-agent:gemini:x")
+ assert single_shot_ctx(ctx2) is None # FakeServices has no chat model → agent path stays
+
+
+# ----------------------------------------------------------------------------- salvage
+def _planner(payload):
+ return FakeChatModel(lambda req: payload)
+
+
+def test_a_budget_stop_before_round_zero_still_delivers_a_judged_round(tmp_path, settings):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ plan.assets = [a for a in plan.assets if a.kind == "threejs"]
+ for z in plan.zones:
+ z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=1, max_usd=5.0)
+ ws = Workspace(tmp_path / "runs" / "greenhouse")
+ services = FakeServices(assemble=True)
+
+ def writer(job, ws_):
+ if job.label.startswith("zones_") or job.label.startswith("zone_"):
+ # the greenhouse hole: the zone fan-out crosses the ceiling mid-stage
+ raise BudgetExceeded("cost $9.99 exceeds max_usd $5.00", spent_usd=9.99, elapsed_min=61.0)
+ if job.label == "env":
+ return {"src/env.js": "export function buildEnv(){}\n"}
+ return {f"src/assets/{job.label[6:]}.js": f"export function build(){{}} // {job.label}\n"}
+
+ track = SceneTrack(services=services, judge=FakeJudge(scores=(0.58,)), agent=FakeAgent(writer),
+ planner_model=_planner(plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.SCENE_THREEJS))
+ rec = track.run(spec, ws)
+ assert rec.status is RunStatus.BUDGET and rec.extra["stop_reason"] == "budget"
+ # …and, unlike the greenhouse run, it has a score
+ assert rec.best_round == 0 and rec.final_score == pytest.approx(0.58)
+ assert len(rec.rounds) == 1 and rec.rounds[0].renders is not None
+ assert "salvaged" in rec.rounds[0].notes
+ ev = [json.loads(x) for x in (ws.root / "events.jsonl").read_text().splitlines() if x.strip()]
+ names = [e["event"] for e in ev]
+ assert "budget.salvage" in names and names.count("best.updated") == 1
+ salvage = next(e for e in ev if e["event"] == "budget.salvage")
+ assert salvage["grace_usd"] > 0 and salvage["grace_minutes"] > 0
+
+
+def test_soft_budget_notes_land_in_the_round_record(tmp_path, settings):
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ plan.assets = [a for a in plan.assets if a.kind == "threejs"]
+ for z in plan.zones:
+ z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0, max_usd=5.0)
+ ws = Workspace(tmp_path / "runs" / "degraded")
+ services = FakeServices(assemble=True)
+ # an expensive agent: the soft cap (55 % of $5) is crossed during the asset stage
+ agent = FakeAgent(_writer, cost=1.1)
+ track = SceneTrack(services=services, judge=FakeJudge(scores=(0.5,)), agent=agent,
+ planner_model=_planner(plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.SCENE_THREEJS))
+ rec = track.run(spec, ws)
+ ev = [json.loads(x) for x in (ws.root / "events.jsonl").read_text().splitlines() if x.strip()]
+ degraded = [e for e in ev if e["event"] == "budget.degraded"]
+ assert degraded, "the soft cap must be reported before the hard cap kills the run"
+ assert any("soft budget spent" in n for n in degraded[0]["note"].split(";")[:1] or [degraded[0]["note"]])
+ assert any("soft budget spent" in n for n in rec.rounds[0].notes.split("; "))
+
+
+def _writer(job, ws):
+ if job.label.startswith("zones_") or job.label.startswith("zone_"):
+ return {rel: "export function build(){}\n" for rel in (job.files_hint or ["src/zones/x.js"])}
+ if job.label == "env":
+ return {"src/env.js": "export function buildEnv(){}\n"}
+ return {f"src/assets/{job.label[6:]}.js": "export function build(){}\n"}
+
+
+@needs_node
+def test_a_merged_asset_leaves_a_working_shim_not_the_placeholder_box(tmp_path, settings, monkeypatch):
+ """Over the cap, twins merge — and a zone that imports the merged name must still
+ get the real prop, not the skeleton's blockout box."""
+ import codeverse.tracks.scene_assets as sa
+
+ monkeypatch.setattr(sa, "MAX_ASSETS", 1) # force the rescue path with a tiny plan
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ plan = plan.model_copy(update={"assets": [_asset("PondRock", (1.1, 0.75, 0.9)),
+ _asset("SteppingStone", (0.65, 0.12, 0.55))], "zones": []})
+
+ def respond(req):
+ rel = req.messages[0].text.split("write `")[1].split("`")[0]
+ return _envelope(rel, _module("PondRock", 1.1, 0.75, 0.9))
+
+ services = _ChatServices(FakeChatModel(respond), judge=FakeJudge(scores=(0.9,)))
+ ctx = _scene_ctx(tmp_path, settings, services=services, agent=FakeAgent(lambda j, w: None), plan=plan)
+ results = run_asset_stage(ctx)
+ assert set(results) == {"PondRock"}, "the twin is a variant of the survivor, not a second build"
+ shim = ctx.ws.src / "assets" / "stepping_stone.js"
+ assert shim.is_file() and "variant: 1" in shim.read_text() and "from './pond_rock.js'" in shim.read_text()
+ chk = check_threejs_asset(ctx, "src/assets/stepping_stone.js", "SteppingStone")
+ assert chk.ok and chk.meshes == 2, "the shim resolves to the real factory, not the blockout stub"
+
+
+def test_every_planned_asset_is_built_while_the_plan_fits_under_the_cap():
+ """Dedupe is a cap rescue: a distinct prop is worth more than a variant flag."""
+ twins = [_asset("PondRock", (1.1, 0.75, 0.9)), _asset("SteppingStone", (0.65, 0.12, 0.55))]
+ kept, alias = select_assets(twins, cap=8)
+ assert [k.name for k in kept] == ["PondRock", "SteppingStone"] and not alias
+ kept, alias = select_assets(twins, cap=1)
+ assert [k.name for k in kept] == ["PondRock"] and alias == {"SteppingStone": "PondRock"}
+
+
+def test_over_the_cap_folding_beats_truncation():
+ """8 planned props, cap 4: folding rescues twins that truncation would delete."""
+ assets = [_asset("HeroBoulder", (2.4, 2.0, 2.2)), _asset("Bench", (1.6, 0.9, 0.6)),
+ _asset("Lantern", (0.4, 1.2, 0.4)), _asset("Crate", (0.6, 0.5, 0.6)),
+ _asset("TalusRock", (1.8, 1.4, 1.6)), _asset("Stool", (0.5, 0.6, 0.5)),
+ _asset("Box", (0.5, 0.4, 0.5)), _asset("Sconce", (0.3, 0.5, 0.2))]
+ kept, alias = select_assets(assets, cap=4)
+ assert len(kept) == 4 and [k.name for k in kept] == ["HeroBoulder", "Bench", "Lantern", "Crate"]
+ # every survivor's twin is reachable as a variant instead of vanishing
+ assert alias == {"TalusRock": "HeroBoulder", "Stool": "Bench", "Box": "Crate", "Sconce": "Lantern"}
+ assert all(v in {k.name for k in kept} for v in alias.values())
+
+
+def test_a_batched_session_that_writes_only_one_file_fails_the_other_zone(tmp_path, settings):
+ """The skeleton leaves a stub at every zone path, so 'the file exists' proves nothing."""
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ plan = plan.model_copy(update={"assets": [_asset("Bollard", (0.3, 0.5, 0.3))],
+ "zones": [_zone("Quay", 0), _zone("Water", 0)]})
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0)
+ ws = Workspace(tmp_path / "runs" / "halfzone")
+ services = FakeServices(assemble=True)
+
+ def writer(job, ws_):
+ if job.label.startswith("zones_"):
+ return {"src/zones/quay.js": "export function build(){}\n"} # Water never written
+ if job.label == "env":
+ return {"src/env.js": "export function buildEnv(){}\n"}
+ return {"src/x.js": "// x\n"}
+
+ track = SceneTrack(services=services, judge=FakeJudge(scores=(0.6,)), agent=FakeAgent(writer),
+ planner_model=FakeChatModel(lambda req: plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.SCENE_THREEJS))
+ track.run(spec, ws)
+ zones = json.loads((ws.root / "stages" / "zones.json").read_text())["result"]
+ assert zones["Quay"]["ok"] and not zones["Water"]["ok"]
+
+
+@needs_node
+def test_an_imperfect_asset_stays_available_but_a_broken_one_does_not(tmp_path, settings):
+ """Wrong size = worth one repair; won't import = zones must not reference it."""
+ services = FakeServices()
+ ctx = _scene_ctx(tmp_path, settings, services=services)
+ (ctx.ws.src / "assets").mkdir(parents=True, exist_ok=True)
+ (ctx.ws.src / "assets" / "small.js").write_text(_module("Small", 0.5, 0.5, 0.5))
+ off = check_threejs_asset(ctx, "src/assets/small.js", "Small", expected_size_m=(4.0, 4.0, 4.0))
+ assert not off.ok and not off.fatal and "rescale" in off.errors[0]
+ (ctx.ws.src / "assets" / "broken.js").write_text(
+ "import * as THREE from 'three';\nexport function nope() { return 1; }\n")
+ bad = check_threejs_asset(ctx, "src/assets/broken.js", "Broken")
+ assert not bad.ok and bad.fatal and "missing export" in bad.errors[0]
+
+
+def test_a_scene_round_judged_at_the_ceiling_is_still_promoted(tmp_path, settings):
+ """The batch-2 promotion order must hold for scenes too: the verdict is paid for,
+ recorded and promoted BEFORE the loop notices the budget is gone — and the salvage
+ must not then run a second round 0 on top of it."""
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ plan.assets = [a for a in plan.assets if a.kind == "threejs"]
+ for z in plan.zones:
+ z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]
+ spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=2, max_usd=0.10)
+ ws = Workspace(tmp_path / "runs" / "ceiling")
+ judge = FakeJudge(scores=(0.61,), cost=0.5) # the single verdict blows max_usd
+ track = SceneTrack(services=FakeServices(assemble=True), judge=judge, agent=FakeAgent(_writer, cost=0.001),
+ planner_model=_planner(plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.SCENE_THREEJS))
+ rec = track.run(spec, ws)
+ assert rec.status is RunStatus.BUDGET and rec.best_round == 0 and rec.final_score == pytest.approx(0.61)
+ assert len(rec.rounds) == 1 and rec.rounds[0].judgment is not None
+ names = [json.loads(x)["event"] for x in (ws.root / "events.jsonl").read_text().splitlines() if x.strip()]
+ assert names.index("best.updated") < names.index("stop")
+ assert "budget.salvage" not in names, "round 0 already exists: nothing to salvage"
+ assert len(judge.calls) == 1
+
+
+def test_a_model_outage_escalates_the_asset_instead_of_losing_it(tmp_path, settings):
+ """A 503 storm that outlives the model layer's retries must fall through to the
+ agent session, not mark the asset NOT AVAILABLE for every zone."""
+ plan = ScenePlan.model_validate(plan_example(Track.SCENE))
+ plan = plan.model_copy(update={"assets": [_asset("Bollard", (0.3, 0.5, 0.3))], "zones": []})
+
+ def boom(req):
+ raise RuntimeError("Gemini API error 503: This model is currently experiencing high demand.")
+
+ agent = FakeAgent(lambda job, ws: {"src/assets/bollard.js": _module("Bollard", 0.3, 0.5, 0.3)})
+ services = _ChatServices(FakeChatModel(boom), judge=FakeJudge(scores=(0.9,)))
+ ctx = _scene_ctx(tmp_path, settings, services=services, agent=agent, plan=plan)
+ results = run_asset_stage(ctx)
+ assert results["Bollard"].ok and results["Bollard"].strategy == "escalated"
+ assert [j.label for j in agent.jobs] == ["asset_bollard"]
+ failed = [e for e in _events(ctx) if e["event"] == "asset.generate_failed"]
+ assert failed and "503" in failed[0]["error"]
diff --git a/harness/tests/orchestrator_tracks/test_prompts_assets.py b/harness/tests/orchestrator_tracks/test_prompts_assets.py
index 3b42bed8..c3c137c2 100644
--- a/harness/tests/orchestrator_tracks/test_prompts_assets.py
+++ b/harness/tests/orchestrator_tracks/test_prompts_assets.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import re
+
from codeverse.contracts.common import Language, Track
from codeverse.contracts.plan import ArticulatedPlan, ScenePlan
from codeverse.events import EventLog
@@ -21,6 +23,24 @@ TEMPLATES = {"plan_static", "plan_articulated", "plan_scene", "generate_static",
"scene_asset", "scene_env", "scene_zone", "scene_compose", "scene_refine"}
+def _asset_module(job) -> str:
+ """A three.js asset module that passes the deterministic asset check (js), else a stub."""
+ rel = job.prompt.split("write `")[1].split("`")[0] if "write `" in job.prompt else ""
+ if not rel.endswith(".js"):
+ return f"# {job.label}\n"
+ pascal = "".join(w.capitalize() for w in rel.rsplit("/", 1)[-1][:-3].split("_"))
+ m = re.search(r"meters\): ([\d.]+) × ([\d.]+) × ([\d.]+)", job.prompt)
+ w, h, d = (float(x) for x in m.groups()) if m else (1.0, 1.0, 1.0)
+ return (f"// {job.label}\nimport * as THREE from 'three';\n"
+ f"export function build{pascal}(T = THREE, opts = {{}}) {{\n"
+ " const g = new T.Group();\n"
+ f" const body = new T.Mesh(new T.BoxGeometry({w}, {h * 0.8}, {d}), new T.MeshStandardMaterial({{ color: 0x886644 }}));\n"
+ f" body.position.y = {h * 0.4};\n g.add(body);\n"
+ f" const top = new T.Mesh(new T.SphereGeometry({min(w, d) * 0.2}, 12, 8), new T.MeshStandardMaterial({{ color: 0x224466 }}));\n"
+ f" top.position.y = {h * 0.8};\n g.add(top);\n"
+ " return g;\n}\n")
+
+
def _ctx(tmp_ws, settings, spec, plan, *, agent_id="single-shot:gemini:x", services=None, agent=None) -> RunContext:
lang = spec.language
return RunContext(spec=spec, ws=tmp_ws, events=EventLog(tmp_ws.events_path), settings=settings, budget=BudgetGuard(spec.budget),
@@ -57,7 +77,7 @@ def test_scene_templates_render_and_asset_stage_with_blender(tmp_ws, settings):
spec = make_spec(Track.SCENE, Language.SCENE_THREEJS)
judge = FakeJudge(scores=(0.5, 0.9))
services = FakeServices(judge=judge)
- agent = FakeAgent(lambda job, ws: {job.prompt.split("write `")[1].split("`")[0] if "write `" in job.prompt else "src/x.js": f"// {job.label}\n"})
+ agent = FakeAgent(lambda job, ws: {job.prompt.split("write `")[1].split("`")[0] if "write `" in job.prompt else "src/x.js": _asset_module(job)})
ctx = _ctx(tmp_ws, settings, spec, plan, agent_id="fake:x", services=services, agent=agent)
ctx.runtime.skeleton(tmp_ws, plan)
tmp_ws.commit("skeleton")
diff --git a/harness/tests/orchestrator_tracks/test_tracks.py b/harness/tests/orchestrator_tracks/test_tracks.py
index d03bc41f..7f37f3e6 100644
--- a/harness/tests/orchestrator_tracks/test_tracks.py
+++ b/harness/tests/orchestrator_tracks/test_tracks.py
@@ -185,6 +185,8 @@ def _scene_writer(job, ws):
return {f"src/assets/{label[6:]}.js": f"export function build(){{}} // {label}\n"}
if label == "env":
return {"src/env.js": "export function buildEnv(){}\n"}
+ if label.startswith("zones_"): # batched small zones: ONE session owns several files
+ return {rel: f"export function build(){{}} // {label}\n" for rel in job.files_hint}
if label.startswith("zone_"):
return {f"src/zones/{label[5:]}.js": f"export function build(){{}} // {label}\n"}
if label == "compose":
@@ -207,12 +209,14 @@ def test_scene_track_stages_and_rounds(tmp_path, settings):
planner_model=_planner(plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.SCENE_THREEJS))
rec = track.run(spec, ws)
labels = [j.label for j in agent.jobs]
- assert set(labels[:2]) == {"asset_fishing_boat", "asset_bollard"} and "env" in labels and "zone_quay" in labels and "zone_water" in labels
+ # Quay and Water are both small zones (≤ 3 placements) → ONE batched session owning both files
+ assert set(labels[:2]) == {"asset_fishing_boat", "asset_bollard"} and "env" in labels and "zones_quay_water" in labels
assert "compose" in labels # assembler unavailable → composer agent fallback
- assert labels.index("env") < labels.index("zone_quay") < labels.index("compose")
+ assert labels.index("env") < labels.index("zones_quay_water") < labels.index("compose")
assert (ws.src / "assets" / "fishing_boat.js").is_file() and (ws.src / "zones" / "quay.js").is_file() and (ws.src / "scene.js").is_file()
- zone_prompt = next(j.prompt for j in agent.jobs if j.label == "zone_quay")
+ zone_prompt = next(j.prompt for j in agent.jobs if j.label == "zones_quay_water")
assert "buildFishingBoat" in zone_prompt and "8.00×3.50×3.00" in zone_prompt and "Neighbouring zones" in zone_prompt
+ assert "2 zone modules in ONE session" in zone_prompt and zone_prompt.count("## This zone") == 2
assert [r.kind for r in rec.rounds] == ["baseline", "refine"] and rec.rounds[0].renders is not None
assert rec.rounds[0].renders.views and rec.status in (RunStatus.PLATEAU, RunStatus.PASSED)
st = RunState.load(ws)
diff --git a/harness/tests/scene_prompts/__init__.py b/harness/tests/scene_prompts/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/harness/tests/scene_prompts/test_prompt_assembler_contract.py b/harness/tests/scene_prompts/test_prompt_assembler_contract.py
new file mode 100644
index 00000000..9812e11d
--- /dev/null
+++ b/harness/tests/scene_prompts/test_prompt_assembler_contract.py
@@ -0,0 +1,77 @@
+"""The scene track's prompts must describe the interface the harness ACTUALLY calls.
+
+The scene track never lets the model write `src/scene.js`: `languages.scene_threejs.assemble`
+generates it and is the only caller of `src/env.js` and `src/zones/*.js`. When a prompt
+teaches a different signature the model either wastes tokens on defensive shims or —
+worse — writes an animation hook nothing calls (the `nothing_moves` defect that cost three
+of the four v1 bench scenes a grade). These tests pin the prompts to the generated file.
+"""
+
+from __future__ import annotations
+
+import re
+
+import pytest
+
+from codeverse.contracts.plan import CameraPlan
+from codeverse.languages.scene_threejs.assemble import render_scene_js
+from codeverse.prompts import load_text
+
+CAMS = [CameraPlan(name="Establishing", position=(1.0, 2.0, 3.0), look_at=(0.0, 1.0, 0.0), fov=44.0)]
+
+
[email protected](scope="module")
+def generated() -> str:
+ return render_scene_js(["pond_basin"], CAMS, [], env_ok=True)
+
+
[email protected](scope="module")
+def zone_prompt() -> str:
+ return load_text("tracks/scene_zone.j2")
+
+
[email protected](scope="module")
+def env_prompt() -> str:
+ return load_text("tracks/scene_env.j2")
+
+
+def test_generated_scene_js_is_what_we_think_it_is(generated: str) -> None:
+ """Guard the four call sites the prompts promise (if this changes, the prompts must)."""
+ assert "import { build as buildPondBasin } from './zones/pond_basin.js';" in generated
+ assert "const env = (await buildEnv(ctx)) || {};" in generated
+ assert "if (env.update) env.update(t, dt);" in generated
+ assert "for (const z of zones) if (z.userData.update) z.userData.update(t, dt);" in generated
+ assert "tickEnv" not in generated and "userData.tick" not in generated
+
+
+def test_zone_prompt_teaches_the_export_and_hook_the_assembler_calls(zone_prompt: str) -> None:
+ assert "export function build(ctx)" in zone_prompt
+ assert "userData.update" in zone_prompt
+ # the historical bug: the prompt asked for `userData.tick`, a hook nothing calls.
+ # It may only appear now as an explicit warning.
+ for line in zone_prompt.splitlines():
+ if "userData.tick" in line:
+ assert "never called" in line, f"zone prompt still advertises userData.tick: {line!r}"
+
+
+def test_env_prompt_teaches_ctx_signature_and_update(env_prompt: str) -> None:
+ assert "buildEnv(ctx)" in env_prompt
+ assert "buildEnv(THREE, scene)" not in env_prompt
+ assert "update(t, dt)" in env_prompt
+ assert "tickEnv" in env_prompt and "NEVER called" in env_prompt
+ # the assembler greps this out of env.js to place the overview cameras
+ assert "SUN_AZIMUTH_DEG" in env_prompt
+
+
+def test_env_prompt_sun_azimuth_matches_the_assembler_regex(env_prompt: str) -> None:
+ from codeverse.languages.scene_threejs.assemble import _SUN_RE
+
+ example = re.search(r"`?export const SUN_AZIMUTH_DEG[^`\n]*", env_prompt)
+ assert example, "env prompt must show the export the assembler looks for"
+ assert _SUN_RE.search("export const SUN_AZIMUTH_DEG = 235;")
+
+
+def test_asset_prompt_uses_the_hook_zones_can_forward() -> None:
+ text = load_text("tracks/scene_asset.j2")
+ assert "group.userData.update" in text
+ assert "`userData.tick` is never called" in text
diff --git a/harness/tests/scene_prompts/test_quality_teaching.py b/harness/tests/scene_prompts/test_quality_teaching.py
new file mode 100644
index 00000000..7623aaf2
--- /dev/null
+++ b/harness/tests/scene_prompts/test_quality_teaching.py
@@ -0,0 +1,117 @@
+"""What the scene prompts, cookbook and rubric must TEACH about picture quality.
+
+Every item here maps to a defect the v1 bench judges actually wrote up (flat ground,
+identical cones, hard world edge, diorama-on-a-plane, undressed, monochrome light,
+invisible motion). The tests are cheap guards that the teaching does not silently
+disappear from a prompt during a refactor.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse.judges.rubrics import load_rubric
+from codeverse.prompts import load_text
+
+#: chapters the prompts point the agent at by name (read_cookbook matches on the title)
+QUALITY_CHAPTERS = [
+ "Ground that reads real",
+ "Horizon: the world must not end",
+ "Vegetation that reads real",
+ "Rocks, cliffs and boulders that read organic",
+ "Set dressing",
+ "Scene layering",
+ "Atmosphere: time-of-day triads",
+ "Motion you can SEE",
+ "The exact contract the harness assembler enforces",
+]
+
+
[email protected](scope="module")
+def cookbook() -> str:
+ return load_text("scene_threejs/cookbook.md")
+
+
[email protected]("title", QUALITY_CHAPTERS)
+def test_cookbook_has_the_quality_chapter(cookbook: str, title: str) -> None:
+ headings = [ln[3:].strip() for ln in cookbook.splitlines() if ln.startswith("## ")]
+ assert any(h.startswith(title) for h in headings), f"missing chapter {title!r}; have {headings}"
+
+
[email protected]("title", QUALITY_CHAPTERS)
+def test_cookbook_chapter_is_findable_by_read_cookbook(cookbook: str, title: str) -> None:
+ from codeverse.spatial.cookbook_tool import find_section, split_sections
+
+ s = find_section(split_sections(cookbook), title)
+ assert s is not None and s.title.startswith(title)
+
+
+def test_cookbook_carries_the_numbers_the_recipes_depend_on(cookbook: str) -> None:
+ for token in ("vertexColors", "setColorAt", "InstancedMesh", "shadow.mapSize",
+ "cameraMask", "buildHorizonRing", "TIME_OF_DAY", "hazeMix"):
+ assert token in cookbook, token
+
+
+def test_planner_asks_for_density_layering_and_subject_framing() -> None:
+ text = load_text("tracks/plan_scene.j2")
+ for token in ("DENSITY COUNTS", "DEPTH ROLE", "foreground frame", "silhouette ring",
+ "HERO motion", "fill hue", "SUBJECT"):
+ assert token in text, token
+
+
+def test_zone_prompt_demands_variation_dressing_and_visible_motion() -> None:
+ text = load_text("tracks/scene_zone.j2")
+ for token in ("3 distinct silhouettes", "hue jitter", "density counts",
+ "foreground frame", "nothing_moves", "cameraMask"):
+ assert token in text, token
+
+
+def test_env_prompt_demands_blended_ground_horizon_and_colour_contrast() -> None:
+ text = load_text("tracks/scene_env.j2")
+ for token in ("flat_ground", "silhouette ring", "fog far", "60", "Shadow texel"):
+ assert token in text, token
+
+
+def test_refine_prompt_maps_judge_complaints_to_chapters() -> None:
+ text = load_text("tracks/scene_refine.j2")
+ for title in ("Ground that reads real", "Horizon: the world must not end",
+ "Vegetation that reads real", "Set dressing", "Scene layering",
+ "Atmosphere: time-of-day triads", "Motion you can SEE"):
+ assert title in text, title
+
+
+# --------------------------------------------------------------------------- rubric
+COMPOSITION_DEFECTS = ("flat_ground", "monotonous_vegetation", "empty_midground",
+ "undressed_scene", "thin_atmosphere")
+
+
+def test_scene_rubric_scores_the_composition_defects() -> None:
+ r = load_rubric("scene_v1")
+ ids = {d.id for d in r.defects}
+ assert set(COMPOSITION_DEFECTS) <= ids
+ for did in COMPOSITION_DEFECTS:
+ d = r.defect(did)
+ assert 0.0 < d.penalty <= 0.05, f"{did}: keep the new craft penalties small"
+ assert d.cap is None, f"{did}: craft defects inform, they do not cap"
+
+
+def test_scene_rubric_penalties_cannot_zero_a_good_scene() -> None:
+ r = load_rubric("scene_v1")
+ assert sum(d.penalty for d in r.defects) <= 0.62
+
+
+def test_scene_rubric_has_the_diorama_anchor() -> None:
+ r = load_rubric("scene_v1")
+ comp = r.criterion("composition_and_camera")
+ assert "0.5" in comp.anchors and "diorama" in comp.anchors["0.5"].lower()
+ assert "foreground" in comp.anchors["1.0"].lower()
+
+
+def test_extra_anchor_levels_reach_the_judge_prompt() -> None:
+ from codeverse.judges.prompt_builder import _rubric_block
+
+ block = _rubric_block(load_rubric("scene_v1"))
+ assert "0.5: The scene reads as a diorama" in block
+ # the four required levels are still rendered, richest first
+ idx = [block.index(f" {lvl}: ") for lvl in ("1.0", "0.7", "0.4", "0.1")]
+ assert idx == sorted(idx)
diff --git a/harness/tests/scene_runtime/test_backdrop.py b/harness/tests/scene_runtime/test_backdrop.py
new file mode 100644
index 00000000..6d369ea0
--- /dev/null
+++ b/harness/tests/scene_runtime/test_backdrop.py
@@ -0,0 +1,76 @@
+"""One backdrop classifier for the census and the coverage instrument.
+
+`lib/host_census.mjs` (what `content_bbox` covers) and `lib/host_coverage.mjs`
+(what `content_frac` measures) used to carry two copies of the same sky/ground
+rules; both now call `lib/backdrop.mjs`. If a copy ever comes back, the census
+and the per-frame coverage can disagree about what "content" is — which is
+exactly what the frame gate and the orbit framing depend on.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+
+import pytest
+
+from codeverse.config import get_settings
+from tests.scene_runtime.conftest import needs_node, run_node_json
+
+pytestmark = [pytest.mark.node, needs_node]
+
+RUNTIME_JS = get_settings().runtime_js_dir()
+
+CASES = [
+ # (name, box size [sx, sy, sz], instanced, content span, expected)
+ ("SkyDome", [400, 200, 400], False, 0, "sky"),
+ ("Anything", [3000, 10, 3000], False, 0, "sky"),
+ ("GroundPlane", [60, 0.2, 60], False, 0, "ground"),
+ ("Terrain", [30, 1.0, 30], False, 0, "ground"), # named ground, flat enough
+ ("Meadow", [100, 0.5, 100], False, 0, "ground"), # unnamed but very wide + flat
+ ("Grass", [80, 1.0, 80], True, 0, "content"), # scatter: instanced wins
+ ("Cabin", [6, 4, 5], False, 0, "content"),
+ ("Path", [30, 0.1, 30], False, 5, "ground"), # far larger than the content bbox
+ ("Path", [30, 0.1, 30], False, 0, "content"), # same box, no content bbox known
+ ("Rug", [3, 0.05, 3], False, 40, "content"), # small relative to content: not backdrop
+]
+
+
+def _classify(cases):
+ body = f"""
+import {{ classifyBackdrop }} from '{RUNTIME_JS}/lib/backdrop.mjs';
+const cases = {json.dumps(cases)};
+const out = cases.map(([name, size, instanced, span]) => classifyBackdrop(
+ {{ name, isInstancedMesh: instanced }},
+ {{ min: {{ x: -size[0] / 2, y: 0, z: -size[2] / 2 }}, max: {{ x: size[0] / 2, y: size[1], z: size[2] / 2 }} }},
+ span,
+));
+console.log(JSON.stringify(out));
+"""
+ return run_node_json(body)
+
+
+def test_classifier_rule_table():
+ got = _classify([[c[0], c[1], c[2], c[3]] for c in CASES])
+ assert got == [c[4] for c in CASES], list(zip([c[0] for c in CASES], got, strict=True))
+
+
+def test_content_span_rule_only_applies_when_a_content_bbox_is_known():
+ """The census classifies before it has a content bbox and therefore passes
+ span 0 (its historical rule set); coverage knows the content bbox and adds
+ the "far larger than the content" rule. One function, one extra argument —
+ not two rule sets."""
+ assert _classify([["Path", [30, 0.1, 30], False, 5]]) == ["ground"]
+ assert _classify([["Path", [30, 0.1, 30], False, 0]]) == ["content"]
+ # a normal object is content whether or not the content span is known
+ assert _classify([["Cabin", [6, 4, 5], False, 3]]) == ["content"]
+ assert _classify([["Cabin", [6, 4, 5], False, 0]]) == ["content"]
+
+
+def test_the_rules_live_in_exactly_one_file():
+ hits = []
+ for p in sorted((RUNTIME_JS / "lib").rglob("*.mjs")) + sorted((RUNTIME_JS / "lib").rglob("*.js")):
+ text = p.read_text()
+ if re.search(r"skydome\|skybox|\bGROUND_NAME_RE\s*=|\bSKY_NAME_RE\s*=", text):
+ hits.append(p.name)
+ assert hits == ["backdrop.mjs"], hits
diff --git a/harness/tests/spatial_tools/test_render_common.py b/harness/tests/spatial_tools/test_render_common.py
new file mode 100644
index 00000000..d7f7a44f
--- /dev/null
+++ b/harness/tests/spatial_tools/test_render_common.py
@@ -0,0 +1,198 @@
+"""The shared render/tool core: `spatial._render_common`, the sheet + gif writers,
+`measure.solid_parts`, `tool_common` helpers and the central ToolUnavailable
+boundary. Each test pins one merge that removed a duplicate implementation.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from PIL import Image
+
+from codeverse.conventions import OBJECT_VIEWS, SCENE_VIEWS
+from codeverse.spatial import _render_common as rc
+from codeverse.spatial.registry import ToolContext, ToolUnavailable, get_tool
+from codeverse.workspace import Workspace
+
+
+# --------------------------------------------------------------------------- _render_common
+def test_out_directory_creates_and_clears_stale_side_cars(tmp_path: Path) -> None:
+ d = tmp_path / "a" / "b"
+ (tmp_path / "a").mkdir()
+ d.mkdir()
+ (d / "metrics.json").write_text('{"stale": true}')
+ (d / "keep.png").write_bytes(b"x")
+ out = rc.out_directory(d, clean=("metrics.json", "views.json"))
+ assert out == d.resolve() and out.is_dir()
+ assert not (d / "metrics.json").exists() and (d / "keep.png").is_file()
+ # creating a missing directory is the common case
+ assert rc.out_directory(tmp_path / "fresh").is_dir()
+
+
+def test_view_specs_is_the_one_camera_payload() -> None:
+ specs = rc.view_specs(OBJECT_VIEWS)
+ assert [s["name"] for s in specs] == [v.name for v in OBJECT_VIEWS]
+ assert all(set(s) == {"name", "azimuth", "elevation"} for s in specs)
+ assert all(isinstance(s["azimuth"], float) and isinstance(s["elevation"], float) for s in specs)
+ # what the scene driver receives is exactly this, JSON-encoded
+ from codeverse.spatial.render_scene import _views_json
+
+ assert json.loads(_views_json(SCENE_VIEWS)) == rc.view_specs(SCENE_VIEWS)
+
+
+def test_read_json_never_raises(tmp_path: Path) -> None:
+ assert rc.read_json(tmp_path / "nope.json") == {}
+ bad = tmp_path / "bad.json"
+ bad.write_text("{not json")
+ assert rc.read_json(bad) == {}
+ good = tmp_path / "g.json"
+ good.write_text('{"a": 1}')
+ assert rc.read_json(good) == {"a": 1}
+
+
+def test_build_sheet_uses_the_settings_grid_and_guards_empty(tmp_path: Path) -> None:
+ assert rc.build_sheet([], tmp_path / "none.png") is None
+ for i in range(2):
+ Image.new("RGB", (64, 64), (10 * i, 0, 0)).save(tmp_path / f"v{i}.png")
+ out = rc.build_sheet([(f"v{i}", tmp_path / f"v{i}.png") for i in range(2)], tmp_path / "sheet.png")
+ assert out and Path(out).is_file()
+ from codeverse.config import get_settings
+
+ tile = get_settings().render.sheet_tile
+ with Image.open(out) as im:
+ assert im.width == 2 * (tile + 6) + 6 # two columns at the configured tile size
+
+
+# --------------------------------------------------------------------------- sheet: cells + gif
+def test_contact_sheet_keeps_a_non_square_cell(tmp_path: Path) -> None:
+ from codeverse.spatial.sheet import LABEL_H, PAD, contact_sheet, tile_size
+
+ src = tmp_path / "wide.png"
+ Image.new("RGB", (1280, 720), (30, 60, 90)).save(src)
+ assert tile_size(480, sample=src) == (480, 270)
+ assert tile_size(480) == (480, 480) and tile_size((300, 100)) == (300, 100)
+ out = contact_sheet([("t=0s", src), ("t=1s", src)], tmp_path / "s.png", cols=2, tile=(480, 270))
+ with Image.open(out) as im:
+ assert im.size == (2 * (480 + PAD) + PAD, (270 + LABEL_H + PAD) + PAD)
+
+
+def test_gl_contact_sheet_and_gif_go_through_the_shared_writers(tmp_path: Path) -> None:
+ from codeverse.spatial.gl_render import GlFrame, write_contact_sheet, write_gif
+ from codeverse.spatial.sheet import LABEL_H, PAD
+
+ frames = []
+ for i in range(3):
+ p = tmp_path / f"f{i}.png"
+ Image.new("RGB", (640, 360), (20 * i, 40, 60)).save(p)
+ frames.append(GlFrame(index=i, time=i * 1.5, path=str(p)))
+ sheet = write_contact_sheet(frames, tmp_path / "sheet.png", cols=2, tile_w=320)
+ with Image.open(sheet) as im: # 16:9 cells, 2 columns, 2 rows
+ assert im.size == (2 * (320 + PAD) + PAD, 2 * (180 + LABEL_H + PAD) + PAD)
+ gif = write_gif(frames, tmp_path / "p.gif", width=160, fps=6)
+ assert gif and Path(gif).is_file()
+ with Image.open(gif) as im:
+ assert im.n_frames == 3 and im.width == 160
+ assert write_gif(frames[:1], tmp_path / "one.gif") is None # < 2 frames = no preview
+
+
+def test_turntable_gif_uses_the_same_writer(tmp_path: Path) -> None:
+ from codeverse.spatial.turntable import assemble_turntable
+
+ paths = []
+ for i in range(4):
+ p = tmp_path / f"tt{i}.png"
+ Image.new("RGB", (64, 64), (10 * i, 0, 0)).save(p)
+ paths.append(p)
+ out = assemble_turntable(paths, tmp_path / "tt.gif", fps=8)
+ with Image.open(out) as im:
+ assert im.n_frames == 4 and im.width == 64
+
+
+# --------------------------------------------------------------------------- parts loader
+def test_solid_parts_is_cached_parts_without_the_empty_ones(stool_glb: Path) -> None:
+ from codeverse.spatial.measure import cached_parts, solid_parts
+
+ solid = solid_parts(stool_glb)
+ assert solid and list(solid) == [k for k, v in cached_parts(stool_glb).items() if v is not None and len(v.faces)]
+ assert all(v is not None and len(v.faces) for v in solid.values())
+
+
+def test_shared_number_formatters() -> None:
+ from codeverse.spatial.connectivity import _fmt_vec as conn_vec
+ from codeverse.spatial.contract import _fmt_ext, _fmt_vec
+ from codeverse.spatial.measure import fmt_extent_cm, fmt_vec
+
+ assert _fmt_ext is fmt_extent_cm and fmt_extent_cm([0.34, 0.47]) == "34.0×47.0"
+ assert _fmt_vec([-0.00001, 0.5, 0]) == "(+0.000, +0.500, +0.000)" # never '-0.000'
+ assert conn_vec((-0.00001, 0.5, 0.0)) == "(+0.0000, +0.5000, +0.0000)" # 4 decimals, same shape
+ assert fmt_vec([1.23456], digits=2) == "(+1.23)"
+
+
+# --------------------------------------------------------------------------- tool plumbing
+def test_tool_out_dir_is_round_stamped(stool_ctx: ToolContext) -> None:
+ from codeverse.spatial.tool_common import render_cache_dir, tool_out_dir
+
+ d = tool_out_dir(stool_ctx, "sections")
+ assert d.is_dir() and d.name == f"r{stool_ctx.round_index:02d}_sections"
+ assert d.parent == stool_ctx.workspace.artifacts / "tool_renders"
+ glb = stool_ctx.workspace.artifacts / "object.glb"
+ a = render_cache_dir(stool_ctx, glb, mode="shaded")
+ b = render_cache_dir(stool_ctx, glb, mode="clay")
+ assert a != b and a.is_dir() and a.parent == d.parent
+
+
+def test_tool_unavailable_is_reported_by_the_registry(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:
+ """No tool catches ToolUnavailable itself any more — ToolDef.call does it for
+ all of them, with the tool's own registered name."""
+ import codeverse.spatial.tool_common as tc
+
+ def boom(module, attr):
+ raise ToolUnavailable(f"{module} not importable")
+
+ monkeypatch.setattr(tc, "lazy", boom)
+ monkeypatch.setattr("codeverse.spatial.tools.lazy", boom)
+ monkeypatch.setattr("codeverse.spatial.tools_scene.lazy", boom)
+ monkeypatch.setattr("codeverse.spatial.tools_graphics.lazy", boom)
+ monkeypatch.setattr("codeverse.spatial.tools_texture.lazy", boom)
+ ws = stool_ctx.workspace
+ (ws.artifacts / "object_textured.glb").write_bytes((ws.artifacts / "object.glb").read_bytes())
+ for name in ("build", "render_views", "scene_probe", "texture_preview"):
+ obs = get_tool(name).call(stool_ctx, {})
+ assert not obs.ok and obs.text.startswith(f"tool {name} unavailable:"), (name, obs.text)
+ # a graphics workspace: the gl tools degrade the same way
+ gl_ctx = ToolContext(workspace=stool_ctx.workspace, language="glsl_shader", track="graphics")
+ obs = get_tool("gl_probe").call(gl_ctx, {})
+ assert not obs.ok and obs.text.startswith("tool gl_probe unavailable:"), obs.text
+
+
+def test_gl_metrics_summary_is_the_one_frame_stats_formatter(tmp_ws: Workspace, monkeypatch: pytest.MonkeyPatch) -> None:
+ from codeverse.contracts.artifacts import GateFinding, GateReport, Severity
+ from codeverse.spatial.frame_stats import FrameStat, SequenceStats
+ from codeverse.spatial.tool_common import gl_metrics_summary
+
+ stats = SequenceStats(frames=[FrameStat(time=0.0, path="f0.png", mean_lum=0.4, std_lum=0.2, pct_black=0.0,
+ pct_blown=0.0, colourfulness=0.3, edge_density=0.05)], mean_diff=0.0)
+ gate = GateReport(gate="gl_frames", passed=False, findings=[
+ GateFinding(gate="gl_frames", severity=Severity.ERROR, message=f"static image in {tmp_ws.root}/src",
+ fix_hint="animate with u_time", data={"kind": "static"}),
+ GateFinding(gate="gl_frames", severity=Severity.INFO, message="ignored"),
+ ])
+ monkeypatch.setattr("codeverse.languages._gl_common.read_metrics", lambda ws: (stats, gate))
+ lines, numbers, ok = gl_metrics_summary(tmp_ws, hints=True, root=tmp_ws.root)
+ body = "\n".join(lines)
+ assert not ok and "frames=1" in body and "[static]" in body and "fix: animate with u_time" in body
+ assert "ignored" not in body and str(tmp_ws.root) not in body # INFO dropped, paths sanitised
+ assert numbers["gate_errors"] == 1 and numbers["n_frames"] == 1 and numbers["gate_passed"] is False
+ no_hints, _, _ = gl_metrics_summary(tmp_ws, hints=False)
+ assert "fix:" not in "\n".join(no_hints)
+ monkeypatch.setattr("codeverse.languages._gl_common.read_metrics", lambda ws: None)
+ assert gl_metrics_summary(tmp_ws) == (["(no frame metrics)"], {}, True)
+
+
+def test_render_scene_still_exports_runtime_js_dir() -> None:
+ """Public symbol kept while the definition moved to spatial.node."""
+ from codeverse.spatial import node, render_scene
+
+ assert render_scene.runtime_js_dir() == node.runtime_js_dir()
diff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.py
index 9c9fbe0f..38de1ee2 100644
--- a/harness/tests/spatial_tools/test_tools.py
+++ b/harness/tests/spatial_tools/test_tools.py
@@ -332,7 +332,7 @@ def test_build_tool_scene_reports_probe_census(tmp_ws: Workspace, monkeypatch: p
def test_build_tool_graphics_reports_frames(tmp_ws: Workspace, monkeypatch: pytest.MonkeyPatch) -> None:
- import codeverse.languages.glsl_shader.gl_build as gl_build
+ import codeverse.languages._gl_common as gl_build # the one metrics reader (gl_build is a shim over it)
from codeverse.spatial.frame_stats import FrameStat, SequenceStats
ctx = ToolContext(workspace=tmp_ws, language="glsl_shader", track="graphics")
diff --git a/harness/tests/threejs_render/test_camera_fit.py b/harness/tests/threejs_render/test_camera_fit.py
new file mode 100644
index 00000000..c9d079e7
--- /dev/null
+++ b/harness/tests/threejs_render/test_camera_fit.py
@@ -0,0 +1,82 @@
+"""The object rig's camera fit — one distance-fit implementation, shared with the orbit rig.
+
+``lib/browser/camera_fit.js`` used to iterate a projection loop of its own while
+``lib/orbit.mjs`` solved the same problem analytically. Now both call
+``orbit.fitDistance``; these tests pin the behaviour that merge must keep:
+the projected bbox fills exactly ``fill`` of the half-frame for every canonical
+view, at any aspect ratio, and the direction convention is the shared one.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from codeverse.conventions import OBJECT_VIEWS
+from codeverse.spatial.node import run_node, runtime_js_dir
+
+pytestmark = pytest.mark.node
+
+VIEWS = [{"name": v.name, "azimuth": v.azimuth_deg, "elevation": v.elevation_deg} for v in OBJECT_VIEWS]
+BOXES = [
+ [[-0.17, 0.0, -0.17], [0.17, 0.47, 0.17]], # stool: tall-ish, centred
+ [[-1.2, 0.0, -0.3], [1.2, 0.9, 0.3]], # bench: wide and shallow
+ [[0.4, 0.4, 0.4], [0.6, 3.0, 0.5]], # tall, thin and OFF-CENTRE (the old loop diverged here)
+]
+
+
+def _fit_report(tmp_path) -> list[dict]:
+ script = tmp_path / "fit.mjs"
+ script.write_text(f"""
+import * as THREE from 'three';
+import {{ fitCameraToBox, boxCorners, viewDirection }} from {json.dumps(str(runtime_js_dir() / 'lib/browser/camera_fit.js'))};
+const views = {json.dumps(VIEWS)}, boxes = {json.dumps(BOXES)};
+const rows = [];
+for (const [bi, [mn, mx]] of boxes.entries()) {{
+ const box = new THREE.Box3(new THREE.Vector3(...mn), new THREE.Vector3(...mx));
+ for (const v of views) {{
+ for (const aspect of [1, 16 / 9]) {{
+ const cam = new THREE.PerspectiveCamera(35, aspect, 0.01, 100);
+ const fit = fitCameraToBox(cam, box, v.azimuth, v.elevation, {{ fill: 0.85 }});
+ let maxExt = 0;
+ for (const c of boxCorners(box)) {{
+ const n = c.clone().project(cam);
+ maxExt = Math.max(maxExt, Math.abs(n.x), Math.abs(n.y));
+ }}
+ const centre = box.getCenter(new THREE.Vector3());
+ rows.push({{ box: bi, name: v.name, aspect, distance: fit.distance, max_ndc: maxExt,
+ inside: box.containsPoint(cam.position), near: cam.near, far: cam.far,
+ look_at: fit.lookAt, centre: centre.toArray() }});
+ }}
+ }}
+}}
+const dir = viewDirection(0, 0).toArray();
+console.log(JSON.stringify({{ rows, front_dir: dir }}));
+""")
+ return run_node(script, [], three_hook=True, timeout_s=60).last_json
+
+
+def test_every_canonical_view_frames_the_box_exactly(tmp_path):
+ report = _fit_report(tmp_path)
+ # azimuth 0 = +Z (conventions.py) — the shared orbitDirection, not a second copy
+ assert report["front_dir"] == pytest.approx([0.0, 0.0, 1.0], abs=1e-12)
+ assert len(report["rows"]) == len(OBJECT_VIEWS) * len(BOXES) * 2
+ for r in report["rows"]:
+ where = f"{r['name']} box={r['box']} aspect={r['aspect']:.2f}"
+ assert r["max_ndc"] == pytest.approx(0.85, abs=1e-6), where # exact frustum fit
+ assert r["distance"] > 0 and not r["inside"], where # never lands inside the object
+ assert 0 < r["near"] < r["far"], where
+ assert r["look_at"] == pytest.approx(r["centre"], abs=1e-9), where
+
+
+def test_fit_scales_with_the_box_not_the_view(tmp_path):
+ rows = _fit_report(tmp_path)["rows"]
+ by = {(r["box"], r["name"], round(r["aspect"], 2)): r["distance"] for r in rows}
+ # the wide bench needs more distance than the small stool from the same view
+ for name in ("front", "front_right_34"):
+ assert by[(1, name, 1.0)] > by[(0, name, 1.0)]
+ # a wider frame never needs to back off further than a square one (vertical fov fixed)
+ for (b, name, aspect), d in by.items():
+ if aspect == 1.0:
+ assert by[(b, name, 1.78)] <= d + 1e-9, (b, name)
diff --git a/harness/tests/threejs_render/test_runtime_js.py b/harness/tests/threejs_render/test_runtime_js.py
index 4b43764c..13f9230a 100644
--- a/harness/tests/threejs_render/test_runtime_js.py
+++ b/harness/tests/threejs_render/test_runtime_js.py
@@ -35,6 +35,41 @@ def test_export_cli_writes_census_and_error_json(stool_ws: Workspace, tmp_path:
assert (stool_ws.artifacts / "export_error.json").is_file()
+def test_render_glb_driver_protocol_and_shared_plumbing(tmp_path: Path):
+ """render_glb.mjs is a thin entry: shared arg parsing / JSON-last-line
+ protocol (lib/cli.mjs), shared browser + static server (lib/host_env.mjs),
+ shared release dance (lib/host_page.mjs) — and it still reports a failure as
+ exit 1 with `{ok: false, error}` as the LAST stdout line."""
+ rt = runtime_js_dir()
+ src = (rt / "render_glb.mjs").read_text()
+ assert "from './lib/cli.mjs'" in src and "from './lib/host_env.mjs'" in src
+ assert "releaseBrowser" in src
+ assert "createRequire" not in src and "parseArgs" not in src # no second copy of either
+ with pytest.raises(NodeError) as ei:
+ run_node(rt / "render_glb.mjs",
+ ["--glb", str(tmp_path / "missing.glb"), "--out", str(tmp_path / "out"),
+ "--views", json.dumps([{"name": "front", "azimuth": 0.0, "elevation": 8.0}])],
+ timeout_s=60)
+ rec = ei.value.result.last_json
+ assert ei.value.result.rc == 1 and rec["ok"] is False and "GLB not found" in rec["error"]
+ with pytest.raises(NodeError) as ei:
+ run_node(rt / "render_glb.mjs", ["--glb", "x.glb", "--out", "o", "--views", "[]"], timeout_s=60)
+ assert "non-empty JSON list" in ei.value.result.last_json["error"]
+
+
+def test_one_webgl_renderer_factory():
+ """Object rig and scene host share `lib/browser/renderer.js`: one place sets
+ the colour pipeline (sRGB + ACES + PCF shadows, pixel ratio 1), so an object
+ render and a scene render cannot drift apart."""
+ rt = runtime_js_dir()
+ sources = sorted(rt.glob("*.mjs")) + sorted(rt.glob("*.cjs")) + sorted((rt / "lib").rglob("*.mjs")) \
+ + sorted((rt / "lib").rglob("*.js"))
+ owners = [p for p in sources if "new THREE.WebGLRenderer(" in p.read_text()]
+ assert [p.name for p in owners] == ["renderer.js"], owners
+ assert "from './renderer.js'" in (rt / "lib/browser/studio.js").read_text()
+ assert "from './browser/renderer.js'" in (rt / "lib/scene_host.mjs").read_text()
+
+
def test_serve_and_importmap(tmp_path: Path):
script = tmp_path / "s.cjs"
root = tmp_path / "root"