Skip to content

Official Codebase of 3DCodeVerse

Python

gallery/cli/flywheel: seven satellite files fold into their only consumers

gaoypengb7d7665d21a6
diff --git a/harness/codeverse/cli/_common.py b/harness/codeverse/cli/_common.py
index 0d373991..8d8672d7 100644
--- a/harness/codeverse/cli/_common.py
+++ b/harness/codeverse/cli/_common.py
@@ -1,5 +1,4 @@
-"""Shared CLI plumbing: lazy imports (sub-packages may be incomplete), workspace
-resolution, slug building, typed exits. Keeps ``main.py`` thin."""
+"""Rich formatting for the CLI: run summaries, tables, observations, doctor rows."""
from __future__ import annotations
@@ -14,13 +13,117 @@ from pathlib import Path
from typing import Any
import typer
+from rich.console import Console
+from rich.panel import Panel
+from rich.table import Table
-from codeverse.cli._fmt import err
from codeverse.config import get_settings
+from codeverse.contracts.run import RunRecord
from codeverse.contracts.spec import Spec
from codeverse.conventions import slugify
from codeverse.workspace import Workspace
+console = Console(emoji=False)
+err_console = Console(stderr=True, style="bold red", emoji=False)
+
+
+def err(msg: str) -> None:
+ err_console.print(f"error: {msg}")
+
+
+def ok(msg: str) -> None:
+ console.print(f"[green]{msg}[/green]")
+
+
+def warn(msg: str) -> None:
+ console.print(f"[yellow]{msg}[/yellow]")
+
+
+def fmt_score(s: float | None) -> str:
+ return "-" if s is None else f"{s:.3f}"
+
+
+def fmt_usd(v: float) -> str:
+ return f"${v:.4f}"
+
+
+def rounds_table(record: RunRecord) -> Table:
+ t = Table(title="rounds (* = best)", show_lines=False)
+ for col in ("#", "kind", "build", "gate err", "score", "passed", "cost", "secs", "commit"):
+ t.add_column(col, justify="right" if col in ("#", "gate err", "score", "cost", "secs") else "left")
+ for r in record.rounds:
+ build = "-" if r.build is None else ("ok" if r.build.ok else "[red]FAIL[/red]")
+ j = r.judgment
+ passed = "-" if j is None else ("[green]yes[/green]" if j.passed else "no")
+ best = "*" if record.best_round is not None and r.index == record.best_round else ""
+ t.add_row(f"{r.index}{best}", r.kind, build, str(sum(len(g.errors) for g in r.gates)), fmt_score(r.score),
+ passed, fmt_usd(r.usage.cost_usd), f"{r.duration_s:.0f}", r.commit[:8])
+ return t
+
+
+def print_record_summary(record: RunRecord, ws_root: Path | None = None) -> None:
+ spec = record.spec
+ status_col = {"passed": "green", "failed": "red", "budget": "yellow", "plateau": "yellow"}.get(record.status.value, "cyan")
+ lines = [
+ f"[bold]{spec.prompt}[/bold]",
+ f"track={spec.track.value} language={spec.language.value} generator={spec.backends.generator}",
+ f"status=[{status_col}]{record.status.value}[/{status_col}] baseline={fmt_score(record.baseline_score)} "
+ f"best={fmt_score(record.final_score)} (round {record.best_round}) rounds={len(record.rounds)} "
+ f"cost={fmt_usd(record.total_usage.cost_usd)}",
+ ]
+ if record.error:
+ lines.append(f"[red]error: {record.error}[/red]")
+ if ws_root is not None:
+ lines.append(f"workspace: {ws_root}")
+ best = next((r for r in record.rounds if r.index == record.best_round), None)
+ if best is not None and best.renders is not None and best.renders.contact_sheet:
+ # rebase, never print the stored string: record.json holds the ABSOLUTE path
+ # of the host that produced the run, so a moved/archived run printed a sheet
+ # that does not exist while the real one sat under this root.
+ lines.append(f"sheet: {Workspace(ws_root).rebase(best.renders.contact_sheet)}")
+ glb = ws_root / "artifacts" / "object.glb"
+ if glb.is_file():
+ lines.append(f"glb: {glb}")
+ console.print(Panel("\n".join(lines), title="run", expand=False))
+ if record.rounds:
+ console.print(rounds_table(record))
+
+
+def kv_table(title: str, rows: dict[str, Any]) -> Table:
+ t = Table(title=title, show_header=False)
+ t.add_column("key", style="bold")
+ t.add_column("value")
+ for k, v in rows.items():
+ t.add_row(str(k), str(v))
+ return t
+
+
+def print_observation(obs: Any, *, as_json: bool) -> None:
+ if as_json:
+ console.print_json(obs.model_dump_json())
+ return
+ style = "green" if obs.ok else "red"
+ console.print(Panel(obs.text, title=f"[{style}]{'ok' if obs.ok else 'error'}[/{style}] ({obs.duration_ms} ms)", expand=False))
+ if obs.numbers:
+ console.print(kv_table("numbers", obs.numbers))
+ for img in obs.images:
+ console.print(f"image: {img}")
+
+
+def doctor_table(rows: list[tuple[str, str, str]]) -> Table:
+ """rows: (check, status OK|WARN|FAIL, detail)."""
+ t = Table(title="3dcv doctor")
+ t.add_column("check", style="bold")
+ t.add_column("status")
+ t.add_column("detail")
+ col = {"OK": "green", "WARN": "yellow", "FAIL": "red", "SKIP": "dim"}
+ for name, status, detail in rows:
+ t.add_row(name, f"[{col.get(status, 'white')}]{status}[/{col.get(status, 'white')}]", detail)
+ return t
+
+
+# ===================================================================== _common
+# (merged from codeverse/cli/_common.py, 2026-08-28)
REPO_ROOT = Path(__file__).resolve().parents[2]
diff --git a/harness/codeverse/cli/_fmt.py b/harness/codeverse/cli/_fmt.py
deleted file mode 100644
index 0be21082..00000000
--- a/harness/codeverse/cli/_fmt.py
+++ /dev/null
@@ -1,111 +0,0 @@
-"""Rich formatting for the CLI: run summaries, tables, observations, doctor rows."""
-
-from __future__ import annotations
-
-from pathlib import Path
-from typing import Any
-
-from rich.console import Console
-from rich.panel import Panel
-from rich.table import Table
-
-from codeverse.contracts.run import RunRecord
-from codeverse.workspace import Workspace
-
-console = Console(emoji=False)
-err_console = Console(stderr=True, style="bold red", emoji=False)
-
-
-def err(msg: str) -> None:
- err_console.print(f"error: {msg}")
-
-
-def ok(msg: str) -> None:
- console.print(f"[green]{msg}[/green]")
-
-
-def warn(msg: str) -> None:
- console.print(f"[yellow]{msg}[/yellow]")
-
-
-def fmt_score(s: float | None) -> str:
- return "-" if s is None else f"{s:.3f}"
-
-
-def fmt_usd(v: float) -> str:
- return f"${v:.4f}"
-
-
-def rounds_table(record: RunRecord) -> Table:
- t = Table(title="rounds (* = best)", show_lines=False)
- for col in ("#", "kind", "build", "gate err", "score", "passed", "cost", "secs", "commit"):
- t.add_column(col, justify="right" if col in ("#", "gate err", "score", "cost", "secs") else "left")
- for r in record.rounds:
- build = "-" if r.build is None else ("ok" if r.build.ok else "[red]FAIL[/red]")
- j = r.judgment
- passed = "-" if j is None else ("[green]yes[/green]" if j.passed else "no")
- best = "*" if record.best_round is not None and r.index == record.best_round else ""
- t.add_row(f"{r.index}{best}", r.kind, build, str(sum(len(g.errors) for g in r.gates)), fmt_score(r.score),
- passed, fmt_usd(r.usage.cost_usd), f"{r.duration_s:.0f}", r.commit[:8])
- return t
-
-
-def print_record_summary(record: RunRecord, ws_root: Path | None = None) -> None:
- spec = record.spec
- status_col = {"passed": "green", "failed": "red", "budget": "yellow", "plateau": "yellow"}.get(record.status.value, "cyan")
- lines = [
- f"[bold]{spec.prompt}[/bold]",
- f"track={spec.track.value} language={spec.language.value} generator={spec.backends.generator}",
- f"status=[{status_col}]{record.status.value}[/{status_col}] baseline={fmt_score(record.baseline_score)} "
- f"best={fmt_score(record.final_score)} (round {record.best_round}) rounds={len(record.rounds)} "
- f"cost={fmt_usd(record.total_usage.cost_usd)}",
- ]
- if record.error:
- lines.append(f"[red]error: {record.error}[/red]")
- if ws_root is not None:
- lines.append(f"workspace: {ws_root}")
- best = next((r for r in record.rounds if r.index == record.best_round), None)
- if best is not None and best.renders is not None and best.renders.contact_sheet:
- # rebase, never print the stored string: record.json holds the ABSOLUTE path
- # of the host that produced the run, so a moved/archived run printed a sheet
- # that does not exist while the real one sat under this root.
- lines.append(f"sheet: {Workspace(ws_root).rebase(best.renders.contact_sheet)}")
- glb = ws_root / "artifacts" / "object.glb"
- if glb.is_file():
- lines.append(f"glb: {glb}")
- console.print(Panel("\n".join(lines), title="run", expand=False))
- if record.rounds:
- console.print(rounds_table(record))
-
-
-def kv_table(title: str, rows: dict[str, Any]) -> Table:
- t = Table(title=title, show_header=False)
- t.add_column("key", style="bold")
- t.add_column("value")
- for k, v in rows.items():
- t.add_row(str(k), str(v))
- return t
-
-
-def print_observation(obs: Any, *, as_json: bool) -> None:
- if as_json:
- console.print_json(obs.model_dump_json())
- return
- style = "green" if obs.ok else "red"
- console.print(Panel(obs.text, title=f"[{style}]{'ok' if obs.ok else 'error'}[/{style}] ({obs.duration_ms} ms)", expand=False))
- if obs.numbers:
- console.print(kv_table("numbers", obs.numbers))
- for img in obs.images:
- console.print(f"image: {img}")
-
-
-def doctor_table(rows: list[tuple[str, str, str]]) -> Table:
- """rows: (check, status OK|WARN|FAIL, detail)."""
- t = Table(title="3dcv doctor")
- t.add_column("check", style="bold")
- t.add_column("status")
- t.add_column("detail")
- col = {"OK": "green", "WARN": "yellow", "FAIL": "red", "SKIP": "dim"}
- for name, status, detail in rows:
- t.add_row(name, f"[{col.get(status, 'white')}]{status}[/{col.get(status, 'white')}]", detail)
- return t
diff --git a/harness/codeverse/cli/bench_cmd.py b/harness/codeverse/cli/bench_cmd.py
index ab7656b7..d86f1542 100644
--- a/harness/codeverse/cli/bench_cmd.py
+++ b/harness/codeverse/cli/bench_cmd.py
@@ -8,7 +8,7 @@ from typing import Annotated
import typer
from codeverse.cli import _common as C
-from codeverse.cli._fmt import console, ok
+from codeverse.cli._common import console, ok
bench_app = typer.Typer(no_args_is_help=True)
diff --git a/harness/codeverse/cli/cost_cmd.py b/harness/codeverse/cli/cost_cmd.py
index d5e8620d..33945bc6 100644
--- a/harness/codeverse/cli/cost_cmd.py
+++ b/harness/codeverse/cli/cost_cmd.py
@@ -24,7 +24,7 @@ import click
import typer
from typer.core import TyperGroup
-from codeverse.cli._fmt import console, ok, warn
+from codeverse.cli._common import console, ok, warn
#: a price row older than this needs re-checking against the provider's page
STALE_AFTER_DAYS = 90
@@ -117,7 +117,7 @@ def _report(paths: list[Path], *, md: Path | None, recheck: bool, limit: int, pe
def _single_run_lines(run: object) -> None:
"""Reconciliation for one run: the ledger against what the record was billed."""
- from codeverse.cli._fmt import kv_table
+ from codeverse.cli._common import kv_table
ledger = float(getattr(run, "ledger_usd", 0.0))
recorded = float(getattr(run, "recorded_usd", 0.0))
diff --git a/harness/codeverse/cli/doctor.py b/harness/codeverse/cli/doctor.py
index c48b8920..41c734cc 100644
--- a/harness/codeverse/cli/doctor.py
+++ b/harness/codeverse/cli/doctor.py
@@ -11,7 +11,7 @@ from typing import Annotated
import typer
-from codeverse.cli._fmt import console, doctor_table
+from codeverse.cli._common import console, doctor_table
from codeverse.config import get_settings
doctor_app = typer.Typer(invoke_without_command=True)
diff --git a/harness/codeverse/cli/flywheel_cmd.py b/harness/codeverse/cli/flywheel_cmd.py
index ac4a180c..752990ed 100644
--- a/harness/codeverse/cli/flywheel_cmd.py
+++ b/harness/codeverse/cli/flywheel_cmd.py
@@ -10,7 +10,7 @@ import typer
from rich.markup import escape
from codeverse.cli import _common as C
-from codeverse.cli._fmt import console, kv_table, ok, warn
+from codeverse.cli._common import console, kv_table, ok, warn
flywheel_app = typer.Typer(no_args_is_help=True)
@@ -156,7 +156,7 @@ def dedupe_cmd(
"""Report near-duplicate sample groups (code fingerprint + mesh voxel Jaccard)."""
import json
- from codeverse.flywheel.dedupe import (
+ from codeverse.flywheel.quality import (
DedupeItem,
code_fingerprint,
mesh_fingerprint,
@@ -193,7 +193,7 @@ def gallery_cmd(
embed: Annotated[bool, typer.Option("--embed/--no-embed", help="inline the contact sheets as data: URIs")] = True,
) -> None:
"""Alias of `3dcv gallery build` (kept for scripts): one self-contained HTML page."""
- from codeverse.gallery.static_site import build_static
+ from codeverse.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)")
diff --git a/harness/codeverse/cli/gallery_cmd.py b/harness/codeverse/cli/gallery_cmd.py
index c3c26430..81c29793 100644
--- a/harness/codeverse/cli/gallery_cmd.py
+++ b/harness/codeverse/cli/gallery_cmd.py
@@ -14,7 +14,7 @@ from typing import Annotated
import typer
from codeverse.cli import _common as C
-from codeverse.cli._fmt import console, kv_table, ok, warn
+from codeverse.cli._common import console, kv_table, ok, warn
gallery_app = typer.Typer(no_args_is_help=True)
@@ -85,7 +85,7 @@ def build_cmd(
thumb_px: Annotated[int, typer.Option("--thumb-px", min=128, help="embedded thumbnail long edge")] = 720,
) -> None:
"""Write the gallery as one self-contained HTML file."""
- from codeverse.gallery.static_site import build_static
+ from codeverse.gallery.page import build_static
path, n, index = build_static(resolve_roots(roots), out, title=title, embed=embed, thumb_px=thumb_px)
broken = sum(1 for e in index.entries() if e.state != "ok")
diff --git a/harness/codeverse/cli/inspect_cmd.py b/harness/codeverse/cli/inspect_cmd.py
index 4f15a319..d15f2578 100644
--- a/harness/codeverse/cli/inspect_cmd.py
+++ b/harness/codeverse/cli/inspect_cmd.py
@@ -19,7 +19,7 @@ from typing import Annotated
import typer
from codeverse.cli import _common as C
-from codeverse.cli._fmt import console, kv_table, print_record_summary, warn
+from codeverse.cli._common import console, kv_table, print_record_summary, warn
from codeverse.config import get_settings
from codeverse.contracts.common import Track
from codeverse.contracts.spec import Spec
diff --git a/harness/codeverse/cli/layout_cmd.py b/harness/codeverse/cli/layout_cmd.py
index 2d14eac7..f24687b0 100644
--- a/harness/codeverse/cli/layout_cmd.py
+++ b/harness/codeverse/cli/layout_cmd.py
@@ -20,7 +20,7 @@ import typer
from rich.table import Table
from codeverse.cli import _common as C
-from codeverse.cli._fmt import console, fmt_score, fmt_usd, kv_table, ok, warn
+from codeverse.cli._common import console, fmt_score, fmt_usd, kv_table, ok, warn
from codeverse.contracts.run import (
CostSummary,
DeliverableFile,
diff --git a/harness/codeverse/cli/main.py b/harness/codeverse/cli/main.py
index cd190b84..71c1ad3a 100644
--- a/harness/codeverse/cli/main.py
+++ b/harness/codeverse/cli/main.py
@@ -22,7 +22,7 @@ import typer
from codeverse import __version__
from codeverse.cli import _common as C
-from codeverse.cli._fmt import console, err_console, kv_table, ok, print_record_summary, warn
+from codeverse.cli._common import console, err_console, kv_table, ok, print_record_summary, warn
from codeverse.cli.bench_cmd import bench_app
from codeverse.cli.cost_cmd import cost_app
from codeverse.cli.doctor import doctor_app
diff --git a/harness/codeverse/cli/skills_cmd.py b/harness/codeverse/cli/skills_cmd.py
index 12d76e48..100e109a 100644
--- a/harness/codeverse/cli/skills_cmd.py
+++ b/harness/codeverse/cli/skills_cmd.py
@@ -15,7 +15,7 @@ from typing import Annotated
import typer
-from codeverse.cli._fmt import console, err_console
+from codeverse.cli._common import console, err_console
from codeverse.proc import read_jsonl_lenient
skills_app = typer.Typer(invoke_without_command=True, help="The skill library: list / show / validate / read-rate report.")
diff --git a/harness/codeverse/cli/texture_cmd.py b/harness/codeverse/cli/texture_cmd.py
index d9e26f53..8a2bebf4 100644
--- a/harness/codeverse/cli/texture_cmd.py
+++ b/harness/codeverse/cli/texture_cmd.py
@@ -13,7 +13,7 @@ from typing import Annotated
import typer
from codeverse.cli import _common as C
-from codeverse.cli._fmt import console, kv_table, warn
+from codeverse.cli._common import console, kv_table, warn
from codeverse.contracts.common import Track
texture_app = typer.Typer(name="texture", help="Text-to-image texturing: object pass + scene texture pack.",
diff --git a/harness/codeverse/cli/tools_cmd.py b/harness/codeverse/cli/tools_cmd.py
index 437e3351..031676fe 100644
--- a/harness/codeverse/cli/tools_cmd.py
+++ b/harness/codeverse/cli/tools_cmd.py
@@ -13,7 +13,7 @@ from typing import Annotated
import typer
from codeverse.cli import _common as C
-from codeverse.cli._fmt import console, print_observation
+from codeverse.cli._common import console, print_observation
def tools(
diff --git a/harness/codeverse/flywheel/dedupe.py b/harness/codeverse/flywheel/dedupe.py
deleted file mode 100644
index 898463eb..00000000
--- a/harness/codeverse/flywheel/dedupe.py
+++ /dev/null
@@ -1,158 +0,0 @@
-"""Near-duplicate detection: code fingerprints + coarse mesh fingerprints.
-
-* ``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 annotations
-
-import hashlib
-import math
-import re
-from collections.abc import Iterable, Mapping
-from pathlib import Path
-
-import numpy as np
-from pydantic import BaseModel, Field
-
-_COMMENT = re.compile(r"^\s*(#|//|\*|/\*).*$")
-_TRAILING_COMMENT = re.compile(r"\s+(#|//).*$")
-VOXEL_RES = 16
-
-
-def normalise_code(text: str) -> str:
- """Drop comment-only lines, trailing comments, blank lines and all whitespace."""
- out = []
- for line in text.splitlines():
- if _COMMENT.match(line):
- continue
- line = _TRAILING_COMMENT.sub("", line)
- line = re.sub(r"\s+", "", line)
- if line:
- out.append(line)
- return "\n".join(out)
-
-
-def code_fingerprint(files: Mapping[str, str | bytes]) -> str:
- """Order-independent sha256 over ``(path, normalised code)`` pairs."""
- h = hashlib.sha256()
- for path in sorted(files):
- data = files[path]
- text = data.decode("utf-8", errors="replace") if isinstance(data, bytes) else data
- h.update(path.encode())
- h.update(b"\0")
- h.update(normalise_code(text).encode())
- h.update(b"\0")
- return h.hexdigest()
-
-
-def code_sha256(files: Mapping[str, str | bytes]) -> str:
- """Order-independent sha256 over the RAW ``(path, bytes)`` pairs — the
- exact-content counterpart of :func:`code_fingerprint` (no normalisation,
- no lossy decode)."""
- h = hashlib.sha256()
- for path in sorted(files):
- data = files[path]
- raw = data.encode("utf-8") if isinstance(data, str) else data
- h.update(path.encode())
- h.update(b"\0")
- h.update(raw)
- h.update(b"\0")
- return h.hexdigest()
-
-
-class MeshFingerprint(BaseModel):
- extents_cm: tuple[int, int, int]
- tri_count: int
- tri_bucket: int = Field(description="log2 bucket of the triangle count")
- voxels: list[int] = Field(description="occupied cell indices in a VOXEL_RES³ grid over the bbox")
- digest: str
-
- def jaccard(self, other: MeshFingerprint) -> float:
- a, b = set(self.voxels), set(other.voxels)
- if not a and not b:
- return 1.0
- return len(a & b) / len(a | b)
-
- def extents_compatible(self, other: MeshFingerprint, tol: float = 0.1) -> bool:
- for x, y in zip(self.extents_cm, other.extents_cm, strict=True):
- if max(x, y) == 0:
- continue
- if abs(x - y) / max(x, y) > tol:
- return False
- return True
-
-
-def mesh_fingerprint(glb: Path | str, *, res: int = VOXEL_RES, samples: int = 50_000, seed: int = 0) -> MeshFingerprint:
- """Coarse, pose-sensitive shape fingerprint of a GLB (seeded surface samples → voxel grid).
-
- Deterministic for identical geometry; near-identical meshes give Jaccard ≈ 1."""
- import trimesh
-
- loaded = trimesh.load(str(glb), force="scene")
- mesh = loaded.to_mesh() if isinstance(loaded, trimesh.Scene) else loaded
- if mesh is None or mesh.is_empty or len(mesh.faces) == 0:
- raise ValueError(f"mesh_fingerprint: no triangles in {glb}")
- ext = mesh.bounding_box.extents
- pts, _ = trimesh.sample.sample_surface(mesh, samples, seed=seed)
- lo = mesh.bounds[0]
- span = np.where(ext > 1e-9, ext, 1.0)
- idx = np.clip(((pts - lo) / span * res).astype(int), 0, res - 1)
- cells = sorted(set((idx[:, 0] * res * res + idx[:, 1] * res + idx[:, 2]).tolist()))
- tri = int(len(mesh.faces))
- digest = hashlib.sha1(
- (",".join(map(str, cells)) + f"|{[int(round(e * 100)) for e in ext]}").encode()
- ).hexdigest()[:16]
- return MeshFingerprint(
- extents_cm=tuple(int(round(e * 100)) for e in ext), # type: ignore[arg-type]
- tri_count=tri,
- tri_bucket=int(math.log2(max(tri, 1))),
- voxels=cells,
- digest=digest,
- )
-
-
-class DedupeItem(BaseModel):
- id: str
- code_fp: str = ""
- mesh_fp: MeshFingerprint | None = None
-
-
-def near_duplicates(items: Iterable[DedupeItem], *, mesh_threshold: float = 0.9) -> list[list[str]]:
- """Groups (size ≥ 2) of ids that are 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])
diff --git a/harness/codeverse/flywheel/export.py b/harness/codeverse/flywheel/export.py
index e08f1793..965eb6d7 100644
--- a/harness/codeverse/flywheel/export.py
+++ b/harness/codeverse/flywheel/export.py
@@ -30,6 +30,7 @@ import hashlib
import json
import logging
import shutil
+from datetime import UTC, datetime
from pathlib import Path
from typing import Any, NamedTuple
@@ -39,15 +40,7 @@ from codeverse.contracts.common import ENTRY_FILE, Language
from codeverse.contracts.run import RunId, RunRecord
from codeverse.flywheel import sample as S
from codeverse.flywheel._git import CODE_ROOTS
-from codeverse.flywheel.dedupe import code_sha256
-from codeverse.flywheel.manifest import (
- DatasetGenerationManifest,
- DroppedRun,
- ManifestEntry,
- ManifestFilters,
- write_manifest,
-)
-from codeverse.flywheel.quality import DuplicateGroup, mark_duplicates
+from codeverse.flywheel.quality import DuplicateGroup, code_sha256, mark_duplicates
from codeverse.flywheel.record import FoundRun, iter_runs
from codeverse.workspace import Workspace
@@ -424,3 +417,76 @@ def write_jsonl(rows: list[dict[str, Any]], path: Path, *, commit: bool = True)
return tmp
tmp.replace(path)
return path
+
+
+# ===================================================================== manifest
+# (merged from codeverse/flywheel/manifest.py, 2026-08-28)
+MANIFEST_NAME = "dataset_manifest.json"
+
+
+class ManifestError(RuntimeError):
+ """The manifest is missing or unreadable."""
+
+
+class ManifestFilters(BaseModel):
+ """The selection knobs the export ran with (provenance for the dataset)."""
+
+ min_score: float | None = None
+ only_passed: bool = False
+ include_unbuilt: bool = False
+ drop_duplicates: bool = False
+ best_round: bool = True
+ captions_dir: str = ""
+
+
+class ManifestEntry(BaseModel):
+ """One exported sample folder, hashed file by file at write time."""
+
+ run: RunId
+ sample_id: str
+ sample_rel_dir: str = Field(description="sample folder relative to the dataset root (posix)")
+ files: dict[str, str] = Field(
+ description="sample-relative file path → sha256 of the bytes the export wrote")
+ code_fingerprint: str = Field(
+ default="", description="sha256 of the NORMALISED src tree (dedupe.code_fingerprint)")
+ code_sha256: str = Field(
+ default="", description="sha256 of the RAW src tree bytes (dedupe.code_sha256 — the exact hash)")
+
+
+class DroppedRun(BaseModel):
+ """A run the selection refused — nothing is dropped silently."""
+
+ run: RunId
+ reason: str = Field(description='filter reason, export error, or "duplicate_of:<sample id>"')
+
+
+class DatasetGenerationManifest(BaseModel):
+ generated_at: datetime | None = Field(
+ default=None, description="stamped at write time when not passed in")
+ filters: ManifestFilters = Field(default_factory=ManifestFilters)
+ entries: list[ManifestEntry] = Field(default_factory=list)
+ dropped: list[DroppedRun] = Field(default_factory=list)
+
+
+def write_manifest(manifest: DatasetGenerationManifest, out_dir: Path | str) -> Path:
+ """Atomic write (tmp + replace) of ``<out_dir>/dataset_manifest.json``."""
+ if manifest.generated_at is None:
+ manifest = manifest.model_copy(update={"generated_at": datetime.now(UTC)})
+ path = Path(out_dir) / MANIFEST_NAME
+ tmp = path.with_suffix(".json.tmp")
+ tmp.write_text(manifest.model_dump_json(indent=2))
+ tmp.replace(path)
+ return path
+
+
+def load_manifest(out_dir: Path | str) -> DatasetGenerationManifest:
+ """Read ``<out_dir>/dataset_manifest.json``; missing or invalid is a hard error."""
+ path = Path(out_dir) / MANIFEST_NAME
+ if not path.is_file():
+ raise ManifestError(
+ f"{path} not found — run export first (3dcv flywheel export writes it): "
+ f"pack no longer rescans directories")
+ try:
+ return DatasetGenerationManifest.model_validate_json(path.read_text())
+ except (ValueError, json.JSONDecodeError) as e:
+ raise ManifestError(f"{path} is not a valid dataset manifest: {e}") from e
diff --git a/harness/codeverse/flywheel/manifest.py b/harness/codeverse/flywheel/manifest.py
deleted file mode 100644
index 20a6b01d..00000000
--- a/harness/codeverse/flywheel/manifest.py
+++ /dev/null
@@ -1,90 +0,0 @@
-"""The dataset generation manifest: what export selected, dropped, and wrote.
-
-``export_samples`` writes ``<out>/dataset_manifest.json`` from its OWN selection
-loop — every sample folder it wrote, with a sha256 per file — and ``pack_samples``
-consumes ONLY this manifest. No directory rescan can resurrect a duplicate that
-``--drop-duplicates`` removed, and a planted ``src/meta.json`` inside a sample's
-LLM-written code tree can never become a phantom row. Nothing is dropped
-silently: every run the selection refused (filters, export errors, de-dup) is
-recorded under ``dropped`` with its reason.
-"""
-
-from __future__ import annotations
-
-import json
-from datetime import UTC, datetime
-from pathlib import Path
-
-from pydantic import BaseModel, Field
-
-from codeverse.contracts.run import RunId
-
-MANIFEST_NAME = "dataset_manifest.json"
-
-
-class ManifestError(RuntimeError):
- """The manifest is missing or unreadable."""
-
-
-class ManifestFilters(BaseModel):
- """The selection knobs the export ran with (provenance for the dataset)."""
-
- min_score: float | None = None
- only_passed: bool = False
- include_unbuilt: bool = False
- drop_duplicates: bool = False
- best_round: bool = True
- captions_dir: str = ""
-
-
-class ManifestEntry(BaseModel):
- """One exported sample folder, hashed file by file at write time."""
-
- run: RunId
- sample_id: str
- sample_rel_dir: str = Field(description="sample folder relative to the dataset root (posix)")
- files: dict[str, str] = Field(
- description="sample-relative file path → sha256 of the bytes the export wrote")
- code_fingerprint: str = Field(
- default="", description="sha256 of the NORMALISED src tree (dedupe.code_fingerprint)")
- code_sha256: str = Field(
- default="", description="sha256 of the RAW src tree bytes (dedupe.code_sha256 — the exact hash)")
-
-
-class DroppedRun(BaseModel):
- """A run the selection refused — nothing is dropped silently."""
-
- run: RunId
- reason: str = Field(description='filter reason, export error, or "duplicate_of:<sample id>"')
-
-
-class DatasetGenerationManifest(BaseModel):
- generated_at: datetime | None = Field(
- default=None, description="stamped at write time when not passed in")
- filters: ManifestFilters = Field(default_factory=ManifestFilters)
- entries: list[ManifestEntry] = Field(default_factory=list)
- dropped: list[DroppedRun] = Field(default_factory=list)
-
-
-def write_manifest(manifest: DatasetGenerationManifest, out_dir: Path | str) -> Path:
- """Atomic write (tmp + replace) of ``<out_dir>/dataset_manifest.json``."""
- if manifest.generated_at is None:
- manifest = manifest.model_copy(update={"generated_at": datetime.now(UTC)})
- path = Path(out_dir) / MANIFEST_NAME
- tmp = path.with_suffix(".json.tmp")
- tmp.write_text(manifest.model_dump_json(indent=2))
- tmp.replace(path)
- return path
-
-
-def load_manifest(out_dir: Path | str) -> DatasetGenerationManifest:
- """Read ``<out_dir>/dataset_manifest.json``; missing or invalid is a hard error."""
- path = Path(out_dir) / MANIFEST_NAME
- if not path.is_file():
- raise ManifestError(
- f"{path} not found — run export first (3dcv flywheel export writes it): "
- f"pack no longer rescans directories")
- try:
- return DatasetGenerationManifest.model_validate_json(path.read_text())
- except (ValueError, json.JSONDecodeError) as e:
- raise ManifestError(f"{path} is not a valid dataset manifest: {e}") from e
diff --git a/harness/codeverse/flywheel/pack.py b/harness/codeverse/flywheel/pack.py
index c6908d4a..6b037727 100644
--- a/harness/codeverse/flywheel/pack.py
+++ b/harness/codeverse/flywheel/pack.py
@@ -28,11 +28,13 @@ from pydantic import BaseModel, Field
from codeverse.flywheel.export import (
JSONL_NAME,
PARQUET_NAME,
+ ManifestEntry,
+ ManifestError,
+ load_manifest,
row_for_sample,
write_jsonl,
write_parquet,
)
-from codeverse.flywheel.manifest import ManifestEntry, ManifestError, load_manifest
from codeverse.flywheel.quality import mark_duplicates
MAX_TAR_BYTES = int(2.5 * 1024**3)
diff --git a/harness/codeverse/flywheel/quality.py b/harness/codeverse/flywheel/quality.py
index 2c7338b9..1d902d9f 100644
--- a/harness/codeverse/flywheel/quality.py
+++ b/harness/codeverse/flywheel/quality.py
@@ -1,30 +1,167 @@
-"""Dataset hygiene: quality tiers + duplicate detection by (code hash, prompt).
-
-* ``quality_tier(passed, gate_errors, score)`` → ``A | B | C | D``::
-
- A judged passed AND the best round has zero gate errors
- B judged passed (some gate errors remain)
- C not passed but best score ≥ 0.6
- D everything else (unjudged, failed, low score)
-
-* ``find_duplicates(rows)`` groups index rows with identical
- ``(code_sha256, prompt_hash)`` — RAW bytes. The canonical row of a group is the
- best (tier, score, fewest gate errors, captioned, then key order) and every other row gets
- ``duplicate_of = canonical id``. This is the only set anything may DROP.
-* ``find_near_duplicates(rows)`` groups on the NORMALISED ``code_fingerprint``
- instead and only stamps ``near_duplicate_of``: ``x = "a b"`` and ``x="ab"``
- normalise the same but are different programs, so they are marked, never removed.
+"""Near-duplicate detection: code fingerprints + coarse mesh fingerprints.
+
+* ``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 annotations
import hashlib
+import math
+import re
from collections import defaultdict
-from collections.abc import Iterable
+from collections.abc import Iterable, Mapping
+from pathlib import Path
from typing import Any, Literal
+import numpy as np
from pydantic import BaseModel, Field
+_COMMENT = re.compile(r"^\s*(#|//|\*|/\*).*$")
+_TRAILING_COMMENT = re.compile(r"\s+(#|//).*$")
+VOXEL_RES = 16
+
+
+def normalise_code(text: str) -> str:
+ """Drop comment-only lines, trailing comments, blank lines and all whitespace."""
+ out = []
+ for line in text.splitlines():
+ if _COMMENT.match(line):
+ continue
+ line = _TRAILING_COMMENT.sub("", line)
+ line = re.sub(r"\s+", "", line)
+ if line:
+ out.append(line)
+ return "\n".join(out)
+
+
+def code_fingerprint(files: Mapping[str, str | bytes]) -> str:
+ """Order-independent sha256 over ``(path, normalised code)`` pairs."""
+ h = hashlib.sha256()
+ for path in sorted(files):
+ data = files[path]
+ text = data.decode("utf-8", errors="replace") if isinstance(data, bytes) else data
+ h.update(path.encode())
+ h.update(b"\0")
+ h.update(normalise_code(text).encode())
+ h.update(b"\0")
+ return h.hexdigest()
+
+
+def code_sha256(files: Mapping[str, str | bytes]) -> str:
+ """Order-independent sha256 over the RAW ``(path, bytes)`` pairs — the
+ exact-content counterpart of :func:`code_fingerprint` (no normalisation,
+ no lossy decode)."""
+ h = hashlib.sha256()
+ for path in sorted(files):
+ data = files[path]
+ raw = data.encode("utf-8") if isinstance(data, str) else data
+ h.update(path.encode())
+ h.update(b"\0")
+ h.update(raw)
+ h.update(b"\0")
+ return h.hexdigest()
+
+
+class MeshFingerprint(BaseModel):
+ extents_cm: tuple[int, int, int]
+ tri_count: int
+ tri_bucket: int = Field(description="log2 bucket of the triangle count")
+ voxels: list[int] = Field(description="occupied cell indices in a VOXEL_RES³ grid over the bbox")
+ digest: str
+
+ def jaccard(self, other: MeshFingerprint) -> float:
+ a, b = set(self.voxels), set(other.voxels)
+ if not a and not b:
+ return 1.0
+ return len(a & b) / len(a | b)
+
+ def extents_compatible(self, other: MeshFingerprint, tol: float = 0.1) -> bool:
+ for x, y in zip(self.extents_cm, other.extents_cm, strict=True):
+ if max(x, y) == 0:
+ continue
+ if abs(x - y) / max(x, y) > tol:
+ return False
+ return True
+
+
+def mesh_fingerprint(glb: Path | str, *, res: int = VOXEL_RES, samples: int = 50_000, seed: int = 0) -> MeshFingerprint:
+ """Coarse, pose-sensitive shape fingerprint of a GLB (seeded surface samples → voxel grid).
+
+ Deterministic for identical geometry; near-identical meshes give Jaccard ≈ 1."""
+ import trimesh
+
+ loaded = trimesh.load(str(glb), force="scene")
+ mesh = loaded.to_mesh() if isinstance(loaded, trimesh.Scene) else loaded
+ if mesh is None or mesh.is_empty or len(mesh.faces) == 0:
+ raise ValueError(f"mesh_fingerprint: no triangles in {glb}")
+ ext = mesh.bounding_box.extents
+ pts, _ = trimesh.sample.sample_surface(mesh, samples, seed=seed)
+ lo = mesh.bounds[0]
+ span = np.where(ext > 1e-9, ext, 1.0)
+ idx = np.clip(((pts - lo) / span * res).astype(int), 0, res - 1)
+ cells = sorted(set((idx[:, 0] * res * res + idx[:, 1] * res + idx[:, 2]).tolist()))
+ tri = int(len(mesh.faces))
+ digest = hashlib.sha1(
+ (",".join(map(str, cells)) + f"|{[int(round(e * 100)) for e in ext]}").encode()
+ ).hexdigest()[:16]
+ return MeshFingerprint(
+ extents_cm=tuple(int(round(e * 100)) for e in ext), # type: ignore[arg-type]
+ tri_count=tri,
+ tri_bucket=int(math.log2(max(tri, 1))),
+ voxels=cells,
+ digest=digest,
+ )
+
+
+class DedupeItem(BaseModel):
+ id: str
+ code_fp: str = ""
+ mesh_fp: MeshFingerprint | None = None
+
+
+def near_duplicates(items: Iterable[DedupeItem], *, mesh_threshold: float = 0.9) -> list[list[str]]:
+ """Groups (size ≥ 2) of ids that are 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])
+
+
+# ===================================================================== quality
+# (merged from codeverse/flywheel/quality.py, 2026-08-28)
QualityTier = Literal["A", "B", "C", "D"]
TIER_ORDER: dict[str, int] = {"A": 0, "B": 1, "C": 2, "D": 3}
TIER_C_MIN_SCORE = 0.6
diff --git a/harness/codeverse/flywheel/sample.py b/harness/codeverse/flywheel/sample.py
index ab209aaf..62b0f1c7 100644
--- a/harness/codeverse/flywheel/sample.py
+++ b/harness/codeverse/flywheel/sample.py
@@ -32,9 +32,8 @@ from codeverse.contracts.common import (
)
from codeverse.contracts.run import RoundRecord, RunRecord
from codeverse.flywheel import _git
-from codeverse.flywheel.dedupe import code_fingerprint
from codeverse.flywheel.deliverable import deliverable_path
-from codeverse.flywheel.quality import QualityTier, prompt_hash, quality_tier
+from codeverse.flywheel.quality import QualityTier, code_fingerprint, prompt_hash, quality_tier
from codeverse.flywheel.record import (
best_round_index,
effective_judgment,
diff --git a/harness/codeverse/gallery/__init__.py b/harness/codeverse/gallery/__init__.py
index fec68d15..f366b568 100644
--- a/harness/codeverse/gallery/__init__.py
+++ b/harness/codeverse/gallery/__init__.py
@@ -15,15 +15,17 @@
from codeverse.gallery.compare import export_csv, render_compare
from codeverse.gallery.index import build_index, default_roots
-from codeverse.gallery.labels import VERDICTS, humanize_view
from codeverse.gallery.model import (
+ VERDICTS,
GalleryIndex,
RootSection,
RunEntry,
Summary,
+ humanize_view,
summarize,
verdict_breakdown,
)
+from codeverse.gallery.page import build_static, render_static
from codeverse.gallery.server import (
DEFAULT_HOST,
DEFAULT_PORT,
@@ -32,7 +34,6 @@ from codeverse.gallery.server import (
resolve_host,
serve,
)
-from codeverse.gallery.static_site import build_static, render_static
__all__ = [
"DEFAULT_HOST", "DEFAULT_PORT", "VERDICTS", "GalleryApp", "GalleryError", "GalleryIndex",
diff --git a/harness/codeverse/gallery/cards.py b/harness/codeverse/gallery/cards.py
index c5fcd6b0..31b2f982 100644
--- a/harness/codeverse/gallery/cards.py
+++ b/harness/codeverse/gallery/cards.py
@@ -14,8 +14,7 @@ Design rules this module exists to hold in one place:
from __future__ import annotations
-from codeverse.gallery.labels import VERDICT_META, humanize_view
-from codeverse.gallery.model import RunEntry, RunLink
+from codeverse.gallery.model import VERDICT_META, RunEntry, RunLink, humanize_view
from codeverse.gallery.theme import esc
from codeverse.gallery.urls import UrlMaker
diff --git a/harness/codeverse/gallery/code.py b/harness/codeverse/gallery/code.py
index 8910a997..bcd6a06f 100644
--- a/harness/codeverse/gallery/code.py
+++ b/harness/codeverse/gallery/code.py
@@ -13,9 +13,8 @@ import re
from pathlib import Path
from codeverse.gallery.model import RunEntry
-from codeverse.gallery.paths import safe_join
from codeverse.gallery.theme import esc, footer, page_shell, top_bar
-from codeverse.gallery.urls import UrlMaker
+from codeverse.gallery.urls import UrlMaker, safe_join
MAX_VIEW_BYTES = 512 * 1024
HIGHLIGHT_SUFFIXES = {".py", ".js", ".mjs", ".cjs", ".frag", ".vert", ".glsl", ".json"}
diff --git a/harness/codeverse/gallery/compare.py b/harness/codeverse/gallery/compare.py
index 3917ae47..0b7a06b5 100644
--- a/harness/codeverse/gallery/compare.py
+++ b/harness/codeverse/gallery/compare.py
@@ -15,8 +15,7 @@ import csv
import io
from codeverse.gallery.cards import fmt, tier_tag, verdict_tag
-from codeverse.gallery.labels import VERDICT_META
-from codeverse.gallery.model import RunEntry
+from codeverse.gallery.model import VERDICT_META, RunEntry
from codeverse.gallery.theme import esc, footer, page_shell, top_bar
from codeverse.gallery.urls import UrlMaker
diff --git a/harness/codeverse/gallery/index.py b/harness/codeverse/gallery/index.py
index 57ccef4e..74f8c4dc 100644
--- a/harness/codeverse/gallery/index.py
+++ b/harness/codeverse/gallery/index.py
@@ -27,8 +27,14 @@ from codeverse.flywheel.record import (
load_record,
)
from codeverse.flywheel.sample import gate_error_summary, telemetry_digest
-from codeverse.gallery.labels import humanize_view
-from codeverse.gallery.model import GalleryIndex, RootSection, RoundRow, RunEntry, RunLink
+from codeverse.gallery.model import (
+ GalleryIndex,
+ RootSection,
+ RoundRow,
+ RunEntry,
+ RunLink,
+ humanize_view,
+)
from codeverse.proc import read_json_or_none
from codeverse.workspace import Workspace
diff --git a/harness/codeverse/gallery/labels.py b/harness/codeverse/gallery/labels.py
deleted file mode 100644
index a0f4dd0e..00000000
--- a/harness/codeverse/gallery/labels.py
+++ /dev/null
@@ -1,79 +0,0 @@
-"""Human-readable labels for the gallery.
-
-Two small vocabularies live here so the page renderers never invent wording:
-
-* :func:`humanize_view` — the render pipeline's machine view names
- (``front_right_34``, ``t=2.5s``, ``pose_door_hinge@upper``) become the words a
- person would say ("Front Right ¾", "t = 2.5 s", "Pose · door_hinge@upper");
-* :data:`VERDICTS` — the four **disjoint** triage buckets every run falls into
- exactly once, so a status breakdown always sums to the number of runs shown.
-"""
-
-from __future__ import annotations
-
-#: the four buckets, in the order they are always displayed
-VERDICTS = ("passed", "failed", "unjudged", "error")
-
-#: bucket → (short label, css class, what it means)
-VERDICT_META: dict[str, tuple[str, str, str]] = {
- "passed": ("passed", "v-pass", "judged and over the rubric threshold"),
- "failed": ("failed", "v-fail", "judged and under the rubric threshold"),
- "unjudged": ("unjudged", "v-none", "the run finished but has no verdict"),
- "error": ("error", "v-err", "no record.json, or a corrupt / half-written one"),
-}
-
-#: view-name tokens that are not words
-_TOKENS = {"34": "¾", "3q": "¾", "hdri": "HDRI", "uv": "UV", "ao": "AO", "id": "ID"}
-
-#: whole names the render pipeline emits that deserve a written-out label
-_WHOLE = {
- "articulation_sheet": "Articulation poses",
- "articulation": "Articulation poses",
- "preview.gif": "Animated preview",
- "preview": "Animated preview",
- "sheet": "Contact sheet",
- "wire": "Wireframe",
- "normals": "Normals",
- "depth": "Depth",
-}
-
-
-def _word(token: str) -> str:
- low = token.lower()
- if low in _TOKENS:
- return _TOKENS[low]
- if not token:
- return token
- return token[:1].upper() + token[1:] if token[:1].islower() else token
-
-
-def humanize_view(name: str) -> str:
- """A render view's machine name as a person would read it.
-
- >>> humanize_view("view_front_right_34.png")
- 'Front Right ¾'
- >>> humanize_view("t=2.5s")
- 't = 2.5 s'
- >>> humanize_view("pose_door_hinge@upper")
- 'Pose · door_hinge@upper'
- """
- raw = (name or "").strip()
- if not raw:
- return ""
- stem = raw
- for suffix in (".png", ".jpg", ".jpeg", ".webp"):
- if stem.lower().endswith(suffix):
- stem = stem[: -len(suffix)]
- break
- if stem.lower().startswith("view_"):
- stem = stem[5:]
- low = stem.lower()
- if low in _WHOLE:
- return _WHOLE[low]
- if low.startswith("t=") and low.endswith("s"):
- return f"t = {stem[2:-1]} s"
- if low.startswith("pose_"):
- return f"Pose · {stem[5:]}"
- if low.startswith("frame_"):
- return f"Frame {stem[6:]}"
- return " ".join(_word(t) for t in stem.split("_") if t) or stem
diff --git a/harness/codeverse/gallery/model.py b/harness/codeverse/gallery/model.py
index 08f4b8b0..2e7761e5 100644
--- a/harness/codeverse/gallery/model.py
+++ b/harness/codeverse/gallery/model.py
@@ -1,10 +1,12 @@
-"""Typed model of the local gallery.
+"""Human-readable labels for the gallery.
-One :class:`RunEntry` per run directory (a run that has no ``record.json`` yet, or
-a corrupt one, is still an entry — ``state`` says so), grouped into
-:class:`RootSection` per run root (``runs/``, ``bench/out/<battery>/runs``).
-Every path an entry exposes is **run-relative** so the server can turn it into a
-URL and the static builder into a ``file://`` link — nothing here knows about HTTP.
+Two small vocabularies live here so the page renderers never invent wording:
+
+* :func:`humanize_view` — the render pipeline's machine view names
+ (``front_right_34``, ``t=2.5s``, ``pose_door_hinge@upper``) become the words a
+ person would say ("Front Right ¾", "t = 2.5 s", "Pose · door_hinge@upper");
+* :data:`VERDICTS` — the four **disjoint** triage buckets every run falls into
+ exactly once, so a status breakdown always sums to the number of runs shown.
"""
from __future__ import annotations
@@ -15,8 +17,76 @@ from typing import Literal
from pydantic import BaseModel, Field
-from codeverse.gallery.labels import VERDICTS
-
+#: the four buckets, in the order they are always displayed
+VERDICTS = ("passed", "failed", "unjudged", "error")
+
+#: bucket → (short label, css class, what it means)
+VERDICT_META: dict[str, tuple[str, str, str]] = {
+ "passed": ("passed", "v-pass", "judged and over the rubric threshold"),
+ "failed": ("failed", "v-fail", "judged and under the rubric threshold"),
+ "unjudged": ("unjudged", "v-none", "the run finished but has no verdict"),
+ "error": ("error", "v-err", "no record.json, or a corrupt / half-written one"),
+}
+
+#: view-name tokens that are not words
+_TOKENS = {"34": "¾", "3q": "¾", "hdri": "HDRI", "uv": "UV", "ao": "AO", "id": "ID"}
+
+#: whole names the render pipeline emits that deserve a written-out label
+_WHOLE = {
+ "articulation_sheet": "Articulation poses",
+ "articulation": "Articulation poses",
+ "preview.gif": "Animated preview",
+ "preview": "Animated preview",
+ "sheet": "Contact sheet",
+ "wire": "Wireframe",
+ "normals": "Normals",
+ "depth": "Depth",
+}
+
+
+def _word(token: str) -> str:
+ low = token.lower()
+ if low in _TOKENS:
+ return _TOKENS[low]
+ if not token:
+ return token
+ return token[:1].upper() + token[1:] if token[:1].islower() else token
+
+
+def humanize_view(name: str) -> str:
+ """A render view's machine name as a person would read it.
+
+ >>> humanize_view("view_front_right_34.png")
+ 'Front Right ¾'
+ >>> humanize_view("t=2.5s")
+ 't = 2.5 s'
+ >>> humanize_view("pose_door_hinge@upper")
+ 'Pose · door_hinge@upper'
+ """
+ raw = (name or "").strip()
+ if not raw:
+ return ""
+ stem = raw
+ for suffix in (".png", ".jpg", ".jpeg", ".webp"):
+ if stem.lower().endswith(suffix):
+ stem = stem[: -len(suffix)]
+ break
+ if stem.lower().startswith("view_"):
+ stem = stem[5:]
+ low = stem.lower()
+ if low in _WHOLE:
+ return _WHOLE[low]
+ if low.startswith("t=") and low.endswith("s"):
+ return f"t = {stem[2:-1]} s"
+ if low.startswith("pose_"):
+ return f"Pose · {stem[5:]}"
+ if low.startswith("frame_"):
+ return f"Frame {stem[6:]}"
+ return " ".join(_word(t) for t in stem.split("_") if t) or stem
+
+
+# ===================================================================== model
+# (merged from codeverse/gallery/model.py, 2026-08-28)
#: how an entry's link should be opened: raw bytes, a directory listing, the code
#: viewer, the GLB viewer, or another gallery page
LinkKind = Literal["file", "dir", "code", "viewer"]
@@ -110,7 +180,7 @@ class RunEntry(BaseModel):
@property
def verdict(self) -> str:
- """The triage bucket — exactly one of :data:`~codeverse.gallery.labels.VERDICTS`.
+ """The triage bucket — exactly one of :data:`~codeverse.gallery.model.VERDICTS`.
The four are disjoint *and* exhaustive on purpose: a status breakdown built
from them always sums to the number of runs on screen. A run whose record
diff --git a/harness/codeverse/gallery/page.py b/harness/codeverse/gallery/page.py
index d4cb3de9..55685117 100644
--- a/harness/codeverse/gallery/page.py
+++ b/harness/codeverse/gallery/page.py
@@ -15,20 +15,23 @@ reader has to do — and cannot.
from __future__ import annotations
import json
+from pathlib import Path
from codeverse.gallery.cards import TABLE_HEAD, render_card, render_row
-from codeverse.gallery.labels import VERDICT_META, VERDICTS
+from codeverse.gallery.index import build_index
from codeverse.gallery.model import (
FILTER_KEYS,
+ VERDICT_META,
+ VERDICTS,
GalleryIndex,
RunEntry,
match,
sort_entries,
summarize,
)
-from codeverse.gallery.scripts import INDEX_JS
-from codeverse.gallery.theme import INDEX_CSS, esc, footer, page_shell, top_bar
-from codeverse.gallery.urls import UrlMaker
+from codeverse.gallery.theme import INDEX_CSS, INDEX_JS, esc, footer, page_shell, top_bar
+from codeverse.gallery.urls import THUMB_PX, StaticUrls, UrlMaker
+from codeverse.proc import write_text_atomic
def _fmt(value: float | None, digits: int = 3, dash: str = "—") -> str:
@@ -180,3 +183,26 @@ def render_index(index: GalleryIndex, urls: UrlMaker, *, title: str = "3dcv gall
data_block = f"<script type='application/json' id='gallery-data'>{data}</script>"
return page_shell(title, body + data_block, scripts=INDEX_JS, extra_css=INDEX_CSS,
body_class="view-table" if view == "table" else "")
+
+
+# ===================================================================== static_site
+# (merged from codeverse/gallery/static_site.py, 2026-08-28)
+def render_static(index: GalleryIndex, *, title: str = "3dcv gallery", embed: bool = False,
+ thumb_px: int = THUMB_PX, sort: str = "score", view: str = "cards",
+ extra_html: str = "") -> str:
+ """The complete HTML document for ``index`` (no server involved)."""
+ note = ("images are inlined; the links open the original run directories on this machine"
+ if embed else "images and links point at the run directories with file:// — "
+ "use `3dcv gallery serve` for a page that works anywhere")
+ return render_index(index, StaticUrls(embed=embed, thumb_px=thumb_px),
+ title=title, sort=sort, view=view, note=note, extra_html=extra_html)
+
+
+def build_static(roots: list[Path] | list[str], out_html: Path | str, *, title: str | None = None,
+ embed: bool = False, thumb_px: int = THUMB_PX) -> tuple[Path, int, GalleryIndex]:
+ """Scan ``roots`` and write one self-contained page; ``(path, n_runs, index)``."""
+ index = build_index(roots)
+ label = title or ("3dcv gallery — " + ", ".join(s.label for s in index.sections[:4])
+ + ("…" if len(index.sections) > 4 else ""))
+ html = render_static(index, title=label, embed=embed, thumb_px=thumb_px)
+ return write_text_atomic(Path(out_html), html), len(index.entries()), index
diff --git a/harness/codeverse/gallery/paths.py b/harness/codeverse/gallery/paths.py
deleted file mode 100644
index 95c7d782..00000000
--- a/harness/codeverse/gallery/paths.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""Path safety for the local file server.
-
-Two independent gates, both required:
-
-1. the run directory must come from the **index** — a URL can only ever name a
- ``(battery, slug)`` pair the scanner found under a declared root; and
-2. :func:`safe_join` resolves the rest of the URL inside that run directory and
- refuses anything that escapes it (``..`` segments, absolute paths, encoded
- separators, symlinks pointing out of the run).
-
-``tests/gallery/test_server.py`` walks the traversal cases.
-"""
-
-from __future__ import annotations
-
-from pathlib import Path, PurePosixPath
-
-
-class PathError(ValueError):
- """A requested path is outside the run directory (or is not usable)."""
-
-
-def safe_join(root: Path | str, rel: str) -> Path:
- """``root / rel`` when ``rel`` stays inside ``root``; :class:`PathError` otherwise.
-
- ``rel`` is a URL path fragment that has already been percent-decoded."""
- base = Path(root).resolve()
- rel = (rel or "").strip()
- if "\x00" in rel:
- raise PathError("null byte in path")
- if rel.startswith(("/", "\\")) or (len(rel) > 1 and rel[1] == ":"):
- raise PathError(f"absolute path refused: {rel!r}")
- parts = [p for p in PurePosixPath(rel.replace("\\", "/")).parts if p not in ("", ".")]
- if any(p == ".." for p in parts):
- raise PathError(f"parent traversal refused: {rel!r}")
- target = base.joinpath(*parts)
- try:
- resolved = target.resolve()
- except OSError as e: # broken symlink loop, too many levels, …
- raise PathError(f"unresolvable path: {rel!r} ({e})") from e
- if resolved != base and base not in resolved.parents:
- raise PathError(f"path escapes the run directory: {rel!r}")
- return resolved
diff --git a/harness/codeverse/gallery/scripts.py b/harness/codeverse/gallery/scripts.py
deleted file mode 100644
index 88da3a8e..00000000
--- a/harness/codeverse/gallery/scripts.py
+++ /dev/null
@@ -1,240 +0,0 @@
-"""The gallery's client-side behaviour — plain ES5-ish JS, no dependencies.
-
-The page ships its run table as JSON in a ``<script type="application/json">``
-block; filtering, sorting, the per-section counts, the status breakdown and the
-bulk-selection bar are all recomputed from that array on every input event.
-Nothing here fetches: a filter change never reloads the page, and the URL is kept
-in sync with ``history.replaceState`` so a filtered view can be copied,
-bookmarked or curled.
-
-The bulk bar is deliberately read-only. ``compare`` and ``export csv`` are links
-to real server routes (so they work in a new tab, and without JS if you build the
-query by hand); ``copy paths`` writes to the clipboard. There is no "re-run"
-because there is no route that would run anything — see ``gallery/compare.py``.
-"""
-
-from __future__ import annotations
-
-INDEX_JS = r"""
-(function(){
-var node=document.getElementById('gallery-data');
-if(!node) return;
-var DATA=JSON.parse(node.textContent);
-var KEYS=['q','track','lang','tier','backend','pass','verdict','battery'];
-var BUCKETS=['passed','failed','unjudged','error'];
-var els={};
-KEYS.concat(['sort']).forEach(function(k){els[k]=document.getElementById('f-'+k);});
-var F={};
-var picked={};
-var filters=document.getElementById('filters');
-
-function readControls(){
- KEYS.forEach(function(k){F[k]=els[k]?String(els[k].value||'').trim():'';});
-}
-function match(r){
- if(F.q && r.text.indexOf(F.q.toLowerCase())<0) return false;
- if(F.track && r.track!==F.track) return false;
- if(F.lang && r.lang!==F.lang) return false;
- if(F.tier && r.tier!==F.tier) return false;
- if(F.backend && r.backend!==F.backend) return false;
- if(F.pass && r.pass!==F.pass) return false;
- if(F.verdict && r.verdict!==F.verdict) return false;
- if(F.battery && r.battery!==F.battery) return false;
- return true;
-}
-function num(v){return (v===null||v===undefined)?-1:Number(v);}
-function cmp(a,b){
- var s=els.sort?els.sort.value:'score';
- if(s==='name') return a.slug<b.slug?-1:(a.slug>b.slug?1:0);
- var k=(s==='cost')?'cost':(s==='time'?'minutes':(s==='complexity'?'complexity':'score'));
- var d=num(b[k])-num(a[k]);
- if(d) return d;
- return a.slug<b.slug?-1:1;
-}
-function fmt(v,d){return (v===null||v===undefined)?'—':Number(v).toFixed(d);}
-function set(id,txt){var e=document.getElementById(id); if(e) e.textContent=txt;}
-
-/* the strip's promise: the four buckets always add up to the runs on screen */
-function summarize(rows){
- var scored=[],total=0,mins=0,passed=0;
- var b={passed:0,failed:0,unjudged:0,error:0};
- rows.forEach(function(r){
- if(typeof r.score==='number') scored.push(r.score);
- total+=r.cost||0; mins+=r.minutes||0;
- if(b[r.verdict]===undefined) b[r.verdict]=0;
- b[r.verdict]++;
- if(r.verdict==='passed') passed++;
- });
- var mean=scored.length?scored.reduce(function(a,c){return a+c;},0)/scored.length:null;
- var srt=scored.slice().sort(function(a,c){return a-c;});
- var med=null;
- if(srt.length) med=srt.length%2?srt[(srt.length-1)/2]:(srt[srt.length/2-1]+srt[srt.length/2])/2;
- var n=document.getElementById('s-n');
- if(n) n.innerHTML=rows.length===DATA.length?String(rows.length)
- :(rows.length+" <span class='faint'>of "+DATA.length+"</span>");
- BUCKETS.forEach(function(k){
- set('vc-'+k,String(b[k]));
- set('vp-'+k,(rows.length?Math.round(100*b[k]/rows.length):0)+'%');
- var seg=document.getElementById('vs-'+k);
- if(seg){ seg.style.flex=String(b[k]); seg.title=b[k]+' '+k; }
- });
- set('s-score', fmt(mean,3)+' / '+fmt(med,3));
- set('s-cost', '$'+total.toFixed(2));
- set('s-perpass', passed?'$'+(total/passed).toFixed(2):'—');
- set('s-time', mins>=90?(mins/60).toFixed(1)+' h':Math.round(mins)+' min');
-}
-
-function paintChips(){
- var chips=document.querySelectorAll('.vchip');
- for(var i=0;i<chips.length;i++)
- chips[i].setAttribute('aria-pressed', chips[i].getAttribute('data-verdict')===F.verdict?'true':'false');
- var badge=document.getElementById('f-count'), active=document.getElementById('f-active');
- var n=0;
- KEYS.forEach(function(k){ if(F[k]) n++; });
- if(badge){ badge.textContent=String(n); badge.classList.toggle('is-hidden',n===0); }
- /* the collapsed accordion still has to say what is being hidden */
- if(active){
- active.textContent='';
- var closed=filters && !filters.hasAttribute('open');
- KEYS.forEach(function(k){
- if(!F[k] || !closed) return;
- var chip=document.createElement('span');
- chip.className='tag';
- chip.textContent=(k==='q'?'search':k)+': '+F[k];
- active.appendChild(chip);
- });
- }
-}
-
-function apply(){
- readControls();
- var keep={},rows=[];
- DATA.forEach(function(r){ if(match(r)){keep[r.key]=1; rows.push(r);} });
- var all=document.querySelectorAll('[data-run]');
- for(var i=0;i<all.length;i++)
- all[i].classList.toggle('is-hidden',!keep[all[i].getAttribute('data-run')]);
- rows.sort(cmp);
- var order={};
- rows.forEach(function(r,i){order[r.key]=i;});
- var boxes=document.querySelectorAll('[data-items]');
- for(var b=0;b<boxes.length;b++){
- var kids=[].slice.call(boxes[b].children).filter(function(k){return k.getAttribute('data-run');});
- kids.sort(function(x,y){
- var a=order[x.getAttribute('data-run')], c=order[y.getAttribute('data-run')];
- return (a===undefined?1e9:a)-(c===undefined?1e9:c);
- });
- for(var k=0;k<kids.length;k++) boxes[b].appendChild(kids[k]);
- }
- var secs=document.querySelectorAll('section.battery');
- for(var s=0;s<secs.length;s++){
- var vis=[].slice.call(secs[s].querySelectorAll('.grid > [data-run]'))
- .filter(function(e){return !e.classList.contains('is-hidden');}).length;
- var c=secs[s].querySelector('[data-count]');
- if(c) c.textContent=vis+(vis===1?' run':' runs');
- secs[s].classList.toggle('is-hidden',vis===0);
- }
- var empty=document.getElementById('empty');
- if(empty) empty.classList.toggle('is-hidden',rows.length>0);
- summarize(rows);
- paintChips();
- syncUrl();
-}
-
-function syncUrl(){
- var p=new URLSearchParams();
- KEYS.forEach(function(k){ if(F[k]) p.set(k,F[k]); });
- if(els.sort && els.sort.value && els.sort.value!=='score') p.set('sort',els.sort.value);
- if(document.body.classList.contains('view-table')) p.set('view','table');
- var qs=p.toString();
- try{ history.replaceState(null,'',qs?('?'+qs):location.pathname); }catch(e){}
-}
-
-/* ------------------------------------------------------------------ selection */
-function selKeys(){
- return DATA.filter(function(r){return picked[r.key];}).map(function(r){return r.key;});
-}
-function paintSelection(){
- var keys=selKeys(), bar=document.getElementById('selbar');
- set('sel-n',String(keys.length));
- if(bar) bar.classList.toggle('empty',keys.length===0);
- var hint=document.getElementById('sel-hint');
- if(hint) hint.classList.toggle('is-hidden',keys.length>0);
- var boxes=document.querySelectorAll('input.sel');
- for(var i=0;i<boxes.length;i++){
- var k=boxes[i].getAttribute('data-key'), on=!!picked[k];
- boxes[i].checked=on;
- var host=boxes[i].closest('[data-run]');
- if(host) host.classList.toggle('picked',on);
- }
- var qs='?runs='+encodeURIComponent(keys.join(','));
- var c=document.getElementById('sel-compare'); if(c) c.href='/compare'+qs;
- var x=document.getElementById('sel-csv'); if(x) x.href='/export.csv'+qs;
-}
-document.addEventListener('change',function(e){
- var t=e.target;
- if(!t || !t.classList || !t.classList.contains('sel')) return;
- var k=t.getAttribute('data-key');
- if(t.checked) picked[k]=1; else delete picked[k];
- paintSelection();
-});
-function on(id,fn){var e=document.getElementById(id); if(e) e.addEventListener('click',fn);}
-on('sel-clear',function(){picked={};paintSelection();});
-on('sel-all',function(){
- DATA.forEach(function(r){ if(match(r)) picked[r.key]=1; });
- paintSelection();
-});
-on('sel-paths',function(e){
- var btn=e.currentTarget;
- var paths=DATA.filter(function(r){return picked[r.key];}).map(function(r){return r.path;}).join('\n');
- var done=function(ok){ btn.textContent=ok?'copied':'copy failed';
- setTimeout(function(){btn.textContent='copy paths';},1400); };
- try{
- navigator.clipboard.writeText(paths).then(function(){done(true);},function(){done(false);});
- }catch(err){ done(false); }
-});
-
-/* ------------------------------------------------------------------ controls */
-KEYS.concat(['sort']).forEach(function(k){
- if(!els[k]) return;
- els[k].addEventListener('input',apply);
- els[k].addEventListener('change',apply);
-});
-var chips=document.querySelectorAll('.vchip');
-for(var i=0;i<chips.length;i++) chips[i].addEventListener('click',function(e){
- var want=e.currentTarget.getAttribute('data-verdict');
- if(els.verdict){ els.verdict.value=(els.verdict.value===want)?'':want; apply(); }
-});
-var reset=document.getElementById('f-reset');
-if(reset) reset.addEventListener('click',function(){
- KEYS.forEach(function(k){ if(els[k]) els[k].value=''; });
- if(els.sort) els.sort.value='score';
- apply();
-});
-var vb=document.getElementById('view-btn');
-if(vb) vb.addEventListener('click',function(){
- var on=document.body.classList.toggle('view-table');
- vb.setAttribute('aria-pressed',on?'true':'false');
- vb.textContent=on?'▤ table':'▦ cards';
- syncUrl();
-});
-/* a phone has no room for eight drop-downs above the first run */
-if(filters){
- if(window.innerWidth<760) filters.removeAttribute('open');
- filters.addEventListener('toggle',paintChips);
-}
-/* one open pop-up at a time */
-document.addEventListener('click',function(e){
- var open=document.querySelectorAll('details.menu[open],details.views[open]');
- for(var i=0;i<open.length;i++) if(!open[i].contains(e.target)) open[i].removeAttribute('open');
-});
-document.addEventListener('keydown',function(e){
- if(e.key==='/' && document.activeElement!==els.q && els.q){ e.preventDefault(); els.q.focus(); }
- if(e.key==='Escape'){
- var open=document.querySelectorAll('details.menu[open],details.views[open]');
- for(var i=0;i<open.length;i++) open[i].removeAttribute('open');
- }
-});
-apply();
-paintSelection();
-})();
-"""
diff --git a/harness/codeverse/gallery/server.py b/harness/codeverse/gallery/server.py
index 13f26395..9ce8ea6e 100644
--- a/harness/codeverse/gallery/server.py
+++ b/harness/codeverse/gallery/server.py
@@ -35,9 +35,8 @@ from codeverse.gallery.detail import render_broken_detail, render_detail
from codeverse.gallery.index import build_index
from codeverse.gallery.model import FILTER_KEYS, RunEntry, match, sort_entries
from codeverse.gallery.page import render_index
-from codeverse.gallery.paths import PathError, safe_join
from codeverse.gallery.theme import esc, footer, page_shell, top_bar
-from codeverse.gallery.urls import UrlMaker, content_type
+from codeverse.gallery.urls import PathError, UrlMaker, content_type, safe_join
DEFAULT_HOST = "127.0.0.1"
DEFAULT_PORT = 8765
diff --git a/harness/codeverse/gallery/static_site.py b/harness/codeverse/gallery/static_site.py
deleted file mode 100644
index 67914626..00000000
--- a/harness/codeverse/gallery/static_site.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""``3dcv gallery build`` — the shareable single-file form of the same page.
-
-Identical markup to the served gallery; only the URL maker differs. Without
-``--embed`` the ``<img>`` tags point at the run directories with ``file://``
-(fast, tiny file, works on this machine); with ``--embed`` every contact sheet is
-inlined as a downscaled JPEG so the page can be copied or published — at the
-price of a much bigger file. The write is atomic: a bench reading the previous
-gallery never sees a half-written one.
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-from codeverse.gallery.index import build_index
-from codeverse.gallery.model import GalleryIndex
-from codeverse.gallery.page import render_index
-from codeverse.gallery.urls import THUMB_PX, StaticUrls
-from codeverse.proc import write_text_atomic
-
-
-def render_static(index: GalleryIndex, *, title: str = "3dcv gallery", embed: bool = False,
- thumb_px: int = THUMB_PX, sort: str = "score", view: str = "cards",
- extra_html: str = "") -> str:
- """The complete HTML document for ``index`` (no server involved)."""
- note = ("images are inlined; the links open the original run directories on this machine"
- if embed else "images and links point at the run directories with file:// — "
- "use `3dcv gallery serve` for a page that works anywhere")
- return render_index(index, StaticUrls(embed=embed, thumb_px=thumb_px),
- title=title, sort=sort, view=view, note=note, extra_html=extra_html)
-
-
-def build_static(roots: list[Path] | list[str], out_html: Path | str, *, title: str | None = None,
- embed: bool = False, thumb_px: int = THUMB_PX) -> tuple[Path, int, GalleryIndex]:
- """Scan ``roots`` and write one self-contained page; ``(path, n_runs, index)``."""
- index = build_index(roots)
- label = title or ("3dcv gallery — " + ", ".join(s.label for s in index.sections[:4])
- + ("…" if len(index.sections) > 4 else ""))
- html = render_static(index, title=label, embed=embed, thumb_px=thumb_px)
- return write_text_atomic(Path(out_html), html), len(index.entries()), index
diff --git a/harness/codeverse/gallery/theme.py b/harness/codeverse/gallery/theme.py
index 476ff100..534a25e3 100644
--- a/harness/codeverse/gallery/theme.py
+++ b/harness/codeverse/gallery/theme.py
@@ -391,3 +391,230 @@ def top_bar(title: str, subtitle: str = "", *, crumbs: str = "", right: str = ""
def footer(text: str) -> str:
return f"<footer class='foot'>{esc(text)}</footer>"
+
+
+# ===================================================================== scripts
+# (merged from codeverse/gallery/scripts.py, 2026-08-28)
+INDEX_JS = r"""
+(function(){
+var node=document.getElementById('gallery-data');
+if(!node) return;
+var DATA=JSON.parse(node.textContent);
+var KEYS=['q','track','lang','tier','backend','pass','verdict','battery'];
+var BUCKETS=['passed','failed','unjudged','error'];
+var els={};
+KEYS.concat(['sort']).forEach(function(k){els[k]=document.getElementById('f-'+k);});
+var F={};
+var picked={};
+var filters=document.getElementById('filters');
+
+function readControls(){
+ KEYS.forEach(function(k){F[k]=els[k]?String(els[k].value||'').trim():'';});
+}
+function match(r){
+ if(F.q && r.text.indexOf(F.q.toLowerCase())<0) return false;
+ if(F.track && r.track!==F.track) return false;
+ if(F.lang && r.lang!==F.lang) return false;
+ if(F.tier && r.tier!==F.tier) return false;
+ if(F.backend && r.backend!==F.backend) return false;
+ if(F.pass && r.pass!==F.pass) return false;
+ if(F.verdict && r.verdict!==F.verdict) return false;
+ if(F.battery && r.battery!==F.battery) return false;
+ return true;
+}
+function num(v){return (v===null||v===undefined)?-1:Number(v);}
+function cmp(a,b){
+ var s=els.sort?els.sort.value:'score';
+ if(s==='name') return a.slug<b.slug?-1:(a.slug>b.slug?1:0);
+ var k=(s==='cost')?'cost':(s==='time'?'minutes':(s==='complexity'?'complexity':'score'));
+ var d=num(b[k])-num(a[k]);
+ if(d) return d;
+ return a.slug<b.slug?-1:1;
+}
+function fmt(v,d){return (v===null||v===undefined)?'—':Number(v).toFixed(d);}
+function set(id,txt){var e=document.getElementById(id); if(e) e.textContent=txt;}
+
+/* the strip's promise: the four buckets always add up to the runs on screen */
+function summarize(rows){
+ var scored=[],total=0,mins=0,passed=0;
+ var b={passed:0,failed:0,unjudged:0,error:0};
+ rows.forEach(function(r){
+ if(typeof r.score==='number') scored.push(r.score);
+ total+=r.cost||0; mins+=r.minutes||0;
+ if(b[r.verdict]===undefined) b[r.verdict]=0;
+ b[r.verdict]++;
+ if(r.verdict==='passed') passed++;
+ });
+ var mean=scored.length?scored.reduce(function(a,c){return a+c;},0)/scored.length:null;
+ var srt=scored.slice().sort(function(a,c){return a-c;});
+ var med=null;
+ if(srt.length) med=srt.length%2?srt[(srt.length-1)/2]:(srt[srt.length/2-1]+srt[srt.length/2])/2;
+ var n=document.getElementById('s-n');
+ if(n) n.innerHTML=rows.length===DATA.length?String(rows.length)
+ :(rows.length+" <span class='faint'>of "+DATA.length+"</span>");
+ BUCKETS.forEach(function(k){
+ set('vc-'+k,String(b[k]));
+ set('vp-'+k,(rows.length?Math.round(100*b[k]/rows.length):0)+'%');
+ var seg=document.getElementById('vs-'+k);
+ if(seg){ seg.style.flex=String(b[k]); seg.title=b[k]+' '+k; }
+ });
+ set('s-score', fmt(mean,3)+' / '+fmt(med,3));
+ set('s-cost', '$'+total.toFixed(2));
+ set('s-perpass', passed?'$'+(total/passed).toFixed(2):'—');
+ set('s-time', mins>=90?(mins/60).toFixed(1)+' h':Math.round(mins)+' min');
+}
+
+function paintChips(){
+ var chips=document.querySelectorAll('.vchip');
+ for(var i=0;i<chips.length;i++)
+ chips[i].setAttribute('aria-pressed', chips[i].getAttribute('data-verdict')===F.verdict?'true':'false');
+ var badge=document.getElementById('f-count'), active=document.getElementById('f-active');
+ var n=0;
+ KEYS.forEach(function(k){ if(F[k]) n++; });
+ if(badge){ badge.textContent=String(n); badge.classList.toggle('is-hidden',n===0); }
+ /* the collapsed accordion still has to say what is being hidden */
+ if(active){
+ active.textContent='';
+ var closed=filters && !filters.hasAttribute('open');
+ KEYS.forEach(function(k){
+ if(!F[k] || !closed) return;
+ var chip=document.createElement('span');
+ chip.className='tag';
+ chip.textContent=(k==='q'?'search':k)+': '+F[k];
+ active.appendChild(chip);
+ });
+ }
+}
+
+function apply(){
+ readControls();
+ var keep={},rows=[];
+ DATA.forEach(function(r){ if(match(r)){keep[r.key]=1; rows.push(r);} });
+ var all=document.querySelectorAll('[data-run]');
+ for(var i=0;i<all.length;i++)
+ all[i].classList.toggle('is-hidden',!keep[all[i].getAttribute('data-run')]);
+ rows.sort(cmp);
+ var order={};
+ rows.forEach(function(r,i){order[r.key]=i;});
+ var boxes=document.querySelectorAll('[data-items]');
+ for(var b=0;b<boxes.length;b++){
+ var kids=[].slice.call(boxes[b].children).filter(function(k){return k.getAttribute('data-run');});
+ kids.sort(function(x,y){
+ var a=order[x.getAttribute('data-run')], c=order[y.getAttribute('data-run')];
+ return (a===undefined?1e9:a)-(c===undefined?1e9:c);
+ });
+ for(var k=0;k<kids.length;k++) boxes[b].appendChild(kids[k]);
+ }
+ var secs=document.querySelectorAll('section.battery');
+ for(var s=0;s<secs.length;s++){
+ var vis=[].slice.call(secs[s].querySelectorAll('.grid > [data-run]'))
+ .filter(function(e){return !e.classList.contains('is-hidden');}).length;
+ var c=secs[s].querySelector('[data-count]');
+ if(c) c.textContent=vis+(vis===1?' run':' runs');
+ secs[s].classList.toggle('is-hidden',vis===0);
+ }
+ var empty=document.getElementById('empty');
+ if(empty) empty.classList.toggle('is-hidden',rows.length>0);
+ summarize(rows);
+ paintChips();
+ syncUrl();
+}
+
+function syncUrl(){
+ var p=new URLSearchParams();
+ KEYS.forEach(function(k){ if(F[k]) p.set(k,F[k]); });
+ if(els.sort && els.sort.value && els.sort.value!=='score') p.set('sort',els.sort.value);
+ if(document.body.classList.contains('view-table')) p.set('view','table');
+ var qs=p.toString();
+ try{ history.replaceState(null,'',qs?('?'+qs):location.pathname); }catch(e){}
+}
+
+/* ------------------------------------------------------------------ selection */
+function selKeys(){
+ return DATA.filter(function(r){return picked[r.key];}).map(function(r){return r.key;});
+}
+function paintSelection(){
+ var keys=selKeys(), bar=document.getElementById('selbar');
+ set('sel-n',String(keys.length));
+ if(bar) bar.classList.toggle('empty',keys.length===0);
+ var hint=document.getElementById('sel-hint');
+ if(hint) hint.classList.toggle('is-hidden',keys.length>0);
+ var boxes=document.querySelectorAll('input.sel');
+ for(var i=0;i<boxes.length;i++){
+ var k=boxes[i].getAttribute('data-key'), on=!!picked[k];
+ boxes[i].checked=on;
+ var host=boxes[i].closest('[data-run]');
+ if(host) host.classList.toggle('picked',on);
+ }
+ var qs='?runs='+encodeURIComponent(keys.join(','));
+ var c=document.getElementById('sel-compare'); if(c) c.href='/compare'+qs;
+ var x=document.getElementById('sel-csv'); if(x) x.href='/export.csv'+qs;
+}
+document.addEventListener('change',function(e){
+ var t=e.target;
+ if(!t || !t.classList || !t.classList.contains('sel')) return;
+ var k=t.getAttribute('data-key');
+ if(t.checked) picked[k]=1; else delete picked[k];
+ paintSelection();
+});
+function on(id,fn){var e=document.getElementById(id); if(e) e.addEventListener('click',fn);}
+on('sel-clear',function(){picked={};paintSelection();});
+on('sel-all',function(){
+ DATA.forEach(function(r){ if(match(r)) picked[r.key]=1; });
+ paintSelection();
+});
+on('sel-paths',function(e){
+ var btn=e.currentTarget;
+ var paths=DATA.filter(function(r){return picked[r.key];}).map(function(r){return r.path;}).join('\n');
+ var done=function(ok){ btn.textContent=ok?'copied':'copy failed';
+ setTimeout(function(){btn.textContent='copy paths';},1400); };
+ try{
+ navigator.clipboard.writeText(paths).then(function(){done(true);},function(){done(false);});
+ }catch(err){ done(false); }
+});
+
+/* ------------------------------------------------------------------ controls */
+KEYS.concat(['sort']).forEach(function(k){
+ if(!els[k]) return;
+ els[k].addEventListener('input',apply);
+ els[k].addEventListener('change',apply);
+});
+var chips=document.querySelectorAll('.vchip');
+for(var i=0;i<chips.length;i++) chips[i].addEventListener('click',function(e){
+ var want=e.currentTarget.getAttribute('data-verdict');
+ if(els.verdict){ els.verdict.value=(els.verdict.value===want)?'':want; apply(); }
+});
+var reset=document.getElementById('f-reset');
+if(reset) reset.addEventListener('click',function(){
+ KEYS.forEach(function(k){ if(els[k]) els[k].value=''; });
+ if(els.sort) els.sort.value='score';
+ apply();
+});
+var vb=document.getElementById('view-btn');
+if(vb) vb.addEventListener('click',function(){
+ var on=document.body.classList.toggle('view-table');
+ vb.setAttribute('aria-pressed',on?'true':'false');
+ vb.textContent=on?'▤ table':'▦ cards';
+ syncUrl();
+});
+/* a phone has no room for eight drop-downs above the first run */
+if(filters){
+ if(window.innerWidth<760) filters.removeAttribute('open');
+ filters.addEventListener('toggle',paintChips);
+}
+/* one open pop-up at a time */
+document.addEventListener('click',function(e){
+ var open=document.querySelectorAll('details.menu[open],details.views[open]');
+ for(var i=0;i<open.length;i++) if(!open[i].contains(e.target)) open[i].removeAttribute('open');
+});
+document.addEventListener('keydown',function(e){
+ if(e.key==='/' && document.activeElement!==els.q && els.q){ e.preventDefault(); els.q.focus(); }
+ if(e.key==='Escape'){
+ var open=document.querySelectorAll('details.menu[open],details.views[open]');
+ for(var i=0;i<open.length;i++) open[i].removeAttribute('open');
+ }
+});
+apply();
+paintSelection();
+})();
+"""
diff --git a/harness/codeverse/gallery/urls.py b/harness/codeverse/gallery/urls.py
index c8a21d6b..c9b8bde0 100644
--- a/harness/codeverse/gallery/urls.py
+++ b/harness/codeverse/gallery/urls.py
@@ -11,7 +11,7 @@ from __future__ import annotations
import base64
import io
import mimetypes
-from pathlib import Path
+from pathlib import Path, PurePosixPath
from urllib.parse import quote
from codeverse.gallery.model import RunEntry, RunLink
@@ -153,3 +153,32 @@ def content_type(path: Path | str) -> str:
if guessed.startswith("text/") and "charset" not in guessed:
return f"{guessed}; charset=utf-8"
return guessed
+
+
+# ===================================================================== paths
+# (merged from codeverse/gallery/paths.py, 2026-08-28)
+class PathError(ValueError):
+ """A requested path is outside the run directory (or is not usable)."""
+
+
+def safe_join(root: Path | str, rel: str) -> Path:
+ """``root / rel`` when ``rel`` stays inside ``root``; :class:`PathError` otherwise.
+
+ ``rel`` is a URL path fragment that has already been percent-decoded."""
+ base = Path(root).resolve()
+ rel = (rel or "").strip()
+ if "\x00" in rel:
+ raise PathError("null byte in path")
+ if rel.startswith(("/", "\\")) or (len(rel) > 1 and rel[1] == ":"):
+ raise PathError(f"absolute path refused: {rel!r}")
+ parts = [p for p in PurePosixPath(rel.replace("\\", "/")).parts if p not in ("", ".")]
+ if any(p == ".." for p in parts):
+ raise PathError(f"parent traversal refused: {rel!r}")
+ target = base.joinpath(*parts)
+ try:
+ resolved = target.resolve()
+ except OSError as e: # broken symlink loop, too many levels, …
+ raise PathError(f"unresolvable path: {rel!r} ({e})") from e
+ if resolved != base and base not in resolved.parents:
+ raise PathError(f"path escapes the run directory: {rel!r}")
+ return resolved
diff --git a/harness/codeverse/gallery/viewer.py b/harness/codeverse/gallery/viewer.py
index 412395ad..99799f71 100644
--- a/harness/codeverse/gallery/viewer.py
+++ b/harness/codeverse/gallery/viewer.py
@@ -104,7 +104,7 @@ def vendor_path(rel: str, runtime_js: Path | str | None = None) -> Path | None:
Only the two whitelisted subtrees are reachable, and :func:`safe_join` still
checks the result — a vendor URL can never leave ``node_modules/three``."""
- from codeverse.gallery.paths import PathError, safe_join
+ from codeverse.gallery.urls import PathError, safe_join
root = three_root(runtime_js)
if root is None:
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index a810fe6f..d57a99e2 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -170,17 +170,18 @@ codeverse/
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/ record.py, export.py, pack.py, sample.py, pairs.py, migrate.py (schema moves),
- deliverable.py, telemetry.py, captions.py, quality.py (tiers + dedupe), dedupe.py, index.py,
+ deliverable.py, telemetry.py, captions.py, quality.py (tiers + dedupe + code/mesh fingerprints), index.py,
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)
- gallery/ THE local run gallery (`3dcv gallery serve|build`): cards.py, labels.py,
+ gallery/ THE local run gallery (`3dcv 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 +
table + filters + per-filter summary), detail.py (/run/<battery>/<slug>),
code.py (src browser), viewer.py (GLB orbit viewer on the vendored three.js),
- paths.py (traversal guard), urls.py (server vs file:// targets + content types),
- server.py (stdlib http.server, loopback-only), static_site.py, theme.py, scripts.py
+ urls.py (server vs file:// targets + content types + the traversal guard),
+ server.py (stdlib http.server, loopback-only; page.py also renders the
+ static single-file form), theme.py (CSS + the index-page JS)
prompts/ system/*, <lang>/{contract,cookbook}.md (incl. glsl_shader/, opengl_python/),
texturing/*.md, tracks/*.j2 (incl. plan/generate/refine_graphics.j2)
cli/ main.py (app wiring, make/resume/mcp), inspect_cmd.py (status/render/judge
diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.md
index 338ad9d8..47dbbb52 100644
--- a/harness/docs/INTERFACES.md
+++ b/harness/docs/INTERFACES.md
@@ -436,7 +436,7 @@ from codeverse.gallery import build_index, default_roots, build_static, serve, G
# render_static(index, *, embed=…, extra_html="") — bench/report.py's page
# GalleryApp(roots, reload=False).route(path, query) -> Response (pure, testable)
# serve(roots, *, host=None, host_explicit=False, port=8765, reload=False)
-from codeverse.gallery.paths import safe_join # (root, rel) -> Path inside root, else PathError
+from codeverse.gallery.urls import safe_join # (root, rel) -> Path inside root, else PathError
from codeverse.gallery.urls import content_type # .glb→model/gltf-binary, .py/.js/.frag→text/plain; charset=utf-8
from codeverse.flywheel.index import build_index, query, summary # sqlite + parquet: adds quality_tier, gate_errors, cost_usd,
# rounds, status, code_fingerprint, prompt_hash, duplicate_of, has_captions
diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.py
index c076df57..afd542a8 100644
--- a/harness/tests/core/test_run_layout.py
+++ b/harness/tests/core/test_run_layout.py
@@ -109,7 +109,7 @@ def _moved_run(tmp_path: Path):
def _captured(render) -> str:
"""rich's Console holds its own stream, so capsys never sees it; widen it too so the
panel cannot wrap the path under assertion."""
- from codeverse.cli._fmt import console
+ from codeverse.cli._common import console
old_width, console.width = console.width, 400
try:
@@ -154,7 +154,7 @@ def test_a_relocated_run_still_resolves_its_stored_paths(tmp_path):
def test_show_prints_the_sheet_that_exists_after_a_move(tmp_path):
"""The user-visible half: `3dcv show` must not print a path that is not there."""
- from codeverse.cli._fmt import print_record_summary
+ from codeverse.cli._common import print_record_summary
from codeverse.workspace import Workspace
_a, b, _sheet, rec = _moved_run(tmp_path)
diff --git a/harness/tests/flywheel_cli/test_flywheel.py b/harness/tests/flywheel_cli/test_flywheel.py
index 04fa3b94..dea5b948 100644
--- a/harness/tests/flywheel_cli/test_flywheel.py
+++ b/harness/tests/flywheel_cli/test_flywheel.py
@@ -12,17 +12,17 @@ import pytest
from codeverse.contracts.run import RunRecord
from codeverse.flywheel import _git
-from codeverse.flywheel.dedupe import (
+from codeverse.flywheel.export import export_samples
+from codeverse.flywheel.index import build_index, round_curve, summary, top_runs
+from codeverse.flywheel.pack import pack_samples, verify_locators
+from codeverse.flywheel.pairs import build_pairs
+from codeverse.flywheel.quality import (
DedupeItem,
MeshFingerprint,
code_fingerprint,
near_duplicates,
normalise_code,
)
-from codeverse.flywheel.export import export_samples
-from codeverse.flywheel.index import build_index, round_curve, summary, top_runs
-from codeverse.flywheel.pack import pack_samples, verify_locators
-from codeverse.flywheel.pairs import build_pairs
from codeverse.flywheel.record import (
RecordError,
best_round_index,
@@ -200,7 +200,7 @@ def test_near_duplicates_groups():
def test_mesh_fingerprint_real_glb(tmp_path: Path):
trimesh = pytest.importorskip("trimesh")
- from codeverse.flywheel.dedupe import mesh_fingerprint
+ from codeverse.flywheel.quality import mesh_fingerprint
box = trimesh.creation.box(extents=(1.0, 0.5, 0.25))
p = tmp_path / "box.glb"
diff --git a/harness/tests/flywheel_cli/test_manifest_pack.py b/harness/tests/flywheel_cli/test_manifest_pack.py
index a0d70040..44d82433 100644
--- a/harness/tests/flywheel_cli/test_manifest_pack.py
+++ b/harness/tests/flywheel_cli/test_manifest_pack.py
@@ -20,10 +20,11 @@ from pathlib import Path
import pytest
-from codeverse.flywheel.export import collect_rows, export_samples
-from codeverse.flywheel.manifest import (
+from codeverse.flywheel.export import (
MANIFEST_NAME,
ManifestError,
+ collect_rows,
+ export_samples,
load_manifest,
write_manifest,
)
diff --git a/harness/tests/gallery/test_page.py b/harness/tests/gallery/test_page.py
index a1d3dac0..dd12341d 100644
--- a/harness/tests/gallery/test_page.py
+++ b/harness/tests/gallery/test_page.py
@@ -8,8 +8,7 @@ from html.parser import HTMLParser
from pathlib import Path
from codeverse.gallery.index import build_index
-from codeverse.gallery.page import render_index
-from codeverse.gallery.static_site import build_static, render_static
+from codeverse.gallery.page import build_static, render_index, render_static
from codeverse.gallery.urls import StaticUrls, UrlMaker
VOID = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param",
diff --git a/harness/tests/gallery/test_server.py b/harness/tests/gallery/test_server.py
index 1f980cb8..658c0e41 100644
--- a/harness/tests/gallery/test_server.py
+++ b/harness/tests/gallery/test_server.py
@@ -13,7 +13,6 @@ from pathlib import Path
import pytest
-from codeverse.gallery.paths import PathError, safe_join
from codeverse.gallery.server import (
DEFAULT_HOST,
GalleryApp,
@@ -21,7 +20,7 @@ from codeverse.gallery.server import (
make_server,
resolve_host,
)
-from codeverse.gallery.urls import content_type
+from codeverse.gallery.urls import PathError, content_type, safe_join
@pytest.fixture
diff --git a/harness/tests/gallery/test_triage.py b/harness/tests/gallery/test_triage.py
index 9808582a..a2c9f603 100644
--- a/harness/tests/gallery/test_triage.py
+++ b/harness/tests/gallery/test_triage.py
@@ -21,8 +21,7 @@ from codeverse.gallery.compare import (
render_compare,
)
from codeverse.gallery.index import HERO_PREFERENCE, build_index, hero_view
-from codeverse.gallery.labels import VERDICTS, humanize_view
-from codeverse.gallery.model import match, summarize, verdict_breakdown
+from codeverse.gallery.model import VERDICTS, humanize_view, match, summarize, verdict_breakdown
from codeverse.gallery.page import render_index
from codeverse.gallery.server import GalleryApp
from codeverse.gallery.urls import UrlMaker
@@ -177,7 +176,7 @@ def test_compare_survives_a_run_with_no_record(gallery_tree: dict[str, Path]):
def test_bulk_bar_is_offered_on_the_server_but_not_in_the_static_build(gallery_tree: dict[str, Path]):
- from codeverse.gallery.static_site import render_static
+ from codeverse.gallery.page import render_static
index = build_index([gallery_tree["runs"]])
served = render_index(index, UrlMaker())