graphlore 0.7.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.
graphlore/graph.py ADDED
@@ -0,0 +1,1643 @@
1
+ """graph.json loading + schema-tolerant node/edge/traversal helpers.
2
+
3
+ Pure graph-data utilities with no dependency on the MCP surface; reads the project
4
+ location from :mod:`graphlore.config`.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import difflib
9
+ import json
10
+ import re
11
+ from collections import deque
12
+ from collections.abc import Callable, Iterable, Sequence
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from . import config
17
+
18
+
19
+ def _out_dir() -> Path:
20
+ return config.PROJECT_DIR / config.OUT_DIR_NAME
21
+
22
+
23
+ def _graph_path() -> Path:
24
+ return _out_dir() / "graph.json"
25
+
26
+
27
+ # Parsed graph.json cache, keyed by path -> (mtime, data). Avoids re-parsing a
28
+ # multi-MB graph on every tool call; keyed on path (not just mtime) so distinct
29
+ # graphs in tests can't collide on a coarse-resolution mtime.
30
+ _GRAPH_CACHE: dict[str, tuple[float, dict[str, Any]]] = {}
31
+ # id(nodes list) -> (nodes, the graph's `graph` header): lets helpers that get
32
+ # only the node list (resolve.py) ask which engine wrote it. Identity-guarded
33
+ # like the other id-keyed caches.
34
+ _GRAPH_META: dict[int, tuple[list, dict[str, Any]]] = {}
35
+ _GRAPH_META_MAX = 8
36
+
37
+
38
+ def _load_graph() -> dict[str, Any] | str:
39
+ """Load graph.json (cached by path+mtime); return an error message if missing."""
40
+ gp = _graph_path()
41
+ if not gp.exists():
42
+ return (
43
+ f"ERROR: {gp} not found. Run the graphlore_build tool first "
44
+ f"(project directory: {config.PROJECT_DIR})."
45
+ )
46
+ try:
47
+ mtime = gp.stat().st_mtime
48
+ key = str(gp)
49
+ cached = _GRAPH_CACHE.get(key)
50
+ if cached is not None and cached[0] == mtime:
51
+ return cached[1]
52
+ data = json.loads(gp.read_text(encoding="utf-8"))
53
+ if not isinstance(data, dict):
54
+ # Callers guard errors with isinstance(graph, str), so any valid-JSON
55
+ # non-object (a top-level array/string/number) must become an error
56
+ # string here — not leak through and AttributeError inside every tool.
57
+ return f"ERROR: graph.json must be a JSON object, not {type(data).__name__}"
58
+ _GRAPH_CACHE[key] = (mtime, data)
59
+ _remember_meta(data)
60
+ return data
61
+ except json.JSONDecodeError as e:
62
+ return f"ERROR: failed to parse graph.json: {e}"
63
+ except (OSError, UnicodeDecodeError) as e:
64
+ # stat/read can fail mid-rebuild (file swapped between exists() and stat)
65
+ # or on undecodable bytes; both are "graph unavailable", not a crash.
66
+ return f"ERROR: failed to read graph.json: {e}"
67
+
68
+
69
+ def _remember_meta(data: dict[str, Any]) -> None:
70
+ nodes = data.get("nodes") or data.get("vertices")
71
+ meta = data.get("graph")
72
+ if not isinstance(nodes, list) or not isinstance(meta, dict):
73
+ return
74
+ if id(nodes) not in _GRAPH_META and len(_GRAPH_META) >= _GRAPH_META_MAX:
75
+ _GRAPH_META.pop(next(iter(_GRAPH_META)), None) # FIFO
76
+ _GRAPH_META[id(nodes)] = (nodes, meta)
77
+
78
+
79
+ def _graph_meta(nodes: list) -> dict[str, Any]:
80
+ """The `graph` header of the loaded graph these nodes came from ({} if none)."""
81
+ entry = _GRAPH_META.get(id(nodes))
82
+ return entry[1] if entry is not None and entry[0] is nodes else {}
83
+
84
+
85
+ def _engine_resolved(nodes: list) -> bool:
86
+ """Whether graphlore's native engine wrote this graph with its own import and
87
+ call resolution (schema 2 on): its edges need no correcting at read time."""
88
+ meta = _graph_meta(nodes)
89
+ try:
90
+ return meta.get("engine") == "graphlore" and int(meta.get("schema_version", 0)) >= 2
91
+ except (TypeError, ValueError):
92
+ return False
93
+
94
+
95
+ def _native_routes(nodes: list) -> bool:
96
+ """Whether the native engine wrote this graph's routes (schema 5 on): route
97
+ nodes with their full paths, `handles` and `http_calls` edges."""
98
+ meta = _graph_meta(nodes)
99
+ try:
100
+ return meta.get("engine") == "graphlore" and int(meta.get("schema_version", 0)) >= 5
101
+ except (TypeError, ValueError):
102
+ return False
103
+
104
+
105
+ def _nodes_edges(graph: dict[str, Any]) -> tuple[list[dict], list[dict]]:
106
+ """Schema-tolerant node/edge extraction."""
107
+ nodes = graph.get("nodes") or graph.get("vertices") or []
108
+ edges = graph.get("edges") or graph.get("links") or []
109
+ return nodes, edges
110
+
111
+
112
+ def _first_present(d: dict, keys: tuple[str, ...]) -> Any:
113
+ """First value among ``keys`` that is present and non-empty.
114
+
115
+ Key-presence based, NOT an ``or``-chain: a falsy-but-valid value (integer id
116
+ ``0`` in a networkx node-link export) must win, not fall through to the next
117
+ key or a ``"?"`` placeholder.
118
+ """
119
+ for k in keys:
120
+ v = d.get(k)
121
+ if v is not None and v != "":
122
+ return v
123
+ return None
124
+
125
+
126
+ def _node_id(n: dict) -> str:
127
+ v = _first_present(n, ("id", "name", "label"))
128
+ return "?" if v is None else str(v)
129
+
130
+
131
+ def _node_label(n: dict) -> str:
132
+ v = _first_present(n, ("label", "name", "id"))
133
+ return "?" if v is None else str(v)
134
+
135
+
136
+ def _node_line(n: dict) -> Any:
137
+ """Source line across schema variants.
138
+
139
+ graphify stores the line as ``source_location`` like ``"L295"`` (or a range
140
+ ``"L295-L312"``); other graph schemas use line/lineno/start_line.
141
+ """
142
+ for k in ("line", "lineno", "start_line"):
143
+ v = n.get(k)
144
+ if v not in (None, ""):
145
+ return v
146
+ digits = ""
147
+ for ch in str(n.get("source_location") or "").lstrip("Ll"):
148
+ if ch.isdigit():
149
+ digits += ch
150
+ else:
151
+ break
152
+ return int(digits) if digits else ""
153
+
154
+
155
+ def _node_file(n: dict) -> str:
156
+ """Source file of a node across schema variants (file / path / source_file).
157
+
158
+ Empty string when the node carries no source file (external-source / concept
159
+ nodes), so callers can skip nodes that don't correspond to a file on disk.
160
+ """
161
+ v = _first_present(n, ("file", "path", "source_file"))
162
+ return "" if v is None else str(v)
163
+
164
+
165
+ def _edge_ends(e: dict) -> tuple[str, str]:
166
+ s = _first_present(e, ("source", "from", "src"))
167
+ t = _first_present(e, ("target", "to", "dst"))
168
+ return ("?" if s is None else str(s), "?" if t is None else str(t))
169
+
170
+
171
+ def _edge_rel(e: dict) -> str:
172
+ v = _first_present(e, ("relation", "label", "type"))
173
+ return "->" if v is None else str(v)
174
+
175
+
176
+ def _node_type(n: dict) -> str:
177
+ """What kind of thing a node is: ``type`` where the schema has it, else
178
+ graphify >= 0.9's ``file_type`` (code / document / concept / rationale)."""
179
+ v = n.get("type") or n.get("file_type")
180
+ return "" if v is None else str(v)
181
+
182
+
183
+ def _bare_name(label: str) -> str:
184
+ """``.dump()`` -> ``dump``, ``helper()`` -> ``helper``, ``TableSchema`` -> itself.
185
+
186
+ A scope written with ``::`` (Ruby ``Faraday::Utils::Headers``, C++ / PHP
187
+ ``Session::SetOption()``) is dropped like a dotted one. Only the part before a
188
+ ``<`` is cut, so type arguments (``Callback<a.B>``) and ``operator<<`` survive.
189
+ """
190
+ name = label.strip()
191
+ if name.endswith("()"):
192
+ name = name[:-2]
193
+ head, lt, tail = name.lstrip(".").partition("<")
194
+ if not head: # `<anonymous>`, `<init>`: nothing to cut
195
+ return name.lstrip(".")
196
+ return head.replace("::", ".").rsplit(".", 1)[-1] + lt + tail
197
+
198
+
199
+ def _is_surprise_edge(e: dict) -> bool:
200
+ """A genuinely flagged surprise edge.
201
+
202
+ Note: an "inferred" confidence (graphify's EXTRACTED/INFERRED/AMBIGUOUS) is
203
+ NOT a surprise — only an explicit surprise flag or type counts. Used by both
204
+ graphlore_overview and graphlore_surprises so they agree on one definition.
205
+ """
206
+ return bool(
207
+ e.get("surprise")
208
+ or e.get("is_surprise")
209
+ or str(e.get("type", "")).lower() == "surprise"
210
+ )
211
+
212
+
213
+ # --- shared state ------------------------------------------------------------
214
+
215
+
216
+ # How far a call path between two definitions sharing state is looked for.
217
+ _CALL_PATH_HOPS = 6
218
+ # Pairs listed per shared state row.
219
+ _SHARED_PAIRS_LIMIT = 10
220
+
221
+
222
+ def _in_test_code(n: dict) -> bool:
223
+ """A node of a test file, or one the native engine marked as test code
224
+ inside a source file (`test`: a Rust `#[cfg(test)]` module)."""
225
+ f = _node_file(n)
226
+ return n.get("test") is True or (bool(f) and _is_test_path(f))
227
+
228
+
229
+ def _engine_pairs(state: dict) -> dict[frozenset[str], tuple[str, int | None]]:
230
+ """The pairs the native engine listed on a state node (`coupling.listed`,
231
+ rows of `[writer, other, hops, forward]`): pair -> (the end its call path
232
+ starts at, hops), hops None for a hidden pair. Empty when the node carries
233
+ none, and a pair missing from a cut list is simply not answered."""
234
+ coupling = state.get("coupling")
235
+ rows = coupling.get("listed") if isinstance(coupling, dict) else None
236
+ out: dict[frozenset[str], tuple[str, int | None]] = {}
237
+ for row in rows if isinstance(rows, list) else []:
238
+ if not (isinstance(row, list) and len(row) == 4):
239
+ continue
240
+ writer, other, n, forward = row
241
+ if isinstance(writer, str) and isinstance(other, str):
242
+ hidden = not isinstance(n, int) or isinstance(n, bool)
243
+ out[frozenset((writer, other))] = (
244
+ writer if forward or hidden else other, None if hidden else n)
245
+ return out
246
+
247
+
248
+ def _shared_state(
249
+ nodes: list[dict], edges: list[dict], labels: Any = None,
250
+ call_edges: list[dict] | None = None,
251
+ coupled: Callable[[str, str], tuple[int, float] | None] | None = None,
252
+ ) -> list[dict]:
253
+ """Variables, fields and resources that code in one file writes and code in
254
+ another file reads or writes: implicit coupling, strongest first.
255
+
256
+ Each pair of a writer and another definition touching the state says
257
+ whether a call path joins them (`call_path`, either way, over calls,
258
+ dispatch and HTTP, within 6 hops) and whether their files change together.
259
+ The call path is the native engine's answer where the state node carries
260
+ one (`coupling.listed`, schema 6 on); otherwise it is looked for here, on
261
+ `call_edges` — the graph's edges by default. `co_change` comes from
262
+ `coupled(file_a, file_b)`, the git history). A score per state node: +2 when
263
+ some pair has no call path between them (a hidden pair), +2 when the
264
+ touching files sit in different top-level directories, +1 when they are in
265
+ different communities, +2 when the files of a hidden pair change together.
266
+ Test code is left out (a test setting a global is how tests work) unless
267
+ the state itself is test code.
268
+ """
269
+ byid = {_node_id(n): n for n in nodes}
270
+ name = (lambda i: labels.get(i, i)) if labels is not None else (
271
+ lambda i: _node_label(byid[i]) if i in byid else i)
272
+ readers: dict[str, set[str]] = {}
273
+ writers: dict[str, set[str]] = {}
274
+ for e in edges:
275
+ rel = _rel(e)
276
+ if rel not in _STATE_RELATIONS:
277
+ continue
278
+ s, t = _edge_ends(e)
279
+ (writers if rel == "writes" else readers).setdefault(t, set()).add(s)
280
+ call_rels = _CALL_RELATIONS | {"dispatches_to"} | _HTTP_RELATIONS
281
+ adj: _Adj | None = None
282
+ reach: dict[str, dict[str, int]] = {}
283
+
284
+ def hops(a: str, b: str) -> int | None:
285
+ nonlocal adj
286
+ if adj is None: # built on the first pair the graph does not answer
287
+ adj = _relation_adjacency(
288
+ call_edges if call_edges is not None else edges, call_rels)
289
+ if a not in reach:
290
+ reach[a] = _hop_distances(adj, a, _CALL_PATH_HOPS)
291
+ return reach[a].get(b)
292
+
293
+ def call_path(w: str, o: str, known: dict[frozenset[str], Any]) -> dict | None:
294
+ """How a call path joins the two, or None for a hidden pair."""
295
+ got = known.get(frozenset((w, o)))
296
+ if got is not None:
297
+ start, n = got
298
+ return None if n is None else {
299
+ "direction": "a→b" if start == w else "b→a", "hops": n}
300
+ ab, ba = hops(w, o), hops(o, w)
301
+ return ({"direction": "a→b", "hops": ab} if ab is not None
302
+ else {"direction": "b→a", "hops": ba} if ba is not None else None)
303
+
304
+ out: list[dict] = []
305
+ for sid, ws in writers.items():
306
+ state = byid.get(sid)
307
+ if state is None:
308
+ continue
309
+ test_state = _in_test_code(state)
310
+
311
+ def keep(i: str, test_state: bool = test_state) -> bool:
312
+ n = byid.get(i)
313
+ return n is not None and bool(_node_file(n)) and (
314
+ test_state or not _in_test_code(n))
315
+
316
+ ws_kept = sorted(i for i in ws if keep(i))
317
+ rs_kept = sorted(i for i in readers.get(sid, set()) - ws if keep(i))
318
+ touch = ws_kept + rs_kept
319
+ if not ws_kept or len(touch) < 2:
320
+ continue
321
+ file_of = {i: _node_file(byid[i]) for i in touch}
322
+ files = sorted(set(file_of.values()))
323
+ if len(files) < 2:
324
+ continue
325
+ why: list[str] = []
326
+ score = 1
327
+ file_pairs = [(file_of[w], file_of[o]) for w in ws_kept for o in touch
328
+ if file_of[o] != file_of[w]]
329
+ pairs: list[dict] = []
330
+ seen: set[frozenset[str]] = set()
331
+ known = _engine_pairs(state)
332
+ for w in ws_kept:
333
+ for o in touch:
334
+ if o == w or frozenset((w, o)) in seen:
335
+ continue
336
+ seen.add(frozenset((w, o)))
337
+ path = call_path(w, o, known)
338
+ cc = (coupled(file_of[w], file_of[o])
339
+ if coupled is not None and file_of[w] != file_of[o] else None)
340
+ pairs.append({
341
+ "writer": name(w), "other": name(o),
342
+ "effect": "both write it" if o in ws else "the other reads what it writes",
343
+ "call_path": path,
344
+ "co_change": {"commits": cc[0], "degree": round(cc[1], 2)} if cc else None,
345
+ })
346
+ hidden = [p for p in pairs if p["call_path"] is None]
347
+ co_hidden = [p for p in hidden if p["co_change"]]
348
+ if hidden:
349
+ score += 2
350
+ why.append(f"{len(hidden)} of {len(pairs)} pair(s) share it with no call "
351
+ "path between them")
352
+ elif pairs:
353
+ why.append("every pair is joined by a call path as well")
354
+ if any(_top_dir(a) != _top_dir(b) for a, b in file_pairs):
355
+ score += 2
356
+ why.append("crosses top-level directories")
357
+ comm = {i: byid[i].get("community", byid[i].get("cluster")) for i in touch}
358
+ if len({c for c in comm.values() if c is not None}) > 1:
359
+ score += 1
360
+ why.append("touched from more than one community")
361
+ if co_hidden:
362
+ score += 2
363
+ why.append(f"{len(co_hidden)} hidden pair(s) whose files change together")
364
+ pairs.sort(key=lambda p: (p["call_path"] is not None, p["co_change"] is None))
365
+ row_pairs = pairs[:_SHARED_PAIRS_LIMIT]
366
+ extra: dict[str, Any] = {}
367
+ if len(pairs) > len(row_pairs):
368
+ extra["pairs_left_out"] = len(pairs) - len(row_pairs)
369
+ out.append({
370
+ "state": name(sid),
371
+ "kind": str(state.get("kind") or state.get("resource") or _node_type(state) or ""),
372
+ "file": _node_file(state) or None,
373
+ "writers": [name(i) for i in ws_kept],
374
+ "readers": [name(i) for i in rs_kept],
375
+ "files": len(files),
376
+ "score": score,
377
+ "strength": "strong" if score >= 5 else "medium" if score >= 3 else "weak",
378
+ "why": why,
379
+ "pairs": row_pairs,
380
+ "hidden_pairs": len(hidden),
381
+ "co_changing_pairs": len(co_hidden),
382
+ **extra,
383
+ })
384
+ out.sort(key=lambda r: (-r["score"], -r["files"], -len(r["writers"]), r["state"]))
385
+ return out
386
+
387
+
388
+ # --- computed surprises -----------------------------------------------------
389
+ # A graph built by local AST extraction carries no surprise flag and often no
390
+ # community info, so the flag check above returns nothing on it. Rather than
391
+ # reporting an empty list (which reads as "this codebase has no surprising
392
+ # couplings" when it means "this tool computed nothing"), score the edges.
393
+
394
+ # Relation vocabularies shared by the analysis tools (cycles, layers, unreferenced,
395
+ # same-names, surprises). Compared against ``_edge_rel(e).strip().lower()``.
396
+ _IMPORT_RELATIONS = frozenset({
397
+ "imports", "imports_from", "dynamic_import", "re_exports", "requires",
398
+ })
399
+ _CALL_RELATIONS = frozenset({"calls", "indirect_call"})
400
+ # Parent -> member. graphify >= 0.9 also writes `defines` (a class's field, a
401
+ # script's function) and `case_of` (an enum's case).
402
+ _CONTAINMENT_RELATIONS = frozenset({"contains", "method", "defines", "case_of"})
403
+ # A pair of definitions that share state with no call path between them (the
404
+ # native engine, schema 6 on): `couples_with` from the definition that sees the
405
+ # state to the one that writes it. Derived from the `reads` / `writes` edges,
406
+ # which stay in the graph, so it is never counted as a dependency of its own.
407
+ _COUPLING_RELATIONS = frozenset({"couples_with"})
408
+ # A document naming code (the native engine, schema 7 on): `documents` from the
409
+ # heading a Markdown or reStructuredText document names it under to the one
410
+ # definition the name means. The document describes the code; it is no part of it.
411
+ _DOCUMENT_RELATIONS = frozenset({"documents"})
412
+ # Edges that say nothing about one piece of code depending on another: structural
413
+ # containment, a docstring/comment node or a document pointing at the code it
414
+ # describes, and the pairs derived from shared state.
415
+ _NON_DEPENDENCY_RELATIONS = (
416
+ _CONTAINMENT_RELATIONS | {"rationale_for"} | _DOCUMENT_RELATIONS | _COUPLING_RELATIONS
417
+ )
418
+ # A definition reading or writing a variable, a field, a constant or a resource
419
+ # (the native engine). Two definitions touching one such node affect each other
420
+ # without either calling the other: shared state.
421
+ _STATE_RELATIONS = frozenset({"reads", "writes"})
422
+ # A web route and the code on either side of it (the native engine): `handles`
423
+ # from a route node to its handler, `http_calls` from a client's definition to
424
+ # the route its request reaches. Each is a real dependency across the wire.
425
+ _HTTP_RELATIONS = frozenset({"handles", "http_calls"})
426
+ # Node kinds that hold state (the native engine's `kind`).
427
+ _STATE_KINDS = frozenset({"variable", "property", "constant"})
428
+
429
+
430
+ def _is_state_node(n: dict) -> bool:
431
+ """A variable, field or constant, or a resource node (env, file, table, …)."""
432
+ return str(n.get("kind", "")).lower() in _STATE_KINDS or _is_resource_node(n)
433
+
434
+
435
+ def _is_resource_node(n: dict) -> bool:
436
+ """Something outside the program's memory that code reads or writes: an
437
+ environment variable, a file, a table, an event (`type: resource`)."""
438
+ return str(n.get("type", "")).lower() == "resource"
439
+
440
+
441
+ def _is_route_node(n: dict) -> bool:
442
+ """A web route the native engine found (`type: route`): its method, full
443
+ pattern and framework, at the line that registers it."""
444
+ return str(n.get("type", "")).lower() == "route"
445
+
446
+
447
+ _SHARED_STATE_CACHE: dict[int, tuple[list[dict], list[dict]]] = {}
448
+
449
+
450
+ def _with_written_by(edges: list[dict]) -> list[dict]:
451
+ """``edges`` plus, for each ``writes`` edge W → R, a ``written_by`` edge
452
+ R → W, so a walk can go from a writer through what it writes to its
453
+ readers. Cached on the identity of ``edges``, like the adjacency."""
454
+ cached = _SHARED_STATE_CACHE.get(id(edges))
455
+ if cached is not None and cached[0] is edges:
456
+ return cached[1]
457
+ out = list(edges)
458
+ for e in edges:
459
+ if _rel(e) == "writes":
460
+ s, t = _edge_ends(e)
461
+ v = {k: e[k] for k in ("confidence", "source_file", "source_location") if k in e}
462
+ out.append({"source": t, "target": s, "relation": "written_by",
463
+ "context": "shared_state", **v})
464
+ if len(_SHARED_STATE_CACHE) >= 4:
465
+ _SHARED_STATE_CACHE.pop(next(iter(_SHARED_STATE_CACHE)), None)
466
+ _SHARED_STATE_CACHE[id(edges)] = (edges, out)
467
+ return out
468
+ _FILE_KEYS = ("file", "path", "source_file")
469
+
470
+
471
+ def _rel(e: dict) -> str:
472
+ """Normalized relation name of an edge (lower-case, stripped)."""
473
+ return _edge_rel(e).strip().lower()
474
+
475
+
476
+ def _is_external_node(n: dict) -> bool:
477
+ """A node standing for code outside the repository.
478
+
479
+ Either explicitly marked (graphify >= 0.9: ``type: "external"`` on imported
480
+ packages such as ``json``/``pytest``), or carrying a source-file key that is
481
+ present but EMPTY — how graphify records a name it could not resolve to a
482
+ file (``Protocol``, a decorator's ``get``, gettext's ``_``). A node with no
483
+ file key at all is not treated as external: that is a schema without file
484
+ info, not an unresolved reference.
485
+ """
486
+ if n.get("external") is True or str(n.get("type", "")).lower() == "external":
487
+ return True
488
+ if _node_file(n):
489
+ return False
490
+ return any(k in n for k in _FILE_KEYS)
491
+
492
+
493
+ # Containment/import scaffolding: structurally expected, never surprising.
494
+ _SURPRISE_STRUCTURAL_RELS = _CONTAINMENT_RELATIONS | {"imports", "imports_from"}
495
+ # Inferred edges of these kinds claim "this code refers to that code"; a resolver
496
+ # that matched on the bare name leaves one with no import to back it.
497
+ _SURPRISE_NAME_RESOLVED_RELS = frozenset({
498
+ "calls", "indirect_call", "uses", "references", "inherits", "extends", "implements",
499
+ })
500
+ # A package's entry file: importing it reaches the modules next to it.
501
+ _PACKAGE_ENTRY_STEMS = frozenset({"__init__", "index", "mod"})
502
+ _LANG_FAMILY = {
503
+ ".py": "python", ".pyi": "python",
504
+ ".js": "js", ".jsx": "js", ".mjs": "js", ".cjs": "js",
505
+ ".ts": "js", ".tsx": "js", ".mts": "js", ".cts": "js",
506
+ ".go": "go", ".rs": "rust",
507
+ ".java": "jvm", ".kt": "jvm", ".kts": "jvm", ".scala": "jvm",
508
+ ".rb": "ruby", ".php": "php", ".cs": "dotnet", ".swift": "swift",
509
+ ".c": "c", ".h": "c", ".cc": "c", ".cpp": "c", ".hpp": "c", ".cxx": "c", ".hxx": "c",
510
+ ".m": "objc", ".mm": "objc", ".lua": "lua", ".zig": "zig",
511
+ ".ex": "elixir", ".exs": "elixir",
512
+ }
513
+ _TEST_DIR_PARTS = frozenset({"test", "tests", "spec", "specs", "__tests__", "testing", "e2e"})
514
+ # A camelCase or dotted name that ends in Test(s): Gradle source sets
515
+ # (`jvmTest`, `androidTest`), .NET projects (`Foo.Tests`, `Foo.Tests.Xml`) and the
516
+ # file convention of the JVM, .NET, PHP and Swift (`OwnerControllerTests`).
517
+ # `Spec` is left out: it is a production suffix too (`TypeSpec`, `FunSpec`).
518
+ _TEST_NAME = re.compile(r"[a-z0-9.](?:Tests?|TestCase)(?:$|\.)")
519
+
520
+
521
+ def _lang_family(path: str) -> str | None:
522
+ dot = path.rfind(".")
523
+ return _LANG_FAMILY.get(path[dot:].lower()) if dot > 0 else None
524
+
525
+
526
+ def _is_test_path(path: str) -> bool:
527
+ parts = path.split("/")
528
+ if any(p.lower() in _TEST_DIR_PARTS or _TEST_NAME.search(p) for p in parts[:-1]):
529
+ return True
530
+ stem = parts[-1].rsplit(".", 1)[0]
531
+ low = stem.lower()
532
+ return (
533
+ low.startswith("test_") or low == "conftest"
534
+ or low.endswith(("_test", "_tests", ".test", ".spec", "_spec"))
535
+ or bool(_TEST_NAME.search(stem))
536
+ )
537
+
538
+
539
+ def _top_dir(path: str) -> str:
540
+ """First path component of a project-relative file ("." for a root-level file)."""
541
+ head, sep, _ = path.partition("/")
542
+ return head if sep else "."
543
+
544
+
545
+ # From this many edges on, two directories are joined by a dependency, not by a
546
+ # surprise: an inbound adapter using the application layer in dozens of places is
547
+ # the architecture, not a finding.
548
+ _ESTABLISHED_PAIR_EDGES = 10
549
+
550
+
551
+ def _diverging(a: str, b: str) -> tuple[str, str]:
552
+ """Where two file paths part ways: ``pkg/adapters/cli/x.py`` and
553
+ ``pkg/application/svc/y.py`` -> (``pkg/adapters``, ``pkg/application``).
554
+ Two files in one directory diverge at the files themselves."""
555
+ pa, pb = a.split("/"), b.split("/")
556
+ common = 0
557
+ for x, y in zip(pa[:-1], pb[:-1], strict=False):
558
+ if x != y:
559
+ break
560
+ common += 1
561
+ return "/".join(pa[: common + 1]), "/".join(pb[: common + 1])
562
+
563
+
564
+ def _is_package_entry_of(entry: str, member: str) -> bool:
565
+ """True if ``entry`` is the entry file (``__init__.py``, ``index.ts``, ``mod.rs``)
566
+ of a package directory that contains ``member``."""
567
+ d, _, name = entry.rpartition("/")
568
+ if name.rsplit(".", 1)[0] not in _PACKAGE_ENTRY_STEMS:
569
+ return False
570
+ return not d or member.startswith(d + "/")
571
+
572
+
573
+ def _dir_distance(a: str, b: str) -> tuple[int, bool]:
574
+ """(tree distance between the two dirnames, do their top-level dirs differ)."""
575
+ da, db = a.split("/")[:-1], b.split("/")[:-1]
576
+ common = 0
577
+ for x, y in zip(da, db, strict=False):
578
+ if x != y:
579
+ break
580
+ common += 1
581
+ return (len(da) - common) + (len(db) - common), da[:1] != db[:1]
582
+
583
+
584
+ def _is_file_hub_node(n: dict) -> bool:
585
+ """A node standing for a whole file.
586
+
587
+ Its label is the file's basename, or a trailing part of its path: graphify
588
+ >= 0.9 labels package entry files ``pkg/__init__.py`` so they can be told apart.
589
+ """
590
+ f = _node_file(n)
591
+ if not f:
592
+ return False
593
+ label = _node_label(n)
594
+ return label == f.rsplit("/", 1)[-1] or f == label or f.endswith("/" + label)
595
+
596
+
597
+ # When the import behind an edge runs (see graphlore.imports, which reads it from
598
+ # the source). Unclassified = the source could not be read as Python; such an
599
+ # import is assumed to run at import time.
600
+ IMPORT_MODULE_LEVEL = "module-level"
601
+ IMPORT_DEFERRED = "deferred" # inside a function body
602
+ IMPORT_TYPE_CHECKING = "type-checking" # under `if TYPE_CHECKING:`
603
+ IMPORT_UNCLASSIFIED = "unclassified"
604
+ # The values an edge's `runs` field may carry (native engine): every kind but
605
+ # unclassified.
606
+ _IMPORT_RUNS = frozenset({IMPORT_MODULE_LEVEL, IMPORT_DEFERRED, IMPORT_TYPE_CHECKING})
607
+ _IMPORT_RUNS_AT_IMPORT = frozenset({IMPORT_MODULE_LEVEL, IMPORT_UNCLASSIFIED})
608
+ # (importing file, imported file, edge) -> one of the kinds above, or None when
609
+ # the import statement cannot mean that file at all (the resolver matched a name).
610
+ ImportKind = Callable[[str, str, dict], "str | None"]
611
+
612
+
613
+ def _file_import_edges(
614
+ nodes: list[dict], edges: list[dict], kind_of: ImportKind | None = None
615
+ ) -> list[tuple[str, str, dict, dict, str]]:
616
+ """Import edges lifted to file level:
617
+ ``(source file, target file, edge, target node, import kind)``.
618
+
619
+ graphify records an import as file -> file (``imports_from``) or as file ->
620
+ imported symbol (``imports``); both say "this module imports that module".
621
+ Edges with an endpoint outside the repository (no source file) and imports
622
+ within one file are dropped. With ``kind_of`` (an
623
+ :class:`graphlore.imports.ImportChecker`'s ``kind``), an edge the source
624
+ contradicts is dropped too and the rest carry when their import runs; without
625
+ it every edge is ``IMPORT_UNCLASSIFIED``.
626
+ """
627
+ byid = {_node_id(n): n for n in nodes}
628
+ out: list[tuple[str, str, dict, dict, str]] = []
629
+ for e in edges:
630
+ if _rel(e) not in _IMPORT_RELATIONS:
631
+ continue
632
+ sid, tid = _edge_ends(e)
633
+ src, dst = byid.get(sid), byid.get(tid)
634
+ if src is None or dst is None:
635
+ continue
636
+ sf, tf = _node_file(src), _node_file(dst)
637
+ if not (sf and tf) or sf == tf:
638
+ continue
639
+ if kind_of is not None:
640
+ kind = kind_of(sf, tf, e)
641
+ else:
642
+ # an extractor that read the statement says when it runs
643
+ carried = e.get("runs")
644
+ kind = carried if carried in _IMPORT_RUNS else IMPORT_UNCLASSIFIED
645
+ if kind is None:
646
+ continue
647
+ if kind == IMPORT_UNCLASSIFIED and kind_of is not None and not _is_file_hub_node(src) \
648
+ and _node_label(src).endswith("()"):
649
+ # The source could not be read, but the graph recorded this import
650
+ # on a function rather than on its file: it runs when that is called.
651
+ kind = IMPORT_DEFERRED
652
+ out.append((sf, tf, e, dst, kind))
653
+ return out
654
+
655
+
656
+ def _computed_surprises(
657
+ nodes: list[dict], edges: list[dict], import_kind: ImportKind | None = None,
658
+ reaches: Callable[[str, str], bool | None] | None = None,
659
+ ) -> tuple[list[dict], dict[str, Any]]:
660
+ """Score cross-file edges for "surprisingness" when the graph carries no flag.
661
+
662
+ Returns (ranked candidates, diagnostics). Diagnostics name *why* edges were
663
+ skipped and which signals the graph lacks, so a caller can distinguish
664
+ "nothing surprising here" from "nothing computable here" — the distinction
665
+ the flag-only check silently collapsed.
666
+
667
+ One O(N+E) pass plus a sort of the survivors; no betweenness, so it stays
668
+ usable on large graphs. ``reaches(importer, imported)`` (``ImportChecker.
669
+ reaches``) answers from the source for a file whose imports the graph did not
670
+ record: False means none of its import statements can mean that file.
671
+ """
672
+ byid = {_node_id(n): n for n in nodes}
673
+ degree: dict[str, int] = {}
674
+ for e in edges:
675
+ s, t = _edge_ends(e)
676
+ degree[s] = degree.get(s, 0) + 1
677
+ degree[t] = degree.get(t, 0) + 1
678
+ comm = {nid: n.get("community", n.get("cluster")) for nid, n in byid.items()}
679
+ has_comm = any(c is not None for c in comm.values())
680
+ ranked_deg = sorted(degree.values())
681
+ # Reaching the graph's biggest hub is the least surprising thing in it, so
682
+ # the peripheral->hub bonus stops applying at the god-node cut.
683
+ god_cut = max(20, ranked_deg[int(len(ranked_deg) * 0.99)] if ranked_deg else 20)
684
+
685
+ # Which files import which, and which top-level directories other directories
686
+ # depend on. Both come from the graph's own edges, so a graph without import
687
+ # edges (or with a single directory) simply leaves the two checks off.
688
+ file_imports: dict[str, set[str]] = {}
689
+ has_imports: set[str] = set()
690
+ for e in edges:
691
+ if _rel(e) in _IMPORT_RELATIONS:
692
+ src = byid.get(_edge_ends(e)[0])
693
+ if src is not None and _node_file(src):
694
+ has_imports.add(_node_file(src))
695
+ for sf, tf, _e, _dst, _kind in _file_import_edges(nodes, edges, import_kind):
696
+ file_imports.setdefault(sf, set()).add(tf)
697
+
698
+ def _imported(fu: str, fv: str) -> bool:
699
+ got = file_imports.get(fu, ())
700
+ return fv in got or any(_is_package_entry_of(g, fv) for g in got)
701
+
702
+ source_says: dict[tuple[str, str], bool | None] = {}
703
+
704
+ def _name_guess(e: dict, rel: str, fu: str, fv: str) -> bool:
705
+ """The resolver guessed this target, and the source file imports neither
706
+ the target's module nor its package: a same-named function in an
707
+ unrelated directory, not a coupling. Judged from the graph's import edges
708
+ when it recorded any for the file; otherwise from the file's own import
709
+ statements (``reaches``), so a file importing only the standard library —
710
+ which leaves no import edge at all — is judged too, not exempted."""
711
+ conf = str(e.get("confidence") or "EXTRACTED").upper()
712
+ if conf not in ("INFERRED", "AMBIGUOUS") or rel not in _SURPRISE_NAME_RESOLVED_RELS:
713
+ return False
714
+ if fu in has_imports:
715
+ return not _imported(fu, fv)
716
+ if reaches is None:
717
+ return False
718
+ key = (fu, fv)
719
+ if key not in source_says:
720
+ source_says[key] = reaches(fu, fv)
721
+ return source_says[key] is False
722
+
723
+ # Who depends on what, by top-level directory and by file — counted over the
724
+ # edges that can be trusted: a resolver guess from the package into a script
725
+ # must not make that script look depended upon. Test code is nobody's
726
+ # dependent here; it uses everything.
727
+ dependents_of: dict[str, set[str]] = {}
728
+ file_dependents: dict[str, set[str]] = {}
729
+ # ...and how many edges join each pair of directories. One edge between two
730
+ # parts of a codebase is a lead; dozens are a dependency someone designed.
731
+ pair_edges: dict[tuple[str, str], int] = {}
732
+ for e in edges:
733
+ rel = _rel(e)
734
+ if rel in _NON_DEPENDENCY_RELATIONS:
735
+ continue
736
+ sid, tid = _edge_ends(e)
737
+ nu, nv = byid.get(sid), byid.get(tid)
738
+ if nu is None or nv is None:
739
+ continue
740
+ fu, fv = _node_file(nu), _node_file(nv)
741
+ if not (fu and fv) or fu == fv or _is_test_path(fu) or _name_guess(e, rel, fu, fv):
742
+ continue
743
+ file_dependents.setdefault(fv, set()).add(fu)
744
+ pair_edges[_diverging(fu, fv)] = pair_edges.get(_diverging(fu, fv), 0) + 1
745
+ if _top_dir(fu) != _top_dir(fv):
746
+ dependents_of.setdefault(_top_dir(fv), set()).add(_top_dir(fu))
747
+
748
+ skipped: dict[str, int] = {}
749
+ confidences: set[str] = set()
750
+ scored: list[dict] = []
751
+
752
+ for e in edges:
753
+ rel = _rel(e)
754
+ if rel in _SURPRISE_STRUCTURAL_RELS:
755
+ skipped["structural"] = skipped.get("structural", 0) + 1
756
+ continue
757
+ sid, tid = _edge_ends(e)
758
+ nu, nv = byid.get(sid), byid.get(tid)
759
+ if nu is None or nv is None:
760
+ skipped["dangling"] = skipped.get("dangling", 0) + 1
761
+ continue
762
+ fu, fv = _node_file(nu), _node_file(nv)
763
+ if not fu or not fv:
764
+ skipped["no_source_file"] = skipped.get("no_source_file", 0) + 1
765
+ continue
766
+ if fu == fv:
767
+ skipped["same_file"] = skipped.get("same_file", 0) + 1
768
+ continue
769
+ if _is_file_hub_node(nu) or _is_file_hub_node(nv):
770
+ skipped["file_hub"] = skipped.get("file_hub", 0) + 1
771
+ continue
772
+
773
+ conf = str(e.get("confidence") or "EXTRACTED").upper()
774
+ confidences.add(conf)
775
+ if _name_guess(e, rel, fu, fv):
776
+ skipped["inferred_unimported"] = skipped.get("inferred_unimported", 0) + 1
777
+ continue
778
+ cat_u = str(nu.get("file_type") or "code").lower()
779
+ cat_v = str(nv.get("file_type") or "code").lower()
780
+ lang_u, lang_v = _lang_family(fu), _lang_family(fv)
781
+ cross_lang = bool(lang_u and lang_v and lang_u != lang_v)
782
+ # An inferred call/uses edge that also crosses a language or code<->doc
783
+ # boundary is usually the resolver guessing, not a real coupling. Both
784
+ # this and the two expected couplings below withhold the structural bonuses.
785
+ resolver_noise = conf == "INFERRED" and rel in ("calls", "uses", "indirect_call") and (
786
+ cross_lang or {cat_u, cat_v} == {"code", "document"}
787
+ )
788
+ # Test code using anything — the source under test, or shared fakes and
789
+ # fixtures in another test directory — is routine. (Non-test code that
790
+ # depends on test code is not, and keeps its bonuses.)
791
+ from_test = _is_test_path(fu)
792
+ # A directory nothing depends on (bench/, demo/, examples/), or a script
793
+ # nothing depends on (docker/smoke/make_catalog.py), using a directory
794
+ # that several others depend on is what it is there for.
795
+ top_u, top_v = _top_dir(fu), _top_dir(fv)
796
+ consumer_edge = (
797
+ top_u != top_v and len(dependents_of.get(top_v, ())) >= 2
798
+ and (not dependents_of.get(top_u) or not file_dependents.get(fu))
799
+ )
800
+ pair = _diverging(fu, fv)
801
+ established = pair_edges.get(pair, 0) >= _ESTABLISHED_PAIR_EDGES
802
+ suppress = resolver_noise or from_test or consumer_edge or established
803
+ # An inferred edge into a module the source file imports is resolved by
804
+ # that import, not guessed: it scores like an extracted one.
805
+ guessed = (
806
+ conf in ("AMBIGUOUS", "INFERRED")
807
+ and not (rel in _SURPRISE_NAME_RESOLVED_RELS and _imported(fu, fv))
808
+ )
809
+
810
+ score = 0
811
+ why: list[str] = []
812
+ if not resolver_noise:
813
+ score += {"AMBIGUOUS": 3, "INFERRED": 2}.get(conf, 1) if guessed else 1
814
+ if guessed:
815
+ why.append(f"{conf.lower()} link — the resolver guessed this target")
816
+ if not suppress:
817
+ if cat_u != cat_v:
818
+ score += 2
819
+ why.append(f"crosses file types ({cat_u} ↔ {cat_v})")
820
+ dist, cross_top = _dir_distance(fu, fv)
821
+ if cross_top:
822
+ score += 2
823
+ why.append("crosses top-level directories")
824
+ elif dist >= 2:
825
+ score += 1
826
+ why.append("distant directories")
827
+ if has_comm and comm.get(sid) is not None and comm.get(tid) is not None \
828
+ and comm[sid] != comm[tid]:
829
+ score += 1
830
+ why.append(f"bridges community {comm[sid]} → {comm[tid]}")
831
+ du, dv = degree.get(sid, 0), degree.get(tid, 0)
832
+ if min(du, dv) <= 2 and 5 <= max(du, dv) < god_cut:
833
+ score += 1
834
+ why.append("peripheral node reaches a well-connected node")
835
+ if rel == "semantically_similar_to":
836
+ score = int(score * 1.5)
837
+ if from_test:
838
+ why.append("(from test code: routine coupling, structural bonuses withheld)")
839
+ elif consumer_edge:
840
+ what = f"{top_u}/" if not dependents_of.get(top_u) else fu
841
+ why.append(
842
+ f"({what} only consumes {top_v}/: expected coupling, "
843
+ "structural bonuses withheld)"
844
+ )
845
+ elif established:
846
+ why.append(
847
+ f"({pair_edges[pair]} edges join {pair[0]} and {pair[1]}: an established "
848
+ "dependency, structural bonuses withheld)"
849
+ )
850
+
851
+ scored.append({
852
+ "from": _node_label(nu), "to": _node_label(nv), "relation": _edge_rel(e),
853
+ "from_file": fu, "to_file": fv, "score": score,
854
+ "strength": "strong" if score >= 5 else ("moderate" if score >= 3 else "weak"),
855
+ "why": why,
856
+ })
857
+
858
+ scored.sort(key=lambda c: (-c["score"], c["from_file"], c["to_file"]))
859
+ seen_pairs: set[tuple[str, str, str]] = set()
860
+ per_target: dict[str, int] = {}
861
+ items: list[dict] = []
862
+ for c in scored:
863
+ key = (c["from_file"], c["to_file"], c["relation"])
864
+ if key in seen_pairs or per_target.get(c["to"], 0) >= 2:
865
+ continue # one row per file pair+relation, and no target may dominate
866
+ seen_pairs.add(key)
867
+ per_target[c["to"]] = per_target.get(c["to"], 0) + 1
868
+ items.append(c)
869
+
870
+ diagnostics = {
871
+ "scorable_edges": len(scored),
872
+ "skipped": skipped,
873
+ "has_community_info": has_comm,
874
+ "confidence_values": sorted(confidences),
875
+ "max_score": max((c["score"] for c in items), default=0),
876
+ }
877
+ return items, diagnostics
878
+
879
+
880
+ # Exact id/label -> node index, keyed by id(nodes) with an identity guard (same
881
+ # scheme as _ADJ_CACHE below). _resolve_node runs once per requested node in
882
+ # graphlore_fetch and once per call in most node-centric tools, so the exact
883
+ # pass — the overwhelmingly common case — should not rescan all N nodes.
884
+ _RESOLVE_CACHE: dict[int, tuple[list[dict], dict[str, dict]]] = {}
885
+ _RESOLVE_CACHE_MAX = 8
886
+
887
+
888
+ def _exact_node_index(nodes: list[dict]) -> dict[str, dict]:
889
+ cached = _RESOLVE_CACHE.get(id(nodes))
890
+ if cached is not None and cached[0] is nodes:
891
+ return cached[1]
892
+ index: dict[str, dict] = {}
893
+ # setdefault in list order preserves the linear scan's first-match winner
894
+ # even when one node's label collides with a later node's id.
895
+ for n in nodes:
896
+ index.setdefault(_node_id(n), n)
897
+ index.setdefault(_node_label(n), n)
898
+ if id(nodes) not in _RESOLVE_CACHE and len(_RESOLVE_CACHE) >= _RESOLVE_CACHE_MAX:
899
+ _RESOLVE_CACHE.pop(next(iter(_RESOLVE_CACHE)), None) # FIFO
900
+ _RESOLVE_CACHE[id(nodes)] = (nodes, index)
901
+ return index
902
+
903
+
904
+ class _NameIndex:
905
+ """Label -> nodes and bare name -> nodes, each list in graph order.
906
+
907
+ ``bare`` leaves file hub nodes out (a file is named by its path, not by a
908
+ symbol name). ``pool`` maps each lowercased bare name to its first node, the
909
+ candidate set for "did you mean" suggestions.
910
+ """
911
+
912
+ __slots__ = ("labels", "bare", "pos", "pool")
913
+
914
+ def __init__(self, nodes: list[dict]) -> None:
915
+ self.labels: dict[str, list[dict]] = {}
916
+ self.bare: dict[str, list[dict]] = {}
917
+ self.pos: dict[int, int] = {}
918
+ self.pool: dict[str, dict] = {}
919
+ for i, n in enumerate(nodes):
920
+ self.pos[id(n)] = i
921
+ label = _node_label(n)
922
+ self.labels.setdefault(label, []).append(n)
923
+ if not _is_file_hub_node(n):
924
+ name = _bare_name(label)
925
+ self.bare.setdefault(name, []).append(n)
926
+ if name:
927
+ self.pool.setdefault(name.lower(), n)
928
+
929
+ def by_name(self, label: str, bare: str) -> list[dict]:
930
+ """Nodes labelled ``label`` or (non-hub) with bare name ``bare``, in graph order."""
931
+ hits = {id(n): n for n in self.labels.get(label, ())}
932
+ for n in self.bare.get(bare, ()):
933
+ hits.setdefault(id(n), n)
934
+ return sorted(hits.values(), key=lambda n: self.pos[id(n)])
935
+
936
+
937
+ # Same identity-guarded FIFO scheme as _RESOLVE_CACHE.
938
+ _NAME_CACHE: dict[int, tuple[list[dict], _NameIndex]] = {}
939
+
940
+
941
+ def _name_index(nodes: list[dict]) -> _NameIndex:
942
+ cached = _NAME_CACHE.get(id(nodes))
943
+ if cached is not None and cached[0] is nodes:
944
+ return cached[1]
945
+ index = _NameIndex(nodes)
946
+ if id(nodes) not in _NAME_CACHE and len(_NAME_CACHE) >= _RESOLVE_CACHE_MAX:
947
+ _NAME_CACHE.pop(next(iter(_NAME_CACHE)), None) # FIFO
948
+ _NAME_CACHE[id(nodes)] = (nodes, index)
949
+ return index
950
+
951
+
952
+ def _substring_matches(nodes: list[dict], key: str, cap: int = 6) -> tuple[list[dict], int]:
953
+ """Nodes whose label or id contains ``key`` (case-insensitive), first ``cap`` in
954
+ graph order, and how many match in all. The first is what ``_resolve_node``
955
+ picks."""
956
+ k = key.lower()
957
+ hits: list[dict] = []
958
+ total = 0
959
+ for n in nodes:
960
+ if k in _node_label(n).lower() or k in _node_id(n).lower():
961
+ total += 1
962
+ if len(hits) < cap:
963
+ hits.append(n)
964
+ return hits, total
965
+
966
+
967
+ # Above this many distinct names, the "did you mean" pool is narrowed before
968
+ # difflib (whose cost is per candidate) runs.
969
+ _CLOSE_MATCH_POOL = 5000
970
+
971
+
972
+ def _close_matches(nodes: list[dict], key: str, n: int = 5) -> list[dict]:
973
+ """Nodes whose bare name is close to ``key`` (difflib ratio >= 0.6), best first.
974
+
975
+ For a name that matched nothing. The candidate pool is bounded on big graphs:
976
+ names of a comparable length first, then names sharing the first letter, then
977
+ graph order.
978
+ """
979
+ want = _bare_name(key).lower()
980
+ if not want:
981
+ return []
982
+ pool = _name_index(nodes).pool
983
+ names = list(pool)
984
+ if len(names) > _CLOSE_MATCH_POOL:
985
+ lo, hi = len(want) * 0.6, len(want) / 0.6
986
+ names = [s for s in names if lo <= len(s) <= hi]
987
+ if len(names) > _CLOSE_MATCH_POOL:
988
+ names = [s for s in names if s[:1] == want[:1]]
989
+ names = names[:_CLOSE_MATCH_POOL]
990
+ return [pool[s] for s in difflib.get_close_matches(want, names, n=n, cutoff=0.6)]
991
+
992
+
993
+ def _resolve_node(nodes: list[dict], key: str) -> dict | None:
994
+ """Match a node by exact id/label, else case-insensitive substring."""
995
+ exact = _exact_node_index(nodes).get(key)
996
+ if exact is not None:
997
+ return exact
998
+ k = key.lower()
999
+ for n in nodes:
1000
+ if k in _node_label(n).lower() or k in _node_id(n).lower():
1001
+ return n
1002
+ return None
1003
+
1004
+
1005
+ # node id -> list of (neighbor id, relation); the shape every traversal walks.
1006
+ _Adj = dict[str, list[tuple[str, str]]]
1007
+
1008
+
1009
+ def _build_adjacency(edges: list[dict]) -> _Adj:
1010
+ """Undirected adjacency: node -> list of (neighbor, relation)."""
1011
+ adj: dict[str, list[tuple[str, str]]] = {}
1012
+ for e in edges:
1013
+ s, t = _edge_ends(e)
1014
+ rel = _edge_rel(e)
1015
+ adj.setdefault(s, []).append((t, rel))
1016
+ adj.setdefault(t, []).append((s, rel))
1017
+ return adj
1018
+
1019
+
1020
+ # Adjacency cache keyed by id(edges) with an identity guard: if the previous edges
1021
+ # list was freed and its id recycled, the stored reference won't be `is`-identical
1022
+ # to the new list, so a stale hit is impossible. _load_graph hands back the SAME
1023
+ # edges list while the parsed graph stays cached (path+mtime), so repeat
1024
+ # subgraph/locate/neighbors calls reuse the built adjacency; a changed graph file
1025
+ # re-parses to a fresh list and misses. Bounded FIFO so old graphs don't pin memory.
1026
+ _ADJ_CACHE: dict[int, tuple[list[dict], _Adj]] = {}
1027
+ _ADJ_CACHE_MAX = 8
1028
+
1029
+
1030
+ def _adjacency(edges: list[dict]) -> _Adj:
1031
+ """Undirected adjacency for `edges`, cached on the edges-list identity.
1032
+
1033
+ Repeat traversals over an unchanged graph reuse the built adjacency instead of
1034
+ rebuilding it every call; a reload (changed file) hands a fresh list, which
1035
+ misses and rebuilds. See _ADJ_CACHE.
1036
+ """
1037
+ cached = _ADJ_CACHE.get(id(edges))
1038
+ if cached is not None and cached[0] is edges:
1039
+ return cached[1]
1040
+ adj = _build_adjacency(edges)
1041
+ if id(edges) not in _ADJ_CACHE and len(_ADJ_CACHE) >= _ADJ_CACHE_MAX:
1042
+ _ADJ_CACHE.pop(next(iter(_ADJ_CACHE)), None) # FIFO: drop the oldest entry
1043
+ _ADJ_CACHE[id(edges)] = (edges, adj)
1044
+ return adj
1045
+
1046
+
1047
+ def _build_directed_adjacency(edges: list[dict]) -> tuple[_Adj, _Adj]:
1048
+ """Directed adjacency, preserving edge orientation that _adjacency flattens away.
1049
+
1050
+ Returns (forward, reverse): ``forward[s]`` lists the targets ``s`` points at
1051
+ (what s depends on), ``reverse[t]`` lists the sources pointing at ``t`` (what
1052
+ depends on t). Reverse is the blast radius — who breaks if t changes.
1053
+ """
1054
+ forward: dict[str, list[tuple[str, str]]] = {}
1055
+ reverse: dict[str, list[tuple[str, str]]] = {}
1056
+ for e in edges:
1057
+ s, t = _edge_ends(e)
1058
+ rel = _edge_rel(e)
1059
+ forward.setdefault(s, []).append((t, rel))
1060
+ reverse.setdefault(t, []).append((s, rel))
1061
+ return forward, reverse
1062
+
1063
+
1064
+ # Same id(edges)+identity-guard scheme as _ADJ_CACHE (see there).
1065
+ _DIR_ADJ_CACHE: dict[int, tuple[list[dict], tuple[_Adj, _Adj]]] = {}
1066
+
1067
+
1068
+ def _directed_adjacency(edges: list[dict]) -> tuple[_Adj, _Adj]:
1069
+ """(forward, reverse) directed adjacency for `edges`, cached on list identity."""
1070
+ cached = _DIR_ADJ_CACHE.get(id(edges))
1071
+ if cached is not None and cached[0] is edges:
1072
+ return cached[1]
1073
+ pair = _build_directed_adjacency(edges)
1074
+ if id(edges) not in _DIR_ADJ_CACHE and len(_DIR_ADJ_CACHE) >= _ADJ_CACHE_MAX:
1075
+ _DIR_ADJ_CACHE.pop(next(iter(_DIR_ADJ_CACHE)), None) # FIFO
1076
+ _DIR_ADJ_CACHE[id(edges)] = (edges, pair)
1077
+ return pair
1078
+
1079
+
1080
+ # Same id(edges)+identity-guard scheme as _ADJ_CACHE (see there).
1081
+ _EDGE_SET_CACHE: dict[int, tuple[list[dict], set[tuple[str, str, str]]]] = {}
1082
+
1083
+
1084
+ def _edge_set(edges: list[dict]) -> set[tuple[str, str, str]]:
1085
+ """Directed ``(source, target, relation)`` triples, cached on list identity.
1086
+
1087
+ The orientation oracle for traversals over the undirected adjacency: lets
1088
+ _bfs_subgraph emit each collected edge in its TRUE direction instead of the
1089
+ (possibly reversed) direction it happened to be traversed in.
1090
+ """
1091
+ cached = _EDGE_SET_CACHE.get(id(edges))
1092
+ if cached is not None and cached[0] is edges:
1093
+ return cached[1]
1094
+ es = {(*_edge_ends(e), _edge_rel(e)) for e in edges}
1095
+ if id(edges) not in _EDGE_SET_CACHE and len(_EDGE_SET_CACHE) >= _ADJ_CACHE_MAX:
1096
+ _EDGE_SET_CACHE.pop(next(iter(_EDGE_SET_CACHE)), None) # FIFO
1097
+ _EDGE_SET_CACHE[id(edges)] = (edges, es)
1098
+ return es
1099
+
1100
+
1101
+ # Token-estimate heuristic. 4.0 chars/token is the common English rule of thumb,
1102
+ # but code — dotted identifiers, punctuation, camelCase — packs more tokens per
1103
+ # char, so we use a conservative 3.5 (≈ +14%) to avoid systematically
1104
+ # UNDER-reporting how much of a budget a subgraph consumes. The result is an
1105
+ # estimate (±~20%), not an exact tokenizer count.
1106
+ _CHARS_PER_TOKEN = 3.5
1107
+ # Fixed allowance for the JSON envelope around the edge array (the wrapper keys
1108
+ # center/hops/nodes/truncated/approx_tokens), so the budget and the reported token
1109
+ # count reflect the whole returned payload, not just the bare edge list.
1110
+ _PAYLOAD_ENVELOPE_CHARS = 96
1111
+
1112
+
1113
+ def _approx_tokens(text: str) -> int:
1114
+ """Conservative chars→tokens estimate (see ``_CHARS_PER_TOKEN``); an estimate, not exact."""
1115
+ return max(1, int(len(text) / _CHARS_PER_TOKEN))
1116
+
1117
+
1118
+ # Optional exact token counting. _TIKTOKEN_ENC: None = not yet probed, False =
1119
+ # unavailable (extra not installed), else a cached encoder.
1120
+ _TIKTOKEN_ENC: Any = None
1121
+
1122
+
1123
+ def _tiktoken_encoder() -> Any:
1124
+ global _TIKTOKEN_ENC
1125
+ if _TIKTOKEN_ENC is None and config.offline():
1126
+ # tiktoken fetches its encoding file on first use unless it is cached;
1127
+ # offline, count with the heuristic (and probe again once back online)
1128
+ return None
1129
+ if _TIKTOKEN_ENC is None:
1130
+ try:
1131
+ import tiktoken
1132
+
1133
+ _TIKTOKEN_ENC = tiktoken.get_encoding("cl100k_base")
1134
+ except Exception:
1135
+ _TIKTOKEN_ENC = False
1136
+ return _TIKTOKEN_ENC or None
1137
+
1138
+
1139
+ def _count_tokens(text: str) -> int:
1140
+ """Token count for ``text``: exact via tiktoken when ``GRAPHLORE_TOKENIZER=tiktoken``
1141
+ and the optional ``[tiktoken]`` extra is installed, else the conservative
1142
+ chars/3.5 estimate (``_approx_tokens``). Falls back silently if tiktoken is
1143
+ requested but unavailable, so it's always safe to call."""
1144
+ if config.env("TOKENIZER", "").strip().lower() == "tiktoken":
1145
+ enc = _tiktoken_encoder()
1146
+ if enc is not None:
1147
+ return max(1, len(enc.encode(text)))
1148
+ return _approx_tokens(text)
1149
+
1150
+
1151
+ _EdgeFlags = dict[tuple[str, str, str], dict[str, str]]
1152
+ _EDGE_FLAGS_CACHE: dict[int, tuple[list[dict], _EdgeFlags]] = {}
1153
+
1154
+
1155
+ def _edge_flags(edges: list[dict]) -> _EdgeFlags:
1156
+ """``(source, target, relation) -> {"confidence"?, "resolved_by"?}`` for the
1157
+ edges whose provenance is worth showing next to them: inferred or ambiguous
1158
+ ones, and ones graphlore resolved from the source. An extracted graph edge is
1159
+ the default and has no entry. Cached on list identity like _edge_set."""
1160
+ cached = _EDGE_FLAGS_CACHE.get(id(edges))
1161
+ if cached is not None and cached[0] is edges:
1162
+ return cached[1]
1163
+ flags: _EdgeFlags = {}
1164
+ for e in edges:
1165
+ f: dict[str, str] = {}
1166
+ conf = str(e.get("confidence") or "EXTRACTED").upper()
1167
+ if conf != "EXTRACTED":
1168
+ f["confidence"] = conf
1169
+ if e.get("resolved_by"):
1170
+ f["resolved_by"] = str(e["resolved_by"])
1171
+ if f:
1172
+ flags.setdefault((*_edge_ends(e), _edge_rel(e)), f)
1173
+ if id(edges) not in _EDGE_FLAGS_CACHE and len(_EDGE_FLAGS_CACHE) >= _ADJ_CACHE_MAX:
1174
+ _EDGE_FLAGS_CACHE.pop(next(iter(_EDGE_FLAGS_CACHE)), None) # FIFO
1175
+ _EDGE_FLAGS_CACHE[id(edges)] = (edges, flags)
1176
+ return flags
1177
+
1178
+
1179
+ def _flag_suffix(flags: dict[str, str] | None) -> str:
1180
+ """``, inferred`` / ``, resolved`` for a text row, as graphlore_impact prints."""
1181
+ if not flags:
1182
+ return ""
1183
+ out = ""
1184
+ if flags.get("confidence"):
1185
+ out += ", " + flags["confidence"].lower()
1186
+ if flags.get("resolved_by"):
1187
+ out += ", resolved"
1188
+ return out
1189
+
1190
+
1191
+ def _bfs_subgraph(
1192
+ adj: dict[str, list[tuple[str, str]]],
1193
+ labels: Any, # id -> display label; dict or server._DisplayLabels (duck-typed .get)
1194
+ start_id: str,
1195
+ hops: int,
1196
+ budget_tokens: int,
1197
+ edge_set: set[tuple[str, str, str]] | None = None,
1198
+ order: Callable[[tuple[str, str]], Any] | None = None,
1199
+ *,
1200
+ edge_flags: _EdgeFlags | None = None,
1201
+ also: Sequence[str] = (),
1202
+ depth_first: bool = False,
1203
+ ) -> tuple[set[str], list[dict], bool, int]:
1204
+ """BFS around start_id collecting edges until a token budget is hit.
1205
+
1206
+ Returns (visited_ids, edges, truncated, approx_tokens). Shared by
1207
+ graphlore_subgraph and graphlore_locate. ``edge_set`` (from :func:`_edge_set`)
1208
+ restores the true orientation of each collected edge: the undirected
1209
+ adjacency flattens direction, and an edge reached via its reverse entry must
1210
+ not be reported as ``B —calls→ A`` when the graph says ``A —calls→ B``.
1211
+ ``order`` is a sort key over a node's ``(neighbor, relation)`` entries: what
1212
+ comes first is what the budget keeps. ``edge_flags`` (from :func:`_edge_flags`)
1213
+ adds ``confidence`` / ``resolved_by`` to the edges that carry them.
1214
+ ``also`` are more nodes to start from (each at depth 0, after ``start_id``),
1215
+ and ``depth_first`` follows each branch to ``hops`` before the next one:
1216
+ graphlore_query's seeds and its ``dfs``.
1217
+ """
1218
+ starts = list(dict.fromkeys([start_id, *also]))
1219
+ visited = set(starts)
1220
+ frontier = deque((s, 0) for s in (reversed(starts) if depth_first else starts))
1221
+ collected_edges: list[dict] = []
1222
+ seen_pairs: set[tuple[str, ...]] = set()
1223
+ truncated = False
1224
+ running_chars = 2 + _PAYLOAD_ENVELOPE_CHARS # "[]" of the edge array + JSON envelope
1225
+
1226
+ while frontier:
1227
+ cur, depth = frontier.pop() if depth_first else frontier.popleft()
1228
+ if depth >= hops:
1229
+ continue
1230
+ neighbours = adj.get(cur, [])
1231
+ ranked = sorted(neighbours, key=order) if order else neighbours
1232
+ pushed: list[tuple[str, int]] = []
1233
+ for nb, rel in ranked:
1234
+ src, dst = cur, nb
1235
+ if (edge_set is not None and (src, dst, rel) not in edge_set
1236
+ and (dst, src, rel) in edge_set):
1237
+ src, dst = dst, src # traversed backwards: emit the true direction
1238
+ key = tuple(sorted((cur, nb)) + [rel]) # type: ignore
1239
+ if key not in seen_pairs:
1240
+ seen_pairs.add(key)
1241
+ edge = {"from": labels.get(src, src), "to": labels.get(dst, dst), "relation": rel}
1242
+ if edge_flags:
1243
+ edge.update(edge_flags.get((src, dst, rel), {}))
1244
+ collected_edges.append(edge)
1245
+ # running size estimate instead of re-serializing the whole list (O(n^2))
1246
+ running_chars += len(json.dumps(edge, ensure_ascii=False)) + 2
1247
+ if nb not in visited:
1248
+ visited.add(nb)
1249
+ pushed.append((nb, depth + 1))
1250
+ if running_chars / _CHARS_PER_TOKEN >= budget_tokens:
1251
+ truncated = True
1252
+ frontier.clear()
1253
+ pushed.clear()
1254
+ break
1255
+ # a stack pops the last pushed first: push in reverse so the best-ranked
1256
+ # neighbour is the branch followed next
1257
+ frontier.extend(reversed(pushed) if depth_first else pushed)
1258
+
1259
+ # Report the count via _count_tokens (exact under GRAPHLORE_TOKENIZER=tiktoken,
1260
+ # else the heuristic). The budget gate above stays on the fast char heuristic,
1261
+ # so the cap is approximate while the reported figure can be exact.
1262
+ serialized = json.dumps(collected_edges, ensure_ascii=False)
1263
+ envelope_tokens = _approx_tokens("x" * _PAYLOAD_ENVELOPE_CHARS)
1264
+ return visited, collected_edges, truncated, max(1, _count_tokens(serialized) + envelope_tokens)
1265
+
1266
+
1267
+ def _strongly_connected_components(forward: _Adj, node_ids: list[str]) -> list[list[str]]:
1268
+ """Tarjan's SCC, iterative (no recursion limit on deep/large graphs).
1269
+
1270
+ Each returned component is a maximal set of mutually-reachable nodes; a component
1271
+ of size >= 2 (or a single node with a self-edge) contains a cycle.
1272
+ """
1273
+ index: dict[str, int] = {}
1274
+ low: dict[str, int] = {}
1275
+ on_stack: dict[str, bool] = {}
1276
+ stack: list[str] = []
1277
+ counter = 0
1278
+ out: list[list[str]] = []
1279
+ for root in node_ids:
1280
+ if root in index:
1281
+ continue
1282
+ work: list[tuple[str, int]] = [(root, 0)]
1283
+ while work:
1284
+ v, pi = work[-1]
1285
+ if pi == 0:
1286
+ index[v] = low[v] = counter
1287
+ counter += 1
1288
+ stack.append(v)
1289
+ on_stack[v] = True
1290
+ recursed = False
1291
+ neigh = forward.get(v, [])
1292
+ j = pi
1293
+ while j < len(neigh):
1294
+ w = neigh[j][0]
1295
+ if w not in index:
1296
+ work[-1] = (v, j + 1)
1297
+ work.append((w, 0))
1298
+ recursed = True
1299
+ break
1300
+ if on_stack.get(w):
1301
+ low[v] = min(low[v], index[w])
1302
+ j += 1
1303
+ if recursed:
1304
+ continue
1305
+ if low[v] == index[v]: # v is an SCC root: pop the component
1306
+ comp: list[str] = []
1307
+ while True:
1308
+ w = stack.pop()
1309
+ on_stack[w] = False
1310
+ comp.append(w)
1311
+ if w == v:
1312
+ break
1313
+ out.append(comp)
1314
+ work.pop()
1315
+ if work: # fold v's lowlink back into its parent
1316
+ low[work[-1][0]] = min(low[work[-1][0]], low[v])
1317
+ return out
1318
+
1319
+
1320
+ def _find_cycles(forward: _Adj) -> tuple[list[list[str]], list[str]]:
1321
+ """(cycles, self_loops) from a directed adjacency.
1322
+
1323
+ ``cycles`` are SCCs of size >= 2 (mutually-dependent node groups), largest first;
1324
+ ``self_loops`` are nodes with an edge to themselves (reported separately, since a
1325
+ self-edge is a degenerate 1-node cycle).
1326
+ """
1327
+ ids: set[str] = set(forward)
1328
+ for lst in forward.values():
1329
+ for w, _ in lst:
1330
+ ids.add(w)
1331
+ self_loops = {s for s in forward for w, _ in forward[s] if w == s}
1332
+ sccs = _strongly_connected_components(forward, sorted(ids))
1333
+ cycles = sorted((c for c in sccs if len(c) >= 2), key=lambda c: (-len(c), min(c)))
1334
+ return cycles, sorted(self_loops)
1335
+
1336
+
1337
+ def _cycle_path(forward: _Adj, comp: list[str]) -> list[str]:
1338
+ """One shortest concrete route through a cycle group: ``[a, b, ..., a]``.
1339
+
1340
+ An SCC proves its members are mutually reachable; this names one actual loop
1341
+ so a reader can follow it. Starts at the smallest member for a stable result.
1342
+ """
1343
+ members = set(comp)
1344
+ start = min(comp)
1345
+ prev: dict[str, str] = {}
1346
+ queue = deque([start])
1347
+ while queue:
1348
+ cur = queue.popleft()
1349
+ for nb, _rel_name in forward.get(cur, []):
1350
+ if nb == start:
1351
+ path = [cur]
1352
+ while path[-1] != start:
1353
+ path.append(prev[path[-1]])
1354
+ path.reverse()
1355
+ return [*path, start]
1356
+ if nb in members and nb not in prev:
1357
+ prev[nb] = cur
1358
+ queue.append(nb)
1359
+ return []
1360
+
1361
+
1362
+ def _relation_adjacency(edges: list[dict], relations: frozenset[str]) -> _Adj:
1363
+ """Directed adjacency over the edges of the given relations, self-edges dropped."""
1364
+ forward: _Adj = {}
1365
+ for e in edges:
1366
+ rel = _rel(e)
1367
+ if rel not in relations:
1368
+ continue
1369
+ s, t = _edge_ends(e)
1370
+ if s != t:
1371
+ forward.setdefault(s, []).append((t, rel))
1372
+ return forward
1373
+
1374
+
1375
+ def _module_import_adjacency(
1376
+ nodes: list[dict], edges: list[dict], kind_of: ImportKind | None = None
1377
+ ) -> tuple[_Adj, int]:
1378
+ """(file -> [(imported file, import kind)], implicit-package edges ignored).
1379
+
1380
+ The second item of each adjacency entry is WHEN the import runs (see
1381
+ ``IMPORT_*``), not a relation name; several edges between two files collapse
1382
+ to the one that runs earliest.
1383
+
1384
+ A module's import of its own package's entry file is left out when the edge
1385
+ targets the file as a whole: ``from . import x`` makes graphify link the
1386
+ module to ``__init__.py``, but the parent package is always imported before
1387
+ its submodules, so that edge can never be the reason an import fails. An
1388
+ import of a *symbol* defined in ``__init__.py`` is kept.
1389
+ """
1390
+ rank = {IMPORT_MODULE_LEVEL: 0, IMPORT_UNCLASSIFIED: 1, IMPORT_DEFERRED: 2,
1391
+ IMPORT_TYPE_CHECKING: 3}
1392
+ best: dict[tuple[str, str], str] = {}
1393
+ implicit = 0
1394
+ for sf, tf, _e, dst, kind in _file_import_edges(nodes, edges, kind_of):
1395
+ if _is_file_hub_node(dst) and _is_package_entry_of(tf, sf):
1396
+ implicit += 1
1397
+ continue
1398
+ known = best.get((sf, tf))
1399
+ if known is None or rank[kind] < rank[known]:
1400
+ best[(sf, tf)] = kind
1401
+ forward: _Adj = {}
1402
+ for (sf, tf), kind in best.items():
1403
+ forward.setdefault(sf, []).append((tf, kind))
1404
+ return forward, implicit
1405
+
1406
+
1407
+ def _shortest_path(forward: _Adj, members: set[str], src: str, dst: str) -> list[str]:
1408
+ """Shortest ``src -> ... -> dst`` route staying inside ``members`` ([] if none)."""
1409
+ if src == dst:
1410
+ return [src]
1411
+ prev: dict[str, str] = {}
1412
+ queue = deque([src])
1413
+ while queue:
1414
+ cur = queue.popleft()
1415
+ for nb, _kind in forward.get(cur, []):
1416
+ if nb not in members or nb in prev or nb == src:
1417
+ continue
1418
+ prev[nb] = cur
1419
+ if nb == dst:
1420
+ path = [dst]
1421
+ while path[-1] != src:
1422
+ path.append(prev[path[-1]])
1423
+ return path[::-1]
1424
+ queue.append(nb)
1425
+ return []
1426
+
1427
+
1428
+ def _route(
1429
+ adj: _Adj, src: str, dst: str, skip: frozenset[str] = frozenset(),
1430
+ avoid: frozenset[str] | set[str] = frozenset(),
1431
+ ) -> list[tuple[str, str, str]] | None:
1432
+ """Shortest ``src -> ... -> dst`` walk over ``adj`` as ``(from, to, relation)``
1433
+ steps, never along a relation in ``skip`` nor through a node in ``avoid``
1434
+ (which may still be an end); ``[]`` when ``src == dst``, None when ``dst``
1435
+ cannot be reached. Of two routes of one length the one whose neighbours
1436
+ come first in ``adj`` wins, so the answer is deterministic."""
1437
+ if src == dst:
1438
+ return []
1439
+ prev: dict[str, tuple[str, str]] = {}
1440
+ queue = deque([src])
1441
+ while queue:
1442
+ cur = queue.popleft()
1443
+ for nb, rel in adj.get(cur, []):
1444
+ if rel in skip or nb == src or nb in prev or (nb in avoid and nb != dst):
1445
+ continue
1446
+ prev[nb] = (cur, rel)
1447
+ if nb == dst:
1448
+ steps: list[tuple[str, str, str]] = []
1449
+ at = dst
1450
+ while at != src:
1451
+ back, how = prev[at]
1452
+ steps.append((back, at, how))
1453
+ at = back
1454
+ return steps[::-1]
1455
+ queue.append(nb)
1456
+ return None
1457
+
1458
+
1459
+ # The three kinds of import cycle, most serious first, with the import kinds
1460
+ # each one's loops may use.
1461
+ _IMPORT_CYCLE_TIERS: tuple[tuple[str, frozenset[str]], ...] = (
1462
+ ("runtime", _IMPORT_RUNS_AT_IMPORT),
1463
+ ("deferred", _IMPORT_RUNS_AT_IMPORT | {IMPORT_DEFERRED}),
1464
+ ("type-only", _IMPORT_RUNS_AT_IMPORT | {IMPORT_DEFERRED, IMPORT_TYPE_CHECKING}),
1465
+ )
1466
+
1467
+
1468
+ def _tiered_import_cycles(forward: _Adj) -> list[dict[str, Any]]:
1469
+ """Import cycles between modules, classified by when their imports run.
1470
+
1471
+ ``runtime`` — some loop consists of module-level imports only: it can fail
1472
+ at start-up.
1473
+ ``deferred`` — the group only closes through an import inside a function.
1474
+ ``type-only`` — the group only closes through an import under
1475
+ ``if TYPE_CHECKING:``; it exists for the type checker alone.
1476
+ A group is reported once, in the first tier where it is a cycle, with one
1477
+ loop through an import that tier needed (``path``) and the kind of each hop
1478
+ (``hops``).
1479
+ """
1480
+ out: list[dict[str, Any]] = []
1481
+ seen: set[frozenset[str]] = set()
1482
+ lower_of: dict[str, int] = {} # node -> its cycle group in the previous tier
1483
+
1484
+ def _apart(u: str, v: str) -> bool:
1485
+ gu, gv = lower_of.get(u), lower_of.get(v)
1486
+ return gu is None or gv is None or gu != gv
1487
+
1488
+ for tier, allowed in _IMPORT_CYCLE_TIERS:
1489
+ sub: _Adj = {
1490
+ s: [(t, k) for t, k in lst if k in allowed] for s, lst in forward.items()
1491
+ }
1492
+ groups = _find_cycles(sub)[0]
1493
+ for comp in groups:
1494
+ key = frozenset(comp)
1495
+ if key in seen:
1496
+ continue
1497
+ seen.add(key)
1498
+ members = set(comp)
1499
+ path: list[str] = []
1500
+ if tier != "runtime":
1501
+ # Lead with an import this tier added that joins two parts the
1502
+ # earlier tiers kept apart — the edge the cycle depends on.
1503
+ newest = IMPORT_DEFERRED if tier == "deferred" else IMPORT_TYPE_CHECKING
1504
+ for u in sorted(members):
1505
+ for v, k in sorted(sub.get(u, [])):
1506
+ if k == newest and v in members and _apart(u, v):
1507
+ back = _shortest_path(sub, members, v, u)
1508
+ if back:
1509
+ path = [u, *back]
1510
+ break
1511
+ if path:
1512
+ break
1513
+ if not path:
1514
+ path = _cycle_path(sub, comp)
1515
+ kinds = {(u, v): k for u in members for v, k in sub.get(u, [])}
1516
+ out.append({
1517
+ "tier": tier, "nodes": comp, "path": path,
1518
+ "hops": [kinds.get((a, b), IMPORT_UNCLASSIFIED)
1519
+ for a, b in zip(path, path[1:], strict=False)],
1520
+ })
1521
+ for i, comp in enumerate(groups):
1522
+ for n in comp:
1523
+ lower_of[n] = i
1524
+ return out
1525
+
1526
+
1527
+ def _hop_distances(
1528
+ adj: dict[str, list[tuple[str, str]]], start_id: str, max_hops: int
1529
+ ) -> dict[str, int]:
1530
+ """Shortest hop distance from start_id to each node reachable within max_hops."""
1531
+ dist = {start_id: 0}
1532
+ frontier = deque([(start_id, 0)])
1533
+ while frontier:
1534
+ cur, d = frontier.popleft()
1535
+ if d >= max_hops:
1536
+ continue
1537
+ for nb, _rel in adj.get(cur, []):
1538
+ if nb not in dist:
1539
+ dist[nb] = d + 1
1540
+ frontier.append((nb, d + 1))
1541
+ return dist
1542
+
1543
+
1544
+ # node id -> list of (neighbor id, the whole edge dict). _directed_adjacency keeps
1545
+ # only the relation, which is all hop-counting needs; impact also wants the
1546
+ # traversed edge's own recorded position (the reference site), so it needs the edge.
1547
+ _EAdj = dict[str, list[tuple[str, dict]]]
1548
+
1549
+
1550
+ def _build_directed_edge_adjacency(edges: list[dict]) -> tuple[_EAdj, _EAdj]:
1551
+ """(forward, reverse) directed adjacency carrying each traversed edge."""
1552
+ forward: _EAdj = {}
1553
+ reverse: _EAdj = {}
1554
+ for e in edges:
1555
+ s, t = _edge_ends(e)
1556
+ forward.setdefault(s, []).append((t, e))
1557
+ reverse.setdefault(t, []).append((s, e))
1558
+ return forward, reverse
1559
+
1560
+
1561
+ # Same id(edges)+identity-guard scheme as _ADJ_CACHE (see there).
1562
+ _DIR_EDGE_ADJ_CACHE: dict[int, tuple[list[dict], tuple[_EAdj, _EAdj]]] = {}
1563
+
1564
+
1565
+ def _directed_edge_adjacency(edges: list[dict]) -> tuple[_EAdj, _EAdj]:
1566
+ """(forward, reverse) edge-carrying adjacency, cached on the edges-list identity."""
1567
+ cached = _DIR_EDGE_ADJ_CACHE.get(id(edges))
1568
+ if cached is not None and cached[0] is edges:
1569
+ return cached[1]
1570
+ pair = _build_directed_edge_adjacency(edges)
1571
+ if id(edges) not in _DIR_EDGE_ADJ_CACHE and len(_DIR_EDGE_ADJ_CACHE) >= _ADJ_CACHE_MAX:
1572
+ _DIR_EDGE_ADJ_CACHE.pop(next(iter(_DIR_EDGE_ADJ_CACHE)), None) # FIFO
1573
+ _DIR_EDGE_ADJ_CACHE[id(edges)] = (edges, pair)
1574
+ return pair
1575
+
1576
+
1577
+ def _hop_records(
1578
+ adj: _EAdj,
1579
+ start_id: str,
1580
+ max_hops: int,
1581
+ relations: frozenset[str] | None = None,
1582
+ seeds: Iterable[str] = (),
1583
+ exclude: frozenset[str] = frozenset(),
1584
+ edge_ok: Callable[[dict], bool] | None = None,
1585
+ ) -> dict[str, tuple[int, str, dict | None]]:
1586
+ """Like :func:`_hop_distances`, but records HOW each node was reached.
1587
+
1588
+ Returns ``{node_id: (distance, reached_via_id, discovery_edge)}`` — the edge
1589
+ that first reached the node on a shortest path. ``relations=None`` walks
1590
+ every edge type, so the distances match _hop_distances exactly. ``seeds`` are
1591
+ extra depth-0 entries (used to keep a class's own members reachable when
1592
+ containment edges are filtered out); they carry ``None`` as their edge so
1593
+ callers can tell them from real hits. ``exclude`` names relations never
1594
+ walked, whatever ``relations`` says; ``edge_ok`` rejects single edges (an
1595
+ inferred one, under a strict walk).
1596
+ """
1597
+ out: dict[str, tuple[int, str, dict | None]] = {start_id: (0, "", None)}
1598
+ frontier = deque([(start_id, 0)])
1599
+ for s in seeds:
1600
+ if s not in out:
1601
+ out[s] = (0, "", None)
1602
+ frontier.append((s, 0))
1603
+ while frontier:
1604
+ cur, d = frontier.popleft()
1605
+ if d >= max_hops:
1606
+ continue
1607
+ for nb, e in adj.get(cur, []):
1608
+ rel = _rel(e)
1609
+ if rel in exclude or (relations is not None and rel not in relations):
1610
+ continue
1611
+ if edge_ok is not None and not edge_ok(e):
1612
+ continue
1613
+ if nb in out:
1614
+ continue
1615
+ out[nb] = (d + 1, cur, e)
1616
+ frontier.append((nb, d + 1))
1617
+ return out
1618
+
1619
+
1620
+ def _beyond_hops(
1621
+ adj: _EAdj,
1622
+ recs: dict[str, tuple[int, str, dict | None]],
1623
+ max_hops: int,
1624
+ relations: frozenset[str] | None = None,
1625
+ exclude: frozenset[str] = frozenset(),
1626
+ edge_ok: Callable[[dict], bool] | None = None,
1627
+ ) -> int:
1628
+ """How many nodes one more hop past ``max_hops`` would add to ``recs`` (a
1629
+ :func:`_hop_records` result walked with the same filters). Zero means the
1630
+ walk reached everything it could: the hop limit cut nothing off."""
1631
+ more: set[str] = set()
1632
+ for nid, (d, _via, _edge) in recs.items():
1633
+ if d != max_hops:
1634
+ continue
1635
+ for nb, e in adj.get(nid, []):
1636
+ rel = _rel(e)
1637
+ if rel in exclude or (relations is not None and rel not in relations):
1638
+ continue
1639
+ if edge_ok is not None and not edge_ok(e):
1640
+ continue
1641
+ if nb not in recs:
1642
+ more.add(nb)
1643
+ return len(more)