@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
@@ -399,13 +399,15 @@ def _rollup_lease_held(home: Path) -> bool:
399
399
  return False
400
400
 
401
401
 
402
- def _touch_rollup_lease(home: Path) -> None:
402
+ def _touch_rollup_lease(home: Path) -> bool:
403
+ """Touch the rollup lease; False when the write failed (degraded dir)."""
403
404
  lease = _to_dir(home) / "rollup.lease"
404
405
  try:
405
406
  lease.parent.mkdir(parents=True, exist_ok=True)
406
407
  lease.touch()
408
+ return True
407
409
  except OSError:
408
- pass
410
+ return False
409
411
 
410
412
 
411
413
  def handle_stop(payload: dict) -> dict:
@@ -421,7 +423,13 @@ def handle_stop(payload: dict) -> dict:
421
423
  if measure_py is None:
422
424
  return {}
423
425
 
424
- _touch_rollup_lease(home)
426
+ if not _touch_rollup_lease(home):
427
+ # Fail closed (the Cursor bridge's throttle-state rule, R12): on a
428
+ # read-only/full data dir the lease can never be observed held, so
429
+ # without this guard EVERY stop would spawn a detached
430
+ # rollup+dashboard pair - a process storm under exactly the degraded
431
+ # conditions the lease exists to contain.
432
+ return {}
425
433
 
426
434
  try:
427
435
  from spawn_utils import spawn_detached
@@ -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
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env python3
2
2
  """Token Optimizer v5: Bash Output Compression Wrapper.
3
3
 
4
- Invoked by bash_hook.py via PreToolUse command rewriting:
4
+ Shared PostToolUse and host-bridge compression; optional direct wrapper:
5
5
  bash_compress.py git status
6
6
  bash_compress.py pytest tests/
7
7
 
8
- Runs the command, captures output, applies pattern-matched compression.
9
- On ANY error, returns raw output unchanged (fail-open).
8
+ The legacy bash_hook.py no longer rewrites PreToolUse commands. Direct calls
9
+ capture and compress output; errors retain raw output unchanged (fail-open).
10
10
 
11
11
  Security:
12
12
  - shell=True is NEVER used
@@ -2,9 +2,8 @@
2
2
  """Token Optimizer v5.12: PostToolUse Bash Compression Hook.
3
3
 
4
4
  Compresses Bash tool output AFTER execution via Claude Code's
5
- ``updatedToolOutput`` mechanism. This is the UNIT B expansion: it handles
6
- pipeline and metachar-containing commands that PreToolUse bash_hook.py
7
- categorically rejects.
5
+ ``updatedToolOutput`` mechanism. Handles eligible simple commands and
6
+ pipelines after execution, without rewriting or approving the original call.
8
7
 
9
8
  Architecture:
10
9
  CC runs Bash tool → PostToolUse fires → this hook receives tool_response
@@ -13,11 +12,11 @@ Architecture:
13
12
  enforce the baseline-size invariant → updatedToolOutput replaces what
14
13
  Claude sees.
15
14
 
16
- The existing PreToolUse bash_hook.py continues to handle simple (metachar-free)
17
- commands. This hook handles everything else — pipes, &&, ||, ;, redirections,
18
- heredocs, and command substitutions.
15
+ The legacy PreToolUse bash_hook.py entry point is silent and is not registered.
16
+ PostToolUse compression covers read-only simple commands and supported pipelines,
17
+ including commands with pipes, &&, ||, ;, redirections, heredocs, and substitutions.
19
18
 
20
- Safety (same stack as bash_hook.py):
19
+ Safety:
21
20
  - Fail-open: any exception → exit 0 with no output → Claude sees raw result
22
21
  - Read-only only: pipeline_analyzer rejects any side-effecting stage
23
22
  - No double-execution: command already ran; we only compress captured output
@@ -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
 
@@ -102,11 +102,11 @@ _TABLE_HEADER_RE = re.compile(r"(?m)^[ \t]*\[\[?[^\[\]\n]+\]\]?[ \t]*(?:#.*)?$")
102
102
 
103
103
  def _toml_root_value(config_text: str):
104
104
  """Return (state, root value of the setting). state is "ok", "invalid"
105
- (the text does not parse) or "unavailable" (no TOML parser, Python < 3.11)."""
105
+ (the text does not parse). Both readers support TOML 1.0."""
106
106
  try:
107
107
  import tomllib # Python 3.11+
108
108
  except ImportError:
109
- return "unavailable", None
109
+ from _measure._vendor import tomli as tomllib
110
110
  try:
111
111
  data = tomllib.loads(config_text)
112
112
  except Exception:
@@ -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)]