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/memory/sources.py ADDED
@@ -0,0 +1,422 @@
1
+ """Read-only discovery of Claude Code memory sources. Missing sources are silently skipped.
2
+
3
+ Sources:
4
+ * CLAUDE.md hierarchy: managed, user (config dir + rules/), ancestors of the project,
5
+ project (CLAUDE.md, .claude/CLAUDE.md, .claude/rules/**), CLAUDE.local.md, nested
6
+ subdirectory CLAUDE.md files, and @imports referenced from any of them.
7
+ * Auto memory: <config>/projects/<encoded project path>/memory/*.md (MEMORY.md first),
8
+ or the `autoMemoryDirectory` setting.
9
+ * Subagent memory: .claude/agent-memory/<agent>/, .claude/agent-memory-local/<agent>/,
10
+ <config>/agent-memory/<agent>/.
11
+ * MCP knowledge-graph memory JSONL (server-memory), located via MEMORY_FILE_PATH in
12
+ .mcp.json or the user config (~/.claude.json, incl. per-project mcpServers).
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import os
18
+ import re
19
+ import sys
20
+ from dataclasses import dataclass, field
21
+ from pathlib import Path
22
+ from typing import Iterator, Mapping
23
+
24
+ from ccr.graph.files import ALL_SKIP_DIRS
25
+
26
+ MAX_BYTES = 256_000
27
+ MAX_NESTED = 200
28
+ MAX_WALK_DIRS = 20_000
29
+ MAX_IMPORT_DEPTH = 4
30
+ MAX_DIR_FILES = 50
31
+
32
+ if sys.platform == "darwin":
33
+ MANAGED_DIRS = [Path("/Library/Application Support/ClaudeCode")]
34
+ elif os.name == "nt":
35
+ MANAGED_DIRS = [Path(os.environ.get("ProgramData", r"C:\ProgramData")) / "ClaudeCode",
36
+ Path(r"C:\Program Files\ClaudeCode")]
37
+ else:
38
+ MANAGED_DIRS = [Path("/etc/claude-code")]
39
+
40
+
41
+ @dataclass
42
+ class MemoryDoc:
43
+ kind: str # claude_md | claude_local | rules | import | auto_memory | agent_memory
44
+ scope: str # managed | user | ancestor | project | local | nested
45
+ path: Path
46
+ text: str
47
+ agent: str | None = None
48
+
49
+
50
+ @dataclass
51
+ class KGMemory:
52
+ path: Path
53
+ server: str
54
+ entities: list[dict] = field(default_factory=list)
55
+ relations: list[dict] = field(default_factory=list)
56
+
57
+
58
+ @dataclass
59
+ class Context:
60
+ root: Path
61
+ home: Path
62
+ environ: Mapping[str, str]
63
+ _project_paths: list[str] | None = field(default=None, repr=False)
64
+
65
+ @property
66
+ def config_dir(self) -> Path:
67
+ cd = self.environ.get("CLAUDE_CONFIG_DIR")
68
+ return Path(cd).expanduser() if cd else self.home / ".claude"
69
+
70
+ def user_json_candidates(self) -> list[Path]:
71
+ out = []
72
+ if self.environ.get("CLAUDE_CONFIG_DIR"):
73
+ out.append(self.config_dir / ".claude.json")
74
+ out.append(self.home / ".claude.json")
75
+ return out
76
+
77
+
78
+ def make_context(root: str | Path, home: str | Path | None = None,
79
+ environ: Mapping[str, str] | None = None) -> Context:
80
+ env = dict(os.environ if environ is None else environ)
81
+ h = Path(home) if home is not None else Path(env.get("HOME") or Path.home())
82
+ return Context(root=Path(root).resolve(), home=h, environ=env)
83
+
84
+
85
+ # --------------------------------------------------------------------------- io helpers
86
+ def read_text(p: Path, max_bytes: int = MAX_BYTES) -> str | None:
87
+ try:
88
+ if not p.is_file():
89
+ return None
90
+ with open(p, "rb") as f:
91
+ data = f.read(max_bytes)
92
+ return data.decode("utf-8", errors="replace")
93
+ except OSError:
94
+ return None
95
+
96
+
97
+ def read_json(p: Path) -> dict | None:
98
+ """Whole-file JSON object (config files such as ~/.claude.json can be several MB)."""
99
+ text = read_text(p, max_bytes=50_000_000)
100
+ if not text:
101
+ return None
102
+ try:
103
+ data = json.loads(text)
104
+ except ValueError:
105
+ return None
106
+ return data if isinstance(data, dict) else None
107
+
108
+
109
+ def _expand(value: str, ctx: Context, base: Path) -> Path:
110
+ """Expand ${VAR}, ${VAR:-default}, $VAR (from ctx.environ) and ~; relative -> base."""
111
+ s = re.sub(r"\$\{(\w+)(?::-([^}]*))?\}|\$(\w+)",
112
+ lambda m: ctx.environ.get(m.group(1) or m.group(3),
113
+ m.group(2) if m.group(2) is not None else m.group(0)),
114
+ value)
115
+ if s == "~" or s.startswith("~/"):
116
+ s = str(ctx.home) + s[1:]
117
+ p = Path(s)
118
+ return p if p.is_absolute() else (base / p)
119
+
120
+
121
+ # --------------------------------------------------------------------------- CLAUDE.md
122
+ _IMPORT_RX = re.compile(r"(?<![\w`@])@((?:~|\.{1,2})?/?[\w.\-/]+\.[A-Za-z0-9]+)")
123
+
124
+
125
+ def _strip_code(text: str) -> str:
126
+ text = re.sub(r"```.*?```", "", text, flags=re.DOTALL)
127
+ return re.sub(r"`[^`\n]*`", "", text)
128
+
129
+
130
+ def _with_imports(doc: MemoryDoc, ctx: Context, seen: set[Path], depth: int = 0
131
+ ) -> Iterator[MemoryDoc]:
132
+ yield doc
133
+ if depth >= MAX_IMPORT_DEPTH:
134
+ return
135
+ for m in _IMPORT_RX.finditer(_strip_code(doc.text)):
136
+ target = _expand(m.group(1), ctx, doc.path.parent)
137
+ try:
138
+ key = target.resolve()
139
+ except OSError:
140
+ continue
141
+ if key in seen:
142
+ continue
143
+ text = read_text(target)
144
+ if text is None:
145
+ continue
146
+ seen.add(key)
147
+ yield from _with_imports(MemoryDoc("import", doc.scope, target, text), ctx, seen,
148
+ depth + 1)
149
+
150
+
151
+ def _doc(kind: str, scope: str, p: Path, seen: set[Path], ctx: Context) -> Iterator[MemoryDoc]:
152
+ try:
153
+ key = p.resolve()
154
+ except OSError:
155
+ return
156
+ if key in seen:
157
+ return
158
+ text = read_text(p)
159
+ if text is None:
160
+ return
161
+ seen.add(key)
162
+ yield from _with_imports(MemoryDoc(kind, scope, p, text), ctx, seen)
163
+
164
+
165
+ def _rules(d: Path, scope: str, seen: set[Path], ctx: Context) -> Iterator[MemoryDoc]:
166
+ if not d.is_dir():
167
+ return
168
+ try:
169
+ files = sorted(d.rglob("*.md"))[:MAX_DIR_FILES]
170
+ except OSError:
171
+ return
172
+ for p in files:
173
+ yield from _doc("rules", scope, p, seen, ctx)
174
+
175
+
176
+ def _nested_dirs(root: Path) -> Iterator[Path]:
177
+ for visited, (dirpath, dirnames, filenames) in enumerate(os.walk(root), 1):
178
+ if visited > MAX_WALK_DIRS:
179
+ return
180
+ dirnames[:] = sorted(d for d in dirnames
181
+ if d not in ALL_SKIP_DIRS and not d.startswith("."))
182
+ if Path(dirpath) != root and ("CLAUDE.md" in filenames or "CLAUDE.local.md" in filenames):
183
+ yield Path(dirpath)
184
+
185
+
186
+ def claude_md_docs(ctx: Context, nested: bool = True) -> list[MemoryDoc]:
187
+ seen: set[Path] = set()
188
+ out: list[MemoryDoc] = []
189
+ for d in MANAGED_DIRS:
190
+ out += _doc("claude_md", "managed", d / "CLAUDE.md", seen, ctx)
191
+ out += _doc("claude_md", "user", ctx.config_dir / "CLAUDE.md", seen, ctx)
192
+ out += _rules(ctx.config_dir / "rules", "user", seen, ctx)
193
+ root = ctx.root
194
+ for anc in reversed(root.parents):
195
+ if anc == anc.parent: # filesystem root
196
+ continue
197
+ out += _doc("claude_md", "ancestor", anc / "CLAUDE.md", seen, ctx)
198
+ out += _doc("claude_local", "ancestor", anc / "CLAUDE.local.md", seen, ctx)
199
+ out += _doc("claude_md", "project", root / "CLAUDE.md", seen, ctx)
200
+ out += _doc("claude_md", "project", root / ".claude" / "CLAUDE.md", seen, ctx)
201
+ out += _rules(root / ".claude" / "rules", "project", seen, ctx)
202
+ out += _doc("claude_local", "local", root / "CLAUDE.local.md", seen, ctx)
203
+ if nested:
204
+ count = 0
205
+ for d in _nested_dirs(root):
206
+ for name, kind in (("CLAUDE.md", "claude_md"), ("CLAUDE.local.md", "claude_local")):
207
+ docs = list(_doc(kind, "nested", d / name, seen, ctx))
208
+ out += docs
209
+ count += len(docs)
210
+ if count >= MAX_NESTED:
211
+ break
212
+ return out
213
+
214
+
215
+ # --------------------------------------------------------------------------- settings
216
+ def _settings_files(ctx: Context) -> list[Path]:
217
+ """Highest precedence first: managed > project local > project > user."""
218
+ return ([d / "managed-settings.json" for d in MANAGED_DIRS]
219
+ + [ctx.root / ".claude" / "settings.local.json",
220
+ ctx.root / ".claude" / "settings.json",
221
+ ctx.config_dir / "settings.json"])
222
+
223
+
224
+ def setting(ctx: Context, key: str):
225
+ for p in _settings_files(ctx):
226
+ data = read_json(p)
227
+ if data and key in data:
228
+ return data[key], p
229
+ return None, None
230
+
231
+
232
+ # --------------------------------------------------------------------------- auto memory
233
+ def encode_project(path: str) -> str:
234
+ """Observed Claude Code encoding: every non-alphanumeric char becomes '-'."""
235
+ return re.sub(r"[^A-Za-z0-9]", "-", path)
236
+
237
+
238
+ def _norm(s: str) -> str:
239
+ return re.sub(r"[^a-z0-9]", "", s.lower())
240
+
241
+
242
+ def _project_paths(ctx: Context) -> list[str]:
243
+ """Spellings of the project path (resolved root, git top level, $PWD). Memoized on the
244
+ context: each git call costs a subprocess."""
245
+ if ctx._project_paths is None:
246
+ ctx._project_paths = _compute_project_paths(ctx)
247
+ return ctx._project_paths
248
+
249
+
250
+ def _compute_project_paths(ctx: Context) -> list[str]:
251
+ cands = [str(ctx.root)]
252
+ try:
253
+ from ccr.graph import git as ggit
254
+ gi = ggit.info(ctx.root)
255
+ if gi and gi.top:
256
+ cands.append(str(Path(gi.top).resolve()))
257
+ except Exception:
258
+ pass
259
+ raw = ctx.environ.get("PWD")
260
+ if raw and Path(raw).resolve() == ctx.root:
261
+ cands.append(raw) # unresolved spelling, e.g. /tmp vs /private/tmp
262
+ return list(dict.fromkeys(cands))
263
+
264
+
265
+ def auto_memory_dir(ctx: Context) -> Path | None:
266
+ value, _src = setting(ctx, "autoMemoryDirectory")
267
+ if isinstance(value, str) and value.strip():
268
+ base = _expand(value.strip(), ctx, ctx.root)
269
+ for cand in [base] + [base / encode_project(p) / "memory" for p in _project_paths(ctx)] \
270
+ + [base / encode_project(p) for p in _project_paths(ctx)]:
271
+ if cand.is_dir():
272
+ return cand
273
+ projects = ctx.config_dir / "projects"
274
+ if not projects.is_dir():
275
+ return None
276
+ for p in _project_paths(ctx):
277
+ for enc in (encode_project(p), p.replace("/", "-").replace("\\", "-")):
278
+ d = projects / enc / "memory"
279
+ if d.is_dir():
280
+ return d
281
+ # glob fallback: compare names with every separator/punctuation removed
282
+ wanted = {_norm(p) for p in _project_paths(ctx)}
283
+ try:
284
+ for d in sorted(projects.iterdir()):
285
+ if d.is_dir() and _norm(d.name) in wanted and (d / "memory").is_dir():
286
+ return d / "memory"
287
+ except OSError:
288
+ pass
289
+ return None
290
+
291
+
292
+ def _md_dir(d: Path) -> list[Path]:
293
+ try:
294
+ files = sorted(p for p in d.glob("*.md") if p.is_file())
295
+ except OSError:
296
+ return []
297
+ files.sort(key=lambda p: (p.name != "MEMORY.md", p.name))
298
+ return files[:MAX_DIR_FILES]
299
+
300
+
301
+ def auto_memory_docs(ctx: Context) -> list[MemoryDoc]:
302
+ d = auto_memory_dir(ctx)
303
+ if d is None:
304
+ return []
305
+ out = []
306
+ for p in _md_dir(d):
307
+ t = read_text(p)
308
+ if t is not None:
309
+ out.append(MemoryDoc("auto_memory", "user", p, t))
310
+ return out
311
+
312
+
313
+ # --------------------------------------------------------------------------- agent memory
314
+ def agent_memory_docs(ctx: Context) -> list[MemoryDoc]:
315
+ out = []
316
+ for base, scope in ((ctx.root / ".claude" / "agent-memory", "project"),
317
+ (ctx.root / ".claude" / "agent-memory-local", "local"),
318
+ (ctx.config_dir / "agent-memory", "user")):
319
+ if not base.is_dir():
320
+ continue
321
+ try:
322
+ agents = sorted(a for a in base.iterdir() if a.is_dir())
323
+ except OSError:
324
+ continue
325
+ for a in agents:
326
+ for p in _md_dir(a):
327
+ t = read_text(p)
328
+ if t is not None:
329
+ out.append(MemoryDoc("agent_memory", scope, p, t, agent=a.name))
330
+ return out
331
+
332
+
333
+ # --------------------------------------------------------------------------- MCP memory
334
+ def _is_memory_server(name: str, cfg: dict) -> bool:
335
+ env = cfg.get("env") or {}
336
+ if isinstance(env, dict) and "MEMORY_FILE_PATH" in env:
337
+ return True
338
+ blob = " ".join(str(x) for x in [cfg.get("command", "")] + list(cfg.get("args") or []))
339
+ return bool(re.search(r"server-memory|mcp-memory|memory-server|knowledge-graph", blob)) or \
340
+ name.lower() in ("memory", "knowledge-graph", "kg-memory")
341
+
342
+
343
+ def mcp_memory_servers(ctx: Context) -> list[tuple[str, dict, Path]]:
344
+ """(server name, config, config file) for MCP servers that look like server-memory."""
345
+ found: list[tuple[str, dict, Path]] = []
346
+ proj = read_json(ctx.root / ".mcp.json")
347
+ if proj and isinstance(proj.get("mcpServers"), dict):
348
+ found += [(n, c, ctx.root / ".mcp.json") for n, c in proj["mcpServers"].items()
349
+ if isinstance(c, dict)]
350
+ for uj in ctx.user_json_candidates():
351
+ data = read_json(uj)
352
+ if not data:
353
+ continue
354
+ servers = dict(data.get("mcpServers") or {})
355
+ projects = data.get("projects") or {}
356
+ for key in _project_paths(ctx):
357
+ pj = projects.get(key) if isinstance(projects, dict) else None
358
+ if isinstance(pj, dict) and isinstance(pj.get("mcpServers"), dict):
359
+ servers.update(pj["mcpServers"])
360
+ found += [(n, c, uj) for n, c in servers.items() if isinstance(c, dict)]
361
+ break # first existing user config wins
362
+ return [(n, c, p) for n, c, p in found if _is_memory_server(n, c)]
363
+
364
+
365
+ def parse_kg(text: str) -> tuple[list[dict], list[dict]]:
366
+ entities, relations = [], []
367
+
368
+ def add(obj):
369
+ if not isinstance(obj, dict):
370
+ return
371
+ t = obj.get("type")
372
+ if t == "entity" or (t is None and "name" in obj and "observations" in obj):
373
+ entities.append(obj)
374
+ elif t == "relation" or (t is None and "from" in obj and "to" in obj):
375
+ relations.append(obj)
376
+
377
+ stripped = text.lstrip()
378
+ if stripped.startswith("{") and '"entities"' in stripped[:2000]:
379
+ try:
380
+ whole = json.loads(text)
381
+ for e in whole.get("entities") or []:
382
+ add({**e, "type": "entity"} if isinstance(e, dict) else e)
383
+ for r in whole.get("relations") or []:
384
+ add({**r, "type": "relation"} if isinstance(r, dict) else r)
385
+ return entities, relations
386
+ except ValueError:
387
+ pass
388
+ for line in text.splitlines():
389
+ line = line.strip()
390
+ if not line:
391
+ continue
392
+ try:
393
+ add(json.loads(line))
394
+ except ValueError:
395
+ continue
396
+ return entities, relations
397
+
398
+
399
+ def mcp_memory(ctx: Context) -> tuple[list[KGMemory], list[str]]:
400
+ """Returns (knowledge graphs read, notes about servers whose file could not be found)."""
401
+ out, notes, seen = [], [], set()
402
+ for name, cfg, cfg_path in mcp_memory_servers(ctx):
403
+ env = cfg.get("env") if isinstance(cfg.get("env"), dict) else {}
404
+ raw = env.get("MEMORY_FILE_PATH")
405
+ if not raw:
406
+ notes.append(f"MCP memory server '{name}' ({cfg_path.name}) has no MEMORY_FILE_PATH; "
407
+ "its default file location is not discoverable")
408
+ continue
409
+ p = _expand(str(raw), ctx, ctx.root)
410
+ try:
411
+ key = p.resolve()
412
+ except OSError:
413
+ continue
414
+ if key in seen:
415
+ continue
416
+ seen.add(key)
417
+ text = read_text(p, max_bytes=20_000_000)
418
+ if text is None:
419
+ continue
420
+ ents, rels = parse_kg(text)
421
+ out.append(KGMemory(path=p, server=name, entities=ents, relations=rels))
422
+ return out, notes
ccr/report.py ADDED
@@ -0,0 +1,40 @@
1
+ """Plain-text rendering of a routing Decision (`ccr explain`)."""
2
+ from __future__ import annotations
3
+
4
+
5
+ def format_decision(task: str, d) -> list[str]:
6
+ from ccr.evaluate.risk import COMPONENTS, LABELS
7
+ tc, loc, r, b = d.task_class, d.location, d.risk, d.budget
8
+ short = " ".join(task.split())
9
+ out = [f"Task: {short if len(short) <= 100 else short[:97] + '...'}",
10
+ f"Tier: {d.tier.name} {d.tier.model} / {d.tier.effort} (agent {d.tier.agent})"
11
+ + (" [T4 rule]" if d.t4_rules else ""),
12
+ f"Class: {tc.kind} ({tc.source}, class confidence {tc.confidence:.2f}"
13
+ + (f", runner-up {tc.secondary}" if tc.secondary else "") + f") scope {tc.scope}"
14
+ + f", vagueness {tc.vagueness:.2f}"
15
+ + (f", destructive: {', '.join(tc.destructive[:3])}" if tc.destructive else ""),
16
+ f"Confidence: {d.confidence:.2f} overall"]
17
+ named = len(loc.explicit)
18
+ out.append(f"Files: {len(loc.candidates)} candidate(s), location confidence "
19
+ f"{loc.confidence:.2f}; {named} named/@-mentioned, {len(loc.symbols)} symbol(s)"
20
+ + ("" if loc.graph else " [no code graph]"))
21
+ for c in loc.candidates[:6]:
22
+ out.append(f" {c.confidence:.2f} {c.path} ({'; '.join(c.reasons[:3])})")
23
+ if len(loc.candidates) > 6:
24
+ out.append(f" ... {len(loc.candidates) - 6} more")
25
+ if r.score is None:
26
+ out.append("Risk: unknown (nothing located)")
27
+ else:
28
+ out.append(f"Risk: {r.score:.2f} {r.level} (code-only {r.code_risk:.2f})")
29
+ for n in COMPONENTS:
30
+ c = r.components[n]
31
+ out.append(f" {LABELS[n]:<15} {c.value:.2f} {c.detail}")
32
+ out.append(f"Budget: {b.detail}" + (" -> pressure" if b.pressure else ""))
33
+ out.append(f"Learning: {d.history}")
34
+ out.append(f"LLM: {d.llm}")
35
+ out.append("Reasoning:")
36
+ out += [f" - {x}" for x in d.reasons]
37
+ for n in d.notes:
38
+ out.append(f"Note: {n}")
39
+ out.append(f"(evaluated in {d.elapsed_ms:.0f} ms; explain runs nothing)")
40
+ return out