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/config.py ADDED
@@ -0,0 +1,518 @@
1
+ """`.ccr/config.yaml` loader: built-in defaults, deep merge, validation.
2
+
3
+ Invalid values never crash a hook: each bad field keeps its default and an error message is
4
+ recorded on `Config.errors` (or `ConfigError` is raised with `strict=True`). PyYAML is only
5
+ imported when a config file exists.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import copy
10
+ import re
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ # Ordered cheapest -> strongest. T2H sits between T2 and T3 (sonnet/high) so it keeps every
15
+ # existing tier name (history records, class_base, user configs) valid.
16
+ TIERS = ("T0", "T1", "T2", "T2H", "T3", "T4")
17
+ TOP = len(TIERS) - 1
18
+ # The `effortLevel` setting accepts only these (subagent frontmatter also allows `max`).
19
+ EFFORTS = ("low", "medium", "high", "xhigh")
20
+ MODEL_ALIASES = ("haiku", "sonnet", "opus", "fable")
21
+ CLASSES = ("question", "trivial", "tests", "bugfix", "feature", "refactor", "perf", "migration",
22
+ "security", "debugging", "design")
23
+ _MODEL_ID = re.compile(r"^claude-[a-z0-9][a-z0-9.\-]*(\[1m\])?$")
24
+ _AGENT = re.compile(r"^[a-z0-9][a-z0-9-]{0,63}$")
25
+
26
+ DEFAULTS: dict = {
27
+ "tiers": {
28
+ "T0": {"model": "haiku", "effort": "low", "agent": "ccr-quick"},
29
+ "T1": {"model": "sonnet", "effort": "low", "agent": "ccr-small"},
30
+ "T2": {"model": "sonnet", "effort": "medium", "agent": "ccr-implement"},
31
+ "T2H": {"model": "sonnet", "effort": "high", "agent": "ccr-senior"},
32
+ "T3": {"model": "opus", "effort": "high", "agent": "ccr-architect"},
33
+ "T4": {"model": "opus", "effort": "xhigh", "agent": "ccr-critical"},
34
+ },
35
+ # Starting tier per task class (before scope / risk / history / budget adjustments).
36
+ "class_base": {
37
+ "question": "T0", "trivial": "T0", "tests": "T1", "bugfix": "T1", "feature": "T2",
38
+ "refactor": "T2", "perf": "T2", "migration": "T3", "security": "T3", "debugging": "T3",
39
+ "design": "T3",
40
+ },
41
+ # Critical-path globs per group. `**` spans directories, `*` does not; a pattern without
42
+ # `/` matches the basename. Matching is case-insensitive. Set a group to [] to disable it.
43
+ "critical_paths": {
44
+ "auth": ["**/auth/**", "**/auth.*", "**/auth_*", "**/*_auth.*", "**/*auth.*",
45
+ "**/authn*", "**/authz*", "**/authenticat*", "**/authoriz*", "**/login*",
46
+ "**/session*", "**/oauth*", "**/jwt*", "**/permission*", "**/rbac*",
47
+ "**/acl.*", "**/password*", "**/credential*"],
48
+ "payments": ["**/payment*/**", "**/payment*", "**/billing/**", "**/billing*",
49
+ "**/checkout*", "**/invoice*", "**/stripe*", "**/ledger*", "**/refund*",
50
+ "**/subscription*"],
51
+ "migrations": ["**/migrations/**", "**/migrate/**", "**/alembic/**", "**/*.sql",
52
+ "**/schema.prisma", "**/db/schema*"],
53
+ "infra": ["**/terraform/**", "**/*.tf", "**/*.tfvars", "**/k8s/**", "**/kubernetes/**",
54
+ "**/helm/**", "**/Dockerfile*", "**/docker-compose*", "**/.github/workflows/**",
55
+ "**/deploy/**", "**/infra/**", "**/ansible/**", "**/.gitlab-ci*"],
56
+ "secrets": ["**/secret*", "**/crypto*", "**/*.pem", "**/*.key", "**/.env*"],
57
+ },
58
+ # Prompt words/phrases that put a task on a critical path even before files are located.
59
+ # Matched as whole words (simple plurals included), case-insensitive.
60
+ "critical_terms": {
61
+ # bare "session" is ordinary wording ("in this session"); only security senses count
62
+ "auth": ["auth", "authentication", "authorization", "login", "logout",
63
+ "session token", "session cookie", "session cookies", "session id", "session key",
64
+ "session secret", "session fixation", "session hijack",
65
+ "session management", "session expiry", "session expiration",
66
+ "session invalidation", "oauth", "jwt", "sso", "saml", "permission", "rbac",
67
+ "password", "credential"],
68
+ "payments": ["payment", "billing", "invoice", "checkout", "refund", "stripe", "ledger",
69
+ "charge", "subscription", "payout"],
70
+ "migrations": ["migration", "alembic", "schema change", "schema migration",
71
+ "database schema", "db schema", "alter table", "drop column",
72
+ "drop table", "backfill"],
73
+ "infra": ["terraform", "kubernetes", "k8s", "helm", "dockerfile", "deployment",
74
+ "infrastructure", "infra", "ci pipeline", "github actions", "s3 bucket",
75
+ "iam", "vpc"],
76
+ "secrets": ["secret", "encryption", "crypto", "certificate", "tls", "api key",
77
+ "private key", "signing key"],
78
+ },
79
+ # Project words that make a bug/perf task a hard problem (like "intermittent"): added to
80
+ # the built-in list in ccr/evaluate/classify.py. Matched as whole words, case-insensitive.
81
+ "hard_terms": [],
82
+ # Blended USD per million tokens by model family, only used for the savings estimate in
83
+ # `ccr stats` (interactive sessions report tokens, not dollars). Set your own rates.
84
+ "pricing": {"haiku": 2.0, "sonnet": 6.0, "opus": 30.0},
85
+ "risk": {
86
+ # Max contribution of each component to the (noisy-or) risk score.
87
+ "weights": {"blast_radius": 0.6, "complexity": 0.5, "test_proximity": 0.3,
88
+ "churn": 0.3, "critical_path": 0.7, "memory": 0.7},
89
+ "medium": 0.3, # score >= medium -> "medium"
90
+ "high": 0.55, # score >= high -> "high" (+1 tier for change tasks)
91
+ "t4_code_risk": 0.65, # code-only risk (no critical/memory) for the T4 rule
92
+ "blast_full": 32, # dependents count that saturates blast radius
93
+ "churn_full_commits": 20,
94
+ "complexity_full_branches": 15,
95
+ },
96
+ "budget": {
97
+ "soft_limit_pct": 80, # weekly usage % at which pressure starts
98
+ "state_max_age_hours": 24, # ignore an older .ccr/local/state.json
99
+ "weekly_token_limit": None, # enables the token fallback when no statusline data
100
+ },
101
+ "history": {
102
+ "min_samples": 3,
103
+ "fail_rate_up": 0.5, # >= this failure rate at the chosen tier -> +1
104
+ "success_rate_down": 0.8, # >= this success rate one tier lower -> -1
105
+ "window_days": 90,
106
+ "struggle_tool_errors": 5, # a success with >= this many tool errors counts as a
107
+ # failure for learning only (0 disables)
108
+ "struggle_turns": 30, # same for >= this many turns (0 disables)
109
+ "explore_down": True, # chosen tier keeps succeeding on low-risk simple
110
+ # tasks -> try one tier lower (ccr/history/learn.py)
111
+ },
112
+ "llm": {
113
+ "threshold": 0.5, # rule confidence below this may ask the LLM (if allowed)
114
+ "model": "haiku",
115
+ "effort": "low",
116
+ "timeout_s": 45,
117
+ },
118
+ "routing": {
119
+ "max_escalation": 2, # tiers above the class base without a T4 rule (2nd tier
120
+ # only when 3+ independent signals agree)
121
+ "ceiling_without_critical": "T3",
122
+ },
123
+ # `ccr run` (headless `claude -p`).
124
+ "run": {
125
+ "test_command": None, # shell command that must pass for success, e.g. "pytest -q"
126
+ "test_timeout_s": 900,
127
+ "max_escalations": 1, # tiers to climb after a failed attempt (0 = never retry)
128
+ "max_turns": 40, # per attempt (--max-turns)
129
+ "max_budget_usd": None, # total for the run across attempts (--max-budget-usd)
130
+ "timeout_s": 3600, # wall clock per attempt
131
+ "permission_mode": None, # passed as --permission-mode (e.g. acceptEdits)
132
+ },
133
+ # Claude Code hooks installed by `ccr init`. All hooks fail open (silent, exit 0).
134
+ "hooks": {
135
+ "enabled": True, # master switch for every ccr hook
136
+ "route_prompts": True, # UserPromptSubmit: inject the routing line
137
+ "store_prompts": False, # opt in: keep prompt text + decision process in
138
+ # .ccr/local/prompts.jsonl (local only) for the dashboard
139
+ "show_in_ui": True, # also show a short routing line to the USER (systemMessage)
140
+ "model_advice": True, # suggest `/model <x>` for iterative work above the main model
141
+ "background_graph": True, # SessionStart: refresh a stale graph in the background
142
+ "watchdog_ms": 1500, # hard internal deadline per hook run
143
+ "redact_prompts": True, # strip keys, tokens, emails and credentials from stored prompts
144
+ "prompt_retention_days": 30, # drop stored prompts older than this (0 = keep forever)
145
+ "rework_minutes": 15, # a dissatisfied reply about the same code within this long
146
+ # flags the previous task as possible rework
147
+ "success_gap_minutes": 120, # idle longer than this before the next prompt: outcome
148
+ # unknown instead of success
149
+ },
150
+ }
151
+
152
+
153
+ class ConfigError(ValueError):
154
+ pass
155
+
156
+
157
+ @dataclass
158
+ class Tier:
159
+ name: str
160
+ model: str
161
+ effort: str
162
+ agent: str
163
+
164
+ @property
165
+ def index(self) -> int:
166
+ return TIERS.index(self.name)
167
+
168
+
169
+ @dataclass
170
+ class Config:
171
+ data: dict
172
+ path: Path | None = None
173
+ errors: list[str] = field(default_factory=list)
174
+ warnings: list[str] = field(default_factory=list)
175
+
176
+ @property
177
+ def tiers(self) -> dict[str, Tier]:
178
+ return {k: Tier(k, v["model"], v["effort"], v["agent"])
179
+ for k, v in self.data["tiers"].items()}
180
+
181
+ def tier(self, name_or_index: str | int) -> Tier:
182
+ name = TIERS[name_or_index] if isinstance(name_or_index, int) else name_or_index
183
+ v = self.data["tiers"][name]
184
+ return Tier(name, v["model"], v["effort"], v["agent"])
185
+
186
+ def __getitem__(self, key: str):
187
+ return self.data[key]
188
+
189
+
190
+ def config_path(root: str | Path) -> Path:
191
+ return Path(root) / ".ccr" / "config.yaml"
192
+
193
+
194
+ def default_config() -> Config:
195
+ return Config(copy.deepcopy(DEFAULTS))
196
+
197
+
198
+ def load_config(root: str | Path | None = None, *, path: str | Path | None = None,
199
+ strict: bool = False) -> Config:
200
+ """Defaults merged with `<root>/.ccr/config.yaml` (or `path`), validated."""
201
+ p = Path(path) if path is not None else (config_path(root) if root is not None else None)
202
+ cfg = default_config()
203
+ if p is None or not p.exists():
204
+ return cfg
205
+ cfg.path = p
206
+ try:
207
+ import yaml
208
+ raw = yaml.safe_load(p.read_text(encoding="utf-8"))
209
+ except Exception as e: # yaml.YAMLError, OSError, UnicodeDecodeError
210
+ cfg.errors.append(f"{p}: cannot parse: {e}".replace("\n", " "))
211
+ raw = None
212
+ if raw is None:
213
+ raw = {}
214
+ if not isinstance(raw, dict):
215
+ cfg.errors.append(f"{p}: top level must be a mapping")
216
+ raw = {}
217
+ _merge_validated(cfg, raw)
218
+ if strict and cfg.errors:
219
+ raise ConfigError("; ".join(cfg.errors))
220
+ return cfg
221
+
222
+
223
+ # --------------------------------------------------------------------------- validation
224
+ def _valid_model(m: object) -> bool:
225
+ return isinstance(m, str) and (m in MODEL_ALIASES or bool(_MODEL_ID.match(m)))
226
+
227
+
228
+ def _num(cfg: Config, where: str, v: object, lo: float, hi: float) -> bool:
229
+ if isinstance(v, bool) or not isinstance(v, (int, float)) or not lo <= v <= hi:
230
+ cfg.errors.append(f"{where}: expected a number in [{lo}, {hi}], got {v!r}")
231
+ return False
232
+ return True
233
+
234
+
235
+ def _str_list(cfg: Config, where: str, v: object) -> bool:
236
+ if not isinstance(v, list) or not all(isinstance(x, str) and x.strip() for x in v):
237
+ cfg.errors.append(f"{where}: expected a list of non-empty strings")
238
+ return False
239
+ return True
240
+
241
+
242
+ def _merge_validated(cfg: Config, raw: dict) -> None:
243
+ for key in raw:
244
+ if key not in DEFAULTS and key != "version":
245
+ cfg.warnings.append(f"unknown config key {key!r} ignored")
246
+ for merge in _MERGERS:
247
+ merge(cfg, raw)
248
+
249
+ def _merge_tiers(cfg: Config, raw: dict) -> None:
250
+ d = cfg.data
251
+ tiers = raw.get("tiers")
252
+ if tiers is not None:
253
+ if not isinstance(tiers, dict):
254
+ cfg.errors.append("tiers: expected a mapping of T0..T4 and T2H")
255
+ else:
256
+ for name, spec in tiers.items():
257
+ if name not in TIERS:
258
+ cfg.errors.append(f"tiers.{name}: unknown tier (expected one of {', '.join(TIERS)})")
259
+ continue
260
+ if not isinstance(spec, dict):
261
+ cfg.errors.append(f"tiers.{name}: expected a mapping")
262
+ continue
263
+ for k, v in spec.items():
264
+ where = f"tiers.{name}.{k}"
265
+ if k == "model":
266
+ if not _valid_model(v):
267
+ cfg.errors.append(f"{where}: unknown model {v!r} (use "
268
+ f"{'/'.join(MODEL_ALIASES)} or a claude-* id)")
269
+ elif "fable" in str(v) and name != "T4":
270
+ cfg.errors.append(f"{where}: fable is only allowed for T4")
271
+ else:
272
+ d["tiers"][name]["model"] = v
273
+ elif k == "effort":
274
+ if v not in EFFORTS:
275
+ cfg.errors.append(f"{where}: effort must be one of "
276
+ f"{'|'.join(EFFORTS)} (effortLevel), got {v!r}")
277
+ else:
278
+ d["tiers"][name]["effort"] = v
279
+ elif k == "agent":
280
+ if not isinstance(v, str) or not _AGENT.match(v):
281
+ cfg.errors.append(f"{where}: agent must be lowercase letters, "
282
+ f"digits and dashes, got {v!r}")
283
+ else:
284
+ d["tiers"][name]["agent"] = v
285
+ else:
286
+ cfg.warnings.append(f"{where}: unknown field ignored")
287
+ _check_monotonic(cfg)
288
+
289
+
290
+ def _merge_class_base(cfg: Config, raw: dict) -> None:
291
+ d = cfg.data
292
+ cb = raw.get("class_base")
293
+ if cb is not None:
294
+ if not isinstance(cb, dict):
295
+ cfg.errors.append("class_base: expected a mapping")
296
+ else:
297
+ for k, v in cb.items():
298
+ if k not in CLASSES:
299
+ cfg.errors.append(f"class_base.{k}: unknown class "
300
+ f"(expected one of {', '.join(CLASSES)})")
301
+ elif v not in TIERS:
302
+ cfg.errors.append(f"class_base.{k}: expected T0..T4, got {v!r}")
303
+ else:
304
+ d["class_base"][k] = v
305
+
306
+
307
+ def _merge_critical(cfg: Config, raw: dict) -> None:
308
+ d = cfg.data
309
+ for key in ("critical_paths", "critical_terms"):
310
+ groups = raw.get(key)
311
+ if groups is None:
312
+ continue
313
+ if not isinstance(groups, dict):
314
+ cfg.errors.append(f"{key}: expected a mapping of group -> list")
315
+ continue
316
+ for g, items in groups.items():
317
+ if items is None:
318
+ items = []
319
+ if _str_list(cfg, f"{key}.{g}", items):
320
+ d[key][str(g)] = [x.strip() if key == "critical_paths" else x.strip().lower()
321
+ for x in items]
322
+
323
+
324
+ def _merge_hard_terms(cfg: Config, raw: dict) -> None:
325
+ d = cfg.data
326
+ ht = raw.get("hard_terms")
327
+ if ht is not None and (ht is None or _str_list(cfg, "hard_terms", ht)):
328
+ d["hard_terms"] = [x.strip().lower() for x in ht if x.strip()]
329
+
330
+
331
+ def _merge_pricing(cfg: Config, raw: dict) -> None:
332
+ d = cfg.data
333
+ pricing = raw.get("pricing")
334
+ if pricing is not None:
335
+ if not isinstance(pricing, dict):
336
+ cfg.errors.append("pricing: expected a mapping of model -> USD per Mtok")
337
+ else:
338
+ for k, v in pricing.items():
339
+ if k not in DEFAULTS["pricing"]:
340
+ cfg.warnings.append(f"pricing.{k}: unknown model ignored")
341
+ elif _num(cfg, f"pricing.{k}", v, 0, 100_000):
342
+ d["pricing"][k] = float(v)
343
+
344
+
345
+ def _merge_risk(cfg: Config, raw: dict) -> None:
346
+ d = cfg.data
347
+ risk = raw.get("risk")
348
+ if risk is not None:
349
+ if not isinstance(risk, dict):
350
+ cfg.errors.append("risk: expected a mapping")
351
+ else:
352
+ for k, v in risk.items():
353
+ if k == "weights":
354
+ if not isinstance(v, dict):
355
+ cfg.errors.append("risk.weights: expected a mapping")
356
+ continue
357
+ for wk, wv in v.items():
358
+ if wk not in DEFAULTS["risk"]["weights"]:
359
+ cfg.errors.append(f"risk.weights.{wk}: unknown component")
360
+ elif _num(cfg, f"risk.weights.{wk}", wv, 0, 1):
361
+ d["risk"]["weights"][wk] = float(wv)
362
+ elif k in ("medium", "high", "t4_code_risk"):
363
+ if _num(cfg, f"risk.{k}", v, 0, 1):
364
+ d["risk"][k] = float(v)
365
+ elif k in ("blast_full", "churn_full_commits", "complexity_full_branches"):
366
+ if _num(cfg, f"risk.{k}", v, 1, 1_000_000):
367
+ d["risk"][k] = v
368
+ else:
369
+ cfg.warnings.append(f"risk.{k}: unknown field ignored")
370
+ if d["risk"]["medium"] >= d["risk"]["high"]:
371
+ cfg.errors.append("risk: medium must be below high; using defaults")
372
+ d["risk"]["medium"], d["risk"]["high"] = (DEFAULTS["risk"]["medium"],
373
+ DEFAULTS["risk"]["high"])
374
+
375
+
376
+ def _merge_budget(cfg: Config, raw: dict) -> None:
377
+ _section(cfg, raw, "budget", {
378
+ "soft_limit_pct": (0, 100), "state_max_age_hours": (0, 24 * 30),
379
+ "weekly_token_limit": (1, 10**13)}, nullable={"weekly_token_limit"})
380
+
381
+
382
+ def _merge_history(cfg: Config, raw: dict) -> None:
383
+ d = cfg.data
384
+ hist = raw.get("history")
385
+ if isinstance(hist, dict) and "explore_down" in hist:
386
+ hist = dict(hist)
387
+ v = hist.pop("explore_down")
388
+ if isinstance(v, bool):
389
+ d["history"]["explore_down"] = v
390
+ else:
391
+ cfg.errors.append(f"history.explore_down: expected true or false, got {v!r}")
392
+ _section(cfg, {"history": hist}, "history", {
393
+ "min_samples": (1, 10_000), "fail_rate_up": (0, 1), "success_rate_down": (0, 1),
394
+ "window_days": (1, 3650), "struggle_tool_errors": (0, 10_000),
395
+ "struggle_turns": (0, 10_000)})
396
+
397
+
398
+ def _merge_run(cfg: Config, raw: dict) -> None:
399
+ d = cfg.data
400
+ run = raw.get("run")
401
+ if isinstance(run, dict):
402
+ run = dict(run)
403
+ for k in ("test_command", "permission_mode"):
404
+ if k not in run:
405
+ continue
406
+ v = run.pop(k)
407
+ if v is None or isinstance(v, str) and v.strip():
408
+ d["run"][k] = v.strip() if isinstance(v, str) else None
409
+ else:
410
+ cfg.errors.append(f"run.{k}: expected a non-empty string or null, got {v!r}")
411
+ _section(cfg, {"run": run}, "run", {
412
+ "test_timeout_s": (1, 86_400), "max_escalations": (0, 4), "max_turns": (1, 10_000),
413
+ "max_budget_usd": (0.001, 100_000), "timeout_s": (10, 86_400)},
414
+ nullable={"max_budget_usd"})
415
+ if isinstance(d["run"]["max_escalations"], float):
416
+ d["run"]["max_escalations"] = int(d["run"]["max_escalations"])
417
+ elif run is not None:
418
+ cfg.errors.append("run: expected a mapping")
419
+
420
+
421
+ def _merge_llm(cfg: Config, raw: dict) -> None:
422
+ d = cfg.data
423
+ llm = raw.get("llm")
424
+ if isinstance(llm, dict):
425
+ llm = dict(llm)
426
+ m, e = llm.pop("model", None), llm.pop("effort", None)
427
+ if m is not None:
428
+ if _valid_model(m):
429
+ d["llm"]["model"] = m
430
+ else:
431
+ cfg.errors.append(f"llm.model: unknown model {m!r}")
432
+ if e is not None:
433
+ if e in EFFORTS:
434
+ d["llm"]["effort"] = e
435
+ else:
436
+ cfg.errors.append(f"llm.effort: must be one of {'|'.join(EFFORTS)}, got {e!r}")
437
+ _section(cfg, {"llm": llm}, "llm", {"threshold": (0, 1), "timeout_s": (1, 600)})
438
+ elif llm is not None:
439
+ cfg.errors.append("llm: expected a mapping")
440
+
441
+
442
+ def _merge_routing(cfg: Config, raw: dict) -> None:
443
+ d = cfg.data
444
+ routing = raw.get("routing")
445
+ if isinstance(routing, dict):
446
+ for k, v in routing.items():
447
+ if k == "max_escalation":
448
+ if _num(cfg, "routing.max_escalation", v, 0, 4):
449
+ d["routing"][k] = int(v)
450
+ elif k == "ceiling_without_critical":
451
+ if v in TIERS:
452
+ d["routing"][k] = v
453
+ else:
454
+ cfg.errors.append(f"routing.{k}: expected T0..T4, got {v!r}")
455
+ else:
456
+ cfg.warnings.append(f"routing.{k}: unknown field ignored")
457
+ elif routing is not None:
458
+ cfg.errors.append("routing: expected a mapping")
459
+
460
+
461
+ def _merge_hooks(cfg: Config, raw: dict) -> None:
462
+ d = cfg.data
463
+ hooks = raw.get("hooks")
464
+ if isinstance(hooks, dict):
465
+ for k, v in hooks.items():
466
+ if k in ("watchdog_ms", "success_gap_minutes", "rework_minutes",
467
+ "prompt_retention_days"):
468
+ lo, hi = {"watchdog_ms": (100, 60_000), "prompt_retention_days": (0, 3650)}.get(
469
+ k, (1, 10_080))
470
+ if _num(cfg, f"hooks.{k}", v, lo, hi):
471
+ d["hooks"][k] = int(v)
472
+ elif k in DEFAULTS["hooks"]:
473
+ if isinstance(v, bool):
474
+ d["hooks"][k] = v
475
+ else:
476
+ cfg.errors.append(f"hooks.{k}: expected true or false, got {v!r}")
477
+ else:
478
+ cfg.warnings.append(f"hooks.{k}: unknown field ignored")
479
+ elif hooks is not None:
480
+ cfg.errors.append("hooks: expected a mapping")
481
+
482
+
483
+ # One validator per config section, run in this order; add a section by appending here.
484
+ _MERGERS = (_merge_tiers, _merge_class_base, _merge_critical, _merge_hard_terms, _merge_pricing,
485
+ _merge_risk, _merge_budget, _merge_history, _merge_run, _merge_llm, _merge_routing,
486
+ _merge_hooks)
487
+
488
+
489
+ def _section(cfg: Config, raw: dict, name: str, ranges: dict[str, tuple[float, float]],
490
+ nullable: set[str] = frozenset()) -> None:
491
+ sec = raw.get(name)
492
+ if sec is None:
493
+ return
494
+ if not isinstance(sec, dict):
495
+ cfg.errors.append(f"{name}: expected a mapping")
496
+ return
497
+ for k, v in sec.items():
498
+ if k not in ranges:
499
+ cfg.warnings.append(f"{name}.{k}: unknown field ignored")
500
+ elif v is None and k in nullable:
501
+ cfg.data[name][k] = None
502
+ elif _num(cfg, f"{name}.{k}", v, *ranges[k]):
503
+ cfg.data[name][k] = v
504
+
505
+
506
+ _MODEL_RANK = {"haiku": 0, "sonnet": 1, "opus": 2, "fable": 3}
507
+
508
+
509
+ def _check_monotonic(cfg: Config) -> None:
510
+ prev = None
511
+ for t in TIERS:
512
+ spec = cfg.data["tiers"][t]
513
+ m = next((r for a, r in _MODEL_RANK.items() if a in spec["model"]), None)
514
+ cur = (m, EFFORTS.index(spec["effort"]))
515
+ if prev is not None and m is not None and prev[0] is not None and cur < prev:
516
+ cfg.warnings.append(f"tiers.{t} ({spec['model']}/{spec['effort']}) is cheaper than "
517
+ f"the tier below it; escalation may not help")
518
+ prev = cur
ccr/detect/__init__.py ADDED
@@ -0,0 +1,123 @@
1
+ """Repository detection: languages, frameworks, size, suggested defaults."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import re
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ SKIP_DIRS = {
10
+ "node_modules", ".venv", "venv", "vendor", "build", "dist", ".git", "target",
11
+ "__pycache__", ".tox", ".mypy_cache", ".pytest_cache", ".next", ".gradle",
12
+ ".idea", ".ccr", "site-packages",
13
+ }
14
+ SKIP_FILES = {
15
+ "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "uv.lock", "poetry.lock",
16
+ "Cargo.lock", "go.sum", "Gemfile.lock", "composer.lock", "Pipfile.lock",
17
+ }
18
+ EXT_LANG = {
19
+ ".py": "Python", ".ts": "TypeScript", ".tsx": "TypeScript", ".js": "JavaScript",
20
+ ".jsx": "JavaScript", ".mjs": "JavaScript", ".cjs": "JavaScript", ".go": "Go",
21
+ ".java": "Java", ".kt": "Kotlin", ".rs": "Rust", ".rb": "Ruby", ".php": "PHP",
22
+ ".cs": "C#", ".c": "C", ".h": "C", ".cpp": "C++", ".cc": "C++", ".hpp": "C++",
23
+ ".swift": "Swift", ".scala": "Scala", ".zig": "Zig", ".ex": "Elixir",
24
+ ".exs": "Elixir", ".lua": "Lua", ".sh": "Shell", ".dart": "Dart",
25
+ }
26
+ MAX_LOC_BYTES = 2_000_000
27
+ SMALL_FILES, SMALL_LOC = 50, 5000
28
+
29
+ # (framework name, manifest file, regex searched in lowercase content)
30
+ FRAMEWORK_RULES = [
31
+ ("FastAPI", ("pyproject.toml", "requirements.txt"), r"fastapi"),
32
+ ("Django", ("pyproject.toml", "requirements.txt"), r"django"),
33
+ ("Flask", ("pyproject.toml", "requirements.txt"), r"flask"),
34
+ ("Typer", ("pyproject.toml", "requirements.txt"), r"typer"),
35
+ ("pytest", ("pyproject.toml", "requirements.txt"), r"pytest"),
36
+ ("React", ("package.json",), r'"react"'),
37
+ ("Next.js", ("package.json",), r'"next"'),
38
+ ("Vue", ("package.json",), r'"vue"'),
39
+ ("Angular", ("package.json",), r'"@angular/core"'),
40
+ ("Express", ("package.json",), r'"express"'),
41
+ ("NestJS", ("package.json",), r'"@nestjs/core"'),
42
+ ("Gin", ("go.mod",), r"gin-gonic/gin"),
43
+ ("Echo", ("go.mod",), r"labstack/echo"),
44
+ ("Spring", ("pom.xml", "build.gradle", "build.gradle.kts"), r"spring"),
45
+ ("Actix", ("Cargo.toml",), r"actix"),
46
+ ("Axum", ("Cargo.toml",), r"axum"),
47
+ ("Tokio", ("Cargo.toml",), r"tokio"),
48
+ ("Rails", ("Gemfile",), r"rails"),
49
+ ("Laravel", ("composer.json",), r"laravel"),
50
+ ]
51
+
52
+
53
+ @dataclass
54
+ class Profile:
55
+ root: str
56
+ languages: dict[str, int] = field(default_factory=dict) # name -> file count
57
+ frameworks: list[str] = field(default_factory=list)
58
+ file_count: int = 0
59
+ total_loc: int = 0
60
+ suggested_model: str = "sonnet"
61
+ suggested_effort: str = "low"
62
+
63
+ def to_dict(self) -> dict:
64
+ return self.__dict__.copy()
65
+
66
+
67
+ def _count_lines(path: Path) -> int:
68
+ try:
69
+ if path.stat().st_size > MAX_LOC_BYTES:
70
+ return 0
71
+ with open(path, "rb") as f:
72
+ return sum(1 for _ in f)
73
+ except OSError:
74
+ return 0
75
+
76
+
77
+ def _read(path: Path) -> str:
78
+ try:
79
+ return path.read_text(encoding="utf-8", errors="ignore").lower()
80
+ except OSError:
81
+ return ""
82
+
83
+
84
+ def _detect_frameworks(manifests: dict[str, list[Path]]) -> list[str]:
85
+ found: list[str] = []
86
+ for name, files, pattern in FRAMEWORK_RULES:
87
+ for fname in files:
88
+ if any(re.search(pattern, _read(p)) for p in manifests.get(fname, [])):
89
+ found.append(name)
90
+ break
91
+ return found
92
+
93
+
94
+ def detect(root: str | Path) -> Profile:
95
+ root = Path(root).resolve()
96
+ langs: dict[str, int] = {}
97
+ manifests: dict[str, list[Path]] = {}
98
+ wanted = {f for _, fs, _ in FRAMEWORK_RULES for f in fs}
99
+ file_count = total_loc = 0
100
+ for dirpath, dirnames, filenames in os.walk(root):
101
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
102
+ for name in filenames:
103
+ if name in SKIP_FILES:
104
+ continue
105
+ p = Path(dirpath) / name
106
+ if name in wanted:
107
+ manifests.setdefault(name, []).append(p)
108
+ lang = EXT_LANG.get(p.suffix.lower())
109
+ if lang:
110
+ langs[lang] = langs.get(lang, 0) + 1
111
+ file_count += 1
112
+ total_loc += _count_lines(p)
113
+ langs = dict(sorted(langs.items(), key=lambda kv: (-kv[1], kv[0])))
114
+ small = file_count < SMALL_FILES and total_loc < SMALL_LOC
115
+ return Profile(
116
+ root=str(root),
117
+ languages=langs,
118
+ frameworks=_detect_frameworks(manifests),
119
+ file_count=file_count,
120
+ total_loc=total_loc,
121
+ suggested_model="haiku" if small else "sonnet",
122
+ suggested_effort="low",
123
+ )