@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
@@ -18,6 +18,8 @@ from typing import Any
18
18
  import codex_compact_prompt
19
19
  import codex_io
20
20
  import codex_statusline
21
+ import codex_hook_provenance
22
+ import hook_provenance
21
23
  from runtime_env import codex_home
22
24
 
23
25
  TOKEN_OPTIMIZER_MARKER = "token-optimizer/scripts"
@@ -96,7 +98,6 @@ def _short_path(path: str) -> str | None:
96
98
  return None
97
99
  try:
98
100
  import ctypes
99
-
100
101
  buf = ctypes.create_unicode_buffer(32768)
101
102
  n = ctypes.windll.kernel32.GetShortPathNameW(path, buf, len(buf))
102
103
  if 0 < n < len(buf) and os.path.exists(buf.value):
@@ -636,64 +637,19 @@ def _load_hooks(path: Path) -> dict[str, Any]:
636
637
  return data
637
638
 
638
639
 
639
- # Anchors for the generated Windows versioned-install command signature.
640
- # _hook_command has emitted exactly two such shapes: the current one, which
641
- # invokes the consolidated runner through the FOR variable
642
- # ("{base}\%R\hooks\run.py"), and the pre-5.13.12 broken one, which invoked it
643
- # through the delayed-expansion var ("!TOKEN_OPTIMIZER_RUNTIME_ROOT!\hooks\
644
- # run.py"). Both always carry the quoted set-assignment AND a hooks\run.py
645
- # runner invocation rooted under a token-optimizer directory (or through one
646
- # of OUR OWN variables, which a foreign command cannot use). Matching on the
647
- # assignment alone silently deletes a user's own hook that merely references
648
- # our env var, so all anchors must hold TOGETHER. (The patterns run on the
649
- # JSON-serialized group, where a literal " arrives as \" and \ as \\, hence
650
- # the escaped-quote and separator-class spellings.)
651
- _WIN_ROOT_SET_RE = re.compile(r'set \\"TOKEN_OPTIMIZER_RUNTIME_ROOT=')
652
- _WIN_RUNNER_RE = re.compile(r'hooks[/\\]+run\.py')
653
- _WIN_TO_DIR_RE = re.compile(r'token-optimizer[/\\]')
654
- _WIN_RUNNER_VIA_VAR_RE = re.compile(
655
- r'(?:!TOKEN_OPTIMIZER_RUNTIME_ROOT!|%R)[/\\]+hooks[/\\]+run\.py'
656
- )
640
+ def _codex_proof(path=None):
641
+ """Exact-bytes ownership for this hooks.json (codex_hook_provenance)."""
642
+ return codex_hook_provenance.for_codex(
643
+ path, _repo_root(), codex_hook_provenance.current_contexts(_managed_hooks),
644
+ codex_home() / "token-optimizer")
657
645
 
658
646
 
659
- # The consolidated runners (hooks/<event>_runner.py) carry no
660
- # "token-optimizer/scripts" text on POSIX marketplace installs, so without this
661
- # signature a reinstall appended a second copy of each runner hook and uninstall
662
- # left them all behind. Ours = a runner name AND our hooks/run.py (or
663
- # python-launcher.sh) AND a path under a token-optimizer folder, together.
664
- _RUNNER_SCRIPT_RE = re.compile(
665
- r'hooks[/\\]+(?:sessionstart|userpromptsubmit|posttooluse|stop)_runner\.py'
666
- )
667
- _RUNNER_ENTRY_RE = re.compile(r'hooks[/\\]+(?:run\.py|python-launcher\.sh)|\$\{R\}hooks/')
668
-
669
-
670
- def _is_token_optimizer_group(group: Any) -> bool:
671
- # The path marker misses generated Windows commands: on versioned
672
- # marketplace installs the baked paths use backslashes
673
- # (...\token-optimizer\X.Y.Z\hooks\run.py) and consolidated-runner args
674
- # like hooks/stop_runner.py, so "token-optimizer/scripts" never appears
675
- # in them. Those commands are instead identified by their full generated
676
- # signature, so a foreign hook that merely contains
677
- # set "TOKEN_OPTIMIZER_RUNTIME_ROOT= (or %TOKEN_OPTIMIZER_RUNTIME_ROOT%,
678
- # or a POSIX-style VAR=x prefix) is never swept up by reinstall/uninstall.
679
- serialized = json.dumps(group, sort_keys=True)
680
- if TOKEN_OPTIMIZER_MARKER in serialized:
681
- return True
682
- if (
683
- _RUNNER_SCRIPT_RE.search(serialized)
684
- and _RUNNER_ENTRY_RE.search(serialized)
685
- and _WIN_TO_DIR_RE.search(serialized)
686
- ):
687
- return True
688
- if not _WIN_ROOT_SET_RE.search(serialized):
689
- return False
690
- return (
691
- _WIN_RUNNER_VIA_VAR_RE.search(serialized) is not None
692
- or (
693
- _WIN_RUNNER_RE.search(serialized) is not None
694
- and _WIN_TO_DIR_RE.search(serialized) is not None
695
- )
696
- )
647
+ def _is_token_optimizer_group(event: str, group: Any, proof=None) -> bool:
648
+ # Ours only when every command in the group is proven by exact bytes: in
649
+ # the ledger beside hooks.json, or generated by a shipped codex_install for
650
+ # this install. Text markers decided this before and deleted foreign hooks
651
+ # that merely mentioned our names.
652
+ return (proof or _codex_proof()).group_is_ours(event, group)
697
653
 
698
654
 
699
655
  # Matches the --baked-root token of a generated launcher-file command, as
@@ -749,7 +705,9 @@ def _merge_hooks(
749
705
  enable_hot_path_hooks: bool = False,
750
706
  enable_prompt_hooks: bool = False,
751
707
  enable_subagent_hooks: bool = False,
708
+ proof=None,
752
709
  ) -> dict[str, Any]:
710
+ proof = proof or _codex_proof()
753
711
  result = json.loads(json.dumps(existing))
754
712
  hooks = result.setdefault("hooks", {})
755
713
  managed = _managed_hooks(
@@ -764,7 +722,7 @@ def _merge_hooks(
764
722
  groups = []
765
723
  for fresh_group in managed.get(event, []):
766
724
  for old_group in groups:
767
- if not _is_token_optimizer_group(old_group):
725
+ if not proof.group_is_ours(event, old_group):
768
726
  continue
769
727
  old_handlers = old_group.get('hooks', [])
770
728
  fresh_handlers = fresh_group.get('hooks', [])
@@ -772,20 +730,21 @@ def _merge_hooks(
772
730
  old_handler, fresh_handler = old_handlers[0], fresh_handlers[0]
773
731
  if _launcher_signature(old_handler.get('command', '')) == _launcher_signature(fresh_handler.get('command', '')):
774
732
  fresh_handler['command'] = old_handler['command']
775
- hooks[event] = [group for group in groups if not _is_token_optimizer_group(group)]
733
+ hooks[event] = [g for g in (proof.strip(event, g) for g in groups) if g is not None]
776
734
  hooks[event].extend(managed.get(event, []))
777
735
  if not hooks[event]:
778
736
  hooks.pop(event, None)
779
737
  return result
780
738
 
781
739
 
782
- def _remove_hooks(existing: dict[str, Any]) -> dict[str, Any]:
740
+ def _remove_hooks(existing: dict[str, Any], proof=None) -> dict[str, Any]:
741
+ proof = proof or _codex_proof()
783
742
  result = json.loads(json.dumps(existing))
784
743
  hooks = result.setdefault("hooks", {})
785
744
  for event, groups in list(hooks.items()):
786
745
  if not isinstance(groups, list):
787
746
  continue
788
- kept = [group for group in groups if not _is_token_optimizer_group(group)]
747
+ kept = [g for g in (proof.strip(event, g) for g in groups) if g is not None]
789
748
  if kept:
790
749
  hooks[event] = kept
791
750
  else:
@@ -860,9 +819,9 @@ def install(
860
819
  force_status_line: bool = False,
861
820
  ) -> tuple[Path, str, dict[str, Any]]:
862
821
  path = _global_hooks_path(ensure_dir=not dry_run) if is_global else _hooks_path(project)
863
- existing = _load_hooks(path)
822
+ existing, proof = _load_hooks(path), _codex_proof(path)
864
823
  updated = _merge_hooks(
865
- existing,
824
+ existing, proof=proof,
866
825
  enable_bash_compression=enable_bash_compression,
867
826
  enable_hot_path_hooks=enable_hot_path_hooks,
868
827
  enable_prompt_hooks=enable_prompt_hooks,
@@ -896,7 +855,7 @@ def install(
896
855
  details["compact_prompt"] = codex_compact_prompt.install(force=force_compact_prompt)
897
856
  if enable_status_line:
898
857
  details["status_line"] = codex_statusline.install(force=force_status_line)
899
- codex_io.atomic_write_json(path, updated)
858
+ hook_provenance.write_codex_hooks(path, updated, proof, codex_io.atomic_write_json)
900
859
  return path, "installed", details
901
860
 
902
861
 
@@ -1046,13 +1005,13 @@ def heal_quoted_launcher_commands(paths=None) -> int:
1046
1005
  try:
1047
1006
  if not path.is_file():
1048
1007
  continue
1049
- data = _load_hooks(path)
1008
+ data, proof, rewritten = _load_hooks(path), _codex_proof(path), []
1050
1009
  changed = 0
1051
- for groups in data.get("hooks", {}).values():
1010
+ for event, groups in data.get("hooks", {}).items():
1052
1011
  if not isinstance(groups, list):
1053
1012
  continue
1054
1013
  for group in groups:
1055
- if not _is_token_optimizer_group(group):
1014
+ if not proof.group_is_ours(event, group):
1056
1015
  continue
1057
1016
  for handler in group.get("hooks", []):
1058
1017
  command = handler.get("command") if isinstance(handler, dict) else None
@@ -1062,13 +1021,18 @@ def heal_quoted_launcher_commands(paths=None) -> int:
1062
1021
  if (neutral is not None and neutral != command
1063
1022
  and launcher_ready(command)):
1064
1023
  handler["command"] = neutral
1024
+ rewritten.append(codex_hook_provenance.entry_context(event, group, handler))
1065
1025
  changed += 1
1066
1026
  elif (command.startswith('"') and _LAUNCHER_MARKER in command):
1067
1027
  handler["command"] = f"{_WIN_UNQUOTED_PREFIX} {command}"
1028
+ rewritten.append(codex_hook_provenance.entry_context(event, group, handler))
1068
1029
  changed += 1
1069
1030
  if changed:
1070
- codex_io.atomic_write_json(path, data)
1031
+ hook_provenance.write_codex_hooks(path, data, proof, codex_io.atomic_write_json,
1032
+ rewritten, "codex_heal")
1071
1033
  fixed += changed
1034
+ else:
1035
+ proof.record_present(data) # seed: survives a later interpreter upgrade
1072
1036
  except Exception:
1073
1037
  continue
1074
1038
  return fixed
@@ -1077,7 +1041,7 @@ def heal_quoted_launcher_commands(paths=None) -> int:
1077
1041
  def uninstall(project: Path, *, is_global: bool = False, dry_run: bool = False) -> tuple[Path, str, dict[str, Any]]:
1078
1042
  path = _global_hooks_path() if is_global else _hooks_path(project)
1079
1043
  existing = _load_hooks(path)
1080
- updated = _remove_hooks(existing)
1044
+ updated = _remove_hooks(existing, _codex_proof(path))
1081
1045
  details: dict[str, Any] = {"hook_events": sorted(updated.get("hooks", {}).keys())}
1082
1046
  # Reverse the config.toml writes the installer made: the compact-prompt
1083
1047
  # managed block + prompt file and the [tui]