@alexgreensh/token-optimizer 5.13.75 → 5.13.76

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 (84) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/hooks/posttooluse_runner.py +7 -9
  5. package/hooks/run.py +5 -1
  6. package/hooks/stop_runner.py +15 -56
  7. package/hooks/userpromptsubmit_runner.py +29 -4
  8. package/package.json +1 -1
  9. package/skills/token-optimizer/assets/dashboard.html +30 -14
  10. package/skills/token-optimizer/assets/savings_story.js +103 -27
  11. package/skills/token-optimizer/references/agent-prompts.md +2 -0
  12. package/skills/token-optimizer/references/implementation-playbook.md +1 -0
  13. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  14. package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
  15. package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
  16. package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
  17. package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
  18. package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
  19. package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
  20. package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
  21. package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
  22. package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
  24. package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
  28. package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
  29. package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
  30. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
  31. package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
  32. package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
  33. package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
  34. package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
  35. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
  36. package/skills/token-optimizer/scripts/_measure/savings.py +75 -81
  37. package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
  38. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  39. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
  40. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
  41. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
  42. package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
  43. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
  44. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
  45. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  46. package/skills/token-optimizer/scripts/archive_result.py +16 -28
  47. package/skills/token-optimizer/scripts/archive_verify.py +1 -1
  48. package/skills/token-optimizer/scripts/bash_compress.py +156 -176
  49. package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
  50. package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
  51. package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
  52. package/skills/token-optimizer/scripts/benchmark.py +11 -13
  53. package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
  54. package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
  55. package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
  56. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  57. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  58. package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
  59. package/skills/token-optimizer/scripts/compact_markers.py +129 -0
  60. package/skills/token-optimizer/scripts/copilot_install.py +3 -0
  61. package/skills/token-optimizer/scripts/cursor_install.py +7 -0
  62. package/skills/token-optimizer/scripts/devin_source.py +5 -5
  63. package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
  64. package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
  65. package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
  66. package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
  67. package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
  68. package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
  69. package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
  70. package/skills/token-optimizer/scripts/grok_install.py +3 -0
  71. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  72. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  73. package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
  74. package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
  75. package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
  76. package/skills/token-optimizer/scripts/measure.py +10 -12
  77. package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
  78. package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
  79. package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
  80. package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
  81. package/skills/token-optimizer/scripts/process_identity.py +66 -0
  82. package/skills/token-optimizer/scripts/read_cache.py +51 -60
  83. package/skills/token-optimizer/scripts/statusline.js +21 -3
  84. package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
@@ -0,0 +1,463 @@
1
+ """Limit-unit accounting: one currency for savings and plan limits (SPEC-limit-units).
2
+
3
+ Prices every token class in input-equivalent limit units using the exact model card
4
+ ratios (R9), never a hard-coded 0.1 read factor. Unknown models stay unpriced (R10).
5
+ Also handles expand_round_trip debits, per-feature signed net, and transcript
6
+ row deduplication / row-timestamp windowing.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import math
12
+ import os
13
+ from datetime import datetime, timedelta
14
+ from pathlib import Path
15
+
16
+ LIMIT_UNITS_LABEL = "share of window, modeled at API-rate weights"
17
+
18
+
19
+ def _resolve_card(facade, model, tier=None, per_request=False, full_input=0):
20
+ """Return the exact rate card dict for *model*, or None if unknown (R9/R10)."""
21
+ if not model:
22
+ return None
23
+ if tier is None:
24
+ tier = facade._load_pricing_tier()
25
+ tier_data = facade.PRICING_TIERS.get(tier, facade.PRICING_TIERS["anthropic"])
26
+ for norm_fn, pricing, lc_pricing, lc_threshold in (
27
+ (facade._normalize_openai_model_name, facade.OPENAI_MODEL_PRICING,
28
+ facade.OPENAI_LONG_CONTEXT_PRICING, facade.OPENAI_LONG_CONTEXT_INPUT_THRESHOLD),
29
+ (facade._normalize_gemini_model_name, facade.GEMINI_MODEL_PRICING,
30
+ facade.GEMINI_LONG_CONTEXT_PRICING, facade.GEMINI_LONG_CONTEXT_INPUT_THRESHOLD),
31
+ ):
32
+ key = norm_fn(model)
33
+ if key:
34
+ rates = pricing[key]
35
+ if per_request and full_input > lc_threshold and key in lc_pricing:
36
+ rates = lc_pricing[key]
37
+ return rates
38
+ normalized = facade._claude_price_key(model, tier_data["claude_models"])
39
+ if normalized and normalized in tier_data["claude_models"]:
40
+ rates = tier_data["claude_models"][normalized]
41
+ lc_models = tier_data.get("claude_models_lc") or {}
42
+ else:
43
+ rates = facade.PRICING_TIERS["anthropic"]["claude_models"].get(normalized or "")
44
+ lc_models = facade.PRICING_TIERS["anthropic"].get("claude_models_lc") or {}
45
+ if rates is None:
46
+ return None
47
+ if (per_request and normalized in lc_models
48
+ and full_input > facade.ANTHROPIC_LONG_CONTEXT_INPUT_THRESHOLD):
49
+ rates = lc_models[normalized]
50
+ return rates
51
+
52
+
53
+ def model_card_ratios(facade, model, tier=None, per_request=False, full_input=0):
54
+ """Return input-normalized class multipliers from the exact model card, or None."""
55
+ rates = _resolve_card(facade, model, tier=tier, per_request=per_request, full_input=full_input)
56
+ if not rates:
57
+ return None
58
+ inp = float(rates.get("input") or 0.0)
59
+ if inp <= 0.0:
60
+ return None
61
+ cw5 = float(rates.get("cache_write", inp * 1.25))
62
+ cw1 = float(rates.get("cache_write_1h", inp * 2.0))
63
+ cr = float(rates.get("cache_read", 0.0))
64
+ out = float(rates.get("output", 0.0))
65
+ return {
66
+ "input": 1.0,
67
+ "cache_write_5m": cw5 / inp,
68
+ "cache_write_1h": cw1 / inp,
69
+ "cache_read": cr / inp,
70
+ "output": out / inp,
71
+ "input_rate_per_m": inp,
72
+ "cache_read_rate_per_m": cr,
73
+ }
74
+
75
+
76
+ def limit_units(row, facade=None, tier=None, per_request=False):
77
+ """Compute input-equivalent limit units for a usage or savings row.
78
+
79
+ Formula:
80
+ input*1 + cache_write_5m*1.25 + cache_write_1h*2
81
+ + cache_read*(card read ratio) + output*(card output ratio)
82
+ where 5m/1h write ratios default to 1.25 / 2.0 (or card ratios when set)
83
+ and read/output ratios always come from the exact model card (R9).
84
+ Unknown model cards return priced=False, units=0.0, unpriced_tokens>0 (R10).
85
+ """
86
+ if facade is None:
87
+ from . import _compat
88
+ facade = _compat.facade()
89
+ r = row or {}
90
+ model = r.get("model") or ""
91
+ inp = int(r.get("input", r.get("fresh_input", r.get("input_tokens", 0))) or 0)
92
+ out = int(r.get("output", r.get("output_tokens", 0)) or 0)
93
+ cr = int(r.get("cache_read", r.get("cache_read_input_tokens", 0)) or 0)
94
+ cw1 = r.get("cache_write_1h", r.get("cache_create_1h"))
95
+ cw5 = r.get("cache_write_5m", r.get("cache_create_5m"))
96
+ cw_total = int(r.get("cache_write", r.get("cache_create", r.get("cache_creation_input_tokens", 0))) or 0)
97
+ if cw1 is not None or cw5 is not None:
98
+ w1 = int(cw1 or 0)
99
+ w5 = int(cw5 or 0)
100
+ unsplit = max(0, cw_total - w1 - w5)
101
+ w5 += unsplit
102
+ else:
103
+ w1 = 0
104
+ w5 = cw_total
105
+ full_input = inp + cr + w5 + w1
106
+ ratios = model_card_ratios(facade, model, tier=tier, per_request=per_request, full_input=full_input)
107
+ if ratios is None:
108
+ return {
109
+ "units": 0.0,
110
+ "priced": False,
111
+ "unpriced_tokens": abs(inp) + abs(out) + abs(cr) + abs(w5) + abs(w1),
112
+ "model": model,
113
+ "by_class": {"input": 0.0, "cache_write_5m": 0.0, "cache_write_1h": 0.0,
114
+ "cache_read": 0.0, "output": 0.0},
115
+ }
116
+ by_class = {
117
+ "input": float(inp) * 1.0,
118
+ "cache_write_5m": float(w5) * 1.25,
119
+ "cache_write_1h": float(w1) * 2.0,
120
+ "cache_read": float(cr) * ratios["cache_read"],
121
+ "output": float(out) * ratios["output"],
122
+ }
123
+ return {
124
+ "units": sum(by_class.values()),
125
+ "priced": True,
126
+ "unpriced_tokens": 0,
127
+ "model": model,
128
+ "by_class": by_class,
129
+ "ratios": ratios,
130
+ }
131
+
132
+
133
+ def _find_next_request_cache_read(facade, session_id, expand_ts=None):
134
+ """Find the next transcript request's (cache_read_tokens, model) after expand_ts."""
135
+ if not session_id or not facade.TRENDS_DB.exists():
136
+ return None
137
+ try:
138
+ conn = facade._init_trends_db()
139
+ try:
140
+ row = conn.execute(
141
+ "SELECT jsonl_path FROM session_log WHERE session_id = ? AND jsonl_path IS NOT NULL LIMIT 1",
142
+ (session_id,),
143
+ ).fetchone()
144
+ finally:
145
+ conn.close()
146
+ except Exception:
147
+ return None
148
+ if not row or not row[0]:
149
+ return None
150
+ path = Path(row[0])
151
+ if not path.is_file():
152
+ return None
153
+ seen_ids = set()
154
+ try:
155
+ with path.open("r", encoding="utf-8", errors="replace") as fh:
156
+ for line in fh:
157
+ line = line.strip()
158
+ if not line:
159
+ continue
160
+ try:
161
+ obj = json.loads(line)
162
+ except ValueError:
163
+ continue
164
+ if not isinstance(obj, dict):
165
+ continue
166
+ ts = obj.get("timestamp") or ""
167
+ if expand_ts and ts and ts <= expand_ts:
168
+ continue
169
+ msg = obj.get("message") if isinstance(obj.get("message"), dict) else {}
170
+ usage = msg.get("usage") if isinstance(msg.get("usage"), dict) else obj.get("usage")
171
+ if not isinstance(usage, dict):
172
+ continue
173
+ mid = msg.get("id") or obj.get("requestId")
174
+ if mid:
175
+ if mid in seen_ids:
176
+ continue
177
+ seen_ids.add(mid)
178
+ cr = int(usage.get("cache_read_input_tokens") or usage.get("cache_read") or 0)
179
+ model = msg.get("model") or obj.get("model") or ""
180
+ if cr > 0 and model:
181
+ return (cr, model)
182
+ except OSError:
183
+ return None
184
+ return None
185
+
186
+
187
+ def log_expand_round_trip(facade, session_id, tool_use_id, feature="tool_archive",
188
+ expand_ts=None, next_request=None):
189
+ """Debit the next request's cache-read round trip when an expand occurs.
190
+
191
+ Logged as event_type='expand_round_trip' (Measured, bookkeeping only).
192
+ If no next request is on record, debits nothing and logs a 0-token marker
193
+ detail='round_trip_unknown' so summaries can report round_trip_unknown.
194
+ """
195
+ try:
196
+ req = next_request if next_request is not None else _find_next_request_cache_read(
197
+ facade, session_id, expand_ts=expand_ts)
198
+ if not req:
199
+ facade._log_savings_event(
200
+ "expand_round_trip", 0, session_id=session_id,
201
+ detail=f"{tool_use_id} ({feature}) round_trip_unknown",
202
+ )
203
+ return {"logged": False, "round_trip_unknown": True, "tokens": 0, "cost_usd": 0.0}
204
+ cr_tokens, model = int(req[0] or 0), str(req[1] or "")
205
+ if cr_tokens <= 0:
206
+ return {"logged": False, "round_trip_unknown": True, "tokens": 0, "cost_usd": 0.0}
207
+ ratios = model_card_ratios(facade, model)
208
+ cost_usd = 0.0
209
+ if ratios is not None:
210
+ cost_usd = cr_tokens * ratios["cache_read_rate_per_m"] / 1e6
211
+ detail = f"{tool_use_id} ({feature}) model={model}"
212
+ facade._log_savings_event(
213
+ "expand_round_trip", cr_tokens, session_id=session_id,
214
+ detail=detail, cost_saved_usd=round(cost_usd, 6),
215
+ )
216
+ return {"logged": True, "round_trip_unknown": False, "tokens": cr_tokens,
217
+ "cost_usd": round(cost_usd, 6), "model": model}
218
+ except Exception:
219
+ return {"logged": False, "round_trip_unknown": True, "tokens": 0, "cost_usd": 0.0}
220
+
221
+
222
+ def apply_round_trip_and_feature_net(summary, counted=None, labels=None, conn=None, cutoff=None):
223
+ """Pop expand_round_trip bookkeeping from by_category and attach per-feature net.
224
+
225
+ net = first_write + repeat_reads - reexpand - round_trip (signed, no floor at 0).
226
+ """
227
+ if not isinstance(summary, dict):
228
+ return summary
229
+ by_cat = summary.get("by_category")
230
+ if not isinstance(by_cat, dict):
231
+ by_cat = {}
232
+ summary["by_category"] = by_cat
233
+ labels = labels or {}
234
+
235
+ rt_entry = by_cat.pop("expand_round_trip", None)
236
+ rt_unknown = 0
237
+ rt_by_feature = {}
238
+ if conn is not None and cutoff is not None:
239
+ try:
240
+ rows = conn.execute(
241
+ "SELECT detail, tokens_saved, cost_saved_usd FROM savings_events "
242
+ "WHERE event_type = 'expand_round_trip' AND timestamp >= ?",
243
+ (cutoff,),
244
+ ).fetchall()
245
+ for detail, tok, cost in rows:
246
+ d = str(detail or "")
247
+ if "round_trip_unknown" in d or int(tok or 0) == 0:
248
+ rt_unknown += 1
249
+ continue
250
+ feat = "tool_archive"
251
+ if "(" in d and ")" in d:
252
+ feat = d.split("(", 1)[1].split(")", 1)[0].strip() or "tool_archive"
253
+ slot = rt_by_feature.setdefault(feat, [0, 0.0])
254
+ slot[0] += int(tok or 0)
255
+ slot[1] += float(cost or 0.0)
256
+ except Exception:
257
+ pass
258
+ elif rt_entry:
259
+ rt_tok = int(rt_entry.get("tokens_saved") or 0)
260
+ rt_cost = float(rt_entry.get("cost_saved_usd") or 0.0)
261
+ if rt_tok > 0:
262
+ rt_by_feature["tool_archive"] = [rt_tok, rt_cost]
263
+ else:
264
+ rt_unknown += int(rt_entry.get("events") or 0)
265
+
266
+ if rt_entry:
267
+ rt_tok = int(rt_entry.get("tokens_saved") or 0)
268
+ rt_cost = float(rt_entry.get("cost_saved_usd") or 0.0)
269
+ rt_ev = int(rt_entry.get("events") or 0)
270
+ summary["total_tokens"] = int(summary.get("total_tokens") or 0) - 2 * rt_tok
271
+ summary["total_cost_usd"] = round(float(summary.get("total_cost_usd") or 0.0) - 2 * rt_cost, 4)
272
+ summary["total_events"] = max(0, int(summary.get("total_events") or 0) - rt_ev)
273
+
274
+ reread_by_cat = {}
275
+ if isinstance(counted, dict):
276
+ for k, v in (counted.get("by_category") or {}).items():
277
+ if isinstance(v, dict):
278
+ reread_by_cat[k] = (
279
+ int(v.get("reread_tokens") or 0),
280
+ float(v.get("reread_usd") or 0.0),
281
+ )
282
+
283
+ feature_net = {}
284
+ all_keys = list(by_cat.keys()) + [k for k in rt_by_feature if k not in by_cat]
285
+ for feat in all_keys:
286
+ entry = by_cat.get(feat) or {}
287
+ fw_tok = int(entry.get("tokens_saved") or 0)
288
+ fw_usd = float(entry.get("cost_saved_usd") or 0.0)
289
+ rr_tok, rr_usd = reread_by_cat.get(feat, (0, 0.0))
290
+ rt_tok, rt_usd = rt_by_feature.get(feat, (0, 0.0))
291
+ if rt_tok and feat in by_cat:
292
+ entry["tokens_saved"] = fw_tok - rt_tok
293
+ entry["cost_saved_usd"] = round(fw_usd - rt_usd, 4)
294
+ net_tok = fw_tok + rr_tok - rt_tok
295
+ net_usd = round(fw_usd + rr_usd - rt_usd, 4)
296
+ feature_net[feat] = {
297
+ "label": labels.get(feat, feat.replace("_", " ").title()),
298
+ "first_write_tokens": fw_tok,
299
+ "repeat_read_tokens": rr_tok,
300
+ "round_trip_tokens": rt_tok,
301
+ "net_tokens": net_tok,
302
+ "first_write_usd": round(fw_usd, 4),
303
+ "repeat_read_usd": round(rr_usd, 4),
304
+ "round_trip_usd": round(rt_usd, 4),
305
+ "net_usd": net_usd,
306
+ }
307
+ summary["feature_net"] = feature_net
308
+ summary["round_trip_unknown"] = rt_unknown
309
+ summary["expand_round_trip_tokens"] = sum(v[0] for v in rt_by_feature.values())
310
+ summary["expand_round_trip_usd"] = round(sum(v[1] for v in rt_by_feature.values()), 4)
311
+ return summary
312
+
313
+
314
+ def plan_limits_summary(facade, conn, days, summary=None, counted=None, default_model=None):
315
+ """Compute plan-limits share in limit units using limit_units() for both sides.
316
+
317
+ Denominator: all top-level requests in the window in limit_units().
318
+ Numerator: measured savings (first write + repeat reads - re-expand - round trip)
319
+ converted through the same limit_units() function.
320
+ Keeps old fresh+output denominator in diagnostic_fresh_plus_output_tokens.
321
+ """
322
+ cutoff = (facade.datetime.now() - facade.timedelta(days=days)).date().isoformat()
323
+ today = facade.datetime.now().date().isoformat()
324
+ columns = {row[1] for row in conn.execute("PRAGMA table_info(session_log)")}
325
+ parent = "parent_daily_usage_json" if "parent_daily_usage_json" in columns else "daily_usage_json"
326
+ side = "COALESCE(is_sidechain,0)=0" if "is_sidechain" in columns else "1=1"
327
+
328
+ denom_units = 0.0
329
+ unpriced_tokens = 0
330
+ diag_fresh_out = 0
331
+ by_class = {"input": 0.0, "cache_write_5m": 0.0, "cache_write_1h": 0.0,
332
+ "cache_read": 0.0, "output": 0.0}
333
+ model_weights = {}
334
+
335
+ for (raw,) in conn.execute(f"SELECT {parent} FROM session_log WHERE {side}"):
336
+ try:
337
+ daily = json.loads(raw or "{}")
338
+ except (TypeError, ValueError):
339
+ continue
340
+ if not isinstance(daily, dict):
341
+ continue
342
+ for day, models in daily.items():
343
+ if not (isinstance(day, str) and cutoff <= day <= today and isinstance(models, dict)):
344
+ continue
345
+ for model, usage in models.items():
346
+ if not isinstance(usage, dict):
347
+ continue
348
+ diag_fresh_out += int(usage.get("fresh_input") or 0) + int(usage.get("output") or 0)
349
+ lu = limit_units({"model": model, **usage}, facade=facade)
350
+ if lu["priced"]:
351
+ denom_units += lu["units"]
352
+ model_weights[model] = model_weights.get(model, 0.0) + lu["units"]
353
+ for k in by_class:
354
+ by_class[k] += lu["by_class"][k]
355
+ else:
356
+ unpriced_tokens += lu["unpriced_tokens"]
357
+
358
+ # Pick dominant priced model in the window for converting aggregate saved tokens
359
+ ref_model = default_model
360
+ if not ref_model and model_weights:
361
+ ref_model = max(model_weights.items(), key=lambda kv: kv[1])[0]
362
+
363
+ saved_units = 0.0
364
+ if summary and ref_model:
365
+ fw_tok = int(summary.get("total_tokens") or 0)
366
+ rr_tok = int((counted or {}).get("reread_tokens") or 0)
367
+ # First-write removals save cache_write (5m conservative) or input;
368
+ # repeat reads save cache_read. Both go through limit_units().
369
+ saved_row = {
370
+ "model": ref_model,
371
+ "input": 0,
372
+ "cache_write_5m": fw_tok,
373
+ "cache_read": rr_tok,
374
+ "output": 0,
375
+ }
376
+ saved_lu = limit_units(saved_row, facade=facade)
377
+ if saved_lu["priced"]:
378
+ saved_units = saved_lu["units"]
379
+
380
+ # Earlier compaction is signed and already net of its own request cost.
381
+ # Convert each priced event with its own model rather than the window model.
382
+ unpriced_estimate_events = 0
383
+ if summary and summary.get("autocompact_window_estimated"):
384
+ table = facade._counted_table(conn, "savings_events")
385
+ for (detail,) in conn.execute(
386
+ f"SELECT detail FROM {table} WHERE event_type=? AND timestamp >= ?",
387
+ ("autocompact_window_estimated", cutoff),
388
+ ):
389
+ try:
390
+ units = float(json.loads(detail)["net_limit_units"])
391
+ if not math.isfinite(units):
392
+ raise ValueError("invalid units")
393
+ except (TypeError, ValueError, AttributeError):
394
+ unpriced_estimate_events += 1
395
+ continue
396
+ except KeyError:
397
+ unpriced_estimate_events += 1
398
+ continue
399
+ saved_units += units
400
+
401
+ share_pct = round(saved_units / denom_units * 100.0, 4) if denom_units > 0 else None
402
+ from . import cold_guard
403
+ guard = (summary or {}).get(cold_guard.ESTIMATE_KEY)
404
+ if guard is None:
405
+ guard = cold_guard.estimate(facade, days=days)
406
+ estimated = {}
407
+ units = guard.get("limit_units_saved")
408
+ if guard.get("events") and units is not None:
409
+ estimated[cold_guard.ESTIMATE_KEY] = {
410
+ "label": guard["label"], "saved_units": units,
411
+ "share_pct": round(units / denom_units * 100.0, 4) if denom_units > 0 else None,
412
+ }
413
+ return {
414
+ "label": LIMIT_UNITS_LABEL,
415
+ "share_pct": share_pct,
416
+ "saved_units": round(saved_units, 2),
417
+ "denominator_units": round(denom_units, 2),
418
+ "unpriced_tokens": unpriced_tokens,
419
+ "unpriced_estimate_events": unpriced_estimate_events,
420
+ "diagnostic_fresh_plus_output_tokens": diag_fresh_out,
421
+ "by_class": {k: round(v, 2) for k, v in by_class.items()},
422
+ "reference_model": ref_model,
423
+ "estimated_by_feature": estimated,
424
+ }
425
+
426
+
427
+ def dedupe_transcript_rows(rows, cutoff_iso=None, end_iso=None):
428
+ """Deduplicate assistant rows by message id and tool results by tool_use_id
429
+ across files, filtering strictly by each row's own timestamp (R6).
430
+ """
431
+ seen_msg_ids = set()
432
+ seen_tool_ids = set()
433
+ kept = []
434
+ for row in rows:
435
+ if not isinstance(row, dict):
436
+ continue
437
+ ts = row.get("timestamp") or ""
438
+ if cutoff_iso and (not ts or ts < cutoff_iso):
439
+ continue
440
+ if end_iso and ts and ts > end_iso:
441
+ continue
442
+ msg = row.get("message") if isinstance(row.get("message"), dict) else {}
443
+ role = msg.get("role") or row.get("type") or ""
444
+ if role == "assistant" or msg.get("id") or row.get("requestId"):
445
+ mid = msg.get("id") or row.get("requestId")
446
+ if mid:
447
+ if mid in seen_msg_ids:
448
+ continue
449
+ seen_msg_ids.add(mid)
450
+ kept.append(row)
451
+ continue
452
+ # Tool result rows: dedupe by tool_use_id across files
453
+ content = msg.get("content") if isinstance(msg.get("content"), list) else []
454
+ tids = [b.get("tool_use_id") for b in content
455
+ if isinstance(b, dict) and b.get("type") == "tool_result" and b.get("tool_use_id")]
456
+ if not tids and row.get("tool_use_id"):
457
+ tids = [row["tool_use_id"]]
458
+ if tids:
459
+ if all(t in seen_tool_ids for t in tids):
460
+ continue
461
+ seen_tool_ids.update(tids)
462
+ kept.append(row)
463
+ return kept
@@ -0,0 +1,192 @@
1
+ """Local self-adaptation: pause or tighten compressors with high local unfold rates (SPEC-local-adapt Part A).
2
+
3
+ Evaluated at SessionStart from the local ledger (savings_events / compression_events).
4
+ Hot-path PostToolUse hooks read at most ONE small JSON file (<4 KB) and fail open to defaults
5
+ on missing, oversize, or corrupt files. Never enables default-off features and never loosens.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from datetime import datetime, timedelta, timezone
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ MAX_STATE_BYTES = 4096
16
+ MIN_REPLACEMENTS = 20
17
+ TIGHTEN_RATE = 0.20
18
+ PAUSE_RATE = 0.30
19
+ PAUSE_DAYS = 14
20
+
21
+
22
+ def _now_utc(now: datetime | None = None) -> datetime:
23
+ if now is None:
24
+ return datetime.now(timezone.utc)
25
+ return now if now.tzinfo else now.replace(tzinfo=timezone.utc)
26
+
27
+
28
+ def feature_health(conn, feature: str, days: int = 14, now: datetime | None = None) -> dict[str, Any]:
29
+ """Return replacements, re-expands attributed to *feature*, and unfold_rate."""
30
+ cur_now = _now_utc(now)
31
+ cutoff = (cur_now - timedelta(days=days)).isoformat()
32
+ replacements = 0
33
+ reexpands = 0
34
+ try:
35
+ r1 = conn.execute(
36
+ "SELECT COUNT(*) FROM compression_events WHERE feature = ? AND timestamp >= ? "
37
+ "AND (tier IS NULL OR tier = 'measured')",
38
+ (feature, cutoff),
39
+ ).fetchone()
40
+ replacements += int(r1[0] or 0) if r1 else 0
41
+ except Exception:
42
+ pass
43
+ try:
44
+ r2 = conn.execute(
45
+ "SELECT COUNT(*) FROM savings_events WHERE event_type = ? AND timestamp >= ?",
46
+ (feature, cutoff),
47
+ ).fetchone()
48
+ replacements += int(r2[0] or 0) if r2 else 0
49
+ except Exception:
50
+ pass
51
+ try:
52
+ r3 = conn.execute(
53
+ "SELECT COUNT(*) FROM savings_events WHERE event_type = 'tool_archive_reexpand' "
54
+ "AND timestamp >= ? AND (detail LIKE ? OR detail LIKE ?)",
55
+ (cutoff, f"%({feature})%", f"% {feature} %"),
56
+ ).fetchone()
57
+ reexpands = int(r3[0] or 0) if r3 else 0
58
+ except Exception:
59
+ pass
60
+ rate = (reexpands / replacements) if replacements > 0 else 0.0
61
+ return {
62
+ "feature": feature,
63
+ "days": days,
64
+ "replacements": replacements,
65
+ "reexpands": reexpands,
66
+ "unfold_rate": round(rate, 4),
67
+ }
68
+
69
+
70
+ def _load_state(state_path: Path) -> dict[str, Any]:
71
+ try:
72
+ if not state_path.is_file() or state_path.stat().st_size > MAX_STATE_BYTES:
73
+ return {"features": {}}
74
+ data = json.loads(state_path.read_text(encoding="utf-8"))
75
+ if isinstance(data, dict) and isinstance(data.get("features"), dict):
76
+ return data
77
+ except Exception:
78
+ pass
79
+ return {"features": {}}
80
+
81
+
82
+ def evaluate_session_start(
83
+ conn,
84
+ state_path: Path,
85
+ features: tuple[str, ...] | list[str],
86
+ *,
87
+ plugin_version: str = "0.0.0",
88
+ days: int = 14,
89
+ now: datetime | None = None,
90
+ ) -> dict[str, Any]:
91
+ """Evaluate local unfold rates at SessionStart and write one small (<4 KB) JSON state file."""
92
+ cur_now = _now_utc(now)
93
+ state = _load_state(state_path)
94
+ fmap: dict[str, dict[str, Any]] = state.setdefault("features", {})
95
+
96
+ for feat in features:
97
+ entry = dict(fmap.get(feat) or {})
98
+ pause_count = int(entry.get("pause_count") or 0)
99
+ paused_until_ver = entry.get("paused_until_next_version")
100
+ # Already permanently paused until next plugin version?
101
+ if paused_until_ver and paused_until_ver == plugin_version:
102
+ entry["paused"] = True
103
+ fmap[feat] = entry
104
+ continue
105
+ elif paused_until_ver and paused_until_ver != plugin_version:
106
+ # New plugin version arrived: resume at tightened step
107
+ entry["paused"] = False
108
+ entry["paused_until"] = None
109
+ entry["paused_until_next_version"] = None
110
+ entry["min_size_mult"] = max(2, int(entry.get("min_size_mult") or 1))
111
+ entry["keep_lines_mult"] = max(2, int(entry.get("keep_lines_mult") or 1))
112
+
113
+ # Check active 14-day pause expiry
114
+ paused_until_s = entry.get("paused_until")
115
+ if entry.get("paused") and paused_until_s:
116
+ try:
117
+ pu = datetime.fromisoformat(paused_until_s)
118
+ if pu.tzinfo is None:
119
+ pu = pu.replace(tzinfo=timezone.utc)
120
+ if cur_now < pu:
121
+ fmap[feat] = entry
122
+ continue
123
+ # Pause expired -> resume at tightened step (never loosens)
124
+ entry["paused"] = False
125
+ entry["paused_until"] = None
126
+ entry["min_size_mult"] = max(2, int(entry.get("min_size_mult") or 1))
127
+ entry["keep_lines_mult"] = max(2, int(entry.get("keep_lines_mult") or 1))
128
+ except ValueError:
129
+ entry["paused"] = False
130
+
131
+ h = feature_health(conn, feat, days=days, now=cur_now)
132
+ entry["replacements"] = h["replacements"]
133
+ entry["reexpands"] = h["reexpands"]
134
+ entry["unfold_rate"] = h["unfold_rate"]
135
+
136
+ if h["replacements"] >= MIN_REPLACEMENTS:
137
+ if h["unfold_rate"] >= PAUSE_RATE:
138
+ pause_count += 1
139
+ entry["pause_count"] = pause_count
140
+ entry["paused"] = True
141
+ if pause_count >= 2:
142
+ entry["paused_until"] = None
143
+ entry["paused_until_next_version"] = plugin_version
144
+ else:
145
+ entry["paused_until"] = (cur_now + timedelta(days=PAUSE_DAYS)).isoformat()
146
+ elif h["unfold_rate"] >= TIGHTEN_RATE:
147
+ entry["min_size_mult"] = max(2, int(entry.get("min_size_mult") or 1))
148
+ entry["keep_lines_mult"] = max(2, int(entry.get("keep_lines_mult") or 1))
149
+
150
+ fmap[feat] = entry
151
+
152
+ state["evaluated_at"] = cur_now.isoformat()
153
+ state["plugin_version"] = plugin_version
154
+ raw = json.dumps(state, separators=(",", ":"), sort_keys=True)
155
+ if len(raw.encode("utf-8")) <= MAX_STATE_BYTES:
156
+ state_path.parent.mkdir(parents=True, exist_ok=True)
157
+ tmp = state_path.with_suffix(".tmp")
158
+ tmp.write_text(raw, encoding="utf-8")
159
+ os.replace(tmp, state_path)
160
+ return state
161
+
162
+
163
+ def read_hot_path_state(state_path: Path, feature: str) -> dict[str, Any]:
164
+ """Hot-path reader for PostToolUse hooks: env override > single <4 KB JSON > defaults."""
165
+ env_key = "TOKEN_OPTIMIZER_" + feature.upper()
166
+ override = os.environ.get(env_key, "").strip()
167
+ if override == "1":
168
+ return {"paused": False, "min_size_mult": 1, "keep_lines_mult": 1, "override": "on"}
169
+ if override == "0":
170
+ return {"paused": True, "min_size_mult": 1, "keep_lines_mult": 1, "override": "off"}
171
+ state = _load_state(state_path)
172
+ entry = state.get("features", {}).get(feature)
173
+ if not isinstance(entry, dict):
174
+ return {"paused": False, "min_size_mult": 1, "keep_lines_mult": 1, "override": None}
175
+ return {
176
+ "paused": bool(entry.get("paused", False)),
177
+ "min_size_mult": max(1, int(entry.get("min_size_mult") or 1)),
178
+ "keep_lines_mult": max(1, int(entry.get("keep_lines_mult") or 1)),
179
+ "override": None,
180
+ }
181
+
182
+
183
+ def paused_summary(state_path: Path) -> list[str]:
184
+ """Human-readable lines for savings report, dashboard, and `measure.py features`."""
185
+ state = _load_state(state_path)
186
+ lines: list[str] = []
187
+ for feat, entry in sorted(state.get("features", {}).items()):
188
+ if isinstance(entry, dict) and entry.get("paused"):
189
+ reexp = int(entry.get("reexpands") or 0)
190
+ repl = int(entry.get("replacements") or 0)
191
+ lines.append(f"paused here: {feat}, unfolded {reexp} of {repl}")
192
+ return lines