@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,722 @@
1
+ #!/usr/bin/env python3
2
+ """Single-import UserPromptSubmit dispatcher.
3
+
4
+ Replaces the six separate ``UserPromptSubmit`` hooks.json entries that each
5
+ spawned ``python-launcher.sh -> run.py -> module_runner.py -> runpy(measure.py)``
6
+ (eighteen processes per prompt, with the 1.88 MB ``measure.py`` imported six
7
+ times). This runner is invoked ONCE per prompt, imports ``measure.py`` ONCE,
8
+ and runs all six subcommands in-process with per-subcommand failure isolation.
9
+
10
+ Key properties:
11
+ - The three always-on subcommands (``quality-cache --warn --quiet``,
12
+ ``prompt-continuity --quiet``, ``verbosity-steer --quiet``) run every prompt.
13
+ - The three harness-only subcommands (``ensure-health --once-per-session``,
14
+ ``quality-cache --force --quiet --once-per-session``,
15
+ ``compact-restore --new-session-only --once-per-session``) run only when the
16
+ harness guard passes, and each is latched by the SAME per-session marker
17
+ ``measure._ran_once_this_session``.
18
+ - ONE shared ``HookDeadline`` (18s, 2s margin under hooks.json timeout=20)
19
+ replaces the six independent 8s per-subcommand deadlines. Remaining time is
20
+ budgeted fairly across subcommands; the shared deadline's ``os._exit(0)`` is
21
+ the ONLY kill switch in the process, so an early subcommand hang can never
22
+ preemptively kill later ones (including the ensure-health bootstrap).
23
+ - stdout from all six subcommands is captured through one buffered emitter and
24
+ emitted at the end of ``main()`` in a controlled, host-consumable way,
25
+ preserving the per-shape contract (hookSpecificOutput JSON, systemMessage
26
+ JSON, raw text). ensure-health and quality-cache ``{"systemMessage": ...}``
27
+ JSON lines are user-facing (shown to the USER's terminal, NOT injected into
28
+ the model's context) and also feed the envelope; their plain-text
29
+ diagnostics go to a log file. All subcommand stderr is also routed to the
30
+ log file -- the host captures both stdout and stderr into the model's
31
+ session context, so diagnostics must reach neither stream.
32
+ - One subcommand throwing/aborting never aborts the others (each is wrapped in
33
+ ``_run_safely``); the hook always exits 0. Failure notices and tracebacks
34
+ go to the diagnostics log file, not stderr.
35
+ - ensure-health's run-once marker is unlinked on failure so a single
36
+ transient failure never permanently deadlocks the consent gate for the
37
+ session.
38
+ - ``run._check_consent`` is imported by explicit path so a future
39
+ ``skills/.../run.py`` on ``sys.path`` cannot shadow the real gate.
40
+
41
+ The runner calls the same module-level entrypoints used by the ``__main__``
42
+ dispatch, preserving their arguments and behavior while only changing how
43
+ they are scheduled.
44
+
45
+ Run: ``hooks/userpromptsubmit_runner.py`` (via run.py -> module_runner.py).
46
+ """
47
+ from __future__ import annotations
48
+
49
+ import importlib.util as _importlib_util
50
+ import io
51
+ import json
52
+ import os
53
+ import sys
54
+ import time as _time
55
+ import traceback
56
+ from contextlib import redirect_stderr, redirect_stdout
57
+ from pathlib import Path
58
+
59
+
60
+ def _resolve_measure_dir() -> str:
61
+ """Locate the directory holding measure.py so ``import measure`` works.
62
+
63
+ module_runner.py puts THIS file's parent (``hooks/``) on ``sys.path[0]``;
64
+ measure.py lives in ``skills/token-optimizer/scripts/``. Resolve it from
65
+ ``CLAUDE_PLUGIN_ROOT`` (set by the host before hook invocation) with a
66
+ ``__file__``-relative fallback (the plugin root is this file's
67
+ grandparent), and insert it ahead of ``hooks/`` so measure.py and its
68
+ sibling modules (runtime_env, plugin_env, hook_io, hook_runtime) resolve.
69
+ """
70
+ candidates: list[Path] = []
71
+ pr = os.environ.get("CLAUDE_PLUGIN_ROOT", "").strip()
72
+ if pr:
73
+ candidates.append(Path(pr) / "skills" / "token-optimizer" / "scripts")
74
+ try:
75
+ candidates.append(
76
+ Path(__file__).resolve().parent.parent
77
+ / "skills" / "token-optimizer" / "scripts"
78
+ )
79
+ except Exception:
80
+ pass
81
+ for c in candidates:
82
+ try:
83
+ if (c / "measure.py").is_file():
84
+ return str(c.resolve())
85
+ except OSError:
86
+ continue
87
+ # Last resort: assume CWD-relative scripts layout (manual/dev invocation).
88
+ return str((Path.cwd() / "skills" / "token-optimizer" / "scripts").resolve())
89
+
90
+
91
+ _MEASURE_DIR = _resolve_measure_dir()
92
+ if _MEASURE_DIR and _MEASURE_DIR not in sys.path:
93
+ sys.path.insert(0, _MEASURE_DIR)
94
+
95
+ import measure # noqa: E402 (path bootstrapped above)
96
+
97
+
98
+ # --------------------------------------------------------------------------- #
99
+ # Diagnostics log: the host captures BOTH stdout and stderr from
100
+ # UserPromptSubmit hooks into the model's session context, where they are
101
+ # re-billed on every turn. The only correct destination for hook diagnostics
102
+ # is therefore a log file, never stdout and never stderr. User-facing
103
+ # ``{"systemMessage": ...}`` JSON lines are tax-free (shown to the USER's
104
+ # terminal, not injected into the model's context) and must keep reaching the
105
+ # host on stdout.
106
+ # --------------------------------------------------------------------------- #
107
+
108
+ _DIAGNOSTICS_LOG_NAME = "userpromptsubmit_diagnostics.log"
109
+ _DIAGNOSTICS_LOG_CAP = 256 * 1024 # keep the last ~256 KB
110
+
111
+
112
+ def _diagnostics_log_path():
113
+ """Resolve the diagnostics log path under measure's snapshot/state dir.
114
+
115
+ Reuses the same state directory measure.py uses for its other log files.
116
+ Returns None if no state dir is resolvable, in which case callers silently
117
+ drop diagnostics.
118
+ """
119
+ try:
120
+ base = getattr(measure, "SNAPSHOT_DIR", None)
121
+ if base is None:
122
+ return None
123
+ return Path(base) / _DIAGNOSTICS_LOG_NAME
124
+ except Exception:
125
+ return None
126
+
127
+
128
+ def _write_diagnostics(text: str) -> None:
129
+ """Append diagnostics text to the capped log file. Fully fail-open.
130
+
131
+ Any error is swallowed so logging can never block or break the hook.
132
+ If no writable log dir can be resolved, silently drop -- never fall back
133
+ to real stderr.
134
+ """
135
+ if not text:
136
+ return
137
+ try:
138
+ path = _diagnostics_log_path()
139
+ if path is None:
140
+ return
141
+ path.parent.mkdir(parents=True, exist_ok=True)
142
+ chunk = text if text.endswith("\n") else text + "\n"
143
+ with open(path, "a", encoding="utf-8") as f:
144
+ f.write(chunk)
145
+ try:
146
+ if path.stat().st_size > _DIAGNOSTICS_LOG_CAP:
147
+ data = path.read_bytes()[-_DIAGNOSTICS_LOG_CAP:]
148
+ path.write_bytes(data)
149
+ except OSError:
150
+ pass
151
+ except Exception:
152
+ pass
153
+
154
+
155
+ def _emit_stdout_envelope(bufs: list[str]) -> None:
156
+ """Collapse all subcommand stdout into ONE host-valid JSON envelope.
157
+
158
+ STDOUT is feature output: ``systemMessage`` JSON lines are user-facing
159
+ (tax-free), bare plain-text nudges and star pitches are model-facing
160
+ (``additionalContext``), and ``hookSpecificOutput`` JSON from
161
+ prompt-continuity / verbosity-steer carries ``additionalContext`` too.
162
+ ``measure._collapse_hook_stdout`` folds all of these into one object so
163
+ the host sees a single parseable document. STDERR is diagnostic and goes
164
+ to the log (handled per-subcommand in ``_capture``).
165
+ """
166
+ combined = "\n".join(part for part in bufs if part and part.strip())
167
+ if not combined.strip():
168
+ return
169
+ _run_safely(
170
+ "user-prompt-submit stdout envelope",
171
+ measure._emit_hook_stdout_envelope,
172
+ combined,
173
+ "UserPromptSubmit",
174
+ )
175
+
176
+
177
+ def _read_hook_input() -> dict:
178
+ """Read the hook stdin JSON once, non-blocking, shared across subcommands.
179
+
180
+ Uses measure's own shared reader (Windows pipe-peek + Unix select) so the
181
+ behavior matches what each ``__main__`` handler saw individually. 1 MB cap
182
+ is the largest any of the six handlers reads (the quality-cache handler).
183
+ """
184
+ try:
185
+ return measure._read_stdin_hook_input(max_bytes=1_000_000) or {}
186
+ except Exception:
187
+ return {}
188
+
189
+
190
+ def _harness_only_context() -> bool:
191
+ """Require remote/container evidence or Codex, not an ambiguous harness tag."""
192
+ container_id = os.environ.get("CLAUDE_CODE_CONTAINER_ID", "").strip()
193
+ # Align with runtime_env._truthy_env, which accepts 1/true/yes/on
194
+ # (case-insensitive). false/0/off/empty stay False. Do NOT treat a generic
195
+ # AI_AGENT=claude-code_*_harness tag as harness evidence (Cowork is gated
196
+ # by detect_runtime() == "codex" below, not by the harness tag).
197
+ remote = os.environ.get("CLAUDE_CODE_REMOTE", "").strip().lower() in {"1", "true", "yes", "on"}
198
+ if container_id or remote:
199
+ return True
200
+ for name in ("CLAUDE_PLUGIN_ROOT", "CLAUDE_PLUGIN_DATA"):
201
+ if "/plugins/synced/" in os.environ.get(name, "").replace("\\", "/"):
202
+ return True
203
+ return measure.detect_runtime() == "codex"
204
+
205
+
206
+ def _quality_cache_is_missing(hook_input: dict) -> bool:
207
+ """True when this session has NO quality cache yet (one stat, no parsing).
208
+
209
+ Deliberately cheap and deliberately narrow: it answers "does the file
210
+ exist", nothing more. Any error resolving the path returns False so the
211
+ recovery branch stays opt-in and a broken resolution can never turn every
212
+ UserPromptSubmit into a full transcript parse.
213
+ """
214
+ try:
215
+ path = measure._quality_cache_path_for(hook_input.get("transcript_path"))
216
+ return path is not None and not Path(path).exists()
217
+ except Exception:
218
+ return False
219
+
220
+
221
+ def _run_safely(name: str, fn, *args, **kwargs) -> None:
222
+ """Run fn, swallow any failure to the diagnostics log, never propagate.
223
+
224
+ Catches ``Exception`` and ``SystemExit`` so one subcommand's bug or internal
225
+ ``sys.exit()`` cannot abort the others. ``_HookTimeout`` (a ``BaseException``
226
+ raised only by tests that inject it) is caught inside each subcommand
227
+ function; in production the ``HookDeadline`` watchdog calls ``os._exit(0)``
228
+ directly, which is uncatchable and correctly terminates the whole hook 0.
229
+
230
+ Failure notices and tracebacks go to the diagnostics log file, not stderr
231
+ (the host captures stderr into the model's session context).
232
+ """
233
+ try:
234
+ fn(*args, **kwargs)
235
+ except (Exception, SystemExit):
236
+ try:
237
+ buf = io.StringIO()
238
+ buf.write(f"[Token Optimizer] {name} failed, continuing\n")
239
+ traceback.print_exc(file=buf)
240
+ _write_diagnostics(buf.getvalue())
241
+ except (OSError, ValueError):
242
+ pass
243
+
244
+
245
+ # --------------------------------------------------------------------------- #
246
+ # Shared deadline: ONE HookDeadline for the whole runner
247
+ # replaces the six independent 8s per-subcommand deadlines. The shared
248
+ # deadline fires os._exit(0) only when the TOTAL time runs out, and the
249
+ # remaining time is budgeted across subcommands so an early subcommand cannot
250
+ # consume a later one's entire allotment. Total budget = 18s (2s margin under
251
+ # the hooks.json 20s HOT_PATH_CEILING).
252
+ # --------------------------------------------------------------------------- #
253
+
254
+ _RUNNER_DEADLINE = None # type: measure.HookDeadline | None
255
+ _RUNNER_TOTAL_BUDGET = 18.0 # seconds, with 2s margin under hooks.json timeout=20
256
+ _SUBCOMMANDS_PENDING = 0 # decremented by _runner_budget on each call
257
+
258
+
259
+ def _install_runner_deadline(total_seconds=_RUNNER_TOTAL_BUDGET):
260
+ """Arm ONE shared HookDeadline watchdog for the entire runner."""
261
+ global _RUNNER_DEADLINE
262
+ if _RUNNER_DEADLINE is not None:
263
+ return _RUNNER_DEADLINE
264
+ _RUNNER_DEADLINE = measure.HookDeadline(total_seconds)
265
+ _RUNNER_DEADLINE.start()
266
+ return _RUNNER_DEADLINE
267
+
268
+
269
+ def _runner_budget(default_seconds, subcommand_count_hint=None):
270
+ """Return the fair-share budget (seconds) for one subcommand.
271
+
272
+ Divides the shared deadline's remaining time among the subcommands that
273
+ have not yet run. Callers check the returned value: if it is below a
274
+ minimum threshold they skip the subcommand entirely so a later subcommand
275
+ with real work still gets a chance.
276
+ """
277
+ global _SUBCOMMANDS_PENDING
278
+ if subcommand_count_hint is not None:
279
+ _SUBCOMMANDS_PENDING = subcommand_count_hint
280
+ _SUBCOMMANDS_PENDING = max(0, _SUBCOMMANDS_PENDING - 1)
281
+ if _RUNNER_DEADLINE is None:
282
+ return default_seconds
283
+ remaining = _RUNNER_DEADLINE.remaining()
284
+ if remaining <= 0:
285
+ return 0.0
286
+ # Fair share: divide remaining time among the subcommands that still need
287
+ # to run (the one we are about to run + the ones still pending).
288
+ divisor = max(1, _SUBCOMMANDS_PENDING + 1)
289
+ fair = remaining / divisor
290
+ return min(default_seconds, max(0.1, fair))
291
+
292
+
293
+ def _clear_runner_deadline():
294
+ """Cancel the shared deadline (normal completion)."""
295
+ global _RUNNER_DEADLINE
296
+ if _RUNNER_DEADLINE is not None:
297
+ _RUNNER_DEADLINE.cancel()
298
+ _RUNNER_DEADLINE = None
299
+
300
+
301
+ # --------------------------------------------------------------------------- #
302
+ # Subcommand handlers — each mirrors its measure.py __main__ dispatch block.
303
+ # --------------------------------------------------------------------------- #
304
+
305
+
306
+ def _sub_quality_cache_warn(hook_input: dict) -> None:
307
+ """``quality-cache --warn --quiet`` (always runs). Mirrors __main__ L40696."""
308
+ budget = _runner_budget(8)
309
+ if budget < 0.1:
310
+ _write_diagnostics("[Token Optimizer] insufficient time budget; skipping quality-cache --warn\n")
311
+ return
312
+ quiet = True
313
+ warn = True
314
+ force = False
315
+ throttle_only = False
316
+ throttle = 120
317
+ warn_threshold = 70
318
+ session_jsonl = hook_input.get("transcript_path")
319
+ session_id = hook_input.get("session_id")
320
+ try:
321
+ measure._daemon_midsession_pulse()
322
+ except Exception:
323
+ pass
324
+ _quality_cache_self_heal()
325
+ measure.quality_cache(
326
+ throttle_seconds=throttle,
327
+ warn_threshold=warn_threshold,
328
+ quiet=quiet,
329
+ session_jsonl=session_jsonl,
330
+ force=force,
331
+ pure_time_throttle=throttle_only,
332
+ session_id=session_id,
333
+ warn=warn,
334
+ )
335
+
336
+
337
+ def _sub_prompt_continuity(hook_input: dict) -> None:
338
+ """``prompt-continuity --quiet`` (always runs). Mirrors __main__ L40602."""
339
+ budget = _runner_budget(8)
340
+ if budget < 0.1:
341
+ return
342
+ prompt_text = (
343
+ hook_input.get("prompt")
344
+ or hook_input.get("current_prompt")
345
+ or hook_input.get("user_prompt")
346
+ or ""
347
+ )
348
+ sid = hook_input.get("session_id")
349
+ cwd = hook_input.get("cwd")
350
+ transcript_path = hook_input.get("transcript_path")
351
+ if not cwd and transcript_path:
352
+ try:
353
+ cwd = str(Path(transcript_path).parent)
354
+ except TypeError:
355
+ cwd = None
356
+ hint = ""
357
+ try:
358
+ hint = measure._continuity_prompt_hint(
359
+ prompt_text=prompt_text, session_id=sid, cwd=cwd
360
+ )
361
+ except Exception:
362
+ hint = ""
363
+ hint = (hint or "").strip()
364
+ if hint:
365
+ print(
366
+ json.dumps(
367
+ {
368
+ "continue": True,
369
+ "hookSpecificOutput": {
370
+ "hookEventName": "UserPromptSubmit",
371
+ "additionalContext": hint,
372
+ },
373
+ }
374
+ )
375
+ )
376
+
377
+
378
+ def _sub_verbosity_steer(hook_input: dict) -> None:
379
+ """``verbosity-steer --quiet`` (always runs). Mirrors __main__ L40642.
380
+
381
+ Note: the __main__ dispatch hardcodes ``quiet=False`` (the ``--quiet`` CLI
382
+ flag is not parsed for this subcommand). Match the REAL call shape, not the
383
+ flag name.
384
+ """
385
+ budget = _runner_budget(8)
386
+ if budget < 0.1:
387
+ return
388
+ transcript_path = hook_input.get("transcript_path")
389
+ session_id = hook_input.get("session_id")
390
+ try:
391
+ payload = measure.run_verbosity_steer(
392
+ transcript_path=transcript_path,
393
+ quiet=False,
394
+ session_id=session_id,
395
+ )
396
+ if payload:
397
+ print(payload)
398
+ except Exception:
399
+ pass
400
+
401
+
402
+ def _sub_ensure_health(hook_input: dict) -> None:
403
+ """``ensure-health --once-per-session`` (harness-gated). Mirrors __main__ L41138.
404
+
405
+ The run-once marker is set BEFORE the work by
406
+ ``_ran_once_this_session``. If the first call throws (caught by
407
+ ``_run_safely``), the marker is already on disk but the consent flags
408
+ were never written, so ensure-health no-ops for the rest of the session
409
+ and consent stays False (all six subcommands dead). To prevent this
410
+ re-deadlock, we unlink the marker on any failure so the next prompt
411
+ retries the bootstrap.
412
+ """
413
+ sid = hook_input.get("session_id")
414
+ if measure._ran_once_this_session("ensure-health", sid):
415
+ return
416
+ budget = _runner_budget(8)
417
+ if budget < 0.1:
418
+ # Unlink the marker we just set so the next prompt can retry.
419
+ marker = measure._once_per_session_marker("ensure-health", sid)
420
+ if marker is not None:
421
+ try:
422
+ marker.unlink(missing_ok=True)
423
+ except OSError:
424
+ pass
425
+ _write_diagnostics(
426
+ "[Token Optimizer] CRITICAL: insufficient time budget for "
427
+ "ensure-health bootstrap; will retry next prompt\n"
428
+ )
429
+ return
430
+ # The daemon ensure/revive runs FIRST, under its own short guard, BEFORE
431
+ # any health budget is consumed (mirrors __main__ L41167).
432
+ measure._ensure_health_daemon_revive_first()
433
+ try:
434
+ measure.run_ensure_health()
435
+ except Exception:
436
+ # Unlink the marker on failure so the next prompt retries the
437
+ # bootstrap. Without this, a single transient failure (disk full,
438
+ # permission error, settings.json temporarily locked) permanently
439
+ # deadlocks the consent gate for the entire session.
440
+ marker = measure._once_per_session_marker("ensure-health", sid)
441
+ if marker is not None:
442
+ try:
443
+ marker.unlink(missing_ok=True)
444
+ except OSError:
445
+ pass
446
+ _write_diagnostics(
447
+ "[Token Optimizer] CRITICAL: ensure-health bootstrap failed; "
448
+ "will retry next prompt. Consent flags may not be written.\n"
449
+ )
450
+ raise
451
+
452
+
453
+ def _sub_quality_cache_force(hook_input: dict) -> None:
454
+ """``quality-cache --force --quiet --once-per-session`` (harness-gated).
455
+
456
+ Mirrors __main__ L40696 with --force --quiet --once-per-session: the daemon
457
+ pulse + self-heal run unconditionally (as in the dispatch), THEN the
458
+ once-per-session gate, THEN quality_cache() with force=True.
459
+
460
+ The gate is CHECK-ONLY, never CHECK+SET.
461
+ ``_ran_once_this_session`` atomically creates the marker BEFORE the work,
462
+ so a hard ``os._exit(0)`` timeout during ``quality_cache()`` leaves it on
463
+ disk and latches the recovery dead for the whole session. The unlink-on-
464
+ failure for ``score is None`` only helps for normal failures, not hard
465
+ kills. Instead, check the marker's existence without creating it, run the
466
+ work, and only write the marker after success. A double-run from a TOCTOU
467
+ race is harmless (quality_cache with force=True is idempotent), and far
468
+ better than a permanently dead recovery.
469
+ """
470
+ budget = _runner_budget(8)
471
+ if budget < 0.1:
472
+ return
473
+ quiet = True
474
+ warn = False
475
+ force = True
476
+ throttle_only = False
477
+ throttle = 120
478
+ warn_threshold = 70
479
+ session_jsonl = hook_input.get("transcript_path")
480
+ session_id = hook_input.get("session_id")
481
+ try:
482
+ measure._daemon_midsession_pulse()
483
+ except Exception:
484
+ pass
485
+ _quality_cache_self_heal()
486
+ # CHECK-ONLY: do not create the marker yet. A hard os._exit(0) during
487
+ # quality_cache() would leave a pre-written marker on disk and latch the
488
+ # recovery dead for the whole session.
489
+ marker = measure._once_per_session_marker("quality-cache-force", session_id)
490
+ if marker is not None and marker.exists():
491
+ return
492
+ score = measure.quality_cache(
493
+ throttle_seconds=throttle,
494
+ warn_threshold=warn_threshold,
495
+ quiet=quiet,
496
+ session_jsonl=session_jsonl,
497
+ force=force,
498
+ pure_time_throttle=throttle_only,
499
+ session_id=session_id,
500
+ warn=warn,
501
+ )
502
+ # Write the marker only after the cache work produced a result. A timeout,
503
+ # missing transcript, busy lease, failed write, or hard os._exit(0) leaves
504
+ # no marker so the next prompt can retry.
505
+ if score is not None:
506
+ measure._mark_ran_this_session("quality-cache-force", session_id)
507
+
508
+
509
+ def _sub_compact_restore(hook_input: dict) -> None:
510
+ """``compact-restore --new-session-only --once-per-session`` (harness-gated).
511
+
512
+ Mirrors __main__ L40526: the --new-session-only --once-per-session copy
513
+ checks-then-skips the marker, then runs compact_restore(new_session_only).
514
+ Under Codex/Cowork the raw stdout is captured and wrapped in the documented
515
+ additionalContext envelope (docs-grounding.md §1).
516
+ """
517
+ sid = hook_input.get("session_id")
518
+ if measure._ran_once_this_session("compact-restore-new-session", sid):
519
+ return
520
+ budget = _runner_budget(8)
521
+ if budget < 0.1:
522
+ return
523
+ _cw = measure.is_cowork()
524
+ if measure.detect_runtime() == "codex" or _cw:
525
+ buf = io.StringIO()
526
+ with redirect_stdout(buf):
527
+ measure.compact_restore(session_id=sid, new_session_only=True)
528
+ measure._emit_additional_context(
529
+ # This runner only handles UserPromptSubmit, regardless of runtime.
530
+ buf.getvalue(), event="UserPromptSubmit"
531
+ )
532
+ else:
533
+ measure.compact_restore(session_id=sid, new_session_only=True)
534
+
535
+
536
+ def _quality_cache_self_heal() -> None:
537
+ """Replicate the quality-cache dispatch's self-healing block (__main__
538
+ L40743-40755): if the quality-cache hook is missing from settings.json and
539
+ this is NOT a plugin install and quality_bar_disabled is unset, reinstall it.
540
+
541
+ For plugin installs (the hooks.json context this runner runs in) the
542
+ ``_is_plugin`` check is True and the block is a no-op, exactly as in the
543
+ dispatch. Replicated verbatim so non-plugin manual installs keep the same
544
+ self-heal behavior. Fail-open: never raises.
545
+ """
546
+ try:
547
+ _is_plugin = measure._is_running_from_plugin_cache() or measure._is_plugin_installed()
548
+ try:
549
+ _qb_disabled = False
550
+ if measure.CONFIG_PATH.exists():
551
+ _qb_cfg = json.loads(measure.CONFIG_PATH.read_text(encoding="utf-8"))
552
+ _qb_disabled = _qb_cfg.get("quality_bar_disabled", False)
553
+ if (
554
+ not _is_plugin
555
+ and not _qb_disabled
556
+ and measure.SETTINGS_PATH.exists()
557
+ ):
558
+ _sh_settings = json.loads(measure.SETTINGS_PATH.read_text(encoding="utf-8"))
559
+ _sh_hooks = _sh_settings.get("hooks", {}).get("UserPromptSubmit", [])
560
+ # Use _quality_cache_hook_present
561
+ # (the fix in sessionstart_runner.py:448) instead of the
562
+ # naive substring check. The naive check cannot see the
563
+ # consolidated UPS runner dispatcher as a quality-cache
564
+ # provider, so on a script (non-plugin) install it re-appends
565
+ # a duplicate legacy hook -- exactly the bug it was meant to prevent.
566
+ if not measure._quality_cache_hook_present(_sh_hooks):
567
+ measure.setup_quality_bar(quiet=True)
568
+ except Exception:
569
+ pass
570
+ except Exception:
571
+ pass
572
+
573
+
574
+ def _check_consent() -> bool:
575
+ """Consent gate for the consolidated runner, mirroring ``run._check_consent``.
576
+
577
+ run.py exempts this script from its own consent gate:
578
+ the runner is dispatched with no distinguishing args, so the
579
+ ``ensure-health`` exempt-command match never fires there; the runner
580
+ contains the ensure-health bootstrap itself). The per-subcommand consent
581
+ decision therefore lives HERE.
582
+
583
+ The consolidated runner requires importing ``run._check_consent`` by explicit path via
584
+ ``importlib.util.spec_from_file_location`` so a future ``skills/.../run.py``
585
+ on ``sys.path`` cannot shadow the real ``hooks/run.py`` and silently
586
+ disable the consent gate (``import run`` fails-open on any AttributeError).
587
+ """
588
+ try:
589
+ run_py = Path(__file__).resolve().parent / "run.py"
590
+ if not run_py.is_file():
591
+ return True
592
+ spec = _importlib_util.spec_from_file_location("_to_run_consent", run_py)
593
+ _run_mod = _importlib_util.module_from_spec(spec)
594
+ spec.loader.exec_module(_run_mod)
595
+ return _run_mod._check_consent()
596
+ except Exception:
597
+ return True
598
+
599
+
600
+ def main() -> int:
601
+ hook_input = _read_hook_input()
602
+
603
+ # Consent gate for the consolidated runner. Before consolidation, the six
604
+ # UserPromptSubmit hooks.json entries each passed distinguishing args, so
605
+ # the ensure-health entry was consent-exempt (it bootstraps the
606
+ # v5_welcome_shown / enterprise_consent_shown flags) and the other five
607
+ # were consent-gated (returned 0 when consent was False). The consolidated
608
+ # runner is dispatched with no args, so run.py exempts the whole runner
609
+ # path and delegates the per-subcommand decision here.
610
+ #
611
+ # When consent is False: ONLY ensure-health runs (it writes the consent
612
+ # flags via _show_v5_welcome + the v5_welcome_shown write, the bootstrap),
613
+ # and only when the harness guard passes. On Cowork (the no-SessionStart
614
+ # host where this deadlock is fatal) the harness guard is True, so
615
+ # ensure-health bootstraps. On native Claude Code, SessionStart already
616
+ # bootstraps consent, so consent is True before UserPromptSubmit fires and
617
+ # this branch is not reached. The other five subcommands skip, preserving
618
+ # the original consent-gated semantics exactly. When consent is True: all
619
+ # six run per their existing gates.
620
+ if not _check_consent():
621
+ if _harness_only_context():
622
+ _install_runner_deadline()
623
+ _bufs: list[str] = []
624
+
625
+ def _capture_consent(name: str, fn, *args, **kwargs) -> None:
626
+ buf = io.StringIO()
627
+ err_buf = io.StringIO()
628
+ with redirect_stdout(buf), redirect_stderr(err_buf):
629
+ _run_safely(name, fn, *args, **kwargs)
630
+ captured = buf.getvalue()
631
+ err_captured = err_buf.getvalue()
632
+ # ALL stdout is feature output (systemMessage + bare-text
633
+ # nudges/star-pitch) -> envelope. stderr is diagnostic -> log.
634
+ if captured:
635
+ _bufs.append(captured)
636
+ if err_captured:
637
+ _write_diagnostics(f"--- {name} ---\n{err_captured}")
638
+
639
+ _capture_consent("ensure-health", _sub_ensure_health, hook_input)
640
+ _emit_stdout_envelope(_bufs)
641
+ _clear_runner_deadline()
642
+ return 0
643
+
644
+ # Install ONE shared HookDeadline for the entire
645
+ # runner (18s, 2s margin under hooks.json timeout=20). The per-subcommand
646
+ # _runner_budget calls divide the remaining time fairly. The shared
647
+ # deadline is the ONLY os._exit(0) in the process -- no individual
648
+ # subcommand deadline can kill later subcommands.
649
+ _install_runner_deadline()
650
+
651
+ # Capture each subcommand's stdout through ONE
652
+ # buffered emitter, then emit at the end in a controlled, host-consumable
653
+ # way. Pre-consolidation each subcommand was its own hooks.json entry and
654
+ # the host parsed their stdout independently; now all six share one stdout
655
+ # stream, so we buffer to avoid mixed JSON/raw-text corruption.
656
+ #
657
+ # STDOUT is feature output: systemMessage JSON (user-facing, tax-free),
658
+ # bare plain-text nudges/star-pitch (model-facing additionalContext), and
659
+ # hookSpecificOutput JSON from prompt-continuity / verbosity-steer /
660
+ # compact-restore (model-facing additionalContext). All of it collapses
661
+ # into ONE envelope via ``_emit_stdout_envelope`` at the end.
662
+ # STDERR is diagnostic -> log file (the host captures both streams into
663
+ # the model's session context, so diagnostics must reach neither).
664
+ _stdout_bufs: list[str] = []
665
+
666
+ def _capture(name: str, fn, *args, **kwargs) -> None:
667
+ buf = io.StringIO()
668
+ err_buf = io.StringIO()
669
+ with redirect_stdout(buf), redirect_stderr(err_buf):
670
+ _run_safely(name, fn, *args, **kwargs)
671
+ captured = buf.getvalue()
672
+ err_captured = err_buf.getvalue()
673
+ # ALL stdout -> envelope (systemMessage + bare-text + JSON all
674
+ # collapse into one host-valid object). stderr -> log.
675
+ if captured:
676
+ _stdout_bufs.append(captured)
677
+ if err_captured:
678
+ _write_diagnostics(f"--- {name} ---\n{err_captured}")
679
+
680
+ # 1-3: always-on subcommands. Ordering: the cheap,
681
+ # user-visible subcommands (prompt-continuity, verbosity-steer) run BEFORE
682
+ # the heavier quality-cache --warn. The shared deadline's os._exit(0)
683
+ # kills the whole process uncatchably, so a hang in an early subcommand
684
+ # still skips later ones; running the cheap user-visible work first
685
+ # minimizes what a quality-cache hang can suppress. The harness-only 4-6
686
+ # still run after the gate (gating-order semantics preserved).
687
+ _runner_budget(8, subcommand_count_hint=6)
688
+ _capture("prompt-continuity", _sub_prompt_continuity, hook_input)
689
+ _capture("verbosity-steer", _sub_verbosity_steer, hook_input)
690
+ _capture("quality-cache --warn", _sub_quality_cache_warn, hook_input)
691
+
692
+ # 4-6: harness-only subcommands. The shell guard that used to prefix
693
+ # hooks.json entries 4/5/6 is evaluated once here; when it fails, all three
694
+ # are skipped exactly as the shell `exit 0` skipped each entry.
695
+ if _harness_only_context():
696
+ _capture("ensure-health", _sub_ensure_health, hook_input)
697
+ _capture("quality-cache --force", _sub_quality_cache_force, hook_input)
698
+ _capture("compact-restore", _sub_compact_restore, hook_input)
699
+ elif _quality_cache_is_missing(hook_input):
700
+ # RECOVERY. Non-harness sessions reach this ONLY when no cache exists.
701
+ # SessionStart is normally the sole creator (`quality-cache --force
702
+ # --quiet --once-mark`, timeout 20s). When it times out -- a busy
703
+ # machine, a boot storm, or heavy workload, exactly when someone
704
+ # looks at the statusline -- nothing else ever created it, and
705
+ # PostToolUse deliberately refuses to (a latency invariant: it fires on
706
+ # every tool call). The session was stuck on `ContextQ:--` with no path
707
+ # back. Bounded: one stat() in the common case; the full computation
708
+ # only when the file is genuinely absent, after which the normal
709
+ # throttle governs and this branch is never taken again.
710
+ _capture("quality-cache --force (bootstrap)", _sub_quality_cache_force,
711
+ hook_input)
712
+
713
+ # Collapse all subcommand stdout into ONE host-valid JSON envelope.
714
+ # systemMessage -> user (tax-free), bare text + additionalContext -> model.
715
+ _emit_stdout_envelope(_stdout_bufs)
716
+
717
+ _clear_runner_deadline()
718
+ return 0
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())