Official Codebase of 3DCodeVerse
Python
tracks: a candidate is a round, and the profiles get their detail round back
gaoypeng21e4259ab605
diff --git a/harness/codeverse/orchestrator.py b/harness/codeverse/orchestrator.pyindex 73f7acdc..4671ee69 100644--- a/harness/codeverse/orchestrator.py+++ b/harness/codeverse/orchestrator.py@@ -15,7 +15,7 @@ import reimport threadingimport timefrom collections.abc import Callable, Sequence-from dataclasses import dataclass, replace+from dataclasses import dataclassfrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any, Literal, TypeVar@@ -28,6 +28,7 @@ from codeverse.contracts.plan import AcceptanceItem, Planfrom codeverse.contracts.run import RoundRecord, RunStatusfrom codeverse.conventions import to_snakefrom codeverse.cost.billing import bills_usd+from codeverse.cost.routing import JUDGE_NOISEfrom codeverse.proc import EventLogfrom codeverse.workspace import Workspace@@ -93,13 +94,11 @@ class RunState(BaseModel):ws.write_json(ws.state_path, self)# ----------------------------------------------------------------- helpers- def mark_round_done(self, index: int, commit: str, ws: Workspace | None = None) -> None:+ def mark_round_done(self, index: int, commit: str) -> None:if index not in self.completed_rounds:self.completed_rounds.append(index)self.round_commits[index] = commitself.current_round = index + 1- if ws is not None:- self.save(ws)def update_best(self, index: int, commit: str, score: float | None) -> bool:"""Record ``index`` as best; returns True when it changed."""@@ -451,14 +450,9 @@ REWRITE_KIND = "rewrite"#: ``RoundRecord.kind`` of the surface-detail round (see :func:`detail_round_due`)DETAIL_KIND = "detail"-#: ``Strategy`` → the ``RoundRecord.kind`` the loop stamps on the round it starts+#: ``Strategy`` → the ``RoundRecord.kind`` the loop stamps on the round it starts (unknown → refine)KIND_FOR_STRATEGY: dict[str, str] = {"same": "refine", "switch": REWRITE_KIND, "detail": DETAIL_KIND}--def kind_for_strategy(strategy: str) -> str:- """THE mapping from a stop decision's strategy to the round kind it produces."""- return KIND_FOR_STRATEGY.get(strategy, "refine")-#: σ for a judge that is not in the measured table: the default judge's#: (``gemini-3.1-pro-preview``, ``Settings.default_judge``), because that is what#: an unnamed judge almost always is. Calibrate a new judge@@ -477,11 +471,6 @@ def judge_sigma(judge_model: str = "", *, default: float = DEFAULT_JUDGE_SIGMA)name = (judge_model or "").strip().split(":")[-1]if not name:return default- try:- from codeverse.cost.routing import JUDGE_NOISE- except Exception as e: # noqa: BLE001 — the cost package is optional at import time- log.debug("judge noise table unavailable: %s", e)- return defaulthit = JUDGE_NOISE.get(name)if hit is None: # version suffixes: gemini-3.7-flash-002 → gemini-3.7-flashhit = next((v for k, v in JUDGE_NOISE.items() if name.startswith(k)), None)@@ -515,30 +504,18 @@ class RoundPolicy:# 0.479 mean score capped, against $1.360 at 0.684 uncapped — no saving and −0.205# score (docs/COST.md §17). 0 = no policy cap: the session runs under the backend's# own AgentJob.max_turns. Callers who want one set it explicitly (cost profiles do).- agent_max_turns: int = 0 # model turns one generation session may take (0 = uncapped)+ agent_max_turns: int = 0 # 0 = the backend's own AgentJob.max_turns (claude-code 60; the other vendors have no turn cap)agent_wrapup_turns: int = 6 # turns granted to land a final build + summary when a cap IS set# ---- depth. Measured (wave "generation-depth"): across 88 consecutive refine-round pairs the# built part count changed ZERO times and mean Δgeometry_detail was +0.003 — the refine loop is# a repair loop and never adds anything. The rounds that DID add geometry did it while assembly# was still broken and lost 0.075 of assembly_fit / 0.025 of overall for it. So detail gets its# own round, and it only runs once the structure gates are clean.- detail_rounds: int = 0 # surface-detail rounds a run may spend (0 = off; tracks that implement- # the round opt in — see lifecycle.BaseTrack.supports_detail_round)+ detail_rounds: int | None = None # surface-detail rounds a run may spend: 0 = off, None = the track's own+ # default (lifecycle.detail_round_budget; only tracks with the round get one)detail_min_score: float = 0.45 # below this the object is still wrong; detail would be polish on a mistakedetail_bbox_tol_m: float = 0.005 # a detail round that moves a part box by more than this failed its brief- def with_candidates(self, n: int | None) -> RoundPolicy:- """Copy with ``n_candidates`` set (``None`` → unchanged)."""- if n is None or n == self.n_candidates:- return self- return replace(self, n_candidates=max(1, int(n)))-- def with_judge(self, judge_model: str | None) -> RoundPolicy:- """Copy that knows which judge scores the rounds (its σ sizes both money stops)."""- if not judge_model or judge_model == self.judge_model:- return self- return replace(self, judge_model=judge_model)-@propertydef sigma(self) -> float:"""Measured judge noise for this run's judge (see :func:`judge_sigma`)."""@@ -591,10 +568,6 @@ class StopPolicy:def __init__(self, policy: RoundPolicy):self.policy = policy- def decide(self, history: Sequence[RoundRecord], *, budget_ok: bool = True) -> StopReason:- """The stop reason only (``evaluate`` also says what shape the next round takes)."""- return self.evaluate(history, budget_ok=budget_ok).reason-def evaluate(self, history: Sequence[RoundRecord], *, budget_ok: bool = True) -> StopDecision:if not budget_ok:return StopDecision("budget")@@ -713,10 +686,10 @@ def detail_blocked(history: Sequence[RoundRecord], policy: RoundPolicy) -> str:and is within one judge σ of the best round in the run. Anything else and themoney belongs to repair (measured: refine rounds that added > 2000 triangleswhile assembly was still broken lost 0.075 of assembly_fit)."""- if policy.detail_rounds <= 0:+ if (policy.detail_rounds or 0) <= 0:return "detail rounds disabled"spent = sum(1 for r in history if r.kind == DETAIL_KIND)- if spent >= policy.detail_rounds:+ if spent >= (policy.detail_rounds or 0):return f"{spent} detail round(s) already spent"if not history:return "no rounds yet"@@ -822,8 +795,6 @@ class BudgetGuard:start_time: float | None = None,*,soft_fraction: float = 1.0,- run: str = "",- ledger: str | Path | Any | None = None,):self.budget = budgetself.start_time = time.time() if start_time is None else start_time@@ -842,15 +813,12 @@ class BudgetGuard:self.soft_fraction = min(1.0, max(0.0, float(soft_fraction)))#: one-off extension of the HARD wall-clock ceiling (finalise/salvage headroom)self.grace_minutes = 0.0- #: run slug + ledger sink for the per-call rows (None = do not write a ledger)- self.run = run- self.ledger = ledger#: stage -> USD and round -> {stage -> USD}, so a round can report what it burnedself.by_stage: dict[str, float] = {}self.by_round: dict[int, dict[str, float]] = {}# ----------------------------------------------------------------- accounting- def spend(+ def charge(self,usage: Usage | None,*,@@ -861,12 +829,17 @@ class BudgetGuard:outcome: str = "ok",enforce: bool = True,) -> None:- """THE door every dollar goes through.-- Accumulates ``usage``, buckets it by ``stage`` (and by round), appends a- priced row to the run's cost ledger, and — when ``enforce`` — raises- ``BudgetExceeded`` if a hard ceiling is now crossed. Accounting never- fails a run: a broken ledger is logged, not propagated."""+ """THE door every dollar goes through — for bucketing and enforcement only.++ Accumulates ``usage``, buckets it by ``stage`` (and by round) and — when+ ``enforce`` — raises ``BudgetExceeded`` if a hard ceiling is now crossed.+ The ledger row is NOT written here: ``cost.instrument`` (MeteredAgent /+ MeteredChatModel) is the one writer, one priced row per real call. Until+ 2026-08-29 this method kept a second, aggregate writer that fired whenever no+ ``run_ledger()`` was active — a direct ``track.run()`` without the CLI, or any+ run with ``CV3D_COST_LEDGER=off`` (the guard's own ledger was opened+ unconditionally), so ledger-off runs of that era carry one unpriced row per+ charge; a ledger-off run now writes nothing at all."""if usage is None:returnwith self._lock:@@ -879,17 +852,9 @@ class BudgetGuard:if round_index is not None:per = self.by_round.setdefault(int(round_index), {})per[key] = per.get(key, 0.0) + float(usage.cost_usd)- self._ledger_row(- usage, stage=key, role=role, label=label, round_index=round_index, outcome=outcome- )if enforce:self.check()- def charge(self, usage: Usage | None, **kw: Any) -> None:- """Account for ``usage``, then enforce the ceilings (see :meth:`spend`)."""- kw.setdefault("enforce", True)- self.spend(usage, **kw)-def add(self, usage: Usage | None, **kw: Any) -> None:"""Account for ``usage`` WITHOUT enforcing the ceilings.@@ -897,55 +862,15 @@ class BudgetGuard:a pairwise tie-break, the texture pass): the money is spent either way,and raising here would throw away a finished, paid-for result. Theround loop stops at its next ``ok()`` check instead. The dollar is- still bucketed and still written to the ledger — "not enforced" never- means "not seen"."""+ still bucketed — "not enforced" never means "not seen"."""kw["enforce"] = False- self.spend(usage, **kw)-- def _ledger_row(- self,- usage: Usage,- *,- stage: str,- role: str | None,- label: str,- round_index: int | None,- outcome: str,- ) -> None:- if self.ledger is None:- return- try:- from codeverse.cost import per_call_metering, record_call-- # When the run is metered call by call (codeverse.cost.instrument wraps every- # ChatModel / CodingAgent), those rows already ARE this dollar with per-call- # tokens, cache hits and latency — one aggregate row on top would double count.- if per_call_metering():- return- record_call(- usage,- run=self.run,- stage=stage,- role=role,- round=round_index,- label=label,- backend=usage.backend,- model=usage.model,- outcome=outcome,- ledger=self.ledger,- )- except Exception as e: # noqa: BLE001 — accounting must never fail a run- log.debug("cost ledger row failed (%s): %s", self.ledger, e)+ self.charge(usage, **kw)def mark(self) -> Usage:"""Snapshot of the running total — diff it with :func:`usage_delta` to seewhat a round burned even when the round itself raised half-way."""return self.spent.model_copy(deep=True)- def round_costs(self, round_index: int) -> dict[str, float]:- """``{stage: USD}`` charged against one round index (empty when none)."""- return dict(self.by_round.get(int(round_index), {}))-# ----------------------------------------------------------------- resume snapshotdef snapshot(self) -> BudgetSnapshot:"""Point-in-time guard state for ``run_state.json`` so a resume continues the@@ -1035,7 +960,7 @@ class BudgetGuard:return Truedef remaining(self) -> dict[str, float]:- """Remaining headroom: ``{"usd": ..., "minutes": ..., "fraction": ...}``."""+ """Remaining wall clock: ``{"minutes": ..., "fraction": ...}`` (no money key since the USD ceiling went, fbf89a5)."""minutes = max(0.0, self.hard_minutes - self.elapsed_minutes())frac = minutes / self.hard_minutes if self.hard_minutes > 0 else 0.0return {"minutes": minutes, "fraction": frac}@@ -1081,7 +1006,7 @@ class BudgetSnapshot(BaseModel):billed_usd: floatcalls: intby_stage: dict[str, float]- #: matches the ``BudgetGuard.by_round`` / ``round_costs()`` shape+ #: matches the ``BudgetGuard.by_round`` shapeby_round: dict[int, dict[str, float]]active_s: floatdiff --git a/harness/codeverse/tracks/__init__.py b/harness/codeverse/tracks/__init__.pyindex 09160eea..c5fcacf7 100644--- a/harness/codeverse/tracks/__init__.py+++ b/harness/codeverse/tracks/__init__.py@@ -19,8 +19,9 @@ class TrackPipeline(Protocol):track: Trackrubric: str # judges/rubrics/<rubric>.yaml- def run(self, spec: Spec, ws: Workspace, *, resume: bool = False) -> RunRecord:- """Full pipeline: plan → baseline → rounds → finalise. Must be resumable."""+ def run(self, spec: Spec, ws: Workspace, *, resume: bool = False, force: bool = False) -> RunRecord:+ """Full pipeline: plan → baseline → rounds → finalise. Must be resumable;+ ``force`` re-plans a resumed run whose spec changed (archives the old rounds)."""...diff --git a/harness/codeverse/tracks/articulated_object.py b/harness/codeverse/tracks/articulated_object.pyindex d9bbbe60..9c384087 100644--- a/harness/codeverse/tracks/articulated_object.py+++ b/harness/codeverse/tracks/articulated_object.py@@ -27,7 +27,6 @@ from codeverse.contracts.plan import ArticulatedPlan, Planfrom codeverse.conventions import to_snakefrom codeverse.spatial.render import RenderErrorfrom codeverse.tracks.common import RunContext-from codeverse.tracks.prompting import language_system_promptfrom codeverse.tracks.static_object import ObjectPipeline, StaticObjectTrackfrom codeverse.workspace import Workspace@@ -99,9 +98,6 @@ class ArticulatedObjectTrack(StaticObjectTrack):def make_pipeline(self) -> ArticulatedPipeline:return ArticulatedPipeline()- def system_prompt(self, ctx: RunContext) -> str:- return language_system_prompt(ctx.language, tools=not ctx.single_shot)-# ----------------------------------------------------------------------------- sweep adapterdef default_joint_sweep(ws: Workspace, plan: Plan | None, out_dir: Path) -> tuple[GateReport, list[RenderView]]:diff --git a/harness/codeverse/tracks/candidates.py b/harness/codeverse/tracks/candidates.pyindex c6ebe7cc..0ded9c03 100644--- a/harness/codeverse/tracks/candidates.py+++ b/harness/codeverse/tracks/candidates.py@@ -3,7 +3,10 @@* ``run_best_of_n`` — N baseline candidates are generated IN PARALLEL, each inits own throw-away sub-workspace (``<ws>/_cand/c<k>``: own git repo, copy ofthe skeleton + spec + plan, own AGENTS.md/MCP config), built (+repair),- gated, quick-rendered (4 views) and quick-judged (n_samples=1). The winner+ gated, quick-rendered (4 views) and judged (n_samples=1) — the ordinary round+ (``steps._run_round``, kind ``candidate``) with two knobs turned: ``quick_render``+ in place of ``pipeline.render`` and no clay views. Each candidate's round trace+ goes to its own ``events.jsonl``; the run log carries ``candidate.*``. The winner(quick score → fewer gate errors; a pairwise tie-break when the top two arewithin judge noise) is copied back into the run workspace and the ordinaryround-0 pipeline (build → gates → 8-view render → full judge) runs on it.@@ -18,28 +21,27 @@ from __future__ import annotationsimport loggingimport shutil-import timefrom collections.abc import Callable, Sequencefrom dataclasses import replace+from functools import partialfrom pathlib import Pathfrom typing import Any, Literalfrom pydantic import BaseModel, Field-from codeverse.contracts.artifacts import GateReport, RenderSet+from codeverse.contracts.artifacts import BuildResult, Measurement, RenderSetfrom codeverse.contracts.common import Usagefrom codeverse.contracts.run import RoundRecordfrom codeverse.conventions import OBJECT_VIEWS_QUICK-from codeverse.orchestrator import BestSelector, BudgetExceeded-from codeverse.proc import fan_out+from codeverse.orchestrator import BestSelector, BudgetExceeded, gate_error_count+from codeverse.proc import EventLog, fan_outfrom codeverse.tracks.common import RunContextfrom codeverse.tracks.generation import GenerationTask-from codeverse.tracks.repair import build_with_repairfrom codeverse.tracks.steps import (RoundFailed,RoundPipeline,+ _run_round,round_record_path,- run_generation_tasks,run_round,)from codeverse.workspace import Workspace@@ -60,7 +62,20 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],subs = [make_candidate_context(track, ctx, k) for k in range(n)]def _one(k: int) -> tuple[CandidateRecord, RenderSet | None]:- return run_candidate(track, subs[k], k, tasks, pipeline, files_hint=files_hint)+ sub, label = subs[k], f"c{k}"+ ctx.events.emit("candidate.start", candidate=k, workspace=str(sub.ws.root))+ # kind="candidate" is what the cost ledger files the sessions under (Stage.CANDIDATE)+ tasks_k = [t.model_copy(update={"label": f"{t.label}_{label}", "kind": "candidate"}) for t in tasks]+ rec = _run_round(sub, index=0, kind="candidate", tasks=tasks_k, pipeline=pipeline, files_hint=list(files_hint),+ render=partial(quick_render, pipeline=pipeline), geometry_views=False)+ build_ok = rec.build is not None and rec.build.ok+ cand = CandidateRecord(index=k, label=label, workspace=str(sub.ws.root), commit=rec.commit, build_ok=build_ok,+ score=rec.score, gate_errors=gate_error_count(rec), usage=rec.usage,+ duration_s=rec.duration_s, sheet=(rec.renders.contact_sheet if rec.renders else "") or "",+ notes=rec.notes)+ ctx.events.emit("candidate.done", candidate=k, score=cand.score, build_ok=build_ok, gate_errors=cand.gate_errors,+ duration_s=cand.duration_s, cost_usd=round(rec.usage.cost_usd, 4), commit=rec.commit[:10])+ return cand, rec.rendersresults = fan_out(list(range(n)), _one, max_workers=ctx.settings.limits.max_parallel_agents, label="candidates",item_name=lambda k: f"c{k}")@@ -106,8 +121,6 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],ctx.ws.write_json(ctx.ws.root / "rounds" / "candidates.json",{"n": n, "selected": best, "candidates": [r.model_dump(mode="json") for r in records],"pairwise": note.model_dump(mode="json") if note else None})- ctx.state.extra["candidates"] = {"n": n, "selected": best,- "scores": {r.label: r.score for r in records}}ctx.events.emit("candidate.selected", round=0, candidate=best, label=records[best].label, score=records[best].score,build_ok=records[best].build_ok, scores={r.label: r.score for r in records},cost_usd=round(usage.cost_usd, 4))@@ -139,56 +152,16 @@ def make_candidate_context(track: Any, ctx: RunContext, k: int) -> RunContext:if path.is_file():shutil.copyfile(path, sub_ws.root / path.name)if not ctx.single_shot:- kind = ctx.agent_id.split(":", 1)[0]- ctx.services.materialize(sub_ws, agent_kind=kind, contract_md=track.agent_contract_md(ctx), cookbook_rel=ctx.cookbook_rel,- spatial_tools=True,- mcp_command=["python", "-m", "codeverse.spatial.mcp_server", "--workspace", str(sub_ws.root)])+ ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=track.agent_contract_md(ctx),+ cookbook_rel=ctx.cookbook_rel, spatial_tools=True)sub_ws.commit("skeleton")- return replace(ctx, ws=sub_ws, extra={})+ # own event log (the run log keeps only candidate.*) and a one-sample judge for ranking+ return replace(ctx, ws=sub_ws, extra={}, events=EventLog(sub_ws.events_path),+ judge=track.make_judge(ctx, n_samples=1))-def run_candidate(track: Any, sub: RunContext, k: int, tasks: Sequence[GenerationTask], pipeline: RoundPipeline, *,- files_hint: Sequence[str] = ()) -> tuple[CandidateRecord, RenderSet | None]:- """generate → build(+repair) → gates → quick 4-view render → quick judge, in the sub-workspace."""- t0 = time.time()- label = f"c{k}"- sub.events.emit("candidate.start", candidate=k, workspace=str(sub.ws.root))- rec = CandidateRecord(index=k, label=label, workspace=str(sub.ws.root))- usage = Usage()- tasks_k = [t.model_copy(update={"label": f"{t.label}_{label}"}) for t in tasks]- gens = run_generation_tasks(sub, tasks_k) # RoundFailed propagates → candidate failed- for g in gens:- usage = usage + g.usage- sub.ws.commit(f"{label}: generated")- outcome = build_with_repair(sub, round_index=0, label=label, files_hint=list(files_hint))- usage = usage + outcome.usage- rec.build_ok = outcome.build.ok- gates: list[GateReport] = [outcome.lint]- renders: RenderSet | None = None- if outcome.build.ok:- measurement = pipeline.measure(sub, outcome.build)- gates.extend(pipeline.gates(sub, 0, outcome.build, measurement))- renders = quick_render(sub, outcome.build.glb_path, pipeline=pipeline,- build=outcome.build, measurement=measurement)- if renders is not None and renders.views:- rec.sheet = renders.contact_sheet or ""- judgment = quick_judge(track, sub, pipeline, outcome.build, gates, measurement, renders)- if judgment is not None:- rec.score = judgment.overall- usage = usage + judgment.usage- else:- rec.notes = f"build failed: {outcome.build.error_type}: {outcome.build.error_message[:160]}"- rec.gate_errors = sum(len(g.errors) for g in gates)- rec.commit = sub.ws.commit(f"candidate {label}")- rec.usage = usage- rec.duration_s = round(time.time() - t0, 2)- sub.events.emit("candidate.done", candidate=k, score=rec.score, build_ok=rec.build_ok, gate_errors=rec.gate_errors,- duration_s=rec.duration_s, cost_usd=round(usage.cost_usd, 4), commit=rec.commit[:10])- return rec, renders---def quick_render(ctx: RunContext, glb_path: str | None, *, pipeline: RoundPipeline | None = None,- build: Any | None = None, measurement: Any | None = None) -> RenderSet | None:+def quick_render(ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None, *,+ pipeline: RoundPipeline | None = None) -> RenderSet | None:"""Cheap renders for ranking a candidate — by the route THIS track actually has.An object has a GLB and gets the reduced-view, reduced-resolution rig, which is the@@ -207,39 +180,25 @@ def quick_render(ctx: RunContext, glb_path: str | None, *, pipeline: RoundPipeliThat costs more than the quick rig; it costs less than paying for N generations andkeeping the first one blind."""- out_dir = ctx.ws.renders_dir(0) / "quick"+ out_dir = ctx.ws.renders_dir(round_index) / "quick"try:- if glb_path:- return ctx.services.render_object(Path(glb_path), out_dir, views=OBJECT_VIEWS_QUICK,- width=QUICK_PX, height=QUICK_PX)- if pipeline is None or build is None:+ if build.glb_path:+ rs = ctx.services.render_object(Path(build.glb_path), out_dir, views=OBJECT_VIEWS_QUICK,+ width=QUICK_PX, height=QUICK_PX)+ # ArticulatedPipeline.gates() parks its sweep views here for render() to pick up+ pose = ctx.extra.pop("pose_views", None)+ if pose:+ rs.views = list(rs.views) + list(pose)+ return rs+ if pipeline is None:return None- return pipeline.render(ctx, 0, build, measurement)+ return pipeline.render(ctx, round_index, build, measurement)except Exception as e: # noqa: BLE001 — a candidate without renders is ranked by gates onlylog.warning("quick render failed for %s: %s", ctx.ws.root, e)ctx.events.emit("candidate.render_failed", workspace=str(ctx.ws.root), error=f"{type(e).__name__}: {e}")return None-def quick_judge(track: Any, ctx: RunContext, pipeline: RoundPipeline, build: Any, gates: list[GateReport],- measurement: Any, renders: RenderSet) -> Any | None:- from codeverse.judges.base import JudgeInput-- try:- judge = track.make_judge(ctx, n_samples=1)- inp = JudgeInput(spec=ctx.spec, renders=renders, measurement=measurement, gates=gates,- acceptance=list(getattr(ctx.plan, "acceptance", []) or []), plan_summary=pipeline.plan_summary(ctx),- round_index=0, extra_context=pipeline.judge_context(ctx.ws, ctx.plan, 0, build, gates))- judgment = judge.judge(inp)- except Exception as e: # noqa: BLE001 — judge outage: candidate ranked by gates only- log.warning("quick judge failed for %s: %s", ctx.ws.root, e)- ctx.events.emit("candidate.judge_failed", workspace=str(ctx.ws.root), error=f"{type(e).__name__}: {e}")- return None- ctx.budget.add(judgment.usage) # verdict already paid for; the loop stops at its next check- ctx.ws.write_json(ctx.ws.judge_path(0, "_quick"), judgment)- return judgment--def select_candidate(ctx: RunContext, records: Sequence[CandidateRecord], renders: dict[int, RenderSet]) -> tuple[int, PairwiseNote | None]:"""Best candidate index (+ pairwise note when the top two were within judge noise)."""order = rank_candidates(records)@@ -253,7 +212,7 @@ def select_candidate(ctx: RunContext, records: Sequence[CandidateRecord], renderdecision, note = decide_best(a.score, b.score, margin=ctx.policy.pairwise_margin,min_confidence=ctx.policy.pairwise_min_confidence, compare=compare, labels=(a.label, b.label))if note is not None:- ctx.budget.add(note.usage) # post-hoc accounting of a finished comparison+ ctx.budget.add(note.usage, stage="judge", role="judge", round_index=0, label="pairwise") # post-hoc: a finished comparisonctx.events.emit("pairwise.done", stage="candidates", a=note.a, b=note.b, winner=note.winner, confidence=note.confidence,accepted=note.accepted, error=note.error, cost_usd=round(note.usage.cost_usd, 4))if decision == "pairwise":@@ -296,7 +255,7 @@ def choose_best_round(ctx: RunContext, rounds: list[RoundRecord], selector: Bestmin_confidence=ctx.policy.pairwise_min_confidence, compare=compare,labels=(f"r{incumbent:02d}", f"r{new_index:02d}"))if note is not None:- ctx.budget.add(note.usage) # post-hoc accounting of a finished comparison+ ctx.budget.add(note.usage, stage="judge", role="judge", round_index=new_index, label="pairwise") # post-hocnew.usage = new.usage + note.usagenew.notes = (new.notes + "; " if new.notes else "") + note.line()ctx.ws.write_json(round_record_path(ctx, new_index), new)@@ -318,10 +277,6 @@ def _pairwise_fn(ctx: RunContext, renders_a: RenderSet | None, renders_b: Renderreturn _compare-__all__ = ["CAND_DIR", "adopt_candidate", "choose_best_round", "make_candidate_context", "run_best_of_n", "run_candidate",- "select_candidate"]--# ===================================================================== decision logicclass CandidateRecord(BaseModel):"""One best-of-N baseline candidate (generated in its own sub-workspace)."""@@ -413,3 +368,7 @@ def decide_best(note.error = getattr(res, "error", "") or ""note.accepted = note.winner == "b" and note.confidence >= min_confidencereturn ("pairwise" if note.accepted else "keep"), note+++__all__ = ["CAND_DIR", "CandidateRecord", "PairwiseNote", "adopt_candidate", "choose_best_round", "decide_best",+ "make_candidate_context", "quick_render", "rank_candidates", "run_best_of_n", "select_candidate"]diff --git a/harness/codeverse/tracks/common.py b/harness/codeverse/tracks/common.pyindex 48e7bf92..fbbe0bcf 100644--- a/harness/codeverse/tracks/common.py+++ b/harness/codeverse/tracks/common.py@@ -1,13 +1,18 @@-"""Shared track machinery: the run context, lazily-bound services, prompt context.--``Services`` is the single seam between the tracks and the other packages-(models, agents, runtimes, spatial tools, judges, flywheel). Every method-imports lazily and raises a clear ``ServiceUnavailable`` when the package is-missing; tests subclass it with fakes. Nothing here touches a network.+"""Shared track machinery: the run context, the services seam, prompt context.++``Services`` is the tracks' injection seam: every call into a sibling package+(models, agents, runtimes, spatial tools, judges, flywheel) goes through one+method here so a test can subclass it with fakes (``tests/orchestrator_tracks/+fakes.py``) and an articulated test double can synthesise joint sweeps from the+plan. The targets are modules of this same package — never optional — and are+imported lazily only to keep ``tracks`` importable without loading Blender,+Chrome or a model client. ``ServiceUnavailable`` is what a FAKE raises for a+service the test did not provide. Nothing here touches a network."""from __future__ import annotations+import importlibimport loggingfrom collections.abc import Sequencefrom dataclasses import dataclass, field@@ -20,10 +25,11 @@ from codeverse.contracts.common import Language, Trackfrom codeverse.contracts.plan import CameraPlan, Planfrom codeverse.contracts.run import RunRecordfrom codeverse.conventions import ViewPreset-from codeverse.languages._docs import prompt_dir_for+from codeverse.languages import get_runtimefrom codeverse.orchestrator import BudgetGuard, RoundPolicy, RunStatefrom codeverse.proc import EventLogfrom codeverse.prompts import load_text, prompt_hash+from codeverse.prompts.catalog import prompt_dir_forfrom codeverse.tracks.generation import is_single_shotfrom codeverse.workspace import Workspace@@ -31,20 +37,12 @@ log = logging.getLogger(__name__)class ServiceUnavailable(RuntimeError):- """A sibling package this track depends on is not importable / not configured."""+ """A test double has no implementation for this service (``scene._assemble_stage``+ falls back to an agent compose session on it)."""def _import(path: str, name: str) -> Any:- import importlib-- try:- mod = importlib.import_module(path)- except ImportError as e:- raise ServiceUnavailable(f"{path} is not available ({e}); cannot call {name}") from e- try:- return getattr(mod, name)- except AttributeError as e:- raise ServiceUnavailable(f"{path}.{name} does not exist") from e+ return getattr(importlib.import_module(path), name)class Services:@@ -76,11 +74,7 @@ class Services:return _import("codeverse.languages", "get_runtime")(language)def rubric_threshold(self, rubric: str) -> float | None:- try:- r = _import("codeverse.judges.rubrics", "load_rubric")(rubric)- except ServiceUnavailable:- return None- return getattr(r, "pass_threshold", None)+ return getattr(_import("codeverse.judges.rubrics", "load_rubric")(rubric), "pass_threshold", None)# ---- spatialdef measure(self, glb: Path) -> Measurement:@@ -111,12 +105,8 @@ class Services:return _import("codeverse.spatial.frame_metrics", "frame_gate_from_renders")(renders)def select_judge_views(self, renders: RenderSet, max_n: int = 10) -> RenderSet:- """The ≤ ``max_n`` scene views a judge should see; identity when the helper is unavailable."""- try:- fn = _import("codeverse.spatial.render_scene", "select_judge_views")- except ServiceUnavailable:- return renders- return fn(renders, max_n=max_n)+ """The ≤ ``max_n`` scene views a judge should see."""+ return _import("codeverse.spatial.render_scene", "select_judge_views")(renders, max_n=max_n)def silhouette(self, render_png: Path | str, reference_png: Path | str) -> dict[str, Any]:"""Outline IoU of a render vs a reference image (``{iou, reliable, ...}``)."""@@ -135,11 +125,9 @@ class Services:return default_joint_sweep(ws, plan, out_dir)# ---- agents' workspace materialisation + tool cards- def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, cookbook_rel: str, spatial_tools: bool,- mcp_command: list[str]) -> None:+ def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, cookbook_rel: str, spatial_tools: bool) -> None:_import("codeverse.agents.materialize", "materialize_workspace")(- ws, agent_kind=agent_kind, contract_md=contract_md, cookbook_rel=cookbook_rel,- spatial_tools=spatial_tools, mcp_command=mcp_command)+ ws, agent_kind=agent_kind, contract_md=contract_md, cookbook_rel=cookbook_rel, spatial_tools=spatial_tools)def tool_cards(self, track: str, language: str) -> str:try:@@ -154,12 +142,7 @@ class Services:return fn(ws, plan, cameras="plan" if getattr(plan, "cameras", None) else "derive")def finalize_record(self, ws: Workspace, record: RunRecord) -> None:- try:- fn = _import("codeverse.flywheel.record", "finalize_record")- except ServiceUnavailable:- ws.write_json(ws.record_path, record)- return- fn(ws, record)+ _import("codeverse.flywheel.record", "finalize_record")(ws, record)# ----------------------------------------------------------------------------- context@@ -198,6 +181,11 @@ class RunContext:def single_shot(self) -> bool:return is_single_shot(self.agent_id)+ @property+ def agent_kind(self) -> str:+ """``gemini-cli`` of ``gemini-cli:gemini-3.7-flash``."""+ return self.agent_id.split(":", 1)[0]+def record_prompt(self, name: str, text: str) -> None:self.prompt_hashes[name] = prompt_hash(text)@@ -212,34 +200,10 @@ def load_prompt_or(rel: str, fallback: str) -> str:def language_contract(ctx_language: Language, runtime: Any) -> str:- """The language authoring contract: prompts/<dir>/contract.md → runtime.contract_doc() → minimal."""- text = load_prompt_or(f"{prompt_dir_for(ctx_language)}/contract.md", "")- if text.strip():- return text- doc = ""- if runtime is not None and hasattr(runtime, "contract_doc"):- try:- doc = runtime.contract_doc() or ""- except Exception as e: # noqa: BLE001- log.warning("runtime.contract_doc failed: %s", e)- return doc.strip() or _MINIMAL_CONTRACT.get(ctx_language, "Write raw code in the language's native frame; meters; named parts.")---_MINIMAL_CONTRACT: dict[Language, str] = {- Language.BLENDER: "src/model.py — pure bpy; Z-up, -Y front, meters; one named object per part (PascalCase); "- "no camera/light/render/export calls; do not import anything but bpy, bmesh, math, mathutils, random.",- Language.CADQUERY: "src/model.py — `import cadquery as cq` only; module-level `result` = cq.Assembly with named parts "- "(PascalCase) or a Workplane; Z-up, -Y front, meters.",- Language.THREEJS: "src/parts/<snake>.js each `export function build<Pascal>(THREE) → THREE.Group` at world pose; "- "src/object.js `export function build(THREE) → THREE.Group` adding every part; Y-up, +Z front, meters; "- "no DOM, no texture loading, no environment sniffing.",- Language.URDF_BLENDER: "src/model.py — pure bpy, one object per link named exactly as the link (PascalCase), Z-up, -Y front, "- "meters, authored at rest pose in WORLD coordinates; src/robot.urdf — native URDF, meshes as "- "meshes/<link>.glb, joint origins/axes in parent-link frames.",- Language.SCENE_THREEJS: "src/scene.js `export function createScene({THREE, renderer, loaders}) → {scene, cameras, update(t,dt)}`; "- "src/env.js, src/zones/*.js, src/assets/*.js (`export function build<Pascal>(THREE, opts)`), "- "src/shaders/*.js; Y-up, meters; `import * as THREE from 'three'` only; no DOM, no fetch.",-}+ """The language authoring contract, as the runtime states it (``LanguageRuntime.contract_doc``+ reads prompts/<dir>/contract.md). ONE lookup: a per-language prose fallback here restated+ frames/units — conventions.py's job (law 2) — and was unreachable anyway."""+ return (runtime or get_runtime(ctx_language)).contract_doc()def cookbook_rel_for(language: Language) -> str:diff --git a/harness/codeverse/tracks/generation.py b/harness/codeverse/tracks/generation.pyindex 928943c9..4c9d51f8 100644--- a/harness/codeverse/tracks/generation.py+++ b/harness/codeverse/tracks/generation.py@@ -26,17 +26,17 @@ profile sets), and a cap that IS set stays **graceful**: the session is not killbut asked, in a short wrap-up (``agent_wrapup_turns``), for one last build + summary.**Every dollar is charged.** Both strategies spend through-``BudgetGuard.spend`` with their stage / label / round, so a retried session+``BudgetGuard.charge`` with their stage / label / round, so a retried session(``<label>.a2``) and a wrap-up session are visible to the guard, the record andthe ledger even when the *next* attempt then raises."""from __future__ import annotations-import jsonimport loggingimport osimport re+import shutilfrom collections.abc import Callable, Collectionfrom pathlib import Pathfrom typing import Any@@ -55,6 +55,8 @@ log = logging.getLogger(__name__)# (merged back from codeverse/tracks/envelope.py, 2026-08-28 — the split existed only# to hold a re-export shim; this module was its one importer)ALLOWED_ROOTS: tuple[str, ...] = ("src/", "public/")+#: where an out-of-workspace task image is copied so a vendor CLI can read it (D9, like the cookbook)+IMAGES_DIR = ".3dcv/images"SINGLE_SHOT_FORMAT = """OUTPUT FORMAT (exactly this, nothing else around it):For EVERY file you create or fully rewrite, emit one block:@@ -168,6 +170,7 @@ def write_files(*,allowed_roots: tuple[str, ...] = ALLOWED_ROOTS,only: Collection[str] | None = None,+ frozen: Collection[str] = (),on_skip: Callable[[str, str], None] | None = None,) -> list[FileChange]:"""Write parsed files under the workspace; returns git-style FileChange rows.@@ -178,10 +181,13 @@ def write_files(the valid files were already paid for.``only`` (an ``edit_only`` task's file scope, entry included when owned) skips a- path that ALREADY EXISTS and is not listed — new files stay allowed, mirroring- ``FileTools``: the single-shot envelope has no write-time gate, so this is where a- scoped task is stopped from rewriting a sibling's file."""+ path that ALREADY EXISTS and is not listed — new files stay allowed; ``frozen``+ (the language's harness-owned files, ``src/recipes.glsl``) is skipped outright.+ The single-shot envelope has no write-time gate, so this is where a scoped task is+ stopped from rewriting a sibling's file — the mirror of the CLI backends' post-hoc+ ``_enforce_scope`` (until 2026-08-29 only that side protected the harness files)."""scope = {_clean_path(p) for p in only} if only is not None else None+ owned = {_clean_path(p) for p in frozen}changes: list[FileChange] = []for raw, content in files.items():try:@@ -193,6 +199,12 @@ def write_files(continuedest = ws.root / relexisted = dest.exists()+ if rel in owned:+ reason = "harness-owned: call its functions, never rewrite it"+ if on_skip is not None:+ on_skip(raw, reason)+ log.warning("skipping harness-owned file from generator: %s", rel)+ continueif scope is not None and existed and rel not in scope:reason = f"out of scope: {rel} already exists and is not in this task's file list"if on_skip is not None:@@ -440,8 +452,8 @@ def generate_files(if events is not None:events.emit("generate.skipped_path", label=task.label, path=path, reason=reason[:200])- changes = write_files(ws, files, allowed_roots=allowed_roots,- only=_scope_only(ws, task), on_skip=_skip)+ only, frozen = _envelope_scope(ws, task)+ changes = write_files(ws, files, allowed_roots=allowed_roots, only=only, frozen=frozen, on_skip=_skip)if events is not None:events.emit("generate.done",@@ -462,29 +474,15 @@ def generate_files()-#: task kinds whose money belongs to a differently-named stage of the cost vocabulary-_STAGE_FOR_KIND = {- "rebuild": "repair",- "asset_fix": "assets",- "asset": "assets",- "zone": "zones",- "generate": "baseline",- "compose": "assemble",-}--def task_stage(task: GenerationTask) -> str:- """The cost stage one generation task spends in (a ``codeverse.cost.types.Stage``- value when we can name one, else the label — which ``record_call`` maps through- ``stage_for_label`` (``asset_koi`` → assets, ``r00_baseline_repair1`` → repair))."""- kind = task.kind or ""- stage = _STAGE_FOR_KIND.get(kind, kind)- try:- from codeverse.cost.types import Stage+ """The cost stage one generation task spends in: its kind through+ ``cost.types.stage_for_label`` — the SAME vocabulary ``MeteredAgent`` files the+ session row by — else the label, which ``record_call`` maps the same way+ (``asset_koi`` → assets, ``r00_baseline_repair1`` → repair)."""+ from codeverse.cost.types import Stage, stage_for_label- return str(Stage(stage))- except Exception: # noqa: BLE001 — unknown kind (or no cost package): let the label decide- return task.label or stage or "other"+ stage = stage_for_label(task.kind)+ return str(stage) if stage is not Stage.OTHER else (task.label or "other")def _charge(@@ -553,17 +551,22 @@ def run_agent_task(# round 0 unfinished — silent-bail retries kept getting floor sessions).budget.check()if budget is not None and hasattr(budget, "timeout_s"):- timeout = budget.timeout_s(timeout, floor_s=120.0)+ # A task that chose its own window already clipped it the way its stage wanted+ # (scene.py: soft for env/zones/assets, hard for refine/rebuild) — re-clipping THAT+ # against the soft share handed every scene refine session after the 0.55 share+ # exactly the 120 s floor instead of the ≤ 900 s it asked for. A task with no+ # window of its own (repair) is still bounded by the soft share, so a failing+ # baseline cannot eat the refine rounds' half. (Both found by review 2026-08-29.)+ timeout = budget.timeout_s(timeout, floor_s=120.0, soft=task.timeout_s is None)turns_cap = task.max_turns or max_turns or agent_max_turns() # 0 = leave AgentJob's own default# typed job context honoured by every CodingAgent: round → trajectory dir + ToolContext,- # language/track → spatial tool filtering, files_hint → per-session attribution of- # files_changed when tasks run concurrently in ONE workspace (see agents/cli_common).+ # language/track → spatial tool filtering, files_hint → the edit_only scope.language, track = _spec_lang_track(ws)+ prompt = task.prompt + _images_block(task.images, ws)job = AgentJob(workspace=str(ws.root),- prompt=task.prompt,+ prompt=prompt,system_append=task.system,- model=getattr(agent, "model", ""),label=task.label,timeout_s=timeout,spatial_tools=True,@@ -597,7 +600,7 @@ def run_agent_task(session_usd=round(acc.usage.cost_usd, 4),)wrap = job.model_copy(- update={"prompt": WRAPUP_PROMPT + task.prompt, "max_turns": max(2, int(wrapup_turns))}+ update={"prompt": WRAPUP_PROMPT + prompt, "max_turns": max(2, int(wrapup_turns))})res = acc.run(agent, wrap, wrapup=True, optional=True) or reschanges = res.files_changed or changes or _attributed_fallback(ws, task, before)@@ -614,7 +617,7 @@ def run_agent_task(update={"prompt": ("Your previous attempt ended WITHOUT writing any file. You must create/edit the files "- "described below and run the build tool before finishing.\n\n" + task.prompt+ "described below and run the build tool before finishing.\n\n" + prompt)})@@ -691,21 +694,10 @@ class _SessionAcc:return Noneself.usage = self.usage + res.usageself.turns += session_turns(res)- self.charge(res.usage, label=label, outcome=res.exit_reason or "ok")+ if res.usage.cost_usd or res.usage.input_tokens or res.usage.output_tokens: # an empty session books no call+ _charge(self.budget, res.usage, task=self.task, label=label, outcome=res.exit_reason or "ok")return res- def charge(self, usage: Usage, *, label: str, outcome: str) -> None:- if self.budget is None or not (usage.cost_usd or usage.input_tokens or usage.output_tokens):- return- self.budget.charge(- usage,- stage=task_stage(self.task),- role="generator",- label=label,- round_index=self.task.round,- outcome=outcome,- )-def _is_budget_stop(e: BaseException) -> bool:from codeverse.orchestrator import BudgetExceeded@@ -714,26 +706,46 @@ def _is_budget_stop(e: BaseException) -> bool:def session_turns(res: Any) -> int:- """The session's turn count as the BACKEND reports it — the ``turns`` field- ``agents/cli_common.finish_session`` writes into ``result.json`` (0 when the- backend does not report one).-- Backends count turns slightly differently, so this is a size signal for the- ``cost.round`` event, not the number the turn cap is compared against —- that one is enforced inside the session by ``job.max_turns``."""- path = getattr(res, "transcript_path", "") or ""- if not path:- return 0- p = Path(path)- result = (p if p.is_dir() else p.parent) / "result.json"- try:- if result.is_file():- value = json.loads(result.read_text(errors="replace")).get("turns")- if isinstance(value, (int, float)):- return int(value)- except (OSError, ValueError) as e: # noqa: PERF203 - best effort telemetry- log.debug("session turns unreadable (%s): %s", result, e)- return 0+ """``AgentResult.turns`` — the count as the BACKEND reports it (0 for gemini-cli,+ which exposes none). Backends count turns slightly differently, so this is a+ size signal for the ``cost.round`` event, not the number the turn cap is compared+ against — that one is enforced inside the session by ``job.max_turns``. (Until+ 2026-08-29 this re-read result.json for a ``turns`` key only the deleted api-agent+ wrote, so ``agent_turns`` was 0 for every vendor CLI.)"""+ return int(getattr(res, "turns", 0) or 0)+++def _images_block(images: list[ImagePart], ws: Workspace) -> str:+ """The task's images (reference photos, the judged contact sheet) as a prompt+ section. No vendor CLI takes an image on argv, so the agent opens the files with+ its own file/image tools; until 2026-08-29 ``AgentJob.images`` was filled and read+ by nobody, so the contact sheet the judge scored reached no CLI session.++ Every image is copied into ``.3dcv/images/`` first, exactly as the cookbook is (D9),+ and listed workspace-relative: a CLI reads only INSIDE its workspace (``--image+ ref.png`` stores the host's absolute path), and the judged contact sheet sits under+ ``artifacts/renders/``, which ``.geminiignore`` hides from gemini-cli's read_file."""+ paths: list[tuple[str, str]] = []+ for i in images:+ if not i.path:+ continue+ src = Path(i.path)+ dest = ws.root / IMAGES_DIR / f"{len(paths):02d}_{src.name}"+ try:+ dest.parent.mkdir(parents=True, exist_ok=True)+ shutil.copy2(src, dest)+ except OSError as e: # unreadable source: naming it is still better than silence+ log.warning("task image %s could not be copied into %s: %s", src, dest, e)+ paths.append((i.label or "image", str(src)))+ continue+ paths.append((i.label or "image", dest.relative_to(ws.root).as_posix()))+ if not paths:+ return ""+ lines = ["", "", "## Images for this task",+ "They are NOT attached to this message: open each file with your image/file-reading tool.",+ "Paths are relative to the workspace root."]+ lines += [f"- {label}: `{path}`" for label, path in paths]+ return "\n".join(lines)def _spec_lang_track(ws: Workspace) -> tuple[str, str]:@@ -763,13 +775,14 @@ def _always_writable(language: str, task: GenerationTask) -> list[str]:return [entry] if task.owns_entry or entry in task.files_hint else []-def _scope_only(ws: Workspace, task: GenerationTask) -> set[str] | None:- """``write_files``'s scope for an ``edit_only`` single-shot task: the files_hint plus- the entry file when the task owns it (the envelope-path mirror of FileTools)."""- if not task.edit_only or not task.files_hint:- return None+def _envelope_scope(ws: Workspace, task: GenerationTask) -> tuple[set[str] | None, list[str]]:+ """``write_files``'s ``only`` (an ``edit_only`` task: files_hint + the entry when+ owned) and ``frozen`` (the language's harness-owned files) for a single-shot task."""language, _ = _spec_lang_track(ws)- return {f for f in task.files_hint if f} | set(_always_writable(language, task))+ frozen = _read_only(language)+ if not task.edit_only or not task.files_hint:+ return None, frozen+ return {f for f in task.files_hint if f} | set(_always_writable(language, task)), frozendef _read_only(language: str) -> list[str]:diff --git a/harness/codeverse/tracks/graphics.py b/harness/codeverse/tracks/graphics.pyindex 1be5645b..30e4974e 100644--- a/harness/codeverse/tracks/graphics.py+++ b/harness/codeverse/tracks/graphics.py@@ -3,7 +3,7 @@Languages: glsl_shader (Shadertoy-style fragment shader) · opengl_python (rawmoderngl program). Reuses ``BaseTrack`` (lifecycle) and ``run_round`` (steps)unchanged; the track-specific pieces are the planner hooks (template / example /-acceptance in ``graphics_steps``), the prompt context (no 3D frame), the+acceptance, below), the prompt context (no 3D frame), the``gl_frames`` gate (frame statistics from the build) and the render step (thesampled frames + contact sheet as the RenderSet the ``shader_v2`` judge sees).Refinement is always one whole-program task.@@ -44,13 +44,12 @@ from codeverse.tracks.prompting import (AGENT_OUTPUT_RULES,acceptance_lines,constraints_text,- current_files,is_always_chapter,judge_digest,judged_sheet,- language_system_prompt,reference_images,reference_note,+ refine_inline_files,select_cookbook_chapters,skeleton_files,)@@ -351,8 +350,8 @@ def graphics_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:d: dict[str, Any] = {"track": ctx.track.value, "language": ctx.language.value, "contract": ctx.contract_text,"cookbook_rel": ctx.cookbook_rel, "cookbook_excerpt": ctx.cookbook_text, "tool_cards": ctx.tool_cards,- # the recipes tracks/graphics_recipes.py put in the harness-owned src/recipes.glsl before the session ([] = no block)- "seeded_recipes": list((getattr(ctx, "extra", None) or {}).get(EXTRA_KEY) or []),+ # the recipes seed_recipes() put in the harness-owned src/recipes.glsl before the session ([] = no block)+ "seeded_recipes": list(ctx.extra.get(EXTRA_KEY) or []),"single_shot": ctx.single_shot, "output_format": SINGLE_SHOT_FORMAT if ctx.single_shot else AGENT_OUTPUT_RULES,"spec_prompt": ctx.spec.prompt, "constraints": constraints_text(ctx.spec),"title": plan.title if plan else "Untitled effect", "plan_summary": plan.summary if plan else "",@@ -468,7 +467,7 @@ class GraphicsTrack(BaseTrack):# ------------------------------------------------------------------ preparedef prepare(self, ctx: RunContext, runner: StageRunner) -> None:"""Skeleton, then the brief's verified cookbook recipes into the harness-owned, read-only- src/recipes.glsl (graphics_recipes: measured, flash does not call a recipe it is only shown — and a+ src/recipes.glsl (seed_recipes: measured, flash does not call a recipe it is only shown — and arecipe seeded into its own common.glsl was overwritten by the end of the run, so the file is onethe agent cannot write: AgentJob.read_only)."""super().prepare(ctx, runner)@@ -476,9 +475,6 @@ class GraphicsTrack(BaseTrack):ctx.ws.commit("recipes")# ------------------------------------------------------------------ baseline- def system_prompt(self, ctx: RunContext) -> str:- return language_system_prompt(ctx.language, tools=not ctx.single_shot)-def baseline_tasks(self, ctx: RunContext) -> list[GenerationTask]:files = graphics_expected_files(ctx)prompt = render(self.generate_template, **graphics_prompt_context(@@ -500,7 +496,7 @@ class GraphicsTrack(BaseTrack):prompt = render(self.refine_template, **graphics_prompt_context(ctx, round_index=index, tasks=[t.line() for t in group.tasks], targets=group.targets, files=files,judge_summary=judge_digest(last), frame_notes=frame_stats_text(ctx.ws),- current_files=current_files(ctx, files) if ctx.single_shot else {}))+ current_files=refine_inline_files(ctx, files, scoped=False)))ctx.record_prompt("refine", prompt)return GenerationTask(label="refine", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=index,kind="refine", temperature=0.5, thinking="medium", owns_entry=True,diff --git a/harness/codeverse/tracks/lifecycle.py b/harness/codeverse/tracks/lifecycle.pyindex 021e1347..17a1ddad 100644--- a/harness/codeverse/tracks/lifecycle.py+++ b/harness/codeverse/tracks/lifecycle.py@@ -25,7 +25,10 @@ from codeverse.contracts.common import Track, Usagefrom codeverse.contracts.plan import Planfrom codeverse.contracts.run import RoundRecord, RunRecord, RunStatusfrom codeverse.contracts.spec import Spec+from codeverse.cost.context import run_binding+from codeverse.cost.instrument import run_ledgerfrom codeverse.orchestrator import (+ KIND_FOR_STRATEGY,BestSelector,BudgetExceeded,BudgetGuard,@@ -41,7 +44,6 @@ from codeverse.orchestrator import (best_score,build_refine_instructions,hash_inputs,- kind_for_strategy,plan_refine_groups,)from codeverse.proc import EventLog@@ -58,7 +60,13 @@ from codeverse.tracks.generation import GenerationTask, single_shot_model_idfrom codeverse.tracks.planner import default_event_stats, ensure_acceptance, normalise_namesfrom codeverse.tracks.planner import plan as run_plannerfrom codeverse.tracks.planner import plan_example as default_plan_example-from codeverse.tracks.prompting import base_prompt_context, current_files, expected_files+from codeverse.tracks.prompting import (+ base_prompt_context,+ expected_files,+ file_for_target_factory,+ language_system_prompt,+ refine_inline_files,+)from codeverse.tracks.repair import format_error_reportfrom codeverse.tracks.steps import (RoundFailed,@@ -75,27 +83,26 @@ log = logging.getLogger(__name__)REFERENCE_RUBRIC = "reference_v1"-#: fallback name of the run's live cost ledger when the cost package cannot place-#: one itself (``flywheel/telemetry.py`` publishes it as ``telemetry/usage.jsonl``)-LEDGER_NAME = "cost_ledger.jsonl"---#: surface-detail rounds a track that implements one gets by default. ``RoundPolicy`` itself-#: defaults to 0 so the pure stop policy is unchanged for everyone else; ``CV3D_DETAIL_ROUNDS``-#: overrides both (0 = off — the A/B switch for docs/EVAL.md).+#: surface-detail rounds a track that implements one gets by default. ``RoundPolicy.detail_rounds``+#: is None (= this default) unless a caller chose a number; ``CV3D_DETAIL_ROUNDS`` overrides both+#: (0 = off — the A/B switch for docs/EVAL.md).DEFAULT_DETAIL_ROUNDS = 1-def detail_round_budget(policy: RoundPolicy, supported: bool, *, explicit: bool) -> int:- """How many detail rounds THIS run gets: env > an explicit policy > the track default."""+def detail_round_budget(policy: RoundPolicy, supported: bool) -> int:+ """How many detail rounds THIS run gets: env > a chosen ``policy.detail_rounds`` > the track default.++ Until 2026-08-29 the third tier was skipped whenever ANY policy object was injected, so the+ economy/quality profiles (a policy for ``judge_samples`` alone) silently lost the static+ track's detail round."""raw = os.environ.get("CV3D_DETAIL_ROUNDS", "").strip()if raw.isdigit():return int(raw) if supported else 0if not supported:return 0- if explicit:+ if policy.detail_rounds is not None:return policy.detail_rounds- return policy.detail_rounds or DEFAULT_DETAIL_ROUNDS+ return DEFAULT_DETAIL_ROUNDSdef _reconcile_billed_from_ledger(budget: BudgetGuard, ws: Workspace, events: EventLog) -> None:@@ -107,9 +114,12 @@ def _reconcile_billed_from_ledger(budget: BudgetGuard, ws: Workspace, events: Evthe provider actually billed — silently under-counting is how a resumed run walkspast its ceiling. Attempt rows stay excluded (the winner is already on the logicalrow), and so do subscription-backend rows: their ``cost_usd`` is notional, not money- (the same ``bills_usd`` predicate the live path uses — ``BudgetGuard.spend``), so a+ (the same ``bills_usd`` predicate the live path uses — ``BudgetGuard.charge``), so acodex/claude/agy run resumed offline keeps billed at $0. A missing or unreadable- ledger simply leaves the snapshot alone."""+ ledger simply leaves the snapshot alone. ``load_ledger(root)`` reads the ledger the+ metered models/agents write (``telemetry/cost.jsonl``), else the root+ ``cost_ledger.jsonl`` that runs before 2026-08-23 wrote directly (bench/out keeps+ hundreds of those)."""try:from codeverse.cost.billing import bills_usdfrom codeverse.cost.ledger import load_ledger@@ -124,24 +134,10 @@ def _reconcile_billed_from_ledger(budget: BudgetGuard, ws: Workspace, events: Evbudget.billed_usd = billed-def run_ledger_path(ws: Workspace) -> Any:- """Where this run's priced per-call rows go.-- ``codeverse.cost`` owns the run layout (``telemetry/cost.jsonl`` + the- ``cost_ledger.jsonl`` alias); fall back to the alias name if it cannot."""- try:- from codeverse.cost.ledger import open_run_ledger-- return open_run_ledger(ws.root)- except Exception as e: # noqa: BLE001 — accounting must never fail a run- log.debug("cost ledger placement fell back to %s: %s", LEDGER_NAME, e)- return ws.root / LEDGER_NAME--_STATUS: dict[str, RunStatus] = {"pass": RunStatus.PASSED, "plateau": RunStatus.PLATEAU, "max_rounds": RunStatus.PLATEAU,"budget": RunStatus.BUDGET,- # the two money stops (orchestrator/rounds.py): the code is intact and the best+ # the two money stops (orchestrator.StopPolicy): the code is intact and the best# round is delivered — the run stopped because another round was not worth buying."regression": RunStatus.PLATEAU, "diminishing_returns": RunStatus.PLATEAU,# judge outage (degraded/crashed verdicts even after a retry): the code is intact@@ -200,7 +196,7 @@ class BaseTrack:allow_refine_fanout: bool = True#: does this track implement ``detail_tasks``? When False the round policy's detail#: budget is zeroed for the run, so the stop policy never offers a round the track- #: cannot build (see orchestrator/rounds.detail_blocked).+ #: cannot build (see ``orchestrator.detail_blocked``).supports_detail_round: bool = False#: share of the run budget the BASELINE may use (1.0 = no soft cap). The scene#: track lowers it so the refine rounds always inherit money and minutes.@@ -241,7 +237,7 @@ class BaseTrack:raise NotImplementedErrordef system_prompt(self, ctx: RunContext) -> str:- raise NotImplementedError+ return language_system_prompt(ctx.language, tools=not ctx.single_shot)def round_files_hint(self, ctx: RunContext) -> list[str]:return []@@ -270,8 +266,8 @@ class BaseTrack:# ---- refine hooks (the scaffold below is shared; tracks fill in the task)def refine_file_for_target(self, ctx: RunContext) -> Any:- """``target → [files]`` mapper for refine tasks (None = whole-object)."""- return None+ """``target → [files]`` mapper for refine tasks (None = whole-object language)."""+ return file_for_target_factory(ctx)def extra_refine_tasks(self, ctx: RunContext, last: RoundRecord) -> Sequence[Any]:"""Harness-derived tasks prepended to the judge's (e.g. reference IoU)."""@@ -290,7 +286,7 @@ class BaseTrack:no change to the silhouette, the placement or the part list.Offered by the stop policy only once the structure gates are clean- (``orchestrator.rounds.detail_blocked``); tracks that do not implement it set+ (``orchestrator.detail_blocked``); tracks that do not implement it set``supports_detail_round = False`` and are never offered the round."""return [], []@@ -337,50 +333,55 @@ class BaseTrack:lint = next((g for g in last.gates if g.gate.startswith("lint")), GateReport(gate="lint", passed=True))report = format_error_report(last.build, lint, ctx.cookbook_text) if last.build else "build did not run"prompt = render(self.generate_template, **self.generate_context(- ctx, skeleton_files=current_files(ctx, files) if ctx.single_shot else {}, previous_error=report))+ ctx, skeleton_files=refine_inline_files(ctx, files, scoped=False), previous_error=report))return GenerationTask(label="rebuild", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=index,kind="rebuild", temperature=0.7, thinking="high")# ------------------------------------------------------------------ public APIdef run(self, spec: Spec, ws: Workspace, *, resume: bool = False, force: bool = False) -> RunRecord:ws.create()- if not ws.spec_path.is_file() or not resume:- ws.write_json(ws.spec_path, spec)- events = EventLog(ws.events_path)- state = RunState.load_or_new(ws, resume=resume)- # BEFORE build_context (which restores the budget snapshot from state.extra):- # make the state agree with the durable round journal, verify spec identity,- # and take the reconciled rounds as the loop's initial history — so the- # FAILED/BUDGET handlers below serialize the real rounds, never [].- rounds: list[RoundRecord] = self.reconcile_resume(spec, ws, events, state, resume=resume, force=force)- ctx = self.build_context(spec, ws, events, state)- runner = StageRunner(ws, events, state)- events.emit("run.start", track=self.track.value, language=spec.language.value, resume=resume,- agent=ctx.agent_id, planner=spec.backends.planner, judge=spec.backends.judge)- stop: StopReason | str = "failed"- error = ""- try:- ctx.plan = runner.stage("plan", lambda: self._plan_stage(ctx), inputs={"spec": plan_stage_inputs(spec), "track": self.track.value},- model=self.plan_model)- self.after_plan(ctx)- self.prepare(ctx, runner)- stop = self._round_loop(ctx, rounds)- except BudgetExceeded as e:- events.emit("budget.exceeded", reason=e.reason, spent_usd=round(e.spent_usd, 4))- stop, error = "budget", e.reason- self._salvage_baseline(ctx, rounds)- except Exception as e: # noqa: BLE001 — persist a FAILED record, then fail loud- error = f"{type(e).__name__}: {e}"- events.emit("run.failed", error=error, traceback=traceback.format_exc()[-3000:])- self._save_budget(ctx) # mid-round charges must survive for resume- state.status, state.error = RunStatus.FAILED, error- state.save(ws)- rec = self._record(ctx, rounds, RunStatus.FAILED, error=error, stop_reason="failed")- self.services.finalize_record(ws, rec)- raise- status = _STATUS.get(stop, RunStatus.FAILED)- rec = self.finalise(ctx, rounds, status, stop_reason=str(stop), error=error)- return rec+ # the run's own ledger even when nobody opened one (a test, a script): the CLI /+ # bench open the same file first and run_ledger nests, restoring theirs on exit.+ # Keep THEIR name when they bound one — a compare_backends cell is "<prompt>:<arm>",+ # and rebinding it to the directory ("run") collapsed every cell into one bucket.+ with run_ledger(ws.root, run=run_binding().run or ws.root.name):+ if not ws.spec_path.is_file() or not resume:+ ws.write_json(ws.spec_path, spec)+ events = EventLog(ws.events_path)+ state = RunState.load_or_new(ws, resume=resume)+ # BEFORE build_context (which restores the budget snapshot from state.extra):+ # make the state agree with the durable round journal, verify spec identity,+ # and take the reconciled rounds as the loop's initial history — so the+ # FAILED/BUDGET handlers below serialize the real rounds, never [].+ rounds: list[RoundRecord] = self.reconcile_resume(spec, ws, events, state, resume=resume, force=force)+ ctx = self.build_context(spec, ws, events, state)+ runner = StageRunner(ws, events, state)+ events.emit("run.start", track=self.track.value, language=spec.language.value, resume=resume,+ agent=ctx.agent_id, planner=spec.backends.planner, judge=spec.backends.judge)+ stop: StopReason | str = "failed"+ error = ""+ try:+ ctx.plan = runner.stage("plan", lambda: self._plan_stage(ctx), inputs={"spec": plan_stage_inputs(spec), "track": self.track.value},+ model=self.plan_model)+ self.after_plan(ctx)+ self.prepare(ctx, runner)+ stop = self._round_loop(ctx, rounds)+ except BudgetExceeded as e:+ events.emit("budget.exceeded", reason=e.reason, spent_usd=round(e.spent_usd, 4))+ stop, error = "budget", e.reason+ self._salvage_baseline(ctx, rounds)+ except Exception as e: # noqa: BLE001 — persist a FAILED record, then fail loud+ error = f"{type(e).__name__}: {e}"+ events.emit("run.failed", error=error, traceback=traceback.format_exc()[-3000:])+ self._save_budget(ctx) # mid-round charges must survive for resume+ state.status, state.error = RunStatus.FAILED, error+ state.save(ws)+ rec = self._record(ctx, rounds, RunStatus.FAILED, error=error, stop_reason="failed")+ self.services.finalize_record(ws, rec)+ raise+ status = _STATUS.get(stop, RunStatus.FAILED)+ rec = self.finalise(ctx, rounds, status, stop_reason=str(stop), error=error)+ return rec# ------------------------------------------------------------------ resume reconciliationdef reconcile_resume(self, spec: Spec, ws: Workspace, events: EventLog, state: RunState,@@ -501,8 +502,7 @@ class BaseTrack:def build_context(self, spec: Spec, ws: Workspace, events: EventLog, state: RunState) -> RunContext:settings = self._settings or get_settings()runtime = self._runtime or self.services.runtime(spec.language)- budget = BudgetGuard(spec.budget, soft_fraction=self.soft_budget_fraction,- run=ws.root.name, ledger=run_ledger_path(ws))+ budget = BudgetGuard(spec.budget, soft_fraction=self.soft_budget_fraction)snap = state.extra.get("budget_snapshot")if snap:# full guard state: money, calls, buckets AND active minutes keep counting,@@ -514,11 +514,9 @@ class BaseTrack:if spent:budget.spent = Usage.model_validate(spent)_reconcile_billed_from_ledger(budget, ws, events)- n_cand = self._resolve_candidates(spec, state, settings)- policy = ((self._policy or RoundPolicy(max_rounds=spec.budget.max_rounds))- .with_candidates(n_cand).with_judge(spec.backends.judge))- policy = replace(policy, detail_rounds=detail_round_budget(policy, self.supports_detail_round,- explicit=self._policy is not None))+ policy = self._policy or RoundPolicy(max_rounds=spec.budget.max_rounds)+ policy = replace(policy, n_candidates=self._resolve_candidates(spec, settings), judge_model=spec.backends.judge,+ detail_rounds=detail_round_budget(policy, self.supports_detail_round))# reference images: static objects are scored with reference_v1 (adds the measured silhouette# criterion); other tracks keep their rubric but the judge still sees the references.rubric = REFERENCE_RUBRIC if spec.references and self.track is Track.STATIC_OBJECT else self.rubric@@ -533,19 +531,15 @@ class BaseTrack:ctx.record_prompt(name, text)return ctx- def _resolve_candidates(self, spec: Spec, state: RunState, settings: Settings) -> int:+ def _resolve_candidates(self, spec: Spec, settings: Settings) -> int:"""Best-of-N width: constructor (CLI --candidates) > ``spec.options.candidates``- > persisted run state (legacy resume) > settings default."""+ (the persisted carrier — spec.json travels with the run) > settings default."""n = self._n_candidatesif n is None:n = spec.options.candidates- if n is None:- n = state.extra.get("n_candidates")if n is None:n = getattr(settings, "default_candidates", 1)- n = max(1, int(n or 1))- state.extra["n_candidates"] = n- return n+ return max(1, int(n or 1))def make_judge(self, ctx: RunContext, *, n_samples: int | None = None) -> Any:"""The main judge: injected → reference / likeness judge when the spec has images → rubric VLM judge."""@@ -567,10 +561,11 @@ class BaseTrack:judge_hash = getattr(ctx.judge, "prompt_hash", "")if isinstance(judge_hash, str) and judge_hash:ctx.prompt_hashes["judge"] = judge_hash- if self._policy is None:- thr = self.services.rubric_threshold(ctx.rubric)- if thr is not None:- ctx.policy = replace(ctx.policy, target=float(thr))+ # the rubric's pass threshold is the stop target whenever the rubric states one —+ # for an injected policy too (the CLI used to re-derive it; one binding now)+ thr = self.services.rubric_threshold(ctx.rubric)+ if thr is not None:+ ctx.policy = replace(ctx.policy, target=float(thr))if ctx.single_shot:if ctx.model is None:ctx.model = self.services.chat_model(single_shot_model_id(ctx.agent_id))@@ -611,12 +606,11 @@ class BaseTrack:"""Materialise AGENTS.md/MCP config once per run for agent generators."""if ctx.single_shot:return- kind = ctx.agent_id.split(":", 1)[0]+ kind = ctx.agent_kindif ctx.state.materialized_for == kind:return- mcp = ["python", "-m", "codeverse.spatial.mcp_server", "--workspace", str(ctx.ws.root)]self.services.materialize(ctx.ws, agent_kind=kind, contract_md=self.agent_contract_md(ctx), cookbook_rel=ctx.cookbook_rel,- spatial_tools=True, mcp_command=mcp)+ spatial_tools=True)ctx.state.materialized_for = kindctx.state.save(ctx.ws)ctx.events.emit("workspace.materialized", agent_kind=kind)@@ -630,7 +624,6 @@ class BaseTrack:self.ensure_materialized(ctx)pipeline = self.make_pipeline()stop_policy = StopPolicy(ctx.policy)- selector = BestSelector()rejudged: set[int] = set()while True:decision = stop_policy.evaluate(rounds, budget_ok=ctx.budget.ok())@@ -655,13 +648,10 @@ class BaseTrack:rejudged.add(last.index)prev_j = rounds[-2].judgment if len(rounds) > 1 else Noneif rejudge_round(ctx, pipeline, last, previous=prev_j):- best = choose_best_round(ctx, rounds, selector, last.index)- if best is not None and ctx.state.update_best(best, rounds[best].commit, rounds[best].score):- ctx.events.emit("best.updated", round=best, score=rounds[best].score)- self._save_budget(ctx)+ self._promote_best(ctx, rounds, last.index)continue # decide() re-runs with the recovered scoretasks, instructions = self.refine_tasks(ctx, last, rounds, strategy=decision.strategy)- kind = kind_for_strategy(decision.strategy)+ kind = KIND_FOR_STRATEGY.get(decision.strategy, "refine")if not tasks:if last.judgment is None and last.build is not None and last.build.ok:# no tasks only because the judge never scored the round: stopping@@ -697,11 +687,15 @@ class BaseTrack:# r1=0.7). Crashing before this save leaves state behind the journal, which# reconcile detects (stale) and repairs by re-ranking; that is the safe side.ctx.state.mark_round_done(index, rec.commit)- best = choose_best_round(ctx, rounds, selector, index)- ctx.state.best_considered_through = index # this round HAS been ranked- if best is not None and ctx.state.update_best(best, rounds[best].commit, rounds[best].score):- ctx.events.emit("best.updated", round=best, score=rounds[best].score)- self._save_budget(ctx)+ self._promote_best(ctx, rounds, index)++ def _promote_best(self, ctx: RunContext, rounds: list[RoundRecord], index: int) -> None:+ """Rank round ``index`` in (pairwise tie-break included), promote the best, save."""+ best = choose_best_round(ctx, rounds, BestSelector(), index)+ ctx.state.best_considered_through = index # this round HAS been ranked+ if best is not None and ctx.state.update_best(best, rounds[best].commit, rounds[best].score):+ ctx.events.emit("best.updated", round=best, score=rounds[best].score)+ self._save_budget(ctx)def _salvage_baseline(self, ctx: RunContext, rounds: list[RoundRecord]) -> None:"""A stage tripped the budget BEFORE round 0 ever ran (the greenhouse scene:@@ -730,16 +724,12 @@ class BaseTrack:ctx.events.emit("budget.salvage_failed", error=f"{type(e).__name__}: {e}")returnrounds.append(rec)- ctx.state.mark_round_done(0, rec.commit, ctx.ws)- if ctx.state.update_best(0, rec.commit, rec.score):- ctx.events.emit("best.updated", round=0, score=rec.score)- self._save_budget(ctx)+ ctx.state.mark_round_done(0, rec.commit)+ self._promote_best(ctx, rounds, 0)def _save_budget(self, ctx: RunContext) -> None:snap = ctx.budget.snapshot()ctx.state.extra["budget_snapshot"] = snap.model_dump(mode="json")- # legacy mirror, kept for one release: older tooling/tests still read spent_usage- ctx.state.extra["spent_usage"] = snap.spent.model_dump(mode="json")ctx.state.save(ctx.ws)# ------------------------------------------------------------------ finalise@@ -858,8 +848,10 @@ class BaseTrack:# none of them in ``rounds`` — the guard is the honest total (docs/COST.md §6).if ctx.budget.spent.cost_usd > total.cost_usd:total = ctx.budget.spent+ cands = ctx.ws.root / "rounds" / "candidates.json" # best-of-N summary: the file is the one copyextra: dict[str, Any] = {"stop_reason": stop_reason, "rubric": ctx.rubric, "budget": ctx.budget.summary(),- "n_candidates": ctx.policy.n_candidates, "candidates": ctx.state.extra.get("candidates"),+ "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"]diff --git a/harness/codeverse/tracks/plan_features.py b/harness/codeverse/tracks/plan_features.pyindex 8dc49575..203a9957 100644--- a/harness/codeverse/tracks/plan_features.py+++ b/harness/codeverse/tracks/plan_features.py@@ -25,8 +25,7 @@ GRAPH_BUDGET = "graph_budget"GRAPH_EXAMPLE = "graph_example"CONSISTENCY = "consistency"KNOWN_FEATURES: tuple[str, ...] = (FIT, CONTACTS, GRAPH, GRAPH_BUDGET, GRAPH_EXAMPLE, CONSISTENCY)-#: which stage each switch would have changed — read by ``pin_plan_blockers``-PLAN_SIDE: frozenset[str] = frozenset({FIT, GRAPH, GRAPH_BUDGET, GRAPH_EXAMPLE, CONSISTENCY})+#: the one generation-side switch; ``pin_plan_blockers`` treats the rest as plan-sideGENERATION_SIDE: frozenset[str] = frozenset({CONTACTS})#: env switches that act AFTER planning — ``--pin-plan`` may share one plan across arms#: that differ only by these. Anything not listed is treated as plan-side: refusing to@@ -80,9 +79,6 @@ LIVE_SWITCHES: dict[str, str] = {# inter-chunk stall detection, and the IPv4-only transport. Read at call time# by every gemini request, so a control arm can set either to 0."CV3D_STREAM": "codeverse/models/gemini.py",- #: v0 = the pre-2026-08-28 two-sentence system prompt; unset = the per-language one.- #: Temporary, for the A/B; remove with the system_v0.md files once it has an answer.- "CV3D_SYSPROMPT": "codeverse/tracks/prompting.py","CV3D_IPV4": "codeverse/models/gemini.py",}@@ -102,4 +98,4 @@ def dead_env_keys(env: dict[str, str]) -> list[str]:__all__ = ["CONSISTENCY", "CONTACTS", "DEAD_SWITCHES", "FIT", "GENERATION_SIDE","GENERATION_SIDE_ENV", "GRAPH", "GRAPH_BUDGET", "GRAPH_EXAMPLE", "KNOWN_FEATURES",- "LIVE_SWITCHES", "PLAN_FEATURES_ENV", "PLAN_SIDE", "dead_env_keys", "pin_plan_blockers"]+ "LIVE_SWITCHES", "PLAN_FEATURES_ENV", "dead_env_keys", "pin_plan_blockers"]diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.pyindex 9da44384..a976c44c 100644--- a/harness/codeverse/tracks/planner.py+++ b/harness/codeverse/tracks/planner.py@@ -1,6 +1,6 @@"""Planner: spec → validated Plan (StaticPlan / ArticulatedPlan / ScenePlan).-An optional cheap **brief expansion** (``tracks/brief.py``) turns the one-line+An optional cheap **brief expansion** (``expand_brief``, below) turns the one-linerequest into an engineering brief, which — together with a **plan budget derivedfrom the request** — goes into one structured ``ChatRequest`` (system prompt from``prompts/tracks/plan_<track>.j2``, ``response_schema`` = the plan model's JSON@@ -34,8 +34,9 @@ from codeverse.contracts.plan import AcceptanceItem, EngineeringBrieffrom codeverse.contracts.spec import Specfrom codeverse.conventions import LANGUAGE_FRAME, frame_doc, to_pascalfrom codeverse.models.schema_utils import parse_json_lenient+from codeverse.proc import sha256_filefrom codeverse.prompts import load_text, prompt_hash, render-from codeverse.tracks.common import language_contract, load_prompt_or+from codeverse.tracks.common import language_contractfrom codeverse.tracks.prompting import constraints_textfrom codeverse.workspace import Workspace@@ -73,21 +74,13 @@ def _reference_digest(spec: Spec) -> list[dict[str, str]]:out: list[dict[str, str]] = []for r in spec.references:try:- digest = _sha256_file(Path(r.path))+ digest = sha256_file(r.path)except OSError:digest = "(unreadable)"out.append({"path": r.path, "role": r.role, "note": r.note, "sha256": digest})return out-def _sha256_file(path: Path) -> str:- h = hashlib.sha256()- with path.open("rb") as fh:- for chunk in iter(lambda: fh.read(1 << 20), b""):- h.update(chunk)- return h.hexdigest()--def brief_cache_key(spec: Spec, model_id: str) -> str:"""Every input to the call must be in the key.@@ -427,7 +420,7 @@ def plan_quality_complaint(plan_obj: Any, budget: PlanBudget, *, unit: str = "padef _fold_pass(ps: Any) -> None:"""Fold a graphics pass's ``elements`` + ``detail_hint`` into its ``description``.- ``graphics_steps.passes_table`` prints ``| name | kind | description |`` — one markdown+ ``graphics.passes_table`` prints ``| name | kind | description |`` — one markdownrow — so the fold must stay on a single line and must be idempotent."""if not (ps.elements or ps.detail_hint) or " · " in ps.description:return@@ -445,7 +438,7 @@ def enrich_plan(plan_obj: Any, brief: EngineeringBrief | None) -> Any:A part's own depth needs no folding: ``tracks/prompting.py`` renders``PartPlan.children`` and ``PartPlan.detail_hint`` straight from the typed fields, socopying them into ``description`` would print every sub-part twice. A graphics PASS is- the exception — ``graphics_steps.passes_table`` renders only ``description`` — so+ the exception — ``graphics.passes_table`` renders only ``description`` — so``elements`` are folded there, on ONE line because that table is markdown.* the brief's signature features become ``should`` acceptance items — ``should``, not@@ -683,7 +676,7 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]The two re-asks have SEPARATE budgets and different complaints:``MAX_VALIDATION_REASKS`` for a plan the schema rejects, ``MAX_QUALITY_REASKS`` for aplan that validates but is boxes-at-different-sizes against the derived budget- (:func:`codeverse.tracks.plan_budget.plan_quality_complaint`). A quality re-ask never eats+ (:func:`plan_quality_complaint`). A quality re-ask never eatsthe validation re-ask, and a plan that fails quality twice is still USED — a mediocreplan beats no plan.@@ -898,4 +891,4 @@ def normalise_names[P: BaseModel](plan_obj: P) -> P:__all__ = ["MAX_QUALITY_REASKS", "MAX_VALIDATION_REASKS", "PLAN_TOKENS_MAX", "PlanningError", "plan","plan_tokens", "plan_with_usage", "plan_example", "ensure_acceptance", "add_acceptance_item",- "default_event_stats", "normalise_names", "build_system_prompt", "build_user_prompt", "load_prompt_or"]+ "default_event_stats", "normalise_names", "build_system_prompt", "build_user_prompt"]diff --git a/harness/codeverse/tracks/prompting.py b/harness/codeverse/tracks/prompting.pyindex 067e1b99..665832e3 100644--- a/harness/codeverse/tracks/prompting.py+++ b/harness/codeverse/tracks/prompting.py@@ -9,21 +9,18 @@ which maps a refine target (part / zone / asset) to the files that own it.from __future__ import annotationsimport logging-import osfrom collections.abc import Sequencefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any-from jinja2 import TemplateNotFound-from codeverse.config import fewer_turns_enabledfrom codeverse.contracts.chat import ImagePart-from codeverse.contracts.common import Language, Track+from codeverse.contracts.common import HARNESS_OWNED_SRC, Language, Trackfrom codeverse.contracts.plan import Plan, StaticPlanfrom codeverse.contracts.run import RoundRecordfrom codeverse.conventions import LANGUAGE_FRAME, Frame, frame_doc, to_snake-from codeverse.languages._docs import prompt_dir_forfrom codeverse.prompts import render+from codeverse.prompts.catalog import prompt_dir_forfrom codeverse.tracks.common import RunContextfrom codeverse.tracks.depth import DepthBudget, PartScope, depth_budget, interfaces_textfrom codeverse.tracks.generation import SINGLE_SHOT_FORMAT@@ -225,7 +222,7 @@ def select_cookbook_chapters(ctx: RunContext, brief: str, *, budget: int = 9000,``COOKBOOK_SYNONYMS`` as the strong signal, until ``budget`` is spent. A chapter is addedwhole or not at all; the output keeps cookbook order. The default budget is the measuredneed of a night-sky brief: always-set 4.4 k + Light phenomena 3.2 k + Gradient sky 1.3 k.- ``tracks/graphics_recipes.py`` seeds the SAME selection's code into the harness-owned ``src/recipes.glsl``.+ ``tracks/graphics.py:seed_recipes`` seeds the SAME selection's code into the harness-owned ``src/recipes.glsl``."""from codeverse.prompts.sections import Section, find_section, split_sections@@ -273,16 +270,12 @@ def language_system_prompt(language: Language, *, role: str = "", tools: bool =the prompt corpus, so the seven can diverge and be edited without touching code."""d = prompt_dir_for(language)- # CV3D_SYSPROMPT=v0 serves the pre-2026-08-28 two-sentence prompt so an A/B can run- # both arms from one tree. Delete the v0 files and this branch once it has an answer.- name = "system_v0.md" if os.environ.get("CV3D_SYSPROMPT") == "v0" else "system.md"# rendered, not read raw: a system prompt that tells a SINGLE-SHOT session to call# gl_probe is instructing something it has no tools to do, and the self-check loop is# the whole point of the graphics prompt. `tools` lets the file say so itself.- try:- base = render(f"{d}/{name}", tools=tools).strip()- except (FileNotFoundError, TemplateNotFound):- base = render(f"{d}/system.md", tools=tools).strip()+ # (The v0 two-sentence arm of the system-prompt A/B was retired 2026-08-29: a+ # three-way null, docs/EVAL.md.)+ base = render(f"{d}/system.md", tools=tools).strip()if not role:return base# roles COMPOSE with the language base rather than replacing it. Replacing was the@@ -413,7 +406,7 @@ def _likeness_note(ctx: RunContext, refs: list[Any]) -> str:the frame stays dark — and the judge sees the same photos beside the frames."""lines = [- f"REFERENCE PHOTOS ({len(refs)}) of the REAL thing are attached. They are not a composition to copy; "+ f"REFERENCE PHOTOS ({len(refs)}) of the REAL thing come with this task. They are not a composition to copy; ""they show what the brief's subject actually looks like: its dominant colour and where the secondary ""colours sit, how its structure folds / layers / thins out, where the brightness concentrates and how ""much of the frame stays dark, its texture at fine scale. Match THAT — it outranks the brief's "@@ -424,7 +417,8 @@ def _likeness_note(ctx: RunContext, refs: list[Any]) -> str:for i, r in enumerate(refs, 1):lines.append(f"- reference {i}: `{r.path}`" + (f" — {r.note}" if r.note else ""))lines.append("The photos are attached to this message." if ctx.single_shot else- "The photos are attached to your first message; look at them again before every `gl_frames` / `scene_views` comparison.")+ "Their paths are listed under 'Images for this task' at the end of this message: open them with "+ "your image/file-reading tool, and look again before every `gl_frames` / `scene_views` comparison.")return "\n".join(lines)@@ -510,11 +504,16 @@ def refine_inline_files(ctx: RunContext, rels: Sequence[str], *, scoped: bool) -def current_files(ctx: RunContext, rels: Sequence[str], max_chars: int = MAX_SKELETON_CHARS) -> dict[str, str]:+ """``{rel: text}`` for the files that exist, trimmed to ``max_chars`` in total. The+ language's harness-owned files (``src/recipes.glsl``) are never inlined: the+ single-shot prompt showed one as an editable skeleton file while every write to it+ is refused (``generate_graphics.j2`` pastes its signatures separately)."""+ owned = set(HARNESS_OWNED_SRC.get(ctx.language, ()))out: dict[str, str] = {}total = 0for rel in rels:p = ctx.ws.root / rel- if not p.is_file():+ if not p.is_file() or rel in owned:continuetext = p.read_text(errors="replace")room = max_chars - total@@ -630,18 +629,6 @@ def file_for_target_factory(ctx: RunContext):log.warning("runtime.file_for_part failed for %s: %s", target, e)return [f"src/parts/{key}.js"] if lang is Language.THREEJS else [entry]if key in ("overall", "assembly", "object", ""):- whole = getattr(rt, "file_for_target", None) # blender: 'overall' → src/model.py- if callable(whole):- try:- out = whole(target)- if out:- return (- [str(out)]- if isinstance(out, (str, Path))- else [str(p) for p in out]- )- except Exception as e: # noqa: BLE001- log.warning("runtime.file_for_target failed for %s: %s", target, e)return [entry]return []diff --git a/harness/codeverse/tracks/scene.py b/harness/codeverse/tracks/scene.pyindex a0f15e71..ca5a5992 100644--- a/harness/codeverse/tracks/scene.py+++ b/harness/codeverse/tracks/scene.py@@ -9,7 +9,7 @@ zone / asset / env / camera, in parallel when file-disjoint.Cost/latency shaping (the baseline used to eat the whole budget, leaving therefine rounds nothing):-* assets are single-shot by default (``scene_assets`` / ``scene_asset_gen``);+* assets are single-shot by default (``scene_assets``);* **small zones are batched** — a zone that places ≤ 3 assets is writtentogether with its neighbour in ONE session that exclusively owns both files,while big zones keep the parallel fan-out;@@ -52,11 +52,9 @@ from codeverse.tracks.prompting import (base_prompt_context,bbox_line,cookbook_sections,- current_files,- file_for_target_factory,judge_digest,- language_system_prompt,reference_images,+ refine_inline_files,)from codeverse.tracks.repair import format_error_reportfrom codeverse.tracks.scene_assets import (@@ -103,9 +101,6 @@ class ScenePipeline:def gates(self, ctx: RunContext, round_index: int, build: BuildResult, measurement: Measurement | None) -> list[GateReport]:out: list[GateReport] = []- extra = getattr(ctx.runtime, "extra_gates", None)- if callable(extra):- out.extend(extra(ctx.ws, build))census_gate = census_gate_report(build)if census_gate is not None:out.append(census_gate)@@ -289,9 +284,8 @@ class SceneTrack(BaseTrack):skills_hook.attach_for_round(zone_gen, index=0, kind="zone")def _one(batch: list[ZonePlan]) -> GenerationResult:- gen = self._strategy(ctx, "zones")- task = skills_hook.with_inlined_skill(gen, [self._zone_task(gen, batch)])[0]- return generate(ctx.ws, agent_id=gen.agent_id, task=task, agent=gen.agent, model=gen.model, settings=ctx.settings,+ task = skills_hook.with_inlined_skill(zone_gen, [self._zone_task(zone_gen, batch)])[0]+ return generate(ctx.ws, agent_id=zone_gen.agent_id, task=task, agent=zone_gen.agent, model=zone_gen.model, settings=ctx.settings,budget=ctx.budget, events=ctx.events)results = fan_out(batches, _one, max_workers=ctx.settings.limits.max_parallel_agents, label="zones",@@ -355,7 +349,7 @@ class SceneTrack(BaseTrack):result = ctx.services.assemble_scene(ctx.ws, ctx.plan)ctx.ws.commit("assemble")ctx.events.emit("assemble.done", deterministic=True)- return {"ok": True, "deterministic": True, "result": _jsonable(result)}+ return {"ok": True, "deterministic": True, "result": result} # StageRunner.stage jsonables itexcept ServiceUnavailable as e:ctx.events.emit("assemble.fallback", reason=str(e))prompt = render("tracks/scene_compose.j2", **self._ctx(ctx))@@ -394,16 +388,13 @@ class SceneTrack(BaseTrack):return list(SCENE_FILES)# ------------------------------------------------------------------ refine (scaffold hooks)- def refine_file_for_target(self, ctx: RunContext) -> Any:- return file_for_target_factory(ctx)-def _refine_task(self, ctx: RunContext, group: TaskGroup, last: RoundRecord, index: int, *, parallel: bool) -> GenerationTask:files = group.files or list(SCENE_FILES)lines = compact_instructions(group.tasks, max_lines=ctx.policy.max_instructions_per_task)prompt = render("tracks/scene_refine.j2", **self._ctx(ctx, recipes=refine_recipes(ctx, files), round_index=index, tasks=lines,targets=group.targets, files=files, edit_only_these=parallel,judge_summary=judge_digest(last),- current_files=current_files(ctx, files) if ctx.single_shot else {}))+ current_files=refine_inline_files(ctx, files, scoped=False)))ctx.record_prompt("scene_refine", prompt)# parallel groups are file-disjoint by plan_refine_groups: enforce the split they promisedreturn GenerationTask(label=f"refine_{group.label}" if parallel else "refine", prompt=prompt, system=self.system_prompt(ctx),@@ -426,16 +417,13 @@ class SceneTrack(BaseTrack):prompt = render("tracks/scene_refine.j2", **self._ctx(ctx, recipes="", round_index=index, tasks=lines, targets=["build"],files=files, edit_only_these=False,judge_summary="(no judgment: the scene did not build — fix the errors above first)",- current_files=current_files(ctx, files) if ctx.single_shot else {}))+ current_files=refine_inline_files(ctx, files, scoped=False)))ctx.record_prompt("scene_refine", prompt)return GenerationTask(label="rebuild", prompt=prompt, system=self.system_prompt(ctx), files_hint=files, round=index,kind="rebuild", temperature=0.7, thinking="high",timeout_s=ctx.budget.timeout_s(REFINE_TIMEOUT_S, floor_s=180, soft=False))# ------------------------------------------------------------------ helpers- def system_prompt(self, ctx: RunContext) -> str:- return language_system_prompt(ctx.language, tools=not ctx.single_shot)-def _ctx(self, ctx: RunContext, **extra: Any) -> dict[str, Any]:plan: ScenePlan = ctx.plan # type: ignore[assignment]zones_table = "\n".join(f"- {z.name}: {z.description} — {bbox_line(z.bbox)}; contents: {', '.join(z.contents) or '-'}" for z in plan.zones)@@ -522,15 +510,3 @@ def _guess_target(error: str, plan: Any) -> str:if "scene.js" in low:return "composition"return "overall"---def _jsonable(obj: Any) -> Any:- if hasattr(obj, "model_dump"):- return obj.model_dump(mode="json")- if isinstance(obj, (str, int, float, bool)) or obj is None:- return obj- if isinstance(obj, (list, tuple)):- return [_jsonable(o) for o in obj]- if isinstance(obj, dict):- return {str(k): _jsonable(v) for k, v in obj.items()}- return str(obj)diff --git a/harness/codeverse/tracks/scene_assets.py b/harness/codeverse/tracks/scene_assets.pyindex 0ceb3001..2bb77e76 100644--- a/harness/codeverse/tracks/scene_assets.py+++ b/harness/codeverse/tracks/scene_assets.py@@ -30,6 +30,7 @@ from codeverse.contracts.common import Language, Trackfrom codeverse.contracts.plan import AssetPlan, BBox, PartPlan, ScenePlan, StaticPlanfrom codeverse.contracts.spec import Specfrom codeverse.conventions import OBJECT_VIEWS_QUICK, to_pascal, to_snake+from codeverse.judges.rubrics import is_degradedfrom codeverse.proc import fan_out, write_json_atomic, write_text_atomicfrom codeverse.prompts import renderfrom codeverse.tracks.common import RunContext, language_contract, load_prompt_or@@ -59,8 +60,7 @@ def asset_timeout_s(ctx: Any, floor_s: int) -> int:"""``ASSET_AGENT_TIMEOUT_S`` clipped to one asset's share of the run AND to thewall clock actually left (:meth:`BudgetGuard.timeout_s`, which owns the floor)."""share = ctx.budget.budget.max_minutes * 60.0 * ASSET_SESSION_SHARE- return ctx.budget.timeout_s(min(ASSET_AGENT_TIMEOUT_S, share) if share else ASSET_AGENT_TIMEOUT_S,- floor_s=floor_s)+ return ctx.budget.timeout_s(min(ASSET_AGENT_TIMEOUT_S, share), floor_s=floor_s)class AssetResult(BaseModel):@@ -73,7 +73,7 @@ class AssetResult(BaseModel):fixed: bool = Falsenotes: str = ""strategy: str = Field(default="", description="single-shot | single-shot+repair | agent | escalated")- judged: bool = False+ judged: bool = Field(default=False, description="a non-degraded verdict was recorded in `score`")def is_model_outage(e: BaseException) -> bool:@@ -257,10 +257,8 @@ def build_blender_asset(ctx: RunContext, asset: AssetPlan, *, judge: bool) -> Asruntime.skeleton(sub_ws, sub_plan)sub_ws.commit("skeleton")if not ctx.single_shot:- kind = ctx.agent_id.split(":", 1)[0]- ctx.services.materialize(sub_ws, agent_kind=kind, contract_md=sub.contract_text, cookbook_rel=sub.cookbook_rel,- spatial_tools=True,- mcp_command=["python", "-m", "codeverse.spatial.mcp_server", "--workspace", str(sub_ws.root)])+ ctx.services.materialize(sub_ws, agent_kind=ctx.agent_kind, contract_md=sub.contract_text, cookbook_rel=sub.cookbook_rel,+ spatial_tools=True)res = _generate_asset(sub, asset, "src/model.py", language=Language.BLENDER, attempt=0,timeout_s=asset_timeout_s(ctx, 180))if not res.ok:@@ -357,12 +355,17 @@ def _judge_and_fix(ctx: RunContext, asset: AssetPlan, result: AssetResult, rendeexcept Exception as e: # noqa: BLE001events.emit("asset.judge_failed", asset=asset.name, error=f"{type(e).__name__}: {e}")return result- # persist the verdict on the result FIRST, then book the money non-enforcing like- # every other judge site (steps.py, candidates.py): the verdict is already paid- # for, and raising here would discard it. The stage boundary enforces the ceiling.+ # book the money non-enforcing like every other judge site (steps.py, candidates.py):+ # the verdict is already paid for, and raising here would discard it. The stage+ # boundary enforces the ceiling.+ ctx.budget.add(verdict.usage, stage="judge", role="judge", label=f"asset_{to_snake(asset.name)}")+ if is_degraded(verdict):+ # a degraded verdict is no verdict: score stays None and `judged` False, and the+ # fix pass is skipped (its improvement_plan is empty by construction).+ events.emit("asset.judge_degraded", asset=asset.name)+ return resultresult.score = verdict.overallresult.judged = True- ctx.budget.add(verdict.usage, stage="judge", role="judge", label=f"asset_{to_snake(asset.name)}")events.emit("asset.judged", asset=asset.name, score=round(verdict.overall, 3), passed=verdict.passed)if verdict.passed or not verdict.improvement_plan:return resultdiff --git a/harness/codeverse/tracks/skills_hook.py b/harness/codeverse/tracks/skills_hook.pyindex 62132f15..791a970c 100644--- a/harness/codeverse/tracks/skills_hook.py+++ b/harness/codeverse/tracks/skills_hook.py@@ -31,7 +31,7 @@ CTX_KEY = "skills" # ctx.extra slot holding this round's SkillsMaterializeddef _previous_findings(ctx: RunContext, index: int) -> list[GateReport]:"""The gates of the last completed round — the input no CLI's own loader can see.- Read straight off disk rather than through ``steps.load_round_records`` so the hook+ Read straight off disk rather than through ``steps.load_round_journal`` so the hookstays independent of the round loop (and so a half-written record from a killed runcosts this round its gate routing, not the round itself)."""if index <= 0:@@ -72,7 +72,7 @@ def attach_for_round(ctx: RunContext, *, index: int, kind: str) -> Any | None:track=ctx.spec.track.value if hasattr(ctx.spec.track, "value") else str(ctx.spec.track),language=ctx.language.value,kind=kind,- agent_kind=ctx.agent_id.split(":", 1)[0],+ agent_kind=ctx.agent_kind,plan=ctx.plan,findings=_previous_findings(ctx, index),single_shot=ctx.single_shot,@@ -124,7 +124,7 @@ def repair_pointers(ctx: RunContext, lint: GateReport | None) -> str:kinds = set(finding_kinds([lint])) if lint is not None else set()answering = [s.name for s in got.selections if kinds & _matched(s, kinds)]- return _fmt(got.selections, agent_kind=ctx.agent_id.split(":", 1)[0], answering=answering)+ return _fmt(got.selections, agent_kind=ctx.agent_kind, answering=answering)def _matched(selection: Any, kinds: set[str]) -> set[str]:diff --git a/harness/codeverse/tracks/static_object.py b/harness/codeverse/tracks/static_object.pyindex 32d098c7..7ca0753b 100644--- a/harness/codeverse/tracks/static_object.py+++ b/harness/codeverse/tracks/static_object.py@@ -46,7 +46,6 @@ from codeverse.tracks.lifecycle import BaseTrackfrom codeverse.tracks.prompting import (base_prompt_context,budget_for,- current_files,expected_files,file_for_target_factory,glb_to_plan_frame,@@ -69,7 +68,7 @@ GEOMETRY_VIEWS = tuple(v for v in OBJECT_VIEWS if v.name in GEOMETRY_VIEW_NAMES)class ObjectPipeline:- """Measure → connectivity + contract (+ runtime extra gates) → 8-view render."""+ """Measure → connectivity + contract → 8-view render."""views = OBJECT_VIEWS@@ -89,9 +88,6 @@ class ObjectPipeline:out.append(ctx.services.contract(measurement, ctx.plan, BBOX_TOLERANCE_M, ctx.language.value))- extra = getattr(ctx.runtime, "extra_gates", None)- if callable(extra):- out.extend(extra(ctx.ws, build))if measurement is not None and ctx.plan is not None:# is the object as dense as its own plan says? Deterministic, so the judge is# never asked "does it look detailed enough" (tracks/depth.py).@@ -310,16 +306,10 @@ class StaticObjectTrack(BaseTrack):return language_system_prompt(ctx.language, role="scope",n_parts=len(scope.parts), names=", ".join(scope.names))- def system_prompt(self, ctx: RunContext) -> str:- return language_system_prompt(ctx.language, tools=not ctx.single_shot)-def round_files_hint(self, ctx: RunContext) -> list[str]:return expected_files(ctx)# ------------------------------------------------------------------ refine (scaffold hooks)- def refine_file_for_target(self, ctx: RunContext) -> Any:- return file_for_target_factory(ctx)-def extra_refine_tasks(self, ctx: RunContext, last: RoundRecord) -> Sequence[RefineTask]:# NB: the `detail_budget` WARN is deliberately NOT turned into a refine task. Measured:# refine rounds that added > 2000 triangles while assembly was still open lost 0.075 of@@ -393,11 +383,11 @@ class StaticObjectTrack(BaseTrack):files = list(scope.files) if scope is not None else expected_files(ctx)context = (scope_context(ctx, scope, round_index=index, tasks=lines, files=files,judge_summary=judge_digest(last),- current_files=current_files(ctx, files) if ctx.single_shot else {})+ current_files=refine_inline_files(ctx, files, scoped=False))if scope is not None elsebase_prompt_context(ctx, round_index=index, tasks=lines, files=files,judge_summary=judge_digest(last),- current_files=current_files(ctx, files) if ctx.single_shot else {}))+ current_files=refine_inline_files(ctx, files, scoped=False)))tasks.append(GenerationTask(label=f"detail_{scope.label}" if scope is not None else "detail",@@ -431,16 +421,15 @@ class StaticObjectTrack(BaseTrack):DRIFT_GATE = "detail_drift"-def drift_findings(before: Any, after: Any, *, tol_m: float, language: str = "") -> list[Any]:+def drift_findings(before: Measurement | None, after: Measurement | None, *, tol_m: float,+ language: str = "") -> list[GateFinding]:"""Did a detail round move anything? Findings for the ``detail_drift`` gate.The detail round's whole contract is "surface only": the silhouette, the partlist and every part box stay put. This is the deterministic check of thatpromise — the judge is never asked whether the shape moved, code answers it."""- from codeverse.contracts.artifacts import GateFinding, Severity-- out: list[Any] = []+ out: list[GateFinding] = []if before is None or after is None:return outfor axis, a, b in zip(_axes(language), before.extents, after.extents, strict=True):@@ -510,10 +499,8 @@ def _axes(language: str) -> tuple[str, str, str]:return ("x", "y", "z")-def drift_gate(before: Any, after: Any, *, tol_m: float, language: str = "") -> Any:+def drift_gate(before: Measurement | None, after: Measurement | None, *, tol_m: float, language: str = "") -> GateReport:"""``detail_drift`` GateReport (passing when nothing moved)."""- from codeverse.contracts.artifacts import GateReport, Severity-findings = drift_findings(before, after, tol_m=tol_m, language=language)return GateReport(gate=DRIFT_GATE, findings=findings,passed=not any(f.severity is Severity.ERROR for f in findings))diff --git a/harness/codeverse/tracks/steps.py b/harness/codeverse/tracks/steps.pyindex cada450a..d33a3926 100644--- a/harness/codeverse/tracks/steps.py+++ b/harness/codeverse/tracks/steps.py@@ -22,7 +22,7 @@ from __future__ import annotationsimport loggingimport time-from collections.abc import Sequence+from collections.abc import Callable, Sequencefrom datetime import UTC, datetimefrom pathlib import Pathfrom typing import Protocol@@ -31,7 +31,9 @@ from codeverse.contracts.artifacts import BuildResult, GateReport, Judgment, Meafrom codeverse.contracts.common import Usagefrom codeverse.contracts.plan import AcceptanceItem, Planfrom codeverse.contracts.run import RoundRecord-from codeverse.orchestrator import usage_delta+from codeverse.judges.base import JudgeInput+from codeverse.judges.rubrics import is_degraded+from codeverse.orchestrator import BudgetExceeded, usage_deltafrom codeverse.proc import fan_outfrom codeverse.spatial.render import RenderErrorfrom codeverse.tracks import skills_hook@@ -56,6 +58,11 @@ class RoundPipeline(Protocol):...+#: ``(ctx, round_index, build, measurement) → renders`` — ``RoundPipeline.render`` or a+#: cheaper stand-in (best-of-N candidates rank on ``candidates.quick_render``)+RenderFn = Callable[[RunContext, int, BuildResult, Measurement | None], RenderSet | None]++class RoundFailed(RuntimeError):"""Every generation task of a round failed — nothing to build."""@@ -68,7 +75,7 @@ def load_round_journal(ws: Workspace) -> list[RoundRecord]:"""The on-disk round journal: ``rounds/r*.json`` sorted, contiguous prefix only.Workspace-level (no ``RunContext``) because ``lifecycle.reconcile_resume``- reads it before the context exists; :func:`load_round_records` delegates here."""+ reads it before the context exists."""d = ws.root / "rounds"if not d.is_dir():return []@@ -131,8 +138,6 @@ def _run_phase(ctx: RunContext, tasks: Sequence[GenerationTask]) -> list[Generatbudget_stop: Exception | None = Nonefor task, r in zip(tasks, results, strict=True):if isinstance(r, Exception):- from codeverse.orchestrator import BudgetExceeded-if isinstance(r, BudgetExceeded) and budget_stop is None:budget_stop = r # a failed item; the siblings' paid results still land in ``out``ctx.events.emit("generate.failed", label=task.label, error=f"{type(r).__name__}: {r}")@@ -160,6 +165,8 @@ def run_round(extra_usage: Usage | None = None,extra_notes: Sequence[str] = (),previous_best: float | None = None,+ render: RenderFn | None = None,+ geometry_views: bool = True,) -> RoundRecord:"""Execute one round and persist its record. Budget is charged as it goes.@@ -167,12 +174,16 @@ def run_round(best-of-N winner copied in): the round is then build → gates → render →judge only. ``extra_usage`` / ``extra_notes`` fold pre-round work(candidate generation) into the record; ``previous_best`` is the best score- before this round, used only to flag the round as wasted in ``cost.round``."""+ before this round, used only to flag the round as wasted in ``cost.round``.+ ``render`` replaces ``pipeline.render`` and ``geometry_views=False`` skips the+ clay views: the two knobs a best-of-N candidate turns (``candidates.run_best_of_n``+ runs each candidate as this round in its sub-workspace)."""mark = ctx.budget.mark()try:return _run_round(ctx, index=index, kind=kind, tasks=tasks, pipeline=pipeline, instructions=instructions,previous=previous, files_hint=files_hint, extra_usage=extra_usage,- extra_notes=extra_notes, previous_best=previous_best)+ extra_notes=extra_notes, previous_best=previous_best, render=render,+ geometry_views=geometry_views)except BaseException as e:# the round died half-way (budget stop, 503 storm, RoundFailed). Whatever it# burned is already in the guard: report it so the round is not invisible.@@ -194,6 +205,8 @@ def _run_round(extra_usage: Usage | None = None,extra_notes: Sequence[str] = (),previous_best: float | None = None,+ render: RenderFn | None = None,+ geometry_views: bool = True,) -> RoundRecord:t0 = time.time()ctx.events.emit("round.start", round=index, kind=kind, n_tasks=len(tasks))@@ -205,7 +218,11 @@ def _run_round(if extra_usage is not None and extra_usage.cost_usd:cost["candidates"] = round(extra_usage.cost_usd, 6)- skills_hook.attach_for_round(ctx, index=index, kind=kind)+ # a candidate IS a baseline written in a sub-workspace: route its skills as baseline work,+ # or every kind-gated bundle (the *-forms / *-joints routes) drops out and the winner is+ # generated with a strictly smaller library than a --candidates 1 baseline (review 2026-08-29)+ skill_kind = "baseline" if kind == "candidate" else kind+ skills_hook.attach_for_round(ctx, index=index, kind=skill_kind)gens = run_generation_tasks(ctx, skills_hook.with_inlined_skill(ctx, tasks))turns = 0for g in gens:@@ -234,7 +251,7 @@ def _run_round(rec.measurement = pipeline.measure(ctx, outcome.build)gates.extend(pipeline.gates(ctx, index, outcome.build, rec.measurement))try:- rec.renders = pipeline.render(ctx, index, outcome.build, rec.measurement)+ rec.renders = (render or pipeline.render)(ctx, index, outcome.build, rec.measurement)except RenderError as e:# A render that times out (measured 2026-08-26, art_verify camera_tripod: the# refine round built in 1.2 s, then render_glb.mjs hit its 330 s timeout with@@ -251,12 +268,15 @@ def _run_round(n_err = sum(len(g.errors) for g in gates)ctx.events.emit("gates.done", round=index, n_gates=len(gates), n_errors=n_err,tri_count=rec.measurement.tri_count if rec.measurement else None)- skip = skip_judge_reason(ctx, gates=gates, renders=rec.renders)+ # a candidate's verdict is the ONLY thing that picks the code r00 starts from, so it is+ # bought even past the ceiling — unlike a refine verdict, which could promote nothing+ skip = skip_judge_reason(ctx, gates=gates, renders=rec.renders, ignore_budget=kind == "candidate")if skip:notes.append(f"judge skipped ({skip})")ctx.events.emit("judge.skipped", round=index, reason=skip)else:- rec.judgment, judge_usage = _judge(ctx, pipeline, index, outcome.build, gates, rec, previous, notes)+ rec.judgment, judge_usage = _judge(ctx, pipeline, index, outcome.build, gates, rec, previous, notes,+ geometry_views=geometry_views)if rec.judgment is not None or judge_usage.cost_usd:# a degraded/crashed verdict was still PAID: fold its usage into the# round's usage and cost["judge"] so rec.usage and the cost.round event@@ -272,7 +292,7 @@ def _run_round(else:notes.append(f"build failed: {outcome.build.error_type}: {outcome.build.error_message[:200]}")rec.gates = gates- rec.skills = skills_hook.record_usage(ctx, index=index, kind=kind)+ rec.skills = skills_hook.record_usage(ctx, index=index, kind=skill_kind)_write_gate_reports(ctx, index, gates)rec.commit = ctx.ws.commit(f"r{index:02d} {kind}")@@ -288,7 +308,8 @@ def _run_round(# ----------------------------------------------------------------------------- cost of a round-def skip_judge_reason(ctx: RunContext, *, gates: Sequence[GateReport], renders: RenderSet | None) -> str:+def skip_judge_reason(ctx: RunContext, *, gates: Sequence[GateReport], renders: RenderSet | None,+ ignore_budget: bool = False) -> str:"""Why this round must NOT be judged (``""`` = judge it).Only states in which the verdict is never bought at all — a skip that the@@ -299,6 +320,8 @@ def skip_judge_reason(ctx: RunContext, *, gates: Sequence[GateReport], renders:* ``budget already exceeded`` — the loop's next ``budget_ok`` check ends therun, so this verdict could not promote anything. Measured: 2 verdicts /$0.09 in the audit were bought past the run's wall clock (docs/COST.md §5).+ ``ignore_budget`` exempts the best-of-N candidates: their verdict picks the+ code r00 starts from, so skipping it wastes the N generations already paid for.* ``gate errors`` — only when the caller set ``judge_on_gate_errors=False``;``rejudge_round`` honours that too, so the verdict is not re-bought.@@ -309,7 +332,7 @@ def skip_judge_reason(ctx: RunContext, *, gates: Sequence[GateReport], renders:return "no judge configured"if renders is None or not renders.views:return "no renders"- if not ctx.budget.ok():+ if not ctx.budget.ok() and not ignore_budget:return "budget already exceeded"if judge_blocked_by_gates(ctx, gates):return "gate errors"@@ -379,7 +402,7 @@ def record_aborted_round(ctx: RunContext, *, index: int, kind: str, usage: Usage"""A round that raised half-way still reports what it burned.Its record is written next to the round records as ``aborted_rNN.json`` (never- ``rNN.json``: the round did not happen, and ``load_round_records`` must not+ ``rNN.json``: the round did not happen, and ``load_round_journal`` must notresume from it), a ``cost.round`` event is emitted, and the usage is rememberedin ``ctx.extra`` so the run record can carry it. Accounting a stop must neverraise on top of the stop that is already happening."""@@ -398,7 +421,8 @@ def record_aborted_round(ctx: RunContext, *, index: int, kind: str, usage: Usagedef _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildResult, gates: list[GateReport],- rec: RoundRecord, previous: Judgment | None, notes: list[str]) -> tuple[Judgment | None, Usage]:+ rec: RoundRecord, previous: Judgment | None, notes: list[str], *,+ geometry_views: bool = True) -> tuple[Judgment | None, Usage]:"""Judge one round → ``(judgment, paid_usage)``.``judgment`` is ``None`` when the verdict is unusable (the judge crashed or@@ -407,8 +431,6 @@ def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildResits ``cost.round`` event. Failure notes are appended to the CALLER's``notes`` list — ``_run_round`` joins that list into ``rec.notes`` at theend of the round, so writing to ``rec.notes`` here was silently lost."""- from codeverse.judges.base import JudgeInput-renders = rec.rendersjv = getattr(pipeline, "judge_views", None)if callable(jv) and renders is not None:@@ -418,7 +440,7 @@ def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildReslog.warning("judge_views selection failed: %s", e)renders = rec.rendersgeometry = None- gv = getattr(pipeline, "geometry_views", None)+ gv = getattr(pipeline, "geometry_views", None) if geometry_views else Noneif callable(gv):try:geometry = gv(ctx, index, build)@@ -447,9 +469,9 @@ def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildResnotes.append(f"judge failed: {type(e).__name__}: {e}")return None, paidctx.ws.write_json(ctx.ws.judge_path(index), judgment)- if _is_degraded(judgment):+ if is_degraded(judgment):# a glitch, never a score: keep the raw verdict on disk, pay for it, but do not- # let 0.0 poison plateau/best/refine (judges/scoring.degraded_judgment contract)+ # let 0.0 poison plateau/best/refine (judges/rubrics.degraded_judgment contract)ctx.budget.add(judgment.usage, stage="judge", role="judge", round_index=index,label=judgment.rubric or "judge", outcome="degraded")ctx.events.emit("judge.degraded", round=index, error=judgment.summary[:300],@@ -462,14 +484,6 @@ def _judge(ctx: RunContext, pipeline: RoundPipeline, index: int, build: BuildResreturn judgment, judgment.usage-def _is_degraded(judgment: Judgment) -> bool:- try:- from codeverse.judges.rubrics import is_degraded- except ImportError: # pragma: no cover — judges package always ships with tracks- return False- return is_degraded(judgment)--def rejudge_round(ctx: RunContext, pipeline: RoundPipeline, rec: RoundRecord, previous: Judgment | None = None) -> bool:"""Re-judge an already built+rendered round whose judgment FAILED or was degraded.diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.pyindex 5ea16e7e..43ccb430 100644--- a/harness/tests/orchestrator_tracks/fakes.py+++ b/harness/tests/orchestrator_tracks/fakes.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport jsonimport threading-import timefrom collections.abc import Callable, Sequencefrom pathlib import Pathfrom typing import Any@@ -129,9 +128,6 @@ class FakeRuntime:def contract_doc(self) -> str:return f"FAKE CONTRACT for {self.language.value}"- def cookbook_path(self) -> Path:- return Path("/dev/null")-# ----------------------------------------------------------------------------- agent / modelclass FakeAgent:@@ -386,7 +382,7 @@ class FakeServices(Services):fix_hint=f"shrink {j.child} by 17 mm along the axis") for j in list(getattr(plan, "joints", []))[: self.sweep_errors]]return GateReport(gate="joint_sweep", passed=not findings, findings=findings), views- def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, cookbook_rel: str, spatial_tools: bool, mcp_command: list[str]) -> None:+ def materialize(self, ws: Workspace, *, agent_kind: str, contract_md: str, cookbook_rel: str, spatial_tools: bool) -> None:(ws.root / "AGENTS.md").write_text(contract_md)self.materialized.append(agent_kind)@@ -402,12 +398,3 @@ class FakeServices(Services):def finalize_record(self, ws: Workspace, record: RunRecord) -> None:self.records.append(record)ws.write_json(ws.record_path, record)---def wait_for(pred: Callable[[], bool], timeout: float = 5.0) -> bool:- t0 = time.time()- while time.time() - t0 < timeout:- if pred():- return True- time.sleep(0.01)- return Falsediff --git a/harness/tests/orchestrator_tracks/test_budget_snapshot.py b/harness/tests/orchestrator_tracks/test_budget_snapshot.pyindex 392655a7..b0c6f734 100644--- a/harness/tests/orchestrator_tracks/test_budget_snapshot.py+++ b/harness/tests/orchestrator_tracks/test_budget_snapshot.py@@ -1,14 +1,4 @@-"""Budget continuity across resume + charge-before-persist ordering.--A resume used to rebuild the guard with only ``spent`` restored: ``billed_usd``,-``calls``, the stage/round buckets and the wall clock all restarted at zero, so-after a resume the money/time already spent no longer constrained new work and a-raised ``--max-usd`` granted a FULL fresh cap. The guard now snapshots and-restores its whole accumulator state (``BudgetSnapshot``), and paid work is-persisted BEFORE the ceiling is enforced: single-shot responses are written to-disk, fan-out siblings are arbitrated/adopted, and planner attempts are booked-the moment each call is paid.-"""+"""Budget continuity across resume and charge-before-persist ordering."""from __future__ import annotations@@ -52,7 +42,7 @@ def test_resume_restores_money_calls_and_active_time_but_not_downtime():g2.restore(revived)assert g2.billed_usd == pytest.approx(0.65) and g2.calls == 2assert g2.by_stage == {"baseline": pytest.approx(0.6), "judge": pytest.approx(0.05)}- assert g2.round_costs(0) == {"baseline": pytest.approx(0.6), "judge": pytest.approx(0.05)}+ assert g2.by_round.get(0, {}) == {"baseline": pytest.approx(0.6), "judge": pytest.approx(0.05)}# ACTIVE minutes carry over; the downtime between the sessions cost nothingassert g2.elapsed_minutes() == pytest.approx(2.0, abs=0.1)g2.start_time -= 60 # one more ACTIVE minute in THIS session accumulates on top@@ -68,7 +58,6 @@ def test_resume_restores_money_calls_and_active_time_but_not_downtime():def test_a_raised_cap_grants_only_the_difference_and_grace_never_persists():- """A resumed run gets the raised ceiling MINUS what it already used, not a fresh one."""import time as _tg1 = BudgetGuard(Budget(max_minutes=10.0), start_time=_t.time())@@ -96,7 +85,7 @@ def test_build_context_restores_the_snapshot_and_falls_back_to_legacy_spent(tmp_state.extra["budget_snapshot"] = g.snapshot().model_dump(mode="json")ctx = track.build_context(spec, ws, EventLog(ws.events_path), state)assert ctx.budget.billed_usd == pytest.approx(0.4) and ctx.budget.calls == 1- assert ctx.budget.round_costs(0)["baseline"] == pytest.approx(0.4)+ assert ctx.budget.by_round.get(0, {})["baseline"] == pytest.approx(0.4)# legacy fallback: an old run dir carries only spent_usage (spent restored, as before)state2 = RunState()@@ -129,7 +118,8 @@ def test_a_budget_tripped_candidate_still_lets_the_sibling_be_adopted(tmp_path,def writer(job, ws_):if ws_.root.name == "c0": # <ws>/_cand/c0 trips the ceiling mid-generation- raise BudgetExceeded("cost $9.99 exceeds max_usd $5.00", spent_usd=9.99, elapsed_min=1.0)+ raise BudgetExceeded("elapsed 9.99 min exceeds max_minutes 5.00",+ spent_usd=9.99, elapsed_min=9.99)return {"src/object.js": f"// {job.label} in {ws_.root.name}\n""export function build(THREE) { return new THREE.Group(); }\n"}diff --git a/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.pyindex c23153e6..1662c3c8 100644--- a/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py+++ b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py@@ -42,8 +42,7 @@ def _planner(plan_dict):# ----------------------------------------------------------------------------- pure logicdef test_round_policy_candidates_and_compaction():pol = RoundPolicy()- assert pol.n_candidates == 1 and pol.with_candidates(None) is pol and pol.with_candidates(3).n_candidates == 3- assert pol.with_candidates(0).n_candidates == 1 and pol.parallel_min_tasks == 2+ assert pol.n_candidates == 1 and pol.parallel_min_tasks == 2tasks = [RefineTask(target=f"BackLeg_{i}", kind="gate:connectivity", instruction=f"leg {i} floats", priority=0, source="gate") for i in range(4)]tasks += [RefineTask(target="Seat", kind="geometry", instruction="thicker", priority=2)]tasks += [RefineTask(target=f"Spindle_{i}", kind="gate:contract", instruction="off", priority=0, source="gate") for i in range(3)]@@ -96,14 +95,14 @@ def test_rank_candidates_and_decide_best():assert decide_best(None, 0.5, margin=0.03, min_confidence=0.6, compare=None) == ("score", None)[email protected]("text,expected", [- ("drawer pulls out towards -Y", "-y"), ("lid opens upward", "up"), ("door swings to the left", "left"),- ("drawer slides out", "front"), ("opens to the front", "front"), ("seat folds down", "down"),- ("drawer pushes in", "back"), ("lid hinges up and out", None), ("spins around its axis", None),- ("", None), ("handle turns", None), ("does not move up", None), ("lower drawer pulls out", "front"),-])-def test_expected_direction(text, expected):- assert expected_direction(text) == expected+def test_expected_direction():+ cases = [+ ("drawer pulls out towards -Y", "-y"), ("lid opens upward", "up"), ("door swings to the left", "left"),+ ("drawer slides out", "front"), ("opens to the front", "front"), ("seat folds down", "down"),+ ("drawer pushes in", "back"), ("lid hinges up and out", None), ("spins around its axis", None),+ ("", None), ("handle turns", None), ("does not move up", None), ("lower drawer pulls out", "front"),+ ]+ assert [expected_direction(text) for text, _ in cases] == [expected for _, expected in cases]# ----------------------------------------------------------------------------- best-of-N track run@@ -177,14 +176,17 @@ def test_best_of_two_pairwise_tiebreak_overrides_ranking(tmp_path, chair_plan, sdef test_candidate_count_persists_for_resume_and_settings_default(tmp_path, chair_plan, settings):- spec = make_spec(language=Language.BLENDER, max_rounds=0)+ from codeverse.contracts.spec import RunOptions++ # the CLI writes --candidates into spec.options (the persisted carrier — spec.json travels+ # with the run); run_state.json no longer mirrors it+ spec = make_spec(language=Language.BLENDER, max_rounds=0, options=RunOptions(candidates=2))ws = Workspace(tmp_path / "runs" / "stool3")track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.5,)), agent=FakeAgent(_writer_by_candidate),planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,- runtime=FakeRuntime(Language.BLENDER), n_candidates=2)+ runtime=FakeRuntime(Language.BLENDER))track.run(spec, ws)- state = json.loads(ws.state_path.read_text())- assert state["extra"]["n_candidates"] == 2+ assert json.loads(ws.state_path.read_text())["extra"].get("n_candidates") is None# a resume without the flag reads the persisted widtht2 = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.5,)), agent=FakeAgent(_writer_by_candidate),planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.BLENDER))@@ -196,7 +198,8 @@ def test_candidate_count_persists_for_resume_and_settings_default(tmp_path, chaisettings2 = settings.model_copy()object.__setattr__(settings2, "default_candidates", 3)t3 = StaticObjectTrack(services=FakeServices(), settings=settings2, runtime=FakeRuntime(Language.BLENDER))- ctx3 = t3.build_context(spec, Workspace(tmp_path / "runs" / "fresh").create(), EventLog(tmp_path / "e.jsonl"), RunState())+ ctx3 = t3.build_context(make_spec(language=Language.BLENDER, max_rounds=0), Workspace(tmp_path / "runs" / "fresh").create(),+ EventLog(tmp_path / "e.jsonl"), RunState())assert ctx3.policy.n_candidates == 3assert get_track("static_object", n_candidates=4)._n_candidates == 4@@ -393,6 +396,7 @@ def test_a_track_without_a_glb_still_gets_candidate_renders():never reached, and every extra candidate was generated, paid for and discarded blind."""from pathlib import Path+ from types import SimpleNamespacefrom codeverse.tracks.candidates import quick_render@@ -409,17 +413,20 @@ def test_a_track_without_a_glb_still_gets_candidate_renders():ws = _WS()pipe = _Pipeline()- got = quick_render(_Ctx(), None, pipeline=pipe, build="BUILD", measurement="MEAS")+ build = SimpleNamespace(glb_path=None)+ got = quick_render(_Ctx(), 0, build, "MEAS", pipeline=pipe)assert got == "frames-renderset", "no GLB must fall back to the track's own renderer"- assert pipe.calls == [(0, "BUILD", "MEAS")]+ assert pipe.calls == [(0, build, "MEAS")]# and with nothing to fall back to, it still degrades quietly rather than raising- assert quick_render(_Ctx(), None) is None+ assert quick_render(_Ctx(), 0, build, None) is Nonedef test_an_object_candidate_still_uses_the_cheap_rig(tmp_path):"""The fallback must not make the object path more expensive: a GLB still goes throughthe reduced-view, reduced-resolution quick rig, not pipeline.render."""+ from types import SimpleNamespace+from codeverse.tracks.candidates import OBJECT_VIEWS_QUICK, QUICK_PX, quick_renderseen = {}@@ -427,7 +434,7 @@ def test_an_object_candidate_still_uses_the_cheap_rig(tmp_path):class _Services:def render_object(self, glb, out_dir, *, views, width, height):seen.update(glb=glb, views=views, width=width, height=height)- return "object-renderset"+ return SimpleNamespace(views=[])class _WS:def renders_dir(self, i): return tmp_path@@ -435,11 +442,12 @@ def test_an_object_candidate_still_uses_the_cheap_rig(tmp_path):class _Ctx:ws = _WS()services = _Services()+ extra = {"pose_views": ["pose-view"]} # what ArticulatedPipeline.gates() parked for render()class _Pipeline:def render(self, *a, **k): # must not be reachedraise AssertionError("an object candidate must not use pipeline.render")- got = quick_render(_Ctx(), "/x/object.glb", pipeline=_Pipeline(), build="B", measurement="M")- assert got == "object-renderset"+ got = quick_render(_Ctx(), 0, SimpleNamespace(glb_path="/x/object.glb"), "M", pipeline=_Pipeline())+ assert got.views == ["pose-view"] # the quick rig still carries the articulated pose views to the judgeassert seen["views"] == OBJECT_VIEWS_QUICK and seen["width"] == QUICK_PXdiff --git a/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py b/harness/tests/orchestrator_tracks/test_cookbook_excerpt.pyindex 39d44b80..1c4ae1fd 100644--- a/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py+++ b/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py@@ -15,23 +15,9 @@ from codeverse.contracts.common import Language, Trackfrom codeverse.prompts import PROMPTS_DIR, load_textfrom codeverse.prompts.sections import split_sections-AURORA = "Aurora borealis over a mountain ridge with a frozen lake, dense stars, green and violet curtains"-RAIN = "rain drops running down a window at night, blurred city lights behind the glass"EXAMPLE = PROMPTS_DIR / "glsl_shader" / "examples" / "aurora_ridge.frag"-def _ctx() -> SimpleNamespace:- return SimpleNamespace(cookbook_text=load_text("glsl_shader/cookbook.md"))---def _titles(text: str) -> list[str]:- return [s.title for s in split_sections(text) if s.level == 2]---def _chapter_bodies(md: str) -> dict[str, str]:- return {s.title: s.body.rstrip() for s in split_sections(md)}--def test_real_cookbook_parses_into_chapters() -> None:secs = [s for s in split_sections(load_text("glsl_shader/cookbook.md")) if s.level == 2]assert len(secs) >= 10@@ -46,8 +32,8 @@ def test_every_track_sends_the_whole_cookbook(monkeypatch) -> None:It used to be ``ctx.cookbook_text[:6000]`` in base_prompt_context and a 9 000-charchapter selection in graphics — 13 % of blender's 46 623 chars, 10 % of- scene_threejs's 57 631, cut mid-snippet. The read_cookbook tool was the stated- escape hatch and went uncalled in all 20 measured sessions, so what the prefix left+ scene_threejs's 57 631, cut mid-snippet. On-demand cookbook lookup was the stated+ escape hatch and went unused in all 20 measured sessions, so what the prefix leftout simply never reached the model. Chapter SELECTION is still right where thestage knows which chapters it needs (scene's env/zone recipes, graphics' recipeseeding); it is not right as a way to shrink the reference itself.@@ -60,7 +46,7 @@ def test_every_track_sends_the_whole_cookbook(monkeypatch) -> None:dims={}, reference_images=[], reference_notes=""),track=Track.GRAPHICS, language=Language.GLSL_SHADER,contract_text="CONTRACT", cookbook_rel="glsl_shader/cookbook.md",- cookbook_text=big, tool_cards="", single_shot=True,+ cookbook_text=big, tool_cards="", single_shot=True, extra={},runtime=SimpleNamespace(entry_globs=()))monkeypatch.setattr(graphics_steps, "constraints_text", lambda spec: "")monkeypatch.setattr(graphics_steps, "reference_note", lambda ctx: "")diff --git a/harness/tests/orchestrator_tracks/test_cost_accounting.py b/harness/tests/orchestrator_tracks/test_cost_accounting.pyindex abb73282..aec530e5 100644--- a/harness/tests/orchestrator_tracks/test_cost_accounting.py+++ b/harness/tests/orchestrator_tracks/test_cost_accounting.py@@ -1,13 +1,4 @@-"""Closing the accounting holes docs/COST.md §6 found, and the money stops of §5.--The audit measured $4.80 of real spend that never reached ``record.total_usage``-(and therefore never reached ``BudgetGuard``): rounds the budget cut after the-work was done, retried ``.a2`` agent sessions, post-hoc texture passes. These-tests replay the *recorded* usage of three of those runs-(``data/offrecord_runs.json``, taken from the read-only bench runs) through the-production accounting objects and assert that every dollar now lands in the-guard, in one ledger row, and in a round bucket.-"""+"""Cost replay, ledger attribution, and billed-versus-notional accounting."""from __future__ import annotations@@ -19,7 +10,8 @@ import pytestfrom codeverse.contracts.agent import AgentJob, AgentResultfrom codeverse.contracts.common import Budget, Usage-from codeverse.cost.ledger import load_ledger+from codeverse.cost.instrument import MeteredAgent, run_ledger+from codeverse.cost.ledger import load_ledger, record_callfrom codeverse.orchestrator import BudgetExceeded, BudgetGuard, usage_deltafrom codeverse.tracks.generation import GenerationTask, _SessionAcc@@ -46,42 +38,51 @@ class _RecordedAgent:return AgentResult(ok=True, exit_reason=s["exit_reason"] or "completed", usage=_usage(s))-def replay(name: str, ledger: Path | None, *, texture: bool = True) -> BudgetGuard:- """Spend one recorded run's money through today's accounting path."""+def replay(name: str, root: Path | None, *, texture: bool = True) -> BudgetGuard:+ """Spend one recorded run's money through today's accounting path.++ The guard only buckets and enforces; the ledger rows come from the ONE writer —+ ``MeteredAgent`` for a session, ``record_call`` (what ``MeteredChatModel`` does+ per call) for the judge and texture money — inside ``run_ledger(root)``, as+ ``BaseTrack.run`` opens it. ``root=None`` replays with no ledger at all."""fx = FIXTURES[name]- guard = BudgetGuard(Budget(max_minutes=10_000), run=name, ledger=ledger)+ guard = BudgetGuard(Budget(max_minutes=10_000))tasks: dict[tuple[str, int], list[dict]] = {}for s in fx["sessions"]:tasks.setdefault((s["job_label"] or s["label"], int(s["round"] or 0)), []).append(s)- for (label, rnd), sessions in tasks.items():- sessions.sort(key=lambda s: s["attempt"])- task = GenerationTask(label=label, prompt="p", round=rnd,- kind="baseline" if label.startswith("baseline") else "refine")- acc = _SessionAcc(task=task, budget=guard)- agent = _RecordedAgent(sessions)- for _ in sessions: # attempt 1, then the .a2 retry — exactly as run_agent_task does- acc.run(agent, AgentJob(workspace="/tmp", prompt="p", label=label, round=rnd))- for j in fx["judges"]: # steps.run_round- guard.add(Usage(cost_usd=j["cost_usd"], input_tokens=j["input_tokens"], output_tokens=j["output_tokens"]),- stage="judge", role="judge", round_index=j["round"], label=j["rubric"])- if texture:- for t in fx["post_hoc_texture_passes"]: # lifecycle._texture_pass- guard.add(Usage(cost_usd=t["cost_usd"]), stage="texture", role="image", label="texture_pass")+ with run_ledger(root or Path("/nonexistent"), run=name, create=root is not None):+ for (label, rnd), sessions in tasks.items():+ sessions.sort(key=lambda s: s["attempt"])+ task = GenerationTask(label=label, prompt="p", round=rnd,+ kind="baseline" if label.startswith("baseline") else "refine")+ acc = _SessionAcc(task=task, budget=guard)+ agent = MeteredAgent(_RecordedAgent(sessions))+ for i in range(len(sessions)): # attempt 1, then the .a2 retry — exactly as run_agent_task does+ job_label = label if i == 0 else f"{label}.a{i + 1}"+ acc.run(agent, AgentJob(workspace="/tmp", prompt="p", label=job_label, round=rnd))+ for j in fx["judges"]: # steps.run_round: the judge's MeteredChatModel writes, the guard buckets+ u = Usage(cost_usd=j["cost_usd"], input_tokens=j["input_tokens"], output_tokens=j["output_tokens"])+ record_call(u, round=j["round"], stage="judge", role="judge", label=j["rubric"])+ guard.add(u, stage="judge", role="judge", round_index=j["round"], label=j["rubric"])+ if texture:+ for t in fx["post_hoc_texture_passes"]: # lifecycle._texture_pass+ u = Usage(cost_usd=t["cost_usd"])+ record_call(u, stage="texture", role="image", label="texture_pass")+ guard.add(u, stage="texture", role="image", label="texture_pass")return guard@pytest.mark.parametrize("name", sorted(FIXTURES))def test_every_recorded_dollar_reaches_the_guard_and_the_ledger(name, tmp_path):fx = FIXTURES[name]- ledger = tmp_path / "cost_ledger.jsonl"- guard = replay(name, ledger)+ guard = replay(name, tmp_path)sessions = sum(s["cost_usd"] for s in fx["sessions"])judges = sum(j["cost_usd"] for j in fx["judges"])texture = sum(t["cost_usd"] for t in fx["post_hoc_texture_passes"])# nothing is lost between the sessions and the guard — retries includedassert guard.spent.cost_usd == pytest.approx(sessions + judges + texture, abs=1e-6)# and the ledger the run ships is the same number, one row per call- rows = load_ledger(ledger)+ rows = load_ledger(tmp_path) # telemetry/cost.jsonl, one writerassert len(rows) == len(fx["sessions"]) + len(fx["judges"]) + len(fx["post_hoc_texture_passes"])assert sum(r.cost_usd for r in rows) == pytest.approx(guard.spent.cost_usd, abs=1e-6)# a retried session is its OWN row, labelled .a2 — the reconstructor had to guess@@ -91,21 +92,17 @@ def test_every_recorded_dollar_reaches_the_guard_and_the_ledger(name, tmp_path):def test_the_round_the_budget_cut_is_still_reported():- """tool_med_hand_drill spent $0.86 on r02 and then stopped: the round is not in- ``record.rounds`` at all, so its dollars used to be attributable to nothing."""fx = FIXTURES["tool_med_hand_drill"]assert fx["rounds_in_record"] == [0, 1]cut = [s for s in fx["sessions"] if s["round"] == 2]assert cut, "fixture must contain the round the budget cut"guard = replay("tool_med_hand_drill", None)burned = sum(s["cost_usd"] for s in cut)- assert guard.round_costs(2)["refine"] == pytest.approx(burned, abs=1e-6)+ assert guard.by_round.get(2, {})["refine"] == pytest.approx(burned, abs=1e-6)assert burned > 0.8 # $0.86 that record.rounds never mentioneddef test_post_hoc_texture_passes_are_inside_the_total_now():- """furn_hard_rolltop_desk ran four texture passes for $0.656; ``record.total_usage``- said $1.2165. Charged through the guard the run reports $1.87."""fx = FIXTURES["furn_hard_rolltop_desk"]with_tex = replay("furn_hard_rolltop_desk", None)without = replay("furn_hard_rolltop_desk", None, texture=False)@@ -121,7 +118,7 @@ def test_spend_buckets_by_stage_and_round_and_only_charge_enforces():g0.charge(Usage(cost_usd=0.4), stage="baseline", round_index=0, label="baseline")g0.add(Usage(cost_usd=0.05), stage="judge", role="judge", round_index=0)assert g0.by_stage == {"baseline": pytest.approx(0.4), "judge": pytest.approx(0.05)}- assert g0.round_costs(0)["judge"] == pytest.approx(0.05) and g0.round_costs(9) == {}+ assert g0.by_round.get(0, {})["judge"] == pytest.approx(0.05) and g0.by_round.get(9, {}) == {}assert list(g0.stage_summary())[0] == "baseline" # biggest bucket firstg = BudgetGuard(Budget(max_minutes=1.0), start_time=time.time() - 600) # already past@@ -140,54 +137,33 @@ def test_usage_delta_reports_what_a_round_burned():assert usage_delta(before, after).cost_usd == 0.0 # never negative-def test_the_ledger_is_optional_and_never_breaks_a_run(tmp_path):- g = BudgetGuard(Budget(max_minutes=60), ledger=tmp_path / "sub" / "dir" / "l.jsonl")- g.charge(Usage(cost_usd=0.1), stage="plan", role="planner")- assert len(load_ledger(tmp_path / "sub" / "dir" / "l.jsonl")) == 1- quiet = BudgetGuard(Budget(max_minutes=60)) # no ledger configured- quiet.charge(Usage(cost_usd=0.1))- assert quiet.spent.cost_usd == pytest.approx(0.1)+def test_the_guard_never_writes_a_ledger_row_itself(tmp_path, monkeypatch):+ """One writer: a charge outside any run ledger lands nowhere, not in a second file."""+ monkeypatch.setenv("CV3D_COST_LEDGER", str(tmp_path / "process.jsonl"))+ from codeverse.cost import ledger as ledger_mod+ monkeypatch.setattr(ledger_mod, "_fallback_read", False)+ quiet = BudgetGuard(Budget(max_minutes=60))+ quiet.charge(Usage(cost_usd=0.1), stage="plan", role="planner")+ assert quiet.spent.cost_usd == pytest.approx(0.1)+ assert not (tmp_path / "process.jsonl").exists() and not any(tmp_path.glob("**/*.jsonl"))-# ------------------------------------------------- subscription backends vs the guard-def test_a_subscription_backend_does_not_consume_the_spend_guard():- """``max_usd`` guards money, and a flat-rate CLI costs none.-- Measured 2026-08-25, ``tsr_scn_temple_night`` (``codex:gpt-5.6-sol``,- ``--profile quality``): two Blender hero sessions priced at OpenAI list rates put the- run at $7.712 against the $4.40 soft cap in 6.8 minutes, so the asset judge was- skipped for BOTH heroes and every later stage ran degraded — over a bill of $0.00.- The run's own cost ledger said $0.00; only the guard disagreed.- """- from codeverse.contracts.common import Budget, Usage- from codeverse.orchestrator import BudgetGuard+def test_backend_billing_and_time_guard():g = BudgetGuard(Budget(max_minutes=60.0), soft_fraction=0.55)- g.spend(Usage(backend="codex", model="gpt-5.6-sol", cost_usd=7.712), enforce=False)-+ g.add(Usage(backend="codex", model="gpt-5.6-sol", cost_usd=7.712))assert g.billed_usd == 0.0- assert g.soft_exceeded() == "" # the degradation that actually happened- assert g.ok()- # the notional price is NOT discarded — reports and $/complexity still want it+ assert g.soft_exceeded() == "" and g.ok()assert g.spent.cost_usd == pytest.approx(7.712)assert g.summary()["notional_usd"] == pytest.approx(7.712)assert g.summary()["spent_usd"] == 0.0--def test_the_guard_still_enforces_backends_that_really_bill():- """The exemption must not become a hole: API backends keep both ceilings, and an- unclassified backend is enforced rather than exempted."""- from codeverse.contracts.common import Budget, Usage- from codeverse.orchestrator import BudgetExceeded, BudgetGuard-- g = BudgetGuard(Budget(max_minutes=60.0), soft_fraction=0.55)- g.spend(Usage(backend="codex", cost_usd=99.0), enforce=False) # subscription: notional- g.spend(Usage(backend="gemini", cost_usd=5.0), enforce=False) # API: real dollars- assert g.billed_usd == pytest.approx(5.0), "a subscription must not bill"+ g.add(Usage(backend="gemini", cost_usd=5.0))+ assert g.billed_usd == pytest.approx(5.0)assert g.ok() and not g.soft_exceeded()- g.spend(Usage(backend="some-new-provider", cost_usd=4.0), enforce=False)- assert g.billed_usd == pytest.approx(9.0), "an unknown backend must bill, not be exempt"- g._active_s = 3600.0 # noqa: SLF001+ g.add(Usage(backend="some-new-provider", cost_usd=4.0))+ assert g.billed_usd == pytest.approx(9.0)+ g._active_s = 3600.0 # noqa: SLF001with pytest.raises(BudgetExceeded):g.check()diff --git a/harness/tests/orchestrator_tracks/test_cost_latency.py b/harness/tests/orchestrator_tracks/test_cost_latency.pyindex 8e529840..2e341b93 100644--- a/harness/tests/orchestrator_tracks/test_cost_latency.py+++ b/harness/tests/orchestrator_tracks/test_cost_latency.py@@ -1,6 +1,4 @@-"""Cost/latency shaping of the scene baseline: soft budget, single-shot assets,-zone batching, judge skipping, and the salvage round that stops a budget-stopped-run from finishing with no score at all."""+"""Scene cost/latency shaping: batching, cheap assets, and budget salvage."""from __future__ import annotations@@ -73,12 +71,6 @@ def test_timeout_is_clipped_to_the_wall_clock_left():assert g.timeout_s(1800, floor_s=90) == 90 # floor, never 0-def _usage(cost: float):- from codeverse.contracts.common import Usage-- return Usage(backend="fake", cost_usd=cost)--# ----------------------------------------------------------------------------- dedupedef _asset(name: str, size: tuple[float, float, float], kind: str = "threejs") -> AssetPlan:return AssetPlan(name=name, kind=kind, description=f"a {name}", approx_size_m=size)@@ -122,8 +114,6 @@ def test_small_zones_share_a_session_and_big_ones_keep_the_fan_out():assert plan_zone_batches(zones) == batchesassert zone_file(zones[0]) == "src/zones/small1.js"--def test_every_zone_gets_exactly_one_owner_file():zones = [_zone(f"Z{i}", i % 5) for i in range(9)]batches = plan_zone_batches(zones)files = [zone_file(z) for b in batches for z in b]@@ -132,9 +122,6 @@ def test_every_zone_gets_exactly_one_owner_file():# ----------------------------------------------------------------------------- single-shot assetsdef test_single_shot_needs_a_chat_model_not_a_coding_agent():- """Single-shot is ONE api call for an asset file — the cheap path before a full agent- session. The coding agent is always a vendor CLI now (2026-08-28), which exposes no- chat model, so the model comes from the run's planner backend."""assert single_shot_agent_id("gemini-cli:gemini-3.6-flash", "gemini:gemini-3.6-flash") == "single-shot:gemini:gemini-3.6-flash"assert single_shot_agent_id("single-shot:gemini:x") == "single-shot:gemini:x"assert single_shot_agent_id("gemini-cli:gemini-3.6-flash") == "" # no chat model given@@ -351,8 +338,6 @@ def _writer(job, ws):@needs_nodedef test_a_merged_asset_leaves_a_working_shim_not_the_placeholder_box(tmp_path, settings, monkeypatch):- """Over the cap, twins merge — and a zone that imports the merged name must still- get the real prop, not the skeleton's blockout box."""import codeverse.tracks.scene_assets as samonkeypatch.setattr(sa, "MAX_ASSETS", 1) # force the rescue path with a tiny plan@@ -374,17 +359,13 @@ def test_a_merged_asset_leaves_a_working_shim_not_the_placeholder_box(tmp_path,assert chk.ok and chk.meshes == 2, "the shim resolves to the real factory, not the blockout stub"-def test_every_planned_asset_is_built_while_the_plan_fits_under_the_cap():- """Dedupe is a cap rescue: a distinct prop is worth more than a variant flag."""+def test_asset_selection_folds_only_over_the_cap():twins = [_asset("PondRock", (1.1, 0.75, 0.9)), _asset("SteppingStone", (0.65, 0.12, 0.55))]kept, alias = select_assets(twins, cap=8)assert [k.name for k in kept] == ["PondRock", "SteppingStone"] and not aliaskept, alias = select_assets(twins, cap=1)assert [k.name for k in kept] == ["PondRock"] and alias == {"SteppingStone": "PondRock"}--def test_over_the_cap_folding_beats_truncation():- """8 planned props, cap 4: folding rescues twins that truncation would delete."""assets = [_asset("HeroBoulder", (2.4, 2.0, 2.2)), _asset("Bench", (1.6, 0.9, 0.6)),_asset("Lantern", (0.4, 1.2, 0.4)), _asset("Crate", (0.6, 0.5, 0.6)),_asset("TalusRock", (1.8, 1.4, 1.6)), _asset("Stool", (0.5, 0.6, 0.5)),@@ -397,7 +378,6 @@ def test_over_the_cap_folding_beats_truncation():def test_a_batched_session_that_writes_only_one_file_fails_the_other_zone(tmp_path, settings):- """The skeleton leaves a stub at every zone path, so 'the file exists' proves nothing."""plan = ScenePlan.model_validate(plan_example(Track.SCENE))plan = plan.model_copy(update={"assets": [_asset("Bollard", (0.3, 0.5, 0.3))],"zones": [_zone("Quay", 0), _zone("Water", 0)]})@@ -422,7 +402,6 @@ def test_a_batched_session_that_writes_only_one_file_fails_the_other_zone(tmp_pa@needs_nodedef test_an_imperfect_asset_stays_available_but_a_broken_one_does_not(tmp_path, settings):- """Wrong size = worth one repair; won't import = zones must not reference it."""services = FakeServices()ctx = _scene_ctx(tmp_path, settings, services=services)(ctx.ws.src / "assets").mkdir(parents=True, exist_ok=True)@@ -436,9 +415,6 @@ def test_an_imperfect_asset_stays_available_but_a_broken_one_does_not(tmp_path,def test_a_scene_round_judged_at_the_ceiling_is_still_promoted(tmp_path, settings):- """The batch-2 promotion order must hold for scenes too: the verdict is paid for,- recorded and promoted BEFORE the loop notices the budget is gone — and the salvage- must not then run a second round 0 on top of it."""plan = _threejs_scene_plan()spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=2)ws = Workspace(tmp_path / "runs" / "ceiling")@@ -458,8 +434,6 @@ def test_a_scene_round_judged_at_the_ceiling_is_still_promoted(tmp_path, setting@pytest.mark.nodedef test_a_model_outage_escalates_the_asset_instead_of_losing_it(tmp_path, settings):- """A 503 storm that outlives the model layer's retries must fall through to the- agent session, not mark the asset NOT AVAILABLE for every zone."""plan = ScenePlan.model_validate(plan_example(Track.SCENE))plan = plan.model_copy(update={"assets": [_asset("Bollard", (0.3, 0.5, 0.3))], "zones": []})@@ -477,14 +451,10 @@ def test_a_model_outage_escalates_the_asset_instead_of_losing_it(tmp_path, settidef test_a_generation_session_never_outlives_the_wall_budget():- """Measured 2026-08-27: a static run with --max-minutes 30 stopped at 39.0 min with- round 0 unfinished, because run_agent_task handed the session a flat- settings.limits.agent_timeout_s (1800 s) and only checked the ceiling at the next- boundary. The scene track had clipped this since the greenhouse incident."""from codeverse.contracts.spec import Budgetfrom codeverse.orchestrator import BudgetGuard- g = BudgetGuard(Budget(max_minutes=30.0, max_rounds=4), run="t")+ g = BudgetGuard(Budget(max_minutes=30.0, max_rounds=4))assert g.timeout_s(1800, floor_s=120.0) == pytest.approx(1800, abs=60) # fresh run: full sessiong.start_time -= 27 * 60 # 3 minutes leftclipped = g.timeout_s(1800, floor_s=120.0)@@ -494,10 +464,6 @@ def test_a_generation_session_never_outlives_the_wall_budget():def test_one_asset_cannot_eat_the_scene_run():- """Measured 2026-08-27 (scn_med_conservatory, 25-min cap): seven assets finished- inside 5.7 min while one escalation ran the full ASSET_AGENT_TIMEOUT_S and held the- stage to 10.9 min — the stage waits for its slowest, so round 0 started at 18.9 min- and the judged round only happened via the budget salvage at 25.5 min."""from codeverse.contracts.spec import Budgetfrom codeverse.orchestrator import BudgetGuardfrom codeverse.tracks.scene_assets import (@@ -507,7 +473,7 @@ def test_one_asset_cannot_eat_the_scene_run():)class Ctx:- budget = BudgetGuard(Budget(max_minutes=25.0, max_rounds=4), run="t")+ budget = BudgetGuard(Budget(max_minutes=25.0, max_rounds=4))fresh = asset_timeout_s(Ctx, 120)assert fresh < ASSET_AGENT_TIMEOUT_S, "one asset may not have the whole preparation budget"@@ -516,6 +482,6 @@ def test_one_asset_cannot_eat_the_scene_run():assert asset_timeout_s(Ctx, 120) == 120, "and never past the wall clock, floor aside"class Long:- budget = BudgetGuard(Budget(max_minutes=90.0, max_rounds=4), run="t")+ budget = BudgetGuard(Budget(max_minutes=90.0, max_rounds=4))assert asset_timeout_s(Long, 120) == ASSET_AGENT_TIMEOUT_S, "a long run keeps the ceiling"diff --git a/harness/tests/orchestrator_tracks/test_fix_batch2.py b/harness/tests/orchestrator_tracks/test_fix_batch2.pyindex d357e127..30c5f3ca 100644--- a/harness/tests/orchestrator_tracks/test_fix_batch2.py+++ b/harness/tests/orchestrator_tracks/test_fix_batch2.py@@ -68,7 +68,7 @@ def test_judged_round_survives_budget_ceiling_crossed_by_judge(tmp_path, chair_pwas committed/recorded, throwing away a complete judged round (scene r2 case)."""spec = make_spec(max_rounds=3)ws = Workspace(tmp_path / "runs" / "r")- judge = FakeJudge(scores=(0.55,), cost=0.05, minutes=12.0) # this single verdict crosses max_usd+ judge = FakeJudge(scores=(0.55,), cost=0.05, minutes=12.0) # this single verdict crosses max_minutestrack = StaticObjectTrack(services=FakeServices(), judge=judge, agent=FakeAgent(_writer),planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,runtime=FakeRuntime(Language.THREEJS))@@ -103,7 +103,7 @@ def test_finalise_restores_best_when_aborted_round_dirtied_src(tmp_path, chair_passert ws.changed_files() == [] # tree clean at the delivered commit# finding lifecycle.py:256 — the aborted round's charges survive into run_state for resumestate = RunState.load(ws)- spent = state.extra["spent_usage"] # legacy mirror, kept one release+ spent = state.extra["budget_snapshot"]["spent"]assert spent["cost_usd"] == pytest.approx(0.025, abs=1e-6)snap = state.extra["budget_snapshot"]assert snap["billed_usd"] == pytest.approx(0.025, abs=1e-6) and snap["calls"] > 0@@ -130,7 +130,7 @@ def test_spent_usage_saved_when_a_round_crashes(tmp_path, chair_plan, settings):with pytest.raises(RuntimeError, match="gate exploded"):track.run(spec, ws)state = RunState.load(ws)- spent = state.extra["spent_usage"] # legacy mirror, kept one release+ spent = state.extra["budget_snapshot"]["spent"]# planner 0.002 + r0 agent 0.01 + r0 judge 0.003 + r1 agent 0.01 — the r1 charge must not vanishassert spent["cost_usd"] == pytest.approx(0.025, abs=1e-6)assert state.extra["budget_snapshot"]["billed_usd"] == pytest.approx(0.025, abs=1e-6)diff --git a/harness/tests/orchestrator_tracks/test_generation_depth.py b/harness/tests/orchestrator_tracks/test_generation_depth.pyindex 93a0f312..e0c77a6f 100644--- a/harness/tests/orchestrator_tracks/test_generation_depth.py+++ b/harness/tests/orchestrator_tracks/test_generation_depth.py@@ -1,16 +1,7 @@-"""Generation depth: complexity-aware budgets, per-part scoped baselines, the detail round.--The measured motivation is in the wave's ``complexity_baseline.md`` and repeated in-``codeverse/tracks/depth.py``: across 88 consecutive refine-round pairs the built part-count never changed once, mean Δgeometry_detail per refine round was +0.003, and the-refine rounds that DID add geometry lost assembly_fit for it. So depth is bought in-round 0 (scoped fan-out) and polish gets its own round behind a clean-structure gate.-"""+"""Complexity-aware depth budgets, scoped baselines, and the gated detail round."""from __future__ import annotations-import pytest-from codeverse.contracts.artifacts import (BuildResult,GateFinding,@@ -27,11 +18,11 @@ from codeverse.contracts.run import RoundRecordfrom codeverse.conventions import MAX_TRIS_OBJECT, to_snakefrom codeverse.orchestrator import (DETAIL_KIND,+ KIND_FOR_STRATEGY,REWRITE_KIND,RoundPolicy,StopPolicy,detail_blocked,- kind_for_strategy,)from codeverse.tracks.depth import (PartScope,@@ -70,24 +61,17 @@ def test_depth_budget_scales_with_the_plan_and_is_bounded(chair_plan):assert big.target_tris > small.target_tris # a bigger machine is allowed moreassert small.target_tris >= 6_000 and big.max_tris <= MAX_TRIS_OBJECTassert small.min_tris < small.target_tris < small.max_tris- # the build-time guard is honest: never longer than the subprocess timeout it is measured againstassert 20 <= big.max_build_s <= 300 - 30---def test_depth_budget_counts_leaves_not_bare_parts():- """``instances`` and ``children`` both multiply the shapes a plan really stands for."""one = PartPlan(name="Leg", role="leg", description="rod", bbox=BBox(center=(0, 0.2, 0), extents=(0.04, 0.4, 0.04)),instances=4)plan = StaticPlan(object_name="X", summary="s", overall_bbox=BBox(center=(0, 0.2, 0), extents=(0.5, 0.4, 0.5)),parts=[one], acceptance=[])assert depth_budget(plan).n_units == 4--def test_detail_budget_prompt_states_the_numbers(chair_plan):text = depth_budget(chair_plan).as_prompt()assert "DETAIL BUDGET" in text and "plan parts" in textassert f"{depth_budget(chair_plan).target_tris:,}" in text- assert "not on new parts" in text # the measured rule: density inside parts, not extra parts+ assert "not on new parts" in text# ----------------------------------------------------------------------------- scoping@@ -101,9 +85,6 @@ def test_scope_groups_partitions_along_the_attachment_tree(chair_plan):# Backrest and Armrest both hang off BackLeg → the subtree stays togetherby_part = {n: i for i, s in enumerate(scopes) for n in s.names}assert by_part["Backrest"] == by_part["BackLeg"] == by_part["Armrest"]---def test_scope_groups_declines_when_scoping_cannot_help(chair_plan):assert scope_groups(chair_plan, files_for=_files_for, min_parts=99) == [] # small planassert scope_groups(chair_plan, files_for=None, min_parts=3) == [] # no per-part filesassert scope_groups(chair_plan, files_for=_files_for, max_groups=1, min_parts=3) == []@@ -133,10 +114,7 @@ def test_scoped_generation_can_be_switched_off(monkeypatch):# ----------------------------------------------------------------------------- the detail rounddef test_kind_for_strategy_is_the_one_mapping():- assert kind_for_strategy("same") == "refine"- assert kind_for_strategy("switch") == REWRITE_KIND- assert kind_for_strategy("detail") == DETAIL_KIND- assert kind_for_strategy("nonsense") == "refine"+ assert KIND_FOR_STRATEGY == {"same": "refine", "switch": REWRITE_KIND, "detail": DETAIL_KIND}def test_detail_round_is_offered_only_on_a_clean_finished_structure():@@ -186,37 +164,34 @@ def _measurement(parts, *, extents=(1.0, 1.0, 1.0), tris=1000) -> Measurement:parts=[PartMeasure(name=n, bbox_min=lo, bbox_max=hi, tri_count=10, islands=1) for n, lo, hi in parts])-def test_drift_gate_passes_when_only_triangles_changed():+def test_drift_gate_allows_detail_only_changes():before = _measurement([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))], tris=1000)after = _measurement([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))], tris=4200)g = drift_gate(before, after, tol_m=0.005)assert g.passed and g.gate == DRIFT_GATEassert "+3,200 triangles" in g.findings[0].message-[email protected]("after_parts,extents,needle", [- ([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))], (1.2, 1.0, 1.0), "overall x extent"),- # the fix hint names the axis in the AUTHOR's frame: GLB y (up) is z for a blender author- ([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))], (1.0, 1.2, 1.0), "overall z extent"),- ([("Seat", (0.02, 0, 0), (0.42, 0.04, 0.4))], (1.0, 1.0, 1.0), "moved 20.0 mm"),- ([], (1.0, 1.0, 1.0), "disappeared"),-])-def test_drift_gate_fails_when_the_detail_round_moved_something(after_parts, extents, needle):- before = _measurement([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))])- g = drift_gate(before, _measurement(after_parts, extents=extents), tol_m=0.005, language="blender")- assert not g.passed and any(needle in f.message for f in g.findings)- assert all(f.data.get("kind") == "detail_drift" for f in g.findings)---def test_drift_gate_warns_but_does_not_fail_on_a_new_part():- before = _measurement([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))])- after = _measurement([("Seat", (0, 0, 0), (0.4, 0.04, 0.4)), ("Bolt", (0, 0, 0), (0.01, 0.01, 0.01))])+ after = _measurement([+ ("Seat", (0, 0, 0), (0.4, 0.04, 0.4)),+ ("Bolt", (0, 0, 0), (0.01, 0.01, 0.01)),+ ])g = drift_gate(before, after, tol_m=0.005)assert g.passed and any(f.severity is Severity.WARN and "new top-level part" in f.message for f in g.findings)+ assert drift_gate(None, _measurement([]), tol_m=0.005).passed-def test_drift_gate_is_silent_without_a_baseline():- assert drift_gate(None, _measurement([]), tol_m=0.005).passed+def test_drift_gate_fails_when_the_detail_round_moved_something():+ before = _measurement([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))])+ cases = [+ ([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))], (1.2, 1.0, 1.0), "overall x extent"),+ ([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))], (1.0, 1.2, 1.0), "overall z extent"),+ ([("Seat", (0.02, 0, 0), (0.42, 0.04, 0.4))], (1.0, 1.0, 1.0), "moved 20.0 mm"),+ ([], (1.0, 1.0, 1.0), "disappeared"),+ ]+ for after_parts, extents, needle in cases:+ g = drift_gate(before, _measurement(after_parts, extents=extents), tol_m=0.005, language="blender")+ assert not g.passed and any(needle in f.message for f in g.findings)+ assert all(f.data.get("kind") == "detail_drift" for f in g.findings)# ----------------------------------------------------------------------------- the track wiringdiff --git a/harness/tests/orchestrator_tracks/test_graphics_recipes.py b/harness/tests/orchestrator_tracks/test_graphics_recipes.pyindex 46da634e..d057cbe9 100644--- a/harness/tests/orchestrator_tracks/test_graphics_recipes.py+++ b/harness/tests/orchestrator_tracks/test_graphics_recipes.py@@ -1,14 +1,4 @@-"""``tracks/graphics_recipes.py``: the brief's verified cookbook recipes land in the HARNESS-OWNED ``src/recipes.glsl``.--Measured 2026-08-26 (refs_v2_graphics, aurora brief, gemini-3.7-flash, shader_v2): the baseline prompt-carried ``curtain()`` five times and ``src/shader.frag`` called it zero times in both finished runs —-showing flash a recipe is not flash using it. Measured again the same day (bench/out/seed_v1, seeding-ON into ``src/common.glsl``): ``recipes.seeded`` fired and the finished run's common.glsl had NO seeded-block and no ``curtain(`` — the agent overwrote the file with its own helpers. Seeding into a file the-agent owns is not sticky; these tests pin the harness-owned file, its self-contained helpers, the-skeleton trim, the resume behaviour, the compose order + line map, the redefinition lint and the-prompt block that names what was seeded.-"""+"""Harness-owned GLSL recipe extraction, seeding, composition, and linting."""from __future__ import annotations@@ -178,8 +168,6 @@ def test_aurora_brief_seeds_recipes_and_helpers_exactly_once(tmp_path) -> None:def test_recipes_are_self_contained_and_the_skeleton_common_is_trimmed(tmp_path) -> None:- """recipes.glsl is pasted ABOVE common.glsl, so it must carry its own hash/noise/fbm — and the- skeleton's copies (the only common.glsl the harness ever edits: the agent has not seen it yet) go."""ws = _ws(tmp_path)assert is_skeleton_common((ws.src / "common.glsl").read_text())names = seed_recipes(_ctx(ws))@@ -203,8 +191,6 @@ def test_recipes_are_self_contained_and_the_skeleton_common_is_trimmed(tmp_path)def test_an_agent_written_common_is_never_touched(tmp_path) -> None:- """Once the agent owns common.glsl (measured: it rewrites the whole file), the seed leaves it- alone — a duplicate is the agent's to remove, and the lint names it."""ws = _ws(tmp_path)mine = "// my helpers\nfloat hash12(vec2 p) { return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }\nfloat mine(float x) { return x * 2.0; }\n"(ws.src / "common.glsl").write_text(mine)@@ -218,22 +204,20 @@ def test_an_agent_written_common_is_never_touched(tmp_path) -> None:assert "`hash12` is already provided by src/recipes.glsl — call it instead of redefining it" in dup[0].message-def test_rain_brief_seeds_drops_and_bokeh(tmp_path) -> None:+def test_brief_and_plan_visuals_select_recipes(tmp_path) -> None:ws = _ws(tmp_path)names = seed_recipes(_ctx(ws, RAIN))assert "dropsLayer" in names and "bokehSoft" in names and "curtain" not in names and "stars" not in namestext = _recipes(ws).read_text()assert "vec2 dropsLayer(vec2 uv, float t, float scale)" in text and "vec3 bokehSoft(vec2 p, float t)" in text--def test_plan_key_visuals_join_the_brief(tmp_path) -> None:- ws = _ws(tmp_path)+ ws = _ws(tmp_path / "plan")plan = GraphicsPlan.model_validate({**plan_example(), "key_visuals": ["an aurora curtain over the ridge"]})names = seed_recipes(_ctx(ws, "a landscape", plan=plan))assert "curtain" in names and "bokehSoft" not in names# the seed follows the prompt's selection exactly, budget included: for "a city at night" the Light +# Gradient-sky chapters fill the 9 k budget and Bokeh does not fit, so bokehSoft is NOT seeded either- ws2 = _ws(tmp_path / "b")+ ws2 = _ws(tmp_path / "city")names2 = seed_recipes(_ctx(ws2, "a city at night", plan=plan))assert "curtain" in names2 and "bokehSoft" not in names2@@ -411,6 +395,3 @@ def test_prompt_block_lists_the_seeded_names(tmp_path) -> None:judge_summary="Previous score 0.3", frame_notes="(no frame metrics)", current_files={}))assert "harness-owned, read-only `src/recipes.glsl`" in ref and "do not copy them into common.glsl" in refassert all(f"`{n}`" in ref for n in names)- # the sibling prompt-context test builds ctx without .extra: the key still resolves to []- bare = SimpleNamespace(**{k: v for k, v in vars(ctx).items() if k != "extra"})- assert graphics_prompt_context(bare, skeleton_files={}, previous_error="")["seeded_recipes"] == []diff --git a/harness/tests/orchestrator_tracks/test_orchestrator.py b/harness/tests/orchestrator_tracks/test_orchestrator.pyindex c28971d7..c5333623 100644--- a/harness/tests/orchestrator_tracks/test_orchestrator.py+++ b/harness/tests/orchestrator_tracks/test_orchestrator.py@@ -27,11 +27,20 @@ from codeverse.orchestrator import (RunState,StageRunner,StopPolicy,+ best_index,build_refine_instructions,hash_inputs,plan_parallel_groups,)-from codeverse.proc import EventLog, fan_out, split_results+from codeverse.proc import EventLog, fan_out+++def test_best_index_prefers_score_then_task_count_then_recency():+ assert best_index([(0.5, 0), (0.7, 2), (0.7, 1), (0.6, 0)]) == 2+ assert best_index([(0.7, 1), (0.7, 1)]) == 1+ assert best_index([(0.9, 3), (0.8, 0)]) == 0+ with pytest.raises(ValueError):+ best_index([])# ----------------------------------------------------------------------------- budget@@ -63,17 +72,14 @@ def test_fan_out_preserves_order_and_captures_exceptions():res = fan_out([0, 1, 2, 3], fn, max_workers=4, label="t")assert res[0] == 0 and res[1] == 10 and res[3] == 30 and isinstance(res[2], ValueError)- ok, bad = split_results(res)- assert ok == [0, 10, 30] and len(bad) == 1assert fan_out([], fn, 2) == []# ----------------------------------------------------------------------------- state + runnerdef test_run_state_roundtrip(tmp_ws):st = RunState()- st.mark_round_done(0, "abc", tmp_ws)+ st.mark_round_done(0, "abc")st.update_best(0, "abc", 0.5)- st.extra["spent_usage"] = Usage(cost_usd=0.1).model_dump()st.save(tmp_ws)again = RunState.load(tmp_ws)assert again is not None and again.best_round == 0 and again.current_round == 1 and again.round_commits[0] == "abc"@@ -164,19 +170,19 @@ def _round(i: int, score: float | None, errors: int = 0, build_ok: bool = True)def test_stop_policy_decisions():sp = StopPolicy(RoundPolicy(max_rounds=3, plateau_window=2, min_delta=0.02, target=0.8))- assert sp.decide([]) == "continue"- assert sp.decide([_round(0, 0.5)]) == "continue"- assert sp.decide([_round(0, 0.5)], budget_ok=False) == "budget"- assert sp.decide([_round(0, 0.5), _round(1, 0.85)]) == "pass"+ assert sp.evaluate([]).reason == "continue"+ assert sp.evaluate([_round(0, 0.5)]).reason == "continue"+ assert sp.evaluate([_round(0, 0.5)], budget_ok=False).reason == "budget"+ assert sp.evaluate([_round(0, 0.5), _round(1, 0.85)]).reason == "pass"# three flat rounds: from r03 on the marginal-value stop answers first (both stop;# "diminishing_returns" is the more precise reason — see test_round_economics.py)- assert sp.decide([_round(0, 0.5), _round(1, 0.51), _round(2, 0.515)]) == "diminishing_returns"+ assert sp.evaluate([_round(0, 0.5), _round(1, 0.51), _round(2, 0.515)]).reason == "diminishing_returns"flat = StopPolicy(RoundPolicy(max_rounds=3, plateau_window=2, min_delta=0.02, target=0.8, marginal_from_round=99))- assert flat.decide([_round(0, 0.5), _round(1, 0.51), _round(2, 0.515)]) == "plateau"- assert sp.decide([_round(0, 0.5), _round(1, 0.6), _round(2, 0.7)]) == "continue"- assert sp.decide([_round(0, 0.5), _round(1, 0.6), _round(2, 0.7), _round(3, 0.75)]) == "max_rounds"+ assert flat.evaluate([_round(0, 0.5), _round(1, 0.51), _round(2, 0.515)]).reason == "plateau"+ assert sp.evaluate([_round(0, 0.5), _round(1, 0.6), _round(2, 0.7)]).reason == "continue"+ assert sp.evaluate([_round(0, 0.5), _round(1, 0.6), _round(2, 0.7), _round(3, 0.75)]).reason == "max_rounds"# unscored rounds (build failed) do not count as plateau evidence- assert sp.decide([_round(0, 0.5), _round(1, None, build_ok=False), _round(2, None, build_ok=False)]) == "continue"+ assert sp.evaluate([_round(0, 0.5), _round(1, None, build_ok=False), _round(2, None, build_ok=False)]).reason == "continue"def test_best_selector_prefers_score_then_fewer_errors():diff --git a/harness/tests/orchestrator_tracks/test_plan_features.py b/harness/tests/orchestrator_tracks/test_plan_features.pyindex 1d9df910..e061b5e5 100644--- a/harness/tests/orchestrator_tracks/test_plan_features.py+++ b/harness/tests/orchestrator_tracks/test_plan_features.py@@ -100,7 +100,8 @@ def test_a_generation_side_switch_may_share_one_plan():from codeverse.tracks.plan_features import pin_plan_blockersassert pin_plan_blockers({"CV3D_PLAN_FEATURES": "contacts"}) == []- assert pin_plan_blockers({"CV3D_SKILLS": "1", "CV3D_SKILLS_MAX": "3"}) == []+ for name in sorted(F.GENERATION_SIDE_ENV):+ assert pin_plan_blockers({name: "1"}) == [], nameassert pin_plan_blockers({}) == []@@ -131,7 +132,6 @@ def test_an_unclassified_switch_defaults_to_refusing():def test_every_known_feature_is_classified():"""A new feature must be put on one side or the other in the same commit; otherwiseit silently inherits 'plan-side' and nobody notices the A/B got noisier."""- from codeverse.tracks.plan_features import GENERATION_SIDE, KNOWN_FEATURES, PLAN_SIDE+ from codeverse.tracks.plan_features import GENERATION_SIDE, KNOWN_FEATURES- assert set(KNOWN_FEATURES) == PLAN_SIDE | GENERATION_SIDE- assert not (PLAN_SIDE & GENERATION_SIDE)+ assert set(KNOWN_FEATURES) > GENERATION_SIDEdiff --git a/harness/tests/orchestrator_tracks/test_prompts_assets.py b/harness/tests/orchestrator_tracks/test_prompts_assets.pyindex 37ca44f4..51a8a8ec 100644--- a/harness/tests/orchestrator_tracks/test_prompts_assets.py+++ b/harness/tests/orchestrator_tracks/test_prompts_assets.py@@ -3,6 +3,7 @@from __future__ import annotationsimport re+from types import SimpleNamespaceimport pytest@@ -10,11 +11,11 @@ from codeverse.contracts.common import Language, Trackfrom codeverse.contracts.plan import ArticulatedPlan, ScenePlanfrom codeverse.orchestrator import BudgetGuard, RoundPolicy, RunStatefrom codeverse.proc import EventLog-from codeverse.prompts import list_prompts, render+from codeverse.prompts import PROMPTS_DIR, renderfrom codeverse.tracks.common import RunContextfrom codeverse.tracks.generation import SINGLE_SHOT_FORMATfrom codeverse.tracks.planner import plan_example-from codeverse.tracks.prompting import base_prompt_context+from codeverse.tracks.prompting import base_prompt_context, judged_sheetfrom codeverse.tracks.scene_assets import asset_api_summary, asset_plan, run_asset_stagefrom tests.orchestrator_tracks.conftest import make_specfrom tests.orchestrator_tracks.fakes import FakeAgent, FakeJudge, FakeRuntime, FakeServices@@ -50,8 +51,18 @@ def _ctx(tmp_ws, settings, spec, plan, *, agent_id="single-shot:gemini:x", servicookbook_rel=f"{lang.value}/cookbook.md", tool_cards="- `build`: builds")+def test_judged_sheet_returns_one_labelled_existing_image(tmp_path):+ png = tmp_path / "sheet.png"+ png.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 32)+ images = judged_sheet(SimpleNamespace(index=2, renders=SimpleNamespace(contact_sheet=str(png))))+ assert len(images) == 1 and images[0].path == str(png)+ assert "round 2" in images[0].label and "judge" in images[0].label+ for renders in (None, SimpleNamespace(contact_sheet=""), SimpleNamespace(contact_sheet=str(tmp_path / "gone.png"))):+ assert judged_sheet(SimpleNamespace(index=0, renders=renders)) == []++def test_all_track_templates_exist_and_render(tmp_ws, settings, chair_plan):- names = {p.split("/")[-1][:-3] for p in list_prompts() if p.startswith("tracks/") and p.endswith(".j2")}+ names = {p.stem for p in (PROMPTS_DIR / "tracks").rglob("*.j2")}assert names >= TEMPLATESspec = make_spec()ctx = _ctx(tmp_ws, settings, spec, chair_plan)diff --git a/harness/tests/orchestrator_tracks/test_refactor_batch2.py b/harness/tests/orchestrator_tracks/test_refactor_batch2.pyindex c6106cda..c79b037b 100644--- a/harness/tests/orchestrator_tracks/test_refactor_batch2.py+++ b/harness/tests/orchestrator_tracks/test_refactor_batch2.py@@ -1,4 +1,4 @@-"""Quality-wave batch 2: refine scaffold, planner hooks, RunOptions wiring, judge-view flags."""+"""Refine grouping, RunOptions wiring, and judge-view flags."""from __future__ import annotations@@ -51,30 +51,36 @@ def test_plan_refine_groups_fans_out_only_when_allowed_and_disjoint():# --------------------------------------------------------------------- RunOptions wiring (F29)-def test_spec_options_candidates_flow_into_the_policy(tmp_path, chair_plan, settings):+def test_candidate_width_precedence(tmp_path, settings):spec = make_spec(options=RunOptions(candidates=2))- ws = Workspace(tmp_path / "runs" / "r").create()track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.THREEJS))+ ws = Workspace(tmp_path / "spec").create()ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState())- assert ctx.policy.n_candidates == 2 and ctx.state.extra["n_candidates"] == 2+ assert ctx.policy.n_candidates == 2--def test_constructor_candidates_beat_spec_options(tmp_path, settings):- spec = make_spec(options=RunOptions(candidates=2))- ws = Workspace(tmp_path / "runs" / "r").create()- track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.THREEJS), n_candidates=3)+ ws = Workspace(tmp_path / "constructor").create()+ track = StaticObjectTrack(services=FakeServices(), settings=settings,+ runtime=FakeRuntime(Language.THREEJS), n_candidates=3)ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState())assert ctx.policy.n_candidates == 3-def test_legacy_run_state_width_survives_resume(tmp_path, settings):- spec = make_spec() # no options.candidates- ws = Workspace(tmp_path / "runs" / "r").create()- state = RunState()- state.extra["n_candidates"] = 4 # persisted by an older run- track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.THREEJS))- ctx = track.build_context(spec, ws, EventLog(ws.events_path), state)- assert ctx.policy.n_candidates == 4++def test_injected_policy_keeps_the_track_detail_round(tmp_path, settings):+ """economy/quality inject RoundPolicy(judge_samples=n) and used to lose the static+ track's detail round (a policy object stood in for 'detail_rounds was chosen')."""+ from codeverse.orchestrator import RoundPolicy+ from codeverse.tracks.lifecycle import DEFAULT_DETAIL_ROUNDS++ ws = Workspace(tmp_path / "eco").create()+ track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.THREEJS),+ policy=RoundPolicy(judge_samples=2))+ ctx = track.build_context(make_spec(), ws, EventLog(ws.events_path), RunState())+ assert ctx.policy.judge_samples == 2 and ctx.policy.detail_rounds == DEFAULT_DETAIL_ROUNDS == 1+ # a chosen 0 still means off+ track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.THREEJS),+ policy=RoundPolicy(judge_samples=2, detail_rounds=0))+ assert track.build_context(make_spec(), ws, EventLog(ws.events_path), RunState()).policy.detail_rounds == 0def test_options_texture_triggers_texture_pass(tmp_path, chair_plan, settings, monkeypatch):@@ -108,9 +114,11 @@ def _rs(flags: list[bool | None]) -> RenderSet:return RenderSet(views=views, renderer="fake")-def test_scene_judge_views_prefers_stamped_flags():+def test_judge_view_flags_and_path_reconstruction(tmp_path):from types import SimpleNamespace+ from codeverse.judges.base import judged_subset, resolve_paths+pipe = ScenePipeline()ctx = SimpleNamespace(services=FakeServices())rs = _rs([True, False, True])@@ -121,10 +129,6 @@ def test_scene_judge_views_prefers_stamped_flags():out2 = pipe.judge_views(ctx, legacy)assert len(out2.views) == 2--def test_cli_judge_reconstructs_the_judged_subset(tmp_path):- from codeverse.judges.base import judged_subset, resolve_paths-rs = _rs([True, False, None])sub = judged_subset(rs)assert [v.name for v in sub.views] == ["v0"]@@ -166,4 +170,3 @@ def test_graphics_planner_hooks_charge_budget_on_planning_error(tmp_ws):**GraphicsTrack()._plan_kwargs(spec))assert budget.spent.cost_usd > 0, "a failed re-ask is still paid for"-diff --git a/harness/tests/orchestrator_tracks/test_resume_reconcile.py b/harness/tests/orchestrator_tracks/test_resume_reconcile.pyindex 70bd8a73..db473e3b 100644--- a/harness/tests/orchestrator_tracks/test_resume_reconcile.py+++ b/harness/tests/orchestrator_tracks/test_resume_reconcile.py@@ -235,7 +235,7 @@ def test_resume_charges_for_spend_the_snapshot_missed(tmp_path, chair_plan, settled = open_run_ledger(ws.root)for cost in (0.30, 0.12): # what the provider actually billedled.append(CallCost(run=ws.root.name, model="gemini:flash", label="planner", cost_usd=cost))- guard = BudgetGuard(make_spec().budget, run=ws.root.name)+ guard = BudgetGuard(make_spec().budget)guard.restore(BudgetSnapshot(spent=guard.spent, billed_usd=0.10, # the boundary save missed 0.32calls=1, by_stage={}, by_round={}, active_s=0.0))_reconcile_billed_from_ledger(guard, ws, EventLog(ws.events_path))@@ -259,7 +259,7 @@ def test_resume_reconcile_keeps_subscription_spend_notional(tmp_path, settings):led = open_run_ledger(ws.root)led.append(CallCost(run=ws.root.name, backend="codex", model="gpt-5.6-sol", label="generator", cost_usd=7.7))led.append(CallCost(run=ws.root.name, backend="claude-code", model="sonnet", cost_usd=1.1))- guard = BudgetGuard(make_spec().budget, run=ws.root.name)+ guard = BudgetGuard(make_spec().budget)_reconcile_billed_from_ledger(guard, ws, EventLog(ws.events_path))assert guard.billed_usd == 0.0, "subscription cost is notional; resume must keep billed at $0"led.append(CallCost(run=ws.root.name, backend="gemini", model="gemini-3.7-flash", cost_usd=0.25))diff --git a/harness/tests/orchestrator_tracks/test_round_economics.py b/harness/tests/orchestrator_tracks/test_round_economics.pyindex b8e9c4d9..bb62674c 100644--- a/harness/tests/orchestrator_tracks/test_round_economics.py+++ b/harness/tests/orchestrator_tracks/test_round_economics.py@@ -1,16 +1,4 @@-"""The round-level cost controls — the ones that survived measurement, and the-proof for the ones that did not.--* a round that scores below the best by more than the judge's noise does not- buy another round of the same shape (``regression`` / strategy switch);-* r03+ only starts when the previous round gained more than 1.5 σ- (``diminishing_returns``);-* agent sessions are **uncapped by default** — a 28-turn cap was A/B-tested and- rejected ($1.381 / 0.479 capped vs $1.360 / 0.684 uncapped, n=3 per arm,- docs/COST.md §17) — but an explicitly requested cap still lands gracefully;-* the judge is skipped only where the verdict is provably never bought at all,- and every round emits one ``cost.round`` event with what it burned.-"""+"""Round stop economics, session limits, judge skipping, and cost attribution."""from __future__ import annotations@@ -68,8 +56,6 @@ def test_judge_sigma_comes_from_the_one_measured_table():pol = RoundPolicy(judge_model="gemini:gemini-3.7-flash")assert pol.sigma == pytest.approx(0.083)assert pol.regression_delta == pytest.approx(0.083) and pol.marginal_delta == pytest.approx(0.1245)- assert RoundPolicy().with_judge("gemini:gemini-3.7-flash").sigma == pytest.approx(0.083)- assert RoundPolicy().with_judge("") is not Nonedef test_best_score_and_last_gain():@@ -94,10 +80,6 @@ def test_a_regression_buys_a_change_of_shape_then_stops():def test_a_sub_noise_dip_never_burns_the_strategy_switch():- """Audit (g): the regression COUNTER used to count ANY drop while the gate used- policy.regression_delta — a -0.02 blip (inside pro sigma 0.030) plus one real- regression made the counter 2 and stopped the run as "regression" without ever- offering the single strategy switch. One predicate now serves both."""from codeverse.orchestrator import meaningful_regressionsp = StopPolicy(RoundPolicy(max_rounds=4, target=0.9, judge_model="gemini:gemini-3.1-pro-preview",@@ -145,18 +127,12 @@ def test_r03_only_runs_when_the_last_round_paid_for_itself():def test_the_marginal_round_is_configurable():- """The audit's recommendation #1 (stop after r01) is this knob, not a new rule."""sp = StopPolicy(RoundPolicy(max_rounds=4, target=0.9, marginal_from_round=2,judge_model="gemini:gemini-3.1-pro-preview"))assert sp.evaluate([_round(0, 0.40), _round(1, 0.42)]).reason == "diminishing_returns"def test_the_stop_order_is_exhausted_regression_then_marginal_then_switch_then_plateau():- """One case per branch, each one where the NEXT branch would answer differently —- the order in ``StopPolicy.evaluate`` is the economics, so it is pinned here.-- (Replayed over the 107 recorded rounds this shipped default cuts 2 runs /- $1.14 with 0 best rounds lost — waste-and-accounting/replay_stops.py.)"""pro = dict(max_rounds=4, target=0.9, judge_model="gemini:gemini-3.1-pro-preview")sp = StopPolicy(RoundPolicy(**pro))# 1. the switch is already spent (a rewrite regressed again) — outranks everything,@@ -204,9 +180,6 @@ class _TurnAgent:def test_agent_sessions_are_uncapped_by_default(tmp_ws, monkeypatch):- """Measured (docs/COST.md §17): cap 28 cost $1.381 at score 0.479, uncapped- $1.360 at 0.684 — n=3 per arm, same prompt/generator/judge/budget. The cap- saved nothing and lost 0.205 of a score point, so nothing sets one by default."""monkeypatch.delenv("CV3D_AGENT_MAX_TURNS", raising=False)assert DEFAULT_AGENT_MAX_TURNS == 0 and RoundPolicy().agent_max_turns == 0agent = _TurnAgent(writes_on=1)@@ -228,7 +201,6 @@ def test_agent_sessions_are_uncapped_by_default(tmp_ws, monkeypatch):def test_the_policy_cap_is_plumbed_through_the_round(tmp_path, spec, settings):- """A caller that DOES set one (a cost profile, a bench arm) still reaches the job."""from codeverse.tracks.steps import run_generation_tasksagent = _TurnAgent(writes_on=1)@@ -251,7 +223,7 @@ def test_hitting_the_cap_asks_for_a_landing_instead_of_killing_the_session(tmp_wassert res.ok and res.turn_capped and res.sessions == 2# both sessions are paid for and both are in the guard, under their own labelsassert res.usage.cost_usd == pytest.approx(0.4) and guard.spent.cost_usd == pytest.approx(0.4)- assert guard.round_costs(1)["refine"] == pytest.approx(0.4)+ assert guard.by_round.get(1, {})["refine"] == pytest.approx(0.4)kinds = [e["event"] for e in events.read()]assert "generate.turn_cap" in kindsdone = next(e for e in events.read() if e["event"] == "generate.done")@@ -272,7 +244,7 @@ def test_a_crashing_second_session_never_erases_what_the_first_one_spent(tmp_ws)budget=guard)assert len(agent.jobs) == 2 and not res.okassert guard.spent.cost_usd == pytest.approx(0.2) and res.usage.cost_usd == pytest.approx(0.2)- assert "503 storm" in res.notes and guard.round_costs(2)["refine"] == pytest.approx(0.2)+ assert "503 storm" in res.notes and guard.by_round.get(2, {})["refine"] == pytest.approx(0.2)def _result_of(agent, i):@@ -313,11 +285,6 @@ def _gates(errors: int = 0):def test_skip_judge_reasons_are_only_states_where_the_verdict_is_never_bought(tmp_path, spec, settings):- """Every branch left in ``skip_judge_reason`` must save a REAL verdict.-- The two wave-2 branches that did not are gone: "no file change" was- unreachable and "build not repaired within the repair budget" was bought back- by ``rejudge_round`` on the next loop iteration (both reproduced below)."""from codeverse.tracks.steps import skip_judge_reasonctx = _ctx(tmp_path, spec, settings)@@ -341,8 +308,6 @@ def test_skip_judge_reasons_are_only_states_where_the_verdict_is_never_bought(tmdef test_a_round_that_changed_no_file_never_reaches_the_judge_question(tmp_path, spec, settings):- """Proof the deleted "no file change" branch was unreachable: a task that writes- nothing is not ``ok``, and ``run_generation_tasks`` raises before any verdict."""from codeverse.tracks.steps import RoundFailed, run_generation_tasksclass _Idle:@@ -357,8 +322,6 @@ def test_a_round_that_changed_no_file_never_reaches_the_judge_question(tmp_path,def test_a_skipped_verdict_is_not_bought_back_by_the_rejudge_path(tmp_path, spec, settings):- """``rejudge_round`` exists for a judge that FAILED, not for one we chose not to- call: without this the "gate errors" skip is a ``judge.retry``, not a saving."""from codeverse.tracks.steps import rejudge_roundctx = _ctx(tmp_path, spec, settings, policy=RoundPolicy(judge_on_gate_errors=False), name="norebuy")@@ -373,8 +336,6 @@ def test_a_skipped_verdict_is_not_bought_back_by_the_rejudge_path(tmp_path, specdef test_a_round_that_broke_the_gates_does_not_displace_a_clean_one():- """The unscored fallback: never promote a round that does not build, and never- let a gate-breaking round displace the previous artifact just by being last."""from codeverse.orchestrator import BestSelectordef r(i, *, build_ok=True, errors=0):@@ -450,22 +411,17 @@ def test_the_loop_switches_shape_after_a_regression_and_emits_cost_rounds(tmp_paassert costs[1]["wasted"] is True and costs[1]["waste_reason"] == "regression"assert costs[2]["judge_usd"] > 0 and costs[2]["run_usd"] >= costs[1]["run_usd"]assert rec.extra["cost_by_stage"]["judge"] > 0 and rec.extra["cost_by_stage"]["refine"] > 0- # ... and the run ships its own priced ledger+ # ... and the run opens its own priced ledger (telemetry/cost.jsonl + the root alias) even+ # outside the CLI; the ONE writer is the metered agent/model, so the injected fakes+ # (a bare FakeAgent, a FakeJudge with no chat model) leave it empty — see+ # test_cost_accounting for the rows a metered session writesfrom codeverse.cost.ledger import load_ledger- rows = load_ledger(ws.root / "cost_ledger.jsonl")- assert {str(r.stage) for r in rows} >= {"baseline", "refine", "judge"}- assert sum(r.cost_usd for r in rows) == pytest.approx(rec.total_usage.cost_usd, abs=1e-6)+ assert (ws.root / "cost_ledger.jsonl").is_symlink() # -> telemetry/cost.jsonl, created on first row+ assert load_ledger(ws.root) == []def test_a_lint_stuck_run_keeps_every_score_instead_of_deferring_the_verdict(tmp_path, chair_plan, settings):- """The verifier's reproduction of the removed "build not repaired" skip.-- Every round here builds but leaves a lint error the repair budget cannot clear.- Wave 2 skipped the judge on all three rounds and then bought two of the verdicts- back one loop iteration later (``judge.retry``) — no money saved — while the LAST- round, the best one (0.7), was left without a score and could not be promoted.- Now each round is judged once, in the round, and r02 wins."""def _writer_lint(job, ws):return {"src/object.js": f"// {job.label} r{job.round}\nLINT_ERROR\nexport function build(THREE) {{}}\n"}@@ -491,8 +447,6 @@ def test_a_round_that_raises_still_reports_what_it_burned(tmp_path, chair_plan,ws = Workspace(tmp_path / "runs" / "cut")class _Expensive(FakeAgent):- """A session that burns the run's clock — the round after it has none left."""-def run(self, job):res = super().run(job)return res.model_copy(update={"usage": Usage(backend="fake", cost_usd=0.04, input_tokens=1000)})@@ -514,9 +468,6 @@ def test_a_round_that_raises_still_reports_what_it_burned(tmp_path, chair_plan,def test_fan_out_workers_inherit_the_callers_context():- """Ledger attribution rides on contextvars: a parallel judge sample, a- best-of-N candidate or a bench cell must not fall back to the process- default just because it ran on a pool thread."""import contextvarsfrom codeverse.proc import fan_out@@ -530,14 +481,10 @@ def test_fan_out_workers_inherit_the_callers_context():def test_a_run_past_its_hard_ceiling_cannot_start_another_session(tmp_ws):- """Measured 2026-08-28 (lamp_bl, --max-minutes 30, killed by hand at 57 min with- round 0 unfinished): a timed-out session bills nothing, so the accounting-driven- check() never fired and silent-bail retries treadmilled on 120 s mercy floors- forever. run_agent_task now checks the HARD ceiling before starting any session."""from codeverse.contracts.spec import Budgetfrom codeverse.orchestrator import BudgetExceeded, BudgetGuard- g = BudgetGuard(Budget(max_minutes=30.0, max_rounds=4), run="t")+ g = BudgetGuard(Budget(max_minutes=30.0, max_rounds=4))g.start_time -= 36 * 60 # ceiling long crossed, nothing billed along the wayagent = _TurnAgent(writes_on=1)with pytest.raises(BudgetExceeded):diff --git a/harness/tests/orchestrator_tracks/test_write_scope.py b/harness/tests/orchestrator_tracks/test_write_scope.pyindex e3c1e1ec..d79b9123 100644--- a/harness/tests/orchestrator_tracks/test_write_scope.py+++ b/harness/tests/orchestrator_tracks/test_write_scope.py@@ -114,6 +114,23 @@ def test_generate_files_without_edit_only_is_unchanged(tmp_path):assert (ws.src / "parts" / "b.js").read_text() == "// new b\n"+def test_generate_files_never_rewrites_a_harness_owned_file(tmp_path):+ """The single-shot mirror of tests/agents/test_cli_write_scope.py's recipes test: the+ CLI path restored src/recipes.glsl post-hoc, the envelope path wrote it (2026-08-29)."""+ ws = Workspace(tmp_path / "ws").create()+ ws.write_json(ws.spec_path, {"language": "glsl_shader", "track": "graphics"})+ (ws.src / "recipes.glsl").write_text("float aurora(vec2 p){return 0.0;}\n")+ events = EventLog(tmp_path / "e.jsonl")+ answer = ("=== FILE: src/shader.frag ===\nvoid main(){}\n=== END FILE ===\n"+ "=== FILE: src/recipes.glsl ===\n// clobbered\n=== END FILE ===")+ res = generate_files(ws, model=ScriptedModel([(answer, "STOP")]),+ task=GenerationTask(label="baseline", prompt="p"), events=events)+ assert res.ok and [c.path for c in res.files_changed] == ["src/shader.frag"]+ assert (ws.src / "recipes.glsl").read_text().startswith("float aurora")+ (skip,) = [e for e in events.read() if e["event"] == "generate.skipped_path"]+ assert skip["path"] == "src/recipes.glsl" and "harness-owned" in skip["reason"]++# --------------------------------------------------------------------------- entry ownershipdef test_always_writable_requires_ownership():part = GenerationTask(label="p", prompt="p", files_hint=["src/parts/seat.js"])