claude-code-router 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. ccr/__init__.py +0 -0
  2. ccr/__main__.py +4 -0
  3. ccr/cli.py +595 -0
  4. ccr/config.py +518 -0
  5. ccr/detect/__init__.py +123 -0
  6. ccr/doctor.py +208 -0
  7. ccr/entry.py +23 -0
  8. ccr/evaluate/__init__.py +13 -0
  9. ccr/evaluate/classify.py +335 -0
  10. ccr/evaluate/llm.py +182 -0
  11. ccr/evaluate/locate.py +359 -0
  12. ccr/evaluate/risk.py +285 -0
  13. ccr/evaluate/text.py +190 -0
  14. ccr/graph/__init__.py +15 -0
  15. ccr/graph/build.py +475 -0
  16. ccr/graph/db.py +88 -0
  17. ccr/graph/files.py +169 -0
  18. ccr/graph/git.py +90 -0
  19. ccr/graph/parse.py +510 -0
  20. ccr/graph/query.py +359 -0
  21. ccr/graph/resolve.py +256 -0
  22. ccr/headless.py +363 -0
  23. ccr/history/__init__.py +172 -0
  24. ccr/history/calibrate.py +161 -0
  25. ccr/history/dashboard.py +374 -0
  26. ccr/history/feedback.py +91 -0
  27. ccr/history/learn.py +184 -0
  28. ccr/history/prompts.py +120 -0
  29. ccr/history/redact.py +45 -0
  30. ccr/history/savings.py +187 -0
  31. ccr/history/shadow.py +114 -0
  32. ccr/history/stats.py +172 -0
  33. ccr/history/tune.py +80 -0
  34. ccr/history/why.py +186 -0
  35. ccr/hooks/__init__.py +134 -0
  36. ccr/hooks/bg.py +68 -0
  37. ccr/hooks/common.py +159 -0
  38. ccr/hooks/prompt.py +322 -0
  39. ccr/hooks/session_start.py +91 -0
  40. ccr/hooks/stop.py +52 -0
  41. ccr/hooks/tasks.py +170 -0
  42. ccr/install/__init__.py +388 -0
  43. ccr/install/agents.py +200 -0
  44. ccr/install/command.py +159 -0
  45. ccr/install/settings.py +175 -0
  46. ccr/memory/__init__.py +87 -0
  47. ccr/memory/signals.py +210 -0
  48. ccr/memory/sources.py +422 -0
  49. ccr/report.py +40 -0
  50. ccr/route/__init__.py +527 -0
  51. ccr/route/budget.py +166 -0
  52. ccr/statusline.py +143 -0
  53. ccr/transcript.py +98 -0
  54. claude_code_router-0.1.1.dist-info/METADATA +291 -0
  55. claude_code_router-0.1.1.dist-info/RECORD +58 -0
  56. claude_code_router-0.1.1.dist-info/WHEEL +4 -0
  57. claude_code_router-0.1.1.dist-info/entry_points.txt +2 -0
  58. claude_code_router-0.1.1.dist-info/licenses/LICENSE +21 -0
ccr/graph/files.py ADDED
@@ -0,0 +1,169 @@
1
+ """File discovery for the code graph: .gitignore aware, skips vendored/build/lock files."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import re
6
+ from pathlib import Path
7
+
8
+ from ccr.detect import SKIP_DIRS, SKIP_FILES
9
+
10
+ # Extension -> import "family" (drives regex import extraction and resolution).
11
+ EXT_FAMILY = {
12
+ ".py": "python", ".pyi": "python",
13
+ ".js": "js", ".jsx": "js", ".mjs": "js", ".cjs": "js", ".ts": "js", ".tsx": "js",
14
+ ".mts": "js", ".cts": "js", ".vue": "js", ".svelte": "js",
15
+ ".go": "go",
16
+ ".java": "jvm", ".kt": "jvm", ".kts": "jvm", ".scala": "jvm", ".groovy": "jvm",
17
+ ".rs": "rust",
18
+ ".c": "c", ".h": "c", ".cc": "c", ".cpp": "c", ".cxx": "c", ".hpp": "c", ".hh": "c",
19
+ ".hxx": "c", ".m": "c", ".mm": "c",
20
+ ".rb": "ruby", ".php": "php", ".cs": "csharp", ".zig": "zig", ".lua": "lua",
21
+ ".ex": "elixir", ".exs": "elixir", ".dart": "dart", ".swift": "swift",
22
+ ".sh": "shell", ".bash": "shell",
23
+ }
24
+ CODE_EXTS = frozenset(EXT_FAMILY)
25
+ # Non-code files the resolver needs (module roots).
26
+ AUX_NAMES = frozenset({"go.mod", "Cargo.toml"})
27
+ EXTRA_SKIP_DIRS = frozenset({"bower_components", "Pods", "third_party", "coverage", "out",
28
+ ".svn", ".hg", ".cache", ".parcel-cache", ".turbo", "elm-stuff"})
29
+ ALL_SKIP_DIRS = frozenset(SKIP_DIRS) | EXTRA_SKIP_DIRS
30
+ MAX_PARSE_BYTES = 1_000_000
31
+
32
+ _TEST_DIR = {"test", "tests", "__tests__", "spec", "specs", "testing", "e2e"}
33
+ _TEST_NAME = re.compile(
34
+ r"(^test_.+|.+_test|.+[._-](test|spec)|.+Tests?|.+Spec|^Test[A-Z_].*|.+_spec)$")
35
+
36
+
37
+ def is_skipped_name(name: str) -> bool:
38
+ return name in SKIP_FILES or ".min." in name or name.endswith((".map", ".lock"))
39
+
40
+
41
+ def is_code(rel: str) -> bool:
42
+ name = rel.rsplit("/", 1)[-1]
43
+ return os.path.splitext(name)[1].lower() in CODE_EXTS and not is_skipped_name(name)
44
+
45
+
46
+ def family_of(rel: str) -> str:
47
+ return EXT_FAMILY.get(os.path.splitext(rel)[1].lower(), "")
48
+
49
+
50
+ def is_test_path(rel: str) -> bool:
51
+ parts = rel.split("/")
52
+ if any(p.lower() in _TEST_DIR for p in parts[:-1]):
53
+ return True
54
+ stem = parts[-1]
55
+ while "." in stem:
56
+ stem, ext = stem.rsplit(".", 1)
57
+ if ext.lower() in ("test", "spec"):
58
+ return True
59
+ return bool(_TEST_NAME.match(stem))
60
+
61
+
62
+ def in_skipped_dir(rel: str) -> bool:
63
+ return any(p in ALL_SKIP_DIRS for p in rel.split("/")[:-1])
64
+
65
+
66
+ # --------------------------------------------------------------------------- gitignore
67
+ class GitIgnore:
68
+ """Minimal .gitignore matcher (used only outside git repos; git does it natively)."""
69
+
70
+ def __init__(self) -> None:
71
+ self.rules: list[tuple[str, re.Pattern, bool, bool]] = [] # (base, rx, negate, dir_only)
72
+
73
+ @staticmethod
74
+ def _compile(pat: str) -> re.Pattern:
75
+ anchored = "/" in pat.rstrip("/")
76
+ pat = pat.lstrip("/")
77
+ out, i = [], 0
78
+ while i < len(pat):
79
+ c = pat[i]
80
+ if pat.startswith("**/", i):
81
+ out.append("(?:.*/)?")
82
+ i += 3
83
+ continue
84
+ if pat.startswith("**", i):
85
+ out.append(".*")
86
+ i += 2
87
+ continue
88
+ if c == "*":
89
+ out.append("[^/]*")
90
+ elif c == "?":
91
+ out.append("[^/]")
92
+ elif c == "[":
93
+ j = pat.find("]", i)
94
+ if j == -1:
95
+ out.append(re.escape(c))
96
+ else:
97
+ out.append(pat[i:j + 1].replace("[!", "[^"))
98
+ i = j
99
+ else:
100
+ out.append(re.escape(c))
101
+ i += 1
102
+ body = "".join(out)
103
+ prefix = "" if anchored else "(?:.*/)?"
104
+ return re.compile(f"^{prefix}{body}(?:/.*)?$")
105
+
106
+ def add_file(self, path: Path, base: str) -> None:
107
+ try:
108
+ lines = path.read_text(encoding="utf-8", errors="ignore").splitlines()
109
+ except OSError:
110
+ return
111
+ for raw in lines:
112
+ line = raw.rstrip()
113
+ if not line or line.startswith("#"):
114
+ continue
115
+ neg = line.startswith("!")
116
+ if neg:
117
+ line = line[1:]
118
+ dir_only = line.endswith("/")
119
+ try:
120
+ self.rules.append((base, self._compile(line.rstrip("/")), neg, dir_only))
121
+ except re.error:
122
+ continue
123
+
124
+ def ignored(self, rel: str, is_dir: bool) -> bool:
125
+ result = False
126
+ for base, rx, neg, dir_only in self.rules:
127
+ if base:
128
+ if not rel.startswith(base + "/"):
129
+ continue
130
+ sub = rel[len(base) + 1:]
131
+ else:
132
+ sub = rel
133
+ if dir_only and not is_dir:
134
+ # "build/" must still match files below build/
135
+ if "/" not in sub:
136
+ continue
137
+ if not rx.match(sub.rsplit("/", 1)[0]):
138
+ continue
139
+ result = not neg
140
+ continue
141
+ if rx.match(sub):
142
+ result = not neg
143
+ return result
144
+
145
+
146
+ def walk_files(root: Path) -> list[str]:
147
+ """All non-ignored files under root (relative posix paths), without git."""
148
+ gi = GitIgnore()
149
+ out: list[str] = []
150
+ root_s = str(root)
151
+ for dirpath, dirnames, filenames in os.walk(root_s):
152
+ rel_dir = os.path.relpath(dirpath, root_s).replace(os.sep, "/")
153
+ rel_dir = "" if rel_dir == "." else rel_dir
154
+ if ".gitignore" in filenames:
155
+ gi.add_file(Path(dirpath) / ".gitignore", rel_dir)
156
+ keep = []
157
+ for d in dirnames:
158
+ if d in ALL_SKIP_DIRS or d.startswith(".") and d not in (".github",):
159
+ continue
160
+ rel = f"{rel_dir}/{d}" if rel_dir else d
161
+ if os.path.islink(os.path.join(dirpath, d)) or gi.ignored(rel, True):
162
+ continue
163
+ keep.append(d)
164
+ dirnames[:] = sorted(keep)
165
+ for name in filenames:
166
+ rel = f"{rel_dir}/{name}" if rel_dir else name
167
+ if not gi.ignored(rel, False):
168
+ out.append(rel)
169
+ return out
ccr/graph/git.py ADDED
@@ -0,0 +1,90 @@
1
+ """Thin git helpers. Every function degrades to None/empty when git is unavailable."""
2
+ from __future__ import annotations
3
+
4
+ import shutil
5
+ import subprocess
6
+ import time
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+
11
+ @dataclass
12
+ class GitInfo:
13
+ top: str
14
+ prefix: str # root relative to the repo top level, "" or "sub/dir/"
15
+ head: str | None
16
+
17
+
18
+ def _git(root: Path, *args: str, timeout: float = 30) -> str | None:
19
+ exe = shutil.which("git")
20
+ if not exe:
21
+ return None
22
+ try:
23
+ r = subprocess.run([exe, "-C", str(root), "-c", "core.quotepath=off", *args],
24
+ capture_output=True, timeout=timeout)
25
+ except (OSError, subprocess.SubprocessError):
26
+ return None
27
+ if r.returncode != 0:
28
+ return None
29
+ return r.stdout.decode("utf-8", errors="surrogateescape")
30
+
31
+
32
+ def info(root: Path) -> GitInfo | None:
33
+ out = _git(root, "rev-parse", "--show-toplevel", "--show-prefix")
34
+ if out is None:
35
+ return None
36
+ lines = out.split("\n")
37
+ top = lines[0].strip()
38
+ prefix = lines[1].strip() if len(lines) > 1 else ""
39
+ head = _git(root, "rev-parse", "--verify", "-q", "HEAD")
40
+ return GitInfo(top=top, prefix=prefix, head=head.strip() if head else None)
41
+
42
+
43
+ def ls_files(root: Path) -> list[str] | None:
44
+ """Tracked + untracked-not-ignored files, relative to root."""
45
+ out = _git(root, "ls-files", "-z", "-c", "-o", "--exclude-standard")
46
+ if out is None:
47
+ return None
48
+ return sorted({p for p in out.split("\0") if p})
49
+
50
+
51
+ def changed_since(root: Path, commit: str) -> set[str] | None:
52
+ """Files differing between `commit` and the working tree (committed + staged + unstaged)."""
53
+ out = _git(root, "diff", "--name-only", "-z", "--relative", "--no-renames", commit, "--")
54
+ if out is None:
55
+ return None
56
+ return {p for p in out.split("\0") if p}
57
+
58
+
59
+ def churn(root: Path, gi: GitInfo, days: int = 180,
60
+ max_commits: int = 20000) -> dict[str, tuple[int, int, int]]:
61
+ """path -> (commit count, distinct authors, last commit unix ts) within the window."""
62
+ since = f"{int(time.time()) - days * 86400}"
63
+ out = _git(root, "log", f"--since={since}", f"--max-count={max_commits}", "--no-merges",
64
+ "--no-renames", "--name-only", "--format=%x1e%ae%x1f%ct", "--relative", "--",
65
+ ".", timeout=120)
66
+ if not out:
67
+ return {}
68
+ stats: dict[str, list] = {}
69
+ for block in out.split("\x1e"):
70
+ if not block.strip():
71
+ continue
72
+ head, _, rest = block.partition("\n")
73
+ author, _, ts = head.partition("\x1f")
74
+ try:
75
+ ts_i = int(ts.strip())
76
+ except ValueError:
77
+ ts_i = 0
78
+ for line in rest.split("\n"):
79
+ p = line.strip()
80
+ if not p:
81
+ continue
82
+ s = stats.get(p)
83
+ if s is None:
84
+ stats[p] = [1, {author}, ts_i]
85
+ else:
86
+ s[0] += 1
87
+ s[1].add(author)
88
+ if ts_i > s[2]:
89
+ s[2] = ts_i
90
+ return {p: (c, len(a), t) for p, (c, a, t) in stats.items()}