@alexgreensh/token-optimizer 5.13.69 → 5.13.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/token-optimizer/assets/dashboard.html +399 -509
  11. package/skills/token-optimizer/assets/savings_story.js +661 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  14. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  15. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  16. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  18. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  19. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  20. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  21. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  23. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  24. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  25. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  26. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  28. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  29. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  30. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  31. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  36. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  37. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  38. package/skills/token-optimizer/scripts/_measure/dashboard.py +87 -151
  39. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  40. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  41. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  42. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  43. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  44. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  46. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  47. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  48. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  50. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  54. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  55. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  56. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  57. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  58. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  59. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  60. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  61. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  62. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  63. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  64. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  65. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  66. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  67. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  68. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  69. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  70. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  71. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  72. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  73. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  74. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  75. package/skills/token-optimizer/scripts/_measure/savings.py +431 -863
  76. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  77. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  78. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  79. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  80. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  81. package/skills/token-optimizer/scripts/_measure/sessions.py +96 -196
  82. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  83. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  84. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  85. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  86. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  91. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  92. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  93. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  94. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  95. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  96. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  97. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  98. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  99. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  100. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  101. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  102. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  103. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  104. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  105. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  106. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  107. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  108. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  109. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  110. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  111. package/skills/token-optimizer/scripts/codemap.py +274 -0
  112. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  113. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  114. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  115. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  116. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  117. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  118. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  119. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  120. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  121. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  122. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  123. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  124. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  125. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  126. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  127. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  128. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  129. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  130. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  132. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  133. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  134. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  135. package/skills/token-optimizer/scripts/holdout.py +136 -0
  136. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  137. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  138. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  139. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  140. package/skills/token-optimizer/scripts/measure.py +34 -76
  141. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  142. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  143. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  144. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  145. package/skills/token-optimizer/scripts/session_store.py +49 -99
  146. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  147. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  148. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  149. package/skills/token-optimizer/scripts/statusline.js +1 -1
  150. package/skills/token-optimizer/scripts/structural.py +25 -0
  151. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -161,9 +161,9 @@ if __name__ in ("__main__",):
161
161
  from runtime_env import consume_runtime_flag as _consume_runtime_flag_early
162
162
  sys.argv[:] = _consume_runtime_flag_early(sys.argv, os.environ)
163
163
 
164
- from _measure import _compat as _measure_compat
164
+ from _measure import _compat as _measure_compat, counted_pricing_v5 as _counted_pricing_v5, transcript_backfill as _transcript_backfill, counted_subagents as _counted_subagents, headline as _headline, structural_report as _structural_report
165
165
  _measure_providers = _measure_compat.prepare(sys.modules[__name__])
166
-
166
+ from _measure import counted_cap as _counted_cap, output_reread as _output_reread, transcript_product as _transcript_product # noqa: E402
167
167
  from hook_io import read_stdin_hook_input as _read_stdin_hook_input_shared
168
168
  from hook_runtime import (
169
169
  HookDeadline,
@@ -273,7 +273,7 @@ _CLAUDE_TARGET_CMDS = frozenset(
273
273
  "git-context", "dashboard-diagnose", "validate-impact",
274
274
  # Usage recommendations: the refresh replays Claude transcripts and
275
275
  # reads ~/.claude/settings.json; surfaces read its record file only.
276
- "recommendations",
276
+ "recommendations", "coverage-replay", "file-refetch",
277
277
  }
278
278
  )
279
279
  # Back-compat alias (pre-Copilot name).
@@ -591,7 +591,7 @@ _FALLBACK_CLAUDE_MODELS = {
591
591
  "fable": {"input": 10.0, "output": 50.0, "cache_read": 1.0, "cache_write": 12.5, "cache_write_1h": 20.0},
592
592
  "fable_5": {"input": 10.0, "output": 50.0, "cache_read": 1.0, "cache_write": 12.5, "cache_write_1h": 20.0},
593
593
  # Fable 5.1 / Mythos 5.1: cache reads are 0.025x input ($0.25), not 0.1x.
594
- "fable_5_1": {"input": 10.0, "output": 50.0, "cache_read": 0.25, "cache_write": 12.5, "cache_write_1h": 20.0},
594
+ "fable_5_1": {"input": 10.0, "output": 50.0, "cache_read": 0.25, "cache_write": 12.5, "cache_write_1h": 20.0}, "fable_5_2": {"input": 8.0, "output": 40.0, "cache_read": 0.2, "cache_write": 10.0, "cache_write_1h": 16.0},
595
595
  "mythos_5": {"input": 10.0, "output": 50.0, "cache_read": 1.0, "cache_write": 12.5, "cache_write_1h": 20.0},
596
596
  "mythos_5_1": {"input": 10.0, "output": 50.0, "cache_read": 0.25, "cache_write": 12.5, "cache_write_1h": 20.0},
597
597
  # Opus 5.5 is $4/$20 with 0.05x cache reads; Opus 4.5+ is $5/$25; Opus <=4.1 is $15/$75.
@@ -2063,7 +2063,7 @@ _COUNTED_TWIN_WINDOW_SECONDS = 3.0
2063
2063
  # GLOB (case-sensitive, anchored). Real ids are UUIDs, short hex agent ids, or
2064
2064
  # harness ids such as Codex "rollout-<date>-<uuid>"; none of them match.
2065
2065
  _FIXTURE_SESSION_GLOBS = (
2066
- "test-session-*", "failwire-*", "unit-c-never*", "torture-*",
2066
+ "test-session-*", "test-failbuild-*", "failwire-*", "unit-c-never*", "torture-*",
2067
2067
  "f3bench-sess*", "sess_test*",
2068
2068
  )
2069
2069
  # Tool names whose results carry images. Matched against the archive event's
@@ -2498,26 +2498,7 @@ classify_keepwarm_record = _measure_compat.bind(_measure_providers['cache_policy
2498
2498
  compact_keepwarm_sidecar = _measure_compat.bind(_measure_providers['cache_policy'].compact_keepwarm_sidecar, __name__, defaults=(None, None,))
2499
2499
 
2500
2500
 
2501
- # ========== Keep-warm billing + consent gate (eligibility) ==========
2502
- # THE pre-ping gate. The tick loop calls keepwarm_gate() before it touches any
2503
- # armed record; it returns (allowed, reason) and nothing pings unless allowed is
2504
- # True. Two independent conditions must both hold:
2505
- # * billing == 'api' — keep-warm only recovers a *write premium*, which only
2506
- # API-key billing pays. On subscription auth a ping spends quota and saves
2507
- # nothing (never net-negative), so subscription is a HARD off and is
2508
- # never even asked for consent.
2509
- # * consent == 'enabled' — opt-in only (the default-on rule explicitly does NOT
2510
- # extend to token-spending features). Tri-state,
2511
- # sticky, stored via the same _write_config_flag/_config_lock surface as the
2512
- # rest of TO's config (0600 atomic write). States: unasked -> asked ->
2513
- # enabled|declined. enabled/declined are terminal unless an explicit CLI
2514
- # flip (keepwarm-enable / keepwarm-disable) moves them.
2515
- # Detection is CONSERVATIVE by construction: anything we cannot positively
2516
- # identify as API-key billing is treated as subscription (= off). Better to skip
2517
- # a legitimate ping than to ever burn a subscription user's quota.
2518
- # Every reader here is PURE + injectable (env dict + config paths) so the
2519
- # tests can drive each ladder rung without touching the real machine.
2520
-
2501
+ # Keep-warm pings fail closed until live-session refresh is proven safe.
2521
2502
  _KEEPWARM_CONSENT_KEY = "keepwarm_consent"
2522
2503
  # Valid sticky consent states. 'unasked' is the implicit default (no key yet).
2523
2504
  _KEEPWARM_CONSENT_STATES = ("unasked", "asked", "declined", "enabled")
@@ -2525,15 +2506,7 @@ _KEEPWARM_CONSENT_STATES = ("unasked", "asked", "declined", "enabled")
2525
2506
  # *inside* a ping resume can never recursively arm/ping again.
2526
2507
  _KEEPWARM_PING_ENV = "TOKEN_OPTIMIZER_KEEPWARM_PING"
2527
2508
 
2528
- # ===== LLM-PING KILL: the ONLY token-spending step is off by default =====
2529
- # Scope it tight: the WATCHER is awesome and stays ON -- the tick loop, meter
2530
- # reading, resume/cache-drop classification, forecast, and quota model are all
2531
- # code-only and spend ZERO tokens, so they keep watching "when the cash drops."
2532
- # The ONE thing that spins up an LLM and costs tokens is the keep-warm ping
2533
- # (`claude -p` in _keepwarm_fire_ping). THAT is gated off by default and never
2534
- # ships hot. An operator can allow the LLM ping for internal dogfood ONLY by
2535
- # explicitly setting the escape-hatch env var truthy; absent/false = ping OFF.
2536
- # Everything else about keep-warm runs normally.
2509
+ # The legacy allow flag remains a supported explicit opt-out when set false.
2537
2510
  _KEEPWARM_ALLOW_LLM_PING_ENV = "TOKEN_OPTIMIZER_KEEPWARM_ALLOW_LLM_PING"
2538
2511
 
2539
2512
 
@@ -2617,11 +2590,8 @@ _KEEPWARM_SCHEDULER_LOG_NAME = "keepwarm-tick.log"
2617
2590
  # last_tick_ok/last_tick_age freshness signal independently of whether the log
2618
2591
  # carries a traceback (the log can be quiet-clean yet the scheduler dead).
2619
2592
  _KEEPWARM_TICK_STAMP_NAME = ".keepwarm-tick-stamp.json"
2620
- # StartInterval: 5min (matches the "~5min" cadence). ThrottleInterval 60s so
2621
- # launchd never hot-loops the tick if it exits fast. Log rotation guard truncates
2622
- # the combined stdout/stderr log when it exceeds this size, on install and on the
2623
- # tick's own check.
2624
- _KEEPWARM_SCHEDULER_START_INTERVAL = 300
2593
+ # Check every minute and throttle launchd to prevent a hot loop.
2594
+ _KEEPWARM_SCHEDULER_START_INTERVAL = 60
2625
2595
  _KEEPWARM_SCHEDULER_THROTTLE = 60
2626
2596
  _KEEPWARM_SCHEDULER_LOG_MAX_BYTES = 1024 * 1024 # 1MB
2627
2597
 
@@ -2753,7 +2723,7 @@ _KEEPWARM_1H_CADENCE = _KEEPWARM_1H_WINDOW_SECONDS - _KEEPWARM_1H_SAFETY_MARGIN
2753
2723
  # 5m entries: the window is 300s; cadence (if viable at all) is window minus a
2754
2724
  # proportional margin. Viability is decided by the break-even formula, NOT this.
2755
2725
  _KEEPWARM_5M_WINDOW_SECONDS = 300
2756
- _KEEPWARM_5M_SAFETY_MARGIN = 60
2726
+ _KEEPWARM_5M_SAFETY_MARGIN = 120
2757
2727
  _KEEPWARM_5M_CADENCE = _KEEPWARM_5M_WINDOW_SECONDS - _KEEPWARM_5M_SAFETY_MARGIN
2758
2728
  # Per-TTL write premium multiplier on the input rate, DERIVED from PRICING_TIERS
2759
2729
  # at module init (single source of truth -- no hand-copied numbers). The anthropic
@@ -3570,11 +3540,11 @@ _EVENT_RATE_CLASS = {"verbosity_steer_measured": "output", "verbosity_steer": "o
3570
3540
  # One statement per (source, has model_usage_json, has all_model_usage_json, by_day,
3571
3541
  # session-scoped). Grouping on column 1 is a no-op when it is the constant NULL.
3572
3542
  _REPRICE_SQL = _sql_variants(
3573
- "SELECT {day}, e.event_type, SUM(e.tokens_saved), SUM(e.cost_saved_usd), {mu}, {amu}, {mdl} "
3543
+ "SELECT {day}, " + _counted_cap.reexpand_type("e") + ", SUM(e.tokens_saved), SUM(e.cost_saved_usd), {mu}, {amu}, {mdl} "
3574
3544
  "FROM {table} e "
3575
3545
  "LEFT JOIN session_log s ON e.session_uuid = s.session_uuid "
3576
3546
  "WHERE e.timestamp >= ? {scope}"
3577
- "GROUP BY 1, e.event_type, e.session_uuid, 7",
3547
+ "GROUP BY 1, 2, e.session_uuid, 7",
3578
3548
  table={"counted_savings_events": "counted_savings_events", "savings_events": "savings_events"},
3579
3549
  mu={True: "s.model_usage_json", False: "NULL"},
3580
3550
  amu={True: "s.all_model_usage_json", False: "NULL"},
@@ -3611,10 +3581,10 @@ _session_model_reprice = _measure_compat.bind(_measure_providers['pricing']._ses
3611
3581
  # * mcp_cap / hint_followed -- estimated-MAGNITUDE (fixed 5,000/event and
3612
3582
  # conservative-guess sizes; _get_savings_summary relocates both to the
3613
3583
  # estimated tier, so a counted annuity here would cross tiers);
3614
- # * verbosity_* -- output trims: generated once, never re-read.
3584
+ # * verbosity_* -- output reductions are estimated, not counted removals.
3615
3585
  _COUNTED_SE_EVENT_TYPES = (
3616
3586
  "tool_archive", "tool_archive_reexpand", "tool_archive_refetch_block",
3617
- "structure_map", "delta_read",
3587
+ "structure_map", "delta_read", "codemap_outline",
3618
3588
  )
3619
3589
  # compression_events features that are bookkeeping, not removals.
3620
3590
  _COUNTED_CE_EXCLUDED_FEATURES = (
@@ -3698,7 +3668,7 @@ _counted_session_path = _measure_compat.bind(_measure_providers['savings']._coun
3698
3668
 
3699
3669
 
3700
3670
  # Eligibility is per row. A global migration flag never certifies old prices.
3701
- _COUNTED_PRICING_VERSION = "4"
3671
+ _COUNTED_PRICING_VERSION = "9"
3702
3672
  _COUNTED_META_PRICING = "counted_pricing_version"
3703
3673
 
3704
3674
 
@@ -3741,7 +3711,7 @@ _counted_backfill_all = _measure_compat.bind(_measure_providers['savings']._coun
3741
3711
  _counted_session_cache_mix = _measure_compat.bind(_measure_providers['savings']._counted_session_cache_mix, __name__, defaults=("cache_read",))
3742
3712
 
3743
3713
 
3744
- _counted_rollup_rows = _measure_compat.bind(_measure_providers['savings']._counted_rollup_rows, __name__, defaults=(None,))
3714
+ _counted_rollup_rows = _measure_compat.bind(_measure_providers['savings']._counted_rollup_rows, __name__, defaults=(None, None))
3745
3715
 
3746
3716
 
3747
3717
  _counted_row_awaits_rescore = _measure_compat.bind(_measure_providers['savings']._counted_row_awaits_rescore, __name__)
@@ -4006,7 +3976,7 @@ _COLLECT_DRAIN_BUDGETS = {
4006
3976
  "counted_seconds": _COUNTED_PASS_DEADLINE_SECONDS},
4007
3977
  "inline": {"count_capped": False, "parse_seconds": 15.0, "commit_batch": 20,
4008
3978
  "daily_seconds": 15.0, "counted_sessions": 10**9, "counted_seconds": 30.0},
4009
- "full": {"count_capped": False, "parse_seconds": None, "commit_batch": 20,
3979
+ "full": {"count_capped": False, "parse_seconds": None, "commit_batch": 1,
4010
3980
  "daily_seconds": 3600.0, "counted_sessions": 10**9, "counted_seconds": None},
4011
3981
  }
4012
3982
  _UPGRADE_DRAIN_META = "upgrade_drain_done"
@@ -5035,19 +5005,11 @@ _apply_daemon_restart_outcome = _measure_compat.bind(_measure_providers['daemon'
5035
5005
  CHECKPOINT_DIR = _STATE_BASE / "token-optimizer" / "checkpoints"
5036
5006
  CHECKPOINT_EVENT_LOG = _STATE_BASE / "token-optimizer" / "checkpoint-events.jsonl"
5037
5007
 
5038
- # v6 dual-score architecture: ResourceHealth (monotonic warning) + SessionEfficiency (behavioral).
5039
- # ResourceHealth can only worsen within a session (no rolling-window signals).
5040
- # SessionEfficiency uses rolling windows and can rise or fall freely.
5041
- # Score schema version. v2 (COMPACTION-QUALITY.md): compaction count carries
5042
- # zero quality weight -- measured post-boundary recovery signals live in a
5043
- # separate evidence panel instead of the count-only penalty. Consumers must
5044
- # never compare or dampen a v1 score against a v2 score.
5045
- _QUALITY_SCORE_VERSION = 2
5008
+ # ResourceHealth combines fill and waste with a bounded continuity prior.
5009
+ # SessionEfficiency remains a separate diagnostic; versions are not compared.
5010
+ _QUALITY_SCORE_VERSION = 3
5046
5011
 
5047
5012
  _RESOURCE_HEALTH_WEIGHTS = {
5048
- # Compaction count is descriptive metadata, not a quality signal: the
5049
- # count-only penalty is replaced by measured recovery evidence
5050
- # (recovery_status/recovery_evidence). Weights renormalized to 1.0.
5051
5013
  "context_fill_degradation": 5 / 7,
5052
5014
  "absolute_waste_tokens": 2 / 7,
5053
5015
  }
@@ -6625,7 +6587,7 @@ _write_config_flag = _measure_compat.bind(_measure_providers['lifecycle']._write
6625
6587
  # This lets power users override via env, but persistent state lives in config.json
6626
6588
  # so dashboard toggles work without touching shell profiles.
6627
6589
 
6628
- V5_FEATURES = {
6590
+ V5_FEATURES = {**__import__('_measure.keepwarm_economics', fromlist=['feature_settings']).feature_settings(),
6629
6591
  "quality_nudges": {
6630
6592
  "env_var": "TOKEN_OPTIMIZER_QUALITY_NUDGES",
6631
6593
  "config_key": "v5_quality_nudges",
@@ -6808,8 +6770,8 @@ _LEGACY_SAVINGS_LABELS = {
6808
6770
  # the full transcript cold. Counterfactual trigger -> estimated tier
6809
6771
  # (popped from the measured total in _get_savings_summary).
6810
6772
  "resume_lean": "Lean resumes",
6811
- "tool_archive": "Tool replacements",
6812
- "structure_map": "Structure maps",
6773
+ "tool_archive": "Tool replacements", "bash_archive_reexpand": "Bash output re-expanded",
6774
+ "structure_map": "Structure maps", "codemap_outline": "Code map re-read outlines", "codemap_lookup": "Code map lookups [est]",
6813
6775
  # mcp_cap: ESTIMATED (not measured). Claude Code truncates MCP output
6814
6776
  # before PostToolUse fires, so the true pre-cap size is invisible to TO.
6815
6777
  # Logged by archive_result.py when an MCP result is at/near the configured
@@ -6830,7 +6792,7 @@ _LEGACY_SAVINGS_LABELS = {
6830
6792
  "verbosity_steer": "Verbosity steering [est]",
6831
6793
  # verbosity_steer_measured: the output reduction actually observed after a
6832
6794
  # conciseness nudge, compared with the session's own pre-nudge replies.
6833
- "verbosity_steer_measured": "Concise output (measured)",
6795
+ "verbosity_steer_measured": "Concise output [est]",
6834
6796
  # tool_archive_refetch_block: a repeat call for an already-archived result
6835
6797
  # was answered from the archive instead of re-running the tool.
6836
6798
  "tool_archive_refetch_block": "Re-fetches answered from archive",
@@ -6886,7 +6848,7 @@ _V5_COMPRESSION_LABELS = {
6886
6848
  # errors and the summary line.
6887
6849
  "build_output_compress": "Build output compression",
6888
6850
  # Codex sessions: command output compressed by the Codex hook path.
6889
- "codex_command_compress": "Command output (Codex)",
6851
+ "codex_command_compress": "Command output (Codex)", "mod_clean": "Clean-up from the Claude Code mod", "mod_clean_first": "Clean-up first from the Claude Code mod",
6890
6852
  }
6891
6853
 
6892
6854
  # compression_events features that are bookkeeping, shadow measurement, or a
@@ -6901,7 +6863,7 @@ _V5_COMPRESSION_LABELS = {
6901
6863
  _NON_SAVINGS_COMPRESSION_FEATURES = frozenset({
6902
6864
  "fresh_session_nudge", "cohort_demoted", "first_read_edit_followup",
6903
6865
  "cache_drop_warning", "agent_result_skeleton", "unknown", "loop_detection",
6904
- "context_advisory_shadow", "context_size_advisory",
6866
+ "context_advisory_shadow", "context_size_advisory", "post_run_classify_shadow",
6905
6867
  })
6906
6868
 
6907
6869
  # Unified label dict used by the savings-report renderer. Legacy entries
@@ -6920,7 +6882,7 @@ _SAVINGS_CATEGORY_LABELS = {**_LEGACY_SAVINGS_LABELS, **_V5_COMPRESSION_LABELS,
6920
6882
  # allowed to pull out of compression_events. Deriving this from the label
6921
6883
  # dict keeps the two in lockstep — add a key to _V5_COMPRESSION_LABELS and
6922
6884
  # it automatically shows up in the merged view.
6923
- _V5_COMPRESSION_CATEGORIES = frozenset(_V5_COMPRESSION_LABELS.keys())
6885
+ _V5_COMPRESSION_CATEGORIES = frozenset(_V5_COMPRESSION_LABELS.keys()) - {"quality_nudge"}
6924
6886
 
6925
6887
 
6926
6888
  _estimate_compression_cost_per_mtok = _measure_compat.bind(_measure_providers['savings']._estimate_compression_cost_per_mtok, __name__, defaults=(None,))
@@ -6952,8 +6914,8 @@ _MIN_OVERAGE_USD_SHOWN = 10.0
6952
6914
 
6953
6915
  _RUNWAY_SAVED_SQL = _counted_sql(
6954
6916
  "savings_events",
6955
- "SELECT event_type, COALESCE(SUM(tokens_saved),0) FROM {table} "
6956
- "WHERE timestamp >= ? AND event_type != 'verbosity_steer' GROUP BY event_type")
6917
+ "SELECT " + _counted_cap.reexpand_type() + ", COALESCE(SUM(tokens_saved),0) FROM {table} "
6918
+ "WHERE timestamp >= ? AND event_type != 'verbosity_steer' GROUP BY 1")
6957
6919
  _RUNWAY_COMPRESSED_TOTAL_SQL = _counted_sql(
6958
6920
  "compression_events",
6959
6921
  "SELECT COALESCE(SUM(original_tokens-compressed_tokens),0) "
@@ -6970,13 +6932,13 @@ _RUNWAY_COMPRESSED_SQL = _counted_sql(
6970
6932
  # The runway figure is the measured floor, so it leaves them out too.
6971
6933
  _RUNWAY_ESTIMATED_EVENT_TYPES = frozenset(
6972
6934
  {"setup_optimization", "mcp_cap", "hint_followed", "resume_lean",
6973
- "checkpoint_restore"})
6935
+ "checkpoint_restore", "codemap_lookup"})
6974
6936
 
6975
6937
 
6976
6938
  _runway_saved_tokens = _measure_compat.bind(_measure_providers['savings']._runway_saved_tokens, __name__, defaults=(False,))
6977
6939
 
6978
6940
 
6979
- runway_snapshot = _measure_compat.bind(_measure_providers['savings'].runway_snapshot, __name__, defaults=(30, None,))
6941
+ runway_snapshot = _measure_compat.bind(_measure_providers['savings'].runway_snapshot, __name__, defaults=(30, None, None))
6980
6942
 
6981
6943
 
6982
6944
  _active_model_cache_rates = _measure_compat.bind(_measure_providers['savings']._active_model_cache_rates, __name__)
@@ -7185,10 +7147,6 @@ _sum_tool_calls = _measure_compat.bind(_measure_providers['savings']._sum_tool_c
7185
7147
  _estimate_output_waste = _measure_compat.bind(_measure_providers['savings']._estimate_output_waste, __name__, defaults=(30,))
7186
7148
 
7187
7149
 
7188
- # A call gap beyond this many seconds likely dropped the prefix from cache,
7189
- # forcing a full re-write on the next turn. Default 5m (the 5m cache TTL).
7190
- _CACHE_DROP_GAP_SECONDS = _int_env("TOKEN_OPTIMIZER_CACHE_DROP_GAP_SECONDS", 300)
7191
-
7192
7150
 
7193
7151
  _estimate_cache_drop_savings = _measure_compat.bind(_measure_providers['savings']._estimate_cache_drop_savings, __name__, defaults=(30,))
7194
7152
 
@@ -7492,7 +7450,7 @@ _allocate_cents = _measure_compat.bind(_measure_providers['savings']._allocate_c
7492
7450
  _format_cents = _measure_compat.bind(_measure_providers['savings']._format_cents, __name__)
7493
7451
 
7494
7452
 
7495
- _action_savings_display = _measure_compat.bind(_measure_providers['savings']._action_savings_display, __name__, defaults=(False,))
7453
+ _action_savings_display = _measure_compat.bind(_measure_providers['savings']._action_savings_display, __name__, defaults=(False, 0.0))
7496
7454
 
7497
7455
 
7498
7456
  _action_savings_components = _measure_compat.bind(_measure_providers['savings']._action_savings_components, __name__, defaults=(None,))
@@ -7605,9 +7563,9 @@ _BUCKET_DAY_SQL = {True: "substr(timestamp, 1, 10)", False: "''"}
7605
7563
  _BUCKET_SESSION_SQL = {
7606
7564
  True: "AND (session_uuid = ? OR (session_uuid IS NULL AND session_id = ?)) ", False: ""}
7607
7565
  _BUCKET_SAVINGS_SQL = _sql_variants(
7608
- "SELECT {day}, event_type, COUNT(*), SUM(tokens_saved), "
7566
+ "SELECT {day}, " + _counted_cap.reexpand_type() + ", COUNT(*), SUM(tokens_saved), "
7609
7567
  "SUM(cost_saved_usd) FROM {table} WHERE timestamp >= ? {scope}"
7610
- "GROUP BY 1, event_type ORDER BY 4 DESC",
7568
+ "GROUP BY 1, 2 ORDER BY 4 DESC",
7611
7569
  table={"counted_savings_events": "counted_savings_events", "savings_events": "savings_events"},
7612
7570
  day=_BUCKET_DAY_SQL, scope=_BUCKET_SESSION_SQL)
7613
7571
  _BUCKET_COMPRESSION_SQL = _sql_variants(
@@ -0,0 +1,349 @@
1
+ #!/usr/bin/env python3
2
+ """Classify a Bash command AFTER it ran, to pick a compressor.
3
+
4
+ ``is_read_only_pipeline`` answers "is this command safe to rewrite before it
5
+ runs". After the command has run, the PostToolUse hook only needs to know which
6
+ compressor fits the output, and the read-only check rejects the shapes agents
7
+ write today: ``cd /repo && git diff``, ``export X=1; pytest``, ``git -C /repo
8
+ status``. This module strips the harmless leading statements and returns the
9
+ one command that produced the output, or ``None`` when that is not clear.
10
+
11
+ Harmless leading statements (joined by ``;``, ``&&`` or a newline):
12
+ ``cd <path>``, ``export A=b ...``, ``A=b ...``, ``set -e`` style flag sets.
13
+ ``git -C <path> <sub>`` maps to ``git <sub>``; leading ``A=b`` words before
14
+ the command are dropped (the compressor ignores them anyway).
15
+
16
+ Returns ``None`` for anything that is not exactly one remaining command or
17
+ pipeline: several commands, loops, heredocs, ``$(...)``, backticks, ``||``,
18
+ background ``&``, subshells and brace groups.
19
+
20
+ Modes (``TOKEN_OPTIMIZER_POST_RUN_CLASSIFY``):
21
+ ``1`` / ``on`` (default) -- compress newly eligible results, log measured savings.
22
+ ``shadow`` -- compute what would be removed, log it at the
23
+ opportunity tier, change nothing the model sees.
24
+ ``0`` / ``off`` -- kill switch: the classifier is never consulted.
25
+
26
+ Only the pattern-specific compressors in ``ALLOWED_PATTERNS`` may act on a
27
+ newly eligible result. The generic fallback never does.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import os
33
+ import re
34
+ import shlex
35
+
36
+ ENV_VAR = "TOKEN_OPTIMIZER_POST_RUN_CLASSIFY"
37
+ _DEFAULT_MODE = "on"
38
+
39
+ ALLOWED_PATTERNS = frozenset({
40
+ "git_diff", "search_results", "disk_stats", "pytest", "sqlite3", "ls",
41
+ "git_status",
42
+ })
43
+
44
+ _ASSIGN_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
45
+ _SET_FLAGS_RE = re.compile(r"^[-+][euxo]+$")
46
+ _SET_OPTIONS = frozenset({"pipefail", "errexit", "nounset", "xtrace"})
47
+ # Shell keywords that start compound commands; any of them means "not one
48
+ # simple command" and the classifier gives up.
49
+ _COMPOUND_WORDS = frozenset({
50
+ "for", "while", "until", "if", "then", "else", "elif", "fi", "do", "done",
51
+ "case", "esac", "function", "select", "{", "}", "[[", "]]",
52
+ })
53
+
54
+
55
+ def mode() -> str:
56
+ """Return ``on``, ``shadow`` or ``off`` from the env (default on)."""
57
+ raw = os.environ.get(ENV_VAR, "").strip().lower()
58
+ if raw in ("0", "off", "false", "no"):
59
+ return "off"
60
+ if raw in ("1", "on", "true", "yes"):
61
+ return "on"
62
+ if raw == "shadow":
63
+ return "shadow"
64
+ return _DEFAULT_MODE
65
+
66
+
67
+ def _split_statements(command: str) -> list[str] | None:
68
+ """Split on unquoted ``;``, ``&&`` and newlines. ``None`` = give up."""
69
+ out: list[str] = []
70
+ cur: list[str] = []
71
+ i, n = 0, len(command)
72
+ quote = ""
73
+ while i < n:
74
+ ch = command[i]
75
+ if quote:
76
+ if ch == "\\" and quote == '"' and i + 1 < n:
77
+ cur.append(command[i:i + 2])
78
+ i += 2
79
+ continue
80
+ if ch == quote:
81
+ quote = ""
82
+ elif quote == '"' and (ch == "`" or command.startswith("$(", i)):
83
+ return None
84
+ cur.append(ch)
85
+ i += 1
86
+ continue
87
+ if ch == "\\":
88
+ if i + 1 < n and command[i + 1] == "\n":
89
+ i += 2 # line continuation
90
+ continue
91
+ cur.append(command[i:i + 2])
92
+ i += 2
93
+ continue
94
+ if ch in ("'", '"'):
95
+ quote = ch
96
+ cur.append(ch)
97
+ i += 1
98
+ continue
99
+ if ch == "#" and (not cur or cur[-1][-1:].isspace()):
100
+ # Comment to end of line.
101
+ while i < n and command[i] != "\n":
102
+ i += 1
103
+ continue
104
+ if ch == "`" or command.startswith("$(", i) or command.startswith("<<", i):
105
+ return None
106
+ if ch in "(){}":
107
+ return None
108
+ if command.startswith("||", i):
109
+ return None
110
+ if command.startswith("&&", i):
111
+ out.append("".join(cur))
112
+ cur = []
113
+ i += 2
114
+ continue
115
+ if ch == "&":
116
+ # `&>` / `>&` / `2>&1` are redirections; a lone `&` backgrounds.
117
+ prev = cur[-1][-1:] if cur else ""
118
+ nxt = command[i + 1:i + 2]
119
+ if prev in (">", "<") or nxt == ">":
120
+ cur.append(ch)
121
+ i += 1
122
+ continue
123
+ return None
124
+ if ch in (";", "\n"):
125
+ out.append("".join(cur))
126
+ cur = []
127
+ i += 1
128
+ continue
129
+ cur.append(ch)
130
+ i += 1
131
+ if quote:
132
+ return None
133
+ out.append("".join(cur))
134
+ return [s.strip() for s in out if s.strip()]
135
+
136
+
137
+ def _is_harmless(tokens: list[str]) -> bool:
138
+ if not tokens:
139
+ return True
140
+ head = tokens[0]
141
+ if head == "cd":
142
+ return len(tokens) <= 2 and (len(tokens) == 1 or tokens[1] != "-")
143
+ if head == "export":
144
+ return len(tokens) >= 2 and all(_ASSIGN_RE.match(t) for t in tokens[1:])
145
+ if head == "set":
146
+ rest = tokens[1:]
147
+ if not rest:
148
+ return False # bare `set` prints every variable
149
+ ok = True
150
+ for j, t in enumerate(rest):
151
+ if _SET_FLAGS_RE.match(t):
152
+ continue
153
+ if t in _SET_OPTIONS and j > 0 and rest[j - 1].endswith("o"):
154
+ continue
155
+ ok = False
156
+ return ok
157
+ return all(_ASSIGN_RE.match(t) for t in tokens)
158
+
159
+
160
+ _WORD = r"""(?:'[^']*'|"(?:[^"\\]|\\.)*"|[^\s'";&|<>])+"""
161
+ _LEAD_ASSIGN_RE = re.compile(r"^(?:[A-Za-z_][A-Za-z0-9_]*=" + r"(?:" + _WORD + r")?" + r"\s+)+")
162
+ _GIT_C_RE = re.compile(r"^git((?:\s+-C\s+" + _WORD + r")+)(?=\s)")
163
+
164
+
165
+ def _rewrite_effective(stmt: str) -> str | None:
166
+ """Drop leading ``A=b`` words and map ``git -C <p>`` to ``git``.
167
+
168
+ Works on the original text so redirections and quoting reach the
169
+ read-only check exactly as written.
170
+ """
171
+ text = _LEAD_ASSIGN_RE.sub("", stmt.strip(), count=1)
172
+ if text.startswith("git") and re.match(r"^git\s+-C\b", text):
173
+ m = _GIT_C_RE.match(text)
174
+ if not m:
175
+ return None
176
+ text = "git" + text[m.end():]
177
+ return text.strip() or None
178
+
179
+
180
+ def _literal_echo_boundary(statements):
181
+ """A single literal echo may label one producer's output."""
182
+ echoes = [s for s in statements if re.fullmatch(r"echo\s+[A-Za-z0-9_][A-Za-z0-9_.-]*", s)]
183
+ return echoes[0].split()[1] if len(echoes) == 1 else None
184
+
185
+
186
+ def echo_boundary_preserved(command, raw, compressed):
187
+ statements = _split_statements(command)
188
+ if not statements:
189
+ return True
190
+ boundary = _literal_echo_boundary(statements)
191
+ if boundary is None:
192
+ return True
193
+ return boundary in raw.splitlines() and boundary in compressed.splitlines()
194
+
195
+
196
+ def unsafe_compound_output(command: str) -> bool:
197
+ """Avoid using single-output renderers on mixed command output."""
198
+ statements = _split_statements(command)
199
+ if statements is None:
200
+ return True
201
+ producers = []
202
+ for statement in statements:
203
+ try:
204
+ tokens = shlex.split(statement)
205
+ except ValueError:
206
+ return True
207
+ if not _is_harmless(tokens):
208
+ producers.append(statement)
209
+ if len(producers) < 2:
210
+ return False
211
+ if len(producers) == 2 and _literal_echo_boundary(producers) is not None:
212
+ return False
213
+ from bash_compress import _detect_pattern
214
+ try:
215
+ from build_output_compress import classify as build_command, _command_eligible_for_shape_fallback
216
+ except ImportError:
217
+ # Closed-set payloads (Devin) do not ship the build classifier. A compound
218
+ # command that cannot be fully classified keeps its raw output.
219
+ return True
220
+ return any(_detect_pattern(stmt) is not None or build_command(stmt)
221
+ or _command_eligible_for_shape_fallback(stmt) for stmt in producers)
222
+
223
+
224
+ def classify(command: str) -> str | None:
225
+ """Return the single effective command, or ``None``.
226
+
227
+ ``None`` means: several commands remain, the shape is compound, or the
228
+ command cannot be parsed. The result is a normalised command string meant
229
+ only for picking a compressor; it is never executed.
230
+ """
231
+ if not command or not isinstance(command, str):
232
+ return None
233
+ statements = _split_statements(command)
234
+ if not statements:
235
+ return None
236
+ remaining: list[str] = []
237
+ for stmt in statements:
238
+ try:
239
+ lexer = shlex.shlex(stmt, posix=True, punctuation_chars="|")
240
+ lexer.whitespace_split = True
241
+ toks = list(lexer)
242
+ except ValueError:
243
+ return None
244
+ if any(t in _COMPOUND_WORDS for t in toks):
245
+ return None
246
+ if _is_harmless(toks):
247
+ continue
248
+ remaining.append(stmt)
249
+ if len(remaining) != 1:
250
+ return None
251
+ return _rewrite_effective(remaining[0])
252
+
253
+
254
+ def _is_file_content_print(effective: str) -> bool:
255
+ """`git show <rev>:<path>` prints file content; never newly eligible."""
256
+ try:
257
+ toks = shlex.split(effective)
258
+ except ValueError:
259
+ return True
260
+ if len(toks) >= 2 and toks[0] == "git" and toks[1] == "show":
261
+ return any(":" in t and not t.startswith("-") for t in toks[2:])
262
+ return False
263
+
264
+
265
+ # Command words that can map to an ALLOWED_PATTERNS compressor (see
266
+ # bash_compress._detect_pattern). Checked before importing bash_compress, whose
267
+ # import costs tens of ms, so `cd x && sed -n ...` and other rejects pay ~0.1 ms.
268
+ # Over-inclusive on purpose: _detect_pattern still makes the real decision.
269
+ _CANDIDATE_HEADS = frozenset({
270
+ "git", "grep", "rg", "ag", "ack", "wc", "du", "df", "ls", "sqlite3",
271
+ "pytest", "py.test", "python", "python3", "rspec", "mocha", "karma",
272
+ "cypress", "playwright", "npx", "go", "cargo", "tox", "nox",
273
+ "nox-sessions", "gradle", "gradlew", "./gradlew", "mvn", "deno", "bun",
274
+ "ava", "npm", "jest", "vitest",
275
+ })
276
+
277
+
278
+ def _has_candidate_head(effective: str) -> bool:
279
+ for stage in re.split(r"\|&?", effective):
280
+ words = [w for w in stage.split() if not _ASSIGN_RE.match(w)]
281
+ if words and words[0].strip("'\"") in _CANDIDATE_HEADS:
282
+ return True
283
+ return False
284
+
285
+
286
+ def eligible_effective(command: str) -> str | None:
287
+ """Effective command when a pattern-specific compressor may act, else None.
288
+
289
+ The effective command must itself pass the same read-only pipeline check
290
+ a bare command passes, and its detected pattern must be in
291
+ ``ALLOWED_PATTERNS``. Fail closed on any error.
292
+ """
293
+ try:
294
+ eff = classify(command)
295
+ if eff is None or eff == command.strip():
296
+ return None
297
+ if _is_file_content_print(eff) or not _has_candidate_head(eff):
298
+ return None
299
+ from pipeline_analyzer import is_read_only_pipeline
300
+ ok, _ = is_read_only_pipeline(eff)
301
+ if not ok:
302
+ return None
303
+ from bash_compress import _detect_pattern
304
+ if _detect_pattern(eff) not in ALLOWED_PATTERNS:
305
+ return None
306
+ return eff
307
+ except Exception:
308
+ return None
309
+
310
+
311
+ SHADOW_FEATURE = "post_run_classify_shadow"
312
+
313
+
314
+ def shadow_measure(command: str, effective: str, stdout: str, stderr: str,
315
+ exit_code, has_error_patterns) -> int:
316
+ """Shadow mode: log what the pattern compressor WOULD remove. Never raises.
317
+
318
+ Runs the same failure and error-word gates as the live path, then the
319
+ compressor on the effective command. Writes one opportunity-tier row when
320
+ the compressor would remove at least 10%, and nothing else: no archive,
321
+ no dedup store, no change to the output. Returns tokens it would remove.
322
+ """
323
+ try:
324
+ from bash_compress import compress, _looks_like_failure, _strip_ansi
325
+ if _looks_like_failure(exit_code, stderr):
326
+ return 0
327
+ cleaned = _strip_ansi(stdout)
328
+ if has_error_patterns(cleaned):
329
+ return 0
330
+ compressed = compress(effective, cleaned, returncode=exit_code, stderr=stderr)
331
+ from token_estimate import estimate_tokens as _est
332
+ orig, comp = _est(cleaned), _est(compressed or "")
333
+ if not compressed or compressed == cleaned or orig == 0 or (1.0 - comp / orig) < 0.10:
334
+ return 0
335
+ from compression_log import log_compression_event
336
+ from credential_patterns import redact_credentials as _redact
337
+ log_compression_event(
338
+ feature=SHADOW_FEATURE,
339
+ session_id=os.environ.get("CLAUDE_SESSION_ID", ""),
340
+ command_pattern=_redact(command)[:100],
341
+ tier="opportunity",
342
+ verified=False,
343
+ detail="shadow",
344
+ original_tokens=orig,
345
+ compressed_tokens=comp,
346
+ )
347
+ return orig - comp
348
+ except Exception:
349
+ return 0