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.
- ccr/__init__.py +0 -0
- ccr/__main__.py +4 -0
- ccr/cli.py +595 -0
- ccr/config.py +518 -0
- ccr/detect/__init__.py +123 -0
- ccr/doctor.py +208 -0
- ccr/entry.py +23 -0
- ccr/evaluate/__init__.py +13 -0
- ccr/evaluate/classify.py +335 -0
- ccr/evaluate/llm.py +182 -0
- ccr/evaluate/locate.py +359 -0
- ccr/evaluate/risk.py +285 -0
- ccr/evaluate/text.py +190 -0
- ccr/graph/__init__.py +15 -0
- ccr/graph/build.py +475 -0
- ccr/graph/db.py +88 -0
- ccr/graph/files.py +169 -0
- ccr/graph/git.py +90 -0
- ccr/graph/parse.py +510 -0
- ccr/graph/query.py +359 -0
- ccr/graph/resolve.py +256 -0
- ccr/headless.py +363 -0
- ccr/history/__init__.py +172 -0
- ccr/history/calibrate.py +161 -0
- ccr/history/dashboard.py +374 -0
- ccr/history/feedback.py +91 -0
- ccr/history/learn.py +184 -0
- ccr/history/prompts.py +120 -0
- ccr/history/redact.py +45 -0
- ccr/history/savings.py +187 -0
- ccr/history/shadow.py +114 -0
- ccr/history/stats.py +172 -0
- ccr/history/tune.py +80 -0
- ccr/history/why.py +186 -0
- ccr/hooks/__init__.py +134 -0
- ccr/hooks/bg.py +68 -0
- ccr/hooks/common.py +159 -0
- ccr/hooks/prompt.py +322 -0
- ccr/hooks/session_start.py +91 -0
- ccr/hooks/stop.py +52 -0
- ccr/hooks/tasks.py +170 -0
- ccr/install/__init__.py +388 -0
- ccr/install/agents.py +200 -0
- ccr/install/command.py +159 -0
- ccr/install/settings.py +175 -0
- ccr/memory/__init__.py +87 -0
- ccr/memory/signals.py +210 -0
- ccr/memory/sources.py +422 -0
- ccr/report.py +40 -0
- ccr/route/__init__.py +527 -0
- ccr/route/budget.py +166 -0
- ccr/statusline.py +143 -0
- ccr/transcript.py +98 -0
- claude_code_router-0.1.1.dist-info/METADATA +291 -0
- claude_code_router-0.1.1.dist-info/RECORD +58 -0
- claude_code_router-0.1.1.dist-info/WHEEL +4 -0
- claude_code_router-0.1.1.dist-info/entry_points.txt +2 -0
- claude_code_router-0.1.1.dist-info/licenses/LICENSE +21 -0
ccr/graph/query.py
ADDED
|
@@ -0,0 +1,359 @@
|
|
|
1
|
+
"""Read-only query API over .ccr/graph.db (sqlite only; never imports tree-sitter)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import posixpath
|
|
6
|
+
import re
|
|
7
|
+
import sqlite3
|
|
8
|
+
import time
|
|
9
|
+
from collections import deque
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from ccr.graph import db as gdb
|
|
14
|
+
from ccr.graph import git as ggit
|
|
15
|
+
import contextlib
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class Symbol:
|
|
20
|
+
id: int
|
|
21
|
+
kind: str
|
|
22
|
+
name: str
|
|
23
|
+
path: str
|
|
24
|
+
start_line: int
|
|
25
|
+
end_line: int
|
|
26
|
+
branches: int
|
|
27
|
+
nesting: int
|
|
28
|
+
parent: str | None = None
|
|
29
|
+
callers: int = 0
|
|
30
|
+
callees: int = 0
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def qualname(self) -> str:
|
|
34
|
+
return f"{self.parent}.{self.name}" if self.parent else self.name
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@dataclass
|
|
38
|
+
class Dependent:
|
|
39
|
+
path: str
|
|
40
|
+
depth: int
|
|
41
|
+
via: str # imports | calls
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class TestLink:
|
|
46
|
+
path: str
|
|
47
|
+
reason: str # imports | calls | name
|
|
48
|
+
distance: int # dependency depth for imports/calls; directory distance for name matches
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
_TEST_AFFIX_CI = re.compile(r"^(?:tests?_)|(?:[_\-](?:tests?|spec))$", re.I)
|
|
52
|
+
_TEST_AFFIX_CAMEL = re.compile(r"(?<=[a-z0-9])(?:Tests?|Spec)$|^Test(?=[A-Z_])")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _subject(name: str, is_test: bool) -> str:
|
|
56
|
+
"""Normalized "what this file is about": test_foo.py / foo_test.go / FooTest.java -> foo."""
|
|
57
|
+
stem = name.split(".", 1)[0]
|
|
58
|
+
if is_test:
|
|
59
|
+
prev = None
|
|
60
|
+
while prev != stem:
|
|
61
|
+
prev = stem
|
|
62
|
+
stem = _TEST_AFFIX_CI.sub("", stem) or stem
|
|
63
|
+
stem = _TEST_AFFIX_CAMEL.sub("", stem) or stem
|
|
64
|
+
return re.sub(r"[_\-]", "", stem).lower()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _dir_distance(a: str, b: str) -> int:
|
|
68
|
+
pa, pb = posixpath.dirname(a).split("/"), posixpath.dirname(b).split("/")
|
|
69
|
+
pa, pb = [p for p in pa if p], [p for p in pb if p]
|
|
70
|
+
common = 0
|
|
71
|
+
for x, y in zip(pa, pb, strict=False):
|
|
72
|
+
if x != y:
|
|
73
|
+
break
|
|
74
|
+
common += 1
|
|
75
|
+
return (len(pa) - common) + (len(pb) - common)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class Graph:
|
|
79
|
+
def __init__(self, conn: sqlite3.Connection, root: Path) -> None:
|
|
80
|
+
self.conn = conn
|
|
81
|
+
self.root = root
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def open(cls, root: str | Path) -> "Graph | None":
|
|
85
|
+
root = Path(root).resolve()
|
|
86
|
+
p = gdb.db_path(root)
|
|
87
|
+
if not p.exists():
|
|
88
|
+
return None
|
|
89
|
+
try:
|
|
90
|
+
conn = gdb.connect(p, readonly=True)
|
|
91
|
+
conn.execute("SELECT 1 FROM nodes LIMIT 1")
|
|
92
|
+
except sqlite3.Error:
|
|
93
|
+
return None
|
|
94
|
+
return cls(conn, root)
|
|
95
|
+
|
|
96
|
+
def close(self) -> None:
|
|
97
|
+
self.conn.close()
|
|
98
|
+
|
|
99
|
+
def __enter__(self):
|
|
100
|
+
return self
|
|
101
|
+
|
|
102
|
+
def __exit__(self, *exc):
|
|
103
|
+
self.close()
|
|
104
|
+
|
|
105
|
+
# ------------------------------------------------------------------ basics
|
|
106
|
+
def rel(self, path: str | Path) -> str:
|
|
107
|
+
"""Project-relative posix path for an absolute, cwd-relative or root-relative path."""
|
|
108
|
+
p = Path(path)
|
|
109
|
+
if not p.is_absolute() and not (self.root / p).exists() and p.exists():
|
|
110
|
+
p = p.resolve()
|
|
111
|
+
if p.is_absolute():
|
|
112
|
+
try:
|
|
113
|
+
p = p.resolve().relative_to(self.root)
|
|
114
|
+
except ValueError:
|
|
115
|
+
return p.as_posix()
|
|
116
|
+
s = p.as_posix()
|
|
117
|
+
while s.startswith("./"):
|
|
118
|
+
s = s[2:]
|
|
119
|
+
return s
|
|
120
|
+
|
|
121
|
+
def file_row(self, path: str | Path) -> sqlite3.Row | None:
|
|
122
|
+
return self.conn.execute("SELECT * FROM nodes WHERE kind = 'file' AND path = ?",
|
|
123
|
+
(self.rel(path),)).fetchone()
|
|
124
|
+
|
|
125
|
+
def find_files(self, fragment: str, limit: int = 20) -> list[str]:
|
|
126
|
+
"""Files whose path ends with (or contains) the fragment."""
|
|
127
|
+
frag = fragment.strip("/")
|
|
128
|
+
rows = self.conn.execute(
|
|
129
|
+
"SELECT path FROM nodes WHERE kind = 'file' AND (path = ? OR path LIKE ? ESCAPE '\\') "
|
|
130
|
+
"ORDER BY length(path) LIMIT ?", (frag, "%/" + _like(frag), limit)).fetchall()
|
|
131
|
+
if not rows:
|
|
132
|
+
rows = self.conn.execute(
|
|
133
|
+
"SELECT path FROM nodes WHERE kind = 'file' AND path LIKE ? ESCAPE '\\' "
|
|
134
|
+
"ORDER BY length(path) LIMIT ?", ("%" + _like(frag) + "%", limit)).fetchall()
|
|
135
|
+
return [r[0] for r in rows]
|
|
136
|
+
|
|
137
|
+
# ------------------------------------------------------------------ symbols
|
|
138
|
+
def _symbols(self, where: str, args: tuple, limit: int) -> list[Symbol]:
|
|
139
|
+
rows = self.conn.execute(
|
|
140
|
+
"SELECT n.*, p.name AS parent_name, "
|
|
141
|
+
"(SELECT COUNT(*) FROM edges e WHERE e.dst = n.id AND e.kind = 'calls') AS n_callers, "
|
|
142
|
+
"(SELECT COUNT(*) FROM edges e WHERE e.src = n.id AND e.kind = 'calls') AS n_callees "
|
|
143
|
+
"FROM nodes n LEFT JOIN nodes p ON p.id = n.parent_id "
|
|
144
|
+
f"WHERE n.kind != 'file' AND {where} ORDER BY n.path, n.start_line LIMIT ?",
|
|
145
|
+
(*args, limit)).fetchall()
|
|
146
|
+
return [Symbol(r["id"], r["kind"], r["name"], r["path"], r["start_line"], r["end_line"],
|
|
147
|
+
r["branches"] or 0, r["nesting"] or 0, r["parent_name"], r["n_callers"],
|
|
148
|
+
r["n_callees"]) for r in rows]
|
|
149
|
+
|
|
150
|
+
def lookup(self, query: str, limit: int = 20) -> list[Symbol]:
|
|
151
|
+
"""Find symbols: exact, case-insensitive, then prefix, then substring. Accepts A.b / A::b."""
|
|
152
|
+
parts = [p for p in re.split(r"\.|::|#", query.strip()) if p]
|
|
153
|
+
if not parts:
|
|
154
|
+
return []
|
|
155
|
+
name, parent = parts[-1], (parts[-2] if len(parts) > 1 else None)
|
|
156
|
+
pclause, pargs = ("AND p.name = ?", (parent,)) if parent else ("", ())
|
|
157
|
+
for where, arg in (("n.name = ?", name),
|
|
158
|
+
("n.name = ? COLLATE NOCASE", name),
|
|
159
|
+
("n.name LIKE ? ESCAPE '\\'", _like(name) + "%"),
|
|
160
|
+
("n.name LIKE ? ESCAPE '\\'", "%" + _like(name) + "%")):
|
|
161
|
+
found = self._symbols(f"{where} {pclause}", (arg, *pargs), limit)
|
|
162
|
+
if found:
|
|
163
|
+
return found
|
|
164
|
+
return []
|
|
165
|
+
|
|
166
|
+
def callers(self, symbol_id: int, limit: int = 50) -> list[tuple[str, str, int]]:
|
|
167
|
+
"""(caller qualname or file, path, line) for a symbol."""
|
|
168
|
+
rows = self.conn.execute(
|
|
169
|
+
"SELECT s.name, s.kind, s.path, e.line FROM edges e JOIN nodes s ON s.id = e.src "
|
|
170
|
+
"WHERE e.dst = ? AND e.kind = 'calls' ORDER BY s.path, e.line LIMIT ?",
|
|
171
|
+
(symbol_id, limit)).fetchall()
|
|
172
|
+
return [(r[0] if r[1] != "file" else "<module>", r[2], r[3]) for r in rows]
|
|
173
|
+
|
|
174
|
+
def callees(self, symbol_id: int, limit: int = 50) -> list[tuple[str, str]]:
|
|
175
|
+
rows = self.conn.execute(
|
|
176
|
+
"SELECT DISTINCT d.name, d.path FROM edges e JOIN nodes d ON d.id = e.dst "
|
|
177
|
+
"WHERE e.src = ? AND e.kind = 'calls' LIMIT ?", (symbol_id, limit)).fetchall()
|
|
178
|
+
return [(r[0], r[1]) for r in rows]
|
|
179
|
+
|
|
180
|
+
# ------------------------------------------------------------------ dependencies
|
|
181
|
+
def dependencies(self, path: str | Path) -> list[str]:
|
|
182
|
+
row = self.file_row(path)
|
|
183
|
+
if row is None:
|
|
184
|
+
return []
|
|
185
|
+
return [r[0] for r in self.conn.execute(
|
|
186
|
+
"SELECT DISTINCT n.path FROM edges e JOIN nodes n ON n.id = e.dst "
|
|
187
|
+
"WHERE e.src = ? AND e.kind = 'imports' ORDER BY n.path", (row["id"],))]
|
|
188
|
+
|
|
189
|
+
def _direct_dependents(self, fid: int, calls: bool) -> list[tuple[int, str]]:
|
|
190
|
+
out = [(r[0], "imports") for r in self.conn.execute(
|
|
191
|
+
"SELECT DISTINCT src FROM edges WHERE dst = ? AND kind = 'imports'", (fid,))]
|
|
192
|
+
if calls:
|
|
193
|
+
out += [(r[0], "calls") for r in self.conn.execute(
|
|
194
|
+
"SELECT DISTINCT COALESCE(s.file_id, s.id) FROM nodes d "
|
|
195
|
+
"JOIN edges e ON e.dst = d.id AND e.kind = 'calls' JOIN nodes s ON s.id = e.src "
|
|
196
|
+
"WHERE d.file_id = ?", (fid,))]
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
def dependents(self, path: str | Path, depth: int = 3, calls: bool = True,
|
|
200
|
+
limit: int = 500) -> list[Dependent]:
|
|
201
|
+
"""Blast radius: files that (transitively) import or call into `path`."""
|
|
202
|
+
row = self.file_row(path)
|
|
203
|
+
if row is None:
|
|
204
|
+
return []
|
|
205
|
+
start = row["id"]
|
|
206
|
+
seen = {start: (0, "")}
|
|
207
|
+
q = deque([start])
|
|
208
|
+
while q and len(seen) <= limit:
|
|
209
|
+
cur = q.popleft()
|
|
210
|
+
d = seen[cur][0]
|
|
211
|
+
if d >= depth:
|
|
212
|
+
continue
|
|
213
|
+
for nid, via in self._direct_dependents(cur, calls):
|
|
214
|
+
if nid not in seen:
|
|
215
|
+
seen[nid] = (d + 1, via)
|
|
216
|
+
q.append(nid)
|
|
217
|
+
ids = [i for i in seen if i != start]
|
|
218
|
+
if not ids:
|
|
219
|
+
return []
|
|
220
|
+
paths = dict(self.conn.execute(
|
|
221
|
+
f"SELECT id, path FROM nodes WHERE id IN ({','.join('?' * len(ids))})", ids).fetchall())
|
|
222
|
+
out = [Dependent(paths[i], seen[i][0], seen[i][1]) for i in ids if i in paths]
|
|
223
|
+
return sorted(out, key=lambda x: (x.depth, x.path))
|
|
224
|
+
|
|
225
|
+
# ------------------------------------------------------------------ metrics
|
|
226
|
+
def complexity(self, path: str | Path) -> dict | None:
|
|
227
|
+
row = self.file_row(path)
|
|
228
|
+
if row is None:
|
|
229
|
+
return None
|
|
230
|
+
syms = self.conn.execute(
|
|
231
|
+
"SELECT name, kind, start_line, end_line, branches, nesting FROM nodes "
|
|
232
|
+
"WHERE file_id = ? ORDER BY branches DESC, nesting DESC", (row["id"],)).fetchall()
|
|
233
|
+
funcs = [s for s in syms if s["kind"] in ("function", "method", "macro")]
|
|
234
|
+
return {
|
|
235
|
+
"path": row["path"], "lang": row["lang"], "parser": row["parser"],
|
|
236
|
+
"loc": row["loc"] or 0, "size": row["size"] or 0,
|
|
237
|
+
"branches": row["branches"] or 0, "nesting": row["nesting"] or 0,
|
|
238
|
+
"symbols": len(syms),
|
|
239
|
+
"max_function_branches": funcs[0]["branches"] if funcs else 0,
|
|
240
|
+
"max_function_lines": max(((s["end_line"] or s["start_line"]) - s["start_line"] + 1
|
|
241
|
+
for s in funcs), default=0),
|
|
242
|
+
"hotspots": [dict(name=s["name"], kind=s["kind"], line=s["start_line"],
|
|
243
|
+
lines=(s["end_line"] or s["start_line"]) - s["start_line"] + 1,
|
|
244
|
+
branches=s["branches"], nesting=s["nesting"])
|
|
245
|
+
for s in funcs[:5] if s["branches"]],
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
def churn(self, path: str | Path) -> dict | None:
|
|
249
|
+
r = self.conn.execute("SELECT commits, authors, last_ts FROM churn WHERE path = ?",
|
|
250
|
+
(self.rel(path),)).fetchone()
|
|
251
|
+
if r is None:
|
|
252
|
+
return None
|
|
253
|
+
return {"commits": r[0], "authors": r[1], "last_ts": r[2],
|
|
254
|
+
"window_days": int(gdb.get_meta(self.conn, "churn_days") or 0)}
|
|
255
|
+
|
|
256
|
+
def tests_for(self, path: str | Path) -> list[TestLink]:
|
|
257
|
+
"""Test files near `path`: tests that import/call it, then name-matched tests."""
|
|
258
|
+
rel = self.rel(path)
|
|
259
|
+
row = self.file_row(rel)
|
|
260
|
+
links: dict[str, TestLink] = {}
|
|
261
|
+
if row is not None:
|
|
262
|
+
for dep in self.dependents(rel, depth=2):
|
|
263
|
+
frow = self.file_row(dep.path)
|
|
264
|
+
if frow is not None and frow["is_test"]:
|
|
265
|
+
links[dep.path] = TestLink(dep.path, dep.via, dep.depth)
|
|
266
|
+
subject = _subject(posixpath.basename(rel), False)
|
|
267
|
+
if subject:
|
|
268
|
+
for (tp,) in self.conn.execute("SELECT path FROM nodes WHERE kind='file' AND is_test=1"):
|
|
269
|
+
if tp in links or tp == rel:
|
|
270
|
+
continue
|
|
271
|
+
if _subject(posixpath.basename(tp), True) == subject:
|
|
272
|
+
links[tp] = TestLink(tp, "name", _dir_distance(rel, tp))
|
|
273
|
+
order = {"imports": 0, "calls": 1, "name": 2}
|
|
274
|
+
return sorted(links.values(), key=lambda t: (order[t.reason], t.distance, t.path))
|
|
275
|
+
|
|
276
|
+
def test_proximity(self, path: str | Path) -> dict:
|
|
277
|
+
tests = self.tests_for(path)
|
|
278
|
+
frow = self.file_row(path)
|
|
279
|
+
return {"is_test": bool(frow and frow["is_test"]), "has_tests": bool(tests),
|
|
280
|
+
"nearest": tests[0].path if tests else None,
|
|
281
|
+
"direct": any(t.reason != "name" and t.distance == 1 for t in tests),
|
|
282
|
+
"tests": [t.path for t in tests[:10]]}
|
|
283
|
+
|
|
284
|
+
# ------------------------------------------------------------------ overview
|
|
285
|
+
def stats(self) -> dict:
|
|
286
|
+
c = self.conn
|
|
287
|
+
kinds = dict(c.execute("SELECT kind, COUNT(*) FROM nodes GROUP BY kind").fetchall())
|
|
288
|
+
files = kinds.pop("file", 0)
|
|
289
|
+
meta = dict(c.execute("SELECT key, value FROM meta").fetchall())
|
|
290
|
+
return {
|
|
291
|
+
"files": files,
|
|
292
|
+
"symbols": sum(kinds.values()),
|
|
293
|
+
"symbol_kinds": dict(sorted(kinds.items(), key=lambda kv: -kv[1])),
|
|
294
|
+
"edges": dict(c.execute("SELECT kind, COUNT(*) FROM edges GROUP BY kind").fetchall()),
|
|
295
|
+
"languages": dict(c.execute("SELECT lang, COUNT(*) FROM nodes WHERE kind='file' "
|
|
296
|
+
"GROUP BY lang ORDER BY 2 DESC").fetchall()),
|
|
297
|
+
"parsers": dict(c.execute("SELECT parser, COUNT(*) FROM nodes WHERE kind='file' "
|
|
298
|
+
"GROUP BY parser ORDER BY 2 DESC").fetchall()),
|
|
299
|
+
"tests": c.execute("SELECT COUNT(*) FROM nodes WHERE kind='file' AND is_test=1")
|
|
300
|
+
.fetchone()[0],
|
|
301
|
+
"unresolved_imports": c.execute("SELECT COUNT(*) FROM imports WHERE resolved_id IS NULL")
|
|
302
|
+
.fetchone()[0],
|
|
303
|
+
"churn_files": c.execute("SELECT COUNT(*) FROM churn").fetchone()[0],
|
|
304
|
+
"meta": meta,
|
|
305
|
+
"db_bytes": _db_bytes(gdb.db_path(self.root)),
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
def hot_files(self, limit: int = 10) -> list[dict]:
|
|
309
|
+
rows = self.conn.execute(
|
|
310
|
+
"SELECT path, commits, authors FROM churn c WHERE EXISTS "
|
|
311
|
+
"(SELECT 1 FROM nodes n WHERE n.kind='file' AND n.path = c.path) "
|
|
312
|
+
"ORDER BY commits DESC LIMIT ?", (limit,)).fetchall()
|
|
313
|
+
return [dict(path=r[0], commits=r[1], authors=r[2]) for r in rows]
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _like(s: str) -> str:
|
|
317
|
+
return s.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _db_bytes(p: Path) -> int:
|
|
321
|
+
total = 0
|
|
322
|
+
for suffix in ("", "-wal"):
|
|
323
|
+
with contextlib.suppress(OSError):
|
|
324
|
+
total += os.path.getsize(str(p) + suffix)
|
|
325
|
+
return total
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def freshness(root: str | Path, check_files: bool = True) -> dict:
|
|
329
|
+
"""status: missing | fresh | stale | error, plus reasons. Cheap enough for `ccr doctor`."""
|
|
330
|
+
root = Path(root).resolve()
|
|
331
|
+
g = Graph.open(root)
|
|
332
|
+
if g is None:
|
|
333
|
+
return {"status": "missing" if not gdb.db_path(root).exists() else "error",
|
|
334
|
+
"reasons": []}
|
|
335
|
+
with g:
|
|
336
|
+
meta = dict(g.conn.execute("SELECT key, value FROM meta").fetchall())
|
|
337
|
+
files = g.conn.execute("SELECT path, mtime_ns, size FROM nodes WHERE kind='file'").fetchall()
|
|
338
|
+
out = {"status": "fresh", "reasons": [], "files": len(files), "mode": meta.get("mode"),
|
|
339
|
+
"commit": meta.get("commit"), "built_at": int(meta.get("built_at") or 0)}
|
|
340
|
+
out["age_s"] = int(time.time()) - out["built_at"] if out["built_at"] else None
|
|
341
|
+
if meta.get("mode") == "git":
|
|
342
|
+
gi = ggit.info(root)
|
|
343
|
+
if gi and gi.head and gi.head != meta.get("commit"):
|
|
344
|
+
out["reasons"].append("HEAD moved since last index")
|
|
345
|
+
if check_files:
|
|
346
|
+
changed = 0
|
|
347
|
+
for path, mtime, size in files:
|
|
348
|
+
try:
|
|
349
|
+
st = os.stat(root / path)
|
|
350
|
+
except OSError:
|
|
351
|
+
changed += 1
|
|
352
|
+
continue
|
|
353
|
+
if (st.st_mtime_ns, st.st_size) != (mtime, size):
|
|
354
|
+
changed += 1
|
|
355
|
+
if changed:
|
|
356
|
+
out["reasons"].append(f"{changed} indexed file(s) modified or deleted")
|
|
357
|
+
if out["reasons"]:
|
|
358
|
+
out["status"] = "stale"
|
|
359
|
+
return out
|
ccr/graph/resolve.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Resolve raw import specifiers to files inside the project (best effort, per language family)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import posixpath
|
|
5
|
+
import re
|
|
6
|
+
from collections import defaultdict
|
|
7
|
+
from typing import Iterable
|
|
8
|
+
|
|
9
|
+
JS_EXTS = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts", ".vue", ".svelte")
|
|
10
|
+
PY_EXTS = (".py", ".pyi")
|
|
11
|
+
JVM_EXTS = (".java", ".kt", ".kts", ".scala", ".groovy")
|
|
12
|
+
C_EXTS = (".h", ".hpp", ".hh", ".hxx", ".c", ".cc", ".cpp", ".cxx", ".m", ".mm")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _noext(p: str) -> str:
|
|
16
|
+
base, ext = posixpath.splitext(p)
|
|
17
|
+
return base if ext else p
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _snake(name: str) -> str:
|
|
21
|
+
return re.sub(r"(?<=[a-z0-9])([A-Z])", r"_\1", name).lower()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Resolver:
|
|
25
|
+
def __init__(self, paths: Iterable[str], aux: dict[str, str] | None = None) -> None:
|
|
26
|
+
"""paths: indexed code files. aux: {relpath: text} for go.mod / Cargo.toml files."""
|
|
27
|
+
self.paths = set(paths)
|
|
28
|
+
self.by_key: dict[str, list[str]] = defaultdict(list) # lowercase last comp -> paths
|
|
29
|
+
self.dirs: dict[str, list[str]] = defaultdict(list)
|
|
30
|
+
self.py_pkgs: set[str] = set()
|
|
31
|
+
for p in self.paths:
|
|
32
|
+
d = posixpath.dirname(p)
|
|
33
|
+
self.dirs[d].append(p)
|
|
34
|
+
key = _noext(p)
|
|
35
|
+
stem = key.rsplit("/", 1)[-1]
|
|
36
|
+
if stem in ("__init__", "index", "mod") and d:
|
|
37
|
+
if stem == "__init__":
|
|
38
|
+
self.py_pkgs.add(d)
|
|
39
|
+
self.by_key[d.rsplit("/", 1)[-1].lower()].append(p)
|
|
40
|
+
self.by_key[stem.lower()].append(p)
|
|
41
|
+
self.go_mods: list[tuple[str, str]] = [] # (dir, module path)
|
|
42
|
+
self.cargo_dirs: set[str] = set()
|
|
43
|
+
for rel, text in (aux or {}).items():
|
|
44
|
+
d = posixpath.dirname(rel)
|
|
45
|
+
if rel.endswith("go.mod"):
|
|
46
|
+
m = re.search(r"^\s*module\s+(\S+)", text, re.MULTILINE)
|
|
47
|
+
if m:
|
|
48
|
+
self.go_mods.append((d, m.group(1)))
|
|
49
|
+
elif rel.endswith("Cargo.toml"):
|
|
50
|
+
self.cargo_dirs.add(d)
|
|
51
|
+
self.go_mods.sort(key=lambda x: -len(x[1]))
|
|
52
|
+
|
|
53
|
+
# ------------------------------------------------------------------ helpers
|
|
54
|
+
def _first(self, cands: Iterable[str]) -> list[str]:
|
|
55
|
+
for c in cands:
|
|
56
|
+
if c in self.paths:
|
|
57
|
+
return [c]
|
|
58
|
+
return []
|
|
59
|
+
|
|
60
|
+
def _with_exts(self, base: str, exts: tuple[str, ...], index: tuple[str, ...] = ()) -> list[str]:
|
|
61
|
+
base = posixpath.normpath(base) if base else base
|
|
62
|
+
if base.startswith("../") or base == "..":
|
|
63
|
+
return []
|
|
64
|
+
if base == ".":
|
|
65
|
+
base = ""
|
|
66
|
+
cands = [base] if posixpath.splitext(base)[1] else []
|
|
67
|
+
cands += [base + e for e in exts]
|
|
68
|
+
for idx in index:
|
|
69
|
+
cands += [posixpath.join(base, idx + e) for e in exts]
|
|
70
|
+
return self._first(c.lstrip("/") for c in cands if c)
|
|
71
|
+
|
|
72
|
+
def _suffix(self, frag: str, exts: tuple[str, ...], ci: bool = False,
|
|
73
|
+
ok=None) -> list[str]:
|
|
74
|
+
frag = frag.strip("/")
|
|
75
|
+
if not frag:
|
|
76
|
+
return []
|
|
77
|
+
last = frag.rsplit("/", 1)[-1].lower()
|
|
78
|
+
want = frag.lower() if ci else frag
|
|
79
|
+
out = []
|
|
80
|
+
for p in self.by_key.get(last, ()):
|
|
81
|
+
if not p.endswith(exts):
|
|
82
|
+
continue
|
|
83
|
+
key = _noext(p)
|
|
84
|
+
if key.rsplit("/", 1)[-1] in ("__init__", "index", "mod"):
|
|
85
|
+
key = posixpath.dirname(key)
|
|
86
|
+
k = key.lower() if ci else key
|
|
87
|
+
if k == want or k.endswith("/" + want):
|
|
88
|
+
prefix = key[: len(key) - len(frag)].rstrip("/")
|
|
89
|
+
if ok is None or ok(prefix, p):
|
|
90
|
+
out.append(p)
|
|
91
|
+
return sorted(out, key=len)
|
|
92
|
+
|
|
93
|
+
# ------------------------------------------------------------------ main entry
|
|
94
|
+
def resolve(self, src: str, family: str, spec: str) -> list[str]:
|
|
95
|
+
try:
|
|
96
|
+
fn = getattr(self, "_r_" + family, None)
|
|
97
|
+
res = fn(src, spec) if fn else []
|
|
98
|
+
except Exception:
|
|
99
|
+
return []
|
|
100
|
+
return [r for r in res if r != src]
|
|
101
|
+
|
|
102
|
+
def _r_python(self, src: str, spec: str) -> list[str]:
|
|
103
|
+
dots = len(spec) - len(spec.lstrip("."))
|
|
104
|
+
mod = spec[dots:]
|
|
105
|
+
frag = mod.replace(".", "/")
|
|
106
|
+
if dots:
|
|
107
|
+
base = posixpath.dirname(src)
|
|
108
|
+
for _ in range(dots - 1):
|
|
109
|
+
base = posixpath.dirname(base)
|
|
110
|
+
target = posixpath.join(base, frag) if frag else base
|
|
111
|
+
return self._with_exts(target, PY_EXTS, ("__init__",)) if target else \
|
|
112
|
+
self._first(["__init__.py"])
|
|
113
|
+
if not frag:
|
|
114
|
+
return []
|
|
115
|
+
for root in ("", "src"):
|
|
116
|
+
r = self._with_exts(posixpath.join(root, frag), PY_EXTS, ("__init__",))
|
|
117
|
+
if r:
|
|
118
|
+
return r
|
|
119
|
+
# source-root rule: the prefix before the module path must not itself be a package
|
|
120
|
+
return self._suffix(frag, PY_EXTS, ok=lambda prefix, _p: prefix not in self.py_pkgs)[:1]
|
|
121
|
+
|
|
122
|
+
def _r_js(self, src: str, spec: str) -> list[str]:
|
|
123
|
+
spec = spec.split("?", 1)[0]
|
|
124
|
+
if spec.startswith("."):
|
|
125
|
+
base = posixpath.join(posixpath.dirname(src), spec)
|
|
126
|
+
elif spec.startswith(("@/", "~/")):
|
|
127
|
+
rest = spec[2:]
|
|
128
|
+
return (self._with_exts("src/" + rest, JS_EXTS, ("index",))
|
|
129
|
+
or self._with_exts(rest, JS_EXTS, ("index",)))
|
|
130
|
+
elif spec.startswith("/"):
|
|
131
|
+
base = spec.lstrip("/")
|
|
132
|
+
else:
|
|
133
|
+
return []
|
|
134
|
+
r = self._with_exts(base, JS_EXTS, ("index",))
|
|
135
|
+
if not r and base.endswith((".js", ".jsx", ".mjs", ".cjs")):
|
|
136
|
+
r = self._with_exts(_noext(base), JS_EXTS, ("index",))
|
|
137
|
+
return r
|
|
138
|
+
|
|
139
|
+
def _r_go(self, src: str, spec: str) -> list[str]:
|
|
140
|
+
for d, mod in self.go_mods:
|
|
141
|
+
if spec == mod or spec.startswith(mod + "/"):
|
|
142
|
+
rel = spec[len(mod):].lstrip("/")
|
|
143
|
+
target = posixpath.normpath(posixpath.join(d, rel)) if (d or rel) else ""
|
|
144
|
+
target = "" if target == "." else target
|
|
145
|
+
return sorted(p for p in self.dirs.get(target, ())
|
|
146
|
+
if p.endswith(".go") and not p.endswith("_test.go"))
|
|
147
|
+
return []
|
|
148
|
+
|
|
149
|
+
def _r_jvm(self, src: str, spec: str) -> list[str]:
|
|
150
|
+
if spec.endswith(".*"):
|
|
151
|
+
frag = spec[:-2].replace(".", "/")
|
|
152
|
+
out = []
|
|
153
|
+
for d, files in self.dirs.items():
|
|
154
|
+
if d == frag or d.endswith("/" + frag):
|
|
155
|
+
out += [p for p in files if p.endswith(JVM_EXTS)]
|
|
156
|
+
return sorted(out)
|
|
157
|
+
frag = spec.replace(".", "/")
|
|
158
|
+
r = self._suffix(frag, JVM_EXTS)
|
|
159
|
+
if not r and "/" in frag: # static member or nested class import
|
|
160
|
+
r = self._suffix(frag.rsplit("/", 1)[0], JVM_EXTS)
|
|
161
|
+
return r[:1]
|
|
162
|
+
|
|
163
|
+
def _rust_mod_dir(self, src: str) -> str:
|
|
164
|
+
d, stem = posixpath.dirname(src), _noext(posixpath.basename(src))
|
|
165
|
+
return d if stem in ("mod", "lib", "main") else posixpath.join(d, stem)
|
|
166
|
+
|
|
167
|
+
def _rust_crate_src(self, src: str) -> str:
|
|
168
|
+
d = posixpath.dirname(src)
|
|
169
|
+
while True:
|
|
170
|
+
if d in self.cargo_dirs:
|
|
171
|
+
return posixpath.join(d, "src") if d else "src"
|
|
172
|
+
if not d:
|
|
173
|
+
break
|
|
174
|
+
d = posixpath.dirname(d)
|
|
175
|
+
parts = src.split("/")
|
|
176
|
+
if "src" in parts:
|
|
177
|
+
return "/".join(parts[: parts.index("src") + 1])
|
|
178
|
+
return posixpath.dirname(src)
|
|
179
|
+
|
|
180
|
+
def _r_rust(self, src: str, spec: str) -> list[str]:
|
|
181
|
+
if spec.startswith("mod:"):
|
|
182
|
+
base = posixpath.join(self._rust_mod_dir(src), spec[4:])
|
|
183
|
+
return self._first([base + ".rs", base + "/mod.rs"])
|
|
184
|
+
parts = [p for p in spec.split("::") if p]
|
|
185
|
+
if not parts:
|
|
186
|
+
return []
|
|
187
|
+
head = parts[0]
|
|
188
|
+
if head == "crate":
|
|
189
|
+
base, rest = self._rust_crate_src(src), parts[1:]
|
|
190
|
+
elif head == "self":
|
|
191
|
+
base, rest = self._rust_mod_dir(src), parts[1:]
|
|
192
|
+
elif head == "super":
|
|
193
|
+
base = posixpath.dirname(self._rust_mod_dir(src))
|
|
194
|
+
rest = parts[1:]
|
|
195
|
+
while rest and rest[0] == "super":
|
|
196
|
+
base, rest = posixpath.dirname(base), rest[1:]
|
|
197
|
+
else:
|
|
198
|
+
return []
|
|
199
|
+
for i in range(len(rest), 0, -1):
|
|
200
|
+
target = posixpath.join(base, *rest[:i])
|
|
201
|
+
r = self._first([target + ".rs", target + "/mod.rs"])
|
|
202
|
+
if r:
|
|
203
|
+
return r
|
|
204
|
+
return []
|
|
205
|
+
|
|
206
|
+
def _r_c(self, src: str, spec: str) -> list[str]:
|
|
207
|
+
system = spec.startswith("<")
|
|
208
|
+
spec = spec.lstrip("<")
|
|
209
|
+
cands = [] if system else [posixpath.join(posixpath.dirname(src), spec)]
|
|
210
|
+
cands += [spec, "include/" + spec, "src/" + spec]
|
|
211
|
+
r = self._first(posixpath.normpath(c) for c in cands)
|
|
212
|
+
if r:
|
|
213
|
+
return r
|
|
214
|
+
hits = self._suffix(_noext(spec), C_EXTS)
|
|
215
|
+
hits = [h for h in hits if h.endswith("/" + spec) or h == spec]
|
|
216
|
+
return hits[:1] if len(hits) == 1 or not system else []
|
|
217
|
+
|
|
218
|
+
def _r_ruby(self, src: str, spec: str) -> list[str]:
|
|
219
|
+
if spec.startswith("."):
|
|
220
|
+
return self._with_exts(posixpath.join(posixpath.dirname(src), spec), (".rb",))
|
|
221
|
+
return (self._with_exts("lib/" + spec, (".rb",)) or self._with_exts(spec, (".rb",))
|
|
222
|
+
or self._suffix(_noext(spec), (".rb",))[:1])
|
|
223
|
+
|
|
224
|
+
def _r_php(self, src: str, spec: str) -> list[str]:
|
|
225
|
+
if spec.startswith("ns:"):
|
|
226
|
+
frag = spec[3:].replace("\\", "/").strip("/")
|
|
227
|
+
return self._suffix(frag, (".php",), ci=True)[:1] or \
|
|
228
|
+
self._suffix(frag.split("/", 1)[-1], (".php",), ci=True)[:1]
|
|
229
|
+
return self._first([posixpath.normpath(posixpath.join(posixpath.dirname(src), spec)),
|
|
230
|
+
posixpath.normpath(spec)])
|
|
231
|
+
|
|
232
|
+
def _r_zig(self, src: str, spec: str) -> list[str]:
|
|
233
|
+
if not spec.endswith(".zig"):
|
|
234
|
+
return []
|
|
235
|
+
return self._first([posixpath.normpath(posixpath.join(posixpath.dirname(src), spec))])
|
|
236
|
+
|
|
237
|
+
def _r_lua(self, src: str, spec: str) -> list[str]:
|
|
238
|
+
frag = spec.replace(".", "/")
|
|
239
|
+
return (self._with_exts(frag, (".lua",), ("init",))
|
|
240
|
+
or self._suffix(frag, (".lua",))[:1])
|
|
241
|
+
|
|
242
|
+
def _r_elixir(self, src: str, spec: str) -> list[str]:
|
|
243
|
+
frag = "/".join(_snake(p) for p in spec.split("."))
|
|
244
|
+
return self._suffix(frag, (".ex", ".exs"))[:1]
|
|
245
|
+
|
|
246
|
+
def _r_dart(self, src: str, spec: str) -> list[str]:
|
|
247
|
+
if spec.startswith("package:"):
|
|
248
|
+
rest = spec[len("package:"):].split("/", 1)
|
|
249
|
+
return self._first(["lib/" + rest[1]]) if len(rest) == 2 else []
|
|
250
|
+
if spec.startswith("dart:"):
|
|
251
|
+
return []
|
|
252
|
+
return self._first([posixpath.normpath(posixpath.join(posixpath.dirname(src), spec))])
|
|
253
|
+
|
|
254
|
+
def _r_shell(self, src: str, spec: str) -> list[str]:
|
|
255
|
+
return self._first([posixpath.normpath(posixpath.join(posixpath.dirname(src), spec)),
|
|
256
|
+
posixpath.normpath(spec)])
|