Official Codebase of 3DCodeVerse
Python
cost: the pre-ledger reconstruction goes — a run's money is read from telemetry/cost.jsonl alone
gaoypeng358f8672b9f7
diff --git a/eval/bench/session_stats.py b/eval/bench/session_stats.pyindex 3cf184cc..cba77070 100644--- a/eval/bench/session_stats.py+++ b/eval/bench/session_stats.py@@ -72,14 +72,14 @@ def tool_rates(sessions: list[Path]) -> tuple[Counter, Counter]:def token_rates(sessions: list[Path]) -> dict[str, float]:"""Prompt/cached tokens and requests for each session's MAIN model.- ``cost.reconstruct._gemini_cli_usages`` owns the envelope — including the older+ ``agents.backends._model_usage`` owns the envelope — including the older``tokens.input`` schema this file would otherwise read as zero — so the tokens comefrom it rather than from a second parser. A session's ``models`` map also carriesgemini-cli's own bookkeeping model (one request per session for the session title),and docs/COST.md §30 counts main-role requests: the model with the most requests ISthe main role, and mixing the other in moves ``uncached per request`` by ~3 %."""- from codeverse3d.cost.reconstruct import _gemini_cli_usages+ from codeverse3d.agents.backends import _model_usageprompt = cached = requests = 0for path in sessions:@@ -91,9 +91,7 @@ def token_rates(sessions: list[Path]) -> dict[str, float]:if not models:continuemain = max(models, key=lambda n: int(((models[n] or {}).get("api") or {}).get("totalRequests") or 0))- usage = next((u for u in _gemini_cli_usages(stdout) if u.model == main), None)- if usage is None:- continue+ usage = _model_usage((models[main] or {}).get("tokens") or {}, main)prompt += usage.input_tokenscached += usage.cached_tokensrequests += int(((models[main] or {}).get("api") or {}).get("totalRequests") or 0)diff --git a/harness/codeverse3d/addons/costreport/__init__.py b/harness/codeverse3d/addons/costreport/__init__.pyindex bb5683d4..92f4fa50 100644--- a/harness/codeverse3d/addons/costreport/__init__.py+++ b/harness/codeverse3d/addons/costreport/__init__.py@@ -1,6 +1,6 @@"""The cost of finished runs, read back: ``3dcode cost`` and its markdown report.-* ``audit`` ``audit_runs(paths)`` → ``Audit`` (reconstruct + aggregate every run under the paths, waste)+* ``audit`` ``audit_runs(paths)`` → ``Audit`` (every run's ledger under the paths, aggregated, + waste)* ``report`` ``console(audit)`` · ``markdown(audit)``* ``caching`` what prompt caching saved, per sessiondiff --git a/harness/codeverse3d/addons/costreport/audit.py b/harness/codeverse3d/addons/costreport/audit.pyindex 15ac72f3..724fad2b 100644--- a/harness/codeverse3d/addons/costreport/audit.py+++ b/harness/codeverse3d/addons/costreport/audit.py@@ -1,21 +1,20 @@"""Cost audit over a directory of runs: where the money and the minutes go.-``audit_runs(paths)`` reconstructs a ledger per run (``reconstruct.py``),-stamps every row with its run's track / language / status, and aggregates:+``audit_runs(paths)`` reads every run's own ledger (``telemetry/cost.jsonl``, the one record+of money — docs/COST.md §12) and its record, stamps every row with the run's track /+language / status, and aggregates:* $ per run, per track, per stage, per role, per backend, per model;* token composition (input / cached / output / thoughts) and the effective$/1k-token rate each bucket actually paid;-* latency next to the money — wall clock, model time, harness (non-model) time;-* **waste**: repair loops that never got their round to build, degraded verdicts,- best-of-N candidates that lost, and spend after the budget was already blown.- Nothing is waste for scoring below another round: since 2026-09-22 every round is- kept and any of them can be the one handed over (the "regression", "zero_delta_round"- and "unpromoted_judge" kinds measured against an in-run best that no longer exists).--Everything is measured from the recorded telemetry; nothing is estimated except-where a row says so (``price_source == "event-cost"`` — the event recorded a-cost but no tokens).+* time next to the money — the run's minutes (``RunRecord.minutes``) and its model time;+* **waste**: repair loops that never got their round to build, best-of-N candidates that+ lost, and spend in a round the clock cut. Nothing is waste for scoring below another+ round: since 2026-09-22 every round is kept and any of them can be the one handed over.++A directory with no ledger has no rows and is left out: the reconstruction of pre-ledger+runs from their trajectories, verdicts and events went on 2026-09-22 (434 of 467 archived+runs carry a ledger; the 33 without are five v1 batteries outside the repo)."""from __future__ import annotations@@ -24,9 +23,110 @@ from collections.abc import Iterablefrom dataclasses import dataclass, fieldfrom pathlib import Path-from codeverse3d.cost.ledger import summarise-from codeverse3d.cost.reconstruct import RunLedger, find_runs, reconstruct-from codeverse3d.cost.types import CallCost, Role, Stage, Summary+from codeverse3d.contracts.common import Usage+from codeverse3d.contracts.run import RunId+from codeverse3d.cost.ledger import load_ledger, price_call, summarise+from codeverse3d.cost.types import CallCost, Stage, Summary+from codeverse3d.proc import read_json_or_none+from codeverse3d.record.record import SUBRUN_DIRS, RecordError, load_record+++@dataclass+class RunLedger:+ """One run's (or compare cell's) ledger rows plus what a cost report says about it."""++ run: str = ""+ path: Path = Path()+ track: str = ""+ language: str = ""+ status: str = ""+ stop_reason: str = ""+ n_rounds: int = 0+ round_built: list[bool | None] = field(default_factory=list) # per round: did its build (+repair) succeed+ selected_candidate: str = "" # "c1" when the run ran best-of-N and c1 won+ minutes: float | None = None # RunRecord.minutes (a one-shot cell: its cell.json minutes)+ cell_score: float | None = None # a one-shot compare cell's one score (it has no record)+ written_usd: float = 0.0 # the rows as written, before a --recheck re-priced them+ rows: list[CallCost] = field(default_factory=list)++ @property+ def ledger_usd(self) -> float:+ return sum(r.cost_usd for r in self.rows)++ @property+ def model_s(self) -> float:+ return sum(r.latency_ms for r in self.rows) / 1000.0+++def _rows(root: Path, led: RunLedger, *, recheck: bool) -> None:+ """Add ``root``'s own ledger rows to ``led`` — stamped with its run name where a battery+ copied them without one, and re-priced from today's table when ``recheck``."""+ for row in load_ledger(root):+ led.written_usd += row.cost_usd+ row.run = row.run or led.run+ if recheck:+ usage = Usage(backend=row.backend, model=row.model_id or row.model, input_tokens=row.input_tokens,+ cached_tokens=row.cached_tokens, output_tokens=row.output_tokens,+ thoughts_tokens=row.thoughts_tokens, tool_calls=row.tool_calls, cost_usd=row.recorded_usd)+ cost, fields = price_call(usage, backend=row.backend, model=row.model_id or row.model,+ cache_write_tokens=row.cache_write_tokens, reprice=True)+ row = row.model_copy(update={"cost_usd": cost, **fields})+ led.rows.append(row)+++def read_run(run_dir: Path, *, name: str = "", recheck: bool = False) -> RunLedger:+ """A run directory: its ledger rows and its record's facts (an unreadable record keeps the rows)."""+ led = RunLedger(run=name or run_dir.name, path=run_dir)+ try:+ rec = load_record(run_dir)+ except RecordError:+ rec = None+ if rec is not None:+ led.track, led.language, led.status = rec.spec.track.value, rec.spec.language.value, rec.status.value+ led.stop_reason = str(rec.extra.get("stop_reason") or "")+ led.n_rounds, led.minutes = len(rec.rounds), rec.minutes+ led.round_built = [None if r.build is None else r.build.ok for r in rec.rounds]+ cands = read_json_or_none(run_dir / "rounds" / "candidates.json") or rec.extra.get("candidates") or {}+ if isinstance(cands, dict) and cands.get("selected") is not None:+ led.selected_candidate = f"c{cands['selected']}"+ _rows(run_dir, led, recheck=recheck)+ return led+++def read_cell(cell_dir: Path, *, name: str, recheck: bool = False) -> RunLedger:+ """A ``compare_backends`` / ``ab_plan`` cell. A harness arm is its run plus the cell's own+ ledger (the fixed evaluator's judge, a repair arm's extra generations); a one-shot or+ bare-agent arm is the cell ledger alone, described by ``cell.json`` and ``eval/spec.json``."""+ if (cell_dir / "run" / "record.json").is_file():+ led = read_run(cell_dir / "run", name=name, recheck=recheck)+ else:+ cell = read_json_or_none(cell_dir / "cell.json") or {}+ spec = read_json_or_none(cell_dir / "eval" / "spec.json") or {}+ minutes = cell.get("minutes")+ led = RunLedger(run=name, path=cell_dir, track=str(spec.get("track") or ""),+ language=str(spec.get("language") or ""), status=str(cell.get("status") or ""),+ n_rounds=1, round_built=[cell.get("build_ok")], cell_score=cell.get("score"),+ minutes=float(cell.get("wall_s") or 0.0) / 60 if minutes is None else float(minutes))+ _rows(cell_dir, led, recheck=recheck)+ return led+++def find_runs(root: str | Path) -> list[Path]:+ """Every run directory under ``root`` (a dir with ``record.json``) and every compare cell+ (a dir with ``cell.json``; one that wraps a harness run is named by the cell, not its+ ``run/``). Sub-workspaces (``_assets/``, ``_cand/``) are part of their run."""+ base = Path(root)+ if (base / "record.json").is_file() or (base / "cell.json").is_file():+ return [base]+ out: set[Path] = set()+ for marker in ("record.json", "cell.json"):+ for path in base.rglob(marker):+ d = path.parent+ if SUBRUN_DIRS & set(d.relative_to(base).parts):+ continue+ out.add(d.parent if d.name == "run" and (d.parent / "cell.json").is_file() else d)+ return sorted(out)+#: dimensions the audit always aggregates onAUDIT_DIMENSIONS = ("run", "track", "language", "stage", "role", "backend", "model", "provider",@@ -37,7 +137,7 @@ AUDIT_DIMENSIONS = ("run", "track", "language", "stage", "role", "backend", "modclass WasteItem:"""One dollar that bought nothing (or bought a worse artifact)."""- kind: str # repair_no_converge | degraded_judge | lost_candidate | post_budget+ kind: str # repair_no_converge | lost_candidate | post_budgetrun: strusd: floatdetail: str = ""@@ -59,8 +159,8 @@ class Audit:return self.summary.total.cost_usd@property- def recorded_usd(self) -> float:- return sum(r.recorded_usd for r in self.runs)+ def written_usd(self) -> float:+ return sum(r.written_usd for r in self.runs)@propertydef n_runs(self) -> int:@@ -71,8 +171,8 @@ class Audit:return self.total_usd / self.n_runs if self.n_runs else 0.0@property- def wall_s(self) -> float:- return sum(r.wall_s for r in self.runs)+ def minutes(self) -> float:+ return sum(r.minutes or 0.0 for r in self.runs)@propertydef model_s(self) -> float:@@ -96,10 +196,6 @@ class Audit:def _waste(led: RunLedger) -> list[WasteItem]:items: list[WasteItem] = []- for row in led.rows:- if row.outcome == "degraded" and (row.stage is Stage.JUDGE or row.role is Role.JUDGE):- items.append(WasteItem("degraded_judge", led.run, row.cost_usd, round=row.round,- detail="degraded verdict (glitch, not a score) — paid for, not usable"))# repair loops that never got their round to buildunbuilt = {i for i, ok in enumerate(led.round_built) if ok is False}repair = [r for r in led.rows if r.stage is Stage.REPAIR and r.round in unbuilt]@@ -108,15 +204,13 @@ def _waste(led: RunLedger) -> list[WasteItem]:detail=f"{len(repair)} repair call(s) in round(s) "f"{', '.join(f'r{i:02d}' for i in sorted({r.round for r in repair}))} "f"that still did not build"))- # 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.+ # best-of-N candidates that lost (their whole sub-workspace is thrown away): the candidate+ # clone's sessions are labelled ``baseline_c<k>``. Generator sessions only — the+ # quick-judge rows inside a candidate carry no candidate marker.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}:") or r.label.endswith(f"_{won}")))]+ losers = [r for r in led.rows if r.stage is Stage.CANDIDATE and not (won and r.label.endswith(f"_{won}"))]if losers:- names = sorted({_candidate_of(r.label) for r in losers})+ names = sorted({r.label.rsplit("_", 1)[-1] 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@@ -128,35 +222,35 @@ def _waste(led: RunLedger) -> 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] = []- for p in paths:- dirs += find_runs(p)+ """Read + aggregate every run and cell under ``paths`` (run dirs or trees). A run is named+ by its place under the path it was found from (``RunId``), so an A/B battery's control and+ variant cells of one prompt stay two runs."""audit = Audit()- for d in dirs:- led = reconstruct(d, recheck=recheck)- if not led.rows:- continue- for row in led.rows:- row.track = led.track or "?"- row.language = led.language or "?"- row.status = led.status or "?"- audit.runs.append(led)- audit.rows += led.rows- audit.waste += _waste(led)+ for root in map(Path, paths):+ for d in find_runs(root):+ name = RunId(battery="", rel=d.relative_to(root).as_posix() if d != root else d.name).slug+ led = read_cell(d, name=name, recheck=recheck) if (d / "cell.json").is_file() else \+ read_run(d, name=name, recheck=recheck)+ _add(audit, led)audit.summary = summarise(audit.rows, dimensions=AUDIT_DIMENSIONS)audit.runs.sort(key=lambda r: -r.ledger_usd)audit.waste.sort(key=lambda w: -w.usd)return audit+def _add(audit: Audit, led: RunLedger) -> None:+ if not led.rows:+ return+ for row in led.rows:+ row.track = led.track or "?"+ row.language = led.language or "?"+ row.status = led.status or "?"+ audit.runs.append(led)+ audit.rows += led.rows+ audit.waste += _waste(led)++# --------------------------------------------------------------------------- derived viewsdef cached_input_share(audit: Audit) -> tuple[int, int, float]:"""``(cached, total input, $ paid for cache reads)`` — how much of every prompt@@ -190,7 +284,7 @@ def price_confidence(audit: Audit) -> dict[str, float]:"""$ by how trustworthy the price row behind it is."""out: dict[str, float] = {}for r in audit.rows:- key = r.price_source if r.price_source in ("unknown", "provider-reported", "event-cost", "residual") \+ key = r.price_source if r.price_source in ("unknown", "provider-reported") \else ("approximate" if r.price_approximate else "verified")out[key] = out.get(key, 0.0) + r.cost_usdreturn dict(sorted(out.items(), key=lambda kv: -kv[1]))diff --git a/harness/codeverse3d/addons/costreport/report.py b/harness/codeverse3d/addons/costreport/report.pyindex 30d9e15a..4b988901 100644--- a/harness/codeverse3d/addons/costreport/report.py+++ b/harness/codeverse3d/addons/costreport/report.py@@ -12,12 +12,12 @@ from collections.abc import Sequencefrom codeverse3d.addons import selectfrom codeverse3d.addons.costreport.audit import (Audit,+ RunLedger,cached_input_share,price_confidence,stage_latency,uncached_if_no_cache,)-from codeverse3d.cost.reconstruct import RunLedgerfrom codeverse3d.cost.types import CostBucketSTAGE_ORDER = ("plan", "skeleton", "assets", "env", "zones", "assemble", "baseline", "candidate",@@ -89,8 +89,7 @@ def _scores(r: RunLedger) -> tuple[float | None, float | None]:return s.baseline_score, s.picked_scoreexcept Exception: # noqa: BLE001 - an unreadable record still gets its cost rowreturn None, None- score = r.round_scores[0] if r.round_scores else None # a one-shot cell: one round- return score, score+ return r.cell_score, r.cell_score # a one-shot cell: one rounddef runs_table(audit: Audit, *, limit: int = 20) -> str:@@ -100,8 +99,9 @@ def runs_table(audit: Audit, *, limit: int = 20) -> str:rows.append([r.run, r.track or "-", _usd(r.ledger_usd), r.n_rounds,f"{baseline:.3f}" if baseline is not None else "-",f"{picked:.3f}" if picked is not None else "-",- r.stop_reason or r.status, f"{r.wall_s / 60:.1f}", f"{r.model_s / 60:.1f}"])- return table(("run", "track", "USD", "rounds", "baseline", "picked", "stop", "wall min", "model min"), rows)+ r.stop_reason or r.status, "-" if r.minutes is None else f"{r.minutes:.1f}",+ f"{r.model_s / 60:.1f}"])+ return table(("run", "track", "USD", "rounds", "baseline", "picked", "stop", "minutes", "model min"), rows)def waste_table(audit: Audit) -> str:@@ -122,7 +122,8 @@ def summary_lines(audit: Audit) -> list[str]:f"- prompt caching already saves **{_usd(no_cache - audit.total_usd)}** "f"({_share(no_cache - audit.total_usd, no_cache):.0f}% of what this traffic would cost uncached); "f"cache reads still cost {_usd(cache_usd)}",- f"- clock: {audit.wall_s / 3600:.1f} h of run time, {audit.model_s / 3600:.1f} h of it waiting on models",+ f"- time: {audit.minutes / 60:.1f} h of run steps (provider errors left out), "+ f"{audit.model_s / 3600:.1f} h of model calls (side by side ones counted each)",f"- calls: {audit.summary.total.n_calls:,} model calls, {audit.calls_per_round():.0f} per round",f"- identified waste: **{_usd(audit.waste_total())}** ({_share(audit.waste_total(), audit.total_usd):.0f}% of spend)",]diff --git a/harness/codeverse3d/cli/cost_cmd.py b/harness/codeverse3d/cli/cost_cmd.pyindex 70652500..0ab2c83a 100644--- a/harness/codeverse3d/cli/cost_cmd.py+++ b/harness/codeverse3d/cli/cost_cmd.py@@ -9,9 +9,8 @@3dcode cost profiles # the economy / balanced / quality dial3dcode cost estimate gemini:… --in 12000 --out 800-A run that wrote a live ledger (``telemetry/cost.jsonl``) is read from it — one-priced row per real model call. Older runs are reconstructed from their-trajectories, verdicts and events, so all 61 reference runs still audit.+Every run is read from its own ledger (``telemetry/cost.jsonl``) — one priced row per+real model call; a run recorded before the ledger existed (2026-08-23) has none."""from __future__ import annotations@@ -94,48 +93,23 @@ def _report(paths: list[Path], *, md: Path | None, recheck: bool, limit: int, peaudit = audit_runs(paths, recheck=recheck)if not audit.runs:- raise typer.BadParameter(f"no runs with a record.json under {', '.join(str(p) for p in paths)}")+ raise typer.BadParameter(f"no run with a cost ledger under {', '.join(str(p) for p in paths)}")console.print(text_report(audit), soft_wrap=True)- if len(audit.runs) == 1:- _single_run_lines(audit.runs[0])- elif per_run:+ if per_run:console.print("")console.print(runs_table(audit, limit=limit), soft_wrap=True)- live = sum(1 for r in audit.runs if r.source == "live")- console.print(f"[dim]ledger source: {live} live / {len(audit.runs) - live} reconstructed[/dim]")if recheck:- drift = audit.total_usd - audit.recorded_usd- warn(f"re-priced total ${audit.total_usd:.4f} vs recorded ${audit.recorded_usd:.4f} ({drift:+.4f})")+ drift = audit.total_usd - audit.written_usd+ warn(f"re-priced total ${audit.total_usd:.4f} vs ${audit.written_usd:.4f} as written ({drift:+.4f})")for run in audit.runs:- for note in run.notes:- console.print(f" {run.run}: {note}")+ if abs(run.ledger_usd - run.written_usd) > 0.005:+ console.print(f" {run.run}: ${run.ledger_usd - run.written_usd:+.4f}")if md:md.parent.mkdir(parents=True, exist_ok=True)md.write_text(markdown(audit, title=f"Cost audit — {', '.join(str(p) for p in paths)}"))ok(f"wrote {md}")-def _single_run_lines(run: object) -> None:- """Reconciliation for one run: the ledger against what the record was billed."""- from codeverse3d.cli._common import kv_table-- ledger = float(getattr(run, "ledger_usd", 0.0))- recorded = float(getattr(run, "recorded_usd", 0.0))- drift = ledger - recorded- pct = (100.0 * drift / recorded) if recorded else 0.0- rows = {- "source": getattr(run, "source", "?"),- "ledger": f"${ledger:.4f} over {len(getattr(run, 'rows', []))} calls",- "record.total_usage": f"${recorded:.4f}",- "difference": f"${drift:+.4f} ({pct:+.2f}%)",- "status": f"{getattr(run, 'status', '')} ({getattr(run, 'stop_reason', '')})",- }- console.print("")- console.print(kv_table("reconciliation", rows))- for note in getattr(run, "notes", []):- warn(note)--# --------------------------------------------------------------------------- prices@cost_app.command("prices")def prices(@@ -208,17 +182,13 @@ def cache(runs_dir: Annotated[Path | None, typer.Option("--runs-dir")] = None,) -> None:"""Did prompt caching actually happen? Per session: the cold first call, the- cached share, the dollars the cache saved and the dollars the cold head cost.-- Only a live ledger has per-call ``cached_tokens``; reconstructed runs show- what their transcripts recorded."""+ cached share, the dollars the cache saved and the dollars the cold head cost."""from codeverse3d.addons.costreport.caching import session_cachefrom codeverse3d.cost.ledger import load_ledger- from codeverse3d.cost.reconstruct import reconstruct_runfor arg in paths:root = _resolve(str(arg), runs_dir)- rows = load_ledger(root) or reconstruct_run(root).rows+ rows = load_ledger(root)sessions = session_cache(rows)if not sessions:warn(f"{root}: no priced calls found")diff --git a/harness/codeverse3d/cli/layout_cmd.py b/harness/codeverse3d/cli/layout_cmd.pyindex 2782adce..f59451a0 100644--- a/harness/codeverse3d/cli/layout_cmd.py+++ b/harness/codeverse3d/cli/layout_cmd.py@@ -272,7 +272,7 @@ def print_cost_and_settings(ws: Workspace, record: RunRecord) -> None:if computed:console.print("[dim]computed on the fly (no telemetry/ in this run)[/dim]")else:- console.print(f"[dim]telemetry: {ws.cost_path} · {ws.usage_path} · {ws.settings_path}[/dim]")+ console.print(f"[dim]telemetry: {ws.cost_path} · {ws.telemetry / 'cost.jsonl'} · {ws.settings_path}[/dim]")# --------------------------------------------------------------------------- commanddiff --git a/harness/codeverse3d/cost/__init__.py b/harness/codeverse3d/cost/__init__.pyindex dc37e291..b704f814 100644--- a/harness/codeverse3d/cost/__init__.py+++ b/harness/codeverse3d/cost/__init__.py@@ -5,8 +5,8 @@ its report are ``codeverse3d.addons.costreport``.)This package re-exports only the names other packages actually import through it.Everything else lives in — and is imported from — its own module: ``cost.profiles``(get_profile/PROFILES), ``cost.instrument`` (metered_chat_model/MeteredAgent),-``cost.types`` (CallCost/CostBucket/Summary), ``cost.reconstruct`` (RunLedger).-Keeping the shim narrow also keeps profiles out of the eager import graph of+``cost.types`` (CallCost/CostBucket/Summary), ``cost.tally`` (the step clock).+Reading the ledgers of finished runs back is ``codeverse3d.addons.costreport``. Keeping the shim narrow also keeps profiles out of the eager import graph of``import codeverse3d.cost``.Nothing here imports tracks/ or orchestrator/, so any layer may use it.@@ -18,10 +18,9 @@ from codeverse3d.cost.context import call_contextfrom codeverse3d.cost.guard import estimate_callfrom codeverse3d.cost.instrument import run_ledgerfrom codeverse3d.cost.ledger import CostLedger, load_ledger, record_call, summarise-from codeverse3d.cost.reconstruct import find_runs, reconstructfrom codeverse3d.cost.types import Role, Stage__all__ = ["CostLedger", "Role", "Stage", "call_context", "estimate_call",- "find_runs", "load_ledger", "reconstruct", "record_call", "run_ledger", "summarise",+ "load_ledger", "record_call", "run_ledger", "summarise",]diff --git a/harness/codeverse3d/cost/ledger.py b/harness/codeverse3d/cost/ledger.pyindex d217ff61..7b063630 100644--- a/harness/codeverse3d/cost/ledger.py+++ b/harness/codeverse3d/cost/ledger.py@@ -47,16 +47,12 @@ from codeverse3d.proc import iter_jsonl_lineslog = logging.getLogger(__name__)-#: the ledger of a run lives in its telemetry bucket (docs/RUN_LAYOUT.md §telemetry)+#: the ledger of a run lives in its telemetry bucket (docs/RUN_LAYOUT.md §telemetry) — the+#: one name it has: the root ``cost_ledger.jsonl`` and ``telemetry/usage.jsonl`` aliases went+#: on 2026-09-22 (runs written before keep them as dangling-safe symlinks nobody reads)TELEMETRY_DIR = "telemetry"TELEMETRY_LEDGER = f"{TELEMETRY_DIR}/cost.jsonl"-#: alias name at the run root: a relative symlink :func:`open_run_ledger` leaves-#: pointing at the telemetry copy, so ``record.telemetry.live_ledger_path`` and-#: anything that learned this path before the telemetry bucket existed still reads-#: the one physical file.-LEDGER_NAME = "cost_ledger.jsonl"-#: env var that points ``record_call`` at a ledger when no path is passed#: (``off`` / ``0`` / ``none`` disables ledger writing for the process)LEDGER_ENV = "C3D_COST_LEDGER"@@ -151,31 +147,17 @@ def process_ledger_path() -> Path:def existing_ledger_path(workspace: str | Path) -> Path | None:- """The ledger file a run actually has, or ``None``.-- Only ``telemetry/cost.jsonl``: the root :data:`LEDGER_NAME` is the symlink- :func:`open_run_ledger` leaves pointing at it, and a walk of every run under- ``$HOME`` on 2026-08-30 found 677 such symlinks and not one real file there."""+ """The ledger file a run actually has, or ``None``: ``telemetry/cost.jsonl``, the only one+ read (a walk of every run under ``$HOME`` on 2026-08-30 found 677 root ``cost_ledger.jsonl``+ files, every one a symlink to it)."""p = Path(workspace) / TELEMETRY_LEDGERreturn p if p.is_file() else Nonedef open_run_ledger(workspace: str | Path) -> CostLedger:- """The run's live ledger, ready to append to.-- Writes to ``telemetry/cost.jsonl`` and leaves ``<run>/cost_ledger.jsonl`` as a- relative symlink to it, so there is exactly one physical copy and the run- layout's ``live_ledger_path`` / ``telemetry/usage.jsonl`` alias keep working."""- root = Path(workspace)- path = root / TELEMETRY_LEDGER- try:- path.parent.mkdir(parents=True, exist_ok=True)- alias = root / LEDGER_NAME- if not alias.exists() and not alias.is_symlink():- os.symlink(TELEMETRY_LEDGER, alias)- except OSError as e: # pragma: no cover - read-only dir / no symlinks- log.debug("cost: could not prepare the run ledger at %s: %s", path, e)- return CostLedger(path)+ """The run's ledger, ``telemetry/cost.jsonl``, ready to append to (the file is created by+ its first row)."""+ return CostLedger(Path(workspace) / TELEMETRY_LEDGER)#: context._stage is the same function; ledger already imports from context. NOT truediff --git a/harness/codeverse3d/cost/reconstruct.py b/harness/codeverse3d/cost/reconstruct.pydeleted file mode 100644index e9d05949..00000000--- a/harness/codeverse3d/cost/reconstruct.py+++ /dev/null@@ -1,463 +0,0 @@-"""Rebuild a cost ledger from an EXISTING run directory.--The harness has been recording ``Usage`` since day one, just not as a ledger:-per-call rows live in ``trajectories/*/transcript.jsonl``, session totals in-``result.json``, judge verdicts in ``record.rounds[].judgment.usage``, and the-plan / texture / pairwise costs only in ``events.jsonl``. This module stitches-those into :class:`~codeverse3d.cost.types.CallCost` rows so the audit and-``3dcode cost`` work on runs recorded *before* the ledger existed.--Nothing here validates against the pydantic ``RunRecord``: old records must keep-loading even when the schema moves on, so everything is read as raw JSON.--Double-counting rules (same order as the row sources):--1. agent sessions — per-turn rows when a transcript has per-call usage, else one- aggregate row from ``result.json``; the label+round is then *covered*;-2. gemini-cli sessions additionally carry the raw ``stats`` envelope in- ``stdout.json`` — with ``recheck=True`` the row is rebuilt from it (per served- model, correct cached/prompt split) instead of the stored ``Usage``;-3. judge verdicts — from the record's rounds (``rNN_cli.json`` re-judges are- outside the run's budget and are skipped);-4. priced events (``plan.done``, ``texture.*``, ``pairwise.done``) that no row- above covers — aggregates (``round.done`` / ``run.done`` / ``texture.done``)- are skipped;-5. a final ``residual`` row for whatever ``record.total_usage`` still has left,- so the ledger always reconciles to the recorded total.-"""--from __future__ import annotations--import logging-import re-from dataclasses import dataclass, field-from pathlib import Path-from typing import Any--from codeverse3d.contracts.common import Usage-from codeverse3d.contracts.run import RunId-from codeverse3d.cost.ledger import price_call-from codeverse3d.cost.types import CallCost, Role, Stage, role_for_stage, stage_for_label-from codeverse3d.proc import read_json_or_none, read_jsonl_lenient-from codeverse3d.record.record import SUBRUN_DIRS--log = logging.getLogger(__name__)--#: events whose cost duplicates rows we already emit-#: events whose ``cost_usd`` RESTATES money the per-call rows already carry — turning one into a-#: priced row double-counts. ``candidate.done`` repeats its own round's total and-#: ``candidate.selected`` the sum over every candidate, so a best-of-N run reconstructed from-#: events alone billed its candidates two to three times (2026-08-30).-_AGGREGATE_EVENTS = frozenset({"round.done", "run.done", "texture.done",- "candidate.done", "candidate.selected"})---def _read_json(path: Path) -> dict[str, Any]:- return read_json_or_none(path, errors="replace") or {}---def _read_jsonl(path: Path) -> list[dict[str, Any]]:- return read_jsonl_lenient(path, dicts_only=True)---def _usage(d: Any) -> Usage:- if isinstance(d, Usage):- return d- if not isinstance(d, dict):- return Usage()- return Usage(- backend=str(d.get("backend") or ""),- model=str(d.get("model") or ""),- input_tokens=int(d.get("input_tokens") or 0),- output_tokens=int(d.get("output_tokens") or 0),- cached_tokens=int(d.get("cached_tokens") or 0),- thoughts_tokens=int(d.get("thoughts_tokens") or 0),- tool_calls=int(d.get("tool_calls") or 0),- cost_usd=float(d.get("cost_usd") or 0.0),- latency_ms=int(d.get("latency_ms") or 0),- )---@dataclass-class RunLedger:- """Rows of one run plus the metadata a cost report needs."""-- run: str = ""- path: Path = Path()- track: str = ""- language: str = ""- generator: str = ""- status: str = ""- stop_reason: str = ""- n_rounds: int = 0- round_scores: list[float | None] = field(default_factory=list)- round_built: list[bool | None] = field(default_factory=list) # per round: did its build (+repair) succeed- recorded_usd: float = 0.0- wall_s: float = 0.0 # time the run was actually working (budget elapsed / stage+round durations)- span_s: float = 0.0 # first to last event — includes time queued behind other runs- model_s: float = 0.0- selected_candidate: str = "" # "c1" when the run ran best-of-N and c1 won- source: str = "reconstructed" # live (the run wrote its own ledger) | reconstructed- rows: list[CallCost] = field(default_factory=list)- notes: list[str] = field(default_factory=list)-- @property- def ledger_usd(self) -> float:- return sum(r.cost_usd for r in self.rows)---def _row(usage: Usage, *, run: str, stage: Stage, label: str, rnd: int | None, source: str,- role: Role | None = None, ts: float = 0.0, outcome: str = "ok", n_calls: int = 1,- reprice: bool = False, backend: str = "", model: str = "") -> CallCost:- cost, price_fields = price_call(usage, backend=backend or usage.backend,- model=model or usage.model, reprice=reprice)- return CallCost(- ts=ts, run=run, round=rnd, stage=stage, role=role or role_for_stage(stage), label=label,- input_tokens=usage.input_tokens, cached_tokens=usage.cached_tokens,- output_tokens=usage.output_tokens, thoughts_tokens=usage.thoughts_tokens,- tool_calls=usage.tool_calls, cost_usd=cost, recorded_usd=float(usage.cost_usd),- latency_ms=usage.latency_ms,- cache_hit=usage.cached_tokens > 0, outcome=outcome, n_calls=n_calls, source=source,- **price_fields,- )---# --------------------------------------------------------------------------- agent sessions-def _gemini_cli_usages(stdout: dict[str, Any]) -> list[Usage]:- """Per served model from a gemini-cli ``stats`` envelope. ``tokens.prompt`` is- the TOTAL prompt (cached included) — sessions recorded before that fix stored- ``tokens.input`` and under-billed by ~3-4x."""- models = (((stdout.get("stats") or {}).get("models")) or {})- out: list[Usage] = []- for name, part in models.items():- tok = (part or {}).get("tokens") or {}- cached = int(tok.get("cached") or 0)- prompt = tok.get("prompt")- total = int(prompt) if prompt is not None else int(tok.get("input") or 0) + cached- api = (part or {}).get("api") or {}- out.append(Usage(- backend="gemini-cli", model=str(name), input_tokens=total, cached_tokens=cached,- output_tokens=int(tok.get("candidates") or 0), thoughts_tokens=int(tok.get("thoughts") or 0),- tool_calls=int(((stdout.get("stats") or {}).get("tools") or {}).get("totalCalls") or 0),- latency_ms=int(api.get("totalLatencyMs") or 0),- ))- return out---#: a retried / wrapped-up agent session records itself as ``<label>.a2`` / ``<label>.wrapup``-_ATTEMPT_SUFFIX = re.compile(r"\.(a\d+|wrapup)$")---def _base_label(label: str) -> str:- """The *job* label a session label was derived from.-- A retry is recorded as ``<label>.a2``, a wrap-up as ``<label>.wrapup`` and a- best-of-N candidate as ``c<k>:<label>``, while the ``generate.done`` event that- summarises the whole job carries the plain job label. De-duplication has to- use this key: keying it on the session's own label left the retry's dollars in- a different bucket, the job's pool ran dry, and the event was counted a SECOND- time. That artifact — not lost money — was most of the "$4.80 invisible to- record.total_usage" in docs/COST.md §6; §6 now quotes the corrected figure."""- lab = label.split(":", 1)[-1] if ":" in label else label- return _ATTEMPT_SUFFIX.sub("", lab)---def _session_rows(d: Path, run: str, *, recheck: bool,- candidate: str = "") -> tuple[list[CallCost], str, int | None, float]:- """Rows for one ``trajectories/<label>_rNN`` directory. ``candidate`` is the- ``_cand/c<k>`` sub-workspace this session belongs to (best-of-N), if any."""- result = _read_json(d / "result.json")- label = str(result.get("label") or d.name)- rnd = result.get("round")- rnd = int(rnd) if isinstance(rnd, (int, float)) else None- stage = stage_for_label(str(result.get("kind") or "") if "repair" in str(result.get("kind") or "") else label)- if candidate:- stage, label = Stage.CANDIDATE, f"{candidate}:{label}"- outcome = "ok" if result.get("ok") else str(result.get("exit_reason") or "error")- duration = float(result.get("duration_s") or 0.0)- session = _usage(result.get("usage"))- rows: list[CallCost] = []-- if recheck and session.backend == "gemini-cli":- parts = _gemini_cli_usages(_read_json(d / "stdout.json"))- if parts:- for part in parts:- rows.append(_row(part, run=run, stage=stage, label=label, rnd=rnd,- source="stdout", outcome=outcome, reprice=True))- return rows, label, rnd, duration-- turns = [r for r in _read_jsonl(d / "transcript.jsonl") if isinstance(r.get("usage"), dict)]- if turns:- for turn in turns:- rows.append(_row(_usage(turn["usage"]), run=run, stage=stage, label=label, rnd=rnd,- source="transcript", ts=float(turn.get("t") or 0.0), outcome=outcome,- reprice=recheck))- return rows, label, rnd, duration- if session.input_tokens or session.output_tokens or session.cost_usd:- # ``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 1- rows.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, duration---def _live_rows(root: Path, *, run: str, recheck: bool) -> list[CallCost]:- """The run's own ledger rows, when it wrote one while it ran.-- Rows carry their run name from the writer; stamp the directory's name on any- that do not (a battery copies runs around). ``recheck`` re-prices them from- today's table exactly like a reconstructed row."""- try:- from codeverse3d.cost.ledger import load_ledger-- rows = load_ledger(root)- except Exception as e: # noqa: BLE001 - a corrupt ledger falls back to reconstruction- log.debug("cost: live ledger unreadable in %s: %s", root, e)- return []- out: list[CallCost] = []- for row in rows:- if not row.run:- row.run = run- if recheck:- usage = Usage(backend=row.backend, model=row.model_id or row.model,- input_tokens=row.input_tokens, cached_tokens=row.cached_tokens,- output_tokens=row.output_tokens, thoughts_tokens=row.thoughts_tokens,- tool_calls=row.tool_calls, cost_usd=row.recorded_usd)- cost, fields = price_call(usage, backend=row.backend, model=row.model_id or row.model,- cache_write_tokens=row.cache_write_tokens, reprice=True)- row = row.model_copy(update={"cost_usd": cost, **fields})- out.append(row)- return out---def _trajectory_dirs(root: Path) -> list[tuple[Path, str]]:- """Every session directory of a run as ``(dir, candidate)``, including scene- asset sub-workspaces (``_assets/<name>/trajectories/*``) and best-of-N- candidates (``_cand/c*``, whose sessions are tagged with the candidate id)."""- out: list[tuple[Path, str]] = []- for traj in sorted(root.glob("trajectories")) + sorted(root.glob("_assets/*/trajectories")):- out += [(p, "") for p in sorted(traj.iterdir()) if p.is_dir()]- for traj in sorted(root.glob("_cand/*/trajectories")):- cand = traj.parent.name- out += [(p, cand) for p in sorted(traj.iterdir()) if p.is_dir()]- return out---# --------------------------------------------------------------------------- one run-def reconstruct_run(run_dir: str | Path, *, recheck: bool = False) -> RunLedger:- """Build the ledger of one run directory.-- A run that wrote its own ledger while it ran (``telemetry/cost.jsonl``, see- :mod:`codeverse3d.cost.instrument`) is read from that ledger — one priced row- per real call, nothing inferred. Runs recorded before the ledger existed are- rebuilt from ``trajectories/`` + ``record.json`` + ``events.jsonl`` exactly as- before, so all 61 reference runs keep auditing.-- ``recheck=True`` re-prices every row with the CURRENT price table (and rebuilds- gemini-cli rows from the raw CLI stats) — that is the audit view; the default- keeps the dollars the run was actually billed."""- root = Path(run_dir)- record = _read_json(root / "record.json")- spec = record.get("spec") or {}- backends = spec.get("backends") or {}- extra = record.get("extra") or {}- total = _usage(record.get("total_usage"))- run = root.name- led = RunLedger(- run=run, path=root,- track=str(spec.get("track") or ""), language=str(spec.get("language") or ""),- generator=str(backends.get("generator") or ""),- status=str(record.get("status") or ""), stop_reason=str(extra.get("stop_reason") or ""),- recorded_usd=float(total.cost_usd),- )- cands = _read_json(root / "rounds" / "candidates.json") or (extra.get("candidates") or {})- if isinstance(cands, dict) and cands.get("selected") is not None:- led.selected_candidate = f"c{cands['selected']}"- rounds = record.get("rounds") or []- led.n_rounds = len(rounds)-- live_rows = _live_rows(root, run=run, recheck=recheck)- led.source = "live" if live_rows else "reconstructed"- led.rows += live_rows-- covered: dict[str, float] = {} # JOB label (see _base_label) -> $ already accounted for by- # its session(s); a ``generate.done`` event within that- # budget is a duplicate, retries and wrap-ups included- model_s = 0.0-- for d, cand in (() if live_rows else _trajectory_dirs(root)):- rows, label, rnd, duration = _session_rows(d, run, recheck=recheck, candidate=cand)- if rows:- led.rows += rows- key = _base_label(label)- covered[key] = covered.get(key, 0.0) + sum(r.recorded_usd for r in rows)- model_s += duration-- judged_rounds: set[int] = set()- for r in rounds:- idx = int(r.get("index") or 0)- judgment = r.get("judgment") or {}- led.round_scores.append((judgment or {}).get("overall"))- led.round_built.append((r.get("build") or {}).get("ok"))- ju = _usage(judgment.get("usage"))- if ju.input_tokens or ju.cost_usd:- judged_rounds.add(idx)- model_s += ju.latency_ms / 1000.0- if (ju.input_tokens or ju.cost_usd) and not live_rows:- n = int(judgment.get("n_samples") or 1)- degraded = bool((judgment.get("raw") or {}).get("degraded")) if isinstance(judgment.get("raw"), dict) else False- led.rows.append(_row(ju, run=run, stage=Stage.JUDGE, label=str(judgment.get("rubric") or "judge"),- rnd=idx, source="record", role=Role.JUDGE, n_calls=max(1, n),- outcome="degraded" if degraded else "ok", reprice=recheck,- backend=str(judgment.get("judge_backend") or ju.backend) or ju.backend,- model=str(judgment.get("judge_backend") or ju.model) or ju.model))-- # ------------------------------------------------------------------ events- first_t = last_t = 0.0- active_s = 0.0- for ev in _read_jsonl(root / "events.jsonl"):- name = str(ev.get("event") or "")- t = float(ev.get("t") or 0.0)- first_t = first_t or t- # folded in from a SECOND full pass over the same file, which added only this- if name == "stage.done" and str(ev.get("stage")) == "plan":- model_s += float(ev.get("duration_s") or 0.0)- if name in ("run.done", "run.failed", "stop", "budget.exceeded"):- last_t = max(last_t, t) # a post-hoc texture pass is not part of the run's wall clock- elif not last_t:- last_t = t- if name in ("stage.done", "round.done"):- active_s += float(ev.get("duration_s") or 0.0)- if name == "judge.done":- model_s += float(ev.get("duration_s") or 0.0) if int(ev.get("round", -1)) not in judged_rounds else 0.0- cost = ev.get("cost_usd")- if live_rows or not isinstance(cost, (int, float)) or not cost or name in _AGGREGATE_EVENTS:- continue- rnd = ev.get("round")- rnd = int(rnd) if isinstance(rnd, (int, float)) else None- label = str(ev.get("label") or name.split(".")[0])- if name == "generate.done":- key = _base_label(label)- if covered.get(key, 0.0) >= float(cost) - 0.0005:- covered[key] = covered[key] - float(cost)- continue # a session already contributed this spend- if name == "judge.done" and rnd in judged_rounds:- continue- stage = Stage.TEXTURE if name.startswith("texture") else stage_for_label(label)- role = Role.IMAGE if name == "texture.generated" else role_for_stage(stage)- model = str(ev.get("model") or "")- usage = Usage(model=model, cost_usd=float(cost))- row = _row(usage, run=run, stage=stage, label=label, rnd=rnd, source=f"event:{name}",- role=role, ts=t, model=model)- row.price_source = "event-cost" # cost known, tokens are not recorded by the event- led.rows.append(row)- led.span_s = max(0.0, last_t - first_t)- elapsed_min = float(((extra.get("budget") or {}).get("elapsed_min")) or 0.0)- # events are emitted from run creation, so the span of a queued bench run counts- # hours it spent waiting for a worker slot; the stage/round clocks are the honest- # ones (the budget's own elapsed restarts on ``3dcode resume``).- led.wall_s = max(active_s, elapsed_min * 60.0) or led.span_s- led.model_s = model_s-- # ------------------------------------------------------------------ residual- if total.cost_usd:- spent = sum(r.recorded_usd for r in led.rows)- tok_in = total.input_tokens - sum(r.input_tokens for r in led.rows)- tok_out = total.output_tokens - sum(r.output_tokens for r in led.rows)- tok_cached = total.cached_tokens - sum(r.cached_tokens for r in led.rows)- gap = total.cost_usd - spent- if gap < -0.005:- led.notes.append(f"${-gap:.4f} of ledger spend is outside record.total_usage "- "(post-run pass, or a round the budget cut before the total was written)")- if gap > 0.005 or tok_in > 5000:- usage = Usage(backend=total.backend, model=total.model,- input_tokens=max(0, tok_in), output_tokens=max(0, tok_out),- cached_tokens=max(0, tok_cached), cost_usd=max(0.0, gap))- row = _row(usage, run=run, stage=Stage.OTHER, label="unattributed", rnd=None,- source="residual", role=Role.OTHER)- row.cost_usd = row.recorded_usd = max(0.0, gap)- row.price_source = "residual"- led.rows.append(row)- drift = led.ledger_usd - led.recorded_usd- if recheck and abs(drift) > 0.005:- led.notes.append(f"re-priced total differs from record.total_usage by ${drift:+.4f}")- return led---# --------------------------------------------------------------------------- compare cells-def reconstruct_cell(cell_dir: str | Path, *, recheck: bool = False) -> RunLedger:- """A ``eval/bench/compare_backends.py`` one-shot cell (``gen/attempt*`` + ``eval/eval.json``)."""- root = Path(cell_dir)- cell = _read_json(root / "cell.json")- run = RunId(battery="", rel=f"{root.parent.name}/{root.name}").slug # <prompt>__<arm>- led = RunLedger(run=run, path=root, track="static_object", language="blender",- generator=str(cell.get("arm") or root.name),- status=str(cell.get("status") or ""), round_scores=[cell.get("score")],- round_built=[cell.get("build_ok")], n_rounds=1,- wall_s=float(cell.get("wall_s") or 0.0), model_s=float(cell.get("gen_seconds") or 0.0))- live = _live_rows(root, run=run, recheck=recheck)- if live: # the cell wrote its own ledger while it ran: one priced row per real call- led.source = "live"- led.rows += live- led.recorded_usd = float(cell.get("gen_cost_usd") or 0.0) + float(cell.get("judge_cost_usd") or 0.0)- return led- for attempt in sorted(root.glob("gen/attempt*")):- result = _read_json(attempt / "result.json")- usage = _usage(result.get("usage"))- if usage.cost_usd or usage.output_tokens:- led.rows.append(_row(usage, run=run, stage=Stage.BASELINE, label="oneshot", rnd=0,- source="trajectory", outcome="ok" if result.get("ok") else "error",- reprice=recheck))- judgment = (_read_json(root / "eval" / "eval.json").get("judgment") or {})- ju = _usage(judgment.get("usage"))- if ju.cost_usd or ju.input_tokens:- led.rows.append(_row(ju, run=run, stage=Stage.JUDGE, label=str(judgment.get("rubric") or "judge"),- rnd=0, source="record", role=Role.JUDGE,- n_calls=int(judgment.get("n_samples") or 1), reprice=recheck))- led.recorded_usd = float(cell.get("gen_cost_usd") or 0.0) + float(cell.get("judge_cost_usd") or 0.0)- return led---def find_runs(root: str | Path) -> list[Path]:- """Every run directory under ``root`` (a dir with ``record.json``), plus one-shot- compare cells (a dir with ``cell.json`` and no ``run/record.json``). Nested- sub-workspaces (``_assets/``, ``_cand/``) are part of their parent, not runs."""- base = Path(root)- if (base / "record.json").is_file():- return [base]- out: list[Path] = []- for path in sorted(base.rglob("record.json")):- rel = path.parent.relative_to(base).parts- if SUBRUN_DIRS & set(rel):- continue- d = path.parent- if d.name == "run" and (d.parent / "cell.json").is_file():- d = d.parent # a compare-battery cell: name it <prompt>/<arm>, not "run"- out.append(d)- known = {str(p) for p in out}- for cell in sorted(base.rglob("cell.json")):- d = cell.parent- if str(d) in known or (d / "run" / "record.json").is_file():- continue- if SUBRUN_DIRS & set(d.relative_to(base).parts):- continue- out.append(d)- return out---def reconstruct(path: str | Path, *, recheck: bool = False) -> RunLedger:- """Dispatch on what the directory looks like (run record vs compare cell)."""- p = Path(path)- if (p / "record.json").is_file():- return reconstruct_run(p, recheck=recheck)- if (p / "run" / "record.json").is_file():- led = reconstruct_run(p / "run", recheck=recheck)- led.run = RunId(battery="", rel=f"{p.parent.name}/{p.name}").slug # <prompt>__<arm>- # a compare cell also spends OUTSIDE the harness run it wraps: the fixed- # evaluator's judge, and a repair arm's extra generations. `run_cell` opens a- # ledger for the cell itself (nested around the run's own), and that spend is- # exactly the §6 gap the audit sees on the two cmp_easy_stool harness cells.- led.rows += _live_rows(p, run=led.run, recheck=recheck)- return led- return reconstruct_cell(p, recheck=recheck)diff --git a/harness/codeverse3d/record/telemetry.py b/harness/codeverse3d/record/telemetry.pyindex 5a9fea1e..097e3c78 100644--- a/harness/codeverse3d/record/telemetry.py+++ b/harness/codeverse3d/record/telemetry.py@@ -1,18 +1,15 @@-"""Run telemetry: the resolved settings snapshot + the money ledger.+"""Run telemetry: the resolved settings snapshot + the summary of the money ledger.-Three files under ``<run>/telemetry/`` (see docs/RUN_LAYOUT.md):+Beside the ledger itself, ``telemetry/cost.jsonl`` (one priced row per model call, written+while the run happens — ``codeverse3d.cost``), two files under ``<run>/telemetry/`` (see+docs/RUN_LAYOUT.md):* ``settings.json`` — how the run was configured: model id per role, thinkinglevel / temperature / judge samples, rounds + budget, rubric and its contenthash, prompt & cookbook hashes, tool versions, harness git sha, key-pool size,price-table hash, render + limit settings.-* ``usage.jsonl`` — one priced row per model call. The rows are- ``codeverse3d.cost`` ledger rows (``CallCost``): the live ledger of the run when- it has one, else ``cost.reconstruct.reconstruct_run`` rebuilds them from the- trajectories, judge verdicts and priced events. There is exactly one ledger- in the harness; this bucket only gives it a stable place in the run directory.-* ``cost.json`` — the run-layout summary of those rows: totals, per stage, per- role, per model, per round, budget vs spent, wall clock.+* ``cost.json`` — the run-layout summary of the ledger rows: totals, per stage, per+ role, per model, per round, the run's minutes against ``max_minutes``.The same content is mirrored into ``record.telemetry`` so a consumer that onlyhas ``record.json`` sees it too. Nothing here is required for a run to@@ -25,8 +22,6 @@ import hashlibimport inspectimport jsonimport logging-import os-from pathlib import Pathfrom typing import Anyfrom codeverse3d.contracts.common import TRACK_INFO@@ -38,9 +33,9 @@ from codeverse3d.contracts.run import (SettingsSnapshot,StageCost,)-from codeverse3d.cost.ledger import LEDGER_NAME+from codeverse3d.cost.ledger import TELEMETRY_LEDGER, load_ledgerfrom codeverse3d.cost.types import Stage-from codeverse3d.proc import read_json_or_none, write_json_atomic, write_text_atomic+from codeverse3d.proc import read_json_or_none, write_json_atomicfrom codeverse3d.workspace import Workspacelog = logging.getLogger(__name__)@@ -192,30 +187,15 @@ def stage_order() -> tuple[str, ...]:return tuple(s.value for s in Stage)-def live_ledger_path(ws: Workspace) -> Path:- """``<run>/cost_ledger.jsonl`` — the ledger written while the run happens, when there is one."""- return ws.root / LEDGER_NAME---def ledger_rows(ws: Workspace) -> tuple[list[dict[str, Any]], str]:- """Priced per-call rows for the run → ``(rows, source)``.-- Source is ``live`` (the run's own ``cost_ledger.jsonl``), ``reconstructed``- (rebuilt by ``codeverse3d.cost.reconstruct`` from trajectories / verdicts /- events) or ``unavailable``. The cost package owns the pricing and the- double-counting rules — this bucket never re-implements them."""+def ledger_rows(ws: Workspace) -> list[dict[str, Any]]:+ """The run's priced per-call rows, ``telemetry/cost.jsonl`` (none when it has no ledger).+ The cost package owns the pricing and the double-counting rules — this bucket never+ re-implements them."""try:- live = live_ledger_path(ws)- if live.is_file():- from codeverse3d.cost.ledger import load_ledger-- return [r.model_dump(mode="json") for r in load_ledger(live)], "live"- from codeverse3d.cost.reconstruct import reconstruct_run-- return [r.model_dump(mode="json") for r in reconstruct_run(ws.root).rows], "reconstructed"+ return [r.model_dump(mode="json") for r in load_ledger(ws.root)]except Exception as e: # noqa: BLE001 - accounting must never fail a run- log.warning("cost ledger unavailable for %s: %s", ws.root, e)- return [], "unavailable"+ log.warning("cost ledger unreadable for %s: %s", ws.root, e)+ return []def _num(row: dict[str, Any], key: str) -> float:@@ -273,38 +253,16 @@ def cost_summary(record: RunRecord, rows: list[dict[str, Any]]) -> CostSummary:# --------------------------------------------------------------------------- io-def write_usage_jsonl(path: Path, rows: list[dict[str, Any]]) -> Path:- return write_text_atomic(path, "".join(json.dumps(r, ensure_ascii=False, default=str) + "\n" for r in rows))---def _place_usage_rows(ws: Workspace, rows: list[dict[str, Any]], source: str) -> str:- """Write ``telemetry/usage.jsonl`` — or, when the run already carries a live- ledger at its root, alias it there so only one physical copy exists."""- if source == "live":- rel = live_ledger_path(ws).name- if ws.usage_path.exists() and not ws.usage_path.is_symlink():- ws.usage_path.unlink()- if not ws.usage_path.is_symlink():- try:- os.symlink(f"../{rel}", ws.usage_path)- except OSError: # no symlinks here: fall back to a copy- write_usage_jsonl(ws.usage_path, rows)- return rel- write_usage_jsonl(ws.usage_path, rows)- return ws.usage_path.name--def build_telemetry(ws: Workspace, record: RunRecord, *, write: bool = True) -> RunTelemetry:"""Compute (and by default persist) ``telemetry/`` for one run."""- rows, source = ledger_rows(ws)+ rows = ledger_rows(ws)tele = RunTelemetry(settings=settings_snapshot(record),cost=cost_summary(record, rows),environment=dict(record.environment),files={"settings": "telemetry/settings.json","cost": "telemetry/cost.json",- "usage": "telemetry/usage.jsonl",- "usage_source": source,+ "ledger": TELEMETRY_LEDGER,"events": "telemetry/events.jsonl","run_state": "telemetry/run_state.json","stages": "telemetry/stages",@@ -314,7 +272,6 @@ def build_telemetry(ws: Workspace, record: RunRecord, *, write: bool = True) ->ws.ensure_layout()write_json_atomic(ws.settings_path, tele.settings.model_dump(mode="json") if tele.settings else {})write_json_atomic(ws.cost_path, tele.cost.model_dump(mode="json") if tele.cost else {})- _place_usage_rows(ws, rows, source)return telediff --git a/harness/codeverse3d/workspace.py b/harness/codeverse3d/workspace.pyindex 0bd7b9f1..eceeaa1a 100644--- a/harness/codeverse3d/workspace.py+++ b/harness/codeverse3d/workspace.py@@ -195,10 +195,6 @@ class Workspace:def cost_path(self) -> Path:return self.telemetry / "cost.json"- @property- def usage_path(self) -> Path:- return self.telemetry / "usage.jsonl"-@propertydef settings_path(self) -> Path:return self.telemetry / "settings.json"diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex ec948a7e..f39a5c5f 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -164,7 +164,7 @@ codeverse3d/billing.py (SUBSCRIPTION_BACKENDS/bills_usd — which backends take real dollars,so the ledger bills real money and not list price; docs/COST.md §25)tally.py (a block's money = its ledger rows, its lost seconds → StepTime; COST §31)- guard.py reconstruct.py (old runs)+ guard.pyjudges/ base.py (JudgeInput; `round_input` + `plan_summary(plan, language)`, the ONE payloadbuilder and plan digest the in-run judge, `3dcode judge`, calibration, the texturegate and eval all use; the pure replay helpers), rubrics.py + rubrics/*.yaml (defect checklists, the wire@@ -305,9 +305,9 @@ runs/<slug>/judge/r00.json (one-sample judge on quick_render views)stages/<name>.json rounds/rNN.json rounds/candidates.json rounds/aborted_rNN.json (a round thebudget/a crash cut: what it burned, never resumed from)- telemetry/cost.jsonl live ledger: one row per metered call / CLI session, opened by BaseTrack.run- (cost_ledger.jsonl at the root is a relative symlink to it, kept for the run-layout- alias; runs before 2026-08-23 have the root file only)+ telemetry/cost.jsonl THE ledger: one row per metered call / CLI session, opened by BaseTrack.run — the+ only record of money (runs before 2026-09-22 also carry a root cost_ledger.jsonl+ and a telemetry/usage.jsonl symlink to it; nothing reads them)run_state.json status + stages; extra carries budget_snapshot and spec_fingerprint only — the roundhistory is rounds/rNN.json + each round's commit alone (no copy since 2026-09-22)artifacts/ object.glb object.stl|step robot.urdf meshes/ build.json census.jsondiff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.mdindex ee36631e..e532c6d4 100644--- a/harness/docs/INTERFACES.md+++ b/harness/docs/INTERFACES.md@@ -116,7 +116,7 @@ record_call(usage, *, run="", round=None, stage=None, role=None, label="", backefrom codeverse3d.cost.instrument import (run_ledger, metered_chat_model, metered_agent,MeteredAgent, MeteredChatModel, metering_enabled)with run_ledger(ws.root, run=slug): # binds the run, points record_call at <run>/telemetry/cost.jsonl- ... # (+ a <run>/cost_ledger.jsonl symlink for the run-layout alias)+ ... # (its one name: no root alias since 2026-09-22)# NESTS by holding ContextVar tokens (bound_run / bound_ledger) — context-local ONLY, no# process-wide default — so bench.run_bench / compare_backends hold one ledger per prompt# across N threads, and a thread that may bill a model goes through proc.fan_out.@@ -158,8 +158,8 @@ from codeverse3d.models.pricing import price_provenance # (provider, model) -````3dcode cost <slug|path>…` · `3dcode cost --runs-dir <root>` · `3dcode cost cache <slug>` ·`3dcode cost prices [--stale] [--days N] [--unverified]` · `3dcode cost profiles` · `3dcode cost estimate`.-A run with a live ledger is read from it (`RunLedger.source == "live"`); older runs are-reconstructed, so all 61 recorded runs keep auditing.+Every run is read from its ledger alone (`addons.costreport.audit.read_run` / `read_cell` /+`find_runs`); `cost/reconstruct.py` and its rebuild of pre-ledger runs went on 2026-09-22.## agents/```python@@ -631,7 +631,8 @@ from codeverse3d.record._git import read_tree_at, diff_between, changed_files_befrom codeverse3d.record.record import unique_files, SUBRUN_DIRS, BATTERY_MARKERS# unique_files(root, name) -> [Path]: every file called `name` under root ONCE per file on disk (follows# the run/telemetry/trajectories symlink and collapses it; skips SUBRUN_DIRS = {_cand, _assets}) — the- # one walker behind eval/bench/session_stats.py, eval/bench/coupling_stats.py and cost.reconstruct.find_runs+ # one walker behind eval/bench/session_stats.py and eval/bench/coupling_stats.py (costreport.audit.find_runs+ # skips SUBRUN_DIRS the same way)# diff_between(ws, before, after, *, max_bytes=None) -> (text, untruncated size, was_truncated)# changed_files_between(ws, before, after) -> [path]; commit_exists(ws, commit) -> bool# both under GIT_SAFE_DIFF_FLAGS (--no-ext-diff --no-textconv) on top of workspace.GIT_SAFE_FLAGSdiff --git a/harness/docs/RUN_LAYOUT.md b/harness/docs/RUN_LAYOUT.mdindex 307a892b..21bb0cf9 100644--- a/harness/docs/RUN_LAYOUT.md+++ b/harness/docs/RUN_LAYOUT.md@@ -8,7 +8,7 @@ three separate buckets:|---|---|---|| `deliverable/` | **what did I get?** | ONE round, the one a pick chose (`3dcode pick`; `3dcode make` picks by score after the run): its code snapshot, its artifact (`object.glb` / `robot.urdf` + `meshes/` / `frames/` + `preview.gif` / the scene bundle), its contact sheet, `captions.json`, `manifest.json` || `evidence/` (= `artifacts/`) | **why should I believe it?** | every round's own build (`rNN/`), `renders/rNN/`, `gates/rNN/`, `judge/rNN.json`, `measurement.json`, `census.json`, `textures/`, `tool_renders/` |-| `telemetry/` | **what did it cost and how was it configured?** | `settings.json`, `cost.json`, `usage.jsonl`, plus `events.jsonl`, `run_state.json`, `stages/`, `trajectories/` |+| `telemetry/` | **what did it cost and how was it configured?** | `cost.jsonl` (the ledger), `settings.json`, `cost.json`, plus `events.jsonl`, `run_state.json`, `stages/`, `trajectories/` |The run's **identity** stays at the root, where every tool has always looked for it:@@ -23,7 +23,7 @@ runs/<slug>/evidence/ -> artifacts/ (b) the proofartifacts/ the last round's build, rNN/ (each round's own), renders/ gates/ judge/ measurement.json …telemetry/ (c) the accounting- settings.json cost.json usage.jsonl+ cost.jsonl settings.json cost.jsonevents.jsonl -> ../events.jsonlrun_state.json -> ../run_state.jsonstages -> ../stages@@ -56,11 +56,9 @@ symlink. Which side is physical was not a matter of taste:is picked, and both on the fly by `3dcode show` / the exporters for a run thatpredates them — old runs are read as-is, never rewritten. `deliverable/` is self-contained so it can be zipped and handed tosomeone (the flywheel exporter only falls back to it when git cannot answer).- `telemetry/usage.jsonl` is the one file that can be either: a real- reconstructed ledger, or a symlink to the run's live `telemetry/cost.jsonl`- when it has one (the root `cost_ledger.jsonl` is itself a symlink alias; a- real root file exists only in runs before 2026-08-23) — same rule as- everywhere else, one physical copy.+ `telemetry/cost.jsonl` is the ledger itself, appended while the run happens, and has+ one name: the root `cost_ledger.jsonl` and `telemetry/usage.jsonl` symlinks runs written+ before 2026-09-22 carry are no longer written or read.`.gitignore` inside the run ignores `deliverable/`, `telemetry/` and `evidence`(as well as `artifacts/`, `stages/`, `trajectories/`, …) so the derived buckets@@ -132,17 +130,11 @@ produces no diff.configures nothing, kept so old records still read back); avalue a call site hard-codes per task is left empty with `source` saying so,never guessed.-* **`usage.jsonl`** — one priced row per model call, in the+* **`cost.jsonl`** — THE ledger: one priced row per model call or CLI session, in the**`codeverse3d.cost` ledger format** (`CallCost`: tokens, unit prices, price- provenance, stage, role, outcome). There is exactly one ledger in the- harness: when the run wrote a live one (`<run>/telemetry/cost.jsonl`; the root- `cost_ledger.jsonl` is a symlink alias, a real root file only in pre-2026-08-23 runs)- `telemetry/usage.jsonl` is a symlink to it, otherwise- `cost.reconstruct.reconstruct_run` rebuilds the rows from the trajectories,- the recorded judge verdicts and the priced events. This bucket never- re-implements pricing or the double-counting rules — it only gives the ledger- a stable place in the run directory (`telemetry.files["usage_source"]` says- `live` / `reconstructed` / `unavailable`).+ provenance, stage, role, outcome), written by the metered models and agents while the+ run happens. It is the only record of money; a run without one (recorded before+ 2026-08-23) has no rows — nothing is reconstructed.* **`cost.json`** (`CostSummary`) — the run-layout view of those rows: total vsbudget, wall clock vs `max_minutes`, tokens, per stage (`plan / assets / env /zones / baseline / refine / repair / judge / pairwise / texture / …`), perdiff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.pyindex 58257992..d69e8f68 100644--- a/harness/tests/core/test_run_layout.py+++ b/harness/tests/core/test_run_layout.py@@ -19,7 +19,7 @@ def test_create_makes_the_three_buckets(tmp_path: Path):evidence = ws.root / EVIDENCE_DIRassert evidence.is_symlink() and os.readlink(evidence) == "artifacts"assert evidence.resolve() == ws.artifacts.resolve()- assert ws.cost_path.parent == ws.telemetry and ws.usage_path.name == "usage.jsonl"+ assert ws.cost_path.parent == ws.telemetrydef test_telemetry_aliases_point_at_the_root_files(tmp_path: Path):diff --git a/harness/tests/cost/conftest.py b/harness/tests/cost/conftest.pyindex b9e186d5..0142ee5f 100644--- a/harness/tests/cost/conftest.py+++ b/harness/tests/cost/conftest.py@@ -1,68 +1,36 @@-"""A tiny synthetic run directory — the shapes ``reconstruct`` must understand."""+"""A tiny synthetic run directory: a record and the ledger its calls wrote."""from __future__ import annotations-import jsonfrom pathlib import Pathimport pytest--def _write(path: Path, obj: object) -> None:- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(json.dumps(obj))---def _usage(**kw: object) -> dict[str, object]:- base = {"backend": "gemini", "model": "gemini-3.7-flash", "input_tokens": 0, "output_tokens": 0,- "cached_tokens": 0, "thoughts_tokens": 0, "tool_calls": 0, "cost_usd": 0.0, "latency_ms": 0}- base.update(kw)- return base+from codeverse3d.contracts.artifacts import Judgment+from codeverse3d.contracts.common import Language, Track, Usage+from codeverse3d.contracts.run import RoundRecord, RunRecord, RunStatus, StepTime+from codeverse3d.contracts.spec import Spec+from codeverse3d.cost.ledger import record_call@pytest.fixturedef fake_run(tmp_path: Path) -> Path:- """plan (event only) + one api-agent baseline session (2 turns) + one judge verdict."""+ """plan + one gemini-cli baseline session + one judge verdict, each a ledger row."""ws = tmp_path / "fake_run"- turns = [- _usage(input_tokens=10_000, output_tokens=100, cost_usd=10_000 * 0.75e-6 + 100 * 3.75e-6),- _usage(input_tokens=20_000, cached_tokens=10_000, output_tokens=200,- cost_usd=10_000 * 0.75e-6 + 10_000 * 0.075e-6 + 200 * 3.75e-6),- ]- session = _usage(backend="api-agent", model="gemini:gemini-3.7-flash",- input_tokens=30_000, cached_tokens=10_000, output_tokens=300,- cost_usd=sum(float(t["cost_usd"]) for t in turns), latency_ms=1000)- d = ws / "trajectories" / "baseline_r00"- _write(d / "result.json", {"ok": True, "exit_reason": "completed", "label": "baseline", "round": 0,- "kind": "api-agent", "usage": session, "duration_s": 30.0, "turns": 2})- (d / "transcript.jsonl").write_text("\n".join(- json.dumps({"t": 100.0 + i, "kind": "assistant", "turn": i, "usage": u}) for i, u in enumerate(turns)))-- judge_usage = _usage(model="gemini-3.1-pro-preview", input_tokens=12_000, output_tokens=1_000,- cost_usd=12_000 * 2e-6 + 1_000 * 12e-6, latency_ms=5000)- plan_cost = 0.01- total = _usage(input_tokens=42_000, cached_tokens=10_000, output_tokens=1_300,- cost_usd=float(session["cost_usd"]) + float(judge_usage["cost_usd"]) + plan_cost)- _write(ws / "record.json", {- "spec": {"track": "static_object", "language": "blender",- "backends": {"generator": "gemini-cli:gemini-3.6-flash",- "judge": "gemini:gemini-3.1-pro-preview"},- "budget": {"max_minutes": 60.0}},- "status": "passed", "baseline_score": 0.6, "final_score": 0.8, "best_round": 0,- "total_usage": total, "extra": {"stop_reason": "pass", "budget": {"elapsed_min": 2.0}},- "rounds": [{"index": 0, "kind": "baseline", "usage": session, "gates": [],- "judgment": {"rubric": "static_object_v1", "judge_backend": "gemini:gemini-3.1-pro-preview",- "overall": 0.8, "passed": True, "n_samples": 1, "usage": judge_usage}}],- })- (ws / "events.jsonl").write_text("\n".join(json.dumps(e) for e in [- {"t": 1.0, "event": "run.start", "track": "static_object"},- {"t": 2.0, "event": "plan.done", "model": "gemini:gemini-3.7-flash", "cost_usd": plan_cost},- {"t": 3.0, "event": "stage.done", "stage": "plan", "duration_s": 2.0},- {"t": 40.0, "event": "generate.done", "label": "baseline", "cost_usd": round(float(session["cost_usd"]), 4)},- {"t": 50.0, "event": "judge.done", "round": 0, "cost_usd": round(float(judge_usage["cost_usd"]), 4),- "duration_s": 5.0},- {"t": 51.0, "event": "round.done", "round": 0, "kind": "baseline", "duration_s": 48.0,- "cost_usd": round(float(session["cost_usd"]) + float(judge_usage["cost_usd"]), 4)},- {"t": 52.0, "event": "run.done", "cost_usd": round(float(total["cost_usd"]), 4)},- ]))+ ledger = ws / "telemetry" / "cost.jsonl"+ flash = {"backend": "gemini", "model": "gemini-3.7-flash"}+ record_call(Usage(**flash, input_tokens=4_000, output_tokens=900, latency_ms=12_000), run=ws.name,+ stage="plan", label="planner", ledger=ledger)+ record_call(Usage(backend="gemini-cli", model="gemini-3.7-flash", input_tokens=30_000, cached_tokens=10_000,+ output_tokens=300, latency_ms=30_000), run=ws.name, round=0, stage="baseline",+ label="baseline", source="session", n_calls=2, ledger=ledger)+ record_call(Usage(backend="gemini", model="gemini-3.1-pro-preview", input_tokens=12_000, output_tokens=1_000,+ latency_ms=5_000), run=ws.name, label="judge:static_object_v1:r00:s0", ledger=ledger)+ spec = Spec(id="fake", track=Track.STATIC_OBJECT, language=Language.BLENDER, prompt="a chair")+ judgment = Judgment(rubric="static_object_v1", scores={}, overall=0.8, passed=True)+ rec = RunRecord(spec=spec, workspace=str(ws), status=RunStatus.MAX_ROUNDS, extra={"stop_reason": "max_rounds"},+ steps=[StepTime(step="plan", wall_s=20.0)],+ rounds=[RoundRecord(index=0, kind="baseline", judgment=judgment,+ steps=[StepTime(step="generate", round=0, wall_s=100.0, lost_s=40.0)])])+ (ws / "record.json").write_text(rec.model_dump_json())return wsdiff --git a/harness/tests/cost/test_audit_read.py b/harness/tests/cost/test_audit_read.pynew file mode 100644index 00000000..925951ee--- /dev/null+++ b/harness/tests/cost/test_audit_read.py@@ -0,0 +1,65 @@+"""Reading finished runs back: the ledger is the money, the record the facts."""++from __future__ import annotations++import json+import shutil+from pathlib import Path++import pytest++from codeverse3d.addons.costreport.audit import audit_runs, find_runs, read_run+from codeverse3d.contracts.common import Usage+from codeverse3d.cost.ledger import load_ledger, record_call+from codeverse3d.cost.types import Stage+++def test_a_run_reads_as_its_ledger_rows_and_its_record_facts(fake_run: Path):+ led = read_run(fake_run)+ assert led.ledger_usd == pytest.approx(sum(r.cost_usd for r in load_ledger(fake_run)))+ assert {r.stage for r in led.rows} == {Stage.PLAN, Stage.BASELINE, Stage.JUDGE}+ assert led.track == "static_object" and led.stop_reason == "max_rounds" and led.round_built == [None]+ assert led.minutes == pytest.approx((20.0 + 60.0) / 60), "the run's minutes, not its span"+ assert led.model_s == pytest.approx(47.0)+++def test_a_run_without_a_ledger_is_left_out(fake_run: Path, tmp_path: Path):+ bare = tmp_path / "pre_ledger"+ shutil.copytree(fake_run, bare)+ shutil.rmtree(bare / "telemetry")+ assert audit_runs([tmp_path]).n_runs == 1+++def test_find_runs_skips_sub_workspaces(tmp_path: Path):+ (tmp_path / "a").mkdir()+ (tmp_path / "a" / "record.json").write_text("{}")+ sub = tmp_path / "a" / "_assets" / "x"+ sub.mkdir(parents=True)+ (sub / "record.json").write_text("{}")+ assert find_runs(tmp_path) == [tmp_path / "a"]+++def test_an_ab_batterys_control_and_variant_cells_stay_two_runs(fake_run: Path, tmp_path: Path):+ """ab_plan lays a prompt's cells out as ``arms/<arm>/cells/<id>/<generator>``: naming a+ cell by its last two segments gave the control and the variant ONE label."""+ for arm in ("control", "variant"):+ cell = tmp_path / "out" / "arms" / arm / "cells" / "chair" / "harness_gemini-cli"+ shutil.copytree(fake_run, cell / "run")+ (cell / "cell.json").write_text(json.dumps({"prompt_id": "chair", "arm": "harness:x", "kind": "harness"}))+ audit = audit_runs([tmp_path / "out"])+ assert sorted(r.run for r in audit.runs) == ["control__chair__harness_gemini-cli",+ "variant__chair__harness_gemini-cli"]+++def test_a_losing_candidate_is_waste(fake_run: Path, tmp_path: Path):+ 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)+ for k in (0, 1):+ record_call(usage, stage=Stage.CANDIDATE, round=0, label=f"baseline_c{k}", source="session",+ ledger=ws / "telemetry" / "cost.jsonl")+ assert read_run(ws).selected_candidate == "c1"+ (item,) = [w for w in audit_runs([ws]).waste if w.kind == "lost_candidate"]+ assert item.usd > 0 and "c0 lost to c1" in item.detaildiff --git a/harness/tests/cost/test_cli.py b/harness/tests/cost/test_cli.pyindex 7aee9222..c4262858 100644--- a/harness/tests/cost/test_cli.py+++ b/harness/tests/cost/test_cli.py@@ -27,7 +27,7 @@ def test_cost_show_recheck_reports_drift(fake_run: Path):def test_cost_show_on_an_empty_tree_fails_cleanly(tmp_path: Path):r = runner.invoke(app, ["cost", "show", str(tmp_path)])- assert r.exit_code != 0 and "no runs" in r.output+ assert r.exit_code != 0 and "no run with a cost ledger" in r.outputdef test_cost_prices_and_estimate():@@ -49,9 +49,9 @@ def _live_ledger(run: Path, rows: list[dict]) -> None:def test_cost_takes_a_bare_run_path_or_slug(fake_run: Path):r = runner.invoke(app, ["cost", str(fake_run)])assert r.exit_code == 0, r.output- assert "reconciliation" in r.output and "reconstructed" in r.output+ assert "| fake_run | static_object |" in r.outputr = runner.invoke(app, ["cost", fake_run.name, "--runs-dir", str(fake_run.parent)])- assert r.exit_code == 0 and "reconciliation" in r.output+ assert r.exit_code == 0 and "| fake_run | static_object |" in r.outputdef test_cost_runs_dir_aggregates_a_battery(fake_run: Path, tmp_path: Path):@@ -59,8 +59,8 @@ def test_cost_runs_dir_aggregates_a_battery(fake_run: Path, tmp_path: Path):assert r.exit_code == 0 and "runs: 1" in r.output-def test_a_live_ledger_is_read_instead_of_being_reconstructed(fake_run: Path):- """The run wrote its own rows while it ran: they ARE the ledger."""+def test_the_ledger_is_the_money(fake_run: Path):+ """The run wrote its own rows while it ran: they ARE the money, whatever the record says."""_live_ledger(fake_run, [{"run": fake_run.name, "round": 0, "stage": "baseline", "role": "generator","backend": "gemini", "provider": "gemini", "model": "gemini-3.7-flash",@@ -72,10 +72,7 @@ def test_a_live_ledger_is_read_instead_of_being_reconstructed(fake_run: Path):])r = runner.invoke(app, ["cost", str(fake_run)])assert r.exit_code == 0, r.output- assert "1 live / 0 reconstructed" in r.output- assert "$0.0999" in r.output # the ledger's own judge dollar, not the reconstruction's $0.036- # what the ledger does not explain is reported, never hidden- assert "unattributed" in r.output or "difference" in r.output+ assert "$0.0999" in r.output and "$0.1200" in r.output # the ledger's own dollarsdef test_cost_reports_the_calls_per_key_when_the_ledger_recorded_them(fake_run: Path, tmp_path: Path):diff --git a/harness/tests/cost/test_instrument.py b/harness/tests/cost/test_instrument.pyindex bc88105a..b677888c 100644--- a/harness/tests/cost/test_instrument.py+++ b/harness/tests/cost/test_instrument.py@@ -129,13 +129,11 @@ def test_get_coding_agent_hands_out_a_metered_agent(monkeypatch: pytest.MonkeyPaassert isinstance(registry.get_coding_agent("gemini-cli:m"), MeteredAgent)-def test_run_ledger_writes_telemetry_and_leaves_a_root_alias(tmp_path: Path):+def test_run_ledger_writes_the_one_telemetry_file(tmp_path: Path):with run_ledger(tmp_path, run="r1"):MeteredChatModel(FakeChat()).generate(ChatRequest(messages=[ChatMessage.user("x")], label="planner"))- assert (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- assert len(load_ledger(tmp_path)) == 1 == len(load_ledger(alias))+ assert (tmp_path / "telemetry" / "cost.jsonl").is_file() and len(load_ledger(tmp_path)) == 1+ assert not (tmp_path / "cost_ledger.jsonl").exists(), "the root alias went on 2026-09-22"def test_accounting_never_breaks_a_call(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):@@ -176,7 +174,6 @@ def test_post_hoc_work_never_creates_a_partial_ledger(tmp_path: Path):MeteredChatModel(FakeChat()).generate(ChatRequest(messages=[ChatMessage.user("x")], label="judge:static_object_v1:r00:s0"))assert not (tmp_path / "telemetry" / "cost.jsonl").exists()- assert not (tmp_path / "cost_ledger.jsonl").exists()# but a run that already keeps one is appended towith run_ledger(tmp_path, run="old"):MeteredChatModel(FakeChat()).generate(ChatRequest(messages=[ChatMessage.user("x")], label="planner"))diff --git a/harness/tests/cost/test_ledger.py b/harness/tests/cost/test_ledger.pyindex bd300f53..0cea7513 100644--- a/harness/tests/cost/test_ledger.py+++ b/harness/tests/cost/test_ledger.py@@ -86,14 +86,11 @@ def test_a_bound_ledger_takes_the_calls_that_name_no_file(tmp_path: Path):assert len(load_ledger(tmp_path / "default.jsonl")) == 1 # the binding is gone with the block-def test_a_run_has_exactly_one_ledger_file_and_the_root_name_is_its_symlink(tmp_path: Path):- """``open_run_ledger`` writes only ``telemetry/cost.jsonl``; the root- ``cost_ledger.jsonl`` others still open by name is a symlink to it, so the reader- must not treat that name as a second, separate ledger."""+def test_a_run_has_exactly_one_ledger_file(tmp_path: Path):+ """``open_run_ledger`` writes only ``telemetry/cost.jsonl``, and that is the only name read."""led = open_run_ledger(tmp_path)assert existing_ledger_path(tmp_path) is None # nothing written yetrecord_call(_usage(), run="r", stage="baseline", ledger=led)assert existing_ledger_path(tmp_path) == tmp_path / "telemetry" / "cost.jsonl"- alias = tmp_path / "cost_ledger.jsonl"- assert alias.is_symlink() and len(load_ledger(alias)) == 1- assert len(load_ledger(tmp_path)) == 1 # the directory reads the one file, not two+ assert sorted(p.name for p in tmp_path.rglob("*.jsonl")) == ["cost.jsonl"]+ assert len(load_ledger(tmp_path)) == 1diff --git a/harness/tests/cost/test_reconstruct.py b/harness/tests/cost/test_reconstruct.pydeleted file mode 100644index 78c9b8ff..00000000--- a/harness/tests/cost/test_reconstruct.py+++ /dev/null@@ -1,142 +0,0 @@-"""Rebuilding a ledger from a run directory: reconcile, never double count."""--from __future__ import annotations--import json-from pathlib import Path--import pytest--from codeverse3d.addons.costreport.audit import audit_runs-from codeverse3d.contracts.common import Usage-from codeverse3d.cost import find_runs, reconstruct-from codeverse3d.cost.types import Role, Stage---def test_reconstructs_and_reconciles(fake_run: Path):- led = reconstruct(fake_run)- assert abs(led.ledger_usd - led.recorded_usd) < 1e-6, "rows must reconcile to record.total_usage"- stages = {r.stage for r in led.rows}- assert Stage.BASELINE in stages and Stage.JUDGE in stages and Stage.PLAN in stages- assert led.track == "static_object" and led.round_scores == [0.8] and led.round_built == [None]---def test_generate_event_does_not_double_count_its_session(fake_run: Path):- led = reconstruct(fake_run)- gen = [r for r in led.rows if r.stage is Stage.BASELINE]- assert len(gen) == 2, "two transcript turns, not the session row and not the event"- assert all(r.source == "transcript" for r in gen)- assert not [r for r in led.rows if r.source == "event:generate.done"]---def test_a_retried_session_does_not_double_count_its_generate_event(fake_run: Path, tmp_path: Path):- """Reconstruction counts a retried generation exactly once."""- import shutil-- ws = tmp_path / "retried"- shutil.copytree(fake_run, ws)- # split the baseline into a first attempt and a retry, as the harness records them- first = ws / "trajectories" / "baseline_r00"- retry = ws / "trajectories" / "baseline.a2_r00"- shutil.copytree(first, retry)- res = json.loads((retry / "result.json").read_text())- res["label"] = "baseline.a2"- for key, factor in (("input_tokens", 0.5), ("output_tokens", 0.5), ("cached_tokens", 0.5),- ("cost_usd", 0.5)):- res["usage"][key] = type(res["usage"][key])(res["usage"][key] * factor)- (retry / "result.json").write_text(json.dumps(res))- turns = [json.loads(line) for line in (retry / "transcript.jsonl").read_text().splitlines()]- for t in turns:- for key in ("input_tokens", "output_tokens", "cached_tokens", "cost_usd"):- t["usage"][key] = type(t["usage"][key])(t["usage"][key] * 0.5)- (retry / "transcript.jsonl").write_text("\n".join(json.dumps(t) for t in turns))- # the event summarises the WHOLE job (first attempt + retry) under the job label- events = [json.loads(line) for line in (ws / "events.jsonl").read_text().splitlines()]- for ev in events:- if ev.get("event") == "generate.done":- ev["cost_usd"] = round(ev["cost_usd"] * 1.5, 6)- (ws / "events.jsonl").write_text("\n".join(json.dumps(e) for e in events))-- led = reconstruct(ws)- assert not [r for r in led.rows if r.source == "event:generate.done"], \- "the retry's dollars cover the job event; nothing may be added on top"- gen = [r for r in led.rows if r.stage is Stage.BASELINE]- assert len(gen) == 4 and all(r.source == "transcript" for r in gen) # 2 turns x 2 attempts---def test_judge_row_carries_the_judge_model(fake_run: Path):- row = next(r for r in reconstruct(fake_run).rows if r.role is Role.JUDGE)- assert row.model == "gemini-3.1-pro-preview" and row.provider == "gemini"- assert row.price_source == "exact"---def test_missing_session_falls_back_to_the_event(fake_run: Path, tmp_path: Path):- """A CLI backend that left no trajectory still shows up, from its event."""- import shutil-- ws = tmp_path / "no_traj"- shutil.copytree(fake_run, ws)- shutil.rmtree(ws / "trajectories")- led = reconstruct(ws)- gen = [r for r in led.rows if r.stage is Stage.BASELINE]- assert len(gen) == 1 and gen[0].source == "event:generate.done"- assert abs(led.ledger_usd - led.recorded_usd) < 0.001---def test_wall_clock_ignores_time_queued_before_the_run_started(fake_run: Path):- led = reconstruct(fake_run)- assert led.wall_s == pytest.approx(120.0) # budget elapsed_min=2.0, not the 51 s event span---def test_find_runs_skips_sub_workspaces(tmp_path: Path):- (tmp_path / "a").mkdir()- (tmp_path / "a" / "record.json").write_text("{}")- sub = tmp_path / "a" / "_assets" / "x"- sub.mkdir(parents=True)- (sub / "record.json").write_text("{}")- assert find_runs(tmp_path) == [tmp_path / "a"]---def test_best_of_n_losers_are_attributed_and_counted_as_waste(fake_run: Path, tmp_path: Path):- """Candidate sub-workspaces attribute their spend to the parent run."""- import shutil-- ws = tmp_path / "cands"- shutil.copytree(fake_run, ws)- for k in (0, 1):- dst = ws / "_cand" / f"c{k}" / "trajectories" / "baseline_r00"- dst.parent.mkdir(parents=True)- shutil.copytree(fake_run / "trajectories" / "baseline_r00", dst)- (ws / "rounds").mkdir(exist_ok=True)- (ws / "rounds" / "candidates.json").write_text(json.dumps({"n": 2, "selected": 1}))-- 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 codeverse3d.cost.instrument import run_ledger- from codeverse3d.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.detaildiff --git a/harness/tests/flywheel_cli/conftest.py b/harness/tests/flywheel_cli/conftest.pyindex 06f9d081..e74c5449 100644--- a/harness/tests/flywheel_cli/conftest.py+++ b/harness/tests/flywheel_cli/conftest.py@@ -25,6 +25,7 @@ from codeverse3d.contracts.artifacts import (from codeverse3d.contracts.common import Backends, Language, Track, Usagefrom codeverse3d.contracts.run import RoundRecord, RunRecord, RunStatus, StepTimefrom codeverse3d.contracts.spec import Spec+from codeverse3d.cost.ledger import record_callfrom codeverse3d.workspace import Workspace@@ -112,6 +113,12 @@ def make_fake_run(build=BuildResult(ok=True, language=language.value),))(ws.artifacts / "object.glb").write_bytes(b"glTF\x02\x00\x00\x00" + bytes([len(scores) - 1]) * 16) # the last round+ # the ledger its calls wrote: the planner, then one session per round ($0.06, the record's total)+ ledger = ws.telemetry / "cost.jsonl"+ record_call(Usage(backend="gemini", model="gemini-3.7-flash", input_tokens=500, cost_usd=0.02),+ run=slug, stage="plan", label="planner", ledger=ledger)+ for r in rounds[:2]:+ record_call(r.usage, run=slug, round=r.index, stage=r.kind, label=r.kind, source="session", ledger=ledger)rec = RunRecord(spec=spec, workspace=str(ws.root), status=RunStatus.MAX_ROUNDS, rounds=rounds,total_usage=Usage(cost_usd=0.06, input_tokens=2000, output_tokens=1000),steps=[StepTime(step="plan", wall_s=30.0, lost_s=6.0)], finished_at=datetime.now(UTC),diff --git a/harness/tests/flywheel_cli/test_run_layout_cli.py b/harness/tests/flywheel_cli/test_run_layout_cli.pyindex 11829c15..2d456603 100644--- a/harness/tests/flywheel_cli/test_run_layout_cli.py+++ b/harness/tests/flywheel_cli/test_run_layout_cli.py@@ -20,7 +20,6 @@ from codeverse3d.record.record import load_record, package_runfrom codeverse3d.record.telemetry import (build_telemetry,ledger_rows,- live_ledger_path,load_telemetry,stage_order,)@@ -78,7 +77,7 @@ def test_package_run_builds_a_stable_independent_and_loadable_handover(fake_run)assert (ws.deliverable / "object.glb").is_file() and (ws.deliverable / "sheet.png").is_file()for f in d.files:assert (ws.root / f.path).is_file() and f.bytes > 0 and len(f.sha256) == 64- assert ws.settings_path.is_file() and ws.cost_path.is_file() and ws.usage_path.is_file()+ assert ws.settings_path.is_file() and ws.cost_path.is_file()cost = json.loads(ws.cost_path.read_text())assert cost["total_usd"] == rec.total_usage.cost_usdassert cost["by_round"]@@ -109,41 +108,20 @@ def test_package_run_builds_a_stable_independent_and_loadable_handover(fake_run)assert (ws.artifacts / "object.glb").read_bytes().startswith(b"glTF")-def test_telemetry_handles_reconstructed_live_and_unavailable_ledgers(fake_run, monkeypatch):+def test_telemetry_summarises_the_runs_own_ledger(fake_run):ws, rec = fake_run- # Historic records reconstruct rows and reconcile them to the recorded total.- rows, source = ledger_rows(ws)- assert source == "reconstructed" # no live cost_ledger.jsonl in this run- assert rows and all("stage" in r and "cost_usd" in r for r in rows)+ ledger = ws.root / "telemetry" / "cost.jsonl"+ ledger.unlink()+ assert ledger_rows(ws) == [] # a run with no ledger has no rows (nothing is reconstructed)tele = build_telemetry(ws, rec, write=False)- cost = tele.cost- assert cost is not None- assert cost.total_usd == rec.total_usage.cost_usd- assert abs(cost.ledger_usd - cost.total_usd) < 1e-9- assert cost.by_role["judge"] > 0 and cost.unattributed_usd > 0 # judge verdicts + the residual- assert {s.stage for s in cost.by_stage} <= set(stage_order())-- # A live ledger is aliased, not copied.- live = live_ledger_path(ws)- live.write_text(json.dumps({"stage": "plan", "role": "planner", "label": "plan", "cost_usd": 0.5,- "model": "gemini-3.7-flash", "n_calls": 1}) + "\n")+ assert tele.cost is not None and tele.cost.n_calls == 0 and tele.settings is not None+ ledger.write_text(json.dumps({"stage": "plan", "role": "planner", "label": "plan", "cost_usd": 0.5,+ "model": "gemini-3.7-flash", "n_calls": 1}) + "\n")tele = build_telemetry(ws, rec)- assert tele.files["usage_source"] == "live"- assert ws.usage_path.is_symlink() and ws.usage_path.resolve() == live.resolve()+ assert tele.files["ledger"] == "telemetry/cost.jsonl"assert tele.cost is not None and tele.cost.by_stage[0].stage == "plan"-- # A core-only install still emits settings and the record-level total.- import codeverse3d.record.telemetry as T-- def boom(*_a, **_k):- raise ImportError("codeverse3d.cost is not installed")-- monkeypatch.setattr(T, "live_ledger_path", boom)- rows, source = T.ledger_rows(ws)- assert rows == [] and source == "unavailable"- tele = T.build_telemetry(ws, rec, write=False)- assert tele.cost is not None and tele.cost.total_usd == rec.total_usage.cost_usd- assert tele.cost.n_calls == 0 and tele.settings is not None # settings never depend on the ledger+ assert {s.stage for s in tele.cost.by_stage} <= set(stage_order())+ assert not (ws.telemetry / "usage.jsonl").exists(), "one ledger, one name"def test_the_settings_snapshot_records_the_temperature_the_track_planned_at(tmp_path):diff --git a/harness/tests/orchestrator_tracks/test_round_economics.py b/harness/tests/orchestrator_tracks/test_round_economics.pyindex 3935d86d..fd7ee4fc 100644--- a/harness/tests/orchestrator_tracks/test_round_economics.py+++ b/harness/tests/orchestrator_tracks/test_round_economics.py@@ -257,14 +257,13 @@ def test_a_regression_changes_nothing_about_the_loop_and_every_round_reports_itsassert [c["wasted"] for c in costs] == [False] * 4 and "previous_best" not in costs[1]assert costs[2]["judge_usd"] > 0 and costs[2]["run_usd"] >= costs[1]["run_usd"]assert rec.extra["cost_by_stage"]["judge"] > 0 and rec.extra["cost_by_stage"]["refine"] > 0- # ... and the run opens its own priced ledger (telemetry/cost.jsonl + the root alias) even- # outside the CLI; the ONE writer is the metered agent/model, so the injected fakes- # (a bare FakeAgent, a FakeJudge with no chat model) leave it empty — see- # test_cost_accounting for the rows a metered session writes+ # ... and the run opens its own priced ledger (telemetry/cost.jsonl) even outside the CLI;+ # the ONE writer is the metered agent/model, so the injected fakes (a bare FakeAgent, a+ # FakeJudge with no chat model) leave it empty — see test_cost_accounting for the rows a+ # metered session writesfrom codeverse3d.cost.ledger import load_ledger- assert (ws.root / "cost_ledger.jsonl").is_symlink() # -> telemetry/cost.jsonl, created on first row- assert load_ledger(ws.root) == []+ assert load_ledger(ws.root) == [] and not (ws.root / "cost_ledger.jsonl").exists()def test_a_lint_stuck_run_keeps_every_score_instead_of_deferring_the_verdict(tmp_path, chair_plan, settings):