@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
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
"""Definition-only implementations; mutable state belongs to measure."""
|
|
2
2
|
from __future__ import annotations
|
|
3
|
-
from . import _compat
|
|
4
|
-
|
|
3
|
+
from . import _compat, dashboard_history
|
|
5
4
|
|
|
6
5
|
def _settings_lock(user_initiated=None):
|
|
7
6
|
"""Bounded portable lease for settings.json writes.
|
|
@@ -25,7 +24,6 @@ def _settings_lock(user_initiated=None):
|
|
|
25
24
|
) as acquired:
|
|
26
25
|
yield acquired
|
|
27
26
|
|
|
28
|
-
|
|
29
27
|
def _acquire_session_end_flush_lock(max_age_seconds=None):
|
|
30
28
|
"""Return a lock directory path, or None if another worker is active."""
|
|
31
29
|
_measure_facade = _compat.facade()
|
|
@@ -50,7 +48,6 @@ def _acquire_session_end_flush_lock(max_age_seconds=None):
|
|
|
50
48
|
except OSError:
|
|
51
49
|
return None
|
|
52
50
|
|
|
53
|
-
|
|
54
51
|
def _release_session_end_flush_lock(lock_dir):
|
|
55
52
|
_measure_facade = _compat.facade()
|
|
56
53
|
if not lock_dir:
|
|
@@ -259,7 +256,7 @@ def _run_session_end_flush_worker(args, budget_seconds=None):
|
|
|
259
256
|
# No browser in a cloud VM: the 4 MB dashboard rebuild is skipped
|
|
260
257
|
# there (an explicit /token-dashboard still builds it on demand).
|
|
261
258
|
if not _lean and not (_measure_facade._dashboard_hook_backoff_active() or _measure_facade._dashboard_selfheal_inflight()):
|
|
262
|
-
_measure_facade.generate_standalone_dashboard(
|
|
259
|
+
_measure_facade.generate_standalone_dashboard(quiet=True)
|
|
263
260
|
except _measure_facade._HookTimeout:
|
|
264
261
|
# Gap 4: the bounded SessionEnd regen was killed by the 20s budget
|
|
265
262
|
# (a large history's 4 MB build does not fit), so it may have left
|
|
@@ -268,7 +265,7 @@ def _run_session_end_flush_worker(args, budget_seconds=None):
|
|
|
268
265
|
# file catches up off the hot path instead of waiting for the user
|
|
269
266
|
# to re-open. Re-raised so the outer handler still runs cleanup.
|
|
270
267
|
try:
|
|
271
|
-
_measure_facade._spawn_detached_dashboard_selfheal(
|
|
268
|
+
_measure_facade._spawn_detached_dashboard_selfheal()
|
|
272
269
|
except Exception:
|
|
273
270
|
pass
|
|
274
271
|
raise
|
|
@@ -667,6 +664,8 @@ def _spawn_detached_dashboard_selfheal(days=None, force=None, *, hook_timeout=No
|
|
|
667
664
|
# Detach so the child outlives the killed hook: POSIX new session, or
|
|
668
665
|
# (on Windows) DETACHED_PROCESS. start_new_session is POSIX-only.
|
|
669
666
|
popen_kw = {} if _measure_facade.os.name == "nt" else {"start_new_session": True}
|
|
667
|
+
if days is None:
|
|
668
|
+
days = dashboard_history.selected_days(_measure_facade.RUNTIME_DIR, _measure_facade.TRENDS_DB)
|
|
670
669
|
argv = [_measure_facade.sys.executable, _measure_facade.os.path.abspath(_measure_facade.__file__),
|
|
671
670
|
"dashboard", "--quiet", "--days", str(int(days))]
|
|
672
671
|
if force:
|
|
@@ -926,12 +925,13 @@ def _is_compaction_runner(cmd, event):
|
|
|
926
925
|
|
|
927
926
|
|
|
928
927
|
def _is_hook_installed(settings=None, settings_only=None):
|
|
929
|
-
"""Check if
|
|
928
|
+
"""Check if Token Optimizer's own SessionEnd hook is installed.
|
|
930
929
|
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
930
|
+
Counts only settings.json SessionEnd entries owned_hooks proves are ours
|
|
931
|
+
(old collect, collect + dashboard and session-end-flush shapes alike), so
|
|
932
|
+
a user's own measure.py never reads as ours. Also checks plugin cache
|
|
933
|
+
hooks (auto-installed via marketplace plugin), unless ``settings_only``
|
|
934
|
+
asks only whether settings.json carries it (doctor's label).
|
|
935
935
|
"""
|
|
936
936
|
# Check user settings.json
|
|
937
937
|
_measure_facade = _compat.facade()
|
|
@@ -945,8 +945,8 @@ def _is_hook_installed(settings=None, settings_only=None):
|
|
|
945
945
|
else:
|
|
946
946
|
settings = {}
|
|
947
947
|
|
|
948
|
-
|
|
949
|
-
session_end =
|
|
948
|
+
import owned_hooks
|
|
949
|
+
session_end = owned_hooks.session_end_view(_measure_facade, settings)["hooks"]["SessionEnd"]
|
|
950
950
|
if isinstance(session_end, list):
|
|
951
951
|
for entry in session_end:
|
|
952
952
|
hook_list = entry.get("hooks", []) if isinstance(entry, dict) else []
|
|
@@ -1007,7 +1007,8 @@ def _sessionend_cmd_is_collect_fossil(cmd) -> bool:
|
|
|
1007
1007
|
|
|
1008
1008
|
|
|
1009
1009
|
def _is_hook_current(settings=None):
|
|
1010
|
-
"""True when
|
|
1010
|
+
"""True when our own installed SessionEnd hook (owned_hooks) is the
|
|
1011
|
+
session-end-flush shape.
|
|
1011
1012
|
|
|
1012
1013
|
The collect-then-dashboard fossil is never current: it runs the
|
|
1013
1014
|
heavy flush inline and unbounded. The pre-v5.11 win32 cmd-null-redirect
|
|
@@ -1024,11 +1025,8 @@ def _is_hook_current(settings=None):
|
|
|
1024
1025
|
except (_measure_facade.json.JSONDecodeError, PermissionError, OSError):
|
|
1025
1026
|
return False
|
|
1026
1027
|
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
if not isinstance(session_end, list):
|
|
1030
|
-
return False
|
|
1031
|
-
for entry in session_end:
|
|
1028
|
+
import owned_hooks
|
|
1029
|
+
for entry in owned_hooks.session_end_view(_measure_facade, settings)["hooks"]["SessionEnd"]:
|
|
1032
1030
|
hook_list = entry.get("hooks", []) if isinstance(entry, dict) else []
|
|
1033
1031
|
for hook in hook_list:
|
|
1034
1032
|
cmd = hook.get("command", "") if isinstance(hook, dict) else ""
|
|
@@ -1584,60 +1582,22 @@ def _is_token_optimizer_session_end_hook(hook: dict) -> bool:
|
|
|
1584
1582
|
def _remove_token_optimizer_session_end_hooks(settings: dict) -> int:
|
|
1585
1583
|
"""Strip Token Optimizer's SessionEnd hooks from ``settings`` in place.
|
|
1586
1584
|
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
``SessionEnd`` ends up empty, the key is dropped. Returns the count of
|
|
1592
|
-
Token Optimizer hook entries removed. Never raises.
|
|
1585
|
+
Only entries Token Optimizer can prove are its own (owned_hooks.remove_session_end):
|
|
1586
|
+
a user's own measure.py hook and ALL other hook events are left intact.
|
|
1587
|
+
Empty groups are removed; if ``SessionEnd`` ends up empty, the key is
|
|
1588
|
+
dropped. Returns the count of hook entries removed. Never raises.
|
|
1593
1589
|
"""
|
|
1594
1590
|
_measure_facade = _compat.facade()
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
hooks = settings.get("hooks")
|
|
1598
|
-
if not isinstance(hooks, dict):
|
|
1599
|
-
return 0
|
|
1600
|
-
session_end = hooks.get("SessionEnd")
|
|
1601
|
-
if not isinstance(session_end, list) or not session_end:
|
|
1602
|
-
return 0
|
|
1603
|
-
removed = 0
|
|
1604
|
-
new_groups = []
|
|
1605
|
-
for group in session_end:
|
|
1606
|
-
if not isinstance(group, dict):
|
|
1607
|
-
new_groups.append(group)
|
|
1608
|
-
continue
|
|
1609
|
-
hook_list = group.get("hooks")
|
|
1610
|
-
if not isinstance(hook_list, list):
|
|
1611
|
-
new_groups.append(group)
|
|
1612
|
-
continue
|
|
1613
|
-
kept_hooks = [h for h in hook_list if not _measure_facade._is_token_optimizer_session_end_hook(h)]
|
|
1614
|
-
removed += len(hook_list) - len(kept_hooks)
|
|
1615
|
-
if kept_hooks:
|
|
1616
|
-
group["hooks"] = kept_hooks
|
|
1617
|
-
new_groups.append(group)
|
|
1618
|
-
if new_groups:
|
|
1619
|
-
hooks["SessionEnd"] = new_groups
|
|
1620
|
-
else:
|
|
1621
|
-
hooks.pop("SessionEnd", None)
|
|
1622
|
-
return removed
|
|
1591
|
+
import owned_hooks
|
|
1592
|
+
return owned_hooks.remove_session_end(_measure_facade, settings)
|
|
1623
1593
|
|
|
1624
1594
|
|
|
1625
1595
|
def _sessionend_has_current_flush(settings: dict) -> bool:
|
|
1626
|
-
"""True when settings.json already has
|
|
1596
|
+
"""True when settings.json already has our own session-end-flush SessionEnd hook."""
|
|
1627
1597
|
_measure_facade = _compat.facade()
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
session_end = hooks.get("SessionEnd")
|
|
1632
|
-
if not isinstance(session_end, list):
|
|
1633
|
-
return False
|
|
1634
|
-
for group in session_end:
|
|
1635
|
-
if not isinstance(group, dict):
|
|
1636
|
-
continue
|
|
1637
|
-
for hook in group.get("hooks", []) or []:
|
|
1638
|
-
if isinstance(hook, dict) and _measure_facade._sessionend_cmd_is_flush(hook.get("command", "")):
|
|
1639
|
-
return True
|
|
1640
|
-
return False
|
|
1598
|
+
import owned_hooks
|
|
1599
|
+
ours = owned_hooks.session_end_view(_measure_facade, settings)["hooks"]["SessionEnd"][0]["hooks"]
|
|
1600
|
+
return any(_measure_facade._sessionend_cmd_is_flush(hook.get("command", "")) for hook in ours)
|
|
1641
1601
|
|
|
1642
1602
|
|
|
1643
1603
|
def _rewrite_collect_fossil_hook(hook: dict) -> dict:
|
|
@@ -1656,133 +1616,17 @@ def _rewrite_collect_fossil_hook(hook: dict) -> dict:
|
|
|
1656
1616
|
|
|
1657
1617
|
|
|
1658
1618
|
def _apply_sessionend_fossil_reconcile(settings, result):
|
|
1659
|
-
"""Apply the fossil heal mutation to ``settings`` in place
|
|
1619
|
+
"""Apply the fossil heal mutation to ``settings`` in place, on entries
|
|
1620
|
+
Token Optimizer can prove are its own only (owned_hooks.apply_fossil_reconcile).
|
|
1660
1621
|
|
|
1661
1622
|
Returns True if anything changed. The ``result`` counters (``rewritten`` /
|
|
1662
1623
|
``removed`` / ``stop_removed``) are incremented for the changes made in
|
|
1663
|
-
THIS call only. Idempotent
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
Extracted from ``_reconcile_sessionend_fossils`` so the caller can re-read
|
|
1667
|
-
fresh under the lease and re-apply instead of writing a
|
|
1668
|
-
snapshot that was read unlocked. If a current-shape session-end-flush
|
|
1669
|
-
SessionEnd hook already exists, collect/dashboard fossils are removed.
|
|
1670
|
-
Otherwise each fossil is rewritten in place to HOOK_COMMAND (preserving
|
|
1671
|
-
async/timeout; adding async:true when absent). Also drops Stop-event
|
|
1672
|
-
collect / bare session-end-flush duplicates when the plugin already
|
|
1673
|
-
provides Stop.
|
|
1624
|
+
THIS call only. Idempotent. Extracted from ``_reconcile_sessionend_fossils``
|
|
1625
|
+
so the caller can re-read fresh under the lease and re-apply.
|
|
1674
1626
|
"""
|
|
1675
1627
|
_measure_facade = _compat.facade()
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
return False
|
|
1679
|
-
|
|
1680
|
-
has_current = _measure_facade._sessionend_has_current_flush(settings)
|
|
1681
|
-
mutated = False
|
|
1682
|
-
|
|
1683
|
-
session_end = hooks.get("SessionEnd")
|
|
1684
|
-
if isinstance(session_end, list) and session_end:
|
|
1685
|
-
new_groups = []
|
|
1686
|
-
for group in session_end:
|
|
1687
|
-
if not isinstance(group, dict):
|
|
1688
|
-
new_groups.append(group)
|
|
1689
|
-
continue
|
|
1690
|
-
hook_list = group.get("hooks")
|
|
1691
|
-
if not isinstance(hook_list, list):
|
|
1692
|
-
new_groups.append(group)
|
|
1693
|
-
continue
|
|
1694
|
-
kept = []
|
|
1695
|
-
for hook in hook_list:
|
|
1696
|
-
if not isinstance(hook, dict):
|
|
1697
|
-
kept.append(hook)
|
|
1698
|
-
continue
|
|
1699
|
-
cmd = hook.get("command", "")
|
|
1700
|
-
if not _measure_facade._sessionend_cmd_is_collect_fossil(cmd):
|
|
1701
|
-
kept.append(hook)
|
|
1702
|
-
continue
|
|
1703
|
-
if has_current:
|
|
1704
|
-
result["removed"] += 1
|
|
1705
|
-
mutated = True
|
|
1706
|
-
continue
|
|
1707
|
-
kept.append(_measure_facade._rewrite_collect_fossil_hook(hook))
|
|
1708
|
-
result["rewritten"] += 1
|
|
1709
|
-
mutated = True
|
|
1710
|
-
has_current = True
|
|
1711
|
-
if kept:
|
|
1712
|
-
group = dict(group)
|
|
1713
|
-
group["hooks"] = kept
|
|
1714
|
-
new_groups.append(group)
|
|
1715
|
-
if mutated:
|
|
1716
|
-
if new_groups:
|
|
1717
|
-
hooks["SessionEnd"] = new_groups
|
|
1718
|
-
else:
|
|
1719
|
-
hooks.pop("SessionEnd", None)
|
|
1720
|
-
|
|
1721
|
-
# Stop event: drop collect fossils and extra session-end-flush entries
|
|
1722
|
-
# when a plugin-provided (or already-present) Stop flush exists. The
|
|
1723
|
-
# first flush-shaped Stop hook is kept; extras and collect fossils go.
|
|
1724
|
-
stop = hooks.get("Stop")
|
|
1725
|
-
if isinstance(stop, list) and stop:
|
|
1726
|
-
plugin_provides_stop_flush = False
|
|
1727
|
-
try:
|
|
1728
|
-
if _measure_facade._is_plugin_installed():
|
|
1729
|
-
plugin_hooks_path = _measure_facade._find_plugin_hooks_json()
|
|
1730
|
-
if plugin_hooks_path:
|
|
1731
|
-
plugin_hooks = _measure_facade.json.loads(plugin_hooks_path.read_text(encoding="utf-8"))
|
|
1732
|
-
for group in (plugin_hooks.get("hooks") or {}).get("Stop") or []:
|
|
1733
|
-
if not isinstance(group, dict):
|
|
1734
|
-
continue
|
|
1735
|
-
for hook in group.get("hooks") or []:
|
|
1736
|
-
if isinstance(hook, dict) and _measure_facade._sessionend_cmd_is_flush(
|
|
1737
|
-
hook.get("command", "")
|
|
1738
|
-
):
|
|
1739
|
-
plugin_provides_stop_flush = True
|
|
1740
|
-
break
|
|
1741
|
-
except (OSError, _measure_facade.json.JSONDecodeError, TypeError, ValueError):
|
|
1742
|
-
plugin_provides_stop_flush = False
|
|
1743
|
-
|
|
1744
|
-
saw_stop_flush = False
|
|
1745
|
-
new_stop_groups = []
|
|
1746
|
-
stop_mutated = False
|
|
1747
|
-
for group in stop:
|
|
1748
|
-
if not isinstance(group, dict):
|
|
1749
|
-
new_stop_groups.append(group)
|
|
1750
|
-
continue
|
|
1751
|
-
hook_list = group.get("hooks")
|
|
1752
|
-
if not isinstance(hook_list, list):
|
|
1753
|
-
new_stop_groups.append(group)
|
|
1754
|
-
continue
|
|
1755
|
-
kept = []
|
|
1756
|
-
for hook in hook_list:
|
|
1757
|
-
if not isinstance(hook, dict):
|
|
1758
|
-
kept.append(hook)
|
|
1759
|
-
continue
|
|
1760
|
-
cmd = hook.get("command", "")
|
|
1761
|
-
is_collect = _measure_facade._sessionend_cmd_is_collect_fossil(cmd)
|
|
1762
|
-
is_flush = _measure_facade._sessionend_cmd_is_flush(cmd)
|
|
1763
|
-
if is_collect:
|
|
1764
|
-
result["stop_removed"] += 1
|
|
1765
|
-
stop_mutated = True
|
|
1766
|
-
continue
|
|
1767
|
-
if is_flush:
|
|
1768
|
-
if plugin_provides_stop_flush or saw_stop_flush:
|
|
1769
|
-
result["stop_removed"] += 1
|
|
1770
|
-
stop_mutated = True
|
|
1771
|
-
continue
|
|
1772
|
-
saw_stop_flush = True
|
|
1773
|
-
kept.append(hook)
|
|
1774
|
-
if kept:
|
|
1775
|
-
group = dict(group)
|
|
1776
|
-
group["hooks"] = kept
|
|
1777
|
-
new_stop_groups.append(group)
|
|
1778
|
-
if stop_mutated:
|
|
1779
|
-
mutated = True
|
|
1780
|
-
if new_stop_groups:
|
|
1781
|
-
hooks["Stop"] = new_stop_groups
|
|
1782
|
-
else:
|
|
1783
|
-
hooks.pop("Stop", None)
|
|
1784
|
-
|
|
1785
|
-
return mutated
|
|
1628
|
+
import owned_hooks
|
|
1629
|
+
return owned_hooks.apply_fossil_reconcile(_measure_facade, settings, result)
|
|
1786
1630
|
|
|
1787
1631
|
|
|
1788
1632
|
def _reconcile_sessionend_fossils():
|
|
@@ -1886,12 +1730,16 @@ def _reconcile_sessionend_fossils():
|
|
|
1886
1730
|
if not isinstance(fresh.get("hooks"), dict):
|
|
1887
1731
|
result["reason"] = "no_hooks"
|
|
1888
1732
|
return result
|
|
1733
|
+
import hook_provenance
|
|
1734
|
+
before = hook_provenance.contexts_of(fresh)
|
|
1889
1735
|
if not _measure_facade._apply_sessionend_fossil_reconcile(fresh, result):
|
|
1890
1736
|
result["reason"] = "nothing_to_do"
|
|
1891
1737
|
return result
|
|
1892
1738
|
if not _measure_facade._write_settings_atomic_locked(fresh):
|
|
1893
1739
|
result["reason"] = "write_skipped"
|
|
1894
1740
|
return result
|
|
1741
|
+
hook_provenance.record_written(_measure_facade, before, fresh, [_measure_facade.HOOK_COMMAND],
|
|
1742
|
+
"sessionend_fossil_reconcile")
|
|
1895
1743
|
return result
|
|
1896
1744
|
except Exception:
|
|
1897
1745
|
result["reason"] = "fail_open"
|
|
@@ -2020,7 +1868,7 @@ def setup_hook(dry_run=None, uninstall=None, user_initiated=None):
|
|
|
2020
1868
|
_measure_facade.sys.exit(1)
|
|
2021
1869
|
return
|
|
2022
1870
|
|
|
2023
|
-
#
|
|
1871
|
+
# Installed / up to date counts only our own SessionEnd hook (owned_hooks).
|
|
2024
1872
|
installed = _measure_facade._is_hook_installed(settings)
|
|
2025
1873
|
current = _measure_facade._is_hook_current(settings)
|
|
2026
1874
|
|
|
@@ -2039,7 +1887,8 @@ def setup_hook(dry_run=None, uninstall=None, user_initiated=None):
|
|
|
2039
1887
|
|
|
2040
1888
|
upgrading = installed and not current
|
|
2041
1889
|
|
|
2042
|
-
|
|
1890
|
+
import hook_provenance
|
|
1891
|
+
_before = hook_provenance.contexts_of(settings) # provenance claims only what this write adds
|
|
2043
1892
|
new_hook = {"type": "command", "command": _measure_facade.HOOK_COMMAND, "async": True}
|
|
2044
1893
|
|
|
2045
1894
|
if "hooks" not in settings:
|
|
@@ -2047,22 +1896,13 @@ def setup_hook(dry_run=None, uninstall=None, user_initiated=None):
|
|
|
2047
1896
|
|
|
2048
1897
|
hooks = settings["hooks"]
|
|
2049
1898
|
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
hook_list = entry.get("hooks", []) if isinstance(entry, dict) else []
|
|
2056
|
-
for i, hook in enumerate(hook_list):
|
|
2057
|
-
cmd = hook.get("command", "") if isinstance(hook, dict) else ""
|
|
2058
|
-
if _measure_facade._sessionend_cmd_is_collect_fossil(cmd) or (
|
|
2059
|
-
"measure.py" in cmd and "collect" in cmd
|
|
2060
|
-
):
|
|
2061
|
-
hook_list[i] = new_hook
|
|
2062
|
-
break
|
|
2063
|
-
elif "SessionEnd" not in hooks:
|
|
1899
|
+
# Replace our own collect/dashboard fossil with session-end-flush; with
|
|
1900
|
+
# none of ours there (a user's own measure.py), install alongside it.
|
|
1901
|
+
import owned_hooks
|
|
1902
|
+
upgrading = upgrading and owned_hooks.replace_session_end_fossil(_measure_facade, hooks, new_hook)
|
|
1903
|
+
if not upgrading and "SessionEnd" not in hooks:
|
|
2064
1904
|
hooks["SessionEnd"] = [{"hooks": [new_hook]}]
|
|
2065
|
-
|
|
1905
|
+
elif not upgrading:
|
|
2066
1906
|
session_end = hooks["SessionEnd"]
|
|
2067
1907
|
if isinstance(session_end, list) and len(session_end) > 0:
|
|
2068
1908
|
first_entry = session_end[0]
|
|
@@ -2104,6 +1944,7 @@ def setup_hook(dry_run=None, uninstall=None, user_initiated=None):
|
|
|
2104
1944
|
if not _measure_facade._write_settings_atomic(settings, user_initiated=user_initiated):
|
|
2105
1945
|
print("[Error] settings.json write was refused; SessionEnd hook was not installed.", file=_measure_facade.sys.stderr)
|
|
2106
1946
|
return
|
|
1947
|
+
hook_provenance.record_written(_measure_facade, _before, settings, [_measure_facade.HOOK_COMMAND], "setup_hook")
|
|
2107
1948
|
action = "upgraded" if upgrading else "installed"
|
|
2108
1949
|
print(f"[Token Optimizer] SessionEnd hook {action}.")
|
|
2109
1950
|
print(f" Backup: {backup_path}")
|
|
@@ -2540,10 +2381,13 @@ def setup_all_hooks(dry_run=None, verbose=None):
|
|
|
2540
2381
|
except OSError:
|
|
2541
2382
|
pass
|
|
2542
2383
|
|
|
2384
|
+
import hook_provenance
|
|
2385
|
+
_before = hook_provenance.contexts_of(current) # provenance claims only what this write adds
|
|
2543
2386
|
current_hooks = dict(current.get("hooks", {}))
|
|
2544
2387
|
|
|
2545
2388
|
added = 0
|
|
2546
2389
|
skipped = 0
|
|
2390
|
+
written = [] # exact commands this call puts into settings.json
|
|
2547
2391
|
|
|
2548
2392
|
for event, handler_groups in desired.items():
|
|
2549
2393
|
if event not in current_hooks:
|
|
@@ -2608,6 +2452,7 @@ def setup_all_hooks(dry_run=None, verbose=None):
|
|
|
2608
2452
|
continue
|
|
2609
2453
|
# Stale path -- replace in place
|
|
2610
2454
|
existing_hook["command"] = resolved_cmd
|
|
2455
|
+
written.append(resolved_cmd)
|
|
2611
2456
|
# Preserve all fields from new hook (async, timeout, etc.)
|
|
2612
2457
|
for k, v in h.items():
|
|
2613
2458
|
if k != "command":
|
|
@@ -2632,6 +2477,7 @@ def setup_all_hooks(dry_run=None, verbose=None):
|
|
|
2632
2477
|
# Preserve all fields from source hook (async, timeout, type, etc.)
|
|
2633
2478
|
new_hook = dict(h)
|
|
2634
2479
|
new_hook["command"] = resolved_cmd
|
|
2480
|
+
written.append(resolved_cmd)
|
|
2635
2481
|
target_group.setdefault("hooks", []).append(new_hook)
|
|
2636
2482
|
existing_ids.setdefault(matcher, set()).add(ident)
|
|
2637
2483
|
existing_entries.setdefault(matcher, {})[ident] = (target_group, new_hook)
|
|
@@ -2661,6 +2507,9 @@ def setup_all_hooks(dry_run=None, verbose=None):
|
|
|
2661
2507
|
print(f" [setup-all-hooks] could not write settings.json: {e}")
|
|
2662
2508
|
return {"added": 0, "skipped": skipped, "plugin_root": plugin_root_str, "error": str(e)}
|
|
2663
2509
|
|
|
2510
|
+
# Provenance: the healer may later remove only entries it can prove it wrote.
|
|
2511
|
+
hook_provenance.record_written(_measure_facade, _before, new_settings, written, "setup_all_hooks")
|
|
2512
|
+
|
|
2664
2513
|
# Record the heal timestamp so ensure-health's 24h throttle
|
|
2665
2514
|
# suppresses the redundant run after install.sh.
|
|
2666
2515
|
try:
|
|
@@ -2933,34 +2782,14 @@ def setup_smart_compact(dry_run=None, uninstall=None, status_only=None,
|
|
|
2933
2782
|
return
|
|
2934
2783
|
|
|
2935
2784
|
if uninstall:
|
|
2936
|
-
|
|
2937
|
-
removed =
|
|
2938
|
-
for event in ("PreCompact", "SessionStart", "Stop", "SessionEnd"):
|
|
2939
|
-
if event not in hooks:
|
|
2940
|
-
continue
|
|
2941
|
-
new_groups = []
|
|
2942
|
-
for group in hooks[event]:
|
|
2943
|
-
new_hooks = [
|
|
2944
|
-
h for h in group.get("hooks", [])
|
|
2945
|
-
if "compact-capture" not in h.get("command", "")
|
|
2946
|
-
and "compact-restore" not in h.get("command", "")
|
|
2947
|
-
]
|
|
2948
|
-
if new_hooks:
|
|
2949
|
-
group["hooks"] = new_hooks
|
|
2950
|
-
new_groups.append(group)
|
|
2951
|
-
else:
|
|
2952
|
-
removed += 1
|
|
2953
|
-
if new_groups:
|
|
2954
|
-
hooks[event] = new_groups
|
|
2955
|
-
elif event in hooks:
|
|
2956
|
-
del hooks[event]
|
|
2785
|
+
import owned_hooks # our entries only: a user's own compact-capture hook stays
|
|
2786
|
+
removed = owned_hooks.remove_smart_compact(_measure_facade, settings)
|
|
2957
2787
|
|
|
2958
2788
|
if dry_run:
|
|
2959
2789
|
print(f"\n [Dry run] Would remove {removed} smart compact hook(s) from {settings_path}")
|
|
2960
2790
|
print(" Run without --dry-run to apply.\n")
|
|
2961
2791
|
return
|
|
2962
2792
|
|
|
2963
|
-
settings["hooks"] = hooks
|
|
2964
2793
|
# setup-smart-compact also installed compactInstructions; take ours
|
|
2965
2794
|
# back out (a user-written part stays).
|
|
2966
2795
|
ci_removed = _measure_facade._remove_our_compact_instructions(settings)
|
|
@@ -2991,9 +2820,10 @@ def setup_smart_compact(dry_run=None, uninstall=None, status_only=None,
|
|
|
2991
2820
|
print("[Token Optimizer] Smart Compaction managed by plugin hooks.json.")
|
|
2992
2821
|
return
|
|
2993
2822
|
|
|
2823
|
+
import hook_provenance
|
|
2824
|
+
_before = hook_provenance.contexts_of(settings) # provenance claims only what this write adds
|
|
2994
2825
|
hooks = settings.setdefault("hooks", {})
|
|
2995
|
-
installed = []
|
|
2996
|
-
skipped = []
|
|
2826
|
+
installed, skipped, written = [], [], []
|
|
2997
2827
|
|
|
2998
2828
|
for event, command in commands.items():
|
|
2999
2829
|
if event == "SessionStart":
|
|
@@ -3018,9 +2848,11 @@ def setup_smart_compact(dry_run=None, uninstall=None, status_only=None,
|
|
|
3018
2848
|
added = False
|
|
3019
2849
|
if not has_compact_matcher:
|
|
3020
2850
|
event_hooks.append({"matcher": "compact", "hooks": [{"type": "command", "command": command}]})
|
|
2851
|
+
written.append(command)
|
|
3021
2852
|
added = True
|
|
3022
2853
|
if not has_new_session:
|
|
3023
2854
|
event_hooks.append({"hooks": [{"type": "command", "command": new_session_cmd}]})
|
|
2855
|
+
written.append(new_session_cmd)
|
|
3024
2856
|
added = True
|
|
3025
2857
|
|
|
3026
2858
|
if added:
|
|
@@ -3036,6 +2868,7 @@ def setup_smart_compact(dry_run=None, uninstall=None, status_only=None,
|
|
|
3036
2868
|
# Append to existing hook groups for this event
|
|
3037
2869
|
hook_entry = {"type": "command", "command": command}
|
|
3038
2870
|
hook_group = {"hooks": [hook_entry]}
|
|
2871
|
+
written.append(command)
|
|
3039
2872
|
|
|
3040
2873
|
if event not in hooks:
|
|
3041
2874
|
hooks[event] = []
|
|
@@ -3064,6 +2897,7 @@ def setup_smart_compact(dry_run=None, uninstall=None, status_only=None,
|
|
|
3064
2897
|
if not _measure_facade._write_settings_atomic(settings, user_initiated=user_initiated):
|
|
3065
2898
|
print("[Error] settings.json write was refused; smart compact hooks were not installed.", file=_measure_facade.sys.stderr)
|
|
3066
2899
|
return
|
|
2900
|
+
hook_provenance.record_written(_measure_facade, _before, settings, written, "setup_smart_compact")
|
|
3067
2901
|
|
|
3068
2902
|
print("[Token Optimizer] Smart Compaction installed.")
|
|
3069
2903
|
print(f" Hooks added: {', '.join(installed)}")
|
|
@@ -3228,7 +3062,8 @@ def _fix_stale_settings_paths():
|
|
|
3228
3062
|
return 0
|
|
3229
3063
|
except Exception:
|
|
3230
3064
|
return 0
|
|
3231
|
-
|
|
3065
|
+
import hook_provenance # records only rewrites of entries already proven ours
|
|
3066
|
+
hook_provenance.record_rewrites(_measure_facade, settings, new_settings, "fix_stale_settings_paths")
|
|
3232
3067
|
return len(stale_roots)
|
|
3233
3068
|
|
|
3234
3069
|
|
|
@@ -3492,315 +3327,36 @@ def _heal_keepwarm_plist_path():
|
|
|
3492
3327
|
|
|
3493
3328
|
|
|
3494
3329
|
def _fix_malformed_hook_commands():
|
|
3495
|
-
"""
|
|
3330
|
+
"""Remove malformed hook entries Token Optimizer can prove it wrote.
|
|
3496
3331
|
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
expand to /Users/X/Users/X/... which doesn't exist.
|
|
3502
|
-
|
|
3503
|
-
Only removes hooks that reference known TO script names, so other
|
|
3504
|
-
plugins' hooks are never touched. After removal, calls setup_all_hooks
|
|
3505
|
-
for script-install users (plugin users get hooks from hooks.json
|
|
3506
|
-
automatically). Resets last_hook_heal_check so the next session's
|
|
3507
|
-
24h gate runs the full heal cycle.
|
|
3508
|
-
|
|
3509
|
-
Returns the number of removed hook entries.
|
|
3332
|
+
Proof is the provenance ledger or a byte-identical shipped template; the
|
|
3333
|
+
pass reads, proves and writes ONE resolved settings file under the
|
|
3334
|
+
settings lock. Script installs are re-provisioned after a removal. Returns
|
|
3335
|
+
the number removed. See hook_heal.heal_settings.
|
|
3510
3336
|
"""
|
|
3511
3337
|
_measure_facade = _compat.facade()
|
|
3338
|
+
import hook_heal
|
|
3512
3339
|
try:
|
|
3513
|
-
|
|
3514
|
-
current, _ok = _measure_facade._read_settings_for_write()
|
|
3515
|
-
if not _ok:
|
|
3516
|
-
return 0
|
|
3340
|
+
return hook_heal.heal_settings(_measure_facade)
|
|
3517
3341
|
except Exception:
|
|
3518
3342
|
return 0
|
|
3519
3343
|
|
|
3520
|
-
current_hooks = current.get("hooks") if current else None
|
|
3521
|
-
if not current_hooks or not isinstance(current_hooks, dict):
|
|
3522
|
-
return 0
|
|
3523
|
-
|
|
3524
|
-
removed = 0
|
|
3525
|
-
new_hooks = {}
|
|
3526
|
-
|
|
3527
|
-
for event, handler_groups in current_hooks.items():
|
|
3528
|
-
if not isinstance(handler_groups, list):
|
|
3529
|
-
new_hooks[event] = handler_groups
|
|
3530
|
-
continue
|
|
3531
|
-
new_groups = []
|
|
3532
|
-
for group in handler_groups:
|
|
3533
|
-
if not isinstance(group, dict):
|
|
3534
|
-
new_groups.append(group)
|
|
3535
|
-
continue
|
|
3536
|
-
original_hook_list = group.get("hooks", [])
|
|
3537
|
-
if not isinstance(original_hook_list, list):
|
|
3538
|
-
new_groups.append(group)
|
|
3539
|
-
continue
|
|
3540
|
-
kept_hooks = []
|
|
3541
|
-
for h in original_hook_list:
|
|
3542
|
-
if not isinstance(h, dict):
|
|
3543
|
-
kept_hooks.append(h)
|
|
3544
|
-
continue
|
|
3545
|
-
cmd = h.get("command", "")
|
|
3546
|
-
if _measure_facade._is_malformed_to_hook(cmd):
|
|
3547
|
-
removed += 1
|
|
3548
|
-
continue
|
|
3549
|
-
kept_hooks.append(h)
|
|
3550
|
-
if kept_hooks:
|
|
3551
|
-
new_group = dict(group)
|
|
3552
|
-
new_group["hooks"] = kept_hooks
|
|
3553
|
-
new_groups.append(new_group)
|
|
3554
|
-
if new_groups:
|
|
3555
|
-
new_hooks[event] = new_groups
|
|
3556
|
-
|
|
3557
|
-
if removed == 0:
|
|
3558
|
-
return 0
|
|
3559
|
-
|
|
3560
|
-
new_settings = dict(current)
|
|
3561
|
-
new_settings["hooks"] = new_hooks
|
|
3562
|
-
|
|
3563
|
-
try:
|
|
3564
|
-
if not _measure_facade._write_settings_atomic(new_settings):
|
|
3565
|
-
return 0
|
|
3566
|
-
except (PermissionError, OSError):
|
|
3567
|
-
return 0
|
|
3568
|
-
|
|
3569
|
-
# Reset 24h throttle so next session re-runs the full hook heal cycle.
|
|
3570
|
-
try:
|
|
3571
|
-
_measure_facade._write_config_flag("last_hook_heal_check", 0)
|
|
3572
|
-
except Exception:
|
|
3573
|
-
pass
|
|
3574
|
-
|
|
3575
|
-
# Script-install users need immediate reprovisioning (plugin users
|
|
3576
|
-
# get hooks from hooks.json automatically, no gap).
|
|
3577
|
-
if not _measure_facade._is_plugin_installed():
|
|
3578
|
-
try:
|
|
3579
|
-
heal_result = _measure_facade.setup_all_hooks(dry_run=False, verbose=False)
|
|
3580
|
-
if heal_result.get("error"):
|
|
3581
|
-
print(f" [Token Optimizer] Warning: hook re-provisioning failed after cleanup: {heal_result['error']}", file=_measure_facade.sys.stderr)
|
|
3582
|
-
except Exception as _e:
|
|
3583
|
-
print(f" [Token Optimizer] Warning: hook re-provisioning failed after cleanup: {_e}", file=_measure_facade.sys.stderr)
|
|
3584
|
-
|
|
3585
|
-
return removed
|
|
3586
|
-
|
|
3587
3344
|
|
|
3588
3345
|
def _is_malformed_to_hook(cmd):
|
|
3589
|
-
"""
|
|
3590
|
-
|
|
3591
|
-
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
script basename (the script the hook will run) and requires it to
|
|
3597
|
-
resolve to skills/token-optimizer/scripts/<name> under one of exactly
|
|
3598
|
-
two runtime-proven roots: the running install root (this module's own
|
|
3599
|
-
__file__; for a plugin-cache install that IS the current cache version
|
|
3600
|
-
directory) or the resolved $CLAUDE_PLUGIN_ROOT environment value. The
|
|
3601
|
-
Claude config dir is never a root by itself: another skill, another
|
|
3602
|
-
plugin's cache entry, a same-named plugin from a different marketplace,
|
|
3603
|
-
or a stale version of this plugin under it is not provably ours and is
|
|
3604
|
-
preserved. A root string in an argument, comment, env assignment, or
|
|
3605
|
-
redirect proves nothing (comments are stripped before tokenizing).
|
|
3606
|
-
Home-relative spellings (~, $HOME, ${HOME}) expand against the real
|
|
3607
|
-
home; a literal $CLAUDE_PLUGIN_ROOT resolves through the environment
|
|
3608
|
-
when set and is unprovable (preserved) when unset. The macOS
|
|
3609
|
-
doubled-$HOME corruption is corrected by stripping the known doubled
|
|
3610
|
-
prefix, then the same full proof applies. A relative script argument
|
|
3611
|
-
resolves only against a literal D="<root>" assignment in the same
|
|
3612
|
-
command (the installer's written form). Every basename-carrying token
|
|
3613
|
-
must resolve to our payload: a command mixing our script with a foreign
|
|
3614
|
-
one is ambiguous and preserved. Deleting the user's own hook is
|
|
3615
|
-
irreversible, so unknown ownership means leave it alone.
|
|
3346
|
+
"""True when the malformed-hook healer would remove this command.
|
|
3347
|
+
|
|
3348
|
+
Provenance, not parsing: the exact command bytes must be recorded in the
|
|
3349
|
+
hook provenance ledger for the current settings file or be a shipped
|
|
3350
|
+
hooks.json template instantiated for this install, and the command must be
|
|
3351
|
+
malformed. A command Token Optimizer cannot prove it wrote is never ours,
|
|
3352
|
+
whatever path or basename it mentions. See hook_provenance.py.
|
|
3616
3353
|
"""
|
|
3617
3354
|
_measure_facade = _compat.facade()
|
|
3618
3355
|
if not cmd:
|
|
3619
3356
|
return False
|
|
3620
|
-
|
|
3621
|
-
|
|
3622
|
-
|
|
3623
|
-
names = _measure_facade._TO_SCRIPT_NAMES
|
|
3624
|
-
# The exact version-resolver assignment every installer-written hook
|
|
3625
|
-
# command carries (hooks/hooks.json, bash-loop wrapper). Kept as a
|
|
3626
|
-
# function local: the split-module policy forbids module-level state in
|
|
3627
|
-
# providers. The regression test asserts behaviour (an installer-shaped
|
|
3628
|
-
# command is not flagged) so hooks.json drift fails loudly.
|
|
3629
|
-
_TO_VERSION_RESOLVER = 'D="$(ls -d "${D%[/\\\\]*}"/*/ 2>/dev/null | grep -E "/[0-9]+[.][0-9]+[.][0-9]+/$" | sort -V | tail -n1)"'
|
|
3630
|
-
# Cheap pre-filter only; ownership is proven below. Backslash counts as a
|
|
3631
|
-
# separator so a Windows path reaches the proof at all.
|
|
3632
|
-
has_to_script = any(
|
|
3633
|
-
re_mod.search(r'(?:^|[/\\\s])' + re_mod.escape(name) + r'(?:$|[\s])', cmd)
|
|
3634
|
-
for name in names
|
|
3635
|
-
)
|
|
3636
|
-
if not has_to_script:
|
|
3637
|
-
return False
|
|
3638
|
-
|
|
3639
|
-
# POSIX, drive-letter (C:/ or C:\) and UNC absolutes; hook commands on
|
|
3640
|
-
# Windows installs carry Windows paths.
|
|
3641
|
-
abs_re = re_mod.compile(r'^(?:/|[A-Za-z]:[\\/]|\\\\)')
|
|
3642
|
-
# Doubled-home prefixes written by Claude on macOS when it expands $HOME
|
|
3643
|
-
# and prepends it again: raw ($HOME/Users/<u>/<abs>) and already-expanded
|
|
3644
|
-
# (/Users/<u>/Users/<u>/...). Stripping yields the intended absolute
|
|
3645
|
-
# path, which still has to pass the full ownership proof.
|
|
3646
|
-
doubled_re = re_mod.compile(
|
|
3647
|
-
r'^(?:\$HOME|\$\{HOME\}|~)/(?:Users|home)/[^/]+?(?=/|[A-Za-z]:[\\/])'
|
|
3648
|
-
r'|^/(?:Users|home)/[^/]+(?=/(?:Users|home)/)'
|
|
3649
|
-
)
|
|
3650
|
-
|
|
3651
|
-
def _canon(path):
|
|
3652
|
-
# normcase: case-insensitive + separator-normalized on Windows,
|
|
3653
|
-
# identity on POSIX.
|
|
3654
|
-
return os_mod.path.normcase(str(path)).replace("\\", "/").rstrip("/")
|
|
3655
|
-
|
|
3656
|
-
def _owned_roots():
|
|
3657
|
-
install_root = None
|
|
3658
|
-
try:
|
|
3659
|
-
# The facade lives at <root>/skills/token-optimizer/scripts/
|
|
3660
|
-
# measure.py, so parents[3] is the install root the installer
|
|
3661
|
-
# writes into hook commands.
|
|
3662
|
-
install_root = Path_mod(_measure_facade.__file__).resolve().parents[3]
|
|
3663
|
-
except Exception:
|
|
3664
|
-
pass
|
|
3665
|
-
roots = [] if install_root is None else [install_root]
|
|
3666
|
-
try:
|
|
3667
|
-
# $CLAUDE_PLUGIN_ROOT is environment input, not proof: it counts
|
|
3668
|
-
# as an owned root only when it resolves to THIS running
|
|
3669
|
-
# install (the same root derived from __file__ above, which for
|
|
3670
|
-
# a plugin-cache install IS the current cache version dir). A
|
|
3671
|
-
# foreign or stale env root - another marketplace's same-named
|
|
3672
|
-
# plugin, an old checkout - must never make its hooks ours.
|
|
3673
|
-
plugin_root = os_mod.environ.get("CLAUDE_PLUGIN_ROOT")
|
|
3674
|
-
if plugin_root and install_root is not None:
|
|
3675
|
-
resolved = Path_mod(plugin_root).expanduser().resolve()
|
|
3676
|
-
if _canon(resolved) == _canon(install_root):
|
|
3677
|
-
roots.append(resolved)
|
|
3678
|
-
except Exception:
|
|
3679
|
-
pass
|
|
3680
|
-
return [_canon(r) for r in roots]
|
|
3681
|
-
|
|
3682
|
-
def _owned_script_path(candidate):
|
|
3683
|
-
canon = _canon(candidate)
|
|
3684
|
-
name = canon.rsplit("/", 1)[-1]
|
|
3685
|
-
if name not in names:
|
|
3686
|
-
return False
|
|
3687
|
-
suffix = "skills/token-optimizer/scripts/" + name
|
|
3688
|
-
return any(len(root) >= 4 and canon == root + "/" + suffix
|
|
3689
|
-
for root in _owned_roots())
|
|
3690
|
-
|
|
3691
|
-
def _proves_ownership():
|
|
3692
|
-
try:
|
|
3693
|
-
home = str(Path_mod.home())
|
|
3694
|
-
except Exception:
|
|
3695
|
-
home = ""
|
|
3696
|
-
try:
|
|
3697
|
-
plugin_root = os_mod.environ.get("CLAUDE_PLUGIN_ROOT") or ""
|
|
3698
|
-
except Exception:
|
|
3699
|
-
plugin_root = ""
|
|
3700
|
-
|
|
3701
|
-
# Shell comments never execute: a root or script path mentioned only
|
|
3702
|
-
# in a comment cannot prove (or veto) ownership.
|
|
3703
|
-
probe = re_mod.sub(r'(?m)(^|[\s;|&])#.*$', r'\1', cmd)
|
|
3704
|
-
|
|
3705
|
-
def _expand(path):
|
|
3706
|
-
if home and home != "~":
|
|
3707
|
-
for prefix in ("${HOME}/", "$HOME/", "~/"):
|
|
3708
|
-
if path.startswith(prefix):
|
|
3709
|
-
return home.rstrip("/") + "/" + path[len(prefix):]
|
|
3710
|
-
if plugin_root:
|
|
3711
|
-
for prefix in ("${CLAUDE_PLUGIN_ROOT}/", "$CLAUDE_PLUGIN_ROOT/"):
|
|
3712
|
-
if path.startswith(prefix):
|
|
3713
|
-
return plugin_root.rstrip("/") + "/" + path[len(prefix):]
|
|
3714
|
-
return path
|
|
3715
|
-
|
|
3716
|
-
# Literal D="<root>" assignments the installer prefixes hook commands
|
|
3717
|
-
# with; the base for the relative script argument that follows them.
|
|
3718
|
-
d_roots = [
|
|
3719
|
-
_expand(m.group(1)).rstrip("/")
|
|
3720
|
-
for m in re_mod.finditer(r'(?:^|[;\s])D="([^"]+)"', probe)
|
|
3721
|
-
]
|
|
3722
|
-
|
|
3723
|
-
try:
|
|
3724
|
-
import shlex
|
|
3725
|
-
# shlex.split(posix=True) with one change on Windows: backslash is
|
|
3726
|
-
# a path separator there, not an escape, so D:\a\x stays D:\a\x.
|
|
3727
|
-
# Quote handling stays POSIX (posix=False would split
|
|
3728
|
-
# "C:\vendor "D:\root\...\measure.py into two words and expose
|
|
3729
|
-
# our path as its own token: false ownership proof).
|
|
3730
|
-
lexer = shlex.shlex(probe, posix=True)
|
|
3731
|
-
lexer.whitespace_split = True
|
|
3732
|
-
lexer.commenters = ""
|
|
3733
|
-
if os_mod.name == "nt":
|
|
3734
|
-
lexer.escape = ""
|
|
3735
|
-
tokens = list(lexer)
|
|
3736
|
-
except Exception:
|
|
3737
|
-
tokens = [t.strip('"').strip("'").rstrip(";").replace("\\", "/")
|
|
3738
|
-
for t in probe.split()]
|
|
3739
|
-
anchors = []
|
|
3740
|
-
for tok in tokens:
|
|
3741
|
-
tok = tok.rstrip(";")
|
|
3742
|
-
# Windows paths may use backslashes throughout; POSIX keeps a
|
|
3743
|
-
# backslash as a literal filename character.
|
|
3744
|
-
seps = tok.replace("\\", "/") if os_mod.name == "nt" else tok
|
|
3745
|
-
for name in names:
|
|
3746
|
-
if tok == name or seps.endswith("/" + name):
|
|
3747
|
-
anchors.append(tok)
|
|
3748
|
-
break
|
|
3749
|
-
if not anchors:
|
|
3750
|
-
return False
|
|
3751
|
-
|
|
3752
|
-
def _resolve_candidates(tok):
|
|
3753
|
-
if tok.startswith("$D/"):
|
|
3754
|
-
tok = tok[len("$D/"):]
|
|
3755
|
-
candidates = []
|
|
3756
|
-
expanded = _expand(tok)
|
|
3757
|
-
if abs_re.match(expanded):
|
|
3758
|
-
candidates.append(expanded)
|
|
3759
|
-
for variant in (tok, expanded):
|
|
3760
|
-
stripped = doubled_re.sub("", variant)
|
|
3761
|
-
if stripped != variant:
|
|
3762
|
-
stripped = _expand(stripped)
|
|
3763
|
-
if abs_re.match(stripped):
|
|
3764
|
-
candidates.append(stripped)
|
|
3765
|
-
if not candidates and d_roots:
|
|
3766
|
-
candidates.append(d_roots[0] + "/" + expanded)
|
|
3767
|
-
return candidates
|
|
3768
|
-
|
|
3769
|
-
for tok in anchors:
|
|
3770
|
-
owned = False
|
|
3771
|
-
for candidate in _resolve_candidates(tok):
|
|
3772
|
-
try:
|
|
3773
|
-
candidate = str(Path_mod(candidate).resolve())
|
|
3774
|
-
except Exception:
|
|
3775
|
-
candidate = os_mod.path.normpath(candidate)
|
|
3776
|
-
if _owned_script_path(candidate):
|
|
3777
|
-
owned = True
|
|
3778
|
-
break
|
|
3779
|
-
if not owned:
|
|
3780
|
-
return False
|
|
3781
|
-
return True
|
|
3782
|
-
|
|
3783
|
-
if not _proves_ownership():
|
|
3784
|
-
return False
|
|
3785
|
-
# The installer's version resolver is recognized plumbing, not
|
|
3786
|
-
# malformation. Recognize the EXACT template hooks/hooks.json writes
|
|
3787
|
-
# (_TO_VERSION_RESOLVER, kept in sync with hooks.json by
|
|
3788
|
-
# tests/test_malformed_detector_installer_resolver.py) and remove ONE
|
|
3789
|
-
# occurrence before the subshell check. A character-class regex is not
|
|
3790
|
-
# acceptable here: this predicate is a rejection gate, and a loose match
|
|
3791
|
-
# would let crafted content hide a real subshell inside a resolver-shaped
|
|
3792
|
-
# string. Any deviation from the template, any second resolver-shaped
|
|
3793
|
-
# subshell, and any other subshell or backtick (Claude-written shapes)
|
|
3794
|
-
# leaves "$(" or "`" in the probe and is still rejected.
|
|
3795
|
-
probe = cmd.replace(_TO_VERSION_RESOLVER, 'D=""', 1)
|
|
3796
|
-
has_subshell = "$(" in probe or "`" in probe
|
|
3797
|
-
has_double_home = False
|
|
3798
|
-
if _measure_facade.platform.system() == "Darwin":
|
|
3799
|
-
has_double_home = (
|
|
3800
|
-
"$HOME/Users/" in cmd or "$HOME/home/" in cmd
|
|
3801
|
-
or "${HOME}/Users/" in cmd or "${HOME}/home/" in cmd
|
|
3802
|
-
)
|
|
3803
|
-
return has_subshell or has_double_home
|
|
3357
|
+
import hook_provenance
|
|
3358
|
+
prov = hook_provenance.Provenance.from_facade(_measure_facade)
|
|
3359
|
+
return prov.verdict(cmd) == "remove"
|
|
3804
3360
|
|
|
3805
3361
|
|
|
3806
3362
|
def _command_drives_quality_cache(command):
|
|
@@ -4604,6 +4160,8 @@ def setup_quality_bar(dry_run=None, uninstall=None, status_only=None, force=None
|
|
|
4604
4160
|
elif current["hook"]:
|
|
4605
4161
|
skipped.append("cache hook")
|
|
4606
4162
|
else:
|
|
4163
|
+
import hook_provenance
|
|
4164
|
+
_before = hook_provenance.contexts_of(settings) # provenance claims only what this write adds
|
|
4607
4165
|
hooks = settings.setdefault("hooks", {})
|
|
4608
4166
|
_py, _mp = _measure_facade._settings_hook_python_and_script(mp)
|
|
4609
4167
|
hook_cmd = f"{_py} {_mp} quality-cache --quiet"
|
|
@@ -4685,6 +4243,8 @@ def setup_quality_bar(dry_run=None, uninstall=None, status_only=None, force=None
|
|
|
4685
4243
|
if not quiet:
|
|
4686
4244
|
print("[Error] settings.json write was refused; Quality Bar was not installed.", file=_measure_facade.sys.stderr)
|
|
4687
4245
|
return
|
|
4246
|
+
if "cache hook" in installed:
|
|
4247
|
+
hook_provenance.record_written(_measure_facade, _before, settings, [hook_cmd], "setup_quality_bar")
|
|
4688
4248
|
# Explicit install is an explicit opt-in — clear any prior opt-out.
|
|
4689
4249
|
_measure_facade._set_quality_bar_disabled(False)
|
|
4690
4250
|
|
|
@@ -5531,7 +5091,7 @@ def run_ensure_health():
|
|
|
5531
5091
|
# already uses; _dashboard_heal_spawn_due() fails OPEN so a lock
|
|
5532
5092
|
# glitch never skips the heal.
|
|
5533
5093
|
try:
|
|
5534
|
-
_measure_facade._spawn_detached_dashboard_selfheal(
|
|
5094
|
+
_measure_facade._spawn_detached_dashboard_selfheal(force=True, hook_timeout=False)
|
|
5535
5095
|
print(f" [Token Optimizer] Refreshing dashboard to v{_measure_facade.TOKEN_OPTIMIZER_VERSION} (background)", file=_measure_facade.sys.stderr)
|
|
5536
5096
|
except Exception as _e:
|
|
5537
5097
|
print(f" [Token Optimizer] dashboard refresh failed: {_e}", file=_measure_facade.sys.stderr)
|