CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
feat(cli): rich rendering + ls/view/stats command wiring
xf gong9cce888aaff7
diff --git a/cubepi/cli/trace/commands.py b/cubepi/cli/trace/commands.pyindex d892eff..60f29b9 100644--- a/cubepi/cli/trace/commands.py+++ b/cubepi/cli/trace/commands.py@@ -1,16 +1,124 @@-"""argparse wiring for `cubepi trace` (stub — completed in Task 6)."""+"""argparse wiring for `cubepi trace`."""from __future__ import annotationsimport argparse+from pathlib import Path++from cubepi.cli.trace import loader, render, stats+from cubepi.cli.trace.follow import follow_run+from cubepi.cli.trace.model import build_forestdef register(subparsers: "argparse._SubParsersAction") -> None:trace = subparsers.add_parser("trace", help="inspect cubepi JSONL traces")trace_sub = trace.add_subparsers(dest="trace_cmd", required=True)- for name, help_text in (- ("ls", "list recent runs"),- ("view", "render a run as a tree"),- ("follow", "stream a run's spans as they complete"),- ("stats", "aggregate stats across runs"),- ):- trace_sub.add_parser(name, help=help_text)++ p_ls = trace_sub.add_parser("ls", help="list recent runs")+ _add_dir(p_ls)+ p_ls.add_argument("-n", type=int, default=20, help="max runs to show")+ p_ls.set_defaults(handler=cmd_ls)++ p_view = trace_sub.add_parser("view", help="render a run as a tree")+ p_view.add_argument("run", help="run id or path to a .jsonl file")+ _add_dir(p_view)+ p_view.add_argument("-v", "--verbose", action="store_true",+ help="expand all span attributes")+ p_view.add_argument("--content", action="store_true",+ help="expand gen_ai content messages")+ p_view.set_defaults(handler=cmd_view)++ p_follow = trace_sub.add_parser("follow", help="stream spans as they complete")+ p_follow.add_argument("run", help="run id or path to a .jsonl file")+ _add_dir(p_follow)+ p_follow.add_argument("--interval", type=float, default=0.5,+ help="poll interval seconds")+ p_follow.add_argument("--timeout", type=float, default=None,+ help="exit after this many idle seconds")+ p_follow.set_defaults(handler=cmd_follow)++ p_stats = trace_sub.add_parser("stats", help="aggregate stats across runs")+ p_stats.add_argument("runs", nargs="*", help="run ids (default: whole dir)")+ _add_dir(p_stats)+ p_stats.add_argument("--by", choices=("model", "tool"), default="model")+ p_stats.add_argument("--since", default=None, help="YYYY-MM-DD lower bound")+ p_stats.set_defaults(handler=cmd_stats)+++def _add_dir(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--dir", default=str(loader.DEFAULT_DIR),+ help="traces directory (default: ./cubepi-traces)")+++def _emit_skipped(skipped: int) -> None:+ if skipped:+ print(f"({skipped} lines skipped (malformed))")+++def cmd_ls(args: argparse.Namespace) -> int:+ directory = Path(args.dir)+ if not directory.exists():+ print(f"no traces directory at {directory}")+ return 1+ runs = loader.list_runs(directory, limit=args.n)+ if not runs:+ print(f"no runs found under {directory}")+ return 1+ render.render_runs(runs)+ return 0+++def cmd_view(args: argparse.Namespace) -> int:+ directory = Path(args.dir)+ try:+ files = loader.resolve_run(args.run, directory)+ except loader.RunResolutionError as exc:+ print(str(exc))+ return 1+ spans, skipped = loader.load_run(files)+ forest = build_forest(spans)+ render.render_tree(forest, verbose=args.verbose, content=args.content)+ _emit_skipped(skipped)+ return 0+++def cmd_follow(args: argparse.Namespace) -> int:+ directory = Path(args.dir)+ try:+ loader.resolve_run(args.run, directory) # validate up front+ except loader.RunResolutionError as exc:+ print(str(exc))+ return 1++ def resolver() -> list[Path]:+ # Re-glob each poll so a cross-midnight run's next-day file is picked up.+ try:+ return loader.resolve_run(args.run, directory)+ except loader.RunResolutionError:+ return []++ follow_run(resolver, interval=args.interval, timeout=args.timeout)+ return 0+++def cmd_stats(args: argparse.Namespace) -> int:+ directory = Path(args.dir)+ if args.runs:+ files: list[Path] = []+ for run in args.runs:+ try:+ files.extend(loader.resolve_run(run, directory))+ except loader.RunResolutionError as exc:+ print(str(exc))+ return 1+ else:+ files = sorted(directory.glob("*/*.jsonl"))+ if args.since:+ files = [f for f in files if f.parent.name >= args.since]+ if not files:+ print(f"no runs found under {directory}")+ return 1+ spans, skipped = loader.load_run(files)+ rows = stats.aggregate(spans, by=args.by)+ render.render_stats(rows, by=args.by)+ _emit_skipped(skipped)+ return 0diff --git a/cubepi/cli/trace/follow.py b/cubepi/cli/trace/follow.pynew file mode 100644index 0000000..be64437--- /dev/null+++ b/cubepi/cli/trace/follow.py@@ -0,0 +1,8 @@+from __future__ import annotations++from pathlib import Path+++def follow_run(path: Path, *, interval: float = 0.5,+ timeout: float | None = None) -> None:+ raise NotImplementedErrordiff --git a/cubepi/cli/trace/render.py b/cubepi/cli/trace/render.pynew file mode 100644index 0000000..8374d69--- /dev/null+++ b/cubepi/cli/trace/render.py@@ -0,0 +1,173 @@+"""rich-based rendering. rich is imported lazily so the package import does+not require the trace-cli extra until something is actually rendered."""+from __future__ import annotations++import json+from typing import TYPE_CHECKING++from cubepi.cli.trace.loader import RunSummary+from cubepi.cli.trace.model import Span, TreeNode+from cubepi.cli.trace.stats import StatRow+from cubepi.tracing import schema++if TYPE_CHECKING: # pragma: no cover+ from rich.console import Console+++class RichMissingError(Exception):+ """Raised when rich is needed but not installed."""+++def _require_rich() -> None:+ try:+ import rich # noqa: F401+ except ImportError as exc: # pragma: no cover+ raise RichMissingError(+ "this command needs rich. Install it via: pip install cubepi[trace-cli]"+ ) from exc+++def _console(record: bool = False) -> "Console":+ _require_rich()+ from rich.console import Console++ return Console(record=record)+++def _dur(span: Span) -> str:+ d = span.duration_ms+ return f"{d:.1f}ms" if d is not None else "…"+++def _node_label(node: TreeNode) -> str:+ sp = node.span+ parts = [f"[bold]{sp.name}[/bold]", _dur(sp)]+ if sp.is_chat:+ model = sp.attributes.get(schema.GEN_AI_REQUEST_MODEL)+ if model:+ parts.append(str(model))+ in_t = sp.attributes.get(schema.GEN_AI_USAGE_INPUT_TOKENS)+ out_t = sp.attributes.get(schema.GEN_AI_USAGE_OUTPUT_TOKENS)+ if in_t is not None or out_t is not None:+ parts.append(f"tok {in_t or 0}/{out_t or 0}")+ elif sp.is_tool:+ tool = sp.attributes.get(schema.GEN_AI_TOOL_NAME)+ if tool:+ parts.append(str(tool))+ if sp.is_error:+ parts.append("[red]ERROR[/red]")+ if sp.is_aborted:+ parts.append("[yellow]aborted[/yellow]")+ if node.orphan:+ parts.append("[dim](orphan)[/dim]")+ return " ".join(parts)+++def _build_rich_tree(roots: list[TreeNode], verbose: bool, content: bool):+ from rich.tree import Tree++ forest = Tree("trace")++ def add(parent_tree, node: TreeNode) -> None:+ branch = parent_tree.add(_node_label(node))+ if verbose:+ for k, v in node.span.attributes.items():+ branch.add(f"[dim]{k}[/dim] = {v!r}")+ if content:+ _add_content(branch, node.span)+ for child in node.children:+ add(branch, child)++ for root in roots:+ add(forest, root)+ return forest+++_CONTENT_KEYS = (+ schema.GEN_AI_INPUT_MESSAGES,+ schema.GEN_AI_OUTPUT_MESSAGES,+ schema.GEN_AI_SYSTEM_INSTRUCTIONS,+ schema.GEN_AI_TOOL_CALL_ARGUMENTS,+ schema.GEN_AI_TOOL_CALL_RESULT,+)+++def _add_content(branch, span: Span) -> None:+ for key in _CONTENT_KEYS:+ raw = span.attributes.get(key)+ if raw is None:+ continue+ try:+ decoded = json.loads(raw) if isinstance(raw, str) else raw+ pretty = json.dumps(decoded, indent=2, ensure_ascii=False)+ except (json.JSONDecodeError, TypeError):+ pretty = str(raw)+ branch.add(f"[cyan]{key}[/cyan]\n{pretty}")+++def render_tree(+ roots: list[TreeNode], *, verbose: bool = False, content: bool = False+) -> None:+ console = _console()+ console.print(_build_rich_tree(roots, verbose, content))+++def render_tree_to_text(+ roots: list[TreeNode], *, verbose: bool = False, content: bool = False+) -> str:+ console = _console(record=True)+ console.print(_build_rich_tree(roots, verbose, content))+ return console.export_text()+++def render_runs(runs: list[RunSummary]) -> None:+ from rich.table import Table++ console = _console()+ table = Table(title="cubepi runs")+ for col in ("started", "run_id", "spans", "status", "duration"):+ table.add_column(col)+ for r in runs:+ started = r.start.isoformat() if r.start else "?"+ dur = f"{r.duration_ms:.0f}ms" if r.duration_ms is not None else "?"+ status = "[red]error[/red]" if r.has_error else "ok"+ table.add_row(started, r.run_id, str(r.span_count), status, dur)+ console.print(table)+++def render_stats(rows: list[StatRow], by: str) -> None:+ from rich.table import Table++ console = _console()+ table = Table(title=f"stats by {by}")+ table.add_column(by)+ table.add_column("calls")+ table.add_column("p50")+ table.add_column("p95")+ table.add_column("err%")+ if by == "model":+ table.add_column("in_tok")+ table.add_column("out_tok")+ table.add_column("cache_tok")+ else:+ table.add_column("aborted")+ for row in rows:+ p50 = row.percentile(50)+ p95 = row.percentile(95)+ cells = [+ row.key,+ str(row.count),+ f"{p50:.0f}ms" if p50 is not None else "?",+ f"{p95:.0f}ms" if p95 is not None else "?",+ f"{row.error_rate * 100:.0f}%",+ ]+ if by == "model":+ cells += [+ str(row.input_tokens),+ str(row.output_tokens),+ str(row.cache_tokens),+ ]+ else:+ cells.append(str(row.aborted))+ table.add_row(*cells)+ console.print(table)diff --git a/tests/cli/trace/test_commands.py b/tests/cli/trace/test_commands.pynew file mode 100644index 0000000..279ee1d--- /dev/null+++ b/tests/cli/trace/test_commands.py@@ -0,0 +1,55 @@+from __future__ import annotations++import json+from pathlib import Path++from cubepi.cli.__main__ import main+++def _write_run(directory: Path):+ f = directory / "2026-05-20" / "r1.jsonl"+ f.parent.mkdir(parents=True)+ rows = [+ {"name": "invoke_agent",+ "context": {"trace_id": "0xt", "span_id": "0x1"}, "parent_id": None,+ "start_time": "2026-05-20T00:00:00Z", "end_time": "2026-05-20T00:00:02Z",+ "status": {"status_code": "UNSET"},+ "attributes": {"cubepi.run_id": "r1",+ "gen_ai.operation.name": "invoke_agent"}},+ {"name": "chat gpt-x",+ "context": {"trace_id": "0xt", "span_id": "0x2"}, "parent_id": "0x1",+ "start_time": "2026-05-20T00:00:00Z", "end_time": "2026-05-20T00:00:01Z",+ "status": {"status_code": "UNSET"},+ "attributes": {"gen_ai.operation.name": "chat",+ "gen_ai.request.model": "gpt-x",+ "gen_ai.usage.input_tokens": 10,+ "gen_ai.usage.output_tokens": 5}},+ ]+ with f.open("w") as fh:+ for r in rows:+ fh.write(json.dumps(r) + "\n")+++def test_ls_lists_run(tmp_path, capsys):+ _write_run(tmp_path)+ rc = main(["trace", "ls", "--dir", str(tmp_path)])+ out = capsys.readouterr().out+ assert rc == 0+ assert "r1" in out+++def test_view_renders_tree(tmp_path, capsys):+ _write_run(tmp_path)+ rc = main(["trace", "view", "r1", "--dir", str(tmp_path)])+ out = capsys.readouterr().out+ assert rc == 0+ assert "invoke_agent" in out+ assert "chat" in out+++def test_stats_by_model(tmp_path, capsys):+ _write_run(tmp_path)+ rc = main(["trace", "stats", "--dir", str(tmp_path), "--by", "model"])+ out = capsys.readouterr().out+ assert rc == 0+ assert "gpt-x" in outdiff --git a/tests/cli/trace/test_render.py b/tests/cli/trace/test_render.pynew file mode 100644index 0000000..f782a03--- /dev/null+++ b/tests/cli/trace/test_render.py@@ -0,0 +1,34 @@+from __future__ import annotations++from cubepi.cli.trace.model import Span, build_forest+from cubepi.cli.trace.render import render_tree_to_text+++def _raw(span_id, parent_id, name, attrs=None, status="UNSET"):+ return {+ "name": name,+ "context": {"trace_id": "0xt", "span_id": span_id},+ "parent_id": parent_id,+ "start_time": "2026-05-20T00:00:00.000000Z",+ "end_time": "2026-05-20T00:00:00.100000Z",+ "status": {"status_code": status},+ "attributes": attrs or {},+ }+++def test_render_tree_includes_names_and_markers():+ spans = [+ Span(_raw("0x1", None, "invoke_agent",+ {"cubepi.run_id": "r1", "gen_ai.operation.name": "invoke_agent"})),+ Span(_raw("0x2", "0x1", "execute_tool read",+ {"gen_ai.operation.name": "execute_tool",+ "gen_ai.tool.name": "read"}, status="ERROR")),+ Span(_raw("0x9", "0xMISSING", "chat gpt-x",+ {"gen_ai.operation.name": "chat"})),+ ]+ forest = build_forest(spans)+ text = render_tree_to_text(forest)+ assert "invoke_agent" in text+ assert "execute_tool" in text+ assert "read" in text+ assert "orphan" in text.lower()