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/doctor.py ADDED
@@ -0,0 +1,208 @@
1
+ """Environment and project health checks behind `ccr doctor`. Each check returns
2
+ (level, message) pairs; level is OK / WARN / FAIL / INFO."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import subprocess
9
+ from pathlib import Path
10
+
11
+
12
+ def _doctor_claude(root: Path) -> list[tuple[str, str]]:
13
+ exe = shutil.which("claude")
14
+ if not exe:
15
+ return [("FAIL", "`claude` not found on PATH")]
16
+ try:
17
+ r = subprocess.run([exe, "--version"], capture_output=True, text=True, timeout=10)
18
+ except (OSError, subprocess.SubprocessError) as e:
19
+ return [("WARN", f"claude found at {exe} but --version failed: {e}")]
20
+ ver = (r.stdout or r.stderr).strip() or "unknown version"
21
+ return [("OK", f"claude found at {exe} ({ver})")]
22
+
23
+
24
+ def _doctor_effort_env(root: Path) -> list[tuple[str, str]]:
25
+ if os.environ.get("CLAUDE_CODE_EFFORT_LEVEL"):
26
+ return [("WARN", "CLAUDE_CODE_EFFORT_LEVEL is set; it overrides subagent effort. Unset it.")]
27
+ return [("OK", "CLAUDE_CODE_EFFORT_LEVEL not set")]
28
+
29
+
30
+ def _doctor_settings(root: Path) -> list[tuple[str, str]]:
31
+ settings = root / ".claude" / "settings.json"
32
+ if not settings.exists():
33
+ return [("INFO", ".claude/settings.json not present")]
34
+ try:
35
+ data = json.loads(settings.read_text(encoding="utf-8"))
36
+ if not isinstance(data, dict):
37
+ raise ValueError("top level is not an object")
38
+ except (ValueError, OSError) as e:
39
+ return [("FAIL", f".claude/settings.json is not valid JSON: {e}")]
40
+ out = [("OK", ".claude/settings.json is valid JSON")]
41
+ hooks = data.get("hooks")
42
+ if isinstance(hooks, dict) and hooks:
43
+ if "ccr" in json.dumps(hooks):
44
+ out.append(("OK", f"ccr hooks wired ({', '.join(hooks)})"))
45
+ else:
46
+ out.append(("WARN", "hooks present but none call ccr"))
47
+ else:
48
+ out.append(("INFO", "no hooks configured (run `ccr init`)"))
49
+ return out
50
+
51
+
52
+ def _doctor_privacy(root: Path) -> list[tuple[str, str]]:
53
+ from ccr.config import load_config
54
+ from ccr.history import prompts
55
+ cfg = load_config(root)
56
+ h = cfg["hooks"]
57
+ pp = prompts.path(root)
58
+ out: list[tuple[str, str]] = []
59
+ if h["store_prompts"]:
60
+ n = len(prompts.read(root))
61
+ keep = (f"kept {h['prompt_retention_days']} day(s)" if h["prompt_retention_days"]
62
+ else "kept forever")
63
+ out.append(("INFO", f"prompt logging is ON ({n} stored, {keep}, "
64
+ f"redaction {'on' if h['redact_prompts'] else 'OFF'}); "
65
+ f"`ccr purge --prompts --yes` deletes them"))
66
+ if not h["redact_prompts"]:
67
+ out.append(("WARN", "hooks.redact_prompts is off: pasted secrets would be stored"))
68
+ elif pp.exists():
69
+ out.append(("INFO", "prompt logging is off but .ccr/local/prompts.jsonl still exists "
70
+ "(`ccr purge --prompts --yes`)"))
71
+ if pp.exists() and (root / ".git").exists():
72
+ try:
73
+ ignored = subprocess.run(["git", "check-ignore", "-q", str(pp.relative_to(root))],
74
+ cwd=root, capture_output=True).returncode == 0
75
+ except OSError:
76
+ ignored = True
77
+ if not ignored:
78
+ out.append(("FAIL", ".ccr/local/prompts.jsonl is not gitignored: it holds prompt text "
79
+ "(add `.ccr/local/` to .gitignore, or rerun `ccr init`)"))
80
+ return out
81
+
82
+
83
+ def _doctor_agents(root: Path) -> list[tuple[str, str]]:
84
+ from ccr.config import load_config
85
+ cfg = load_config(root)
86
+ adir = root / ".claude" / "agents"
87
+ if not adir.is_dir():
88
+ return [("INFO", ".claude/agents not present (run `ccr init`)")]
89
+ missing = [f"{t.agent} ({n})" for n, t in cfg.tiers.items()
90
+ if not (adir / f"{t.agent}.md").exists()]
91
+ if missing:
92
+ return [("WARN", "tier agent file(s) missing: " + ", ".join(missing)
93
+ + " (rerun `ccr init` to create them)")]
94
+ return [("OK", f"all {len(cfg.tiers)} tier agents present in .claude/agents")]
95
+
96
+
97
+ def _doctor_history(root: Path) -> list[tuple[str, str]]:
98
+ from ccr import history as H
99
+ p = H.history_path(root)
100
+ if not p.exists():
101
+ return [("INFO", ".ccr/history.jsonl not present (created by `ccr init`)")]
102
+ try:
103
+ lines = [ln for ln in p.read_text(encoding="utf-8", errors="replace").splitlines()
104
+ if ln.strip()]
105
+ except OSError as e:
106
+ return [("WARN", f"history unreadable: {e}")]
107
+ raw = H.read_raw(root)
108
+ tasks = H.resolve(raw)
109
+ fb = sum(1 for r in raw if r.get("type") == "feedback")
110
+ bad = len(lines) - len(raw)
111
+ dup = len(raw) - fb - len(tasks)
112
+ msg = (f"history: {len(tasks)} task(s), {fb} feedback record(s)"
113
+ + (f", {dup} duplicate line(s) ignored" if dup > 0 else "")
114
+ + (f", {bad} unreadable line(s) skipped" if bad else ""))
115
+ out = [("OK" if not bad else "INFO", msg)]
116
+ ga = root / ".gitattributes"
117
+ try:
118
+ has_union = "history.jsonl merge=union" in ga.read_text(encoding="utf-8")
119
+ except OSError:
120
+ has_union = False
121
+ if (root / ".git").exists() and not has_union:
122
+ out.append(("INFO", "no `.ccr/history.jsonl merge=union` in .gitattributes: parallel "
123
+ "branches may conflict on history (rerun `ccr init`)"))
124
+ return out
125
+
126
+
127
+ def _doctor_config(root: Path) -> list[tuple[str, str]]:
128
+ from ccr.config import config_path, load_config
129
+ cfg = load_config(root)
130
+ if cfg.path is None:
131
+ return [("INFO", f"{config_path(root).relative_to(root)} not present (built-in tier "
132
+ f"defaults)")]
133
+ out = [("WARN", f"config: {e}") for e in cfg.errors]
134
+ out += [("INFO", f"config: {w}") for w in cfg.warnings]
135
+ if not cfg.errors:
136
+ t = cfg.tiers
137
+ out.insert(0, ("OK", "config valid; tiers " + ", ".join(
138
+ f"{k} {v.model}/{v.effort}" for k, v in t.items())))
139
+ return out
140
+
141
+
142
+ def _doctor_graph(root: Path) -> list[tuple[str, str]]:
143
+ from ccr.graph import freshness
144
+ try:
145
+ f = freshness(root)
146
+ except Exception as e: # never let doctor crash on a broken db
147
+ return [("WARN", f"graph check failed: {e}")]
148
+ if f["status"] == "missing":
149
+ return [("INFO", "graph not built yet (run `ccr graph`)")]
150
+ if f["status"] == "error":
151
+ return [("WARN", "graph database unreadable (run `ccr graph --rebuild`)")]
152
+ age = f.get("age_s")
153
+ age_s = f"{age // 60} min ago" if age is not None and age < 7200 else (
154
+ f"{age // 3600} h ago" if age is not None else "unknown age")
155
+ msg = f"graph: {f['files']} files, mode {f['mode']}, built {age_s}"
156
+ if f["status"] == "fresh":
157
+ return [("OK", msg + ", fresh")]
158
+ return [("WARN", msg + ", stale: " + "; ".join(f["reasons"]) + " (run `ccr graph`)")]
159
+
160
+
161
+ _MEM_LABELS = {"claude_md": "CLAUDE.md", "claude_local": "CLAUDE.local.md", "rules": "rules",
162
+ "import": "@imports", "auto_memory": "auto memory", "agent_memory": "agent memory",
163
+ "mcp_memory": "MCP memory"}
164
+
165
+
166
+ def _doctor_memory(root: Path) -> list[tuple[str, str]]:
167
+ from ccr.memory import collect
168
+ try:
169
+ rep = collect(root)
170
+ except Exception as e: # collect never raises, but doctor must not either
171
+ return [("WARN", f"memory check failed: {e}")]
172
+ out: list[tuple[str, str]] = []
173
+ if not rep.sources:
174
+ out.append(("INFO", "no memory sources found (CLAUDE.md, auto memory, agent memory, "
175
+ "MCP memory)"))
176
+ else:
177
+ groups: dict[str, list] = {}
178
+ for s in rep.sources:
179
+ groups.setdefault(s.kind, []).append(s)
180
+ parts = []
181
+ for kind, items in groups.items():
182
+ label = _MEM_LABELS.get(kind, kind)
183
+ if kind == "agent_memory":
184
+ parts.append(f"{label} ({len({i.agent for i in items})} agent(s))")
185
+ elif kind == "mcp_memory":
186
+ parts.append(f"{label} ({sum(i.entries for i in items)} entries)")
187
+ else:
188
+ scopes = sorted({i.scope for i in items})
189
+ parts.append(f"{label} x{len(items)} ({', '.join(scopes)})")
190
+ out.append(("OK", f"memory: {len(rep.sources)} source(s): " + "; ".join(parts)))
191
+ kinds = rep.by_kind()
192
+ out.append(("INFO", f"memory signals: {len(rep.signals)}" + (
193
+ " (" + ", ".join(f"{k} {v}" for k, v in sorted(kinds.items())) + ")" if kinds else "")))
194
+ out += [("INFO", n) for n in rep.notes]
195
+ return out
196
+
197
+
198
+ # Checks run in this order; add a check by appending a `(root) -> [(level, message)]` function.
199
+ CHECKS = (_doctor_claude, _doctor_effort_env, _doctor_settings, _doctor_config, _doctor_graph,
200
+ _doctor_memory, _doctor_agents, _doctor_privacy, _doctor_history)
201
+
202
+
203
+ def run_doctor(root: Path) -> list[tuple[str, str]]:
204
+ """Return list of (level, message); level in OK/WARN/FAIL/INFO."""
205
+ out: list[tuple[str, str]] = []
206
+ for check in CHECKS:
207
+ out += check(root)
208
+ return out
ccr/entry.py ADDED
@@ -0,0 +1,23 @@
1
+ """Console entry point: `ccr hook ...` and `ccr statusline` take a fast path that never
2
+ imports typer (or tree-sitter); everything else goes to the typer app in ccr.cli."""
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ FAST = ("hook", "statusline")
8
+
9
+
10
+ def main(argv: list[str] | None = None) -> None:
11
+ args = list(sys.argv[1:] if argv is None else argv)
12
+ if args and args[0] == "hook":
13
+ from ccr.hooks import main as hook_main
14
+ raise SystemExit(hook_main(args[1:]))
15
+ if args and args[0] == "statusline":
16
+ from ccr.statusline import main as sl_main
17
+ raise SystemExit(sl_main(args[1:]))
18
+ from ccr.cli import app
19
+ app(args=args, prog_name="ccr")
20
+
21
+
22
+ if __name__ == "__main__":
23
+ main()
@@ -0,0 +1,13 @@
1
+ """Token-free task evaluation: classification, code location and risk scoring.
2
+
3
+ `ccr.evaluate.llm` holds the optional (opt-in) LLM assist; nothing here imports typer or
4
+ tree-sitter, so it is safe to use from hooks.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from ccr.evaluate.classify import TaskClass, classify
9
+ from ccr.evaluate.locate import Candidate, Location, locate
10
+ from ccr.evaluate.risk import Component, Risk, assess_risk
11
+
12
+ __all__ = ["Candidate", "Component", "Location", "Risk", "TaskClass", "assess_risk",
13
+ "classify", "locate"]
@@ -0,0 +1,335 @@
1
+ """Rule-based task classification: class, scope, vagueness, destructive / hard markers.
2
+
3
+ Token-free and deterministic. Each class has weighted patterns; the score of a pattern grows
4
+ (sub-linearly) with the number of distinct terms it matched. Paths, @mentions, backticks and
5
+ quoted strings are blanked out first so `app/auth/x.py` does not read as a security task.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import dataclass, field
11
+
12
+ from ccr.evaluate import text as T
13
+
14
+ _I = re.I
15
+
16
+ _POLITE = re.compile(
17
+ r"^\s*(?:(?:hey|hi|ok(?:ay)?|so|now|then|also|claude)[,!.:]?\s+)*"
18
+ r"(?:please\s+|pls\s+|kindly\s+|can\s+you\s+|could\s+you\s+|would\s+you\s+|will\s+you\s+|"
19
+ r"i\s+(?:want|need|would\s+like)\s+(?:you\s+)?to\s+|i'?d\s+like\s+(?:you\s+)?to\s+|"
20
+ r"help\s+me\s+(?:to\s+)?|let'?s\s+|we\s+(?:need|have)\s+to\s+|go\s+ahead\s+and\s+)+", _I)
21
+
22
+ # class -> [(pattern, weight)]
23
+ RULES: dict[str, list[tuple[re.Pattern, float]]] = {
24
+ "question": [
25
+ (re.compile(r"^\s*(?:what|where|which|who|when|how|wheres|where'?s|what'?s|how'?s|is|are|does|do\s+(?:i|we|you)|"
26
+ r"did|can\s+(?:i|we)|should\s+(?:i|we)|explain|describe|summari[sz]e|"
27
+ r"tell\s+me|show\s+me|list|walk\s+me\s+through)\b", _I), 2.0),
28
+ (re.compile(r"\?\s*$"), 1.5),
29
+ (re.compile(r"^\s*(?:help|hi|hello|hey)\s*[!?.]*\s*$", _I), 4.0),
30
+ (re.compile(r"\b(?:explain|describe|summari[sz]e|walk\s+me\s+through|overview\s+of|"
31
+ r"what\s+does|how\s+does|how\s+do(?:es)?\s+\w+\s+work|where\s+is|where\s+are|"
32
+ r"which\s+files?|find\s+where|look\s+up|understand|what\s+is|what\s+are|"
33
+ r"how\s+is|how\s+are)\b", _I), 2.0),
34
+ ],
35
+ "trivial": [
36
+ (re.compile(r"\b(?:typos?|spelling|misspell\w*|renam\w*|reword\w*|wording|comments?|"
37
+ r"docstrings?|readme|changelog|whitespace|indent\w*|formatting|reformat|"
38
+ r"lint(?:ing)?|bump|version\s+number|copy\s?text|label|colou?r|"
39
+ r"log\s+message|sort\s+imports|import\s+order|unused\s+imports?|"
40
+ r"dead\s+code|one[- ]liner|license\s+header|todo)\b", _I), 2.0),
41
+ (re.compile(r"\b(?:add|delete|remove|drop)\s+(?:a\s+|an\s+|the\s+)?(?:short\s+|trailing\s+|blank\s+)?"
42
+ r"(?:comments?|docstrings?|type\s+hints?|newlines?|blank\s+lines?|whitespace|"
43
+ r"license\s+header|commented[- ]out\s+code)\b|\bcommented[- ]out\b|"
44
+ r"\btrailing\s+(?:newline|whitespace)\b", _I), 3.0),
45
+ (re.compile(r"\b(?:change|update|set|fix)\s+(?:the\s+)?(?:[\w-]+\s+){0,2}?"
46
+ r"(?:text|label|title|wording|copy|colou?r)\b|\bcapitali[sz]\w*|\bwording\b", _I), 3.0),
47
+ ],
48
+ "tests": [
49
+ (re.compile(r"\b(?:add|write|create|increase|improve|extend|cover)\b[\w\s,-]{0,40}?"
50
+ r"\b(?:unit\s+|integration\s+|e2e\s+|regression\s+|snapshot\s+)?tests?\b",
51
+ _I), 3.0),
52
+ (re.compile(r"\btest\s+coverage\b|\btest\s+cases?\b", _I), 2.0),
53
+ ],
54
+ "bugfix": [
55
+ (re.compile(r"\b(?:fix\w*|bugs?|broken|crash\w*|errors?|exceptions?|fails?|failing|"
56
+ r"failure|incorrect\w*|wrong|regression|null|nil|nan|undefined|"
57
+ r"off[- ]by[- ]one|doesn'?t\s+work|not\s+working|traceback|panic\w*|"
58
+ r"segfault|returns?\s+(?:none|null|nil|wrong|empty)|double[- ]count\w*)\b",
59
+ _I), 2.0),
60
+ ],
61
+ "feature": [
62
+ (re.compile(r"\b(?:add|implement|create|build|support|introduce|new|enable|allow|"
63
+ r"expose|integrate|endpoint|option|flag|feature|page|component|prop|"
64
+ r"command|subcommand|toggle|button|api)\b", _I), 1.5),
65
+ ],
66
+ "refactor": [
67
+ (re.compile(r"\b(?:refactor\w*|restructur\w*|reorgani[sz]\w*|clean\s?up|cleanup|"
68
+ r"extract|split|decouple|simplif\w*|dedup\w*|de-?duplicat\w*|"
69
+ r"consolidat\w*|modulari[sz]\w*|rewrite|tidy|untangle|"
70
+ r"smaller\s+(?:functions|components|modules|pieces))\b", _I), 3.0),
71
+ ],
72
+ "migration": [
73
+ (re.compile(r"\b(?:migrat\w*|upgrade|port\s+(?:it\s+)?(?:to|from)|convert\w*\s+[\w\s]{1,40}?"
74
+ r"\s+(?:to|into)|move\s+from\s+\w+\s+to|switch\s+(?:from|over)|"
75
+ r"schema\s+changes?|alter\s+table|alembic|backfill\w*|deprecat\w*)\b",
76
+ _I), 3.5),
77
+ # schema changes in plain words: "add a nullable notes column to products"
78
+ (re.compile(r"\b(?:add|create|drop|remove|rename|alter|change)\b[\w\s,'\"-]{0,30}?"
79
+ r"\b(?:columns?|tables?|unique\s+constraints?|foreign\s+keys?|primary\s+keys?|"
80
+ r"constraints?|index(?:es)?\s+(?:on|to|for)|indices)\b", _I), 3.5),
81
+ # dropping schema objects is a migration even without the word
82
+ (re.compile(r"\b(?:drop|truncate)\s+(?:the\s+)?(?:[\w.]+\s+){0,3}?"
83
+ r"(?:columns?|tables?|databases?|schemas?)\b", _I), 3.5),
84
+ ],
85
+ "security": [
86
+ (re.compile(r"\b(?:security|secure|insecure|vulnerab\w*|cve-?\d*|exploit\w*|xss|csrf|"
87
+ r"ssrf|injection|sqli|rce|sanitiz\w*|privilege\s+escalation|hard-?cod\w*|"
88
+ r"leak(?:s|ed|ing)?\s+(?:secrets?|credentials?|tokens?|keys?|pii)|"
89
+ r"audit|pen-?test\w*|threat\s+model)\b", _I), 3.0),
90
+ (re.compile(r"\b(?:session\s+fixation|fixation|csrf|clickjack\w*|brute[- ]?force|"
91
+ r"lock\s*down|access\s+control|authori[sz]\w*|rate[- ]limit\w*|"
92
+ r"tokens?\s+(?:never\s+)?expir\w*|admin\s+routes?|two[- ]factor|2fa|mfa)\b",
93
+ _I), 4.0),
94
+ (re.compile(r"\b(?:auth\w*|permissions?|secrets?|credentials?|passwords?|encrypt\w*|"
95
+ r"decrypt\w*|crypto\w*|jwt|signature\s+verification|rotate|tls|cors|"
96
+ r"api\s+keys?)\b", _I), 1.0),
97
+ ],
98
+ "perf": [
99
+ (re.compile(r"\b(?:perf\b|performance|slow\w*|speed\s?up|faster|latency|throughput|"
100
+ r"optimi[sz]\w*|bottleneck\w*|profil\w*|caching|n\+1|memory\s+usage|"
101
+ r"cpu|benchmark\w*|hot\s+path|allocations?)\b", _I), 2.5),
102
+ ],
103
+ "debugging": [
104
+ (re.compile(r"\b(?:debug\w*|investigat\w*|diagnos\w*|root\s+cause|figure\s+out\s+why|"
105
+ r"find\s+out\s+why|intermittent\w*|flaky|flakiness|sometimes|randomly|"
106
+ r"occasionally|sporadic\w*|race\s+conditions?|data\s+races?|deadlock\w*|"
107
+ r"hangs?|hanging|leak(?:s|ing)?|memory\s+leak|heisenbug|"
108
+ r"can'?t\s+reproduce|non-?deterministic\w*|keeps?\s+(?:growing|crashing|"
109
+ r"failing))\b", _I), 3.0),
110
+ (re.compile(r"^\s*why\b", _I), 2.0),
111
+ # symptoms with no cause named: the work is finding out what is wrong
112
+ (re.compile(r"\b(?:no\s+idea\s+why|(?:do\s?n'?t|not)\s+(?:know|sure)\s+why|at\s+random|"
113
+ r"random\s+\w+|now\s+and\s+then|at\s+times|(?:do(?:es)?n'?t|do(?:es)?\s+not)\s+add\s+up|"
114
+ r"numbers?\s+(?:are\s+|look\s+)?(?:off|wrong)|(?:feels?|seems?|looks?)\s+(?:off|broken|wrong)|"
115
+ r"(?:wrong|incorrect|off)\s+(?:totals?|numbers?|amounts?)|keeps?\s+\w+ing|"
116
+ r"breaks?\s+again|users?\s+(?:are\s+|keep\s+)?(?:report|complain)\w*|customers?\s+(?:report|complain|see|get)\w*|"
117
+ r"duplicate\s+\w+|twice)\b", _I), 3.0),
118
+ ],
119
+ "design": [
120
+ (re.compile(r"\b(?:design|outline|sketch|propose|draft)\s+(?:me\s+)?(?:a|an|the|how)\b|"
121
+ r"\b(?:architecture|design|rollout|roadmap|migration|adoption)\s+(?:plan|for|of)\b|"
122
+ r"\b(?:come\s+up\s+with|give\s+me|write)\s+(?:a\s+)?(?:plan|strategy|design|roadmap)\b|"
123
+ r"\bhow\s+(?:should|could|would)\s+(?:we|you|i)\s+(?:structure|split|design|organi[sz]e|"
124
+ r"migrate|handle|approach|architect|build|support)\b|"
125
+ r"\bbest\s+(?:way|approach)\s+to\s+(?:add|build|structure|support|handle|implement)\b|"
126
+ r"\bwhat\s+would\s+a\s+good\s+(?:architecture|design|approach)\b|"
127
+ r"\b(?:strategy|plan)\s+for\b", _I), 4.0),
128
+ ],
129
+ }
130
+
131
+ # A leading imperative verb is the strongest single cue.
132
+ LEAD_VERB = [
133
+ (re.compile(r"^\s*(?:fix|repair|resolve|patch)\b", _I), "bugfix", 1.5),
134
+ (re.compile(r"^\s*(?:add|implement|create|build|introduce|support|enable|expose|make)\b",
135
+ _I), "feature", 1.0),
136
+ (re.compile(r"^\s*(?:refactor|restructure|reorgani[sz]e|clean|extract|split|simplify|"
137
+ r"rewrite|tidy|decouple)\b", _I), "refactor", 1.5),
138
+ (re.compile(r"^\s*(?:migrate|upgrade|port|convert)\b", _I), "migration", 1.5),
139
+ (re.compile(r"^\s*(?:debug|investigate|diagnose|figure\s+out|find\s+out)\b", _I),
140
+ "debugging", 1.5),
141
+ (re.compile(r"^\s*(?:optimi[sz]e|speed\s+up|profile)\b", _I), "perf", 1.5),
142
+ (re.compile(r"^\s*(?:rename|bump|reformat|format|reword|update\s+the\s+(?:readme|docs?|"
143
+ r"changelog|comment))\b", _I), "trivial", 1.5),
144
+ (re.compile(r"^\s*(?:audit|harden|secure)\b", _I), "security", 1.5),
145
+ (re.compile(r"^\s*(?:plan|design|architect)\b", _I), "design", 1.5),
146
+ ]
147
+
148
+ SWEEPING = re.compile(
149
+ r"\b(?:everything|everywhere|the\s+whole\s+(?:thing|app|backend|frontend|stack|project)|"
150
+ r"rewrite\s+(?:the\s+)?(?:web\s+)?(?:app|backend|frontend|site)\b|all\s+(?:of\s+)?the\s+code|"
151
+ r"monorepo|micro-?services?|serverless|multi[- ]?region|"
152
+ r"entire\s+(?:app|backend|frontend|codebase|project))\b", _I)
153
+ SCOPE_LARGE = re.compile(
154
+ r"\b(?:everything|multi[- ]?region|monorepo|micro-?services?|serverless|"
155
+ r"entire|whole|everywhere|codebase|code\s+base|project-?wide|repo(?:sitory)?-?wide|"
156
+ r"system-?wide|throughout|globally|all\s+over|architecture|overall|"
157
+ r"across\s+(?:the\s+)?(?:codebase|project|repo|app|services|modules|packages|files)|"
158
+ r"all\s+(?:the\s+)?(?:files|modules|components|endpoints|services|tests|usages|call\s?sites|"
159
+ r"places|occurrences|packages|handlers|routes|models|class\s+components)|"
160
+ r"every\s+(?:file|module|component|endpoint|service|call|handler|route|model|usage))\b", _I)
161
+ SCOPE_SMALL = re.compile(
162
+ r"\b(?:small|tiny|minor|quick(?:ly)?|simple|trivial|just|single|one[- ]liner|one[- ]line|"
163
+ r"one\s+(?:function|file|place|spot|method)|this\s+(?:function|method|line)|"
164
+ r"a\s+few\s+lines|slight(?:ly)?)\b", _I)
165
+ DESTRUCTIVE = re.compile(
166
+ r"\b(?:drop(?:s|ping|ped)?\s+(?:the\s+)?(?:[\w.]+\s+){0,3}?(?:columns?|tables?|"
167
+ r"index(?:es)?|databases?|collections?|fields?|schemas?|users?|records?|rows?)|truncat\w*|"
168
+ r"irreversibl\w*|backfill\w*|in\s+production|"
169
+ r"(?:on|in|against|from)\s+(?:the\s+)?(?:prod|production|live)\b|"
170
+ r"production\s+(?:data|database|db)|live\s+(?:data|db|database)|prod\s+(?:data|db)|"
171
+ r"wipe|purge|(?:delete|remove|erase|clear|empty)\s+(?:all|every)|"
172
+ r"force[- ]push|rewrite\s+history|data\s+loss)\b", _I)
173
+ HARD = re.compile(
174
+ r"\b(?:race\s+conditions?|data\s+races?|deadlock\w*|concurren\w*|thread[- ]safe\w*|"
175
+ r"lock\s+contention|goroutine\s+leaks?|memory\s+leaks?|distributed|idempoten\w*|"
176
+ r"transactional|consistency|"
177
+ # intermittent failures: reproduction and diagnosis dominate the work, not the edit
178
+ r"sometimes|intermittent\w*|flak(?:y|iness|e)|randomly|occasional\w*|sporadic\w*|"
179
+ r"every\s+now\s+and\s+then|once\s+in\s+a\s+while|only\s+under\s+load|"
180
+ r"works?\s+on\s+my\s+machine)\b", _I)
181
+ VAGUE = re.compile(
182
+ r"\b(?:something|somehow|stuff|things|whatever|etc|better|improve|nicer|cleaner|properly|"
183
+ r"make\s+it\s+work|doesn'?t\s+work|not\s+working|weird|some\s+issues?|"
184
+ r"the\s+code|the\s+app|fix\s+it|look\s+into)\b", _I)
185
+ # explicit step-by-step instructions: the user already did the planning, so the work is
186
+ # execution, not exploration. Numbered/"step N" lines, or a first ... then ... finally chain.
187
+ STEP_LINE = re.compile(r"^\s*(?:\(?\d{1,2}[.):]|step\s*\d{1,2}\b)", _I | re.M)
188
+ STEP_WORDS = re.compile(r"\b(?:first(?:ly)?|then|next|after\s+that|finally|lastly)\b", _I)
189
+ MIN_STEPS = 3
190
+
191
+
192
+ def count_steps(text: str) -> int:
193
+ """Number of explicit steps in the prompt (0 when it is not a step-by-step list)."""
194
+ n = len(STEP_LINE.findall(text))
195
+ if n < MIN_STEPS:
196
+ found = [w.lower() for w in STEP_WORDS.findall(text)]
197
+ n = len(found) if found and found[0].startswith("first") else 0
198
+ return n if n >= MIN_STEPS else 0
199
+
200
+
201
+ @dataclass
202
+ class TaskClass:
203
+ kind: str
204
+ confidence: float
205
+ scores: dict[str, float] = field(default_factory=dict)
206
+ matched: dict[str, list[str]] = field(default_factory=dict)
207
+ secondary: str | None = None
208
+ scope: str = "unspecified" # small | medium | large | unspecified
209
+ scope_terms: list[str] = field(default_factory=list)
210
+ steps: int = 0 # explicit step-by-step instructions given (0 = none)
211
+ vagueness: float = 0.0
212
+ vague_terms: list[str] = field(default_factory=list)
213
+ destructive: list[str] = field(default_factory=list)
214
+ sweeping: list[str] = field(default_factory=list)
215
+ words: int = 0
216
+ hard: list[str] = field(default_factory=list)
217
+ source: str = "rules" # rules | llm
218
+
219
+ @property
220
+ def vague(self) -> bool:
221
+ return self.vagueness >= 0.6
222
+
223
+ def evidence_terms(self) -> list[str]:
224
+ """Matched cue words for the chosen class, for the history trace: short rule
225
+ vocabulary only (at most 4 terms of 24 characters)."""
226
+ return [t for t in (self.matched.get(self.kind) or []) if len(t) <= 24][:4]
227
+
228
+ def evidence(self, kind: str | None = None) -> str:
229
+ terms = self.matched.get(kind or self.kind) or []
230
+ return ", ".join(f"'{t}'" for t in terms[:4])
231
+
232
+
233
+ def _hits(rx: re.Pattern, text: str) -> list[str]:
234
+ seen = []
235
+ for m in rx.finditer(text):
236
+ t = re.sub(r"\s+", " ", m.group(0).strip().lower())
237
+ if t and t not in seen:
238
+ seen.append(t)
239
+ return seen
240
+
241
+
242
+ def _extra_hard(terms: list[str]) -> re.Pattern | None:
243
+ words = [re.escape(t).replace(r"\ ", r"\s+") for t in terms if t]
244
+ return re.compile(r"\b(?:" + "|".join(words) + r")s?\b", _I) if words else None
245
+
246
+
247
+ def classify(task: str, located: bool | None = None,
248
+ hard_terms: list[str] | None = None) -> TaskClass:
249
+ """Classify a task prompt. `located`: whether code was located (feeds vagueness).
250
+ `hard_terms`: project words (config `hard_terms`) that count like "intermittent"."""
251
+ raw = task.strip()
252
+ core = _POLITE.sub("", raw, count=1)
253
+ body = T.strip_refs(core)
254
+ scores: dict[str, float] = {}
255
+ matched: dict[str, list[str]] = {}
256
+ for kind, rules in RULES.items():
257
+ s = 0.0
258
+ for rx, weight in rules:
259
+ src = core if rx.pattern.startswith("^") or rx.pattern.startswith(r"\?") else body
260
+ hits = _hits(rx, src)
261
+ if hits:
262
+ s += weight * (1 + 0.5 * (min(len(hits), 3) - 1))
263
+ matched.setdefault(kind, []).extend(h for h in hits
264
+ if h not in matched.get(kind, []))
265
+ if s:
266
+ scores[kind] = s
267
+ for rx, kind, bonus in LEAD_VERB:
268
+ m = rx.search(core)
269
+ if m and not (kind == "bugfix" and "trivial" in scores): # "fix the typo"
270
+ scores[kind] = scores.get(kind, 0.0) + bonus
271
+ lead = m.group(0).strip().lower()
272
+ terms = [t for t in matched.get(kind, []) if t != lead]
273
+ matched[kind] = [lead] + terms
274
+ break
275
+ # concurrency / leak bugs are hard-to-diagnose bugs, not routine fixes
276
+ hard = _hits(HARD, body)
277
+ extra = _extra_hard(hard_terms or [])
278
+ if extra:
279
+ hard += [h for h in _hits(extra, body) if h not in hard]
280
+ if hard and ("bugfix" in scores or "debugging" in scores):
281
+ scores["debugging"] = scores.get("debugging", 0.0) + 1.5
282
+ matched.setdefault("debugging", []).extend(h for h in hard
283
+ if h not in matched.get("debugging", []))
284
+ # "add/write tests" is a tests task, not a feature that happens to mention tests
285
+ if scores.get("tests", 0) >= 3.0 and "feature" in scores:
286
+ scores["feature"] = max(0.0, scores["feature"] - 2.5)
287
+ # questions that also carry a strong change cue ("can you fix ...?") are change requests
288
+ ranked = sorted(scores.items(), key=lambda kv: (-kv[1], _PRIORITY.index(kv[0])))
289
+ if ranked:
290
+ kind, top = ranked[0]
291
+ second = ranked[1][1] if len(ranked) > 1 else 0.0
292
+ strength = min(1.0, top / 4.0)
293
+ margin = (top - second) / top if top else 0.0
294
+ conf = strength * (0.55 + 0.45 * margin)
295
+ secondary = ranked[1][0] if len(ranked) > 1 and ranked[1][1] >= 0.6 * top else None
296
+ else:
297
+ kind, conf, secondary = "feature", 0.15, None
298
+ matched["feature"] = []
299
+
300
+ large, small = _hits(SCOPE_LARGE, body), _hits(SCOPE_SMALL, body)
301
+ scope = ("medium" if large and small else "large" if large else "small" if small
302
+ else "unspecified")
303
+
304
+ steps = count_steps(core)
305
+ v, vterms = _vagueness(raw, body, located, steps)
306
+ return TaskClass(kind=kind, confidence=round(conf, 3), scores=scores, matched=matched,
307
+ secondary=secondary, scope=scope, scope_terms=large + small, steps=steps,
308
+ vagueness=v, vague_terms=vterms, destructive=_hits(DESTRUCTIVE, body),
309
+ sweeping=_hits(SWEEPING, body), hard=hard,
310
+ words=len(raw.split()))
311
+
312
+
313
+ # tie-break order: prefer the cheaper interpretation ("start low")
314
+ _PRIORITY = ["question", "trivial", "tests", "bugfix", "feature", "refactor", "perf",
315
+ "migration", "debugging", "design", "security"]
316
+
317
+
318
+ def _vagueness(raw: str, body: str, located: bool | None,
319
+ steps: int = 0) -> tuple[float, list[str]]:
320
+ v = 0.0
321
+ terms = _hits(VAGUE, body)
322
+ # prompt length is deliberately not a signal: a terse prompt can be huge work and a long
323
+ # one can be a trivial edit. Vagueness comes from vague wording and missing specifics.
324
+ v += min(0.45, 0.15 * len(terms))
325
+ ats, paths = T.path_tokens(raw)
326
+ specifics = len(ats) + len(paths) + len(T.identifiers(raw))
327
+ specifics += len(T.QUOTED_RX.findall(raw)) + len(re.findall(r"\b\d+\b", raw)) // 2
328
+ v -= min(0.5, 0.25 * specifics)
329
+ if steps:
330
+ v -= 0.3
331
+ if located is False:
332
+ v += 0.3
333
+ elif located:
334
+ v -= 0.1
335
+ return round(max(0.0, min(1.0, v)), 3), terms