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
compactlab/verify.py ADDED
@@ -0,0 +1,462 @@
1
+ """Check a threshold change against what happened: predicted vs observed, from the same logs.
2
+
3
+ After `apply` the harness keeps writing session logs. This splits them at the apply time (from the manifest) and
4
+ compares, per model and role:
5
+
6
+ observed logged cost and compactions per 1k turns, before vs after (list price, each cache write at the
7
+ tier it was billed at), with a bootstrap interval over sessions. A compaction's own summary
8
+ request is not a logged turn, so its cost (a cached read of the context and the summary's
9
+ output) is estimated and added, as the replay charges it. Threshold, idle (Claude Code's
10
+ idleCompaction) and hand-typed compactions are counted apart.
11
+ predicted a replay of the BEFORE sessions at the old and at the new threshold (no data from after)
12
+ replay on after the same replay on the AFTER sessions; if it disagrees with `predicted`, the workload changed
13
+
14
+ Workload is divided out (per 1k turns), not matched: a different mix of tasks before and after still moves the
15
+ observed figure, so the interval and the replay-on-after column are the guard. Wall-clock is not verified here
16
+ (timestamps include tool and network time); the report says so. Sessions that straddle the apply time are dropped.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import random
22
+ import statistics
23
+ import time
24
+ from collections import defaultdict
25
+ from dataclasses import dataclass
26
+ from datetime import datetime
27
+ from typing import Any
28
+
29
+ from .model import Session, Turn, is_auto, is_threshold
30
+ from .pricing import PricingTable
31
+ from .sim.engine import SimOptions, _actual_cost, analyze
32
+
33
+ SUMMARY_TOKENS = 12_000 # when a compaction's summary text is not in the log (the replay's default too)
34
+
35
+ MIN_SESSIONS = 3
36
+ MIN_ACTIVE_DAYS = 2
37
+ BOOTSTRAP = 400
38
+ NEAR = (0.8, 1.05) # median size at compaction vs the new threshold: "setting is in effect" band
39
+ PER_MODEL_KEYS = ("modelSettings.", "provider.") # Claude Code's and OpenCode's keys are per model; others global
40
+ # A global fraction (Gemini CLI) is one setting but a different token threshold for each model's window, so its
41
+ # changes are verified per model too.
42
+ FRACTION_HARNESSES = ("gemini-cli",)
43
+
44
+
45
+ @dataclass
46
+ class Change:
47
+ harness: str
48
+ model: str # "" = every model of the harness (a global key, e.g. Codex's)
49
+ key: str
50
+ old: int | None # the threshold in force before (None = the harness default)
51
+ new: int
52
+
53
+
54
+ def changes_from_manifest(manifest: dict[str, Any]) -> list[Change]:
55
+ out = []
56
+ for ent in manifest.get("entries", []):
57
+ for ch in ent.get("changes", []):
58
+ old = ch.get("old_effective", ch.get("old")) # manifests before old_effective only know the key itself
59
+ out.append(
60
+ Change(
61
+ ch["harness"],
62
+ ch.get("model") or "",
63
+ str(ch.get("key", "")),
64
+ old if isinstance(old, int) and not isinstance(old, bool) else None,
65
+ int(ch["new"]),
66
+ )
67
+ )
68
+ return resolve(out)
69
+
70
+
71
+ def resolve(changes: list[Change]) -> list[Change]:
72
+ """One change per setting that really exists. A per-model key stays per model; a global key (Codex's) is one
73
+ setting for every model, so its first old value and last new value stand for all of them."""
74
+ out: list[Change] = []
75
+ glob: dict[tuple[str, str], Change] = {}
76
+ for c in changes:
77
+ if c.key.startswith(PER_MODEL_KEYS) or (c.harness in FRACTION_HARNESSES and c.model):
78
+ out.append(c)
79
+ continue
80
+ first = glob.get((c.harness, c.key))
81
+ glob[(c.harness, c.key)] = Change(c.harness, "", c.key, first.old if first else c.old, c.new)
82
+ return out + list(glob.values())
83
+
84
+
85
+ def parse_when(text: str) -> float:
86
+ """Epoch seconds for an ISO date or datetime; one without a zone is local time."""
87
+ try:
88
+ return datetime.fromisoformat(text).timestamp()
89
+ except ValueError as e:
90
+ raise ValueError(f"cannot read {text!r} as a date; use 2026-10-29 or 2026-10-29T21:05") from e
91
+
92
+
93
+ def manual_manifest(applied_at: float, harness: str, model: str, new: int, old: int | None = None) -> dict[str, Any]:
94
+ """A manifest for a change made by hand: the time, model and values come from the user, not from `apply`."""
95
+ if harness == "claude-code":
96
+ key, who = f"modelSettings.{model}.autoCompactWindow", model
97
+ elif harness == "codex":
98
+ key, who = "model_auto_compact_token_limit", ""
99
+ elif harness == "opencode":
100
+ prov, _, mid = model.partition("/")
101
+ key, who = f"provider.{prov}.models.{mid}.limit", model
102
+ elif harness == "gemini-cli":
103
+ if not model:
104
+ raise ValueError(
105
+ "Gemini CLI: name the model with --model; one compressionThreshold is a different "
106
+ "token threshold for each model's window, so --new is that model's token count"
107
+ )
108
+ key, who = "model.compressionThreshold", model
109
+ else:
110
+ raise ValueError(f"verifying a manual change is not supported for {harness}")
111
+ change = {"harness": harness, "key": key, "model": who, "old": old, "new": new}
112
+ return {"id": "manual", "created": applied_at, "entries": [{"changes": [change]}]}
113
+
114
+
115
+ def split(sessions: list[Session], t: float) -> tuple[list[Session], list[Session], int]:
116
+ """(before, after, dropped): by first/last timestamp; sessions without times or spanning `t` are dropped."""
117
+ before, after, dropped = [], [], 0
118
+ for s in sessions:
119
+ ts = [x.ts for x in s.turns if x.ts]
120
+ if not ts:
121
+ dropped += 1
122
+ elif max(ts) < t:
123
+ before.append(s)
124
+ elif min(ts) >= t:
125
+ after.append(s)
126
+ else:
127
+ dropped += 1
128
+ return before, after, dropped
129
+
130
+
131
+ def _active_days(ss: list[Session]) -> int:
132
+ return len({time.strftime("%Y-%m-%d", time.localtime(x.ts)) for s in ss for x in s.turns if x.ts})
133
+
134
+
135
+ def _logged_cost(s: Session, pricing: PricingTable) -> float:
136
+ """Each turn at its own model's list price: a session that switched models is not priced as its majority."""
137
+ by_model: dict[str, list[Turn]] = defaultdict(list)
138
+ for t in s.turns:
139
+ by_model[t.model].append(t)
140
+ return sum(
141
+ _actual_cost(Session(s.id, s.harness, s.role, s.path, turns=ts), pricing.lookup(m, s.platform))
142
+ for m, ts in by_model.items()
143
+ )
144
+
145
+
146
+ def _compaction_calls(s: Session, pricing: PricingTable) -> float:
147
+ """Estimated cost of a session's compaction requests, which are not logged turns: each reads the context from
148
+ the cache and writes a summary (its logged text when there is one, else the replay's default size)."""
149
+ model = s.model
150
+ total = 0.0
151
+ for c in s.compactions:
152
+ if not c.pre_tokens:
153
+ continue
154
+ _, ro, _, rr = pricing.lookup(model, s.platform).rates(c.pre_tokens)
155
+ summ = c.summary_len // 4 if c.summary_len else SUMMARY_TOKENS
156
+ total += c.pre_tokens * rr + summ * ro
157
+ return total
158
+
159
+
160
+ def observe(ss: list[Session], pricing: PricingTable) -> dict[str, Any]:
161
+ """Logged figures for one period of one group."""
162
+ if not ss:
163
+ return {
164
+ "sessions": 0, "turns": 0, "active_days": 0, "cost": 0.0, "compaction_call_cost": 0.0, "compactions": 0,
165
+ "idle_compactions": 0, "manual_compactions": 0, "per_session": [], "median_compaction_tokens": None,
166
+ } # fmt: skip
167
+ # `compactions` counts only what the threshold caused: a hand-typed /compact or an idle compaction says nothing
168
+ # about the setting. All three cost a summary request, so all three are in the cost.
169
+ calls = [_compaction_calls(s, pricing) for s in ss]
170
+ per = [
171
+ (_logged_cost(s, pricing) + calls[i], len(s.turns), sum(is_threshold(c) for c in s.compactions),
172
+ sum(c.idle for c in s.compactions))
173
+ for i, s in enumerate(ss)
174
+ ] # fmt: skip
175
+ pre = [c.pre_tokens for s in ss for c in s.compactions if c.pre_tokens and is_threshold(c)]
176
+ return {
177
+ "sessions": len(ss),
178
+ "turns": sum(p[1] for p in per),
179
+ "active_days": _active_days(ss),
180
+ "cost": sum(p[0] for p in per),
181
+ "compaction_call_cost": sum(calls),
182
+ "compactions": sum(p[2] for p in per),
183
+ "idle_compactions": sum(p[3] for p in per),
184
+ "manual_compactions": sum(not is_auto(c) for s in ss for c in s.compactions),
185
+ "per_session": per,
186
+ "median_compaction_tokens": int(statistics.median(pre)) if pre else None,
187
+ }
188
+
189
+
190
+ def _cost_per_kturn(rows: list[tuple[float, int, int, int]]) -> float | None:
191
+ turns = sum(r[1] for r in rows)
192
+ return sum(r[0] for r in rows) / turns * 1000 if turns else None
193
+
194
+
195
+ def _comp_per_kturn(rows: list[tuple[float, int, int, int]]) -> float | None:
196
+ turns = sum(r[1] for r in rows)
197
+ return sum(r[2] for r in rows) / turns * 1000 if turns else None
198
+
199
+
200
+ def _idle_per_kturn(rows: list[tuple[float, int, int, int]]) -> float | None:
201
+ turns = sum(r[1] for r in rows)
202
+ return sum(r[3] for r in rows) / turns * 1000 if turns else None
203
+
204
+
205
+ def _change(b: float | None, a: float | None, pct: bool) -> float | None:
206
+ if b is None or a is None or (pct and not b):
207
+ return None
208
+ return (a / b - 1) * 100 if pct else a - b
209
+
210
+
211
+ def _interval(before: list, after: list, fn: Any, pct: bool) -> list[float] | None:
212
+ """80% bootstrap interval of the change in `fn` (cost or compactions per 1k turns), resampling sessions."""
213
+ if len(before) < 2 or len(after) < 2:
214
+ return None
215
+ rng = random.Random(7)
216
+ vals = []
217
+ for _ in range(BOOTSTRAP):
218
+ v = _change(fn([rng.choice(before) for _ in before]), fn([rng.choice(after) for _ in after]), pct)
219
+ if v is not None:
220
+ vals.append(v)
221
+ if len(vals) < BOOTSTRAP // 2:
222
+ return None
223
+ vals.sort()
224
+ return [vals[int(0.1 * len(vals))], vals[int(0.9 * len(vals)) - 1]]
225
+
226
+
227
+ def replay_pair(
228
+ ss: list[Session],
229
+ pricing: PricingTable,
230
+ harness: str,
231
+ model: str,
232
+ old: int | None,
233
+ new: int,
234
+ base: SimOptions | None = None,
235
+ ) -> dict[str, dict[str, Any]]:
236
+ """Replay a period's sessions at the old (None = harness default) and the new threshold, per role. `base` carries
237
+ options such as the idle-compaction setting; the grid is unused (only the default / current points are)."""
238
+ opts = SimOptions(grid_start=100_000, grid_stop=100_000)
239
+ if base is not None:
240
+ opts.idle_compaction, opts.idle_min_tokens = base.idle_compaction, base.idle_min_tokens
241
+ at_new = analyze(ss, pricing, opts, current={(harness, model): (new, "")})
242
+ at_old = analyze(ss, pricing, opts, current={(harness, model): (old, "")}) if old is not None else None
243
+ out = {}
244
+ for g in at_new["groups"]:
245
+ o = g["default"]
246
+ if at_old is not None:
247
+ o = next(x["current"] for x in at_old["groups"] if x["role"] == g["role"] and x["model"] == g["model"])
248
+ out[g["role"]] = {
249
+ "old": o,
250
+ "new": g["current"],
251
+ "turns": g["n_turns"],
252
+ "old_threshold": g["default"]["threshold"],
253
+ }
254
+ return out
255
+
256
+
257
+ def _threshold_comps(p: dict[str, Any]) -> int:
258
+ """Replayed compactions the threshold caused: not idle ones, not the hand-typed /compact the replay keeps."""
259
+ return int(p["compactions"] - p.get("idle_compactions", 0) - p.get("manual_compactions", 0))
260
+
261
+
262
+ def _predicted(r: dict[str, Any]) -> dict[str, float | None]:
263
+ o, n, turns = r["old"], r["new"], max(r["turns"], 1)
264
+ return {
265
+ "cost_pct": (n["cost"] / o["cost"] - 1) * 100 if o["cost"] else None,
266
+ "compactions_per_kturn": (_threshold_comps(n) - _threshold_comps(o)) / turns * 1000,
267
+ "idle_per_kturn": (n.get("idle_compactions", 0) - o.get("idle_compactions", 0)) / turns * 1000,
268
+ "threshold_reached": bool(_threshold_comps(n) or _threshold_comps(o)),
269
+ }
270
+
271
+
272
+ def _verdict(g: dict[str, Any], min_sessions: int, min_days: int) -> tuple[str, str]:
273
+ b, a = g["before"], g["after"]
274
+ if g["already_in_effect"]:
275
+ return "already", (
276
+ "the sessions before this date already compacted near the new threshold, so it took effect earlier "
277
+ "than the time given: use an earlier --applied-at (the settings file's modification time is not it)"
278
+ )
279
+ if not (b["compactions"] or a["compactions"] or g["predicted"]["threshold_reached"]
280
+ or (g["replay_after"] or {}).get("threshold_reached")): # fmt: skip
281
+ return "untouched", (
282
+ "the threshold was not reached before or after, nor in the replays: the cost change comes from the work, "
283
+ "not from this setting"
284
+ )
285
+ if min(b["sessions"], a["sessions"]) < min_sessions or min(b["active_days"], a["active_days"]) < min_days:
286
+ return "too_early", (
287
+ f"too early: need {min_sessions}+ sessions and {min_days}+ active days on each side "
288
+ f"(have {b['sessions']}/{a['sessions']} sessions, {b['active_days']}/{a['active_days']} days)"
289
+ )
290
+ obs, pred, ci = g["observed"]["cost_pct"], g["predicted"]["cost_pct"], g["observed"]["cost_pct_interval"]
291
+ if obs is None or pred is None or ci is None:
292
+ return "unclear", "not enough turns on one side to compare cost"
293
+ after_rep = (g["replay_after"] or {}).get("cost_pct")
294
+ shifted = after_rep is not None and abs(after_rep - pred) > 10
295
+ note = " (the replay on the after sessions differs from the prediction: the workload changed)" if shifted else ""
296
+ if ci[0] <= pred <= ci[1]:
297
+ return "consistent", "consistent with the prediction, within the noise" + note
298
+ if obs > pred:
299
+ return "less", "saved less than predicted (or cost more)" + note
300
+ return "more", "saved more than predicted" + note
301
+
302
+
303
+ def verify(
304
+ sessions: list[Session],
305
+ manifest: dict[str, Any],
306
+ pricing: PricingTable,
307
+ *,
308
+ min_sessions: int = MIN_SESSIONS,
309
+ min_days: int = MIN_ACTIVE_DAYS,
310
+ opts: SimOptions | None = None,
311
+ ) -> dict[str, Any]:
312
+ t = float(manifest["created"])
313
+ groups = []
314
+ dropped_total = 0
315
+ for ch in changes_from_manifest(manifest):
316
+ mine = [s for s in sessions if s.harness == ch.harness and (not ch.model or s.model == ch.model)]
317
+ for model in sorted({s.model for s in mine}):
318
+ ms = [s for s in mine if s.model == model]
319
+ before, after, dropped = split(ms, t)
320
+ dropped_total += dropped
321
+ if not before or not after:
322
+ groups.append(_empty(ch, model, t, bool(before)))
323
+ continue
324
+ pb = replay_pair(before, pricing, ch.harness, model, ch.old, ch.new, opts)
325
+ pa = replay_pair(after, pricing, ch.harness, model, ch.old, ch.new, opts)
326
+ for role in sorted(pb):
327
+ rb = [s for s in before if s.role == role]
328
+ ra = [s for s in after if s.role == role]
329
+ ob, oa = observe(rb, pricing), observe(ra, pricing)
330
+ g: dict[str, Any] = {
331
+ "harness": ch.harness,
332
+ "model": model,
333
+ "role": role,
334
+ "applied_at": t,
335
+ "old": ch.old,
336
+ "old_effective": pb[role]["old_threshold"],
337
+ "new": ch.new,
338
+ "new_effective": pb[role]["new"]["threshold"], # what the harness honours (clamped to its window)
339
+ "expected_compactions_after": _threshold_comps(pa[role]["new"]) if role in pa else 0,
340
+ "before": {k: v for k, v in ob.items() if k != "per_session"},
341
+ "after": {k: v for k, v in oa.items() if k != "per_session"},
342
+ "predicted": _predicted(pb[role]),
343
+ "replay_after": _predicted(pa[role]) if role in pa else None,
344
+ "observed": {
345
+ "cost_per_kturn_before": _cost_per_kturn(ob["per_session"]),
346
+ "cost_per_kturn_after": _cost_per_kturn(oa["per_session"]),
347
+ "cost_pct": _change(
348
+ _cost_per_kturn(ob["per_session"]), _cost_per_kturn(oa["per_session"]), True
349
+ ),
350
+ "cost_pct_interval": _interval(ob["per_session"], oa["per_session"], _cost_per_kturn, True),
351
+ "compactions_per_kturn_before": _comp_per_kturn(ob["per_session"]),
352
+ "compactions_per_kturn_after": _comp_per_kturn(oa["per_session"]),
353
+ "compactions_per_kturn": _change(
354
+ _comp_per_kturn(ob["per_session"]), _comp_per_kturn(oa["per_session"]), False
355
+ ),
356
+ "compactions_interval": _interval(ob["per_session"], oa["per_session"], _comp_per_kturn, False),
357
+ "idle_per_kturn_before": _idle_per_kturn(ob["per_session"]),
358
+ "idle_per_kturn_after": _idle_per_kturn(oa["per_session"]),
359
+ "idle_per_kturn": _change(
360
+ _idle_per_kturn(ob["per_session"]), _idle_per_kturn(oa["per_session"]), False
361
+ ),
362
+ },
363
+ }
364
+ g["in_effect"] = _in_effect(g)
365
+ g["already_in_effect"] = _near(g["before"]["median_compaction_tokens"], g["new_effective"])
366
+ g["verdict"], g["summary"] = _verdict(g, min_sessions, min_days)
367
+ groups.append(g)
368
+ return {"applied_at": t, "groups": groups, "dropped_sessions": dropped_total}
369
+
370
+
371
+ def _empty(ch: Change, model: str, t: float, has_before: bool) -> dict[str, Any]:
372
+ side = "after" if has_before else "before"
373
+ return {"harness": ch.harness, "model": model, "role": "*", "applied_at": t, "old": ch.old, "new": ch.new,
374
+ "verdict": "no_data", "summary": f"no sessions {side} the change for this model"} # fmt: skip
375
+
376
+
377
+ def _in_effect(g: dict[str, Any]) -> str:
378
+ """Did compactions after the change happen near the threshold the harness honours?
379
+ 'yes' / 'no', 'none seen' when the replay says the after sessions should have compacted, else 'n/a'."""
380
+ med, eff = g["after"]["median_compaction_tokens"], g["new_effective"]
381
+ if med is None:
382
+ return "none seen" if g["expected_compactions_after"] > 0 else "n/a"
383
+ return "yes" if _near(med, eff) else "no"
384
+
385
+
386
+ def _near(median_tokens: int | None, threshold: int) -> bool:
387
+ return median_tokens is not None and NEAR[0] * threshold <= median_tokens <= NEAR[1] * threshold
388
+
389
+
390
+ # ---------- text ----------
391
+
392
+
393
+ def _fmt(x: float | None, spec: str) -> str:
394
+ return "-" if x is None else format(x, spec)
395
+
396
+
397
+ def _range(iv: list[float] | None, spec: str) -> str:
398
+ return "" if not iv else f" (80%: {iv[0]:{spec}}..{iv[1]:{spec}})"
399
+
400
+
401
+ def _k(n: int | None) -> str:
402
+ return "default" if n is None else f"{n // 1000}k"
403
+
404
+
405
+ def render(res: dict[str, Any]) -> str:
406
+ when = time.strftime("%Y-%m-%d %H:%M", time.localtime(res["applied_at"]))
407
+ lines = [f"Verification of the change applied {when}"]
408
+ if res.get("note"):
409
+ lines.append(res["note"])
410
+ for g in res["groups"]:
411
+ lines.append("")
412
+ if g["verdict"] == "no_data":
413
+ lines += [f"{g['model']} · {g['harness']}: {g['summary']}"]
414
+ continue
415
+ old = g["old_effective"] if g["old"] is None else g["old"]
416
+ lines.append(f"{g['model']} · {g['role']} {_k(g['old'])} ({old // 1000}k) → {_k(g['new'])}")
417
+ b, a, o, p, r = g["before"], g["after"], g["observed"], g["predicted"], g["replay_after"] or {}
418
+ lines += [
419
+ f" {'':26}{'before':>9}{'after':>9} {'observed change':<30}{'predicted':>10}{'replay on after':>17}",
420
+ f" {'sessions / active days':26}{str(b['sessions']) + ' / ' + str(b['active_days']):>9}"
421
+ f"{str(a['sessions']) + ' / ' + str(a['active_days']):>9}",
422
+ f" {'cost per 1k turns':26}{'$' + _fmt(o['cost_per_kturn_before'], '.2f'):>9}"
423
+ f"{'$' + _fmt(o['cost_per_kturn_after'], '.2f'):>9} "
424
+ f"{(_fmt(o['cost_pct'], '+.1f') + '%' + _range(o['cost_pct_interval'], '+.0f')):<30}"
425
+ f"{_fmt(p['cost_pct'], '+.1f') + '%':>10}{_fmt(r.get('cost_pct'), '+.1f') + '%':>17}",
426
+ f" {'compactions per 1k turns':26}{_fmt(o['compactions_per_kturn_before'], '.2f'):>9}"
427
+ f"{_fmt(o['compactions_per_kturn_after'], '.2f'):>9} "
428
+ f"{(_fmt(o['compactions_per_kturn'], '+.2f') + _range(o['compactions_interval'], '+.1f')):<30}"
429
+ f"{_fmt(p['compactions_per_kturn'], '+.2f'):>10}{_fmt(r.get('compactions_per_kturn'), '+.2f'):>17}",
430
+ ]
431
+ if o.get("idle_per_kturn_before") or o.get("idle_per_kturn_after") or p.get("idle_per_kturn"):
432
+ lines.append(
433
+ f" {'idle compactions per 1k turns':30}{_fmt(o['idle_per_kturn_before'], '.2f'):>5}"
434
+ f"{_fmt(o['idle_per_kturn_after'], '.2f'):>9} {_fmt(o['idle_per_kturn'], '+.2f'):<30}"
435
+ f"{_fmt(p.get('idle_per_kturn'), '+.2f'):>10}{_fmt(r.get('idle_per_kturn'), '+.2f'):>17}"
436
+ )
437
+ med = a["median_compaction_tokens"]
438
+ near = _k(g["new_effective"])
439
+ eff = {
440
+ "yes": f"✓ near {near}",
441
+ "no": f"✗ far from {near}: the setting may be overridden (project settings, env vars, CLI flags)",
442
+ "none seen": "no compaction after the change",
443
+ "n/a": "-",
444
+ }[g["in_effect"]]
445
+ before_med = f"{b['median_compaction_tokens'] // 1000}k" if b["median_compaction_tokens"] else "-"
446
+ after_med = f"{med // 1000}k" if med else "-"
447
+ lines.append(f" {'median size at compaction':26}{before_med:>9}{after_med:>9} {eff}")
448
+ lines.append(f" → {g['summary']}")
449
+ lines += [
450
+ "",
451
+ "Cost is the logged list-price figure per 1k turns, so a busier week does not look like a cost rise, plus"
452
+ " an estimate of each compaction's summary request, which the logs do not record.",
453
+ "It is not your invoice and does not control for a change in what you worked on. Wall-clock is not verified.",
454
+ ]
455
+ manual = sum(g[side]["manual_compactions"] for g in res["groups"] if "before" in g for side in ("before", "after"))
456
+ if manual:
457
+ lines.append(
458
+ f"{manual} hand-typed /compact left out of the compaction counts: they say nothing about the threshold."
459
+ )
460
+ if res["dropped_sessions"]:
461
+ lines.append(f"{res['dropped_sessions']} session(s) spanning the change, or without timestamps, were left out.")
462
+ return "\n".join(lines)