@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
@@ -1942,45 +1942,8 @@ def _compress_search_results(output):
1942
1942
  if not files:
1943
1943
  return output # not file:line format, don't compress
1944
1944
 
1945
- _MAX_PER_FILE = 3
1946
- _MAX_FILES = 20
1947
- result: list[str] = []
1948
- file_count = 0
1949
- file_items = list(files.items())
1950
- for fname, file_lines in file_items:
1951
- if file_count >= _MAX_FILES:
1952
- break
1953
- if len(file_lines) <= _MAX_PER_FILE:
1954
- result.extend(file_lines)
1955
- else:
1956
- result.extend(file_lines[:_MAX_PER_FILE])
1957
- result.append(f" ... {len(file_lines) - _MAX_PER_FILE} more matches in {fname} ...")
1958
- file_count += 1
1959
-
1960
- # Keep EVERY matching filename (cheap) so "does file X match?" stays
1961
- # answerable; only per-line CONTENT past the top-N is dropped, never names.
1962
- if file_count < len(file_items):
1963
- result.append(f"... plus {len(file_items) - file_count} more files with matches "
1964
- f"(filenames + counts, content omitted):")
1965
- for fname, file_lines in file_items[file_count:]:
1966
- result.append(f" {fname}: {len(file_lines)} matches")
1967
-
1968
- if no_file:
1969
- result.append("")
1970
- # "Binary file X matches" lines name a matching file; keep ALL of them so
1971
- # the banner's "a file not listed has NO matches" stays true for binaries.
1972
- binary = [ln for ln in no_file if ln.startswith("Binary file ") and " matches" in ln]
1973
- other = [ln for ln in no_file if not (ln.startswith("Binary file ") and " matches" in ln)]
1974
- result.extend(binary)
1975
- result.extend(other[:10])
1976
- if len(other) > 10:
1977
- result.append(f"... {len(other) - 10} more non-file lines omitted ...")
1978
-
1979
- total_matches = sum(len(v) for v in files.values())
1980
- result.insert(0, f"[Search results: {total_matches} matches across {len(files)} files. "
1981
- f"ALL matching filenames listed; per-line content shown for the top "
1982
- f"{_MAX_FILES}. A file not listed here has NO matches.]")
1983
- return "\n".join(result)
1945
+ from bash_search_results import render_search_results
1946
+ return render_search_results(files, no_file)
1984
1947
 
1985
1948
 
1986
1949
  _PATTERN_HANDLERS = {
@@ -2190,6 +2153,10 @@ def compress(command_str, raw_output, returncode=0, stderr=""):
2190
2153
  patterns on stderr even with exit 0, return raw output verbatim. Never
2191
2154
  compress failure output — the user needs the full signal to debug.
2192
2155
  """
2156
+ from post_run_classify import unsafe_compound_output, echo_boundary_preserved
2157
+ if unsafe_compound_output(command_str):
2158
+ return raw_output
2159
+
2193
2160
  if _looks_like_failure(returncode, stderr):
2194
2161
  return raw_output # fail-open tee: full output, unchanged
2195
2162
 
@@ -2199,15 +2166,8 @@ def compress(command_str, raw_output, returncode=0, stderr=""):
2199
2166
  # Strip ANSI codes (always safe)
2200
2167
  cleaned = _strip_ansi(raw_output)
2201
2168
 
2202
- # PRE-compression token preservation scan (credentials + errors), plus
2203
- # rarity-based needle preservation: a line carrying a distinctive token
2204
- # (UUID/URL/hash/id) that the user is likely grepping FOR must survive the
2205
- # summarizer, or the model re-runs a narrower query and spends back the
2206
- # tokens we just saved. Both feed the shared re-injection path below (capped
2207
- # at _MAX_REINJECTED_LINES, so a needle-dense log still compresses).
2208
- # The git log / find summarizers keep every hash and path themselves, so
2209
- # re-injecting "rare token" lines would only paste raw "commit <hash>" lines
2210
- # back; they keep only the credential/error scan.
2169
+ # Preserve credentials, errors, and distinctive tokens before summarizing.
2170
+ # Git log and find keep their own hashes and paths.
2211
2171
  _summarizer_pattern = False
2212
2172
  try:
2213
2173
  _summarizer_pattern = _detect_pattern(command_str) in ("git_log", "find")
@@ -2216,7 +2176,9 @@ def compress(command_str, raw_output, returncode=0, stderr=""):
2216
2176
  preserved_lines = _find_preserved_lines(cleaned)
2217
2177
  if not _summarizer_pattern:
2218
2178
  preserved_lines = preserved_lines | _find_distinctive_lines(cleaned)
2219
-
2179
+ from preserved_reinject import find_priority_lines, reinject
2180
+ priority_lines = find_priority_lines(cleaned, _ERROR_STDERR_PATTERNS + _FOREIGN_ERROR_PATTERNS)
2181
+ preserved_lines = preserved_lines | priority_lines
2220
2182
  # Detect pattern
2221
2183
  pattern = _detect_pattern(command_str)
2222
2184
  if pattern is None:
@@ -2246,40 +2208,12 @@ def compress(command_str, raw_output, returncode=0, stderr=""):
2246
2208
  except Exception:
2247
2209
  return cleaned # fail open
2248
2210
 
2249
- # Re-inject preserved lines that were stripped by compression.
2250
- # Uses exact-line membership (not substring) so a short preserved
2251
- # line that happens to be contained inside a longer compressed line
2252
- # is still emitted on its own rather than silently folded into the
2253
- # larger line.
2254
- #
2255
- # Cap at _MAX_REINJECTED_LINES: when a credential pattern appears on
2256
- # most lines (e.g. grep for API keys), re-injecting all of them
2257
- # defeats compression. The first N are re-injected; the full original
2258
- # is already archived via progressive disclosure for retrieval.
2211
+ # Cap credential reinjection; the full original remains archived.
2259
2212
  if preserved_lines:
2260
- _MAX_REINJECTED_LINES = max(1, min(20, len(compressed.splitlines()) // 5))
2261
- original_lines = cleaned.splitlines()
2262
- compressed_line_set = set(compressed.splitlines())
2263
- appended: list[str] = []
2264
- injected = 0
2265
- for line_idx in preserved_lines:
2266
- if injected >= _MAX_REINJECTED_LINES:
2267
- break
2268
- if line_idx < len(original_lines):
2269
- preserved_line = original_lines[line_idx]
2270
- if _summarizer_pattern and preserved_line.strip() in compressed:
2271
- continue # already carried by a summary line
2272
- if preserved_line not in compressed_line_set:
2273
- appended.append(preserved_line)
2274
- compressed_line_set.add(preserved_line)
2275
- injected += 1
2276
- if appended:
2277
- if injected < len(preserved_lines):
2278
- appended.append(
2279
- f"... {len(preserved_lines) - injected} more credential-bearing lines "
2280
- f"archived in full original (retrieve via expand key) ..."
2281
- )
2282
- compressed = compressed + "\n" + "\n".join(appended)
2213
+ compressed = reinject(compressed, cleaned, preserved_lines, priority_lines, _summarizer_pattern)
2214
+
2215
+ if not echo_boundary_preserved(command_str, cleaned, compressed):
2216
+ return raw_output
2283
2217
 
2284
2218
  try:
2285
2219
  from token_estimate import estimate_tokens as _est
@@ -2385,7 +2319,7 @@ def main():
2385
2319
 
2386
2320
  # Progressive disclosure: archive the raw original BEFORE compression
2387
2321
  # so the model can retrieve it via `expand <key>` if needed. Fail-open:
2388
- # if archiving fails, compression proceeds without the pointer.
2322
+ # if archiving fails, serve the original instead of a lossy preview.
2389
2323
  _archive_key = None
2390
2324
  if compressed != raw_output and len(raw_output) > 500:
2391
2325
  try:
@@ -2414,6 +2348,11 @@ def main():
2414
2348
  except Exception:
2415
2349
  _archive_key = None
2416
2350
 
2351
+ # Search matches must remain recoverable even below the archive floor
2352
+ # or when the archive write fails. Other handlers keep their contracts.
2353
+ if _archive_key is None and _detect_pattern(command_str) == "search_results":
2354
+ compressed = raw_output
2355
+
2417
2356
  # Record savings to trends.db if compression was meaningful
2418
2357
  try:
2419
2358
  orig_bytes = len(raw_output.encode("utf-8", errors="replace"))
@@ -214,6 +214,14 @@ def _run(payload: dict) -> None:
214
214
  except Exception:
215
215
  pass # Fail open: the raw output stands
216
216
 
217
+ # Control group (TOKEN_OPTIMIZER_HOLDOUT, default 0 = off, see holdout.py): a
218
+ # control session replaces nothing and gets no nudge. What this hook would
219
+ # have done is logged at the opportunity tier. With the variable unset this
220
+ # is one environment lookup and no import.
221
+ if _holdout_control():
222
+ _shadow_bash(command, stdout, exit_code)
223
+ return
224
+
217
225
  # Codex-via-install perf optimization: TOKEN_OPTIMIZER_NO_UPDATED_TOOL_OUTPUT
218
226
  # skips the compression compute entirely. updatedToolOutput is ignored by
219
227
  # Codex anyway (collapse there is via archival), so skipping the compute
@@ -231,22 +239,67 @@ def _run(payload: dict) -> None:
231
239
  print(json.dumps(_payload))
232
240
  return
233
241
 
242
+ # Coverage funnel (counters only, no behaviour change): every result that
243
+ # gets past the checks above ends in exactly one gate row. The closure
244
+ # records the first gate reached and ignores later calls, so no exit path
245
+ # can double count. Fail-open inside coverage_funnel.record().
246
+ _cov_done: list = []
247
+
248
+ def _cov(gate: str, reason: str = "", pattern: str = "", text: str = "",
249
+ removed: int = 0) -> None:
250
+ if _cov_done:
251
+ return
252
+ _cov_done.append(gate)
253
+ _record_coverage(gate, reason, pattern, text, removed)
254
+
234
255
  # Too small to compress
235
256
  if not stdout or len(stdout) < 100:
257
+ _cov("error_or_short", "short", text=stdout or "")
236
258
  if _nudge:
237
259
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
238
260
  return
239
261
 
240
262
  # Detect if the output was ALREADY compressed by PreToolUse bash_hook.
241
263
  if "[Full result archived" in stdout or "[bash_compress]" in stdout:
264
+ _cov("already_compressed", "marker", text=stdout)
242
265
  if _nudge:
243
266
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
244
267
  return
245
268
 
269
+ # A single renderer cannot safely separate output from multiple producers.
270
+ try:
271
+ from post_run_classify import unsafe_compound_output
272
+ if unsafe_compound_output(command):
273
+ _cov("not_read_only", "mixed_output", text=stdout)
274
+ if _nudge:
275
+ _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
276
+ return
277
+ except Exception:
278
+ return # fail open on ambiguous output
279
+
246
280
  # Check pipeline read-only eligibility
281
+ compress_command = command # command used to pick a compressor
282
+ _post_run_shadow = None # effective command, shadow mode only
247
283
  try:
248
284
  from pipeline_analyzer import is_read_only_pipeline
249
285
  is_ro, reason = is_read_only_pipeline(command)
286
+ if not is_ro:
287
+ # W2: the command already ran, so a harmless prefix (`cd /p &&`,
288
+ # `export X=1;`, `git -C /p`) should not hide it from the same
289
+ # pattern-specific compressor its bare form gets. post_run_classify
290
+ # returns that bare form, or None. Shadow mode only measures.
291
+ try:
292
+ from post_run_classify import mode as _prc_mode
293
+ _prc = _prc_mode()
294
+ if _prc != "off":
295
+ from post_run_classify import eligible_effective
296
+ _eff = eligible_effective(command)
297
+ if _eff is not None and _prc == "on":
298
+ is_ro, compress_command = True, _eff
299
+ elif _eff is not None:
300
+ _post_run_shadow = _eff
301
+ except Exception:
302
+ pass # Fail open: the baseline path below runs unchanged
250
303
  if not is_ro:
251
304
  # --- K1: build/test/run output compression (PostToolUse) ---
252
305
  # The command is not read-only, so the standard compression path
@@ -276,15 +329,26 @@ def _run(payload: dict) -> None:
276
329
  _compressed_build = _try_build_output_compress(
277
330
  command, stdout)
278
331
  if _compressed_build is not None:
332
+ _cov("compressed", "build_output", "build_output",
333
+ stdout, _removed_tokens(stdout, _compressed_build))
279
334
  _emit_updated_tool_output(
280
335
  _compressed_build, stderr, nudge=_nudge)
281
336
  return
282
337
  except Exception:
283
338
  pass # Fail open: raw output stands
339
+ _cov("not_read_only", reason, text=stdout)
340
+ if _post_run_shadow is not None:
341
+ try:
342
+ from post_run_classify import shadow_measure
343
+ shadow_measure(command, _post_run_shadow, stdout, stderr,
344
+ exit_code, _stdout_has_error_patterns)
345
+ except Exception:
346
+ pass # Shadow never changes what the model sees
284
347
  if _nudge:
285
348
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
286
349
  return # Not eligible, pass through raw
287
350
  except Exception:
351
+ _cov("not_read_only", "analyzer-error", text=stdout)
288
352
  if _nudge:
289
353
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
290
354
  return # Fail open
@@ -302,10 +366,12 @@ def _run(payload: dict) -> None:
302
366
  _find_preserved_lines,
303
367
  _ERROR_STDERR_PATTERNS,
304
368
  _enforce_baseline_invariant,
369
+ _detect_pattern,
305
370
  )
306
371
 
307
372
  # --- check for failure (exit code or stderr patterns) ---
308
373
  if _looks_like_failure(exit_code, stderr):
374
+ _cov("error_or_short", "failed_command", text=stdout)
309
375
  if _nudge:
310
376
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
311
377
  return # Don't compress failure output
@@ -318,12 +384,13 @@ def _run(payload: dict) -> None:
318
384
  # on stdout. If the pipeline exits 0 but stdout contains error
319
385
  # patterns, pass through raw so the model sees the errors.
320
386
  if _stdout_has_error_patterns(cleaned_stdout):
387
+ _cov("error_or_short", "error_words", text=stdout)
321
388
  if _nudge:
322
389
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
323
390
  return # Error on stdout: pass through raw
324
391
 
325
392
  # Run the standard compression pipeline
326
- compressed = compress(command, cleaned_stdout, returncode=exit_code, stderr=stderr)
393
+ compressed = compress(compress_command, cleaned_stdout, returncode=exit_code, stderr=stderr)
327
394
 
328
395
  # Best single-output representation: the compressed preview when it
329
396
  # actually shrank the output by >=10%, else the raw output.
@@ -344,6 +411,7 @@ def _run(payload: dict) -> None:
344
411
  _log_feature = "crossturn_dedup"
345
412
 
346
413
  if not comp_helped:
414
+ _cov("under_10pct", "read_only", _detect_pattern(command), stdout)
347
415
  if _nudge:
348
416
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
349
417
  return # nothing shrank the output -> pass through raw
@@ -378,6 +446,11 @@ def _run(payload: dict) -> None:
378
446
  except Exception:
379
447
  _archive_key = None
380
448
 
449
+ # Search matches must remain recoverable even below the archive floor
450
+ # or when the archive write fails. Other handlers keep their contracts.
451
+ if _archive_key is None and _detect_pattern(compress_command) == "search_results":
452
+ compressed = stdout
453
+
381
454
  # --- enforce the baseline-size invariant ---
382
455
  # If our compressed preview + archive pointer would exceed what
383
456
  # Claude Code would show as a baseline stub, shrink to fit.
@@ -388,6 +461,10 @@ def _run(payload: dict) -> None:
388
461
 
389
462
  # Log compression event to trends.db
390
463
  _log_event(command, cleaned_stdout, compressed, feature=_log_feature)
464
+ _cov("compressed",
465
+ "crossturn_dedup" if _log_feature == "crossturn_dedup" else "read_only",
466
+ "crossturn_dedup" if _log_feature == "crossturn_dedup" else _detect_pattern(command),
467
+ stdout, _removed_tokens(cleaned_stdout, compressed))
391
468
 
392
469
  # Emit updatedToolOutput to replace what Claude sees. The thrash nudge,
393
470
  # if present, goes out as additionalContext in the same envelope (every
@@ -396,6 +473,7 @@ def _run(payload: dict) -> None:
396
473
  _emit_updated_tool_output(compressed, stderr, nudge=_nudge)
397
474
 
398
475
  except Exception:
476
+ _cov("under_10pct", "hook_error", text=stdout)
399
477
  if _nudge:
400
478
  _emit_updated_tool_output(stdout, stderr, nudge=_nudge)
401
479
  return # Fail open: any error → pass through raw
@@ -610,6 +688,61 @@ def _crossturn_dedup(command: str, output: str, tool_use_id: str = ""):
610
688
  return None
611
689
 
612
690
 
691
+ def _holdout_control() -> bool:
692
+ """True only when the holdout is on and this session is in the control arm."""
693
+ try:
694
+ if not os.environ.get("TOKEN_OPTIMIZER_HOLDOUT", "").strip():
695
+ return False
696
+ from holdout import is_control
697
+ return is_control(os.environ.get("CLAUDE_SESSION_ID", ""))
698
+ except Exception:
699
+ return False
700
+
701
+
702
+ def _shadow_bash(command: str, stdout: str, exit_code: int | None) -> None:
703
+ """Control arm: record what compression would have removed. Emits nothing,
704
+ archives nothing, writes no coverage-funnel row. Fail-open."""
705
+ try:
706
+ from coverage_funnel import classify_result
707
+ verdict = classify_result(command, stdout, is_error=bool(exit_code))
708
+ if verdict["gate"] != "compressed":
709
+ return
710
+ from compression_log import log_compression_event
711
+ from credential_patterns import redact_credentials as _redact
712
+ log_compression_event(
713
+ feature=("build_output_compress" if verdict["reason"] == "build_output"
714
+ else "bash_compress_pipeline"),
715
+ session_id=os.environ.get("CLAUDE_SESSION_ID", ""),
716
+ command_pattern=_redact(command)[:100],
717
+ original_tokens=verdict["tokens"],
718
+ compressed_tokens=max(0, verdict["tokens"] - verdict["removed"]),
719
+ quality_preserved=True, verified=False, tier="opportunity",
720
+ detail="holdout_control",
721
+ )
722
+ except Exception:
723
+ pass
724
+
725
+
726
+ def _removed_tokens(original: str, compressed: str) -> int:
727
+ """Tokens the compressed form saves, never negative. Fail-open to 0."""
728
+ try:
729
+ from coverage_funnel import tokens_of
730
+ return max(0, tokens_of(original) - tokens_of(compressed))
731
+ except Exception:
732
+ return 0
733
+
734
+
735
+ def _record_coverage(gate: str, reason: str, pattern: str, text: str,
736
+ removed: int) -> None:
737
+ """Write one coverage-funnel counter row (see coverage_funnel). Never raises."""
738
+ try:
739
+ from coverage_funnel import record, tokens_of
740
+ record(gate, reason, pattern or "", tokens_of(text), removed,
741
+ os.environ.get("CLAUDE_SESSION_ID", ""))
742
+ except Exception:
743
+ pass
744
+
745
+
613
746
  def _log_event(command: str, original: str, compressed: str,
614
747
  feature: str = "bash_compress_pipeline") -> None:
615
748
  """Log a compression event to trends.db. Fail-open, never raises.
@@ -664,6 +797,9 @@ def _try_build_output_compress(command: str, stdout: str) -> str | None:
664
797
  compressed = _build_compress(command, cleaned_stdout)
665
798
  if not compressed or compressed == cleaned_stdout:
666
799
  return None
800
+ from post_run_classify import echo_boundary_preserved
801
+ if not echo_boundary_preserved(command, cleaned_stdout, compressed):
802
+ return None
667
803
 
668
804
  # Check that compression actually helped by >= 10%
669
805
  from token_estimate import estimate_tokens as _est
@@ -0,0 +1,43 @@
1
+ """Render parsed search matches with explicit per-file and file-count limits."""
2
+
3
+
4
+ def render_search_results(files, no_file):
5
+ _MAX_PER_FILE = 3
6
+ _MAX_FILES = 20
7
+ result: list[str] = []
8
+ file_count = 0
9
+ file_items = list(files.items())
10
+ for fname, file_lines in file_items:
11
+ if file_count >= _MAX_FILES:
12
+ break
13
+ if len(file_lines) <= _MAX_PER_FILE:
14
+ result.extend(file_lines)
15
+ else:
16
+ result.extend(file_lines[:_MAX_PER_FILE])
17
+ result.append(f" ... {len(file_lines) - _MAX_PER_FILE} more matches in {fname} (content omitted) ...")
18
+ file_count += 1
19
+
20
+ # Keep EVERY matching filename (cheap) so "does file X match?" stays
21
+ # answerable; only per-line CONTENT past the top-N is dropped, never names.
22
+ if file_count < len(file_items):
23
+ result.append(f"... plus {len(file_items) - file_count} more files with matches "
24
+ f"(filenames + counts, content omitted):")
25
+ for fname, file_lines in file_items[file_count:]:
26
+ result.append(f" {fname}: {len(file_lines)} matches")
27
+
28
+ if no_file:
29
+ result.append("")
30
+ # "Binary file X matches" lines name a matching file; keep ALL of them so
31
+ # the banner's "a file not listed has NO matches" stays true for binaries.
32
+ binary = [ln for ln in no_file if ln.startswith("Binary file ") and " matches" in ln]
33
+ other = [ln for ln in no_file if not (ln.startswith("Binary file ") and " matches" in ln)]
34
+ result.extend(binary)
35
+ result.extend(other[:10])
36
+ if len(other) > 10:
37
+ result.append(f"... {len(other) - 10} more non-file lines omitted ...")
38
+
39
+ total_matches = sum(len(v) for v in files.values())
40
+ result.insert(0, f"[Search results: {total_matches} matches across {len(files)} files. "
41
+ f"ALL matching filenames listed; up to {_MAX_PER_FILE} matches per file "
42
+ f"shown for the first {_MAX_FILES} files. Other match content omitted.]")
43
+ return "\n".join(result)
@@ -27,7 +27,7 @@ TASK_STATE_VERSION = 2
27
27
  # Bounds: the sidecar is JSON and the .md renderer applies its own budget, but
28
28
  # the extractor itself must stay small enough to serialize cheaply on every
29
29
  # Stop/SessionEnd hook fire.
30
- _MAX_CONSTRAINTS = 12
30
+ _MAX_CONSTRAINTS = 8
31
31
  _MAX_REQUIREMENTS = 20
32
32
  _MAX_FACTS = 8
33
33
  _MAX_CHECKS = 15
@@ -44,7 +44,7 @@ _CONSTRAINT_RE = re.compile(
44
44
  r"\b(?:must(?:n['’]t|\s+not)?|never|always|do(?:es)?\s+not|don['’]t|"
45
45
  r"should(?:\s+not|n['’]t)?|cannot|can['’]t|won['’]t|shall|required|"
46
46
  r"requirement|constraint|forbidden|avoid|only|no\s+more\s+than|"
47
- r"at\s+most|exactly|without|must\s+keep|do\s+not\s+dare)\b",
47
+ r"at\s+most|exactly|without|cap|no|must\s+keep|do\s+not\s+dare)\b",
48
48
  re.IGNORECASE,
49
49
  )
50
50
 
@@ -480,16 +480,13 @@ def render_run_sh(root: Path, pycache: Path, version: str) -> str:
480
480
 
481
481
  # -------------------------------------------------------------------- install
482
482
 
483
- # What the package carries and the install copies. Everything else in the
484
- # extracted tarball (package.json, README, LICENSE files) is copied too; this
485
- # list is what must exist for a usable install.
483
+ # Required files for a usable install; the extracted package carries the rest.
486
484
  _REQUIRED = ("hooks/hooks.json", "hooks/python-launcher.sh", "hooks/run.py",
487
- "skills/token-optimizer/scripts/measure.py") + tuple(
485
+ "skills/token-optimizer/scripts/measure.py", "skills/token-optimizer/scripts/session_store.py", "skills/token-optimizer/scripts/session_store_guard.py") + tuple(
488
486
  "skills/token-optimizer/scripts/_measure/" + name for name in (
489
487
  '__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py',
490
488
  'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py',
491
- 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py',
492
- )
489
+ 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', 'dashboard_history.py', 'weekly_activity.py', 'headline.py', 'counted_position.py', 'counted_pricing_v5.py', 'transcript_backfill.py', 'counted_subagents.py', 'lean_resume_threshold.py', 'output_reread.py', 'session_effect.py', 'structural_ledger.py', 'structural_archives.py', 'structural_listing.py', 'structural_report.py', 'structural_seed.py', 'structural_value.py', 'rework_metrics.py', 'session_best.py', 'savings_story.py', 'counted_orphans.py', 'counted_cap.py', 'archive_void_evidence.py', 'cost_per_message_trend.py', 'lean_resume_receivers.py', 'routing_period.py', 'fixture_context.py', 'transcript_product.py', 'periphery_exposure.py', 'structure_funnel.py', 'setup_attachment_counter.py', 'first_read_outcomes.py', 'setup_budget_monitor.py', 'setup_connector_ledger.py', 'first_call_context.py', 'timestamp_cache.py', 'token_type_split.py', 'evidence_parallel.py', 'ttl_period.py', 'first_read_revive.py', 'mcp_archive_tripwire.py', 'compaction_survival.py', 'archive_void_codex.py', 'compression_fixture_void.py', 'feature_health.py', 'archive_health.py', 'coverage_report.py', 'file_refetch.py', 'holdout_report.py', 'structural_dedupe.py', 'setup_step.py', 'baseline_provenance.py', 'own_price_card.py', 'transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py', 'keepwarm_safety.py', 'keepwarm_economics.py', 'keepwarm_linux.py', 'keepwarm_prefix.py', 'keepwarm_response_filter.py', 'keepwarm_guard.py', 'keepwarm_guard_server.py', 'keepwarm_fork.py', 'mod_action_booking.py', 'mod_compaction_booking.py', 'mod_fresh_booking.py', 'quality_continuity.py', 'quality_checkpoint.py', 'codex_quality.py', 'lease_candidate_cleanup.py', 'session_store_spool.py', 'upgrade_drain_control.py', 'compression_scan_checkpoint.py', 'status_bar_lock.py', 'session_flush_lock.py', 'context_reset_marker.py', 'holdout_fallback.py', 'dashboard_heal_claim.py')
493
490
  )
494
491
 
495
492