@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,562 @@
1
+ """Shared path and config resolution for Token Optimizer.
2
+
3
+ Single source of truth for two recurring lookups that previously diverged across
4
+ hook scripts:
5
+
6
+ 1. Plugin-data directory: env var > installed_plugins.json discovery > legacy
7
+ _backups/ fallback. The installed_plugins.json walk lets dashboard CLI runs
8
+ find live data when CLAUDE_PLUGIN_DATA is not set in the parent env.
9
+
10
+ 2. v5 feature flag check: env var > user config > plugin-data config > default.
11
+ User config wins over plugin-data config so manual edits to
12
+ ~/.claude/token-optimizer/config.json take effect even after the plugin
13
+ writes its own config (the dashboard toggle writes to plugin-data only,
14
+ and missing keys there used to mask user-level enables).
15
+
16
+ Hot-path safe: only stdlib imports, no I/O at import time. Discovery results are
17
+ cached with lru_cache(maxsize=1) so repeated calls within a single hook process
18
+ share one filesystem traversal.
19
+
20
+ Security: all returned paths are confined under the active runtime home and
21
+ reject symlinks to prevent registry-key path traversal and symlink-based write
22
+ redirection.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import os
29
+ import re
30
+ import shutil
31
+ import sys
32
+ import time
33
+ from functools import lru_cache
34
+ from pathlib import Path
35
+
36
+ from runtime_env import plugin_data_env_vars, project_config_value, runtime_home
37
+
38
+ _RUNTIME_HOME = runtime_home()
39
+ _USER_CONFIG_DIR = _RUNTIME_HOME / "token-optimizer"
40
+ _LEGACY_BACKUP_DIR = _RUNTIME_HOME / "_backups" / "token-optimizer"
41
+ _INSTALLED_PLUGINS = _RUNTIME_HOME / "plugins" / "installed_plugins.json"
42
+ _PLUGIN_DATA_BASE = _RUNTIME_HOME / "plugins" / "data"
43
+ _PLUGIN_NAME = "token-optimizer"
44
+ _PLUGIN_DATA_ENV_VARS = plugin_data_env_vars()
45
+
46
+ # Bound JSON reads in hot-path hooks. 1 MB is generous for plugin metadata and
47
+ # user config; larger files are treated as malformed and skipped silently.
48
+ _MAX_CONFIG_BYTES = 1_048_576
49
+
50
+ # Marketplace names map to filesystem paths. Allow only conservative chars.
51
+ _SAFE_MARKETPLACE_NAME = re.compile(r"^[A-Za-z0-9._-]+$")
52
+
53
+
54
+ def _is_safe_subdir(candidate: Path, base: Path) -> bool:
55
+ """True if candidate is a real directory STRICTLY inside base, not a symlink.
56
+
57
+ ``Path.is_relative_to`` is reflexive (a path is "relative to" itself), so
58
+ without the explicit inequality check a candidate that resolves to ``base``
59
+ itself would pass this confinement test. That matters because every other
60
+ plugin's data directory lives as a sibling subdir directly under the same
61
+ shared ``plugins/data`` root: a misconfigured or malicious env var pointed
62
+ straight at that root (rather than at a real per-plugin identity subdir)
63
+ would otherwise be accepted as "confined" while actually granting access to
64
+ every plugin's data, not just this one's.
65
+ """
66
+ try:
67
+ if not candidate.is_dir():
68
+ return False
69
+ if candidate.is_symlink():
70
+ return False
71
+ resolved = candidate.resolve(strict=True)
72
+ base_resolved = base.resolve(strict=False)
73
+ return resolved != base_resolved and resolved.is_relative_to(base_resolved)
74
+ except (OSError, ValueError):
75
+ return False
76
+
77
+
78
+ def _plugin_data_env_value() -> str | None:
79
+ """Return the first runtime-appropriate plugin-data env value."""
80
+ for env_var in _PLUGIN_DATA_ENV_VARS:
81
+ value = os.environ.get(env_var)
82
+ if value:
83
+ return value
84
+ return None
85
+
86
+
87
+ def _safe_load_json(path: Path):
88
+ """Read and parse JSON with size + recursion guards. Returns None on failure."""
89
+ try:
90
+ if not path.is_file():
91
+ return None
92
+ if path.stat().st_size > _MAX_CONFIG_BYTES:
93
+ return None
94
+ with path.open("r", encoding="utf-8") as fh:
95
+ return json.load(fh)
96
+ except (OSError, ValueError, RecursionError):
97
+ return None
98
+
99
+
100
+ def _registered_plugin_data_dirs() -> list[Path]:
101
+ """Return safe identities still referenced by installed_plugins.json."""
102
+ candidates: list[Path] = []
103
+ registry = _safe_load_json(_INSTALLED_PLUGINS)
104
+ if not isinstance(registry, dict):
105
+ return candidates
106
+ plugins = registry.get("plugins", {})
107
+ if not isinstance(plugins, dict):
108
+ return candidates
109
+ for key in plugins:
110
+ if not isinstance(key, str) or not key.startswith(_PLUGIN_NAME + "@"):
111
+ continue
112
+ marketplace = key.split("@", 1)[1]
113
+ if not _SAFE_MARKETPLACE_NAME.match(marketplace):
114
+ continue
115
+ candidate = _PLUGIN_DATA_BASE / f"{_PLUGIN_NAME}-{marketplace}"
116
+ if _is_safe_subdir(candidate, _PLUGIN_DATA_BASE):
117
+ candidates.append(candidate)
118
+ return sorted(set(candidates), key=lambda path: path.name)
119
+
120
+
121
+ def resolve_claude_plugin_data_env() -> Path | None:
122
+ """Identity-checked resolver for the raw CLAUDE_PLUGIN_DATA env var.
123
+
124
+ Returns CLAUDE_PLUGIN_DATA's resolved path ONLY when it is a declared
125
+ identity of THIS plugin (present in installed_plugins.json via
126
+ _registered_plugin_data_dirs) and confined under the shared plugins/data
127
+ root as a real subdir (not the root itself — see _is_safe_subdir). A name
128
+ merely starting with "token-optimizer" is NOT proof; a foreign plugin's
129
+ CLAUDE_PLUGIN_DATA sharing the same plugins/data/ root is rejected.
130
+
131
+ This is the SINGLE identity check every raw-CLAUDE_PLUGIN_DATA site shares
132
+ (identity check): resolve_plugin_data_dir() below calls it directly, and so do
133
+ the sibling sites that read CLAUDE_PLUGIN_DATA outside this module —
134
+ hooks/run.py's consent-config read and detectors/cache_instability.py's
135
+ detector-state write. None of the three duplicate the identity logic; a
136
+ leaked/foreign CLAUDE_PLUGIN_DATA can misdirect none of them.
137
+ """
138
+ env_val = os.environ.get("CLAUDE_PLUGIN_DATA", "")
139
+ if not env_val:
140
+ return None
141
+ try:
142
+ resolved = Path(env_val).resolve(strict=False)
143
+ except (OSError, ValueError):
144
+ return None
145
+ if not _is_safe_subdir(resolved, _PLUGIN_DATA_BASE):
146
+ return None
147
+ registered = {r.resolve(strict=False) for r in _registered_plugin_data_dirs()}
148
+ if resolved in registered:
149
+ return resolved
150
+ return None # Foreign plugin's CLAUDE_PLUGIN_DATA leaked in.
151
+
152
+
153
+ @lru_cache(maxsize=1)
154
+ def resolve_plugin_data_dir() -> Path | None:
155
+ """Return the active plugin-data directory.
156
+
157
+ Priority:
158
+ 1. TOKEN_OPTIMIZER_PLUGIN_DATA (dedicated, unconditional — but still
159
+ confined to a REAL subdir of plugins/data, never the shared root
160
+ itself). Checked FIRST regardless of CLAUDE_PLUGIN_DATA's validity,
161
+ so it wins even when CLAUDE_PLUGIN_DATA ALSO happens to resolve to a
162
+ valid registered identity (the common in-plugin hook case).
163
+ 2. CLAUDE_PLUGIN_DATA — accepted ONLY when the resolved path is a
164
+ declared identity of THIS plugin, via resolve_claude_plugin_data_env().
165
+ 3. installed_plugins.json lookup for the active marketplace install
166
+ 4. Stable lexical glob fallback across token-optimizer-* data dirs
167
+ 5. None (caller falls back to the legacy _backups/ path)
168
+
169
+ All discovered paths are confined under the active runtime's plugin-data
170
+ tree and reject symlinks. The env-var path must resolve under that runtime
171
+ home.
172
+ """
173
+ # TOKEN_OPTIMIZER_PLUGIN_DATA must win even when CLAUDE_PLUGIN_DATA ALSO
174
+ # resolves to a valid registered identity. The previous implementation
175
+ # iterated _PLUGIN_DATA_ENV_VARS (CLAUDE_PLUGIN_DATA listed first for the
176
+ # Claude runtime) in a single for-loop and returned on the first env var
177
+ # that matched — so a valid CLAUDE_PLUGIN_DATA silently shadowed the
178
+ # dedicated override, exactly backwards from the documented priority.
179
+ # Checking the dedicated var first, unconditionally, fixes that.
180
+ if "TOKEN_OPTIMIZER_PLUGIN_DATA" in _PLUGIN_DATA_ENV_VARS:
181
+ dedicated_val = os.environ.get("TOKEN_OPTIMIZER_PLUGIN_DATA")
182
+ if dedicated_val:
183
+ try:
184
+ resolved = Path(dedicated_val).resolve(strict=False)
185
+ except (OSError, ValueError):
186
+ resolved = None
187
+ if resolved is not None and _is_safe_subdir(resolved, _PLUGIN_DATA_BASE):
188
+ return resolved # dedicated — unconditional, but a real subdir
189
+
190
+ if "CLAUDE_PLUGIN_DATA" in _PLUGIN_DATA_ENV_VARS:
191
+ claude_identity = resolve_claude_plugin_data_env()
192
+ if claude_identity is not None:
193
+ return claude_identity
194
+
195
+ candidates = _registered_plugin_data_dirs()
196
+
197
+ if not candidates:
198
+ try:
199
+ if _PLUGIN_DATA_BASE.is_dir():
200
+ for p in _PLUGIN_DATA_BASE.glob(f"{_PLUGIN_NAME}-*"):
201
+ if _is_safe_subdir(p, _PLUGIN_DATA_BASE):
202
+ candidates.append(p)
203
+ except OSError:
204
+ pass
205
+
206
+ if not candidates:
207
+ return None
208
+
209
+ candidates.sort(key=lambda p: p.name)
210
+ return candidates[0]
211
+
212
+
213
+ def _all_plugin_data_dirs() -> list[Path]:
214
+ """Return every safe Token Optimizer identity in deterministic order."""
215
+ candidates: list[Path] = []
216
+ try:
217
+ if _PLUGIN_DATA_BASE.is_dir():
218
+ for path in _PLUGIN_DATA_BASE.glob(f"{_PLUGIN_NAME}-*"):
219
+ if _is_safe_subdir(path, _PLUGIN_DATA_BASE):
220
+ candidates.append(path)
221
+ except OSError:
222
+ pass
223
+ return sorted(set(candidates), key=lambda path: path.name)
224
+
225
+
226
+ def find_sibling_plugin_data_dirs(active: Path | None = None) -> list[Path]:
227
+ """Return safe plugin-data identities other than the active identity."""
228
+ active = active if active is not None else resolve_plugin_data_dir()
229
+ try:
230
+ active_resolved = active.resolve(strict=False) if active is not None else None
231
+ except (OSError, ValueError):
232
+ active_resolved = None
233
+ siblings: list[Path] = []
234
+ for candidate in _all_plugin_data_dirs():
235
+ try:
236
+ if active_resolved is not None and candidate.resolve(strict=False) == active_resolved:
237
+ continue
238
+ except (OSError, ValueError):
239
+ continue
240
+ siblings.append(candidate)
241
+ return siblings
242
+
243
+
244
+ def snapshot_dir_candidates() -> list[Path]:
245
+ """Return active then sibling snapshot roots for read-side recovery."""
246
+ override = os.environ.get("TOKEN_OPTIMIZER_SNAPSHOT_DIR", "").strip()
247
+ if override:
248
+ return [Path(override).expanduser()]
249
+ active = resolve_plugin_data_dir()
250
+ candidates: list[Path] = []
251
+ if active is not None:
252
+ candidates.append(active / "data")
253
+ candidates.extend(path / "data" for path in find_sibling_plugin_data_dirs(active))
254
+ if not candidates:
255
+ candidates.append(_LEGACY_BACKUP_DIR)
256
+ return candidates
257
+
258
+
259
+ def _latest_tree_mtime(path: Path) -> float | None:
260
+ """Return newest mtime, treating symlinks/read errors as non-reclaimable."""
261
+ try:
262
+ latest = os.lstat(path).st_mtime
263
+ errors: list[OSError] = []
264
+ for root, dirnames, filenames in os.walk(
265
+ path,
266
+ followlinks=False,
267
+ onerror=errors.append,
268
+ ):
269
+ root_path = Path(root)
270
+ for name in [*dirnames, *filenames]:
271
+ item = root_path / name
272
+ if item.is_symlink():
273
+ return None
274
+ latest = max(latest, os.lstat(item).st_mtime)
275
+ if errors:
276
+ return None
277
+ return latest
278
+ except OSError:
279
+ return None
280
+
281
+
282
+ def _announce_orphan_reclamation(message: str, active: Path | None) -> None:
283
+ """Emit to stderr and persist destructive-action notices when possible."""
284
+ print(message, file=sys.stderr)
285
+ if active is None:
286
+ return
287
+ try:
288
+ log_dir = active / "data"
289
+ log_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
290
+ os.chmod(log_dir, 0o700)
291
+ log_path = log_dir / "orphan-reclamation.log"
292
+ with log_path.open("a", encoding="utf-8") as handle:
293
+ handle.write(f"{int(time.time())} {message}\n")
294
+ os.chmod(log_path, 0o600)
295
+ except OSError:
296
+ pass
297
+
298
+
299
+ def reclaim_orphaned_plugin_data_dirs(min_age_days: int | None = None) -> list[Path]:
300
+ """Reclaim old sibling identities only with explicit user opt-in.
301
+
302
+ Detection is always safe and announced. Deletion requires
303
+ TOKEN_OPTIMIZER_RECLAIM_ORPHANED_DATA=1, a minimum seven-day age gate, a
304
+ symlink-free readable tree, and an identity distinct from the active one.
305
+ """
306
+ if min_age_days is None:
307
+ try:
308
+ min_age_days = int(os.environ.get(
309
+ "TOKEN_OPTIMIZER_ORPHAN_RETENTION_DAYS", "30"
310
+ ))
311
+ except (TypeError, ValueError):
312
+ min_age_days = 30
313
+ min_age_days = max(7, min_age_days)
314
+ cutoff = time.time() - (min_age_days * 86400)
315
+ active = resolve_plugin_data_dir()
316
+ registered = {
317
+ path.resolve(strict=False) for path in _registered_plugin_data_dirs()
318
+ }
319
+ if not registered:
320
+ return []
321
+ eligible = [
322
+ path for path in find_sibling_plugin_data_dirs(active)
323
+ if path.resolve(strict=False) not in registered
324
+ and (latest := _latest_tree_mtime(path)) is not None
325
+ and latest < cutoff
326
+ ]
327
+ if not eligible:
328
+ return []
329
+ opted_in = os.environ.get(
330
+ "TOKEN_OPTIMIZER_RECLAIM_ORPHANED_DATA", ""
331
+ ).strip().lower() in _TRUTHY_ENV
332
+ if not opted_in:
333
+ names = ", ".join(path.name for path in eligible)
334
+ print(
335
+ "[Token Optimizer] Old orphaned plugin data detected but not deleted: "
336
+ f"{names}. Set TOKEN_OPTIMIZER_RECLAIM_ORPHANED_DATA=1 to reclaim "
337
+ f"identities inactive for at least {min_age_days} days.",
338
+ file=sys.stderr,
339
+ )
340
+ return []
341
+ removed: list[Path] = []
342
+ for path in eligible:
343
+ # Eligibility is only a candidate snapshot. A reinstall can update the
344
+ # registry, active identity, or directory contents while the initial
345
+ # tree scan is running, so repeat every destructive precondition at
346
+ # the point of deletion.
347
+ resolve_plugin_data_dir.cache_clear()
348
+ active_now = resolve_plugin_data_dir()
349
+ try:
350
+ target = path.resolve(strict=False)
351
+ active_resolved = (
352
+ active_now.resolve(strict=False)
353
+ if active_now is not None else None
354
+ )
355
+ registered_now = {
356
+ item.resolve(strict=False)
357
+ for item in _registered_plugin_data_dirs()
358
+ }
359
+ latest_now = _latest_tree_mtime(path)
360
+ except OSError:
361
+ continue
362
+ if (
363
+ active_resolved == target
364
+ or target in registered_now
365
+ or latest_now is None
366
+ or latest_now >= cutoff
367
+ ):
368
+ continue
369
+ # Even with every precondition rechecked above, check-then-rmtree is not
370
+ # atomic: rmtree resolves the PATHNAME, so an installer that re-registers
371
+ # and recreates this identity inside the gap gets its live data deleted.
372
+ # Claim the tree with an atomic rename first. After it succeeds the
373
+ # original pathname is free -- a concurrent reinstall lands on a fresh
374
+ # directory and is unaffected by what we do next -- and we are deleting a
375
+ # name only this process knows.
376
+ quarantine = path.with_name(
377
+ f".{path.name}.reclaiming-{os.getpid()}-{int(time.time() * 1000)}"
378
+ )
379
+ try:
380
+ os.rename(path, quarantine)
381
+ except OSError:
382
+ continue
383
+ # Revalidate against the claimed tree. If it turns out someone touched it
384
+ # or registered it in the gap, put it back exactly where it was.
385
+ try:
386
+ latest_claimed = _latest_tree_mtime(quarantine)
387
+ resolve_plugin_data_dir.cache_clear()
388
+ active_after = resolve_plugin_data_dir()
389
+ active_after_resolved = (
390
+ active_after.resolve(strict=False)
391
+ if active_after is not None else None
392
+ )
393
+ registered_after = {
394
+ item.resolve(strict=False)
395
+ for item in _registered_plugin_data_dirs()
396
+ }
397
+ except OSError:
398
+ latest_claimed, active_after_resolved, registered_after = None, None, set()
399
+ if (
400
+ latest_claimed is None
401
+ or latest_claimed >= cutoff
402
+ or active_after_resolved == target
403
+ or target in registered_after
404
+ ):
405
+ try:
406
+ os.rename(quarantine, path)
407
+ except OSError:
408
+ pass
409
+ continue
410
+ try:
411
+ shutil.rmtree(quarantine)
412
+ if not quarantine.exists():
413
+ removed.append(path)
414
+ _announce_orphan_reclamation(
415
+ "[Token Optimizer] Reclaimed orphaned plugin data identity: "
416
+ f"{path.name}",
417
+ active,
418
+ )
419
+ except OSError as exc:
420
+ _announce_orphan_reclamation(
421
+ "[Token Optimizer] Could not reclaim orphaned plugin data identity "
422
+ f"{path.name}: {exc.__class__.__name__}",
423
+ active,
424
+ )
425
+ return removed
426
+
427
+
428
+ def resolve_snapshot_dir() -> Path:
429
+ """Return the data directory for snapshots, caches, and decision logs.
430
+
431
+ v5.11.1: TOKEN_OPTIMIZER_SNAPSHOT_DIR overrides the resolved location when
432
+ set, so tests (and any sandboxed caller) can pin a private data dir without
433
+ monkeypatching every module that resolves SNAPSHOT_DIR independently
434
+ (measure/archive_result/read_cache each call this). Production no-op when
435
+ unset. Any module that imports this resolver therefore honors the sandbox.
436
+ """
437
+ override = os.environ.get("TOKEN_OPTIMIZER_SNAPSHOT_DIR", "").strip()
438
+ if override:
439
+ return Path(override).expanduser()
440
+ plugin_data = resolve_plugin_data_dir()
441
+ if plugin_data is not None:
442
+ return plugin_data / "data"
443
+ return _LEGACY_BACKUP_DIR
444
+
445
+
446
+ # Common truthy/falsy strings accepted in env-var boolean checks.
447
+ _TRUTHY_ENV = frozenset({"1", "true", "yes", "on"})
448
+ _FALSY_ENV = frozenset({"0", "false", "no", "off", ""})
449
+
450
+ _warned_flag_values: set = set()
451
+
452
+
453
+ def _warn_unrecognized_flag_value(flag_name: str, value, config_path) -> None:
454
+ """One-time stderr warning for an unrecognized config flag value.
455
+
456
+ Diagnostics go to stderr only (stdout must stay clean for hook contracts).
457
+ Deduped per (flag, type) so a misconfigured config.json warns once, not on
458
+ every hook invocation. The raw value is NEVER echoed in full — only its type
459
+ and length — so a secret mistakenly placed as a flag value can't leak into
460
+ logs/CI captures. The dedup key is a string so an unhashable
461
+ JSON value (list/dict) can't crash the caller.
462
+ """
463
+ sig = (flag_name, type(value).__name__)
464
+ if sig in _warned_flag_values:
465
+ return
466
+ _warned_flag_values.add(sig)
467
+ try:
468
+ try:
469
+ length = len(value)
470
+ except TypeError:
471
+ length = "n/a"
472
+ print(
473
+ f"[Token Optimizer] WARNING: {config_path}: flag '{flag_name}' has an "
474
+ f"unrecognized value (type={type(value).__name__}, length={length}); "
475
+ f"expected a boolean or one of {sorted(_TRUTHY_ENV | _FALSY_ENV)}. "
476
+ "Ignoring and using the next source/default.",
477
+ file=sys.stderr,
478
+ )
479
+ except Exception:
480
+ pass
481
+
482
+
483
+ def interpret_flag_value(value, *, env_truthy_value: str | None = None):
484
+ """Single source of truth for reading ONE feature-flag value.
485
+
486
+ Accepts an env string OR a config JSON bool/number/string. Returns:
487
+ * True / False when the value decisively enables or disables, or
488
+ * None when the value is unrecognized/unset, so the CALLER falls through
489
+ to its next source (env -> config -> default).
490
+
491
+ Binary flags accept "1"/"true"/"yes"/"on" as True and "0"/"false"/"no"/
492
+ "off"/"" as False, case-insensitively; a genuine JSON bool/number is taken
493
+ as-is. Tri-state flags (env_truthy_value set, e.g. structure-map "beta") are
494
+ ALWAYS decisive: only the exact token (case-insensitive) enables, everything
495
+ else disables. Both readers (this module's hot path and measure.py's
496
+ dashboard) call this so they can never disagree.
497
+ """
498
+ if isinstance(value, bool):
499
+ return value
500
+ if isinstance(value, (int, float)):
501
+ return bool(value)
502
+ s = str(value).strip()
503
+ if env_truthy_value is not None:
504
+ return s.lower() == env_truthy_value.strip().lower()
505
+ low = s.lower()
506
+ if low in _TRUTHY_ENV:
507
+ return True
508
+ if low in _FALSY_ENV: # includes ""
509
+ return False
510
+ return None
511
+
512
+
513
+ def is_v5_flag_enabled(
514
+ flag_name: str,
515
+ env_var: str,
516
+ *,
517
+ default: bool,
518
+ env_truthy_value: str | None = None,
519
+ ) -> bool:
520
+ """Check a v5 feature flag in priority order.
521
+
522
+ 1. Environment variable
523
+ 2. User config: <runtime-home>/token-optimizer/config.json
524
+ 3. Plugin-data config: <plugin-data>/config/config.json
525
+ 4. Project config: $CLAUDE_PROJECT_DIR/.claude/token-optimizer.json
526
+ (runtime_env.project_config: committed, allowlisted keys only)
527
+ 5. default
528
+
529
+ Value interpretation is delegated to interpret_flag_value so the env path,
530
+ the config path, and measure.py's dashboard reader all share one gate. An
531
+ unrecognized value at any source falls through to the next (warned once for
532
+ config sources); the default is the final fallback.
533
+ """
534
+ env_val = os.environ.get(env_var)
535
+ if env_val is not None:
536
+ r = interpret_flag_value(env_val, env_truthy_value=env_truthy_value)
537
+ if r is not None:
538
+ return r
539
+ # Unrecognized env value: don't guess, fall through to config/default.
540
+
541
+ config_paths = [_USER_CONFIG_DIR / "config.json"]
542
+ plugin_data = resolve_plugin_data_dir()
543
+ if plugin_data is not None:
544
+ config_paths.append(plugin_data / "config" / "config.json")
545
+
546
+ for config_path in config_paths:
547
+ cfg = _safe_load_json(config_path)
548
+ if isinstance(cfg, dict) and flag_name in cfg:
549
+ r = interpret_flag_value(cfg[flag_name], env_truthy_value=env_truthy_value)
550
+ if r is not None:
551
+ return r
552
+ # Unrecognized string / unusable JSON type: warn once, fall through.
553
+ _warn_unrecognized_flag_value(flag_name, cfg[flag_name], config_path)
554
+ continue
555
+
556
+ project_val = project_config_value(flag_name)
557
+ if project_val is not None:
558
+ r = interpret_flag_value(project_val, env_truthy_value=env_truthy_value)
559
+ if r is not None:
560
+ return r
561
+
562
+ return default
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env python3
2
+ """Shared python-interpreter trust gate for hook installers.
3
+
4
+ Every adapter persists an absolute interpreter path into a hook command that
5
+ fires under the host agent. A writable or foreign-owned interpreter (or one
6
+ sitting in a writable directory) is a persistence vector: whoever controls the
7
+ bytes controls every future hook invocation. This module is the single gate
8
+ all installers share; per-adapter copies were consolidated here so the
9
+ semantics cannot drift between adapters.
10
+
11
+ Pure stat, never runs the target.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import stat as _stat
18
+
19
+
20
+ def py_trust_reason(p: str) -> str | None:
21
+ """None when trusted, else a short human-readable rejection reason."""
22
+ try:
23
+ real = os.path.realpath(p)
24
+ if not os.path.isfile(real):
25
+ return f"{real} does not exist"
26
+ if os.name == "nt" or not hasattr(os, "geteuid"):
27
+ return None
28
+ euid = os.geteuid()
29
+
30
+ def _admin_owned(uid: int) -> bool:
31
+ # euid (ours) or root/admin (0): an interpreter either we or the
32
+ # system controls. Hosted-CI caches (hostedtoolcache) and macOS
33
+ # Homebrew are euid/admin-owned; /usr/bin is root-owned.
34
+ return uid == euid or uid == 0
35
+
36
+ st_file = os.stat(real)
37
+ st_dir = os.stat(os.path.dirname(real))
38
+ # The interpreter's BYTES must never be world-writable, and must be
39
+ # admin-owned. Group-writable is accepted ONLY in the self-group case
40
+ # (owner is us AND the group is our own primary group): hosted-CI tool
41
+ # caches extract the interpreter 0775 under the runner's own group, and
42
+ # that group is exactly the account running this installer. A file
43
+ # group-writable by any OTHER group is a swap vector.
44
+ if st_file.st_mode & _stat.S_IWOTH:
45
+ return f"{real} is world-writable"
46
+ if st_file.st_mode & _stat.S_IWGRP and not (
47
+ st_file.st_uid == euid and st_file.st_gid == os.getegid()
48
+ ):
49
+ return f"{real} is group-writable by a foreign group"
50
+ if not _admin_owned(st_file.st_uid):
51
+ return f"{real} is owned by uid {st_file.st_uid}, not by us or root"
52
+ # The containing DIR must not be world-writable. Group-writable is the
53
+ # admin-group case (hostedtoolcache 0775 under the runner's own group)
54
+ # and is accepted only when root owns the dir, or when the owner is us
55
+ # AND the writable group is our own primary group -- a group-writable
56
+ # dir whose group is any other account would let that account swap the
57
+ # interpreter.
58
+ if st_dir.st_mode & _stat.S_IWOTH:
59
+ return f"{os.path.dirname(real)} is world-writable"
60
+ if st_dir.st_mode & _stat.S_IWGRP and not (
61
+ st_dir.st_uid == 0
62
+ or (st_dir.st_uid == euid and st_dir.st_gid == os.getegid())
63
+ ):
64
+ return (f"{os.path.dirname(real)} is group-writable by a group "
65
+ f"the user does not control (uid {st_dir.st_uid}, "
66
+ f"gid {st_dir.st_gid})")
67
+ return None
68
+ except (OSError, ValueError) as exc:
69
+ # ValueError: embedded null byte in path (realpath raises it, not
70
+ # OSError). Without catching it, one bad candidate aborts the entire
71
+ # resolver search instead of being rejected and skipped.
72
+ return f"stat failed: {exc}"
73
+
74
+
75
+ def py_path_is_trusted(p: str) -> bool:
76
+ """Trusted iff the interpreter's bytes are admin-owned (euid or root) and
77
+ not group/other-writable, and its dir is not world-writable and not
78
+ group-writable by a third party. On Windows, stat ownership is unreliable
79
+ under Git-Bash, so require only that the path is a real file."""
80
+ return py_trust_reason(p) is None