@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
@@ -1942,45 +1942,8 @@ def _compress_search_results(output):
1942
1942
  if not files:
1943
1943
  return output # not file:line format, don't compress
1944
1944
 
1945
- _MAX_PER_FILE = 3
1946
- _MAX_FILES = 20
1947
- result: list[str] = []
1948
- file_count = 0
1949
- file_items = list(files.items())
1950
- for fname, file_lines in file_items:
1951
- if file_count >= _MAX_FILES:
1952
- break
1953
- if len(file_lines) <= _MAX_PER_FILE:
1954
- result.extend(file_lines)
1955
- else:
1956
- result.extend(file_lines[:_MAX_PER_FILE])
1957
- result.append(f" ... {len(file_lines) - _MAX_PER_FILE} more matches in {fname} ...")
1958
- file_count += 1
1959
-
1960
- # Keep EVERY matching filename (cheap) so "does file X match?" stays
1961
- # answerable; only per-line CONTENT past the top-N is dropped, never names.
1962
- if file_count < len(file_items):
1963
- result.append(f"... plus {len(file_items) - file_count} more files with matches "
1964
- f"(filenames + counts, content omitted):")
1965
- for fname, file_lines in file_items[file_count:]:
1966
- result.append(f" {fname}: {len(file_lines)} matches")
1967
-
1968
- if no_file:
1969
- result.append("")
1970
- # "Binary file X matches" lines name a matching file; keep ALL of them so
1971
- # the banner's "a file not listed has NO matches" stays true for binaries.
1972
- binary = [ln for ln in no_file if ln.startswith("Binary file ") and " matches" in ln]
1973
- other = [ln for ln in no_file if not (ln.startswith("Binary file ") and " matches" in ln)]
1974
- result.extend(binary)
1975
- result.extend(other[:10])
1976
- if len(other) > 10:
1977
- result.append(f"... {len(other) - 10} more non-file lines omitted ...")
1978
-
1979
- total_matches = sum(len(v) for v in files.values())
1980
- result.insert(0, f"[Search results: {total_matches} matches across {len(files)} files. "
1981
- f"ALL matching filenames listed; per-line content shown for the top "
1982
- f"{_MAX_FILES}. A file not listed here has NO matches.]")
1983
- return "\n".join(result)
1945
+ from bash_search_results import render_search_results
1946
+ return render_search_results(files, no_file)
1984
1947
 
1985
1948
 
1986
1949
  _PATTERN_HANDLERS = {
@@ -2385,7 +2348,7 @@ def main():
2385
2348
 
2386
2349
  # Progressive disclosure: archive the raw original BEFORE compression
2387
2350
  # so the model can retrieve it via `expand <key>` if needed. Fail-open:
2388
- # if archiving fails, compression proceeds without the pointer.
2351
+ # if archiving fails, serve the original instead of a lossy preview.
2389
2352
  _archive_key = None
2390
2353
  if compressed != raw_output and len(raw_output) > 500:
2391
2354
  try:
@@ -2414,6 +2377,11 @@ def main():
2414
2377
  except Exception:
2415
2378
  _archive_key = None
2416
2379
 
2380
+ # Search matches must remain recoverable even below the archive floor
2381
+ # or when the archive write fails. Other handlers keep their contracts.
2382
+ if _archive_key is None and _detect_pattern(command_str) == "search_results":
2383
+ compressed = raw_output
2384
+
2417
2385
  # Record savings to trends.db if compression was meaningful
2418
2386
  try:
2419
2387
  orig_bytes = len(raw_output.encode("utf-8", errors="replace"))
@@ -302,6 +302,7 @@ def _run(payload: dict) -> None:
302
302
  _find_preserved_lines,
303
303
  _ERROR_STDERR_PATTERNS,
304
304
  _enforce_baseline_invariant,
305
+ _detect_pattern,
305
306
  )
306
307
 
307
308
  # --- check for failure (exit code or stderr patterns) ---
@@ -378,6 +379,11 @@ def _run(payload: dict) -> None:
378
379
  except Exception:
379
380
  _archive_key = None
380
381
 
382
+ # Search matches must remain recoverable even below the archive floor
383
+ # or when the archive write fails. Other handlers keep their contracts.
384
+ if _archive_key is None and _detect_pattern(command) == "search_results":
385
+ compressed = stdout
386
+
381
387
  # --- enforce the baseline-size invariant ---
382
388
  # If our compressed preview + archive pointer would exceed what
383
389
  # Claude Code would show as a baseline stub, shrink to fit.
@@ -0,0 +1,43 @@
1
+ """Render parsed search matches with explicit per-file and file-count limits."""
2
+
3
+
4
+ def render_search_results(files, no_file):
5
+ _MAX_PER_FILE = 3
6
+ _MAX_FILES = 20
7
+ result: list[str] = []
8
+ file_count = 0
9
+ file_items = list(files.items())
10
+ for fname, file_lines in file_items:
11
+ if file_count >= _MAX_FILES:
12
+ break
13
+ if len(file_lines) <= _MAX_PER_FILE:
14
+ result.extend(file_lines)
15
+ else:
16
+ result.extend(file_lines[:_MAX_PER_FILE])
17
+ result.append(f" ... {len(file_lines) - _MAX_PER_FILE} more matches in {fname} (content omitted) ...")
18
+ file_count += 1
19
+
20
+ # Keep EVERY matching filename (cheap) so "does file X match?" stays
21
+ # answerable; only per-line CONTENT past the top-N is dropped, never names.
22
+ if file_count < len(file_items):
23
+ result.append(f"... plus {len(file_items) - file_count} more files with matches "
24
+ f"(filenames + counts, content omitted):")
25
+ for fname, file_lines in file_items[file_count:]:
26
+ result.append(f" {fname}: {len(file_lines)} matches")
27
+
28
+ if no_file:
29
+ result.append("")
30
+ # "Binary file X matches" lines name a matching file; keep ALL of them so
31
+ # the banner's "a file not listed has NO matches" stays true for binaries.
32
+ binary = [ln for ln in no_file if ln.startswith("Binary file ") and " matches" in ln]
33
+ other = [ln for ln in no_file if not (ln.startswith("Binary file ") and " matches" in ln)]
34
+ result.extend(binary)
35
+ result.extend(other[:10])
36
+ if len(other) > 10:
37
+ result.append(f"... {len(other) - 10} more non-file lines omitted ...")
38
+
39
+ total_matches = sum(len(v) for v in files.values())
40
+ result.insert(0, f"[Search results: {total_matches} matches across {len(files)} files. "
41
+ f"ALL matching filenames listed; up to {_MAX_PER_FILE} matches per file "
42
+ f"shown for the first {_MAX_FILES} files. Other match content omitted.]")
43
+ return "\n".join(result)
@@ -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
 
@@ -488,7 +488,7 @@ _REQUIRED = ("hooks/hooks.json", "hooks/python-launcher.sh", "hooks/run.py",
488
488
  "skills/token-optimizer/scripts/_measure/" + name for name in (
489
489
  '__init__.py', '_compat.py', 'runtime.py', 'pricing.py', 'audit.py',
490
490
  'dashboard.py', 'lifecycle.py', 'sessions.py', 'trends.py', 'cache_policy.py',
491
- 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py',
491
+ 'daemon.py', 'quality_archive.py', 'continuity.py', 'savings.py', 'cli.py', 'dashboard_history.py', 'weekly_activity.py',
492
492
  )
493
493
  )
494
494
 
@@ -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",
@@ -63,7 +64,7 @@ _MEASURE_PACKAGE_FILES = (
63
64
  "_measure/pricing.py", "_measure/audit.py", "_measure/dashboard.py",
64
65
  "_measure/lifecycle.py", "_measure/sessions.py", "_measure/trends.py",
65
66
  "_measure/cache_policy.py", "_measure/daemon.py", "_measure/quality_archive.py",
66
- "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py",
67
+ "_measure/continuity.py", "_measure/savings.py", "_measure/cli.py", "_measure/dashboard_history.py", "_measure/weekly_activity.py",
67
68
  )
68
69
 
69
70
 
@@ -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)]