@alexgreensh/token-optimizer 5.13.69 → 5.13.71

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 (148) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/token-optimizer/assets/dashboard.html +729 -767
  11. package/skills/token-optimizer/assets/savings_story.js +765 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  15. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  16. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  18. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  19. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  20. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  21. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  23. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  24. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  25. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  26. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  28. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  29. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +66 -0
  30. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  31. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_cap.py +30 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  36. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  37. package/skills/token-optimizer/scripts/_measure/coverage_report.py +295 -0
  38. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  39. package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -151
  40. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  41. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  42. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  43. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  44. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  46. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  47. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  48. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  50. package/skills/token-optimizer/scripts/_measure/holdout_report.py +129 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -0
  54. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  55. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  56. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  57. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  58. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  59. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  60. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  61. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  62. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  63. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  64. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  65. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  66. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  67. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +174 -0
  68. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  69. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  70. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  71. package/skills/token-optimizer/scripts/_measure/savings.py +439 -864
  72. package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
  73. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  74. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  75. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  76. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  77. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  78. package/skills/token-optimizer/scripts/_measure/sessions.py +103 -196
  79. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  80. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  81. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  82. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  83. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  84. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  85. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  86. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  91. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  92. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  93. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  94. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  95. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  96. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  97. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  98. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  99. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  100. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  101. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  102. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  103. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  104. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  105. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  106. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  107. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  108. package/skills/token-optimizer/scripts/codemap.py +274 -0
  109. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  110. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  111. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  112. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  113. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  114. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  115. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  116. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  117. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  118. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  119. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  120. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  121. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  122. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  123. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  124. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  125. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  126. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  127. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  128. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  129. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  130. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  131. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  132. package/skills/token-optimizer/scripts/holdout.py +136 -0
  133. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  134. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  135. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  136. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  137. package/skills/token-optimizer/scripts/measure.py +34 -76
  138. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  139. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  140. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  141. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  142. package/skills/token-optimizer/scripts/session_store.py +49 -99
  143. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  144. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  145. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  146. package/skills/token-optimizer/scripts/statusline.js +144 -30
  147. package/skills/token-optimizer/scripts/structural.py +25 -0
  148. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -0,0 +1,629 @@
1
+ """Output that was never written is also never re-read (savings-truth U5).
2
+
3
+ A verbosity nudge changes how many output tokens the next replies carry. Those
4
+ replies stay in the conversation, so each later call until the next compaction
5
+ re-reads them from the cache. This module walks a transcript once and scores
6
+ that carry turn by turn, in the estimated tier only.
7
+
8
+ Two rules keep it honest:
9
+
10
+ * Signed. A reply that grew after the nudge is a negative reduction and is
11
+ carried as a debit, never clamped to zero.
12
+ * Net of a control. The before/after change of a nudged reply includes what
13
+ would have happened anyway (replies vary a lot, and a single reply compared
14
+ with a long running mean is noisy). Callers pass ``control_per_request``, the
15
+ same change measured at user-prompt boundaries of sessions that were never
16
+ nudged, and only the difference is credited.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ import hashlib
22
+ import json
23
+ import os
24
+ import tempfile
25
+ from pathlib import Path
26
+ from bisect import bisect_left, bisect_right
27
+
28
+ from . import _compat, transcript_stream
29
+
30
+ # A control needs this many un-nudged boundaries before the pool is credited.
31
+ MIN_CONTROL_SAMPLES = 30
32
+
33
+
34
+ def signed_delta(baseline, outputs):
35
+ """Baseline per request times requests, minus what was produced. Signed."""
36
+ return int(baseline * len(outputs) - sum(outputs))
37
+
38
+
39
+ def _dt(raw):
40
+ facade = _compat.facade()
41
+ try:
42
+ return facade.datetime.strptime(str(raw)[:19], "%Y-%m-%dT%H:%M:%S")
43
+ except (ValueError, TypeError):
44
+ return None
45
+
46
+
47
+ def _is_user_prompt(entry):
48
+ """A real prompt typed by the user, not a tool result or injected meta line."""
49
+ if entry.get("isSidechain") or entry.get("isMeta"):
50
+ return False
51
+ msg = entry.get("message")
52
+ content = msg.get("content") if isinstance(msg, dict) else None
53
+ if isinstance(content, str):
54
+ text = content.lstrip()
55
+ return bool(text) and not text.startswith(("<command-", "<local-command"))
56
+ if isinstance(content, list):
57
+ kinds = {b.get("type") for b in content if isinstance(b, dict)}
58
+ return "text" in kinds and "tool_result" not in kinds
59
+ return False
60
+
61
+
62
+ def walk_requests(path):
63
+ """One pass over a transcript.
64
+
65
+ Returns a dict with:
66
+ ``outputs``: [(key, positive_lines_before, output, utc time)] in the order and with
67
+ the request folding of ``_transcript_request_outputs`` (the list a nudge
68
+ indexes with ``pre_turns``), sidechain lines included;
69
+ ``turns``: parent API calls [(utc datetime, model, prompt tokens, key)]
70
+ sorted by time, deduped per request, as the counted walker sees them;
71
+ ``compacts``: sorted compaction times;
72
+ ``prompts``: [(outputs seen before the prompt, last parent prompt tokens)]
73
+ for each real user prompt;
74
+ ``lines``: [(request key, output)] per output-bearing assistant line,
75
+ unfolded: the unit nudges recorded before ``unit=req``.
76
+ Never raises; an unreadable file gives empty lists.
77
+ """
78
+ facade = _compat.facade()
79
+ out = {"outputs": [], "turns": [], "compacts": [], "prompts": [], "lines": []}
80
+ by_key, turn_at, seen_lines = {}, {}, 0
81
+ last_prompt_tokens = 0
82
+ try:
83
+ from .transcript_stream import open_transcript
84
+ handle = open_transcript(path)
85
+ except OSError:
86
+ return out
87
+ with handle as lines:
88
+ for line in lines:
89
+ if '"assistant"' not in line and '"user"' not in line and "compact_boundary" not in line:
90
+ continue
91
+ try:
92
+ entry = facade.json.loads(line)
93
+ except ValueError:
94
+ continue
95
+ if not isinstance(entry, dict):
96
+ continue
97
+ kind = entry.get("type")
98
+ if kind == "system" and entry.get("subtype") == "compact_boundary":
99
+ when = _dt(entry.get("timestamp"))
100
+ if when is not None:
101
+ out["compacts"].append(when)
102
+ continue
103
+ if kind == "user":
104
+ if _is_user_prompt(entry):
105
+ out["prompts"].append((len(out["outputs"]), last_prompt_tokens))
106
+ continue
107
+ if kind != "assistant":
108
+ continue
109
+ msg = entry.get("message")
110
+ if not isinstance(msg, dict):
111
+ continue
112
+ usage = msg.get("usage") if isinstance(msg.get("usage"), dict) else None
113
+ if usage is None:
114
+ continue
115
+ key = facade._usage_request_key(entry, msg)
116
+ produced = facade._safe_int(usage.get("output_tokens", 0))
117
+ if produced > 0:
118
+ okey = key if key is not None else f"__noreq__{len(out['outputs'])}"
119
+ slot = by_key.get(okey)
120
+ if slot is None:
121
+ by_key[okey] = len(out["outputs"])
122
+ out["outputs"].append([okey, seen_lines, produced, _dt(entry.get("timestamp"))])
123
+ else:
124
+ out["outputs"][slot][2] = max(out["outputs"][slot][2], produced)
125
+ out["lines"].append((okey, produced))
126
+ seen_lines += 1
127
+ when = _dt(entry.get("timestamp"))
128
+ if entry.get("isSidechain") or when is None:
129
+ continue
130
+ prompt = facade._context_token_count(usage)
131
+ model = msg.get("model") if isinstance(msg.get("model"), str) else None
132
+ if key is not None and key in turn_at:
133
+ index = turn_at[key]
134
+ old = out["turns"][index]
135
+ out["turns"][index] = (old[0], old[1] or model, max(old[2], prompt), key)
136
+ else:
137
+ if key is not None:
138
+ turn_at[key] = len(out["turns"])
139
+ out["turns"].append((when, model, prompt, key))
140
+ last_prompt_tokens = max(prompt, 0)
141
+ out["outputs"] = [tuple(row) for row in out["outputs"]]
142
+ out["turns"].sort(key=lambda t: t[0])
143
+ out["compacts"].sort()
144
+ return out
145
+
146
+
147
+ def cached_walk(path, cache_dir):
148
+ """Reuse a transcript walk only while its file identity is unchanged."""
149
+ facade = _compat.facade()
150
+ path, cache_dir = Path(path), Path(cache_dir)
151
+ try:
152
+ stat = path.stat()
153
+ identity = [stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns]
154
+ name = hashlib.sha256(os.fsencode(str(path.resolve()))).hexdigest() + ".json"
155
+ target = cache_dir / name
156
+ try:
157
+ saved = json.loads(target.read_text(encoding="utf-8"))
158
+ if saved["version"] == 1 and saved["identity"] == identity and not transcript_stream.needs_resume(path):
159
+ walk = saved["walk"]
160
+ walk["outputs"] = [(r[0], r[1], r[2], facade.datetime.fromisoformat(r[3]) if r[3] else None) for r in walk["outputs"]]
161
+ walk["turns"] = [(facade.datetime.fromisoformat(r[0]), *r[1:]) for r in walk["turns"]]
162
+ walk["compacts"] = [facade.datetime.fromisoformat(t) for t in walk["compacts"]]
163
+ walk["prompts"] = [tuple(r) for r in walk["prompts"]]
164
+ walk["lines"] = [tuple(r) for r in walk["lines"]]
165
+ return walk
166
+ except (OSError, ValueError, KeyError, TypeError, IndexError):
167
+ pass
168
+ walk = walk_requests(path)
169
+ after = path.stat()
170
+ if identity == [after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns] and not transcript_stream.needs_resume(path):
171
+ cache_dir.mkdir(parents=True, exist_ok=True)
172
+ with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=cache_dir, delete=False) as handle:
173
+ json.dump({"version": 1, "identity": identity, "walk": walk}, handle,
174
+ default=lambda value: value.isoformat())
175
+ name = handle.name
176
+ os.replace(name, target)
177
+ return walk
178
+ except OSError:
179
+ return walk_requests(path)
180
+
181
+
182
+ def post_window(walk, pre_turns, post_turns):
183
+ """The replies a ``unit=req`` nudge measured, or None when the file no
184
+ longer holds that many (a rewritten or truncated transcript)."""
185
+ chosen = walk["outputs"][pre_turns:pre_turns + post_turns]
186
+ return chosen if len(chosen) == post_turns and post_turns > 0 else None
187
+
188
+
189
+ def legacy_line_window(walk, pre_turns, post_turns, pre_avg, booked):
190
+ """Window of a nudge recorded before ``unit=req``.
191
+
192
+ Those nudges counted output-bearing transcript LINES, not requests, so a
193
+ request streamed over three lines counted three times. The line window is
194
+ trusted only when it reproduces the booked amount and the recorded
195
+ baseline exactly; it is then mapped back to whole requests. Returns
196
+ (request rows, request-unit baseline) or None."""
197
+ lines = walk["lines"]
198
+ window = lines[pre_turns:pre_turns + post_turns]
199
+ if pre_turns <= 0 or len(window) != post_turns or post_turns <= 0:
200
+ return None
201
+ outs = [o for _k, o in window]
202
+ if round(sum(o for _k, o in lines[:pre_turns]) / pre_turns) != pre_avg:
203
+ return None
204
+ if max(0, int((pre_avg - sum(outs) / len(outs)) * len(outs))) != booked:
205
+ return None
206
+ keys = list(dict.fromkeys(k for k, _o in window))
207
+ position = {row[0]: i for i, row in enumerate(walk["outputs"])}
208
+ if any(k not in position for k in keys):
209
+ return None
210
+ first = position[keys[0]]
211
+ rows = [walk["outputs"][position[k]] for k in keys]
212
+ if first <= 0:
213
+ return None
214
+ return rows, round(sum(r[2] for r in walk["outputs"][:first]) / first)
215
+
216
+
217
+ def score_rereads(walk, post_rows, reduction_per_request, rate_for_turn):
218
+ """Integrate signed reductions over the later parent calls that re-read them.
219
+
220
+ Each post-nudge reply of ``reduction_per_request[i]`` fewer tokens is absent
221
+ from every parent call after the one that produced it, up to the first
222
+ compaction after that call. Calls are found by request key, so two calls in
223
+ the same second are never confused. Sidechain replies never reach the
224
+ parent context and carry nothing. Each call is priced at its own
225
+ cache-read rate; calls without a known rate keep their tokens unpriced.
226
+ """
227
+ turns, compacts = walk["turns"], walk["compacts"]
228
+ times = [t[0] for t in turns]
229
+ index_of = {t[3]: i for i, t in enumerate(turns) if t[3] is not None}
230
+ diff = [0] * (len(turns) + 1)
231
+ unmapped = 0
232
+ for row, reduction in zip(post_rows, reduction_per_request):
233
+ key = row[0]
234
+ at = index_of.get(key)
235
+ if at is None:
236
+ unmapped += 1
237
+ continue
238
+ nxt = bisect_right(compacts, times[at])
239
+ boundary = compacts[nxt] if nxt < len(compacts) else None
240
+ end = bisect_left(times, boundary) if boundary is not None else len(turns)
241
+ if end > at + 1:
242
+ diff[at + 1] += reduction
243
+ diff[end] -= reduction
244
+ carried = tokens = unpriced = turns_counted = 0
245
+ usd = 0.0
246
+ for i, turn in enumerate(turns):
247
+ carried += diff[i]
248
+ if not carried:
249
+ continue
250
+ turns_counted += 1
251
+ tokens += carried
252
+ rate = rate_for_turn(turn)
253
+ if isinstance(rate, (int, float)) and math.isfinite(rate) and rate >= 0:
254
+ usd += carried * rate / 1e6
255
+ else:
256
+ unpriced += abs(carried)
257
+ return {"tokens": tokens, "usd": usd, "unpriced_tokens": unpriced,
258
+ "turns_counted": turns_counted, "unmapped_requests": unmapped}
259
+
260
+
261
+ def boundary_changes(walk, min_pre=10):
262
+ """Un-nudged change at each user prompt: running mean of all earlier
263
+ replies minus the mean of the replies to that prompt, per request.
264
+
265
+ Returns [(pre_count, post_count, pre_mean, change_per_request,
266
+ context_tokens)], the same statistic a nudge books, for control use."""
267
+ rows = [r[2] for r in walk["outputs"]]
268
+ prompts = walk["prompts"]
269
+ result = []
270
+ prefix = [0]
271
+ for value in rows:
272
+ prefix.append(prefix[-1] + value)
273
+ for i, (pre, context) in enumerate(prompts):
274
+ nxt = prompts[i + 1][0] if i + 1 < len(prompts) else len(rows)
275
+ post = nxt - pre
276
+ if pre < min_pre or post <= 0:
277
+ continue
278
+ pre_mean = round(prefix[pre] / pre)
279
+ post_mean = (prefix[nxt] - prefix[pre]) / post
280
+ result.append((pre, post, pre_mean, pre_mean - post_mean, context))
281
+ return result
282
+
283
+
284
+ def match_controls(treated, controls, k=5):
285
+ """Nearest un-nudged boundaries for each nudge, with replacement.
286
+
287
+ ``treated`` and ``controls`` hold (pre_count, post_count, pre_mean,
288
+ change_per_request, context_tokens). Distance is on log scales of request
289
+ position, reply count, running mean and context size. Returns, per treated
290
+ item, the mean control change per request (None without candidates)."""
291
+ def point(row):
292
+ return tuple(math.log1p(max(0.0, float(v))) for v in (row[0], row[1], row[2], row[4]))
293
+ pts = [point(c) for c in controls]
294
+ out = []
295
+ for row in treated:
296
+ if not pts:
297
+ out.append(None)
298
+ continue
299
+ here = point(row)
300
+ dist = sorted((sum((a - b) ** 2 for a, b in zip(here, p)), i) for i, p in enumerate(pts))
301
+ nearest = [controls[i][3] for _d, i in dist[:k]]
302
+ out.append(sum(nearest) / len(nearest))
303
+ return out
304
+
305
+
306
+ def net_effect(treated, control_change):
307
+ """Per-event net reduction: post replies x (nudged change - control change)."""
308
+ total, used = 0.0, 0
309
+ per_event = []
310
+ for row, control in zip(treated, control_change):
311
+ if control is None:
312
+ per_event.append(None)
313
+ continue
314
+ value = row[1] * (row[3] - control)
315
+ per_event.append(value)
316
+ total += value
317
+ used += 1
318
+ return {"events": used, "net_tokens": total, "per_event": per_event}
319
+
320
+
321
+ def cluster_interval(groups, values, resamples=1000, seed=7):
322
+ """Mean per event with a 95% interval that resamples whole sessions."""
323
+ import random
324
+ by = {}
325
+ for group, value in zip(groups, values):
326
+ if value is not None:
327
+ by.setdefault(group, []).append(value)
328
+ flat = [v for vals in by.values() for v in vals]
329
+ if not flat:
330
+ return {"events": 0, "sessions": 0, "mean": None, "ci95": None}
331
+ keys, rnd, means = sorted(by), random.Random(seed), []
332
+ for _ in range(resamples):
333
+ draw = [v for key in (rnd.choice(keys) for _ in keys) for v in by[key]]
334
+ means.append(sum(draw) / len(draw))
335
+ means.sort()
336
+ return {"events": len(flat), "sessions": len(keys), "mean": sum(flat) / len(flat),
337
+ "ci95": [means[int(0.025 * resamples)], means[int(0.975 * resamples) - 1]]}
338
+
339
+
340
+ def _fields(detail):
341
+ import re
342
+ return dict(re.findall(r"(\w+)=(\S+)", detail or ""))
343
+
344
+
345
+ class StudyDeadline(Exception):
346
+ """The study ran out of its time budget; nothing is written."""
347
+
348
+
349
+ def verbosity_study(conn, start_utc, end_utc, tier_data, path_for, deadline=None, k=5, details=False, cache_dir=None):
350
+ """Nudged replies against matched un-nudged replies, and what both carry.
351
+
352
+ Treated: each ``verbosity_steer_measured`` event in the UTC window whose
353
+ post-nudge replies can be found again and reproduce the booked amount
354
+ exactly (events that cannot are counted, never guessed). Controls: user
355
+ prompt boundaries in sessions where Token Optimizer logged savings but never
356
+ nudged, so the absence of a nudge is real. Each nudge is compared with its
357
+ ``k`` nearest controls by position, reply count, running mean and context
358
+ size. Everything is signed; the caller decides what to credit.
359
+ Raises StudyDeadline when ``deadline`` (a monotonic time) passes.
360
+ """
361
+ facade = _compat.facade()
362
+ clock = facade.time.monotonic
363
+
364
+ def check():
365
+ if deadline is not None and clock() > deadline:
366
+ raise StudyDeadline()
367
+
368
+ walks = {}
369
+
370
+ def walk_for(uuid):
371
+ if uuid not in walks:
372
+ check()
373
+ path = path_for(uuid)
374
+ walks[uuid] = (cached_walk(path, cache_dir) if cache_dir else walk_requests(path)) if path else None
375
+ return walks[uuid]
376
+
377
+ def card(turn):
378
+ return facade._counted_exact_card(turn[1], tier_data, turn[2]) or {}
379
+
380
+ # Local-naive timestamps: prefilter two days early, then convert each one.
381
+ loose = (start_utc - facade.timedelta(days=2)).isoformat()
382
+ events = conn.execute(
383
+ "SELECT id, timestamp, session_uuid, tokens_saved, detail FROM savings_events "
384
+ "WHERE event_type='verbosity_steer_measured' AND timestamp >= ? ORDER BY timestamp",
385
+ (loose,)).fetchall()
386
+ status = {"events": 0, "verified": 0, "verified_line_unit": 0, "no_source": 0,
387
+ "no_transcript": 0, "not_reproducible": 0}
388
+ treated, meta = [], []
389
+ for _id, ts, uuid, booked, detail in events:
390
+ when = facade._counted_event_utc(ts)
391
+ if when is None or not (start_utc <= when < end_utc):
392
+ continue
393
+ status["events"] += 1
394
+ fields = _fields(detail)
395
+ source = conn.execute(
396
+ "SELECT timestamp, detail FROM savings_events WHERE event_type='verbosity_steer' "
397
+ "AND session_uuid=? AND timestamp=?", (uuid, fields.get("calibrates_ts"))).fetchone()
398
+ try:
399
+ src = _fields(source[1])
400
+ pre, post, pre_avg = int(src["pre_turns"]), int(fields["post_turns"]), int(fields["pre_avg_out"])
401
+ except (TypeError, KeyError, ValueError):
402
+ status["no_source"] += 1
403
+ continue
404
+ walk = walk_for(uuid)
405
+ if not walk or not walk["outputs"]:
406
+ status["no_transcript"] += 1
407
+ continue
408
+
409
+ if "unit=req" in (source[1] or ""):
410
+ rows = post_window(walk, pre, post)
411
+ outs = [r[2] for r in rows] if rows else []
412
+ if not rows or max(0, int((pre_avg - sum(outs) / len(outs)) * len(outs))) != int(booked or 0):
413
+ status["not_reproducible"] += 1
414
+ continue
415
+ base = pre_avg
416
+ status["verified"] += 1
417
+ else:
418
+ legacy = legacy_line_window(walk, pre, post, pre_avg, int(booked or 0))
419
+ if legacy is None:
420
+ status["not_reproducible"] += 1
421
+ continue
422
+ rows, base = legacy
423
+ status["verified_line_unit"] += 1
424
+ index_of = {t[3]: i for i, t in enumerate(walk["turns"])}
425
+ first = index_of.get(rows[0][0])
426
+ context = walk["turns"][first - 1][2] if first else 0
427
+ outs = [r[2] for r in rows]
428
+ position = next(i for i, r in enumerate(walk["outputs"]) if r[0] == rows[0][0])
429
+ treated.append((position, len(rows), base, base - sum(outs) / len(rows), context))
430
+ turn = walk["turns"][first] if first is not None else (None, None, 0, None)
431
+ meta.append((uuid, rows, base, int(booked or 0), card(turn).get("output")))
432
+
433
+ nudged = {r[0] for r in conn.execute(
434
+ "SELECT DISTINCT session_uuid FROM savings_events WHERE event_type LIKE 'verbosity_steer%'")}
435
+ logged = {r[0] for r in conn.execute(
436
+ "SELECT DISTINCT session_uuid FROM savings_events WHERE timestamp >= ? "
437
+ "UNION SELECT DISTINCT session_uuid FROM compression_events WHERE timestamp >= ?", (loose, loose))}
438
+ controls, control_sessions = [], 0
439
+ for uuid in sorted(u for u in logged if u and u not in nudged):
440
+ check()
441
+ path = path_for(uuid)
442
+ if not path:
443
+ continue
444
+ rows = boundary_changes(walk_requests(path))
445
+ if rows:
446
+ control_sessions += 1
447
+ controls.extend(rows)
448
+
449
+ control = match_controls(treated, controls, k=k) if len(controls) >= MIN_CONTROL_SAMPLES else [None] * len(treated)
450
+ groups = [m[0] for m in meta]
451
+ out_tok = {"booked": 0, "signed": 0, "net": 0.0}
452
+ out_usd = {"booked": 0.0, "signed": 0.0, "net": 0.0}
453
+ reread = {"signed": [0, 0.0, 0], "net": [0, 0.0, 0]}
454
+ unmapped = 0
455
+ net_events = []
456
+ rate = lambda turn: card(turn).get("cache_read") # noqa: E731
457
+ for row, (uuid, rows, pre_avg, booked, out_rate), ctrl in zip(treated, meta, control):
458
+ signed = signed_delta(pre_avg, [r[2] for r in rows])
459
+ priced = isinstance(out_rate, (int, float)) and out_rate >= 0
460
+ out_tok["booked"] += booked
461
+ out_tok["signed"] += signed
462
+ if priced:
463
+ out_usd["booked"] += booked * out_rate / 1e6
464
+ out_usd["signed"] += signed * out_rate / 1e6
465
+ plans = [("signed", [pre_avg - r[2] for r in rows])]
466
+ if ctrl is not None:
467
+ net = row[1] * (row[3] - ctrl)
468
+ net_events.append(net)
469
+ out_tok["net"] += net
470
+ if priced:
471
+ out_usd["net"] += net * out_rate / 1e6
472
+ plans.append(("net", [pre_avg - r[2] - ctrl for r in rows]))
473
+ else:
474
+ net_events.append(None)
475
+ for name, reductions in plans:
476
+ score = score_rereads(walks[uuid], rows, reductions, rate)
477
+ if name == "signed":
478
+ unmapped += score["unmapped_requests"]
479
+ reread[name][0] += score["tokens"]
480
+ reread[name][1] += score["usd"]
481
+ reread[name][2] += score["unpriced_tokens"]
482
+ result = {
483
+ "window_utc": [start_utc.isoformat(), end_utc.isoformat()],
484
+ "status": status, "treated": len(treated),
485
+ "control_sessions": control_sessions, "control_boundaries": len(controls),
486
+ "matched": sum(c is not None for c in control),
487
+ "output_tokens": {k2: round(v) for k2, v in out_tok.items()},
488
+ "output_usd": {k2: round(v, 6) for k2, v in out_usd.items()},
489
+ "reread_tokens": {k2: round(v[0]) for k2, v in reread.items()},
490
+ "reread_usd": {k2: round(v[1], 6) for k2, v in reread.items()},
491
+ "reread_unpriced_tokens": {k2: round(v[2]) for k2, v in reread.items()},
492
+ "replies_without_parent_call": unmapped,
493
+ "per_event": {
494
+ "booked": cluster_interval(groups, [m[3] for m in meta]),
495
+ "signed": cluster_interval(groups, [row[1] * row[3] for row in treated]),
496
+ "control": cluster_interval(groups, [row[1] * c if c is not None else None
497
+ for row, c in zip(treated, control)]),
498
+ "net": cluster_interval(groups, net_events),
499
+ },
500
+ }
501
+ if details:
502
+ result["details"] = {"treated": treated, "groups": groups, "controls": controls,
503
+ "control_change": control, "net_events": net_events}
504
+ return result
505
+
506
+
507
+ def credited(study):
508
+ """What the estimated tier may credit: the net-of-control reduction and its
509
+ rereads, never below zero, and nothing without a matched control."""
510
+ if not study or not study.get("matched"):
511
+ return {"tokens": 0, "usd": 0.0, "reread_tokens": 0, "reread_usd": 0.0, "basis": "not_measured"}
512
+ tokens = max(0, int(study["output_tokens"]["net"]))
513
+ usd = max(0.0, float(study["output_usd"]["net"]))
514
+ reread_tokens = max(0, int(study["reread_tokens"]["net"]))
515
+ reread_usd = max(0.0, float(study["reread_usd"]["net"]))
516
+ basis = "net_of_control" if (tokens or reread_tokens) else "no_reduction_net_of_control"
517
+ return {"tokens": tokens, "usd": usd, "reread_tokens": reread_tokens,
518
+ "reread_usd": reread_usd, "basis": basis}
519
+
520
+
521
+ STUDY_FILE = "verbosity-study.json"
522
+ STUDY_VERSION = 1
523
+ STUDY_DAYS = 30
524
+ STUDY_MAX_AGE_HOURS = 20
525
+ STUDY_STALE_DAYS = 7
526
+
527
+
528
+ def _study_path():
529
+ return _compat.facade().SNAPSHOT_DIR / STUDY_FILE
530
+
531
+
532
+ def load_study():
533
+ """The last stored study, or None when missing, unreadable or too old."""
534
+ facade = _compat.facade()
535
+ try:
536
+ data = facade.json.loads(_study_path().read_text(encoding="utf-8"))
537
+ if not isinstance(data, dict) or data.get("version") != STUDY_VERSION:
538
+ return None
539
+ made = facade.datetime.fromisoformat(data["computed_at_utc"])
540
+ age = facade.datetime.now(facade.timezone.utc).replace(tzinfo=None) - made
541
+ return data if age <= facade.timedelta(days=STUDY_STALE_DAYS) else None
542
+ except (OSError, ValueError, KeyError, TypeError):
543
+ return None
544
+
545
+
546
+ def refresh_study(conn, deadline=None, force=False, now_utc=None):
547
+ """Recompute the stored study when it is older than STUDY_MAX_AGE_HOURS.
548
+
549
+ Read-only on the database; writes one derived JSON file atomically. Runs
550
+ from user-run and detached collects only, never from a hook. Returns the
551
+ study, or None when it was fresh, timed out or failed."""
552
+ facade = _compat.facade()
553
+ try:
554
+ current = None if force else load_study()
555
+ now = now_utc or facade.datetime.now(facade.timezone.utc).replace(tzinfo=None)
556
+ if current and now - facade.datetime.fromisoformat(current["computed_at_utc"]) < facade.timedelta(hours=STUDY_MAX_AGE_HOURS):
557
+ return None
558
+ tier = facade.PRICING_TIERS.get(facade._load_pricing_tier(), facade.PRICING_TIERS["anthropic"])
559
+ study = verbosity_study(conn, now - facade.timedelta(days=STUDY_DAYS), now, tier,
560
+ lambda uuid: facade._counted_session_path(conn, uuid), deadline=deadline,
561
+ cache_dir=facade.SNAPSHOT_DIR / "verbosity-walk-cache")
562
+ study.update(version=STUDY_VERSION, computed_at_utc=now.isoformat(), days=STUDY_DAYS)
563
+ path = _study_path()
564
+ tmp = path.with_suffix(".tmp")
565
+ tmp.write_text(facade.json.dumps(study, indent=1), encoding="utf-8")
566
+ facade.os.replace(tmp, path)
567
+ return study
568
+ except StudyDeadline:
569
+ return None
570
+ except Exception:
571
+ return None
572
+
573
+
574
+ def summary_pool(booked_entry, study=None):
575
+ """Estimated-tier line for nudged replies, sized net of the control.
576
+
577
+ ``booked_entry`` is the relocated ``verbosity_steer_measured`` aggregate
578
+ (kept for reference, never credited). The credit is the study's
579
+ net-of-control reduction per matched event, output plus its rereads,
580
+ floored at zero, times this window's events. Without a study the line is
581
+ NOT MEASURED and credits nothing."""
582
+ entry = booked_entry or {}
583
+ events = int(entry.get("events", 0) or 0)
584
+ pool = {"events": events, "tokens_saved": 0, "cost_saved_usd": 0.0,
585
+ "booked_tokens": int(entry.get("tokens_saved", 0) or 0),
586
+ "booked_usd": round(float(entry.get("cost_saved_usd", 0.0) or 0.0), 4),
587
+ "output_tokens": 0, "reread_tokens": 0, "reread_usd": 0.0,
588
+ "basis": "not_measured", "tier": "estimated"}
589
+ if study is None:
590
+ study = load_study()
591
+ if not study or not study.get("matched"):
592
+ return pool
593
+ matched = int(study["matched"])
594
+ net = study["per_event"]["net"]
595
+ pool.update(
596
+ basis="net_of_control", study_window_utc=study.get("window_utc"),
597
+ study_events=matched, control_boundaries=int(study.get("control_boundaries", 0)),
598
+ net_per_event_tokens=net.get("mean"), net_per_event_ci95=net.get("ci95"),
599
+ booked_per_event_tokens=study["per_event"]["booked"].get("mean"),
600
+ control_per_event_tokens=study["per_event"]["control"].get("mean"))
601
+ per = lambda value: max(0.0, float(value)) / matched # noqa: E731
602
+ out_tok = per(study["output_tokens"]["net"]) * events
603
+ out_usd = per(study["output_usd"]["net"]) * events
604
+ rr_tok = per(study["reread_tokens"]["net"]) * events
605
+ rr_usd = per(study["reread_usd"]["net"]) * events
606
+ pool.update(output_tokens=int(out_tok), reread_tokens=int(rr_tok), reread_usd=round(rr_usd, 4),
607
+ tokens_saved=int(out_tok + rr_tok), cost_saved_usd=round(out_usd + rr_usd, 4))
608
+ if not pool["tokens_saved"]:
609
+ pool["basis"] = "no_reduction_net_of_control"
610
+ return pool
611
+
612
+
613
+ def cli_line(pool, amount_text=None):
614
+ """One CLI line for the pool, or "" when there were no nudges."""
615
+ pool = pool or {}
616
+ if not pool.get("events"):
617
+ return ""
618
+ if pool.get("basis") == "not_measured":
619
+ return (f" Concise output nudges: NOT MEASURED ({pool['events']:,} calibrated nudges; "
620
+ "no un-nudged control yet, so nothing is credited)")
621
+ net = pool.get("net_per_event_tokens") or 0.0
622
+ ci = pool.get("net_per_event_ci95") or [0.0, 0.0]
623
+ if pool.get("basis") == "no_reduction_net_of_control":
624
+ return (f" Concise output nudges: no reduction net of an un-nudged control "
625
+ f"({net:+,.0f} tokens per nudge, 95% interval {ci[0]:+,.0f} to {ci[1]:+,.0f}); $0 credited")
626
+ amount = amount_text or f"{pool['cost_saved_usd']:.2f}"
627
+ return (f" + est. concise output nudges: ~${amount} net of an un-nudged control, "
628
+ f"including {pool['reread_tokens']:,} re-read tokens "
629
+ f"({net:+,.0f} tokens per nudge, 95% interval {ci[0]:+,.0f} to {ci[1]:+,.0f}) [estimated]")