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/hooks/__init__.py ADDED
@@ -0,0 +1,134 @@
1
+ """Claude Code hooks: `ccr hook session-start | prompt | stop`.
2
+
3
+ Contract: every hook FAILS OPEN. Any exception, bad stdin, missing/corrupt config or graph,
4
+ or a run longer than the watchdog (`hooks.watchdog_ms`, default 1.5 s) -> nothing on stdout
5
+ or stderr and exit 0. Output is produced only after the hook finished, so it is never
6
+ partial. Hook paths import neither typer nor tree-sitter and only read the graph.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import io
11
+ import os
12
+ import sys
13
+ import threading
14
+ import time
15
+ import contextlib
16
+
17
+ HOOKS = ("session-start", "prompt", "stop")
18
+ DEFAULT_WATCHDOG_S = 1.5
19
+ EVENT = {"session-start": "SessionStart", "prompt": "UserPromptSubmit"}
20
+
21
+
22
+ def _impl(name: str):
23
+ if name == "prompt":
24
+ from ccr.hooks.prompt import run
25
+ elif name == "session-start":
26
+ from ccr.hooks.session_start import run
27
+ elif name == "stop":
28
+ from ccr.hooks.stop import run
29
+ else:
30
+ return None
31
+ return run
32
+
33
+
34
+ def _body(name: str, raw: bytes, environ, result: dict) -> tuple[str | None, object]:
35
+ """Returns (stdout text or None, root for logging)."""
36
+ from ccr.hooks.common import find_root, parse_stdin
37
+ if environ.get("CCR_INTERNAL"):
38
+ return None, None # inside ccr's own `claude -p` calls (ccr run, LLM assist)
39
+ data = parse_stdin(raw)
40
+ if data is None:
41
+ return None, None
42
+ root = find_root(data, environ)
43
+ if root is None:
44
+ return None, None # project not initialised with ccr
45
+ if environ.get("CCR_HOOK_DEBUG"): # field names only, never values
46
+ _log(root, f"{name} stdin keys: {','.join(sorted(map(str, data)))}")
47
+ from ccr.config import load_config
48
+ result["root"] = root
49
+ cfg = load_config(root)
50
+ if not environ.get("CCR_HOOK_WATCHDOG_MS"):
51
+ result["budget"] = float(cfg["hooks"]["watchdog_ms"]) / 1000.0
52
+ if cfg.errors and name != "session-start":
53
+ return None, root # corrupt config: stay out of the way (doctor reports it)
54
+ if not cfg["hooks"]["enabled"]:
55
+ return None, root
56
+ run = _impl(name)
57
+ if run is None:
58
+ return None, root
59
+ text = run(data, root, cfg)
60
+ if not text:
61
+ return None, root
62
+ event = EVENT.get(name)
63
+ if event is None:
64
+ return None, root
65
+ import json
66
+ out = {"hookSpecificOutput": {"hookEventName": event, "additionalContext": text}}
67
+ ui = getattr(text, "ui", None)
68
+ if ui and cfg["hooks"]["show_in_ui"]:
69
+ out["systemMessage"] = str(ui)
70
+ return json.dumps(out), root
71
+
72
+
73
+ def main(args: list[str], *, stdin=None, stdout=None, environ=None,
74
+ hard_exit: bool = True, watchdog_s: float | None = None) -> int:
75
+ """Entry for `ccr hook <name>`. Always returns 0 (or hard-exits 0 on watchdog)."""
76
+ t0 = time.perf_counter()
77
+ name = args[0] if args else ""
78
+ out = stdout if stdout is not None else sys.stdout
79
+ env = os.environ if environ is None else environ
80
+ if hard_exit: # real hook process: nothing may ever reach Claude Code's stderr
81
+ with contextlib.suppress(Exception):
82
+ sys.stderr = io.StringIO()
83
+ result: dict = {}
84
+
85
+ def work():
86
+ try:
87
+ src = stdin if stdin is not None else sys.stdin.buffer
88
+ raw = src.read(4 * 1024 * 1024)
89
+ result["out"], result["root"] = _body(name, raw, env, result)
90
+ except BaseException as e: # noqa: BLE001 - fail open on anything
91
+ result["err"] = e
92
+
93
+ budget = watchdog_s
94
+ if budget is None:
95
+ try:
96
+ budget = float(env.get("CCR_HOOK_WATCHDOG_MS", "")) / 1000.0
97
+ except ValueError:
98
+ budget = DEFAULT_WATCHDOG_S
99
+ budget = budget or DEFAULT_WATCHDOG_S
100
+ th = threading.Thread(target=work, name=f"ccr-hook-{name}", daemon=True)
101
+ th.start()
102
+ while th.is_alive():
103
+ if watchdog_s is None and "budget" in result: # hooks.watchdog_ms from config
104
+ budget = result["budget"]
105
+ left = t0 + budget - time.perf_counter()
106
+ if left <= 0:
107
+ break
108
+ th.join(min(left, 0.05))
109
+ if th.is_alive():
110
+ _log(result.get("root"), f"{name} watchdog {budget * 1000:.0f}ms exceeded")
111
+ if hard_exit:
112
+ with contextlib.suppress(Exception):
113
+ out.flush()
114
+ os._exit(0)
115
+ return 0
116
+ ms = (time.perf_counter() - t0) * 1000
117
+ if "err" in result:
118
+ e = result["err"]
119
+ _log(result.get("root"), f"{name} error {e.__class__.__name__}: {e} ({ms:.0f}ms)")
120
+ return 0
121
+ text = result.get("out")
122
+ _log(result.get("root"), f"{name} ok {ms:.0f}ms" + ("" if text else " (silent)"))
123
+ if text:
124
+ try:
125
+ out.write(text + "\n")
126
+ out.flush()
127
+ except Exception:
128
+ pass
129
+ return 0
130
+
131
+
132
+ def _log(root, line: str) -> None:
133
+ from ccr.hooks.common import log
134
+ log(root, line)
ccr/hooks/bg.py ADDED
@@ -0,0 +1,68 @@
1
+ """Background graph refresh started by the SessionStart hook: `python -m ccr.hooks.bg ROOT`.
2
+
3
+ Offline (never downloads grammars), single worker, guarded by .ccr/local/graph.lock so
4
+ concurrent sessions do not build at the same time. A lock older than LOCK_STALE_S is
5
+ considered abandoned.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import sys
11
+ import time
12
+ from pathlib import Path
13
+ import contextlib
14
+
15
+ LOCK_STALE_S = 600
16
+
17
+
18
+ def lock_path(root: Path) -> Path:
19
+ return Path(root) / ".ccr" / "local" / "graph.lock"
20
+
21
+
22
+ def lock_held(root: Path) -> bool:
23
+ try:
24
+ return time.time() - lock_path(root).stat().st_mtime < LOCK_STALE_S
25
+ except OSError:
26
+ return False
27
+
28
+
29
+ def acquire(root: Path) -> bool:
30
+ p = lock_path(root)
31
+ p.parent.mkdir(parents=True, exist_ok=True)
32
+ if p.exists() and not lock_held(root):
33
+ try:
34
+ p.unlink()
35
+ except OSError:
36
+ return False
37
+ try:
38
+ fd = os.open(p, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
39
+ except OSError:
40
+ return False
41
+ with os.fdopen(fd, "w") as f:
42
+ f.write(str(os.getpid()))
43
+ return True
44
+
45
+
46
+ def main(argv: list[str]) -> int:
47
+ if not argv:
48
+ return 0
49
+ root = Path(argv[0]).resolve()
50
+ if not acquire(root):
51
+ return 0
52
+ t0 = time.perf_counter()
53
+ from ccr.hooks.common import log
54
+ try:
55
+ from ccr.graph import update
56
+ r = update(root, offline=True, workers=1)
57
+ log(root, f"bg graph refresh: parsed {r.parsed}, removed {r.removed} in "
58
+ f"{(time.perf_counter() - t0) * 1000:.0f}ms")
59
+ except Exception as e: # noqa: BLE001
60
+ log(root, f"bg graph refresh failed: {e.__class__.__name__}: {e}")
61
+ finally:
62
+ with contextlib.suppress(OSError):
63
+ lock_path(root).unlink()
64
+ return 0
65
+
66
+
67
+ if __name__ == "__main__":
68
+ raise SystemExit(main(sys.argv[1:]))
ccr/hooks/common.py ADDED
@@ -0,0 +1,159 @@
1
+ """Shared helpers for hooks and the status line: stdlib only, nothing slow at import."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import re
7
+ import time
8
+ from pathlib import Path
9
+
10
+ MAX_STDIN = 4 * 1024 * 1024
11
+ LOG_MAX = 512 * 1024
12
+ SESSION_TTL_S = 7 * 86400
13
+ _SID = re.compile(r"[^A-Za-z0-9_.-]")
14
+ MODEL_RANK = (("haiku", 0), ("sonnet", 1), ("opus", 2), ("fable", 3))
15
+ EFFORT_RANK = {"low": 0, "medium": 1, "high": 2, "xhigh": 3, "max": 4}
16
+
17
+
18
+ def parse_stdin(raw: bytes | str | None) -> dict | None:
19
+ if raw is None:
20
+ return None
21
+ if isinstance(raw, bytes):
22
+ raw = raw.decode("utf-8", errors="replace")
23
+ try:
24
+ data = json.loads(raw)
25
+ except ValueError:
26
+ return None
27
+ return data if isinstance(data, dict) else None
28
+
29
+
30
+ def find_root(data: dict | None, environ=None) -> Path | None:
31
+ """Nearest directory holding `.ccr/` above CLAUDE_PROJECT_DIR or the hook's cwd."""
32
+ env = os.environ if environ is None else environ
33
+ starts = []
34
+ for v in (env.get("CLAUDE_PROJECT_DIR"),
35
+ (data or {}).get("cwd") if isinstance(data, dict) else None):
36
+ if isinstance(v, str) and v:
37
+ starts.append(v)
38
+ ws = (data or {}).get("workspace") if isinstance(data, dict) else None
39
+ if isinstance(ws, dict):
40
+ for k in ("project_dir", "current_dir"):
41
+ if isinstance(ws.get(k), str) and ws[k]:
42
+ starts.append(ws[k])
43
+ home = Path.home()
44
+ for s in starts:
45
+ p = Path(s)
46
+ for cand in (p, *p.parents):
47
+ if (cand / ".ccr").is_dir():
48
+ return cand
49
+ if cand == home:
50
+ break
51
+ return None
52
+
53
+
54
+ def local_dir(root: Path) -> Path:
55
+ d = root / ".ccr" / "local"
56
+ d.mkdir(parents=True, exist_ok=True)
57
+ return d
58
+
59
+
60
+ def read_json(path: Path) -> dict:
61
+ try:
62
+ with open(path, encoding="utf-8") as f:
63
+ data = json.load(f)
64
+ return data if isinstance(data, dict) else {}
65
+ except (OSError, ValueError):
66
+ return {}
67
+
68
+
69
+ def write_json_atomic(path: Path, obj: dict) -> None:
70
+ path.parent.mkdir(parents=True, exist_ok=True)
71
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
72
+ with open(tmp, "w", encoding="utf-8") as f:
73
+ json.dump(obj, f, separators=(",", ":"))
74
+ os.replace(tmp, path)
75
+
76
+
77
+ def session_path(root: Path, sid: str) -> Path:
78
+ return root / ".ccr" / "local" / "sessions" / (_SID.sub("_", sid)[:128] + ".json")
79
+
80
+
81
+ def load_session(root: Path, sid: str | None) -> dict:
82
+ return read_json(session_path(root, sid)) if sid else {}
83
+
84
+
85
+ def save_session(root: Path, sid: str | None, data: dict) -> None:
86
+ if sid:
87
+ data["updated"] = time.time()
88
+ write_json_atomic(session_path(root, sid), data)
89
+
90
+
91
+ def log(root: Path | None, line: str) -> None:
92
+ """Append one line to .ccr/local/hooks.log (bounded). Never raises."""
93
+ if root is None:
94
+ return
95
+ try:
96
+ p = local_dir(root) / "hooks.log"
97
+ try:
98
+ if p.stat().st_size > LOG_MAX:
99
+ keep = p.read_bytes()[-LOG_MAX // 2:]
100
+ p.write_bytes(keep[keep.find(b"\n") + 1:])
101
+ except OSError:
102
+ pass
103
+ with open(p, "a", encoding="utf-8") as f:
104
+ f.write(time.strftime("%Y-%m-%dT%H:%M:%S ") + line.replace("\n", " ") + "\n")
105
+ except Exception:
106
+ pass
107
+
108
+
109
+ def model_rank(model: str | None) -> int | None:
110
+ if not isinstance(model, str):
111
+ return None
112
+ m = model.lower()
113
+ for name, r in MODEL_RANK:
114
+ if name in m:
115
+ return r
116
+ return None
117
+
118
+
119
+ def model_alias(model: str | None) -> str | None:
120
+ r = model_rank(model)
121
+ return None if r is None else MODEL_RANK[r][0]
122
+
123
+
124
+ def effort_level(v) -> str | None:
125
+ if isinstance(v, dict):
126
+ v = v.get("level")
127
+ return v if isinstance(v, str) and v in EFFORT_RANK else None
128
+
129
+
130
+ class Msg(str):
131
+ """Model-facing hook text that also carries a short user-facing line (`.ui`)."""
132
+ ui: str | None = None
133
+
134
+ def __new__(cls, text: str, ui: str | None = None):
135
+ o = super().__new__(cls, text)
136
+ o.ui = ui
137
+ return o
138
+
139
+
140
+ def main_model(root: Path, sid: str | None, session: dict) -> tuple[str | None, str | None]:
141
+ """(model id, effort) of the main session: the freshest of the status line relay
142
+ (per session), SessionStart's `model` and the last model seen in the transcript."""
143
+ cands = []
144
+ st = read_json(root / ".ccr" / "local" / "state.json")
145
+ sess = (st.get("sessions") or {}).get(sid) if sid and isinstance(st.get("sessions"),
146
+ dict) else None
147
+ if isinstance(sess, dict) and sess.get("model"):
148
+ cands.append((float(sess.get("ts") or 0), sess.get("model"), sess.get("effort")))
149
+ elif not sid and isinstance(st.get("model"), dict) and st["model"].get("id"):
150
+ cands.append((float(st.get("ts") or 0), st["model"]["id"], effort_level(st.get("effort"))))
151
+ mm = session.get("main_model")
152
+ if isinstance(mm, dict) and mm.get("id"):
153
+ cands.append((float(mm.get("ts") or 0), mm["id"], mm.get("effort")))
154
+ if not cands:
155
+ return None, None
156
+ cands.sort(key=lambda c: c[0])
157
+ model = cands[-1][1]
158
+ effort = next((c[2] for c in reversed(cands) if c[2]), None)
159
+ return model, effort
ccr/hooks/prompt.py ADDED
@@ -0,0 +1,322 @@
1
+ """UserPromptSubmit: route the prompt with decide() (rules only, never an LLM) and inject one
2
+ `ccr:` line of context, e.g.
3
+
4
+ ccr: T2 (sonnet/medium) — touches 6 files in billing/, 14 dependents, tests present.
5
+ Delegate implementation to ccr-implement; use Explore (haiku) for search.
6
+
7
+ Silent for: `!noroute` anywhere in the prompt (a leading `!` is bash mode in the interactive
8
+ CLI, so a trailing `!noroute` is the practical form), slash commands, synthetic user turns
9
+ such as `<task-notification>` (a background subagent finishing), short chatter
10
+ ("thanks", "yes go on"), `hooks.route_prompts: false`, a corrupt graph or config.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import posixpath
16
+ import re
17
+ import time
18
+
19
+ from ccr.hooks.common import (EFFORT_RANK, Msg, effort_level, load_session, log, main_model,
20
+ model_alias, model_rank, save_session)
21
+ from ccr.hooks.tasks import finalize, infer_outcome, is_retry, start
22
+
23
+ NOROUTE = re.compile(r"(?:^|\s)!noroute\b", re.I)
24
+ # Messages Claude Code injects as user turns (background task results, slash command
25
+ # echoes, bash-mode output): `<task-notification>`, `<command-name>`, `<bash-stdout>`, ...
26
+ SYNTHETIC = re.compile(r"^\s*<(?:task-notification|system-reminder|[a-z]+(?:-[a-z]+)+)[\s>]")
27
+ MAX_EVAL_CHARS = 8000
28
+ CHANGE_KINDS = {"trivial", "tests", "bugfix", "feature", "refactor", "perf", "migration",
29
+ "security"}
30
+
31
+
32
+ CHATTER_MAX_WORDS = 4
33
+ RETRY_REUSE_WORDS = 8 # a short retry ("still failing") keeps the previous facts
34
+ CHATTER_MAX_CONFIDENCE = 0.3
35
+
36
+
37
+ def is_chatter(prompt: str, d) -> bool:
38
+ """Short follow-ups with nothing to route on ("thanks", "yes go ahead", "fix it")."""
39
+ if len(prompt.split()) > CHATTER_MAX_WORDS or d.location.candidates or \
40
+ d.risk.critical_terms:
41
+ return False
42
+ return (d.task_class.kind in ("question", "trivial")
43
+ or d.confidence < CHATTER_MAX_CONFIDENCE)
44
+
45
+
46
+ def facts(d) -> str:
47
+ prim = d.location.primary()
48
+ parts = []
49
+ if prim:
50
+ paths = [c.path for c in prim]
51
+ if len(paths) <= 2:
52
+ parts.append("touches " + " and ".join(paths))
53
+ else:
54
+ dirs = [posixpath.dirname(p) for p in paths]
55
+ common = posixpath.commonpath(dirs) if all(dirs) else ""
56
+ parts.append(f"touches {len(paths)} files" + (f" in {common}/" if common else ""))
57
+ else:
58
+ parts.append("no specific files located")
59
+ r = d.risk
60
+ if r.dependents:
61
+ parts.append(f"{r.dependents} dependent{'s' if r.dependents != 1 else ''}")
62
+ if r.tests == "direct":
63
+ parts.append("tests present")
64
+ elif r.tests == "name-matched":
65
+ parts.append("only name-matched tests")
66
+ elif r.tests == "none":
67
+ parts.append("no tests found")
68
+ if r.critical_groups:
69
+ parts.append("critical path: " + "/".join(r.critical_groups))
70
+ kinds = sorted({f.kind for f in r.memory_flags})
71
+ if kinds:
72
+ parts.append("memory flags: " + "/".join(kinds))
73
+ if r.level == "high":
74
+ parts.append(f"risk high ({r.score:.2f})")
75
+ return ", ".join(parts)
76
+
77
+
78
+ def ui_line(d, tier, kind: str, fact: str, retry: bool) -> str:
79
+ """Short user-facing summary, e.g. `ccr → T2 sonnet/medium · ccr-implement · 2 files, risk high`."""
80
+ prim = d.location.primary()
81
+ bits = []
82
+ if prim:
83
+ bits.append(f"{len(prim)} file{'s' if len(prim) != 1 else ''}")
84
+ if d.risk.level != "low":
85
+ bits.append(f"risk {d.risk.level}")
86
+ if retry:
87
+ bits.append("retry")
88
+ tail = f" · {', '.join(bits)}" if bits else f" · {kind}"
89
+ return f"ccr → {tier.name} {tier.model}/{tier.effort} · {tier.agent}{tail}"
90
+
91
+
92
+ def iterative_reason(d, retry: bool) -> str | None:
93
+ tc = d.task_class
94
+ if retry:
95
+ return "a retry"
96
+ if tc.kind == "debugging":
97
+ return "debugging"
98
+ if tc.vague:
99
+ return "a vague request"
100
+ if tc.kind == "question" and tc.scope == "large":
101
+ return "a broad design question"
102
+ return None
103
+
104
+
105
+ def advice(d, tier, main: str | None, main_effort: str | None, why_iter: str | None,
106
+ cfg) -> str:
107
+ kind = d.task_class.kind
108
+ mr, tr = model_rank(main), model_rank(tier.model)
109
+ eff_ok = EFFORT_RANK.get(main_effort or "", -1) >= EFFORT_RANK.get(tier.effort, 0)
110
+ same = mr is not None and mr == tr and eff_ok
111
+ search = "use Explore (haiku) for search."
112
+ if tier.name == "T0" and kind == "question":
113
+ out = f"Answer directly; {search}"
114
+ elif same:
115
+ out = (f"Main session already runs {model_alias(main)}/{main_effort}: handle it "
116
+ f"directly; {search}")
117
+ else:
118
+ verb = ("Delegate implementation to" if kind in CHANGE_KINDS else
119
+ "Delegate the investigation to" if kind == "debugging" else "Delegate to")
120
+ out = f"{verb} {tier.agent}; {search}"
121
+ if tier.name == "T4":
122
+ out += " Review its diff before accepting."
123
+ if why_iter and mr is not None and tr is not None and mr < tr and \
124
+ cfg["hooks"]["model_advice"]:
125
+ out += (f" This looks iterative ({why_iter}) and the main model is "
126
+ f"{model_alias(main)}: consider `/model {model_alias(tier.model) or tier.model}`"
127
+ f" for this conversation, then `/model {model_alias(main)}` afterwards.")
128
+ return out
129
+
130
+
131
+ def _retry(d, cfg, pending: dict, session: dict, prompt: str, kind: str, area: str, fact: str):
132
+ """A retry escalates one tier above the failed attempt (within the ceiling)."""
133
+ from ccr.config import TIERS, TOP
134
+ prev = pending.get("tier")
135
+ p = TIERS.index(prev) if prev in TIERS else 0
136
+ ceiling = TOP if (d.t4_rules or d.risk.critical) else \
137
+ TIERS.index(cfg["routing"]["ceiling_without_critical"])
138
+ own = 0 if d.reclassed else d.tier.index # "still failing" names no code: not debugging
139
+ new = max(own, min(p + 1, ceiling))
140
+ tier = cfg.tier(new)
141
+ if pending.get("class"):
142
+ kind = pending["class"]
143
+ if pending.get("area") and area == "*":
144
+ area = pending["area"]
145
+ if session.get("facts") and (not d.location.candidates
146
+ or len(prompt.split()) <= RETRY_REUSE_WORDS):
147
+ fact = session["facts"]
148
+ note = (f"Previous attempt ({prev}) did not work: escalated to {tier.name}."
149
+ if new > p else f"Previous attempt ({prev}) did not work and it is "
150
+ f"already the ceiling: re-plan before retrying.")
151
+ return tier, prev, kind, area, fact, [note]
152
+
153
+
154
+ REWORK = re.compile(
155
+ r"\b(?:not\s+quite|not\s+what\s+i|i\s+meant|i\s+said|instead|rather\s+than|actually|"
156
+ r"wrong\s+(?:file|function|place|approach)|you\s+(?:missed|forgot|broke|removed|changed)|"
157
+ r"too\s+(?:shallow|simple|basic|vague)|redo|do\s+it\s+properly|start\s+again|"
158
+ r"that'?s\s+not\s+(?:it|right|what))\b", re.I)
159
+
160
+
161
+ def escalation_signals(prompt: str, pending: dict, session: dict, d, main, cfg,
162
+ now: float | None = None) -> list[str]:
163
+ """Signs that the previous task's answer fell short without a "still failing" phrase:
164
+ manual_model_up you moved the main session to a stronger model before this prompt, and
165
+ this prompt is about the same code or leans on the last answer
166
+ possible_rework a dissatisfied reply ("not quite", "I meant", "you missed") about the same
167
+ code within hooks.rework_minutes of the last activity"""
168
+ paths = {c.path for c in d.location.candidates}
169
+ same = bool(paths & set(session.get("files") or ())) or (
170
+ d.area not in ("*", "") and d.area == pending.get("area"))
171
+ sig = []
172
+ old, new = model_rank(pending.get("main_model")), model_rank(main)
173
+ if old is not None and new is not None and new > old and (same or is_followup(prompt, d)):
174
+ sig.append("manual_model_up")
175
+ task = session.get("task") if isinstance(session.get("task"), dict) else {}
176
+ last = float(task.get("last_ts") or pending.get("ts") or 0)
177
+ window = int(cfg["hooks"]["rework_minutes"]) * 60
178
+ if same and REWORK.search(prompt[:300]) and last and (now or time.time()) - last <= window:
179
+ sig.append("possible_rework")
180
+ return sig
181
+
182
+
183
+ def _record(root, sid, tp, session: dict, pending, d, tier, kind: str, area: str, fact: str,
184
+ retry: bool, escalated_from, main, outcome: str | None, prompt: str = "",
185
+ cfg=None) -> None:
186
+ """Close the previous task and start tracking this one in the session file."""
187
+ from ccr.config import TIERS
188
+ if tp:
189
+ session["transcript"] = tp
190
+ if "offset" not in session: # first task here: earlier usage is not ours
191
+ try:
192
+ session["offset"] = os.path.getsize(tp)
193
+ except OSError:
194
+ session["offset"] = 0
195
+ if pending is not None and cfg is not None and not retry:
196
+ sig = escalation_signals(prompt, pending, session, d, main, cfg)
197
+ if sig:
198
+ task = session.setdefault("task", {})
199
+ task["signals"] = sorted(set(task.get("signals") or []) | set(sig))
200
+ if pending is not None: # absorbs the transcript tail, then records it
201
+ if retry and escalated_from in TIERS and tier.index > TIERS.index(escalated_from):
202
+ pending["escalated_to"] = tier.name
203
+ finalize(root, sid, session, outcome)
204
+ start(session, {
205
+ "ts": int(time.time()), "class": kind, "area": area, "tier": tier.name,
206
+ "model": tier.model, "effort": tier.effort, "risk": d.risk.score,
207
+ "confidence": d.confidence, "source": "hook", "escalated_from": escalated_from,
208
+ "main_model": model_alias(main), "trace": d.trace()})
209
+ session["facts"] = fact
210
+ if d.location.candidates:
211
+ session["files"] = [c.path for c in d.location.candidates[:3]]
212
+ save_session(root, sid, session)
213
+
214
+
215
+ ANAPHORA = re.compile(r"\b(?:that|it|this|those|them|these|the\s+same|same\s+(?:for|here|thing|way)|"
216
+ r"too|also|as\s+well|again|the\s+other|next|another\s+one)\b", re.I)
217
+ FOLLOWUP_MAX_WORDS = 6
218
+ FOLLOWUP_MAX_CONFIDENCE = 0.35
219
+
220
+
221
+ def is_followup(prompt: str, d) -> bool:
222
+ """A reply that leans on the conversation ("do the same for refunds", "make it stricter",
223
+ "the header row is wrong") rather than carrying its own anchor in the code."""
224
+ words = len(prompt.split())
225
+ return bool(ANAPHORA.search(prompt)) and words <= 12 or words <= FOLLOWUP_MAX_WORDS \
226
+ and not d.location.located
227
+
228
+
229
+ def _follow_up(prompt: str, d, pending: dict, session: dict, root, cfg, graph_kw: dict):
230
+ """Give a follow-up the previous task's context: its files for locating, and (when the
231
+ follow-up itself says little about the kind of work) its class and tier."""
232
+ from ccr.route import decide
233
+ note = None
234
+ files = [f for f in session.get("files") or [] if isinstance(f, str)]
235
+ if files and not d.location.located:
236
+ d = decide(prompt[:MAX_EVAL_CHARS] + "\n" + " ".join(files), root, cfg=cfg, **graph_kw)
237
+ note = "uses the files from the previous task"
238
+ inherit = None
239
+ if d.task_class.confidence < FOLLOWUP_MAX_CONFIDENCE and pending.get("tier") \
240
+ and pending.get("class") in CHANGE_KINDS:
241
+ inherit = pending
242
+ note = f"continues the previous {pending['class']} task at {pending['tier']}"
243
+ return d, inherit, note
244
+
245
+
246
+ def _decide(prompt, root, cfg, g, tp, session, pending, retry):
247
+ """decide() for the prompt, plus the previous task's context for a follow-up."""
248
+ from ccr.route import decide
249
+ inherit = note = None
250
+ try:
251
+ d = decide(prompt[:MAX_EVAL_CHARS], root, cfg=cfg, graph=g, transcript_path=tp)
252
+ if pending is not None and not retry and is_followup(prompt, d) \
253
+ and not is_chatter(prompt, d):
254
+ d, inherit, note = _follow_up(prompt, d, pending, session, root, cfg,
255
+ {"graph": g, "transcript_path": tp})
256
+ finally:
257
+ if g is not None:
258
+ g.close()
259
+ return d, inherit, note
260
+
261
+
262
+ def run(data: dict, root, cfg) -> str | None:
263
+ if not cfg["hooks"]["route_prompts"]:
264
+ return None
265
+ prompt = data.get("prompt")
266
+ if not isinstance(prompt, str) or not prompt.strip():
267
+ return None
268
+ if NOROUTE.search(prompt) or prompt.lstrip().startswith("/") or SYNTHETIC.match(prompt):
269
+ return None # also leaves the pending task untouched
270
+ sid = data.get("session_id") if isinstance(data.get("session_id"), str) else None
271
+ tp = data.get("transcript_path") if isinstance(data.get("transcript_path"), str) else None
272
+
273
+ from ccr.graph.db import db_path
274
+ from ccr.graph.query import Graph
275
+ g = Graph.open(root)
276
+ if g is None and db_path(root).exists():
277
+ return None # unreadable graph: fail open, doctor reports it
278
+ session = load_session(root, sid)
279
+ pending = session.get("pending") if isinstance(session.get("pending"), dict) else None
280
+ retry = pending is not None and is_retry(prompt)
281
+ d, inherit, follow_note = _decide(prompt, root, cfg, g, tp, session, pending, retry)
282
+
283
+ if not retry and is_chatter(prompt, d):
284
+ return None # "thanks", "yes go on": the current task continues
285
+
286
+ kind, area, fact = d.task_class.kind, d.area, facts(d)
287
+ tier, escalated_from, notes = d.tier, None, []
288
+ if inherit is not None:
289
+ tier, kind = cfg.tier(inherit["tier"]), inherit["class"]
290
+ if inherit.get("area") and area == "*":
291
+ area = inherit["area"]
292
+ fact = session.get("facts") or fact
293
+ if follow_note:
294
+ notes.append(f"Follow-up: {follow_note}.")
295
+ if retry:
296
+ tier, escalated_from, kind, area, fact, notes = _retry(
297
+ d, cfg, pending, session, prompt, kind, area, fact)
298
+ if d.budget.pressure and not retry:
299
+ notes.append(f"Weekly usage {d.budget.used_pct:.0f}%: tier lowered to save quota.")
300
+ if d.confidence < float(cfg["llm"]["threshold"]) and not retry and tier.index < len(cfg.tiers) - 1:
301
+ notes.append("Low routing confidence: escalate one tier if this falls short.")
302
+
303
+ main, main_effort = main_model(root, sid, session)
304
+ main_effort = (main_effort or effort_level(data.get("effort"))
305
+ or effort_level(os.environ.get("CLAUDE_EFFORT")))
306
+ text = (f"ccr: {tier.name} ({tier.model}/{tier.effort}) — {fact}. "
307
+ + advice(d, tier, main, main_effort, iterative_reason(d, retry), cfg))
308
+ if notes:
309
+ text += " " + " ".join(notes)
310
+
311
+ try: # bookkeeping is best effort: the routing line is still worth emitting
312
+ outcome = infer_outcome(prompt, session, cfg) if pending is not None else None
313
+ _record(root, sid, tp, session, pending, d, tier, kind, area, fact, retry,
314
+ escalated_from, main, outcome, prompt, cfg)
315
+ if cfg["hooks"]["store_prompts"] and isinstance(session.get("pending"), dict):
316
+ from ccr.history import prompts
317
+ prompts.append(root, prompts.snapshot(
318
+ session["pending"]["id"], prompt, d, tier, fact, notes, retry, escalated_from,
319
+ cfg["hooks"]["redact_prompts"]))
320
+ except Exception as e: # noqa: BLE001
321
+ log(root, f"prompt bookkeeping failed: {e.__class__.__name__}: {e}")
322
+ return Msg(text, ui_line(d, tier, kind, fact, retry))