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/blast.py ADDED
@@ -0,0 +1,141 @@
1
+ # agent-certify — Structural verification of multiagent systems
2
+ # Copyright 2026 Cognitive Engineering (Switzerland)
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """Blast radius: what a compromised agent or tool can touch.
5
+
6
+ A compromised node can act on everything it invokes, and can influence
7
+ everything that invokes it (a poisoned tool result steers its caller). Spread
8
+ is therefore measured on the undirected graph. Tool *access* follows call
9
+ direction: the tools a node can reach by invoking, directly or through the
10
+ agents it spawns.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import asdict, dataclass, field
15
+
16
+ from agent_certify.graph import AgentGraph
17
+ from agent_certify.scanner import FIStructure
18
+
19
+
20
+ @dataclass
21
+ class BlastReport:
22
+ """Impact of compromising one node."""
23
+ compromised: str
24
+ direct_impact: list[str] # 1-hop neighbours
25
+ total_reachable: list[str] # within ``hops`` hops
26
+ accessible_tools: list[str] # tools reachable by invocation
27
+ remaining_fi: float # FI after isolating the node
28
+ system_fragmented: bool # isolating it splits the system
29
+ isolation_recommendation: str
30
+ hops: int = 3
31
+ baseline_fi: float = 0.0
32
+ components_after: list[list[str]] = field(default_factory=list)
33
+ reach_by_hop: dict[int, list[str]] = field(default_factory=dict)
34
+
35
+ def to_dict(self) -> dict:
36
+ return asdict(self)
37
+
38
+ def __str__(self) -> str:
39
+ lines = [
40
+ f"Blast radius: {self.compromised}",
41
+ f" Direct impact ({len(self.direct_impact)}): {', '.join(self.direct_impact) or '-'}",
42
+ f" Reachable within {self.hops} hops: {len(self.total_reachable)}",
43
+ f" Accessible tools ({len(self.accessible_tools)}): {', '.join(self.accessible_tools) or '-'}",
44
+ f" FI: {self.baseline_fi:.4f} -> {self.remaining_fi:.4f} after isolation",
45
+ (f" Fragmented after isolation: {self.system_fragmented} "
46
+ f"({len(self.components_after)} component(s))"),
47
+ f" Recommendation: {self.isolation_recommendation}",
48
+ ]
49
+ return "\n".join(lines)
50
+
51
+
52
+ class BlastRadiusAnalyzer:
53
+ """Usage::
54
+
55
+ report = BlastRadiusAnalyzer(graph).analyze("tool:Bash")
56
+ report.direct_impact # ["claude", "agent:a3e..."]
57
+ report.system_fragmented # False
58
+ """
59
+
60
+ def __init__(self, graph: AgentGraph, hops: int = 3):
61
+ if hops < 1:
62
+ raise ValueError("hops must be at least 1")
63
+ self.graph = graph
64
+ self.hops = hops
65
+ self._structure: FIStructure | None = None
66
+ self._components_before: int | None = None
67
+
68
+ def analyze(self, compromised_node: str) -> BlastReport:
69
+ """What happens if this node is compromised?"""
70
+ node = self.graph.resolve(compromised_node)
71
+ direct = sorted(self._get_neighbors(node))
72
+ by_hop = self._get_n_hop(node, n=self.hops)
73
+ reachable = sorted(set().union(*by_hop.values())) if by_hop else []
74
+ tools = self._reachable_tools(node)
75
+
76
+ # One triangle structure serves every node: FI without a node is a local
77
+ # computation, and components are counted without copying the graph.
78
+ if self._structure is None:
79
+ self._structure = FIStructure(self.graph)
80
+ self._components_before = len(self.graph.connected_components())
81
+ remaining_fi = self._structure.fi_without(node)
82
+ before = self._components_before
83
+ after = self.graph.connected_components(without=node)
84
+ # More pieces than the system had before (an already-split system is
85
+ # not "fragmented" by this node).
86
+ fragmented = len(after) > before
87
+
88
+ return BlastReport(
89
+ compromised=node,
90
+ direct_impact=direct,
91
+ total_reachable=reachable,
92
+ accessible_tools=tools,
93
+ remaining_fi=remaining_fi,
94
+ system_fragmented=fragmented,
95
+ isolation_recommendation=self._recommend(node, fragmented, after, tools),
96
+ hops=self.hops,
97
+ baseline_fi=self._structure.fi,
98
+ components_after=[sorted(c) for c in after],
99
+ reach_by_hop={k: sorted(v) for k, v in by_hop.items()},
100
+ )
101
+
102
+ def analyze_all(self) -> dict[str, BlastReport]:
103
+ return {nid: self.analyze(nid) for nid in sorted(self.graph.nodes)}
104
+
105
+ # ------------------------------------------------------------ internals
106
+ def _get_neighbors(self, node: str) -> set[str]:
107
+ return self.graph.neighbors(node)
108
+
109
+ def _get_n_hop(self, node: str, n: int) -> dict[int, set[str]]:
110
+ """Nodes first reached at each hop distance 1..n (BFS, undirected)."""
111
+ seen, frontier, out = {node}, {node}, {}
112
+ for hop in range(1, n + 1):
113
+ nxt = set().union(*(self.graph.neighbors(v) for v in frontier)) - seen if frontier else set()
114
+ if not nxt:
115
+ break
116
+ out[hop] = nxt
117
+ seen |= nxt
118
+ frontier = nxt
119
+ return out
120
+
121
+ def _reachable_tools(self, node: str) -> list[str]:
122
+ """Tools ``node`` can reach by invoking (transitively, along call direction)."""
123
+ seen, stack = {node}, [node]
124
+ while stack:
125
+ for w in self.graph.successors(stack.pop()):
126
+ if w not in seen:
127
+ seen.add(w)
128
+ stack.append(w)
129
+ return sorted(w for w in seen if w != node and self.graph.nodes[w].kind == "tool")
130
+
131
+ def _recommend(self, node: str, fragmented: bool, after: list[set[str]], tools: list[str]) -> str:
132
+ kind = self.graph.nodes[node].kind
133
+ if fragmented:
134
+ stranded = sum(len(c) for c in after) - max((len(c) for c in after), default=0)
135
+ return (f"Single point of failure: isolating {node} strands {stranded} node(s) in "
136
+ f"{len(after) - 1} detached group(s). Add a redundant path (a second caller or "
137
+ f"a fallback agent) before relying on isolation as a containment strategy.")
138
+ if kind in ("orchestrator", "agent") and tools:
139
+ return (f"Isolation is structurally safe, but {node} can invoke {len(tools)} tool(s); "
140
+ f"restrict its tool set to what its task needs.")
141
+ return f"Isolation is structurally safe: {node} can be cut off without splitting the system."
@@ -0,0 +1,503 @@
1
+ # agent-certify — Structural verification of multiagent systems
2
+ # Copyright 2026 Cognitive Engineering (Switzerland)
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """Signed structural baseline of a multiagent system.
5
+
6
+ An :class:`AgentCertificate` records a system's topology (which agents exist,
7
+ which tools each may invoke), its FI and its node roles, and is signed with an
8
+ Ed25519 key. :meth:`AgentCertificate.verify` compares a live graph against it
9
+ and names every structural change: a new agent, a new tool link, lost
10
+ redundancy. A topology change is visible before any behaviour it enables.
11
+
12
+ Trust model
13
+ -----------
14
+ A signature only means something when it is checked against a public key the
15
+ verifier already trusts. ``signer_public_key`` inside the certificate is
16
+ informational (it helps pick a key from a keyring) and is **never** used as the
17
+ trust anchor: whoever can edit the certificate can also replace it. So
18
+ :meth:`verify` fails unless it is given the issuer's public key, or is told
19
+ explicitly that unsigned certificates are acceptable (``allow_unsigned``).
20
+
21
+ Certificates issued since v0.5 also carry a validity window (``not_before``,
22
+ ``not_after``; 90 days by default) that :meth:`verify` enforces, so an older,
23
+ more permissive certificate cannot be replayed indefinitely.
24
+
25
+ Signed bytes (``cert_format`` 2, since v0.5)
26
+ --------------------------------------------
27
+ ``b"agent-certify/cert/v1\\x00"`` followed by the certificate as JSON: every
28
+ field except ``signature``, keys sorted, separators ``,`` and ``:``, non-ASCII
29
+ escaped (``ensure_ascii``), and ``fi_score`` written as a fixed-point decimal
30
+ string with 10 places, so that no float formatting is involved. Any
31
+ implementation that sorts keys and escapes the same way reproduces the bytes.
32
+
33
+ Certificates written before v0.5 (``cert_format`` 1) keep their original
34
+ encoding, so their signatures still verify; :meth:`verify` reports them as
35
+ legacy. The format is part of the signed bytes, so a v2 certificate cannot be
36
+ re-labelled as v1.
37
+
38
+ ``graph_hash`` covers the node ids, their kinds and the directed binary
39
+ adjacency (who may invoke whom). Call counts are deliberately left out: a
40
+ system that does the same thing more often has not changed shape.
41
+ """
42
+ from __future__ import annotations
43
+
44
+ import base64
45
+ import binascii
46
+ import hashlib
47
+ import json
48
+ import math
49
+ import re
50
+ import time
51
+ from dataclasses import MISSING, asdict, dataclass, field, fields
52
+ from datetime import datetime, timedelta, timezone
53
+ from pathlib import Path
54
+ from uuid import uuid4
55
+
56
+ from cryptography.exceptions import InvalidSignature
57
+ from cryptography.hazmat.primitives import serialization
58
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
59
+
60
+ from agent_certify.graph import NODE_KINDS, AgentGraph
61
+ from agent_certify.scanner import AgentFIScanner
62
+
63
+ DEFAULT_FI_TOLERANCE = 0.001
64
+ DEFAULT_VALIDITY_DAYS = 90
65
+ DOMAIN = b"agent-certify/cert/v1\x00"
66
+ CURRENT_FORMAT = 2
67
+ _TS = "%Y-%m-%dT%H:%M:%SZ"
68
+ _V2_ONLY = ("cert_format", "not_before", "not_after", "skipped_records")
69
+
70
+
71
+ def _now() -> str:
72
+ return time.strftime(_TS, time.gmtime())
73
+
74
+
75
+ def _parse_ts(value: str) -> datetime:
76
+ return datetime.strptime(value, _TS).replace(tzinfo=timezone.utc)
77
+
78
+
79
+ ROLE, ID = "role", "id"
80
+
81
+
82
+ def _topology(graph: AgentGraph, identity: str = ROLE) -> dict:
83
+ """Nodes and directed links, with agents named by type (``role``) or by unique id (``id``)."""
84
+ name = graph.role if identity == ROLE else (lambda nid: nid)
85
+ return {
86
+ "nodes": sorted({(name(nid), n.kind) for nid, n in graph.nodes.items()}),
87
+ "edges": sorted({(name(e.source), name(e.target)) for e in graph.edges}),
88
+ }
89
+
90
+
91
+ def graph_hash(graph: AgentGraph, identity: str = ROLE) -> str:
92
+ """SHA-256 of the graph's nodes and directed binary adjacency.
93
+
94
+ With ``identity="role"`` (the default since v0.3) sub-agents count by type,
95
+ so two sessions that spawn the same kinds of agent for the same tools hash
96
+ the same. ``identity="id"`` is the v0.1/v0.2 behaviour.
97
+ """
98
+ topo = _topology(graph, identity)
99
+ blob = json.dumps({"nodes": [list(n) for n in topo["nodes"]], "edges": [list(e) for e in topo["edges"]]},
100
+ sort_keys=True, separators=(",", ":"))
101
+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()
102
+
103
+
104
+ # ------------------------------------------------------------------------ keys
105
+ def generate_keypair() -> tuple[str, str]:
106
+ """New Ed25519 key pair as (private seed hex, public key hex)."""
107
+ key = Ed25519PrivateKey.generate()
108
+ return _private_hex(key), _public_hex(key.public_key())
109
+
110
+
111
+ def _private_hex(key: Ed25519PrivateKey) -> str:
112
+ return key.private_bytes(serialization.Encoding.Raw, serialization.PrivateFormat.Raw,
113
+ serialization.NoEncryption()).hex()
114
+
115
+
116
+ def _public_hex(key: Ed25519PublicKey) -> str:
117
+ return key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()
118
+
119
+
120
+ def _signing_key(key) -> Ed25519PrivateKey:
121
+ if isinstance(key, Ed25519PrivateKey):
122
+ return key
123
+ if isinstance(key, str):
124
+ key = bytes.fromhex(key.strip())
125
+ if isinstance(key, (bytes, bytearray)) and len(key) == 32:
126
+ return Ed25519PrivateKey.from_private_bytes(bytes(key))
127
+ raise TypeError("signing_key must be an Ed25519PrivateKey or its 32-byte seed (bytes or hex string)")
128
+
129
+
130
+ def _public_key_hex(public_key: str | bytes) -> str | None:
131
+ """Normalise a trusted public key to lowercase hex, or None when it is not 32 bytes."""
132
+ try:
133
+ raw = bytes(public_key) if isinstance(public_key, (bytes, bytearray)) else bytes.fromhex(str(public_key).strip())
134
+ except (ValueError, TypeError):
135
+ return None
136
+ return raw.hex() if len(raw) == 32 else None
137
+
138
+
139
+ # ----------------------------------------------------------------- certificate
140
+ @dataclass
141
+ class AgentCertificate:
142
+ """Signed structural baseline of a multiagent system.
143
+
144
+ Usage::
145
+
146
+ priv, pub = generate_keypair()
147
+ cert = AgentCertificate.create(graph, system_id="support-bot-v3", signing_key=priv)
148
+ cert.save("support-bot-v3.cert.json")
149
+
150
+ cert = AgentCertificate.load("support-bot-v3.cert.json")
151
+ drift = cert.verify(live_graph, public_key=pub) # the issuer's key, obtained out of band
152
+ drift.is_valid # False if the topology changed, the signature or dates are wrong
153
+ drift.added_edges # [["agent:planner", "tool:Bash"]]
154
+ """
155
+ system_id: str
156
+ timestamp: str
157
+ fi_score: float
158
+ node_count: int
159
+ edge_count: int
160
+ bridge_count: int
161
+ critical_nodes: list[str]
162
+ node_classifications: dict[str, str]
163
+ graph_hash: str # SHA-256 of the adjacency matrix
164
+ signature: str = "" # Ed25519 signature, base64
165
+ signer_public_key: str = "" # Ed25519 public key, hex — informational, never a trust anchor
166
+ nodes: dict[str, str] = field(default_factory=dict) # role (or id) -> kind
167
+ edges: list[list[str]] = field(default_factory=list) # directed [source, target]
168
+ certificate_id: str = ""
169
+ agent_certify_version: str = ""
170
+ # How agents are named in nodes/edges/graph_hash: "role" (by type, v0.3+) or
171
+ # "id" (unique spawn id). Certificates written before v0.3 have no such field
172
+ # and load as "id", so they keep comparing exactly as they did.
173
+ identity: str = ID
174
+ # Since v0.5. Certificates without these fields load as format 1 (legacy).
175
+ cert_format: int = 1
176
+ not_before: str = "" # ISO 8601 UTC; empty = no validity window (legacy)
177
+ not_after: str = ""
178
+ skipped_records: int = 0 # records the parser could not read when the graph was certified
179
+
180
+ @classmethod
181
+ def create(cls, graph: AgentGraph, system_id: str | None = None, signing_key=None,
182
+ validity_days: int = DEFAULT_VALIDITY_DAYS, now: datetime | None = None) -> AgentCertificate:
183
+ """Scan ``graph`` and package its structural profile, valid for ``validity_days``."""
184
+ from agent_certify import __version__
185
+
186
+ if not isinstance(validity_days, int) or validity_days < 1:
187
+ raise ValueError("validity_days must be a positive integer")
188
+ start = (now or datetime.now(timezone.utc)).astimezone(timezone.utc).replace(microsecond=0)
189
+ result = AgentFIScanner(graph).scan()
190
+ topo = _topology(graph, ROLE)
191
+ cert = cls(
192
+ system_id=system_id or graph.session_id or "unnamed-system",
193
+ timestamp=start.strftime(_TS),
194
+ fi_score=result.fi,
195
+ node_count=result.node_count,
196
+ edge_count=result.edge_count,
197
+ bridge_count=len(result.bridges),
198
+ critical_nodes=result.critical_nodes,
199
+ node_classifications=result.node_classifications,
200
+ graph_hash=graph_hash(graph, ROLE),
201
+ nodes={nid: kind for nid, kind in topo["nodes"]},
202
+ edges=[list(e) for e in topo["edges"]],
203
+ certificate_id=str(uuid4()),
204
+ agent_certify_version=__version__,
205
+ identity=ROLE,
206
+ cert_format=CURRENT_FORMAT,
207
+ not_before=start.strftime(_TS),
208
+ not_after=(start + timedelta(days=validity_days)).strftime(_TS),
209
+ skipped_records=graph.skipped_records,
210
+ )
211
+ if signing_key is not None:
212
+ cert.sign(signing_key)
213
+ return cert
214
+
215
+ # --------------------------------------------------------------- signature
216
+ def payload(self) -> bytes:
217
+ """The exact bytes the signature covers (see the module docstring)."""
218
+ data = asdict(self)
219
+ data.pop("signature")
220
+ if self.cert_format >= 2:
221
+ data["fi_score"] = f"{self.fi_score:.10f}"
222
+ return DOMAIN + json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii")
223
+ for key in _V2_ONLY: # pre-v0.5 encoding, kept so old signatures still verify
224
+ data.pop(key)
225
+ if data["identity"] == ID:
226
+ data.pop("identity") # pre-v0.3 certificates were signed without this field
227
+ return json.dumps(data, sort_keys=True, separators=(",", ":")).encode("utf-8")
228
+
229
+ def sign(self, signing_key) -> AgentCertificate:
230
+ """Sign the certificate in place with an Ed25519 private key."""
231
+ key = _signing_key(signing_key)
232
+ self.signer_public_key = _public_hex(key.public_key())
233
+ self.signature = base64.b64encode(key.sign(self.payload())).decode("ascii")
234
+ return self
235
+
236
+ @property
237
+ def is_signed(self) -> bool:
238
+ return bool(self.signature)
239
+
240
+ def signature_valid(self, public_key: str | bytes | None = None) -> bool:
241
+ """True only when the certificate was signed by ``public_key`` and not edited since.
242
+
243
+ ``public_key`` is the issuer's key (hex or 32 raw bytes), obtained through a
244
+ trusted channel. Without it this returns False: the key recorded in the
245
+ certificate proves nothing, since whoever edits the certificate can
246
+ replace it too.
247
+ """
248
+ if not self.signature or public_key is None:
249
+ return False
250
+ trusted = _public_key_hex(public_key)
251
+ if trusted is None:
252
+ return False
253
+ try:
254
+ Ed25519PublicKey.from_public_bytes(bytes.fromhex(trusted)).verify(
255
+ base64.b64decode(self.signature, validate=True), self.payload())
256
+ except (InvalidSignature, ValueError, TypeError, binascii.Error):
257
+ return False
258
+ return True
259
+
260
+ # ------------------------------------------------------------ verification
261
+ def verify(self, graph: AgentGraph, fi_tolerance: float = DEFAULT_FI_TOLERANCE,
262
+ public_key: str | bytes | None = None, *, allow_unsigned: bool = False,
263
+ ignore_expiry: bool = False, expected_system_id: str | None = None,
264
+ now: datetime | None = None) -> DriftReport:
265
+ """Compare a live graph against this certificate.
266
+
267
+ Fails (``is_valid`` False) when: the topology or FI changed; no trusted
268
+ ``public_key`` is given (unless ``allow_unsigned``); the certificate is
269
+ unsigned or its signature does not match that key; the current time is
270
+ outside [``not_before``, ``not_after``] (unless ``ignore_expiry``); the
271
+ system id differs from ``expected_system_id``. Agents are compared the
272
+ way the certificate names them: by type since v0.3, by spawn id before.
273
+ """
274
+ reasons: list[str] = []
275
+ warnings: list[str] = []
276
+
277
+ # --- trust: signature against a key the caller supplies
278
+ sig_ok: bool | None = None
279
+ if public_key is not None:
280
+ if not self.is_signed:
281
+ reasons.append("Certificate is not signed")
282
+ sig_ok = False
283
+ else:
284
+ sig_ok = self.signature_valid(public_key)
285
+ if not sig_ok:
286
+ reasons.append("Certificate signature is invalid or was not made by the trusted key")
287
+ elif allow_unsigned:
288
+ warnings.append("Signature not checked (unsigned certificates explicitly allowed)")
289
+ elif not self.is_signed:
290
+ reasons.append("Certificate is not signed")
291
+ else:
292
+ reasons.append("No trusted public key given: the signature cannot be checked")
293
+
294
+ # --- validity window
295
+ moment = (now or datetime.now(timezone.utc)).astimezone(timezone.utc)
296
+ if not (self.not_before or self.not_after):
297
+ warnings.append("Certificate has no validity period (issued before v0.5): it never expires")
298
+ elif not ignore_expiry:
299
+ try:
300
+ if self.not_before and moment < _parse_ts(self.not_before):
301
+ reasons.append(f"Certificate not valid before {self.not_before}")
302
+ if self.not_after and moment > _parse_ts(self.not_after):
303
+ reasons.append(f"Certificate expired on {self.not_after}")
304
+ except ValueError:
305
+ reasons.append("Certificate validity dates are malformed")
306
+ if self.cert_format < CURRENT_FORMAT:
307
+ warnings.append("Legacy certificate format (issued before v0.5); re-issue it to get the current format")
308
+ if expected_system_id is not None and expected_system_id != self.system_id:
309
+ reasons.append(f"Certificate is for system {self.system_id!r}, not {expected_system_id!r}")
310
+ if not (isinstance(self.fi_score, (int, float)) and math.isfinite(self.fi_score)):
311
+ reasons.append("Certificate FI is not a finite number")
312
+
313
+ # --- topology
314
+ result = AgentFIScanner(graph).scan()
315
+ topo = _topology(graph, self.identity)
316
+ now_nodes = dict(topo["nodes"])
317
+ now_edges = {tuple(e) for e in topo["edges"]}
318
+ cert_edges = {tuple(e) for e in self.edges}
319
+ kind_changed = sorted(n for n in set(now_nodes) & set(self.nodes) if now_nodes[n] != self.nodes[n])
320
+ added_nodes = sorted(set(now_nodes) - set(self.nodes))
321
+ removed_nodes = sorted(set(self.nodes) - set(now_nodes))
322
+ added_edges = sorted(list(e) for e in now_edges - cert_edges)
323
+ removed_edges = sorted(list(e) for e in cert_edges - now_edges)
324
+ # Roles of individual agents can't be paired across sessions; compare the rest.
325
+ comparable = {n for n in result.node_classifications
326
+ if self.identity == ID or graph.nodes[n].kind != "agent"}
327
+ changed = [{"node": n, "was": self.node_classifications[n], "now": c}
328
+ for n, c in sorted(result.node_classifications.items())
329
+ if n in comparable and n in self.node_classifications and self.node_classifications[n] != c]
330
+ fi_delta = result.fi - self.fi_score if math.isfinite(self.fi_score) else float("nan")
331
+ hash_match = graph_hash(graph, self.identity) == self.graph_hash
332
+
333
+ def is_agent_type(n):
334
+ return self.identity == ROLE and n.startswith("agent:")
335
+
336
+ added_types = [n for n in added_nodes if is_agent_type(n)]
337
+ removed_types = [n for n in removed_nodes if is_agent_type(n)]
338
+ added_other = [n for n in added_nodes if not is_agent_type(n)]
339
+ removed_other = [n for n in removed_nodes if not is_agent_type(n)]
340
+
341
+ topology_reasons = [f"New agent type: {n} (not in certified baseline)" for n in added_types]
342
+ topology_reasons += [f"Missing agent type: {n} (was in certified baseline)" for n in removed_types]
343
+ topology_reasons += [f"Node kind changed: {n} (was {self.nodes[n]}, now {now_nodes[n]})" for n in kind_changed]
344
+ if added_other:
345
+ topology_reasons.append(f"{len(added_other)} node(s) not in the certified topology: {', '.join(added_other)}")
346
+ if removed_other:
347
+ topology_reasons.append(f"{len(removed_other)} certified node(s) missing: {', '.join(removed_other)}")
348
+ if added_edges:
349
+ topology_reasons.append(f"{len(added_edges)} new invocation link(s): "
350
+ + ", ".join(f"{s} -> {t}" for s, t in added_edges))
351
+ if removed_edges:
352
+ topology_reasons.append(f"{len(removed_edges)} certified link(s) gone: "
353
+ + ", ".join(f"{s} -> {t}" for s, t in removed_edges))
354
+ if not hash_match and not topology_reasons:
355
+ topology_reasons.append("Topology hash differs from the certified one")
356
+ reasons += topology_reasons
357
+ if math.isfinite(fi_delta) and abs(fi_delta) >= fi_tolerance:
358
+ reasons.append(f"FI changed by {fi_delta:+.4f} (tolerance {fi_tolerance})")
359
+ if graph.skipped_records:
360
+ warnings.append(f"{graph.skipped_records} record(s) of the live session could not be read")
361
+
362
+ return DriftReport(
363
+ is_valid=not reasons, graph_hash_match=hash_match,
364
+ fi_certified=self.fi_score, fi_current=result.fi, fi_delta=fi_delta,
365
+ added_nodes=added_nodes, removed_nodes=removed_nodes,
366
+ added_edges=added_edges, removed_edges=removed_edges,
367
+ changed_classifications=changed, signature_valid=sig_ok,
368
+ certificate_id=self.certificate_id, verified_at=_now(), reasons=reasons,
369
+ added_agent_types=added_types, removed_agent_types=removed_types,
370
+ kind_changes=kind_changed, warnings=warnings,
371
+ )
372
+
373
+ # --------------------------------------------------------------------- io
374
+ def to_dict(self) -> dict:
375
+ return asdict(self)
376
+
377
+ def save(self, path) -> Path:
378
+ p = Path(path)
379
+ p.write_text(json.dumps(self.to_dict(), indent=2), encoding="utf-8")
380
+ return p
381
+
382
+ @classmethod
383
+ def from_dict(cls, data) -> AgentCertificate:
384
+ """Build a certificate from untrusted JSON data, checking every field's type and range.
385
+
386
+ Raises ``ValueError("Invalid certificate format")`` on any problem; the
387
+ message deliberately names no field or value.
388
+ """
389
+ try:
390
+ _validate(data)
391
+ return cls(**data)
392
+ except (TypeError, KeyError, AttributeError):
393
+ raise ValueError("Invalid certificate format") from None
394
+
395
+ @classmethod
396
+ def load(cls, path) -> AgentCertificate:
397
+ """Read a certificate written by :meth:`save`. NaN and Infinity are rejected."""
398
+ try:
399
+ data = json.loads(Path(path).read_text(encoding="utf-8"), parse_constant=_reject_constant)
400
+ except (json.JSONDecodeError, UnicodeDecodeError, RecursionError):
401
+ raise ValueError("Invalid certificate format") from None
402
+ return cls.from_dict(data)
403
+
404
+
405
+ def _reject_constant(name: str):
406
+ raise ValueError("Invalid certificate format")
407
+
408
+
409
+ _HEX64 = re.compile(r"[0-9a-f]{64}")
410
+ _FIELD_TYPES = {f.name: f for f in fields(AgentCertificate)}
411
+
412
+
413
+ def _validate(data) -> None:
414
+ def check(ok: bool):
415
+ if not ok:
416
+ raise ValueError("Invalid certificate format")
417
+
418
+ def is_count(v):
419
+ return isinstance(v, int) and not isinstance(v, bool) and v >= 0
420
+
421
+ def is_str_list(v):
422
+ return isinstance(v, list) and all(isinstance(x, str) for x in v)
423
+
424
+ check(isinstance(data, dict))
425
+ check(set(data) <= set(_FIELD_TYPES))
426
+ required = {n for n, f in _FIELD_TYPES.items() if f.default is MISSING and f.default_factory is MISSING}
427
+ check(required <= set(data))
428
+ for key in ("system_id", "timestamp", "graph_hash", "signature", "signer_public_key", "certificate_id",
429
+ "agent_certify_version", "identity", "not_before", "not_after"):
430
+ if key in data:
431
+ check(isinstance(data[key], str))
432
+ fi = data["fi_score"]
433
+ check(isinstance(fi, (int, float)) and not isinstance(fi, bool) and math.isfinite(fi) and 0 <= fi <= 1)
434
+ for key in ("node_count", "edge_count", "bridge_count", "skipped_records"):
435
+ if key in data:
436
+ check(is_count(data[key]))
437
+ check(is_str_list(data["critical_nodes"]))
438
+ check(isinstance(data["node_classifications"], dict)
439
+ and all(isinstance(k, str) and isinstance(v, str) for k, v in data["node_classifications"].items()))
440
+ check(bool(_HEX64.fullmatch(data["graph_hash"])))
441
+ if "nodes" in data:
442
+ check(isinstance(data["nodes"], dict)
443
+ and all(isinstance(k, str) and v in NODE_KINDS for k, v in data["nodes"].items()))
444
+ if "edges" in data:
445
+ check(isinstance(data["edges"], list) and all(is_str_list(e) and len(e) == 2 for e in data["edges"]))
446
+ check(data.get("identity", ID) in (ID, ROLE))
447
+ check(data.get("cert_format", 1) in (1, 2) and not isinstance(data.get("cert_format", 1), bool))
448
+ if data.get("signer_public_key"):
449
+ check(bool(_HEX64.fullmatch(data["signer_public_key"])))
450
+ if data.get("signature"):
451
+ try:
452
+ check(len(base64.b64decode(data["signature"], validate=True)) == 64)
453
+ except (binascii.Error, ValueError):
454
+ check(False)
455
+ stamps = {}
456
+ for key in ("timestamp", "not_before", "not_after"):
457
+ if data.get(key):
458
+ try:
459
+ stamps[key] = _parse_ts(data[key])
460
+ except ValueError:
461
+ check(False) # strptime's message would quote the value
462
+ if "not_before" in stamps and "not_after" in stamps:
463
+ check(stamps["not_before"] <= stamps["not_after"])
464
+
465
+
466
+ @dataclass
467
+ class DriftReport:
468
+ """Structural differences between a live graph and its certificate."""
469
+ is_valid: bool
470
+ graph_hash_match: bool
471
+ fi_certified: float
472
+ fi_current: float
473
+ fi_delta: float
474
+ added_nodes: list[str]
475
+ removed_nodes: list[str]
476
+ added_edges: list[list[str]]
477
+ removed_edges: list[list[str]]
478
+ changed_classifications: list[dict]
479
+ signature_valid: bool | None # None = not checked (no key, unsigned certificates allowed)
480
+ certificate_id: str
481
+ verified_at: str
482
+ reasons: list[str] = field(default_factory=list)
483
+ added_agent_types: list[str] = field(default_factory=list)
484
+ removed_agent_types: list[str] = field(default_factory=list)
485
+ kind_changes: list[str] = field(default_factory=list)
486
+ warnings: list[str] = field(default_factory=list)
487
+
488
+ def to_dict(self) -> dict:
489
+ return asdict(self)
490
+
491
+ def __str__(self) -> str:
492
+ sig = "not checked" if self.signature_valid is None else ("valid" if self.signature_valid else "INVALID")
493
+ lines = [
494
+ f"Verification: {'PASS' if self.is_valid else 'FAIL'}",
495
+ f" FI: {self.fi_certified:.4f} -> {self.fi_current:.4f} (delta={self.fi_delta:+.4f})",
496
+ f" Topology hash match: {self.graph_hash_match}",
497
+ f" Role changes: {len(self.changed_classifications)} (informational)",
498
+ f" Signature: {sig}",
499
+ f" Certificate: {self.certificate_id}",
500
+ ]
501
+ lines += [f" - {r}" for r in self.reasons]
502
+ lines += [f" ! {w}" for w in self.warnings]
503
+ return "\n".join(lines)