Official Codebase of 3DCodeVerse
Python
models/agents/bench: a real deadline, one render cache, and 210 lines nothing calls
gaoypenga11a130339bd
diff --git a/harness/bench/compare_backends.py b/harness/bench/compare_backends.pyindex 20692423..b1723d47 100644--- a/harness/bench/compare_backends.py+++ b/harness/bench/compare_backends.py@@ -76,6 +76,7 @@ from bench._oneshot import ( # noqa: E402from bench.run_bench import ( # noqa: E402Battery,BenchPrompt,+ archive_attempt,build_spec,default_run_track,select_prompts,@@ -233,8 +234,17 @@ def entry_of(spec: Spec) -> str:return ENTRY_FILE[spec.language]-def _run_harness(spec: Spec, cell: Path, eval_ws: Workspace, deps: CompareDeps, res: CellResult) -> None:+def _run_harness(spec: Spec, cell: Path, eval_ws: Workspace, opts: CompareOptions,+ deps: CompareDeps, res: CellResult) -> None:run_ws = Workspace(cell / "run")+ if run_ws.exists() and not opts.resume:+ # --no-resume regenerates every other arm (a recorded one-shot answer is not re-used+ # either), so a harness arm that resumed its FINISHED workspace handed back its old+ # score, generated in the old weather, against a partner generated in today's — the+ # cross-weather comparison the pairing exists to prevent (ab_plan.archive_cell has+ # the measured story). The old tree is archived, never deleted: it holds that+ # attempt's cost ledger.+ archive_attempt(run_ws.root)resume = run_ws.exists()if not resume:run_ws.create()@@ -278,7 +288,7 @@ def run_cell(battery: Battery, item: BenchPrompt, arm: Arm, out: Path, opts: Com# of the per-process fallback log. Context-local, so --parallel keeps cells apart.with run_ledger(cell, run=f"{item.id}:{arm.slug}"):if arm.kind == "harness":- _run_harness(spec, cell, eval_ws, deps, res)+ _run_harness(spec, cell, eval_ws, opts, deps, res)else:_generate_oneshot(arm, spec, cell, eval_ws, opts, deps, res)# A one-shot arm whose LAST attempt was lost to the provider has not finisheddiff --git a/harness/bench/run_bench.py b/harness/bench/run_bench.pyindex 4d546aa9..d5422ff2 100644--- a/harness/bench/run_bench.py+++ b/harness/bench/run_bench.py@@ -106,7 +106,9 @@ class BenchOptions(BaseModel):limit: int | None = Noneids: list[str] = Field(default_factory=list)tiers: list[str] = Field(default_factory=list)- resume: bool = True+ # No "start over" switch: --redo-status is the ONE way to re-run a recorded prompt,+ # because it archives the old tree first (RUNBOOK 7.u). The `resume` flag it replaced+ # skipped that archive and resumed the old workspace, spec and clock (dropped 2026-08-30).redo_status: list[str] = Field(default_factory=list,description="re-run prompts already recorded with one of these statuses ""(the point of `infra_failed`: retry what the weather lost)")@@ -231,7 +233,7 @@ def run_battery("options": opts.model_dump(mode="json"),"started_at": datetime.now(UTC).isoformat()}, indent=2))results_jsonl = out / "results.jsonl"- done = _load_done(results_jsonl) if opts.resume else {}+ done = _load_done(results_jsonl)# `--redo-status infra_failed` re-runs the cells the weather lost, once it clearsredo_ids = {k for k, r in done.items() if r.status in set(opts.redo_status)}for pid in redo_ids:diff --git a/harness/codeverse/agents/cli_common.py b/harness/codeverse/agents/cli_common.pyindex 922aa1f9..378ae032 100644--- a/harness/codeverse/agents/cli_common.py+++ b/harness/codeverse/agents/cli_common.py@@ -310,16 +310,13 @@ def _hinted(path: str, hints: frozenset[str]) -> bool:return any(path == h or path.startswith(h.rstrip("/") + "/") for h in hints)-def attribute_changes(- files: list[FileChange],- *,- write_roots: list[str],- own_hints: frozenset[str] = frozenset(),-) -> list[FileChange]:+def attribute_changes(files: list[FileChange], *, write_roots: list[str]) -> list[FileChange]:"""The subset of a whole-worktree git diff that belongs to ONE session: inside its``write_roots`` and not harness-owned. (Sessions on one workspace are serialised —- :data:`EXCLUSIVE_KINDS` — so there is no sibling to attribute against; ``own_hints``- is the session's declared scope, kept for callers that narrow further.)"""+ :data:`EXCLUSIVE_KINDS` — so there is no sibling to attribute against. An ``own_hints``+ parameter sat in this signature unread until 2026-08-30: the edit_only scope is enforced+ by :func:`_enforce_scope`, which REVERTS an out-of-scope write rather than hiding it from+ ``files_changed``, so narrowing here would only have lied about what the session did.)"""roots = tuple(r.strip("/") for r in write_roots if r.strip("/"))out: list[FileChange] = []for f in files:@@ -498,8 +495,7 @@ def finish_session(errors.append(msg)s.notes.append(msg)s.ws.commit(f"agent:{s.label}")- files = attribute_changes(s.ws.changed_files(s.head_before), write_roots=s.job.write_roots,- own_hints=s.files_hint)+ files = attribute_changes(s.ws.changed_files(s.head_before), write_roots=s.job.write_roots)res = AgentResult(ok=ok, exit_reason=exit_reason, text=text, files_changed=files,transcript_path=str(s.traj.transcript_path if s.traj.transcript_path.exists() else s.traj.dir),diff --git a/harness/codeverse/agents/materialize.py b/harness/codeverse/agents/materialize.pyindex d0cf9106..9a3cf85a 100644--- a/harness/codeverse/agents/materialize.py+++ b/harness/codeverse/agents/materialize.py@@ -31,15 +31,16 @@ would otherwise refuse to read the build census / the long-prompt file there.from __future__ import annotationsimport json+import loggingimport shutilfrom pathlib import Path-from pydantic import BaseModel, Field-from codeverse.agents.cli_common import default_mcp_commandfrom codeverse.prompts import PROMPTS_DIRfrom codeverse.workspace import Workspace+log = logging.getLogger(__name__)+CV3D_DIR = ".3dcv" # harness-owned read-only docs inside the workspaceMCP_SERVER_NAME = "3dcv"MCP_TOOL_TIMEOUT_MS = 600_000@@ -59,16 +60,6 @@ IGNORE_LINES = (GEMINI_CONTEXT_SETTINGS = {"fileFiltering": {"respectGitIgnore": False, "respectGeminiIgnore": True}}-class Materialized(BaseModel):- """What :func:`materialize_workspace` wrote and how each CLI reaches the tools."""-- body_files: list[str] = Field(default_factory=list)- ignore_files: list[str] = Field(default_factory=list)- cookbook_path: str = ""- mcp_command: list[str] = Field(default_factory=list)- warnings: list[str] = Field(default_factory=list)--# --------------------------------------------------------------------------- bodydef _tool_section(agent_kind: str, spatial_tools: bool, mcp_command: list[str]) -> str:if not spatial_tools:@@ -195,14 +186,21 @@ def materialize_workspace(cookbook_rel: str,spatial_tools: bool,mcp_command: list[str] | None = None,-) -> Materialized:+) -> None:"""Write AGENTS.md / GEMINI.md / CLAUDE.md + MCP configs + ignore files into ``ws``.``mcp_command`` defaults to ``cli_common.default_mcp_command(ws)`` — the same``sys.executable`` the backends launch; three callers used to spell a bare ``python``- here, which the body text and codex's ``-c`` overrides then quoted verbatim."""+ here, which the body text and codex's ``-c`` overrides then quoted verbatim.++ Returns nothing: the ``Materialized`` DTO this used to build (body/ignore paths, the+ cookbook path, the argv, a warnings list) was discarded by every production caller —+ ``tracks/common.Services.materialize`` is typed ``-> None`` — so its one real signal,+ a cookbook that did not resolve, was written and read by nobody. That is the exact+ failure ``tracks/common.cookbook_rel_for`` was fixed for on 2026-08-29 (an articulated+ run told the agent "No cookbook is available" while its 24 kB cookbook sat on disk);+ it is a log line now, where someone reading the run can see it (2026-08-30)."""mcp_command = list(mcp_command) if mcp_command else default_mcp_command(ws)- out = Materialized(mcp_command=mcp_command)# cookbook: copy into the harness-owned .3dcv/ dir so every CLI can read it in-workspacesrc = _resolve_cookbook(ws, cookbook_rel)@@ -210,21 +208,18 @@ def materialize_workspace(dest = ws.root / CV3D_DIR / "cookbook.md"dest.parent.mkdir(parents=True, exist_ok=True)shutil.copyfile(src, dest)- out.cookbook_path = str(dest)cookbook_note = (f"The cookbook for this language — copyable, verified snippets and skeletons — is at "f"`{CV3D_DIR}/cookbook.md` (relative to the workspace root). Read the relevant sections ""before writing code and copy its patterns exactly."-)else:- out.warnings.append(f"cookbook not found: {cookbook_rel!r}")+ log.warning("cookbook not found: %r — the %s session gets the contract only", cookbook_rel, agent_kind)cookbook_note = "No cookbook is available in this session; rely on the contract below."body = _body(agent_kind, contract_md, cookbook_note, spatial_tools, mcp_command)for name in ("AGENTS.md", "GEMINI.md", "CLAUDE.md"):(ws.root / name).write_text(body)- out.body_files.append(str(ws.root / name))# No MCP server is written into the workspace: every CLI gets 3dcv from a harness-owned# per-session file, so an agent-planted server cannot reach the next round (audit 2026-08-27).@@ -235,5 +230,3 @@ def materialize_workspace(ignore_text = "\n".join(IGNORE_LINES) + "\n"for name in (".geminiignore", ".aiexclude"):(ws.root / name).write_text(ignore_text)- out.ignore_files.append(str(ws.root / name))- return outdiff --git a/harness/codeverse/cli/main.py b/harness/codeverse/cli/main.pyindex b17e4654..33fd5f55 100644--- a/harness/codeverse/cli/main.py+++ b/harness/codeverse/cli/main.py@@ -107,7 +107,6 @@ def run_cmd(limit: Annotated[int | None, typer.Option("--limit")] = None,ids: Annotated[list[str] | None, typer.Option("--id", help="only these prompt ids")] = None,tiers: Annotated[list[str] | None, typer.Option("--tier")] = None,- no_resume: Annotated[bool, typer.Option("--no-resume")] = False,redo_status: Annotated[str, typer.Option("--redo-status", help="comma list of recorded statuses to re-run, ""e.g. infra_failed once the provider recovers")] = "",report: Annotated[bool, typer.Option("--report/--no-report")] = True,@@ -120,7 +119,7 @@ def run_cmd(# one source of truth for the worker count: BenchOptions.parallel (the measured knee)par = {"parallel": parallel} if parallel is not None else {}opts = run_bench.BenchOptions(generator=generator, planner=planner, judge=judge, rounds=rounds, max_minutes=max_minutes,- limit=limit, ids=ids or [], tiers=tiers or [], resume=not no_resume,+ limit=limit, ids=ids or [], tiers=tiers or [],redo_status=[x for x in redo_status.split(",") if x], **par)out_dir = out or (C.REPO_ROOT / "bench" / "out" / battery.stem)console.print(f"battery={battery} out={out_dir} generator={generator or 'default'} judge={judge or 'default'}")diff --git a/harness/codeverse/languages/file_lint.py b/harness/codeverse/languages/file_lint.pydeleted file mode 100644index 715ed36c..00000000--- a/harness/codeverse/languages/file_lint.py+++ /dev/null@@ -1,141 +0,0 @@-"""One file, one cheap verdict — what ``write_file`` / ``edit_file`` hand back so the agent-never has to ``read_file`` its own output (docs/COST.md §29: ~35 read_file turns per run,-each a 4 s round trip carrying the whole context, to look at a file it wrote a turn ago).--This is deliberately the language's OWN per-file lint, not a new rule set: the same-``lint_*_source`` the workspace lint calls per file (blender / cadquery / opengl_python /-urdf), ``node --check`` for JS (threejs / scene_threejs) and the static shader rules for-GLSL. Only ERRORs are reported — a WARN is what ``build`` shows. A file type the-language has no cheap check for gets ``checked=False`` and the tool says nothing about-syntax rather than pretending. Never raises: a lint crash is reported as unchecked.-"""--from __future__ import annotations--import logging-from dataclasses import dataclass, field-from pathlib import Path--from codeverse.contracts.artifacts import GateFinding, Severity-from codeverse.contracts.common import Language--log = logging.getLogger(__name__)--MAX_ERRORS = 3---@dataclass(frozen=True)-class FileVerdict:- checked: bool- errors: list[str] = field(default_factory=list) # "line 7: SyntaxError: ..." (≤ MAX_ERRORS)- n_total: int = 0-- def summary(self) -> str:- """`syntax OK` / `2 lint error(s): ...` / "" when nothing was checked."""- if not self.checked:- return ""- if not self.errors:- return "syntax OK"- head = f"{self.n_total} lint error(s) — fix before build:"- return head + "".join(f"\n - {e}" for e in self.errors)---def _line_of(f: GateFinding) -> int | None:- n = f.data.get("line") if isinstance(f.data, dict) else None- return int(n) if isinstance(n, int) and n > 0 else None---def _errors(findings: list[GateFinding], max_errors: int) -> FileVerdict:- errs = [f for f in findings if f.severity == Severity.ERROR]- out = []- for f in errs[:max_errors]:- line = _line_of(f)- msg = f.message- out.append((f"line {line}: " if line else "") + msg + (f" (fix: {f.fix_hint})" if f.fix_hint else ""))- return FileVerdict(checked=True, errors=out, n_total=len(errs))---def _python(language: Language, rel: str, text: str, max_errors: int) -> FileVerdict:- name = Path(rel).name- if language is Language.BLENDER:- from codeverse.languages.blender import lint_blender_source-- # same per-file settings as blender.layout.lint_workspace: helpers (_x.py) need no bpy;- # PascalCase-name checks are WARNs anyway and never reported here- rep = lint_blender_source(text, target=rel, expect_names=False, expect_bpy=not name.startswith("_"))- return _errors(rep.findings, max_errors)- if language is Language.CADQUERY:- from codeverse.languages.cadquery import lint_cadquery_source-- return _errors(lint_cadquery_source(text, target=rel).findings, max_errors)- if language is Language.OPENGL_PYTHON:- from codeverse.languages.opengl_python import lint_source-- return _errors(lint_source(text), max_errors)- if language is Language.URDF_BLENDER:- from codeverse.languages.urdf import lint_model_text-- # link names are the urdf's business; here only syntax + forbidden APIs + `import bpy`- return _errors(lint_model_text(text, [], label=rel), max_errors)- return FileVerdict(checked=False)---def _js(path: Path, max_errors: int) -> FileVerdict:- from codeverse.config import get_settings- from codeverse.languages._js_lint import node_check_syntax-- problem = node_check_syntax(path, get_settings().binaries.node or "node")- if problem is None:- return FileVerdict(checked=True)- if problem.line is None and "could not run" in problem.message:- return FileVerdict(checked=False)- return FileVerdict(checked=True, n_total=1,- errors=[(f"line {problem.line}: " if problem.line else "") + problem.message][:max_errors])---def _glsl(rel: str, text: str, path: Path, max_errors: int) -> FileVerdict:- import codeverse.languages.glsl_shader as gl-- role = {gl.SHADER: "shader", gl.COMMON: "common", gl.BUFFER_A: "buffer_a"}.get(rel, "shader")- # the harness-owned recipe file beside it reserves its names (redefines_recipe)- recipes = path.parent / Path(gl.RECIPES).name- reserved = frozenset(gl.defined_functions(recipes.read_text(errors="replace"))) if recipes.is_file() else frozenset()- return _errors(gl._check_file(rel, text, role=role, recipe_names=reserved), max_errors)---def _urdf(rel: str, text: str, max_errors: int) -> FileVerdict:- from codeverse.languages.urdf import lint_urdf_text-- findings, _links = lint_urdf_text(text, label=rel)- return _errors(findings, max_errors)---def lint_one_file(language: str, rel: str, text: str, path: Path, *, max_errors: int = MAX_ERRORS) -> FileVerdict:- """Verdict for ONE just-written source file (``rel`` workspace-relative, ``path`` on disk).-- Cheap by construction: an ``ast.parse`` + visitor for python, one ``node --check``- for JS, regexes for GLSL / URDF. Files outside ``src/`` and types the language has no- per-file check for come back ``checked=False``.- """- try:- lang = Language(language)- except ValueError:- return FileVerdict(checked=False)- if not rel.startswith("src/"):- return FileVerdict(checked=False)- suffix = Path(rel).suffix- try:- if suffix == ".py":- return _python(lang, rel, text, max_errors)- if suffix in (".js", ".mjs") and lang in (Language.THREEJS, Language.SCENE_THREEJS):- return _js(path, max_errors)- if suffix in (".frag", ".glsl") and lang is Language.GLSL_SHADER:- return _glsl(rel, text, path, max_errors)- if suffix == ".urdf" and lang is Language.URDF_BLENDER:- return _urdf(rel, text, max_errors)- except Exception as e: # noqa: BLE001 — a lint crash is not the agent's problem- log.warning("per-file lint of %s failed: %s: %s", rel, type(e).__name__, e)- return FileVerdict(checked=False)---__all__ = ["MAX_ERRORS", "FileVerdict", "lint_one_file"]diff --git a/harness/codeverse/models/anthropic.py b/harness/codeverse/models/anthropic.pyindex 25321e86..dca68db4 100644--- a/harness/codeverse/models/anthropic.py+++ b/harness/codeverse/models/anthropic.py@@ -33,8 +33,10 @@ from codeverse.models.base import ModelErrorfrom codeverse.models.parts import (BoundedCache,Stopwatch,+ attempt_timeout_s,classify_sdk_exception,image_b64,+ retry_budget_s,with_logged_retries,)from codeverse.models.pricing import cache_write_surcharge, estimate_cost@@ -304,10 +306,11 @@ class AnthropicModel:# -------------------------------------------------------------- generatedef generate(self, request: ChatRequest) -> ChatResponse:kwargs = build_kwargs(request, self.model, json_mode=self.json_mode)+ deadline = time.monotonic() + retry_budget_s(request.max_wait_s)def attempt() -> ChatResponse:try:- return self._once(kwargs, request)+ return self._once(kwargs, request, deadline)except Exception as exc: # noqa: BLE001 - classifiederr = classify_exception(exc)raise err from cause_for(err, exc)@@ -317,10 +320,12 @@ class AnthropicModel:max_delay=self.max_delay, sleep=self._sleep, log=log,max_wait_s=request.max_wait_s)- def _once(self, kwargs: dict[str, Any], request: ChatRequest) -> ChatResponse:+ def _once(self, kwargs: dict[str, Any], request: ChatRequest, deadline: float) -> ChatResponse:client = self.client()with Stopwatch() as sw:- msg = client.messages.create(model=self.model, **kwargs)+ # the client is built once with a fixed timeout; the deadline is per call+ msg = client.messages.create(+ model=self.model, timeout=attempt_timeout_s(deadline, self.timeout_s), **kwargs)text, calls, submit, thinking_blocks = parse_content(msg.content)stop = str(msg.stop_reason or "")if calls and thinking_blocks:diff --git a/harness/codeverse/models/openai.py b/harness/codeverse/models/openai.pyindex 508f0e23..61ddeb16 100644--- a/harness/codeverse/models/openai.py+++ b/harness/codeverse/models/openai.py@@ -26,7 +26,14 @@ from codeverse.contracts.chat import ()from codeverse.contracts.common import Usagefrom codeverse.models.base import ModelError-from codeverse.models.parts import Stopwatch, classify_sdk_exception, image_b64, with_logged_retries+from codeverse.models.parts import (+ Stopwatch,+ attempt_timeout_s,+ classify_sdk_exception,+ image_b64,+ retry_budget_s,+ with_logged_retries,+)from codeverse.models.pricing import estimate_costfrom codeverse.models.retry import MAX_WAIT_S, cause_forfrom codeverse.models.schema_utils import (@@ -271,11 +278,13 @@ class OpenAIModel:# -------------------------------------------------------------- generatedef generate(self, request: ChatRequest) -> ChatResponse:+ deadline = time.monotonic() + retry_budget_s(request.max_wait_s)+def attempt() -> ChatResponse:strict = self._strict_ok and request.response_schema is not Nonekwargs = build_kwargs(request, self.model, strict_schema=strict)try:- return self._once(kwargs, request)+ return self._once(kwargs, request, deadline)except Exception as exc: # noqa: BLE001 - classifiederr = classify_exception(exc)if strict and _is_schema_rejection(err):@@ -288,7 +297,7 @@ class OpenAIModel:self._strict_ok = Falsekwargs = build_kwargs(request, self.model, strict_schema=False)try:- return self._once(kwargs, request)+ return self._once(kwargs, request, deadline)except Exception as exc2: # noqa: BLE001err2 = classify_exception(exc2)raise err2 from cause_for(err2, exc2)@@ -299,10 +308,12 @@ class OpenAIModel:max_delay=self.max_delay, sleep=self._sleep, log=log,max_wait_s=request.max_wait_s)- def _once(self, kwargs: dict[str, Any], request: ChatRequest) -> ChatResponse:+ def _once(self, kwargs: dict[str, Any], request: ChatRequest, deadline: float) -> ChatResponse:client = self.client()with Stopwatch() as sw:- completion = client.chat.completions.create(model=self.model, **kwargs)+ # the client is built once with a fixed timeout; the deadline is per call+ completion = client.chat.completions.create(+ model=self.model, timeout=attempt_timeout_s(deadline, self.timeout_s), **kwargs)if not completion.choices:raise ModelError("OpenAI returned no choices", retryable=True)text, calls, finish = parse_choice(completion.choices[0])diff --git a/harness/codeverse/models/parts.py b/harness/codeverse/models/parts.pyindex 87458c3e..0f8ced7c 100644--- a/harness/codeverse/models/parts.py+++ b/harness/codeverse/models/parts.py@@ -118,6 +118,34 @@ def classify_sdk_exception(exc: BaseException, sdk: Any, label: str,return ModelError(f"{label} unexpected error: {type(exc).__name__}: {exc}", retryable=False)+#: floor of the per-attempt SDK timeout derived from what is left of the call's+#: ``max_wait_s`` budget: a call that starts near its deadline still gets ONE real+#: attempt instead of an instant timeout. Same 20 s as gemini's ``HTTP_TIMEOUT_FLOOR_S``+#: and the judge's own ``SAMPLE_MIN_WAIT_S``, so an attempt in flight overshoots the+#: deadline by at most this floor.+SDK_TIMEOUT_FLOOR_S = 20.0+++def retry_budget_s(max_wait_s: float | None) -> float:+ """The budget for ONE logical call: the caller clips ``RETRY_DEADLINE_S``, never extends it."""+ from codeverse.models.retry import RETRY_DEADLINE_S++ return RETRY_DEADLINE_S if max_wait_s is None else min(RETRY_DEADLINE_S, float(max_wait_s))+++def attempt_timeout_s(deadline: float, ceiling: float) -> float:+ """The SDK timeout for ONE attempt: what is left of ``deadline``, capped at the+ client's ``timeout_s`` and floored at :data:`SDK_TIMEOUT_FLOOR_S`.++ ``with_retries`` checks the deadline only BETWEEN attempts and both SDK clients are+ built once with a fixed ``timeout`` (600 s), so a judge told it had 20 s of budget+ left held a socket for 600 s (audit 2026-08-29). The floor is what keeps a legitimate+ long completion (the 930 s plan budget) on its full ``timeout_s`` — this shortens an+ attempt, it never lengthens one. Gemini clips the same way (``_attempt_config``).+ """+ return min(ceiling, max(SDK_TIMEOUT_FLOOR_S, deadline - time.monotonic()))++def with_logged_retries(attempt: Any, *, label: str, model: str, attempts: int,base_delay: float, max_delay: float, sleep: Any, log: Any,max_wait_s: float | None = None) -> Any:@@ -127,13 +155,13 @@ def with_logged_retries(attempt: Any, *, label: str, model: str, attempts: int,their waits included; ``None`` = ``RETRY_DEADLINE_S``); the backoff itself is``attempts`` x <= ``MAX_WAIT_S`` (3 s), the round-trips are the real cost."""- from codeverse.models.retry import RETRY_DEADLINE_S, with_retries+ from codeverse.models.retry import with_retriesdef on_retry(n: int, exc: BaseException, delay: float) -> None:log.warning("%s %s attempt %d/%d failed (%s); retrying in %.1fs",label, model, n, attempts, exc, delay)- budget = RETRY_DEADLINE_S if max_wait_s is None else min(RETRY_DEADLINE_S, float(max_wait_s))+ budget = retry_budget_s(max_wait_s)return with_retries(attempt, is_retryable=lambda e: isinstance(e, ModelError) and e.retryable,attempts=attempts, base_delay=base_delay, max_delay=max_delay, max_total_s=budget,on_retry=on_retry, sleep=sleep)diff --git a/harness/codeverse/models/schema_utils.py b/harness/codeverse/models/schema_utils.pyindex cc296743..bb2abdaa 100644--- a/harness/codeverse/models/schema_utils.py+++ b/harness/codeverse/models/schema_utils.py@@ -385,8 +385,9 @@ def ask_structured(model: Any, schema: type[BaseModel], *, system: str, text: stresp = model.generate(req)except ModelError as e:return None, Usage(), f"call failed: {e}"- payload = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text)- try:+ try: # the parse is inside: every provider raises ModelError first today, but this+ # function must not depend on all three keeping that half of the ChatModel contract+ payload = resp.parsed if resp.parsed is not None else parse_json_lenient(resp.text)return schema.model_validate(payload), resp.usage, ""- except (ValidationError, TypeError) as e:+ except (JsonParseError, ValidationError, TypeError) as e:return None, resp.usage, f"answer unparsable: {e}"diff --git a/harness/codeverse/skills/__init__.py b/harness/codeverse/skills/__init__.pyindex cf9f572b..c17c8ee3 100644--- a/harness/codeverse/skills/__init__.py+++ b/harness/codeverse/skills/__init__.py@@ -1,9 +1,13 @@"""The 3dcv skill library: task-scoped rule sheets, routed automatically, read-measured.-A *skill* is not a renamed cookbook chapter. The cookbook stays the reference manual-(copyable code, reachable by ``read_cookbook``); a skill is <=350 lines of rules and-numbers for one recurring failure class, and it is attached to a session only when the-track / language / kind / plan / **previous round's gate findings** say it applies.+A *skill* is not a renamed cookbook chapter — the two sit on opposite sides of the split+in ``prompts/catalog.py``. The cookbook is PROMPT material: the reference manual of+copyable code, resolved through that catalog, inlined into the generate templates and+materialised at ``.3dcv/cookbook.md`` for the agent to re-read (the ``read_cookbook`` MCP+tool that once served it a chapter at a time was deleted — 0 calls in 16 zone sessions).+A skill is AGENT-READ material the harness only materialises: <=350 lines of rules and+numbers for one recurring failure class, attached to a session only when the track /+language / kind / plan / **previous round's gate findings** say it applies.Why the library lives inside the package: every backend reads it from a materialisedworkspace copy, but the source of truth ships in the wheel, so it must be package datadiff --git a/harness/codeverse/spatial/tool_common.py b/harness/codeverse/spatial/tool_common.pyindex 4d970798..39dff4f1 100644--- a/harness/codeverse/spatial/tool_common.py+++ b/harness/codeverse/spatial/tool_common.py@@ -207,23 +207,23 @@ def cached_render_glb(explode: float = 0.0,sheet: bool = True,) -> RenderSet:- """``render_glb`` with an on-disk RenderSet cache (same args → same files)."""+ """``render_glb`` into a deterministic per-call out_dir; the CACHE lives in+ ``spatial.render``, which is the only thing allowed to decide a PNG is still good.++ This used to keep a second ``renderset.json`` marker here, keyed on the GLB's+ size+mtime alone. It served stale views whenever a rebuild landed on the same+ size and mtime, ignored a rig edit / CACHE_VERSION bump entirely, and — because the+ marker stores absolute paths — a copied workspace returned views inside the ORIGINAL+ one. ``render_glb``'s key (sha256 of the GLB + CACHE_VERSION + the rig signature)+ has none of those holes, so one authority is both cheaper and correct.+ """out_dir = render_cache_dir(ctx, glb, views=[v.name for v in views], mode=mode, size=size,isolate=list(isolate or []), explode=explode, sheet=sheet)- marker = out_dir / "renderset.json"- if marker.is_file():- try:- rs = RenderSet.model_validate_json(marker.read_text())- if all(Path(v.path).is_file() for v in rs.views) and (not rs.contact_sheet or Path(rs.contact_sheet).is_file()):- return rs- except ValidationError:- passrender_glb = lazy("codeverse.spatial.render", "render_glb")rs = render_glb(glb, out_dir, views=list(views), mode=mode, width=size, height=size,isolate=list(isolate) if isolate else None, explode=explode, sheet=sheet)if not isinstance(rs, RenderSet):raise ToolUnavailable(f"render_glb returned {type(rs).__name__}, expected RenderSet")- marker.write_text(rs.model_dump_json())return rsdiff --git a/harness/tests/agents/test_agent_job_wiring.py b/harness/tests/agents/test_agent_job_wiring.pyindex c06584fa..b538e5dd 100644--- a/harness/tests/agents/test_agent_job_wiring.py+++ b/harness/tests/agents/test_agent_job_wiring.py@@ -29,9 +29,11 @@ class StubAgent:def test_images_reach_the_agent_as_paths_in_the_prompt(tmp_ws: Workspace, tmp_path):"""No vendor CLI takes an image on argv: the contact sheet the judge scored (and thereference photos) are copied into the workspace and listed for the agent's own file- tools — until 2026-08-29 ``AgentJob.images`` was filled and read by nobody. The copy- is what makes the read possible: a host path is outside every CLI's workspace, and the- sheet's own home (``artifacts/renders/``) is hidden by ``.geminiignore``."""+ tools. The copy is what makes the read possible: a host path is outside every CLI's+ workspace, and the sheet's own home (``artifacts/renders/``) is hidden by+ ``.geminiignore``. ``AgentJob.images`` used to be filled beside this and read by+ nobody; it was deleted 2026-08-30, so the prompt block and the staged bytes below are+ the whole delivery path — nothing else carries an image into a session."""sheet = tmp_path / "contact_sheet.png"sheet.write_bytes(b"png")task = GenerationTask(label="refine", prompt="fix the horn", round=1, kind="refine",@@ -45,7 +47,8 @@ def test_images_reach_the_agent_as_paths_in_the_prompt(tmp_ws: Workspace, tmp_paassert (tmp_ws.root / ".3dcv/images/00_contact_sheet.png").read_bytes() == b"png"# an unreadable source is still named, never silently droppedassert "reference (target): `/refs/photo.jpg`" in job.prompt- assert job.images and job.images[0].path == str(sheet)+ # and only the readable one is staged: the named-but-uncopied path stays a host path+ assert sorted(p.name for p in (tmp_ws.root / ".3dcv/images").iterdir()) == ["00_contact_sheet.png"]run_agent_task(tmp_ws, agent=agent, task=task.model_copy(update={"images": [], "label": "r2"}))assert "Images for this task" not in agent.jobs[1].promptdiff --git a/harness/tests/agents/test_materialize.py b/harness/tests/agents/test_materialize.pyindex 5f009df2..d91cef7b 100644--- a/harness/tests/agents/test_materialize.py+++ b/harness/tests/agents/test_materialize.py@@ -3,6 +3,7 @@from __future__ import annotationsimport json+import loggingimport sysfrom codeverse.agents.cli_common import default_mcp_command@@ -18,7 +19,7 @@ def _mat(ws: Workspace, kind: str = "gemini-cli", spatial: bool = True, cookbookdef test_writes_three_bodies_same_content(tmp_ws: Workspace):- res = _mat(tmp_ws)+ _mat(tmp_ws)bodies = [(tmp_ws.root / n).read_text() for n in ("AGENTS.md", "GEMINI.md", "CLAUDE.md")]assert bodies[0] == bodies[1] == bodies[2]body = bodies[0]@@ -26,7 +27,6 @@ def test_writes_three_bodies_same_content(tmp_ws: Workspace):assert "never import from `codeverse`" in body.lower() or "Never import from `codeverse`" in bodyassert CONTRACT.splitlines()[0] in bodyassert "Spatial tools (3dcv)" in body- assert len(res.body_files) == 3def test_no_mcp_server_is_written_into_the_workspace(tmp_ws: Workspace):@@ -50,7 +50,7 @@ def test_ignore_files_keep_agent_facing_paths_readable(tmp_ws: Workspace):from codeverse.agents.materialize import IGNORE_LINES- res = _mat(tmp_ws)+ _mat(tmp_ws)def ignored(rel: str, lines: tuple[str, ...]) -> bool:for pat in lines:@@ -63,7 +63,7 @@ def test_ignore_files_keep_agent_facing_paths_readable(tmp_ws: Workspace):for f in (".geminiignore", ".aiexclude"):lines = tuple(ln for ln in (tmp_ws.root / f).read_text().splitlines() if ln.strip())- assert lines == IGNORE_LINES and str(tmp_ws.root / f) in res.ignore_files+ assert lines == IGNORE_LINESassert "artifacts/" not in lines and "trajectories/" not in linesfor readable in ("artifacts/census.json", "artifacts/build_last.json", "artifacts/measurement.json","artifacts/gates/r00/contract_tool.json", "artifacts/tool_renders/r00_ab/sheet.png",@@ -81,19 +81,27 @@ def test_spatial_disabled_drops_server_and_documents_absence(tmp_ws: Workspace):assert "No spatial tools are available" in (tmp_ws.root / "AGENTS.md").read_text()-def test_cookbook_copied_when_found(tmp_ws: Workspace, tmp_path):+def test_cookbook_copied_when_found(tmp_ws: Workspace, tmp_path, caplog):cb = tmp_path / "cookbook.md"cb.write_text("# cookbook\nsnippet")- res = _mat(tmp_ws, cookbook=str(cb))- assert res.cookbook_path.endswith(f"{CV3D_DIR}/cookbook.md")+ with caplog.at_level(logging.WARNING, logger="codeverse.agents.materialize"):+ _mat(tmp_ws, cookbook=str(cb))assert (tmp_ws.root / CV3D_DIR / "cookbook.md").read_text().startswith("# cookbook")assert f"{CV3D_DIR}/cookbook.md" in (tmp_ws.root / "AGENTS.md").read_text()- assert not res.warnings+ assert not [r for r in caplog.records if r.name == "codeverse.agents.materialize"], \+ "a resolved cookbook must not warn"-def test_missing_cookbook_is_a_warning(tmp_ws: Workspace):- res = _mat(tmp_ws, cookbook="nope/cookbook.md")- assert any("cookbook not found" in w for w in res.warnings)+def test_missing_cookbook_warns_where_someone_can_see_it(tmp_ws: Workspace, caplog):+ """The unresolved cookbook is the failure `tracks/common.cookbook_rel_for` was fixed for+ (an articulated run told the agent "No cookbook is available" while its 24 kB cookbook sat+ on disk). It used to land in a `Materialized.warnings` list every caller threw away; the+ log line is the whole signal now, so it has to fire."""+ with caplog.at_level(logging.WARNING, logger="codeverse.agents.materialize"):+ _mat(tmp_ws, cookbook="nope/cookbook.md")+ assert any("cookbook not found" in r.getMessage() and "nope/cookbook.md" in r.getMessage()+ for r in caplog.records)+ assert "No cookbook is available" in (tmp_ws.root / "AGENTS.md").read_text()def test_kind_specific_tool_hint(tmp_ws: Workspace):@@ -115,7 +123,7 @@ def test_codex_overrides_are_valid_toml_fragments():def test_default_mcp_command_is_the_backends_interpreter(tmp_ws: Workspace):# one place knows the command: the body + codex overrides quote sys.executable, never bare "python"- res = materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", cookbook_rel="", spatial_tools=True)- assert res.mcp_command == default_mcp_command(tmp_ws)- assert res.mcp_command[0] == sys.executable- assert sys.executable in (tmp_ws.root / "AGENTS.md").read_text()+ materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", cookbook_rel="", spatial_tools=True)+ body = (tmp_ws.root / "AGENTS.md").read_text()+ assert default_mcp_command(tmp_ws)[0] == sys.executable+ assert f"command: `{' '.join(default_mcp_command(tmp_ws))}`" in bodydiff --git a/harness/tests/compare_bench/test_compare_matrix.py b/harness/tests/compare_bench/test_compare_matrix.pyindex 98190959..cd26efb9 100644--- a/harness/tests/compare_bench/test_compare_matrix.py+++ b/harness/tests/compare_bench/test_compare_matrix.py@@ -276,3 +276,32 @@ def test_max_usd_flag_was_deleted(capsys):main(["--prompts", "x.yaml", "--arms", "harness:gemini-cli:m", "--out", "o","--max-usd", "2.5"])assert "--max-usd" in capsys.readouterr().err+++def test_no_resume_starts_the_harness_arm_fresh(tmp_path: Path):+ """`--no-resume` regenerates every other arm, so the harness arm must not resume.++ It used to: `_run_harness` only ever asked whether `<cell>/run` existed, so the arm+ that had SUCCEEDED handed back its old score, generated in the old weather, against a+ partner regenerated in today's.+ """+ ev = FakeEvaluator()+ inner = fake_run_track(0.9)+ seen: list[bool] = []++ def run(spec, ws, resume):+ seen.append(resume)+ return inner(spec, ws, resume)++ out = tmp_path / "cmp"+ arms = parse_arms("harness:gemini-cli:gemini-3.6-flash")+ deps = _deps(ev, {}, run)+ opts = CompareOptions(judge="gemini:fixed", limit=1, parallel=1, pairwise=False)+ cell = Path(run_matrix(BATTERY, out, arms, opts, deps)[0].workspace)+ (cell / "run" / "src" / "stale.py").write_text("# stale")+ run_matrix(BATTERY, out, arms, opts, deps)+ assert seen == [False], "a plain resume re-runs nothing: the cell is already recorded"+ run_matrix(BATTERY, out, arms, opts.model_copy(update={"resume": False}), deps)+ assert seen == [False, False], "the redone cell ran fresh, not resumed"+ assert (cell / "run.attempt1" / "src" / "stale.py").is_file(), "the old run is archived, not deleted"+ assert not (cell / "run" / "src" / "stale.py").exists()diff --git a/harness/tests/flywheel_cli/test_bench.py b/harness/tests/flywheel_cli/test_bench.pyindex 5ddc406d..3f3e6d89 100644--- a/harness/tests/flywheel_cli/test_bench.py+++ b/harness/tests/flywheel_cli/test_bench.py@@ -195,6 +195,9 @@ def test_the_runner_classifies_the_outage_that_reaches_it(tmp_path: Path):assert calls == [], "a plain resume still skips every recorded row"run_battery(battery, out, BenchOptions(parallel=1, limit=1, redo_status=["infra_failed"]), run_fn=counting)assert len(calls) == 1, "--redo-status infra_failed re-runs what the weather lost"+ # ...and it is the ONLY way in. A `resume` switch that merely dropped the recorded rows+ # skipped the archive below and silently resumed the old workspace, spec and clock.+ assert "resume" not in BenchOptions.model_fieldsdef test_a_redo_starts_from_a_fresh_workspace(tmp_path):diff --git a/harness/tests/languages/test_file_lint.py b/harness/tests/languages/test_file_lint.pydeleted file mode 100644index 94bfcb8d..00000000--- a/harness/tests/languages/test_file_lint.py+++ /dev/null@@ -1,68 +0,0 @@-"""``languages/file_lint.py``: one file → one cheap verdict, per language, never raising."""--from __future__ import annotations--from pathlib import Path--import pytest--from codeverse.languages.file_lint import FileVerdict, lint_one_file---def _v(language: str, rel: str, text: str, tmp_path: Path, **kw) -> FileVerdict:- p = tmp_path / rel- p.parent.mkdir(parents=True, exist_ok=True)- p.write_text(text)- return lint_one_file(language, rel, text, p, **kw)---def test_blender_good_and_broken(tmp_path):- ok = _v("blender", "src/parts/seat.py", "import bpy\n\n\ndef build_seat():\n return bpy.context.object\n", tmp_path)- assert ok.checked and not ok.errors and ok.summary() == "syntax OK"- bad = _v("blender", "src/model.py", "import bpy\nx = (\n", tmp_path)- assert bad.checked and bad.n_total == 1 and bad.errors[0].startswith("line ") and "SyntaxError" in bad.errors[0]- assert bad.summary().startswith("1 lint error(s)")- # a helper module needs no `import bpy`; a part file does- assert not _v("blender", "src/parts/_helpers.py", "def f():\n return 1\n", tmp_path).errors- nobpy = _v("blender", "src/parts/leg.py", "def build_leg():\n return None\n", tmp_path)- assert nobpy.errors and "never imports bpy" in nobpy.errors[0]---def test_first_three_errors_only(tmp_path):- src = "import bpy\nimport subprocess\nimport socket\nimport pathlib\nimport urllib\nimport requests\n"- v = _v("blender", "src/model.py", src, tmp_path)- assert v.n_total >= 4 and len(v.errors) == 3- assert v.summary().startswith(f"{v.n_total} lint error(s)") and v.summary().count("\n - ") == 3---def test_cadquery_opengl_urdf(tmp_path):- assert "SyntaxError" in _v("cadquery", "src/model.py", "import cadquery as cq\nresult = cq.Workplane(\n", tmp_path).errors[0]- gl = _v("opengl_python", "src/program.py", "def setup(ctx, width, height):\n return {}\n", tmp_path)- assert gl.checked and any("render" in e for e in gl.errors) # missing render()- urdf = _v("urdf_blender", "src/robot.urdf", "<robot name='r'><link name='base'/><joint", tmp_path)- assert urdf.checked and urdf.errors- model = _v("urdf_blender", "src/model.py", "import bpy\nx = 1\n", tmp_path)- assert model.checked and not model.errors---def test_glsl_static_rules(tmp_path):- good = "void mainImage(out vec4 fragColor, in vec2 fragCoord) { fragColor = vec4(1.0); }\n"- assert _v("glsl_shader", "src/shader.frag", good, tmp_path).summary() == "syntax OK"- bad = _v("glsl_shader", "src/shader.frag", "#version 330 core\n" + good, tmp_path)- assert bad.errors and "line 1" in bad.errors[0] and "#version" in bad.errors[0]---def test_threejs_node_check(tmp_path):- ok = _v("threejs", "src/parts/seat.js", "export function buildSeat(THREE) { return new THREE.Group(); }\n", tmp_path)- assert ok.checked and not ok.errors- bad = _v("threejs", "src/parts/seat.js", "export function buildSeat(THREE) {\n return new THREE.Group(;\n}\n", tmp_path)- assert bad.checked and bad.errors and "line 2" in bad.errors[0]---def test_unchecked_cases(tmp_path):- assert not _v("blender", "public/x.py", "x = (\n", tmp_path).checked # outside src/- assert not _v("blender", "src/notes.md", "# hi", tmp_path).checked # no per-file check- assert not _v("opengl_python", "src/pass.glsl", "#version 330", tmp_path).checked # no cheap GLSL compile- assert not _v("not-a-language", "src/model.py", "x = (", tmp_path).checked- assert FileVerdict(checked=False).summary() == ""diff --git a/harness/tests/models/test_anthropic.py b/harness/tests/models/test_anthropic.pyindex 6b32c883..7499e591 100644--- a/harness/tests/models/test_anthropic.py+++ b/harness/tests/models/test_anthropic.py@@ -314,3 +314,25 @@ def test_a_failed_reply_carries_what_it_was_billed():with pytest.raises(ModelError) as e:m.generate(req)assert e.value.usage.input_tokens == 100 and e.value.usage.output_tokens == 20+++def test_each_attempt_gets_what_is_left_of_the_call_budget():+ """``max_wait_s`` is the whole call's deadline, and ``with_retries`` only checks it+ BETWEEN attempts — so the attempt itself must carry it. The client is built once with+ a fixed 600 s timeout, so a judge with 20 s of budget left used to hold a socket for+ 600 s. Floor: a long completion (the 930 s plan) keeps the full client timeout."""+ m, fc = make([msg([text("hi")])], timeout_s=600.0)+ m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=25.0))+ assert 20.0 <= fc.calls[0]["timeout"] <= 25.0++ m, fc = make([msg([text("hi")])], timeout_s=600.0)+ m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=5.0))+ assert fc.calls[0]["timeout"] == 20.0, "a near-dead budget still buys ONE real attempt"++ m, fc = make([msg([text("hi")])], timeout_s=600.0)+ m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=930.0))+ assert fc.calls[0]["timeout"] == 600.0, "a long plan is bounded by the client, not clipped"++ m, fc = make([msg([text("hi")])], timeout_s=600.0)+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))+ assert fc.calls[0]["timeout"] == 600.0diff --git a/harness/tests/models/test_openai.py b/harness/tests/models/test_openai.pyindex 745a853f..bbbfcd9c 100644--- a/harness/tests/models/test_openai.py+++ b/harness/tests/models/test_openai.py@@ -286,3 +286,23 @@ def test_a_failed_reply_carries_what_it_was_billed():m.generate(req)u = e.value.usageassert u.input_tokens == 100 and u.output_tokens == 20 and u.thoughts_tokens == 10+++def test_each_attempt_gets_what_is_left_of_the_call_budget():+ """Same deadline contract as the anthropic adapter: the SDK client is built once with+ a fixed 600 s timeout, so the per-call ``max_wait_s`` has to reach ``create()``."""+ m, fc = make([completion("hi")], timeout_s=600.0)+ m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=25.0))+ assert 20.0 <= fc.calls[0]["timeout"] <= 25.0++ m, fc = make([completion("hi")], timeout_s=600.0)+ m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=5.0))+ assert fc.calls[0]["timeout"] == 20.0, "a near-dead budget still buys ONE real attempt"++ m, fc = make([completion("hi")], timeout_s=600.0)+ m.generate(ChatRequest(messages=[ChatMessage.user("x")], max_wait_s=930.0))+ assert fc.calls[0]["timeout"] == 600.0, "a long plan is bounded by the client, not clipped"++ m, fc = make([completion("hi")], timeout_s=600.0)+ m.generate(ChatRequest(messages=[ChatMessage.user("x")]))+ assert fc.calls[0]["timeout"] == 600.0diff --git a/harness/tests/models/test_schema_utils.py b/harness/tests/models/test_schema_utils.pyindex 80da2236..48b43d36 100644--- a/harness/tests/models/test_schema_utils.py+++ b/harness/tests/models/test_schema_utils.py@@ -205,3 +205,24 @@ def test_parse_json_lenient_accepts_wrappers_and_rejects_non_json():with pytest.raises(JsonParseError):parse_json_lenient(text)assert json.dumps(parse_json_lenient('{"n": {"x": [1]}}')) == '{"n": {"x": [1]}}'+++def test_ask_structured_returns_the_triple_for_prose_it_cannot_parse():+ """The five callers branch on the error string; none of them catches. Every shipped+ provider raises ModelError on unparseable structured output, but this must not depend+ on all three keeping that half of the ChatModel contract."""+ from codeverse.contracts.chat import ChatResponse+ from codeverse.contracts.common import Usage+ from codeverse.models.schema_utils import ask_structured++ class Answer(BaseModel):+ ok: bool++ class Prose:+ """A ChatModel that hands back text instead of raising (base.py:22-30 says it should)."""++ def generate(self, request):+ return ChatResponse(text="I refuse.", usage=Usage(cost_usd=0.01))++ out, usage, err = ask_structured(Prose(), Answer, system="s", text="t", temperature=0.2, label="l")+ assert out is None and usage.cost_usd == 0.01 and err.startswith("answer unparsable:")diff --git a/harness/tests/spatial_tools/test_render_common.py b/harness/tests/spatial_tools/test_render_common.pyindex 4dc68ff5..3efe1a4c 100644--- a/harness/tests/spatial_tools/test_render_common.py+++ b/harness/tests/spatial_tools/test_render_common.py@@ -119,6 +119,38 @@ def test_tool_out_dir_is_round_stamped(stool_ctx: ToolContext) -> None:assert a != b and a.is_dir() and a.parent == d.parent+def test_cached_render_glb_leaves_the_cache_to_render_glb(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:+ """One cache authority. ``tool_common`` used to short-circuit on its own+ ``renderset.json`` marker keyed on the GLB's size+mtime, so a rebuild that landed on+ the same stamp served stale PNGs and a copied workspace served views pointing into the+ ORIGINAL one. ``render.render_glb`` (sha256 + CACHE_VERSION + rig signature) decides now.+ """+ import codeverse.spatial.tool_common as tc+ from codeverse.contracts.artifacts import RenderSet, RenderView++ calls: list[Path] = []++ def fake_render_glb(glb, out_dir, *, views, mode, width, height, isolate, explode, sheet):+ calls.append(Path(out_dir))+ png = Path(out_dir) / f"{views[0].name}.png"+ png.write_bytes(b"png")+ return RenderSet(views=[RenderView(name=views[0].name, path=str(png))], contact_sheet=None)++ monkeypatch.setattr(tc, "lazy", lambda module, attr: fake_render_glb)+ glb = stool_ctx.workspace.artifacts / "object.glb"+ preset = OBJECT_VIEWS[0]+ first = tc.cached_render_glb(stool_ctx, glb, views=[preset])+ stamp = glb.stat()+ glb.write_bytes(glb.read_bytes()[::-1]) # new content, same size+ import os++ os.utime(glb, ns=(stamp.st_atime_ns, stamp.st_mtime_ns)) # ...and the same mtime+ second = tc.cached_render_glb(stool_ctx, glb, views=[preset])+ assert len(calls) == 2 and calls[0] == calls[1], calls # re-rendered into the same dir+ assert first.views[0].path == second.views[0].path+ assert not list(calls[0].glob("renderset.json")) # no second marker on disk++def test_tool_unavailable_is_reported_by_the_registry(stool_ctx: ToolContext, monkeypatch: pytest.MonkeyPatch) -> None:"""No tool catches ToolUnavailable itself any more — ToolDef.call does it forall of them, with the tool's own registered name."""diff --git a/harness/tests/spatial_tools/test_tools.py b/harness/tests/spatial_tools/test_tools.pyindex 0c71efb3..6b07f9c8 100644--- a/harness/tests/spatial_tools/test_tools.py+++ b/harness/tests/spatial_tools/test_tools.py@@ -222,8 +222,12 @@ def test_render_views_cached(stool_ctx: ToolContext, fake_renderer) -> None:assert obs.ok and obs.images[0].endswith("sheet.png") and len(obs.images) == 5 # sheet + 4 viewsassert obs.numbers["views"] == ["front_right_34", "back_left_34", "front", "top"]assert "artifacts/tool_renders/r00_" in obs.text and str(stool_ctx.workspace.root) not in obs.text- get_tool("render_views").call(stool_ctx, {})- assert fake_renderer.calls == 1 # second call served from the on-disk cache+ again = get_tool("render_views").call(stool_ctx, {})+ # same args → the same deterministic out_dir, which is what lets render_glb's OWN cache+ # (sha256 of the glb + CACHE_VERSION + rig signature) skip the work. It is reached every+ # time: tool_common used to keep a second size+mtime marker here and short-circuit above+ # it, which served stale PNGs. This fake renderer has no cache, hence two calls.+ assert again.images == obs.images and fake_renderer.calls == 2obs = get_tool("render_views").call(stool_ctx, {"views": ["front", "back", "left", "right", "top"]})assert obs.ok and len(obs.images) == 1 # > 4 views → sheet onlyobs = get_tool("render_views").call(stool_ctx, {"views": ["frontal"]})