Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

feat(trace-cli): run-id prefix match, inline errors, input column (#107)

Chrisd65644b110bd
diff --git a/cubepi/cli/trace/loader.py b/cubepi/cli/trace/loader.py
index b63c84a..e320ce7 100644
--- a/cubepi/cli/trace/loader.py
+++ b/cubepi/cli/trace/loader.py
@@ -8,6 +8,7 @@ from datetime import datetime, timezone
from pathlib import Path
from cubepi.cli.trace.model import Span
+from cubepi.tracing import schema
DEFAULT_DIR = Path("./cubepi-traces")
_MIN = datetime.min.replace(tzinfo=timezone.utc)
@@ -29,11 +30,24 @@ def resolve_run(arg: str, directory: Path) -> list[Path]:
if path.suffix == ".jsonl" and path.is_file():
return [path]
matches = sorted(directory.glob(f"*/{arg}.jsonl"))
- if not matches:
+ if matches:
+ return matches
+ # No exact run id. `ls` truncates ids, so accept any prefix that names
+ # exactly one run; an ambiguous prefix is reported with its candidates.
+ by_run: dict[str, list[Path]] = {}
+ for f in sorted(directory.glob(f"*/{arg}*.jsonl")):
+ by_run.setdefault(f.stem, []).append(f)
+ if len(by_run) == 1:
+ (only,) = by_run.values()
+ return sorted(only)
+ if len(by_run) > 1:
+ candidates = ", ".join(sorted(by_run))
raise RunResolutionError(
- f"no trace file for run {arg!r} under {directory} (try `cubepi trace ls`)"
+ f"run prefix {arg!r} is ambiguous under {directory}: matches {candidates}"
)
- return matches
+ raise RunResolutionError(
+ f"no trace file for run {arg!r} under {directory} (try `cubepi trace ls`)"
+ )
def load_run(files: list[Path]) -> tuple[list[Span], int]:
@@ -63,6 +77,47 @@ def load_run(files: list[Path]) -> tuple[list[Span], int]:
return spans, skipped
+def _run_prompt(spans: list[Span]) -> str | None:
+ """The most recent human turn that drove the run, for `ls` identification.
+
+ Reads ``gen_ai.input.messages`` off the root invoke_agent span (only
+ present when the Tracer records content). Returns the last user text, so
+ successive runs in one thread stay distinguishable. ``None`` when content
+ isn't recorded or no user text is present.
+ """
+ root = next((s for s in spans if s.is_invoke_agent), None)
+ candidates = [root] if root is not None else spans
+ for sp in candidates:
+ raw = sp.attributes.get(schema.GEN_AI_INPUT_MESSAGES)
+ if not raw:
+ continue
+ try:
+ messages = json.loads(raw) if isinstance(raw, str) else raw
+ except (json.JSONDecodeError, TypeError):
+ continue
+ if not isinstance(messages, list):
+ continue
+ last: str | None = None
+ for m in messages:
+ if not isinstance(m, dict) or m.get("role") != "user":
+ continue
+ parts = m.get("parts")
+ if isinstance(parts, list):
+ text = " ".join(
+ str(p.get("content", ""))
+ for p in parts
+ if isinstance(p, dict) and p.get("type") == "text"
+ ).strip()
+ else:
+ content = m.get("content")
+ text = content.strip() if isinstance(content, str) else ""
+ if text:
+ last = text
+ if last is not None:
+ return last
+ return None
+
+
@dataclass
class RunSummary:
run_id: str
@@ -71,6 +126,7 @@ class RunSummary:
span_count: int
has_error: bool
duration_ms: float | None
+ prompt: str | None
def list_runs(directory: Path, limit: int | None = None) -> list[RunSummary]:
@@ -101,6 +157,7 @@ def list_runs(directory: Path, limit: int | None = None) -> list[RunSummary]:
span_count=len(spans),
has_error=any(s.is_error for s in spans),
duration_ms=duration,
+ prompt=_run_prompt(spans),
)
)
summaries.sort(key=lambda s: s.start or _MIN, reverse=True)
diff --git a/cubepi/cli/trace/model.py b/cubepi/cli/trace/model.py
index cdc7024..0f4d426 100644
--- a/cubepi/cli/trace/model.py
+++ b/cubepi/cli/trace/model.py
@@ -70,6 +70,28 @@ class Span:
def is_error(self) -> bool:
return self.status_code == "ERROR"
+ @property
+ def status_description(self) -> str | None:
+ return (self.raw.get("status") or {}).get("description")
+
+ @property
+ def events(self) -> list[dict[str, Any]]:
+ return self.raw.get("events") or []
+
+ @property
+ def error_message(self) -> str | None:
+ """Human-readable error text for an errored span.
+
+ Prefers the exception event's full message (OTel status descriptions
+ get truncated); falls back to the status description.
+ """
+ for ev in self.events:
+ if ev.get("name") == schema.EVENT_GEN_AI_EXCEPTION:
+ msg = (ev.get("attributes") or {}).get("exception.message")
+ if msg:
+ return str(msg)
+ return self.status_description
+
@property
def is_aborted(self) -> bool:
# The recorder sets a boolean cubepi.aborted attribute (and also an
diff --git a/cubepi/cli/trace/render.py b/cubepi/cli/trace/render.py
index a55d588..6772fba 100644
--- a/cubepi/cli/trace/render.py
+++ b/cubepi/cli/trace/render.py
@@ -71,6 +71,10 @@ def _build_rich_tree(roots: list[TreeNode], verbose: bool, content: bool):
def add(parent_tree, node: TreeNode) -> None:
branch = parent_tree.add(_node_label(node))
+ if node.span.is_error:
+ msg = node.span.error_message
+ if msg:
+ branch.add(f"[red]error:[/red] {msg}")
if verbose:
for k, v in node.span.attributes.items():
branch.add(f"[dim]{k}[/dim] = {v!r}")
@@ -128,11 +132,13 @@ def render_runs(runs: list[RunSummary]) -> None:
table = Table(title="cubepi runs")
for col in ("started", "run_id", "spans", "status", "duration"):
table.add_column(col)
+ table.add_column("input", max_width=48, no_wrap=True, overflow="ellipsis")
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)
+ prompt = " ".join(r.prompt.split()) if r.prompt else "[dim]—[/dim]"
+ table.add_row(started, r.run_id, str(r.span_count), status, dur, prompt)
console.print(table)
diff --git a/tests/cli/trace/test_loader.py b/tests/cli/trace/test_loader.py
index 0a4931f..c4a954e 100644
--- a/tests/cli/trace/test_loader.py
+++ b/tests/cli/trace/test_loader.py
@@ -52,6 +52,43 @@ def test_resolve_zero_match_errors(tmp_path):
resolve_run("missing", tmp_path)
+def test_resolve_by_unique_prefix(tmp_path):
+ # `ls` truncates run ids, so a copied prefix must resolve to its one run.
+ f = tmp_path / "2026-05-20" / "66f1806f-4c90-4d50.jsonl"
+ _write(f, [_span("0x1", None, "invoke_agent", "2026-05-20T00:00:00Z", "r1")])
+ assert resolve_run("66f1806f", tmp_path) == [f]
+
+
+def test_resolve_prefix_merges_cross_midnight(tmp_path):
+ f1 = tmp_path / "2026-05-19" / "abc123def.jsonl"
+ f2 = tmp_path / "2026-05-20" / "abc123def.jsonl"
+ _write(f1, [_span("0x1", None, "invoke_agent", "2026-05-19T23:59:59Z", "r1")])
+ _write(f2, [_span("0x2", "0x1", "chat", "2026-05-20T00:00:01Z", "r1")])
+ assert sorted(resolve_run("abc123", tmp_path)) == sorted([f1, f2])
+
+
+def test_resolve_ambiguous_prefix_errors(tmp_path):
+ _write(
+ tmp_path / "2026-05-20" / "abc111.jsonl", [_span("0x1", None, "x", None, "r1")]
+ )
+ _write(
+ tmp_path / "2026-05-20" / "abc222.jsonl", [_span("0x2", None, "y", None, "r2")]
+ )
+ with pytest.raises(RunResolutionError, match="ambiguous"):
+ resolve_run("abc", tmp_path)
+
+
+def test_resolve_exact_match_preferred_over_prefix(tmp_path):
+ # An exact run id must not be shadowed by a longer-named sibling run.
+ exact = tmp_path / "2026-05-20" / "run1.jsonl"
+ _write(exact, [_span("0x1", None, "x", None, "r1")])
+ _write(
+ tmp_path / "2026-05-20" / "run1extra.jsonl",
+ [_span("0x2", None, "y", None, "r2")],
+ )
+ assert resolve_run("run1", tmp_path) == [exact]
+
+
def test_load_run_skips_malformed(tmp_path):
f = tmp_path / "2026-05-20" / "r1.jsonl"
f.parent.mkdir(parents=True)
@@ -100,6 +137,120 @@ def test_list_runs(tmp_path):
assert runs[0].span_count == 2
+def test_list_runs_extracts_prompt(tmp_path):
+ msgs = json.dumps(
+ [
+ {"role": "user", "parts": [{"type": "text", "content": "first question"}]},
+ {"role": "assistant", "parts": [{"type": "text", "content": "answer"}]},
+ {
+ "role": "user",
+ "parts": [{"type": "text", "content": "北京明天天气如何\n\n"}],
+ },
+ ]
+ )
+ f = tmp_path / "2026-05-20" / "r1.jsonl"
+ _write(
+ f,
+ [
+ _span(
+ "0x1",
+ None,
+ "invoke_agent",
+ "2026-05-20T00:00:00Z",
+ "r1",
+ **{
+ "gen_ai.operation.name": "invoke_agent",
+ "gen_ai.input.messages": msgs,
+ },
+ ),
+ ],
+ )
+ runs = list_runs(tmp_path)
+ # Most recent human turn, so multiple runs in a thread stay distinguishable.
+ assert runs[0].prompt == "北京明天天气如何"
+
+
+def test_list_runs_prompt_from_string_content(tmp_path):
+ # Older message shape: content is a bare string, not parts.
+ msgs = json.dumps([{"role": "user", "content": " plain string prompt "}])
+ f = tmp_path / "2026-05-20" / "r1.jsonl"
+ _write(
+ f,
+ [
+ _span(
+ "0x1",
+ None,
+ "invoke_agent",
+ "2026-05-20T00:00:00Z",
+ "r1",
+ **{
+ "gen_ai.operation.name": "invoke_agent",
+ "gen_ai.input.messages": msgs,
+ },
+ )
+ ],
+ )
+ assert list_runs(tmp_path)[0].prompt == "plain string prompt"
+
+
+def test_list_runs_prompt_handles_bad_messages(tmp_path):
+ # Malformed JSON and a non-list payload both yield no prompt, never raise.
+ f1 = tmp_path / "2026-05-20" / "r1.jsonl"
+ _write(
+ f1,
+ [
+ _span(
+ "0x1",
+ None,
+ "invoke_agent",
+ "2026-05-20T00:00:00Z",
+ "r1",
+ **{
+ "gen_ai.operation.name": "invoke_agent",
+ "gen_ai.input.messages": "{ not json",
+ },
+ )
+ ],
+ )
+ f2 = tmp_path / "2026-05-20" / "r2.jsonl"
+ _write(
+ f2,
+ [
+ _span(
+ "0x2",
+ None,
+ "invoke_agent",
+ "2026-05-20T00:00:01Z",
+ "r2",
+ **{
+ "gen_ai.operation.name": "invoke_agent",
+ "gen_ai.input.messages": '"a string"',
+ },
+ )
+ ],
+ )
+ prompts = {r.run_id: r.prompt for r in list_runs(tmp_path)}
+ assert prompts == {"r1": None, "r2": None}
+
+
+def test_list_runs_prompt_none_without_content(tmp_path):
+ f = tmp_path / "2026-05-20" / "r1.jsonl"
+ _write(
+ f,
+ [
+ _span(
+ "0x1",
+ None,
+ "invoke_agent",
+ "2026-05-20T00:00:00Z",
+ "r1",
+ **{"gen_ai.operation.name": "invoke_agent"},
+ )
+ ],
+ )
+ assert list_runs(tmp_path)[0].prompt is None
+
+
def test_list_runs_merges_cross_midnight(tmp_path):
f1 = tmp_path / "2026-05-19" / "r1.jsonl"
f2 = tmp_path / "2026-05-20" / "r1.jsonl"
diff --git a/tests/cli/trace/test_render.py b/tests/cli/trace/test_render.py
index ed89f6a..fe94c18 100644
--- a/tests/cli/trace/test_render.py
+++ b/tests/cli/trace/test_render.py
@@ -1,18 +1,27 @@
from __future__ import annotations
+from pathlib import Path
+
+from cubepi.cli.trace.loader import RunSummary
from cubepi.cli.trace.model import Span, build_forest
-from cubepi.cli.trace.render import render_tree_to_text
+from cubepi.cli.trace.render import render_runs, render_tree_to_text
-def _raw(span_id, parent_id, name, attrs=None, status="UNSET"):
+def _raw(
+ span_id, parent_id, name, attrs=None, status="UNSET", description=None, events=None
+):
+ status_obj = {"status_code": status}
+ if description is not None:
+ status_obj["description"] = description
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},
+ "status": status_obj,
"attributes": attrs or {},
+ "events": events or [],
}
@@ -43,3 +52,66 @@ def test_render_tree_includes_names_and_markers():
assert "execute_tool" in text
assert "read" in text
assert "orphan" in text.lower()
+
+
+def test_render_tree_surfaces_exception_message():
+ # The full error lives in the exception event; show it without -v.
+ spans = [
+ Span(
+ _raw(
+ "0x1",
+ None,
+ "chat gpt-x",
+ {"gen_ai.operation.name": "chat"},
+ status="ERROR",
+ description="truncated...",
+ events=[
+ {
+ "name": "gen_ai.client.operation.exception",
+ "attributes": {
+ "exception.type": "BadRequestError",
+ "exception.message": "tool_use without tool_result blocks",
+ },
+ }
+ ],
+ )
+ ),
+ ]
+ text = render_tree_to_text(build_forest(spans))
+ assert "tool_use without tool_result blocks" in text
+
+
+def test_render_tree_falls_back_to_status_description():
+ # No exception event -> use the OTel status description.
+ spans = [
+ Span(
+ _raw(
+ "0x1",
+ None,
+ "execute_tool read",
+ {"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": "read"},
+ status="ERROR",
+ description="boom from tool",
+ )
+ ),
+ ]
+ text = render_tree_to_text(build_forest(spans))
+ assert "boom from tool" in text
+
+
+def test_render_runs_includes_input_column(capsys):
+ runs = [
+ RunSummary(
+ run_id="r1",
+ files=[Path("x.jsonl")],
+ start=None,
+ span_count=3,
+ has_error=False,
+ duration_ms=12.0,
+ prompt="北京明天天气如何",
+ )
+ ]
+ render_runs(runs)
+ out = capsys.readouterr().out
+ assert "input" in out
+ assert "北京" in out