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/viz.py ADDED
@@ -0,0 +1,299 @@
1
+ # agent-certify — Structural verification of multiagent systems
2
+ # Copyright 2026 Cognitive Engineering (Switzerland)
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """Self-contained HTML view of an agent graph.
5
+
6
+ One file, inline SVG, a few lines of inline script, no external requests.
7
+ Nodes are coloured by structural level (high red, medium amber, low green;
8
+ labelled per perspective), edge width follows call count, bridges are dashed
9
+ red. Hovering a node shows its blast radius and dims everything it cannot
10
+ reach.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import html
15
+ import json
16
+ import math
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+
21
+ from agent_certify.anomaly import AnomalyReport
22
+ from agent_certify.blast import BlastRadiusAnalyzer
23
+ from agent_certify.graph import AgentGraph
24
+ from agent_certify.scanner import HIGH, LEVELS, LOW, AgentFIScanner, Perspective, ScanResult
25
+
26
+ W, H = 960, 680
27
+ _RING = {"orchestrator": 0.0, "human": 0.55, "agent": 0.45, "tool": 0.9, "file": 0.9}
28
+
29
+
30
+ def layout(graph: AgentGraph, iterations: int = 400, seed: int = 7) -> dict[str, tuple[float, float]]:
31
+ """Deterministic Fruchterman–Reingold layout, seeded on rings by node kind."""
32
+ ids = sorted(graph.nodes)
33
+ n = len(ids)
34
+ if n == 0:
35
+ return {}
36
+ if n == 1:
37
+ return {ids[0]: (W / 2, H / 2)}
38
+ rng = np.random.default_rng(seed)
39
+ idx = {nid: i for i, nid in enumerate(ids)}
40
+ pos = np.zeros((n, 2))
41
+ for i, nid in enumerate(ids):
42
+ r = _RING.get(graph.nodes[nid].kind, 0.9)
43
+ a = 2 * math.pi * i / n + rng.uniform(-0.1, 0.1)
44
+ pos[i] = (r * math.cos(a), r * math.sin(a))
45
+ edges = np.array([(idx[a], idx[b]) for a, b in graph.undirected_edges()], dtype=int).reshape(-1, 2)
46
+ k = 1.6 / math.sqrt(n)
47
+ t = 0.15
48
+ for _ in range(iterations):
49
+ delta = pos[:, None, :] - pos[None, :, :]
50
+ dist = np.linalg.norm(delta, axis=2) + 1e-9
51
+ disp = (delta / dist[..., None] * (k * k / dist)[..., None]).sum(axis=1)
52
+ if len(edges):
53
+ d = pos[edges[:, 0]] - pos[edges[:, 1]]
54
+ dl = np.linalg.norm(d, axis=1, keepdims=True) + 1e-9
55
+ f = d / dl * (dl * dl / k)
56
+ np.add.at(disp, edges[:, 0], -f)
57
+ np.add.at(disp, edges[:, 1], f)
58
+ disp -= pos * 0.05 # mild pull to the centre keeps components close
59
+ length = np.linalg.norm(disp, axis=1, keepdims=True) + 1e-9
60
+ pos += disp / length * np.minimum(length, t)
61
+ t *= 0.99
62
+ lo, hi = pos.min(axis=0), pos.max(axis=0)
63
+ span = np.where(hi - lo < 1e-9, 1.0, hi - lo)
64
+ margin = np.array([110.0, 70.0])
65
+ scaled = margin + (pos - lo) / span * (np.array([W, H]) - 2 * margin)
66
+ return {nid: (float(scaled[i, 0]), float(scaled[i, 1])) for i, nid in enumerate(ids)}
67
+
68
+
69
+ def _short(name: str, limit: int = 22) -> str:
70
+ if name.startswith("mcp__"):
71
+ name = name.split("__")[-1]
72
+ return name if len(name) <= limit else name[: limit - 1] + "…"
73
+
74
+
75
+ # (high, medium, low) fills per perspective, light then dark theme.
76
+ _DEFAULT_COLORS = (("#dc2626", "#d97706", "#16a34a"), ("#f87171", "#f59e0b", "#22c55e"))
77
+ _COLORS = {
78
+ "compliance": (("#dc2626", "#d97706", "#2563eb"), ("#f87171", "#f59e0b", "#60a5fa")), # LOGGED: neutral blue
79
+ "monitoring": (("#dc2626", "#2563eb", "#a8a29e"), ("#f87171", "#60a5fa", "#78716c")), # IGNORE: grey
80
+ }
81
+
82
+
83
+ def script_json(value) -> str:
84
+ """JSON safe to embed in an inline ``<script>``: ``<``, ``>`` and ``&`` become ``\\u003c`` etc.
85
+
86
+ That keeps names such as ``</script>`` or ``<!--`` in tool or agent names from
87
+ ending the script block or switching the HTML parser's state.
88
+ """
89
+ return (json.dumps(value).replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026")
90
+ .replace("\u2028", "\\u2028").replace("\u2029", "\\u2029"))
91
+
92
+
93
+ def render_html(graph: AgentGraph, result: ScanResult | None = None, title: str | None = None,
94
+ perspective: str | None = None, anomalies: AnomalyReport | None = None,
95
+ violations: list | None = None, session_findings: list | None = None) -> str:
96
+ """Return the HTML page for ``graph``.
97
+
98
+ ``perspective`` picks the role labels and colours (default: the result's
99
+ own perspective). ``anomalies`` and ``violations`` add the baseline
100
+ anomalies and policy violations of a single session; ``session_findings``
101
+ — ``[(session_id, AnomalyReport | None, violations | None), ...]`` — adds a
102
+ per-session summary when several sessions were merged.
103
+ """
104
+ result = result or AgentFIScanner(graph).scan()
105
+ perspective = (perspective or result.perspective).lower()
106
+ names = Perspective.labels(perspective)
107
+ labels = result.labels(perspective)
108
+ light, dark = _COLORS.get(perspective, _DEFAULT_COLORS)
109
+ blasts = BlastRadiusAnalyzer(graph).analyze_all()
110
+ pos = layout(graph)
111
+ bridge_keys = {e.key for e in result.bridges}
112
+ max_w = max((e.weight for e in graph.edges), default=1)
113
+ max_calls = max((n.call_count for n in graph.nodes.values()), default=1) or 1
114
+ title = title or f"agent-certify · {graph.session_id or 'agent graph'}"
115
+
116
+ edge_svg = []
117
+ for e in graph.edges:
118
+ (x1, y1), (x2, y2) = pos[e.source], pos[e.target]
119
+ width = 1.2 + 5.0 * math.log1p(e.weight) / math.log1p(max_w)
120
+ cls = "edge bridge" if e.key in bridge_keys else "edge"
121
+ tip = f"{e.source} → {e.target}\n{e.weight} call(s), {e.errors} error(s), tri(e)={e.tri_count}"
122
+ edge_svg.append(
123
+ f'<line class="{cls}" data-a="{html.escape(e.source)}" data-b="{html.escape(e.target)}" '
124
+ f'x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" stroke-width="{width:.2f}">'
125
+ f'<title>{html.escape(tip)}</title></line>')
126
+
127
+ node_svg = []
128
+ for nid, n in sorted(graph.nodes.items()):
129
+ x, y = pos[nid]
130
+ role = f"lvl-{result.node_levels.get(nid, LOW)}"
131
+ r = 9 + 13 * math.sqrt(n.call_count / max_calls) if n.kind == "tool" else (8 if n.kind == "file" else 20)
132
+ if n.kind == "orchestrator":
133
+ r = 26
134
+ if n.kind in ("orchestrator", "agent"):
135
+ shape = (f'<rect x="{x - r:.1f}" y="{y - r * 0.75:.1f}" width="{2 * r:.1f}" '
136
+ f'height="{1.5 * r:.1f}" rx="7"/>')
137
+ elif n.kind == "human":
138
+ shape = f'<polygon points="{x:.1f},{y - r:.1f} {x + r:.1f},{y:.1f} {x:.1f},{y + r:.1f} {x - r:.1f},{y:.1f}"/>'
139
+ else:
140
+ shape = f'<circle cx="{x:.1f}" cy="{y:.1f}" r="{r:.1f}"/>'
141
+ if n.kind == "file": # code written (Cursor Agent Trace): small square
142
+ shape = f'<rect x="{x - r:.1f}" y="{y - r:.1f}" width="{2 * r:.1f}" height="{2 * r:.1f}" rx="2"/>'
143
+ label = _short(n.name if n.kind != "agent" else n.name.split(":", 1)[-1].strip() or n.name)
144
+ node_svg.append(
145
+ f'<g class="node {role} {n.kind}" data-id="{html.escape(nid)}" tabindex="0">{shape}'
146
+ f'<text x="{x:.1f}" y="{y + r + 14:.1f}">{html.escape(label)}</text></g>')
147
+
148
+ info = {}
149
+ for nid, b in blasts.items():
150
+ n = graph.nodes[nid]
151
+ info[nid] = {
152
+ "name": n.name, "kind": n.kind, "role": labels.get(nid),
153
+ "calls": n.call_count, "errors": n.error_count,
154
+ "direct": b.direct_impact, "reach": b.total_reachable, "tools": b.accessible_tools,
155
+ "fi_after": round(b.remaining_fi, 4), "fragmented": b.system_fragmented,
156
+ "groups": len(b.components_after), "advice": b.isolation_recommendation,
157
+ }
158
+
159
+ d = graph.duration_seconds
160
+ duration = "–" if not d else (f"{d / 3600:.1f} h" if d >= 3600 else f"{d / 60:.0f} min")
161
+ stats = [
162
+ ("Fragility Index", f"{result.fi:.4f}"),
163
+ ("Nodes", str(result.node_count)),
164
+ ("Links", str(result.edge_count)),
165
+ ("Bridges", str(len(result.bridges))),
166
+ (names[HIGH].title(), str(len(result.critical_nodes))),
167
+ ("Tool calls", str(graph.total_tool_calls)),
168
+ ("Duration", duration),
169
+ ]
170
+ if anomalies is not None:
171
+ stats.append(("Anomalies", str(len(anomalies.anomalies))))
172
+ stat_html = "".join(f'<div class="stat"><span>{html.escape(k)}</span><b>{html.escape(v)}</b></div>'
173
+ for k, v in stats)
174
+ data = script_json(info)
175
+
176
+ def item(severity: str, message: str, detail: str = "") -> str:
177
+ return (f'<li class="sev-{html.escape(severity)}"><b>{html.escape(severity.upper())}</b> '
178
+ f'{html.escape(message)}' + (f'<div class="sub">{html.escape(detail)}</div>' if detail else "")
179
+ + "</li>")
180
+
181
+ panels = []
182
+ if anomalies is not None:
183
+ items = "".join(item(a.severity, a.message, a.detail) for a in anomalies.anomalies)
184
+ panels.append(f'<section class="anomalies"><h2>{html.escape(anomalies.summary)}</h2><ul>{items}</ul></section>')
185
+ if violations is not None:
186
+ items = "".join(item(v.severity, v.message, f"Rule: {v.rule.describe()}") for v in violations)
187
+ heading = f"{len(violations)} policy violation(s)" if violations else "No policy violations"
188
+ panels.append(f'<section class="anomalies"><h2>{html.escape(heading)}</h2><ul>{items}</ul></section>')
189
+ if session_findings:
190
+ rows = []
191
+ for sid, rep, viol in session_findings:
192
+ parts = []
193
+ if rep is not None:
194
+ parts.append(rep.summary)
195
+ if viol is not None:
196
+ parts.append(f"{len(viol)} policy violation(s)" + (": " + "; ".join(v.message for v in viol[:3])
197
+ if viol else ""))
198
+ worst = ("critical" if (rep and rep.has_critical) or any(v.severity == "critical" for v in viol or [])
199
+ else "warning" if (rep and rep.anomalies) or viol else "info")
200
+ rows.append(item(worst, sid, " · ".join(parts)))
201
+ panels.append('<section class="anomalies"><h2>Per session (anomalies and policy are evaluated per '
202
+ f'session)</h2><ul>{"".join(rows)}</ul></section>')
203
+ anomaly_html = "\n".join(panels)
204
+
205
+ legend = "".join(f'<span><i class="sw" style="background:var(--{lvl})"></i>{html.escape(names[lvl])}</span>'
206
+ for lvl in LEVELS)
207
+ return _TEMPLATE.format(
208
+ title=html.escape(title), stats=stat_html, w=W, h=H,
209
+ edges="\n".join(edge_svg), nodes="\n".join(node_svg), data=data,
210
+ project=html.escape(graph.project or ""), legend=legend, anomalies=anomaly_html,
211
+ perspective=html.escape(perspective),
212
+ hl=light[0], ml=light[1], ll=light[2], hd=dark[0], md=dark[1], ld=dark[2],
213
+ )
214
+
215
+
216
+ def save_html(graph: AgentGraph, path, result: ScanResult | None = None, title: str | None = None,
217
+ perspective: str | None = None, anomalies: AnomalyReport | None = None,
218
+ violations: list | None = None) -> Path:
219
+ p = Path(path)
220
+ p.write_text(render_html(graph, result, title, perspective, anomalies, violations), encoding="utf-8")
221
+ return p
222
+
223
+
224
+ _TEMPLATE = """<!doctype html>
225
+ <html lang="en"><head><meta charset="utf-8">
226
+ <meta name="viewport" content="width=device-width, initial-scale=1">
227
+ <title>{title}</title>
228
+ <style>
229
+ :root {{ --bg:#fafaf9; --fg:#1c1917; --muted:#78716c; --panel:#ffffff; --line:#a8a29e; --border:#e7e5e4;
230
+ --high:{hl}; --medium:{ml}; --low:{ll}; --bridge:#dc2626; --warn:#d97706; --info:#2563eb; }}
231
+ @media (prefers-color-scheme: dark) {{ :root {{ --bg:#1c1917; --fg:#f5f5f4; --muted:#a8a29e; --panel:#292524;
232
+ --line:#78716c; --border:#44403c; --high:{hd}; --medium:{md}; --low:{ld}; --bridge:#f87171;
233
+ --warn:#f59e0b; --info:#60a5fa; }} }}
234
+ * {{ box-sizing:border-box; }}
235
+ body {{ margin:0; font:14px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif; background:var(--bg); color:var(--fg); }}
236
+ header {{ padding:16px 20px 8px; }}
237
+ h1 {{ font-size:18px; margin:0 0 2px; }} .sub {{ color:var(--muted); font-size:13px; }}
238
+ .stats {{ display:flex; flex-wrap:wrap; gap:8px; padding:8px 20px; }}
239
+ .stat {{ background:var(--panel); border:1px solid var(--border); border-radius:8px; padding:6px 12px; }}
240
+ .stat span {{ display:block; font-size:11px; color:var(--muted); text-transform:uppercase; letter-spacing:.04em; }}
241
+ .stat b {{ font-size:16px; font-variant-numeric:tabular-nums; }}
242
+ main {{ display:flex; flex-wrap:wrap; gap:12px; padding:8px 20px 20px; }}
243
+ .canvas {{ flex:1 1 600px; min-width:0; background:var(--panel); border:1px solid var(--border); border-radius:10px; }}
244
+ svg {{ width:100%; height:auto; display:block; }}
245
+ aside {{ flex:0 1 300px; min-width:240px; background:var(--panel); border:1px solid var(--border); border-radius:10px; padding:12px 14px; }}
246
+ aside h2 {{ font-size:15px; margin:0 0 6px; word-break:break-all; }}
247
+ aside dl {{ margin:0; }} aside dt {{ color:var(--muted); font-size:12px; margin-top:8px; }} aside dd {{ margin:0; word-break:break-all; }}
248
+ .edge {{ stroke:var(--line); stroke-opacity:.7; }}
249
+ .edge.bridge {{ stroke:var(--bridge); stroke-dasharray:6 4; stroke-opacity:.85; }}
250
+ .node rect, .node circle, .node polygon {{ stroke:var(--panel); stroke-width:2; cursor:pointer; }}
251
+ .node.lvl-low > :first-child {{ fill:var(--low); }} .node.lvl-medium > :first-child {{ fill:var(--medium); }}
252
+ .node.lvl-high > :first-child {{ fill:var(--high); }}
253
+ .anomalies {{ margin:4px 20px 8px; background:var(--panel); border:1px solid var(--border); border-radius:10px; padding:10px 14px; }}
254
+ .anomalies h2 {{ font-size:14px; margin:0 0 6px; }} .anomalies ul {{ margin:0; padding-left:18px; }}
255
+ .anomalies li {{ margin:4px 0; }} .anomalies li b {{ font-size:11px; letter-spacing:.04em; }}
256
+ .sev-critical b {{ color:var(--high); }} .sev-warning b {{ color:var(--warn); }} .sev-info b {{ color:var(--info); }}
257
+ .node text {{ fill:var(--fg); font-size:11px; text-anchor:middle; pointer-events:none; }}
258
+ .dim {{ opacity:.12; }} .focus > :first-child {{ stroke:var(--fg); stroke-width:3; }}
259
+ .legend {{ display:flex; flex-wrap:wrap; gap:14px; font-size:12px; color:var(--muted); padding:0 20px 16px; }}
260
+ .sw {{ display:inline-block; width:10px; height:10px; border-radius:50%; margin-right:5px; vertical-align:-1px; }}
261
+ </style></head><body>
262
+ <header><h1>{title}</h1><div class="sub">{project} · structural scan by agent-certify · {perspective} perspective</div></header>
263
+ <div class="stats">{stats}</div>
264
+ {anomalies}
265
+ <main>
266
+ <div class="canvas"><svg viewBox="0 0 {w} {h}" role="img" aria-label="Agent graph">
267
+ <g id="edges">{edges}</g><g id="nodes">{nodes}</g></svg></div>
268
+ <aside id="panel"><h2>Blast radius</h2><p class="sub">Hover or focus a node to see what compromising it would reach.</p></aside>
269
+ </main>
270
+ <div class="legend">
271
+ {legend}
272
+ <span>▭ agent · ● tool (size = calls) · ◆ human · ■ file</span>
273
+ <span style="color:var(--bridge)">- - - bridge (no backup path)</span>
274
+ </div>
275
+ <script>
276
+ const INFO = {data};
277
+ const panel = document.getElementById('panel');
278
+ const nodes = [...document.querySelectorAll('.node')];
279
+ const edges = [...document.querySelectorAll('.edge')];
280
+ const esc = s => String(s).replace(/[&<>"]/g, c => ({{'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}})[c]);
281
+ const list = a => a.length ? a.map(esc).join(', ') : '–';
282
+ function show(id) {{
283
+ const d = INFO[id]; if (!d) return;
284
+ const hit = new Set([id, ...d.reach]);
285
+ nodes.forEach(n => {{ n.classList.toggle('dim', !hit.has(n.dataset.id)); n.classList.toggle('focus', n.dataset.id === id); }});
286
+ edges.forEach(e => e.classList.toggle('dim', !(hit.has(e.dataset.a) && hit.has(e.dataset.b))));
287
+ panel.innerHTML = `<h2>${{esc(id)}}</h2><div class="sub">${{esc(d.kind)}} · ${{esc(d.role)}} · ${{d.calls}} call(s), ${{d.errors}} error(s)</div>
288
+ <dl><dt>Direct impact (${{d.direct.length}})</dt><dd>${{list(d.direct)}}</dd>
289
+ <dt>Reachable within 3 hops</dt><dd>${{d.reach.length}} node(s)</dd>
290
+ <dt>Tools it can invoke (${{d.tools.length}})</dt><dd>${{list(d.tools)}}</dd>
291
+ <dt>FI after isolating it</dt><dd>${{d.fi_after}}</dd>
292
+ <dt>System after isolation</dt><dd>${{d.fragmented ? 'fragmented into ' + d.groups + ' groups' : 'stays connected'}}</dd>
293
+ <dt>Recommendation</dt><dd>${{esc(d.advice)}}</dd></dl>`;
294
+ }}
295
+ function clear() {{ nodes.forEach(n => n.classList.remove('dim','focus')); edges.forEach(e => e.classList.remove('dim')); }}
296
+ nodes.forEach(n => {{ n.addEventListener('mouseenter', () => show(n.dataset.id)); n.addEventListener('focus', () => show(n.dataset.id)); }});
297
+ document.querySelector('svg').addEventListener('mouseleave', clear);
298
+ </script></body></html>
299
+ """
@@ -0,0 +1,242 @@
1
+ # agent-certify — Structural verification of multiagent systems
2
+ # Copyright 2026 Cognitive Engineering (Switzerland)
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """Live monitoring of an active Claude Code session.
5
+
6
+ The transcript is append-only. The watcher polls its size (plus the sizes of
7
+ its sub-agent transcripts) and, when anything grew, re-parses the session,
8
+ rescans it and reports:
9
+
10
+ * a status line (nodes, links, FI and its change, tool calls)
11
+ * nodes that appeared since the previous scan
12
+ * anomalies against a baseline (critical and warning)
13
+ * policy violations
14
+
15
+ Each anomaly or violation is reported once, when it first appears (again only
16
+ if its severity changes), not on every scan. A file that does not exist yet is
17
+ waited for; a half-written last line is skipped until it is complete.
18
+ No file-system notification library: plain size polling.
19
+
20
+ Any format :class:`~agent_certify.parser.AutoParser` reads can be watched: a
21
+ Claude Code transcript, a Cursor ``traces.jsonl`` or an MCP server log.
22
+
23
+ Known limitation (v0.5): every change triggers a full re-parse and rescan of
24
+ the session, so the cost of each scan grows with the session's length. The
25
+ scan itself is near-linear since v0.5, which keeps this practical for long
26
+ sessions; incremental parsing from the last file offset is planned.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import logging
31
+ import threading
32
+ import time
33
+ from collections.abc import Callable
34
+ from datetime import datetime, timezone
35
+ from pathlib import Path
36
+
37
+ from agent_certify.anomaly import AnomalyDetector
38
+ from agent_certify.baseline import Baseline
39
+ from agent_certify.graph import AgentGraph
40
+ from agent_certify.parser.auto import AutoParser
41
+ from agent_certify.policy import Policy, PolicyViolation
42
+ from agent_certify.scanner import HIGH, AgentFIScanner, Perspective
43
+
44
+
45
+ def latest_session(directory: str | Path) -> Path | None:
46
+ """The most recently modified session transcript in a project folder."""
47
+ files = [f for f in Path(directory).glob("*.jsonl") if f.is_file()]
48
+ return max(files, key=lambda f: f.stat().st_mtime) if files else None
49
+
50
+
51
+ class SessionWatcher:
52
+ """Watch an active session JSONL file and report structural changes.
53
+
54
+ Usage::
55
+
56
+ SessionWatcher(path, baseline=b, policy=p, interval=30).watch() # blocks until Ctrl+C
57
+
58
+ In a thread, call :meth:`stop` to end it; ``max_scans`` ends it after that
59
+ many scans, ``max_seconds`` after that much time (scans only happen when the
60
+ session grows, so a quiet session needs the latter). ``history`` keeps one
61
+ summary dict per scan. ``on_scan(graph, result, report, violations, started_at)`` is
62
+ called after every scan with all of that scan's anomalies (an
63
+ :class:`AnomalyReport`, or None without a baseline) and policy violations
64
+ (a list, or None without a policy), not only the newly reported ones.
65
+ """
66
+
67
+ def __init__(
68
+ self,
69
+ session_path: str,
70
+ baseline: Baseline | None = None,
71
+ policy: Policy | None = None,
72
+ interval: float = 30.0,
73
+ on_anomaly: Callable | None = None,
74
+ on_policy_violation: Callable | None = None,
75
+ perspective: str = "engineering",
76
+ max_scans: int | None = None,
77
+ max_seconds: float | None = None,
78
+ out: Callable[[str], None] = print,
79
+ on_scan: Callable | None = None,
80
+ ):
81
+ if interval <= 0:
82
+ raise ValueError("interval must be positive")
83
+ Perspective.labels(perspective)
84
+ self.session_path = Path(session_path)
85
+ self.baseline = baseline
86
+ self.policy = policy
87
+ self.interval = interval
88
+ self.on_anomaly = on_anomaly or self._default_print
89
+ self.on_policy_violation = on_policy_violation or self._print_violation
90
+ self.perspective = perspective
91
+ self.max_scans = max_scans
92
+ self.max_seconds = max_seconds
93
+ self.out = out
94
+ self.on_scan = on_scan
95
+ self.history: list[dict] = []
96
+ self._stop = threading.Event()
97
+ self._last_size: int | None = None
98
+ self._last_graph: AgentGraph | None = None
99
+ self._last_fi: float | None = None
100
+ self._last_result = None
101
+ self._reported: dict[tuple, str] = {}
102
+ self._waiting_said = False
103
+
104
+ # ------------------------------------------------------------------ api
105
+ def watch(self) -> None:
106
+ """Block and watch until Ctrl+C, :meth:`stop`, or ``max_scans``."""
107
+ self.out(f"Watching {self.session_path} (every {self.interval:g}s, Ctrl+C to stop)")
108
+ self.out("Baseline: " + (f"loaded ({self.baseline.learned_from} sessions)" if self.baseline else "none"))
109
+ self.out("Policy: " + (f"loaded ({len(self.policy.rules)} rules)" if self.policy else "none"))
110
+ self.out("─" * 60)
111
+ deadline = time.monotonic() + self.max_seconds if self.max_seconds is not None else None
112
+ try:
113
+ while not self._stop.is_set():
114
+ self.poll()
115
+ if self.max_scans is not None and len(self.history) >= self.max_scans:
116
+ break
117
+ if deadline is not None:
118
+ left = deadline - time.monotonic()
119
+ if left <= 0:
120
+ break
121
+ self._sleep(min(self.interval, left))
122
+ else:
123
+ self._sleep(self.interval)
124
+ except KeyboardInterrupt:
125
+ self.out("\nStopped watching.")
126
+ self._final_report()
127
+
128
+ def stop(self) -> None:
129
+ self._stop.set()
130
+
131
+ def _sleep(self, seconds: float) -> None:
132
+ # Short slices: Ctrl+C is not delivered during Event.wait() on Windows.
133
+ end = time.monotonic() + seconds
134
+ while not self._stop.is_set():
135
+ left = end - time.monotonic()
136
+ if left <= 0:
137
+ return
138
+ time.sleep(min(0.2, left))
139
+
140
+ def poll(self) -> bool:
141
+ """One check: scan if the session grew. Returns True when it scanned."""
142
+ size = self._size()
143
+ if size is None:
144
+ if not self._waiting_said:
145
+ self.out(f"Waiting for {self.session_path} to appear...")
146
+ self._waiting_said = True
147
+ return False
148
+ if size == self._last_size:
149
+ return False
150
+ self._last_size = size
151
+ self._scan_and_report()
152
+ return True
153
+
154
+ # ------------------------------------------------------------ internals
155
+ def _size(self) -> int | None:
156
+ """Combined size of the transcript and its sub-agent transcripts (None if absent)."""
157
+ if not self.session_path.is_file():
158
+ return None
159
+ total = self.session_path.stat().st_size
160
+ sub = self.session_path.parent / self.session_path.stem / "subagents"
161
+ if sub.is_dir():
162
+ total += sum(f.stat().st_size for f in sub.glob("agent-*.jsonl"))
163
+ return total
164
+
165
+ def _scan_and_report(self) -> None:
166
+ """Parse, scan, detect anomalies, check policy."""
167
+ # A half-written last line is normal while the file grows: keep the parsers quiet about it.
168
+ loggers = [logging.getLogger(f"agent_certify.parser.{m}") for m in ("claude_code", "cursor_trace", "mcp_logs")]
169
+ levels = [lg.level for lg in loggers]
170
+ for lg in loggers:
171
+ lg.setLevel(logging.ERROR)
172
+ started = datetime.now(timezone.utc)
173
+ try:
174
+ graph = AutoParser().parse(str(self.session_path))
175
+ finally:
176
+ for lg, level in zip(loggers, levels):
177
+ lg.setLevel(level)
178
+ result = AgentFIScanner(graph, perspective=self.perspective).scan()
179
+
180
+ fi_str = f"FI: {result.fi:.4f}"
181
+ if self._last_fi is not None and abs(result.fi - self._last_fi) > 1e-12:
182
+ fi_str += f" (Δ {result.fi - self._last_fi:+.4f})"
183
+ stamp = time.strftime("%H:%M:%S")
184
+ self.out(f"[{stamp}] Nodes: {len(graph.nodes):<3} Links: {result.edge_count:<3} {fi_str} "
185
+ f"Calls: {graph.total_tool_calls}")
186
+
187
+ new_nodes = sorted(set(graph.nodes) - set(self._last_graph.nodes)) if self._last_graph else []
188
+ for nid in new_nodes:
189
+ role = graph.role(nid)
190
+ self.out(f" ⚡ New node appeared: {nid}" + (f" ({role})" if role != nid else ""))
191
+
192
+ anomalies, report, all_violations = [], None, None
193
+ if self.baseline:
194
+ report = AnomalyDetector(self.baseline).detect(graph, result)
195
+ for a in report.anomalies:
196
+ if a.severity in ("critical", "warning") and self._is_new(("anomaly", a.category, self._ident(a)),
197
+ a.severity):
198
+ anomalies.append(a)
199
+ self.on_anomaly(a)
200
+ violations = []
201
+ if self.policy:
202
+ all_violations = self.policy.check(graph)
203
+ for v in all_violations:
204
+ if self._is_new(("policy", v.rule.kind, v.rule.target, v.message), v.severity):
205
+ violations.append(v)
206
+ self.on_policy_violation(v)
207
+
208
+ self.history.append({"time": stamp, "nodes": len(graph.nodes), "links": result.edge_count,
209
+ "fi": result.fi, "calls": graph.total_tool_calls, "new_nodes": new_nodes,
210
+ "anomalies": anomalies, "violations": violations})
211
+ self._last_graph, self._last_fi, self._last_result = graph, result.fi, result
212
+ if self.on_scan:
213
+ self.on_scan(graph, result, report, all_violations, started)
214
+
215
+ @staticmethod
216
+ def _ident(a) -> str:
217
+ # Categorical anomalies are distinct per value; numeric ones (FI, error rate...) are one stream.
218
+ return str(a.value) if a.category in ("new_tool", "new_link") else ""
219
+
220
+ def _is_new(self, key: tuple, severity: str) -> bool:
221
+ if self._reported.get(key) == severity:
222
+ return False
223
+ self._reported[key] = severity
224
+ return True
225
+
226
+ def _final_report(self) -> None:
227
+ """Print summary when watch stops."""
228
+ if self._last_graph is None:
229
+ self.out("No scans completed.")
230
+ return
231
+ r = self._last_result
232
+ self.out(f"Final state: {len(self._last_graph.nodes)} nodes, {r.edge_count} links, FI: {self._last_fi:.4f} "
233
+ f"({len(self.history)} scan(s))")
234
+ top = [n for n, lvl in r.node_levels.items() if lvl == HIGH]
235
+ if top:
236
+ self.out(f" {Perspective.labels(self.perspective)[HIGH]}: {', '.join(sorted(top))}")
237
+
238
+ def _default_print(self, item) -> None:
239
+ self.out(f" [{item.severity.upper()}] {item.message}")
240
+
241
+ def _print_violation(self, v: PolicyViolation) -> None:
242
+ self.out(f" [{v.severity.upper()}] POLICY VIOLATION: {v.message}")