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
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# agent-certify — Structural verification of multiagent systems
|
|
2
|
+
# Copyright 2026 Cognitive Engineering (Switzerland)
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""agent-certify: structural verification of multiagent systems."""
|
|
5
|
+
__version__ = "0.5.0"
|
|
6
|
+
|
|
7
|
+
from agent_certify.anomaly import Anomaly, AnomalyDetector, AnomalyReport
|
|
8
|
+
from agent_certify.baseline import Baseline, BaselineLearner, load_baseline
|
|
9
|
+
from agent_certify.blast import BlastRadiusAnalyzer, BlastReport
|
|
10
|
+
from agent_certify.certificate import AgentCertificate, DriftReport, generate_keypair, graph_hash
|
|
11
|
+
from agent_certify.graph import AgentEdge, AgentGraph, AgentNode
|
|
12
|
+
from agent_certify.mcp_server import AgentCertifyMCPServer
|
|
13
|
+
from agent_certify.otel import OTelExporter, OTelSpan
|
|
14
|
+
from agent_certify.parser import AutoParser, BaseParser, ClaudeCodeParser, CursorTraceParser, MCPLogsParser
|
|
15
|
+
from agent_certify.policy import Policy, PolicyGenerator, PolicyRule, PolicyViolation
|
|
16
|
+
from agent_certify.scanner import AgentFIScanner, Perspective, ScanResult, compute_fi
|
|
17
|
+
from agent_certify.watcher import SessionWatcher
|
|
18
|
+
|
|
19
|
+
__all__ = [
|
|
20
|
+
"AgentCertificate",
|
|
21
|
+
"AgentCertifyMCPServer",
|
|
22
|
+
"AgentEdge",
|
|
23
|
+
"AgentFIScanner",
|
|
24
|
+
"AgentGraph",
|
|
25
|
+
"AgentNode",
|
|
26
|
+
"Anomaly",
|
|
27
|
+
"AnomalyDetector",
|
|
28
|
+
"AnomalyReport",
|
|
29
|
+
"AutoParser",
|
|
30
|
+
"BaseParser",
|
|
31
|
+
"Baseline",
|
|
32
|
+
"BaselineLearner",
|
|
33
|
+
"BlastRadiusAnalyzer",
|
|
34
|
+
"BlastReport",
|
|
35
|
+
"ClaudeCodeParser",
|
|
36
|
+
"CursorTraceParser",
|
|
37
|
+
"DriftReport",
|
|
38
|
+
"MCPLogsParser",
|
|
39
|
+
"OTelExporter",
|
|
40
|
+
"OTelSpan",
|
|
41
|
+
"Perspective",
|
|
42
|
+
"Policy",
|
|
43
|
+
"PolicyGenerator",
|
|
44
|
+
"PolicyRule",
|
|
45
|
+
"PolicyViolation",
|
|
46
|
+
"ScanResult",
|
|
47
|
+
"SessionWatcher",
|
|
48
|
+
"__version__",
|
|
49
|
+
"compute_fi",
|
|
50
|
+
"generate_keypair",
|
|
51
|
+
"graph_hash",
|
|
52
|
+
"load_baseline",
|
|
53
|
+
]
|
agent_certify/anomaly.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
# agent-certify — Structural verification of multiagent systems
|
|
2
|
+
# Copyright 2026 Cognitive Engineering (Switzerland)
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""Anomaly detection against a learned baseline.
|
|
5
|
+
|
|
6
|
+
Each check compares one aspect of a session with the :class:`Baseline`:
|
|
7
|
+
|
|
8
|
+
============== ========================================= ======================
|
|
9
|
+
check flags severity
|
|
10
|
+
============== ========================================= ======================
|
|
11
|
+
new_tool a tool never seen in the baseline critical
|
|
12
|
+
new_link an invocation path never seen (by role) warning
|
|
13
|
+
fi_deviation FI more than 2 sigma from the mean warning; critical past
|
|
14
|
+
3 sigma when FI *rose*
|
|
15
|
+
error_rate error rate more than 2 sigma *above* warning; critical past
|
|
16
|
+
3 sigma
|
|
17
|
+
sub_agents more sub-agents than ever seen, or 2 sigma warning; critical when
|
|
18
|
+
above the mean above max *and* 3 sigma
|
|
19
|
+
node_count node count more than 2 sigma from mean info; warning past 3
|
|
20
|
+
============== ========================================= ======================
|
|
21
|
+
|
|
22
|
+
A falling FI means added redundancy (usually sub-agents sharing tools), a
|
|
23
|
+
structural change worth knowing about but not a risk in itself, so it never
|
|
24
|
+
goes past warning. When the baseline never varied on a metric (std 0), z is
|
|
25
|
+
undefined: any difference is reported with ``z_score=None`` at the lower
|
|
26
|
+
severity.
|
|
27
|
+
"""
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
from dataclasses import asdict, dataclass
|
|
31
|
+
|
|
32
|
+
from agent_certify.baseline import Baseline, node_role
|
|
33
|
+
from agent_certify.graph import AgentGraph
|
|
34
|
+
from agent_certify.scanner import ScanResult
|
|
35
|
+
|
|
36
|
+
CRITICAL, WARNING, INFO = "critical", "warning", "info"
|
|
37
|
+
_ORDER = {CRITICAL: 0, WARNING: 1, INFO: 2}
|
|
38
|
+
_CATEGORICAL = {"new_tool", "new_link"}
|
|
39
|
+
_EPS = 1e-9
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Anomaly:
|
|
44
|
+
"""A single detected anomaly."""
|
|
45
|
+
severity: str # "critical", "warning", "info"
|
|
46
|
+
category: str # "new_tool", "fi_deviation", "error_rate", "new_link", "sub_agents", "node_count"
|
|
47
|
+
message: str # human-readable description
|
|
48
|
+
value: float | str # the observed value
|
|
49
|
+
baseline_value: str # what the baseline says (e.g., "0.87 ± 0.12")
|
|
50
|
+
z_score: float | None # how many std deviations from mean (None for categorical)
|
|
51
|
+
detail: str = "" # context: why it may have happened
|
|
52
|
+
|
|
53
|
+
def to_dict(self) -> dict:
|
|
54
|
+
return asdict(self)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class AnomalyReport:
|
|
59
|
+
"""All anomalies detected in a session compared to baseline."""
|
|
60
|
+
session_id: str
|
|
61
|
+
anomalies: list[Anomaly]
|
|
62
|
+
baseline_source: str # path to baseline.json
|
|
63
|
+
learned_from: int = 0
|
|
64
|
+
|
|
65
|
+
@property
|
|
66
|
+
def has_critical(self) -> bool:
|
|
67
|
+
return any(a.severity == CRITICAL for a in self.anomalies)
|
|
68
|
+
|
|
69
|
+
def count(self, severity: str) -> int:
|
|
70
|
+
return sum(1 for a in self.anomalies if a.severity == severity)
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def summary(self) -> str:
|
|
74
|
+
if not self.anomalies:
|
|
75
|
+
return f"No anomalies against baseline of {self.learned_from} session(s)"
|
|
76
|
+
parts = [f"{self.count(s)} {s}" for s in (CRITICAL, WARNING, INFO) if self.count(s)]
|
|
77
|
+
return f"{len(self.anomalies)} anomal{'y' if len(self.anomalies) == 1 else 'ies'} ({', '.join(parts)})"
|
|
78
|
+
|
|
79
|
+
def to_dict(self) -> dict:
|
|
80
|
+
return {"session_id": self.session_id, "baseline_source": self.baseline_source,
|
|
81
|
+
"learned_from": self.learned_from, "summary": self.summary,
|
|
82
|
+
"has_critical": self.has_critical, "anomalies": [a.to_dict() for a in self.anomalies]}
|
|
83
|
+
|
|
84
|
+
def __str__(self) -> str:
|
|
85
|
+
if not self.anomalies:
|
|
86
|
+
return f"✓ {self.summary}"
|
|
87
|
+
lines = [f"⚠ ANOMALIES DETECTED ({len(self.anomalies)}):", ""]
|
|
88
|
+
for a in self.anomalies:
|
|
89
|
+
tag = f"[{a.severity.upper()}]"
|
|
90
|
+
lines.append(f"{tag:<11}{a.message}")
|
|
91
|
+
if a.category in _CATEGORICAL: # numeric messages already carry baseline and z
|
|
92
|
+
lines.append(f"{'':<11}Baseline: {a.baseline_value}")
|
|
93
|
+
if a.detail:
|
|
94
|
+
lines.append(f"{'':<11}{a.detail}")
|
|
95
|
+
lines.append("")
|
|
96
|
+
return "\n".join(lines).rstrip()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _z(value: float, mean: float, std: float) -> float | None:
|
|
100
|
+
return (value - mean) / std if std > _EPS else None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _pm(mean: float, std: float, pct: bool = False) -> str:
|
|
104
|
+
return f"{mean:.1%} ± {std:.1%}" if pct else f"{mean:.2f} ± {std:.2f}"
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class AnomalyDetector:
|
|
108
|
+
"""Compare a session scan against a learned baseline.
|
|
109
|
+
|
|
110
|
+
Usage::
|
|
111
|
+
|
|
112
|
+
detector = AnomalyDetector(load_baseline(".agent-certify/baseline.json"))
|
|
113
|
+
report = detector.detect(graph, AgentFIScanner(graph).scan())
|
|
114
|
+
report.has_critical
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
def __init__(self, baseline: Baseline, source: str = ""):
|
|
118
|
+
self.baseline = baseline
|
|
119
|
+
self.source = source
|
|
120
|
+
|
|
121
|
+
def detect(self, graph: AgentGraph, scan_result: ScanResult) -> AnomalyReport:
|
|
122
|
+
"""Run all anomaly checks."""
|
|
123
|
+
anomalies = []
|
|
124
|
+
anomalies += self._check_new_tools(graph)
|
|
125
|
+
anomalies += self._check_new_links(graph)
|
|
126
|
+
anomalies += self._check_fi(scan_result, graph)
|
|
127
|
+
anomalies += self._check_error_rate(graph)
|
|
128
|
+
anomalies += self._check_sub_agents(graph)
|
|
129
|
+
anomalies += self._check_node_count(graph)
|
|
130
|
+
anomalies.sort(key=lambda a: _ORDER[a.severity])
|
|
131
|
+
return AnomalyReport(session_id=graph.session_id or "", anomalies=anomalies,
|
|
132
|
+
baseline_source=self.source, learned_from=self.baseline.learned_from)
|
|
133
|
+
|
|
134
|
+
# --------------------------------------------------------------- checks
|
|
135
|
+
def _new_tool_names(self, graph: AgentGraph) -> set[str]:
|
|
136
|
+
return {n.name for n in graph.nodes.values() if n.kind == "tool"} - self.baseline.known_tools
|
|
137
|
+
|
|
138
|
+
def _check_new_tools(self, graph: AgentGraph) -> list[Anomaly]:
|
|
139
|
+
"""Flag any tool not in baseline.known_tools. Severity: critical."""
|
|
140
|
+
out = []
|
|
141
|
+
for name in sorted(self._new_tool_names(graph)):
|
|
142
|
+
nid = next(i for i, n in graph.nodes.items() if n.kind == "tool" and n.name == name)
|
|
143
|
+
callers = sorted({e.source for e in graph.edges if e.target == nid})
|
|
144
|
+
out.append(Anomaly(
|
|
145
|
+
CRITICAL, "new_tool", f"New tool never seen: {name}", name,
|
|
146
|
+
f"not in {len(self.baseline.known_tools)} known tools", None,
|
|
147
|
+
f"{graph.nodes[nid].call_count} call(s) by {', '.join(callers) or '-'}"))
|
|
148
|
+
return out
|
|
149
|
+
|
|
150
|
+
def _check_new_links(self, graph: AgentGraph) -> list[Anomaly]:
|
|
151
|
+
"""Flag any (source, target) link not in baseline.known_links. Severity: warning.
|
|
152
|
+
|
|
153
|
+
Links to a new tool are covered by the new_tool anomaly and not repeated.
|
|
154
|
+
"""
|
|
155
|
+
new_tools = {f"tool:{t}" for t in self._new_tool_names(graph)}
|
|
156
|
+
links = {(node_role(graph, e.source), node_role(graph, e.target)) for e in graph.edges}
|
|
157
|
+
out = []
|
|
158
|
+
for s, t in sorted(links - self.baseline.known_links):
|
|
159
|
+
if s in new_tools or t in new_tools:
|
|
160
|
+
continue
|
|
161
|
+
out.append(Anomaly(WARNING, "new_link", f"New communication path: {s} -> {t}", f"{s} -> {t}",
|
|
162
|
+
f"not among {len(self.baseline.known_links)} known links", None))
|
|
163
|
+
return out
|
|
164
|
+
|
|
165
|
+
def _check_fi(self, scan_result: ScanResult, graph: AgentGraph | None = None) -> list[Anomaly]:
|
|
166
|
+
"""Flag if FI deviates > 2 std from baseline mean.
|
|
167
|
+
|
|
168
|
+
Severity: warning past 2 sigma; critical past 3 sigma only when FI rose
|
|
169
|
+
(redundancy lost).
|
|
170
|
+
"""
|
|
171
|
+
b = self.baseline
|
|
172
|
+
fi = scan_result.fi
|
|
173
|
+
z = _z(fi, b.fi_mean, b.fi_std)
|
|
174
|
+
if z is None:
|
|
175
|
+
if abs(fi - b.fi_mean) <= _EPS:
|
|
176
|
+
return []
|
|
177
|
+
severity = WARNING
|
|
178
|
+
elif abs(z) <= 2:
|
|
179
|
+
return []
|
|
180
|
+
else:
|
|
181
|
+
severity = CRITICAL if z > 3 else WARNING
|
|
182
|
+
if fi < b.fi_mean:
|
|
183
|
+
agents = sum(1 for n in graph.nodes.values() if n.kind == "agent") if graph else 0
|
|
184
|
+
detail = ("Sub-agents detected — shared tools add triangles; structural change expected"
|
|
185
|
+
if agents else "More redundant than usual: new cross-links between agents or tools")
|
|
186
|
+
else:
|
|
187
|
+
detail = "Redundancy lost: more links without a backup path than usual"
|
|
188
|
+
return [Anomaly(severity, "fi_deviation",
|
|
189
|
+
f"FI deviation: {fi:.2f} (baseline: {_pm(b.fi_mean, b.fi_std)}"
|
|
190
|
+
+ ("" if z is None else f", z = {z:+.1f}") + ")",
|
|
191
|
+
fi, _pm(b.fi_mean, b.fi_std), z, detail)]
|
|
192
|
+
|
|
193
|
+
def _check_error_rate(self, graph: AgentGraph) -> list[Anomaly]:
|
|
194
|
+
"""Flag if error rate is > 2 std above baseline. Warning past 2 sigma, critical past 3."""
|
|
195
|
+
if not graph.total_tool_calls:
|
|
196
|
+
return []
|
|
197
|
+
b = self.baseline
|
|
198
|
+
rate = sum(n.error_count for n in graph.nodes.values()) / graph.total_tool_calls
|
|
199
|
+
z = _z(rate, b.error_rate_mean, b.error_rate_std)
|
|
200
|
+
if z is None:
|
|
201
|
+
if rate <= b.error_rate_mean + _EPS:
|
|
202
|
+
return []
|
|
203
|
+
severity = WARNING
|
|
204
|
+
elif z <= 2:
|
|
205
|
+
return []
|
|
206
|
+
else:
|
|
207
|
+
severity = CRITICAL if z > 3 else WARNING
|
|
208
|
+
return [Anomaly(severity, "error_rate",
|
|
209
|
+
f"Error rate: {rate:.1%} (baseline: {_pm(b.error_rate_mean, b.error_rate_std, pct=True)}"
|
|
210
|
+
+ ("" if z is None else f", z = {z:+.1f}") + ")",
|
|
211
|
+
rate, _pm(b.error_rate_mean, b.error_rate_std, pct=True), z,
|
|
212
|
+
f"Elevated error rate across {graph.total_tool_calls} tool calls")]
|
|
213
|
+
|
|
214
|
+
def _check_sub_agents(self, graph: AgentGraph) -> list[Anomaly]:
|
|
215
|
+
"""Flag if sub-agent count exceeds max_seen or is > 2 std above the mean.
|
|
216
|
+
|
|
217
|
+
Severity: warning; critical when above max_seen and more than 3 sigma.
|
|
218
|
+
"""
|
|
219
|
+
b = self.baseline
|
|
220
|
+
count = sum(1 for n in graph.nodes.values() if n.kind == "agent")
|
|
221
|
+
z = _z(count, b.sub_agent_count_mean, b.sub_agent_count_std)
|
|
222
|
+
above_max = count > b.max_sub_agents_seen
|
|
223
|
+
if not above_max and (z is None or z <= 2):
|
|
224
|
+
return []
|
|
225
|
+
severity = CRITICAL if above_max and z is not None and z > 3 else WARNING
|
|
226
|
+
types = sorted({node_role(graph, n) for n, node in graph.nodes.items() if node.kind == "agent"})
|
|
227
|
+
return [Anomaly(severity, "sub_agents",
|
|
228
|
+
f"Sub-agents: {count} (baseline: {_pm(b.sub_agent_count_mean, b.sub_agent_count_std)}, "
|
|
229
|
+
f"max seen {b.max_sub_agents_seen})",
|
|
230
|
+
count, f"{_pm(b.sub_agent_count_mean, b.sub_agent_count_std)}, max {b.max_sub_agents_seen}",
|
|
231
|
+
z, f"Types: {', '.join(types)}")]
|
|
232
|
+
|
|
233
|
+
def _check_node_count(self, graph: AgentGraph) -> list[Anomaly]:
|
|
234
|
+
"""Flag if total node count deviates > 2 std. Info past 2 sigma, warning past 3."""
|
|
235
|
+
b = self.baseline
|
|
236
|
+
count = len(graph.nodes)
|
|
237
|
+
z = _z(count, b.node_count_mean, b.node_count_std)
|
|
238
|
+
if z is None:
|
|
239
|
+
if abs(count - b.node_count_mean) <= _EPS:
|
|
240
|
+
return []
|
|
241
|
+
severity = INFO
|
|
242
|
+
elif abs(z) <= 2:
|
|
243
|
+
return []
|
|
244
|
+
else:
|
|
245
|
+
severity = WARNING if abs(z) > 3 else INFO
|
|
246
|
+
return [Anomaly(severity, "node_count",
|
|
247
|
+
f"Node count: {count} (baseline: {_pm(b.node_count_mean, b.node_count_std)}"
|
|
248
|
+
+ ("" if z is None else f", z = {z:+.1f}") + ")",
|
|
249
|
+
count, _pm(b.node_count_mean, b.node_count_std), z,
|
|
250
|
+
"System is larger than usual" if count > b.node_count_mean else "System is smaller than usual")]
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
# agent-certify — Structural verification of multiagent systems
|
|
2
|
+
# Copyright 2026 Cognitive Engineering (Switzerland)
|
|
3
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
"""Statistical baseline learned from past sessions.
|
|
5
|
+
|
|
6
|
+
A :class:`Baseline` summarises what "normal" looks like for a system: the
|
|
7
|
+
spread of FI, size, bridges, sub-agent use and error rate over N sessions, and
|
|
8
|
+
the set of tools and invocation links ever seen. :mod:`agent_certify.anomaly`
|
|
9
|
+
compares new sessions against it.
|
|
10
|
+
|
|
11
|
+
Sub-agent ids are unique per spawn, so links are recorded by *role*: an agent
|
|
12
|
+
node becomes ``agent:<type>`` (``agent:Explore``, ``agent:general-purpose``).
|
|
13
|
+
Tools and the orchestrator keep their ids. Standard deviations are population
|
|
14
|
+
deviations, so a baseline learned from one session has std 0.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import math
|
|
20
|
+
import os
|
|
21
|
+
from dataclasses import MISSING, asdict, dataclass, field, fields
|
|
22
|
+
from datetime import datetime, timezone
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
from agent_certify.graph import AgentGraph
|
|
28
|
+
from agent_certify.paths import ensure_state_dir
|
|
29
|
+
from agent_certify.scanner import AgentFIScanner, ScanResult
|
|
30
|
+
|
|
31
|
+
DEFAULT_BASELINE_PATH = Path(".agent-certify") / "baseline.json"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def node_role(graph: AgentGraph, node_id: str) -> str:
|
|
35
|
+
"""Stable identity of a node across sessions (agents by type); see :meth:`AgentGraph.role`."""
|
|
36
|
+
return graph.role(node_id)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def session_features(graph: AgentGraph, scan: ScanResult | None = None) -> dict:
|
|
40
|
+
"""The per-session numbers a baseline is built from."""
|
|
41
|
+
scan = scan or AgentFIScanner(graph).scan()
|
|
42
|
+
errors = sum(n.error_count for n in graph.nodes.values())
|
|
43
|
+
return {
|
|
44
|
+
"fi": scan.fi,
|
|
45
|
+
"nodes": scan.node_count,
|
|
46
|
+
"edges": scan.edge_count,
|
|
47
|
+
"bridges": len(scan.bridges),
|
|
48
|
+
"tools": {n.name for n in graph.nodes.values() if n.kind == "tool"},
|
|
49
|
+
"sub_agents": sum(1 for n in graph.nodes.values() if n.kind == "agent"),
|
|
50
|
+
"error_rate": errors / graph.total_tool_calls if graph.total_tool_calls else None,
|
|
51
|
+
"links": {(node_role(graph, e.source), node_role(graph, e.target)) for e in graph.edges},
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
@dataclass
|
|
56
|
+
class Baseline:
|
|
57
|
+
"""Statistical baseline learned from N sessions."""
|
|
58
|
+
learned_from: int # number of sessions
|
|
59
|
+
period_start: str # ISO timestamp of earliest session
|
|
60
|
+
period_end: str # ISO timestamp of latest session
|
|
61
|
+
|
|
62
|
+
# Structural stats
|
|
63
|
+
fi_mean: float
|
|
64
|
+
fi_std: float
|
|
65
|
+
node_count_mean: float
|
|
66
|
+
node_count_std: float
|
|
67
|
+
edge_count_mean: float
|
|
68
|
+
edge_count_std: float
|
|
69
|
+
|
|
70
|
+
# Tool usage
|
|
71
|
+
known_tools: set[str] # all tools seen across sessions
|
|
72
|
+
tool_frequency: dict[str, float] # tool -> fraction of sessions it appears in
|
|
73
|
+
|
|
74
|
+
# Agent patterns
|
|
75
|
+
sub_agent_count_mean: float
|
|
76
|
+
sub_agent_count_std: float
|
|
77
|
+
max_sub_agents_seen: int
|
|
78
|
+
|
|
79
|
+
# Error rates
|
|
80
|
+
error_rate_mean: float # errors / total_calls
|
|
81
|
+
error_rate_std: float
|
|
82
|
+
|
|
83
|
+
# Topology
|
|
84
|
+
known_links: set[tuple[str, str]] # all (source, target) role links seen
|
|
85
|
+
bridge_count_mean: float
|
|
86
|
+
bridge_count_std: float
|
|
87
|
+
|
|
88
|
+
# Metadata
|
|
89
|
+
created_at: str
|
|
90
|
+
version: str = "0.2.0"
|
|
91
|
+
fi_min: float = 0.0
|
|
92
|
+
fi_max: float = 0.0
|
|
93
|
+
session_ids: list[str] = field(default_factory=list)
|
|
94
|
+
|
|
95
|
+
def to_dict(self) -> dict:
|
|
96
|
+
d = asdict(self)
|
|
97
|
+
d["known_tools"] = sorted(self.known_tools)
|
|
98
|
+
d["known_links"] = sorted(list(link) for link in self.known_links)
|
|
99
|
+
d["tool_frequency"] = dict(sorted(self.tool_frequency.items(), key=lambda kv: (-kv[1], kv[0])))
|
|
100
|
+
return d
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
def from_dict(cls, data: dict) -> Baseline:
|
|
104
|
+
"""Build a baseline from untrusted JSON data, checking every field.
|
|
105
|
+
|
|
106
|
+
Raises ``ValueError("Invalid baseline format")``; the message deliberately
|
|
107
|
+
names no field or value, since the data may not be a baseline at all.
|
|
108
|
+
"""
|
|
109
|
+
try:
|
|
110
|
+
_check(isinstance(data, dict))
|
|
111
|
+
names = {f.name for f in fields(cls)}
|
|
112
|
+
required = {f.name for f in fields(cls) if f.default is MISSING and f.default_factory is MISSING}
|
|
113
|
+
_check(set(data) <= names and required <= set(data))
|
|
114
|
+
for key in ("learned_from", "max_sub_agents_seen"):
|
|
115
|
+
_check(_is_count(data[key]))
|
|
116
|
+
for key in ("fi_mean", "fi_std", "node_count_mean", "node_count_std", "edge_count_mean",
|
|
117
|
+
"edge_count_std", "sub_agent_count_mean", "sub_agent_count_std", "error_rate_mean",
|
|
118
|
+
"error_rate_std", "bridge_count_mean", "bridge_count_std", "fi_min", "fi_max"):
|
|
119
|
+
if key in data:
|
|
120
|
+
_check(_is_number(data[key]) and data[key] >= 0)
|
|
121
|
+
for key in ("period_start", "period_end", "created_at", "version"):
|
|
122
|
+
if key in data:
|
|
123
|
+
_check(isinstance(data[key], str))
|
|
124
|
+
_check(isinstance(data["known_tools"], list) and all(isinstance(t, str) for t in data["known_tools"]))
|
|
125
|
+
_check(isinstance(data["tool_frequency"], dict)
|
|
126
|
+
and all(isinstance(k, str) and _is_number(v) and 0 <= v <= 1
|
|
127
|
+
for k, v in data["tool_frequency"].items()))
|
|
128
|
+
_check(isinstance(data["known_links"], list)
|
|
129
|
+
and all(isinstance(link, list) and len(link) == 2 and all(isinstance(x, str) for x in link)
|
|
130
|
+
for link in data["known_links"]))
|
|
131
|
+
ids = data.get("session_ids", [])
|
|
132
|
+
_check(isinstance(ids, list) and all(isinstance(x, str) for x in ids))
|
|
133
|
+
data = dict(data)
|
|
134
|
+
data["known_tools"] = set(data["known_tools"])
|
|
135
|
+
data["known_links"] = {tuple(link) for link in data["known_links"]}
|
|
136
|
+
return cls(**data)
|
|
137
|
+
except (TypeError, KeyError, AttributeError):
|
|
138
|
+
raise ValueError("Invalid baseline format") from None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _mean_std(values: list[float]) -> tuple[float, float]:
|
|
142
|
+
if not values:
|
|
143
|
+
return 0.0, 0.0
|
|
144
|
+
a = np.asarray(values, dtype=float)
|
|
145
|
+
return float(a.mean()), float(a.std())
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class BaselineLearner:
|
|
149
|
+
"""Learn a statistical baseline from multiple sessions.
|
|
150
|
+
|
|
151
|
+
Usage::
|
|
152
|
+
|
|
153
|
+
learner = BaselineLearner()
|
|
154
|
+
baseline = learner.learn(["~/.claude/projects/C--dev-myproject/"])
|
|
155
|
+
learner.save(baseline) # .agent-certify/baseline.json
|
|
156
|
+
baseline = learner.load(".agent-certify/baseline.json")
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
def __init__(self, parser=None):
|
|
160
|
+
"""If parser is None, auto-detect each input's format (Claude Code, Cursor Agent Trace)."""
|
|
161
|
+
if parser is None:
|
|
162
|
+
from agent_certify.parser import AutoParser
|
|
163
|
+
parser = AutoParser()
|
|
164
|
+
self.parser = parser
|
|
165
|
+
|
|
166
|
+
def learn(self, paths: list[str]) -> Baseline:
|
|
167
|
+
"""Learn baseline from a list of JSONL session files or directories."""
|
|
168
|
+
if isinstance(paths, (str, os.PathLike)):
|
|
169
|
+
paths = [paths]
|
|
170
|
+
graphs = []
|
|
171
|
+
for raw in paths:
|
|
172
|
+
p = Path(str(raw)).expanduser() # environment variables are the CLI's job, not the library's
|
|
173
|
+
if p.is_dir():
|
|
174
|
+
graphs += self.parser.parse_directory(str(p))
|
|
175
|
+
elif p.is_file():
|
|
176
|
+
graphs.append(self.parser.parse(str(p)))
|
|
177
|
+
else:
|
|
178
|
+
raise FileNotFoundError(p)
|
|
179
|
+
return self.learn_graphs(graphs)
|
|
180
|
+
|
|
181
|
+
def learn_graphs(self, graphs: list[AgentGraph]) -> Baseline:
|
|
182
|
+
"""Learn baseline from already-parsed graphs."""
|
|
183
|
+
if not graphs:
|
|
184
|
+
raise ValueError("no sessions to learn from")
|
|
185
|
+
feats = [session_features(g) for g in graphs]
|
|
186
|
+
n = len(feats)
|
|
187
|
+
|
|
188
|
+
fi_mean, fi_std = _mean_std([f["fi"] for f in feats])
|
|
189
|
+
nodes_mean, nodes_std = _mean_std([f["nodes"] for f in feats])
|
|
190
|
+
edges_mean, edges_std = _mean_std([f["edges"] for f in feats])
|
|
191
|
+
bridges_mean, bridges_std = _mean_std([f["bridges"] for f in feats])
|
|
192
|
+
agents_mean, agents_std = _mean_std([f["sub_agents"] for f in feats])
|
|
193
|
+
err_mean, err_std = _mean_std([f["error_rate"] for f in feats if f["error_rate"] is not None])
|
|
194
|
+
|
|
195
|
+
tool_sessions: dict[str, int] = {}
|
|
196
|
+
for f in feats:
|
|
197
|
+
for t in f["tools"]:
|
|
198
|
+
tool_sessions[t] = tool_sessions.get(t, 0) + 1
|
|
199
|
+
starts = [g.started_at for g in graphs if g.started_at]
|
|
200
|
+
ends = [g.ended_at for g in graphs if g.ended_at]
|
|
201
|
+
from agent_certify import __version__
|
|
202
|
+
|
|
203
|
+
return Baseline(
|
|
204
|
+
learned_from=n,
|
|
205
|
+
period_start=min(starts) if starts else "",
|
|
206
|
+
period_end=max(ends) if ends else "",
|
|
207
|
+
fi_mean=fi_mean, fi_std=fi_std,
|
|
208
|
+
node_count_mean=nodes_mean, node_count_std=nodes_std,
|
|
209
|
+
edge_count_mean=edges_mean, edge_count_std=edges_std,
|
|
210
|
+
known_tools=set(tool_sessions),
|
|
211
|
+
tool_frequency={t: c / n for t, c in tool_sessions.items()},
|
|
212
|
+
sub_agent_count_mean=agents_mean, sub_agent_count_std=agents_std,
|
|
213
|
+
max_sub_agents_seen=max(f["sub_agents"] for f in feats),
|
|
214
|
+
error_rate_mean=err_mean, error_rate_std=err_std,
|
|
215
|
+
known_links=set().union(*(f["links"] for f in feats)),
|
|
216
|
+
bridge_count_mean=bridges_mean, bridge_count_std=bridges_std,
|
|
217
|
+
created_at=datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
218
|
+
version=__version__,
|
|
219
|
+
fi_min=min(f["fi"] for f in feats),
|
|
220
|
+
fi_max=max(f["fi"] for f in feats),
|
|
221
|
+
session_ids=[g.session_id or "" for g in graphs],
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
def save(self, baseline: Baseline, path: str | os.PathLike | None = None) -> Path:
|
|
225
|
+
"""Save baseline as JSON, by default to .agent-certify/baseline.json."""
|
|
226
|
+
p = Path(path) if path is not None else DEFAULT_BASELINE_PATH
|
|
227
|
+
ensure_state_dir(p)
|
|
228
|
+
p.write_text(json.dumps(baseline.to_dict(), indent=2), encoding="utf-8")
|
|
229
|
+
return p
|
|
230
|
+
|
|
231
|
+
def load(self, path: str | os.PathLike) -> Baseline:
|
|
232
|
+
"""Load baseline from JSON."""
|
|
233
|
+
return load_baseline(path)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def load_baseline(path: str | os.PathLike) -> Baseline:
|
|
237
|
+
"""Read a baseline written by :meth:`BaselineLearner.save`; NaN and Infinity are rejected."""
|
|
238
|
+
try:
|
|
239
|
+
data = json.loads(Path(path).read_text(encoding="utf-8"), parse_constant=_reject_constant)
|
|
240
|
+
except (ValueError, UnicodeDecodeError, RecursionError):
|
|
241
|
+
raise ValueError("Invalid baseline format") from None
|
|
242
|
+
return Baseline.from_dict(data)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _reject_constant(name: str):
|
|
246
|
+
raise ValueError("Invalid baseline format")
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _check(ok: bool) -> None:
|
|
250
|
+
if not ok:
|
|
251
|
+
raise ValueError("Invalid baseline format")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _is_count(v) -> bool:
|
|
255
|
+
return isinstance(v, int) and not isinstance(v, bool) and v >= 0
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _is_number(v) -> bool:
|
|
259
|
+
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
|