Official Codebase of 3DCodeVerse
Python
cli: one single-run view — status is show --section status
gaoypengecb73119f8f7
diff --git a/harness/codeverse3d/cli/_common.py b/harness/codeverse3d/cli/_common.pyindex eb6c06e9..57894076 100644--- a/harness/codeverse3d/cli/_common.py+++ b/harness/codeverse3d/cli/_common.py@@ -75,7 +75,8 @@ def print_record_summary(record: RunRecord, ws_root: Path | None = None) -> Nonestatus_col = {"failed": "red", "budget": "yellow", "agent_quota": "yellow"}.get(record.status.value, "cyan")lines = [f"[bold]{spec.prompt}[/bold]",- f"track={spec.track.value} language={spec.language.value} generator={spec.backends.generator}",+ f"track={spec.track.value} language={spec.language.value} generator={spec.backends.generator} "+ f"judge={spec.backends.judge}",f"stop=[{status_col}]{s.stop_reason}[/{status_col}] baseline={fmt_score(s.baseline_score)} "f"picked={fmt_score(s.picked_score)} (round {s.picked_round}, by {s.method}) rounds={s.rounds} "f"cost={fmt_usd(record.total_usage.cost_usd)}",diff --git a/harness/codeverse3d/cli/inspect_cmd.py b/harness/codeverse3d/cli/inspect_cmd.pyindex 32ebf7f4..5fb4f636 100644--- a/harness/codeverse3d/cli/inspect_cmd.py+++ b/harness/codeverse3d/cli/inspect_cmd.py@@ -1,124 +1,25 @@-"""``3dcode status`` / ``3dcode render`` / ``3dcode judge`` — inspect one existing run.--Owns the three read-mostly commands on a finished (or in-flight) workspace: the-``status`` summary (spec / run_state / record / candidates / recent events), the-``render`` command (the working tree, which ends at the run's last round) with its-round-label refusal and the graphics-track frame copy, and the ``judge`` re-judge that-writes ``artifacts/judge/rNN_cli.json`` (default: the round ``addons/select`` picks). Its sibling ``cli/main.py`` owns the typer app,-``make`` / ``resume`` (spec building + track dispatch), ``mcp`` and the registration-of every command — including these three, which it registers with ``app.command``-like ``layout_cmd.py``'s ``show``.+"""``3dcode render`` / ``3dcode judge`` — act on one existing run.++Owns the ``render`` command (the working tree, which ends at the run's last round) with+its round-label refusal and the graphics-track frame copy, and the ``judge`` re-judge that+writes ``artifacts/judge/rNN_cli.json`` (default: the round ``addons/select`` picks). The+single-run VIEW (``show``, and ``status`` = ``show --section status``) is ``layout_cmd.py``'s.+Its sibling ``cli/main.py`` owns the typer app, ``make`` / ``resume`` (spec building + track+dispatch), ``mcp`` and the registration of every command."""from __future__ import annotations-import jsonfrom pathlib import Pathfrom typing import Annotatedimport typerfrom codeverse3d.cli import _common as C-from codeverse3d.cli._common import RunsDirOpt, console, kv_table, print_record_summary, warn+from codeverse3d.cli._common import RunsDirOpt, console, kv_tablefrom codeverse3d.config import get_settingsfrom codeverse3d.contracts.common import Trackfrom codeverse3d.contracts.spec import Spec-from codeverse3d.proc import read_json_or_none---# --------------------------------------------------------------------------- status-def status(- slug: str,- runs_dir: RunsDirOpt = None,- events: Annotated[int, typer.Option("--events", help="tail N events")] = 8,-) -> None:- """Show spec / run_state / record / recent events of a run."""- from codeverse3d.proc import EventLog, holder_of- from codeverse3d.record.record import RecordError, load_record-- ws = C.open_workspace(slug, runs_dir)- spec = C.load_spec(ws)- rows = {- "workspace": ws.root,- "track": spec.track.value,- "language": spec.language.value,- "generator": spec.backends.generator,- "judge": spec.backends.judge,- "prompt": spec.prompt,- }- if (held := holder_of(ws.root)) is not None: # kill THAT pid, never `pkill -f 3dcode`- rows["RUNNING NOW"] = f"pid {held.get('pid', '?')} ({held.get('what') or '3dcode'})"- if ws.state_path.is_file():- try:- state = json.loads(ws.state_path.read_text())- rows["run_state"] = ", ".join(- f"{k}={v}" for k, v in state.items() if not isinstance(v, (dict, list))- )[:300]- except ValueError:- rows["run_state"] = "(unreadable)"- console.print(kv_table("status", rows))- record = None- try:- record = load_record(ws)- print_record_summary(record, ws.root)- except RecordError as e:- warn(f"no record yet ({e})")- _print_candidates(ws)- if record is not None and record.extra.get("texturing"):- t = record.extra["texturing"]- console.print(- kv_table(- "texturing",- {- "shipped": t.get("shipped"),- "delta": t.get("delta"),- "reason": t.get("reason", ""),- "textures": t.get("n_textures", len(t.get("textures", {}) or {})),- "glb": t.get("glb_textured", "") or "-",- },- )- )- console.print(- f"[dim]`3dcode show {ws.root.name}` for the DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS view[/dim]"- )- evs = EventLog(ws.events_path).read()- if evs:- console.print(f"[dim]last {min(events, len(evs))} of {len(evs)} events:[/dim]")- for ev in evs[-events:]:- extra = {k: v for k, v in ev.items() if k not in ("t", "event")}- console.print(- f" {_event_time(ev)} {ev.get('event', '?'):<14} {json.dumps(extra, default=str)[:160]}"- )---def _print_candidates(ws) -> None:- """Best-of-N candidate table + pairwise verdict (rounds/candidates.json), when present."""- data = read_json_or_none(ws.root / "rounds" / "candidates.json")- if data is None:- return- cands = data.get("candidates") or []- rows: dict[str, str] = {"n": str(data.get("n", len(cands)))}- for c in cands:- mark = " *" if c.get("index") == data.get("selected") else ""- score = c.get("score")- rows[f"{c.get('label', c.get('index'))}{mark}"] = (- f"score {score if score is None else round(score, 3)} build_ok={c.get('build_ok')}"- )- pw = data.get("pairwise")- if pw:- rows["pairwise"] = (- f"{pw.get('a')} vs {pw.get('b')} → {pw.get('winner')} (confidence {pw.get('confidence')})"- )- console.print(kv_table("candidates (best-of-N, * = selected)", rows))---def _event_time(ev: dict) -> str:- from datetime import UTC, datetime-- try:- return datetime.fromtimestamp(float(ev["t"]), UTC).strftime("%H:%M:%S")- except (KeyError, TypeError, ValueError, OSError):- return "--:--:--"# --------------------------------------------------------------------------- render / judgediff --git a/harness/codeverse3d/cli/layout_cmd.py b/harness/codeverse3d/cli/layout_cmd.pyindex 3671a0c3..7efa7620 100644--- a/harness/codeverse3d/cli/layout_cmd.py+++ b/harness/codeverse3d/cli/layout_cmd.py@@ -1,7 +1,8 @@-"""``3dcode show`` — one run directory, read in three sections.--``show`` prints one run as three clearly separated sections (docs/RUN_LAYOUT.md):+"""``3dcode show`` — THE single-run view, in four sections (docs/RUN_LAYOUT.md):+* **STATUS** — where the run stands: the run, the rounds, the process holding the run+ lock, run_state, best-of-N candidates, a texture pass, the latest events. It needs no+ record.json, so it works mid-run; ``3dcode status`` is ``show --section status``;* **DELIVERABLE** — what the run produced and where to find it;* **QUALITY EVIDENCE** — why we believe it is good (score, rubric, gates, acceptance);* **COST & SETTINGS** — tokens and dollars per stage, model ids, thinking levels,@@ -13,13 +14,22 @@ is computed on the fly when ``telemetry/`` is not there yet.from __future__ import annotations+import jsonfrom typing import Annotated, Anyimport typerfrom rich.table import Tablefrom codeverse3d.cli import _common as C-from codeverse3d.cli._common import RunsDirOpt, console, fmt_score, fmt_usd, kv_table, warn+from codeverse3d.cli._common import (+ RunsDirOpt,+ console,+ fmt_score,+ fmt_usd,+ kv_table,+ print_record_summary,+ warn,+)from codeverse3d.contracts.run import (CostSummary,DeliverableFile,@@ -43,6 +53,60 @@ def _section(title: str) -> None:console.rule(f"[bold]{title}[/bold]", align="left")+# --------------------------------------------------------------------------- status+def print_status(ws: Workspace, record: RunRecord | None, n_events: int) -> None:+ """Where the run stands. Needs no record.json: a run in flight shows its spec, its lock+ holder, run_state and the latest events."""+ from codeverse3d.proc import EventLog, holder_of, read_json_or_none++ _section("STATUS — where the run stands")+ if record is not None:+ print_record_summary(record, ws.root)+ else:+ spec = C.load_spec(ws)+ console.print(kv_table("run (no record.json yet)", {+ "prompt": spec.prompt, "track": spec.track.value, "language": spec.language.value,+ "generator": spec.backends.generator, "judge": spec.backends.judge, "workspace": ws.root}))+ state: dict[str, Any] = {}+ if (held := holder_of(ws.root)) is not None: # kill THAT pid, never `pkill -f 3dcode`+ state["RUNNING NOW"] = f"pid {held.get('pid', '?')} ({held.get('what') or '3dcode'})"+ if ws.state_path.is_file():+ raw = read_json_or_none(ws.state_path)+ state["run_state"] = "(unreadable)" if raw is None else ", ".join(+ f"{k}={v}" for k, v in raw.items() if not isinstance(v, (dict, list)))[:300]+ if state:+ console.print(kv_table("state", state))+ cands = read_json_or_none(ws.root / "rounds" / "candidates.json")+ if cands is not None:+ rows: dict[str, str] = {"n": str(cands.get("n", len(cands.get("candidates") or [])))}+ for c in cands.get("candidates") or []:+ score = c.get("score")+ rows[f"{c.get('label', c.get('index'))}{' *' if c.get('index') == cands.get('selected') else ''}"] = (+ f"score {score if score is None else round(score, 3)} build_ok={c.get('build_ok')}")+ if pw := cands.get("pairwise"): # a record from before 2026-09-22 (in-loop pairwise)+ rows["pairwise"] = f"{pw.get('a')} vs {pw.get('b')} → {pw.get('winner')} (confidence {pw.get('confidence')})"+ console.print(kv_table("candidates (best-of-N, * = selected)", rows))+ if record is not None and (t := record.extra.get("texturing")):+ console.print(kv_table("texturing", {+ "shipped": t.get("shipped"), "delta": t.get("delta"), "reason": t.get("reason", ""),+ "textures": t.get("n_textures", len(t.get("textures", {}) or {})), "glb": t.get("glb_textured", "") or "-"}))+ evs = EventLog(ws.events_path).read()+ if evs:+ console.print(f"[dim]last {min(n_events, len(evs))} of {len(evs)} events:[/dim]")+ for ev in evs[-n_events:]:+ extra = {k: v for k, v in ev.items() if k not in ("t", "event")}+ console.print(f" {_event_time(ev)} {ev.get('event', '?'):<14} {json.dumps(extra, default=str)[:160]}")+++def _event_time(ev: dict) -> str:+ from datetime import UTC, datetime++ try:+ return datetime.fromtimestamp(float(ev["t"]), UTC).strftime("%H:%M:%S")+ except (KeyError, TypeError, ValueError, OSError):+ return "--:--:--"++# --------------------------------------------------------------------------- (a) deliverableMAX_ROWS_PER_ROLE = 6@@ -84,11 +148,8 @@ def print_deliverable(ws: Workspace, record: RunRecord) -> None:from codeverse3d.record.deliverable import load_deliverable_section("DELIVERABLE — what the run produced")- spec = record.specs = select.summarise(ws.root, record=record)- head = {"prompt": spec.prompt, "track": spec.track.value, "language": spec.language.value,- "stop": s.stop_reason, "picked round": f"{s.picked_round} (by {s.method})",- "score": fmt_score(s.picked_score), "workspace": ws.root}+ 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})"@@ -119,7 +180,6 @@ def print_evidence(ws: Workspace, record: RunRecord) -> None:"rubric": (j.rubric if j else "") or str(record.extra.get("rubric") or "-"),"judge on that round": "-" if j is None else ("pass" if j.passed else "fail"),"gate errors": f"{sum(gates.values())} ({', '.join(f'{g}:{n}' for g, n in gates.items() if n) or 'none'})",- "stop reason": s.stop_reason or "-",}if j is not None:acc = j.acceptance_results or {}@@ -215,21 +275,34 @@ def print_cost_and_settings(ws: Workspace, record: RunRecord) -> None:# --------------------------------------------------------------------------- command+SECTIONS = ("status", "deliverable", "evidence", "cost")+EventsOpt = Annotated[int, typer.Option("--events", help="tail N events (the status section)")]++def show(slug: str,runs_dir: RunsDirOpt = None,- section: Annotated[str, typer.Option("--section", help="all | deliverable | evidence | cost")] = "all",+ section: Annotated[str, typer.Option("--section", help="all | status | deliverable | evidence | cost")] = "all",+ events: EventsOpt = 8,) -> None:- """Show one run in three separated sections: DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS."""+ """One run in four sections: STATUS / DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS."""from codeverse3d.record.record import RecordError, load_recordws = C.open_workspace(slug, runs_dir)+ if section not in ("all", *SECTIONS):+ raise C.CliError(f"unknown --section {section!r} (all | {' | '.join(SECTIONS)})")try:- record = load_record(ws)+ record: RunRecord | None = load_record(ws)except RecordError as e:- raise C.CliError(f"{e} (run `3dcode status {slug}` for a partial view)") from e- if section not in ("all", "deliverable", "evidence", "cost"):- raise C.CliError(f"unknown --section {section!r} (all | deliverable | evidence | cost)")+ if section not in ("all", "status"):+ raise C.CliError(f"{e} (`3dcode status {slug}` shows where the run stands)") from e+ record, missing = None, str(e)+ if section in ("all", "status"):+ print_status(ws, record, events)+ if record is None:+ if section == "all":+ warn(f"{missing}: DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS need the record")+ returnif section in ("all", "deliverable"):print_deliverable(ws, record)if section in ("all", "evidence"):@@ -237,3 +310,7 @@ def show(if section in ("all", "cost"):print_cost_and_settings(ws, record)++def status(slug: str, runs_dir: RunsDirOpt = None, events: EventsOpt = 8) -> None:+ """Where a run stands, mid-run too: `3dcode show <slug> --section status`."""+ show(slug, runs_dir, section="status", events=events)diff --git a/harness/codeverse3d/cli/main.py b/harness/codeverse3d/cli/main.pyindex 0c1fdc13..414d7441 100644--- a/harness/codeverse3d/cli/main.py+++ b/harness/codeverse3d/cli/main.py@@ -5,9 +5,9 @@ packages through function-local imports, so ``3dcode --help`` loads none of themOwns the typer app and every registration, the run-starting commands ``make`` /``resume`` (spec building, reference grounding, track dispatch, budget raising, and the-hand-over after the run), ``pick`` and ``mcp``. The run-inspecting commands ``status`` / ``render`` / ``judge`` live in the-sibling ``cli/inspect_cmd.py`` and are registered here, the way ``layout_cmd.py``'s-``show`` is.+hand-over after the run), ``pick`` and ``mcp``. ``render`` / ``judge`` live in the sibling+``cli/inspect_cmd.py``, the single-run view ``show`` (and its ``status`` alias) in+``cli/layout_cmd.py``; all are registered here."""from __future__ import annotations@@ -660,11 +660,9 @@ def pick(f"gate errors {r.gate_errors} {C.fmt_usd(r.cost_usd)}" for r in rows}))-# --------------------------------------------------------------------------- status / render / judge-# moved to codeverse3d/cli/inspect_cmd.py; imported here so existing importers keep working-from codeverse3d.cli.inspect_cmd import judge, render, status # noqa: E402+# --------------------------------------------------------------------------- render / judge+from codeverse3d.cli.inspect_cmd import judge, render # noqa: E402-app.command()(status)app.command()(render)app.command()(judge)@@ -681,13 +679,11 @@ def mcp(workspace: Annotated[Path, typer.Option("--workspace")]) -> None:)-# --------------------------------------------------------------------------- run layout (show)-# appended registration — see codeverse3d/cli/layout_cmd.py-from codeverse3d.cli.layout_cmd import show as _show # noqa: E402+# --------------------------------------------------------------------------- the single-run view (show, status)+from codeverse3d.cli.layout_cmd import show, status # noqa: E402-app.command(- "show", help="One run in three sections: DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS."-)(_show)+app.command()(show)+app.command()(status)if __name__ == "__main__": # pragma: no coverdiff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex 59973b28..28625049 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -242,8 +242,10 @@ codeverse3d/to read (SKILL.md + references/ + a _claims file pinning its numbers tolive constants). A file that tries to be both is the bug this prevents.cli/ main.py (app wiring, make/resume/mcp + the tools/gallery- commands), inspect_cmd.py (status/render/judge on one existing run),- flywheel_cmd.py, texture_cmd.py, cost_cmd.py (`3dcode cost`), layout_cmd.py, doctor.py+ commands), inspect_cmd.py (render/judge on one existing run), layout_cmd.py+ (THE single-run view: `show` = STATUS / DELIVERABLE / QUALITY EVIDENCE / COST &+ SETTINGS; `status` = `show --section status`, which also reads a run in flight),+ flywheel_cmd.py, texture_cmd.py, cost_cmd.py (`3dcode cost`), doctor.py(`--skills` checks the library + its discovery wiring),skills_cmd.py (`3dcode skills list|show|validate|report` — the read-rate report)eval/bench/ run_bench.py + report.py (the battery launcher, `python -m bench.run_bench` / `bench.report`;diff --git a/harness/docs/RUN_LAYOUT.md b/harness/docs/RUN_LAYOUT.mdindex 294c15b5..24f932bc 100644--- a/harness/docs/RUN_LAYOUT.md+++ b/harness/docs/RUN_LAYOUT.md@@ -168,14 +168,15 @@ carries no `deliverable` block. A `record.json` written before that still valid## Reading a run```-3dcode show <slug> # DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS+3dcode show <slug> # STATUS / DELIVERABLE / QUALITY EVIDENCE / COST & SETTINGS3dcode show <slug> --section cost # just the token price + key step settings-3dcode status <slug> # unchanged (+ a pointer to `3dcode show`)+3dcode status <slug> # = show --section status: the rounds, run_state, the lock holder, events````3dcode show` works on both layouts: when a run has no `telemetry/` yet the costand settings block is computed on the fly (read-only) from the trajectories,-judge verdicts and events already on disk.+judge verdicts and events already on disk. Its STATUS section needs no `record.json`, so it+also reads a run in flight (the other three sections wait for the record).For the money itself across many runs — waste, $ per run, price provenance — use the costpackage's own command, `3dcode cost show <runs-dir>`.diff --git a/harness/tests/flywheel_cli/test_run_layout_cli.py b/harness/tests/flywheel_cli/test_run_layout_cli.pyindex 4d852b59..11829c15 100644--- a/harness/tests/flywheel_cli/test_run_layout_cli.py+++ b/harness/tests/flywheel_cli/test_run_layout_cli.py@@ -210,12 +210,31 @@ def test_show_sections_and_status_share_the_packaged_run(fake_run):assert r.exit_code == 0 and "COST & SETTINGS" in r.output and "DELIVERABLE" not in r.outputassert _show(ws.root.name, ws.root.parent, "--section", "bogus").exit_code == 1- # The legacy status view stays available and points to the richer view.+ # `status` is `show --section status`: the run and its rounds, nothing from the other sections;+ # `show` opens with that same section.ws.write_json(ws.record_path, rec)r = runner.invoke(app, ["status", ws.root.name, "--runs-dir", str(ws.root.parent)])assert r.exit_code == 0, r.output- assert "rounds" in r.output and "passed" in r.output- assert f"3dcode show {ws.root.name}" in r.output+ assert "STATUS" in r.output and "rounds" in r.output and "passed" in r.output and "DELIVERABLE" not in r.output+ assert out.index("STATUS") < out.index("DELIVERABLE")+++def test_show_on_a_run_without_a_record_is_its_status(tmp_path: Path):+ """Mid-run there is no record.json: `show` prints where the run stands and says what the other+ sections wait for (it used to exit 1 and point at `3dcode status`); a named section still fails."""+ from codeverse3d.contracts.common import Backends, Language, Track+ from codeverse3d.contracts.spec import Spec+ from codeverse3d.proc import EventLog+ from codeverse3d.workspace import Workspace++ ws = Workspace(tmp_path / "runs" / "stool").create()+ ws.write_json(ws.spec_path, Spec(id="stool", track=Track.STATIC_OBJECT, language=Language.BLENDER,+ prompt="a small wooden stool", backends=Backends(generator="gemini-cli:x")))+ EventLog(ws.events_path).emit("run.start")+ r = _show("stool", ws.root.parent)+ assert r.exit_code == 0, r.output+ assert "a small wooden stool" in r.output and "run.start" in r.output and "need the record" in r.output+ assert _show("stool", ws.root.parent, "--section", "cost").exit_code == 1def test_show_works_on_an_old_layout_run(tmp_path: Path):