@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.
Files changed (75) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/package.json +1 -1
  5. package/skills/fleet-auditor/references/fleet-systems.md +38 -0
  6. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  7. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  8. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  9. package/skills/token-coach/SKILL.md +21 -23
  10. package/skills/token-dashboard/SKILL.md +5 -4
  11. package/skills/token-optimizer/SKILL.md +1 -1
  12. package/skills/token-optimizer/assets/dashboard.html +101 -50
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  15. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  16. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  17. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  18. package/skills/token-optimizer/scripts/_measure/_vendor/README.md +8 -2
  19. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +46 -6
  20. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +34 -3
  21. package/skills/token-optimizer/scripts/_measure/audit.py +5 -21
  22. package/skills/token-optimizer/scripts/_measure/cli.py +86 -0
  23. package/skills/token-optimizer/scripts/_measure/daemon.py +34 -76
  24. package/skills/token-optimizer/scripts/_measure/dashboard.py +63 -37
  25. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  26. package/skills/token-optimizer/scripts/_measure/lifecycle.py +88 -528
  27. package/skills/token-optimizer/scripts/_measure/savings.py +20 -70
  28. package/skills/token-optimizer/scripts/_measure/sessions.py +58 -20
  29. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  30. package/skills/token-optimizer/scripts/{_measure/_vendor/tomli/_parser.py → _tomli.py} +156 -10
  31. package/skills/token-optimizer/scripts/antigravity_install.py +7 -0
  32. package/skills/token-optimizer/scripts/bash_compress.py +8 -40
  33. package/skills/token-optimizer/scripts/bash_compress_hook.py +6 -0
  34. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  35. package/skills/token-optimizer/scripts/cloud_kit.py +22 -22
  36. package/skills/token-optimizer/scripts/codex_doctor.py +34 -8
  37. package/skills/token-optimizer/scripts/codex_hook_provenance.py +268 -0
  38. package/skills/token-optimizer/scripts/codex_install.py +33 -69
  39. package/skills/token-optimizer/scripts/command_filters.py +39 -309
  40. package/skills/token-optimizer/scripts/copilot_install.py +9 -0
  41. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  42. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  43. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  44. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  45. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  46. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  47. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  48. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  49. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  50. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  51. package/skills/token-optimizer/scripts/cursor_install.py +111 -19
  52. package/skills/token-optimizer/scripts/cursor_quality.py +505 -0
  53. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  54. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  55. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  56. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  57. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  58. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  59. package/skills/token-optimizer/scripts/devin_install.py +6 -12
  60. package/skills/token-optimizer/scripts/devin_source.py +17 -6
  61. package/skills/token-optimizer/scripts/devin_verify.py +17 -0
  62. package/skills/token-optimizer/scripts/grok_install.py +9 -0
  63. package/skills/token-optimizer/scripts/heal_report.py +92 -0
  64. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  65. package/skills/token-optimizer/scripts/hermes_install.py +4 -1
  66. package/skills/token-optimizer/scripts/hook_heal.py +138 -0
  67. package/skills/token-optimizer/scripts/hook_provenance.py +878 -0
  68. package/skills/token-optimizer/scripts/measure.py +2 -2
  69. package/skills/token-optimizer/scripts/owned_hooks.py +420 -0
  70. package/skills/token-optimizer/scripts/shipped_codex_hook_templates.json +5815 -0
  71. package/skills/token-optimizer/scripts/shipped_hook_templates.py +252 -0
  72. package/skills/token-optimizer/scripts/shipped_starter_hooks.py +55 -0
  73. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
  74. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +0 -112
  75. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_types.py +0 -10
@@ -23,7 +23,7 @@ if str(SCRIPTS) not in sys.path:
23
23
  sys.path.insert(0, str(SCRIPTS))
24
24
 
25
25
  import devin_state as state
26
- from devin_verify import PAYLOAD
26
+ from devin_verify import PAYLOAD, payload_key_shapes
27
27
  from py_trust import py_path_is_trusted
28
28
  import devin_hooks as hooks
29
29
  SKILL_NAME = 'token-optimizer-output'
@@ -132,16 +132,12 @@ def _ownership(*, allow_missing=False) -> dict | None:
132
132
  raise OSError('invalid ownership record; run uninstall --purge (which also removes stored captures) to discard adapter state')
133
133
  if not isinstance(record, dict) or record.get('owner') != MARKER or not isinstance(record.get('files'), dict):
134
134
  raise OSError('invalid ownership record; run uninstall --purge (which also removes stored captures) to discard adapter state')
135
- expected = {str(state.data_dir() / 'plugin' / name) for name in PAYLOAD} | {str(skill_dir() / 'SKILL.md')}
136
- # Earlier releases shipped fewer payload files: 5.13.43 had no hook module,
137
- # and releases before it also lacked the two plugin-env modules.
138
- previous = expected - {str(state.data_dir() / 'plugin' / 'devin_hooks.py')}
139
- legacy = previous - {str(state.data_dir() / 'plugin' / name) for name in ('plugin_env.py', 'refetch_fingerprint.py')}
135
+ _, shapes = payload_key_shapes(state.data_dir() / 'plugin', PAYLOAD, skill_dir() / 'SKILL.md')
140
136
  try:
141
137
  record_keys = _resolved_keys(record['files'])
142
138
  except (OSError, ValueError, TypeError, RuntimeError):
143
139
  raise OSError('recorded paths cannot be resolved; run uninstall --purge (which also removes stored captures) to discard adapter state')
144
- if record_keys not in (sorted(expected), sorted(previous), sorted(legacy)):
140
+ if record_keys not in shapes:
145
141
  # A recorded path routed through a symlink resolves elsewhere; name the
146
142
  # real cause before falling through to the version/spelling advice.
147
143
  for name in record['files']:
@@ -533,16 +529,14 @@ def _recover_pending() -> None:
533
529
  value=json.loads(_private_bytes(pending))
534
530
  except (ValueError,RecursionError):
535
531
  value=None
536
- expected={str(state.data_dir()/'plugin'/name) for name in PAYLOAD}|{str(skill_dir()/'SKILL.md')}
537
- previous=expected - {str(state.data_dir()/'plugin'/'devin_hooks.py')}
538
- legacy=previous - {str(state.data_dir()/'plugin'/name) for name in ('plugin_env.py','refetch_fingerprint.py')}
532
+ expected,shapes=payload_key_shapes(state.data_dir()/'plugin',PAYLOAD,skill_dir()/'SKILL.md')
539
533
  files=value.get('files') if isinstance(value,dict) else None
540
534
  try:
541
535
  keys=_resolved_keys(files) if isinstance(files,dict) else None
542
536
  except (OSError,ValueError,TypeError,RuntimeError):
543
537
  keys=None
544
538
  if (not isinstance(value,dict) or value.get('owner')!=MARKER
545
- or keys not in (sorted(expected),sorted(previous),sorted(legacy))):
539
+ or keys not in shapes):
546
540
  raise OSError('invalid pending install record: ' + str(pending) + '; preserved; run uninstall --purge (which also removes stored captures) to discard adapter state')
547
541
  # Reconcile published new bytes first: stale pending must not undo a completed update.
548
542
  if manifest_path().exists():
@@ -563,7 +557,7 @@ def _recover_pending() -> None:
563
557
  raise OSError('pending version/content ambiguous: ' + str(pending) + '; preserved; run uninstall --purge (which also removes stored captures) to discard adapter state, or follow the documented manual repair')
564
558
  old=value.get('previous')
565
559
  if old is not None:
566
- if not isinstance(old,dict) or _resolved_keys(old) not in (sorted(expected),sorted(legacy)):raise OSError('invalid refresh recovery record')
560
+ if not isinstance(old,dict) or _resolved_keys(old) not in shapes:raise OSError('invalid refresh recovery record')
567
561
  if any(not isinstance(content,str) for content in old.values()) or not isinstance(value.get('previous_manifest'),str):
568
562
  raise OSError('invalid refresh recovery encoding')
569
563
  previous={name:base64.b64decode(content,validate=True) for name,content in old.items()}
@@ -9,24 +9,26 @@ import stat
9
9
  import sys
10
10
 
11
11
  PAYLOAD = ('devin_compress.py', 'devin_state.py', 'devin_doctor.py', 'devin_verify.py', 'devin_source.py',
12
- 'bash_compress.py', 'bash_whitelist.py', 'credential_patterns.py',
12
+ 'bash_compress.py', 'bash_search_results.py', 'bash_whitelist.py', 'credential_patterns.py',
13
+ 'credential_url_patterns.py',
13
14
  'token_estimate.py', 'command_filters.py', 'runtime_env.py', 'py_trust.py', 'plugin_env.py', 'refetch_fingerprint.py',
14
- 'devin_hooks.py')
15
+ '_tomli.py', 'devin_hooks.py')
15
16
  ALLOWED_MODULES = frozenset(Path(name).stem for name in PAYLOAD)
16
17
 
17
18
  # Repo names outside the installed closure must never fall back to sys.path.
18
19
  REPO_MODULES = frozenset((
19
- '_measure',
20
+ '_measure', '_tomli',
20
21
  'activity_tracker', 'adapter_hook_command', 'antigravity_doctor', 'antigravity_hook_bridge', 'antigravity_install',
21
22
  'antigravity_proto', 'antigravity_session', 'antigravity_state', 'archive_result',
22
- 'bash_compress', 'bash_compress_hook', 'bash_hook', 'bash_whitelist', 'benchmark', 'cloud_kit',
23
+ 'bash_compress', 'bash_search_results', 'bash_compress_hook', 'bash_hook', 'bash_whitelist', 'benchmark', 'cloud_kit',
23
24
  'build_output_compress', 'codex_command_compress', 'codex_compact_prompt', 'codex_doctor',
24
- 'codex_hook_bridge', 'codex_install', 'codex_io', 'codex_log_index', 'codex_models',
25
+ 'codex_hook_bridge', 'codex_hook_provenance', 'codex_install', 'codex_io', 'codex_log_index', 'codex_models',
25
26
  'codex_session', 'codex_state', 'codex_statusline', 'command_filters',
26
27
  'compression_backfill', 'compression_log', 'context_intel', 'context_pressure',
27
28
  'copilot_doctor', 'copilot_hook_bridge', 'copilot_install', 'copilot_session',
28
29
  'copilot_state', 'copilot_vscode', 'cowork_doctor', 'cowork_install',
29
- 'credential_patterns', 'cursor_doctor', 'cursor_hook_bridge', 'cursor_install',
30
+ 'credential_patterns', 'heal_report', 'hook_heal', 'hook_provenance', 'owned_hooks',
31
+ 'shipped_hook_templates', 'shipped_starter_hooks', 'cursor_doctor', 'cursor_hook_bridge', 'cursor_install',
30
32
  'cursor_session', 'cursor_state', 'delta_diff', 'detectors', 'deterministic_candidates',
31
33
  'devin_compress', 'devin_doctor', 'devin_hooks', 'devin_install', 'devin_source', 'devin_state',
32
34
  'devin_verify', 'grok_doctor', 'grok_hook_bridge', 'grok_install', 'grok_session',
@@ -36,6 +38,15 @@ REPO_MODULES = frozenset((
36
38
  'read_cache', 'recovery_output', 'refetch_fingerprint', 'refetch_guard', 'routing_advisor',
37
39
  'reset_epoch', 'runtime_env', 'session_activity', 'session_store', 'spawn_utils', 'structure_map', 'structure_map_ts',
38
40
  'structure_replay', 'thrash_guard', 'token_estimate', 'tool_search_diagnostic', 'utf8_io', 'archive_window', 'checkpoint_state',
41
+ 'cursor_audit',
42
+ 'cursor_coach',
43
+ 'cursor_bridge_checkpoint', 'cursor_bridge_payload', 'cursor_bridge_rewrite', 'cursor_bridge_rollup',
44
+ 'credential_url_patterns',
45
+ 'cursor_quality',
46
+ 'cursor_read_cache',
47
+ 'cursor_statusline',
48
+ 'cursor_thrash',
49
+ 'cursor_transcript',
39
50
  ))
40
51
 
41
52
  class SourceOnly(importlib.abc.MetaPathFinder, importlib.abc.Loader):
@@ -65,3 +65,20 @@ def verify_install():
65
65
  state.private_path(state.data_dir()/'consent.json')
66
66
  if not state.consent_ok():raise OSError('missing local data consent')
67
67
  return True
68
+
69
+
70
+ def payload_key_shapes(plugin, names, skill_md):
71
+ """Recorded-key sets for every payload shape an install record may carry.
72
+
73
+ Returns ``(expected, shapes)``: the current payload's path set plus the
74
+ sorted key lists for both independent module additions and older releases.
75
+ """
76
+ expected={str(plugin/name) for name in names}|{str(skill_md)}
77
+ tomli=str(plugin/'_tomli.py')
78
+ search=str(plugin/'bash_search_results.py')
79
+ urls=str(plugin/'credential_url_patterns.py')
80
+ variants=(expected,expected-{search},expected-{urls},expected-{search,urls})
81
+ before_both=expected-{search,urls}
82
+ previous=before_both-{str(plugin/'devin_hooks.py'),tomli}
83
+ legacy=previous-{str(plugin/name) for name in ('plugin_env.py','refetch_fingerprint.py')}
84
+ return expected,tuple(sorted(keys) for keys in (*variants,before_both-{tomli},previous,legacy))
@@ -56,11 +56,17 @@ _PAYLOAD_MODULES = (
56
56
  "grok_session.py",
57
57
  "bash_hook.py",
58
58
  "bash_compress.py",
59
+ "bash_search_results.py",
59
60
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
60
61
  # Without it, `import bash_hook` fails in the installed path, the bridge
61
62
  # sets _bash_hook = None, and the entire PreToolUse bash compression
62
63
  # feature silently no-ops.
63
64
  "bash_whitelist.py",
65
+ # command_filters + _tomli: user [filters.*] TOML config consulted by
66
+ # bash_compress/bash_whitelist; _tomli is the 3.9/3.10 parser it
67
+ # lazy-imports when tomllib is absent.
68
+ "command_filters.py",
69
+ "_tomli.py",
64
70
  "hook_io.py",
65
71
  "plugin_env.py",
66
72
  "runtime_env.py",
@@ -79,6 +85,9 @@ _PAYLOAD_MODULES = (
79
85
  # credential_patterns: bash_compress's credential-preservation patterns
80
86
  # (the inline fallback misses e.g. ghp_/github_pat_ tokens, #171).
81
87
  "credential_patterns.py",
88
+ # credential_patterns imports this at module import time (URL family split
89
+ # under the 1,000-line ratchet); missing = import failure in the payload.
90
+ "credential_url_patterns.py",
82
91
  )
83
92
 
84
93
  # One-line locator written next to the bridge, naming the canonical measure.py
@@ -0,0 +1,92 @@
1
+ """Doctor and health rows for the settings self-heal.
2
+
3
+ Two kinds of rows:
4
+
5
+ * "Settings self-heal": restore history from heal_log.jsonl (moved here
6
+ verbatim from audit.doctor so that legacy file could shrink).
7
+ * "Hook left alone": every hook in settings.json that looks like a broken
8
+ Token Optimizer hook but that Token Optimizer cannot prove it wrote (the
9
+ healer's "hook_unproven" verdict, hook_provenance.py). One plain line each:
10
+ what it is, where it lives, that it was left alone and can be deleted.
11
+
12
+ The hook list is computed live from settings.json with the healer's own
13
+ verdict, not replayed from the heal log: the log is capped and does not know
14
+ when the user deletes a hook, so it would show stale or missing entries.
15
+ Everything here is read-only and never raises into doctor/health.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+
21
+ import hook_provenance as hp
22
+
23
+ _SHOWN = 110
24
+
25
+
26
+ def unproven_hooks(facade):
27
+ """[(event, command, settings_path)] for hooks the healer leaves alone and
28
+ reports. Empty on any error."""
29
+ try:
30
+ data, path = facade._read_settings_json()
31
+ hooks = data.get("hooks") if isinstance(data, dict) else None
32
+ if not isinstance(hooks, dict):
33
+ return []
34
+ prov = hp.Provenance.from_facade(facade)
35
+ found, seen = [], set()
36
+ for event, groups in hooks.items():
37
+ for group in groups if isinstance(groups, list) else ():
38
+ for hook in (group.get("hooks") or []) if isinstance(group, dict) else ():
39
+ command = hook.get("command") if isinstance(hook, dict) else None
40
+ # One row per entry: the same command in two events is two hooks to look at.
41
+ key = hp.entry_context(event, group, hook) or (event, command)
42
+ if not isinstance(command, str) or key in seen:
43
+ continue
44
+ if prov.verdict_entry(event, group, hook) == hp.UNPROVEN and prov.reportable(command):
45
+ seen.add(key)
46
+ found.append((str(event), command, str(path)))
47
+ return found
48
+ except Exception:
49
+ return []
50
+
51
+
52
+ def describe(event, command, settings_path):
53
+ """One plain line: what it is, where it lives, what to do."""
54
+ shown = hp.echo_command(command, _SHOWN)
55
+ return (f"{event} hook `{shown}` in {settings_path} looks broken but was not written by "
56
+ "Token Optimizer, so Token Optimizer left it alone. Delete it there if you don't want it.")
57
+
58
+
59
+ def doctor_rows(facade):
60
+ """(status, name, detail) rows for doctor. Informational: callers append
61
+ them without touching the score."""
62
+ rows = []
63
+ try:
64
+ heal_log = facade._settings_heal_dir() / "heal_log.jsonl"
65
+ if heal_log.is_file():
66
+ entries = [json.loads(line) for line in heal_log.read_text(encoding="utf-8").strip().split("\n")
67
+ if line.strip()]
68
+ restores = [e for e in entries if e.get("action") == "restore"]
69
+ if restores:
70
+ last = restores[-1]
71
+ keys = ", ".join(last.get("restored_keys", [])[:5])
72
+ if len(last.get("restored_keys", [])) > 5:
73
+ keys += f" (+{len(last['restored_keys']) - 5} more)"
74
+ rows.append(("OK", "Settings self-heal",
75
+ f"{len(restores)} restore(s), last: {keys} at {last.get('timestamp', '?')[:19]}"))
76
+ else:
77
+ rows.append(("OK", "Settings self-heal", "no restores needed"))
78
+ else:
79
+ rows.append(("OK", "Settings self-heal", "no heal history yet"))
80
+ except Exception:
81
+ pass # doctor must never fail on heal history
82
+ for event, command, path in unproven_hooks(facade):
83
+ rows.append(("WARN", "Hook left alone", describe(event, command, path)))
84
+ return rows
85
+
86
+
87
+ def health_lines(facade):
88
+ """Lines for `measure.py health` (empty when there is nothing to say)."""
89
+ found = unproven_hooks(facade)
90
+ if not found:
91
+ return []
92
+ return ["", f"HOOKS LEFT ALONE ({len(found)})"] + [" - " + describe(*entry) for entry in found]
@@ -80,6 +80,9 @@ REQUIRED_ENGINE_SCRIPTS = (
80
80
  "read_cache.py",
81
81
  "refetch_guard.py",
82
82
  "credential_patterns.py",
83
+ # credential_patterns imports this at module import time (URL family split
84
+ # under the 1,000-line ratchet); missing = import failure in the payload.
85
+ "credential_url_patterns.py",
83
86
  )
84
87
 
85
88
  # Copied into the plugin dir by hermes_install; a copy older than the checkout
@@ -351,7 +354,7 @@ _MEASURE_PACKAGE_FILES = (
351
354
  "_measure/pricing.py", "_measure/audit.py", "_measure/dashboard.py",
352
355
  "_measure/lifecycle.py", "_measure/sessions.py", "_measure/trends.py",
353
356
  "_measure/cache_policy.py", "_measure/daemon.py", "_measure/quality_archive.py",
354
- "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py",
357
+ "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py",
355
358
  )
356
359
 
357
360
 
@@ -73,6 +73,9 @@ _ENGINE_SCRIPTS = (
73
73
  "read_cache.py",
74
74
  "refetch_guard.py",
75
75
  "credential_patterns.py",
76
+ # credential_patterns imports this at module import time (URL family split
77
+ # under the 1,000-line ratchet); missing = import failure in the payload.
78
+ "credential_url_patterns.py",
76
79
  )
77
80
 
78
81
  # Plain-text locator file written into the plugin dir: one line, the absolute
@@ -96,7 +99,7 @@ _MEASURE_PACKAGE_FILES = (
96
99
  "_measure/pricing.py", "_measure/audit.py", "_measure/dashboard.py",
97
100
  "_measure/lifecycle.py", "_measure/sessions.py", "_measure/trends.py",
98
101
  "_measure/cache_policy.py", "_measure/daemon.py", "_measure/quality_archive.py",
99
- "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py",
102
+ "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py",
100
103
  )
101
104
 
102
105
 
@@ -0,0 +1,138 @@
1
+ """The settings.json heal transaction: the malformed-hook healer's plan and
2
+ its one bound write (lifecycle._fix_malformed_hook_commands).
3
+
4
+ Ownership comes from hook_provenance (the ledger and the frozen shipped
5
+ contexts); this module only decides, per entry in its context, and writes
6
+ under the settings lock. Lives beside measure.py and must stay importable
7
+ on Python 3.9 with the standard library only.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ from pathlib import Path
13
+
14
+ import hook_provenance as hp
15
+
16
+
17
+ def _resolved(path):
18
+ try:
19
+ return Path(path).resolve(strict=False)
20
+ except (OSError, ValueError, RuntimeError):
21
+ return None
22
+
23
+
24
+ def _read_settings_at(dest):
25
+ """The settings object stored at exactly ``dest``, or None when it is
26
+ missing, not a regular file, unreadable, not JSON or not an object."""
27
+ try:
28
+ data = json.loads(hp._read_regular(dest).decode("utf-8-sig"))
29
+ except (OSError, ValueError):
30
+ return None
31
+ return data if isinstance(data, dict) else None
32
+
33
+
34
+ def plan_removals(settings, prov):
35
+ """``(new_hooks, removed, kept_contexts, unproven)`` for one settings
36
+ object. Pure: decides per hook entry, in its context; mutates nothing."""
37
+ hooks = settings.get("hooks") if isinstance(settings, dict) else None
38
+ if not isinstance(hooks, dict) or not hooks:
39
+ return None, 0, [], []
40
+ removed, new_hooks, kept_contexts, unproven = 0, {}, [], []
41
+ for event, groups in hooks.items():
42
+ if not isinstance(groups, list):
43
+ new_hooks[event] = groups
44
+ continue
45
+ new_groups = []
46
+ for group in groups:
47
+ entries = group.get("hooks", []) if isinstance(group, dict) else None
48
+ if not isinstance(entries, list):
49
+ new_groups.append(group)
50
+ continue
51
+ kept = []
52
+ for hook in entries:
53
+ if not isinstance(hook, dict):
54
+ kept.append(hook)
55
+ continue
56
+ command = hook.get("command", "")
57
+ verdict = prov.verdict_entry(event, group, hook)
58
+ if verdict == hp.REMOVE:
59
+ removed += 1
60
+ continue
61
+ if verdict == hp.UNPROVEN:
62
+ unproven.append((event, command))
63
+ context = hp.entry_context(event, group, hook)
64
+ if context is not None:
65
+ kept_contexts.append(context)
66
+ kept.append(hook)
67
+ if kept:
68
+ new_group = dict(group)
69
+ new_group["hooks"] = kept
70
+ new_groups.append(new_group)
71
+ if new_groups:
72
+ new_hooks[event] = new_groups
73
+ return new_hooks, removed, kept_contexts, unproven
74
+
75
+
76
+ def _write_bound(facade, dest, prov):
77
+ """Under the settings lock: confirm SETTINGS_PATH still resolves to
78
+ ``dest``, fresh-read ``dest``, re-plan with the proof keyed to ``dest``
79
+ and write only if the file is still the one read (identity check right
80
+ before os.replace, which re-resolves). Any drift writes nothing.
81
+ Returns ``(removed, plan)``; ``plan`` is None when nothing was decided."""
82
+ with facade._settings_lock() as acquired:
83
+ if not acquired or _resolved(facade.SETTINGS_PATH) != dest:
84
+ return 0, None
85
+ identity = facade._settings_file_identity(dest)
86
+ fresh = _read_settings_at(dest)
87
+ if fresh is None:
88
+ return 0, None
89
+ plan = plan_removals(fresh, prov)
90
+ if not plan[1] or _resolved(facade.SETTINGS_PATH) != dest:
91
+ return 0, plan
92
+ new_settings = dict(fresh)
93
+ new_settings["hooks"] = plan[0]
94
+ if not facade._write_settings_atomic_locked(new_settings, expect_identity=identity):
95
+ return 0, plan
96
+ return plan[1], plan
97
+
98
+
99
+ def heal_settings(facade):
100
+ """The malformed-hook heal pass (lifecycle._fix_malformed_hook_commands).
101
+
102
+ SETTINGS_PATH is resolved ONCE; that destination is what is read, what
103
+ keys the proof, and what is written. A symlink retargeted mid-pass can
104
+ never get one file judged with another file's proof, or an A-derived
105
+ payload written into B. Returns the number of removed entries.
106
+ """
107
+ dest = _resolved(facade.SETTINGS_PATH)
108
+ current = _read_settings_at(dest) if dest is not None else None
109
+ if current is None:
110
+ return 0
111
+ prov = hp.Provenance.from_facade(facade, settings_path=dest)
112
+ plan = plan_removals(current, prov)
113
+ if plan[0] is None:
114
+ return 0
115
+ removed = 0
116
+ if plan[1]:
117
+ removed, fresh_plan = _write_bound(facade, dest, prov)
118
+ plan = fresh_plan or plan
119
+ # Seed on first run, report unproven entries once; never a removal.
120
+ prov.finish(plan[2], plan[3], log=facade._settings_heal_log)
121
+ if not removed:
122
+ return 0
123
+ try: # next session re-runs the full hook heal cycle
124
+ facade._write_config_flag("last_hook_heal_check", 0)
125
+ except Exception:
126
+ pass
127
+ # Script installs need the current hooks back now; plugin installs get
128
+ # them from hooks.json.
129
+ if not facade._is_plugin_installed():
130
+ warn = " [Token Optimizer] Warning: hook re-provisioning failed after cleanup: %s"
131
+ try:
132
+ result = facade.setup_all_hooks(dry_run=False, verbose=False)
133
+ if result.get("error"):
134
+ print(warn % result["error"], file=facade.sys.stderr)
135
+ except Exception as exc:
136
+ print(warn % exc, file=facade.sys.stderr)
137
+ return removed
138
+