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/evaluate/llm.py ADDED
@@ -0,0 +1,182 @@
1
+ """Optional LLM assist for low-confidence classifications.
2
+
3
+ Uses only the user's own `claude` CLI found on PATH (`claude -p --model haiku --effort low`),
4
+ never an API key or SDK. Disabled in hooks; callers opt in (`ccr explain --llm`, `ccr run`).
5
+ Everything funnels through `run_claude`, so tests replace that one function.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ from dataclasses import dataclass, field
15
+
16
+ from ccr.config import CLASSES
17
+
18
+ SCOPES = ("small", "medium", "large")
19
+
20
+
21
+ @dataclass
22
+ class LLMHint:
23
+ kind: str | None = None
24
+ scope: str | None = None
25
+ vague: bool | None = None
26
+ files: list[str] = field(default_factory=list)
27
+ confidence: float | None = None
28
+ reason: str = ""
29
+ cost_usd: float | None = None
30
+
31
+
32
+ class LLMUnavailable(RuntimeError):
33
+ pass
34
+
35
+
36
+ def claude_command(model: str, effort: str) -> list[str]:
37
+ exe = shutil.which("claude")
38
+ if not exe:
39
+ raise LLMUnavailable("`claude` CLI not found on PATH")
40
+ # no tools, no MCP servers, no saved session: a single cheap classification turn
41
+ return [exe, "-p", "--model", model, "--effort", effort, "--output-format", "json",
42
+ "--tools", "", "--strict-mcp-config", "--no-session-persistence"]
43
+
44
+
45
+ def run_claude(prompt: str, *, model: str = "haiku", effort: str = "low",
46
+ timeout: float = 45) -> dict:
47
+ """Run the user's claude CLI headlessly; return its JSON result object. Mock me in tests."""
48
+ cmd = claude_command(model, effort)
49
+ env = {**os.environ, "CCR_INTERNAL": "1"} # ccr hooks no-op inside this call
50
+ env.pop("CLAUDE_CODE_EFFORT_LEVEL", None)
51
+ try:
52
+ r = subprocess.run(cmd, input=prompt, capture_output=True, text=True, timeout=timeout,
53
+ env=env)
54
+ except subprocess.TimeoutExpired as e:
55
+ raise LLMUnavailable(f"claude timed out after {timeout:.0f}s") from e
56
+ except OSError as e:
57
+ raise LLMUnavailable(f"cannot run claude: {e}") from e
58
+ out = (r.stdout or "").strip()
59
+ try:
60
+ data = json.loads(out.splitlines()[-1] if out else "")
61
+ except (ValueError, IndexError) as e:
62
+ raise LLMUnavailable(f"claude returned non-JSON output (exit {r.returncode}): "
63
+ f"{(r.stderr or out)[:200]}") from e
64
+ if not isinstance(data, dict):
65
+ raise LLMUnavailable("claude JSON output is not an object")
66
+ if data.get("is_error"):
67
+ raise LLMUnavailable(f"claude reported an error: {str(data.get('result'))[:200]}")
68
+ return data
69
+
70
+
71
+ PROMPT = """You classify a software task for model routing. Reply with ONE JSON object only, no
72
+ prose, no code fences:
73
+ {{"class": one of {classes}, "scope": "small"|"medium"|"large", "vague": true|false,
74
+ "files": [up to 5 project-relative paths from the summary most likely touched],
75
+ "confidence": 0.0-1.0, "reason": "<= 15 words"}}
76
+ Classes: question=explain/lookup only; trivial=typo/rename/format/version bump; tests=write tests;
77
+ bugfix=clear bug; feature=new behaviour; refactor=restructure without behaviour change;
78
+ perf=speed/memory; migration=framework/language/schema migration; security=vulnerability/auth
79
+ hardening; debugging=unclear, intermittent or concurrency bug needing investigation.
80
+
81
+ Project summary:
82
+ {summary}
83
+
84
+ Rule-based guess: {guess}
85
+
86
+ Task:
87
+ <<<
88
+ {task}
89
+ >>>"""
90
+
91
+
92
+ def build_prompt(task: str, summary: str, guess: str) -> str:
93
+ return PROMPT.format(classes="|".join(f'"{c}"' for c in CLASSES), summary=summary,
94
+ guess=guess, task=task.strip()[:4000])
95
+
96
+
97
+ def parse_hint(text: str) -> LLMHint | None:
98
+ """Lenient JSON extraction from the model's reply; None when nothing usable."""
99
+ if not text:
100
+ return None
101
+ m = re.search(r"\{.*\}", text, re.S)
102
+ if not m:
103
+ return None
104
+ try:
105
+ obj = json.loads(m.group(0))
106
+ except ValueError:
107
+ return None
108
+ if not isinstance(obj, dict):
109
+ return None
110
+ hint = LLMHint()
111
+ k = str(obj.get("class") or "").strip().lower()
112
+ hint.kind = k if k in CLASSES else None
113
+ s = str(obj.get("scope") or "").strip().lower()
114
+ hint.scope = s if s in SCOPES else None
115
+ if isinstance(obj.get("vague"), bool):
116
+ hint.vague = obj["vague"]
117
+ files = obj.get("files")
118
+ if isinstance(files, list):
119
+ hint.files = [_rel(f) for f in files if isinstance(f, str) and f.strip()][:5]
120
+ c = obj.get("confidence")
121
+ if isinstance(c, (int, float)) and not isinstance(c, bool):
122
+ hint.confidence = max(0.0, min(1.0, float(c)))
123
+ hint.reason = str(obj.get("reason") or "")[:200]
124
+ if hint.kind is None and hint.scope is None and not hint.files:
125
+ return None
126
+ return hint
127
+
128
+
129
+ def _rel(p: str) -> str:
130
+ p = p.strip()
131
+ while p.startswith("./"):
132
+ p = p[2:]
133
+ return p
134
+
135
+
136
+ def assist(task: str, summary: str, guess: str, *, model: str = "haiku", effort: str = "low",
137
+ timeout: float = 45, runner=None) -> tuple[LLMHint | None, str]:
138
+ """(hint or None, status message). Never raises."""
139
+ runner = runner or run_claude
140
+ try:
141
+ data = runner(build_prompt(task, summary, guess), model=model, effort=effort,
142
+ timeout=timeout)
143
+ except LLMUnavailable as e:
144
+ return None, f"LLM assist unavailable: {e}"
145
+ except Exception as e: # a broken runner must not break routing
146
+ return None, f"LLM assist failed: {e}"
147
+ hint = parse_hint(str(data.get("result") or ""))
148
+ if hint is None:
149
+ return None, "LLM assist returned no usable classification"
150
+ cost = data.get("total_cost_usd")
151
+ if isinstance(cost, (int, float)):
152
+ hint.cost_usd = float(cost)
153
+ return hint, f"LLM assist ({model}/{effort})"
154
+
155
+
156
+ def graph_summary(root, graph, location, max_chars: int = 2500) -> str:
157
+ """Compact, token-cheap project summary: languages, top directories, candidate files."""
158
+ lines = []
159
+ if graph is not None:
160
+ try:
161
+ st = graph.conn.execute(
162
+ "SELECT lang, COUNT(*) FROM nodes WHERE kind='file' GROUP BY lang "
163
+ "ORDER BY 2 DESC LIMIT 6").fetchall()
164
+ lines.append("languages: " + ", ".join(f"{lang or '?'} {n}" for lang, n in st))
165
+ dirs: dict[str, int] = {}
166
+ for (p,) in graph.conn.execute("SELECT path FROM nodes WHERE kind='file'"):
167
+ parts = p.split("/")
168
+ key = "/".join(parts[:2]) if len(parts) > 2 else (parts[0] if len(parts) > 1
169
+ else ".")
170
+ dirs[key] = dirs.get(key, 0) + 1
171
+ top = sorted(dirs.items(), key=lambda kv: -kv[1])[:15]
172
+ lines.append("directories: " + ", ".join(f"{d} ({n})" for d, n in top))
173
+ except Exception:
174
+ pass
175
+ else:
176
+ lines.append("no code graph available")
177
+ if location is not None and location.candidates:
178
+ lines.append("candidate files (rule match confidence):")
179
+ for c in location.candidates[:10]:
180
+ lines.append(f" {c.path} {c.confidence:.2f} ({'; '.join(c.reasons[:2])})")
181
+ out = "\n".join(lines)
182
+ return out if len(out) <= max_chars else out[: max_chars - 3] + "..."
ccr/evaluate/locate.py ADDED
@@ -0,0 +1,359 @@
1
+ """Locate the code a task touches: @-mentions and named paths, symbol names, path words and
2
+ memory entities, matched against the code graph (or the file tree when no graph exists).
3
+
4
+ Every candidate carries a confidence in [0, 1] and the reasons it was picked. Evidence for the
5
+ same file is combined noisy-or style, so two weak hits ("stripe" + "client") reinforce.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ import posixpath
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ from ccr.evaluate import text as T
15
+
16
+ BROAD_WORD_FILES = 25 # a word matching more files than this is too broad to use
17
+ MAX_CANDIDATES = 40
18
+ MAX_OTHER_FILES = 5000 # non-graph files (docs, config, IaC) considered for matching
19
+ TOOL_CONFIG_PREFIXES = (".claude/", ".ccr/")
20
+ _CODE_EXT_PARTS = {"py", "pyi", "ts", "tsx", "js", "jsx", "mjs", "cjs", "go", "rs", "java", "kt",
21
+ "rb", "php", "cs", "c", "h", "cc", "cpp", "hpp", "swift", "scala", "zig", "md",
22
+ "json", "yaml", "yml", "toml", "txt", "lua", "ex", "exs", "dart", "sh"}
23
+ # path components that say nothing about the area
24
+ _GENERIC_DIRS = {"src", "lib", "app", "apps", "pkg", "internal", "cmd", "main", "java", "com",
25
+ "org", "index", "mod", "init", "__init__", "core", "common", "shared", "utils",
26
+ "util", "helpers", "test", "tests", "spec", "__tests__"}
27
+
28
+
29
+ @dataclass
30
+ class Candidate:
31
+ path: str
32
+ confidence: float
33
+ reasons: list[str] = field(default_factory=list)
34
+ indexed: bool = True # present in the code graph
35
+ is_test: bool = False
36
+
37
+
38
+ @dataclass
39
+ class Location:
40
+ candidates: list[Candidate] = field(default_factory=list)
41
+ explicit: list[str] = field(default_factory=list) # resolved @-mentions / named paths
42
+ mentioned: list[str] = field(default_factory=list) # @-mentions (subset of explicit)
43
+ unresolved: list[str] = field(default_factory=list) # named paths not found
44
+ symbols: list[str] = field(default_factory=list) # identifiers that resolved
45
+ terms: list[str] = field(default_factory=list) # plain words that matched paths
46
+ broad_terms: list[str] = field(default_factory=list)
47
+ memory_terms: list[str] = field(default_factory=list)
48
+ confidence: float = 0.0
49
+ graph: bool = False
50
+ notes: list[str] = field(default_factory=list)
51
+
52
+ @property
53
+ def located(self) -> bool:
54
+ return self.confidence >= 0.45
55
+
56
+ def primary(self, limit: int = 8) -> list[Candidate]:
57
+ """The files risk is scored over."""
58
+ strong = [c for c in self.candidates if c.confidence >= 0.4]
59
+ if strong:
60
+ return strong[:limit]
61
+ return [c for c in self.candidates if c.confidence >= 0.2][:3]
62
+
63
+ def top_area(self) -> str:
64
+ """Coarse area key for history: up to two leading directories of the top candidate."""
65
+ prim = self.primary(1)
66
+ if not prim:
67
+ return "*"
68
+ d = posixpath.dirname(prim[0].path)
69
+ return "/".join(d.split("/")[:2]) if d else "."
70
+
71
+
72
+ class _Acc:
73
+ def __init__(self):
74
+ self.miss: dict[str, float] = {}
75
+ self.reasons: dict[str, list[str]] = {}
76
+
77
+ def add(self, path: str, conf: float, reason: str) -> None:
78
+ conf = max(0.0, min(1.0, conf))
79
+ self.miss[path] = self.miss.get(path, 1.0) * (1.0 - conf)
80
+ rs = self.reasons.setdefault(path, [])
81
+ if reason not in rs:
82
+ rs.append(reason)
83
+
84
+ def items(self):
85
+ for p, m in self.miss.items():
86
+ yield p, 1.0 - m, self.reasons[p]
87
+
88
+
89
+ def _universe(root: Path, graph) -> tuple[list[str], set[str], set[str]]:
90
+ """(all known files, graph-indexed files, test files)."""
91
+ indexed: set[str] = set()
92
+ tests: set[str] = set()
93
+ if graph is not None:
94
+ for path, is_test in graph.conn.execute(
95
+ "SELECT path, is_test FROM nodes WHERE kind = 'file'"):
96
+ indexed.add(path)
97
+ if is_test:
98
+ tests.add(path)
99
+ others: list[str] = []
100
+ try:
101
+ from ccr.graph import git as ggit
102
+ listed = ggit.ls_files(root) # None outside git
103
+ except Exception:
104
+ listed = None
105
+ if listed is None:
106
+ try:
107
+ from ccr.graph.files import walk_files
108
+ listed = walk_files(root)
109
+ except Exception:
110
+ listed = []
111
+ from ccr.graph.files import in_skipped_dir, is_skipped_name, is_test_path
112
+ for p in listed:
113
+ if p in indexed or in_skipped_dir(p) or is_skipped_name(posixpath.basename(p)):
114
+ continue
115
+ # Claude Code's own config (agents, settings, commands) is not project code: its
116
+ # words ("explore", "implement", "tests") would match ordinary prompts. Named paths
117
+ # still resolve through the is_file() fallback in locate().
118
+ if p.startswith(TOOL_CONFIG_PREFIXES):
119
+ continue
120
+ others.append(p)
121
+ if len(others) > MAX_OTHER_FILES: # huge trees: keep the shallowest non-code files
122
+ others = sorted(others, key=lambda x: (x.count("/"), x))[:MAX_OTHER_FILES]
123
+ if graph is None:
124
+ tests.update(p for p in others if is_test_path(p))
125
+ return sorted(indexed) + sorted(others), indexed, tests
126
+
127
+
128
+ def _components(path: str) -> tuple[list[str], list[str]]:
129
+ """(directory word components, file-stem word components)."""
130
+ parts = path.split("/")
131
+ dirs: list[str] = []
132
+ for d in parts[:-1]:
133
+ dirs += T.split_ident(d)
134
+ name = parts[-1]
135
+ stem = name.split(".")[0] if not name.startswith(".") else name[1:]
136
+ return dirs, [c for c in T.split_ident(stem) if c not in _CODE_EXT_PARTS]
137
+
138
+
139
+ def _sym_rows(graph, name: str, nocase: bool) -> list[tuple[str, str | None, str]]:
140
+ op = "= ? COLLATE NOCASE" if nocase else "= ?"
141
+ return [(r[0], r[1], r[2]) for r in graph.conn.execute(
142
+ "SELECT DISTINCT n.path, p.name, n.name FROM nodes n LEFT JOIN nodes p "
143
+ f"ON p.id = n.parent_id WHERE n.kind != 'file' AND n.name {op} LIMIT 60", (name,))]
144
+
145
+
146
+ @dataclass
147
+ class _Ctx:
148
+ """State shared by the matching stages of `locate`."""
149
+ task: str
150
+ root: Path
151
+ graph: object
152
+ loc: Location
153
+ acc: _Acc
154
+ universe: list[str]
155
+ indexed: set[str]
156
+ tests: set[str]
157
+ wants_tests: bool
158
+ uni_set: set[str] = field(init=False)
159
+ _suffix: dict[str, list[str]] = field(default_factory=dict)
160
+
161
+ def __post_init__(self) -> None:
162
+ self.uni_set = set(self.universe)
163
+
164
+ def suffix(self, frag: str) -> list[str]:
165
+ if frag not in self._suffix:
166
+ f = frag.strip("/")
167
+ self._suffix[frag] = [p for p in self.universe if p == f or p.endswith("/" + f)]
168
+ return self._suffix[frag]
169
+
170
+
171
+ def _match_paths(c: _Ctx) -> None:
172
+ """1) @-mentions and named paths."""
173
+ loc = c.loc
174
+ ats, named = T.path_tokens(c.task)
175
+ for tok, how in [(a, "@-mentioned") for a in ats] + [(n, "named in prompt") for n in named]:
176
+ frag = tok.strip("/")
177
+ if frag in c.uni_set:
178
+ hits = [frag]
179
+ else:
180
+ under = [p for p in c.universe if p.startswith(frag + "/")]
181
+ if under:
182
+ n = len(under)
183
+ for p in under[:30]:
184
+ c.acc.add(p, max(0.35, 0.9 / math.sqrt(n)), f"{how} (in {frag}/)")
185
+ loc.explicit.append(frag + "/")
186
+ if how == "@-mentioned":
187
+ loc.mentioned.append(frag + "/")
188
+ continue
189
+ hits = c.suffix(frag)
190
+ if not hits and (c.root / frag).is_file():
191
+ hits = [frag]
192
+ c.universe.append(frag)
193
+ c.uni_set.add(frag)
194
+ if not hits:
195
+ loc.unresolved.append(tok)
196
+ continue
197
+ conf = 1.0 if len(hits) == 1 else 0.9 / math.sqrt(len(hits))
198
+ for p in hits[:10]:
199
+ c.acc.add(p, conf, how)
200
+ loc.explicit.append(hits[0] if len(hits) == 1 else frag)
201
+ if how == "@-mentioned":
202
+ loc.mentioned.append(hits[0] if len(hits) == 1 else frag)
203
+
204
+
205
+ def _symbol_files(graph, name: str, qual: str | None) -> tuple[list[str], bool]:
206
+ """Files defining `name` (narrowed by a qualifier), and whether the match was exact-case."""
207
+ rows = _sym_rows(graph, name, nocase=False)
208
+ exact = bool(rows)
209
+ if not rows:
210
+ rows = _sym_rows(graph, name, nocase=True)
211
+ if qual:
212
+ q = qual.lower()
213
+ narrowed = [r for r in rows if (r[1] or "").lower() == q
214
+ or q in r[0].lower().replace("_", "")]
215
+ rows = narrowed or rows
216
+ return sorted({r[0] for r in rows}), exact
217
+
218
+
219
+ def _match_identifiers(c: _Ctx) -> set[str]:
220
+ """2) identifiers -> symbols (graph) or file stems. Returns the words they consumed."""
221
+ loc = c.loc
222
+ used_words: set[str] = set()
223
+ for ident in T.identifiers(c.task):
224
+ parts = [p for p in ident.replace("::", ".").replace("#", ".").split(".") if p]
225
+ name, qual = parts[-1], (parts[-2] if len(parts) > 1 else None)
226
+ found: list[str] = []
227
+ exact = False
228
+ if c.graph is not None:
229
+ found, exact = _symbol_files(c.graph, name, qual)
230
+ stem_hits = [p for p in c.universe
231
+ if posixpath.basename(p).split(".")[0].lower() in
232
+ {name.lower(), (qual or "").lower()} - {""}]
233
+ if found:
234
+ base = 0.85 if exact else 0.6
235
+ for p in found[:20]:
236
+ c.acc.add(p, base / math.sqrt(len(found)), f"symbol {ident}")
237
+ loc.symbols.append(ident)
238
+ if stem_hits and len(stem_hits) <= 10:
239
+ for p in stem_hits:
240
+ c.acc.add(p, 0.75 / math.sqrt(len(stem_hits)), f"file name ~ {ident}")
241
+ if ident not in loc.symbols:
242
+ loc.symbols.append(ident)
243
+ if found or stem_hits: # resolved: its words are not re-used as plain path words
244
+ used_words.update(w.lower() for w in T.split_ident(ident))
245
+ used_words.update(p.lower() for p in parts)
246
+ return used_words
247
+
248
+
249
+ def _match_words(c: _Ctx, used_words: set[str]) -> None:
250
+ """3) plain words -> symbol names and path components."""
251
+ loc = c.loc
252
+ comps = {p: _components(p) for p in c.universe}
253
+ for w in T.content_words(c.task):
254
+ if w in used_words or len(w) < 3:
255
+ continue
256
+ sw = T.stem(w)
257
+ file_hits = [p for p, (_, fs) in comps.items() if any(T.stem(x) == sw for x in fs)]
258
+ dir_hits = [p for p, (ds, fs) in comps.items() if p not in file_hits
259
+ and any(T.stem(x) == sw for x in ds) and sw not in _GENERIC_DIRS]
260
+ sym_hits: list[str] = []
261
+ if c.graph is not None and len(w) >= 4:
262
+ sym_hits = sorted({r[0] for r in _sym_rows(c.graph, w, nocase=True)})
263
+ hit_set = set(file_hits) | set(dir_hits) | set(sym_hits)
264
+ if not hit_set:
265
+ continue
266
+ # tests that merely share the word do not dilute the match for the code they test
267
+ non_test = hit_set - c.tests if not c.wants_tests else hit_set
268
+ total = len(non_test) or len(hit_set)
269
+ if total > BROAD_WORD_FILES:
270
+ loc.broad_terms.append(w)
271
+ continue
272
+ loc.terms.append(w)
273
+ n = math.sqrt(total)
274
+ for p in file_hits:
275
+ c.acc.add(p, 0.5 / n, f"path word '{w}'")
276
+ for p in dir_hits:
277
+ c.acc.add(p, 0.35 / n, f"directory '{w}'")
278
+ for p in sym_hits:
279
+ c.acc.add(p, 0.45 / n, f"symbol name '{w}'")
280
+
281
+
282
+ def _match_memory(c: _Ctx, memory) -> None:
283
+ """4) memory entities mentioned in the prompt."""
284
+ if memory is None or not getattr(memory, "signals", None):
285
+ return
286
+ from ccr.memory import matches
287
+ loc = c.loc
288
+ prompt_words = T.words(T.strip_refs(c.task))
289
+ seen_terms: set[str] = set()
290
+ for sig in memory.signals:
291
+ term = sig.path_or_term
292
+ key = term.lower()
293
+ if key in seen_terms:
294
+ continue
295
+ significant = [x for x in T.words(term) if x not in T.STOP and len(x) >= 3
296
+ and x not in _CODE_EXT_PARTS]
297
+ if not significant:
298
+ continue
299
+ mentioned = any(term == e or term.strip("/") == e.strip("/") for e in loc.explicit) \
300
+ or T.phrase_in(" ".join(significant), prompt_words)
301
+ if not mentioned:
302
+ continue
303
+ seen_terms.add(key)
304
+ hits = [p for p in c.universe if matches(sig, p)]
305
+ if not hits or len(hits) > BROAD_WORD_FILES:
306
+ continue
307
+ loc.memory_terms.append(term)
308
+ for p in hits:
309
+ c.acc.add(p, 0.55 / math.sqrt(len(hits)), f"memory entity '{term}'")
310
+
311
+
312
+ def _rank(c: _Ctx) -> list[Candidate]:
313
+ cands = []
314
+ for p, conf, reasons in c.acc.items():
315
+ is_test = p in c.tests
316
+ if is_test and not c.wants_tests and not any(r in ("@-mentioned", "named in prompt")
317
+ for r in reasons):
318
+ conf *= 0.6
319
+ cands.append(Candidate(p, round(conf, 3), reasons, p in c.indexed, is_test))
320
+ cands.sort(key=lambda x: (-x.confidence, len(x.path), x.path))
321
+ return cands
322
+
323
+
324
+ def locate(task: str, root: str | Path, graph=None, memory=None,
325
+ files: list[str] | None = None) -> Location:
326
+ """Find candidate files for `task`. `graph`: open ccr.graph.Graph or None; `memory`:
327
+ ccr.memory.MemoryReport or None; `files`: override the file universe (tests)."""
328
+ root = Path(root).resolve()
329
+ loc = Location(graph=graph is not None)
330
+ if files is not None:
331
+ from ccr.graph.files import is_test_path
332
+ universe = sorted(set(files))
333
+ indexed, tests = set(), {p for p in universe if is_test_path(p)}
334
+ else:
335
+ universe, indexed, tests = _universe(root, graph)
336
+ if graph is None:
337
+ loc.notes.append("code graph not built (run `ccr graph`): matching paths only, "
338
+ "no blast radius / complexity")
339
+ c = _Ctx(task=task, root=root, graph=graph, loc=loc, acc=_Acc(), universe=universe,
340
+ indexed=indexed, tests=tests,
341
+ wants_tests=any(T.stem(w) == "test" for w in T.words(task)))
342
+ _match_paths(c)
343
+ used_words = _match_identifiers(c)
344
+ _match_words(c, used_words)
345
+ _match_memory(c, memory)
346
+
347
+ cands = _rank(c)
348
+ loc.candidates = cands[:MAX_CANDIDATES]
349
+ if loc.explicit and not loc.unresolved:
350
+ loc.confidence = 1.0
351
+ elif loc.explicit:
352
+ loc.confidence = 0.7
353
+ elif cands:
354
+ top = cands[0].confidence
355
+ crowd = sum(1 for x in cands if x.confidence >= 0.8 * top)
356
+ loc.confidence = round(top * (0.85 if crowd > 3 else 1.0), 3)
357
+ if loc.unresolved:
358
+ loc.notes.append("named but not found: " + ", ".join(loc.unresolved))
359
+ return loc