@alexgreensh/token-optimizer 5.13.68 → 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 (182) 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/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -0,0 +1,419 @@
1
+ """Rebuild ledger events from Token Optimizer's own markers in transcripts.
2
+
3
+ Hooks that run somewhere else (a cloud machine, any future remote runtime) log
4
+ their events to a database on that machine. The transcript comes home; the
5
+ events do not. When a session's transcript shows Token Optimizer ran but this
6
+ machine's ledger holds no event for it, the compressions it made are rebuilt
7
+ here from the pointer Token Optimizer itself left in each tool result.
8
+
9
+ Rules:
10
+ * Only Token Optimizer's exact pointer counts (see POINTER_RX). Text that only
11
+ mentions the marker (source code, docs, escaped JSON) does not match,
12
+ because the real pointer is always the tail of the tool result.
13
+ * Qualify sessions by Token Optimizer evidence, never by directory name.
14
+ In mixed sessions, skip markers matching a nearby native event.
15
+ * original tokens come from the size the pointer states (measured);
16
+ compressed tokens from the text actually in the transcript. Both go through
17
+ the shared calibrated estimator, as the hooks themselves log them.
18
+ * Markers with no stated original size are counted, never sized or written.
19
+ * Every row carries origin='transcript_backfill' and a unique backfill_key
20
+ (session uuid + tool_use_id), so a second run inserts nothing.
21
+
22
+ The facade is passed in (helpers and constants), so this module holds no
23
+ import-time state and imports nothing from measure.
24
+ """
25
+
26
+ import json
27
+ import re
28
+ from datetime import datetime, timezone
29
+ from pathlib import Path
30
+
31
+ ORIGIN = "transcript_backfill"
32
+ META_CURSOR = "transcript_backfill_cursor_mixed_v2"
33
+ BASH_FEATURE = "bash_compress_pipeline"
34
+
35
+ # archive_result.build_archive_pointer and the MCP replacement in
36
+ # archive_result.archive_result: a header line stating the original size, the
37
+ # retrieval instruction, then "expand <key>" and the closing bracket, always at
38
+ # the very end of the tool result.
39
+ POINTER_RX = re.compile(
40
+ r"\[Full result archived \((?P<chars>\d{1,3}(?:,\d{3})*|\d+) chars"
41
+ r"(?: \((?P<kind>[a-z]+)\))?(?P<truncated>, truncated to 5MB)?\)"
42
+ r"(?:\.\]| — saved to disk, not lost\.\n(?:[^\n]*\n){0,3}?[^\n]*\bexpand [\w\-]+(?:\]|\n\]))\s*\Z")
43
+
44
+ # Token Optimizer output that states no original size. Counted, never sized.
45
+ UNSIZED_RX = {
46
+ "lines_omitted": re.compile(r"(?m)^\.\.\. \d+ lines omitted(?: \(kept \d+ error/warning lines\))? \.\.\.$"),
47
+ "crossturn_identical": re.compile(r"\A\[Token Optimizer: identical to your previous `"),
48
+ "crossturn_delta": re.compile(r"\A\[Token Optimizer: same as your previous `"),
49
+ "search_results": re.compile(r"\A\[Search results: \d+ matches across \d+ files\. "),
50
+ }
51
+
52
+ # Evidence that Token Optimizer's hooks ran in a session, read only from hook
53
+ # attachments (never from tool output, which can quote anything).
54
+ _HOOK_ATTACHMENTS = ("hook_system_message", "hook_additional_context", "hook_success",
55
+ "hook_non_blocking_error", "hook_cancelled")
56
+ _HOOK_TRACES = ("[Token Optimizer]", "bash_compress_hook budget exceeded")
57
+
58
+
59
+ def _texts(content):
60
+ if isinstance(content, str):
61
+ return [content]
62
+ out = []
63
+ if isinstance(content, list):
64
+ for block in content:
65
+ if isinstance(block, dict) and block.get("type") == "text" and isinstance(block.get("text"), str):
66
+ out.append(block["text"])
67
+ return out
68
+
69
+
70
+ def _hook_trace(attachment):
71
+ if not isinstance(attachment, dict) or attachment.get("type") not in _HOOK_ATTACHMENTS:
72
+ return None
73
+ for field in ("content", "stdout", "stderr"):
74
+ value = attachment.get(field)
75
+ if isinstance(value, str):
76
+ for trace in _HOOK_TRACES:
77
+ if trace in value:
78
+ return trace
79
+ return None
80
+
81
+
82
+ def scan_transcript(path):
83
+ """One pass over a transcript. Never raises.
84
+
85
+ Returns {"traces": {...}, "sized": [event...], "unsized": {name: n},
86
+ "pointer_results": n}. Each sized event: tool_use_id, ts (UTC
87
+ ISO string), tool, model, original_chars, kind, text (the tool result text).
88
+ """
89
+ out = {"traces": {}, "sized": [], "unsized": {}, "pointer_results": 0, "error": None}
90
+ tool_uses = {}
91
+ try:
92
+ with transcript_stream.open_transcript(path) as stream:
93
+ for line in stream:
94
+ is_assistant = '"tool_use"' in line and '"assistant"' in line
95
+ is_result = '"tool_result"' in line
96
+ is_hook = '"attachment"' in line and any(t in line for t in _HOOK_TRACES)
97
+ if not (is_assistant or is_result or is_hook):
98
+ continue
99
+ try:
100
+ record = json.loads(line)
101
+ except ValueError:
102
+ continue
103
+ if not isinstance(record, dict) or record.get("isSidechain"):
104
+ continue
105
+ if is_hook and record.get("type") == "attachment":
106
+ trace = _hook_trace(record.get("attachment"))
107
+ if trace:
108
+ out["traces"][trace] = out["traces"].get(trace, 0) + 1
109
+ continue
110
+ message = record.get("message")
111
+ if not isinstance(message, dict) or not isinstance(message.get("content"), list):
112
+ continue
113
+ if record.get("type") == "assistant":
114
+ model = message.get("model")
115
+ model = model if isinstance(model, str) and model and not model.startswith("<") else None
116
+ for block in message["content"]:
117
+ if isinstance(block, dict) and block.get("type") == "tool_use" and block.get("id"):
118
+ args = block.get("input")
119
+ tool_uses[block["id"]] = (block.get("name"), model, args.get("command") if isinstance(args, dict) else None)
120
+ continue
121
+ if record.get("type") != "user":
122
+ continue
123
+ for block in message["content"]:
124
+ if not (isinstance(block, dict) and block.get("type") == "tool_result"):
125
+ continue
126
+ text = "\n".join(_texts(block.get("content")))
127
+ if not text:
128
+ continue
129
+ match = POINTER_RX.search(text)
130
+ if match:
131
+ out["pointer_results"] += 1
132
+ tool, model, command = tool_uses.get(block.get("tool_use_id"), (None, None, None))
133
+ out["sized"].append({
134
+ "tool_use_id": block.get("tool_use_id"), "ts": record.get("timestamp"),
135
+ "tool": tool, "model": model, "command": command, "kind": match.group("kind"),
136
+ "original_chars": int(match.group("chars").replace(",", "")),
137
+ "truncated": bool(match.group("truncated")), "text": text})
138
+ continue
139
+ for name, rx in UNSIZED_RX.items():
140
+ if rx.search(text):
141
+ out["unsized"][name] = out["unsized"].get(name, 0) + 1
142
+ break
143
+ except OSError as exc:
144
+ out["error"] = type(exc).__name__
145
+ return out
146
+
147
+
148
+ def token_optimizer_ran(scan):
149
+ """True when the transcript carries Token Optimizer's own evidence."""
150
+ return bool(scan["pointer_results"] or scan["traces"])
151
+
152
+
153
+ def local_naive(ts_utc):
154
+ """Ledger timestamps are naive local time (datetime.now()); transcripts are UTC."""
155
+ try:
156
+ value = datetime.fromisoformat(str(ts_utc).replace("Z", "+00:00"))
157
+ except (TypeError, ValueError):
158
+ return None
159
+ if value.tzinfo is None:
160
+ value = value.replace(tzinfo=timezone.utc)
161
+ return value.astimezone().replace(tzinfo=None).isoformat()
162
+
163
+
164
+ def ensure_schema(conn):
165
+ """Additive: origin + backfill_key columns and a unique guard on each table."""
166
+ for table in ("compression_events", "savings_events"):
167
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(%s)" % table)}
168
+ if "origin" not in cols:
169
+ conn.execute("ALTER TABLE %s ADD COLUMN origin TEXT" % table)
170
+ if "backfill_key" not in cols:
171
+ conn.execute("ALTER TABLE %s ADD COLUMN backfill_key TEXT" % table)
172
+ conn.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_%s_backfill_key ON %s (backfill_key) "
173
+ "WHERE backfill_key IS NOT NULL" % (table, table))
174
+
175
+
176
+ def local_event_sessions(conn):
177
+ """Sessions with any ledger row this machine logged itself (any time)."""
178
+ found = set()
179
+ for table in ("savings_events", "compression_events"):
180
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(%s)" % table)}
181
+ where = "WHERE origin IS NULL OR origin != ?" if "origin" in cols else ""
182
+ params = (ORIGIN,) if where else ()
183
+ for uuid, sid in conn.execute("SELECT session_uuid, session_id FROM %s %s" % (table, where), params):
184
+ found.update(v for v in (uuid, sid) if v)
185
+ return found
186
+
187
+
188
+ def unmatched_markers(conn, session_uuid, scan, estimate_tokens, tokens_from_chars):
189
+ """Skip markers with a plausible native row, keeping ambiguous cases conservative."""
190
+ ce = conn.execute("SELECT timestamp, original_tokens, command_pattern FROM compression_events WHERE "
191
+ "(session_uuid=? OR session_id=?) AND (origin IS NULL OR origin!=?) "
192
+ "AND (feature LIKE 'bash_%' OR feature IN ('build_output_compress','crossturn_dedup'))", (session_uuid, session_uuid, ORIGIN)).fetchall()
193
+ se = conn.execute("SELECT timestamp, tokens_saved, detail FROM savings_events WHERE "
194
+ "(session_uuid=? OR session_id=?) AND (origin IS NULL OR origin!=?) "
195
+ "AND event_type='tool_archive'", (session_uuid, session_uuid, ORIGIN)).fetchall()
196
+ def near(stamp, other):
197
+ try:
198
+ return abs((datetime.fromisoformat(stamp) - datetime.fromisoformat(other)).total_seconds()) <= 20
199
+ except (ValueError, TypeError):
200
+ return False
201
+ def same_command(a, b):
202
+ if not a or not b or a == b:
203
+ return True
204
+ try:
205
+ import shlex
206
+ return shlex.split(a) == shlex.split(b)
207
+ except ValueError:
208
+ return False
209
+ missing = []
210
+ for event in scan['sized']:
211
+ stamp = local_naive(event.get('ts'))
212
+ if not stamp or not event.get('tool'):
213
+ continue
214
+ if event['tool'] == 'Bash':
215
+ from .counted_subagents import _stored_command
216
+ command = _stored_command(event['command']) if isinstance(event.get('command'), str) else None
217
+ match = any(near(stamp, ts) and same_command(command, pattern)
218
+ for ts, _orig, pattern in ce)
219
+ else:
220
+ match = any(near(stamp, ts) and (not detail or detail.startswith('replaced ' + event['tool'] + ' ('))
221
+ for ts, _tokens, detail in se)
222
+ if not match:
223
+ missing.append(event)
224
+ return dict(scan, sized=missing)
225
+
226
+
227
+ def build_rows(session_uuid, scan, estimate_tokens, tokens_from_chars, input_rate):
228
+ """(compression rows, savings rows, skipped counts) for one session's sized markers."""
229
+ ce_rows, se_rows = [], []
230
+ skipped = {"no_tool_use_id": 0, "no_timestamp": 0, "no_reduction": 0}
231
+ for event in scan["sized"]:
232
+ if not event["tool_use_id"]:
233
+ skipped["no_tool_use_id"] += 1
234
+ continue
235
+ ts = local_naive(event["ts"])
236
+ if not ts:
237
+ skipped["no_timestamp"] += 1
238
+ continue
239
+ original = int(tokens_from_chars(event["original_chars"]))
240
+ compressed = int(estimate_tokens(event["text"]))
241
+ if original <= compressed:
242
+ skipped["no_reduction"] += 1
243
+ continue
244
+ key = "%s:%s" % (session_uuid, event["tool_use_id"])
245
+ if event["tool"] == "Bash":
246
+ ce_rows.append((ts, session_uuid, BASH_FEATURE, original, compressed,
247
+ round(compressed / original, 4), 1, 1,
248
+ "rebuilt from transcript marker (%s chars)" % format(event["original_chars"], ","),
249
+ session_uuid, event["model"], "measured", ORIGIN, key))
250
+ else:
251
+ saved = original - compressed
252
+ rate = input_rate(event["model"])
253
+ se_rows.append((ts, "tool_archive", saved,
254
+ None if rate is None else saved * rate / 1e6, session_uuid,
255
+ "replaced %s (%s chars -> %s chars)" % (
256
+ event["tool"] or "unknown tool", format(event["original_chars"], ","),
257
+ format(len(event["text"]), ",")),
258
+ event["model"], session_uuid, 0, ORIGIN, key))
259
+ return ce_rows, se_rows, skipped
260
+
261
+
262
+ _CE_INSERT = ("INSERT OR IGNORE INTO compression_events (timestamp, session_id, feature, original_tokens, "
263
+ "compressed_tokens, compression_ratio, quality_preserved, verified, detail, session_uuid, model, "
264
+ "tier, origin, backfill_key) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
265
+ _SE_INSERT = ("INSERT OR IGNORE INTO savings_events (timestamp, event_type, tokens_saved, cost_saved_usd, "
266
+ "session_id, detail, model, session_uuid, unjoinable, origin, backfill_key) "
267
+ "VALUES (?,?,?,?,?,?,?,?,?,?,?)")
268
+
269
+
270
+ def write_rows(conn, ce_rows, se_rows):
271
+ """Insert, then read back by key: returns the number of rows that now exist and were new."""
272
+ keys = [r[-1] for r in ce_rows] + [r[-1] for r in se_rows]
273
+ before = _existing(conn, keys)
274
+ conn.executemany(_CE_INSERT, ce_rows)
275
+ conn.executemany(_SE_INSERT, se_rows)
276
+ after = _existing(conn, keys)
277
+ return len(after - before)
278
+
279
+
280
+ def _existing(conn, keys):
281
+ found = set()
282
+ for i in range(0, len(keys), 400):
283
+ part = keys[i:i + 400]
284
+ marks = ",".join("?" * len(part))
285
+ for table in ("compression_events", "savings_events"):
286
+ found.update(r[0] for r in conn.execute(
287
+ "SELECT backfill_key FROM %s WHERE backfill_key IN (%s)" % (table, marks), part))
288
+ return found
289
+
290
+
291
+ def _cursor(conn):
292
+ conn.execute("CREATE TABLE IF NOT EXISTS token_optimizer_meta (key TEXT PRIMARY KEY, value TEXT)")
293
+ row = conn.execute("SELECT value FROM token_optimizer_meta WHERE key = ?", (META_CURSOR,)).fetchone()
294
+ try:
295
+ value = json.loads(row[0]) if row and row[0] else {}
296
+ except ValueError:
297
+ value = {}
298
+ value = value if isinstance(value, dict) else {}
299
+ from . import upgrade_drain_control
300
+ value.update(upgrade_drain_control.transcript_progress(conn))
301
+ return value
302
+
303
+
304
+ from . import fixture_context, transcript_stream
305
+
306
+
307
+ def candidate_sessions(conn, since_date, is_fixture):
308
+ """Distinct session_log sessions on or after since_date, newest row per session."""
309
+ rows = conn.execute(
310
+ "SELECT session_uuid, jsonl_path FROM session_log WHERE session_uuid IS NOT NULL AND date >= ? "
311
+ "ORDER BY id", (since_date,)).fetchall()
312
+ latest = {}
313
+ for uuid, path in rows:
314
+ if uuid and not is_fixture(uuid) and fixture_context.allowed_path(path):
315
+ latest[uuid] = path or latest.get(uuid)
316
+ return latest
317
+
318
+
319
+ def run(conn, m, since_date, max_files=None, deadline_seconds=None, report=None):
320
+ """Backfill every qualifying session once per transcript change. Fail-open.
321
+
322
+ ``m`` is the measure facade (path resolver, fixture test, estimators, cards).
323
+ ``report`` (a dict) collects per-session detail for audits; leave None in
324
+ the collect pass.
325
+ """
326
+ import time
327
+ stats = {"sessions_considered": 0, "files_scanned": 0, "to_ran_ledger_empty": 0,
328
+ "mixed_sessions": 0, "rows_written": 0, "sized_markers": 0, "unsized_markers": 0,
329
+ "no_transcript": 0, "pending": 0}
330
+ try:
331
+ from token_estimate import estimate_tokens, estimate_tokens_from_bytes
332
+ ensure_schema(conn)
333
+ tier = m.PRICING_TIERS.get(m._load_pricing_tier(), m.PRICING_TIERS["anthropic"])
334
+
335
+ def input_rate(model):
336
+ card = m._counted_exact_card(model, tier) if model else None
337
+ rate = (card or {}).get("input")
338
+ return rate if isinstance(rate, (int, float)) else None
339
+
340
+ cursor = _cursor(conn)
341
+ local = local_event_sessions(conn)
342
+ started = time.monotonic()
343
+ for uuid, logged_path in candidate_sessions(conn, since_date, m._is_fixture_session_id).items():
344
+ stats["sessions_considered"] += 1
345
+ path = Path(logged_path) if logged_path else None
346
+ if path is None or not path.is_file():
347
+ path = m._counted_session_path(conn, uuid)
348
+ try:
349
+ st = path.stat()
350
+ except (AttributeError, OSError):
351
+ stats["no_transcript"] += 1
352
+ continue
353
+ stamp = [st.st_size, st.st_mtime_ns]
354
+ if report is None and cursor.get(uuid) == stamp and not transcript_stream.needs_resume(path):
355
+ continue # unchanged since the last scan
356
+ if (max_files is not None and stats["files_scanned"] >= max_files) or (
357
+ deadline_seconds is not None and time.monotonic() - started > deadline_seconds):
358
+ stats["pending"] += 1
359
+ continue
360
+ stats["files_scanned"] += 1
361
+ scan = scan_transcript(path)
362
+ if scan["error"]:
363
+ continue
364
+ ran = token_optimizer_ran(scan)
365
+ entry = {"path": str(path), "to_ran": ran, "local_events": uuid in local,
366
+ "sized": len(scan["sized"]), "unsized": scan["unsized"], "traces": scan["traces"]}
367
+ if ran and uuid in local:
368
+ stats["mixed_sessions"] += 1
369
+ if ran:
370
+ if uuid not in local: stats["to_ran_ledger_empty"] += 1
371
+ stats["sized_markers"] += len(scan["sized"])
372
+ stats["unsized_markers"] += sum(scan["unsized"].values())
373
+ if uuid in local: scan = unmatched_markers(conn, uuid, scan, estimate_tokens, estimate_tokens_from_bytes)
374
+ ce_rows, se_rows, skipped = build_rows(uuid, scan, estimate_tokens,
375
+ estimate_tokens_from_bytes, input_rate)
376
+ written = write_rows(conn, ce_rows, se_rows)
377
+ stats["rows_written"] += written
378
+ entry.update(rows=len(ce_rows) + len(se_rows), written=written, skipped=skipped)
379
+ if not transcript_stream.needs_resume(path):
380
+ cursor[uuid] = stamp
381
+ from . import upgrade_drain_control
382
+ upgrade_drain_control.commit_transcript(conn, uuid, stamp)
383
+ if report is not None:
384
+ report[uuid] = entry
385
+ conn.execute("INSERT OR REPLACE INTO token_optimizer_meta (key, value) VALUES (?, ?)",
386
+ (META_CURSOR, json.dumps(cursor, separators=(",", ":"))))
387
+ conn.commit()
388
+ except Exception as exc: # fail-open: never break the collect pass
389
+ stats["error"] = type(exc).__name__
390
+ return stats
391
+
392
+
393
+ def collect_pass(conn, m, drain, budgets, quiet=True):
394
+ """The collect-pass hook: same caps and deadline as the marker backfill."""
395
+ if drain == "full":
396
+ max_files, deadline = None, None
397
+ elif drain == "inline":
398
+ max_files, deadline = None, budgets.get("counted_seconds")
399
+ else:
400
+ max_files, deadline = m._COUNTED_MARKER_FILES_PER_PASS, m._COUNTED_PASS_DEADLINE_SECONDS
401
+ import time
402
+ started = time.monotonic()
403
+ stats = run(conn, m, m._COUNTED_LEDGER_ERA_START[:10], max_files=max_files, deadline_seconds=deadline)
404
+ from . import archive_void_evidence
405
+ remaining = None if deadline is None else max(0.0, deadline - (time.monotonic() - started))
406
+ try: stats["archive_void"] = archive_void_evidence.collect(conn, max_sessions=None if drain == "full" else 8, deadline_seconds=remaining)
407
+ except Exception as exc: stats["archive_void_error"] = type(exc).__name__
408
+ from . import compression_fixture_void
409
+ remaining = None if deadline is None else max(0.0, deadline - (time.monotonic() - started))
410
+ try: stats["fixture_void"] = compression_fixture_void.collect(conn, m._counted_event_utc, m.CLAUDE_DIR / "projects", deadline_seconds=remaining)
411
+ except Exception as exc: stats["fixture_void_error"] = type(exc).__name__
412
+ from . import lean_resume_receivers
413
+ remaining = None if deadline is None else max(0.0, deadline - (time.monotonic() - started))
414
+ try: stats["lean_receivers"] = lean_resume_receivers.collect(conn, m._counted_event_utc, max_files=None if drain == "full" else 8, deadline_seconds=remaining)
415
+ except Exception as exc: stats["lean_receivers_error"] = type(exc).__name__
416
+ if not quiet and stats.get("rows_written"):
417
+ print("[Token Optimizer] transcript backfill: %d session(s), %d row(s)."
418
+ % (stats["to_ran_ledger_empty"], stats["rows_written"]))
419
+ return stats
@@ -0,0 +1,228 @@
1
+ """Read Claude transcripts for skill-list and MCP prefix opportunities.
2
+
3
+ Character counts describe text observed in transcripts. Tokens are an
4
+ approximation, not provider billing. Missing evidence never becomes a saving.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import os
10
+ import re
11
+ import statistics
12
+ from datetime import datetime, timedelta, timezone
13
+ from pathlib import Path
14
+
15
+
16
+ def _server(name):
17
+ if not isinstance(name, str) or not name.startswith('mcp__'):
18
+ return None
19
+ parts = name.split('__', 2)
20
+ return parts[1] if len(parts) == 3 and parts[1] else None
21
+
22
+
23
+ def _normalize(name):
24
+ return re.sub(r'[^A-Za-z0-9_-]', '_', name)
25
+
26
+
27
+ def _time(value):
28
+ try:
29
+ parsed = datetime.fromisoformat(value.replace('Z', '+00:00'))
30
+ return parsed.replace(tzinfo=timezone.utc) if parsed.tzinfo is None else parsed
31
+ except (AttributeError, ValueError, TypeError):
32
+ return None
33
+
34
+
35
+ def scan(paths, budget=None, now=None, days=30):
36
+ now = now or datetime.now(timezone.utc)
37
+ cutoff = now - timedelta(days=days)
38
+ listing, samples, used, seen_calls = [], {}, set(), set()
39
+ incomplete = False
40
+ for path in paths:
41
+ path = Path(path)
42
+ tools, instructions = {}, {}
43
+ have_listing = False
44
+ files = [path] + sorted((path.parent / path.stem / 'subagents').glob('*.jsonl'))
45
+ for source in files:
46
+ try:
47
+ with source.open(encoding='utf-8', errors='replace') as stream:
48
+ for line in stream:
49
+ if not any(tag in line for tag in ('"tool_use"', '"skill_listing"', '"deferred_tools_delta"', '"mcp_instructions_delta"')):
50
+ continue
51
+ try:
52
+ record = json.loads(line)
53
+ except (ValueError, TypeError):
54
+ incomplete = True
55
+ continue
56
+ if not isinstance(record, dict):
57
+ continue
58
+ a = record.get('attachment') or {}
59
+ if not isinstance(a, dict):
60
+ continue
61
+ kind = a.get('type')
62
+ stamp = _time(record.get('timestamp'))
63
+ recent = stamp is not None and now - timedelta(days=7) <= stamp <= now
64
+ if source == path and recent and not have_listing and kind == 'skill_listing' and a.get('isInitial') and isinstance(a.get('content'), str):
65
+ listing.append((len(a['content']), a.get('skillCount')))
66
+ have_listing = True
67
+ if source == path and recent and kind in ('deferred_tools_delta', 'mcp_instructions_delta'):
68
+ names = a.get('addedNames') or []
69
+ values = a.get('addedLines' if kind == 'deferred_tools_delta' else 'addedBlocks') or []
70
+ target = tools if kind == 'deferred_tools_delta' else instructions
71
+ for name in a.get('removedNames') or []:
72
+ target.pop(name, None)
73
+ if kind == 'deferred_tools_delta':
74
+ for value in values:
75
+ if isinstance(value, str):
76
+ name = value.split(None, 1)[0] if value.strip() else ''
77
+ if _server(name):
78
+ target[name] = len(value)
79
+ elif len(names) == len(values):
80
+ for name, value in zip(names, values):
81
+ if isinstance(name, str) and isinstance(value, str):
82
+ target[name] = len(value)
83
+ else:
84
+ incomplete = True
85
+ if record.get('type') != 'assistant':
86
+ continue
87
+ message = record.get('message') or {}
88
+ content = message.get('content') if isinstance(message, dict) else []
89
+ if not isinstance(content, list):
90
+ continue
91
+ for item in content:
92
+ if not isinstance(item, dict) or item.get('type') != 'tool_use':
93
+ continue
94
+ server = _server(item.get('name'))
95
+ call_id = item.get('id')
96
+ if server and (stamp is None or cutoff <= stamp <= now):
97
+ if not call_id or call_id not in seen_calls:
98
+ used.add(_normalize(server))
99
+ if call_id:
100
+ seen_calls.add(call_id)
101
+ except OSError:
102
+ incomplete = True
103
+ session = {}
104
+ for name, size in tools.items():
105
+ server = _server(name)
106
+ if server:
107
+ session.setdefault(_normalize(server), [0, 0])[0] += size
108
+ for name, size in instructions.items():
109
+ session.setdefault(_normalize(name), [0, 0])[1] += size
110
+ for server, sizes in session.items():
111
+ samples.setdefault(server, []).append(sizes)
112
+ median = int(statistics.median(size for size, _ in listing)) if listing else None
113
+ try:
114
+ budget = int(budget)
115
+ if budget <= 0:
116
+ budget = None
117
+ except (TypeError, ValueError, OverflowError):
118
+ budget = None
119
+ at_cap = None if median is None or budget is None else median >= budget * .98
120
+ basis = 'configured budget' if at_cap is not None else 'unknown'
121
+ if at_cap is None and median:
122
+ plateau = [(size, count) for size, count in listing if abs(size - median) <= median * .01 and isinstance(count, int) and count > 0]
123
+ counts = [count for _, count in plateau]
124
+ if len(counts) >= 5 and max(counts) >= min(counts) * 1.1:
125
+ at_cap, basis = True, 'observed plateau'
126
+ unused = []
127
+ if not incomplete:
128
+ for server in sorted(set(samples) - used):
129
+ rows = samples[server]
130
+ tool = int(statistics.median(r[0] for r in rows))
131
+ instruction = int(statistics.median(r[1] for r in rows))
132
+ unused.append({'server': server, 'tool_chars': tool, 'instruction_chars': instruction,
133
+ 'estimated_tokens_per_call': (tool + instruction) // 4, 'sessions': len(rows)})
134
+ return {'listing': {'median_chars': median, 'samples': len(listing), 'budget_chars': budget, 'at_cap': at_cap, 'basis': basis},
135
+ 'unused_connectors': unused, 'incomplete': incomplete}
136
+
137
+
138
+ def from_facade(facade, days=30):
139
+ if facade.detect_runtime() != 'claude':
140
+ return {'listing': {'at_cap': None}, 'unused_connectors': [], 'incomplete': False}
141
+ budget = os.environ.get('SLASH_COMMAND_TOOL_CHAR_BUDGET')
142
+ if not budget:
143
+ try:
144
+ settings = json.loads((facade.CLAUDE_DIR / 'settings.json').read_text(encoding='utf-8'))
145
+ budget = (settings.get('env') or {}).get('SLASH_COMMAND_TOOL_CHAR_BUDGET')
146
+ except (OSError, ValueError, TypeError, AttributeError):
147
+ pass
148
+ try:
149
+ return scan([row[0] for row in facade._find_all_jsonl_files(days=days)], budget=budget, days=days)
150
+ except (OSError, ValueError, TypeError):
151
+ return {'listing': {'at_cap': None}, 'unused_connectors': [], 'incomplete': True}
152
+
153
+
154
+ def listing_message(check):
155
+ state = check['listing']
156
+ if state.get('at_cap'):
157
+ prefix = 'Skill listing appears at its budget (stable listing despite changing skill counts). ' if state.get('basis') == 'observed plateau' else 'Skill listing is at its character budget. '
158
+ return (prefix + 'Archiving skills frees ~0 tokens while the cap holds; '
159
+ 'lower SLASH_COMMAND_TOOL_CHAR_BUDGET for shorter descriptions and weaker triggering.')
160
+ if state.get('at_cap') is None:
161
+ return 'Skill-list savings unknown: the effective character budget or transcript listing was not observed.'
162
+ return 'Skill listing is below the observed character budget; archive savings require a before/after measurement.'
163
+
164
+
165
+ def connector_message(check):
166
+ if check.get('incomplete'):
167
+ return 'Unused connectors unknown: some transcript records could not be read.'
168
+ rows = check['unused_connectors']
169
+ if not rows:
170
+ return 'No observed connector qualifies as unused in readable transcripts from the last 30 days.'
171
+ return 'No calls in the last 30 days (observed transcripts; median prefix in recent sessions where present): ' + '; '.join(
172
+ '{}: ~{} tokens per call ({} tool chars, {} instruction chars)'.format(
173
+ r['server'], r['estimated_tokens_per_call'], r['tool_chars'], r['instruction_chars']) for r in rows)
174
+
175
+
176
+ def quick_win(facade, components, skills, check):
177
+ try:
178
+ trends = facade._collect_trends_data(days=30) or {}
179
+ names = set(skills.get('names', []))
180
+ unused = {n for n in trends.get('skills', {}).get('never_used', [])
181
+ if n in names and not facade._is_own_tool_skill(n)}
182
+ if len(unused) >= 3:
183
+ detail = listing_message(check)
184
+ return {'action': 'Review skills not invoked in the window', 'savings': 0,
185
+ 'detail': detail, 'extend': 'Savings require an observed listing change.'}
186
+ except Exception:
187
+ pass
188
+ return None
189
+
190
+
191
+ def coach_patterns(check):
192
+ return [
193
+ {'name': 'Skill listing budget', 'severity': 'info', 'detail': listing_message(check),
194
+ 'fix': 'Review listing evidence before changing skills.', 'savings': 'Not priced'},
195
+ {'name': 'Unused connectors', 'severity': 'info', 'detail': connector_message(check),
196
+ 'fix': 'Review whether observed unused connectors are still needed.', 'savings': 'Estimated prefix tokens only'},
197
+ ]
198
+
199
+
200
+ def unused_savings(components, unused, check):
201
+ if check is not None:
202
+ return listing_message(check)
203
+ measured = 0
204
+ missing = 0
205
+ for name in unused:
206
+ try:
207
+ value = int((components.get('skills_detail', {}).get(name) or {}).get('frontmatter_tokens') or 0)
208
+ except (ValueError, TypeError, OverflowError):
209
+ value = 0
210
+ if value > 0:
211
+ measured += value
212
+ else:
213
+ missing += 1
214
+ if not measured:
215
+ return 'Unknown: per-skill token measurements unavailable for the unused set'
216
+ if missing:
217
+ return '~{:,} tokens measured for the unused set ({} of {} lack per-skill measurement)'.format(measured, missing, len(unused))
218
+ return '~{:,} tokens (measured descriptions of the {} unused skills)'.format(measured, len(unused))
219
+
220
+
221
+ def skill_recommendations(facade, components, trends, usage_basis):
222
+ names = sorted(str(n) for n in (trends or {}).get('skills', {}).get('never_used', [])
223
+ if not facade._is_own_tool_skill(n))
224
+ if len(names) < 2 and (trends or components.get('skills', {}).get('count', 0) <= 10):
225
+ return []
226
+ display = ', '.join(facade._strip_ansi(n) for n in names[:8]) if names else 'Review installed skills.'
227
+ return ['Review skills not invoked (' + usage_basis + '): ' + display + facade._skill_slim_clause(0, 'claude') +
228
+ ' Archive (harder step) only skills you no longer need. Measure the resulting listing change.']