Official Codebase of 3DCodeVerse
Python
tests: orchestrator_tracks — 100 tests go that cover no line another test does not (−1 924 lines)
gaoypengce51e0c0a59b
diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.pyindex e247b3ba..b323c267 100644--- a/harness/tests/orchestrator_tracks/fakes.py+++ b/harness/tests/orchestrator_tracks/fakes.py@@ -49,10 +49,9 @@ class FakeRuntime:"""Writes a tiny GLB (one box per part) on build; fails when a src file contains FAIL_MARK.Its file layout (``expected_files`` / ``files_for``) is the real runtime's for the language."""- def __init__(self, language: Language = Language.THREEJS, *, lint_error_mark: str = "LINT_ERROR"):+ def __init__(self, language: Language = Language.THREEJS):self.language = languageself.entry_globs = ("src/**/*.js",) if language in (Language.THREEJS, Language.SCENE_THREEJS) else ("src/model.py",)- self.lint_error_mark = lint_error_markself.builds = 0self.lock = threading.Lock()layout = get_runtime(language)@@ -104,7 +103,7 @@ class FakeRuntime:def lint(self, ws: Workspace) -> GateReport:text = self._src_text(ws)findings = []- if self.lint_error_mark in text:+ if "LINT_ERROR" in text:findings.append(GateFinding(gate=f"lint:{self.language.value}", severity=Severity.ERROR, target="src/model.py",message="forbidden construct", fix_hint="remove LINT_ERROR"))return GateReport(gate=f"lint:{self.language.value}", passed=not findings, findings=findings)@@ -242,11 +241,10 @@ class FakeJudge:name = "fake"prompt_hash = "fakejudge001" # D37: BaseTrack.after_plan records it as prompt_hashes["judge"]- def __init__(self, scores: Sequence[float] = (0.55, 0.7, 0.85), *, targets: Sequence[str] = ("Seat", "FrontLeg", "Backrest", "Armrest"),- acceptance_fail: Sequence[str] = (), cost: float = 0.003, minutes: float = 0.0):+ def __init__(self, scores: Sequence[float] = (0.55, 0.7, 0.85), *, targets: Sequence[str] = ("Seat", "FrontLeg", "Backrest", "Armrest"), cost: float = 0.003,+ minutes: float = 0.0):self.scores = list(scores)self.targets = list(targets)- self.acceptance_fail = list(acceptance_fail)self.cost = costself.minutes = minutesself.calls: list[Any] = []@@ -263,7 +261,7 @@ class FakeJudge:self.calls.append(inp)plan = [ImprovementItem(target=t, kind="geometry", instruction=f"make {t} match plan bbox", priority=k + 1, expected_gain=0.05)for k, t in enumerate(self.targets)]- acc = {a.id: (a.id not in self.acceptance_fail) for a in inp.acceptance}+ acc = {a.id: True for a in inp.acceptance}return Judgment(rubric="fake_v1", judge_backend="fake", scores={"geometry": s, "material": s}, overall=s, passed=s >= 0.8,summary=f"round {inp.round_index} score {s}", issues=[JudgeIssue(target=self.targets[0], kind="geometry", severity="major",detail="too thin", evidence="front")],@@ -311,9 +309,7 @@ class FakeServices(Services):self.records: list[RunRecord] = []self.reference_judges: list[tuple[str, int, str]] = []self.silhouette_calls: list[tuple[str, str]] = []- self.connectivity_languages: list[str] = []self.planned_edges: list[list[tuple[str, str]]] = []- self.geometry_renders: list[str] = []def chat_model(self, model_id: str) -> Any:raise ServiceUnavailable("no chat model in tests")@@ -362,7 +358,6 @@ class FakeServices(Services):parts=parts, ground_gap_m=float(bounds[0][1]), footprint_offset_m=float(np.hypot(cen[0], cen[2])))def connectivity(self, glb: Path, language: str = "", planned_edges: Sequence[tuple[str, str]] = ()) -> GateReport:- self.connectivity_languages.append(language)self.planned_edges.append(list(planned_edges))return GateReport(gate="connectivity", passed=True)@@ -382,7 +377,6 @@ class FakeServices(Services):return RenderSet(views=vs, contact_sheet=str(sheet), renderer="fake")def render_geometry(self, glb: Path, out_dir: Path, *, views) -> RenderSet:- self.geometry_renders.append(str(glb))vs = []for v in views:p = out_dir / f"clay_{v.name}.png"diff --git a/harness/tests/orchestrator_tracks/test_asset_alias_note.py b/harness/tests/orchestrator_tracks/test_asset_alias_note.pyindex 1fde9d84..c279c096 100644--- a/harness/tests/orchestrator_tracks/test_asset_alias_note.py+++ b/harness/tests/orchestrator_tracks/test_asset_alias_note.py@@ -1,29 +1,8 @@-"""The merge map the asset stage USED is what the zones are told (2026-09-07).--`run_asset_stage` folds near-identical props under a cap that depends on the soft budget at-the time (`MAX_ASSETS` or `DEGRADED_MAX_ASSETS`); the scene's pre-round hook (then `prepare`)-used to recompute the map from the plan with `MAX_ASSETS` alone, so a degraded run told the-zones merged assets were "NOT AVAILABLE" while working shims existed. The stage writes the-note it used, and the `asset_api` stage reads it back.-"""+"""A scene refine target routes to the file that really holds the asset."""from __future__ import annotations-from codeverse3d.tracks.scene_assets import read_dedupe_note, write_dedupe_note---def test_the_note_round_trips_and_an_empty_map_is_still_a_note(tmp_ws):- assert read_dedupe_note(tmp_ws) is None, "no stage has run"- write_dedupe_note(tmp_ws, {"SteppingStone": "PondRock"})- assert read_dedupe_note(tmp_ws) == {"SteppingStone": "PondRock"}- write_dedupe_note(tmp_ws, {})- assert read_dedupe_note(tmp_ws) == {}, "a stage that merged nothing says so (not None)"-def test_a_refine_target_routes_to_the_file_that_really_holds_the_asset():- """Every asset target used to map to ``src/assets/<snake>.js``. The skeleton writes- that file only for a three.js asset: a merged asset's is the variant shim onto its- survivor, and a blender hero ships as ``public/assets/<snake>.glb`` — so a refine- session could "succeed" editing a file nothing imports."""from types import SimpleNamespacefrom codeverse3d.contracts.common import Language, Trackdiff --git a/harness/tests/orchestrator_tracks/test_budget_snapshot.py b/harness/tests/orchestrator_tracks/test_budget_snapshot.pyindex 6b6d8f3d..30255f5d 100644--- a/harness/tests/orchestrator_tracks/test_budget_snapshot.py+++ b/harness/tests/orchestrator_tracks/test_budget_snapshot.py@@ -8,7 +8,7 @@ from pathlib import Pathimport pytest-from codeverse3d.contracts.common import Budget, Language, Usage+from codeverse3d.contracts.common import Budget, Languagefrom codeverse3d.contracts.plan import StaticPlanfrom codeverse3d.contracts.run import RunStatusfrom codeverse3d.cost.instrument import metered_chat_model, run_ledger@@ -53,21 +53,6 @@ def test_resume_restores_active_time_but_not_downtime():g3.check()-def test_a_raised_cap_grants_only_the_difference_and_grace_never_persists():- import time as _t-- g1 = BudgetGuard(Budget(max_minutes=10.0), start_time=_t.time())- g1._active_s = 8.0 * 60 # noqa: SLF001 — 8 of its 10 min- g1.grant_grace(minutes=30.0) # per-attempt salvage headroom — must NOT survive- snap = g1.snapshot()- assert "grace_minutes" not in snap.model_dump() and "soft_fraction" not in snap.model_dump()-- g2 = BudgetGuard(Budget(max_minutes=15.0)) # --max-minutes raised 10 → 15- g2.restore(snap)- assert g2.grace_minutes == 0.0- assert g2.timeout_s(3600, floor_s=0, soft=False) == pytest.approx(7 * 60, abs=6) # 15 − 8, never a fresh 15--def test_build_context_restores_the_budget_snapshot(tmp_path, settings):spec = make_spec()ws = Workspace(tmp_path / "runs" / "r").create()@@ -109,52 +94,17 @@ def test_a_paid_single_shot_response_is_persisted_when_the_budget_trips(tmp_pathassert not guard.ok() # the phase boundary (steps._run_phase) turns this into the stop-def test_single_shot_obeys_the_run_clock(tmp_path):- """A run past its HARD wall-clock ceiling must not buy a single-shot call at all- (agent-path symmetry), and a live run's request carries the REMAINING wall clock- as max_wait_s — never the models' 1800 s retry default. The truncation retry is- a second full-price call: it is preflighted the same way."""+def test_single_shot_past_the_ceiling_buys_no_call(tmp_path):ws = Workspace(tmp_path / "ws").create()task = GenerationTask(label="baseline", prompt="p", files_hint=["src/object.js"], max_output_tokens=1000)-calls: list = []- answer = ("=== FILE: src/object.js ===\n"- "export function build(THREE) { return new THREE.Group(); }\n"- "=== END FILE ===")- model = FakeChatModel(lambda req: (calls.append(req) or answer), cost=0.01)-+ model = FakeChatModel(lambda req: calls.append(req) or "", cost=0.01)past = BudgetGuard(Budget(max_minutes=1.0))past._active_s = 120.0 # noqa: SLF001 — already past 1 minwith pytest.raises(BudgetExceeded):generate_files(ws, model=model, task=task, budget=past)assert calls == [] # refused BEFORE any model call- live = BudgetGuard(Budget(max_minutes=10.0))- live._active_s = 8 * 60.0 # noqa: SLF001 — 2 minutes left- res = generate_files(ws, model=model, task=task, budget=live)- assert res.ok and len(calls) == 1- assert calls[0].max_wait_s is not None and calls[0].max_wait_s <= 121 # clipped to remaining clock-- # truncation retry: the first response is truncated, then the clock runs out- class TruncatingModel:- def __init__(self):- self.calls = 0-- def generate(self, req):- from codeverse3d.contracts.chat import ChatResponse- self.calls += 1- live2._active_s = 11 * 60.0 # noqa: SLF001 — ceiling crossed mid-call- return ChatResponse(text="=== FILE: src/object.js ===\nx", finish_reason="max_tokens",- usage=Usage(backend="fake", cost_usd=0.01), raw={})-- live2 = BudgetGuard(Budget(max_minutes=10.0))- tm = TruncatingModel()- with run_ledger(tmp_path / "trunc"), pytest.raises(BudgetExceeded):- generate_files(ws, model=metered_chat_model(tm), task=task, budget=live2)- assert tm.calls == 1 # the retry was never bought- (row,) = load_ledger(tmp_path / "trunc") # ...but the paid first call is on the ledger- assert row.cost_usd == pytest.approx(0.01)-# --------------------------------------------------------------- ordering: fan-out siblingsdef test_a_budget_tripped_candidate_still_lets_the_sibling_be_adopted(tmp_path, chair_plan, settings):@@ -213,40 +163,8 @@ def test_planning_error_dollars_are_booked_exactly_once(tmp_path):assert ei.value.usage.cost_usd == pytest.approx(0.01 * n) # the error still reports the total-# --------------------------------------------------------------- ordering: r00 boundary stop-def test_the_adopted_best_of_n_winner_survives_a_boundary_budget_stop(tmp_path, chair_plan, settings, monkeypatch):- """The winner is adopted + committed + candidates.json written, then the boundary- ``budget.check()`` trips BEFORE run_round persists r00. prepare_salvage must say- yes (the paid, buildable candidate is sitting in src/) so the salvage round- delivers ONE scored round instead of a 0-round record that re-pays all N on resume."""- import codeverse3d.tracks.candidates as cand-- real_adopt = cand.adopt_candidate-- def adopt_then_ceiling(ctx, sub_ws):- real_adopt(ctx, sub_ws)- ctx.budget._active_s = ctx.spec.budget.max_minutes * 60 + 60 # noqa: SLF001 — clock ran out during candidates-- monkeypatch.setattr(cand, "adopt_candidate", adopt_then_ceiling)-- def writer(job, ws_):- return {"src/object.js": f"// {job.label} in {ws_.root.name}\n"- "export function build(THREE) { return new THREE.Group(); }\n"}-- ws = Workspace(tmp_path / "runs" / "bo")- track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.6,)), agent=FakeAgent(writer),- planner_model=FakeChatModel(lambda req: chair_plan.model_dump(mode="json")),- settings=settings, runtime=FakeRuntime(Language.THREEJS), n_candidates=2)- rec = track.run(make_spec(max_rounds=0), ws)- assert rec.status is RunStatus.BUDGET- assert len(rec.rounds) == 1 and rec.rounds[0].score == pytest.approx(0.6)- ev = [e["event"] for e in EventLog(ws.events_path).read()]- assert "budget.salvage" in ev and "budget.salvage_skipped" not in ev--def test_a_baseline_session_the_clock_stopped_after_it_wrote_code_is_salvaged(tmp_path, chair_plan, settings):- """E6 (neon_glsl c007b166: a committed baseline, then the budget stop, then 0 rounds): code the- baseline session left behind is built, rendered and judged as one salvaged round."""+ """E6: code the baseline session left behind is built, rendered and judged as one salvaged round."""def writer(job, ws_):(ws_.src / "object.js").write_text("// paid for\nexport function build(THREE) { return new THREE.Group(); }\n")@@ -262,8 +180,6 @@ def test_a_baseline_session_the_clock_stopped_after_it_wrote_code_is_salvaged(tmdef test_a_skeleton_only_budget_trip_still_salvages_nothing(tmp_path, chair_plan, settings):- """No candidate ever finished (the ceiling tripped mid-generation): there is no- adopted winner, so the salvage hook must keep saying no off-scene."""def writer(job, ws_):raise BudgetExceeded("elapsed 11.0 min exceeds max_minutes 10.0")diff --git a/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.pyindex c991acb4..1623cd0a 100644--- a/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py+++ b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py@@ -2,14 +2,11 @@from __future__ import annotations-import json-import pytestfrom PIL import Imagefrom codeverse3d.contracts.common import Language, Trackfrom codeverse3d.contracts.plan import ArticulatedPlan-from codeverse3d.contracts.run import RunStatusfrom codeverse3d.contracts.spec import ReferenceImagefrom codeverse3d.orchestrator import (RefineTask,@@ -18,7 +15,6 @@ from codeverse3d.orchestrator import (compact_instructions,)from codeverse3d.proc import EventLog-from codeverse3d.tracks import get_trackfrom codeverse3d.tracks.articulated_object import ArticulatedObjectTrack, expected_directionfrom codeverse3d.tracks.candidates import CandidateRecord, rank_candidatesfrom codeverse3d.tracks.planner import plan_example@@ -106,79 +102,6 @@ def _writer_by_candidate(job, ws):return {"src/model.py": f"import bpy # {job.label} in {tag}\n"}-def test_best_of_two_baseline_selects_highest_quick_score(tmp_path, chair_plan, settings):- spec = make_spec(language=Language.BLENDER, max_rounds=0)- ws = Workspace(tmp_path / "runs" / "stool")- agent = FakeAgent(_writer_by_candidate)- judge = _CandidateJudge({"c0": 0.55, "c1": 0.72})- services = FakeServices()- track = StaticObjectTrack(services=services, judge=judge, agent=agent, planner_model=_planner(chair_plan.model_dump(mode="json")),- settings=settings, runtime=FakeRuntime(Language.BLENDER), n_candidates=2)- rec = track.run(spec, ws)- assert rec.status is RunStatus.MAX_ROUNDS and len(rec.rounds) == 1- r0 = rec.rounds[0]- assert "best-of-2: selected c1" in r0.notes and r0.score == pytest.approx(0.6)- assert "_cand/c1" in (ws.src / "model.py").read_text()- cands = json.loads((ws.root / "rounds" / "candidates.json").read_text())- assert cands["selected"] == 1 and [c["score"] for c in cands["candidates"]] == [0.55, 0.72]- assert cands["candidates"][1]["selected"] and cands["candidates"][0]["build_ok"]- labels = sorted(j.label for j in agent.jobs)- assert labels == ["baseline_c0", "baseline_c1"]- kinds = [e["event"] for e in EventLog(ws.events_path).read()]- assert kinds.count("candidate.done") == 2 and "candidate.selected" in kinds and "candidates.start" in kinds- # both candidates charged: round usage > one generation + one judge- assert r0.usage.cost_usd > 2 * agent.cost and rec.extra["n_candidates"] == 2 and rec.extra["candidates"]["selected"] == 1- # the sub-workspaces are git-ignored and self-contained- assert (ws.root / "_cand" / "c0" / "spec.json").is_file() and "_cand/" in (ws.root / ".gitignore").read_text()- assert (ws.root / "_cand" / "c1" / "AGENTS.md").is_file()- # the winner's trajectory was kept under the run workspace- assert any(p.name.startswith("baseline_c1") for p in ws.trajectories.iterdir())---def test_best_of_two_within_judge_noise_still_takes_the_higher_quick_score(tmp_path, chair_plan, settings):- """No pairwise tie-break any more (2026-09-22): 0.61 vs 0.60 is decided by the score."""- spec = make_spec(language=Language.BLENDER, max_rounds=0)- ws = Workspace(tmp_path / "runs" / "stool2")- judge = _CandidateJudge({"c0": 0.61, "c1": 0.60})- track = StaticObjectTrack(services=FakeServices(), judge=judge, agent=FakeAgent(_writer_by_candidate),- planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,- runtime=FakeRuntime(Language.BLENDER), n_candidates=2)- rec = track.run(spec, ws)- assert "best-of-2: selected c0" in rec.rounds[0].notes and "pairwise" not in rec.rounds[0].notes- assert "_cand/c0" in (ws.src / "model.py").read_text()- assert not [e for e in EventLog(ws.events_path).read() if e["event"] == "pairwise.done"]- assert "pairwise" not in json.loads((ws.root / "rounds" / "candidates.json").read_text())---def test_candidate_count_persists_for_resume_and_settings_default(tmp_path, chair_plan, settings):- from codeverse3d.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))- track.run(spec, ws)- assert json.loads(ws.state_path.read_text())["extra"].get("n_candidates") is None- # a resume without the flag reads the persisted width- t2 = 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))- from codeverse3d.orchestrator import RunState-- ctx = t2.build_context(spec, ws, EventLog(ws.events_path), RunState.load(ws))- assert ctx.policy.n_candidates == 2- # settings default is honoured when nothing else says- settings2 = settings.model_copy()- object.__setattr__(settings2, "default_candidates", 3)- t3 = StaticObjectTrack(services=FakeServices(), settings=settings2, runtime=FakeRuntime(Language.BLENDER))- 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 == 3- assert get_track("static_object", n_candidates=4)._n_candidates == 4--# ----------------------------------------------------------------------------- reference imagesdef test_reference_images_wire_judge_prompts_and_silhouette(tmp_path, chair_plan, settings):ref = tmp_path / "ref.png"@@ -208,20 +131,6 @@ def test_reference_images_wire_judge_prompts_and_silhouette(tmp_path, chair_planassert "## Reference images" in refine_prompt and "compare_reference" not in refine_prompt # single-shot: no tools-def test_reference_note_mentions_silhouette_tool_for_agents(tmp_path, chair_plan, settings):- ref = tmp_path / "ref.png"- Image.new("RGB", (64, 48)).save(ref)- spec = make_spec(language=Language.BLENDER, max_rounds=0, references=[ReferenceImage(path=str(ref))])- ws = Workspace(tmp_path / "runs" / "ref2")- agent = FakeAgent(lambda job, ws: {"src/model.py": "import bpy\n"})- track = StaticObjectTrack(services=FakeServices(silhouette_iou=0.8), agent=agent, planner_model=_planner(chair_plan.model_dump(mode="json")),- settings=settings, runtime=FakeRuntime(Language.BLENDER))- rec = track.run(spec, ws)- assert "compare_reference" in agent.jobs[0].prompt and str(ref) in agent.jobs[0].prompt- gate = next(g for g in rec.rounds[0].gates if g.gate == "reference_silhouette")- assert gate.findings[0].severity.value == "info" # IoU 0.8 is fine → no refine task--# ----------------------------------------------------------------------------- articulated motion gatedef test_articulated_motion_direction_gate_feeds_refine_and_judge(tmp_path, settings):spec = make_spec(Track.ARTICULATED_OBJECT, Language.URDF_BLENDER, max_rounds=1)@@ -239,19 +148,6 @@ def test_articulated_motion_direction_gate_feeds_refine_and_judge(tmp_path, settassert any(v.name == "pose_DrawerSlide_upper" for v in rec.rounds[0].renders.views)-# ----------------------------------------------------------------------------- per-part files come from the runtime-def test_expected_files_and_targets_follow_the_runtime_layout(tmp_path, chair_plan, settings):- from codeverse3d.orchestrator import RunState-- spec = make_spec(language=Language.BLENDER, max_rounds=0)- track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.BLENDER))- ctx = track.build_context(spec, Workspace(tmp_path / "ws").create(), EventLog(tmp_path / "e.jsonl"), RunState())- ctx.plan = chair_plan- assert ctx.runtime.expected_files(ctx.plan)[:3] == ["src/model.py", "src/parts/seat.py", "src/parts/front_leg.py"]- fft = track.refine_file_for_target(ctx)- assert fft("Seat") == ["src/parts/seat.py"] and fft("overall") == ["src/model.py"] and fft("BackLeg_1") == []--def test_crashed_candidate_is_retried_once(tmp_path, chair_plan, settings):spec = make_spec(language=Language.BLENDER, max_rounds=0)ws = Workspace(tmp_path / "runs" / "retry")@@ -274,7 +170,6 @@ def test_crashed_candidate_is_retried_once(tmp_path, chair_plan, settings):def test_default_motion_checks_on_real_urdf(tmp_path):- """Hinged door: axis -z opens to the front (ok); axis +z → WRONG with the negated-axis fix."""import trimeshfrom codeverse3d.contracts.plan import BBox, JointPlan, PartPlan@@ -330,44 +225,8 @@ def test_default_motion_checks_on_real_urdf(tmp_path):assert default_motion_checks(robot(tmp_path / "none", 1), plan) is None-# ------------------------------------------------- best-of-N on a track with no GLB-def test_a_track_without_a_glb_still_gets_candidate_renders():- """`quick_render` hardcoded the GLB rig, so tracks that produce no GLB got None —- the candidate was never judged, scored None, and best-of-N fell through to index 0.-- Measured 2026-08-25 across the teaser battery: static_object and articulated_object- candidates all carried real scores; all SIX graphics runs recorded- `scores: {c0: null, c1: null}` with `selected: 0`, two of them at n=3. No- `candidate.judge_failed` event fired anywhere — nothing errored, the judge was simply- never reached, and every extra candidate was generated, paid for and discarded blind.- """- from pathlib import Path- from types import SimpleNamespace-- from codeverse3d.tracks.candidates import quick_render-- class _Pipeline:- def __init__(self): self.calls = []- def render(self, ctx, round_index, build, measurement):- self.calls.append((round_index, build, measurement))- return "frames-renderset"-- class _WS:- def renders_dir(self, i): return Path("/tmp/unused")-- class _Ctx:- ws = _WS()-- pipe = _Pipeline()- 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")]--def 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 through- the reduced-view, reduced-resolution quick rig, not pipeline.render."""+ """A GLB candidate goes through the reduced quick rig, never pipeline.render."""from types import SimpleNamespacefrom codeverse3d.tracks.candidates import OBJECT_VIEWS_QUICK, QUICK_PX, quick_renderdiff --git a/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py b/harness/tests/orchestrator_tracks/test_cookbook_excerpt.pyindex 49680307..593fb18b 100644--- a/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py+++ b/harness/tests/orchestrator_tracks/test_cookbook_excerpt.py@@ -1,10 +1,4 @@-"""``select_cookbook_excerpt``: the graphics prompt carries the cookbook chapters its brief calls for.--Measured 2026-08-26: ``cookbook_text[:7000]`` of an 11,298-char cookbook cut everything after-the raymarching template (sky / stars, rain, bokeh, feedback, PITFALLS) out of every graphics-prompt, and flash drew what it was handed — an aurora as a comb of bars, a star field of twenty-sparkles. The selector hands over whole chapters, ranked by the brief, inside a budget.-"""+"""Every track sends the whole cookbook; the GLSL cookbook's aurora example ships (Q9)."""from __future__ import annotations@@ -12,31 +6,11 @@ from types import SimpleNamespacefrom codeverse3d.contracts.common import Language, Trackfrom codeverse3d.prompts import PROMPTS_DIR, load_text-from codeverse3d.prompts.sections import split_sectionsEXAMPLE = PROMPTS_DIR / "glsl_shader" / "examples" / "aurora_ridge.frag"-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- titles = [s.title for s in secs]- assert any(t.startswith("Light phenomena") for t in titles)- assert any(t.startswith("Gradient sky") for t in titles)- assert any(t.startswith("PITFALLS") for t in titles)--def test_every_track_sends_the_whole_cookbook(monkeypatch) -> None:- """No track delivers the cookbook by byte offset any more.-- It used to be ``ctx.cookbook_text[:6000]`` in base_prompt_context and a 9 000-char- chapter selection in graphics — 13 % of blender's 46 623 chars, 10 % of- 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 left- out simply never reached the model. Chapter SELECTION is still right where the- stage knows which chapters it needs (scene's env/zone recipes, graphics' recipe- seeding); it is not right as a way to shrink the reference itself.- """from codeverse3d.languages import get_runtimefrom codeverse3d.tracks import graphics as graphics_stepsfrom codeverse3d.tracks.prompting import base_prompt_contextdiff --git a/harness/tests/orchestrator_tracks/test_cost_latency.py b/harness/tests/orchestrator_tracks/test_cost_latency.pyindex 05aee436..92bd9a53 100644--- a/harness/tests/orchestrator_tracks/test_cost_latency.py+++ b/harness/tests/orchestrator_tracks/test_cost_latency.py@@ -17,8 +17,6 @@ from codeverse3d.proc import EventLogfrom codeverse3d.tracks.common import (RunContext,generate_for,- single_shot_agent_id,- single_shot_ctx,)from codeverse3d.tracks.generation import GenerationTaskfrom codeverse3d.tracks.planner import plan_example@@ -114,14 +112,6 @@ def _zone(name: str, n: int) -> ZonePlan:contents=[f"A{i}" for i in range(n)])-# ----------------------------------------------------------------------------- single-shot assets-def test_single_shot_needs_a_chat_model_not_a_coding_agent():- 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- assert single_shot_agent_id("claude-code:opus", "not-an-id") == "" # not '<provider>:<model>'--class _ChatServices(FakeServices):"""FakeServices that CAN hand out a chat model (so single-shot is reachable)."""@@ -168,81 +158,6 @@ def _events(ctx) -> list[dict]:return [json.loads(line) for line in ctx.ws.events_path.read_text().splitlines() if line.strip()]-@needs_node-def test_assets_are_single_shot_by_default_and_never_open_an_agent_session(tmp_path, settings):- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- plan = plan.model_copy(update={"assets": [a for a in plan.assets if a.kind == "threejs"]})- calls: list[str] = []-- def respond(req):- rel = req.messages[0].text.split("write `")[1].split("`")[0]- calls.append(rel)- pascal = "".join(w.capitalize() for w in rel.rsplit("/", 1)[-1][:-3].split("_"))- size = [float(x) for x in req.messages[0].text.split("meters): ")[1].split("\n")[0].split(" × ")]- return _envelope(rel, _module(pascal, *size))-- agent = FakeAgent(lambda job, ws: {"src/nope.js": "// should not run\n"})- services = _ChatServices(FakeChatModel(respond, cost=0.02), judge=FakeJudge(scores=(0.4,)))- ctx = _scene_ctx(tmp_path, settings, services=services, agent=agent, plan=plan)- results = run_asset_stage(ctx)- assert set(results) == {a.name for a in plan.assets}- assert all(r.ok and r.strategy == "single-shot" for r in results.values())- assert not agent.jobs, "a single-shot asset must not open a coding-agent session"- assert sorted(calls) == sorted(f"src/assets/{n}" for n in ("bollard.js", "fishing_boat.js"))- # measured size comes from the deterministic check, not the plan guess- assert results["FishingBoat"].size_m is not None- ev = {e["event"] for e in _events(ctx)}- assert "asset.generated" in ev and "assets.done" in ev---@needs_node-def test_a_broken_asset_gets_one_error_feedback_repair_then_escalates_to_an_agent(tmp_path, settings):- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- one = [a for a in plan.assets if a.kind == "threejs"][:1]- plan = plan.model_copy(update={"assets": one, "zones": []})- prompts: list[str] = []-- def respond(req):- prompts.append(req.messages[0].text)- rel = "src/assets/fishing_boat.js"- # both single-shot attempts return a module with a removed-API call- return _envelope(rel, "import * as THREE from 'three';\n"- "export function buildFishingBoat(T = THREE) {\n"- " return new T.Mesh(new T.BoxBufferGeometry(1, 1, 1));\n}\n")-- agent = FakeAgent(lambda job, ws: {"src/assets/fishing_boat.js": _module("FishingBoat", 8.0, 3.5, 3.0)})- services = _ChatServices(FakeChatModel(respond, cost=0.02), judge=FakeJudge(scores=(0.9,)))- ctx = _scene_ctx(tmp_path, settings, services=services, agent=agent, plan=plan)- results = run_asset_stage(ctx)- assert len(prompts) == 2, "exactly ONE error-feedback repair before escalating"- assert "did NOT pass the deterministic asset check" in prompts[1] and "BoxBufferGeometry" in prompts[1]- assert [j.label for j in agent.jobs] == ["asset_fishing_boat"]- assert results["FishingBoat"].ok and results["FishingBoat"].strategy == "escalated"- ev = [e for e in _events(ctx) if e["event"] == "asset.escalated"]- assert ev and ev[0]["asset"] == "FishingBoat"---@needs_node-def test_small_clean_assets_skip_the_judge_and_heroes_do_not(tmp_path, settings):- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- small = _asset("Bollard", (0.3, 0.5, 0.3))- plan = plan.model_copy(update={"assets": [small], "zones": []})-- def respond(req):- return _envelope("src/assets/bollard.js", _module("Bollard", 0.3, 0.5, 0.3))-- judge = FakeJudge(scores=(0.2,))- services = _ChatServices(FakeChatModel(respond), judge=judge)- ctx = _scene_ctx(tmp_path, settings, services=services, agent=FakeAgent(lambda j, w: None), plan=plan)- # the scene runtime grows a render_asset hook: without the skip rule this would judge- ctx.runtime.render_asset = lambda ws, name, out_dir: services.render_object( # type: ignore[attr-defined]- ws.artifacts / "x.glb", out_dir, views=(), width=64, height=64)- run_asset_stage(ctx)- skipped = [e for e in _events(ctx) if e["event"] == "asset.judge_skipped"]- assert skipped and skipped[0]["reason"] == "gates_ok_and_small" and skipped[0]["volume_fraction"] < 0.05- assert not judge.calls--def test_asset_check_names_the_file_that_was_never_written(tmp_path, settings):services = FakeServices()ctx = _scene_ctx(tmp_path, settings, services=services)@@ -250,22 +165,13 @@ def test_asset_check_names_the_file_that_was_never_written(tmp_path, settings):assert not chk.ok and chk.ran and chk.fatal and "was not written" in chk.errors[0]-def test_single_shot_ctx_is_none_for_cli_backends(tmp_path, settings):- ctx = _scene_ctx(tmp_path, settings, services=FakeServices(), agent_id="gemini-cli:gemini-3.7-flash")- assert single_shot_ctx(ctx) is None- ctx2 = _scene_ctx(tmp_path, settings, services=FakeServices(), agent_id="fake-agent:gemini:x")- assert single_shot_ctx(ctx2) is None # FakeServices has no chat model → agent path stays--# a CLI session that died at the wall after a 503 streak: nothing written, transientSTORM_DEATH = AgentResult(ok=False, exit_reason="timeout", transient=True,errors=["killed by watchdog (hard_timeout) after 720s", "11 x 503 inside the CLI's own retry loop before the wall; nothing produced"])def test_a_storm_dead_session_falls_back_to_single_shot(tmp_path, settings):- """Loops 10-11 (2026-09-07): 23 of 24 gemini-cli sessions ended timeout / 0 turns / $0 in- a 503 storm while every single-shot got through; env and zones shipped the skeleton and- judged 0.00-0.14. The same task goes once more through the hedged single-shot path."""+ """A session that died in a 503 storm goes once more through the single-shot path."""def respond(req):return _envelope("src/env.js", "export function buildEnv() { return {}; }\n")@@ -281,53 +187,8 @@ def test_a_storm_dead_session_falls_back_to_single_shot(tmp_path, settings):assert "generate.storm_fallback" in kinds-def test_a_plain_failed_session_does_not_fall_back(tmp_path, settings):- """An agent that ran and produced nothing (not a storm) keeps its own verdict: the- fallback is for the transport being down, not for the task being hard."""- services = _ChatServices(FakeChatModel(lambda req: _envelope("src/env.js", "x")))- agent = FakeAgent(lambda j, w: None)- ctx = _scene_ctx(tmp_path, settings, services=services, agent=agent, agent_id="fake-agent:gemini:x")- task = GenerationTask(label="env", prompt="write `src/env.js`", files_hint=["src/env.js"], round=0, kind="env")- res = generate_for(ctx, task)- assert not res.ok and not res.storm and services.chat_ids == []---# ----------------------------------------------------------------------------- salvage-def test_a_budget_stop_before_round_zero_still_delivers_a_judged_round(tmp_path, settings):- plan = small_scene()- spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=1)- ws = Workspace(tmp_path / "runs" / "greenhouse")- services = FakeServices(assemble=True)-- def writer(job, ws_):- if job.label == "env":- return {"src/env.js": "export function buildEnv(){}\n"}- if job.label.startswith("zones_") or job.label.startswith("zone_"):- return {rel: "export function build(){}\n" for rel in (job.files_hint or ["src/zones/x.js"])}- return {f"src/assets/{job.label[6:]}.js": f"export function build(){{}} // {job.label}\n"}-- # the greenhouse hole: 2 asset sessions + env stay under the 10-minute clock; the zone- # session's own 3 minutes cross it mid-stage (4 × 3 = 12)- track = SceneTrack(services=services, judge=FakeJudge(scores=(0.58,)), agent=FakeAgent(writer, cost=1.3, minutes=3.0),- planner_model=_planner(plan.model_dump(mode="json")), settings=settings,- runtime=FakeRuntime(Language.SCENE_THREEJS))- with fake_clock():- rec = track.run(spec, ws)- assert rec.status is RunStatus.BUDGET and rec.extra["stop_reason"] == "budget"- # …and, unlike the greenhouse run, it has a score- assert len(rec.rounds) == 1 and rec.rounds[0].renders is not None and rec.rounds[0].score == pytest.approx(0.58)- assert "salvaged" in rec.rounds[0].notes- ev = [json.loads(x) for x in (ws.root / "events.jsonl").read_text().splitlines() if x.strip()]- names = [e["event"] for e in ev]- assert "budget.salvage" in names- salvage = next(e for e in ev if e["event"] == "budget.salvage")- assert salvage["grace_minutes"] > 0--def test_a_zones_session_the_clock_stopped_is_kept_for_the_resume(tmp_path, settings):- """Q1: the clock is checked AFTER the zones stage is recorded, so the finished (paid) session- is cached, and the resume under the salvaged r00 serves it — it used to re-run the zones- session over r00's src/ (reproduced in the 2026-09-22 review)."""+ """Q1: the finished (paid) zones session is cached and the resume under the salvaged r00 serves it."""plan = small_scene()spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=1)ws = Workspace(tmp_path / "runs" / "quay")@@ -345,25 +206,6 @@ def test_a_zones_session_the_clock_stopped_is_kept_for_the_resume(tmp_path, settassert agent.jobs and not any(j.label.startswith("zone") for j in agent.jobs)-def test_soft_budget_notes_land_in_the_round_record(tmp_path, settings):- plan = small_scene()- spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0)- ws = Workspace(tmp_path / "runs" / "degraded")- services = FakeServices(assemble=True)- # a slow agent: the soft cap (55 % of the 10-minute clock) is crossed during the asset stage- agent = FakeAgent(_writer, cost=1.1, minutes=2.0)- track = SceneTrack(services=services, judge=FakeJudge(scores=(0.5,)), agent=agent,- planner_model=_planner(plan.model_dump(mode="json")), settings=settings,- runtime=FakeRuntime(Language.SCENE_THREEJS))- with fake_clock():- rec = track.run(spec, ws)- ev = [json.loads(x) for x in (ws.root / "events.jsonl").read_text().splitlines() if x.strip()]- degraded = [e for e in ev if e["event"] == "budget.degraded"]- assert degraded, "the soft cap must be reported before the hard cap kills the run"- assert any("soft budget spent" in n for n in degraded[0]["note"].split(";")[:1] or [degraded[0]["note"]])- assert any("soft budget spent" in n for n in rec.rounds[0].notes.split("; "))--def _writer(job, ws):if job.label.startswith("zones_") or job.label.startswith("zone_"):return {rel: "export function build(){}\n" for rel in (job.files_hint or ["src/zones/x.js"])}@@ -413,32 +255,8 @@ def test_asset_selection_folds_only_over_the_cap():assert all(v in {k.name for k in kept} for v in alias.values())-def test_a_batched_session_that_writes_only_one_file_fails_the_other_zone(tmp_path, settings):- 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)]})- spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0)- ws = Workspace(tmp_path / "runs" / "halfzone")- services = FakeServices(assemble=True)-- def writer(job, ws_):- if job.label.startswith("zones_"):- return {"src/zones/quay.js": "export function build(){}\n"} # Water never written- if job.label == "env":- return {"src/env.js": "export function buildEnv(){}\n"}- return {"src/x.js": "// x\n"}-- track = SceneTrack(services=services, judge=FakeJudge(scores=(0.6,)), agent=FakeAgent(writer),- planner_model=FakeChatModel(lambda req: plan.model_dump(mode="json")), settings=settings,- runtime=FakeRuntime(Language.SCENE_THREEJS))- track.run(spec, ws)- zones = json.loads((ws.root / "stages" / "zones.json").read_text())["result"]- assert zones["Quay"]["ok"] and not zones["Water"]["ok"]--def test_a_clock_that_trips_after_a_finished_zones_session_records_what_it_wrote(tmp_path, settings):- """Q1: the session finished and wrote both zones, then its charge crossed the ceiling; the cached- zones result said ok: False for every zone — a resume served "all failed" for written work."""+ """Q1: the cached zones result records the zones the session wrote before its charge crossed the ceiling."""from tests.orchestrator_tracks.conftest import FAKE_CLOCKplan = ScenePlan.model_validate(plan_example(Track.SCENE))@@ -534,27 +352,3 @@ def test_the_shot_after_an_outage_is_a_plain_generation_not_a_repair(tmp_path, sassert results["Bollard"].ok and results["Bollard"].strategy == "single-shot" and not agent.jobsassert len(prompts) == 2 and prompts[1] == prompts[0], "the model wrote nothing: there is nothing to repair"assert "did NOT pass" not in prompts[1] and "rewrite COMPLETELY" not in prompts[1]---def test_one_asset_cannot_eat_the_scene_run():- from codeverse3d.contracts.spec import Budget- from codeverse3d.orchestrator import BudgetGuard- from codeverse3d.tracks.scene_assets import (- ASSET_AGENT_TIMEOUT_S,- ASSET_SESSION_SHARE,- asset_timeout_s,- )-- class Ctx:- 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"- assert fresh <= 25 * 60 * ASSET_SESSION_SHARE + 1, "at most its share of the run"- Ctx.budget.start_time -= 23 * 60 # 2 minutes left- 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))-- 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 7d083f1e..c7c5520b 100644--- a/harness/tests/orchestrator_tracks/test_fix_batch2.py+++ b/harness/tests/orchestrator_tracks/test_fix_batch2.py@@ -1,4 +1,4 @@-"""Regression tests for review fix batch 2 (orchestrator / lifecycle findings)."""+"""Lifecycle regressions: aborted rounds, degraded verdicts, the skeleton guard, finalise rebuilds."""from __future__ import annotations@@ -6,13 +6,12 @@ import jsonimport pytest-from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Judgment, Severity+from codeverse3d.contracts.artifacts import BuildResult, GateReport, Judgmentfrom codeverse3d.contracts.common import Language, Trackfrom codeverse3d.contracts.plan import BBox, PartPlan, ScenePlan, StaticPlanfrom codeverse3d.contracts.run import RoundRecord, RunStatusfrom codeverse3d.orchestrator import RunStatefrom codeverse3d.proc import EventLog-from codeverse3d.prompts import load_textfrom codeverse3d.tracks.planner import plan_examplefrom codeverse3d.tracks.scene import SceneTrackfrom codeverse3d.tracks.static_object import StaticObjectTrack@@ -58,29 +57,9 @@ class ScriptedJudge(FakeJudge):return out-# --------------------------------------------------------------------- finding: judge charge after persist-def test_judged_round_survives_budget_ceiling_crossed_by_judge(tmp_path, chair_plan, settings):- """steps.py:148 — the judge's own charge used to raise BudgetExceeded BEFORE the round- was 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_minutes- track = StaticObjectTrack(services=FakeServices(), judge=judge, agent=FakeAgent(_writer),- planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,- runtime=FakeRuntime(Language.THREEJS))- with fake_clock():- rec = track.run(spec, ws)- assert rec.status is RunStatus.BUDGET and rec.extra["stop_reason"] == "budget"- assert len(rec.rounds) == 1 and rec.rounds[0].score == pytest.approx(0.55)- assert (ws.root / "rounds" / "r00.json").is_file() and ws.judge_path(0).is_file()- # the judge cost is still in the totals, and in the round's- assert rec.total_usage.cost_usd > 0.05 and rec.rounds[0].usage.cost_usd > 0.05--# --------------------------------------------------------------------- finding: finalise with a dirty tree at the last commitdef test_finalise_restores_the_last_round_when_an_aborted_round_dirtied_src(tmp_path, chair_plan, settings):- """lifecycle.py:263 — a refine round that wrote files but died on the generation charge- left HEAD at the last round's commit with foreign src/: the run then ended on unjudged code."""+ """A refine round that died after writing files leaves src/ back on the last judged round."""spec = make_spec(max_rounds=3)ws = Workspace(tmp_path / "runs" / "r")# the baseline session's 6 minutes fit the 10-minute clock; the refine session's 6 more@@ -100,31 +79,6 @@ def test_finalise_restores_the_last_round_when_an_aborted_round_dirtied_src(tmp_assert rec.extra["aborted_rounds"][0]["cost_usd"] == pytest.approx(0.01, abs=1e-6)-# --------------------------------------------------------------------- finding: finalise rebuild fails after invalidation-def test_a_failed_finalise_rebuild_cannot_finalize_silently(tmp_path, chair_plan, settings, monkeypatch):- """Every real runtime invalidates the canonical artifact FIRST in build(), so a- failed rebuild of the restored last round leaves object.glb MISSING — yet the run- used to finalize as if nothing happened. The earned status + judge scores are kept;- the ``finalise_rebuild_failed`` flag says what happened, and the round's own kept- build (``artifacts/r00/``) is untouched."""- spec = make_spec(max_rounds=3)- ws = Workspace(tmp_path / "runs" / "r")- # the refine round's agent crosses the wall clock after its files hit the disk: finalise- # puts src/ back on r00 and rebuilds it — and that rebuild fails- track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.7,), targets=("Seat",)),- agent=FakeAgent(_writer, minutes=6.0), planner_model=_planner(chair_plan.model_dump(mode="json")),- settings=settings, runtime=_RebuildFails(Language.THREEJS))- with fake_clock():- rec = track.run(spec, ws)- assert rec.status is RunStatus.BUDGET and rec.rounds[0].score == pytest.approx(0.7) # the earned status + score stay- assert "runtime crashed on rebuild" in rec.extra["finalise_rebuild_failed"]- assert not (ws.artifacts / "object.glb").is_file() and (ws.round_artifacts(0) / "object.glb").is_file()- on_disk = json.loads(ws.record_path.read_text())- assert on_disk["extra"]["finalise_rebuild_failed"] and on_disk["status"] == "budget"- ev = [e for e in EventLog(ws.events_path).read() if e["event"] == "finalise.rebuild"]- assert ev and ev[-1]["ok"] is False--class _RebuildFails(FakeRuntime):"""Fails the finalise rebuild (the build right after a "back to the last round" commit)``fails`` times, invalidating the canonical GLB first as the real runtimes do."""@@ -281,41 +235,8 @@ def test_plan_digest_is_labelled_w_h_d_in_the_measurement_frame():assert "Overall 0.48×0.52×0.80 m (W×H×D)" in yup # identity for Y-up plans-# --------------------------------------------------------------------- finding: articulated prompt origin rule-def test_articulated_prompt_states_negated_pivot_visual_origin():- text = load_text("tracks/generate_articulated.j2")- assert "child mesh offset relative to P" not in text- assert "NEGATED world pivot" in text and "WORLD coordinates" in text- assert "visual AND collision" in text---# --------------------------------------------------------------------- integration: scene_frames errors reach refine-def test_scene_frames_gate_errors_flow_into_refine_instructions(tmp_path, settings):- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- spec = make_spec(Track.SCENE, Language.SCENE_THREEJS)- ws = Workspace(tmp_path / "runs" / "r")- ws.create()- track = SceneTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.SCENE_THREEJS))- ctx = track.build_context(spec, ws, EventLog(ws.events_path), RunState())- ctx.plan = plan- frames = GateReport(gate="scene_frames", passed=False, findings=[- GateFinding(gate="scene_frames", severity=Severity.ERROR, target=plan.cameras[0].name,- message="frame is 78% dark (mean luminance 0.04)",- fix_hint="raise ambient/hemisphere light intensity or move the camera out of shadow",- data={"kind": "dark_frame"})])- last = RoundRecord(index=0, kind="baseline", build=BuildResult(ok=True, language="scene_threejs"),- gates=[GateReport(gate="lint:scene_threejs", passed=True), frames])- tasks, instructions = track.refine_tasks(ctx, last)- assert tasks, "a scene_frames ERROR must produce a refine task"- joined = "\n".join(instructions)- assert "dark" in joined and "FIX: raise ambient" in joined--def test_a_successful_re_finalise_clears_the_stale_rebuild_failed_flag(tmp_path, chair_plan, settings, monkeypatch):- """The prior-record merge carries extra keys the new record lacks — so a run that- once recorded ``finalise_rebuild_failed`` and is later resumed to a SUCCESSFUL- rebuild must clear the flag explicitly (a no-rebuild resume keeps it: the- artifact may still be the missing one)."""+ """A failed finalise rebuild is flagged; a later resume that rebuilds successfully clears the flag."""spec = make_spec(max_rounds=3)ws = Workspace(tmp_path / "runs" / "r")runtime = _RebuildFails(Language.THREEJS, fails=1)diff --git a/harness/tests/orchestrator_tracks/test_fix_generation.py b/harness/tests/orchestrator_tracks/test_fix_generation.pyindex 304e3252..3d6818d4 100644--- a/harness/tests/orchestrator_tracks/test_fix_generation.py+++ b/harness/tests/orchestrator_tracks/test_fix_generation.py@@ -59,29 +59,6 @@ def test_generate_files_truncation_policy(tmp_path):assert [e["event"] for e in events.read()].count("generate.truncated") == 1 # one cut, one event-# --------------------------------------------------------------------- finding: out-of-root path aborted the whole write-def test_out_of_root_paths_are_skipped_not_fatal(tmp_path):- ws = Workspace(tmp_path / "ws").create()- answer = (- "=== FILE: src/model.py ===\nimport bpy\n=== END FILE ===\n"- "=== FILE: README.md ===\n# notes\n=== END FILE ===\n"- "=== FILE: package.json ===\n{}\n=== END FILE ===\n"- "=== FILE: ../evil.py ===\nx = 1\n=== END FILE ==="- )- events = EventLog(tmp_path / "e.jsonl")- task = GenerationTask(label="baseline", prompt="p", files_hint=["src/model.py"])- res = generate_files(ws, model=scripted([(answer, "STOP")]), task=task, events=events)- assert res.ok, res.notes # the good file was paid for — never abort the round on a README- assert (ws.root / "src" / "model.py").is_file()- assert not (ws.root / "README.md").exists() and not (tmp_path / "evil.py").exists()- assert [c.path for c in res.files_changed] == ["src/model.py"]- assert "README.md" in res.notes- skipped = [e for e in events.read() if e["event"] == "generate.skipped_path"]- assert {e["path"] for e in skipped} == {"README.md", "package.json", "../evil.py"}- done = next(e for e in events.read() if e["event"] == "generate.done")- assert done["files"] == ["src/model.py"]--# --------------------------------------------------------------------- finding: whole-workspace diff claimed sibling tasks' filesclass NonReportingAgent:"""An agent that writes its own file but reports no files_changed (fallback path)."""@@ -116,13 +93,3 @@ def test_run_agent_task_passes_files_hint_and_attributes_fallback_diff(tmp_path)res = run_agent_task(ws, agent=agent, task=task)assert agent.jobs[0].files_hint == ["src/parts/seat.js"] # per-session attribution keyassert res.ok and [c.path for c in res.files_changed] == ["src/parts/seat.js"]---def test_run_agent_task_that_wrote_nothing_is_not_ok(tmp_path):- ws = Workspace(tmp_path / "ws").create()- ws.commit("init")- (ws.root / "events.jsonl").write_text("{}\n") # harness noise only- agent = NonReportingAgent({})- task = GenerationTask(label="asset_stone_lantern", prompt="p", files_hint=["src/assets/stone_lantern.js"])- res = run_agent_task(ws, agent=agent, task=task)- assert not res.ok and res.files_changed == []diff --git a/harness/tests/orchestrator_tracks/test_fixed_rounds.py b/harness/tests/orchestrator_tracks/test_fixed_rounds.pyindex 5068b9ff..f9ed6930 100644--- a/harness/tests/orchestrator_tracks/test_fixed_rounds.py+++ b/harness/tests/orchestrator_tracks/test_fixed_rounds.py@@ -10,7 +10,7 @@ from codeverse3d.contracts.run import RunStatusfrom codeverse3d.proc import EventLogfrom codeverse3d.tracks.static_object import StaticObjectTrackfrom codeverse3d.workspace import Workspace-from tests.orchestrator_tracks.conftest import fake_clock, make_spec+from tests.orchestrator_tracks.conftest import make_specfrom tests.orchestrator_tracks.fakes import (FakeAgent,FakeJudge,@@ -27,12 +27,11 @@ def _track(chair_plan, settings, scores, *, agent=None) -> StaticObjectTrack:runtime=FakeRuntime(Language.CADQUERY))[email protected]("scores", [- (0.55, 0.85, 0.95), # passes at r01 — once a "pass" stop- (0.60, 0.60, 0.60), # flat — once a plateau / diminishing-returns stop- (0.70, 0.40, 0.30), # regresses twice — once a rewrite, then a "regression" stop-], ids=["passing", "flat", "regressing"])[email protected]("max_rounds", [0, 3])[email protected](("scores", "max_rounds"), [+ ((0.55, 0.85, 0.95), 3), # passes at r01 — once a "pass" stop+ ((0.70, 0.40, 0.30), 3), # regresses twice — once a "regression" stop+ ((0.60,), 0),+], ids=["passing", "regressing", "baseline-only"])def test_a_run_is_the_baseline_plus_max_rounds_whatever_the_judge_says(tmp_path, chair_plan, settings, scores,max_rounds):ws = Workspace(tmp_path / "runs" / "fixed")@@ -45,18 +44,7 @@ def test_a_run_is_the_baseline_plus_max_rounds_whatever_the_judge_says(tmp_path,assert [e["reason"] for e in stops] == ["max_rounds"]-def test_only_the_clock_stops_a_run_early(tmp_path, chair_plan, settings):- agent = FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # r{job.round}\n"}, minutes=4.0)- ws = Workspace(tmp_path / "runs" / "clock")- with fake_clock():- rec = _track(chair_plan, settings, (0.5, 0.6, 0.7, 0.8), agent=agent).run(- make_spec(language=Language.CADQUERY, max_rounds=4, max_minutes=10.0), ws)- assert rec.status is RunStatus.BUDGET and 1 <= len(rec.rounds) < 5--def test_every_refine_starts_from_the_previous_rounds_commit(tmp_path, chair_plan, settings):- """0.70 → 0.30 is a regression the loop once answered by restoring r00 before r02- (D73 refine-from-best). Now r02 starts from r01's code, and nothing is restored."""seen: dict[int, str] = {}def writer(job, ws):diff --git a/harness/tests/orchestrator_tracks/test_generation_depth.py b/harness/tests/orchestrator_tracks/test_generation_depth.pyindex d48a164b..caba67c7 100644--- a/harness/tests/orchestrator_tracks/test_generation_depth.py+++ b/harness/tests/orchestrator_tracks/test_generation_depth.py@@ -6,14 +6,12 @@ import refrom codeverse3d.contracts.common import Languagefrom codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan-from codeverse3d.conventions import MAX_TRIS_OBJECT, to_snake+from codeverse3d.conventions import to_snakefrom codeverse3d.tracks.depth import (DETAIL_ADVICE,PartScope,- depth_budget,interfaces_text,scope_groups,- scoped_generation_enabled,)from .conftest import make_spec@@ -24,26 +22,6 @@ def _files_for(name):return [f"src/parts/{to_snake(name)}.py"]-# ----------------------------------------------------------------------------- the triangle budget-def test_depth_budget_scales_with_the_plan_and_is_bounded(chair_plan):- small = depth_budget(StaticPlan(object_name="Stool", summary="s", overall_bbox=chair_plan.overall_bbox,- parts=chair_plan.parts[:1], acceptance=chair_plan.acceptance))- big = depth_budget(chair_plan)- assert big.n_units > small.n_units # 5 parts / 7 units vs 1- assert big.target_tris > small.target_tris # a bigger machine is allowed more- assert small.target_tris >= 6_000 and big.max_tris <= MAX_TRIS_OBJECT- assert small.min_tris < small.target_tris < small.max_tris- assert 20 <= big.max_build_s <= 300 - 30- 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-- # the budget is enforced by budget_gate; the prompt's detail advice states no number- assert "not on new parts" in DETAIL_ADVICE and not re.search(r"\d", DETAIL_ADVICE)--# ----------------------------------------------------------------------------- scopingdef test_scope_groups_partitions_along_the_attachment_tree(chair_plan):scopes = scope_groups(chair_plan, files_for=_files_for, max_groups=6, min_parts=3)@@ -73,15 +51,6 @@ def test_interfaces_text_names_only_the_neighbours_outside_the_scope(chair_plan)assert "no parts outside this scope" in empty-def test_scoped_generation_can_be_switched_off(switch):- switch("C3D_SCOPED_PARTS", "off")- assert scoped_generation_enabled() is False- switch("C3D_SCOPED_PARTS", "on")- assert scoped_generation_enabled() is True- switch("C3D_SCOPED_PARTS", None)- assert scoped_generation_enabled() is True--# ----------------------------------------------------------------------------- the track wiringdef big_plan(n: int = 11) -> StaticPlan:"""A plan past the scoping threshold, with a real attachment tree (Body → N children)."""@@ -124,20 +93,10 @@ def test_scoped_baseline_fans_out_and_the_assembly_session_owns_the_entry(tmp_pa# every scoped prompt carries ITS parts, the interface table and the detail advice — not the planone = parts[0]assert "Interfaces" in one.prompt and DETAIL_ADVICE in one.prompt+ assert not re.search(r"\d", DETAIL_ADVICE), "the budget is enforced by budget_gate; the advice states no number"assert "FILES YOU MAY WRITE" in one.prompt-def test_scoping_off_single_shot_or_a_small_plan_falls_back_to_one_task(tmp_path, chair_plan, settings, monkeypatch):- monkeypatch.setenv("C3D_SCOPED_PARTS", "off")- track, ctx = _ctx(tmp_path, big_plan(), settings)- assert [t.label for t in track.baseline_tasks(ctx)] == ["baseline"]- monkeypatch.delenv("C3D_SCOPED_PARTS")- t2, c2 = _ctx(tmp_path / "ss", big_plan(), settings, agent_id="single-shot:fake:m")- assert [t.label for t in t2.baseline_tasks(c2)] == ["baseline"] # one envelope, no sessions- t3, c3 = _ctx(tmp_path / "small", chair_plan, settings)- assert [t.label for t in t3.baseline_tasks(c3)] == ["baseline"] # 5 parts: one session is fine--def test_phases_run_in_order_and_a_failed_phase_does_not_kill_the_round(tmp_path, chair_plan, settings):"""``run_generation_tasks`` is the only place that knows about phases."""from codeverse3d.tracks.generation import GenerationResult, GenerationTask@@ -162,18 +121,3 @@ def test_phases_run_in_order_and_a_failed_phase_does_not_kill_the_round(tmp_pathassert order.index("z") == 2 # phase 1 ran lastassert [r.label for r in out] == ["a", "b", "z"] # results keep the caller's orderassert [r.ok for r in out] == [True, False, True]---def test_the_depth_templates_render_with_strict_undefined(tmp_path, settings):- """StrictUndefined: a variable the template names and the track does not provide is a crash."""- from codeverse3d.prompts import render- from codeverse3d.tracks.prompting import base_prompt_context, scope_context-- track, ctx = _ctx(tmp_path, big_plan(), settings)- scope = track.scopes(ctx)[0]- part = render("tracks/generate_static_part.j2", **scope_context(ctx, scope, files=list(scope.files),- expected_files=list(scope.files)))- assert "Interfaces" in part and "DO NOT create or edit it" in part and scope.names[0] in part- entry = ctx.runtime.expected_files(ctx.plan)[:1]- asm = render("tracks/assemble_static.j2", **base_prompt_context(ctx, files=entry, expected_files=entry))- assert "you own placement, not geometry" in asm and "check_connectivity" in asmdiff --git a/harness/tests/orchestrator_tracks/test_generation_planner_repair.py b/harness/tests/orchestrator_tracks/test_generation_planner_repair.pyindex 4dbe71de..3e30a6b5 100644--- a/harness/tests/orchestrator_tracks/test_generation_planner_repair.py+++ b/harness/tests/orchestrator_tracks/test_generation_planner_repair.py@@ -22,15 +22,12 @@ from codeverse3d.tracks.generation import (write_files,)from codeverse3d.tracks.planner import (- PlanningError,- build_system_prompt,ensure_acceptance,plan,plan_example,)from codeverse3d.tracks.repair import (build_with_repair,- format_error_report,relevant_cookbook_section,)from tests.orchestrator_tracks.conftest import make_spec@@ -43,24 +40,10 @@ from tests.orchestrator_tracks.fakes import ()-# ----------------------------------------------------------------------------- envelope-def test_parse_multifile_blocks_and_fences():- text = """Here you go.-=== FILE: src/object.js ===-```js-export function build(THREE) { return new THREE.Group(); }-```-=== END FILE ===-=== FILE: ./src/parts/seat.js ===-export function buildSeat(THREE) {}-=== END FILE ===-"""- files = parse_multifile(text)- assert set(files) == {"src/object.js", "src/parts/seat.js"}- assert files["src/object.js"].startswith("export function build") and "```" not in files["src/object.js"]---def test_parse_multifile_single_fence_fallback_and_errors():+def test_parse_multifile_blocks_fences_fallback_and_errors():+ blocks = ("Here you go.\n=== FILE: src/object.js ===\n```js\nexport const A=1;\n```\n=== END FILE ===\n"+ "=== FILE: ./src/parts/seat.js ===\nexport const B=2;\n=== END FILE ===\n")+ assert parse_multifile(blocks) == {"src/object.js": "export const A=1;", "src/parts/seat.js": "export const B=2;"}assert parse_multifile("```python\nimport bpy\nprint(1)\n```", expected_files=["src/model.py"]) == {"src/model.py": "import bpy\nprint(1)"}hinted = "**src/env.js**\n```js\nexport const A=1;\n```\nand `src/scene.js`:\n```js\nexport const B=2;\n```"files = parse_multifile(hinted)@@ -157,32 +140,6 @@ def test_planner_validates_retries_and_writes(tmp_ws):assert "plan.invalid" in kinds and "plan.done" in kinds-def test_planner_validation_reasks_and_ceiling(tmp_ws):- model = FakeChatModel(lambda req: {"bad": 1})- with pytest.raises(PlanningError):- plan(make_spec(), "fake:planner", StaticPlan, tmp_ws, model=model)- from codeverse3d.tracks.planner import MAX_VALIDATION_REASKS-- assert len(model.requests) == 1 + MAX_VALIDATION_REASKS == 3-- answers = [{"object_name": "X"}, {"object_name": "Y"}, _valid_plan_dict()]- model = FakeChatModel(lambda req: answers.pop(0))- p = plan(make_spec(), "fake:planner", StaticPlan, tmp_ws, model=model)- assert p.object_name == "DiningChair" and len(model.requests) == 3- assert all("failed validation" in r.messages[-1].text for r in model.requests[1:])---def test_planner_scene_example_validates_and_prompts_render():- assert isinstance(ScenePlan.model_validate(plan_example(Track.SCENE)), ScenePlan)- spec = make_spec(Track.SCENE, Language.SCENE_THREEJS)- s = build_system_prompt(spec, ScenePlan)- assert "zones" in s and "Y is UP" in s- from codeverse3d.contracts.plan import ArticulatedPlan-- assert isinstance(ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT)), ArticulatedPlan)- assert "pivot" in build_system_prompt(make_spec(Track.ARTICULATED_OBJECT, Language.URDF_BLENDER), ArticulatedPlan)--def test_ensure_acceptance_is_idempotent():p = StaticPlan.model_validate(_valid_plan_dict())spec = make_spec()@@ -219,26 +176,6 @@ def _ctx(tmp_ws, settings, agent_id: str, agent=None, model=None, cookbook: strcontract_text="CONTRACT")-def test_build_with_repair_agent_path_escalates_on_same_error(tmp_ws, settings):- (tmp_ws.src / "model.py").write_text(f"import bpy\n# {FAIL_MARK}\nprint(1)\n")- tmp_ws.write_json(tmp_ws.plan_path, {"parts": []})- prompts = []-- def writer(job, ws):- prompts.append(job.prompt)- if len(prompts) == 1:- return {"src/model.py": f"import bpy\n# still {FAIL_MARK}\n"} # same error again- return {"src/model.py": "import bpy\nprint('fixed')\n"}-- ctx = _ctx(tmp_ws, settings, "fake:x", agent=FakeAgent(writer), cookbook="## Intro\nhello\n## RuntimeError boom\nuse boom fix snippet\n")- out = build_with_repair(ctx, round_index=0, label="r00")- assert out.ok and len(out.attempts) == 2- assert "BUILD FAILED" in prompts[0] and "src/model.py:3" in prompts[0] and "boom fix snippet" in prompts[0]- assert "SAME ERROR AS THE PREVIOUS ATTEMPT" in prompts[1] and "SAME ERROR" not in prompts[0]- kinds = [e["event"] for e in ctx.events.read()]- assert kinds.count("repair.attempt") == 2 and kinds.count("build.done") == 3--def test_build_with_repair_single_shot_sends_file_contents_and_stops_at_max(tmp_ws, settings):(tmp_ws.src / "model.py").write_text(f"import bpy\n# {FAIL_MARK}\n")tmp_ws.write_json(tmp_ws.plan_path, {"parts": []})@@ -256,8 +193,6 @@ def test_build_with_repair_single_shot_sends_file_contents_and_stops_at_max(tmp_assert out.usage.cost_usd == pytest.approx(0.004)--def test_repair_cookbook_sections_are_the_prompt_sections():"""Repair splits the cookbook with ``prompts.sections`` (its own ``^##+`` regex went,identical on all 7 shipped cookbooks): a ``## `` comment inside a fence is code, not@@ -278,16 +213,3 @@ def test_repair_rel_strips_a_prefix_not_a_character_set(tmp_ws):assert _rel(ctx, "./src/.env.js") == "src/.env.js"assert _rel(ctx, "src/parts/seat.js") == "src/parts/seat.js"assert _rel(ctx, "../outside.js") == "" and _rel(ctx, "/etc/passwd") == ""--def test_format_error_report_and_cookbook_section():- from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity-- b = BuildResult(ok=False, language="threejs", error_type="TypeError", error_message="Cannot read properties of null (reading 'fillStyle')",- error_file="src/parts/base.js", error_line=12, stderr_tail="\n".join(f"line{i}" for i in range(60)))- lint = GateReport(gate="lint:threejs", passed=False, findings=[GateFinding(gate="lint:threejs", severity=Severity.ERROR, target="src/parts/base.js",- message="document.createElement is forbidden", fix_hint="use vertex colours")])- cb = "## Materials\nuse MeshStandardMaterial\n## Canvas textures are not available\nfillStyle getContext canvas null properties → procedural colours\n"- rep = format_error_report(b, lint, cb)- assert "src/parts/base.js:12" in rep and "line59" in rep and "line5\n" not in rep.split("traceback")[1][:20]- assert "FIX: use vertex colours" in rep and "Canvas textures" in rep- assert relevant_cookbook_section(cb, "totally unrelated words") == ""diff --git a/harness/tests/orchestrator_tracks/test_graphics_recipes.py b/harness/tests/orchestrator_tracks/test_graphics_recipes.pyindex bcc7452b..24ded69b 100644--- a/harness/tests/orchestrator_tracks/test_graphics_recipes.py+++ b/harness/tests/orchestrator_tracks/test_graphics_recipes.py@@ -8,18 +8,15 @@ from types import SimpleNamespaceimport pytest-from codeverse3d.config import Settings, get_settings-from codeverse3d.contracts.common import HARNESS_OWNED_SRC, Language, Track+from codeverse3d.contracts.common import Language, Trackfrom codeverse3d.contracts.plan import GraphicsPlanfrom codeverse3d.languages import get_runtimefrom codeverse3d.languages.glsl_shader import (COMMON_GLSL,GlslShaderRuntime,compose,- first_error,lint_text,lint_workspace,- parse_glsl_log,write_skeleton,)from codeverse3d.languages.glsl_shader import HEADER as WRAP_HEADER@@ -27,15 +24,12 @@ from codeverse3d.proc import EventLogfrom codeverse3d.prompts import load_text, renderfrom codeverse3d.tracks.graphics import (HEADER,- NOT_SEEDED,RECIPES_REL,RESUME_HEADER,cookbook_functions,defined_names,graphics_prompt_context,is_skeleton_common,- parse_functions,- recipe_chapters,seed_recipes,seeded_on_disk,)@@ -43,7 +37,6 @@ from codeverse3d.tracks.planner import plan_examplefrom codeverse3d.workspace import WorkspaceAURORA = "Aurora borealis over a mountain ridge with a frozen lake, dense stars, green and violet curtains"-RAIN = "neon rain on glass"NOTHING = "a rotating rainbow gear wheel" # matches the Instancing chapter, which defines no functionUNMATCHED = "xyzzy plugh"AURORA_NAMES = ("curtain", "auroraCol", "aurora", "stars")@@ -88,56 +81,6 @@ def _default_on(monkeypatch) -> None:monkeypatch.delenv("C3D_SEED_RECIPES", raising=False)-# ----------------------------------------------------------------------------- extraction-def test_cookbook_functions_are_real_definitions_without_usage_lines() -> None:- known = cookbook_functions(load_text("glsl_shader/cookbook.md"))- for name in AURORA_NAMES + HELPERS + ("bokehSoft", "dropsLayer", "warped"):- assert name in known, name- assert "mainImage" not in known and "main" not in known- assert known["curtain"].signature == "float curtain(vec2 p, float t, float seed, out float k)"- assert {"fbm", "noise"} <= known["curtain"].calls and {"hash12", "hash22"} <= known["stars"].calls- assert "// ORGANIC CURTAIN" in known["curtain"].text and "Never a comb" in known["curtain"].text- for r in known.values():- assert "// usage:" not in r.text and "// e.g." not in r.text and r.text.count("{") == r.text.count("}"), r.name- # the stars doc comment (prose with a ';' inside) is kept, the usage line under it is not- assert "DENSE STARS" in known["stars"].text and "col += vec3(0.9, 0.95, 1.0)" not in known["stars"].text- assert "// sunset:" not in known["tonemapACES"].text and "// water colour" not in "".join(r.text for r in known.values())---def test_parse_functions_handles_one_liners_and_nested_braces() -> None:- code = "// doc\nfloat a(float x) { return x; }\n// usage: a(1.0);\nvec2 b(vec2 p) {\n for (int i = 0; i < 2; i++) { p = p * 2.0; }\n return p; // }\n}\nvoid mainImage(out vec4 f, in vec2 c) { f = vec4(a(1.0)); }\n"- got = parse_functions(code, "ch")- assert [r.name for r in got] == ["a", "b"] and got[0].text == "// doc\nfloat a(float x) { return x; }"- assert got[1].signature == "vec2 b(vec2 p)" and got[1].text.endswith("\n}") and got[1].calls == frozenset()- assert got[1].purpose == 'from the cookbook chapter "ch"'- assert defined_names(COMMON_GLSL) >= {"hash11", "hash12", "hash22", "noise", "fbm", "rot2", "palette", "tonemap", "PI", "TAU"}---def test_chapter_selection_excludes_always_on_and_templates(tmp_path) -> None:- ws = _ws(tmp_path)- titles = [s.title for s in recipe_chapters(_ctx(ws, AURORA))]- assert any(t.startswith("Light phenomena") for t in titles) and any(t.startswith("Gradient sky") for t in titles)- assert not any("Hash" in t or "Palettes" in t or "PITFALLS" in t for t in titles)- assert recipe_chapters(_ctx(ws, "a raymarched temple corridor with fog")) == [] and NOT_SEEDED == ("Raymarching",)- assert recipe_chapters(_ctx(ws, UNMATCHED)) == []-- # a chapter arrives whole or not at all — the budget never cuts one in half- from codeverse3d.prompts.sections import split_sections- from codeverse3d.tracks.prompting import select_cookbook_chapters-- ctx = _ctx(ws, AURORA)- whole = {s.title: s.body.rstrip() for s in split_sections(ctx.cookbook_text)}- for s in select_cookbook_chapters(ctx, AURORA, budget=6000):- assert s.body.rstrip() == whole[s.title], s.title- assert [s.title[:10] for s in recipe_chapters(_ctx(ws, NOTHING))] == ["Instancing"]---# ----------------------------------------------------------------------------- seeding-def test_the_file_is_the_harness_owned_recipes_glsl() -> None:- assert RECIPES_REL == "src/recipes.glsl" and HARNESS_OWNED_SRC[Language.GLSL_SHADER] == (RECIPES_REL,)- assert HEADER.startswith("// harness-owned:") and "READ-ONLY" in HEADER and "above src/common.glsl" in HEADER--def test_aurora_brief_seeds_recipes_and_helpers_exactly_once(tmp_path) -> None:ws = _ws(tmp_path, skeleton=False)ctx = _ctx(ws)@@ -203,24 +146,6 @@ 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_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 names- text = _recipes(ws).read_text()- assert "vec2 dropsLayer(vec2 uv, float t, float scale)" in text and "vec3 bokehSoft(vec2 p, float t)" in text-- ws = _ws(tmp_path / "plan")- plan = GraphicsPlan.model_validate({**plan_example(Track.GRAPHICS), "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 / "city")- names2 = seed_recipes(_ctx(ws2, "a city at night", plan=plan))- assert "curtain" in names2 and "bokehSoft" not in names2--def test_nothing_matches_nothing_seeded_no_file_no_block(tmp_path) -> None:ws = _ws(tmp_path)ctx = _ctx(ws, NOTHING)@@ -265,30 +190,6 @@ def test_resume_appends_only_new_names(tmp_path) -> None:assert _seeded_events(ws)[-1]["names"] == third and _seeded_events(ws)[-1]["trimmed"] == []-def test_gate_and_language(tmp_path, monkeypatch) -> None:- def seeding(raw: str | None) -> bool:- if raw is None:- monkeypatch.delenv("C3D_SEED_RECIPES", raising=False)- else:- monkeypatch.setenv("C3D_SEED_RECIPES", raw)- get_settings.cache_clear()- return get_settings().limits.seed_recipes-- ws = _ws(tmp_path)- assert seeding(None) is True- assert seeding("0") is False- ctx = _ctx(ws)- assert seed_recipes(ctx) == [] and not _recipes(ws).exists() and "seeded_recipes" not in ctx.extra- assert (ws.src / "common.glsl").read_text() == COMMON_GLSL and not _seeded_events(ws)- assert seeding("garbage") is True # a typo keeps the default: never a crash, never the arm- assert seeding("on") is True and seeding("off") is False- assert seeding(None) is True- assert seed_recipes(_ctx(ws, language=Language.OPENGL_PYTHON)) == [] # opengl_python: nothing seeded- assert not _recipes(ws).exists() and (ws.src / "common.glsl").read_text() == COMMON_GLSL- monkeypatch.setenv("C3D_LIMITS__SEED_RECIPES", "off")- assert Settings().limits.seed_recipes is False # the nested spelling reads the same field--# ----------------------------------------------------------------------------- compose / lint / promptdef _gl_or_skip(tmp_path: Path, src: str, **kw):pytest.importorskip("moderngl")@@ -334,49 +235,6 @@ def test_recipes_compose_above_common_and_the_seeded_aurora_renders(tmp_path) ->assert all(v > 0.0 for v in lum), lum-def test_a_compile_error_inside_recipes_is_reported_at_its_recipes_line(tmp_path) -> None:- recipes = "// harness-owned: verified cookbook recipes ...\nfloat ok(float x) { return x; }\n\nfloat bad(float x) { return x + ; }\n"- common = "float mine(float x) { return x; }\n"- comp = compose(SHADER, common, recipes_src=recipes)- header_lines = WRAP_HEADER.count("\n")- composed_line = header_lines + 4 # `bad` is recipes.glsl line 4- assert comp.source.splitlines()[composed_line - 1].startswith("float bad(")- for log in (f"0:{composed_line}(32): error: syntax error, unexpected ';'", # Mesa- f"0({composed_line}) : error C0000: syntax error, unexpected ';'", # NVIDIA- f"ERROR: 0:{composed_line}: ';' : syntax error"): # ANGLE / ES- first = first_error(parse_glsl_log(log, comp.line_map))- assert first is not None and (first.file, first.file_line) == ("src/recipes.glsl", 4), log- assert first.text().startswith("src/recipes.glsl:4: error:")- # and common.glsl / shader.frag lines still map to themselves, shifted by the recipes block- assert comp.line_map.locate(header_lines + 5) == ("src/common.glsl", 1)- assert comp.line_map.locate(header_lines + 6) == ("src/shader.frag", 1)- # the real compiler, when there is one: the build names src/recipes.glsl:4- res = _gl_or_skip(tmp_path, comp.source, width=32, height=18, times=(0.0,))- assert not res.ok and res.stage == "compile"- first = first_error(parse_glsl_log(res.error_message, comp.line_map))- assert first is not None and (first.file, first.file_line) == ("src/recipes.glsl", 4), res.error_message---def test_lint_flags_a_redefinition_of_a_seeded_recipe(tmp_path) -> None:- recipes = "float curtain(vec2 p, float t, float seed, out float k) { k = 0.0; return 0.0; }\nvec3 aurora(vec2 p, float t) { return vec3(0.0); }\n"- shader = "// mine\nfloat curtain(vec2 p, float t, float seed, out float k) { k = 1.0; return 1.0; }\n" + SHADER- common = "float hash12(vec2 p) { return 0.0; }\n\nvec3 aurora(vec2 p, float t) { return vec3(1.0); }\n"- found = [f for f in lint_text(shader, common, recipes_src=recipes) if f.data["kind"] == "redefines_recipe"]- assert [(f.data["file"], f.data["line"]) for f in found] == [("src/shader.frag", 2), ("src/common.glsl", 3)]- assert found[0].message == "src/shader.frag:2: `curtain` is already provided by src/recipes.glsl — call it instead of redefining it"- assert found[1].message.endswith("`aurora` is already provided by src/recipes.glsl — call it instead of redefining it")- assert all(f.severity.value == "error" for f in found) and "harness-owned" in found[0].fix_hint- assert not [f for f in lint_text(shader, common) if f.data["kind"] == "redefines_recipe"] # no recipes: no rule- # the workspace lint reads recipes.glsl itself (and does not call it a stray file); buffer_a is checked too- ws = _ws(tmp_path, skeleton=False)- (ws.src / "shader.frag").write_text(SHADER)- (ws.src / "buffer_a.frag").write_text("vec3 aurora(vec2 p, float t) { return vec3(0.0); }\n" + SHADER)- _recipes(ws).write_text(recipes)- rep = lint_workspace(ws)- assert not rep.passed and [f.data["file"] for f in rep.findings if f.data["kind"] == "redefines_recipe"] == ["src/buffer_a.frag"]- assert not any(f.data["kind"] == "stray_file" for f in rep.findings)--def test_prompt_block_lists_the_seeded_names(tmp_path) -> None:ws = _ws(tmp_path)ctx = _ctx(ws, plan=GraphicsPlan.model_validate({**plan_example(Track.GRAPHICS), "key_visuals": ["green aurora curtains", "dense stars"]}))@@ -398,9 +256,6 @@ def test_prompt_block_lists_the_seeded_names(tmp_path) -> None:def test_a_single_shot_repair_never_inlines_the_harness_owned_recipes(tmp_path) -> None:- """``repair.files_for_repair`` re-implemented ``prompting.current_files`` without its- harness-owned rule, so a build error naming src/recipes.glsl pasted the read-only- file into the single-shot repair prompt as a failing file to rewrite."""from codeverse3d.contracts.artifacts import BuildResult, GateReportfrom codeverse3d.tracks.repair import files_for_repairdiff --git a/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py b/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.pyindex ac1cec27..5c431f6e 100644--- a/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py+++ b/harness/tests/orchestrator_tracks/test_harness_failure_no_repair.py@@ -1,15 +1,4 @@-"""A build that failed IN THE HARNESS never becomes an agent repair.--Measured 2026-09-05 on `bench/out/scene_textures` (japanese_garden): the scene probe-returned no summary line — a dropped stdout tail, which `probes.probe_report` already-labels "scene probe produced no result (driver output lost)" with-`harness_failure: True` and the hint "this is a harness/driver failure, not your code".-`build_with_repair` never read that flag, so the round spent all three repair attempts on-it: the agent rewrote 5 files, then **14** (env.js and every zone), then 3, and the-fourth build passed on its own. The 14-file rewrite deleted the texture use the arm-existed to measure — the cell scored 0.496 where the same prompt scored 0.636 without the-detour.-"""+"""A build that failed IN THE HARNESS is rebuilt, never handed to the agent as a repair."""from __future__ import annotations@@ -51,31 +40,8 @@ def no_generate(monkeypatch):@pytest.mark.parametrize("repair_budget", [3, 0])-def test_a_harness_failure_is_rebuilt_not_repaired(monkeypatch, no_generate, repair_budget):- """The build is simply re-run — no model call — and a rebuild that succeeds ends it.- The rebuilds are bounded by MAX_HARNESS_REBUILDS, not by the repair budget: a baseline- arm that runs with max_repair_attempts=0 must still get its retries, or a dropped stdout- tail costs it the whole round."""- seq = [(_build(ok=False, harness=True, msg="scene probe produced no result (driver output lost)"),- GateReport(gate="lint", passed=True, findings=[])),- (_build(ok=True), GateReport(gate="lint", passed=True, findings=[]))]- calls = {"n": 0}-- def fake_build_once(ctx):- calls["n"] += 1- return seq[min(calls["n"] - 1, len(seq) - 1)]-- monkeypatch.setattr(R, "build_once", fake_build_once)- ctx = _ctx(spec=SimpleNamespace(budget=SimpleNamespace(max_repair_attempts=repair_budget)))- out = R.build_with_repair(ctx, round_index=0, label="r00")- assert out.ok is True- assert calls["n"] == 2, "one rebuild, no repair"- assert out.attempts == [], "no agent attempt was spent"---def test_a_harness_failure_that_persists_gives_up_without_a_repair(monkeypatch, no_generate):- """Bounded: the driver already retries once itself, so a failure that survives- MAX_HARNESS_REBUILDS is not transient and is not the agent's to fix either."""+def test_a_harness_failure_that_persists_gives_up_without_a_repair(monkeypatch, no_generate, repair_budget):+ """Bounded by MAX_HARNESS_REBUILDS, not by the repair budget (a max_repair_attempts=0 arm still rebuilds)."""stuck = (_build(ok=False, harness=True), GateReport(gate="lint", passed=True, findings=[]))calls = {"n": 0}@@ -84,37 +50,13 @@ def test_a_harness_failure_that_persists_gives_up_without_a_repair(monkeypatch,return stuckmonkeypatch.setattr(R, "build_once", fake_build_once)- out = R.build_with_repair(_ctx(), round_index=0, label="r00")+ ctx = _ctx(spec=SimpleNamespace(budget=SimpleNamespace(max_repair_attempts=repair_budget)))+ out = R.build_with_repair(ctx, round_index=0, label="r00")assert out.ok is Falseassert calls["n"] == 1 + R.MAX_HARNESS_REBUILDSassert out.attempts == []-def test_a_real_build_failure_is_still_repaired(monkeypatch):- """The control: an ordinary failure still reaches the agent, as it always did."""- seen: list[int] = []-- from codeverse3d.contracts.common import Usage-- def fake_generate(ws, **kw):- seen.append(1)- return SimpleNamespace(ok=True, files_changed=[], usage=Usage(), notes="", storm=False, transient=False)-- monkeypatch.setattr(C, "generate", fake_generate)- monkeypatch.setattr(R, "make_repair_task", lambda *a, **k: SimpleNamespace(label="t"))- seq = [(_build(ok=False, msg="TypeError: x is not a function"), GateReport(gate="lint", passed=True, findings=[])),- (_build(ok=True), GateReport(gate="lint", passed=True, findings=[]))]- calls = {"n": 0}-- def fake_build_once(ctx):- calls["n"] += 1- return seq[min(calls["n"] - 1, len(seq) - 1)]-- monkeypatch.setattr(R, "build_once", fake_build_once)- out = R.build_with_repair(_ctx(), round_index=0, label="r00")- assert out.ok is True and len(seen) == 1, "a real error still gets one repair"--def test_a_repair_session_that_died_in_the_storm_ends_the_loop(monkeypatch):"""D68: a repair session that timed out in a 503 streak (partial or no files) is built onceand the loop stops — the next attempt would spend its whole window at the same wall."""diff --git a/harness/tests/orchestrator_tracks/test_integrations2.py b/harness/tests/orchestrator_tracks/test_integrations2.pyindex dd18b55c..11f31ecb 100644--- a/harness/tests/orchestrator_tracks/test_integrations2.py+++ b/harness/tests/orchestrator_tracks/test_integrations2.py@@ -1,15 +1,10 @@-"""Integration wiring from the other packages into the tracks (fix batch 2):-clay geometry views for the judge, scene frame gate + judge view selection,-connectivity language, blender multi-file targets, texture hook."""+"""Integration wiring into the tracks: runtime file layout, no texture pass inside a run."""from __future__ import annotationsfrom codeverse3d.contracts.common import Language, Trackfrom codeverse3d.contracts.plan import ScenePlan-from codeverse3d.tracks import get_track-from codeverse3d.tracks.graphics import GraphicsTrackfrom codeverse3d.tracks.planner import plan_example-from codeverse3d.tracks.scene import SceneTrackfrom codeverse3d.tracks.static_object import StaticObjectTrackfrom codeverse3d.workspace import Workspacefrom tests.orchestrator_tracks.conftest import make_spec@@ -20,7 +15,7 @@ from tests.orchestrator_tracks.fakes import (FakeServices,_planner,)-from tests.orchestrator_tracks.test_tracks import _agent_writer, _scene_writer+from tests.orchestrator_tracks.test_tracks import _agent_writerdef _static_run(tmp_path, chair_plan, settings, **spec_kw):@@ -35,49 +30,8 @@ def _static_run(tmp_path, chair_plan, settings, **spec_kw):return rec, ws, judge, services-# --------------------------------------------------------------------- (b) clay geometry views reach the judge-def test_object_judge_receives_clay_geometry_views(tmp_path, chair_plan, settings):- rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings)- inp = judge.calls[0]- assert inp.geometry_views is not None and len(inp.geometry_views.views) == 4- assert {v.name for v in inp.geometry_views.views} == {"front_right_34", "back_left_34", "top", "low_front_left"}- assert all(v.mode == "clay" for v in inp.geometry_views.views)- assert services.geometry_renders # rendered from the round's GLB- assert (ws.renders_dir(0) / "clay").is_dir()---def test_scene_judge_gets_no_geometry_views(tmp_path, settings):- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- plan.assets = [a for a in plan.assets if a.kind == "threejs"]- for z in plan.zones:- z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]- spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0)- ws = Workspace(tmp_path / "runs" / "scene")- judge = FakeJudge(scores=(0.6,))- services = FakeServices(assemble=True)- track = SceneTrack(services=services, judge=judge, agent=FakeAgent(_scene_writer),- planner_model=_planner(plan.model_dump(mode="json")), settings=settings,- runtime=FakeRuntime(Language.SCENE_THREEJS))- rec = track.run(spec, ws)- assert judge.calls and judge.calls[0].geometry_views is None- # (a) the scene_frames gate ran (passing empty report without metrics.json)- frames = [g for g in rec.rounds[0].gates if g.gate == "scene_frames"]- assert len(frames) == 1 and frames[0].passed- assert services.geometry_renders == []---# --------------------------------------------------------------------- (d) connectivity hints in the author's frame-def test_connectivity_gate_receives_spec_language(tmp_path, chair_plan, settings):- rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings)- assert services.connectivity_languages == ["threejs"]--# --------------------------------------------------------------------- (e) every runtime states its file layoutdef test_each_runtime_states_which_file_owns_what(chair_plan):- """The runtime owns the file layout its skeleton writes; the tracks ask it (``expected_files`` /- ``files_for``) instead of restating it — they did in four places, and the scene copy sent a- refine aimed at a GLB hero into ``src/assets/<hero>.js``, a module nothing imports."""- from codeverse3d.contracts.plan import ScenePlanfrom codeverse3d.languages import get_runtimeper_part = {Language.BLENDER: ("src/model.py", ".py"), Language.THREEJS: ("src/object.js", ".js")}@@ -104,8 +58,7 @@ def test_each_runtime_states_which_file_owns_what(chair_plan):# --------------------------------------------------------------------- (f) no texture pass in the rundef test_the_run_itself_never_textures_even_when_asked(tmp_path, chair_plan, settings, monkeypatch):- """The texture pass belongs to the hand-over of the PICKED round (addons/select.package,- `3dcode make` after the run), not to finalise (2026-09-22)."""+ """The texture pass belongs to the hand-over of the PICKED round, not to finalise."""import codeverse3d.texturing.run as trundef boom(*a, **kw):@@ -115,10 +68,3 @@ def test_the_run_itself_never_textures_even_when_asked(tmp_path, chair_plan, setfor tags in ([], ["texture"]):rec, ws, judge, services = _static_run(tmp_path / (tags[0] if tags else "plain"), chair_plan, settings, tags=tags)assert "texturing" not in rec.extra---# --------------------------------------------------------------------- (i) graphics track still constructs through get_track-def test_get_track_graphics_accepts_options(settings):- t = get_track("graphics", settings=settings, n_candidates=2)- assert isinstance(t, GraphicsTrack) and t._n_candidates == 2- assert isinstance(get_track(Track.GRAPHICS), GraphicsTrack)diff --git a/harness/tests/orchestrator_tracks/test_one_world_session.py b/harness/tests/orchestrator_tracks/test_one_world_session.pyindex 4be612a9..65019099 100644--- a/harness/tests/orchestrator_tracks/test_one_world_session.py+++ b/harness/tests/orchestrator_tracks/test_one_world_session.py@@ -1,10 +1,4 @@-"""D70: one author for the whole world — every zone goes to ONE session whose window-scales with the zone count (2026-09-08; the fan-out control arm was removed 2026-09-21).--Measured under one fixed judge with codex:gpt-6-astra@low on both sides: a bare one-file-scene scored 0.894 (clockmaker) and 0.82 (boat) while the harness's round 0, its zones-written by separate sessions of at most two small zones, sat at 0.17 and 0.30-0.57.-"""+"""D70: every zone goes to ONE session whose window scales with the zone count."""from __future__ import annotationsfrom codeverse3d.contracts.common import Language, Trackdiff --git a/harness/tests/orchestrator_tracks/test_orchestrator.py b/harness/tests/orchestrator_tracks/test_orchestrator.pyindex 0b2b1069..94ee53c2 100644--- a/harness/tests/orchestrator_tracks/test_orchestrator.py+++ b/harness/tests/orchestrator_tracks/test_orchestrator.py@@ -5,7 +5,6 @@ from __future__ import annotationsimport jsonimport time-import pytestfrom pydantic import BaseModelfrom codeverse3d.contracts.artifacts import (@@ -22,7 +21,6 @@ from codeverse3d.orchestrator import (RunState,StageRunner,build_refine_instructions,- hash_inputs,plan_parallel_groups,)from codeverse3d.proc import EventLog, fan_out@@ -41,19 +39,8 @@ def test_fan_out_preserves_order_and_captures_exceptions():assert fan_out([], fn, 2) == []-# ----------------------------------------------------------------------------- state + runner-def test_run_state_roundtrip(tmp_ws):- st = RunState(status=RunStatus.REFINING, materialized_for="gemini-cli")- st.save(tmp_ws)- again = RunState.load(tmp_ws)- assert again is not None and again.status is RunStatus.REFINING and again.materialized_for == "gemini-cli"- assert RunState.load_or_new(tmp_ws, resume=False).status is RunStatus.PLANNING--def test_a_run_state_saved_before_2026_09_22_still_loads(tmp_ws):- """It named a best round, cached the round journal and could end ``passed`` / ``plateau``:- the keys are ignored and the status reads as ``stopped`` — a resume goes on from the- journal's last round."""+ """Its best-round and journal keys are ignored and ``passed`` / ``plateau`` read as ``stopped``."""tmp_ws.state_path.write_text(json.dumps({"status": "passed", "stop_reason": "pass", "current_round": 2, "completed_rounds": [0, 1],"round_commits": {"0": "a0", "1": "a1"}, "best_round": 0, "best_commit": "a0", "best_score": 0.81,@@ -65,35 +52,8 @@ def test_a_run_state_saved_before_2026_09_22_still_loads(tmp_ws):assert RunStatus("plateau") is RunStatus.STOPPED-def test_stage_runner_caches_by_input_hash(tmp_ws):- events = EventLog(tmp_ws.events_path)- runner = StageRunner(tmp_ws, events)- calls = []-- def fn():- calls.append(1)- return {"x": 1}-- assert runner.stage("s1", fn, inputs={"a": 1}) == {"x": 1}- assert runner.stage("s1", fn, inputs={"a": 1}) == {"x": 1}- assert len(calls) == 1- assert runner.stage("s1", fn, inputs={"a": 2}) == {"x": 1}- assert len(calls) == 2- kinds = [e["event"] for e in events.read()]- assert kinds.count("stage.cached") == 1 and kinds.count("stage.done") == 2- # resume from disk with a fresh runner + state- st = RunState.load(tmp_ws)- r2 = StageRunner(tmp_ws, events, st)- assert r2.stage("s1", fn, inputs={"a": 2}) == {"x": 1} and len(calls) == 2- assert runner.result_path("a:b/c").name == "a_b_c.json"--def test_an_unreadable_cached_stage_is_a_miss_not_a_dead_run(tmp_ws):- """RS-2: inputs_hash covers the INPUTS, never the result model's schema. A cached- result that no longer validates (the contract gained a field) or no longer parses- (a clobbered file) used to escape as ValidationError / JSONDecodeError, which- BaseTrack.run turns into a FAILED run — so every later `3dcode resume` died the same- way. Both must re-run the stage and overwrite the file."""+ """A cached result that no longer validates or parses re-runs the stage instead of failing the run."""class PlanV1(BaseModel):name: str@@ -123,18 +83,6 @@ def test_an_unreadable_cached_stage_is_a_miss_not_a_dead_run(tmp_ws):assert [e["event"] for e in events.read()].count("stage.cache_invalid") == 2-def test_stage_runner_raises_and_records_nothing(tmp_ws):- runner = StageRunner(tmp_ws, EventLog(tmp_ws.events_path))-- def boom():- raise RuntimeError("nope")-- with pytest.raises(RuntimeError):- runner.stage("bad", boom, inputs="y")- assert "bad" not in runner.state.stages- assert hash_inputs({"a": [1, 2]}) == hash_inputs({"a": (1, 2)})--# ----------------------------------------------------------------------------- refine instructionsdef test_build_refine_instructions_merges_and_groups(chair_plan):judgment = Judgment(rubric="r", scores={}, overall=0.6, passed=False, improvement_plan=[diff --git a/harness/tests/orchestrator_tracks/test_plan_features.py b/harness/tests/orchestrator_tracks/test_plan_features.pyindex 341ac7f9..68e3ff25 100644--- a/harness/tests/orchestrator_tracks/test_plan_features.py+++ b/harness/tests/orchestrator_tracks/test_plan_features.py@@ -1,8 +1,4 @@-"""``tracks/plan_features.py``: what an A/B rig may assume about a ``C3D_*`` switch (CQ-5).--Which names are live is derived from ``Settings`` — every switch the harness reads is a-field there — so no list can drift from the code and no test has to grep the tree.-"""+"""``tracks/plan_features.py``: what an A/B rig may assume about a ``C3D_*`` switch."""from __future__ import annotations@@ -16,10 +12,6 @@ from codeverse3d.tracks.plan_features import (def test_every_settings_field_is_a_live_switch_and_anything_else_is_dead():- """An arm that differs only by a name nothing reads is byte-identical to its control- (one A/B printed "keep, mean delta +0.344" for two such arms), so ab_plan refuses it.- Every field, nested field, flat spelling and node-side name is live; the retired ones- are dead the moment their field goes."""live = [f"C3D_{name.upper()}" for name in Settings.model_fields]live += [f"C3D_{section.upper()}__{name.upper()}" for section in ("rate", "render", "limits", "judge")for name in Settings.model_fields[section].annotation.model_fields]@@ -31,29 +23,12 @@ def test_every_settings_field_is_a_live_switch_and_anything_else_is_dead():assert dead_env_keys({"GEMINI_CLI_HOME": "/x"}) == [], "outside the C3D_ family nothing is judged dead"-# --------------------------------------------------------------------- pin-plan safety-def test_a_generation_side_switch_may_share_one_plan():- """A switch that acts after planning cannot change the plan, so both arms can be- seeded with the same plan.json and the paired delta stops carrying the planner's- spread — the dominant variance term (eval/docs/EVAL.md §8.1)."""+def test_pin_plan_refuses_only_live_switches_not_known_to_act_after_planning():+ assert pin_plan_blockers({}) == []for name in sorted(GENERATION_SIDE_ENV):assert pin_plan_blockers({name: "1"}) == [], name- assert pin_plan_blockers({}) == []---def test_a_dead_switch_blocks_nothing_but_a_live_neighbour_still_does():- """No code reads C3D_PLAN_FEATURES, so it cannot change a plan: it never blocks- --pin-plan (until 2026-09-22 its six never-implemented feature names did)."""- assert pin_plan_blockers({"C3D_PLAN_FEATURES": "fit"}) == []+ assert pin_plan_blockers({"C3D_PLAN_FEATURES": "fit"}) == [], "a dead switch cannot change a plan"assert pin_plan_blockers({"C3D_PLAN_FEATURES": "all", "C3D_PLAN_BRIEF": "off"}) == ["C3D_PLAN_BRIEF is not known to act after planning"]---def test_an_unclassified_switch_defaults_to_refusing():- """Refusing to pin costs one noisy A/B; pinning wrongly costs a confident wrong- answer. So anything live that is not known to act after planning refuses — a- plan-side field, or a variable some CLI may read."""- assert pin_plan_blockers({"C3D_PLAN_BRIEF": "off"}) == [- "C3D_PLAN_BRIEF is not known to act after planning"]assert pin_plan_blockers({"GEMINI_CLI_HOME": "/x"}) == ["GEMINI_CLI_HOME is not known to act after planning"]diff --git a/harness/tests/orchestrator_tracks/test_planner_depth.py b/harness/tests/orchestrator_tracks/test_planner_depth.pyindex 26db5314..493e8dac 100644--- a/harness/tests/orchestrator_tracks/test_planner_depth.py+++ b/harness/tests/orchestrator_tracks/test_planner_depth.py@@ -121,17 +121,6 @@ def test_plan_budget_contracts():assert "PLAN BUDGET" in text and "10 checklist items" in text-def test_the_scene_track_gets_no_part_budget():- from codeverse3d.contracts.plan import ScenePlan-- spec = _spec(must=10, track=Track.SCENE, language=Language.SCENE_THREEJS)- assert "PLAN BUDGET" not in build_user_prompt(spec)- scene = ScenePlan(title="T", summary="s", setting="x", bounds=_bbox(), environment="e",- zones=[{"name": "Z", "description": "d", "bbox": _bbox()}],- cameras=[{"name": "C", "position": (1, 1, 1), "look_at": (0, 0, 0)}])- assert B.plan_quality_complaint(scene, B.plan_budget(spec)) == ""--def test_plan_templates_render_the_budget_numbers():for track, language, model in ((Track.STATIC_OBJECT, Language.BLENDER, StaticPlan),(Track.GRAPHICS, Language.GLSL_SHADER, GraphicsPlan)):@@ -207,43 +196,8 @@ def test_brief_is_cached_by_prompt_hash_and_the_second_call_is_free(tmp_path):assert calls["n"] == 2-def test_the_brief_cache_follows_the_config_files_cache_dir(tmp_path, monkeypatch):- """``brief_cache_dir()`` read only $C3D_CACHE_DIR, so a ``cache_dir:`` set in- 3dcodeverse.yaml moved every cache but this one — the briefs stayed in ~/.cache."""- from codeverse3d.config import get_settings-- for env in ("C3D_CACHE_DIR", "CV3D_CACHE_DIR"):- monkeypatch.delenv(env, raising=False)- monkeypatch.chdir(tmp_path)- (tmp_path / "3dcodeverse.yaml").write_text(f"cache_dir: {tmp_path / 'cfg-cache'}\n")- get_settings.cache_clear()- assert BR.brief_cache_dir() == tmp_path / "cfg-cache" / "briefs"---def test_reference_images_are_part_of_the_brief_cache_key(tmp_path):- """RS-4: expand_brief attaches spec.references and tells the model to read the- dimensions off them, so a key that omits them let an --image run silently- reuse a brief generated WITHOUT the image (and vice versa)."""- img = tmp_path / "ref.png"- img.write_bytes(b"\x89PNG\r\n\x1a\n-first-")- plain = _spec()- withref = plain.model_copy(update={"references": [ReferenceImage(path=str(img))]})-- assert BR.brief_cache_key(plain, "m") != BR.brief_cache_key(withref, "m")-- # --reference synthesises a NEW image per run under identical spec fields:- # the path alone does not separate the two runs, the bytes must.- before = BR.brief_cache_key(withref, "m")- img.write_bytes(b"\x89PNG\r\n\x1a\n-second-")- assert BR.brief_cache_key(withref, "m") != before-- # ... and the role/note that go into the image label matter too- other = plain.model_copy(update={"references": [ReferenceImage(path=str(img), role="style")]})- assert BR.brief_cache_key(other, "m") != BR.brief_cache_key(withref, "m")--def test_an_image_run_does_not_drink_the_no_image_brief(tmp_path):- """The end-to-end shape of RS-4: two expand_brief calls, one model call each."""+ """RS-4: the reference images are part of the brief cache key."""cache = tmp_path / "cache"img = tmp_path / "ref.png"img.write_bytes(b"\x89PNG\r\n\x1a\n-bytes-")@@ -272,42 +226,10 @@ def test_an_unreadable_reference_never_collapses_onto_no_references(tmp_path):(ModelError("bad json", usage=Usage(backend="fake", cost_usd=0.002)), 0.002),])def test_a_failed_brief_is_never_fatal_and_keeps_what_the_provider_billed(tmp_path, error, billed):- """expand_brief goes through ``ask_structured``: a ModelError's ``usage`` (a billed- bad reply) is returned, where the hand-built call reported the failure as free."""brief, usage = BR.expand_brief(_spec(), "fake:planner", model=FakeChatModel([error]), cache_dir=tmp_path)assert brief is None and usage.cost_usd == pytest.approx(billed)-def test_brief_switch_and_track_scope(monkeypatch, switch):- switch("C3D_PLAN_BRIEF", None)- assert BR.brief_enabled(_spec())- assert not BR.brief_enabled(_spec(track=Track.GRAPHICS, language=Language.GLSL_SHADER))- switch("C3D_PLAN_BRIEF", "off")- assert not BR.brief_enabled(_spec())- switch("C3D_PLAN_BRIEF", "on")- assert BR.brief_enabled(_spec())---# ----------------------------------------------------------------------------- enrichment-def test_the_plan_keeps_subparts_typed_and_does_not_duplicate_them_into_the_description():- """Depth is rendered from the typed fields by ``tracks/prompting.py``; enrichment must- not copy it into ``description`` as well or the generation prompt prints it twice."""- from codeverse3d.tracks.prompting import part_details-- part = _part("GrindHead", desc="cast iron housing", children=[- SubPartPlan(name="Burr", description="conical burr, 24 flutes", bbox=_bbox(ex=0.4, ey=0.4, ez=0.4),- material="hardened steel"),- SubPartPlan(name="Nut", description="knurled nut", bbox=_bbox(cz=0.4, ex=0.2, ey=0.2, ez=0.1), instances=2),- ])- part.detail_hint = "carries the visible mechanism"- plan = _plan([part])- B.enrich_plan(plan, None)- assert plan.parts[0].description == "cast iron housing"- rendered = part_details(plan)- assert rendered.count("Burr") == 1 and rendered.count("carries the visible mechanism") == 1- assert "hardened steel" in rendered and "Nut** ×2" in rendered--def test_enrichment_adds_signature_features_as_SHOULD_items_only():plan = _plan([_part("P0")])B.enrich_plan(plan, _brief())@@ -317,8 +239,7 @@ def test_enrichment_adds_signature_features_as_SHOULD_items_only():def test_graphics_pass_elements_are_folded_into_the_one_markdown_row_that_renders_them():- """``graphics_steps.passes_table`` prints only ``description`` — and it is a markdown- table row, so the fold must be single-line and idempotent."""+ """The fold into the passes table row is single-line and idempotent."""from codeverse3d.contracts.plan import PassPlanfrom codeverse3d.tracks.graphics import passes_table@@ -335,15 +256,6 @@ def test_graphics_pass_elements_are_folded_into_the_one_markdown_row_that_renderassert row.count("|") == 4 and "integer tooth ratios" in row-# ----------------------------------------------------------------------------- output room-def test_plan_output_room_grows_with_the_plan_and_is_capped():- from codeverse3d.tracks.planner import PLAN_TOKENS_MAX, plan_tokens-- small, big = B.plan_budget(_spec(must=0)), B.plan_budget(_spec(must=20))- assert 24000 < plan_tokens(small, 24000) < plan_tokens(big, 24000) <= PLAN_TOKENS_MAX- assert plan_tokens(small, 24000) >= 24000 # never below the caller's floor--def test_truncated_plans_keep_growing_output_room(tmp_path, switch):switch("C3D_PLAN_BRIEF", "off")from codeverse3d.models.base import ModelErrordiff --git a/harness/tests/orchestrator_tracks/test_planner_reask.py b/harness/tests/orchestrator_tracks/test_planner_reask.pyindex 466bf0cb..70025233 100644--- a/harness/tests/orchestrator_tracks/test_planner_reask.py+++ b/harness/tests/orchestrator_tracks/test_planner_reask.py@@ -1,5 +1,4 @@-"""Articulated planner paths that outlived the plan-time geometry re-ask (D49, code removed-2026-09-21): the articulation acceptance items and the validation re-ask's wording."""+"""Articulated planner: the articulation acceptance items and the validation re-ask's wording."""from __future__ import annotations@@ -48,9 +47,6 @@ def test_every_moving_joint_gets_an_articulation_acceptance_item(tmp_ws):def test_validation_reask_names_the_missing_parts_when_the_plan_is_thin(tmp_ws):- """A thin plan whose joints stay INSIDE the part list: the in-context re-ask still owns- it (a plan that also references links it never lists is a restart — see- test_planner_restart.py, which measured that editing that one in context reproduces it)."""thin = _good()thin["parts"] = thin["parts"][:1] # only the cabinet ...thin["joints"] = [] # ... and no joint references the dropped linkdiff --git a/harness/tests/orchestrator_tracks/test_planner_restart.py b/harness/tests/orchestrator_tracks/test_planner_restart.pyindex f0c0ed6a..e9faa527 100644--- a/harness/tests/orchestrator_tracks/test_planner_restart.py+++ b/harness/tests/orchestrator_tracks/test_planner_restart.py@@ -1,8 +1,4 @@-"""A degenerate plan is re-sampled from the original prompt, not edited in context.--Measured 2026-09-02 over 200 plan calls on two trees: 3-4 % of articulated plan calls end-in `PlanningError`, always the same way — one top-level part, joints naming links the plan-never lists — and both in-context re-asks come back with that same answer."""+"""A degenerate plan (one part, dangling links) is re-sampled from the original prompt, not edited in context."""from __future__ import annotations@@ -11,7 +7,6 @@ import jsonimport pytest-from codeverse3d.config import get_settingsfrom codeverse3d.contracts.common import Language, Trackfrom codeverse3d.contracts.plan import ArticulatedPlanfrom codeverse3d.proc import EventLog@@ -73,28 +68,8 @@ def test_a_degenerate_plan_is_resampled_without_its_own_answer_in_context(tmp_wsassert [e for e in events.read() if e["event"] == "plan.done"][0]["restarts"] == 1-def test_an_ordinary_validation_error_still_edits_in_context(tmp_ws):- """Nothing changes for the failures a re-ask does fix: the model sees its own answer."""- bad = _good()- bad["joints"][0]["axis"] = [0, 0, 0] # a real slip, not a degenerate plan- p, model = _run(tmp_ws, [bad, _good()])- assert isinstance(p, ArticulatedPlan) and len(model.requests) == 2- assert len(model.requests[1].messages) == 3 # user + echoed answer + complaint- assert "failed validation" in model.requests[1].messages[-1].text---def test_the_kill_switch_restores_the_in_context_reask(tmp_ws, monkeypatch):- monkeypatch.setattr(get_settings(), "plan_restart", False) # C3D_PLAN_RESTART=off- p, model = _run(tmp_ws, [_degenerate(), _good()])- assert isinstance(p, ArticulatedPlan) and len(model.requests[1].messages) == 3--def test_a_restart_costs_an_attempt_not_one_of_the_two_reask_slots(tmp_ws):- """Every answer degenerate: restart once, then still get BOTH in-context re-asks.-- The restart used to increment the same counter as a re-ask, so a run that restarted- had one re-ask left instead of two — visible in the recorded battery as deaths with- ``restarts=1`` at the validation cap (bench/data/plan_stage/restart_on.jsonl)."""+ """Every answer degenerate: restart once, then still get BOTH in-context re-asks."""model = FakeChatModel(lambda req: _degenerate())with pytest.raises(PlanningError):plan(_spec(), "fake:planner", ArticulatedPlan, tmp_ws, model=model)@@ -105,9 +80,7 @@ def test_a_restart_costs_an_attempt_not_one_of_the_two_reask_slots(tmp_ws):def test_a_full_plan_with_one_dangling_link_is_edited_in_context_not_resampled(tmp_ws):- """The restart's trigger is the MEASURED class: collapsed AND dangling. A plan with- every part in place and one misspelled link is what the re-ask is good at, and- re-sampling it throws away the parts that were right."""+ """The restart's trigger is collapsed AND dangling; a full plan with a typo is edited in context."""typo = _good()for i in range(4): # a full-sized plan, well over the degeneracy floortypo["parts"].append({"name": f"Filler{i}", "role": "trim", "description": "a rail",@@ -121,9 +94,6 @@ def test_a_full_plan_with_one_dangling_link_is_edited_in_context_not_resampled(tdef test_a_rejected_plan_is_written_where_a_dead_run_can_be_read(tmp_ws):- """A run that dies at the plan stage used to leave nothing but the pydantic message,- which truncates the offending value — so "what did the model actually write?", the- question every plan-stage failure class starts from, had no answer at all."""from codeverse3d.tracks.planner import INVALID_PLAN_DIRmodel = FakeChatModel(lambda req: _degenerate())diff --git a/harness/tests/orchestrator_tracks/test_prompts_assets.py b/harness/tests/orchestrator_tracks/test_prompts_assets.pyindex 7f26fdfa..151db856 100644--- a/harness/tests/orchestrator_tracks/test_prompts_assets.py+++ b/harness/tests/orchestrator_tracks/test_prompts_assets.py@@ -1,29 +1,23 @@-"""Every tracks/*.j2 renders with the context the tracks build; scene asset stage incl. blender_glb."""+"""The scene asset stage: blender GLB assets, the scene templates, and reuse of committed assets."""from __future__ import annotationsimport re-from types import SimpleNamespaceimport pytestfrom codeverse3d.contracts.common import Language, Track-from codeverse3d.contracts.plan import ArticulatedPlan, ScenePlan+from codeverse3d.contracts.plan import ScenePlanfrom codeverse3d.orchestrator import BudgetGuard, RoundPolicy, RunStatefrom codeverse3d.proc import EventLog-from codeverse3d.prompts import PROMPTS_DIR, render+from codeverse3d.prompts import renderfrom codeverse3d.tracks.common import RunContext-from codeverse3d.tracks.generation import SINGLE_SHOT_FORMATfrom codeverse3d.tracks.planner import plan_example-from codeverse3d.tracks.prompting import base_prompt_context, judged_sheet+from codeverse3d.tracks.prompting import base_prompt_contextfrom codeverse3d.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-TEMPLATES = {"plan_static", "plan_articulated", "plan_scene", "generate_static", "generate_articulated", "refine_object", "repair",- "generate_static_part", "assemble_static",- "scene_asset", "scene_env", "scene_zone", "scene_refine"}-def _asset_module(job) -> str:"""A three.js asset module that passes the deterministic asset check (js), else a stub."""@@ -51,39 +45,6 @@ def _ctx(tmp_ws, settings, spec, plan, *, agent_id="single-shot:gemini:x", servitool_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.stem for p in (PROMPTS_DIR / "tracks").rglob("*.j2")}- assert names >= TEMPLATES- spec = make_spec()- ctx = _ctx(tmp_ws, settings, spec, chair_plan)- base = base_prompt_context(ctx)- assert base["output_format"] == SINGLE_SHOT_FORMAT and "| Seat |" in base["parts_table"]- g = render("tracks/generate_static.j2", **base_prompt_context(ctx, expected_files=["src/object.js"], skeleton_files={"src/object.js": "// s"}, previous_error=""))- assert "Y is UP" in g and "0.430" in g and "[a1]" in g and "=== FILE:" in g and "--- src/object.js ---" in g- r = render("tracks/refine_object.j2", **base_prompt_context(ctx, round_index=1, tasks=["[gate/contract] Seat: off"], targets=["Seat"],- files=["src/parts/seat.js"], edit_only_these=True, judge_summary="js", measurement_notes="mn",- current_files={"src/parts/seat.js": "x"}))- assert "EDIT ONLY THESE FILES" in r and "[gate/contract] Seat" in r- rp = render("tracks/repair.j2", **base_prompt_context(ctx, error_report="BUILD FAILED", files={}, repeats=1, attempt=2, failing_files=["src/model.py"]))- assert "SAME ERROR" in rp- art = ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT))- actx = _ctx(tmp_ws, settings, make_spec(Track.ARTICULATED_OBJECT, Language.URDF_BLENDER), art, agent_id="fake:x")- a = render("tracks/generate_articulated.j2", **base_prompt_context(actx, expected_files=["src/model.py", "src/robot.urdf"], skeleton_files={}, previous_error=""))- assert "| DrawerSlide |" in a and "rooted at `Cabinet`" in a and "HOW TO FINISH (agent mode)" in a and "Tools available" in a- # agent mode does not carry the single-shot format- assert "=== FILE:" not in a--@pytest.mark.blender@pytest.mark.node # its threejs sibling asset runs the node import checkdef test_scene_templates_render_and_asset_stage_with_blender(tmp_ws, settings):@@ -129,9 +90,7 @@ def test_scene_templates_render_and_asset_stage_with_blender(tmp_ws, settings):@pytest.mark.node # the threejs asset check imports three under nodedef test_a_committed_asset_is_reused_on_a_second_stage_run(tmp_ws, settings):- """Review-3 S2 (V3-claim4): re-entering the stage (budget stop after commit, or a- failed sibling) reuses a committed, import-clean module without a model call;- a committed but broken module is regenerated."""+ """A committed, import-clean module is reused without a model call; a broken one is regenerated."""plan = ScenePlan.model_validate(plan_example(Track.SCENE))plan.assets = [a for a in plan.assets if a.kind == "threejs"]spec = make_spec(Track.SCENE, Language.SCENE_THREEJS)@@ -150,28 +109,3 @@ def test_a_committed_asset_is_reused_on_a_second_stage_run(tmp_ws, settings):(tmp_ws.root / results["FishingBoat"].path).write_text("export function nope() {}\n")results3 = run_asset_stage(ctx)assert len(agent.jobs) > n_jobs and results3["FishingBoat"].strategy != "reused"--[email protected] # the threejs asset check imports three under node-def test_a_replanned_asset_with_the_same_name_is_not_reused(tmp_ws, settings):- """Review-3 S2 sharp edge: after a --force re-plan, a committed module that kept- its NAME but changed its plan slice (description/dims) must regenerate — the reuse- guard's identity is the whole AssetPlan hash, not the file path."""- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- plan.assets = [a for a in plan.assets if a.kind == "threejs"]- spec = make_spec(Track.SCENE, Language.SCENE_THREEJS)- agent = FakeAgent(lambda job, ws: {job.prompt.split("write `")[1].split("`")[0] if "write `" in job.prompt else "src/x.js": _asset_module(job)})- ctx = _ctx(tmp_ws, settings, spec, plan, agent_id="fake:x", services=FakeServices(judge=FakeJudge(scores=(0.9, 0.9))), agent=agent)- ctx.runtime.skeleton(tmp_ws, plan)- tmp_ws.commit("skeleton")- run_asset_stage(ctx)- n_jobs = len(agent.jobs)- # the re-plan keeps the asset's name but changes what it IS- boat = next(a for a in ctx.plan.assets if a.name == "FishingBoat")- boat.description = "a rusted iron rowboat, half-sunk, barnacle-crusted"- results = run_asset_stage(ctx)- assert len(agent.jobs) > n_jobs, "a changed plan slice must regenerate, file presence is not identity"- assert results["FishingBoat"].strategy != "reused"- # and the regenerated module is reusable again under the NEW identity- n2 = len(agent.jobs)- assert run_asset_stage(ctx)["FishingBoat"].strategy == "reused" and len(agent.jobs) == n2diff --git a/harness/tests/orchestrator_tracks/test_refactor_batch2.py b/harness/tests/orchestrator_tracks/test_refactor_batch2.pyindex ab18b148..6f09c669 100644--- a/harness/tests/orchestrator_tracks/test_refactor_batch2.py+++ b/harness/tests/orchestrator_tracks/test_refactor_batch2.py@@ -1,20 +1,12 @@-"""Refine grouping, RunOptions wiring, and judge-view flags."""+"""Refine grouping and judge-view flags."""from __future__ import annotations-from codeverse3d.contracts.artifacts import BuildResult, RenderSet, RenderView-from codeverse3d.contracts.common import Language, Track-from codeverse3d.contracts.plan import ScenePlan-from codeverse3d.contracts.spec import RunOptions-from codeverse3d.orchestrator import RefineTask, RunState, plan_refine_groups-from codeverse3d.proc import EventLog-from codeverse3d.tracks.planner import plan_example+from codeverse3d.contracts.artifacts import RenderSet, RenderView+from codeverse3d.orchestrator import RefineTask, plan_refine_groupsfrom codeverse3d.tracks.scene import ScenePipeline-from codeverse3d.tracks.static_object import StaticObjectTrackfrom codeverse3d.workspace import Workspace-from tests.orchestrator_tracks.conftest import make_specfrom tests.orchestrator_tracks.fakes import (- FakeRuntime,FakeServices,)@@ -42,21 +34,6 @@ def test_plan_refine_groups_fans_out_only_when_allowed_and_disjoint():assert not parallel and len(groups) == 1-# --------------------------------------------------------------------- RunOptions wiring (F29)-def test_candidate_width_precedence(tmp_path, settings):- spec = make_spec(options=RunOptions(candidates=2))- 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-- 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--# --------------------------------------------------------------------- judge-view flags (F30 consumption)def _rs(flags: list[bool | None]) -> RenderSet:views = [RenderView(name=f"v{i}", path=f"/tmp/v{i}.png", judge=f) for i, f in enumerate(flags)]@@ -85,13 +62,3 @@ def test_judge_view_flags_and_path_reconstruction(tmp_path):fixed = resolve_paths(ws, rel)assert fixed.out_dir == str(ws.root / "artifacts/renders/r00")assert fixed.views[0].path == str(ws.root / "artifacts/renders/r00/a.png")---# --------------------------------------------------------------------- judge_context is ctx-free (F3)-def test_judge_context_needs_no_run_context(tmp_path):- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- ws = Workspace(tmp_path / "ws").create()- build = BuildResult(ok=True, language="scene_threejs")- text = ScenePipeline().judge_context(ws, plan, 0, build, [])- assert "Environment plan:" in text and "Cameras:" in text- assert ScenePipeline().judge_context(ws, None, 0, build, []) == ""diff --git a/harness/tests/orchestrator_tracks/test_resume_reconcile.py b/harness/tests/orchestrator_tracks/test_resume_reconcile.pyindex b90bdb39..30505882 100644--- a/harness/tests/orchestrator_tracks/test_resume_reconcile.py+++ b/harness/tests/orchestrator_tracks/test_resume_reconcile.py@@ -1,10 +1,4 @@-"""reconcile_resume: on resume, the durable round journal is the truth.--One test per audited failure mode — the crash window between a round write and the state-save, a run recorded before 2026-09-22 (it restored its best round), a planner outage wiping-``record.rounds``, ``--force``/no-``--force`` after a spec edit, judge notes lost to a local-list, and spend the budget snapshot missed.-"""+"""reconcile_resume: on resume, the durable round journal is the truth."""from __future__ import annotations@@ -44,12 +38,7 @@ def _track(planner, settings, *, judge=None, policy=None):@pytest.fixturedef completed_run(tmp_path, chair_plan, settings):- """A finished StaticObjectTrack run — the starting point of every resume test below.-- ``.rerun(...)`` replays the same track over the same workspace (``resume=``/``force=``)- with a FRESH planner, so a test that passes its own ``planner=`` sees in ``.requests``- only what the resume asked for; ``policy=`` / ``spec=`` override the rest.- """+ """A finished run; ``.rerun(...)`` replays the track over the same workspace with a fresh planner."""plan = chair_plan.model_dump(mode="json")def rerun(r, *, planner=None, policy=None, spec=None, **kw):@@ -69,10 +58,7 @@ def completed_run(tmp_path, chair_plan, settings):# --------------------------------------------------------------------- (a) crash windowdef test_crash_between_round_write_and_state_save_ends_at_the_newer_round(completed_run):- """rNN.json + its commit are durable; the state save after them is not. A crash in that- window — here with a state written before r01 (a pre-2026-09-22 one that still caches the- journal one round short) and the tree on the older round — resumes from the JOURNAL: the- history is r00 + r01 and the run ends on the LAST round."""+ """A crash after rNN.json but before the state save resumes from the journal, on the last round."""run = completed_run(max_rounds=1)rec1, ws = run.record, run.wsassert len(rec1.rounds) == 2@@ -91,9 +77,7 @@ def test_crash_between_round_write_and_state_save_ends_at_the_newer_round(compledef test_an_old_run_that_restored_its_best_round_resumes_from_its_last(completed_run, settings):- """A run recorded before 2026-09-22 ended on a "restore best round rNN" commit, with its- run_state.json and record.json naming that best round and status ``passed``. Both still- load; the resume puts src/ back on the LAST round and the next round refines THAT one."""+ """A pre-2026-09-22 run that ended on "restore best round" resumes from, and refines, its LAST round."""run = completed_run(max_rounds=1)rec1, ws = run.record, run.wsstate = json.loads(ws.state_path.read_text())@@ -130,9 +114,6 @@ def _code_at(ws: Workspace, commit: str) -> str:# --------------------------------------------------------------------- (b) history wipedef test_a_planner_outage_on_resume_keeps_the_recorded_history(completed_run):- """The FAILED handler serialized record.json with rounds=[] because the journal was- loaded only AFTER the plan and the pre-round stages — one planner outage on resume wiped record.rounds- (and with it the flywheel's rounds_summary)."""run = completed_run(max_rounds=0)ws = run.wsassert len(run.record.rounds) == 1@@ -151,9 +132,7 @@ def test_a_planner_outage_on_resume_keeps_the_recorded_history(completed_run):# --------------------------------------------------------------------- (d) force provenancedef test_force_resume_with_an_edited_prompt_archives_the_old_rounds(completed_run):- """`resume --force` after a prompt edit re-planned and then paired the OLD rounds with- the NEW spec/plan in record.json — fake prompt→code provenance. The old journal +- record are archived under rounds/pre_force/ instead."""+ """`resume --force` after a prompt edit archives the old journal and record under rounds/pre_force/."""run = completed_run(max_rounds=0)ws = run.wsold_commit = run.record.rounds[0].commit@@ -199,8 +178,6 @@ def test_a_spec_edit_without_force_is_refused_before_anything_runs(completed_run# --------------------------------------------------------------------- (f3) notes survivedef test_notes_survive_a_judge_crash(tmp_path, chair_plan, settings):- """_judge appended 'judge failed: ...' to rec.notes, which _run_round then overwrote- with its own local notes list — the note never reached rNN.json."""class BoomJudge(FakeJudge):def judge(self, inp):if inp.round_index >= 1:@@ -220,8 +197,7 @@ def test_notes_survive_a_judge_crash(tmp_path, chair_plan, settings):def test_has_commit_answers_no_when_git_cannot_answer(tmp_path, monkeypatch):- """has_commit raised on a missing run dir (the OSError of a cwd that is gone) and had no- timeout, unlike every other git read — a hung git hung the resume / the export."""+ """has_commit answers False on a missing dir or a hung git (with the shared timeout)."""import subprocessfrom codeverse3d.workspace import HAS_COMMIT_TIMEOUT_S, Workspacediff --git a/harness/tests/orchestrator_tracks/test_round_economics.py b/harness/tests/orchestrator_tracks/test_round_economics.pyindex cf7e7919..b4fcdeaf 100644--- a/harness/tests/orchestrator_tracks/test_round_economics.py+++ b/harness/tests/orchestrator_tracks/test_round_economics.py@@ -2,29 +2,24 @@from __future__ import annotations-import json-import pytestfrom codeverse3d.contracts.agent import AgentJob, AgentResult-from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Severityfrom codeverse3d.contracts.common import Language, Usage-from codeverse3d.contracts.run import RoundRecord, RunStatus+from codeverse3d.contracts.run import RunStatusfrom codeverse3d.cost.instrument import MeteredAgent, run_ledgerfrom codeverse3d.cost.ledger import load_ledgerfrom codeverse3d.orchestrator import RoundPolicyfrom codeverse3d.proc import EventLogfrom codeverse3d.tracks.generation import (- DEFAULT_AGENT_MAX_TURNS,DEFAULT_WRAPUP_TURNS,GenerationTask,- agent_max_turns,run_agent_task,turn_capped,)from codeverse3d.tracks.static_object import StaticObjectTrackfrom codeverse3d.workspace import Workspace-from tests.orchestrator_tracks.conftest import fake_clock, make_spec+from tests.orchestrator_tracks.conftest import make_specfrom tests.orchestrator_tracks.fakes import (FakeAgent,FakeJudge,@@ -60,34 +55,6 @@ class _TurnAgent:usage=Usage(backend="api-agent", cost_usd=self.cost, input_tokens=1000))-def test_agent_sessions_are_uncapped_by_default(tmp_ws, switch):- switch("C3D_AGENT_MAX_TURNS", None)- assert DEFAULT_AGENT_MAX_TURNS == 0- agent = _TurnAgent(writes_on=1)- task = GenerationTask(label="baseline", prompt="p", round=0, kind="baseline")- run_agent_task(tmp_ws, agent=agent, task=task)- assert agent.jobs[0].max_turns == AgentJob(workspace="w", prompt="p").max_turns # the backend's own default- assert agent_max_turns() == 0 # "no cap asked for"- # ... and the machine's way of asking for one still works- switch("C3D_AGENT_MAX_TURNS", "9")- assert agent_max_turns() == 9- run_agent_task(tmp_ws, agent=agent, task=task)- assert agent.jobs[-1].max_turns == 9- switch("C3D_AGENT_MAX_TURNS", "nonsense") # warns, keeps the default: never a crash- assert agent_max_turns() == DEFAULT_AGENT_MAX_TURNS == 0---def test_the_configured_cap_is_plumbed_through_the_round(tmp_path, spec, settings, monkeypatch):- from codeverse3d.tracks.steps import run_generation_tasks-- monkeypatch.setenv("C3D_AGENT_MAX_TURNS", "15")- agent = _TurnAgent(writes_on=1)- ctx = _ctx(tmp_path, spec, settings, agent=agent)- run_generation_tasks(ctx, [GenerationTask(label="baseline", prompt="p", round=0, kind="baseline")])- assert agent.jobs[0].max_turns == 15- assert agent.jobs[1].max_turns == DEFAULT_WRAPUP_TURNS # ... and the landing session--def test_hitting_the_cap_asks_for_a_landing_instead_of_killing_the_session(tmp_ws, monkeypatch):monkeypatch.setenv("C3D_AGENT_MAX_TURNS", "28")events = EventLog(tmp_ws.events_path)@@ -157,11 +124,6 @@ def _renders():return RenderSet(views=[RenderView(name="front", path="x.png")], renderer="fake")-def _gates(errors: int = 0):- return [GateReport(gate="lint", passed=not errors,- findings=[GateFinding(gate="lint", severity=Severity.ERROR, message="e")] * errors)]--def test_skip_judge_reasons_are_only_states_where_the_verdict_is_never_bought(tmp_path, spec, settings):from codeverse3d.tracks.steps import skip_judge_reason@@ -187,28 +149,6 @@ def test_a_round_that_changed_no_file_never_reaches_the_judge_question(tmp_path,run_generation_tasks(ctx, [GenerationTask(label="refine", prompt="p", round=1, kind="refine")])-def test_a_round_with_gate_errors_whose_verdict_was_lost_is_rejudged(tmp_path, spec, settings):- from codeverse3d.tracks.steps import rejudge_round-- ctx = _ctx(tmp_path, spec, settings, name="rebuy")- rec = RoundRecord(index=1, kind="refine", build=BuildResult(ok=True, language="l"),- gates=_gates(2), renders=_renders())- assert rejudge_round(ctx, _pipeline(), rec) is True and len(ctx.judge.calls) == 1---class _Pipeline:- """The minimum ``RoundPipeline`` the judge path touches."""-- def measure(self, ctx, build): return None- def gates(self, ctx, i, build, m): return []- def render(self, ctx, i, build, m): return _renders()- def judge_context(self, ws, plan, i, build, gates): return ""---def _pipeline():- return _Pipeline()--def _ctx(tmp_path, spec, settings, *, policy: RoundPolicy | None = None, agent=None, name: str = "skip"):from codeverse3d.contracts.common import Budgetfrom codeverse3d.orchestrator import BudgetGuard, RunState@@ -228,8 +168,7 @@ def _writer(job, ws):def test_a_regression_changes_nothing_about_the_loop_and_every_round_reports_its_cost(tmp_path, chair_plan, settings):- """r01 regresses hard: no strategy switch, no rewrite, no stop — the loop runs its- rounds, each an ordinary refine, and a lower score is not waste (every round is kept)."""+ """A regression changes nothing about the loop; the run's total is its ledger's (D84)."""spec = make_spec(max_rounds=3)ws = Workspace(tmp_path / "runs" / "regress")agent = FakeAgent(_writer, cost=0.02)@@ -252,51 +191,6 @@ def test_a_regression_changes_nothing_about_the_loop_and_every_round_reports_itsassert "cost_by_stage" not in rec.extra-def test_a_lint_stuck_run_keeps_every_score_instead_of_deferring_the_verdict(tmp_path, chair_plan, settings):- def _writer_lint(job, ws):- return {"src/object.js": f"// {job.label} r{job.round}\nLINT_ERROR\nexport function build(THREE) {{}}\n"}-- spec = make_spec(max_rounds=2)- ws = Workspace(tmp_path / "runs" / "lintstuck")- judge = FakeJudge(scores=(0.5, 0.6, 0.7))- track = StaticObjectTrack(services=FakeServices(), judge=judge, agent=FakeAgent(_writer_lint),- planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,- runtime=FakeRuntime(Language.THREEJS),- policy=RoundPolicy(max_rounds=2))- rec = track.run(spec, ws)- events = EventLog(ws.events_path).read()- assert [e for e in events if e["event"] == "judge.skipped"] == []- assert [e for e in events if e["event"] == "judge.retry"] == []- assert [r.score for r in rec.rounds] == [0.5, 0.6, 0.7]- # one verdict per round, bought once- assert len([e for e in events if e["event"] == "judge.done"]) == len(rec.rounds) == len(judge.calls)---def test_a_round_that_raises_still_reports_what_it_burned(tmp_path, chair_plan, settings):- spec = make_spec(max_rounds=2, max_minutes=10.0)- ws = Workspace(tmp_path / "runs" / "cut")-- class _Expensive(FakeAgent):- def run(self, job):- res = super().run(job)- return res.model_copy(update={"usage": Usage(backend="fake", cost_usd=0.04, input_tokens=1000)})-- track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.5, 0.6)), agent=_Expensive(_writer, minutes=8.0),- planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,- runtime=FakeRuntime(Language.THREEJS), policy=RoundPolicy(max_rounds=2))- with fake_clock():- rec = track.run(spec, ws)- assert rec.status is RunStatus.BUDGET- aborted = json.loads((ws.root / "rounds" / "aborted_r01.json").read_text())- assert aborted["index"] == 1 and aborted["usage"]["cost_usd"] > 0 and "BudgetExceeded" in aborted["notes"]- assert rec.extra["aborted_rounds"][0]["index"] == 1- # the aborted round is NOT resumable state, and its money is in the total- assert [r.index for r in rec.rounds] == [0]- assert rec.extra["aborted_rounds"][0]["cost_usd"] == pytest.approx(aborted["usage"]["cost_usd"])- assert rec.total_usage.cost_usd == pytest.approx(- sum(r.usage.cost_usd for r in rec.rounds) + aborted["usage"]["cost_usd"] + 0.002) # + the planner--def test_fan_out_workers_inherit_the_callers_context():import contextvarsdiff --git a/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py b/harness/tests/orchestrator_tracks/test_scene_hero_ladder.pyindex c489cdc6..8aa5645c 100644--- a/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py+++ b/harness/tests/orchestrator_tracks/test_scene_hero_ladder.py@@ -1,13 +1,8 @@-"""The blender hero of the scene track climbs the same ladder as a threejs asset, with the-scene in its prompt and its GLB checked (2026-09-07 review of PR #7).--Offline: fake agent / chat model / judge / runtime (a trimesh box per plan part) / services.-"""+"""The blender hero of the scene track climbs the same ladder as a threejs asset (offline fakes)."""from __future__ import annotationsimport json-import subprocessimport pytest@@ -15,7 +10,6 @@ from codeverse3d.contracts.common import Language, Trackfrom codeverse3d.contracts.plan import ScenePlanfrom codeverse3d.contracts.spec import Constraintsfrom codeverse3d.tracks import scene_assets as SA-from codeverse3d.tracks.depth import DETAIL_ADVICEfrom codeverse3d.tracks.planner import plan_examplefrom tests.orchestrator_tracks.conftest import make_specfrom tests.orchestrator_tracks.fakes import (@@ -71,31 +65,6 @@ def _writer(text: str):return lambda job, ws: {"src/model.py": f"{text}# session {job.label}\n"}-def test_hero_prompt_carries_the_scene_and_blenders_own_tools(tmp_ws, settings):- agent = FakeAgent(_writer(GOOD_MODEL))- ctx, hero = _scene(tmp_ws, settings, services=CardedServices(), agent=agent)- res = SA.build_blender_asset(ctx, hero, judge=False)- assert res.ok and res.strategy == "agent"- job = agent.jobs[0]- assert job.label == f"asset_{SA.to_snake(hero.name)}"- # the SCENE, not the asset sheet, is the scene; its style reaches the prop- assert f"Scene: {SCENE_PROMPT}" in job.prompt and "weathered, hand-painted" in job.prompt- assert f"Scene: {hero.description}" not in job.prompt and "(none)" not in job.prompt.split("## The asset")[0]- # the hero's tools are Blender's (check_contract, cross_section …), not the scene's- assert "CARDS(static_object/blender)" in job.prompt and "CARDS(scene/" not in job.prompt- # the plan's detail advice and no triangle number; the layout it must fill- assert "40k" not in job.prompt and DETAIL_ADVICE in job.prompt and "DETAIL BUDGET" not in job.prompt- # the blender layout: the entry + one file per planned part (the one-part sheet here)- assert job.files_hint == ["src/model.py", f"src/parts/{SA.to_snake(hero.name)}.py"]- assert job.timeout_s <= SA.asset_timeout_s(ctx, 180)- # the sub-run's plan.json is the plan the prompt was built from- sub = tmp_ws.root / "_assets" / SA.to_snake(hero.name)- assert json.loads((sub / "plan.json").read_text())["object_name"] == hero.name- events = [json.loads(line) for line in tmp_ws.events_path.read_text().splitlines()]- gen = [e for e in events if e["event"] == "asset.generated" and e["asset"] == hero.name]- assert gen and gen[0]["strategy"] == "agent" and gen[0]["ok"] is True--def _crate_plan(asset):"""A two-part plan the fake runtime builds at the crate's size (one box per part)."""from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan@@ -107,57 +76,8 @@ def _crate_plan(asset):acceptance=[])-def test_hero_tries_single_shot_before_an_agent_session(tmp_ws, settings, monkeypatch):- services = SingleShotServices()- agent = FakeAgent(_writer(GOOD_MODEL))- monkeypatch.setattr(SA, "hero_plan", lambda sub, asset: _crate_plan(asset)) # two parts → two boxes → not "one low-poly box"- ctx, hero = _scene(tmp_ws, settings, services=services, agent=agent)- res = SA.build_blender_asset(ctx, hero, judge=False)- assert res.ok and res.strategy == "single-shot" and res.path == f"public/assets/{SA.to_snake(hero.name)}.glb"- assert agent.jobs == [] and len(services.chat.requests) == 1- req = services.chat.requests[0]- assert req.response_schema is None and "=== FILE:" in req.system + " ".join(p.text for m in req.messages for p in m.parts if getattr(p, "text", ""))- assert (tmp_ws.public / "assets" / f"{SA.to_snake(hero.name)}.glb").is_file() and res.size_m is not None---def test_hero_plan_is_the_static_planners_part_list(tmp_ws, settings):- services = SingleShotServices()- ctx, hero = _scene(tmp_ws, settings, services=services, agent=FakeAgent(_writer(GOOD_MODEL)))- res = SA.build_blender_asset(ctx, hero, judge=False)- assert res.ok- sub = tmp_ws.root / "_assets" / SA.to_snake(hero.name)- plan = json.loads((sub / "plan.json").read_text())- assert len(plan["parts"]) > 1, "a hero gets a real part list, not the one-part sheet"- events = [json.loads(line) for line in tmp_ws.events_path.read_text().splitlines()]- assert any(e["event"] == "asset.planned" and e["n_parts"] == len(plan["parts"]) for e in events)---def test_hero_glb_soft_findings_trigger_one_feedback_repair_then_escalate(tmp_ws, settings):- # the one-part sheet (planner unavailable → fallback) builds ONE tiny box: "still a single- # low-poly box" is exactly the finding a threejs module gets; single-shot gets one repair- # with that feedback, then the agent session takes over- class NoPlanner(SingleShotServices):- def _answer(self, req):- if req.response_schema is not None:- raise RuntimeError("planner down")- return self.model_text-- services = NoPlanner()- agent = FakeAgent(_writer(GOOD_MODEL))- ctx, hero = _scene(tmp_ws, settings, services=services, agent=agent)- res = SA.build_blender_asset(ctx, hero, judge=False)- assert res.strategy == "escalated" and res.ok- texts = [" ".join(p.text for m in r.messages for p in m.parts if getattr(p, "text", "")) for r in services.chat.requests- if r.response_schema is None]- assert len(texts) == 2 and "did NOT pass the deterministic asset check" in texts[1] and "single low-poly box" in texts[1]- assert "## Current file(s)" in texts[1] and [j.label for j in agent.jobs] == [f"asset_{SA.to_snake(hero.name)}"]- events = [json.loads(line) for line in tmp_ws.events_path.read_text().splitlines()]- assert any(e["event"] == "asset.escalated" for e in events) and any(e["event"] == "asset.plan_failed" for e in events)--class _StormAgent(FakeAgent):- """A CLI session that wrote partial files and died at the wall in a 503 streak with no final- answer (D68: 26 of the evening's 40 timed-out sessions)."""+ """A CLI session that wrote partial files and died at the wall in a 503 streak (D68)."""def run(self, job):from codeverse3d.contracts.agent import AgentResult@@ -174,10 +94,7 @@ class _StormAgent(FakeAgent):def test_a_hero_session_that_died_in_the_storm_gets_one_more_cheap_repair(tmp_ws, settings, monkeypatch):- """Loops 10 and 13 (2026-09-07): the clockmaker's LongcaseClock escalated, the session wrote- eleven part files and died at the wall after 7 x 503, the partial parts failed the check and- the scene shipped without its hero. The ladder now takes ONE more single-shot repair with- that check's feedback (asset.storm_repair) before giving the hero up."""+ """A storm-dead hero session gets ONE more single-shot repair with the check's feedback."""calls = {"n": 0}class FailTwiceThenGood(SingleShotServices):@@ -215,23 +132,6 @@ def test_hero_repair_sessions_are_clipped_to_the_asset_window_and_capped_at_one(assert all(j.timeout_s <= window for j in agent.jobs), [(j.label, j.timeout_s) for j in agent.jobs]-def test_hero_fix_is_rejudged_committed_and_carries_a_system_prompt(tmp_ws, settings):- judge = FakeJudge(scores=(0.5, 0.9))- agent = FakeAgent(_writer(GOOD_MODEL))- ctx, hero = _scene(tmp_ws, settings, services=CardedServices(judge=judge), agent=agent)- res = SA.build_blender_asset(ctx, hero, judge=True)- assert res.ok and res.fixed and res.judged- assert res.score_before == 0.5 and res.score == 0.9 and len(judge.calls) == 2- snake = SA.to_snake(hero.name)- fix = next(j for j in agent.jobs if j.label == f"asset_{snake}_fix")- assert fix.system_append and "PROP" in fix.system_append.upper()- sub = tmp_ws.root / "_assets" / snake- out = SA.Workspace(sub).renders_dir(0) / "assets" # the hero is judged in ITS workspace- assert (out / snake / "judge.json").is_file() and (out / f"{snake}_fix" / "judge.json").is_file()- status = subprocess.run(["git", "status", "--porcelain", "--", "src"], cwd=sub, capture_output=True, text=True).stdout- assert status.strip() == "", status--def test_hero_reentry_keeps_the_previous_sessions_src(tmp_ws, settings):agent = FakeAgent(_writer(GOOD_MODEL))ctx, hero = _scene(tmp_ws, settings, services=CardedServices(), agent=agent)@@ -256,8 +156,7 @@ def test_asset_check_soft_findings_share_one_rule_set(kind):def test_a_fix_that_judges_worse_is_undone(tmp_ws, settings):- """The judge's fix pass is one more model answer: when the re-judge says it made the- asset worse, the pre-fix GLB and src ship (loop 1, 2026-09-07: BronzeCenser 0.526 → 0.43)."""+ """When the re-judge says the fix made the asset worse, the pre-fix GLB and src ship."""judge = FakeJudge(scores=(0.6, 0.4))agent = FakeAgent(_writer(GOOD_MODEL))ctx, hero = _scene(tmp_ws, settings, services=CardedServices(judge=judge), agent=agent)@@ -272,8 +171,6 @@ def test_a_fix_that_judges_worse_is_undone(tmp_ws, settings):def test_a_fix_that_does_not_build_is_undone(tmp_ws, settings):- """The restore only ran when the fix JUDGED worse; a fix that broke the build left the broken- src in the hero's workspace next to the GLB of the version before it."""judge = FakeJudge(scores=(0.6,))snake = "crate"agent = FakeAgent(lambda job, ws: {"src/model.py": GOOD_MODEL + ("" if job.label == f"asset_{snake}" else FAIL_MARK) # the fix AND its repair break@@ -288,9 +185,6 @@ def test_a_fix_that_does_not_build_is_undone(tmp_ws, settings):def test_the_largest_module_is_judged_and_the_small_ones_are_not(tmp_ws, settings):- """`render_asset` makes a threejs verdict possible; the share rule alone judged nothing- (no prop reaches 5 % of a scene's volume), so the plan's largest module keeps its- verdict and the rest skip with the same event as before."""ctx, _hero = _scene(tmp_ws, settings, services=CardedServices(), agent=FakeAgent(_writer(GOOD_MODEL)))mods = [a for a in ctx.plan.assets if a.kind == "threejs"]big = max(mods, key=lambda a: a.approx_size_m[0] * a.approx_size_m[1] * a.approx_size_m[2])@@ -303,9 +197,7 @@ def test_the_largest_module_is_judged_and_the_small_ones_are_not(tmp_ws, settingdef test_a_thin_hero_plan_is_asked_again_with_the_sheets_features_as_the_checklist(tmp_ws, settings):- """The windmill got a one-part plan twice while every other hero got 7-12 parts: a plan- of <= HERO_THIN_PLAN_PARTS parts for a sheet naming more features is re-asked ONCE with- those features as must_have (what sizes the planner's part budget)."""+ """A plan of <= HERO_THIN_PLAN_PARTS parts for a richer sheet is re-asked ONCE with its features as must_have."""calls = []@@ -343,10 +235,7 @@ def test_a_thin_hero_plan_is_asked_again_with_the_sheets_features_as_the_checklidef test_a_threejs_fix_with_only_soft_findings_is_kept_and_judged_again(tmp_ws, settings, monkeypatch):- """The three.js ``_after_fix`` returned ``check.ok``, which is False on a SOFT finding- too (size off, too many triangles), so ``_judge_and_fix`` reverted a fix that imports- fine and never judged it. A fix is undone only when the module no longer imports —- the rule the hero's ``_after_fix`` (a successful build) already applied."""+ """A fix with only soft findings still imports, so it is kept and judged; only a non-importing fix is undone."""from codeverse3d.contracts.artifacts import RenderSetboat = "src/assets/fishing_boat.js"diff --git a/harness/tests/orchestrator_tracks/test_static_judge_context.py b/harness/tests/orchestrator_tracks/test_static_judge_context.pyindex 6884286b..f2e545ae 100644--- a/harness/tests/orchestrator_tracks/test_static_judge_context.py+++ b/harness/tests/orchestrator_tracks/test_static_judge_context.py@@ -7,7 +7,6 @@ from __future__ import annotationsfrom codeverse3d.contracts.artifacts import Measurement, PartMeasurefrom codeverse3d.contracts.plan import BBox, PartPlan, StaticPlanfrom codeverse3d.spatial.contract import planned_joins-from codeverse3d.tracks.static_object import ObjectPipelinefrom tests.orchestrator_tracks.test_integrations2 import _static_run@@ -24,10 +23,7 @@ def test_track_passes_attach_to_pairs_to_the_connectivity_gate(tmp_path, chair_pdef test_planned_joins_spell_instances_as_the_glb_does_and_pair_every_touching_parent_copy(chair_plan):- """Counted 2026-08-30 over the 342 stored static rounds with attach_to edges: 823 of 2 568- edges name an instance part (``FrontLeg`` for ``FrontLeg_0``/``FrontLeg_1``). Each child copy- joins every copy of its parent it touches (the backrest spans both back legs), else the- nearest — the cross product would call the far apron/leg pair of every chair OPEN."""+ """Each child copy joins every parent copy it touches, never the cross product."""leg = lambda x, z: ((x - 0.02, 0.0, z - 0.02), (x + 0.02, 0.41, z + 0.02)) # noqa: E731m = _measurement({"Seat": ((-0.21, 0.41, -0.2), (0.21, 0.45, 0.2)),@@ -54,12 +50,3 @@ def test_planned_joins_drop_what_the_mesh_does_not_have():del boxes["Top"] # the parent never made it into the export: no edge, the contract gate reports the missing partassert planned_joins(plan, _measurement(boxes)) == [('Ring', ('Leg_0', 'Leg_1'))]assert planned_joins(None, _measurement(boxes)) == [] and planned_joins(plan, None) == []---def test_judge_context_stays_empty_because_the_block_lives_in_gates_section(tmp_path, chair_plan):- """The block is rendered from the stored GateReport, so ``3dcode judge <slug>`` on a recorded- round gets it too; a judge_context copy would be a second source of the same facts."""- from codeverse3d.contracts.artifacts import BuildResult- from codeverse3d.workspace import Workspace-- assert ObjectPipeline().judge_context(Workspace(tmp_path / "w"), chair_plan, 0, BuildResult(ok=True, language="threejs"), []) == ""diff --git a/harness/tests/orchestrator_tracks/test_tracks.py b/harness/tests/orchestrator_tracks/test_tracks.pyindex 8ee47930..5b5a8eae 100644--- a/harness/tests/orchestrator_tracks/test_tracks.py+++ b/harness/tests/orchestrator_tracks/test_tracks.py@@ -7,23 +7,16 @@ import jsonimport pytestfrom codeverse3d.addons import select-from codeverse3d.contracts.artifacts import GateFinding, GateReport, Severityfrom codeverse3d.contracts.common import Language, Track-from codeverse3d.contracts.plan import ArticulatedPlan, ScenePlan-from codeverse3d.contracts.run import RunRecord, RunStatus+from codeverse3d.contracts.run import RunStatusfrom codeverse3d.orchestrator import RoundPolicy, RunStatefrom codeverse3d.proc import EventLog-from codeverse3d.tracks import get_track-from codeverse3d.tracks.articulated_object import ArticulatedObjectTrack-from codeverse3d.tracks.planner import plan_examplefrom codeverse3d.tracks.scene import SceneTrackfrom codeverse3d.tracks.static_object import StaticObjectTrackfrom codeverse3d.workspace import Workspace-from tests.orchestrator_tracks.conftest import fake_clock, make_spec+from tests.orchestrator_tracks.conftest import make_specfrom tests.orchestrator_tracks.fakes import (- FAIL_MARK,FakeAgent,- FakeChatModel,FakeJudge,FakeRuntime,FakeServices,@@ -48,65 +41,19 @@ def _agent_writer(job, ws):def test_static_track_end_to_end_agent_path(tmp_path, chair_plan, settings):- spec = make_spec(max_rounds=3)ws = Workspace(tmp_path / "runs" / "chair")- judge = FakeJudge(scores=(0.55, 0.7, 0.85))- services = FakeServices(contract_errors=1)- agent = FakeAgent(_agent_writer)- track = StaticObjectTrack(services=services, judge=judge, agent=agent, planner_model=_planner(chair_plan.model_dump(mode="json")),+ track = StaticObjectTrack(services=FakeServices(contract_errors=1), judge=FakeJudge(scores=(0.55, 0.7, 0.85)),+ agent=FakeAgent(_agent_writer), planner_model=_planner(chair_plan.model_dump(mode="json")),settings=settings, runtime=FakeRuntime(Language.THREEJS))- rec = track.run(spec, ws)- # FIXED rounds: 0.85 would once have stopped the run as a pass; the baseline + 3 refine rounds run- assert isinstance(rec, RunRecord) and rec.status is RunStatus.MAX_ROUNDS- assert [r.kind for r in rec.rounds] == ["baseline", "refine", "refine", "refine"]- assert [r.score for r in rec.rounds] == [0.55, 0.7, 0.85, 0.85]- assert rec.total_usage.cost_usd > 0 and rec.extra["stop_reason"] == "max_rounds"- assert ws.record_path.is_file() and ws.plan_path.is_file() and ws.state_path.is_file()- assert RunState.load(ws).status is RunStatus.MAX_ROUNDS- assert services.materialized == ["fake"] and (ws.root / "AGENTS.md").is_file()- kinds = [e["event"] for e in EventLog(ws.events_path).read()]- for k in ("run.start", "stage.done", "plan.done", "round.start", "build.done", "gates.done", "judge.done", "round.done", "stop", "run.done"):- assert k in kinds, k- # per-round artifacts- assert (ws.root / "rounds" / "r00.json").is_file() and ws.judge_path(2).is_file() and (ws.gates_dir(1) / "contract.json").is_file()- assert (ws.renders_dir(0) / "sheet.png").is_file()- # refine rounds carried gate + judge instructions; the contract error was the first instruction- assert rec.rounds[1].instructions and rec.rounds[1].instructions[0].startswith("[gate/gate:contract] Seat")- # baseline prompt is concrete: parts table + acceptance + contract + skeleton reminder- p0 = agent.jobs[0].prompt- assert "| Seat |" in p0 and "Acceptance checklist" in p0 and "Y is UP" in p0 and "overlap" in p0- # the refine round fanned out per part (≥3 file-disjoint groups, threejs)- labels = [j.label for j in agent.jobs]- assert sum(1 for lb in labels if lb.startswith("refine_")) >= 3- assert all("EDIT ONLY THESE FILES" in j.prompt for j in agent.jobs if j.label.startswith("refine_"))- # git history: one commit per round, and the workspace ends at the last one+ rec = track.run(make_spec(max_rounds=3), ws)+ assert rec.status is RunStatus.MAX_ROUNDS and [r.score for r in rec.rounds] == [0.55, 0.7, 0.85, 0.85]+ assert rec.rounds[1].instructions[0].startswith("[gate/gate:contract] Seat") # gate findings lead the refine+ # Law 6: one commit per round, and the workspace ends at the last oneassert len({r.commit for r in rec.rounds}) == 4 and ws.head() == rec.rounds[3].commit# provenance (D37): the judge protocol hash sits next to the generator prompt hashesassert rec.prompt_hashes["judge"] == FakeJudge.prompt_hash and "generate" in rec.prompt_hashes-def test_static_track_single_shot_with_repair_and_budget_stop(tmp_path, chair_plan, settings):- spec = make_spec(generator="single-shot:gemini:fake", max_rounds=4, max_minutes=6.0)- ws = Workspace(tmp_path / "runs" / "chair2")- n = {"gen": 0}-- def responder(req):- n["gen"] += 1- if req.label.startswith("baseline"): # first build fails, the repair fixes it- return f"=== FILE: src/object.js ===\n// {FAIL_MARK}\nexport function build(){{}}\n=== END FILE ==="- return "=== FILE: src/object.js ===\nexport function build(THREE) { return new THREE.Group(); }\n=== END FILE ==="-- model = FakeChatModel(responder, cost=0.004, minutes=0.5)- track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.5, 0.55, 0.6, 0.62)), model=model,- planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.THREEJS))- with fake_clock():- rec = track.run(spec, ws)- assert rec.status is RunStatus.BUDGET and rec.rounds[0].build.ok and "repair attempts: 1/2 (fixed)" in rec.rounds[0].notes- assert rec.rounds[0].score == pytest.approx(0.5)- assert any(r.label.startswith("r00_baseline_repair") for r in model.requests) or any("Repair" in r.messages[0].text for r in model.requests)- assert rec.total_usage.cost_usd > 0.03 and ws.record_path.is_file()--def test_static_track_resume_continues_from_saved_rounds(tmp_path, chair_plan, settings):spec = make_spec(max_rounds=2)ws = Workspace(tmp_path / "runs" / "chair3")@@ -130,56 +77,6 @@ def test_static_track_resume_continues_from_saved_rounds(tmp_path, chair_plan, sassert kinds.count("stage.cached") >= 2 # plan + skeleton cached on resume-def test_static_track_failure_writes_failed_record_and_raises(tmp_path, chair_plan, settings):- spec = make_spec()- ws = Workspace(tmp_path / "runs" / "chair4")-- class BoomRuntime(FakeRuntime):- def skeleton(self, ws, plan):- raise RuntimeError("skeleton exploded")-- track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(), agent=FakeAgent(_agent_writer),- planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=BoomRuntime(Language.THREEJS))- with pytest.raises(RuntimeError, match="skeleton exploded"):- track.run(spec, ws)- rec = RunRecord.model_validate(json.loads(ws.record_path.read_text()))- assert rec.status is RunStatus.FAILED and "skeleton exploded" in rec.error- assert RunState.load(ws).status is RunStatus.FAILED---def test_static_track_whole_object_refine(tmp_path, chair_plan, settings):- """cadquery = whole-object language (its runtime names no per-part file): refine is ONE task;- the prompt carries measured-vs-plan numbers in Z-up."""- spec = make_spec(language=Language.CADQUERY, max_rounds=1)- ws = Workspace(tmp_path / "runs" / "chair5")- agent = FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # {job.label}\n"})- track = StaticObjectTrack(services=FakeServices(contract_errors=2), judge=FakeJudge(scores=(0.5, 0.6)), agent=agent,- planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.CADQUERY))- rec = track.run(spec, ws)- assert [j.label for j in agent.jobs] == ["baseline", "refine"]- p = agent.jobs[1].prompt- assert "Measured overall extents" in p and "EDIT ONLY" not in p and "Files in scope: `src/model.py`" in p- assert rec.status is RunStatus.MAX_ROUNDS---# ----------------------------------------------------------------------------- articulated-def test_articulated_track_adds_pose_views_and_sweep_gate(tmp_path, settings):- spec = make_spec(Track.ARTICULATED_OBJECT, Language.URDF_BLENDER, max_rounds=1)- ws = Workspace(tmp_path / "runs" / "drawer")- plan = ArticulatedPlan.model_validate(plan_example(Track.ARTICULATED_OBJECT))- agent = FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # {job.label}\n", "src/robot.urdf": "<robot name='x'/>\n"})- services = FakeServices(sweep_errors=1)- track = ArticulatedObjectTrack(services=services, judge=FakeJudge(scores=(0.6, 0.9), targets=("Drawer",)), agent=agent,- planner_model=_planner(plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.URDF_BLENDER))- rec = track.run(spec, ws)- assert rec.status is RunStatus.MAX_ROUNDS- r0 = rec.rounds[0]- assert any(v.name.startswith("pose_") for v in r0.renders.views)- sweep = next(g for g in r0.gates if g.gate == "joint_sweep")- assert not sweep.passed and rec.rounds[1].instructions[0].startswith("[gate/gate:joint_sweep] DrawerSlide")- assert "Joints (the URDF must realise EXACTLY these" in agent.jobs[0].prompt and "| DrawerSlide |" in agent.jobs[0].prompt--# ----------------------------------------------------------------------------- scenedef _scene_writer(job, ws):label = job.label@@ -196,57 +93,8 @@ def _scene_writer(job, ws):return {"src/scene.js": "// x\n"}-def test_scene_track_stages_and_rounds(tmp_path, settings):- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- plan.assets = [a for a in plan.assets if a.kind == "threejs"] # blender assets need a Blender runtime → covered separately- for z in plan.zones:- z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]- spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=1, prompt="a small harbour at dusk")- ws = Workspace(tmp_path / "runs" / "harbour")- agent = FakeAgent(_scene_writer)- services = FakeServices()- track = SceneTrack(services=services, judge=FakeJudge(scores=(0.6, 0.7), targets=("Quay", "Water")), agent=agent,- planner_model=_planner(plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.SCENE_THREEJS))- rec = track.run(spec, ws)- labels = [j.label for j in agent.jobs]- # Quay and Water are both small zones (≤ 3 placements) → ONE batched session owning both files- # assets ∥ env: the combined stage's three sessions interleave freely; order resumes at zones- assert set(labels[:3]) == {"asset_fishing_boat", "asset_bollard", "env"} and "zones_quay_water" in labels- assert "compose" not in labels and labels.index("env") < labels.index("zones_quay_water") # scene.js is assembled- assert (ws.src / "assets" / "fishing_boat.js").is_file() and (ws.src / "zones" / "quay.js").is_file() and (ws.src / "scene.js").is_file()- zone_prompt = next(j.prompt for j in agent.jobs if j.label == "zones_quay_water")- assert "buildFishingBoat" in zone_prompt and "8.00×3.50×3.00" in zone_prompt and "Neighbouring zones" in zone_prompt- assert "2 zone modules in ONE session" in zone_prompt and zone_prompt.count("## This zone") == 2- assert [r.kind for r in rec.rounds] == ["baseline", "refine"] and rec.rounds[0].renders is not None- assert rec.rounds[0].renders.views and rec.status is RunStatus.MAX_ROUNDS- st = RunState.load(ws)- assert {"plan", "skeleton", "assets", "env", "layouts", "zones", "assemble"} <= set(st.stages)- # scene refine tasks route by file ownership: zone → src/zones/<zone>.js- assert any("src/zones/quay.js" in i for i in rec.rounds[1].instructions)---def test_scene_track_deterministic_assembler_and_resume(tmp_path, settings):- plan = ScenePlan.model_validate(plan_example(Track.SCENE))- plan.assets = [a for a in plan.assets if a.kind == "threejs"]- for z in plan.zones:- z.contents = [c for c in z.contents if c in {a.name for a in plan.assets}]- spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0)- ws = Workspace(tmp_path / "runs" / "harbour2")- agent = FakeAgent(_scene_writer)- services = FakeServices(assemble=True)- mk = lambda: SceneTrack(services=services, judge=FakeJudge(scores=(0.6,)), agent=agent, planner_model=_planner(plan.model_dump(mode="json")), # noqa: E731- settings=settings, runtime=FakeRuntime(Language.SCENE_THREEJS))- rec = mk().run(spec, ws)- assert "compose" not in [j.label for j in agent.jobs] and "assembled by fake" in (ws.src / "scene.js").read_text()- n_jobs = len(agent.jobs)- rec2 = mk().run(spec, ws, resume=True)- assert len(agent.jobs) == n_jobs # all stages + baseline cached / loaded- assert len(rec2.rounds) == 1 and rec2.rounds[0].commit == rec.rounds[0].commit--def test_scene_children_are_stages_and_a_failed_env_never_repays_assets(tmp_path, settings):- """Review-3 V3-claim3: assets/env/layouts each cache as their OWN stage, so a- failing sibling leaves the paid asset results cached and resume re-runs only it."""+ """assets/env/layouts cache as their own stages: a failing sibling never re-pays the others."""plan = small_scene()spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0)ws = Workspace(tmp_path / "runs" / "harbour3")@@ -298,9 +146,7 @@ def _mood_replanned(tmp_path, settings, name, *, force):def test_a_mood_only_replan_invalidates_the_env_stage(tmp_path, settings):- """Review-3 V4a: the stage key is the whole plan, so a re-plan differing only in- `mood` misses the cache (it used to serve an env generated under the old mood) — once the- rounds are archived — which `resume --force` does even when the spec is unchanged (Q2)."""+ """Q2: the stage key is the whole plan; `resume --force` archives the rounds, so a mood-only re-plan re-runs env."""labels, events = _mood_replanned(tmp_path, settings, "harbour4", force=True)assert "env" in labels # a stale cached env must not be servedassert "resume.archived" in events and "resume.spec_changed" not in events and "stage.frozen" not in events@@ -308,63 +154,14 @@ def test_a_mood_only_replan_invalidates_the_env_stage(tmp_path, settings):def test_a_drifted_stage_key_never_reruns_a_stage_under_existing_rounds(tmp_path, settings):- """F5: with r00 on disk, a drifted key (81 of 91 recorded scene runs, after ScenePlan.interior)- serves the recorded env / zones instead of re-paying their sessions over the rounds' src/."""+ """F5: with r00 on disk, a drifted key serves the recorded stages instead of re-paying them."""labels, events = _mood_replanned(tmp_path, settings, "harbour5", force=False)assert labels == []assert events.count("stage.frozen") >= 3 # env, zones, assets (at least)assert "stage.start" not in events-class _ProbedSceneRuntime(FakeRuntime):- """The fake scene build, carrying the two reports the real one returns in ``BuildResult.gates``."""-- def build(self, ws, *, timeout_s=None):- res = super().build(ws, timeout_s=timeout_s)- sev = Severity.WARN if res.ok else Severity.ERROR- shader = GateFinding(gate="shader_preflight", severity=sev, target="src/zones/quay.js:3",- message="uniform uTime is read but never bound")- return res.model_copy(update={"gates": [GateReport.of("scene_probe"), GateReport.of("shader_preflight", [shader])]})--[email protected]("broken", [False, True])-def test_the_builds_own_gate_reports_join_the_round(tmp_path, settings, broken):- """scene_probe + shader_preflight reach the round's gates: after the track's own on a built round- (the judge's warning list is capped in gate order), and on a failed build too — where the shader- error is what routes the shader skill (R21) into the next round."""- from codeverse3d.skills.registry import SHADER_COMPILE_OR_BINDING, finding_kinds-- plan = small_scene()- spec = make_spec(Track.SCENE, Language.SCENE_THREEJS, max_rounds=0)- ws = Workspace(tmp_path / "runs" / "probed")-- def _writer(job, ws_):- files = _scene_writer(job, ws_)- return {k: v + f"// {FAIL_MARK}\n" for k, v in files.items()} if broken and job.label.startswith("zones_") else files-- track = SceneTrack(services=FakeServices(assemble=True), judge=FakeJudge(scores=(0.6,)), agent=FakeAgent(_writer),- planner_model=_planner(plan.model_dump(mode="json")), settings=settings,- runtime=_ProbedSceneRuntime(Language.SCENE_THREEJS))- r0 = track.run(spec, ws).rounds[0]- names = [g.gate for g in r0.gates]- assert r0.build.ok is not broken- assert names[0] == "lint:scene_threejs" and names[-2:] == ["scene_probe", "shader_preflight"]- if broken: # nothing but lint ran besides the build- assert names == ["lint:scene_threejs", "scene_probe", "shader_preflight"]- assert (ws.gates_dir(0) / "shader_preflight.json").is_file()- assert SHADER_COMPILE_OR_BINDING in finding_kinds(r0.gates)---def test_get_track_dispatch():- assert isinstance(get_track("static_object"), StaticObjectTrack)- assert isinstance(get_track(Track.SCENE), SceneTrack)--def test_a_render_timeout_degrades_the_round_instead_of_failing_the_run(tmp_path, chair_plan, settings):- """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 under load and the run was recorded `failed` with a- judged round 0 on disk. The round keeps build/gates and skips the judge, so a pick- hands over the judged round 0."""from codeverse3d.spatial.render import RenderErrorclass _Services(FakeServices):diff --git a/harness/tests/orchestrator_tracks/test_transport_retry.py b/harness/tests/orchestrator_tracks/test_transport_retry.pyindex 5096845f..38adff73 100644--- a/harness/tests/orchestrator_tracks/test_transport_retry.py+++ b/harness/tests/orchestrator_tracks/test_transport_retry.py@@ -1,14 +1,5 @@-"""The transport-retry lever: a round killed by the PROVIDER (a 503 storm, a dropped-socket, an overloaded API) is re-run exactly once before the failure may mean anything;-an agent that ran fine and DECLINED the work is still a no_change stop; the vendor's-spent usage limit stops the run as agent_quota.--Shipped after 2026-08-29: rc=247 gemini-cli crashes killed three whole runs at-baseline, and a refine-round crash was delivered as a fake plateau (microscope).-Typed since 2026-09-22: each backend classifies its own CLI's failure-(``AgentResult.transient`` / ``.quota``), the flags ride ``GenerationResult`` into-``RoundFailed``, and the loop reads them — it matched substrings of the joined-notes before, with a vocabulary that had drifted from the backends'."""+"""The transport-retry lever: a round killed by the PROVIDER (typed ``transient``) is re-run+exactly once; a declined round is a no_change stop; a spent vendor quota stops as agent_quota."""from __future__ import annotationsimport pytest@@ -76,25 +67,6 @@ class CrashingAgent(FakeAgent):return super().run(job)-class CrashUntilRetried(FakeAgent):- """Every session at ``crash_round`` dies until the lever's OWN retry event exists- in the workspace event log — so the whole first attempt crashes (task count never- assumed) and the whole retry succeeds, with the boundary written by the lever."""-- def __init__(self, *, crash_round: int):- super().__init__(_writer)- self.crash_round = crash_round-- def run(self, job: AgentJob) -> AgentResult:- ws = Workspace(job.workspace)- retried = any(e["event"] == "round.transport_retry" for e in EventLog(ws.events_path).read())- if job.round == self.crash_round and not retried:- self.jobs.append(job)- return AgentResult(ok=False, exit_reason="error", errors=list(CRASH), usage=Usage(cost_usd=0.01),- transient=True)- return super().run(job)--def after_baseline(failure: AgentResult) -> FakeAgent:"""Baseline works; every refine session ends in ``failure``."""return FakeAgent(lambda job, ws: _writer(job, ws) if job.round == 0 else failure)@@ -119,28 +91,6 @@ def _events(ws: Workspace) -> list[str]:# --------------------------------------------------------------- track behaviour-def test_baseline_transport_crash_is_retried_and_the_run_recovers(tmp_path, chair_plan, settings):- # the ax_umbrella shape: every baseline session dies rc-nonzero with an empty- # response until the lever steps in; before the lever that was the whole run.- agent = CrashUntilRetried(crash_round=0)- ws = Workspace(tmp_path / "runs" / "recover")- rec = _track(agent, (0.55, 0.7, 0.85), chair_plan, settings).run(make_spec(max_rounds=3), ws)- assert rec.status is RunStatus.MAX_ROUNDS and [r.score for r in rec.rounds] == pytest.approx([0.55, 0.7, 0.85, 0.85])- evs = _events(ws)- assert evs.count("round.transport_retry") == 1 and "run.failed" not in evs- assert [r.kind for r in rec.rounds] == ["baseline", "refine", "refine", "refine"]---def test_refine_transport_crash_retries_only_once_then_stops_as_no_change(tmp_path, chair_plan, settings):- agent = CrashingAgent(crash_round=1, crashes=-1)- ws = Workspace(tmp_path / "runs" / "plateau")- rec = _track(agent, (0.55,), chair_plan, settings).run(make_spec(max_rounds=3), ws)- assert rec.status is RunStatus.NO_CHANGE and rec.extra["stop_reason"] == "no_change"- assert [r.score for r in rec.rounds] == pytest.approx([0.55]) # the baseline is still recorded- evs = _events(ws)- assert evs.count("round.transport_retry") == 1 # exactly once, never a loop- assert "round.no_change" in evs-def test_baseline_transport_crash_is_retried_once_then_fails(tmp_path, chair_plan, settings):agent = CrashingAgent(crash_round=0, crashes=-1)@@ -153,8 +103,7 @@ def test_baseline_transport_crash_is_retried_once_then_fails(tmp_path, chair_pla@pytest.mark.parametrize("refine", [UNTYPED_CRASH, IDLE], ids=["untyped_crash", "idle"])def test_an_untyped_crash_or_an_idle_session_is_a_no_change_stop_not_a_retry(tmp_path, chair_plan, settings, refine):- """The words "response=<empty>" used to buy a retry of the whole round; only the backend's- own verdict does now (0 of 34 recorded gemini-cli error exits lacked a provider signature)."""+ """Only the backend's typed verdict buys a retry, never words in the notes."""ws = Workspace(tmp_path / "runs" / "crash")rec = _track(after_baseline(refine), (0.55,), chair_plan, settings).run(make_spec(max_rounds=3), ws)assert rec.status is RunStatus.NO_CHANGEdiff --git a/harness/tests/orchestrator_tracks/test_write_scope.py b/harness/tests/orchestrator_tracks/test_write_scope.pyindex 2d005d1a..9165a063 100644--- a/harness/tests/orchestrator_tracks/test_write_scope.py+++ b/harness/tests/orchestrator_tracks/test_write_scope.py@@ -1,12 +1,4 @@-"""Write-scope enforcement at the task layer.--* the single-shot envelope (``write_files(only=...)``) skips a pre-existing path the- task does not own — new files stay allowed, the entry only when owned;-* ``GenerationTask.owns_entry`` → ``AgentJob.always_writable`` wiring;-* the constructors whose plans are file-disjoint by construction (scoped baseline,- zones, threejs assets, parallel refine groups) now set- ``edit_only=True`` so the split they promise is enforced, not just prompted.-"""+"""Write-scope enforcement at the task layer: envelope scope, harness-owned paths, scoped constructors."""from __future__ import annotations@@ -22,7 +14,6 @@ from codeverse3d.tracks.generation import (GenerationTask,_always_writable,generate_files,- run_agent_task,write_files,)from codeverse3d.tracks.planner import plan_example@@ -35,23 +26,6 @@ from .conftest import make_specfrom .fakes import FakeAgent, FakeRuntime, FakeServices-# --------------------------------------------------------------------------- envelope-def test_write_files_only_skips_existing_out_of_scope_paths(tmp_ws: Workspace):- (tmp_ws.src / "parts").mkdir(parents=True, exist_ok=True)- (tmp_ws.src / "zones").mkdir(parents=True, exist_ok=True)- (tmp_ws.src / "parts" / "a.js").write_text("// old a\n")- (tmp_ws.src / "zones" / "q.js").write_text("// old q\n")- skipped: list[tuple[str, str]] = []- files = {"src/parts/a.js": "// new a", "src/zones/q.js": "// new q", "src/parts/new.js": "// new"}- changes = write_files(tmp_ws, files, only={"src/parts/a.js"},- on_skip=lambda p, r: skipped.append((p, r)))- assert [c.path for c in changes] == ["src/parts/a.js", "src/parts/new.js"]- assert (tmp_ws.src / "zones" / "q.js").read_text() == "// old q\n"- assert skipped == [("src/zones/q.js", skipped[0][1])] and "scope" in skipped[0][1]- # only=None keeps the old behaviour: everything valid is written- assert [c.path for c in write_files(tmp_ws, {"src/zones/q.js": "// new q"})] == ["src/zones/q.js"]--def test_write_files_normalises_a_path_before_the_owned_and_scope_checks(tmp_ws: Workspace):"""B1: `src//lib/x.js`, `src/./lib/x.js` and `src//recipes.glsl` ARE the harness-owned files —un-normalised they slipped past `is_harness_owned` and the edit_only scope and were written."""@@ -105,28 +79,7 @@ def test_generate_files_enforces_the_task_scope(tmp_path):assert all("scope" in e["reason"] for e in skips)-def test_generate_files_lets_an_owner_write_the_entry(tmp_path):- ws = _envelope_ws(tmp_path)- task = GenerationTask(label="refine_a", prompt="p", files_hint=["src/parts/a.js"],- edit_only=True, owns_entry=True)- res = generate_files(ws, model=scripted([(ANSWER, "STOP")]), task=task,- events=EventLog(tmp_path / "e.jsonl"))- assert res.ok and (ws.src / "object.js").read_text() == "// new entry\n"- assert (ws.src / "parts" / "b.js").read_text() == "// b\n", "b stays out of scope"---def test_generate_files_without_edit_only_is_unchanged(tmp_path):- ws = _envelope_ws(tmp_path)- task = GenerationTask(label="baseline", prompt="p", files_hint=["src/parts/a.js"])- generate_files(ws, model=scripted([(ANSWER, "STOP")]), task=task,- events=EventLog(tmp_path / "e.jsonl"))- assert (ws.src / "object.js").read_text() == "// new entry\n"- 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")@@ -141,11 +94,8 @@ def test_generate_files_never_rewrites_a_harness_owned_file(tmp_path):assert skip["path"] == "src/recipes.glsl" and "harness-owned" in skip["reason"]-def test_generate_files_never_writes_under_a_harness_owned_directory(tmp_path):- """``HARNESS_OWNED_SRC`` names ``src/lib/`` as a DIRECTORY; the envelope checked by exact- match, so a single-shot answer could overwrite the effect library (B1, 2026-09-22) while- the CLI path (``is_harness_owned``) reverted the same write."""+ """B1: ``src/lib/`` is a harness-owned DIRECTORY; the envelope checks it by prefix."""ws = Workspace(tmp_path / "ws").create()ws.write_json(ws.spec_path, {"language": "scene_threejs", "track": "scene"})(ws.src / "lib").mkdir(parents=True)@@ -170,16 +120,6 @@ def test_always_writable_requires_ownership():assert _always_writable("", part) == [] and _always_writable("nope", part) == []-def test_run_agent_task_wires_entry_ownership_into_the_job(tmp_ws: Workspace):- tmp_ws.write_json(tmp_ws.spec_path, {"language": "threejs", "track": "static_object"})- agent = FakeAgent(lambda job, ws: {"src/parts/seat.js": "// seat\n"})- part = GenerationTask(label="detail_seat", prompt="p", files_hint=["src/parts/seat.js"], edit_only=True)- res = run_agent_task(tmp_ws, agent=agent, task=part)- assert res.ok and agent.jobs[0].edit_only is True and agent.jobs[0].always_writable == []- run_agent_task(tmp_ws, agent=agent, task=part.model_copy(update={"owns_entry": True, "label": "d2"}))- assert agent.jobs[1].always_writable == ["src/object.js"]--# --------------------------------------------------------------------------- constructorsdef _big_plan(n: int = 8) -> StaticPlan:parts = [PartPlan(name="Body", role="main mass", description="the shell",diff --git a/harness/tests/orchestrator_tracks/test_zone_layout.py b/harness/tests/orchestrator_tracks/test_zone_layout.pyindex 2c87f28a..9b2345f4 100644--- a/harness/tests/orchestrator_tracks/test_zone_layout.py+++ b/harness/tests/orchestrator_tracks/test_zone_layout.py@@ -42,10 +42,7 @@ def test_validator_accepts_a_buildable_layout_and_names_every_problem():def test_an_aerial_camera_does_not_reject_the_placements_beneath_it():- """PR #3 review: the clearance check is 2D, so an establishing camera 8 m up- rejected every large cluster under it and the zone lost its whole layout.- A lens above the cluster top (+ margin) cannot be inside the geometry; a lens- AT stall height directly above the cluster is still rejected."""+ """A lens above the cluster top is clear; a lens at stall height above it is still rejected."""plan = _plan()plan.cameras = [CameraPlan(name="aerial", position=(10, 8, 0), look_at=(10, 0, 0), fov=50, purpose="p")]under = _layout(placements=[{"asset": "Stall", "count": 4, "cluster": (10.0, 0.0), "spread_m": 3.0}],@@ -56,26 +53,8 @@ def test_an_aerial_camera_does_not_reject_the_placements_beneath_it():assert "camera low" in complaint, "a lens at stall height above the cluster is still inside its reach"-def test_validator_rejects_a_cluster_that_swallows_a_camera():- """fv_izakaya_night: BarCounter 0.7 m from the PotDetail camera — the lens sat inside- the counter and camera_in_geometry capped all three rounds. The camera list is an- input to the layout, so the validator must reject this before a builder sees it."""- plan = _plan() # camera 'overview' at (1, 1, 1)- bad = _layout(placements=[{"asset": "Stall", "count": 1, "cluster": (1.2, 0.8), "spread_m": 0.0}],- zone="Market")- complaint = validate_layout(bad, plan.zones[1], plan)- assert "camera overview" in complaint and "lens stays outside" in complaint- # the dg_izakaya lesson: an asset NEAR a camera but out of its reach is legal —- # a 0.3 m-foot lantern 1.5 m from the lens must never be rejected- near_ok = _layout(placements=[{"asset": "Bollard", "count": 2, "cluster": (2.0, 2.0), "spread_m": 0.4}],- zone="Market")- assert "camera" not in validate_layout(near_ok, plan.zones[1], plan)--def test_validator_rejects_two_large_assets_on_one_spot_but_spares_adjacency():- """fv2_alpine: RetainingWall x PrayerBench interpenetrated because their clusters- coincided. The rule is deliberately narrow: small footprints (a stool against a- counter) and support relations (bottles ON the bar) must pass untouched."""+ """Narrow rule: small footprints and declared support relations pass untouched."""plan = _plan()stacked = _layout(placements=[{"asset": "FishingBoat", "count": 1, "cluster": (-12.0, 3.0), "spread_m": 0.0},@@ -104,18 +83,6 @@ def test_layout_block_renders_numbers_the_builder_can_follow():assert layout_block(None) == ""-def test_layout_zones_runs_per_zone_and_reasks_once_with_the_complaint():- plan = _plan()- good_quay = _layout().model_dump(mode="json")- bad_quay = _layout(placements=[{"asset": "Kraken", "count": 1, "cluster": (0.0, 0.0), "spread_m": 1.0}]).model_dump(mode="json")- good_market = {"zone": "Market", "placements": [{"asset": "Stall", "count": 4, "cluster": (10.0, 0.0), "spread_m": 5.0}]}- # zones fan out with max_workers=1 so the scripted queue stays ordered- model = FakeChatModel([bad_quay, good_quay, good_market])- out = layout_zones(plan, model, max_workers=1)- assert set(out) == {"Quay", "Market"} and len(model.requests) == 3- assert out["Quay"].placements[0].asset == "Bollard"--def test_layout_zones_drops_a_twice_rejected_zone_instead_of_dying():plan = _plan()bad = {"zone": "Quay", "placements": [{"asset": "Kraken", "count": 1, "cluster": (0.0, 0.0), "spread_m": 1.0}]}@@ -125,9 +92,6 @@ def test_layout_zones_drops_a_twice_rejected_zone_instead_of_dying():def test_a_run_past_its_ceiling_buys_no_layout_calls():- """Review-3 S3 (V5-claim2): past the hard ceiling, layout_zones makes ZERO model- calls and returns no layouts (the documented degraded mode) instead of buying up- to 2 x 300 s per zone."""import timefrom codeverse3d.contracts.common import Budget@@ -137,20 +101,3 @@ def test_a_run_past_its_ceiling_buys_no_layout_calls():guard = BudgetGuard(Budget(max_minutes=30), start_time=time.time() - 45 * 60)out = layout_zones(_plan(), model, budget=guard, max_workers=1)assert out == {} and len(model.requests) == 0---def test_layout_waits_are_clipped_to_the_remaining_run_clock():- """A call that does go out asks for min(LAYOUT_WAIT_S, wall clock left), floored."""- import time-- from codeverse3d.contracts.common import Budget- from codeverse3d.orchestrator import BudgetGuard-- good_quay = _layout().model_dump(mode="json")- good_market = {"zone": "Market", "placements": [{"asset": "Stall", "count": 4, "cluster": (10.0, 0.0), "spread_m": 5.0}]}- model = FakeChatModel([good_quay, good_market])- guard = BudgetGuard(Budget(max_minutes=30), start_time=time.time() - 28 * 60) # ~2 min left- out = layout_zones(_plan(), model, budget=guard, max_workers=1)- assert set(out) == {"Quay", "Market"}- waits = [r.max_wait_s for r in model.requests]- assert waits and all(20 <= w <= 125 for w in waits), waits