@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,1110 @@
1
+ #!/usr/bin/env python3
2
+ """Single-import PostToolUse dispatcher.
3
+
4
+ Replaces the SIX separate ``PostToolUse`` hooks.json entries that each spawned
5
+ ``python-launcher.sh -> run.py -> module_runner.py -> runpy(<script>)`` --
6
+ eighteen processes per tool call at worst, on the single hottest path in the
7
+ product (PostToolUse fires on EVERY tool call):
8
+
9
+ 1. ``bash_compress_hook.py --quiet`` [Bash] (15s, sync)
10
+ 2. ``archive_result.py --quiet`` [mcp__.*] (15s, async)
11
+ 3. ``archive_result.py --quiet`` [Bash|Read|Glob|Grep|Agent] (15s, async)
12
+ 4. ``context_intel.py --quiet`` [Bash|Read|Grep|Glob|mcp__.*] (15s, async)
13
+ 5. ``read_cache.py --invalidate --quiet`` [Edit|Write|MultiEdit|NotebookEdit] (10s, sync)
14
+ 6. ``measure.py quality-cache --quiet --throttle-only`` [the union matcher] (10s, sync)
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.
32
+
33
+ This runner is invoked ONCE per tool call, pays the dispatch overhead ONCE,
34
+ imports each hook module at most once, and runs every subcommand in-process
35
+ under ONE shared deadline. It is the same consolidation the ``UserPromptSubmit``
36
+ group received in ``hooks/userpromptsubmit_runner.py`` and the
37
+ ``SessionStart`` group received in ``hooks/sessionstart_runner.py``; the
38
+ structure here deliberately mirrors those two files.
39
+
40
+ FOUR THINGS THAT ARE DIFFERENT HERE, and how each is handled:
41
+
42
+ 1. MATCHERS. Unlike the other two groups, these six entries carry FIVE distinct
43
+ tool matchers (and ``archive_result`` is registered TWICE under two of
44
+ them). The consolidated hooks.json entry uses the UNION matcher -- which is
45
+ byte-identical to entry 6's, because entry 6 already matched every tool any
46
+ of the others did -- and each subcommand re-checks its OWN original matcher
47
+ in-process via ``_matches``. See the ``_MATCHER_*`` block for the exact
48
+ equivalence argument, including why ``re.search`` is the right replication
49
+ whichever way the host anchors its own regex.
50
+
51
+ 2. ASYNC. Entries 2, 3 and 4 carried ``"async": true``. A hook group cannot be
52
+ half-async, and entries 1, 5 and 6 CANNOT be async (tests/
53
+ test_async_hook_wiring.py documents why for each), so the consolidated entry
54
+ is SYNCHRONOUS. See the "KNOWN CHANGE" block below for what that costs and
55
+ what it buys.
56
+
57
+ 3. THE HOT PATH. ``measure.py`` is NOT imported at module scope here -- the
58
+ single deviation from the other two runners, and a deliberate one. It is
59
+ imported lazily, only by the quality-cache subcommand, and only after the
60
+ throttle question has been asked. That question is asked through ONE seam
61
+ (``_throttle_tick_due``) so that an import diet which learns to answer it
62
+ without importing measure.py plugs straight in and this consolidation does
63
+ not undo it. See ``_throttle_tick_due``.
64
+
65
+ 4. THE INVARIANT. ``tests/test_hook_runtime_parity.py::
66
+ test_throttle_only_cache_miss_never_parses_transcript`` encodes that a
67
+ throttle-only cache MISS must never parse a transcript. It is enforced
68
+ INSIDE ``measure.quality_cache`` (``if pure_time_throttle and not force and
69
+ not cache_path.exists(): return None``), and this runner calls that function
70
+ with exactly ``pure_time_throttle=True, force=False``, so the invariant is
71
+ preserved by construction, not by re-implementation. There is deliberately
72
+ no bootstrap branch here: the UserPromptSubmit runner owns cache recovery
73
+ precisely because THIS path fires on every tool call.
74
+
75
+ KNOWN CHANGE -- the three async entries become synchronous:
76
+ * ``context_intel.py`` writes to the session store and emits NOTHING on
77
+ stdout, so nothing it produced is gained or lost. What changes is that the
78
+ turn now waits for it. In-process that is ~96ms of real work (223ms cold
79
+ minus the 127ms dispatch overhead it no longer pays).
80
+ * ``archive_result.py`` is the interesting one. Its ``mcp__.*`` registration
81
+ prints ``{"hookSpecificOutput": {"updatedMCPToolOutput": ...}}`` to replace
82
+ an oversized MCP result with a preview plus an archive pointer -- and as an
83
+ ASYNC hook that stdout was DISCARDED ENTIRELY on Claude Code, so the
84
+ replacement never happened there. It already happens on Codex, whose mirror
85
+ strips every async flag because Codex skips async hooks outright. Making
86
+ the group sync therefore does not invent a behaviour; it makes Claude Code
87
+ match the Codex mirror and the code's own documented intent. Large MCP
88
+ results will now actually be replaced by the pointer on Claude Code. That
89
+ is a real, user-visible change and it is called out here rather than buried.
90
+ * What could NOT be preserved: fire-and-forget. Under the old wiring a stalled
91
+ archive/intel write could not delay the turn at all. Now it can, bounded by
92
+ ``_RUNNER_TOTAL_BUDGET``.
93
+
94
+ Key properties (shared with the other two runners):
95
+ - ONE shared ``HookDeadline`` replaces six independent host timeouts. Its
96
+ ``os._exit(0)`` is the ONLY kill switch in the process, so an early
97
+ subcommand hang can never preemptively kill later ones. Remaining time is
98
+ budgeted fairly across the subcommands still pending, seeded from
99
+ ``hook_runtime.resolve_entry_budget`` so the evidence-based per-entry
100
+ numbers keep governing each subcommand after consolidation. Each handler
101
+ gets an interruptible per-handler deadline; an overrun is reported on
102
+ stderr and dispatch continues with the next handler.
103
+ - stdin is read ONCE (six processes each got their own copy from the host;
104
+ one process has one stdin) and the SAME payload is handed to every
105
+ subcommand by patching ``hook_io.read_stdin_hook_input`` before the hook
106
+ modules bind it. The cap is the LARGEST any of the six used.
107
+ - stdout is buffered per subcommand and emitted as AT MOST ONE JSON document
108
+ (see ``_emit_post_tool_use_stdout``).
109
+ - One subcommand throwing/aborting never aborts the others (each is wrapped
110
+ in ``_run_safely``, which catches both ``Exception`` and ``SystemExit``);
111
+ the hook always exits 0.
112
+
113
+ No ``measure.py`` edit, and no edit to any of the four standalone hook scripts:
114
+ every call uses the real entrypoint the script's own ``__main__`` calls. The
115
+ runner only re-orchestrates them.
116
+
117
+ Run: ``hooks/posttooluse_runner.py`` (via run.py -> module_runner.py).
118
+ """
119
+ from __future__ import annotations
120
+
121
+ import io
122
+ import json
123
+ import os
124
+ import re
125
+ import signal
126
+ import sys
127
+ import time
128
+ import traceback
129
+ from contextlib import contextmanager, redirect_stdout
130
+ from pathlib import Path
131
+
132
+
133
+ def _resolve_scripts_dir() -> str:
134
+ """Locate ``skills/token-optimizer/scripts`` so the hook modules import.
135
+
136
+ module_runner.py puts THIS file's parent (``hooks/``) on ``sys.path[0]``;
137
+ the hook scripts live in ``skills/token-optimizer/scripts/``. Resolve it
138
+ from ``CLAUDE_PLUGIN_ROOT`` (set by the host before hook invocation) with a
139
+ ``__file__``-relative fallback (the plugin root is this file's
140
+ grandparent), and insert it ahead of ``hooks/`` so the scripts and their
141
+ sibling modules (hook_io, hook_runtime, session_store, plugin_env, ...)
142
+ resolve. Same resolver the other two runners use.
143
+ """
144
+ candidates: list[Path] = []
145
+ pr = os.environ.get("CLAUDE_PLUGIN_ROOT", "").strip()
146
+ if pr:
147
+ candidates.append(Path(pr) / "skills" / "token-optimizer" / "scripts")
148
+ try:
149
+ candidates.append(
150
+ Path(__file__).resolve().parent.parent
151
+ / "skills" / "token-optimizer" / "scripts"
152
+ )
153
+ except Exception:
154
+ pass
155
+ for c in candidates:
156
+ try:
157
+ if (c / "measure.py").is_file():
158
+ return str(c.resolve())
159
+ except OSError:
160
+ continue
161
+ # Last resort: assume CWD-relative scripts layout (manual/dev invocation).
162
+ return str((Path.cwd() / "skills" / "token-optimizer" / "scripts").resolve())
163
+
164
+
165
+ _SCRIPTS_DIR = _resolve_scripts_dir()
166
+ if _SCRIPTS_DIR and _SCRIPTS_DIR not in sys.path:
167
+ sys.path.insert(0, _SCRIPTS_DIR)
168
+
169
+
170
+ # --------------------------------------------------------------------------- #
171
+ # NOTE: there is NO `import measure` here.
172
+ #
173
+ # The other two runners import it at module scope, which is right for them:
174
+ # UserPromptSubmit fires once per prompt and SessionStart once per session, and
175
+ # every one of their subcommands needs measure anyway. PostToolUse fires on
176
+ # EVERY tool call and exactly ONE of its six subcommands touches measure.py, so
177
+ # a module-scope import would tax every Bash, Read, Grep and Edit in the session
178
+ # with 682ms of cold import (99ms warm) to run four subcommands that never use
179
+ # it. measure is imported lazily by _measure(), from the quality-cache
180
+ # subcommand only. See _throttle_tick_due for the import-diet seam.
181
+ # --------------------------------------------------------------------------- #
182
+
183
+ _MEASURE = None
184
+
185
+
186
+ def _measure():
187
+ """Import measure.py on first use and cache it. Raises on real failure."""
188
+ global _MEASURE
189
+ if _MEASURE is None:
190
+ import measure # noqa: PLC0415 (lazy by design -- see the note above)
191
+
192
+ _MEASURE = measure
193
+ return _MEASURE
194
+
195
+
196
+ # --------------------------------------------------------------------------- #
197
+ # Shared stdin.
198
+ #
199
+ # Pre-consolidation each of the six entries was its own process and the host
200
+ # handed each one its own copy of the PostToolUse payload. One process has one
201
+ # stdin, readable once, so the runner reads it once and hands the SAME payload
202
+ # to every subcommand.
203
+ #
204
+ # Mechanism: ``hook_io.read_stdin_hook_input`` is the single source every hook
205
+ # script reads through (bash_compress_hook imports it INSIDE main(); archive_
206
+ # result, context_intel and read_cache bind it at module import). Patching
207
+ # hook_io BEFORE importing any of them covers both binding styles; the module
208
+ # attribute is re-patched after each import as belt and braces in case a module
209
+ # was already in sys.modules.
210
+ #
211
+ # The cap is the LARGEST of the six (archive_result's), not the smallest. Two
212
+ # of the six read only 1 MB, and on a payload above that they used to get {}
213
+ # and silently no-op -- read_cache.py --invalidate would skip invalidating the
214
+ # cache for a large edit, and quality-cache would fall back to the legacy
215
+ # GLOBAL throttle marker instead of the per-session one. Handing them the real
216
+ # payload fixes both. That is a behaviour change, and an intended one.
217
+ # --------------------------------------------------------------------------- #
218
+
219
+ # archive_result._STDIN_MAX_BYTES == _ARCHIVE_MAX_SIZE (5 MB) + 262_144, the
220
+ # largest of the six. Hardcoded rather than imported so reading stdin never
221
+ # requires importing archive_result (sqlite3, session_store, ...) on a tool
222
+ # call that will not use it. tests/test_posttooluse_runner.py pins this value
223
+ # against the real module constants so it cannot silently drift.
224
+ _STDIN_MAX_BYTES = 5_242_880 + 262_144
225
+
226
+
227
+ def _read_hook_input() -> dict:
228
+ """Read the hook stdin JSON once, non-blocking, shared across subcommands."""
229
+ try:
230
+ from hook_io import read_stdin_hook_input
231
+
232
+ return read_stdin_hook_input(_STDIN_MAX_BYTES) or {}
233
+ except Exception:
234
+ return {}
235
+
236
+
237
+ def _install_shared_stdin(payload: dict) -> None:
238
+ """Make every subcommand's stdin read return the payload we already read."""
239
+
240
+ def _shared(max_bytes=None, *_a, **_kw):
241
+ # A shallow copy per caller: the top-level dict cannot be mutated for
242
+ # the next subcommand. tool_response is a str (immutable) so the 5 MB
243
+ # body is shared by reference, not copied.
244
+ return dict(payload)
245
+
246
+ try:
247
+ import hook_io
248
+
249
+ hook_io.read_stdin_hook_input = _shared
250
+ except Exception:
251
+ pass
252
+
253
+
254
+ def _rebind_shared_stdin(module) -> None:
255
+ """Re-patch a module that bound read_stdin_hook_input at import time."""
256
+ try:
257
+ if hasattr(module, "read_stdin_hook_input"):
258
+ import hook_io
259
+
260
+ module.read_stdin_hook_input = hook_io.read_stdin_hook_input
261
+ except Exception:
262
+ pass
263
+
264
+
265
+ # --------------------------------------------------------------------------- #
266
+ # Matcher replication.
267
+ #
268
+ # The host still applies the UNION matcher to the consolidated entry, so the
269
+ # runner only ever sees a tool that at least one of the six would have seen.
270
+ # Each subcommand then re-checks its own original matcher here.
271
+ #
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.
300
+ #
301
+ # archive_result was registered TWICE (matchers "mcp__.*" and
302
+ # "Bash|Read|Glob|Grep|Agent") with a byte-identical command. The two matchers
303
+ # are disjoint, so it ran at most once per tool call; the alternation of the
304
+ # two below is exactly equivalent under search, and it runs once here.
305
+ # --------------------------------------------------------------------------- #
306
+
307
+ _MATCHER_BASH_COMPRESS = "Bash"
308
+ # PowerShell is in the archive/intel matchers: both handlers only read the
309
+ # tool's OUTPUT (archive the body, log the activity row), which is
310
+ # tool-name-generic. bash_compress_hook stays Bash-only -- it rewrites Bash
311
+ # command-line output, which is not valid for PowerShell -- and read_cache
312
+ # --invalidate stays on the edit tools.
313
+ _MATCHER_ARCHIVE = "Bash|PowerShell|Read|Glob|Grep|Agent|mcp__.*"
314
+ _MATCHER_CONTEXT_INTEL = (
315
+ "Bash|PowerShell|Read|Grep|Glob|Edit|Write|MultiEdit|NotebookEdit|mcp__.*"
316
+ )
317
+ _MATCHER_READ_CACHE_INVALIDATE = "Edit|Write|MultiEdit|NotebookEdit"
318
+ _MATCHER_QUALITY_CACHE = (
319
+ "Bash|PowerShell|Read|Glob|Grep|Agent|Edit|Write|MultiEdit|NotebookEdit|mcp__.*"
320
+ )
321
+
322
+ # Entry 6's matcher IS the union, and the union is what the consolidated
323
+ # hooks.json entry declares. So if the host invoked this runner at all, entry 6
324
+ # matched -- by definition, under whatever anchoring the host uses. Gating the
325
+ # quality-cache subcommand on `None` (always run) rather than re-matching the
326
+ # string is therefore both simpler and strictly MORE faithful: a payload that
327
+ # arrives with a missing or unexpected tool_name still gets the tick it used to
328
+ # get, instead of being silently dropped by a re-derivation of a decision the
329
+ # host already made.
330
+ _MATCHER_UNION = None
331
+
332
+
333
+ def _matches(pattern, tool_name: str) -> bool:
334
+ """Replicate the host's tool-name matcher gate. Fail CLOSED on a bad regex.
335
+
336
+ ``pattern is None`` means "the consolidated entry's own union matcher",
337
+ which the host already evaluated: always True. Otherwise case-sensitive
338
+ ``re.search``, like the host. A pattern that will not compile means this
339
+ file is broken, and the safe answer for a hook that must not fire on the
340
+ wrong tool is "do not fire".
341
+ """
342
+ if pattern is None:
343
+ return True
344
+ if not tool_name:
345
+ return False
346
+ try:
347
+ return bool(re.search(pattern, tool_name))
348
+ except re.error:
349
+ return False
350
+
351
+
352
+ class _HandlerBudgetExceeded(BaseException):
353
+ """Raised by a per-handler alarm so the dispatcher can continue."""
354
+
355
+ def __init__(self, seconds: float):
356
+ super().__init__(seconds)
357
+ self.seconds = seconds
358
+
359
+
360
+ @contextmanager
361
+ def _handler_deadline(seconds: float):
362
+ """Bound one handler without killing the shared runner.
363
+
364
+ POSIX hook processes can interrupt Python sleeps and other Python-level
365
+ waits with SIGALRM. On platforms without interval timers, the completion
366
+ check still makes an overrun visible, while the shared process deadline
367
+ remains the hard backstop.
368
+ """
369
+ if _RUNNER_DEADLINE is None or seconds <= 0:
370
+ yield
371
+ return
372
+
373
+ setitimer = getattr(signal, "setitimer", None)
374
+ timer_kind = getattr(signal, "ITIMER_REAL", None)
375
+ alarm_signal = getattr(signal, "SIGALRM", None)
376
+ if setitimer is None or timer_kind is None or alarm_signal is None:
377
+ started = time.monotonic()
378
+ completed = False
379
+ try:
380
+ yield
381
+ completed = True
382
+ finally:
383
+ if completed and time.monotonic() - started >= seconds:
384
+ raise _HandlerBudgetExceeded(seconds)
385
+ return
386
+
387
+ try:
388
+ previous_handler = signal.getsignal(alarm_signal)
389
+ previous_timer = signal.getitimer(timer_kind)
390
+ except (AttributeError, OSError, ValueError):
391
+ yield
392
+ return
393
+
394
+ started = time.monotonic()
395
+
396
+ def _raise_timeout(_signum, _frame):
397
+ raise _HandlerBudgetExceeded(seconds)
398
+
399
+ try:
400
+ signal.signal(alarm_signal, _raise_timeout)
401
+ setitimer(timer_kind, seconds)
402
+ yield
403
+ finally:
404
+ elapsed = time.monotonic() - started
405
+ outer_delivered = False
406
+ try:
407
+ setitimer(timer_kind, 0)
408
+ signal.signal(alarm_signal, previous_handler)
409
+ previous_remaining, previous_interval = previous_timer
410
+ if previous_remaining > 0:
411
+ outer_remaining = previous_remaining - elapsed
412
+ if outer_remaining > 0:
413
+ # Outer deadline still has budget: re-arm it for what's left.
414
+ setitimer(timer_kind, outer_remaining, previous_interval)
415
+ elif callable(previous_handler):
416
+ # Outer deadline already elapsed while the inner block ran.
417
+ # Passing max(0.0, ...) -> 0.0 to setitimer would DISARM it,
418
+ # silently dropping the outer budget. Deliver it now instead
419
+ # via the just-restored outer handler. (Skipped when the
420
+ # previous handler is SIG_DFL/SIG_IGN, so we never turn an
421
+ # expired timer into a process-killing default SIGALRM.)
422
+ # M-13: set a flag so the inner raise below is skipped —
423
+ # otherwise both inner and outer budgets report exhaustion
424
+ # for a single invocation (double "budget exhausted" stderr).
425
+ os.kill(os.getpid(), alarm_signal)
426
+ outer_delivered = True
427
+ except (OSError, ValueError):
428
+ pass
429
+ # M-13: skip the inner raise if the outer budget was already delivered
430
+ # via os.kill above. The outer handler already raised _HandlerBudgetExceeded.
431
+ if elapsed >= seconds and not outer_delivered:
432
+ raise _HandlerBudgetExceeded(seconds)
433
+
434
+
435
+ def _run_with_handler_deadline(seconds: float, fn, *args, **kwargs) -> None:
436
+ """Run one handler under its fair-share deadline."""
437
+ with _handler_deadline(seconds):
438
+ fn(*args, **kwargs)
439
+
440
+
441
+ def _report_budget_exhausted(name: str, seconds: float, *, skipped: bool) -> None:
442
+ action = "skipping" if skipped else "continuing"
443
+ detail = "was exhausted before dispatch" if skipped else f"exceeded {seconds:.3f}s"
444
+ try:
445
+ sys.stderr.write(
446
+ f"[Token Optimizer] {name} budget {detail}; {action}\n"
447
+ )
448
+ sys.stderr.flush()
449
+ except (OSError, ValueError):
450
+ pass
451
+
452
+
453
+ def _run_safely(name: str, fn, *args, **kwargs) -> None:
454
+ """Run fn, swallow any failure to stderr, never propagate.
455
+
456
+ Catches handler budget exhaustion, ``Exception`` and ``SystemExit`` so one
457
+ 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.
460
+ """
461
+ try:
462
+ fn(*args, **kwargs)
463
+ except _HandlerBudgetExceeded as exc:
464
+ _report_budget_exhausted(name, exc.seconds, skipped=False)
465
+ except (Exception, SystemExit):
466
+ try:
467
+ sys.stderr.write(f"[Token Optimizer] {name} failed, continuing\n")
468
+ traceback.print_exc(file=sys.stderr)
469
+ sys.stderr.flush()
470
+ except (OSError, ValueError):
471
+ pass
472
+
473
+
474
+ # --------------------------------------------------------------------------- #
475
+ # Shared deadline.
476
+ #
477
+ # ONE HookDeadline for the whole runner replaces the six independent host
478
+ # timeouts (15 + 15 + 15 + 15 + 10 + 10 = 80s declared).
479
+ #
480
+ # WHY 2.5s, when the other two runners use 18s:
481
+ # * They fire once per prompt / once per session. This fires on EVERY tool
482
+ # call, so its ceiling is a latency budget, not a safety net, and
483
+ # hook_runtime's per-entry table sizes this event in HUNDREDS of
484
+ # milliseconds (BUDGET_POSTTOOL 0.75s, BUDGET_POSTTOOL_MEASURE 2.0s), from
485
+ # measured cold cost.
486
+ # * The consolidated worst case is measurably smaller than the six-entry sum:
487
+ # one 127ms dispatch instead of up to five, and one measure import instead
488
+ # of one-plus-four-modules. Cold worst case ~1.1s
489
+ # (127 dispatch + ~91 archive + ~96 intel + ~91 invalidate + ~671
490
+ # quality-cache-with-measure-import), warm ~0.3s. 2.5s is ~2.3x the cold
491
+ # worst case.
492
+ # * module_runner arms hook_runtime's own SILENT backstop for this entry
493
+ # (BUDGET_POSTTOOL_RUNNER, 4.5s). 2.5s leaves 2.0s of margin under it -- the
494
+ # same 2s margin the other two runners keep under their declared timeout --
495
+ # so this deadline always wins the race and the runner self-exits 0 with its
496
+ # buffered stdout emitted, rather than being hard-killed mid-write. The
497
+ # hooks.json declared timeout (10s) is a third-tier backstop above both.
498
+ # --------------------------------------------------------------------------- #
499
+
500
+ _RUNNER_DEADLINE = None
501
+ _RUNNER_TOTAL_BUDGET = 2.5 # seconds, 2s margin under hook_runtime's 4.5s backstop
502
+ _SUBCOMMANDS_PENDING = 0 # handlers still waiting for their turn
503
+ _MIN_HANDLER_BUDGET = 0.1
504
+
505
+
506
+ def _install_runner_deadline(total_seconds=None):
507
+ """Arm ONE shared HookDeadline watchdog for the entire runner."""
508
+ global _RUNNER_DEADLINE
509
+ if _RUNNER_DEADLINE is not None:
510
+ return _RUNNER_DEADLINE
511
+ if total_seconds is None:
512
+ total_seconds = _RUNNER_TOTAL_BUDGET
513
+ try:
514
+ from hook_runtime import HookDeadline
515
+
516
+ _RUNNER_DEADLINE = HookDeadline(total_seconds)
517
+ _RUNNER_DEADLINE.start()
518
+ except Exception:
519
+ _RUNNER_DEADLINE = None
520
+ return _RUNNER_DEADLINE
521
+
522
+
523
+ def _runner_budget(default_seconds, subcommand_count_hint=None):
524
+ """Return the fair-share budget (seconds) for one subcommand.
525
+
526
+ Divides the shared deadline's remaining time among the subcommands that
527
+ have not yet run. ``subcommand_count_hint`` seeds the pending count and is
528
+ not itself a handler, so the first handler receives a true 1/N share.
529
+ Budgets below the minimum are returned as zero for an explicit, visible
530
+ skip rather than silently handing out time that cannot be used.
531
+ """
532
+ global _SUBCOMMANDS_PENDING
533
+ if subcommand_count_hint is not None:
534
+ _SUBCOMMANDS_PENDING = max(0, int(subcommand_count_hint))
535
+ return 0.0
536
+ _SUBCOMMANDS_PENDING = max(0, _SUBCOMMANDS_PENDING - 1)
537
+ if _RUNNER_DEADLINE is None:
538
+ return default_seconds
539
+ remaining = _RUNNER_DEADLINE.remaining()
540
+ if remaining <= 0:
541
+ return 0.0
542
+ divisor = max(1, _SUBCOMMANDS_PENDING + 1)
543
+ fair = remaining / divisor
544
+ if fair < _MIN_HANDLER_BUDGET:
545
+ return 0.0
546
+ return min(default_seconds, fair)
547
+
548
+
549
+ def _clear_runner_deadline():
550
+ """Cancel the shared deadline (normal completion)."""
551
+ global _RUNNER_DEADLINE
552
+ if _RUNNER_DEADLINE is not None:
553
+ try:
554
+ _RUNNER_DEADLINE.cancel()
555
+ except Exception:
556
+ pass
557
+ _RUNNER_DEADLINE = None
558
+
559
+
560
+ def _entry_budget(module_name, argv, fallback):
561
+ """Per-subcommand default budget, taken from hook_runtime's own table.
562
+
563
+ The table in ``hook_runtime._entry_budget_rules`` still carries a rule for
564
+ each of the five original PostToolUse entry points, with the measured
565
+ evidence behind every number. After consolidation module_runner no longer
566
+ matches those rules (it sees module ``posttooluse_runner``), so the runner
567
+ consumes them HERE instead: the table stays the single source of truth for
568
+ "how long is this hook allowed to take", and a future tuning pass to those
569
+ numbers still lands on this path. Falls back to the caller's number if
570
+ hook_runtime or the rule is unavailable.
571
+ """
572
+ try:
573
+ from hook_runtime import resolve_entry_budget
574
+
575
+ seconds, _label = resolve_entry_budget(module_name, list(argv))
576
+ if seconds:
577
+ return seconds
578
+ except Exception:
579
+ pass
580
+ return fallback
581
+
582
+
583
+ # --------------------------------------------------------------------------- #
584
+ # The PostToolUse stdout envelope.
585
+ #
586
+ # Pre-consolidation each subcommand owned its own stdout stream and the host
587
+ # parsed each independently. Now they share one, and two JSON documents on one
588
+ # stream -- or a JSON document with a stray plain-text line beside it -- is not
589
+ # parseable. Only two of the six ever write to stdout:
590
+ #
591
+ # bash_compress_hook {"hookSpecificOutput": {"hookEventName": "PostToolUse",
592
+ # "updatedToolOutput": {...}}} -- only when tool == Bash
593
+ # archive_result {"hookSpecificOutput": {"hookEventName": "PostToolUse",
594
+ # "updatedMCPToolOutput": "..."}} -- only when "__" in tool
595
+ #
596
+ # Those two conditions are mutually exclusive (a tool is either exactly "Bash"
597
+ # or an mcp__ tool, never both), so in practice AT MOST ONE JSON document
598
+ # exists and it is emitted BYTE-IDENTICALLY to what the six-entry wiring
599
+ # produced. The merge path below exists so that a future change which makes
600
+ # both fire cannot corrupt the stream: the two payload keys live side by side
601
+ # in one hookSpecificOutput object, which is valid.
602
+ # --------------------------------------------------------------------------- #
603
+
604
+
605
+ def _emit_post_tool_use_stdout(parts) -> None:
606
+ """Emit every subcommand's stdout as AT MOST ONE host-valid JSON document."""
607
+ texts = [p for p in parts if p and p.strip()]
608
+ if not texts:
609
+ return
610
+
611
+ payloads = []
612
+ plain = []
613
+ for text in texts:
614
+ stripped = text.strip()
615
+ if stripped[:1] in ("{", "["):
616
+ try:
617
+ parsed = json.loads(stripped)
618
+ except ValueError:
619
+ plain.append(text)
620
+ continue
621
+ if isinstance(parsed, dict):
622
+ payloads.append((text, parsed))
623
+ else:
624
+ plain.append(text)
625
+ else:
626
+ plain.append(text)
627
+
628
+ if not payloads:
629
+ # No JSON in play: the raw stream is exactly what the host used to see.
630
+ for text in plain:
631
+ sys.stdout.write(text)
632
+ return
633
+
634
+ if len(payloads) == 1 and not plain:
635
+ # The overwhelming common case. Emit the original bytes untouched so the
636
+ # host sees precisely what the standalone hook produced.
637
+ sys.stdout.write(payloads[0][0])
638
+ return
639
+
640
+ merged: dict = {}
641
+ hook_specific: dict = {}
642
+ for _text, obj in payloads:
643
+ for key, value in obj.items():
644
+ if key == "hookSpecificOutput" and isinstance(value, dict):
645
+ hook_specific.update(value)
646
+ else:
647
+ merged[key] = value
648
+ if hook_specific:
649
+ merged["hookSpecificOutput"] = hook_specific
650
+ sys.stdout.write(json.dumps(merged))
651
+
652
+ # Plain text alongside JSON would break the parse. On exit 0 a PostToolUse
653
+ # hook's stdout and stderr are both transcript-only, so routing it to stderr
654
+ # keeps it visible in the same place without corrupting the document.
655
+ for text in plain:
656
+ try:
657
+ sys.stderr.write(text)
658
+ except (OSError, ValueError):
659
+ pass
660
+
661
+
662
+ # --------------------------------------------------------------------------- #
663
+ # Subcommand handlers -- each mirrors its hooks.json entry exactly.
664
+ # --------------------------------------------------------------------------- #
665
+
666
+
667
+ _SUBCOMMAND_BUDGETS = {
668
+ "bash_compress_hook": ("bash_compress_hook", ["--quiet"], 0.75),
669
+ "archive_result": ("archive_result", ["--quiet"], 0.75),
670
+ "context_intel": ("context_intel", ["--quiet"], 0.75),
671
+ "read_cache --invalidate": ("read_cache", ["--invalidate", "--quiet"], 0.75),
672
+ "quality-cache --throttle-only": (
673
+ "measure",
674
+ ["quality-cache", "--quiet", "--throttle-only"],
675
+ 2.0,
676
+ ),
677
+ }
678
+
679
+
680
+ def _subcommand_budget(name: str) -> float:
681
+ module_name, argv, fallback = _SUBCOMMAND_BUDGETS[name]
682
+ return _entry_budget(module_name, argv, fallback)
683
+
684
+
685
+ def _sub_bash_compress(hook_input: dict) -> None:
686
+ """``bash_compress_hook.py --quiet`` (entry 1, matcher ``Bash``).
687
+
688
+ Calls the script's own ``main()``, which reads the shared payload through
689
+ the patched ``hook_io.read_stdin_hook_input`` (it imports it inside main(),
690
+ so the hook_io patch is what reaches it) and self-gates on
691
+ ``tool_name != "Bash"``. It emits the ``updatedToolOutput`` replacement.
692
+ """
693
+ import bash_compress_hook # noqa: PLC0415 (lazy: per-tool-call hot path)
694
+
695
+ _rebind_shared_stdin(bash_compress_hook)
696
+ bash_compress_hook.main()
697
+
698
+
699
+ def _sub_archive_result(hook_input: dict) -> None:
700
+ """``archive_result.py --quiet`` (entries 2 AND 3 -- one call, see the
701
+ matcher block: the two registrations are the same command under two
702
+ disjoint matchers, so it ran at most once per tool call before too).
703
+ """
704
+ import archive_result # noqa: PLC0415 (lazy: per-tool-call hot path)
705
+
706
+ _rebind_shared_stdin(archive_result)
707
+ archive_result.archive_result(quiet=True)
708
+
709
+
710
+ def _sub_context_intel(hook_input: dict) -> None:
711
+ """``context_intel.py --quiet`` (entry 4). Emits nothing on stdout."""
712
+ import context_intel # noqa: PLC0415 (lazy: per-tool-call hot path)
713
+
714
+ _rebind_shared_stdin(context_intel)
715
+ context_intel.handle_post_tool_use()
716
+
717
+
718
+ def _sub_read_cache_invalidate(hook_input: dict) -> None:
719
+ """``read_cache.py --invalidate --quiet`` (entry 5).
720
+
721
+ Mirrors read_cache.main()'s --invalidate branch: no payload -> return, else
722
+ ``handle_invalidate(payload, quiet=True)``. Called directly with the shared
723
+ payload (the same shape sessionstart_runner uses for --clear-compacted).
724
+ """
725
+ if not hook_input:
726
+ return
727
+ import read_cache # noqa: PLC0415 (lazy: per-tool-call hot path)
728
+
729
+ read_cache.handle_invalidate(hook_input, True)
730
+
731
+
732
+ def _throttle_tick_due(hook_input: dict, throttle_seconds: int = 120) -> bool:
733
+ """Is a quality-cache refresh due? -- asked as cheaply as the install allows.
734
+
735
+ FALLBACK GATE. The primary route is ``_delegate_to_quality_cache_gate``,
736
+ which hands the whole subcommand to the import diet's
737
+ ``quality_cache_gate.py`` when that module is present. This function is what
738
+ runs when it is not.
739
+
740
+ The question itself costs one ``stat()`` of a marker file, but the only
741
+ implementation of that stat in THIS tree lives in
742
+ ``measure._quality_cache_tick_due``, so asking costs a 682ms cold measure
743
+ import to run a syscall -- which is exactly why the throttle-only entry was
744
+ the 798ms cold outlier of the six. A measure-free
745
+ ``hook_runtime.quality_cache_tick_due(throttle_seconds, filepath,
746
+ session_id)`` is honoured first if one ever appears, so the fallback path
747
+ can shed the import too without another edit here.
748
+
749
+ Deliberately NOT re-implemented here. The marker path is derived from
750
+ measure's ``_STATE_BASE`` / ``QUALITY_CACHE_DIR`` resolution; a second copy
751
+ of that logic in this file would be a second source of truth that could
752
+ drift from the diet's, and drift here means either a stale statusline or a
753
+ transcript parse on every tool call. One implementation, one seam.
754
+
755
+ Fails OPEN (returns True) so a broken gate degrades to "ask the real
756
+ quality_cache()", which enforces the throttle itself, rather than silently
757
+ freezing the statusline forever.
758
+ """
759
+ gate = None
760
+ try:
761
+ import hook_runtime
762
+
763
+ gate = getattr(hook_runtime, "quality_cache_tick_due", None)
764
+ except Exception:
765
+ gate = None
766
+ if gate is None:
767
+ try:
768
+ gate = _measure()._quality_cache_tick_due
769
+ except Exception:
770
+ return True
771
+ try:
772
+ return bool(
773
+ gate(
774
+ throttle_seconds,
775
+ hook_input.get("transcript_path"),
776
+ hook_input.get("session_id"),
777
+ )
778
+ )
779
+ except Exception:
780
+ return True
781
+
782
+
783
+ def _delegate_to_quality_cache_gate(hook_input: dict) -> bool:
784
+ """Route the quality-cache subcommand through ``quality_cache_gate.py``.
785
+
786
+ THE IMPORT DIET, as it actually landed. A parallel workstream added
787
+ ``skills/token-optimizer/scripts/quality_cache_gate.py``: a standalone hook
788
+ script that answers the throttle question with ONE ``stat()`` of the marker
789
+ and exits, importing measure.py only on the rare tick where the throttle has
790
+ expired. It was built to REPLACE ``measure.py quality-cache --quiet
791
+ --throttle-only`` as this event's hooks.json entry -- the very entry this
792
+ consolidation folds in -- so the two changes touch the same hook.
793
+
794
+ They compose instead of colliding, because the gate module IS the whole
795
+ PostToolUse quality-cache entry point (gate, then the work). Delegating to
796
+ it wholesale means the gate stays the single source of truth for the
797
+ decision, this runner picks up the entire cold-import win the moment the
798
+ module lands, and neither change undoes the other. The inline path below is
799
+ the fallback for a tree where the module is not present yet, and it stays
800
+ fully tested.
801
+
802
+ Returns True when the gate module owned the call (so the caller must NOT
803
+ also run the inline path and do the work twice), False when it is absent.
804
+
805
+ TWO THINGS THE GATE ASSUMES THAT ARE NOT TRUE IN HERE, both handled below.
806
+
807
+ 1. It reads its own stdin. On POSIX that goes through
808
+ ``hook_io.read_stdin_hook_input``, which this runner has already patched,
809
+ so it would work by luck. On Windows ``_read_stdin_payload`` peeks and
810
+ reads ``sys.stdin`` DIRECTLY, bypassing hook_io -- and this runner has
811
+ already drained stdin, so the gate would get ``{}``, fall back to the
812
+ legacy GLOBAL throttle marker instead of the per-session one, and share
813
+ one throttle window across every concurrent session. So the payload is
814
+ injected by replacing ``_read_stdin_payload`` for the duration of the
815
+ call rather than relying on the hook_io patch reaching it.
816
+
817
+ 2. It parses ``sys.argv[1:]`` for ``--quiet``. Under module_runner this
818
+ process's argv is ``["posttooluse_runner"]``, so the gate would run with
819
+ ``quiet=False`` and could print on a path the standalone entry
820
+ (``... quality_cache_gate.py --quiet``) kept silent. argv is set to the
821
+ flags that entry passed, and restored afterwards.
822
+
823
+ Both are restored in a ``finally`` so a raising gate cannot leave this
824
+ process with a foreign argv or a stubbed reader.
825
+ """
826
+ try:
827
+ import quality_cache_gate # noqa: PLC0415 (optional: import diet)
828
+ except Exception:
829
+ return False
830
+ entry = getattr(quality_cache_gate, "main", None)
831
+ if not callable(entry):
832
+ return False
833
+
834
+ saved_argv = sys.argv
835
+ saved_reader = getattr(quality_cache_gate, "_read_stdin_payload", None)
836
+ try:
837
+ sys.argv = ["quality_cache_gate", "--quiet"]
838
+ if saved_reader is not None:
839
+ quality_cache_gate._read_stdin_payload = lambda: dict(hook_input)
840
+ _rebind_shared_stdin(quality_cache_gate)
841
+ entry()
842
+ finally:
843
+ sys.argv = saved_argv
844
+ if saved_reader is not None:
845
+ quality_cache_gate._read_stdin_payload = saved_reader
846
+ return True
847
+
848
+
849
+ def _quality_cache_self_heal() -> None:
850
+ """Replicate the quality-cache dispatch's self-healing block: if the
851
+ quality-cache hook is missing from settings.json and this is NOT a plugin
852
+ install and quality_bar_disabled is unset, reinstall it.
853
+
854
+ For plugin installs (the hooks.json context this runner runs in) the
855
+ ``_is_plugin`` check is True and the block is a no-op, exactly as in the
856
+ dispatch. Replicated verbatim so non-plugin manual installs keep the same
857
+ self-heal behavior. Uses ``measure._quality_cache_hook_present`` so an
858
+ install whose canonical hook is a consolidated dispatcher is not
859
+ "healed" by appending a duplicate legacy hook. Fail-open: never raises.
860
+
861
+ Note the ORDER: in the dispatch this runs only AFTER the throttle-only
862
+ ``due`` check has passed (``if not due: sys.exit(0)`` comes first), so on a
863
+ not-due tick neither settings.json nor config.json is read. That ordering is
864
+ preserved in ``_sub_quality_cache`` and it matters -- these are two file
865
+ reads on the hottest path in the product.
866
+ """
867
+ measure = _measure()
868
+ try:
869
+ _is_plugin = (
870
+ measure._is_running_from_plugin_cache() or measure._is_plugin_installed()
871
+ )
872
+ try:
873
+ _qb_disabled = False
874
+ if measure.CONFIG_PATH.exists():
875
+ _qb_cfg = json.loads(measure.CONFIG_PATH.read_text(encoding="utf-8"))
876
+ _qb_disabled = _qb_cfg.get("quality_bar_disabled", False)
877
+ if (not _is_plugin and not _qb_disabled
878
+ and measure._is_regular_file(measure.SETTINGS_PATH)):
879
+ _sh_settings = json.loads(
880
+ measure.SETTINGS_PATH.read_text(encoding="utf-8")
881
+ )
882
+ _sh_hooks = _sh_settings.get("hooks", {}).get("UserPromptSubmit", [])
883
+ if not measure._quality_cache_hook_present(_sh_hooks):
884
+ measure.setup_quality_bar(quiet=True)
885
+ except Exception:
886
+ pass
887
+ except Exception:
888
+ pass
889
+
890
+
891
+ def _sub_quality_cache(hook_input: dict) -> None:
892
+ """``measure.py quality-cache --quiet --throttle-only`` (entry 6).
893
+
894
+ Mirrors the ``quality-cache`` dispatch (measure.py ~L43065) for this exact
895
+ flag set, in the dispatch's own order:
896
+
897
+ 1. argument-only policy: quiet=True, warn=False, force=False,
898
+ throttle_only=True, throttle=120, warn_threshold=70.
899
+ 2. the throttle-only gate FIRST, before touching the filesystem, the
900
+ daemon, settings, or config. Not due -> return, having done nothing.
901
+ 3. the mid-session daemon liveness pulse (swallowed).
902
+ 4. the settings.json self-heal block.
903
+ 5. quality_cache(..., pure_time_throttle=True, force=False). Neither
904
+ --once-mark nor --once-per-session is in this entry's argv, so neither
905
+ marker branch applies, and hook_event_name is PostToolUse so the
906
+ SessionStart JSON-collapsing wrapper does not apply either.
907
+ 6. the cohort-tripwire piggyback, which the dispatch runs only on the
908
+ throttle-only path.
909
+
910
+ NO RUN-ONCE MARKER, DELIBERATELY. This entry's argv carries neither
911
+ ``--once-mark`` nor ``--once-per-session``, so neither marker branch of the
912
+ dispatch applies and this runner writes no session marker at all. That
913
+ matters beyond parity: ``quality-cache-force`` is a marker path SHARED with
914
+ the SessionStart and UserPromptSubmit runners, and a marker latched here
915
+ before the work completed would silently disable the UserPromptSubmit
916
+ recovery path (which opens by checking ``_ran_once_this_session(
917
+ "quality-cache-force")``) for the rest of the session. The only marker this
918
+ path touches at all is the 120s throttle marker, and measure touches that
919
+ inside ``_write_quality_cache`` AFTER ``os.replace`` succeeds -- i.e. after
920
+ the work, never before it. Keep it that way.
921
+
922
+ THE INVARIANT (tests/test_hook_runtime_parity.py::
923
+ test_throttle_only_cache_miss_never_parses_transcript): a throttle-only
924
+ cache MISS must never parse a transcript. It is enforced inside
925
+ ``quality_cache`` by ``if pure_time_throttle and not force and not
926
+ cache_path.exists(): return None``, and the two kwargs that arm it are
927
+ passed literally below. There is NO bootstrap branch here, deliberately:
928
+ the UserPromptSubmit runner owns cache recovery because it fires once per
929
+ prompt, while this fires on every tool call.
930
+ """
931
+ # Prefer the dedicated gate module when the import diet has landed it. See
932
+ # _delegate_to_quality_cache_gate.
933
+ if _delegate_to_quality_cache_gate(hook_input):
934
+ return
935
+
936
+ throttle = 120
937
+ warn_threshold = 70
938
+
939
+ # Step 2: the gate, BEFORE any filesystem/daemon/settings work.
940
+ if not _throttle_tick_due(hook_input, throttle):
941
+ return
942
+
943
+ measure = _measure()
944
+ try:
945
+ measure._daemon_midsession_pulse()
946
+ except Exception:
947
+ pass
948
+ _quality_cache_self_heal()
949
+
950
+ measure.quality_cache(
951
+ throttle_seconds=throttle,
952
+ warn_threshold=warn_threshold,
953
+ quiet=True,
954
+ session_jsonl=hook_input.get("transcript_path"),
955
+ force=False,
956
+ pure_time_throttle=True,
957
+ session_id=hook_input.get("session_id"),
958
+ warn=False,
959
+ )
960
+
961
+ # Tripwire piggyback: the --throttle-only invocation fires on the PostToolUse
962
+ # Edit/Write path (where active first-read follow-ups are resolved), so this
963
+ # is the natural place to refresh the per-cohort live edit-rate verdict. It
964
+ # is mtime-gated to 5 min, so the common case is a single sidecar stat().
965
+ try:
966
+ measure.evaluate_cohort_tripwire()
967
+ except Exception:
968
+ pass
969
+
970
+
971
+ # --------------------------------------------------------------------------- #
972
+ # Dispatch table: (name, matcher, handler), in hooks.json entry order.
973
+ #
974
+ # A function, not a module constant, so the handler bound at dispatch time is
975
+ # whatever the module currently holds. That keeps the table honest for tests
976
+ # that substitute a single subcommand, and costs one tuple build per tool call.
977
+ # --------------------------------------------------------------------------- #
978
+
979
+
980
+ def _subcommand_table():
981
+ return (
982
+ ("bash_compress_hook", _MATCHER_BASH_COMPRESS, _sub_bash_compress),
983
+ ("archive_result", _MATCHER_ARCHIVE, _sub_archive_result),
984
+ ("context_intel", _MATCHER_CONTEXT_INTEL, _sub_context_intel),
985
+ (
986
+ "read_cache --invalidate",
987
+ _MATCHER_READ_CACHE_INVALIDATE,
988
+ _sub_read_cache_invalidate,
989
+ ),
990
+ ("quality-cache --throttle-only", _MATCHER_UNION, _sub_quality_cache),
991
+ )
992
+
993
+
994
+ # --------------------------------------------------------------------------- #
995
+ # PostToolUseFailure (matcher "Bash|PowerShell", its own hooks.json entry).
996
+ #
997
+ # Claude Code delivers a failed Bash call on this event, not on PostToolUse --
998
+ # and the Windows PowerShell tool is the same event's other shell consumer.
999
+ # The payload carries the exit status in ``error`` ("Exit code N\n<output>")
1000
+ # and there is no tool_response to rewrite. The only consumer is the thrash
1001
+ # guard, which gets the authoritative exit code; a nudge, if any, goes out as
1002
+ # ``additionalContext`` (the one output field this event supports). Nothing is
1003
+ # emitted when there is nothing to say, and any failure here is swallowed: a
1004
+ # broken hook must never turn a tool failure into a worse one.
1005
+ #
1006
+ # Why PowerShell is safe here: the guard is byte-level (identical command +
1007
+ # byte-identical output streaks, same-command burn streaks) -- both signals
1008
+ # are tool-agnostic. Its Bash-only smarts (heredoc bodies) simply never match
1009
+ # PowerShell syntax; the ``command`` field name is shared by both tools; and
1010
+ # any error string not shaped "Exit code N\n..." fails the regex and no-ops.
1011
+ # --------------------------------------------------------------------------- #
1012
+
1013
+ # "Exit code N" followed by the command's output (may be empty, may be
1014
+ # multi-line, hence DOTALL).
1015
+ _FAILURE_ERROR_RE = re.compile(r"^Exit code (\d+)\n?(.*)$", re.DOTALL)
1016
+
1017
+
1018
+ def _handle_post_tool_use_failure(hook_input: dict) -> None:
1019
+ try:
1020
+ if str(hook_input.get("tool_name") or "") not in ("Bash", "PowerShell"):
1021
+ return
1022
+ m = _FAILURE_ERROR_RE.match(str(hook_input.get("error") or ""))
1023
+ if m is None:
1024
+ return
1025
+ command = str((hook_input.get("tool_input") or {}).get("command") or "")
1026
+ if not command:
1027
+ return
1028
+ session_id = str(hook_input.get("session_id") or "")
1029
+ if session_id and not os.environ.get("CLAUDE_SESSION_ID"):
1030
+ os.environ["CLAUDE_SESSION_ID"] = session_id
1031
+ from thrash_guard import check as _thrash_check
1032
+ nudge = _thrash_check(
1033
+ command, m.group(2) or "", stderr="", exit_code=int(m.group(1))
1034
+ )
1035
+ if nudge:
1036
+ print(json.dumps({"hookSpecificOutput": {
1037
+ "hookEventName": "PostToolUseFailure",
1038
+ "additionalContext": nudge,
1039
+ }}))
1040
+ except _HandlerBudgetExceeded:
1041
+ raise # Let the deadline wrapper report the overrun
1042
+ except Exception:
1043
+ pass # Fail open: never add a hook failure on top of a tool failure
1044
+
1045
+
1046
+ def main() -> int:
1047
+ hook_input = _read_hook_input()
1048
+ tool_name = str(hook_input.get("tool_name") or "")
1049
+
1050
+ if hook_input.get("hook_event_name") == "PostToolUseFailure":
1051
+ # Arm the same shared per-handler deadline as the PostToolUse path so
1052
+ # a slow regex/handler on the failure branch is bounded, not unbounded.
1053
+ _install_runner_deadline()
1054
+ _runner_budget(0.0, subcommand_count_hint=1)
1055
+ budget = _runner_budget(_RUNNER_TOTAL_BUDGET)
1056
+ if budget > 0:
1057
+ _run_safely(
1058
+ "post-tool-use-failure",
1059
+ lambda: _run_with_handler_deadline(
1060
+ budget, _handle_post_tool_use_failure, hook_input
1061
+ ),
1062
+ )
1063
+ _clear_runner_deadline()
1064
+ return 0
1065
+
1066
+ _install_shared_stdin(hook_input)
1067
+
1068
+ # Gate FIRST, then budget: the fair share must be divided among the
1069
+ # subcommands that will actually run, not among all five. An Edit only runs
1070
+ # two of them and should get half the budget each, not a fifth.
1071
+ pending = [
1072
+ (name, handler)
1073
+ for name, matcher, handler in _subcommand_table()
1074
+ if _matches(matcher, tool_name)
1075
+ ]
1076
+ if not pending: # pragma: no cover -- quality-cache's _MATCHER_UNION is always True
1077
+ return 0
1078
+
1079
+ _install_runner_deadline()
1080
+
1081
+ # Buffer every subcommand's stdout and emit in dispatch order at the end.
1082
+ _stdout_bufs: list[str] = []
1083
+
1084
+ def _capture(name: str, fn, *args, **kwargs) -> None:
1085
+ budget = _runner_budget(_subcommand_budget(name))
1086
+ if budget <= 0:
1087
+ _report_budget_exhausted(name, 0.0, skipped=True)
1088
+ return
1089
+ buf = io.StringIO()
1090
+ with redirect_stdout(buf):
1091
+ _run_safely(
1092
+ name,
1093
+ lambda: _run_with_handler_deadline(budget, fn, *args, **kwargs),
1094
+ )
1095
+ captured = buf.getvalue()
1096
+ if captured:
1097
+ _stdout_bufs.append(captured)
1098
+
1099
+ _runner_budget(0.0, subcommand_count_hint=len(pending))
1100
+ for name, handler in pending:
1101
+ _capture(name, handler, hook_input)
1102
+
1103
+ _emit_post_tool_use_stdout(_stdout_bufs)
1104
+
1105
+ _clear_runner_deadline()
1106
+ return 0
1107
+
1108
+
1109
+ if __name__ == "__main__":
1110
+ sys.exit(main())