@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,287 @@
1
+ """Coordinate upgrade-drain processes without expiring a live worker."""
2
+ import os
3
+ import itertools
4
+ import re
5
+ import sqlite3
6
+ import tempfile
7
+ import time
8
+ from contextlib import contextmanager
9
+
10
+ from hook_provenance import _exclusive
11
+ from .lease_candidate_cleanup import owner_is_gone
12
+
13
+
14
+ def _marker(facade):
15
+ return facade.SNAPSHOT_DIR / facade._UPGRADE_DRAIN_LOCK_NAME
16
+
17
+
18
+ def _write_marker(marker, pid, exclusive=False):
19
+ fd, name = tempfile.mkstemp(prefix="." + marker.name + "." + str(os.getpid()) + ".", dir=str(marker.parent))
20
+ try:
21
+ with os.fdopen(fd, "w") as handle:
22
+ handle.write(str(pid))
23
+ handle.flush()
24
+ os.fsync(handle.fileno())
25
+ if exclusive:
26
+ os.link(name, marker)
27
+ else:
28
+ os.replace(name, marker)
29
+ finally:
30
+ try:
31
+ os.unlink(name)
32
+ except FileNotFoundError:
33
+ pass
34
+
35
+
36
+ def _clean_temporaries(facade, marker):
37
+ prefix = "." + marker.name + "."
38
+ deadline = time.monotonic() + 0.025
39
+ try:
40
+ with os.scandir(marker.parent) as entries:
41
+ for entry in entries:
42
+ if time.monotonic() >= deadline:
43
+ break
44
+ if not entry.name.startswith(prefix):
45
+ continue
46
+ parts = entry.name[len(prefix):].split(".")
47
+ if (len(parts) != 2 or not parts[0].isdigit() or len(parts[1]) != 8
48
+ or any(c not in "abcdefghijklmnopqrstuvwxyz0123456789_" for c in parts[1])):
49
+ continue
50
+ try:
51
+ if (entry.is_file(follow_symlinks=False) and entry.stat(follow_symlinks=False).st_mtime < time.time() - 86400
52
+ and owner_is_gone(int(parts[0]))):
53
+ os.unlink(entry.path)
54
+ except OSError:
55
+ continue
56
+ except OSError:
57
+ pass
58
+
59
+
60
+ def claim(facade):
61
+ marker = _marker(facade)
62
+ try:
63
+ marker.parent.mkdir(parents=True, exist_ok=True)
64
+ with _exclusive(marker.with_name(marker.name + ".claim"), timeout=0.05) as held:
65
+ if not held:
66
+ return False
67
+ _clean_temporaries(facade, marker)
68
+ if marker.exists():
69
+ age = time.time() - marker.stat().st_mtime
70
+ try:
71
+ pid = int(marker.read_text(encoding="utf-8"))
72
+ except (ValueError, OSError):
73
+ pid = 0
74
+ if age < 1 or (pid > 0 and not owner_is_gone(pid)):
75
+ return False
76
+ marker.unlink()
77
+ _write_marker(marker, os.getpid(), exclusive=True)
78
+ return True
79
+ except OSError:
80
+ return False
81
+
82
+
83
+ def publish_child(facade, child_pid):
84
+ marker = _marker(facade)
85
+ try:
86
+ with _exclusive(marker.with_name(marker.name + ".claim"), timeout=0.05) as held:
87
+ if held and marker.read_text(encoding="utf-8") == str(os.getpid()):
88
+ _write_marker(marker, child_pid)
89
+ except OSError:
90
+ pass
91
+
92
+
93
+ def release(facade):
94
+ marker = _marker(facade)
95
+ try:
96
+ with _exclusive(marker.with_name(marker.name + ".claim"), timeout=0.05) as held:
97
+ if held and marker.read_text(encoding="utf-8") == str(os.getpid()):
98
+ marker.unlink()
99
+ except OSError:
100
+ pass
101
+
102
+
103
+ @contextmanager
104
+ def running(facade):
105
+ marker = _marker(facade)
106
+ try:
107
+ marker.parent.mkdir(parents=True, exist_ok=True)
108
+ except OSError:
109
+ yield False
110
+ return
111
+ with _exclusive(marker.with_name(marker.name + ".running"), timeout=0) as held:
112
+ yield held
113
+
114
+
115
+ def retry_ready(raw, key, now):
116
+ parts = (raw or "").split(":")
117
+ if len(parts) < 2 or parts[0] != key:
118
+ return True, 0
119
+ try:
120
+ attempts = max(0, int(parts[1]))
121
+ last = float(parts[2]) if len(parts) > 2 else 0
122
+ except ValueError:
123
+ return True, 0
124
+ age = now - last
125
+ delay = min(300, 2 ** min(attempts, 9))
126
+ return not (0 <= age < delay), attempts
127
+
128
+
129
+ def transcript_progress(conn):
130
+ conn.execute("CREATE TABLE IF NOT EXISTS transcript_backfill_progress "
131
+ "(session_uuid TEXT PRIMARY KEY, size INTEGER NOT NULL, mtime_ns INTEGER NOT NULL)")
132
+ return {sid: [size, mtime] for sid, size, mtime in conn.execute(
133
+ "SELECT session_uuid, size, mtime_ns FROM transcript_backfill_progress")}
134
+
135
+
136
+ def commit_transcript(conn, session_uuid, stamp):
137
+ conn.execute("INSERT INTO transcript_backfill_progress (session_uuid, size, mtime_ns) VALUES (?, ?, ?) "
138
+ "ON CONFLICT(session_uuid) DO UPDATE SET size=excluded.size, mtime_ns=excluded.mtime_ns",
139
+ (session_uuid, stamp[0], stamp[1]))
140
+ conn.commit()
141
+
142
+
143
+ def commit_marker_cursor(conn, key, cursor):
144
+ conn.execute("INSERT INTO token_optimizer_meta (key, value) VALUES (?, ?) "
145
+ "ON CONFLICT(key) DO UPDATE SET value=excluded.value WHERE token_optimizer_meta.value < excluded.value",
146
+ (key, cursor))
147
+ conn.commit()
148
+
149
+
150
+ def commit_drain_session(conn):
151
+ if os.environ.get("TOKEN_OPTIMIZER_UPGRADE_DRAIN", "").strip() == "1":
152
+ conn.commit()
153
+
154
+
155
+ def backfill_pending(stats):
156
+ return bool(stats.get("pending") or any(
157
+ (value.get("pending") if isinstance(value, dict) else value)
158
+ for key, value in stats.items() if key.endswith("error") or isinstance(value, dict)))
159
+
160
+
161
+ _SESSION_WRITE = re.compile(r'^\s*(?:INSERT(?:\s+OR\s+\w+)?\s+INTO|UPDATE(?:\s+OR\s+\w+)?|DELETE\s+FROM)\s+["`\[]?session_log(?=[\s(\]`";]|$)', re.I)
162
+
163
+
164
+ class _RawConnection:
165
+ def __init__(self, conn):
166
+ self.conn = conn
167
+
168
+ def execute(self, sql, parameters=()):
169
+ return sqlite3.Connection.execute(self.conn, sql, parameters)
170
+
171
+ def executemany(self, sql, parameters):
172
+ return sqlite3.Connection.executemany(self.conn, sql, parameters)
173
+
174
+
175
+ class SessionLogConnection(sqlite3.Connection):
176
+ """Apply the bounded retry to direct session_log writes from every adapter."""
177
+ def execute(self, sql, parameters=()):
178
+ if _SESSION_WRITE.match(sql):
179
+ result = session_write(self, sql, parameters)
180
+ if result is None:
181
+ raise sqlite3.OperationalError("session_log write deferred: database is locked")
182
+ return result
183
+ return super().execute(sql, parameters)
184
+
185
+ def executemany(self, sql, parameters):
186
+ if _SESSION_WRITE.match(sql):
187
+ result = session_write(self, sql, parameters, many=True)
188
+ if result is None:
189
+ raise sqlite3.OperationalError("session_log write deferred: database is locked")
190
+ return result
191
+ return super().executemany(sql, parameters)
192
+
193
+
194
+ def session_write(conn, sql, parameters, budget_seconds=0.3, many=False):
195
+ """Retry a session-row mutation briefly; None leaves it for the next pass."""
196
+ raw = _RawConnection(conn) if isinstance(conn, SessionLogConnection) else conn
197
+ previous = raw.execute("PRAGMA busy_timeout").fetchone()[0]
198
+ deadline = time.monotonic() + budget_seconds
199
+ raw.execute("PRAGMA busy_timeout=50")
200
+ source = iter(parameters) if many else None
201
+ try:
202
+ for attempt in range(6):
203
+ try:
204
+ if not many:
205
+ return raw.execute(sql, parameters)
206
+ batch, source = itertools.tee(source)
207
+ if conn.isolation_level is not None and not conn.in_transaction:
208
+ raw.execute("BEGIN")
209
+ raw.execute("SAVEPOINT to_session_write")
210
+ try:
211
+ result = raw.executemany(sql, batch)
212
+ except BaseException:
213
+ raw.execute("ROLLBACK TO to_session_write")
214
+ raw.execute("RELEASE to_session_write")
215
+ raise
216
+ raw.execute("RELEASE to_session_write")
217
+ return result
218
+ except sqlite3.OperationalError as exc:
219
+ if "locked" not in str(exc).lower() and "busy" not in str(exc).lower():
220
+ raise
221
+ remaining = deadline - time.monotonic()
222
+ if remaining <= 0:
223
+ return None
224
+ time.sleep(min(remaining, 0.01 * (2 ** attempt)))
225
+ return None
226
+ finally:
227
+ raw.execute("PRAGMA busy_timeout=" + str(int(previous)))
228
+
229
+
230
+ class DailyUpdates:
231
+ """Commit each completed session in a drain; keep hook passes batched."""
232
+ def __init__(self, conn, facade):
233
+ self.conn = conn
234
+ self.facade = facade
235
+ self.pending = []
236
+ self.count = 0
237
+ self.immediate = facade._collect_drain_mode() == "full"
238
+
239
+ def append(self, row):
240
+ self.pending.append(row)
241
+ if self.immediate and self.facade._retry_db_operation(self.conn, self.flush) is None:
242
+ raise self.facade.sqlite3.OperationalError("daily backfill remained locked")
243
+
244
+ def flush(self):
245
+ count = len(self.pending)
246
+ result = session_write(self.conn,
247
+ "UPDATE session_log SET daily_usage_json=?, session_uuid=COALESCE(session_uuid, ?), "
248
+ "first_activity_day=?, last_activity_day=?, date=?, parent_daily_usage_json=?, "
249
+ "daily_calls_json=?, daily_metrics_json=? WHERE jsonl_path=? AND daily_usage_json IS NULL", self.pending, many=True)
250
+ if result is None:
251
+ raise sqlite3.OperationalError("database is locked")
252
+ self.conn.commit()
253
+ self.pending.clear()
254
+ self.count += count
255
+ return count
256
+
257
+
258
+ def counted_backfill_all(facade, conn, quiet):
259
+ stats = facade._update_counted_cumulative(conn, max_sessions=10**9, deadline_seconds=None, quiet=quiet)
260
+ marker_total = {"files_scanned": 0, "rows_written": 0, "done": False}
261
+
262
+ def cursor():
263
+ try:
264
+ row = conn.execute("SELECT value FROM token_optimizer_meta WHERE key=?",
265
+ (facade._COUNTED_META_MARKER_CURSOR,)).fetchone()
266
+ return row[0] if row else ""
267
+ except facade.sqlite3.Error:
268
+ return None
269
+
270
+ seen = {cursor()}
271
+ for _ in range(1000):
272
+ marker = facade._counted_marker_backfill(conn, max_files=500, deadline_seconds=None, quiet=quiet)
273
+ marker_total["files_scanned"] += int(marker.get("files_scanned", 0) or 0)
274
+ marker_total["rows_written"] += int(marker.get("rows_written", 0) or 0)
275
+ marker_total["done"] = bool(marker.get("done"))
276
+ if marker_total["done"] or not marker.get("files_scanned"):
277
+ break
278
+ current = cursor()
279
+ if current in seen:
280
+ break
281
+ seen.add(current)
282
+ stats.update({"marker_files_scanned": marker_total["files_scanned"],
283
+ "marker_rows_written": marker_total["rows_written"],
284
+ "marker_backfill_done": marker_total["done"],
285
+ "rows_removed_no_transcript": facade._purge_counted_without_transcripts(conn)})
286
+ stats["pricing_coverage"] = facade._counted_rollup_rows(facade._counted_stored_rows(conn).values(), conn)
287
+ return stats
@@ -0,0 +1,69 @@
1
+ """Price a weekly activity window while reporting missing transcript coverage."""
2
+
3
+
4
+ def price(facade, conn, start, end, tier):
5
+ paths = conn.execute(
6
+ "SELECT jsonl_path, date, last_activity_day, cost_usd FROM session_log "
7
+ "WHERE input_tokens IS NOT NULL AND COALESCE(is_sidechain,0)=0").fetchall()
8
+ known = {str(row[0]) for row in paths}
9
+ for path, _mtime, _ in facade._find_all_jsonl_files(None):
10
+ if str(path) not in known:
11
+ paths.append((str(path), '', None, None))
12
+ known.add(str(path))
13
+ rows, missing = [], 0
14
+ costs, missing_cost, cost_complete = 0.0, 0.0, True
15
+ request_ledger = {}
16
+ for name, recorded_date, last_day, recorded_cost in paths:
17
+ path = facade.Path(name)
18
+ if not path.exists():
19
+ if ((last_day or recorded_date) and str(last_day or recorded_date) < start.date().isoformat()) or (recorded_date and str(recorded_date) > end.date().isoformat()):
20
+ continue
21
+ missing += 1
22
+ if recorded_cost is None:
23
+ cost_complete = False
24
+ else:
25
+ missing_cost += max(0.0, float(recorded_cost))
26
+ continue
27
+ children = facade._find_subagent_jsonl_files(path)
28
+ parsed = facade._parse_session_jsonl(path, window_start=start, window_end=end)
29
+ if parsed and parsed.get('is_sidechain'):
30
+ continue
31
+ if parsed:
32
+ parsed = facade._parsed_net_of_ledger(parsed, request_ledger)
33
+ if not parsed:
34
+ parsed = {'total_input_tokens': 0, 'total_output_tokens': 0,
35
+ 'total_cache_create_1h': 0, 'total_cache_create_5m': 0,
36
+ 'cache_hit_rate': 0, 'model_usage': {}, 'api_calls': 0,
37
+ 'message_count': 0}
38
+ inp, out = parsed['total_input_tokens'], parsed['total_output_tokens']
39
+ cw1, cw5 = parsed['total_cache_create_1h'], parsed['total_cache_create_5m']
40
+ child_cache_read = 0
41
+ for child in children:
42
+ cp = facade._parse_session_jsonl(child, window_start=start, window_end=end)
43
+ if cp:
44
+ cp = facade._parsed_net_of_ledger(cp, request_ledger)
45
+ inp += cp['total_input_tokens']
46
+ out += cp['total_output_tokens']
47
+ cw1 += cp['total_cache_create_1h']
48
+ cw5 += cp['total_cache_create_5m']
49
+ child_cache_read += cp['total_cache_read']
50
+ if not parsed['api_calls'] and inp + out == 0:
51
+ continue
52
+ if recorded_cost is None:
53
+ cost_complete = False
54
+ else:
55
+ costs += max(0.0, float(recorded_cost))
56
+ usage = facade.json.dumps(parsed['model_usage'])
57
+ hit = parsed['cache_hit_rate'] if parsed['api_calls'] else child_cache_read / inp if inp else 0
58
+ rows.append((inp, out, cw5, cw1, hit, usage, usage,
59
+ parsed['api_calls'], parsed['message_count']))
60
+ total = len(rows) + missing
61
+ cost_share = missing_cost / (costs + missing_cost) if cost_complete and costs + missing_cost > 0 else None
62
+ # Beyond 5% missing, a partial workload is too incomplete to headline.
63
+ if not total or missing / total > 0.05 or (cost_share is not None and cost_share > 0.05):
64
+ return None
65
+ result = facade._price_parent_rows(rows, tier)
66
+ if result:
67
+ result['coverage'] = {'priced_sessions': len(rows), 'total_sessions': total,
68
+ 'missing_recorded_cost_share': cost_share}
69
+ return result
@@ -106,38 +106,9 @@ def log_tool_use(store, tool_name: str, command: str = "", has_error: bool = Fal
106
106
  Current detected mode string, or None on failure
107
107
  """
108
108
  try:
109
- bucket = classify_tool(tool_name, command)
110
- conn = store._connect()
111
-
112
- conn.execute(
113
- "INSERT INTO activity_log (tool_name, tool_bucket, has_error, timestamp) "
114
- "VALUES (?, ?, ?, ?)",
115
- (tool_name[:64], bucket, 1 if has_error else 0, time.time()),
116
- )
117
-
118
- rows = conn.execute(
119
- "SELECT tool_bucket, has_error FROM activity_log "
120
- "ORDER BY id DESC LIMIT ?",
121
- (_WINDOW_SIZE,),
122
- ).fetchall()
123
-
124
- row_count = conn.execute("SELECT COUNT(*) FROM activity_log").fetchone()[0]
125
- if row_count > _PRUNE_THRESHOLD:
126
- conn.execute(
127
- "DELETE FROM activity_log WHERE id NOT IN "
128
- "(SELECT id FROM activity_log ORDER BY id DESC LIMIT ?)",
129
- (_PRUNE_KEEP,),
130
- )
131
-
132
- recent_buckets = [r[0] for r in rows]
133
- has_recent_errors = any(r[1] for r in rows)
134
- mode = detect_mode(recent_buckets, has_recent_errors)
135
-
136
- conn.execute(
137
- "INSERT OR REPLACE INTO session_meta (key, value) VALUES (?, ?)",
138
- ("current_mode", mode),
139
- )
140
- conn.commit()
141
- return mode
109
+ from _measure import session_store_spool
110
+ session_store_spool.enqueue(store, {"kind": "activity", "tool_name": tool_name[:64],
111
+ "bucket": classify_tool(tool_name, command), "has_error": int(bool(has_error)), "timestamp": time.time()})
112
+ return store.get_meta("current_mode") if store._conn is not None else None
142
113
  except Exception:
143
114
  return None
@@ -57,6 +57,9 @@ _PAYLOAD_MODULES = (
57
57
  "plugin_env.py",
58
58
  "bash_hook.py",
59
59
  "bash_compress.py",
60
+ "post_run_classify.py",
61
+ "preserved_reinject.py",
62
+ "bash_search_results.py",
60
63
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
61
64
  "bash_whitelist.py",
62
65
  "command_filters.py",
@@ -68,6 +71,9 @@ _PAYLOAD_MODULES = (
68
71
  # credential_patterns: bash_compress's credential-preservation patterns
69
72
  # (the inline fallback misses e.g. ghp_/github_pat_ tokens, #171).
70
73
  "credential_patterns.py",
74
+ # credential_patterns imports this at module import time (URL family split
75
+ # under the 1,000-line ratchet); missing = import failure in the payload.
76
+ "credential_url_patterns.py",
71
77
  )
72
78
 
73
79
 
@@ -1472,11 +1472,10 @@ def archive_result(quiet: bool = False) -> None:
1472
1472
  print("[Tool Archive] Missing tool_use_id or session_id, skipping.", file=sys.stderr)
1473
1473
  return
1474
1474
 
1475
- # Map tool_use_id to a filesystem-safe archive key. Unsafe characters (+,
1476
- # space, /, ., ') used to skip archiving entirely — the full result passed
1477
- # through uncompressed with no expand path and nothing on disk. A
1478
- # deterministic digest keeps the archive, satisfies expand's own key
1479
- # validation, and makes path traversal impossible by construction.
1475
+ if '__' in tool_name and not _is_archive_exempt(tool_name):
1476
+ from _measure.mcp_archive_tripwire import decide
1477
+ if decide(TRENDS_DB, tool_name, active=os.environ.get('TOKEN_OPTIMIZER_MCP_ARCHIVE_TRIPWIRE') == 'active'):
1478
+ return
1480
1479
  raw_tool_use_id = tool_use_id
1481
1480
  tool_use_id = _safe_archive_key(tool_use_id)
1482
1481
  if tool_use_id != raw_tool_use_id and not quiet:
@@ -1671,10 +1670,7 @@ def archive_result(quiet: bool = False) -> None:
1671
1670
  if store is not None:
1672
1671
  store.close()
1673
1672
 
1674
- # Allowlisted tools are documented large-payload
1675
- # fetchers: skip the replacement so the full verbatim result reaches
1676
- # context. It's still archived to disk above, so `expand <id>` works —
1677
- # same treatment as _AGENT_RESULT_TOOL_NAMES (archive, don't replace).
1673
+ # Allowlisted tools serve their full result.
1678
1674
  if "__" in tool_name and _is_archive_exempt(tool_name):
1679
1675
  if not quiet:
1680
1676
  print(f"[Tool Archive] {tool_name} is allowlisted; serving full result (archived for expand).", file=sys.stderr)
@@ -1691,7 +1687,8 @@ def archive_result(quiet: bool = False) -> None:
1691
1687
 
1692
1688
  if "__" in tool_name:
1693
1689
  output_type = _detect_output_type(safe_response)
1694
- preview = _compress_mcp_preview(safe_response, output_type)
1690
+ from _measure.mcp_archive_tripwire import structured_preview
1691
+ preview = structured_preview(safe_response, breaks_cluster=_breaks_cluster)
1695
1692
  suffix = f" ({output_type})" if output_type != "text" else ""
1696
1693
  if original_char_count > _ARCHIVE_MAX_SIZE:
1697
1694
  replacement = preview + (
@@ -1706,15 +1703,12 @@ def archive_result(quiet: bool = False) -> None:
1706
1703
  original_tokens = int(original_char_count / CODE_CHARS_PER_TOKEN)
1707
1704
  replacement_tokens = int(len(replacement) / CODE_CHARS_PER_TOKEN)
1708
1705
  tokens_saved = max(0, original_tokens - replacement_tokens)
1709
- _log_savings_event(
1710
- "tool_archive",
1711
- tokens_saved,
1712
- session_id=session_id,
1713
- detail=(
1714
- f"replaced {tool_name} "
1715
- f"({original_char_count:,} chars -> {len(replacement):,} chars)"
1716
- ),
1717
- )
1706
+ detail = f"replaced {tool_name} ({original_char_count:,} chars -> {len(replacement):,} chars)"
1707
+ _log_savings_event("tool_archive", tokens_saved, session_id=session_id, detail=detail)
1708
+ import archive_verify # read back earlier replacements from the transcript, then queue this one
1709
+ archive_verify.verify(TRENDS_DB, session_id)
1710
+ if tokens_saved > 0: archive_verify.record(TRENDS_DB, session_id, raw_tool_use_id, tool_name,
1711
+ original_char_count, len(replacement), hook_input.get("transcript_path"), detail)
1718
1712
  output = json.dumps({
1719
1713
  "hookSpecificOutput": {
1720
1714
  "hookEventName": "PostToolUse",
@@ -1722,6 +1716,8 @@ def archive_result(quiet: bool = False) -> None:
1722
1716
  }
1723
1717
  })
1724
1718
  print(output)
1719
+ from _measure.mcp_archive_tripwire import record
1720
+ record(TRENDS_DB, tool_name, sanitize_sid(session_id), tool_use_id, tokens_saved)
1725
1721
 
1726
1722
 
1727
1723
  if __name__ == "__main__":
@@ -0,0 +1,165 @@
1
+ """Check at the source that an archived tool result was really replaced.
2
+
3
+ The archive hook returns a trimmed replacement and logs "replaced" right
4
+ away. Whether the host honoured the replacement only shows later, in the
5
+ session transcript: the tool_result there is either the pointer or the full
6
+ output. Some host versions ignored the replacement for months while the
7
+ ledger kept claiming the saving, and nothing warned.
8
+
9
+ ``record`` notes each replacement as pending. ``verify`` runs on a later hook
10
+ call in the same session, reads back the tool_result for pending calls from
11
+ the transcript tail, and stores a verdict: ``pointer`` (the saving is real) or
12
+ ``full`` (it is not; the counted view leaves that ledger row out). ``health``
13
+ raises a warning when the newest MIN_STREAK verdicts are all ``full``.
14
+
15
+ Hook hot path: stdlib only, bounded reads, never raises.
16
+ """
17
+ import json
18
+ import os
19
+ import sqlite3
20
+ from datetime import datetime
21
+ from pathlib import Path
22
+
23
+ TABLE = "archive_verifications"
24
+ MIN_STREAK = 3
25
+ TAIL_BYTES = 16 * 1024 * 1024
26
+ MARKER = "Full result archived"
27
+ _SCHEMA = ("CREATE TABLE IF NOT EXISTS " + TABLE + " (tool_use_id TEXT, session_id TEXT, event_id INTEGER, "
28
+ "tool_name TEXT, original_chars INTEGER, pointer_chars INTEGER, transcript_path TEXT, "
29
+ "logged_at TEXT, verdict TEXT, checked_at TEXT, PRIMARY KEY(session_id, tool_use_id))")
30
+
31
+
32
+ def _connect(trends_db, timeout=0.5):
33
+ conn = sqlite3.connect(str(trends_db), timeout=timeout)
34
+ conn.execute("PRAGMA busy_timeout=%d" % int(timeout * 1000))
35
+ conn.execute(_SCHEMA)
36
+ return conn
37
+
38
+
39
+ def record(trends_db, session_id, tool_use_id, tool_name, original_chars, pointer_chars, transcript_path, detail):
40
+ """Note a logged replacement as pending verification. Never raises."""
41
+ if not (session_id and tool_use_id and transcript_path):
42
+ return
43
+ conn = None
44
+ try:
45
+ conn = _connect(trends_db)
46
+ row = conn.execute("SELECT max(id) FROM savings_events WHERE event_type='tool_archive' AND session_id=? AND detail=?",
47
+ (session_id, detail)).fetchone()
48
+ conn.execute("INSERT OR IGNORE INTO " + TABLE + " (tool_use_id, session_id, event_id, tool_name, original_chars, "
49
+ "pointer_chars, transcript_path, logged_at) VALUES (?,?,?,?,?,?,?,?)",
50
+ (tool_use_id, session_id, row[0] if row else None, tool_name, int(original_chars),
51
+ int(pointer_chars), str(transcript_path), datetime.now().isoformat()))
52
+ conn.commit()
53
+ except Exception:
54
+ pass
55
+ finally:
56
+ if conn is not None:
57
+ conn.close()
58
+
59
+
60
+ def _tail_results(path, wanted):
61
+ """{tool_use_id: result text length, has pointer marker} from the transcript tail."""
62
+ found = {}
63
+ with open(path, "rb") as stream:
64
+ size = os.fstat(stream.fileno()).st_size
65
+ if size > TAIL_BYTES:
66
+ stream.seek(size - TAIL_BYTES)
67
+ stream.readline()
68
+ for line in stream:
69
+ if b'"tool_result"' not in line or not any(t.encode() in line for t in wanted):
70
+ continue
71
+ try:
72
+ record = json.loads(line)
73
+ except ValueError:
74
+ continue
75
+ content = (record.get("message") or {}).get("content") if isinstance(record, dict) else None
76
+ for block in content if isinstance(content, list) else []:
77
+ if not isinstance(block, dict) or block.get("type") != "tool_result" or block.get("tool_use_id") not in wanted:
78
+ continue
79
+ value = block.get("content")
80
+ if isinstance(value, list):
81
+ value = "\n".join(b.get("text", "") for b in value if isinstance(b, dict) and b.get("type") == "text")
82
+ if isinstance(value, str):
83
+ found[block["tool_use_id"]] = (len(value), MARKER in value)
84
+ return found
85
+
86
+
87
+ def verdict_for(length, has_marker, original_chars, pointer_chars):
88
+ if has_marker or abs(length - pointer_chars) <= max(100, pointer_chars * 0.1):
89
+ return "pointer"
90
+ if length >= 0.9 * original_chars:
91
+ return "full"
92
+ return None
93
+
94
+
95
+ def verify(trends_db, session_id, limit=50):
96
+ """Judge pending replacements of this session from its transcript. Never raises."""
97
+ if not session_id:
98
+ return 0
99
+ conn = None
100
+ judged = 0
101
+ try:
102
+ conn = _connect(trends_db)
103
+ rows = conn.execute("SELECT tool_use_id, original_chars, pointer_chars, transcript_path FROM " + TABLE +
104
+ " WHERE session_id=? AND verdict IS NULL ORDER BY logged_at LIMIT ?", (session_id, limit)).fetchall()
105
+ if not rows:
106
+ return 0
107
+ found = _tail_results(rows[0][3], {r[0] for r in rows})
108
+ now = datetime.now().isoformat()
109
+ for tool_use_id, original, pointer, _path in rows:
110
+ if tool_use_id not in found:
111
+ continue
112
+ verdict = verdict_for(found[tool_use_id][0], found[tool_use_id][1], original, pointer)
113
+ if verdict:
114
+ conn.execute("UPDATE " + TABLE + " SET verdict=?, checked_at=? WHERE session_id=? AND tool_use_id=?",
115
+ (verdict, now, session_id, tool_use_id))
116
+ judged += 1
117
+ conn.commit()
118
+ except Exception:
119
+ pass
120
+ finally:
121
+ if conn is not None:
122
+ conn.close()
123
+ return judged
124
+
125
+
126
+ def health(conn, min_streak=MIN_STREAK):
127
+ """{'status': ok|warning|unknown, ...} from the newest verdicts."""
128
+ try:
129
+ if not conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (TABLE,)).fetchone():
130
+ return {"status": "unknown", "verified": 0, "full": 0, "full_streak": 0}
131
+ rows = conn.execute("SELECT verdict, checked_at FROM " + TABLE + " WHERE verdict IS NOT NULL "
132
+ "ORDER BY checked_at DESC, rowid DESC LIMIT 200").fetchall()
133
+ except sqlite3.Error:
134
+ return {"status": "unknown", "verified": 0, "full": 0, "full_streak": 0}
135
+ streak = 0
136
+ for verdict, _at in rows:
137
+ if verdict != "full":
138
+ break
139
+ streak += 1
140
+ full = sum(1 for v, _ in rows if v == "full")
141
+ status = "unknown" if not rows else ("warning" if streak >= min_streak else "ok")
142
+ out = {"status": status, "verified": len(rows), "full": full, "full_streak": streak,
143
+ "last_checked": rows[0][1] if rows else None}
144
+ if status == "warning":
145
+ out["message"] = ("The last %d archived tool results stayed in full in the transcript: the host is not "
146
+ "applying archive replacements, and those savings are not counted." % streak)
147
+ return out
148
+
149
+
150
+ def view_filter(alias):
151
+ """SQL clause leaving out archive rows whose transcript kept the full result."""
152
+ return ("NOT EXISTS (SELECT 1 FROM main." + TABLE + " w WHERE w.event_id=" + alias
153
+ + ".id AND w.verdict='full')")
154
+
155
+
156
+ def replacement_check(trends_db):
157
+ """Health of archive replacements for the dashboard and audit. Never raises."""
158
+ try:
159
+ conn = sqlite3.connect(Path(trends_db).resolve().as_uri() + "?mode=ro", uri=True, timeout=1.0)
160
+ try:
161
+ return health(conn)
162
+ finally:
163
+ conn.close()
164
+ except Exception:
165
+ return {"status": "unknown", "verified": 0, "full": 0, "full_streak": 0}