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
@@ -0,0 +1,161 @@
1
+ """Offline calibration from real outcomes (reports only: it never changes routing).
2
+
3
+ export_benchmark turn decided tasks that have a stored prompt into a labelled replay set
4
+ for `scripts/bench_routing.py --prompts FILE`
5
+ fit logistic regression (stdlib) of P(task fails) on the routing signals kept
6
+ in each record's `trace` plus the tier it got, then a shadow comparison:
7
+ which tier would the model have picked, against the rule router
8
+
9
+ Benchmark labels, from one decided task at tier T:
10
+ failure need = the tier above T, cap = top (T was not enough)
11
+ success need = lowest tier that has succeeded for this class x area, cap = the tier above T
12
+ A success proves T was sufficient, not necessary, so these labels catch under-routing well and
13
+ over-routing only where a cheaper tier has its own record.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ import random
19
+
20
+ from ccr.config import TIERS, TOP
21
+ from ccr.history.learn import FAILURE, SUCCESS, tier_counts
22
+
23
+ MIN_TASKS = 30
24
+ MIN_FAILURES = 5
25
+ FOLDS = 5
26
+ RISK_LEVEL = {"low": 0.0, "medium": 0.5, "high": 1.0}
27
+ FEATURES = ("tier", "base", "scope_large", "scope_small", "vagueness", "steps", "class_conf",
28
+ "hard", "destructive", "located", "loc_conf", "code_risk", "risk_level",
29
+ "critical", "memory_flags", "bumps", "n_rules", "t4")
30
+
31
+
32
+ def export_benchmark(records: list[dict], logged: dict[str, dict]) -> list[list]:
33
+ decided = [r for r in records if r.get("tier") in TIERS and r.get("class")
34
+ and r.get("outcome") in SUCCESS | FAILURE]
35
+ out = []
36
+ for r in decided:
37
+ p = (logged.get(str(r.get("id"))) or {}).get("prompt")
38
+ if not p:
39
+ continue
40
+ i = TIERS.index(r["tier"])
41
+ if r["outcome"] in FAILURE:
42
+ need, cap = min(i + 1, TOP), TOP
43
+ else:
44
+ st, _ = tier_counts(decided, r["class"], r.get("area"))
45
+ ok = [TIERS.index(t) for t, (s, _f) in st.items() if s and t in TIERS]
46
+ need, cap = min([i, *ok]), min(i + 1, TOP)
47
+ out.append([p, TIERS[need], TIERS[cap]])
48
+ return out
49
+
50
+
51
+ def _num(v) -> float:
52
+ return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else 0.0
53
+
54
+
55
+ def features(r: dict, tier: str | None = None) -> list[float]:
56
+ t = r.get("trace") if isinstance(r.get("trace"), dict) else {}
57
+ base = t.get("base") if t.get("base") in TIERS else r.get("tier")
58
+ return [TIERS.index(tier or r["tier"]) / TOP, TIERS.index(base) / TOP if base in TIERS else 0.0,
59
+ float(t.get("scope") == "large"), float(t.get("scope") == "small"),
60
+ _num(t.get("vagueness")), _num(t.get("steps")), _num(t.get("class_conf")),
61
+ float(bool(t.get("hard"))), float(bool(t.get("destructive"))),
62
+ float(bool(t.get("located"))), _num(t.get("loc_conf")), _num(t.get("code_risk")),
63
+ RISK_LEVEL.get(t.get("risk_level"), 0.0), float(bool(t.get("critical"))),
64
+ float(len(t.get("memory_flags") or [])), float(len(t.get("bumps") or [])),
65
+ float(len(t.get("rules") or [])), float(bool(t.get("t4")))]
66
+
67
+
68
+ def _sigmoid(z: float) -> float:
69
+ return 1 / (1 + math.exp(-max(-30.0, min(30.0, z))))
70
+
71
+
72
+ def _train(X: list[list[float]], y: list[int], l2: float = 0.05, steps: int = 600,
73
+ lr: float = 0.3) -> list[float]:
74
+ """Batch gradient descent; w[0] is the bias. Features are used as given (already 0-1ish)."""
75
+ n, m = len(X), len(X[0])
76
+ w = [0.0] * (m + 1)
77
+ for _ in range(steps):
78
+ g = [0.0] * (m + 1)
79
+ for xi, yi in zip(X, y, strict=True):
80
+ e = _sigmoid(w[0] + sum(a * b for a, b in zip(w[1:], xi, strict=True))) - yi
81
+ g[0] += e
82
+ for j in range(m):
83
+ g[j + 1] += e * xi[j]
84
+ for j in range(m + 1):
85
+ w[j] -= lr * (g[j] / n + (l2 * w[j] if j else 0.0))
86
+ return w
87
+
88
+
89
+ def _predict(w: list[float], x: list[float]) -> float:
90
+ return _sigmoid(w[0] + sum(a * b for a, b in zip(w[1:], x, strict=True)))
91
+
92
+
93
+ def _auc(scores: list[float], y: list[int]) -> float | None:
94
+ pos = [s for s, v in zip(scores, y, strict=True) if v]
95
+ neg = [s for s, v in zip(scores, y, strict=True) if not v]
96
+ if not pos or not neg:
97
+ return None
98
+ wins = sum((p > q) + 0.5 * (p == q) for p in pos for q in neg)
99
+ return wins / (len(pos) * len(neg))
100
+
101
+
102
+ def fit(records: list[dict], max_fail_prob: float = 0.2, seed: int = 7) -> dict:
103
+ rows = [r for r in records if r.get("tier") in TIERS and isinstance(r.get("trace"), dict)
104
+ and r.get("outcome") in SUCCESS | FAILURE]
105
+ y = [int(r["outcome"] in FAILURE) for r in rows]
106
+ n, fails = len(rows), sum(y)
107
+ res = {"tasks": n, "failures": fails, "ready": False, "min_tasks": MIN_TASKS,
108
+ "min_failures": MIN_FAILURES}
109
+ if n < MIN_TASKS or fails < MIN_FAILURES or n - fails < MIN_FAILURES:
110
+ res["note"] = (f"need at least {MIN_TASKS} decided tasks with a routing trace and "
111
+ f"{MIN_FAILURES} each of successes and failures (have {n}, {fails} failed); "
112
+ f"keep using ccr feedback good|bad and try again")
113
+ return res
114
+ X = [features(r) for r in rows]
115
+ idx = list(range(n))
116
+ random.Random(seed).shuffle(idx)
117
+ cv = [0.0] * n
118
+ for k in range(FOLDS):
119
+ test = set(idx[k::FOLDS])
120
+ tr = [i for i in idx if i not in test]
121
+ if not any(y[i] for i in tr) or all(y[i] for i in tr):
122
+ continue
123
+ w = _train([X[i] for i in tr], [y[i] for i in tr])
124
+ for i in test:
125
+ cv[i] = _predict(w, X[i])
126
+ w = _train(X, y)
127
+ base = fails / n
128
+ brier = sum((c - v) ** 2 for c, v in zip(cv, y, strict=True)) / n
129
+ brier0 = sum((base - v) ** 2 for v in y) / n
130
+ shadow = {"same": 0, "cheaper": 0, "stronger": 0}
131
+ for r in rows:
132
+ picked = next((t for t in TIERS if _predict(w, features(r, t)) <= max_fail_prob),
133
+ TIERS[TOP])
134
+ d = TIERS.index(picked) - TIERS.index(r["tier"])
135
+ shadow["same" if d == 0 else "cheaper" if d < 0 else "stronger"] += 1
136
+ res.update(ready=True, fail_rate=round(base, 3), cv_auc=_auc(cv, y), cv_brier=round(brier, 4),
137
+ baseline_brier=round(brier0, 4), max_fail_prob=max_fail_prob, shadow=shadow,
138
+ weights=sorted(({"feature": f, "weight": round(wt, 3)}
139
+ for f, wt in zip(FEATURES, w[1:], strict=True)),
140
+ key=lambda d: -abs(d["weight"])))
141
+ res["cv_auc"] = None if res["cv_auc"] is None else round(res["cv_auc"], 3)
142
+ res["useful"] = bool(res["cv_auc"] and res["cv_auc"] >= 0.65 and brier < brier0)
143
+ return res
144
+
145
+
146
+ def format_text(res: dict) -> list[str]:
147
+ out = [f"ccr calibrate: {res['tasks']} decided task(s) with a trace, {res['failures']} failed"]
148
+ if not res["ready"]:
149
+ return out + [f" {res['note']}"]
150
+ out.append(f" cross-validated AUC {res['cv_auc']} (0.5 is chance); Brier {res['cv_brier']} vs "
151
+ f"{res['baseline_brier']} for always guessing the base rate {res['fail_rate']:.0%}")
152
+ out.append(" verdict: " + ("the signals predict failures better than chance; shadow picks below "
153
+ "are worth reviewing" if res["useful"] else
154
+ "no better than guessing yet; do not change rules from this"))
155
+ s = res["shadow"]
156
+ out.append(f" shadow router (tier with predicted failure <= {res['max_fail_prob']:.0%}): "
157
+ f"same tier {s['same']}, cheaper {s['cheaper']}, stronger {s['stronger']}")
158
+ out.append(" strongest signals (+ means more failures):")
159
+ out += [f" {w['weight']:+.2f} {w['feature']}" for w in res["weights"][:8]]
160
+ out.append(" report only: routing is unchanged")
161
+ return out
@@ -0,0 +1,374 @@
1
+ """`ccr dashboard`: a self-contained HTML report over resolved history.
2
+
3
+ One file, no server, no network: the data is embedded as JSON and drawn with inline SVG.
4
+ Prompt text and the decision process appear only when `hooks.store_prompts` was on
5
+ (.ccr/local/prompts.jsonl); otherwise each task shows the signals kept in history.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import time
11
+ from pathlib import Path
12
+
13
+ from ccr.config import TIERS
14
+ from ccr.history import prompts as prompt_log
15
+ from ccr.history import shadow, why
16
+ from ccr.history.learn import FAILURE, SUCCESS
17
+ from ccr.history.stats import compute
18
+
19
+ TASK_FIELDS = ("id", "ts", "tier", "class", "area", "outcome", "tokens", "source", "escalated_to")
20
+
21
+
22
+ def _task_row(r: dict, logged: dict) -> dict:
23
+ row = {k: r.get(k) for k in TASK_FIELDS}
24
+ row["full_id"] = str(r.get("id") or "")
25
+ row["trace"] = r.get("trace") if isinstance(r.get("trace"), dict) else None
26
+ row["confidence"] = r.get("confidence")
27
+ row["risk"] = r.get("risk")
28
+ row["decision"] = logged.get(row["full_id"])
29
+ d = row["decision"]
30
+ row["why"] = d["why"] if d and d.get("why") else None
31
+ o = r.get("outcome")
32
+ row["result"] = "ok" if o in SUCCESS else "fail" if o in FAILURE else "unknown"
33
+ row["id"] = str(row["id"] or "")[:8]
34
+ return row
35
+
36
+
37
+ def build_payload(records: list[dict], cfg, root: Path) -> dict:
38
+ s = compute(records, cfg)
39
+ tasks = [r for r in records if r.get("tier") in TIERS]
40
+ tasks.sort(key=lambda r: r.get("ts") or 0)
41
+ s["project"] = root.name
42
+ s["generated"] = int(time.time())
43
+ s["tier_order"] = list(TIERS)
44
+ s["tier_models"] = {t: f"{cfg.tier(t).model}/{cfg.tier(t).effort}" for t in TIERS}
45
+ logged = prompt_log.read(root)
46
+ s["shadow"] = shadow.summarize(shadow.read(root))
47
+ s["pricing"] = dict(cfg["pricing"])
48
+ s["tier_family"] = {t: cfg.tier(t).model for t in TIERS}
49
+ s["task_rows"] = [_task_row(r, logged) for r in tasks]
50
+ for row in s["task_rows"]:
51
+ if row["why"] is None:
52
+ row["why"] = why.from_trace(row, s["tier_models"])
53
+ s["prompts_logged"] = len(logged)
54
+ s["store_prompts"] = bool(cfg["hooks"]["store_prompts"])
55
+ return s
56
+
57
+
58
+ def render(payload: dict) -> str:
59
+ data = json.dumps(payload, default=str).replace("</", "<\\/")
60
+ return _TEMPLATE.replace("__DATA__", data)
61
+
62
+
63
+ def write(root: Path, records: list[dict], cfg, out: Path) -> Path:
64
+ html = render(build_payload(records, cfg, root))
65
+ out.parent.mkdir(parents=True, exist_ok=True)
66
+ out.write_text(html, encoding="utf-8")
67
+ return out
68
+
69
+
70
+ _TEMPLATE = r"""<!doctype html>
71
+ <html lang="en"><head><meta charset="utf-8">
72
+ <meta name="viewport" content="width=device-width,initial-scale=1">
73
+ <title>ccr Dashboard</title>
74
+ <style>
75
+ :root{color-scheme:light;--bg:#f4f5fa;--bg2:#eaecf6;--surface:#ffffff;--ink:#12131a;--ink2:#4a4d5e;--muted:#8a8da0;
76
+ --line:#e6e8f1;--shadow:0 1px 2px rgba(20,22,40,.04),0 8px 24px -12px rgba(20,22,60,.12);
77
+ --accent:#5b5bf0;--accent2:#8b5cf6;--good:#0f9d63;--bad:#d9433f;--warn:#c27a0a;
78
+ --t0:#cfe0fb;--t1:#a3c4f5;--t2:#6f9eec;--t2h:#4a7fdf;--t3:#3158b8;--t4:#1d2f78;
79
+ --c1:#5b5bf0;--c2:#f0713a;--c3:#17b585;--hero:linear-gradient(120deg,#4f46e5 0%,#7c3aed 55%,#c026d3 100%)}
80
+ @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){color-scheme:dark;--bg:#0c0d14;--bg2:#12131d;--surface:#161824;--ink:#eef0f8;--ink2:#b4b8cc;--muted:#7d8198;--line:#262a3b;--shadow:0 1px 2px rgba(0,0,0,.3),0 10px 30px -14px rgba(0,0,0,.6);--accent:#7c7cff;--accent2:#a78bfa;--good:#34d399;--bad:#f87171;--warn:#fbbf24;
81
+ --t0:#26405f;--t1:#33598a;--t2:#4478b8;--t2h:#5f93d2;--t3:#86b1e6;--t4:#bcd6f6;--c1:#7c7cff;--c2:#f0713a;--c3:#2dd4a0;--hero:linear-gradient(120deg,#312e81 0%,#5b21b6 55%,#86198f 100%)}}
82
+ :root[data-theme="dark"]{color-scheme:dark;--bg:#0c0d14;--bg2:#12131d;--surface:#161824;--ink:#eef0f8;--ink2:#b4b8cc;--muted:#7d8198;--line:#262a3b;--shadow:0 1px 2px rgba(0,0,0,.3),0 10px 30px -14px rgba(0,0,0,.6);--accent:#7c7cff;--accent2:#a78bfa;--good:#34d399;--bad:#f87171;--warn:#fbbf24;
83
+ --t0:#26405f;--t1:#33598a;--t2:#4478b8;--t2h:#5f93d2;--t3:#86b1e6;--t4:#bcd6f6;--c1:#7c7cff;--c2:#f0713a;--c3:#2dd4a0;--hero:linear-gradient(120deg,#312e81 0%,#5b21b6 55%,#86198f 100%)}
84
+ *{box-sizing:border-box}html{scroll-behavior:smooth}
85
+ body{margin:0;background:radial-gradient(1200px 500px at 85% -10%,var(--bg2),transparent 60%),var(--bg);color:var(--ink);font:14px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;-webkit-font-smoothing:antialiased}
86
+ .wrap{max-width:1240px;margin:0 auto;padding:20px 20px 64px}
87
+ header{background:var(--hero);color:#fff;border-radius:20px;padding:26px 28px;margin-bottom:20px;display:flex;flex-wrap:wrap;gap:16px;align-items:flex-end;justify-content:space-between;box-shadow:0 18px 40px -20px rgba(91,70,240,.55);position:relative;overflow:hidden}
88
+ header:after{content:"";position:absolute;right:-60px;top:-80px;width:280px;height:280px;border-radius:50%;background:radial-gradient(circle,rgba(255,255,255,.22),transparent 65%);pointer-events:none}
89
+ h1{margin:0;font-size:28px;font-weight:750;letter-spacing:-.6px}header .sub{color:rgba(255,255,255,.82);margin-top:4px}
90
+ h2{margin:0 0 2px;font-size:15px;font-weight:650;letter-spacing:-.1px}.sub{color:var(--ink2);font-size:13px}
91
+ .ctl{display:flex;gap:8px;align-items:center;flex-wrap:wrap;position:relative;z-index:1}
92
+ header label.sub{color:rgba(255,255,255,.85)}
93
+ select,button,input[type=search]{background:var(--surface);color:var(--ink);border:1px solid var(--line);border-radius:10px;padding:7px 12px;font:inherit;cursor:pointer;transition:border-color .15s,box-shadow .15s,transform .05s}
94
+ select:hover,button:hover:not(:disabled),input[type=search]:hover{border-color:var(--accent)}
95
+ select:focus-visible,button:focus-visible,input:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
96
+ button:active:not(:disabled){transform:translateY(1px)}
97
+ header select,header button{background:rgba(255,255,255,.16);color:#fff;border-color:rgba(255,255,255,.28);backdrop-filter:blur(6px)}
98
+ header select option{color:#111}
99
+ input[type=search]{min-width:240px;cursor:text}
100
+ .tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:14px;margin-bottom:16px}
101
+ .tile,.card{background:var(--surface);border:1px solid var(--line);border-radius:16px;padding:16px 18px;box-shadow:var(--shadow)}
102
+ .tile{position:relative;overflow:hidden}.tile:before{content:"";position:absolute;left:0;top:0;bottom:0;width:4px;background:linear-gradient(var(--accent),var(--accent2))}
103
+ .tile:nth-child(2):before{background:linear-gradient(var(--good),var(--c3))}.tile:nth-child(3):before{background:linear-gradient(#0ea5e9,#38bdf8)}
104
+ .tile:nth-child(4):before{background:linear-gradient(var(--warn),#f59e0b)}.tile:nth-child(5):before{background:linear-gradient(var(--c2),#f59e0b)}
105
+ .tile .v{font-size:30px;font-weight:750;letter-spacing:-1px;margin-top:2px}.tile .l{color:var(--ink2);font-size:11.5px;text-transform:uppercase;letter-spacing:.07em;font-weight:600}
106
+ .tile .n{color:var(--muted);font-size:12px;margin-top:2px}
107
+ .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(340px,1fr));gap:14px;margin-bottom:14px}.wide{grid-column:1/-1}
108
+ .card h2+.sub{margin-bottom:8px}
109
+ svg{display:block;width:100%;height:auto;overflow:visible}svg text{fill:var(--ink2);font:11px Inter,system-ui,sans-serif}
110
+ svg rect.bar{transform-box:fill-box;transform-origin:left center;animation:grow .55s cubic-bezier(.2,.8,.2,1) both}
111
+ svg rect.rise{transform-box:fill-box;transform-origin:center bottom;animation:rise .55s cubic-bezier(.2,.8,.2,1) both}
112
+ @keyframes grow{from{transform:scaleX(0)}}@keyframes rise{from{transform:scaleY(0)}}
113
+ @media (prefers-reduced-motion:reduce){svg rect.bar,svg rect.rise{animation:none}}
114
+ svg rect:hover{filter:brightness(1.12)}
115
+ .legend{display:flex;flex-wrap:wrap;gap:14px;margin:10px 0 0;font-size:12px;color:var(--ink2)}
116
+ .sw{display:inline-block;width:10px;height:10px;border-radius:3px;margin-right:6px;vertical-align:-1px}
117
+ table{width:100%;border-collapse:collapse;font-size:13px}th,td{text-align:left;padding:8px 10px;border-bottom:1px solid var(--line)}
118
+ th{color:var(--ink2);font-weight:600;font-size:11.5px;text-transform:uppercase;letter-spacing:.05em}td.n,th.n{text-align:right;font-variant-numeric:tabular-nums}
119
+ .pill{display:inline-block;padding:2px 10px;border-radius:99px;font-size:12px;font-weight:600;border:1.5px solid var(--line);background:var(--bg)}
120
+ .ok{color:var(--good)}.fail{color:var(--bad)}.unk{color:var(--muted)}
121
+ #tip{position:fixed;pointer-events:none;background:#1b1d2b;color:#fff;padding:7px 10px;border-radius:9px;font-size:12px;opacity:0;transition:opacity .1s;z-index:9;max-width:270px;box-shadow:0 8px 24px rgba(0,0,0,.35)}
122
+ .empty{color:var(--muted);padding:28px 0;text-align:center}ul.tune{margin:8px 0 0;padding-left:18px;color:var(--ink2)}ul.tune li{margin:3px 0}
123
+ .note{color:var(--muted);font-size:12px;margin-top:10px}code{background:var(--bg);border:1px solid var(--line);border-radius:6px;padding:0 5px;font-size:12px}
124
+ .pager{display:flex;gap:14px;align-items:center;justify-content:center;margin-top:14px}button:disabled{opacity:.4;cursor:default}
125
+ details.dec{border:1px solid var(--line);border-radius:14px;margin:0 0 10px;background:var(--surface);transition:box-shadow .15s,border-color .15s}
126
+ details.dec:hover{box-shadow:var(--shadow)}details.dec[open]{border-color:var(--accent);box-shadow:var(--shadow)}
127
+ details.dec>summary{list-style:none;cursor:pointer;display:grid;grid-template-columns:auto auto 1fr auto auto;gap:12px;align-items:center;padding:11px 14px}
128
+ details.dec>summary::-webkit-details-marker{display:none}
129
+ .pr{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--ink)}.pr.dim{color:var(--muted);font-style:italic}
130
+ .body{padding:6px 18px 16px;border-top:1px solid var(--line)}.body h3{margin:14px 0 6px;font-size:11.5px;text-transform:uppercase;letter-spacing:.07em;color:var(--ink2)}
131
+ pre.pt{white-space:pre-wrap;word-break:break-word;background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:12px;margin:0;font:12.5px/1.5 ui-monospace,"SF Mono",Menlo,monospace;max-height:220px;overflow:auto}
132
+ ol.steps{margin:0;padding-left:20px}ol.steps li{margin:3px 0}
133
+ .kv{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:4px 16px;color:var(--ink2)}.kv b{color:var(--ink)}
134
+ .banner{background:var(--bg);border:1px dashed var(--line);border-radius:12px;padding:10px 14px;color:var(--ink2);font-size:13px;margin-bottom:12px}
135
+ .chain{display:flex;flex-wrap:wrap;gap:6px;align-items:center;margin:2px 0 10px}.chain span{background:var(--bg);border:1px solid var(--line);border-radius:9px;padding:4px 10px;font-size:12.5px;color:var(--ink)}
136
+ .chain i{font-style:normal;color:var(--muted)}.chain span:last-child{background:linear-gradient(120deg,var(--accent),var(--accent2));border-color:transparent;color:#fff;font-weight:650}
137
+ .chk{display:grid;grid-template-columns:28px 1fr auto;gap:2px 12px;padding:10px 0;border-top:1px solid var(--line)}.chk:first-of-type{border-top:0}
138
+ .chk .no{grid-row:span 3;width:24px;height:24px;border-radius:50%;background:var(--bg);border:1px solid var(--line);text-align:center;font-size:12px;line-height:22px;color:var(--ink2);font-weight:600}
139
+ .chk .q{font-weight:650}.chk .lk{color:var(--muted);font-size:12px;grid-column:2}.chk .fd{grid-column:2;color:var(--ink)}
140
+ .eff{grid-column:3;grid-row:1;align-self:start;white-space:nowrap;font-size:12px;border-radius:99px;padding:2px 11px;border:1px solid var(--line);color:var(--ink2);background:var(--bg)}
141
+ .eff.up{border-color:var(--warn);color:var(--warn);font-weight:650}.eff.down{border-color:var(--good);color:var(--good);font-weight:650}.eff.rule{border-color:var(--bad);color:var(--bad);font-weight:650}
142
+ .effnote{margin-top:8px;color:var(--ink2)}details.raw{margin-top:10px}details.raw summary{cursor:pointer;color:var(--muted);font-size:12px}
143
+ @media (max-width:640px){.wrap{padding:12px 12px 48px}header{padding:20px 18px}h1{font-size:23px}.grid{grid-template-columns:1fr}details.dec>summary{grid-template-columns:auto 1fr auto}details.dec>summary .hide-s{display:none}.chk{grid-template-columns:28px 1fr}.eff{grid-column:2;grid-row:auto;justify-self:start;margin-top:2px}}
144
+ .card>h2.sec{display:flex;align-items:center;gap:8px;cursor:pointer;user-select:none;border-radius:8px}
145
+ .card>h2.sec:hover{color:var(--accent)}.card>h2.sec:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
146
+ .card>h2.sec:before{content:"";width:7px;height:7px;border-right:2px solid currentColor;border-bottom:2px solid currentColor;transform:rotate(45deg);transition:transform .18s;margin:-3px 4px 0 2px;flex:none}
147
+ .card.closed>h2.sec:before{transform:rotate(-45deg)}.card.closed .sec-body{display:none}.card.closed>h2.sec{margin-bottom:0}
148
+ .sec-body{margin-top:2px}
149
+ </style></head><body><div class="wrap">
150
+ <header><div><h1 id="title">ccr Dashboard</h1><div class="sub" id="meta"></div></div>
151
+ <input id="assume" type="hidden" value="50000"><div class="ctl"><label class="sub">Range <select id="range"><option value="0">All time</option><option value="7">7 days</option><option value="30">30 days</option><option value="90">90 days</option></select></label>
152
+ <button id="collapse" type="button">Collapse all</button><button id="expand" type="button">Expand all</button><button id="theme" type="button">Toggle theme</button></div></header>
153
+ <div class="tiles" id="tiles"></div>
154
+ <div class="grid">
155
+ <section class="card wide"><h2>Tasks per day, by tier</h2><div class="sub">Darker means a stronger model</div><div id="daily"></div><div class="legend" id="tierLegend"></div></section>
156
+ <section class="card"><h2>Success rate by tier</h2><div class="sub">Decided tasks only</div><div id="succ"></div></section>
157
+ <section class="card"><h2>Estimated cost</h2><div class="sub">Tokens priced by <code>pricing:</code>; an estimate</div><div id="cost"></div></section>
158
+ <section class="card"><h2 id="areaTitle">Tokens by area</h2><div id="area"></div></section>
159
+ <section class="card"><h2>Task class &times; tier</h2><div class="sub">Task counts</div><div id="heat"></div></section>
160
+ <section class="card wide"><h2>Routing health</h2><div id="health"></div></section>
161
+ <section class="card wide"><h2>Routing decisions</h2><div class="sub">Each task: the prompt, the tier chosen, and how ccr got there. Click a row to expand.</div>
162
+ <div class="ctl" style="margin:8px 0"><input id="q" type="search" placeholder="Search prompt, class, area, id" aria-label="Search"><select id="fres"><option value="">All results</option><option>ok</option><option>fail</option><option>unknown</option></select>
163
+ <select id="ftier"><option value="">All tiers</option></select><select id="psize"><option>10</option><option>25</option><option>50</option></select></div>
164
+ <div id="banner"></div><div id="tasks"></div><div class="pager"><button id="prev" type="button">&larr; Newer</button><span id="pginfo" class="sub"></span><button id="next" type="button">Older &rarr;</button></div></section>
165
+ </div><div class="note">Generated by <code>ccr dashboard</code>. Data comes from <code>.ccr/history.jsonl</code>; prompts appear only if <code>hooks.store_prompts</code> is on (local file, never committed).</div>
166
+ <div id="tip"></div></div>
167
+ <script>
168
+ const D=__DATA__;
169
+ const $=s=>document.querySelector(s),NS='http://www.w3.org/2000/svg';
170
+ const tierVar=t=>'var(--'+t.toLowerCase()+')';
171
+ const fk=n=>n>=1e6?(n/1e6).toFixed(2)+'M':n>=1e3?(n/1e3).toFixed(1)+'k':String(Math.round(n));
172
+ const pct=v=>v==null?'-':Math.round(v*100)+'%';
173
+ const money=v=>'$'+(v>=100?v.toFixed(0):v.toFixed(2));
174
+ const esc=s=>String(s??'').replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
175
+ const fmtT=t=>new Date(t*1000).toLocaleString([], {month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'});
176
+ const tip=$('#tip');
177
+ function showTip(e,html){tip.innerHTML=html;tip.style.opacity=1;const x=Math.min(e.clientX+14,innerWidth-270);tip.style.left=x+'px';tip.style.top=(e.clientY+14)+'px'}
178
+ function hideTip(){tip.style.opacity=0}
179
+ function el(n,a,p){const e=document.createElementNS(NS,n);for(const k in a)e.setAttribute(k,a[k]);if(p)p.appendChild(e);return e}
180
+ function txt(p,x,y,s,a){const t=el('text',Object.assign({x,y},a||{}),p);t.textContent=s;return t}
181
+ function hover(node,html){node.addEventListener('mousemove',e=>showTip(e,html));node.addEventListener('mouseleave',hideTip)}
182
+ function svg(w,h){const s=document.createElementNS(NS,'svg');s.setAttribute('viewBox','0 0 '+w+' '+h);return s}
183
+ function mount(sel,node){const m=$(sel);m.innerHTML='';m.appendChild(node)}
184
+ function empty(sel,msg){$(sel).innerHTML='<div class="empty">'+(msg||'No data in this range')+'</div>'}
185
+
186
+ let rows=[];
187
+ function inRange(){const d=+$('#range').value;const cut=d?Date.now()/1000-d*86400:0;rows=D.task_rows.filter(r=>(r.ts||0)>=cut)}
188
+ const decided=r=>r.result!=='unknown';
189
+
190
+ function price(model){const p=D.pricing||{};for(const k in p)if(String(model).includes(k))return p[k];return 0}
191
+ function assumed(){return +($('#assume')?$('#assume').value:50000)}
192
+ function measured(){return rows.filter(r=>(r.tokens||0)>0).length}
193
+ function est(rs){
194
+ const a=assumed();let routed=0,opus=0,sonnet=0,dr=0,do_=0,dn=0,dok=0;
195
+ rs.forEach(r=>{const tok=(r.tokens||0)>0?r.tokens:a,c=tok*price(D.tier_family[r.tier])/1e6,o=tok*price('opus')/1e6;
196
+ routed+=c;opus+=o;sonnet+=tok*price('sonnet')/1e6;
197
+ if(r.result!=='unknown'){dn++;do_+=o;dr+=c;if(r.result==='ok')dok++}});
198
+ return {routed,opus,sonnet,perOk:dok?dr/dok:null,opusPer:dn?do_/dn:null,so:opus?1-routed/opus:null,ss:sonnet?1-routed/sonnet:null}}
199
+ function tiles(){
200
+ const n=rows.length,ok=rows.filter(r=>r.result==='ok').length,bad=rows.filter(r=>r.result==='fail').length;
201
+ const m=measured(),tok=rows.reduce((a,r)=>a+(r.tokens||0),0),esc_=rows.filter(r=>r.escalated_to).length;
202
+ const sr=ok+bad?ok/(ok+bad):null,e=est(rows);
203
+ const T=[['Tasks',n,(D.runs||0)+' headless run(s)'],['Success rate',pct(sr),ok+' ok / '+bad+' failed / '+(n-ok-bad)+' unknown'],
204
+ ['Tokens',m?fk(tok):'not measured',m?(m===n?fk(tok/n)+' per task':m+' of '+n+' tasks measured'):'no session transcript was available'],
205
+ ['Escalated',n?pct(esc_/n):'-',esc_+' retried one tier up'],
206
+ ['Saved vs all-Opus',e.so==null?'-':pct(e.so),money(e.routed)+' vs '+money(e.opus)+(m===n?'':' (assumes '+fk(assumed())+' tokens/task where unmeasured)')]];
207
+ $('#tiles').innerHTML=T.map(t=>'<div class="tile"><div class="l">'+t[0]+'</div><div class="v"'+(t[1]==='not measured'?' style="font-size:18px;color:var(--muted)"':'')+'>'+t[1]+'</div><div class="n">'+t[2]+'</div></div>').join('');
208
+ }
209
+
210
+ function daily(){
211
+ if(!rows.length)return empty('#daily');
212
+ const day=ts=>{const d=new Date(ts*1000);return d.getFullYear()+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+String(d.getDate()).padStart(2,'0')};
213
+ const m={};rows.forEach(r=>{const k=day(r.ts||0);(m[k]=m[k]||{})[r.tier]=(m[k][r.tier]||0)+1});
214
+ const days=Object.keys(m).sort(),W=1100,H=240,L=34,B=28,T=10,pw=W-L-8,ph=H-B-T;
215
+ const tot=d=>Object.values(m[d]).reduce((a,b)=>a+b,0),mx=Math.max(...days.map(tot));
216
+ const s=svg(W,H);
217
+ for(let i=0;i<=4;i++){const v=Math.round(mx*i/4),y=T+ph-ph*i/4;el('line',{x1:L,x2:W-8,y1:y,y2:y,stroke:'var(--line)'},s);txt(s,L-6,y+4,v,{'text-anchor':'end'})}
218
+ const bw=Math.min(48,pw/days.length*.7),step=pw/days.length;
219
+ days.forEach((d,i)=>{let y=T+ph;const x=L+step*i+(step-bw)/2;
220
+ D.tier_order.forEach(t=>{const c=m[d][t];if(!c)return;const h=ph*c/mx;y-=h;
221
+ const r=el('rect',{x,y:y+1,width:bw,height:Math.max(h-2,1),rx:4,fill:tierVar(t),class:'rise'},s);
222
+ hover(r,'<b>'+d+'</b><br>'+t+' ('+D.tier_models[t]+'): '+c+' task'+(c>1?'s':''))});
223
+ if(days.length<=14||i%Math.ceil(days.length/12)===0)txt(s,x+bw/2,H-8,d.slice(5),{'text-anchor':'middle'})});
224
+ mount('#daily',s);
225
+ $('#tierLegend').innerHTML=D.tier_order.filter(t=>rows.some(r=>r.tier===t)).map(t=>'<span><i class="sw" style="background:'+tierVar(t)+'"></i>'+t+' '+D.tier_models[t]+'</span>').join('');
226
+ }
227
+
228
+ function hbars(sel,items,fmt,color){
229
+ if(!items.length)return empty(sel);
230
+ const W=420,rh=30,H=items.length*rh+4,L=150,mx=Math.max(...items.map(i=>i.v),1e-9),s=svg(W,H);
231
+ items.forEach((it,i)=>{const y=i*rh+4,w=Math.max((W-L-52)*it.v/mx,it.v>0?3:0);
232
+ txt(s,L-8,y+14,it.k.length>26?it.k.slice(0,25)+'…':it.k,{'text-anchor':'end'});
233
+ const r=el('rect',{x:L,y,width:w,height:18,rx:6,fill:it.c||color,class:'bar'},s);
234
+ txt(s,L+w+6,y+14,fmt(it.v),{});hover(r,'<b>'+esc(it.k)+'</b><br>'+(it.tip||fmt(it.v)))});
235
+ mount(sel,s)}
236
+
237
+ function succ(){
238
+ const items=D.tier_order.map(t=>{const rs=rows.filter(r=>r.tier===t&&decided(r));if(!rs.length)return null;
239
+ const ok=rs.filter(r=>r.result==='ok').length;return {k:t+' · '+D.tier_models[t],v:ok/rs.length,c:tierVar(t),tip:ok+' of '+rs.length+' decided tasks succeeded'}}).filter(Boolean);
240
+ hbars('#succ',items,pct,'var(--c1)')}
241
+
242
+ function cost(){
243
+ if(!rows.length)return empty('#cost');
244
+ const e=est(rows),m=measured(),n=rows.length;
245
+ const items=[{k:'Routed (ccr)',v:e.routed,c:'var(--c1)'},{k:'All Sonnet',v:e.sonnet,c:'var(--c3)'},{k:'All Opus',v:e.opus,c:'var(--c2)'}];
246
+ hbars('#cost',items,money,'var(--c1)');
247
+ const d=document.createElement('div');d.className='note';
248
+ d.innerHTML=(m<n?'<label>Assumed tokens per unmeasured task <select id="assume2"><option>20000</option><option>50000</option><option>100000</option><option>200000</option></select></label><br>':'')+
249
+ 'Saved '+pct(e.so)+' vs all-Opus, '+pct(e.ss)+' vs all-Sonnet (negative means routing cost more).'+
250
+ (e.perOk!=null?'<br>Per success: '+money(e.perOk)+' routed vs '+money(e.opusPer)+' all-Opus.':'')+
251
+ '<br>'+(m===n?'Estimate: measured tokens priced by <code>pricing:</code>.':(m?m+' of '+n+' tasks have measured tokens; the rest use the assumption.':'No tokens were measured, so every task uses the assumption: this shows the relative cost of the tier mix, not real spend.'));
252
+ $('#cost').appendChild(d);
253
+ const sel=$('#assume2');if(sel){sel.value=String(assumed());sel.onchange=()=>{$('#assume').value=sel.value;tiles();cost()}}}
254
+
255
+ function area(){
256
+ const m={};rows.forEach(r=>{const k=r.area||'*';m[k]=m[k]||{t:0,n:0};m[k].t+=r.tokens||0;m[k].n++});
257
+ const byTok=rows.some(r=>(r.tokens||0)>0);
258
+ $('#areaTitle').textContent=byTok?'Tokens by area':'Tasks by area';
259
+ const items=Object.entries(m).sort((a,b)=>byTok?b[1].t-a[1].t:b[1].n-a[1].n).slice(0,10)
260
+ .map(([k,v])=>({k,v:byTok?v.t:v.n,tip:v.n+' task(s)'+(byTok?', '+fk(v.t)+' tokens':'')}));
261
+ hbars('#area',items,byTok?fk:String,'var(--c1)')}
262
+
263
+ function heat(){
264
+ const cls=[...new Set(rows.map(r=>r.class||'?'))].sort(),ts=D.tier_order.filter(t=>rows.some(r=>r.tier===t));
265
+ if(!cls.length)return empty('#heat');
266
+ const cw=72,rh=28,L=88,W=L+cw*ts.length+4,H=rh*cls.length+42,s=svg(W,H);
267
+ const cnt={};rows.forEach(r=>{const k=(r.class||'?')+'|'+r.tier;cnt[k]=(cnt[k]||0)+1});
268
+ const mx=Math.max(...Object.values(cnt));
269
+ ts.forEach((t,j)=>{txt(s,L+cw*j+cw/2,13,t,{'text-anchor':'middle',style:'fill:var(--ink);font-weight:600'});txt(s,L+cw*j+cw/2,26,(D.tier_models[t]||'').replace('/',' '),{'text-anchor':'middle',style:'font-size:9px'})});
270
+ cls.forEach((c,i)=>{txt(s,L-8,42+rh*i+17,c,{'text-anchor':'end'});
271
+ ts.forEach((t,j)=>{const v=cnt[c+'|'+t]||0;
272
+ const r=el('rect',{x:L+cw*j+1,y:38+rh*i+1,width:cw-2,height:rh-2,rx:4,fill:v?'var(--c1)':'var(--line)','fill-opacity':v?.18+.82*v/mx:.35},s);
273
+ if(v){txt(s,L+cw*j+cw/2,38+rh*i+18,v,{'text-anchor':'middle',style:'fill:var(--ink);font-weight:600'});hover(r,'<b>'+c+' at '+t+'</b><br>'+v+' task(s)')}})});
274
+ mount('#heat',s)}
275
+
276
+ function health(){
277
+ const mis=D.misroutes||{},L=D.learning||[];let h='';
278
+ if(mis.decided){h+='<div class="sub">Over-routed '+mis.over+'/'+mis.decided+' ('+pct(mis.over_rate)+') · Under-routed '+mis.under+'/'+mis.decided+' ('+pct(mis.under_rate)+')</div>';
279
+ if(mis.suggestions&&mis.suggestions.length)h+='<ul class="tune">'+mis.suggestions.map(x=>'<li>'+esc(x)+'</li>').join('')+'</ul>';
280
+ if(mis.items&&mis.items.length)h+='<table style="margin-top:10px"><tr><th>Task</th><th>Kind</th><th>Tier</th><th>Class</th><th>Area</th><th>Why</th></tr>'+mis.items.slice(0,15).map(i=>'<tr><td>'+esc(String(i.id||'').slice(0,8))+'</td><td>'+i.kind+'</td><td>'+i.tier+' <span class="sub">'+esc((D.tier_models[i.tier]||'').replace('/',' '))+'</span></td><td>'+esc(i.class)+'</td><td>'+esc(i.area||'*')+'</td><td>'+esc(i.why)+'</td></tr>').join('')+'</table>'+(mis.items.length>15?'<div class="note">Showing 15 of '+mis.items.length+'. Run <code>ccr stats --misroutes</code> for the full list.</div>':'');
281
+ }else h+='<div class="sub">No decided tasks yet, so misroutes cannot be measured.</div>';
282
+ if(D.manual_escalations||D.possible_reworks)h+='<div class="sub" style="margin-top:6px">'+D.manual_escalations+' manual move(s) to a stronger model and '+D.possible_reworks+' possible rework(s) after a cheap answer, counted against the tier they came from.</div>';
283
+ const sh=D.shadow||{n:0};
284
+ h+='<h2 style="margin-top:14px">Would a cheaper tier have done it?</h2>'+(sh.n?'<div class="sub">'+sh.ok+' of '+sh.n+' sampled deep-tier tasks also succeeded at a lower tier ('+Math.round(sh.rate*100)+'%); '+sh.verified_ok+'/'+sh.verified_n+' verified by tests. '+Object.entries(sh.pairs).map(([k,v])=>k+' '+v.ok+'/'+v.n).join(', ')+'.</div>':'<div class="sub">Not measured. <code>ccr shadow --max-budget-usd 1 --yes</code> re-runs a few deep-tier tasks at a lower tier in a throwaway worktree (uses your claude usage).</div>');
285
+ const act=L.filter(x=>x.action!=='watch');
286
+ h+='<h2 style="margin-top:14px">Learning</h2>'+(act.length?'<ul class="tune">'+act.map(x=>'<li><b>'+esc(x.action)+'</b> '+esc(x.note)+'</li>').join('')+'</ul>':'<div class="sub">No adjustments yet. Learning starts after a few decided tasks per class and area (see <code>history:</code> in config).</div>');
287
+ $('#health').innerHTML=h}
288
+
289
+ let page=0;
290
+ const RES={ok:['✓ ok','ok'],fail:['✗ failed','fail'],unknown:['? unknown','unk']};
291
+ function steps(r){
292
+ const d=r.decision,t=r.trace||{};
293
+ if(d){
294
+ const s=[];
295
+ s.push('Classified as <b>'+esc(d.class.kind)+'</b> ('+esc(d.class.source)+', confidence '+d.class.confidence.toFixed(2)+(d.class.secondary?', runner-up '+esc(d.class.secondary):'')+'); scope '+esc(d.class.scope)+', vagueness '+d.class.vagueness.toFixed(2)+(d.class.evidence.length?'. Matched: '+d.class.evidence.map(esc).join(', '):'')+'.');
296
+ s.push('Starting tier for this class: <b>'+esc(d.base)+'</b>.');
297
+ s.push(d.files.length?'Located '+d.files.length+' candidate file(s): '+d.files.map(f=>'<code>'+esc(f.path)+'</code> ('+f.confidence.toFixed(2)+')').join(', ')+'.':'No specific files located.');
298
+ if(d.risk&&d.risk.score!=null)s.push('Risk <b>'+d.risk.score.toFixed(2)+' ('+esc(d.risk.level)+')</b>: '+Object.entries(d.risk.components).map(([k,c])=>k.replace(/_/g,' ')+' '+c.value.toFixed(2)).join(', ')+'.');
299
+ d.reasons.forEach(x=>s.push(esc(x)));
300
+ if(d.learning&&d.learning!=='none')s.push('Learning: '+esc(d.learning));
301
+ if(d.budget)s.push('Budget: '+esc(d.budget));
302
+ d.notes.forEach(x=>s.push(esc(x)));
303
+ if(d.t4&&d.t4.length)s.push('T4 rule: '+d.t4.map(esc).join('; '));
304
+ s.push('Final: <b>'+esc(d.tier)+'</b> ('+esc(d.model)+'/'+esc(d.effort)+(d.retry?', retry after a failure':'')+').');
305
+ return s}
306
+ if(!r.trace)return ['No decision details were recorded for this task (older history).'];
307
+ const s=['Class <b>'+esc(r.class||'?')+'</b> (confidence '+(t.class_conf??'?')+', '+esc(t.class_source||'rules')+'); scope '+esc(t.scope||'?')+', vagueness '+(t.vagueness??'?')+'.'];
308
+ if(t.base)s.push('Starting tier for the class: <b>'+esc(t.base)+'</b>.');
309
+ if((t.rules||[]).length)s.push('Cue words that fired: '+t.rules.map(esc).join(', ')+'.');
310
+ if((t.hard_terms||[]).length)s.push('Hard-problem words: '+t.hard_terms.map(esc).join(', ')+'.');
311
+ if((t.bumps||[]).length)s.push('Moved up a tier for: '+t.bumps.map(esc).join(', ')+'.');
312
+ s.push((t.located?'Code located':'No code located')+'; risk '+esc(t.risk_level||'unknown')+(t.code_risk!=null?' (code-only '+t.code_risk+')':'')+'.');
313
+ if((t.critical||[]).length)s.push('Critical path: '+t.critical.map(esc).join(', ')+'.');
314
+ if((t.memory_flags||[]).length)s.push('Memory flags: '+t.memory_flags.map(esc).join(', ')+'.');
315
+ if(t.t4)s.push('A T4 rule applied.');
316
+ if(t.budget_pressure)s.push('Weekly budget pressure lowered the tier.');
317
+ if(r.escalated_to)s.push('It failed here and was retried at '+esc(r.escalated_to)+'.');
318
+ s.push('Final: <b>'+esc(r.tier)+'</b>.');return s}
319
+ const ARROW={up:'↑ ',down:'↓ ',rule:'⚑ ',none:'= '};
320
+ function why(r){
321
+ const w=r.why;if(!w||!w.checks.length)return '<div class="sub">No decision details were recorded for this task.</div>';
322
+ let h='<div class="chain">'+w.chain.map(c=>'<span>'+esc(c)+'</span>').join('<i>→</i>')+'</div>';
323
+ h+=w.checks.map(c=>'<div class="chk"><div class="no">'+c.n+'</div><div class="q">'+esc(c.title)+'</div><div class="eff '+c.move+'">'+ARROW[c.move]+esc(c.effect)+'</div>'+
324
+ '<div class="lk">Looked at: '+esc(c.looked_at)+'</div><div class="fd">Found: '+esc(c.found)+'</div></div>').join('');
325
+ if(w.partial)h+='<div class="sub" style="margin-top:6px">Older task: only the saved routing signals are available. Turn on <code>hooks.store_prompts</code> for the full checklist on new tasks.</div>';
326
+ return h+'<div class="effnote">'+esc(w.effort_note)+'</div>'}
327
+ function card(r){
328
+ const d=r.decision,[lab,cls]=RES[r.result],pr=d?d.prompt:null;
329
+ const sum='<summary><span class="sub">'+fmtT(r.ts)+'</span><span class="pill" title="'+esc(D.tier_models[r.tier]||'')+'" style="border-color:'+tierVar(r.tier)+'">'+r.tier+' <small style="color:var(--muted);font-weight:500">'+esc((D.tier_models[r.tier]||'').replace('/',' '))+'</small></span>'+
330
+ '<span class="pr'+(pr?'':' dim')+'">'+(pr?esc(pr.replace(/\s+/g,' ').slice(0,140)):'prompt not stored · '+esc(r.class||'?')+' in '+esc(r.area||'*'))+'</span>'+
331
+ '<span class="'+cls+'">'+lab+(r.escalated_to?' → '+r.escalated_to:'')+'</span><span class="sub hide-s">'+fk(r.tokens||0)+'</span></summary>';
332
+ const body='<div class="body"><h3>Prompt</h3>'+(pr?'<pre class="pt">'+esc(pr)+'</pre>':'<div class="sub">Not stored. Set <code>hooks.store_prompts: true</code> in <code>.ccr/config.yaml</code> to keep prompts for new tasks.</div>')+
333
+ '<h3>What ccr checked before choosing '+r.tier+' ('+esc(D.tier_models[r.tier]||'')+')</h3>'+why(r)+
334
+ '<details class="raw"><summary>Raw engine notes</summary><ol class="steps">'+steps(r).map(x=>'<li>'+x+'</li>').join('')+'</ol></details>'+
335
+ '<h3>Details</h3><div class="kv"><span>ID <b>'+esc(r.full_id.slice(0,12))+'</b></span><span>Class <b>'+esc(r.class||'?')+'</b></span><span>Area <b>'+esc(r.area||'*')+'</b></span><span>Model <b>'+esc(D.tier_models[r.tier]||'')+'</b></span><span>Tokens <b>'+fk(r.tokens||0)+'</b></span><span>Source <b>'+esc(r.source||'')+'</b></span>'+(r.confidence!=null?'<span>Confidence <b>'+Number(r.confidence).toFixed(2)+'</b></span>':'')+'</div></div>';
336
+ return '<details class="dec">'+sum+body+'</details>'}
337
+ function tasks(reset){
338
+ if(reset)page=0;
339
+ const q=$('#q').value.toLowerCase().trim(),f=$('#fres').value,ft=$('#ftier').value,size=+$('#psize').value;
340
+ $('#banner').innerHTML=D.store_prompts?'':'<div class="banner">Prompt text is off. Showing the routing signals kept in history. Enable <code>hooks.store_prompts: true</code> to see prompts and the full decision steps for new tasks (stored locally in <code>.ccr/local/prompts.jsonl</code>, never committed).</div>';
341
+ const hay=r=>[r.decision&&r.decision.prompt,r.class,r.area,r.full_id,r.tier].join(' ').toLowerCase();
342
+ const rs=rows.filter(r=>(!f||r.result===f)&&(!ft||r.tier===ft)&&(!q||hay(r).includes(q))).slice().reverse();
343
+ const pages=Math.max(1,Math.ceil(rs.length/size));page=Math.min(page,pages-1);
344
+ $('#tasks').innerHTML=rs.length?rs.slice(page*size,page*size+size).map(card).join(''):'<div class="empty">No tasks match</div>';
345
+ $('#pginfo').textContent='Page '+(page+1)+' of '+pages+' · '+rs.length+' task'+(rs.length===1?'':'s');
346
+ $('#prev').disabled=page<=0;$('#next').disabled=page>=pages-1}
347
+ function draw(){inRange();tiles();daily();succ();cost();area();heat();health();tasks(true)}
348
+ $('#title').textContent=D.project;document.title=D.project+' · ccr dashboard';
349
+ $('#meta').textContent='ccr dashboard · '+D.tasks+' task(s)'+(D.since?' · '+fmtT(D.since)+' to '+fmtT(D.until):'')+' · generated '+fmtT(D.generated);
350
+ $('#range').onchange=draw;
351
+ $('#ftier').innerHTML+=D.tier_order.map(t=>'<option value="'+t+'">'+t+' · '+D.tier_models[t].replace('/',' ')+'</option>').join('');
352
+ ['#fres','#ftier','#psize'].forEach(i=>$(i).onchange=()=>tasks(true));$('#q').oninput=()=>tasks(true);
353
+ $('#prev').onclick=()=>{page--;tasks()};$('#next').onclick=()=>{page++;tasks()};
354
+ $('#theme').onclick=()=>{const r=document.documentElement,dark=r.dataset.theme?r.dataset.theme==='dark':matchMedia('(prefers-color-scheme:dark)').matches;r.dataset.theme=dark?'light':'dark'};
355
+ function secs(){return [...document.querySelectorAll('section.card')]}
356
+ function secKey(c){return c.querySelector('h2').textContent.trim()}
357
+ function loadClosed(){try{return JSON.parse(localStorage.getItem('ccr-closed')||'[]')}catch(e){return []}}
358
+ function saveClosed(){try{localStorage.setItem('ccr-closed',JSON.stringify(secs().filter(c=>c.classList.contains('closed')).map(secKey)))}catch(e){}}
359
+ function setOpen(c,open){c.classList.toggle('closed',!open);c.querySelector('h2').setAttribute('aria-expanded',open)}
360
+ (function initSections(){
361
+ const closed=loadClosed();
362
+ secs().forEach(c=>{const h=c.querySelector('h2');if(!h)return;h.classList.add('sec');h.setAttribute('role','button');h.tabIndex=0;
363
+ const body=document.createElement('div');body.className='sec-body';
364
+ while(h.nextSibling)body.appendChild(h.nextSibling);c.appendChild(body);
365
+ setOpen(c,!closed.includes(secKey(c)));
366
+ const toggle=()=>{setOpen(c,c.classList.contains('closed'));saveClosed()};
367
+ h.addEventListener('click',toggle);
368
+ h.addEventListener('keydown',e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();toggle()}})});
369
+ $('#collapse').onclick=()=>{secs().forEach(c=>setOpen(c,false));saveClosed()};
370
+ $('#expand').onclick=()=>{secs().forEach(c=>setOpen(c,true));saveClosed()};
371
+ })();
372
+ draw();
373
+ </script></body></html>
374
+ """