@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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 +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -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 +149 -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 +3633 -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 +141 -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 +93 -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 +379 -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 +1011 -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 +288 -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 +426 -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 +400 -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 +716 -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 +59531 -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 +1923 -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,629 @@
1
+ #!/usr/bin/env python3
2
+ """Single-import SessionStart dispatcher.
3
+
4
+ Replaces the FIVE separate ``SessionStart`` hook commands in hooks.json that
5
+ each spawned ``python-launcher.sh -> run.py -> module_runner.py ->
6
+ runpy(measure.py)`` and repeated the interpreter and module startup work:
7
+
8
+ 1. ``measure.py ensure-health --once-mark`` (timeout 15, async)
9
+ 2. ``measure.py quality-cache --force --quiet --once-mark`` (timeout 20)
10
+ 3. ``measure.py compact-restore --compact`` [matcher compact] (timeout 20)
11
+ 4. ``read_cache.py --clear-compacted --quiet`` [matcher compact] (timeout 10)
12
+ 5. ``measure.py compact-restore --new-session-only --once-mark`` (timeout 20)
13
+
14
+ This runner is invoked ONCE per session start, imports ``measure.py`` ONCE, and
15
+ runs all five subcommands in-process under ONE shared deadline. That removes
16
+ repeated startup work while keeping the host-specific timeout as a backstop.
17
+
18
+ This is the same consolidation the ``UserPromptSubmit`` group received in
19
+ ``hooks/userpromptsubmit_runner.py``; SessionStart never got it. The
20
+ structure here deliberately mirrors that file.
21
+
22
+ Key properties:
23
+ - ONE shared ``HookDeadline`` (18s, 2s margin under the hooks.json timeout of
24
+ 20, and 7s under Codex's hard 25s SessionStart ceiling) replaces the five
25
+ independent per-entry timeouts. Remaining time is budgeted fairly across the
26
+ subcommands still pending (``_runner_budget``); the shared deadline's
27
+ ``os._exit(0)`` is the ONLY kill switch in the process, so an early
28
+ subcommand hang can never preemptively kill later ones.
29
+ - ``--once-mark`` latching semantics are preserved EXACTLY: subcommands 1, 2
30
+ and 5 call ``measure._mark_ran_this_session`` (WRITE, never check), so the
31
+ SessionStart work always runs -- including on the second SessionStart of a
32
+ session (resume / post-compaction keep the same session_id) --
33
+ while the ``--once-per-session`` UserPromptSubmit copies stay latched out.
34
+ No unlink-on-failure here: the ``--once-mark`` semantics differ from the
35
+ retryable ``--once-per-session`` flow and must remain distinct.
36
+ - The ``matcher: "compact"`` gate on subcommands 3 and 4 is replicated
37
+ in-process by ``_is_compact_start`` (the SessionStart ``source`` field the
38
+ host matches on), so a non-compact start skips them exactly as the matcher
39
+ did.
40
+ - The consent gate that run.py used to apply per-entry is applied per
41
+ subcommand HERE: ensure-health was consent-EXEMPT (it bootstraps the consent
42
+ flags), the other four were consent-gated. run.py exempts this runner path
43
+ wholesale, same as the UserPromptSubmit runner.
44
+ - stdout from the two compact-restore subcommands is captured and emitted in
45
+ dispatch order at the end of ``main()`` as ONE host-valid JSON envelope
46
+ (raw text, systemMessage JSON, additionalContext JSON). ensure-health and
47
+ quality-cache ``{"systemMessage": ...}`` JSON lines are user-facing (shown
48
+ to the USER's terminal, NOT injected into the model's context) and also
49
+ feed the envelope; their plain-text diagnostics are routed to a log file.
50
+ All subcommand stderr is also routed to the log file -- the host captures
51
+ both stdout and stderr into the model's session context, so diagnostics
52
+ must reach neither stream.
53
+ - One subcommand throwing/aborting never aborts the others (each is wrapped in
54
+ ``_run_safely``); the hook always exits 0. Failure notices and tracebacks
55
+ go to the diagnostics log file, not stderr.
56
+ - ``run._check_consent`` is imported by explicit path so a future
57
+ ``skills/.../run.py`` on ``sys.path`` cannot shadow the real gate.
58
+
59
+ The runner calls the same module-level entrypoints used by the ``__main__``
60
+ dispatch, preserving their arguments and behavior while only changing how
61
+ they are scheduled.
62
+
63
+ Run: ``hooks/sessionstart_runner.py`` (via run.py -> module_runner.py).
64
+ """
65
+ from __future__ import annotations
66
+
67
+ import importlib.util as _importlib_util
68
+ import io
69
+ import json
70
+ import os
71
+ import sys
72
+ import traceback
73
+ from contextlib import redirect_stderr, redirect_stdout
74
+ from pathlib import Path
75
+
76
+
77
+ def _resolve_measure_dir() -> str:
78
+ """Locate the directory holding measure.py so ``import measure`` works.
79
+
80
+ module_runner.py puts THIS file's parent (``hooks/``) on ``sys.path[0]``;
81
+ measure.py lives in ``skills/token-optimizer/scripts/``. Resolve it from
82
+ ``CLAUDE_PLUGIN_ROOT`` (set by the host before hook invocation) with a
83
+ ``__file__``-relative fallback (the plugin root is this file's
84
+ grandparent), and insert it ahead of ``hooks/`` so measure.py and its
85
+ sibling modules (runtime_env, plugin_env, hook_io, hook_runtime) resolve.
86
+ """
87
+ candidates: list[Path] = []
88
+ pr = os.environ.get("CLAUDE_PLUGIN_ROOT", "").strip()
89
+ if pr:
90
+ candidates.append(Path(pr) / "skills" / "token-optimizer" / "scripts")
91
+ try:
92
+ candidates.append(
93
+ Path(__file__).resolve().parent.parent
94
+ / "skills" / "token-optimizer" / "scripts"
95
+ )
96
+ except Exception:
97
+ pass
98
+ for c in candidates:
99
+ try:
100
+ if (c / "measure.py").is_file():
101
+ return str(c.resolve())
102
+ except OSError:
103
+ continue
104
+ # Last resort: assume CWD-relative scripts layout (manual/dev invocation).
105
+ return str((Path.cwd() / "skills" / "token-optimizer" / "scripts").resolve())
106
+
107
+
108
+ _MEASURE_DIR = _resolve_measure_dir()
109
+ if _MEASURE_DIR and _MEASURE_DIR not in sys.path:
110
+ sys.path.insert(0, _MEASURE_DIR)
111
+
112
+ import measure # noqa: E402 (path bootstrapped above)
113
+
114
+
115
+ # --------------------------------------------------------------------------- #
116
+ # Diagnostics log: the host captures BOTH stdout and stderr from SessionStart
117
+ # hooks into the model's session context, where they are re-billed on every
118
+ # turn. The only correct destination for hook diagnostics is therefore a log
119
+ # file, never stdout and never stderr.
120
+ # --------------------------------------------------------------------------- #
121
+
122
+ _DIAGNOSTICS_LOG_NAME = "sessionstart_diagnostics.log"
123
+ _DIAGNOSTICS_LOG_CAP = 256 * 1024 # keep the last ~256 KB
124
+
125
+
126
+ def _diagnostics_log_path():
127
+ """Resolve the diagnostics log path under measure's snapshot/state dir.
128
+
129
+ Reuses the same state directory measure.py uses for its other log files
130
+ (e.g. the keep-warm scheduler log). Returns None if no state dir is
131
+ resolvable, in which case callers silently drop diagnostics (devnull).
132
+ """
133
+ try:
134
+ base = getattr(measure, "SNAPSHOT_DIR", None)
135
+ if base is None:
136
+ return None
137
+ return Path(base) / _DIAGNOSTICS_LOG_NAME
138
+ except Exception:
139
+ return None
140
+
141
+
142
+ def _write_diagnostics(text: str) -> None:
143
+ """Append diagnostics text to the capped log file. Fully fail-open.
144
+
145
+ Any error is swallowed so logging can never block or break SessionStart.
146
+ If no writable log dir can be resolved, silently drop (devnull) -- never
147
+ fall back to real stderr.
148
+ """
149
+ if not text:
150
+ return
151
+ try:
152
+ path = _diagnostics_log_path()
153
+ if path is None:
154
+ return
155
+ path.parent.mkdir(parents=True, exist_ok=True)
156
+ chunk = text if text.endswith("\n") else text + "\n"
157
+ with open(path, "a", encoding="utf-8") as f:
158
+ f.write(chunk)
159
+ # Cap: trim to the last ~256 KB so the file stays small.
160
+ try:
161
+ if path.stat().st_size > _DIAGNOSTICS_LOG_CAP:
162
+ data = path.read_bytes()[-_DIAGNOSTICS_LOG_CAP:]
163
+ path.write_bytes(data)
164
+ except OSError:
165
+ pass
166
+ except Exception:
167
+ pass
168
+
169
+
170
+ def _read_hook_input() -> dict:
171
+ """Read the hook stdin JSON once, non-blocking, shared across subcommands.
172
+
173
+ Uses measure's own shared reader (Windows pipe-peek + Unix select) so the
174
+ behavior matches what each ``__main__`` handler saw individually. 1 MB cap
175
+ is the largest any of the five handlers reads (quality-cache and
176
+ read_cache.py --clear-compacted both read 1_000_000).
177
+ """
178
+ try:
179
+ return measure._read_stdin_hook_input(max_bytes=1_000_000) or {}
180
+ except Exception:
181
+ return {}
182
+
183
+
184
+ def _is_compact_start(hook_input: dict) -> bool:
185
+ """Replicate the ``"matcher": "compact"`` gate on hooks.json entries 3 and 4.
186
+
187
+ Claude Code / Codex match a SessionStart hook group's ``matcher`` against
188
+ the start ``source`` (``startup`` | ``resume`` | ``clear`` | ``compact``)
189
+ carried in the stdin payload. Entries 3 and 4 only ran when that was
190
+ ``compact``; every other start skipped them. ``is_compact`` is also honored
191
+ because measure's own compact-restore dispatch honors it
192
+ (``bool(hook_input.get("is_compact", False)) or source == "compact"``).
193
+ """
194
+ if bool(hook_input.get("is_compact", False)):
195
+ return True
196
+ source = str(hook_input.get("source") or "").strip().lower()
197
+ return source == "compact"
198
+
199
+
200
+ def _run_safely(name: str, fn, *args, **kwargs) -> None:
201
+ """Run fn, swallow any failure to the diagnostics log, never propagate.
202
+
203
+ Catches ``Exception`` and ``SystemExit`` so one subcommand's bug or internal
204
+ ``sys.exit()`` cannot abort the others. ``_HookTimeout`` (a ``BaseException``
205
+ raised only by tests that inject it) is caught inside each subcommand
206
+ function; in production the ``HookDeadline`` watchdog calls ``os._exit(0)``
207
+ directly, which is uncatchable and correctly terminates the whole hook 0.
208
+
209
+ The failure notice and traceback go to the diagnostics log file, never to
210
+ real stderr (the host captures stderr into the model's session context).
211
+ """
212
+ try:
213
+ fn(*args, **kwargs)
214
+ except (Exception, SystemExit):
215
+ try:
216
+ buf = io.StringIO()
217
+ buf.write(f"[Token Optimizer] {name} failed, continuing\n")
218
+ traceback.print_exc(file=buf)
219
+ _write_diagnostics(buf.getvalue())
220
+ except Exception:
221
+ pass
222
+
223
+
224
+ # --------------------------------------------------------------------------- #
225
+ # Shared deadline: ONE HookDeadline for the whole runner replaces the five
226
+ # independent per-entry timeouts (15 + 20 + 20 + 10 + 20 = 85s declared).
227
+ #
228
+ # WHY 18s:
229
+ # * Codex enforces a HARD 25s ceiling on SessionStart hooks and kills the
230
+ # process ("hook timed out after 25s") regardless of the declared timeout.
231
+ # That is the smallest host ceiling, so it sets the budget.
232
+ # * The consolidated hooks.json entry declares timeout=20 (Claude honors the
233
+ # declared value; 20 also sits 5s under Codex's ceiling, leaving room for
234
+ # the bash -> python-launcher -> run.py -> module_runner -> measure-import
235
+ # spawn chain, ~1-2s on a cold cache).
236
+ # * The internal deadline is 18s: 2s of margin under the declared 20 so the
237
+ # runner self-exits 0 with its buffered stdout emitted, rather than being
238
+ # SIGKILLed by the host mid-write. Same 2s margin the UserPromptSubmit
239
+ # runner uses under its own timeout=20.
240
+ # --------------------------------------------------------------------------- #
241
+
242
+ _RUNNER_DEADLINE = None # type: measure.HookDeadline | None
243
+ _RUNNER_TOTAL_BUDGET = 18.0 # seconds, 2s margin under hooks.json timeout=20
244
+ _SUBCOMMANDS_PENDING = 0 # decremented by _runner_budget on each call
245
+
246
+
247
+ def _install_runner_deadline(total_seconds=None):
248
+ """Arm ONE shared HookDeadline watchdog for the entire runner."""
249
+ global _RUNNER_DEADLINE
250
+ if _RUNNER_DEADLINE is not None:
251
+ return _RUNNER_DEADLINE
252
+ if total_seconds is None:
253
+ total_seconds = _RUNNER_TOTAL_BUDGET
254
+ _RUNNER_DEADLINE = measure.HookDeadline(total_seconds)
255
+ _RUNNER_DEADLINE.start()
256
+ return _RUNNER_DEADLINE
257
+
258
+
259
+ def _runner_budget(default_seconds, subcommand_count_hint=None):
260
+ """Return the fair-share budget (seconds) for one subcommand.
261
+
262
+ Divides the shared deadline's remaining time among the subcommands that
263
+ have not yet run. Callers check the returned value: if it is below a
264
+ minimum threshold they skip the subcommand entirely so a later subcommand
265
+ with real work still gets a chance.
266
+ """
267
+ global _SUBCOMMANDS_PENDING
268
+ if subcommand_count_hint is not None:
269
+ _SUBCOMMANDS_PENDING = subcommand_count_hint
270
+ _SUBCOMMANDS_PENDING = max(0, _SUBCOMMANDS_PENDING - 1)
271
+ if _RUNNER_DEADLINE is None:
272
+ return default_seconds
273
+ remaining = _RUNNER_DEADLINE.remaining()
274
+ if remaining <= 0:
275
+ return 0.0
276
+ divisor = max(1, _SUBCOMMANDS_PENDING + 1)
277
+ fair = remaining / divisor
278
+ return min(default_seconds, max(0.1, fair))
279
+
280
+
281
+ def _clear_runner_deadline():
282
+ """Cancel the shared deadline (normal completion)."""
283
+ global _RUNNER_DEADLINE
284
+ if _RUNNER_DEADLINE is not None:
285
+ _RUNNER_DEADLINE.cancel()
286
+ _RUNNER_DEADLINE = None
287
+
288
+
289
+ # --------------------------------------------------------------------------- #
290
+ # The SessionStart stdout envelope.
291
+ #
292
+ # Every subcommand's stdout is buffered and emitted as ONE JSON object in the
293
+ # documented {"hookSpecificOutput": {...}} shape
294
+ # (docs-grounding.md §1), with the event name taken from the firing hook's stdin
295
+ # payload (PR #142) so a SessionStart hook can never emit a UserPromptSubmit
296
+ # envelope (Claude Code rejects the mismatch).
297
+ #
298
+ # This is UNCONDITIONAL -- it is not gated on detect_runtime(). The old gate
299
+ # (`detect_runtime() == "codex" or is_cowork()`) was dead code on Codex: Codex
300
+ # sets neither CODEX_HOME nor TOKEN_OPTIMIZER_RUNTIME in a hook subprocess (only
301
+ # CLAUDE_PLUGIN_ROOT / CLAUDE_PLUGIN_DATA), so detect_runtime() returns "claude"
302
+ # inside a Codex plugin hook and the raw "[Token Optimizer] ..." text went out
303
+ # unwrapped -- "hook returned invalid session start JSON output". The envelope is
304
+ # valid on BOTH hosts, so there is nothing to detect.
305
+ #
306
+ # It also has to be ONE object, not one per subcommand: pre-consolidation each
307
+ # subcommand owned its own stdout stream; now they share one, and two JSON
308
+ # documents on a single stream is exactly what Codex refuses to parse. See
309
+ # tests/test_codex_sessionstart_json_contract.py for the verified contract.
310
+ # --------------------------------------------------------------------------- #
311
+
312
+
313
+ def _envelope_event(hook_input: dict) -> str:
314
+ """Envelope hookEventName, derived from the firing hook's stdin payload."""
315
+ event = hook_input.get("hook_event_name")
316
+ return "SessionStart" if event != "SessionStart" else event
317
+
318
+
319
+ def _emit_session_start_stdout(parts, hook_input: dict) -> None:
320
+ """Emit every subcommand's stdout as AT MOST ONE host-valid JSON object.
321
+
322
+ This runner is now the ONLY SessionStart stdout producer, so it owns the
323
+ host's output contract. Codex (verified against 0.150.0-alpha.12.2) parses
324
+ SessionStart stdout like this: whitespace-only is a no-op; stdout that does
325
+ NOT start with ``{`` or ``[`` is ignored as plain text; stdout that DOES
326
+ start with ``{`` or ``[`` must be ONE JSON document that validates against
327
+ its ``session-start.command.output`` schema, or the entire hook fails with
328
+ "hook returned invalid session start JSON output".
329
+
330
+ Concatenating the subcommands' raw streams breaks that three ways at once:
331
+ every human-readable Token Optimizer line starts with ``[Token Optimizer]``
332
+ (a ``[``, read as the start of a JSON array); two ``{"systemMessage": ...}``
333
+ objects on one stream are two documents; and a raw line followed by a JSON
334
+ line is neither. ``measure._collapse_hook_stdout`` folds all of it into one
335
+ object -- systemMessages joined, plain text carried in
336
+ ``hookSpecificOutput.additionalContext`` -- which BOTH Claude Code and Codex
337
+ accept, so no runtime sniffing is required (and none is possible: Codex sets
338
+ neither CODEX_HOME nor TOKEN_OPTIMIZER_RUNTIME in the hook subprocess, so
339
+ ``detect_runtime()`` returns "claude" inside a Codex plugin hook).
340
+ """
341
+ combined = "\n".join(part for part in parts if part and part.strip())
342
+ if not combined.strip():
343
+ return
344
+ _run_safely(
345
+ "session-start stdout envelope",
346
+ measure._emit_hook_stdout_envelope,
347
+ combined,
348
+ _envelope_event(hook_input),
349
+ )
350
+
351
+
352
+ # --------------------------------------------------------------------------- #
353
+ # Subcommand handlers -- each mirrors its measure.py __main__ dispatch block.
354
+ # --------------------------------------------------------------------------- #
355
+
356
+
357
+ def _sub_ensure_health(hook_input: dict) -> None:
358
+ """``measure.py ensure-health --once-mark`` (hooks.json entry 1).
359
+
360
+ Mirrors the ``ensure-health`` dispatch (measure.py ~L43205):
361
+ --once-mark -> _mark_ran_this_session (WRITE, never check), so the
362
+ SessionStart copy ALWAYS runs and refreshes the marker that latches the
363
+ UserPromptSubmit --once-per-session copy;
364
+ then _ensure_health_daemon_revive_first() under its own guard before any
365
+ health budget is consumed;
366
+ then run_ensure_health().
367
+ """
368
+ sid = hook_input.get("session_id")
369
+ measure._mark_ran_this_session("ensure-health", sid)
370
+ budget = _runner_budget(8)
371
+ if budget < 0.1:
372
+ sys.stderr.write(
373
+ "[Token Optimizer] insufficient time budget; skipping ensure-health\n"
374
+ )
375
+ return
376
+ measure._ensure_health_daemon_revive_first()
377
+ measure.run_ensure_health()
378
+
379
+
380
+ def _sub_quality_cache_force(hook_input: dict) -> None:
381
+ """``measure.py quality-cache --force --quiet --once-mark`` (entry 2).
382
+
383
+ Mirrors the ``quality-cache`` dispatch (measure.py ~L42760) for this exact
384
+ flag set: daemon pulse, then the settings self-heal block, then the
385
+ --once-mark WRITE, then quality_cache(force=True, quiet=True, warn=False).
386
+ """
387
+ budget = _runner_budget(8)
388
+ if budget < 0.1:
389
+ return
390
+ quiet = True
391
+ warn = False
392
+ force = True
393
+ throttle_only = False
394
+ throttle = 120
395
+ warn_threshold = 70
396
+ session_jsonl = hook_input.get("transcript_path")
397
+ session_id = hook_input.get("session_id")
398
+ try:
399
+ measure._daemon_midsession_pulse()
400
+ except Exception:
401
+ pass
402
+ _quality_cache_self_heal()
403
+ score = measure.quality_cache(
404
+ throttle_seconds=throttle,
405
+ warn_threshold=warn_threshold,
406
+ quiet=quiet,
407
+ session_jsonl=session_jsonl,
408
+ force=force,
409
+ pure_time_throttle=throttle_only,
410
+ session_id=session_id,
411
+ warn=warn,
412
+ )
413
+ # Claim the shared once-per-session marker only after the cache work
414
+ # produced a result. A timeout or failed write must leave UserPromptSubmit
415
+ # free to run its recovery path for this session.
416
+ if score is not None:
417
+ measure._mark_ran_this_session("quality-cache-force", session_id)
418
+
419
+
420
+ def _sub_compact_restore_compact(hook_input: dict, sink: list) -> None:
421
+ """``measure.py compact-restore --compact`` (entry 3, matcher ``compact``).
422
+
423
+ Mirrors the ``compact-restore`` dispatch (measure.py ~L42582) with
424
+ ``--compact``: no marker (only the --new-session-only pointer is guarded --
425
+ the in-place restore must run on EVERY compaction), is_compact=True, and the
426
+ Codex/Cowork additionalContext wrap. The wrapped text is appended to
427
+ ``sink`` instead of being emitted here, so both compact-restore subcommands
428
+ share ONE envelope (see the envelope note above).
429
+ """
430
+ budget = _runner_budget(measure._int_env("TOKEN_OPTIMIZER_COMPACT_RESTORE_BUDGET", 8))
431
+ if budget < 0.1:
432
+ return
433
+ sid = hook_input.get("session_id")
434
+ buf = io.StringIO()
435
+ with redirect_stdout(buf):
436
+ measure.compact_restore(session_id=sid, is_compact=True)
437
+ sink.append(buf.getvalue())
438
+
439
+
440
+ def _sub_clear_compacted(hook_input: dict) -> None:
441
+ """``read_cache.py --clear-compacted --quiet`` (entry 4, matcher ``compact``).
442
+
443
+ Mirrors read_cache.main()'s --clear-compacted branch: bail loudly (stderr)
444
+ when the stdin payload is empty, else call handle_clear_compacted(payload,
445
+ quiet=True). read_cache is imported lazily so a non-compact SessionStart --
446
+ the overwhelming majority -- never pays for the import.
447
+
448
+ Emits nothing on stdout by design (all its output, success and failure, goes
449
+ to stderr), so it cannot perturb the SessionStart context stream.
450
+ """
451
+ budget = _runner_budget(10)
452
+ if budget < 0.1:
453
+ return
454
+ if not hook_input:
455
+ # C5 parity: FAILED branches stay loud even under --quiet.
456
+ sys.stderr.write(
457
+ "[read_cache] --clear-compacted FAILED: no stdin hook input; "
458
+ "live session file_reads left intact (not cleared)\n"
459
+ )
460
+ return
461
+ import read_cache # noqa: PLC0415 (lazy: only compact starts pay for it)
462
+
463
+ read_cache.handle_clear_compacted(hook_input, True)
464
+
465
+
466
+ def _sub_compact_restore_new_session(hook_input: dict, sink: list) -> None:
467
+ """``measure.py compact-restore --new-session-only --once-mark`` (entry 5).
468
+
469
+ Mirrors the ``compact-restore`` dispatch (measure.py ~L42582) with
470
+ ``--new-session-only --once-mark``: _mark_ran_this_session (WRITE, never
471
+ check -- a resume/compact SessionStart is NOT latched out), then
472
+ compact_restore(new_session_only=True), with the same Codex/Cowork wrap
473
+ routed into the shared ``sink``.
474
+ """
475
+ sid = hook_input.get("session_id")
476
+ measure._mark_ran_this_session("compact-restore-new-session", sid)
477
+ budget = _runner_budget(measure._int_env("TOKEN_OPTIMIZER_COMPACT_RESTORE_BUDGET", 8))
478
+ if budget < 0.1:
479
+ return
480
+ buf = io.StringIO()
481
+ with redirect_stdout(buf):
482
+ measure.compact_restore(session_id=sid, new_session_only=True)
483
+ sink.append(buf.getvalue())
484
+
485
+
486
+ def _quality_cache_self_heal() -> None:
487
+ """Replicate the quality-cache dispatch's self-healing block: if the
488
+ quality-cache hook is missing from settings.json and this is NOT a plugin
489
+ install and quality_bar_disabled is unset, reinstall it.
490
+
491
+ For plugin installs (the hooks.json context this runner runs in) the
492
+ ``_is_plugin`` check is True and the block is a no-op, exactly as in the
493
+ dispatch. Replicated verbatim so non-plugin manual installs keep the same
494
+ self-heal behavior. Uses measure._quality_cache_hook_present
495
+ so an install whose canonical hook is the consolidated dispatcher is
496
+ not "healed" by appending a duplicate legacy hook. Fail-open: never raises.
497
+ """
498
+ try:
499
+ _is_plugin = measure._is_running_from_plugin_cache() or measure._is_plugin_installed()
500
+ try:
501
+ _qb_disabled = False
502
+ if measure.CONFIG_PATH.exists():
503
+ _qb_cfg = json.loads(measure.CONFIG_PATH.read_text(encoding="utf-8"))
504
+ _qb_disabled = _qb_cfg.get("quality_bar_disabled", False)
505
+ if (
506
+ not _is_plugin
507
+ and not _qb_disabled
508
+ and measure.SETTINGS_PATH.exists()
509
+ ):
510
+ _sh_settings = json.loads(measure.SETTINGS_PATH.read_text(encoding="utf-8"))
511
+ _sh_hooks = _sh_settings.get("hooks", {}).get("UserPromptSubmit", [])
512
+ if not measure._quality_cache_hook_present(_sh_hooks):
513
+ measure.setup_quality_bar(quiet=True)
514
+ except Exception:
515
+ pass
516
+ except Exception:
517
+ pass
518
+
519
+
520
+ def _check_consent() -> bool:
521
+ """Consent gate for the consolidated runner, mirroring ``run._check_consent``.
522
+
523
+ run.py exempts this script from its own consent gate (the runner is
524
+ dispatched with no distinguishing args, so the ``ensure-health``
525
+ exempt-command match cannot fire there, and the runner contains the
526
+ ensure-health bootstrap itself). The per-subcommand consent decision
527
+ therefore lives HERE.
528
+
529
+ Imports ``run._check_consent`` by explicit path via
530
+ ``importlib.util.spec_from_file_location`` so a future ``skills/.../run.py``
531
+ on ``sys.path`` cannot shadow the real ``hooks/run.py`` and silently
532
+ disable the consent gate. Fails open on any error.
533
+ """
534
+ try:
535
+ run_py = Path(__file__).resolve().parent / "run.py"
536
+ if not run_py.is_file():
537
+ return True
538
+ spec = _importlib_util.spec_from_file_location("_to_run_consent_ss", run_py)
539
+ _run_mod = _importlib_util.module_from_spec(spec)
540
+ spec.loader.exec_module(_run_mod)
541
+ return _run_mod._check_consent()
542
+ except Exception:
543
+ return True
544
+
545
+
546
+ def main() -> int:
547
+ hook_input = _read_hook_input()
548
+ is_compact = _is_compact_start(hook_input)
549
+
550
+ # Consent gate. Pre-consolidation, run.py's exempt_commands check matched
551
+ # the literal "ensure-health" arg on hooks.json entry 1, so THAT entry ran
552
+ # even with consent False (it bootstraps v5_welcome_shown /
553
+ # enterprise_consent_shown), while entries 2-5 carried no exempt arg and
554
+ # run.py returned 0 for them. The consolidated runner is dispatched with no
555
+ # args, so run.py exempts the whole runner path and the per-subcommand
556
+ # decision is made here: consent False -> ONLY ensure-health runs.
557
+ consent = _check_consent()
558
+
559
+ # ONE shared HookDeadline for the entire runner (see the sizing note above).
560
+ _install_runner_deadline()
561
+
562
+ # Raw compact-restore text destined for ONE shared additionalContext
563
+ # envelope (see the envelope note above). compact-restore produces the
564
+ # restored-state additionalContext, which is legitimately model-context
565
+ # (the feature, not the tax). ensure-health and quality-cache
566
+ # systemMessage lines are user-facing (tax-free) and also feed the
567
+ # envelope; their bare plain-text star pitch / nudges are model-facing
568
+ # additionalContext and feed the envelope too. All stderr is diagnostic
569
+ # and goes to the log file.
570
+ _wrapped: list[str] = []
571
+
572
+ def _capture(name: str, fn, *args, **kwargs) -> None:
573
+ # Capture BOTH stdout and stderr from each subcommand. The host
574
+ # captures both streams into the model's session context, so
575
+ # diagnostics must go to the log file, never to either real stream.
576
+ buf = io.StringIO()
577
+ err_buf = io.StringIO()
578
+ with redirect_stdout(buf), redirect_stderr(err_buf):
579
+ _run_safely(name, fn, *args, **kwargs)
580
+ captured = buf.getvalue()
581
+ err_captured = err_buf.getvalue()
582
+ # ALL stdout -> envelope (systemMessage + bare-text + JSON all
583
+ # collapse into one host-valid object via _emit_session_start_stdout).
584
+ # stderr -> log.
585
+ if captured:
586
+ _wrapped.append(captured)
587
+ if err_captured:
588
+ _write_diagnostics(f"--- {name} ---\n{err_captured}")
589
+
590
+ if not consent:
591
+ # Bootstrap only. ensure-health writes the consent flags; every other
592
+ # subcommand stayed dark behind run.py's gate and stays dark here.
593
+ _runner_budget(8, subcommand_count_hint=1)
594
+ _capture("ensure-health", _sub_ensure_health, hook_input)
595
+ _emit_session_start_stdout(_wrapped, hook_input)
596
+ _clear_runner_deadline()
597
+ return 0
598
+
599
+ # Fair-share the 18s across the subcommands that will actually run. The two
600
+ # matcher:"compact" subcommands only count on a compact start, so a normal
601
+ # start gives its three subcommands a third of the budget each instead of a
602
+ # fifth. Dispatch order matches the hooks.json entry order exactly.
603
+ pending = 5 if is_compact else 3
604
+ _runner_budget(8, subcommand_count_hint=pending)
605
+
606
+ _capture("ensure-health", _sub_ensure_health, hook_input)
607
+ _capture("quality-cache --force", _sub_quality_cache_force, hook_input)
608
+ if is_compact:
609
+ _capture("compact-restore --compact", _sub_compact_restore_compact,
610
+ hook_input, _wrapped)
611
+ _capture("read_cache --clear-compacted", _sub_clear_compacted, hook_input)
612
+ _capture("compact-restore --new-session-only", _sub_compact_restore_new_session,
613
+ hook_input, _wrapped)
614
+
615
+ # Emit the compact-restore payloads and ensure-health/quality-cache
616
+ # systemMessage lines as ONE host-valid JSON object. systemMessage values
617
+ # collapse to payload["systemMessage"] (user-facing, no additionalContext,
618
+ # zero model-context tax); compact-restore text collapses to
619
+ # hookSpecificOutput.additionalContext (the restored-state feature).
620
+ # See _emit_session_start_stdout for why a concatenated raw stream is not
621
+ # an option on Codex.
622
+ _emit_session_start_stdout(_wrapped, hook_input)
623
+
624
+ _clear_runner_deadline()
625
+ return 0
626
+
627
+
628
+ if __name__ == "__main__":
629
+ sys.exit(main())