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/__init__.py ADDED
File without changes
ccr/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ """`python -m ccr ...` (used by hook commands when `ccr` is not on PATH)."""
2
+ from ccr.entry import main
3
+
4
+ main()
ccr/cli.py ADDED
@@ -0,0 +1,595 @@
1
+ """ccr command line interface."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import logging
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Optional
9
+
10
+ import typer
11
+
12
+ from ccr.doctor import _doctor_history, run_doctor # noqa: F401 - re-exported
13
+ from ccr.report import format_decision
14
+
15
+ app = typer.Typer(help="Route Claude Code tasks to the cheapest sufficient model.",
16
+ no_args_is_help=True, add_completion=False)
17
+
18
+ log = logging.getLogger("ccr")
19
+
20
+
21
+ def _setup_logging(root: Path, verbose: bool) -> None:
22
+ if not verbose:
23
+ return
24
+ d = root / ".ccr" / "local"
25
+ d.mkdir(parents=True, exist_ok=True)
26
+ logging.basicConfig(filename=d / "ccr.log", level=logging.DEBUG,
27
+ format="%(asctime)s %(levelname)s %(message)s", force=True)
28
+ typer.echo(f"verbose: logging to {d / 'ccr.log'}")
29
+
30
+
31
+ def _print_profile(p) -> None:
32
+ typer.echo(f"Root: {p.root}")
33
+ langs = ", ".join(f"{k} ({v})" for k, v in p.languages.items()) or "none detected"
34
+ typer.echo(f"Languages: {langs}")
35
+ typer.echo(f"Frameworks: {', '.join(p.frameworks) or 'none detected'}")
36
+ typer.echo(f"Files: {p.file_count}")
37
+ typer.echo(f"LOC: {p.total_loc}")
38
+ typer.echo(f"Suggested default: {p.suggested_model} / {p.suggested_effort}")
39
+
40
+
41
+ def _show_plan(plan, dry_run: bool) -> None:
42
+ for n in plan.notes:
43
+ typer.echo(f" - {n}")
44
+ for w in plan.warnings:
45
+ typer.echo(f" ! {w}")
46
+ if not plan.changes:
47
+ typer.echo("Nothing to change (already up to date).")
48
+ return
49
+ if dry_run:
50
+ typer.echo(f"Dry run: {len(plan.changes)} file(s) would change; nothing written.\n")
51
+ typer.echo(plan.diff(), nl=False)
52
+ else:
53
+ for c in plan.changes:
54
+ typer.echo(f" {c.action:<6} {c.rel}")
55
+
56
+
57
+ @app.command()
58
+ def init(dry_run: bool = typer.Option(False, "--dry-run", help="Print the exact diff; "
59
+ "write nothing"),
60
+ force: bool = typer.Option(False, "--force", help="Override your model/effortLevel "
61
+ "and regenerate edited ccr agent files (with backups)"),
62
+ local: bool = typer.Option(False, "--local", help="Write settings to "
63
+ ".claude/settings.local.json (personal, uncommitted)"),
64
+ no_statusline: bool = typer.Option(False, "--no-statusline",
65
+ help="Do not install the status line relay"),
66
+ no_graph: bool = typer.Option(False, "--no-graph", help="Skip building the graph"),
67
+ command: Optional[str] = typer.Option(None, "--command", help="Command prefix hooks "
68
+ "use to run ccr (default: auto-detect)"),
69
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
70
+ """Install ccr into the project: settings (model, hooks, status line), agents, config.
71
+
72
+ Re-running is safe: existing user keys, hooks and edited agents are kept, and every
73
+ modified file is backed up to .ccr/backups/ first."""
74
+ from ccr.config import load_config
75
+ from ccr.detect import detect
76
+ from ccr.install import InstallError, apply, plan_init
77
+ from ccr.install.settings import SettingsError
78
+ root = path.resolve()
79
+ prof = detect(root)
80
+ typer.echo(f"ccr init ({root})")
81
+ langs = ", ".join(f"{k} {v}" for k, v in list(prof.languages.items())[:4]) or "no code"
82
+ typer.echo(f" profile: {langs}; {prof.file_count} files, {prof.total_loc} LOC -> "
83
+ f"default {prof.suggested_model}/{prof.suggested_effort}")
84
+ if not dry_run and not no_graph:
85
+ from ccr.graph import update
86
+ try:
87
+ r = update(root)
88
+ typer.echo(f" graph: {r.scanned} files ({'built' if r.full else 'updated'}, "
89
+ f"parsed {r.parsed}) in {r.elapsed:.1f}s")
90
+ except Exception as e: # graph is optional; routing degrades without it
91
+ typer.echo(f" ! graph build failed ({e}); routing works without it")
92
+ elif dry_run and not no_graph:
93
+ typer.echo(" graph: would be built/updated (.ccr/graph.db, git-ignored)")
94
+ try:
95
+ plan = plan_init(root, cfg=load_config(root), profile=prof, force=force, local=local,
96
+ statusline=not no_statusline, command=command)
97
+ except (SettingsError, InstallError) as e:
98
+ typer.echo(f"error: {e}", err=True)
99
+ raise typer.Exit(1) from None
100
+ _show_plan(plan, dry_run)
101
+ if dry_run or not plan.changes:
102
+ return
103
+ try:
104
+ bdir = apply(plan)
105
+ except (InstallError, OSError) as e:
106
+ typer.echo(f"error: {e}", err=True)
107
+ raise typer.Exit(1) from None
108
+ if bdir:
109
+ typer.echo(f" backups in {bdir.relative_to(root)}")
110
+ typer.echo("Done. Start `claude` here; `ccr explain \"<task>\"` previews routing.")
111
+
112
+
113
+ @app.command()
114
+ def profile(path: Path = typer.Argument(Path("."), help="Project root"),
115
+ apply_: bool = typer.Option(False, "--apply", help="Write the suggested model/"
116
+ "effortLevel into .claude/settings.json (overrides)"),
117
+ dry_run: bool = typer.Option(False, "--dry-run", help="With --apply: print the "
118
+ "diff only"),
119
+ local: bool = typer.Option(False, "--local", help="With --apply: write "
120
+ ".claude/settings.local.json instead")) -> None:
121
+ """Print the detected project profile; --apply sets it as the session default."""
122
+ from ccr.detect import detect
123
+ p = detect(path)
124
+ _print_profile(p)
125
+ if not apply_:
126
+ return
127
+ from ccr.install import apply, plan_profile
128
+ from ccr.install.settings import SettingsError
129
+ try:
130
+ plan = plan_profile(path, p, local=local)
131
+ except SettingsError as e:
132
+ typer.echo(f"error: {e}", err=True)
133
+ raise typer.Exit(1) from None
134
+ _show_plan(plan, dry_run)
135
+ if plan.changes and not dry_run:
136
+ apply(plan)
137
+
138
+
139
+ @app.command()
140
+ def explain(task: str = typer.Argument(..., help="The task prompt to evaluate"),
141
+ llm: bool = typer.Option(False, "--llm", help="Ask haiku (your claude CLI) when "
142
+ "rule confidence is low"),
143
+ as_json: bool = typer.Option(False, "--json", help="Machine-readable output"),
144
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
145
+ """Show the tier decision, scores, touched files and reasoning. Runs nothing."""
146
+ from ccr.route import decide
147
+ d = decide(task, path.resolve(), allow_llm=llm)
148
+ if as_json:
149
+ typer.echo(json.dumps(d.to_dict(), indent=2))
150
+ return
151
+ for line in format_decision(task, d):
152
+ typer.echo(line)
153
+
154
+
155
+ @app.command()
156
+ def run(task: Optional[str] = typer.Argument(None, help="The task; `-` or omitted reads "
157
+ "stdin"),
158
+ tier: Optional[str] = typer.Option(None, "--tier", help="Start at this tier "
159
+ "(T0..T4) instead of the routed one"),
160
+ max_turns: Optional[int] = typer.Option(None, "--max-turns", min=1,
161
+ help="Turn cap per attempt (default "
162
+ "run.max_turns)"),
163
+ max_budget_usd: Optional[float] = typer.Option(
164
+ None, "--max-budget-usd", min=0.001, help="Spend cap for the whole run, all "
165
+ "attempts (claude's own client-side estimate)"),
166
+ max_escalations: Optional[int] = typer.Option(None, "--max-escalations", min=0,
167
+ max=4, help="Default "
168
+ "run.max_escalations (1)"),
169
+ test_command: Optional[str] = typer.Option(None, "--test-command",
170
+ help="Shell command that must pass "
171
+ "(default run.test_command)"),
172
+ no_test: bool = typer.Option(False, "--no-test", help="Skip the test command"),
173
+ permission_mode: Optional[str] = typer.Option(None, "--permission-mode",
174
+ help="Passed to claude (e.g. "
175
+ "acceptEdits)"),
176
+ no_llm: bool = typer.Option(False, "--no-llm", help="Rules only: never ask haiku "
177
+ "to help classify"),
178
+ dry_run: bool = typer.Option(False, "--dry-run", help="Show the routing and the "
179
+ "command; run nothing"),
180
+ as_json: bool = typer.Option(False, "--json", help="Print a JSON summary instead "
181
+ "of the result text"),
182
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
183
+ """Run a task headlessly with routing and one-tier escalation.
184
+
185
+ Routes the task, runs your `claude -p` at that tier's model/effort, escalates one tier
186
+ on failure and logs every attempt to .ccr/history.jsonl (no prompt text)."""
187
+ import sys
188
+
189
+ from ccr.config import TIERS, load_config
190
+ from ccr.headless import build_argv, find_claude, run_task
191
+ from ccr.route import decide
192
+ root = path.resolve()
193
+ if task is None or task == "-":
194
+ task = sys.stdin.read()
195
+ if not task or not task.strip():
196
+ typer.echo("error: empty task", err=True)
197
+ raise typer.Exit(2)
198
+ if tier is not None:
199
+ tier = tier.upper()
200
+ if tier not in TIERS:
201
+ typer.echo(f"error: --tier must be one of {', '.join(TIERS)}", err=True)
202
+ raise typer.Exit(2)
203
+ cfg = load_config(root)
204
+
205
+ def say(msg: str) -> None:
206
+ typer.echo(f"ccr: {msg}", err=True)
207
+
208
+ d = decide(task, root, cfg=cfg, allow_llm=not no_llm)
209
+ t = cfg.tier(tier) if tier else d.tier
210
+ say(f"routed {d.tier.name} ({d.tier.model}/{d.tier.effort}) for {d.task_class.kind} in "
211
+ f"{d.area}, confidence {d.confidence:.2f}" + (f"; starting at {t.name} (--tier)"
212
+ if tier else ""))
213
+ say(f"learning: {d.history}")
214
+ if d.llm_used:
215
+ say(f"LLM: {d.llm}")
216
+ if dry_run:
217
+ exe = find_claude(dict(os.environ)) or "claude"
218
+ rc = cfg["run"]
219
+ argv = build_argv(exe, t, max_turns=max_turns or rc["max_turns"],
220
+ max_budget_usd=max_budget_usd if max_budget_usd is not None
221
+ else rc["max_budget_usd"],
222
+ permission_mode=permission_mode or rc["permission_mode"])
223
+ typer.echo("would run: " + " ".join(argv) + " < task on stdin")
224
+ tc = test_command or rc["test_command"]
225
+ esc = rc["max_escalations"] if max_escalations is None else max_escalations
226
+ typer.echo(f"test command: {tc if tc and not no_test else 'none'}; "
227
+ f"max escalations: {esc}")
228
+ return
229
+ res = run_task(task, root, cfg=cfg, tier=tier, max_turns=max_turns,
230
+ max_budget_usd=max_budget_usd, max_escalations=max_escalations,
231
+ test_command=test_command, use_tests=not no_test,
232
+ permission_mode=permission_mode, decision=d, echo=say)
233
+ last = res.attempts[-1] if res.attempts else None
234
+ if as_json:
235
+ typer.echo(json.dumps(res.to_dict(), indent=2))
236
+ elif last is not None and last.result:
237
+ typer.echo(last.result)
238
+ tiers = " -> ".join(f"{a.tier} {a.outcome}" for a in res.attempts)
239
+ say(f"{'success' if res.success else 'failed'}: {tiers}; {res.tokens} tokens, "
240
+ f"${res.cost_usd:.4f}" + (f"; stopped: {res.stopped}" if res.stopped and
241
+ not res.success else "")
242
+ + (f"; resume with `claude --resume {last.session}`" if last and last.session
243
+ else ""))
244
+ if last is not None and last.outcome == "error":
245
+ raise typer.Exit(2)
246
+ raise typer.Exit(0 if res.success else 1)
247
+
248
+
249
+ @app.command()
250
+ def stats(as_json: bool = typer.Option(False, "--json", help="Machine-readable output"),
251
+ days: Optional[float] = typer.Option(None, "--days", min=0.01,
252
+ help="Only the last N days"),
253
+ misroutes: bool = typer.Option(False, "--misroutes",
254
+ help="List each over- and under-routed task"),
255
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
256
+ """Show usage, estimated savings, misroutes, tier distribution, success and escalation.
257
+
258
+ Per tier, area and task class, plus what the learning loop does with the history."""
259
+ from ccr import history as H
260
+ from ccr.config import load_config
261
+ from ccr.history.stats import compute, format_text
262
+ root = path.resolve()
263
+ cfg = load_config(root)
264
+ s = compute(H.read(root, window_days=days), cfg)
265
+ if as_json:
266
+ typer.echo(json.dumps(s, indent=2))
267
+ return
268
+ for line in format_text(s, root, detail=misroutes):
269
+ typer.echo(line)
270
+
271
+
272
+ @app.command()
273
+ def dashboard(days: Optional[float] = typer.Option(None, "--days", min=0.01,
274
+ help="Only the last N days"),
275
+ out: Optional[Path] = typer.Option(None, "--out", help="Output file (default "
276
+ ".ccr/local/dashboard.html)"),
277
+ open_: bool = typer.Option(False, "--open", help="Open it in the browser"),
278
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
279
+ """Write a self-contained HTML dashboard: charts, savings, misroutes and recent tasks."""
280
+ from ccr import history as H
281
+ from ccr.config import load_config
282
+ from ccr.history import dashboard as dash
283
+ root = path.resolve()
284
+ cfg = load_config(root)
285
+ target = (out or root / ".ccr" / "local" / "dashboard.html").resolve()
286
+ dash.write(root, H.read(root, window_days=days), cfg, target)
287
+ typer.echo(f"wrote {target}")
288
+ if open_:
289
+ import webbrowser
290
+ webbrowser.open(target.as_uri())
291
+
292
+
293
+ @app.command("export-benchmark")
294
+ def export_benchmark(out: Path = typer.Option(Path("ccr-benchmark.json"), "--out",
295
+ help="Output JSON file"),
296
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
297
+ """Write a replay set from decided tasks with stored prompts (needs hooks.store_prompts).
298
+
299
+ Replay it with: uv run python scripts/bench_routing.py --prompts FILE"""
300
+ from ccr import history as H
301
+ from ccr.history import calibrate, prompts
302
+ root = path.resolve()
303
+ items = calibrate.export_benchmark(H.read(root), prompts.read(root))
304
+ if not items:
305
+ typer.echo("no decided tasks with a stored prompt yet: set hooks.store_prompts: true, "
306
+ "use ccr, and mark outcomes with `ccr feedback good|bad`", err=True)
307
+ raise typer.Exit(1)
308
+ out.write_text(json.dumps(items, indent=1))
309
+ typer.echo(f"wrote {len(items)} labelled prompt(s) to {out} (contains your prompt text)")
310
+
311
+
312
+ @app.command()
313
+ def calibrate(as_json: bool = typer.Option(False, "--json", help="Machine-readable output"),
314
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
315
+ """Fit failure odds on routing signals and compare with the rules (report only)."""
316
+ from ccr import history as H
317
+ from ccr.history import calibrate as C
318
+ res = C.fit(H.read(path.resolve()))
319
+ if as_json:
320
+ typer.echo(json.dumps(res, indent=2))
321
+ return
322
+ for line in C.format_text(res):
323
+ typer.echo(line)
324
+
325
+
326
+ @app.command()
327
+ def shadow(from_tier: str = typer.Option("T3", "--from-tier",
328
+ help="Sample tasks routed to this tier or above"),
329
+ lower: Optional[str] = typer.Option(None, "--shadow-tier", help="Tier to try instead "
330
+ "(default: one below the task's tier)"),
331
+ sample: int = typer.Option(3, "--sample", min=1, max=50, help="How many tasks to re-run"),
332
+ max_budget_usd: Optional[float] = typer.Option(None, "--max-budget-usd", min=0.01,
333
+ help="Total spend cap across the sample"),
334
+ test_command: Optional[str] = typer.Option(None, "--test-command", help="Must exit 0 "
335
+ "for a shadow run to count as success"),
336
+ yes: bool = typer.Option(False, "--yes", help="Actually run (spends real usage)"),
337
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
338
+ """Re-run sampled deep-tier tasks at a lower tier to measure over-routing (opt-in, costs usage).
339
+
340
+ Runs your own `claude -p` in a throwaway git worktree of HEAD. Prompts come from
341
+ `hooks.store_prompts`. Without --yes it only prints the plan."""
342
+ from ccr import history as H
343
+ from ccr.config import TIERS, load_config
344
+ from ccr.history import prompts, shadow as S
345
+ root = path.resolve()
346
+ if from_tier not in TIERS or (lower and lower not in TIERS):
347
+ typer.echo(f"error: tiers are {', '.join(TIERS)}", err=True)
348
+ raise typer.Exit(2)
349
+ cfg = load_config(root)
350
+ picks = S.pick(H.read(root), prompts.read(root), {e["id"] for e in S.read(root)},
351
+ from_tier, sample)
352
+ if not picks:
353
+ typer.echo("nothing to sample: need successful tasks at or above "
354
+ f"{from_tier} with stored prompts (hooks.store_prompts: true)", err=True)
355
+ raise typer.Exit(1)
356
+ if max_budget_usd is None:
357
+ typer.echo("error: --max-budget-usd is required (total cap across the sample)", err=True)
358
+ raise typer.Exit(2)
359
+ per = round(max_budget_usd / len(picks), 4)
360
+ tests = (f"tests: {test_command}" if test_command else
361
+ "NO test command: success will only mean claude exited cleanly")
362
+ typer.echo(f"plan: re-run {len(picks)} task(s) at {lower or 'one tier below'}, up to ${per} "
363
+ f"each (worst case ${max_budget_usd}); {tests}")
364
+ typer.echo("note: this uses your own claude login. On a subscription it draws on your plan "
365
+ "limits; with an API key it is billed in dollars.")
366
+ if not yes:
367
+ typer.echo("dry run: add --yes to execute")
368
+ raise typer.Exit(0)
369
+ logged = prompts.read(root)
370
+ for rec in picks:
371
+ entry = S.run_one(root, rec, logged[rec["id"]]["prompt"],
372
+ S.shadow_tier(rec["tier"], lower), cfg, budget=per,
373
+ test_command=test_command)
374
+ S.append(root, entry)
375
+ typer.echo(f" {rec['id'][:8]} {entry['deep_tier']}->{entry['shadow_tier']}: "
376
+ f"{entry['outcome']} ({entry['reason']})")
377
+ for line in S.format_lines(S.summarize(S.read(root))):
378
+ typer.echo(line)
379
+
380
+
381
+ @app.command()
382
+ def tune(apply: bool = typer.Option(False, "--apply", help="Write the changes (backs up the config)"),
383
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
384
+ """Propose config edits from misroute evidence as a diff. Never changes anything without --apply."""
385
+ import shutil
386
+ import time
387
+ from ccr import history as H
388
+ from ccr.config import config_path, load_config
389
+ from ccr.history import tune as TU
390
+ root = path.resolve()
391
+ cfg = load_config(root)
392
+ changes = TU.propose(H.read(root), cfg)
393
+ if not changes:
394
+ typer.echo("no changes proposed (not enough decided misroutes yet)")
395
+ return
396
+ cp = config_path(root)
397
+ old = cp.read_text(encoding="utf-8") if cp.exists() else "version: 1\n"
398
+ new = TU.apply_text(old, changes)
399
+ for ch in changes:
400
+ typer.echo(f"- {ch['why']}")
401
+ for line in TU.diff(old, new):
402
+ typer.echo(line)
403
+ if not apply:
404
+ typer.echo("\nnot applied: run `ccr tune --apply` to write this")
405
+ return
406
+ tmp = cp.with_suffix(".tune.tmp")
407
+ tmp.write_text(new, encoding="utf-8")
408
+ check = load_config(path=tmp)
409
+ if check.errors:
410
+ tmp.unlink(missing_ok=True)
411
+ typer.echo("error: the edited config would be invalid: " + "; ".join(check.errors), err=True)
412
+ raise typer.Exit(2)
413
+ if cp.exists():
414
+ bk = root / ".ccr" / "backups"
415
+ bk.mkdir(parents=True, exist_ok=True)
416
+ shutil.copy2(cp, bk / f"config.yaml.{int(time.time())}")
417
+ tmp.replace(cp)
418
+ typer.echo(f"applied to {cp} (backup in .ccr/backups/)")
419
+
420
+
421
+ @app.command()
422
+ def purge(prompts_: bool = typer.Option(False, "--prompts", help="Stored prompts and decisions"),
423
+ shadow_: bool = typer.Option(False, "--shadow", help="Shadow-run results"),
424
+ older_than: Optional[int] = typer.Option(None, "--older-than", min=1,
425
+ help="Only entries older than N days (prompts)"),
426
+ redact_: bool = typer.Option(False, "--redact", help="Re-scrub existing stored prompts"),
427
+ yes: bool = typer.Option(False, "--yes", help="Actually delete (default: show only)"),
428
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
429
+ """Delete or scrub locally stored prompts and shadow results. Shows what it would do first."""
430
+ import json
431
+ from ccr.history import prompts as P, shadow as S
432
+ root = path.resolve()
433
+ if not (prompts_ or shadow_ or redact_):
434
+ typer.echo("choose what to purge: --prompts, --shadow, or --redact", err=True)
435
+ raise typer.Exit(2)
436
+ pp, sp = P.path(root), S.path(root)
437
+ entries = P.read(root)
438
+ typer.echo(f"prompts: {len(entries)} stored ({pp.stat().st_size if pp.exists() else 0} bytes)")
439
+ typer.echo(f"shadow: {len(S.read(root))} result(s)")
440
+ if not yes:
441
+ typer.echo("dry run: add --yes to apply")
442
+ return
443
+ if prompts_:
444
+ if older_than:
445
+ typer.echo(f"removed {P.prune(root, older_than)} prompt(s) older than {older_than} days")
446
+ else:
447
+ pp.unlink(missing_ok=True)
448
+ typer.echo("removed all stored prompts")
449
+ if shadow_:
450
+ sp.unlink(missing_ok=True)
451
+ typer.echo("removed shadow results")
452
+ if redact_ and pp.exists():
453
+ n = 0
454
+ out = []
455
+ for e in P.read(root).values():
456
+ text, kinds = P.redact_text(str(e.get("prompt") or ""))
457
+ n += bool(kinds)
458
+ out.append(json.dumps({**e, "prompt": text, "redacted": sorted(
459
+ set(e.get("redacted") or []) | set(kinds))}, separators=(",", ":"), default=str))
460
+ pp.write_text("\n".join(out) + ("\n" if out else ""), encoding="utf-8")
461
+ typer.echo(f"re-scrubbed {n} prompt(s) that held secrets")
462
+
463
+
464
+ @app.command()
465
+ def feedback(verdict: Optional[str] = typer.Argument(None, help="good | bad (omit to show "
466
+ "the last task)"),
467
+ last: bool = typer.Option(True, "--last", help="Target the most recent routed "
468
+ "task (the default)"),
469
+ ref: Optional[str] = typer.Option(None, "--id", help="Target a task by id "
470
+ "(prefix) instead"),
471
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
472
+ """Mark the last routed task good or bad.
473
+
474
+ Works for interactive (hook) tasks, including one still in progress, and `ccr run`
475
+ attempts. Appends a correction record; history is never rewritten."""
476
+ from ccr.history import feedback as F
477
+ root = path.resolve()
478
+ if verdict is None:
479
+ t = F.find(root, ref)
480
+ typer.echo(F.describe(t) if t else "no routed task found")
481
+ raise typer.Exit(0 if t else 1)
482
+ verdict = verdict.lower()
483
+ if verdict not in ("good", "bad"):
484
+ typer.echo("error: verdict must be good or bad", err=True)
485
+ raise typer.Exit(2)
486
+ t, _ = F.mark(root, verdict, ref)
487
+ if t is None:
488
+ typer.echo("no matching routed task found" + (f" for id {ref!r}" if ref else ""),
489
+ err=True)
490
+ raise typer.Exit(1)
491
+ typer.echo(f"marked {verdict} ({'success' if verdict == 'good' else 'failure'}): "
492
+ f"{F.describe(t)}")
493
+
494
+
495
+ @app.command()
496
+ def graph(rebuild: bool = typer.Option(False, "--rebuild", help="Drop and rebuild the graph"),
497
+ stats: bool = typer.Option(False, "--stats", help="Show graph statistics"),
498
+ query: Optional[str] = typer.Option(None, "--query", help="Look up a symbol"),
499
+ offline: bool = typer.Option(False, "--offline", help="Never download grammars"),
500
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
501
+ """Build/refresh the code graph (incremental), or inspect it."""
502
+ from ccr.graph import Graph, update
503
+ root = path.resolve()
504
+ if rebuild or not (stats or query):
505
+ r = update(root, rebuild=rebuild, offline=offline or None)
506
+ kind = "built" if r.full else "updated"
507
+ typer.echo(f"graph {kind} ({r.mode}): {r.scanned} files, parsed {r.parsed}, "
508
+ f"unchanged {r.unchanged}, added {r.added}, removed {r.removed} "
509
+ f"in {r.elapsed:.2f}s")
510
+ if r.parsers:
511
+ typer.echo(" parsers: " + ", ".join(f"{k} {v}" for k, v in r.parsers.items()))
512
+ g = Graph.open(root)
513
+ if g is None:
514
+ if stats or query:
515
+ typer.echo("graph not built yet; run `ccr graph`")
516
+ raise typer.Exit(1)
517
+ return
518
+ with g:
519
+ if stats:
520
+ st = g.stats()
521
+ meta = st["meta"]
522
+ typer.echo(f"Files: {st['files']} ({st['tests']} tests)")
523
+ typer.echo(f"Symbols: {st['symbols']} "
524
+ f"({', '.join(f'{k} {v}' for k, v in st['symbol_kinds'].items())})")
525
+ typer.echo(f"Edges: {', '.join(f'{k} {v}' for k, v in st['edges'].items()) or 'none'}")
526
+ typer.echo(f"Languages: {', '.join(f'{k} {v}' for k, v in st['languages'].items())}")
527
+ typer.echo(f"Parsers: {', '.join(f'{k} {v}' for k, v in st['parsers'].items())}")
528
+ typer.echo(f"Unresolved imports (external or unknown): {st['unresolved_imports']}")
529
+ typer.echo(f"Mode: {meta.get('mode')} commit {(meta.get('commit') or '-')[:12]}")
530
+ typer.echo(f"Churn: {st['churn_files']} files over {meta.get('churn_days', '-')} days")
531
+ hot = g.hot_files(5)
532
+ if hot:
533
+ typer.echo("Hot files: " + ", ".join(f"{h['path']} ({h['commits']})" for h in hot))
534
+ typer.echo(f"DB size: {st['db_bytes'] // 1024} KiB")
535
+ if query:
536
+ found = g.lookup(query)
537
+ if not found:
538
+ typer.echo(f"no symbol matching {query!r}")
539
+ raise typer.Exit(1)
540
+ for s in found:
541
+ typer.echo(f"{s.kind:<9} {s.qualname} {s.path}:{s.start_line}-{s.end_line} "
542
+ f"branches {s.branches}, nesting {s.nesting}, "
543
+ f"callers {s.callers}, callees {s.callees}")
544
+ if len(found) == 1:
545
+ s = found[0]
546
+ for name, p, line in g.callers(s.id, 10):
547
+ typer.echo(f" <- {name} ({p}:{line})")
548
+ deps = g.dependents(s.path)
549
+ tests = g.tests_for(s.path)
550
+ ch = g.churn(s.path)
551
+ typer.echo(f" file dependents: {len(deps)}; tests: "
552
+ f"{', '.join(t.path for t in tests[:3]) or 'none found'}"
553
+ + (f"; churn {ch['commits']} commits / {ch['authors']} authors"
554
+ if ch else ""))
555
+
556
+
557
+ def _line(level: str, msg: str) -> None:
558
+ typer.echo(f" [{level:<4}] {msg}")
559
+
560
+
561
+ @app.command()
562
+ def doctor(verbose: bool = typer.Option(False, "--verbose", help="Log details to .ccr/local/ccr.log"),
563
+ path: Path = typer.Option(Path("."), "--path", help="Project root")) -> None:
564
+ """Check the environment and project setup."""
565
+ root = path.resolve()
566
+ _setup_logging(root, verbose)
567
+ typer.echo(f"ccr doctor ({root})")
568
+ results = run_doctor(root)
569
+ for level, msg in results:
570
+ log.debug("%s %s", level, msg)
571
+ _line(level, msg)
572
+ fails = sum(1 for lv, _ in results if lv == "FAIL")
573
+ warns = sum(1 for lv, _ in results if lv == "WARN")
574
+ typer.echo(f"{fails} problem(s), {warns} warning(s)")
575
+ raise typer.Exit(1 if fails else 0)
576
+
577
+
578
+ @app.command(context_settings={"allow_extra_args": True, "ignore_unknown_options": True})
579
+ def hook(ctx: typer.Context,
580
+ name: str = typer.Argument(..., help="session-start | prompt | stop")) -> None:
581
+ """Claude Code hook entry (reads hook JSON on stdin; always exits 0)."""
582
+ from ccr.hooks import main as hook_main
583
+ raise typer.Exit(hook_main([name, *ctx.args]))
584
+
585
+
586
+ @app.command(context_settings={"allow_extra_args": True, "ignore_unknown_options": True})
587
+ def statusline(ctx: typer.Context) -> None:
588
+ """Status line relay: records model/effort/rate limits, prints a short line.
589
+ `--wrap "<cmd>"` runs your own status line command and prints its output instead."""
590
+ from ccr.statusline import main as sl_main
591
+ raise typer.Exit(sl_main(list(ctx.args)))
592
+
593
+
594
+ if __name__ == "__main__":
595
+ app()