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/history/shadow.py ADDED
@@ -0,0 +1,114 @@
1
+ """Counterfactual sampling: would a cheaper tier have done a task the router sent to a deep tier?
2
+
3
+ `ccr shadow` re-runs a few sampled deep-tier tasks (prompts from `hooks.store_prompts`) headless
4
+ at a lower tier, inside a throwaway `git worktree` of HEAD so your working tree is never touched,
5
+ and records whether that run succeeded in `.ccr/local/shadow.jsonl`. It uses your own `claude`
6
+ CLI, so it spends real usage: nothing runs without `--yes` and a total budget cap.
7
+ Success needs `--test-command` to mean anything; without one it only means "claude exited cleanly".
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import random
13
+ import shutil
14
+ import subprocess
15
+ import tempfile
16
+ import time
17
+ from pathlib import Path
18
+
19
+ from ccr.config import TIERS
20
+ from ccr.history.learn import SUCCESS
21
+
22
+
23
+ def path(root) -> Path:
24
+ return Path(root) / ".ccr" / "local" / "shadow.jsonl"
25
+
26
+
27
+ def read(root) -> list[dict]:
28
+ out = []
29
+ try:
30
+ for line in path(root).read_text(encoding="utf-8").splitlines():
31
+ try:
32
+ e = json.loads(line)
33
+ except ValueError:
34
+ continue
35
+ if isinstance(e, dict) and isinstance(e.get("id"), str):
36
+ out.append(e)
37
+ except OSError:
38
+ pass
39
+ return out
40
+
41
+
42
+ def append(root, entry: dict) -> None:
43
+ p = path(root)
44
+ p.parent.mkdir(parents=True, exist_ok=True)
45
+ with open(p, "a", encoding="utf-8") as f:
46
+ f.write(json.dumps(entry, separators=(",", ":")) + "\n")
47
+
48
+
49
+ def pick(records: list[dict], logged: dict[str, dict], done: set[str], from_tier: str,
50
+ sample: int, seed: int = 11) -> list[dict]:
51
+ """Successful tasks at `from_tier` or above that have a stored prompt and no shadow run yet."""
52
+ floor = TIERS.index(from_tier)
53
+ pool = [r for r in records if r.get("tier") in TIERS and TIERS.index(r["tier"]) >= floor
54
+ and r.get("outcome") in SUCCESS and r.get("id") not in done
55
+ and (logged.get(str(r.get("id"))) or {}).get("prompt")]
56
+ random.Random(seed).shuffle(pool)
57
+ return pool[:sample]
58
+
59
+
60
+ def shadow_tier(deep: str, lower: str | None) -> str:
61
+ return lower or TIERS[max(0, TIERS.index(deep) - 1)]
62
+
63
+
64
+ def run_one(root: Path, rec: dict, prompt: str, tier: str, cfg, *, budget: float,
65
+ test_command: str | None, runner=None, test_runner=None, worktree=True) -> dict:
66
+ from ccr.headless import run_task
67
+ tmp = None
68
+ work = root
69
+ if worktree:
70
+ tmp = Path(tempfile.mkdtemp(prefix="ccr-shadow-"))
71
+ work = tmp / "wt"
72
+ subprocess.run(["git", "worktree", "add", "--detach", str(work), "HEAD"], cwd=root,
73
+ check=True, capture_output=True)
74
+ try:
75
+ res = run_task(prompt, work, cfg=cfg, tier=tier, max_escalations=0,
76
+ max_budget_usd=budget, test_command=test_command,
77
+ permission_mode="acceptEdits", allow_llm=False, record=False,
78
+ runner=runner, test_runner=test_runner)
79
+ finally:
80
+ if worktree:
81
+ subprocess.run(["git", "worktree", "remove", "--force", str(work)], cwd=root,
82
+ capture_output=True)
83
+ shutil.rmtree(tmp, ignore_errors=True)
84
+ a = res.attempts[-1]
85
+ return {"id": rec["id"], "ts": int(time.time()), "deep_tier": rec["tier"],
86
+ "shadow_tier": tier, "class": rec.get("class"), "area": rec.get("area"),
87
+ "outcome": a.outcome, "reason": a.reason, "verified": bool(test_command),
88
+ "test": a.test, "cost_usd": a.cost_usd, "tokens": a.tokens}
89
+
90
+
91
+ def summarize(entries: list[dict]) -> dict:
92
+ n = len(entries)
93
+ ok = sum(e.get("outcome") == "success" for e in entries)
94
+ ver = [e for e in entries if e.get("verified")]
95
+ pairs: dict[str, list[int]] = {}
96
+ for e in entries:
97
+ c = pairs.setdefault(f"{e.get('deep_tier')}->{e.get('shadow_tier')}", [0, 0])
98
+ c[0] += e.get("outcome") == "success"
99
+ c[1] += 1
100
+ return {"n": n, "ok": ok, "rate": round(ok / n, 3) if n else None,
101
+ "verified_n": len(ver), "verified_ok": sum(e.get("outcome") == "success" for e in ver),
102
+ "pairs": {k: {"ok": v[0], "n": v[1]} for k, v in sorted(pairs.items())},
103
+ "cost_usd": round(sum(e.get("cost_usd") or 0 for e in entries), 4)}
104
+
105
+
106
+ def format_lines(s: dict) -> list[str]:
107
+ if not s["n"]:
108
+ return []
109
+ out = [f"Shadow: a cheaper tier succeeded on {s['ok']}/{s['n']} sampled deep-tier task(s) "
110
+ f"({100 * s['rate']:.0f}%); {s['verified_ok']}/{s['verified_n']} verified by tests"]
111
+ out.append(" " + ", ".join(f"{k} {v['ok']}/{v['n']}" for k, v in s["pairs"].items()))
112
+ if s["verified_n"] < s["n"]:
113
+ out.append(" unverified runs only mean claude exited cleanly: use --test-command")
114
+ return out
ccr/history/stats.py ADDED
@@ -0,0 +1,172 @@
1
+ """`ccr stats`: numbers over resolved history (feedback applied, duplicates dropped).
2
+
3
+ tasks task records: one per routed interactive task (hook) or `ccr run` attempt
4
+ success rate successes / (successes + failures); outcome-unknown tasks are left out
5
+ escalation share of a tier's tasks that were retried one tier higher (`escalated_to`)
6
+ tokens input + output + cache-creation tokens (cache reads excluded)
7
+ cost `total_cost_usd` as reported by `claude -p` (ccr run, LLM assist); interactive
8
+ subscription sessions report no cost, so they show tokens only
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from ccr.config import TIERS
13
+ from ccr.history import savings
14
+ from ccr.history.learn import FAILURE, SUCCESS, struggled, summarize
15
+
16
+
17
+ def _bucket() -> dict:
18
+ return {"tasks": 0, "success": 0, "failure": 0, "unknown": 0, "escalated": 0,
19
+ "tokens": 0, "cost_usd": 0.0, "tiers": {}}
20
+
21
+
22
+ def _num(v) -> float:
23
+ return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else 0.0
24
+
25
+
26
+ def _add(b: dict, r: dict) -> None:
27
+ b["tasks"] += 1
28
+ o = r.get("outcome")
29
+ if o in SUCCESS:
30
+ b["success"] += 1
31
+ elif o in FAILURE:
32
+ b["failure"] += 1
33
+ else:
34
+ b["unknown"] += 1
35
+ if r.get("escalated_to"):
36
+ b["escalated"] += 1
37
+ b["tokens"] += int(_num(r.get("tokens")))
38
+ b["cost_usd"] += _num(r.get("cost_usd")) + _num(r.get("assist_cost_usd"))
39
+ t = r.get("tier") if r.get("tier") in TIERS else "?"
40
+ b["tiers"][t] = b["tiers"].get(t, 0) + 1
41
+
42
+
43
+ def _finish(b: dict) -> dict:
44
+ decided = b["success"] + b["failure"]
45
+ b["success_rate"] = round(b["success"] / decided, 3) if decided else None
46
+ b["escalation_rate"] = round(b["escalated"] / b["tasks"], 3) if b["tasks"] else None
47
+ b["cost_usd"] = round(b["cost_usd"], 6)
48
+ b["tiers"] = dict(sorted(b["tiers"].items()))
49
+ return b
50
+
51
+
52
+ def compute(records: list[dict], cfg) -> dict:
53
+ tasks = [r for r in records if isinstance(r.get("tier"), str) or r.get("class")]
54
+ total = _bucket()
55
+ by_tier: dict[str, dict] = {}
56
+ by_area: dict[str, dict] = {}
57
+ by_class: dict[str, dict] = {}
58
+ by_source: dict[str, dict] = {}
59
+ runs: set[str] = set()
60
+ feedback = 0
61
+ for r in tasks:
62
+ _add(total, r)
63
+ _add(by_tier.setdefault(r.get("tier") if r.get("tier") in TIERS else "?", _bucket()),
64
+ r)
65
+ _add(by_area.setdefault(str(r.get("area") or "*"), _bucket()), r)
66
+ _add(by_class.setdefault(str(r.get("class") or "?"), _bucket()), r)
67
+ src = "run" if r.get("source") == "run" else "hook" if r.get("source") == "hook" \
68
+ else str(r.get("source") or "other")
69
+ _add(by_source.setdefault(src, _bucket()), r)
70
+ if isinstance(r.get("run_id"), str):
71
+ runs.add(r["run_id"])
72
+ if r.get("feedback"):
73
+ feedback += 1
74
+ ts = [r["ts"] for r in tasks if isinstance(r.get("ts"), (int, float))]
75
+ _finish(total)
76
+ n = total["tasks"]
77
+ tiers = {}
78
+ for t in [*TIERS, "?"]:
79
+ if t in by_tier:
80
+ b = _finish(by_tier[t])
81
+ b["share"] = round(b["tasks"] / n, 3) if n else None
82
+ b.pop("tiers")
83
+ tiers[t] = b
84
+ return {
85
+ "tasks": n, "runs": len(runs), "feedback_corrections": feedback,
86
+ "since": min(ts) if ts else None, "until": max(ts) if ts else None,
87
+ "usage": {"tokens": total["tokens"], "cost_usd": total["cost_usd"],
88
+ "by_source": {k: {"tasks": v["tasks"], "tokens": v["tokens"],
89
+ "cost_usd": round(v["cost_usd"], 6)}
90
+ for k, v in sorted(by_source.items())}},
91
+ "struggled": sum(1 for r in tasks if struggled(r, cfg["history"])),
92
+ "manual_escalations": sum("manual_model_up" in (r.get("signals") or ()) for r in tasks),
93
+ "possible_reworks": sum("possible_rework" in (r.get("signals") or ()) for r in tasks),
94
+ "overall": {k: total[k] for k in ("success", "failure", "unknown", "escalated",
95
+ "success_rate", "escalation_rate")},
96
+ "tiers": tiers,
97
+ "areas": {k: _finish(v) for k, v in sorted(by_area.items())},
98
+ "classes": {k: _finish(v) for k, v in sorted(by_class.items())},
99
+ "learning": summarize(tasks, cfg),
100
+ "savings": savings.estimate(tasks, cfg),
101
+ "misroutes": savings.misroutes(tasks, cfg),
102
+ }
103
+
104
+
105
+ def _pct(v) -> str:
106
+ return "-" if v is None else f"{100 * v:.0f}%"
107
+
108
+
109
+ def _k(n: int) -> str:
110
+ return f"{n / 1e6:.2f}M" if n >= 1e6 else f"{n / 1e3:.1f}k" if n >= 1e3 else str(n)
111
+
112
+
113
+ def _table(title: str, rows: dict, key_w: int, with_tiers: bool) -> list[str]:
114
+ head = (f" {title:<{key_w}} {'tasks':>5} {'ok':>4} {'fail':>4} {'?':>3} {'success':>7} "
115
+ f"{'escal':>5} {'tokens':>8} {'cost':>9}")
116
+ out = [head + (" tiers" if with_tiers else "")]
117
+ for k, b in rows.items():
118
+ line = (f" {k[:key_w]:<{key_w}} {b['tasks']:>5} {b['success']:>4} {b['failure']:>4} "
119
+ f"{b['unknown']:>3} {_pct(b['success_rate']):>7} {_pct(b['escalation_rate']):>5}"
120
+ f" {_k(b['tokens']):>8} {('$%.4f' % b['cost_usd']) if b['cost_usd'] else '-':>9}")
121
+ if with_tiers:
122
+ line += " " + " ".join(f"{t}:{c}" for t, c in b["tiers"].items())
123
+ out.append(line)
124
+ return out
125
+
126
+
127
+ def format_text(s: dict, root=None, when=None, detail: bool = False) -> list[str]:
128
+ from ccr.history import shadow
129
+ import time
130
+ fmt = (lambda t: time.strftime("%Y-%m-%d %H:%M", time.localtime(t))) if when is None \
131
+ else when
132
+ out = ["ccr stats" + (f" ({root})" if root else "")]
133
+ if not s["tasks"]:
134
+ return out + [" no routed tasks in history yet (.ccr/history.jsonl)"]
135
+ src = s["usage"]["by_source"]
136
+ by_src = ", ".join(f"{k} {v['tasks']}" for k, v in src.items())
137
+ out.append(f"Tasks: {s['tasks']} ({by_src}; {s['runs']} ccr run(s)) from "
138
+ f"{fmt(s['since'])} to {fmt(s['until'])}"
139
+ + (f"; {s['feedback_corrections']} corrected by feedback"
140
+ if s["feedback_corrections"] else ""))
141
+ u = s["usage"]
142
+ out.append(f"Usage: {_k(u['tokens'])} tokens ("
143
+ + ", ".join(f"{k} {_k(v['tokens'])}" for k, v in src.items())
144
+ + f"); est. cost ${u['cost_usd']:.4f} (claude-reported, headless only)")
145
+ o = s["overall"]
146
+ out.append(f"Outcomes: {o['success']} ok, {o['failure']} failed, {o['unknown']} unknown; "
147
+ f"success {_pct(o['success_rate'])}, escalated {o['escalated']} "
148
+ f"({_pct(o['escalation_rate'])})")
149
+ if s.get("struggled"):
150
+ out.append(f" {s['struggled']} success(es) struggled (many tool errors/turns or a "
151
+ f"self-reported failure): learning counts them as failures")
152
+ if s.get("manual_escalations") or s.get("possible_reworks"):
153
+ out.append(f" {s['manual_escalations']} manual move(s) to a stronger model, "
154
+ f"{s['possible_reworks']} possible rework(s) after a cheap answer")
155
+ out += savings.format_lines(s["savings"], s["misroutes"], detail)
156
+ if root is not None:
157
+ out += shadow.format_lines(shadow.summarize(shadow.read(root)))
158
+ out.append("Tier distribution: " + " ".join(
159
+ f"{t} {b['tasks']} ({_pct(b['share'])})" for t, b in s["tiers"].items()))
160
+ out.append("Per tier:")
161
+ out += _table("tier", s["tiers"], 4, False)
162
+ out.append("Per area:")
163
+ out += _table("area", s["areas"], max(4, min(28, max(len(k) for k in s["areas"]))), True)
164
+ out.append("Per task class:")
165
+ out += _table("class", s["classes"], 9, True)
166
+ learn = [x for x in s["learning"] if x["action"] != "watch"]
167
+ out.append("Learning (what routing does with this history):")
168
+ if learn:
169
+ out += [f" {x['action']:<7} {x['note']}" for x in learn]
170
+ else:
171
+ out.append(" no adjustments yet (thresholds: `history:` in .ccr/config.yaml)")
172
+ return out
ccr/history/tune.py ADDED
@@ -0,0 +1,80 @@
1
+ """`ccr tune`: propose edits to `.ccr/config.yaml` from misroute evidence, as a diff you approve.
2
+
3
+ ccr never edits its own rules on its own. This only reads history (the same evidence as
4
+ `ccr stats --misroutes`) and turns it into concrete, minimal config changes:
5
+ hard_terms a cue word whose tasks keep failing at the tier it routes to
6
+ class_base.<k> a class that keeps failing (raise one tier) or keeps being over-routed (lower)
7
+ Changes are plain text edits so your comments and ordering survive.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import difflib
12
+ import re
13
+
14
+ from ccr.config import TIERS
15
+ from ccr.history import savings
16
+
17
+ MAX_BASE = TIERS.index("T3")
18
+
19
+
20
+ def propose(records: list[dict], cfg) -> list[dict]:
21
+ hc = cfg["history"]
22
+ k = int(hc["min_samples"])
23
+ mis = savings.misroutes(records, cfg)
24
+ changes: list[dict] = []
25
+ have = {t.lower() for t in cfg["hard_terms"]}
26
+ for c in mis["cues"]:
27
+ term = c["term"]
28
+ if term.lower() not in have and 0 < len(term) <= 24:
29
+ n = c["ok"] + c["failed"]
30
+ changes.append({"kind": "hard_term", "term": term,
31
+ "why": f"cue '{term}' failed {c['failed']}/{n} at {c['tier']}"})
32
+ have.add(term.lower())
33
+ by_class: dict[tuple[str, str], list[str]] = {}
34
+ for it in mis["items"]:
35
+ if it.get("class") and it.get("tier"):
36
+ by_class.setdefault((it["kind"], it["class"]), []).append(it["tier"])
37
+ for (kind, cls), tiers in sorted(by_class.items()):
38
+ base = cfg["class_base"].get(cls)
39
+ if base not in TIERS or len(tiers) < k or any(t != base for t in tiers[:k]):
40
+ continue
41
+ i = TIERS.index(base)
42
+ new = i + 1 if kind == "under" else i - 1
43
+ floor = 0 if cls in savings.NO_FLOOR else 1
44
+ if kind == "under" and new > MAX_BASE or kind == "over" and new < floor:
45
+ continue
46
+ changes.append({"kind": "class_base", "class": cls, "from": base, "to": TIERS[new],
47
+ "why": f"{len(tiers)} {kind}-routed {cls} task(s) at {base}"})
48
+ return changes
49
+
50
+
51
+ _HARD = re.compile(r"^hard_terms:\s*\[(.*?)\]\s*(#.*)?$", re.M)
52
+
53
+
54
+ def apply_text(text: str, changes: list[dict]) -> str:
55
+ for ch in changes:
56
+ if ch["kind"] == "hard_term":
57
+ m = _HARD.search(text)
58
+ if m:
59
+ items = [x.strip() for x in m.group(1).split(",") if x.strip()]
60
+ items.append(f'"{ch["term"]}"' if " " in ch["term"] else ch["term"])
61
+ text = text[:m.start()] + f"hard_terms: [{', '.join(items)}]" \
62
+ + (f" {m.group(2)}" if m.group(2) else "") + text[m.end():]
63
+ else:
64
+ text = text.rstrip("\n") + f'\n\nhard_terms: [{ch["term"]}]\n'
65
+ else:
66
+ cls, to = ch["class"], ch["to"]
67
+ line = re.compile(rf"^(\s+){cls}:\s*\S+", re.M)
68
+ if line.search(text) and re.search(r"^class_base:\s*$", text, re.M):
69
+ text = line.sub(rf"\g<1>{cls}: {to}", text, count=1)
70
+ elif re.search(r"^class_base:\s*$", text, re.M):
71
+ text = re.sub(r"^class_base:\s*$", f"class_base:\n {cls}: {to}", text, count=1,
72
+ flags=re.M)
73
+ else:
74
+ text = text.rstrip("\n") + f"\n\nclass_base:\n {cls}: {to}\n"
75
+ return text
76
+
77
+
78
+ def diff(old: str, new: str, name: str = ".ccr/config.yaml") -> list[str]:
79
+ return list(difflib.unified_diff(old.splitlines(), new.splitlines(), f"a/{name}",
80
+ f"b/{name}", lineterm=""))
ccr/history/why.py ADDED
@@ -0,0 +1,186 @@
1
+ """A plain-language checklist of what ccr looked at before choosing a tier (model + effort).
2
+
3
+ Built from a live routing Decision (`from_decision`) or, for older history records, from the
4
+ routing signals kept in the record's `trace` (`from_trace`). Each check is
5
+ {n, title, looked_at, found, effect, move} where `move` is up | down | rule | none.
6
+ `chain` is the short story: where it started, what moved it, where it ended.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ _MOVE = re.compile(r"^(\+\d|-\d)\b")
13
+
14
+
15
+ def _check(n: int, title: str, looked: str, found: str, effect: str, move: str = "none") -> dict:
16
+ return {"n": n, "title": title, "looked_at": looked, "found": found, "effect": effect,
17
+ "move": move}
18
+
19
+
20
+ def _terms(xs, k=4) -> str:
21
+ xs = [str(x) for x in (xs or [])][:k]
22
+ return ", ".join(f"“{x}”" for x in xs)
23
+
24
+
25
+ def _scope_effect(scope: str, bumps: list[str], downs: list[str]) -> tuple[str, str]:
26
+ if "large scope" in bumps:
27
+ return "Raises the tier by 1", "up"
28
+ if any(d.startswith("small scope") for d in downs):
29
+ return "Lowers the tier by 1", "down"
30
+ return ("No change", "none") if scope != "unspecified" else ("No change (scope not stated)", "none")
31
+
32
+
33
+ def _downs(reasons: list[str]) -> list[str]:
34
+ return [r.split(": ", 1)[1] for r in reasons if r.startswith("-1: ") and "history" not in r
35
+ and "budget" not in r]
36
+
37
+
38
+ def from_decision(d, tier) -> dict:
39
+ tc, loc, r = d.task_class, d.location, d.risk
40
+ bumps = list(d.bumps)
41
+ reasons = list(d.reasons)
42
+ downs = _downs(reasons)
43
+ checks = []
44
+ kind_found = f"a {tc.kind} task (confidence {tc.confidence:.2f}, decided by {tc.source})"
45
+ if tc.matched.get(tc.kind):
46
+ kind_found += f"; matched words {_terms(tc.matched[tc.kind])}"
47
+ if tc.secondary:
48
+ kind_found += f"; runner-up: {tc.secondary}"
49
+ if d.reclassed:
50
+ kind_found += "; the report names no code, so it is treated as debugging"
51
+ checks.append(_check(1, "What kind of task is it?", "the wording of the prompt", kind_found,
52
+ f"Starting point: {d.base}", "none"))
53
+ eff, mv = _scope_effect(tc.scope, bumps, downs)
54
+ scope_found = f"scope {tc.scope}" + (f" ({_terms(tc.scope_terms)})" if tc.scope_terms else "")
55
+ if tc.steps:
56
+ scope_found += f"; {tc.steps} explicit steps given"
57
+ if any("step-by-step" in x for x in downs):
58
+ eff, mv = "Lowers the tier by 1 (you already planned the work)", "down"
59
+ if tc.sweeping:
60
+ scope_found += f"; sweeping change {_terms(tc.sweeping)}"
61
+ eff, mv = "Raises the tier (a plan is needed first)", "up"
62
+ checks.append(_check(2, "How big is it?", "size words, explicit steps",
63
+ scope_found, eff, mv))
64
+ vague = f"vagueness {tc.vagueness:.2f}" + (f" ({_terms(tc.vague_terms)})" if tc.vague_terms else "")
65
+ extra = []
66
+ if tc.hard:
67
+ extra.append(f"hard-problem words {_terms(tc.hard)}")
68
+ if tc.destructive:
69
+ extra.append(f"destructive words {_terms(tc.destructive)}")
70
+ wording_up = [b for b in bumps if b.startswith(("vague bug", "hard problem"))]
71
+ checks.append(_check(3, "How clear and how hard does it sound?",
72
+ "vague wording, intermittent or hard-problem words, destructive words",
73
+ "; ".join([vague, *extra]),
74
+ ("Raises the tier: " + ", ".join(wording_up)) if wording_up else "No change",
75
+ "up" if wording_up else "none"))
76
+ if loc.candidates:
77
+ files = "; ".join(f"{c.path} ({c.confidence:.2f})" for c in loc.candidates[:3])
78
+ found = f"{len(loc.candidates)} candidate file(s), location confidence {loc.confidence:.2f}: {files}"
79
+ else:
80
+ found = "no file could be tied to the prompt"
81
+ checks.append(_check(4, "Which code does it touch?", "file names, symbols and the code graph",
82
+ found, "Needed for the risk checks below", "none"))
83
+ comp = r.components or {}
84
+ if r.score is None:
85
+ risk_found, risk_eff, risk_mv = "unknown, because no files were located", "No change", "none"
86
+ else:
87
+ parts = [f"{n.replace('_', ' ')} {c.value:.2f}" for n, c in comp.items()
88
+ if n in ("blast_radius", "complexity", "test_proximity", "churn")]
89
+ risk_found = f"risk {r.score:.2f} ({r.level}): " + ", ".join(parts)
90
+ hi = [b for b in bumps if b.startswith(("risk high", "complex code", "unclassified"))]
91
+ risk_eff = ("Raises the tier: " + ", ".join(hi)) if hi else "No change"
92
+ risk_mv = "up" if hi else "none"
93
+ checks.append(_check(5, "How risky is that code?",
94
+ "dependents (blast radius), complexity, tests nearby, recent churn",
95
+ risk_found, risk_eff, risk_mv))
96
+ crit = [f"critical path: {'/'.join(r.critical_groups)}"] if r.critical_groups else []
97
+ mem = sorted({f.kind for f in r.memory_flags}) if r.memory_flags else []
98
+ if mem:
99
+ crit.append("project notes mark it " + "/".join(mem))
100
+ crit_up = [b for b in bumps if b.startswith(("critical path", "memory flags"))]
101
+ checks.append(_check(6, "Is it a critical or protected area?",
102
+ "auth, payments, migrations, infra, secrets paths; CLAUDE.md notes",
103
+ "; ".join(crit) or "no critical path or flagged file",
104
+ "Raises the tier (never lowered here)" if crit_up else "No change",
105
+ "up" if crit_up else "none"))
106
+ checks.append(_check(7, "What did past tasks like this do?", "this project's recorded outcomes",
107
+ str(d.history), "Moves the tier" if re.search(r"[+-]1", str(d.history)) and
108
+ "no change" not in str(d.history) else "No change", "none"))
109
+ t4 = list(d.t4_rules)
110
+ checks.append(_check(8, "Does a safety rule force the top tier?",
111
+ "security on a critical path, destroying production data, protected files",
112
+ "; ".join(t4) or "no", "Forces T4" if t4 else "No change",
113
+ "rule" if t4 else "none"))
114
+ checks.append(_check(9, "Is the weekly budget under pressure?", "usage from the status line",
115
+ str(d.budget.detail), "Lowers the tier by 1" if d.budget.pressure
116
+ else "No change", "down" if d.budget.pressure else "none"))
117
+ return {"checks": checks, "chain": _chain(d.base, reasons, tier), "effort_note": _effort(tier)}
118
+
119
+
120
+ def _chain(base: str, reasons: list[str], tier) -> list[str]:
121
+ out = [f"Start at {base}"]
122
+ for x in reasons:
123
+ if _MOVE.match(x) or x.startswith(("T4 rule", "capped")):
124
+ out.append(x if len(x) < 140 else x[:137] + "…")
125
+ out.append(f"Final {tier.name}: {tier.model} / {tier.effort}")
126
+ return out
127
+
128
+
129
+ def _effort(tier) -> str:
130
+ return (f"Model and effort come together with the tier: {tier.name} runs {tier.model} at "
131
+ f"{tier.effort} effort, through the {tier.agent} agent.")
132
+
133
+
134
+ def from_trace(row: dict, tier_models: dict) -> dict:
135
+ """Checklist for a record without a stored decision (only the trace signals are known)."""
136
+ t = row.get("trace") if isinstance(row.get("trace"), dict) else {}
137
+ if not t:
138
+ return {"checks": [], "chain": [], "effort_note": ""}
139
+ bumps = list(t.get("bumps") or [])
140
+ final = row.get("tier")
141
+ checks = [
142
+ _check(1, "What kind of task is it?", "the wording of the prompt",
143
+ f"{row.get('class') or '?'} (confidence {t.get('class_conf', '?')}, "
144
+ f"{t.get('class_source', 'rules')})"
145
+ + (f"; matched {_terms(t.get('rules'))}" if t.get("rules") else ""),
146
+ f"Starting point: {t.get('base', '?')}"),
147
+ _check(2, "How big is it?", "size words, explicit steps",
148
+ f"scope {t.get('scope', '?')}" + (f"; {t['steps']} steps" if t.get("steps") else ""),
149
+ "Raises the tier by 1" if "large scope" in bumps else "No change",
150
+ "up" if "large scope" in bumps else "none"),
151
+ _check(3, "How clear and how hard does it sound?", "vague, intermittent or destructive words",
152
+ f"vagueness {t.get('vagueness', '?')}"
153
+ + (f"; hard words {_terms(t.get('hard_terms'))}" if t.get("hard_terms") else "")
154
+ + ("; destructive" if t.get("destructive") else ""),
155
+ "Raises the tier" if any(b.startswith(("vague bug", "hard problem")) for b in bumps)
156
+ else "No change",
157
+ "up" if any(b.startswith(("vague bug", "hard problem")) for b in bumps) else "none"),
158
+ _check(4, "Which code does it touch?", "the code graph",
159
+ "code located" if t.get("located") else "no file could be tied to the prompt",
160
+ "Needed for the risk checks", "none"),
161
+ _check(5, "How risky is that code?", "dependents, complexity, tests, churn",
162
+ f"risk {t.get('risk_level', 'unknown')}"
163
+ + (f" (code-only {t['code_risk']})" if t.get("code_risk") is not None else ""),
164
+ "Raises the tier" if any(b.startswith(("risk high", "complex code", "unclassified"))
165
+ for b in bumps) else "No change",
166
+ "up" if any(b.startswith(("risk high", "complex code", "unclassified"))
167
+ for b in bumps) else "none"),
168
+ _check(6, "Is it a critical or protected area?", "critical paths and project notes",
169
+ "; ".join([*(f"critical path {c}" for c in t.get("critical") or []),
170
+ *(f"notes mark it {m}" for m in t.get("memory_flags") or [])]) or "no",
171
+ "Raises the tier" if any(b.startswith(("critical path", "memory flags")) for b in bumps)
172
+ else "No change",
173
+ "up" if any(b.startswith(("critical path", "memory flags")) for b in bumps) else "none"),
174
+ _check(7, "Does a safety rule force the top tier?", "critical-path and production rules",
175
+ "yes" if t.get("t4") else "no", "Forces T4" if t.get("t4") else "No change",
176
+ "rule" if t.get("t4") else "none"),
177
+ _check(8, "Is the weekly budget under pressure?", "usage from the status line",
178
+ "yes" if t.get("budget_pressure") else "no",
179
+ "Lowers the tier by 1" if t.get("budget_pressure") else "No change",
180
+ "down" if t.get("budget_pressure") else "none"),
181
+ ]
182
+ chain = [f"Start at {t.get('base', '?')}", *[f"+1 {b}" for b in bumps]]
183
+ chain.append(f"Final {final}: {tier_models.get(final, '?').replace('/', ' / ')}")
184
+ return {"checks": checks, "chain": chain, "partial": True,
185
+ "effort_note": f"Model and effort come with the tier: {final} runs "
186
+ f"{tier_models.get(final, '?').replace('/', ' at ')} effort."}