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.
@@ -0,0 +1,214 @@
1
+ # agent-certify — Structural verification of multiagent systems
2
+ # Copyright 2026 Cognitive Engineering (Switzerland)
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """Policy engine: explicit organisational rules for an agent system.
5
+
6
+ Anomalies say "this is unusual". A policy says "this is not allowed" (or "this
7
+ must be there"), whatever the statistics. A session can have both.
8
+
9
+ Rule kinds:
10
+
11
+ ================== ============================== =================================
12
+ kind target violated when
13
+ ================== ============================== =================================
14
+ ``forbidden_tool`` tool pattern a matching tool is used
15
+ ``forbidden_link`` ``"source-pattern → target"`` a matching link exists
16
+ ``max_sub_agents`` integer more sub-agents than that
17
+ ``required_tool`` tool pattern no matching tool is used
18
+ ================== ============================== =================================
19
+
20
+ Patterns are shell-style globs (``*``, ``?``), case-insensitive, matched
21
+ against a node's id (``tool:Bash``), its type (``agent:Explore``) and its name
22
+ (``Bash``). So ``bash``, ``tool:Bash`` and ``B*`` all match Bash, and
23
+ ``agent:*`` matches every sub-agent. Links accept ``→`` or ``->``.
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import os
29
+ from dataclasses import asdict, dataclass
30
+ from datetime import datetime, timezone
31
+ from fnmatch import fnmatchcase
32
+ from pathlib import Path
33
+
34
+ from agent_certify.baseline import Baseline
35
+ from agent_certify.graph import AgentGraph
36
+ from agent_certify.paths import ensure_state_dir
37
+
38
+ DEFAULT_POLICY_PATH = Path(".agent-certify") / "policy.json"
39
+ KINDS = ("forbidden_tool", "forbidden_link", "max_sub_agents", "required_tool")
40
+ SEVERITIES = ("critical", "warning")
41
+
42
+
43
+ def _split_link(target: str) -> tuple[str, str]:
44
+ for arrow in ("→", "->"):
45
+ if arrow in target:
46
+ source, dest = target.split(arrow, 1)
47
+ return source.strip(), dest.strip()
48
+ raise ValueError(f"link target {target!r} needs 'source → target' (or 'source -> target')")
49
+
50
+
51
+ def matches(pattern: str, graph: AgentGraph, node_id: str) -> bool:
52
+ """True when ``pattern`` matches the node's id, type or name."""
53
+ p = pattern.lower()
54
+ node = graph.nodes[node_id]
55
+ return any(fnmatchcase(c.lower(), p) for c in (node_id, graph.role(node_id), node.name))
56
+
57
+
58
+ @dataclass
59
+ class PolicyRule:
60
+ """A single policy rule."""
61
+ kind: str # "forbidden_tool", "forbidden_link", "max_sub_agents", "required_tool"
62
+ target: str # tool pattern, link "source → target", or number
63
+ severity: str # "critical", "warning"
64
+ message: str # human description
65
+
66
+ def __post_init__(self):
67
+ if self.kind not in KINDS:
68
+ raise ValueError(f"unknown rule kind {self.kind!r}; expected one of {', '.join(KINDS)}")
69
+ if self.severity not in SEVERITIES:
70
+ raise ValueError(f"rule severity must be one of {', '.join(SEVERITIES)}, not {self.severity!r}")
71
+ if self.kind == "forbidden_link":
72
+ _split_link(self.target)
73
+ if self.kind == "max_sub_agents":
74
+ int(self.target)
75
+
76
+ def describe(self) -> str:
77
+ label = {"forbidden_tool": "FORBIDDEN", "forbidden_link": "FORBIDDEN LINK",
78
+ "max_sub_agents": "MAX SUB-AGENTS", "required_tool": "REQUIRED"}[self.kind]
79
+ return f"{label}: {self.target}"
80
+
81
+
82
+ @dataclass
83
+ class PolicyViolation:
84
+ """A detected policy violation."""
85
+ rule: PolicyRule
86
+ observed: str # what was actually seen
87
+ severity: str
88
+ message: str
89
+
90
+ def to_dict(self) -> dict:
91
+ return asdict(self)
92
+
93
+
94
+ @dataclass
95
+ class Policy:
96
+ """A set of rules for an agent system."""
97
+ rules: list[PolicyRule]
98
+ generated_from: str | None = None # baseline description if auto-generated
99
+ created_at: str | None = None
100
+
101
+ def check(self, graph: AgentGraph) -> list[PolicyViolation]:
102
+ """Check all rules against a graph. Return violations."""
103
+ violations = []
104
+ tools = [nid for nid, n in graph.nodes.items() if n.kind == "tool"]
105
+ for rule in self.rules:
106
+ if rule.kind == "forbidden_tool":
107
+ for nid in tools:
108
+ if matches(rule.target, graph, nid):
109
+ name = graph.nodes[nid].name
110
+ violations.append(PolicyViolation(
111
+ rule=rule,
112
+ observed=f"Tool {name} was used ({graph.nodes[nid].call_count} calls)",
113
+ severity=rule.severity,
114
+ message=f"FORBIDDEN tool used: {name}"))
115
+ elif rule.kind == "forbidden_link":
116
+ source, target = _split_link(rule.target)
117
+ for edge in graph.edges:
118
+ if matches(source, graph, edge.source) and matches(target, graph, edge.target):
119
+ violations.append(PolicyViolation(
120
+ rule=rule,
121
+ observed=f"Link {edge.source} → {edge.target} exists ({edge.weight} calls)",
122
+ severity=rule.severity,
123
+ message=f"FORBIDDEN link: {edge.source} → {edge.target}"))
124
+ elif rule.kind == "max_sub_agents":
125
+ agent_count = sum(1 for n in graph.nodes.values() if n.kind == "agent")
126
+ max_allowed = int(rule.target)
127
+ if agent_count > max_allowed:
128
+ violations.append(PolicyViolation(
129
+ rule=rule,
130
+ observed=f"{agent_count} sub-agents (max: {max_allowed})",
131
+ severity=rule.severity,
132
+ message=f"Too many sub-agents: {agent_count} > {max_allowed}"))
133
+ elif rule.kind == "required_tool" and not any(matches(rule.target, graph, nid) for nid in tools):
134
+ violations.append(PolicyViolation(
135
+ rule=rule,
136
+ observed=f"Tool {rule.target} not found",
137
+ severity=rule.severity,
138
+ message=f"REQUIRED tool missing: {rule.target}"))
139
+ violations.sort(key=lambda v: SEVERITIES.index(v.severity))
140
+ return violations
141
+
142
+ def to_dict(self) -> dict:
143
+ return {"rules": [asdict(r) for r in self.rules], "generated_from": self.generated_from,
144
+ "created_at": self.created_at}
145
+
146
+ def save(self, path: str | os.PathLike | None = None) -> Path:
147
+ """Write the policy as human-editable JSON (default: .agent-certify/policy.json)."""
148
+ p = Path(path) if path is not None else DEFAULT_POLICY_PATH
149
+ ensure_state_dir(p)
150
+ p.write_text(json.dumps(self.to_dict(), indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
151
+ return p
152
+
153
+ @classmethod
154
+ def load(cls, path: str | os.PathLike) -> Policy:
155
+ """Read a policy file. Raises ``ValueError`` for anything that is not a valid policy.
156
+
157
+ Errors about individual rules name the rule's kind or severity (useful to
158
+ whoever edits the file); the MCP server replaces every load error with a
159
+ generic message.
160
+ """
161
+ try:
162
+ data = json.loads(Path(path).read_text(encoding="utf-8"), parse_constant=_reject_constant)
163
+ except (ValueError, UnicodeDecodeError, RecursionError):
164
+ raise ValueError("Invalid policy format (not JSON)") from None
165
+ if not isinstance(data, dict) or not isinstance(data.get("rules"), list):
166
+ raise ValueError("Invalid policy format (no 'rules' list)") # noqa: TRY004 — one error type for bad files
167
+ for key in ("generated_from", "created_at"):
168
+ if data.get(key) is not None and not isinstance(data[key], str):
169
+ raise ValueError("Invalid policy format")
170
+ rules = []
171
+ for r in data["rules"]:
172
+ if not (isinstance(r, dict) and set(r) == {"kind", "target", "severity", "message"}
173
+ and all(isinstance(v, str) for v in r.values())):
174
+ raise ValueError("Invalid policy format (each rule needs string kind, target, severity, message)")
175
+ rules.append(PolicyRule(**r))
176
+ return cls(rules=rules, generated_from=data.get("generated_from"), created_at=data.get("created_at"))
177
+
178
+
179
+ def _reject_constant(name: str):
180
+ raise ValueError("Invalid policy format")
181
+
182
+
183
+ class PolicyGenerator:
184
+ """Auto-generate a draft policy from a learned baseline.
185
+
186
+ The draft is deliberately conservative: a human edits it, adds FORBIDDEN
187
+ rules (``deploy_production``, ``agent:* → *database*``...), adjusts
188
+ thresholds and deletes rules they don't want. New tools and new links are
189
+ already flagged by anomaly detection, so the draft does not repeat them.
190
+ """
191
+
192
+ def suggest(self, baseline: Baseline) -> Policy:
193
+ """Generate conservative policy rules from baseline statistics.
194
+
195
+ - tools seen in every session -> REQUIRED (warning)
196
+ - sub-agents: more than baseline max + 1 -> warning, max + 3 -> critical
197
+ """
198
+ rules = []
199
+ for tool, freq in sorted(baseline.tool_frequency.items()):
200
+ if freq >= 1.0:
201
+ rules.append(PolicyRule(
202
+ kind="required_tool", target=tool, severity="warning",
203
+ message=f"{tool} is expected in every session (seen in {freq:.0%} of sessions)"))
204
+ rules.append(PolicyRule(
205
+ kind="max_sub_agents", target=str(baseline.max_sub_agents_seen + 1), severity="warning",
206
+ message=f"Baseline max was {baseline.max_sub_agents_seen}"))
207
+ rules.append(PolicyRule(
208
+ kind="max_sub_agents", target=str(baseline.max_sub_agents_seen + 3), severity="critical",
209
+ message=f"Far exceeds baseline max of {baseline.max_sub_agents_seen}"))
210
+ return Policy(
211
+ rules=rules,
212
+ generated_from=f"baseline ({baseline.learned_from} sessions)",
213
+ created_at=datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
214
+ )
@@ -0,0 +1,400 @@
1
+ # agent-certify — Structural verification of multiagent systems
2
+ # Copyright 2026 Cognitive Engineering (Switzerland)
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """Fragility Index (FI) of an agent graph.
5
+
6
+ FI is the fraction of communication links with **zero triangle support**: links
7
+ whose two endpoints share no common neighbour, so the link has no alternative
8
+ two-hop path. It is the same measure sal-torch computes on attention-head
9
+ graphs (``sal.fi.compute_fi``), applied here to agents and tools.
10
+
11
+ * FI = 0 → every link sits in at least one triangle (fully redundant).
12
+ * FI = 1 → no link sits in a triangle (a tree or star: fully fragile).
13
+
14
+ Direction is dropped first: two nodes are linked if either ever invoked the
15
+ other. Call counts do not enter FI; it is a property of the topology alone.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass, field, replace
20
+ from typing import ClassVar
21
+
22
+ import numpy as np
23
+
24
+ from agent_certify.graph import AgentEdge, AgentGraph
25
+
26
+ CRITICAL, BUFFER, IMMUNE = "CRITICAL", "BUFFER", "IMMUNE"
27
+ HIGH, MEDIUM, LOW = "high", "medium", "low"
28
+ LEVELS = (HIGH, MEDIUM, LOW)
29
+ DEFAULT_CRITICAL_THR = 0.10
30
+ DEFAULT_IMMUNE_THR = 0.02
31
+
32
+
33
+ class Perspective:
34
+ """Maps structural roles to domain-appropriate labels.
35
+
36
+ The scanner measures one structural level per node; a perspective only
37
+ names it. The levels:
38
+
39
+ * high: an articulation point (removing the node disconnects the
40
+ system), or removing it raises FI by >= 10% (relative)
41
+ * medium: removing it raises FI by 2-10%
42
+ * low: removing it raises FI by < 2%, or lowers it
43
+
44
+ ``classic`` is the v0.1 vocabulary and the Python API default; the CLI
45
+ defaults to ``engineering``.
46
+ """
47
+
48
+ CLASSIC: ClassVar[dict[str, str]] = {HIGH: CRITICAL, MEDIUM: BUFFER, LOW: IMMUNE}
49
+
50
+ ENGINEERING: ClassVar[dict[str, str]] = {
51
+ HIGH: "KEYSTONE", # the structure stands or falls with it
52
+ MEDIUM: "LOAD-BEARING", # carries redundancy others rely on
53
+ LOW: "PERIPHERAL", # minimal structural impact
54
+ }
55
+
56
+ RISK: ClassVar[dict[str, str]] = {
57
+ HIGH: "HIGH RISK",
58
+ MEDIUM: "MODERATE RISK",
59
+ LOW: "LOW RISK",
60
+ }
61
+
62
+ COMPLIANCE: ClassVar[dict[str, str]] = {
63
+ HIGH: "UNRESTRICTED", # failure or compromise propagates widely
64
+ MEDIUM: "BOUNDED", # contained impact
65
+ LOW: "LOGGED", # minimal impact, tracked
66
+ }
67
+
68
+ MONITORING: ClassVar[dict[str, str]] = {
69
+ HIGH: "WATCH", # monitor closely
70
+ MEDIUM: "TRACK", # routine monitoring
71
+ LOW: "IGNORE", # no action needed
72
+ }
73
+
74
+ DEFAULT = "classic"
75
+ NAMES = ("engineering", "risk", "compliance", "monitoring", "classic")
76
+
77
+ @classmethod
78
+ def labels(cls, name: str | None = None) -> dict[str, str]:
79
+ """The level -> label mapping for ``name`` (case-insensitive)."""
80
+ key = (name or cls.DEFAULT).lower()
81
+ if key not in cls.NAMES:
82
+ raise ValueError(f"unknown perspective {name!r}; choose from {', '.join(cls.NAMES)}")
83
+ return dict(getattr(cls, key.upper()))
84
+
85
+
86
+ def compute_fi(adjacency) -> float:
87
+ """Fragility Index: fraction of edges with zero triangle support.
88
+
89
+ An edge (i, j) is fragile when i and j share no common neighbour, i.e.
90
+ ``(A @ A)[i, j] == 0``. A graph with no edges has FI 0: it has no links
91
+ that could fail. (sal-torch reports 1.0 there; for an attention graph an
92
+ edgeless result means the measurement failed, for an agent graph it just
93
+ means one agent and no tools.)
94
+ """
95
+ A = (np.asarray(adjacency) != 0).astype(np.int64)
96
+ n = A.shape[0] if A.ndim == 2 else 0
97
+ if n < 2:
98
+ return 0.0
99
+ np.fill_diagonal(A, 0)
100
+ common = A @ A
101
+ triu = np.triu_indices(n, k=1)
102
+ edges = A[triu] > 0
103
+ total = int(edges.sum())
104
+ if total == 0:
105
+ return 0.0
106
+ return float(np.sum(common[triu][edges] == 0) / total)
107
+
108
+
109
+ class FIStructure:
110
+ """Triangle bookkeeping for one graph, built once in O(m · min degree).
111
+
112
+ Gives FI and, for any node x, the FI of the graph without x in
113
+ O(Σ_{u∈N(x)} min(deg u, deg x)) without copying anything. Removing x drops
114
+ its deg(x) edges; a surviving edge (u, v) loses a triangle only when both u
115
+ and v were neighbours of x, so it becomes fragile exactly when x was its
116
+ only common neighbour (tri = 1). Hence
117
+
118
+ FI(G − x) = (F − F_x + N_x) / (E − deg x)
119
+
120
+ with F the fragile edges, F_x those incident to x, N_x the edges among
121
+ N(x) whose only triangle was through x. This equals recomputing FI on
122
+ G − x from scratch (checked against that in the test suite).
123
+ """
124
+
125
+ def __init__(self, graph: AgentGraph):
126
+ self.adj = graph.adjacency()
127
+ self.tri: dict[tuple[str, str], int] = {}
128
+ for u, nbrs in self.adj.items():
129
+ for v in nbrs:
130
+ if u < v:
131
+ a, b = (nbrs, self.adj[v]) if len(nbrs) <= len(self.adj[v]) else (self.adj[v], nbrs)
132
+ self.tri[(u, v)] = sum(1 for w in a if w in b)
133
+ self.edge_count = len(self.tri)
134
+ self.fragile = sum(1 for t in self.tri.values() if t == 0)
135
+
136
+ @staticmethod
137
+ def _key(u: str, v: str) -> tuple[str, str]:
138
+ return (u, v) if u < v else (v, u)
139
+
140
+ @property
141
+ def fi(self) -> float:
142
+ return self.fragile / self.edge_count if self.edge_count else 0.0
143
+
144
+ def fi_without(self, x: str) -> float:
145
+ nbrs = self.adj.get(x, set())
146
+ remaining = self.edge_count - len(nbrs)
147
+ if remaining <= 0:
148
+ return 0.0
149
+ incident_fragile = sum(1 for v in nbrs if self.tri[self._key(x, v)] == 0)
150
+ newly_fragile = 0
151
+ for u in nbrs:
152
+ for v in (self.adj[u] if len(self.adj[u]) < len(nbrs) else nbrs):
153
+ if u < v and v in nbrs and v in self.adj[u] and self.tri[(u, v)] == 1:
154
+ newly_fragile += 1
155
+ return (self.fragile - incident_fragile + newly_fragile) / remaining
156
+
157
+
158
+ def triangle_counts(graph: AgentGraph) -> dict[frozenset, int]:
159
+ """tri(e) for every undirected edge: the number of triangles containing it."""
160
+ return {frozenset(k): t for k, t in FIStructure(graph).tri.items()}
161
+
162
+
163
+ def find_bridges(graph: AgentGraph) -> set[frozenset]:
164
+ """Undirected edges whose removal disconnects their component (iterative Tarjan)."""
165
+ adj: dict[str, list[str]] = {nid: [] for nid in graph.nodes}
166
+ for a, b in graph.undirected_edges():
167
+ adj[a].append(b)
168
+ adj[b].append(a)
169
+ disc: dict[str, int] = {}
170
+ low: dict[str, int] = {}
171
+ bridges: set[frozenset] = set()
172
+ t = 0
173
+ for root in sorted(adj):
174
+ if root in disc:
175
+ continue
176
+ disc[root] = low[root] = t
177
+ t += 1
178
+ stack = [(root, None, iter(adj[root]))]
179
+ while stack:
180
+ v, parent, it = stack[-1]
181
+ advanced = False
182
+ for w in it:
183
+ if w == parent:
184
+ continue
185
+ if w in disc:
186
+ low[v] = min(low[v], disc[w])
187
+ else:
188
+ disc[w] = low[w] = t
189
+ t += 1
190
+ stack.append((w, v, iter(adj[w])))
191
+ advanced = True
192
+ break
193
+ if not advanced:
194
+ stack.pop()
195
+ if parent is not None:
196
+ low[parent] = min(low[parent], low[v])
197
+ if low[v] > disc[parent]:
198
+ bridges.add(frozenset((parent, v)))
199
+ return bridges
200
+
201
+
202
+ def articulation_points(graph: AgentGraph) -> set[str]:
203
+ """Nodes whose removal splits their component into more pieces (iterative Tarjan, O(n + m)).
204
+
205
+ A DFS root is an articulation point when it has two or more DFS children;
206
+ any other node u is one when some child v cannot reach above u
207
+ (``low[v] >= disc[u]``). Isolated nodes and leaves never are.
208
+ """
209
+ adj = {nid: sorted(nbrs) for nid, nbrs in graph.adjacency().items()}
210
+ disc: dict[str, int] = {}
211
+ low: dict[str, int] = {}
212
+ cut: set[str] = set()
213
+ t = 0
214
+ for root in sorted(adj):
215
+ if root in disc:
216
+ continue
217
+ disc[root] = low[root] = t
218
+ t += 1
219
+ root_children = 0
220
+ stack = [(root, None, iter(adj[root]))]
221
+ while stack:
222
+ v, parent, it = stack[-1]
223
+ advanced = False
224
+ for w in it:
225
+ if w == parent:
226
+ continue
227
+ if w in disc:
228
+ low[v] = min(low[v], disc[w])
229
+ else:
230
+ disc[w] = low[w] = t
231
+ t += 1
232
+ if v == root:
233
+ root_children += 1
234
+ stack.append((w, v, iter(adj[w])))
235
+ advanced = True
236
+ break
237
+ if not advanced:
238
+ stack.pop()
239
+ if parent is not None:
240
+ low[parent] = min(low[parent], low[v])
241
+ if parent != root and low[v] >= disc[parent]:
242
+ cut.add(parent)
243
+ if root_children >= 2:
244
+ cut.add(root)
245
+ return cut
246
+
247
+
248
+ @dataclass
249
+ class ScanResult:
250
+ """Structural profile of one agent graph."""
251
+ fi: float
252
+ bridges: list[AgentEdge]
253
+ node_classifications: dict[str, str]
254
+ node_count: int = 0
255
+ edge_count: int = 0 # undirected links
256
+ fragile_edges: list[tuple[str, str]] = field(default_factory=list) # tri(e) == 0
257
+ articulation_points: list[str] = field(default_factory=list)
258
+ fi_deltas: dict[str, float] = field(default_factory=dict) # FI change on removing each node
259
+ components: int = 1
260
+ node_levels: dict[str, str] = field(default_factory=dict) # high / medium / low
261
+ perspective: str = Perspective.DEFAULT
262
+ skipped_records: int = 0 # records the parser could not read: the graph may be incomplete
263
+
264
+ def __post_init__(self):
265
+ if not self.node_levels and self.node_classifications:
266
+ inverse = {v: k for k, v in Perspective.labels(self.perspective).items()}
267
+ self.node_levels = {n: inverse[c] for n, c in self.node_classifications.items()}
268
+
269
+ def labels(self, perspective: str | None = None) -> dict[str, str]:
270
+ """Node labels under ``perspective`` (default: this result's own)."""
271
+ names = Perspective.labels(perspective or self.perspective)
272
+ return {n: names[lvl] for n, lvl in self.node_levels.items()}
273
+
274
+ def with_perspective(self, perspective: str) -> ScanResult:
275
+ """The same result, labelled under another perspective."""
276
+ return replace(self, node_classifications=self.labels(perspective), perspective=perspective.lower())
277
+
278
+ @property
279
+ def critical_nodes(self) -> list[str]:
280
+ return sorted(n for n, lvl in self.node_levels.items() if lvl == HIGH)
281
+
282
+ @property
283
+ def buffer_nodes(self) -> list[str]:
284
+ return sorted(n for n, lvl in self.node_levels.items() if lvl == MEDIUM)
285
+
286
+ @property
287
+ def immune_nodes(self) -> list[str]:
288
+ return sorted(n for n, lvl in self.node_levels.items() if lvl == LOW)
289
+
290
+ def summary(self) -> str:
291
+ names = Perspective.labels(self.perspective)
292
+ return (f"FI={self.fi:.4f} | {self.node_count} nodes, {self.edge_count} links, "
293
+ f"{len(self.bridges)} bridges | {len(self.critical_nodes)} {names[HIGH].lower()}, "
294
+ f"{len(self.buffer_nodes)} {names[MEDIUM].lower()}, {len(self.immune_nodes)} {names[LOW].lower()}")
295
+
296
+ def to_dict(self) -> dict:
297
+ return {
298
+ "fi": self.fi,
299
+ "node_count": self.node_count,
300
+ "edge_count": self.edge_count,
301
+ "components": self.components,
302
+ "bridges": [[e.source, e.target] for e in self.bridges],
303
+ "fragile_edges": [list(e) for e in self.fragile_edges],
304
+ "articulation_points": self.articulation_points,
305
+ "perspective": self.perspective,
306
+ "node_classifications": self.node_classifications,
307
+ "node_levels": self.node_levels,
308
+ "fi_deltas": self.fi_deltas,
309
+ "skipped_records": self.skipped_records,
310
+ }
311
+
312
+
313
+ class AgentFIScanner:
314
+ """Compute FI, bridges and node roles for an :class:`AgentGraph`.
315
+
316
+ Usage::
317
+
318
+ result = AgentFIScanner(graph).scan()
319
+ result.fi # 0.0 .. 1.0
320
+ result.bridges # AgentEdge list
321
+ result.node_classifications # {"tool:Bash": "IMMUNE", "claude": "CRITICAL", ...}
322
+ result.labels("engineering") # {"tool:Bash": "PERIPHERAL", "claude": "KEYSTONE", ...}
323
+
324
+ A node is CRITICAL when removing it raises FI by at least ``critical_thr``
325
+ (relative), BUFFER between ``immune_thr`` and ``critical_thr``, IMMUNE
326
+ below (including nodes whose removal lowers FI). A node whose removal
327
+ disconnects the graph (an articulation point) is CRITICAL regardless of FI:
328
+ it is a single point of failure even when the fraction of fragile links
329
+ happens not to move. ``scan()`` also stores each edge's triangle count in
330
+ ``edge.tri_count``.
331
+
332
+ These are the ``classic`` labels of the high / medium / low levels;
333
+ ``perspective=`` picks another vocabulary (see :class:`Perspective`).
334
+ """
335
+
336
+ def __init__(self, graph: AgentGraph, critical_thr: float = DEFAULT_CRITICAL_THR,
337
+ immune_thr: float = DEFAULT_IMMUNE_THR, perspective: str = Perspective.DEFAULT):
338
+ if not 0 <= immune_thr <= critical_thr:
339
+ raise ValueError("need 0 <= immune_thr <= critical_thr")
340
+ Perspective.labels(perspective) # validate early
341
+ self.perspective = perspective.lower()
342
+ self.graph = graph
343
+ self.critical_thr = critical_thr
344
+ self.immune_thr = immune_thr
345
+
346
+ def scan(self) -> ScanResult:
347
+ """Compute FI, classify nodes, identify bridges."""
348
+ self.structure = FIStructure(self.graph)
349
+ tri = self.structure.tri
350
+ for e in self.graph.edges:
351
+ e.tri_count = tri.get(FIStructure._key(e.source, e.target), 0)
352
+ fi = self._compute_fi()
353
+ bridges = self._find_bridges()
354
+ levels, deltas, cut_nodes = self._classify_nodes(fi)
355
+ names = Perspective.labels(self.perspective)
356
+ return ScanResult(
357
+ fi=fi,
358
+ bridges=bridges,
359
+ node_classifications={n: names[lvl] for n, lvl in levels.items()},
360
+ node_levels=levels,
361
+ perspective=self.perspective,
362
+ node_count=len(self.graph.nodes),
363
+ edge_count=self.structure.edge_count,
364
+ fragile_edges=sorted(k for k, v in tri.items() if v == 0),
365
+ articulation_points=sorted(cut_nodes),
366
+ fi_deltas=deltas,
367
+ components=len(self.graph.connected_components()),
368
+ skipped_records=self.graph.skipped_records,
369
+ )
370
+
371
+ def _compute_fi(self) -> float:
372
+ """FI = proportion of edges with tri(e) = 0, on the undirected graph."""
373
+ return self.structure.fi
374
+
375
+ def _find_bridges(self) -> list[AgentEdge]:
376
+ """Edges whose removal disconnects the graph."""
377
+ keys = find_bridges(self.graph)
378
+ return [e for e in self.graph.edges if e.key in keys]
379
+
380
+ def _classify_nodes(self, base_fi: float) -> tuple[dict[str, str], dict[str, float], set[str]]:
381
+ """Assign each node a structural level: high, medium or low.
382
+
383
+ Only an *increase* counts: a node whose removal lowers FI was holding up
384
+ fragile links, not redundancy. (sal-torch's layer classifier uses the
385
+ absolute change.) The increase is relative to the base FI; when the base
386
+ FI is 0 the absolute increase is used instead.
387
+ """
388
+ cut_nodes = articulation_points(self.graph)
389
+ classes, deltas = {}, {}
390
+ for nid in sorted(self.graph.nodes):
391
+ new_fi = self.structure.fi_without(nid)
392
+ delta = (new_fi - base_fi) / base_fi if base_fi > 1e-12 else new_fi - base_fi
393
+ deltas[nid] = round(new_fi - base_fi, 6)
394
+ if nid in cut_nodes or delta >= self.critical_thr:
395
+ classes[nid] = HIGH
396
+ elif delta >= self.immune_thr:
397
+ classes[nid] = MEDIUM
398
+ else:
399
+ classes[nid] = LOW
400
+ return classes, deltas, cut_nodes