Repository navigation
Expand file tree
/
Copy pathgraph.py
More file actions
executable file
·538 lines (436 loc) · 20.8 KB
/
Copy pathgraph.py
File metadata and controls
executable file
·538 lines (436 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
#!/usr/bin/env python3
# `kings graph <subcommand> [args]`: queries a code dependency graph generated by Graphify.
# Mostly run by AI agents, so the output is compact and every query opens with how stale the
# graph is compared to the working tree.
import json
import os
import re
import shutil
import subprocess
import sys
from collections import defaultdict
from datetime import datetime
USAGE = """Usage: kings graph <subcommand> [args] [--graph DIR]
update [path] regenerates the graph (from path, or the git root of the cwd) and stamps its branch/commit
info graph state: which commit it came from and how stale it is
deps <Type> full dependency survey of a type (the mock briefing) — tuned for Swift projects
impact <Type> [n] who is affected if the type changes, n levels deep (default 2)
find <pattern> resolves a name to graph node(s), with id
--graph DIR graph folder (holding graph.json, or its graphify-out/); default:
$KINGS_GRAPH_DIR, else <git root of cwd>/graphify-out"""
INIT_LABELS = (".init()", ".__init__()")
TEST_MARKERS = re.compile(r"Tests|Mock|Spy|Stub|Fake|(^|/)tests?/|(^|/)test_|_test\.|conftest")
# ------------------------------------------------------------------------------------ paths
def die(message):
sys.exit(message)
def git(*args, cwd):
try:
out = subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True)
return out.stdout.strip() if out.returncode == 0 else None
except OSError:
return None
def git_root(path):
return git("rev-parse", "--show-toplevel", cwd=path) if os.path.isdir(path) else None
# Pulls `--graph DIR` out of the arguments so it works before or after the subcommand.
def split_graph_flag(args):
rest, flag = [], None
while args:
a = args.pop(0)
if a == "--graph":
if not args:
die("--graph needs a folder")
flag = args.pop(0)
else:
rest.append(a)
return rest, flag
# Flag first, then the environment, then the repo being graphed (the cwd's, by default).
def resolve_graph_dir(flag, root=None):
chosen = flag or os.environ.get("KINGS_GRAPH_DIR")
if chosen:
return os.path.abspath(os.path.expanduser(chosen))
root = root or git_root(os.getcwd())
if not root:
die("not inside a git repo — pass --graph DIR or set KINGS_GRAPH_DIR")
return os.path.join(root, "graphify-out")
# `graphify extract --out X` writes to X/graphify-out/, so both layouts are accepted.
def graph_file(graph_dir):
nested = os.path.join(graph_dir, "graphify-out", "graph.json")
direct = os.path.join(graph_dir, "graph.json")
return nested if not os.path.exists(direct) and os.path.exists(nested) else direct
def source_file_path(graph_path):
return os.path.join(os.path.dirname(graph_path), "SOURCE.json")
# Older layouts kept SOURCE.json next to graphify-out/, not inside it. Read-only fallback:
# `update` always stamps next to graph.json.
def existing_source_file(graph_path):
here = source_file_path(graph_path)
graph_dir = os.path.dirname(graph_path)
parent = os.path.join(os.path.dirname(graph_dir), "SOURCE.json")
if not os.path.exists(here) and os.path.basename(graph_dir) == "graphify-out" and os.path.exists(parent):
return parent
return here
# ------------------------------------------------------------------------------------ load
class Graph:
def __init__(self, path):
with open(path) as fh:
self.raw = json.load(fh)
self.path = path
self.nodes = [n for n in self.raw["nodes"] if n.get("file_type", "code") == "code"]
# graph.json names the edge list `edges`, or `links` in the networkx node-link format.
self.edges = self.raw.get("edges") or self.raw.get("links") or []
self.by_id = {n["id"]: n for n in self.nodes}
self.out = defaultdict(list)
self.inn = defaultdict(list)
for e in self.edges:
self.out[e["source"]].append(e)
self.inn[e["target"]].append(e)
# Node metadata doesn't tell a Swift protocol from a class, but only a protocol is
# ever the TARGET of `implements`.
self.protocols = {e["target"] for e in self.edges if e["relation"] == "implements"}
self.extensions = sorted({os.path.splitext(n["source_file"])[1] for n in self.nodes
if n.get("source_file") and os.path.splitext(n["source_file"])[1]})
def label(self, nid):
return self.by_id.get(nid, {}).get("label", nid)
def defined(self, nid):
return bool(self.by_id.get(nid, {}).get("source_file"))
def kind(self, nid):
return "protocol" if nid in self.protocols else "class/struct"
def is_swift(self):
return ".swift" in self.extensions
# A type name is almost always unique; a method name never is.
def resolve(self, name):
exact = [n for n in self.nodes if n["label"] == name and n.get("source_file")]
if exact:
return exact
target = name.lower()
return [n for n in self.nodes if target in n["label"].lower() and n.get("source_file")]
def load_graph(graph_dir):
path = graph_file(graph_dir)
if not os.path.exists(path):
die(f"graph not found at {path}\nRun: kings graph update")
return Graph(path)
def pick(g, name):
hits = g.resolve(name)
if not hits:
die(f"nothing found for '{name}'. Try: kings graph find {name}")
if len(hits) > 1 and not any(n["label"] == name for n in hits):
lines = [f"! '{name}' is ambiguous — {len(hits)} candidates:"]
lines += [f" {n['label']:40} {n['source_file']}:{n['source_location']}" for n in hits[:15]]
die("\n".join(lines))
exact = [n for n in hits if n["label"] == name]
return (exact or hits)[0]
def line_of(edge):
m = re.match(r"L(\d+)", edge.get("source_location") or "")
return int(m.group(1)) if m else 0
# ------------------------------------------------------------------------------- staleness
def repo_state(target):
return {
"branch": git("rev-parse", "--abbrev-ref", "HEAD", cwd=target),
"commit": git("rev-parse", "HEAD", cwd=target),
"commit_date": git("log", "-1", "--format=%ci", cwd=target),
}
# SOURCE.json comes from `kings graph update`; graphify's own `built_at_commit` is the fallback.
def read_source(g):
path = existing_source_file(g.path)
if os.path.exists(path):
with open(path) as fh:
return json.load(fh)
if g.raw.get("built_at_commit"):
return {"commit": g.raw["built_at_commit"], "branch": "?",
"generated_at": "graphify stamp, no SOURCE.json",
"target": git_root(os.path.dirname(g.path))}
return None
def count_lines(text):
return len([x for x in (text or "").splitlines() if x])
# Always printed: a graph behind the working tree is the normal case, and whoever reads the
# answer has to know it.
def staleness_lines(g):
src = read_source(g)
if src is None:
return ["! graph has no SOURCE.json — origin unknown. Run: kings graph update"]
target = src.get("target")
if not target or not os.path.isdir(os.path.join(target, ".git")):
return [f"! graph source path no longer exists: {target} — staleness unknown"]
now = repo_state(target)
out = [f"graph generated from {src.get('branch')} @ {(src.get('commit') or '?')[:10]}"
f" ({src.get('generated_at')}) [{target}]"]
if not now["commit"]:
out.append(f"! could not read git in {target} — staleness unknown")
return out
specs = [f"*{ext}" for ext in g.extensions]
kinds = "/".join(g.extensions) or "source"
if now["commit"] == src.get("commit"):
out.append("working tree is AT THE SAME commit as the graph")
else:
ahead = git("rev-list", "--count", f"{src['commit']}..HEAD", cwd=target)
behind = git("rev-list", "--count", f"HEAD..{src['commit']}", cwd=target)
changed = count_lines(git("diff", "--name-only", f"{src['commit']}..HEAD", "--", *specs,
cwd=target))
out.append(f"! working tree is at {now['branch']} @ {now['commit'][:10]}"
f" — {ahead or '?'} commit(s) ahead, {behind or '?'} behind")
if changed:
out.append(f"! {changed} {kinds} file(s) changed since generation"
f" — treat the graph as a HINT, confirm in the code")
dirty = count_lines(git("status", "--porcelain", "--", *specs, cwd=target))
if dirty:
out.append(f"! {dirty} {kinds} file(s) modified and uncommitted — invisible to the graph")
return out
def print_header(g):
for line in staleness_lines(g):
print(f"# {line}")
print()
# ------------------------------------------------------------------------------------ deps
# Exists because `graphify explain <Type>` doesn't roll up method parameters: looking only at
# the type's node, a dependency injected through the init seems not to exist.
def cmd_deps(g, name):
n = pick(g, name)
nid = n["id"]
if not g.is_swift():
print("# ! deps is tuned for Swift projects — here the stored vs init-only split"
" is unreliable\n")
print(f"## {n['label']} [{g.kind(nid)}]")
print(f" {n['source_file']}:{n['source_location']}\n")
parents = [e for e in g.out[nid] if e["relation"] in ("inherits", "implements")]
if parents:
print("### Inherits / conforms")
for e in parents:
print(f" {e['relation']:11} {g.label(e['target']):38} {e.get('source_location')}")
print()
stored = {e["target"]: e for e in g.out[nid]
if e.get("context") == "field" and g.defined(e["target"])}
inits = [e["target"] for e in g.out[nid]
if e["relation"] == "method" and g.label(e["target"]) in INIT_LABELS]
params, built = {}, []
for init in inits:
for e in g.out[init]:
if not g.defined(e["target"]):
continue
if e.get("context") == "parameter_type":
params[e["target"]] = e
elif e["relation"] == "calls" and not g.label(e["target"]).startswith("."):
built.append(e)
print("### Dependencies to mock")
if not stored and not params:
print(" (no dependency on a type defined in the project)")
for tid, e in sorted(stored.items(), key=lambda kv: line_of(kv[1])):
mark = "" if tid in params else " [not from init]"
print(f" stored {g.label(tid):36} {g.kind(tid):14}"
f" {e.get('source_location'):6}{mark}")
for tid, e in sorted(params.items(), key=lambda kv: line_of(kv[1])):
if tid in stored:
continue
print(f" INIT ONLY {g.label(tid):36} {g.kind(tid):14}"
f" {e.get('source_location'):6} <-- not a property:"
f" singleton or used to build another")
print()
if built:
print("### Built inside the init (fallback / default)")
for e in sorted(built, key=line_of):
print(f" {g.label(e['target']):38} {e.get('source_location')}")
print()
deps = {**stored, **params}
if deps:
print("### Contract width — who else consumes each dependency")
for tid in deps:
files = {x.get("source_file") for x in g.inn[tid] if x.get("source_file")}
files.discard(n["source_file"])
print(f" {g.label(tid):38} {len(files)} other file(s)")
for f in sorted(files)[:6]:
print(f" {f}")
if len(files) > 6:
print(f" ... +{len(files) - 6}")
print()
tests = set()
for tid in list(deps) + [nid]:
for x in g.inn[tid] + g.out[tid]:
f = x.get("source_file") or ""
if TEST_MARKERS.search(f):
tests.add(f)
print("### Any test/mock already touching this?")
for f in sorted(tests):
print(f" {f}")
if not tests:
print(" nothing found in the graph — probably doesn't exist yet")
print()
methods = sorted([e for e in g.out[nid] if e["relation"] == "method"], key=line_of)
print(f"### Methods ({len(methods)}) — scenario candidates")
for e in methods:
print(f" {g.label(e['target']):38} {e.get('source_location')}")
print()
users = defaultdict(list)
for e in g.inn[nid]:
if e.get("source_file") and e["source_file"] != n["source_file"]:
users[e["source_file"]].append(e)
if users:
print(f"### Who uses {n['label']} ({len(users)} file(s))")
for f, es in sorted(users.items()):
locs = ", ".join(sorted({str(e.get("source_location")) for e in es}))
print(f" {f} [{locs}]")
print()
print("> The graph doesn't tell BEHAVIOR, which overload is called, or which value")
print("> reaches the mock. Reading the production code is still required.")
# ---------------------------------------------------------------------------------- impact
# Walks incoming edges level by level, so the result reads as "who breaks, and how far away".
def cmd_impact(g, name, depth=2):
n = pick(g, name)
spread = ("calls", "references", "inherits", "implements", "imports", "uses")
seen, frontier, level = {n["id"]}, [n["id"]], 0
found = []
while frontier and level < depth:
level += 1
following = []
for nid in frontier:
for e in g.inn[nid]:
if e["relation"] in spread and e["source"] not in seen:
seen.add(e["source"])
following.append(e["source"])
found.append((level, e))
frontier = following
print(f"## Blast radius of {n['label']} (depth {depth})")
print(f" {n['source_file']}:{n['source_location']}\n")
by_module = defaultdict(list)
for level, e in found:
f = e.get("source_file") or "?"
by_module["/".join(f.split("/")[:3])].append((level, e))
for mod in sorted(by_module, key=lambda m: -len(by_module[m])):
items = by_module[mod]
print(f"### {mod} ({len(items)})")
for level, e in sorted(items, key=lambda x: (x[0], x[1].get("source_file") or "")):
print(f" d{level} {e['relation']:11} {g.label(e['source']):36}"
f" {e.get('source_file')}:{e.get('source_location')}")
print()
if not found:
print(" nothing depends on this in the graph")
# ------------------------------------------------------------------------------------ find
def cmd_find(g, pattern):
target = pattern.lower()
hits = [n for n in g.nodes if target in n["label"].lower()]
defined = [n for n in hits if n.get("source_file")]
print(f"## '{pattern}' — {len(defined)} node(s) with a definition"
f" ({len(hits) - len(defined)} placeholder(s) omitted)\n")
for n in sorted(defined, key=lambda n: n["label"])[:60]:
mark = " [protocol]" if n["id"] in g.protocols else ""
print(f" {n['label']:44}{mark}")
print(f" {n['source_file']}:{n['source_location']}")
print(f" id={n['id']}")
if len(defined) > 60:
print(f"\n ... +{len(defined) - 60}. Refine the pattern.")
# ------------------------------------------------------------------------------------ info
def cmd_info(graph_dir):
path = graph_file(graph_dir)
if not os.path.exists(path):
print(f"graph missing: {path}")
return
g = Graph(path)
for line in staleness_lines(g):
print(line)
mb = os.path.getsize(path) / 1024 / 1024
print(f"\n{len(g.raw['nodes'])} nodes · {len(g.edges)} edges · {mb:.0f} MB")
print(f"LLM tokens spent: {g.raw.get('input_tokens', 0)} in"
f" / {g.raw.get('output_tokens', 0)} out")
print(f"\ngraph: {path}")
# ---------------------------------------------------------------------------------- update
def find_graphify():
exe = shutil.which("graphify")
fallback = os.path.expanduser("~/.local/bin/graphify")
if not exe and os.path.exists(fallback):
exe = fallback
if not exe:
die("graphify not found on PATH\nInstall with: uv tool install graphifyy")
return exe
def has_extract(exe):
out = subprocess.run([exe, "--help"], capture_output=True, text=True)
return re.search(r"^\s+extract\b", out.stdout + out.stderr, re.M) is not None
def warn(message):
print(message, file=sys.stderr)
# `extract` is pure AST parsing with zero LLM tokens; clustering is the only step that costs.
def run_extract(exe, target, graph_dir):
out_base = os.path.dirname(graph_dir) if os.path.basename(graph_dir) == "graphify-out" else graph_dir
rc = subprocess.run(
[exe, "extract", target, "--code-only", "--no-cluster", "--out", out_base],
stdout=sys.stderr,
).returncode
if rc != 0:
die(f"\ngraphify extract failed (rc={rc}) — SOURCE.json was not updated")
move_leaked_cache(target, os.path.join(out_base, "graphify-out"))
# `extract` also writes a graphify-out/cache/ inside the target itself, besides --out — that's
# generated clutter in the target repo, so it's moved next to the graph.
def move_leaked_cache(target, out_dir):
leaked = os.path.join(target, "graphify-out")
if not os.path.isdir(leaked) or os.path.realpath(leaked) == os.path.realpath(out_dir):
return
leaked_cache = os.path.join(leaked, "cache")
if os.path.isdir(leaked_cache):
cache = os.path.join(out_dir, "cache")
os.makedirs(cache, exist_ok=True)
for name in os.listdir(leaked_cache):
os.replace(os.path.join(leaked_cache, name), os.path.join(cache, name))
shutil.rmtree(leaked)
warn(f"! graphify-out/ leaked into {target} — moved next to the graph and removed there\n")
# Older graphify has no `extract`; its `update` only writes to <target>/graphify-out.
def check_legacy_target(target, graph_dir):
if os.path.realpath(graph_dir) != os.path.realpath(os.path.join(target, "graphify-out")):
die("this graphify has no `extract`, and its `update` can only write to"
f" {target}/graphify-out\nUpgrade with: uv tool upgrade graphifyy")
def run_legacy_update(exe, target):
rc = subprocess.run([exe, "update", target], stdout=sys.stderr).returncode
if rc != 0:
die(f"\ngraphify update failed (rc={rc}) — SOURCE.json was not updated")
def stamp_source(graph_dir, state, target, command):
if not os.path.exists(graph_file(graph_dir)):
die(f"graphify finished but no graph.json in {graph_dir} — SOURCE.json was not updated")
state["generated_at"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
state["target"] = target
state["command"] = command
path = source_file_path(graph_file(graph_dir))
with open(path, "w") as fh:
json.dump(state, fh, indent=2)
fh.write("\n")
print(f"SOURCE.json stamped: {state['branch']} @ {(state['commit'] or '?')[:10]} ({path})")
def cmd_update(graph_flag, target):
target = os.path.abspath(os.path.expanduser(target)) if target else git_root(os.getcwd())
if not target or not os.path.isdir(os.path.join(target, ".git")):
die(f"{target or os.getcwd()} doesn't look like a git repo")
graph_dir = resolve_graph_dir(graph_flag, target)
exe = find_graphify()
extract = has_extract(exe)
if not extract:
check_legacy_target(target, graph_dir)
state = repo_state(target)
dirty = count_lines(git("status", "--porcelain", cwd=target))
if dirty:
warn(f"! {dirty} file(s) modified and uncommitted.")
warn("! The graph will reflect the working tree, not the stamped commit.\n")
warn(f"generating from {target}\n{state['branch']} @ {(state['commit'] or '?')[:10]}\n")
os.makedirs(graph_dir, exist_ok=True)
if extract:
run_extract(exe, target, graph_dir)
stamp_source(graph_dir, state, target, "graphify extract --code-only --no-cluster")
else:
run_legacy_update(exe, target)
stamp_source(graph_dir, state, target, "graphify update")
# ------------------------------------------------------------------------------------ main
def main():
args, graph_flag = split_graph_flag(sys.argv[1:])
cmd, rest = (args[0], args[1:]) if args else (None, [])
if cmd in (None, "-h", "--help", "help"):
print(USAGE)
sys.exit(0 if cmd else 1)
if cmd == "update":
cmd_update(graph_flag, rest[0] if rest else None)
return
if cmd not in ("info", "deps", "impact", "find") or (cmd != "info" and not rest):
die(USAGE)
graph_dir = resolve_graph_dir(graph_flag)
if cmd == "info":
cmd_info(graph_dir)
return
g = load_graph(graph_dir)
print_header(g)
if cmd == "deps":
cmd_deps(g, rest[0])
elif cmd == "impact":
cmd_impact(g, rest[0], int(rest[1]) if len(rest) > 1 else 2)
elif cmd == "find":
cmd_find(g, rest[0])
if __name__ == "__main__":
main()