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/headless.py ADDED
@@ -0,0 +1,363 @@
1
+ """`ccr run`: route a task, run it with the user's own `claude -p`, escalate once on failure.
2
+
3
+ Each attempt runs
4
+ claude -p --model <tier model> --effort <tier effort> --output-format json
5
+ --max-turns N [--max-budget-usd X] [--permission-mode M]
6
+ with the task on stdin (never on the command line) and CCR_INTERNAL=1 so ccr's own hooks
7
+ stay silent inside it. The result object of the installed build (verified on 2.1.x) has
8
+ `type: "result"`, `subtype` (`success`, `error_max_turns`, `error_max_budget_usd`,
9
+ `error_during_execution`, ...), `is_error`, `num_turns`, `total_cost_usd`, `usage`
10
+ (input/output/cache tokens), `modelUsage` ({model id: {inputTokens, outputTokens,
11
+ cacheReadInputTokens, cacheCreationInputTokens, costUSD}}), `session_id` and `result` (the
12
+ final text; absent on error subtypes). A failing run exits 1 and still prints that object.
13
+
14
+ Success = exit 0, `is_error` false, `subtype` success and, when configured, `run.test_command`
15
+ exiting 0. On failure the next attempt runs exactly one tier higher (never skipping a tier;
16
+ T4 only when a critical-path rule allows it) until `run.max_escalations` (default 1) is used
17
+ up. A failure that escalation cannot fix (claude missing, unparseable output, timeout)
18
+ stops the run with outcome `error`, which learning does not count. Every attempt appends one
19
+ history record (whitelisted fields only, no prompt text); the escalated attempt is recorded
20
+ as a `failure` of its tier with `escalated_to`, the next one carries `escalated_from`.
21
+ `max_budget_usd` caps the whole run: later attempts only get what is left.
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import contextlib
26
+ import json
27
+ import os
28
+ import shutil
29
+ import subprocess
30
+ import time
31
+ from dataclasses import dataclass, field
32
+ from pathlib import Path
33
+ from typing import TYPE_CHECKING, Callable
34
+
35
+ from ccr.config import TIERS, TOP, Config
36
+
37
+ if TYPE_CHECKING:
38
+ from ccr.route import Decision
39
+
40
+ TEST_TAIL_CHARS = 3000
41
+
42
+
43
+ @dataclass
44
+ class Proc:
45
+ returncode: int
46
+ stdout: str = ""
47
+ stderr: str = ""
48
+
49
+
50
+ # runner(argv, stdin_text, cwd, env, timeout) -> Proc; raises OSError /
51
+ # subprocess.TimeoutExpired like subprocess.run
52
+ Runner = Callable[[list, str, Path, dict, float], Proc]
53
+ TestRunner = Callable[[str, Path, dict, float], Proc]
54
+
55
+
56
+ def default_runner(argv: list, stdin_text: str, cwd: Path, env: dict, timeout: float) -> Proc:
57
+ r = subprocess.run(argv, input=stdin_text, capture_output=True, text=True, cwd=cwd,
58
+ env=env, timeout=timeout, check=False)
59
+ return Proc(r.returncode, r.stdout or "", r.stderr or "")
60
+
61
+
62
+ def default_test_runner(command: str, cwd: Path, env: dict, timeout: float) -> Proc:
63
+ r = subprocess.run(command, shell=True, capture_output=True, text=True, cwd=cwd, env=env,
64
+ timeout=timeout, check=False)
65
+ return Proc(r.returncode, r.stdout or "", r.stderr or "")
66
+
67
+
68
+ @dataclass
69
+ class Attempt:
70
+ tier: str
71
+ model: str
72
+ effort: str
73
+ outcome: str = "failure" # success | failure | error
74
+ reason: str = "" # success, error_max_turns, exit_1, test_failed, ...
75
+ subtype: str | None = None
76
+ exit_code: int | None = None
77
+ is_error: bool | None = None
78
+ turns: int | None = None
79
+ cost_usd: float | None = None
80
+ tokens: int = 0
81
+ usage: dict = field(default_factory=dict)
82
+ models: dict = field(default_factory=dict)
83
+ session: str | None = None
84
+ duration_ms: int | None = None
85
+ test: str | None = None # pass | fail | timeout | None (not configured)
86
+ result: str = "" # final text (printed, never stored)
87
+ test_tail: str = "" # end of the test output (fed to the next attempt only)
88
+ escalated_to: str | None = None
89
+ record: dict = field(default_factory=dict)
90
+
91
+
92
+ @dataclass
93
+ class RunResult:
94
+ decision: object
95
+ attempts: list[Attempt]
96
+ run_id: str
97
+ stopped: str = "" # why escalation stopped, if it did
98
+
99
+ @property
100
+ def success(self) -> bool:
101
+ return bool(self.attempts) and self.attempts[-1].outcome == "success"
102
+
103
+ @property
104
+ def cost_usd(self) -> float:
105
+ return round(sum(a.cost_usd or 0.0 for a in self.attempts), 6)
106
+
107
+ @property
108
+ def tokens(self) -> int:
109
+ return sum(a.tokens for a in self.attempts)
110
+
111
+ def to_dict(self) -> dict:
112
+ d = self.decision
113
+ return {"run_id": self.run_id, "success": self.success, "stopped": self.stopped,
114
+ "class": d.task_class.kind, "area": d.area, "routed_tier": d.tier.name,
115
+ "cost_usd": self.cost_usd, "tokens": self.tokens,
116
+ "attempts": [{k: v for k, v in a.__dict__.items()
117
+ if k not in ("record", "test_tail")} for a in self.attempts]}
118
+
119
+
120
+ def find_claude(env: dict) -> str | None:
121
+ return shutil.which("claude", path=env.get("PATH"))
122
+
123
+
124
+ def build_argv(exe: str, tier, *, max_turns: int, max_budget_usd: float | None,
125
+ permission_mode: str | None) -> list[str]:
126
+ argv = [exe, "-p", "--model", tier.model, "--effort", tier.effort,
127
+ "--output-format", "json", "--max-turns", str(int(max_turns))]
128
+ if max_budget_usd is not None:
129
+ argv += ["--max-budget-usd", f"{max_budget_usd:.4f}".rstrip("0").rstrip(".")]
130
+ if permission_mode:
131
+ argv += ["--permission-mode", permission_mode]
132
+ return argv
133
+
134
+
135
+ def _int(v) -> int:
136
+ return v if isinstance(v, int) and not isinstance(v, bool) and v > 0 else 0
137
+
138
+
139
+ def parse_result(stdout: str) -> dict | None:
140
+ """The `type: result` object from --output-format json (last JSON line wins)."""
141
+ text = (stdout or "").strip()
142
+ if not text:
143
+ return None
144
+ cands = [text] + [ln for ln in reversed(text.splitlines()) if ln.strip().startswith("{")]
145
+ for c in cands:
146
+ try:
147
+ obj = json.loads(c)
148
+ except ValueError:
149
+ continue
150
+ if isinstance(obj, list): # stream-style array: take the result element
151
+ obj = next((o for o in reversed(obj) if isinstance(o, dict)
152
+ and o.get("type") == "result"), None)
153
+ if isinstance(obj, dict) and ("subtype" in obj or "is_error" in obj):
154
+ return obj
155
+ return None
156
+
157
+
158
+ def absorb_result(a: Attempt, data: dict) -> None:
159
+ a.subtype = data.get("subtype") if isinstance(data.get("subtype"), str) else None
160
+ a.is_error = data.get("is_error") if isinstance(data.get("is_error"), bool) else None
161
+ a.turns = data.get("num_turns") if isinstance(data.get("num_turns"), int) else None
162
+ c = data.get("total_cost_usd")
163
+ a.cost_usd = round(float(c), 6) if isinstance(c, (int, float)) and \
164
+ not isinstance(c, bool) else None
165
+ d = data.get("duration_ms")
166
+ a.duration_ms = int(d) if isinstance(d, (int, float)) and not isinstance(d, bool) else None
167
+ a.session = data.get("session_id") if isinstance(data.get("session_id"), str) else None
168
+ u = data.get("usage") if isinstance(data.get("usage"), dict) else {}
169
+ a.usage = {k: _int(u.get(f"{k}_tokens")) for k in
170
+ ("input", "output", "cache_creation_input", "cache_read_input")}
171
+ a.usage = {k.replace("_input", ""): v for k, v in a.usage.items() if v}
172
+ models = {}
173
+ mu = data.get("modelUsage") if isinstance(data.get("modelUsage"), dict) else {}
174
+ for mid, m in mu.items():
175
+ if not isinstance(m, dict):
176
+ continue
177
+ toks = sum(_int(m.get(k)) for k in ("inputTokens", "outputTokens",
178
+ "cacheCreationInputTokens"))
179
+ cost = m.get("costUSD")
180
+ models[str(mid)[:80]] = {"tokens": toks, **(
181
+ {"cost_usd": round(float(cost), 6)} if isinstance(cost, (int, float)) else {})}
182
+ a.models = models
183
+ # same definition as hook records: input + output + cache creation (no cache reads)
184
+ a.tokens = sum(v["tokens"] for v in models.values()) if models else \
185
+ sum(a.usage.get(k, 0) for k in ("input", "output", "cache_creation"))
186
+ r = data.get("result")
187
+ a.result = r if isinstance(r, str) else ""
188
+
189
+
190
+ def _escalation_note(prev: Attempt) -> str:
191
+ why = {"test_failed": "the test command failed afterwards",
192
+ "error_max_turns": "it ran out of turns",
193
+ "error_max_budget_usd": "it hit the budget cap"}.get(prev.reason, prev.reason)
194
+ note = (f"\n\n[ccr] A previous attempt at {prev.tier} ({prev.model}/{prev.effort}) did "
195
+ f"not finish the task: {why}. The working tree may contain its partial changes; "
196
+ f"review them, then complete the task.")
197
+ if prev.test_tail:
198
+ note += f"\nEnd of the test output:\n```\n{prev.test_tail}\n```"
199
+ return note
200
+
201
+
202
+ def next_tier(cur: int, decision, cfg) -> tuple[int | None, str]:
203
+ """(next tier index or None, reason when None). Exactly one tier up, never skipping."""
204
+ if cur >= TOP:
205
+ return None, "already at T4"
206
+ nxt = cur + 1
207
+ rule = bool(getattr(decision, "t4_rules", None))
208
+ ceiling = TIERS.index(cfg["routing"]["ceiling_without_critical"])
209
+ if nxt == TOP and not rule:
210
+ return None, "T4 needs a critical-path rule"
211
+ if nxt > ceiling and not rule:
212
+ return None, f"routing.ceiling_without_critical is {TIERS[ceiling]}"
213
+ return nxt, ""
214
+
215
+
216
+ def _invoke(a: Attempt, exe: str | None, t, runner: Runner, prompt: str, root: Path, env: dict,
217
+ rc: dict, max_turns: int, left: float | None, permission_mode: str | None) -> None:
218
+ """Run claude once and fill `a` with the outcome."""
219
+ if exe is None:
220
+ a.outcome, a.reason = "error", "claude_not_found"
221
+ return
222
+ argv = build_argv(exe, t, max_turns=max_turns, max_budget_usd=left,
223
+ permission_mode=permission_mode)
224
+ try:
225
+ p = runner(argv, prompt, root, env, float(rc["timeout_s"]))
226
+ except subprocess.TimeoutExpired:
227
+ a.outcome, a.reason = "error", "timeout"
228
+ return
229
+ except OSError as e:
230
+ a.outcome, a.reason = "error", f"cannot_run ({e.__class__.__name__})"
231
+ return
232
+ a.exit_code = p.returncode
233
+ data = parse_result(p.stdout)
234
+ if data is None:
235
+ a.outcome, a.reason = "error", f"no_json_exit_{p.returncode}"
236
+ return
237
+ absorb_result(a, data)
238
+ if p.returncode == 0 and a.is_error is False and a.subtype == "success":
239
+ a.outcome, a.reason = "success", "success"
240
+ else:
241
+ a.outcome = "failure"
242
+ a.reason = (a.subtype if a.subtype and a.subtype != "success"
243
+ else "is_error" if a.is_error else f"exit_{p.returncode}")
244
+
245
+
246
+ def _run_tests(a: Attempt, test_cmd: str, test_runner: TestRunner, root: Path, env: dict,
247
+ rc: dict) -> None:
248
+ """Run the project's tests after a successful attempt; a failure downgrades the outcome."""
249
+ try:
250
+ tp = test_runner(test_cmd, root, {k: v for k, v in env.items() if k != "CCR_INTERNAL"},
251
+ float(rc["test_timeout_s"]))
252
+ a.test = "pass" if tp.returncode == 0 else "fail"
253
+ a.test_tail = ((tp.stdout or "") + (tp.stderr or ""))[-TEST_TAIL_CHARS:]
254
+ except subprocess.TimeoutExpired:
255
+ a.test = "timeout"
256
+ except OSError:
257
+ a.test = "fail"
258
+ if a.test != "pass":
259
+ a.outcome, a.reason = "failure", "test_failed"
260
+
261
+
262
+ def run_task(task: str, root: str | Path, *, cfg: Config | None = None, tier: str | None = None,
263
+ max_turns: int | None = None, max_budget_usd: float | None = None,
264
+ max_escalations: int | None = None, test_command: str | None = None,
265
+ use_tests: bool = True, permission_mode: str | None = None,
266
+ allow_llm: bool = True, runner: Runner | None = None,
267
+ test_runner: TestRunner | None = None, environ: dict | None = None,
268
+ decision: Decision | None = None, echo: Callable[[str], None] | None = None,
269
+ record: bool = True, claude_exe: str | None = None) -> RunResult:
270
+ from ccr import history as H
271
+ from ccr.config import load_config
272
+ root = Path(root).resolve()
273
+ cfg = cfg or load_config(root)
274
+ rc = cfg["run"]
275
+ runner = runner or default_runner
276
+ test_runner = test_runner or default_test_runner
277
+ say = echo or (lambda s: None)
278
+ env = dict(os.environ if environ is None else environ)
279
+ env["CCR_INTERNAL"] = "1" # ccr hooks no-op inside the child
280
+ env.pop("CLAUDE_CODE_EFFORT_LEVEL", None) # it would override --effort
281
+ max_turns = int(max_turns or rc["max_turns"])
282
+ budget = max_budget_usd if max_budget_usd is not None else rc["max_budget_usd"]
283
+ max_esc = int(rc["max_escalations"] if max_escalations is None else max_escalations)
284
+ test_cmd = (test_command or rc["test_command"]) if use_tests else None
285
+ permission_mode = permission_mode or rc["permission_mode"]
286
+
287
+ if decision is None:
288
+ from ccr.route import decide
289
+ decision = decide(task, root, cfg=cfg, allow_llm=allow_llm, llm_runner=None)
290
+ d = decision
291
+ assist_cost = None
292
+ if d.llm_used and "[~$" in d.llm:
293
+ with contextlib.suppress(ValueError):
294
+ assist_cost = float(d.llm.rsplit("[~$", 1)[1].rstrip("]"))
295
+ cur = TIERS.index(tier) if tier else d.tier.index
296
+ res = RunResult(decision=d, attempts=[], run_id=H.new_id())
297
+ exe = claude_exe or find_claude(env)
298
+ escalations = 0
299
+ prompt = task
300
+ while True:
301
+ t = cfg.tier(cur)
302
+ a = Attempt(tier=t.name, model=t.model, effort=t.effort)
303
+ left = None if budget is None else round(float(budget) - res.cost_usd, 4)
304
+ prev = res.attempts[-1] if res.attempts else None
305
+ say(f"attempt {len(res.attempts) + 1}: {t.name} {t.model}/{t.effort}"
306
+ + (f" (escalated from {prev.tier})" if prev else "")
307
+ + (f", budget left ${left:.2f}" if left is not None else ""))
308
+ t0 = time.time()
309
+ _invoke(a, exe, t, runner, prompt, root, env, rc, max_turns, left, permission_mode)
310
+ if a.duration_ms is None:
311
+ a.duration_ms = int((time.time() - t0) * 1000)
312
+ if a.outcome == "success" and test_cmd:
313
+ say(f" test: {test_cmd}")
314
+ _run_tests(a, test_cmd, test_runner, root, env, rc)
315
+ res.attempts.append(a)
316
+
317
+ nxt, why = (None, "")
318
+ if a.outcome == "failure":
319
+ if escalations >= max_esc:
320
+ why = f"max_escalations {max_esc} reached"
321
+ else:
322
+ nxt, why = next_tier(cur, d, cfg)
323
+ if nxt is not None and budget is not None and \
324
+ float(budget) - res.cost_usd < 0.001:
325
+ nxt, why = None, f"budget ${float(budget):.2f} used up (${res.cost_usd:.4f})"
326
+ if nxt is not None:
327
+ a.escalated_to = TIERS[nxt]
328
+ if record:
329
+ rec = H.make_record(d, a.outcome, tier=a.tier, model=a.model, effort=a.effort,
330
+ source="run", run_id=res.run_id, attempt=len(res.attempts),
331
+ reason=a.reason, subtype=a.subtype, exit_code=a.exit_code,
332
+ tokens=a.tokens or None, cost_usd=a.cost_usd, turns=a.turns,
333
+ usage=a.usage or None, models=a.models or None,
334
+ duration_ms=a.duration_ms, test=a.test,
335
+ session=a.session, escalated_to=a.escalated_to,
336
+ escalated_from=prev.tier if prev else None,
337
+ forced=True if tier else None,
338
+ assist_cost_usd=assist_cost if not prev else None)
339
+ a.record = rec
340
+ try:
341
+ H.append(root, rec)
342
+ if cfg["hooks"]["store_prompts"]:
343
+ from ccr.history import prompts
344
+ prompts.append(root, prompts.snapshot(
345
+ rec["id"], task, d, t, "headless run", retry=bool(prev),
346
+ escalated_from=prev.tier if prev else None,
347
+ redact=cfg["hooks"]["redact_prompts"]))
348
+ except OSError as e:
349
+ say(f" ! could not write history: {e}")
350
+ cost = f"${a.cost_usd:.4f}" if a.cost_usd is not None else "cost n/a"
351
+ say(f" -> {a.outcome} ({a.reason}; {a.turns if a.turns is not None else '?'} turns, "
352
+ f"{a.tokens} tokens, {cost}" + (f", test {a.test}" if a.test else "") + ")")
353
+ if a.outcome != "failure":
354
+ break
355
+ if nxt is None:
356
+ res.stopped = why
357
+ say(f" no escalation: {why}")
358
+ break
359
+ say(f" escalating {a.tier} -> {TIERS[nxt]}")
360
+ escalations += 1
361
+ prompt = task + _escalation_note(a)
362
+ cur = nxt
363
+ return res
@@ -0,0 +1,172 @@
1
+ """Routing history in `.ccr/history.jsonl` (one JSON object per line, append-only).
2
+
3
+ Records hold only routing metadata: class, area (a directory prefix), tier, model, effort,
4
+ outcome, usage numbers. Prompt text is never stored: `make_record` / `append` drop any field
5
+ outside the whitelist.
6
+
7
+ Two record types share the file:
8
+ task one routed task or one `ccr run` attempt (no `type` field); has a random `id`
9
+ feedback `{"type": "feedback", "ref": <task id>, "outcome": ..., "feedback": good|bad}`,
10
+ written by `ccr feedback`; it corrects the task's outcome at read time
11
+ The file is never rewritten. `read()` resolves it: corrupt lines (including git conflict
12
+ markers) are skipped, duplicate lines (same `id`, or identical content for old records
13
+ without one) count once, records are ordered by `ts`, and the newest feedback for a task
14
+ wins, wherever it appears in the file. So a team can merge the file by concatenation
15
+ (`.gitattributes`: `.ccr/history.jsonl merge=union`) and nothing double counts.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import time
22
+ import uuid
23
+ from pathlib import Path
24
+
25
+ FIELDS = ("id", "type", "ref", "feedback",
26
+ "ts", "session", "class", "area", "tier", "model", "effort", "outcome", "tokens",
27
+ "cost_usd", "turns", "risk", "confidence", "escalated_from", "escalated_to", "source",
28
+ # hook-recorded signals (no prompt text): main-session model, subagents used
29
+ # ({agent_type: count}), tool errors seen, outcome hints
30
+ "main_model", "agents", "tool_errors", "signals",
31
+ # `ccr run` attempts: grouping, failure reason code, usage breakdown, per-model
32
+ # usage ({model id: {tokens, cost_usd}}), test command result
33
+ "run_id", "attempt", "reason", "subtype", "exit_code", "usage", "models",
34
+ "duration_ms", "test", "forced", "assist_cost_usd",
35
+ # routing signals behind the decision (Decision.trace(): no prompt text)
36
+ "trace")
37
+ OUTCOMES = ("success", "failure", "escalated", "abandoned", "error")
38
+ SUCCESS = {"success"}
39
+ FAILURE = {"failure", "escalated"}
40
+ FEEDBACK = {"good": "success", "bad": "failure"}
41
+ MAX_READ_BYTES = 4_000_000
42
+
43
+
44
+ def history_path(root: str | Path) -> Path:
45
+ return Path(root) / ".ccr" / "history.jsonl"
46
+
47
+
48
+ def new_id() -> str:
49
+ return uuid.uuid4().hex[:16]
50
+
51
+
52
+ def make_record(decision=None, outcome: str | None = None, **extra) -> dict:
53
+ """Whitelisted task record for a routing decision (a ccr.route.Decision or a dict)."""
54
+ rec: dict = {"ts": int(time.time())}
55
+ if decision is not None:
56
+ d = decision.record() if hasattr(decision, "record") else dict(decision)
57
+ rec.update(d)
58
+ if outcome is not None:
59
+ rec["outcome"] = outcome
60
+ rec.update(extra)
61
+ if not rec.get("id"):
62
+ rec["id"] = new_id()
63
+ return {k: v for k, v in rec.items() if k in FIELDS and v is not None}
64
+
65
+
66
+ def feedback_record(ref: str, verdict: str, now: float | None = None) -> dict:
67
+ if verdict not in FEEDBACK:
68
+ raise ValueError(f"verdict must be one of {', '.join(FEEDBACK)}")
69
+ return {"id": new_id(), "type": "feedback", "ts": int(now or time.time()), "ref": ref,
70
+ "outcome": FEEDBACK[verdict], "feedback": verdict}
71
+
72
+
73
+ def append(root: str | Path, record: dict) -> None:
74
+ p = history_path(root)
75
+ p.parent.mkdir(parents=True, exist_ok=True)
76
+ clean = {k: v for k, v in record.items() if k in FIELDS}
77
+ line = json.dumps(clean, separators=(",", ":")) + "\n"
78
+ # one write() per record on an O_APPEND descriptor: concurrent writers do not interleave
79
+ fd = os.open(p, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o644)
80
+ try:
81
+ os.write(fd, line.encode("utf-8"))
82
+ finally:
83
+ os.close(fd)
84
+
85
+
86
+ def read_raw(root: str | Path | None = None, path: str | Path | None = None) -> list[dict]:
87
+ """Every parseable object line, in file order (no dedup, no feedback resolution)."""
88
+ p = Path(path) if path else history_path(root)
89
+ try:
90
+ size = os.path.getsize(p)
91
+ except OSError:
92
+ return []
93
+ try:
94
+ with open(p, "rb") as f:
95
+ if size > MAX_READ_BYTES:
96
+ f.seek(size - MAX_READ_BYTES)
97
+ f.readline() # drop the partial first line
98
+ raw = f.read().decode("utf-8", errors="replace")
99
+ except OSError:
100
+ return []
101
+ out = []
102
+ for line in raw.splitlines():
103
+ line = line.strip()
104
+ if not line or line[0] != "{": # blank, conflict markers, garbage
105
+ continue
106
+ try:
107
+ rec = json.loads(line)
108
+ except ValueError:
109
+ continue
110
+ if isinstance(rec, dict):
111
+ out.append(rec)
112
+ return out
113
+
114
+
115
+ def record_key(rec: dict) -> str:
116
+ """Identity for dedup: the `id`, else the canonical content (old id-less records)."""
117
+ rid = rec.get("id")
118
+ if isinstance(rid, str) and rid:
119
+ return "id:" + rid
120
+ return "c:" + json.dumps(rec, sort_keys=True, separators=(",", ":"))
121
+
122
+
123
+ def _ts(rec: dict) -> float:
124
+ ts = rec.get("ts")
125
+ return float(ts) if isinstance(ts, (int, float)) and not isinstance(ts, bool) else 0.0
126
+
127
+
128
+ def resolve(raw: list[dict]) -> list[dict]:
129
+ """Dedup, order by ts, apply the newest feedback per task. Returns task records only
130
+ (copies; a corrected record gets `outcome` from feedback and `feedback: good|bad`)."""
131
+ seen: set[str] = set()
132
+ tasks: list[dict] = []
133
+ fbs: dict[str, tuple[float, int, dict]] = {}
134
+ for i, rec in enumerate(raw):
135
+ k = record_key(rec)
136
+ if k in seen:
137
+ continue
138
+ seen.add(k)
139
+ if rec.get("type") == "feedback":
140
+ ref = rec.get("ref")
141
+ if not isinstance(ref, str) or rec.get("outcome") not in OUTCOMES:
142
+ continue
143
+ cur = fbs.get(ref)
144
+ if cur is None or (_ts(rec), i) >= cur[:2]:
145
+ fbs[ref] = (_ts(rec), i, rec)
146
+ elif rec.get("type") is None:
147
+ tasks.append(rec)
148
+ tasks.sort(key=_ts) # stable: equal timestamps keep file order
149
+ out = []
150
+ for rec in tasks:
151
+ fb = fbs.get(rec.get("id")) if isinstance(rec.get("id"), str) else None
152
+ if fb is not None:
153
+ rec = {**rec, "outcome": fb[2]["outcome"], "feedback": fb[2].get("feedback")}
154
+ out.append(rec)
155
+ return out
156
+
157
+
158
+ def read(root: str | Path, window_days: float | None = None, now: float | None = None,
159
+ path: str | Path | None = None) -> list[dict]:
160
+ """Resolved task records (see `resolve`), optionally only those newer than the window."""
161
+ recs = resolve(read_raw(root, path))
162
+ if not window_days:
163
+ return recs
164
+ cutoff = (now if now is not None else time.time()) - window_days * 86400
165
+ return [r for r in recs if isinstance(r.get("ts"), (int, float)) and r["ts"] >= cutoff]
166
+
167
+
168
+ def tier_stats(records: list[dict], kind: str, area: str | None) -> tuple[dict, str]:
169
+ """{tier: [successes, failures]} for class x area, else class-wide. Returns (stats, scope)
170
+ where scope is "area" or "class"."""
171
+ from ccr.history.learn import tier_counts
172
+ return tier_counts(records, kind, area)