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,238 @@
1
+ """Threshold selection: three profiles over the replay grid, with guardrails.
2
+
3
+ A profile is a value of time (USD per hour of agent wall-clock folded into the score) plus guardrails:
4
+
5
+ cost money first $10/h no minimum window (warns below 25% of the max window)
6
+ balanced default $250/h never below 40% of the max window, <= 30 min/day of added compaction wait
7
+ time time first $600/h never below 50% of the max window, <= 30 min/day of added compaction wait
8
+
9
+ Within the allowed thresholds the pick is the largest threshold whose score is within `tol` of the lowest
10
+ (`recommend`). Every profile keeps the recall floor. Selection works on the stored grid arrays only, so a result
11
+ file can be re-selected with another profile or value of time without replaying.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ from typing import Any
18
+
19
+ PROFILES: dict[str, dict[str, Any]] = {
20
+ "cost": {"value_of_time": 10.0, "min_fraction": 0.0, "enforce_wait_cap": False},
21
+ "balanced": {"value_of_time": 250.0, "min_fraction": 0.40, "enforce_wait_cap": True},
22
+ "time": {"value_of_time": 600.0, "min_fraction": 0.50, "enforce_wait_cap": True},
23
+ }
24
+ PROFILE_NAMES = tuple(PROFILES)
25
+
26
+
27
+ DEFAULT_PROFILE = "balanced"
28
+ WARN_FRACTION = 0.25 # any profile below this share of the max window gets a warning
29
+ WAIT_CAP_MIN_PER_DAY = 30.0 # added compaction + re-discovery wait vs the harness default
30
+
31
+
32
+ class InfeasibleCap(ValueError):
33
+ """The threshold cap leaves no grid point to recommend."""
34
+
35
+
36
+ def recommend(
37
+ grid: list[int],
38
+ combined: list[float],
39
+ recall: list[float],
40
+ floor: float,
41
+ tol: float = 0.02,
42
+ range_tol: float = 0.05,
43
+ allowed: list[int] | None = None,
44
+ ) -> dict:
45
+ """Largest threshold within `tol` of the lowest score among `allowed` indexes that meet the recall floor."""
46
+ idx = allowed if allowed else list(range(len(grid)))
47
+ ok = [i for i in idx if recall[i] >= floor]
48
+ floor_ok = bool(ok)
49
+ if not ok: # nothing meets the floor: fall back to the highest-recall threshold(s)
50
+ best_r = max(recall[i] for i in idx)
51
+ ok = [i for i in idx if recall[i] >= best_r - 1e-9]
52
+ lo = min(combined[i] for i in ok)
53
+ best = max(i for i in ok if combined[i] <= lo * (1 + tol))
54
+ rng = [i for i in ok if combined[i] <= lo * (1 + range_tol)]
55
+ return {
56
+ "threshold": grid[best],
57
+ "range": [grid[min(rng)], grid[max(rng)]],
58
+ "floor_met": floor_ok,
59
+ "recall_floor": floor,
60
+ "tolerance": tol,
61
+ "min_combined_threshold": grid[min(ok, key=lambda i: combined[i])],
62
+ "combined_at_best": combined[best],
63
+ "recall_at_best": recall[best],
64
+ "note": "" if floor_ok else "No threshold met the recall floor; showing highest-recall candidates.",
65
+ }
66
+
67
+
68
+ def pareto(combined: list[float], recall: list[float]) -> list[int]:
69
+ """Indexes not dominated on (lower combined cost, higher recall)."""
70
+ out = []
71
+ for i in range(len(combined)):
72
+ dom = any(
73
+ combined[j] <= combined[i]
74
+ and recall[j] >= recall[i]
75
+ and (combined[j] < combined[i] or recall[j] > recall[i])
76
+ for j in range(len(combined))
77
+ )
78
+ if not dom:
79
+ out.append(i)
80
+ return out
81
+
82
+
83
+ def score(g: dict[str, Any], vot: float) -> list[float]:
84
+ """cost + penalty + value of time × wall-clock, per grid point."""
85
+ return [c + t / 3600 * vot for c, t in zip(g["combined_cost"], g["time_s"], strict=True)]
86
+
87
+
88
+ def point(g: dict[str, Any], i: int, vot: float) -> dict[str, Any]:
89
+ keys = ("cost", "penalty", "combined_cost", "time_s", "time_turns_s", "time_compact_s", "time_redisc_s",
90
+ "compactions", "idle_compactions", "idle_cost", "idle_tail_cost", "manual_compactions",
91
+ "recall") # fmt: skip
92
+ p = {k: g[k][i] for k in keys if k in g} # idle_* exist in results from this version on
93
+ p["threshold"] = g["grid"][i]
94
+ p["combined"] = p["combined_cost"] + p["time_s"] / 3600 * vot
95
+ return p
96
+
97
+
98
+ MONTH_DAYS = 30.0
99
+
100
+
101
+ def impact(
102
+ d_cost: float,
103
+ d_time_s: float,
104
+ wait_s: float,
105
+ turn_gain_s: float,
106
+ compactions: float,
107
+ ref_compactions: float,
108
+ days: float,
109
+ active_days: float | None = None,
110
+ ) -> dict[str, Any]:
111
+ """Per-day / per-active-day / per-month figures for one profile vs one reference.
112
+
113
+ Sign convention: negative usd = money saved, negative minutes = time saved. `wait_s` is added compaction
114
+ + re-discovery wait (positive = more waiting), `turn_gain_s` is the turn-speed gain from a smaller context
115
+ (positive = faster turns), so d_time_s = wait_s - turn_gain_s. A month is 30 calendar days.
116
+ """
117
+ days = max(float(days), 1.0)
118
+ active = max(float(active_days), 1.0) if active_days else None
119
+
120
+ def per(x: float, scale: float = 1.0) -> dict[str, float | None]:
121
+ return {
122
+ "per_day": x * scale / days,
123
+ "per_active_day": x * scale / active if active else None,
124
+ "per_month": x * scale / days * MONTH_DAYS,
125
+ }
126
+
127
+ return {
128
+ "days": days,
129
+ "active_days": active,
130
+ "usd": per(d_cost),
131
+ "minutes": per(d_time_s, 1 / 60),
132
+ "wait_minutes": per(wait_s, 1 / 60),
133
+ "turn_gain_minutes": per(turn_gain_s, 1 / 60),
134
+ "compactions": per(compactions),
135
+ "ref_compactions": per(ref_compactions),
136
+ }
137
+
138
+
139
+ def compare(
140
+ p: dict[str, Any], ref: dict[str, Any], days: float = 1.0, active_days: float | None = None
141
+ ) -> dict[str, Any]:
142
+ """Profile (or any point) minus a reference point (default or current)."""
143
+ dc = p["combined_cost"] - ref["combined_cost"]
144
+ added = (p["time_compact_s"] + p["time_redisc_s"]) - (ref["time_compact_s"] + ref["time_redisc_s"])
145
+ dt = p["time_s"] - ref["time_s"]
146
+ gain = ref["time_turns_s"] - p["time_turns_s"]
147
+ return {
148
+ "impact": impact(dc, dt, added, gain, p["compactions"], ref["compactions"], days, active_days),
149
+ "d_cost": dc,
150
+ "d_cost_pct": dc / ref["combined_cost"] if ref["combined_cost"] else 0.0,
151
+ "d_time_s": dt,
152
+ "d_time_pct": dt / ref["time_s"] if ref["time_s"] else 0.0,
153
+ "d_time_min_per_day": dt / 60 / days,
154
+ "time_saved_context_s": gain,
155
+ "time_added_compaction_s": added,
156
+ "added_wait_min_per_day": added / 60 / days,
157
+ "compactions": p["compactions"],
158
+ "ref_compactions": ref["compactions"],
159
+ "compactions_per_day": p["compactions"] / days,
160
+ "ref_compactions_per_day": ref["compactions"] / days,
161
+ "d_recall": p["recall"] - ref["recall"],
162
+ }
163
+
164
+
165
+ def select_profile(
166
+ g: dict[str, Any],
167
+ name: str,
168
+ *,
169
+ vot: float | None = None,
170
+ floor: float = 0.90,
171
+ tol: float = 0.02,
172
+ range_tol: float = 0.05,
173
+ wait_cap: float = WAIT_CAP_MIN_PER_DAY,
174
+ cap: int | None = None,
175
+ ) -> dict[str, Any]:
176
+ """Pick one profile's threshold from a group's grid arrays. `g` needs grid, cost arrays, time arrays,
177
+ compactions, recall, effective_max, days and default (a point at the harness default)."""
178
+ spec = PROFILES[name]
179
+ v = spec["value_of_time"] if vot is None else float(vot)
180
+ grid, days, d = g["grid"], max(float(g.get("days") or 1.0), 1.0), g["default"]
181
+ comb = score(g, v)
182
+ emax = int(g.get("effective_max") or grid[-1])
183
+ step = (grid[1] - grid[0]) if len(grid) > 1 else 1
184
+ min_thr = math.ceil(emax * spec["min_fraction"] / step) * step if spec["min_fraction"] else 0
185
+ limit = min(x for x in (cap, emax, grid[-1]) if x is not None)
186
+ if grid[0] > limit: # never answer with a threshold above the cap
187
+ raise InfeasibleCap(
188
+ f"no grid threshold is at or below {limit:,} tokens (the grid starts at {grid[0]:,}"
189
+ + (f"; --max-threshold is {cap:,}" if cap is not None and cap == limit else "")
190
+ + "): lower the grid start or raise the cap"
191
+ )
192
+ in_range = [i for i, T in enumerate(grid) if min_thr <= T <= limit]
193
+ flags: list[str] = []
194
+ if not in_range: # the grid does not reach the minimum: use the largest allowed threshold
195
+ in_range = [max(i for i, T in enumerate(grid) if limit >= T)]
196
+ flags.append("min_window_unreachable")
197
+
198
+ def wait(i: int) -> float:
199
+ added = (g["time_compact_s"][i] + g["time_redisc_s"][i]) - (d["time_compact_s"] + d["time_redisc_s"])
200
+ return added / 60 / days
201
+
202
+ allowed = in_range
203
+ if spec["enforce_wait_cap"]:
204
+ under = [i for i in in_range if wait(i) <= wait_cap]
205
+ if under:
206
+ allowed = under
207
+ else:
208
+ flags.append("wait_cap_unreachable")
209
+ rec = recommend(grid, comb, g["recall"], floor, tol, range_tol, allowed)
210
+ i = grid.index(rec["threshold"])
211
+ unconstrained = recommend(grid, comb, g["recall"], floor, tol, range_tol)["threshold"]
212
+ if rec["threshold"] != unconstrained:
213
+ flags.append("guardrail_applied")
214
+ if not rec["floor_met"]:
215
+ flags.append("recall_floor_not_met")
216
+ if rec["threshold"] < WARN_FRACTION * emax:
217
+ flags.append("below_quarter_window")
218
+ if wait(i) > wait_cap:
219
+ flags.append("wait_over_cap")
220
+ p = point(g, i, v)
221
+ p.update(
222
+ {
223
+ "profile": name,
224
+ "value_of_time": v,
225
+ "min_threshold": min_thr,
226
+ "unconstrained_threshold": unconstrained,
227
+ "fraction_of_max": rec["threshold"] / emax if emax else 0.0,
228
+ "recommendation": rec,
229
+ "flags": flags,
230
+ "wait_cap_min_per_day": wait_cap,
231
+ }
232
+ )
233
+ return p
234
+
235
+
236
+ def select_all(g: dict[str, Any], *, selected: str = DEFAULT_PROFILE, vot: float | None = None, **kw: Any) -> dict:
237
+ """All three profiles; `vot` overrides only the selected profile's value of time."""
238
+ return {n: select_profile(g, n, vot=vot if n == selected else None, **kw) for n in PROFILE_NAMES}
@@ -0,0 +1,134 @@
1
+ """Wall-clock model fitted from the user's own timestamps.
2
+
3
+ turn latency(ctx) median latency per 50k-token context bin, made monotone non-decreasing, interpolated.
4
+ compaction latency(n) least-squares a + b·pre_tokens over observed compactions (a, b >= 0).
5
+ re-discovery step median turn latency.
6
+
7
+ Latency of a turn = timestamp of the response minus the last user/tool-result line before it. That includes
8
+ generation time and, for Claude Code, only the first content block of a response. It is a proxy, so every fit
9
+ carries a confidence label. A fit that is not "ok" never drives a recommendation: the group falls back to the
10
+ pooled fit of all sessions of the same harness when that one is "ok", else to a documented prior that is
11
+ deliberately pessimistic about compaction latency, so thin data cannot push thresholds down.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import statistics
17
+ from bisect import bisect_right
18
+ from dataclasses import asdict, dataclass, field
19
+
20
+ from ..model import Session
21
+
22
+ BIN = 50_000
23
+ MAX_TURN_S = 600.0
24
+ MIN_BIN_N = 5
25
+ # Priors (assumed): used only when the user's data is too thin to fit.
26
+ PRIOR_TURN = (8.0, 4.0 / 100_000) # seconds = a + b·ctx
27
+ PRIOR_COMPACT = (30.0, 0.3 / 1000) # seconds = a + b·pre_tokens (pessimistic: ~120 s at 300k)
28
+ MIN_COMPACT_OK = 20
29
+
30
+
31
+ @dataclass
32
+ class TimeModel:
33
+ xs: list[float] = field(default_factory=list) # bin centers
34
+ ys: list[float] = field(default_factory=list) # monotone medians (seconds)
35
+ turn_prior: tuple[float, float] = PRIOR_TURN
36
+ compact_ab: tuple[float, float] = PRIOR_COMPACT
37
+ median_turn_s: float = 10.0
38
+ n_turn_samples: int = 0
39
+ n_bins: int = 0
40
+ n_compact_samples: int = 0
41
+ turn_confidence: str = "prior" # "ok" | "low" | "prior" (of this group's own data)
42
+ compact_confidence: str = "prior"
43
+ turn_source: str = "prior" # what the model actually uses: "own" | "pooled" | "prior"
44
+ compact_source: str = "prior"
45
+ slope_s_per_100k: float = 0.0
46
+
47
+ def turn(self, ctx: float) -> float:
48
+ if not self.xs:
49
+ a, b = self.turn_prior
50
+ return a + b * ctx
51
+ if ctx <= self.xs[0]:
52
+ return self.ys[0]
53
+ if ctx >= self.xs[-1]:
54
+ return self.ys[-1]
55
+ i = bisect_right(self.xs, ctx)
56
+ w = (ctx - self.xs[i - 1]) / (self.xs[i] - self.xs[i - 1])
57
+ return self.ys[i - 1] + w * (self.ys[i] - self.ys[i - 1])
58
+
59
+ def compact(self, pre: float) -> float:
60
+ a, b = self.compact_ab
61
+ return a + b * pre
62
+
63
+ def summary(self) -> dict:
64
+ d = asdict(self)
65
+ d.pop("xs")
66
+ d.pop("ys")
67
+ d["curve"] = [[int(x), round(y, 2)] for x, y in zip(self.xs, self.ys, strict=True)]
68
+ return d
69
+
70
+
71
+ def turn_samples(sessions: list[Session]) -> list[tuple[int, float]]:
72
+ out = []
73
+ for s in sessions:
74
+ for t in s.turns:
75
+ if t.ts and t.start_ts:
76
+ d = t.ts - t.start_ts
77
+ if 0 < d <= MAX_TURN_S:
78
+ out.append((t.ctx, d))
79
+ return out
80
+
81
+
82
+ def _fit_line(pts: list[tuple[float, float]]) -> tuple[float, float]:
83
+ n = len(pts)
84
+ mx = sum(x for x, _ in pts) / n
85
+ my = sum(y for _, y in pts) / n
86
+ vx = sum((x - mx) ** 2 for x, _ in pts)
87
+ b = max(sum((x - mx) * (y - my) for x, y in pts) / vx, 0.0) if vx else 0.0
88
+ a = max(my - b * mx, 0.0)
89
+ return a, b
90
+
91
+
92
+ def fit(sessions: list[Session], fallback: TimeModel | None = None) -> TimeModel:
93
+ """Fit from `sessions`; parts whose confidence is not "ok" use `fallback` (if it is "ok") or the prior."""
94
+ m = TimeModel()
95
+ samples = turn_samples(sessions)
96
+ m.n_turn_samples = len(samples)
97
+ if samples:
98
+ m.median_turn_s = statistics.median(d for _, d in samples)
99
+ bins: dict[int, list[float]] = {}
100
+ for ctx, d in samples:
101
+ bins.setdefault(ctx // BIN, []).append(d)
102
+ good = sorted((k, statistics.median(v)) for k, v in bins.items() if len(v) >= MIN_BIN_N)
103
+ m.n_bins = len(good)
104
+ if good:
105
+ run = 0.0
106
+ for k, med in good:
107
+ run = max(run, med) # monotone non-decreasing
108
+ m.xs.append(k * BIN + BIN / 2)
109
+ m.ys.append(run)
110
+ if len(good) >= 2:
111
+ m.slope_s_per_100k = _fit_line([(k * BIN + BIN / 2, med) for k, med in good])[1] * 100_000
112
+ m.turn_confidence = "ok" if (m.n_turn_samples >= 200 and m.n_bins >= 3) else ("low" if good else "prior")
113
+ comp = [
114
+ (float(c.pre_tokens), float(c.duration_s))
115
+ for s in sessions
116
+ for c in s.compactions
117
+ if c.duration_s and c.pre_tokens
118
+ ]
119
+ m.n_compact_samples = len(comp)
120
+ if len(comp) >= 5:
121
+ m.compact_confidence = "ok" if len(comp) >= MIN_COMPACT_OK else "low"
122
+ if m.compact_confidence == "ok":
123
+ m.compact_ab, m.compact_source = _fit_line(comp), "own"
124
+ elif fallback is not None and fallback.compact_confidence == "ok":
125
+ m.compact_ab, m.compact_source = fallback.compact_ab, "pooled"
126
+ if m.turn_confidence == "ok":
127
+ m.turn_source = "own"
128
+ elif fallback is not None and fallback.turn_confidence == "ok":
129
+ m.xs, m.ys, m.turn_source = list(fallback.xs), list(fallback.ys), "pooled"
130
+ m.median_turn_s = fallback.median_turn_s
131
+ else:
132
+ m.xs, m.ys = [], [] # a thin curve must not drive the choice either
133
+ m.median_turn_s = TimeModel.median_turn_s # nor may a handful of samples set the re-discovery step
134
+ return m