@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,777 @@
1
+ """Warn or ask before a large Claude Code session rewrites its cold cache."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import hashlib
6
+ import itertools
7
+ import json
8
+ import math
9
+ import os
10
+ import re
11
+ import signal
12
+ import sqlite3
13
+ import tempfile
14
+ import time
15
+ from contextlib import closing, contextmanager, nullcontext
16
+ from datetime import datetime, timedelta
17
+ from pathlib import Path
18
+
19
+
20
+ LABEL = "Cold-session guard"
21
+ ESTIMATE_KEY = "cold_guard_estimated"
22
+ MODES = ("off", "warn", "ask")
23
+ CHOICES = ("continue", "compact", "fresh", "unknown")
24
+ _PASS = {"kind": "pass"}
25
+ _MIN_CONTEXT = 300_000
26
+ _HOUR = 3600
27
+ _CHOICE_WINDOW = 600
28
+ _RETENTION = 14 * 86400
29
+ _CHECKPOINT_BUDGET = 5.0
30
+ _WARNING_BUDGET = 0.25
31
+ _OUTPUT_BUDGET = 0.10
32
+ _TAIL_BYTES = 1024 * 1024
33
+ _MARKER_NAME = re.compile(r"[0-9a-f]{64}\.json\Z")
34
+ _SESSION_ID = re.compile(r"[A-Za-z0-9_-]+\Z")
35
+ _MODEL_ID = re.compile(r"[A-Za-z0-9_.:@/-]{1,160}\Z")
36
+ _FINGERPRINT = re.compile(r"[0-9a-f]{32}:[0-9a-f]{64}\Z")
37
+ _WIN_WORKER = """
38
+ import json, sys
39
+ from contextlib import redirect_stdout, redirect_stderr
40
+ from io import StringIO
41
+ from pathlib import Path
42
+ sys.path.insert(0, sys.argv[1])
43
+ from _measure import cold_guard
44
+ with redirect_stdout(StringIO()), redirect_stderr(StringIO()):
45
+ import measure
46
+ path, session_id, checkpoint_dir = json.load(sys.stdin)
47
+ measure.CHECKPOINT_DIR = Path(checkpoint_dir)
48
+ saved = cold_guard._checkpoint_saved(measure, Path(path), session_id, float(sys.argv[2]))
49
+ print(json.dumps(saved))
50
+ """
51
+
52
+
53
+ class BudgetExceeded(BaseException):
54
+ """Interrupt a guard without exiting the runner or being swallowed by a checkpoint."""
55
+
56
+
57
+ @contextmanager
58
+ def deadline(seconds):
59
+ """Use the earlier alarm when nested inside the runner's shorter budget."""
60
+ if not hasattr(signal, "setitimer"):
61
+ # Windows bounds checkpoint capture in a child process.
62
+ yield
63
+ return
64
+ old_wait, old_interval = signal.getitimer(signal.ITIMER_REAL)
65
+ if 0 < old_wait <= seconds:
66
+ yield
67
+ return
68
+ old_handler = signal.getsignal(signal.SIGALRM)
69
+ started = time.monotonic()
70
+
71
+ def expired(_signum, _frame):
72
+ raise BudgetExceeded(seconds)
73
+
74
+ signal.signal(signal.SIGALRM, expired)
75
+ try:
76
+ signal.setitimer(signal.ITIMER_REAL, seconds)
77
+ yield
78
+ if time.monotonic() - started >= seconds:
79
+ raise BudgetExceeded(seconds)
80
+ finally:
81
+ signal.setitimer(signal.ITIMER_REAL, 0)
82
+ signal.signal(signal.SIGALRM, old_handler)
83
+ if old_wait:
84
+ signal.setitimer(
85
+ signal.ITIMER_REAL, max(1e-6, old_wait - (time.monotonic() - started)), old_interval,
86
+ )
87
+
88
+
89
+ def bounded_evaluate(facade, hook_input, now, seconds):
90
+ expires = time.monotonic() + seconds
91
+ with deadline(seconds):
92
+ return evaluate(facade, hook_input, now, expires)
93
+
94
+
95
+ def _checkpoint_in_worker(facade, path, session_id, seconds):
96
+ """Give only checkpoint capture a killable process on Windows."""
97
+ import subprocess
98
+ import sys
99
+
100
+ try:
101
+ child = subprocess.run(
102
+ [sys.executable, "-c", _WIN_WORKER, str(Path(__file__).resolve().parents[1]), str(seconds)],
103
+ input=json.dumps([str(path), session_id, str(facade.CHECKPOINT_DIR)]),
104
+ capture_output=True, text=True,
105
+ encoding="utf-8", timeout=seconds, check=True,
106
+ )
107
+ return json.loads(child.stdout) is True
108
+ except (subprocess.SubprocessError, OSError, ValueError):
109
+ return False
110
+
111
+
112
+ def _configured_mode(facade):
113
+ value = facade._read_config_flag("cold_guard_mode", "warn")
114
+ return value if value in MODES else "warn"
115
+
116
+
117
+ def _mode(facade):
118
+ value = os.environ.get("TOKEN_OPTIMIZER_COLD_GUARD")
119
+ return value if value in MODES else _configured_mode(facade)
120
+
121
+
122
+ def _marker_dir(facade):
123
+ return Path(facade.SNAPSHOT_DIR) / "cold-guard"
124
+
125
+
126
+ def _marker_path(directory, session_id):
127
+ return directory / (hashlib.sha256(session_id.encode("utf-8")).hexdigest() + ".json")
128
+
129
+
130
+ def _marker_paths(directory):
131
+ try:
132
+ with os.scandir(directory) as entries:
133
+ yield from (
134
+ directory / entry.name for entry in entries
135
+ if _MARKER_NAME.fullmatch(entry.name) and entry.is_file(follow_symlinks=False)
136
+ )
137
+ except OSError:
138
+ pass
139
+
140
+
141
+ def _read_marker(path):
142
+ with os.fdopen(os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)), encoding="utf-8") as stream:
143
+ data = json.load(stream)
144
+ if not isinstance(data, dict):
145
+ raise ValueError("invalid cold-guard marker")
146
+ return data
147
+
148
+
149
+ def _maybe_marker(path):
150
+ try:
151
+ return _read_marker(path)
152
+ except FileNotFoundError:
153
+ return {}
154
+
155
+
156
+ def _write_marker(path, state):
157
+ fd, temp = tempfile.mkstemp(prefix=".marker-", dir=path.parent)
158
+ try:
159
+ with os.fdopen(fd, "w", encoding="utf-8") as stream:
160
+ json.dump(state, stream, separators=(",", ":"))
161
+ stream.flush()
162
+ os.fsync(stream.fileno())
163
+ os.replace(temp, path)
164
+ if os.name == "posix":
165
+ dir_fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
166
+ try:
167
+ os.fsync(dir_fd)
168
+ finally:
169
+ os.close(dir_fd)
170
+ finally:
171
+ Path(temp).unlink(missing_ok=True)
172
+
173
+
174
+ def _marker_lock(facade, directory):
175
+ return facade.lease_lock(directory / ".markers.lease", acquire_timeout=0.025, reclaim_released=True)
176
+
177
+
178
+ def _prune(facade, directory, now):
179
+ cutoff = now - _RETENTION
180
+ stale = []
181
+ for path in _marker_paths(directory):
182
+ try:
183
+ if path.stat().st_mtime < cutoff:
184
+ stale.append(path)
185
+ except OSError:
186
+ continue
187
+ if len(stale) == 50:
188
+ break
189
+ if not stale:
190
+ return
191
+ with _marker_lock(facade, directory) as held:
192
+ if held:
193
+ for path in stale:
194
+ try:
195
+ if path.stat().st_mtime < cutoff:
196
+ path.unlink()
197
+ except OSError:
198
+ pass
199
+
200
+
201
+ def _project_id(directory):
202
+ return hashlib.sha256(directory.name.encode("utf-8")).hexdigest()
203
+
204
+
205
+ def _transcript(facade, hook_input, session_id):
206
+ path = facade._confine_transcript_path(hook_input.get("transcript_path"))
207
+ projects = (facade.CLAUDE_DIR / "projects").resolve()
208
+ if path and path.parent.parent == projects and path.name == f"{session_id}.jsonl":
209
+ return path
210
+ return None
211
+
212
+
213
+ def _price_card(facade, model, context):
214
+ tiers = facade.PRICING_TIERS
215
+ tier = tiers.get(facade._load_pricing_tier(), tiers["anthropic"])
216
+ return facade._counted_exact_card(model, tier, prompt_tokens=context) or {}
217
+
218
+
219
+ def _write_key(ttl):
220
+ return "cache_write_1h" if ttl == "1h" else "cache_write"
221
+
222
+
223
+ def _rate(card, key):
224
+ rate = card.get(key)
225
+ return rate if isinstance(rate, (int, float)) and math.isfinite(rate) and rate >= 0 else None
226
+
227
+
228
+ def texts(facade, context, model, idle, ttl):
229
+ minutes = int(idle // 60)
230
+ hours, minutes = divmod(minutes, 60)
231
+ size = f"{context / 1000:,.0f}K tokens at write price"
232
+ rate = _rate(_price_card(facade, model, context), _write_key(ttl))
233
+ if rate is not None:
234
+ size += f", about ${context * rate / 1_000_000:,.2f} at API rates"
235
+ cold = f"cache went cold (idle {hours}h {minutes}m)."
236
+ return {
237
+ "warn": (
238
+ f"Token Optimizer: {cold} This message re-reads {size}. "
239
+ "To be asked first next time: measure.py cold-guard set ask"
240
+ ),
241
+ "block": (
242
+ "Token Optimizer held this message. Nothing was sent and nothing is lost: your text is below.\n"
243
+ f"{cold.capitalize()} Sending re-reads {size}. A checkpoint is saved.\n"
244
+ " 1. Start fresh: type /clear, then send your message again. The checkpoint joins it. Cheapest.\n"
245
+ " 2. Compact: type /compact, then send again. Pays one full re-read now; later messages get cheaper.\n"
246
+ " 3. Continue: send the same message again. It goes through.\n"
247
+ "This will not stop you again for this pause. Turn off: measure.py cold-guard set warn"
248
+ ),
249
+ }
250
+
251
+
252
+ def _blocks(marker):
253
+ prior = marker.get("previous_blocks", [])
254
+ if isinstance(prior, list):
255
+ for block in prior:
256
+ if isinstance(block, dict) and isinstance(block.get("told_at"), (float, int)):
257
+ yield block
258
+ if marker.get("kind") == "block" and isinstance(marker.get("told_at"), (float, int)):
259
+ yield marker
260
+
261
+
262
+ def _recent_block(marker, now):
263
+ return any(0 <= now - block["told_at"] < _HOUR for block in _blocks(marker))
264
+
265
+
266
+ def _model_id(value):
267
+ return value if isinstance(value, str) and _MODEL_ID.fullmatch(value) else None
268
+
269
+
270
+ def _checkpoint_saved(facade, path, session_id, seconds):
271
+ try:
272
+ with deadline(seconds):
273
+ checkpoint = facade.compact_capture(transcript_path=str(path), session_id=session_id)
274
+ return bool(checkpoint and facade._checkpoint_has_restorable_body(checkpoint))
275
+ except (Exception, BudgetExceeded, facade._HookTimeout):
276
+ return False
277
+
278
+
279
+ def _prompt_fingerprint(prompt, salt):
280
+ digest = hashlib.blake2b(prompt.strip().encode("utf-8", errors="surrogatepass"),
281
+ key=bytes.fromhex(salt), digest_size=32)
282
+ return f"{salt}:{digest.hexdigest()}"
283
+
284
+
285
+ def _publish(facade, path, state):
286
+ """Recheck the decision while committing it so racing hooks hold only once."""
287
+ with _marker_lock(facade, path.parent) as held:
288
+ if not held:
289
+ return False
290
+ current = _maybe_marker(path)
291
+ now = state["told_at"]
292
+ told_at = current.get("told_at")
293
+ if current.get("gap_key") == state["gap_key"]:
294
+ return False
295
+ if isinstance(told_at, (float, int)) and told_at > now:
296
+ return False
297
+ if _recent_block(current, now):
298
+ state["kind"] = "warn"
299
+ state.pop("prompt_fingerprint", None)
300
+ history = [
301
+ {key: value for key, value in block.items() if key != "previous_blocks"}
302
+ for block in _blocks(current) if now - block["told_at"] < _RETENTION
303
+ ]
304
+ if history:
305
+ state["previous_blocks"] = history
306
+ _write_marker(path, state)
307
+ return True
308
+
309
+
310
+ def _bounded_last_usage(path):
311
+ """Inspect a fixed transcript suffix where the hook has no alarm."""
312
+ try:
313
+ with path.open("rb") as stream:
314
+ start = max(0, stream.seek(0, os.SEEK_END) - _TAIL_BYTES)
315
+ stream.seek(start)
316
+ lines = stream.read(_TAIL_BYTES).split(b"\n")
317
+ except OSError:
318
+ return None, None, None
319
+ for line in reversed(lines[bool(start):]):
320
+ try:
321
+ row = json.loads(line)
322
+ except (ValueError, RecursionError):
323
+ continue
324
+ if isinstance(row, dict) and not _delegated(row) and (found := _assistant_usage(row)):
325
+ return *found, row.get("timestamp") or row.get("ts")
326
+ return None, None, None
327
+
328
+
329
+ def evaluate(facade, hook_input, now, expires=None):
330
+ """Return a decision without emitting output or retaining any prompt text."""
331
+ directory = _marker_dir(facade)
332
+ _prune(facade, directory, now)
333
+ prompt = hook_input.get("prompt") or hook_input.get("current_prompt") or hook_input.get("user_prompt")
334
+ session_id = hook_input.get("session_id")
335
+ if (not isinstance(prompt, str) or not prompt.strip() or prompt.lstrip().startswith("/")
336
+ or "agent_id" in hook_input or "TOKEN_OPTIMIZER_KEEPWARM_PING" in os.environ
337
+ or not isinstance(session_id, str) or not _SESSION_ID.fullmatch(session_id)):
338
+ return dict(_PASS)
339
+ mode = _mode(facade)
340
+ if mode == "off":
341
+ return dict(_PASS)
342
+ path = _transcript(facade, hook_input, session_id)
343
+ if path is None:
344
+ return dict(_PASS)
345
+ alarm_available = hasattr(signal, "setitimer")
346
+ usage, model, ts = facade._keepwarm_last_usage(path) if alarm_available else _bounded_last_usage(path)
347
+ model = _model_id(model)
348
+ context = facade._context_token_count(usage)
349
+ last = facade._keepwarm_iso_to_epoch(ts)
350
+ if context < _MIN_CONTEXT or last is None:
351
+ return dict(_PASS)
352
+ ttl = "1h" if facade._keepwarm_ttl_kind(usage) == "1h" else "5m"
353
+ lifetime = _HOUR if ttl == "1h" else 300
354
+ idle = now - last
355
+ if idle < max(_HOUR, lifetime):
356
+ return dict(_PASS)
357
+ marker_path = _marker_path(directory, session_id)
358
+ current = _maybe_marker(marker_path)
359
+ if current.get("gap_key") == str(ts):
360
+ return dict(_PASS)
361
+ text = texts(facade, context, model, idle, ttl)
362
+ state = {
363
+ "gap_key": str(ts), "told_at": now, "kind": "warn", "context": context, "model": model,
364
+ "ttl": ttl, "session_id": session_id, "project_id": _project_id(path.parent),
365
+ }
366
+ if (mode == "ask" and not _recent_block(current, now) and not hook_input.get("attachments")
367
+ and "[Image #" not in prompt and "[Pasted text #" not in prompt):
368
+ from . import keepwarm_safety
369
+ if keepwarm_safety.session_owner(facade.SNAPSHOT_DIR, session_id, now):
370
+ remaining = _CHECKPOINT_BUDGET if expires is None else expires - time.monotonic() - _WARNING_BUDGET
371
+ save = _checkpoint_saved if alarm_available else _checkpoint_in_worker
372
+ if remaining > 0 and save(facade, path, session_id, min(remaining, _CHECKPOINT_BUDGET)):
373
+ state["kind"] = "block"
374
+ state["prompt_fingerprint"] = _prompt_fingerprint(prompt, os.urandom(16).hex())
375
+ if expires is not None and time.monotonic() >= expires:
376
+ raise BudgetExceeded
377
+ try:
378
+ directory.mkdir(mode=0o700, parents=True, exist_ok=True)
379
+ if not _publish(facade, marker_path, state):
380
+ return dict(_PASS)
381
+ except OSError:
382
+ return dict(_PASS)
383
+ kind = state["kind"]
384
+ # A durable decision should still reach the host if bookkeeping stalls.
385
+ log_budget = None if expires is None else expires - time.monotonic() - _OUTPUT_BUDGET
386
+ if log_budget is None or log_budget > 0:
387
+ try:
388
+ with nullcontext() if log_budget is None else deadline(log_budget):
389
+ facade._log_compression_event("cold_guard", session_id=session_id, detail=kind, tier="estimated")
390
+ except BudgetExceeded:
391
+ pass
392
+ return {"kind": kind, "text": text[kind]}
393
+
394
+
395
+ def _markers(facade):
396
+ for path in _marker_paths(_marker_dir(facade)):
397
+ try:
398
+ yield path, _read_marker(path)
399
+ except (OSError, ValueError):
400
+ continue
401
+
402
+
403
+ def _delegated(row):
404
+ return row.get("isSidechain") or row.get("agentId") or row.get("teamName")
405
+
406
+
407
+ def _rows(facade, path):
408
+ with path.open(encoding="utf-8", errors="replace") as stream:
409
+ for line in stream:
410
+ try:
411
+ row = json.loads(line)
412
+ except ValueError:
413
+ continue
414
+ if not isinstance(row, dict) or _delegated(row):
415
+ continue
416
+ stamp = facade._keepwarm_iso_to_epoch(row.get("timestamp") or row.get("ts"))
417
+ if stamp is not None:
418
+ yield stamp, row
419
+
420
+
421
+ def _assistant_usage(row):
422
+ message = row.get("message")
423
+ if row.get("type") == "assistant" and isinstance(message, dict):
424
+ usage = message.get("usage")
425
+ model = message.get("model") or row.get("model")
426
+ if isinstance(usage, dict) and usage and model != "<synthetic>":
427
+ return usage, model
428
+ return None
429
+
430
+
431
+ def _user_text(row):
432
+ message = row.get("message")
433
+ if (row.get("type") != "user" or row.get("isMeta") or row.get("isCompactSummary")
434
+ or not isinstance(message, dict) or message.get("role") != "user"):
435
+ return None
436
+ content = message.get("content")
437
+ if isinstance(content, str):
438
+ if not content.lstrip().startswith(("<command-name>", "<local-command-stdout>")):
439
+ return content
440
+ return None
441
+ if isinstance(content, list) and content and all(
442
+ isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str)
443
+ for part in content
444
+ ):
445
+ return "\n".join(part["text"] for part in content)
446
+ return ""
447
+
448
+
449
+ def _handover(facade, usage, model):
450
+ splits = usage.get("cache_creation")
451
+ splits = splits if isinstance(splits, dict) else {}
452
+ hour, short = (max(0, facade._safe_int(splits.get(key) or usage.get(key))) for key in (
453
+ "ephemeral_1h_input_tokens", "ephemeral_5m_input_tokens",
454
+ ))
455
+ total = facade._safe_int(usage.get("cache_creation_input_tokens"))
456
+ return {"model": _model_id(model), "context": facade._context_token_count(usage),
457
+ "write_1h": hour, "write_5m": short, "write_unknown": max(0, total - hour - short)}
458
+
459
+
460
+ def _fresh_session(facade, project, old, block):
461
+ fingerprint = block.get("prompt_fingerprint")
462
+ if not isinstance(fingerprint, str) or not _FINGERPRINT.fullmatch(fingerprint):
463
+ return None
464
+ salt = fingerprint.split(":", 1)[0]
465
+ told_at = block["told_at"]
466
+ until = told_at + _CHOICE_WINDOW
467
+ candidate = None
468
+ for path in project.glob("*.jsonl"):
469
+ if path == old or path.is_symlink() or not _SESSION_ID.fullmatch(path.stem):
470
+ continue
471
+ try:
472
+ if path.stat().st_mtime < told_at:
473
+ continue
474
+ with _read_rows(facade, path) as rows:
475
+ first = next(rows, None)
476
+ if not first or not told_at <= first[0] <= until:
477
+ continue
478
+ for stamp, row in itertools.chain((first,), rows):
479
+ if not told_at <= stamp <= until or _assistant_usage(row):
480
+ break
481
+ prompt = _user_text(row)
482
+ if prompt is None:
483
+ continue
484
+ if _prompt_fingerprint(prompt, salt) == fingerprint:
485
+ if candidate:
486
+ return None # Two sessions resent the same held prompt.
487
+ candidate = {"fresh_session_id": path.stem}
488
+ usage = next((use for _, reply in rows if (use := _assistant_usage(reply))), None)
489
+ if usage is not None:
490
+ candidate["handover"] = _handover(facade, *usage)
491
+ break
492
+ except OSError:
493
+ continue
494
+ return candidate
495
+
496
+
497
+ @contextmanager
498
+ def _read_rows(facade, path):
499
+ rows = _rows(facade, path)
500
+ try:
501
+ yield rows
502
+ finally:
503
+ rows.close()
504
+
505
+
506
+ def _choice(facade, project, block):
507
+ session_id = block.get("session_id")
508
+ if not project or not isinstance(session_id, str) or not _SESSION_ID.fullmatch(session_id):
509
+ return {"choice": "unknown"}
510
+ old = project / f"{session_id}.jsonl"
511
+ if old.is_symlink():
512
+ return {"choice": "unknown"}
513
+ told_at = block["told_at"]
514
+ compact = False
515
+ try:
516
+ with _read_rows(facade, old) as rows:
517
+ for stamp, row in rows:
518
+ if not told_at <= stamp <= told_at + _CHOICE_WINDOW:
519
+ continue
520
+ if row.get("type") == "system" and row.get("subtype") == "compact_boundary":
521
+ compact = True
522
+ if _assistant_usage(row):
523
+ return {"choice": "compact" if compact else "continue"}
524
+ except OSError:
525
+ return {"choice": "unknown"}
526
+ fresh = _fresh_session(facade, project, old, block)
527
+ return {"choice": "fresh", **fresh} if fresh else {"choice": "unknown"}
528
+
529
+
530
+ def resolve(facade, now):
531
+ """Reconcile holds from transcript evidence. Never called on prompt submission."""
532
+ _prune(facade, _marker_dir(facade), now)
533
+ projects = None
534
+ for path, marker in _markers(facade):
535
+ pending = [
536
+ block for block in _blocks(marker)
537
+ if now - block["told_at"] >= _CHOICE_WINDOW
538
+ and block.get("choice") not in ("continue", "compact")
539
+ ]
540
+ if not pending:
541
+ continue
542
+ if projects is None:
543
+ root = facade.CLAUDE_DIR / "projects"
544
+ projects = {_project_id(p): p for p in root.glob("*") if p.is_dir() and not p.is_symlink()}
545
+ before = json.dumps(marker)
546
+ for block in pending:
547
+ outcome = _choice(facade, projects.get(block.get("project_id")), block)
548
+ for key in ("fresh_session_id", "handover"):
549
+ if key not in outcome:
550
+ block.pop(key, None)
551
+ block.update(outcome)
552
+ try:
553
+ with _marker_lock(facade, path.parent) as held:
554
+ if held and json.dumps(_maybe_marker(path)) == before and json.dumps(marker) != before:
555
+ _write_marker(path, marker)
556
+ except (OSError, ValueError):
557
+ pass
558
+
559
+
560
+ def _net_estimate(facade, block):
561
+ handover = block.get("handover")
562
+ if handover is None or handover["write_unknown"]:
563
+ return None
564
+ old = _price_card(facade, block["model"], block["context"])
565
+ old_write = _rate(old, _write_key(block["ttl"]))
566
+ old_read = _rate(old, "cache_read")
567
+ if old_write is None or old_read is None:
568
+ return None
569
+ gross = block["context"] * (old_write - old_read)
570
+ recipient = _price_card(facade, handover["model"], handover["context"])
571
+ cost = 0.0
572
+ for ttl in ("1h", "5m"):
573
+ tokens = handover[f"write_{ttl}"]
574
+ if tokens:
575
+ write = _rate(recipient, _write_key(ttl))
576
+ if write is None:
577
+ return None
578
+ cost += tokens * write
579
+ old_input = _rate(old, "input")
580
+ new_input = _rate(recipient, "input")
581
+ units = gross / old_input if old_input else 0.0
582
+ if cost and new_input:
583
+ units -= cost / new_input
584
+ return gross / 1_000_000, cost / 1_000_000, units
585
+
586
+
587
+ def _overlapping_credits(facade, days, since, now, handover, mod_fresh):
588
+ """Use the receipt identities from the pools that contribute to this report."""
589
+ from . import mod_fresh_booking
590
+
591
+ restores = set()
592
+ mod_starts = {}
593
+ handover_counted = float((handover or {}).get("cost_saved_usd") or 0) > 0
594
+ mod_counted = mod_fresh_booking.additive(mod_fresh, handover) > 0
595
+ if handover_counted or mod_counted:
596
+ cutoff = datetime.fromtimestamp(now) - timedelta(days=days)
597
+ with closing(facade._open_trends_db_readonly(timeout=1.0)) as conn:
598
+ if handover_counted:
599
+ table = facade._counted_table(conn, "savings_events")
600
+ restored_ids = {sid for sid, in conn.execute(
601
+ facade._CHECKPOINT_RESTORED_SQL[table], (cutoff.isoformat(),)
602
+ )}
603
+ restores = restored_ids.intersection(
604
+ Path(path).stem for path, in conn.execute(
605
+ "SELECT jsonl_path FROM session_log WHERE date >= ?", (cutoff.date().isoformat(),)
606
+ ) if path
607
+ )
608
+ if mod_counted:
609
+ mod_starts = {sid: datetime.fromisoformat(stamp).timestamp() for sid, stamp in conn.execute(
610
+ "SELECT session_uuid, timestamp FROM mod_fresh_receipts "
611
+ "WHERE timestamp >= ? AND estimated_usd > 0", (since or cutoff.isoformat(),)
612
+ )}
613
+ return restores, mod_starts
614
+
615
+
616
+ def estimate(facade, days=30, since=None, now=None, *, handover=None, mod_fresh=None):
617
+ """Read the signed estimate from retained, resolved choices."""
618
+ now = time.time() if now is None else now
619
+ days = days or 30
620
+ cutoff = facade._keepwarm_iso_to_epoch(since) if since else None
621
+ if cutoff is None:
622
+ cutoff = now - days * 86400
623
+ fresh = sorted(
624
+ (block for _, marker in _markers(facade) for block in _blocks(marker)
625
+ if block.get("choice") == "fresh" and block.get("fresh_session_id") and block.get("session_id")
626
+ and isinstance(block.get("prompt_fingerprint"), str) and _FINGERPRINT.fullmatch(block["prompt_fingerprint"])),
627
+ key=lambda block: (block["told_at"], block["session_id"]),
628
+ )
629
+ gross = cost = units = 0.0
630
+ priced = unpriced = 0
631
+ if fresh:
632
+ try:
633
+ restores, mod_starts = _overlapping_credits(facade, days, since, now, handover, mod_fresh)
634
+ except (OSError, sqlite3.Error, ValueError):
635
+ # An unavailable overlap check cannot support an additional credit.
636
+ fresh = []
637
+ seen = set()
638
+ for block in fresh:
639
+ target = block["fresh_session_id"]
640
+ if target in seen:
641
+ continue
642
+ seen.add(target)
643
+ if not cutoff <= block["told_at"] <= now:
644
+ continue
645
+ mod_at = mod_starts.get(block["session_id"])
646
+ if target in restores or (mod_at is not None and block["told_at"] <= mod_at <= block["told_at"] + _CHOICE_WINDOW):
647
+ continue
648
+ if facade._resume_lean_already_credited(block["session_id"]):
649
+ continue
650
+ try:
651
+ values = _net_estimate(facade, block)
652
+ except (KeyError, TypeError, ValueError):
653
+ values = None
654
+ if values is None:
655
+ unpriced += 1
656
+ continue
657
+ avoided_cost, handover_cost, net_units = values
658
+ gross += avoided_cost
659
+ cost += handover_cost
660
+ units += net_units
661
+ priced += 1
662
+ return {"label": LABEL, "events": priced, "unpriced_events": unpriced,
663
+ "gross_usd": round(gross, 4), "handover_cost_usd": round(cost, 4),
664
+ "cost_saved_usd": round(gross - cost, 4), "limit_units_saved": round(units, 2)}
665
+
666
+
667
+ def on_savings_refresh(facade, summary):
668
+ from . import savings_story
669
+
670
+ now = time.time()
671
+ resolve(facade, now)
672
+ previous = summary.get(ESTIMATE_KEY)
673
+ current = estimate(
674
+ facade, days=summary.get("period_days"), since=savings_story.install_anchor(), now=now,
675
+ handover=summary.get("handover_rerun"), mod_fresh=summary.get("mod_fresh_estimated"),
676
+ )
677
+ summary[ESTIMATE_KEY] = current
678
+ if previous != current and "action_savings" in summary:
679
+ summary["action_savings"] = facade._action_savings_components(summary, summary.get("counted_period"))
680
+ if "savings_headline" in summary:
681
+ from . import savings_headline
682
+ summary["savings_headline"] = savings_headline.build(summary)
683
+ if previous != current and summary.get("since_install") is not None:
684
+ summary["since_install"] = facade._savings_since_install()
685
+
686
+
687
+ def print_estimate(summary, cents, format_cents, period):
688
+ row = summary.get(ESTIMATE_KEY) or {}
689
+ if row.get("events"):
690
+ amount = cents.get(ESTIMATE_KEY, 0)
691
+ sign = "-" if amount < 0 else ""
692
+ print(f" + est. {LABEL}: {sign}${format_cents(abs(amount))}{period} "
693
+ f"({row['events']:,} fresh starts, net of handover writes) [estimated]")
694
+ if row.get("unpriced_events"):
695
+ print(f" i {LABEL}: {row['unpriced_events']:,} fresh starts without complete cache-write pricing")
696
+
697
+
698
+ def _opportunity(facade, days):
699
+ drops = facade._estimate_cache_drop_savings(days=days)
700
+ return {"days": days, "events": int(drops.get("est_drops") or 0),
701
+ "cost_saved_usd": float(drops.get("cost_saved_usd") or 0)}
702
+
703
+
704
+ def pool(facade, days=30):
705
+ resolve(facade, time.time())
706
+ return _opportunity(facade, days)
707
+
708
+
709
+ def plan_item(facade):
710
+ if _mode(facade) == "ask":
711
+ return None
712
+ opportunity = _opportunity(facade, 30)
713
+ events, dollars = opportunity["events"], opportunity["cost_saved_usd"]
714
+ if events < 3:
715
+ return None
716
+ return {
717
+ "id": "cold_guard:ask", "kind": "cold_guard",
718
+ "label": "Ask before re-reading a cold session over 300K",
719
+ "tokens_per_request": None, "net_usd_month": None, "own_cost_usd_month": 0.0,
720
+ "basis": f"{events:,} cold resumes cost ${dollars:,.2f} in your last 30 days; "
721
+ "the saving depends on what you choose each time",
722
+ "undo": "measure.py cold-guard set warn", "default_selected": True,
723
+ }
724
+
725
+
726
+ def _set_mode(facade, mode):
727
+ facade._write_config_flag("cold_guard_mode", mode)
728
+ if facade._read_config_flag("cold_guard_mode") != mode:
729
+ raise OSError("cold-guard mode was not written")
730
+
731
+
732
+ def apply_item(facade, item):
733
+ previous = _configured_mode(facade)
734
+ _set_mode(facade, "ask")
735
+ return {'ok': True, 'before': previous, 'after': 'ask'}
736
+
737
+
738
+ def undo_item(facade, receipt):
739
+ before = receipt.get('before')
740
+ if before not in MODES or _configured_mode(facade) != receipt.get('after'):
741
+ return False
742
+ _set_mode(facade, before)
743
+ return True
744
+
745
+
746
+ def main(facade, args):
747
+ parser = argparse.ArgumentParser(prog="measure.py cold-guard")
748
+ subcommands = parser.add_subparsers(dest="command", required=True)
749
+ for command in ("status", "pool"):
750
+ subcommands.add_parser(command).add_argument("--json", action="store_true")
751
+ subcommands.add_parser("set").add_argument("mode", choices=MODES)
752
+ options = parser.parse_args(args)
753
+ if options.command == "set":
754
+ _set_mode(facade, options.mode)
755
+ effective = _mode(facade)
756
+ print(f"{LABEL} set to {options.mode}."
757
+ + (f" The environment overrides it to {effective}." if effective != options.mode else ""))
758
+ return 0
759
+ opportunity = pool(facade)
760
+ result = opportunity
761
+ if options.command == "status":
762
+ counts = dict.fromkeys(CHOICES, 0)
763
+ for _, marker in _markers(facade):
764
+ for block in _blocks(marker):
765
+ choice = block.get("choice")
766
+ if choice in counts:
767
+ counts[choice] += 1
768
+ result = {"mode": _mode(facade), "pool": opportunity, "counts": counts}
769
+ if options.json:
770
+ print(json.dumps(result, indent=2))
771
+ else:
772
+ if options.command == "status":
773
+ print(f"{LABEL} mode: {result['mode']}")
774
+ print("Choices: " + ", ".join(f"{choice} {count}" for choice, count in result["counts"].items()))
775
+ print(f"Last {opportunity['days']} days: {opportunity['events']:,} cold resumes, "
776
+ f"${opportunity['cost_saved_usd']:,.2f} of cache rewrites at API rates.")
777
+ return 0