Skip to content

Official Codebase of 3DCodeVerse

Python

core/cli/flywheel: migrate-runs retires, and a moved run exports its renders again

gaoypeng70eecab00b4f
diff --git a/harness/codeverse/cli/_common.py b/harness/codeverse/cli/_common.py
index 44ba6157..3123c9ee 100644
--- a/harness/codeverse/cli/_common.py
+++ b/harness/codeverse/cli/_common.py
@@ -1,4 +1,6 @@
-"""Rich formatting for the CLI: run summaries, tables, observations, doctor rows."""
+"""Shared CLI plumbing: Rich formatting (run summaries, tables, observations, doctor
+rows), the run-mutation mutex, workspace opening / creation, lazy imports and the
+cost-quality dial resolution every command goes through."""
from __future__ import annotations
@@ -10,7 +12,7 @@ from collections.abc import Iterator
from contextlib import ExitStack, contextmanager
from dataclasses import dataclass
from pathlib import Path
-from typing import Any
+from typing import Annotated, Any
import typer
from rich.console import Console
@@ -26,6 +28,8 @@ from codeverse.workspace import Workspace
console = Console(emoji=False)
err_console = Console(stderr=True, style="bold red", emoji=False)
+RunsDirOpt = Annotated[Path | None, typer.Option("--runs-dir", help="runs root (default: settings.runs_dir)")]
+
def err(msg: str) -> None:
err_console.print(f"error: {msg}")
@@ -75,7 +79,9 @@ def print_record_summary(record: RunRecord, ws_root: Path | None = None) -> None
lines.append(f"[red]error: {record.error}[/red]")
if ws_root is not None:
lines.append(f"workspace: {ws_root}")
- best = next((r for r in record.rounds if r.index == record.best_round), None)
+ from codeverse.flywheel.record import best_round_record
+
+ best = best_round_record(record)
if best is not None and best.renders is not None and best.renders.contact_sheet:
# rebase, never print the stored string: record.json holds the ABSOLUTE path
# of the host that produced the run, so a moved/archived run printed a sheet
@@ -311,37 +317,15 @@ def round_policy_options(spec: Spec, settings: Any | None = None) -> dict[str, A
Only the judge sample count needs a ``RoundPolicy`` (rounds travel on
``spec.budget``, best-of-N on ``spec.options``), so a run at the default
- ``n=1`` gets **no** policy and keeps the track's own — including the
- rubric-derived stop target that ``BaseTrack.after_plan`` binds when no policy
- was injected. When a profile does ask for more samples we bind that target
- here instead, from the same rubric the track will use."""
+ ``n=1`` gets **no** policy and keeps the track's own. The rubric stop target
+ and the detail-round budget are bound by ``BaseTrack`` for an injected policy
+ too, so nothing else is set here."""
settings = settings or get_settings()
samples = int(getattr(settings.judge, "samples", 1) or 1)
if samples <= 1:
return {}
- from dataclasses import replace
-
from codeverse.orchestrator import RoundPolicy
- policy = RoundPolicy(max_rounds=spec.budget.max_rounds, judge_samples=samples)
- threshold = rubric_threshold(spec)
- if threshold is not None:
- policy = replace(policy, target=float(threshold))
- return {"policy": policy}
+ return {"policy": RoundPolicy(max_rounds=spec.budget.max_rounds, judge_samples=samples)}
-def rubric_threshold(spec: Spec) -> float | None:
- """Pass threshold of the rubric this spec will be judged with (``None`` when
- the rubric cannot be loaded — the caller then keeps the policy default)."""
- try:
- from codeverse.contracts.common import Track
- from codeverse.judges.rubrics import load_rubric
- from codeverse.tracks import get_track
- from codeverse.tracks.lifecycle import REFERENCE_RUBRIC
-
- # same selection rule as BaseTrack.build_context
- name = (REFERENCE_RUBRIC if spec.references and spec.track is Track.STATIC_OBJECT
- else get_track(spec.track).rubric)
- return float(load_rubric(name).pass_threshold)
- except Exception: # noqa: BLE001 - a missing rubric must not stop a run
- return None
diff --git a/harness/codeverse/cli/_judge.py b/harness/codeverse/cli/_judge.py
index 6c891585..cc4ab5d6 100644
--- a/harness/codeverse/cli/_judge.py
+++ b/harness/codeverse/cli/_judge.py
@@ -43,8 +43,7 @@ def rubric_for(rec: RunRecord, rnd: RoundRecord, override: str | None) -> str:
return override
if rnd.judgment is not None and rnd.judgment.rubric:
return rnd.judgment.rubric
- info = TRACK_INFO.get(rec.spec.track)
- return info.rubric if info is not None else "static_object_v1"
+ return TRACK_INFO[rec.spec.track].rubric
def plan_summary_for(ws: Workspace) -> str:
diff --git a/harness/codeverse/cli/inspect_cmd.py b/harness/codeverse/cli/inspect_cmd.py
index c9c38a2b..ee8125ec 100644
--- a/harness/codeverse/cli/inspect_cmd.py
+++ b/harness/codeverse/cli/inspect_cmd.py
@@ -7,7 +7,7 @@ graphics-track frame copy, and the ``judge`` re-judge that writes
``artifacts/judge/rNN_cli.json``. Its sibling ``cli/main.py`` owns the typer app,
``make`` / ``resume`` (spec building + track dispatch), ``mcp`` and the registration
of every command — including these three, which it registers with ``app.command``
-like ``layout_cmd.py``'s ``show`` / ``migrate-runs``.
+like ``layout_cmd.py``'s ``show``.
"""
from __future__ import annotations
@@ -19,16 +19,12 @@ from typing import Annotated
import typer
from codeverse.cli import _common as C
-from codeverse.cli._common import console, kv_table, print_record_summary, warn
+from codeverse.cli._common import RunsDirOpt, console, kv_table, print_record_summary, warn
from codeverse.config import get_settings
from codeverse.contracts.common import Track
from codeverse.contracts.spec import Spec
from codeverse.proc import read_json_or_none
-RunsDirOpt = Annotated[
- Path | None, typer.Option("--runs-dir", help="runs root (default: settings.runs_dir)")
-]
-
# --------------------------------------------------------------------------- status
def status(
diff --git a/harness/codeverse/cli/layout_cmd.py b/harness/codeverse/cli/layout_cmd.py
index c9ded1d5..26f51fef 100644
--- a/harness/codeverse/cli/layout_cmd.py
+++ b/harness/codeverse/cli/layout_cmd.py
@@ -1,4 +1,4 @@
-"""``3dcv show`` + ``3dcv migrate-runs`` — the run directory, read and reorganised.
+"""``3dcv show`` — one run directory, read in three sections.
``show`` prints one run as three clearly separated sections (docs/RUN_LAYOUT.md):
@@ -7,20 +7,19 @@
* **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.
+Works 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._common import console, fmt_score, fmt_usd, kv_table, ok, warn
+from codeverse.cli._common import RunsDirOpt, console, fmt_score, fmt_usd, kv_table, warn
from codeverse.contracts.run import (
CostSummary,
DeliverableFile,
@@ -30,8 +29,6 @@ from codeverse.contracts.run import (
)
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)
@@ -100,14 +97,14 @@ def print_deliverable(ws: Workspace, record: RunRecord) -> None:
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/)",
+ console.print(kv_table("artifacts (old layout — no 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
+ from codeverse.flywheel.record import best_round_record, effective_judgment
+ from codeverse.flywheel.sample import gate_error_summary
_section("QUALITY EVIDENCE — why we believe it")
rnd = best_round_record(record)
@@ -135,7 +132,7 @@ def print_evidence(ws: Workspace, record: RunRecord) -> 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/)"
+ rows["evidence dir"] = f"{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]:
@@ -208,12 +205,12 @@ def print_cost_and_settings(ws: Workspace, record: RunRecord) -> None:
"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]")
+ console.print("[dim]computed on the fly (no telemetry/ in this run)[/dim]")
else:
console.print(f"[dim]telemetry: {ws.cost_path} · {ws.usage_path} · {ws.settings_path}[/dim]")
-# --------------------------------------------------------------------------- commands
+# --------------------------------------------------------------------------- command
def show(
slug: str,
runs_dir: RunsDirOpt = None,
@@ -236,30 +233,3 @@ def show(
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 6deb93bb..b17e4654 100644
--- a/harness/codeverse/cli/main.py
+++ b/harness/codeverse/cli/main.py
@@ -8,7 +8,7 @@ Owns the typer app and every registration, the run-starting commands ``make`` /
``resume`` (spec building, reference grounding, track dispatch, budget raising) and
``mcp``. The run-inspecting commands ``status`` / ``render`` / ``judge`` live in the
sibling ``cli/inspect_cmd.py`` and are registered here, the way ``layout_cmd.py``'s
-``show`` / ``migrate-runs`` are.
+``show`` is.
"""
from __future__ import annotations
@@ -27,6 +27,7 @@ import typer
from codeverse import __version__
from codeverse.cli import _common as C
from codeverse.cli._common import (
+ RunsDirOpt,
console,
err_console,
kv_table,
@@ -254,11 +255,6 @@ app.command(
help="List spatial tools or run one: `3dcv tools list` | `3dcv tools <name> --json '{...}' --workspace ws`.",
)(tools)
-RunsDirOpt = Annotated[
- Path | None, typer.Option("--runs-dir", help="runs root (default: settings.runs_dir)")
-]
-
-
@app.callback(invoke_without_command=True)
def _root(
ctx: typer.Context, version: Annotated[bool, typer.Option("--version", is_eager=True)] = False
@@ -669,18 +665,13 @@ def mcp(workspace: Annotated[Path, typer.Option("--workspace")]) -> None:
)
-# --------------------------------------------------------------------------- run layout (show / migrate)
+# --------------------------------------------------------------------------- run layout (show)
# 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
diff --git a/harness/codeverse/cli/texture_cmd.py b/harness/codeverse/cli/texture_cmd.py
index 70cd9097..a7ecac39 100644
--- a/harness/codeverse/cli/texture_cmd.py
+++ b/harness/codeverse/cli/texture_cmd.py
@@ -19,12 +19,11 @@ from codeverse.contracts.common import Track
texture_app = typer.Typer(name="texture", help="Text-to-image texturing: object pass + scene texture pack.",
no_args_is_help=True)
-RunsDirOpt = Annotated[Path | None, typer.Option("--runs-dir", help="runs root (default: settings.runs_dir)")]
+RunsDirOpt = C.RunsDirOpt
def _image_model(name: str | None):
- GeminiImageModel = C.lazy("codeverse.models.gemini", "GeminiImageModel")
- return GeminiImageModel(name) if name else GeminiImageModel()
+ return C.lazy("codeverse.reference", "_image_model")(name or "")
@texture_app.command("pass")
diff --git a/harness/codeverse/config.py b/harness/codeverse/config.py
index 4793ba85..d82e5443 100644
--- a/harness/codeverse/config.py
+++ b/harness/codeverse/config.py
@@ -45,7 +45,6 @@ class Binaries(BaseModel):
claude_cli: str = "claude"
codex_cli: str = "codex"
agy_cli: str = "agy"
- ffmpeg: str = "ffmpeg"
class Agents(BaseModel):
@@ -102,7 +101,7 @@ class Limits(BaseModel):
description="graphics / glsl_shader: paste the cookbook recipes the brief calls for "
"(curtain / aurora / stars / bokehSoft / dropsLayer + the hash / noise / fbm helpers "
"they use) into the harness-owned, read-only src/recipes.glsl BEFORE the baseline session "
- "(tracks/graphics_recipes.py; pasted above src/common.glsl at build time). "
+ "(tracks/graphics.py:seed_recipes; pasted above src/common.glsl at build time). "
"ON by default: measured 2026-08-26 (refs_v2_graphics, aurora brief, gemini-3.7-flash) "
"the prompt carried the verified curtain() recipe five times and the agent used it zero "
"times — round 0 was again a comb of bars (comb_artefact, 0.33); and (bench/out/seed_v1) "
@@ -182,10 +181,12 @@ def _env_flag(raw: str, env: str) -> bool:
raise ValueError(f"{env}={raw!r}: expected on/off (1/0, true/false, yes/no)")
-def _call_time_flag(env: str, fallback: bool) -> bool:
- """``$env`` when it is set (garbage counts as off, with a warning — a typo in a bench
- command must produce a control run, not a crash mid-battery), else ``fallback`` (the
- cached Settings value)."""
+def env_flag(env: str, fallback: bool) -> bool:
+ """``$env`` read NOW (never through the cached Settings — an A/B arm sets it after
+ first touch): unset or empty → ``fallback``; garbage → OFF with a warning, because a
+ typo in a bench command must produce a control run, not a crash mid-battery (and
+ not the variant: ``fallback`` may be on). ``skills/config.py`` reads its switches
+ through this too."""
raw = os.environ.get(env)
if raw is not None and raw.strip():
try:
@@ -199,13 +200,13 @@ def _call_time_flag(env: str, fallback: bool) -> bool:
def fewer_turns_enabled() -> bool:
"""Is the fewer-turns bundle on for THIS call? ``$CV3D_FEWER_TURNS`` when it is set,
else ``Settings.limits.fewer_turns``."""
- return _call_time_flag(FEWER_TURNS_ENV, get_settings().limits.fewer_turns)
+ return env_flag(FEWER_TURNS_ENV, get_settings().limits.fewer_turns)
def seed_recipes_enabled() -> bool:
- """Is recipe seeding (``tracks/graphics_recipes.py``) on for THIS call? ``$CV3D_SEED_RECIPES``
+ """Is recipe seeding (``tracks/graphics.py:seed_recipes``) on for THIS call? ``$CV3D_SEED_RECIPES``
when it is set, else ``Settings.limits.seed_recipes`` (default ON)."""
- return _call_time_flag(SEED_RECIPES_ENV, get_settings().limits.seed_recipes)
+ return env_flag(SEED_RECIPES_ENV, get_settings().limits.seed_recipes)
class Settings(BaseSettings):
diff --git a/harness/codeverse/contracts/__init__.py b/harness/codeverse/contracts/__init__.py
index 0be15c53..8820a9b4 100644
--- a/harness/codeverse/contracts/__init__.py
+++ b/harness/codeverse/contracts/__init__.py
@@ -1,11 +1,11 @@
-"""Typed contracts shared across the harness. Data only — no behaviour.
+"""Typed contracts shared across the harness. Data + validators — no I/O, no model calls.
Modules:
- ``common`` enums, vectors, usage/cost.
- ``spec`` what the user asked for (track, language, prompt, budget, backends).
- ``plan`` what the planner decided (parts / joints / zones / acceptance).
-- ``artifacts`` what tools produced (measurements, renders, gate reports, builds).
-- ``judgment`` what judges said (scores, issues, improvement plan).
+- ``artifacts`` what tools produced (measurements, renders, gate reports, builds) and
+ what judges said (scores, issues, improvement plan).
- ``run`` the run record (rounds, totals, provenance) — the flywheel unit.
- ``chat`` ChatModel request/response shapes.
- ``agent`` CodingAgent job/result shapes.
diff --git a/harness/codeverse/contracts/common.py b/harness/codeverse/contracts/common.py
index e433c405..652726c9 100644
--- a/harness/codeverse/contracts/common.py
+++ b/harness/codeverse/contracts/common.py
@@ -74,7 +74,7 @@ ENTRY_FILE: dict[Language, str] = {
}
#: source files the HARNESS writes under ``src/`` and owns: the agent reads them and calls what
-#: they define, never writes them (``AgentJob.read_only`` → ``FileTools`` refuses the write).
+#: they define, never writes them (``AgentJob.read_only`` — the agent's write scope excludes them).
#: Measured 2026-08-26 (bench/out/seed_v1, aurora brief, gemini-3.7-flash api-agent): recipes
#: seeded into the agent's own ``src/common.glsl`` were gone by the end of the run — it rewrote
#: the file with its own helpers — so a seeded file has to be one the agent cannot rewrite.
diff --git a/harness/codeverse/contracts/run.py b/harness/codeverse/contracts/run.py
index e1e7fbee..9acff9c8 100644
--- a/harness/codeverse/contracts/run.py
+++ b/harness/codeverse/contracts/run.py
@@ -1,8 +1,11 @@
-"""What a round did with its skills — the record shape, kept in contracts with the rest.
-
-Lives here rather than in ``codeverse/skills`` so ``contracts`` stays a leaf package that
-``flywheel``, ``gallery`` and the CLI can import without pulling the router in, and so a
-stored ``record.json`` can be re-read by a build that has no skill library at all.
+"""The run record — ``record.json`` — and everything stored inside it.
+
+``RunRecord`` (rounds, totals, provenance: the flywheel unit), ``RunId`` (where a run
+sits in a runs dir or a battery), the per-round skills usage, and the packaged
+``telemetry/`` + ``deliverable/`` blocks. The skills shapes live here rather than in
+``codeverse/skills`` so ``contracts`` stays a leaf that ``flywheel``, ``gallery`` and the
+CLI import without the router, and a stored record re-reads on a build with no skill
+library at all.
"""
from __future__ import annotations
@@ -28,7 +31,7 @@ class SkillRead(BaseModel):
deep: bool = Field(default=False, description="a references/*.md atime > mtime: the body was read and followed")
deep_measurable: bool = Field(default=True, description="False when the bundle ships no references/ file to probe")
body_tokens: int = 0
- first_seen_turn: int | None = Field(default=None, description="historical (pre-2026-08-28) api-agent runs only: exact turn of the first read")
+ first_seen_turn: int | None = Field(default=None, description="HISTORICAL, read-only: only the api-agent (deleted 2026-08-28) knew the exact turn of the first read; CLI agents leave it None")
reason: str = Field(default="", description="which route attached it, and which finding")
@@ -197,7 +200,7 @@ class RoleSettings(BaseModel):
role: str
model: str = ""
- backend: str = Field(default="", description="gemini | anthropic | api-agent | gemini-cli | codex | …")
+ backend: str = Field(default="", description="gemini | anthropic | gemini-cli | codex | … (api-agent only in records written before 2026-08-28)")
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")
diff --git a/harness/codeverse/doctor.py b/harness/codeverse/doctor.py
index 468179b3..c9de3608 100644
--- a/harness/codeverse/doctor.py
+++ b/harness/codeverse/doctor.py
@@ -9,10 +9,10 @@ from __future__ import annotations
import importlib
import json
import shutil
-import subprocess
from pathlib import Path
from codeverse.config import get_settings
+from codeverse.proc import version_line
Row = tuple[str, str, str]
_PY_DEPS = ("pydantic", "pydantic_settings", "typer", "rich", "jinja2", "yaml", "numpy", "trimesh", "fcl", "PIL", "pyarrow",
@@ -38,15 +38,10 @@ _CLI_TIMEOUT = 25
def _ver(cmd: list[str], timeout: int = _CLI_TIMEOUT) -> tuple[bool, str]:
if not shutil.which(cmd[0]) and not Path(cmd[0]).is_file():
return False, "not found"
- try:
- p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
- except subprocess.TimeoutExpired:
- return False, f"timed out after {timeout}s"
- except OSError as e:
- return False, str(e)
- out = (p.stdout or p.stderr).strip().splitlines()
- first = out[0].strip() if out else ""
- return p.returncode == 0, first[:100] or f"exit {p.returncode}"
+ rc, first = version_line(cmd, timeout=timeout)
+ if rc is None:
+ return False, first
+ return rc == 0, first[:100] or f"exit {rc}"
def check_python_deps() -> list[Row]:
@@ -244,8 +239,6 @@ def check_clis() -> list[Row]:
rows.append((name, "OK" if okk else "WARN", v if okk else f"{v} (backend {name} unavailable)"))
okk, v = _ver(["git", "--version"])
rows.append(("git", "OK" if okk else "FAIL", v))
- okk, v = _ver([s.binaries.ffmpeg, "-version"])
- rows.append(("ffmpeg", "OK" if okk else "WARN", v if okk else "not found (turntable mp4 disabled)"))
return rows
diff --git a/harness/codeverse/flywheel/captions.py b/harness/codeverse/flywheel/captions.py
index 2f8b8734..b652a846 100644
--- a/harness/codeverse/flywheel/captions.py
+++ b/harness/codeverse/flywheel/captions.py
@@ -28,7 +28,8 @@ from codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePart
from codeverse.contracts.common import ENTRY_FILE, Language, Track
from codeverse.contracts.run import RunRecord
from codeverse.flywheel import _git
-from codeverse.flywheel.sample import best_round_record, code_files_for_round
+from codeverse.flywheel.record import best_round_record
+from codeverse.flywheel.sample import code_files_for_round
from codeverse.prompts import prompt_hash
from codeverse.workspace import Workspace
@@ -107,12 +108,10 @@ def _round_images(ws: Workspace, record: RunRecord) -> tuple[list[ImagePart], li
def _add(path: str | None, label: str) -> None:
if not path or len(images) >= N_VIEWS + 1:
return
- p = Path(path)
- if not p.is_absolute():
- p = ws.root / p
+ p = ws.rebase(path)
if p.is_file():
images.append(ImagePart(path=str(p), label=label))
- used.append(str(p))
+ used.append(p.relative_to(ws.root).as_posix() if p.is_relative_to(ws.root) else str(p))
_add(rnd.renders.contact_sheet, "contact sheet (all views, labelled)")
views = list(rnd.renders.views)
@@ -202,7 +201,7 @@ def caption_sample(
raise CaptionError(f"{ws.root}: captions rejected after retry: {problems}")
rnd = best_round_record(record)
prov = CaptionProvenance(captioner=model_id, round_index=rnd.index if rnd else None,
- images_used=[_rel(ws, u) for u in used], code_chars=len(code),
+ images_used=used, code_chars=len(code),
prompt_hash=prompt_hash(system), cost_usd=cost)
payload = {**caps.model_dump(), "provenance": prov.model_dump(mode="json")}
record.extra["captions"] = payload
@@ -219,13 +218,6 @@ def caption_sample(
return caps
-def _rel(ws: Workspace, path: str) -> str:
- try:
- return Path(path).relative_to(ws.root).as_posix()
- except ValueError:
- return path
-
-
def _parse_json(text: str) -> dict:
s = text.strip()
if s.startswith("```"):
diff --git a/harness/codeverse/flywheel/code_quality.py b/harness/codeverse/flywheel/code_quality.py
index 1d3a7f1b..d126b74f 100644
--- a/harness/codeverse/flywheel/code_quality.py
+++ b/harness/codeverse/flywheel/code_quality.py
@@ -316,7 +316,8 @@ def measure(files: Mapping[str, bytes | str]) -> CodeQuality | None:
def code_quality_block(ws: Any, record: Any) -> dict[str, Any] | None:
"""``record.extra["code_quality"]`` for the BEST round's code tree, or None."""
- from codeverse.flywheel.sample import best_round_record, code_files_for_round
+ from codeverse.flywheel.record import best_round_record
+ from codeverse.flywheel.sample import code_files_for_round
try:
rnd = best_round_record(record)
diff --git a/harness/codeverse/flywheel/deliverable.py b/harness/codeverse/flywheel/deliverable.py
index 70d96161..9ca53eda 100644
--- a/harness/codeverse/flywheel/deliverable.py
+++ b/harness/codeverse/flywheel/deliverable.py
@@ -29,7 +29,7 @@ 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.proc import sha256_file, write_json_atomic
from codeverse.workspace import Workspace
log = logging.getLogger(__name__)
@@ -49,10 +49,6 @@ _ARTIFACT_ROLES: tuple[tuple[str, str], ...] = (
)
-def _sha256(data: bytes) -> str:
- return hashlib.sha256(data).hexdigest()
-
-
class _Writer:
"""Collects files into ``deliverable/`` and remembers role/size/hash."""
@@ -73,7 +69,7 @@ class _Writer:
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)))
+ self.files.append(DeliverableFile(path=f"deliverable/{rel}", role=role, bytes=len(data), sha256=hashlib.sha256(data).hexdigest()))
def add_file(self, src: Path, rel: str, role: str) -> bool:
if not src.is_file():
@@ -90,7 +86,7 @@ class _Writer:
_place(src, dest)
self.total += size
self.files.append(DeliverableFile(path=f"deliverable/{rel}", role=role, bytes=size,
- sha256=_sha256(src.read_bytes())))
+ sha256=sha256_file(src)))
return True
@@ -102,15 +98,6 @@ def _place(src: Path, dest: Path) -> None:
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:
@@ -149,8 +136,10 @@ def _copy_artifacts(ws: Workspace, record: RunRecord, w: _Writer) -> None:
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:
+ if rnd is None or rnd.renders is None or not rnd.renders.contact_sheet:
+ return
+ sheet = ws.rebase(rnd.renders.contact_sheet)
+ if sheet.is_file():
w.add_file(sheet, f"sheet{sheet.suffix or '.png'}", "sheet")
@@ -181,10 +170,9 @@ def build_deliverable(ws: Workspace, record: RunRecord, *, clean: bool = True) -
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
+ from codeverse.flywheel.record import best_round_record
- idx = best_round_index(record)
- rnd = next((r for r in record.rounds if r.index == idx), None)
+ rnd = best_round_record(record)
previous = load_deliverable(ws) if ws.deliverable_manifest_path.is_file() else None
if clean and ws.deliverable.exists():
shutil.rmtree(ws.deliverable)
@@ -198,7 +186,7 @@ def build_deliverable(ws: Workspace, record: RunRecord, *, clean: bool = True) -
_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,
+ best_round=(rnd.index if rnd is not None else None), 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),
diff --git a/harness/codeverse/flywheel/export.py b/harness/codeverse/flywheel/export.py
index cea08929..7dde56fe 100644
--- a/harness/codeverse/flywheel/export.py
+++ b/harness/codeverse/flywheel/export.py
@@ -26,7 +26,6 @@ else ``<captions_dir>/<slug>.json`` (side-car written by ``3dcv flywheel caption
from __future__ import annotations
-import hashlib
import json
import logging
import shutil
@@ -41,7 +40,8 @@ from codeverse.contracts.run import RunId, RunRecord
from codeverse.flywheel import sample as S
from codeverse.flywheel._git import CODE_ROOTS
from codeverse.flywheel.quality import DuplicateGroup, code_sha256, mark_duplicates
-from codeverse.flywheel.record import FoundRun, iter_runs
+from codeverse.flywheel.record import FoundRun, best_round_record, iter_runs
+from codeverse.proc import sha256_file
from codeverse.workspace import Workspace
log = logging.getLogger(__name__)
@@ -107,14 +107,6 @@ class ExportedSample(NamedTuple):
meta: S.SampleMeta
-def _sha256_file(path: Path) -> str:
- h = hashlib.sha256()
- with path.open("rb") as fh:
- for chunk in iter(lambda: fh.read(1 << 20), b""):
- h.update(chunk)
- return h.hexdigest()
-
-
def export_one(
ws: Workspace, record: RunRecord, out_dir: Path, *, overwrite: bool = True,
captions_dir: Path | None = None, run_id: RunId | None = None
@@ -126,7 +118,7 @@ def export_one(
one the key falls back to the directory basename (flat layouts only)."""
key = run_id.slug if run_id is not None else S.sample_key(ws)
dest = out_dir / S.sample_rel_dir(record, key)
- rnd = S.best_round_record(record)
+ rnd = best_round_record(record)
files, code_source = S.code_files_for_round(ws, rnd)
if not files:
raise S.SampleError("no code files in src/ (nothing to export)")
@@ -151,7 +143,7 @@ def export_one(
tmp = dest / "meta.json.tmp"
tmp.write_text(meta.model_dump_json(indent=2))
tmp.replace(dest / "meta.json")
- hashes = {rel: _sha256_file(dest / rel) for rel in all_files}
+ hashes = {rel: sha256_file(dest / rel) for rel in all_files}
return ExportedSample(dest=dest, file_hashes=hashes,
code_sha256=code_sha256(files), meta=meta)
@@ -213,7 +205,7 @@ def export_samples(
for ws, rec, rid in found:
rep.n_runs += 1
- rnd = S.best_round_record(rec)
+ rnd = best_round_record(rec)
j = S.effective_judgment(rnd) if rnd is not None else None
score = j.overall if j is not None else None
if rnd is None:
diff --git a/harness/codeverse/flywheel/index.py b/harness/codeverse/flywheel/index.py
index 0b211f6b..97e943ad 100644
--- a/harness/codeverse/flywheel/index.py
+++ b/harness/codeverse/flywheel/index.py
@@ -12,7 +12,13 @@ from typing import Any
from codeverse.contracts.run import RoundRecord, RunId, RunRecord
from codeverse.flywheel.quality import prompt_hash, quality_tier
-from codeverse.flywheel.record import effective_judgment, iter_runs
+from codeverse.flywheel.record import (
+ best_round_index,
+ best_round_record,
+ effective_judgment,
+ iter_runs,
+)
+from codeverse.flywheel.sample import gate_error_summary
from codeverse.workspace import Workspace
_SCHEMA = """
@@ -43,17 +49,17 @@ CREATE INDEX idx_rounds_slug ON rounds(slug);
def _run_row(ws: Workspace, rec: RunRecord, rid: RunId) -> tuple:
- best = next((r for r in rec.rounds if r.index == rec.best_round), None)
+ best = best_round_record(rec)
best_j = effective_judgment(best) if best is not None else None # degraded → unjudged
passed = None if best_j is None else int(best_j.passed)
dur = (rec.finished_at - rec.started_at).total_seconds() if rec.finished_at else None
- n_err = sum(len(g.errors) for g in best.gates) if best is not None else 0
+ n_err = sum(gate_error_summary(best).values())
score = best_j.overall if best_j is not None else None
tier = quality_tier(passed=None if passed is None else bool(passed), gate_errors=n_err, score=score)
return (
rid.slug, str(ws.root), rec.spec.track.value, rec.spec.language.value, rec.spec.prompt,
prompt_hash(rec.spec.prompt), rec.spec.backends.generator, rec.spec.backends.planner,
- rec.spec.backends.judge, rec.status.value, rec.baseline_score, rec.final_score, rec.best_round,
+ rec.spec.backends.judge, rec.status.value, rec.baseline_score, rec.final_score, best_round_index(rec),
len(rec.rounds), passed, rec.total_usage.cost_usd, rec.total_usage.input_tokens,
rec.total_usage.output_tokens, rec.started_at.isoformat(),
rec.finished_at.isoformat() if rec.finished_at else None, dur, rec.error,
@@ -143,15 +149,3 @@ def summary(db: Path | str) -> list[dict[str, Any]]:
"AVG(n_rounds) AS rounds_mean, SUM(quality_tier = 'A') AS n_tier_a, SUM(quality_tier = 'B') AS n_tier_b "
"FROM runs GROUP BY track, language, generator ORDER BY track, language",
)
-
-
-def top_runs(db: Path | str, n: int = 20, *, track: str | None = None) -> list[dict[str, Any]]:
- where = "WHERE track = ?" if track else ""
- params: tuple = (track, n) if track else (n,)
- return query(db, f"SELECT slug, track, language, generator, final_score, passed, quality_tier, cost_usd, n_rounds "
- f"FROM runs {where} ORDER BY final_score DESC LIMIT ?", params)
-
-
-def round_curve(db: Path | str, slug: str) -> list[dict[str, Any]]:
- return query(db, "SELECT round_index, kind, score, passed, build_ok, gate_errors, cost_usd FROM rounds "
- "WHERE slug = ? ORDER BY round_index", (slug,))
diff --git a/harness/codeverse/flywheel/migrate.py b/harness/codeverse/flywheel/migrate.py
deleted file mode 100644
index 2cb3b39c..00000000
--- a/harness/codeverse/flywheel/migrate.py
+++ /dev/null
@@ -1,150 +0,0 @@
-"""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 contextlib import ExitStack
-from pathlib import Path
-
-from pydantic import BaseModel, Field
-
-from codeverse.flywheel.record import RecordError, load_record, package_run
-from codeverse.proc import RunLocked, exclusive
-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.
-
- Under the run mutex unless ``dry_run`` (it relinks the layout and rewrites
- ``record.json``); a run someone is using is reported SKIPPED, not migrated."""
- m = RunMigration(run=str(ws.root))
- if not ws.exists():
- m.status = SKIPPED
- m.reason = "no spec.json"
- return m
- stack = ExitStack()
- try:
- if not dry_run:
- stack.enter_context(exclusive(ws.root, what=f"3dcv migrate-runs {ws.root.name}"))
- except RunLocked as e:
- m.status, m.reason = SKIPPED, str(e)
- return m
- with stack:
- 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/pairs.py b/harness/codeverse/flywheel/pairs.py
index b9fe3463..c60ecf70 100644
--- a/harness/codeverse/flywheel/pairs.py
+++ b/harness/codeverse/flywheel/pairs.py
@@ -32,7 +32,8 @@ from typing import Any
from codeverse.contracts.run import RoundRecord, RunRecord
from codeverse.flywheel import _git
from codeverse.flywheel.quality import prompt_hash
-from codeverse.flywheel.record import effective_judgment, iter_runs
+from codeverse.flywheel.record import best_round_record, effective_judgment, iter_runs
+from codeverse.proc import read_jsonl_lenient
from codeverse.workspace import Workspace
__all__ = ["build_pairs", "preference_pairs", "repair_pairs", "in_round_repair_pairs",
@@ -147,15 +148,8 @@ def repair_pairs(ws: Workspace, rec: RunRecord, *, slug: str | None = None) -> l
def _round_build_errors(ws: Workspace, index: int) -> list[str]:
"""Failing ``build.done`` error messages of one round, from events.jsonl."""
- p = ws.events_path
- if not p.is_file():
- return []
out: list[str] = []
- for line in p.read_text(errors="replace").splitlines():
- try:
- ev = json.loads(line)
- except ValueError:
- continue
+ for ev in read_jsonl_lenient(ws.events_path, dicts_only=True):
if ev.get("event") == "build.done" and ev.get("round") == index and ev.get("ok") is False:
msg = str(ev.get("error") or "").strip()
if msg:
@@ -215,7 +209,7 @@ def cross_backend_pairs(
continue
cands = []
for ws, rec, slug in runs:
- best = next((r for r in rec.rounds if r.index == rec.best_round), None)
+ best = best_round_record(rec)
if best is None or effective_judgment(best) is None: # unjudged or degraded verdict
continue
cands.append((ws, rec, slug, best))
diff --git a/harness/codeverse/flywheel/record.py b/harness/codeverse/flywheel/record.py
index 92857812..213daac9 100644
--- a/harness/codeverse/flywheel/record.py
+++ b/harness/codeverse/flywheel/record.py
@@ -26,6 +26,7 @@ from codeverse.config import get_settings
from codeverse.contracts.common import Usage
from codeverse.contracts.run import RoundRecord, RunId, RunRecord
from codeverse.flywheel.code_quality import code_quality_block
+from codeverse.proc import version_line
from codeverse.workspace import Workspace
log = logging.getLogger(__name__)
@@ -39,12 +40,8 @@ class RecordError(RuntimeError):
# --------------------------------------------------------------------------- environment
def _cmd_first_line(cmd: list[str]) -> str:
- try:
- proc = subprocess.run(cmd, capture_output=True, text=True, timeout=_VERSION_TIMEOUT_S, check=False)
- except (OSError, subprocess.TimeoutExpired) as e:
- return f"error: {type(e).__name__}"
- out = (proc.stdout or proc.stderr).strip().splitlines()
- return out[0].strip() if out else f"exit {proc.returncode}"
+ rc, line = version_line(cmd, timeout=_VERSION_TIMEOUT_S)
+ return line or f"exit {rc}"
def _git(args: list[str], cwd: Path) -> subprocess.CompletedProcess[str] | None:
@@ -158,6 +155,11 @@ def best_round_index(record: RunRecord) -> int | None:
return record.rounds[-1].index
+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)
+
+
def _n_gate_errors(r: RoundRecord) -> int:
return sum(len(g.errors) for g in r.gates)
@@ -211,7 +213,7 @@ def fill_derived(record: RunRecord) -> RunRecord:
if record.baseline_score is None and scored:
record.baseline_score = effective_score(scored[0])
if record.final_score is None and record.best_round is not None:
- best = next((r for r in record.rounds if r.index == record.best_round), None)
+ best = best_round_record(record)
record.final_score = effective_score(best) if best else None
if record.total_usage.cost_usd == 0 and record.total_usage.input_tokens == 0 and record.rounds:
record.total_usage = _sum_usage(record.rounds)
@@ -235,7 +237,7 @@ def complexity_block(record: RunRecord) -> dict[str, Any] | None:
restored and rebuilt at finalise, so it describes the artifact actually
shipped. ``plan_parts`` / ``parts_per_plan_part`` say whether the build
reached the plan's ambition or collapsed it (docs/COMPLEXITY.md)."""
- best = next((r for r in record.rounds if r.index == record.best_round), None)
+ best = best_round_record(record)
cx = round_complexity(best) if best is not None else None
if cx is None:
cx = next((c for c in (round_complexity(r) for r in reversed(record.rounds)) if c), None)
diff --git a/harness/codeverse/flywheel/sample.py b/harness/codeverse/flywheel/sample.py
index 62b0f1c7..f870d17a 100644
--- a/harness/codeverse/flywheel/sample.py
+++ b/harness/codeverse/flywheel/sample.py
@@ -27,7 +27,6 @@ from codeverse.contracts.common import (
LANGUAGE_LABEL,
TRACK_INFO,
Language,
- Track,
code_file,
)
from codeverse.contracts.run import RoundRecord, RunRecord
@@ -35,18 +34,12 @@ from codeverse.flywheel import _git
from codeverse.flywheel.deliverable import deliverable_path
from codeverse.flywheel.quality import QualityTier, code_fingerprint, prompt_hash, quality_tier
from codeverse.flywheel.record import (
- best_round_index,
effective_judgment,
round_complexity,
round_summary,
)
from codeverse.workspace import Workspace
-#: deprecated aliases — the registries in ``codeverse.contracts.common`` are the
-#: single source now; import ``ENTRY_FILE`` / ``code_file`` / ``TRACK_INFO`` instead
-ENTRY_BY_LANGUAGE: dict[Language, str] = ENTRY_FILE
-CODE_FILE_BY_LANGUAGE: dict[Language, str] = {lang: code_file(lang) for lang in Language}
-TYPE_LABEL: dict[Track, str] = {t: TRACK_INFO[t].label for t in Track}
MAX_GLB_BYTES = 20 * 1024 * 1024
SOURCE_NAME = "3dcodeverse"
SAMPLE_LICENSE = "CC-BY-4.0"
@@ -140,15 +133,6 @@ def sample_rel_dir(record: RunRecord, key: str) -> Path:
return Path(record.spec.track.value) / record.spec.language.value / key
-def _resolve(ws: Workspace, p: str | None) -> Path | None:
- if not p:
- return None
- path = Path(p)
- if not path.is_absolute():
- path = ws.root / path
- return path if path.is_file() else None
-
-
def code_files_for_round(ws: Workspace, rnd: RoundRecord | None) -> tuple[dict[str, bytes], str]:
"""Raw code tree for a round → ``(files, source)`` where source is ``commit``,
``deliverable`` (the packaged snapshot of the best round) or ``working_tree``."""
@@ -209,8 +193,8 @@ def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str
names = [v.name for v in rnd.renders.views]
by_stem = len(set(names)) != len(names) # scene views repeat a camera name per time → use file stems
for v in rnd.renders.views:
- src = _resolve(ws, v.path)
- if src is None:
+ src = ws.rebase(v.path)
+ if not src.is_file():
continue
name = f"view_{src.stem if by_stem else v.name}{src.suffix or '.png'}"
i = 2
@@ -218,11 +202,11 @@ def copy_renders(ws: Workspace, rnd: RoundRecord | None, dest: Path) -> list[str
name = f"view_{src.stem}_{i}{src.suffix or '.png'}"
i += 1
_cp(src, name)
- sheet = _resolve(ws, rnd.renders.contact_sheet)
- if sheet is not None:
+ sheet = ws.rebase(rnd.renders.contact_sheet or "")
+ if sheet.is_file():
_cp(sheet, f"sheet{sheet.suffix or '.png'}")
- tt = _resolve(ws, rnd.renders.turntable)
- if tt is not None:
+ tt = ws.rebase(rnd.renders.turntable or "")
+ if tt.is_file():
_cp(tt, f"turntable{tt.suffix or '.mp4'}")
if not any(o.startswith("renders/sheet") for o in out):
packaged = ws.deliverable / "sheet.png" # new layout keeps the best sheet here
@@ -251,7 +235,9 @@ def copy_textured(ws: Workspace, record: RunRecord, dest: Path) -> list[str]:
(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 deliverable_path(ws, "object_textured.glb")
+ glb = ws.rebase(str(tex.get("glb_textured") or ""))
+ if not glb.is_file():
+ glb = 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")
@@ -386,8 +372,3 @@ def telemetry_digest(ws: Workspace, record: RunRecord) -> dict[str, Any]:
"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
index c921f95f..5629c336 100644
--- a/harness/codeverse/flywheel/telemetry.py
+++ b/harness/codeverse/flywheel/telemetry.py
@@ -38,6 +38,8 @@ from codeverse.contracts.run import (
SettingsSnapshot,
StageCost,
)
+from codeverse.cost.ledger import LEDGER_NAME
+from codeverse.cost.types import Stage
from codeverse.proc import read_json_or_none, write_json_atomic, write_text_atomic
from codeverse.workspace import Workspace
@@ -92,9 +94,10 @@ def _planner_defaults() -> dict[str, Any]:
def _generator_defaults(model_id: str) -> dict[str, Any]:
- """CLI agents own their sampling knobs. Only the deleted in-process ``api-agent``
- exposed ours — the constants below reproduce its shipped defaults so a HISTORICAL
- run record (pre-2026-08-28) still reports what it actually ran with."""
+ """HISTORICAL shim, read-only: CLI agents own their sampling knobs and only the
+ in-process ``api-agent`` (deleted 2026-08-28) exposed ours. The constants reproduce
+ its shipped defaults so a pre-deletion record still reports what it ran with; they
+ configure nothing."""
if backend_kind(model_id) != "api-agent":
return {}
return {"temperature": 0.3, "thinking": "low"}
@@ -193,28 +196,12 @@ _TOOL_KEYS = frozenset({"python", "platform", "host", "blender", "blender_path",
# --------------------------------------------------------------------------- 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
+ return tuple(s.value for s in Stage)
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
diff --git a/harness/codeverse/gallery/__init__.py b/harness/codeverse/gallery/__init__.py
index f366b568..77fee54d 100644
--- a/harness/codeverse/gallery/__init__.py
+++ b/harness/codeverse/gallery/__init__.py
@@ -1,16 +1,16 @@
"""The local run gallery: ``3dcv gallery serve`` (localhost) and ``3dcv gallery build`` (one file).
* ``index`` ``build_index(roots)`` · ``default_roots()`` — record.json → typed entries
-* ``model`` ``RunEntry`` / ``RootSection`` / ``GalleryIndex`` / ``summarize`` / ``match``
-* ``labels`` view-name humanisation + the four disjoint verdict buckets
-* ``page`` the index page (status rail, filters, cards + table)
+* ``model`` ``RunEntry`` / ``RootSection`` / ``GalleryIndex`` / ``summarize`` / ``match``,
+ view-name humanisation + the four disjoint verdict buckets
+* ``page`` the index page (status rail, filters, cards + table) and
+ ``build_static(roots, out.html, embed=…)``
* ``cards`` one run as a card / a table row / a compare column
* ``compare`` ``/compare`` side-by-side + ``/export.csv`` (read-only projections)
* ``detail`` ``/run/<battery>/<slug>`` — rounds, judge, measurement, renders, cost, code
* ``code`` directory listings + the file viewer
* ``viewer`` optional GLB viewer on the vendored three.js (no CDN)
* ``server`` ``GalleryApp.route`` + ``serve(...)`` — loopback-only unless --host is typed
-* ``static_site`` ``build_static(roots, out.html, embed=…)``
"""
from codeverse.gallery.compare import export_csv, render_compare
diff --git a/harness/codeverse/gallery/detail.py b/harness/codeverse/gallery/detail.py
index 2c4adc16..9fe6d6a6 100644
--- a/harness/codeverse/gallery/detail.py
+++ b/harness/codeverse/gallery/detail.py
@@ -13,8 +13,8 @@ from pathlib import Path
from codeverse.contracts.common import ENTRY_FILE
from codeverse.contracts.run import RunRecord
-from codeverse.flywheel.record import effective_judgment
-from codeverse.gallery.cards import gallery_figure, tier_tag, verdict_tag
+from codeverse.flywheel.record import best_round_record, effective_judgment
+from codeverse.gallery.cards import fmt, gallery_figure, tier_tag, verdict_tag
from codeverse.gallery.code import CODE_CSS, numbered, read_text, src_files
from codeverse.gallery.index import _rel, best_sheet, hero_view
from codeverse.gallery.model import RunEntry
@@ -62,10 +62,6 @@ SEVERITY_CLASS = {"critical": "pill-fail", "blocker": "pill-fail", "major": "pil
"moderate": "pill-warn", "minor": "pill-warn"}
-def _fmt(v: float | None, d: int = 3) -> str:
- return "—" if v is None else format(v, f".{d}f")
-
-
def _kv(key: str, value: str) -> str:
return f"<div class='kv'><span class='k'>{esc(key)}</span><span class='v'>{value}</span></div>"
@@ -93,7 +89,7 @@ def _hero(entry: RunEntry, urls: UrlMaker, rec: RunRecord) -> str:
delta = ("—" if entry.score is None or entry.baseline_score is None
else format(entry.score - entry.baseline_score, "+.3f"))
facts = "".join([
- _kv("score", f"<b>{_fmt(entry.score)}</b> (baseline {_fmt(entry.baseline_score)}, Δ {delta})"),
+ _kv("score", f"<b>{fmt(entry.score)}</b> (baseline {fmt(entry.baseline_score)}, Δ {delta})"),
_kv("rounds", f"{entry.rounds} · best r{entry.best_round if entry.best_round is not None else '–'}"),
_kv("gate errors", str(entry.gate_errors) + (
" — " + ", ".join(f"{k}:{v}" for k, v in entry.gate_summary.items()) if entry.gate_summary else "")),
@@ -124,7 +120,7 @@ def _rounds_table(entry: RunEntry, urls: UrlMaker) -> str:
sheet = f"<a href='{esc(urls.file(entry, r.sheet))}'>all views</a>" if r.sheet else "—"
best = " class='best'" if r.index == entry.best_round else ""
rows.append(f"<tr{best}><td class='n'>{r.index}</td><td>{esc(r.kind)}</td>"
- f"<td class='n'>{_fmt(r.score)}</td><td>{verdict}</td><td class='n'>{esc(gates)}</td>"
+ f"<td class='n'>{fmt(r.score)}</td><td>{verdict}</td><td class='n'>{esc(gates)}</td>"
f"<td>{build}</td><td class='n'>{r.cost_usd:.3f}</td><td class='n'>{r.duration_s:.0f}</td>"
f"<td><code class='xs'>{esc(r.commit)}</code></td><td>{sheet}</td></tr>")
body = "".join(rows) or "<tr><td colspan='10' class='faint'>no rounds recorded</td></tr>"
@@ -134,7 +130,7 @@ def _rounds_table(entry: RunEntry, urls: UrlMaker) -> str:
def _judgment_panel(rec: RunRecord, best: int | None) -> str:
- rnd = next((r for r in rec.rounds if r.index == best), None)
+ rnd = best_round_record(rec)
j = effective_judgment(rnd) if rnd is not None else None
if j is None:
return _panel("judge", "<p class='faint small'>the best round has no (non-degraded) verdict.</p>",
@@ -165,8 +161,8 @@ def _judgment_panel(rec: RunRecord, best: int | None) -> str:
return _panel(f"judge — best round r{best}", inner, anchor="judge")
-def _measurement_panel(rec: RunRecord, best: int | None) -> str:
- rnd = next((r for r in rec.rounds if r.index == best), None)
+def _measurement_panel(rec: RunRecord) -> str:
+ rnd = best_round_record(rec)
m = rnd.measurement if rnd is not None else None
if m is None:
m = next((r.measurement for r in reversed(rec.rounds) if r.measurement is not None), None)
@@ -217,10 +213,10 @@ def _complexity_panel(entry: RunEntry, rec: RunRecord) -> str:
block = block if isinstance(block, dict) else {}
index = entry.complexity if entry.complexity is not None else block.get("index")
rows = [_kv("index", f"{float(index):.3f} ({esc(entry.complexity_band or block.get('band', ''))})")]
- for axis, label, fmt in _CX_ROWS:
+ for axis, label, spec in _CX_ROWS:
v = entry.complexity_axes.get(axis, block.get(axis))
if isinstance(v, (int, float)):
- rows.append(_kv(label, fmt.format(float(v))))
+ rows.append(_kv(label, spec.format(float(v))))
if isinstance(block.get("plan_parts"), int) and block["plan_parts"]:
rows.append(_kv("plan parts", str(block["plan_parts"])))
if block.get("parts_per_plan_part") is not None:
@@ -233,14 +229,14 @@ def _complexity_panel(entry: RunEntry, rec: RunRecord) -> str:
return _panel("complexity", f"<div class='kvs'>{''.join(rows)}</div>{note}", anchor="complexity")
-def _renders_panel(entry: RunEntry, urls: UrlMaker, rec: RunRecord, best: int | None) -> str:
- run = Path(entry.path)
- rnd = next((r for r in rec.rounds if r.index == best), None)
+def _renders_panel(entry: RunEntry, urls: UrlMaker, rec: RunRecord) -> str:
+ ws = Workspace(entry.path)
+ rnd = best_round_record(rec)
figs: list[tuple[str, str]] = []
if rnd is not None and rnd.renders is not None:
for v in rnd.renders.views:
- rel = _rel(run, v.path)
- if rel and (run / rel).is_file():
+ rel = _rel(ws, v.path)
+ if rel and (ws.root / rel).is_file():
figs.append((v.name, rel))
figs += [(link.label, link.rel) for link in entry.links
if link.label in ("articulation", "preview.gif") and link.rel]
@@ -358,7 +354,7 @@ def render_detail(entry: RunEntry, urls: UrlMaker, ws: Workspace, rec: RunRecord
if not entry.sheet:
entry = entry.model_copy(update={"sheet": best_sheet(ws, rec)})
if not entry.hero:
- hero, label, n = hero_view(ws, rec, best)
+ hero, label, n = hero_view(ws, rec)
entry = entry.model_copy(update={"hero": hero, "hero_label": label, "n_views": n})
nav = "".join(f"<a href='#{a}'>{a}</a>" for a in
("rounds", "judge", "complexity", "measurement", "renders", "cost", "code"))
@@ -374,8 +370,8 @@ def render_detail(entry: RunEntry, urls: UrlMaker, ws: Workspace, rec: RunRecord
+ _rounds_table(entry, urls)
+ _judgment_panel(rec, best)
+ _complexity_panel(entry, rec)
- + _measurement_panel(rec, best)
- + _renders_panel(entry, urls, rec, best)
+ + _measurement_panel(rec)
+ + _renders_panel(entry, urls, rec)
+ _cost_panel(entry, ws, rec)
+ _code_panel(entry, urls, rec)
+ (_foot_nav(urls, prev, nxt) if urls.has_detail else "")
diff --git a/harness/codeverse/gallery/index.py b/harness/codeverse/gallery/index.py
index 74f8c4dc..ead8db33 100644
--- a/harness/codeverse/gallery/index.py
+++ b/harness/codeverse/gallery/index.py
@@ -21,6 +21,7 @@ from codeverse.flywheel.record import (
RecordError,
battery_label,
best_round_index,
+ best_round_record,
effective_judgment,
find_run_dirs,
is_run_dir,
@@ -58,14 +59,13 @@ def root_label(root: Path) -> str:
return battery_label(Path(root))
-def _rel(run_dir: Path, path: Path | str | None) -> str:
- """``path`` as a run-relative posix string, or ``""`` when it is outside the run."""
+def _rel(ws: Workspace, path: Path | str | None) -> str:
+ """``path`` (rebased into this workspace) as a run-relative posix string, or ``""``
+ when it is outside the run."""
if not path:
return ""
- p = Path(path)
- p = p if p.is_absolute() else run_dir / p
try:
- return p.resolve().relative_to(run_dir.resolve()).as_posix()
+ return ws.rebase(path).resolve().relative_to(ws.root.resolve()).as_posix()
except (ValueError, OSError):
return ""
@@ -80,7 +80,7 @@ def _first_file(run_dir: Path, *rels: str) -> str:
def _round_sheet(ws: Workspace, rec: RunRecord, index: int) -> str:
rnd = next((r for r in rec.rounds if r.index == index), None)
if rnd is not None and rnd.renders is not None and rnd.renders.contact_sheet:
- rel = _rel(ws.root, rnd.renders.contact_sheet)
+ rel = _rel(ws, rnd.renders.contact_sheet)
if rel and (ws.root / rel).is_file():
return rel
return _first_file(ws.root, f"artifacts/renders/r{index:02d}/sheet.png")
@@ -105,13 +105,13 @@ def best_sheet(ws: Workspace, rec: RunRecord) -> str:
HERO_PREFERENCE = ("front_right_34", "back_left_34", "low_front_left", "front")
-def hero_view(ws: Workspace, rec: RunRecord, best: int | None) -> tuple[str, str, int]:
+def hero_view(ws: Workspace, rec: RunRecord) -> tuple[str, str, int]:
"""``(rel, label, n_views)`` — the ONE image a card should show.
A card that shows an 8-up contact sheet at 320 px shows eight unreadable
thumbnails; one 320 px hero view is legible. Costs a single ``is_file``
beyond what the record already told us, so the index stays cheap."""
- rnd = next((r for r in rec.rounds if r.index == best), None)
+ rnd = best_round_record(rec)
if rnd is None or rnd.renders is None or not rnd.renders.views:
return "", "", 0
views = [v for v in rnd.renders.views if not v.name.startswith(("pose_", "articulation"))]
@@ -119,7 +119,7 @@ def hero_view(ws: Workspace, rec: RunRecord, best: int | None) -> tuple[str, str
return "", "", 0
by_name = {v.name: v for v in views}
chosen = next((by_name[n] for n in HERO_PREFERENCE if n in by_name), views[0])
- rel = _rel(ws.root, chosen.path)
+ rel = _rel(ws, chosen.path)
if not rel or not (ws.root / rel).is_file():
return "", "", len(views)
return rel, humanize_view(chosen.name), len(views)
@@ -233,14 +233,14 @@ def entry_from_record(battery: str, ws: Workspace, rec: RunRecord, *, slug: str
``slug`` is the RunId slug the scan minted; without one the directory basename is
used (correct for flat layouts only — nested battery runs are all named ``run``)."""
best = best_round_index(rec)
- rnd = next((r for r in rec.rounds if r.index == best), None)
+ rnd = best_round_record(rec)
j = effective_judgment(rnd) if rnd is not None else None
gates = gate_error_summary(rnd)
n_err = sum(gates.values())
minutes = ((rec.finished_at - rec.started_at).total_seconds() / 60.0) if rec.finished_at else None
digest = telemetry_digest(ws, rec)
caps = rec.extra.get("captions") or {}
- hero, hero_label, n_views = hero_view(ws, rec, best)
+ hero, hero_label, n_views = hero_view(ws, rec)
plan = rec.plan
cx_index, cx_band, cx_axes = _complexity(ws, rec)
return RunEntry(
diff --git a/harness/codeverse/gallery/page.py b/harness/codeverse/gallery/page.py
index 7a09a9c8..49c366cd 100644
--- a/harness/codeverse/gallery/page.py
+++ b/harness/codeverse/gallery/page.py
@@ -17,7 +17,7 @@ from __future__ import annotations
import json
from pathlib import Path
-from codeverse.gallery.cards import TABLE_HEAD, render_card, render_row
+from codeverse.gallery.cards import TABLE_HEAD, fmt, render_card, render_row
from codeverse.gallery.index import build_index
from codeverse.gallery.model import (
FILTER_KEYS,
@@ -34,10 +34,6 @@ from codeverse.gallery.urls import THUMB_PX, StaticUrls, UrlMaker
from codeverse.proc import write_text_atomic
-def _fmt(value: float | None, digits: int = 3, dash: str = "—") -> str:
- return dash if value is None else format(value, f".{digits}f")
-
-
# --------------------------------------------------------------------------- summary
def _verdict_chip(bucket: str, count: int, *, total: int) -> str:
label, cls, why = VERDICT_META[bucket]
@@ -60,7 +56,7 @@ def _summary_strip(entries: list[RunEntry], total: int) -> str:
chips = "".join(_verdict_chip(b, s.breakdown[b], total=s.n) for b in VERDICTS)
per_pass = "—" if s.usd_per_pass is None else f"${s.usd_per_pass:.2f}"
nums = (f"<span title='mean / median best score'>score <b class='num' id='s-score'>"
- f"{_fmt(s.mean_score)} / {_fmt(s.median_score)}</b></span>"
+ f"{fmt(s.mean_score)} / {fmt(s.median_score)}</b></span>"
f"<span>spend <b class='num' id='s-cost'>${s.total_usd:.2f}</b></span>"
f"<span title='total spend divided by the number of passing runs'>per pass "
f"<b class='num' id='s-perpass'>"
diff --git a/harness/codeverse/gallery/server.py b/harness/codeverse/gallery/server.py
index 9ce8ea6e..d0fcfc2c 100644
--- a/harness/codeverse/gallery/server.py
+++ b/harness/codeverse/gallery/server.py
@@ -5,7 +5,7 @@ construction — there is no route that writes anything. Routing is split in tw
so it can be tested without a socket: :meth:`GalleryApp.route` maps a decoded
path + query to a :class:`Response`, and the request handler only moves bytes.
-Safety model (see also ``gallery/paths.py``):
+Safety model (see also ``gallery/urls.py``):
* a URL names a run by ``(battery, slug)`` and those must exist **in the index**,
which only ever contains directories found under the roots the user declared;
@@ -22,7 +22,6 @@ import json
import os
import threading
from dataclasses import dataclass, field
-from datetime import UTC, datetime
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
@@ -385,7 +384,3 @@ def _open(url: str) -> None:
with contextlib.suppress(Exception): # headless box, no browser
webbrowser.open(url)
-
-
-def started_at() -> str:
- return datetime.now(UTC).isoformat(timespec="seconds")
diff --git a/harness/codeverse/proc.py b/harness/codeverse/proc.py
index 827eab21..c873a0cb 100644
--- a/harness/codeverse/proc.py
+++ b/harness/codeverse/proc.py
@@ -7,8 +7,6 @@ tolerant JSON / JSONL readers every "best effort" side-car consumer needs. Peer
of ``workspace.py``; stdlib-only — imports nothing from ``codeverse`` so wrappers,
spatial helpers and agents can all use it without layering back-edges.
-``languages/_common.py`` currently carries the same helpers for its runtime
-callers; it will become a re-export of this module.
"""
from __future__ import annotations
@@ -16,6 +14,7 @@ from __future__ import annotations
import contextlib
import contextvars
import fcntl
+import hashlib
import json
import logging
import os
@@ -27,9 +26,9 @@ from collections import deque
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
-from dataclasses import dataclass, field
+from dataclasses import dataclass
from pathlib import Path
-from typing import IO, Any, TypeVar
+from typing import IO, Any
@dataclass(frozen=True)
@@ -169,7 +168,7 @@ class ManagedProcess:
"""A ``Popen`` in its own session whose process group cannot outlive the ``with`` block.
The shared lifecycle core under :func:`run_subprocess` and
- ``agents.watchdog.run_with_watchdog`` (which keep their public signatures):
+ ``agents/cli_common.run_with_watchdog`` (which keep their public signatures):
* binary pipes + two pump threads feeding a :class:`_BoundedSink` per stream
(:data:`STREAM_BUDGET_BYTES` each, decoded utf-8 ``errors="replace"``);
@@ -347,9 +346,8 @@ class ManagedProcess:
# ------------------------------------------------------------------ env scrubbing
-#: COPY of the credential patterns in ``agents/cli_common.is_secret_env`` (its sibling —
-#: keep the two in sync; tests/core/test_proc.py pins them together). Duplicated because
-#: proc.py imports nothing from ``codeverse``: the agents package sits above this layer.
+#: The ONE owner of the credential patterns: ``agents/cli_common.is_secret_env`` delegates
+#: here (tests/core/test_proc.py pins the two together).
_SECRET_EXACT: frozenset[str] = frozenset({
"GEMINI_API_KEYS", "GEMINI_API_KEY", "GOOGLE_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_API_KEY",
"OPENAI_ORG_ID", "HF_TOKEN", "HUGGINGFACE_TOKEN", "GITHUB_TOKEN", "GH_TOKEN",
@@ -382,6 +380,30 @@ def tail(text: str, *, max_lines: int = 40, max_chars: int = 4000) -> str:
return s[-max_chars:] if len(s) > max_chars else s
+def sha256_file(path: Path | str) -> str:
+ """Chunked sha256 of one file — for manifests / caches keyed on content."""
+ h = hashlib.sha256()
+ with Path(path).open("rb") as fh:
+ for chunk in iter(lambda: fh.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def version_line(cmd: Sequence[str], *, timeout: float) -> tuple[int | None, str]:
+ """``(returncode, first output line)`` of a ``--version``-style probe.
+
+ ``returncode`` is None when the binary could not be run at all (missing, timed out)
+ and the line then says why; an empty line means the probe printed nothing."""
+ try:
+ p = subprocess.run(list(cmd), capture_output=True, text=True, timeout=timeout, check=False)
+ except subprocess.TimeoutExpired:
+ return None, f"timed out after {timeout:g}s"
+ except OSError as e:
+ return None, str(e)
+ out = (p.stdout or p.stderr).strip().splitlines()
+ return p.returncode, (out[0].strip() if out else "")
+
+
def unique_tmp(path: Path) -> Path:
"""A temp sibling of ``path`` unique to this process AND thread.
@@ -434,7 +456,7 @@ def read_json_or_none(path: Path | str, *, errors: str | None = None) -> dict[st
copies in ``flywheel/telemetry.read_json``, ``bench/complexity_report._read_json``,
``gallery/index._measurement_complexity`` / ``_spec_fields``,
``cli/inspect_cmd._best_round_of_record``, ``runlock._holder``,
- ``languages/threejs/lint._load_plan``, ``cost/reconstruct._read_json``,
+ ``languages/threejs/__init__.py``'s plan loader, ``cost/reconstruct._read_json``,
``spatial/_render_common.read_json`` and ``cli/_judge.plan_summary_for`` — all
the same algorithm, differing only in whether they also checked ``isinstance(dict)``
(which every caller then relied on anyway). Strict readers that must raise on
@@ -649,21 +671,6 @@ def exclusive(run_root: Path | str, *, what: str = "", action: str = "enter") ->
# ===================================================================== fanout
-T = TypeVar("T")
-R = TypeVar("R")
-
-
-@dataclass
-class FanOutReport:
- """Timing/outcome per item, for events and logs."""
-
- label: str
- n_items: int
- n_ok: int
- n_failed: int
- durations_s: list[float] = field(default_factory=list)
- total_s: float = 0.0
-
def _in_caller_context(snapshot: contextvars.Context, fn: Callable[[int], None], i: int) -> None:
"""Run ``fn(i)`` with the values the caller's context held at fan-out time.
@@ -707,7 +714,6 @@ def fan_out[T, R](
return results
workers = max(1, min(max_workers, len(items)))
t_all = time.time()
- durations = [0.0] * len(items)
def _run(i: int) -> None:
item = items[i]
@@ -719,7 +725,6 @@ def fan_out[T, R](
out = e
log.warning("%s[%s] failed: %s: %s", label, name, type(e).__name__, e)
dt = time.time() - t0
- durations[i] = dt
results[i] = out
log.info("%s[%s] done in %.1fs (%s)", label, name, dt, "error" if isinstance(out, Exception) else "ok")
if on_done is not None:
@@ -734,15 +739,5 @@ def fan_out[T, R](
range(len(items))))
n_failed = sum(1 for r in results if isinstance(r, Exception))
- report = FanOutReport(label, len(items), len(items) - n_failed, n_failed, durations, time.time() - t_all)
- log.info("%s: %d/%d ok in %.1fs", label, report.n_ok, report.n_items, report.total_s)
+ log.info("%s: %d/%d ok in %.1fs", label, len(items) - n_failed, len(items), time.time() - t_all)
return results
-
-
-def split_results[R](results: Sequence[R | Exception]) -> tuple[list[R], list[Exception]]:
- """Separate successes from failures (order preserved within each list)."""
- ok: list[R] = []
- bad: list[Exception] = []
- for r in results:
- (bad if isinstance(r, Exception) else ok).append(r) # type: ignore[arg-type]
- return ok, bad
diff --git a/harness/codeverse/skills/config.py b/harness/codeverse/skills/config.py
index fda4d1cf..d5cbd69d 100644
--- a/harness/codeverse/skills/config.py
+++ b/harness/codeverse/skills/config.py
@@ -28,6 +28,8 @@ from __future__ import annotations
import logging
import os
+from codeverse.config import env_flag
+
log = logging.getLogger(__name__)
SKILLS_ENV = "CV3D_SKILLS"
@@ -36,28 +38,14 @@ SKILLS_UNVERIFIED_ENV = "CV3D_SKILLS_UNVERIFIED"
SKILLS_ONLY_ENV = "CV3D_SKILLS_ONLY"
DEFAULT_SKILLS_MAX = 5
-_TRUE = frozenset({"1", "on", "true", "yes", "y"})
-_FALSE = frozenset({"", "0", "off", "false", "no", "n"})
-
-
-def _flag(env: str, default: bool = False) -> bool:
- raw = os.environ.get(env, "").strip().lower()
- if raw in _TRUE:
- return True
- if raw in _FALSE:
- return default
- log.warning("%s=%r is not a boolean; treating it as %s", env, raw, "on" if default else "off")
- return default
-
-
def skills_enabled() -> bool:
"""Is the skill system on for this process? Default OFF until the A/B says otherwise."""
- return _flag(SKILLS_ENV)
+ return env_flag(SKILLS_ENV, False)
def skills_unverified() -> bool:
"""Route bundles whose evidence label is ``inherited-unverified``? Default no."""
- return _flag(SKILLS_UNVERIFIED_ENV)
+ return env_flag(SKILLS_UNVERIFIED_ENV, False)
def skills_only() -> frozenset[str]:
diff --git a/harness/codeverse/skills/prompting.py b/harness/codeverse/skills/prompting.py
index f6d8d581..64ad2cab 100644
--- a/harness/codeverse/skills/prompting.py
+++ b/harness/codeverse/skills/prompting.py
@@ -1,7 +1,7 @@
"""How one shared skill library reaches each coding agent — the ONE place that differs.
The library itself is agent-agnostic: plain `agentskills.io` bundles under
-``codeverse/skills/<name>/SKILL.md``, routed by ``router.py`` from typed inputs. Nothing
+``codeverse/skills/<name>/SKILL.md``, routed by ``registry.py`` from typed inputs. Nothing
in it knows what a backend is. What genuinely differs between backends is only
**delivery**, and only in two bits:
@@ -81,8 +81,8 @@ def known_backends() -> tuple[str, ...]:
# ===================================================================== prompting
-#: Per-backend policy lives in ONE place (``skills/delivery.py``); these are re-exported so
-#: existing importers keep working and so nothing here re-derives what a backend needs.
+#: Per-backend policy lives in ONE place (``_BACKENDS`` above); derived here so nothing
+#: else re-derives what a backend needs.
NATIVE_LOADERS = tuple(k for k in known_backends() if delivery_for(k).native_loader)
#: what a NATIVE loader is told. Its own index lists every skill it can see, including any
diff --git a/harness/codeverse/skills/registry.py b/harness/codeverse/skills/registry.py
index 78035ef4..b2b38720 100644
--- a/harness/codeverse/skills/registry.py
+++ b/harness/codeverse/skills/registry.py
@@ -9,7 +9,7 @@ gate reword breaks one golden test instead of silently unrouting a repair skill.
classifies **actionable** findings only: INFO lines ("named objects: [...]") are census,
not defects, and return ``None``.
-**ROUTES** — typed rows, evaluated by ``router.py``. A row fires when ALL of its stated
+**ROUTES** — typed rows, evaluated by ``select()`` below. A row fires when ALL of its stated
conditions hold; ``priority`` decides who survives the cap, and every gate-fired row sits
at >= 90 so a repair round spends its budget on what actually broke.
diff --git a/harness/codeverse/skills/telemetry.py b/harness/codeverse/skills/telemetry.py
index 012ef8b5..734daeea 100644
--- a/harness/codeverse/skills/telemetry.py
+++ b/harness/codeverse/skills/telemetry.py
@@ -34,7 +34,6 @@ from __future__ import annotations
import json
import logging
-from collections.abc import Sequence
from pathlib import Path
from typing import Any
@@ -115,20 +114,4 @@ def append_usage(ws_root: Path, usage: SkillsUsage, **context: Any) -> Path | No
return None
-def deep_read_rate(usages: Sequence[SkillsUsage]) -> dict[str, tuple[int, int]]:
- """skill → (deep reads, times listed) across sessions — the metric with the teeth.
-
- Standing rule from the design: a skill under 20% over 20 sessions is merged or
- deleted. A library that only ever grows is how this ends as bloat."""
- out: dict[str, list[int]] = {}
- for u in usages:
- for name in u.listed:
- out.setdefault(name, [0, 0])[1] += 1
- for r in u.reads:
- if r.deep:
- out.setdefault(r.name, [0, 0])[0] += 1
- return {k: (v[0], v[1]) for k, v in sorted(out.items())}
-
-
-__all__ = ["ATIME_EPSILON_S", "SKILLS_FILE", "TELEMETRY_DIR", "append_usage",
- "deep_read_rate", "probe_reads"]
+__all__ = ["ATIME_EPSILON_S", "SKILLS_FILE", "TELEMETRY_DIR", "append_usage", "probe_reads"]
diff --git a/harness/codeverse/workspace.py b/harness/codeverse/workspace.py
index 55a5bbdc..c65ba717 100644
--- a/harness/codeverse/workspace.py
+++ b/harness/codeverse/workspace.py
@@ -15,7 +15,7 @@ import shutil
import subprocess
import threading
import time
-from collections.abc import Iterator, Sequence
+from collections.abc import Sequence
from pathlib import Path
from typing import Any
@@ -163,11 +163,6 @@ class Workspace:
"""(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."""
@@ -286,7 +281,7 @@ class Workspace:
Use as a context manager for the full stage-then-promote lifecycle, or
call ``.invalidate()`` on the returned stage for a bare wipe of the
- canonical names (the ``remove_stale`` replacement)."""
+ canonical names (a bare wipe, no staging)."""
return ArtifactStage(self, names)
def read_json(self, path: Path) -> dict[str, Any]:
@@ -369,15 +364,6 @@ class Workspace:
self._git("commit", "-q", "-m", message, "--allow-empty")
return self._git("rev-parse", "HEAD").stdout.strip()
- @contextlib.contextmanager
- def git_transaction(self) -> Iterator[None]:
- """Hold this workspace's git lock across SEVERAL calls (re-entrant).
-
- For a caller whose unit spans methods — read the diff, then restore from it —
- where a sibling commit in between would make the second act on stale facts."""
- with self._lock:
- yield
-
def head(self) -> str:
return self._git("rev-parse", "HEAD").stdout.strip()
@@ -438,16 +424,6 @@ class Workspace:
return
self._git("checkout", "-q", commit, "--", *paths)
- def diff(self, a: str, b: str = "HEAD") -> str:
- self._sanitise_git_config()
- return self._git("diff", a, b, "--", "src", "public").stdout
-
- def snapshot_src(self, dest: Path) -> None:
- """Copy src/ (raw code only) to ``dest`` — used by the flywheel exporter."""
- if dest.exists():
- shutil.rmtree(dest)
- shutil.copytree(self.src, dest, ignore=shutil.ignore_patterns("node_modules", "__pycache__"))
-
class ArtifactStage:
"""Stage-then-promote lifecycle for a fixed set of canonical ``artifacts/`` names.
@@ -471,7 +447,7 @@ class ArtifactStage:
* exit without promote **discards** the staging directory — canonical stays absent.
``invalidate()`` also works standalone (no ``with``) as the one-call
- replacement for ``languages._common.remove_stale`` + ``shutil.rmtree``.
+ replacement for wiping the canonical names by hand with ``shutil.rmtree``.
Directory promotion (``meshes/``) is NOT atomic: the old dir is renamed away
(parked inside the staging dir), the new one renamed in, then the parked copy
diff --git a/harness/pyproject.toml b/harness/pyproject.toml
index 121153a4..97ad1fbb 100644
--- a/harness/pyproject.toml
+++ b/harness/pyproject.toml
@@ -60,16 +60,17 @@ dev = ["pytest>=8", "pytest-timeout>=2.3", "pytest-xdist>=3.6", "ruff>=0.5", "py
include = ["codeverse*"]
[tool.setuptools.package-data]
-# Every non-python file a runtime reads at call time. `languages/**/*.md` + the
-# scene starter tree were missing and `spatial/js/*` matched nothing at all (no such
-# directory), so a wheel install shipped no starter files: skeleton.write_example()
-# rglob'd an absent directory and wrote ZERO files while reporting success.
+# Every non-python file a runtime reads at call time. The scene starter tree was once
+# missing and `spatial/js/*` matched nothing at all (no such directory), so a wheel
+# install shipped no starter files: skeleton.write_example() rglob'd an absent
+# directory and wrote ZERO files while reporting success. tests/core/test_portability.py
+# fails on a glob that matches nothing (languages/**/*.md died with the last README).
# `skills/**/*` carries the SKILL.md bundles + their references/: an installed wheel that
# ships none of them routes an empty set, and the failure is silent (the run still passes,
# the skill simply never appears). tests/skills/test_packaging.py builds a wheel and
# asserts the files are in it.
codeverse = ["prompts/**/*", "judges/rubrics/*.yaml", "languages/**/wrappers/*",
- "languages/**/*.md", "languages/**/starter/**/*", "skills/**/*"]
+ "languages/**/starter/**/*", "skills/**/*"]
[tool.setuptools.exclude-package-data]
codeverse = ["**/__pycache__/*"] # a wheel must not carry the build host's bytecode
@@ -89,7 +90,7 @@ timeout = 600
# that happens to have API keys configured fires real requests, and during a provider
# outage it hangs instead of failing — which is exactly what happened on 2026-08-24.
# Everyone's default run is the offline suite (run locally before every push; there is no CI).
-# -n auto: the offline suite is ~2 800 mostly-independent tests and this box has 24
+# -n auto: the offline suite is ~1 900 mostly-independent tests and this box has 24
# cores — serial it is ~3 min, parallel ~15 s. -p no:randomly is NOT set: xdist
# distributes by file, and every test that touches shared state already uses tmp_path.
addopts = ["-m", "not live", "-n", "auto", "--dist", "worksteal"]
@@ -97,5 +98,5 @@ markers = [
"live: needs network + API keys (deselect with -m 'not live')",
"blender: needs a Blender binary",
"node: needs node + runtime_js deps",
- "slow: recomputes something from bench/out (deselect with -m 'not slow')",
+ "slow: builds or validates a distributable artifact (deselect with -m 'not slow')",
]
diff --git a/harness/tests/compare_bench/test_compare_matrix.py b/harness/tests/compare_bench/test_compare_matrix.py
index d776c3a9..98190959 100644
--- a/harness/tests/compare_bench/test_compare_matrix.py
+++ b/harness/tests/compare_bench/test_compare_matrix.py
@@ -251,7 +251,7 @@ def test_every_cell_and_its_harness_run_open_a_ledger(tmp_path: Path):
inner_track = fake_run_track(0.9)
def run_track(spec, ws, resume): # the harness run spends inside its own ledger
- bill("api-agent:baseline:t0")
+ bill("baseline")
return inner_track(spec, ws, resume)
deps = _deps(ev, {"claude-code": FakeBackend(["```python\n" + GOOD.format(score=0.6) + "```"])}, run_track)
@@ -262,7 +262,7 @@ def test_every_cell_and_its_harness_run_open_a_ledger(tmp_path: Path):
assert len(rows) == 2
cells = {r.arm: Path(r.workspace) for r in rows}
harness = cells["harness:gemini-cli:gemini-3.6-flash"]
- assert [r.label for r in load_ledger(harness / "run")] == ["api-agent:baseline:t0"]
+ assert [r.label for r in load_ledger(harness / "run")] == ["baseline"]
assert [r.label for r in load_ledger(harness)] == ["judge:static_object_v1:r00:s0"]
oneshot = cells["oneshot:claude-code"]
assert not (oneshot / "run").exists()
diff --git a/harness/tests/core/test_contract_additions.py b/harness/tests/core/test_contract_additions.py
index 11827843..d883ecb6 100644
--- a/harness/tests/core/test_contract_additions.py
+++ b/harness/tests/core/test_contract_additions.py
@@ -1,4 +1,4 @@
-"""Batch-1 contract additions: registries, as_line, typed AgentJob, RunOptions."""
+"""Registry, finding, agent-job, and run-option contracts."""
from __future__ import annotations
@@ -10,7 +10,6 @@ from codeverse.contracts import (
LANGUAGE_LABEL,
TRACK_INFO,
TRACK_LANGUAGES,
- AgentJob,
Language,
RunOptions,
Spec,
@@ -21,7 +20,9 @@ from codeverse.contracts.artifacts import GateFinding, RenderSet, RenderView, Se
# ------------------------------------------------------------------ registries
-def test_track_info_covers_every_track_and_is_frozen():
+def test_registries_cover_their_enums_and_are_frozen():
+ from codeverse.conventions import LANGUAGE_FRAME, Frame
+
assert set(TRACK_INFO) == set(Track)
assert TRACK_INFO[Track.STATIC_OBJECT].rubric == "static_object_v1"
assert TRACK_INFO[Track.ARTICULATED_OBJECT].rubric == "articulated_v1"
@@ -29,20 +30,13 @@ def test_track_info_covers_every_track_and_is_frozen():
assert TRACK_INFO[Track.GRAPHICS].rubric == "shader_v2"
with pytest.raises(ValidationError):
TRACK_INFO[Track.SCENE].rubric = "other" # frozen
-
-
-def test_entry_file_and_labels_cover_every_language():
assert set(ENTRY_FILE) == set(Language)
assert set(LANGUAGE_LABEL) == set(Language)
+ assert set(TRACK_LANGUAGES) == set(Track)
assert all(e.startswith("src/") for e in ENTRY_FILE.values())
assert code_file(Language.BLENDER) == "code.py"
assert code_file(Language.THREEJS) == "code.js"
assert code_file(Language.GLSL_SHADER) == "code.frag"
-
-
-def test_language_frame_covers_every_language():
- from codeverse.conventions import LANGUAGE_FRAME, Frame
-
assert set(LANGUAGE_FRAME) == {lang.value for lang in Language}
assert LANGUAGE_FRAME["glsl_shader"] is Frame.Y_UP_POS_Z_FRONT
assert LANGUAGE_FRAME["opengl_python"] is Frame.Y_UP_POS_Z_FRONT
@@ -55,12 +49,9 @@ def _finding(**kw) -> GateFinding:
return GateFinding(**base)
-def test_as_line_default_is_message_plus_fix():
+def test_as_line_formats_defaults_flags_and_empty_fields():
assert _finding().as_line() == "leg floats FIX: drop z by 0.02"
assert _finding(fix_hint="").as_line() == "leg floats"
-
-
-def test_as_line_flag_combinations():
f = _finding()
assert f.as_line(with_gate=True, with_hint=False) == "GATE contract: leg floats"
assert f.as_line(with_severity=True, with_hint=False) == "[error] leg floats"
@@ -68,9 +59,6 @@ def test_as_line_flag_combinations():
assert (f.as_line(with_gate=True, with_severity=True, with_target=True)
== "GATE contract: [error] leg floats [leg_1] FIX: drop z by 0.02")
assert not f.as_line().startswith("- ")
-
-
-def test_as_line_skips_empty_target():
assert _finding(target=None).as_line(with_target=True, with_hint=False) == "leg floats"
@@ -82,41 +70,14 @@ def test_render_view_judge_flag_defaults_none():
assert RenderSet().out_dir == ""
-# ------------------------------------------------------------------ AgentJob
-def test_agent_job_legacy_extra_is_lifted_and_kept():
- extra = {"round": 2, "kind": "refine", "language": "blender", "track": "static_object",
- "files_hint": ["src/a.py"], "mcp_command": ["python", "-m", "x"],
- "temperature": 0.7} # unknown keys (like the old api-agent knobs) just stay put
- j = AgentJob(workspace="w", prompt="p", extra=dict(extra))
- assert (j.round, j.kind, j.language, j.track) == (2, "refine", "blender", "static_object")
- assert j.files_hint == ["src/a.py"]
- assert j.mcp_command == ["python", "-m", "x"]
- assert j.extra == extra # untouched: legacy readers see what they were given
-
-
-def test_agent_job_explicit_fields_beat_extra():
- j = AgentJob(workspace="w", prompt="p", round=5, extra={"round": 2})
- assert j.round == 5
-
-
-def test_agent_job_defaults_and_roundtrip():
- j = AgentJob(workspace="w", prompt="p")
- assert j.round == 0 and j.kind == "" and j.files_hint == [] and j.mcp_command is None
- j2 = AgentJob(workspace="w", prompt="p", extra={"round": 3, "temperature": 0.9})
- assert AgentJob(**j2.model_dump()) == j2 # dump/construct stable
-
-
# ------------------------------------------------------------------ RunOptions
-def test_spec_options_default_and_legacy_json():
+def test_spec_options_default_legacy_roundtrip_and_validation():
s = Spec(id="x", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a chair")
assert s.options == RunOptions()
d = s.model_dump(mode="json")
d.pop("options")
s2 = Spec(**d) # old spec.json without options still parses
assert s2.options.candidates is None and s2.options.texture is False
-
-
-def test_spec_options_roundtrip_and_validation():
s = Spec(id="x", track=Track.SCENE, language=Language.SCENE_THREEJS, prompt="p",
options=RunOptions(candidates=3, texture=True))
s2 = Spec(**s.model_dump(mode="json"))
@@ -132,9 +93,3 @@ def test_spec_options_do_not_change_the_plan_stage_hash():
plain = Spec(id="x", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a chair")
opted = plain.model_copy(update={"options": RunOptions(candidates=4, texture=True)})
assert hash_inputs(plan_stage_inputs(plain)) == hash_inputs(plan_stage_inputs(opted))
-
-
-def test_track_languages_still_the_gate():
- assert set(TRACK_LANGUAGES) == set(Track)
- with pytest.raises(ValidationError):
- Spec(id="x", track=Track.SCENE, language=Language.BLENDER, prompt="p")
diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.py
index afd542a8..56aaa619 100644
--- a/harness/tests/core/test_run_layout.py
+++ b/harness/tests/core/test_run_layout.py
@@ -9,15 +9,16 @@ 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
+from codeverse.workspace import EVIDENCE_DIR, 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()
+ evidence = ws.root / EVIDENCE_DIR
+ assert evidence.is_symlink() and os.readlink(evidence) == "artifacts"
+ assert evidence.resolve() == ws.artifacts.resolve()
assert ws.cost_path.parent == ws.telemetry and ws.usage_path.name == "usage.jsonl"
@@ -83,8 +84,7 @@ def test_record_blocks_are_additive(tmp_path: Path):
# --------------------------------------------------------------------------- relocation
def _moved_run(tmp_path: Path):
- """A run written at A/run1 with one contact sheet, then MOVED to B/run1 — the SMOKE2
- shape. Returns ``(old root, new root, the stored sheet path, a record naming it)``."""
+ """Create a record whose absolute sheet path predates a workspace move."""
import shutil
from codeverse.contracts.artifacts import RenderSet
@@ -121,17 +121,7 @@ def _captured(render) -> str:
def test_a_relocated_run_still_resolves_its_stored_paths(tmp_path):
- """SMOKE2: record.json stores ABSOLUTE host paths (29 per run — rounds[].renders[]
- .path, contact_sheet, build.glb_path, build.extra_paths, census exports — plus
- run_state.stages[].result_path), so archiving, moving or rsyncing a run silently
- broke every consumer that trusted them. `3dcv show` printed a contact sheet at the
- OLD location, which did not exist, while the real one sat under the new root;
- object.glb kept resolving because it is recomputed from the workspace, which made
- the breakage partial and therefore silent.
-
- The intended repair, _judge.resolve_paths, only rebased paths for which
- ``Path(p).is_absolute()`` was False — a no-op against every record the harness itself
- writes — and _fmt, which is what show/status actually use, never called it at all."""
+ """Stored absolute paths rebase after moving or archiving a run."""
from codeverse.workspace import Workspace
_a, b, sheet_a, _rec = _moved_run(tmp_path)
@@ -166,13 +156,7 @@ def test_show_prints_the_sheet_that_exists_after_a_move(tmp_path):
def test_a_stale_index_lock_names_the_remedy(tmp_path):
- """CP-7: a run killed mid-commit leaves .git/index.lock behind, and every subsequent
- `3dcv resume <slug>` then failed with the bare line "Command '['git', 'add', '-A']'
- returned non-zero exit status 128". git's own explanation sat unread in e.stderr:
- CalledProcessError.__str__ drops it and cli/main.py prints only
- "run failed: {type(e).__name__}: {e}". The 4-try/1.2 s retry loop is built for a
- LIVE holder and can never clear a stale lock, so the failure repeated forever with
- no clue and no named remedy."""
+ """A stale git index lock is surfaced with its exact safe remedy."""
import subprocess
import pytest
@@ -198,10 +182,7 @@ def test_a_stale_index_lock_names_the_remedy(tmp_path):
def test_a_planted_git_hook_or_filter_never_runs_on_a_commit(tmp_path):
- """The workspace is agent-writable, and ``_git`` used to set HOME=<ws> — so
- ws/.gitconfig WAS git's global config. Four repro-confirmed vectors executed with
- harness privileges on ws.commit(): .git/hooks/pre-commit, a global core.hooksPath, a
- global filter.*.clean + .gitattributes, and a LOCAL filter.*.clean (audit 2026-08-27)."""
+ """Agent-writable hooks and clean filters never execute with harness privileges."""
ws = Workspace(tmp_path / "run").create()
fired = tmp_path / "fired"
shell = f"#!/bin/sh\necho x >> {fired}\n"
@@ -230,12 +211,7 @@ def test_a_planted_git_hook_or_filter_never_runs_on_a_commit(tmp_path):
def test_show_itself_prints_the_relocated_sheet_not_the_stored_one(tmp_path):
- """Sign-off follow-up to SMOKE2. The reported command was `3dcv show`, but the fix
- landed in ``cli/_fmt.py`` (which backs `3dcv status`) — ``cli/layout_cmd.py``'s
- print_evidence still assigned ``rows["contact sheet"] = rnd.renders.contact_sheet``,
- the raw stored ABSOLUTE path, so `3dcv show` on a moved run still printed a sheet
- under the original root while ``object.glb`` beside it resolved correctly. Verified
- on the real e2e_chair_blender run before this line existed."""
+ """The actual ``show`` command also rebases its displayed contact sheet."""
from codeverse.cli.layout_cmd import print_evidence
from codeverse.workspace import Workspace
diff --git a/harness/tests/flywheel_cli/test_flywheel.py b/harness/tests/flywheel_cli/test_flywheel.py
index dea5b948..bb38b3aa 100644
--- a/harness/tests/flywheel_cli/test_flywheel.py
+++ b/harness/tests/flywheel_cli/test_flywheel.py
@@ -13,7 +13,7 @@ import pytest
from codeverse.contracts.run import RunRecord
from codeverse.flywheel import _git
from codeverse.flywheel.export import export_samples
-from codeverse.flywheel.index import build_index, round_curve, summary, top_runs
+from codeverse.flywheel.index import build_index, summary
from codeverse.flywheel.pack import pack_samples, verify_locators
from codeverse.flywheel.pairs import build_pairs
from codeverse.flywheel.quality import (
@@ -225,8 +225,6 @@ def test_build_index_and_queries(runs_dir: Path, tmp_path: Path):
con.close()
s = summary(db)
assert {r["language"] for r in s} == {"blender", "threejs"}
- assert top_runs(db, 1)[0]["slug"] == "wooden_chair_ab12cd34"
- assert [r["score"] for r in round_curve(db, "wooden_chair_ab12cd34")] == [0.55, 0.80]
assert isinstance(load_record(Workspace(runs_dir / "lamp_three")), RunRecord)
@@ -371,42 +369,26 @@ def test_export_includes_textured_assets_when_shipped(fake_run, tmp_path: Path):
assert not (sdir2 / "textures").exists()
-def test_a_battery_dir_is_discovered_rather_than_reported_as_zero_runs(tmp_path):
- """CP-6: pointing an exporter at `bench/out/<battery>` used to report "runs 0,
- exported 0" as a SUCCESS. The old guard only fired when `<root>/runs` existed —
- true for the run_bench layout, FALSE for compare_backends (cells/<id>/<arm>/run) and
- ab_plan (arms/<arm>/cells/<id>/<slug>/run), i.e. exactly today's batteries. All
- three layouts are now discovered instead."""
- from codeverse.flywheel.record import find_run_dirs
+def test_battery_layouts_are_discovered_by_flywheel_and_gallery(tmp_path):
+ """All three battery layouts resolve runs; eval siblings never become gallery runs."""
+ from codeverse.flywheel.record import find_run_dirs, iter_runs
+ from codeverse.gallery.index import scan_root
battery = tmp_path / "static_v2_flash" # run_bench: runs/<id>
(battery / "runs" / "some_run").mkdir(parents=True)
(battery / "runs" / "some_run" / "record.json").write_text("{}")
assert [d.name for d in find_run_dirs(battery)] == ["some_run"]
- cmp_bat = tmp_path / "compare_v2" # compare_backends: cells/<id>/<arm>/run
- cell = cmp_bat / "cells" / "cmp_med_chair" / "harness_api-agent" / "run"
- cell.mkdir(parents=True)
- (cell / "record.json").write_text("{}")
- assert find_run_dirs(cmp_bat) == [cell]
-
- ab = tmp_path / "ab_aa_noise" # ab_plan: arms/<arm>/cells/<id>/<slug>/run
- for arm in ("control", "variant"):
- d = ab / "arms" / arm / "cells" / "ctrl_med_chair" / "harness_api-agent" / "run"
- d.mkdir(parents=True)
- (d / "record.json").write_text("{}")
- assert len(find_run_dirs(ab)) == 2
-
-
-def test_a_gallery_of_a_battery_dir_is_not_a_gallery_of_zero_runs(tmp_path):
- """CP-6, the other half: gallery/index.scan_root did a single `root.iterdir()`, so
- `3dcv gallery build bench/out/<ab battery>` printed "gallery of 0 runs" and exit 0.
-
- A nested run is gated on record.json — the same rule as flywheel.record.is_run_dir.
- The cell's sibling ``eval/`` judge workspace only has a spec.json and used to be
- counted as a phantom run; it must not appear. The entry is named by its RunId slug,
- not the degenerate directory basename ``run``."""
- from codeverse.gallery.index import scan_root
+ compare = tmp_path / "compare_v3" # compare_backends: cells/<id>/<arm>/run
+ for pid in ("p0", "p1"):
+ for arm in ("harness_codex", "oneshot_gemini"):
+ run = compare / "cells" / pid / arm / "run"
+ run.mkdir(parents=True)
+ (run / "record.json").write_text("{}")
+ assert len(find_run_dirs(compare)) == 4
+ invalid: list[str] = []
+ list(iter_runs(compare, on_error=lambda d, e: invalid.append(d.name)))
+ assert len(invalid) == 4, "every cell is reached; these stub records are invalid, not absent"
ab = tmp_path / "ab_aa_noise"
cell = ab / "arms" / "control" / "cells" / "ctrl_med_chair" / "harness_api-agent"
@@ -414,15 +396,12 @@ def test_a_gallery_of_a_battery_dir_is_not_a_gallery_of_zero_runs(tmp_path):
(cell / "run" / "record.json").write_text("{}")
(cell / "eval").mkdir()
(cell / "eval" / "spec.json").write_text("{}")
+ assert find_run_dirs(ab) == [cell / "run"]
section = scan_root(ab)
assert [e.slug for e in section.entries] == ["control__ctrl_med_chair__harness_api-agent"]
-def test_an_empty_battery_dir_still_refuses_to_look_like_an_empty_dataset(tmp_path):
- """A battery directory with the layout but no records is the case the anti-silence
- guard is still for — it must raise, not export nothing and exit 0."""
- import pytest
-
+def test_empty_run_roots_distinguish_a_failed_battery_from_legitimate_empty_input(tmp_path):
from codeverse.flywheel.record import iter_runs
battery = tmp_path / "compare_empty"
@@ -430,45 +409,7 @@ def test_an_empty_battery_dir_still_refuses_to_look_like_an_empty_dataset(tmp_pa
with pytest.raises(FileNotFoundError, match=r"looks like a battery directory"):
list(iter_runs(battery))
-
-def test_a_compare_or_ab_battery_dir_is_exported_not_refused(tmp_path):
- """RS-8 / CP-6, the two reports of one defect. The original guard only knew the
- runs/ layout, so for compare_backends (``cells/<prompt>/<arm>/run``) and ab_plan
- (``arms/<arm>/cells/<prompt>/<slug>/run``) — the drivers that produced today's
- compare_v3 and A-B batteries — pointing an exporter at the battery reported
- n_runs=0 as a SUCCESS and wrote an empty metadata.parquet.
-
- Sign-off note: two waves fixed this, one by raising a loud hint and one by
- discovering the runs. Discovery wins and subsumes the hint — every other battery
- reader (``3dcv cost --runs-dir``) already accepts a battery root, so refusing here
- would have been the only command that did not. The anti-silence guard is kept for
- the case discovery cannot rescue: a battery-SHAPED directory holding no records
- (``test_an_empty_battery_dir_still_refuses_to_look_like_an_empty_dataset``)."""
- from codeverse.flywheel.record import find_run_dirs, iter_runs
-
- compare = tmp_path / "compare_v3"
- for pid in ("p0", "p1"):
- for arm in ("harness_codex", "oneshot_gemini"):
- run = compare / "cells" / pid / arm / "run"
- run.mkdir(parents=True)
- (run / "record.json").write_text("{}")
- assert len(find_run_dirs(compare)) == 4
- seen: list[str] = []
- list(iter_runs(compare, on_error=lambda d, e: seen.append(d.name))) # must not raise
- assert len(seen) == 4, "every cell is reached; these stub records are invalid, not absent"
-
- ab = tmp_path / "ab_plan_v1"
- deep = ab / "arms" / "control" / "cells" / "p0" / "stool_ab12" / "run"
- deep.mkdir(parents=True)
- (deep / "record.json").write_text("{}")
- assert find_run_dirs(ab) == [deep]
-
-
-def test_a_genuinely_empty_runs_root_is_still_just_empty(tmp_path):
- """The hint fires only when a run really does exist below — an empty runs root, and
- a tree of directories holding no record.json at all, are legitimate empty results."""
- from codeverse.flywheel.record import iter_runs
-
+ # Plain empty inputs are valid and stay quiet.
empty = tmp_path / "runs"
empty.mkdir()
assert list(iter_runs(empty)) == []
@@ -479,11 +420,7 @@ def test_a_genuinely_empty_runs_root_is_still_just_empty(tmp_path):
def test_parquet_keeps_the_complexity_columns_the_exporter_writes(tmp_path):
- """RS-9: ``pa.Table.from_pylist(rows, schema=...)`` DROPS any key the schema does not
- name, without a warning. ``row_for_sample`` fills complexity / complexity_band,
- metadata.jsonl keeps them and the module docstring lists them among the parquet's
- queryable extras — but parquet_schema() had no such fields, so every query of the
- shipped dataset (STORAGE_RULES §4) by complexity band silently returned nothing."""
+ """The fixed Arrow schema preserves exported complexity columns."""
import pyarrow.parquet as pq
from codeverse.flywheel.export import parquet_schema, write_parquet
@@ -500,12 +437,7 @@ def test_parquet_keeps_the_complexity_columns_the_exporter_writes(tmp_path):
def test_a_core_only_install_still_gets_a_complete_dataset(runs_dir: Path, tmp_path: Path, monkeypatch):
- """PORT-5: `3dcv flywheel export` (no --pack) called write_parquet unconditionally,
- so on an install without the optional `flywheel` extra it died with a raw
- ModuleNotFoundError AFTER writing every sample folder — a partial dataset with no
- index of any kind. docs/INSTALL.md §4 scopes pyarrow to the extra and promises the
- harness only raises when the named feature is used, so a plain export must degrade:
- metadata.jsonl always, metadata.parquet only when pyarrow is importable."""
+ """Core installs always export JSONL and make parquet optional."""
import builtins
real_import = builtins.__import__
@@ -528,8 +460,7 @@ def test_a_core_only_install_still_gets_a_complete_dataset(runs_dir: Path, tmp_p
def test_pack_refuses_before_writing_anything_when_pyarrow_is_missing(runs_dir: Path, tmp_path: Path, monkeypatch):
- """--pack genuinely needs pyarrow (pack.py reads the index back with pq.read_table),
- so it must say so BEFORE the first sample is written, not after a few hundred."""
+ """Packing refuses before writing when its optional dependency is absent."""
import builtins
from typer.testing import CliRunner
diff --git a/harness/tests/flywheel_cli/test_gemini_image.py b/harness/tests/flywheel_cli/test_gemini_image.py
index 162f18a1..d46cd6e9 100644
--- a/harness/tests/flywheel_cli/test_gemini_image.py
+++ b/harness/tests/flywheel_cli/test_gemini_image.py
@@ -95,9 +95,7 @@ def test_all_keys_dead_raises_the_key_error():
assert ei.value.status == 403 and len(set(used)) == 2
-def test_a_small_image_budget_shortens_the_per_attempt_http_timeout():
- """max_wait_s=60 must clip the attempt's HTTP read timeout below the 180 s
- constant (floored at HTTP_TIMEOUT_FLOOR_S) — mirrors GeminiModel._attempt_config."""
+def _captured_timeout(max_wait_s: float | None = None) -> int:
configs: list = []
class _Capture(_Client):
@@ -110,24 +108,31 @@ def test_a_small_image_budget_shortens_the_per_attempt_http_timeout():
pool = KeyPool(["key_a", "key_b"])
m = GeminiImageModel("test-image", fallback=None, pool=pool, max_attempts=1,
sleep=lambda s: None, client_factory=lambda key: _Capture(key, script, used))
- m.generate("a red cube", size=512, max_wait_s=60.0)
+ kw = {} if max_wait_s is None else {"max_wait_s": max_wait_s}
+ m.generate_with_usage("a red cube", size=512, **kw)
assert len(configs) == 1
- t_ms = configs[0].http_options.timeout
- assert 20_000 <= t_ms <= 60_000, t_ms # clipped to the budget, floored at 20 s
+ return configs[0].http_options.timeout
-def test_no_image_budget_keeps_the_configured_read_timeout():
- configs: list = []
+def test_image_budget_bounds_the_per_attempt_http_timeout():
+ """A small budget clips the read timeout; no budget keeps the configured limit."""
+ clipped = _captured_timeout(60.0)
+ assert 20_000 <= clipped <= 60_000 # clipped to the budget, floored at 20 s
+ assert _captured_timeout() == 180_000
- class _Capture(_Client):
- def _generate(self, *, model, contents, config):
- configs.append(config)
- return super()._generate(model=model, contents=contents, config=config)
- used: list[str] = []
- script = [_image_response()]
- pool = KeyPool(["key_a", "key_b"])
- m = GeminiImageModel("test-image", fallback=None, pool=pool, max_attempts=1,
- sleep=lambda s: None, client_factory=lambda key: _Capture(key, script, used))
- m.generate("a red cube", size=512)
- assert configs[0].http_options.timeout == 180_000 # min(180 s, 900 s remaining) = the constant
+def test_images_are_priced_by_the_generated_size():
+ """A 2K request is billed at the 2K per-image price (it was billed at the 1K rate,
+ 0.067 instead of 0.134); a 512 request generates a 1K image and is billed as one."""
+ from codeverse.models.pricing import per_image_usd
+
+ def cost(size: int) -> float:
+ used: list[str] = []
+ m, _pool = _model([_image_response()], used, [], max_attempts=1)
+ m.model = "gemini-3.1-flash-image"
+ m.fallback = None
+ _images, usage = m.generate_with_usage("brushed steel", size=size)
+ return usage.cost_usd
+
+ assert cost(2048) == pytest.approx(per_image_usd("gemini", "gemini-3.1-flash-image", size=2048)) == pytest.approx(0.134)
+ assert cost(512) == pytest.approx(0.067) and cost(1024) == pytest.approx(0.067)
diff --git a/harness/tests/flywheel_cli/test_run_layout_cli.py b/harness/tests/flywheel_cli/test_run_layout_cli.py
index b7ac3708..796a5c7e 100644
--- a/harness/tests/flywheel_cli/test_run_layout_cli.py
+++ b/harness/tests/flywheel_cli/test_run_layout_cli.py
@@ -1,5 +1,5 @@
-"""deliverable/ + telemetry/ packaging, `3dcv show`, `3dcv migrate-runs`, and
-export / gallery on BOTH layouts (old runs must keep working)."""
+"""deliverable/ + telemetry/ packaging, `3dcv show`, and export / gallery on BOTH
+layouts (old runs must keep working)."""
from __future__ import annotations
@@ -13,7 +13,6 @@ 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.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,
@@ -53,8 +52,12 @@ def old_layout_run(tmp_path: Path, slug: str = "wooden_chair_ab12cd34") -> tuple
# --------------------------------------------------------------------------- packaging
-def test_package_run_builds_deliverable_and_telemetry(fake_run):
+def test_package_run_builds_a_stable_independent_and_loadable_handover(fake_run):
ws, rec = fake_run
+ assert load_telemetry(ws, rec) is None and load_deliverable(ws, rec) is None
+ assert deliverable_path(ws, "object.glb") == ws.artifacts / "object.glb"
+ # Cross the old hard-link fast-path threshold before packaging.
+ (ws.artifacts / "object.glb").write_bytes(b"glTF" + b"\0" * (300 * 1024))
package_run(ws, rec)
assert rec.deliverable is not None and rec.telemetry is not None
d = rec.deliverable
@@ -76,11 +79,11 @@ def test_package_run_builds_deliverable_and_telemetry(fake_run):
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"]
+ assert deliverable_path(ws, "object.glb") == ws.deliverable / "object.glb"
+ assert deliverable_path(ws, "nope.glb") is None
-
-def test_deliverable_rebuild_is_idempotent(fake_run):
- ws, rec = fake_run
- first = build_deliverable(ws, rec)
+ # Rebuilding unchanged content is byte-for-byte stable.
+ first = rec.deliverable
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())
@@ -88,19 +91,21 @@ def test_deliverable_rebuild_is_idempotent(fake_run):
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]
+ # Package metadata can be recovered from files even before the caller saves rec.
+ bare = load_record(ws)
+ assert bare.telemetry is None and bare.deliverable is None
+ assert load_telemetry(ws, bare) is not None and load_deliverable(ws, bare) is not None
-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
+ # Delivered assets are copies: editing a hand-over cannot mutate evidence.
+ delivered = ws.deliverable / "object.glb"
+ assert delivered.stat().st_nlink == 1 and (ws.artifacts / "object.glb").stat().st_nlink == 1
+ delivered.write_bytes(b"user edited the hand-over copy")
+ assert (ws.artifacts / "object.glb").read_bytes().startswith(b"glTF")
-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."""
+def test_telemetry_handles_reconstructed_live_and_unavailable_ledgers(fake_run, monkeypatch):
ws, rec = fake_run
+ # Historic records reconstruct rows and reconcile them to the recorded total.
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)
@@ -112,9 +117,7 @@ def test_cost_summary_reconciles_with_the_record_total(fake_run):
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())
-
-def test_usage_rows_alias_a_live_ledger_instead_of_copying_it(fake_run):
- ws, rec = fake_run
+ # A live ledger is aliased, not copied.
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")
@@ -123,9 +126,7 @@ def test_usage_rows_alias_a_live_ledger_instead_of_copying_it(fake_run):
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
+ # A core-only install still emits settings and the record-level total.
import codeverse.flywheel.telemetry as T
def boom(*_a, **_k):
@@ -139,20 +140,6 @@ def test_telemetry_degrades_when_the_cost_package_is_unavailable(fake_run, monke
assert tele.cost.n_calls == 0 and tele.settings is not None # settings never depend on the ledger
-def test_deliverable_files_are_real_copies_not_hardlinks(fake_run):
- """Editing a delivered file must never mutate the canonical evidence: every
- deliverable file is a real copy (st_nlink == 1), whatever its size — the old
- ≥256 KiB hard-link fast path silently broke the recorded sha256."""
- ws, rec = fake_run
- (ws.artifacts / "object.glb").write_bytes(b"glTF" + b"\0" * (300 * 1024)) # past the old link floor
- build_deliverable(ws, rec)
- delivered = ws.deliverable / "object.glb"
- assert delivered.is_file() and delivered.stat().st_nlink == 1
- assert (ws.artifacts / "object.glb").stat().st_nlink == 1
- delivered.write_bytes(b"user edited the hand-over copy")
- assert (ws.artifacts / "object.glb").read_bytes().startswith(b"glTF") # evidence untouched
-
-
def test_rejected_texture_pass_is_not_delivered_or_linked(fake_run):
"""Belt and braces: a stray canonical object_textured.glb from a rejected pass
is skipped by the deliverable AND by the gallery links (both gate on shipped)."""
@@ -171,64 +158,12 @@ def test_rejected_texture_pass_is_not_delivered_or_linked(fake_run):
assert "textured glb" in {ln.label for ln in entry.links}
-# --------------------------------------------------------------------------- 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):
+def test_show_sections_and_status_share_the_packaged_run(fake_run):
ws, rec = fake_run
package_run(ws, rec)
r = _show(ws.root.name, ws.root.parent)
@@ -241,19 +176,12 @@ def test_show_prints_three_separated_sections(fake_run):
assert "spent / budget" in out and "models per role" in out and "price table" in out
assert "gemini-cli" 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)
+ # A selected section stays isolated, and invalid selectors fail cleanly.
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)
+ # The legacy status view stays available and points to the richer view.
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
@@ -293,7 +221,7 @@ def test_export_and_gallery_on_both_layouts(tmp_path: Path):
assert n == 2 and "deliverable" in path.read_text()
new_item = entry_from_record("runs", ws_new, load_record(ws_new))
old_item = entry_from_record("runs", ws_old, load_record(ws_old))
- assert new_item.cost_by_stage == {} or isinstance(new_item.cost_by_stage, dict)
+ assert new_item.cost_by_stage and old_item.cost_by_stage == {}
new_links = {ln.label: ln.rel for ln in new_item.links}
old_links = {ln.label: ln.rel for ln in old_item.links}
assert old_links["glb"] == "artifacts/object.glb"
@@ -311,12 +239,3 @@ def test_export_falls_back_to_the_packaged_snapshot_without_git(tmp_path: Path):
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/gallery/test_triage.py b/harness/tests/gallery/test_triage.py
index 731949a4..d6ef8830 100644
--- a/harness/tests/gallery/test_triage.py
+++ b/harness/tests/gallery/test_triage.py
@@ -101,7 +101,7 @@ def test_hero_falls_back_to_the_sheet_when_a_round_has_no_views(tmp_path: Path):
ws, rec = make_fake_run(tmp_path / "runs", "noviews")
for rnd in rec.rounds:
rnd.renders = None
- assert hero_view(ws, rec, rec.best_round) == ("", "", 0)
+ assert hero_view(ws, rec) == ("", "", 0)
# --------------------------------------------------------------------------- labels
diff --git a/harness/tests/install/test_docs.py b/harness/tests/install/test_docs.py
index 2d64be3b..09884afc 100644
--- a/harness/tests/install/test_docs.py
+++ b/harness/tests/install/test_docs.py
@@ -1,32 +1,20 @@
-"""Offline guards for the install documentation.
-
-Covers only the files the install guide owns (``docs/INSTALL.md``, the three
-READMEs, ``scripts/setup.sh``) so a doc change elsewhere cannot fail them:
-
-* ``docs/INSTALL.md`` exists and is non-empty;
-* every command in a fenced *shell* block starts with a binary we expect a
- reader to have (catches copy-paste typos and invented tools);
-* every internal markdown link, backticked ``*.md`` path and same-page anchor
- resolves;
-* ``scripts/setup.sh`` is executable, parses (``bash -n``) and answers ``--help``;
-* every extra declared in ``pyproject.toml`` is documented in INSTALL.md.
-"""
+"""Offline guards for the install guide, READMEs, and setup script."""
from __future__ import annotations
import os
import re
import subprocess
-import sys
import tomllib
from pathlib import Path
+from types import SimpleNamespace
import pytest
HARNESS = Path(__file__).resolve().parents[2]
REPO = HARNESS.parent
INSTALL = HARNESS / "docs" / "INSTALL.md"
-SETUP = HARNESS / "scripts" / "setup.sh"
+SETUP = HARNESS / "setup.sh"
#: docs owned by the install guide (repo README is optional: the harness can be checked out alone)
OWNED_DOCS = [INSTALL, HARNESS / "README.md", HARNESS / "runtime_js" / "README.md", REPO / "README.md"]
@@ -43,7 +31,7 @@ ALLOWED_BINARIES = {
"git", "python", "python3", "pip", "pip3", "pytest", "conda", "uv", "node", "npm", "npx", "nvm",
"sudo", "apt-get", "apt", "brew", "dnf", "pacman",
# this project
- "3dcv", "3dcodeverse", "setup.sh", "blender", "ffmpeg", "gemini", "claude", "codex", "agy",
+ "3dcv", "3dcodeverse", "setup.sh", "blender", "gemini", "claude", "codex", "agy",
}
_ENV_ASSIGN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
@@ -110,26 +98,23 @@ def test_install_guide_exists() -> None:
assert INSTALL.is_file(), f"{INSTALL} is missing"
text = INSTALL.read_text()
assert len(text) > 2000, "docs/INSTALL.md looks truncated"
- for needle in ("runtime_js", "npm ci", "3dcodeverse doctor", "GEMINI_API_KEYS", "scripts/setup.sh"):
+ for needle in ("runtime_js", "npm ci", "3dcodeverse doctor", "GEMINI_API_KEYS", "setup.sh"):
assert needle in text, f"docs/INSTALL.md never mentions {needle!r}"
@pytest.mark.parametrize("doc", existing_docs(), ids=lambda p: str(p.relative_to(REPO)))
-def test_shell_commands_use_known_binaries(doc: Path) -> None:
+def test_owned_docs_have_valid_commands_links_and_paths(doc: Path) -> None:
bad: list[str] = []
- for lang, body in fenced_blocks(doc.read_text()):
+ text = doc.read_text()
+ for lang, body in fenced_blocks(text):
if lang not in SHELL_LANGS:
continue
for cmd in shell_commands(body):
name = cmd.split("/")[-1]
if cmd not in ALLOWED_BINARIES and name not in ALLOWED_BINARIES:
bad.append(cmd)
- assert not bad, f"{doc}: unknown command(s) in shell blocks: {sorted(set(bad))}"
+ assert not bad, f"{doc}: unknown shell commands: {sorted(set(bad))}"
-
[email protected]("doc", existing_docs(), ids=lambda p: str(p.relative_to(REPO)))
-def test_internal_links_resolve(doc: Path) -> None:
- text = doc.read_text()
headings = {slugify(ln) for ln in text.splitlines() if ln.startswith("#")}
missing: list[str] = []
for target in _MD_LINK.findall(text):
@@ -142,30 +127,23 @@ def test_internal_links_resolve(doc: Path) -> None:
path, _, anchor = target.partition("#")
if path and not (doc.parent / path).exists():
missing.append(f"link {target}")
- assert not missing, f"{doc}: unresolved {missing}"
+ assert not missing, f"{doc}: unresolved links: {missing}"
-
[email protected]("doc", existing_docs(), ids=lambda p: str(p.relative_to(REPO)))
-def test_backticked_markdown_paths_resolve(doc: Path) -> None:
- """`docs/INSTALL.md`-style references must point at a file that exists."""
- missing = []
- for ref in sorted(set(_BACKTICK_MD.findall(doc.read_text()))):
+ missing_paths = []
+ for ref in sorted(set(_BACKTICK_MD.findall(text))):
if ref.startswith("~"):
continue
if not any((base / ref).exists() for base in (doc.parent, HARNESS, REPO)):
- missing.append(ref)
- assert not missing, f"{doc}: backticked markdown path(s) do not exist: {missing}"
+ missing_paths.append(ref)
+ assert not missing_paths, f"{doc}: unresolved backticked paths: {missing_paths}"
-def test_setup_script_is_executable_and_parses() -> None:
+def test_setup_script_is_executable_parses_and_has_help() -> None:
assert SETUP.is_file(), f"{SETUP} is missing"
assert os.access(SETUP, os.X_OK), f"{SETUP} is not executable (chmod +x)"
- assert SETUP.read_text().startswith("#!"), "scripts/setup.sh has no shebang"
+ assert SETUP.read_text().startswith("#!"), "setup.sh has no shebang"
proc = subprocess.run(["bash", "-n", str(SETUP)], capture_output=True, text=True, timeout=60)
assert proc.returncode == 0, f"bash -n failed:\n{proc.stderr}"
-
-
-def test_setup_script_help_works() -> None:
proc = subprocess.run(["bash", str(SETUP), "--help"], capture_output=True, text=True, timeout=60)
assert proc.returncode == 0, f"setup.sh --help exited {proc.returncode}:\n{proc.stderr}"
assert "--extras" in proc.stdout
@@ -179,6 +157,14 @@ def test_every_pyproject_extra_is_documented() -> None:
assert not undocumented, f"extras missing from docs/INSTALL.md: {undocumented}"
+def test_bare_pytest_keeps_live_tests_opt_in() -> None:
+ """A default local run must never spend API quota or wait on a provider."""
+ with (HARNESS / "pyproject.toml").open("rb") as fh:
+ addopts = tomllib.load(fh)["tool"]["pytest"]["ini_options"]["addopts"]
+ assert "-m" in addopts
+ assert addopts[addopts.index("-m") + 1] == "not live"
+
+
#: `pytest ... -m "<expr>"` as published in the docs
_PYTEST_MARKER_EXPR = re.compile(r'pytest[^\n]*?-m\s+"([^"]+)"')
#: every file that publishes a pytest command a reader will paste
@@ -188,12 +174,7 @@ DOCS_WITH_TEST_COMMANDS = [INSTALL, HARNESS / "docs" / "RUNBOOK.md", HARNESS / "
@pytest.mark.parametrize("doc", DOCS_WITH_TEST_COMMANDS, ids=lambda p: p.name)
def test_documented_pytest_subsets_never_re_enable_the_live_tests(doc: Path) -> None:
- """PORT-1: a command-line ``-m`` REPLACES ``addopts = ["-m", "not live"]``, it does not
- add to it. The published "pure-python subset" line was ``-m "not blender and not
- node"``, which selects 23 live tests (2058 collected vs 2035) — run verbatim it opened
- real Gemini connections and hung against the intermittent provider, three lines above a
- sentence promising the opposite. Every documented selection must spell ``not live``
- itself; the only exception is the deliberate ``-m live`` opt-in."""
+ """Every documented marker override must keep live tests opt-in."""
if not doc.is_file(): # the harness can be checked out without the repo README
pytest.skip(f"{doc} not present")
for expr in _PYTEST_MARKER_EXPR.findall(doc.read_text()):
@@ -202,12 +183,7 @@ def test_documented_pytest_subsets_never_re_enable_the_live_tests(doc: Path) ->
def test_doctor_checks_every_module_of_every_optional_extra(monkeypatch) -> None:
- """PORT-3: docs/INSTALL.md §4 says `3dcv doctor` lists every one of these modules under
- `python deps`, and docs/RUNBOOK.md:12 names moderngl explicitly — but neither moderngl
- nor cadquery was in ``_PY_DEPS``, so a venv installed with every extra EXCEPT
- [graphics] printed "21/21 importable" and exited 0, and the graphics track then died
- with "no usable OpenGL context: ModuleNotFoundError: No module named 'moderngl'" — a
- missing pip package reported as a GPU/driver problem."""
+ """Every optional dependency is checked and attributed to its install extra."""
import importlib
from codeverse.doctor import _OPTIONAL_DEPS, _PY_DEPS, check_python_deps
@@ -217,12 +193,6 @@ def test_doctor_checks_every_module_of_every_optional_extra(monkeypatch) -> None
wanted = {re.split(r"[<>=!\[ ]", req)[0].replace("-", "_")
for name, reqs in extras.items() if name not in ("all", "dev") for req in reqs}
assert not wanted - set(_PY_DEPS), f"extras doctor never checks: {sorted(wanted - set(_PY_DEPS))}"
- # ...and every one of them must also be ATTRIBUTED to its extra. Checking without
- # attributing is what made a correct base install report itself broken: scipy (urdf),
- # networkx (mesh) and pyarrow (flywheel) were in _PY_DEPS but not in _OPTIONAL_DEPS, so
- # a fresh 3.10 clone installed exactly as docs/INSTALL.md §1 documents printed
- # `python deps FAIL 14/23` with a remedy that named four of the five extras and could
- # not clear the row. Found on the sign-off clean-clone run, 2026-08-24.
assert not wanted - set(_OPTIONAL_DEPS), (
f"extras doctor checks but cannot name: {sorted(wanted - set(_OPTIONAL_DEPS))}")
# the two lazily-imported tracks are a WARN naming their extra, not a FAIL: without them
@@ -256,46 +226,84 @@ def test_doctor_checks_every_module_of_every_optional_extra(monkeypatch) -> None
assert extra in deps[2], f"the remedy does not name [{extra}]: {deps[2]}"
-def test_doctor_rows_have_troubleshooting_entries() -> None:
- """Every check `3dcv doctor` can print must appear in the INSTALL troubleshooting table."""
+def test_doctor_rows_have_troubleshooting_entries(monkeypatch) -> None:
+ """Run real checks under deterministic stand-ins; require every row in the fix table."""
from codeverse import doctor as doctor_mod
+ from codeverse.config import Settings
+ from codeverse.models.health import PoolBudget
+ from codeverse.proc import ProcResult
+
+ settings = SimpleNamespace(
+ gemini_api_keys=("fake",), anthropic_api_key="", openai_api_key="",
+ rate=SimpleNamespace(rpm_per_key=1, tpm_per_key=1_000, max_in_flight=1),
+ binaries=SimpleNamespace(node="node", gemini_cli="gemini", claude_cli="claude",
+ codex_cli="codex", agy_cli="agy"),
+ resolve_blender=lambda: "blender",
+ runtime_js_dir=lambda: HARNESS / "runtime_js",
+ )
+ monkeypatch.setattr(doctor_mod, "get_settings", lambda: settings)
+ monkeypatch.setattr(doctor_mod, "_ver", lambda *args, **kwargs: (True, "v1"))
+ monkeypatch.setattr(
+ "codeverse.proc.run_subprocess",
+ lambda *args, **kwargs: ProcResult(0, '{"gpu": true, "renderer": "fake"}', "", False, 1),
+ )
+ monkeypatch.setattr("codeverse.models.health.pool_budget", lambda: PoolBudget(1, 64))
+ monkeypatch.setattr(
+ "codeverse.models.get_chat_model",
+ lambda model: SimpleNamespace(generate=lambda request: SimpleNamespace(
+ text="pong", usage=SimpleNamespace(cost_usd=0.0))),
+ )
+ gate = SimpleNamespace(snapshot=lambda: {
+ "name": "gemini:test", "storming": False, "storms": 0, "hits": 0,
+ "probes": 0, "parked_s": 0, "closed_for_s": 0,
+ })
+ monkeypatch.setattr("codeverse.models.retry.all_gates", lambda: [gate])
+ monkeypatch.setattr("codeverse.skills.registry.ROUTED_SKILLS", ("missing",))
- text = INSTALL.read_text()
- names = {"python", "python deps", "blender", "node", "three", "puppeteer", "chrome webgl",
- "gemini keys", "anthropic key", "openai key", "gemini quota", "gemini pool",
- "storm gate", "gemini-cli", "claude", "codex", "agy", "git", "ffmpeg", "mcp"}
- assert hasattr(doctor_mod, "run_doctor")
- missing = [n for n in sorted(names) if f"`{n}`" not in text]
- assert not missing, f"doctor rows undocumented in docs/INSTALL.md: {missing}"
+ rows = doctor_mod.run_doctor(live=True, gpu=True, skills=True)
+ def no_runtime() -> Path:
+ raise RuntimeError("runtime_js unavailable")
-if __name__ == "__main__": # pragma: no cover
- sys.exit(pytest.main([__file__, "-q"]))
+ monkeypatch.setattr(
+ doctor_mod, "get_settings",
+ lambda: SimpleNamespace(binaries=settings.binaries, runtime_js_dir=no_runtime),
+ )
+ rows += doctor_mod.check_node() # the alternate row when runtime_js cannot resolve
+
+ pool_detail = next(detail for name, _, detail in rows if name == "pool sharing")
+ mentioned_settings = set(re.findall(r"\b(CV3D_[A-Z0-9_]+)=", pool_detail))
+ assert mentioned_settings and mentioned_settings <= set(Settings._FLAT_ALIASES), (
+ f"doctor recommends setting unknown variables: {sorted(mentioned_settings - set(Settings._FLAT_ALIASES))}")
+
+ troubleshooting = INSTALL.read_text().split("### Troubleshooting table", 1)[1].split("\n---", 1)[0]
+ documented = {
+ name
+ for line in troubleshooting.splitlines() if line.startswith("|")
+ for name in re.findall(r"`([^`]+)`", line.split("|", 2)[1])
+ if not name.startswith("--")
+ }
+ names = {"storm gate" if name.startswith("storm gate ") else name for name, _, _ in rows}
+ missing = sorted(names - documented)
+ assert not missing, f"doctor rows undocumented in docs/INSTALL.md: {missing}"
def test_architecture_package_map_covers_every_module():
- """`docs/ARCHITECTURE.md` is the maintained map of the codebase — a module that
- exists but is not on it is a hole in the map.
-
- Hand-maintained docs drift silently: three parallel waves on 2026-08-24 added six
- modules (brief, plan_budget, tokens, storm, health, _infra) and none reached the
- map. A whole package (`reference/`, 11 modules) had never been on it at all.
-
- The doc's shorthand counts: an explicit name, a glob (`tools*.py`, `joints*.py`),
- or the bare stem in prose all satisfy it. `wrappers/` subtrees are covered by the
- `wrappers/` entry, and private / dunder modules are exempt.
- """
+ """Every public module appears in the architecture package-map code block."""
import fnmatch
- import re
- from pathlib import Path
root = Path(__file__).resolve().parents[2]
arch = (root / "docs" / "ARCHITECTURE.md").read_text()
- globs = set(re.findall(r"[A-Za-z_][\w*]*\.py", arch))
+ _, marker, rest = arch.partition("## 2. Package map (as built)")
+ assert marker, "docs/ARCHITECTURE.md has no package-map section"
+ blocks = fenced_blocks(rest)
+ assert blocks, "docs/ARCHITECTURE.md package map has no fenced code block"
+ package_map = blocks[0][1]
+ globs = set(re.findall(r"[A-Za-z_][\w*]*\.py", package_map))
def documented(mod: Path) -> bool:
return (any(fnmatch.fnmatch(mod.name, g) for g in globs)
- or re.search(rf"\b{re.escape(mod.stem)}\b", arch) is not None)
+ or re.search(rf"\b{re.escape(mod.stem)}\b", package_map) is not None)
missing = sorted(
str(m.relative_to(root))
@@ -308,12 +316,7 @@ def test_architecture_package_map_covers_every_module():
def test_setup_verifies_the_interpreter_it_installed_into(tmp_path) -> None:
- """PORT-6: the closing doctor is the installer's only verification, and it used to
- run `command -v 3dcodeverse` first. With `--python` — the documented flag for
- installing into a NON-activated interpreter — that venv's entry point is not on PATH,
- so setup.sh ran a pre-existing install (here /home/.../miniconda3/bin/3dcodeverse,
- python 3.13) and printed an all-green table for an environment it never touched.
- An installer must verify what it installed."""
+ """The closing doctor uses ``--python``, not an unrelated executable on PATH."""
import sys
fake = tmp_path / "bin"
@@ -332,11 +335,7 @@ def test_setup_verifies_the_interpreter_it_installed_into(tmp_path) -> None:
def test_setup_names_the_remedy_when_the_interpreter_has_no_pip(tmp_path) -> None:
- """PORT-7: on a stock Debian/Ubuntu box `/usr/bin/python3` ships without pip and is
- PEP 668 marked, so the primary documented install path passed the whole prerequisite
- block and then aborted on one unexplained line, `/usr/bin/python3: No module named
- pip`, exit 1. setup.sh already die()s with actionable text for a missing python,
- git, npm and package-lock.json; pip was the gap in its own contract."""
+ """A Python without pip fails with an actionable distro/venv remedy."""
import sys
# a stand-in that answers the version probes but refuses `-m pip`, like a distro python3
@@ -356,8 +355,6 @@ def test_setup_names_the_remedy_when_the_interpreter_has_no_pip(tmp_path) -> Non
def test_install_docs_list_pip_and_venv_as_prerequisites() -> None:
- """The §2.2 table listed python/git/node/blender/ffmpeg but never pip or venv, and
- §3 called a virtualenv "recommended but not required" — untrue on the OS §2.1 names."""
text = INSTALL.read_text()
assert "python3-venv" in text and "EXTERNALLY-MANAGED" in text
assert "pip + venv" in text, "the requirements table must name pip and venv"
diff --git a/harness/tests/skills/test_contract_agreement.py b/harness/tests/skills/test_contract_agreement.py
index 88dd6e63..599f9a01 100644
--- a/harness/tests/skills/test_contract_agreement.py
+++ b/harness/tests/skills/test_contract_agreement.py
@@ -1,22 +1,4 @@
-"""A skill may not contradict the language contract, and neither may contradict the gate.
-
-WHY this is the sharpest of the contradiction tests: ``prompts/<lang>/contract.md`` and a
-routed SKILL.md land in the SAME session, one in the system prompt and one in a file the
-agent opens. Two numbers for one physical quantity is strictly worse than one number,
-because the agent now has to choose and we have no idea which it picks.
-
-The arbiter is neither document. It is the gate constant, so all three checks below are
-anchored on live code:
-
- * weld overlap and contact gap, stated anywhere in a contract, against
- ``PENETRATION_WARN_M`` and ``CONTACT_GAP_M``;
- * a skill may not recommend an API its language's contract forbids;
- * a skill may not restate a contract number with a different value.
-
-The first of these caught three shipped contracts telling the agent to overlap parts by
-2-4 mm / ">= 2 mm" while ``connectivity.py`` WARNs above 2 mm and its own ``fix_hint``
-says "overlap by <= 2 mm" — against the top defect class in the corpus.
-"""
+"""Keep skill advice, language contracts and live gate tolerances consistent."""
from __future__ import annotations
@@ -26,29 +8,24 @@ from pathlib import Path
import pytest
from codeverse.conventions import CONTACT_GAP_M
-from codeverse.languages._docs import PROMPT_DIRS
+from codeverse.prompts.catalog import PROMPT_DIRS
from codeverse.skills import bundle_dirs, iter_skills, skills_dir
from codeverse.skills.registry import ROUTES
from codeverse.spatial.connectivity import PENETRATION_WARN_M
HARNESS = Path(__file__).resolve().parents[2]
PROMPTS = HARNESS / "codeverse" / "prompts"
-#: the per-language contract an agent reads. There was a second family under
-#: languages/<lang>/CONTRACT.md until 2026-08-28; it was unreachable (contract_doc
-#: always read prompts/ first) and two of its numbers had drifted, so it is gone.
CONTRACTS = sorted(PROMPTS.glob("*/contract.md"))
BUNDLES = bundle_dirs()
SKILLS = list(iter_skills()) if BUNDLES else []
-#: prompts/<dir> per language id — codeverse.languages._docs owns the mapping now
+#: prompts/<dir> per language id — codeverse.prompts.catalog owns the mapping
#: (urdf_blender's docs live under prompts/urdf)
_DIR_FOR_LANG = {k.value: v for k, v in PROMPT_DIRS.items()}
WARN_MM = PENETRATION_WARN_M * 1000
GAP_MM = CONTACT_GAP_M * 1000
-#: "2-4 mm overlap", "overlap (>= 2 mm)", "reaches 4 mm into the seat (weld)",
-#: "sunk 1.5 mm into the door (weld)" — a number in mm within a sentence about welding.
#: The sentence boundary must NOT be a decimal point: splitting "0.5-2 mm" on the dot
#: leaves "5-2 mm" and invents a 5 mm recommendation that nobody wrote.
_SENTENCE_SPLIT = re.compile(r"(?<!\d)\.(?!\d)|\n")
@@ -79,27 +56,25 @@ def _mm_values(sentence: str) -> list[float]:
return out
[email protected]("contract", CONTRACTS, ids=[f"{p.parent.name}/{p.name}" for p in CONTRACTS])
-def test_no_contract_asks_for_an_overlap_the_gate_calls_interpenetration(contract: Path):
- """`PENETRATION_WARN_M` is the ceiling on a weld, and it is 2 mm, not 4."""
- for sentence in _weld_sentences(contract.read_text()):
- for mm in _mm_values(sentence):
- assert mm <= WARN_MM, (
- f"{contract.parent.name}/{contract.name} asks for {mm} mm here, and the "
- f"connectivity gate WARNs above {WARN_MM:.0f} mm:\n {sentence.strip()}")
-
-
[email protected](not SKILLS, reason=f"no bundles in {skills_dir()} yet")
[email protected]("s", SKILLS, ids=[s.name for s in SKILLS])
-def test_no_skill_asks_for_an_overlap_the_gate_calls_interpenetration(s):
- """The same rule on the other side, so neither document can drift alone."""
- text = "\n".join([s.body] + [p.read_text() for p in sorted(s.dir.rglob("references/*.md"))])
- for sentence in _weld_sentences(text):
- if _NOT_A_RECOMMENDATION.search(sentence):
- continue # teaching the LIMIT, quoting a gate message, or REPORTING what
- # the corpus measured — all of those may name a number past it
- for mm in _mm_values(sentence):
- assert mm <= WARN_MM, f"{s.name} recommends {mm} mm:\n {sentence.strip()}"
+def test_contract_tolerances_match_the_live_gates():
+ for contract in CONTRACTS:
+ text = contract.read_text()
+ label = f"{contract.parent.name}/{contract.name}"
+ for sentence in _weld_sentences(text):
+ for mm in _mm_values(sentence):
+ assert mm <= WARN_MM, (
+ f"{label} asks for {mm} mm; the gate warns above {WARN_MM:.0f} mm:\n"
+ f" {sentence.strip()}"
+ )
+ for sentence in (part for part in _SENTENCE_SPLIT.split(text)
+ if re.search(r"\bgap\b", part, re.I)):
+ if not re.search(r"[<≤]=?\s*\d|within|at most|no more than", sentence, re.I):
+ continue
+ for mm in _mm_values(sentence):
+ assert mm <= GAP_MM, (
+ f"{label} allows a {mm} mm gap; the gate joins only within "
+ f"{GAP_MM:.0f} mm:\n {sentence.strip()}"
+ )
def _forbidden_apis(contract: Path) -> set[str]:
@@ -124,40 +99,38 @@ def _languages_of(skill_name: str) -> set[str]:
@pytest.mark.skipif(not SKILLS, reason=f"no bundles in {skills_dir()} yet")
[email protected]("s", SKILLS, ids=[s.name for s in SKILLS])
-def test_no_skill_recommends_an_api_its_language_contract_forbids(s):
- """Naming a forbidden call to warn about it is fine; recommending it is not."""
- text = "\n".join([s.body] + [p.read_text() for p in sorted(s.dir.rglob("references/*.md"))])
- for lang in sorted(_languages_of(s.name)):
- contract = PROMPTS / _DIR_FOR_LANG.get(lang, lang) / "contract.md"
- if not contract.is_file():
- continue
- for api in sorted(_forbidden_apis(contract)):
- stem = api.rstrip("*").rstrip(".")
- if len(stem) < 5:
+def test_skill_advice_respects_gates_and_language_contracts():
+ for skill in SKILLS:
+ text = "\n".join(
+ [skill.body] + [p.read_text() for p in sorted(skill.dir.rglob("references/*.md"))]
+ )
+ for sentence in _weld_sentences(text):
+ if _NOT_A_RECOMMENDATION.search(sentence):
continue
- # a BACKTICKED, whole-word mention is a claim about the API; "renders straight
- # to the canvas" is English, and `ImageLoader` is not `Image`
- quoted = re.compile(rf"`[^`\n]*(?<![A-Za-z0-9_]){re.escape(stem)}(?![A-Za-z0-9_])[^`\n]*`")
- # per SENTENCE, not per line: markdown wraps, and the prohibition is often on
- # the next line from the name it prohibits
- for sentence in _PARAGRAPH_SPLIT.split(text):
- if not quoted.search(sentence):
+ for mm in _mm_values(sentence):
+ assert mm <= WARN_MM, f"{skill.name} recommends {mm} mm:\n {sentence.strip()}"
+
+ for language in sorted(_languages_of(skill.name)):
+ contract = PROMPTS / _DIR_FOR_LANG.get(language, language) / "contract.md"
+ if not contract.is_file():
+ continue
+ for api in sorted(_forbidden_apis(contract)):
+ stem = api.rstrip("*").rstrip(".")
+ if len(stem) < 5:
continue
- assert re.search(r"never|not\b|forbidden|do not|don't|avoid|refuse|reject|instead of"
- r"|banned|lint|fails|error|no DOM|headless", sentence, re.I), (
- f"{s.name} names {api!r}, which {lang}/contract.md forbids, without "
- f"saying so:\n {' '.join(sentence.split())[:160]}")
-
-
[email protected]("contract", CONTRACTS, ids=[f"{p.parent.name}/{p.name}" for p in CONTRACTS])
-def test_no_contract_states_a_contact_gap_looser_than_the_gate_measures(contract: Path):
- """"parts touch" means within CONTACT_GAP_M; a contract promising more is wrong."""
- for sentence in (s for s in _SENTENCE_SPLIT.split(contract.read_text())
- if re.search(r"\bgap\b", s, re.I)):
- if not re.search(r"[<≤]=?\s*\d|within|at most|no more than", sentence, re.I):
- continue
- for mm in _mm_values(sentence):
- assert mm <= GAP_MM, (
- f"{contract.parent.name}/{contract.name} allows a {mm} mm gap; the connectivity "
- f"gate joins parts only within {GAP_MM:.0f} mm:\n {sentence.strip()}")
+ quoted = re.compile(
+ rf"`[^`\n]*(?<![A-Za-z0-9_]){re.escape(stem)}(?![A-Za-z0-9_])[^`\n]*`"
+ )
+ for paragraph in _PARAGRAPH_SPLIT.split(text):
+ if not quoted.search(paragraph):
+ continue
+ refusal = re.search(
+ r"never|not\b|forbidden|do not|don't|avoid|refuse|reject|instead of"
+ r"|banned|lint|fails|error|no DOM|headless",
+ paragraph,
+ re.I,
+ )
+ assert refusal, (
+ f"{skill.name} recommends {api!r}, forbidden by {language}/contract.md:\n"
+ f" {' '.join(paragraph.split())[:160]}"
+ )
diff --git a/harness/tests/skills/test_hook.py b/harness/tests/skills/test_hook.py
index a53ecc90..5a268984 100644
--- a/harness/tests/skills/test_hook.py
+++ b/harness/tests/skills/test_hook.py
@@ -32,7 +32,7 @@ def ctx(tmp_path: Path, library_dir: Path, monkeypatch):
parts = [NS(name=f"P{i}", instances=1, symmetry="none", children=[]) for i in range(3)]
hashes: dict[str, str] = {}
return NS(ws=NS(root=root), spec=NS(track=NS(value="static_object")), language=NS(value="blender"),
- agent_id="unknown-backend:gemini-3.7-flash", plan=NS(parts=parts, summary="a chair"),
+ agent_id="unknown-backend:gemini-3.7-flash", agent_kind="unknown-backend", plan=NS(parts=parts, summary="a chair"),
single_shot=False, extra={}, events=Events(), prompt_hashes=hashes,
record_prompt=lambda name, text: hashes.__setitem__(name, str(len(text))))
@@ -140,14 +140,3 @@ def test_a_probe_failure_is_logged_not_raised(ctx, monkeypatch):
H.attach_for_round(ctx, index=0, kind="baseline")
monkeypatch.setattr("codeverse.skills.telemetry.probe_reads", lambda *a, **k: (_ for _ in ()).throw(OSError("boom")))
assert H.record_usage(ctx, index=0, kind="baseline") is None
-
-
-def test_the_round_and_the_repair_loop_really_call_the_hook():
- """Grep-level, on purpose: these two call sites are the whole integration, and a
- refactor that drops one leaves every unit test above green."""
- src = Path(__file__).resolve().parents[2] / "codeverse" / "tracks"
- steps = (src / "steps.py").read_text()
- assert "skills_hook.attach_for_round(" in steps
- assert "skills_hook.with_inlined_skill(" in steps
- assert "rec.skills = skills_hook.record_usage(" in steps
- assert "skills_hook.repair_pointers(" in (src / "repair.py").read_text()
diff --git a/harness/tests/skills/test_telemetry.py b/harness/tests/skills/test_telemetry.py
index b19793da..8017ed07 100644
--- a/harness/tests/skills/test_telemetry.py
+++ b/harness/tests/skills/test_telemetry.py
@@ -18,7 +18,6 @@ from codeverse.skills.telemetry import (
SKILLS_FILE,
TELEMETRY_DIR,
append_usage,
- deep_read_rate,
probe_reads,
)
from tests.skills.conftest import write_bundle
@@ -103,16 +102,6 @@ def test_usage_is_appended_as_one_json_line_per_session(ws, library):
assert rows[0]["listed"] == usage.listed and "index_tokens" in rows[0]
-def test_deep_read_rate_aggregates_across_sessions(ws, library):
- got = _attach(ws, library)
- a = probe_reads(ws, got)
- _touch_read(ws / ".agents" / "skills" / got.listed[0] / "references" / "worked_example.md")
- b = probe_reads(ws, got)
- rates = deep_read_rate([a, b])
- assert rates[got.listed[0]] == (1, 2)
- assert rates[got.listed[1]] == (0, 2)
-
-
def test_the_control_bundle_is_materialised_and_starts_unread(ws, library):
from codeverse.skills.materialize import CONTROL_NAME, materialize_skills