Official Codebase of 3DCodeVerse
Python
flywheel/ is gone: what a run writes is codeverse/record, what reads runs is codeverse/addons
gaoypeng03a90fe56a6d
diff --git a/harness/CLAUDE.md b/harness/CLAUDE.mdindex 050526a2..d4f4c57c 100644--- a/harness/CLAUDE.md+++ b/harness/CLAUDE.md@@ -95,10 +95,10 @@ cd /home/yipeng/3dcodeverse/harness3dcode cost <slug> · 3dcode cost --runs-dir bench/out/<battery> · 3dcode cost cache <slug>3dcode cost prices [--stale] · 3dcode cost profiles · 3dcode cost estimate gemini:gemini-3.1-pro-preview --in 120003dcode flywheel export runs/ dataset/ [--pack --drop-duplicates --captions-dir d/] · 3dcode flywheel pairs runs/ pairs.jsonl-3dcode flywheel caption <slug> [--out dir] · 3dcode flywheel gallery runs/ gallery.html+3dcode flywheel caption <slug> [--out dir] # the gallery is `3dcode gallery build --embed`3dcode gallery serve [ROOTS...] [--port 8765] [--reload] · 3dcode gallery build --out gallery.html [--embed]3dcode bench run bench/prompts/static_objects_v1.yaml --generator ... --judge gemini:gemini-3.1-pro-preview-python -m codeverse.judges.calibration runs/<slug>... --model gemini:gemini-3.1-pro-preview --n 3 --out out/+python -m codeverse.addons.calibration runs/<slug>... --model gemini:gemini-3.1-pro-preview --n 3 --out out/python bench/complexity_report.py bench/out --recursive # score-vs-complexity + $/complexity point (docs/COMPLEXITY.md)python bench/compare_backends.py --prompts bench/prompts/compare_v1.yaml --arms harness:gemini-cli:gemini-3.6-flash,oneshot:claude-code --judge gemini:gemini-3.1-pro-preview --out bench/out/compare_v1python -m pytest tests -q -m "not live" # 3 060 tests, ~65 s (real Blender + headless Chrome + CadQuery)diff --git a/harness/README.md b/harness/README.mdindex 460efac0..789e4b78 100644--- a/harness/README.md+++ b/harness/README.md@@ -53,13 +53,15 @@ codeverse/models/ ChatModel + gemini/anthropic/openai adapters; key-pool retry machine,streaming with stall detection, IPv4-pinned transport, pricing, healthspatial/ the measurement/render toolbox behind every gate and MCP tool- judges/ rubric VLM judge on labelled montages, pairwise/ranking/reference, calibration+ judges/ rubric VLM judge on labelled montages, pairwise, reference/likenessreference.py reference grounding: synthesis, plausibility gate, proportions, difftexturing/ material plan → seamless tiles → world-metre UVs → object_textured.glbcost/ append-only ledger, metering, budget guard, profiles, billingskills/ typed skill routes + materialisation + read telemetry- flywheel/ record, export (tiers/dedupe/parquet), preference/repair pairs, sqlite index- gallery/ the runs browser (`3dcode gallery serve`) + one-file embed+ record/ what every run writes: record.json, deliverable/, telemetry+ addons/ optional tools that READ finished runs — nothing a run needs:+ gallery (the runs browser), dataset (export, tiers, preference/repair pairs,+ captions, sqlite index), costreport (`3dcode cost`), calibration, skill_targetscli/ the typer CLI · doctor.py the environment checks behind `3dcode doctor`bench/ the evaluation harness around the harness: run_bench, compare_backends(A/B matrix), ab_plan, infra-failure classificationdiff --git a/harness/bench/complexity_report.py b/harness/bench/complexity_report.pyindex 178cc528..f1c4ba6d 100644--- a/harness/bench/complexity_report.py+++ b/harness/bench/complexity_report.py@@ -30,10 +30,10 @@ from typing import Anysys.path.insert(0, str(Path(__file__).resolve().parents[0].parent))+from codeverse.addons.calibration import _ranks # noqa: E402 — tie-averaged ranks, one copyfrom codeverse.contracts.run import RunId # noqa: E402-from codeverse.flywheel.record import find_run_dirs # noqa: E402-from codeverse.judges.calibration import _ranks # noqa: E402 — tie-averaged ranks, one copyfrom codeverse.proc import read_json_or_none # noqa: E402+from codeverse.record.record import find_run_dirs # noqa: E402from codeverse.spatial.complexity import COMPLEXITY_WEIGHTS, ComplexityVector, band_of # noqa: E402CRITERIA = (diff --git a/harness/bench/coupling_stats.py b/harness/bench/coupling_stats.pyindex 2f8dba78..e8450c61 100644--- a/harness/bench/coupling_stats.py+++ b/harness/bench/coupling_stats.py@@ -23,7 +23,7 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # `python bench/coupling_stats.py` from the repo root-from codeverse.flywheel.record import unique_files # noqa: E402+from codeverse.record.record import unique_files # noqa: E402from codeverse.spatial.joints_model import UrdfError, load_urdf # noqa: E402diff --git a/harness/bench/judge_calib_graphics.py b/harness/bench/judge_calib_graphics.pyindex ef348b5b..aff58c86 100644--- a/harness/bench/judge_calib_graphics.py+++ b/harness/bench/judge_calib_graphics.py@@ -29,10 +29,10 @@ from concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom typing import Any+from codeverse.addons.calibration import spearmanfrom codeverse.contracts.artifacts import GateReport, RenderSetfrom codeverse.contracts.spec import Specfrom codeverse.judges.base import JudgeInput, plan_digest-from codeverse.judges.calibration import spearmanfrom codeverse.judges.vlm_judge import VlmJudgefrom codeverse.tracks.graphics import frame_stats_textfrom codeverse.workspace import Workspacediff --git a/harness/bench/penetration_thresholds.py b/harness/bench/penetration_thresholds.pyindex 62d6eb37..be845c61 100644--- a/harness/bench/penetration_thresholds.py+++ b/harness/bench/penetration_thresholds.py@@ -26,8 +26,8 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent.parent))-from codeverse.flywheel.record import unique_files # noqa: E402from codeverse.languages.urdf import REST_PENETRATION_MAX_M # noqa: E402+from codeverse.record.record import unique_files # noqa: E402from codeverse.spatial.connectivity import ( # noqa: E402PENETRATION_ERROR_M,PENETRATION_WARN_M,diff --git a/harness/bench/rejudge_offline.py b/harness/bench/rejudge_offline.pyindex 7cb88eb4..2523206a 100644--- a/harness/bench/rejudge_offline.py+++ b/harness/bench/rejudge_offline.py@@ -43,10 +43,10 @@ from pathlib import Pathfrom pydantic import BaseModel, Field+from codeverse.addons.calibration import _run_labelfrom codeverse.contracts.artifacts import GateReport, Severityfrom codeverse.contracts.plan import AcceptanceItemfrom codeverse.contracts.run import RoundRecord-from codeverse.judges.calibration import _run_labelfrom codeverse.judges.rubrics import (SCORING_VERSION,JudgeOutput,diff --git a/harness/bench/report.py b/harness/bench/report.pyindex 247a0409..d7f145eb 100644--- a/harness/bench/report.py+++ b/harness/bench/report.py@@ -22,7 +22,7 @@ from bench._jsonl import read_jsonlfrom bench.run_bench import BenchItemResultfrom codeverse.addons.gallery import GalleryIndex, RootSection, RunEntry, render_staticfrom codeverse.addons.gallery.index import entry_from_record-from codeverse.flywheel.record import RecordError, load_record+from codeverse.record.record import RecordError, load_recordfrom codeverse.workspace import WorkspaceTIER_ORDER = {"easy": 0, "medium": 1, "hard": 2}diff --git a/harness/bench/scene_stats.py b/harness/bench/scene_stats.pyindex 4cbe67b3..9203d26c 100644--- a/harness/bench/scene_stats.py+++ b/harness/bench/scene_stats.py@@ -26,8 +26,8 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # this tree's codeverse, not the editable install-from codeverse.flywheel.record import unique_files # noqa: E402from codeverse.proc import read_jsonl_lenient # noqa: E402+from codeverse.record.record import unique_files # noqa: E402from codeverse.spatial.node import browser_was_lost # noqa: E402#: pipeline stages in the order the scene track runs themdiff --git a/harness/bench/session_stats.py b/harness/bench/session_stats.pyindex 708fd2b3..354af8fa 100644--- a/harness/bench/session_stats.py+++ b/harness/bench/session_stats.py@@ -24,7 +24,7 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # `python bench/session_stats.py` from the repo root-from codeverse.flywheel.record import unique_files # noqa: E402+from codeverse.record.record import unique_files # noqa: E402#: gemini-cli names an MCP tool ``mcp_<server>_<tool>``; ours is the ``3dcode`` server#: (``3dcv`` in every session recorded before the 2026-09-21 rename).diff --git a/harness/bench/skill_targets.py b/harness/bench/skill_targets.pyindex d4d7e987..3ec685d1 100644--- a/harness/bench/skill_targets.py+++ b/harness/bench/skill_targets.py@@ -1,7 +1,7 @@"""Per-skill deterministic readout: what each bundle claims to move, measured.``bench/ab_gate_rates.py`` prints the gate numbers of an A/B run; it does not know which-*skill* owns which number. This does. ``codeverse/skills/targets.py`` holds one+*skill* owns which number. This does. ``codeverse/addons/skill_targets.py`` holds onefalsifiable claim per bundle; this file computes it over a recorded battery or an A/Bdirectory, so the same command answers both "what is the baseline" and "did the variantmove it".@@ -32,8 +32,7 @@ from typing import Anysys.path.insert(0, str(Path(__file__).resolve().parents[1]))-from codeverse.skills.registry import finding_kind # noqa: E402-from codeverse.skills.targets import ( # noqa: E402+from codeverse.addons.skill_targets import ( # noqa: E402SRC_ARTIFACT,SRC_BUILD,SRC_FRAMES,@@ -42,6 +41,7 @@ from codeverse.skills.targets import ( # noqa: E402TARGETS,Target,)+from codeverse.skills.registry import finding_kind # noqa: E402CACHE_NAME = ".skill_targets_cache.json"_FRAME_T = re.compile(r"_t(\d+(?:\.\d+)?)\.png$")diff --git a/harness/codeverse/addons/__init__.py b/harness/codeverse/addons/__init__.pyindex 8ab3d71f..c1e05493 100644--- a/harness/codeverse/addons/__init__.py+++ b/harness/codeverse/addons/__init__.py@@ -1,11 +1,16 @@"""Optional tools that READ finished runs — nothing a run needs in order to happen.-* ``gallery`` the run browser (``3dcode gallery serve|build``)-* ``dataset`` run records → samples, packs, preference pairs, captions, an index- (``3dcode flywheel export|pairs|caption|index``)+* ``gallery`` the run browser (``3dcode gallery serve|build``)+* ``dataset`` run records → samples, packs, preference pairs, captions, an index+ (``3dcode flywheel export|pairs|caption|index``)+* ``costreport`` the cost audit of finished runs (``3dcode cost``)+* ``calibration`` judge repeatability / calibration over recorded runs+ (``python -m codeverse.addons.calibration``)+* ``skill_targets`` each skill bundle's falsifiable claim, measured (``3dcode skills …``,+ ``bench/skill_targets.py``)The boundary is one-way and pinned by ``tests/core/test_addons_boundary.py``: an addon mayimport anything in ``codeverse``; outside ``codeverse.cli`` nothing in ``codeverse`` imports anaddon. What a run itself writes (``record.json``, ``deliverable/``, telemetry) is NOT an-addon — that is ``codeverse.flywheel``.+addon — that is ``codeverse.record``; booking its cost while it runs is ``codeverse.cost``."""diff --git a/harness/codeverse/judges/calibration.py b/harness/codeverse/addons/calibration.pysimilarity index 99%rename from harness/codeverse/judges/calibration.pyrename to harness/codeverse/addons/calibration.pyindex 20a281aa..ea6bee47 100644--- a/harness/codeverse/judges/calibration.py+++ b/harness/codeverse/addons/calibration.py@@ -10,7 +10,7 @@ negative), and between stored and new overalls. Optionally renders a clay /normals geometry set for the run's best round (``artifacts/object.glb``) so thegeometry montage is exercised. Output goes to ``out_dir`` (never into the run).-CLI: ``python -m codeverse.judges.calibration runs/a runs/b --model gemini:gemini-3.7-flash --n 3 --out scratch/``+CLI: ``python -m codeverse.addons.calibration runs/a runs/b --model gemini:gemini-3.7-flash --n 3 --out scratch/``"""from __future__ import annotationsdiff --git a/harness/codeverse/addons/costreport/__init__.py b/harness/codeverse/addons/costreport/__init__.pynew file mode 100644index 00000000..3203989c--- /dev/null+++ b/harness/codeverse/addons/costreport/__init__.py@@ -0,0 +1,8 @@+"""The cost of finished runs, read back: ``3dcode cost`` and its markdown report.++* ``audit`` ``audit_runs(paths)`` → ``Audit`` (reconstruct + aggregate every run under the paths, waste)+* ``report`` ``console(audit)`` · ``markdown(audit)``+* ``caching`` what prompt caching saved, per session++Booking the money WHILE a run happens (ledger, guard, billing, instrument) is ``codeverse.cost``.+"""diff --git a/harness/codeverse/cost/audit.py b/harness/codeverse/addons/costreport/audit.pysimilarity index 100%rename from harness/codeverse/cost/audit.pyrename to harness/codeverse/addons/costreport/audit.pydiff --git a/harness/codeverse/cost/caching.py b/harness/codeverse/addons/costreport/caching.pysimilarity index 100%rename from harness/codeverse/cost/caching.pyrename to harness/codeverse/addons/costreport/caching.pydiff --git a/harness/codeverse/cost/report.py b/harness/codeverse/addons/costreport/report.pysimilarity index 98%rename from harness/codeverse/cost/report.pyrename to harness/codeverse/addons/costreport/report.pyindex 51d24eb8..807d3cb3 100644--- a/harness/codeverse/cost/report.py+++ b/harness/codeverse/addons/costreport/report.py@@ -1,4 +1,4 @@-"""Render an :class:`~codeverse.cost.audit.Audit` as markdown or a console table.+"""Render an :class:`~codeverse.addons.costreport.audit.Audit` as markdown or a console table.Pure formatting: every number comes from the audit, nothing is recomputed here."""@@ -7,7 +7,7 @@ from __future__ import annotationsfrom collections.abc import Sequence-from codeverse.cost.audit import (+from codeverse.addons.costreport.audit import (Audit,cached_input_share,price_confidence,diff --git a/harness/codeverse/addons/dataset/__init__.py b/harness/codeverse/addons/dataset/__init__.pyindex 48ae7959..7fb9ef86 100644--- a/harness/codeverse/addons/dataset/__init__.py+++ b/harness/codeverse/addons/dataset/__init__.py@@ -6,4 +6,6 @@* ``refine`` the refine-transition rows (``RefineTransition``)* ``captions`` ``caption_sample(ws, record, model_id)`` → ``Captions``* ``index`` ``build_index(runs_dir, out_sqlite)`` + query helpers+* ``sample`` one run → one dataset sample (the code files of its best round)+* ``quality`` ``quality_tier`` (A/B/C/D) · ``prompt_hash`` · code fingerprints, duplicate groups"""diff --git a/harness/codeverse/addons/dataset/captions.py b/harness/codeverse/addons/dataset/captions.pyindex b652a846..3286492e 100644--- a/harness/codeverse/addons/dataset/captions.py+++ b/harness/codeverse/addons/dataset/captions.py@@ -24,13 +24,13 @@ from pathlib import Pathfrom pydantic import BaseModel, Field+from codeverse.addons.dataset.sample import code_files_for_roundfrom codeverse.contracts.chat import ChatMessage, ChatRequest, ImagePartfrom codeverse.contracts.common import ENTRY_FILE, Language, Trackfrom codeverse.contracts.run import RunRecord-from codeverse.flywheel import _git-from codeverse.flywheel.record import best_round_record-from codeverse.flywheel.sample import code_files_for_roundfrom codeverse.prompts import prompt_hash+from codeverse.record import _git+from codeverse.record.record import best_round_recordfrom codeverse.workspace import WorkspaceMAX_CODE_CHARS = 12_000@@ -210,7 +210,7 @@ def caption_sample(out.mkdir(parents=True, exist_ok=True)(out / f"{slug or ws.root.name}.json").write_text(json.dumps(payload, indent=2, ensure_ascii=False))return caps- from codeverse.flywheel.record import package_run+ from codeverse.record.record import package_runws.write_json(ws.root / "captions.json", payload)package_run(ws, record) # captions.json + cost.json + the manifest all go stale otherwisediff --git a/harness/codeverse/addons/dataset/export.py b/harness/codeverse/addons/dataset/export.pyindex 2c8e427e..b3bab3f1 100644--- a/harness/codeverse/addons/dataset/export.py+++ b/harness/codeverse/addons/dataset/export.py@@ -35,13 +35,13 @@ from typing import Any, NamedTuplefrom pydantic import BaseModel, Field+from codeverse.addons.dataset import sample as S+from codeverse.addons.dataset.quality import DuplicateGroup, code_sha256, mark_duplicatesfrom codeverse.contracts.common import ENTRY_FILE, Languagefrom 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, best_round_record, iter_runsfrom codeverse.proc import sha256_file+from codeverse.record._git import CODE_ROOTS+from codeverse.record.record import FoundRun, best_round_record, iter_runsfrom codeverse.workspace import Workspacelog = logging.getLogger(__name__)diff --git a/harness/codeverse/addons/dataset/index.py b/harness/codeverse/addons/dataset/index.pyindex 97e943ad..f8686476 100644--- a/harness/codeverse/addons/dataset/index.py+++ b/harness/codeverse/addons/dataset/index.py@@ -10,15 +10,15 @@ import sqlite3from pathlib import Pathfrom typing import Any+from codeverse.addons.dataset.quality import prompt_hash, quality_tier+from codeverse.addons.dataset.sample import gate_error_summaryfrom codeverse.contracts.run import RoundRecord, RunId, RunRecord-from codeverse.flywheel.quality import prompt_hash, quality_tier-from codeverse.flywheel.record import (+from codeverse.record.record import (best_round_index,best_round_record,effective_judgment,iter_runs,)-from codeverse.flywheel.sample import gate_error_summaryfrom codeverse.workspace import Workspace_SCHEMA = """diff --git a/harness/codeverse/addons/dataset/pack.py b/harness/codeverse/addons/dataset/pack.pyindex faa4a728..1a30f351 100644--- a/harness/codeverse/addons/dataset/pack.py+++ b/harness/codeverse/addons/dataset/pack.py@@ -35,7 +35,7 @@ from codeverse.addons.dataset.export import (write_jsonl,write_parquet,)-from codeverse.flywheel.quality import mark_duplicates+from codeverse.addons.dataset.quality import mark_duplicatesMAX_TAR_BYTES = int(2.5 * 1024**3)#: per-member allowance for tar headers/padding in the rollover size estimatediff --git a/harness/codeverse/addons/dataset/pairs.py b/harness/codeverse/addons/dataset/pairs.pyindex ec7f2e0c..449ea9e1 100644--- a/harness/codeverse/addons/dataset/pairs.py+++ b/harness/codeverse/addons/dataset/pairs.py@@ -29,11 +29,11 @@ from collections import defaultdictfrom pathlib import Pathfrom typing import Any+from codeverse.addons.dataset.quality import prompt_hashfrom codeverse.contracts.run import RoundRecord, RunRecord-from codeverse.flywheel import _git-from codeverse.flywheel.quality import prompt_hash-from codeverse.flywheel.record import best_round_record, effective_judgment, iter_runsfrom codeverse.proc import read_jsonl_lenient+from codeverse.record import _git+from codeverse.record.record import best_round_record, effective_judgment, iter_runsfrom codeverse.workspace import Workspace__all__ = ["build_pairs", "preference_pairs", "repair_pairs", "in_round_repair_pairs",diff --git a/harness/codeverse/flywheel/quality.py b/harness/codeverse/addons/dataset/quality.pysimilarity index 57%rename from harness/codeverse/flywheel/quality.pyrename to harness/codeverse/addons/dataset/quality.pyindex 88f565ea..4a2f3482 100644--- a/harness/codeverse/flywheel/quality.py+++ b/harness/codeverse/addons/dataset/quality.py@@ -1,24 +1,17 @@-"""Near-duplicate detection: code fingerprints + coarse mesh fingerprints.+"""Code fingerprints, quality tiers and duplicate groups.* ``code_fingerprint(files)`` sha256 of whitespace/comment-normalised code.* ``code_sha256(files)`` sha256 of the raw bytes (the exact-content hash).-* ``mesh_fingerprint(glb)`` bbox extents (cm), triangle bucket and a 16³ voxel- occupancy set computed with trimesh — compare with Jaccard.-* ``near_duplicates(items)`` union-find groups: identical code fingerprint OR- mesh Jaccard ≥ threshold with compatible extents."""from __future__ import annotationsimport hashlib-import mathimport refrom collections import defaultdictfrom collections.abc import Iterable, Mapping-from pathlib import Pathfrom typing import Any, Literal-import numpy as npfrom pydantic import BaseModel, Field_COMMENT = re.compile(r"^\s*(#|//|\*|/\*).*$")@@ -67,99 +60,6 @@ def code_sha256(files: Mapping[str, str | bytes]) -> str:return h.hexdigest()-class MeshFingerprint(BaseModel):- extents_cm: tuple[int, int, int]- tri_count: int- tri_bucket: int = Field(description="log2 bucket of the triangle count")- voxels: list[int] = Field(description="occupied cell indices in a VOXEL_RES³ grid over the bbox")- digest: str-- def jaccard(self, other: MeshFingerprint) -> float:- a, b = set(self.voxels), set(other.voxels)- if not a and not b:- return 1.0- return len(a & b) / len(a | b)-- def extents_compatible(self, other: MeshFingerprint, tol: float = 0.1) -> bool:- for x, y in zip(self.extents_cm, other.extents_cm, strict=True):- if max(x, y) == 0:- continue- if abs(x - y) / max(x, y) > tol:- return False- return True---def mesh_fingerprint(glb: Path | str, *, res: int = VOXEL_RES, samples: int = 50_000, seed: int = 0) -> MeshFingerprint:- """Coarse, pose-sensitive shape fingerprint of a GLB (seeded surface samples → voxel grid).-- Deterministic for identical geometry; near-identical meshes give Jaccard ≈ 1."""- import trimesh-- loaded = trimesh.load(str(glb), force="scene")- mesh = loaded.to_mesh() if isinstance(loaded, trimesh.Scene) else loaded- if mesh is None or mesh.is_empty or len(mesh.faces) == 0:- raise ValueError(f"mesh_fingerprint: no triangles in {glb}")- ext = mesh.bounding_box.extents- pts, _ = trimesh.sample.sample_surface(mesh, samples, seed=seed)- lo = mesh.bounds[0]- span = np.where(ext > 1e-9, ext, 1.0)- idx = np.clip(((pts - lo) / span * res).astype(int), 0, res - 1)- cells = sorted(set((idx[:, 0] * res * res + idx[:, 1] * res + idx[:, 2]).tolist()))- tri = int(len(mesh.faces))- digest = hashlib.sha1(- (",".join(map(str, cells)) + f"|{[int(round(e * 100)) for e in ext]}").encode()- ).hexdigest()[:16]- return MeshFingerprint(- extents_cm=tuple(int(round(e * 100)) for e in ext), # type: ignore[arg-type]- tri_count=tri,- tri_bucket=int(math.log2(max(tri, 1))),- voxels=cells,- digest=digest,- )---class DedupeItem(BaseModel):- id: str- code_fp: str = ""- mesh_fp: MeshFingerprint | None = None---def near_duplicates(items: Iterable[DedupeItem], *, mesh_threshold: float = 0.9) -> list[list[str]]:- """Groups (size ≥ 2) of ids that are normalised-code duplicates or near-identical meshes."""- items = list(items)- parent = {it.id: it.id for it in items}-- def find(x: str) -> str:- while parent[x] != x:- parent[x] = parent[parent[x]]- x = parent[x]- return x-- def union(a: str, b: str) -> None:- ra, rb = find(a), find(b)- if ra != rb:- parent[rb] = ra-- by_code: dict[str, str] = {}- for it in items:- if it.code_fp:- if it.code_fp in by_code:- union(by_code[it.code_fp], it.id)- else:- by_code[it.code_fp] = it.id- meshed = [it for it in items if it.mesh_fp is not None]- for i, a in enumerate(meshed):- for b in meshed[i + 1 :]:- fa, fb = a.mesh_fp, b.mesh_fp- assert fa is not None and fb is not None- if fa.extents_compatible(fb) and fa.jaccard(fb) >= mesh_threshold:- union(a.id, b.id)- groups: dict[str, list[str]] = {}- for it in items:- groups.setdefault(find(it.id), []).append(it.id)- return sorted((sorted(g) for g in groups.values() if len(g) > 1), key=lambda g: g[0])--# ===================================================================== qualityQualityTier = Literal["A", "B", "C", "D"]TIER_ORDER: dict[str, int] = {"A": 0, "B": 1, "C": 2, "D": 3}diff --git a/harness/codeverse/addons/dataset/refine.py b/harness/codeverse/addons/dataset/refine.pyindex 8feea538..4dfdb239 100644--- a/harness/codeverse/addons/dataset/refine.py+++ b/harness/codeverse/addons/dataset/refine.py@@ -30,8 +30,8 @@ from pydantic import BaseModel, Fieldfrom codeverse.addons.dataset.pairs import MIN_PREFERENCE_DELTAfrom codeverse.contracts.artifacts import Severityfrom codeverse.contracts.run import RoundRecord, RunRecord-from codeverse.flywheel._git import GitReadError, changed_files_between, diff_between, read_tree_at-from codeverse.flywheel.record import (+from codeverse.record._git import GitReadError, changed_files_between, diff_between, read_tree_at+from codeverse.record.record import (BATTERY_MARKERS,effective_judgment,effective_score,diff --git a/harness/codeverse/flywheel/sample.py b/harness/codeverse/addons/dataset/sample.pysimilarity index 98%rename from harness/codeverse/flywheel/sample.pyrename to harness/codeverse/addons/dataset/sample.pyindex 30b51b8c..b0db345d 100644--- a/harness/codeverse/flywheel/sample.py+++ b/harness/codeverse/addons/dataset/sample.py@@ -22,6 +22,12 @@ from typing import Anyfrom pydantic import BaseModel, Fieldfrom codeverse import __version__+from codeverse.addons.dataset.quality import (+ QualityTier,+ code_fingerprint,+ prompt_hash,+ quality_tier,+)from codeverse.contracts.common import (ENTRY_FILE,LANGUAGE_LABEL,@@ -30,10 +36,9 @@ from codeverse.contracts.common import (code_file,)from codeverse.contracts.run import RoundRecord, RunRecord-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 (+from codeverse.record import _git+from codeverse.record.deliverable import deliverable_path+from codeverse.record.record import (effective_judgment,round_complexity,round_summary,@@ -347,7 +352,7 @@ def telemetry_digest(ws: Workspace, record: RunRecord) -> dict[str, Any]:"""The few accounting numbers a dataset consumer wants inline: total, per stage,model + thinking level per role, rubric/price hashes. ``{}`` when a run has notelemetry (old layout and nothing computable)."""- from codeverse.flywheel.telemetry import load_telemetry+ from codeverse.record.telemetry import load_telemetrytele = load_telemetry(ws, record)if tele is None:diff --git a/harness/codeverse/addons/gallery/detail.py b/harness/codeverse/addons/gallery/detail.pyindex b0b6e050..522a03ff 100644--- a/harness/codeverse/addons/gallery/detail.py+++ b/harness/codeverse/addons/gallery/detail.py@@ -20,7 +20,7 @@ from codeverse.addons.gallery.theme import esc, footer, page_shell, top_barfrom codeverse.addons.gallery.urls import UrlMakerfrom codeverse.contracts.common import ENTRY_FILEfrom codeverse.contracts.run import RunRecord-from codeverse.flywheel.record import best_round_record, effective_judgment+from codeverse.record.record import best_round_record, effective_judgmentfrom codeverse.workspace import WorkspaceDETAIL_CSS = CODE_CSS + """@@ -252,7 +252,7 @@ def _renders_panel(entry: RunEntry, urls: UrlMaker, rec: RunRecord) -> str:def _cost_panel(entry: RunEntry, ws: Workspace, rec: RunRecord) -> str:- from codeverse.flywheel.telemetry import load_telemetry+ from codeverse.record.telemetry import load_telemetrytele = load_telemetry(ws, rec)cost = tele.cost if tele is not None else Nonediff --git a/harness/codeverse/addons/gallery/index.py b/harness/codeverse/addons/gallery/index.pyindex a1d17729..fb3c4edb 100644--- a/harness/codeverse/addons/gallery/index.py+++ b/harness/codeverse/addons/gallery/index.py@@ -15,6 +15,8 @@ from __future__ import annotationsimport timefrom pathlib import Path+from codeverse.addons.dataset.quality import quality_tier+from codeverse.addons.dataset.sample import gate_error_summary, telemetry_digestfrom codeverse.addons.gallery.model import (GalleryIndex,RootSection,@@ -24,8 +26,8 @@ from codeverse.addons.gallery.model import (humanize_view,)from codeverse.contracts.run import RunId, RunRecord-from codeverse.flywheel.quality import quality_tier-from codeverse.flywheel.record import (+from codeverse.proc import read_json_or_none+from codeverse.record.record import (RecordError,battery_label,best_round_index,@@ -35,8 +37,6 @@ from codeverse.flywheel.record import (is_run_dir,load_record,)-from codeverse.flywheel.sample import gate_error_summary, telemetry_digest-from codeverse.proc import read_json_or_nonefrom codeverse.workspace import Workspace#: run roots the CLI defaults to when the user names none@@ -212,7 +212,7 @@ def _complexity(ws: Workspace, rec: RunRecord) -> tuple[float | None, str, dict[complexity block, else the best round's measurement, else the measurementfile on disk. A run built before the complexity vector existed has none(``bench/complexity_report.py`` recomputes those from the GLB)."""- from codeverse.flywheel.record import complexity_block+ from codeverse.record.record import complexity_blocktry:block = rec.extra.get("complexity") or complexity_block(rec) or _measurement_complexity(ws)diff --git a/harness/codeverse/addons/gallery/server.py b/harness/codeverse/addons/gallery/server.pyindex bf3558f7..d9742468 100644--- a/harness/codeverse/addons/gallery/server.py+++ b/harness/codeverse/addons/gallery/server.py@@ -232,7 +232,7 @@ class GalleryApp:return Response(content_type=ctype, path=target, headers=headers)def _detail(self, entry: RunEntry) -> Response:- from codeverse.flywheel.record import RecordError, load_record+ from codeverse.record.record import RecordError, load_recordfrom codeverse.workspace import Workspacews = Workspace(entry.path)diff --git a/harness/codeverse/skills/targets.py b/harness/codeverse/addons/skill_targets.pysimilarity index 100%rename from harness/codeverse/skills/targets.pyrename to harness/codeverse/addons/skill_targets.pydiff --git a/harness/codeverse/cli/_common.py b/harness/codeverse/cli/_common.pyindex 6f3348ec..c3082772 100644--- a/harness/codeverse/cli/_common.py+++ b/harness/codeverse/cli/_common.py@@ -79,7 +79,7 @@ def print_record_summary(record: RunRecord, ws_root: Path | None = None) -> Nonelines.append(f"[red]error: {record.error}[/red]")if ws_root is not None:lines.append(f"workspace: {ws_root}")- from codeverse.flywheel.record import best_round_record+ from codeverse.record.record import best_round_recordbest = best_round_record(record)if best is not None and best.renders is not None and best.renders.contact_sheet:diff --git a/harness/codeverse/cli/_judge.py b/harness/codeverse/cli/_judge.pyindex 1ca536b4..f5a1adbd 100644--- a/harness/codeverse/cli/_judge.py+++ b/harness/codeverse/cli/_judge.py@@ -54,7 +54,7 @@ def plan_summary_for(ws: Workspace) -> str:def previous_judgment(ws: Workspace, rec: RunRecord, index: int) -> Any:"""The preceding round's verdict (skipping degraded ones), like the round loop."""- from codeverse.flywheel.record import effective_judgment+ from codeverse.record.record import effective_judgmentfor i in range(index - 1, -1, -1):rnd = load_round(ws, rec, i)diff --git a/harness/codeverse/cli/cost_cmd.py b/harness/codeverse/cli/cost_cmd.pyindex a7be0b9a..e685f288 100644--- a/harness/codeverse/cli/cost_cmd.py+++ b/harness/codeverse/cli/cost_cmd.py@@ -88,9 +88,9 @@ def _resolve(arg: str, runs_dir: Path | None) -> Path:def _report(paths: list[Path], *, md: Path | None, recheck: bool, limit: int, per_run: bool) -> None:- from codeverse.cost import audit_runs- from codeverse.cost.report import console as text_report- from codeverse.cost.report import markdown, runs_table+ from codeverse.addons.costreport.audit import audit_runs+ from codeverse.addons.costreport.report import console as text_report+ from codeverse.addons.costreport.report import markdown, runs_tableaudit = audit_runs(paths, recheck=recheck)if not audit.runs:@@ -212,7 +212,7 @@ def cache(Only a live ledger has per-call ``cached_tokens``; reconstructed runs showwhat their transcripts recorded."""- from codeverse.cost.caching import session_cache+ from codeverse.addons.costreport.caching import session_cachefrom codeverse.cost.ledger import load_ledgerfrom codeverse.cost.reconstruct import reconstruct_rundiff --git a/harness/codeverse/cli/flywheel_cmd.py b/harness/codeverse/cli/flywheel_cmd.pyindex d3875ad6..26f92648 100644--- a/harness/codeverse/cli/flywheel_cmd.py+++ b/harness/codeverse/cli/flywheel_cmd.py@@ -1,4 +1,4 @@-"""``3dcode flywheel export | pairs | caption | index | dedupe | gallery``."""+"""``3dcode flywheel export | pairs | caption | index``."""from __future__ import annotations@@ -105,8 +105,8 @@ def caption_cmd(from codeverse.addons.dataset.captions import CaptionError, caption_samplefrom codeverse.addons.dataset.export import load_captionsfrom codeverse.cost.instrument import run_ledger- from codeverse.flywheel.record import iter_runs, load_recordfrom codeverse.proc import RunLocked, exclusive+ from codeverse.record.record import iter_runs, load_recordif all_runs:targets = [(fr.ws, fr.record, fr.run_id.slug)@@ -160,56 +160,3 @@ def index_cmd(f"{(r['pass_rate'] or 0):.2f}", f"{(r['baseline_mean'] or 0):.3f}", f"{(r['final_mean'] or 0):.3f}",f"{(r['delta_mean'] or 0):+.3f}", f"${(r['cost_usd'] or 0):.2f}")console.print(t)---@flywheel_app.command("dedupe")-def dedupe_cmd(- dataset_dir: Annotated[Path, typer.Argument(help="exported dataset folder")],- mesh: Annotated[bool, typer.Option("--mesh/--no-mesh", help="also fingerprint renders/object.glb")] = True,- threshold: Annotated[float, typer.Option("--threshold")] = 0.9,-) -> None:- """Report near-duplicate sample groups (code fingerprint + mesh voxel Jaccard)."""- import json-- from codeverse.flywheel.quality import (- DedupeItem,- code_fingerprint,- mesh_fingerprint,- near_duplicates,- )-- items = []- # exactly track/language/key deep — a src/meta.json in a sample's LLM-written- # code tree must not become a phantom sample- for meta_path in sorted(dataset_dir.glob("*/*/*/meta.json")):- sdir = meta_path.parent- meta = json.loads(meta_path.read_text())- files = {p.relative_to(sdir).as_posix(): p.read_bytes() for p in (sdir / "src").rglob("*") if p.is_file()}- fp = None- glb = sdir / "renders" / "object.glb"- if mesh and glb.is_file():- try:- fp = mesh_fingerprint(glb)- except Exception as e: # unreadable glb → code-only- warn(f"{meta['key']}: mesh fingerprint failed: {e}")- items.append(DedupeItem(id=meta["id"], code_fp=code_fingerprint(files), mesh_fp=fp))- groups = near_duplicates(items, mesh_threshold=threshold)- console.print(f"{len(items)} samples, {len(groups)} duplicate groups")- for g in groups:- console.print(" " + " == ".join(g))---@flywheel_app.command("gallery")-def gallery_cmd(- runs_dir: Annotated[Path, typer.Argument(help="runs root")],- out_html: Annotated[Path, typer.Argument(help="output .html (self-contained)")],- title: Annotated[str | None, typer.Option("--title")] = None,- thumb_px: Annotated[int, typer.Option("--thumb-px", min=128, help="thumbnail long edge")] = 640,- embed: Annotated[bool, typer.Option("--embed/--no-embed", help="inline the contact sheets as data: URIs")] = True,-) -> None:- """Alias of `3dcode gallery build` (kept for scripts): one self-contained HTML page."""- from codeverse.addons.gallery.page import build_static-- path, n, _ = build_static([runs_dir], out_html, title=title, embed=embed, thumb_px=thumb_px)- ok(f"gallery of {n} runs → {path} ({path.stat().st_size // 1024} KB)")- console.print("[dim]`3dcode gallery serve` serves the same page with working links[/dim]")diff --git a/harness/codeverse/cli/inspect_cmd.py b/harness/codeverse/cli/inspect_cmd.pyindex bb806b7a..900b11d6 100644--- a/harness/codeverse/cli/inspect_cmd.py+++ b/harness/codeverse/cli/inspect_cmd.py@@ -33,8 +33,8 @@ def status(events: Annotated[int, typer.Option("--events", help="tail N events")] = 8,) -> None:"""Show spec / run_state / record / recent events of a run."""- from codeverse.flywheel.record import RecordError, load_recordfrom codeverse.proc import EventLog, holder_of+ from codeverse.record.record import RecordError, load_recordws = C.open_workspace(slug, runs_dir)spec = C.load_spec(ws)@@ -195,7 +195,7 @@ def judge(gates + acceptance + plan digest + previous verdict + stored clay views); writesartifacts/judge/rNN_cli.json."""from codeverse.cli import _judge as J- from codeverse.flywheel.record import load_record+ from codeverse.record.record import load_recordws = C.open_workspace(slug, runs_dir)rec = load_record(ws)diff --git a/harness/codeverse/cli/layout_cmd.py b/harness/codeverse/cli/layout_cmd.pyindex ab721e72..535660da 100644--- a/harness/codeverse/cli/layout_cmd.py+++ b/harness/codeverse/cli/layout_cmd.py@@ -80,7 +80,7 @@ def _legacy_deliverable_rows(ws: Workspace) -> dict[str, Any]:def print_deliverable(ws: Workspace, record: RunRecord) -> None:- from codeverse.flywheel.deliverable import load_deliverable+ from codeverse.record.deliverable import load_deliverable_section("DELIVERABLE — what the run produced")spec = record.spec@@ -103,8 +103,8 @@ def print_deliverable(ws: Workspace, record: RunRecord) -> None:# --------------------------------------------------------------------------- (b) evidencedef print_evidence(ws: Workspace, record: RunRecord) -> None:- from codeverse.flywheel.record import best_round_record, effective_judgment- from codeverse.flywheel.sample import gate_error_summary+ from codeverse.addons.dataset.sample import gate_error_summary+ from codeverse.record.record import best_round_record, effective_judgment_section("QUALITY EVIDENCE — why we believe it")rnd = best_round_record(record)@@ -162,7 +162,7 @@ def _roles_table(settings: SettingsSnapshot) -> Table:def print_cost_and_settings(ws: Workspace, record: RunRecord) -> None:- from codeverse.flywheel.telemetry import build_telemetry, load_telemetry+ from codeverse.record.telemetry import build_telemetry, load_telemetry_section("COST & SETTINGS — token price and the key step settings")tele = load_telemetry(ws, record)@@ -217,7 +217,7 @@ def show(section: Annotated[str, typer.Option("--section", help="all | deliverable | evidence | cost")] = "all",) -> None:"""Show one run in three separated sections: DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS."""- from codeverse.flywheel.record import RecordError, load_record+ from codeverse.record.record import RecordError, load_recordws = C.open_workspace(slug, runs_dir)try:diff --git a/harness/codeverse/cli/skills_cmd.py b/harness/codeverse/cli/skills_cmd.pyindex 541ff83e..3c11a91c 100644--- a/harness/codeverse/cli/skills_cmd.py+++ b/harness/codeverse/cli/skills_cmd.py@@ -40,9 +40,9 @@ def list_skills("""from rich.table import Table+ from codeverse.addons.skill_targets import target_forfrom codeverse.skills import iter_skillsfrom codeverse.skills.registry import ROUTED_SKILLS, ROUTES- from codeverse.skills.targets import target_forfound = list(iter_skills())t = Table(title="3dcode skills")@@ -85,10 +85,10 @@ def validate(strict: Annotated[bool, typer.Option("--strict", help="also fail on a routed skill with no bundle")] = False,) -> None:"""Check every bundle against the open spec and our budget/evidence rules."""+ from codeverse.addons.skill_targets import check_claimsfrom codeverse.skills import bundle_dirs, validate_bundlefrom codeverse.skills.model import SkillError, parse_skillfrom codeverse.skills.registry import ROUTED_SKILLS- from codeverse.skills.targets import check_claimsdirs = bundle_dirs()bad = 0diff --git a/harness/codeverse/cost/__init__.py b/harness/codeverse/cost/__init__.pyindex ccb42443..4f6cd891 100644--- a/harness/codeverse/cost/__init__.py+++ b/harness/codeverse/cost/__init__.py@@ -1,12 +1,12 @@"""Cost accounting: a typed ledger of every model call, a price-provenance layer on-top of ``models/pricing.py``, an audit over recorded runs, and a pre-send cost guard.+top of ``models/pricing.py``, and a pre-send cost guard. (The audit of FINISHED runs and+its report are ``codeverse.addons.costreport``.)This package re-exports only the names other packages actually import through it.-Everything else lives in — and is imported from — its own module: ``cost.report``-(console/markdown), ``cost.profiles`` (get_profile/PROFILES), ``cost.routing``+Everything else lives in — and is imported from — its own module: ``cost.profiles`` (get_profile/PROFILES), ``cost.routing``(ROUTES/Route), ``cost.instrument`` (metered_chat_model/MeteredAgent),``cost.types`` (CallCost/CostBucket/Summary), ``cost.reconstruct`` (RunLedger).-Keeping the shim narrow also keeps report/profiles/routing out of the eager import+Keeping the shim narrow also keeps profiles/routing out of the eager importgraph of ``import codeverse.cost``.Nothing here imports tracks/ or orchestrator/, so any layer may use it.@@ -14,7 +14,6 @@ Nothing here imports tracks/ or orchestrator/, so any layer may use it.from __future__ import annotations-from codeverse.cost.audit import audit_runsfrom codeverse.cost.context import call_contextfrom codeverse.cost.guard import estimate_callfrom codeverse.cost.instrument import run_ledger@@ -23,6 +22,6 @@ from codeverse.cost.reconstruct import find_runs, reconstructfrom codeverse.cost.types import Role, Stage__all__ = [- "CostLedger", "Role", "Stage", "audit_runs", "call_context", "estimate_call",+ "CostLedger", "Role", "Stage", "call_context", "estimate_call","find_runs", "load_ledger", "reconstruct", "record_call", "run_ledger", "summarise",]diff --git a/harness/codeverse/cost/reconstruct.py b/harness/codeverse/cost/reconstruct.pyindex 5d6fb302..99ac1caf 100644--- a/harness/codeverse/cost/reconstruct.py+++ b/harness/codeverse/cost/reconstruct.py@@ -38,8 +38,8 @@ from codeverse.contracts.common import Usagefrom codeverse.contracts.run import RunIdfrom codeverse.cost.ledger import price_callfrom codeverse.cost.types import CallCost, Role, Stage, role_for_stage, stage_for_label-from codeverse.flywheel.record import SUBRUN_DIRSfrom codeverse.proc import read_json_or_none, read_jsonl_lenient+from codeverse.record.record import SUBRUN_DIRSlog = logging.getLogger(__name__)diff --git a/harness/codeverse/flywheel/__init__.py b/harness/codeverse/flywheel/__init__.pydeleted file mode 100644index d7f8dc84..00000000--- a/harness/codeverse/flywheel/__init__.py+++ /dev/null@@ -1,14 +0,0 @@-"""Flywheel: what every run WRITES so it can be learned from later.--Public API (see docs/INTERFACES.md):--* ``record`` ``finalize_record(ws, record)`` · ``load_record(ws)`` · ``iter_runs(runs_dir)``-* ``deliverable`` the run's ``deliverable/`` directory-* ``telemetry`` the settings / environment a record carries-* ``sample`` one run → one dataset sample (code files of the best round)-* ``quality`` ``quality_tier`` (A/B/C/D) · ``prompt_hash`` · code / mesh fingerprints, duplicate groups-* ``code_quality`` the per-record code metrics--Turning a tree of finished runs into a dataset (export, pack, pairs, captions, index) is-``codeverse.addons.dataset``.-"""diff --git a/harness/codeverse/flywheel/code_quality.py b/harness/codeverse/flywheel/code_quality.pydeleted file mode 100644index d126b74f..00000000--- a/harness/codeverse/flywheel/code_quality.py+++ /dev/null@@ -1,332 +0,0 @@-"""A deterministic code-quality vector for the flywheel: is this code worth learning from?--The judge scores the PICTURE; the gates score the GEOMETRY. Nothing scored the CODE, and-the code is the dataset. A run can ship a 0.85 render from a 900-line ``model.py`` with-one function, 400 unnamed numbers and three copies of the same loop — a fine artifact and-a poor training example. This module measures the difference so ``flywheel export`` can-filter on it, the same way it already filters on ``score`` and ``complexity``.--Everything here is computed from the source tree of the BEST round, offline, in-milliseconds, with no model call. Python languages (blender, cadquery, urdf_blender,-opengl_python) go through ``ast``; JavaScript / GLSL (threejs, scene_threejs, glsl_shader)-through a small tokenizer, because nothing in the harness's python side parses JS and-shelling out to node for a metric is not worth its cost. The two paths report the same-fields; the JS numbers are approximate and say so (``method``).--What is measured, and why each one:--* ``magic_per_100loc`` — numeric literals that are neither bound to a name at module- level nor one of the trivially-structural values (0, 1, 2, 0.5, -1, 180, 360 …). The- authoring contracts say "plan numbers = named constants at the top"; this is that rule- as a number. A dimension buried in a call cannot be found by a refine session and- cannot be learned as a *design decision*.-* ``fn_len_max`` / ``fn_len_mean`` — a part is meant to be one function. A 300-line- function is a script, not a part library.-* ``dead_functions`` — defined and never referenced. Scaffolding a model wrote and- abandoned; the flywheel would learn to write it too.-* ``duplication`` — fraction of 6-line windows (whitespace-normalised) that occur more- than once. Symmetry by construction is the contract; copy-paste is its failure mode.-* ``docstring_cov`` (python only) — functions with a docstring. Cheap, and the only- in-band explanation of *why* a shape is what it is.-* ``const_names`` — module-level UPPER_CASE bindings. The positive form of the magic- count.--``index`` folds these into one 0-1 number with stated weights, so a dataset can be cut-at "index >= 0.6" the way it is cut at "score >= 0.7". The weights are a first guess-and are recorded in the block so a later re-weighting can recompute from the fields.-"""--from __future__ import annotations--import ast-import hashlib-import re-from collections.abc import Mapping-from typing import Any--from pydantic import BaseModel, Field--VERSION = 1-PY_SUFFIXES = (".py",)-JS_SUFFIXES = (".js", ".mjs", ".glsl", ".frag", ".vert")-#: literals that are structure, not design: counting them as magic would punish every-#: ``range(2)``, ``* 0.5``, ``rotate(90)``.-_STRUCTURAL = frozenset({0, 1, 2, 3, 4, -1, 0.5, 90, 180, 360})-_WINDOW = 6-_WEIGHTS: dict[str, float] = {- "magic": 0.30,- "fn_len": 0.20,- "dead": 0.15,- "dup": 0.20,- "doc": 0.05,- "const": 0.10,-}---class CodeQuality(BaseModel):- version: int = VERSION- method: str = Field(description="ast (python) | tokens (js/glsl, approximate) | mixed")- n_files: int = 0- loc: int = 0- n_functions: int = 0- fn_len_mean: float = 0.0- fn_len_max: int = 0- magic_numbers: int = 0- magic_per_100loc: float = 0.0- const_names: int = 0- dead_functions: int = 0- docstring_cov: float | None = Field(default=None, description="python only")- duplication: float = 0.0- index: float = 0.0- weights: dict[str, float] = Field(default_factory=lambda: dict(_WEIGHTS))---# ----------------------------------------------------------------------------- python-def _py_stats(src: str) -> dict[str, Any]:- try:- tree = ast.parse(src)- except SyntaxError:- return {"parsed": False}- const_names: set[str] = set()- bound_values: set[float] = set()- for node in tree.body:- targets: list[ast.expr] = []- if isinstance(node, ast.Assign):- targets = node.targets- elif isinstance(node, ast.AnnAssign) and node.target is not None:- targets = [node.target]- for t in targets:- names = [e.id for e in ast.walk(t) if isinstance(e, ast.Name)]- if any(n.isupper() for n in names):- const_names.update(n for n in names if n.isupper())- for c in ast.walk(- node.value- if isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value- else ast.Constant(0)- ):- if (- isinstance(c, ast.Constant)- and isinstance(c.value, (int, float))- and not isinstance(c.value, bool)- ):- bound_values.add(c.value)- fns = [n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]- fn_lens = [max(1, (n.end_lineno or n.lineno) - n.lineno + 1) for n in fns]- docs = sum(1 for n in fns if ast.get_docstring(n))- called: set[str] = set()- for n in ast.walk(tree):- if isinstance(n, ast.Name):- called.add(n.id)- elif isinstance(n, ast.Attribute):- called.add(n.attr)- defined = {n.name for n in fns}- dead = [d for d in defined if d not in called and not d.startswith("_") and d != "main"]- # magic: numeric constants inside calls / binops, not in a module-level constant binding- top_level_const_nodes: set[int] = set()- for node in tree.body:- if isinstance(node, (ast.Assign, ast.AnnAssign)):- for c in ast.walk(node):- top_level_const_nodes.add(id(c))- magic = 0- for n in ast.walk(tree):- if (- isinstance(n, ast.Constant)- and isinstance(n.value, (int, float))- and not isinstance(n.value, bool)- ):- if id(n) in top_level_const_nodes or n.value in _STRUCTURAL or n.value in bound_values:- continue- magic += 1- return {- "parsed": True,- "n_functions": len(fns),- "fn_lens": fn_lens,- "docs": docs,- "dead": len(dead),- "magic": magic,- "const_names": len(const_names),- }---# ----------------------------------------------------------------------------- js / glsl-_JS_FN = re.compile(- r"\bfunction\b\s*[A-Za-z_$][\w$]*\s*\(|=>|\b(?:export\s+)?(?:async\s+)?function\s*\("-)-_JS_NAMED_FN = re.compile(- r"\bfunction\s+([A-Za-z_$][\w$]*)|\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>"-)-#: every UPPER_CASE name bound in a ``const`` statement — ``const A = 1, B = 2`` binds two-_JS_CONST_STMT = re.compile(r"\bconst\s+([^;]+?);", re.S)-_JS_UPPER_BIND = re.compile(r"\b([A-Z][A-Z0-9_]{2,})\s*=")-_JS_NUM = re.compile(r"(?<![\w.])-?\d+(?:\.\d+)?(?![\w.])")-_JS_STRIP = re.compile(- r"//[^\n]*|/\*.*?\*/|'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"|`(?:\\.|[^`\\])*`", re.S-)---def _js_stats(src: str) -> dict[str, Any]:- code = _JS_STRIP.sub(" ", src)- lines = code.splitlines()- consts: set[str] = set()- for m in _JS_CONST_STMT.finditer(code):- consts.update(_JS_UPPER_BIND.findall(m.group(1)))- const_line_idx = {- i- for i, ln in enumerate(lines)- if ln.lstrip().startswith("const ") and _JS_UPPER_BIND.search(ln)- }- magic = 0- for i, ln in enumerate(lines):- if i in const_line_idx:- continue- for m in _JS_NUM.finditer(ln):- try:- v = float(m.group(0))- except ValueError:- continue- if v in _STRUCTURAL:- continue- magic += 1- # crude function extents: count openers; lengths via brace depth from each 'function' / '=>'- names = [g[0] or g[1] for g in _JS_NAMED_FN.findall(code)]- fn_lens: list[int] = []- for m in _JS_FN.finditer(code):- depth = 0- started = False- length = 0- for ch in code[m.start() :]:- if ch == "{":- depth += 1- started = True- elif ch == "}":- depth -= 1- elif ch == "\n":- length += 1- if started and depth == 0:- break- if length > 2000:- break- fn_lens.append(max(1, length))- called = set(re.findall(r"\b([A-Za-z_$][\w$]*)\s*\(", code))- exported = set(re.findall(r"\bexport\s+(?:function|const|let)\s+([A-Za-z_$][\w$]*)", code))- dead = [n for n in names if n and n not in called and n not in exported]- return {- "parsed": True,- "n_functions": len(fn_lens),- "fn_lens": fn_lens,- "docs": None,- "dead": len(dead),- "magic": magic,- "const_names": len(consts),- }---# ----------------------------------------------------------------------------- shared-def _duplication(sources: list[str]) -> float:- seen: dict[str, int] = {}- total = 0- for src in sources:- norm = [re.sub(r"\s+", " ", ln).strip() for ln in src.splitlines()]- norm = [ln for ln in norm if ln and not ln.startswith(("#", "//"))]- for i in range(0, max(0, len(norm) - _WINDOW + 1)):- h = hashlib.blake2b(- "\n".join(norm[i : i + _WINDOW]).encode(), digest_size=8- ).hexdigest()- seen[h] = seen.get(h, 0) + 1- total += 1- if not total:- return 0.0- dup = sum(c for c in seen.values() if c > 1)- return round(dup / total, 4)---def _loc(src: str) -> int:- return sum(- 1 for ln in src.splitlines() if ln.strip() and not ln.strip().startswith(("#", "//"))- )---def _index(q: CodeQuality) -> float:- """0-1; 1 = tidy. Each term is a saturating penalty, so one bad axis cannot go negative."""- magic = max(0.0, 1.0 - q.magic_per_100loc / 25.0) # 25 unnamed numbers per 100 lines = 0- fn_len = max(0.0, 1.0 - max(0, q.fn_len_max - 60) / 240.0) # a 300-line function = 0- dead = max(0.0, 1.0 - q.dead_functions / max(q.n_functions, 1) * 2)- dup = max(0.0, 1.0 - q.duplication * 3) # a third duplicated = 0- doc = q.docstring_cov if q.docstring_cov is not None else 0.5- const = min(1.0, q.const_names / 8.0)- w = _WEIGHTS- return round(- w["magic"] * magic- + w["fn_len"] * fn_len- + w["dead"] * dead- + w["dup"] * dup- + w["doc"] * doc- + w["const"] * const,- 4,- )---def measure(files: Mapping[str, bytes | str]) -> CodeQuality | None:- """The vector for one code tree (``path -> bytes/str``). ``None`` when nothing parses."""- py: list[dict[str, Any]] = []- js: list[dict[str, Any]] = []- sources: list[str] = []- loc = 0- n = 0- for path, body in files.items():- text = body.decode("utf-8", "replace") if isinstance(body, bytes) else body- if path.endswith(PY_SUFFIXES):- st = _py_stats(text)- if st.get("parsed"):- py.append(st)- sources.append(text)- loc += _loc(text)- n += 1- elif path.endswith(JS_SUFFIXES):- st = _js_stats(text)- js.append(st)- sources.append(text)- loc += _loc(text)- n += 1- stats = py + js- if not stats:- return None- fn_lens = [x for s in stats for x in s["fn_lens"]]- n_fn = sum(s["n_functions"] for s in stats)- docs = [s["docs"] for s in py if s.get("docs") is not None]- q = CodeQuality(- method="ast" if py and not js else "tokens" if js and not py else "mixed",- n_files=n,- loc=loc,- n_functions=n_fn,- fn_len_mean=round(sum(fn_lens) / len(fn_lens), 1) if fn_lens else 0.0,- fn_len_max=max(fn_lens) if fn_lens else 0,- magic_numbers=sum(s["magic"] for s in stats),- magic_per_100loc=round(100.0 * sum(s["magic"] for s in stats) / max(loc, 1), 2),- const_names=sum(s["const_names"] for s in stats),- dead_functions=sum(s["dead"] for s in stats),- docstring_cov=round(sum(docs) / max(sum(s["n_functions"] for s in py), 1), 3)- if py- else None,- duplication=_duplication(sources),- )- q.index = _index(q)- return q---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.record import best_round_record- from codeverse.flywheel.sample import code_files_for_round-- try:- rnd = best_round_record(record)- files, source = code_files_for_round(ws, rnd)- except Exception: # noqa: BLE001 — a metric must never fail a run- return None- q = measure(files)- if q is None:- return None- block = q.model_dump(mode="json")- block["code_source"] = source- return blockdiff --git a/harness/codeverse/orchestrator.py b/harness/codeverse/orchestrator.pyindex 40bb4730..4beda6be 100644--- a/harness/codeverse/orchestrator.py+++ b/harness/codeverse/orchestrator.py@@ -456,7 +456,7 @@ KIND_FOR_STRATEGY: dict[str, str] = {"same": "refine", "switch": REWRITE_KIND, "#: σ for a judge that is not in the measured table: the default judge's#: (``gemini-3.1-pro-preview``, ``Settings.default_judge``), because that is what#: an unnamed judge almost always is. Calibrate a new judge-#: (``python -m codeverse.judges.calibration``) and add it to JUDGE_NOISE rather+#: (``python -m codeverse.addons.calibration``) and add it to JUDGE_NOISE rather#: than tuning the multipliers around it.DEFAULT_JUDGE_SIGMA = 0.030diff --git a/harness/codeverse/record/__init__.py b/harness/codeverse/record/__init__.pynew file mode 100644index 00000000..e97d27c4--- /dev/null+++ b/harness/codeverse/record/__init__.py@@ -0,0 +1,10 @@+"""What every run WRITES so it can be read later: ``record.json`` and what travels with it.++* ``record`` ``finalize_record(ws, record)`` · ``load_record(ws)`` · ``iter_runs(runs_dir)`` ·+ ``best_round_record`` · ``unique_files``+* ``deliverable`` the run's ``deliverable/`` directory+* ``telemetry`` the settings / environment a record carries+* ``_git`` reading the workspace's own git history (files at a round's commit)++Turning a tree of finished runs into a dataset, a gallery or a cost report is ``codeverse.addons``.+"""diff --git a/harness/codeverse/flywheel/_git.py b/harness/codeverse/record/_git.pysimilarity index 100%rename from harness/codeverse/flywheel/_git.pyrename to harness/codeverse/record/_git.pydiff --git a/harness/codeverse/flywheel/deliverable.py b/harness/codeverse/record/deliverable.pysimilarity index 99%rename from harness/codeverse/flywheel/deliverable.pyrename to harness/codeverse/record/deliverable.pyindex 9ca53eda..5498f8c8 100644--- a/harness/codeverse/flywheel/deliverable.py+++ b/harness/codeverse/record/deliverable.py@@ -28,8 +28,8 @@ from pathlib import Pathfrom codeverse.contracts.common import ENTRY_FILE, Languagefrom codeverse.contracts.run import DeliverableFile, RoundRecord, RunDeliverable, RunRecord-from codeverse.flywheel import _gitfrom codeverse.proc import sha256_file, write_json_atomic+from codeverse.record import _gitfrom codeverse.workspace import Workspacelog = logging.getLogger(__name__)@@ -170,7 +170,7 @@ def build_deliverable(ws: Workspace, record: RunRecord, *, clean: bool = True) -Idempotent: the folder is rebuilt from scratch every time, so a second callon an unchanged run produces byte-identical content."""- from codeverse.flywheel.record import best_round_record+ from codeverse.record.record import best_round_recordrnd = best_round_record(record)previous = load_deliverable(ws) if ws.deliverable_manifest_path.is_file() else Nonediff --git a/harness/codeverse/flywheel/record.py b/harness/codeverse/record/record.pysimilarity index 96%rename from harness/codeverse/flywheel/record.pyrename to harness/codeverse/record/record.pyindex 6e153ded..843307e7 100644--- a/harness/codeverse/flywheel/record.py+++ b/harness/codeverse/record/record.py@@ -25,7 +25,6 @@ from codeverse import __version__from codeverse.config import get_settingsfrom codeverse.contracts.common import Usagefrom codeverse.contracts.run import RoundRecord, RunId, RunRecord-from codeverse.flywheel.code_quality import code_quality_blockfrom codeverse.proc import version_linefrom codeverse.workspace import Workspace@@ -71,7 +70,7 @@ def _harness_git_sha(pkg_file: Path | None = None) -> str:return ""sha = head.stdout.strip()# dirty = any tracked file under the package tree (harness/) modified; untracked files ignored- pkg_root = here.parents[2] if here.parent.name == "flywheel" else here.parent+ pkg_root = here.parents[2] if here.parent.name == "record" else here.parentstatus = _git(["status", "--porcelain", "--untracked-files=no", "--", str(pkg_root)], here.parent)if status is not None and status.returncode == 0 and status.stdout.strip():sha += "-dirty"@@ -260,8 +259,8 @@ def package_run(ws: Workspace, record: RunRecord) -> None:Best-effort by contract: a packaging failure is logged and the run stillgets its ``record.json`` (the old layout is always enough to read a run)."""- from codeverse.flywheel.deliverable import build_deliverable- from codeverse.flywheel.telemetry import build_telemetry+ from codeverse.record.deliverable import build_deliverable+ from codeverse.record.telemetry import build_telemetrytry:ws.ensure_layout()@@ -284,12 +283,6 @@ def finalize_record(ws: Workspace, record: RunRecord, *, package: bool = True) -fill_derived(record)if package:package_run(ws, record)- # the delivered CODE's own vector, next to the delivered ARTIFACT's (complexity):- # the judge scored the picture, the gates the geometry; this scores what the- # flywheel will actually learn from (flywheel/code_quality.py)- cq = code_quality_block(ws, record)- if cq is not None:- record.extra["code_quality"] = cqws.write_json(ws.record_path, record)return ws.record_pathdiff --git a/harness/codeverse/flywheel/telemetry.py b/harness/codeverse/record/telemetry.pysimilarity index 100%rename from harness/codeverse/flywheel/telemetry.pyrename to harness/codeverse/record/telemetry.pydiff --git a/harness/codeverse/skills/__init__.py b/harness/codeverse/skills/__init__.pyindex 3631f556..7bf17f16 100644--- a/harness/codeverse/skills/__init__.py+++ b/harness/codeverse/skills/__init__.py@@ -107,10 +107,9 @@ def load_skill(name: str, root: Path | None = None) -> Skill:from codeverse.skills.config import skills_enabled, skills_max, skills_unverified # noqa: E402from codeverse.skills.materialize import attach_skills, materialize_skills # noqa: E402from codeverse.skills.registry import plan_signals, select, skills_for # noqa: E402-from codeverse.skills.targets import check_claims # noqa: E402from codeverse.skills.telemetry import probe_reads # noqa: E402__all__ = ["SKILLS_DIR_ENV", "Skill", "SkillError", "SkillRef", "all_skills", "attach_skills", "bundle_dirs",- "check_claims", "iter_skills", "load_skill", "materialize_skills", "plan_signals", "probe_reads", "select",+ "iter_skills", "load_skill", "materialize_skills", "plan_signals", "probe_reads", "select","skills_dir", "skills_enabled", "skills_for", "skills_max", "skills_unverified","validate_bundle"]diff --git a/harness/codeverse/tracks/common.py b/harness/codeverse/tracks/common.pyindex 004ec6ff..fafd9e1c 100644--- a/harness/codeverse/tracks/common.py+++ b/harness/codeverse/tracks/common.py@@ -148,7 +148,7 @@ class Services:return fn(ws, plan, cameras="plan" if getattr(plan, "cameras", None) else "derive")def finalize_record(self, ws: Workspace, record: RunRecord) -> None:- _import("codeverse.flywheel.record", "finalize_record")(ws, record)+ _import("codeverse.record.record", "finalize_record")(ws, record)# ----------------------------------------------------------------------------- contextdiff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex c9828eb2..2003bc77 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -140,22 +140,21 @@ codeverse/skills/ registry.py (typed ROUTES + the router that evaluates them),model.py (Skill/Selection + the SKILL.md loader), prompting.py(per-backend delivery policy + the index/mandate text),- targets.py (measured targets + claims), materialize.py,+ materialize.py,telemetry.py (the read probe), config.py (call-time switches)cost/ types.py (CallCost/Stage/Role) ledger.py (append-only telemetry/cost.jsonl + price provenance)context.py (per-call > ambient attribution) instrument.py (MeteredChatModel /MeteredAgent — one row per ChatModel.generate; one session row only for a backendthat does NOT meter itself; run_ledger nests + is context-local so bench --parallel works)profiles.py (economy|balanced|quality; cli._common.resolve_dial is THE resolver)- caching.py (session_cache/session_key — measurement only, docs/COST.md §13)billing.py (SUBSCRIPTION_BACKENDS/bills_usd — which backends take real dollars,so the ledger bills real money and not list price; docs/COST.md §25)- guard.py routing.py reconstruct.py (old runs) audit.py report.py+ guard.py routing.py reconstruct.py (old runs)judges/ base.py (JudgeInput/Judgment helpers + the pure round-replay pieces `3dcode judge` andcalibration share), rubrics.py + rubrics/*.yaml (defect checklists, the wireschema, caps and scoring), prompt_builder.py (image prep, montages, thejudge messages), vlm_judge.py (+ the reference/likeness judges),- pairwise.py, calibration.py. No Judge Protocol: a judge is+ pairwise.py. No Judge Protocol: a judge isduck-typed `.judge(JudgeInput) -> Judgment`reference.py reference GROUNDING — give the pipeline a picture of what it is building:synthesis, THE plausibility gate that makes a synthesized@@ -197,14 +196,15 @@ codeverse/planner as a re-ask before any code is written),skills_hook.py (the round's view of codeverse/skills: attach before generating,probe reads after — a no-op unless CV3D_SKILLS is on)- flywheel/ what every run WRITES: record.py (+ best_round_record), sample.py,- deliverable.py, telemetry.py, quality.py (tiers + dedupe + code/mesh fingerprints),- code_quality.py (the delivered CODE's own vector — magic numbers per 100 LOC,- function length, dead functions, duplication, docstrings → record.extra- ["code_quality"].index, a flywheel filter beside score and complexity)+ record/ what every run WRITES: record.py (finalize_record, load_record, iter_runs,+ best_round_record), deliverable.py, telemetry.py, _git.py (files at a round's commit)addons/ optional tools that READ finished runs; outside cli/ nothing imports them(tests/core/test_addons_boundary.py). dataset/ = export.py, pack.py, pairs.py,- refine.py, captions.py, index.py (`3dcode flywheel …`); gallery/ = below+ refine.py, captions.py, index.py, sample.py, quality.py (tiers + code fingerprints ++ duplicate groups) — `3dcode flywheel …`; costreport/ = audit.py, report.py,+ caching.py (session_cache/session_key — measurement only, docs/COST.md §13) —+ `3dcode cost`; calibration.py (judge repeatability over recorded runs);+ skill_targets.py (measured targets + claims per skill bundle); gallery/ = belowaddons/gallery/ THE local run gallery (`3dcode gallery serve|build`): cards.py,compare.py (side-by-side arms), index.py (run roots →typed RunEntry, tolerant of half-written records), model.py, page.py (cards +@@ -563,7 +563,7 @@ in the harness's own words, and what the fix changed. `toolkits/llamafactory/`turns those rows into training files; the harness writes the measurement, not thetrainer's format. `flywheel caption` adds{detailed, instruction, factory} captions (image-grounded, brand-free, `--out` for-side-car mode); `flywheel gallery` is an alias of `3dcode gallery build --embed`+side-car mode); the gallery is `3dcode gallery build --embed`(the flywheel package has no renderer of its own).`codeverse/addons/gallery/` is the **local** answer to the same question: `3dcode gallerydiff --git a/harness/docs/COST.md b/harness/docs/COST.mdindex e59ddf85..2cbcb904 100644--- a/harness/docs/COST.md+++ b/harness/docs/COST.md@@ -15,7 +15,7 @@ Reproduce:3dcode cost prices [--unverified] # the price table + provenance```-The audit is `codeverse/cost/audit.py`; it reconstructs a per-call ledger from+The audit is `codeverse/addons/costreport/audit.py`; it reconstructs a per-call ledger fromold runs (`codeverse/cost/reconstruct.py`), so it works on every run recorded sofar — no re-instrumentation needed. `bench/out/compare_v1_full` (a partial,superseded compare battery) is excluded.diff --git a/harness/docs/EVAL.md b/harness/docs/EVAL.mdindex 7a1100f6..39abad70 100644--- a/harness/docs/EVAL.md+++ b/harness/docs/EVAL.md@@ -152,10 +152,10 @@ cross-backend candidate pairs keyed by prompt hash).## 6. Judge calibration-`codeverse.judges.calibration` re-judges recorded rounds without touching the runs:+`codeverse.addons.calibration` re-judges recorded rounds without touching the runs:```bash-python -m codeverse.judges.calibration <run-dir> [<run-dir> ...] \+python -m codeverse.addons.calibration <run-dir> [<run-dir> ...] \--model gemini:gemini-3.1-pro-preview --n 3 --out out/calib [--geometry clay|normals|none] [--rounds 0,1]# run dirs: any recorded run, e.g. bench/out/<battery>/runs/<slug>```diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.mdindex 9f247049..5167fbdc 100644--- a/harness/docs/INTERFACES.md+++ b/harness/docs/INTERFACES.md@@ -132,7 +132,7 @@ from codeverse.cost.ledger import bound_ledger, process_ledger_path # (Δ 2026# session's; a generation label yields to the session (best-of-N: kind="candidate" beats# label="baseline"); Stage.OTHER means "the label said nothing" and displaces nothing.# labels understood: judge:<rubric>:r<NN>:s<k> · planner · pairwise:… · texture… · caption… (api-agent:<label>:t<turn> in historical ledgers only)-from codeverse.cost.caching import session_cache, session_key+from codeverse.addons.costreport.caching import session_cache, session_keysession_cache(rows) -> [SessionCache] # per session: cold first call, cached share, saved_usd, cold_usdfrom codeverse.cost.profiles import get_profile, PROFILES # economy | balanced | qualityget_settings().apply_profile(name, *, force=False) -> Profile@@ -371,8 +371,8 @@ from codeverse.judges.rubrics import apply_caps # (rubric, overall, ga# console_errors=None, views=None, defects_present=None) -> CapResult;# cap rules add when="missing_views" and ledger lines "defect:<id>"from codeverse.judges.pairwise import PairwiseJudge # .compare(spec, renders_a, renders_b, *, rubric=…) -> PairwiseResult-from codeverse.judges.calibration import calibrate, CalibrationTable # (run_dirs, *, model_id, n_samples=3, out_dir, geometry_mode,- # rounds, …) -> rows + pearson/spearman(errors vs score), mean_std, cost; CLI: python -m codeverse.judges.calibration RUN… --n 3+from codeverse.addons.calibration import calibrate, CalibrationTable # (run_dirs, *, model_id, n_samples=3, out_dir, geometry_mode,+ # rounds, …) -> rows + pearson/spearman(errors vs score), mean_std, cost; CLI: python -m codeverse.addons.calibration RUN… --n 3from codeverse.judges.vlm_judge import ReferenceJudge # image-conditioned specs```Rubrics: `static_object_v1` (0.72), `articulated_v1` (requires pose views via@@ -529,14 +529,14 @@ from codeverse.texturing.plan import scene_texture_pack, texture_pack_prompt ### flywheel/ + cli/```python-from codeverse.flywheel.record import finalize_record, load_record, iter_runs, best_round_index, best_round_record+from codeverse.record.record import finalize_record, load_record, iter_runs, best_round_index, best_round_recordfrom codeverse.addons.gallery.index import hero_view # (ws, rec) -> (rel, label, n_views): the card image, rebased via ws-from codeverse.flywheel.record import complexity_block, round_complexity # objective complexity of what shipped+from codeverse.record.record import complexity_block, round_complexity # objective complexity of what shipped# finalize_record fills record.extra["complexity"] = the BEST round's vector + plan_parts /# parts_per_plan_part / by_round; every rounds_summary row gains "complexity" (the index or None)from codeverse.addons.dataset.export import export_samples # (runs_dir, out_dir, *, min_score=None, only_passed=False,# include_unbuilt=False, captions_dir=None, drop_duplicates=False) -> ExportReport{…, n_duplicates, duplicates, tiers}-from codeverse.flywheel.quality import quality_tier, prompt_hash, find_duplicates # tiers: A passed & 0 gate errors, B passed,+from codeverse.addons.dataset.quality import quality_tier, prompt_hash, find_duplicates # tiers: A passed & 0 gate errors, B passed,# C best ≥ 0.6, D else; dedupe = (code fingerprint, prompt)from codeverse.addons.dataset.pairs import build_pairs # (runs_dir, out_jsonl, *, min_delta=0.05) -> nfrom codeverse.addons.dataset.refine import build_refine, transitions, RefineTransition, REFINE_KINDS, outcome_of@@ -546,11 +546,11 @@ from codeverse.addons.dataset.refine import build_refine, transitions, RefineTra# one row per round i -> i+1 the harness asked to change; outcome improved|regressed|unchanged|unscored# (threshold: pairs.MIN_PREFERENCE_DELTA); dropped rows carry the reason (no_predecessor / no_commit /# predecessor_build_failed / predecessor_unjudged / git_read_failed / duplicate_run)-from codeverse.flywheel._git import read_tree_at, diff_between, changed_files_between, commit_exists, GitReadError+from codeverse.record._git import read_tree_at, diff_between, changed_files_between, commit_exists, GitReadError# read_tree_at(ws, commit, *, paths=None) -> {path: bytes} via ls-tree + cat-file --batch — NEVER# `git archive`, which renders content through a planted filter.<name>.smudge and has no --no-filters# (tests/flywheel_cli); symlinks (mode 120000) are skipped; `paths` reads only those files-from codeverse.flywheel.record import unique_files, SUBRUN_DIRS, BATTERY_MARKERS+from codeverse.record.record import unique_files, SUBRUN_DIRS, BATTERY_MARKERS# unique_files(root, name) -> [Path]: every file called `name` under root ONCE per file on disk (follows# the run/telemetry/trajectories symlink and collapses it; skips SUBRUN_DIRS = {_cand, _assets}) — the# one walker behind bench/session_stats.py, bench/coupling_stats.py and cost.reconstruct.find_runs@@ -578,7 +578,7 @@ from codeverse.addons.dataset.index import build_index, query, summary # sqlit# rounds, status, code_fingerprint, prompt_hash, duplicate_of, has_captions3dcodeverse make [--profile economy|balanced|quality]|resume|status|show|render|judge|tools|mcp|texture {pass,scene-pack,show}|cost {<slug>,show,cache,prices,profiles,estimate}- |flywheel {export,pairs,refine,caption,index,dedupe,gallery}|gallery {serve,build}+ |flywheel {export,pairs,refine,caption,index}|gallery {serve,build}|bench {run,report}|doctor # alias: 3dcode```diff --git a/harness/docs/RUNBOOK.md b/harness/docs/RUNBOOK.mdindex e05e81e5..58312651 100644--- a/harness/docs/RUNBOOK.md+++ b/harness/docs/RUNBOOK.md@@ -118,7 +118,6 @@ events.3dcode gallery serve # ./runs + every ./bench/out/*/runs → http://127.0.0.1:8765/3dcode gallery serve bench/out/static_v2_flash/runs --port 9000 --reload --no-open3dcode gallery build --out gallery.html [--embed] # one self-contained file (--embed inlines the sheets)-3dcode flywheel gallery runs/ gallery.html # alias of `gallery build --embed` (old signature)````serve` indexes the run roots (records only — ~85 runs in ~0.15 s) and serves the run**directories** too, so every link works: contact sheet, full-size renders, `record.json`,@@ -164,9 +163,8 @@ unless you type `--host` yourself; it never serves a path outside the declared r# INTERFACES has the call signatures. Training formats live# in toolkits/llamafactory/, not here.3dcode flywheel caption <slug> [--model …] [--out caps/] # --out = side-car mode, run untouched-3dcode flywheel gallery runs/ gallery.html [--title …] # alias of `3dcode gallery build --embed` (§4)-3dcode flywheel index runs/ runs_index.sqlite · 3dcode flywheel dedupe dataset/-python -m codeverse.judges.calibration runs/<slug> [runs/<slug2> …] --model gemini:gemini-3.1-pro-preview --n 3 --out out/+3dcode flywheel index runs/ runs_index.sqlite+python -m codeverse.addons.calibration runs/<slug> [runs/<slug2> …] --model gemini:gemini-3.1-pro-preview --n 3 --out out/# re-judges recorded rounds; writes calibration_<model>.md/.json (never touches runs/)```**Do not run the offline suite while a battery is running.** The suite is 2 300+ tests ondiff --git a/harness/docs/RUN_LAYOUT.md b/harness/docs/RUN_LAYOUT.mdindex 86c92af8..30b2d716 100644--- a/harness/docs/RUN_LAYOUT.md+++ b/harness/docs/RUN_LAYOUT.md@@ -66,7 +66,7 @@ never enter the code snapshot.## `deliverable/`-Built by `codeverse.flywheel.deliverable.build_deliverable(ws, record)` from the+Built by `codeverse.record.deliverable.build_deliverable(ws, record)` from the**best round** (`record.best_round`, else the highest judged score):```@@ -100,7 +100,7 @@ the packager produces no diff.harness version + git sha; key-pool size; **price-table hash**; resolvedrender and limit settings. Sampling values are read from the call sites'typed defaults (`VlmJudge.__init__`, `planner.plan`, and- `flywheel/telemetry.py::_generator_defaults` — a historical shim that+ `record/telemetry.py::_generator_defaults` — a historical shim thatconfigures nothing, kept so old records still read back); avalue a call site hard-codes per task is left empty with `source` saying so,never guessed. A track may publish real values as@@ -162,7 +162,7 @@ provenance — use the cost package's own command, `3dcode cost show <runs-dir>`* `flywheel export` reads the packaged code snapshot only when git cannot answer(`meta.code_source == "deliverable"`), and adds a compact `meta.telemetry`digest when the run has one (`{}` otherwise).-* the gallery (`3dcode gallery build` / `flywheel gallery`) links the packaged+* the gallery (`3dcode gallery build`) links the packaged`deliverable/object.glb` and `cost.json` when they exist and falls back to`artifacts/` otherwise; the per-stage cost line appears only for runs thatcarry telemetry.diff --git a/harness/docs/SKILLS.md b/harness/docs/SKILLS.mdindex 2e441507..84c8cb82 100644--- a/harness/docs/SKILLS.md+++ b/harness/docs/SKILLS.md@@ -146,7 +146,7 @@ record refers to a routing decision by id, so recycling it would silently relabe`evidence` is about **provenance** — where the bundle's prose came from. A bundle can be`measured` for provenance and have **no measured effect**; five are. Every bundle alsodeclares **one deterministic quantity it claims to move**, in its own frontmatter-(`target_metric`, `target_direction`, `target_baseline`) and in `codeverse/skills/targets.py`.+(`target_metric`, `target_direction`, `target_baseline`) and in `codeverse/addons/skill_targets.py`.`python bench/skill_targets.py bench/out` prints them all — per battery or paired across anA/B's two arms — and **`docs/SKILLS_LEDGER.md` is the row-by-row maintenance surface**.@@ -513,7 +513,7 @@ chose to go deeper" (§1).format = "{:.0f} mm"```4. Add its rows to `ROUTES` in `codeverse/skills/registry.py`, in the same commit.-5. Add a `Target` row to `codeverse/skills/targets.py` and the matching `target_*` keys to+5. Add a `Target` row to `codeverse/addons/skill_targets.py` and the matching `target_*` keys tothe frontmatter — the ONE deterministic quantity the bundle claims to move, itsdirection, and its baseline from `python bench/skill_targets.py bench/out`. If nodeterministic instrument can see the claim, say so with `measurable=False` and adiff --git a/harness/docs/SKILLS_LEDGER.md b/harness/docs/SKILLS_LEDGER.mdindex f7041322..429ba9cf 100644--- a/harness/docs/SKILLS_LEDGER.md+++ b/harness/docs/SKILLS_LEDGER.md@@ -14,7 +14,7 @@ Three files hold it up:| file | what it is ||---|---|-| `codeverse/skills/targets.py` | the table — one `Target` row per bundle |+| `codeverse/addons/skill_targets.py` | the table — one `Target` row per bundle || `bench/skill_targets.py` | the readout — one command, battery **or** A/B || `tests/skills/test_targets.py` | the pins — the rows exist, the gate kinds are still live, the frontmatter agrees, the readout counts what the row says |diff --git a/harness/tests/core/test_addons_boundary.py b/harness/tests/core/test_addons_boundary.pyindex c7879e85..13c91780 100644--- a/harness/tests/core/test_addons_boundary.py+++ b/harness/tests/core/test_addons_boundary.py@@ -24,6 +24,6 @@ def test_nothing_outside_the_cli_imports_an_addon() -> None:def test_the_addons_are_the_ones_the_docstring_lists() -> None:- names = sorted(p.name for p in (PKG / "addons").iterdir() if p.is_dir() and p.name != "__pycache__")- assert names == ["dataset", "gallery"]+ names = sorted(p.stem for p in (PKG / "addons").iterdir() if p.name not in {"__init__.py", "__pycache__"})+ assert names == ["calibration", "costreport", "dataset", "gallery", "skill_targets"]assert all(f"``{n}``" in (codeverse.addons.__doc__ or "") for n in names)diff --git a/harness/tests/cost/test_audit_report.py b/harness/tests/cost/test_audit_report.pyindex 88a2d3ad..69c60771 100644--- a/harness/tests/cost/test_audit_report.py+++ b/harness/tests/cost/test_audit_report.py@@ -7,14 +7,14 @@ from pathlib import Pathimport pytest-from codeverse.cost import audit_runs-from codeverse.cost.audit import (+from codeverse.addons.costreport.audit import (+ audit_runs,cached_input_share,price_confidence,stage_latency,uncached_if_no_cache,)-from codeverse.cost.report import console, markdown+from codeverse.addons.costreport.report import console, markdowndef test_audit_of_one_run(fake_run: Path):diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.pyindex eebb8461..5bec5b27 100644--- a/harness/tests/cost/test_instrument.py+++ b/harness/tests/cost/test_instrument.py@@ -310,8 +310,8 @@ def test_a_failed_call_records_its_attempts_but_no_key(tmp_path: Path):def test_per_key_buckets_and_tries_per_call(tmp_path: Path):from types import SimpleNamespace+ from codeverse.addons.costreport.report import BUCKET_HEADERS, bucket_rows, keyed_bucketsfrom codeverse.cost.ledger import record_call, summarise- from codeverse.cost.report import BUCKET_HEADERS, bucket_rows, keyed_bucketsled = tmp_path / "cost.jsonl"rows = [diff --git a/harness/tests/cost/test_live.py b/harness/tests/cost/test_live.pyindex d0909b8d..163b7ae0 100644--- a/harness/tests/cost/test_live.py+++ b/harness/tests/cost/test_live.py@@ -54,7 +54,7 @@ def test_a_metered_run_reconciles_with_its_own_record(tmp_path: Path):from codeverse.cli.main import appfrom codeverse.cost.ledger import load_ledger- from codeverse.flywheel.record import load_record+ from codeverse.record.record import load_recordfrom codeverse.workspace import Workspaceruns = tmp_path / "runs"diff --git a/harness/tests/cost/test_reconstruct.py b/harness/tests/cost/test_reconstruct.pyindex 500f66ee..0efc8c89 100644--- a/harness/tests/cost/test_reconstruct.py+++ b/harness/tests/cost/test_reconstruct.py@@ -7,8 +7,9 @@ from pathlib import Pathimport pytest+from codeverse.addons.costreport.audit import audit_runsfrom codeverse.contracts.common import Usage-from codeverse.cost import audit_runs, find_runs, reconstruct+from codeverse.cost import find_runs, reconstructfrom codeverse.cost.types import Role, Stagediff --git a/harness/tests/flywheel_cli/test_captions.py b/harness/tests/flywheel_cli/test_captions.pyindex 691c7c5f..190edf58 100644--- a/harness/tests/flywheel_cli/test_captions.py+++ b/harness/tests/flywheel_cli/test_captions.py@@ -14,7 +14,7 @@ from codeverse.addons.dataset.captions import ()from codeverse.contracts.chat import ChatRequest, ChatResponse, ImagePartfrom codeverse.contracts.common import Usage-from codeverse.flywheel.record import load_record+from codeverse.record.record import load_recordGOOD = {"detailed": "A four-legged wooden dining chair with a flat square seat and a tall slatted backrest.",diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.pyindex 2ed626ef..ed33a393 100644--- a/harness/tests/flywheel_cli/test_cli.py+++ b/harness/tests/flywheel_cli/test_cli.py@@ -96,11 +96,6 @@ def test_flywheel_commands(runs_dir: Path, tmp_path: Path):assert r.exit_code == 0 and "pairs" in r.outputr = runner.invoke(app, ["flywheel", "index", str(runs_dir), str(tmp_path / "i.sqlite")])assert r.exit_code == 0 and "indexed 3 runs" in r.output- r = runner.invoke(app, ["flywheel", "dedupe", str(out), "--no-mesh"])- assert r.exit_code == 0 and "3 samples" in r.output- r = runner.invoke(app, ["flywheel", "gallery", str(runs_dir), str(tmp_path / "g.html"), "--title", "batch 1"])- assert r.exit_code == 0 and "gallery of 3 runs" in r.output, r.output- assert "batch 1" in (tmp_path / "g.html").read_text()def test_tools_list_handles_an_optional_spatial_install():@@ -233,10 +228,10 @@ def test_calibration_rubric_map_includes_graphics(tmp_path: Path):"""Same default as `3dcode judge`: a graphics round with no stored judgment used to bere-judged with static_object_v1 because calibration kept its own three-trackTRACK_RUBRIC instead of reading TRACK_INFO."""+ from codeverse.addons.calibration import load_run_casesfrom codeverse.contracts.artifacts import RenderSet, RenderViewfrom codeverse.contracts.common import Language, Trackfrom codeverse.contracts.run import RoundRecord- from codeverse.judges.calibration import load_run_casesrun = tmp_path / "shader_run"(run / "rounds").mkdir(parents=True)diff --git a/harness/tests/flywheel_cli/test_code_quality.py b/harness/tests/flywheel_cli/test_code_quality.pydeleted file mode 100644index dceb1d9a..00000000--- a/harness/tests/flywheel_cli/test_code_quality.py+++ /dev/null@@ -1,77 +0,0 @@-"""The delivered code's own vector — see codeverse/flywheel/code_quality.py."""--from __future__ import annotations--from codeverse.flywheel.code_quality import measure--TIDY = '''"""Stool."""-import bpy, bmesh, math-SEAT_D, SEAT_T, SEAT_Z = 0.34, 0.04, 0.45-LEG_R, LEG_N, LEG_RING = 0.02, 3, 0.12--def build_seat():- """Seat disc with its top at SEAT_Z."""- bm = bmesh.new()- bmesh.ops.create_cone(bm, cap_ends=True, segments=48, radius1=SEAT_D / 2, radius2=SEAT_D / 2, depth=SEAT_T)- return bm--def build_leg(i: int):- """One of LEG_N legs on a ring of LEG_RING."""- a = 2 * math.pi * i / LEG_N- return (LEG_RING * math.cos(a), LEG_RING * math.sin(a))--def main():- build_seat()- for i in range(LEG_N):- build_leg(i)-main()-'''--MESSY = '''import bpy, bmesh-def main():- bm = bmesh.new()- bmesh.ops.create_cone(bm, cap_ends=True, segments=48, radius1=0.17, radius2=0.17, depth=0.04)- bmesh.ops.translate(bm, vec=(0, 0, 0.43), verts=bm.verts)- bm2 = bmesh.new()- bmesh.ops.create_cone(bm2, cap_ends=True, segments=24, radius1=0.02, radius2=0.02, depth=0.41)- bmesh.ops.translate(bm2, vec=(0.12, 0, 0.205), verts=bm2.verts)- bm3 = bmesh.new()- bmesh.ops.create_cone(bm3, cap_ends=True, segments=24, radius1=0.02, radius2=0.02, depth=0.41)- bmesh.ops.translate(bm3, vec=(-0.06, 0.104, 0.205), verts=bm3.verts)-def unused_helper(x):- return x * 3.7-main()-'''---def test_named_constants_and_one_function_per_part_score_higher_than_a_script():- tidy, messy = measure({"src/model.py": TIDY}), measure({"src/model.py": MESSY})- assert tidy.index > 0.8 > 0.5 > messy.index, (tidy.index, messy.index)- assert tidy.magic_per_100loc < 10 < messy.magic_per_100loc, "the contract's 'plan numbers = named constants' as a number"- assert tidy.dead_functions == 0 and messy.dead_functions == 1- assert tidy.docstring_cov and tidy.docstring_cov > 0.5- assert tidy.const_names >= 6 and messy.const_names == 0- assert tidy.method == "ast"---def test_the_same_fields_come_back_for_javascript_approximately():- js = '''import * as THREE from 'three';-const SEAT_D = 0.34, SEAT_T = 0.04, LEG_N = 3;-export function buildSeat() { return new THREE.CylinderGeometry(SEAT_D / 2, SEAT_D / 2, SEAT_T, 48); }-export function buildLeg(i) { const a = 2 * Math.PI * i / LEG_N; return [Math.cos(a) * 0.12, Math.sin(a) * 0.12]; }-'''- q = measure({"src/object.js": js})- assert q.method == "tokens" and q.n_functions >= 2 and q.const_names == 3- assert q.docstring_cov is None, "docstrings are a python notion; JS does not fake one"---def test_nothing_parseable_is_none_not_zero():- assert measure({}) is None- assert measure({"src/model.py": "def broken(:\n"}) is None, "a syntax error is 'unmeasured', not 'index 0'"---def test_duplication_sees_copy_paste():- block = " x = build_thing(1.234, 5.678)\n y = other(x, 9.10)\n z = third(y, 2.22)\n w = fourth(z)\n v = fifth(w)\n u = sixth(v)\n"- once = "def a():\n" + block + "def b():\n return 1\n"- twice = "def a():\n" + block + "def b():\n" + block- assert measure({"m.py": twice}).duplication > measure({"m.py": once}).duplicationdiff --git a/harness/tests/flywheel_cli/test_complexity_record.py b/harness/tests/flywheel_cli/test_complexity_record.pyindex 1149011e..7e9a09da 100644--- a/harness/tests/flywheel_cli/test_complexity_record.py+++ b/harness/tests/flywheel_cli/test_complexity_record.py@@ -20,7 +20,7 @@ from codeverse.contracts.common import Backends, Language, Track, Usagefrom codeverse.contracts.plan import BBox, PartPlan, StaticPlanfrom codeverse.contracts.run import RoundRecord, RunRecord, RunStatusfrom codeverse.contracts.spec import Spec-from codeverse.flywheel.record import complexity_block, fill_derived, round_summary+from codeverse.record.record import complexity_block, fill_derived, round_summaryREPO = Path(__file__).resolve().parents[2]diff --git a/harness/tests/flywheel_cli/test_flywheel.py b/harness/tests/flywheel_cli/test_flywheel.pyindex 4f13ce4d..79f003fd 100644--- a/harness/tests/flywheel_cli/test_flywheel.py+++ b/harness/tests/flywheel_cli/test_flywheel.py@@ -14,16 +14,13 @@ from codeverse.addons.dataset.export import export_samplesfrom codeverse.addons.dataset.index import build_index, summaryfrom codeverse.addons.dataset.pack import pack_samples, verify_locatorsfrom codeverse.addons.dataset.pairs import build_pairs-from codeverse.contracts.run import RunRecord-from codeverse.flywheel import _git-from codeverse.flywheel.quality import (- DedupeItem,- MeshFingerprint,+from codeverse.addons.dataset.quality import (code_fingerprint,- near_duplicates,normalise_code,)-from codeverse.flywheel.record import (+from codeverse.contracts.run import RunRecord+from codeverse.record import _git+from codeverse.record.record import (RecordError,best_round_index,finalize_record,@@ -120,7 +117,7 @@ def test_a_symlink_is_not_exported_as_a_file_of_its_target(fake_run) -> None:as a blob whose content IS the link target, so ``src/link.py -> model.py`` came backas a one-line file saying ``model.py`` — and with ``--with-code`` that goes into atraining sample."""- from codeverse.flywheel._git import read_tree_at+ from codeverse.record._git import read_tree_atws, _rec = fake_run(ws.src / "model.py").write_text("import bpy\n")@@ -273,29 +270,6 @@ def test_code_fingerprint_normalises():assert normalise_code("// a\nlet x = 1; // t\n") == "letx=1;"-def test_near_duplicates_groups():- fa = MeshFingerprint(extents_cm=(100, 50, 40), tri_count=1000, tri_bucket=9, voxels=list(range(100)), digest="a")- fb = MeshFingerprint(extents_cm=(102, 50, 40), tri_count=1200, tri_bucket=10, voxels=list(range(95)), digest="b")- fc = MeshFingerprint(extents_cm=(100, 50, 40), tri_count=1000, tri_bucket=9, voxels=list(range(50, 150)), digest="c")- items = [DedupeItem(id="a", code_fp="x", mesh_fp=fa), DedupeItem(id="b", code_fp="y", mesh_fp=fb),- DedupeItem(id="c", code_fp="z", mesh_fp=fc), DedupeItem(id="d", code_fp="x")]- assert near_duplicates(items) == [["a", "b", "d"]]---def test_mesh_fingerprint_real_glb(tmp_path: Path):- trimesh = pytest.importorskip("trimesh")- from codeverse.flywheel.quality import mesh_fingerprint-- box = trimesh.creation.box(extents=(1.0, 0.5, 0.25))- p = tmp_path / "box.glb"- box.export(p)- fp = mesh_fingerprint(p)- assert fp.tri_count == 12 and fp.voxels- assert sorted(fp.extents_cm) == [25, 50, 100]- assert fp.jaccard(mesh_fingerprint(p)) == 1.0- assert fp.jaccard(mesh_fingerprint(p, seed=7)) > 0.9--# --------------------------------------------------------------------------- index@@ -371,7 +345,7 @@ def _degrade(judgment):def test_degraded_round_is_not_a_zero_score(tmp_path: Path):from codeverse.addons.dataset.pairs import preference_pairs- from codeverse.flywheel.record import effective_judgment, effective_score, round_summary+ from codeverse.record.record import effective_judgment, effective_score, round_summaryfrom tests.flywheel_cli.conftest import make_fake_runws, rec = make_fake_run(tmp_path / "runs", scores=(0.62, 0.64))@@ -456,7 +430,7 @@ def test_export_includes_textured_assets_when_shipped(fake_run, tmp_path: Path):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.addons.gallery.index import scan_root- from codeverse.flywheel.record import find_run_dirs, iter_runs+ from codeverse.record.record import find_run_dirs, iter_runsbattery = tmp_path / "static_v2_flash" # run_bench: runs/<id>(battery / "runs" / "some_run").mkdir(parents=True)@@ -486,7 +460,7 @@ def test_battery_layouts_are_discovered_by_flywheel_and_gallery(tmp_path):def test_empty_run_roots_distinguish_a_failed_battery_from_legitimate_empty_input(tmp_path):- from codeverse.flywheel.record import iter_runs+ from codeverse.record.record import iter_runsbattery = tmp_path / "compare_empty"(battery / "cells" / "cmp_med_chair").mkdir(parents=True)diff --git a/harness/tests/flywheel_cli/test_quality_gallery.py b/harness/tests/flywheel_cli/test_quality_gallery.pyindex aec856f0..a8c5fd46 100644--- a/harness/tests/flywheel_cli/test_quality_gallery.py+++ b/harness/tests/flywheel_cli/test_quality_gallery.py@@ -7,9 +7,14 @@ from pathlib import Pathfrom codeverse.addons.dataset.captions import caption_samplefrom codeverse.addons.dataset.export import export_samples, load_captions+from codeverse.addons.dataset.quality import (+ find_duplicates,+ mark_duplicates,+ prompt_hash,+ quality_tier,+)from codeverse.contracts.common import Language-from codeverse.flywheel.quality import find_duplicates, mark_duplicates, prompt_hash, quality_tier-from codeverse.flywheel.record import load_record+from codeverse.record.record import load_recordfrom tests.flywheel_cli.conftest import make_fake_runfrom tests.flywheel_cli.test_captions import GOOD, FakeModeldiff --git a/harness/tests/flywheel_cli/test_record_env.py b/harness/tests/flywheel_cli/test_record_env.pyindex e9d57bfb..fb142743 100644--- a/harness/tests/flywheel_cli/test_record_env.py+++ b/harness/tests/flywheel_cli/test_record_env.py@@ -7,8 +7,8 @@ from pathlib import Pathimport pytest-from codeverse.flywheel import record as record_mod-from codeverse.flywheel.record import _harness_git_sha, environment_versions+from codeverse.record import record as record_mod+from codeverse.record.record import _harness_git_sha, environment_versionsSHA_RE = re.compile(r"^[0-9a-f]{40}(-dirty)?$")@@ -34,7 +34,7 @@ def test_harness_git_sha_from_a_tracked_file_and_dirty_marker(tmp_path):if shutil.which("git") is None:pytest.skip("git not installed")repo = tmp_path / "repo"- pkg = repo / "harness" / "codeverse" / "flywheel"+ pkg = repo / "harness" / "codeverse" / "record"pkg.mkdir(parents=True)mod = pkg / "record.py"mod.write_text("# tracked\n")@@ -68,7 +68,7 @@ def test_harness_git_sha_is_empty_for_an_untracked_copy(tmp_path):(repo / "tracked.txt").write_text("x")_git("-c", "user.email=t@t", "-c", "user.name=t", "add", "-A", cwd=repo)_git("-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "-m", "init", cwd=repo)- copy = repo / ".venv" / "lib" / "codeverse" / "flywheel" / "record.py"+ copy = repo / ".venv" / "lib" / "codeverse" / "record" / "record.py"copy.parent.mkdir(parents=True)copy.write_text("# untracked copy\n")assert _harness_git_sha(copy) == ""diff --git a/harness/tests/flywheel_cli/test_refine.py b/harness/tests/flywheel_cli/test_refine.pyindex 6fc99f2d..b4a0a0e5 100644--- a/harness/tests/flywheel_cli/test_refine.py+++ b/harness/tests/flywheel_cli/test_refine.py@@ -10,7 +10,7 @@ import pytestfrom codeverse.addons.dataset.pairs import MIN_PREFERENCE_DELTAfrom codeverse.addons.dataset.refine import build_refine, outcome_of, transitionsfrom codeverse.contracts.artifacts import GateFinding, GateReport, Severity-from codeverse.flywheel.record import load_record+from codeverse.record.record import load_recordfrom tests.flywheel_cli.conftest import make_fake_rundiff --git a/harness/tests/flywheel_cli/test_run_identity.py b/harness/tests/flywheel_cli/test_run_identity.pyindex 514a37b4..277bbda6 100644--- a/harness/tests/flywheel_cli/test_run_identity.py+++ b/harness/tests/flywheel_cli/test_run_identity.py@@ -18,9 +18,9 @@ import pytestfrom codeverse.addons.dataset.export import export_samples, load_captionsfrom codeverse.addons.dataset.index import build_index as build_sqlite_indexfrom codeverse.addons.dataset.pairs import build_pairs+from codeverse.addons.dataset.sample import SampleErrorfrom codeverse.contracts.run import RunId-from codeverse.flywheel.record import FoundRun, battery_label, iter_runs, run_id_for, unique_files-from codeverse.flywheel.sample import SampleError+from codeverse.record.record import FoundRun, battery_label, iter_runs, run_id_for, unique_filesfrom tests.flywheel_cli.conftest import make_fake_rundiff --git a/harness/tests/flywheel_cli/test_run_layout_cli.py b/harness/tests/flywheel_cli/test_run_layout_cli.pyindex c9fe90d4..385dd54b 100644--- a/harness/tests/flywheel_cli/test_run_layout_cli.py+++ b/harness/tests/flywheel_cli/test_run_layout_cli.py@@ -14,9 +14,9 @@ from codeverse.addons.gallery import build_staticfrom codeverse.addons.gallery.index import entry_from_recordfrom codeverse.cli.main import appfrom codeverse.contracts.run import RunRecord-from codeverse.flywheel.deliverable import build_deliverable, deliverable_path, load_deliverable-from codeverse.flywheel.record import load_record, package_run-from codeverse.flywheel.telemetry import (+from codeverse.record.deliverable import build_deliverable, deliverable_path, load_deliverable+from codeverse.record.record import load_record, package_run+from codeverse.record.telemetry import (build_telemetry,ledger_rows,live_ledger_path,@@ -127,7 +127,7 @@ def test_telemetry_handles_reconstructed_live_and_unavailable_ledgers(fake_run,assert tele.cost is not None and tele.cost.by_stage[0].stage == "plan"# A core-only install still emits settings and the record-level total.- import codeverse.flywheel.telemetry as T+ import codeverse.record.telemetry as Tdef boom(*_a, **_k):raise ImportError("codeverse.cost is not installed")diff --git a/harness/tests/gallery/test_cli.py b/harness/tests/gallery/test_cli.pyindex 879f705d..1e061a93 100644--- a/harness/tests/gallery/test_cli.py+++ b/harness/tests/gallery/test_cli.py@@ -1,4 +1,4 @@-"""``3dcode gallery build|serve`` and the ``3dcode flywheel gallery`` alias."""+"""``3dcode gallery build|serve``."""from __future__ import annotations@@ -47,16 +47,6 @@ def test_build_rejects_a_missing_root(tmp_path: Path):assert r.exit_code != 0 and "not a directory" in r.output-def test_flywheel_gallery_alias_still_works(gallery_tree: dict[str, Path], tmp_path: Path):- out = tmp_path / "alias.html"- r = runner.invoke(app, ["flywheel", "gallery", str(gallery_tree["runs"]), str(out), "--title", "batch 1"])- assert r.exit_code == 0, r.output- assert "gallery of 2 runs" in r.output- markup = out.read_text()- assert "batch 1" in markup- assert "data:image/jpeg;base64," in markup # the alias keeps the old self-contained behaviour--def test_default_roots_from_cwd(gallery_tree: dict[str, Path], monkeypatch: pytest.MonkeyPatch):monkeypatch.chdir(gallery_tree["root"])roots = resolve_roots(None)diff --git a/harness/tests/gallery/test_index.py b/harness/tests/gallery/test_index.pyindex f314ca2f..b1b34ab8 100644--- a/harness/tests/gallery/test_index.py+++ b/harness/tests/gallery/test_index.py@@ -7,7 +7,7 @@ from pathlib import Pathfrom codeverse.addons.gallery.index import build_index, default_roots, entry_for_dirfrom codeverse.addons.gallery.model import match, sort_entries, summarize-from codeverse.flywheel.record import battery_label+from codeverse.record.record import battery_labeldef test_build_index_sections_and_states(gallery_tree: dict[str, Path]):diff --git a/harness/tests/judges/test_calibration.py b/harness/tests/judges/test_calibration.pyindex fdf4c046..ff6457f9 100644--- a/harness/tests/judges/test_calibration.py+++ b/harness/tests/judges/test_calibration.py@@ -3,10 +3,10 @@ from pathlib import Pathimport pytest+from codeverse.addons.calibration import calibrate, load_run_cases, pearson, spearmanfrom codeverse.contracts.artifacts import GateFinding, GateReport, Severityfrom codeverse.contracts.run import RoundRecordfrom codeverse.judges.base import plan_digest-from codeverse.judges.calibration import calibrate, load_run_cases, pearson, spearmanfrom codeverse.judges.rubrics import load_rubricfrom tests.judges.conftest import (ACCEPTANCE,@@ -90,7 +90,7 @@ def test_run_labels_stay_distinct_across_battery_layouts():"""Bench cells all end in .../run: compare_backends cells for DIFFERENT prompts(and ab_plan's control vs treatment arms) used to collapse to one label, sotheir judgment sidecars overwrote each other (V9c)."""- from codeverse.judges.calibration import _run_label+ from codeverse.addons.calibration import _run_label# compare_backends: <battery>/cells/<prompt>/<arm>/runa = _run_label(Path("/bench/out/compare_v1/cells/chair/harness-gemini/run"))diff --git a/harness/tests/skills/test_freshness.py b/harness/tests/skills/test_freshness.pyindex d855a0b7..40983c56 100644--- a/harness/tests/skills/test_freshness.py+++ b/harness/tests/skills/test_freshness.py@@ -234,7 +234,7 @@ def test_every_named_cookbook_section_exists():def test_every_live_constant_named_by_a_skill_has_a_claim():- from codeverse.skills.targets import load_claims+ from codeverse.addons.skill_targets import load_claimsfor s in SKILLS:pinned = {diff --git a/harness/tests/skills/test_library.py b/harness/tests/skills/test_library.pyindex c7d56156..af5b3d64 100644--- a/harness/tests/skills/test_library.py+++ b/harness/tests/skills/test_library.py@@ -8,9 +8,9 @@ from collections import defaultdictimport pytest+from codeverse.addons.skill_targets import check_claims, claim_bases, load_claimsfrom codeverse.skills import bundle_dirs, iter_skills, skills_dir, validate_bundlefrom codeverse.skills.registry import ROUTES-from codeverse.skills.targets import check_claims, claim_bases, load_claimsBUNDLES = bundle_dirs()SKILLS = list(iter_skills()) if BUNDLES else []diff --git a/harness/tests/skills/test_targets.py b/harness/tests/skills/test_targets.pyindex 6ff9223f..794d0c1f 100644--- a/harness/tests/skills/test_targets.py+++ b/harness/tests/skills/test_targets.py@@ -9,9 +9,7 @@ from pathlib import Pathimport pytestimport yaml-from codeverse.skills import bundle_dirs, skills_dir-from codeverse.skills.registry import ROUTED_SKILLS, finding_kind-from codeverse.skills.targets import (+from codeverse.addons.skill_targets import (BY_SKILL,DIRECTIONS,METRICS,@@ -21,6 +19,8 @@ from codeverse.skills.targets import (gate_kinds_claimed,target_for,)+from codeverse.skills import bundle_dirs, skills_dir+from codeverse.skills.registry import ROUTED_SKILLS, finding_kindBUNDLES = bundle_dirs()pytestmark = pytest.mark.skipif(not BUNDLES, reason=f"no bundles in {skills_dir()} yet")