@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,602 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer — Cursor readiness doctor.
3
+
4
+ Per-surface health report with fix-it hints, plus ``--probe`` which replays
5
+ the documented payload for each wired event through the exact installed
6
+ command string (POSIX ``/bin/sh -c``) so a live Cursor is not required to prove
7
+ the hooks can fire.
8
+
9
+ Checks:
10
+ P0 Cursor binary presence (CLI ``agent`` / ``cursor`` launcher)
11
+ P0 ~/.cursor exists; hooks.json present + writable
12
+ P1 Token Optimizer hook entries installed (six events) + parseable
13
+ P1 installed payload integrity (bridge, atomic-writer, compress)
14
+ P1 observed-events ledger (which events fired; rewrite_honoured vs ignored)
15
+ P2 state.vscdb (IDE token plane) / transcript dir (CLI plane)
16
+ P2 daemon port 24846 availability
17
+
18
+ Usage:
19
+ python3 cursor_doctor.py [--json]
20
+ python3 cursor_doctor.py --probe [--json]
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import json
27
+ import os
28
+ import shlex
29
+ import shutil
30
+ import subprocess
31
+ import sys
32
+ import tempfile
33
+ from pathlib import Path
34
+
35
+ _SCRIPT_DIR = Path(__file__).resolve().parent
36
+ sys.path.insert(0, str(_SCRIPT_DIR))
37
+
38
+ from runtime_env import cursor_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
39
+ from cursor_install import _py_path_is_trusted # noqa: E402
40
+
41
+ DAEMON_PORT = 24846
42
+ _NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
43
+
44
+ # The six events the installer wires (order = probe order = docs order).
45
+ _WIRED_EVENTS = ("sessionStart", "preToolUse", "postToolUse", "preCompact", "stop", "sessionEnd")
46
+
47
+
48
+ def _check(status: str, name: str, detail: str, hint: str = "") -> dict:
49
+ out = {"status": status, "name": name, "detail": detail}
50
+ if hint:
51
+ out["hint"] = hint
52
+ return out
53
+
54
+
55
+ def _binary_checks() -> list:
56
+ checks = []
57
+ override = os.environ.get("TOKEN_OPTIMIZER_CURSOR_BIN", "").strip()
58
+ candidates = [override] if override else []
59
+ # `agent` is deliberately NOT PATH-scanned (too generic a binary name);
60
+ # the documented CLI install path is checked directly instead.
61
+ candidates.append(shutil.which("cursor") or "")
62
+ candidates.append(str(Path.home() / ".local" / "bin" / "agent"))
63
+ found = next((c for c in candidates if c and Path(c).is_file()), None)
64
+ if found:
65
+ checks.append(_check("ok", "cursor binary", found))
66
+ else:
67
+ checks.append(
68
+ _check(
69
+ "warn",
70
+ "cursor binary",
71
+ "No Cursor binary found (checked `cursor` on PATH and ~/.local/bin/agent).",
72
+ "Install Cursor from https://cursor.com, or set TOKEN_OPTIMIZER_CURSOR_BIN.",
73
+ )
74
+ )
75
+ return checks
76
+
77
+
78
+ def _home_checks() -> list:
79
+ checks = []
80
+ root = cursor_home()
81
+ if not root.exists():
82
+ checks.append(
83
+ _check(
84
+ "warn",
85
+ "~/.cursor",
86
+ f"{root} does not exist yet.",
87
+ "Run Cursor once so it creates its home, then re-run install.",
88
+ )
89
+ )
90
+ return checks
91
+ checks.append(_check("ok", "~/.cursor", str(root)))
92
+
93
+ hook_path = root / "hooks.json"
94
+ if hook_path.exists() and not hook_path.is_file():
95
+ checks.append(_check("fail", "hooks.json", f"{hook_path} exists but is not a file."))
96
+ elif hook_path.exists() and not os.access(str(hook_path), os.W_OK):
97
+ checks.append(_check("fail", "hooks.json", f"{hook_path} is not writable.", "Fix permissions (chmod u+w)."))
98
+ elif hook_path.exists():
99
+ checks.append(_check("ok", "hooks.json", f"{hook_path} (writable)"))
100
+ else:
101
+ checks.append(
102
+ _check("warn", "hooks.json", f"{hook_path} missing (created on install).",
103
+ _hint("Run `python3 measure.py cursor-install`."))
104
+ )
105
+ return checks
106
+
107
+
108
+ def _str_entry_commands(config: dict) -> dict:
109
+ """event -> [command strings], preserving only entries with a command."""
110
+ hooks = config.get("hooks") if isinstance(config, dict) else None
111
+ out: dict = {}
112
+ if not isinstance(hooks, dict):
113
+ return out
114
+ for event, entries in hooks.items():
115
+ if not isinstance(entries, list):
116
+ continue
117
+ commands = []
118
+ for e in entries:
119
+ if isinstance(e, dict) and isinstance(e.get("command"), str):
120
+ commands.append(e["command"])
121
+ if commands:
122
+ out[str(event)] = commands
123
+ return out
124
+
125
+
126
+ def _hook_config_checks() -> list:
127
+ checks = []
128
+ hook_path = cursor_home() / "hooks.json"
129
+ if not hook_path.exists():
130
+ checks.append(_check("warn", "TO hook config", "Not installed.",
131
+ _hint("Run `python3 measure.py cursor-install`.")))
132
+ return checks
133
+ try:
134
+ config = json.loads(hook_path.read_text(encoding="utf-8"))
135
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
136
+ checks.append(
137
+ _check("fail", "TO hook config", f"{hook_path} unreadable/invalid: {exc}",
138
+ _hint("Re-run `python3 measure.py cursor-install` to rewrite it."))
139
+ )
140
+ return checks
141
+
142
+ commands = _str_entry_commands(config)
143
+ ours = {
144
+ event: [c for c in commands.get(event, []) if "cursor_hook_bridge.py" in c]
145
+ for event in _WIRED_EVENTS
146
+ }
147
+ wired = [e for e in _WIRED_EVENTS if ours.get(e)]
148
+ if wired:
149
+ checks.append(_check("ok", "TO hook config",
150
+ f"{hook_path} (wired events: {', '.join(wired)})"))
151
+ else:
152
+ checks.append(
153
+ _check("fail", "TO hook config", "No Token Optimizer cursor entries found.",
154
+ _hint("Run `python3 measure.py cursor-install`."))
155
+ )
156
+ missing = [e for e in _WIRED_EVENTS if not ours.get(e)]
157
+ if missing and wired:
158
+ checks.append(
159
+ _check("warn", "hook event coverage", f"Missing events: {', '.join(missing)}.",
160
+ "Re-run install to restore the full six-event set.")
161
+ )
162
+ return checks
163
+
164
+
165
+ def _payload_checks() -> list:
166
+ checks = []
167
+ plugin_dir = cursor_home() / "token-optimizer" / "plugin"
168
+ if not plugin_dir.is_dir():
169
+ checks.append(_check("warn", "hook payload", f"{plugin_dir} missing.",
170
+ _hint("Run `python3 measure.py cursor-install`.")))
171
+ return checks
172
+ missing = [
173
+ m for m in ("cursor_hook_bridge.py", "codex_io.py", "bash_compress.py")
174
+ if not (plugin_dir / m).exists()
175
+ ]
176
+ if missing:
177
+ checks.append(
178
+ _check("fail", "hook payload",
179
+ f"Installed bridge is missing modules: {', '.join(missing)}.",
180
+ _hint("Re-run `python3 measure.py cursor-install` to refresh the payload."))
181
+ )
182
+ else:
183
+ checks.append(_check("ok", "hook payload", f"{plugin_dir} (complete)"))
184
+ return checks
185
+
186
+
187
+ def _locator_checks() -> list:
188
+ """The bridge's detached rollup/dashboard spawns resolve measure.py via a
189
+ one-line ``measure-path`` locator (measure.py is never copied into the
190
+ plugin dir). Verify it exists and names a real file."""
191
+ checks = []
192
+ plugin_dir = cursor_home() / "token-optimizer" / "plugin"
193
+ locator = plugin_dir / "measure-path"
194
+ if not locator.exists():
195
+ checks.append(
196
+ _check(
197
+ "warn",
198
+ "measure-path locator",
199
+ f"{locator} missing (rollups paused).",
200
+ _hint("Run `python3 measure.py cursor-install` to rewrite it."),
201
+ )
202
+ )
203
+ return checks
204
+ try:
205
+ target = Path(locator.read_text(encoding="utf-8").strip())
206
+ except OSError:
207
+ target = None
208
+ if target is not None and target.is_file():
209
+ checks.append(_check("ok", "measure-path locator", str(target)))
210
+ else:
211
+ checks.append(
212
+ _check(
213
+ "fail",
214
+ "measure-path locator",
215
+ f"{locator} does not name an existing measure.py.",
216
+ _hint("Run `python3 measure.py cursor-install` to rewrite it."),
217
+ )
218
+ )
219
+ return checks
220
+
221
+
222
+ def _persisted_python_check() -> list:
223
+ """The persisted hook command must use an absolute trusted interpreter,
224
+ never a bare ``python3`` (PATH-hijack risk). Parse our command and verify."""
225
+ checks = []
226
+ commands = _installed_commands()
227
+ if not commands:
228
+ checks.append(
229
+ _check("warn", "persisted python", "No wired hook command to inspect.",
230
+ _hint("Run `python3 measure.py cursor-install`."))
231
+ )
232
+ return checks
233
+ for event, cmd in commands.items():
234
+ # Same strict shape the probe enforces: runtime pin, absolute python,
235
+ # absolute bridge, wired event.
236
+ argv = _parse_hook_command(cmd)
237
+ if argv and Path(argv[0]).is_file():
238
+ checks.append(_check("ok", "persisted python", argv[0]))
239
+ return checks
240
+ checks.append(
241
+ _check(
242
+ "fail",
243
+ "persisted python",
244
+ "The wired hook command does not use an absolute python path.",
245
+ _hint("Run `python3 measure.py cursor-install` to re-persist a trusted interpreter."),
246
+ )
247
+ )
248
+ return checks
249
+
250
+
251
+ def _read_observed(path: Path) -> list:
252
+ if not path.exists():
253
+ return []
254
+ entries = []
255
+ try:
256
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
257
+ line = line.strip()
258
+ if not line:
259
+ continue
260
+ try:
261
+ data = json.loads(line)
262
+ if isinstance(data, dict):
263
+ entries.append(data)
264
+ except json.JSONDecodeError:
265
+ continue
266
+ except OSError:
267
+ return []
268
+ return entries
269
+
270
+
271
+ def _observed_checks() -> list:
272
+ checks = []
273
+ path = cursor_home() / "token-optimizer" / "observed-events.jsonl"
274
+ entries = _read_observed(path)
275
+ if not entries:
276
+ checks.append(
277
+ _check("warn", "observed events", f"{path} empty or missing.",
278
+ _hint("Run `python3 measure.py cursor-doctor --probe` to prove hooks fire."))
279
+ )
280
+ return checks
281
+ counts: dict = {}
282
+ honoured = 0
283
+ ignored = 0
284
+ for e in entries:
285
+ event = str(e.get("event") or "?")
286
+ counts[event] = counts.get(event, 0) + 1
287
+ rewrite = e.get("rewrite")
288
+ if rewrite == "honoured":
289
+ honoured += 1
290
+ elif rewrite == "ignored":
291
+ ignored += 1
292
+ summary = ", ".join(f"{k} ({v})" for k, v in sorted(counts.items()))
293
+ detail = f"{len(entries)} event(s): {summary}"
294
+ if honoured or ignored:
295
+ detail += f"; Shell rewrite: {honoured} honoured, {ignored} ignored"
296
+ checks.append(_check("ok", "observed events", detail))
297
+ return checks
298
+
299
+
300
+ def _data_checks() -> list:
301
+ checks = []
302
+ try:
303
+ import cursor_state
304
+
305
+ vscdb = cursor_state.state_vscdb_path()
306
+ except Exception as exc:
307
+ vscdb = None
308
+ checks.append(_check("warn", "IDE token plane", f"reader unavailable: {exc}"))
309
+ if vscdb is not None:
310
+ if vscdb.exists():
311
+ checks.append(_check("ok", "IDE token plane", str(vscdb)))
312
+ else:
313
+ checks.append(
314
+ _check("warn", "IDE token plane", f"{vscdb} missing (no IDE chats yet).")
315
+ )
316
+
317
+ projects = cursor_home() / "projects"
318
+ if projects.is_dir():
319
+ checks.append(_check("ok", "CLI transcript plane", str(projects)))
320
+ else:
321
+ checks.append(
322
+ _check("warn", "CLI transcript plane", f"{projects} missing (no CLI chats yet).")
323
+ )
324
+ return checks
325
+
326
+
327
+ def _daemon_check() -> dict:
328
+ import socket
329
+
330
+ try:
331
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
332
+ sock.settimeout(0.5)
333
+ in_use = sock.connect_ex(("127.0.0.1", DAEMON_PORT)) == 0
334
+ except OSError:
335
+ in_use = False
336
+ if in_use:
337
+ return _check("ok", "dashboard daemon", f"port {DAEMON_PORT} serving")
338
+ return _check("ok", "dashboard daemon", f"port {DAEMON_PORT} free (daemon not running — optional)")
339
+
340
+
341
+ def run_checks() -> list:
342
+ checks = []
343
+ checks.extend(_binary_checks())
344
+ checks.extend(_home_checks())
345
+ checks.extend(_hook_config_checks())
346
+ checks.extend(_payload_checks())
347
+ checks.extend(_locator_checks())
348
+ checks.extend(_persisted_python_check())
349
+ checks.extend(_observed_checks())
350
+ checks.extend(_data_checks())
351
+ checks.append(_daemon_check())
352
+ return checks
353
+
354
+
355
+ # ---------------------------------------------------------------------------
356
+ # --probe: replay documented payloads through the installed command
357
+ # ---------------------------------------------------------------------------
358
+
359
+
360
+ def _probe_payloads() -> dict:
361
+ cv = os.environ.get("CURSOR_VERSION", "").strip()
362
+ return {
363
+ "sessionStart": {
364
+ "hook_event_name": "sessionStart",
365
+ "session_id": "to-probe-session",
366
+ "workspace_roots": ["/tmp/token-optimizer-probe"],
367
+ "cursor_version": cv or "3.18.9",
368
+ },
369
+ "preToolUse": {
370
+ "hook_event_name": "preToolUse",
371
+ "tool_name": "Shell",
372
+ "tool_input": {"command": "echo token-optimizer-probe",
373
+ "working_directory": "/tmp/token-optimizer-probe"},
374
+ "conversation_id": "to-probe-conv",
375
+ "cursor_version": cv or "3.18.9",
376
+ "workspace_roots": ["/tmp/token-optimizer-probe"],
377
+ },
378
+ "postToolUse": {
379
+ "hook_event_name": "postToolUse",
380
+ "tool_name": "Shell",
381
+ "tool_input": {"command": "echo token-optimizer-probe",
382
+ "working_directory": "/tmp/token-optimizer-probe"},
383
+ "conversation_id": "to-probe-conv",
384
+ "cursor_version": cv or "3.18.9",
385
+ "workspace_roots": ["/tmp/token-optimizer-probe"],
386
+ },
387
+ "preCompact": {
388
+ "hook_event_name": "preCompact",
389
+ "trigger": "manual",
390
+ "context_usage_percent": 0.8,
391
+ "context_tokens": 100_000,
392
+ "context_window_size": 128_000,
393
+ "conversation_id": "to-probe-conv",
394
+ "cursor_version": cv or "3.18.9",
395
+ },
396
+ "stop": {
397
+ "hook_event_name": "stop",
398
+ "conversation_id": "to-probe-conv",
399
+ "cursor_version": cv or "3.18.9",
400
+ },
401
+ "sessionEnd": {
402
+ "hook_event_name": "sessionEnd",
403
+ "conversation_id": "to-probe-conv",
404
+ "reason": "probe",
405
+ "cursor_version": cv or "3.18.9",
406
+ },
407
+ }
408
+
409
+
410
+ def _installed_commands() -> dict:
411
+ hook_path = cursor_home() / "hooks.json"
412
+ if not hook_path.exists():
413
+ return {}
414
+ try:
415
+ config = json.loads(hook_path.read_text(encoding="utf-8"))
416
+ except (OSError, json.JSONDecodeError, ValueError):
417
+ return {}
418
+ commands = _str_entry_commands(config)
419
+ # Identity, not substring: only entries whose bridge token is a bridge we
420
+ # own (the installed plugin copy, or the sibling checkout bridge in dev)
421
+ # qualify, so a corrupted entry pointing at /tmp/evil/cursor_hook_bridge.py
422
+ # is never replayed by --probe.
423
+ ours = {
424
+ str(cursor_home() / "token-optimizer" / "plugin" / "cursor_hook_bridge.py"),
425
+ str(_SCRIPT_DIR / "cursor_hook_bridge.py"),
426
+ }
427
+ out = {}
428
+ for event in _WIRED_EVENTS:
429
+ for cmd in commands.get(event, []):
430
+ argv = _parse_hook_command(cmd)
431
+ if argv and argv[1] in ours:
432
+ out[event] = cmd
433
+ break
434
+ return out
435
+
436
+
437
+ def _parse_hook_command(command: str) -> list | None:
438
+ """Parse a persisted hooks.json command into argv, or None if malformed.
439
+
440
+ The installer writes exactly ``TOKEN_OPTIMIZER_RUNTIME=cursor <abs-py>
441
+ <abs-bridge> <event>``. Anything else (extra tokens, relative paths, an
442
+ unknown event, shell metacharacters that survive shlex) is rejected rather
443
+ than executed: hooks.json is shared with other tools, and --probe must never
444
+ become an injection vector for a corrupted or malicious entry.
445
+ """
446
+ try:
447
+ # posix=False on Windows: shlex's POSIX mode eats backslashes, so
448
+ # C:\Python314\python.exe would parse as "C:Python314python.exe".
449
+ tokens = shlex.split(command, posix=(os.name != "nt"))
450
+ except ValueError:
451
+ return None
452
+ if len(tokens) != 4:
453
+ return None
454
+ runtime, py, bridge, event = tokens
455
+ if runtime != "TOKEN_OPTIMIZER_RUNTIME=cursor":
456
+ return None
457
+ if not os.path.isabs(py) or not os.path.isabs(bridge):
458
+ return None
459
+ if event not in _WIRED_EVENTS:
460
+ return None
461
+ return tokens[1:]
462
+
463
+
464
+ def _run_probe_command(command: str, payload: dict, probe_home: Path) -> dict:
465
+ """Run one installed command (no shell) with the payload on stdin.
466
+
467
+ The command is shlex-parsed and shape-validated first (see
468
+ _parse_hook_command); a malformed entry is reported, never executed.
469
+ ``probe_home`` redirects the bridge's data writes (tallies, observed-events)
470
+ to a throwaway dir so replaying the documented payloads proves the hooks can
471
+ fire without contaminating real session data with synthetic probe rows.
472
+ """
473
+ if sys.platform == "win32":
474
+ return {"event": None, "status": "skip", "detail": "probe is POSIX-only"}
475
+ argv = _parse_hook_command(command)
476
+ if argv is None:
477
+ return {"event": None, "status": "fail",
478
+ "detail": "hook command is not the expected "
479
+ "TOKEN_OPTIMIZER_RUNTIME=cursor <abs-python> <abs-bridge> <event> shape; refusing to run it"}
480
+ # B2-P2-1: validate the persisted python interpreter through the same trust
481
+ # gate the installer uses. A corrupted/tampered hooks.json could point at an
482
+ # untrusted interpreter even with a legitimate bridge path; the probe must
483
+ # never execute an untrusted binary.
484
+ if not _py_path_is_trusted(argv[0]):
485
+ return {"event": None, "status": "fail",
486
+ "detail": f"persisted python {argv[0]} is not trusted (ownership/writability); refusing to execute it"}
487
+ env = dict(os.environ)
488
+ env.update({
489
+ "PYTHONUTF8": "1",
490
+ "PYTHONIOENCODING": "utf-8",
491
+ "TOKEN_OPTIMIZER_PROBE": "1",
492
+ "TOKEN_OPTIMIZER_CURSOR_HOME": str(probe_home),
493
+ })
494
+ try:
495
+ proc = subprocess.run(
496
+ argv,
497
+ input=json.dumps(payload),
498
+ capture_output=True,
499
+ text=True,
500
+ timeout=5,
501
+ env=env,
502
+ creationflags=_NO_WINDOW,
503
+ )
504
+ except subprocess.TimeoutExpired:
505
+ return {"status": "fail", "detail": "timed out after 5s"}
506
+ except (OSError, subprocess.SubprocessError) as exc:
507
+ return {"status": "fail", "detail": str(exc)}
508
+ return {
509
+ "status": "ok" if proc.returncode == 0 else "fail",
510
+ "returncode": proc.returncode,
511
+ "stdout": (proc.stdout or "").strip(),
512
+ "stderr": (proc.stderr or "").strip(),
513
+ }
514
+
515
+
516
+ def run_probe() -> list:
517
+ results = []
518
+ commands = _installed_commands()
519
+ # Throwaway data home (under $HOME so runtime_env's strict guard accepts it)
520
+ # so probe replays never write synthetic tallies/observed-events into the
521
+ # real ~/.cursor/token-optimizer data dir.
522
+ probe_home = Path(tempfile.mkdtemp(prefix=".cursor-to-probe-", dir=Path.home()))
523
+ try:
524
+ for event, payload in _probe_payloads().items():
525
+ command = commands.get(event)
526
+ if not command:
527
+ results.append({"event": event, "status": "skip",
528
+ "detail": "no cursor hook entry installed for this event"})
529
+ continue
530
+ row = _run_probe_command(command, payload, probe_home)
531
+ row["event"] = event
532
+ results.append(row)
533
+ finally:
534
+ shutil.rmtree(probe_home, ignore_errors=True)
535
+ return results
536
+
537
+
538
+ _BADGES = {"ok": "[OK] ", "warn": "[WARN]", "fail": "[FAIL]"}
539
+
540
+
541
+ def _print_text(checks: list) -> None:
542
+ print("Token Optimizer — Cursor doctor")
543
+ print()
544
+ for c in checks:
545
+ print(f" {_BADGES.get(c['status'], '[?] ')} {c['name']}: {c['detail']}")
546
+ if c.get("hint"):
547
+ print(f" fix: {c['hint']}")
548
+ fails = sum(1 for c in checks if c["status"] == "fail")
549
+ warns = sum(1 for c in checks if c["status"] == "warn")
550
+ print()
551
+ print(f" {len(checks)} checks — {fails} fail, {warns} warn")
552
+
553
+
554
+ def _print_probe(results: list) -> None:
555
+ print("Cursor hook probe (replaying documented payloads through the installed commands)")
556
+ print()
557
+ for r in results:
558
+ event = r.get("event", "?")
559
+ status = r.get("status", "?")
560
+ if status == "ok":
561
+ print(f" [OK] {event}: exit 0" + (f" — {r['stdout']}" if r.get("stdout") else ""))
562
+ elif status == "skip":
563
+ print(f" [SKIP] {event}: {r.get('detail', '')}")
564
+ else:
565
+ print(f" [FAIL] {event}: {r.get('detail') or r.get('returncode')}")
566
+ if r.get("stderr"):
567
+ print(f" stderr: {r['stderr']}")
568
+ ran = [r for r in results if r.get("status") == "ok"]
569
+ print()
570
+ print(f" {len(ran)}/{len(results)} wired events fired (exit 0)")
571
+
572
+
573
+ def build_parser() -> argparse.ArgumentParser:
574
+ parser = argparse.ArgumentParser(description=__doc__)
575
+ parser.add_argument("--json", action="store_true")
576
+ parser.add_argument("--probe", action="store_true")
577
+ return parser
578
+
579
+
580
+ def main(argv=None) -> int:
581
+ args = build_parser().parse_args(argv)
582
+ if args.probe:
583
+ results = run_probe()
584
+ if args.json:
585
+ print(json.dumps(results, indent=1))
586
+ else:
587
+ _print_probe(results)
588
+ ran = [r for r in results if r.get("status") == "ok"]
589
+ failed = [r for r in results if r.get("status") == "fail"]
590
+ # Skips are informational (not installed / Windows), not failures.
591
+ return 1 if failed else 0
592
+
593
+ checks = run_checks()
594
+ if args.json:
595
+ print(json.dumps(checks, indent=1))
596
+ else:
597
+ _print_text(checks)
598
+ return 1 if any(c["status"] == "fail" for c in checks) else 0
599
+
600
+
601
+ if __name__ == "__main__":
602
+ sys.exit(main())