@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
@@ -1,8 +1,159 @@
1
+ """Vendored Tomli 2.2.1 (MIT, Taneli Hukkinen) as a single flat module.
2
+
3
+ Full TOML 1.0 parser used as the Python 3.9/3.10 fallback where stdlib
4
+ tomllib is absent.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ # SPDX-License-Identifier: MIT
9
+ # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
10
+ # Licensed to PSF under a Contributor Agreement.
11
+ # MIT License
12
+ #
13
+ # Copyright (c) 2021 Taneli Hukkinen
14
+ #
15
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ # of this software and associated documentation files (the "Software"), to deal
17
+ # in the Software without restriction, including without limitation the rights
18
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ # copies of the Software, and to permit persons to whom the Software is
20
+ # furnished to do so, subject to the following conditions:
21
+ #
22
+ # The above copyright notice and this permission notice shall be included in all
23
+ # copies or substantial portions of the Software.
24
+ #
25
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ # SOFTWARE.
32
+
33
+ from typing import Any, Callable, Tuple
34
+
35
+ # Type annotations
36
+ ParseFloat = Callable[[str], Any]
37
+ Key = Tuple[str, ...]
38
+ Pos = int
39
+
40
+
41
+ # SPDX-License-Identifier: MIT
42
+ # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
43
+ # Licensed to PSF under a Contributor Agreement.
44
+
45
+
46
+ from datetime import date, datetime, time, timedelta, timezone, tzinfo
47
+ from functools import lru_cache
48
+ import re
49
+ from typing import Any, Final
50
+
51
+
52
+ # E.g.
53
+ # - 00:32:00.999999
54
+ # - 00:32:00
55
+ _TIME_RE_STR: Final = (
56
+ r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.([0-9]{1,6})[0-9]*)?"
57
+ )
58
+
59
+ RE_NUMBER: Final = re.compile(
60
+ r"""
61
+ 0
62
+ (?:
63
+ x[0-9A-Fa-f](?:_?[0-9A-Fa-f])* # hex
64
+ |
65
+ b[01](?:_?[01])* # bin
66
+ |
67
+ o[0-7](?:_?[0-7])* # oct
68
+ )
69
+ |
70
+ [+-]?(?:0|[1-9](?:_?[0-9])*) # dec, integer part
71
+ (?P<floatpart>
72
+ (?:\.[0-9](?:_?[0-9])*)? # optional fractional part
73
+ (?:[eE][+-]?[0-9](?:_?[0-9])*)? # optional exponent part
74
+ )
75
+ """,
76
+ flags=re.VERBOSE,
77
+ )
78
+ RE_LOCALTIME: Final = re.compile(_TIME_RE_STR)
79
+ RE_DATETIME: Final = re.compile(
80
+ rf"""
81
+ ([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) # date, e.g. 1988-10-27
82
+ (?:
83
+ [Tt ]
84
+ {_TIME_RE_STR}
85
+ (?:([Zz])|([+-])([01][0-9]|2[0-3]):([0-5][0-9]))? # optional time offset
86
+ )?
87
+ """,
88
+ flags=re.VERBOSE,
89
+ )
90
+
91
+
92
+ def match_to_datetime(match: re.Match) -> datetime | date:
93
+ """Convert a `RE_DATETIME` match to `datetime.datetime` or `datetime.date`.
94
+
95
+ Raises ValueError if the match does not correspond to a valid date
96
+ or datetime.
97
+ """
98
+ (
99
+ year_str,
100
+ month_str,
101
+ day_str,
102
+ hour_str,
103
+ minute_str,
104
+ sec_str,
105
+ micros_str,
106
+ zulu_time,
107
+ offset_sign_str,
108
+ offset_hour_str,
109
+ offset_minute_str,
110
+ ) = match.groups()
111
+ year, month, day = int(year_str), int(month_str), int(day_str)
112
+ if hour_str is None:
113
+ return date(year, month, day)
114
+ hour, minute, sec = int(hour_str), int(minute_str), int(sec_str)
115
+ micros = int(micros_str.ljust(6, "0")) if micros_str else 0
116
+ if offset_sign_str:
117
+ tz: tzinfo | None = cached_tz(
118
+ offset_hour_str, offset_minute_str, offset_sign_str
119
+ )
120
+ elif zulu_time:
121
+ tz = timezone.utc
122
+ else: # local date-time
123
+ tz = None
124
+ return datetime(year, month, day, hour, minute, sec, micros, tzinfo=tz)
125
+
126
+
127
+ # No need to limit cache size. This is only ever called on input
128
+ # that matched RE_DATETIME, so there is an implicit bound of
129
+ # 24 (hours) * 60 (minutes) * 2 (offset direction) = 2880.
130
+ @lru_cache(maxsize=None)
131
+ def cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone:
132
+ sign = 1 if sign_str == "+" else -1
133
+ return timezone(
134
+ timedelta(
135
+ hours=sign * int(hour_str),
136
+ minutes=sign * int(minute_str),
137
+ )
138
+ )
139
+
140
+
141
+ def match_to_localtime(match: re.Match) -> time:
142
+ hour_str, minute_str, sec_str, micros_str = match.groups()
143
+ micros = int(micros_str.ljust(6, "0")) if micros_str else 0
144
+ return time(int(hour_str), int(minute_str), int(sec_str), micros)
145
+
146
+
147
+ def match_to_number(match: re.Match, parse_float: ParseFloat) -> Any:
148
+ if match.group("floatpart"):
149
+ return parse_float(match.group())
150
+ return int(match.group(), 0)
151
+
152
+
1
153
  # SPDX-License-Identifier: MIT
2
154
  # SPDX-FileCopyrightText: 2021 Taneli Hukkinen
3
155
  # Licensed to PSF under a Contributor Agreement.
4
156
 
5
- from __future__ import annotations
6
157
 
7
158
  from collections.abc import Iterable
8
159
  import string
@@ -11,15 +162,6 @@ from types import MappingProxyType
11
162
  from typing import IO, Any, Final, NamedTuple
12
163
  import warnings
13
164
 
14
- from ._re import (
15
- RE_DATETIME,
16
- RE_LOCALTIME,
17
- RE_NUMBER,
18
- match_to_datetime,
19
- match_to_localtime,
20
- match_to_number,
21
- )
22
- from ._types import Key, ParseFloat, Pos
23
165
 
24
166
  # Inline tables/arrays are implemented using recursion. Pathologically
25
167
  # nested documents cause pure Python to raise RecursionError (which is OK),
@@ -768,3 +910,7 @@ def make_safe_parse_float(parse_float: ParseFloat) -> ParseFloat:
768
910
  return float_value
769
911
 
770
912
  return safe_parse_float
913
+
914
+
915
+ __all__ = ("loads", "load", "TOMLDecodeError")
916
+ __version__ = "2.2.1" # DO NOT EDIT THIS LINE MANUALLY. LET bump2version UTILITY DO IT
@@ -60,6 +60,9 @@ _PAYLOAD_MODULES = (
60
60
  # Dependency-free whitelist gate shared by bash_hook + bash_compress.
61
61
  "bash_whitelist.py",
62
62
  "command_filters.py",
63
+ # The 3.9/3.10 TOML parser command_filters lazy-imports when tomllib is
64
+ # absent; without it load_filters() silently returns an empty config.
65
+ "_tomli.py",
63
66
  "spawn_utils.py",
64
67
  "utf8_io.py",
65
68
  # credential_patterns: bash_compress's credential-preservation patterns
@@ -28,8 +28,8 @@ This module puts the REAL Token Optimizer there, not a reimplementation:
28
28
  Checks the install from inside a VM (or any machine).
29
29
 
30
30
  Rules this module keeps:
31
- * stdlib only, no imports from sibling modules: install runs under
32
- ``python3 -I`` straight out of the extracted tarball.
31
+ * stdlib only, no sibling imports (``python3 -I`` from the tarball); the one
32
+ exception, hook_provenance.py, is loaded by explicit path to record hooks.
33
33
  * nothing is written into any repository working tree.
34
34
  * settings are merged, never overwritten; only entries whose command runs
35
35
  our run.sh are ever replaced or removed; JSONC / duplicate keys refused.
@@ -41,6 +41,7 @@ from __future__ import annotations
41
41
  import base64
42
42
  import compileall
43
43
  import hashlib
44
+ import importlib.util
44
45
  import json
45
46
  import os
46
47
  import re
@@ -235,32 +236,19 @@ def _is_ours(group) -> bool:
235
236
 
236
237
 
237
238
  def _without_ours(groups: list) -> list:
238
- """The groups with our hook commands taken out, hook by hook. A group that
239
- also holds the user's own hooks (someone added one next to ours) keeps
240
- them, with its matcher and other keys; only a group left with no hooks at
241
- all is dropped. Groups without any of ours are returned untouched."""
239
+ """Our hook commands taken out, hook by hook. A group that also holds the user's own
240
+ hooks keeps them and its other keys; only a group left empty is dropped; others untouched."""
242
241
  kept = []
243
242
  for group in groups:
244
- if not _is_ours(group):
245
- kept.append(group)
246
- continue
247
- rest = [h for h in group["hooks"] if not _is_our_hook(h)]
248
- if rest:
249
- g = dict(group)
250
- g["hooks"] = rest
251
- kept.append(g)
243
+ rest = [h for h in group["hooks"] if not _is_our_hook(h)] if _is_ours(group) else None
244
+ if rest is None or rest:
245
+ kept.append(group if rest is None else dict(group, hooks=rest))
252
246
  return kept
253
247
 
254
248
 
255
249
  def _only_ours(groups: list) -> list:
256
250
  """The inverse view, for the doctor: each group cut down to our hooks."""
257
- out = []
258
- for group in groups:
259
- if _is_ours(group):
260
- g = dict(group)
261
- g["hooks"] = [h for h in group["hooks"] if _is_our_hook(h)]
262
- out.append(g)
263
- return out
251
+ return [dict(g, hooks=[h for h in g["hooks"] if _is_our_hook(h)]) for g in groups if _is_ours(g)]
264
252
 
265
253
 
266
254
  def merge_settings(settings: dict, hook_map: dict) -> dict:
@@ -349,9 +337,21 @@ def write_settings_hooks(settings_path: Path, hook_map) -> bool:
349
337
  # A file that held only our hooks is left as {} rather than deleted: we
350
338
  # cannot know whether something else created it.
351
339
  _atomic_write(settings_path, dump_settings(new, text))
340
+ _record_provenance(settings_path, data, new, hook_map or {})
352
341
  return True
353
342
 
354
343
 
344
+ def _record_provenance(path: Path, before: dict, after: dict, hook_map: dict) -> None:
345
+ """Record the hook entries this write added (hook_provenance.py, by path)."""
346
+ try:
347
+ spec = importlib.util.spec_from_file_location("hook_provenance", SCRIPTS_DIR / "hook_provenance.py")
348
+ hp = importlib.util.module_from_spec(spec)
349
+ spec.loader.exec_module(hp)
350
+ hp.record_cloud_write(path, before, after, hook_map)
351
+ except Exception: # noqa: BLE001 - provenance never blocks an install
352
+ pass
353
+
354
+
355
355
  def write_managed_fallback(hook_map: dict, directory=None) -> str:
356
356
  """Write the same hook map into our own managed-settings drop-in.
357
357
 
@@ -15,6 +15,7 @@ import codex_compact_prompt
15
15
  import codex_install
16
16
  import codex_state
17
17
  import codex_statusline
18
+ from hook_provenance import echo_command
18
19
 
19
20
  SUPPORTED_HOOK_EVENTS = {
20
21
  "PreToolUse",
@@ -291,16 +292,39 @@ def _status_line_check() -> dict[str, str]:
291
292
  return _check("WARN", "Codex CLI status line", "not configured; rerun codex-install with --enable-status-line")
292
293
 
293
294
 
294
- def _has_our_hooks(data: dict[str, Any]) -> bool:
295
+ def _has_our_hooks(data: dict[str, Any], hooks_path=None) -> bool:
295
296
  """Same ownership test the installer uses. The consolidated runner hooks
296
297
  carry no "token-optimizer/scripts" text on POSIX installs, so a substring
297
298
  check called a working install "no Token Optimizer hooks"."""
298
- for groups in data.get("hooks", {}).values():
299
- if isinstance(groups, list) and any(codex_install._is_token_optimizer_group(g) for g in groups):
299
+ proof = codex_install._codex_proof(hooks_path)
300
+ for event, groups in data.get("hooks", {}).items():
301
+ if isinstance(groups, list) and any(codex_install._is_token_optimizer_group(event, g, proof)
302
+ for g in groups):
300
303
  return True
301
304
  return False
302
305
 
303
306
 
307
+ # Our hook scripts as a hook names them (hooks/<script>, either separator), so a
308
+ # user's own run.py or *_runner.py elsewhere is not called one of ours.
309
+ _OUR_HOOK_SCRIPTS = tuple(sep.join(("hooks", name)) for name in (
310
+ "run.py", "module_runner.py", "posttooluse_runner.py", "sessionstart_runner.py",
311
+ "stop_runner.py", "userpromptsubmit_runner.py") for sep in ("/", "\\"))
312
+
313
+
314
+ def _unproven_hook_checks() -> list[dict[str, str]]:
315
+ """One line per hook that names our scripts but that Token Optimizer
316
+ cannot prove it wrote: installs and uninstalls leave it alone."""
317
+ hooks_path = codex_home() / "hooks.json"
318
+ data, error = _load_json(hooks_path)
319
+ if error or not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
320
+ return []
321
+ names = ("token-optimizer", "measure.py", "python-launcher.sh") + _OUR_HOOK_SCRIPTS
322
+ proof = codex_install._codex_proof(hooks_path)
323
+ return [_check("WARN", "Unrecognized hook", f"{echo_command(command, 120)} in {hooks_path}: not written by this "
324
+ "Token Optimizer install, so it was left alone; delete it there if you do not want it")
325
+ for command in proof.unproven(data, names)]
326
+
327
+
304
328
  def _global_hook_check() -> dict[str, str]:
305
329
  hooks_path = codex_home() / "hooks.json"
306
330
  data, error = _load_json(hooks_path)
@@ -308,7 +332,7 @@ def _global_hook_check() -> dict[str, str]:
308
332
  return _check("FAIL", "Global hooks", f"{hooks_path} not found; run measure.py codex-install")
309
333
  if not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
310
334
  return _check("FAIL", "Global hooks", f"{hooks_path} has no hooks object")
311
- if _has_our_hooks(data):
335
+ if _has_our_hooks(data, hooks_path):
312
336
  return _check("OK", "Global hooks", str(hooks_path))
313
337
  return _check("WARN", "Global hooks", f"no Token Optimizer hooks in {hooks_path}; run measure.py codex-install")
314
338
 
@@ -327,14 +351,15 @@ def _hook_shell_check() -> list[dict[str, str]]:
327
351
  ours = 0
328
352
  cmd_only = 0
329
353
  dev_only = 0
354
+ proof = codex_install._codex_proof(hooks_path)
330
355
  advices: list[str] = []
331
- for groups in data["hooks"].values():
356
+ for event, groups in data["hooks"].items():
332
357
  if not isinstance(groups, list):
333
358
  continue
334
359
  for group in groups:
335
360
  if not isinstance(group, dict):
336
361
  continue
337
- group_ours = codex_install._is_token_optimizer_group(group)
362
+ group_ours = codex_install._is_token_optimizer_group(event, group, proof)
338
363
  for hook in group.get("hooks", []):
339
364
  command = hook.get("command") if isinstance(hook, dict) else None
340
365
  if not isinstance(command, str):
@@ -421,7 +446,7 @@ def _project_hook_check(project: Path) -> dict[str, str]:
421
446
  return _check("WARN", "Project hooks", f"{hooks_path} not found; per-project hooks are optional when global hooks are installed")
422
447
  if not isinstance(data, dict) or not isinstance(data.get("hooks"), dict):
423
448
  return _check("FAIL", "Project hooks", f"{hooks_path} has no hooks object")
424
- if _has_our_hooks(data):
449
+ if _has_our_hooks(data, hooks_path):
425
450
  return _check("OK", "Project hooks", str(hooks_path))
426
451
  return _check("WARN", "Project hooks", f"no Token Optimizer hooks installed in {hooks_path}; manual refresh mode avoids visible Codex hook rows")
427
452
 
@@ -547,6 +572,7 @@ def run_checks(project: Path | None = None) -> list[dict[str, str]]:
547
572
  checks.append(_global_hook_check())
548
573
  checks.append(_stop_hook_activity_check())
549
574
  checks.extend(_hook_shell_check())
575
+ checks.extend(_unproven_hook_checks())
550
576
  checks.extend(_global_hook_config_checks())
551
577
  checks.append(_project_hook_check(project))
552
578
  checks.extend(_project_feature_checks(project))
@@ -0,0 +1,268 @@
1
+ """Exact-bytes ownership for Token Optimizer's Codex hooks.
2
+
3
+ Same rule as the Claude healer (hook_provenance.py): codex_install may replace
4
+ or remove a hook in ~/.codex/hooks.json (or a project .codex/hooks.json) only
5
+ when that hook's whole entry, ``(event, matcher, hook type, command)``, is
6
+
7
+ * recorded in the ledger for that hooks.json (every Codex write records
8
+ the entries it wrote, and every Codex run records the provable entries it
9
+ finds, so a later interpreter upgrade cannot orphan them), or
10
+ * an entry the current generator writes for this install, or
11
+ * byte-identical to an entry some shipped codex_install.py generated
12
+ (shipped_codex_hook_templates.json, harvested from git history with
13
+ placeholder paths), its command instantiated with this machine's real
14
+ install root, its parent, the running interpreter (on Windows also the
15
+ interpreter the command itself starts with, when it is one our generator
16
+ wrote, so an install from before a Python change is still found) and each
17
+ shipped version number.
18
+
19
+ Our command copied into another event or under another matcher is a
20
+ different entry and is not ours.
21
+
22
+ The ledger, its lock and its queue live in Token Optimizer's own Codex state
23
+ dir (``<CODEX_HOME>/token-optimizer/``), keyed by each hooks.json's resolved
24
+ path, never beside a project's .codex/hooks.json in the user's repo. Command-only records from before entries
25
+ were recorded prove nothing (the fail-safe choice).
26
+
27
+ No text markers, regexes, separator rewriting or signature normalization
28
+ decide ownership. A shipped version number appearing in a command only picks
29
+ which exact candidates to build; equality alone decides. Unproven hooks are
30
+ kept, whatever they mention.
31
+
32
+ Ownership is per hook command, not per group: a group mixing ours and a
33
+ foreign hook loses only ours.
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import json
38
+ import os
39
+ import sys
40
+ from pathlib import Path
41
+
42
+ import hook_provenance as hp
43
+
44
+ _MARK = "TOSENT"
45
+ # os.path, not Path(): Path() dispatches on os.name, so under an os.name="nt"
46
+ # simulation on POSIX it instantiates WindowsPath, which raises here.
47
+ _TEMPLATES_FILE = os.path.join(
48
+ os.path.dirname(os.path.realpath(__file__)),
49
+ "shipped_codex_hook_templates.json")
50
+ _SHIPPED = []
51
+
52
+
53
+ def shipped():
54
+ """The frozen harvest (loaded once). Unreadable => nothing proves by template."""
55
+ if not _SHIPPED:
56
+ try:
57
+ with open(_TEMPLATES_FILE, encoding="utf-8") as fh:
58
+ _SHIPPED.append(json.load(fh))
59
+ except (OSError, ValueError):
60
+ _SHIPPED.append({"placeholders": {}, "templates": {}, "versions": []})
61
+ return _SHIPPED[0]
62
+
63
+
64
+ def _is_semver(name):
65
+ parts = str(name).split(".")
66
+ return len(parts) == 3 and all(p.isdigit() for p in parts)
67
+
68
+
69
+ def hook_commands(group):
70
+ """The command strings a hooks.json group carries (any shape)."""
71
+ return [hook.get("command") for hook in _handlers(group)]
72
+
73
+
74
+ def _handlers(group):
75
+ """The dicts in a group that carry a command: its hooks, or the group
76
+ itself in the older one-command-per-group shape."""
77
+ if not isinstance(group, dict):
78
+ return []
79
+ hooks = group.get("hooks")
80
+ if isinstance(hooks, list):
81
+ return [h for h in hooks if isinstance(h, dict)]
82
+ return [group] if "command" in group else []
83
+
84
+
85
+ def entry_context(event, group, handler):
86
+ """``(event, matcher, type, command)`` of one handler, or None when it has
87
+ none a generator could have written. An absent matcher is ""."""
88
+ if not isinstance(event, str) or not isinstance(group, dict) or not isinstance(handler, dict):
89
+ return None
90
+ matcher, hook_type, command = group.get("matcher", ""), handler.get("type"), handler.get("command")
91
+ if not isinstance(matcher, str) or not isinstance(command, str) or not command:
92
+ return None
93
+ if hook_type is not None and not isinstance(hook_type, str):
94
+ return None
95
+ return (event, matcher, hook_type, command)
96
+
97
+
98
+ def contexts_in(event, group):
99
+ return [entry_context(event, group, handler) for handler in _handlers(group)]
100
+
101
+
102
+ _MAX_NAMED_INTERPRETERS = 4
103
+
104
+
105
+ class CodexProof:
106
+ def __init__(self, hooks_path, root, current_contexts=(), windows=None, executable=None,
107
+ ledger_dir=None):
108
+ self.windows = (sys.platform == "win32") if windows is None else bool(windows)
109
+ self.executable = sys.executable if executable is None else str(executable)
110
+ self.current = frozenset(c for c in current_contexts if isinstance(c, tuple) and len(c) == 4)
111
+ self.hooks_path = Path(hooks_path) if hooks_path else None
112
+ self.ledger_path = (Path(ledger_dir) / hp.CODEX_LEDGER_NAME
113
+ if self.hooks_path and ledger_dir is not None else None)
114
+ self.recorded = frozenset()
115
+ if self.ledger_path is not None:
116
+ ledger, status = hp.load_ledger(self.ledger_path)
117
+ if status == "ok":
118
+ self.recorded = frozenset(ledger["contexts"].get(hp.settings_key(self.hooks_path), {}))
119
+ self.root = root
120
+ self.root_str = str(root) if root is not None else ""
121
+ name = getattr(root, "name", "")
122
+ self.semver = root is not None and _is_semver(name)
123
+ self.parent_str = str(root.parent) if self.semver else ""
124
+ self.versions = frozenset(shipped()["versions"]) | ({name} if self.semver else frozenset())
125
+ self._cache = {}
126
+
127
+ def _shipped_for(self, executable):
128
+ """Placeholders and templates for this root and interpreter: spaced
129
+ placeholders only where the real path has a space, so the
130
+ generator's quoting matches byte for byte."""
131
+ plat = "windows" if self.windows else "posix"
132
+ variant = ("S" if " " in self.root_str else "P") + ("S" if " " in executable else "P")
133
+ return (shipped()["placeholders"].get(plat, {}).get(variant, {}),
134
+ shipped()["templates"].get(plat + "/" + variant, ()))
135
+
136
+ def _interpreters(self, command):
137
+ """The running interpreter, plus on Windows each interpreter the
138
+ command itself names (a quoted segment or a bare word) that is one our
139
+ generator wrote: an install from before a Python change must still be
140
+ found to be replaced. These only pick which candidates to build;
141
+ equality of the whole entry decides."""
142
+ found = [self.executable]
143
+ if self.windows and command:
144
+ import owned_hooks
145
+ for piece in command.split('"') + command.replace('"', " ").split():
146
+ if piece not in found and owned_hooks._our_interpreter(piece):
147
+ found.append(piece)
148
+ # Our commands name one interpreter. A few covers every
149
+ # real shape and keeps a crafted command from making the
150
+ # check build template sets for hundreds of paths.
151
+ if len(found) > _MAX_NAMED_INTERPRETERS:
152
+ break
153
+ return found
154
+
155
+ def _instances(self, version, executable=None):
156
+ executable = self.executable if executable is None else executable
157
+ key = (version, executable)
158
+ if key in self._cache:
159
+ return self._cache[key]
160
+ ph, templates = self._shipped_for(executable)
161
+ if not ph:
162
+ return frozenset()
163
+ if version is None:
164
+ subs = [(ph["dev"], self.root_str)]
165
+ else:
166
+ # The generator joined with the install's own path class.
167
+ subs = [(ph["root"], str(self.root.parent / version)), (ph["parent"], self.parent_str)]
168
+ subs.append((ph["python"], executable))
169
+ out = set()
170
+ for template in templates:
171
+ if not (isinstance(template, list) and len(template) == 4):
172
+ continue # a command-only template proves nothing
173
+ inst = template[3]
174
+ for placeholder, real in subs:
175
+ inst = inst.replace(placeholder, real)
176
+ if _MARK not in inst:
177
+ out.add((template[0], template[1], template[2], inst))
178
+ self._cache[key] = frozenset(out)
179
+ return self._cache[key]
180
+
181
+ def owns(self, context):
182
+ """True when this exact entry ``(event, matcher, type, command)`` is ours."""
183
+ if not (isinstance(context, tuple) and len(context) == 4) or self.root is None:
184
+ return False
185
+ if context in self.current or hp.context_digest(context) in self.recorded:
186
+ return True
187
+ for executable in self._interpreters(context[3]):
188
+ if not self.semver:
189
+ if context in self._instances(None, executable):
190
+ return True
191
+ elif any(context in self._instances(v, executable) for v in self.versions if v in context[3]):
192
+ return True
193
+ return False
194
+
195
+ def group_is_ours(self, event, group):
196
+ contexts = contexts_in(event, group)
197
+ return bool(contexts) and all(self.owns(c) for c in contexts)
198
+
199
+ def strip(self, event, group):
200
+ """``group`` under ``event`` without our hooks; None when nothing of it is left."""
201
+ if not isinstance(group, dict):
202
+ return group
203
+ hooks = group.get("hooks")
204
+ if not isinstance(hooks, list):
205
+ return None if self.group_is_ours(event, group) else group
206
+ kept = [h for h in hooks if not self.owns(entry_context(event, group, h))]
207
+ if len(kept) == len(hooks):
208
+ return group
209
+ if not kept:
210
+ return None
211
+ trimmed = dict(group)
212
+ trimmed["hooks"] = kept
213
+ return trimmed
214
+
215
+ def unproven(self, data, names):
216
+ """Commands present that mention one of ``names`` but are not proven.
217
+ Diagnostics only (doctor); never used to decide a removal."""
218
+ found = []
219
+ for event, group in _all_groups(data):
220
+ for handler in _handlers(group):
221
+ command = handler.get("command")
222
+ if isinstance(command, str) and not self.owns(entry_context(event, group, handler)) \
223
+ and any(n in command for n in names):
224
+ found.append(command)
225
+ return found
226
+
227
+ def record_present(self, data, extra=(), source="codex_seen"):
228
+ """Record every proven entry in ``data`` plus ``extra``, the entries
229
+ (contexts) this run just wrote. Idempotent; writes only when new."""
230
+ if self.ledger_path is None:
231
+ return False
232
+ contexts = [c for event, g in _all_groups(data) for c in contexts_in(event, g) if self.owns(c)]
233
+ contexts.extend(c for c in extra if isinstance(c, tuple) and len(c) == 4)
234
+ return hp.record_contexts(self.ledger_path, self.hooks_path, contexts, source)
235
+
236
+
237
+ def _all_groups(data):
238
+ hooks = data.get("hooks") if isinstance(data, dict) else None
239
+ for event, groups in hooks.items() if isinstance(hooks, dict) else ():
240
+ for group in groups if isinstance(groups, list) else ():
241
+ yield event, group
242
+
243
+
244
+ def for_codex(hooks_path, root, current_contexts, ledger_dir):
245
+ return CodexProof(hooks_path, root, current_contexts, ledger_dir=ledger_dir)
246
+
247
+
248
+ def _managed(managed_hooks):
249
+ import inspect
250
+ kw = {}
251
+ try:
252
+ for name, param in inspect.signature(managed_hooks).parameters.items():
253
+ if param.kind == param.KEYWORD_ONLY:
254
+ kw[name] = True
255
+ return managed_hooks(**kw) or {}
256
+ except Exception:
257
+ return {}
258
+
259
+
260
+ def current_contexts(managed_hooks):
261
+ """Every entry the current generator writes, all optional hooks on."""
262
+ return [c for event, groups in _managed(managed_hooks).items() for g in groups
263
+ for c in contexts_in(event, g) if c is not None]
264
+
265
+
266
+ def current_commands(managed_hooks):
267
+ """Every command the current generator writes, all optional hooks on."""
268
+ return [c[3] for c in current_contexts(managed_hooks)]