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/graph.py ADDED
@@ -0,0 +1,325 @@
1
+ # agent-certify — Structural verification of multiagent systems
2
+ # Copyright 2026 Cognitive Engineering (Switzerland)
3
+ # SPDX-License-Identifier: Apache-2.0
4
+ """Agent graph data model.
5
+
6
+ An :class:`AgentGraph` is the communication topology of a multiagent session:
7
+ agents, tools and humans as nodes, invocations as directed edges. Structural
8
+ analysis (FI, bridges, blast radius) works on the undirected version, where two
9
+ nodes are linked if either one ever invoked the other.
10
+
11
+ Edges are indexed by (source, target) and adjacency sets are kept alongside, so
12
+ edge lookups are O(1) and neighbourhoods O(degree). The index follows ``edges``:
13
+ it is rebuilt whenever that list is replaced or changes length outside
14
+ :meth:`AgentGraph.add_call`.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import copy
19
+ import math
20
+ from collections.abc import Iterable
21
+ from dataclasses import asdict, dataclass, field
22
+
23
+ NODE_KINDS = ("human", "orchestrator", "agent", "tool", "file") # file: code written (Cursor agent-trace)
24
+
25
+
26
+ @dataclass
27
+ class AgentNode:
28
+ """A node in the agent graph — an agent or a tool."""
29
+ id: str # unique identifier
30
+ kind: str # "agent", "tool", "human", "orchestrator", "file"
31
+ name: str # display name (e.g., "Bash", "Edit", "sub-agent-1")
32
+ call_count: int = 0 # how many times this node was invoked
33
+ error_count: int = 0 # how many times it returned an error
34
+ metadata: dict = field(default_factory=dict)
35
+
36
+
37
+ @dataclass
38
+ class AgentEdge:
39
+ """A directed edge: source invoked target."""
40
+ source: str # caller node id
41
+ target: str # callee node id
42
+ weight: int = 1 # number of invocations
43
+ errors: int = 0 # number of failed invocations
44
+ tri_count: int = 0 # triangle participation (computed by scanner)
45
+
46
+ @property
47
+ def key(self) -> frozenset:
48
+ """Undirected identity of the edge."""
49
+ return frozenset((self.source, self.target))
50
+
51
+
52
+ @dataclass
53
+ class AgentGraph:
54
+ """The complete topology of a multiagent session."""
55
+ nodes: dict[str, AgentNode] = field(default_factory=dict)
56
+ edges: list[AgentEdge] = field(default_factory=list)
57
+ session_id: str | None = None
58
+ project: str | None = None
59
+ total_messages: int = 0
60
+ total_tool_calls: int = 0
61
+ duration_seconds: float | None = None
62
+ started_at: str | None = None # ISO 8601, UTC
63
+ ended_at: str | None = None
64
+ skipped_records: int = 0 # malformed / oversized records the parser could not read
65
+
66
+ _edge_index: dict = field(default=None, init=False, repr=False, compare=False)
67
+ _adjacency: dict = field(default=None, init=False, repr=False, compare=False)
68
+ _successors: dict = field(default=None, init=False, repr=False, compare=False)
69
+ _index_key: tuple = field(default=None, init=False, repr=False, compare=False)
70
+
71
+ # ---------------------------------------------------------------- index
72
+ def _ensure_index(self) -> None:
73
+ key = (id(self.edges), len(self.edges))
74
+ if self._index_key == key:
75
+ return
76
+ index, adj, succ = {}, {}, {}
77
+ for e in self.edges:
78
+ index[(e.source, e.target)] = e
79
+ adj.setdefault(e.source, set()).add(e.target)
80
+ adj.setdefault(e.target, set()).add(e.source)
81
+ succ.setdefault(e.source, set()).add(e.target)
82
+ self._edge_index, self._adjacency, self._successors, self._index_key = index, adj, succ, key
83
+
84
+ def _index_append(self, e: AgentEdge) -> None:
85
+ """Record an edge just appended to ``edges`` without rebuilding the index."""
86
+ self._edge_index[(e.source, e.target)] = e
87
+ self._adjacency.setdefault(e.source, set()).add(e.target)
88
+ self._adjacency.setdefault(e.target, set()).add(e.source)
89
+ self._successors.setdefault(e.source, set()).add(e.target)
90
+ self._index_key = (id(self.edges), len(self.edges))
91
+
92
+ # ------------------------------------------------------------- building
93
+ def add_node(self, node_id: str, kind: str, name: str | None = None, **metadata) -> AgentNode:
94
+ """Add a node, or return the existing one with that id."""
95
+ if kind not in NODE_KINDS:
96
+ raise ValueError(f"unknown node kind {kind!r}; expected one of {NODE_KINDS}")
97
+ node = self.nodes.get(node_id)
98
+ if node is None:
99
+ node = self.nodes[node_id] = AgentNode(id=node_id, kind=kind, name=name or node_id)
100
+ node.metadata.update(metadata)
101
+ return node
102
+
103
+ def get_edge(self, source: str, target: str) -> AgentEdge | None:
104
+ self._ensure_index()
105
+ return self._edge_index.get((source, target))
106
+
107
+ def add_call(self, source: str, target: str, error: bool = False, count: int = 1) -> AgentEdge:
108
+ """Record ``count`` invocations of ``target`` by ``source``."""
109
+ for nid in (source, target):
110
+ if nid not in self.nodes:
111
+ raise KeyError(f"unknown node {nid!r}; add it with add_node() first")
112
+ if source == target:
113
+ raise ValueError(f"self-loop on {source!r}")
114
+ edge = self.get_edge(source, target)
115
+ if edge is None:
116
+ edge = AgentEdge(source, target, weight=0)
117
+ self.edges.append(edge)
118
+ self._index_append(edge)
119
+ edge.weight += count
120
+ self.nodes[target].call_count += count
121
+ if error:
122
+ edge.errors += 1
123
+ self.nodes[target].error_count += 1
124
+ return edge
125
+
126
+ def record_error(self, source: str, target: str) -> None:
127
+ """Mark one already-recorded invocation of ``target`` by ``source`` as failed."""
128
+ edge = self.get_edge(source, target)
129
+ if edge is None:
130
+ raise KeyError(f"no edge {source!r} -> {target!r}")
131
+ edge.errors += 1
132
+ self.nodes[target].error_count += 1
133
+
134
+ # ------------------------------------------------------------ structure
135
+ def adjacency_matrix(self) -> tuple[list[str], list[list[int]]]:
136
+ """Return (node_ids, matrix) for FI computation.
137
+
138
+ The matrix is the binary, symmetric adjacency of the undirected graph:
139
+ ``matrix[i][j] == 1`` when either node ever invoked the other. Node ids
140
+ are sorted so the matrix is canonical for a given topology. O(n²) memory:
141
+ the scanner itself works on :meth:`adjacency` instead.
142
+ """
143
+ ids = sorted(self.nodes)
144
+ index = {nid: i for i, nid in enumerate(ids)}
145
+ n = len(ids)
146
+ matrix = [[0] * n for _ in range(n)]
147
+ for e in self.edges:
148
+ i, j = index[e.source], index[e.target]
149
+ matrix[i][j] = matrix[j][i] = 1
150
+ return ids, matrix
151
+
152
+ def neighbors(self, node_id: str) -> set[str]:
153
+ """Undirected neighbours of ``node_id`` (a copy; safe to modify)."""
154
+ self._ensure_index()
155
+ return set(self._adjacency.get(node_id, ()))
156
+
157
+ def adjacency(self) -> dict[str, set[str]]:
158
+ """Undirected adjacency of every node, isolated ones included. Do not modify the sets."""
159
+ self._ensure_index()
160
+ empty: set[str] = set()
161
+ return {nid: self._adjacency.get(nid, empty) for nid in self.nodes}
162
+
163
+ def successors(self, node_id: str) -> set[str]:
164
+ """Nodes that ``node_id`` invoked."""
165
+ self._ensure_index()
166
+ return set(self._successors.get(node_id, ()))
167
+
168
+ def undirected_edges(self) -> list[tuple[str, str]]:
169
+ """Distinct undirected edges as sorted (a, b) pairs."""
170
+ return sorted({tuple(sorted((e.source, e.target))) for e in self.edges})
171
+
172
+ def remove_node(self, node_id: str) -> AgentGraph:
173
+ """Return a copy with node_id and its edges removed."""
174
+ if node_id not in self.nodes:
175
+ raise KeyError(f"unknown node {node_id!r}")
176
+ g = copy.deepcopy(self)
177
+ del g.nodes[node_id]
178
+ g.edges = [e for e in g.edges if node_id not in (e.source, e.target)]
179
+ return g
180
+
181
+ def connected_components(self, without: str | None = None) -> list[set[str]]:
182
+ """Return connected components of the undirected version.
183
+
184
+ ``without`` leaves one node out, as if it were removed, without copying the graph.
185
+ """
186
+ adj = self.adjacency()
187
+ seen: set[str] = {without} if without is not None else set()
188
+ components = []
189
+ for start in sorted(adj):
190
+ if start in seen:
191
+ continue
192
+ comp, stack = set(), [start]
193
+ while stack:
194
+ v = stack.pop()
195
+ if v in comp:
196
+ continue
197
+ comp.add(v)
198
+ stack.extend(w for w in adj[v] if w not in comp and w != without)
199
+ seen |= comp
200
+ components.append(comp)
201
+ return components
202
+
203
+ # ---------------------------------------------------------------- lookup
204
+ def role(self, node_id: str) -> str:
205
+ """Stable identity of a node across sessions.
206
+
207
+ Sub-agent ids are unique per spawn, so an agent's role is its type
208
+ (``agent:Explore``, or ``agent:unknown``); every other node is its own role.
209
+ """
210
+ node = self.nodes[node_id]
211
+ if node.kind == "agent":
212
+ return f"agent:{node.metadata.get('agentType') or 'unknown'}"
213
+ return node_id
214
+
215
+ def resolve(self, name: str) -> str:
216
+ """Find a node id from an id or display name (case-insensitive).
217
+
218
+ ``resolve("bash")`` finds ``tool:Bash``. Raises ``KeyError`` when the name
219
+ matches no node or more than one.
220
+ """
221
+ if name in self.nodes:
222
+ return name
223
+ low = name.lower()
224
+ hits = [nid for nid, n in self.nodes.items() if nid.lower() == low or n.name.lower() == low]
225
+ if len(hits) == 1:
226
+ return hits[0]
227
+ if not hits:
228
+ raise KeyError(f"no node named {name!r}; known: {', '.join(sorted(self.nodes))}")
229
+ raise KeyError(f"{name!r} is ambiguous: {', '.join(sorted(hits))}")
230
+
231
+ # ------------------------------------------------------------------- io
232
+ def to_dict(self) -> dict:
233
+ return {
234
+ "session_id": self.session_id,
235
+ "project": self.project,
236
+ "total_messages": self.total_messages,
237
+ "total_tool_calls": self.total_tool_calls,
238
+ "duration_seconds": self.duration_seconds,
239
+ "started_at": self.started_at,
240
+ "ended_at": self.ended_at,
241
+ "skipped_records": self.skipped_records,
242
+ "nodes": [asdict(n) for n in self.nodes.values()],
243
+ "edges": [asdict(e) for e in self.edges],
244
+ }
245
+
246
+ @classmethod
247
+ def from_dict(cls, data: dict) -> AgentGraph:
248
+ """Rebuild a graph from :meth:`to_dict` output; ``ValueError("Invalid graph format")`` otherwise."""
249
+ try:
250
+ _check(isinstance(data, dict))
251
+ _check(all(data.get(k) is None or isinstance(data[k], str)
252
+ for k in ("session_id", "project", "started_at", "ended_at")))
253
+ _check(all(_is_count(data.get(k, 0)) for k in ("total_messages", "total_tool_calls", "skipped_records")))
254
+ duration = data.get("duration_seconds")
255
+ _check(duration is None or (_is_number(duration) and duration >= 0))
256
+ nodes, edges = data.get("nodes", []), data.get("edges", [])
257
+ _check(isinstance(nodes, list) and isinstance(edges, list))
258
+ g = cls(session_id=data.get("session_id"), project=data.get("project"),
259
+ total_messages=data.get("total_messages", 0), total_tool_calls=data.get("total_tool_calls", 0),
260
+ duration_seconds=duration, started_at=data.get("started_at"), ended_at=data.get("ended_at"),
261
+ skipped_records=data.get("skipped_records", 0))
262
+ for n in nodes:
263
+ _check(isinstance(n, dict) and set(n) <= set(AgentNode.__dataclass_fields__))
264
+ _check(isinstance(n.get("id"), str) and n.get("kind") in NODE_KINDS and isinstance(n.get("name"), str))
265
+ _check(_is_count(n.get("call_count", 0)) and _is_count(n.get("error_count", 0)))
266
+ _check(isinstance(n.get("metadata", {}), dict))
267
+ g.nodes[n["id"]] = AgentNode(**n)
268
+ for e in edges:
269
+ _check(isinstance(e, dict) and set(e) <= set(AgentEdge.__dataclass_fields__))
270
+ _check(e.get("source") in g.nodes and e.get("target") in g.nodes and e["source"] != e["target"])
271
+ _check(all(_is_count(e.get(k, 0)) for k in ("weight", "errors", "tri_count")))
272
+ g.edges = [AgentEdge(**e) for e in edges]
273
+ except (TypeError, KeyError, AttributeError):
274
+ raise ValueError("Invalid graph format") from None
275
+ return g
276
+
277
+ @classmethod
278
+ def merge(cls, graphs: Iterable[AgentGraph], session_id: str | None = None) -> AgentGraph:
279
+ """Union of several graphs: nodes with the same id are combined and counts summed."""
280
+ out = cls(session_id=session_id)
281
+ durations = []
282
+ projects = set()
283
+ for g in graphs:
284
+ for n in g.nodes.values():
285
+ m = out.add_node(n.id, n.kind, n.name)
286
+ m.call_count += n.call_count
287
+ m.error_count += n.error_count
288
+ for k, v in n.metadata.items():
289
+ m.metadata.setdefault(k, v)
290
+ for e in g.edges:
291
+ f = out.get_edge(e.source, e.target)
292
+ if f is None:
293
+ f = AgentEdge(e.source, e.target, weight=e.weight, errors=e.errors)
294
+ out.edges.append(f)
295
+ out._index_append(f)
296
+ else:
297
+ f.weight += e.weight
298
+ f.errors += e.errors
299
+ out.total_messages += g.total_messages
300
+ out.total_tool_calls += g.total_tool_calls
301
+ out.skipped_records += g.skipped_records
302
+ if g.duration_seconds is not None:
303
+ durations.append(g.duration_seconds)
304
+ if g.project:
305
+ projects.add(g.project)
306
+ if g.started_at and (out.started_at is None or g.started_at < out.started_at):
307
+ out.started_at = g.started_at
308
+ if g.ended_at and (out.ended_at is None or g.ended_at > out.ended_at):
309
+ out.ended_at = g.ended_at
310
+ out.duration_seconds = sum(durations) if durations else None
311
+ out.project = projects.pop() if len(projects) == 1 else None
312
+ return out
313
+
314
+
315
+ def _check(ok: bool) -> None:
316
+ if not ok:
317
+ raise ValueError("Invalid graph format")
318
+
319
+
320
+ def _is_count(v) -> bool:
321
+ return isinstance(v, int) and not isinstance(v, bool) and v >= 0
322
+
323
+
324
+ def _is_number(v) -> bool:
325
+ return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)