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/route/__init__.py ADDED
@@ -0,0 +1,527 @@
1
+ """Routing: task class + located code + risk + history + budget -> tier T0..T4, with reasons.
2
+
3
+ Policy (all thresholds in .ccr/config.yaml):
4
+ * start from the class base tier (question/trivial T0 ... migration/security/debugging T3);
5
+ * adjustments: large scope, vague bug report, high risk, critical path, memory flags push up;
6
+ small scope pushes down. Ups and downs each count once, and escalation above the base is
7
+ capped at `routing.max_escalation` (2) tiers (the second only when 3+ signals agree);
8
+ * history: repeated failures at the chosen tier push up (within the cap); consistent
9
+ success one tier lower pushes down;
10
+ * without a T4 rule the tier never exceeds `routing.ceiling_without_critical` (T3);
11
+ * T4 rules (critical path) may jump straight to T4;
12
+ * budget pressure moves non-critical tasks one tier down; critical / T4 tasks never move.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import time
17
+ from dataclasses import dataclass, field, replace
18
+ from pathlib import Path
19
+
20
+ from ccr.config import TIERS, TOP, Config, Tier, load_config
21
+ from ccr.evaluate.classify import TaskClass, classify
22
+ from ccr.evaluate.locate import Candidate, Location, locate
23
+ from ccr.evaluate.risk import Risk, assess_risk
24
+ from ccr.route.budget import Budget, budget_pressure
25
+
26
+ CHANGE = {"trivial", "tests", "bugfix", "feature", "refactor", "perf", "migration", "security",
27
+ "debugging"}
28
+ SUBSTANTIVE = (CHANGE - {"trivial"}) | {"design"} # design: plans and architecture, no edit
29
+ DEEP_COMPLEXITY = 0.6 # complexity component at which code counts as hard to change
30
+ UNSURE_CLASS = 0.4 # class confidence below this, with no cue words, is a guess
31
+ DEEP_SUPPORT = 0.4 # blast radius / missing-test level that makes complex code risky
32
+ _AUTO = object()
33
+
34
+
35
+ @dataclass
36
+ class Decision:
37
+ task_class: TaskClass
38
+ location: Location
39
+ risk: Risk
40
+ budget: Budget
41
+ tier: Tier
42
+ base: str
43
+ confidence: float
44
+ reasons: list[str] = field(default_factory=list)
45
+ t4_rules: list[str] = field(default_factory=list)
46
+ history: str = "no history"
47
+ llm: str = "not requested"
48
+ llm_used: bool = False
49
+ area: str = "*"
50
+ notes: list[str] = field(default_factory=list)
51
+ bumps: list[str] = field(default_factory=list) # names of the +1 signals that fired
52
+ elapsed_ms: float = 0.0
53
+ reclassed: bool = False # an unanchored bug report was routed as debugging
54
+
55
+ def record(self) -> dict:
56
+ """History fields for this decision (no prompt text)."""
57
+ return {"class": self.task_class.kind, "area": self.area, "tier": self.tier.name,
58
+ "model": self.tier.model, "effort": self.tier.effort,
59
+ "risk": self.risk.score, "confidence": self.confidence,
60
+ "source": "llm" if self.llm_used else "rules", "trace": self.trace()}
61
+
62
+ def trace(self) -> dict:
63
+ """Compact signals behind this decision, for tuning the rules from real data.
64
+ Numbers, flags and rule names only: no prompt text, no file paths."""
65
+ tc, r = self.task_class, self.risk
66
+ return {"base": self.base, "scope": tc.scope, "vagueness": tc.vagueness,
67
+ "steps": tc.steps, "class_conf": tc.confidence, "secondary": tc.secondary,
68
+ "class_source": tc.source, "destructive": bool(tc.destructive),
69
+ "hard": bool(tc.hard), "rules": tc.evidence_terms(), "hard_terms": tc.hard[:3],
70
+ "bumps": self.bumps, "located": self.location.located,
71
+ "loc_conf": self.location.confidence, "risk_level": r.level,
72
+ "code_risk": r.code_risk, "critical": r.critical_groups,
73
+ "memory_flags": sorted({f.kind for f in r.memory_flags}),
74
+ "t4": bool(self.t4_rules), "budget_pressure": bool(self.budget.pressure),
75
+ "elapsed_ms": round(self.elapsed_ms, 1)}
76
+
77
+ def to_dict(self) -> dict:
78
+ tc, loc, r, b = self.task_class, self.location, self.risk, self.budget
79
+ return {
80
+ "tier": self.tier.name, "model": self.tier.model, "effort": self.tier.effort,
81
+ "agent": self.tier.agent, "base": self.base, "confidence": self.confidence,
82
+ "class": {"kind": tc.kind, "confidence": tc.confidence, "source": tc.source,
83
+ "secondary": tc.secondary, "scope": tc.scope,
84
+ "steps": tc.steps, "vagueness": tc.vagueness, "evidence": tc.matched.get(tc.kind, []),
85
+ "destructive": tc.destructive, "hard": tc.hard},
86
+ "location": {"confidence": loc.confidence, "explicit": loc.explicit,
87
+ "mentioned": loc.mentioned, "unresolved": loc.unresolved,
88
+ "symbols": loc.symbols, "terms": loc.terms,
89
+ "memory_terms": loc.memory_terms, "graph": loc.graph,
90
+ "candidates": [{"path": c.path, "confidence": c.confidence,
91
+ "reasons": c.reasons} for c in loc.candidates[:15]]},
92
+ "risk": {"score": r.score, "level": r.level, "code_risk": r.code_risk,
93
+ "components": {n: {"value": c.value, "detail": c.detail}
94
+ for n, c in r.components.items()},
95
+ "critical_groups": r.critical_groups, "critical_files": r.critical_files,
96
+ "critical_terms": r.critical_terms,
97
+ "memory_flags": [{"kind": f.kind, "term": f.term, "path": f.path}
98
+ for f in r.memory_flags]},
99
+ "budget": {"used_pct": b.used_pct, "source": b.source, "pressure": b.pressure,
100
+ "soft_limit_pct": b.soft_limit_pct, "detail": b.detail},
101
+ "history": self.history, "llm": self.llm, "t4_rules": self.t4_rules,
102
+ "area": self.area, "reasons": self.reasons, "notes": self.notes,
103
+ "elapsed_ms": round(self.elapsed_ms, 1),
104
+ }
105
+
106
+
107
+ def overall_confidence(tc: TaskClass, loc: Location) -> float:
108
+ loc_factor = 0.85 + 0.15 * loc.confidence if tc.kind == "question" else 0.6 + 0.4 * loc.confidence
109
+ return round(tc.confidence * loc_factor * (1 - 0.35 * tc.vagueness), 3)
110
+
111
+
112
+ def decide(task: str, root: str | Path = ".", *, cfg: Config | None = None,
113
+ allow_llm: bool = False, llm_runner=None, graph=_AUTO, memory=_AUTO,
114
+ budget: Budget | None = None, history_records: list[dict] | None = None,
115
+ now: float | None = None, transcript_path: str | None = None,
116
+ budget_fallback=None, nested_memory: bool = True) -> Decision:
117
+ """Evaluate and route a task. Token-free unless `allow_llm` and rule confidence is low."""
118
+ t0 = time.perf_counter()
119
+ root = Path(root).resolve()
120
+ cfg = cfg or load_config(root)
121
+ now = time.time() if now is None else now
122
+ notes = [f"config: {e}" for e in cfg.errors]
123
+ own_graph = None
124
+ if graph is _AUTO:
125
+ from ccr.graph import Graph
126
+ own_graph = graph = Graph.open(root)
127
+ if memory is _AUTO:
128
+ from ccr.memory import collect
129
+ memory = collect(root, nested=nested_memory)
130
+ try:
131
+ loc = locate(task, root, graph, memory)
132
+ tc = classify(task, located=loc.located, hard_terms=cfg["hard_terms"])
133
+ risk = assess_risk(loc, task, cfg, graph, memory)
134
+ conf = overall_confidence(tc, loc)
135
+ llm_status, llm_used = "not requested", False
136
+ threshold = float(cfg["llm"]["threshold"])
137
+ if allow_llm and conf < threshold:
138
+ from ccr.evaluate import llm as L
139
+ guess = f"{tc.kind} (confidence {tc.confidence:.2f}), scope {tc.scope}"
140
+ hint, status = L.assist(task, L.graph_summary(root, graph, loc), guess,
141
+ model=cfg["llm"]["model"], effort=cfg["llm"]["effort"],
142
+ timeout=float(cfg["llm"]["timeout_s"]), runner=llm_runner)
143
+ llm_status = status
144
+ if hint is not None:
145
+ llm_used = True
146
+ changes = _apply_hint(hint, tc, loc, root, graph)
147
+ risk = assess_risk(loc, task, cfg, graph, memory)
148
+ if hint.confidence is not None:
149
+ conf = round(max(conf, 0.9 * hint.confidence), 3)
150
+ llm_status += ": " + (", ".join(changes) or "agreed with rules") + (
151
+ f" ({hint.reason})" if hint.reason else "") + (
152
+ f" [~${hint.cost_usd:.4f}]" if hint.cost_usd is not None else "")
153
+ elif allow_llm:
154
+ llm_status = f"not needed (confidence {conf:.2f} >= {threshold:.2f})"
155
+ elif conf < threshold:
156
+ llm_status = (f"off (confidence {conf:.2f} < {threshold:.2f}; "
157
+ f"`ccr explain --llm` would ask haiku)")
158
+ if budget is None:
159
+ budget = budget_pressure(root, cfg, now=now, fallback=budget_fallback,
160
+ transcript_path=transcript_path)
161
+ if history_records is None:
162
+ from ccr import history as H
163
+ history_records = H.read(root, window_days=cfg["history"]["window_days"], now=now)
164
+ d = _route(tc, loc, risk, budget, history_records, cfg, conf)
165
+ d.llm, d.llm_used = llm_status, llm_used
166
+ d.notes = notes + loc.notes + risk.notes
167
+ d.elapsed_ms = (time.perf_counter() - t0) * 1000
168
+ return d
169
+ finally:
170
+ if own_graph is not None:
171
+ own_graph.close()
172
+
173
+
174
+ def _apply_hint(hint, tc: TaskClass, loc: Location, root: Path, graph) -> list[str]:
175
+ changes = []
176
+ if hint.kind and hint.kind != tc.kind:
177
+ changes.append(f"class {tc.kind} -> {hint.kind}")
178
+ tc.kind = hint.kind
179
+ tc.source = "llm"
180
+ if hint.scope:
181
+ new_scope = {"small": "small", "medium": "unspecified", "large": "large"}[hint.scope]
182
+ if new_scope != tc.scope:
183
+ changes.append(f"scope {tc.scope} -> {hint.scope}")
184
+ tc.scope = new_scope
185
+ if hint.vague is not None:
186
+ nv = max(tc.vagueness, 0.6) if hint.vague else min(tc.vagueness, 0.3)
187
+ if (nv >= 0.6) != tc.vague:
188
+ changes.append("vague" if hint.vague else "not vague")
189
+ tc.vagueness = nv
190
+ known = {c.path: c for c in loc.candidates}
191
+ added = []
192
+ for f in hint.files:
193
+ exists = (graph is not None and graph.file_row(f) is not None) or (root / f).is_file()
194
+ if not exists:
195
+ continue
196
+ if f in known:
197
+ c = known[f]
198
+ c.confidence = round(1 - (1 - c.confidence) * 0.4, 3)
199
+ c.reasons.append("suggested by LLM")
200
+ else:
201
+ indexed = graph is not None and graph.file_row(f) is not None
202
+ loc.candidates.append(Candidate(f, 0.6, ["suggested by LLM"], indexed))
203
+ added.append(f)
204
+ if added:
205
+ changes.append("files +" + ", ".join(added[:3]))
206
+ loc.candidates.sort(key=lambda c: (-c.confidence, len(c.path), c.path))
207
+ if loc.candidates and loc.confidence < loc.candidates[0].confidence:
208
+ loc.confidence = loc.candidates[0].confidence
209
+ return changes
210
+
211
+
212
+ def _deep_code(risk: Risk) -> str | None:
213
+ """Why the located code is hard to change safely, or None. Needs complex code plus
214
+ either many dependents or weak test coverage."""
215
+ c = risk.components
216
+ cx, br, tp = (c[n].value if n in c else 0.0
217
+ for n in ("complexity", "blast_radius", "test_proximity"))
218
+ if cx < DEEP_COMPLEXITY or (br < DEEP_SUPPORT and tp < DEEP_SUPPORT):
219
+ return None
220
+ why = [f"complexity {cx:.2f}"]
221
+ if br >= DEEP_SUPPORT:
222
+ why.append(f"blast radius {br:.2f}")
223
+ if tp >= DEEP_SUPPORT:
224
+ why.append("weak tests")
225
+ return ", ".join(why)
226
+
227
+
228
+ def _impactful(risk: Risk) -> str | None:
229
+ """Why the located code is costly to get wrong (complex or widely depended on)."""
230
+ c = risk.components
231
+ cx, br = (c[n].value if n in c else 0.0 for n in ("complexity", "blast_radius"))
232
+ if cx >= DEEP_COMPLEXITY:
233
+ return f"complexity {cx:.2f}"
234
+ if br >= DEEP_SUPPORT:
235
+ return f"blast radius {br:.2f}"
236
+ return None
237
+
238
+
239
+ _NO_DOWN = {"migration", "security", "debugging"}
240
+ _CRITICAL_UP = ("critical path", "memory flags")
241
+ _WORDING_UP = ("hard problem", "vague bug", "large scope")
242
+ _SWEEPING_UP = "sweeping change"
243
+
244
+
245
+ def _scope_label(tc: TaskClass) -> str:
246
+ return ", ".join(tc.scope_terms[:3]) or "LLM"
247
+
248
+
249
+ # Each signal rule inspects the task and returns a reason string when it applies. New rules
250
+ # are added to _UP_RULES / _DOWN_RULES; _signals and _route do not change. Order is the order
251
+ # reasons are reported in.
252
+
253
+ def _up_large_scope(tc, loc, risk):
254
+ if tc.scope == "large":
255
+ return f"large scope ({_scope_label(tc)})"
256
+
257
+
258
+ VAGUE_BUG_WORDS = 8 # a short bug report that names no file or function
259
+
260
+
261
+ def _up_vague_bug(tc, loc, risk):
262
+ bare = len(tc.scope_terms) == 0 and not (loc.explicit or loc.symbols or tc.steps) \
263
+ and tc.words <= VAGUE_BUG_WORDS
264
+ if tc.kind == "bugfix" and (tc.vague or bare):
265
+ why = (f"vagueness {tc.vagueness:.2f}" if tc.vague else "names no file or function")
266
+ return f"vague bug report ({why}): needs exploration"
267
+
268
+
269
+ def _up_sweeping(tc, loc, risk):
270
+ if tc.sweeping and tc.kind in ("refactor", "migration", "feature", "perf"):
271
+ return f"sweeping change ({', '.join(tc.sweeping[:2])}): needs a plan"
272
+
273
+
274
+ def _up_hard_problem(tc, loc, risk):
275
+ if tc.hard and tc.kind in ("perf", "bugfix"):
276
+ return f"hard problem ({', '.join(tc.hard[:2])})"
277
+
278
+
279
+ def _up_code_difficulty(tc, loc, risk):
280
+ kind = tc.kind
281
+ # the codebase decides how hard a bug is, whatever the wording: complex code that is
282
+ # widely depended on or untested needs a stronger model to diagnose safely
283
+ deep = _deep_code(risk) if kind in ("bugfix", "debugging", "perf") else None
284
+ if deep:
285
+ return f"complex code ({deep})"
286
+ if risk.level == "high" and kind in SUBSTANTIVE:
287
+ return f"risk high ({risk.score:.2f})"
288
+ if kind in SUBSTANTIVE and not tc.evidence_terms() and tc.confidence < UNSURE_CLASS \
289
+ and not tc.steps and loc.located and _impactful(risk):
290
+ # a terse prompt with no cue words says nothing about difficulty: let the code decide
291
+ return f"unclassified task on impactful code ({_impactful(risk)})"
292
+
293
+
294
+ def _up_critical_path(tc, loc, risk):
295
+ kind = tc.kind
296
+ if kind in SUBSTANTIVE and risk.critical or kind == "trivial" and risk.critical_located:
297
+ return f"critical path ({'/'.join(risk.critical_groups)})"
298
+
299
+
300
+ def _up_memory_flags(tc, loc, risk):
301
+ if tc.kind in CHANGE and risk.has_memory("critical", "protected", "fragile"):
302
+ kinds = sorted({f.kind for f in risk.memory_flags
303
+ if f.kind in ("critical", "protected", "fragile")})
304
+ return f"memory flags {'/'.join(kinds)} on {risk.memory_flags[0].path}"
305
+
306
+
307
+ def _down_small_scope(tc, loc, risk):
308
+ if tc.scope == "small" and tc.kind in SUBSTANTIVE - _NO_DOWN:
309
+ return f"small scope ({_scope_label(tc)})"
310
+
311
+
312
+ def _down_explicit_steps(tc, loc, risk):
313
+ if tc.steps and tc.kind in SUBSTANTIVE - _NO_DOWN and not tc.destructive:
314
+ return f"explicit step-by-step instructions ({tc.steps} steps)"
315
+
316
+
317
+ _UP_RULES = (_up_large_scope, _up_sweeping, _up_vague_bug, _up_hard_problem, _up_code_difficulty,
318
+ _up_critical_path, _up_memory_flags)
319
+ _DOWN_RULES = (_down_small_scope, _down_explicit_steps)
320
+
321
+
322
+ def _signals(tc: TaskClass, loc: Location, risk: Risk) -> tuple[list[str], list[str]]:
323
+ """The +1 signals (`ups`) and -1 signals (`downs`) that apply to this task."""
324
+ ups = [r for rule in _UP_RULES if (r := rule(tc, loc, risk))]
325
+ downs = [r for rule in _DOWN_RULES if (r := rule(tc, loc, risk))]
326
+ return ups, downs
327
+
328
+
329
+ _HALF = TIERS.index("T2H")
330
+
331
+
332
+ def _climb(tier: int, step: int) -> int:
333
+ """`tier` raised by `step` signals. T2H is a half step between T2 and T3: a single +1 from
334
+ T2 lands on it, but a +2 jumps over it so strong signals still reach the same tier as before."""
335
+ pos = tier + step
336
+ if step > 1 and tier < _HALF <= pos:
337
+ pos += 1
338
+ return pos
339
+
340
+
341
+ def _escalate(tier: int, ups: list[str], max_esc: int, reasons: list[str]) -> int:
342
+ if not ups:
343
+ return tier
344
+ if max_esc <= 0:
345
+ reasons.append("escalation disabled (routing.max_escalation 0): " + "; ".join(ups))
346
+ return tier
347
+ # one tier normally; two when three or more independent signals agree, or when a
348
+ # critical path meets a difficulty signal from the wording (a hard bug in auth code
349
+ # is not a T2 job). Risk and critical path both come from the code, so they don't
350
+ # count as two opinions.
351
+ crit = any(u.startswith(_CRITICAL_UP) for u in ups)
352
+ wording = any(u.startswith(_WORDING_UP) for u in ups)
353
+ sweeping = any(u.startswith(_SWEEPING_UP) for u in ups)
354
+ step = 2 if (len(ups) >= 3 or crit and wording or sweeping) and max_esc >= 2 else 1
355
+ reasons.append(f"+{step}: " + "; ".join(ups)
356
+ + (" (escalation capped at one tier)" if len(ups) > 1 and step == 1 else ""))
357
+ new = _climb(tier, step)
358
+ return new + 1 if crit and new == _HALF else new # a critical path never stops at T2H
359
+
360
+
361
+ def _descend(tier: int, downs: list[str], kind: str, critical_up: bool, reasons: list[str]) -> int:
362
+ if not downs:
363
+ return tier
364
+ text = "; ".join(downs)
365
+ if critical_up:
366
+ reasons.append(f"{text}: ignored on a critical path")
367
+ return tier
368
+ floor = 1 if kind in SUBSTANTIVE else 0
369
+ if tier - 1 >= floor:
370
+ reasons.append("-1: " + text)
371
+ return tier - 1
372
+ reasons.append(f"{text}: already at the {TIERS[floor]} floor for {kind}")
373
+ return tier
374
+
375
+
376
+ def _risk_note(kind: str, risk: Risk, ups: list[str], downs: list[str], reasons: list[str]) -> None:
377
+ if not ups and not downs:
378
+ if risk.level == "unknown":
379
+ reasons.append("risk unknown (no files located): no risk adjustment")
380
+ elif kind not in SUBSTANTIVE:
381
+ what = "read-only questions" if kind == "question" else "trivial edits"
382
+ reasons.append(f"risk {risk.level} ({risk.score:.2f}) does not move {what}")
383
+ else:
384
+ reasons.append(f"risk {risk.level} ({risk.score:.2f}): no adjustment")
385
+ elif risk.level in ("low", "medium") and not any(u.startswith("risk") for u in ups):
386
+ reasons.append(f"risk {risk.level} ({risk.score:.2f})")
387
+
388
+
389
+ # T4 rules: each returns a reason when the task must run at T4. Add a rule to _T4_RULES to
390
+ # extend the policy. A rule sees the reasons found so far (the production-migration rule
391
+ # only applies when no other rule fired).
392
+
393
+ def _t4_security(tc, risk, cfg, found):
394
+ if tc.kind == "security" and risk.critical:
395
+ return f"security change on a critical path ({'/'.join(risk.critical_groups)})"
396
+
397
+
398
+ def _t4_destructive_migration(tc, risk, cfg, found):
399
+ if tc.kind == "migration" and risk.critical and tc.destructive:
400
+ return (f"destructive migration ({', '.join(tc.destructive[:2])}) on "
401
+ f"{'/'.join(risk.critical_groups)}")
402
+
403
+
404
+ def _t4_memory_marked(tc, risk, cfg, found):
405
+ if tc.kind in SUBSTANTIVE - {"tests"} and risk.critical_located and \
406
+ risk.has_memory("critical", "protected"):
407
+ flag = next(f for f in risk.memory_flags if f.kind in ("critical", "protected"))
408
+ return f"memory marks {flag.path} {flag.kind} ('{flag.term}')"
409
+
410
+
411
+ def _t4_risky_critical_code(tc, risk, cfg, found):
412
+ if tc.kind in SUBSTANTIVE - {"tests"} and risk.critical_located and tc.scope != "small" and \
413
+ risk.code_risk >= cfg["risk"]["t4_code_risk"]:
414
+ return (f"critical path {'/'.join(risk.critical_groups)} with code risk "
415
+ f"{risk.code_risk:.2f}")
416
+
417
+
418
+ _WIPE = ("wipe", "purge", "truncat", "delete all", "delete every", "remove all", "remove every",
419
+ "erase", "clear all", "empty all", "drop")
420
+
421
+
422
+ def _t4_production_migration(tc, risk, cfg, found):
423
+ """Destroying data in production, whatever the task was classed as."""
424
+ prod = [t for t in tc.destructive if "prod" in t or "live" in t]
425
+ wipe = [t for t in tc.destructive if t.startswith(_WIPE)]
426
+ if tc.kind in SUBSTANTIVE - {"tests", "design"} and prod and (wipe or tc.kind == "migration") \
427
+ and not found:
428
+ return f"destructive change against production ({', '.join(tc.destructive[:2])})"
429
+
430
+
431
+ _T4_RULES = (_t4_security, _t4_destructive_migration, _t4_memory_marked,
432
+ _t4_risky_critical_code, _t4_production_migration)
433
+
434
+
435
+ def _t4_rules(tc: TaskClass, risk: Risk, cfg: Config) -> list[str]:
436
+ """Critical-path rules that jump straight to T4."""
437
+ found: list[str] = []
438
+ for rule in _T4_RULES:
439
+ reason = rule(tc, risk, cfg, found)
440
+ if reason:
441
+ found.append(reason)
442
+ return found
443
+
444
+
445
+ def _under_budget(tier: int, t4: list[str], risk: Risk, budget: Budget, reasons: list[str]) -> int:
446
+ if not budget.pressure:
447
+ return tier
448
+ if t4 or tier >= TOP:
449
+ reasons.append(f"budget pressure ({budget.used_pct:.0f}%): T4 is never downgraded")
450
+ elif risk.critical:
451
+ reasons.append(f"budget pressure ({budget.used_pct:.0f}%): critical path, no downgrade")
452
+ elif tier > 0:
453
+ reasons.append(f"-1: budget pressure (weekly {budget.used_pct:.0f}% >= "
454
+ f"{budget.soft_limit_pct:.0f}%)")
455
+ return tier - 1
456
+ else:
457
+ reasons.append("budget pressure: already at T0")
458
+ return tier
459
+
460
+
461
+ def _unanchored_bug(tc: TaskClass, loc: Location) -> TaskClass:
462
+ """A bug report that names no code we can find says nothing about where or why: treat it
463
+ as a debugging task (exploration first) instead of a routine fix."""
464
+ if tc.kind == "bugfix" and tc.source == "rules" and not loc.located and not tc.steps:
465
+ both = tc.matched.get("bugfix", []) + tc.matched.get("debugging", [])
466
+ return replace(tc, kind="debugging", matched={**tc.matched, "debugging": both})
467
+ return tc
468
+
469
+
470
+ def _route(tc: TaskClass, loc: Location, risk: Risk, budget: Budget, records: list[dict],
471
+ cfg: Config, conf: float) -> Decision:
472
+ reclassed = _unanchored_bug(tc, loc)
473
+ note = ["bug report names no code ccr can find: treated as debugging (explore first)"] \
474
+ if reclassed is not tc else []
475
+ tc = reclassed
476
+ kind = tc.kind
477
+ base_name = cfg["class_base"][kind]
478
+ base = TIERS.index(base_name)
479
+ max_esc = int(cfg["routing"]["max_escalation"])
480
+ ceiling = TIERS.index(cfg["routing"]["ceiling_without_critical"])
481
+ reasons = [f"base {base_name} for {kind}"
482
+ + (f" (matched {tc.evidence()})" if tc.evidence() else "")
483
+ + (" [class from LLM]" if tc.source == "llm" else "")] + note
484
+
485
+ ups, downs = _signals(tc, loc, risk)
486
+ critical_up = any(u.startswith(_CRITICAL_UP) for u in ups)
487
+ tier = _escalate(base, ups, max_esc, reasons)
488
+ tier = _descend(tier, downs, kind, critical_up, reasons)
489
+ _risk_note(kind, risk, ups, downs, reasons)
490
+
491
+ # history (learning loop, ccr/history/learn.py)
492
+ from ccr.history import learn
493
+ area = loc.top_area()
494
+ on_critical = critical_up or bool(risk.critical)
495
+ low_risk_simple = (not on_critical and tc.scope != "large" and not tc.vague
496
+ and not tc.hard and not risk.memory_flags
497
+ and (risk.level == "low"
498
+ or risk.level == "unknown" and kind not in SUBSTANTIVE))
499
+ learned = learn.adjust(tier, kind=kind, area=area, records=records, cfg=cfg,
500
+ cap=min(_climb(base, max_esc), ceiling),
501
+ floor=1 if kind in SUBSTANTIVE else 0, critical=on_critical,
502
+ low_risk_simple=low_risk_simple)
503
+ tier = learned.tier
504
+ if learned.reason:
505
+ reasons.append(learned.reason)
506
+
507
+ if tier > ceiling:
508
+ reasons.append(f"capped at {TIERS[ceiling]} (T4 needs a critical-path rule)")
509
+ tier = ceiling
510
+
511
+ t4 = _t4_rules(tc, risk, cfg)
512
+ if t4:
513
+ if tier < TOP:
514
+ reasons.append(f"T4 rule: {'; '.join(t4)} -> T4")
515
+ tier = TOP
516
+
517
+ tier = _under_budget(tier, t4, risk, budget, reasons)
518
+
519
+ if conf < float(cfg["llm"]["threshold"]) and tier < TOP:
520
+ reasons.append(f"low confidence ({conf:.2f}): starting low; escalate one tier "
521
+ f"if the result falls short")
522
+ t = cfg.tier(tier)
523
+ reasons.append(f"final {t.name}: {t.model}/{t.effort} via {t.agent}")
524
+ return Decision(task_class=tc, location=loc, risk=risk, budget=budget, tier=t,
525
+ base=base_name, confidence=conf, reasons=reasons, t4_rules=t4,
526
+ history=learned.note, area=area,
527
+ bumps=[u.split(" (")[0] for u in ups], reclassed=bool(note))