ctxloop 0.3.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.
- ctxloop/__init__.py +2 -0
- ctxloop/__main__.py +4 -0
- ctxloop-0.3.0.dist-info/METADATA +551 -0
- ctxloop-0.3.0.dist-info/RECORD +33 -0
- ctxloop-0.3.0.dist-info/WHEEL +5 -0
- ctxloop-0.3.0.dist-info/entry_points.txt +3 -0
- ctxloop-0.3.0.dist-info/licenses/LICENSE +202 -0
- ctxloop-0.3.0.dist-info/licenses/NOTICE +7 -0
- ctxloop-0.3.0.dist-info/top_level.txt +2 -0
- graphsnip/__init__.py +3 -0
- graphsnip/__main__.py +4 -0
- graphsnip/ab.py +211 -0
- graphsnip/baseline.py +89 -0
- graphsnip/bench.py +208 -0
- graphsnip/cli.py +591 -0
- graphsnip/dashboard.py +765 -0
- graphsnip/engine.py +576 -0
- graphsnip/hooks.py +178 -0
- graphsnip/installer.py +445 -0
- graphsnip/ledger.py +107 -0
- graphsnip/mcp_server.py +305 -0
- graphsnip/memory_client.py +66 -0
- graphsnip/memory_eval.py +51 -0
- graphsnip/probe.py +83 -0
- graphsnip/project.py +503 -0
- graphsnip/py.typed +0 -0
- graphsnip/retrieval.py +77 -0
- graphsnip/router.py +175 -0
- graphsnip/semantic.py +335 -0
- graphsnip/shellfilter.py +116 -0
- graphsnip/slicer.py +217 -0
- graphsnip/tokens.py +35 -0
- graphsnip/usage.py +73 -0
graphsnip/project.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
"""Project: where the Graphify graph lives, how to (re)build it, how to load it."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
from collections import Counter
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
CODE_EXTS = {
|
|
16
|
+
".py", ".pyi", ".js", ".jsx", ".mjs", ".cjs", ".ts", ".tsx", ".go", ".rs", ".java",
|
|
17
|
+
".c", ".h", ".cc", ".cpp", ".hpp", ".rb", ".cs", ".kt", ".kts", ".scala", ".php",
|
|
18
|
+
".swift", ".lua", ".sh", ".bash", ".zig", ".ex", ".exs", ".vue", ".svelte",
|
|
19
|
+
}
|
|
20
|
+
IGNORE_DIRS = {
|
|
21
|
+
".git", "node_modules", "venv", ".venv", "env", "__pycache__", "dist", "build",
|
|
22
|
+
"graphify-out", ".graphsnip", ".next", ".nuxt", "target", "vendor", ".tox",
|
|
23
|
+
".mypy_cache", ".pytest_cache", ".idea", ".vscode", "coverage", ".gradle", "Pods",
|
|
24
|
+
}
|
|
25
|
+
MAX_FILE_BYTES = 400_000
|
|
26
|
+
_LOC_RE = re.compile(r"L(\d+)")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class GraphError(RuntimeError):
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def parse_line(loc) -> int | None:
|
|
34
|
+
m = _LOC_RE.match(str(loc or ""))
|
|
35
|
+
return int(m.group(1)) if m else None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Project:
|
|
39
|
+
def __init__(self, root: str | os.PathLike = "."):
|
|
40
|
+
self.root = Path(root).resolve()
|
|
41
|
+
self.graph_dir = self.root / "graphify-out"
|
|
42
|
+
self.graph_json = self.graph_dir / "graph.json"
|
|
43
|
+
self.graph_html = self.graph_dir / "graph.html"
|
|
44
|
+
self.report_md = self.graph_dir / "GRAPH_REPORT.md"
|
|
45
|
+
self.gs_dir = self.root / ".graphsnip"
|
|
46
|
+
self._graph = None
|
|
47
|
+
self._graph_mtime = 0.0
|
|
48
|
+
self._files: list[Path] | None = None
|
|
49
|
+
self._labels: dict[str, list[str]] | None = None
|
|
50
|
+
self._last_stale_check = 0.0
|
|
51
|
+
self._last_stale = False
|
|
52
|
+
|
|
53
|
+
# ---------- config ----------
|
|
54
|
+
def config(self) -> dict:
|
|
55
|
+
cfg = {
|
|
56
|
+
"mode": "nudge", # nudge | strict | off
|
|
57
|
+
"read_threshold_tokens": 1500, # hook: files bigger than this get redirected
|
|
58
|
+
"shell_filter": False, # hook: opt-in rewrite of noisy shell commands
|
|
59
|
+
"price_per_mtok": 3.0, # USD per million input tokens, for the cost estimate
|
|
60
|
+
}
|
|
61
|
+
p = self.gs_dir / "config.json"
|
|
62
|
+
try:
|
|
63
|
+
if p.exists():
|
|
64
|
+
cfg.update(json.loads(p.read_text(encoding="utf-8")))
|
|
65
|
+
except Exception:
|
|
66
|
+
pass
|
|
67
|
+
if os.environ.get("GRAPHSNIP_MODE"):
|
|
68
|
+
cfg["mode"] = os.environ["GRAPHSNIP_MODE"]
|
|
69
|
+
if os.environ.get("GRAPHSNIP_PRICE_PER_MTOK"):
|
|
70
|
+
try:
|
|
71
|
+
cfg["price_per_mtok"] = float(os.environ["GRAPHSNIP_PRICE_PER_MTOK"])
|
|
72
|
+
except ValueError:
|
|
73
|
+
pass
|
|
74
|
+
return cfg
|
|
75
|
+
|
|
76
|
+
def write_default_config(self) -> Path:
|
|
77
|
+
self.gs_dir.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
p = self.gs_dir / "config.json"
|
|
79
|
+
if not p.exists():
|
|
80
|
+
default = {
|
|
81
|
+
"mode": "nudge",
|
|
82
|
+
"read_threshold_tokens": 1500,
|
|
83
|
+
"shell_filter": False,
|
|
84
|
+
"price_per_mtok": 3.0,
|
|
85
|
+
}
|
|
86
|
+
p.write_text(json.dumps(default, indent=2) + "\n", encoding="utf-8")
|
|
87
|
+
return p
|
|
88
|
+
|
|
89
|
+
# ---------- files ----------
|
|
90
|
+
def files(self) -> list[Path]:
|
|
91
|
+
if self._files is not None:
|
|
92
|
+
return self._files
|
|
93
|
+
out: list[Path] = []
|
|
94
|
+
try:
|
|
95
|
+
r = subprocess.run(
|
|
96
|
+
["git", "-C", str(self.root), "ls-files", "-z", "--cached", "--others", "--exclude-standard"],
|
|
97
|
+
capture_output=True, timeout=30,
|
|
98
|
+
)
|
|
99
|
+
if r.returncode == 0 and r.stdout:
|
|
100
|
+
for rel in r.stdout.decode("utf-8", "replace").split("\0"):
|
|
101
|
+
if not rel:
|
|
102
|
+
continue
|
|
103
|
+
p = self.root / rel
|
|
104
|
+
if p.suffix.lower() in CODE_EXTS and not (set(p.relative_to(self.root).parts) & IGNORE_DIRS):
|
|
105
|
+
out.append(p)
|
|
106
|
+
except Exception:
|
|
107
|
+
pass
|
|
108
|
+
if not out:
|
|
109
|
+
for dp, dns, fns in os.walk(self.root):
|
|
110
|
+
dns[:] = [d for d in dns if d not in IGNORE_DIRS]
|
|
111
|
+
for fn in fns:
|
|
112
|
+
p = Path(dp) / fn
|
|
113
|
+
if p.suffix.lower() in CODE_EXTS:
|
|
114
|
+
out.append(p)
|
|
115
|
+
out = [p for p in out if p.is_file()]
|
|
116
|
+
self._files = sorted(out)
|
|
117
|
+
return self._files
|
|
118
|
+
|
|
119
|
+
def rel(self, p: Path | str) -> str:
|
|
120
|
+
p = Path(p)
|
|
121
|
+
try:
|
|
122
|
+
return p.resolve().relative_to(self.root).as_posix()
|
|
123
|
+
except Exception:
|
|
124
|
+
return str(p).replace("\\", "/")
|
|
125
|
+
|
|
126
|
+
def read(self, rel: str) -> str | None:
|
|
127
|
+
p = (self.root / rel)
|
|
128
|
+
try:
|
|
129
|
+
if p.stat().st_size > MAX_FILE_BYTES * 3:
|
|
130
|
+
return None
|
|
131
|
+
return p.read_text(encoding="utf-8", errors="replace")
|
|
132
|
+
except Exception:
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
# ---------- graph build / load ----------
|
|
136
|
+
def has_graph(self) -> bool:
|
|
137
|
+
return self.graph_json.exists()
|
|
138
|
+
|
|
139
|
+
def _run_graphify(self, *args: str, timeout: int = 900) -> subprocess.CompletedProcess:
|
|
140
|
+
return subprocess.run(
|
|
141
|
+
[sys.executable, "-m", "graphify", *args],
|
|
142
|
+
capture_output=True, text=True, timeout=timeout, cwd=str(self.root),
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
def build(self, force: bool = False) -> dict:
|
|
146
|
+
"""Build or refresh the Graphify graph (code only, no LLM) and regenerate
|
|
147
|
+
graph.html + GRAPH_REPORT.md. Returns a small summary dict."""
|
|
148
|
+
t0 = time.time()
|
|
149
|
+
first = not self.has_graph() or force
|
|
150
|
+
args = ["extract", str(self.root), "--code-only"]
|
|
151
|
+
if force:
|
|
152
|
+
args.append("--force")
|
|
153
|
+
if first:
|
|
154
|
+
r = self._run_graphify(*args)
|
|
155
|
+
else:
|
|
156
|
+
r = self._run_graphify("update", str(self.root))
|
|
157
|
+
if r.returncode != 0: # fall back to a full extract
|
|
158
|
+
r = self._run_graphify(*args)
|
|
159
|
+
if r.returncode != 0 or not self.has_graph():
|
|
160
|
+
raise GraphError(f"graphify failed (exit {r.returncode}):\n{(r.stderr or r.stdout)[-1500:]}")
|
|
161
|
+
r2 = self._run_graphify("cluster-only", str(self.root), "--no-label")
|
|
162
|
+
if r2.returncode != 0:
|
|
163
|
+
# graph.json exists; html/report generation is best-effort
|
|
164
|
+
sys.stderr.write(f"[graphsnip] cluster-only warning: {(r2.stderr or r2.stdout)[-400:]}\n")
|
|
165
|
+
self._graph = None
|
|
166
|
+
self._labels = None
|
|
167
|
+
self._last_stale_check = 0.0
|
|
168
|
+
sem = self._post_build()
|
|
169
|
+
s = self.graph_stats()
|
|
170
|
+
if sem:
|
|
171
|
+
s["semantic"] = sem
|
|
172
|
+
s["seconds"] = round(time.time() - t0, 1)
|
|
173
|
+
s["mode"] = "full build" if first else "incremental update"
|
|
174
|
+
return s
|
|
175
|
+
|
|
176
|
+
# ---------- change detection (manifest: size, mtime, content hash per file) ----------
|
|
177
|
+
@property
|
|
178
|
+
def manifest_path(self) -> Path:
|
|
179
|
+
return self.gs_dir / "manifest.json"
|
|
180
|
+
|
|
181
|
+
def _load_manifest(self) -> dict | None:
|
|
182
|
+
try:
|
|
183
|
+
d = json.loads(self.manifest_path.read_text(encoding="utf-8"))
|
|
184
|
+
return d.get("files") if isinstance(d, dict) and d.get("v") == 1 else None
|
|
185
|
+
except Exception:
|
|
186
|
+
return None
|
|
187
|
+
|
|
188
|
+
@staticmethod
|
|
189
|
+
def _hash_file(p: Path) -> str:
|
|
190
|
+
h = hashlib.sha1()
|
|
191
|
+
try:
|
|
192
|
+
h.update(p.read_bytes())
|
|
193
|
+
except OSError:
|
|
194
|
+
return ""
|
|
195
|
+
return h.hexdigest()
|
|
196
|
+
|
|
197
|
+
def write_manifest(self) -> None:
|
|
198
|
+
self._files = None
|
|
199
|
+
files = {}
|
|
200
|
+
for p in self.files():
|
|
201
|
+
try:
|
|
202
|
+
st = p.stat()
|
|
203
|
+
except OSError:
|
|
204
|
+
continue
|
|
205
|
+
files[self.rel(p)] = [st.st_size, st.st_mtime_ns, self._hash_file(p)]
|
|
206
|
+
try:
|
|
207
|
+
self.gs_dir.mkdir(parents=True, exist_ok=True)
|
|
208
|
+
tmp = self.manifest_path.with_suffix(".tmp")
|
|
209
|
+
tmp.write_text(json.dumps({"v": 1, "built": time.time(), "files": files}), encoding="utf-8")
|
|
210
|
+
os.replace(tmp, self.manifest_path)
|
|
211
|
+
except OSError:
|
|
212
|
+
pass
|
|
213
|
+
|
|
214
|
+
def changes(self) -> dict | None:
|
|
215
|
+
"""Files added, modified or deleted since the graph was last built (None: no manifest yet).
|
|
216
|
+
A touched file whose content hash is unchanged (git checkout, formatter no-op) does not count."""
|
|
217
|
+
man = self._load_manifest()
|
|
218
|
+
if man is None:
|
|
219
|
+
return None
|
|
220
|
+
self._files = None
|
|
221
|
+
now: dict[str, Path] = {self.rel(p): p for p in self.files()}
|
|
222
|
+
added = [r for r in now if r not in man]
|
|
223
|
+
deleted = [r for r in man if r not in now]
|
|
224
|
+
modified, touched = [], False
|
|
225
|
+
for r, p in now.items():
|
|
226
|
+
old = man.get(r)
|
|
227
|
+
if not old:
|
|
228
|
+
continue
|
|
229
|
+
try:
|
|
230
|
+
st = p.stat()
|
|
231
|
+
except OSError:
|
|
232
|
+
continue
|
|
233
|
+
if st.st_size == old[0] and st.st_mtime_ns == old[1]:
|
|
234
|
+
continue
|
|
235
|
+
if self._hash_file(p) == old[2]:
|
|
236
|
+
man[r] = [st.st_size, st.st_mtime_ns, old[2]]
|
|
237
|
+
touched = True
|
|
238
|
+
else:
|
|
239
|
+
modified.append(r)
|
|
240
|
+
if touched and not (added or deleted or modified):
|
|
241
|
+
try:
|
|
242
|
+
self.manifest_path.write_text(json.dumps({"v": 1, "built": time.time(), "files": man}), encoding="utf-8")
|
|
243
|
+
except OSError:
|
|
244
|
+
pass
|
|
245
|
+
return {"added": added, "modified": modified, "deleted": deleted}
|
|
246
|
+
|
|
247
|
+
def is_stale(self, max_age_s: float = 20.0) -> bool:
|
|
248
|
+
"""True when the code changed since the graph was built (cheap, cached for a few seconds)."""
|
|
249
|
+
now = time.time()
|
|
250
|
+
if now - self._last_stale_check < max_age_s:
|
|
251
|
+
return self._last_stale
|
|
252
|
+
self._last_stale_check = now
|
|
253
|
+
if not self.has_graph():
|
|
254
|
+
self._last_stale = True
|
|
255
|
+
return True
|
|
256
|
+
ch = self.changes()
|
|
257
|
+
if ch is not None:
|
|
258
|
+
self._last_stale = bool(ch["added"] or ch["modified"] or ch["deleted"])
|
|
259
|
+
return self._last_stale
|
|
260
|
+
# no manifest yet (graph built by an older version): fall back to modification times once, then record a manifest
|
|
261
|
+
gm = self.graph_json.stat().st_mtime
|
|
262
|
+
stale = False
|
|
263
|
+
for p in self.files():
|
|
264
|
+
try:
|
|
265
|
+
if p.stat().st_mtime > gm + 1:
|
|
266
|
+
stale = True
|
|
267
|
+
break
|
|
268
|
+
except OSError:
|
|
269
|
+
continue
|
|
270
|
+
if not stale:
|
|
271
|
+
self.write_manifest()
|
|
272
|
+
self._last_stale = stale
|
|
273
|
+
return stale
|
|
274
|
+
|
|
275
|
+
def freshness(self) -> dict:
|
|
276
|
+
ch = self.changes() if self.has_graph() else None
|
|
277
|
+
age = time.time() - self.graph_json.stat().st_mtime if self.has_graph() else None
|
|
278
|
+
return {"graph_age_s": age, "changes": ch, "refreshing": self.refreshing()}
|
|
279
|
+
|
|
280
|
+
# ---------- cross-process refresh lock ----------
|
|
281
|
+
@property
|
|
282
|
+
def lock_path(self) -> Path:
|
|
283
|
+
return self.gs_dir / "refresh.lock"
|
|
284
|
+
|
|
285
|
+
def _lock_is_stale(self) -> bool:
|
|
286
|
+
try:
|
|
287
|
+
pid_s, ts_s = self.lock_path.read_text(encoding="utf-8").split()[:2]
|
|
288
|
+
if time.time() - float(ts_s) > 1800:
|
|
289
|
+
return True
|
|
290
|
+
if os.name == "posix":
|
|
291
|
+
try:
|
|
292
|
+
os.kill(int(pid_s), 0)
|
|
293
|
+
except ProcessLookupError:
|
|
294
|
+
return True
|
|
295
|
+
except (PermissionError, OSError):
|
|
296
|
+
return False
|
|
297
|
+
return False
|
|
298
|
+
except FileNotFoundError:
|
|
299
|
+
return False
|
|
300
|
+
except Exception:
|
|
301
|
+
return True
|
|
302
|
+
|
|
303
|
+
def try_lock(self) -> bool:
|
|
304
|
+
self.gs_dir.mkdir(parents=True, exist_ok=True)
|
|
305
|
+
for _ in range(2):
|
|
306
|
+
try:
|
|
307
|
+
fd = os.open(str(self.lock_path), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
|
308
|
+
os.write(fd, f"{os.getpid()} {time.time()}".encode())
|
|
309
|
+
os.close(fd)
|
|
310
|
+
return True
|
|
311
|
+
except FileExistsError:
|
|
312
|
+
if self._lock_is_stale():
|
|
313
|
+
try:
|
|
314
|
+
os.unlink(self.lock_path)
|
|
315
|
+
except OSError:
|
|
316
|
+
return False
|
|
317
|
+
continue
|
|
318
|
+
return False
|
|
319
|
+
except OSError:
|
|
320
|
+
return False
|
|
321
|
+
return False
|
|
322
|
+
|
|
323
|
+
def unlock(self) -> None:
|
|
324
|
+
try:
|
|
325
|
+
os.unlink(self.lock_path)
|
|
326
|
+
except OSError:
|
|
327
|
+
pass
|
|
328
|
+
|
|
329
|
+
def refreshing(self) -> bool:
|
|
330
|
+
return self.lock_path.exists() and not self._lock_is_stale()
|
|
331
|
+
|
|
332
|
+
def wait_unlocked(self, timeout: float = 900.0) -> bool:
|
|
333
|
+
t0 = time.time()
|
|
334
|
+
while self.refreshing():
|
|
335
|
+
if time.time() - t0 > timeout:
|
|
336
|
+
return False
|
|
337
|
+
time.sleep(0.5)
|
|
338
|
+
return True
|
|
339
|
+
|
|
340
|
+
def _post_build(self) -> dict | None:
|
|
341
|
+
"""Hooks that follow a successful graph refresh (the semantic index catches up on changed nodes)."""
|
|
342
|
+
self.write_manifest()
|
|
343
|
+
try:
|
|
344
|
+
from graphsnip import semantic
|
|
345
|
+
|
|
346
|
+
return semantic.refresh_if_enabled(self)
|
|
347
|
+
except Exception as e: # never let an optional layer break the graph
|
|
348
|
+
sys.stderr.write(f"[graphsnip] semantic refresh skipped: {type(e).__name__}: {e}\n")
|
|
349
|
+
return None
|
|
350
|
+
|
|
351
|
+
def refresh(self, background: bool = False) -> bool:
|
|
352
|
+
"""Rebuild the graph under the cross-process lock. False: another refresh is already running."""
|
|
353
|
+
if not self.try_lock():
|
|
354
|
+
return False
|
|
355
|
+
|
|
356
|
+
def run():
|
|
357
|
+
try:
|
|
358
|
+
self.build()
|
|
359
|
+
except GraphError as e:
|
|
360
|
+
sys.stderr.write(f"[graphsnip] refresh failed, using existing graph: {e}\n")
|
|
361
|
+
finally:
|
|
362
|
+
self.unlock()
|
|
363
|
+
|
|
364
|
+
if background:
|
|
365
|
+
threading.Thread(target=run, daemon=True, name="graphsnip-refresh").start()
|
|
366
|
+
else:
|
|
367
|
+
run()
|
|
368
|
+
return True
|
|
369
|
+
|
|
370
|
+
def ensure_graph(self, auto_refresh: bool = True, background: bool = False) -> None:
|
|
371
|
+
if not self.has_graph():
|
|
372
|
+
if self.try_lock():
|
|
373
|
+
try:
|
|
374
|
+
self.build()
|
|
375
|
+
finally:
|
|
376
|
+
self.unlock()
|
|
377
|
+
else: # another process is building the first graph: wait for it
|
|
378
|
+
self.wait_unlocked(900.0)
|
|
379
|
+
if not self.has_graph():
|
|
380
|
+
raise GraphError("The graph is still being built by another process. Try again shortly.")
|
|
381
|
+
elif auto_refresh and self.is_stale():
|
|
382
|
+
self._files = None
|
|
383
|
+
self.refresh(background=background)
|
|
384
|
+
|
|
385
|
+
def graph(self):
|
|
386
|
+
if not self.has_graph():
|
|
387
|
+
raise GraphError("No graph yet. Run `graphsnip build` (or `graphsnip init`).")
|
|
388
|
+
m = self.graph_json.stat().st_mtime
|
|
389
|
+
if self._graph is None or m != self._graph_mtime:
|
|
390
|
+
from graphify.serve import _read_graph # Graphify's own loader (size cap, edge direction)
|
|
391
|
+
|
|
392
|
+
last = None
|
|
393
|
+
for attempt in range(4): # the file can be mid-write while a background refresh finishes
|
|
394
|
+
try:
|
|
395
|
+
self._graph = _read_graph(str(self.graph_json))
|
|
396
|
+
last = None
|
|
397
|
+
break
|
|
398
|
+
except Exception as e:
|
|
399
|
+
last = e
|
|
400
|
+
if self._graph is not None:
|
|
401
|
+
return self._graph # keep serving the previous snapshot
|
|
402
|
+
time.sleep(0.5 * (attempt + 1))
|
|
403
|
+
if last is not None:
|
|
404
|
+
raise GraphError(f"could not read {self.graph_json}: {last}")
|
|
405
|
+
self._graph_mtime = self.graph_json.stat().st_mtime
|
|
406
|
+
self._labels = None
|
|
407
|
+
return self._graph
|
|
408
|
+
|
|
409
|
+
# ---------- graph helpers ----------
|
|
410
|
+
@staticmethod
|
|
411
|
+
def is_file_node(d: dict) -> bool:
|
|
412
|
+
lab = str(d.get("label", ""))
|
|
413
|
+
sf = str(d.get("source_file", ""))
|
|
414
|
+
return bool(sf) and (lab.endswith(tuple(CODE_EXTS)) or lab == sf or sf.endswith("/" + lab) or sf.endswith(lab))
|
|
415
|
+
|
|
416
|
+
def symbol_nodes(self):
|
|
417
|
+
"""Yield (nid, data) for real code symbols (not file/concept/rationale nodes)."""
|
|
418
|
+
G = self.graph()
|
|
419
|
+
for nid, d in G.nodes(data=True):
|
|
420
|
+
if d.get("file_type") != "code":
|
|
421
|
+
continue
|
|
422
|
+
if parse_line(d.get("source_location")) is None or not d.get("source_file"):
|
|
423
|
+
continue
|
|
424
|
+
if Path(str(d.get("source_file"))).suffix.lower() not in CODE_EXTS:
|
|
425
|
+
continue # toml / yaml / json config nodes are not code symbols
|
|
426
|
+
if self.is_file_node(d):
|
|
427
|
+
continue
|
|
428
|
+
yield nid, d
|
|
429
|
+
|
|
430
|
+
def display(self, nid: str) -> str:
|
|
431
|
+
"""'.make_response()' -> 'Flask.make_response()' using the owning class when known."""
|
|
432
|
+
G = self.graph()
|
|
433
|
+
lab = str(G.nodes[nid].get("label", nid))
|
|
434
|
+
if lab.startswith("."):
|
|
435
|
+
try:
|
|
436
|
+
for u, _v, d in G.in_edges(nid, data=True):
|
|
437
|
+
if d.get("relation") == "method":
|
|
438
|
+
owner = re.sub(r"\(\)\s*$", "", str(G.nodes[u].get("label", "")))
|
|
439
|
+
return f"{owner}{lab}"
|
|
440
|
+
except Exception:
|
|
441
|
+
pass
|
|
442
|
+
return lab
|
|
443
|
+
|
|
444
|
+
def label_index(self) -> dict[str, list[str]]:
|
|
445
|
+
"""lower-case bare label -> node ids (for hook lookups and quick resolution)."""
|
|
446
|
+
self.graph()
|
|
447
|
+
if self._labels is None:
|
|
448
|
+
idx: dict[str, list[str]] = {}
|
|
449
|
+
for nid, d in self.symbol_nodes():
|
|
450
|
+
key = bare(str(d.get("label", "")))
|
|
451
|
+
idx.setdefault(key, []).append(nid)
|
|
452
|
+
self._labels = idx
|
|
453
|
+
return self._labels
|
|
454
|
+
|
|
455
|
+
def outline_rows(self, rel: str) -> list[tuple[int, str, bool]]:
|
|
456
|
+
"""[(line, label, is_class)] for the symbols Graphify found in one file."""
|
|
457
|
+
rows = []
|
|
458
|
+
for _nid, d in self.symbol_nodes():
|
|
459
|
+
if str(d.get("source_file")) == rel:
|
|
460
|
+
rows.append((parse_line(d.get("source_location")) or 0, str(d.get("label")), bool(d.get("_callable_class"))))
|
|
461
|
+
rows.sort()
|
|
462
|
+
return rows
|
|
463
|
+
|
|
464
|
+
def graph_stats(self) -> dict:
|
|
465
|
+
G = self.graph()
|
|
466
|
+
langs: Counter = Counter()
|
|
467
|
+
n_sym = 0
|
|
468
|
+
for _nid, d in self.symbol_nodes():
|
|
469
|
+
n_sym += 1
|
|
470
|
+
langs[Path(str(d.get("source_file"))).suffix.lower() or "?"] += 1
|
|
471
|
+
comms = {d.get("community") for _n, d in G.nodes(data=True) if d.get("community") is not None}
|
|
472
|
+
return {
|
|
473
|
+
"nodes": G.number_of_nodes(),
|
|
474
|
+
"edges": G.number_of_edges(),
|
|
475
|
+
"symbols": n_sym,
|
|
476
|
+
"communities": len(comms),
|
|
477
|
+
"languages": dict(langs.most_common(8)),
|
|
478
|
+
"built_at_commit": G.graph.get("_built_at_commit"),
|
|
479
|
+
"graph_json": str(self.graph_json),
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
def top_symbols(self, n: int = 10, exclude_tests: bool = True) -> list[dict]:
|
|
483
|
+
G = self.graph()
|
|
484
|
+
rows = []
|
|
485
|
+
for nid, d in self.symbol_nodes():
|
|
486
|
+
sf = str(d.get("source_file"))
|
|
487
|
+
if exclude_tests and re.search(r"(^|/)(tests?|__tests__|spec|specs)(/|$)|test_|_test\.|\.test\.|\.spec\.", sf):
|
|
488
|
+
continue
|
|
489
|
+
try:
|
|
490
|
+
deg = G.degree(nid)
|
|
491
|
+
except Exception:
|
|
492
|
+
deg = 0
|
|
493
|
+
rows.append({"id": nid, "label": d.get("label"), "file": sf, "line": parse_line(d.get("source_location")),
|
|
494
|
+
"degree": deg, "community": d.get("community")})
|
|
495
|
+
rows.sort(key=lambda r: -r["degree"])
|
|
496
|
+
return rows[:n]
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def bare(label: str) -> str:
|
|
500
|
+
"""'Foo.bar()' -> 'foo.bar'; '.run()' -> 'run'; 'app_ctx()' -> 'app_ctx'."""
|
|
501
|
+
s = label.strip()
|
|
502
|
+
s = re.sub(r"\(.*\)\s*$", "", s)
|
|
503
|
+
return s.lstrip(".").lower()
|
graphsnip/py.typed
ADDED
|
File without changes
|
graphsnip/retrieval.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Keyword-only vs hybrid (keyword + semantic) retrieval on the same questions.
|
|
2
|
+
|
|
3
|
+
Run it on questions that do NOT use the code's own words (a `tasks.json` with `question` and `expect`):
|
|
4
|
+
a task counts as found when every expected string appears in what `gs_pack` returns.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
from graphsnip import semantic
|
|
13
|
+
from graphsnip.bench import load_tasks
|
|
14
|
+
from graphsnip.engine import Engine
|
|
15
|
+
from graphsnip.project import Project
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _arm(project: Project, question: str, expect: list[str], hybrid: bool) -> dict:
|
|
19
|
+
prev = os.environ.get("GRAPHSNIP_SEMANTIC")
|
|
20
|
+
if hybrid:
|
|
21
|
+
os.environ.pop("GRAPHSNIP_SEMANTIC", None)
|
|
22
|
+
else:
|
|
23
|
+
os.environ["GRAPHSNIP_SEMANTIC"] = "off"
|
|
24
|
+
try:
|
|
25
|
+
eng = Engine(project.root, source="bench", auto_refresh=False) # "bench" calls are kept out of the savings totals
|
|
26
|
+
r = eng.pack(question)
|
|
27
|
+
finally:
|
|
28
|
+
if prev is None:
|
|
29
|
+
os.environ.pop("GRAPHSNIP_SEMANTIC", None)
|
|
30
|
+
else:
|
|
31
|
+
os.environ["GRAPHSNIP_SEMANTIC"] = prev
|
|
32
|
+
text = r.text.lower() if r.ok else ""
|
|
33
|
+
found = [e for e in expect if e.lower() in text]
|
|
34
|
+
first = min((text.find(e.lower()) for e in found), default=-1)
|
|
35
|
+
return {"ok": r.ok, "found": len(found), "expected": len(expect), "hit": bool(expect) and len(found) == len(expect),
|
|
36
|
+
"tokens": r.returned if r.ok else 0, "first_at_pct": round(100 * first / max(len(text), 1)) if first >= 0 else None,
|
|
37
|
+
"retrieval": eng.last_retrieval}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def run_eval(root: str = ".", tasks_path: str | None = None, write: bool = True) -> dict:
|
|
41
|
+
p = Project(root)
|
|
42
|
+
if not semantic.has_index(p):
|
|
43
|
+
raise semantic.SemanticUnavailable("No semantic index yet. Run `graphsnip embed` first.")
|
|
44
|
+
p.ensure_graph(False)
|
|
45
|
+
rows = []
|
|
46
|
+
for t in load_tasks(p, tasks_path):
|
|
47
|
+
exp = [str(e) for e in (t.get("expect") or [])]
|
|
48
|
+
rows.append({"id": t.get("id"), "question": t["question"], "kind": t.get("kind", ""),
|
|
49
|
+
"keyword": _arm(p, t["question"], exp, False), "hybrid": _arm(p, t["question"], exp, True)})
|
|
50
|
+
n = len(rows)
|
|
51
|
+
kh = sum(r["keyword"]["hit"] for r in rows)
|
|
52
|
+
hh = sum(r["hybrid"]["hit"] for r in rows)
|
|
53
|
+
res = {
|
|
54
|
+
"ran_at": time.strftime("%Y-%m-%dT%H:%M:%S"), "model": semantic.status(p).get("model"), "tasks": rows,
|
|
55
|
+
"totals": {"n": n, "keyword_hits": kh, "hybrid_hits": hh, "gained": sum(1 for r in rows if r["hybrid"]["hit"] and not r["keyword"]["hit"]),
|
|
56
|
+
"lost": sum(1 for r in rows if r["keyword"]["hit"] and not r["hybrid"]["hit"]),
|
|
57
|
+
"keyword_tokens": sum(r["keyword"]["tokens"] for r in rows), "hybrid_tokens": sum(r["hybrid"]["tokens"] for r in rows)},
|
|
58
|
+
}
|
|
59
|
+
if write:
|
|
60
|
+
p.gs_dir.mkdir(parents=True, exist_ok=True)
|
|
61
|
+
(p.gs_dir / "retrieval.json").write_text(json.dumps(res, indent=2), encoding="utf-8")
|
|
62
|
+
return res
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def format_table(res: dict) -> str:
|
|
66
|
+
t = res["totals"]
|
|
67
|
+
out = [f"Retrieval: keyword vs hybrid ({res.get('model')}), {t['n']} questions", ""]
|
|
68
|
+
out.append(f" {'question':<56} {'keyword':>8} {'hybrid':>8}")
|
|
69
|
+
for r in res["tasks"]:
|
|
70
|
+
out.append(f" {r['question'][:55]:<56} {('found' if r['keyword']['hit'] else 'MISSED'):>8} {('found' if r['hybrid']['hit'] else 'MISSED'):>8}")
|
|
71
|
+
out.append("")
|
|
72
|
+
out.append(f" found: keyword {t['keyword_hits']}/{t['n']}, hybrid {t['hybrid_hits']}/{t['n']} "
|
|
73
|
+
f"(gained {t['gained']}, lost {t['lost']})")
|
|
74
|
+
out.append(f" tokens returned: keyword {t['keyword_tokens']:,}, hybrid {t['hybrid_tokens']:,}")
|
|
75
|
+
if t["lost"]:
|
|
76
|
+
out.append(" ! hybrid lost questions that keyword search found; do not ship this model or setting for this repo.")
|
|
77
|
+
return "\n".join(out)
|