@alexgreensh/token-optimizer 5.13.67 → 5.13.69
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.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/module_runner.py +1 -1
- package/package.json +1 -1
- package/skills/fleet-auditor/references/fleet-systems.md +38 -0
- package/skills/fleet-auditor/scripts/fleet.py +63 -92
- package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
- package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
- package/skills/token-coach/SKILL.md +21 -23
- package/skills/token-dashboard/SKILL.md +5 -4
- package/skills/token-optimizer/SKILL.md +1 -1
- package/skills/token-optimizer/assets/dashboard.html +101 -50
- package/skills/token-optimizer/references/cli-reference.md +1 -1
- package/skills/token-optimizer/references/cursor-workflow.md +1 -1
- package/skills/token-optimizer/references/phase0-setup.md +1 -1
- package/skills/token-optimizer/references/presentation-workflow.md +1 -1
- package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
- package/skills/token-optimizer/scripts/_measure/_vendor/README.md +8 -2
- package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +46 -6
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +34 -3
- package/skills/token-optimizer/scripts/_measure/audit.py +5 -21
- package/skills/token-optimizer/scripts/_measure/cli.py +86 -0
- package/skills/token-optimizer/scripts/_measure/daemon.py +34 -76
- package/skills/token-optimizer/scripts/_measure/dashboard.py +63 -37
- package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
- package/skills/token-optimizer/scripts/_measure/lifecycle.py +88 -528
- package/skills/token-optimizer/scripts/_measure/savings.py +20 -70
- package/skills/token-optimizer/scripts/_measure/sessions.py +58 -20
- package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
- package/skills/token-optimizer/scripts/{_measure/_vendor/tomli/_parser.py → _tomli.py} +156 -10
- package/skills/token-optimizer/scripts/antigravity_install.py +7 -0
- package/skills/token-optimizer/scripts/bash_compress.py +8 -40
- package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -0
- package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +22 -22
- package/skills/token-optimizer/scripts/codex_doctor.py +34 -8
- package/skills/token-optimizer/scripts/codex_hook_provenance.py +268 -0
- package/skills/token-optimizer/scripts/codex_install.py +33 -69
- package/skills/token-optimizer/scripts/command_filters.py +39 -309
- package/skills/token-optimizer/scripts/copilot_install.py +9 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
- package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
- package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
- package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
- package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
- package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
- package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
- package/skills/token-optimizer/scripts/cursor_install.py +111 -19
- package/skills/token-optimizer/scripts/cursor_quality.py +505 -0
- package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
- package/skills/token-optimizer/scripts/cursor_session.py +26 -5
- package/skills/token-optimizer/scripts/cursor_state.py +8 -0
- package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
- package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
- package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
- package/skills/token-optimizer/scripts/devin_install.py +6 -12
- package/skills/token-optimizer/scripts/devin_source.py +17 -6
- package/skills/token-optimizer/scripts/devin_verify.py +17 -0
- package/skills/token-optimizer/scripts/grok_install.py +9 -0
- package/skills/token-optimizer/scripts/heal_report.py +92 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
- package/skills/token-optimizer/scripts/hermes_install.py +4 -1
- package/skills/token-optimizer/scripts/hook_heal.py +138 -0
- package/skills/token-optimizer/scripts/hook_provenance.py +878 -0
- package/skills/token-optimizer/scripts/measure.py +2 -2
- package/skills/token-optimizer/scripts/owned_hooks.py +420 -0
- package/skills/token-optimizer/scripts/shipped_codex_hook_templates.json +5815 -0
- package/skills/token-optimizer/scripts/shipped_hook_templates.py +252 -0
- package/skills/token-optimizer/scripts/shipped_starter_hooks.py +55 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +0 -112
- package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_types.py +0 -10
|
@@ -1603,7 +1603,7 @@ _manage_mcp = _measure_compat.bind(_measure_providers['dashboard']._manage_mcp,
|
|
|
1603
1603
|
_codex_memory_review_data = _measure_compat.bind(_measure_providers['dashboard']._codex_memory_review_data, __name__)
|
|
1604
1604
|
|
|
1605
1605
|
|
|
1606
|
-
generate_standalone_dashboard = _measure_compat.bind(_measure_providers['dashboard'].generate_standalone_dashboard, __name__, defaults=(
|
|
1606
|
+
generate_standalone_dashboard = _measure_compat.bind(_measure_providers['dashboard'].generate_standalone_dashboard, __name__, defaults=(None, False, False,))
|
|
1607
1607
|
|
|
1608
1608
|
|
|
1609
1609
|
_acquire_session_end_flush_lock = _measure_compat.bind(_measure_providers['lifecycle']._acquire_session_end_flush_lock, __name__, defaults=(120,))
|
|
@@ -1648,7 +1648,7 @@ _inline_flush_budget_seconds = _measure_compat.bind(_measure_providers['lifecycl
|
|
|
1648
1648
|
_dispatch_collect = _measure_compat.bind(_measure_providers['lifecycle']._dispatch_collect, __name__)
|
|
1649
1649
|
|
|
1650
1650
|
|
|
1651
|
-
_spawn_detached_dashboard_selfheal = _measure_compat.bind(_measure_providers['lifecycle']._spawn_detached_dashboard_selfheal, __name__, defaults=(
|
|
1651
|
+
_spawn_detached_dashboard_selfheal = _measure_compat.bind(_measure_providers['lifecycle']._spawn_detached_dashboard_selfheal, __name__, defaults=(None, False,), kwdefaults={'hook_timeout': True})
|
|
1652
1652
|
|
|
1653
1653
|
|
|
1654
1654
|
# Thundering-herd guard for the version-bump dashboard self-heal. The marker is
|
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
"""Token Optimizer's own SessionEnd, Stop and smart-compact entries in
|
|
2
|
+
settings.json: which ones the fossil reconcile, setup_hook's upgrade and
|
|
3
|
+
uninstall, and setup_smart_compact --uninstall may rewrite or remove.
|
|
4
|
+
|
|
5
|
+
These used to act on any command that merely mentioned measure.py with one
|
|
6
|
+
of our subcommands, so a user's own /home/me/mytool/measure.py collect was
|
|
7
|
+
rewritten or deleted. An entry is now theirs to touch only when it is
|
|
8
|
+
proven ours (a shipped context or a ledger record, exactly as the healer
|
|
9
|
+
proves), or it is byte-identical to one of the exact commands setup_hook /
|
|
10
|
+
setup_smart_compact ever generated, rebuilt forward with a measure.py path
|
|
11
|
+
that is a Token Optimizer install's.
|
|
12
|
+
|
|
13
|
+
Command tokens only propose candidates here; byte equality of a forward
|
|
14
|
+
rebuild decides. Lives beside measure.py and must stay importable on Python
|
|
15
|
+
3.9 with the standard library only.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import shlex
|
|
22
|
+
import subprocess
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
import hook_heal
|
|
26
|
+
import hook_provenance as hp
|
|
27
|
+
from shipped_starter_hooks import STARTER_HOOK_CONTEXTS
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
_PLACEHOLDER_SCRIPT = "${CLAUDE_PLUGIN_ROOT}/skills/token-optimizer/scripts/measure.py"
|
|
31
|
+
_SCRIPT_TAIL = ("skills", "token-optimizer", "scripts", "measure.py")
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _sq(path):
|
|
35
|
+
return "'%s'" % path
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _sh(text):
|
|
39
|
+
return shlex.quote(str(text).replace("\\", "/"))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _l2c(*args):
|
|
43
|
+
return subprocess.list2cmdline(list(args))
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# setup_hook's HOOK_COMMAND, every shape it shipped (git history of measure.py).
|
|
47
|
+
SESSION_END_SHAPES = (
|
|
48
|
+
lambda py, mp: "python3 %s collect --quiet" % mp,
|
|
49
|
+
lambda py, mp: "python3 %s collect --quiet" % _sq(mp),
|
|
50
|
+
lambda py, mp: "python3 {0} collect --quiet && python3 {0} dashboard --quiet".format(_sq(mp)),
|
|
51
|
+
lambda py, mp: "%s && %s >NUL 2>&1" % (_l2c(py, mp, "collect", "--quiet"), _l2c(py, mp, "dashboard", "--quiet")),
|
|
52
|
+
lambda py, mp: "{0} {1} collect --quiet && {0} {1} dashboard --quiet >/dev/null 2>&1".format(_sh(py), _sh(mp)),
|
|
53
|
+
lambda py, mp: "python3 %s session-end-flush --trigger end" % _sq(mp),
|
|
54
|
+
lambda py, mp: "%s %s session-end-flush --trigger end >/dev/null 2>&1" % (_sh(py), _sh(mp)),
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
# setup_smart_compact's commands, every shape it shipped.
|
|
58
|
+
_COMPACT_SUBCOMMANDS = ("compact-capture --trigger auto", "compact-restore",
|
|
59
|
+
"compact-restore --new-session-only",
|
|
60
|
+
"compact-capture --trigger stop", "compact-capture --trigger end")
|
|
61
|
+
COMPACT_SHAPES = tuple(
|
|
62
|
+
shape for sub in _COMPACT_SUBCOMMANDS for shape in (
|
|
63
|
+
lambda py, mp, sub=sub: "python3 %s %s" % (_sq(mp), sub),
|
|
64
|
+
lambda py, mp, sub=sub: "[ -r {0} ] || exit 0; python3 {0} {1}".format(_sq(mp), sub),
|
|
65
|
+
lambda py, mp, sub=sub: "[ -r {0} ] || exit 0; {1} {0} {2}".format(_sh(mp), _sh(py), sub),
|
|
66
|
+
))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# setup_quality_bar's UserPromptSubmit command, every shape it shipped.
|
|
70
|
+
QUALITY_SHAPES = (
|
|
71
|
+
lambda py, mp: "python3 %s quality-cache --quiet" % _sq(mp),
|
|
72
|
+
lambda py, mp: "%s %s quality-cache --quiet" % (_sh(py), _sh(mp)),
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _path_parts(path):
|
|
77
|
+
text = str(path).replace("\\", "/")
|
|
78
|
+
if os.name == "nt":
|
|
79
|
+
text = text.lower()
|
|
80
|
+
return tuple(part for part in text.split("/") if part)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _install_roots(facade):
|
|
84
|
+
"""Fixed roots R whose R/skills/token-optimizer/scripts/measure.py is ours."""
|
|
85
|
+
roots = [Path(facade.CLAUDE_DIR), # script install, skill link: ~/.claude/skills/token-optimizer
|
|
86
|
+
Path(facade.CLAUDE_DIR) / "token-optimizer"] # install.sh's clone that link points into
|
|
87
|
+
for get in (lambda: Path(facade.MEASURE_PY_PATH).parents[3],
|
|
88
|
+
lambda: Path(facade.__file__).resolve().parents[3],
|
|
89
|
+
lambda: Path(facade._find_plugin_hooks_json()).parent.parent):
|
|
90
|
+
try:
|
|
91
|
+
roots.append(get())
|
|
92
|
+
except Exception:
|
|
93
|
+
pass
|
|
94
|
+
return roots
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def is_install_script(facade, path):
|
|
98
|
+
"""True when ``path`` is a Token Optimizer install's measure.py: this copy,
|
|
99
|
+
the script install (skill link or its clone), the plugin root hooks.json names, any plugin-cache
|
|
100
|
+
version (one since removed included), or the placeholder spelling."""
|
|
101
|
+
if path == _PLACEHOLDER_SCRIPT:
|
|
102
|
+
return True
|
|
103
|
+
text = str(path).replace("\\", "/")
|
|
104
|
+
if not _absolute(text):
|
|
105
|
+
return False
|
|
106
|
+
parts = _path_parts(text)
|
|
107
|
+
if parts[-4:] != _path_parts("/".join(_SCRIPT_TAIL)) or "." in parts or ".." in parts:
|
|
108
|
+
return False
|
|
109
|
+
head = parts[:-4]
|
|
110
|
+
if any(head == _path_parts(root) for root in _install_roots(facade)):
|
|
111
|
+
return True
|
|
112
|
+
# Any marketplace: Claude Code names the cache dir after the plugin, our
|
|
113
|
+
# marketplace has been renamed and mirrored, and this path only proposes a
|
|
114
|
+
# candidate; the whole command must still equal one we generated.
|
|
115
|
+
cache = _path_parts(Path(facade.CLAUDE_DIR) / "plugins" / "cache")
|
|
116
|
+
return len(head) == len(cache) + 3 and head[:len(cache)] == cache and head[-2] == "token-optimizer"
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _absolute(text):
|
|
120
|
+
text = str(text).replace("\\", "/")
|
|
121
|
+
return text.startswith("/") or (len(text) > 2 and text[1] == ":" and text[2] == "/")
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def matches_shape(facade, command, shapes):
|
|
125
|
+
"""``command`` is exactly one of ``shapes`` rebuilt from its own measure.py
|
|
126
|
+
and interpreter tokens, with that measure.py an install's. The tokens only
|
|
127
|
+
propose candidates; byte equality of the rebuilt command decides."""
|
|
128
|
+
for tokens in _token_views(command):
|
|
129
|
+
for i, token in enumerate(tokens):
|
|
130
|
+
if not token.endswith("measure.py") or not is_install_script(facade, token):
|
|
131
|
+
continue
|
|
132
|
+
for py in {"python3", tokens[i - 1] if i else "python3"}:
|
|
133
|
+
if not _our_interpreter(py):
|
|
134
|
+
continue # a wrapper (sudo, env, nice) is not a command we wrote
|
|
135
|
+
for shape in shapes:
|
|
136
|
+
try:
|
|
137
|
+
if shape(py, token) == command:
|
|
138
|
+
return True
|
|
139
|
+
except Exception:
|
|
140
|
+
continue
|
|
141
|
+
return False
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _our_interpreter(token):
|
|
145
|
+
"""An interpreter token our generators wrote: bare python3 (POSIX shapes)
|
|
146
|
+
or sys.executable, an absolute path to a CPython or PyPy binary (Windows
|
|
147
|
+
shapes): python / python3 / python3.N, free-threaded or debug builds
|
|
148
|
+
(python3.13t, python3.13d, python3.12-dbg, python_d.exe), pythonw, and
|
|
149
|
+
pypy / pypy3 / pypy3.N, each with or without .exe. Never a ``py``
|
|
150
|
+
launcher or a wrapper: no generator emitted one."""
|
|
151
|
+
if token == "python3":
|
|
152
|
+
return True
|
|
153
|
+
if not _absolute(token):
|
|
154
|
+
return False
|
|
155
|
+
parts = _path_parts(token)
|
|
156
|
+
name = parts[-1].lower() if parts else ""
|
|
157
|
+
for suffix in (".exe", "-dbg", "_d", "w"):
|
|
158
|
+
if name[-len(suffix):] == suffix:
|
|
159
|
+
name = name[:-len(suffix)]
|
|
160
|
+
for family in ("python", "pypy"):
|
|
161
|
+
if name[:len(family)] != family:
|
|
162
|
+
continue
|
|
163
|
+
version = name[len(family):]
|
|
164
|
+
if family == "python" and version[:1] == "w":
|
|
165
|
+
version = version[1:] # pythonw3.13t.exe
|
|
166
|
+
for flag in ("d", "t"): # ABI flags, in CPython's order (3.13td)
|
|
167
|
+
if version[-1:] == flag and version[:-1]:
|
|
168
|
+
version = version[:-1]
|
|
169
|
+
return all(c.isdigit() or c == "." for c in version) and ".." not in version \
|
|
170
|
+
and version[:1] != "." and version[-1:] != "."
|
|
171
|
+
return False
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _token_views(command):
|
|
175
|
+
"""POSIX shell tokens, plus cmd-style tokens (list2cmdline output, where a
|
|
176
|
+
backslash is a plain path separator) with one pair of quotes removed."""
|
|
177
|
+
views = []
|
|
178
|
+
for posix in (True, False):
|
|
179
|
+
try:
|
|
180
|
+
tokens = shlex.split(command, posix=posix)
|
|
181
|
+
except ValueError:
|
|
182
|
+
continue
|
|
183
|
+
if not posix:
|
|
184
|
+
tokens = [t[1:-1] if len(t) > 1 and t[0] == t[-1] == '"' else t for t in tokens]
|
|
185
|
+
views.append(tokens)
|
|
186
|
+
return views
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def owner(facade, shapes):
|
|
190
|
+
"""``owns(event, group, hook)`` for one pass: proven ours in its context,
|
|
191
|
+
or an exact generated shape. Proof is loaded on first use only."""
|
|
192
|
+
cache = []
|
|
193
|
+
|
|
194
|
+
def owns(event, group, hook):
|
|
195
|
+
context = hp.entry_context(event, group, hook)
|
|
196
|
+
if context is None:
|
|
197
|
+
return False
|
|
198
|
+
if not cache:
|
|
199
|
+
dest = hook_heal._resolved(facade.SETTINGS_PATH)
|
|
200
|
+
cache.append(hp.Provenance.from_facade(facade, settings_path=dest or facade.SETTINGS_PATH))
|
|
201
|
+
return bool(cache[0].proof(context[3], context[:3])) or matches_shape(facade, context[3], shapes)
|
|
202
|
+
return owns
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _entries(groups):
|
|
206
|
+
"""``(group, hook)`` for every hook dict under a list of groups."""
|
|
207
|
+
for group in groups if isinstance(groups, list) else ():
|
|
208
|
+
entries = group.get("hooks") if isinstance(group, dict) else None
|
|
209
|
+
for hook in entries if isinstance(entries, list) else ():
|
|
210
|
+
if isinstance(hook, dict):
|
|
211
|
+
yield group, hook
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _map_groups(hooks, event, fn):
|
|
215
|
+
"""Apply ``fn(group, hook)`` to each hook dict in ``hooks[event]``: it
|
|
216
|
+
returns the hook (kept), a replacement, or None (dropped). A group emptied
|
|
217
|
+
by drops goes; an untouched group stays the same object. Returns
|
|
218
|
+
``(dropped, replaced)``."""
|
|
219
|
+
groups = hooks.get(event)
|
|
220
|
+
if not isinstance(groups, list):
|
|
221
|
+
return 0, 0
|
|
222
|
+
dropped = replaced = 0
|
|
223
|
+
new_groups = []
|
|
224
|
+
for group in groups:
|
|
225
|
+
entries = group.get("hooks") if isinstance(group, dict) else None
|
|
226
|
+
if not isinstance(entries, list):
|
|
227
|
+
new_groups.append(group)
|
|
228
|
+
continue
|
|
229
|
+
out = []
|
|
230
|
+
for hook in entries:
|
|
231
|
+
new = fn(group, hook) if isinstance(hook, dict) else hook
|
|
232
|
+
if new is None:
|
|
233
|
+
dropped += 1
|
|
234
|
+
else:
|
|
235
|
+
replaced += new is not hook
|
|
236
|
+
out.append(new)
|
|
237
|
+
if len(out) == len(entries) and all(x is y for x, y in zip(out, entries)):
|
|
238
|
+
new_groups.append(group)
|
|
239
|
+
elif out:
|
|
240
|
+
new_groups.append(dict(group, hooks=out))
|
|
241
|
+
if dropped or replaced:
|
|
242
|
+
if new_groups:
|
|
243
|
+
hooks[event] = new_groups
|
|
244
|
+
else:
|
|
245
|
+
hooks.pop(event, None)
|
|
246
|
+
return dropped, replaced
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _filter_groups(hooks, event, drop):
|
|
250
|
+
"""Drop the hooks ``drop(group, hook)`` selects; returns how many."""
|
|
251
|
+
return _map_groups(hooks, event, lambda g, h: None if drop(g, h) else h)[0]
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _plugin_provides_stop_flush(facade):
|
|
255
|
+
try:
|
|
256
|
+
if not facade._is_plugin_installed():
|
|
257
|
+
return False
|
|
258
|
+
path = facade._find_plugin_hooks_json()
|
|
259
|
+
plugin = json.loads(Path(path).read_text(encoding="utf-8")) if path else {}
|
|
260
|
+
return any(facade._sessionend_cmd_is_flush(hook.get("command", ""))
|
|
261
|
+
for _, hook in _entries((plugin.get("hooks") or {}).get("Stop")))
|
|
262
|
+
except (OSError, ValueError, TypeError, AttributeError):
|
|
263
|
+
return False
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def apply_fossil_reconcile(facade, settings, result):
|
|
267
|
+
"""lifecycle._apply_sessionend_fossil_reconcile, on our entries only.
|
|
268
|
+
|
|
269
|
+
SessionEnd: each collect/dashboard fossil of ours is rewritten in place to
|
|
270
|
+
HOOK_COMMAND, or removed when a current flush of ours is already there.
|
|
271
|
+
Stop: our collect fossils go, and so does every flush of ours after the
|
|
272
|
+
first (all of them when the plugin's hooks.json provides the Stop flush).
|
|
273
|
+
Anything not ours is left byte for byte. Returns True if anything changed;
|
|
274
|
+
``result`` counts this call's changes."""
|
|
275
|
+
hooks = settings.get("hooks") if isinstance(settings, dict) else None
|
|
276
|
+
if not isinstance(hooks, dict):
|
|
277
|
+
return False
|
|
278
|
+
owns = owner(facade, SESSION_END_SHAPES)
|
|
279
|
+
flush, fossil = facade._sessionend_cmd_is_flush, facade._sessionend_cmd_is_collect_fossil
|
|
280
|
+
|
|
281
|
+
def ours(event, group, hook, shape):
|
|
282
|
+
return shape(hook.get("command", "")) and owns(event, group, hook)
|
|
283
|
+
|
|
284
|
+
has_current = [any(ours("SessionEnd", g, h, flush) for g, h in _entries(hooks.get("SessionEnd")))]
|
|
285
|
+
|
|
286
|
+
def heal_session_end(group, hook):
|
|
287
|
+
if not ours("SessionEnd", group, hook, fossil):
|
|
288
|
+
return hook
|
|
289
|
+
if has_current[0]:
|
|
290
|
+
result["removed"] += 1
|
|
291
|
+
return None
|
|
292
|
+
result["rewritten"] += 1
|
|
293
|
+
has_current[0] = True
|
|
294
|
+
return facade._rewrite_collect_fossil_hook(hook)
|
|
295
|
+
|
|
296
|
+
changed = any(_map_groups(hooks, "SessionEnd", heal_session_end))
|
|
297
|
+
provides, seen = _plugin_provides_stop_flush(facade), [False]
|
|
298
|
+
|
|
299
|
+
def drop_stop(group, hook):
|
|
300
|
+
if ours("Stop", group, hook, fossil):
|
|
301
|
+
return True
|
|
302
|
+
if ours("Stop", group, hook, flush):
|
|
303
|
+
if provides or seen[0]:
|
|
304
|
+
return True
|
|
305
|
+
seen[0] = True
|
|
306
|
+
return False
|
|
307
|
+
|
|
308
|
+
stop_removed = _filter_groups(hooks, "Stop", drop_stop)
|
|
309
|
+
result["stop_removed"] += stop_removed
|
|
310
|
+
return changed or stop_removed > 0
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def remove_session_end(facade, settings):
|
|
314
|
+
"""setup_hook --uninstall / cleanup: drop our SessionEnd hooks only."""
|
|
315
|
+
hooks = settings.get("hooks") if isinstance(settings, dict) else None
|
|
316
|
+
if not isinstance(hooks, dict):
|
|
317
|
+
return 0
|
|
318
|
+
owns = owner(facade, SESSION_END_SHAPES)
|
|
319
|
+
return _filter_groups(hooks, "SessionEnd", lambda group, hook: (
|
|
320
|
+
facade._is_token_optimizer_session_end_hook(hook) and owns("SessionEnd", group, hook)))
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def session_end_view(facade, settings):
|
|
324
|
+
"""``settings`` reduced to our own SessionEnd hooks, for setup_hook's
|
|
325
|
+
installed / up-to-date check: a user's own measure.py session-end-flush
|
|
326
|
+
must never read as ours and make setup_hook skip installing it."""
|
|
327
|
+
hooks = settings.get("hooks") if isinstance(settings, dict) else None
|
|
328
|
+
groups = hooks.get("SessionEnd") if isinstance(hooks, dict) else None
|
|
329
|
+
owns = owner(facade, SESSION_END_SHAPES)
|
|
330
|
+
mine = [hook for group, hook in _entries(groups) if owns("SessionEnd", group, hook)]
|
|
331
|
+
return {"hooks": {"SessionEnd": [{"hooks": mine}]}}
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def replace_session_end_fossil(facade, hooks, new_hook):
|
|
335
|
+
"""setup_hook's upgrade: in each SessionEnd group, our first fossil
|
|
336
|
+
becomes ``new_hook``. True when one was replaced; with none of ours,
|
|
337
|
+
the caller installs alongside instead."""
|
|
338
|
+
owns, replaced = owner(facade, SESSION_END_SHAPES), False
|
|
339
|
+
groups = hooks.get("SessionEnd") if isinstance(hooks, dict) else None
|
|
340
|
+
for group in groups if isinstance(groups, list) else ():
|
|
341
|
+
entries = group.get("hooks") if isinstance(group, dict) else None
|
|
342
|
+
for i, hook in enumerate(entries if isinstance(entries, list) else ()):
|
|
343
|
+
if isinstance(hook, dict) and facade._sessionend_cmd_is_collect_fossil(hook.get("command", "")) \
|
|
344
|
+
and owns("SessionEnd", group, hook):
|
|
345
|
+
entries[i] = new_hook
|
|
346
|
+
replaced = True
|
|
347
|
+
break
|
|
348
|
+
return replaced
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def remove_smart_compact(facade, settings):
|
|
352
|
+
"""setup_smart_compact --uninstall: drop our compact-capture /
|
|
353
|
+
compact-restore entries from its four events. Returns hooks removed."""
|
|
354
|
+
hooks = settings.get("hooks") if isinstance(settings, dict) else None
|
|
355
|
+
if not isinstance(hooks, dict):
|
|
356
|
+
return 0
|
|
357
|
+
owns = owner(facade, COMPACT_SHAPES)
|
|
358
|
+
removed = 0
|
|
359
|
+
for event in ("PreCompact", "SessionStart", "Stop", "SessionEnd"):
|
|
360
|
+
removed += _filter_groups(hooks, event, lambda group, hook, event=event: (
|
|
361
|
+
isinstance(hook.get("command"), str)
|
|
362
|
+
and ("compact-capture" in hook["command"] or "compact-restore" in hook["command"])
|
|
363
|
+
and owns(event, group, hook)))
|
|
364
|
+
return removed
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def _cache_roots_named(facade, command):
|
|
368
|
+
"""Plugin-cache version roots (.../plugins/cache/<m>/token-optimizer/<v>)
|
|
369
|
+
a command names, removed versions included. Candidates only."""
|
|
370
|
+
roots = []
|
|
371
|
+
for cache in {str(Path(facade.CLAUDE_DIR) / "plugins" / "cache"),
|
|
372
|
+
str(Path(facade.CLAUDE_DIR) / "plugins" / "cache").replace("\\", "/")}:
|
|
373
|
+
start = 0
|
|
374
|
+
while True:
|
|
375
|
+
at = command.find(cache, start)
|
|
376
|
+
if at < 0:
|
|
377
|
+
break
|
|
378
|
+
start = at + len(cache)
|
|
379
|
+
rest = command[start:].replace("\\", "/").split("/")
|
|
380
|
+
if len(rest) > 3 and rest[0] == "" and rest[2] == "token-optimizer":
|
|
381
|
+
version = rest[3]
|
|
382
|
+
for stop in ("'", '"', " ", ";", ")"):
|
|
383
|
+
version = version.split(stop)[0]
|
|
384
|
+
if version and version not in (".", ".."):
|
|
385
|
+
roots.append(str(Path(cache) / rest[1] / "token-optimizer" / version))
|
|
386
|
+
return roots
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def cleanup_owner(facade):
|
|
390
|
+
"""``owns(event, group, hook)`` for measure.py cleanup: proven ours only.
|
|
391
|
+
|
|
392
|
+
Ours when the entry is proven in its context (ledger, or a shipped
|
|
393
|
+
hooks.json entry for this install), or is a shipped hooks.json entry
|
|
394
|
+
instantiated for an install root the command itself names (a removed
|
|
395
|
+
plugin version, the script-install clone, the ${CLAUDE_PLUGIN_ROOT}
|
|
396
|
+
spelling), or is an examples/hooks-starter.json entry pasted as shipped,
|
|
397
|
+
or is byte-identical to a SessionEnd, smart-compact or quality-bar command
|
|
398
|
+
we generated for an install's measure.py. Naming our subcommands or
|
|
399
|
+
scripts proves nothing."""
|
|
400
|
+
base = owner(facade, SESSION_END_SHAPES + COMPACT_SHAPES + QUALITY_SHAPES)
|
|
401
|
+
fixed = [str(r) for r in _install_roots(facade)] + ["${CLAUDE_PLUGIN_ROOT}"]
|
|
402
|
+
cache = {}
|
|
403
|
+
|
|
404
|
+
def instantiated(roots):
|
|
405
|
+
key = tuple(sorted(set(roots)))
|
|
406
|
+
if key not in cache:
|
|
407
|
+
cache[key] = hp.instantiate_contexts(hp.SHIPPED_HOOK_CONTEXTS, list(key),
|
|
408
|
+
getattr(facade, "_resolve_hook_command", None))
|
|
409
|
+
return cache[key]
|
|
410
|
+
|
|
411
|
+
def owns(event, group, hook):
|
|
412
|
+
if base(event, group, hook):
|
|
413
|
+
return True
|
|
414
|
+
context = hp.entry_context(event, group, hook)
|
|
415
|
+
if context is None:
|
|
416
|
+
return False
|
|
417
|
+
if context in STARTER_HOOK_CONTEXTS:
|
|
418
|
+
return True
|
|
419
|
+
return context in instantiated(fixed + _cache_roots_named(facade, context[3]))
|
|
420
|
+
return owns
|