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
test(cli): schema round-trip guard + apply ruff format
xf gongdc051e820d3a
diff --git a/cubepi/cli/__main__.py b/cubepi/cli/__main__.pyindex 3bbcd61..096a95e 100644--- a/cubepi/cli/__main__.py+++ b/cubepi/cli/__main__.py@@ -1,4 +1,5 @@"""Entry point for the ``cubepi`` console script."""+from __future__ import annotationsimport argparsediff --git a/cubepi/cli/trace/commands.py b/cubepi/cli/trace/commands.pyindex 60f29b9..108089c 100644--- a/cubepi/cli/trace/commands.py+++ b/cubepi/cli/trace/commands.py@@ -1,4 +1,5 @@"""argparse wiring for `cubepi trace`."""+from __future__ import annotationsimport argparse@@ -21,19 +22,23 @@ def register(subparsers: "argparse._SubParsersAction") -> None: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.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.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")@@ -45,8 +50,11 @@ def register(subparsers: "argparse._SubParsersAction") -> None:def _add_dir(parser: argparse.ArgumentParser) -> None:- parser.add_argument("--dir", default=str(loader.DEFAULT_DIR),- help="traces directory (default: ./cubepi-traces)")+ parser.add_argument(+ "--dir",+ default=str(loader.DEFAULT_DIR),+ help="traces directory (default: ./cubepi-traces)",+ )def _emit_skipped(skipped: int) -> None:diff --git a/cubepi/cli/trace/follow.py b/cubepi/cli/trace/follow.pyindex 362666f..8109080 100644--- a/cubepi/cli/trace/follow.py+++ b/cubepi/cli/trace/follow.py@@ -5,6 +5,7 @@ before their parents, so a live tree cannot be drawn correctly. Instead weprint one line per span in the order it completes. The run is consideredfinished when the root ``invoke_agent`` span (``parent_id == null``) appears."""+from __future__ import annotationsimport jsondiff --git a/cubepi/cli/trace/loader.py b/cubepi/cli/trace/loader.pyindex 04aae9c..54907dd 100644--- a/cubepi/cli/trace/loader.py+++ b/cubepi/cli/trace/loader.py@@ -1,4 +1,5 @@"""Discover trace files, resolve a run id to file(s), read spans."""+from __future__ import annotationsimport json@@ -30,8 +31,7 @@ def resolve_run(arg: str, directory: Path) -> list[Path]:matches = sorted(directory.glob(f"*/{arg}.jsonl"))if not matches:raise RunResolutionError(- f"no trace file for run {arg!r} under {directory} "- f"(try `cubepi trace ls`)"+ f"no trace file for run {arg!r} under {directory} (try `cubepi trace ls`)")return matchesdiff --git a/cubepi/cli/trace/model.py b/cubepi/cli/trace/model.pyindex 7e65ba0..2da2fce 100644--- a/cubepi/cli/trace/model.py+++ b/cubepi/cli/trace/model.py@@ -1,4 +1,5 @@"""Span wrapper + tree building over OTLP/JSON span dicts."""+from __future__ import annotationsfrom dataclasses import dataclass, fielddiff --git a/cubepi/cli/trace/render.py b/cubepi/cli/trace/render.pyindex 8374d69..a55d588 100644--- a/cubepi/cli/trace/render.py+++ b/cubepi/cli/trace/render.py@@ -1,5 +1,6 @@"""rich-based rendering. rich is imported lazily so the package import doesnot require the trace-cli extra until something is actually rendered."""+from __future__ import annotationsimport jsondiff --git a/cubepi/cli/trace/stats.py b/cubepi/cli/trace/stats.pyindex aa086a3..040807e 100644--- a/cubepi/cli/trace/stats.py+++ b/cubepi/cli/trace/stats.py@@ -1,4 +1,5 @@"""Aggregate spans by model or tool."""+from __future__ import annotationsfrom dataclasses import dataclass@@ -37,9 +38,7 @@ def aggregate(spans: list[Span], by: str) -> list[StatRow]:None — tokens live on chat spans, not tool spans."""want_tokens = by == "model"- key_attr = (- schema.GEN_AI_REQUEST_MODEL if by == "model" else schema.GEN_AI_TOOL_NAME- )+ key_attr = schema.GEN_AI_REQUEST_MODEL if by == "model" else schema.GEN_AI_TOOL_NAMErows: dict[str, StatRow] = {}for sp in spans:# Classify on gen_ai.operation.name, not span name (names carrydiff --git a/cubepi/tracing/__init__.py b/cubepi/tracing/__init__.pyindex f406b63..007288c 100644--- a/cubepi/tracing/__init__.py+++ b/cubepi/tracing/__init__.py@@ -45,9 +45,7 @@ def __getattr__(name: str) -> Any:try:module_name, attr = _LAZY[name]except KeyError:- raise AttributeError(- f"module {__name__!r} has no attribute {name!r}"- ) from None+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from Nonetry:import opentelemetry.sdk.trace # noqa: F401except ImportError as exc: # pragma: no cover — only without the extra.diff --git a/tests/cli/trace/test_commands.py b/tests/cli/trace/test_commands.pyindex 279ee1d..7e25851 100644--- a/tests/cli/trace/test_commands.py+++ b/tests/cli/trace/test_commands.py@@ -10,20 +10,32 @@ 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}},+ {+ "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:diff --git a/tests/cli/trace/test_follow.py b/tests/cli/trace/test_follow.pyindex 274036a..5e04d32 100644--- a/tests/cli/trace/test_follow.py+++ b/tests/cli/trace/test_follow.py@@ -7,15 +7,17 @@ from cubepi.cli.trace.model import Spandef _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},- })+ 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):diff --git a/tests/cli/trace/test_loader.py b/tests/cli/trace/test_loader.pyindex d34fe0d..d8d25e2 100644--- a/tests/cli/trace/test_loader.py+++ b/tests/cli/trace/test_loader.py@@ -56,11 +56,15 @@ def test_load_run_skips_malformed(tmp_path):f = tmp_path / "2026-05-20" / "r1.jsonl"f.parent.mkdir(parents=True)with f.open("w") as fh:- fh.write(json.dumps(_span("0x1", None, "invoke_agent",- "2026-05-20T00:00:00Z", "r1")) + "\n")+ fh.write(+ json.dumps(_span("0x1", None, "invoke_agent", "2026-05-20T00:00:00Z", "r1"))+ + "\n"+ )fh.write("{ not json\n")- fh.write(json.dumps(_span("0x2", "0x1", "chat",- "2026-05-20T00:00:00.1Z", "r1")) + "\n")+ fh.write(+ json.dumps(_span("0x2", "0x1", "chat", "2026-05-20T00:00:00.1Z", "r1"))+ + "\n"+ )spans, skipped = load_run([f])assert len(spans) == 2assert skipped == 1@@ -68,10 +72,13 @@ def test_load_run_skips_malformed(tmp_path):def test_list_runs(tmp_path):f = tmp_path / "2026-05-20" / "r1.jsonl"- _write(f, [- _span("0x1", None, "invoke_agent", "2026-05-20T00:00:00Z", "r1"),- _span("0x2", "0x1", "chat", "2026-05-20T00:00:00.1Z", "r1"),- ])+ _write(+ f,+ [+ _span("0x1", None, "invoke_agent", "2026-05-20T00:00:00Z", "r1"),+ _span("0x2", "0x1", "chat", "2026-05-20T00:00:00.1Z", "r1"),+ ],+ )runs = list_runs(tmp_path)assert len(runs) == 1assert runs[0].run_id == "r1"diff --git a/tests/cli/trace/test_model.py b/tests/cli/trace/test_model.pyindex e355103..0f0a733 100644--- a/tests/cli/trace/test_model.py+++ b/tests/cli/trace/test_model.py@@ -16,9 +16,16 @@ def _raw(span_id, parent_id, name, start, end=None, status="UNSET", attrs=None):def test_span_fields_and_duration():- sp = Span(_raw("0x1", None, "invoke_agent",- "2026-05-20T00:00:00.000000Z", "2026-05-20T00:00:01.500000Z",- attrs={"cubepi.run_id": "run-1"}))+ sp = Span(+ _raw(+ "0x1",+ None,+ "invoke_agent",+ "2026-05-20T00:00:00.000000Z",+ "2026-05-20T00:00:01.500000Z",+ attrs={"cubepi.run_id": "run-1"},+ )+ )assert sp.span_id == "0x1"assert sp.parent_id is Noneassert sp.name == "invoke_agent"@@ -28,25 +35,63 @@ def test_span_fields_and_duration():def test_error_and_abort_distinct():- err = Span(_raw("0x2", "0x1", "chat gpt-x", "2026-05-20T00:00:00Z",- "2026-05-20T00:00:00.1Z", status="ERROR",- attrs={"gen_ai.operation.name": "chat"}))- aborted = Span(_raw("0x3", "0x1", "chat gpt-x", "2026-05-20T00:00:00Z",- "2026-05-20T00:00:00.1Z",- attrs={"gen_ai.operation.name": "chat",- "cubepi.aborted": True,- "error.type": "cubepi.aborted"}))+ err = Span(+ _raw(+ "0x2",+ "0x1",+ "chat gpt-x",+ "2026-05-20T00:00:00Z",+ "2026-05-20T00:00:00.1Z",+ status="ERROR",+ attrs={"gen_ai.operation.name": "chat"},+ )+ )+ aborted = Span(+ _raw(+ "0x3",+ "0x1",+ "chat gpt-x",+ "2026-05-20T00:00:00Z",+ "2026-05-20T00:00:00.1Z",+ attrs={+ "gen_ai.operation.name": "chat",+ "cubepi.aborted": True,+ "error.type": "cubepi.aborted",+ },+ )+ )assert err.is_error is True and err.is_aborted is Falseassert aborted.is_error is False and aborted.is_aborted is Truedef test_operation_classification():- chat = Span(_raw("0x4", "0x1", "chat gpt-x", "2026-05-20T00:00:00Z",- attrs={"gen_ai.operation.name": "chat"}))- tool = Span(_raw("0x5", "0x1", "execute_tool read", "2026-05-20T00:00:00Z",- attrs={"gen_ai.operation.name": "execute_tool"}))- agent = Span(_raw("0x6", None, "invoke_agent", "2026-05-20T00:00:00Z",- attrs={"gen_ai.operation.name": "invoke_agent"}))+ chat = Span(+ _raw(+ "0x4",+ "0x1",+ "chat gpt-x",+ "2026-05-20T00:00:00Z",+ attrs={"gen_ai.operation.name": "chat"},+ )+ )+ tool = Span(+ _raw(+ "0x5",+ "0x1",+ "execute_tool read",+ "2026-05-20T00:00:00Z",+ attrs={"gen_ai.operation.name": "execute_tool"},+ )+ )+ agent = Span(+ _raw(+ "0x6",+ None,+ "invoke_agent",+ "2026-05-20T00:00:00Z",+ attrs={"gen_ai.operation.name": "invoke_agent"},+ )+ )assert chat.is_chat and not chat.is_toolassert tool.is_tool and not tool.is_chatassert agent.is_invoke_agentdiff --git a/tests/cli/trace/test_render.py b/tests/cli/trace/test_render.pyindex f782a03..ed89f6a 100644--- a/tests/cli/trace/test_render.py+++ b/tests/cli/trace/test_render.py@@ -18,13 +18,24 @@ def _raw(span_id, parent_id, name, attrs=None, status="UNSET"):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"})),+ 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)diff --git a/tests/cli/trace/test_schema_roundtrip.py b/tests/cli/trace/test_schema_roundtrip.pynew file mode 100644index 0000000..651174f--- /dev/null+++ b/tests/cli/trace/test_schema_roundtrip.py@@ -0,0 +1,41 @@+from __future__ import annotations++import json++import pytest++pytest.importorskip("opentelemetry.sdk.trace")++from opentelemetry.sdk.trace import TracerProvider # noqa: E402++from cubepi.cli.trace.loader import load_run # noqa: E402+from cubepi.cli.trace.model import build_forest # noqa: E402+from cubepi.tracing.exporters import JsonlSpanExporter # noqa: E402+from cubepi.tracing.schema import CUBEPI_RUN_ID # noqa: E402+++def test_real_exporter_output_parses(tmp_path):+ exporter = JsonlSpanExporter(directory=tmp_path)+ provider = TracerProvider()+ tracer = provider.get_tracer("cubepi.tracing")+ # After the `with` blocks exit the spans have ended; the span objects are+ # ReadableSpans, so we can hand them straight to the exporter.+ with tracer.start_as_current_span("invoke_agent") as root:+ root.set_attribute(CUBEPI_RUN_ID, "roundtrip")+ with tracer.start_as_current_span("chat") as chat:+ chat.set_attribute(CUBEPI_RUN_ID, "roundtrip")+ exporter.export([root, chat])++ files = sorted(tmp_path.glob("*/roundtrip.jsonl"))+ assert files, "exporter wrote no file"+ loaded, skipped = load_run(files)+ assert skipped == 0+ names = {s.name for s in loaded}+ assert {"invoke_agent", "chat"} <= names+ forest = build_forest(loaded)+ assert any(r.span.name == "invoke_agent" for r in forest)+ # JSON shape sanity: every line is valid JSON with a context.span_id.+ for f in files:+ for line in f.read_text().splitlines():+ obj = json.loads(line)+ assert "span_id" in obj["context"]diff --git a/tests/cli/trace/test_stats.py b/tests/cli/trace/test_stats.pyindex ec54e62..4d6a23d 100644--- a/tests/cli/trace/test_stats.py+++ b/tests/cli/trace/test_stats.py@@ -6,20 +6,22 @@ from cubepi.cli.trace.stats import aggregatedef _chat(model, in_tok, out_tok, dur_ms, error=False):end = f"2026-05-20T00:00:{dur_ms / 1000:09.6f}Z"- return Span({- "name": "chat",- "context": {"trace_id": "0xt", "span_id": "0x1"},- "parent_id": "0x0",- "start_time": "2026-05-20T00:00:00.000000Z",- "end_time": end,- "status": {"status_code": "ERROR" if error else "UNSET"},- "attributes": {- "gen_ai.operation.name": "chat",- "gen_ai.request.model": model,- "gen_ai.usage.input_tokens": in_tok,- "gen_ai.usage.output_tokens": out_tok,- },- })+ return Span(+ {+ "name": "chat",+ "context": {"trace_id": "0xt", "span_id": "0x1"},+ "parent_id": "0x0",+ "start_time": "2026-05-20T00:00:00.000000Z",+ "end_time": end,+ "status": {"status_code": "ERROR" if error else "UNSET"},+ "attributes": {+ "gen_ai.operation.name": "chat",+ "gen_ai.request.model": model,+ "gen_ai.usage.input_tokens": in_tok,+ "gen_ai.usage.output_tokens": out_tok,+ },+ }+ )def _tool(name, dur_ms, aborted=False):@@ -28,15 +30,17 @@ def _tool(name, dur_ms, aborted=False):if aborted:attrs["cubepi.aborted"] = Trueattrs["error.type"] = "cubepi.aborted"- return Span({- "name": "execute_tool",- "context": {"trace_id": "0xt", "span_id": "0x2"},- "parent_id": "0x0",- "start_time": "2026-05-20T00:00:00.000000Z",- "end_time": end,- "status": {"status_code": "UNSET"},- "attributes": attrs,- })+ return Span(+ {+ "name": "execute_tool",+ "context": {"trace_id": "0xt", "span_id": "0x2"},+ "parent_id": "0x0",+ "start_time": "2026-05-20T00:00:00.000000Z",+ "end_time": end,+ "status": {"status_code": "UNSET"},+ "attributes": attrs,+ }+ )def test_aggregate_by_model_tokens():diff --git a/tests/tracing/test_lazy_import.py b/tests/tracing/test_lazy_import.pyindex d0a744c..506b457 100644--- a/tests/tracing/test_lazy_import.py+++ b/tests/tracing/test_lazy_import.py@@ -1,4 +1,5 @@"""schema constants must be importable without the opentelemetry SDK."""+from __future__ import annotationsimport subprocess