Skip to content

Official Codebase of 3DCodeVerse

Python

Record: telemetry lives only in record.json (no cost.json/settings.json), drop dead snapshot/manifest/RunId fields; fix claude_end stdout scan, EventLog non-dict rows, one --version timeout

gaoypengced06fd56856
diff --git a/eval/bench/data/loop/README.md b/eval/bench/data/loop/README.md
index 8faaa9e8..0eab7a3e 100644
--- a/eval/bench/data/loop/README.md
+++ b/eval/bench/data/loop/README.md
@@ -17,7 +17,7 @@ and read back as `bench.loop.LedgerRow`, one JSON object per line:
| `languages` | the loop's languages (`scene_threejs`, `scene_blender`) |
| `variant` | the variant name (`argon`) |
| `version_from` → `version_to` | `variant.toml` version before and after: an `accept` bumps it by one; a `rollback` keeps it (working edits discarded) or, when the iteration was itself the latest accept, returns to `version_from` of that accept |
-| `variant_hash` | the overlay fingerprint after the decision: `prompts.variants.variant_hash` — the number every run record of the iteration carries (`extra.variant.hash`, `SettingsSnapshot.variant_hash`; `README.md` is left out of it, so a README edit never moves it) — and the same `hash` the snapshot's `snapshot.json` records, so a snapshot pairs with the runs it was measured on. Only an overlay the variant layer does not know (a tmp tree in the tests) falls back to the loop's own sha256[:12] over every file |
+| `variant_hash` | the overlay fingerprint after the decision: `prompts.variants.variant_hash` — the number every run record of the iteration carries (`extra.variant.hash`; `README.md` is left out of it, so a README edit never moves it) — and the same `hash` the snapshot's `snapshot.json` records, so a snapshot pairs with the runs it was measured on. Only an overlay the variant layer does not know (a tmp tree in the tests) falls back to the loop's own sha256[:12] over every file |
| `battery_sha` | sha256[:12] over the iteration's `battery_*.yaml` files — the prompts the verdict was measured on |
| `verdicts` | language → `keep` / `revert` / `inconclusive` from `compare_<lang>.json` (empty when the iteration was never compared: iteration 0, or an accept on diagnosis alone) |
| `decision` | `accept` or `rollback` |
diff --git a/eval/bench/loop.py b/eval/bench/loop.py
index 0d18ac4e..b128d6ff 100644
--- a/eval/bench/loop.py
+++ b/eval/bench/loop.py
@@ -333,7 +333,7 @@ class VariantPaths:
def ledger_hash(self) -> str:
"""THE hash of this overlay: ``prompts.variants.variant_hash`` — what every run record of the
- iteration carries (``extra.variant.hash``, ``SettingsSnapshot.variant_hash``) — whenever these
+ iteration carries (``extra.variant.hash``) — whenever these
paths are the real overlay; :meth:`overlay_hash` only for a tmp tree. The ledger row and the
snapshot both write this one, so a snapshot can be paired with the runs it was measured on."""
api = _variants_api_or_none()
diff --git a/harness/codeverse3d/addons/dataset/sample.py b/harness/codeverse3d/addons/dataset/sample.py
index d2d728e0..ed3b88ea 100644
--- a/harness/codeverse3d/addons/dataset/sample.py
+++ b/harness/codeverse3d/addons/dataset/sample.py
@@ -102,7 +102,7 @@ class SampleMeta(BaseModel):
prompt_hashes: dict[str, str] = Field(default_factory=dict)
telemetry: dict[str, Any] = Field(
default_factory=dict,
- description="compact accounting digest from record.telemetry / telemetry/cost.json ({} when absent)")
+ description="compact accounting digest from record.telemetry ({} when absent)")
def sample_key(ws: Workspace) -> str:
@@ -295,14 +295,12 @@ def build_meta(
has_captions=bool(caps.get("detailed")),
captioner=str((caps.get("provenance") or {}).get("captioner", "")),
prompt_hashes=dict(record.prompt_hashes),
- telemetry=telemetry_digest(ws, record),
+ telemetry=telemetry_digest(record),
)
-def telemetry_digest(ws: Workspace, record: RunRecord) -> dict[str, Any]:
- from codeverse3d.record.telemetry import load_telemetry
-
- tele = load_telemetry(ws, record)
+def telemetry_digest(record: RunRecord) -> dict[str, Any]:
+ tele = record.telemetry
if tele is None:
return {}
out: dict[str, Any] = {}
diff --git a/harness/codeverse3d/addons/gallery/detail.py b/harness/codeverse3d/addons/gallery/detail.py
index 821dc3be..63b667dd 100644
--- a/harness/codeverse3d/addons/gallery/detail.py
+++ b/harness/codeverse3d/addons/gallery/detail.py
@@ -241,11 +241,8 @@ def _renders_panel(entry: RunEntry, urls: UrlMaker, rec: RunRecord) -> str:
anchor="renders", extra_head=sheet)
-def _cost_panel(entry: RunEntry, ws: Workspace, rec: RunRecord) -> str:
- from codeverse3d.record.telemetry import load_telemetry
-
- tele = load_telemetry(ws, rec)
- cost = tele.cost if tele is not None else None
+def _cost_panel(entry: RunEntry, rec: RunRecord) -> str:
+ cost = rec.telemetry.cost if rec.telemetry is not None else None
if cost is None:
rows = "".join(_kv(k, f"${v:.4f}") for k, v in sorted(entry.cost_by_stage.items(), key=lambda kv: -kv[1]))
u = rec.total_usage
@@ -351,7 +348,7 @@ def render_detail(entry: RunEntry, urls: UrlMaker, ws: Workspace, rec: RunRecord
+ _complexity_panel(entry, rec)
+ _measurement_panel(entry, rec)
+ _renders_panel(entry, urls, rec)
- + _cost_panel(entry, ws, rec)
+ + _cost_panel(entry, rec)
+ _code_panel(entry, urls, rec)
+ (_foot_nav(urls, prev, nxt) if urls.has_detail else "")
+ "</main>"
diff --git a/harness/codeverse3d/addons/gallery/index.py b/harness/codeverse3d/addons/gallery/index.py
index 310ad592..d6517718 100644
--- a/harness/codeverse3d/addons/gallery/index.py
+++ b/harness/codeverse3d/addons/gallery/index.py
@@ -137,8 +137,6 @@ def entry_links(ws: Workspace, rec: RunRecord | None, picked: int | None) -> lis
links.append(RunLink(label="frames/", rel=frames_rel, kind="dir"))
if (run / "public" / "assets").is_dir():
links.append(RunLink(label="assets/", rel="public/assets", kind="dir"))
- if (run / "telemetry" / "cost.json").is_file():
- links.append(RunLink(label="cost.json", rel="telemetry/cost.json"))
return links
@@ -172,7 +170,7 @@ def entry_from_record(battery: str, ws: Workspace, rec: RunRecord, *, slug: str
gates = gate_error_summary(rnd)
n_err = sum(gates.values())
minutes = rec.minutes
- digest = telemetry_digest(ws, rec)
+ digest = telemetry_digest(rec)
caps = rec.extra.get("captions") or {}
hero, hero_label, n_views = hero_view(ws, rec, picked)
plan = rec.plan
diff --git a/harness/codeverse3d/agents/backends.py b/harness/codeverse3d/agents/backends.py
index 99c87278..9a4c1315 100644
--- a/harness/codeverse3d/agents/backends.py
+++ b/harness/codeverse3d/agents/backends.py
@@ -185,12 +185,30 @@ def primary_served_model(env: dict[str, Any], model: str) -> str:
return max(served, key=lambda n: float((served[n] or {}).get("costUSD") or 0.0))
+def _stream_errors(stdout: str) -> tuple[str, ...]:
+ """What the CLI itself reported as failing: ``error`` / ``error_status`` of its events (``api_retry`` among
+ them) and a ``result`` event's text. Never the tool results and model text that fill the rest of the stream."""
+ out: list[str] = []
+ for line in stdout.splitlines():
+ if not line.startswith("{"):
+ continue
+ try:
+ ev = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(ev, dict):
+ out += [str(ev[k]) for k in ("error", "error_status") if ev.get(k)]
+ if ev.get("type") == "result" and ev.get("result"):
+ out.append(str(ev["result"]))
+ return tuple(out)
+
+
def claude_end(proc: CompletedProc, env: dict[str, Any] | None, text: str) -> SessionEnd:
sub = str((env or {}).get("subtype", ""))
if proc.timed_out:
return classify_end(proc, ok=False, text=text)
if env is None or proc.rc != 0:
- return classify_end(proc, ok=False, text=text, said=(proc.stderr, proc.stdout))
+ return classify_end(proc, ok=False, text=text, said=(proc.stderr, *_stream_errors(proc.stdout)))
if env.get("is_error") or sub.startswith("error"):
return SessionEnd("budget") if "max_turns" in sub else classify_end(proc, ok=False, text=text, said=(text,))
return classify_end(proc, ok=True, text=text)
diff --git a/harness/codeverse3d/cli/layout_cmd.py b/harness/codeverse3d/cli/layout_cmd.py
index 3e5b1394..ee9a4e55 100644
--- a/harness/codeverse3d/cli/layout_cmd.py
+++ b/harness/codeverse3d/cli/layout_cmd.py
@@ -131,8 +131,8 @@ def print_deliverable(ws: Workspace, record: RunRecord) -> None:
head: dict[str, Any] = {"picked round": f"{s.picked_round} (by {s.method})", "score": fmt_score(s.picked_score)}
d = load_deliverable(ws)
if d is not None:
- head["code"] = f"{d.entry or 'deliverable/src/'} @ {d.commit[:12] or '-'} ({d.code_source})"
- head["total"] = f"{len(d.files)} files, {_human_bytes(d.total_bytes)}"
+ head["code"] = f"{d.entry or 'deliverable/src/'} @ {d.commit[:12] or '-'}"
+ head["total"] = f"{len(d.files)} files, {_human_bytes(sum(f.bytes for f in d.files))}"
console.print(kv_table("deliverable", head))
if d is not None:
console.print(_deliverable_table(d))
@@ -199,14 +199,13 @@ def _roles_table(settings: SettingsSnapshot) -> Table:
def print_cost_and_settings(ws: Workspace, record: RunRecord) -> None:
- from codeverse3d.record.telemetry import build_telemetry, load_telemetry
+ from codeverse3d.record.telemetry import build_telemetry
_section("COST & SETTINGS — token price and the key step settings")
- tele = load_telemetry(ws, record)
- computed = False
- if tele is None or tele.cost is None:
- tele = build_telemetry(ws, record, write=False)
- computed = True
+ tele = record.telemetry
+ computed = tele is None or tele.cost is None
+ if computed:
+ tele = build_telemetry(ws, record)
cost, settings = tele.cost, tele.settings
if cost is not None:
u = cost.tokens
@@ -237,9 +236,9 @@ def print_cost_and_settings(ws: Workspace, record: RunRecord) -> None:
"render": " · ".join(f"{k}={v}" for k, v in settings.render.items()),
}))
if computed:
- console.print("[dim]computed on the fly (no telemetry/ in this run)[/dim]")
+ console.print("[dim]computed on the fly (no telemetry in this record)[/dim]")
else:
- console.print(f"[dim]telemetry: {ws.cost_path} · {ws.telemetry / 'cost.jsonl'} · {ws.settings_path}[/dim]")
+ console.print(f"[dim]ledger: {ws.telemetry / 'cost.jsonl'}[/dim]")
# --------------------------------------------------------------------------- command
diff --git a/harness/codeverse3d/contracts/run.py b/harness/codeverse3d/contracts/run.py
index c4ac6786..8e538fad 100644
--- a/harness/codeverse3d/contracts/run.py
+++ b/harness/codeverse3d/contracts/run.py
@@ -31,7 +31,6 @@ class SkillRead(BaseModel):
deep: bool = Field(default=False, description="transcript: the agent opened a file under its references/ (or "
"its atime says so while the control's references/ are untouched — a shell read the "
"trace cannot parse); atime fallback: a references/*.md atime > mtime")
- deep_measurable: bool = Field(default=True, description="False when the bundle ships no references/ file to probe")
body_tokens: int = 0
reason: str = Field(default="", description="which route attached it, and which finding")
@@ -110,29 +109,6 @@ class RunId(BaseModel):
meaningful = [parts[-1]]
return "__".join(meaningful)
- @property
- def cell(self) -> str | None:
- """The ``cells/<cell>/…`` segment, when the layout has one."""
- parts = self._parts()
- if "cells" in parts:
- i = parts.index("cells")
- if i + 1 < len(parts):
- return parts[i + 1]
- return None
-
- @property
- def arm(self) -> str | None:
- """The ``arms/<arm>/…`` segment, or the directory between the cell and its ``run``."""
- parts = self._parts()
- if "arms" in parts:
- i = parts.index("arms")
- return parts[i + 1] if i + 1 < len(parts) else None
- if "cells" in parts:
- i = parts.index("cells")
- if i + 2 < len(parts) and parts[i + 2] != "run":
- return parts[i + 2]
- return None
-
class RunStatus(StrEnum):
"""Where a run is, and once stopped, why it stopped. Never a verdict."""
@@ -214,7 +190,6 @@ class RoleSettings(BaseModel):
class SettingsSnapshot(BaseModel):
"""Everything that decided how the run ran."""
- schema_version: int = 1
roles: list[RoleSettings] = Field(default_factory=list)
budget: dict[str, Any] = Field(default_factory=dict, description="max_rounds / max_minutes / max_repair_attempts")
candidates: int | None = Field(default=None, description="best-of-N baseline width, resolved")
@@ -228,10 +203,6 @@ class SettingsSnapshot(BaseModel):
key_pool_size: int = Field(default=0, description="number of API keys in the rotating pool")
price_table_version: str = Field(default="", description="content hash of codeverse3d.models.pricing.PRICES")
render: dict[str, Any] = Field(default_factory=dict, description="resolved render settings (size, gpu, sheet)")
- limits: dict[str, Any] = Field(default_factory=dict, description="resolved timeouts / parallelism")
- variant: str = Field(default="", description="per-model prompt/skill variant the run used ('' = base; D105)")
- variant_version: int = Field(default=0, description="the variant's version from its variant.toml (0 = base)")
- variant_hash: str = Field(default="", description="sha256[:12] over the variant overlay's files (name, text), '' = base")
class StageCost(BaseModel):
@@ -247,9 +218,8 @@ class StageCost(BaseModel):
class CostSummary(BaseModel):
- """``telemetry/cost.json``: the run's ledger rows summarised."""
+ """The run's ledger rows summarised (``record.telemetry.cost``)."""
- schema_version: int = 1
total_usd: float = Field(default=0.0, description="the ledger's sum at list price = record.total_usage")
minutes: float | None = Field(default=None, description="RunRecord.minutes when the record was written")
max_minutes: float = 0.0
@@ -263,7 +233,6 @@ class CostSummary(BaseModel):
class RunTelemetry(BaseModel):
- schema_version: int = 1
settings: SettingsSnapshot | None = None
cost: CostSummary | None = None
@@ -280,18 +249,10 @@ class DeliverableFile(BaseModel):
class RunDeliverable(BaseModel):
"""``deliverable/manifest.json``: the handed-over round as paths + hashes + sizes."""
- schema_version: int = 1
- dir: str = "deliverable"
round: int | None = Field(default=None, description="the packaged round")
commit: str = ""
- code_source: str = Field(default="", description="commit | working_tree")
entry: str = Field(default="", description="run-relative entry file of the code snapshot")
files: list[DeliverableFile] = Field(default_factory=list)
- total_bytes: int = 0
- generated_at: datetime | None = None
-
- def by_role(self, role: str) -> list[DeliverableFile]:
- return [f for f in self.files if f.role == role]
class RunRecord(BaseModel):
diff --git a/harness/codeverse3d/doctor.py b/harness/codeverse3d/doctor.py
index 273f3e7a..ba6f73bd 100644
--- a/harness/codeverse3d/doctor.py
+++ b/harness/codeverse3d/doctor.py
@@ -21,13 +21,12 @@ _PY_DEPS = ("pydantic", "pydantic_settings", "typer", "rich", "jinja2", "yaml",
_OPTIONAL_DEPS = {"shapely": "mesh", "networkx": "mesh", "matplotlib": "mesh",
"yourdfpy": "urdf", "scipy": "urdf", "mcp": "mcp",
"moderngl": "graphics", "cadquery": "cad", "pyarrow": "flywheel"}
-_CLI_TIMEOUT = 25
-def _ver(cmd: list[str], timeout: int = _CLI_TIMEOUT) -> tuple[bool, str]:
+def _ver(cmd: list[str]) -> tuple[bool, str]:
if not shutil.which(cmd[0]) and not Path(cmd[0]).is_file():
return False, "not found"
- rc, first = version_line(cmd, timeout=timeout)
+ rc, first = version_line(cmd)
if rc is None:
return False, first
return rc == 0, first[:100] or f"exit {rc}"
@@ -59,7 +58,7 @@ def check_blender() -> list[Row]:
if not b:
return [("blender", "FAIL", f"C3D_BINARIES__BLENDER={s.binaries.blender} is not an executable"
if s.binaries.blender else "no binary (set C3D_BINARIES__BLENDER or put blender-5.2 on PATH)")]
- okk, v = _ver([b, "--version"], timeout=60)
+ okk, v = _ver([b, "--version"])
m = re.search(r"Blender (\d+)\.(\d+)", v)
if okk and m and (int(m[1]), int(m[2])) < BLENDER_MIN:
return [("blender", "FAIL", f"{v} @ {b} — too old, need >= {'.'.join(map(str, BLENDER_MIN))}")]
diff --git a/harness/codeverse3d/proc.py b/harness/codeverse3d/proc.py
index 284effed..71fc405e 100644
--- a/harness/codeverse3d/proc.py
+++ b/harness/codeverse3d/proc.py
@@ -356,7 +356,11 @@ def sha256_file(path: Path | str) -> str:
return h.hexdigest()
-def version_line(cmd: Sequence[str], *, timeout: float) -> tuple[int | None, str]:
+#: the one timeout of every ``--version`` probe (a cold Blender start is the slow one)
+VERSION_TIMEOUT_S = 60.0
+
+
+def version_line(cmd: Sequence[str], *, timeout: float = VERSION_TIMEOUT_S) -> tuple[int | None, str]:
"""``(returncode, first output line)`` of a ``--version``-style probe.
``returncode`` is None when the binary could not be run at all (missing, timed out)
@@ -458,7 +462,7 @@ class EventLog:
append_jsonl_line(self.path, {"t": round(time.time(), 3), "event": event, **data}, self._lock)
def read(self) -> list[dict[str, Any]]:
- return read_jsonl_lenient(self.path, log=log)
+ return read_jsonl_lenient(self.path, log=log, dicts_only=True)
class _NullEvents:
diff --git a/harness/codeverse3d/record/deliverable.py b/harness/codeverse3d/record/deliverable.py
index e4d10b9c..cd6aab29 100644
--- a/harness/codeverse3d/record/deliverable.py
+++ b/harness/codeverse3d/record/deliverable.py
@@ -10,7 +10,6 @@ import hashlib
import json
import logging
import shutil
-from datetime import UTC, datetime
from pathlib import Path
from codeverse3d.contracts.common import ENTRY_FILE, Language, Track
@@ -57,13 +56,11 @@ class _Writer:
def __init__(self, ws: Workspace):
self.ws = ws
self.files: list[DeliverableFile] = []
- self.total = 0
def add_bytes(self, rel: str, data: bytes, role: str) -> None:
dest = self.ws.deliverable / rel
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(data)
- self.total += len(data)
self.files.append(DeliverableFile(path=f"deliverable/{rel}", role=role, bytes=len(data), sha256=hashlib.sha256(data).hexdigest()))
def add_file(self, src: Path, rel: str, role: str) -> None:
@@ -71,13 +68,13 @@ class _Writer:
self.add_bytes(rel, src.read_bytes(), role)
-def _code_tree(ws: Workspace, rnd: RoundRecord | None) -> tuple[dict[str, bytes], str]:
+def _code_tree(ws: Workspace, rnd: RoundRecord | None) -> dict[str, bytes]:
"""``src/**`` (+ ``public/**``) at the round's commit; the working tree only when no round is named."""
if rnd is None:
- return git_history.read_working_tree(ws), "working_tree"
+ return git_history.read_working_tree(ws)
if not (rnd.commit and ws.has_commit(rnd.commit)):
raise git_history.GitReadError(f"round {rnd.index}: commit {rnd.commit[:10] or '(none)'} is not in {ws.root}")
- return git_history.read_tree_at(ws, rnd.commit), "commit"
+ return git_history.read_tree_at(ws, rnd.commit)
def round_outputs(ws: Workspace, rnd: RoundRecord | None) -> Path | None:
@@ -120,24 +117,15 @@ def _copy_captions(ws: Workspace, record: RunRecord, w: _Writer) -> None:
indent=2, ensure_ascii=False).encode(), "captions")
-def _stable_timestamp(previous: RunDeliverable | None, current: RunDeliverable) -> datetime:
- """Keep the old timestamp when the content is byte-identical."""
- if previous is None or previous.generated_at is None:
- return current.generated_at or datetime.now(UTC)
- same = {(f.path, f.sha256) for f in previous.files} == {(f.path, f.sha256) for f in current.files}
- return previous.generated_at if same else (current.generated_at or datetime.now(UTC))
-
-
def build_deliverable(ws: Workspace, record: RunRecord, round_index: int | None, *, clean: bool = True) -> RunDeliverable:
"""(Re)build ``<run>/deliverable/`` for round ``round_index`` and return the manifest (idempotent)."""
rnd = next((r for r in record.rounds if r.index == round_index), None)
- previous = load_deliverable(ws) if ws.deliverable_manifest_path.is_file() else None
out = round_outputs(ws, rnd)
if clean and ws.deliverable.exists():
shutil.rmtree(ws.deliverable)
ws.ensure_layout()
w = _Writer(ws)
- files, code_source = _code_tree(ws, rnd)
+ files = _code_tree(ws, rnd)
for rel, data in sorted(files.items()):
w.add_bytes(rel, data, "code" if rel.startswith("src/") else "bundle")
_copy_artifacts(ws, record, rnd, out, w)
@@ -145,12 +133,10 @@ def build_deliverable(ws: Workspace, record: RunRecord, round_index: int | None,
_copy_captions(ws, record, w)
entry = ENTRY_FILE.get(record.spec.language, "")
manifest = RunDeliverable(
- round=(rnd.index if rnd is not None else None), commit=(rnd.commit if rnd is not None else ""), code_source=code_source,
+ round=(rnd.index if rnd is not None else None), commit=(rnd.commit if rnd is not None else ""),
entry=f"deliverable/{entry}" if entry in files else "",
- files=sorted(w.files, key=lambda f: f.path), total_bytes=w.total,
- generated_at=datetime.now(UTC),
+ files=sorted(w.files, key=lambda f: f.path),
)
- manifest.generated_at = _stable_timestamp(previous, manifest)
write_json_atomic(ws.deliverable_manifest_path, manifest.model_dump(mode="json"))
return manifest
diff --git a/harness/codeverse3d/record/record.py b/harness/codeverse3d/record/record.py
index 34eb1943..f976bb3f 100644
--- a/harness/codeverse3d/record/record.py
+++ b/harness/codeverse3d/record/record.py
@@ -1,7 +1,7 @@
"""Run records: finalise / load / iterate.
``finalize_record`` fills the environment, reads the run's total off its cost ledger, writes
-``telemetry/`` and ``record.json`` atomically. Telemetry is best-effort and never fails a run.
+``record.json`` (telemetry included) atomically. Telemetry is best-effort and never fails a run.
"""
from __future__ import annotations
@@ -27,8 +27,6 @@ from codeverse3d.workspace import Workspace
log = logging.getLogger(__name__)
-_VERSION_TIMEOUT_S = 30
-
class RecordError(RuntimeError):
"""A record.json is missing or invalid."""
@@ -36,7 +34,7 @@ class RecordError(RuntimeError):
# --------------------------------------------------------------------------- environment
def _cmd_first_line(cmd: list[str]) -> str:
- rc, line = version_line(cmd, timeout=_VERSION_TIMEOUT_S)
+ rc, line = version_line(cmd)
return line or f"exit {rc}"
@@ -202,7 +200,7 @@ def complexity_block(record: RunRecord) -> dict[str, Any] | None:
# --------------------------------------------------------------------------- io
def package_run(ws: Workspace, record: RunRecord) -> None:
- """Read the run's total off its ledger (``record.total_usage`` = its sum at list price), write ``telemetry/``.
+ """Read the run's total off its ledger (``record.total_usage`` = its sum at list price).
Best-effort: a failure is logged and the run still gets its ``record.json``."""
from codeverse3d.record.telemetry import build_telemetry
@@ -247,7 +245,7 @@ def join_post_run(ws: Workspace) -> Iterator[None]:
def finalize_record(ws: Workspace, record: RunRecord) -> Path:
- """Fill derived fields + environment, write ``telemetry/`` and ``record.json``."""
+ """Fill derived fields + environment, build the telemetry block and write ``record.json``."""
record.workspace = record.workspace or str(ws.root)
fill_derived(record)
package_run(ws, record)
diff --git a/harness/codeverse3d/record/telemetry.py b/harness/codeverse3d/record/telemetry.py
index 670b9222..4ebcff54 100644
--- a/harness/codeverse3d/record/telemetry.py
+++ b/harness/codeverse3d/record/telemetry.py
@@ -1,5 +1,5 @@
-"""Run telemetry: ``telemetry/settings.json`` (how the run was configured) and ``cost.json``
-(summary of the ledger rows), mirrored into ``record.telemetry``. Builders degrade to what could be read."""
+"""Run telemetry, stored in ``record.telemetry``: how the run was configured (the settings snapshot)
+and a summary of the ledger rows. Builders degrade to what could be read."""
from __future__ import annotations
@@ -18,7 +18,6 @@ from codeverse3d.contracts.run import (
)
from codeverse3d.cost.ledger import load_ledger, summarise
from codeverse3d.cost.types import STAGE_ORDER, CallCost
-from codeverse3d.proc import read_json_or_none, write_json_atomic
from codeverse3d.record.record import effective_score, rubric_of
from codeverse3d.workspace import Workspace
@@ -77,10 +76,8 @@ def settings_snapshot(record: RunRecord) -> SettingsSnapshot:
rubric = rubric_of(record)
s = get_settings()
render = s.render.model_dump(mode="json")
- limits = s.limits.model_dump(mode="json")
keys = len(s.gemini_api_keys)
env = dict(record.environment)
- variant, variant_version, variant_hash = _variant_fields(record)
return SettingsSnapshot(
roles=_role_settings(record),
budget=spec.budget.model_dump(mode="json"),
@@ -95,25 +92,9 @@ def settings_snapshot(record: RunRecord) -> SettingsSnapshot:
key_pool_size=keys,
price_table_version=price_table_version(),
render=render,
- limits=limits,
- variant=variant,
- variant_version=variant_version,
- variant_hash=variant_hash,
)
-def _variant_fields(record: RunRecord) -> tuple[str, int, str]:
- """``(name, version, hash)`` of the variant the run used; the base is ``("", 0, "")``."""
- block = record.extra.get("variant")
- block = block if isinstance(block, dict) else {}
- name = str(block.get("name") or record.environment.get("variant") or record.spec.options.variant or "")
- if not name:
- return "", 0, ""
- version = block.get("version")
- hashed = block.get("hash") or record.prompt_hashes.get("variant", "")
- return name, int(version) if isinstance(version, int) and not isinstance(version, bool) else 0, str(hashed or "")
-
-
_TOOL_KEYS = frozenset({"python", "platform", "host", "blender", "blender_path", "node", "three",
"chrome", "puppeteer", "codeverse3d", "harness_git_sha"})
@@ -151,34 +132,7 @@ def cost_summary(record: RunRecord, rows: list[CallCost]) -> CostSummary:
)
-# --------------------------------------------------------------------------- io
-def build_telemetry(ws: Workspace, record: RunRecord, *, write: bool = True) -> RunTelemetry:
- """Compute (and by default persist) ``telemetry/`` for one run."""
- rows = ledger_rows(ws)
- tele = RunTelemetry(
- settings=settings_snapshot(record),
- cost=cost_summary(record, rows),
- )
- if write:
- 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 {})
- return tele
-
-
-def load_telemetry(ws: Workspace, record: RunRecord | None = None) -> RunTelemetry | None:
- """``record.telemetry`` when present, else the files under ``telemetry/``, else None."""
- if record is not None and record.telemetry is not None:
- return record.telemetry
- cost = read_json_or_none(ws.cost_path)
- settings = read_json_or_none(ws.settings_path)
- if cost is None and settings is None:
- return None
- try:
- return RunTelemetry(
- settings=SettingsSnapshot.model_validate(settings) if settings else None,
- cost=CostSummary.model_validate(cost) if cost else None,
- )
- except Exception as e:
- log.warning("unreadable telemetry in %s: %s", ws.root, e)
- return None
+# --------------------------------------------------------------------------- build
+def build_telemetry(ws: Workspace, record: RunRecord) -> RunTelemetry:
+ """Compute the settings snapshot and the cost summary of one run (``record.telemetry``)."""
+ return RunTelemetry(settings=settings_snapshot(record), cost=cost_summary(record, ledger_rows(ws)))
diff --git a/harness/codeverse3d/skills/telemetry.py b/harness/codeverse3d/skills/telemetry.py
index c22323fb..aa2e38ad 100644
--- a/harness/codeverse3d/skills/telemetry.py
+++ b/harness/codeverse3d/skills/telemetry.py
@@ -63,7 +63,7 @@ def probe_reads(ws_root: Path, materialized: SkillsMaterialized) -> SkillsUsage:
# reading a reference means the bundle was reached, whatever SKILL.md's atime says
surfaced = surfaced or deep
reads.append(SkillRead(
- name=name, surfaced=surfaced, deep=deep, deep_measurable=bool(refs),
+ name=name, surfaced=surfaced, deep=deep,
body_tokens=sel.skill.body_tokens, reason=sel.reason,
))
return SkillsUsage(
diff --git a/harness/codeverse3d/spatial/node.py b/harness/codeverse3d/spatial/node.py
index 7c22dc2c..a7e95dfc 100644
--- a/harness/codeverse3d/spatial/node.py
+++ b/harness/codeverse3d/spatial/node.py
@@ -143,7 +143,7 @@ def parse_node_version(text: str) -> tuple[int, int, int] | None:
@lru_cache(maxsize=8)
def node_version(node_bin: str) -> tuple[int, int, int] | None:
"""``node --version`` for ``node_bin``, or None when it cannot be asked (cached)."""
- rc, line = version_line([node_bin, "--version"], timeout=20)
+ rc, line = version_line([node_bin, "--version"])
return parse_node_version(line) if rc == 0 else None
diff --git a/harness/codeverse3d/workspace.py b/harness/codeverse3d/workspace.py
index a95350c5..900eda08 100644
--- a/harness/codeverse3d/workspace.py
+++ b/harness/codeverse3d/workspace.py
@@ -137,14 +137,6 @@ class Workspace:
def telemetry(self) -> Path:
return self.root / TELEMETRY_DIR
- @property
- def cost_path(self) -> Path:
- return self.telemetry / "cost.json"
-
- @property
- def settings_path(self) -> Path:
- return self.telemetry / "settings.json"
-
@property
def deliverable_manifest_path(self) -> Path:
return self.deliverable / "manifest.json"
diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.md
index b80cd99d..b7b0a777 100644
--- a/harness/docs/ARCHITECTURE.md
+++ b/harness/docs/ARCHITECTURE.md
@@ -209,7 +209,7 @@ tests/ one directory per package area (the count is `pytest --col
One run is one directory, `runs/<slug>/`: `src/` is the code (git, one commit per round),
`artifacts/` the last round's build plus every round's own `artifacts/rNN/`, and a pick writes
-`deliverable/` + `selection.json`; `telemetry/` holds the cost ledger and settings
+`deliverable/` + `selection.json`; `telemetry/` holds the cost ledger
(`workspace.py` names the buckets; `3dcodeverse show <slug>` walks a run).
## 4. Per-language authoring contracts (raw code; the harness owns export)
diff --git a/harness/tests/agents/test_claude_code.py b/harness/tests/agents/test_claude_code.py
index 08e5c395..89282a15 100644
--- a/harness/tests/agents/test_claude_code.py
+++ b/harness/tests/agents/test_claude_code.py
@@ -150,3 +150,15 @@ def test_a_killed_session_is_booked_from_its_messages_and_its_retries_are_provid
assert 0.0 < res.provider_wait_s <= res.duration_s
rec = json.loads((Path(res.transcript_path).parent / "result.json").read_text())
assert rec["usage_from"] == "stream messages"
+
+
+def test_a_crash_is_read_from_the_cli_errors_not_from_the_tool_results_in_the_stream():
+ from codeverse3d.agents.backends import claude_end
+ from codeverse3d.agents.cli_common import CompletedProc
+
+ chatty = json.dumps({"type": "user", "message": "mesh has 503 triangles; see docs on rate limit handling"})
+ ended = claude_end(CompletedProc(rc=1, stdout=chatty, stderr="Segmentation fault", duration_s=1.0), None, "")
+ assert not ended.transient and not ended.rate_limited
+ retry = json.dumps({"type": "system", "subtype": "api_retry", "error": "rate_limit", "error_status": 429})
+ limited = claude_end(CompletedProc(rc=1, stdout=chatty + "\n" + retry, stderr="", duration_s=1.0), None, "")
+ assert limited.rate_limited
diff --git a/harness/tests/core/test_run_layout.py b/harness/tests/core/test_run_layout.py
index 6d256021..14f945da 100644
--- a/harness/tests/core/test_run_layout.py
+++ b/harness/tests/core/test_run_layout.py
@@ -71,3 +71,13 @@ def test_a_planted_git_hook_or_filter_never_runs_on_a_commit(tmp_path):
(ws.src / "model.py").write_text("x = 2\n")
ws.changed_files()
assert not fired.exists(), f"a planted filter ran during changed_files(): {fired.read_text()!r}"
+
+
+def test_the_event_log_skips_rows_that_are_not_objects(tmp_path):
+ from codeverse3d.proc import EventLog
+
+ log = EventLog(tmp_path / "events.jsonl")
+ log.emit("start")
+ with log.path.open("a") as fh:
+ fh.write("12\n\"text\"\n[1]\n")
+ assert [e["event"] for e in log.read()] == ["start"]
diff --git a/harness/tests/flywheel_cli/test_run_layout_cli.py b/harness/tests/flywheel_cli/test_run_layout_cli.py
index 7a4876b8..3eb3fca2 100644
--- a/harness/tests/flywheel_cli/test_run_layout_cli.py
+++ b/harness/tests/flywheel_cli/test_run_layout_cli.py
@@ -12,11 +12,10 @@ from codeverse3d.addons import select
from codeverse3d.cli.main import app
from codeverse3d.cost.types import STAGE_ORDER
from codeverse3d.record.deliverable import build_deliverable, load_deliverable
-from codeverse3d.record.record import load_record, package_run
+from codeverse3d.record.record import package_run
from codeverse3d.record.telemetry import (
build_telemetry,
ledger_rows,
- load_telemetry,
)
runner = CliRunner()
@@ -25,7 +24,7 @@ runner = CliRunner()
# --------------------------------------------------------------------------- packaging
def test_package_run_builds_a_stable_independent_and_loadable_handover(fake_run):
ws, rec = fake_run
- assert load_telemetry(ws, rec) is None and load_deliverable(ws) is None
+ assert rec.telemetry is None and load_deliverable(ws) is None
# Cross the old hard-link fast-path threshold before packaging.
(ws.artifacts / "object.glb").write_bytes(b"glTF" + b"\0" * (300 * 1024))
package_run(ws, rec)
@@ -35,24 +34,17 @@ def test_package_run_builds_a_stable_independent_and_loadable_handover(fake_run)
assert d is not None
roles = {f.role for f in d.files}
assert {"code", "model", "sheet"} <= roles and "manifest" not in roles # it cannot carry its own hash
- assert load_deliverable(ws) == d and d.total_bytes == sum(f.bytes for f in d.files)
+ assert load_deliverable(ws) == d
assert d.round == 1 and d.entry == "deliverable/src/model.py"
assert (ws.deliverable / "src" / "model.py").read_text().startswith("# round 1")
- cost = json.loads(ws.cost_path.read_text())
- assert cost["total_usd"] == rec.total_usage.cost_usd
- assert cost["by_round"]
- settings = json.loads(ws.settings_path.read_text())
- assert {r["role"] for r in settings["roles"]} == {"planner", "generator", "judge", "captioner"}
+ cost, settings = rec.telemetry.cost, rec.telemetry.settings
+ assert cost.total_usd == rec.total_usage.cost_usd and cost.by_round
+ assert {r.role for r in settings.roles} == {"planner", "generator", "judge", "captioner"}
# Rebuilding unchanged content is byte-for-byte stable.
second = build_deliverable(ws, rec, 1)
- assert d.generated_at == second.generated_at # unchanged content → no diff
assert [(f.path, f.sha256) for f in d.files] == [(f.path, f.sha256) for f in second.files]
- # Package metadata can be recovered from files even before the caller saves rec.
- bare = load_record(ws).model_copy(update={"telemetry": None})
- assert load_telemetry(ws, bare) is not None and load_deliverable(ws) is not None
-
# Delivered assets are copies: editing a hand-over cannot mutate evidence.
delivered = ws.deliverable / "object.glb"
assert delivered.stat().st_nlink == 1 and (ws.artifacts / "object.glb").stat().st_nlink == 1
@@ -98,7 +90,7 @@ def test_telemetry_summarises_the_runs_own_ledger(fake_run):
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)
+ tele = build_telemetry(ws, rec)
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.8-flash", "n_calls": 1}) + "\n")
@@ -108,5 +100,5 @@ def test_telemetry_summarises_the_runs_own_ledger(fake_run):
assert not (ws.telemetry / "usage.jsonl").exists(), "one ledger, one name"
# a degraded verdict is unscored in the per-round cost table, never a 0.0
rec.rounds[1].judgment = rec.rounds[1].judgment.model_copy(update={"summary": "judge_error: outage"})
- by_round = build_telemetry(ws, rec, write=False).cost.by_round
+ by_round = build_telemetry(ws, rec).cost.by_round
assert [r["score"] for r in by_round] == [rec.rounds[0].judgment.overall, None]