Official Codebase of 3DCodeVerse
Python
agents/cost: turn telemetry comes back, and one writer owns the ledger
gaoypenge3f1f646230f
diff --git a/harness/codeverse/agents/backends.py b/harness/codeverse/agents/backends.pyindex e3c875b2..35bde4b6 100644--- a/harness/codeverse/agents/backends.py+++ b/harness/codeverse/agents/backends.py@@ -34,6 +34,7 @@ from codeverse.agents.cli_common import (estimate_cost_safe,exists_on_path,failed,+ find_json_object,finish_session,hardened_env,invoke,@@ -104,22 +105,8 @@ def write_system_settings(path: Path | None = None, *, mcp_command: list[str] |def parse_gemini_json(stdout: str) -> dict[str, Any] | None:- """The CLI prints one JSON object (possibly after log noise); find it."""- s = stdout.strip()- if not s:- return None- try:- return json.loads(s)- except json.JSONDecodeError:- pass- start = s.find("{")- while start != -1:- try:- obj = json.loads(s[start:])- return obj if isinstance(obj, dict) else None- except json.JSONDecodeError:- start = s.find("{", start + 1)- return None+ """The CLI prints one (indented, multi-line) JSON object, possibly after log noise."""+ return find_json_object(stdout, lambda d: True)def _model_usage(tok: dict[str, Any], name: str) -> Usage:@@ -245,7 +232,8 @@ class GeminiCliAgent(_CliAgent):while True:attempts += 1used.add(key)- proc = self._invoke(s, prompt, key, attempt=attempts, soft_timeout_s=next_soft)+ proc = invoke(s, self.build_argv(prompt), self.build_env(s, key), prompt=prompt, attempt=attempts,+ soft_timeout_s=next_soft, model=self.model, key_tail=key[-4:])outcome = self._interpret(s, proc)usage_total = usage_total + outcome["usage"]pool.report(key, "429" if outcome["quota"] else ("ok" if outcome["ok"] else "5xx"))@@ -266,6 +254,7 @@ class GeminiCliAgent(_CliAgent):s.notes.append(f"attempt {attempts} transient failure ({outcome['exit_reason']}); retrying with {how}")s.traj.append("retry", attempt=attempts, reason=outcome["errors"][:1])usage_total.cost_usd = round(usage_total.cost_usd, 6)+ # turns stays 0: gemini-cli's stats carry tools.totalCalls only, no turn countreturn finish_session(s, ok=outcome["ok"], exit_reason=outcome["exit_reason"], text=outcome["text"],usage=usage_total, tool_calls=usage_total.tool_calls, errors=outcome["errors"],@@ -274,11 +263,6 @@ class GeminiCliAgent(_CliAgent):finally:release_session(s)- def _invoke(self, s: Session, prompt: str, key: str, *, attempt: int,- soft_timeout_s: float | None = None) -> CompletedProc:- return invoke(s, self.build_argv(prompt), self.build_env(s, key), prompt=prompt, attempt=attempt,- soft_timeout_s=soft_timeout_s, model=self.model, key_tail=key[-4:])-def _interpret(self, s: Session, proc: CompletedProc) -> dict[str, Any]:parsed = parse_gemini_json(proc.stdout)stats = (parsed or {}).get("stats") or {}@@ -326,29 +310,12 @@ ALLOWED_TOOLS = ("Read", "Edit", "Write", "MultiEdit", "Glob", "Grep", "Skill",def parse_claude_json(stdout: str) -> dict[str, Any] | None:- """Envelope is one JSON object; tolerate leading log noise and stream-json arrays."""- s = stdout.strip()- if not s:- return None- try:- obj = json.loads(s)- except json.JSONDecodeError:- obj = None- for line in reversed(s.splitlines()):- line = line.strip()- if line.startswith("{"):- try:- cand = json.loads(line)- except json.JSONDecodeError:- continue- if isinstance(cand, dict) and cand.get("type") == "result":- return cand- obj = obj or cand- return obj if isinstance(obj, dict) else None- if isinstance(obj, list): # stream-json array: last result event wins- results = [e for e in obj if isinstance(e, dict) and e.get("type") == "result"]- return results[-1] if results else None- return obj if isinstance(obj, dict) else None+ """The ``type == "result"`` envelope, else the last JSON line (a stream-json array+ without a result event is no envelope)."""+ env = find_json_object(stdout, lambda d: d.get("type") == "result")+ if env is not None or stdout.lstrip().startswith("["):+ return env+ return find_json_object(stdout, lambda d: True)def usage_from_envelope(env: dict[str, Any], model: str) -> Usage:@@ -458,7 +425,7 @@ class ClaudeCodeAgent(_CliAgent):else:reason, ok = "completed", Truereturn finish_session(- s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=max(turns - 1, 0),+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=max(turns - 1, 0), turns=turns,errors=errors, rc=proc.rc, killed_reason=proc.killed_reason, num_turns=turns,session_id=(env or {}).get("session_id", ""), subtype=(env or {}).get("subtype", ""),model_usage=(env or {}).get("modelUsage", {}),@@ -613,7 +580,8 @@ class CodexAgent(_CliAgent):else:ok, reason = True, "completed"return finish_session(- s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=events.tool_calls, errors=errors,+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=events.tool_calls,+ turns=events.turns_completed, errors=errors,rc=proc.rc, killed_reason=proc.killed_reason, thread_id=events.thread_id,turns_completed=events.turns_completed, usage_raw=events.usage_raw,)@@ -676,17 +644,8 @@ def resolve_model(model: str, binary: str) -> str:def parse_agy_json(stdout: str) -> dict[str, Any] | None:- s = stdout.strip()- if not s:- return None- for cand in (s, *reversed([ln for ln in s.splitlines() if ln.strip().startswith("{")])):- try:- obj = json.loads(cand)- except json.JSONDecodeError:- continue- if isinstance(obj, dict) and ("response" in obj or "status" in obj):- return obj- return None+ """agy's envelope is the JSON line carrying ``response`` or ``status``."""+ return find_json_object(stdout, lambda d: "response" in d or "status" in d)def usage_from_agy(env: dict[str, Any], model: str) -> Usage:@@ -756,7 +715,8 @@ class AntigravityAgent(_CliAgent):else:ok, reason = True, "completed"return finish_session(- s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=0, errors=errors,+ s, ok=ok, exit_reason=reason, text=text, usage=usage, tool_calls=0,+ turns=int((env or {}).get("num_turns") or 0), errors=errors,rc=proc.rc, killed_reason=proc.killed_reason,conversation_id=(env or {}).get("conversation_id", ""), num_turns=(env or {}).get("num_turns", 0),)diff --git a/harness/codeverse/agents/cli_common.py b/harness/codeverse/agents/cli_common.pyindex 2362fd7c..922aa1f9 100644--- a/harness/codeverse/agents/cli_common.py+++ b/harness/codeverse/agents/cli_common.py@@ -23,6 +23,7 @@ from pydantic import BaseModelfrom codeverse.contracts.agent import AgentJob, AgentResult, FileChangefrom codeverse.contracts.common import Usage+from codeverse.models.pricing import estimate_costfrom codeverse.proc import ManagedProcess, append_jsonl_line, read_jsonl_lenient, scrub_secretsfrom codeverse.workspace import Workspace@@ -110,9 +111,8 @@ class CompletedProc:"""Outcome of :func:`run_with_watchdog`.``stdout``/``stderr`` are bounded to ``codeverse.proc.STREAM_BUDGET_BYTES`` per- stream (head + tail kept, truncation marker in between); the ``*_lines`` lists- are derived from those bounded texts — streaming consumers that must see every- line unconditionally use ``on_line``.+ stream (head + tail kept, truncation marker in between) — streaming consumers+ that must see every line unconditionally use ``on_line``."""rc: int@@ -121,8 +121,6 @@ class CompletedProc:duration_s: floattimed_out: bool = Falsekilled_reason: str = "" # "" | idle | hard_timeout- stdout_lines: list[str] = field(default_factory=list, repr=False)- stderr_lines: list[str] = field(default_factory=list, repr=False)class ActivityTracker:@@ -224,7 +222,6 @@ def run_with_watchdog(return CompletedProc(rc=rc, stdout=out_text, stderr=err_text, duration_s=time.monotonic() - t0,timed_out=bool(killed), killed_reason=killed,- stdout_lines=out_text.splitlines(), stderr_lines=err_text.splitlines(),)@@ -309,44 +306,6 @@ HARNESS_OWNED_FILES = frozenset({"events.jsonl", "run_state.json", "record.json"".mcp.json", ".geminiignore", ".aiexclude", ".gitignore"})-@dataclass-class _LiveSession:- """Registry entry: lets concurrent sessions in ONE workspace (scene fan-out) attribute files."""-- label: str- hints: frozenset[str]- t_start: float- t_end: float | None = None---_LIVE: dict[str, list[_LiveSession]] = {}-_LIVE_LOCK = threading.Lock()---def _register(ws: Workspace, label: str, hints: frozenset[str]) -> _LiveSession:- entry = _LiveSession(label=label, hints=hints, t_start=time.monotonic())- with _LIVE_LOCK:- _LIVE.setdefault(str(ws.root), []).append(entry)- return entry---def _sibling_hints(ws: Workspace, me: _LiveSession) -> frozenset[str]:- """Files claimed (``job.files_hint``) by OTHER sessions that overlapped ``me`` in time."""- me.t_end = time.monotonic()- with _LIVE_LOCK:- entries = _LIVE.get(str(ws.root), [])- claimed: set[str] = set()- for e in entries:- if e is me:- continue- overlaps = e.t_start <= me.t_end and (e.t_end is None or e.t_end >= me.t_start)- if overlaps:- claimed |= e.hints- oldest_active = min((e.t_start for e in entries if e.t_end is None), default=me.t_end)- entries[:] = [e for e in entries if e.t_end is None or e.t_end >= oldest_active]- return frozenset(claimed - me.hints)--def _hinted(path: str, hints: frozenset[str]) -> bool:return any(path == h or path.startswith(h.rstrip("/") + "/") for h in hints)@@ -356,11 +315,11 @@ def attribute_changes(*,write_roots: list[str],own_hints: frozenset[str] = frozenset(),- sibling_hints: frozenset[str] = frozenset(),) -> list[FileChange]:"""The subset of a whole-worktree git diff that belongs to ONE session: inside its- ``write_roots``, not harness-owned, and not a file another concurrent session- declared as its target (``job.files_hint``) unless this session declared it too."""+ ``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.)"""roots = tuple(r.strip("/") for r in write_roots if r.strip("/"))out: list[FileChange] = []for f in files:@@ -369,8 +328,6 @@ def attribute_changes(continueif roots and not any(f.path == r or f.path.startswith(r + "/") for r in roots):continue- if sibling_hints and _hinted(f.path, sibling_hints) and not _hinted(f.path, own_hints):- continueout.append(f)return out@@ -390,7 +347,6 @@ class Session:notes: list[str] = field(default_factory=list)attempt: int = 1files_hint: frozenset[str] = frozenset()- live: _LiveSession | None = Nonews_lock: threading.RLock | None = None@@ -454,7 +410,6 @@ def begin_session(job: AgentJob, kind: str) -> Session:if lock is not None:lock.acquire()try:- live = _register(ws, label, hints)head_before = ws.commit(f"pre:{label}")except BaseException:if lock is not None:@@ -462,7 +417,7 @@ def begin_session(job: AgentJob, kind: str) -> Session:raisereturn Session(ws=ws, job=job, kind=kind, label=label, round_index=round_index,traj=traj, head_before=head_before, attempt=attempt, files_hint=hints,- live=live, ws_lock=lock)+ ws_lock=lock)def _clean(seq: Any) -> frozenset[str]:@@ -519,11 +474,13 @@ def finish_session(text: str,usage: Usage,tool_calls: int = 0,+ turns: int = 0,errors: list[str] | None = None,**extra: Any,) -> AgentResult:"""Commit the agent's work, compute ``files_changed`` via git (attributed to this- session — see :func:`attribute_changes`), write result.json.+ session — see :func:`attribute_changes`), write result.json. ``turns`` is the+ backend's own count (``AgentResult.turns``); ``extra`` lands in result.json only.Write scope is enforced here for the CLI backends (they have no write-time gate):writes outside ``write_roots`` (and, for ``edit_only``, outside ``files_hint``) are@@ -541,14 +498,13 @@ def finish_session(errors.append(msg)s.notes.append(msg)s.ws.commit(f"agent:{s.label}")- siblings = _sibling_hints(s.ws, s.live) if s.live is not None else frozenset()files = attribute_changes(s.ws.changed_files(s.head_before), write_roots=s.job.write_roots,- own_hints=s.files_hint, sibling_hints=siblings)+ own_hints=s.files_hint)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),usage=usage, duration_s=round(time.monotonic() - s.t0, 3), tool_calls=tool_calls,- errors=errors,+ turns=turns, errors=errors,)s.traj.write_result(res, kind=s.kind, label=s.label, round=s.round_index, attempt=s.attempt, job_label=s.job.label,head_before=s.head_before, head_after=s.ws.head(), notes=s.notes, **extra)@@ -671,14 +627,51 @@ def tail(text: str, n: int = 2000) -> str:return text if len(text) <= n else text[-n:]+def find_json_object(stdout: str, accept: Callable[[dict[str, Any]], bool]) -> dict[str, Any] | None:+ """The one JSON envelope a CLI printed, possibly around log noise.++ Tries the whole text; unwraps a top-level list (claude's stream-json array) to+ its LAST accepted element; then ``{``-starting lines from the END (claude / agy+ print one envelope per line after their chatter); then ``json.loads(s[start:])``+ forward from every ``{`` — mandatory, not a fallback: ``gemini --output-format+ json`` prints an INDENTED multi-line object that no single-line scan can parse.+ ``accept`` says which dict is the envelope."""+ s = stdout.strip()+ if not s:+ return None+ try:+ whole = json.loads(s)+ except json.JSONDecodeError:+ whole = None+ if isinstance(whole, list):+ hits = [e for e in whole if isinstance(e, dict) and accept(e)]+ return hits[-1] if hits else None+ if isinstance(whole, dict):+ return whole if accept(whole) else None+ for line in reversed(s.splitlines()):+ line = line.strip()+ if not line.startswith("{"):+ continue+ try:+ cand = json.loads(line)+ except json.JSONDecodeError:+ continue+ if isinstance(cand, dict) and accept(cand):+ return cand+ start = s.find("{")+ while start != -1:+ try:+ obj = json.loads(s[start:])+ except json.JSONDecodeError:+ start = s.find("{", start + 1)+ continue+ return obj if isinstance(obj, dict) and accept(obj) else None+ return None++# --------------------------------------------------------------------------- pricingdef estimate_cost_safe(provider: str, model: str, usage: Usage) -> float:- """``codeverse.models.pricing.estimate_cost`` when available; else 0.0 + warning."""- try:- from codeverse.models.pricing import estimate_cost- except ImportError:- log.warning("codeverse.models.pricing unavailable; cost for %s:%s recorded as 0", provider, model)- return 0.0+ """``estimate_cost`` that never raises: an unknown model prices as 0.0 + a warning."""try:return float(estimate_cost(provider, model, usage))except Exception as e: # unknown model in the price table must not sink the rundiff --git a/harness/codeverse/agents/materialize.py b/harness/codeverse/agents/materialize.pyindex cf4218c2..d0cf9106 100644--- a/harness/codeverse/agents/materialize.py+++ b/harness/codeverse/agents/materialize.py@@ -5,10 +5,10 @@ One shared body is written to ``AGENTS.md`` (codex / generic), ``GEMINI.md``the ``3dcv`` spatial tools, where the cookbook is, and the language contract.MCP wiring:-* gemini-cli → the per-session system settings (``agents/gemini_cli.write_system_settings``);+* gemini-cli → the per-session system settings (``agents/backends.write_system_settings``);``ws/.gemini/settings.json`` is agent-writable, so it only carries the ``context`` block-* claude-code → per-session ``trajectories/<label>_rNN/mcp.json`` (``agents/claude_code.py``)-* codex → ``-c`` overrides returned in :class:`Materialized.codex_overrides`+* claude-code → per-session ``trajectories/<label>_rNN/mcp.json`` (``agents/backends.py``)+* codex → ``-c`` overrides (:func:`codex_mcp_overrides`, built per session by its backend)* agy (Antigravity) → no per-workspace MCP; the body documents the CLI fallback.Skills: the routed ``SKILL.md`` bundles are written per ROUND, not here — the set depends@@ -18,9 +18,9 @@ into the three body files this module writes, so there is exactly one shared heanew one (docs/COST.md §13 measured and reverted a second head at +2,925 tokens/call).Nothing here needs to change for the CLIs to see them: codex's per-tool approval overridebelow is scoped to ``mcp_servers.3dcv.*`` and cannot reach its skills loader, and-gemini-cli's ``activate_skill`` consent is already covered by ``--approval-mode yolo``-(``agents/gemini_cli.py``). claude-code needed one change — ``Skill`` in its-``--allowedTools``, see ``agents/claude_code.py``.+gemini-cli's ``activate_skill`` consent is already covered by ``--approval-mode yolo``.+claude-code needed one change — ``Skill`` in its ``--allowedTools``+(``agents/backends.ALLOWED_TOOLS``).Ignore files: ``.geminiignore`` / ``.aiexclude`` hide only noise (:data:`IGNORE_LINES`);``.gemini/settings.json`` gets ``context.fileFiltering.respectGitIgnore=false`` because the@@ -36,6 +36,7 @@ from pathlib import Pathfrom pydantic import BaseModel, Field+from codeverse.agents.cli_common import default_mcp_commandfrom codeverse.prompts import PROMPTS_DIRfrom codeverse.workspace import Workspace@@ -65,8 +66,6 @@ class Materialized(BaseModel):ignore_files: list[str] = Field(default_factory=list)cookbook_path: str = ""mcp_command: list[str] = Field(default_factory=list)- codex_overrides: list[str] = Field(default_factory=list, description="extra argv for `codex exec` (-c k=v pairs)")- agy_mcp: str = Field(default="", description="how Antigravity reaches the tools")warnings: list[str] = Field(default_factory=list)@@ -195,12 +194,15 @@ def materialize_workspace(contract_md: str,cookbook_rel: str,spatial_tools: bool,- mcp_command: list[str],+ mcp_command: list[str] | None = None,) -> Materialized:- """Write AGENTS.md / GEMINI.md / CLAUDE.md + MCP configs + ignore files into ``ws``."""- out = Materialized(mcp_command=list(mcp_command))- if spatial_tools and not mcp_command:- raise ValueError("spatial_tools=True requires a non-empty mcp_command")+ """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."""+ 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)@@ -219,7 +221,7 @@ def materialize_workspace(out.warnings.append(f"cookbook not found: {cookbook_rel!r}")cookbook_note = "No cookbook is available in this session; rely on the contract below."- body = _body(agent_kind, contract_md, cookbook_note, spatial_tools, list(mcp_command))+ 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))@@ -229,15 +231,6 @@ def materialize_workspace(gemini_settings = ws.root / ".gemini" / "settings.json"_merge_json(gemini_settings, {"context": dict(GEMINI_CONTEXT_SETTINGS)})_drop_server(gemini_settings)- if spatial_tools:- out.codex_overrides = codex_mcp_overrides(list(mcp_command))- out.agy_mcp = (- "Antigravity CLI only supports GLOBAL MCP registration (`agy mcp add ...`), which would "- "leak across parallel runs; no per-workspace MCP is written. The body documents the "- "`python -m codeverse.cli.main tools <name> --json ...` shell fallback instead."- )- else:- out.agy_mcp = "spatial tools disabled"ignore_text = "\n".join(IGNORE_LINES) + "\n"for name in (".geminiignore", ".aiexclude"):diff --git a/harness/codeverse/agents/registry.py b/harness/codeverse/agents/registry.pyindex f784aeac..86be2694 100644--- a/harness/codeverse/agents/registry.py+++ b/harness/codeverse/agents/registry.py@@ -53,8 +53,16 @@ def parse_agent_id(agent_id: str) -> tuple[str, str]:return kind, model-@lru_cache(maxsize=32)def get_coding_agent(agent_id: str) -> CodingAgent:+ """The (metered) CodingAgent for ``<kind>:<model>`` — the same wrap+ ``models.registry.get_chat_model`` gives a chat model."""+ from codeverse.cost.instrument import metered_agent++ return metered_agent(_build_agent(agent_id))+++@lru_cache(maxsize=32)+def _build_agent(agent_id: str) -> CodingAgent:kind, model = parse_agent_id(agent_id)if kind == "gemini-cli":from codeverse.agents.backends import GeminiCliAgentdiff --git a/harness/codeverse/contracts/agent.py b/harness/codeverse/contracts/agent.pyindex 55f00f4b..2e62bf98 100644--- a/harness/codeverse/contracts/agent.py+++ b/harness/codeverse/contracts/agent.py@@ -8,9 +8,7 @@ runtimes, ``agents/cli_common.hardened_env`` for the coding-agent CLIs).from __future__ import annotations-from typing import Any--from pydantic import BaseModel, Field, model_validator+from pydantic import BaseModel, Fieldfrom codeverse.contracts.chat import ImagePartfrom codeverse.contracts.common import Usage@@ -23,17 +21,14 @@ class FileChange(BaseModel):lines_removed: int = 0-#: legacy ``AgentJob.extra`` keys lifted into the typed fields (values stay in extra too)-_LEGACY_JOB_KEYS = ("round", "kind", "language", "track", "files_hint", "mcp_command")--class AgentJob(BaseModel):workspace: strprompt: strsystem_append: str = ""- model: str = ""label: str = ""timeout_s: int = 1800+ #: consumed only by claude-code (``--max-turns``); gemini-cli / codex / agy have no+ #: turn flag and run unbounded except by ``timeout_s`` and the run's wall clockmax_turns: int = 60spatial_tools: bool = Field(default=True, description="expose the 3dcv MCP spatial tools to the agent"@@ -51,8 +46,8 @@ class AgentJob(BaseModel):track: str = Field(default="", description="spec track (spatial tool filtering)")files_hint: list[str] = Field(default_factory=list,- description="workspace-relative files/dirs this task is expected to touch — attributes "- "files_changed between concurrent sessions in one workspace",+ description="workspace-relative files/dirs this task is expected to touch (the "+ "``edit_only`` scope)",)edit_only: bool = Field(default=False,@@ -62,8 +57,9 @@ class AgentJob(BaseModel):)images: list[ImagePart] = Field(default_factory=list,- description="inline images for the FIRST user message (reference photos; the contact sheet the "- "judge scored). Backends without an image channel ignore them; the prompt names the files too.",+ description="images for this task (reference photos; the contact sheet the judge scored). "+ "No vendor CLI takes an image on argv: ``tracks/generation.run_agent_task`` lists their "+ "paths in the prompt for the agent's own file/image tools.",)always_writable: list[str] = Field(default_factory=list,@@ -79,26 +75,6 @@ class AgentJob(BaseModel):mcp_command: list[str] | None = Field(default=None, description="override for the 3dcv MCP server command")- extra: dict[str, Any] = Field(- default_factory=dict, description="one-off backend hints (legacy keys are lifted)"- )-- @model_validator(mode="before")- @classmethod- def _lift_legacy_extra(cls, data: Any) -> Any:- """Constructors that pass ``extra={"round": 2, ...}`` keep working: known keys- are lifted into the typed fields. ``extra`` itself is left untouched so- existing ``job.extra[...]`` readers see exactly what they were given."""- if not isinstance(data, dict):- return data- extra = data.get("extra")- if not isinstance(extra, dict):- return data- data = dict(data) # never mutate the caller's dict- for key in _LEGACY_JOB_KEYS:- if key in extra and key not in data:- data[key] = extra[key]- return dataclass AgentResult(BaseModel):@@ -110,4 +86,8 @@ class AgentResult(BaseModel):usage: Usage = Field(default_factory=Usage)duration_s: float = 0.0tool_calls: int = 0+ turns: int = Field(+ default=0, description="model turns as the backend counts them (claude-code num_turns, codex "+ "turn.completed events, agy num_turns); 0 for gemini-cli, which exposes no turn count",+ )errors: list[str] = Field(default_factory=list)diff --git a/harness/codeverse/cost/__init__.py b/harness/codeverse/cost/__init__.pyindex a22a5c6b..d64a1b89 100644--- a/harness/codeverse/cost/__init__.py+++ b/harness/codeverse/cost/__init__.py@@ -17,7 +17,7 @@ from __future__ import annotationsfrom codeverse.cost.audit import audit_runsfrom codeverse.cost.context import call_contextfrom codeverse.cost.guard import estimate_call, text_tokens-from codeverse.cost.instrument import per_call_metering, run_ledger+from codeverse.cost.instrument import run_ledgerfrom codeverse.cost.ledger import CostLedger, load_ledger, open_run_ledger, record_call, summarisefrom codeverse.cost.reconstruct import find_runs, reconstructfrom codeverse.cost.report import markdown@@ -27,6 +27,6 @@ from codeverse.cost.types import Role, Stage__all__ = ["CostLedger", "Role", "Stage", "audit_runs", "call_context", "default_route","estimate_call", "find_runs", "load_ledger", "markdown", "open_run_ledger",- "per_call_metering", "pro_break_even", "reconstruct", "record_call", "run_ledger",+ "pro_break_even", "reconstruct", "record_call", "run_ledger","summarise", "text_tokens",]diff --git a/harness/codeverse/cost/audit.py b/harness/codeverse/cost/audit.pyindex d200c1cd..031d5e02 100644--- a/harness/codeverse/cost/audit.py+++ b/harness/codeverse/cost/audit.py@@ -174,11 +174,15 @@ def _waste(led: RunLedger, rounds: Sequence[RoundCost]) -> list[WasteItem]:if repair and not led.passed:items.append(WasteItem("repair_no_converge", led.run, sum(r.cost_usd for r in repair),detail=f"{len(repair)} repair call(s) in a run that ended '{led.status}'"))- # best-of-N candidates that lost (their whole sub-workspace is thrown away)+ # best-of-N candidates that lost (their whole sub-workspace is thrown away). Two label+ # forms: a live ledger row is ``baseline_c<k>`` (the candidate clone's label), a+ # reconstructed one ``c<k>:baseline``. Generator sessions only — the quick-judge rows+ # inside a candidate carry no candidate marker on either path.won = led.selected_candidate- losers = [r for r in led.rows if r.stage is Stage.CANDIDATE and not (won and r.label.startswith(f"{won}:"))]+ losers = [r for r in led.rows if r.stage is Stage.CANDIDATE+ and not (won and (r.label.startswith(f"{won}:") or r.label.endswith(f"_{won}")))]if losers:- names = sorted({r.label.split(":", 1)[0] for r in losers})+ names = sorted({_candidate_of(r.label) for r in losers})items.append(WasteItem("lost_candidate", led.run, sum(r.cost_usd for r in losers),detail=f"best-of-N: {', '.join(names)} lost to {won or '(unknown)'}"))# anything spent on a round that finished after the budget was blown@@ -191,6 +195,12 @@ def _waste(led: RunLedger, rounds: Sequence[RoundCost]) -> list[WasteItem]:return items+def _candidate_of(label: str) -> str:+ """``c1:baseline`` → ``c1``; ``baseline_c1`` → ``c1``."""+ head, sep, _ = label.partition(":")+ return head if sep else label.rsplit("_", 1)[-1]++def audit_runs(paths: Iterable[str | Path], *, recheck: bool = False) -> Audit:"""Reconstruct + aggregate every run under ``paths`` (files, run dirs or trees)."""dirs: list[Path] = []diff --git a/harness/codeverse/cost/billing.py b/harness/codeverse/cost/billing.pyindex bc02dc0f..602a589b 100644--- a/harness/codeverse/cost/billing.py+++ b/harness/codeverse/cost/billing.py@@ -2,24 +2,18 @@``Usage.cost_usd`` answers "what would these tokens cost at list price?". That is theright number for a report, a $/complexity-point, or a flywheel record: it is comparable-across backends and it does not depend on who is paying. It is the WRONG number for a-spend guard, because a backend on a local subscription bills no dollars at all.--Conflating the two degraded real runs. Measured 2026-08-25 on-``tsr_scn_temple_night`` (``codex:gpt-5.6-sol``, ``--profile quality``): two Blender hero-sessions priced at OpenAI list rates put the run at $7.712 against the profile's $4.40-soft cap in 6.8 minutes, so the asset judge was skipped for both heroes and every later-stage ran degraded — over a bill of exactly $0.00. The run's own cost ledger agreed it-was $0.00; only the guard disagreed.--So the split is: the LEDGER and the reports keep pricing everything, and the BUDGET-enforces only what is billed. See ``orchestrator/budget.py`` for the enforcement side-and ``docs/COST.md`` §25.--What a subscription backend is still bounded by: ``max_minutes``, which-``BudgetMeter.timeout_s`` also clips individual sessions against. Wall clock, not money,-is the scarce resource when the money is flat-rate — a runaway session is still stopped,-just by the ceiling that actually applies to it.+across backends and it does not depend on who is paying. It is the WRONG number for+"what did this run bill", because a backend on a local subscription bills no dollars at+all — measured 2026-08-25 on ``tsr_scn_temple_night`` (``codex:gpt-5.6-sol``): two+Blender hero sessions priced at OpenAI list rates read as $7.712 over a bill of exactly+$0.00 (docs/COST.md §25).++So the split is: the LEDGER and the reports price everything, and :func:`bills_usd`+shapes the BILLED figure — ``BudgetGuard.billed_usd`` (``record.json`` / the report's+``spent_usd`` beside ``notional_usd``) and the resume reconcile in+``tracks/lifecycle.py``. Nothing enforces a dollar ceiling any more (removed in+fbf89a5); the only ceiling is ``max_minutes``, which ``BudgetGuard.timeout_s`` also+clips individual sessions against."""from __future__ import annotations@@ -35,7 +29,6 @@ def bills_usd(backend: str | None) -> bool:"""True when this backend's ``cost_usd`` is money someone is actually charged.Unknown backends bill: a new API provider that nobody remembered to classify must be- enforced, not exempted. Getting this wrong in the safe direction costs a degraded- run; getting it wrong in the other direction spends real money with no ceiling.+ reported as spend, not exempted."""return (backend or "").strip().lower() not in SUBSCRIPTION_BACKENDSdiff --git a/harness/codeverse/cost/context.py b/harness/codeverse/cost/context.pyindex b45763d1..03965f77 100644--- a/harness/codeverse/cost/context.py+++ b/harness/codeverse/cost/context.py@@ -13,9 +13,9 @@ role" for the call that is about to happen. Precedence:under the session's ``stage=refine / role=generator``;3. the ambient context (:func:`call_context`) — set by:mod:`codeverse.cost.instrument` around an agent session. It beats a- *generation* label because the session knows more than one of its turns does:- a best-of-N candidate runs with ``job.kind="candidate"`` while its turns are- labelled ``api-agent:baseline:t3``;+ *generation* label because the session knows more than a call made inside it+ does: a best-of-N candidate session runs with ``job.kind="candidate"`` while a+ tool it calls bills a model under a plain ``baseline`` label;4. what is left of the label (a generation stage, the round tag) — which alsosurvives a thread hop that a ``ContextVar`` does not.@@ -163,21 +163,14 @@ _LABEL_HINTS: tuple[tuple[str, Stage, Role], ...] = (def context_from_label(label: str) -> CallContext:- """Best-effort attribution from a ``ChatRequest.label``.-- Understands the api-agent's ``api-agent:<job label>:t<turn>`` form (the job- label carries the stage) and the judge's ``…:r<NN>:s<k>`` round tag."""+ """Best-effort attribution from a ``ChatRequest.label``: its head names the job+ (``judge:…``, ``texture_plan``, a generation stage) and the judge's+ ``…:r<NN>:s<k>`` tag carries the round."""low = (label or "").strip()if not low:return _EMPTYround_index = _round_from_label(low)- body = low- if low.startswith("api-agent:"):- parts = low.split(":")- body = parts[1] if len(parts) > 1 else ""- return CallContext(round=round_index, stage=_stated(stage_for_label(body)),- role=Role.GENERATOR, label=low)- head = body.split(":", 1)[0].lower()+ head = low.split(":", 1)[0].lower()best: tuple[int, Stage, Role] | None = Nonefor prefix, stage, role in _LABEL_HINTS:if head.startswith(prefix) and (best is None or len(prefix) > best[0]):@@ -240,7 +233,7 @@ class AttemptRecord:attempt: int #: 1-based issue order within the logical callkey: str #: the full API key that served it; the ledger keeps only its last 4 chars- outcome: str #: KeyPool vocabulary: ok | 429 | 5xx | error | dead+ outcome: str #: the KeyPool report vocabulary (``models.retry``): ok | 429 | 5xx | error | dead, plus whatever the pool addsdiscarded: bool #: True for every round-trip that is not the winning oneusage: Usage #: what the provider billed for THIS round-triperror: str = "" #: str(ModelError) when the round-trip faileddiff --git a/harness/codeverse/cost/guard.py b/harness/codeverse/cost/guard.pyindex 7cd0f435..12603c47 100644--- a/harness/codeverse/cost/guard.py+++ b/harness/codeverse/cost/guard.py@@ -1,8 +1,8 @@"""Estimate what a call will cost **before** sending it, and pick a tier.-The budget guard in ``orchestrator/budget.py`` stops a run *after* the money is-gone. This is the cheap estimate that belongs in front of a call: how many-tokens am I about to send, and what will they cost on this model?+``orchestrator.BudgetGuard`` accounts for money *after* it is spent (and stops a+run only on wall clock). This is the cheap estimate that belongs in front of a+call: how many tokens am I about to send, and what will they cost on this model?Token counts are estimates (≈4 characters per token for prose/code, a flatper-image count for vision parts) — good to ±15% for prompt sizing, which is alldiff --git a/harness/codeverse/cost/instrument.py b/harness/codeverse/cost/instrument.pyindex 1e0591c3..4da013cb 100644--- a/harness/codeverse/cost/instrument.py+++ b/harness/codeverse/cost/instrument.py@@ -10,10 +10,10 @@ Two thin proxies do the whole job:generation.* :class:`MeteredAgent` wraps a :class:`~codeverse.agents.registry.CodingAgent`.It sets the ambient attribution (round / stage / label) for the session so- the model rows above land in the right bucket, applies the profile's turn cap- and, for backends whose calls we cannot see (every subscription CLI that does- not declare ``meters_own_calls``), records one session row from- ``AgentResult.usage``.+ the model rows above land in the right bucket and, for backends whose calls we+ cannot see (every subscription CLI that does not declare ``meters_own_calls``),+ records one session row from ``AgentResult.usage``. ``agents.registry+ .get_coding_agent`` returns the proxy.Accounting is never allowed to fail a run: every hook is wrapped, and anexception in the ledger is logged and swallowed. The proxies forward every@@ -24,11 +24,9 @@ sees the real object's.from __future__ import annotationsimport logging-import threadingimport timefrom collections.abc import Iteratorfrom contextlib import contextmanager-from contextvars import ContextVarfrom pathlib import Pathfrom typing import Anyfrom uuid import uuid4@@ -56,30 +54,6 @@ from codeverse.cost.types import Role, Stage, stage_for_labellog = logging.getLogger(__name__)-#: True while a run is metered call-by-call (:func:`run_ledger`). Any aggregate-#: writer that appends one row per *charge* must not also write, or every dollar-#: lands in the ledger twice.-#:-#: Context-local first, with a process-wide **count** of the open run ledgers as-#: the fallback for a worker thread that inherited no context. A plain global-#: boolean cannot survive ``bench.run_bench --parallel N``: two threads entering-#: and leaving their own ledgers interleave, and the second one restores "on"-#: after the first turned it off.-_per_call_var: ContextVar[bool | None] = ContextVar("cv3d_cost_per_call", default=None)-_active_lock = threading.Lock()-_active_ledgers = 0---def per_call_metering() -> bool:- """True when every model call of the current run is already written to the- ledger one by one, so a coarser writer should skip its own row."""- local = _per_call_var.get()- if local is not None:- return local- with _active_lock:- return _active_ledgers > 0--def meters_own_calls(agent: Any) -> bool:"""True when this backend's individual model calls are already on the ledger.@@ -208,18 +182,11 @@ def _outcome(exc: BaseException) -> str:class MeteredAgent:- """CodingAgent proxy: attribution for the session + a turn-cap backstop.-- ``tracks.generation.agent_max_turns`` is where the cap is *decided* (it reads- ``Settings.limits.agent_max_turns`` and handles the wrap-up continuation).- There is no default cap — a 28-turn one lost its A/B, ``docs/COST.md`` §17 —- so this is only a backstop for a caller that names one: a bench script, a- test, ``$CV3D_AGENT_MAX_TURNS``. It only ever *lowers* ``job.max_turns``, so- it composes with whatever the caller set."""+ """CodingAgent proxy: attribution for the session + its one ledger row. The+ job runs as given — the turn cap is decided in ``tracks.generation``."""- def __init__(self, inner: Any, *, max_turns: int | None = None):+ def __init__(self, inner: Any):self._inner = inner- self.max_turns = max_turns@propertydef kind(self) -> str:@@ -243,7 +210,6 @@ class MeteredAgent:return f"MeteredAgent({self._inner!r})"def run(self, job: AgentJob) -> AgentResult:- job = self._capped(job)stage = stage_for_label(job.kind or job.label)t0 = time.perf_counter()with call_context(round=job.round, stage=stage, role=Role.GENERATOR, label=job.label):@@ -252,12 +218,6 @@ class MeteredAgent:self._record_session(job, result, stage, int((time.perf_counter() - t0) * 1000))return result- def _capped(self, job: AgentJob) -> AgentJob:- cap = self.max_turns if self.max_turns is not None else _settings_turn_cap()- if cap and 0 < cap < job.max_turns:- return job.model_copy(update={"max_turns": cap})- return job-def _record_session(self, job: AgentJob, result: AgentResult, stage: Stage, ms: int) -> None:usage = result.usageif not (usage.input_tokens or usage.output_tokens or usage.cost_usd):@@ -272,15 +232,6 @@ class MeteredAgent:log.debug("cost: could not record agent session %s: %s", job.label, e)-def _settings_turn_cap() -> int:- try:- from codeverse.config import get_settings-- return int(get_settings().limits.agent_max_turns)- except Exception: # pragma: no cover - settings must never break a run- return 0--# --------------------------------------------------------------------------- factoriesdef metered_chat_model(model: Any) -> Any:"""Wrap ``model`` unless it is already metered or metering is off."""@@ -305,51 +256,14 @@ def metering_enabled() -> bool:return True-# --------------------------------------------------------------------------- agent seam-_install_lock = threading.Lock()-_installed = False---def install_agent_metering() -> bool:- """Make ``get_coding_agent`` hand out metered agents (idempotent).-- The agent package builds its backends through one factory, so wrapping that- factory is the whole integration; when ``agents/registry.py`` starts calling- :func:`metered_agent` itself this seam becomes a no-op."""- global _installed- with _install_lock:- if _installed:- return False- try:- import codeverse.agents as agents_pkg- from codeverse.agents import registry as agents_registry- except Exception as e: # pragma: no cover - agents are optional for cost-only use- log.debug("cost: agent metering unavailable: %s", e)- return False- inner = agents_registry.get_coding_agent- if getattr(inner, "_cv3d_metered", False):- _installed = True- return False-- def get_coding_agent(agent_id: str) -> Any:- return metered_agent(inner(agent_id))-- get_coding_agent._cv3d_metered = True # type: ignore[attr-defined]- get_coding_agent.__doc__ = inner.__doc__- agents_registry.get_coding_agent = get_coding_agent # type: ignore[assignment]- agents_pkg.get_coding_agent = get_coding_agent # type: ignore[attr-defined]- _installed = True- return True--# --------------------------------------------------------------------------- run activation@contextmanagerdef run_ledger(workspace: str | Path, *, run: str = "", create: bool = True) -> Iterator[CostLedger | None]:"""Meter one run into ``<workspace>/telemetry/cost.jsonl``.- Binds the run name, points :func:`~codeverse.cost.ledger.record_call` at the- run's ledger and installs the agent seam; restores the previous default on- the way out so a second run in the same process is not mixed in.+ Binds the run name and points :func:`~codeverse.cost.ledger.record_call` at the+ run's ledger; restores the previous default on the way out so a second run in+ the same process is not mixed in.``create=False`` is for work done *after* a run finished (``3dcv judge``,a post-hoc texture pass): it appends only when the run already keeps a@@ -365,11 +279,9 @@ def run_ledger(workspace: str | Path, *, run: str = "", create: bool = True) ->if not metering_enabled():yield Nonereturn- global _active_ledgersws = Path(workspace)prev_run = run_binding().runprev_path = default_ledger_path()- prev_metering = _per_call_var.get()if not create and existing_ledger_path(ws) is None:bind_run(run or ws.name)try:@@ -380,19 +292,12 @@ def run_ledger(workspace: str | Path, *, run: str = "", create: bool = True) ->ledger = open_run_ledger(ws)set_default_ledger(ledger.path)bind_run(run or ws.name)- install_agent_metering()- _per_call_var.set(True)- with _active_lock:- _active_ledgers += 1try:yield ledgerfinally:- _per_call_var.set(prev_metering)- with _active_lock:- _active_ledgers -= 1set_default_ledger(prev_path)bind_run(prev_run)-__all__ = ["MeteredAgent", "MeteredChatModel", "install_agent_metering", "metered_agent",- "metered_chat_model", "metering_enabled", "per_call_metering", "run_ledger"]+__all__ = ["MeteredAgent", "MeteredChatModel", "metered_agent", "metered_chat_model",+ "metering_enabled", "run_ledger"]diff --git a/harness/codeverse/cost/reconstruct.py b/harness/codeverse/cost/reconstruct.pyindex 45b94e03..eb872630 100644--- a/harness/codeverse/cost/reconstruct.py+++ b/harness/codeverse/cost/reconstruct.py@@ -197,7 +197,9 @@ def _session_rows(d: Path, run: str, *, recheck: bool,reprice=recheck))return rows, label, rnd, durationif session.input_tokens or session.output_tokens or session.cost_usd:- n_calls = int(result.get("turns") or 0) or 1+ # ``turns`` is AgentResult.turns (since 2026-08-29); older vendor result.json files+ # carry only the backend's own key (claude / agy ``num_turns``, codex ``turns_completed``)+ n_calls = int(result.get("turns") or result.get("num_turns") or result.get("turns_completed") or 0) or 1rows.append(_row(session, run=run, stage=stage, label=label, rnd=rnd, source="trajectory",outcome=outcome, n_calls=n_calls, reprice=recheck))return rows, label, rnd, durationdiff --git a/harness/codeverse/cost/types.py b/harness/codeverse/cost/types.pyindex 84ebfb09..955fbcd9 100644--- a/harness/codeverse/cost/types.py+++ b/harness/codeverse/cost/types.py@@ -52,6 +52,20 @@ class Role(StrEnum):OTHER = "other"+#: a bare ``GenerationTask.kind`` whose money belongs to a differently-named stage. ONE+#: vocabulary for both spend paths: ``MeteredAgent.run`` files the session row by+#: ``job.kind`` and ``tracks.generation.task_stage`` buckets the guard by the same kind —+#: until 2026-08-29 only the tracks side knew these, so every scene zone / compose /+#: asset / rebuild session landed in the ledger as ``other``.+_KIND_STAGES: dict[str, Stage] = {+ "generate": Stage.BASELINE,+ "rebuild": Stage.REPAIR,+ "asset": Stage.ASSETS,+ "asset_fix": Stage.ASSETS,+ "zone": Stage.ZONES,+ "compose": Stage.ASSEMBLE,+}+#: label prefix → stage, longest prefix wins (``asset_stone_lantern`` → assets)_LABEL_STAGES: tuple[tuple[str, Stage], ...] = (("asset_", Stage.ASSETS),@@ -69,11 +83,14 @@ _LABEL_STAGES: tuple[tuple[str, Stage], ...] = (def stage_for_label(label: str) -> Stage:- """Map a generation/trajectory label (``refine_drip_tray``, ``r00_baseline_repair1``,- ``asset_koi``) to its :class:`Stage`. Repair labels win over the label they repair."""+ """Map a task kind or a generation/trajectory label (``zone``, ``refine_drip_tray``,+ ``r00_baseline_repair1``, ``asset_koi``) to its :class:`Stage`. A bare kind or+ stage name wins outright; repair labels win over the label they repair."""low = (label or "").strip().lower()if not low:return Stage.OTHER+ if low in _KIND_STAGES:+ return _KIND_STAGES[low]if "repair" in low:return Stage.REPAIRbest: tuple[int, Stage] | None = Nonediff --git a/harness/tests/agents/conftest.py b/harness/tests/agents/conftest.pyindex 8fe8ac0c..c64b6ae8 100644--- a/harness/tests/agents/conftest.py+++ b/harness/tests/agents/conftest.py@@ -33,7 +33,7 @@ def fake_bin(tmp_path: Path):@pytest.fixturedef scoped_ws(tmp_ws):"""A workspace with an entry file and two part files — the tree every write-scope- test (CLI post-hoc restore and in-process FileTools alike) needs."""+ test (the CLI post-hoc restore and the single-shot envelope alike) needs."""(tmp_ws.src / "parts").mkdir(parents=True, exist_ok=True)(tmp_ws.src / "model.py").write_text("# entry\n")(tmp_ws.src / "parts" / "seat.py").write_text("# seat\n")diff --git a/harness/tests/agents/test_agent_job_wiring.py b/harness/tests/agents/test_agent_job_wiring.pynew file mode 100644index 00000000..c06584fa--- /dev/null+++ b/harness/tests/agents/test_agent_job_wiring.py@@ -0,0 +1,66 @@+"""What ``tracks.generation.run_agent_task`` hands a CodingAgent: the task's images as a+prompt section, a hard-clock session window, the backend's turn count."""++from __future__ import annotations++from codeverse.contracts.agent import AgentJob, AgentResult+from codeverse.contracts.chat import ImagePart+from codeverse.contracts.common import Budget, Usage+from codeverse.orchestrator import BudgetGuard+from codeverse.tracks.generation import GenerationTask, run_agent_task+from codeverse.workspace import Workspace+++class StubAgent:+ kind, model = "stub", "m"++ def __init__(self, turns: int = 0):+ self.jobs: list[AgentJob] = []+ self.turns = turns++ def run(self, job: AgentJob) -> AgentResult:+ self.jobs.append(job)+ ws = Workspace(job.workspace)+ (ws.src / "a.txt").write_text("x\n")+ return AgentResult(ok=True, exit_reason="completed", turns=self.turns,+ usage=Usage(backend="stub", input_tokens=10, cost_usd=0.01))+++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 the+ reference 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``."""+ sheet = tmp_path / "contact_sheet.png"+ sheet.write_bytes(b"png")+ task = GenerationTask(label="refine", prompt="fix the horn", round=1, kind="refine",+ images=[ImagePart(path=str(sheet), label="the contact sheet the judge scored (round 0)"),+ ImagePart(path="/refs/photo.jpg", label="reference (target)")])+ agent = StubAgent()+ run_agent_task(tmp_ws, agent=agent, task=task)+ (job,) = agent.jobs+ assert job.prompt.startswith("fix the horn") and "## Images for this task" in job.prompt+ assert "`.3dcv/images/00_contact_sheet.png`" in job.prompt+ assert (tmp_ws.root / ".3dcv/images/00_contact_sheet.png").read_bytes() == b"png"+ # an unreadable source is still named, never silently dropped+ assert "reference (target): `/refs/photo.jpg`" in job.prompt+ assert job.images and job.images[0].path == str(sheet)+ 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].prompt+++def test_session_window_is_clipped_to_the_hard_clock_not_the_soft_share(tmp_ws: Workspace):+ """A scene refine asks for its window with soft=False (after the 0.55 soft share is+ spent); re-clipping it against the SOFT share handed it the 120 s floor (2026-08-29)."""+ guard = BudgetGuard(Budget(max_minutes=100), soft_fraction=0.5)+ guard.start_time -= 60 * 60 # 60 of 100 minutes gone: the soft share is spent, 40 min remain+ assert guard.soft_remaining()["minutes"] == 0+ agent = StubAgent()+ run_agent_task(tmp_ws, agent=agent, task=GenerationTask(label="refine", prompt="p", timeout_s=900), budget=guard)+ assert agent.jobs[0].timeout_s == 900+++def test_turns_come_from_the_typed_result(tmp_ws: Workspace):+ res = run_agent_task(tmp_ws, agent=StubAgent(turns=7), task=GenerationTask(label="baseline", prompt="p"))+ assert res.turns == 7diff --git a/harness/tests/agents/test_claude_code.py b/harness/tests/agents/test_claude_code.pyindex 7d14e34d..1abd1182 100644--- a/harness/tests/agents/test_claude_code.py+++ b/harness/tests/agents/test_claude_code.py@@ -100,6 +100,7 @@ def test_fake_run_success_and_error(tmp_ws: Workspace, fake_bin, monkeypatch):res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="c", system_append="SYS", timeout_s=30))assert res.ok and res.exit_reason == "completed", res.errorsassert res.text.endswith("sys=SYS") and res.usage.cost_usd == 0.0123 and res.tool_calls == 2+ assert res.turns == 3 # the envelope's num_turns, in the typed resultassert [f.path for f in res.files_changed] == ["src/hello.txt"]rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())assert rec["num_turns"] == 3 and rec["session_id"] == "abc"diff --git a/harness/tests/agents/test_cli_common.py b/harness/tests/agents/test_cli_common.pyindex 5e80cefa..6c09e760 100644--- a/harness/tests/agents/test_cli_common.py+++ b/harness/tests/agents/test_cli_common.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport jsonimport os-import threadingfrom codeverse.agents.cli_common import (Trajectory,@@ -39,7 +38,7 @@ def test_hardened_env_strips_secrets_and_adds_guards(tmp_ws: Workspace, monkeypadef test_session_roundtrip_tracks_files_and_writes_result(tmp_ws: Workspace):- job = AgentJob(workspace=str(tmp_ws.root), prompt="do it", label="baseline", extra={"round": 2})+ job = AgentJob(workspace=str(tmp_ws.root), prompt="do it", label="baseline", round=2)s = begin_session(job, "fake")assert s.traj.dir.name == "baseline_r02" and s.traj.prompt_path.read_text() == "do it"(tmp_ws.src / "model.py").write_text("print(1)\n")@@ -53,7 +52,7 @@ def test_session_roundtrip_tracks_files_and_writes_result(tmp_ws: Workspace):def test_retry_same_label_round_keeps_first_attempt_trajectory(tmp_ws: Workspace):"""run_agent_task re-runs a silently-bailing job with the same label+round: attempt 1's files must survive."""- job = AgentJob(workspace=str(tmp_ws.root), prompt="first", label="baseline", extra={"round": 0})+ job = AgentJob(workspace=str(tmp_ws.root), prompt="first", label="baseline", round=0)s1 = begin_session(job, "fake")s1.traj.write_text("stdout.json", "attempt 1 stdout")r1 = finish_session(s1, ok=False, exit_reason="error", text="", usage=Usage(cost_usd=0.5), errors=["bailed"])@@ -77,41 +76,7 @@ def test_attribute_changes_pure():"trajectories/zone_a_r00/result.json", "public/assets/y.glb", "README.md", "AGENTS.md")]got = attribute_changes(files, write_roots=["src", "public"])assert [f.path for f in got] == ["src/zones/a.js", "src/zones/b.js", "src/assets/x.js", "public/assets/y.glb"]- got = attribute_changes(files, write_roots=["src", "public"], own_hints=frozenset({"src/zones/a.js"}),- sibling_hints=frozenset({"src/zones/b.js", "src/assets/"}))- assert [f.path for f in got] == ["src/zones/a.js", "public/assets/y.glb"]- # a file both sessions declared stays attributed to both- got = attribute_changes(files, write_roots=["src"], own_hints=frozenset({"src/zones/b.js"}), sibling_hints=frozenset({"src/zones/b.js"}))- assert "src/zones/b.js" in [f.path for f in got]---def test_concurrent_sessions_in_one_workspace_attribute_their_own_files(tmp_ws: Workspace):- """Scene fan-out: zone sessions run in parallel in ONE workspace; each result must list only its own work- and a session that wrote nothing must report no changes even though siblings wrote files."""- (tmp_ws.src / "zones").mkdir(parents=True)- barrier = threading.Barrier(3)- results = {}-- def session(name: str, write: bool):- job = AgentJob(workspace=str(tmp_ws.root), prompt="p", label=f"zone_{name}",- extra={"round": 0, "files_hint": [f"src/zones/{name}.js"]})- s = begin_session(job, "fake")- barrier.wait(timeout=30) # every session has started before anyone writes- if write:- (tmp_ws.src / "zones" / f"{name}.js").write_text(f"// {name}\n")- (tmp_ws.root / "events.jsonl").open("a").write(f"{name}\n")- barrier.wait(timeout=30) # every write landed before anyone finishes- results[name] = finish_session(s, ok=True, exit_reason="completed", text="", usage=Usage())-- threads = [threading.Thread(target=session, args=("koi", True)), threading.Thread(target=session, args=("gravel", True)),- threading.Thread(target=session, args=("lantern", False))]- for t in threads:- t.start()- for t in threads:- t.join(timeout=60)- assert [f.path for f in results["koi"].files_changed] == ["src/zones/koi.js"]- assert [f.path for f in results["gravel"].files_changed] == ["src/zones/gravel.js"]- assert results["lantern"].files_changed == [] # bailed agent: siblings' files are not its work+ assert [f.path for f in attribute_changes(files, write_roots=["public"])] == ["public/assets/y.glb"]def test_deliver_prompt_uses_file_when_long(tmp_ws: Workspace):@@ -146,10 +111,10 @@ def test_mcp_command_resolution(tmp_ws: Workspace):from codeverse.agents.cli_common import default_mcp_command, mcp_command_forfrom codeverse.agents.materialize import materialize_workspace- job = AgentJob(workspace=str(tmp_ws.root), prompt="p", extra={"language": "blender", "track": "static_object", "round": 2})+ job = AgentJob(workspace=str(tmp_ws.root), prompt="p", language="blender", track="static_object", round=2)cmd = mcp_command_for(tmp_ws, job)assert cmd[1:3] == ["-m", "codeverse.spatial.mcp_server"] and "--language" in cmd and cmd[cmd.index("--round") + 1] == "2"- job2 = AgentJob(workspace=str(tmp_ws.root), prompt="p", extra={"mcp_command": ["python", "-m", "x"]})+ job2 = AgentJob(workspace=str(tmp_ws.root), prompt="p", mcp_command=["python", "-m", "x"])assert mcp_command_for(tmp_ws, job2) == ["python", "-m", "x"]# a workspace .mcp.json NEVER wins: the agent works in that directory and could# otherwise choose what the next round's CLI launches (audit 2026-08-27)diff --git a/harness/tests/agents/test_cli_write_scope.py b/harness/tests/agents/test_cli_write_scope.pyindex 67c91ed2..5f01e595 100644--- a/harness/tests/agents/test_cli_write_scope.py+++ b/harness/tests/agents/test_cli_write_scope.py@@ -21,7 +21,7 @@ from codeverse.workspace import Workspacedef _job(ws: Workspace, label: str, **kw) -> AgentJob:- return AgentJob(workspace=str(ws.root), prompt="p", label=label, extra={"round": 0}, **kw)+ return AgentJob(workspace=str(ws.root), prompt="p", label=label, round=0, **kw)def _finish(s, *, ok: bool = True):diff --git a/harness/tests/agents/test_codex.py b/harness/tests/agents/test_codex.pyindex 9fab89fe..79b51b07 100644--- a/harness/tests/agents/test_codex.py+++ b/harness/tests/agents/test_codex.py@@ -96,6 +96,8 @@ def test_fake_run(tmp_ws: Workspace, fake_bin, monkeypatch):assert res.ok and res.exit_reason == "completed" and res.text == "Done." and res.tool_calls == 2, res.errorsassert [f.path for f in res.files_changed] == ["src/hello.txt"]assert res.usage.input_tokens == 1000+ # the turn count lands in the TYPED result (one turn.completed event), not only in result.json+ assert res.turns == 1 == json.loads((Path(res.transcript_path).parent / "result.json").read_text())["turns"]assert (Path(res.transcript_path).parent / "stdout.jsonl").exists()monkeypatch.setenv("FAKE_MODE", "fail")res2 = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="hello", label="y", timeout_s=30))@@ -114,15 +116,18 @@ def test_live_codex_mcp_tool_call_is_not_cancelled(tmp_ws: Workspace):"""Regression: without default_tools_approval_mode=approve codex auto-cancels every 3dcv MCP call."""if not shutil.which("codex"):pytest.skip("codex not installed")+ import trimesh+from codeverse.agents.cli_common import default_mcp_commandfrom codeverse.agents.materialize import materialize_workspace+ trimesh.creation.box().export(tmp_ws.artifacts / "object.glb")materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", cookbook_rel="threejs/cookbook.md", spatial_tools=True,mcp_command=default_mcp_command(tmp_ws, language="threejs"))a = CodexAgent("")- res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="Call the 3dcv MCP tool `read_cookbook` once and reply with its first "- "five words, then DONE. Do not edit files.", timeout_s=300, label="mcpt", spatial_tools=True,- extra={"language": "threejs"}))+ res = a.run(AgentJob(workspace=str(tmp_ws.root), prompt="Call the 3dcv MCP tool `measure` exactly once, then reply with the "+ "measured part count and DONE. Do not edit files.", timeout_s=300, label="mcpt",+ spatial_tools=True, language="threejs"))assert res.ok, res.errorsevents = [json.loads(ln) for ln in (Path(res.transcript_path).parent / "stdout.jsonl").read_text().splitlines()if ln.startswith("{")]diff --git a/harness/tests/agents/test_gemini_cli.py b/harness/tests/agents/test_gemini_cli.pyindex 384349e3..942725ae 100644--- a/harness/tests/agents/test_gemini_cli.py+++ b/harness/tests/agents/test_gemini_cli.py@@ -206,6 +206,8 @@ def test_unavailable_when_no_keys(tmp_ws: Workspace, agent: GeminiCliAgent, monkdef test_parse_helpers():assert parse_gemini_json("noise\n{\"response\": \"x\"}") == {"response": "x"}assert parse_gemini_json("") is None+ # the CLI prints the envelope INDENTED over many lines (a single-line scan finds nothing)+ assert parse_gemini_json('log line\n{\n "response": "x",\n "stats": {\n "models": {}\n }\n}\n')["response"] == "x"# no `prompt` key: total prompt = uncached input + cachedu = usage_from_stats({"models": {"m": {"tokens": {"input": 1, "candidates": 2, "cached": 3, "thoughts": 4}}},"tools": {"totalCalls": 9}}, "m")diff --git a/harness/tests/agents/test_materialize.py b/harness/tests/agents/test_materialize.pyindex 0e977775..5f009df2 100644--- a/harness/tests/agents/test_materialize.py+++ b/harness/tests/agents/test_materialize.py@@ -3,8 +3,7 @@from __future__ import annotationsimport json--import pytest+import sysfrom codeverse.agents.cli_common import default_mcp_commandfrom codeverse.agents.materialize import CV3D_DIR, codex_mcp_overrides, materialize_workspace@@ -36,14 +35,11 @@ def test_no_mcp_server_is_written_into_the_workspace(tmp_ws: Workspace):gs = tmp_ws.root / ".gemini" / "settings.json"gs.parent.mkdir(parents=True)gs.write_text(json.dumps({"mcpServers": {"3dcv": {"command": "/tmp/evil"}}, "ui": {"theme": "dark"}}))- res = _mat(tmp_ws)+ _mat(tmp_ws)data = json.loads(gs.read_text())assert data["ui"]["theme"] == "dark"assert "3dcv" not in data["mcpServers"], "an agent-planted 3dcv impostor must be dropped"assert not (tmp_ws.root / ".mcp.json").exists(), "claude-code writes its own per-session mcp.json"- assert res.codex_overrides[1].startswith("mcp_servers.3dcv.command=")- assert "mcp_servers.3dcv.args=[" in res.codex_overrides[3]- assert "global" in res.agy_mcp.lower()assert data["context"]["fileFiltering"]["respectGitIgnore"] is False # .gitignore hides artifacts/ + trajectories/@@ -80,8 +76,7 @@ def test_ignore_files_keep_agent_facing_paths_readable(tmp_ws: Workspace):def test_spatial_disabled_drops_server_and_documents_absence(tmp_ws: Workspace):_mat(tmp_ws)- res = _mat(tmp_ws, spatial=False)- assert res.codex_overrides == []+ _mat(tmp_ws, spatial=False)assert "3dcv" not in json.loads((tmp_ws.root / ".gemini" / "settings.json").read_text()).get("mcpServers", {})assert "No spatial tools are available" in (tmp_ws.root / "AGENTS.md").read_text()@@ -118,6 +113,9 @@ def test_codex_overrides_are_valid_toml_fragments():assert keys["mcp_servers.3dcv.default_tools_approval_mode"] == '"approve"'-def test_spatial_requires_mcp_command(tmp_ws: Workspace):- with pytest.raises(ValueError):- materialize_workspace(tmp_ws, agent_kind="codex", contract_md="c", cookbook_rel="", spatial_tools=True, mcp_command=[])+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()diff --git a/harness/tests/cost/test_context.py b/harness/tests/cost/test_context.pyindex e80f7812..c3ff6535 100644--- a/harness/tests/cost/test_context.py+++ b/harness/tests/cost/test_context.py@@ -14,8 +14,9 @@ from codeverse.cost.types import Role, Stagedef test_label_tells_stage_role_and_round():- c = context_from_label("api-agent:refine_drip_tray:t7")- assert c.stage is Stage.REFINE and c.role is Role.GENERATOR+ c = context_from_label("refine_drip_tray")+ assert c.stage is Stage.REFINE and c.role is None # a generation label states no role...+ assert attribute(label="refine_drip_tray").role is Role.GENERATOR # ...the stage derives itc = context_from_label("judge:static_object_v1:r02:s1")assert c.stage is Stage.JUDGE and c.role is Role.JUDGE and c.round == 2assert context_from_label("planner-retry").stage is Stage.PLAN@@ -26,16 +27,16 @@ def test_label_tells_stage_role_and_round():def test_repair_label_wins_over_the_label_it_repairs():- assert context_from_label("api-agent:baseline_repair1:t0").stage is Stage.REPAIR+ assert context_from_label("baseline_repair1").stage is Stage.REPAIRdef test_a_generation_label_yields_to_the_session_and_explicit_beats_both():- # best-of-N: the session knows it is a candidate, its turns only say "baseline"+ # best-of-N: the session knows it is a candidate, a call inside it only says "baseline"with call_context(round=3, stage=Stage.CANDIDATE, label="cand_c1"):- got = attribute(label="api-agent:baseline:t0")+ got = attribute(label="baseline")assert got.stage is Stage.CANDIDATE and got.round == 3- assert got.label == "api-agent:baseline:t0" # the most specific label is kept- forced = attribute(CallContext(stage=Stage.REPAIR, round=9), label="api-agent:baseline:t0")+ assert got.label == "baseline" # the most specific label is kept+ forced = attribute(CallContext(stage=Stage.REPAIR, round=9), label="baseline")assert forced.stage is Stage.REPAIR and forced.round == 9diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.pyindex 6e0c85ad..f751f27f 100644--- a/harness/tests/cost/test_instrument.py+++ b/harness/tests/cost/test_instrument.py@@ -12,7 +12,6 @@ from codeverse.contracts.common import Usagefrom codeverse.cost.instrument import (MeteredAgent,MeteredChatModel,- per_call_metering,run_ledger,)from codeverse.cost.ledger import load_ledger@@ -49,10 +48,7 @@ class FakeChat:class FakeAgent:- """A backend whose individual model calls already reach the ledger. Until- 2026-08-28 the in-process ``api-agent`` was the only one and the KIND decided;- every shipped backend is a vendor CLI now, so a self-metering backend declares- itself with ``meters_own_calls`` — that seam is what these tests pin."""+ """A backend whose individual calls already reach the ledger."""kind = "self-metering"meters_own_calls = True@@ -118,21 +114,28 @@ def test_a_cli_agent_we_cannot_see_inside_gets_one_session_row(tmp_path: Path):assert row.stage is Stage.BASELINE and row.round == 0 and row.input_tokens == 50_000-def test_the_turn_cap_only_ever_lowers(tmp_path: Path):- agent = FakeAgent(MeteredChatModel(FakeChat()))- job = AgentJob(workspace=str(tmp_path), prompt="p", label="baseline", max_turns=60)- MeteredAgent(agent, max_turns=20).run(job)- assert agent.seen_turns == 20- MeteredAgent(agent, max_turns=90).run(job)- assert agent.seen_turns == 60 # a bigger cap never raises the caller's own+def test_a_session_row_is_filed_by_the_task_kind(tmp_path: Path):+ """``job.kind`` is a bare task kind (``zone``, ``compose``, ``rebuild``); until 2026-08-29+ only the label PREFIXES were known here, so every scene zone session was ``other``."""+ with run_ledger(tmp_path, run="r1"):+ for kind, label in (("zone", "zone_courtyard"), ("compose", "compose"), ("rebuild", "rebuild"),+ ("asset", "asset_koi"), ("candidate", "baseline_c1")):+ MeteredAgent(CliAgent(FakeChat())).run(+ AgentJob(workspace=str(tmp_path), prompt="p", label=label, round=0, kind=kind))+ assert [r.stage for r in load_ledger(tmp_path)] == [Stage.ZONES, Stage.ASSEMBLE, Stage.REPAIR,+ Stage.ASSETS, Stage.CANDIDATE]+++def test_get_coding_agent_hands_out_a_metered_agent(monkeypatch: pytest.MonkeyPatch):+ from codeverse.agents import registry++ monkeypatch.setattr(registry, "_build_agent", lambda aid: CliAgent(FakeChat()))+ assert isinstance(registry.get_coding_agent("gemini-cli:m"), MeteredAgent)def test_run_ledger_writes_telemetry_and_leaves_a_root_alias(tmp_path: Path):- assert per_call_metering() is Falsewith run_ledger(tmp_path, run="r1"):- assert per_call_metering() is TrueMeteredChatModel(FakeChat()).generate(ChatRequest(messages=[ChatMessage.user("x")], label="planner"))- assert per_call_metering() is Falseassert (tmp_path / "telemetry" / "cost.jsonl").is_file()alias = tmp_path / "cost_ledger.jsonl"assert alias.is_symlink() and alias.is_file() # resolves to the telemetry copy@@ -171,8 +174,7 @@ def test_get_chat_model_hands_out_a_metered_model(monkeypatch: pytest.MonkeyPatcdef test_post_hoc_work_never_creates_a_partial_ledger(tmp_path: Path):- """A re-judge of an old run must not leave a ledger holding only that verdict:- a reader would take it for the whole run's cost."""+ """Post-hoc work never creates a misleading partial ledger."""with run_ledger(tmp_path, run="old", create=False) as led:assert led is NoneMeteredChatModel(FakeChat()).generate(@@ -203,10 +205,7 @@ class SideEffectCliAgent(CliAgent):def test_a_cli_session_is_recorded_even_when_a_tool_bills_a_model_inside_it(tmp_path: Path):- """The old rule was "did anybody write a row while the session ran?", which a- single in-process call (a texture pass, a summariser) flipped — and the whole- CLI session, the only record of that money, was dropped. Reproduction:- scratchpad costfix/verifier/adversarial.py."""+ """An unrelated inner model row never suppresses the CLI session."""def inner_model_call() -> None:MeteredChatModel(FakeChat()).generate(ChatRequest(messages=[ChatMessage.user("x")], label="texture_plan"))@@ -223,9 +222,7 @@ def test_a_cli_session_is_recorded_even_when_a_tool_bills_a_model_inside_it(tmp_def test_an_in_process_session_is_never_counted_twice_even_from_another_thread(tmp_path: Path):- """The mirror failure: the api-agent's turns are already rows, so its- AgentResult.usage must never be added on top — including when the turns ran in- a worker thread the row counter could not see."""+ """Worker-thread rows from a self-metered agent are not double counted."""import threadingclass ThreadedAgent(FakeAgent):@@ -256,20 +253,18 @@ def test_a_backend_may_declare_that_it_meters_itself(tmp_path: Path):# ------------------------------------------------------------------- nesting / parallelismdef test_run_ledgers_nest_and_restore_the_outer_one(tmp_path: Path):- """A bench cell opens a ledger for the cell and another for the harness run- inside it; the cell's must come back when the inner one closes."""+ """Closing a nested ledger restores the outer context."""outer, inner = tmp_path / "cell", tmp_path / "cell" / "run"with run_ledger(outer, run="cell"):MeteredChatModel(FakeChat()).generate(ChatRequest(messages=[ChatMessage.user("x")], label="planner"))with run_ledger(inner, run="cell:run"):MeteredChatModel(FakeChat()).generate(- ChatRequest(messages=[ChatMessage.user("x")], label="api-agent:baseline:t0"))+ ChatRequest(messages=[ChatMessage.user("x")], label="baseline"))MeteredChatModel(FakeChat()).generate(ChatRequest(messages=[ChatMessage.user("x")], label="judge:static_object_v1:r00:s0"))assert [r.stage for r in load_ledger(inner)] == [Stage.BASELINE]assert [r.stage for r in load_ledger(outer)] == [Stage.PLAN, Stage.JUDGE]assert {r.run for r in load_ledger(outer)} == {"cell"}- assert per_call_metering() is Falsedef test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Path):@@ -280,7 +275,7 @@ def test_parallel_runs_in_their_own_threads_keep_their_own_ledgers(tmp_path: Patwith run_ledger(tmp_path / name, run=name):for _ in range(3):MeteredChatModel(FakeChat()).generate(- ChatRequest(messages=[ChatMessage.user("x")], label="api-agent:baseline:t0"))+ ChatRequest(messages=[ChatMessage.user("x")], label="baseline"))names = [f"p{i}" for i in range(4)]with ThreadPoolExecutor(max_workers=4) as pool:@@ -304,9 +299,7 @@ class KeyedChat(FakeChat):def test_the_row_says_which_key_served_the_call_and_how_many_round_trips(tmp_path: Path):- """No telemetry row used to say which key served a call — `keys.py` scanned 1 542 files of- the storm-day corpus for the `"key": "…xxxx"` that gemini.py puts in ``raw`` and found none,- so the per-key distribution could only be probed, never read."""+ """Safe key identity and retry counts reach telemetry rows."""with run_ledger(tmp_path, run="r1"):MeteredChatModel(KeyedChat({"key": "…ab12", "attempts": 3, "hedged": 1})).generate(ChatRequest(messages=[ChatMessage.user("x")], label="planner"))@@ -356,9 +349,7 @@ def test_per_key_buckets_and_tries_per_call(tmp_path: Path):assert BUCKET_HEADERS[-1] == "tries/call" and table[0][-1] == "2.00" and table[1][-1] == "1.00"# ------------------------------------------------------- per-attempt rows (audit 2026-08-27)def test_a_billed_but_invalid_attempt_is_in_the_total_exactly_once(tmp_path: Path):- """A charged-but-invalid reply used to vanish: the logical row carries only the- winner's usage and its own row was ``source="attempt"``, which every total- filtered out. It is now ``source="extra"`` — counted once, joined by call_id."""+ """A charged invalid attempt is counted exactly once beside its winner."""from codeverse.cost.ledger import summarisefrom tests.models.test_gemini import make_model, text_response@@ -383,9 +374,7 @@ def test_a_billed_but_invalid_attempt_is_in_the_total_exactly_once(tmp_path: Patdef test_a_hedge_losers_tokens_reach_the_ledger_when_it_lands(tmp_path: Path):- """The loser of a raced 503 retry keeps running after the winner returned; when- it lands, its billed tokens must appear in the ledger TOTAL — before, that money- left no trace anywhere, and then no trace in any total."""+ """A late hedge loser's billed tokens reach the ledger total."""import threadingimport time as _time@@ -437,8 +426,7 @@ def test_a_hedge_losers_tokens_reach_the_ledger_when_it_lands(tmp_path: Path):def test_a_failed_calls_error_row_carries_what_was_billed(tmp_path: Path):- """instrument's error path used to write an EMPTY Usage; it now records- ``ModelError.usage`` — the money a failed-after-retries call still cost."""+ """A final ModelError carries its billed usage into the error row."""from codeverse.models.base import ModelErrorerr = ModelError("bad json after retries", retryable=True, attempts=6, usage=_usage())diff --git a/harness/tests/cost/test_price_hygiene.py b/harness/tests/cost/test_price_hygiene.pyindex 694d6827..fe9168ec 100644--- a/harness/tests/cost/test_price_hygiene.py+++ b/harness/tests/cost/test_price_hygiene.py@@ -1,11 +1,7 @@-"""Price table hygiene: provenance for every row, and no silent $0 for any model-id that appears in a recorded run."""+"""Price table hygiene: provenance and non-zero prices for canonical model ids."""from __future__ import annotations-import json-from pathlib import Path-import pytestfrom codeverse.contracts.common import Usage@@ -19,17 +15,23 @@ from codeverse.models.pricing import (unit_prices,)-REPO = Path(__file__).resolve().parents[2]--#: model ids the harness uses by default (config/contracts defaults + the CLI-#: backends we run here) — asserted even when no recorded run is present.-CORE_MODEL_IDS = (+#: model ids exposed by defaults, routes, CLI examples, and public backend contracts.+#: They must stay priceable even when no recorded run happens to mention them.+SUPPORTED_MODEL_IDS = ("gemini:gemini-3.7-flash",+ "gemini:gemini-3.6-flash",+ "gemini:gemini-3.5-flash","gemini:gemini-3.1-pro-preview",+ "gemini:gemini-3.1-flash-lite","gemini:gemini-3.1-flash-image","gemini:gemini-2.5-flash-image","openai:gpt-5.6-sol",+ "openai:gpt-5.5",+ "openai:gpt-5","anthropic:claude-fable-5",+ "anthropic:claude-opus-5",+ "anthropic:claude-sonnet-5",+ "anthropic:claude-haiku-4-5","anthropic:claude-haiku-4-5-20251001","anthropic:claude-opus-5[1m]", # what the DEFAULT claude-code arm reports (CC-2))@@ -65,14 +67,6 @@ def test_image_models_have_a_per_image_price():assert per_image_usd("gemini", "gemini-2.5-flash-image-preview") == 0.039-def test_image_price_agrees_with_the_image_backend():- """``models/gemini_image.IMAGE_USD`` and the price table must not drift apart."""- from codeverse.models.gemini import IMAGE_USD-- for model, usd in IMAGE_USD.items():- assert per_image_usd("gemini", model) == pytest.approx(usd), model--def test_long_context_tier_is_applied():small = Usage(input_tokens=100_000, output_tokens=1_000)big = Usage(input_tokens=300_000, output_tokens=1_000)@@ -84,43 +78,16 @@ def test_long_context_tier_is_applied():assert unit_prices("gemini", "gemini-3.7-flash", prompt_tokens=900_000)[0] == 0.75-def _recorded_model_ids() -> set[tuple[str, str]]:- """Every (backend, model) pair that appears in a recorded run of this repo."""- from codeverse.cost.types import split_model_id-- out: set[tuple[str, str]] = set()- for root in (REPO / "runs", REPO / "bench" / "out"):- if not root.is_dir():- continue- for record in root.rglob("record.json"):- try:- data = json.loads(record.read_text())- except (OSError, ValueError):- continue- usages = [data.get("total_usage")]- for rnd in data.get("rounds") or []:- usages.append(rnd.get("usage"))- usages.append((rnd.get("judgment") or {}).get("usage"))- for u in usages:- if isinstance(u, dict) and (u.get("model") or ""):- out.add(split_model_id(str(u.get("backend") or ""), str(u["model"])))- return out--[email protected]("model_id", CORE_MODEL_IDS)-def test_core_model_ids_resolve_to_a_price(model_id: str):- provider, model = model_id.split(":", 1)+def test_supported_model_ids_resolve_to_a_price():u = Usage(input_tokens=1_000, output_tokens=1_000)- assert price_provenance(provider, model).price is not None, model_id- assert estimate_cost(provider, model, u) > 0, model_id+ for model_id in SUPPORTED_MODEL_IDS:+ provider, model = model_id.split(":", 1)+ assert price_provenance(provider, model).price is not None, model_id+ assert estimate_cost(provider, model, u) > 0, model_iddef test_the_bracketed_context_variant_prices_on_its_own_row():- """CC-2: '[1m]' is not a version/date/channel tag, so _is_version_suffix() refuses to- fall back to claude-opus-5 — correctly, since a sibling's rate is never assumed here.- The id is real (the default claude-code arm reports it, and one recorded cell billed- $1.218 under it), so it needs a row of its own or `3dcv cost prices` calls the default- arm unknown and estimate_cost values it $0.00."""+ """A bracketed context variant requires its own exact price row."""row = price_provenance("anthropic", "claude-opus-5[1m]")assert row.match == "exact" and row.price is not Noneassert row.provenance.status == "inferred" and row.provenance.checked >= "2026-08-24"@@ -131,13 +98,6 @@ def test_the_bracketed_context_variant_prices_on_its_own_row():assert price_provenance("anthropic", "claude-sonnet-5[1m]").price is None-def test_every_recorded_model_id_resolves_to_a_price():- """No silent $0: a model that billed us in a recorded run must have a row."""- unknown = sorted(f"{p}:{m}" for p, m in _recorded_model_ids()- if p and price_provenance(p, m).price is None)- assert not unknown, f"models with no price row (they cost $0 in every report): {unknown}"--# --------------------------------------------------------------- staleness maintenancedef test_every_price_row_was_checked_within_the_maintenance_window():"""A price nobody re-checked for 90 days is not evidence. When this fails,diff --git a/harness/tests/cost/test_profiles.py b/harness/tests/cost/test_profiles.pyindex 668457f5..70d38f21 100644--- a/harness/tests/cost/test_profiles.py+++ b/harness/tests/cost/test_profiles.py@@ -12,6 +12,7 @@ from codeverse.cli._common import resolve_dialfrom codeverse.cli.main import appfrom codeverse.config import Settings, get_settingsfrom codeverse.cost.profiles import PROFILE_NAMES, PROFILES, get_profile, profile_table+from codeverse.orchestrator import RoundPolicyrunner = CliRunner()@@ -49,20 +50,6 @@ def test_balanced_is_todays_defaults():assert p.max_minutes == 60.0 and p.judge_max_px == 1024-def test_apply_profile_sets_the_whole_dial():- s = Settings()- p = s.apply_profile("quality")- assert p.name == "quality" and s.profile == "quality"- assert s.default_judge == p.judge and s.default_candidates == 2- assert s.judge.samples == 3 and s.judge.max_px == 1024- s2 = Settings()- s2.apply_profile("economy")- assert s2.judge.samples == 2 and s2.limits.agent_max_turns == 0- # payload untouched: 768 px bills the same on Gemini and is noisier, and the- # crop cut did not survive a second draw (docs/COST.md §14)- assert s2.judge.detail_crops == 2 and s2.judge.max_px == 1024--def test_a_value_the_user_configured_survives_the_profile_unless_forced():s = Settings(default_generator="codex:gpt-5.6-sol")s.apply_profile("economy")@@ -73,11 +60,7 @@ def test_a_value_the_user_configured_survives_the_profile_unless_forced():def test_one_stated_judge_field_does_not_disable_the_whole_judge_block(monkeypatch):- """SM-03: ``model_fields_set`` on Settings is SECTION-granular — pydantic marks the- whole ``judge`` sub-model as set when any CV3D_JUDGE__* is present — so stating- max_px (which no profile even changes) used to suppress judge_samples too:- ``CV3D_PROFILE=quality CV3D_JUDGE__MAX_PX=800`` judged at n=1 while `3dcv make`- advertised "judge sigma 0.017 at n=3". Statedness must be per FIELD."""+ """A stated judge field freezes only itself, not the whole section."""monkeypatch.setenv("CV3D_JUDGE__MAX_PX", "800")s = Settings()s.apply_profile("quality")@@ -95,8 +78,7 @@ def test_one_stated_judge_field_does_not_disable_the_whole_judge_block(monkeypatdef test_applying_a_profile_twice_is_idempotent():- """A profile writes DEFAULTS, so its own values must not come back as "stated" and- freeze the next apply_profile (model_copy(update=) marks the copied fields set)."""+ """Profile defaults do not masquerade as user-stated fields."""s = Settings()s.apply_profile("quality")s.apply_profile("economy")@@ -109,10 +91,7 @@ def test_unknown_profile_is_a_clear_error():def test_a_bogus_profile_name_is_a_typed_cli_error_not_a_traceback(monkeypatch, tmp_path):- """SM-10: the profile is read while get_settings() builds, and `app` runs with- pretty_exceptions_enable=False, so one typo in an exported CV3D_PROFILE dumped a raw- Python stack from EVERY command — including `3dcv doctor`, the command you would run- to find out what is wrong with your configuration."""+ """An invalid environment profile yields one clean validation error."""runner = CliRunner()monkeypatch.setenv("CV3D_PROFILE", "bogus")get_settings.cache_clear()@@ -175,8 +154,8 @@ 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 bound here because injecting a policy skips BaseTrack's own binding- assert opts["policy"].target == pytest.approx(0.72)+ # 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@@ -221,6 +200,9 @@ def _dial_from_env(name: str, monkeypatch):)def test_each_profile_resolves_to_its_documented_dial(name, expected, monkeypatch):"""Every dial value docs/COST.md §15 promises, from BOTH entry points."""+ settings = Settings()+ applied = settings.apply_profile(name)+ assert applied.name == settings.profile == namefor dial in (_dial_from_flag(name), _dial_from_env(name, monkeypatch)):assert dial.profile == namefor field, want in expected.items():diff --git a/harness/tests/cost/test_reconstruct.py b/harness/tests/cost/test_reconstruct.pyindex 028396d0..500f66ee 100644--- a/harness/tests/cost/test_reconstruct.py+++ b/harness/tests/cost/test_reconstruct.py@@ -7,11 +7,10 @@ from pathlib import Pathimport pytest+from codeverse.contracts.common import Usagefrom codeverse.cost import audit_runs, find_runs, reconstructfrom codeverse.cost.types import Role, Stage-REPO = Path(__file__).resolve().parents[2]-def test_reconstructs_and_reconciles(fake_run: Path):led = reconstruct(fake_run)@@ -30,13 +29,7 @@ def test_generate_event_does_not_double_count_its_session(fake_run: Path):def test_a_retried_session_does_not_double_count_its_generate_event(fake_run: Path, tmp_path: Path):- """The de-duplication bug behind docs/COST.md §6.-- A retry records itself as ``<label>.a2`` while the ``generate.done`` event- carries the plain job label, so keying the "already covered" pool on the- session's own label left the retry's dollars in a different bucket, the pool- ran dry and the event was counted a SECOND time — $3.58 of the reconstructed- $89.88 across the 61 recorded runs."""+ """Reconstruction counts a retried generation exactly once."""import shutilws = tmp_path / "retried"@@ -103,49 +96,8 @@ def test_find_runs_skips_sub_workspaces(tmp_path: Path):assert find_runs(tmp_path) == [tmp_path / "a"][email protected](not (REPO / "runs" / "e2e_chair_blender" / "record.json").is_file(),- reason="recorded reference runs are not present")-def test_reference_runs_reconcile():- """Every recorded run reconciles to its own record (or explains the gap)."""- audit = audit_runs([REPO / "runs"])- assert audit.n_runs >= 5- for led in audit.runs:- gap = led.ledger_usd - led.recorded_usd- assert gap > -0.01, f"{led.run}: ledger lost ${-gap:.4f}"- if gap > 0.01:- assert led.notes, f"{led.run}: unexplained extra ${gap:.4f}"--[email protected](not (REPO / "bench" / "out" / "articulated_v1_flash").is_dir(),- reason="the recorded bench batteries are not present")- ("path", "record_usd"),- [("bench/out/articulated_v1_flash/runs/art_hard_door_handle", 3.0690),- ("bench/out/static_v1_flash/runs/tool_med_hand_drill", 4.0210),- ("bench/out/articulated_v1_flash/runs/art_easy_laptop", 1.1223)],-)-def test_runs_with_retried_sessions_reconcile_instead_of_looking_off_record(path: str, record_usd: float):- """The three worst rows of the old docs/COST.md §6 table ($1.38 / $0.50 / $0.31- "off record") were the retry de-duplication bug, not lost money."""- led = reconstruct(REPO / path)- assert led.recorded_usd == pytest.approx(record_usd, abs=0.001)- found = sum(r.recorded_usd for r in led.rows if r.source != "residual")- assert found <= led.recorded_usd + 0.005, f"{path}: ${found - led.recorded_usd:.4f} counted twice"--[email protected](not (REPO / "runs" / "e2e_chair_blender" / "record.json").is_file(),- reason="recorded reference runs are not present")-def test_gemini_cli_recheck_finds_the_stale_parse():- """The threejs run was recorded before ``tokens.prompt`` was the total prompt:- re-pricing from the raw CLI stats must show the under-billing, not hide it."""- led = reconstruct(REPO / "runs" / "e2e_bench_threejs", recheck=True)- assert led.ledger_usd > 2.0 > led.recorded_usd- assert any("differs from record.total_usage" in n for n in led.notes)--def test_best_of_n_losers_are_attributed_and_counted_as_waste(fake_run: Path, tmp_path: Path):- """A ``_cand/c<k>`` sub-workspace is the run's, not a run of its own; the- candidates that lost are money spent on artifacts nobody kept."""+ """Candidate sub-workspaces attribute their spend to the parent run."""import shutilws = tmp_path / "cands"@@ -157,11 +109,33 @@ def test_best_of_n_losers_are_attributed_and_counted_as_waste(fake_run: Path, tm(ws / "rounds").mkdir(exist_ok=True)(ws / "rounds" / "candidates.json").write_text(json.dumps({"n": 2, "selected": 1}))- from codeverse.cost import audit_runs-led = reconstruct(ws)assert find_runs(ws) == [ws], "a candidate sub-workspace is not a separate run"cand_rows = [r for r in led.rows if r.stage is Stage.CANDIDATE]assert len(cand_rows) == 4 and {r.label.split(":")[0] for r in cand_rows} == {"c0", "c1"}waste = audit_runs([ws]).waste_by_kind()assert "lost_candidate" in waste and waste["lost_candidate"][1] > 0+++def test_a_live_ledger_files_losing_candidates_as_waste(fake_run: Path, tmp_path: Path):+ """Live rows carry the candidate clone's label (``baseline_c<k>``, kind=candidate) —+ not the reconstructed ``c<k>:baseline`` — and the waste detector must read both."""+ import shutil++ from codeverse.cost.instrument import run_ledger+ from codeverse.cost.ledger import record_call++ ws = tmp_path / "live_cands"+ shutil.copytree(fake_run, ws)+ (ws / "rounds").mkdir(exist_ok=True)+ (ws / "rounds" / "candidates.json").write_text(json.dumps({"n": 2, "selected": 1}))+ usage = Usage(backend="gemini-cli", model="gemini-3.7-flash", input_tokens=10_000, output_tokens=500)+ with run_ledger(ws, run=ws.name):+ for k in (0, 1):+ record_call(usage, stage=Stage.CANDIDATE, round=0, label=f"baseline_c{k}", source="session")+ led = reconstruct(ws)+ assert led.source == "live" and led.selected_candidate == "c1"+ waste = audit_runs([ws]).waste_by_kind()+ assert waste["lost_candidate"][0] == 1 and waste["lost_candidate"][1] > 0+ (item,) = [w for w in audit_runs([ws]).waste if w.kind == "lost_candidate"]+ assert "c0 lost to c1" in item.detail