@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,952 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer — self-heal reconcile for dev-symlink / plugin-cache shadow.
3
+
4
+ Detects when ``~/.claude/skills/token-optimizer`` is a symlink to a dev repo
5
+ AND a version-pinned plugin cache copy exists under
6
+ ``~/.claude/plugins/cache/*/token-optimizer/<version>/`` (read from
7
+ ``installed_plugins.json``), or when the loaded skill version mismatches the
8
+ pinned plugin cache version. When the canonical target is UNAMBIGUOUS (the dev
9
+ symlink is at a NEWER VERSION than the pinned cache), it auto-reconciles to
10
+ a single canonical skill, non-destructively: the displaced/stale copy is backed
11
+ up under ``<claude_home>/_backups/token-optimizer/<timestamp>/`` BEFORE anything
12
+ is moved, then the stale skill tree is removed so only the canonical skill
13
+ loads. When AMBIGUOUS, it warns loudly and does NOT act.
14
+
15
+ Safety contract:
16
+ - NEVER delete without a backup first. If the backup dir is unwritable, abort
17
+ the reconcile and warn, leaving state untouched.
18
+ - No-op for normal single-install users (plugin cache only, no symlink).
19
+ - No-op when running under a foreign runtime (detect_runtime() != "claude") so
20
+ OpenCode/Copilot sessions never touch ~/.claude.
21
+ - Safe to call from the SessionStart ensure-health path: cheap, idempotent,
22
+ never raises into the caller (errors are returned in the result dict).
23
+
24
+ The reconcile target is the SKILL tree only (``skills/token-optimizer/``
25
+ inside a cache version dir). The plugin's hooks/commands/etc. in the cache
26
+ version dir are preserved so the plugin keeps functioning; only the duplicate
27
+ skill is de-duplicated in favor of the canonical dev symlink. The cache skill
28
+ tree returns on the next plugin update (at which point versions match or the
29
+ user re-runs reconcile).
30
+
31
+ Usage:
32
+ python3 install_reconcile.py [--dry-run]
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import datetime as _dt
39
+ import json
40
+ import os
41
+ import shutil
42
+ import sys
43
+ from pathlib import Path
44
+
45
+ _SCRIPT_DIR = Path(__file__).resolve().parent
46
+ sys.path.insert(0, str(_SCRIPT_DIR))
47
+
48
+ from runtime_env import claude_home, detect_runtime # noqa: E402
49
+
50
+ _PLUGIN_NAME = "token-optimizer"
51
+ _SKILL_DIR_NAME = "token-optimizer"
52
+ _BACKUP_ROOT_NAME = "_backups"
53
+ _MANIFEST_NAME = "installed_plugins.json"
54
+ _PLUGIN_JSON_NAME = "plugin.json"
55
+ # Bound JSON reads so a pathological file never chews the SessionStart budget.
56
+ _MAX_MANIFEST_BYTES = 1_048_576
57
+
58
+
59
+ def _timestamp() -> str:
60
+ return _dt.datetime.now().strftime("%Y%m%d-%H%M%S-%f")
61
+
62
+
63
+ def _parse_version(text: str) -> tuple[int, ...]:
64
+ """Parse a dotted version string into a comparable tuple.
65
+
66
+ Non-numeric segments are dropped; ``"unknown"`` / empty -> ``(0,)`` so any
67
+ real version sorts above it. Never raises.
68
+ """
69
+ if not text:
70
+ return (0,)
71
+ parts: list[int] = []
72
+ for chunk in str(text).strip().split("."):
73
+ digits = "".join(ch for ch in chunk if ch.isdigit())
74
+ parts.append(int(digits) if digits else 0)
75
+ return tuple(parts) or (0,)
76
+
77
+
78
+ def _read_plugin_version(skill_dir: Path) -> str | None:
79
+ """Return the ``version`` field from ``<skill_dir>/../../plugin.json``.
80
+
81
+ A cache version dir layout is ``<cache>/<mkt>/token-optimizer/<ver>/`` with
82
+ ``plugin.json`` at the version-dir root and the skill at
83
+ ``<ver>/skills/token-optimizer/``. A dev repo layout has ``plugin.json`` at
84
+ the repo root and the skill at ``<repo>/skills/token-optimizer/``. We probe
85
+ a few candidate parents so both resolve. Never raises.
86
+ """
87
+ candidates: list[Path] = []
88
+ # Cache version dir: skill_dir = <ver>/skills/token-optimizer -> plugin.json
89
+ # at <ver>/plugin.json (2 parents up).
90
+ if skill_dir.parent.name == "skills":
91
+ candidates.append(skill_dir.parent.parent / _PLUGIN_JSON_NAME)
92
+ # Dev repo: skill_dir = <repo>/skills/token-optimizer -> plugin.json at
93
+ # <repo>/plugin.json (3 parents up).
94
+ candidates.append(skill_dir.parent.parent.parent / _PLUGIN_JSON_NAME)
95
+ # Also try a plugin.json directly inside the skill dir (defensive).
96
+ candidates.append(skill_dir / _PLUGIN_JSON_NAME)
97
+ for cand in candidates:
98
+ try:
99
+ if cand.is_file() and cand.stat().st_size <= _MAX_MANIFEST_BYTES:
100
+ with cand.open("r", encoding="utf-8") as fh:
101
+ data = json.load(fh)
102
+ if isinstance(data, dict) and isinstance(data.get("version"), str):
103
+ return data["version"]
104
+ except (OSError, ValueError, json.JSONDecodeError):
105
+ continue
106
+ return None
107
+
108
+
109
+ def _load_installed_plugins(claude_home_dir: Path) -> dict:
110
+ """Return the parsed installed_plugins.json, or {} on any failure."""
111
+ manifest = claude_home_dir / "plugins" / _MANIFEST_NAME
112
+ try:
113
+ if not manifest.is_file() or manifest.stat().st_size > _MAX_MANIFEST_BYTES:
114
+ return {}
115
+ with manifest.open("r", encoding="utf-8") as fh:
116
+ data = json.load(fh)
117
+ if isinstance(data, dict):
118
+ return data
119
+ except (OSError, ValueError, json.JSONDecodeError):
120
+ pass
121
+ return {}
122
+
123
+
124
+ def _active_cache_entries(claude_home_dir: Path) -> list[dict]:
125
+ """Return active token-optimizer cache entries from installed_plugins.json.
126
+
127
+ Each entry: {"marketplace": str, "version": str, "install_path": Path,
128
+ "skill_dir": Path}.
129
+ """
130
+ registry = _load_installed_plugins(claude_home_dir)
131
+ plugins = registry.get("plugins", {})
132
+ if not isinstance(plugins, dict):
133
+ return []
134
+ entries: list[dict] = []
135
+ for key, installs in plugins.items():
136
+ if not isinstance(key, str) or not key.startswith(_PLUGIN_NAME + "@"):
137
+ continue
138
+ marketplace = key.split("@", 1)[1]
139
+ if not isinstance(installs, list):
140
+ continue
141
+ for inst in installs:
142
+ if not isinstance(inst, dict):
143
+ continue
144
+ raw = inst.get("installPath", "")
145
+ version = inst.get("version", "")
146
+ if not raw:
147
+ continue
148
+ install_path = Path(raw)
149
+ skill_dir = install_path / "skills" / _SKILL_DIR_NAME
150
+ entries.append({
151
+ "marketplace": marketplace,
152
+ "version": str(version) if version else "",
153
+ "install_path": install_path,
154
+ "skill_dir": skill_dir,
155
+ })
156
+ return entries
157
+
158
+
159
+ def _all_cache_skill_dirs(claude_home_dir: Path) -> list[Path]:
160
+ """Glob every token-optimizer skill dir under the plugin cache tree."""
161
+ cache_root = claude_home_dir / "plugins" / "cache"
162
+ found: list[Path] = []
163
+ try:
164
+ if not cache_root.is_dir():
165
+ return found
166
+ for mkt in sorted(cache_root.iterdir()):
167
+ if not mkt.is_dir():
168
+ continue
169
+ plugin_dir = mkt / _PLUGIN_NAME
170
+ if not plugin_dir.is_dir():
171
+ continue
172
+ for ver in sorted(plugin_dir.iterdir()):
173
+ if not ver.is_dir():
174
+ continue
175
+ skill_dir = ver / "skills" / _SKILL_DIR_NAME
176
+ if skill_dir.is_dir():
177
+ found.append(skill_dir)
178
+ except OSError:
179
+ pass
180
+ return found
181
+
182
+
183
+ def _backup_dir_writable(backup_root: Path) -> bool:
184
+ """True if we can create+write a fresh subdir under backup_root.
185
+
186
+ Probes without persisting an empty dir: if backup_root did not exist before
187
+ the probe, it is removed again afterward, so an aborted/dry-run reconcile
188
+ leaves ~/.claude genuinely untouched (the real reconcile re-creates it via
189
+ backup_dest.mkdir when it actually needs it).
190
+ """
191
+ existed = backup_root.exists()
192
+ try:
193
+ backup_root.mkdir(parents=True, exist_ok=True)
194
+ probe = backup_root / (".write-probe-" + _timestamp())
195
+ probe.write_text("probe", encoding="utf-8")
196
+ probe.unlink()
197
+ return True
198
+ except OSError:
199
+ return False
200
+ finally:
201
+ if not existed:
202
+ try:
203
+ backup_root.rmdir() # only succeeds if still empty
204
+ except OSError:
205
+ pass
206
+
207
+
208
+ def _is_confined_to_cache(target: Path, home: Path) -> bool:
209
+ """True only if `target` is a real path under <home>/plugins/cache with NO
210
+ symlinked component along the way.
211
+
212
+ Guards ``shutil.rmtree`` against an intermediate symlinked path component
213
+ (or a crafted ``installPath`` in installed_plugins.json) redirecting a
214
+ delete outside the plugin cache tree. Resolving
215
+ both paths catches symlink escapes (a symlinked component would resolve
216
+ outside the cache root); the per-component check additionally refuses to
217
+ rmtree *through* any symlink even when it resolves back inside the cache.
218
+ """
219
+ cache_root = home / "plugins" / "cache"
220
+ try:
221
+ cache_root_resolved = cache_root.resolve(strict=True)
222
+ target_resolved = target.resolve(strict=True)
223
+ except (OSError, RuntimeError):
224
+ return False
225
+ if not target_resolved.is_relative_to(cache_root_resolved):
226
+ return False
227
+ probe = cache_root
228
+ if probe.is_symlink():
229
+ return False
230
+ try:
231
+ rel_parts = target.relative_to(cache_root).parts
232
+ except ValueError:
233
+ return False
234
+ for part in rel_parts:
235
+ probe = probe / part
236
+ if probe.is_symlink():
237
+ return False
238
+ return True
239
+
240
+
241
+ def _backup_tree(src: Path, backup_dest_parent: Path) -> Path | None:
242
+ """Copy ``src`` tree into ``backup_dest_parent/<src-name>``. Returns dest or None.
243
+
244
+ ``symlinks=True`` preserves any symlinks inside the tree as links rather
245
+ than dereferencing them (so a link to a large/external target is backed up
246
+ as a link, not a deep copy of someone else's data).
247
+ """
248
+ try:
249
+ dest = backup_dest_parent / src.name
250
+ # If a same-named backup already exists (rare), suffix to avoid clobber.
251
+ i = 1
252
+ while dest.exists():
253
+ dest = backup_dest_parent / f"{src.name}-{i}"
254
+ i += 1
255
+ shutil.copytree(src, dest, symlinks=True)
256
+ return dest
257
+ except OSError:
258
+ return None
259
+
260
+
261
+ def detect_and_reconcile(
262
+ *,
263
+ dry_run: bool = False,
264
+ claude_home_override: Path | None = None,
265
+ ) -> dict:
266
+ """Detect a dev-symlink / plugin-cache skill shadow and reconcile if safe.
267
+
268
+ Returns a result dict:
269
+ {
270
+ "action": "no-op" | "reconciled" | "warn" | "aborted",
271
+ "reason": str,
272
+ "dry_run": bool,
273
+ "runtime": str,
274
+ "symlink": str | None, # path the symlink points at, if any
275
+ "loaded_version": str | None,
276
+ "cache_entries": [...], # active entries from installed_plugins.json
277
+ "backup": str | None, # backup dir created, if any
278
+ "removed": [str, ...], # skill dirs removed (empty if none)
279
+ "canonical": str | None, # the canonical skill path left active
280
+ "warnings": [str, ...],
281
+ }
282
+
283
+ Never raises: all errors are captured into ``action``/``reason``/``warnings``.
284
+ """
285
+ runtime = detect_runtime()
286
+ result: dict = {
287
+ "action": "no-op",
288
+ "reason": "",
289
+ "dry_run": dry_run,
290
+ "runtime": runtime,
291
+ "symlink": None,
292
+ "loaded_version": None,
293
+ "cache_entries": [],
294
+ "backup": None,
295
+ "removed": [],
296
+ "canonical": None,
297
+ "warnings": [],
298
+ }
299
+
300
+ # Guard: foreign runtime must never touch ~/.claude.
301
+ if runtime != "claude":
302
+ result["reason"] = f"foreign runtime ({runtime}); not modifying ~/.claude"
303
+ return result
304
+
305
+ home = claude_home_override if claude_home_override is not None else claude_home()
306
+ skills_link = home / "skills" / _SKILL_DIR_NAME
307
+ backup_root = home / _BACKUP_ROOT_NAME / _PLUGIN_NAME
308
+
309
+ # Resolve the dev symlink (if any).
310
+ symlink_target: Path | None = None
311
+ is_symlink = False
312
+ try:
313
+ is_symlink = skills_link.is_symlink()
314
+ if is_symlink:
315
+ symlink_target = Path(os.readlink(skills_link))
316
+ if not symlink_target.is_absolute():
317
+ symlink_target = (skills_link.parent / symlink_target).resolve(strict=False)
318
+ result["symlink"] = str(symlink_target)
319
+ except OSError:
320
+ result["warnings"].append(f"could not read symlink at {skills_link}")
321
+
322
+ # Loaded skill version (from the symlink target's plugin.json, or the dir
323
+ # itself if it is a real directory).
324
+ loaded_version: str | None = None
325
+ try:
326
+ if is_symlink and symlink_target is not None:
327
+ loaded_version = _read_plugin_version(symlink_target)
328
+ elif skills_link.is_dir():
329
+ loaded_version = _read_plugin_version(skills_link)
330
+ except OSError:
331
+ pass
332
+ result["loaded_version"] = loaded_version
333
+
334
+ cache_entries = _active_cache_entries(home)
335
+ result["cache_entries"] = [
336
+ {
337
+ "marketplace": e["marketplace"],
338
+ "version": e["version"],
339
+ "install_path": str(e["install_path"]),
340
+ "skill_dir": str(e["skill_dir"]),
341
+ "skill_dir_exists": e["skill_dir"].is_dir(),
342
+ }
343
+ for e in cache_entries
344
+ ]
345
+
346
+ cache_skill_dirs_with_version: list[tuple[Path, str]] = []
347
+ for e in cache_entries:
348
+ if e["skill_dir"].is_dir():
349
+ ver = e["version"] or _read_plugin_version(e["skill_dir"]) or ""
350
+ cache_skill_dirs_with_version.append((e["skill_dir"], ver))
351
+
352
+ # Also discover cache skill dirs NOT in installed_plugins.json (orphan
353
+ # caches) so the ambiguous-two-caches case is detectable.
354
+ active_skill_dir_paths = {e["skill_dir"] for e in cache_entries}
355
+ for sd in _all_cache_skill_dirs(home):
356
+ if sd not in active_skill_dir_paths:
357
+ ver = _read_plugin_version(sd) or ""
358
+ cache_skill_dirs_with_version.append((sd, ver))
359
+
360
+ # --- Classification ---
361
+ # Case: normal single-install user — plugin cache only, no symlink.
362
+ if not is_symlink:
363
+ if len(cache_skill_dirs_with_version) <= 1:
364
+ result["reason"] = "no dev symlink and <=1 cache skill; nothing to reconcile"
365
+ return result
366
+ # Two+ cache skill dirs, no symlink, differing versions -> AMBIGUOUS.
367
+ versions = {v for _, v in cache_skill_dirs_with_version if v}
368
+ if len(versions) > 1:
369
+ result["action"] = "warn"
370
+ result["reason"] = "ambiguous: multiple plugin cache skill copies with differing versions and no dev symlink to disambiguate"
371
+ conflict_desc = ", ".join(
372
+ f"{sd.parent.parent.name}={v or 'unknown'}" for sd, v in sorted(cache_skill_dirs_with_version)
373
+ )
374
+ msg = (
375
+ f"[Token Optimizer] CONFLICT: multiple token-optimizer skill copies in "
376
+ f"{home / 'plugins' / 'cache'} ({conflict_desc}). "
377
+ f"Manual reconcile: review {home / 'plugins' / 'installed_plugins.json'} "
378
+ f"and remove the stale cache version dir(s) you do not want."
379
+ )
380
+ result["warnings"].append(msg)
381
+ print(msg, file=sys.stderr)
382
+ return result
383
+ # Two+ caches but same version -> not a real conflict, no-op.
384
+ result["reason"] = "multiple cache skill copies but same version; no reconcile needed"
385
+ return result
386
+
387
+ # --- A dev symlink exists ---
388
+ if not cache_skill_dirs_with_version:
389
+ # Symlink present, no cache skill -> already canonical, nothing to do.
390
+ result["reason"] = "dev symlink present and no plugin cache skill to reconcile"
391
+ result["canonical"] = str(skills_link)
392
+ return result
393
+
394
+ # Compare loaded (symlink) version vs each cache version.
395
+ loaded_ver_tuple = _parse_version(loaded_version or "")
396
+ # Find cache skill dirs whose version differs from the loaded one.
397
+ stale_caches: list[tuple[Path, str]] = []
398
+ for sd, v in cache_skill_dirs_with_version:
399
+ if _parse_version(v) == loaded_ver_tuple and loaded_ver_tuple != (0,):
400
+ # Same version as the loaded skill -> not stale, leave it.
401
+ continue
402
+ elif _parse_version(v) < loaded_ver_tuple:
403
+ stale_caches.append((sd, v))
404
+ else:
405
+ # Cache is NEWER than the symlink, or versions incomparable.
406
+ # Removing a dev symlink the user placed intentionally is destructive
407
+ # -> treat as ambiguous (warn), do not act.
408
+ pass
409
+
410
+ newer_than_symlink = [
411
+ (sd, v) for sd, v in cache_skill_dirs_with_version
412
+ if _parse_version(v) > loaded_ver_tuple
413
+ ]
414
+
415
+ if newer_than_symlink:
416
+ result["action"] = "warn"
417
+ conflict_desc = ", ".join(f"{sd.parent.parent.name}={v or 'unknown'}" for sd, v in newer_than_symlink)
418
+ msg = (
419
+ f"[Token Optimizer] CONFLICT: dev symlink {skills_link} -> "
420
+ f"{symlink_target} (version {loaded_version or 'unknown'}) is OLDER than "
421
+ f"plugin cache skill copy ({conflict_desc}). "
422
+ f"Manual reconcile: `git pull` in {symlink_target} to update the dev repo, "
423
+ f"or remove the symlink with `rm {skills_link}` to use the plugin cache."
424
+ )
425
+ result["reason"] = "ambiguous: dev symlink is older than the plugin cache"
426
+ result["warnings"].append(msg)
427
+ print(msg, file=sys.stderr)
428
+ return result
429
+
430
+ if not stale_caches:
431
+ # Symlink + cache at same version -> no-op (no false reconcile).
432
+ result["reason"] = "dev symlink and plugin cache skill at the same version; no reconcile needed"
433
+ result["canonical"] = str(skills_link)
434
+ return result
435
+
436
+ # --- UNAMBIGUOUS: symlink is newer than one or more stale caches. ---
437
+ # Reconcile: back up each stale cache skill tree, then remove it so only the
438
+ # dev symlink remains canonical. Never delete without a backup first.
439
+ if dry_run:
440
+ # Pre-flight the backup dir writability so the dry-run preview is honest.
441
+ writable = _backup_dir_writable(backup_root)
442
+ if not writable:
443
+ result["action"] = "aborted"
444
+ result["reason"] = f"backup dir {backup_root} is not writable; would abort reconcile"
445
+ msg = f"[Token Optimizer] ABORT: backup dir {backup_root} is not writable; cannot reconcile safely."
446
+ result["warnings"].append(msg)
447
+ print(msg, file=sys.stderr)
448
+ return result
449
+ stale_desc = ", ".join(f"{sd.parent.parent.name}={v or 'unknown'}" for sd, v in stale_caches)
450
+ result["action"] = "reconciled"
451
+ result["reason"] = f"dry-run: would back up and remove stale cache skill(s) ({stale_desc}); dev symlink stays canonical"
452
+ result["canonical"] = str(skills_link)
453
+ result["backup"] = str(backup_root / _timestamp())
454
+ return result
455
+
456
+ # Verify backup dir is writable BEFORE touching anything.
457
+ if not _backup_dir_writable(backup_root):
458
+ result["action"] = "aborted"
459
+ result["reason"] = f"backup dir {backup_root} is not writable; aborted before any change"
460
+ msg = (
461
+ f"[Token Optimizer] ABORT: backup dir {backup_root} is not writable. "
462
+ "Reconcile aborted; ~/.claude left untouched. Fix permissions and re-run."
463
+ )
464
+ result["warnings"].append(msg)
465
+ print(msg, file=sys.stderr)
466
+ return result
467
+
468
+ stamp = _timestamp()
469
+ backup_dest = backup_root / stamp
470
+ try:
471
+ backup_dest.mkdir(parents=True, exist_ok=False)
472
+ except OSError:
473
+ result["action"] = "aborted"
474
+ result["reason"] = f"could not create backup dir {backup_dest}"
475
+ msg = f"[Token Optimizer] ABORT: could not create backup dir {backup_dest}; ~/.claude left untouched."
476
+ result["warnings"].append(msg)
477
+ print(msg, file=sys.stderr)
478
+ return result
479
+
480
+ removed: list[str] = []
481
+ backups_made: list[str] = []
482
+ aborted = False
483
+ for sd, v in stale_caches:
484
+ # Confinement guard: never rmtree a target that resolves outside the
485
+ # plugin cache, or through a symlinked path component. Skip + warn
486
+ # rather than risk deleting outside ~/.claude/plugins/cache.
487
+ if not _is_confined_to_cache(sd, home):
488
+ msg = (
489
+ f"[Token Optimizer] SKIP: stale cache candidate {sd} is not safely "
490
+ "confined to the plugin cache (symlinked component or resolves "
491
+ "outside the cache tree). Not removed."
492
+ )
493
+ result["warnings"].append(msg)
494
+ print(msg, file=sys.stderr)
495
+ continue
496
+ # Back up FIRST.
497
+ backed = _backup_tree(sd, backup_dest)
498
+ if backed is None:
499
+ aborted = True
500
+ msg = (
501
+ f"[Token Optimizer] ABORT: failed to back up {sd} before removing it. "
502
+ "Reconcile aborted; the stale cache skill was NOT removed. "
503
+ f"Partial backups may exist under {backup_dest}."
504
+ )
505
+ result["warnings"].append(msg)
506
+ print(msg, file=sys.stderr)
507
+ break
508
+ backups_made.append(str(backed))
509
+ # Only now remove the stale skill tree.
510
+ try:
511
+ shutil.rmtree(sd)
512
+ removed.append(str(sd))
513
+ print(
514
+ f"[Token Optimizer] Reconciled: backed up stale cache skill {sd} "
515
+ f"(version {v or 'unknown'}) to {backed}, then removed it. "
516
+ f"Canonical skill: {skills_link} -> {symlink_target}."
517
+ )
518
+ except OSError as exc:
519
+ aborted = True
520
+ msg = (
521
+ f"[Token Optimizer] ABORT: backed up {sd} to {backed} but failed to remove it ({exc}). "
522
+ "Backup retained; reconcile incomplete. Re-run after resolving the error."
523
+ )
524
+ result["warnings"].append(msg)
525
+ print(msg, file=sys.stderr)
526
+ break
527
+
528
+ result["backup"] = str(backup_dest)
529
+ result["removed"] = removed # full list of removed cache skill dirs
530
+ result["canonical"] = str(skills_link)
531
+ if aborted:
532
+ result["action"] = "aborted"
533
+ result["reason"] = "reconcile aborted mid-way; backups retained"
534
+ elif removed:
535
+ result["action"] = "reconciled"
536
+ result["reason"] = (
537
+ f"backed up {len(backups_made)} stale cache skill(s) to {backup_dest} "
538
+ f"and removed them; dev symlink {skills_link} is the canonical skill"
539
+ )
540
+ else:
541
+ result["action"] = "no-op"
542
+ result["reason"] = "no stale cache skill was removed"
543
+ return result
544
+
545
+
546
+ def build_parser() -> argparse.ArgumentParser:
547
+ parser = argparse.ArgumentParser(
548
+ description="Detect and reconcile a dev-symlink / plugin-cache skill shadow.",
549
+ )
550
+ parser.add_argument(
551
+ "--dry-run",
552
+ action="store_true",
553
+ help="Report what would change without modifying anything.",
554
+ )
555
+ return parser
556
+
557
+
558
+ # ---------------------------------------------------------------------------
559
+ # Uninstall-direction manifest reconcile
560
+ # ---------------------------------------------------------------------------
561
+
562
+ _KNOWN_MARKETPLACES_NAME = "known_marketplaces.json"
563
+ # A marketplace entry is "ours" when its name OR installLocation references
564
+ # token-optimizer. Our marketplace names derive from the repo, so they always
565
+ # contain "token-optimizer"; matching the installLocation too catches a
566
+ # renamed entry that still points at our marketplace dir.
567
+ _TOKEN_MARKER = "token-optimizer"
568
+
569
+
570
+ def _is_our_marketplace(name: str, entry: object, our_marketplaces=None) -> bool:
571
+ """True only when we can EVIDENCE that ``name`` is our own marketplace.
572
+
573
+ The old rule was a bare substring test -- any marketplace
574
+ whose name merely contained "token-optimizer" was claimed as ours and
575
+ deleted. A user's own marketplace (a fork, a "my-token-optimizer-tweaks"
576
+ registry, a colleague's mirror) is not ours to remove, and
577
+ known_marketplaces.json is Claude Code's file, not ours.
578
+
579
+ Ownership now requires one of:
580
+ * ``our_marketplaces`` -- the marketplace suffixes taken from OUR OWN
581
+ installed_plugins keys (``token-optimizer@<marketplace>``), i.e. the
582
+ registry itself says we installed a plugin from it; or
583
+ * an ``installLocation`` whose final path component is a plugin-cache
584
+ dir for our plugin name (``.../<something>token-optimizer<something>``
585
+ is NOT enough -- the directory must actually be a marketplace dir we
586
+ installed into, matched on an exact path segment).
587
+
588
+ Anything else is reported (so the user can see it) but never removed.
589
+ """
590
+ if not isinstance(name, str):
591
+ return False
592
+ if our_marketplaces and name in our_marketplaces:
593
+ return True
594
+ if isinstance(entry, dict):
595
+ loc = entry.get("installLocation", "")
596
+ if isinstance(loc, str) and loc:
597
+ try:
598
+ segments = {seg.lower() for seg in Path(loc).parts}
599
+ except (OSError, ValueError):
600
+ segments = set()
601
+ # Exact path-segment match, not a substring of the whole path:
602
+ # ".../marketplaces/alexgreensh-token-optimizer" counts only when
603
+ # that segment is one WE are installed from (checked above), while
604
+ # a bare ".../token-optimizer" cache dir is ours by construction.
605
+ if _PLUGIN_NAME in segments:
606
+ return True
607
+ return False
608
+
609
+
610
+ def _our_marketplace_names(registry: dict) -> set:
611
+ """Marketplace suffixes from our own installed_plugins keys.
612
+
613
+ ``token-optimizer@alexgreensh-token-optimizer`` -> the marketplace name
614
+ after the ``@``. This is the registry's own statement that we installed a
615
+ plugin from that marketplace, which is the only self-evident proof of
616
+ ownership available.
617
+ """
618
+ names = set()
619
+ for key in _our_plugin_keys(registry):
620
+ _, _, suffix = key.partition("@")
621
+ if suffix:
622
+ names.add(suffix)
623
+ return names
624
+
625
+
626
+ def _load_known_marketplaces(claude_home_dir: Path) -> dict:
627
+ """Return the parsed known_marketplaces.json, or {} on any failure."""
628
+ path = claude_home_dir / "plugins" / _KNOWN_MARKETPLACES_NAME
629
+ try:
630
+ if not path.is_file() or path.stat().st_size > _MAX_MANIFEST_BYTES:
631
+ return {}
632
+ with path.open("r", encoding="utf-8") as fh:
633
+ data = json.load(fh)
634
+ if isinstance(data, dict):
635
+ return data
636
+ except (OSError, ValueError, json.JSONDecodeError):
637
+ pass
638
+ return {}
639
+
640
+
641
+ def _our_plugin_keys(registry: dict) -> list[str]:
642
+ """Return our ``token-optimizer@<marketplace>`` keys in installed_plugins."""
643
+ plugins = registry.get("plugins", {})
644
+ if not isinstance(plugins, dict):
645
+ return []
646
+ return sorted(
647
+ k for k in plugins
648
+ if isinstance(k, str) and k.startswith(_PLUGIN_NAME + "@")
649
+ )
650
+
651
+
652
+ def _entry_is_stale(install_path: str) -> bool:
653
+ """True iff the entry's installPath no longer exists on disk."""
654
+ if not install_path:
655
+ return True
656
+ try:
657
+ return not Path(install_path).is_dir()
658
+ except (OSError, ValueError):
659
+ return True
660
+
661
+
662
+ # Default dashboard daemon port (mirrors measure.DAEMON_PORT). Read from the
663
+ # env so tests can point the probe at a closed port without importing measure.
664
+ _DEFAULT_DAEMON_PORT = 24842
665
+
666
+
667
+ def _daemon_port() -> int:
668
+ """The dashboard daemon port, overridable via TOKEN_OPTIMIZER_DAEMON_PORT."""
669
+ try:
670
+ return int(os.environ.get("TOKEN_OPTIMIZER_DAEMON_PORT", _DEFAULT_DAEMON_PORT))
671
+ except (TypeError, ValueError):
672
+ return _DEFAULT_DAEMON_PORT
673
+
674
+
675
+ def _dashboard_daemon_alive(port: int | None = None, timeout: float = 1.0) -> bool:
676
+ """True iff OUR dashboard daemon is currently serving on the loopback port.
677
+
678
+ Self-contained liveness probe (no ``measure`` import -- that would be
679
+ circular: measure imports this module). Used by ``reconcile_uninstall`` to
680
+ protect a LIVE daemon's manifest entry from a stale-path misclassification
681
+ during a routine plugin update: when the marketplace cache path moves on
682
+ update, the active identity's ``installPath`` is momentarily gone, so the
683
+ bare "installPath missing -> stale" rule would drop the running daemon's
684
+ manifest entry and orphan it (a later sweep then tears down the plist). A
685
+ live daemon on the port disproves "stale", so the entry is kept.
686
+
687
+ Identity-checked: only trusts the response when ``server ==
688
+ "token-optimizer-daemon"`` (mirrors ``measure._verify_daemon_port``), so a
689
+ foreign listener on the port never fakes liveness. Fail-open: any error ->
690
+ False, so a probe failure falls back to the existing installPath rule and
691
+ can never block a legitimate stale removal -- and never raises.
692
+ """
693
+ if port is None:
694
+ port = _daemon_port()
695
+ try:
696
+ import urllib.request
697
+ with urllib.request.urlopen(
698
+ f"http://127.0.0.1:{port}/api/health", timeout=timeout
699
+ ) as resp:
700
+ body = resp.read(2048).decode("utf-8", "replace")
701
+ data = json.loads(body)
702
+ return isinstance(data, dict) and data.get("server") == "token-optimizer-daemon"
703
+ except Exception: # noqa: BLE001 -- probe must never raise
704
+ return False
705
+
706
+
707
+ def _atomic_write_json(path: Path, data) -> bool:
708
+ """Write JSON to ``path`` via a temp file + os.replace. Returns success."""
709
+ import tempfile
710
+ try:
711
+ path.parent.mkdir(parents=True, exist_ok=True)
712
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".tmp-", suffix=".json")
713
+ try:
714
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
715
+ json.dump(data, fh, indent=2, ensure_ascii=False)
716
+ fh.write("\n")
717
+ os.replace(tmp, str(path))
718
+ return True
719
+ finally:
720
+ if os.path.exists(tmp):
721
+ try:
722
+ os.unlink(tmp)
723
+ except OSError:
724
+ pass
725
+ except OSError:
726
+ return False
727
+
728
+
729
+ def _backup_file(src: Path, backup_dest_parent: Path) -> Path | None:
730
+ """Copy a single file into ``backup_dest_parent/<src.name>``. Returns dest or None."""
731
+ try:
732
+ dest = backup_dest_parent / src.name
733
+ i = 1
734
+ while dest.exists():
735
+ dest = backup_dest_parent / f"{src.name}-{i}"
736
+ i += 1
737
+ shutil.copy2(src, dest)
738
+ return dest
739
+ except OSError:
740
+ return None
741
+
742
+
743
+ def reconcile_uninstall(
744
+ claude_home_dir: Path,
745
+ *,
746
+ dry_run: bool = False,
747
+ remove: bool = False,
748
+ daemon_already_stopped: bool = False,
749
+ ) -> dict:
750
+ """Report (and optionally remove) our stale host-manifest entries.
751
+
752
+ Two Claude Code state files are reconciled on the UNINSTALL direction:
753
+
754
+ - ``installed_plugins.json``: our ``token-optimizer@*`` entries whose
755
+ ``installPath`` no longer exists (left dangling after
756
+ ``/plugin uninstall`` removed the cache dir but not the manifest key).
757
+ - ``known_marketplaces.json``: our marketplace entries (name or
758
+ installLocation references token-optimizer).
759
+
760
+ By default (``remove=False``) this only REPORTS what is stale. Under the
761
+ explicit cleanup command (``remove=True``) it writes a backup of each file
762
+ first, then removes our STALE entries, leaving other plugins' entries
763
+ byte-identical. Never raises; all errors land in ``warnings``.
764
+
765
+ When *daemon_already_stopped* is True (set by ``measure.cleanup()`` after
766
+ step 1 already stopped the daemon), the live-daemon probe is SKIPPED and
767
+ any key whose installPath is gone is classified as stale. This prevents a
768
+ false-alive probe (e.g. a real daemon on a different port responding to
769
+ the health check, or a port collision in a test) from blocking manifest
770
+ pruning during cleanup.
771
+
772
+ Returns a result dict with ``reported`` and ``removed`` lists plus
773
+ ``backup`` (the backup dir created, when any) and ``warnings``.
774
+ """
775
+ result: dict = {
776
+ "dry_run": dry_run,
777
+ "remove": remove,
778
+ "reported": [],
779
+ "removed": [],
780
+ "backup": None,
781
+ "warnings": [],
782
+ }
783
+ home = claude_home_dir
784
+ plugins_dir = home / "plugins"
785
+ installed_path = plugins_dir / _MANIFEST_NAME
786
+ marketplaces_path = plugins_dir / _KNOWN_MARKETPLACES_NAME
787
+
788
+ registry = _load_installed_plugins(home)
789
+ our_keys = _our_plugin_keys(registry)
790
+ # FIX-SPEC-DAEMON req 1: a LIVE dashboard daemon disproves "stale". During a
791
+ # routine plugin update the marketplace cache path can move, so the active
792
+ # identity's installPath is momentarily gone and the bare "installPath
793
+ # missing -> stale" rule would drop the running daemon's manifest entry
794
+ # (orphaning it -- a later sweep then tears down the plist). Probe the daemon
795
+ # once; if it is alive, no our-entry is classified stale, so a routine update
796
+ # never removes the active daemon's manifest entry. Fail-open: a probe error
797
+ # -> not alive (the installPath rule still removes genuinely-stale entries),
798
+ # and the call site below also guards so the protection can never raise.
799
+ daemon_alive = False
800
+ if our_keys and not daemon_already_stopped:
801
+ try:
802
+ daemon_alive = _dashboard_daemon_alive()
803
+ except Exception: # noqa: BLE001 -- protection must never raise
804
+ daemon_alive = False
805
+ stale_keys: list[str] = []
806
+ for key in our_keys:
807
+ installs = registry.get("plugins", {}).get(key, [])
808
+ if not isinstance(installs, list) or not installs:
809
+ # No install records -- stale unless a live daemon protects it.
810
+ if not daemon_alive:
811
+ stale_keys.append(key)
812
+ continue
813
+ # An entry is stale if ALL its install records point at gone paths.
814
+ all_gone = all(
815
+ _entry_is_stale(str(inst.get("installPath", "")))
816
+ for inst in installs if isinstance(inst, dict)
817
+ ) or not any(isinstance(inst, dict) for inst in installs)
818
+ # FIX-SPEC-DAEMON req 1: a live daemon protects the active identity
819
+ # from a stale-path misclassification during a plugin update (the
820
+ # marketplace cache path moved, so installPath is gone but the daemon
821
+ # is still serving). Classified active/kept, never removed by reconcile.
822
+ if all_gone and daemon_alive:
823
+ all_gone = False
824
+ if all_gone:
825
+ stale_keys.append(key)
826
+ result["reported"].append({
827
+ "file": str(installed_path),
828
+ "key": key,
829
+ "stale": all_gone,
830
+ "daemon_alive": daemon_alive,
831
+ "install_path": installs[0].get("installPath", "") if isinstance(installs[0], dict) else "",
832
+ })
833
+
834
+ marketplaces = _load_known_marketplaces(home)
835
+ # Ownership must be evidenced by our own installed_plugins
836
+ # keys (or an exact plugin-name path segment), never a bare name substring.
837
+ our_marketplace_names = _our_marketplace_names(registry)
838
+ our_mkt_keys = sorted(
839
+ k for k, v in marketplaces.items()
840
+ if _is_our_marketplace(k, v, our_marketplace_names)
841
+ )
842
+ for key in our_mkt_keys:
843
+ entry = marketplaces.get(key, {})
844
+ loc = entry.get("installLocation", "") if isinstance(entry, dict) else ""
845
+ stale = bool(loc) and not Path(loc).is_dir()
846
+ result["reported"].append({
847
+ "file": str(marketplaces_path),
848
+ "key": key,
849
+ "stale": stale,
850
+ "install_location": loc,
851
+ })
852
+
853
+ if not remove:
854
+ return result
855
+
856
+ # Removal path: back up both files first, then drop our STALE entries.
857
+ to_remove_installed = [k for k in stale_keys]
858
+ to_remove_marketplaces = [
859
+ k for k in our_mkt_keys
860
+ if (isinstance(marketplaces.get(k), dict)
861
+ and _entry_is_stale(str(marketplaces[k].get("installLocation", ""))))
862
+ ]
863
+ if not to_remove_installed and not to_remove_marketplaces:
864
+ return result
865
+
866
+ if dry_run:
867
+ # Dry-run + remove: disclose what WOULD be removed, touch nothing
868
+ # (no backup dir created, no files written).
869
+ for key in to_remove_installed:
870
+ result["removed"].append(f"{installed_path}::{key}")
871
+ for key in to_remove_marketplaces:
872
+ result["removed"].append(f"{marketplaces_path}::{key}")
873
+ return result
874
+
875
+ backup_root = home / _BACKUP_ROOT_NAME / _PLUGIN_NAME
876
+ if not _backup_dir_writable(backup_root):
877
+ msg = f"[Token Optimizer] ABORT: backup dir {backup_root} not writable; manifest entries left in place."
878
+ result["warnings"].append(msg)
879
+ print(msg, file=sys.stderr)
880
+ return result
881
+ stamp = _timestamp()
882
+ backup_dest = backup_root / stamp
883
+ try:
884
+ backup_dest.mkdir(parents=True, exist_ok=False)
885
+ except OSError:
886
+ msg = f"[Token Optimizer] ABORT: could not create backup dir {backup_dest}; manifest entries left in place."
887
+ result["warnings"].append(msg)
888
+ print(msg, file=sys.stderr)
889
+ return result
890
+ result["backup"] = str(backup_dest)
891
+
892
+ if to_remove_installed and installed_path.is_file():
893
+ backed = _backup_file(installed_path, backup_dest)
894
+ if backed is None:
895
+ msg = f"[Token Optimizer] ABORT: could not back up {installed_path}; installed_plugins entries left in place."
896
+ result["warnings"].append(msg)
897
+ print(msg, file=sys.stderr)
898
+ else:
899
+ plugins = registry.get("plugins", {})
900
+ for key in to_remove_installed:
901
+ plugins.pop(key, None)
902
+ result["removed"].append(f"{installed_path}::{key}")
903
+ if not _atomic_write_json(installed_path, registry):
904
+ msg = f"[Token Optimizer] WARNING: failed to write {installed_path}; entries may remain."
905
+ result["warnings"].append(msg)
906
+ print(msg, file=sys.stderr)
907
+
908
+ if to_remove_marketplaces and marketplaces_path.is_file():
909
+ backed = _backup_file(marketplaces_path, backup_dest)
910
+ if backed is None:
911
+ msg = f"[Token Optimizer] ABORT: could not back up {marketplaces_path}; known_marketplaces entries left in place."
912
+ result["warnings"].append(msg)
913
+ print(msg, file=sys.stderr)
914
+ else:
915
+ for key in to_remove_marketplaces:
916
+ marketplaces.pop(key, None)
917
+ result["removed"].append(f"{marketplaces_path}::{key}")
918
+ if not _atomic_write_json(marketplaces_path, marketplaces):
919
+ msg = f"[Token Optimizer] WARNING: failed to write {marketplaces_path}; entries may remain."
920
+ result["warnings"].append(msg)
921
+ print(msg, file=sys.stderr)
922
+
923
+ return result
924
+
925
+
926
+ def main(argv: list[str] | None = None) -> int:
927
+ args = build_parser().parse_args(argv)
928
+ result = detect_and_reconcile(dry_run=args.dry_run)
929
+ action = result["action"]
930
+ if action == "reconciled":
931
+ prefix = "Would reconcile" if args.dry_run else "Reconciled"
932
+ print(f"[Token Optimizer] {prefix}: {result['reason']}")
933
+ if result.get("backup"):
934
+ print(f"[Token Optimizer] backup: {result['backup']}")
935
+ if result.get("canonical"):
936
+ print(f"[Token Optimizer] canonical: {result['canonical']}")
937
+ return 0
938
+ if action == "warn":
939
+ # Warnings already printed inside detect_and_reconcile.
940
+ return 0
941
+ if action == "aborted":
942
+ return 1
943
+ # no-op
944
+ if not args.dry_run:
945
+ # Keep the ensure-health path quiet on a clean no-op.
946
+ return 0
947
+ print(f"[Token Optimizer] no-op: {result['reason']}")
948
+ return 0
949
+
950
+
951
+ if __name__ == "__main__":
952
+ raise SystemExit(main())