@alexgreensh/token-optimizer 5.13.75 → 5.13.76

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 (84) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/hooks/posttooluse_runner.py +7 -9
  5. package/hooks/run.py +5 -1
  6. package/hooks/stop_runner.py +15 -56
  7. package/hooks/userpromptsubmit_runner.py +29 -4
  8. package/package.json +1 -1
  9. package/skills/token-optimizer/assets/dashboard.html +30 -14
  10. package/skills/token-optimizer/assets/savings_story.js +103 -27
  11. package/skills/token-optimizer/references/agent-prompts.md +2 -0
  12. package/skills/token-optimizer/references/implementation-playbook.md +1 -0
  13. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  14. package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
  15. package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
  16. package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
  17. package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
  18. package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
  19. package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
  20. package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
  21. package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
  22. package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
  24. package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
  28. package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
  29. package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
  30. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
  31. package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
  32. package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
  33. package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
  34. package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
  35. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
  36. package/skills/token-optimizer/scripts/_measure/savings.py +75 -81
  37. package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
  38. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  39. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
  40. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
  41. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
  42. package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
  43. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
  44. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
  45. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  46. package/skills/token-optimizer/scripts/archive_result.py +16 -28
  47. package/skills/token-optimizer/scripts/archive_verify.py +1 -1
  48. package/skills/token-optimizer/scripts/bash_compress.py +156 -176
  49. package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
  50. package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
  51. package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
  52. package/skills/token-optimizer/scripts/benchmark.py +11 -13
  53. package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
  54. package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
  55. package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
  56. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  57. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  58. package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
  59. package/skills/token-optimizer/scripts/compact_markers.py +129 -0
  60. package/skills/token-optimizer/scripts/copilot_install.py +3 -0
  61. package/skills/token-optimizer/scripts/cursor_install.py +7 -0
  62. package/skills/token-optimizer/scripts/devin_source.py +5 -5
  63. package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
  64. package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
  65. package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
  66. package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
  67. package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
  68. package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
  69. package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
  70. package/skills/token-optimizer/scripts/grok_install.py +3 -0
  71. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  72. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  73. package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
  74. package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
  75. package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
  76. package/skills/token-optimizer/scripts/measure.py +10 -12
  77. package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
  78. package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
  79. package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
  80. package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
  81. package/skills/token-optimizer/scripts/process_identity.py +66 -0
  82. package/skills/token-optimizer/scripts/read_cache.py +51 -60
  83. package/skills/token-optimizer/scripts/statusline.js +21 -3
  84. package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
@@ -13,7 +13,7 @@
13
13
  "name": "token-optimizer",
14
14
  "source": "./",
15
15
  "description": "Audit, fix, and monitor Claude Code context window usage. Find the ghost tokens.",
16
- "version": "5.13.75",
16
+ "version": "5.13.76",
17
17
  "author": {
18
18
  "name": "Alex Greenshpun",
19
19
  "url": "https://linkedin.com/in/alexgreensh"
@@ -55,7 +55,7 @@
55
55
  "name": "token-optimizer-cowork",
56
56
  "source": "./cowork/token-optimizer",
57
57
  "description": "Token Optimizer for Claude Cowork \u2014 full skills + Cowork-native hooks (beta). Install THIS in Cowork; the standard token-optimizer entry is for desktop Claude Code.",
58
- "version": "5.13.75",
58
+ "version": "5.13.76",
59
59
  "author": {
60
60
  "name": "Alex Greenshpun",
61
61
  "url": "https://linkedin.com/in/alexgreensh"
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "homepage": "https://github.com/alexgreensh/token-optimizer",
9
9
  "repository": "https://github.com/alexgreensh/token-optimizer",
10
- "version": "5.13.75",
10
+ "version": "5.13.76",
11
11
  "license": "PolyForm-Noncommercial-1.0.0",
12
12
  "keywords": [
13
13
  "token",
@@ -134,7 +134,7 @@ _COLD_COMPILE_FAILED = ".token-optimizer-compile.failed"
134
134
  _COLD_COMPILE_TAG = "token-optimizer-bytecode-warmup"
135
135
 
136
136
  # This closed set matches _measure.RUNTIME_SOURCES. No recursive repo scan.
137
- _MEASURE_PACKAGE_SOURCES = ('__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py', 'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py', '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', 'savings_headline.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', 'mod_action_booking.py', 'mod_action_diagnostics.py', 'mod_action_selftest.py', 'install_baseline.py', 'routing_credit.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', 'config_cache.py', 'setup_observation_cache.py', 'status_bar_refresh.py', 'routing_default.py', 'pilot_report.py', 'nudge_followthrough.py', 'runway_all_in.py', 'session_activity.py', 'routing_savings.py')
137
+ _MEASURE_PACKAGE_SOURCES = ('__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py', 'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py', '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', 'savings_headline.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', 'mod_action_booking.py', 'mod_action_diagnostics.py', 'mod_action_selftest.py', 'install_baseline.py', 'routing_credit.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', 'config_cache.py', 'setup_observation_cache.py', 'status_bar_refresh.py', 'routing_default.py', 'pilot_report.py', 'nudge_followthrough.py', 'runway_all_in.py', 'session_activity.py', 'routing_savings.py', 'pt_resume_cues.py', 'subscription_audits.py', 'limit_units.py', 'local_adapt.py', 'prefix_cost.py', 'poc_commands.py', 'counted_closes.py', 'counted_headline.py', 'apply_safe.py', 'autocompact_advice.py', 'cold_guard.py', 'keepwarm_auto.py', 'next_actions.py')
138
138
 
139
139
 
140
140
  def _runtime_sources(measure_src):
@@ -114,7 +114,6 @@ import re
114
114
  import signal
115
115
  import sys
116
116
  import time
117
- import traceback
118
117
  from contextlib import contextmanager, redirect_stdout
119
118
  from pathlib import Path
120
119
 
@@ -433,7 +432,7 @@ def _run_safely(name: str, fn, *args, **kwargs):
433
432
  except (Exception, SystemExit):
434
433
  try:
435
434
  sys.stderr.write(f"[Token Optimizer] {name} failed, continuing\n")
436
- traceback.print_exc(file=sys.stderr)
435
+ __import__("traceback").print_exc(file=sys.stderr) # lazy: error path only
437
436
  sys.stderr.flush()
438
437
  except (OSError, ValueError):
439
438
  pass
@@ -1039,10 +1038,8 @@ def _handle_post_tool_use_failure(hook_input: dict) -> None:
1039
1038
  def main() -> int:
1040
1039
  hook_input = _read_hook_input()
1041
1040
  tool_name = str(hook_input.get("tool_name") or "")
1042
-
1043
1041
  if hook_input.get("hook_event_name") == "PostToolUseFailure":
1044
- # Arm the same shared per-handler deadline as the PostToolUse path so
1045
- # a slow regex/handler on the failure branch is bounded, not unbounded.
1042
+ # Shared per-handler deadline bounds the failure branch too.
1046
1043
  _install_runner_deadline()
1047
1044
  _runner_budget(0.0, subcommand_count_hint=1)
1048
1045
  budget = _runner_budget(_RUNNER_TOTAL_BUDGET)
@@ -1058,9 +1055,7 @@ def main() -> int:
1058
1055
 
1059
1056
  _install_shared_stdin(hook_input)
1060
1057
 
1061
- # Gate FIRST, then budget: the fair share must be divided among the
1062
- # subcommands that will actually run, not among all five. An Edit only runs
1063
- # two of them and should get half the budget each, not a fifth.
1058
+ # Gate FIRST, then budget: divide fair share among subcommands that actually run.
1064
1059
  pending = [
1065
1060
  (name, handler)
1066
1061
  for name, matcher, handler in _subcommand_table()
@@ -1068,10 +1063,13 @@ def main() -> int:
1068
1063
  ]
1069
1064
  if not pending: # pragma: no cover -- quality-cache's _MATCHER_UNION is always True
1070
1065
  return 0
1066
+ try: # fast path: only a provable no-op may skip (see hook_fastpath)
1067
+ if __import__("hook_fastpath").skip_posttooluse([n for n, _ in pending], hook_input): return 0
1068
+ except Exception: pass
1071
1069
 
1072
1070
  _install_runner_deadline()
1073
1071
 
1074
- # Buffer every subcommand's stdout and emit in dispatch order at the end.
1072
+ # Buffer subcommand stdout and emit in dispatch order.
1075
1073
  _stdout_bufs: list[str] = []
1076
1074
 
1077
1075
  def _capture(name: str, fn, *args, **kwargs) -> None:
package/hooks/run.py CHANGED
@@ -34,7 +34,6 @@ import os
34
34
  import signal
35
35
  import subprocess
36
36
  import sys
37
- import traceback
38
37
  from pathlib import Path
39
38
 
40
39
  # Defense in depth: the launcher script already filters interpreters, but
@@ -365,6 +364,7 @@ def _check_consent(plugin_root: Path | None = None) -> bool:
365
364
  try:
366
365
  buf = io.StringIO()
367
366
  buf.write("[Token Optimizer] _check_consent unexpected error, failing open\n")
367
+ import traceback # lazy: error path only (~10 ms import on the hot path)
368
368
  traceback.print_exc(file=buf)
369
369
  _consent_log_diagnostics(buf.getvalue())
370
370
  except Exception:
@@ -654,6 +654,10 @@ def main() -> int:
654
654
  # never crash a hook with UnicodeDecode/EncodeError. PYTHONUTF8 also makes the
655
655
  # child's default open() encoding UTF-8; PYTHONIOENCODING covers its std streams.
656
656
  child_env = {**os.environ, "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}
657
+ if script_path.stem == "stop_runner" or script_args[:1] == ["session-end-flush"]:
658
+ # module_runner's parent is this short-lived dispatcher. The detached
659
+ # flush worker must start its lookup above it, at the hook's parent.
660
+ child_env["TOKEN_OPTIMIZER_HOOK_PARENT_PID"] = str(os.getppid())
657
661
  if stale_plugin_root:
658
662
  # The handler and everything it imports resolve paths from this too.
659
663
  child_env["CLAUDE_PLUGIN_ROOT"] = str(root_resolved)
@@ -10,9 +10,8 @@ and caused each subcommand to start a separate interpreter and import
10
10
  2. ``measure.py session-end-flush --trigger stop --quiet --defer`` (timeout 8)
11
11
  3. ``measure.py keepwarm-arm --quiet`` (timeout 5)
12
12
 
13
- The separate processes also repeat cold imports when a read-only plugin
14
- installation cannot retain ``__pycache__``. Consolidation pays that startup
15
- cost once, then runs the real work under one shared deadline.
13
+ The runner pays the import cost once, then captures the checkpoint and
14
+ hands refresh and keep-warm to one detached worker under a shared deadline.
16
15
 
17
16
  The ``SessionEnd`` hook (a fourth entry: ``session-end-flush --trigger end
18
17
  --defer``, timeout 60) joins this runner too. It synchronously marks the
@@ -28,23 +27,18 @@ files.
28
27
  Key properties:
29
28
  - ONE shared ``HookDeadline`` (13s for Stop, 2s margin under the hooks.json
30
29
  timeout of 15; 58s for SessionEnd, 2s margin under timeout 60) replaces the
31
- three independent per-entry timeouts (12 + 8 + 5 = 25s). Remaining time is
30
+ three former per-entry timeouts (12 + 8 + 5 = 25s). Remaining time is
32
31
  budgeted fairly across the subcommands still pending (``_runner_budget``);
33
32
  the shared deadline's ``os._exit(0)`` is the ONLY kill switch in the
34
33
  process, so an early subcommand hang can never preemptively kill later ones.
35
- - The ``--defer`` behaviour is preserved EXACTLY: ``session-end-flush`` calls
36
- ``measure._dispatch_session_end_flush`` with the same args list the
37
- ``__main__`` dispatch received, so the detached worker gets the same
38
- ``--trigger`` / ``--defer`` / ``--quiet`` flags.
34
+ - The flush worker receives the original trigger, defer and quiet flags,
35
+ plus the session identity and keep-warm candidate when available.
39
36
  - The trigger values ``stop`` and ``end`` are preserved EXACTLY so entry
40
37
  budget rules can distinguish the Stop and SessionEnd work.
41
38
  - SessionEnd runs synchronously to prevent keep-warm from pinging ended sessions.
42
- - No once-per-session latching exists in the Stop/SessionEnd chain (none of
43
- the three subcommands use ``_mark_ran_this_session`` or
44
- ``_ran_once_this_session``), so there is nothing to preserve there.
45
39
  - stdout from all subcommands is captured through one buffered emitter and
46
40
  emitted in dispatch order at the end of ``main()``. Under ``--quiet`` (the
47
- Stop path) all three subcommands produce no stdout; the SessionEnd path
41
+ Stop path) both subcommands produce no stdout; the SessionEnd path
48
42
  likewise produces none (``_dispatch_session_end_flush`` only spawns a
49
43
  detached worker). The buffer is a safety net for any unexpected output.
50
44
  - One subcommand throwing/aborting never aborts the others (each is wrapped in
@@ -148,7 +142,7 @@ def _is_session_end(hook_input: dict) -> bool:
148
142
  registered under both ``Stop`` and ``SessionEnd`` in hooks.json; this check
149
143
  routes to the right subcommand set. Case-insensitive to tolerate host
150
144
  variations. When the field is missing, default to the Stop path (the
151
- primary use case -- running all three subcommands when only
145
+ primary use case -- running both subcommands when only
152
146
  session-end-flush was needed is harmless and fail-open; the reverse would
153
147
  miss the checkpoint and keepwarm arm).
154
148
  """
@@ -161,9 +155,7 @@ def _run_safely(name: str, fn, *args, **kwargs) -> None:
161
155
 
162
156
  Catches ``Exception``, ``SystemExit``, and ``measure._HookTimeout`` (a
163
157
  ``BaseException``) so one subcommand's bug, internal ``sys.exit()``, or
164
- legacy timeout signal cannot abort the others. The ``session-end-flush``
165
- and ``keepwarm-arm`` dispatch blocks both end in ``sys.exit(0)``; in-process
166
- that is a ``SystemExit`` that this guard isolates. The original
158
+ legacy timeout signal cannot abort the others. The original
167
159
  ``__main__`` blocks explicitly catch ``_HookTimeout``; in production the
168
160
  new ``HookDeadline`` watchdog calls ``os._exit(0)`` directly (uncatchable),
169
161
  but ``_HookTimeout`` is caught here for defense-in-depth and for tests
@@ -295,48 +287,18 @@ def _sub_compact_capture_stop(hook_input: dict) -> None:
295
287
  def _sub_session_end_flush_stop(hook_input: dict) -> None:
296
288
  """``measure.py session-end-flush --trigger stop --quiet --defer`` (entry 2).
297
289
 
298
- Mirrors the ``session-end-flush`` dispatch (measure.py ~L42154):
299
- calls _dispatch_session_end_flush(args) with the exact args list;
300
- _dispatch_session_end_flush defers by default (--no-defer not present),
301
- spawning a detached worker with args[1:] = [--trigger, stop, --quiet,
302
- --defer]; the worker reads --trigger for its compact_capture call.
303
- The dispatch's trailing ``sys.exit(0)`` is NOT part of
304
- _dispatch_session_end_flush; calling the function directly avoids it. Even
305
- if it did sys.exit, ``_run_safely`` catches SystemExit.
290
+ The same detached worker handles checkpoint refresh and keep-warm.
306
291
  """
307
292
  budget = _runner_budget(8)
308
293
  if budget < 0.1:
309
294
  return
310
- args = ["session-end-flush", "--trigger", "stop", "--quiet", "--defer"]
311
- # The deferred worker has no stdin, so hand it the session identity the
312
- # host gave THIS hook; without it the worker can only guess and (on Codex)
313
- # wrote an "unknown" placeholder checkpoint (issue #278).
314
- for flag, key in (("--session-id", "session_id"), ("--transcript-path", "transcript_path")):
315
- value = hook_input.get(key)
316
- if isinstance(value, str) and value and len(value) <= 4096 and "\x00" not in value:
317
- args += [flag, value]
295
+ from _measure import keepwarm_safety
296
+ args = keepwarm_safety.stop_flush_args(
297
+ measure, ["session-end-flush", "--trigger", "stop", "--quiet", "--defer"], hook_input,
298
+ )
318
299
  measure._dispatch_session_end_flush(args, budget_seconds=budget)
319
300
 
320
301
 
321
- def _sub_keepwarm_arm(hook_input: dict) -> None:
322
- """``measure.py keepwarm-arm --quiet`` (Stop entry 3).
323
-
324
- Mirrors the ``keepwarm-arm`` dispatch (measure.py ~L42479):
325
- reads stdin for session_id and transcript_path;
326
- calls write_keepwarm_arm_record(sid, transcript);
327
- --quiet suppresses the print.
328
- The dispatch's own ``_install_hook_budget(2)`` is replaced by the runner's
329
- shared HookDeadline. The dispatch's ``sys.exit(0)`` on _HookTimeout /
330
- Exception is replaced by ``_run_safely``'s SystemExit catch.
331
- """
332
- budget = _runner_budget(2)
333
- if budget < 0.1:
334
- return
335
- sid = hook_input.get("session_id")
336
- transcript = hook_input.get("transcript_path")
337
- measure.write_keepwarm_arm_record(sid, transcript)
338
-
339
-
340
302
  def _sub_session_end_flush_end(hook_input: dict) -> None:
341
303
  """``measure.py session-end-flush --trigger end --defer`` (SessionEnd entry).
342
304
 
@@ -379,7 +341,7 @@ def main() -> int:
379
341
  _install_runner_deadline()
380
342
 
381
343
  # Buffer every subcommand's stdout and emit in dispatch order at the end.
382
- # Under --quiet (the Stop path) all three subcommands produce no stdout;
344
+ # Under --quiet (the Stop path) both subcommands produce no stdout;
383
345
  # the SessionEnd path likewise produces none. The buffer is a safety net
384
346
  # for any unexpected output, preserving the host's no-output contract.
385
347
  _stdout_bufs: list[str] = []
@@ -398,13 +360,10 @@ def main() -> int:
398
360
  _capture("session-end-flush --trigger end", _sub_session_end_flush_end,
399
361
  hook_input)
400
362
  else:
401
- # Stop: all three subcommands in dispatch order (matching the legacy
402
- # hooks.json entry order: compact-capture, session-end-flush, keepwarm-arm).
403
- _runner_budget(8, subcommand_count_hint=3)
363
+ _runner_budget(8, subcommand_count_hint=2)
404
364
  _capture("compact-capture", _sub_compact_capture_stop, hook_input)
405
365
  _capture("session-end-flush --trigger stop", _sub_session_end_flush_stop,
406
366
  hook_input)
407
- _capture("keepwarm-arm", _sub_keepwarm_arm, hook_input)
408
367
 
409
368
  # Emit all buffered stdout in order (preserves per-shape contract: each
410
369
  # subcommand's output is a self-contained unit, emitted in the order the
@@ -8,6 +8,8 @@ times). This runner is invoked ONCE per prompt, imports ``measure.py`` ONCE,
8
8
  and runs all six subcommands in-process with per-subcommand failure isolation.
9
9
 
10
10
  Key properties:
11
+ - The cold-session guard runs after consent, before the six subcommands.
12
+ It can warn in the same envelope or hold an opted-in prompt by itself.
11
13
  - The three always-on subcommands (``quality-cache --warn --quiet``,
12
14
  ``prompt-continuity --quiet``, ``verbosity-steer --quiet``) run every prompt.
13
15
  - The three harness-only subcommands (``ensure-health --once-per-session``,
@@ -230,7 +232,7 @@ def _quality_cache_is_missing(hook_input: dict) -> bool:
230
232
  return False
231
233
 
232
234
 
233
- def _run_safely(name: str, fn, *args, **kwargs) -> None:
235
+ def _run_safely(name: str, fn, *args, **kwargs):
234
236
  """Run fn, swallow any failure to the diagnostics log, never propagate.
235
237
 
236
238
  Catches ``Exception`` and ``SystemExit`` so one subcommand's bug or internal
@@ -243,7 +245,7 @@ def _run_safely(name: str, fn, *args, **kwargs) -> None:
243
245
  (the host captures stderr into the model's session context).
244
246
  """
245
247
  try:
246
- fn(*args, **kwargs)
248
+ return fn(*args, **kwargs)
247
249
  except (Exception, SystemExit):
248
250
  try:
249
251
  buf = io.StringIO()
@@ -315,6 +317,22 @@ def _clear_runner_deadline():
315
317
  # --------------------------------------------------------------------------- #
316
318
 
317
319
 
320
+ def _sub_cold_guard(hook_input: dict):
321
+ from _measure import cold_guard
322
+
323
+ try:
324
+ # Only the decision may reach the host, even if checkpointing prints.
325
+ with redirect_stdout(io.StringIO()):
326
+ result = cold_guard.bounded_evaluate(measure, hook_input, _time.time(), 2.0)
327
+ except cold_guard.BudgetExceeded:
328
+ return None
329
+ if result["kind"] == "warn":
330
+ print(json.dumps({"systemMessage": result["text"]}))
331
+ elif result["kind"] == "block":
332
+ return result["text"]
333
+ return None
334
+
335
+
318
336
  def _sub_quality_cache_warn(hook_input: dict) -> None:
319
337
  """``quality-cache --warn --quiet`` (always runs). Mirrors __main__ L40696."""
320
338
  budget = _runner_budget(8)
@@ -675,11 +693,11 @@ def main() -> int:
675
693
  # the model's session context, so diagnostics must reach neither).
676
694
  _stdout_bufs: list[str] = []
677
695
 
678
- def _capture(name: str, fn, *args, **kwargs) -> None:
696
+ def _capture(name: str, fn, *args, **kwargs):
679
697
  buf = io.StringIO()
680
698
  err_buf = io.StringIO()
681
699
  with redirect_stdout(buf), redirect_stderr(err_buf):
682
- _run_safely(name, fn, *args, **kwargs)
700
+ result = _run_safely(name, fn, *args, **kwargs)
683
701
  captured = buf.getvalue()
684
702
  err_captured = err_buf.getvalue()
685
703
  # ALL stdout -> envelope (systemMessage + bare-text + JSON all
@@ -688,6 +706,13 @@ def main() -> int:
688
706
  _stdout_bufs.append(captured)
689
707
  if err_captured:
690
708
  _write_diagnostics(f"--- {name} ---\n{err_captured}")
709
+ return result
710
+
711
+ # A hold has its own host envelope and must leave the other hooks untouched.
712
+ if reason := _capture("cold-guard", _sub_cold_guard, hook_input):
713
+ print(json.dumps({"decision": "block", "reason": reason}), flush=True)
714
+ _clear_runner_deadline()
715
+ return 0
691
716
 
692
717
  # 1-3: always-on subcommands. Ordering: the cheap,
693
718
  # user-visible subcommands (prompt-continuity, verbosity-steer) run BEFORE
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgreensh/token-optimizer",
3
- "version": "5.13.75",
3
+ "version": "5.13.76",
4
4
  "description": "Token Optimizer for Claude Code cloud sessions: the real plugin, installed by your cloud environment's setup script.",
5
5
  "license": "PolyForm-Noncommercial-1.0.0",
6
6
  "author": "Alex Greenshpun (https://linkedin.com/in/alexgreensh)",
@@ -4238,11 +4238,7 @@ var DB = (function() {
4238
4238
  if (v >= 10) return '$' + v.toFixed(1);
4239
4239
  return '$' + v.toFixed(2);
4240
4240
  }
4241
- // Validate the numbers this template did not produce. The guard above only
4242
- // proves the payload SHAPE; a window missing a numeric field would render
4243
- // "NaN%" to the user, which is worse than the card being absent. Every
4244
- // figure here originates in runway_snapshot, so a bad window means that
4245
- // contract changed and the honest response is to drop the window.
4241
+ // Ignore malformed window metrics before rendering the meter.
4246
4242
  var rwCards = rw.windows.map(function (w) {
4247
4243
  var headPct = Number(w.headroom_pct);
4248
4244
  var offPct = w.would_be_capped ? 0 : Number(w.without_headroom_pct);
@@ -4484,6 +4480,7 @@ var DB = (function() {
4484
4480
  '</div>' +
4485
4481
  '</div>';
4486
4482
  }
4483
+ if (html && typeof savingsLimitsLifetime === 'function') html += savingsLimitsLifetime(data);
4487
4484
  return html;
4488
4485
  }
4489
4486
 
@@ -4596,7 +4593,8 @@ var DB = (function() {
4596
4593
  { key: 'contamination_exit', label: 'avoided rework (heeded nudges)', amt: mo(ce.cost_saved_usd), n: Number(ce.heeded_sessions) || 0, unit: 'heeded', conf: ce.confidence },
4597
4594
  { key: 'handover_rerun', label: 'continuity handover', amt: mo(hr.cost_saved_usd), n: Number(hr.restored_sessions) || 0, unit: 'restored', conf: hr.confidence },
4598
4595
  { key: 'avoided_search', label: 'avoided search (hints)', amt: avoidedSearchMo, n: avoidedSearchN, unit: avoidedSearchUnit, conf: hfHasData ? 'trigger observed, size estimated' : rs.confidence },
4599
- { key: 'checkpoint_restore_estimated', label: 'checkpoint restores (working-set re-reads)', amt: mo(cr.cost_saved_usd), n: Number(cr.events) || 0, unit: 'restores' },
4596
+ { key: 'checkpoint_restore_estimated', label: 'checkpoint restores (working-set re-reads)', amt: mo(cr.cost_saved_usd), n: Number(cr.events) || 0, unit: 'restores' }, { key: 'autocompact_window_estimated', label: 'Earlier auto-compact', amt: mo((s.autocompact_window_estimated || {}).cost_saved_usd), n: Number((s.autocompact_window_estimated || {}).events) || 0, unit: 'compactions', conf: Number((s.autocompact_window_estimated || {}).cost_saved_usd) < 0 ? 'net cost' : undefined },
4597
+ { key: 'cold_guard_estimated', label: 'Cold-session guard', amt: mo((s.cold_guard_estimated || {}).cost_saved_usd), n: Number((s.cold_guard_estimated || {}).events) || 0, unit: 'fresh starts', conf: (s.cold_guard_estimated || {}).events ? 'net of handover writes' : undefined },
4600
4598
  { key: 'verbosity_steer', label: 'concise output nudges', amt: mo(vs.cost_saved_usd), n: Number(vs.events) || 0, unit: 'nudges' },
4601
4599
  { key: 'verbosity_output_estimated', label: 'shorter replies and their re-reads (net of un-nudged replies)', amt: mo(vo.cost_saved_usd), n: Number(vo.events) || 0, unit: 'calibrated nudges',
4602
4600
  conf: vo.basis === 'no_reduction_net_of_control' ? 'no reduction net of the control' : (vo.basis === 'not_measured' && vo.events ? 'NOT MEASURED: no un-nudged control yet' : undefined) }
@@ -4713,10 +4711,7 @@ var DB = (function() {
4713
4711
  parts.push('Favor targeted Edits over full-file Writes. About ' + (Number(ow.avoidable_writes) || 0) + ' of your Writes could have been Edits, worth about ' + moneyCents(oppCents.output) + per + ' in output.');
4714
4712
  }
4715
4713
 
4716
- // U9: the savings story leads when the payload carries session_effect;
4717
- // older payloads (or a template without the inlined module) keep the
4718
- // previous layout unchanged. extras carries the "Still on the table" fix
4719
- // targets and the merged "More changes you could make" parts.
4714
+ // The detailed story needs session_effect. The stored total can render without it.
4720
4715
  var story = '';
4721
4716
  if (storyOn) {
4722
4717
  try {
@@ -4744,7 +4739,8 @@ var DB = (function() {
4744
4739
  '</div>' +
4745
4740
  '<div class="last-updated">Updated ' + esc(updTxt) + ' &middot; refreshes after every session</div>';
4746
4741
 
4747
- html += story || runwayCardHtml();
4742
+ var overallFallback = !story && typeof savingsOverallFallback === 'function' ? savingsOverallFallback(data) : '';
4743
+ html += story || (overallFallback + runwayCardHtml() + (typeof keepwarmNetHtml === 'function' ? keepwarmNetHtml(data) : ''));
4748
4744
  var storyHead = html; html = '';
4749
4745
 
4750
4746
  // ---- Tokens Saved card: the full card (hero + spent-vs-saved + model-
@@ -4849,6 +4845,21 @@ var DB = (function() {
4849
4845
  '<div class="savings-split"><span>Setup <strong>' + money(periodValue(structMo)) + '</strong></span>' +
4850
4846
  '<span>Runtime <strong>' + money(periodValue(runtimeMo + rereadMo)) + '</strong></span>' +
4851
4847
  '<span>Habits <strong>' + money(periodValue(behavMo)) + '</strong></span></div>' +
4848
+ (function() {
4849
+ var cats = s.by_category || {};
4850
+ var builtinFallback = { builtin_grep: 'Built-in Grep compression', builtin_glob: 'Built-in Glob compression' };
4851
+ var rows = Object.keys(cats).filter(function(k) {
4852
+ return cats[k] && (Number(cats[k].tokens_saved) || 0) > 0 && k !== 'structural_savings';
4853
+ }).sort(function(a, b) {
4854
+ return (Number(cats[b].tokens_saved) || 0) - (Number(cats[a].tokens_saved) || 0);
4855
+ }).map(function(k) {
4856
+ var c = cats[k];
4857
+ var lbl = c.label || builtinFallback[k] || k;
4858
+ return '<p>' + esc(lbl) + ': <strong>' + fmtTok(c.tokens_saved) + ' tokens</strong> (' +
4859
+ money(Number(c.cost_saved_usd) || 0) + ', ' + (Number(c.events) || 0).toLocaleString() + ' events).</p>';
4860
+ });
4861
+ return rows.length ? '<p><strong>Measured by feature:</strong></p>' + rows.join('') : '';
4862
+ })() +
4852
4863
  (estItems.length ? '<p>Other estimates:</p>' + estItems.map(function(it) {
4853
4864
  var shown = exactCents && estCents(it) != null ? moneyCents(estCents(it)) : money(periodValue(it.amt));
4854
4865
  return '<p>' + esc(it.label) + ': <strong>' + shown + '</strong> (' +
@@ -4933,7 +4944,7 @@ var DB = (function() {
4933
4944
  html += '</div>';
4934
4945
  html += fold('Token savings and model usage', tokensSavedCardHtml(s));
4935
4946
  var ledgerHtml = html;
4936
- html = storyHead + (story ? '' : ledgerHtml);
4947
+ html = storyHead + (story ? '' : overallFallback ? fold('Full ledger and history', ledgerHtml) : ledgerHtml);
4937
4948
 
4938
4949
  // ---- SAVE MORE: the parts list was built before the story render (see
4939
4950
  // above); story mode already folded it into "Still on the table". ----
@@ -4965,7 +4976,7 @@ var DB = (function() {
4965
4976
  moreFolds.push('<details class="fold"><summary>Full ledger and history</summary><div class="fold__body">' + ledgerBody + '</div></details>');
4966
4977
  } else if (parts.length > 0) {
4967
4978
  html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);border:1px solid var(--c-amber);box-shadow:0 0 0 1px rgba(217,164,65,0.18), 0 0 44px rgba(217,164,65,0.12);">';
4968
- html += '<div class="label" style="margin-bottom:var(--s-2);color:var(--c-text-dim);">Money on the table &middot; opportunity</div>';
4979
+ html += '<div class="label" style="margin-bottom:var(--s-2);color:var(--c-text-dim);">' + (overallFallback ? 'Could save (not saved yet)' : 'Money on the table &middot; opportunity') + '</div>';
4969
4980
  if (opportunityMo > 0) {
4970
4981
  html += '<div style="display:flex;align-items:baseline;gap:var(--s-2);flex-wrap:wrap;">' +
4971
4982
  '<span style="font-family:var(--font-mono);font-weight:300;font-size:76px;line-height:0.9;color:var(--c-text-main);text-shadow:0 0 30px rgba(217,164,65,0.5);letter-spacing:-0.02em;">' + moneyCents(oppCents.total) + '</span>' +
@@ -6000,7 +6011,12 @@ var DB = (function() {
6000
6011
  '</p>';
6001
6012
 
6002
6013
  v5Names.forEach(function(fname) {
6003
- var f = v5Features[fname]; if (fname === 'keepwarm') { html += '<div class="hook-row" style="padding:20px var(--s-3);border-top:1px solid var(--c-border);">Keep-warm: paused while we prove it is safe and saves you money</div>'; return; }
6014
+ var f = v5Features[fname];
6015
+ if (fname === 'keepwarm' && typeof keepwarmStateHtml === 'function' && keepwarmStateHtml(data)) {
6016
+ html += '<div class="hook-row" style="padding:20px var(--s-3);border-top:1px solid var(--c-border);">' + keepwarmStateHtml(data) + '</div>';
6017
+ return;
6018
+ }
6019
+ if (fname === 'keepwarm') { html += '<div class="hook-row" style="padding:20px var(--s-3);border-top:1px solid var(--c-border);">Keep-warm: paused while we prove it is safe and saves you money</div>'; return; }
6004
6020
  var unavailable = !!f.unavailable || f.source === 'codex api gap';
6005
6021
  var managedByHooks = !!f.managed_by_hooks || (isCodex && (f.source === 'codex hook' || f.source === 'codex opt-in' || f.source === 'codex hook-managed'));
6006
6022
  var riskBg = 'var(--c-badge-savings)';