@alexgreensh/token-optimizer 5.13.69 → 5.13.70

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 (151) 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 +399 -509
  11. package/skills/token-optimizer/assets/savings_story.js +661 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  14. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  15. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  16. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  18. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  19. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  20. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  21. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  23. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  24. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  25. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  26. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  28. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  29. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  30. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  31. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  36. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  37. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  38. package/skills/token-optimizer/scripts/_measure/dashboard.py +87 -151
  39. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  40. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  41. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  42. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  43. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  44. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  46. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  47. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  48. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  50. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  54. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  55. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  56. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  57. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  58. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  59. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  60. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  61. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  62. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  63. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  64. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  65. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  66. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  67. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  68. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  69. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  70. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  71. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  72. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  73. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  74. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  75. package/skills/token-optimizer/scripts/_measure/savings.py +431 -863
  76. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  77. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  78. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  79. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  80. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  81. package/skills/token-optimizer/scripts/_measure/sessions.py +96 -196
  82. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  83. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  84. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  85. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  86. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  91. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  92. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  93. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  94. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  95. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  96. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  97. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  98. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  99. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  100. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  101. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  102. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  103. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  104. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  105. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  106. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  107. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  108. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  109. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  110. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  111. package/skills/token-optimizer/scripts/codemap.py +274 -0
  112. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  113. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  114. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  115. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  116. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  117. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  118. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  119. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  120. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  121. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  122. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  123. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  124. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  125. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  126. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  127. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  128. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  129. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  130. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  132. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  133. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  134. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  135. package/skills/token-optimizer/scripts/holdout.py +136 -0
  136. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  137. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  138. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  139. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  140. package/skills/token-optimizer/scripts/measure.py +34 -76
  141. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  142. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  143. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  144. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  145. package/skills/token-optimizer/scripts/session_store.py +49 -99
  146. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  147. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  148. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  149. package/skills/token-optimizer/scripts/statusline.js +1 -1
  150. package/skills/token-optimizer/scripts/structural.py +25 -0
  151. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -0,0 +1,89 @@
1
+ """Opportunity-tier record of a Bash compression the PostToolUse budget cut off.
2
+
3
+ When the runner's per-handler deadline interrupts ``bash_compress_hook`` (or the
4
+ shared budget is gone before it is dispatched), the raw output reaches the model
5
+ uncompressed. Nothing was saved, so nothing may be counted, but the cost of the
6
+ skip should be visible: this writes one ``compression_events`` row with
7
+ ``tier='opportunity'`` and the size of the output that went through unshrunk.
8
+
9
+ Never a saving, by construction and not only by tier:
10
+ * ``tier = 'opportunity'``: realized-savings readers take measured/estimated only.
11
+ * ``compressed_tokens == original_tokens``: any reader that sums
12
+ ``original_tokens - compressed_tokens`` (the counted views, the reread pass)
13
+ gets exactly 0 from these rows, even one that ignores the tier.
14
+ * The would-be size lives in ``detail`` (``output_tokens``) for opportunity reports.
15
+
16
+ Hot path: imported only after an overrun, standard library plus the hook-side
17
+ ``compression_log`` writer (50 ms DB timeout, fail-open). Never raises.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import re
23
+
24
+ FEATURE = "bash_compress_skipped"
25
+ # bash_compress_hook never compresses stdout shorter than this, so a skip of a
26
+ # smaller output cost nothing and is not recorded.
27
+ MIN_OUTPUT_CHARS = 100
28
+ _FIRST_WORD = re.compile(r"[A-Za-z0-9_.+-]{1,40}")
29
+
30
+
31
+ def _bash_stdout(hook_input):
32
+ """The Bash stdout the hook would have compressed, or '' when there is none."""
33
+ response = hook_input.get("tool_response")
34
+ if isinstance(response, str):
35
+ return response
36
+ if not isinstance(response, dict) or response.get("interrupted") or response.get("isImage"):
37
+ return ""
38
+ return str(response.get("stdout") or "")
39
+
40
+
41
+ def _command_word(command):
42
+ """First program word of the command, for grouping only (never the full line)."""
43
+ for part in re.split(r"&&|\|\||;|\|", str(command or "")):
44
+ part = part.strip()
45
+ if not part or part.startswith("cd "):
46
+ continue
47
+ for word in part.split():
48
+ if "=" in word or word in ("sudo", "env", "time", "timeout"):
49
+ continue
50
+ m = _FIRST_WORD.fullmatch(word.rsplit("/", 1)[-1])
51
+ return m.group(0) if m else "unknown"
52
+ return "unknown"
53
+
54
+
55
+ def skip_row(hook_input, handler, budget_s, reason):
56
+ """The compression_events fields for one skipped compression, or None."""
57
+ if not isinstance(hook_input, dict) or hook_input.get("tool_name") != "Bash":
58
+ return None
59
+ stdout = _bash_stdout(hook_input)
60
+ if len(stdout) < MIN_OUTPUT_CHARS:
61
+ return None
62
+ try:
63
+ from token_estimate import estimate_tokens
64
+ tokens = int(estimate_tokens(stdout))
65
+ except Exception:
66
+ tokens = len(stdout.encode("utf-8", errors="replace")) // 4
67
+ detail = json.dumps({
68
+ "reason": reason, "handler": handler, "budget_s": round(float(budget_s or 0.0), 3),
69
+ "output_chars": len(stdout), "output_tokens": tokens, "saved_tokens": 0,
70
+ }, sort_keys=True)
71
+ command = (hook_input.get("tool_input") or {}).get("command", "")
72
+ return {
73
+ "feature": FEATURE, "session_id": str(hook_input.get("session_id") or "") or None,
74
+ "command_pattern": _command_word(command), "tier": "opportunity",
75
+ "original_tokens": tokens, "compressed_tokens": tokens, "detail": detail,
76
+ }
77
+
78
+
79
+ def log_skipped_compression(hook_input, handler, budget_s, reason="hook_budget"):
80
+ """Write the opportunity row for one skip. Returns True when a row was attempted."""
81
+ try:
82
+ row = skip_row(hook_input, handler, budget_s, reason)
83
+ if row is None:
84
+ return False
85
+ from compression_log import log_compression_event
86
+ log_compression_event(**row)
87
+ return True
88
+ except Exception:
89
+ return False
@@ -0,0 +1,31 @@
1
+ """Disclose large transcripts whose resumable scan is unfinished or failed."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+ from pathlib import Path
6
+
7
+
8
+ def count(claude_dir, days=30, now=None, limit=None):
9
+ """Unfinished large transcripts in the active runtime's session roots."""
10
+ try:
11
+ if limit is None:
12
+ from codex_session import MAX_PARSE_FILE_BYTES as limit
13
+ cutoff = (now or time.time()) - max(1, int(days or 30)) * 86400
14
+ n = 0
15
+ from runtime_env import detect_runtime
16
+ from _measure.transcript_stream import pending
17
+ paths = Path(claude_dir, "projects").glob("*/*.jsonl")
18
+ if detect_runtime() == 'codex':
19
+ from codex_session import session_roots
20
+ from codex_log_index import pending
21
+ paths = (path for root in session_roots() for path in root.rglob('*.jsonl'))
22
+ for path in paths:
23
+ try:
24
+ st = path.stat()
25
+ except OSError:
26
+ continue
27
+ if st.st_mtime >= cutoff and st.st_size > limit:
28
+ n += int(pending(path))
29
+ return {"unscanned_large_sessions": n}
30
+ except Exception:
31
+ return {"unscanned_large_sessions": 0}
@@ -0,0 +1,518 @@
1
+ """Shadow diagnostic for lean-resume carry (savings-truth U6).
2
+
3
+ For every ``resume_lean`` savings event this walks the resumed session's
4
+ transcript and credits the avoided context once per real API turn up to the
5
+ first real compaction, capped when the session's own context growth passes the
6
+ avoided size or the counterfactual reaches its auto-compaction threshold. The
7
+ result is a SHADOW field only: it is never added to
8
+ ``total_tokens``, ``total_cost_usd``, counted ledger summaries, action savings,
9
+ or any dashboard headline total.
10
+
11
+ The event row records the TARGET session that was lean-resumed, not the session
12
+ that received the injected lean block, so the resumed transcript is proxied by
13
+ the target session's own ``.jsonl``. That linkage is the method's largest known
14
+ weakness and is disclosed in every payload.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import sqlite3
20
+ from datetime import datetime, timedelta
21
+ from pathlib import Path
22
+ from _measure import lean_resume_threshold
23
+
24
+ _EVENT_TYPE = "resume_lean"
25
+ _TURN_CAP = 20000
26
+
27
+
28
+ def _m():
29
+ import measure # noqa: PLC0415 - lazy: this module is imported by measure providers
30
+ return measure
31
+
32
+
33
+ def _parse_ts(value):
34
+ try:
35
+ return datetime.strptime(str(value)[:19], "%Y-%m-%dT%H:%M:%S")
36
+ except (TypeError, ValueError):
37
+ return None
38
+
39
+
40
+ def _event_dt(m, ts):
41
+ try:
42
+ dt = m._counted_event_utc(ts)
43
+ except Exception:
44
+ dt = None
45
+ return dt or _parse_ts(ts)
46
+
47
+
48
+ def _cutoff(days, since, m):
49
+ if since:
50
+ return str(since)
51
+ return (m.datetime.now() - m.timedelta(days=days or 30)).isoformat()
52
+
53
+
54
+ def _connect(db_path, m):
55
+ if db_path is not None:
56
+ uri = Path(db_path).resolve().as_uri() + "?mode=ro"
57
+ return sqlite3.connect(uri, uri=True, timeout=1.5)
58
+ return m._init_trends_db()
59
+
60
+
61
+ def _events(days=None, since=None, db_path=None):
62
+ m = _m()
63
+ conn = _connect(db_path, m)
64
+ try:
65
+ conn.row_factory = sqlite3.Row
66
+ rows = conn.execute(
67
+ "SELECT id, timestamp, tokens_saved, cost_saved_usd, session_id, "
68
+ "session_uuid, model, detail FROM savings_events "
69
+ "WHERE event_type = ? AND timestamp >= ? ORDER BY timestamp",
70
+ (_EVENT_TYPE, _cutoff(days, since, m)),
71
+ ).fetchall()
72
+ finally:
73
+ conn.close()
74
+ return [dict(r) for r in rows]
75
+
76
+
77
+ def _sid_for(row, m):
78
+ raw = row.get("session_uuid") or row.get("session_id")
79
+ if not raw:
80
+ return None
81
+ try:
82
+ canonical, _unjoinable = m._extract_session_uuid(str(raw))
83
+ raw = canonical or str(raw)
84
+ except Exception:
85
+ pass
86
+ try:
87
+ safe = m.sanitize_session_id(raw)
88
+ except Exception:
89
+ safe = None
90
+ return safe or str(raw)
91
+
92
+
93
+ def _transcript_for(sid, m):
94
+ try:
95
+ conn = m._open_trends_db_readonly(timeout=1.0)
96
+ try:
97
+ row = conn.execute('SELECT jsonl_path FROM session_log WHERE session_uuid=? AND jsonl_path IS NOT NULL ORDER BY id DESC LIMIT 1', (sid,)).fetchone()
98
+ finally:
99
+ conn.close()
100
+ if row and Path(row[0]).is_file():
101
+ return Path(row[0])
102
+ except (OSError, sqlite3.Error, AttributeError):
103
+ pass
104
+ try:
105
+ base = m.CLAUDE_DIR / "projects"
106
+ candidates = list(base.glob("*/" + sid + ".jsonl")) if base.exists() else []
107
+ return max(candidates, key=lambda p: p.stat().st_mtime) if candidates else None
108
+ except (OSError, PermissionError):
109
+ return None
110
+
111
+
112
+ def _prompt_tokens(m, usage):
113
+ try:
114
+ selected = m._context_usage(usage)
115
+ return int(m._context_token_count(selected) or 0)
116
+ except Exception:
117
+ return 0
118
+
119
+
120
+ def _walk(path, ev_floor, avoided, m, threshold):
121
+ """Post-event turns until real or counterfactual compaction or the growth cap.
122
+
123
+ Returns (turns, stopped_by) where turns is a list of
124
+ (utc-naive datetime, raw model, context tokens). Never raises; returns
125
+ (None, 'unreadable') when the file cannot be opened.
126
+ """
127
+ turns = []
128
+ seen = {}
129
+ first_prompt = None
130
+ stopped_by = "eof"
131
+ try:
132
+ with open(path, "r", encoding="utf-8", errors="replace") as handle:
133
+ for line in handle:
134
+ if '"assistant"' not in line and "compact_boundary" not in line:
135
+ continue
136
+ try:
137
+ record = json.loads(line)
138
+ except (json.JSONDecodeError, ValueError, UnicodeDecodeError):
139
+ continue
140
+ if not isinstance(record, dict):
141
+ continue
142
+ rtype = record.get("type")
143
+ dt = _parse_ts(record.get("timestamp"))
144
+ if rtype == "system" and record.get("subtype") == "compact_boundary":
145
+ if dt is not None and dt >= ev_floor:
146
+ stopped_by = "compaction"
147
+ break
148
+ continue
149
+ if (rtype != "assistant" or record.get("isSidechain") or dt is None
150
+ or dt < ev_floor):
151
+ continue
152
+ message = record.get("message") or {}
153
+ if not isinstance(message, dict):
154
+ continue
155
+ usage = message.get("usage")
156
+ if not isinstance(usage, dict) or not usage:
157
+ continue
158
+ ctx = _prompt_tokens(m, usage)
159
+ if ctx <= 0:
160
+ continue
161
+ model = message.get("model")
162
+ rid = None
163
+ try:
164
+ rid = m._usage_request_key(record, message)
165
+ except Exception:
166
+ rid = None
167
+ if rid is not None and rid in seen:
168
+ index = seen[rid]
169
+ if ctx > turns[index][2]:
170
+ if ctx + avoided >= threshold:
171
+ del turns[index:]
172
+ stopped_by = "counterfactual_compaction"
173
+ break
174
+ turns[index] = (dt, model or turns[index][1], ctx)
175
+ continue
176
+ if ctx + avoided >= threshold:
177
+ stopped_by = "counterfactual_compaction"
178
+ break
179
+ if first_prompt is None:
180
+ first_prompt = ctx
181
+ elif ctx - first_prompt > avoided:
182
+ stopped_by = "growth_cap"
183
+ break
184
+ turns.append((dt, model, ctx))
185
+ if rid is not None:
186
+ seen[rid] = len(turns) - 1
187
+ if len(turns) >= _TURN_CAP:
188
+ stopped_by = "turn_cap"
189
+ break
190
+ except (OSError, PermissionError):
191
+ return None, "unreadable"
192
+ return turns, stopped_by
193
+
194
+
195
+ def _resolver(m):
196
+ """resolve(model, largest) -> the user's effective compaction settings for a model.
197
+
198
+ Transcripts name the model without the [1m] tag, so a session seen past
199
+ 200K is resolved as the 1M variant of its model.
200
+ """
201
+ def resolve(model, largest):
202
+ model = str(model or "") or None
203
+ out = m._resolve_compact_window(model)
204
+ if largest > 200000 and int(out.get("model_window") or 0) < 1_000_000 and model and "[1m]" not in model:
205
+ out = m._resolve_compact_window(model + "[1m]")
206
+ if largest > int(out.get("model_window") or 0):
207
+ # The session itself proves a larger window than the model table knows.
208
+ out = dict(out, model_window=1_000_000,
209
+ tokens=out["tokens"] if out.get("user_override") else m._COMPACT_WINDOW_1M_DEFAULT)
210
+ return out
211
+ return resolve
212
+
213
+
214
+ def _card_for(m, model, prompt_tokens, tier_data, fallback_key):
215
+ card = None
216
+ try:
217
+ if model:
218
+ card = m._counted_exact_card(model, tier_data, prompt_tokens)
219
+ except Exception:
220
+ card = None
221
+ if card is None and fallback_key:
222
+ card = (tier_data.get("claude_models") or {}).get(fallback_key)
223
+ if card is None:
224
+ card = (tier_data.get("claude_models") or {}).get("sonnet") or {}
225
+ return card
226
+
227
+
228
+ def _cache_read_rate(card):
229
+ rate = card.get("cache_read") if isinstance(card, dict) else None
230
+ if not isinstance(rate, (int, float)):
231
+ rate = card.get("input") if isinstance(card, dict) else None
232
+ return float(rate or 0.0)
233
+
234
+
235
+ def _score_event(row, m, tier_data):
236
+ sid = _sid_for(row, m)
237
+ avoided = int(row.get("tokens_saved") or 0)
238
+ out = {
239
+ "event_id": row.get("id"),
240
+ "session": sid,
241
+ "event_ts": row.get("timestamp"),
242
+ "avoided_tokens": avoided,
243
+ "logged_cost_usd": row.get("cost_saved_usd"),
244
+ "turns": 0,
245
+ "carry_tokens": 0,
246
+ "carry_cost_usd": 0.0,
247
+ "stopped_by": "no_transcript",
248
+ "priced": False,
249
+ "threshold_source": None,
250
+ }
251
+ if not sid or avoided <= 0:
252
+ out["stopped_by"] = "no_avoided_context"
253
+ return out
254
+ path = _transcript_for(sid, m)
255
+ if path is None:
256
+ return out
257
+ ev_dt = _event_dt(m, row.get("timestamp"))
258
+ if ev_dt is None:
259
+ out["stopped_by"] = "bad_timestamp"
260
+ return out
261
+ ev_floor = ev_dt.replace(microsecond=0)
262
+ threshold, source = lean_resume_threshold.threshold(path, lambda usage: _prompt_tokens(m, usage), _resolver(m))
263
+ if threshold is None:
264
+ out["stopped_by"] = "unreadable"
265
+ return out
266
+ out["threshold_source"] = source
267
+ turns, stopped_by = _walk(path, ev_floor, avoided, m, threshold)
268
+ if turns is None:
269
+ out["stopped_by"] = "unreadable"
270
+ return out
271
+ out["stopped_by"] = stopped_by or "eof"
272
+ fallback_key = row.get("model")
273
+ cost = 0.0
274
+ for _dt, model, ctx in turns:
275
+ card = _card_for(m, model, ctx, tier_data, fallback_key)
276
+ cost += avoided * _cache_read_rate(card) / 1_000_000.0
277
+ out["turns"] = len(turns)
278
+ out["carry_tokens"] = avoided * len(turns)
279
+ out["carry_cost_usd"] = round(cost, 6)
280
+ out["priced"] = bool(turns)
281
+ return out
282
+
283
+
284
+ def summary(days=30, since=None, db_path=None, include_events=True):
285
+ """Shadow lean-resume carry diagnostic. Never feeds savings totals."""
286
+ m = _m()
287
+ empty = {
288
+ "available": False,
289
+ "evidence": "shadow",
290
+ "included_in_totals": False,
291
+ "days": days,
292
+ "events": 0,
293
+ "events_with_transcript": 0,
294
+ "events_priced": 0,
295
+ "missing_transcript": 0,
296
+ "no_post_event_turns": 0,
297
+ "carry_tokens": 0,
298
+ "carry_cost_usd": 0.0,
299
+ "threshold_source_counts": {"observed_auto": 0, "fallback": 0},
300
+ "method": "avoided context x real parent API turns to first "
301
+ "compact_boundary, capped when context growth exceeds the "
302
+ "avoided size or counterfactual context reaches the session's "
303
+ "auto-compaction threshold; priced per turn at that turn's exact "
304
+ "cache-read card",
305
+ "weaknesses": [
306
+ "resume_lean rows name the target session, not the session that "
307
+ "received the lean block; the target transcript is the resumed-"
308
+ "session proxy",
309
+ "the resume trigger is counterfactual, so the carry is shadow "
310
+ "evidence only",
311
+ "turns are deduped on requestId/message.id and stop at the first "
312
+ "compact_boundary; a request split across the event boundary can "
313
+ "be missed",
314
+ "the growth cap uses first-post-event context as the baseline, "
315
+ "so sessions that compact without a compact_boundary line are "
316
+ "truncated only by the caps or EOF",
317
+ "the auto-compaction threshold is inferred from this session's "
318
+ "observed auto compactions or a context-window fallback",
319
+ ],
320
+ }
321
+ try:
322
+ rows = _events(days=days, since=since, db_path=db_path)
323
+ except Exception:
324
+ return empty
325
+ try:
326
+ tier_data = m.PRICING_TIERS.get(
327
+ m._load_pricing_tier(), m.PRICING_TIERS.get("anthropic", {}))
328
+ except Exception:
329
+ tier_data = {}
330
+ details = []
331
+ carry_tokens = 0
332
+ carry_cost = 0.0
333
+ priced = with_transcript = missing = no_turns = 0
334
+ for row in rows:
335
+ try:
336
+ item = _score_event(row, m, tier_data)
337
+ except Exception:
338
+ continue
339
+ details.append(item)
340
+ source = item.get("threshold_source")
341
+ if source in empty["threshold_source_counts"]:
342
+ empty["threshold_source_counts"][source] += 1
343
+ carry_tokens += int(item.get("carry_tokens") or 0)
344
+ carry_cost += float(item.get("carry_cost_usd") or 0.0)
345
+ stopped = item.get("stopped_by")
346
+ if stopped in ("no_transcript", "unreadable", "bad_timestamp"):
347
+ missing += 1
348
+ elif stopped not in ("no_avoided_context",):
349
+ with_transcript += 1
350
+ if item.get("priced"):
351
+ priced += 1
352
+ if int(item.get("turns") or 0) <= 0:
353
+ no_turns += 1
354
+ if include_events:
355
+ empty["event_details"] = details
356
+ empty.update({
357
+ "available": True,
358
+ "events": len(rows),
359
+ "events_with_transcript": with_transcript,
360
+ "events_priced": priced,
361
+ "missing_transcript": missing,
362
+ "no_post_event_turns": no_turns,
363
+ "carry_tokens": int(carry_tokens),
364
+ "carry_cost_usd": round(carry_cost, 4),
365
+ })
366
+ return empty
367
+
368
+
369
+ def main(argv=None):
370
+ import argparse
371
+ import sys
372
+
373
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
374
+ parser.add_argument("--days", type=int, default=30)
375
+ parser.add_argument("--since", default=None)
376
+ parser.add_argument("--db", default=None)
377
+ parser.add_argument("--no-events", action="store_true")
378
+ args = parser.parse_args(argv)
379
+ print(json.dumps(summary(days=args.days, since=args.since, db_path=args.db,
380
+ include_events=not args.no_events), indent=2))
381
+ return 0
382
+
383
+
384
+ if __name__ == "__main__":
385
+ raise SystemExit(main())
386
+
387
+
388
+ def _score_verified_event(row, m, tier_data, compactions=None):
389
+ """Score a delivered lean block only if the old session stayed stopped.
390
+
391
+ The counterfactual old session's compaction point comes from the user's own
392
+ compaction sizes (``compaction_survival``); with too little history the
393
+ fixed 500K rule stays.
394
+ """
395
+ import re
396
+ result = {'eligible': False, 'turns': 0, 'carry_tokens': 0, 'carry_cost_usd': 0.0}
397
+ target = _sid_for(row, m)
398
+ match = re.search(r'(?:^|\s)receiver=([0-9a-fA-F-]{36})(?:\s|$)', row.get('detail') or '')
399
+ ev = _event_dt(m, row.get('timestamp'))
400
+ if not target or not match or not ev or match.group(1) == target:
401
+ return result
402
+ receiver = match.group(1)
403
+ old_path, new_path = _transcript_for(target, m), _transcript_for(receiver, m)
404
+ if not old_path or not new_path:
405
+ return result
406
+ old_seen = False
407
+ old_latest = None
408
+ delivered = False
409
+ try:
410
+ old_stat, new_stat = old_path.stat(), new_path.stat()
411
+ with old_path.open(encoding='utf-8', errors='replace') as f:
412
+ for line in f:
413
+ if '"assistant"' not in line or '"usage"' not in line:
414
+ continue
415
+ try: obj = json.loads(line)
416
+ except ValueError: continue
417
+ stamp = _parse_ts(obj.get('timestamp'))
418
+ if obj.get('type') != 'assistant' or obj.get('isSidechain') or not (obj.get('message') or {}).get('usage') or not stamp:
419
+ continue
420
+ if stamp > ev:
421
+ return result
422
+ old_seen = True
423
+ if old_latest is None or stamp > old_latest[0]:
424
+ msg = obj['message']
425
+ old_latest = (stamp, msg.get('model'), _prompt_tokens(m, msg['usage']))
426
+ marker = 'Cold-resume lean (session ' + target[:8]
427
+ with new_path.open(encoding='utf-8', errors='replace') as f:
428
+ for line in f:
429
+ if marker not in line:
430
+ continue
431
+ try: obj = json.loads(line)
432
+ except ValueError: continue
433
+ stamp = _parse_ts(obj.get('timestamp'))
434
+ attachment = obj.get('attachment') or {}
435
+ if obj.get('type') == 'attachment' and attachment.get('type') == 'hook_additional_context' and stamp and abs((stamp - ev).total_seconds()) <= 180 and re.search(re.escape(marker) + r'(?=[, )])', json.dumps(attachment)):
436
+ delivered = True
437
+ break
438
+ except OSError:
439
+ return result
440
+ if not old_seen or not delivered:
441
+ return result
442
+ avoided = int(row.get('tokens_saved') or 0)
443
+ if avoided <= 0:
444
+ return result
445
+ from _measure import compaction_survival
446
+ old_model, old_largest = (old_latest[1], old_latest[2]) if old_latest else (None, 0)
447
+ if compactions is None:
448
+ compactions = compaction_survival.user_history(m, ev)
449
+ survival = compaction_survival.for_event(compactions, ev, avoided)
450
+ if survival.usable:
451
+ # The counterfactual is the old session continuing: its context window
452
+ # is 1M when either session (or the avoided reload itself) passed 200K.
453
+ sizes = [lean_resume_threshold.window_limit(p, lambda usage: _prompt_tokens(m, usage), _resolver(m)) for p in (new_path, old_path)]
454
+ threshold = None if None in sizes else max(sizes + [lean_resume_threshold.window_for(avoided, old_model, _resolver(m))])
455
+ source = 'user_compaction_survival'
456
+ else:
457
+ # Too little history: the old session would have compacted at the
458
+ # user's effective compaction window for its model (env, then
459
+ # modelSettings, then autoCompactWindow, then the model default).
460
+ threshold = lean_resume_threshold.compaction_window(max(avoided, old_largest), old_model, _resolver(m))
461
+ source = 'effective_compact_window'
462
+ if threshold is None:
463
+ return result
464
+ turns, stopped = _walk(new_path, ev.replace(microsecond=0), avoided, m, threshold)
465
+ if not turns and (stopped != 'counterfactual_compaction' or not (_walk(new_path, ev.replace(microsecond=0), 0, m, 2**63)[0] or [])):
466
+ return result
467
+ from _measure import counted_pricing_v5
468
+ key = counted_pricing_v5.resume_rate_key(row.get('detail'))
469
+ old_card = m._counted_exact_card(old_latest[1], tier_data, old_latest[2]) if old_latest and old_latest[1] else None
470
+ if not key or not old_card or not isinstance(old_card.get(key), (int, float)):
471
+ return result
472
+ cards = [m._counted_exact_card(model, tier_data, ctx) if model else None for _dt, model, ctx in turns]
473
+ if any(not card or not isinstance(card.get('cache_read'), (int, float)) for card in cards):
474
+ return result
475
+ try:
476
+ if (old_path.stat().st_mtime_ns, old_path.stat().st_size) != (old_stat.st_mtime_ns, old_stat.st_size) or (new_path.stat().st_mtime_ns, new_path.stat().st_size) != (new_stat.st_mtime_ns, new_stat.st_size):
477
+ return result
478
+ except OSError:
479
+ return result
480
+ weights = [survival.weight(ctx) if survival.usable else 1.0 for _dt, _model, ctx in turns]
481
+ result.update(eligible=True, receiver=receiver, oneshot_usd=round(avoided * old_card[key] / 1e6, 6), turns=len(turns),
482
+ carry_tokens=int(round(sum(avoided * w for w in weights))),
483
+ carry_cost_usd=round(sum(avoided * w * card['cache_read'] / 1e6 for w, card in zip(weights, cards)), 6),
484
+ weighted_turns=round(sum(weights), 4), compactions_above=survival.above,
485
+ stopped_by=stopped, threshold_source=source)
486
+ return result
487
+
488
+
489
+ def verified_summary(days=30, since=None, db_path=None):
490
+ """Estimated reload and carry only for receiver-linked, stopped sessions."""
491
+ m = _m()
492
+ tier_data = m.PRICING_TIERS.get(m._load_pricing_tier(), m.PRICING_TIERS['anthropic'])
493
+ out = {'events': 0, 'tokens_saved': 0, 'cost_saved_usd': 0.0, 'evidence': 'estimated'}
494
+ try:
495
+ from _measure import lean_resume_receivers
496
+ conn = _connect(db_path, m)
497
+ try: links = lean_resume_receivers.resolved(conn)
498
+ finally: conn.close()
499
+ except Exception:
500
+ links = {}
501
+ from _measure import compaction_survival
502
+ compactions = None
503
+ for row in _events(days=days, since=since, db_path=db_path):
504
+ if compactions is None:
505
+ compactions = compaction_survival.user_history(m, _event_dt(m, row.get('timestamp')))
506
+ if 'receiver=' not in (row.get('detail') or ''):
507
+ receiver = links.get(row.get('id'))
508
+ if not receiver:
509
+ continue
510
+ row = dict(row, detail=(row.get('detail') or '') + ' receiver=' + receiver)
511
+ score = _score_verified_event(row, m, tier_data, compactions)
512
+ if not score['eligible']:
513
+ continue
514
+ out['events'] += 1
515
+ out['tokens_saved'] += max(0, int(row.get('tokens_saved') or 0)) + score['carry_tokens']
516
+ out['cost_saved_usd'] += score['oneshot_usd'] + score['carry_cost_usd']
517
+ out['cost_saved_usd'] = round(out['cost_saved_usd'], 6)
518
+ return out