@alexgreensh/token-optimizer 5.13.68 → 5.13.70

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 (182) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -45,10 +45,18 @@ HOOK_TIMEOUT_SEC = 10
45
45
  # hook never depends on the repo checkout location.
46
46
  _PAYLOAD_MODULES = (
47
47
  "cursor_hook_bridge.py",
48
+ "cursor_read_cache.py",
49
+ "structure_map.py",
50
+ "structure_map_ts.py",
51
+ "read_cache.py",
48
52
  "cursor_state.py",
49
53
  "cursor_session.py",
54
+ "cursor_quality.py",
50
55
  "bash_hook.py",
51
56
  "bash_compress.py",
57
+ "post_run_classify.py",
58
+ "preserved_reinject.py",
59
+ "bash_search_results.py",
52
60
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
53
61
  "bash_whitelist.py",
54
62
  # command_filters + _tomli: user [filters.*] TOML config consulted by
@@ -75,6 +83,44 @@ _PAYLOAD_MODULES = (
75
83
  # credential_patterns: bash_compress's credential-preservation patterns
76
84
  # (the inline fallback misses e.g. ghp_/github_pat_ tokens, #171).
77
85
  "credential_patterns.py",
86
+ # credential_url_patterns: credential_patterns imports it at module import
87
+ # time (URL pattern family split under the 1,000-line ratchet) — without it
88
+ # EVERY payload consumer of credential_patterns breaks at import.
89
+ "credential_url_patterns.py",
90
+ # cursor_bridge_*: cursor_hook_bridge's helper modules (payload decode,
91
+ # rewrite staging, rollup spawn, checkpoint I/O) split under the ratchet.
92
+ # The bridge degrades to a no-op without them.
93
+ "cursor_bridge_payload.py",
94
+ "cursor_bridge_rewrite.py",
95
+ "cursor_bridge_rollup.py",
96
+ "cursor_bridge_checkpoint.py",
97
+ # cursor_thrash powers the Shell thrash nudge in postToolUse; its runtime
98
+ # dependency closure (empirically traced over the identical-output, burn
99
+ # and inline-script nudge paths) is thrash_guard -> session_store,
100
+ # delta_diff, archive_result -> recovery_output, refetch_fingerprint,
101
+ # reset_epoch, token_estimate. Without ANY of these the nudge silently
102
+ # no-ops in a real install (fail-open). cursor_transcript powers the
103
+ # transcript translation in the compact-checkpoint capture.
104
+ "cursor_thrash.py",
105
+ "thrash_guard.py",
106
+ "session_store.py",
107
+ "session_store_guard.py",
108
+ "hint_paths.py", # session_store imports it at module load
109
+ "delta_diff.py",
110
+ "archive_result.py",
111
+ "recovery_output.py",
112
+ "refetch_fingerprint.py",
113
+ "reset_epoch.py",
114
+ "token_estimate.py",
115
+ # session_store queues contended writes through the spool and publishes
116
+ # reset markers; both live in the _measure package.
117
+ "_measure/__init__.py",
118
+ "_measure/session_store_spool.py",
119
+ "_measure/lease_candidate_cleanup.py",
120
+ "_measure/context_reset_marker.py",
121
+ "hook_provenance.py",
122
+ "shipped_hook_templates.py", # hook_provenance imports it at module load
123
+ "cursor_transcript.py",
78
124
  )
79
125
 
80
126
  # One-line locator written next to the bridge, naming the canonical measure.py
@@ -168,13 +214,21 @@ def _hook_entries(bridge_path: Path) -> dict:
168
214
 
169
215
  return {
170
216
  "sessionStart": [entry("sessionStart")],
171
- # Only the Shell tool is rewritten; matcher keeps every other tool out
172
- # of the bridge's hot path (Cursor matchers are JS regex over tool name).
173
- "preToolUse": [entry("preToolUse", matcher="Shell")],
217
+ # Shell is rewritten; Read is intercepted by the U2 read cache
218
+ # (shadow by default, emitting nothing until explicitly armed).
219
+ # The matcher keeps every other tool out of the bridge's hot path
220
+ # (Cursor matchers are JS regex over tool name).
221
+ "preToolUse": [entry("preToolUse", matcher="Shell|Read")],
174
222
  "postToolUse": [entry("postToolUse")],
175
223
  "preCompact": [entry("preCompact")],
176
224
  "stop": [entry("stop")],
177
225
  "sessionEnd": [entry("sessionEnd")],
226
+ # U4 record-only events: accounting, failure/burn signals, corroboration.
227
+ "afterAgentResponse": [entry("afterAgentResponse")],
228
+ "postToolUseFailure": [entry("postToolUseFailure")],
229
+ "afterShellExecution": [entry("afterShellExecution")],
230
+ "subagentStart": [entry("subagentStart")],
231
+ "subagentStop": [entry("subagentStop")],
178
232
  }
179
233
 
180
234
 
@@ -242,7 +296,10 @@ def _hooks_lock(hooks_path: Path):
242
296
  # 120s lease: the critical section copies the payload and rewrites
243
297
  # hooks.json; a 30s lease could lapse mid-RMW on a slow disk and let a
244
298
  # concurrent installer reclaim it, reintroducing the clobber.
245
- with lease_lock(lock_path, acquire_timeout=5.0, lease_seconds=120.0) as acquired:
299
+ # reclaim_released: a cleanly FINISHED install (release marker written)
300
+ # must not block a fast re-run (git pull + reinstall) for the rest of the
301
+ # lease window; a crashed install's tombstone still holds until expiry.
302
+ with lease_lock(lock_path, acquire_timeout=5.0, lease_seconds=120.0, reclaim_released=True) as acquired:
246
303
  if not acquired:
247
304
  raise RuntimeError(
248
305
  "another Cursor install/uninstall is in progress "
@@ -274,9 +331,28 @@ def _copy_no_follow(src: Path, dest: Path) -> None:
274
331
  raise
275
332
 
276
333
 
334
+ def _resolved_root(home):
335
+ if home is None:
336
+ return cursor_home()
337
+ raw = str(home)
338
+ if not raw or raw.startswith("-"):
339
+ raise ValueError("--home requires a directory path")
340
+ path = home.expanduser() if isinstance(home, Path) else Path(raw).expanduser()
341
+ if path.is_symlink():
342
+ raise ValueError("--home must not be a symlink")
343
+ root = path.resolve()
344
+ try:
345
+ different = root != cursor_home().resolve()
346
+ except (OSError, ValueError, NotImplementedError):
347
+ different = True
348
+ if different:
349
+ print("Warning: set TOKEN_OPTIMIZER_CURSOR_HOME to this home for Cursor hooks and doctor.", file=sys.stderr)
350
+ return root
351
+
352
+
277
353
  def install(*, dry_run: bool = False, home: Path = None) -> dict:
278
354
  """Install the adapter. Returns a summary dict of actions taken."""
279
- root = home if home is not None else cursor_home()
355
+ root = _resolved_root(home)
280
356
  actions = {"copied": [], "hook_file": None, "skipped": [], "dry_run": dry_run}
281
357
  plugin_dir = _plugin_dir(root)
282
358
 
@@ -322,12 +398,24 @@ def install(*, dry_run: bool = False, home: Path = None) -> dict:
322
398
  with _hooks_lock(hooks_path):
323
399
  existing = _read_hooks(hooks_path)
324
400
  hooks = existing.get("hooks")
325
- if not isinstance(hooks, dict):
401
+ if hooks is None:
326
402
  hooks = {}
403
+ elif not isinstance(hooks, dict):
404
+ # Fail closed like the non-object root: replacing a malformed
405
+ # member would silently destroy foreign configuration (G4).
406
+ raise RuntimeError(
407
+ f"{hooks_path} has a non-object 'hooks' member "
408
+ f"({type(hooks).__name__}); refusing to replace it. "
409
+ "Fix or remove the member and re-run."
410
+ )
327
411
  for event, new_entries in _hook_entries(bridge_path).items():
328
412
  old = hooks.get(event, [])
329
413
  if not isinstance(old, list):
330
- old = []
414
+ raise RuntimeError(
415
+ f"{hooks_path} event {event!r} is not a list "
416
+ f"({type(old).__name__}); refusing to replace it. "
417
+ "Fix or remove the entry and re-run."
418
+ )
331
419
  hooks[event] = [e for e in old if not _is_ours(e, bridge_path)] + new_entries
332
420
  existing["hooks"] = hooks
333
421
  existing.setdefault("version", 1)
@@ -342,13 +430,8 @@ def install(*, dry_run: bool = False, home: Path = None) -> dict:
342
430
 
343
431
 
344
432
  def uninstall(*, dry_run: bool = False, home: Path = None) -> dict:
345
- """Remove only entries install() added, plus the payload dir.
346
-
347
- Session data (``<cursor_home>/token-optimizer/sessions``,
348
- ``restore-context``, ``observed-events.jsonl``) and trends are left in place
349
- for the user to purge manually, matching the Copilot uninstall contract.
350
- """
351
- root = home if home is not None else cursor_home()
433
+ """Remove our hooks, payload and derived caches; retain session history."""
434
+ root = _resolved_root(home)
352
435
  actions = {"removed": [], "dry_run": dry_run}
353
436
 
354
437
  bridge_path = _plugin_dir(root) / "cursor_hook_bridge.py"
@@ -376,17 +459,27 @@ def uninstall(*, dry_run: bool = False, home: Path = None) -> dict:
376
459
  raise RuntimeError(f"failed writing {hooks_path}: {exc}") from exc
377
460
  actions["removed"].append(f"{hooks_path} (Cursor entries)")
378
461
 
379
- plugin_dir = _plugin_dir(root)
380
- if plugin_dir.exists():
462
+ data_dir = root / "token-optimizer"
463
+ if data_dir.is_symlink() or (data_dir / "snapshot").is_symlink():
464
+ raise RuntimeError("refusing to remove caches through a symlinked data directory")
465
+ for plugin_dir in (_plugin_dir(root), data_dir / "read-fingerprints",
466
+ data_dir / "checkpoints", data_dir / "restore-context",
467
+ data_dir / "snapshot" / "checkpoints"):
468
+ if not plugin_dir.exists() and not plugin_dir.is_symlink():
469
+ continue
381
470
  if not dry_run:
382
471
  try:
383
- shutil.rmtree(plugin_dir)
472
+ if plugin_dir.is_symlink():
473
+ plugin_dir.unlink()
474
+ else:
475
+ shutil.rmtree(plugin_dir)
384
476
  except OSError as exc:
385
477
  # main() only surfaces RuntimeError; a raw OSError would escape
386
478
  # as a traceback and leave a half-uninstalled state unexplained.
387
479
  raise RuntimeError(f"failed removing {plugin_dir}: {exc}") from exc
388
480
  actions["removed"].append(str(plugin_dir))
389
481
 
482
+ actions["kept"] = ["session tallies, observed events, trends and other session data"]
390
483
  return actions
391
484
 
392
485
 
@@ -394,6 +487,10 @@ def build_parser() -> argparse.ArgumentParser:
394
487
  parser = argparse.ArgumentParser(description=__doc__)
395
488
  parser.add_argument("action", choices=("install", "uninstall"))
396
489
  parser.add_argument("--dry-run", action="store_true")
490
+ # --home overrides the resolved Cursor home (install.sh forwards the
491
+ # WSL-aware resolved path so the install and its banner agree, mirroring
492
+ # grok_install --home / copilot_install --home).
493
+ parser.add_argument("--home", type=Path, default=None)
397
494
  return parser
398
495
 
399
496
 
@@ -401,7 +498,7 @@ def main(argv=None) -> int:
401
498
  args = build_parser().parse_args(argv)
402
499
  try:
403
500
  if args.action == "install":
404
- result = install(dry_run=args.dry_run)
501
+ result = install(dry_run=args.dry_run, home=args.home)
405
502
  verb = "Would install" if args.dry_run else "Installed"
406
503
  print(f"{verb} Token Optimizer for Cursor.")
407
504
  print(f" Hooks merged into: {result['hook_file']}")
@@ -409,10 +506,12 @@ def main(argv=None) -> int:
409
506
  + (f", {len(result['skipped'])} missing: {result['skipped']}" if result["skipped"] else ""))
410
507
  print(_hint(" Run `python3 measure.py cursor-doctor` to verify readiness."))
411
508
  else:
412
- result = uninstall(dry_run=args.dry_run)
509
+ result = uninstall(dry_run=args.dry_run, home=args.home)
413
510
  verb = "Would remove" if args.dry_run else "Removed"
414
511
  for item in result["removed"] or ["(nothing installed)"]:
415
512
  print(f"{verb}: {item}")
513
+ for item in result["kept"]:
514
+ print(f"Kept: {item}")
416
515
  return 0
417
516
  except RuntimeError as exc:
418
517
  print(f"[Token Optimizer] {exc}", file=sys.stderr)