Skip to content

Official Codebase of 3DCodeVerse

Python

review round 2: the code fixes

ziyaoba24c8181266
diff --git a/harness/bench/coupling_stats.py b/harness/bench/coupling_stats.py
index 882da8c4..4e9d94de 100644
--- a/harness/bench/coupling_stats.py
+++ b/harness/bench/coupling_stats.py
@@ -26,9 +26,14 @@ from codeverse.spatial.joints_model import UrdfError, load_urdf # noqa: E402
def _urdfs(root: Path) -> list[Path]:
- """Every built ``robot.urdf`` under ``root``, deduplicated by resolved path."""
+ """Every built ``robot.urdf`` under ``root``, once per file on disk.
+
+ ``recurse_symlinks=True`` + resolve-dedupe for the same reason as
+ ``bench/session_stats._sessions``: batteries symlink each other's cells, and a walk
+ that leaves symlink behaviour to the default counts a run once or twice depending on
+ how the tree happens to be laid out."""
seen: dict[Path, Path] = {}
- for p in root.rglob("robot.urdf"):
+ for p in sorted(root.rglob("robot.urdf", recurse_symlinks=True)):
seen.setdefault(p.resolve(), p)
return sorted(seen.values())
diff --git a/harness/bench/plan_stage_bench.py b/harness/bench/plan_stage_bench.py
index f31083c9..359e1076 100644
--- a/harness/bench/plan_stage_bench.py
+++ b/harness/bench/plan_stage_bench.py
@@ -24,6 +24,7 @@ import concurrent.futures as cf
import json
import os
import shutil
+import subprocess
import sys
import tempfile
import time
@@ -75,7 +76,27 @@ def _stats(ws_root: Path) -> dict:
return out
-def run_one(battery, item, backends, label: str, rep: int) -> dict:
+def tree_provenance(tree: Path, codeverse_file: str) -> dict[str, str]:
+ """What was actually running, on every row: the imported package and the commit.
+
+ Two arms that differ by a worktree are only comparable if the rows say which tree
+ they came from — ``--label`` is a name the caller chose, and ``sys.path`` order is
+ not visible after the fact (a stale editable install would silently make both arms
+ the same code). ``codeverse_file`` is passed in, never imported here: this module is
+ run as a file, so every ``import codeverse`` must sit below the sys.path bootstrap
+ (tests/compare_bench/test_worktree_import.py)."""
+ out = {"codeverse_file": codeverse_file}
+ try:
+ proc = subprocess.run(["git", "-C", str(tree), "rev-parse", "--short", "HEAD"],
+ capture_output=True, text=True, check=False, timeout=30)
+ if proc.returncode == 0:
+ out["tree_commit"] = proc.stdout.strip()
+ except (OSError, subprocess.SubprocessError): # a tree that is not a checkout is fine
+ pass
+ return out
+
+
+def run_one(battery, item, backends, label: str, rep: int, provenance: dict[str, str] | None = None) -> dict:
"""One plan-stage call in a throwaway workspace; never raises."""
from bench.pin_plan import plan_once
from bench.run_bench import build_spec
@@ -89,7 +110,8 @@ def run_one(battery, item, backends, label: str, rep: int) -> dict:
except Exception as e: # noqa: BLE001 — the failure IS the measurement
ok, error = False, f"{type(e).__name__}: {e}"[:300].replace("\n", " ")
row = {"tree": label, "prompt": item.id, "rep": rep, "ok": ok, "error": error,
- "seconds": round(time.time() - started, 1), **_stats(root / "ws")}
+ "started_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(started)),
+ "seconds": round(time.time() - started, 1), **(provenance or {}), **_stats(root / "ws")}
shutil.rmtree(root, ignore_errors=True)
return row
@@ -113,8 +135,14 @@ def main(argv: list[str] | None = None) -> int:
print(f"env {key.strip()}={value.strip()}")
sys.path.insert(0, str(ns.tree.resolve()))
- from bench.run_bench import Battery
+ import codeverse
+ from bench._jsonl import seal_for_append # after the path insert: `python bench/x.py`
+ from bench.run_bench import Battery # puts bench/ on sys.path, not the tree
from codeverse.config import get_settings
+ if not Path(codeverse.__file__).resolve().is_relative_to(ns.tree.resolve()):
+ raise SystemExit(f"--tree {ns.tree} but `codeverse` imported from {codeverse.__file__}: "
+ "an editable install won the path race, so both arms would run the "
+ "same code (ab_plan.py's header documents this failure)")
battery = Battery.load(ns.tree / ns.battery)
backends = get_settings().backends(generator=DEFAULT_GENERATOR, planner=ns.planner, judge=DEFAULT_JUDGE)
@@ -124,8 +152,16 @@ def main(argv: list[str] | None = None) -> int:
print(f"{ns.label}: {len(jobs)} plan call(s) — {len(wanted)} prompt(s) x {ns.reps} rep(s), {len(done)} already recorded")
ns.out.parent.mkdir(parents=True, exist_ok=True)
+ seal_for_append(ns.out) # a killed run leaves a partial last line; do not glue onto it
+ prov = tree_provenance(ns.tree, codeverse.__file__)
+ print(f"{ns.label}: {prov}")
with ns.out.open("a") as fh, cf.ThreadPoolExecutor(ns.workers) as pool:
- for row in pool.map(lambda job: run_one(battery, job[0], backends, ns.label, job[1]), jobs):
+ # imap-style ordering: pool.map yields in submission order, so one slow call holds
+ # back every finished row behind it. Rows are the journal, so they go out as they
+ # land instead (resume reads what is on disk, order does not matter).
+ futures = [pool.submit(run_one, battery, item, backends, ns.label, rep, prov) for item, rep in jobs]
+ for fut in cf.as_completed(futures):
+ row = fut.result()
fh.write(json.dumps(row) + "\n")
fh.flush()
print(f" {row['prompt']:28} r{row['rep']:<3} ok={row['ok']} restart={row['restarts']} {row['error'][:60]}")
diff --git a/harness/bench/plan_stage_report.py b/harness/bench/plan_stage_report.py
index 596cd322..e93f6587 100644
--- a/harness/bench/plan_stage_report.py
+++ b/harness/bench/plan_stage_report.py
@@ -15,11 +15,41 @@ import math
from collections import Counter
from pathlib import Path
+#: what a validation failure was ABOUT, read off the error text. The mechanism under test
+#: (``CV3D_PLAN_RESTART``) only ever addresses ``dangling_link``; every other class is a
+#: bystander, and a total that mixes them hides both the effect and its residue.
+FAILURE_CLASSES: dict[str, str] = {
+ "dangling_link": "references unknown link",
+ "parent_eq_child": "parent == child",
+ "disconnected": "not connected to root",
+}
+
def outcome(row: dict) -> str:
+ """``valid`` | ``planning_error`` (the code under test lost the call) | ``provider``.
+
+ ``provider`` is dropped from the denominator, so it is deliberately narrow: only the
+ model-side failures the harness cannot help. A harness-side death — a budget ceiling,
+ an unexpected exception — is a loss of the run and must NOT be hidden here, so anything
+ that is neither a ``PlanningError`` nor a known provider failure counts as a loss.
+ """
if row["ok"]:
return "valid"
- return "planning_error" if "PlanningError" in row.get("error", "") else "provider"
+ err = row.get("error", "")
+ if "PlanningError" in err:
+ return "planning_error"
+ if any(w in err for w in ("ModelError", "BlockedReason", "429", "503", "Deadline", "RESOURCE_EXHAUSTED")):
+ return "provider"
+ return "planning_error"
+
+
+def failure_class(row: dict) -> str:
+ """Which validation rule the plan broke (``other`` when none of the known ones)."""
+ err = row.get("error", "")
+ for name, needle in FAILURE_CLASSES.items():
+ if needle in err:
+ return name
+ return "other"
def wilson(hits: int, n: int, z: float = 1.96) -> tuple[float, float]:
@@ -76,6 +106,24 @@ def report(arms: dict[str, list[dict]]) -> str:
judged = [r for r in rows if r["prompt"] == prompt and outcome(r) != "provider"]
cells.append(f"{sum(1 for r in judged if r['ok'])}/{len(judged)}")
lines.append(f"| {prompt} | " + " | ".join(cells) + " |")
+ classes = {name: Counter(failure_class(r) for r in rows if outcome(r) == "planning_error")
+ for name, rows in arms.items()}
+ if any(classes.values()):
+ seen = [k for k in (*FAILURE_CLASSES, "other") if any(c[k] for c in classes.values())]
+ lines += ["", "| arm | " + " | ".join(seen) + " |", "|---|" + "--:|" * len(seen)]
+ for name, c in classes.items():
+ lines.append(f"| {name} | " + " | ".join(str(c[k]) for k in seen) + " |")
+ names = list(arms)
+ judged_n = {n: len(arms[n]) - Counter(outcome(r) for r in arms[n])["provider"] for n in names}
+ for k in seen:
+ for i, a in enumerate(names):
+ for b in names[i + 1:]:
+ x, y = classes[a][k], classes[b][k]
+ if not (x or y):
+ continue
+ p = fisher_exact(x, judged_n[a] - x, y, judged_n[b] - y)
+ lines.append(f" {k}: {a} {x}/{judged_n[a]} vs {b} {y}/{judged_n[b]} "
+ f"Fisher p = {p:.4f}")
failures = Counter()
for name, rows in arms.items():
for r in rows:
diff --git a/harness/bench/session_stats.py b/harness/bench/session_stats.py
index 64f5a08a..7a32e021 100644
--- a/harness/bench/session_stats.py
+++ b/harness/bench/session_stats.py
@@ -26,9 +26,16 @@ MCP_PREFIX = "mcp_3dcv_"
def _sessions(root: Path) -> list[Path]:
- """Every ``stdout.json`` under ``root``, deduplicated by resolved path."""
+ """Every ``stdout.json`` under ``root``, once per file on disk.
+
+ ``run/telemetry/trajectories`` is a symlink to ``run/trajectories``, so the walk has
+ to say what it does about symlinks rather than inherit it: ``recurse_symlinks=True``
+ reaches both paths and the resolve-dedupe collapses them. Walking with the default
+ (no descent into symlinked directories) would give the same answer here by accident,
+ and would silently double every number the day a battery is laid out differently.
+ """
seen: dict[Path, Path] = {}
- for p in root.rglob("stdout.json"):
+ for p in sorted(root.rglob("stdout.json", recurse_symlinks=True)):
if "trajectories" not in p.parts:
continue
seen.setdefault(p.resolve(), p)
@@ -74,7 +81,7 @@ def round_costs(root: Path) -> list[float]:
"""Generator dollars per round, from the run records (judging is billed elsewhere)."""
out: list[float] = []
seen: set[Path] = set()
- for rec in root.rglob("record.json"):
+ for rec in root.rglob("record.json", recurse_symlinks=True):
if rec.resolve() in seen:
continue
seen.add(rec.resolve())
diff --git a/harness/codeverse/cli/flywheel_cmd.py b/harness/codeverse/cli/flywheel_cmd.py
index 078085b4..9a625d61 100644
--- a/harness/codeverse/cli/flywheel_cmd.py
+++ b/harness/codeverse/cli/flywheel_cmd.py
@@ -11,6 +11,7 @@ from rich.markup import escape
from codeverse.cli import _common as C
from codeverse.cli._common import console, kv_table, ok, warn
+from codeverse.flywheel.pairs import MIN_PREFERENCE_DELTA
flywheel_app = typer.Typer(no_args_is_help=True)
@@ -68,7 +69,7 @@ def export_cmd(
def pairs_cmd(
runs_dir: Annotated[Path, typer.Argument()],
out_jsonl: Annotated[Path, typer.Argument()],
- min_delta: Annotated[float, typer.Option("--min-delta")] = 0.05,
+ min_delta: Annotated[float, typer.Option("--min-delta")] = MIN_PREFERENCE_DELTA,
) -> None:
"""Preference / repair (round + in-session) / cross-backend pairs → JSONL."""
from codeverse.flywheel.pairs import build_pairs
diff --git a/harness/codeverse/contracts/plan.py b/harness/codeverse/contracts/plan.py
index aee00d08..474346a8 100644
--- a/harness/codeverse/contracts/plan.py
+++ b/harness/codeverse/contracts/plan.py
@@ -17,7 +17,6 @@ from typing import Literal
from pydantic import BaseModel, Field, field_validator, model_validator
from codeverse.contracts.common import (
- MIMIC_MIN_MULTIPLIER,
MimicSpec,
Vec3,
mimic_issues,
@@ -191,13 +190,6 @@ class MimicPlan(BaseModel):
multiplier: float = Field(default=1.0, description="q_this = multiplier * q_that + offset")
offset: float = Field(default=0.0)
- @model_validator(mode="after")
- def _sane(self) -> MimicPlan:
- if abs(self.multiplier) < MIMIC_MIN_MULTIPLIER:
- raise ValueError(f"mimic of {self.joint}: multiplier 0 means the joint cannot move; use type=fixed")
- return self
-
-
class JointPlan(BaseModel):
name: str
@@ -526,6 +518,9 @@ class ArticulatedPlan(StaticPlan):
for i in issues:
follower = by_name.get(i.joint)
wanted = follower.mimic.joint if follower is not None and follower.mimic else i.target
+ if i.kind == "out_of_range":
+ continue # the plan does not reject a coupling for overshooting a limit;
+ # the lint warns (contracts.common._driven_range says why)
raise ValueError({
"immobile": f"joint {i.joint}: a fixed joint cannot mimic {wanted}",
"zero_multiplier": f"mimic of {wanted}: multiplier 0 means the joint cannot move; use type=fixed",
diff --git a/harness/codeverse/flywheel/_git.py b/harness/codeverse/flywheel/_git.py
index 03678337..b196889a 100644
--- a/harness/codeverse/flywheel/_git.py
+++ b/harness/codeverse/flywheel/_git.py
@@ -109,7 +109,10 @@ def read_tree_at(ws: Workspace, commit: str) -> dict[str, bytes]:
continue
meta, _, path = rec.partition("\t")
parts = meta.split()
- if len(parts) < 3 or parts[1] != "blob" or not _keep(path):
+ # mode 120000 is a SYMLINK, stored as a blob whose content is the link target:
+ # `git archive` filtered it (tar member, not a file) and this path must too, or
+ # `src/link.py -> model.py` comes back as a one-line file saying "model.py".
+ if len(parts) < 3 or parts[1] != "blob" or parts[0] == "120000" or not _keep(path):
continue
entries.append((parts[2], path))
if not entries:
diff --git a/harness/codeverse/flywheel/pairs.py b/harness/codeverse/flywheel/pairs.py
index 2d537f60..4ffdfbbf 100644
--- a/harness/codeverse/flywheel/pairs.py
+++ b/harness/codeverse/flywheel/pairs.py
@@ -243,7 +243,7 @@ def cross_backend_pairs(
return out
-def build_pairs(runs_dir: Path | str, out_jsonl: Path | str, *, min_delta: float = 0.05) -> int:
+def build_pairs(runs_dir: Path | str, out_jsonl: Path | str, *, min_delta: float = MIN_PREFERENCE_DELTA) -> int:
"""Write all pair kinds for the runs under ``runs_dir``; returns the number written."""
out = Path(out_jsonl)
out.parent.mkdir(parents=True, exist_ok=True)
diff --git a/harness/codeverse/flywheel/refine.py b/harness/codeverse/flywheel/refine.py
index 49954b74..197a0a36 100644
--- a/harness/codeverse/flywheel/refine.py
+++ b/harness/codeverse/flywheel/refine.py
@@ -175,7 +175,7 @@ def transitions(runs_dir: Path | str, *, threshold: float = MIN_PREFERENCE_DELTA
drops["no_predecessor"] += 1
elif not (prev.commit and cur.commit):
drops["no_commit"] += 1
- elif not prev.build.ok:
+ elif prev.build is None or not prev.build.ok:
drops["predecessor_build_failed"] += 1
elif effective_judgment(prev) is None:
drops["predecessor_unjudged"] += 1
diff --git a/harness/codeverse/spatial/joints_model.py b/harness/codeverse/spatial/joints_model.py
index 9ba4a597..abebb5d4 100644
--- a/harness/codeverse/spatial/joints_model.py
+++ b/harness/codeverse/spatial/joints_model.py
@@ -24,7 +24,7 @@ from pathlib import Path
import numpy as np
import trimesh
-from codeverse.contracts.common import MIMIC_MIN_MULTIPLIER, MimicIssue, MimicSpec, mimic_issues
+from codeverse.contracts.common import MimicIssue, MimicSpec, mimic_issues
MOVABLE_TYPES = ("revolute", "prismatic", "continuous")
JOINT_TYPES = MOVABLE_TYPES + ("fixed",)
@@ -326,8 +326,8 @@ def _joint_from_xml(el: ET.Element) -> Joint:
off = float(mim.get("offset", 0.0) or 0.0)
except ValueError as e:
raise UrdfError(f"joint {name}: <mimic> multiplier/offset must be numbers") from e
- if abs(mult) < MIMIC_MIN_MULTIPLIER:
- raise UrdfError(f"joint {name}: <mimic multiplier=\"0\"> — the joint cannot move; use type=fixed")
+ # the multiplier floor is NOT checked here: mimic_issues owns every coupling rule,
+ # and a copy at parse time makes the shared one unreachable (review, 2026-09-03)
j.mimic = Mimic(joint=src, multiplier=mult, offset=off)
return j
diff --git a/harness/codeverse/spatial/mcp_server.py b/harness/codeverse/spatial/mcp_server.py
index 4649ca39..25fd401b 100644
--- a/harness/codeverse/spatial/mcp_server.py
+++ b/harness/codeverse/spatial/mcp_server.py
@@ -44,8 +44,12 @@ MAX_TEXT_CHARS = 6000
#: ceiling on the encoded image data of ONE result. The count and the 1024 px long side
#: bound pixels, not bytes: the largest recorded articulation sheet (1,966,609 B,
#: 1176x3350) still encodes to 394,988 base64 characters after the downscale, so without
-#: this a legal result could hand the model ~280 k tokens of image.
+#: this a legal result could hand the model ~280 k tokens of image. That leaves only ~1 %
+#: of headroom, so a slightly taller sheet is DOWNSCALED to fit rather than dropped
+#: (``_fit_first``): shipping no picture at all is the worse failure.
MAX_IMAGE_BYTES = 400_000
+#: long sides tried, in order, when the first image does not fit the byte bound
+IMAGE_FALLBACK_SIDES = (768, 512, 384)
SERVER_NAME = "3dcv"
@@ -86,6 +90,23 @@ def max_images_for(obs: Observation) -> int:
return MAX_IMAGES if obs.ok else 1
+def _fit_first(path: str, budget: int) -> tuple[str | None, int]:
+ """The first image, re-encoded smaller until it fits ``budget``.
+
+ Returns ``(base64, long side used)`` or ``(None, 0)``. ``images[0]`` is the contact
+ sheet — the one picture the round is about — and the byte bound has ~1 % of headroom
+ over the largest recorded sheet, so "over budget" means "a bit taller than last time",
+ not "unreasonable"."""
+ b64 = encode_image(path)
+ if b64 is not None and len(b64) <= budget:
+ return b64, MAX_IMAGE_SIDE
+ for side in IMAGE_FALLBACK_SIDES:
+ smaller = encode_image(path, max_side=side)
+ if smaller is not None and len(smaller) <= budget:
+ return smaller, side
+ return None, 0
+
+
def observation_content(obs: Observation) -> list[Any]:
"""Observation → MCP content blocks (text first, then images), both bounded."""
from mcp import types
@@ -102,27 +123,61 @@ def observation_content(obs: Observation) -> list[Any]:
# than skipping it: dropping the sheet and shipping three views of the same thing would
# be the worst of both. Whatever is dropped is said in the text — a FAIL verdict that
# silently shipped no picture is the case this guards.
- kept, spent, dropped = [], 0, 0
- for p in obs.images[:max_images_for(obs)]:
+ wanted = obs.images[:max_images_for(obs)]
+ kept, spent, dropped, shrunk = [], 0, 0, 0
+ for i, p in enumerate(wanted):
b64 = encode_image(p)
+ if i == 0 and b64 is not None and len(b64) > MAX_IMAGE_BYTES:
+ b64, side = _fit_first(p, MAX_IMAGE_BYTES)
+ shrunk = side
if b64 is None:
dropped += 1
continue
if spent + len(b64) > MAX_IMAGE_BYTES:
- dropped += len(obs.images[:max_images_for(obs)]) - len(kept) - dropped
+ dropped += len(wanted) - len(kept) - dropped
break
spent += len(b64)
kept.append(b64)
+ notes = []
+ if shrunk:
+ notes.append(f"[the sheet was re-encoded at {shrunk} px to fit the "
+ f"{MAX_IMAGE_BYTES}-byte payload bound]")
if dropped:
- blocks[0] = types.TextContent(
- type="text",
- text=f"{blocks[0].text}\n[{dropped} image(s) not attached: over the "
- f"{MAX_IMAGE_BYTES}-byte payload bound or unreadable; the files are in the workspace]")
+ notes.append(f"[{dropped} image(s) not attached: over the {MAX_IMAGE_BYTES}-byte "
+ "payload bound or unreadable; the files are in the workspace]")
+ if notes:
+ # inside the ceiling, not appended past it: this is the last bound before the
+ # vendor's prompt, so the note takes room from the body rather than adding to it
+ tail = "\n" + "\n".join(notes)
+ body = blocks[0].text[:max(0, MAX_TEXT_CHARS - len(tail))]
+ blocks[0] = types.TextContent(type="text", text=body + tail)
for b64 in kept:
blocks.append(types.ImageContent(type="image", data=b64, mime_type="image/png"))
return blocks
+async def call_tool(ctx: ToolContext, defs: dict[str, Any], params: Any) -> Any:
+ """One MCP tool call → a ``CallToolResult``.
+
+ Module level, not a closure inside :func:`make_server`, so the coupling below can be
+ driven by a test instead of grepped for: ``is_error`` is ``Observation.failed``, NOT
+ ``not ok``. A tool that RAN and answered FAIL is a result the model must read; an MCP
+ error is a call the vendor retries instead (a mean 119k prompt tokens, $0.030 blended)
+ — and, on gemini-cli, one whose images it re-sends as base64 TEXT. The FAIL verdict
+ leads the text.
+ """
+ from mcp import types
+
+ tdef = defs.get(params.name)
+ if tdef is None:
+ return types.CallToolResult(
+ content=[types.TextContent(type="text",
+ text=f"unknown tool {params.name!r}; known: {sorted(defs)}")],
+ is_error=True)
+ obs = await asyncio.to_thread(tdef.call, ctx, params.arguments or {})
+ return types.CallToolResult(content=observation_content(obs), is_error=obs.failed)
+
+
def make_server(ctx: ToolContext):
"""Low-level MCP ``Server`` wired to the registry for ``ctx``."""
from mcp import types
@@ -136,15 +191,7 @@ def make_server(ctx: ToolContext):
return types.ListToolsResult(tools=tools)
async def on_call_tool(_req_ctx: Any, params: types.CallToolRequestParams) -> types.CallToolResult:
- tdef = defs.get(params.name)
- if tdef is None:
- return types.CallToolResult(content=[types.TextContent(type="text", text=f"unknown tool {params.name!r}; known: {sorted(defs)}")], is_error=True)
- obs = await asyncio.to_thread(tdef.call, ctx, params.arguments or {})
- # is_error is Observation.failed, NOT `not ok`: a tool that RAN and answered FAIL
- # is a result the model must read, and an MCP error is a call the vendor retries
- # instead (a mean 119k prompt tokens, $0.030 blended) — and, on gemini-cli, one
- # whose images it re-sends as base64 TEXT. The FAIL verdict leads the text.
- return types.CallToolResult(content=observation_content(obs), is_error=obs.failed)
+ return await call_tool(ctx, defs, params)
return Server(SERVER_NAME, version="0.1.0",
instructions="3dcodeverse spatial tools: build, measure, render and check the 3D object in this workspace.",
diff --git a/harness/codeverse/spatial/observe.py b/harness/codeverse/spatial/observe.py
index 44ffccf4..17ab48a9 100644
--- a/harness/codeverse/spatial/observe.py
+++ b/harness/codeverse/spatial/observe.py
@@ -170,12 +170,15 @@ def build_failure_lines(br: BuildResult, root: Path, lint_warns: Sequence[str],
return lines
-def gate_observation(report: GateReport, *, title: str = "", max_findings: int = 20, images: Iterable[str] = ()) -> Observation:
+def gate_observation(report: GateReport, *, title: str = "", max_findings: int = 20,
+ images: Iterable[str] = (), failed: bool = False) -> Observation:
"""Errors first, each with its fix hint; counts in ``numbers``.
The verdict leads the text for every gate, ``title`` or not: a failing gate is a
result, not a tool error (``Observation.failed`` stays False), so PASS/FAIL is all
- the model has to go on. ``title`` names the gate, never the verdict.
+ the model has to go on. ``title`` names the gate, never the verdict. ``failed`` is
+ for the one caller whose gate report can also mean the tool did not run (the scene
+ probe driver dying); it forces ``ok=False``, because a call that failed has no verdict.
"""
findings = sorted(report.findings, key=lambda f: _SEV_ORDER.get(f.severity, 3))
n_err = sum(1 for f in findings if f.severity == Severity.ERROR)
@@ -193,7 +196,8 @@ def gate_observation(report: GateReport, *, title: str = "", max_findings: int =
for f in findings:
if f.severity == Severity.ERROR and f.data:
numbers.setdefault("error_data", {})[f.target or f.message[:40]] = f.data
- return Observation(ok=report.passed, text=truncate("\n".join(lines)), numbers=numbers, images=list(images))
+ return Observation(ok=report.passed and not failed, failed=failed,
+ text=truncate("\n".join(lines)), numbers=numbers, images=list(images))
def render_observation(rs: RenderSet, root: Path, *, note: str = "", max_individual: int = 4) -> Observation:
diff --git a/harness/codeverse/spatial/registry.py b/harness/codeverse/spatial/registry.py
index 19b64226..d8f8ee4e 100644
--- a/harness/codeverse/spatial/registry.py
+++ b/harness/codeverse/spatial/registry.py
@@ -25,7 +25,7 @@ from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
-from pydantic import BaseModel, Field, model_validator
+from pydantic import BaseModel, ConfigDict, Field, model_validator
from codeverse.workspace import Workspace
@@ -41,6 +41,10 @@ class Observation(BaseModel):
broken call (what that cost when the two were one flag: docs/COST.md §30).
"""
+ # validate_assignment: the invariant below has to hold for `obs.failed = ...` at a call
+ # site as well, not only at construction (spatial/tools.scene_probe did exactly that)
+ model_config = ConfigDict(validate_assignment=True)
+
ok: bool = True
failed: bool = Field(default=False, description="the tool could not run: exception, missing "
"artefact, unusable arguments (NOT a negative verdict)")
diff --git a/harness/codeverse/spatial/tools.py b/harness/codeverse/spatial/tools.py
index 2b780646..cb786651 100644
--- a/harness/codeverse/spatial/tools.py
+++ b/harness/codeverse/spatial/tools.py
@@ -537,8 +537,7 @@ def scene_probe(ctx: ToolContext, args: NoArgs) -> Observation:
res = probe_scene(ctx.workspace)
# ok = the gate verdict; failed = the probe TOOL could not run (SceneProbeResult
# semantics): agent-fixable findings are a FAIL the agent must read, not an error
- obs = gate_observation(res.gate, title="scene probe")
- obs.failed = bool(res.errors)
+ obs = gate_observation(res.gate, title="scene probe", failed=bool(res.errors))
if res.errors:
obs.text += "\nerrors:\n" + "\n".join(f" ! {e[:200]}" for e in res.errors[:10])
if res.census:
diff --git a/harness/codeverse/tracks/planner.py b/harness/codeverse/tracks/planner.py
index 098832ff..bc4c3f23 100644
--- a/harness/codeverse/tracks/planner.py
+++ b/harness/codeverse/tracks/planner.py
@@ -895,8 +895,13 @@ def plan_with_usage[P: BaseModel](spec: Spec, model_id: str, plan_model: type[P]
if events is not None:
events.emit("plan.restart", attempt=attempt, n_parts=len(raw.get("parts") or []),
missing=missing[:10])
+ # rebuilt from the ORIGINAL request, so a compact-answer note an earlier
+ # truncation retry added is rebuilt with it: this attempt keeps that
+ # retry's smaller `tokens` and thinking="off", and dropping the note
+ # while keeping the budget asks for the answer that did not fit.
+ note = TRUNCATION_NOTE.format(tokens=tokens) if thinking == "off" else ""
messages = base_messages[:-1] + [
- ChatMessage.user(base_messages[-1].text + restart_note(raw, missing, budget),
+ ChatMessage.user(base_messages[-1].text + restart_note(raw, missing, budget) + note,
images=images or None),
]
continue
diff --git a/harness/docs/COST.md b/harness/docs/COST.md
index a289be4a..4cfee6aa 100644
--- a/harness/docs/COST.md
+++ b/harness/docs/COST.md
@@ -1497,12 +1497,18 @@ block and each round's recorded `usage`:
| uncached prompt tokens | 38 390 | **13 945** (−64 %) |
| generator $ per round | mean 1.900, median 1.572 | **mean 1.242, median 0.950** (−35 % / −40 %) |
-**Correction (2026-09-03):** the after column first read 1.4 % (48 / 3 480), 13 736
-uncached tokens, median \$0.967 over "108 sessions / 5 082 requests". Those counts were
-inflated by the `run/telemetry/trajectories` symlink this section warns about — the same
-sessions counted about twice. The before column was unaffected and is unchanged. The
-script deduplicates by resolved path and a test plants the symlink, so the mistake cannot
-come back.
+**Correction (2026-09-03), and what it does NOT explain.** The after column first read
+1.4 % (48 / 3 480), 13 736 uncached tokens and median \$0.967 over "108 sessions / 5 082
+requests". It was computed by hand, by a method that is not in the tree, and
+`bench/session_stats.py` does not reproduce it: the ratios are 1.87x on MCP calls and on
+requests but only 1.06x on sessions, and no mechanism tested accounts for that shape —
+following the `run/telemetry/trajectories` symlink doubles the file count exactly (2.0x on
+both batteries), counting every tool instead of the MCP ones gives 2 756 not 3 480, and no
+union of recorded batteries lands on those totals. The BEFORE column reproduces to the
+digit, which says the method changed between the columns rather than the data. The
+hand-computed after column is therefore **withdrawn**, not explained; the table above is
+what the committed script prints, and the script is what a later run should be compared
+against.
The residual 1.3 % are genuine `Observation.error` cases: `joint_sweep` with no
`artifacts/robot.urdf` yet or an unparseable one, `check_connectivity` / `check_contract`
diff --git a/harness/docs/DECISIONS.md b/harness/docs/DECISIONS.md
index 7523aa67..6b1bb62e 100644
--- a/harness/docs/DECISIONS.md
+++ b/harness/docs/DECISIONS.md
@@ -707,8 +707,10 @@ written) that were accepted because the code works that way and the tests pin it
`Observation.error` cases), cache hit 68.8 % → **89.2 %**, uncached prompt tokens per
request 38 390 → **13 945**, generator dollars per round median 1.572 → **0.950**
(−40 %). `bench/session_stats.py` computes both columns from the recorded sessions —
- the first hand-computed after column double-counted the telemetry symlink (docs/COST.md
- §30 carries the correction and the selector).
+ the first, hand-computed after column (1.4 %, 13 736, $0.967 over "108 sessions") is
+ NOT reproduced by it and is withdrawn: no tested mechanism explains its shape (1.87x on
+ calls and requests against 1.06x on sessions), while the before column reproduces to
+ the digit. docs/COST.md §30 carries that and the selector.
* **`CV3D_LEAN_PROMPT` stays OFF, now with a number.** Paired battery on
`articulated_v2` (12 pairs, plan pinned, same fixed judge): mean Δ **+0.030**, paired
sd 0.131, **2 SE ±0.076**, 8 up / 3 down (p 0.227), one regression — inconclusive by
diff --git a/harness/docs/PAPER_WRITING.md b/harness/docs/PAPER_WRITING.md
index ac7c94f3..c8ce9d84 100644
--- a/harness/docs/PAPER_WRITING.md
+++ b/harness/docs/PAPER_WRITING.md
@@ -267,9 +267,11 @@ Both columns come from `bench/session_stats.py`, which is in the repo with its o
| uncached prompt tokens | 38 390 | **13 945** (−64 %) |
| generator $ per round | mean 1.900, median 1.572 | **mean 1.242, median 0.950** (−35 % / −40 %) |
-(The after column first read 1.4 % / 13 736 / \$0.967 over "108 sessions"; those counts
-double-counted the `run/telemetry/trajectories` symlink. Rates barely move, the counts do;
-the script deduplicates and a test plants the symlink.)
+(The after column first read 1.4 % / 13 736 / \$0.967 over "108 sessions". That was
+hand-computed, `bench/session_stats.py` does not reproduce it, and no mechanism tested
+explains its shape — 1.87x on calls and requests against 1.06x on sessions. It is
+withdrawn, not corrected; docs/COST.md §30 carries the detail. The before column
+reproduces exactly.)
The residual 1.3 % are genuine `Observation.error` cases (`joint_sweep` before a build,
`check_*` with no readable GLB). **This is the largest effect found in the whole effort,
diff --git a/harness/tests/compare_bench/test_plan_stage.py b/harness/tests/compare_bench/test_plan_stage.py
index cf8c5913..af0a9a19 100644
--- a/harness/tests/compare_bench/test_plan_stage.py
+++ b/harness/tests/compare_bench/test_plan_stage.py
@@ -6,11 +6,12 @@ pins the statistic that turns them into 0.0067, and the report that prints it.""
from __future__ import annotations
import json
+from collections import Counter
from pathlib import Path
import pytest
-from bench.plan_stage_report import fisher_exact, report
+from bench.plan_stage_report import failure_class, fisher_exact, outcome, report
DATA = Path(__file__).resolve().parents[2] / "bench" / "data" / "plan_stage"
@@ -36,3 +37,41 @@ def test_the_recorded_arms_still_read_out_the_way_d52_says() -> None:
text = report(arms)
assert "Fisher exact two-sided p = 0.0067" in text
assert "fired on 40/280 calls, recovered 39" in text
+
+
+def test_the_failure_class_split_the_re_measurement_reports_is_computed_here() -> None:
+ """The 2026-09-03 three-arm readout turns on a CLASS, not the total: the restart only
+ ever addresses a plan that references links it never lists. That split was derived by
+ hand for the first write-up; it is the report's job, and this pins the number the docs
+ quote."""
+ arms = {p.stem.replace("trigger_", ""): [json.loads(x) for x in p.read_text().splitlines() if x.strip()]
+ for p in sorted(DATA.glob("trigger_*.jsonl"))}
+ assert set(arms) == {"narrow", "off", "wide"}
+
+ classes = {name: Counter(failure_class(r) for r in rows if outcome(r) == "planning_error")
+ for name, rows in arms.items()}
+ assert classes["off"]["dangling_link"] == 3 and classes["wide"]["dangling_link"] == 4
+ assert classes["narrow"]["dangling_link"] == 0, "the class the mechanism addresses"
+ assert [classes[a]["parent_eq_child"] for a in ("off", "wide", "narrow")] == [1, 2, 4]
+
+ judged = {n: sum(1 for r in rows if outcome(r) != "provider") for n, rows in arms.items()}
+ p = fisher_exact(3, judged["off"] - 3, 0, judged["narrow"])
+ assert round(p, 4) == 0.0376
+
+ text = report(arms)
+ assert "| arm | dangling_link | parent_eq_child | other |" in text
+ assert "dangling_link: narrow 0/276 vs off 3/140 Fisher p = 0.0376" in text
+
+
+def test_a_harness_side_death_is_a_loss_not_provider_weather() -> None:
+ """``provider`` drops a row from the denominator, so it has to name the provider
+ failures rather than catch everything that is not a PlanningError. A budget ceiling
+ and a harness exception are losses of the run: trigger_narrow carries one
+ BudgetExceeded row, and classing it as weather would have hidden it."""
+ rows = [json.loads(x) for x in (DATA / "trigger_narrow.jsonl").read_text().splitlines() if x.strip()]
+ budget = [r for r in rows if "BudgetExceeded" in r.get("error", "")]
+ assert len(budget) == 1
+ assert outcome(budget[0]) == "planning_error" and failure_class(budget[0]) == "other"
+
+ assert outcome({"ok": False, "error": "ModelError: Gemini prompt blocked: BlockedReason.OTHER"}) == "provider"
+ assert outcome({"ok": False, "error": "KeyError: 'parts'"}) == "planning_error"
diff --git a/harness/tests/flywheel_cli/test_flywheel.py b/harness/tests/flywheel_cli/test_flywheel.py
index 1d07e1cf..02da46c2 100644
--- a/harness/tests/flywheel_cli/test_flywheel.py
+++ b/harness/tests/flywheel_cli/test_flywheel.py
@@ -115,6 +115,23 @@ def test_a_planted_diff_driver_never_runs(fake_run, tmp_path):
assert files == ["src/blob.bin"] and "src/blob.bin" in text
+def test_a_symlink_is_not_exported_as_a_file_of_its_target(fake_run) -> None:
+ """``git archive`` skipped symlinks (a tar member, not a file); ``ls-tree`` lists one
+ as a blob whose content IS the link target, so ``src/link.py -> model.py`` came back
+ as a one-line file saying ``model.py`` — and with ``--with-code`` that goes into a
+ training sample."""
+ from codeverse.flywheel._git import read_tree_at
+
+ ws, _rec = fake_run
+ (ws.src / "model.py").write_text("import bpy\n")
+ (ws.src / "link.py").symlink_to("model.py")
+ commit = ws.commit("with a symlink")
+
+ tree = read_tree_at(ws, commit)
+ assert "src/model.py" in tree
+ assert "src/link.py" not in tree, "a symlink is not a file the agent wrote"
+
+
def test_a_planted_smudge_filter_never_runs(fake_run, tmp_path):
"""The same window, the other content-rendering command: ``git archive`` renders
blobs through ``convert_to_working_tree``, so a planted ``filter.<name>.smudge``
diff --git a/harness/tests/flywheel_cli/test_refine.py b/harness/tests/flywheel_cli/test_refine.py
index f13bca9c..ba6e18e5 100644
--- a/harness/tests/flywheel_cli/test_refine.py
+++ b/harness/tests/flywheel_cli/test_refine.py
@@ -77,6 +77,9 @@ def test_a_run_reached_through_a_symlink_is_exported_once_under_its_physical_bat
@pytest.mark.parametrize("break_it,reason", [
("kind", None), ("commit", "no_commit"), ("build", "predecessor_build_failed"),
+ # RoundRecord.build is optional: a round that never reached the build stage carries
+ # None, and reading .ok on it took the whole export down with an AttributeError
+ ("no_build", "predecessor_build_failed"),
("judgment", "predecessor_unjudged"),
])
def test_every_unexportable_round_is_counted_under_a_named_reason(tmp_path, break_it, reason):
@@ -88,6 +91,8 @@ def test_every_unexportable_round_is_counted_under_a_named_reason(tmp_path, brea
rec.rounds[0].commit = ""
elif break_it == "build":
rec.rounds[0].build.ok = False
+ elif break_it == "no_build":
+ rec.rounds[0].build = None
else:
rec.rounds[0].judgment = None
ws.write_json(ws.record_path, rec)
diff --git a/harness/tests/spatial_tools/test_mcp_server.py b/harness/tests/spatial_tools/test_mcp_server.py
index b0e5cdd5..e147559e 100644
--- a/harness/tests/spatial_tools/test_mcp_server.py
+++ b/harness/tests/spatial_tools/test_mcp_server.py
@@ -8,6 +8,7 @@ import sys
from pathlib import Path
import pytest
+from PIL import Image
from pydantic import ValidationError
from codeverse.spatial.mcp_server import build_context, encode_image, main, observation_content
@@ -101,16 +102,66 @@ def test_the_byte_bound_keeps_the_sheet_drops_the_rest_and_says_so(tmp_path: Pat
assert "1 image(s) not attached" in blocks[0].text
-def test_is_error_is_failed_not_the_verdict(tmp_path: Path) -> None:
- """The one coupling every other bound assumes: a FAIL verdict is an ordinary result,
- so the vendor sends its images as images. Re-couple this to ``not obs.ok`` and the
- base64-as-text blow-up of docs/COST.md §30 comes back."""
- import inspect
+def test_an_oversized_sheet_is_downscaled_not_dropped(tmp_path: Path) -> None:
+ """The byte bound had ~1 % of headroom over the largest recorded sheet, so a slightly
+ taller one lost EVERY image and the round was judged on text alone. The first image
+ is the sheet; it gets re-encoded smaller until it fits, and the text says so."""
+ from PIL import Image
+
+ from codeverse.spatial.mcp_server import MAX_IMAGE_BYTES
+
+ big = tmp_path / "sheet.png"
+ Image.effect_noise((1600, 4200), 90).convert("RGB").save(big) # noise: PNG cannot shrink it
+ assert len(encode_image(str(big))) > MAX_IMAGE_BYTES
+
+ blocks = observation_content(Observation(ok=True, text="t", images=[str(big)]))
+ images = [b for b in blocks if b.type == "image"]
+ assert len(images) == 1 and len(images[0].data) <= MAX_IMAGE_BYTES
+ assert "re-encoded at" in blocks[0].text
- from codeverse.spatial import mcp_server
- src = inspect.getsource(mcp_server.make_server)
- assert "is_error=obs.failed" in src and "is_error=not obs.ok" not in src
+def test_every_bound_holds_including_the_note(tmp_path: Path) -> None:
+ """The "not attached" note used to be appended AFTER the hard slice, so the ceiling
+ was soft by the length of the note."""
+ from codeverse.spatial.mcp_server import MAX_TEXT_CHARS
+
+ heavy = tmp_path / "heavy.png"
+ Image.effect_noise((1600, 4200), 90).convert("RGB").save(heavy)
+ blocks = observation_content(Observation(ok=True, text="x" * 20_000,
+ images=[str(heavy), str(heavy)]))
+ assert len(blocks[0].text) <= MAX_TEXT_CHARS
+ assert "not attached" in blocks[0].text or "re-encoded" in blocks[0].text
+
+
+def test_is_error_is_failed_not_the_verdict(stool_ctx: ToolContext) -> None:
+ """The one coupling every other bound assumes, checked through the server itself.
+
+ A tool that RAN and answered FAIL must reach the model as an ordinary result, so the
+ vendor sends its images as images; re-couple this to ``not obs.ok`` and the
+ base64-as-text blow-up of docs/COST.md §30 comes back. This used to be a grep over
+ ``make_server``'s source, which passes for any code that merely mentions the name."""
+ from mcp import types
+
+ from codeverse.spatial import mcp_server
+ from codeverse.spatial.registry import NoArgs, ToolDef
+
+ fakes = [
+ ToolDef(name="verdict", args_model=NoArgs, description="a gate that answers FAIL",
+ fn=lambda ctx, args: Observation(ok=False, failed=False, text="GATE: FAIL — one error")),
+ ToolDef(name="broken", args_model=NoArgs, description="a tool that cannot run",
+ fn=lambda ctx, args: Observation.error("no readable GLB")),
+ ]
+ defs = {t.name: t for t in fakes}
+
+ async def call(name: str) -> types.CallToolResult:
+ return await mcp_server.call_tool(stool_ctx, defs,
+ types.CallToolRequestParams(name=name, arguments={}))
+
+ verdict = asyncio.run(call("verdict"))
+ broken = asyncio.run(call("broken"))
+ assert verdict.is_error is False, "a FAIL verdict is a result, not a protocol error"
+ assert "FAIL" in verdict.content[0].text
+ assert broken.is_error is True, "a tool that could not run IS a protocol error"
def test_a_failure_cannot_also_be_a_pass() -> None: