claude-code-router 0.1.1__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.
Files changed (58) hide show
  1. ccr/__init__.py +0 -0
  2. ccr/__main__.py +4 -0
  3. ccr/cli.py +595 -0
  4. ccr/config.py +518 -0
  5. ccr/detect/__init__.py +123 -0
  6. ccr/doctor.py +208 -0
  7. ccr/entry.py +23 -0
  8. ccr/evaluate/__init__.py +13 -0
  9. ccr/evaluate/classify.py +335 -0
  10. ccr/evaluate/llm.py +182 -0
  11. ccr/evaluate/locate.py +359 -0
  12. ccr/evaluate/risk.py +285 -0
  13. ccr/evaluate/text.py +190 -0
  14. ccr/graph/__init__.py +15 -0
  15. ccr/graph/build.py +475 -0
  16. ccr/graph/db.py +88 -0
  17. ccr/graph/files.py +169 -0
  18. ccr/graph/git.py +90 -0
  19. ccr/graph/parse.py +510 -0
  20. ccr/graph/query.py +359 -0
  21. ccr/graph/resolve.py +256 -0
  22. ccr/headless.py +363 -0
  23. ccr/history/__init__.py +172 -0
  24. ccr/history/calibrate.py +161 -0
  25. ccr/history/dashboard.py +374 -0
  26. ccr/history/feedback.py +91 -0
  27. ccr/history/learn.py +184 -0
  28. ccr/history/prompts.py +120 -0
  29. ccr/history/redact.py +45 -0
  30. ccr/history/savings.py +187 -0
  31. ccr/history/shadow.py +114 -0
  32. ccr/history/stats.py +172 -0
  33. ccr/history/tune.py +80 -0
  34. ccr/history/why.py +186 -0
  35. ccr/hooks/__init__.py +134 -0
  36. ccr/hooks/bg.py +68 -0
  37. ccr/hooks/common.py +159 -0
  38. ccr/hooks/prompt.py +322 -0
  39. ccr/hooks/session_start.py +91 -0
  40. ccr/hooks/stop.py +52 -0
  41. ccr/hooks/tasks.py +170 -0
  42. ccr/install/__init__.py +388 -0
  43. ccr/install/agents.py +200 -0
  44. ccr/install/command.py +159 -0
  45. ccr/install/settings.py +175 -0
  46. ccr/memory/__init__.py +87 -0
  47. ccr/memory/signals.py +210 -0
  48. ccr/memory/sources.py +422 -0
  49. ccr/report.py +40 -0
  50. ccr/route/__init__.py +527 -0
  51. ccr/route/budget.py +166 -0
  52. ccr/statusline.py +143 -0
  53. ccr/transcript.py +98 -0
  54. claude_code_router-0.1.1.dist-info/METADATA +291 -0
  55. claude_code_router-0.1.1.dist-info/RECORD +58 -0
  56. claude_code_router-0.1.1.dist-info/WHEEL +4 -0
  57. claude_code_router-0.1.1.dist-info/entry_points.txt +2 -0
  58. claude_code_router-0.1.1.dist-info/licenses/LICENSE +21 -0
ccr/graph/build.py ADDED
@@ -0,0 +1,475 @@
1
+ """Build / incrementally update .ccr/graph.db."""
2
+ from __future__ import annotations
3
+
4
+ import contextlib
5
+ import logging
6
+ import os
7
+ import stat as stat_mod
8
+ import time
9
+ from collections import defaultdict
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+
13
+ from ccr.graph import db as gdb
14
+ from ccr.graph import git as ggit
15
+ from ccr.graph.files import (AUX_NAMES, family_of, in_skipped_dir, is_code, is_test_path,
16
+ walk_files)
17
+ from ccr.graph.parse import init_worker, parse_file
18
+ from ccr.graph.resolve import Resolver
19
+
20
+ log = logging.getLogger("ccr.graph")
21
+
22
+ PARALLEL_MIN = 200 # parse in a process pool above this many files
23
+ CHURN_DAYS = 180
24
+
25
+
26
+ @dataclass
27
+ class UpdateResult:
28
+ mode: str = "fs" # git | fs
29
+ full: bool = False # fresh database
30
+ scanned: int = 0 # code files discovered
31
+ checked: int = 0 # files read and hashed
32
+ parsed: int = 0 # files actually (re)parsed
33
+ unchanged: int = 0 # hashed but content identical
34
+ added: int = 0
35
+ removed: int = 0
36
+ parsed_files: list[str] = field(default_factory=list)
37
+ parsers: dict[str, int] = field(default_factory=dict)
38
+ churn_updated: bool = False
39
+ commit: str | None = None
40
+ elapsed: float = 0.0
41
+
42
+
43
+ # --------------------------------------------------------------------------- helpers
44
+ def _ts_languages(rels: list[str], offline: bool) -> tuple[dict[str, str | None], frozenset[str]]:
45
+ """Map rel -> tree-sitter language name and return the set usable without network."""
46
+ try:
47
+ import tree_sitter_language_pack as tslp
48
+ except Exception as e: # pragma: no cover - broken install
49
+ log.debug("tree-sitter-language-pack unavailable: %s", e)
50
+ return {r: None for r in rels}, frozenset()
51
+ langs: dict[str, str | None] = {}
52
+ for r in rels:
53
+ try:
54
+ langs[r] = tslp.detect_language_from_path(r)
55
+ except Exception:
56
+ log.debug("language detection failed for %s", r, exc_info=True)
57
+ langs[r] = None
58
+ try:
59
+ have = set(tslp.downloaded_languages())
60
+ except Exception:
61
+ log.debug("could not list downloaded grammars", exc_info=True)
62
+ have = set()
63
+ needed = {lang for lang in langs.values() if lang} - have
64
+ if needed and not offline:
65
+ try:
66
+ tslp.download(sorted(needed))
67
+ except Exception as e:
68
+ log.debug("grammar download failed (%s); falling back to regex", e)
69
+ with contextlib.suppress(Exception):
70
+ have = set(tslp.downloaded_languages())
71
+ return langs, frozenset(have)
72
+
73
+
74
+ def _parse_all(jobs: list[tuple], allowed: frozenset[str], workers: int | None) -> list[dict]:
75
+ if not jobs:
76
+ return []
77
+ n = workers if workers is not None else min(8, os.cpu_count() or 1)
78
+ if n > 1 and len(jobs) >= PARALLEL_MIN:
79
+ try:
80
+ from concurrent.futures import ProcessPoolExecutor
81
+ with ProcessPoolExecutor(max_workers=n, initializer=init_worker,
82
+ initargs=(allowed,)) as ex:
83
+ return list(ex.map(parse_file, jobs, chunksize=max(8, len(jobs) // (n * 8))))
84
+ except Exception as e: # pool cannot start (sandbox, frozen app): go sequential
85
+ log.debug("process pool failed (%s); parsing sequentially", e)
86
+ init_worker(allowed)
87
+ return [parse_file(j) for j in jobs]
88
+
89
+
90
+ def _temp_ids(conn, name: str, ids) -> None:
91
+ conn.execute(f"DROP TABLE IF EXISTS temp.{name}")
92
+ conn.execute(f"CREATE TEMP TABLE {name}(v PRIMARY KEY) WITHOUT ROWID")
93
+ conn.executemany(f"INSERT OR IGNORE INTO temp.{name} VALUES(?)", ((i,) for i in ids))
94
+
95
+
96
+ def _purge_file(conn, fid: int, names: set[str], drop_file: bool) -> None:
97
+ for (nm,) in conn.execute("SELECT name FROM nodes WHERE file_id = ?", (fid,)):
98
+ names.add(nm)
99
+ conn.execute("DELETE FROM edges WHERE src IN (SELECT id FROM nodes WHERE file_id = ?) "
100
+ "OR dst IN (SELECT id FROM nodes WHERE file_id = ?)", (fid, fid))
101
+ conn.execute("DELETE FROM edges WHERE src = ?", (fid,))
102
+ conn.execute("DELETE FROM refs WHERE file_id = ?", (fid,))
103
+ conn.execute("DELETE FROM imports WHERE file_id = ?", (fid,))
104
+ conn.execute("DELETE FROM nodes WHERE file_id = ?", (fid,))
105
+ if drop_file:
106
+ conn.execute("DELETE FROM edges WHERE dst = ?", (fid,))
107
+ conn.execute("UPDATE imports SET resolved_id = NULL WHERE resolved_id = ?", (fid,))
108
+ conn.execute("DELETE FROM nodes WHERE id = ?", (fid,))
109
+
110
+
111
+ def _read_aux(root: Path, rels: list[str]) -> dict[str, str]:
112
+ out = {}
113
+ for r in rels:
114
+ try:
115
+ out[r] = (root / r).read_text(encoding="utf-8", errors="ignore")[:20000]
116
+ except OSError:
117
+ continue
118
+ return out
119
+
120
+
121
+ # Families where code in the same directory shares a namespace without imports.
122
+ SAME_DIR_NS = frozenset({"go", "jvm", "csharp", "swift"})
123
+ # Families with a global namespace (includes/requires load everything); unique names link.
124
+ GLOBAL_NS = frozenset({"c", "ruby", "php", "shell", "elixir", "lua", "dart", "swift", "csharp"})
125
+ # Generic method names: a qualified x.close() across files is too ambiguous to link by name.
126
+ COMMON_METHODS = frozenset("""
127
+ open close get set put post delete patch run start stop read write update add append extend
128
+ insert remove pop push clear copy keys values items join split strip format execute fetch
129
+ fetchone fetchall commit rollback send recv call apply bind map filter reduce find index count
130
+ sort reverse load save dump dumps loads parse render init setup teardown reset next iter len str
131
+ repr eq hash then catch finally emit on off subscribe toString equals hashCode valueOf length size
132
+ contains has exists list create build make new error info debug warn warning log print
133
+ """.split())
134
+
135
+
136
+ def _load_call_inputs(conn, names: set[str] | None):
137
+ """Refs to resolve and the candidate symbols for them (deleting stale call edges)."""
138
+ cols = "r.id, r.file_id, r.caller_id, r.name, r.line, r.qual, f.path"
139
+ base = f"SELECT {cols} FROM refs r JOIN nodes f ON f.id = r.file_id"
140
+ if names is None:
141
+ conn.execute("DELETE FROM edges WHERE kind = 'calls'")
142
+ refs = conn.execute(base).fetchall()
143
+ syms = conn.execute("SELECT id, file_id, name, kind, path FROM nodes "
144
+ "WHERE kind != 'file'").fetchall()
145
+ return refs, syms
146
+ _temp_ids(conn, "aff_names", names)
147
+ conn.execute("DELETE FROM edges WHERE kind = 'calls' AND ref_id IN "
148
+ "(SELECT id FROM refs WHERE name IN (SELECT v FROM temp.aff_names))")
149
+ refs = conn.execute(base + " WHERE r.name IN (SELECT v FROM temp.aff_names)").fetchall()
150
+ syms = conn.execute("SELECT id, file_id, name, kind, path FROM nodes WHERE kind != 'file' "
151
+ "AND name IN (SELECT v FROM temp.aff_names)").fetchall()
152
+ return refs, syms
153
+
154
+
155
+ def _import_maps(conn, refs, names: set[str] | None):
156
+ """file -> files it imports, and file -> modules reached through barrel re-exports."""
157
+ imports: dict[int, set[int]] = defaultdict(set)
158
+ sql = "SELECT file_id, resolved_id FROM imports WHERE resolved_id IS NOT NULL"
159
+ if names is not None:
160
+ _temp_ids(conn, "ref_files", {r[1] for r in refs})
161
+ sql += " AND file_id IN (SELECT v FROM temp.ref_files)"
162
+ for fid, rid in conn.execute(sql):
163
+ imports[fid].add(rid)
164
+ # one hop through barrel files (__init__.py, index.ts, mod.rs) that re-export modules
165
+ barrels = {i for (i,) in conn.execute(
166
+ "SELECT id FROM nodes WHERE kind = 'file' AND (name LIKE '\\_\\_init\\_\\_.%' ESCAPE '\\' "
167
+ "OR name LIKE 'index.%' OR name = 'mod.rs')")}
168
+ used = {b for targets in imports.values() for b in targets if b in barrels}
169
+ reexports: dict[int, set[int]] = defaultdict(set)
170
+ if used:
171
+ _temp_ids(conn, "barrels", used)
172
+ via: dict[int, set[int]] = defaultdict(set)
173
+ for b, rid in conn.execute("SELECT file_id, resolved_id FROM imports WHERE resolved_id "
174
+ "IS NOT NULL AND file_id IN (SELECT v FROM temp.barrels)"):
175
+ via[b].add(rid)
176
+ for fid, targets in imports.items():
177
+ for b in targets:
178
+ reexports[fid] |= via.get(b, set())
179
+ return imports, reexports
180
+
181
+
182
+ def _pick(entries, qual: int) -> list[int]:
183
+ return [sid for sid, is_m in entries if qual or not is_m]
184
+
185
+
186
+ def _callee_hits(fid: int, nm: str, qual: int, rpath: str, files: dict, by_dir: dict,
187
+ plain: dict, imports: dict, reexports: dict) -> list[int]:
188
+ """Symbols a call to `nm` can reach, by tier: caller's file, imported files, barrel
189
+ re-exports, same directory, globally unique."""
190
+ hit = [sid for sid, _m in files.get(fid, ())]
191
+ if hit:
192
+ return hit
193
+ if qual and nm in COMMON_METHODS:
194
+ return []
195
+ # outside the caller's file, a bare call f() cannot reach a method
196
+ for t in imports.get(fid, ()):
197
+ if t in files:
198
+ hit += _pick(files[t], qual)
199
+ if not hit:
200
+ for t in reexports.get(fid, ()):
201
+ if t in files:
202
+ hit += _pick(files[t], qual)
203
+ fam = family_of(rpath)
204
+ if not hit and fam in SAME_DIR_NS:
205
+ rdir = rpath.rsplit("/", 1)[0] if "/" in rpath else ""
206
+ hit = _pick(by_dir[nm].get(rdir, ()), qual)
207
+ if not hit and not qual and fam in GLOBAL_NS and len(plain.get(nm, ())) == 1:
208
+ hit = plain[nm][:]
209
+ return hit
210
+
211
+
212
+ def _resolve_calls(conn, names: set[str] | None) -> None:
213
+ """(Re)compute call edges for refs whose callee name is in `names` (None = all).
214
+
215
+ Tiers, first hit wins: same file; files the caller imports; same directory (package-
216
+ scoped languages); globally unique name (global-namespace languages). Bare calls f()
217
+ never resolve to methods outside the caller's own file.
218
+ """
219
+ if names is not None and not names:
220
+ return
221
+ refs, syms = _load_call_inputs(conn, names)
222
+ if not refs:
223
+ return
224
+ # name -> file_id -> [(symbol id, is_method)], plus a per-directory index and global counts
225
+ by_file: dict[str, dict[int, list[tuple[int, bool]]]] = defaultdict(lambda: defaultdict(list))
226
+ by_dir: dict[str, dict[str, list[tuple[int, bool]]]] = defaultdict(lambda: defaultdict(list))
227
+ plain: dict[str, list[int]] = defaultdict(list) # non-method definitions per name
228
+ for sid, fid, nm, kind, spath in syms:
229
+ is_m = kind == "method"
230
+ by_file[nm][fid].append((sid, is_m))
231
+ by_dir[nm][spath.rsplit("/", 1)[0] if "/" in spath else ""].append((sid, is_m))
232
+ if not is_m:
233
+ plain[nm].append(sid)
234
+ imports, reexports = _import_maps(conn, refs, names)
235
+ rows = []
236
+ for ref_id, fid, caller, nm, line, qual, rpath in refs:
237
+ files = by_file.get(nm)
238
+ if not files:
239
+ continue
240
+ for sid in _callee_hits(fid, nm, qual, rpath, files, by_dir, plain, imports, reexports):
241
+ if sid != caller:
242
+ rows.append((caller, sid, "calls", line, ref_id))
243
+ conn.executemany("INSERT INTO edges(src, dst, kind, line, ref_id) VALUES(?,?,?,?,?)", rows)
244
+
245
+
246
+ def _rebuild_import_edges(conn, file_ids: set[int] | None) -> None:
247
+ sql = ("INSERT INTO edges(src, dst, kind, line) SELECT file_id, resolved_id, 'imports', "
248
+ "MIN(line) FROM imports WHERE resolved_id IS NOT NULL {w} GROUP BY file_id, resolved_id")
249
+ if file_ids is None:
250
+ conn.execute("DELETE FROM edges WHERE kind = 'imports'")
251
+ conn.execute(sql.format(w=""))
252
+ return
253
+ if not file_ids:
254
+ return
255
+ _temp_ids(conn, "imp_files", file_ids)
256
+ conn.execute("DELETE FROM edges WHERE kind = 'imports' AND src IN (SELECT v FROM temp.imp_files)")
257
+ conn.execute(sql.format(w="AND file_id IN (SELECT v FROM temp.imp_files)"))
258
+
259
+
260
+ @dataclass
261
+ class _Batch:
262
+ """Rows collected while ingesting parsed files, inserted in bulk afterwards."""
263
+ next_id: int
264
+ next_ref: int
265
+ sym_rows: list = field(default_factory=list)
266
+ edge_rows: list = field(default_factory=list)
267
+ ref_rows: list = field(default_factory=list)
268
+ imp_rows: list = field(default_factory=list)
269
+
270
+
271
+ def _stat_files(root: Path, rels: list[str]) -> dict[str, tuple[int, int]]:
272
+ stats: dict[str, tuple[int, int]] = {}
273
+ for rel in rels:
274
+ try:
275
+ st = os.lstat(root / rel)
276
+ except OSError:
277
+ continue
278
+ if stat_mod.S_ISREG(st.st_mode):
279
+ stats[rel] = (st.st_mtime_ns, st.st_size)
280
+ return stats
281
+
282
+
283
+ def _ingest(conn, r: dict, existing: dict, resolver: Resolver, names: set[str],
284
+ import_dirty: set[int], batch: _Batch, res: UpdateResult) -> None:
285
+ """Write one parsed file's node and queue its symbols, refs and imports."""
286
+ rel, status = r["rel"], r["status"]
287
+ if status == "error":
288
+ return
289
+ if status == "unchanged":
290
+ res.unchanged += 1
291
+ conn.execute("UPDATE nodes SET mtime_ns = ?, size = ? WHERE id = ?",
292
+ (r["mtime_ns"], r["size"], existing[rel][0]))
293
+ return
294
+ res.parsed += 1
295
+ res.parsed_files.append(rel)
296
+ res.parsers[r["parser"]] = res.parsers.get(r["parser"], 0) + 1
297
+ file_cols = (r["lang"] or family_of(rel), r["parser"], r["loc"], r["size"],
298
+ r["mtime_ns"], r["hash"], r["branches"], r["nesting"], int(is_test_path(rel)))
299
+ if rel in existing:
300
+ fid = existing[rel][0]
301
+ _purge_file(conn, fid, names, drop_file=False)
302
+ conn.execute("UPDATE nodes SET lang=?, parser=?, loc=?, size=?, mtime_ns=?, "
303
+ "hash=?, branches=?, nesting=?, is_test=? WHERE id=?", (*file_cols, fid))
304
+ else:
305
+ res.added += 1
306
+ fid = batch.next_id
307
+ batch.next_id += 1
308
+ conn.execute("INSERT INTO nodes(id, kind, name, path, lang, parser, loc, size, "
309
+ "mtime_ns, hash, branches, nesting, is_test, start_line, end_line) "
310
+ "VALUES(?, 'file', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NULL)",
311
+ (fid, rel.rsplit("/", 1)[-1], rel, *file_cols))
312
+ import_dirty.add(fid)
313
+ ids = []
314
+ for kind, nm, sl, el, parent, nb, nd in r["symbols"]:
315
+ sid = batch.next_id
316
+ batch.next_id += 1
317
+ ids.append(sid)
318
+ pid = ids[parent] if 0 <= parent < len(ids) - 1 else None
319
+ batch.sym_rows.append((sid, kind, nm, rel, fid, pid, sl, el, nb, nd))
320
+ batch.edge_rows.append((pid or fid, sid, "contains", sl, None))
321
+ names.add(nm)
322
+ for caller, nm, line, qual in r["refs"]:
323
+ cid = ids[caller] if 0 <= caller < len(ids) else fid
324
+ batch.ref_rows.append((batch.next_ref, fid, cid, nm, line, qual))
325
+ batch.next_ref += 1
326
+ names.add(nm)
327
+ fam = family_of(rel)
328
+ seen: set[tuple[str, int | None]] = set()
329
+ for spec, line, optional in r["imports"]:
330
+ targets = resolver.resolve(rel, fam, spec)
331
+ if not targets and optional:
332
+ continue
333
+ for t in targets or [None]:
334
+ if (spec, t) not in seen:
335
+ seen.add((spec, t))
336
+ batch.imp_rows.append((fid, spec, line, t))
337
+
338
+
339
+ def _relink_imports(conn, resolver: Resolver, path_ids: dict, import_dirty: set[int],
340
+ names: set[str]) -> None:
341
+ rows = conn.execute(
342
+ "SELECT i.rowid, i.file_id, i.spec, n.path FROM imports i JOIN nodes n "
343
+ "ON n.id = i.file_id WHERE i.resolved_id IS NULL").fetchall()
344
+ fixes, extra, fixed_files = [], [], set()
345
+ for rowid, fid, spec, src in rows:
346
+ if fid in import_dirty: # just parsed and resolved above
347
+ continue
348
+ targets = [path_ids[t] for t in resolver.resolve(src, family_of(src), spec)
349
+ if t in path_ids]
350
+ if targets:
351
+ fixes.append((targets[0], rowid))
352
+ extra += [(fid, spec, None, t) for t in targets[1:]]
353
+ fixed_files.add(fid)
354
+ conn.executemany("UPDATE imports SET resolved_id = ? WHERE rowid = ?", fixes)
355
+ conn.executemany("INSERT INTO imports(file_id, spec, line, resolved_id) VALUES(?,?,?,?)",
356
+ extra)
357
+ import_dirty |= fixed_files
358
+ if fixed_files:
359
+ _temp_ids(conn, "fix_files", fixed_files)
360
+ names.update(nm for (nm,) in conn.execute(
361
+ "SELECT DISTINCT name FROM refs WHERE file_id IN (SELECT v FROM temp.fix_files)"))
362
+
363
+
364
+ def _refresh_churn(conn, root: Path, gi, churn_days: int) -> None:
365
+ data = ggit.churn(root, gi, churn_days)
366
+ conn.execute("DELETE FROM churn")
367
+ conn.executemany("INSERT INTO churn VALUES(?,?,?,?)",
368
+ [(p, c, a, t) for p, (c, a, t) in data.items()])
369
+ gdb.set_meta(conn, "churn_commit", gi.head)
370
+ gdb.set_meta(conn, "churn_days", str(churn_days))
371
+
372
+
373
+ # --------------------------------------------------------------------------- main
374
+ def update(root: str | Path, rebuild: bool = False, offline: bool | None = None,
375
+ workers: int | None = None, churn_days: int = CHURN_DAYS) -> UpdateResult:
376
+ """Incrementally bring the graph up to date. Returns counts incl. files parsed."""
377
+ t0 = time.perf_counter()
378
+ root = Path(root).resolve()
379
+ if offline is None:
380
+ offline = os.environ.get("CCR_OFFLINE", "") not in ("", "0")
381
+ res = UpdateResult()
382
+ path = gdb.db_path(root)
383
+ if rebuild:
384
+ for suffix in ("", "-wal", "-shm"):
385
+ with contextlib.suppress(OSError):
386
+ os.remove(str(path) + suffix)
387
+ full = not path.exists()
388
+ conn = gdb.connect(path)
389
+ if gdb.get_meta(conn, "schema_version") != gdb.SCHEMA_VERSION:
390
+ conn.close()
391
+ return update(root, rebuild=True, offline=offline, workers=workers, churn_days=churn_days)
392
+ gdb.ensure_gitignored(root)
393
+ res.full = full
394
+
395
+ gi = ggit.info(root)
396
+ listed = ggit.ls_files(root) if gi else None
397
+ if listed is None:
398
+ gi = None
399
+ listed = walk_files(root)
400
+ res.mode = "git" if gi else "fs"
401
+ listed = [p for p in listed if not in_skipped_dir(p)]
402
+ code_all = [p for p in listed if is_code(p)]
403
+ aux_rels = [p for p in listed if p.rsplit("/", 1)[-1] in AUX_NAMES]
404
+
405
+ existing = {r["path"]: (r["id"], r["mtime_ns"], r["size"], r["hash"]) for r in conn.execute(
406
+ "SELECT id, path, mtime_ns, size, hash FROM nodes WHERE kind = 'file'")}
407
+ stats = _stat_files(root, code_all)
408
+ code = set(stats)
409
+ res.scanned = len(code)
410
+
411
+ git_changed: set[str] = set()
412
+ last_commit = gdb.get_meta(conn, "commit")
413
+ if gi and last_commit and not full:
414
+ git_changed = ggit.changed_since(root, last_commit) or set()
415
+ to_check: list[str] = []
416
+ for rel in sorted(code):
417
+ old = existing.get(rel)
418
+ if old is None or (old[1], old[2]) != stats[rel] or rel in git_changed:
419
+ to_check.append(rel)
420
+ removed = [p for p in existing if p not in code]
421
+
422
+ langs, allowed = _ts_languages(to_check, offline)
423
+ jobs = [(str(root), rel, langs.get(rel), existing[rel][3] if rel in existing else None)
424
+ for rel in to_check]
425
+ results = _parse_all(jobs, allowed, workers)
426
+ res.checked = len(results)
427
+
428
+ failed = {r["rel"] for r in results if r["status"] == "error"}
429
+ final_paths = code - failed
430
+ resolver = Resolver(final_paths, _read_aux(root, aux_rels))
431
+
432
+ names: set[str] = set() # symbol names whose call edges must be recomputed
433
+ import_dirty: set[int] = set() # files whose import edges must be rebuilt
434
+ with conn:
435
+ for rel in removed + sorted(failed & set(existing)):
436
+ _purge_file(conn, existing[rel][0], names, drop_file=True)
437
+ res.removed = len(removed)
438
+ next_id = (conn.execute("SELECT COALESCE(MAX(id), 0) FROM nodes").fetchone()[0]) + 1
439
+ next_ref = (conn.execute("SELECT COALESCE(MAX(id), 0) FROM refs").fetchone()[0]) + 1
440
+ batch = _Batch(next_id, next_ref)
441
+ for r in results:
442
+ _ingest(conn, r, existing, resolver, names, import_dirty, batch, res)
443
+ sym_rows, edge_rows, ref_rows, imp_rows = (batch.sym_rows, batch.edge_rows,
444
+ batch.ref_rows, batch.imp_rows)
445
+ # map resolved paths to ids (files inserted above are visible in this transaction)
446
+ path_ids = {p: i for i, p in conn.execute("SELECT id, path FROM nodes WHERE kind='file'")}
447
+ conn.executemany("INSERT INTO nodes(id, kind, name, path, file_id, parent_id, start_line, "
448
+ "end_line, branches, nesting) VALUES(?,?,?,?,?,?,?,?,?,?)", sym_rows)
449
+ conn.executemany("INSERT INTO edges(src, dst, kind, line, ref_id) VALUES(?,?,?,?,?)",
450
+ edge_rows)
451
+ conn.executemany("INSERT INTO refs(id, file_id, caller_id, name, line, qual) "
452
+ "VALUES(?,?,?,?,?,?)", ref_rows)
453
+ conn.executemany("INSERT INTO imports(file_id, spec, line, resolved_id) VALUES(?,?,?,?)",
454
+ [(f, s, ln, path_ids.get(t) if t else None) for f, s, ln, t in imp_rows])
455
+
456
+ # file set changed: previously unresolved imports elsewhere may resolve now
457
+ if (res.added or res.removed) and not full:
458
+ _relink_imports(conn, resolver, path_ids, import_dirty, names)
459
+
460
+ _rebuild_import_edges(conn, None if full else import_dirty)
461
+ _resolve_calls(conn, None if full else names)
462
+
463
+ res.commit = gi.head if gi else None
464
+ gdb.set_meta(conn, "commit", res.commit)
465
+ gdb.set_meta(conn, "mode", res.mode)
466
+ gdb.set_meta(conn, "built_at", str(int(time.time())))
467
+ gdb.set_meta(conn, "root", str(root))
468
+ if gi and (full or gdb.get_meta(conn, "churn_commit") != gi.head
469
+ or gdb.get_meta(conn, "churn_days") != str(churn_days)):
470
+ _refresh_churn(conn, root, gi, churn_days)
471
+ res.churn_updated = True
472
+ conn.close()
473
+ res.elapsed = time.perf_counter() - t0
474
+ log.debug("graph update: %s", res)
475
+ return res
ccr/graph/db.py ADDED
@@ -0,0 +1,88 @@
1
+ """SQLite storage for the code graph (.ccr/graph.db). stdlib only, safe to import in hooks."""
2
+ from __future__ import annotations
3
+
4
+ import sqlite3
5
+ from pathlib import Path
6
+
7
+ SCHEMA_VERSION = "2"
8
+
9
+ SCHEMA = """
10
+ CREATE TABLE IF NOT EXISTS meta(key TEXT PRIMARY KEY, value TEXT);
11
+ CREATE TABLE IF NOT EXISTS nodes(
12
+ id INTEGER PRIMARY KEY,
13
+ kind TEXT NOT NULL, -- file | function | method | class | interface | module | type | macro
14
+ name TEXT NOT NULL, -- symbol name; basename for files
15
+ path TEXT NOT NULL, -- project-relative posix path of the (owning) file
16
+ file_id INTEGER, -- owning file node (NULL for files)
17
+ parent_id INTEGER, -- enclosing symbol (NULL = top level)
18
+ start_line INTEGER, end_line INTEGER,
19
+ branches INTEGER DEFAULT 0, nesting INTEGER DEFAULT 0,
20
+ -- file-only columns
21
+ lang TEXT, parser TEXT, loc INTEGER, size INTEGER, mtime_ns INTEGER, hash TEXT,
22
+ is_test INTEGER DEFAULT 0
23
+ );
24
+ CREATE UNIQUE INDEX IF NOT EXISTS nodes_file_path ON nodes(path) WHERE kind = 'file';
25
+ CREATE INDEX IF NOT EXISTS nodes_name ON nodes(name COLLATE NOCASE);
26
+ CREATE INDEX IF NOT EXISTS nodes_file ON nodes(file_id);
27
+ CREATE TABLE IF NOT EXISTS edges(
28
+ src INTEGER NOT NULL, dst INTEGER NOT NULL,
29
+ kind TEXT NOT NULL, -- imports | calls | contains
30
+ line INTEGER, ref_id INTEGER -- ref_id: refs.rowid for call edges
31
+ );
32
+ CREATE INDEX IF NOT EXISTS edges_src ON edges(src, kind);
33
+ CREATE INDEX IF NOT EXISTS edges_dst ON edges(dst, kind);
34
+ CREATE INDEX IF NOT EXISTS edges_ref ON edges(ref_id);
35
+ CREATE TABLE IF NOT EXISTS imports(
36
+ file_id INTEGER NOT NULL, spec TEXT NOT NULL, line INTEGER, resolved_id INTEGER
37
+ );
38
+ CREATE INDEX IF NOT EXISTS imports_file ON imports(file_id);
39
+ CREATE INDEX IF NOT EXISTS imports_resolved ON imports(resolved_id);
40
+ CREATE TABLE IF NOT EXISTS refs(
41
+ id INTEGER PRIMARY KEY, file_id INTEGER NOT NULL, caller_id INTEGER,
42
+ name TEXT NOT NULL, line INTEGER,
43
+ qual INTEGER DEFAULT 0 -- 1 = qualified call (x.f(), pkg.F()), 0 = bare f()
44
+ );
45
+ CREATE INDEX IF NOT EXISTS refs_file ON refs(file_id);
46
+ CREATE INDEX IF NOT EXISTS refs_name ON refs(name);
47
+ CREATE TABLE IF NOT EXISTS churn(
48
+ path TEXT PRIMARY KEY, commits INTEGER, authors INTEGER, last_ts INTEGER
49
+ );
50
+ """
51
+
52
+
53
+ def db_path(root: Path) -> Path:
54
+ return Path(root) / ".ccr" / "graph.db"
55
+
56
+
57
+ def connect(path: Path, readonly: bool = False) -> sqlite3.Connection:
58
+ if readonly:
59
+ conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=5)
60
+ else:
61
+ path.parent.mkdir(parents=True, exist_ok=True)
62
+ conn = sqlite3.connect(str(path), timeout=30)
63
+ conn.execute("PRAGMA journal_mode=WAL")
64
+ conn.execute("PRAGMA synchronous=NORMAL")
65
+ conn.executescript(SCHEMA)
66
+ conn.execute("INSERT OR IGNORE INTO meta VALUES('schema_version', ?)", (SCHEMA_VERSION,))
67
+ conn.row_factory = sqlite3.Row
68
+ return conn
69
+
70
+
71
+ def get_meta(conn: sqlite3.Connection, key: str) -> str | None:
72
+ row = conn.execute("SELECT value FROM meta WHERE key = ?", (key,)).fetchone()
73
+ return row[0] if row else None
74
+
75
+
76
+ def set_meta(conn: sqlite3.Connection, key: str, value: str | None) -> None:
77
+ conn.execute("INSERT OR REPLACE INTO meta VALUES(?, ?)", (key, value))
78
+
79
+
80
+ def ensure_gitignored(root: Path) -> None:
81
+ """Drop a .ccr/.gitignore so the db is never committed, even before `ccr init`."""
82
+ gi = Path(root) / ".ccr" / ".gitignore"
83
+ if not gi.exists():
84
+ try:
85
+ gi.parent.mkdir(parents=True, exist_ok=True)
86
+ gi.write_text("graph.db\ngraph.db-*\nlocal/\n", encoding="utf-8")
87
+ except OSError:
88
+ pass