Skip to content

Official Codebase of 3DCodeVerse

Python

addons: select — pick a round and hand it over after the run (`3dcode pick`, `make --no-pick`)

gaoypeng4d1e3f749e76
diff --git a/harness/codeverse3d/addons/__init__.py b/harness/codeverse3d/addons/__init__.py
index 58b5f441..31dbedfb 100644
--- a/harness/codeverse3d/addons/__init__.py
+++ b/harness/codeverse3d/addons/__init__.py
@@ -8,9 +8,13 @@
(``python -m codeverse3d.addons.calibration``)
* ``skill_targets`` each skill bundle's falsifiable claim, measured (``3dcode skills …``,
``eval/bench/skill_targets.py``)
+* ``select`` which round of a finished run to hand over, and ``deliverable/`` for it
+ (``3dcode pick``; ``3dcode make`` calls it after the run) — the reader
+ every other reader asks for a run's baseline / picked score
The boundary is one-way and pinned by ``tests/core/test_addons_boundary.py``: an addon may
import anything in ``codeverse3d``; outside ``codeverse3d.cli`` nothing in ``codeverse3d`` imports an
-addon. What a run itself writes (``record.json``, ``deliverable/``, telemetry) is NOT an
-addon — that is ``codeverse3d.record``; booking its cost while it runs is ``codeverse3d.cost``.
+addon. What a run itself writes (``record.json``, the per-round ``artifacts/rNN/``,
+telemetry) is NOT an addon — that is ``codeverse3d.record``; booking its cost while it runs is
+``codeverse3d.cost``.
"""
diff --git a/harness/codeverse3d/addons/dataset/captions.py b/harness/codeverse3d/addons/dataset/captions.py
index b1005311..5ab43276 100644
--- a/harness/codeverse3d/addons/dataset/captions.py
+++ b/harness/codeverse3d/addons/dataset/captions.py
@@ -161,8 +161,8 @@ def caption_sample(
"""Caption the best round of ``record``.
Default: store into ``record.extra["captions"]`` + ``<ws>/captions.json`` and
- re-package the run (``package_run``: deliverable/, telemetry/, ``record.json``) —
- a caption changes all three. With ``out_dir`` the workspace is left untouched and
+ refresh what a caption changes: telemetry/ (``package_run``), ``record.json``, and
+ ``deliverable/`` when a round has been packaged (it carries captions.json). With ``out_dir`` the workspace is left untouched and
``<out_dir>/<slug>.json`` (captions + provenance) is written instead — ``slug``
should be the run's :class:`~codeverse3d.contracts.run.RunId` slug; without one the
side-car falls back to the directory basename (flat layouts only: every nested
@@ -210,11 +210,15 @@ 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 codeverse3d.record.deliverable import build_deliverable, load_deliverable
from codeverse3d.record.record import package_run
ws.write_json(ws.root / "captions.json", payload)
- package_run(ws, record) # captions.json + cost.json + the manifest all go stale otherwise
+ package_run(ws, record) # cost.json goes stale otherwise
ws.write_json(ws.record_path, record)
+ handed = load_deliverable(ws)
+ if handed is not None and handed.round is not None: # ... and the hand-over's captions.json + manifest
+ build_deliverable(ws, record, handed.round)
return caps
diff --git a/harness/codeverse3d/addons/select.py b/harness/codeverse3d/addons/select.py
new file mode 100644
index 00000000..4901126a
--- /dev/null
+++ b/harness/codeverse3d/addons/select.py
@@ -0,0 +1,250 @@
+"""Which round of a finished run to hand over — and the hand-over itself (``3dcode pick``).
+
+Since 2026-09-22 the run loop keeps every round, ends at the last one and calls no run
+passed or failed: the judge scores each round and its verdict shapes the next one, and
+choosing among the rounds is a READER's job. This addon is that reader, and the one every
+other reader asks (gallery, dataset, cost report, calibration, the CLI, eval/bench):
+
+* :func:`round_rows` one typed row per saved round — the effective judged score, the
+ judge's own verdict for that round, gate errors, commit, cost, minutes;
+* :func:`pick` the round to hand over: the highest judged score, ties to fewer gate
+ errors, then the earlier round. ``by="pairwise"`` lets the position-
+ swapped pairwise judge decide between the top two when they sit within
+ the judge's noise (the verdict is paid once and cached in
+ ``artifacts/judge/``);
+* :func:`summarise` baseline score, the picked round and its score, the delta, rounds run
+ and the stop reason — the round ``selection.json`` names when the run
+ was packaged, else :func:`pick`'s;
+* :func:`package` ``deliverable/`` for one round, the texture pass on it when asked, and
+ ``selection.json`` (round, method, scores) beside ``record.json``.
+
+Nothing here runs during a run: ``3dcode make`` calls :func:`pick` + :func:`package` after the
+track returns (unless ``--no-pick``).
+"""
+
+from __future__ import annotations
+
+import logging
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+from codeverse3d.contracts.common import TRACK_INFO, Usage
+from codeverse3d.contracts.run import PairwiseNote, RunRecord
+from codeverse3d.cost.context import call_context
+from codeverse3d.cost.types import Role, Stage
+from codeverse3d.judges.base import judged_subset, resolve_paths
+from codeverse3d.proc import EventLog, read_json_or_none
+from codeverse3d.record.deliverable import build_deliverable, round_outputs, texture_report_for
+from codeverse3d.record.record import effective_judgment, load_record, package_run
+from codeverse3d.workspace import Workspace
+
+log = logging.getLogger(__name__)
+
+SELECTION_NAME = "selection.json"
+#: |Δscore| at or below this is judge noise: ``by="pairwise"`` asks the pairwise judge
+PAIRWISE_MARGIN = 0.03
+#: the runner-up replaces the top-scored round only when the pairwise judge is this sure
+PAIRWISE_MIN_CONFIDENCE = 0.6
+
+PickBy = Literal["score", "pairwise"]
+#: how ``selection.json``'s round was chosen: by score, by the pairwise judge, or named (``--round``)
+Method = Literal["score", "pairwise", "round"]
+
+
+class RoundRow(BaseModel):
+ """One saved round, as a reader needs it."""
+
+ index: int
+ kind: str = ""
+ score: float | None = Field(default=None, description="effective judged score; None = unjudged or a degraded verdict")
+ passed: bool | None = Field(default=None, description="the judge's own verdict for THIS round (None = unjudged)")
+ gate_errors: int = 0
+ build_ok: bool | None = None
+ commit: str = ""
+ cost_usd: float = 0.0
+ minutes: float = 0.0
+
+
+class RunSummary(BaseModel):
+ """A run in one line — no pass/fail: the scores say how it went."""
+
+ rounds: int = Field(default=0, description="rounds run (the baseline included)")
+ stop_reason: str = ""
+ baseline_score: float | None = Field(default=None, description="round 0's effective score")
+ picked_round: int | None = None
+ picked_score: float | None = None
+ delta: float | None = Field(default=None, description="picked − baseline, when both were judged")
+ method: Method = "score"
+
+
+class Selection(BaseModel):
+ """``selection.json``: which round ``deliverable/`` holds, and why."""
+
+ round: int
+ method: Method
+ scores: dict[int, float | None] = Field(default_factory=dict, description="every round's effective score")
+ textured: bool = Field(default=False, description="the deliverable carries a shipped texture pack of this round")
+ selected_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
+
+
+# --------------------------------------------------------------------------- rows
+def _load(run_dir: Path | str, record: RunRecord | None) -> RunRecord:
+ return record if record is not None else load_record(Workspace(run_dir))
+
+
+def round_rows(run_dir: Path | str, *, record: RunRecord | None = None) -> list[RoundRow]:
+ """One row per round of the run's ``record.json`` (``record=`` skips re-reading it)."""
+ rows = []
+ for r in _load(run_dir, record).rounds:
+ j = effective_judgment(r)
+ rows.append(RoundRow(index=r.index, kind=r.kind, score=j.overall if j else None, passed=j.passed if j else None,
+ gate_errors=sum(len(g.errors) for g in r.gates),
+ build_ok=None if r.build is None else r.build.ok, commit=r.commit,
+ cost_usd=round(r.usage.cost_usd, 6), minutes=round(r.duration_s / 60.0, 2)))
+ return rows
+
+
+def _ranked(rows: list[RoundRow]) -> list[RoundRow]:
+ """Judged rounds, best first: highest score, then fewer gate errors, then the earlier round."""
+ return sorted((r for r in rows if r.score is not None), key=lambda r: (-(r.score or 0.0), r.gate_errors, r.index))
+
+
+# --------------------------------------------------------------------------- pick
+def pick(run_dir: Path | str, *, by: PickBy = "score", pairwise_model: str | None = None,
+ record: RunRecord | None = None, judge: Any | None = None) -> int | None:
+ """The round to hand over, or None when no round was judged.
+
+ ``by="pairwise"``: when the top two scores are within :data:`PAIRWISE_MARGIN`, the
+ pairwise judge (``pairwise_model``, default the run's judge; ``judge`` injects one)
+ compares their renders and the runner-up wins only with confidence ≥
+ :data:`PAIRWISE_MIN_CONFIDENCE`. A verdict already paid for this pair is re-read,
+ never re-bought."""
+ rec = _load(run_dir, record)
+ ranked = _ranked(round_rows(run_dir, record=rec))
+ if not ranked:
+ return None
+ top = ranked[0]
+ if by != "pairwise" or len(ranked) < 2 or (top.score or 0.0) - (ranked[1].score or 0.0) > PAIRWISE_MARGIN:
+ return top.index
+ note = pairwise_verdict(Workspace(run_dir), rec, top.index, ranked[1].index,
+ model=pairwise_model or rec.spec.backends.judge, judge=judge)
+ return ranked[1].index if note.accepted else top.index
+
+
+def pairwise_verdict(ws: Workspace, rec: RunRecord, a: int, b: int, *, model: str, judge: Any | None = None) -> PairwiseNote:
+ """Does round ``b`` beat round ``a``? Position-swapped pairwise judge, one paid verdict
+ per (pair, model), cached at ``artifacts/judge/rAA_vs_rBB_pairwise.json``. A judge
+ outage keeps ``a`` (never a worse pick for a failed call)."""
+ cache = ws.judge_path(a, f"_vs_r{b:02d}_pairwise")
+ stored = read_json_or_none(cache) or {}
+ if stored.get("model") == model and isinstance(stored.get("note"), dict):
+ return PairwiseNote.model_validate(stored["note"])
+ rounds = {r.index: r for r in rec.rounds}
+ renders = [judged_subset(resolve_paths(ws, rounds[i].renders)) for i in (a, b)]
+ note = PairwiseNote(a=f"r{a:02d}", b=f"r{b:02d}")
+ if renders[0] is None or renders[1] is None:
+ note.error = "a round has no renders to compare"
+ return note
+ try:
+ if judge is None:
+ from codeverse3d.judges.pairwise import PairwiseJudge
+
+ judge = PairwiseJudge(model)
+ with call_context(stage=Stage.PAIRWISE, role=Role.JUDGE, label="pick"):
+ res = judge.compare(rec.spec, renders[0], renders[1],
+ rubric=str(rec.extra.get("rubric") or TRACK_INFO[rec.spec.track].rubric))
+ except Exception as e: # noqa: BLE001 — an outage must not move the pick
+ log.warning("pairwise pick failed: %s", e)
+ note.error = f"{type(e).__name__}: {e}"
+ return note
+ note.winner, note.confidence = res.winner, float(res.confidence or 0.0)
+ note.reasons, note.usage, note.error = list(res.reasons or [])[:6], res.usage or Usage(), res.error or ""
+ note.accepted = note.winner == "b" and note.confidence >= PAIRWISE_MIN_CONFIDENCE
+ ws.write_json(cache, {"model": model, "note": note.model_dump(mode="json")})
+ EventLog(ws.events_path).emit("pick.pairwise", a=a, b=b, winner=note.winner, confidence=note.confidence,
+ accepted=note.accepted, cost_usd=round(note.usage.cost_usd, 4))
+ return note
+
+
+# --------------------------------------------------------------------------- summarise
+def load_selection(ws: Workspace) -> Selection | None:
+ data = read_json_or_none(ws.root / SELECTION_NAME)
+ try:
+ return Selection.model_validate(data) if data is not None else None
+ except ValueError: # a hand-edited file must not break every reader
+ return None
+
+
+def summarise(run_dir: Path | str, *, record: RunRecord | None = None) -> RunSummary:
+ """The run in one line. The picked round is the one ``selection.json`` names (what was
+ packaged), else what :func:`pick` chooses by score."""
+ rec = _load(run_dir, record)
+ rows = round_rows(run_dir, record=rec)
+ by_index = {r.index: r for r in rows}
+ sel = load_selection(Workspace(run_dir))
+ if sel is not None and sel.round in by_index:
+ picked, method = sel.round, sel.method
+ else:
+ picked, method = pick(run_dir, record=rec), "score"
+ baseline = by_index[0].score if 0 in by_index else None
+ score = by_index[picked].score if picked is not None else None
+ return RunSummary(rounds=len(rows), stop_reason=str(rec.extra.get("stop_reason") or rec.status.value),
+ baseline_score=baseline, picked_round=picked, picked_score=score, method=method,
+ delta=round(score - baseline, 6) if score is not None and baseline is not None else None)
+
+
+# --------------------------------------------------------------------------- package
+def package(run_dir: Path | str, round_index: int, *, texture: bool = False, method: Method = "round",
+ image_model: Any | None = None) -> Path:
+ """Write ``deliverable/`` for round ``round_index`` (from its commit and ``artifacts/rNN/``,
+ no rebuild) and ``selection.json``; returns the deliverable directory.
+
+ ``texture=True`` runs the texture pass on that round's own GLB first, unless a pass
+ already started from those exact bytes (a paid pass is never bought twice); a pack
+ ships into the deliverable only when its judge gate shipped it."""
+ ws = Workspace(run_dir)
+ rec = load_record(ws)
+ rnd = next((r for r in rec.rounds if r.index == round_index), None)
+ if rnd is None:
+ raise ValueError(f"no round {round_index} in {ws.root} (rounds: {[r.index for r in rec.rounds]})")
+ if texture:
+ rec = _texture(ws, rec, round_index, image_model=image_model)
+ manifest = build_deliverable(ws, rec, round_index)
+ sel = Selection(round=round_index, method=method, scores={r.index: r.score for r in round_rows(ws.root, record=rec)},
+ textured=any(f.path == "deliverable/object_textured.glb" for f in manifest.files))
+ ws.write_json(ws.root / SELECTION_NAME, sel)
+ EventLog(ws.events_path).emit("pick.packaged", round=round_index, method=method, textured=sel.textured,
+ files=len(manifest.files))
+ return ws.deliverable
+
+
+def _texture(ws: Workspace, rec: RunRecord, index: int, *, image_model: Any | None) -> RunRecord:
+ """The texture pass on round ``index``'s GLB; returns the record as the pass left it."""
+ from codeverse3d.texturing.run import texture_pass, texture_supported
+
+ if not texture_supported(rec.spec.track):
+ raise ValueError(f"the texture pass is for object tracks; {rec.spec.track.value} runs have no GLB to texture")
+ rnd = next(r for r in rec.rounds if r.index == index)
+ out = round_outputs(ws, rnd)
+ glb = out / "object.glb" if out is not None else None
+ if glb is None or not glb.is_file():
+ raise ValueError(f"round {index} kept no object.glb to texture (artifacts/r{index:02d}/)")
+ if texture_report_for(ws, glb) is not None:
+ EventLog(ws.events_path).emit("texture.skipped", reason="already_textured_this_artifact", round=index)
+ return rec
+ sheet = ws.rebase(rnd.renders.contact_sheet) if rnd.renders is not None and rnd.renders.contact_sheet else None
+ events = EventLog(ws.events_path)
+ try:
+ texture_pass(ws, rec.spec, rec.plan, model_id=rec.spec.backends.planner, image_model=image_model, judge=True,
+ judge_model_id=rec.spec.backends.judge, glb_in=glb, sheet=sheet, events=events, update_record=True)
+ except Exception as e: # noqa: BLE001 — a derived asset pack: the hand-over goes out without it
+ log.warning("texture pass failed on round %d: %s", index, e)
+ events.emit("texture.failed", round=index, error=f"{type(e).__name__}: {e}")
+ return rec
+ rec = load_record(ws) # the pass wrote extra["texturing"]; its spend is post-run: refresh telemetry/
+ package_run(ws, rec)
+ ws.write_json(ws.record_path, rec)
+ return rec
diff --git a/harness/codeverse3d/cli/layout_cmd.py b/harness/codeverse3d/cli/layout_cmd.py
index 7cdee685..f2b96f08 100644
--- a/harness/codeverse3d/cli/layout_cmd.py
+++ b/harness/codeverse3d/cli/layout_cmd.py
@@ -87,7 +87,7 @@ def print_deliverable(ws: Workspace, record: RunRecord) -> None:
head = {"prompt": spec.prompt, "track": spec.track.value, "language": spec.language.value,
"status": record.status.value, "best round": record.best_round,
"score": fmt_score(record.final_score), "workspace": ws.root}
- d = load_deliverable(ws, record)
+ d = load_deliverable(ws)
if d is not None:
head["code"] = f"{d.entry or 'deliverable/src/'} @ {d.commit[:12] or '-'} ({d.code_source})"
head["total"] = f"{len(d.files)} files, {_human_bytes(d.total_bytes)}"
diff --git a/harness/codeverse3d/cli/main.py b/harness/codeverse3d/cli/main.py
index 43072421..04f14a62 100644
--- a/harness/codeverse3d/cli/main.py
+++ b/harness/codeverse3d/cli/main.py
@@ -4,8 +4,8 @@ Thin by design: every command builds typed inputs and calls into the harness
packages through function-local imports, so ``3dcode --help`` loads none of them.
Owns the typer app and every registration, the run-starting commands ``make`` /
-``resume`` (spec building, reference grounding, track dispatch, budget raising) and
-``mcp``. The run-inspecting commands ``status`` / ``render`` / ``judge`` live in the
+``resume`` (spec building, reference grounding, track dispatch, budget raising, and the
+hand-over after the run), ``pick`` and ``mcp``. The run-inspecting commands ``status`` / ``render`` / ``judge`` live in the
sibling ``cli/inspect_cmd.py`` and are registered here, the way ``layout_cmd.py``'s
``show`` is.
"""
@@ -364,7 +364,15 @@ def make(
bool,
typer.Option(
"--texture",
- help="run the text-to-image texture pass after the rounds (frozen on spec.options)",
+ help="texture the picked round after the run (frozen on spec.options)",
+ ),
+ ] = False,
+ no_pick: Annotated[
+ bool,
+ typer.Option(
+ "--no-pick",
+ help="stop after the rounds: no round is picked, no deliverable/ is written "
+ "(`3dcode pick <slug>` does it later)",
),
] = False,
seed: Annotated[int, typer.Option("--seed")] = 0,
@@ -481,7 +489,7 @@ def make(
if no_run:
ok(f"spec written: {ws.spec_path} (not run; `3dcode resume {run_slug}` to start)")
return
- _run_track(spec, ws, resume=False, candidates=candidates)
+ _run_track(spec, ws, resume=False, candidates=candidates, pick=not no_pick)
def _ground_in_reference(spec: Spec, ws, *, n_views: int) -> Spec:
@@ -516,7 +524,8 @@ def _ground_in_reference(spec: Spec, ws, *, n_views: int) -> Spec:
return grounded
-def _run_track(spec: Spec, ws, *, resume: bool, candidates: int | None = None, force: bool = False) -> None:
+def _run_track(spec: Spec, ws, *, resume: bool, candidates: int | None = None, force: bool = False,
+ pick: bool = True) -> None:
from codeverse3d.cost.instrument import run_ledger
from codeverse3d.tracks import get_track
@@ -542,11 +551,40 @@ def _run_track(spec: Spec, ws, *, resume: bool, candidates: int | None = None, f
raise C.CliError(
f"run failed: {type(e).__name__}: {e} (workspace {ws.root}; see events.jsonl)"
) from e
+ if pick: # the hand-over: the best-scored round → deliverable/ (+ its texture pass)
+ with run_ledger(ws.root, run=ws.root.name):
+ _pick_and_package(ws, by="score", texture=_texture_requested(spec))
print_record_summary(record, ws.root)
if record.status.value == "failed":
raise typer.Exit(code=1)
+def _texture_requested(spec: Spec) -> bool:
+ from codeverse3d.texturing.run import texture_requested
+
+ return texture_requested(spec)
+
+
+def _pick_and_package(ws, *, by: str, texture: bool, round_index: int | None = None,
+ judge_model: str | None = None) -> int | None:
+ """``codeverse3d.addons.select``: choose the round (or take ``round_index``) and package it."""
+ from codeverse3d.addons import select
+
+ idx = round_index if round_index is not None else select.pick(ws.root, by=by, pairwise_model=judge_model)
+ if idx is None:
+ warn("no round was judged, so none was picked: name one with `3dcode pick <slug> --round N`")
+ return None
+ try:
+ select.package(ws.root, idx, texture=texture, method="round" if round_index is not None else by)
+ except ValueError as e:
+ raise C.CliError(str(e), code=2) from e
+ ok(f"picked round {idx} ({'named' if round_index is not None else f'by {by}'}) → {ws.deliverable}")
+ sel = select.load_selection(ws)
+ if texture and sel is not None and not sel.textured:
+ warn("the texture pass did not ship a pack for this round (see `3dcode texture show` / events.jsonl)")
+ return idx
+
+
def _finished_reason(ws, raised: dict) -> str:
"""Why this run must not be re-entered, or "" when resuming it is meaningful.
@@ -605,6 +643,7 @@ def resume(
"under rounds/pre_force/ and the run re-plans from the edited spec",
),
] = False,
+ no_pick: Annotated[bool, typer.Option("--no-pick", help="do not pick + package a round afterwards")] = False,
) -> None:
"""Resume an interrupted / partial run (or start a `--no-run` one).
@@ -640,7 +679,41 @@ def resume(
spec = spec.model_copy(update={"budget": spec.budget.model_copy(update=raised)})
ws.write_json(ws.spec_path, spec)
EventLog(ws.events_path).emit("budget.raised", **raised)
- _run_track(spec, ws, resume=True, candidates=candidates, force=force)
+ _run_track(spec, ws, resume=True, candidates=candidates, force=force, pick=not no_pick)
+
+
+def pick(
+ slug: str,
+ by: Annotated[str, typer.Option("--by", help="score | pairwise (the pairwise judge decides "
+ "between the top two when they are within judge noise)")] = "score",
+ round_index: Annotated[int | None, typer.Option("--round", min=0, help="hand over this round instead")] = None,
+ texture: Annotated[bool, typer.Option("--texture", help="texture the picked round first (object tracks)")] = False,
+ judge: Annotated[str | None, typer.Option("--judge", help="pairwise judge model (default: the run's judge)")] = None,
+ runs_dir: RunsDirOpt = None,
+) -> None:
+ """Choose the round of a finished run to hand over and package it: deliverable/ + selection.json."""
+ from codeverse3d.addons import select
+ from codeverse3d.cost.instrument import run_ledger
+ from codeverse3d.record.record import RecordError
+
+ if by not in ("score", "pairwise"):
+ raise C.CliError(f"--by must be score or pairwise, not {by!r}", code=2)
+ ws = C.open_workspace(slug, runs_dir)
+ # writes deliverable/ + selection.json (a texture pass or a pairwise verdict is paid):
+ # one writer per run dir, and the money joins the run's ledger
+ with (C.mutating(ws, what=f"3dcode pick {ws.root.name}", action="pick"),
+ run_ledger(ws.root, run=ws.root.name, create=False)):
+ try:
+ idx = _pick_and_package(ws, by=by, texture=texture, round_index=round_index, judge_model=judge)
+ rows = select.round_rows(ws.root)
+ except RecordError as e:
+ raise C.CliError(str(e), code=2) from e
+ if idx is None:
+ raise typer.Exit(code=1)
+ console.print(kv_table("rounds (* = picked)", {
+ f"r{r.index:02d}{' *' if r.index == idx else ''}": f"{r.kind:<9} score {C.fmt_score(r.score)} "
+ f"gate errors {r.gate_errors} {C.fmt_usd(r.cost_usd)}" for r in rows}))
# --------------------------------------------------------------------------- status / render / judge
diff --git a/harness/codeverse3d/contracts/run.py b/harness/codeverse3d/contracts/run.py
index fe092976..acad4a2b 100644
--- a/harness/codeverse3d/contracts/run.py
+++ b/harness/codeverse3d/contracts/run.py
@@ -374,6 +374,4 @@ class RunRecord(BaseModel):
error: str = ""
telemetry: RunTelemetry | None = Field(
default=None, description="settings snapshot + cost ledger + environment (written by finalize_record)")
- deliverable: RunDeliverable | None = Field(
- default=None, description="what to hand over: paths + hashes + sizes under deliverable/")
extra: dict[str, Any] = Field(default_factory=dict)
diff --git a/harness/codeverse3d/record/deliverable.py b/harness/codeverse3d/record/deliverable.py
index aa775e52..9d6aaa2f 100644
--- a/harness/codeverse3d/record/deliverable.py
+++ b/harness/codeverse3d/record/deliverable.py
@@ -141,7 +141,7 @@ def _code_tree(ws: Workspace, rnd: RoundRecord | None) -> tuple[dict[str, bytes]
return {}, "working_tree"
-def _round_outputs(ws: Workspace, rnd: RoundRecord | None) -> Path | None:
+def round_outputs(ws: Workspace, rnd: RoundRecord | None) -> Path | None:
"""Where the round's build outputs are: ``artifacts/rNN/``, or — a run recorded before
rounds kept their own (2026-09-22) — ``artifacts/`` itself, but only for the round
that run's finalise rebuilt there (the ``best_round`` its record.json still names)."""
@@ -154,19 +154,21 @@ def _round_outputs(ws: Workspace, rnd: RoundRecord | None) -> Path | None:
return ws.artifacts if legacy == rnd.index else None
-def _texture_is_for(ws: Workspace, glb: Path) -> bool:
- """Did the SHIPPED texture pass start from these exact bytes? The report names the GLB
- it consumed; a pack made mid-round, or for another round, is not this round's."""
+def texture_report_for(ws: Workspace, glb: Path) -> dict | None:
+ """The texture report (raw ``artifacts/textures/texturing.json``) of a pass that started
+ from these exact GLB bytes, else None. The report names the GLB it consumed; a pack made
+ mid-round, or for another round, is not this round's."""
from codeverse3d.texturing.run import report_path
rep = read_json_or_none(report_path(ws)) or {}
- src = ws.rebase(str(rep.get("glb_in") or "")) if rep.get("glb_in") else None
- return (bool(rep.get("shipped")) and src is not None and src.is_file() and glb.is_file()
- and sha256_file(src) == sha256_file(glb))
+ src = ws.rebase(str(rep["glb_in"])) if rep.get("glb_in") else None
+ if src is None or not src.is_file() or not glb.is_file() or sha256_file(src) != sha256_file(glb):
+ return None
+ return rep
def _copy_artifacts(ws: Workspace, record: RunRecord, rnd: RoundRecord | None, w: _Writer) -> None:
- out = _round_outputs(ws, rnd)
+ out = round_outputs(ws, rnd)
if out is None:
return
for name, role in _ARTIFACT_ROLES:
@@ -180,7 +182,7 @@ def _copy_artifacts(ws: Workspace, record: RunRecord, rnd: RoundRecord | None, w
w.add_file(src, f"frames/{src.name}", "frames")
tex = record.extra.get("texturing") or {}
# old layout: the one canonical pack belonged to the one round finalise rebuilt
- shipped = tex.get("shipped") if out == ws.artifacts else _texture_is_for(ws, out / "object.glb")
+ shipped = tex.get("shipped") if out == ws.artifacts else (texture_report_for(ws, out / "object.glb") or {}).get("shipped")
if shipped:
w.add_file(ws.artifacts / "object_textured.glb", "object_textured.glb", "model")
tex_dir = ws.root / str(tex.get("textures_dir") or "artifacts/textures")
@@ -247,10 +249,8 @@ def build_deliverable(ws: Workspace, record: RunRecord, round_index: int | None,
return manifest # exactly what is on disk: len(files) and total_bytes == sum(f.bytes)
-def load_deliverable(ws: Workspace, record: RunRecord | None = None) -> RunDeliverable | None:
- """``record.deliverable`` when present, else ``deliverable/manifest.json``, else None."""
- if record is not None and record.deliverable is not None:
- return record.deliverable
+def load_deliverable(ws: Workspace) -> RunDeliverable | None:
+ """``deliverable/manifest.json`` (the round ``codeverse3d.addons.select`` packaged), else None."""
path = ws.deliverable_manifest_path
if not path.is_file():
return None
diff --git a/harness/codeverse3d/record/record.py b/harness/codeverse3d/record/record.py
index 872a96fd..0bda4386 100644
--- a/harness/codeverse3d/record/record.py
+++ b/harness/codeverse3d/record/record.py
@@ -3,10 +3,10 @@
``finalize_record`` is the last step of every track run: it fills the
environment (tool versions + harness git sha), derives best/baseline/final
scores and totals when the track left them empty, adds a compact per-round
-summary under ``record.extra["rounds_summary"]``, packages the run
-(``deliverable/`` + ``telemetry/``, see docs/RUN_LAYOUT.md) and writes
-``record.json`` atomically. Packaging is best-effort: a run is never failed
-by it.
+summary under ``record.extra["rounds_summary"]``, writes ``telemetry/`` (see
+docs/RUN_LAYOUT.md) and writes ``record.json`` atomically. ``deliverable/`` is not
+the run's: which round to hand over is ``codeverse3d.addons.select``'s question
+(2026-09-22). Telemetry is best-effort: a run is never failed by it.
"""
from __future__ import annotations
@@ -252,11 +252,10 @@ def complexity_block(record: RunRecord) -> dict[str, Any] | None:
# --------------------------------------------------------------------------- io
def package_run(ws: Workspace, record: RunRecord) -> None:
- """Materialise ``deliverable/`` + ``telemetry/`` and mirror them onto the record.
+ """Materialise ``telemetry/`` and mirror it onto the record.
- Best-effort by contract: a packaging failure is logged and the run still
- gets its ``record.json`` (the old layout is always enough to read a run)."""
- from codeverse3d.record.deliverable import build_deliverable
+ Best-effort by contract: a failure is logged and the run still gets its
+ ``record.json`` (the old layout is always enough to read a run)."""
from codeverse3d.record.telemetry import build_telemetry
try:
@@ -264,18 +263,14 @@ def package_run(ws: Workspace, record: RunRecord) -> None:
except OSError as e: # read-only mount, exotic filesystem
log.warning("run layout not created in %s: %s", ws.root, e)
return
- try:
- record.deliverable = build_deliverable(ws, record, best_round_index(record))
- except Exception as e: # noqa: BLE001 - never fail a finished run over packaging
- log.warning("deliverable not built for %s: %s", ws.root, e)
try:
record.telemetry = build_telemetry(ws, record)
- except Exception as e: # noqa: BLE001
+ except Exception as e: # noqa: BLE001 - never fail a finished run over accounting
log.warning("telemetry not written for %s: %s", ws.root, e)
def finalize_record(ws: Workspace, record: RunRecord) -> Path:
- """Fill derived fields + environment, package the run and write ``record.json``."""
+ """Fill derived fields + environment, write ``telemetry/`` and ``record.json``."""
record.workspace = record.workspace or str(ws.root)
fill_derived(record)
package_run(ws, record)
diff --git a/harness/codeverse3d/texturing/run.py b/harness/codeverse3d/texturing/run.py
index 8e5b9d39..9e85a543 100644
--- a/harness/codeverse3d/texturing/run.py
+++ b/harness/codeverse3d/texturing/run.py
@@ -173,6 +173,7 @@ def texture_pass(
judge_model_id: str | None = None,
rubric: str | None = None,
glb_in: Path | None = None,
+ sheet: Path | None = None,
views: Sequence[ViewPreset] = OBJECT_VIEWS_QUICK,
size: int = 1024,
plan_model: Any | None = None,
@@ -189,7 +190,8 @@ def texture_pass(
textured and no seam failed); ``judge_obj`` replaces the constructed
``VlmJudge`` (tests). ``services`` bundles the five injectable dependencies
(image_model / plan_model / render / cache_dir / judge_obj); explicit
- keyword arguments win over the bundle.
+ keyword arguments win over the bundle. ``sheet`` is the contact sheet the material
+ planner looks at — the round being textured; the latest round's otherwise.
``normalise=True`` first runs the deterministic material normaliser
(:func:`codeverse3d.texturing.apply.normalise_materials`) over the input GLB,
@@ -213,8 +215,8 @@ def texture_pass(
notes: list[str] = []
events.emit("texture.start", model=model_id, glb=glb_in.name)
- # 1. renders for the planner (reuse the latest sheet; else a quick render)
- sheet = latest_sheet(ws)
+ # 1. renders for the planner (the round's own sheet, else the latest; else a quick render)
+ sheet = sheet if sheet is not None and Path(sheet).is_file() else latest_sheet(ws)
if sheet is None:
rs = _render_quick(glb_in, tex_dir / "planner_views", views, render)
sheet = Path(rs.contact_sheet) if rs.contact_sheet else (Path(rs.views[0].path) if rs.views else None)
diff --git a/harness/codeverse3d/tracks/lifecycle.py b/harness/codeverse3d/tracks/lifecycle.py
index 82405eda..70a4fd4e 100644
--- a/harness/codeverse3d/tracks/lifecycle.py
+++ b/harness/codeverse3d/tracks/lifecycle.py
@@ -38,7 +38,7 @@ from codeverse3d.orchestrator import (
hash_inputs,
plan_refine_groups,
)
-from codeverse3d.proc import EventLog, read_json_or_none
+from codeverse3d.proc import EventLog
from codeverse3d.prompts import render
from codeverse3d.tracks.candidates import choose_best_round, replay_best_round, run_best_of_n
from codeverse3d.tracks.common import (
@@ -708,10 +708,8 @@ class BaseTrack:
# left (the prior-record merge would otherwise carry it forward); no-rebuild
# resumes keep the prior flag — the artifact may still be the missing one
ctx.extra["finalise_rebuild_failed"] = ""
- if rounds and not rebuild_err and self._texture_wanted(ctx):
- self._texture_pass(ctx)
ctx.state.status, ctx.state.stop_reason, ctx.state.error = status, status.value, error
- self._save_budget(ctx) # saves state too — AFTER the texture pass charged
+ self._save_budget(ctx) # saves state too
rec = self._record(ctx, rounds, status, error=error)
self.services.finalize_record(ctx.ws, rec)
ctx.events.emit("run.done", status=status.value, best_round=rec.best_round,
@@ -730,90 +728,6 @@ class BaseTrack:
log.warning("changed_files failed in finalise: %s", e)
return False
- @staticmethod
- def _texture_wanted(ctx: RunContext) -> bool:
- """``codeverse3d.texturing.run.texture_requested`` is the single owner of this
- decision (spec.options.texture / the legacy tag) — the same predicate the
- ``texture_pass`` spatial tool asks, so a ``texture: false`` run cannot be
- textured from inside an agent session either."""
- try:
- from codeverse3d.texturing.run import texture_requested
-
- return texture_requested(ctx.spec)
- except Exception as e: # noqa: BLE001 — texturing is optional; never block finalise
- log.debug("texture_requested unavailable: %s", e)
- return bool(ctx.spec.options.texture)
-
- def _texture_pass(self, ctx: RunContext) -> None:
- """Optional post-hoc texture pass (``Spec.options.texture``). Additive: any
- failure is logged + emitted, never fatal.
-
- Its usage goes through the SAME guard as everything else (stage ``texture``,
- role ``image``) so it lands in ``record.total_usage`` and in the ledger — four
- post-hoc passes on ``furn_hard_rolltop_desk`` ($0.656) were invisible to both
- (docs/COST.md §6). It is charged without enforcement: the run is finalising,
- the tiles are already paid for, and raising here would throw away the pack."""
- if self._already_textured(ctx):
- # An agent can call the `texture_pass` spatial tool during a round; the
- # finalise hook must not buy the same pack a second time (a texture pass
- # is $0.10-0.30 and the input GLB is unchanged). The tool no longer writes
- # record.json mid-session (control files have one owner), so the report is
- # collected into the record here.
- ctx.events.emit("texture.skipped", reason="already_textured_this_artifact")
- try: # a malformed report must not block finalise
- from codeverse3d.texturing.run import load_report, texturing_extra
-
- ctx.extra["texturing"] = texturing_extra(ctx.ws, load_report(ctx.ws))
- except Exception: # noqa: BLE001
- log.warning("tool-textured report could not be collected into the record")
- return
- try:
- from codeverse3d.texturing.run import texture_pass
-
- trep = texture_pass(ctx.ws, ctx.spec, ctx.plan, model_id=ctx.spec.backends.planner, judge=True,
- judge_model_id=ctx.spec.backends.judge, rubric=self.rubric, events=ctx.events,
- update_record=False)
- except Exception as e: # noqa: BLE001 — texturing is a derived asset pack, never run-fatal
- log.warning("texture pass failed: %s", e)
- ctx.events.emit("texture.failed", error=f"{type(e).__name__}: {e}")
- return
- ctx.budget.add(trep.usage, stage="texture")
- ctx.extra["texturing"] = trep.summary()
- if not ctx.budget.ok():
- # visible, but NOT `budget.exceeded`: that event means "the loop stopped",
- # and a texture pass runs after the loop has already finished.
- ctx.events.emit("budget.overrun", stage="texture",
- reason=f"the texture pass took the run past its wall-clock ceiling "
- f"(spent ${ctx.budget.spent.cost_usd:.3f})",
- spent_usd=round(ctx.budget.spent.cost_usd, 4))
-
- @staticmethod
- def _already_textured(ctx: RunContext) -> bool:
- """True when a texture pass already ran against the current ``object.glb``.
-
- The report (``artifacts/textures/texturing.json``) records the GLB it consumed
- — reading it at ``artifacts/texturing.json`` made this guard dead code and the
- finalise pass double-bought every tool-textured pack (review of PR #3); the
- hook compares content hashes so a texture pass from an EARLIER round (whose
- GLB has since been rebuilt) does not suppress the final one."""
- import hashlib
-
- from codeverse3d.texturing.run import report_path
-
- report = report_path(ctx.ws)
- glb = ctx.ws.artifacts / "object.glb"
- if not report.is_file() or not glb.is_file():
- return False
- try:
- data = read_json_or_none(report) or {}
- prev = Path(str(data.get("glb_in") or ""))
- if not prev.is_file():
- return False
- digest = lambda p: hashlib.sha256(p.read_bytes()).hexdigest() # noqa: E731
- return digest(prev) == digest(glb)
- except Exception: # noqa: BLE001 — a malformed report must not block texturing
- return False
-
def _record(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, error: str) -> RunRecord:
best = ctx.state.best_round
baseline = rounds[0].score if rounds else None
@@ -828,8 +742,6 @@ class BaseTrack:
"n_candidates": ctx.policy.n_candidates,
"candidates": ctx.ws.read_json(cands) if cands.is_file() else None,
"cost_by_stage": ctx.budget.stage_summary()}
- if ctx.extra.get("texturing"):
- extra["texturing"] = ctx.extra["texturing"]
if ctx.extra.get("finalise_rebuild_failed"):
extra["finalise_rebuild_failed"] = ctx.extra["finalise_rebuild_failed"]
if ctx.extra.get("aborted_rounds"):
diff --git a/harness/codeverse3d/workspace.py b/harness/codeverse3d/workspace.py
index 3a363683..7dbc1f6c 100644
--- a/harness/codeverse3d/workspace.py
+++ b/harness/codeverse3d/workspace.py
@@ -222,7 +222,7 @@ class Workspace:
def round_artifacts(self, round_index: int) -> Path:
"""``artifacts/rNN/`` — the round's own copy of the build outputs a hand-over needs
- (``record.deliverable.keep_round_artifacts``; docs/RUN_LAYOUT.md)."""
+ (``codeverse3d.record.deliverable.keep_round_artifacts``; docs/RUN_LAYOUT.md)."""
return self.artifacts / f"r{round_index:02d}"
def trajectory_dir(self, stage: str, round_index: int) -> Path:
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index 20e4bf2a..b8512b53 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -202,7 +202,10 @@ codeverse3d/
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/ = below
+ skill_targets.py (measured targets + claims per skill bundle);
+ select.py (round_rows / pick / summarise / package: which round of a
+ finished run to hand over, deliverable/ + selection.json for it —
+ `3dcode pick`, and `3dcode make` after the run); gallery/ = below
addons/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 +
diff --git a/harness/tests/core/test_addons_boundary.py b/harness/tests/core/test_addons_boundary.py
index 8f216ecf..93b8dfe8 100644
--- a/harness/tests/core/test_addons_boundary.py
+++ b/harness/tests/core/test_addons_boundary.py
@@ -25,5 +25,5 @@ def test_nothing_outside_the_cli_imports_an_addon() -> None:
def test_the_addons_are_the_ones_the_docstring_lists() -> None:
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 names == ["calibration", "costreport", "dataset", "gallery", "select", "skill_targets"]
assert all(f"``{n}``" in (codeverse3d.addons.__doc__ or "") for n in names)
diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.py
index b3848ef3..32a3bead 100644
--- a/harness/tests/core/test_run_layout.py
+++ b/harness/tests/core/test_run_layout.py
@@ -70,16 +70,17 @@ def test_gitignore_covers_the_derived_buckets(tmp_path: Path):
def test_record_blocks_are_additive(tmp_path: Path):
- """An old record.json (no telemetry / deliverable) must still validate."""
+ """An old record.json (no telemetry; or a deliverable block, which records stopped
+ carrying on 2026-09-22) must still validate, and an old manifest still loads."""
spec = Spec(id="x", track="static_object", language="blender", prompt="a chair")
- old = {"spec": spec.model_dump(mode="json"), "workspace": str(tmp_path), "status": "passed"}
+ old = {"spec": spec.model_dump(mode="json"), "workspace": str(tmp_path), "status": "passed",
+ "deliverable": {"best_round": 1, "commit": "abc"}}
rec = RunRecord.model_validate(old)
- assert rec.telemetry is None and rec.deliverable is None
+ assert rec.telemetry is None and rec.status.value == "stopped"
rec.telemetry = RunTelemetry()
- rec.deliverable = RunDeliverable.model_validate({"best_round": 1, "commit": "abc"}) # a pre-2026-09-22 manifest
again = RunRecord.model_validate_json(rec.model_dump_json())
- assert again.deliverable is not None and again.deliverable.round == 1
assert again.telemetry is not None and again.telemetry.schema_version == 1
+ assert RunDeliverable.model_validate({"best_round": 1, "commit": "abc"}).round == 1 # a pre-2026-09-22 manifest
# --------------------------------------------------------------------------- relocation
diff --git a/harness/tests/flywheel_cli/test_captions.py b/harness/tests/flywheel_cli/test_captions.py
index 55f5b076..40d9a6e5 100644
--- a/harness/tests/flywheel_cli/test_captions.py
+++ b/harness/tests/flywheel_cli/test_captions.py
@@ -41,7 +41,11 @@ class FakeModel:
def test_caption_sample_stores_and_writes(fake_run):
+ from codeverse3d.addons import select
+ from codeverse3d.record.deliverable import load_deliverable
+
ws, rec = fake_run
+ select.package(ws.root, 1) # a round was handed over: its deliverable/ must follow the caption
m = FakeModel([GOOD])
caps = caption_sample(ws, rec, "fake:fake", model=m)
assert caps.detailed.startswith("A four-legged")
@@ -56,10 +60,11 @@ def test_caption_sample_stores_and_writes(fake_run):
assert again.extra["captions"]["provenance"]["captioner"] == "fake:fake"
assert again.extra["captions"]["provenance"]["cost_usd"] == pytest.approx(0.001)
# a caption changes the hand-over folder too — it used to leave deliverable/,
- # the manifest, record.deliverable and telemetry/ describing an uncaptioned run
+ # the manifest and telemetry/ describing an uncaptioned run
assert json.loads((ws.deliverable / "captions.json").read_text())["factory"] == GOOD["factory"]
- assert again.deliverable is not None and again.telemetry is not None
- assert "deliverable/captions.json" in {f.path for f in again.deliverable.files}
+ handed = load_deliverable(ws)
+ assert handed is not None and handed.round == 1 and again.telemetry is not None
+ assert "deliverable/captions.json" in {f.path for f in handed.files}
def test_caption_cmd_writes_the_captioner_row_into_the_run_ledger(fake_run, monkeypatch):
@@ -68,10 +73,12 @@ def test_caption_cmd_writes_the_captioner_row_into_the_run_ledger(fake_run, monk
from typer.testing import CliRunner
import codeverse3d.models.registry as R
+ from codeverse3d.addons import select
from codeverse3d.cli.main import app
from codeverse3d.cost.ledger import open_run_ledger
ws, rec = fake_run
+ select.package(ws.root, 1)
ledger = open_run_ledger(ws.root) # the run already keeps one (create=False appends)
ledger.path.touch()
monkeypatch.setattr(R, "_build_chat_model", lambda _mid: FakeModel([GOOD]))
diff --git a/harness/tests/flywheel_cli/test_run_layout_cli.py b/harness/tests/flywheel_cli/test_run_layout_cli.py
index 6011c4cb..4cfa1440 100644
--- a/harness/tests/flywheel_cli/test_run_layout_cli.py
+++ b/harness/tests/flywheel_cli/test_run_layout_cli.py
@@ -1,5 +1,5 @@
-"""deliverable/ + telemetry/ packaging, `3dcode show`, and export / gallery on BOTH
-layouts (old runs must keep working)."""
+"""deliverable/ (addons/select.package) + telemetry/ (record.package_run), `3dcode show`, and
+export / gallery on BOTH layouts (old runs must keep working)."""
from __future__ import annotations
@@ -9,6 +9,7 @@ from pathlib import Path
from typer.testing import CliRunner
+from codeverse3d.addons import select
from codeverse3d.addons.dataset.export import export_samples
from codeverse3d.addons.gallery import build_static
from codeverse3d.addons.gallery.index import entry_from_record
@@ -54,13 +55,15 @@ def old_layout_run(tmp_path: Path, slug: str = "wooden_chair_ab12cd34") -> tuple
# --------------------------------------------------------------------------- packaging
def test_package_run_builds_a_stable_independent_and_loadable_handover(fake_run):
ws, rec = fake_run
- assert load_telemetry(ws, rec) is None and load_deliverable(ws, rec) is None
+ assert load_telemetry(ws, rec) is None and load_deliverable(ws) is None
assert deliverable_path(ws, "object.glb") == ws.artifacts / "object.glb"
# Cross the old hard-link fast-path threshold before packaging.
(ws.artifacts / "object.glb").write_bytes(b"glTF" + b"\0" * (300 * 1024))
package_run(ws, rec)
- assert rec.deliverable is not None and rec.telemetry is not None
- d = rec.deliverable
+ assert rec.telemetry is not None and load_deliverable(ws) is None # the run packages no round
+ select.package(ws.root, 1)
+ d = load_deliverable(ws)
+ assert d is not None
roles = {f.role for f in d.files}
# the manifest does NOT list itself: no file can carry its own hash, and the
# returned object used to have one more file (and a smaller total) than the disk
@@ -83,7 +86,7 @@ def test_package_run_builds_a_stable_independent_and_loadable_handover(fake_run)
assert deliverable_path(ws, "nope.glb") is None
# Rebuilding unchanged content is byte-for-byte stable.
- first = rec.deliverable
+ first = d
files_before = sorted(p.relative_to(ws.deliverable).as_posix() for p in ws.deliverable.rglob("*") if p.is_file())
second = build_deliverable(ws, rec, 1)
files_after = sorted(p.relative_to(ws.deliverable).as_posix() for p in ws.deliverable.rglob("*") if p.is_file())
@@ -93,8 +96,8 @@ def test_package_run_builds_a_stable_independent_and_loadable_handover(fake_run)
# Package metadata can be recovered from files even before the caller saves rec.
bare = load_record(ws)
- assert bare.telemetry is None and bare.deliverable is None
- assert load_telemetry(ws, bare) is not None and load_deliverable(ws, bare) is not None
+ assert bare.telemetry is None
+ assert load_telemetry(ws, bare) is not None and load_deliverable(ws) is not None
# Delivered assets are copies: editing a hand-over cannot mutate evidence.
delivered = ws.deliverable / "object.glb"
@@ -178,6 +181,7 @@ def _show(slug: str, runs_dir: Path, *args: str):
def test_show_sections_and_status_share_the_packaged_run(fake_run):
ws, rec = fake_run
package_run(ws, rec)
+ select.package(ws.root, 1)
r = _show(ws.root.name, ws.root.parent)
assert r.exit_code == 0, r.output
out = r.output
@@ -216,6 +220,7 @@ def test_export_and_gallery_on_both_layouts(tmp_path: Path):
ws_new, rec_new = make_fake_run(runs, "run_new")
package_run(ws_new, rec_new)
ws_new.write_json(ws_new.record_path, rec_new)
+ select.package(ws_new.root, 1)
ws_old, _ = make_fake_run(runs, "run_old")
strip_layout(ws_old)
@@ -245,6 +250,7 @@ def test_export_falls_back_to_the_packaged_snapshot_without_git(tmp_path: Path):
ws, rec = make_fake_run(runs, "run_new")
package_run(ws, rec)
ws.write_json(ws.record_path, rec)
+ select.package(ws.root, 1)
shutil.rmtree(ws.root / ".git") # a run copied without its history
rep = export_samples(runs, tmp_path / "ds")
assert rep.n_exported == 1, rep.skipped
diff --git a/harness/tests/flywheel_cli/test_select.py b/harness/tests/flywheel_cli/test_select.py
new file mode 100644
index 00000000..3ebf5207
--- /dev/null
+++ b/harness/tests/flywheel_cli/test_select.py
@@ -0,0 +1,244 @@
+"""``codeverse3d.addons.select``: which round of a finished run is handed over, and how
+(``round_rows`` / ``pick`` / ``summarise`` / ``package``, ``3dcode pick``, ``make --no-pick``)."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+from typer.testing import CliRunner
+
+from codeverse3d.addons import select
+from codeverse3d.cli.main import app
+from codeverse3d.contracts.artifacts import (
+ BuildResult,
+ GateFinding,
+ GateReport,
+ Judgment,
+ RenderSet,
+ RenderView,
+ Severity,
+)
+from codeverse3d.contracts.common import Backends, Language, Track, Usage
+from codeverse3d.contracts.run import RoundRecord, RunRecord, RunStatus
+from codeverse3d.contracts.spec import Spec
+from codeverse3d.proc import EventLog
+from codeverse3d.workspace import Workspace
+
+from .conftest import make_fake_run, tiny_png
+
+runner = CliRunner()
+
+
+def _run(root: Path, rounds: list[tuple[float | str | None, int]], *, status: RunStatus = RunStatus.MAX_ROUNDS) -> Workspace:
+ """A finished run whose round i scored ``rounds[i][0]`` (None = unjudged, "degraded" = a
+ judge glitch) with ``rounds[i][1]`` gate errors; every round kept its own GLB."""
+ ws = Workspace(root).create()
+ spec = Spec(id=root.name, track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a stool",
+ backends=Backends(judge="fake:judge"))
+ ws.write_json(ws.spec_path, spec)
+ recs = []
+ for i, (score, errors) in enumerate(rounds):
+ (ws.src / "model.py").write_text(f"import bpy # round {i}\n")
+ commit = ws.commit(f"r{i:02d}")
+ views = [RenderView(name="front", path=str(tiny_png(ws.renders_dir(i) / "view_front.png")))]
+ kept = ws.round_artifacts(i) / "object.glb"
+ kept.parent.mkdir(parents=True, exist_ok=True)
+ kept.write_bytes(b"glTF\x02\x00\x00\x00" + bytes([i]) * 16)
+ if score == "degraded": # a judge glitch: paid for, never a score
+ j = Judgment(rubric="static_object_v1", scores={}, overall=0.0, passed=False,
+ summary="judge_error: 503", raw=json.dumps({"status": "degraded"}))
+ else:
+ j = None if score is None else Judgment(rubric="static_object_v1", scores={}, overall=score, passed=score >= 0.72)
+ gates = [GateReport(gate="contract", passed=not errors,
+ findings=[GateFinding(gate="contract", severity=Severity.ERROR, message="off")] * errors)]
+ recs.append(RoundRecord(index=i, kind="baseline" if i == 0 else "refine", commit=commit, judgment=j, gates=gates,
+ build=BuildResult(ok=True, language="blender"), duration_s=90.0,
+ renders=RenderSet(views=views, contact_sheet=str(tiny_png(ws.renders_dir(i) / "sheet.png"))),
+ usage=Usage(cost_usd=0.1 * (i + 1))))
+ ws.write_json(ws.record_path, RunRecord(spec=spec, workspace=str(ws.root), status=status, rounds=recs,
+ extra={"stop_reason": status.value, "rubric": "static_object_v1"}))
+ return ws
+
+
+# --------------------------------------------------------------------------- pick
[email protected]("rounds,want", [
+ ([(0.50, 0), (0.70, 0), (0.60, 0)], 1), # the highest judged score
+ ([(0.70, 2), (0.70, 0)], 1), # a tie: fewer gate errors
+ ([(0.70, 1), (0.70, 1), (0.65, 0)], 0), # a full tie: the earlier round
+ ([(0.40, 0), ("degraded", 0), (None, 0)], 0), # a glitch or no verdict is never a score
+ ([(None, 0), ("degraded", 0)], None), # no judged round: nothing to pick by score
+], ids=["score", "gate-errors", "earlier", "unjudged", "none-judged"])
+def test_pick_takes_the_best_score_then_fewer_gate_errors_then_the_earlier_round(tmp_path, rounds, want):
+ assert select.pick(_run(tmp_path / "r", rounds).root) == want
+
+
+def test_round_rows_carry_the_judges_own_verdict_per_round(tmp_path):
+ rows = select.round_rows(_run(tmp_path / "r", [(0.5, 0), (0.8, 2), ("degraded", 0)]).root)
+ assert [(r.index, r.score, r.passed, r.gate_errors) for r in rows] == [
+ (0, 0.5, False, 0), (1, 0.8, True, 2), (2, None, None, 0)]
+ assert rows[1].commit and rows[1].minutes == 1.5 and rows[1].cost_usd == pytest.approx(0.2)
+
+
+def test_summarise_is_baseline_pick_delta_rounds_and_the_stop_reason(tmp_path):
+ ws = _run(tmp_path / "r", [(0.5, 0), (0.8, 0), (0.6, 0)], status=RunStatus.BUDGET)
+ s = select.summarise(ws.root)
+ assert (s.rounds, s.stop_reason, s.baseline_score, s.picked_round, s.picked_score, s.method) == (
+ 3, "budget", 0.5, 1, 0.8, "score")
+ assert s.delta == pytest.approx(0.3)
+ # once a round is handed over, that round is the run's pick — whichever way it was chosen
+ select.package(ws.root, 2, method="round")
+ s = select.summarise(ws.root)
+ assert (s.picked_round, s.picked_score, s.method) == (2, 0.6, "round") and s.delta == pytest.approx(0.1)
+ none = select.summarise(_run(tmp_path / "n", [(None, 0)]).root)
+ assert (none.picked_round, none.picked_score, none.baseline_score, none.delta) == (None, None, None, None)
+
+
+def test_an_old_record_with_best_fields_still_summarises(tmp_path):
+ """A record.json written before 2026-09-22 (best_round / final_score / status 'passed')
+ loads — the extra keys are ignored, the status reads 'stopped', the stop reason stays."""
+ ws, _ = make_fake_run(tmp_path / "runs")
+ data = json.loads(ws.record_path.read_text())
+ data.update(status="passed", best_round=0, baseline_score=0.55, final_score=0.55)
+ data.setdefault("extra", {})["stop_reason"] = "pass"
+ ws.record_path.write_text(json.dumps(data))
+ s = select.summarise(ws.root)
+ assert (s.picked_round, s.stop_reason, s.baseline_score) == (1, "pass", 0.55)
+
+
+class _Pairwise:
+ def __init__(self, winner: str, confidence: float, *, fail: bool = False):
+ self.winner, self.confidence, self.fail, self.calls = winner, confidence, fail, []
+
+ def compare(self, spec, renders_a, renders_b, *, rubric):
+ self.calls.append((renders_a.views[0].path, renders_b.views[0].path, rubric))
+ if self.fail:
+ raise RuntimeError("judge down")
+ return SimpleNamespace(winner=self.winner, confidence=self.confidence, reasons=["r"], usage=Usage(cost_usd=0.05),
+ error="")
+
+
+def test_pick_by_pairwise_asks_only_inside_the_margin_and_never_buys_a_verdict_twice(tmp_path):
+ ws = _run(tmp_path / "r", [(0.70, 0), (0.72, 0)])
+ judge = _Pairwise("b", 0.9)
+ assert select.pick(ws.root, by="pairwise", judge=judge) == 0 # r00 is B, and B won
+ assert judge.calls and "/r01/" in judge.calls[0][0] and judge.calls[0][2] == "static_object_v1"
+ assert select.pick(ws.root, by="pairwise", judge=judge) == 0 and len(judge.calls) == 1 # cached, not re-bought
+ assert ws.judge_path(1, "_vs_r00_pairwise").is_file()
+ assert [e for e in EventLog(ws.events_path).read() if e["event"] == "pick.pairwise"]
+ # an unsure verdict, an outage or a clear gap keep the top score
+ assert select.pick(_run(tmp_path / "u", [(0.70, 0), (0.72, 0)]).root, by="pairwise", judge=_Pairwise("b", 0.5)) == 1
+ assert select.pick(_run(tmp_path / "f", [(0.70, 0), (0.72, 0)]).root, by="pairwise",
+ judge=_Pairwise("b", 0.9, fail=True)) == 1
+ far = _Pairwise("b", 0.99)
+ assert select.pick(_run(tmp_path / "g", [(0.60, 0), (0.72, 0)]).root, by="pairwise", judge=far) == 1 and not far.calls
+ assert select.pick(ws.root) == 1 # by score it is still the top score
+
+
+# --------------------------------------------------------------------------- package
+def test_package_hands_over_one_round_and_says_why(tmp_path):
+ ws = _run(tmp_path / "r", [(0.5, 0), (0.8, 0), (0.6, 0)])
+ out = select.package(ws.root, 1, method="score")
+ assert out == ws.deliverable and (out / "src" / "model.py").read_text() == "import bpy # round 1\n"
+ assert (out / "object.glb").read_bytes() == (ws.round_artifacts(1) / "object.glb").read_bytes()
+ sel = json.loads((ws.root / select.SELECTION_NAME).read_text())
+ assert (sel["round"], sel["method"], sel["textured"]) == (1, "score", False)
+ assert sel["scores"] == {"0": 0.5, "1": 0.8, "2": 0.6}
+ assert json.loads(ws.deliverable_manifest_path.read_text())["round"] == 1
+ with pytest.raises(ValueError, match="no round 7"):
+ select.package(ws.root, 7)
+
+
+def _fake_texture_pass(calls: list, *, shipped: bool = True, fail: bool = False):
+ import codeverse3d.texturing.run as trun
+
+ def run(ws, spec, plan, *, glb_in, sheet, update_record, **kw):
+ calls.append((Path(glb_in), Path(sheet)))
+ if fail:
+ raise RuntimeError("image model down")
+ report = trun.TextureReport(plan=trun.TexturePlan(), textures=trun.TextureSet(), seam=trun.SeamGateResult(),
+ glb_in=str(glb_in), shipped=shipped)
+ (ws.artifacts / trun.TEXTURED_GLB).write_bytes(b"glTF textured")
+ ws.write_json(trun.report_path(ws), report)
+ if update_record:
+ trun.record_texturing(ws, report)
+ return report
+
+ return run
+
+
+def test_package_textures_the_rounds_own_glb_once(tmp_path, monkeypatch):
+ import codeverse3d.texturing.run as trun
+
+ ws = _run(tmp_path / "r", [(0.5, 0), (0.8, 0)])
+ calls: list = []
+ monkeypatch.setattr(trun, "texture_pass", _fake_texture_pass(calls))
+ select.package(ws.root, 0, texture=True)
+ assert calls == [(ws.round_artifacts(0) / "object.glb", ws.renders_dir(0) / "sheet.png")] # round 0, not the last
+ assert (ws.deliverable / "object_textured.glb").is_file()
+ assert json.loads((ws.root / select.SELECTION_NAME).read_text())["textured"] is True
+ assert json.loads(ws.record_path.read_text())["extra"]["texturing"]["shipped"] is True
+ select.package(ws.root, 0, texture=True)
+ assert len(calls) == 1, "a pass already made from these bytes is never bought again"
+ # another round's hand-over does not carry round 0's pack
+ select.package(ws.root, 1)
+ assert not (ws.deliverable / "object_textured.glb").exists()
+
+
+def test_a_failed_texture_pass_does_not_stop_the_hand_over(tmp_path, monkeypatch):
+ import codeverse3d.texturing.run as trun
+
+ ws = _run(tmp_path / "r", [(0.5, 0)])
+ monkeypatch.setattr(trun, "texture_pass", _fake_texture_pass([], fail=True))
+ select.package(ws.root, 0, texture=True)
+ assert (ws.deliverable / "object.glb").is_file() and not (ws.deliverable / "object_textured.glb").exists()
+ assert json.loads((ws.root / select.SELECTION_NAME).read_text())["textured"] is False
+ assert "texture.failed" in [e["event"] for e in EventLog(ws.events_path).read()]
+
+
+# --------------------------------------------------------------------------- CLI
+def test_pick_command_by_score_by_round_and_by_pairwise(tmp_path, monkeypatch):
+ runs = tmp_path / "runs"
+ ws = _run(runs / "stool", [(0.70, 0), (0.72, 0), (0.50, 0)])
+ r = runner.invoke(app, ["pick", "stool", "--runs-dir", str(runs)])
+ assert r.exit_code == 0, r.output
+ assert "picked round 1" in r.output and json.loads((ws.root / "selection.json").read_text())["round"] == 1
+ r = runner.invoke(app, ["pick", "stool", "--runs-dir", str(runs), "--round", "2"])
+ assert r.exit_code == 0 and json.loads((ws.root / "selection.json").read_text())["method"] == "round"
+ assert (ws.deliverable / "src" / "model.py").read_text() == "import bpy # round 2\n"
+
+ import codeverse3d.judges.pairwise as pw
+
+ monkeypatch.setattr(pw, "PairwiseJudge", lambda model: _Pairwise("b", 0.95))
+ r = runner.invoke(app, ["pick", "stool", "--runs-dir", str(runs), "--by", "pairwise", "--judge", "fake:pairwise"])
+ assert r.exit_code == 0, r.output
+ sel = json.loads((ws.root / "selection.json").read_text())
+ assert (sel["round"], sel["method"]) == (0, "pairwise")
+ assert runner.invoke(app, ["pick", "stool", "--runs-dir", str(runs), "--by", "vibes"]).exit_code == 2
+ assert runner.invoke(app, ["pick", "stool", "--runs-dir", str(runs), "--round", "9"]).exit_code == 2
+
+ _run(runs / "blank", [(None, 0)])
+ r = runner.invoke(app, ["pick", "blank", "--runs-dir", str(runs)])
+ assert r.exit_code == 1 and "no round was judged" in r.output
+
+
+def test_make_hands_over_the_picked_round_unless_no_pick(tmp_path, monkeypatch):
+ import codeverse3d.tracks as tracks_pkg
+
+ class _Track:
+ def run(self, spec, ws, *, resume=False, force=False):
+ done = _run(ws.root, [(0.6, 0), (0.9, 0), (0.7, 0)])
+ return RunRecord.model_validate_json(done.record_path.read_text())
+
+ monkeypatch.setattr(tracks_pkg, "get_track", lambda track, **options: _Track())
+ runs = tmp_path / "runs"
+ r = runner.invoke(app, ["make", "a stool", "--runs-dir", str(runs), "--slug", "picked", "--language", "blender"])
+ assert r.exit_code == 0, r.output
+ assert json.loads((runs / "picked" / "selection.json").read_text())["round"] == 1
+ assert (runs / "picked" / "deliverable" / "src" / "model.py").read_text() == "import bpy # round 1\n"
+ r = runner.invoke(app, ["make", "a stool", "--runs-dir", str(runs), "--slug", "kept", "--language", "blender",
+ "--no-pick"])
+ assert r.exit_code == 0, r.output
+ assert not (runs / "kept" / "selection.json").exists() and not (runs / "kept" / "deliverable" / "manifest.json").exists()
diff --git a/harness/tests/orchestrator_tracks/test_budget_snapshot.py b/harness/tests/orchestrator_tracks/test_budget_snapshot.py
index 7431fde9..f9dc3c08 100644
--- a/harness/tests/orchestrator_tracks/test_budget_snapshot.py
+++ b/harness/tests/orchestrator_tracks/test_budget_snapshot.py
@@ -4,14 +4,12 @@ from __future__ import annotations
import json
from pathlib import Path
-from types import SimpleNamespace
import pytest
from codeverse3d.contracts.common import Budget, Language, Usage
from codeverse3d.contracts.plan import StaticPlan
from codeverse3d.contracts.run import RunStatus
-from codeverse3d.contracts.spec import RunOptions
from codeverse3d.orchestrator import BudgetExceeded, BudgetGuard, BudgetSnapshot, RunState
from codeverse3d.proc import EventLog
from codeverse3d.tracks.generation import GenerationTask, generate_files
@@ -96,33 +94,6 @@ def test_build_context_restores_the_budget_snapshot(tmp_path, settings):
assert ctx2.budget.billed_usd == pytest.approx(0.4)
-def test_the_texture_pass_spend_reaches_the_snapshot_a_resume_restores(tmp_path, chair_plan, settings, monkeypatch):
- """finalise saved the state BEFORE the texture pass charged, so the snapshot a resume
- restored was the PRE-texture one and a $0.12 pack simply vanished from the run's money
- (reproduced 2026-08-30: total_usage 0.217 with cost_by_stage[texture], 0.097 after)."""
- import codeverse3d.texturing.run as texrun
-
- monkeypatch.setattr(texrun, "texture_pass",
- lambda *a, **kw: SimpleNamespace(usage=Usage(backend="gemini", cost_usd=0.12),
- summary=lambda: {"shipped": True}))
- spec = make_spec(max_rounds=0, options=RunOptions(texture=True))
- ws = Workspace(tmp_path / "runs" / "tex")
- track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.6,)),
- agent=FakeAgent(lambda job, ws_: {"src/object.js": "export function build(THREE) "
- "{ return new THREE.Group(); }\n"}),
- planner_model=FakeChatModel(lambda req: chair_plan.model_dump(mode="json")),
- settings=settings, runtime=FakeRuntime(Language.THREEJS))
- rec = track.run(spec, ws)
- assert rec.extra["texturing"] == {"shipped": True}, "the pass must have run at all"
-
- snap = RunState.load(ws).extra["budget_snapshot"]
- assert snap["by_stage"]["texture"] == pytest.approx(0.12)
- assert snap["spent"]["cost_usd"] == pytest.approx(rec.total_usage.cost_usd, abs=1e-6)
- # and the guard a resume rebuilds starts from that number, not from the pre-texture one
- ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState.load(ws))
- assert ctx.budget.by_stage["texture"] == pytest.approx(0.12)
-
-
# --------------------------------------------------------------- ordering: single-shot
def test_a_paid_single_shot_response_is_persisted_when_the_budget_trips(tmp_path):
ws = Workspace(tmp_path / "ws").create()
diff --git a/harness/tests/orchestrator_tracks/test_fix_batch2.py b/harness/tests/orchestrator_tracks/test_fix_batch2.py
index 62fcef6d..a91ffb37 100644
--- a/harness/tests/orchestrator_tracks/test_fix_batch2.py
+++ b/harness/tests/orchestrator_tracks/test_fix_batch2.py
@@ -111,8 +111,7 @@ def test_a_failed_finalise_rebuild_cannot_finalize_silently(tmp_path, chair_plan
failed rebuild of the restored best round leaves object.glb MISSING — yet the run
used to finalize with final_score set, ``record.error == ""`` and a deliverable
with no model file. The earned status + judge scores are kept; the error and the
- ``finalise_rebuild_failed`` flag must say what happened, and the texture pass
- (whose input GLB is gone) must not charge image calls first."""
+ ``finalise_rebuild_failed`` flag must say what happened."""
import subprocess
class RebuildFailsRuntime(FakeRuntime):
@@ -125,11 +124,6 @@ def test_a_failed_finalise_rebuild_cannot_finalize_silently(tmp_path, chair_plan
error_message="runtime crashed on rebuild", error_file="src/object.js")
return super().build(ws, timeout_s=timeout_s)
- textured = []
- from codeverse3d.tracks.lifecycle import BaseTrack
- monkeypatch.setattr(BaseTrack, "_texture_wanted", staticmethod(lambda ctx: True))
- monkeypatch.setattr(BaseTrack, "_texture_pass", lambda self, ctx: textured.append(True))
-
spec = make_spec(max_rounds=2)
ws = Workspace(tmp_path / "runs" / "r")
track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.7, 0.5), targets=("Seat",)),
@@ -141,7 +135,6 @@ def test_a_failed_finalise_rebuild_cannot_finalize_silently(tmp_path, chair_plan
assert rec.error.startswith("finalise rebuild failed: Timeout")
assert "runtime crashed on rebuild" in rec.extra["finalise_rebuild_failed"]
assert not (ws.artifacts / "object.glb").is_file()
- assert textured == [], "the texture pass must not run against a missing GLB"
on_disk = json.loads(ws.record_path.read_text())
assert on_disk["error"].startswith("finalise rebuild failed") and on_disk["status"] == "max_rounds"
ev = [e for e in EventLog(ws.events_path).read() if e["event"] == "finalise.rebuild"]
diff --git a/harness/tests/orchestrator_tracks/test_integrations2.py b/harness/tests/orchestrator_tracks/test_integrations2.py
index de031d4f..1d4120d4 100644
--- a/harness/tests/orchestrator_tracks/test_integrations2.py
+++ b/harness/tests/orchestrator_tracks/test_integrations2.py
@@ -4,11 +4,8 @@ connectivity language, blender multi-file targets, texture hook."""
from __future__ import annotations
-from types import SimpleNamespace
-
-from codeverse3d.contracts.common import Language, Track, Usage
+from codeverse3d.contracts.common import Language, Track
from codeverse3d.contracts.plan import ScenePlan
-from codeverse3d.contracts.run import RunStatus
from codeverse3d.orchestrator import RunState
from codeverse3d.proc import EventLog
from codeverse3d.tracks import get_track
@@ -114,49 +111,19 @@ def test_blender_expected_files_and_whole_object_targets(tmp_path, chair_plan, s
assert fft("Seat") == ["src/parts/seat.py"]
-# --------------------------------------------------------------------- (f) texture hook in finalise
-def test_texture_tag_runs_texture_pass_and_records_summary(tmp_path, chair_plan, settings, monkeypatch):
- calls = {}
-
- def fake_texture_pass(ws, spec, plan, **kw):
- calls["kw"] = kw
- calls["ws"] = str(ws.root)
- return SimpleNamespace(usage=Usage(backend="fake", cost_usd=0.02),
- summary=lambda: {"shipped": True, "n_textures": 3})
-
- import codeverse3d.texturing.run as trun
-
- monkeypatch.setattr(trun, "texture_pass", fake_texture_pass)
- rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings, tags=["texture"])
- assert rec.extra["texturing"] == {"shipped": True, "n_textures": 3}
- assert calls["kw"]["judge"] is True and calls["kw"]["update_record"] is False
- assert calls["kw"]["rubric"] == "static_object_v1" and calls["kw"]["judge_model_id"] == "fake:judge"
- assert rec.total_usage.cost_usd >= 0.02 # texture usage charged into the totals
-
-
-def test_texture_pass_failure_is_additive_not_fatal(tmp_path, chair_plan, settings, monkeypatch):
- import codeverse3d.texturing.run as trun
-
- def boom(*a, **kw):
- raise RuntimeError("image model down")
-
- monkeypatch.setattr(trun, "texture_pass", boom)
- rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings, tags=["texture"])
- assert rec.status in (RunStatus.MAX_ROUNDS, RunStatus.BUDGET)
- assert "texturing" not in rec.extra
- kinds = [e["event"] for e in EventLog(ws.events_path).read()]
- assert "texture.failed" in kinds
-
-
-def test_untagged_run_never_calls_texture_pass(tmp_path, chair_plan, settings, monkeypatch):
+# --------------------------------------------------------------------- (f) no texture pass in the run
+def test_the_run_itself_never_textures_even_when_asked(tmp_path, chair_plan, settings, monkeypatch):
+ """The texture pass belongs to the hand-over of the PICKED round (addons/select.package,
+ `3dcode make` after the run), not to finalise (2026-09-22)."""
import codeverse3d.texturing.run as trun
def boom(*a, **kw):
- raise AssertionError("texture_pass must not run without the tag")
+ raise AssertionError("texture_pass must not run inside a run")
monkeypatch.setattr(trun, "texture_pass", boom)
- rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings)
- assert "texturing" not in rec.extra
+ for tags in ([], ["texture"]):
+ rec, ws, judge, services = _static_run(tmp_path / (tags[0] if tags else "plain"), chair_plan, settings, tags=tags)
+ assert "texturing" not in rec.extra
# --------------------------------------------------------------------- (i) graphics track still constructs through get_track
@@ -164,36 +131,3 @@ def test_get_track_graphics_accepts_options(settings):
t = get_track("graphics", settings=settings, n_candidates=2)
assert isinstance(t, GraphicsTrack) and t._n_candidates == 2
assert isinstance(get_track(Track.GRAPHICS), GraphicsTrack)
-
-
-def test_a_tool_textured_run_is_not_double_bought_and_still_records(tmp_path, chair_plan, settings, monkeypatch):
- """PR #3 review: the double-buy guard read ``artifacts/texturing.json`` while the
- report is written to ``artifacts/textures/texturing.json`` — dead code, so every
- re-finalise re-bought the pack; and the mid-session ``record.json`` write the tool
- used to make is now forbidden (control files have ONE owner during a session), so
- finalise must collect the report into ``extra['texturing']`` itself."""
- import codeverse3d.texturing.run as trun
-
- calls = []
-
- def fake_texture_pass(ws, spec, plan, **kw):
- calls.append(1)
- report = trun.TextureReport(
- plan=trun.TexturePlan(), textures=trun.TextureSet(), seam=trun.SeamGateResult(),
- glb_in=str(ws.artifacts / "object.glb"), shipped=True)
- ws.write_json(trun.report_path(ws), report.model_dump(mode="json"))
- return SimpleNamespace(usage=Usage(backend="fake", cost_usd=0.02),
- summary=lambda: {"shipped": True, "n_textures": 1})
-
- monkeypatch.setattr(trun, "texture_pass", fake_texture_pass)
- rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings, tags=["texture"])
- assert calls == [1] and rec.extra["texturing"]["shipped"] is True
-
- # a resume re-finalises: the guard must SKIP the pass (report's glb matches) and
- # still carry extra['texturing'] built from the report on disk
- track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.6,)), agent=FakeAgent(_agent_writer),
- planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
- runtime=FakeRuntime(Language.THREEJS))
- rec2 = track.run(make_spec(max_rounds=0, tags=["texture"]), ws, resume=True)
- assert calls == [1], "the pack must not be bought a second time"
- assert rec2.extra["texturing"]["shipped"] is True, "the report is collected into the record at finalise"
diff --git a/harness/tests/orchestrator_tracks/test_refactor_batch2.py b/harness/tests/orchestrator_tracks/test_refactor_batch2.py
index a7d0ca17..336a5ccb 100644
--- a/harness/tests/orchestrator_tracks/test_refactor_batch2.py
+++ b/harness/tests/orchestrator_tracks/test_refactor_batch2.py
@@ -5,7 +5,6 @@ from __future__ import annotations
from codeverse3d.contracts.artifacts import BuildResult, RenderSet, RenderView
from codeverse3d.contracts.common import Language, Track
from codeverse3d.contracts.plan import ScenePlan
-from codeverse3d.contracts.run import RunStatus
from codeverse3d.contracts.spec import RunOptions
from codeverse3d.orchestrator import RefineTask, RunState, plan_refine_groups
from codeverse3d.proc import EventLog
@@ -15,12 +14,9 @@ from codeverse3d.tracks.static_object import StaticObjectTrack
from codeverse3d.workspace import Workspace
from tests.orchestrator_tracks.conftest import make_spec
from tests.orchestrator_tracks.fakes import (
- FakeAgent,
FakeChatModel,
- FakeJudge,
FakeRuntime,
FakeServices,
- _planner,
)
@@ -62,31 +58,6 @@ def test_candidate_width_precedence(tmp_path, settings):
assert ctx.policy.n_candidates == 3
-def test_options_texture_triggers_texture_pass(tmp_path, chair_plan, settings, monkeypatch):
- calls = {}
-
- def fake_texture_pass(ws, spec, plan, **kw):
- from types import SimpleNamespace
-
- from codeverse3d.contracts.common import Usage
-
- calls["ws"] = str(ws.root)
- return SimpleNamespace(usage=Usage(backend="fake", cost_usd=0.01), summary=lambda: {"shipped": True})
-
- import codeverse3d.texturing.run as trun
-
- monkeypatch.setattr(trun, "texture_pass", fake_texture_pass)
- spec = make_spec(max_rounds=0, options=RunOptions(texture=True))
- ws = Workspace(tmp_path / "runs" / "r")
- track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.9,)), agent=FakeAgent(_writer),
- planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
- runtime=FakeRuntime(Language.THREEJS))
- rec = track.run(spec, ws)
- assert rec.status is RunStatus.MAX_ROUNDS
- assert calls, "options.texture must run the texture pass without the legacy tag"
- assert rec.extra.get("texturing") == {"shipped": True}
-
-
# --------------------------------------------------------------------- judge-view flags (F30 consumption)
def _rs(flags: list[bool | None]) -> RenderSet:
views = [RenderView(name=f"v{i}", path=f"/tmp/v{i}.png", judge=f) for i, f in enumerate(flags)]