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.
- ccr/__init__.py +0 -0
- ccr/__main__.py +4 -0
- ccr/cli.py +595 -0
- ccr/config.py +518 -0
- ccr/detect/__init__.py +123 -0
- ccr/doctor.py +208 -0
- ccr/entry.py +23 -0
- ccr/evaluate/__init__.py +13 -0
- ccr/evaluate/classify.py +335 -0
- ccr/evaluate/llm.py +182 -0
- ccr/evaluate/locate.py +359 -0
- ccr/evaluate/risk.py +285 -0
- ccr/evaluate/text.py +190 -0
- ccr/graph/__init__.py +15 -0
- ccr/graph/build.py +475 -0
- ccr/graph/db.py +88 -0
- ccr/graph/files.py +169 -0
- ccr/graph/git.py +90 -0
- ccr/graph/parse.py +510 -0
- ccr/graph/query.py +359 -0
- ccr/graph/resolve.py +256 -0
- ccr/headless.py +363 -0
- ccr/history/__init__.py +172 -0
- ccr/history/calibrate.py +161 -0
- ccr/history/dashboard.py +374 -0
- ccr/history/feedback.py +91 -0
- ccr/history/learn.py +184 -0
- ccr/history/prompts.py +120 -0
- ccr/history/redact.py +45 -0
- ccr/history/savings.py +187 -0
- ccr/history/shadow.py +114 -0
- ccr/history/stats.py +172 -0
- ccr/history/tune.py +80 -0
- ccr/history/why.py +186 -0
- ccr/hooks/__init__.py +134 -0
- ccr/hooks/bg.py +68 -0
- ccr/hooks/common.py +159 -0
- ccr/hooks/prompt.py +322 -0
- ccr/hooks/session_start.py +91 -0
- ccr/hooks/stop.py +52 -0
- ccr/hooks/tasks.py +170 -0
- ccr/install/__init__.py +388 -0
- ccr/install/agents.py +200 -0
- ccr/install/command.py +159 -0
- ccr/install/settings.py +175 -0
- ccr/memory/__init__.py +87 -0
- ccr/memory/signals.py +210 -0
- ccr/memory/sources.py +422 -0
- ccr/report.py +40 -0
- ccr/route/__init__.py +527 -0
- ccr/route/budget.py +166 -0
- ccr/statusline.py +143 -0
- ccr/transcript.py +98 -0
- claude_code_router-0.1.1.dist-info/METADATA +291 -0
- claude_code_router-0.1.1.dist-info/RECORD +58 -0
- claude_code_router-0.1.1.dist-info/WHEEL +4 -0
- claude_code_router-0.1.1.dist-info/entry_points.txt +2 -0
- claude_code_router-0.1.1.dist-info/licenses/LICENSE +21 -0
ccr/history/feedback.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
"""`ccr feedback good|bad`: correct the outcome of the last routed task.
|
|
2
|
+
|
|
3
|
+
The target is the newest task by timestamp among
|
|
4
|
+
* finalised task records in .ccr/history.jsonl (hook tasks and `ccr run` attempts), and
|
|
5
|
+
* tasks still pending in a Claude Code session (.ccr/local/sessions/*.json): the prompt
|
|
6
|
+
hook gives each one its history id up front, so feedback can point at it before the
|
|
7
|
+
task is written.
|
|
8
|
+
Feedback is appended as its own record (`type: feedback`, `ref: <id>`); history is never
|
|
9
|
+
rewritten and the correction is applied whenever history is read (history.resolve).
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import time
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from ccr import history as H
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Target:
|
|
22
|
+
id: str
|
|
23
|
+
record: dict
|
|
24
|
+
where: str # "history" | "pending"
|
|
25
|
+
session_file: Path | None = None
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _pending(root: Path) -> list[Target]:
|
|
29
|
+
from ccr.hooks.common import read_json, write_json_atomic
|
|
30
|
+
out = []
|
|
31
|
+
d = root / ".ccr" / "local" / "sessions"
|
|
32
|
+
try:
|
|
33
|
+
files = sorted(d.glob("*.json"))
|
|
34
|
+
except OSError:
|
|
35
|
+
return out
|
|
36
|
+
for p in files:
|
|
37
|
+
data = read_json(p)
|
|
38
|
+
pend = data.get("pending")
|
|
39
|
+
if not isinstance(pend, dict):
|
|
40
|
+
continue
|
|
41
|
+
if not isinstance(pend.get("id"), str): # recorded by an older ccr: tag it now
|
|
42
|
+
pend["id"] = H.new_id()
|
|
43
|
+
try:
|
|
44
|
+
write_json_atomic(p, data)
|
|
45
|
+
except OSError:
|
|
46
|
+
continue
|
|
47
|
+
out.append(Target(pend["id"], pend, "pending", p))
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def candidates(root: str | Path) -> list[Target]:
|
|
52
|
+
"""Every addressable task, oldest first."""
|
|
53
|
+
root = Path(root)
|
|
54
|
+
out = [Target(r["id"], r, "history") for r in H.read(root) if isinstance(r.get("id"), str)]
|
|
55
|
+
out += _pending(root)
|
|
56
|
+
out.sort(key=lambda t: float(t.record.get("ts") or 0))
|
|
57
|
+
return out
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def find(root: str | Path, ref: str | None = None) -> Target | None:
|
|
61
|
+
cands = candidates(root)
|
|
62
|
+
if ref:
|
|
63
|
+
hits = [t for t in cands if t.id.startswith(ref)]
|
|
64
|
+
return hits[-1] if len(hits) >= 1 and len({t.id for t in hits}) == 1 else None
|
|
65
|
+
return cands[-1] if cands else None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def mark(root: str | Path, verdict: str, ref: str | None = None,
|
|
69
|
+
now: float | None = None) -> tuple[Target | None, dict | None]:
|
|
70
|
+
t = find(root, ref)
|
|
71
|
+
if t is None:
|
|
72
|
+
return None, None
|
|
73
|
+
rec = H.feedback_record(t.id, verdict, now)
|
|
74
|
+
H.append(root, rec)
|
|
75
|
+
return t, rec
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def describe(t: Target) -> str:
|
|
79
|
+
r = t.record
|
|
80
|
+
ts = r.get("ts")
|
|
81
|
+
when = time.strftime("%Y-%m-%d %H:%M", time.localtime(ts)) if isinstance(
|
|
82
|
+
ts, (int, float)) else "?"
|
|
83
|
+
src = {"run": "ccr run", "hook": "claude session"}.get(r.get("source"), r.get("source"))
|
|
84
|
+
bits = [f"{r.get('tier', '?')} {r.get('class', '?')}",
|
|
85
|
+
f"area {r.get('area', '*')}", when, str(src or "?")]
|
|
86
|
+
if t.where == "pending":
|
|
87
|
+
bits.append("in progress")
|
|
88
|
+
elif r.get("outcome"):
|
|
89
|
+
bits.append(f"outcome {r['outcome']}" + (f" (feedback {r['feedback']})"
|
|
90
|
+
if r.get("feedback") else ""))
|
|
91
|
+
return f"[{t.id[:8]}] " + ", ".join(bits)
|
ccr/history/learn.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""Learning loop: count/threshold rules over resolved history, per (task class x area).
|
|
2
|
+
|
|
3
|
+
Every number comes from `.ccr/config.yaml` `history:` and every adjustment cites its counts.
|
|
4
|
+
|
|
5
|
+
up the starting tier failed >= `fail_rate_up` of >= `min_samples` decided tasks
|
|
6
|
+
-> start one tier higher (never above the escalation cap / T3 ceiling)
|
|
7
|
+
down the tier below succeeded >= `success_rate_down` of >= `min_samples`
|
|
8
|
+
-> start one tier lower
|
|
9
|
+
explore the starting tier itself succeeded >= `success_rate_down` of >= `min_samples`,
|
|
10
|
+
the task is low-risk and simple (risk low, scope not large, not vague, not a hard
|
|
11
|
+
problem, no critical path or memory flag) and the tier below has no failure
|
|
12
|
+
record -> try one tier lower (`explore_down: false` disables). If the lower tier
|
|
13
|
+
then fails, the `up` rule brings it back, so the loop settles.
|
|
14
|
+
Downward moves never apply on a critical path and never go below the class floor (T1 for
|
|
15
|
+
code changes, T0 for questions and trivial edits). Counts are per class x area when that
|
|
16
|
+
area has decided samples, else class-wide. Outcomes `unknown`/`abandoned`/`error` are not
|
|
17
|
+
counted; `ccr feedback` corrections are applied before counting (history.resolve).
|
|
18
|
+
"""
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
|
|
23
|
+
from ccr.config import TIERS, TOP
|
|
24
|
+
|
|
25
|
+
SUCCESS = {"success"}
|
|
26
|
+
FAILURE = {"failure", "escalated"}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def tier_counts(records: list[dict], kind: str, area: str | None) -> tuple[dict, str]:
|
|
30
|
+
"""({tier: [successes, failures]}, scope) for class x area, else class-wide."""
|
|
31
|
+
def collect(match_area: bool) -> dict:
|
|
32
|
+
st: dict[str, list[int]] = {}
|
|
33
|
+
for r in records:
|
|
34
|
+
if r.get("class") != kind or not isinstance(r.get("tier"), str):
|
|
35
|
+
continue
|
|
36
|
+
if match_area and r.get("area") != area:
|
|
37
|
+
continue
|
|
38
|
+
o = r.get("outcome")
|
|
39
|
+
s = st.setdefault(r["tier"], [0, 0])
|
|
40
|
+
if o in SUCCESS:
|
|
41
|
+
s[0] += 1
|
|
42
|
+
elif o in FAILURE:
|
|
43
|
+
s[1] += 1
|
|
44
|
+
return st
|
|
45
|
+
if area and area != "*":
|
|
46
|
+
st = collect(True)
|
|
47
|
+
if sum(sum(v) for v in st.values()):
|
|
48
|
+
return st, "area"
|
|
49
|
+
return collect(False), "class"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Learned:
|
|
54
|
+
tier: int # tier index after learning
|
|
55
|
+
delta: int # -1, 0, +1
|
|
56
|
+
note: str # one line for Decision.history / `ccr explain`
|
|
57
|
+
reason: str | None = None # line for Decision.reasons (None: no change)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
STRUGGLE_SIGNALS = {"self_reported_failure", "subagent_reported_failure", "manual_model_up"}
|
|
61
|
+
REWORK_REPEATS = 2 # possible_rework counts only when it keeps happening for a class x area x tier
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def struggled(r: dict, hc: dict) -> bool:
|
|
65
|
+
"""A recorded success that looks like it was hard won: many tool errors or turns, or the
|
|
66
|
+
model said it could not finish. Learning treats these as failures; stats still show the
|
|
67
|
+
real outcome."""
|
|
68
|
+
if r.get("outcome") not in SUCCESS:
|
|
69
|
+
return False
|
|
70
|
+
errs, turns = int(hc.get("struggle_tool_errors") or 0), int(hc.get("struggle_turns") or 0)
|
|
71
|
+
return bool((errs and (r.get("tool_errors") or 0) >= errs)
|
|
72
|
+
or (turns and (r.get("turns") or 0) >= turns)
|
|
73
|
+
or STRUGGLE_SIGNALS & set(r.get("signals") or ()))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def mark_struggle(records: list[dict], cfg) -> list[dict]:
|
|
77
|
+
hc = cfg["history"]
|
|
78
|
+
rework: dict[tuple, int] = {}
|
|
79
|
+
for r in records:
|
|
80
|
+
if r.get("outcome") in SUCCESS and "possible_rework" in (r.get("signals") or ()):
|
|
81
|
+
k = (r.get("class"), r.get("area"), r.get("tier"))
|
|
82
|
+
rework[k] = rework.get(k, 0) + 1
|
|
83
|
+
out = []
|
|
84
|
+
for r in records:
|
|
85
|
+
again = "possible_rework" in (r.get("signals") or ()) and r.get("outcome") in SUCCESS \
|
|
86
|
+
and rework.get((r.get("class"), r.get("area"), r.get("tier")), 0) >= REWORK_REPEATS
|
|
87
|
+
out.append({**r, "outcome": "failure", "struggled": True} if struggled(r, hc) or again
|
|
88
|
+
else r)
|
|
89
|
+
return out
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _rate(c: list[int] | None, i: int) -> float:
|
|
93
|
+
return c[i] / sum(c) if c and sum(c) else 0.0
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def adjust(tier: int, *, kind: str, area: str, records: list[dict], cfg, cap: int,
|
|
97
|
+
floor: int, critical: bool = False, low_risk_simple: bool = False) -> Learned:
|
|
98
|
+
"""Apply the learning rules to a routed tier index."""
|
|
99
|
+
hc = cfg["history"]
|
|
100
|
+
k, up, down = int(hc["min_samples"]), float(hc["fail_rate_up"]), \
|
|
101
|
+
float(hc["success_rate_down"])
|
|
102
|
+
stats, scope = tier_counts(mark_struggle(records, cfg), kind, area)
|
|
103
|
+
where = f"{kind} in {area}" if scope == "area" else f"{kind} (all areas)"
|
|
104
|
+
if not stats:
|
|
105
|
+
return Learned(tier, 0, f"no history for {kind}")
|
|
106
|
+
cur = stats.get(TIERS[tier])
|
|
107
|
+
lower = stats.get(TIERS[tier - 1]) if tier > 0 else None
|
|
108
|
+
cur_n, low_n = sum(cur or ()), sum(lower or ())
|
|
109
|
+
|
|
110
|
+
if cur_n >= k and _rate(cur, 1) >= up:
|
|
111
|
+
counts = f"{TIERS[tier]} failed {cur[1]}/{cur_n} for {where}"
|
|
112
|
+
if tier < cap:
|
|
113
|
+
return Learned(tier + 1, 1, f"{counts}: +1", f"+1: history: {counts}")
|
|
114
|
+
return Learned(tier, 0, f"{counts}, but escalation cap reached",
|
|
115
|
+
f"history: {counts}, but escalation cap reached")
|
|
116
|
+
lower_bad = bool(lower) and low_n >= k and _rate(lower, 1) >= up
|
|
117
|
+
if tier > floor and not critical:
|
|
118
|
+
if low_n >= k and _rate(lower, 0) >= down:
|
|
119
|
+
counts = f"{TIERS[tier - 1]} succeeded {lower[0]}/{low_n} for {where}"
|
|
120
|
+
return Learned(tier - 1, -1, f"{counts}: -1", f"-1: history: {counts}")
|
|
121
|
+
if hc.get("explore_down", True) and low_risk_simple and cur_n >= k and \
|
|
122
|
+
_rate(cur, 0) >= down and not (lower and lower[1]):
|
|
123
|
+
counts = f"{TIERS[tier]} succeeded {cur[0]}/{cur_n} for {where}"
|
|
124
|
+
return Learned(tier - 1, -1,
|
|
125
|
+
f"{counts}; low-risk simple task: trying {TIERS[tier - 1]} (-1)",
|
|
126
|
+
f"-1: history: {counts}, low-risk simple task: trying "
|
|
127
|
+
f"{TIERS[tier - 1]}")
|
|
128
|
+
summary = ", ".join(f"{t} {s}/{s + f} ok" for t, (s, f) in sorted(stats.items()))
|
|
129
|
+
why = ""
|
|
130
|
+
if lower_bad:
|
|
131
|
+
why = f"; {TIERS[tier - 1]} failed {lower[1]}/{low_n}, staying"
|
|
132
|
+
elif critical and (low_n >= k or cur_n >= k):
|
|
133
|
+
why = "; critical path: never lowered by history"
|
|
134
|
+
return Learned(tier, 0, f"{where}: {summary} (no change{why})")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def summarize(records: list[dict], cfg) -> list[dict]:
|
|
138
|
+
"""What the rules currently say for every class x area seen in history (for `ccr stats`).
|
|
139
|
+
Each item: {class, area, tier, action: up|down|explore|watch, note}."""
|
|
140
|
+
hc = cfg["history"]
|
|
141
|
+
k, up, down = int(hc["min_samples"]), float(hc["fail_rate_up"]), \
|
|
142
|
+
float(hc["success_rate_down"])
|
|
143
|
+
groups: dict[tuple[str, str], dict[str, list[int]]] = {}
|
|
144
|
+
for r in mark_struggle(records, cfg):
|
|
145
|
+
kind, tier = r.get("class"), r.get("tier")
|
|
146
|
+
if not isinstance(kind, str) or tier not in TIERS:
|
|
147
|
+
continue
|
|
148
|
+
area = r.get("area") if isinstance(r.get("area"), str) else "*"
|
|
149
|
+
st = groups.setdefault((kind, area), {}).setdefault(tier, [0, 0])
|
|
150
|
+
if r.get("outcome") in SUCCESS:
|
|
151
|
+
st[0] += 1
|
|
152
|
+
elif r.get("outcome") in FAILURE:
|
|
153
|
+
st[1] += 1
|
|
154
|
+
out = []
|
|
155
|
+
for (kind, area), stats in sorted(groups.items()):
|
|
156
|
+
where = f"{kind} in {area}" if area != "*" else f"{kind} (no area)"
|
|
157
|
+
for t in sorted(stats):
|
|
158
|
+
s, f = stats[t]
|
|
159
|
+
n = s + f
|
|
160
|
+
i = TIERS.index(t)
|
|
161
|
+
if n < k:
|
|
162
|
+
if n:
|
|
163
|
+
out.append({"class": kind, "area": area, "tier": t, "action": "watch",
|
|
164
|
+
"note": f"{where}: {t} {s}/{n} ok (needs {k} samples)"})
|
|
165
|
+
continue
|
|
166
|
+
if f / n >= up:
|
|
167
|
+
nxt = TIERS[min(i + 1, TOP)]
|
|
168
|
+
out.append({"class": kind, "area": area, "tier": t, "action": "up",
|
|
169
|
+
"note": f"{where}: {t} failed {f}/{n} -> start at {nxt}"})
|
|
170
|
+
elif s / n >= down and i > 0:
|
|
171
|
+
lo = stats.get(TIERS[i - 1])
|
|
172
|
+
if lo and sum(lo) >= k and lo[1] / sum(lo) >= up:
|
|
173
|
+
note = (f"{where}: {t} ok {s}/{n}, but {TIERS[i - 1]} failed "
|
|
174
|
+
f"{lo[1]}/{sum(lo)} -> stays {t}")
|
|
175
|
+
out.append({"class": kind, "area": area, "tier": t, "action": "watch",
|
|
176
|
+
"note": note})
|
|
177
|
+
else:
|
|
178
|
+
out.append({"class": kind, "area": area, "tier": t, "action": "explore",
|
|
179
|
+
"note": f"{where}: {t} ok {s}/{n} -> low-risk simple tasks "
|
|
180
|
+
f"try {TIERS[i - 1]}"})
|
|
181
|
+
else:
|
|
182
|
+
out.append({"class": kind, "area": area, "tier": t, "action": "watch",
|
|
183
|
+
"note": f"{where}: {t} {s}/{n} ok (within thresholds)"})
|
|
184
|
+
return out
|
ccr/history/prompts.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Opt-in prompt + decision log: `.ccr/local/prompts.jsonl` (stdlib only; safe for hooks).
|
|
2
|
+
|
|
3
|
+
Off by default (`hooks.store_prompts`). It holds your prompt text, so it lives under
|
|
4
|
+
`.ccr/local/` (gitignored, never shared through history.jsonl) and is keyed by the history
|
|
5
|
+
task id. `ccr dashboard` joins it back to show why each task got its tier.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import contextlib
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from ccr.history import why
|
|
16
|
+
from ccr.history.redact import redact as redact_text
|
|
17
|
+
|
|
18
|
+
MAX_PROMPT_CHARS = 2000
|
|
19
|
+
MAX_BYTES = 4 * 1024 * 1024
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def path(root) -> Path:
|
|
23
|
+
return Path(root) / ".ccr" / "local" / "prompts.jsonl"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def snapshot(task_id: str, prompt: str, d, tier, fact: str, notes: list[str] | None = None,
|
|
27
|
+
retry: bool = False, escalated_from: str | None = None, redact: bool = True) -> dict:
|
|
28
|
+
"""The prompt and the decision process behind `tier` (a ccr.route.Decision `d`)."""
|
|
29
|
+
tc, r = d.task_class, d.risk
|
|
30
|
+
text, kinds = redact_text(prompt[:MAX_PROMPT_CHARS]) if redact else (prompt[:MAX_PROMPT_CHARS], [])
|
|
31
|
+
return {
|
|
32
|
+
"id": task_id, "ts": int(time.time()), "prompt": text, "redacted": kinds, "tier": tier.name,
|
|
33
|
+
"model": tier.model, "effort": tier.effort, "fact": fact, "retry": retry,
|
|
34
|
+
"escalated_from": escalated_from, "base": d.base, "confidence": d.confidence,
|
|
35
|
+
"class": {"kind": tc.kind, "confidence": tc.confidence, "source": tc.source,
|
|
36
|
+
"secondary": tc.secondary, "scope": tc.scope, "vagueness": tc.vagueness,
|
|
37
|
+
"evidence": tc.matched.get(tc.kind, [])[:6]},
|
|
38
|
+
"files": [{"path": c.path, "confidence": c.confidence, "why": "; ".join(c.reasons[:3])}
|
|
39
|
+
for c in d.location.candidates[:5]],
|
|
40
|
+
"risk": {"score": r.score, "level": r.level,
|
|
41
|
+
"components": {n: {"value": c.value, "detail": c.detail}
|
|
42
|
+
for n, c in r.components.items()}},
|
|
43
|
+
"why": why.from_decision(d, tier),
|
|
44
|
+
"reasons": list(d.reasons), "learning": str(d.history), "budget": d.budget.detail,
|
|
45
|
+
"notes": [*d.notes, *(notes or [])], "t4": list(d.t4_rules)}
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def append(root, entry: dict) -> None:
|
|
49
|
+
p = path(root)
|
|
50
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
51
|
+
try:
|
|
52
|
+
if p.stat().st_size > MAX_BYTES: # keep the newest half
|
|
53
|
+
keep = p.read_bytes()[-MAX_BYTES // 2:]
|
|
54
|
+
p.write_bytes(keep[keep.find(b"\n") + 1:])
|
|
55
|
+
except OSError:
|
|
56
|
+
pass
|
|
57
|
+
line = json.dumps(entry, separators=(",", ":"), default=str) + "\n"
|
|
58
|
+
fd = os.open(p, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
|
|
59
|
+
try:
|
|
60
|
+
os.write(fd, line.encode("utf-8"))
|
|
61
|
+
finally:
|
|
62
|
+
os.close(fd)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def read(root) -> dict[str, dict]:
|
|
66
|
+
"""{task id: entry}; the newest entry wins, unreadable lines are skipped."""
|
|
67
|
+
out: dict[str, dict] = {}
|
|
68
|
+
try:
|
|
69
|
+
text = path(root).read_text(encoding="utf-8", errors="replace")
|
|
70
|
+
except OSError:
|
|
71
|
+
return out
|
|
72
|
+
for line in text.splitlines():
|
|
73
|
+
try:
|
|
74
|
+
e = json.loads(line)
|
|
75
|
+
except ValueError:
|
|
76
|
+
continue
|
|
77
|
+
if isinstance(e, dict) and isinstance(e.get("id"), str):
|
|
78
|
+
out[e["id"]] = e
|
|
79
|
+
return out
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def prune(root, days: int, now: float | None = None) -> int:
|
|
83
|
+
"""Drop entries older than `days` (entries without a timestamp are kept). Returns how many."""
|
|
84
|
+
if days <= 0:
|
|
85
|
+
return 0
|
|
86
|
+
cutoff = (now or time.time()) - days * 86400
|
|
87
|
+
p = path(root)
|
|
88
|
+
try:
|
|
89
|
+
lines = p.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
90
|
+
except OSError:
|
|
91
|
+
return 0
|
|
92
|
+
keep, dropped = [], 0
|
|
93
|
+
for line in lines:
|
|
94
|
+
try:
|
|
95
|
+
ts = json.loads(line).get("ts")
|
|
96
|
+
except (ValueError, AttributeError):
|
|
97
|
+
ts = None
|
|
98
|
+
if isinstance(ts, (int, float)) and ts < cutoff:
|
|
99
|
+
dropped += 1
|
|
100
|
+
else:
|
|
101
|
+
keep.append(line)
|
|
102
|
+
if dropped:
|
|
103
|
+
p.write_text("\n".join(keep) + ("\n" if keep else ""), encoding="utf-8")
|
|
104
|
+
return dropped
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def prune_daily(root, days: int) -> int:
|
|
108
|
+
"""`prune`, at most once a day (cheap enough for the SessionStart hook)."""
|
|
109
|
+
p = path(root)
|
|
110
|
+
marker = p.with_suffix(".pruned")
|
|
111
|
+
try:
|
|
112
|
+
if not p.exists() or time.time() - marker.stat().st_mtime < 86400:
|
|
113
|
+
return 0
|
|
114
|
+
except OSError:
|
|
115
|
+
if not p.exists():
|
|
116
|
+
return 0
|
|
117
|
+
n = prune(root, days)
|
|
118
|
+
with contextlib.suppress(OSError):
|
|
119
|
+
marker.write_text("")
|
|
120
|
+
return n
|
ccr/history/redact.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Best-effort secret redaction for stored prompts (stdlib only; safe for hooks).
|
|
2
|
+
|
|
3
|
+
Prompts can paste keys, tokens, connection strings or customer emails. Redaction runs before a
|
|
4
|
+
prompt is written to `.ccr/local/prompts.jsonl` (`hooks.redact_prompts`, on by default). It is a
|
|
5
|
+
safety net, not a guarantee: unusual secrets can slip through, so keep `store_prompts` off for
|
|
6
|
+
projects where prompts hold sensitive data.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
_I = re.I
|
|
13
|
+
PATTERNS: list[tuple[str, re.Pattern]] = [
|
|
14
|
+
("private-key", re.compile(
|
|
15
|
+
r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)")),
|
|
16
|
+
("aws-key", re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),
|
|
17
|
+
("api-key", re.compile(r"\b(?:sk|pk|rk)[-_](?:live|test|proj|ant)?[-_]?[A-Za-z0-9_-]{16,}\b")),
|
|
18
|
+
("github-token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{20,}\b")),
|
|
19
|
+
("slack-token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}\b")),
|
|
20
|
+
("jwt", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b")),
|
|
21
|
+
("bearer", re.compile(r"\bBearer\s+[A-Za-z0-9._~+/=-]{16,}", _I)),
|
|
22
|
+
("url-credentials", re.compile(r"\b[a-z][a-z0-9+.-]*://[^\s:/@]+:[^\s@/]+@", _I)),
|
|
23
|
+
("secret-assignment", re.compile(
|
|
24
|
+
r"\b(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|auth)\b\s*[:=]\s*"
|
|
25
|
+
r"[\"']?[^\s\"',;]{6,}", _I)),
|
|
26
|
+
("email", re.compile(r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b")),
|
|
27
|
+
("long-token", re.compile(
|
|
28
|
+
r"\b(?=[A-Za-z0-9+/_=-]*\d)(?=[A-Za-z0-9+/_=-]*[A-Za-z])[A-Za-z0-9+/_=-]{32,}\b")),
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def redact(text: str) -> tuple[str, list[str]]:
|
|
33
|
+
"""(text with secrets replaced by [redacted:kind], kinds that were found)."""
|
|
34
|
+
found: list[str] = []
|
|
35
|
+
for kind, rx in PATTERNS:
|
|
36
|
+
def repl(m, kind=kind):
|
|
37
|
+
if kind == "secret-assignment":
|
|
38
|
+
head = re.split(r"[:=]", m.group(0), maxsplit=1)[0]
|
|
39
|
+
return f"{head}=[redacted:{kind}]"
|
|
40
|
+
return f"[redacted:{kind}]"
|
|
41
|
+
new, n = rx.subn(repl, text)
|
|
42
|
+
if n:
|
|
43
|
+
found.append(kind)
|
|
44
|
+
text = new
|
|
45
|
+
return text, found
|
ccr/history/savings.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Cost-savings estimate and misroute detection over resolved history (`ccr stats`).
|
|
2
|
+
|
|
3
|
+
Savings: interactive sessions report tokens, not dollars, so each task's tokens are priced at
|
|
4
|
+
the blended USD/Mtok of the model its tier used (`pricing:` in .ccr/config.yaml) and compared
|
|
5
|
+
with the same tokens priced at an all-Opus and an all-Sonnet baseline. It is an estimate: it
|
|
6
|
+
assumes the stronger model would have used the same tokens, which ignores rework saved or
|
|
7
|
+
extra thinking spent.
|
|
8
|
+
|
|
9
|
+
Misroutes, from decided outcomes (feedback applied):
|
|
10
|
+
under the task failed or was escalated at the tier it was routed to
|
|
11
|
+
over the task succeeded at a tier above the class floor while the tier below has a proven
|
|
12
|
+
record (>= `history.min_samples` decided tasks, >= `history.success_rate_down`
|
|
13
|
+
success) for the same class x area, so a cheaper tier would likely have done
|
|
14
|
+
Suggestions group the under-routed tasks by the signals that fired (no prompt text is stored),
|
|
15
|
+
to show which rule to tune.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
from ccr.config import TIERS
|
|
21
|
+
from ccr.history.learn import FAILURE, SUCCESS, tier_counts
|
|
22
|
+
|
|
23
|
+
NO_FLOOR = {"question", "trivial"}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _num(v) -> float:
|
|
27
|
+
return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) else 0.0
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def price(cfg, model: str) -> float:
|
|
31
|
+
"""USD per Mtok for a model alias or id (matched by family name), 0 if unknown."""
|
|
32
|
+
m = str(model).lower()
|
|
33
|
+
for fam, usd in cfg["pricing"].items():
|
|
34
|
+
if fam in m:
|
|
35
|
+
return float(usd)
|
|
36
|
+
return 0.0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def estimate(records: list[dict], cfg) -> dict:
|
|
40
|
+
routed = opus = sonnet = 0.0
|
|
41
|
+
tokens = n = 0
|
|
42
|
+
d_routed = d_opus = 0.0 # decided tasks only, for cost per success
|
|
43
|
+
d_n = d_ok = 0
|
|
44
|
+
for r in records:
|
|
45
|
+
t, tok = r.get("tier"), _num(r.get("tokens"))
|
|
46
|
+
if t not in TIERS or tok <= 0:
|
|
47
|
+
continue
|
|
48
|
+
n += 1
|
|
49
|
+
tokens += int(tok)
|
|
50
|
+
c = tok * price(cfg, cfg.tier(t).model) / 1e6
|
|
51
|
+
routed += c
|
|
52
|
+
opus += tok * price(cfg, "opus") / 1e6
|
|
53
|
+
sonnet += tok * price(cfg, "sonnet") / 1e6
|
|
54
|
+
if r.get("outcome") in SUCCESS | FAILURE:
|
|
55
|
+
d_n += 1
|
|
56
|
+
d_ok += r["outcome"] in SUCCESS
|
|
57
|
+
d_routed += c
|
|
58
|
+
d_opus += tok * price(cfg, "opus") / 1e6
|
|
59
|
+
|
|
60
|
+
def saved(base: float):
|
|
61
|
+
return round(1 - routed / base, 3) if base else None
|
|
62
|
+
# Quality-adjusted: failed tasks still cost their tokens, so routed cost is divided by the
|
|
63
|
+
# successes. The all-Opus side assumes every task succeeds (the most favourable case for
|
|
64
|
+
# Opus), so a saving that survives this comparison is not just cheaper-and-worse.
|
|
65
|
+
per_ok = round(d_routed / d_ok, 4) if d_ok else None
|
|
66
|
+
opus_per = round(d_opus / d_n, 4) if d_n else None
|
|
67
|
+
return {"tasks": n, "tokens": tokens, "routed_usd": round(routed, 4),
|
|
68
|
+
"decided": d_n, "successes": d_ok, "routed_per_success": per_ok,
|
|
69
|
+
"opus_per_success": opus_per,
|
|
70
|
+
"saved_per_success": round(1 - per_ok / opus_per, 3) if per_ok and opus_per
|
|
71
|
+
else None,
|
|
72
|
+
"all_opus_usd": round(opus, 4), "all_sonnet_usd": round(sonnet, 4),
|
|
73
|
+
"saved_vs_opus": saved(opus), "saved_vs_sonnet": saved(sonnet),
|
|
74
|
+
"estimate": True}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _item(r: dict, kind: str, why: str) -> dict:
|
|
78
|
+
tr = r.get("trace") if isinstance(r.get("trace"), dict) else {}
|
|
79
|
+
return {"id": r.get("id"), "kind": kind, "class": r.get("class"), "area": r.get("area"),
|
|
80
|
+
"tier": r.get("tier"), "outcome": r.get("outcome"), "why": why,
|
|
81
|
+
"rules": tr.get("rules"), "hard": tr.get("hard"), "bumps": tr.get("bumps"),
|
|
82
|
+
"class_conf": tr.get("class_conf"), "has_trace": bool(tr)}
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def misroutes(records: list[dict], cfg) -> dict:
|
|
86
|
+
hc = cfg["history"]
|
|
87
|
+
k, down = int(hc["min_samples"]), float(hc["success_rate_down"])
|
|
88
|
+
tasks = [r for r in records if r.get("tier") in TIERS and r.get("class")]
|
|
89
|
+
decided = [r for r in tasks if r.get("outcome") in SUCCESS | FAILURE]
|
|
90
|
+
items: list[dict] = []
|
|
91
|
+
over = under = 0
|
|
92
|
+
for r in decided:
|
|
93
|
+
i = TIERS.index(r["tier"])
|
|
94
|
+
if r["outcome"] in FAILURE:
|
|
95
|
+
under += 1
|
|
96
|
+
items.append(_item(r, "under", f"{r['outcome']} at {r['tier']}"))
|
|
97
|
+
continue
|
|
98
|
+
floor = 0 if r["class"] in NO_FLOOR else 1
|
|
99
|
+
if i <= floor:
|
|
100
|
+
continue
|
|
101
|
+
stats, _ = tier_counts(records, r["class"], r.get("area"))
|
|
102
|
+
lo = stats.get(TIERS[i - 1])
|
|
103
|
+
n = sum(lo) if lo else 0
|
|
104
|
+
if n >= k and lo[0] / n >= down:
|
|
105
|
+
over += 1
|
|
106
|
+
items.append(_item(r, "over", f"{TIERS[i - 1]} succeeded {lo[0]}/{n} for "
|
|
107
|
+
f"{r['class']}"))
|
|
108
|
+
cues = cue_stats(decided, k, float(hc["fail_rate_up"]))
|
|
109
|
+
n = len(decided)
|
|
110
|
+
return {"decided": n, "cues": cues, "over": over, "under": under,
|
|
111
|
+
"over_rate": round(over / n, 3) if n else None,
|
|
112
|
+
"under_rate": round(under / n, 3) if n else None,
|
|
113
|
+
"items": items, "suggestions": suggestions(items) + [c["note"] for c in cues]}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def cue_stats(decided: list[dict], k: int, fail_up: float) -> list[dict]:
|
|
117
|
+
"""Per cue word and tier: outcomes of the tasks it fired on. A cue whose tasks keep
|
|
118
|
+
failing at the tier it routed to is a rule that has drifted (it under-rates the work)."""
|
|
119
|
+
st: dict[tuple[str, str], list[int]] = {}
|
|
120
|
+
for r in decided:
|
|
121
|
+
tr = r.get("trace") if isinstance(r.get("trace"), dict) else {}
|
|
122
|
+
for term in {*(tr.get("rules") or []), *(tr.get("hard_terms") or [])}:
|
|
123
|
+
c = st.setdefault((term, r["tier"]), [0, 0])
|
|
124
|
+
c[0 if r["outcome"] in SUCCESS else 1] += 1
|
|
125
|
+
out = []
|
|
126
|
+
for (term, tier), (ok, bad) in sorted(st.items()):
|
|
127
|
+
n = ok + bad
|
|
128
|
+
if n >= k and bad / n >= fail_up:
|
|
129
|
+
out.append({"term": term, "tier": tier, "ok": ok, "failed": bad,
|
|
130
|
+
"note": f"cue '{term}' failed {bad}/{n} at {tier}: it under-rates "
|
|
131
|
+
f"these tasks; weight it up or add it to hard_terms"})
|
|
132
|
+
return out
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def suggestions(items: list[dict]) -> list[str]:
|
|
136
|
+
"""Which rule to tune, from the under-routed tasks (grouped by class and tier)."""
|
|
137
|
+
groups: dict[tuple, list[dict]] = {}
|
|
138
|
+
for it in items:
|
|
139
|
+
if it["kind"] == "under":
|
|
140
|
+
groups.setdefault((it["class"], it["tier"]), []).append(it)
|
|
141
|
+
out = []
|
|
142
|
+
for (kind, tier), its in sorted(groups.items(), key=lambda kv: -len(kv[1])):
|
|
143
|
+
n = len(its)
|
|
144
|
+
traced = [i for i in its if i["has_trace"]]
|
|
145
|
+
bare = [i for i in traced if not i["rules"]]
|
|
146
|
+
calm = [i for i in traced if not i["hard"] and not i["bumps"]]
|
|
147
|
+
if bare:
|
|
148
|
+
out.append(f"{len(bare)}/{n} {kind} task(s) failed at {tier} with no cue word "
|
|
149
|
+
f"matched: the class was a guess; raise class_base.{kind} or add "
|
|
150
|
+
f"cues to the rules")
|
|
151
|
+
if kind in ("bugfix", "perf") and calm:
|
|
152
|
+
out.append(f"{len(calm)}/{n} {kind} task(s) failed at {tier} with no hard or "
|
|
153
|
+
f"escalation signal: add project words that mean 'hard' to "
|
|
154
|
+
f"`hard_terms:` in .ccr/config.yaml")
|
|
155
|
+
if not traced:
|
|
156
|
+
out.append(f"{n} {kind} task(s) failed at {tier}; older records have no routing "
|
|
157
|
+
f"trace to tune from")
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def format_lines(est: dict, mis: dict, detail: bool = False) -> list[str]:
|
|
162
|
+
def pct(v):
|
|
163
|
+
return "-" if v is None else f"{100 * v:.0f}%"
|
|
164
|
+
out = []
|
|
165
|
+
if est["tasks"]:
|
|
166
|
+
out.append(f"Savings: est. ${est['routed_usd']:.2f} routed vs ${est['all_opus_usd']:.2f}"
|
|
167
|
+
f" all-Opus ({pct(est['saved_vs_opus'])} saved) and "
|
|
168
|
+
f"${est['all_sonnet_usd']:.2f} all-Sonnet ({pct(est['saved_vs_sonnet'])}) "
|
|
169
|
+
f"over {est['tasks']} tasks; estimate from tokens x `pricing:`")
|
|
170
|
+
if est["saved_per_success"] is not None:
|
|
171
|
+
out.append(f" per success (failures cost tokens too; Opus assumed to "
|
|
172
|
+
f"always succeed): ${est['routed_per_success']:.4f} routed vs "
|
|
173
|
+
f"${est['opus_per_success']:.4f} all-Opus "
|
|
174
|
+
f"({pct(est['saved_per_success'])} saved)")
|
|
175
|
+
if mis["decided"]:
|
|
176
|
+
out.append(f"Misroutes: over-routed {mis['over']}/{mis['decided']} "
|
|
177
|
+
f"({pct(mis['over_rate'])}, a cheaper tier had a proven record), "
|
|
178
|
+
f"under-routed {mis['under']}/{mis['decided']} ({pct(mis['under_rate'])}, "
|
|
179
|
+
f"failed or escalated)")
|
|
180
|
+
out += [f" tune: {s}" for s in mis["suggestions"]]
|
|
181
|
+
if detail:
|
|
182
|
+
for it in mis["items"]:
|
|
183
|
+
tid = str(it["id"] or "?")[:8]
|
|
184
|
+
out.append(f" [{tid}] {it['kind']:<5} {it['tier']} {it['class']} in "
|
|
185
|
+
f"{it['area'] or '*'}: {it['why']}; rules={it['rules'] or '-'} "
|
|
186
|
+
f"hard={it['hard']} bumps={it['bumps'] or '-'}")
|
|
187
|
+
return out
|