@alexgreensh/token-optimizer 5.13.66 → 5.13.68

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 (43) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/hooks.json +0 -10
  4. package/package.json +1 -1
  5. package/skills/token-optimizer/examples/hooks-starter.json +0 -10
  6. package/skills/token-optimizer/scripts/_measure/_compat.py +2 -2
  7. package/skills/token-optimizer/scripts/_measure/_vendor/README.md +15 -0
  8. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +63 -0
  9. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/LICENSE +21 -0
  10. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +39 -0
  11. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/py.typed +1 -0
  12. package/skills/token-optimizer/scripts/_measure/audit.py +5 -21
  13. package/skills/token-optimizer/scripts/_measure/cache_policy.py +54 -1
  14. package/skills/token-optimizer/scripts/_measure/daemon.py +21 -51
  15. package/skills/token-optimizer/scripts/_measure/lifecycle.py +81 -327
  16. package/skills/token-optimizer/scripts/_tomli.py +916 -0
  17. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +11 -3
  18. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  19. package/skills/token-optimizer/scripts/bash_compress.py +3 -3
  20. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -7
  21. package/skills/token-optimizer/scripts/cloud_kit.py +21 -21
  22. package/skills/token-optimizer/scripts/codex_compact_prompt.py +2 -2
  23. package/skills/token-optimizer/scripts/codex_doctor.py +33 -7
  24. package/skills/token-optimizer/scripts/codex_hook_provenance.py +268 -0
  25. package/skills/token-optimizer/scripts/codex_install.py +33 -69
  26. package/skills/token-optimizer/scripts/command_filters.py +359 -18
  27. package/skills/token-optimizer/scripts/copilot_install.py +5 -0
  28. package/skills/token-optimizer/scripts/cursor_install.py +5 -0
  29. package/skills/token-optimizer/scripts/devin_install.py +6 -12
  30. package/skills/token-optimizer/scripts/devin_source.py +6 -5
  31. package/skills/token-optimizer/scripts/devin_verify.py +16 -0
  32. package/skills/token-optimizer/scripts/grok_install.py +5 -0
  33. package/skills/token-optimizer/scripts/heal_report.py +92 -0
  34. package/skills/token-optimizer/scripts/hook_heal.py +138 -0
  35. package/skills/token-optimizer/scripts/hook_provenance.py +878 -0
  36. package/skills/token-optimizer/scripts/measure.py +2 -2
  37. package/skills/token-optimizer/scripts/owned_hooks.py +420 -0
  38. package/skills/token-optimizer/scripts/read_cache.py +20 -21
  39. package/skills/token-optimizer/scripts/reset_epoch.py +177 -0
  40. package/skills/token-optimizer/scripts/session_store.py +11 -48
  41. package/skills/token-optimizer/scripts/shipped_codex_hook_templates.json +5815 -0
  42. package/skills/token-optimizer/scripts/shipped_hook_templates.py +252 -0
  43. package/skills/token-optimizer/scripts/shipped_starter_hooks.py +55 -0
@@ -926,12 +926,13 @@ def _is_compaction_runner(cmd, event):
926
926
 
927
927
 
928
928
  def _is_hook_installed(settings=None, settings_only=None):
929
- """Check if the SessionEnd measure.py collect hook is installed.
929
+ """Check if Token Optimizer's own SessionEnd hook is installed.
930
930
 
931
- Returns True if any SessionEnd hook command contains 'measure.py collect'.
932
- Recognizes both old (collect-only) and new (collect + dashboard) hook commands.
933
- Also checks plugin cache hooks (auto-installed via marketplace plugin), unless
934
- ``settings_only`` asks only whether settings.json carries it (doctor's label).
931
+ Counts only settings.json SessionEnd entries owned_hooks proves are ours
932
+ (old collect, collect + dashboard and session-end-flush shapes alike), so
933
+ a user's own measure.py never reads as ours. Also checks plugin cache
934
+ hooks (auto-installed via marketplace plugin), unless ``settings_only``
935
+ asks only whether settings.json carries it (doctor's label).
935
936
  """
936
937
  # Check user settings.json
937
938
  _measure_facade = _compat.facade()
@@ -945,8 +946,8 @@ def _is_hook_installed(settings=None, settings_only=None):
945
946
  else:
946
947
  settings = {}
947
948
 
948
- hooks = settings.get("hooks", {})
949
- session_end = hooks.get("SessionEnd", [])
949
+ import owned_hooks
950
+ session_end = owned_hooks.session_end_view(_measure_facade, settings)["hooks"]["SessionEnd"]
950
951
  if isinstance(session_end, list):
951
952
  for entry in session_end:
952
953
  hook_list = entry.get("hooks", []) if isinstance(entry, dict) else []
@@ -1007,7 +1008,8 @@ def _sessionend_cmd_is_collect_fossil(cmd) -> bool:
1007
1008
 
1008
1009
 
1009
1010
  def _is_hook_current(settings=None):
1010
- """True when the installed SessionEnd hook is the session-end-flush shape.
1011
+ """True when our own installed SessionEnd hook (owned_hooks) is the
1012
+ session-end-flush shape.
1011
1013
 
1012
1014
  The collect-then-dashboard fossil is never current: it runs the
1013
1015
  heavy flush inline and unbounded. The pre-v5.11 win32 cmd-null-redirect
@@ -1024,11 +1026,8 @@ def _is_hook_current(settings=None):
1024
1026
  except (_measure_facade.json.JSONDecodeError, PermissionError, OSError):
1025
1027
  return False
1026
1028
 
1027
- hooks = settings.get("hooks", {})
1028
- session_end = hooks.get("SessionEnd", [])
1029
- if not isinstance(session_end, list):
1030
- return False
1031
- for entry in session_end:
1029
+ import owned_hooks
1030
+ for entry in owned_hooks.session_end_view(_measure_facade, settings)["hooks"]["SessionEnd"]:
1032
1031
  hook_list = entry.get("hooks", []) if isinstance(entry, dict) else []
1033
1032
  for hook in hook_list:
1034
1033
  cmd = hook.get("command", "") if isinstance(hook, dict) else ""
@@ -1584,60 +1583,22 @@ def _is_token_optimizer_session_end_hook(hook: dict) -> bool:
1584
1583
  def _remove_token_optimizer_session_end_hooks(settings: dict) -> int:
1585
1584
  """Strip Token Optimizer's SessionEnd hooks from ``settings`` in place.
1586
1585
 
1587
- Mirrors the proven filter pattern in ``setup_smart_compact --uninstall``:
1588
- iterate the ``SessionEnd`` event only, drop hook entries whose command is
1589
- Token Optimizer's, keep every other hook (the user's own SessionEnd hooks
1590
- and ALL other hook events are left intact). Empty groups are removed; if
1591
- ``SessionEnd`` ends up empty, the key is dropped. Returns the count of
1592
- Token Optimizer hook entries removed. Never raises.
1586
+ Only entries Token Optimizer can prove are its own (owned_hooks.remove_session_end):
1587
+ a user's own measure.py hook and ALL other hook events are left intact.
1588
+ Empty groups are removed; if ``SessionEnd`` ends up empty, the key is
1589
+ dropped. Returns the count of hook entries removed. Never raises.
1593
1590
  """
1594
1591
  _measure_facade = _compat.facade()
1595
- if not isinstance(settings, dict):
1596
- return 0
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
1592
+ import owned_hooks
1593
+ return owned_hooks.remove_session_end(_measure_facade, settings)
1623
1594
 
1624
1595
 
1625
1596
  def _sessionend_has_current_flush(settings: dict) -> bool:
1626
- """True when settings.json already has a session-end-flush SessionEnd hook."""
1597
+ """True when settings.json already has our own session-end-flush SessionEnd hook."""
1627
1598
  _measure_facade = _compat.facade()
1628
- hooks = settings.get("hooks") if isinstance(settings, dict) else None
1629
- if not isinstance(hooks, dict):
1630
- return False
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
1599
+ import owned_hooks
1600
+ ours = owned_hooks.session_end_view(_measure_facade, settings)["hooks"]["SessionEnd"][0]["hooks"]
1601
+ return any(_measure_facade._sessionend_cmd_is_flush(hook.get("command", "")) for hook in ours)
1641
1602
 
1642
1603
 
1643
1604
  def _rewrite_collect_fossil_hook(hook: dict) -> dict:
@@ -1656,133 +1617,17 @@ def _rewrite_collect_fossil_hook(hook: dict) -> dict:
1656
1617
 
1657
1618
 
1658
1619
  def _apply_sessionend_fossil_reconcile(settings, result):
1659
- """Apply the fossil heal mutation to ``settings`` in place.
1620
+ """Apply the fossil heal mutation to ``settings`` in place, on entries
1621
+ Token Optimizer can prove are its own only (owned_hooks.apply_fossil_reconcile).
1660
1622
 
1661
1623
  Returns True if anything changed. The ``result`` counters (``rewritten`` /
1662
1624
  ``removed`` / ``stop_removed``) are incremented for the changes made in
1663
- THIS call only. Idempotent: a second call on an already-healed settings
1664
- is a no-op and returns False.
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.
1625
+ THIS call only. Idempotent. Extracted from ``_reconcile_sessionend_fossils``
1626
+ so the caller can re-read fresh under the lease and re-apply.
1674
1627
  """
1675
1628
  _measure_facade = _compat.facade()
1676
- hooks = settings.get("hooks") if isinstance(settings, dict) else None
1677
- if not isinstance(hooks, dict):
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
1629
+ import owned_hooks
1630
+ return owned_hooks.apply_fossil_reconcile(_measure_facade, settings, result)
1786
1631
 
1787
1632
 
1788
1633
  def _reconcile_sessionend_fossils():
@@ -1886,12 +1731,16 @@ def _reconcile_sessionend_fossils():
1886
1731
  if not isinstance(fresh.get("hooks"), dict):
1887
1732
  result["reason"] = "no_hooks"
1888
1733
  return result
1734
+ import hook_provenance
1735
+ before = hook_provenance.contexts_of(fresh)
1889
1736
  if not _measure_facade._apply_sessionend_fossil_reconcile(fresh, result):
1890
1737
  result["reason"] = "nothing_to_do"
1891
1738
  return result
1892
1739
  if not _measure_facade._write_settings_atomic_locked(fresh):
1893
1740
  result["reason"] = "write_skipped"
1894
1741
  return result
1742
+ hook_provenance.record_written(_measure_facade, before, fresh, [_measure_facade.HOOK_COMMAND],
1743
+ "sessionend_fossil_reconcile")
1895
1744
  return result
1896
1745
  except Exception:
1897
1746
  result["reason"] = "fail_open"
@@ -2020,7 +1869,7 @@ def setup_hook(dry_run=None, uninstall=None, user_initiated=None):
2020
1869
  _measure_facade.sys.exit(1)
2021
1870
  return
2022
1871
 
2023
- # Check if hook is installed and whether it needs upgrading
1872
+ # Installed / up to date counts only our own SessionEnd hook (owned_hooks).
2024
1873
  installed = _measure_facade._is_hook_installed(settings)
2025
1874
  current = _measure_facade._is_hook_current(settings)
2026
1875
 
@@ -2039,7 +1888,8 @@ def setup_hook(dry_run=None, uninstall=None, user_initiated=None):
2039
1888
 
2040
1889
  upgrading = installed and not current
2041
1890
 
2042
- # Build the hook entry
1891
+ import hook_provenance
1892
+ _before = hook_provenance.contexts_of(settings) # provenance claims only what this write adds
2043
1893
  new_hook = {"type": "command", "command": _measure_facade.HOOK_COMMAND, "async": True}
2044
1894
 
2045
1895
  if "hooks" not in settings:
@@ -2047,22 +1897,13 @@ def setup_hook(dry_run=None, uninstall=None, user_initiated=None):
2047
1897
 
2048
1898
  hooks = settings["hooks"]
2049
1899
 
2050
- if upgrading:
2051
- # Replace the collect/dashboard fossil with session-end-flush.
2052
- session_end = hooks.get("SessionEnd", [])
2053
- if isinstance(session_end, list):
2054
- for entry in session_end:
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:
1900
+ # Replace our own collect/dashboard fossil with session-end-flush; with
1901
+ # none of ours there (a user's own measure.py), install alongside it.
1902
+ import owned_hooks
1903
+ upgrading = upgrading and owned_hooks.replace_session_end_fossil(_measure_facade, hooks, new_hook)
1904
+ if not upgrading and "SessionEnd" not in hooks:
2064
1905
  hooks["SessionEnd"] = [{"hooks": [new_hook]}]
2065
- else:
1906
+ elif not upgrading:
2066
1907
  session_end = hooks["SessionEnd"]
2067
1908
  if isinstance(session_end, list) and len(session_end) > 0:
2068
1909
  first_entry = session_end[0]
@@ -2104,6 +1945,7 @@ def setup_hook(dry_run=None, uninstall=None, user_initiated=None):
2104
1945
  if not _measure_facade._write_settings_atomic(settings, user_initiated=user_initiated):
2105
1946
  print("[Error] settings.json write was refused; SessionEnd hook was not installed.", file=_measure_facade.sys.stderr)
2106
1947
  return
1948
+ hook_provenance.record_written(_measure_facade, _before, settings, [_measure_facade.HOOK_COMMAND], "setup_hook")
2107
1949
  action = "upgraded" if upgrading else "installed"
2108
1950
  print(f"[Token Optimizer] SessionEnd hook {action}.")
2109
1951
  print(f" Backup: {backup_path}")
@@ -2540,10 +2382,13 @@ def setup_all_hooks(dry_run=None, verbose=None):
2540
2382
  except OSError:
2541
2383
  pass
2542
2384
 
2385
+ import hook_provenance
2386
+ _before = hook_provenance.contexts_of(current) # provenance claims only what this write adds
2543
2387
  current_hooks = dict(current.get("hooks", {}))
2544
2388
 
2545
2389
  added = 0
2546
2390
  skipped = 0
2391
+ written = [] # exact commands this call puts into settings.json
2547
2392
 
2548
2393
  for event, handler_groups in desired.items():
2549
2394
  if event not in current_hooks:
@@ -2608,6 +2453,7 @@ def setup_all_hooks(dry_run=None, verbose=None):
2608
2453
  continue
2609
2454
  # Stale path -- replace in place
2610
2455
  existing_hook["command"] = resolved_cmd
2456
+ written.append(resolved_cmd)
2611
2457
  # Preserve all fields from new hook (async, timeout, etc.)
2612
2458
  for k, v in h.items():
2613
2459
  if k != "command":
@@ -2632,6 +2478,7 @@ def setup_all_hooks(dry_run=None, verbose=None):
2632
2478
  # Preserve all fields from source hook (async, timeout, type, etc.)
2633
2479
  new_hook = dict(h)
2634
2480
  new_hook["command"] = resolved_cmd
2481
+ written.append(resolved_cmd)
2635
2482
  target_group.setdefault("hooks", []).append(new_hook)
2636
2483
  existing_ids.setdefault(matcher, set()).add(ident)
2637
2484
  existing_entries.setdefault(matcher, {})[ident] = (target_group, new_hook)
@@ -2661,6 +2508,9 @@ def setup_all_hooks(dry_run=None, verbose=None):
2661
2508
  print(f" [setup-all-hooks] could not write settings.json: {e}")
2662
2509
  return {"added": 0, "skipped": skipped, "plugin_root": plugin_root_str, "error": str(e)}
2663
2510
 
2511
+ # Provenance: the healer may later remove only entries it can prove it wrote.
2512
+ hook_provenance.record_written(_measure_facade, _before, new_settings, written, "setup_all_hooks")
2513
+
2664
2514
  # Record the heal timestamp so ensure-health's 24h throttle
2665
2515
  # suppresses the redundant run after install.sh.
2666
2516
  try:
@@ -2933,34 +2783,14 @@ def setup_smart_compact(dry_run=None, uninstall=None, status_only=None,
2933
2783
  return
2934
2784
 
2935
2785
  if uninstall:
2936
- hooks = settings.get("hooks", {})
2937
- removed = 0
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]
2786
+ import owned_hooks # our entries only: a user's own compact-capture hook stays
2787
+ removed = owned_hooks.remove_smart_compact(_measure_facade, settings)
2957
2788
 
2958
2789
  if dry_run:
2959
2790
  print(f"\n [Dry run] Would remove {removed} smart compact hook(s) from {settings_path}")
2960
2791
  print(" Run without --dry-run to apply.\n")
2961
2792
  return
2962
2793
 
2963
- settings["hooks"] = hooks
2964
2794
  # setup-smart-compact also installed compactInstructions; take ours
2965
2795
  # back out (a user-written part stays).
2966
2796
  ci_removed = _measure_facade._remove_our_compact_instructions(settings)
@@ -2991,9 +2821,10 @@ def setup_smart_compact(dry_run=None, uninstall=None, status_only=None,
2991
2821
  print("[Token Optimizer] Smart Compaction managed by plugin hooks.json.")
2992
2822
  return
2993
2823
 
2824
+ import hook_provenance
2825
+ _before = hook_provenance.contexts_of(settings) # provenance claims only what this write adds
2994
2826
  hooks = settings.setdefault("hooks", {})
2995
- installed = []
2996
- skipped = []
2827
+ installed, skipped, written = [], [], []
2997
2828
 
2998
2829
  for event, command in commands.items():
2999
2830
  if event == "SessionStart":
@@ -3018,9 +2849,11 @@ def setup_smart_compact(dry_run=None, uninstall=None, status_only=None,
3018
2849
  added = False
3019
2850
  if not has_compact_matcher:
3020
2851
  event_hooks.append({"matcher": "compact", "hooks": [{"type": "command", "command": command}]})
2852
+ written.append(command)
3021
2853
  added = True
3022
2854
  if not has_new_session:
3023
2855
  event_hooks.append({"hooks": [{"type": "command", "command": new_session_cmd}]})
2856
+ written.append(new_session_cmd)
3024
2857
  added = True
3025
2858
 
3026
2859
  if added:
@@ -3036,6 +2869,7 @@ def setup_smart_compact(dry_run=None, uninstall=None, status_only=None,
3036
2869
  # Append to existing hook groups for this event
3037
2870
  hook_entry = {"type": "command", "command": command}
3038
2871
  hook_group = {"hooks": [hook_entry]}
2872
+ written.append(command)
3039
2873
 
3040
2874
  if event not in hooks:
3041
2875
  hooks[event] = []
@@ -3064,6 +2898,7 @@ def setup_smart_compact(dry_run=None, uninstall=None, status_only=None,
3064
2898
  if not _measure_facade._write_settings_atomic(settings, user_initiated=user_initiated):
3065
2899
  print("[Error] settings.json write was refused; smart compact hooks were not installed.", file=_measure_facade.sys.stderr)
3066
2900
  return
2901
+ hook_provenance.record_written(_measure_facade, _before, settings, written, "setup_smart_compact")
3067
2902
 
3068
2903
  print("[Token Optimizer] Smart Compaction installed.")
3069
2904
  print(f" Hooks added: {', '.join(installed)}")
@@ -3228,7 +3063,8 @@ def _fix_stale_settings_paths():
3228
3063
  return 0
3229
3064
  except Exception:
3230
3065
  return 0
3231
-
3066
+ import hook_provenance # records only rewrites of entries already proven ours
3067
+ hook_provenance.record_rewrites(_measure_facade, settings, new_settings, "fix_stale_settings_paths")
3232
3068
  return len(stale_roots)
3233
3069
 
3234
3070
 
@@ -3492,122 +3328,36 @@ def _heal_keepwarm_plist_path():
3492
3328
 
3493
3329
 
3494
3330
  def _fix_malformed_hook_commands():
3495
- """Detect and remove malformed hook commands from settings.json.
3331
+ """Remove malformed hook entries Token Optimizer can prove it wrote.
3496
3332
 
3497
- Targets two patterns that break hooks silently:
3498
- 1. Subshell commands ($(...) or backticks) referencing TO scripts —
3499
- written by Claude during interactive sessions, not by our installers.
3500
- 2. Double-$HOME paths ($HOME/Users/X/... or ${HOME}/Users/X/...) —
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.
3333
+ Proof is the provenance ledger or a byte-identical shipped template; the
3334
+ pass reads, proves and writes ONE resolved settings file under the
3335
+ settings lock. Script installs are re-provisioned after a removal. Returns
3336
+ the number removed. See hook_heal.heal_settings.
3510
3337
  """
3511
3338
  _measure_facade = _compat.facade()
3339
+ import hook_heal
3512
3340
  try:
3513
- # Writes `new_settings` (built from `current`) back.
3514
- current, _ok = _measure_facade._read_settings_for_write()
3515
- if not _ok:
3516
- return 0
3341
+ return hook_heal.heal_settings(_measure_facade)
3517
3342
  except Exception:
3518
3343
  return 0
3519
3344
 
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
3345
 
3588
3346
  def _is_malformed_to_hook(cmd):
3589
- """Check if a hook command is a malformed token-optimizer entry.
3347
+ """True when the malformed-hook healer would remove this command.
3590
3348
 
3591
- Returns True if the command references a known TO script AND contains
3592
- either a subshell pattern or a double-$HOME expansion.
3349
+ Provenance, not parsing: the exact command bytes must be recorded in the
3350
+ hook provenance ledger for the current settings file or be a shipped
3351
+ hooks.json template instantiated for this install, and the command must be
3352
+ malformed. A command Token Optimizer cannot prove it wrote is never ours,
3353
+ whatever path or basename it mentions. See hook_provenance.py.
3593
3354
  """
3594
3355
  _measure_facade = _compat.facade()
3595
3356
  if not cmd:
3596
3357
  return False
3597
- has_to_script = any(
3598
- _measure_facade.re.search(r'(?:^|[/\s])' + _measure_facade.re.escape(name) + r'(?:$|[\s])', cmd)
3599
- for name in _measure_facade._TO_SCRIPT_NAMES
3600
- )
3601
- if not has_to_script:
3602
- return False
3603
- has_subshell = "$(" in cmd or "`" in cmd
3604
- has_double_home = False
3605
- if _measure_facade.platform.system() == "Darwin":
3606
- has_double_home = (
3607
- "$HOME/Users/" in cmd or "$HOME/home/" in cmd
3608
- or "${HOME}/Users/" in cmd or "${HOME}/home/" in cmd
3609
- )
3610
- return has_subshell or has_double_home
3358
+ import hook_provenance
3359
+ prov = hook_provenance.Provenance.from_facade(_measure_facade)
3360
+ return prov.verdict(cmd) == "remove"
3611
3361
 
3612
3362
 
3613
3363
  def _command_drives_quality_cache(command):
@@ -4411,6 +4161,8 @@ def setup_quality_bar(dry_run=None, uninstall=None, status_only=None, force=None
4411
4161
  elif current["hook"]:
4412
4162
  skipped.append("cache hook")
4413
4163
  else:
4164
+ import hook_provenance
4165
+ _before = hook_provenance.contexts_of(settings) # provenance claims only what this write adds
4414
4166
  hooks = settings.setdefault("hooks", {})
4415
4167
  _py, _mp = _measure_facade._settings_hook_python_and_script(mp)
4416
4168
  hook_cmd = f"{_py} {_mp} quality-cache --quiet"
@@ -4492,6 +4244,8 @@ def setup_quality_bar(dry_run=None, uninstall=None, status_only=None, force=None
4492
4244
  if not quiet:
4493
4245
  print("[Error] settings.json write was refused; Quality Bar was not installed.", file=_measure_facade.sys.stderr)
4494
4246
  return
4247
+ if "cache hook" in installed:
4248
+ hook_provenance.record_written(_measure_facade, _before, settings, [hook_cmd], "setup_quality_bar")
4495
4249
  # Explicit install is an explicit opt-in — clear any prior opt-out.
4496
4250
  _measure_facade._set_quality_bar_disabled(False)
4497
4251