agent-certify 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_certify/__init__.py +53 -0
- agent_certify/anomaly.py +250 -0
- agent_certify/baseline.py +259 -0
- agent_certify/blast.py +141 -0
- agent_certify/certificate.py +503 -0
- agent_certify/cli.py +708 -0
- agent_certify/graph.py +325 -0
- agent_certify/mcp_server.py +603 -0
- agent_certify/otel.py +195 -0
- agent_certify/parser/__init__.py +10 -0
- agent_certify/parser/auto.py +118 -0
- agent_certify/parser/base.py +67 -0
- agent_certify/parser/claude_code.py +267 -0
- agent_certify/parser/cursor_trace.py +227 -0
- agent_certify/parser/mcp_logs.py +240 -0
- agent_certify/paths.py +128 -0
- agent_certify/policy.py +214 -0
- agent_certify/scanner.py +400 -0
- agent_certify/viz.py +299 -0
- agent_certify/watcher.py +242 -0
- agent_certify-0.5.0.dist-info/METADATA +564 -0
- agent_certify-0.5.0.dist-info/RECORD +26 -0
- agent_certify-0.5.0.dist-info/WHEEL +5 -0
- agent_certify-0.5.0.dist-info/entry_points.txt +2 -0
- agent_certify-0.5.0.dist-info/licenses/LICENSE +204 -0
- agent_certify-0.5.0.dist-info/top_level.txt +1 -0
agent_certify/otel.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# agent-certify — Structural verification of multiagent systems
|
|
2
|
+
# Copyright 2026 Cognitive Engineering (Switzerland)
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""OpenTelemetry export without the OpenTelemetry SDK.
|
|
5
|
+
|
|
6
|
+
Each scan becomes one span, ``agent_certify.scan``, carrying the structural
|
|
7
|
+
metrics as attributes; anomalies and policy violations become span events.
|
|
8
|
+
A critical anomaly or any policy violation sets the span status to ERROR.
|
|
9
|
+
|
|
10
|
+
Spans are written as OTLP/JSON (the protobuf JSON mapping used by OTLP/HTTP
|
|
11
|
+
with ``Content-Type: application/json``): one ``{"resourceSpans": [...]}``
|
|
12
|
+
object per line. That is the layout the OpenTelemetry Collector's ``file``
|
|
13
|
+
exporter writes and its ``otlpjsonfile`` receiver reads, so a collector can
|
|
14
|
+
pick the file up and forward it to Jaeger, Grafana Tempo, Datadog, etc.
|
|
15
|
+
Trace and span ids are lowercase hex, as OTLP/JSON requires.
|
|
16
|
+
|
|
17
|
+
All scans of one session share a trace id (derived from the session id), so a
|
|
18
|
+
``watch`` run shows up as one trace with a span per scan cycle.
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import os
|
|
25
|
+
import secrets
|
|
26
|
+
import sys
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from datetime import datetime, timezone
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
from agent_certify.anomaly import AnomalyReport
|
|
32
|
+
from agent_certify.graph import AgentGraph
|
|
33
|
+
from agent_certify.paths import ensure_state_dir
|
|
34
|
+
from agent_certify.policy import PolicyViolation
|
|
35
|
+
from agent_certify.scanner import ScanResult
|
|
36
|
+
|
|
37
|
+
DEFAULT_TRACES_PATH = Path(".agent-certify") / "traces.jsonl"
|
|
38
|
+
SPAN_KIND_INTERNAL = 1
|
|
39
|
+
STATUS_CODES = {"UNSET": 0, "OK": 1, "ERROR": 2}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _now() -> datetime:
|
|
43
|
+
return datetime.now(timezone.utc)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _iso(ts: datetime) -> str:
|
|
47
|
+
return ts.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _nanos(iso: str) -> str:
|
|
51
|
+
ts = datetime.fromisoformat(iso.replace("Z", "+00:00"))
|
|
52
|
+
whole = int(ts.timestamp()) * 1_000_000_000
|
|
53
|
+
return str(whole + ts.microsecond * 1000)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _value(v) -> dict:
|
|
57
|
+
"""An OTLP AnyValue. bool before int: bool is an int subclass."""
|
|
58
|
+
if isinstance(v, bool):
|
|
59
|
+
return {"boolValue": v}
|
|
60
|
+
if isinstance(v, int):
|
|
61
|
+
return {"intValue": str(v)} # int64 is a string in OTLP/JSON
|
|
62
|
+
if isinstance(v, float):
|
|
63
|
+
return {"doubleValue": v}
|
|
64
|
+
return {"stringValue": str(v)}
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _attrs(d: dict) -> list[dict]:
|
|
68
|
+
return [{"key": k, "value": _value(v)} for k, v in d.items()]
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class OTelSpan:
|
|
73
|
+
"""A lightweight OpenTelemetry-compatible span."""
|
|
74
|
+
trace_id: str # 32 hex chars
|
|
75
|
+
span_id: str # 16 hex chars
|
|
76
|
+
name: str
|
|
77
|
+
start_time: str # ISO 8601, UTC
|
|
78
|
+
end_time: str
|
|
79
|
+
attributes: dict[str, str | int | float | bool]
|
|
80
|
+
events: list[dict] = field(default_factory=list) # {"name", "time", "attributes"}
|
|
81
|
+
status: str = "OK" # "OK", "ERROR"
|
|
82
|
+
status_message: str = ""
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class OTelExporter:
|
|
86
|
+
"""Export agent-certify results as OpenTelemetry spans.
|
|
87
|
+
|
|
88
|
+
Usage::
|
|
89
|
+
|
|
90
|
+
exporter = OTelExporter()
|
|
91
|
+
span = exporter.export_scan(graph, result, anomalies, violations)
|
|
92
|
+
exporter.write(span) # appends to .agent-certify/traces.jsonl
|
|
93
|
+
exporter.write(span, stdout=True) # one OTLP/JSON line on stdout
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
def __init__(self, service_name: str = "agent-certify"):
|
|
97
|
+
from agent_certify import __version__
|
|
98
|
+
self.service_name = service_name
|
|
99
|
+
self.version = __version__
|
|
100
|
+
|
|
101
|
+
def export_scan(self, graph: AgentGraph, result: ScanResult,
|
|
102
|
+
anomalies: AnomalyReport | None = None,
|
|
103
|
+
violations: list[PolicyViolation] | None = None,
|
|
104
|
+
start_time: datetime | None = None) -> OTelSpan:
|
|
105
|
+
"""Create a span representing one scan (``start_time``: when the scan began)."""
|
|
106
|
+
end = _now()
|
|
107
|
+
start = start_time or end
|
|
108
|
+
span = OTelSpan(
|
|
109
|
+
trace_id=self._trace_id(graph.session_id),
|
|
110
|
+
span_id=secrets.token_hex(8),
|
|
111
|
+
name="agent_certify.scan",
|
|
112
|
+
start_time=_iso(start),
|
|
113
|
+
end_time=_iso(end),
|
|
114
|
+
attributes={
|
|
115
|
+
"agent_certify.fi": float(result.fi),
|
|
116
|
+
"agent_certify.node_count": result.node_count,
|
|
117
|
+
"agent_certify.edge_count": result.edge_count,
|
|
118
|
+
"agent_certify.bridge_count": len(result.bridges),
|
|
119
|
+
"agent_certify.components": result.components,
|
|
120
|
+
"agent_certify.articulation_point_count": len(result.articulation_points),
|
|
121
|
+
"agent_certify.high_level_node_count": len(result.critical_nodes),
|
|
122
|
+
"agent_certify.sub_agent_count": sum(1 for n in graph.nodes.values() if n.kind == "agent"),
|
|
123
|
+
"agent_certify.tool_call_count": graph.total_tool_calls,
|
|
124
|
+
"agent_certify.skipped_records": graph.skipped_records,
|
|
125
|
+
"agent_certify.perspective": result.perspective,
|
|
126
|
+
"agent_certify.session_id": graph.session_id or "",
|
|
127
|
+
"agent_certify.project": graph.project or "",
|
|
128
|
+
},
|
|
129
|
+
)
|
|
130
|
+
reasons = []
|
|
131
|
+
if anomalies is not None:
|
|
132
|
+
span.attributes["agent_certify.anomaly_count"] = len(anomalies.anomalies)
|
|
133
|
+
for a in anomalies.anomalies:
|
|
134
|
+
attrs = {"severity": a.severity, "category": a.category, "message": a.message,
|
|
135
|
+
"baseline_value": a.baseline_value}
|
|
136
|
+
if a.z_score is not None:
|
|
137
|
+
attrs["z_score"] = float(a.z_score)
|
|
138
|
+
span.events.append({"name": f"anomaly.{a.category}", "time": span.end_time, "attributes": attrs})
|
|
139
|
+
if a.severity == "critical":
|
|
140
|
+
span.status = "ERROR"
|
|
141
|
+
reasons.append(a.message)
|
|
142
|
+
if violations is not None:
|
|
143
|
+
span.attributes["agent_certify.policy_violation_count"] = len(violations)
|
|
144
|
+
for v in violations:
|
|
145
|
+
span.events.append({"name": f"policy_violation.{v.rule.kind}", "time": span.end_time,
|
|
146
|
+
"attributes": {"severity": v.severity, "message": v.message,
|
|
147
|
+
"rule_target": v.rule.target, "observed": v.observed}})
|
|
148
|
+
span.status = "ERROR"
|
|
149
|
+
reasons.append(v.message)
|
|
150
|
+
span.status_message = "; ".join(reasons)[:500]
|
|
151
|
+
return span
|
|
152
|
+
|
|
153
|
+
def to_otlp_json(self, span: OTelSpan) -> dict:
|
|
154
|
+
"""Convert to OTLP/JSON (one ExportTraceServiceRequest)."""
|
|
155
|
+
status = {"code": STATUS_CODES[span.status]}
|
|
156
|
+
if span.status_message:
|
|
157
|
+
status["message"] = span.status_message
|
|
158
|
+
return {"resourceSpans": [{
|
|
159
|
+
"resource": {"attributes": _attrs({"service.name": self.service_name,
|
|
160
|
+
"service.version": self.version})},
|
|
161
|
+
"scopeSpans": [{
|
|
162
|
+
"scope": {"name": "agent_certify", "version": self.version},
|
|
163
|
+
"spans": [{
|
|
164
|
+
"traceId": span.trace_id,
|
|
165
|
+
"spanId": span.span_id,
|
|
166
|
+
"name": span.name,
|
|
167
|
+
"kind": SPAN_KIND_INTERNAL,
|
|
168
|
+
"startTimeUnixNano": _nanos(span.start_time),
|
|
169
|
+
"endTimeUnixNano": _nanos(span.end_time),
|
|
170
|
+
"attributes": _attrs(span.attributes),
|
|
171
|
+
"events": [{"timeUnixNano": _nanos(e["time"]), "name": e["name"],
|
|
172
|
+
"attributes": _attrs(e["attributes"])} for e in span.events],
|
|
173
|
+
"status": status,
|
|
174
|
+
}],
|
|
175
|
+
}],
|
|
176
|
+
}]}
|
|
177
|
+
|
|
178
|
+
def write(self, span: OTelSpan, path: str | os.PathLike | None = None, stdout: bool = False) -> Path | None:
|
|
179
|
+
"""Append the span as one OTLP/JSON line to ``path`` (default .agent-certify/traces.jsonl), or stdout."""
|
|
180
|
+
line = json.dumps(self.to_otlp_json(span), separators=(",", ":"))
|
|
181
|
+
if stdout:
|
|
182
|
+
sys.stdout.write(line + "\n")
|
|
183
|
+
sys.stdout.flush()
|
|
184
|
+
return None
|
|
185
|
+
p = Path(path) if path is not None else DEFAULT_TRACES_PATH
|
|
186
|
+
ensure_state_dir(p)
|
|
187
|
+
with open(p, "a", encoding="utf-8") as f:
|
|
188
|
+
f.write(line + "\n")
|
|
189
|
+
return p
|
|
190
|
+
|
|
191
|
+
@staticmethod
|
|
192
|
+
def _trace_id(session_id: str | None) -> str:
|
|
193
|
+
if not session_id:
|
|
194
|
+
return secrets.token_hex(16)
|
|
195
|
+
return hashlib.sha256(f"agent-certify:{session_id}".encode()).hexdigest()[:32]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# agent-certify — Structural verification of multiagent systems
|
|
2
|
+
# Copyright 2026 Cognitive Engineering (Switzerland)
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
from agent_certify.parser.auto import AutoParser, detect_format
|
|
5
|
+
from agent_certify.parser.base import BaseParser
|
|
6
|
+
from agent_certify.parser.claude_code import ClaudeCodeParser
|
|
7
|
+
from agent_certify.parser.cursor_trace import CursorTraceParser
|
|
8
|
+
from agent_certify.parser.mcp_logs import MCPLogsParser
|
|
9
|
+
|
|
10
|
+
__all__ = ["AutoParser", "BaseParser", "ClaudeCodeParser", "CursorTraceParser", "MCPLogsParser", "detect_format"]
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
# agent-certify — Structural verification of multiagent systems
|
|
2
|
+
# Copyright 2026 Cognitive Engineering (Switzerland)
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""Input format auto-detection.
|
|
5
|
+
|
|
6
|
+
Detection looks at the content, not only the extension: Agent Trace's own
|
|
7
|
+
storage file is ``.agent-trace/traces.jsonl``, which is as ``.jsonl`` as a
|
|
8
|
+
Claude Code transcript.
|
|
9
|
+
|
|
10
|
+
================================== ===================================
|
|
11
|
+
input parser
|
|
12
|
+
================================== ===================================
|
|
13
|
+
``*.agent-trace`` / ``.agent-trace/`` :class:`CursorTraceParser`
|
|
14
|
+
``*.jsonl`` with trace records :class:`CursorTraceParser`
|
|
15
|
+
``*.jsonl`` with MCP log records :class:`MCPLogsParser`
|
|
16
|
+
other ``*.jsonl`` (incl. empty) :class:`ClaudeCodeParser`
|
|
17
|
+
anything else ``ValueError``
|
|
18
|
+
================================== ===================================
|
|
19
|
+
"""
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from agent_certify.graph import AgentGraph
|
|
25
|
+
from agent_certify.parser.base import BaseParser, decode_json, session_files
|
|
26
|
+
from agent_certify.parser.claude_code import ClaudeCodeParser
|
|
27
|
+
from agent_certify.parser.cursor_trace import TRACE_DIR, TRACE_SUFFIX, CursorTraceParser, looks_like_trace_record
|
|
28
|
+
from agent_certify.parser.mcp_logs import MCPLogsParser
|
|
29
|
+
from agent_certify.paths import iter_lines
|
|
30
|
+
|
|
31
|
+
CLAUDE, CURSOR, MCP_LOG = "claude-code", "cursor-agent-trace", "mcp-log"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def is_trace_dir(p: Path) -> bool:
|
|
35
|
+
"""A ``.agent-trace`` folder, or a repository holding one and no sessions of its own."""
|
|
36
|
+
return p.is_dir() and (p.name == TRACE_DIR or ((p / TRACE_DIR).is_dir() and not any(p.glob("*.jsonl"))))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def detect_format(path: str | Path) -> str:
|
|
40
|
+
"""Name of the format at ``path``; raises ``ValueError`` when unsupported."""
|
|
41
|
+
p = Path(path)
|
|
42
|
+
if p.is_dir():
|
|
43
|
+
if is_trace_dir(p):
|
|
44
|
+
return CURSOR
|
|
45
|
+
raise ValueError(f"{p} is a directory; use parse_directory()")
|
|
46
|
+
if p.suffix == TRACE_SUFFIX:
|
|
47
|
+
return CURSOR
|
|
48
|
+
if p.suffix != ".jsonl":
|
|
49
|
+
raise ValueError(f"Unknown format: {p} (expected .jsonl or .agent-trace)")
|
|
50
|
+
for i, (_, line) in enumerate(iter_lines(p)): # bounded reads: a huge first line is skipped
|
|
51
|
+
if i >= 20:
|
|
52
|
+
break
|
|
53
|
+
if line is None or not line.strip():
|
|
54
|
+
continue
|
|
55
|
+
rec = decode_json(line.strip())
|
|
56
|
+
if looks_like_trace_record(rec):
|
|
57
|
+
return CURSOR
|
|
58
|
+
if isinstance(rec, dict) and "sessionId" in rec and "cwd" in rec and "type" not in rec \
|
|
59
|
+
and ("debug" in rec or "error" in rec):
|
|
60
|
+
return MCP_LOG
|
|
61
|
+
if isinstance(rec, dict):
|
|
62
|
+
return CLAUDE
|
|
63
|
+
return CLAUDE # empty or unreadable lines: v0.1 behaviour
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class AutoParser(BaseParser):
|
|
67
|
+
"""Auto-detect input format and use the right parser.
|
|
68
|
+
|
|
69
|
+
Usage::
|
|
70
|
+
|
|
71
|
+
AutoParser().parse("session.jsonl") # Claude Code
|
|
72
|
+
AutoParser().parse(".agent-trace/traces.jsonl") # Cursor
|
|
73
|
+
AutoParser().parse_directory("~/.claude/projects/C--dev-x/") # every session found
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
def __init__(self):
|
|
77
|
+
self.claude = ClaudeCodeParser()
|
|
78
|
+
self.cursor = CursorTraceParser()
|
|
79
|
+
self.mcp = MCPLogsParser()
|
|
80
|
+
self.last_format: str | None = None
|
|
81
|
+
|
|
82
|
+
def parse(self, path: str) -> AgentGraph:
|
|
83
|
+
p = self._expand(path)
|
|
84
|
+
if not p.exists():
|
|
85
|
+
raise FileNotFoundError(p)
|
|
86
|
+
if p.is_dir() and not is_trace_dir(p):
|
|
87
|
+
graphs = self.parse_directory(str(p))
|
|
88
|
+
if not graphs:
|
|
89
|
+
raise ValueError(f"no supported sessions under {p}")
|
|
90
|
+
return graphs[0] if len(graphs) == 1 else AgentGraph.merge(graphs, session_id=p.name)
|
|
91
|
+
fmt = detect_format(p)
|
|
92
|
+
self.last_format = fmt
|
|
93
|
+
if fmt == CURSOR:
|
|
94
|
+
return self.cursor.parse(str(p))
|
|
95
|
+
if fmt == MCP_LOG:
|
|
96
|
+
return self.mcp.parse(str(p))
|
|
97
|
+
return self.claude.parse(str(p))
|
|
98
|
+
|
|
99
|
+
def parse_directory(self, directory: str) -> list[AgentGraph]:
|
|
100
|
+
"""Every Claude Code session and Cursor trace under ``directory``.
|
|
101
|
+
|
|
102
|
+
Claude Code sessions are found as :meth:`ClaudeCodeParser.parse_directory`
|
|
103
|
+
finds them (``*.jsonl`` here, or one level down). Sub-agent transcripts
|
|
104
|
+
are read with their parent session, and MCP server logs are left out
|
|
105
|
+
(they enrich a session; see ``--include-mcp``).
|
|
106
|
+
"""
|
|
107
|
+
d = self._expand(directory)
|
|
108
|
+
if not d.is_dir():
|
|
109
|
+
raise NotADirectoryError(d)
|
|
110
|
+
graphs = []
|
|
111
|
+
for f in session_files(d):
|
|
112
|
+
fmt = detect_format(f)
|
|
113
|
+
if fmt == CLAUDE:
|
|
114
|
+
graphs.append(self.claude.parse(str(f)))
|
|
115
|
+
elif fmt == CURSOR and f.parent.name != TRACE_DIR:
|
|
116
|
+
graphs.append(self.cursor.parse(str(f))) # a loose traces file; .agent-trace dirs come below
|
|
117
|
+
graphs += [self.cursor.parse(str(t)) for t in self.cursor.find_traces(str(d))]
|
|
118
|
+
return graphs
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
# agent-certify — Structural verification of multiagent systems
|
|
2
|
+
# Copyright 2026 Cognitive Engineering (Switzerland)
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""Parser interface and the reading helpers every parser shares.
|
|
5
|
+
|
|
6
|
+
Logs are untrusted input. The helpers here make every parser fail soft: a
|
|
7
|
+
line that is malformed, nested deeply enough to exhaust the decoder
|
|
8
|
+
(``RecursionError``), or large enough to exhaust memory is counted as skipped
|
|
9
|
+
instead of aborting the scan, and directory scans stop at
|
|
10
|
+
:data:`agent_certify.paths.MAX_FILES` files.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import logging
|
|
16
|
+
from abc import ABC, abstractmethod
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from agent_certify.graph import AgentGraph
|
|
20
|
+
from agent_certify.paths import MAX_FILES
|
|
21
|
+
|
|
22
|
+
logger = logging.getLogger(__name__)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class BaseParser(ABC):
|
|
26
|
+
"""Reads one framework's session logs into an :class:`AgentGraph`."""
|
|
27
|
+
|
|
28
|
+
@abstractmethod
|
|
29
|
+
def parse(self, path: str) -> AgentGraph:
|
|
30
|
+
"""Parse one session into an AgentGraph."""
|
|
31
|
+
|
|
32
|
+
def parse_directory(self, directory: str) -> list[AgentGraph]:
|
|
33
|
+
"""Parse every session found under ``directory``."""
|
|
34
|
+
raise NotImplementedError(f"{type(self).__name__} does not support directories")
|
|
35
|
+
|
|
36
|
+
@staticmethod
|
|
37
|
+
def _expand(path: str) -> Path:
|
|
38
|
+
"""``~`` only: parsers never expand environment variables (the CLI does, for typed paths)."""
|
|
39
|
+
return Path(path).expanduser()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def decode_json(text: str):
|
|
43
|
+
"""``json.loads`` that returns None instead of raising, NaN/Infinity included."""
|
|
44
|
+
try:
|
|
45
|
+
return json.loads(text, parse_constant=_no_constant)
|
|
46
|
+
except (ValueError, RecursionError, MemoryError): # JSONDecodeError is a ValueError
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _no_constant(name: str):
|
|
51
|
+
raise ValueError(f"{name} is not valid JSON")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def session_files(directory: Path, max_files: int = MAX_FILES) -> list[Path]:
|
|
55
|
+
"""Session transcripts in a project folder (``*.jsonl``), or one level down for ``~/.claude/projects``.
|
|
56
|
+
|
|
57
|
+
At most ``max_files`` are returned (newest kept when there are more); a
|
|
58
|
+
warning says how many were left out.
|
|
59
|
+
"""
|
|
60
|
+
files = sorted(directory.glob("*.jsonl"))
|
|
61
|
+
if not files:
|
|
62
|
+
files = sorted(f for sub in sorted(directory.iterdir()) if sub.is_dir() and not sub.name.startswith(".")
|
|
63
|
+
for f in sub.glob("*.jsonl"))
|
|
64
|
+
if len(files) > max_files:
|
|
65
|
+
logger.warning("%s: %d session files, reading the %d most recent", directory, len(files), max_files)
|
|
66
|
+
files = sorted(sorted(files, key=lambda f: f.stat().st_mtime, reverse=True)[:max_files])
|
|
67
|
+
return files
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
# agent-certify — Structural verification of multiagent systems
|
|
2
|
+
# Copyright 2026 Cognitive Engineering (Switzerland)
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""Claude Code session parser.
|
|
5
|
+
|
|
6
|
+
Claude Code writes one JSONL transcript per session under
|
|
7
|
+
``~/.claude/projects/<project>/<session-id>.jsonl``. Each line is a record such
|
|
8
|
+
as ``{"type": "assistant", "message": {"role": "assistant", "content": [...]}}``.
|
|
9
|
+
Assistant content holds ``tool_use`` blocks (``id``, ``name``, ``input``); user
|
|
10
|
+
content holds the matching ``tool_result`` blocks (``tool_use_id``,
|
|
11
|
+
``is_error``). One assistant message may be streamed over several records, so
|
|
12
|
+
tool calls are de-duplicated by their ``id``.
|
|
13
|
+
|
|
14
|
+
Sub-agents spawned through the ``Agent`` (formerly ``Task``) tool keep their own
|
|
15
|
+
transcript in ``<session-id>/subagents/agent-<agent-id>.jsonl``, with a
|
|
16
|
+
``.meta.json`` beside it naming the ``toolUseId`` that spawned it. The parser
|
|
17
|
+
follows those links, so a session's graph contains every sub-agent and every
|
|
18
|
+
tool it used. Tools are shared nodes: when the orchestrator and a sub-agent
|
|
19
|
+
both call ``Bash``, both edges end at ``tool:Bash``.
|
|
20
|
+
|
|
21
|
+
Node ids: ``human``, ``claude`` (the orchestrator), ``agent:<agent-id>``,
|
|
22
|
+
``tool:<tool-name>``.
|
|
23
|
+
"""
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import json
|
|
27
|
+
import logging
|
|
28
|
+
from collections.abc import Iterator
|
|
29
|
+
from datetime import datetime, timezone
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
|
|
32
|
+
from agent_certify.graph import AgentGraph
|
|
33
|
+
from agent_certify.parser.base import BaseParser, decode_json, session_files
|
|
34
|
+
from agent_certify.paths import MAX_LINE_BYTES, iter_lines
|
|
35
|
+
|
|
36
|
+
logger = logging.getLogger(__name__)
|
|
37
|
+
|
|
38
|
+
HUMAN = "human"
|
|
39
|
+
ORCHESTRATOR = "claude"
|
|
40
|
+
|
|
41
|
+
# Tools that spawn a sub-agent. Matching on "agent"/"Task" substrings would also
|
|
42
|
+
# catch TaskStop, TaskList, ListAgents..., which manage agents but spawn none.
|
|
43
|
+
SPAWN_TOOLS = {"Agent", "Task"}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def tool_id(name: str) -> str:
|
|
47
|
+
return f"tool:{name}"
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def agent_id(aid: str) -> str:
|
|
51
|
+
return f"agent:{aid}"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class ClaudeCodeParser(BaseParser):
|
|
55
|
+
"""Parse Claude Code JSONL transcripts into agent graphs.
|
|
56
|
+
|
|
57
|
+
Usage::
|
|
58
|
+
|
|
59
|
+
parser = ClaudeCodeParser()
|
|
60
|
+
graph = parser.parse("~/.claude/projects/-home-me-proj/<session>.jsonl")
|
|
61
|
+
graphs = parser.parse_directory("~/.claude/projects/-home-me-proj/")
|
|
62
|
+
|
|
63
|
+
``include_subagents=False`` ignores sub-agent transcripts; spawned agents
|
|
64
|
+
then appear as leaf nodes. ``include_human=False`` drops the human node.
|
|
65
|
+
After a parse, ``skipped_lines`` (and ``graph.skipped_records``) hold the
|
|
66
|
+
number of lines that could not be read: malformed or too deeply nested JSON,
|
|
67
|
+
or a line over :data:`agent_certify.paths.MAX_LINE_BYTES`.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
def __init__(self, include_subagents: bool = True, include_human: bool = True):
|
|
71
|
+
self.include_subagents = include_subagents
|
|
72
|
+
self.include_human = include_human
|
|
73
|
+
self.skipped_lines = 0
|
|
74
|
+
|
|
75
|
+
# ------------------------------------------------------------------ api
|
|
76
|
+
def parse(self, path: str) -> AgentGraph:
|
|
77
|
+
"""Parse a Claude Code JSONL session into an AgentGraph."""
|
|
78
|
+
p = self._expand(path)
|
|
79
|
+
if not p.is_file():
|
|
80
|
+
raise FileNotFoundError(p)
|
|
81
|
+
self.skipped_lines = 0
|
|
82
|
+
g = AgentGraph(session_id=p.stem, project=p.parent.name)
|
|
83
|
+
g.add_node(ORCHESTRATOR, "orchestrator", "claude")
|
|
84
|
+
state = _State()
|
|
85
|
+
sub_dir = p.parent / p.stem / "subagents"
|
|
86
|
+
metas = _load_metas(sub_dir)
|
|
87
|
+
state.spawn_links = {m["toolUseId"]: aid for aid, m in metas.items() if "toolUseId" in m}
|
|
88
|
+
|
|
89
|
+
self._read_transcript(p, ORCHESTRATOR, g, state, is_main=True)
|
|
90
|
+
|
|
91
|
+
if self.include_subagents and sub_dir.is_dir():
|
|
92
|
+
for f in sorted(sub_dir.glob("agent-*.jsonl")):
|
|
93
|
+
aid = f.stem[len("agent-"):]
|
|
94
|
+
meta = metas.get(aid, {})
|
|
95
|
+
node = agent_id(aid)
|
|
96
|
+
if node not in g.nodes:
|
|
97
|
+
# Spawned from somewhere the transcripts do not show
|
|
98
|
+
# (e.g. a workflow script); attach it to the orchestrator.
|
|
99
|
+
g.add_node(node, "agent", _agent_label(meta.get("agentType"), meta.get("description"), aid),
|
|
100
|
+
spawned_by="unknown")
|
|
101
|
+
g.add_call(ORCHESTRATOR, node)
|
|
102
|
+
g.nodes[node].metadata.update({k: meta[k] for k in ("agentType", "description", "spawnDepth")
|
|
103
|
+
if k in meta})
|
|
104
|
+
g.nodes[node].metadata["transcript"] = str(f)
|
|
105
|
+
self._read_transcript(f, node, g, state, is_main=False)
|
|
106
|
+
|
|
107
|
+
g.total_messages = state.messages
|
|
108
|
+
g.total_tool_calls = len(state.calls)
|
|
109
|
+
if state.first and state.last:
|
|
110
|
+
g.duration_seconds = (state.last - state.first).total_seconds()
|
|
111
|
+
g.started_at = _iso(state.first)
|
|
112
|
+
g.ended_at = _iso(state.last)
|
|
113
|
+
g.skipped_records = self.skipped_lines
|
|
114
|
+
if self.skipped_lines:
|
|
115
|
+
logger.warning("%s: skipped %d unreadable line(s)", p, self.skipped_lines)
|
|
116
|
+
return g
|
|
117
|
+
|
|
118
|
+
def parse_directory(self, directory: str) -> list[AgentGraph]:
|
|
119
|
+
"""Parse all JSONL files in a ``~/.claude/projects/`` subdirectory.
|
|
120
|
+
|
|
121
|
+
Given ``~/.claude/projects/`` itself, parses every project under it.
|
|
122
|
+
Sub-agent transcripts are read as part of their parent session, not as
|
|
123
|
+
sessions of their own.
|
|
124
|
+
"""
|
|
125
|
+
d = self._expand(directory)
|
|
126
|
+
if not d.is_dir():
|
|
127
|
+
raise NotADirectoryError(d)
|
|
128
|
+
files = session_files(d)
|
|
129
|
+
graphs = []
|
|
130
|
+
for f in files:
|
|
131
|
+
try:
|
|
132
|
+
graphs.append(self.parse(str(f)))
|
|
133
|
+
except OSError as exc:
|
|
134
|
+
logger.warning("%s: cannot read (%s)", f, exc)
|
|
135
|
+
return graphs
|
|
136
|
+
|
|
137
|
+
# ------------------------------------------------------------ internals
|
|
138
|
+
def _read_transcript(self, path: Path, caller: str, g: AgentGraph, state: _State, is_main: bool) -> None:
|
|
139
|
+
for rec in self._records(path):
|
|
140
|
+
rtype = rec.get("type")
|
|
141
|
+
msg = rec.get("message")
|
|
142
|
+
if rtype not in ("user", "assistant") or not isinstance(msg, dict):
|
|
143
|
+
continue
|
|
144
|
+
state.messages += 1
|
|
145
|
+
ts = _timestamp(rec.get("timestamp"))
|
|
146
|
+
if ts:
|
|
147
|
+
state.first = min(state.first or ts, ts)
|
|
148
|
+
state.last = max(state.last or ts, ts)
|
|
149
|
+
|
|
150
|
+
# Old transcripts inline sub-agent ("sidechain") records in the main file.
|
|
151
|
+
who = caller
|
|
152
|
+
if is_main and rec.get("isSidechain"):
|
|
153
|
+
who = agent_id(rec.get("agentId") or "sidechain")
|
|
154
|
+
if who not in g.nodes:
|
|
155
|
+
g.add_node(who, "agent", who.split(":", 1)[1])
|
|
156
|
+
g.add_call(ORCHESTRATOR, who)
|
|
157
|
+
|
|
158
|
+
content = msg.get("content")
|
|
159
|
+
if rtype == "assistant":
|
|
160
|
+
if isinstance(content, list):
|
|
161
|
+
for block in content:
|
|
162
|
+
if isinstance(block, dict) and block.get("type") == "tool_use":
|
|
163
|
+
self._tool_use(block, who, g, state)
|
|
164
|
+
else:
|
|
165
|
+
self._user(rec, content, who, g, state, is_main)
|
|
166
|
+
|
|
167
|
+
def _tool_use(self, block: dict, caller: str, g: AgentGraph, state: _State) -> None:
|
|
168
|
+
call_id = block.get("id")
|
|
169
|
+
name = block.get("name") or "unknown"
|
|
170
|
+
if call_id in state.calls:
|
|
171
|
+
return # same block re-streamed in a later record
|
|
172
|
+
inp = block.get("input") if isinstance(block.get("input"), dict) else {}
|
|
173
|
+
if name in SPAWN_TOOLS or "subagent_type" in inp:
|
|
174
|
+
linked = state.spawn_links.get(call_id)
|
|
175
|
+
target = agent_id(linked or call_id or f"anon{len(state.calls)}")
|
|
176
|
+
g.add_node(target, "agent", _agent_label(inp.get("subagent_type"), inp.get("description"), linked),
|
|
177
|
+
spawned_via=name, spawn_call_id=call_id,
|
|
178
|
+
**({"agentType": inp["subagent_type"]} if inp.get("subagent_type") else {}))
|
|
179
|
+
else:
|
|
180
|
+
target = tool_id(name)
|
|
181
|
+
g.add_node(target, "tool", name)
|
|
182
|
+
g.add_call(caller, target)
|
|
183
|
+
state.calls[call_id or f"anon{len(state.calls)}"] = (caller, target)
|
|
184
|
+
|
|
185
|
+
def _user(self, rec: dict, content, caller: str, g: AgentGraph, state: _State, is_main: bool) -> None:
|
|
186
|
+
if isinstance(content, list):
|
|
187
|
+
results = [b for b in content if isinstance(b, dict) and b.get("type") == "tool_result"]
|
|
188
|
+
for b in results:
|
|
189
|
+
rid = b.get("tool_use_id")
|
|
190
|
+
if rid in state.results:
|
|
191
|
+
continue
|
|
192
|
+
state.results.add(rid)
|
|
193
|
+
if b.get("is_error") and rid in state.calls:
|
|
194
|
+
g.record_error(*state.calls[rid])
|
|
195
|
+
if results:
|
|
196
|
+
return
|
|
197
|
+
# A prompt typed by the person. A sub-agent's first "user" message is
|
|
198
|
+
# its parent's prompt, already covered by the spawn edge.
|
|
199
|
+
if (self.include_human and is_main and caller == ORCHESTRATOR and not rec.get("isMeta")
|
|
200
|
+
and not rec.get("isCompactSummary") and content):
|
|
201
|
+
g.add_node(HUMAN, "human", "human")
|
|
202
|
+
g.add_call(HUMAN, ORCHESTRATOR)
|
|
203
|
+
|
|
204
|
+
def _records(self, path: Path) -> Iterator[dict]:
|
|
205
|
+
"""Stream records, skipping lines that are malformed, too deeply nested or too long."""
|
|
206
|
+
for lineno, line in iter_lines(path):
|
|
207
|
+
if line is None:
|
|
208
|
+
self.skipped_lines += 1
|
|
209
|
+
logger.debug("%s:%d: line over the size limit, skipped", path, lineno)
|
|
210
|
+
continue
|
|
211
|
+
line = line.strip()
|
|
212
|
+
if not line:
|
|
213
|
+
continue
|
|
214
|
+
rec = decode_json(line)
|
|
215
|
+
if isinstance(rec, dict):
|
|
216
|
+
yield rec
|
|
217
|
+
else:
|
|
218
|
+
self.skipped_lines += 1
|
|
219
|
+
logger.debug("%s:%d: unreadable record, skipped", path, lineno)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
class _State:
|
|
223
|
+
def __init__(self):
|
|
224
|
+
self.messages = 0
|
|
225
|
+
self.calls: dict[str, tuple[str, str]] = {} # tool_use id -> (caller, target)
|
|
226
|
+
self.results: set[str] = set()
|
|
227
|
+
self.spawn_links: dict[str, str] = {} # spawning tool_use id -> agent id
|
|
228
|
+
self.first: datetime | None = None
|
|
229
|
+
self.last: datetime | None = None
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _load_metas(sub_dir: Path) -> dict[str, dict]:
|
|
233
|
+
metas = {}
|
|
234
|
+
if not sub_dir.is_dir():
|
|
235
|
+
return metas
|
|
236
|
+
for m in sub_dir.glob("agent-*.meta.json"):
|
|
237
|
+
try:
|
|
238
|
+
meta = json.loads(m.read_text(encoding="utf-8")) if m.stat().st_size <= MAX_LINE_BYTES else None
|
|
239
|
+
except (OSError, ValueError, RecursionError):
|
|
240
|
+
meta = None
|
|
241
|
+
if isinstance(meta, dict):
|
|
242
|
+
metas[m.name[len("agent-"):-len(".meta.json")]] = meta
|
|
243
|
+
else:
|
|
244
|
+
logger.warning("%s: unreadable sub-agent metadata", m)
|
|
245
|
+
return metas
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _agent_label(agent_type: str | None, description: str | None, aid: str | None) -> str:
|
|
249
|
+
parts = [p for p in (agent_type, description) if p]
|
|
250
|
+
if parts:
|
|
251
|
+
return ": ".join(parts)
|
|
252
|
+
return f"agent-{aid}" if aid else "sub-agent"
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _iso(ts: datetime) -> str:
|
|
256
|
+
if ts.tzinfo is not None:
|
|
257
|
+
ts = ts.astimezone(timezone.utc).replace(tzinfo=None)
|
|
258
|
+
return ts.strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _timestamp(value) -> datetime | None:
|
|
262
|
+
if not isinstance(value, str):
|
|
263
|
+
return None
|
|
264
|
+
try:
|
|
265
|
+
return datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
266
|
+
except ValueError:
|
|
267
|
+
return None
|