Skip to content

Official Codebase of 3DCodeVerse

Python

orchestrator: fixed rounds — baseline + max_rounds, stopped only by the clock or a hard failure

gaoypeng75b5752d43c4
diff --git a/eval/tests/conftest.py b/eval/tests/conftest.py
index c217b7cd..1cc37b90 100644
--- a/eval/tests/conftest.py
+++ b/eval/tests/conftest.py
@@ -131,7 +131,7 @@ def fake_run_track(score: float = 0.8):
(ws.root / MODEL_FILE).write_text(GOOD.format(score=score))
(ws.src / "parts").mkdir(exist_ok=True)
(ws.src / "parts" / "legs.py").write_text("LEGS = 3\n")
- rec = RunRecord(spec=spec, workspace=str(ws.root), status=RunStatus.PASSED, final_score=score - 0.1,
+ rec = RunRecord(spec=spec, workspace=str(ws.root), status=RunStatus.MAX_ROUNDS, final_score=score - 0.1,
total_usage=Usage(cost_usd=0.9, tool_calls=12))
ws.write_json(ws.record_path, rec)
return rec
diff --git a/eval/tests/test_bench.py b/eval/tests/test_bench.py
index f7723ad8..70c55a10 100644
--- a/eval/tests/test_bench.py
+++ b/eval/tests/test_bench.py
@@ -45,7 +45,7 @@ def _fake_run_fn(scores_by_id: dict[str, tuple[float, float]], fail_ids: set[str
scores=scores_by_id.get(pid, (0.5, 0.7)))
rec.spec = spec
ws.write_json(ws.spec_path, spec)
- rec.status = RunStatus.PASSED if rec.final_score and rec.final_score >= 0.75 else RunStatus.PLATEAU
+ rec.status = RunStatus.MAX_ROUNDS
ws.write_json(ws.record_path, rec)
return rec
return run
diff --git a/eval/tests/test_compare_matrix.py b/eval/tests/test_compare_matrix.py
index 9052217b..bb535bfa 100644
--- a/eval/tests/test_compare_matrix.py
+++ b/eval/tests/test_compare_matrix.py
@@ -103,7 +103,7 @@ def test_matrix_end_to_end_with_fakes(tmp_path: Path):
by = {(r.prompt_id, r.arm): r for r in rows}
h = by[("cmp_easy_stool", "harness:gemini-cli:gemini-3.6-flash")]
assert h.status == "scored" and h.score == pytest.approx(0.9) and h.passed and h.build_ok
- assert h.gen_cost_usd == pytest.approx(0.9) and h.harness_status == "passed" and h.harness_loop_score == pytest.approx(0.8)
+ assert h.gen_cost_usd == pytest.approx(0.9) and h.harness_status == "max_rounds" and h.harness_loop_score == pytest.approx(0.8)
assert h.judge_cost_usd == pytest.approx(0.01) and h.tris == 900 and Path(h.sheet).is_file()
assert (Path(h.workspace) / "run" / "src" / "model.py").is_file() and (Path(h.workspace) / "eval" / "eval.json").is_file()
assert (Path(h.workspace) / "eval" / "src" / "parts" / "legs.py").is_file() # whole src/ tree is evaluated
diff --git a/eval/tests/test_degraded.py b/eval/tests/test_degraded.py
index 88149e37..ba93d2e3 100644
--- a/eval/tests/test_degraded.py
+++ b/eval/tests/test_degraded.py
@@ -48,7 +48,7 @@ def _track(status: RunStatus, stop_reason: str, rounds: int, cost: float, aborte
(RunStatus.BUDGET, "budget", 0, 0.9, 1, True), # never completed a round
(RunStatus.BUDGET, "budget", 2, 1.5, 1, False), # iterated twice: cut, but not degraded
- (RunStatus.PASSED, "pass", 1, 0.8, 0, False), # passed after one round: fine
+ (RunStatus.MAX_ROUNDS, "max_rounds", 1, 0.8, 0, False), # ran every round it was given: fine
])
def test_flag_degraded_rule(tmp_path, status, stop, rounds, cost, aborted, expect):
battery = Battery.load(BATTERY)
diff --git a/harness/codeverse3d/cli/_common.py b/harness/codeverse3d/cli/_common.py
index a566fce4..77f7fe46 100644
--- a/harness/codeverse3d/cli/_common.py
+++ b/harness/codeverse3d/cli/_common.py
@@ -311,9 +311,7 @@ def round_policy_options(spec: Spec, settings: Any | None = None) -> dict[str, A
Only the judge sample count needs a ``RoundPolicy`` (rounds travel on
``spec.budget``, best-of-N on ``spec.options``), so a run at the default
- ``n=1`` gets **no** policy and keeps the track's own. The rubric stop target
- and the detail-round budget are bound by ``BaseTrack`` for an injected policy
- too, so nothing else is set here."""
+ ``n=1`` gets **no** policy and keeps the track's own."""
settings = settings or get_settings()
samples = int(getattr(settings.judge, "samples", 1) or 1)
if samples <= 1:
diff --git a/harness/codeverse3d/cli/main.py b/harness/codeverse3d/cli/main.py
index 8b5fa20d..43072421 100644
--- a/harness/codeverse3d/cli/main.py
+++ b/harness/codeverse3d/cli/main.py
@@ -551,11 +551,11 @@ def _finished_reason(ws, raised: dict) -> str:
"""Why this run must not be re-entered, or "" when resuming it is meaningful.
A run that reached a terminal state has nothing to resume, and re-entering it is
- destructive, not idempotent: `3dcode resume` on a run that ended stop_reason='pass'
- re-ran the plan stage as a real billed model call and rewrote run_state.status from
- 'passed' back to 'planning', leaving a finished run stuck mid-pipeline while still
- holding its best_score. A BUDGET stop is the documented exception — raising a cap is
- how you continue one — so it only blocks when no cap was raised.
+ destructive, not idempotent: `3dcode resume` on a finished run re-ran the plan stage
+ as a real billed model call and rewrote run_state.status back to 'planning', leaving
+ a finished run stuck mid-pipeline. Two stops are the documented exceptions — raising
+ the cap a run stopped on is how you continue it: BUDGET (any raised cap) and
+ MAX_ROUNDS (a raised ``--rounds``; the run goes on from its last round).
"""
from codeverse3d.contracts.run import RunStatus
from codeverse3d.orchestrator import RunState, StateCorrupt
@@ -566,16 +566,16 @@ def _finished_reason(ws, raised: dict) -> str:
return "" # let the track report it the way it always has
if state is None:
return ""
- if state.status in (RunStatus.PASSED, RunStatus.PLATEAU) or (
- state.status is RunStatus.BUDGET and not raised
- ):
- detail = f"status={state.status.value}" + (
- f" stop_reason={state.stop_reason!r}" if state.stop_reason else ""
- )
- if state.status is RunStatus.BUDGET:
- return f"{detail}: raise a cap to continue it (--max-minutes / --rounds)"
- return f"{detail} best_score={state.best_score}"
- return ""
+ status = state.status
+ detail = f"status={status.value}" + (
+ f" stop_reason={state.stop_reason!r}" if state.stop_reason not in ("", status.value) else ""
+ )
+ if status is RunStatus.BUDGET:
+ return "" if raised else f"{detail}: raise a cap to continue it (--max-minutes / --rounds)"
+ if status is RunStatus.MAX_ROUNDS:
+ return "" if "max_rounds" in raised else f"{detail}: raise --rounds to continue it"
+ finished = (RunStatus.STOPPED, RunStatus.NO_CHANGE, RunStatus.NO_REFINE_TASKS, RunStatus.JUDGE_UNAVAILABLE)
+ return detail if status in finished else ""
@app.command()
diff --git a/harness/codeverse3d/contracts/run.py b/harness/codeverse3d/contracts/run.py
index 5de378a0..9dd7137f 100644
--- a/harness/codeverse3d/contracts/run.py
+++ b/harness/codeverse3d/contracts/run.py
@@ -174,13 +174,27 @@ class RunId(BaseModel):
class RunStatus(StrEnum):
+ """Where a run is — and once it has stopped, only WHY it stopped. Never a verdict:
+ since 2026-09-22 a run is the baseline plus ``max_rounds`` refine rounds, cut short
+ only by the clock or a hard failure, and which round to hand over is a reader's
+ question (``codeverse3d.addons.select``)."""
+
PLANNING = "planning"
GENERATING = "generating"
REFINING = "refining"
- PASSED = "passed"
- PLATEAU = "plateau"
- BUDGET = "budget"
+ MAX_ROUNDS = "max_rounds" # every round the budget asked for ran
+ BUDGET = "budget" # the wall clock (``max_minutes``) ran out
+ AGENT_QUOTA = "agent_quota" # the vendor's usage limit, not ours
+ NO_CHANGE = "no_change" # a refine round's sessions all failed / changed nothing
+ NO_REFINE_TASKS = "no_refine_tasks" # the last round left nothing to ask for
+ JUDGE_UNAVAILABLE = "judge_unavailable" # the last round has no verdict, even after a re-judge
FAILED = "failed"
+ #: a run recorded before 2026-09-22 that ended on a judgement stop (``passed`` / ``plateau``)
+ STOPPED = "stopped"
+
+ @classmethod
+ def _missing_(cls, value: object) -> RunStatus | None:
+ return cls.STOPPED if value in ("passed", "plateau") else None
class PairwiseNote(BaseModel):
diff --git a/harness/codeverse3d/cost/types.py b/harness/codeverse3d/cost/types.py
index 5e7a19bb..ad8b37d5 100644
--- a/harness/codeverse3d/cost/types.py
+++ b/harness/codeverse3d/cost/types.py
@@ -74,9 +74,9 @@ _LABEL_STAGES: tuple[tuple[str, Stage], ...] = (
("env", Stage.ENV),
("baseline", Stage.BASELINE),
("refine", Stage.REFINE),
- # the static track's surface-detail round (labels "detail" / "detail_<scope>",
- # lifecycle.DEFAULT_DETAIL_ROUNDS=1 so it runs by default) is a refine pass under
- # another name; without this its ledger row AND generation.task_stage said "other"
+ # the static track's surface-detail round (labels "detail" / "detail_<scope>") was a
+ # refine pass under another name. The round went on 2026-09-22; the row stays so the
+ # runs that recorded one still reconstruct its sessions as refine, not "other".
("detail", Stage.REFINE),
("candidate", Stage.CANDIDATE),
("cand", Stage.CANDIDATE),
diff --git a/harness/codeverse3d/orchestrator.py b/harness/codeverse3d/orchestrator.py
index a5248e31..dc69e75d 100644
--- a/harness/codeverse3d/orchestrator.py
+++ b/harness/codeverse3d/orchestrator.py
@@ -1,5 +1,5 @@
-"""Orchestration: the stage runner with resume, run state, the round loop
-(RoundPolicy / StopPolicy / pick_best_round), refine-task compilation and the budget.
+"""Orchestration: the stage runner with resume, run state, the round policy
+(RoundPolicy / pick_best_round), refine-task compilation and the budget.
One module since 2026-08-28: the seven-file package predates the 1,500-line cap,
nobody ever imported the package itself, and refine_tasks existed only to be
@@ -28,7 +28,6 @@ from codeverse3d.contracts.plan import AcceptanceItem, Plan
from codeverse3d.contracts.run import RoundRecord, RunStatus
from codeverse3d.conventions import to_snake
from codeverse3d.cost.billing import bills_usd
-from codeverse3d.cost.routing import JUDGE_NOISE
from codeverse3d.proc import EventLog
from codeverse3d.workspace import Workspace
@@ -439,280 +438,19 @@ def _acceptance_target(item: AcceptanceItem, known: dict[str, str]) -> str:
# ===================================================================== rounds
-StopReason = Literal["pass", "plateau", "budget", "continue", "max_rounds", "judge_unavailable",
- "regression", "diminishing_returns", "agent_quota"]
-
-#: what the next round should look like when the loop continues
-Strategy = Literal["same", "switch", "detail"]
-
-#: ``RoundRecord.kind`` of a round that already changed strategy after a regression
-REWRITE_KIND = "rewrite"
-#: ``RoundRecord.kind`` of the surface-detail round (see :func:`detail_round_due`)
-DETAIL_KIND = "detail"
-
-#: ``Strategy`` → the ``RoundRecord.kind`` the loop stamps on the round it starts (unknown → refine)
-KIND_FOR_STRATEGY: dict[str, str] = {"same": "refine", "switch": REWRITE_KIND, "detail": DETAIL_KIND}
-
-#: σ for a judge that is not in the measured table: the default judge's
-#: (``gemini-3.1-pro-preview``, ``Settings.default_judge``), because that is what
-#: an unnamed judge almost always is. Calibrate a new judge
-#: (``python -m codeverse3d.addons.calibration``) and add it to JUDGE_NOISE rather
-#: than tuning the multipliers around it.
-DEFAULT_JUDGE_SIGMA = 0.030
-
-
-def judge_sigma(judge_model: str = "", *, default: float = DEFAULT_JUDGE_SIGMA) -> float:
- """Measured score noise (std) of one judge model.
-
- The numbers come from ``judges/calibration.py`` (n=3 on the e2e rounds) and
- are tabulated ONCE in :data:`codeverse3d.cost.routing.JUDGE_NOISE`; this is
- the only reader in the orchestrator. Accepts a bare model name or a full
- backend id (``gemini:gemini-3.1-pro-preview``)."""
- name = (judge_model or "").strip().split(":")[-1]
- if not name:
- return default
- hit = JUDGE_NOISE.get(name)
- if hit is None: # version suffixes: gemini-3.7-flash-002 → gemini-3.7-flash
- hit = next((v for k, v in JUDGE_NOISE.items() if name.startswith(k)), None)
- return float(hit[0]) if hit else default
-
-
@dataclass(frozen=True)
class RoundPolicy:
- """Calibrated knobs for the refine loop."""
+ """The refine loop's knobs. There is no stop knob besides ``max_rounds``: a run is the
+ baseline plus ``max_rounds`` refine rounds, cut short only by the clock or a hard
+ failure (owner, 2026-09-22 — the pass / plateau / regression / diminishing-returns
+ stops, the rewrite and the surface-detail rounds they drove are gone)."""
max_rounds: int = 4 # refine rounds AFTER the baseline
- plateau_window: int = 2 # consecutive scored rounds without min_delta gain
- min_delta: float = 0.02
- target: float = 0.8 # rubric pass threshold (overridden from the rubric when known)
max_refine_tasks: int = 6
max_instructions_per_task: int = 6 # lines handed to ONE generation task (grouped by target)
parallel_min_tasks: int = 2 # fan out only when >= this many file-disjoint groups
n_candidates: int = 1 # best-of-N baseline (candidates generated in parallel, best kept)
- pairwise_margin: float = 0.03 # |Δscore| below this = judge noise → pairwise tie-break
- pairwise_min_confidence: float = 0.6 # new round replaces best only when pairwise is this sure
judge_samples: int = 1 # VLM judge samples per round (flash: std ≈ 0.001 between samples → 1 is enough)
- # ---- money stops (docs/COST.md §5); thresholds are multiples of the judge's measured σ
- judge_model: str = "" # judge backend id → σ via judge_sigma(); "" = the default judge's σ
- regression_sigma: float = 1.0 # a round below (best − this × σ) regressed: change shape or stop
- marginal_sigma: float = 1.5 # from marginal_from_round on, the last gain must beat this × σ
- marginal_from_round: int = 3 # first refine round index the marginal-value test applies to
- # ---- depth. Measured (wave "generation-depth"): across 88 consecutive refine-round pairs the
- # built part count changed ZERO times and mean Δgeometry_detail was +0.003 — the refine loop is
- # a repair loop and never adds anything. The rounds that DID add geometry did it while assembly
- # was still broken and lost 0.075 of assembly_fit / 0.025 of overall for it. So detail gets its
- # own round, and it only runs once the structure gates are clean.
- detail_rounds: int | None = None # surface-detail rounds a run may spend: 0 = off, None = the track's own
- # default (lifecycle.detail_round_budget; only tracks with the round get one)
- detail_min_score: float = 0.45 # below this the object is still wrong; detail would be polish on a mistake
- detail_bbox_tol_m: float = 0.005 # a detail round that moves a part box by more than this failed its brief
-
- @property
- def sigma(self) -> float:
- """Measured judge noise for this run's judge (see :func:`judge_sigma`)."""
- return judge_sigma(self.judge_model)
-
- @property
- def regression_delta(self) -> float:
- """How far below the best a round must score to count as a regression."""
- return self.regression_sigma * self.sigma
-
- @property
- def marginal_delta(self) -> float:
- """Gain the previous round must have produced for r03+ to be worth starting."""
- return self.marginal_sigma * self.sigma
-
-
-def meaningful_regression(score: float | None, before: float | None, policy: RoundPolicy) -> bool:
- """Did ``score`` fall below ``before`` by MORE than this judge's own noise?
-
- THE regression predicate: ``StopPolicy._regression`` (the stop gate) and
- ``StopPolicy._regressions`` (the counter behind "a second regression stops
- the run") both call it, so they cannot drift apart. The scale is the
- measured per-judge sigma table via ``policy.regression_delta`` — deliberately
- NOT the 0.202 A/A replay floor, which measures cross-run planner variance,
- not judge noise."""
- if score is None or before is None:
- return False
- return (before - score) > policy.regression_delta
-
-
-@dataclass(frozen=True)
-class StopDecision:
- """``StopPolicy``'s answer: stop (and why), or continue (and in what shape)."""
-
- reason: StopReason
- strategy: Strategy = "same"
- detail: str = ""
-
- @property
- def stop(self) -> bool:
- return self.reason != "continue"
-
- def event(self) -> dict[str, object]:
- return {"reason": self.reason, "strategy": self.strategy, "detail": self.detail}
-
-
-class StopPolicy:
- """Decide whether the loop goes on. ``history`` = rounds so far (baseline first)."""
-
- def __init__(self, policy: RoundPolicy):
- self.policy = policy
-
- def evaluate(self, history: Sequence[RoundRecord], *, budget_ok: bool = True) -> StopDecision:
- if not budget_ok:
- return StopDecision("budget")
- if not history:
- return StopDecision("continue")
- last = history[-1]
- if last.judgment is not None and last.judgment.passed and last.judgment.overall >= self.policy.target:
- return StopDecision("pass")
- refine_rounds = len(history) - 1
- if refine_rounds >= self.policy.max_rounds:
- return StopDecision("max_rounds")
- # Order is the economics. A regression whose strategy switch is already spent
- # is the most specific answer there is, so it comes first. Otherwise the
- # marginal-value test decides late rounds (at r03 no *shape* is worth $0.5),
- # and only before that does a first regression buy one change of shape.
- # Plateau is the fallback: the same money statement, less precisely.
- exhausted = self._regression(history, switch=False)
- if exhausted is not None:
- return self._maybe_detail(history, exhausted)
- marginal = self._diminishing(history)
- if marginal is not None:
- return self._maybe_detail(history, marginal)
- regressed = self._regression(history)
- if regressed is not None:
- return regressed
- if self._plateaued(history):
- return self._maybe_detail(history, StopDecision("plateau"))
- return StopDecision("continue")
-
- def _maybe_detail(self, history: Sequence[RoundRecord], stop: StopDecision) -> StopDecision:
- """Convert a "we are done repairing" stop into ONE surface-detail round.
-
- Only from a stop the loop was going to take anyway, so the detail round is
- never bought instead of a repair round — and only on a clean, best-scoring
- artifact, because the rounds that added geometry while assembly was still
- broken measurably lost score (module docstring / ``detail_rounds``)."""
- if stop.reason not in ("plateau", "diminishing_returns"):
- return stop
- why = detail_blocked(history, self.policy)
- if why:
- return stop
- return StopDecision("continue", strategy="detail",
- detail=f"structure clean at r{history[-1].index:02d} → one surface-detail round "
- f"({stop.reason} otherwise)")
-
- # ---------------------------------------------------------------- money stops
- def _regression(self, history: Sequence[RoundRecord], *, switch: bool = True) -> StopDecision | None:
- """The last round scored below the best by more than the judge's own noise.
-
- Another round of the SAME shape is not justified by that evidence: the
- first regression buys one change of strategy (a whole-artifact rewrite),
- a second one — or one after a rewrite already failed to recover — stops
- the run. ``switch=False`` asks only "is the switch already spent?", which
- is the question that outranks every other stop."""
- last = history[-1]
- score, best_before = last.score, best_score(history[:-1])
- if not meaningful_regression(score, best_before, self.policy):
- return None
- drop = best_before - score
- detail = (f"r{last.index:02d} scored {score:.3f} vs best {best_before:.3f} "
- f"({-drop:+.3f}, judge σ {self.policy.sigma:.3f})")
- if last.kind == REWRITE_KIND or self._regressions(history) > 1:
- return StopDecision("regression", detail=detail + " — a changed strategy did not recover it")
- return StopDecision("continue", strategy="switch", detail=detail) if switch else None
-
- def _diminishing(self, history: Sequence[RoundRecord]) -> StopDecision | None:
- """From ``marginal_from_round`` on, only run when the last round actually
- bought something (> ``marginal_sigma`` × σ) and the target is still open."""
- nxt = len(history)
- if nxt < self.policy.marginal_from_round:
- return None
- gain = last_gain(history)
- best = best_score(history)
- need = self.policy.marginal_delta
- if gain is None:
- return None
- if gain <= need:
- return StopDecision("diminishing_returns",
- detail=f"r{nxt:02d} not started: last gain {gain:+.3f} ≤ {need:.3f} "
- f"({self.policy.marginal_sigma:g} × judge σ {self.policy.sigma:.3f})")
- if best is not None and best >= self.policy.target:
- return StopDecision("diminishing_returns",
- detail=f"r{nxt:02d} not started: best {best:.3f} already at target "
- f"{self.policy.target:.2f}")
- return None
-
- def _regressions(self, history: Sequence[RoundRecord]) -> int:
- """How many scored rounds ended MEANINGFULLY below the best of everything
- before them. Same predicate as the gate (:func:`meaningful_regression`),
- so a sub-noise dip can never help burn the run's single strategy switch
- (a -0.005 blip + one real regression used to count 2 = "regression" stop
- with the switch never offered)."""
- return sum(1 for i in range(1, len(history))
- if meaningful_regression(history[i].score, best_score(history[:i]), self.policy))
-
- def _plateaued(self, history: Sequence[RoundRecord]) -> bool:
- """True when the last ``plateau_window`` scored rounds did not raise the best
- score by ``min_delta``. Rounds without a judgment (build failures) do not
- count as evidence of a plateau: a pending repair explains a flat score."""
- scored = [r for r in history if r.score is not None]
- w = self.policy.plateau_window
- if len(scored) < w + 1:
- return False
- before = max(r.score for r in scored[:-w]) # type: ignore[type-var]
- after = max(r.score for r in scored[-w:]) # type: ignore[type-var]
- return (after - before) < self.policy.min_delta
-
-
-def detail_blocked(history: Sequence[RoundRecord], policy: RoundPolicy) -> str:
- """"" when a surface-detail round is due; otherwise the reason it is not.
-
- A detail round is worth money only on an artifact whose STRUCTURE is finished:
- the last round built, has no gate ERROR, scored at least ``detail_min_score``
- and is within one judge σ of the best round in the run. Anything else and the
- money belongs to repair (measured: refine rounds that added > 2000 triangles
- while assembly was still broken lost 0.075 of assembly_fit)."""
- if (policy.detail_rounds or 0) <= 0:
- return "detail rounds disabled"
- spent = sum(1 for r in history if r.kind == DETAIL_KIND)
- if spent >= (policy.detail_rounds or 0):
- return f"{spent} detail round(s) already spent"
- if not history:
- return "no rounds yet"
- last = history[-1]
- if last.build is None or not last.build.ok:
- return "last round did not build"
- if gate_error_count(last) > 0:
- return f"{gate_error_count(last)} gate error(s) still open"
- if last.score is None:
- return "last round was not judged"
- if last.score < policy.detail_min_score:
- return f"score {last.score:.3f} < detail floor {policy.detail_min_score:.2f}"
- best = best_score(history)
- if best is not None and last.score < best - policy.sigma:
- return f"last round {last.score:.3f} is below best {best:.3f} by more than σ"
- return ""
-
-
-def best_score(history: Sequence[RoundRecord]) -> float | None:
- """Best judged score in ``history`` (``None`` when nothing was scored)."""
- scores = [r.score for r in history if r.score is not None]
- return max(scores) if scores else None
-
-
-def last_gain(history: Sequence[RoundRecord]) -> float | None:
- """How much the LAST round moved the best score (``None`` when unscored).
-
- Negative when it regressed; 0.0 when it changed nothing measurable."""
- if len(history) < 2 or history[-1].score is None:
- return None
- before = best_score(history[:-1])
- if before is None:
- return None
- return float(history[-1].score) - before
def pick_best_round(rounds: Sequence[RoundRecord]) -> int | None:
diff --git a/harness/codeverse3d/prompts/system/role_detail.j2 b/harness/codeverse3d/prompts/system/role_detail.j2
deleted file mode 100644
index 86574fca..00000000
--- a/harness/codeverse3d/prompts/system/role_detail.j2
+++ /dev/null
@@ -1,4 +0,0 @@
-For this task you are adding SURFACE DETAIL to a model whose structure is already accepted.
-You may not move, resize, rename, add or remove a part — a deterministic gate compares every
-part's bounding box against the previous round and fails the round if one moved. Everything
-you add lives inside or on an existing part's surface.
diff --git a/harness/codeverse3d/prompts/tracks/detail_object.j2 b/harness/codeverse3d/prompts/tracks/detail_object.j2
deleted file mode 100644
index 8fcc8cc8..00000000
--- a/harness/codeverse3d/prompts/tracks/detail_object.j2
+++ /dev/null
@@ -1,70 +0,0 @@
-# Detail pass on `{{ object_name }}` — round {{ round_index }}
-
-The structure is DONE and it passed the assembly gates. This round has exactly one job: make the
-surfaces read as a real manufactured/grown object instead of clean primitives. Nothing about the
-silhouette, the layout or the part list may change — a harness gate compares this round's bounding
-box and every part's box against the previous round and fails the round if they moved.
-
-## THE RULE
-- **Do not move, resize, rename, add or delete any part.** Every part keeps its name and its
- bounding box (±5 mm). If a change would grow a box, make it smaller instead.
-- **Do not change the overall bounding box** ({{ overall_bbox }}).
-- Everything you add must be *inside or on* an existing part's surface.
-
-## What to add (pick what suits each part — you do NOT have to do all of them)
-{% for t in tasks %}
-{{ loop.index }}. {{ t }}
-{% endfor %}
-
-Detail vocabulary that is worth score here, cheapest first:
-- **Edge treatment**: bevel/chamfer every hard edge a real object would have (2–6 mm on furniture,
- 0.5–2 mm on metal parts). A single bevel modifier on a part transforms how it reads under light.
-- **Panel lines and seams**: shallow inset grooves where two shells of the real object meet
- (drawer fronts, housings, lids, crumb trays). 1–2 mm wide, 1 mm deep.
-- **Fasteners**: bolt heads, screws, rivets, hinges, nuts — small, arrayed, at the places a real
- object is actually joined. Use a loop, not twelve hand-placed cylinders.
-- **Secondary shapes**: fillets at joints, ribs and gussets on cast parts, flutes and knurling on
- handles, tread and sipes on tyres, laminations and grain steps on wood.
-- **Counted features the brief asks for** that are missing or under-count (spokes, slats, dentils,
- panes, rafter tails) — add the missing ones INSIDE the existing part.
-- **Material variation**: distinct roughness/metalness per material family, a darker worn value
- where hands touch, a lighter one on exposed edges. Do not make everything one grey.
-
-## Files in scope
-{% for f in files %}- `{{ f }}`
-{% endfor %}
-
-## What the judge saw last round
-{{ judge_summary }}
-
-## Part boxes you must stay inside (unchanged from last round)
-{{ parts_table }}
-
-## Detail budget
-{{ detail_budget }}
-
-## Contract reminders
-{{ frame_doc }}
-- One code path; no environment sniffing, no DOM/texture loading/network/file IO.
-- Keep the build clean and under the time budget: prefer a bevel/array/solidify stack over
- subdividing everything.
-{% if current_files %}
-
-## Current file contents (edit these; return each edited file COMPLETE)
-{% for path, body in current_files.items() %}
---- {{ path }} ---
-```
-{{ body }}
-```
-{% endfor %}
-{% endif %}
-{% if tool_cards and not single_shot %}
-
-## Tools
-{{ tool_cards }}
-Run `build` and then `measure` after editing: if any part box moved by more than 5 mm, undo that
-change before you finish.
-{% endif %}
-
-## Output
-{{ output_format }}
diff --git a/harness/codeverse3d/tracks/candidates.py b/harness/codeverse3d/tracks/candidates.py
index 1dcd49e7..13dc5ef6 100644
--- a/harness/codeverse3d/tracks/candidates.py
+++ b/harness/codeverse3d/tracks/candidates.py
@@ -1,39 +1,34 @@
-"""Best-of-N baseline and pairwise best-round selection (track side).
-
-* ``run_best_of_n`` — N baseline candidates are generated IN PARALLEL, each in
- its own throw-away sub-workspace (``<ws>/_cand/c<k>``: own git repo, copy of
- the skeleton + spec + plan, own AGENTS.md/MCP config), built (+repair),
- gated, quick-rendered (4 views) and judged (n_samples=1) — the ordinary round
- (``steps._run_round``, kind ``candidate``) with two knobs turned: ``quick_render``
- in place of ``pipeline.render`` and no clay views. Each candidate's round trace
- goes to its own ``events.jsonl``; the run log carries ``candidate.*``. The winner
- (quick score → fewer gate errors; a pairwise tie-break when the top two are
- within judge noise) is copied back into the run workspace and the ordinary
- round-0 pipeline (build → gates → 14-view render → full judge) runs on it.
- Every candidate is charged to the run budget and persisted in
- ``rounds/candidates.json``.
-* ``choose_best_round`` — after each round: when the new score is within
- ``policy.pairwise_margin`` of the current best, a position-swapped pairwise
- comparison decides (confidence ≥ ``policy.pairwise_min_confidence`` to replace).
+"""Best-of-N baseline (track side).
+
+``run_best_of_n`` — N baseline candidates are generated IN PARALLEL, each in its own
+throw-away sub-workspace (``<ws>/_cand/c<k>``: own git repo, copy of the skeleton + spec +
+plan, own AGENTS.md/MCP config), built (+repair), gated, quick-rendered (4 views) and
+judged (n_samples=1) — the ordinary round (``steps._run_round``, kind ``candidate``) with
+two knobs turned: ``quick_render`` in place of ``pipeline.render`` and no clay views. Each
+candidate's round trace goes to its own ``events.jsonl``; the run log carries
+``candidate.*``. The winner — built, then the highest quick score, then fewer gate errors,
+then the earlier candidate — is copied back into the run workspace and the ordinary
+round-0 pipeline (build → gates → 14-view render → full judge) runs on it. That is the
+ONE choice the loop still makes (2026-09-22: no pairwise tie-break, no best round).
+Every candidate is charged to the run budget and persisted in ``rounds/candidates.json``.
"""
from __future__ import annotations
import logging
import shutil
-from collections.abc import Callable, Sequence
+from collections.abc import Sequence
from dataclasses import replace
from functools import partial
from pathlib import Path
-from typing import Any, Literal
+from typing import Any
from pydantic import BaseModel, Field
from codeverse3d.contracts.artifacts import BuildResult, Measurement, RenderSet
from codeverse3d.contracts.common import Usage
-from codeverse3d.contracts.run import PairwiseNote, RoundRecord
+from codeverse3d.contracts.run import RoundRecord
from codeverse3d.conventions import OBJECT_VIEWS_QUICK
-from codeverse3d.cost.types import Stage
from codeverse3d.orchestrator import BudgetExceeded, gate_error_count, pick_best_round
from codeverse3d.proc import EventLog, fan_out
from codeverse3d.tracks.common import RunContext
@@ -42,7 +37,6 @@ from codeverse3d.tracks.steps import (
RoundFailed,
RoundPipeline,
_run_round,
- round_record_path,
run_round,
)
from codeverse3d.workspace import Workspace
@@ -62,7 +56,7 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],
ctx.ws.ensure_gitignore() # legacy run dirs may predate _cand/ in the standard lines
subs = [make_candidate_context(track, ctx, k) for k in range(n)]
- def _one(k: int) -> tuple[CandidateRecord, RenderSet | None]:
+ def _one(k: int) -> CandidateRecord:
sub, label = subs[k], f"c{k}"
ctx.events.emit("candidate.start", candidate=k, workspace=str(sub.ws.root))
# kind="candidate" is what the cost ledger files the sessions under (Stage.CANDIDATE)
@@ -76,7 +70,7 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],
notes=rec.notes)
ctx.events.emit("candidate.done", candidate=k, score=cand.score, build_ok=build_ok, gate_errors=cand.gate_errors,
duration_s=cand.duration_s, cost_usd=round(rec.usage.cost_usd, 4), commit=rec.commit[:10])
- return cand, rec.renders
+ return cand
results = fan_out(list(range(n)), _one, max_workers=ctx.settings.limits.max_parallel_agents, label="candidates",
item_name=lambda k: f"c{k}")
@@ -91,7 +85,6 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],
for k, r in zip(retry, again, strict=True):
results[k] = r
records: list[CandidateRecord] = []
- renders: dict[int, RenderSet] = {}
budget_stop: BudgetExceeded | None = None
for k, r in enumerate(results):
if isinstance(r, Exception):
@@ -104,22 +97,16 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],
notes=f"{type(r).__name__}: {r}"[:300]))
ctx.events.emit("candidate.failed", candidate=k, error=f"{type(r).__name__}: {r}"[:300])
continue
- rec, rs = r
- records.append(rec)
- if rs is not None:
- renders[k] = rs
+ records.append(r)
if not any(r.commit for r in records):
if budget_stop is not None:
raise budget_stop # nothing usable survived: the budget stop stands
raise RoundFailed("; ".join(f"{r.label}: {r.notes}" for r in records) or "every candidate failed")
- best, note = select_candidate(ctx, records, renders)
+ best = rank_candidates(records)[0]
records[best].selected = True
usage = sum((r.usage for r in records), Usage())
- if note is not None:
- usage = usage + note.usage
ctx.ws.write_json(ctx.ws.root / "rounds" / "candidates.json",
- {"n": n, "selected": best, "candidates": [r.model_dump(mode="json") for r in records],
- "pairwise": note.model_dump(mode="json") if note else None})
+ {"n": n, "selected": best, "candidates": [r.model_dump(mode="json") for r in records]})
ctx.events.emit("candidate.selected", round=0, candidate=best, label=records[best].label, score=records[best].score,
build_ok=records[best].build_ok, scores={r.label: r.score for r in records},
cost_usd=round(usage.cost_usd, 4))
@@ -129,8 +116,6 @@ def run_best_of_n(track: Any, ctx: RunContext, tasks: Sequence[GenerationTask],
for r in records if r.index != best)
notes = [f"best-of-{n}: selected {records[best].label} "
f"(quick score {records[best].score if records[best].score is None else round(records[best].score, 3)}; others: {others or '-'})"]
- if note is not None:
- notes.append(note.line())
ctx.budget.check() # boundary: the winner is adopted + persisted; a real ceiling stop lands here
return run_round(ctx, index=0, kind="baseline", tasks=[], pipeline=pipeline, files_hint=list(files_hint),
extra_usage=usage, extra_notes=notes)
@@ -196,27 +181,6 @@ def quick_render(ctx: RunContext, round_index: int, build: BuildResult, measurem
return None
-def select_candidate(ctx: RunContext, records: Sequence[CandidateRecord], renders: dict[int, RenderSet]) -> tuple[int, PairwiseNote | None]:
- """Best candidate index (+ pairwise note when the top two were within judge noise)."""
- order = rank_candidates(records)
- best = order[0]
- if len(order) < 2:
- return best, None
- a, b = records[order[0]], records[order[1]]
- if not (a.build_ok and b.build_ok and a.index in renders and b.index in renders):
- return best, None
- compare = _pairwise_fn(ctx, renders[a.index], renders[b.index])
- decision, note = decide_best(a.score, b.score, margin=ctx.policy.pairwise_margin,
- min_confidence=ctx.policy.pairwise_min_confidence, compare=compare, labels=(a.label, b.label))
- if note is not None:
- ctx.budget.add(note.usage, stage=Stage.PAIRWISE) # post-hoc: a finished comparison
- ctx.events.emit("pairwise.done", stage="candidates", a=note.a, b=note.b, winner=note.winner, confidence=note.confidence,
- accepted=note.accepted, error=note.error, cost_usd=round(note.usage.cost_usd, 4))
- if decision == "pairwise":
- best = b.index
- return best, note
-
-
def adopt_candidate(ctx: RunContext, sub_ws: Workspace) -> None:
"""Copy the winner's src/ + public/ into the run workspace and keep its trajectories."""
for rel in ("src", "public"):
@@ -232,33 +196,10 @@ def adopt_candidate(ctx: RunContext, sub_ws: Workspace) -> None:
shutil.copytree(sub_ws.trajectories, ctx.ws.trajectories, dirs_exist_ok=True)
-# ----------------------------------------------------------------------------- best round (pairwise tie-break)
+# ----------------------------------------------------------------------------- best round
def choose_best_round(ctx: RunContext, rounds: list[RoundRecord], new_index: int) -> int | None:
- """Index of the best round after ``rounds[new_index]`` finished.
-
- Ordinary ranking (score → fewer gate errors) unless the new round's score is
- within ``policy.pairwise_margin`` of the current best: then a pairwise
- comparison of the two render sets decides, and the new round replaces the
- best only when it wins with ``confidence ≥ policy.pairwise_min_confidence``.
- The verdict is stored on the round (``RoundRecord.pairwise``, plus a notes line)
- and re-persisted; the decision itself is :func:`replay_best_round` over the journal,
- so the live pick and any later resume replay the SAME sequential rule."""
- incumbent = ctx.state.best_round
- if incumbent is not None and incumbent < len(rounds) and incumbent != new_index:
- inc, new = rounds[incumbent], rounds[new_index]
- if new.score is not None and inc.score is not None:
- compare = _pairwise_fn(ctx, inc.renders, new.renders) if (inc.renders and new.renders) else None
- _, note = decide_best(inc.score, new.score, margin=ctx.policy.pairwise_margin,
- min_confidence=ctx.policy.pairwise_min_confidence, compare=compare,
- labels=(f"r{incumbent:02d}", f"r{new_index:02d}"))
- if note is not None:
- ctx.budget.add(note.usage, stage=Stage.PAIRWISE) # post-hoc
- new.usage = new.usage + note.usage
- new.pairwise = note
- new.notes = (new.notes + "; " if new.notes else "") + note.line()
- ctx.ws.write_json(round_record_path(ctx, new_index), new)
- ctx.events.emit("pairwise.done", stage="rounds", a=note.a, b=note.b, winner=note.winner, confidence=note.confidence,
- accepted=note.accepted, error=note.error, cost_usd=round(note.usage.cost_usd, 4))
+ """Index of the best round after ``rounds[new_index]`` finished (no pairwise tie-break is
+ bought any more; verdicts stored by earlier runs are still honoured by the replay)."""
return replay_best_round(rounds)
@@ -284,17 +225,6 @@ def replay_best_round(journal: Sequence[RoundRecord]) -> int | None:
return best
-def _pairwise_fn(ctx: RunContext, renders_a: RenderSet | None, renders_b: RenderSet | None):
- if renders_a is None or renders_b is None:
- return None
-
- def _compare() -> Any:
- judge = ctx.services.pairwise(ctx.spec.backends.judge)
- return judge.compare(ctx.spec, renders_a, renders_b, rubric=ctx.rubric)
-
- return _compare
-
-
# ===================================================================== decision logic
class CandidateRecord(BaseModel):
"""One best-of-N baseline candidate (generated in its own sub-workspace)."""
@@ -321,56 +251,5 @@ def rank_candidates(records: Sequence[CandidateRecord]) -> list[int]:
return [r.index for r in sorted(records, key=lambda r: r.sort_key(), reverse=True)]
-Decision = Literal["score", "pairwise", "keep"]
-
-#: ``compare()`` → any object with ``winner`` ('a'|'b'|'tie'), ``confidence``, ``reasons``, ``usage``.
-CompareFn = Callable[[], Any]
-
-
-def within_margin(a: float | None, b: float | None, margin: float) -> bool:
- return a is not None and b is not None and abs(a - b) <= margin
-
-
-def decide_best(
- incumbent_score: float | None,
- challenger_score: float | None,
- *,
- margin: float,
- min_confidence: float,
- compare: CompareFn | None,
- labels: tuple[str, str] = ("best", "new"),
-) -> tuple[Decision, PairwiseNote | None]:
- """Should the challenger replace the incumbent?
-
- * scores differ by more than ``margin`` → ``"score"`` (caller uses the
- ordinary ranking rule);
- * within the margin and ``compare`` given → run it; ``"pairwise"`` when the
- challenger wins with ``confidence ≥ min_confidence``, else ``"keep"``;
- * within the margin without a comparator → ``"keep"`` (ties go to the
- incumbent: fewer regenerations, stable best commit).
- """
- if incumbent_score is None or challenger_score is None:
- return "score", None
- if not within_margin(incumbent_score, challenger_score, margin):
- return "score", None
- note = PairwiseNote(a=labels[0], b=labels[1])
- if compare is None:
- return "keep", note
- try:
- res = compare()
- except Exception as e: # noqa: BLE001 — a judge outage must not pick a worse round
- log.warning("pairwise tie-break failed: %s", e)
- note.error = f"{type(e).__name__}: {e}"
- return "keep", note
- note.winner = getattr(res, "winner", "tie")
- note.confidence = float(getattr(res, "confidence", 0.0) or 0.0)
- note.reasons = list(getattr(res, "reasons", []) or [])[:6]
- note.usage = getattr(res, "usage", None) or Usage()
- note.error = getattr(res, "error", "") or ""
- note.accepted = note.winner == "b" and note.confidence >= min_confidence
- return ("pairwise" if note.accepted else "keep"), note
-
-
-__all__ = ["CAND_DIR", "CandidateRecord", "adopt_candidate", "choose_best_round", "decide_best",
- "make_candidate_context", "quick_render", "rank_candidates", "replay_best_round", "run_best_of_n",
- "select_candidate"]
+__all__ = ["CAND_DIR", "CandidateRecord", "adopt_candidate", "choose_best_round", "make_candidate_context",
+ "quick_render", "rank_candidates", "replay_best_round", "run_best_of_n"]
diff --git a/harness/codeverse3d/tracks/common.py b/harness/codeverse3d/tracks/common.py
index 4b5b9cff..f37b0d4c 100644
--- a/harness/codeverse3d/tracks/common.py
+++ b/harness/codeverse3d/tracks/common.py
@@ -66,16 +66,9 @@ class Services:
"""Reference photos beside the frames, no silhouette (graphics / scene with images)."""
return _import("codeverse3d.judges.vlm_judge", "LikenessJudge")(model_id=model_id, n_samples=n_samples, rubric=rubric)
- def pairwise(self, model_id: str) -> Any:
- """Position-swapped A/B judge: ``.compare(spec, renders_a, renders_b, rubric=...)``."""
- return _import("codeverse3d.judges.pairwise", "PairwiseJudge")(model_id)
-
def runtime(self, language: Language) -> Any:
return _import("codeverse3d.languages", "get_runtime")(language)
- def rubric_threshold(self, rubric: str) -> float | None:
- return getattr(_import("codeverse3d.judges.rubrics", "load_rubric")(rubric), "pass_threshold", None)
-
# ---- spatial
def measure(self, glb: Path) -> Measurement:
return _import("codeverse3d.spatial.measure", "measure_glb")(glb)
diff --git a/harness/codeverse3d/tracks/lifecycle.py b/harness/codeverse3d/tracks/lifecycle.py
index 9ae14c0b..82405eda 100644
--- a/harness/codeverse3d/tracks/lifecycle.py
+++ b/harness/codeverse3d/tracks/lifecycle.py
@@ -4,13 +4,12 @@ Concrete tracks (static / articulated / scene / graphics) override the hooks
(``plan_model``, ``make_pipeline``, ``prepare``, ``baseline_tasks``, the planner
knobs ``plan_template``/``plan_example``/``finalise_plan`` and the refine
scaffold's ``_refine_task``). All bookkeeping — workspace, events, budget, run
-state, stage cache, best tracking, stop policy, record — lives here once.
+state, stage cache, best tracking, the fixed round count, record — lives here once.
"""
from __future__ import annotations
import logging
-import os
import platform
import traceback
from collections.abc import Sequence
@@ -28,19 +27,13 @@ from codeverse3d.contracts.spec import Spec
from codeverse3d.cost.context import run_binding
from codeverse3d.cost.instrument import run_ledger
from codeverse3d.orchestrator import (
- KIND_FOR_STRATEGY,
BudgetExceeded,
BudgetGuard,
BudgetSnapshot,
- RefineTask,
RoundPolicy,
RunState,
StageRunner,
- StopPolicy,
- StopReason,
- Strategy,
TaskGroup,
- best_score,
build_refine_instructions,
hash_inputs,
plan_refine_groups,
@@ -84,27 +77,6 @@ log = logging.getLogger(__name__)
REFERENCE_RUBRIC = "reference_v1"
-#: surface-detail rounds a track that implements one gets by default. ``RoundPolicy.detail_rounds``
-#: is None (= this default) unless a caller chose a number; ``C3D_DETAIL_ROUNDS`` overrides both
-#: (0 = off — the A/B switch for eval/docs/EVAL.md).
-DEFAULT_DETAIL_ROUNDS = 1
-
-
-def detail_round_budget(policy: RoundPolicy, supported: bool) -> int:
- """How many detail rounds THIS run gets: env > a chosen ``policy.detail_rounds`` > the track default.
-
- Until 2026-08-29 the third tier was skipped whenever ANY policy object was injected, so the
- economy/quality profiles (a policy for ``judge_samples`` alone) silently lost the static
- track's detail round."""
- raw = os.environ.get("C3D_DETAIL_ROUNDS", "").strip()
- if raw.isdigit():
- return int(raw) if supported else 0
- if not supported:
- return 0
- if policy.detail_rounds is not None:
- return policy.detail_rounds
- return DEFAULT_DETAIL_ROUNDS
-
def _reconcile_billed_from_ledger(budget: BudgetGuard, ws: Workspace, events: EventLog) -> None:
"""Adopt the run ledger's total when it exceeds the restored snapshot.
@@ -135,20 +107,6 @@ def _reconcile_billed_from_ledger(budget: BudgetGuard, ws: Workspace, events: Ev
budget.billed_usd = billed
-_STATUS: dict[str, RunStatus] = {
- "pass": RunStatus.PASSED, "plateau": RunStatus.PLATEAU, "max_rounds": RunStatus.PLATEAU,
- "budget": RunStatus.BUDGET,
- # the two money stops (orchestrator.StopPolicy): the code is intact and the best
- # round is delivered — the run stopped because another round was not worth buying.
- "regression": RunStatus.PLATEAU, "diminishing_returns": RunStatus.PLATEAU,
- # judge outage (degraded/crashed verdicts even after a retry): the code is intact
- # and the best built round is delivered — a stop, not a failure.
- "judge_unavailable": RunStatus.PLATEAU,
- # the vendor's usage limit, not ours — the best round ships, the status says a budget ended
- "agent_quota": RunStatus.BUDGET,
-}
-
-
def plan_stage_inputs(spec: Spec) -> dict[str, Any]:
"""Only the spec fields the PLAN depends on: hashing the whole Spec meant that
raising ``budget.max_minutes`` in spec.json (the only way to continue a BUDGET-stopped
@@ -197,10 +155,6 @@ class BaseTrack:
plan_max_output_tokens: int = 24000
#: refine fan-out (graphics is always ONE whole-program task)
allow_refine_fanout: bool = True
- #: does this track implement ``detail_tasks``? When False the round policy's detail
- #: budget is zeroed for the run, so the stop policy never offers a round the track
- #: cannot build (see ``orchestrator.detail_blocked``).
- supports_detail_round: bool = False
#: share of the run budget the BASELINE may use (1.0 = no soft cap). The scene
#: track lowers it so the refine rounds always inherit money and minutes.
soft_budget_fraction: float = 1.0
@@ -288,50 +242,26 @@ class BaseTrack:
def _refine_task(self, ctx: RunContext, group: TaskGroup, last: RoundRecord, index: int, *, parallel: bool) -> GenerationTask:
raise NotImplementedError
- def detail_tasks(self, ctx: RunContext, last: RoundRecord, index: int) -> tuple[list[GenerationTask], list[str]]:
- """The SURFACE-DETAIL round (``kind='detail'``): bevels, seams, fasteners, wear —
- no change to the silhouette, the placement or the part list.
-
- Offered by the stop policy only once the structure gates are clean
- (``orchestrator.detail_blocked``); tracks that do not implement it set
- ``supports_detail_round = False`` and are never offered the round."""
- return [], []
-
# ------------------------------------------------------------------ refine scaffold
- def refine_tasks(self, ctx: RunContext, last: RoundRecord, history: Sequence[RoundRecord],
- *, strategy: Strategy = "same") -> tuple[list[GenerationTask], list[str]]:
- """index → rebuild guard → instructions → groups → per-track ``_refine_task``.
-
- ``strategy="switch"`` is what the loop asks for after a regression: the same
- evidence, but ONE whole-artifact task instead of the per-part set that just
- made the score worse (docs/COST.md §5 — repeating the shape is what the 19
- regression rounds did)."""
- index = len(history)
+ def refine_tasks(self, ctx: RunContext, last: RoundRecord) -> tuple[list[GenerationTask], list[str]]:
+ """The round after ``last``: rebuild guard → instructions → groups → per-track ``_refine_task``.
+
+ Always built on ``last`` — the previous round, whatever it scored (2026-09-22: no
+ refine-from-best, no whole-artifact rewrite after a regression)."""
+ index = last.index + 1
if last.build is None or not last.build.ok:
return [self._rebuild_task(ctx, last, index)], ["rebuild: previous round did not build"]
- if strategy == "detail":
- gen_tasks, lines = self.detail_tasks(ctx, last, index)
- if gen_tasks:
- ctx.events.emit("refine.planned", round=index, n_tasks=len(lines), n_groups=len(gen_tasks),
- parallel=len(gen_tasks) > 1, strategy="detail",
- targets=[t.files_hint for t in gen_tasks])
- return gen_tasks, lines
- return [], [] # the track offered no detail work: let the loop stop as it meant to
tasks = build_refine_instructions(last.judgment, last.gates, failed_acceptance(ctx, last.judgment), ctx.plan,
file_for_target=self.refine_file_for_target(ctx),
max_tasks=ctx.policy.max_refine_tasks,
extra=self.extra_refine_tasks(ctx, last))
if not tasks:
return [], []
- if strategy == "switch":
- tasks = [rewrite_task(last, best_score(history))] + tasks
- groups, parallel = [TaskGroup(tasks=tasks, files=[])], False
- else:
- groups, parallel = plan_refine_groups(tasks, allow_fanout=self.allow_refine_fanout,
- parallel_min_tasks=ctx.policy.parallel_min_tasks)
+ groups, parallel = plan_refine_groups(tasks, allow_fanout=self.allow_refine_fanout,
+ parallel_min_tasks=ctx.policy.parallel_min_tasks)
gen_tasks = [self._refine_task(ctx, g, last, index, parallel=parallel) for g in groups]
ctx.events.emit("refine.planned", round=index, n_tasks=len(tasks), n_groups=len(groups), parallel=parallel,
- strategy=strategy, targets=[g.targets for g in groups])
+ targets=[g.targets for g in groups])
return gen_tasks, [t.line() for t in tasks]
def _rebuild_task(self, ctx: RunContext, last: RoundRecord, index: int) -> GenerationTask:
@@ -365,7 +295,7 @@ class BaseTrack:
runner = StageRunner(ws, events, state)
events.emit("run.start", track=self.track.value, language=spec.language.value, resume=resume,
agent=ctx.agent_id, planner=spec.backends.planner, judge=spec.backends.judge)
- stop: StopReason | str = "failed"
+ stop = RunStatus.FAILED
error = ""
try:
ctx.plan = runner.stage("plan", lambda: self._plan_stage(ctx), inputs={"spec": plan_stage_inputs(spec), "track": self.track.value},
@@ -375,7 +305,7 @@ class BaseTrack:
stop = self._round_loop(ctx, rounds)
except BudgetExceeded as e:
events.emit("budget.exceeded", reason=e.reason, spent_usd=round(e.spent_usd, 4))
- stop, error = "budget", e.reason
+ stop, error = RunStatus.BUDGET, e.reason
self._salvage_baseline(ctx, rounds)
except Exception as e: # noqa: BLE001 — persist a FAILED record, then fail loud
error = f"{type(e).__name__}: {e}"
@@ -383,12 +313,10 @@ class BaseTrack:
self._save_budget(ctx) # mid-round charges must survive for resume
state.status, state.error = RunStatus.FAILED, error
state.save(ws)
- rec = self._record(ctx, rounds, RunStatus.FAILED, error=error, stop_reason="failed")
+ rec = self._record(ctx, rounds, RunStatus.FAILED, error=error)
self.services.finalize_record(ws, rec)
raise
- status = _STATUS.get(stop, RunStatus.FAILED)
- rec = self.finalise(ctx, rounds, status, stop_reason=str(stop), error=error)
- return rec
+ return self.finalise(ctx, rounds, stop, error=error)
# ------------------------------------------------------------------ resume reconciliation
def reconcile_resume(self, spec: Spec, ws: Workspace, events: EventLog, state: RunState,
@@ -518,8 +446,7 @@ class BaseTrack:
budget.restore(BudgetSnapshot.model_validate(snap))
_reconcile_billed_from_ledger(budget, ws, events)
policy = self._policy or RoundPolicy(max_rounds=spec.budget.max_rounds)
- policy = replace(policy, n_candidates=self._resolve_candidates(spec, settings), judge_model=spec.backends.judge,
- detail_rounds=detail_round_budget(policy, self.supports_detail_round))
+ policy = replace(policy, n_candidates=self._resolve_candidates(spec, settings))
# reference images: static objects are scored with reference_v1 (adds the measured silhouette
# criterion); other tracks keep their rubric but the judge still sees the references.
rubric = REFERENCE_RUBRIC if spec.references and self.track is Track.STATIC_OBJECT else self.rubric
@@ -556,7 +483,7 @@ class BaseTrack:
return self.services.judge(ctx.rubric, ctx.spec.backends.judge, n_samples=n_samples)
def after_plan(self, ctx: RunContext) -> None:
- """Bind judge / generator backends once the plan exists (rubric threshold → policy target)."""
+ """Bind judge / generator backends once the plan exists."""
if ctx.judge is None:
ctx.judge = self.make_judge(ctx)
# provenance: the judge protocol (role prompt + rig rules + wire schema) is hashed
@@ -564,11 +491,6 @@ class BaseTrack:
judge_hash = getattr(ctx.judge, "prompt_hash", "")
if isinstance(judge_hash, str) and judge_hash:
ctx.prompt_hashes["judge"] = judge_hash
- # the rubric's pass threshold is the stop target whenever the rubric states one —
- # for an injected policy too (the CLI used to re-derive it; one binding now)
- thr = self.services.rubric_threshold(ctx.rubric)
- if thr is not None:
- ctx.policy = replace(ctx.policy, target=float(thr))
if ctx.single_shot:
if ctx.model is None:
ctx.model = self.services.chat_model(single_shot_model_id(ctx.agent_id))
@@ -623,22 +545,30 @@ class BaseTrack:
return (harness + "\n\n" + ctx.contract_text).strip()
# ------------------------------------------------------------------ round loop
- def _round_loop(self, ctx: RunContext, rounds: list[RoundRecord]) -> StopReason:
+ def _round_loop(self, ctx: RunContext, rounds: list[RoundRecord]) -> RunStatus:
+ """The baseline, then ``max_rounds`` refine rounds — each built on the round before it.
+
+ FIXED rounds (owner, 2026-09-22): the judge scores every round and its verdict shapes
+ the next round's tasks, but nothing here decides that another round is not worth
+ buying. The run stops early only on the clock (``BudgetGuard``) or a hard failure:
+ the vendor's quota, a refine round whose sessions changed nothing, or a last round
+ that leaves nothing to ask for (no gate error, no failed must-item, no judge plan) or
+ no verdict to ask from."""
self.ensure_materialized(ctx)
pipeline = self.make_pipeline()
- stop_policy = StopPolicy(ctx.policy)
rejudged: set[int] = set()
transport_retried: set[int] = set()
+
+ def _stop(reason: RunStatus) -> RunStatus:
+ ctx.events.emit("stop", reason=reason.value, rounds=len(rounds), best=ctx.state.best_round)
+ return reason
+
while True:
- decision = stop_policy.evaluate(rounds, budget_ok=ctx.budget.ok())
- if decision.stop:
- ctx.events.emit("stop", rounds=len(rounds), best=ctx.state.best_round, **decision.event())
- return decision.reason
- if decision.strategy == "switch":
- # the last round regressed by more than the judge's noise: one round of a
- # DIFFERENT shape (whole-artifact rewrite), never another of the same.
- ctx.events.emit("strategy.switch", round=len(rounds), reason="regression", detail=decision.detail)
index = len(rounds)
+ if index > ctx.policy.max_rounds: # the baseline + max_rounds refine rounds all ran
+ return _stop(RunStatus.MAX_ROUNDS)
+ if not ctx.budget.ok():
+ return _stop(RunStatus.BUDGET)
previous = rounds[-1].judgment if rounds else None
if index == 0:
ctx.state.status = RunStatus.GENERATING
@@ -653,19 +583,14 @@ class BaseTrack:
prev_j = rounds[-2].judgment if len(rounds) > 1 else None
if rejudge_round(ctx, pipeline, last, previous=prev_j):
self._promote_best(ctx, rounds, last.index)
- continue # decide() re-runs with the recovered score
- last = self._refine_base(ctx, rounds, decision.strategy)
- previous = last.judgment
- tasks, instructions = self.refine_tasks(ctx, last, rounds, strategy=decision.strategy)
- kind = KIND_FOR_STRATEGY.get(decision.strategy, "refine")
+ continue # plan the next round from the recovered verdict
+ tasks, instructions = self.refine_tasks(ctx, last)
+ kind = "refine"
if not tasks:
- if last.judgment is None and last.build is not None and last.build.ok:
- # no tasks only because the judge never scored the round: stopping
- # as 'plateau' would blame the code for a judge glitch
- ctx.events.emit("stop", reason="judge_unavailable", rounds=len(rounds), best=ctx.state.best_round)
- return "judge_unavailable"
- ctx.events.emit("stop", reason="no_refine_tasks", rounds=len(rounds))
- return "plateau"
+ # no gate error, no failed must-item, no judge plan: nothing to ask for. When
+ # that is only because the judge never scored the round, say so.
+ unjudged = last.judgment is None and last.build is not None and last.build.ok
+ return _stop(RunStatus.JUDGE_UNAVAILABLE if unjudged else RunStatus.NO_REFINE_TASKS)
ctx.state.current_round = index
ctx.state.save(ctx.ws)
try:
@@ -674,36 +599,33 @@ class BaseTrack:
else:
rec = run_round(ctx, index=index, kind=kind, tasks=tasks, pipeline=pipeline, instructions=instructions,
previous=previous, files_hint=self.round_files_hint(ctx),
- extra_notes=self.round_extra_notes(ctx), previous_best=best_score(rounds))
+ extra_notes=self.round_extra_notes(ctx))
except RoundFailed as e:
if looks_quota(str(e)):
# The vendor's own usage limit: not a transport death (a retry meets the
- # same wall) and not a plateau (the code did not stop improving) — the
- # agent is gone until the limit resets. cmp8 (2026-09-09): three runs
- # filed "plateau" on "You've hit your usage limit … try again at Sep 14th".
+ # same wall) — the agent is gone until the limit resets. cmp8
+ # (2026-09-09): three runs filed a plateau on "You've hit your usage
+ # limit … try again at Sep 14th".
ctx.events.emit("round.agent_quota", round=index, detail=str(e)[:500])
if index == 0:
raise
- ctx.events.emit("stop", reason="agent_quota", rounds=len(rounds), best=ctx.state.best_round)
- return "agent_quota"
+ return _stop(RunStatus.AGENT_QUOTA)
if index not in transport_retried and looks_transport(str(e)):
# A vendor-CLI crash / 503 storm / dropped socket is not an agent
# verdict — the session never really happened. Re-run the SAME
# round once, baseline included (rc=247 alone killed three whole
# runs on 2026-08-29), before letting the failure mean anything.
- # ``continue`` re-enters through StopPolicy, so the budget and
+ # ``continue`` re-enters through the loop head, so the budget and
# round ceilings still guard the retry.
transport_retried.add(index)
ctx.events.emit("round.transport_retry", round=index, detail=str(e)[:500])
continue
if index == 0:
raise
- # A refine round in which no task changed any file is not a crash: the
- # agents judged the requested edits unnecessary (or bailed). Treat it as
- # a plateau signal so the best round so far is delivered.
+ # every session of a refine round failed or changed nothing: the next round
+ # would be asked the same thing from the same code
ctx.events.emit("round.no_change", round=index, detail=str(e)[:500])
- ctx.events.emit("stop", reason="no_change", rounds=len(rounds), best=ctx.state.best_round)
- return "plateau"
+ return _stop(RunStatus.NO_CHANGE)
rounds.append(rec)
# ONE save, AFTER the best is chosen — never a durable "round done" with a
# not-yet-updated best. Saving the round first (an earlier attempt at
@@ -715,29 +637,6 @@ class BaseTrack:
ctx.state.mark_round_done(index, rec.commit)
self._promote_best(ctx, rounds, index)
- @staticmethod
- def _refine_base(ctx: RunContext, rounds: list[RoundRecord], strategy: str) -> RoundRecord:
- """The round the next refine builds on. The last one — unless it regressed past the
- judge's noise (StopPolicy's ``switch``) and a better round exists: then ``src/`` is
- restored to that best round and its record is the base, so the session works from
- the best code and the best verdict's issues rather than from a worse attempt's.
- Measured 2026-09-09 (loop 22): 0.66 → 0.61 → 0.47 and 0.60 → 0.32, each refine
- building on the round before it, the regressions compounding while the best sat in
- git; the finalise restore then delivered r0 after two paid rounds of drift."""
- last = rounds[-1]
- best = ctx.state.best_round
- if strategy != "switch" or best is None or best >= len(rounds) or best == last.index:
- return last
- commit = rounds[best].commit
- if not commit or not ctx.ws.has_commit(commit):
- return last
- if ctx.ws.head() != commit or ctx.ws.changed_files():
- ctx.ws.restore(commit)
- ctx.ws.commit(f"restore best round r{best:02d} before refine")
- ctx.events.emit("round.refine_from_best", round=len(rounds), best=best, regressed=last.index,
- best_score=rounds[best].score, last_score=last.score)
- return rounds[best]
-
def _promote_best(self, ctx: RunContext, rounds: list[RoundRecord], index: int) -> None:
"""Rank round ``index`` in (pairwise tie-break included), promote the best, save."""
best = choose_best_round(ctx, rounds, index)
@@ -782,7 +681,7 @@ class BaseTrack:
ctx.state.save(ctx.ws)
# ------------------------------------------------------------------ finalise
- def finalise(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, stop_reason: str, error: str = "") -> RunRecord:
+ def finalise(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, error: str = "") -> RunRecord:
self._save_budget(ctx) # aborted-round / stage charges must survive for resume
best = ctx.state.best_round
rebuild_err = ""
@@ -811,11 +710,11 @@ class BaseTrack:
ctx.extra["finalise_rebuild_failed"] = ""
if rounds and not rebuild_err and self._texture_wanted(ctx):
self._texture_pass(ctx)
- ctx.state.status, ctx.state.stop_reason, ctx.state.error = status, stop_reason, error
+ ctx.state.status, ctx.state.stop_reason, ctx.state.error = status, status.value, error
self._save_budget(ctx) # saves state too — AFTER the texture pass charged
- rec = self._record(ctx, rounds, status, error=error, stop_reason=stop_reason)
+ rec = self._record(ctx, rounds, status, error=error)
self.services.finalize_record(ctx.ws, rec)
- ctx.events.emit("run.done", status=status.value, stop=stop_reason, best_round=rec.best_round,
+ ctx.events.emit("run.done", status=status.value, best_round=rec.best_round,
final_score=rec.final_score, cost_usd=round(rec.total_usage.cost_usd, 4))
return rec
@@ -915,7 +814,7 @@ class BaseTrack:
except Exception: # noqa: BLE001 — a malformed report must not block texturing
return False
- def _record(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, error: str, stop_reason: str) -> RunRecord:
+ def _record(self, ctx: RunContext, rounds: list[RoundRecord], status: RunStatus, *, error: str) -> RunRecord:
best = ctx.state.best_round
baseline = rounds[0].score if rounds else None
final = rounds[best].score if best is not None and best < len(rounds) else None
@@ -925,7 +824,7 @@ class BaseTrack:
if ctx.budget.spent.cost_usd > total.cost_usd:
total = ctx.budget.spent
cands = ctx.ws.root / "rounds" / "candidates.json" # best-of-N summary: the file is the one copy
- extra: dict[str, Any] = {"stop_reason": stop_reason, "rubric": ctx.rubric, "budget": ctx.budget.summary(),
+ extra: dict[str, Any] = {"stop_reason": status.value, "rubric": ctx.rubric, "budget": ctx.budget.summary(),
"n_candidates": ctx.policy.n_candidates,
"candidates": ctx.ws.read_json(cands) if cands.is_file() else None,
"cost_by_stage": ctx.budget.stage_summary()}
@@ -977,14 +876,3 @@ class BaseTrack:
return (dict(extra) if isinstance(extra, dict) else {},
{str(k): str(v) for k, v in hashes.items()} if isinstance(hashes, dict) else {})
-
-def rewrite_task(last: RoundRecord, best: float | None) -> RefineTask:
- """The instruction that turns a repeat into a change of approach."""
- was = f"{last.score:.3f}" if last.score is not None else "no score"
- peak = f"{best:.3f}" if best is not None else "the earlier best"
- return RefineTask(
- target="overall", kind="rewrite", priority=0, source="judge",
- instruction=(f"The previous round made the artifact WORSE ({was} against {peak}) — its edits are not the "
- "way forward. Do NOT repeat them part by part: re-read the plan and the failures below, then "
- "rewrite the whole artifact coherently, keeping only what the evidence shows was already right."),
- )
diff --git a/harness/codeverse3d/tracks/plan_features.py b/harness/codeverse3d/tracks/plan_features.py
index 342e5dec..3d3c5c9d 100644
--- a/harness/codeverse3d/tracks/plan_features.py
+++ b/harness/codeverse3d/tracks/plan_features.py
@@ -20,8 +20,7 @@ PLAN_FEATURES_ENV = "C3D_PLAN_FEATURES"
#: pin costs one noisy A/B, pinning wrongly costs a confident wrong answer
#: (eval/docs/EVAL.md §8.1 measured it — the A/A's worst pair differed 1 part vs 10).
GENERATION_SIDE_ENV: frozenset[str] = frozenset({"C3D_SKILLS", "C3D_SKILLS_MAX", "C3D_SKILLS_UNVERIFIED",
- "C3D_SKILLS_ONLY",
- "C3D_DETAIL_ROUNDS", "C3D_REFERENCE_DIFF",
+ "C3D_SKILLS_ONLY", "C3D_REFERENCE_DIFF",
"C3D_FEWER_TURNS", "C3D_SEED_RECIPES"})
@@ -43,7 +42,6 @@ LIVE_SWITCHES: dict[str, str] = {
# re-sample a degenerate plan from the original prompt instead of editing it in context
"C3D_PLAN_RESTART": "codeverse3d/tracks/planner.py",
"C3D_SCOPED_PARTS": "codeverse3d/tracks/depth.py",
- "C3D_DETAIL_ROUNDS": "codeverse3d/tracks/lifecycle.py",
"C3D_REFERENCE_DIFF": "codeverse3d/judges/vlm_judge.py", # reference.py merged in, 2026-08-28
# the skill system (design: scratchpad/skills/design/DESIGN.md §6.5). All three are
# read at call time by one module, so an A/B arm that sets them really differs.
@@ -73,6 +71,7 @@ LIVE_SWITCHES: dict[str, str] = {
#: about nothing. A name leaves this dict in the same commit as the code that reads it.
DEAD_SWITCHES: dict[str, str] = {
PLAN_FEATURES_ENV: "none of its six features was ever implemented; nothing reads this variable",
+ "C3D_DETAIL_ROUNDS": "the surface-detail round went with the judgement stops that offered it (2026-09-22)",
}
diff --git a/harness/codeverse3d/tracks/prompting.py b/harness/codeverse3d/tracks/prompting.py
index 2b77a941..4ba3fe3f 100644
--- a/harness/codeverse3d/tracks/prompting.py
+++ b/harness/codeverse3d/tracks/prompting.py
@@ -280,8 +280,8 @@ def language_system_prompt(language: Language, *, role: str = "", tools: bool =
return base
# roles COMPOSE with the language base rather than replacing it. Replacing was the
# shape inherited from the f-strings, and it left every fatal language-specific fact —
- # the self-check loop, the sampled-time contract — absent from exactly the stages that
- # violate it: the repair pass and the detail pass.
+ # the self-check loop, the sampled-time contract — absent from exactly the stage that
+ # violates it: the repair pass.
return base + "\n\n" + render(f"system/role_{role}.j2", language=language.value, **vars).strip()
@@ -363,7 +363,7 @@ def budget_for(ctx: RunContext) -> DepthBudget:
def detail_budget_text(ctx: RunContext) -> str:
- """The limits block every generate/refine/detail prompt shows, sized from the plan."""
+ """The limits block every generate/refine prompt shows, sized from the plan."""
if ctx.plan is None or not (getattr(ctx.plan, "parts", None) or ()):
return ""
return budget_for(ctx).as_prompt()
diff --git a/harness/codeverse3d/tracks/static_object.py b/harness/codeverse3d/tracks/static_object.py
index 0a01c08a..df278627 100644
--- a/harness/codeverse3d/tracks/static_object.py
+++ b/harness/codeverse3d/tracks/static_object.py
@@ -10,7 +10,6 @@ from __future__ import annotations
import logging
from collections.abc import Sequence
from pathlib import Path
-from typing import Any
from codeverse3d.contracts.artifacts import (
BuildResult,
@@ -26,14 +25,10 @@ from codeverse3d.contracts.plan import Plan, StaticPlan
from codeverse3d.contracts.run import RoundRecord
from codeverse3d.conventions import (
BBOX_TOLERANCE_M,
- LANGUAGE_FRAME,
OBJECT_CLAY_VIEWS,
OBJECT_VIEWS,
- Frame,
- to_pascal,
- to_snake,
)
-from codeverse3d.orchestrator import DETAIL_KIND, RefineTask, TaskGroup, compact_instructions
+from codeverse3d.orchestrator import RefineTask, TaskGroup, compact_instructions
from codeverse3d.prompts import render
from codeverse3d.spatial.contract import planned_joins
from codeverse3d.tracks.common import RunContext
@@ -94,16 +89,6 @@ class ObjectPipeline:
# is the object as dense as its own plan says? Deterministic, so the judge is
# never asked "does it look detailed enough" (tracks/depth.py).
out.append(budget_gate(measurement, build, budget_for(ctx)))
- # a DETAIL round promised not to move anything: prove it in code, not with the judge
- if measurement is not None and ctx.extra.get("detail_round") == round_index:
- out.append(
- drift_gate(
- ctx.extra.get("detail_baseline"),
- measurement,
- tol_m=ctx.policy.detail_bbox_tol_m,
- language=ctx.language.value,
- )
- )
return out
def render(
@@ -182,8 +167,6 @@ class StaticObjectTrack(BaseTrack):
refine_template = "tracks/refine_object.j2"
part_template = "tracks/generate_static_part.j2"
assemble_template = "tracks/assemble_static.j2"
- detail_template = "tracks/detail_object.j2"
- supports_detail_round = True
def make_pipeline(self) -> ObjectPipeline:
return ObjectPipeline()
@@ -321,8 +304,7 @@ class StaticObjectTrack(BaseTrack):
def extra_refine_tasks(self, ctx: RunContext, last: RoundRecord) -> Sequence[RefineTask]:
# NB: the `detail_budget` WARN is deliberately NOT turned into a refine task. Measured:
# refine rounds that added > 2000 triangles while assembly was still open lost 0.075 of
- # assembly_fit and 0.025 of overall. Density is the DETAIL round's job (detail_tasks),
- # which runs only once the structure gates are clean.
+ # assembly_fit and 0.025 of overall.
return reference_refine_tasks(ctx, last)
def _refine_task(
@@ -364,206 +346,6 @@ class StaticObjectTrack(BaseTrack):
owns_entry=True, # refine_object.j2 promises entry-file access even when scoped
)
- # ------------------------------------------------------------------ detail round
- def detail_tasks(
- self, ctx: RunContext, last: RoundRecord, index: int
- ) -> tuple[list[GenerationTask], list[str]]:
- """One surface-detail round: bevels, seams, fasteners, wear, material variation —
- with the silhouette, the placement and the part list frozen.
-
- Fanned out over the same per-part scopes as the baseline when the language owns
- one file per part, because detail is embarrassingly parallel and file-disjoint.
- ``ctx.extra`` records the round index and the measurement to diff against, which
- is what ``ObjectPipeline.gates`` turns into the ``detail_drift`` gate.
- """
- lines = detail_instructions(last, max_lines=ctx.policy.max_instructions_per_task + 2)
- if not lines:
- return [], []
- ctx.extra["detail_round"] = index
- ctx.extra["detail_baseline"] = last.measurement
- scopes = self.scopes(ctx)
- tasks: list[GenerationTask] = []
- # one scoped task per scope, or one whole-object task. The two arms differed in
- # four values — the context builder, the label, the file list, and which of
- # edit_only / owns_entry is set (detail is file-disjoint per scope, so a scoped
- # pass never touches the entry; the whole-object pass owns the full tree).
- for scope in scopes or [None]:
- files = list(scope.files) if scope is not None else expected_files(ctx)
- context = (scope_context(ctx, scope, round_index=index, tasks=lines, files=files,
- judge_summary=judge_digest(last),
- current_files=refine_inline_files(ctx, files, scoped=False))
- if scope is not None else
- base_prompt_context(ctx, round_index=index, tasks=lines, files=files,
- judge_summary=judge_digest(last),
- current_files=refine_inline_files(ctx, files, scoped=False)))
- tasks.append(
- GenerationTask(
- label=f"detail_{scope.label}" if scope is not None else "detail",
- prompt=render(self.detail_template, **context),
- system=self.detail_system_prompt(ctx),
- files_hint=files,
- round=index,
- kind=DETAIL_KIND,
- temperature=0.6,
- thinking="high",
- edit_only=scope is not None,
- owns_entry=scope is None,
- )
- )
- ctx.record_prompt("detail", tasks[0].prompt)
- ctx.events.emit(
- "detail.planned",
- round=index,
- n_tasks=len(tasks),
- n_lines=len(lines),
- tol_mm=round(ctx.policy.detail_bbox_tol_m * 1000, 1),
- )
- return tasks, lines
-
- def detail_system_prompt(self, ctx: RunContext) -> str:
- return language_system_prompt(ctx.language, role="detail")
-
-
-# ===================================================================== the DETAIL round
-# --------------------------------------------------------------------------- detail-round drift gate
-DRIFT_GATE = "detail_drift"
-
-
-def drift_findings(before: Measurement | None, after: Measurement | None, *, tol_m: float,
- language: str = "") -> list[GateFinding]:
- """Did a detail round move anything? Findings for the ``detail_drift`` gate.
-
- The detail round's whole contract is "surface only": the silhouette, the part
- list and every part box stay put. This is the deterministic check of that
- promise — the judge is never asked whether the shape moved, code answers it.
- """
- out: list[GateFinding] = []
- if before is None or after is None:
- return out
- for axis, a, b in zip(_axes(language), before.extents, after.extents, strict=True):
- d = float(b) - float(a)
- if abs(d) > tol_m:
- out.append(GateFinding(
- gate=DRIFT_GATE, severity=Severity.ERROR, target="overall",
- message=f"the detail round changed the overall {axis} extent by {d * 1000:+.1f} mm "
- f"({a:.3f} → {b:.3f} m); a detail round may not change the silhouette",
- fix_hint="revert whatever grew the object (a bevel that widened a part, a fastener sticking out) "
- "and keep the added geometry inside the existing surfaces",
- data={"kind": "detail_drift", "axis": axis, "delta_m": round(d, 5)}))
- was = {to_snake(str(p.name)): p for p in (before.parts or ())}
- now = {to_snake(str(p.name)): p for p in (after.parts or ())}
- for key in sorted(set(was) - set(now)):
- out.append(GateFinding(
- gate=DRIFT_GATE, severity=Severity.ERROR, target=to_pascal(key),
- message=f"part '{to_pascal(key)}' disappeared during the detail round",
- fix_hint=f"restore '{to_pascal(key)}' exactly as it was before this round",
- data={"kind": "detail_drift", "removed": key}))
- for key in sorted(set(now) - set(was)):
- out.append(GateFinding(
- gate=DRIFT_GATE, severity=Severity.WARN, target=to_pascal(key),
- message=f"the detail round introduced a new top-level part '{to_pascal(key)}'",
- fix_hint="detail belongs inside an existing part; merge it into the part it decorates "
- "(or accept it only if the plan names it)",
- data={"kind": "detail_drift", "added": key}))
- moved = 0
- for key in sorted(set(was) & set(now)):
- a, b = was[key], now[key]
- dc = max(abs((bl + bh) / 2 - (al + ah) / 2)
- for al, ah, bl, bh in zip(a.bbox_min, a.bbox_max, b.bbox_min, b.bbox_max, strict=True))
- de = max(abs((bh - bl) - (ah - al))
- for al, ah, bl, bh in zip(a.bbox_min, a.bbox_max, b.bbox_min, b.bbox_max, strict=True))
- if max(dc, de) <= tol_m:
- continue
- moved += 1
- if moved > 8:
- continue
- out.append(GateFinding(
- gate=DRIFT_GATE, severity=Severity.ERROR, target=to_pascal(key),
- message=f"part '{to_pascal(key)}' moved {dc * 1000:.1f} mm / resized {de * 1000:.1f} mm during the "
- f"detail round (tolerance {tol_m * 1000:.0f} mm)",
- fix_hint="put the part back on its previous centre and extents; add the detail inside that box",
- data={"kind": "detail_drift", "part": key, "centre_mm": round(dc * 1000, 2),
- "extent_mm": round(de * 1000, 2)}))
- if moved > 8:
- out.append(GateFinding(gate=DRIFT_GATE, severity=Severity.ERROR, target="overall",
- message=f"{moved} parts moved during the detail round ({moved - 8} more not listed)",
- fix_hint="revert the placement changes; this round may only add surface geometry",
- data={"kind": "detail_drift", "moved": moved}))
- if not out:
- d_tri = int(getattr(after, "tri_count", 0) or 0) - int(getattr(before, "tri_count", 0) or 0)
- out.append(GateFinding(gate=DRIFT_GATE, severity=Severity.INFO, target="overall",
- message=f"detail round held the contract: no part moved more than "
- f"{tol_m * 1000:.0f} mm; {d_tri:+,} triangles added",
- data={"kind": "detail_drift", "delta_tris": d_tri}))
- return out
-
-
-def _axes(language: str) -> tuple[str, str, str]:
- """Axis letters as the AUTHOR sees them. ``Measurement.extents`` is in the GLB frame
- (Y-up); a blender/cadquery/urdf author thinks Z-up, where glb (x, y, z) reads (x, z, y)
- — so naming the GLB axis in a fix hint would send them to the wrong dimension."""
- if LANGUAGE_FRAME.get(language) is Frame.Z_UP_NEG_Y_FRONT:
- return ("x", "z", "y")
- return ("x", "y", "z")
-
-
-def drift_gate(before: Measurement | None, after: Measurement | None, *, tol_m: float, language: str = "") -> GateReport:
- """``detail_drift`` GateReport (passing when nothing moved)."""
- findings = drift_findings(before, after, tol_m=tol_m, language=language)
- return GateReport(gate=DRIFT_GATE, findings=findings,
- passed=not any(f.severity is Severity.ERROR for f in findings))
-
-
-# --------------------------------------------------------------------------- detail-round tasks
-#: judge improvement-plan kinds a DETAIL round is allowed to act on. Assembly/placement
-#: work is the repair loop's job and would break the no-drift contract.
-DETAIL_KINDS = frozenset({"geometry", "detail", "material", "materials", "craftsmanship", "texture", "finish"})
-
-#: what a detail round always does, whatever the judge said. Ordered by measured value per
-#: triangle: edge treatment first (it changes how every surface reads under light), then the
-#: features a viewer counts, then wear.
-DEFAULT_DETAIL_LINES: tuple[str, ...] = (
- "Bevel or chamfer every hard edge that a real version of this object would have "
- "(2-6 mm on furniture and cast parts, 0.5-2 mm on sheet metal and small mechanisms).",
- "Add the panel lines, seams and shut-lines where the real object's shells meet "
- "(lids, drawers, housings, trays): 1-2 mm wide, ~1 mm deep insets.",
- "Add the fasteners the real object is held together with — bolt heads, rivets, screws, "
- "hinges — arrayed in a loop at the joints, sized 3-10 mm.",
- "Give each material family a distinct roughness/metalness and a slightly different value; "
- "no two different materials may share the same flat grey.",
-)
-
-
-def detail_instructions(last: Any, *, max_lines: int = 8) -> list[str]:
- """Instruction lines for a detail round: the measured density gap first, then the
- judge's detail-shaped asks, then the standing detail vocabulary; deduped and capped."""
- lines: list[str] = []
- seen: set[str] = set()
-
- def _add(text: str) -> None:
- key = text.strip().lower()[:80]
- if key and key not in seen:
- seen.add(key)
- lines.append(text.strip())
-
- for g in getattr(last, "gates", None) or ():
- for f in getattr(g, "findings", None) or ():
- if (f.data or {}).get("kind") == "under_tri_budget":
- _add(f"{f.message}. {f.fix_hint}")
- j = getattr(last, "judgment", None)
- for item in sorted(getattr(j, "improvement_plan", None) or (),
- key=lambda i: (i.priority, -getattr(i, "expected_gain", 0.0))):
- if str(getattr(item, "kind", "")).lower() not in DETAIL_KINDS:
- continue
- target = getattr(item, "target", "") or "overall"
- _add(f"{target}: {item.instruction}")
- for issue in getattr(j, "issues", None) or ():
- if str(getattr(issue, "kind", "")).lower() in ("material", "materials", "detail"):
- _add(f"{issue.target or 'overall'}: {issue.detail}")
- for text in DEFAULT_DETAIL_LINES:
- _add(text)
- return lines[:max_lines]
-
# ===================================================================== reference images
SILHOUETTE_GATE = "reference_silhouette"
diff --git a/harness/codeverse3d/tracks/steps.py b/harness/codeverse3d/tracks/steps.py
index bcc38905..57f0b07b 100644
--- a/harness/codeverse3d/tracks/steps.py
+++ b/harness/codeverse3d/tracks/steps.py
@@ -208,15 +208,13 @@ def run_round(
files_hint: Sequence[str] = (),
extra_usage: Usage | None = None,
extra_notes: Sequence[str] = (),
- previous_best: float | None = None,
) -> RoundRecord:
"""Execute one round and persist its record. Budget is charged as it goes.
``tasks`` may be empty when the code is already in place (scene stages,
best-of-N winner copied in): the round is then build → gates → render →
judge only. ``extra_usage`` / ``extra_notes`` fold pre-round work
- (candidate generation) into the record; ``previous_best`` is the best score
- before this round, used only to flag the round as wasted in ``cost.round``.
+ (candidate generation) into the record.
``_run_round`` (the same round without the aborted-round record) also takes
``render`` (replaces ``pipeline.render``) and ``geometry_views=False`` (skips the
clay views): the two knobs a best-of-N candidate turns (``candidates.run_best_of_n``
@@ -225,7 +223,7 @@ def run_round(
try:
return _run_round(ctx, index=index, kind=kind, tasks=tasks, pipeline=pipeline, instructions=instructions,
previous=previous, files_hint=files_hint, extra_usage=extra_usage,
- extra_notes=extra_notes, previous_best=previous_best)
+ extra_notes=extra_notes)
except BaseException as e:
# the round died half-way (budget stop, 503 storm, RoundFailed). Whatever it
# burned is already in the guard: report it so the round is not invisible.
@@ -246,7 +244,6 @@ def _run_round(
files_hint: Sequence[str] = (),
extra_usage: Usage | None = None,
extra_notes: Sequence[str] = (),
- previous_best: float | None = None,
render: RenderFn | None = None,
geometry_views: bool = True,
) -> RoundRecord:
@@ -344,7 +341,7 @@ def _run_round(
ctx.events.emit("round.done", round=index, kind=kind, commit=rec.commit[:10], score=rec.score,
build_ok=outcome.build.ok, duration_s=rec.duration_s, cost_usd=round(usage.cost_usd, 4))
emit_round_cost(ctx, index=index, kind=kind, cost=cost, usage=usage, turns=turns, score=rec.score,
- previous_best=previous_best, build_ok=outcome.build.ok, judged=rec.judgment is not None)
+ build_ok=outcome.build.ok, judged=rec.judgment is not None)
return rec
@@ -384,19 +381,17 @@ def emit_round_cost(
usage: Usage,
turns: int,
score: float | None,
- previous_best: float | None,
build_ok: bool,
judged: bool,
aborted: str = "",
corrected: bool = False,
) -> None:
"""One ``cost.round`` event per round: ``{stage → $}``, judge $, agent turns and
- whether the money bought anything. The ledger/audit reads this instead of
+ whether the money bought a usable round. The ledger/audit reads this instead of
reconstructing the round from trajectories and events. ``corrected=True``
marks a re-emission after ``rejudge_round`` recovered a verdict — the LAST
event per round is the truth."""
- wasted, why = _waste_flag(score=score, previous_best=previous_best, build_ok=build_ok,
- judged=judged, aborted=aborted)
+ wasted, why = _waste_flag(build_ok=build_ok, judged=judged and score is not None, aborted=aborted)
ctx.events.emit(
"cost.round", round=index, kind=kind,
stages={k: round(v, 6) for k, v in cost.items()},
@@ -404,28 +399,22 @@ def emit_round_cost(
total_usd=round(usage.cost_usd, 6),
agent_turns=turns,
input_tokens=usage.input_tokens, output_tokens=usage.output_tokens, cached_tokens=usage.cached_tokens,
- score=score, previous_best=previous_best, wasted=wasted, waste_reason=why, aborted=aborted,
+ score=score, wasted=wasted, waste_reason=why, aborted=aborted,
corrected=corrected,
run_usd=round(ctx.budget.spent.cost_usd, 6),
)
-def _waste_flag(*, score: float | None, previous_best: float | None, build_ok: bool,
- judged: bool, aborted: str) -> tuple[bool, str]:
- """Did this round buy anything? (docs/COST.md §5 vocabulary)"""
+def _waste_flag(*, build_ok: bool, judged: bool, aborted: str) -> tuple[bool, str]:
+ """Did this round buy a usable, judged round? (docs/COST.md §5 vocabulary.) A round that
+ scored below an earlier one is NOT waste any more (2026-09-22): every round is kept, and
+ any of them can be the one handed over (``codeverse3d.addons.select``)."""
if aborted:
return True, "aborted"
if not build_ok:
return True, "build_failed"
- if not judged or score is None:
+ if not judged:
return True, "unjudged"
- if previous_best is None:
- return False, ""
- delta = score - previous_best
- if delta < -0.005:
- return True, "regression"
- if abs(delta) < 0.005:
- return True, "zero_delta"
return False, ""
@@ -446,7 +435,7 @@ def record_aborted_round(ctx: RunContext, *, index: int, kind: str, usage: Usage
aborted = ctx.extra.setdefault("aborted_rounds", [])
aborted.append({"index": index, "kind": kind, "cost_usd": round(usage.cost_usd, 6), "error": error[:300]})
emit_round_cost(ctx, index=index, kind=kind, cost={"aborted": round(usage.cost_usd, 6)}, usage=usage,
- turns=0, score=None, previous_best=None, build_ok=False, judged=False, aborted=error[:300])
+ turns=0, score=None, build_ok=False, judged=False, aborted=error[:300])
except Exception as e: # noqa: BLE001 — never mask the exception that stopped the round
log.warning("could not record aborted round r%02d: %s", index, e)
@@ -541,8 +530,7 @@ def rejudge_round(ctx: RunContext, pipeline: RoundPipeline, rec: RoundRecord, pr
# the round's original cost.round went out as wasted=unjudged; emit the corrected
# one so the audit stream stops counting a now-scored round as wasted.
emit_round_cost(ctx, index=rec.index, kind=rec.kind, cost={"judge": round(judgment.usage.cost_usd, 6)},
- usage=rec.usage, turns=0, score=rec.score, previous_best=None,
- build_ok=True, judged=True, corrected=True)
+ usage=rec.usage, turns=0, score=rec.score, build_ok=True, judged=True, corrected=True)
return True
diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.py
index b804cf50..c480f827 100644
--- a/harness/tests/core/test_run_layout.py
+++ b/harness/tests/core/test_run_layout.py
@@ -97,7 +97,7 @@ def _moved_run(tmp_path: Path):
sheet_a.write_bytes(b"PNG")
spec = Spec(id="run1", track=Track.STATIC_OBJECT, language=Language.BLENDER,
prompt="a wooden chair", backends=Backends(generator="gemini-cli:gemini-3.6-flash"))
- rec = RunRecord(spec=spec, workspace=str(a), status=RunStatus.PASSED, best_round=0,
+ rec = RunRecord(spec=spec, workspace=str(a), status=RunStatus.MAX_ROUNDS, best_round=0,
rounds=[RoundRecord(index=0, kind="generate",
renders=RenderSet(views=[], contact_sheet=str(sheet_a)))])
b = tmp_path / "B" / "run1"
diff --git a/harness/tests/cost/test_profiles.py b/harness/tests/cost/test_profiles.py
index 3b946d3a..fa12d7fb 100644
--- a/harness/tests/cost/test_profiles.py
+++ b/harness/tests/cost/test_profiles.py
@@ -12,7 +12,6 @@ from codeverse3d.cli._common import resolve_dial
from codeverse3d.cli.main import app
from codeverse3d.config import Settings, get_settings
from codeverse3d.cost.profiles import PROFILE_NAMES, PROFILES, get_profile, profile_table
-from codeverse3d.orchestrator import RoundPolicy
runner = CliRunner()
@@ -159,8 +158,6 @@ def test_judge_samples_reach_the_round_policy_only_when_a_profile_asks(tmp_path:
s.apply_profile("quality", force=True)
opts = C.round_policy_options(spec, s)
assert opts["policy"].judge_samples == 3 and opts["policy"].max_rounds == 3
- # the rubric threshold is NOT bound here: BaseTrack.after_plan binds it for an injected policy too
- assert opts["policy"].target == RoundPolicy().target
# --------------------------------------------------------------- flag == env var
diff --git a/harness/tests/flywheel_cli/conftest.py b/harness/tests/flywheel_cli/conftest.py
index 7d37a062..c5fcc4ea 100644
--- a/harness/tests/flywheel_cli/conftest.py
+++ b/harness/tests/flywheel_cli/conftest.py
@@ -108,7 +108,7 @@ def make_fake_run(
build=BuildResult(ok=True, language=language.value),
))
(ws.artifacts / "object.glb").write_bytes(b"glTF\x02\x00\x00\x00" + b"\0" * 16)
- rec = RunRecord(spec=spec, workspace=str(ws.root), status=RunStatus.PASSED if scores[-1] >= 0.75 else RunStatus.PLATEAU,
+ rec = RunRecord(spec=spec, workspace=str(ws.root), status=RunStatus.MAX_ROUNDS,
rounds=rounds, best_round=1, baseline_score=scores[0], final_score=scores[1],
total_usage=Usage(cost_usd=0.06, input_tokens=2000, output_tokens=1000),
finished_at=datetime.now(UTC),
diff --git a/harness/tests/flywheel_cli/test_cli.py b/harness/tests/flywheel_cli/test_cli.py
index 67ce775f..0aba3779 100644
--- a/harness/tests/flywheel_cli/test_cli.py
+++ b/harness/tests/flywheel_cli/test_cli.py
@@ -294,18 +294,28 @@ def test_resume_refuses_a_finished_run_and_never_re_enters_it(made_run, stub_tra
runs, run_dir = made_run()
ws = Workspace(run_dir)
- RunState(status=RunStatus.PASSED, stop_reason="pass", best_score=0.7436).save(ws)
+ # a run recorded before 2026-09-22 that stopped on a pass (its state names the best it kept)
+ ws.state_path.write_text(json.dumps({"status": "passed", "stop_reason": "pass", "best_round": 1,
+ "best_commit": "abc", "best_score": 0.7436}))
+ assert RunState.load(ws).status is RunStatus.STOPPED
entered = []
stub_track(lambda spec, resume, force: entered.append(resume))
r = runner.invoke(app, ["resume", ws.root.name, "--runs-dir", str(runs)])
- assert r.exit_code == 1 and "already finished" in r.output
+ assert r.exit_code == 1 and "already finished" in r.output and "stop_reason='pass'" in r.output
assert entered == [], "the pipeline must not be re-entered"
- assert RunState.load(ws).status is RunStatus.PASSED, "the terminal state must survive"
+ assert RunState.load(ws).status is RunStatus.STOPPED, "the terminal state must survive"
# ... and the escape hatch still works, loudly
assert runner.invoke(app, ["resume", ws.root.name, "--runs-dir", str(runs), "--force"]).exit_code == 130
assert entered == [True]
+ # every round ran: raising --rounds is how a max_rounds stop goes on (from its last round)
+ RunState(status=RunStatus.MAX_ROUNDS, stop_reason="max_rounds").save(ws)
+ r = runner.invoke(app, ["resume", ws.root.name, "--runs-dir", str(runs)])
+ assert r.exit_code == 1 and "status=max_rounds" in r.output
+ assert runner.invoke(app, ["resume", ws.root.name, "--runs-dir", str(runs), "--max-minutes", "90"]).exit_code == 1
+ assert runner.invoke(app, ["resume", ws.root.name, "--runs-dir", str(runs), "--rounds", "5"]).exit_code == 130
+
# a budget stop is the documented exception: it resumes when a cap is raised
RunState(status=RunStatus.BUDGET, stop_reason="budget").save(ws)
assert runner.invoke(app, ["resume", ws.root.name, "--runs-dir", str(runs)]).exit_code == 1
diff --git a/harness/tests/flywheel_cli/test_complexity_record.py b/harness/tests/flywheel_cli/test_complexity_record.py
index cebc0e8e..978672f1 100644
--- a/harness/tests/flywheel_cli/test_complexity_record.py
+++ b/harness/tests/flywheel_cli/test_complexity_record.py
@@ -50,7 +50,7 @@ def _record(rounds: list[RoundRecord], best: int | None = None) -> RunRecord:
return RunRecord(
spec=Spec(id="t", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a thing",
backends=Backends()),
- plan=plan, workspace="/tmp/x", status=RunStatus.PASSED, rounds=rounds, best_round=best,
+ plan=plan, workspace="/tmp/x", status=RunStatus.MAX_ROUNDS, rounds=rounds, best_round=best,
started_at=datetime.now(UTC),
)
diff --git a/harness/tests/graphics/test_track.py b/harness/tests/graphics/test_track.py
index 5cd3ab91..e70dd879 100644
--- a/harness/tests/graphics/test_track.py
+++ b/harness/tests/graphics/test_track.py
@@ -122,8 +122,8 @@ def test_graphics_track_end_to_end(tmp_path, settings):
settings=settings, runtime=runtime)
assert isinstance(get_track(Track.GRAPHICS), GraphicsTrack)
rec = track.run(spec, ws)
- assert rec.status is RunStatus.PASSED and [r.kind for r in rec.rounds] == ["baseline", "refine", "refine"]
- assert rec.baseline_score == pytest.approx(0.55) and rec.final_score == pytest.approx(0.9) and rec.best_round == 2
+ assert rec.status is RunStatus.MAX_ROUNDS and [r.kind for r in rec.rounds] == ["baseline", "refine", "refine", "refine"]
+ assert [r.score for r in rec.rounds] == pytest.approx([0.55, 0.72, 0.9, 0.9])
assert rec.extra["rubric"] == "shader_v2"
plan = GraphicsPlan.model_validate(json.loads(ws.plan_path.read_text()))
assert any(a.text.startswith("Includes: bokeh") for a in plan.acceptance)
diff --git a/harness/tests/orchestrator_tracks/fakes.py b/harness/tests/orchestrator_tracks/fakes.py
index d04607c5..dccf0826 100644
--- a/harness/tests/orchestrator_tracks/fakes.py
+++ b/harness/tests/orchestrator_tracks/fakes.py
@@ -261,14 +261,13 @@ def _png(path: Path, size: int = 32) -> None:
class FakeServices(Services):
def __init__(self, *, runtime_factory: Callable[[Language], Any] | None = None, judge: Any | None = None,
- contract_errors: int = 0, assemble: bool = True, sweep_errors: int = 0, pairwise: Any | None = None,
+ contract_errors: int = 0, assemble: bool = True, sweep_errors: int = 0,
silhouette_iou: float | None = None, motion_errors: int = 0):
self.runtime_factory = runtime_factory or (lambda lang: FakeRuntime(lang))
self._judge = judge
self.contract_errors = contract_errors
self.assemble = assemble
self.sweep_errors = sweep_errors
- self._pairwise = pairwise
self.silhouette_iou = silhouette_iou
self.motion_errors = motion_errors
self.materialized: list[str] = []
@@ -292,11 +291,6 @@ class FakeServices(Services):
self.reference_judges.append((model_id, n_samples, rubric))
return self._judge if self._judge is not None else FakeJudge()
- def pairwise(self, model_id: str) -> Any:
- if self._pairwise is None:
- raise ServiceUnavailable("no pairwise judge in tests")
- return self._pairwise
-
def silhouette(self, render_png, reference_png) -> dict[str, Any]:
self.silhouette_calls.append((str(render_png), str(reference_png)))
if self.silhouette_iou is None:
@@ -316,9 +310,6 @@ class FakeServices(Services):
def runtime(self, language: Language) -> Any:
return self.runtime_factory(language)
- def rubric_threshold(self, rubric: str) -> float | None:
- return 0.8
-
def measure(self, glb: Path) -> Measurement:
scene = trimesh.load(str(glb), force="scene")
bounds = scene.bounds
diff --git a/harness/tests/orchestrator_tracks/test_budget_snapshot.py b/harness/tests/orchestrator_tracks/test_budget_snapshot.py
index 63b5a000..7431fde9 100644
--- a/harness/tests/orchestrator_tracks/test_budget_snapshot.py
+++ b/harness/tests/orchestrator_tracks/test_budget_snapshot.py
@@ -205,7 +205,7 @@ def test_a_budget_tripped_candidate_still_lets_the_sibling_be_adopted(tmp_path,
planner_model=FakeChatModel(lambda req: chair_plan.model_dump(mode="json")),
settings=settings, runtime=FakeRuntime(Language.THREEJS), n_candidates=2)
rec = track.run(spec, ws)
- assert rec.status in (RunStatus.PLATEAU, RunStatus.PASSED)
+ assert rec.status is RunStatus.MAX_ROUNDS
assert len(rec.rounds) == 1 and "best-of-2: selected c1" in rec.rounds[0].notes
assert "c1" in (ws.src / "object.js").read_text() # the sibling's code was adopted
cands = json.loads((ws.root / "rounds" / "candidates.json").read_text())
diff --git a/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py
index ecce3e34..287e8886 100644
--- a/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py
+++ b/harness/tests/orchestrator_tracks/test_candidates_reference_motion.py
@@ -1,4 +1,4 @@
-"""Best-of-N candidates, pairwise tie-breaks, reference images, motion checks, instruction compaction."""
+"""Best-of-N candidates, reference images, motion checks, instruction compaction."""
from __future__ import annotations
@@ -20,7 +20,7 @@ from codeverse3d.orchestrator import (
from codeverse3d.proc import EventLog
from codeverse3d.tracks import get_track
from codeverse3d.tracks.articulated_object import ArticulatedObjectTrack, expected_direction
-from codeverse3d.tracks.candidates import CandidateRecord, decide_best, rank_candidates
+from codeverse3d.tracks.candidates import CandidateRecord, rank_candidates
from codeverse3d.tracks.planner import plan_example
from codeverse3d.tracks.static_object import StaticObjectTrack
from codeverse3d.workspace import Workspace
@@ -29,7 +29,6 @@ from tests.orchestrator_tracks.fakes import (
FakeAgent,
FakeChatModel,
FakeJudge,
- FakePairwise,
FakeRuntime,
FakeServices,
_planner,
@@ -61,35 +60,16 @@ def test_build_refine_instructions_extra_and_instance_targets(chair_plan):
assert [t.target for t in tasks] == ["BackLeg_1", "overall"] and tasks[1].kind == "reference"
-def test_rank_candidates_and_decide_best():
+def test_rank_candidates():
+ """Built > higher quick score > fewer gate errors > earlier — the one in-loop choice left."""
recs = [CandidateRecord(index=0, label="c0", build_ok=True, score=0.62, gate_errors=2),
CandidateRecord(index=1, label="c1", build_ok=True, score=0.62, gate_errors=0),
CandidateRecord(index=2, label="c2", build_ok=False),
CandidateRecord(index=3, label="c3", build_ok=True, score=0.70, gate_errors=5)]
assert rank_candidates(recs) == [3, 1, 0, 2]
- # clear delta → ordinary ranking
- assert decide_best(0.60, 0.70, margin=0.03, min_confidence=0.6, compare=None) == ("score", None)
- # within noise, no comparator → keep
- d, note = decide_best(0.60, 0.61, margin=0.03, min_confidence=0.6, compare=None, labels=("r00", "r01"))
- assert d == "keep" and note is not None and not note.accepted and "keep" in note.line()
-
- class R:
- def __init__(self, w, c):
- self.winner, self.confidence, self.reasons, self.usage, self.error = w, c, ["x"], None, ""
-
- d, note = decide_best(0.60, 0.61, margin=0.03, min_confidence=0.6, compare=lambda: R("b", 0.8))
- assert d == "pairwise" and note.accepted and note.winner == "b"
- d, note = decide_best(0.60, 0.61, margin=0.03, min_confidence=0.6, compare=lambda: R("b", 0.5))
- assert d == "keep" and not note.accepted
- d, note = decide_best(0.60, 0.61, margin=0.03, min_confidence=0.6, compare=lambda: R("a", 0.9))
- assert d == "keep"
-
- def boom():
- raise RuntimeError("judge down")
-
- d, note = decide_best(0.60, 0.61, margin=0.03, min_confidence=0.6, compare=boom)
- assert d == "keep" and "judge down" in note.error
- assert decide_best(None, 0.5, margin=0.03, min_confidence=0.6, compare=None) == ("score", None)
+ tie = [CandidateRecord(index=0, label="c0", build_ok=True, score=0.6),
+ CandidateRecord(index=1, label="c1", build_ok=True, score=0.6)]
+ assert rank_candidates(tie) == [0, 1]
def test_expected_direction():
@@ -131,11 +111,11 @@ def test_best_of_two_baseline_selects_highest_quick_score(tmp_path, chair_plan,
ws = Workspace(tmp_path / "runs" / "stool")
agent = FakeAgent(_writer_by_candidate)
judge = _CandidateJudge({"c0": 0.55, "c1": 0.72})
- services = FakeServices(pairwise=FakePairwise())
+ 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.PLATEAU and len(rec.rounds) == 1
+ 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()
@@ -153,23 +133,21 @@ def test_best_of_two_baseline_selects_highest_quick_score(tmp_path, chair_plan,
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())
- # pairwise not consulted: scores differ by more than the margin
- assert services._pairwise.calls == []
-def test_best_of_two_pairwise_tiebreak_overrides_ranking(tmp_path, chair_plan, settings):
+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})
- pw = FakePairwise(verdicts=[("b", 0.9)])
- track = StaticObjectTrack(services=FakeServices(pairwise=pw), judge=judge, agent=FakeAgent(_writer_by_candidate),
+ 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 len(pw.calls) == 1 and "pairwise c0 vs c1: c1 wins" in rec.rounds[0].notes
- assert "_cand/c1" in (ws.src / "model.py").read_text()
- ev = [e for e in EventLog(ws.events_path).read() if e["event"] == "pairwise.done"]
- assert ev and ev[0]["stage"] == "candidates" and ev[0]["accepted"] is True
+ 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):
@@ -201,42 +179,6 @@ def test_candidate_count_persists_for_resume_and_settings_default(tmp_path, chai
assert get_track("static_object", n_candidates=4)._n_candidates == 4
-# ----------------------------------------------------------------------------- refine pairwise tie-break
-def test_refine_round_within_margin_needs_pairwise_win(tmp_path, chair_plan, settings):
- spec = make_spec(language=Language.BLENDER, max_rounds=2)
- ws = Workspace(tmp_path / "runs" / "tie")
- agent = FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # {job.label} {job.round}\n"})
- pw = FakePairwise(verdicts=[("a", 0.8), ("b", 0.9)])
- # r01 scores +0.01 (noise) → pairwise says incumbent wins → best stays r00; r02 +0.02 → pairwise b wins → best r02
- judge = FakeJudge(scores=(0.60, 0.61, 0.62))
- track = StaticObjectTrack(services=FakeServices(pairwise=pw), judge=judge, agent=agent,
- planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.BLENDER),
- policy=RoundPolicy(max_rounds=2, target=0.9, plateau_window=5))
- rec = track.run(spec, ws)
- assert [r.score for r in rec.rounds] == pytest.approx([0.60, 0.61, 0.62])
- assert len(pw.calls) == 2 and rec.best_round == 2
- assert "pairwise r00 vs r01: r00 wins" in rec.rounds[1].notes and "→ keep" in rec.rounds[1].notes
- assert "pairwise r00 vs r02: r02 wins" in rec.rounds[2].notes and "→ replace" in rec.rounds[2].notes
- events = EventLog(ws.events_path).read()
- best_updates = [e["round"] for e in events if e["event"] == "best.updated"]
- assert best_updates == [0, 2]
- assert sum(1 for e in events if e["event"] == "pairwise.done") == 2
- # persisted round record carries the note + pairwise cost
- saved = json.loads((ws.root / "rounds" / "r01.json").read_text())
- assert "pairwise" in saved["notes"] and saved["usage"]["cost_usd"] > 0
-
-
-def test_refine_round_clear_delta_skips_pairwise(tmp_path, chair_plan, settings):
- spec = make_spec(language=Language.BLENDER, max_rounds=1)
- ws = Workspace(tmp_path / "runs" / "clear")
- pw = FakePairwise()
- track = StaticObjectTrack(services=FakeServices(pairwise=pw), judge=FakeJudge(scores=(0.50, 0.70)),
- agent=FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # {job.label}\n"}),
- planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings, runtime=FakeRuntime(Language.BLENDER))
- rec = track.run(spec, ws)
- assert rec.best_round == 1 and pw.calls == []
-
-
# ----------------------------------------------------------------------------- reference images
def test_reference_images_wire_judge_prompts_and_silhouette(tmp_path, chair_plan, settings):
ref = tmp_path / "ref.png"
diff --git a/harness/tests/orchestrator_tracks/test_fewer_turns.py b/harness/tests/orchestrator_tracks/test_fewer_turns.py
index 09379866..217da57d 100644
--- a/harness/tests/orchestrator_tracks/test_fewer_turns.py
+++ b/harness/tests/orchestrator_tracks/test_fewer_turns.py
@@ -3,14 +3,21 @@
from __future__ import annotations
from codeverse3d.config import FEWER_TURNS_ENV, Settings, fewer_turns_enabled, get_settings
+from codeverse3d.contracts.artifacts import BuildResult, Judgment
from codeverse3d.contracts.common import Language
+from codeverse3d.contracts.run import RoundRecord
from codeverse3d.orchestrator import RefineTask, TaskGroup
from codeverse3d.tracks.plan_features import LIVE_SWITCHES
from codeverse3d.tracks.prompting import INLINE_MAX_CHARS, INLINE_MAX_FILES, TURN_DISCIPLINE
from .conftest import make_spec
from .fakes import FakeAgent, FakeRuntime, FakeServices
-from .test_generation_depth import _round
+
+
+def _round(i: int, score: float) -> RoundRecord:
+ return RoundRecord(index=i, kind="refine", build=BuildResult(ok=True, language="blender"), commit=f"c{i}",
+ judgment=Judgment(rubric="r", scores={}, overall=score, passed=score >= 0.8))
+
SEAT = "import bpy\n\n\ndef build_seat():\n return bpy.context.object # SEAT-BODY\n"
LEG = "import bpy\n\n\ndef build_leg():\n return bpy.context.object # LEG-BODY\n"
diff --git a/harness/tests/orchestrator_tracks/test_fix_batch2.py b/harness/tests/orchestrator_tracks/test_fix_batch2.py
index f2c0aa48..62fcef6d 100644
--- a/harness/tests/orchestrator_tracks/test_fix_batch2.py
+++ b/harness/tests/orchestrator_tracks/test_fix_batch2.py
@@ -136,14 +136,14 @@ def test_a_failed_finalise_rebuild_cannot_finalize_silently(tmp_path, chair_plan
agent=FakeAgent(_writer), planner_model=_planner(chair_plan.model_dump(mode="json")),
settings=settings, runtime=RebuildFailsRuntime(Language.THREEJS))
rec = track.run(spec, ws)
- assert rec.status is RunStatus.PLATEAU and rec.best_round == 0 # the earned status stays
+ assert rec.status is RunStatus.MAX_ROUNDS and rec.best_round == 0 # the earned status stays
assert rec.final_score == pytest.approx(0.7) # ...and so do the paid scores
assert rec.error.startswith("finalise rebuild failed: Timeout")
assert "runtime crashed on rebuild" in rec.extra["finalise_rebuild_failed"]
assert not (ws.artifacts / "object.glb").is_file()
assert textured == [], "the texture pass must not run against a missing GLB"
on_disk = json.loads(ws.record_path.read_text())
- assert on_disk["error"].startswith("finalise rebuild failed") and on_disk["status"] == "plateau"
+ assert on_disk["error"].startswith("finalise rebuild failed") and on_disk["status"] == "max_rounds"
ev = [e for e in EventLog(ws.events_path).read() if e["event"] == "finalise.rebuild"]
assert ev and ev[-1]["ok"] is False
@@ -186,7 +186,7 @@ def test_degraded_verdict_never_scores_and_run_stops_as_judge_unavailable(tmp_pa
rec = track.run(spec, ws)
assert rec.rounds[1].judgment is None and rec.rounds[1].score is None # never 0.0
assert rec.best_round == 0 and rec.final_score == pytest.approx(0.65)
- assert rec.extra["stop_reason"] == "judge_unavailable" and rec.status is RunStatus.PLATEAU
+ assert rec.extra["stop_reason"] == "judge_unavailable" and rec.status is RunStatus.JUDGE_UNAVAILABLE
kinds = [e["event"] for e in EventLog(ws.events_path).read()]
assert "judge.degraded" in kinds and "judge.retry" in kinds
# the degraded summary never reaches a refine prompt
@@ -213,10 +213,10 @@ def test_degraded_verdict_recovers_via_rejudge_of_same_commit(tmp_path, chair_pl
planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
runtime=FakeRuntime(Language.THREEJS))
rec = track.run(spec, ws)
- assert rec.status is RunStatus.PASSED and rec.best_round == 1
- assert rec.rounds[1].score == pytest.approx(0.85)
- # the recovery re-judged the SAME commit: exactly 2 generation rounds ran
- assert [j.round for j in agent.jobs] == [0, 1]
+ assert rec.status is RunStatus.MAX_ROUNDS
+ assert [r.score for r in rec.rounds] == pytest.approx([0.55, 0.85, 0.85, 0.85])
+ # the recovery re-judged the SAME commit: every round was generated exactly once
+ assert [j.round for j in agent.jobs] == [0, 1, 2, 3]
saved = RoundRecord.model_validate(json.loads((ws.root / "rounds" / "r01.json").read_text()))
assert saved.judgment is not None and saved.judgment.overall == pytest.approx(0.85)
# audit f2: the recovery re-emits a CORRECTED cost.round so the audit stream stops
@@ -240,7 +240,7 @@ def test_resume_with_raised_budget_does_not_replan_or_reskeleton(tmp_path, chair
services = FakeServices()
mk = lambda: StaticObjectTrack(services=services, judge=FakeJudge(scores=(0.5, 0.6, 0.9)), agent=FakeAgent(_writer), # noqa: E731
planner_model=planner, settings=settings, runtime=FakeRuntime(Language.THREEJS),
- policy=RoundPolicy(max_rounds=1, target=0.8))
+ policy=RoundPolicy(max_rounds=1))
mk().run(spec, ws)
n_plan_calls = len(planner.requests)
src_before = (ws.src / "object.js").read_text()
@@ -300,7 +300,7 @@ def test_scene_refine_emits_rebuild_task_when_build_failed(tmp_path, settings):
error_message="Cannot read properties of undefined (reading 'update')",
error_file="src/zones/quay.js"),
gates=[GateReport(gate="lint:scene_threejs", passed=True)])
- tasks, instructions = track.refine_tasks(ctx, last, [last])
+ tasks, instructions = track.refine_tasks(ctx, last)
assert len(tasks) == 1 and tasks[0].kind == "rebuild"
assert tasks[0].files_hint == ["src/zones/quay.js"]
assert "ProbeError" in tasks[0].prompt and "Cannot read properties" in tasks[0].prompt
@@ -343,7 +343,7 @@ def test_scene_frames_gate_errors_flow_into_refine_instructions(tmp_path, settin
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, [last])
+ 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
diff --git a/harness/tests/orchestrator_tracks/test_fixed_rounds.py b/harness/tests/orchestrator_tracks/test_fixed_rounds.py
new file mode 100644
index 00000000..6338a32a
--- /dev/null
+++ b/harness/tests/orchestrator_tracks/test_fixed_rounds.py
@@ -0,0 +1,74 @@
+"""FIXED rounds (owner, 2026-09-22): a run is the baseline plus ``max_rounds`` refine rounds,
+each built on the round before it, and only the clock or a hard failure ends it early."""
+
+from __future__ import annotations
+
+import pytest
+
+from codeverse3d.contracts.common import Language
+from codeverse3d.contracts.run import RunStatus
+from codeverse3d.proc import EventLog
+from codeverse3d.tracks.static_object import StaticObjectTrack
+from codeverse3d.workspace import Workspace
+from tests.orchestrator_tracks.conftest import fake_clock, make_spec
+from tests.orchestrator_tracks.fakes import (
+ FakeAgent,
+ FakeJudge,
+ FakeRuntime,
+ FakeServices,
+ _planner,
+)
+
+
+def _track(chair_plan, settings, scores, *, agent=None) -> StaticObjectTrack:
+ agent = agent or FakeAgent(lambda job, ws: {"src/model.py": f"import bpy # {job.label} r{job.round}\n"})
+ return StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=scores), agent=agent,
+ planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
+ runtime=FakeRuntime(Language.BLENDER))
+
+
[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])
+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")
+ rec = _track(chair_plan, settings, scores).run(make_spec(language=Language.BLENDER, max_rounds=max_rounds), ws)
+ assert len(rec.rounds) == max_rounds + 1
+ assert [r.kind for r in rec.rounds] == ["baseline"] + ["refine"] * max_rounds
+ assert rec.status is RunStatus.MAX_ROUNDS and rec.extra["stop_reason"] == "max_rounds"
+ assert all(r.judgment is not None for r in rec.rounds), "the judge still scores every round"
+ stops = [e for e in EventLog(ws.events_path).read() if e["event"] == "stop"]
+ 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.BLENDER, 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):
+ model = ws.src / "model.py"
+ seen[job.round] = model.read_text() if model.is_file() else ""
+ return {"src/model.py": f"import bpy # written in r{job.round}\n"}
+
+ ws = Workspace(tmp_path / "runs" / "prev")
+ rec = _track(chair_plan, settings, (0.70, 0.30, 0.50), agent=FakeAgent(writer)).run(
+ make_spec(language=Language.BLENDER, max_rounds=2), ws)
+ assert seen[1] == "import bpy # written in r0\n"
+ assert seen[2] == "import bpy # written in r1\n", "r02 must refine r01, not the higher-scored r00"
+ assert rec.rounds[2].instructions, "the tasks come from r01's verdict and gates"
+ events = [e["event"] for e in EventLog(ws.events_path).read()]
+ assert "round.refine_from_best" not in events and "strategy.switch" not in events
diff --git a/harness/tests/orchestrator_tracks/test_generation_depth.py b/harness/tests/orchestrator_tracks/test_generation_depth.py
index f1d325e5..9cc51403 100644
--- a/harness/tests/orchestrator_tracks/test_generation_depth.py
+++ b/harness/tests/orchestrator_tracks/test_generation_depth.py
@@ -1,29 +1,10 @@
-"""Complexity-aware depth budgets, scoped baselines, and the gated detail round."""
+"""Complexity-aware depth budgets and scoped baselines."""
from __future__ import annotations
-from codeverse3d.contracts.artifacts import (
- BuildResult,
- GateFinding,
- GateReport,
- ImprovementItem,
- Judgment,
- Measurement,
- PartMeasure,
- Severity,
-)
from codeverse3d.contracts.common import Language
from codeverse3d.contracts.plan import BBox, PartPlan, StaticPlan
-from codeverse3d.contracts.run import RoundRecord
from codeverse3d.conventions import MAX_TRIS_OBJECT, to_snake
-from codeverse3d.orchestrator import (
- DETAIL_KIND,
- KIND_FOR_STRATEGY,
- REWRITE_KIND,
- RoundPolicy,
- StopPolicy,
- detail_blocked,
-)
from codeverse3d.tracks.depth import (
PartScope,
depth_budget,
@@ -31,7 +12,6 @@ from codeverse3d.tracks.depth import (
scope_groups,
scoped_generation_enabled,
)
-from codeverse3d.tracks.static_object import DRIFT_GATE, detail_instructions, drift_gate
from .conftest import make_spec
from .fakes import FakeAgent, FakeRuntime, FakeServices
@@ -41,17 +21,6 @@ def _files_for(name):
return [f"src/parts/{to_snake(name)}.py"]
-def _round(i: int, score: float | None, *, kind: str = "refine", gates=(), build_ok: bool = True) -> RoundRecord:
- j = Judgment(rubric="r", scores={}, overall=score, passed=bool(score and score >= 0.8)) if score is not None else None
- return RoundRecord(index=i, kind="baseline" if i == 0 else kind, judgment=j, gates=list(gates),
- build=BuildResult(ok=build_ok, language="blender"), commit=f"c{i}")
-
-
-def _gate_error() -> GateReport:
- return GateReport(gate="connectivity", passed=False, findings=[GateFinding(
- gate="connectivity", severity=Severity.ERROR, target="Seat", message="Seat floats 12 mm above FrontLeg")])
-
-
# ----------------------------------------------------------------------------- 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,
@@ -112,88 +81,6 @@ def test_scoped_generation_can_be_switched_off(monkeypatch):
assert scoped_generation_enabled() is True
-# ----------------------------------------------------------------------------- the detail round
-def test_kind_for_strategy_is_the_one_mapping():
- assert KIND_FOR_STRATEGY == {"same": "refine", "switch": REWRITE_KIND, "detail": DETAIL_KIND}
-
-
-def test_detail_round_is_offered_only_on_a_clean_finished_structure():
- pol = RoundPolicy(detail_rounds=1, target=0.9, judge_model="gemini:gemini-3.1-pro-preview")
- clean = [_round(0, 0.60), _round(1, 0.61), _round(2, 0.615)]
- assert detail_blocked(clean, pol) == ""
- assert "gate error" in detail_blocked([_round(0, 0.6), _round(1, 0.61, gates=[_gate_error()])], pol)
- assert "did not build" in detail_blocked([_round(0, 0.6), _round(1, 0.6, build_ok=False)], pol)
- assert "detail floor" in detail_blocked([_round(0, 0.2), _round(1, 0.2)], pol)
- assert "not judged" in detail_blocked([_round(0, 0.6), _round(1, None)], pol)
- spent = [*clean, _round(3, 0.62, kind=DETAIL_KIND)]
- assert "already spent" in detail_blocked(spent, pol)
- assert "disabled" in detail_blocked(clean, RoundPolicy(detail_rounds=0))
-
-
-def test_a_plateau_on_a_clean_object_becomes_one_detail_round():
- pol = RoundPolicy(max_rounds=6, target=0.9, plateau_window=2, min_delta=0.02, marginal_from_round=99,
- detail_rounds=1, judge_model="gemini:gemini-3.1-pro-preview")
- flat = [_round(0, 0.60), _round(1, 0.605), _round(2, 0.61)]
- d = StopPolicy(pol).evaluate(flat)
- assert (d.reason, d.strategy, d.stop) == ("continue", "detail", False)
- # ...and exactly once: after the detail round the same history stops as it meant to
- after = [*flat, _round(3, 0.62, kind=DETAIL_KIND)]
- assert StopPolicy(pol).evaluate(after).reason == "plateau"
- # a regression is never converted: repair money is not detail money
- reg = [_round(0, 0.70), _round(1, 0.50), _round(2, 0.48, kind=REWRITE_KIND)]
- assert StopPolicy(pol).evaluate(reg).reason == "regression"
- # detail_rounds=0 (every track that cannot build one) leaves the money stops untouched
- assert StopPolicy(RoundPolicy(**{**pol.__dict__, "detail_rounds": 0})).evaluate(flat).reason == "plateau"
-
-
-def test_detail_instructions_take_the_judges_detail_asks_then_the_standing_vocabulary():
- j = Judgment(rubric="r", scores={}, overall=0.6, passed=False, improvement_plan=[
- ImprovementItem(target="Seat", kind="material", instruction="give the seat an oiled-oak colour", priority=1),
- ImprovementItem(target="FrontLeg", kind="assembly", instruction="move the leg 12 mm in", priority=1),
- ])
- lines = detail_instructions(RoundRecord(index=1, kind="refine", judgment=j), max_lines=8)
- assert any("oiled-oak" in ln for ln in lines)
- assert not any("move the leg" in ln for ln in lines) # assembly work is the repair loop's
- assert any("Bevel or chamfer" in ln for ln in lines) # the standing vocabulary is always there
-
-
-# ----------------------------------------------------------------------------- the drift gate
-def _measurement(parts, *, extents=(1.0, 1.0, 1.0), tris=1000) -> Measurement:
- return Measurement(bbox_min=(0, 0, 0), bbox_max=extents, extents=extents, center=(0, 0, 0),
- tri_count=tris, n_meshes=len(parts), n_islands=len(parts),
- parts=[PartMeasure(name=n, bbox_min=lo, bbox_max=hi, tri_count=10, islands=1) for n, lo, hi in parts])
-
-
-def test_drift_gate_allows_detail_only_changes():
- before = _measurement([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))], tris=1000)
- after = _measurement([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))], tris=4200)
- g = drift_gate(before, after, tol_m=0.005)
- assert g.passed and g.gate == DRIFT_GATE
- assert "+3,200 triangles" in g.findings[0].message
-
- after = _measurement([
- ("Seat", (0, 0, 0), (0.4, 0.04, 0.4)),
- ("Bolt", (0, 0, 0), (0.01, 0.01, 0.01)),
- ])
- g = drift_gate(before, after, tol_m=0.005)
- assert g.passed and any(f.severity is Severity.WARN and "new top-level part" in f.message for f in g.findings)
- assert drift_gate(None, _measurement([]), tol_m=0.005).passed
-
-
-def test_drift_gate_fails_when_the_detail_round_moved_something():
- before = _measurement([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))])
- cases = [
- ([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))], (1.2, 1.0, 1.0), "overall x extent"),
- ([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))], (1.0, 1.2, 1.0), "overall z extent"),
- ([("Seat", (0.02, 0, 0), (0.42, 0.04, 0.4))], (1.0, 1.0, 1.0), "moved 20.0 mm"),
- ([], (1.0, 1.0, 1.0), "disappeared"),
- ]
- for after_parts, extents, needle in cases:
- g = drift_gate(before, _measurement(after_parts, extents=extents), tol_m=0.005, language="blender")
- assert not g.passed and any(needle in f.message for f in g.findings)
- assert all(f.data.get("kind") == "detail_drift" for f in g.findings)
-
-
# ----------------------------------------------------------------------------- the track wiring
def big_plan(n: int = 11) -> StaticPlan:
"""A plan past the scoping threshold, with a real attachment tree (Body → N children)."""
@@ -250,28 +137,6 @@ def test_scoping_off_single_shot_or_a_small_plan_falls_back_to_one_task(tmp_path
assert [t.label for t in t3.baseline_tasks(c3)] == ["baseline"] # 5 parts: one session is fine
-def test_detail_tasks_are_scoped_frozen_and_arm_the_drift_gate(tmp_path, settings):
- track, ctx = _ctx(tmp_path, big_plan(), settings)
- last = _round(2, 0.62)
- last.measurement = _measurement([("Seat", (0, 0, 0), (0.4, 0.04, 0.4))])
- tasks, lines = track.detail_tasks(ctx, last, 3)
- assert tasks and lines
- assert all(t.kind == DETAIL_KIND and t.round == 3 for t in tasks)
- assert ctx.extra["detail_round"] == 3 and ctx.extra["detail_baseline"] is last.measurement
- body = tasks[0].prompt
- assert "Do not move, resize, rename, add or delete any part" in body
- assert "DETAIL BUDGET" in body
- # the gate the prompt promises actually fires from ctx.extra
- pipe = track.make_pipeline()
- moved = _measurement([("Seat", (0.03, 0, 0), (0.43, 0.04, 0.4))])
- gates = pipe.gates(ctx, 3, BuildResult(ok=True, language="blender", glb_path=""), moved)
- drift = [g for g in gates if g.gate == DRIFT_GATE]
- assert drift and not drift[0].passed
- # ...and not on any other round
- assert [g for g in pipe.gates(ctx, 4, BuildResult(ok=True, language="blender", glb_path=""), moved)
- if g.gate == DRIFT_GATE] == []
-
-
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
@@ -298,10 +163,10 @@ def test_phases_run_in_order_and_a_failed_phase_does_not_kill_the_round(tmp_path
assert [r.ok for r in out] == [True, False, True]
-def test_the_three_depth_templates_render_with_strict_undefined(tmp_path, settings):
+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, judge_digest, scope_context
+ from codeverse3d.tracks.prompting import base_prompt_context, scope_context
track, ctx = _ctx(tmp_path, big_plan(), settings)
scope = track.scopes(ctx)[0]
@@ -311,34 +176,3 @@ def test_the_three_depth_templates_render_with_strict_undefined(tmp_path, settin
entry = track.entry_files(ctx)
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 asm
- det = render("tracks/detail_object.j2", **base_prompt_context(
- ctx, round_index=3, tasks=["Body: bevel the shell"], files=entry,
- judge_summary=judge_digest(_round(2, 0.6)), current_files={}))
- assert "THE RULE" in det and "Do not move, resize, rename" in det
-
-
-def test_a_full_run_spends_exactly_one_detail_round_after_the_plateau(tmp_path, chair_plan, settings):
- """End to end on fakes: flat scores → plateau → ONE round of kind 'detail', gated by
- detail_drift, and never a second one."""
- from codeverse3d.contracts.run import RunStatus
- from codeverse3d.tracks.static_object import DRIFT_GATE as _DRIFT
- from codeverse3d.tracks.static_object import StaticObjectTrack
- from codeverse3d.workspace import Workspace
-
- from .fakes import FakeJudge
- from .test_fix_batch2 import _planner, _writer
-
- spec = make_spec(max_rounds=5)
- ws = Workspace(tmp_path / "runs" / "detail")
- track = StaticObjectTrack(services=FakeServices(), judge=FakeJudge(scores=(0.6,), targets=("Seat",)),
- agent=FakeAgent(_writer), planner_model=_planner(chair_plan.model_dump(mode="json")),
- settings=settings, runtime=FakeRuntime(Language.THREEJS))
- rec = track.run(spec, ws)
- kinds = [r.kind for r in rec.rounds]
- assert kinds.count(DETAIL_KIND) == 1, kinds
- detail = next(r for r in rec.rounds if r.kind == DETAIL_KIND)
- assert any(g.gate == _DRIFT for g in detail.gates) # the promise is checked in code
- assert rec.status in (RunStatus.PLATEAU, RunStatus.PASSED)
- events = [__import__("json").loads(line) for line in ws.events_path.read_text().splitlines()]
- assert any(e["event"] == "detail.planned" for e in events)
- assert any(e["event"] == "refine.planned" and e.get("strategy") == "detail" for e in events)
diff --git a/harness/tests/orchestrator_tracks/test_integrations2.py b/harness/tests/orchestrator_tracks/test_integrations2.py
index e0536f2c..de031d4f 100644
--- a/harness/tests/orchestrator_tracks/test_integrations2.py
+++ b/harness/tests/orchestrator_tracks/test_integrations2.py
@@ -142,7 +142,7 @@ def test_texture_pass_failure_is_additive_not_fatal(tmp_path, chair_plan, settin
monkeypatch.setattr(trun, "texture_pass", boom)
rec, ws, judge, services = _static_run(tmp_path, chair_plan, settings, tags=["texture"])
- assert rec.status in (RunStatus.PLATEAU, RunStatus.PASSED, RunStatus.BUDGET)
+ assert rec.status in (RunStatus.MAX_ROUNDS, RunStatus.BUDGET)
assert "texturing" not in rec.extra
kinds = [e["event"] for e in EventLog(ws.events_path).read()]
assert "texture.failed" in kinds
diff --git a/harness/tests/orchestrator_tracks/test_orchestrator.py b/harness/tests/orchestrator_tracks/test_orchestrator.py
index 11e9307a..e909165f 100644
--- a/harness/tests/orchestrator_tracks/test_orchestrator.py
+++ b/harness/tests/orchestrator_tracks/test_orchestrator.py
@@ -22,10 +22,8 @@ from codeverse3d.orchestrator import (
BudgetExceeded,
BudgetGuard,
RefineTask,
- RoundPolicy,
RunState,
StageRunner,
- StopPolicy,
build_refine_instructions,
hash_inputs,
pick_best_round,
@@ -147,30 +145,13 @@ def test_stage_runner_raises_and_records_nothing(tmp_ws):
assert hash_inputs({"a": [1, 2]}) == hash_inputs({"a": (1, 2)})
-# ----------------------------------------------------------------------------- stop policy
+# ----------------------------------------------------------------------------- best round
def _round(i: int, score: float | None, errors: int = 0, build_ok: bool = True) -> RoundRecord:
j = Judgment(rubric="r", scores={"a": score}, overall=score, passed=score >= 0.8) if score is not None else None
gates = [GateReport(gate="g", passed=errors == 0, findings=[GateFinding(gate="g", severity=Severity.ERROR, message="e")] * errors)]
return RoundRecord(index=i, kind="x", judgment=j, gates=gates, build=BuildResult(ok=build_ok, language="l"), commit=f"c{i}")
-def test_stop_policy_decisions():
- sp = StopPolicy(RoundPolicy(max_rounds=3, plateau_window=2, min_delta=0.02, target=0.8))
- assert sp.evaluate([]).reason == "continue"
- assert sp.evaluate([_round(0, 0.5)]).reason == "continue"
- assert sp.evaluate([_round(0, 0.5)], budget_ok=False).reason == "budget"
- assert sp.evaluate([_round(0, 0.5), _round(1, 0.85)]).reason == "pass"
- # three flat rounds: from r03 on the marginal-value stop answers first (both stop;
- # "diminishing_returns" is the more precise reason — see test_round_economics.py)
- assert sp.evaluate([_round(0, 0.5), _round(1, 0.51), _round(2, 0.515)]).reason == "diminishing_returns"
- flat = StopPolicy(RoundPolicy(max_rounds=3, plateau_window=2, min_delta=0.02, target=0.8, marginal_from_round=99))
- assert flat.evaluate([_round(0, 0.5), _round(1, 0.51), _round(2, 0.515)]).reason == "plateau"
- assert sp.evaluate([_round(0, 0.5), _round(1, 0.6), _round(2, 0.7)]).reason == "continue"
- assert sp.evaluate([_round(0, 0.5), _round(1, 0.6), _round(2, 0.7), _round(3, 0.75)]).reason == "max_rounds"
- # unscored rounds (build failed) do not count as plateau evidence
- assert sp.evaluate([_round(0, 0.5), _round(1, None, build_ok=False), _round(2, None, build_ok=False)]).reason == "continue"
-
-
def test_pick_best_round_prefers_score_then_fewer_errors_then_recency():
rounds = [_round(0, 0.5), _round(1, 0.7, errors=2), _round(2, 0.7, errors=0), _round(3, 0.6)]
assert pick_best_round(rounds) == 2
diff --git a/harness/tests/orchestrator_tracks/test_prompts_assets.py b/harness/tests/orchestrator_tracks/test_prompts_assets.py
index 38ef9355..92e0d90c 100644
--- a/harness/tests/orchestrator_tracks/test_prompts_assets.py
+++ b/harness/tests/orchestrator_tracks/test_prompts_assets.py
@@ -21,7 +21,7 @@ from tests.orchestrator_tracks.conftest import make_spec
from 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", "detail_object",
+ "generate_static_part", "assemble_static",
"scene_asset", "scene_env", "scene_zone", "scene_refine"}
diff --git a/harness/tests/orchestrator_tracks/test_refactor_batch2.py b/harness/tests/orchestrator_tracks/test_refactor_batch2.py
index c7dc7fb4..a7d0ca17 100644
--- a/harness/tests/orchestrator_tracks/test_refactor_batch2.py
+++ b/harness/tests/orchestrator_tracks/test_refactor_batch2.py
@@ -62,24 +62,6 @@ def test_candidate_width_precedence(tmp_path, settings):
assert ctx.policy.n_candidates == 3
-
-def test_injected_policy_keeps_the_track_detail_round(tmp_path, settings):
- """economy/quality inject RoundPolicy(judge_samples=n) and used to lose the static
- track's detail round (a policy object stood in for 'detail_rounds was chosen')."""
- from codeverse3d.orchestrator import RoundPolicy
- from codeverse3d.tracks.lifecycle import DEFAULT_DETAIL_ROUNDS
-
- ws = Workspace(tmp_path / "eco").create()
- track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.THREEJS),
- policy=RoundPolicy(judge_samples=2))
- ctx = track.build_context(make_spec(), ws, EventLog(ws.events_path), RunState())
- assert ctx.policy.judge_samples == 2 and ctx.policy.detail_rounds == DEFAULT_DETAIL_ROUNDS == 1
- # a chosen 0 still means off
- track = StaticObjectTrack(services=FakeServices(), settings=settings, runtime=FakeRuntime(Language.THREEJS),
- policy=RoundPolicy(judge_samples=2, detail_rounds=0))
- assert track.build_context(make_spec(), ws, EventLog(ws.events_path), RunState()).policy.detail_rounds == 0
-
-
def test_options_texture_triggers_texture_pass(tmp_path, chair_plan, settings, monkeypatch):
calls = {}
@@ -100,7 +82,7 @@ def test_options_texture_triggers_texture_pass(tmp_path, chair_plan, settings, m
planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
runtime=FakeRuntime(Language.THREEJS))
rec = track.run(spec, ws)
- assert rec.status in (RunStatus.PASSED, RunStatus.PLATEAU)
+ assert rec.status is RunStatus.MAX_ROUNDS
assert calls, "options.texture must run the texture pass without the legacy tag"
assert rec.extra.get("texturing") == {"shipped": True}
diff --git a/harness/tests/orchestrator_tracks/test_resume_reconcile.py b/harness/tests/orchestrator_tracks/test_resume_reconcile.py
index 9e2e9d1c..060ade50 100644
--- a/harness/tests/orchestrator_tracks/test_resume_reconcile.py
+++ b/harness/tests/orchestrator_tracks/test_resume_reconcile.py
@@ -24,7 +24,6 @@ from tests.orchestrator_tracks.fakes import (
FakeAgent,
FakeChatModel,
FakeJudge,
- FakePairwise,
FakeRuntime,
FakeServices,
_planner,
@@ -58,7 +57,7 @@ def completed_run(tmp_path, chair_plan, settings):
def build(max_rounds: int = 1, **spec_kw) -> SimpleNamespace:
r = SimpleNamespace(plan=plan, ws=Workspace(tmp_path / "runs" / "r"),
spec=make_spec(language=Language.BLENDER, max_rounds=max_rounds, **spec_kw),
- policy=RoundPolicy(max_rounds=max_rounds, target=0.9))
+ policy=RoundPolicy(max_rounds=max_rounds))
r.rerun = partial(rerun, r)
r.record = r.rerun()
return r
@@ -95,41 +94,6 @@ def test_crash_between_round_write_and_state_save_delivers_the_newer_round(compl
assert ev and ev[-1]["state_was_stale"] is True and ev[-1]["best_changed"] is True
-def test_a_paid_pairwise_verdict_survives_the_crash_window(tmp_path, chair_plan, settings):
- """``choose_best_round`` re-persists rNN.json WITH its verdict and only THEN does
- ``_promote_best`` save the state, so a kill in that gap (or any state predating
- ``best_considered_through``) left a paid ~$0.05 judgement on disk that reconcile
- could not see — and score-only re-ranking silently reversed it. 18 runs on disk
- were in that shape (2026-08-30)."""
- plan = chair_plan.model_dump(mode="json")
-
- def build(pairwise):
- return StaticObjectTrack(services=FakeServices(pairwise=pairwise), judge=FakeJudge(scores=(0.70, 0.72)),
- agent=FakeAgent(_writer), planner_model=_planner(plan), settings=settings,
- runtime=FakeRuntime(Language.BLENDER),
- policy=RoundPolicy(max_rounds=1, target=0.9))
-
- spec = make_spec(language=Language.BLENDER, max_rounds=1)
- ws = Workspace(tmp_path / "runs" / "r")
- paid = FakePairwise([("a", 0.9)]) # r1 outscores r0 by 0.02 (inside the margin); the judge says r0
- rec1 = build(paid).run(spec, ws)
- assert len(paid.calls) == 1 and rec1.best_round == 0 and rec1.final_score == pytest.approx(0.70)
- note = rec1.rounds[1].pairwise
- assert note is not None and note.winner == "a" and note.accepted is False
- on_disk = json.loads((ws.root / "rounds" / "r01.json").read_text())
- assert on_disk["pairwise"]["winner"] == "a", "the verdict must be durable, not just in notes"
-
- state = json.loads(ws.state_path.read_text()) # ...killed before _promote_best saved
- state["best_considered_through"] = 0
- ws.state_path.write_text(json.dumps(state))
-
- again = FakePairwise([("b", 0.99)]) # a second verdict would flip it
- rec2 = build(again).run(spec, ws, resume=True)
- assert again.calls == [], "resume replays the stored verdict, it never buys another"
- assert rec2.best_round == 0 and rec2.final_score == pytest.approx(0.70)
- assert RunState.load(ws).best_round == 0
-
-
def test_a_self_consistent_state_with_an_unranked_round_still_re_ranks(completed_run):
"""The sharper crash shape (reproduced by review, 2026-08-27): the round was saved
BEFORE best selection, so completed_rounds/round_commits matched the journal exactly
@@ -200,7 +164,7 @@ def test_a_planner_outage_on_resume_keeps_the_recorded_history(completed_run):
raise RuntimeError("planner 503 storm")
with pytest.raises(RuntimeError, match="503 storm"):
- run.rerun(planner=FakeChatModel(_boom), policy=RoundPolicy(max_rounds=1, target=0.9), resume=True)
+ run.rerun(planner=FakeChatModel(_boom), policy=RoundPolicy(max_rounds=1), resume=True)
saved = json.loads(ws.record_path.read_text())
assert saved["status"] == "failed" and "503 storm" in saved["error"]
assert [r["index"] for r in saved["rounds"]] == [0], "a planner outage must not wipe the history"
diff --git a/harness/tests/orchestrator_tracks/test_round_economics.py b/harness/tests/orchestrator_tracks/test_round_economics.py
index d3640141..14040fd2 100644
--- a/harness/tests/orchestrator_tracks/test_round_economics.py
+++ b/harness/tests/orchestrator_tracks/test_round_economics.py
@@ -1,4 +1,4 @@
-"""Round stop economics, session limits, judge skipping, and cost attribution."""
+"""Session limits, judge skipping, and cost attribution of a round."""
from __future__ import annotations
@@ -7,18 +7,10 @@ import json
import pytest
from codeverse3d.contracts.agent import AgentJob, AgentResult
-from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Judgment, Severity
+from codeverse3d.contracts.artifacts import BuildResult, GateFinding, GateReport, Severity
from codeverse3d.contracts.common import Language, Usage
from codeverse3d.contracts.run import RoundRecord, RunStatus
-from codeverse3d.orchestrator import (
- DEFAULT_JUDGE_SIGMA,
- REWRITE_KIND,
- RoundPolicy,
- StopPolicy,
- best_score,
- judge_sigma,
- last_gain,
-)
+from codeverse3d.orchestrator import RoundPolicy
from codeverse3d.proc import EventLog
from codeverse3d.tracks.generation import (
DEFAULT_AGENT_MAX_TURNS,
@@ -28,7 +20,6 @@ from codeverse3d.tracks.generation import (
run_agent_task,
turn_capped,
)
-from codeverse3d.tracks.lifecycle import BaseTrack
from codeverse3d.tracks.static_object import StaticObjectTrack
from codeverse3d.workspace import Workspace
from tests.orchestrator_tracks.conftest import fake_clock, make_spec
@@ -41,119 +32,6 @@ from tests.orchestrator_tracks.fakes import (
)
-def _round(i: int, score: float | None, kind: str = "refine") -> RoundRecord:
- j = Judgment(rubric="r", scores={}, overall=score, passed=bool(score and score >= 0.8)) if score is not None else None
- return RoundRecord(index=i, kind="baseline" if i == 0 else kind, judgment=j,
- build=BuildResult(ok=True, language="l"), commit=f"c{i}")
-
-
-# ----------------------------------------------------------------------------- judge noise table
-def test_judge_sigma_comes_from_the_one_measured_table():
- from codeverse3d.cost.routing import JUDGE_NOISE
-
- assert judge_sigma("gemini:gemini-3.1-pro-preview") == pytest.approx(JUDGE_NOISE["gemini-3.1-pro-preview"][0])
- assert judge_sigma("gemini:gemini-3.7-flash") == pytest.approx(0.083)
- assert judge_sigma("gemini:gemini-3.7-flash-002") == pytest.approx(0.083) # version suffix
- assert judge_sigma("") == DEFAULT_JUDGE_SIGMA and judge_sigma("who:knows") == DEFAULT_JUDGE_SIGMA
- pol = RoundPolicy(judge_model="gemini:gemini-3.7-flash")
- assert pol.sigma == pytest.approx(0.083)
- assert pol.regression_delta == pytest.approx(0.083) and pol.marginal_delta == pytest.approx(0.1245)
-
-
-def test_best_score_and_last_gain():
- h = [_round(0, 0.5), _round(1, 0.62), _round(2, 0.55)]
- assert best_score(h) == pytest.approx(0.62) and last_gain(h) == pytest.approx(-0.07)
- assert best_score([]) is None and last_gain([_round(0, 0.5)]) is None
- assert last_gain([_round(0, 0.5), _round(1, None)]) is None
-
-
-# ----------------------------------------------------------------------------- regression
-def test_a_regression_buys_a_change_of_shape_then_stops():
- sp = StopPolicy(RoundPolicy(max_rounds=4, target=0.9, judge_model="gemini:gemini-3.1-pro-preview",
- marginal_from_round=99))
- inside = sp.evaluate([_round(0, 0.60), _round(1, 0.58)]) # −0.02 < σ 0.030 → judge noise
- assert inside.reason == "continue" and inside.strategy == "same"
- first = sp.evaluate([_round(0, 0.60), _round(1, 0.52)]) # −0.08: a real regression
- assert first.reason == "continue" and first.strategy == "switch" and "0.520" in first.detail
- again = sp.evaluate([_round(0, 0.60), _round(1, 0.52), _round(2, 0.50, kind=REWRITE_KIND)])
- assert again.reason == "regression" and "changed strategy" in again.detail
- twice = sp.evaluate([_round(0, 0.60), _round(1, 0.52), _round(2, 0.55)]) # two regressions vs best
- assert twice.reason == "regression"
-
-
-def test_a_sub_noise_dip_never_burns_the_strategy_switch():
- from codeverse3d.orchestrator import meaningful_regression
-
- sp = StopPolicy(RoundPolicy(max_rounds=4, target=0.9, judge_model="gemini:gemini-3.1-pro-preview",
- marginal_from_round=99))
- d = sp.evaluate([_round(0, 0.60), _round(1, 0.58), _round(2, 0.50)])
- assert (d.reason, d.strategy) == ("continue", "switch"), "the single switch must still be offered"
- pol = RoundPolicy(judge_model="gemini:gemini-3.1-pro-preview")
- assert not meaningful_regression(0.58, 0.60, pol) # sub-noise dip: not a regression
- assert meaningful_regression(0.50, 0.60, pol) # a real one
- assert not meaningful_regression(None, 0.60, pol) and not meaningful_regression(0.5, None, pol)
-
-
-def test_a_noisy_judge_widens_the_regression_band():
- flash = StopPolicy(RoundPolicy(max_rounds=4, target=0.9, marginal_from_round=99,
- judge_model="gemini:gemini-3.7-flash"))
- # −0.06 is a regression for pro (σ 0.030) but inside flash's own noise (σ 0.083)
- assert flash.evaluate([_round(0, 0.60), _round(1, 0.54)]).strategy == "same"
- pro = StopPolicy(RoundPolicy(max_rounds=4, target=0.9, marginal_from_round=99,
- judge_model="gemini:gemini-3.1-pro-preview"))
- assert pro.evaluate([_round(0, 0.60), _round(1, 0.54)]).strategy == "switch"
-
-
-# ----------------------------------------------------------------------------- diminishing returns
-def test_r03_only_runs_when_the_last_round_paid_for_itself():
- sp = StopPolicy(RoundPolicy(max_rounds=4, target=0.9, judge_model="gemini:gemini-3.1-pro-preview"))
- # r02 gained +0.10 ≫ 1.5σ = 0.045 → r03 is worth starting
- assert sp.evaluate([_round(0, 0.4), _round(1, 0.5), _round(2, 0.6)]).reason == "continue"
- # r02 gained +0.03 < 0.045 → not worth another round
- d = sp.evaluate([_round(0, 0.40), _round(1, 0.55), _round(2, 0.58)])
- assert d.reason == "diminishing_returns" and "1.5 × judge σ" in d.detail
- # ... and the rule does not apply to r01/r02, which the audit shows are the good buys
- assert sp.evaluate([_round(0, 0.40), _round(1, 0.42)]).reason == "continue"
- # scoring at/above target without passing (a failed must-item) is not worth
- # another refine round either — the score is not what is missing
- above = RoundRecord(index=2, kind="refine", build=BuildResult(ok=True, language="l"),
- judgment=Judgment(rubric="r", scores={}, overall=0.95, passed=False))
- at_target = sp.evaluate([_round(0, 0.4), _round(1, 0.6), above])
- assert at_target.reason == "diminishing_returns" and "target" in at_target.detail
-
-
-def test_the_marginal_round_is_configurable():
- sp = StopPolicy(RoundPolicy(max_rounds=4, target=0.9, marginal_from_round=2,
- judge_model="gemini:gemini-3.1-pro-preview"))
- assert sp.evaluate([_round(0, 0.40), _round(1, 0.42)]).reason == "diminishing_returns"
- # the detail states the multiple that was APPLIED, not the default one
- wide = StopPolicy(RoundPolicy(max_rounds=4, target=0.9, marginal_sigma=3.0,
- judge_model="gemini:gemini-3.1-pro-preview"))
- d = wide.evaluate([_round(0, 0.40), _round(1, 0.50), _round(2, 0.57)])
- assert d.reason == "diminishing_returns" and "3 × judge σ" in d.detail and "1.5 ×" not in d.detail
-
-
-def test_the_stop_order_is_exhausted_regression_then_marginal_then_switch_then_plateau():
- pro = dict(max_rounds=4, target=0.9, judge_model="gemini:gemini-3.1-pro-preview")
- sp = StopPolicy(RoundPolicy(**pro))
- # 1. the switch is already spent (a rewrite regressed again) — outranks everything,
- # even though the marginal test would also stop here (last gain −0.10)
- spent = [_round(0, 0.60), _round(1, 0.52), _round(2, 0.50, kind=REWRITE_KIND)]
- assert sp.evaluate(spent).reason == "regression" and "changed strategy" in sp.evaluate(spent).detail
- # 2. at r03 the marginal test beats a FIRST regression: no shape is worth $0.5 there
- marginal = [_round(0, 0.60), _round(1, 0.65), _round(2, 0.55)]
- assert sp.evaluate(marginal).reason == "diminishing_returns"
- # 3. before r03 the same first regression buys exactly one change of shape
- switch = sp.evaluate([_round(0, 0.60), _round(1, 0.52)])
- assert (switch.reason, switch.strategy, switch.stop) == ("continue", "switch", False)
- # 4. plateau is the fallback: no regression, marginal test not in force, no gain
- flat = StopPolicy(RoundPolicy(max_rounds=4, target=0.9, marginal_from_round=99, plateau_window=2,
- min_delta=0.02, judge_model="gemini:gemini-3.1-pro-preview"))
- assert flat.evaluate([_round(0, 0.50), _round(1, 0.505), _round(2, 0.51)]).reason == "plateau"
- # ... and a run that is still climbing is never stopped by any of the four
- assert flat.evaluate([_round(0, 0.50), _round(1, 0.60), _round(2, 0.70)]).reason == "continue"
-
-
# ----------------------------------------------------------------------------- turn budget
class _TurnAgent:
"""Burns turns; reports 'max_turns (N) reached' when it runs out."""
@@ -267,8 +145,8 @@ def test_task_stage_names_the_cost_bucket_a_task_spends_in():
assert t("rebuild") == "repair" # regenerating after a failed build IS repair money
assert t("zone") == "zones" and t("asset") == "assets" and t("asset_fix") == "assets"
assert t("env") == "env"
- # the static track's surface-detail round is refine money, not "other" — it filed as
- # Stage.OTHER until 2026-08-30 because _LABEL_STAGES had no "detail" prefix
+ # the static track's surface-detail round (gone 2026-09-22) was refine money, not "other":
+ # the recorded runs that have one still file it there
assert t("detail") == "refine" and t("detail", "detail_seat") == "refine"
# an unknown kind falls back to the label, which record_call maps by prefix
assert t("something_new", "asset_koi") == "asset_koi"
@@ -299,7 +177,6 @@ def test_skip_judge_reasons_are_only_states_where_the_verdict_is_never_bought(tm
ctx.budget.add(Usage(cost_usd=99.0), stage="refine")
ctx.budget._active_s = (ctx.budget.budget.max_minutes + 1) * 60 # noqa: SLF001
assert skip_judge_reason(ctx, renders=_renders()) == "budget already exceeded"
- assert StopPolicy(ctx.policy).evaluate([_round(0, 0.5)], budget_ok=ctx.budget.ok()).reason == "budget"
ctx.judge = None
assert skip_judge_reason(ctx, renders=_renders()) == "no judge configured"
@@ -373,30 +250,27 @@ def _writer(job, ws):
return {"src/object.js": f"// {job.label} r{job.round}\nexport function build(THREE) {{}}\n"}
-def test_the_loop_switches_shape_after_a_regression_and_emits_cost_rounds(tmp_path, chair_plan, settings):
- """r01 regresses hard → r02 is ONE whole-object rewrite, not another per-part fan-out."""
+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)."""
spec = make_spec(max_rounds=3)
ws = Workspace(tmp_path / "runs" / "regress")
agent = FakeAgent(_writer, cost=0.02)
- judge = FakeJudge(scores=(0.60, 0.30, 0.35))
+ judge = FakeJudge(scores=(0.60, 0.30, 0.35, 0.40))
track = StaticObjectTrack(services=FakeServices(contract_errors=2), judge=judge, agent=agent,
planner_model=_planner(chair_plan.model_dump(mode="json")), settings=settings,
- runtime=FakeRuntime(Language.THREEJS),
- policy=RoundPolicy(max_rounds=3, target=0.8, judge_model="gemini:gemini-3.1-pro-preview"))
+ runtime=FakeRuntime(Language.THREEJS), policy=RoundPolicy(max_rounds=3))
rec = track.run(spec, ws)
- assert [r.kind for r in rec.rounds] == ["baseline", "refine", REWRITE_KIND]
- assert rec.extra["stop_reason"] == "regression" and rec.status is RunStatus.PLATEAU
+ assert [r.kind for r in rec.rounds] == ["baseline", "refine", "refine", "refine"]
+ assert rec.extra["stop_reason"] == "max_rounds" and rec.status is RunStatus.MAX_ROUNDS
events = EventLog(ws.events_path).read()
- switch = next(e for e in events if e["event"] == "strategy.switch")
- assert switch["reason"] == "regression"
- rewrite = [j for j in agent.jobs if "rewrite" in j.prompt.lower() or "made the artifact WORSE" in j.prompt]
- assert rewrite, "the rewrite round must tell the agent the last round made it worse"
- assert len([j for j in agent.jobs if j.round == 2]) == 1 # ONE task, not a per-part fan-out
+ assert not [e for e in events if e["event"] in ("strategy.switch", "round.refine_from_best")]
+ assert not [j for j in agent.jobs if "made the artifact WORSE" in j.prompt]
# every round reports what it burned
costs = [e for e in events if e["event"] == "cost.round"]
- assert len(costs) == 3 and all("generate" in c["stages"] for c in costs)
+ assert len(costs) == 4 and all("generate" in c["stages"] for c in costs)
assert costs[0]["agent_turns"] == 0 # the fake agent keeps no transcript
- assert costs[1]["wasted"] is True and costs[1]["waste_reason"] == "regression"
+ assert [c["wasted"] for c in costs] == [False] * 4 and "previous_best" not in costs[1]
assert costs[2]["judge_usd"] > 0 and costs[2]["run_usd"] >= costs[1]["run_usd"]
assert rec.extra["cost_by_stage"]["judge"] > 0 and rec.extra["cost_by_stage"]["refine"] > 0
# ... and the run opens its own priced ledger (telemetry/cost.jsonl + the root alias) even
@@ -419,7 +293,7 @@ def test_a_lint_stuck_run_keeps_every_score_instead_of_deferring_the_verdict(tmp
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, target=0.9))
+ 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"] == []
@@ -441,7 +315,7 @@ def test_a_round_that_raises_still_reports_what_it_burned(tmp_path, chair_plan,
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, target=0.9))
+ runtime=FakeRuntime(Language.THREEJS), policy=RoundPolicy(max_rounds=2))
with fake_clock():
rec = track.run(spec, ws)
assert rec.status is RunStatus.BUDGET
@@ -480,31 +354,3 @@ def test_a_run_past_its_hard_ceiling_cannot_start_another_session(tmp_ws):
task=GenerationTask(label="baseline", prompt="p", round=0, kind="baseline"),
budget=g)
assert agent.jobs == [] # the treadmill ends BEFORE the agent is invoked
-
-
-# ----------------------------------------------------------------------------- refine from the best round
-def test_a_refine_after_a_regression_restores_the_best_round_and_plans_from_its_verdict(tmp_path):
- """Loop 22 (2026-09-09): 0.66 → 0.61 → 0.47, each refine building on the round before it while
- the best sat in git. After StopPolicy's ``switch`` the working tree is the BEST round again
- and the tasks come from its verdict; a same-shape refine keeps building on the last round."""
- from types import SimpleNamespace
-
- from codeverse3d.workspace import Workspace
-
- ws = Workspace(tmp_path / "run").create()
- (ws.src / "scene.js").write_text("// r0: the good one\n")
- c0 = ws.commit("r00")
- (ws.src / "scene.js").write_text("// r1: the regression\n")
- c1 = ws.commit("r01")
- rounds = [_round(0, 0.66), _round(1, 0.47)]
- rounds[0].commit, rounds[1].commit = c0, c1
- events: list[dict] = []
- ctx = SimpleNamespace(ws=ws, state=SimpleNamespace(best_round=0), events=SimpleNamespace(emit=lambda name, **kw: events.append({"event": name, **kw})))
- same = BaseTrack._refine_base(ctx, rounds, "same")
- assert same is rounds[1] and ws.head() == c1 and not events # no regression: the last round
- base = BaseTrack._refine_base(ctx, rounds, "switch")
- assert base is rounds[0] and (ws.src / "scene.js").read_text() == "// r0: the good one\n"
- assert ws.head() != c1 and events[0]["event"] == "round.refine_from_best" and events[0]["best"] == 0 and events[0]["regressed"] == 1
- # the best IS the last round (nothing regressed past it): nothing to restore
- ctx.state.best_round = 1
- assert BaseTrack._refine_base(ctx, rounds, "switch") is rounds[1]
diff --git a/harness/tests/orchestrator_tracks/test_tracks.py b/harness/tests/orchestrator_tracks/test_tracks.py
index 61529e69..b9d4f8fc 100644
--- a/harness/tests/orchestrator_tracks/test_tracks.py
+++ b/harness/tests/orchestrator_tracks/test_tracks.py
@@ -53,13 +53,14 @@ def test_static_track_end_to_end_agent_path(tmp_path, chair_plan, settings):
track = StaticObjectTrack(services=services, judge=judge, agent=agent, planner_model=_planner(chair_plan.model_dump(mode="json")),
settings=settings, runtime=FakeRuntime(Language.THREEJS))
rec = track.run(spec, ws)
- assert isinstance(rec, RunRecord) and rec.status is RunStatus.PASSED
- assert [r.kind for r in rec.rounds] == ["baseline", "refine", "refine"]
- assert rec.baseline_score == pytest.approx(0.55) and rec.final_score == pytest.approx(0.85) and rec.best_round == 2
- assert rec.total_usage.cost_usd > 0 and rec.extra["stop_reason"] == "pass"
+ # 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 rec.baseline_score == pytest.approx(0.55) and rec.final_score == pytest.approx(0.85) and rec.best_round == 3
+ 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()
state = RunState.load(ws)
- assert state.status is RunStatus.PASSED and state.best_round == 2 and state.completed_rounds == [0, 1, 2]
+ assert state.status is RunStatus.MAX_ROUNDS and state.completed_rounds == [0, 1, 2, 3]
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", "best.updated", "stop", "run.done"):
@@ -76,8 +77,8 @@ def test_static_track_end_to_end_agent_path(tmp_path, chair_plan, settings):
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
- assert len({r.commit for r in rec.rounds}) == 3 and ws.head() == rec.rounds[2].commit
+ # git history: one commit per round, and the workspace ends at the last one
+ assert 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 hashes
assert rec.prompt_hashes["judge"] == FakeJudge.prompt_hash and "generate" in rec.prompt_hashes
@@ -113,16 +114,16 @@ def test_static_track_resume_continues_from_saved_rounds(tmp_path, chair_plan, s
rt = FakeRuntime(Language.THREEJS)
# first run: policy with max_rounds=0 → stops after the baseline (max_rounds)
t1 = StaticObjectTrack(services=services, judge=judge, agent=FakeAgent(_agent_writer), planner_model=planner, settings=settings,
- runtime=rt, policy=RoundPolicy(max_rounds=0, target=0.8))
+ runtime=rt, policy=RoundPolicy(max_rounds=0))
rec1 = t1.run(spec, ws)
- assert len(rec1.rounds) == 1 and rec1.status is RunStatus.PLATEAU and rec1.extra["stop_reason"] == "max_rounds"
+ assert len(rec1.rounds) == 1 and rec1.status is RunStatus.MAX_ROUNDS and rec1.extra["stop_reason"] == "max_rounds"
# resume with the full policy: planner must NOT be called again, baseline not re-run
planner.requests.clear()
t2 = StaticObjectTrack(services=services, judge=judge, agent=FakeAgent(_agent_writer), planner_model=planner, settings=settings,
- runtime=rt, policy=RoundPolicy(max_rounds=2, target=0.8))
+ runtime=rt, policy=RoundPolicy(max_rounds=2))
rec2 = t2.run(spec, ws, resume=True)
assert planner.requests == [] and [r.kind for r in rec2.rounds] == ["baseline", "refine", "refine"]
- assert rec2.rounds[0].commit == rec1.rounds[0].commit and rec2.status is RunStatus.PASSED
+ assert rec2.rounds[0].commit == rec1.rounds[0].commit and rec2.status is RunStatus.MAX_ROUNDS
kinds = [e["event"] for e in EventLog(ws.events_path).read()]
assert kinds.count("stage.cached") >= 2 # plan + skeleton cached on resume
@@ -155,7 +156,7 @@ def test_static_track_blender_whole_object_refine(tmp_path, chair_plan, settings
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.PLATEAU
+ assert rec.status is RunStatus.MAX_ROUNDS
# ----------------------------------------------------------------------------- articulated
@@ -168,7 +169,7 @@ def test_articulated_track_adds_pose_views_and_sweep_gate(tmp_path, settings):
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.PASSED
+ 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")
@@ -214,7 +215,7 @@ def test_scene_track_stages_and_rounds(tmp_path, settings):
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 in (RunStatus.PLATEAU, RunStatus.PASSED)
+ 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
diff --git a/harness/tests/orchestrator_tracks/test_transport_retry.py b/harness/tests/orchestrator_tracks/test_transport_retry.py
index e50dfa64..854d1834 100644
--- a/harness/tests/orchestrator_tracks/test_transport_retry.py
+++ b/harness/tests/orchestrator_tracks/test_transport_retry.py
@@ -156,18 +156,18 @@ def test_baseline_transport_crash_is_retried_and_the_run_recovers(tmp_path, chai
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.PASSED and rec.final_score == pytest.approx(0.85)
+ 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"]
+ assert [r.kind for r in rec.rounds] == ["baseline", "refine", "refine", "refine"]
-def test_refine_transport_crash_retries_only_once_then_plateaus(tmp_path, chair_plan, settings):
+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.PLATEAU and rec.extra["stop_reason"] == "plateau"
- assert rec.final_score == pytest.approx(0.55) # the baseline best is still delivered
+ 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
@@ -182,21 +182,21 @@ def test_baseline_transport_crash_is_retried_once_then_fails(tmp_path, chair_pla
assert evs.count("round.transport_retry") == 1 and "run.failed" in evs
-def test_an_idle_agent_is_a_plateau_not_a_retry(tmp_path, chair_plan, settings):
+def test_an_idle_agent_is_a_no_change_stop_not_a_retry(tmp_path, chair_plan, settings):
agent = IdleAfterBaseline()
ws = Workspace(tmp_path / "runs" / "idle")
rec = _track(agent, (0.55,), chair_plan, settings).run(make_spec(max_rounds=3), ws)
- assert rec.status is RunStatus.PLATEAU
+ assert rec.status is RunStatus.NO_CHANGE
evs = _events(ws)
assert "round.transport_retry" not in evs and "round.no_change" in evs
-def test_a_vendor_usage_limit_stops_the_run_as_agent_quota_not_plateau(tmp_path, chair_plan, settings):
+def test_a_vendor_usage_limit_stops_the_run_as_agent_quota_not_no_change(tmp_path, chair_plan, settings):
agent = QuotaAfterBaseline()
ws = Workspace(tmp_path / "runs" / "quota")
rec = _track(agent, (0.55,), chair_plan, settings).run(make_spec(max_rounds=3), ws)
- assert rec.status is RunStatus.BUDGET and rec.extra["stop_reason"] == "agent_quota"
- assert rec.final_score == pytest.approx(0.55) # the baseline best is still delivered
+ assert rec.status is RunStatus.AGENT_QUOTA and rec.extra["stop_reason"] == "agent_quota"
+ assert [r.score for r in rec.rounds] == pytest.approx([0.55]) # the baseline is still recorded
evs = _events(ws)
assert "round.agent_quota" in evs and "round.transport_retry" not in evs and "round.no_change" not in evs
assert max(j.round for j in agent.jobs) == 1 # the refine round's sessions met the wall; no retry round
diff --git a/harness/tests/orchestrator_tracks/test_write_scope.py b/harness/tests/orchestrator_tracks/test_write_scope.py
index f55a2787..b823d594 100644
--- a/harness/tests/orchestrator_tracks/test_write_scope.py
+++ b/harness/tests/orchestrator_tracks/test_write_scope.py
@@ -4,13 +4,13 @@
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, scoped detail, threejs assets, parallel refine groups) now set
+ zones, threejs assets, parallel refine groups) now set
``edit_only=True`` so the split they promise is enforced, not just prompted.
"""
from __future__ import annotations
-from codeverse3d.contracts.artifacts import BuildResult, Judgment, Measurement, PartMeasure
+from codeverse3d.contracts.artifacts import BuildResult, Judgment
from codeverse3d.contracts.chat import ChatResponse
from codeverse3d.contracts.common import Language, Track, Usage
from codeverse3d.contracts.plan import BBox, PartPlan, ScenePlan, StaticPlan
@@ -187,15 +187,7 @@ def test_scoped_static_constructors_enforce_their_file_sets(tmp_path, settings):
assert len(parts) >= 2
assert all(t.edit_only and not t.owns_entry for t in parts), "part sessions are scoped"
assert assemble.owns_entry and not assemble.edit_only, "assemble owns the entry"
- # scoped detail: file-disjoint and enforced
last = _round(2, 0.62)
- last.measurement = Measurement(bbox_min=(0, 0, 0), bbox_max=(1, 1, 1), extents=(1, 1, 1),
- center=(0, 0, 0), tri_count=900, n_meshes=1, n_islands=1,
- parts=[PartMeasure(name="Body", bbox_min=(0, 0, 0),
- bbox_max=(0.6, 1.0, 0.4), tri_count=10, islands=1)])
- detail, lines = track.detail_tasks(ctx, last, 3)
- assert detail and lines
- assert all(t.edit_only and not t.owns_entry for t in detail), "detail never touches the entry"
# refine keeps entry access: the prompt promises it ("edit the entry file to import a new part")
group = TaskGroup(tasks=[RefineTask(target="Body", kind="geometry", instruction="thicken",
priority=2, files=["src/parts/body.js"])],
diff --git a/harness/tests/prompts/test_files.py b/harness/tests/prompts/test_files.py
index 191f5a9a..4d1e9bbd 100644
--- a/harness/tests/prompts/test_files.py
+++ b/harness/tests/prompts/test_files.py
@@ -84,5 +84,5 @@ def test_every_language_ships_a_system_prompt() -> None:
text = language_system_prompt(lang)
assert text.strip(), f"{lang.value}: empty system prompt"
assert (PROMPTS_DIR / prompt_dir_for(lang) / "system.md").is_file(), lang.value
- for role in ("scope", "detail", "repair"):
+ for role in ("scope", "repair"):
assert (PROMPTS_DIR / "system" / f"role_{role}.j2").is_file(), role
diff --git a/harness/tests/skills/test_end_to_end.py b/harness/tests/skills/test_end_to_end.py
index eac6b9b2..0aa0c777 100644
--- a/harness/tests/skills/test_end_to_end.py
+++ b/harness/tests/skills/test_end_to_end.py
@@ -100,7 +100,7 @@ def run(tmp_path: Path, chair_plan, settings, monkeypatch):
agent=agent, planner_model=FakeChatModel(lambda req: chair_plan.model_dump(mode="json")),
settings=settings, runtime=RepairOnceRuntime(Language.THREEJS))
rec = track.run(make_spec(max_rounds=3), ws)
- assert rec.status is RunStatus.PASSED
+ assert rec.status is RunStatus.MAX_ROUNDS
return rec, ws, agent
@@ -134,7 +134,7 @@ def test_enabled_run_delivers_routes_repairs_and_records_skills(run):
assert {k.split(":", 1)[1] for k in keys} >= set(rec.rounds[0].skills.listed)
rows = (ws.root / "telemetry" / "skills.jsonl").read_text().splitlines()
- assert len(rows) == 3 and all('"listed"' in r for r in rows)
+ assert len(rows) == len(rec.rounds) == 4 and all('"listed"' in r for r in rows)
repair = next(job for job in agent.jobs if job.kind == "repair")
assert "c3d-threejs-shader-traps" in repair.prompt