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): trace follow — chronological end-of-span event stream
xf gong2ad05be740c2
diff --git a/cubepi/cli/trace/follow.py b/cubepi/cli/trace/follow.pyindex be64437..362666f 100644--- a/cubepi/cli/trace/follow.py+++ b/cubepi/cli/trace/follow.py@@ -1,8 +1,101 @@+"""Tail a run file and print spans as a flat chronological event stream.++Spans are written by JsonlSpanExporter when they *end*, and children end+before their parents, so a live tree cannot be drawn correctly. Instead we+print one line per span in the order it completes. The run is considered+finished when the root ``invoke_agent`` span (``parent_id == null``) appears.+"""from __future__ import annotations+import json+import time+from collections.abc import Callablefrom pathlib import Path+from typing import Any++from cubepi.cli.trace.model import Span+++def iter_new_spans(path: Path, state: dict[str, Any]):+ """Yield Spans for newly-completed lines since the last call.++ ``state`` carries ``offset`` (bytes consumed) and ``buffer`` (an+ unterminated trailing line held until its newline arrives). Malformed+ complete lines are skipped and counted in ``state['skipped']``.+ """+ if not path.exists():+ return+ with path.open(encoding="utf-8") as fh:+ fh.seek(state["offset"])+ chunk = fh.read()+ state["offset"] = fh.tell()+ data = state["buffer"] + chunk+ lines = data.split("\n")+ state["buffer"] = lines.pop() # trailing remainder (no newline yet)+ for line in lines:+ line = line.strip()+ if not line:+ continue+ try:+ yield Span(json.loads(line))+ except json.JSONDecodeError:+ state["skipped"] = state.get("skipped", 0) + 1+ continue+++def is_run_complete(span: Span) -> bool:+ return span.parent_id is None and span.is_invoke_agent+++def format_event(span: Span) -> str:+ end = span.end.isoformat() if span.end else "?"+ dur = f"{span.duration_ms:.1f}ms" if span.duration_ms is not None else "…"+ parts = [end, span.name, dur]+ if span.is_error:+ parts.append("ERROR")+ if span.is_aborted:+ parts.append("aborted")+ return " ".join(parts)++def follow_run(+ resolve_files: "Callable[[], list[Path]]",+ *,+ interval: float = 0.5,+ timeout: float | None = None,+) -> None:+ """Tail a run, printing each span as it completes.-def follow_run(path: Path, *, interval: float = 0.5,- timeout: float | None = None) -> None:- raise NotImplementedError+ ``resolve_files`` is re-invoked every poll so a run crossing UTC midnight+ (a new ``<next-date>/<run_id>.jsonl`` file) is picked up without restarting.+ Each file keeps its own offset/buffer/skipped state. Exits when the root+ invoke_agent span appears, after ``timeout`` idle seconds, or on Ctrl-C.+ """+ states: dict[Path, dict[str, Any]] = {}+ last_activity = time.monotonic()+ try:+ while True:+ saw_any = False+ done = False+ for path in resolve_files():+ state = states.setdefault(+ path, {"offset": 0, "buffer": "", "skipped": 0}+ )+ for span in iter_new_spans(path, state):+ print(format_event(span), flush=True)+ saw_any = True+ if is_run_complete(span):+ done = True+ if done:+ break+ now = time.monotonic()+ if saw_any:+ last_activity = now+ elif timeout is not None and (now - last_activity) >= timeout:+ break+ time.sleep(interval)+ except KeyboardInterrupt:+ pass+ skipped = sum(s.get("skipped", 0) for s in states.values())+ if skipped:+ print(f"({skipped} lines skipped (malformed))")diff --git a/tests/cli/trace/test_follow.py b/tests/cli/trace/test_follow.pynew file mode 100644index 0000000..274036a--- /dev/null+++ b/tests/cli/trace/test_follow.py@@ -0,0 +1,55 @@+from __future__ import annotations++import json++from cubepi.cli.trace.follow import format_event, is_run_complete, iter_new_spans+from cubepi.cli.trace.model import Span+++def _line(span_id, parent_id, name):+ return json.dumps({+ "name": name,+ "context": {"trace_id": "0xt", "span_id": span_id},+ "parent_id": parent_id,+ "start_time": "2026-05-20T00:00:00Z",+ "end_time": "2026-05-20T00:00:00.1Z",+ "status": {"status_code": "UNSET"},+ "attributes": {"gen_ai.operation.name": name},+ })+++def test_iter_new_spans_incremental(tmp_path):+ f = tmp_path / "r1.jsonl"+ f.write_text(_line("0x2", "0x1", "chat") + "\n")+ state = {"offset": 0, "buffer": ""}+ spans = list(iter_new_spans(f, state))+ assert [s.name for s in spans] == ["chat"]+ # Append more; only the new span is yielded.+ with f.open("a") as fh:+ fh.write(_line("0x3", "0x1", "execute_tool") + "\n")+ spans = list(iter_new_spans(f, state))+ assert [s.name for s in spans] == ["execute_tool"]+++def test_partial_line_held_until_newline(tmp_path):+ f = tmp_path / "r1.jsonl"+ payload = _line("0x2", "0x1", "chat")+ f.write_text(payload) # no trailing newline yet+ state = {"offset": 0, "buffer": ""}+ assert list(iter_new_spans(f, state)) == [] # held in buffer+ with f.open("a") as fh:+ fh.write("\n")+ spans = list(iter_new_spans(f, state))+ assert [s.name for s in spans] == ["chat"]+++def test_is_run_complete_on_root():+ root = Span(json.loads(_line("0x1", None, "invoke_agent")))+ child = Span(json.loads(_line("0x2", "0x1", "chat")))+ assert is_run_complete(child) is False+ assert is_run_complete(root) is True+++def test_format_event_contains_name():+ sp = Span(json.loads(_line("0x2", "0x1", "chat")))+ assert "chat" in format_event(sp)