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/__init__.py +7 -0
- graphlore/__main__.py +12 -0
- graphlore/agents_md.py +96 -0
- graphlore/algorithms.py +311 -0
- graphlore/apis.py +617 -0
- graphlore/cli.py +133 -0
- graphlore/clients.py +260 -0
- graphlore/config.py +68 -0
- graphlore/embed.py +233 -0
- graphlore/engine.py +379 -0
- graphlore/graph.py +1643 -0
- graphlore/history.py +198 -0
- graphlore/imports.py +581 -0
- graphlore/oauth.py +169 -0
- graphlore/resolve.py +332 -0
- graphlore/review.py +1121 -0
- graphlore/routes.py +1417 -0
- graphlore/scope.py +362 -0
- graphlore/search.py +1070 -0
- graphlore/server.py +8152 -0
- graphlore/spans.py +1254 -0
- graphlore/viewer.html +1649 -0
- graphlore/viz.py +381 -0
- graphlore-0.7.0.dist-info/METADATA +379 -0
- graphlore-0.7.0.dist-info/RECORD +28 -0
- graphlore-0.7.0.dist-info/WHEEL +4 -0
- graphlore-0.7.0.dist-info/entry_points.txt +2 -0
- graphlore-0.7.0.dist-info/licenses/LICENSE +21 -0
graphlore/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""graphlore — an MCP server exposing a codebase knowledge graph, joined to source spans."""
|
|
2
|
+
|
|
3
|
+
from graphlore.apis import api_uses_for_source
|
|
4
|
+
from graphlore.routes import routes_for_source
|
|
5
|
+
from graphlore.server import __version__, main, mcp
|
|
6
|
+
|
|
7
|
+
__all__ = ["__version__", "api_uses_for_source", "main", "mcp", "routes_for_source"]
|
graphlore/__main__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""Enable ``python -m graphlore``: the same as the ``graphlore`` command.
|
|
2
|
+
|
|
3
|
+
With no arguments it runs the MCP server; ``python -m graphlore setup codex``
|
|
4
|
+
and the other subcommands are those of ``graphlore.cli``.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from graphlore.cli import main
|
|
10
|
+
|
|
11
|
+
if __name__ == "__main__":
|
|
12
|
+
sys.exit(main())
|
graphlore/agents_md.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""The usage guide graphlore gives coding agents that read a project file
|
|
2
|
+
(AGENTS.md, GEMINI.md, a Cursor rule, Copilot's instructions) rather than an
|
|
3
|
+
MCP server's instructions or prompts: Codex, Kimi, Cursor, Copilot, Zed, Gemini
|
|
4
|
+
CLI. It names only the tools of the toolset the server runs with, says when
|
|
5
|
+
graphlore is the better tool and when grep is, and how to read an answer.
|
|
6
|
+
|
|
7
|
+
`render(tools)` gives the block between its markers; `merge(text, block)`
|
|
8
|
+
puts it into an existing file, replacing only what is between the markers.
|
|
9
|
+
Imports nothing from graphlore.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from collections.abc import Iterable
|
|
14
|
+
|
|
15
|
+
BEGIN = "<!-- graphlore:begin -->"
|
|
16
|
+
END = "<!-- graphlore:end -->"
|
|
17
|
+
|
|
18
|
+
# (the tools a line needs, all of them registered; the line)
|
|
19
|
+
_FLOW: tuple[tuple[tuple[str, ...], str], ...] = (
|
|
20
|
+
(("graphlore_overview",),
|
|
21
|
+
"Start with `graphlore_overview`: the graph's size, its most central nodes and "
|
|
22
|
+
"its communities."),
|
|
23
|
+
(("graphlore_locate",),
|
|
24
|
+
"To find code by what it does, `graphlore_locate(\"<question>\")`: the best hit, "
|
|
25
|
+
"its graph neighbourhood and similar code elsewhere."),
|
|
26
|
+
(("graphlore_impact",),
|
|
27
|
+
"Before changing something, `graphlore_impact(\"<name>\")`: what depends on it, "
|
|
28
|
+
"by hop, and the chokepoints it funnels through."),
|
|
29
|
+
(("graphlore_neighbors", "graphlore_subgraph"),
|
|
30
|
+
"Around one node: `graphlore_neighbors` (one hop) or `graphlore_subgraph` "
|
|
31
|
+
"(a token-budgeted neighbourhood)."),
|
|
32
|
+
(("graphlore_node_details",),
|
|
33
|
+
"A node's file, line, kind and docstring: `graphlore_node_details`."),
|
|
34
|
+
(("graphlore_fetch",),
|
|
35
|
+
"Read the code of the nodes you settled on with `graphlore_fetch([...])`: their "
|
|
36
|
+
"exact lines, under one budget."),
|
|
37
|
+
(("graphlore_tests_for",),
|
|
38
|
+
"Tests that exercise a symbol: `graphlore_tests_for(\"<name>\")`."),
|
|
39
|
+
(("graphlore_path",),
|
|
40
|
+
"How A reaches B: `graphlore_path(\"A\", \"B\")`, the most certain path."),
|
|
41
|
+
(("graphlore_cycles", "graphlore_layers", "graphlore_unreferenced"),
|
|
42
|
+
"Reviewing structure: `graphlore_cycles` (import cycles, runtime first), "
|
|
43
|
+
"`graphlore_layers` (layer rules), `graphlore_unreferenced` (dead-code "
|
|
44
|
+
"candidates: confirm each before deleting)."),
|
|
45
|
+
(("graphlore_bridges", "graphlore_god_nodes"),
|
|
46
|
+
"Where the code hangs by one link: `graphlore_bridges`; what everything leans "
|
|
47
|
+
"on: `graphlore_god_nodes(rank=\"pagerank\")`."),
|
|
48
|
+
(("graphlore_freshness", "graphlore_build"),
|
|
49
|
+
"After editing code, `graphlore_freshness` says whether the graph is stale; "
|
|
50
|
+
"`graphlore_build(update=True)` brings it up to date."),
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
_READING = (
|
|
54
|
+
"An edge marked `INFERRED` was matched by name, not resolved: confirm it in the "
|
|
55
|
+
"source before relying on it.",
|
|
56
|
+
"An empty answer means no edge was indexed, not that the code has none: check "
|
|
57
|
+
"with `rg`.",
|
|
58
|
+
"A name several nodes share resolves to one, and the reply says which "
|
|
59
|
+
"(`matched`); pass the node's id to pick another. A miss answers `did_you_mean`.",
|
|
60
|
+
"Answers carry `file:line`. Read those lines before editing them.",
|
|
61
|
+
"Analysis tools leave vendored files and external packages out by default and "
|
|
62
|
+
"say so; `scope=\"-tests\"` leaves test code out.",
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def render(tools: Iterable[str]) -> str:
|
|
67
|
+
"""The guide for an agent whose graphlore server registers ``tools``,
|
|
68
|
+
between the markers."""
|
|
69
|
+
have = set(tools)
|
|
70
|
+
lines = [
|
|
71
|
+
BEGIN,
|
|
72
|
+
"## graphlore: this repository's code graph (MCP)",
|
|
73
|
+
"",
|
|
74
|
+
"The graphlore MCP server holds a graph of this repository: its definitions "
|
|
75
|
+
"with exact `file:line` spans, and the calls, imports, references and bases "
|
|
76
|
+
"between them. Use it for structure: who calls this, what breaks if it "
|
|
77
|
+
"changes, where a behaviour lives, how two parts connect. Use `grep` / `rg` "
|
|
78
|
+
"for an exact string or identifier: it is faster there.",
|
|
79
|
+
"",
|
|
80
|
+
]
|
|
81
|
+
lines += [f"- {text}" for needs, text in _FLOW if all(t in have for t in needs)]
|
|
82
|
+
lines += ["", "Reading an answer:", ""]
|
|
83
|
+
lines += [f"- {text}" for text in _READING]
|
|
84
|
+
lines.append(END)
|
|
85
|
+
return "\n".join(lines) + "\n"
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def merge(existing: str, block: str) -> str:
|
|
89
|
+
"""``existing`` with ``block`` in place of what stands between the markers,
|
|
90
|
+
or appended (after one blank line) when the file has none."""
|
|
91
|
+
start, end = existing.find(BEGIN), existing.find(END)
|
|
92
|
+
if start >= 0 and end > start:
|
|
93
|
+
return existing[:start] + block.rstrip("\n") + existing[end + len(END):]
|
|
94
|
+
if not existing.strip():
|
|
95
|
+
return block
|
|
96
|
+
return existing.rstrip("\n") + "\n\n" + block
|
graphlore/algorithms.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
"""Graph algorithms over plain adjacency maps, with no graph.json knowledge.
|
|
2
|
+
|
|
3
|
+
Each function takes node ids and successor lists (``{node: [neighbour, ...]}``)
|
|
4
|
+
and is deterministic: ties are broken by the order of the lists handed in and,
|
|
5
|
+
where nodes are sampled, by a hash of their id, never by a random draw.
|
|
6
|
+
|
|
7
|
+
- :func:`certain_route` — the path with the fewest uncertain steps, then the
|
|
8
|
+
fewest steps (Dijkstra on that pair of costs).
|
|
9
|
+
- :func:`pagerank` — the stationary rank of a walk along the edges.
|
|
10
|
+
- :func:`betweenness` — Brandes' betweenness, exact or estimated from sampled
|
|
11
|
+
sources.
|
|
12
|
+
- :func:`dominators` — the immediate dominator of each node reachable from a
|
|
13
|
+
root (Cooper, Harvey and Kennedy's iterative algorithm).
|
|
14
|
+
- :func:`cut_structure` — the bridges and cut vertices of an undirected graph
|
|
15
|
+
(Tarjan's low-link), with the size of what each one cuts off.
|
|
16
|
+
|
|
17
|
+
Imports nothing from graphlore.
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import hashlib
|
|
22
|
+
import heapq
|
|
23
|
+
from collections import deque
|
|
24
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
25
|
+
from typing import NamedTuple
|
|
26
|
+
|
|
27
|
+
Succ = Mapping[str, Sequence[str]]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def certain_route(
|
|
31
|
+
adj: Mapping[str, Sequence[tuple[str, str]]],
|
|
32
|
+
src: str,
|
|
33
|
+
dst: str,
|
|
34
|
+
uncertain: Callable[[str, str, str], bool],
|
|
35
|
+
skip: frozenset[str] = frozenset(),
|
|
36
|
+
avoid: frozenset[str] | set[str] = frozenset(),
|
|
37
|
+
) -> list[tuple[str, str, str]] | None:
|
|
38
|
+
"""The ``src -> ... -> dst`` walk over ``adj`` (``node -> [(neighbour,
|
|
39
|
+
relation)]``) with the fewest steps ``uncertain(from, to, relation)`` says
|
|
40
|
+
are uncertain, then the fewest steps, as ``(from, to, relation)`` steps.
|
|
41
|
+
|
|
42
|
+
Never along a relation in ``skip`` nor through a node in ``avoid`` (which may
|
|
43
|
+
still be an end); ``[]`` when ``src == dst``, None when ``dst`` cannot be
|
|
44
|
+
reached. When no step is uncertain the answer is the breadth-first one,
|
|
45
|
+
neighbours in ``adj`` order: of two equal walks the one found first wins.
|
|
46
|
+
"""
|
|
47
|
+
if src == dst:
|
|
48
|
+
return []
|
|
49
|
+
best: dict[str, tuple[int, int]] = {src: (0, 0)}
|
|
50
|
+
prev: dict[str, tuple[str, str]] = {}
|
|
51
|
+
seq = 0
|
|
52
|
+
heap: list[tuple[int, int, int, str]] = [(0, 0, seq, src)]
|
|
53
|
+
done: set[str] = set()
|
|
54
|
+
while heap:
|
|
55
|
+
unc, steps, _, cur = heapq.heappop(heap)
|
|
56
|
+
if cur in done:
|
|
57
|
+
continue
|
|
58
|
+
done.add(cur)
|
|
59
|
+
if cur == dst:
|
|
60
|
+
break
|
|
61
|
+
for nb, rel in adj.get(cur, ()):
|
|
62
|
+
if rel in skip or nb == src or nb in done or (nb in avoid and nb != dst):
|
|
63
|
+
continue
|
|
64
|
+
cost = (unc + (1 if uncertain(cur, nb, rel) else 0), steps + 1)
|
|
65
|
+
if nb not in best or cost < best[nb]:
|
|
66
|
+
best[nb] = cost
|
|
67
|
+
prev[nb] = (cur, rel)
|
|
68
|
+
seq += 1
|
|
69
|
+
heapq.heappush(heap, (cost[0], cost[1], seq, nb))
|
|
70
|
+
if dst not in prev:
|
|
71
|
+
return None
|
|
72
|
+
out: list[tuple[str, str, str]] = []
|
|
73
|
+
at = dst
|
|
74
|
+
while at != src:
|
|
75
|
+
p, rel = prev[at]
|
|
76
|
+
out.append((p, at, rel))
|
|
77
|
+
at = p
|
|
78
|
+
out.reverse()
|
|
79
|
+
return out
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def pagerank(
|
|
83
|
+
ids: Sequence[str], succ: Succ, damping: float = 0.85, tol: float = 1e-10,
|
|
84
|
+
max_iter: int = 200,
|
|
85
|
+
) -> dict[str, float]:
|
|
86
|
+
"""PageRank of ``ids`` over the edges ``succ`` gives (an edge ``u -> v``
|
|
87
|
+
hands rank from ``u`` to ``v``; one written twice counts twice). A node with
|
|
88
|
+
no edge out spreads its rank over every node. The ranks sum to 1."""
|
|
89
|
+
n = len(ids)
|
|
90
|
+
if not n:
|
|
91
|
+
return {}
|
|
92
|
+
pos = {nid: i for i, nid in enumerate(ids)}
|
|
93
|
+
out_lists = [[pos[v] for v in succ.get(nid, ()) if v in pos] for nid in ids]
|
|
94
|
+
rank = [1.0 / n] * n
|
|
95
|
+
for _ in range(max_iter):
|
|
96
|
+
nxt = [0.0] * n
|
|
97
|
+
dangling = 0.0
|
|
98
|
+
for i, outs in enumerate(out_lists):
|
|
99
|
+
if outs:
|
|
100
|
+
share = rank[i] / len(outs)
|
|
101
|
+
for j in outs:
|
|
102
|
+
nxt[j] += share
|
|
103
|
+
else:
|
|
104
|
+
dangling += rank[i]
|
|
105
|
+
base = (1.0 - damping) / n + damping * dangling / n
|
|
106
|
+
nxt = [base + damping * x for x in nxt]
|
|
107
|
+
diff = sum(abs(a - b) for a, b in zip(nxt, rank, strict=True))
|
|
108
|
+
rank = nxt
|
|
109
|
+
if diff < tol:
|
|
110
|
+
break
|
|
111
|
+
return {nid: rank[i] for i, nid in enumerate(ids)}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _hash_order(ids: Iterable[str]) -> list[str]:
|
|
115
|
+
return sorted(ids, key=lambda s: hashlib.sha1(s.encode("utf-8", "replace"),
|
|
116
|
+
usedforsecurity=False).hexdigest())
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Betweenness(NamedTuple):
|
|
120
|
+
scores: dict[str, float]
|
|
121
|
+
sources: int # how many sources the paths were counted from
|
|
122
|
+
nodes: int # of how many
|
|
123
|
+
exact: bool
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def betweenness(ids: Sequence[str], succ: Succ, samples: int = 0) -> Betweenness:
|
|
127
|
+
"""Betweenness of each node of ``ids`` along the directed edges of ``succ``
|
|
128
|
+
(Brandes): the number of shortest paths between two other nodes that pass
|
|
129
|
+
through it. With ``0 < samples < len(ids)`` the paths are counted from that
|
|
130
|
+
many sources, picked by a hash of their id, and scaled up by
|
|
131
|
+
``len(ids) / samples``: an estimate, said so in ``exact``."""
|
|
132
|
+
n = len(ids)
|
|
133
|
+
pos = {nid: i for i, nid in enumerate(ids)}
|
|
134
|
+
out_lists = [[pos[v] for v in succ.get(nid, ()) if v in pos and v != nid] for nid in ids]
|
|
135
|
+
sources = list(range(n))
|
|
136
|
+
exact = True
|
|
137
|
+
if 0 < samples < n:
|
|
138
|
+
sources = [pos[s] for s in _hash_order(ids)[:samples]]
|
|
139
|
+
exact = False
|
|
140
|
+
score = [0.0] * n
|
|
141
|
+
for s in sources:
|
|
142
|
+
stack: list[int] = []
|
|
143
|
+
preds: list[list[int]] = [[] for _ in range(n)]
|
|
144
|
+
sigma = [0] * n
|
|
145
|
+
sigma[s] = 1
|
|
146
|
+
dist = [-1] * n
|
|
147
|
+
dist[s] = 0
|
|
148
|
+
queue = deque([s])
|
|
149
|
+
while queue:
|
|
150
|
+
v = queue.popleft()
|
|
151
|
+
stack.append(v)
|
|
152
|
+
for w in out_lists[v]:
|
|
153
|
+
if dist[w] < 0:
|
|
154
|
+
dist[w] = dist[v] + 1
|
|
155
|
+
queue.append(w)
|
|
156
|
+
if dist[w] == dist[v] + 1:
|
|
157
|
+
sigma[w] += sigma[v]
|
|
158
|
+
preds[w].append(v)
|
|
159
|
+
delta = [0.0] * n
|
|
160
|
+
while stack:
|
|
161
|
+
w = stack.pop()
|
|
162
|
+
for v in preds[w]:
|
|
163
|
+
delta[v] += sigma[v] / sigma[w] * (1.0 + delta[w])
|
|
164
|
+
if w != s:
|
|
165
|
+
score[w] += delta[w]
|
|
166
|
+
scale = n / len(sources) if sources and not exact else 1.0
|
|
167
|
+
return Betweenness({nid: score[i] * scale for i, nid in enumerate(ids)},
|
|
168
|
+
len(sources), n, exact)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def dominators(root: str, succ: Succ) -> dict[str, str]:
|
|
172
|
+
"""The immediate dominator of every node reachable from ``root`` along
|
|
173
|
+
``succ`` (the root maps to itself): the last node every path from the root
|
|
174
|
+
to it must pass through. Cooper, Harvey and Kennedy, "A Simple, Fast
|
|
175
|
+
Dominance Algorithm" (2001), on the reverse postorder of a depth-first walk."""
|
|
176
|
+
order: list[str] = []
|
|
177
|
+
seen = {root}
|
|
178
|
+
stack: list[tuple[str, int]] = [(root, 0)]
|
|
179
|
+
while stack:
|
|
180
|
+
node, k = stack.pop()
|
|
181
|
+
kids = succ.get(node, ())
|
|
182
|
+
if k < len(kids):
|
|
183
|
+
stack.append((node, k + 1))
|
|
184
|
+
nxt = kids[k]
|
|
185
|
+
if nxt not in seen:
|
|
186
|
+
seen.add(nxt)
|
|
187
|
+
stack.append((nxt, 0))
|
|
188
|
+
else:
|
|
189
|
+
order.append(node)
|
|
190
|
+
order.reverse() # reverse postorder, root first
|
|
191
|
+
rpo = {nid: i for i, nid in enumerate(order)}
|
|
192
|
+
preds: dict[str, list[str]] = {nid: [] for nid in order}
|
|
193
|
+
for u in order:
|
|
194
|
+
for v in succ.get(u, ()):
|
|
195
|
+
if v in preds and u != v:
|
|
196
|
+
preds[v].append(u)
|
|
197
|
+
idom: dict[str, str] = {root: root}
|
|
198
|
+
|
|
199
|
+
def meet(a: str, b: str) -> str:
|
|
200
|
+
while a != b:
|
|
201
|
+
while rpo[a] > rpo[b]:
|
|
202
|
+
a = idom[a]
|
|
203
|
+
while rpo[b] > rpo[a]:
|
|
204
|
+
b = idom[b]
|
|
205
|
+
return a
|
|
206
|
+
|
|
207
|
+
changed = True
|
|
208
|
+
while changed:
|
|
209
|
+
changed = False
|
|
210
|
+
for v in order[1:]:
|
|
211
|
+
done = [p for p in preds[v] if p in idom]
|
|
212
|
+
if not done:
|
|
213
|
+
continue
|
|
214
|
+
new = done[0]
|
|
215
|
+
for p in done[1:]:
|
|
216
|
+
new = meet(p, new)
|
|
217
|
+
if idom.get(v) != new:
|
|
218
|
+
idom[v] = new
|
|
219
|
+
changed = True
|
|
220
|
+
return idom
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def dominated_counts(idom: Mapping[str, str]) -> dict[str, int]:
|
|
224
|
+
"""How many nodes each node dominates, itself left out (its subtree in the
|
|
225
|
+
dominator tree ``idom`` gives, less one)."""
|
|
226
|
+
kids: dict[str, list[str]] = {}
|
|
227
|
+
root = next((v for v, d in idom.items() if v == d), None)
|
|
228
|
+
for v, d in idom.items():
|
|
229
|
+
if v != d:
|
|
230
|
+
kids.setdefault(d, []).append(v)
|
|
231
|
+
size: dict[str, int] = {}
|
|
232
|
+
if root is None:
|
|
233
|
+
return {}
|
|
234
|
+
stack: list[tuple[str, bool]] = [(root, False)]
|
|
235
|
+
while stack:
|
|
236
|
+
node, expanded = stack.pop()
|
|
237
|
+
if expanded:
|
|
238
|
+
size[node] = 1 + sum(size[k] for k in kids.get(node, ()))
|
|
239
|
+
else:
|
|
240
|
+
stack.append((node, True))
|
|
241
|
+
stack.extend((k, False) for k in kids.get(node, ()))
|
|
242
|
+
return {v: s - 1 for v, s in size.items()}
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
class CutStructure(NamedTuple):
|
|
246
|
+
# (u, v, nodes on v's side once the edge goes, nodes of their component)
|
|
247
|
+
bridges: list[tuple[str, str, int, int]]
|
|
248
|
+
# node -> (nodes cut off from the largest remaining piece, pieces, component size)
|
|
249
|
+
cuts: dict[str, tuple[int, int, int]]
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def cut_structure(ids: Sequence[str], neighbours: Mapping[str, Iterable[str]]) -> CutStructure:
|
|
253
|
+
"""The bridges (edges whose removal disconnects their component) and cut
|
|
254
|
+
vertices (nodes whose removal does) of the undirected simple graph
|
|
255
|
+
``neighbours`` over ``ids``, by Tarjan's low-link on an iterative depth-first
|
|
256
|
+
walk. A bridge carries the size of the side it cuts off from the walk's
|
|
257
|
+
start; a cut vertex, how many nodes lose the largest piece left without it."""
|
|
258
|
+
adj = {nid: sorted({v for v in neighbours.get(nid, ()) if v != nid}) for nid in ids}
|
|
259
|
+
disc: dict[str, int] = {}
|
|
260
|
+
low: dict[str, int] = {}
|
|
261
|
+
sub: dict[str, int] = {}
|
|
262
|
+
bridges: list[tuple[str, str, int, int]] = []
|
|
263
|
+
cuts: dict[str, tuple[int, int, int]] = {}
|
|
264
|
+
clock = 0
|
|
265
|
+
for start in ids:
|
|
266
|
+
if start in disc:
|
|
267
|
+
continue
|
|
268
|
+
comp_bridges: list[tuple[str, str, int]] = []
|
|
269
|
+
cut_parts: dict[str, list[int]] = {}
|
|
270
|
+
disc[start] = low[start] = clock
|
|
271
|
+
clock += 1
|
|
272
|
+
sub[start] = 1
|
|
273
|
+
stack: list[tuple[str, str | None, int]] = [(start, None, 0)]
|
|
274
|
+
while stack:
|
|
275
|
+
node, parent, k = stack.pop()
|
|
276
|
+
kids = adj.get(node, [])
|
|
277
|
+
if k < len(kids):
|
|
278
|
+
stack.append((node, parent, k + 1))
|
|
279
|
+
nb = kids[k]
|
|
280
|
+
if nb == parent:
|
|
281
|
+
continue
|
|
282
|
+
if nb in disc:
|
|
283
|
+
low[node] = min(low[node], disc[nb])
|
|
284
|
+
else:
|
|
285
|
+
disc[nb] = low[nb] = clock
|
|
286
|
+
clock += 1
|
|
287
|
+
sub[nb] = 1
|
|
288
|
+
stack.append((nb, node, 0))
|
|
289
|
+
continue
|
|
290
|
+
if parent is None:
|
|
291
|
+
continue
|
|
292
|
+
low[parent] = min(low[parent], low[node])
|
|
293
|
+
sub[parent] += sub[node]
|
|
294
|
+
if low[node] > disc[parent]:
|
|
295
|
+
comp_bridges.append((parent, node, sub[node]))
|
|
296
|
+
if low[node] >= disc[parent]:
|
|
297
|
+
cut_parts.setdefault(parent, []).append(sub[node])
|
|
298
|
+
size = sub[start]
|
|
299
|
+
bridges.extend((u, v, s, size) for u, v, s in comp_bridges)
|
|
300
|
+
for node, parts in cut_parts.items():
|
|
301
|
+
if node == start:
|
|
302
|
+
if len(parts) < 2:
|
|
303
|
+
continue # the root cuts only when it has two subtrees
|
|
304
|
+
pieces = parts
|
|
305
|
+
else:
|
|
306
|
+
pieces = parts + [size - 1 - sum(parts)]
|
|
307
|
+
pieces = [p for p in pieces if p > 0]
|
|
308
|
+
if len(pieces) < 2:
|
|
309
|
+
continue
|
|
310
|
+
cuts[node] = (size - 1 - max(pieces), len(pieces), size)
|
|
311
|
+
return CutStructure(bridges, cuts)
|