@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,426 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer — Cursor installer.
3
+
4
+ Wires Token Optimizer into Cursor's shared user hooks file:
5
+
6
+ 1. Copies the adapter modules into ``<cursor_home>/token-optimizer/plugin/``
7
+ so the hook bridge runs from a stable path that survives repo moves.
8
+ 2. READ-MERGE-WRITES ``~/.cursor/hooks.json``: existing entries owned by other
9
+ tools are preserved verbatim; only entries whose ``command`` points at our
10
+ bridge path are replaced. Cursor has one shared hooks.json (no per-plugin
11
+ file like Copilot), so clobbering it would destroy other people's hooks.
12
+ 3. Refuses on native Windows (``os.name == "nt"``): the persisted ``command``
13
+ string is POSIX-shell quoted and cmd.exe would not parse it. Windows work is
14
+ deferred rather than silently writing a no-op hook.
15
+
16
+ Idempotent: re-running refreshes the payload and replaces only OUR entries.
17
+ Uninstall removes only OUR entries and the payload dir; session data stays.
18
+
19
+ Usage:
20
+ python3 cursor_install.py install [--dry-run]
21
+ python3 cursor_install.py uninstall [--dry-run]
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import json
28
+ import os
29
+ import shlex
30
+ import shutil
31
+ import stat as _stat
32
+ import sys
33
+ from contextlib import contextmanager
34
+ from pathlib import Path
35
+
36
+ _SCRIPT_DIR = Path(__file__).resolve().parent
37
+ sys.path.insert(0, str(_SCRIPT_DIR))
38
+
39
+ from py_trust import py_path_is_trusted, py_trust_reason # noqa: E402
40
+ from runtime_env import cursor_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
41
+
42
+ HOOK_TIMEOUT_SEC = 10
43
+
44
+ # Modules the bridge needs at runtime, copied next to it so the installed
45
+ # hook never depends on the repo checkout location.
46
+ _PAYLOAD_MODULES = (
47
+ "cursor_hook_bridge.py",
48
+ "cursor_state.py",
49
+ "cursor_session.py",
50
+ "bash_hook.py",
51
+ "bash_compress.py",
52
+ # Dependency-free whitelist gate shared by bash_hook + bash_compress.
53
+ "bash_whitelist.py",
54
+ "hook_io.py",
55
+ "plugin_env.py",
56
+ "runtime_env.py",
57
+ # codex_io supplies atomic_write_json — without it the bridge's tally and
58
+ # observed-events writes silently no-op (crash recovery would be dead).
59
+ "codex_io.py",
60
+ # hermes_session supplies compute_quality_score — without it cursor_session
61
+ # silently falls back to a single-signal quality estimate.
62
+ "hermes_session.py",
63
+ # spawn_utils supplies spawn_detached — without it the bridge's degraded
64
+ # fallback does NOT detach, so rollup/dashboard spawns die with the hook.
65
+ "spawn_utils.py",
66
+ # hook_runtime supplies lease_lock (tally RMW + stop throttle) and
67
+ # utf8_io is enforced at startup; both degrade silently when absent.
68
+ "hook_runtime.py",
69
+ "utf8_io.py",
70
+ # credential_patterns: bash_compress's credential-preservation patterns
71
+ # (the inline fallback misses e.g. ghp_/github_pat_ tokens, #171).
72
+ "credential_patterns.py",
73
+ )
74
+
75
+ # One-line locator written next to the bridge, naming the canonical measure.py
76
+ # in the checkout. The bridge's detached rollup/dashboard spawns resolve
77
+ # measure.py through this locator because measure.py itself is NOT copied into
78
+ # the plugin dir (version-drift risk — nothing refreshes a plugin-dir copy on
79
+ # update; the checkout's measure.py stays the single source). Mirrors
80
+ # hermes_install._MEASURE_LOCATOR_NAME.
81
+ _MEASURE_LOCATOR_NAME = "measure-path"
82
+
83
+
84
+ def _plugin_dir(root: Path) -> Path:
85
+ return root / "token-optimizer" / "plugin"
86
+
87
+
88
+ def _host_hooks_path(root: Path) -> Path:
89
+ return root / "hooks.json"
90
+
91
+
92
+ def _py_trust_reason(p: str) -> str | None:
93
+ """None when trusted, else a short human-readable rejection reason."""
94
+ return py_trust_reason(p)
95
+
96
+
97
+ def _py_path_is_trusted(p: str) -> bool:
98
+ """Trusted iff the interpreter's bytes are admin-owned (euid or root) and
99
+ not group/other-writable, and its dir is not world-writable and not
100
+ group-writable by a third party. Pure stat, never runs the target. On
101
+ Windows, stat ownership is unreliable under Git-Bash, so require only that
102
+ the path is a real file."""
103
+ return py_path_is_trusted(p)
104
+
105
+
106
+ def _resolve_safe_python() -> str:
107
+ """An ABSOLUTE, trusted python for the persisted Cursor hook command.
108
+
109
+ Never emit a bare "python3": that string is resolved via $PATH every time the
110
+ hook fires, so a hijacked PATH entry runs attacker code. Resolution order:
111
+ 1. TOKEN_OPTIMIZER_PYTHON, if it names a trusted file;
112
+ 2. sys.executable (absolute path baked in ONCE) -- but only through the
113
+ same trust gate: a writable venv interpreter must never be persisted;
114
+ 3. a $PATH search, accepting only a candidate that passes the gate.
115
+ Raises RuntimeError rather than persist an unsafe command.
116
+ """
117
+ override = os.environ.get("TOKEN_OPTIMIZER_PYTHON", "").strip()
118
+ candidates = []
119
+ if override:
120
+ candidates.append(("TOKEN_OPTIMIZER_PYTHON", override))
121
+ if sys.executable:
122
+ candidates.append(("sys.executable", sys.executable))
123
+ for name in ("python3", "python"):
124
+ cand = shutil.which(name)
125
+ if cand:
126
+ candidates.append((name, cand))
127
+ for _label, cand in candidates:
128
+ if _py_path_is_trusted(cand):
129
+ # Persist the RESOLVED realpath, not abspath: the gate validated
130
+ # realpath(cand) (the symlink target + its parent dir), so persisting
131
+ # the original symlink path would leave a swap window between install
132
+ # and hook fire (an attacker with write access to the symlink's parent
133
+ # dir could redirect the symlink to a malicious interpreter).
134
+ return os.path.realpath(cand)
135
+ reasons = [f"{label}={cand}: {_py_trust_reason(cand)}"
136
+ for label, cand in candidates]
137
+ raise RuntimeError(
138
+ "no trusted python interpreter found for the Cursor hook; "
139
+ "set TOKEN_OPTIMIZER_PYTHON to an absolute python3 path and re-run install. "
140
+ "Candidates: " + "; ".join(reasons)
141
+ )
142
+
143
+
144
+ def _hook_entries(bridge_path: Path) -> dict:
145
+ """The hook entries TO appends to ~/.cursor/hooks.json.
146
+
147
+ Cursor's per-hook schema is ``{command, type, matcher?, timeout,
148
+ failClosed?, loop_limit?}`` (verified 2026-09-01). ``command`` is assumed to
149
+ run through a POSIX shell, so the two paths are shlex-quoted and the runtime
150
+ is pinned so the bridge never process-scans on the hot path.
151
+ """
152
+ py_q = shlex.quote(_resolve_safe_python())
153
+ bridge_q = shlex.quote(str(bridge_path))
154
+
155
+ def entry(event: str, *, matcher: str | None = None) -> dict:
156
+ e = {
157
+ "command": f"TOKEN_OPTIMIZER_RUNTIME=cursor {py_q} {bridge_q} {event}",
158
+ "type": "command",
159
+ "timeout": HOOK_TIMEOUT_SEC,
160
+ }
161
+ if matcher is not None:
162
+ e["matcher"] = matcher
163
+ return e
164
+
165
+ return {
166
+ "sessionStart": [entry("sessionStart")],
167
+ # Only the Shell tool is rewritten; matcher keeps every other tool out
168
+ # of the bridge's hot path (Cursor matchers are JS regex over tool name).
169
+ "preToolUse": [entry("preToolUse", matcher="Shell")],
170
+ "postToolUse": [entry("postToolUse")],
171
+ "preCompact": [entry("preCompact")],
172
+ "stop": [entry("stop")],
173
+ "sessionEnd": [entry("sessionEnd")],
174
+ }
175
+
176
+
177
+ def _is_ours(entry, bridge_path: Path) -> bool:
178
+ if not isinstance(entry, dict):
179
+ return False
180
+ cmd = entry.get("command")
181
+ return isinstance(cmd, str) and str(bridge_path) in cmd
182
+
183
+
184
+ def _read_hooks(path: Path) -> dict:
185
+ """Read hooks.json. Missing -> {} (fresh install). A symlink, an unreadable,
186
+ invalid, or non-object root -> RuntimeError: Cursor has ONE shared
187
+ hooks.json, so silently treating a corrupt file as empty would clobber
188
+ other tools' (and Cursor's own) entries on the next write, and writing
189
+ through a symlink would redirect the installer's output to an
190
+ attacker-chosen target."""
191
+ if path.is_symlink():
192
+ raise RuntimeError(
193
+ f"{path} is a symlink; refusing to read-merge-write through it. "
194
+ "Remove the symlink (or point it at the real hooks.json) and re-run."
195
+ )
196
+ if not path.exists():
197
+ return {}
198
+ try:
199
+ raw = path.read_text(encoding="utf-8")
200
+ except OSError as exc:
201
+ raise RuntimeError(f"cannot read {path}: {exc}") from exc
202
+ try:
203
+ data = json.loads(raw)
204
+ except (json.JSONDecodeError, ValueError) as exc:
205
+ raise RuntimeError(f"{path} is not valid JSON: {exc}") from exc
206
+ if not isinstance(data, dict):
207
+ raise RuntimeError(
208
+ f"{path} has a non-object root; refusing to overwrite it."
209
+ )
210
+ return data
211
+
212
+
213
+ def _write_hooks(path: Path, data: dict) -> None:
214
+ try:
215
+ from codex_io import atomic_write_json
216
+
217
+ # replace_symlink: even if a symlink appears between _read_hooks and
218
+ # here, os.replace swaps the symlink itself, never its target.
219
+ atomic_write_json(path, data, replace_symlink=True)
220
+ except ImportError: # pragma: no cover - broken checkout
221
+ path.parent.mkdir(parents=True, exist_ok=True)
222
+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
223
+
224
+
225
+ @contextmanager
226
+ def _hooks_lock(hooks_path: Path):
227
+ """Exclusive lease around the hooks.json read-merge-write.
228
+
229
+ Two concurrent installs (or install racing uninstall) would otherwise both
230
+ read stale content and the second write would silently drop the first's
231
+ entries. Uses hook_runtime.lease_lock (the same portable lock the bridges
232
+ use); a failed acquire aborts loudly instead of racing.
233
+ """
234
+ from hook_runtime import lease_lock
235
+
236
+ lock_path = hooks_path.parent / f".{hooks_path.name}.to-install.lock"
237
+ # 120s lease: the critical section copies the payload and rewrites
238
+ # hooks.json; a 30s lease could lapse mid-RMW on a slow disk and let a
239
+ # concurrent installer reclaim it, reintroducing the clobber.
240
+ with lease_lock(lock_path, acquire_timeout=5.0, lease_seconds=120.0) as acquired:
241
+ if not acquired:
242
+ raise RuntimeError(
243
+ "another Cursor install/uninstall is in progress "
244
+ f"(could not acquire {lock_path}); re-run in a moment"
245
+ )
246
+ yield
247
+
248
+
249
+ def _copy_no_follow(src: Path, dest: Path) -> None:
250
+ """Copy src to dest without ever writing through a symlink at dest.
251
+
252
+ A pre-write is_symlink() check is TOCTOU-racy; tempfile + os.replace swaps
253
+ whatever is at dest (a symlink included) instead of following it.
254
+ """
255
+ import tempfile
256
+
257
+ dest.parent.mkdir(parents=True, exist_ok=True)
258
+ fd, tmp_name = tempfile.mkstemp(prefix=f".{dest.name}.", dir=str(dest.parent))
259
+ try:
260
+ with os.fdopen(fd, "wb") as out, open(src, "rb") as inp:
261
+ shutil.copyfileobj(inp, out)
262
+ os.chmod(tmp_name, 0o644)
263
+ os.replace(tmp_name, dest)
264
+ except BaseException:
265
+ try:
266
+ os.unlink(tmp_name)
267
+ except OSError:
268
+ pass
269
+ raise
270
+
271
+
272
+ def install(*, dry_run: bool = False, home: Path = None) -> dict:
273
+ """Install the adapter. Returns a summary dict of actions taken."""
274
+ # Windows refusal (deferred quoting: cmd.exe would not parse shlex.quote).
275
+ if os.name == "nt":
276
+ raise RuntimeError(
277
+ "Cursor install on native Windows is not supported yet: the persisted "
278
+ "hook command is POSIX-shell quoted and cmd.exe would not parse it. "
279
+ "Install from a POSIX shell or WSL."
280
+ )
281
+
282
+ root = home if home is not None else cursor_home()
283
+ actions = {"copied": [], "hook_file": None, "skipped": [], "dry_run": dry_run}
284
+ plugin_dir = _plugin_dir(root)
285
+
286
+ for name in _PAYLOAD_MODULES:
287
+ src = _SCRIPT_DIR / name
288
+ if not src.exists():
289
+ actions["skipped"].append(name)
290
+ continue
291
+ dest = plugin_dir / name
292
+ if not dry_run:
293
+ try:
294
+ _copy_no_follow(src, dest)
295
+ except OSError as exc:
296
+ # A partial payload would silently break the bridge; abort BEFORE
297
+ # touching hooks.json.
298
+ raise RuntimeError(f"failed copying {name}: {exc}") from exc
299
+ actions["copied"].append(name)
300
+
301
+ if actions["skipped"]:
302
+ raise RuntimeError(
303
+ "missing payload modules in this checkout: "
304
+ f"{actions['skipped']} — refusing to wire hooks against an incomplete bridge."
305
+ )
306
+
307
+ # Write the measure.py locator so the bridge's detached rollup/dashboard
308
+ # spawns resolve the canonical measure.py (measure.py is never copied into
309
+ # the plugin dir — version-drift risk). Only written when measure.py exists
310
+ # next to the installer; the bridge degrades to "rollups paused" otherwise.
311
+ measure_py = _SCRIPT_DIR / "measure.py"
312
+ if measure_py.is_file():
313
+ locator = plugin_dir / _MEASURE_LOCATOR_NAME
314
+ if not dry_run:
315
+ try:
316
+ tmp = locator.with_name(f".{locator.name}.tmp")
317
+ tmp.write_text(f"{measure_py}\n", encoding="utf-8")
318
+ os.replace(tmp, locator) # swaps a symlink, never follows it
319
+ except OSError as exc:
320
+ raise RuntimeError(f"failed writing measure-path locator: {exc}") from exc
321
+ actions["measure_locator"] = str(measure_py)
322
+
323
+ bridge_path = plugin_dir / "cursor_hook_bridge.py"
324
+ hooks_path = _host_hooks_path(root)
325
+ with _hooks_lock(hooks_path):
326
+ existing = _read_hooks(hooks_path)
327
+ hooks = existing.get("hooks")
328
+ if not isinstance(hooks, dict):
329
+ hooks = {}
330
+ for event, new_entries in _hook_entries(bridge_path).items():
331
+ old = hooks.get(event, [])
332
+ if not isinstance(old, list):
333
+ old = []
334
+ hooks[event] = [e for e in old if not _is_ours(e, bridge_path)] + new_entries
335
+ existing["hooks"] = hooks
336
+ existing.setdefault("version", 1)
337
+
338
+ if not dry_run:
339
+ try:
340
+ _write_hooks(hooks_path, existing)
341
+ except OSError as exc:
342
+ raise RuntimeError(f"failed writing {hooks_path}: {exc}") from exc
343
+ actions["hook_file"] = str(hooks_path)
344
+ return actions
345
+
346
+
347
+ def uninstall(*, dry_run: bool = False, home: Path = None) -> dict:
348
+ """Remove only entries install() added, plus the payload dir.
349
+
350
+ Session data (``<cursor_home>/token-optimizer/sessions``,
351
+ ``restore-context``, ``observed-events.jsonl``) and trends are left in place
352
+ for the user to purge manually, matching the Copilot uninstall contract.
353
+ """
354
+ root = home if home is not None else cursor_home()
355
+ actions = {"removed": [], "dry_run": dry_run}
356
+
357
+ bridge_path = _plugin_dir(root) / "cursor_hook_bridge.py"
358
+ hooks_path = _host_hooks_path(root)
359
+ with _hooks_lock(hooks_path):
360
+ existing = _read_hooks(hooks_path)
361
+ hooks = existing.get("hooks")
362
+ if isinstance(hooks, dict):
363
+ changed = False
364
+ pruned = {}
365
+ for event, entries in hooks.items():
366
+ if not isinstance(entries, list):
367
+ pruned[event] = entries
368
+ continue
369
+ kept = [e for e in entries if not _is_ours(e, bridge_path)]
370
+ if len(kept) != len(entries):
371
+ changed = True
372
+ pruned[event] = kept
373
+ if changed:
374
+ existing["hooks"] = pruned
375
+ if not dry_run:
376
+ try:
377
+ _write_hooks(hooks_path, existing)
378
+ except OSError as exc:
379
+ raise RuntimeError(f"failed writing {hooks_path}: {exc}") from exc
380
+ actions["removed"].append(f"{hooks_path} (Cursor entries)")
381
+
382
+ plugin_dir = _plugin_dir(root)
383
+ if plugin_dir.exists():
384
+ if not dry_run:
385
+ try:
386
+ shutil.rmtree(plugin_dir)
387
+ except OSError as exc:
388
+ # main() only surfaces RuntimeError; a raw OSError would escape
389
+ # as a traceback and leave a half-uninstalled state unexplained.
390
+ raise RuntimeError(f"failed removing {plugin_dir}: {exc}") from exc
391
+ actions["removed"].append(str(plugin_dir))
392
+
393
+ return actions
394
+
395
+
396
+ def build_parser() -> argparse.ArgumentParser:
397
+ parser = argparse.ArgumentParser(description=__doc__)
398
+ parser.add_argument("action", choices=("install", "uninstall"))
399
+ parser.add_argument("--dry-run", action="store_true")
400
+ return parser
401
+
402
+
403
+ def main(argv=None) -> int:
404
+ args = build_parser().parse_args(argv)
405
+ try:
406
+ if args.action == "install":
407
+ result = install(dry_run=args.dry_run)
408
+ verb = "Would install" if args.dry_run else "Installed"
409
+ print(f"{verb} Token Optimizer for Cursor.")
410
+ print(f" Hooks merged into: {result['hook_file']}")
411
+ print(f" Modules: {len(result['copied'])} copied"
412
+ + (f", {len(result['skipped'])} missing: {result['skipped']}" if result["skipped"] else ""))
413
+ print(_hint(" Run `python3 measure.py cursor-doctor` to verify readiness."))
414
+ else:
415
+ result = uninstall(dry_run=args.dry_run)
416
+ verb = "Would remove" if args.dry_run else "Removed"
417
+ for item in result["removed"] or ["(nothing installed)"]:
418
+ print(f"{verb}: {item}")
419
+ return 0
420
+ except RuntimeError as exc:
421
+ print(f"[Token Optimizer] {exc}", file=sys.stderr)
422
+ return 1
423
+
424
+
425
+ if __name__ == "__main__":
426
+ sys.exit(main())