compactlab 0.2.0__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 (67) hide show
  1. compactlab/__init__.py +3 -0
  2. compactlab/adapters/__init__.py +2 -0
  3. compactlab/adapters/base.py +212 -0
  4. compactlab/adapters/cache.py +396 -0
  5. compactlab/adapters/claude_code.py +226 -0
  6. compactlab/adapters/codex.py +298 -0
  7. compactlab/adapters/dsh.py +287 -0
  8. compactlab/adapters/gemini_cli.py +259 -0
  9. compactlab/adapters/opencode.py +375 -0
  10. compactlab/apply/__init__.py +582 -0
  11. compactlab/cli/__init__.py +5 -0
  12. compactlab/cli/main.py +2436 -0
  13. compactlab/data/config_knobs.json +158 -0
  14. compactlab/data/harness_defaults.json +72 -0
  15. compactlab/data/harness_formats.json +300 -0
  16. compactlab/data/pricing.json +51 -0
  17. compactlab/engine/__init__.py +138 -0
  18. compactlab/engine/live.py +306 -0
  19. compactlab/engine/settings.py +175 -0
  20. compactlab/engine/watch.py +82 -0
  21. compactlab/eval/__init__.py +1 -0
  22. compactlab/eval/deep.py +390 -0
  23. compactlab/eval/executors.py +84 -0
  24. compactlab/eval/factcheck.py +75 -0
  25. compactlab/lens.py +80 -0
  26. compactlab/model/__init__.py +285 -0
  27. compactlab/pricing/__init__.py +211 -0
  28. compactlab/pricing/auto.py +118 -0
  29. compactlab/pricing/ids.py +148 -0
  30. compactlab/pricing/refresh.py +299 -0
  31. compactlab/publish.py +125 -0
  32. compactlab/py.typed +0 -0
  33. compactlab/recommend/__init__.py +201 -0
  34. compactlab/recommend/claude_code.py +172 -0
  35. compactlab/recommend/codex.py +104 -0
  36. compactlab/recommend/dsh.py +89 -0
  37. compactlab/recommend/gemini_cli.py +85 -0
  38. compactlab/recommend/opencode.py +117 -0
  39. compactlab/recommend/units.py +63 -0
  40. compactlab/report/__init__.py +3 -0
  41. compactlab/report/html.py +27 -0
  42. compactlab/report/template.html +1189 -0
  43. compactlab/service/__init__.py +1 -0
  44. compactlab/service/core.py +220 -0
  45. compactlab/service/http.py +133 -0
  46. compactlab/service/lock.py +92 -0
  47. compactlab/service/policy.py +258 -0
  48. compactlab/service/schedule.py +212 -0
  49. compactlab/share.py +553 -0
  50. compactlab/sim/__init__.py +1 -0
  51. compactlab/sim/baseline.py +214 -0
  52. compactlab/sim/calibrate.py +108 -0
  53. compactlab/sim/engine.py +1130 -0
  54. compactlab/sim/select.py +238 -0
  55. compactlab/sim/timing.py +134 -0
  56. compactlab/synth.py +416 -0
  57. compactlab/term/__init__.py +0 -0
  58. compactlab/term/style.py +134 -0
  59. compactlab/term/top.py +531 -0
  60. compactlab/term/views.py +598 -0
  61. compactlab/term/widgets.py +238 -0
  62. compactlab/verify.py +462 -0
  63. compactlab-0.2.0.dist-info/METADATA +243 -0
  64. compactlab-0.2.0.dist-info/RECORD +67 -0
  65. compactlab-0.2.0.dist-info/WHEEL +4 -0
  66. compactlab-0.2.0.dist-info/entry_points.txt +2 -0
  67. compactlab-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,598 @@
1
+ """Terminal views of a result: header, a panel per group, the recommendations table; doctor and serve banners.
2
+
3
+ Figures follow the report: percent of the harness default first (cost vs its window cost, time vs its wall-clock,
4
+ the engine's d_cost_pct / d_time_pct), the per-day amount second, ▼ saves (green) / ▲ adds (amber), grey = the
5
+ default. Aggregates divide summed amounts by the summed default of the models with a "set" group.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import time
12
+ from datetime import UTC, datetime
13
+ from typing import Any
14
+
15
+ from .style import Line, clip, cw, pad, width
16
+ from .widgets import (
17
+ chip,
18
+ fmin,
19
+ fpct,
20
+ fusd,
21
+ gauge,
22
+ header,
23
+ k,
24
+ money,
25
+ pack,
26
+ panel,
27
+ spark,
28
+ was_now,
29
+ )
30
+
31
+ PROFILES = ("cost", "balanced", "time")
32
+ PGLYPH = {"cost": "$", "balanced": "◆", "time": "◷"}
33
+ W: dict[str, dict[str, str]] = {
34
+ "en": {"history": "history", "harnesses": "harnesses", "models": "models", "calibrated": "calibrated",
35
+ "service": "service", "impact": "if applied", "sessions": "sessions", "turns": "turns", "days": "d",
36
+ "cost": "cost", "balanced": "balanced", "time": "time", "was": "was", "now": "now", "per_day": "/day",
37
+ "vs_default": "per day vs default", "set": "change", "keep": "keep default", "cur": "keep current",
38
+ "wall": "wall-clock",
39
+ "costm": "cost", "noop": "no change",
40
+ "no_change": "No change needed", "never": "never reaches the default", "recs": "Recommended settings",
41
+ "by_thr": "cost by threshold", "foot": "Δ vs the harness default · list-price estimates · recall is a "
42
+ "lite-mode proxy · --plain prints the full tables", "models_set": "{n} model(s) to change", "ago": "{t} ago",
43
+ "next": "next {t}", "up": "up", "down": "not running", "none": "–",
44
+ "kw_above": "{a} is not below the default {b}",
45
+ "kw_score": "no net gain at ${v:g}/h (net {n}/day)",
46
+ "kw_small": "net gain under {tol:g}% at ${v:g}/h ({n}/day)",
47
+ "kw_cur": "{p} would not beat your {c} by more than {tol:g}% at ${v:g}/h (net {n}/day)",
48
+ "kw_glob": "Codex has one limit for every model; across {ms} it is {a}",
49
+ "kw_sup": "replaced by {b}: Codex's one limit follows the models in use",
50
+ "kw_worth": "not worth it at ${v:g}/h: saves {u}/day but adds {m}/day of wall-clock (= {tv})",
51
+ "unsafe": "░ recall < {f:g}", "saved": "░ = saved", "cache": "cache {t}", "to": "set", "more": "+{n} more"},
52
+ "zh": {"history": "历史", "harnesses": "工具", "models": "模型", "calibrated": "校准", "service": "服务",
53
+ "impact": "若应用", "sessions": "会话", "turns": "轮", "days": "天", "cost": "省钱", "balanced": "均衡",
54
+ "time": "省时", "was": "原来", "now": "现在", "per_day": "/天", "vs_default": "每天,对默认",
55
+ "set": "建议改", "keep": "保持默认", "cur": "保持当前", "wall": "总耗时", "costm": "成本",
56
+ "noop": "无需调整",
57
+ "no_change": "无需调整", "never": "从未达到默认阈值",
58
+ "recs": "推荐设置", "by_thr": "各阈值成本", "foot": "差值相对 harness 默认值 · 按公开标价估算 · 召回为 "
59
+ "lite 代理值 · --plain 输出完整表格", "models_set": "{n} 个模型建议改", "ago": "{t}前", "next": "下次 {t}",
60
+ "up": "运行中", "down": "未运行", "none": "–", "kw_above": "{a} 不低于默认值 {b}",
61
+ "kw_score": "按 ${v:g}/小时 没有净收益(每天净 {n})",
62
+ "kw_small": "按 ${v:g}/小时 净收益不到 {tol:g}%(每天 {n})",
63
+ "kw_cur": "按 ${v:g}/小时,{p} 比你现在的 {c} 好不到 {tol:g}%(每天净 {n})",
64
+ "kw_glob": "Codex 所有模型共用一个阈值;综合 {ms} 的结论是{a}",
65
+ "kw_sup": "已被 {b} 取代:Codex 的共用阈值按在用的模型定",
66
+ "kw_worth": "按 ${v:g}/小时 不划算:每天省 {u},但总耗时每天多 {m}(折合 {tv})", "unsafe": "░ 召回 < {f:g}",
67
+ "saved": "░ = 省下的部分", "cache": "缓存 {t}", "to": "设为", "more": "另 {n} 个"},
68
+ } # fmt: skip
69
+
70
+
71
+ def label(model: str) -> str:
72
+ """'claude-opus-5-5' -> 'Opus 5.5'; date suffixes dropped (the id stays in --plain and JSON)."""
73
+ b = re.sub(r"-\d{8}$", "", model)
74
+ m = re.fullmatch(r"claude-([a-z]+)-(\d+(?:-\d+)*)", b)
75
+ if m:
76
+ return f"{m.group(1).capitalize()} {m.group(2).replace('-', '.')}"
77
+ m = re.fullmatch(r"gpt-(.+)", b, re.I)
78
+ return f"GPT-{m.group(1)}" if m else b
79
+
80
+
81
+ def per_day(g: dict[str, Any], key: str) -> float:
82
+ return float(g["default"][key]) / max(float(g["days"] or 1), 1.0)
83
+
84
+
85
+ def figs(g: dict[str, Any], prof: str, ref: str = "vs_default") -> dict[str, Any] | None:
86
+ """Was / now / change per day for one profile against the default or the current setting."""
87
+ c = g["comparison"][prof].get(ref)
88
+ point = g["default"] if ref == "vs_default" else g.get("current")
89
+ if not c or not point:
90
+ return None
91
+ days = max(float(g["days"] or 1), 1.0)
92
+ im = c["impact"]
93
+ was, d = point["combined_cost"] / days, im["usd"]["per_day"]
94
+ wasm, dm = point["time_s"] / 60 / days, im["minutes"]["per_day"]
95
+ return {"was": was, "now": was + d, "d": d, "pc": c["d_cost_pct"] if point["combined_cost"] else None,
96
+ "wasm": wasm, "nowm": wasm + dm, "dm": dm, "pt": c["d_time_pct"] if point["time_s"] else None} # fmt: skip
97
+
98
+
99
+ def status(g: dict[str, Any], prof: str) -> str:
100
+ a = g["comparison"][prof]["action"]
101
+ return {"no action needed": "noop", "keep default": "keep", "keep current": "cur"}.get(a, "set")
102
+
103
+
104
+ def keep_reason(g: dict[str, Any], prof: str, lang: str = "en") -> str:
105
+ """The engine's keep-current and keep-default tests, in words (compactlab.sim.engine._comparison)."""
106
+ w = W[lang]
107
+ p, d = g["profiles"][prof], g["default"]
108
+ glob = g["comparison"][prof].get("global")
109
+ if glob and status(g, prof) != "set":
110
+ if glob.get("superseded_by"):
111
+ return w["kw_sup"].format(b=label(glob["superseded_by"]))
112
+ act = {"keep default": w["keep"], "keep current": w["cur"], "no action needed": w["noop"]}.get(
113
+ glob["action"], glob["action"]) # fmt: skip
114
+ return w["kw_glob"].format(ms=", ".join(glob["models"]), a=act)
115
+ if status(g, prof) == "cur":
116
+ im = g["comparison"][prof]["vs_current"]["impact"]
117
+ vot = float(p["value_of_time"])
118
+ net = im["usd"]["per_day"] + im["minutes"]["per_day"] / 60 * vot
119
+ tol = p.get("recommendation", {}).get("tolerance", 0.02) * 100
120
+ return w["kw_cur"].format(p=k(p["threshold"]), c=k(g["current"]["configured"]), tol=tol, v=vot,
121
+ n=fusd(net, True)) # fmt: skip
122
+ if p["threshold"] >= d["threshold"]:
123
+ return w["kw_above"].format(a=k(p["threshold"]), b=k(d["threshold"]))
124
+ f = figs(g, prof)
125
+ assert f is not None
126
+ vot = float(p["value_of_time"])
127
+ tv = f["dm"] / 60 * vot
128
+ if f["d"] + tv < 0: # better than the default, but within the selection tolerance
129
+ tol = p.get("recommendation", {}).get("tolerance", 0.02) * 100
130
+ return w["kw_small"].format(v=vot, n=fusd(f["d"] + tv, True), tol=tol)
131
+ if f["d"] < 0 < f["dm"]:
132
+ return w["kw_worth"].format(v=vot, u=f"${-f['d']:,.1f}", m=f"{f['dm']:.1f} min", tv=f"${tv:,.1f}")
133
+ return w["kw_score"].format(v=vot, n=fusd(f["d"] + tv, True))
134
+
135
+
136
+ def totals(res: dict[str, Any], prof: str | None = None) -> dict[str, Any]:
137
+ """Summed change of the "set" groups over the summed default of the models that have one (the report's base)."""
138
+ groups = res["groups"]
139
+ pr = lambda g: prof or g.get("profile") or "balanced" # noqa: E731
140
+ setm = {(g["harness"], g["model"]) for g in groups if status(g, pr(g)) == "set"}
141
+ base = [g for g in groups if (g["harness"], g["model"]) in setm]
142
+ was, wasm = sum(per_day(g, "combined_cost") for g in base), sum(per_day(g, "time_s") / 60 for g in base)
143
+ d = dm = 0.0
144
+ for g in groups:
145
+ if status(g, pr(g)) == "set":
146
+ f = figs(g, pr(g))
147
+ assert f is not None
148
+ d, dm = d + f["d"], dm + f["dm"]
149
+ return {"n": len(setm), "was": was, "d": d, "pc": d / was if was else None, "wasm": wasm, "dm": dm,
150
+ "pt": dm / wasm if wasm else None} # fmt: skip
151
+
152
+
153
+ def _ago(sec: float) -> str:
154
+ sec = max(sec, 0)
155
+ return f"{sec / 60:.0f}m" if sec < 3600 else f"{sec / 3600:.1f}h" if sec < 86400 else f"{sec / 86400:.1f}d"
156
+
157
+
158
+ def _ttl(g: dict[str, Any], w: dict[str, str]) -> list[Line]:
159
+ sec = g.get("cache_ttl")
160
+ if not sec or g.get("harness") != "claude-code": # only Anthropic bills by cache tier
161
+ return []
162
+ return [[(w["cache"].format(t=f"{sec // 3600} h" if sec >= 3600 else f"{sec // 60} min"), "dim")]]
163
+
164
+
165
+ def verdict(res: dict[str, Any], lang: str = "en", prof: str | None = None) -> Line:
166
+ """One line to act on and share: the group with the largest saving among those to change, or nothing."""
167
+ w = W[lang]
168
+ picks = []
169
+ for g in res["groups"]:
170
+ p = prof or g.get("profile") or "balanced"
171
+ f = figs(g, p) if status(g, p) == "set" else None
172
+ if f:
173
+ picks.append((f["d"], g, p, f))
174
+ if not picks:
175
+ return []
176
+ picks.sort(key=lambda x: x[0])
177
+ _, g, p, f = picks[0]
178
+ line: Line = [("→ ", "acc_b"), (f"{label(g['model'])} {g['role']}", "ink_b"), (": " + w["to"] + " ", "dim"),
179
+ (k(g["profiles"][p]["threshold"]), "acc_b"), (" ", None), (fpct(f["pc"]), _t(f["d"])),
180
+ (" " + w["costm"] + " ", "dim"), (fmin(f["dm"], True) + w["per_day"], _t(f["dm"])),
181
+ (" " + w["wall"], "dim")] # fmt: skip
182
+ if len(picks) > 1:
183
+ line.append((" · " + w["more"].format(n=len(picks) - 1), "dim"))
184
+ return line
185
+
186
+
187
+ def summary_facts(res: dict[str, Any], lang: str = "en", unit: str = "pct", service: str | None = None,
188
+ now: float | None = None) -> list[tuple[str, Line]]: # fmt: skip
189
+ w = W[lang]
190
+ gs = res["groups"]
191
+ spans = [g["span"] for g in gs if g.get("span")]
192
+ day = lambda ts: datetime.fromtimestamp(ts, UTC).strftime("%Y-%m-%d") # noqa: E731
193
+ days = (max(s[1] for s in spans) - min(s[0] for s in spans)) / 86400 if spans else max(g["days"] for g in gs)
194
+ hist: Line = [(f"{day(min(s[0] for s in spans))} → {day(max(s[1] for s in spans))}", "ink")] if spans else []
195
+ hist += [(f" {days:.1f} {w['days']}", "dim")]
196
+ models = {(g["harness"], g["model"]) for g in gs}
197
+ facts: list[tuple[str, Line]] = [
198
+ (w["history"], hist),
199
+ (w["harnesses"], [(", ".join(sorted({g["harness"] for g in gs})), "ink")]),
200
+ (w["models"], [(f"{len(models)}", "ink_b"), (f" {sum(g['n_sessions'] for g in gs)} {w['sessions']} · "
201
+ f"{sum(g['n_turns'] for g in gs):,} {w['turns']}", "dim")]),
202
+ ] # fmt: skip
203
+ cal = res.get("calibration")
204
+ if cal and cal.get("at"):
205
+ facts.append((w["calibrated"], [(w["ago"].format(t=_ago((now or time.time()) - cal["at"])), "ink")]))
206
+ if service:
207
+ facts.append((w["service"], [("● ", "good" if service == "up" else "dim"), (w.get(service, service), "ink")]))
208
+ t = totals(res)
209
+ if t["n"]:
210
+ nset = w["models_set"].format(n=t["n"]).replace("model(s)", "model" if t["n"] == 1 else "models")
211
+ cost, tm = chip(t["pc"], fusd(t["d"]) + w["per_day"], unit), chip(t["pt"], fmin(t["dm"]) + w["per_day"], unit)
212
+ facts.append((w["impact"], [*cost, (" ", None), *tm, (" " + nset, "dim")]))
213
+ if res.get("demo"):
214
+ facts.append(("", [("synthetic demo data", "warn")]))
215
+ return facts
216
+
217
+
218
+ def group_panel(
219
+ g: dict[str, Any], cols: int, lang: str = "en", unit: str = "pct", prof: str | None = None
220
+ ) -> list[Line]:
221
+ w = W[lang]
222
+ prof = prof or g.get("profile") or "balanced"
223
+ iw = cols - 4
224
+ p, d = g["profiles"][prof], g["default"]
225
+ title: Line = [(label(g["model"]), "title"), (f" · {g['role']} · {g['harness']}", "dim")]
226
+ body: list[Line] = []
227
+ body += pack([[(f"{g['n_sessions']} {w['sessions']}", "dim")], [(f"{g['n_turns']:,} {w['turns']}", "dim")],
228
+ [(f"{g['days']:.1f} {w['days']}", "dim")], *_ttl(g, w)], iw, " · ") # fmt: skip
229
+ # gauge: default, current and the three profiles on the threshold axis; red where recall is below the floor
230
+ grid = g["grid"]
231
+ floor = g["recommendation"]["recall_floor"]
232
+ unsafe, i = [], 0
233
+ while i < len(grid):
234
+ if g["recall"][i] < floor:
235
+ j = i
236
+ while j + 1 < len(grid) and g["recall"][j + 1] < floor:
237
+ j += 1
238
+ unsafe.append((grid[i], grid[j]))
239
+ i = j + 1
240
+ else:
241
+ i += 1
242
+ marks = [(d["threshold"], "┊", "dim")]
243
+ if g.get("current"):
244
+ marks.append((g["current"]["threshold"], "╎", "dim"))
245
+ marks += [
246
+ (g["profiles"][n]["threshold"], PGLYPH[n], "acc_b" if n == prof else "acc") for n in PROFILES if n != prof
247
+ ]
248
+ marks.append((p["threshold"], PGLYPH[prof], "acc_b"))
249
+ body += gauge(iw, grid[0], grid[-1], marks, unsafe)
250
+ if unsafe:
251
+ body.append([(w["unsafe"].format(f=floor), "bad"), (" ┊ " + k(d["threshold"]), "dim")])
252
+ # the answer, then was / now bars for cost and time
253
+ f = figs(g, prof)
254
+ st = status(g, prof)
255
+ if f:
256
+ ans: list[Line] = [
257
+ [(k(p["threshold"]), "big")],
258
+ [*chip(f["pc"], None, unit), (" " + w["costm"], "dim")],
259
+ [*chip(f["pt"], None, unit), (" " + w["wall"], "dim")],
260
+ [(f"{fusd(f['d'])} · {fmin(f['dm'])} {w['vs_default']} {k(d['threshold'])}", "dim")],
261
+ ]
262
+ if unit != "pct":
263
+ ans[1] = [(fusd(f["d"], True), (_t(f["d"]) or "ink") + "_b"), (" " + w["costm"], "dim")]
264
+ ans[2] = [(fmin(f["dm"], True), (_t(f["dm"]) or "ink") + "_b"), (" " + w["wall"], "dim")]
265
+ body += pack(ans, iw)
266
+ if st in ("keep", "cur"):
267
+ body += pack([[("▪ " + w[st] + ": ", "dim"), (keep_reason(g, prof, lang), "dim")]], iw)
268
+ lab = max(cw(w["was"]), cw(w["now"])) + max(cw(w["costm"]), cw(w["wall"])) + 2
269
+ bw = max(min(iw - lab - 22, 56), 6)
270
+ for key, was, now in (("cost", f["was"], f["now"]), ("time", f["wasm"], f["nowm"])):
271
+ a, b = was_now(was, now, bw)
272
+ fmt = money if key == "cost" else (lambda v: f"{v:.0f} min")
273
+ name = w["costm"] if key == "cost" else w["wall"]
274
+ body.append([(name + " " * (lab - cw(name) - cw(w["was"]) - 1), "dim"), (w["was"] + " ", "dim"), *a,
275
+ (f" {fmt(was)}{w['per_day']}", "dim")]) # fmt: skip
276
+ pc = f["pc"] if key == "cost" else f["pt"]
277
+ body.append([(" " * (lab - cw(w["now"]) - 1), None), (w["now"] + " ", "dim"), *b,
278
+ (f" {fmt(now)}{w['per_day']} ", "ink"), (fpct(pc), _t(pc))]) # fmt: skip
279
+ if f["d"] < 0:
280
+ body.append([(" " * lab, None), (w["saved"], "good")])
281
+ cost = [c / max(g["days"], 1) for c in g["combined_cost"]]
282
+ sel = grid.index(p["threshold"]) if p["threshold"] in grid else None
283
+ sw = max(iw - cw(w["by_thr"]) - 14, 6)
284
+ body.append([(w["by_thr"] + " ", "dim"), *spark(cost, sw, sel), (f" {k(grid[0])}→{k(grid[-1])}", "dim")])
285
+ # the three profiles as chips
286
+ toks = []
287
+ for n in PROFILES:
288
+ fn = figs(g, n)
289
+ star = "★" if n == g.get("profile") else ""
290
+ on = "ink" if n == prof else "dim"
291
+ tok: Line = [(PGLYPH[n] + " ", "acc" if n == prof else "dim"), (w[n] + star + " ", on),
292
+ (k(g["profiles"][n]["threshold"]) + " ", "ink")] # fmt: skip
293
+ if fn:
294
+ tok += [(fpct(fn["pc"]) if unit == "pct" else fusd(fn["d"], True), _t(fn["d"]))]
295
+ tok += [(f" [{w[status(g, n)]}]", "acc" if status(g, n) == "set" else "dim")]
296
+ toks.append(tok)
297
+ body += pack(toks, iw, " ")
298
+ for fl in g["profiles"][prof]["flags"]:
299
+ if fl in ("guardrail_applied", "deep_recall_below_floor"):
300
+ continue
301
+ body += pack([[("⚠ ", "warn" if fl not in BROKEN else "bad"), (fl.replace("_", " "), "dim")]], iw)
302
+ return panel(title, body, cols)
303
+
304
+
305
+ BROKEN = {"recall_floor_not_met", "wait_cap_unreachable", "min_window_unreachable"}
306
+
307
+
308
+ def _t(v: float | None) -> str | None:
309
+ return None if v is None or abs(v) < 1e-9 else "good" if v < 0 else "warn"
310
+
311
+
312
+ def noop_lines(res: dict[str, Any], cols: int, lang: str = "en") -> list[Line]:
313
+ w = W[lang]
314
+ gs = [g for g in res["groups"] if g["no_action_needed"]]
315
+ if not gs:
316
+ return []
317
+ toks = [[("✓ ", "good"), (f"{label(g['model'])} {g['role']}", "ink"),
318
+ (f" {k(g.get('peak_max'))} < {k(g['default']['threshold'])}", "dim")] for g in gs] # fmt: skip
319
+ return [[("✓ " + w["no_change"], "good_b"), (" · " + w["never"], "dim")], *pack(toks, cols)]
320
+
321
+
322
+ def recs_table(res: dict[str, Any], cols: int, lang: str = "en", unit: str = "pct") -> list[Line]:
323
+ """One row per group with an action: model, role, threshold, action chip, change, and the keep-default reason."""
324
+ w = W[lang]
325
+ rows = []
326
+ for g in sorted(
327
+ res["groups"], key=lambda g: (g["no_action_needed"], -abs((figs(g, g["profile"]) or {"d": 0})["d"]))
328
+ ):
329
+ prof = g.get("profile") or "balanced"
330
+ st = status(g, prof)
331
+ f = figs(g, prof)
332
+ name: Line = [(label(g["model"]), "ink"), (f" {g['role']}", "dim")]
333
+ thr: Line = [("–" if st == "noop" else k(g["profiles"][prof]["threshold"]), "ink")]
334
+ act: Line = [(f"[{w[st]}]", "acc_b" if st == "set" else "dim")]
335
+ ch: Line = [] if st == "noop" or not f else [*chip(f["pc"], fusd(f["d"]) + w["per_day"], unit), (" ", None),
336
+ *chip(f["pt"], None, unit), (" " + w["wall"], "dim")] # fmt: skip
337
+ why = keep_reason(g, prof, lang) if st in ("keep", "cur") else ""
338
+ rows.append((name, thr, act, ch, why))
339
+ nw = max((width(r[0]) for r in rows), default=0)
340
+ out: list[Line] = [[(w["recs"], "title")]]
341
+ wide = cols >= 90
342
+ for name, thr, act, ch, why in rows:
343
+ if wide:
344
+ line = [*pad(name, min(nw, 26)), (" ", None), *pad(thr, 5), (" ", None), *pad(act, 15), *ch]
345
+ out.append(clip(line, cols))
346
+ else:
347
+ out += pack([name, thr, act], cols, " ")
348
+ if ch:
349
+ out.append(clip([(" ", None), *ch], cols))
350
+ if why:
351
+ out += pack([[(" ↳ ", "dim"), (why, "dim")]], cols)
352
+ return out
353
+
354
+
355
+ IDLE_W: dict[str, dict[str, Any]] = {
356
+ "en": {
357
+ "head": "idle compaction (Claude Code idleCompaction: {state}{src}; min context {m}) · {groups}",
358
+ "on": "on", "off": "off", "default": ", the default",
359
+ "rate": "{g}: fires on {r:.0%} of eligible idle gaps ({src}); {n} in the logs",
360
+ "scope": {"group": "{f} of {e} in this group", "harness": "{f} of {e} across this harness",
361
+ "assumed": "assumed: too few eligible gaps in the logs"},
362
+ "with": {"profile": "with the {p} picks", "current": "with your current settings"},
363
+ "flip": {True: "turning it off", False: "turning it on"},
364
+ "line": "{w}, {f}: {u}/day ({pc}), {m}/day wall-clock, {c:+.1f} compactions/day, recall {r:+.3f} → {v}",
365
+ "verdict": {(True, True): "turn it off", (True, False): "turn it on",
366
+ (False, True): "keep it on", (False, False): "keep it off"},
367
+ "tail": "includes {u}/day of summaries for sessions left idle and never resumed (expected; not in the logs)",
368
+ },
369
+ "zh": {
370
+ "head": "空闲压缩(Claude Code idleCompaction:{state}{src};最小上下文 {m})· {groups}",
371
+ "on": "开", "off": "关", "default": ",默认",
372
+ "rate": "{g}:符合条件的空闲间隔里有 {r:.0%} 触发({src});日志里 {n} 次",
373
+ "scope": {"group": "本组 {e} 次里 {f} 次", "harness": "该 harness 全部会话 {e} 次里 {f} 次",
374
+ "assumed": "假定:日志里符合条件的间隔太少"},
375
+ "with": {"profile": "按{p}方案的阈值", "current": "按你当前的设置"},
376
+ "flip": {True: "关掉它", False: "打开它"},
377
+ "line": "{w},{f}:每天 {u}({pc}),耗时每天 {m},压缩每天 {c:+.1f} 次,召回 {r:+.3f} → {v}",
378
+ "verdict": {(True, True): "建议关掉", (True, False): "建议打开",
379
+ (False, True): "保持开启", (False, False): "保持关闭"},
380
+ "tail": "其中每天 {u} 是空闲后没再回来的会话做的摘要(期望值,日志里看不到)",
381
+ },
382
+ } # fmt: skip
383
+ PROFILE_ZH = {"cost": "省钱", "balanced": "均衡", "time": "省时"}
384
+
385
+
386
+ def idle_lines(res: dict[str, Any], lang: str = "en") -> list[str]:
387
+ """Keep Claude Code's idle compaction on or off, in plain lines (empty when it applies to no group)."""
388
+ adv = res.get("idle_compaction")
389
+ if not adv:
390
+ return []
391
+ w = IDLE_W[lang]
392
+ on = adv["enabled"]
393
+ gs = [g for g in res["groups"] if g.get("idle", {}).get("alt")]
394
+ out = [w["head"].format(state=w["on"] if on else w["off"], src="" if adv.get("configured") else w["default"],
395
+ m=k(adv["min_tokens"]), groups=", ".join(adv["groups"]))] # fmt: skip
396
+ for g in gs:
397
+ if g["idle"]["rate_scope"] == "group": # groups with enough eligible gaps of their own
398
+ i = g["idle"]
399
+ src = w["scope"][i["rate_scope"]].format(f=i["rate_fired"], e=i["rate_eligible"])
400
+ out.append(
401
+ " · "
402
+ + w["rate"].format(
403
+ g=f"{label(g['model'])} {g['role']}", r=i["rate"], src=src, n=g["observed_idle_compactions"]
404
+ )
405
+ )
406
+ rows = [("profile", adv["profiles"][adv["profile"]]), ("current", adv["current"])]
407
+ for which, v in rows:
408
+ base = v["configured"]["combined_cost"]
409
+ pname = adv["profile"] if lang == "en" else PROFILE_ZH.get(adv["profile"], adv["profile"])
410
+ out.append(" · " + w["line"].format(
411
+ w=w["with"][which].format(p=pname), f=w["flip"][on], u=fusd(v["d_usd_per_day"], True),
412
+ pc=fpct(v["d_usd_per_day"] / base if base else None), m=fmin(v["d_min_per_day"], True),
413
+ c=v["d_compactions_per_day"], r=v["d_recall"], v=w["verdict"][(v["switch"], on)])) # fmt: skip
414
+ tail = adv["profiles"][adv["profile"]]["configured"].get("idle_tail_cost", 0.0) if on else 0.0
415
+ if tail >= 0.05:
416
+ out.append(" · " + w["tail"].format(u=fusd(tail)))
417
+ return out
418
+
419
+
420
+ MODEL_W: dict[str, dict[str, Any]] = {
421
+ "en": {
422
+ "head": "models",
423
+ "family": "{m}: no price of its own; priced as {row}, the closest model of the same family",
424
+ "fallback": "{m}: unknown model; priced with the fallback row (${i:g} in / ${o:g} out per 1M, {w} window)",
425
+ "vendor": "{m} on {p}: no {p} price; priced at the vendor's list price ({row})",
426
+ "fix_auto": "automatic price refresh is on: the background service fetches the public data for it",
427
+ "fix": "fix: compactlab pricing refresh (or `compactlab pricing auto on` to do it whenever a new model "
428
+ "appears; downloads public data only)",
429
+ "unset": "{m}: no autoCompactWindow of its own, so it compacts at the default {d}; {peer} is set to {v}",
430
+ "thin": " (only {n:.0f} active days of its own data: {peer}'s {v} is a reasonable stand-in "
431
+ "until there is more)",
432
+ "own": " (`compactlab recommend` gives it a value from its own data)",
433
+ "window_changed": "{m} {r}: {h} changed its window from {a} to {b} around {d}; the replay uses {b}",
434
+ "peak_over_window": "{m} {r}: contexts reached {peak}, beyond the {a} window assumed, so it is replayed with "
435
+ "{w} (the window has probably grown: refresh the price data{why})",
436
+ "peak_why": {"claude-code": ", or CLAUDE_CODE_MAX_CONTEXT_TOKENS is set where compactlab cannot see it",
437
+ "opencode": ", or your OpenCode config sets this model's limit"},
438
+ "drift": "{m} {r}: the last {n} threshold compactions were at about {o}, not the default {a} assumed: "
439
+ "{h} may have changed its default, or a setting compactlab cannot read is in force (an env var, a "
440
+ "project settings file, a CLI flag)",
441
+ "price_change": "price data {d}: {m} {f} {o} → {n} (history is replayed at today's prices)",
442
+ "superseded": "{m} ({h}): replaced by {b} (last used {d})",
443
+ "superseded_glob": "; not counted for its one setting for every model",
444
+ "global": "{h} (one limit for every model), {p}: {a} · across {ms}",
445
+ "global_set": "set {t}: {u}/day, {mn}/day wall-clock",
446
+ },
447
+ "zh": {
448
+ "head": "模型",
449
+ "family": "{m}:没有自己的价格,借用同族最接近的 {row}",
450
+ "fallback": "{m}:未知模型,按兜底价格计算(输入 ${i:g} / 输出 ${o:g} 每百万 token,窗口 {w})",
451
+ "vendor": "{m}({p}):没有 {p} 的价格,按厂商官方价 {row} 计算",
452
+ "fix_auto": "已开启自动更新价格:后台服务会去公开数据里取",
453
+ "fix": "处理:compactlab pricing refresh(或 `compactlab pricing auto on`,"
454
+ "出现新模型时自动更新;只下载公开数据)",
455
+ "unset": "{m}:没有单独设置 autoCompactWindow,按默认 {d} 压缩;{peer} 设为 {v}",
456
+ "thin": "(自己的数据只有 {n:.0f} 个活跃天,先参照 {peer} 的 {v})",
457
+ "own": "(`compactlab recommend` 会按它自己的数据给值)",
458
+ "window_changed": "{m} {r}:{h} 在 {d} 前后把窗口从 {a} 改成 {b},按 {b} 回放",
459
+ "peak_over_window": "{m} {r}:上下文到过 {peak},超出假设的 {a} 窗口,按 {w} 回放(窗口多半变大了:"
460
+ "更新价格数据{why})",
461
+ "peak_why": {"claude-code": ",或 CLAUDE_CODE_MAX_CONTEXT_TOKENS 设在 compactlab 看不到的地方",
462
+ "opencode": ",或你的 OpenCode 配置给这个模型设了上限"},
463
+ "drift": "{m} {r}:最近 {n} 次阈值压缩在约 {o},不是假设的默认 {a}:{h} 可能改了默认值,"
464
+ "或有 compactlab 读不到的设置在生效(环境变量、项目设置文件、命令行参数)",
465
+ "price_change": "价格数据 {d}:{m} {f} {o} → {n}(历史按现价回放)",
466
+ "superseded": "{m}({h}):已被 {b} 取代(最后使用 {d})",
467
+ "superseded_glob": ",所有模型共用的那个设置不再算它",
468
+ "global": "{h}(所有模型共用一个阈值),{p}:{a} · 综合 {ms}",
469
+ "global_set": "设为 {t}:每天 {u},耗时每天 {mn}",
470
+ },
471
+ } # fmt: skip
472
+ THIN_DAYS = 3
473
+
474
+
475
+ def _day(ts: float | None) -> str:
476
+ return time.strftime("%Y-%m-%d", time.localtime(ts)) if ts else "?"
477
+
478
+
479
+ def model_lines(res: dict[str, Any], lang: str = "en") -> list[str]:
480
+ """Models priced from someone else's row; windows that changed or that the logs contradict; defaults the latest
481
+ compactions do not match; recent price changes; Claude Code models with no window of their own while others have
482
+ one (empty when there is nothing to say)."""
483
+ notes = res.get("model_notes") or {}
484
+ w = MODEL_W[lang]
485
+ out = []
486
+ fb = notes.get("fallback") or {}
487
+ for p in notes.get("prices", []):
488
+ out.append(" · " + w[p["kind"]].format(
489
+ m=label(p["model"]), row=p["row"], p=p.get("platform") or "", i=fb.get("input", 3), o=fb.get("output", 15),
490
+ w=k(fb.get("max_window", 200_000)))) # fmt: skip
491
+ if notes.get("prices"):
492
+ out.append(" " + w["fix_auto" if notes.get("auto_refresh") else "fix"])
493
+ for x in notes.get("windows", []):
494
+ args = {"m": label(x["model"]), "r": x["role"], "h": x["harness"]}
495
+ if x["kind"] == "window_changed":
496
+ out.append(" · " + w["window_changed"].format(a=k(x["from"]), b=k(x["to"]), d=_day(x["since"]), **args))
497
+ else:
498
+ why = w["peak_why"].get(x["harness"], "") # a hint only where the harness has such a setting
499
+ out.append(" · " + w["peak_over_window"].format(peak=k(x["peak"]), a=k(x["assumed"]), w=k(x["window"]),
500
+ why=why, **args)) # fmt: skip
501
+ for x in notes.get("defaults", []):
502
+ out.append(" · " + w["drift"].format(m=label(x["model"]), r=x["role"], h=x["harness"], n=x["n"],
503
+ o=k(x["observed"]), a=k(x["assumed"]))) # fmt: skip
504
+ for x in notes.get("superseded", []):
505
+ out.append(" · " + w["superseded"].format(m=label(x["model"]), h=x["harness"], b=label(x["by"]),
506
+ d=_day(x["last_used"]))
507
+ + (w["superseded_glob"] if x.get("global_key") else "")) # fmt: skip
508
+ for h, gk in (res.get("global_keys") or {}).items():
509
+ prof = (res.get("options") or {}).get("profile") or "balanced"
510
+ gp = gk["profiles"][prof]
511
+ act = (
512
+ w["global_set"].format(t=k(gp["threshold"]), u=fusd(gp["d_usd_per_day"], True),
513
+ mn=fmin(gp["d_min_per_day"], True))
514
+ if gp["action"] == "set"
515
+ else W[lang][{"keep default": "keep", "keep current": "cur"}.get(gp["action"], "noop")]
516
+ ) # fmt: skip
517
+ pname = prof if lang == "en" else PROFILE_ZH.get(prof, prof)
518
+ out.append(" · " + w["global"].format(h=h, p=pname, a=act, ms=", ".join(gk["models"])))
519
+ for c in notes.get("price_changes", []):
520
+ out.append(" · " + w["price_change"].format(d=c["date"], m=c["model"], f=c["field"], o=c["old"], n=c["new"]))
521
+ for u in notes.get("unset", []):
522
+ line = w["unset"].format(m=label(u["model"]), d=k(u["default"]), peer=label(u["peer"]), v=k(u["peer_value"]))
523
+ thin = u["active_days"] < THIN_DAYS
524
+ out.append(" · " + line + (w["thin"] if thin else w["own"]).format(
525
+ n=u["active_days"], peer=label(u["peer"]), v=k(u["peer_value"]))) # fmt: skip
526
+ return [w["head"], *out] if out else []
527
+
528
+
529
+ def summary_view(res: dict[str, Any], cols: int, lang: str = "en", unit: str = "pct",
530
+ service: str | None = None) -> list[Line]: # fmt: skip
531
+ cols = max(30, min(cols, 200))
532
+ lines = header(summary_facts(res, lang, unit, service), cols)
533
+ v = verdict(res, lang)
534
+ lines += [[], v] if v else []
535
+ lines.append([])
536
+ gs = [g for g in res["groups"] if not g["no_action_needed"]]
537
+ gs.sort(key=lambda g: (status(g, g["profile"]) != "set", -abs((figs(g, g["profile"]) or {"d": 0})["d"])))
538
+ pw = min(cols, 120)
539
+ for g in gs:
540
+ lines += group_panel(g, pw, lang, unit)
541
+ nl = noop_lines(res, pw, lang)
542
+ if nl:
543
+ lines += [[], *nl]
544
+ il = idle_lines(res, lang)
545
+ if il:
546
+ lines += [[], [(il[0], "ink_b")], *([(x, "dim")] for x in il[1:])]
547
+ ml = model_lines(res, lang)
548
+ if ml:
549
+ lines += [[], [(ml[0], "ink_b")], *([(x, "dim")] for x in ml[1:])]
550
+ lines += [
551
+ [],
552
+ *recs_table(res, pw, lang, unit),
553
+ [],
554
+ *pack([[(x, "dim")] for x in W[lang]["foot"].split(" · ")], pw, " · "),
555
+ ]
556
+ return [clip(x, cols) for x in lines]
557
+
558
+
559
+ # ---------- doctor and serve ----------
560
+
561
+
562
+ def doctor_view(report: dict[str, Any], cols: int) -> list[Line]:
563
+ cols = max(30, min(cols, 200))
564
+ facts: list[tuple[str, Line]] = [
565
+ ("version", [(report["compactlab"], "ink"), (f" Python {report['python']}", "dim")]),
566
+ ("pricing", [(f"bundled {report['pricing']['bundled']}", "ink"),
567
+ (" refreshed" if report["pricing"]["refreshed"] else " not refreshed", "dim")]),
568
+ ("cache", [("✓ " if report["cache"]["exists"] else "· ", "good" if report["cache"]["exists"] else "dim"),
569
+ (f"{report['cache']['bytes'] / 1e6:.1f} MB" if report["cache"]["exists"] else "none", "ink")]),
570
+ ] # fmt: skip
571
+ out = header(facts, cols, "compactlab doctor")
572
+ pw = min(cols, 120)
573
+ for h in report["harnesses"]:
574
+ body: list[Line] = [[("✓ " if h["cli"] else "✗ ", "good" if h["cli"] else "warn"),
575
+ ("CLI ", "dim"), (h["cli"] or "not found", "ink")]] # fmt: skip
576
+ for r in h["log_roots"]:
577
+ body.append([("✓ " if r["exists"] else "· ", "good" if r["exists"] else "dim"), ("logs ", "dim"),
578
+ (r["path"], "ink"), (f" {r['jsonl_files']} files", "dim")]) # fmt: skip
579
+ for c in h["config"]:
580
+ body.append([("✓ " if c["exists"] else "· ", "good" if c["exists"] else "dim"), ("config ", "dim"),
581
+ (c["path"], "ink")]) # fmt: skip
582
+ for c in h.get("checks", []):
583
+ body.append([("✓ " if c["ok"] else "· ", "good" if c["ok"] else "dim"), (f"{c['label']:7}", "dim"),
584
+ (c["text"], "ink")]) # fmt: skip
585
+ out += [[], *panel([(h["name"], "title")], body, pw)]
586
+ return [clip(x, cols) for x in out]
587
+
588
+
589
+ def serve_view(url: str, token_path: str, next_cal: str, state_dir: str, auto_apply: bool, cols: int) -> list[Line]:
590
+ facts: list[tuple[str, Line]] = [
591
+ ("report", [(url, "acc_b")]),
592
+ ("token", [(token_path, "dim")]),
593
+ ("next calibration", [(next_cal, "ink")]),
594
+ ("auto-apply", [("on" if auto_apply else "off", "warn" if auto_apply else "dim")]),
595
+ ("state", [(state_dir, "dim")]),
596
+ ("", [("Ctrl-C stops · localhost only · never writes settings without consent", "dim")]),
597
+ ]
598
+ return [clip(x, max(30, cols)) for x in header(facts, max(30, min(cols, 200)), "compactlab serve")]