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/evaluate/risk.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Code risk over the located candidate set.
|
|
2
|
+
|
|
3
|
+
Components (each in [0, 1], reported with a human-readable detail):
|
|
4
|
+
blast_radius transitive dependents (imports + calls, depth 3)
|
|
5
|
+
complexity worst function branches, nesting depth, file size
|
|
6
|
+
test_proximity 1 = no tests found, 0.4 = only name-matched/indirect tests, 0 = direct tests
|
|
7
|
+
churn commits / authors in the git churn window
|
|
8
|
+
critical_path configurable critical globs (auth, payments, migrations, infra, ...) or
|
|
9
|
+
critical words in the prompt
|
|
10
|
+
memory risk flags from CLAUDE.md / auto memory / agent memory / MCP memory
|
|
11
|
+
|
|
12
|
+
Each file's values are scaled by how sure we are it is touched, then the worst file wins per
|
|
13
|
+
component. The overall score is a weighted noisy-or, so one strong factor is enough for
|
|
14
|
+
"high" and several moderate ones add up.
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
import re
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from functools import lru_cache
|
|
22
|
+
|
|
23
|
+
from ccr.evaluate import text as T
|
|
24
|
+
|
|
25
|
+
COMPONENTS = ("blast_radius", "complexity", "test_proximity", "churn", "critical_path", "memory")
|
|
26
|
+
CODE_COMPONENTS = ("blast_radius", "complexity", "test_proximity", "churn")
|
|
27
|
+
LABELS = {"blast_radius": "blast radius", "complexity": "complexity",
|
|
28
|
+
"test_proximity": "test proximity", "churn": "churn",
|
|
29
|
+
"critical_path": "critical path", "memory": "memory flags"}
|
|
30
|
+
MEMORY_KIND_VALUE = {"protected": 1.0, "critical": 0.9, "fragile": 0.6, "hard": 0.5,
|
|
31
|
+
"ownership": 0.3}
|
|
32
|
+
PROMPT_CRITICAL_VALUE = 0.6
|
|
33
|
+
CRITICAL_MIN_CONF = 0.45 # a weakly-located file (one directory word) is not a critical hit
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class Component:
|
|
38
|
+
name: str
|
|
39
|
+
value: float = 0.0
|
|
40
|
+
detail: str = "none"
|
|
41
|
+
files: list[str] = field(default_factory=list)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass
|
|
45
|
+
class MemoryFlag:
|
|
46
|
+
kind: str
|
|
47
|
+
term: str
|
|
48
|
+
path: str
|
|
49
|
+
text: str
|
|
50
|
+
source: str
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass
|
|
54
|
+
class Risk:
|
|
55
|
+
score: float | None = None
|
|
56
|
+
level: str = "unknown" # low | medium | high | unknown
|
|
57
|
+
code_risk: float = 0.0 # noisy-or of the code-only components
|
|
58
|
+
components: dict[str, Component] = field(default_factory=dict)
|
|
59
|
+
critical_groups: list[str] = field(default_factory=list)
|
|
60
|
+
critical_files: list[str] = field(default_factory=list)
|
|
61
|
+
critical_terms: list[str] = field(default_factory=list)
|
|
62
|
+
memory_flags: list[MemoryFlag] = field(default_factory=list)
|
|
63
|
+
evaluated: list[str] = field(default_factory=list)
|
|
64
|
+
notes: list[str] = field(default_factory=list)
|
|
65
|
+
dependents: int | None = None # files depending on the located set (graph only)
|
|
66
|
+
tests: str | None = None # direct | name-matched | none (graph only)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def critical(self) -> bool:
|
|
70
|
+
return bool(self.critical_files or self.critical_terms)
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def critical_located(self) -> bool:
|
|
74
|
+
return bool(self.critical_files)
|
|
75
|
+
|
|
76
|
+
def has_memory(self, *kinds: str) -> bool:
|
|
77
|
+
return any(f.kind in kinds for f in self.memory_flags)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@lru_cache(maxsize=512)
|
|
81
|
+
def glob_rx(pattern: str) -> re.Pattern:
|
|
82
|
+
"""gitignore-ish glob: `**` spans dirs, `*`/`?` do not; no `/` means "any directory"."""
|
|
83
|
+
pat = pattern.strip().lower()
|
|
84
|
+
if pat.startswith("/"):
|
|
85
|
+
pat = pat[1:]
|
|
86
|
+
elif not pat.startswith("**/"):
|
|
87
|
+
pat = "**/" + pat
|
|
88
|
+
out, i = "", 0
|
|
89
|
+
while i < len(pat):
|
|
90
|
+
if pat.startswith("**/", i):
|
|
91
|
+
out += "(?:.*/)?"
|
|
92
|
+
i += 3
|
|
93
|
+
elif pat.startswith("/**", i) and i + 3 == len(pat):
|
|
94
|
+
out += "(?:/.*)?"
|
|
95
|
+
i += 3
|
|
96
|
+
elif pat.startswith("**", i):
|
|
97
|
+
out += ".*"
|
|
98
|
+
i += 2
|
|
99
|
+
elif pat[i] == "*":
|
|
100
|
+
out += "[^/]*"
|
|
101
|
+
i += 1
|
|
102
|
+
elif pat[i] == "?":
|
|
103
|
+
out += "[^/]"
|
|
104
|
+
i += 1
|
|
105
|
+
else:
|
|
106
|
+
out += re.escape(pat[i])
|
|
107
|
+
i += 1
|
|
108
|
+
return re.compile(out + r"\Z")
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def critical_groups_for(path: str, groups: dict[str, list[str]]) -> list[str]:
|
|
112
|
+
p = path.lower()
|
|
113
|
+
return [g for g, pats in groups.items() if any(glob_rx(x).match(p) for x in pats)]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def prompt_critical_terms(task: str, groups: dict[str, list[str]]) -> list[tuple[str, str]]:
|
|
117
|
+
"""[(group, term)] for critical words in the prompt (paths/backticks excluded)."""
|
|
118
|
+
ws = T.words(T.strip_refs(task))
|
|
119
|
+
out = []
|
|
120
|
+
for g, terms in groups.items():
|
|
121
|
+
for t in terms:
|
|
122
|
+
if T.phrase_in(t, ws):
|
|
123
|
+
out.append((g, t))
|
|
124
|
+
return out
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def noisy_or(values: dict[str, float], weights: dict[str, float], names) -> float:
|
|
128
|
+
miss = 1.0
|
|
129
|
+
for n in names:
|
|
130
|
+
miss *= 1.0 - weights.get(n, 0.0) * max(0.0, min(1.0, values.get(n, 0.0)))
|
|
131
|
+
return round(1.0 - miss, 3)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class _Best:
|
|
135
|
+
"""Strongest evidence per risk component: (value, detail, file)."""
|
|
136
|
+
|
|
137
|
+
def __init__(self) -> None:
|
|
138
|
+
self.items = {n: (0.0, "", None) for n in COMPONENTS}
|
|
139
|
+
|
|
140
|
+
def offer(self, name: str, value: float, detail: str, path: str | None) -> None:
|
|
141
|
+
if value > self.items[name][0] or (self.items[name][2] is None and detail):
|
|
142
|
+
self.items[name] = (value, detail, path)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _scale(conf: float) -> float:
|
|
146
|
+
return min(1.0, conf / 0.7)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
_TEST_RANK = {"none": 0, "name-matched": 1, "direct": 2}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _file_metrics(risk: Risk, c, graph, rc: dict, full_blast: float, best: _Best,
|
|
153
|
+
blast_union: set[str]) -> None:
|
|
154
|
+
"""Offer blast radius, complexity, test proximity and churn evidence for one candidate."""
|
|
155
|
+
s = _scale(c.confidence)
|
|
156
|
+
try:
|
|
157
|
+
deps = graph.dependents(c.path)
|
|
158
|
+
except Exception:
|
|
159
|
+
deps = []
|
|
160
|
+
blast_union.update(d.path for d in deps)
|
|
161
|
+
n = len(deps)
|
|
162
|
+
direct = sum(1 for d in deps if d.depth == 1)
|
|
163
|
+
v = min(1.0, math.log2(1 + n) / full_blast) if n else 0.0
|
|
164
|
+
best.offer("blast_radius", v * s, f"{n} dependents of {c.path} ({direct} direct)"
|
|
165
|
+
if n else f"no dependents of {c.path}", c.path)
|
|
166
|
+
cx = graph.complexity(c.path) or {}
|
|
167
|
+
mfb, nest, loc = (cx.get("max_function_branches", 0), cx.get("nesting", 0), cx.get("loc", 0))
|
|
168
|
+
v = (0.5 * min(1.0, mfb / rc["complexity_full_branches"])
|
|
169
|
+
+ 0.25 * min(1.0, nest / 5) + 0.25 * min(1.0, loc / 600))
|
|
170
|
+
hot = (cx.get("hotspots") or [{}])[0].get("name")
|
|
171
|
+
best.offer("complexity", v * s, f"{c.path}: max function branches {mfb}"
|
|
172
|
+
+ (f" ({hot})" if hot else "") + f", nesting {nest}, {loc} loc", c.path)
|
|
173
|
+
if not c.is_test:
|
|
174
|
+
_test_metrics(risk, c, graph, s, best)
|
|
175
|
+
ch = graph.churn(c.path)
|
|
176
|
+
if ch:
|
|
177
|
+
v = (0.7 * min(1.0, ch["commits"] / rc["churn_full_commits"])
|
|
178
|
+
+ 0.3 * min(1.0, ch["authors"] / 5))
|
|
179
|
+
best.offer("churn", v * s, f"{c.path}: {ch['commits']} commits, {ch['authors']} "
|
|
180
|
+
f"author(s) in {ch['window_days']}d", c.path)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _test_metrics(risk: Risk, c, graph, s: float, best: _Best) -> None:
|
|
184
|
+
tests = graph.tests_for(c.path)
|
|
185
|
+
linked = [t for t in tests if t.reason != "name"]
|
|
186
|
+
kind = "direct" if linked else "name-matched" if tests else "none"
|
|
187
|
+
if risk.tests is None or _TEST_RANK[kind] > _TEST_RANK[risk.tests]:
|
|
188
|
+
risk.tests = kind
|
|
189
|
+
if not tests:
|
|
190
|
+
best.offer("test_proximity", 1.0 * s, f"no tests found for {c.path}", c.path)
|
|
191
|
+
elif not linked:
|
|
192
|
+
best.offer("test_proximity", 0.4 * s,
|
|
193
|
+
f"{c.path}: only name-matched tests ({tests[0].path})", c.path)
|
|
194
|
+
else:
|
|
195
|
+
best.offer("test_proximity", 0.0, f"{c.path} covered by {linked[0].path} "
|
|
196
|
+
f"({linked[0].reason})", c.path)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _code_metrics(risk: Risk, prim, graph, rc: dict, best: _Best) -> None:
|
|
200
|
+
if graph is None:
|
|
201
|
+
if prim:
|
|
202
|
+
risk.notes.append("no code graph: blast radius, complexity, tests and churn unknown")
|
|
203
|
+
return
|
|
204
|
+
blast_union: set[str] = set()
|
|
205
|
+
full_blast = math.log2(1 + rc["blast_full"])
|
|
206
|
+
for c in prim:
|
|
207
|
+
if c.indexed:
|
|
208
|
+
_file_metrics(risk, c, graph, rc, full_blast, best, blast_union)
|
|
209
|
+
if prim:
|
|
210
|
+
blast_union -= {c.path for c in prim}
|
|
211
|
+
risk.dependents = len(blast_union)
|
|
212
|
+
if len(prim) > 1 and blast_union:
|
|
213
|
+
v, d, p = best.items["blast_radius"]
|
|
214
|
+
best.items["blast_radius"] = (v, d + f"; {len(blast_union)} across all candidates", p)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _critical_paths(risk: Risk, prim, task: str, cfg, best: _Best) -> None:
|
|
218
|
+
groups = cfg["critical_paths"]
|
|
219
|
+
for c in prim:
|
|
220
|
+
hit = critical_groups_for(c.path, groups)
|
|
221
|
+
if hit and c.confidence >= CRITICAL_MIN_CONF:
|
|
222
|
+
risk.critical_files.append(c.path)
|
|
223
|
+
for g in hit:
|
|
224
|
+
if g not in risk.critical_groups:
|
|
225
|
+
risk.critical_groups.append(g)
|
|
226
|
+
best.offer("critical_path", _scale(c.confidence), f"{'/'.join(hit)}: {c.path}", c.path)
|
|
227
|
+
for g, t in prompt_critical_terms(task, cfg["critical_terms"]):
|
|
228
|
+
risk.critical_terms.append(t)
|
|
229
|
+
if g not in risk.critical_groups:
|
|
230
|
+
risk.critical_groups.append(g)
|
|
231
|
+
current = best.items["critical_path"]
|
|
232
|
+
if risk.critical_terms and current[0] < PROMPT_CRITICAL_VALUE:
|
|
233
|
+
terms = ", ".join(f"'{t}'" for t in risk.critical_terms[:3])
|
|
234
|
+
best.items["critical_path"] = (
|
|
235
|
+
PROMPT_CRITICAL_VALUE,
|
|
236
|
+
f"prompt mentions {terms} ({'/'.join(risk.critical_groups)})", None)
|
|
237
|
+
elif risk.critical_terms:
|
|
238
|
+
v, d, p = current
|
|
239
|
+
best.items["critical_path"] = (v, d + f"; prompt mentions '{risk.critical_terms[0]}'", p)
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _memory_flags(risk: Risk, prim, memory, best: _Best) -> None:
|
|
243
|
+
if memory is None:
|
|
244
|
+
return
|
|
245
|
+
for c in prim:
|
|
246
|
+
for sig in memory.signals_for(c.path):
|
|
247
|
+
risk.memory_flags.append(MemoryFlag(sig.kind, sig.path_or_term, c.path,
|
|
248
|
+
sig.text, sig.source))
|
|
249
|
+
v = MEMORY_KIND_VALUE.get(sig.kind, 0.3) * _scale(c.confidence)
|
|
250
|
+
best.offer("memory", v, f"{sig.kind}: '{sig.path_or_term}' ({_short(sig.text)})", c.path)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def assess_risk(location, task: str, cfg, graph=None, memory=None) -> Risk:
|
|
254
|
+
rc = cfg["risk"]
|
|
255
|
+
weights = rc["weights"]
|
|
256
|
+
risk = Risk(components={n: Component(n) for n in COMPONENTS})
|
|
257
|
+
comp = risk.components
|
|
258
|
+
prim = location.primary()
|
|
259
|
+
risk.evaluated = [c.path for c in prim]
|
|
260
|
+
best = _Best()
|
|
261
|
+
|
|
262
|
+
_code_metrics(risk, prim, graph, rc, best)
|
|
263
|
+
_critical_paths(risk, prim, task, cfg, best)
|
|
264
|
+
_memory_flags(risk, prim, memory, best)
|
|
265
|
+
|
|
266
|
+
for n in COMPONENTS:
|
|
267
|
+
v, d, p = best.items[n]
|
|
268
|
+
comp[n].value = round(v, 3)
|
|
269
|
+
if d:
|
|
270
|
+
comp[n].detail = d
|
|
271
|
+
comp[n].files = [p] if p else []
|
|
272
|
+
vals = {n: comp[n].value for n in COMPONENTS}
|
|
273
|
+
risk.code_risk = noisy_or(vals, weights, CODE_COMPONENTS)
|
|
274
|
+
if not prim and not risk.critical_terms:
|
|
275
|
+
risk.notes.append("no files located: risk unknown")
|
|
276
|
+
return risk
|
|
277
|
+
risk.score = noisy_or(vals, weights, COMPONENTS)
|
|
278
|
+
risk.level = ("high" if risk.score >= rc["high"] else
|
|
279
|
+
"medium" if risk.score >= rc["medium"] else "low")
|
|
280
|
+
return risk
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _short(s: str, n: int = 70) -> str:
|
|
284
|
+
s = " ".join(s.split())
|
|
285
|
+
return s if len(s) <= n else s[: n - 3] + "..."
|
ccr/evaluate/text.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Prompt tokenization shared by the classifier and the locator (stdlib only)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
_EXT = (r"py|pyi|ts|tsx|js|jsx|mjs|cjs|go|rs|java|kt|kts|scala|rb|php|cs|c|h|cc|cpp|hpp|swift|"
|
|
7
|
+
r"sql|ya?ml|json|toml|ini|cfg|md|rst|txt|sh|zig|ex|exs|lua|dart|vue|svelte|proto|tf|"
|
|
8
|
+
r"tfvars|mod|sum|lock|gradle|xml|html|css|scss|env|dockerfile")
|
|
9
|
+
# @path mentions (Claude Code file references), e.g. @src/app.ts or @README.md
|
|
10
|
+
AT_RX = re.compile(r"(?<![\w@])@((?:\.{0,2}/)?[\w.\-]+(?:/[\w.\-]+)*/?)")
|
|
11
|
+
# bare path-like tokens: a/b/c, ./x, file.ext
|
|
12
|
+
PATH_RX = re.compile(
|
|
13
|
+
r"(?<![\w@/.\-])((?:\.{1,2}/)?(?:[\w.\-]+/)+[\w.\-]*|[\w\-]+(?:\.[\w\-]+)*\.(?:" + _EXT +
|
|
14
|
+
r"))(?![\w/])", re.I)
|
|
15
|
+
TICK_RX = re.compile(r"`([^`\n]{1,120})`")
|
|
16
|
+
URL_RX = re.compile(r"\bhttps?://\S+|\bwww\.\S+", re.I)
|
|
17
|
+
QUOTED_RX = re.compile(r"\"[^\"\n]{3,200}\"|'[^'\n]{6,200}'")
|
|
18
|
+
IDENT_RX = re.compile(
|
|
19
|
+
r"\b(?:[A-Za-z_]\w*(?:\.|::|#)[A-Za-z_]\w*" # Engine.run / store::get
|
|
20
|
+
r"|[A-Za-z_]\w*(?=\(\))" # paginate()
|
|
21
|
+
r"|[a-z]+[A-Z]\w*|[A-Z][a-z0-9]+[A-Z]\w*" # camelCase / CamelCase
|
|
22
|
+
r"|[A-Za-z]\w*_\w+" # snake_case
|
|
23
|
+
r"|[A-Z][a-z0-9]{2,})\b(?:\(\))?") # Capitalized (Button, Engine)
|
|
24
|
+
WORD_RX = re.compile(r"[a-z0-9][a-z0-9+\-]*[a-z0-9]|[a-z0-9]", re.I)
|
|
25
|
+
|
|
26
|
+
_SLASH_WORDS = {"and/or", "either/or", "i/o", "n/a", "w/o", "yes/no", "on/off", "read/write",
|
|
27
|
+
"input/output", "client/server", "true/false", "ci/cd", "async/await"}
|
|
28
|
+
|
|
29
|
+
STOP = frozenset("""
|
|
30
|
+
a an the and or but nor so yet to of in on at by for with from into onto over under about as
|
|
31
|
+
is are was were be been being am it its it's this that these those there here then than
|
|
32
|
+
what where which who whom whose when why how do does did done doing can could should would
|
|
33
|
+
will shall may might must please pls let lets let's i me my we our us you your they them their
|
|
34
|
+
he she his her not no yes also just only very more less much many few some any each every all
|
|
35
|
+
both either neither one two three first last next previous same other another such own
|
|
36
|
+
make makes made sure need needs want wants like get gets got set sets put use uses using used
|
|
37
|
+
add adds added fix fixes fixed change changes changed update updates updated create creates
|
|
38
|
+
implement write remove delete rename move edit modify improve handle handles support
|
|
39
|
+
new old existing current now still again instead without within via per etc
|
|
40
|
+
code codes file files function functions method methods class classes module modules
|
|
41
|
+
bug bugs error errors issue issues problem problems feature features test tests testing
|
|
42
|
+
line lines value values data type types variable variables var name names thing things stuff
|
|
43
|
+
project repo repository codebase app application system logic way part work works working
|
|
44
|
+
broken wrong bad good better best simple small large big quick quickly whole entire
|
|
45
|
+
everywhere across throughout something somehow anything everything nothing whatever
|
|
46
|
+
explain describe tell show find look see check run runs running call calls called return
|
|
47
|
+
returns returned page help okay ok hey hi thanks thank
|
|
48
|
+
""".split())
|
|
49
|
+
|
|
50
|
+
_CAMEL = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
# "in this session", "earlier in the session": the Claude Code conversation, not an auth
|
|
54
|
+
# session. Kept when a security noun follows ("this session token").
|
|
55
|
+
CONVERSATION_RX = re.compile(
|
|
56
|
+
r"\b(?:(?:this|that|current|same|previous|last|whole|entire|prior)\s+"
|
|
57
|
+
r"(?:(?:claude|chat|coding|work)\s+)?session"
|
|
58
|
+
r"|(?:earlier|later|before)\s+in\s+(?:the|this)\s+session)\b"
|
|
59
|
+
r"(?!\s+(?:tokens?|cookies?|ids?|keys?|secrets?|fixation|hijack\w*|management|expir\w*|"
|
|
60
|
+
r"invalidation|store|storage|data|handling|validation|timeouts?))", re.I)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def strip_refs(text: str) -> str:
|
|
64
|
+
"""Text with URLs, @mentions, paths, backticks, quoted strings and conversational
|
|
65
|
+
"this session" references blanked out."""
|
|
66
|
+
t = CONVERSATION_RX.sub(" ", text)
|
|
67
|
+
t = URL_RX.sub(" ", t)
|
|
68
|
+
t = TICK_RX.sub(" ", t)
|
|
69
|
+
t = QUOTED_RX.sub(" ", t)
|
|
70
|
+
t = AT_RX.sub(" ", t)
|
|
71
|
+
t = PATH_RX.sub(lambda m: m.group(0) if m.group(0).lower() in _SLASH_WORDS else " ", t)
|
|
72
|
+
return t
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def path_tokens(text: str) -> tuple[list[str], list[str]]:
|
|
76
|
+
"""(@-mentioned paths, other path-like tokens), cleaned and de-duplicated."""
|
|
77
|
+
text = URL_RX.sub(" ", text)
|
|
78
|
+
ats = _uniq(_clean_path(m.group(1)) for m in AT_RX.finditer(text))
|
|
79
|
+
rest = AT_RX.sub(" ", text)
|
|
80
|
+
found = []
|
|
81
|
+
for m in TICK_RX.finditer(rest):
|
|
82
|
+
inner = m.group(1).strip()
|
|
83
|
+
if " " not in inner and ("/" in inner or PATH_RX.fullmatch(inner)):
|
|
84
|
+
found.append(inner)
|
|
85
|
+
for m in PATH_RX.finditer(TICK_RX.sub(" ", rest)):
|
|
86
|
+
v = m.group(1)
|
|
87
|
+
if v.lower() in _SLASH_WORDS or not re.search(r"[A-Za-z]", v):
|
|
88
|
+
continue
|
|
89
|
+
if re.fullmatch(r"\d+(\.\d+)+", v) or v.endswith("/") and len(v) <= 2:
|
|
90
|
+
continue
|
|
91
|
+
found.append(v)
|
|
92
|
+
paths = _uniq(_clean_path(p) for p in found)
|
|
93
|
+
return [a for a in ats if a], [p for p in paths if p and p not in ats]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def identifiers(text: str) -> list[str]:
|
|
97
|
+
"""Symbol-shaped tokens: backticked names, Dotted.names, calls(), camelCase, snake_case,
|
|
98
|
+
Capitalized words that are not the first word of a sentence."""
|
|
99
|
+
out = []
|
|
100
|
+
for m in TICK_RX.finditer(text):
|
|
101
|
+
inner = m.group(1).strip().rstrip("()")
|
|
102
|
+
if inner and " " not in inner and "/" not in inner and not PATH_RX.fullmatch(inner):
|
|
103
|
+
out.append(inner)
|
|
104
|
+
body = TICK_RX.sub(" ", URL_RX.sub(" ", text))
|
|
105
|
+
body = AT_RX.sub(" ", body)
|
|
106
|
+
body = PATH_RX.sub(" ", body)
|
|
107
|
+
for m in IDENT_RX.finditer(body):
|
|
108
|
+
tok = m.group(0).rstrip("()")
|
|
109
|
+
start = m.start()
|
|
110
|
+
before = body[:start].rstrip()
|
|
111
|
+
sentence_start = not before or before[-1] in ".!?;:\n"
|
|
112
|
+
if re.fullmatch(r"[A-Z][a-z0-9]{2,}", tok) and (sentence_start or tok.lower() in STOP):
|
|
113
|
+
continue
|
|
114
|
+
out.append(tok)
|
|
115
|
+
return _uniq(out)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def words(text: str) -> list[str]:
|
|
119
|
+
return [w.lower() for w in WORD_RX.findall(text)]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def content_words(text: str, min_len: int = 3) -> list[str]:
|
|
123
|
+
return _uniq(w for w in words(strip_refs(text)) if len(w) >= min_len and w not in STOP
|
|
124
|
+
and not w.isdigit())
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def stem(w: str) -> str:
|
|
128
|
+
w = w.lower()
|
|
129
|
+
for suf in ("ies", "ing", "es", "ed", "s"):
|
|
130
|
+
if w.endswith(suf) and len(w) - len(suf) >= 4:
|
|
131
|
+
if suf == "ies":
|
|
132
|
+
return w[:-3] + "y"
|
|
133
|
+
if suf == "es" and not w.endswith(("sses", "xes", "ches", "shes", "zes")):
|
|
134
|
+
return w[:-1]
|
|
135
|
+
return w[: -len(suf)]
|
|
136
|
+
return w
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def split_ident(name: str) -> list[str]:
|
|
140
|
+
"""Components of a path segment or identifier: useAuth.ts -> [use, auth]."""
|
|
141
|
+
parts = []
|
|
142
|
+
for chunk in re.split(r"[/_.\-\s]+", name):
|
|
143
|
+
if chunk:
|
|
144
|
+
parts += [p.lower() for p in _CAMEL.sub(" ", chunk).split()]
|
|
145
|
+
return parts
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def phrase_in(phrase: str, text_words: list[str]) -> bool:
|
|
149
|
+
"""Whole-word (stemmed) phrase containment."""
|
|
150
|
+
pw = [stem(w) for w in words(phrase)]
|
|
151
|
+
if not pw:
|
|
152
|
+
return False
|
|
153
|
+
tw = [stem(w) for w in text_words]
|
|
154
|
+
n = len(pw)
|
|
155
|
+
return any(tw[i:i + n] == pw for i in range(len(tw) - n + 1))
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _clean_path(p: str) -> str:
|
|
159
|
+
p = p.strip().strip("`'\"()[]{}<>,;:!?")
|
|
160
|
+
p = re.sub(r"[.:]+$", "", p) if not p.endswith("/") else p
|
|
161
|
+
while p.startswith("./"):
|
|
162
|
+
p = p[2:]
|
|
163
|
+
return p
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _uniq(items) -> list:
|
|
167
|
+
seen, out = set(), []
|
|
168
|
+
for x in items:
|
|
169
|
+
if x not in seen:
|
|
170
|
+
seen.add(x)
|
|
171
|
+
out.append(x)
|
|
172
|
+
return out
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
RETRY = re.compile(
|
|
176
|
+
r"\b(?:still\s+(?:fail\w*|broken|wrong|getting|erroring|crash\w*|red|"
|
|
177
|
+
r"not\s+(?:work\w*|fix\w*|pass\w*|right|correct|compil\w*|load\w*|show\w*|resolved)|"
|
|
178
|
+
r"the\s+same|happening|there|seeing)"
|
|
179
|
+
r"|(?:did\s*n[o']?t|does\s*n[o']?t|doesn'?t|didn'?t|isn'?t|is\s+not|wasn'?t)\s+"
|
|
180
|
+
r"(?:work\w*|fix\w*|help\w*|solve\w*|change\w*)"
|
|
181
|
+
r"|not\s+(?:fixed|working|solved|resolved)"
|
|
182
|
+
r"|same\s+(?:error|problem|issue|failure|exception|bug|result)"
|
|
183
|
+
r"|(?:that|this|it)\s+(?:broke|made\s+it\s+worse)"
|
|
184
|
+
r"|(?:try|do\s+it)\s+again|no\s+luck|wrong\s+again|regress\w*|nothing\s+changed"
|
|
185
|
+
r"|(?:tests?|build|ci)\s+(?:still\s+)?(?:fail\w*|red|broken))", re.I)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def is_retry(prompt: str) -> bool:
|
|
189
|
+
""""still failing", "that did not work": a follow-up about the previous attempt."""
|
|
190
|
+
return bool(RETRY.search(prompt[:400]))
|
ccr/graph/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Code graph: files, symbols, imports, calls, complexity and git signals in .ccr/graph.db.
|
|
2
|
+
|
|
3
|
+
Query helpers are sqlite-only (safe for hooks); building imports tree-sitter lazily.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from ccr.graph.query import Dependent, Graph, Symbol, TestLink, freshness
|
|
8
|
+
|
|
9
|
+
__all__ = ["Dependent", "Graph", "Symbol", "TestLink", "freshness", "update"]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def update(root, **kwargs):
|
|
13
|
+
"""Incrementally update (or build) the graph. See ccr.graph.build.update."""
|
|
14
|
+
from ccr.graph.build import update as _update
|
|
15
|
+
return _update(root, **kwargs)
|