@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
@@ -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.68",
16
+ "version": "5.13.70",
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.68",
58
+ "version": "5.13.70",
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.68",
10
+ "version": "5.13.70",
11
11
  "license": "PolyForm-Noncommercial-1.0.0",
12
12
  "keywords": [
13
13
  "token",
package/PRIVACY.md CHANGED
@@ -144,6 +144,10 @@ Token Optimizer sets `cleanupPeriodDays=99999` in the host platform's `settings.
144
144
  - Users can override this setting in their `settings.json`
145
145
  - The `purge` command does NOT delete transcripts (they belong to the host platform)
146
146
 
147
+ ## Settings Self-Heal
148
+
149
+ Token Optimizer keeps a secret-free backup of your `settings.json` (`~/.claude/token-optimizer/settings_heal/`, owner-only) so it can undo an accidental wipe. It is never stored: `env`, `apiKeyHelper` and the other credential helpers, any key named like a token, secret, key, password or auth, MCP server `env` and `headers`, and any value the credential detector flags. Restores only fill in what is missing, never write back a removed secret, print one line saying what was restored and what was not (for example "env was not restored"), and show in `doctor`/`health`. Backups made by older versions are cleaned the same way on the first run of 5.13.70. Set `TOKEN_OPTIMIZER_SETTINGS_HEAL=0` to turn the backup and restore off.
150
+
147
151
  ## Subagent Prompt-Cache Setting
148
152
 
149
153
  On Claude Code 2.1.243+, Token Optimizer measures whether `subagentPromptCacheTtl: "1h"` would pay on your own transcripts and recommends it -- it never sets the key for you. `subagent-cache enable` applies the recommendation (setting it once in the user `settings.json` so subagents keep their prompt cache for an hour instead of five minutes). This is the host platform's billing setting, not Token Optimizer data.
package/hooks/hooks.json CHANGED
@@ -77,6 +77,17 @@
77
77
  ]
78
78
  }
79
79
  ],
80
+ "SubagentStart": [
81
+ {
82
+ "hooks": [
83
+ {
84
+ "type": "command",
85
+ "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%[/\\\\]*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/hooks/run.py\" skills/token-optimizer/scripts/codemap_hint.py; done; exit 0",
86
+ "timeout": 10
87
+ }
88
+ ]
89
+ }
90
+ ],
80
91
  "Stop": [
81
92
  {
82
93
  "hooks": [
@@ -94,7 +105,6 @@
94
105
  {
95
106
  "type": "command",
96
107
  "command": "for b in bash /bin/bash /usr/bin/bash /usr/local/bin/bash /opt/homebrew/bin/bash; do command -v \"$b\" >/dev/null 2>&1 || continue; D=\"${CLAUDE_PLUGIN_ROOT}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || D=\"$(ls -d \"${D%[/\\\\]*}\"/*/ 2>/dev/null | grep -E \"/[0-9]+[.][0-9]+[.][0-9]+/$\" | sort -V | tail -n1)\"; D=\"${D%/}\"; [ -r \"$D/hooks/python-launcher.sh\" ] || exit 0; exec \"$b\" \"$D/hooks/python-launcher.sh\" \"$D/hooks/run.py\" hooks/stop_runner.py; done; exit 0",
97
- "async": true,
98
108
  "timeout": 60
99
109
  }
100
110
  ]
@@ -137,8 +137,11 @@ _COLD_COMPILE_TAG = "token-optimizer-bytecode-warmup"
137
137
  _MEASURE_PACKAGE_SOURCES = (
138
138
  '__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py',
139
139
  'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py',
140
- 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py',
140
+ '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',
141
141
  )
142
+ _MEASURE_PACKAGE_SOURCES += ('transcript_stream.py', 'checkpoint_direction.py', 'checkpoint_retention.py')
143
+ _MEASURE_PACKAGE_SOURCES += ('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',)
144
+ _MEASURE_PACKAGE_SOURCES += ('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',)
142
145
 
143
146
 
144
147
  def _runtime_sources(measure_src):
@@ -13,22 +13,11 @@ product (PostToolUse fires on EVERY tool call):
13
13
  5. ``read_cache.py --invalidate --quiet`` [Edit|Write|MultiEdit|NotebookEdit] (10s, sync)
14
14
  6. ``measure.py quality-cache --quiet --throttle-only`` [the union matcher] (10s, sync)
15
15
 
16
- Combined declared budget: 80s. Measured cost per entry with ``__pycache__``
17
- wiped before every call (the container steady state -- module_runner.py warns
18
- that a read-only scripts dir means bytecode is never cached):
19
-
20
- entry point warm cold
21
- bash_compress_hook.py --quiet 128ms 122ms
22
- archive_result.py --quiet 204ms 218ms
23
- context_intel.py --quiet 204ms 223ms
24
- read_cache.py --invalidate 205ms 218ms
25
- measure.py quality-cache -to 226ms 798ms
26
-
27
- Of each of those, 127ms is FIXED dispatch overhead (bash launcher -> run.py ->
28
- a second interpreter -> module_runner) paid before any hook work happens, and
29
- the 798ms cold outlier is the one entry that imports measure.py (682ms cold /
30
- 99ms warm on its own). Under a sustained container workload, ``PostToolUse:Bash``
31
- was CANCELLED 372 times and succeeded 9.
16
+ Combined declared budget: 80s. Measured per entry with ``__pycache__`` wiped
17
+ before every call (the container steady state): 122-223ms each, 798ms for the one
18
+ entry that imports measure.py, of which 127ms is FIXED dispatch overhead (bash
19
+ launcher -> run.py -> a second interpreter -> module_runner). Under a sustained
20
+ container workload, ``PostToolUse:Bash`` was CANCELLED 372 times and succeeded 9.
32
21
 
33
22
  This runner is invoked ONCE per tool call, pays the dispatch overhead ONCE,
34
23
  imports each hook module at most once, and runs every subcommand in-process
@@ -269,34 +258,12 @@ def _rebind_shared_stdin(module) -> None:
269
258
  # runner only ever sees a tool that at least one of the six would have seen.
270
259
  # Each subcommand then re-checks its own original matcher here.
271
260
  #
272
- # WHY re.search AND WHY THAT IS EXACT EITHER WAY:
273
- #
274
- # The host's own regex anchoring is not something this file should have to
275
- # guess at, and it does not have to. Take the two possibilities:
276
- #
277
- # * Host uses an UNANCHORED test (regex.test / re.search). Then re.search
278
- # here is literally the same operation on the same pattern, and every
279
- # subcommand fires on exactly the tools its own entry fired on. Exact.
280
- #
281
- # * Host ANCHORS (fullmatch). Then the union gate admits exactly
282
- # {Bash, PowerShell, Read, Glob, Grep, Agent, Edit, Write, MultiEdit,
283
- # NotebookEdit} plus mcp__*, and re.search here can only over-match INSIDE
284
- # that set.
285
- # Enumerated, it does not:
286
- # - _MATCHER_ARCHIVE searches for
287
- # Bash|PowerShell|Read|Glob|Grep|Agent|mcp__.* -- no admitted tool
288
- # contains one of those as a substring without also matching it under
289
- # fullmatch (MultiEdit/NotebookEdit/Edit/Write contain none of them;
290
- # "PowerShell" itself contains no "Bash").
291
- # - _MATCHER_CONTEXT_INTEL likewise.
292
- # - _MATCHER_BASH_COMPRESS ("Bash") and _MATCHER_READ_CACHE_INV are the
293
- # two where an mcp tool could contain the substring (e.g.
294
- # "mcp__x__Bash"), and BOTH of those hook functions re-check the tool
295
- # name themselves -- bash_compress_hook.main() returns unless
296
- # tool_name == "Bash", read_cache.handle_invalidate returns unless
297
- # tool_name is in ("Edit","Write","MultiEdit","NotebookEdit") -- so an
298
- # over-match is a no-op, not a misfire.
299
- # - _MATCHER_QUALITY_CACHE IS the union, so it is true whenever we run.
261
+ # WHY re.search is exact either way: if the host tests unanchored, it is the
262
+ # same operation on the same pattern. If the host anchors (fullmatch), the union
263
+ # gate admits only the listed tool names plus mcp__*; re.search over-matches none
264
+ # of them except an mcp tool containing "Bash" or an edit-tool name, which
265
+ # bash_compress_hook.main() and read_cache.handle_invalidate both re-check (a
266
+ # no-op, not a misfire). _MATCHER_QUALITY_CACHE is the union itself.
300
267
  #
301
268
  # archive_result was registered TWICE (matchers "mcp__.*" and
302
269
  # "Bash|Read|Glob|Grep|Agent") with a byte-identical command. The two matchers
@@ -450,18 +417,19 @@ def _report_budget_exhausted(name: str, seconds: float, *, skipped: bool) -> Non
450
417
  pass
451
418
 
452
419
 
453
- def _run_safely(name: str, fn, *args, **kwargs) -> None:
420
+ def _run_safely(name: str, fn, *args, **kwargs):
454
421
  """Run fn, swallow any failure to stderr, never propagate.
455
422
 
456
423
  Catches handler budget exhaustion, ``Exception`` and ``SystemExit`` so one
457
424
  subcommand's overrun, bug or internal ``sys.exit()`` cannot abort the
458
- others. In production the shared ``HookDeadline`` watchdog remains the
459
- uncatchable hard process backstop.
425
+ others. Returns the budget (seconds) when the handler overran, else None.
426
+ The shared ``HookDeadline`` watchdog stays the hard process backstop.
460
427
  """
461
428
  try:
462
429
  fn(*args, **kwargs)
463
430
  except _HandlerBudgetExceeded as exc:
464
431
  _report_budget_exhausted(name, exc.seconds, skipped=False)
432
+ return exc.seconds
465
433
  except (Exception, SystemExit):
466
434
  try:
467
435
  sys.stderr.write(f"[Token Optimizer] {name} failed, continuing\n")
@@ -977,6 +945,31 @@ def _sub_quality_cache(hook_input: dict) -> None:
977
945
  # --------------------------------------------------------------------------- #
978
946
 
979
947
 
948
+ _SKIP_LOG_BUDGET = 0.2 # seconds; the row is a 50 ms-timeout SQLite insert
949
+
950
+
951
+ def _log_skipped_compression(name, hook_input, seconds, reason) -> None:
952
+ """Opportunity-tier row for a Bash compression the budget cut off (U2).
953
+
954
+ The raw output went to the model unshrunk: zero saved, so the row is
955
+ tier 'opportunity' with compressed == original (see scripts/hook_skip_log.py).
956
+ Bounded by its own small deadline and never raises.
957
+ """
958
+ if name != "bash_compress_hook":
959
+ return
960
+ remaining = _RUNNER_DEADLINE.remaining() if _RUNNER_DEADLINE is not None else _SKIP_LOG_BUDGET
961
+ budget = min(_SKIP_LOG_BUDGET, remaining / max(1, _SUBCOMMANDS_PENDING + 1))
962
+ if budget < _MIN_HANDLER_BUDGET / 2:
963
+ return
964
+
965
+ def _write():
966
+ from hook_skip_log import log_skipped_compression
967
+
968
+ log_skipped_compression(hook_input, name, seconds, reason)
969
+
970
+ _run_safely("skip-log", lambda: _run_with_handler_deadline(budget, _write))
971
+
972
+
980
973
  def _subcommand_table():
981
974
  return (
982
975
  ("bash_compress_hook", _MATCHER_BASH_COMPRESS, _sub_bash_compress),
@@ -1085,13 +1078,16 @@ def main() -> int:
1085
1078
  budget = _runner_budget(_subcommand_budget(name))
1086
1079
  if budget <= 0:
1087
1080
  _report_budget_exhausted(name, 0.0, skipped=True)
1081
+ _log_skipped_compression(name, hook_input, 0.0, "budget_exhausted")
1088
1082
  return
1089
1083
  buf = io.StringIO()
1090
1084
  with redirect_stdout(buf):
1091
- _run_safely(
1085
+ overran = _run_safely(
1092
1086
  name,
1093
1087
  lambda: _run_with_handler_deadline(budget, fn, *args, **kwargs),
1094
1088
  )
1089
+ if overran is not None:
1090
+ _log_skipped_compression(name, hook_input, overran, "hook_budget")
1095
1091
  captured = buf.getvalue()
1096
1092
  if captured:
1097
1093
  _stdout_bufs.append(captured)
@@ -368,6 +368,12 @@ def _emit_session_start_stdout(parts, hook_input: dict) -> None:
368
368
  # --------------------------------------------------------------------------- #
369
369
 
370
370
 
371
+ def _observe_setup_budget(hook_input: dict) -> None:
372
+ if measure.detect_runtime() == "claude":
373
+ from _measure.setup_budget_monitor import observe_hook
374
+ observe_hook(hook_input, measure.TRENDS_DB)
375
+
376
+
371
377
  def _sub_ensure_health(hook_input: dict) -> None:
372
378
  """``measure.py ensure-health --once-mark`` (hooks.json entry 1).
373
379
 
@@ -485,14 +491,13 @@ def _sub_clear_compacted(hook_input: dict) -> None:
485
491
  def _sub_compact_restore_new_session(hook_input: dict, sink: list) -> None:
486
492
  """``measure.py compact-restore --new-session-only --once-mark`` (entry 5).
487
493
 
488
- Mirrors the ``compact-restore`` dispatch (measure.py ~L42582) with
489
- ``--new-session-only --once-mark``: _mark_ran_this_session (WRITE, never
490
- check -- a resume/compact SessionStart is NOT latched out), then
491
- compact_restore(new_session_only=True), with the same Codex/Cowork wrap
492
- routed into the shared ``sink``.
494
+ Mark every start so the first-prompt fallback stays quiet; offer a
495
+ cross-session pointer only on a fresh startup, never resume or compact.
493
496
  """
494
497
  sid = hook_input.get("session_id")
495
498
  measure._mark_ran_this_session("compact-restore-new-session", sid)
499
+ if hook_input.get("source", "startup") != "startup" or _is_compact_start(hook_input):
500
+ return
496
501
  budget = _runner_budget(measure._int_env("TOKEN_OPTIMIZER_COMPACT_RESTORE_BUDGET", 8))
497
502
  if budget < 0.1:
498
503
  return
@@ -502,6 +507,18 @@ def _sub_compact_restore_new_session(hook_input: dict, sink: list) -> None:
502
507
  sink.append(buf.getvalue())
503
508
 
504
509
 
510
+ def _sub_codemap_hint(hook_input: dict) -> None:
511
+ """Code map discovery hint (codemap_hint.py): plain text, so it lands in
512
+ additionalContext via the envelope. Silent when the feature is off
513
+ (TOKEN_OPTIMIZER_CODEMAP=0) or the cwd has no Python/JS/TS code. Takes no
514
+ runner budget share: a bounded directory probe plus a detached index warm."""
515
+ import codemap_hint # noqa: PLC0415
516
+
517
+ text = codemap_hint.session_text(hook_input)
518
+ if text:
519
+ print(text)
520
+
521
+
505
522
  def _quality_cache_self_heal() -> None:
506
523
  """Replicate the quality-cache dispatch's self-healing block: if the
507
524
  quality-cache hook is missing from settings.json and this is NOT a plugin
@@ -624,6 +641,7 @@ def main() -> int:
624
641
  _runner_budget(8, subcommand_count_hint=pending)
625
642
 
626
643
  _capture("ensure-health", _sub_ensure_health, hook_input)
644
+ _capture("setup-budget-observation", _observe_setup_budget, hook_input)
627
645
  _capture("quality-cache --force", _sub_quality_cache_force, hook_input)
628
646
  if is_compact:
629
647
  _capture("compact-restore --compact", _sub_compact_restore_compact,
@@ -632,6 +650,7 @@ def main() -> int:
632
650
  _capture("read_cache --clear-compacted", _sub_clear_compacted, hook_input)
633
651
  _capture("compact-restore --new-session-only", _sub_compact_restore_new_session,
634
652
  hook_input, _wrapped)
653
+ _capture("codemap hint", _sub_codemap_hint, hook_input)
635
654
 
636
655
  # Emit the compact-restore payloads and ensure-health/quality-cache
637
656
  # systemMessage lines as ONE host-valid JSON object. systemMessage values
@@ -15,8 +15,8 @@ installation cannot retain ``__pycache__``. Consolidation pays that startup
15
15
  cost once, then runs the real work under one shared deadline.
16
16
 
17
17
  The ``SessionEnd`` hook (a fourth entry: ``session-end-flush --trigger end
18
- --defer``, async, timeout 60) joins this runner too. It is a separate hooks.json
19
- entry (different event, ``async: true``, timeout 60) but dispatches the SAME
18
+ --defer``, timeout 60) joins this runner too. It synchronously marks the
19
+ session ended before dispatching the SAME
20
20
  runner file, branching on ``hook_event_name`` so the trigger value ``end`` is
21
21
  preserved exactly. This saves one more measure.py import per session end.
22
22
 
@@ -38,8 +38,7 @@ Key properties:
38
38
  ``--trigger`` / ``--defer`` / ``--quiet`` flags.
39
39
  - The trigger values ``stop`` and ``end`` are preserved EXACTLY so entry
40
40
  budget rules can distinguish the Stop and SessionEnd work.
41
- - The ``async: true`` flag on the SessionEnd hooks.json entry is a host-level
42
- semantic (fire-and-forget); the runner itself is the same for both events.
41
+ - SessionEnd runs synchronously to prevent keep-warm from pinging ended sessions.
43
42
  - No once-per-session latching exists in the Stop/SessionEnd chain (none of
44
43
  the three subcommands use ``_mark_ran_this_session`` or
45
44
  ``_ran_once_this_session``), so there is nothing to preserve there.
@@ -205,8 +204,7 @@ def _run_safely(name: str, fn, *args, **kwargs) -> None:
205
204
  # UserPromptSubmit runners use.
206
205
  #
207
206
  # WHY 58s for SessionEnd:
208
- # * The legacy SessionEnd entry declared timeout=60 with async=true. The
209
- # consolidated entry preserves both. The internal deadline is 58s (2s
207
+ # * SessionEnd runs synchronously with timeout=60. Its internal deadline is 58s (2s
210
208
  # margin under 60). The work is trivial (spawn a detached worker and
211
209
  # return), so the deadline is a safety net that never fires in practice.
212
210
  # * The 58s applies to Claude Code only. The Codex
@@ -348,6 +346,8 @@ def _sub_session_end_flush_end(hook_input: dict) -> None:
348
346
  matches on it. ``--defer`` is preserved (default defer, but the flag is
349
347
  passed through to the detached worker's args).
350
348
  """
349
+ from _measure import keepwarm_safety
350
+ keepwarm_safety.mark_ended(measure.SNAPSHOT_DIR, hook_input.get("session_id"))
351
351
  budget = _runner_budget(60)
352
352
  if budget < 0.1:
353
353
  return
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgreensh/token-optimizer",
3
- "version": "5.13.68",
3
+ "version": "5.13.70",
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)",
@@ -12,6 +12,7 @@ Reference file for Fleet Auditor. Loaded on demand for adapter development.
12
12
  - [Hermes](#hermes)
13
13
  - [OpenCode](#opencode)
14
14
  - [IronClaw](#ironclaw)
15
+ - [Cursor](#cursor)
15
16
 
16
17
  ---
17
18
 
@@ -165,3 +166,40 @@ CREATE TABLE messages (
165
166
  - Requires database connection string from config
166
167
  - Detect only today, no scan
167
168
  - Scanning would need exported data files or a direct DB connection
169
+
170
+ ---
171
+
172
+ ## Cursor
173
+
174
+ **Data Location**: `~/.cursor/token-optimizer/` plus `~/.cursor/_backups/token-optimizer/` (override: `TOKEN_OPTIMIZER_CURSOR_HOME`; snapshot override: `TOKEN_OPTIMIZER_SNAPSHOT_DIR`)
175
+ **Format**: JSON hook tallies + SQLite trends rollup (both written by Token Optimizer's own Cursor adapter — the collector adds no new write paths)
176
+
177
+ ### Key Files
178
+ - `token-optimizer/sessions/{conversation-id}.json` — hook tally, the authoritative session record (turns, tool calls, models, compactions, cwd, timestamps). Written by `cursor_hook_bridge.py`'s `_update_tally`.
179
+ - `_backups/token-optimizer/trends.db` — rollup output (`measure.py cursor-rollup`); `session_log` rows with `platform='cursor'` carry the resolved token figures. Read-only for consumers (`mode=ro`).
180
+
181
+ ### Tally Fields (JSON)
182
+ ```json
183
+ {
184
+ "conversation_id": "...",
185
+ "first_ts": 1762684800.0,
186
+ "updated_at": 1762686600.0,
187
+ "turns": 14,
188
+ "tool_calls": 22,
189
+ "models": {"gpt-5.1": 9},
190
+ "tool_names": {"Shell": 15},
191
+ "compactions": [],
192
+ "cursor_version": "2026.11.05-abc1234",
193
+ "cwd": "/work/project",
194
+ "final": true,
195
+ "end_reason": "sessionEnd"
196
+ }
197
+ ```
198
+
199
+ ### Token Fields
200
+ The tally carries **no token totals**. Tokens come from the rollup's `session_log` (`input_tokens`, `output_tokens`), resolved by the rollup from `state.vscdb` bubble `tokenCount` (best-effort per Cursor staff) or a chars-over-four transcript estimate. Cache read/write breakdown does not exist for Cursor — leave it 0, do not estimate.
201
+
202
+ A tallied session with no rollup row yet has **unknown** token figures: collect it with `token_source = "cursor_tally_only"` and zero tokens, and say the figures are unknown (run `measure.py cursor-rollup`). A silent zero is a defect (#149 class).
203
+
204
+ ### Cost
205
+ `cost_source` is `cursor_no_cost_data`: Cursor exposes no local billing data and Token Optimizer never derives dollar figures for Cursor — no pricing-table lookup, no $0.00-as-free. Fleet rows carry `cost_usd = 0` with an explicit "no cost data" surface; waste columns show token deltas only.