@alexgreensh/token-optimizer 5.13.67 → 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 (31) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/package.json +1 -1
  4. package/skills/token-optimizer/scripts/_measure/_vendor/README.md +8 -2
  5. package/skills/token-optimizer/scripts/_measure/_vendor/__init__.py +46 -6
  6. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/__init__.py +34 -3
  7. package/skills/token-optimizer/scripts/_measure/audit.py +5 -21
  8. package/skills/token-optimizer/scripts/_measure/daemon.py +21 -51
  9. package/skills/token-optimizer/scripts/_measure/lifecycle.py +82 -521
  10. package/skills/token-optimizer/scripts/{_measure/_vendor/tomli/_parser.py → _tomli.py} +156 -10
  11. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  12. package/skills/token-optimizer/scripts/cloud_kit.py +21 -21
  13. package/skills/token-optimizer/scripts/codex_doctor.py +33 -7
  14. package/skills/token-optimizer/scripts/codex_hook_provenance.py +268 -0
  15. package/skills/token-optimizer/scripts/codex_install.py +33 -69
  16. package/skills/token-optimizer/scripts/command_filters.py +39 -309
  17. package/skills/token-optimizer/scripts/copilot_install.py +5 -0
  18. package/skills/token-optimizer/scripts/cursor_install.py +5 -0
  19. package/skills/token-optimizer/scripts/devin_install.py +6 -12
  20. package/skills/token-optimizer/scripts/devin_source.py +5 -4
  21. package/skills/token-optimizer/scripts/devin_verify.py +16 -0
  22. package/skills/token-optimizer/scripts/grok_install.py +5 -0
  23. package/skills/token-optimizer/scripts/heal_report.py +92 -0
  24. package/skills/token-optimizer/scripts/hook_heal.py +138 -0
  25. package/skills/token-optimizer/scripts/hook_provenance.py +878 -0
  26. package/skills/token-optimizer/scripts/owned_hooks.py +420 -0
  27. package/skills/token-optimizer/scripts/shipped_codex_hook_templates.json +5815 -0
  28. package/skills/token-optimizer/scripts/shipped_hook_templates.py +252 -0
  29. package/skills/token-optimizer/scripts/shipped_starter_hooks.py +55 -0
  30. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_re.py +0 -112
  31. package/skills/token-optimizer/scripts/_measure/_vendor/tomli/_types.py +0 -10
@@ -11,22 +11,23 @@ import sys
11
11
  PAYLOAD = ('devin_compress.py', 'devin_state.py', 'devin_doctor.py', 'devin_verify.py', 'devin_source.py',
12
12
  'bash_compress.py', 'bash_whitelist.py', 'credential_patterns.py',
13
13
  'token_estimate.py', 'command_filters.py', 'runtime_env.py', 'py_trust.py', 'plugin_env.py', 'refetch_fingerprint.py',
14
- 'devin_hooks.py')
14
+ '_tomli.py', 'devin_hooks.py')
15
15
  ALLOWED_MODULES = frozenset(Path(name).stem for name in PAYLOAD)
16
16
 
17
17
  # Repo names outside the installed closure must never fall back to sys.path.
18
18
  REPO_MODULES = frozenset((
19
- '_measure',
19
+ '_measure', '_tomli',
20
20
  'activity_tracker', 'adapter_hook_command', 'antigravity_doctor', 'antigravity_hook_bridge', 'antigravity_install',
21
21
  'antigravity_proto', 'antigravity_session', 'antigravity_state', 'archive_result',
22
22
  'bash_compress', 'bash_compress_hook', 'bash_hook', 'bash_whitelist', 'benchmark', 'cloud_kit',
23
23
  'build_output_compress', 'codex_command_compress', 'codex_compact_prompt', 'codex_doctor',
24
- 'codex_hook_bridge', 'codex_install', 'codex_io', 'codex_log_index', 'codex_models',
24
+ 'codex_hook_bridge', 'codex_hook_provenance', 'codex_install', 'codex_io', 'codex_log_index', 'codex_models',
25
25
  'codex_session', 'codex_state', 'codex_statusline', 'command_filters',
26
26
  'compression_backfill', 'compression_log', 'context_intel', 'context_pressure',
27
27
  'copilot_doctor', 'copilot_hook_bridge', 'copilot_install', 'copilot_session',
28
28
  'copilot_state', 'copilot_vscode', 'cowork_doctor', 'cowork_install',
29
- 'credential_patterns', 'cursor_doctor', 'cursor_hook_bridge', 'cursor_install',
29
+ 'credential_patterns', 'heal_report', 'hook_heal', 'hook_provenance', 'owned_hooks',
30
+ 'shipped_hook_templates', 'shipped_starter_hooks', 'cursor_doctor', 'cursor_hook_bridge', 'cursor_install',
30
31
  'cursor_session', 'cursor_state', 'delta_diff', 'detectors', 'deterministic_candidates',
31
32
  'devin_compress', 'devin_doctor', 'devin_hooks', 'devin_install', 'devin_source', 'devin_state',
32
33
  'devin_verify', 'grok_doctor', 'grok_hook_bridge', 'grok_install', 'grok_session',
@@ -65,3 +65,19 @@ 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 of the current, pre-Tomli, previous and legacy shapes.
75
+ Earlier releases shipped fewer payload files: 5.13.43 had no hook module,
76
+ releases before it also lacked the two plugin-env modules, and every
77
+ existing record predates the _tomli.py payload module shipped now.
78
+ """
79
+ expected={str(plugin/name) for name in names}|{str(skill_md)}
80
+ tomli=str(plugin/'_tomli.py')
81
+ previous=expected-{str(plugin/'devin_hooks.py'),tomli}
82
+ legacy=previous-{str(plugin/name) for name in ('plugin_env.py','refetch_fingerprint.py')}
83
+ return expected,tuple(sorted(keys) for keys in (expected,expected-{tomli},previous,legacy))
@@ -61,6 +61,11 @@ _PAYLOAD_MODULES = (
61
61
  # sets _bash_hook = None, and the entire PreToolUse bash compression
62
62
  # feature silently no-ops.
63
63
  "bash_whitelist.py",
64
+ # command_filters + _tomli: user [filters.*] TOML config consulted by
65
+ # bash_compress/bash_whitelist; _tomli is the 3.9/3.10 parser it
66
+ # lazy-imports when tomllib is absent.
67
+ "command_filters.py",
68
+ "_tomli.py",
64
69
  "hook_io.py",
65
70
  "plugin_env.py",
66
71
  "runtime_env.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]
@@ -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
+