@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
@@ -0,0 +1,878 @@
1
+ """Provenance for Token Optimizer's own Claude Code hook entries.
2
+
3
+ The malformed-hook healer may delete a settings.json hook only when it can
4
+ prove Token Optimizer wrote that exact entry. An entry is its full context,
5
+ ``(event, matcher, hook type, command)``; proof is byte identity of that whole
6
+ tuple, nothing looser:
7
+
8
+ * the context is in the provenance ledger under this settings file (every
9
+ writer records the entries it adds, see ``record_written``), or
10
+ * it is byte-identical to a shipped hooks.json entry
11
+ (``shipped_hook_templates``) with the command instantiated for the running
12
+ install root, in one of the exact spellings setup_all_hooks writes.
13
+
14
+ The same command under another event or matcher is a different entry and is
15
+ not proven by either. Ledger records from before contexts existed (command
16
+ digests under "files") prove nothing for settings.json: the fail-safe choice.
17
+ Their in-context cases are exactly the shipped-template cases, which still
18
+ prove by template. Codex hooks.json keeps command-keyed records ("files").
19
+
20
+ There is deliberately no regex, shlex, quote stripping, separator rewriting,
21
+ case folding or prefix test anywhere on the removal path: every text
22
+ heuristic tried (PR #323) either deleted a foreign hook or missed ours; an
23
+ unproven entry is left alone and reported once instead.
24
+
25
+ Ledger: ``<CONFIG_DIR>/settings_heal/hook_provenance.json``. Writes take an
26
+ OS file lock (``flock`` / ``msvcrt.locking``) that the kernel holds exactly as
27
+ long as the owning process lives, re-read under it, union-merge and land with
28
+ tempfile + os.replace. A stalled but live writer keeps the lock, so a second
29
+ writer can never be told it succeeded and then lose its record to the first
30
+ one's older snapshot; it fails instead. A dead writer's lock is gone at once. Missing ledger: empty.
31
+ Unreadable: template-only and never overwritten. Corrupt: template-only, and
32
+ the next write moves it aside and starts fresh.
33
+
34
+ Lives beside measure.py (not in _measure/, whose file set is frozen) and must
35
+ stay importable on Python 3.9 with the standard library only.
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import contextlib
40
+ import errno
41
+ import hashlib
42
+ import json
43
+ import os
44
+ import stat
45
+ import tempfile
46
+ import time
47
+ from pathlib import Path
48
+
49
+ try:
50
+ import fcntl
51
+ except ImportError: # Windows
52
+ fcntl = None
53
+ try:
54
+ import msvcrt
55
+ except ImportError: # POSIX
56
+ msvcrt = None
57
+
58
+ try:
59
+ from shipped_hook_templates import SHIPPED_HOOK_CONTEXTS, SHIPPED_HOOK_TEMPLATES
60
+ except ImportError: # loaded by path under python -I (cloud_kit): the sibling, by path too
61
+ import importlib.util as _ilu
62
+ _spec = _ilu.spec_from_file_location(
63
+ "shipped_hook_templates", str(Path(__file__).with_name("shipped_hook_templates.py")))
64
+ _shipped = _ilu.module_from_spec(_spec)
65
+ _spec.loader.exec_module(_shipped)
66
+ SHIPPED_HOOK_CONTEXTS, SHIPPED_HOOK_TEMPLATES = (_shipped.SHIPPED_HOOK_CONTEXTS,
67
+ _shipped.SHIPPED_HOOK_TEMPLATES)
68
+
69
+ LEDGER_NAME = "hook_provenance.json"
70
+ LEDGER_VERSION = 1
71
+ CODEX_LEDGER_NAME = "hook_provenance.json" # in <CODEX_HOME>/token-optimizer/
72
+
73
+ # The exact version resolver every current installer-written command carries
74
+ # (hooks/hooks.json). Removing ONE exact copy before the subshell test keeps
75
+ # installer plumbing from reading as malformation; any other "$(" or backtick
76
+ # still counts. tests/test_malformed_detector_installer_resolver.py pins it to
77
+ # hooks.json byte for byte.
78
+ CURRENT_RESOLVER = 'D="$(ls -d "${D%[/\\\\]*}"/*/ 2>/dev/null | grep -E "/[0-9]+[.][0-9]+[.][0-9]+/$" | sort -V | tail -n1)"'
79
+
80
+ _DOUBLE_HOME = ("$HOME/Users/", "$HOME/home/", "${HOME}/Users/", "${HOME}/home/")
81
+ _PLACEHOLDERS = ("${CLAUDE_PLUGIN_ROOT}", "$CLAUDE_PLUGIN_ROOT")
82
+
83
+ KEEP = "keep"
84
+ REMOVE = "remove"
85
+ UNPROVEN = "unproven"
86
+
87
+
88
+ # --- identity -----------------------------------------------------------------
89
+
90
+ def command_digest(command):
91
+ """sha256 of the command's exact UTF-8 bytes (lone surrogates kept)."""
92
+ return hashlib.sha256(command.encode("utf-8", "surrogatepass")).hexdigest()
93
+
94
+
95
+ def context_digest(context):
96
+ """sha256 of one entry's full context ``(event, matcher, type, command)``."""
97
+ return hashlib.sha256(json.dumps(list(context)).encode("ascii")).hexdigest()
98
+
99
+
100
+ def entry_context(event, group, hook):
101
+ """The exact context of one settings.json hook entry, or None when it has
102
+ none we could ever have written (non-string matcher, type or command).
103
+ An absent matcher is "": setup_all_hooks' own group-selection rule."""
104
+ if not isinstance(group, dict) or not isinstance(hook, dict) or not isinstance(event, str):
105
+ return None
106
+ matcher, hook_type, command = group.get("matcher", ""), hook.get("type"), hook.get("command")
107
+ if not isinstance(matcher, str) or not isinstance(command, str) or not command:
108
+ return None
109
+ if hook_type is not None and not isinstance(hook_type, str):
110
+ return None
111
+ return (event, matcher, hook_type, command)
112
+
113
+
114
+ def iter_contexts(settings):
115
+ """Every entry context in a settings object (its "hooks" map)."""
116
+ hooks = settings.get("hooks") if isinstance(settings, dict) else None
117
+ for event, groups in hooks.items() if isinstance(hooks, dict) else ():
118
+ for group in groups if isinstance(groups, list) else ():
119
+ entries = group.get("hooks") if isinstance(group, dict) else None
120
+ for hook in entries if isinstance(entries, list) else ():
121
+ context = entry_context(event, group, hook)
122
+ if context is not None:
123
+ yield context
124
+
125
+
126
+ def contexts_of(settings):
127
+ """Multiset of entry contexts: take it from the read a writer derives its
128
+ payload from, and hand it to ``record_written`` after the write."""
129
+ counts = {}
130
+ for context in iter_contexts(settings):
131
+ counts[context] = counts.get(context, 0) + 1
132
+ return counts
133
+
134
+
135
+ def settings_key(settings_path):
136
+ """Stable per-file ledger key: absolute, symlink-resolved, OS-normcased.
137
+
138
+ Writer and healer both derive it from the same SETTINGS_PATH, so this only
139
+ has to be deterministic; it is never compared against a hook command.
140
+ """
141
+ try:
142
+ path = Path(settings_path).resolve(strict=False)
143
+ except (OSError, ValueError, RuntimeError):
144
+ path = Path(os.path.abspath(str(settings_path)))
145
+ return os.path.normcase(str(path))
146
+
147
+
148
+ def looks_malformed(command, darwin):
149
+ """Main's syntactic malformation test, unchanged: a subshell or backtick
150
+ left after removing one exact resolver, or a doubled $HOME on macOS."""
151
+ probe = command.replace(CURRENT_RESOLVER, 'D=""', 1)
152
+ if "$(" in probe or "`" in probe:
153
+ return True
154
+ return bool(darwin) and any(marker in command for marker in _DOUBLE_HOME)
155
+
156
+
157
+ def instantiate_contexts(contexts, roots, resolve=None):
158
+ """``instantiate`` for shipped contexts: same event, matcher and type,
159
+ command instantiated for each root spelling."""
160
+ out = set()
161
+ for event, matcher, hook_type, template in contexts:
162
+ for command in instantiate((template,), roots, resolve):
163
+ out.add((event, matcher, hook_type, command))
164
+ return frozenset(out)
165
+
166
+
167
+ def instantiate(templates, roots, resolve=None):
168
+ """Exact strings the given templates become for the given root spellings.
169
+
170
+ ``resolve`` is setup_all_hooks' own resolver (current output: forward
171
+ slashes on Windows). The plain substitution is the legacy spelling older
172
+ installers wrote with the native root. Both are forward instantiations of
173
+ shipped bytes; nothing is ever parsed back out of a settings command.
174
+ """
175
+ out = set()
176
+ for template in templates:
177
+ for root in roots:
178
+ plain = template
179
+ for placeholder in _PLACEHOLDERS:
180
+ plain = plain.replace(placeholder, root)
181
+ out.add(plain)
182
+ if resolve is not None:
183
+ try:
184
+ out.add(resolve(template, root))
185
+ except Exception:
186
+ pass
187
+ return frozenset(out)
188
+
189
+
190
+ # --- ledger -------------------------------------------------------------------
191
+
192
+ def _empty():
193
+ return {"version": LEDGER_VERSION, "files": {}, "seeded": {}, "reported": {},
194
+ "contexts": {}, "contexts_seeded": {}}
195
+
196
+
197
+ def _records_ok(section):
198
+ if not isinstance(section, dict):
199
+ return False
200
+ for key, entries in section.items():
201
+ if not isinstance(key, str) or not isinstance(entries, dict):
202
+ return False
203
+ if not all(isinstance(d, str) and isinstance(v, dict) for d, v in entries.items()):
204
+ return False
205
+ return True
206
+
207
+
208
+ def _valid(data):
209
+ if not isinstance(data, dict) or data.get("version") != LEDGER_VERSION:
210
+ return False
211
+ if not _records_ok(data.get("files")) or not _records_ok(data.get("contexts", {})):
212
+ return False
213
+ if not isinstance(data.get("contexts_seeded", {}), dict):
214
+ return False
215
+ seeded = data.get("seeded", {})
216
+ reported = data.get("reported", {})
217
+ if not isinstance(seeded, dict) or not isinstance(reported, dict):
218
+ return False
219
+ return all(isinstance(v, list) and all(isinstance(d, str) for d in v)
220
+ for v in reported.values())
221
+
222
+
223
+ def _read_regular(path):
224
+ """Bytes of a regular file, without ever blocking. open() on a FIFO waits
225
+ for a writer forever and a device can read forever, so anything that is
226
+ not a regular file raises OSError (the caller's "unreadable"). The stat
227
+ covers platforms without O_NONBLOCK; the fstat closes the swap-after-stat
228
+ race on the descriptor actually read."""
229
+ if not stat.S_ISREG(os.stat(str(path)).st_mode):
230
+ raise OSError("ledger is not a regular file")
231
+ fd = os.open(str(path), os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0))
232
+ try:
233
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
234
+ raise OSError("ledger is not a regular file")
235
+ chunks = []
236
+ while True:
237
+ chunk = os.read(fd, 1 << 16)
238
+ if not chunk:
239
+ return b"".join(chunks)
240
+ chunks.append(chunk)
241
+ finally:
242
+ os.close(fd)
243
+
244
+
245
+ def load_ledger(path):
246
+ """Return ``(ledger, status)``; status is ok, missing, unreadable or corrupt.
247
+
248
+ Anything but ok yields an empty ledger, so the caller proves by template
249
+ only (invariant: no ledger, no extra removals).
250
+ """
251
+ try:
252
+ raw = _read_regular(path)
253
+ except FileNotFoundError:
254
+ return _empty(), "missing"
255
+ except OSError:
256
+ return _empty(), "unreadable"
257
+ try:
258
+ data = json.loads(raw.decode("utf-8"))
259
+ except (UnicodeDecodeError, ValueError):
260
+ return _empty(), "corrupt"
261
+ version = data.get("version") if isinstance(data, dict) else None
262
+ if isinstance(version, int) and not isinstance(version, bool) and version != LEDGER_VERSION:
263
+ return _empty(), "unreadable" # another version's ledger: never ours to move or rewrite
264
+ if not _valid(data):
265
+ return _empty(), "corrupt"
266
+ for section in ("seeded", "reported", "contexts", "contexts_seeded"):
267
+ data.setdefault(section, {})
268
+ return data, "ok"
269
+
270
+
271
+ def _write_atomic(path, data):
272
+ tmp = None
273
+ try:
274
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".hook_provenance-", suffix=".json")
275
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
276
+ json.dump(data, handle, sort_keys=True, indent=1)
277
+ handle.flush()
278
+ try:
279
+ os.fsync(handle.fileno())
280
+ except OSError:
281
+ pass
282
+ if os.name != "nt":
283
+ try:
284
+ os.chmod(tmp, 0o600)
285
+ except OSError:
286
+ pass
287
+ os.replace(tmp, str(path))
288
+ tmp = None
289
+ return True
290
+ except OSError:
291
+ return False
292
+ finally:
293
+ if tmp is not None:
294
+ try:
295
+ os.unlink(tmp)
296
+ except OSError:
297
+ pass
298
+
299
+
300
+ # Errors that mean another process holds the lock: worth waiting for. Any
301
+ # other error (a filesystem without locks, a bad descriptor) never clears.
302
+ _BUSY = (frozenset((errno.EAGAIN, errno.EWOULDBLOCK, errno.EINTR)) if fcntl is not None
303
+ else frozenset((errno.EACCES, getattr(errno, "EDEADLOCK", errno.EDEADLK))))
304
+
305
+
306
+ def _try_lock(fd):
307
+ """True: locked. False: held by another process. None: unusable here."""
308
+ try:
309
+ if fcntl is not None:
310
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
311
+ else:
312
+ os.lseek(fd, 0, os.SEEK_SET)
313
+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
314
+ return True
315
+ except OSError as exc:
316
+ return False if exc.errno in _BUSY else None
317
+
318
+
319
+ def _unlock(fd):
320
+ try:
321
+ if fcntl is not None:
322
+ fcntl.flock(fd, fcntl.LOCK_UN)
323
+ else:
324
+ os.lseek(fd, 0, os.SEEK_SET)
325
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
326
+ except OSError:
327
+ pass
328
+
329
+
330
+ @contextlib.contextmanager
331
+ def _exclusive(lock_path, timeout=2.0):
332
+ """Yield True while this process holds the OS lock on ``lock_path``.
333
+
334
+ The kernel owns it: it stays exclusive for as long as the holder lives,
335
+ however long it stalls, and is released the moment it exits or dies. No
336
+ lease to expire, so no second owner while the first is still writing.
337
+ A lock file that is not a regular file (FIFO, device) is never waited on.
338
+ Exactly one yield on every path, so an exception from the body always
339
+ propagates as itself.
340
+ """
341
+ fd = _acquire(lock_path, timeout)
342
+ if fd is None:
343
+ yield False
344
+ return
345
+ try:
346
+ yield True
347
+ finally:
348
+ _unlock(fd)
349
+ os.close(fd)
350
+
351
+
352
+ def _acquire(lock_path, timeout):
353
+ """A descriptor holding the lock on ``lock_path``, or None."""
354
+ flags = os.O_RDWR | os.O_CREAT | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
355
+ try:
356
+ if os.path.lexists(str(lock_path)) and not stat.S_ISREG(os.stat(str(lock_path)).st_mode):
357
+ return None
358
+ fd = os.open(str(lock_path), flags, 0o600)
359
+ except OSError:
360
+ return None
361
+ try:
362
+ usable = stat.S_ISREG(os.fstat(fd).st_mode) and (fcntl is not None or msvcrt is not None)
363
+ deadline = time.monotonic() + timeout
364
+ while usable:
365
+ got = _try_lock(fd)
366
+ if got:
367
+ return fd
368
+ if got is None or time.monotonic() >= deadline:
369
+ break
370
+ time.sleep(0.01)
371
+ except OSError:
372
+ pass
373
+ except BaseException:
374
+ os.close(fd)
375
+ raise
376
+ os.close(fd)
377
+ return None
378
+
379
+
380
+ def _update(path, mutate):
381
+ """Locked read-merge-write. ``mutate(data)`` returns True when it changed
382
+ something. Returns ``(written, reset)``: reset is True when a corrupt
383
+ ledger was moved aside. Never raises; no lock, no write."""
384
+ path = Path(path)
385
+ try:
386
+ path.parent.mkdir(parents=True, exist_ok=True)
387
+ except OSError:
388
+ return False, False
389
+ lock = path.with_name(path.name + ".flock")
390
+ try:
391
+ with _exclusive(lock) as acquired:
392
+ if not acquired:
393
+ return False, False
394
+ data, status = load_ledger(path)
395
+ if status == "unreadable":
396
+ return False, False
397
+ reset = False
398
+ if status == "corrupt":
399
+ try:
400
+ os.replace(str(path), str(path.with_name(
401
+ "%s.corrupt-%d" % (path.name, int(time.time())))))
402
+ reset = True
403
+ except OSError:
404
+ return False, False
405
+ changed = mutate(data)
406
+ pending = _merge_pending(path, data)
407
+ if not (changed or reset or pending):
408
+ return True, False
409
+ written = _write_atomic(path, data)
410
+ for item in pending if written else ():
411
+ try:
412
+ os.unlink(str(item))
413
+ except OSError:
414
+ pass
415
+ return written, reset
416
+ except Exception:
417
+ return False, False
418
+
419
+
420
+ # --- pending records ------------------------------------------------------------
421
+ # A record whose locked write fails (lock held past the timeout, no lock
422
+ # support, unreadable ledger) is queued as one small file beside the ledger
423
+ # and merged by the next locked write that lands: late, never lost. Same
424
+ # directory and trust as the ledger. Only what a writer added is ever queued.
425
+
426
+ def _pending_dir(path):
427
+ path = Path(path)
428
+ return path.with_name(path.name + ".pending")
429
+
430
+
431
+ def _queued(path):
432
+ """Names of the queue's record files: regular files named as _queue names
433
+ them (64 lowercase hex). Anything else there is not ours and is ignored."""
434
+ try:
435
+ with os.scandir(str(_pending_dir(path))) as entries:
436
+ return sorted(e.name for e in entries if len(e.name) == 64
437
+ and all(c in "0123456789abcdef" for c in e.name)
438
+ and e.is_file(follow_symlinks=False))
439
+ except OSError:
440
+ return []
441
+
442
+
443
+ def has_pending(path):
444
+ return bool(_queued(path))
445
+
446
+
447
+ def _queue(path, section, key, entries):
448
+ """Queue ``entries`` (digest -> meta) for ``section``/``key``. True when
449
+ the file landed. Named by its content, so a retry adds no second file;
450
+ written beside the ledger and renamed in, so the queue only ever holds
451
+ complete files."""
452
+ tmp = None
453
+ try:
454
+ name = hashlib.sha256(json.dumps([section, key, sorted(entries)]).encode("utf-8")).hexdigest()
455
+ qdir = _pending_dir(path)
456
+ qdir.mkdir(mode=0o700, parents=True, exist_ok=True)
457
+ fd, tmp = tempfile.mkstemp(dir=str(qdir.parent), prefix=".hook_provenance-q-", suffix=".tmp")
458
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
459
+ json.dump({"section": section, "key": key, "entries": entries}, handle)
460
+ handle.flush()
461
+ os.fsync(handle.fileno())
462
+ os.replace(tmp, str(qdir / name))
463
+ tmp = None
464
+ return True
465
+ except (OSError, TypeError, ValueError):
466
+ return False
467
+ finally:
468
+ if tmp is not None:
469
+ try:
470
+ os.unlink(tmp)
471
+ except OSError:
472
+ pass
473
+
474
+
475
+ def _merge_pending(path, data):
476
+ """Fold every well-formed queued record into ``data``. Returns the record
477
+ files to delete once the ledger write lands: the merged ones, and any
478
+ that can never merge (unparseable), so neither stays pending forever."""
479
+ qdir, merged = _pending_dir(path), []
480
+ for name in _queued(path):
481
+ try:
482
+ body = json.loads(_read_regular(qdir / name).decode("utf-8"))
483
+ section, key, entries = body["section"], body["key"], body["entries"]
484
+ except OSError:
485
+ continue # unreadable now; retried on the next write
486
+ except (ValueError, KeyError, TypeError):
487
+ merged.append(qdir / name)
488
+ continue
489
+ if section not in ("files", "contexts") or not isinstance(key, str) \
490
+ or not _records_ok({key: entries}):
491
+ merged.append(qdir / name)
492
+ continue
493
+ target = data[section].setdefault(key, {})
494
+ for digest, meta in entries.items():
495
+ target.setdefault(digest, meta)
496
+ merged.append(qdir / name)
497
+ return merged
498
+
499
+
500
+ def _record_entries(ledger_path, section, key, entries):
501
+ """"ok" (in the ledger), "queued" (lands with the next write) or "failed"."""
502
+ def mutate(data):
503
+ target = data[section].setdefault(key, {})
504
+ new = {d: v for d, v in entries.items() if d not in target}
505
+ target.update(new)
506
+ return bool(new)
507
+
508
+ if _update(ledger_path, mutate)[0]:
509
+ return "ok"
510
+ return "queued" if _queue(ledger_path, section, key, entries) else "failed"
511
+
512
+
513
+ def record(ledger_path, settings_path, commands, source):
514
+ """Record that Token Optimizer wrote these exact commands into
515
+ ``settings_path``. Call after the settings write landed. Never raises."""
516
+ try:
517
+ wanted = [c for c in commands if isinstance(c, str) and c]
518
+ if not wanted:
519
+ return True
520
+ now = int(time.time())
521
+ entries = {command_digest(c): {"source": str(source), "ts": now} for c in wanted}
522
+ return _record_entries(ledger_path, "files", settings_key(settings_path), entries) == "ok"
523
+ except Exception:
524
+ return False
525
+
526
+
527
+ # --- facade glue ----------------------------------------------------------------
528
+
529
+ def echo_command(command, limit):
530
+ """A hook command as a heal-log field or doctor line: likely secrets
531
+ (tokens, keys, passwords, URL credentials) redacted first by
532
+ credential_patterns, then cut to ``limit``. Redacting before cutting
533
+ keeps a half-cut secret from slipping past the patterns. When redaction
534
+ is unavailable nothing of the command is shown. Display only; never
535
+ consulted for a removal."""
536
+ try:
537
+ from credential_patterns import redact_credentials
538
+ shown = redact_credentials(command, command=True)
539
+ except Exception:
540
+ return "(command not shown)"
541
+ return shown if len(shown) <= limit else shown[:limit - 3] + "..."
542
+
543
+
544
+ def _same_path(a, b):
545
+ try:
546
+ return os.path.normcase(str(Path(a).resolve())) == os.path.normcase(str(Path(b).resolve()))
547
+ except (OSError, ValueError, RuntimeError):
548
+ return False
549
+
550
+
551
+ def _hook_commands(hooks_json):
552
+ try:
553
+ data = json.loads(Path(hooks_json).read_text(encoding="utf-8"))
554
+ except (OSError, ValueError, TypeError):
555
+ return set()
556
+ found = set()
557
+ hooks = data.get("hooks") if isinstance(data, dict) else None
558
+ for groups in (hooks or {}).values() if isinstance(hooks, dict) else ():
559
+ for group in groups if isinstance(groups, list) else ():
560
+ for hook in (group.get("hooks") or []) if isinstance(group, dict) else ():
561
+ command = hook.get("command") if isinstance(hook, dict) else None
562
+ if isinstance(command, str) and command:
563
+ found.add(command)
564
+ return found
565
+
566
+
567
+ def ledger_path_for(facade):
568
+ return Path(facade._settings_heal_dir()) / LEDGER_NAME
569
+
570
+
571
+ def record_contexts(ledger_path, settings_path, contexts, source):
572
+ """Record that Token Optimizer wrote these exact entries (full contexts)
573
+ into ``settings_path``. Call after the settings write landed. Never raises."""
574
+ return _contexts_status(ledger_path, settings_path, contexts, source) == "ok"
575
+
576
+
577
+ def _contexts_status(ledger_path, settings_path, contexts, source):
578
+ try:
579
+ wanted = [c for c in contexts if isinstance(c, tuple) and len(c) == 4]
580
+ if not wanted:
581
+ return "ok"
582
+ now = int(time.time())
583
+ entries = {context_digest(c): {"source": str(source), "ts": now, "cmd": command_digest(c[3])}
584
+ for c in wanted}
585
+ return _record_entries(ledger_path, "contexts", settings_key(settings_path), entries)
586
+ except Exception:
587
+ return "failed"
588
+
589
+
590
+ def _record_failed(log, source, count, status, settings):
591
+ """One heal-log line for a record that did not land in the ledger."""
592
+ try:
593
+ log("hook_provenance_record_failed", source=str(source), entries=count,
594
+ queued=status == "queued", settings=str(settings),
595
+ reason="queued beside the ledger; lands with the next ledger write" if status == "queued"
596
+ else "not recorded; a later malformed copy will be kept, never removed")
597
+ except Exception:
598
+ pass
599
+
600
+
601
+ def added_contexts(before, after, commands):
602
+ """Entries in ``after`` (a settings object) that are not in ``before``
603
+ (``contexts_of`` the read it was derived from), counted as a multiset and
604
+ limited to ``commands``, the exact strings this writer generated. So a
605
+ preserved entry, foreign or ours, is never claimed: only what this write
606
+ added."""
607
+ wanted = set(c for c in commands if isinstance(c, str))
608
+ remaining = dict(before or {})
609
+ added = []
610
+ for context in iter_contexts(after):
611
+ if context[3] not in wanted:
612
+ continue
613
+ if remaining.get(context, 0) > 0:
614
+ remaining[context] -= 1
615
+ continue
616
+ added.append(context)
617
+ return added
618
+
619
+
620
+ def record_written(facade, before, after, commands, source):
621
+ """Installer-side hook: record the entries a successful SETTINGS_PATH
622
+ write added. ``before`` is ``contexts_of`` the read the payload came from,
623
+ ``after`` the payload written."""
624
+ try:
625
+ contexts = added_contexts(before, after, commands)
626
+ if not contexts:
627
+ if has_pending(ledger_path_for(facade)): # an earlier run's queued record lands now
628
+ _update(ledger_path_for(facade), lambda data: False)
629
+ return True
630
+ status = "failed"
631
+ if facade._settings_heal_ensure_dir() is not None:
632
+ status = _contexts_status(ledger_path_for(facade), facade.SETTINGS_PATH, contexts, source)
633
+ if status != "ok":
634
+ _record_failed(facade._settings_heal_log, source, len(contexts), status, facade.SETTINGS_PATH)
635
+ return status == "ok"
636
+ except Exception:
637
+ return False
638
+
639
+
640
+ def record_rewrites(facade, before, after, source):
641
+ """For writers that substitute text INSIDE existing commands
642
+ (_fix_stale_settings_paths): such output can be part foreign, so a
643
+ rewritten entry is recorded only when the entry it replaced was already
644
+ proven ours, in its context, under the same settings file. ``before`` and
645
+ ``after`` must have the same shape (only command strings changed)."""
646
+ try:
647
+ prov = Provenance.from_facade(facade)
648
+ contexts = []
649
+ for old, new in zip(_hook_slots(before), _hook_slots(after)):
650
+ if old[0] != new[0] or old[1] == new[1] or None in (old[1], new[1]):
651
+ continue
652
+ if new[1][:3] == old[1][:3] and prov.proof(old[1][3], old[1][:3]):
653
+ contexts.append(new[1])
654
+ if not contexts:
655
+ return True
656
+ status = "failed"
657
+ if facade._settings_heal_ensure_dir() is not None:
658
+ status = _contexts_status(prov.ledger_path, prov.settings_path, contexts, source)
659
+ if status != "ok":
660
+ _record_failed(facade._settings_heal_log, source, len(contexts), status, prov.settings_path)
661
+ return status == "ok"
662
+ except Exception:
663
+ return False
664
+
665
+
666
+ def _hook_slots(settings):
667
+ """``((event, group index, hook index), context or None)`` per hook slot."""
668
+ hooks = settings.get("hooks") if isinstance(settings, dict) else None
669
+ for event, groups in hooks.items() if isinstance(hooks, dict) else ():
670
+ for gi, group in enumerate(groups if isinstance(groups, list) else ()):
671
+ entries = group.get("hooks") if isinstance(group, dict) else None
672
+ for hi, hook in enumerate(entries if isinstance(entries, list) else ()):
673
+ yield (event, gi, hi), entry_context(event, group, hook)
674
+
675
+
676
+ def record_cloud_write(settings_path, before, after, hook_map):
677
+ """cloud_kit (python -I, no facade): record the entries its settings
678
+ write added, in the ledger measure.py's healer reads for that profile:
679
+ ``<claude dir>/token-optimizer/settings_heal``."""
680
+ try:
681
+ commands = [context[3] for context in iter_contexts({"hooks": hook_map})]
682
+ contexts = added_contexts(contexts_of(before), after, commands)
683
+ if not contexts:
684
+ return True
685
+ heal_dir = Path(settings_path).parent / "token-optimizer" / "settings_heal"
686
+ heal_dir.mkdir(parents=True, exist_ok=True)
687
+ if os.name != "nt":
688
+ os.chmod(str(heal_dir), 0o700)
689
+ status = _contexts_status(heal_dir / LEDGER_NAME, settings_path, contexts, "cloud_kit")
690
+ if status != "ok":
691
+ _record_failed(lambda action, **fields: _append_log(heal_dir, action, fields),
692
+ "cloud_kit", len(contexts), status, settings_path)
693
+ return status == "ok"
694
+ except Exception:
695
+ return False
696
+
697
+
698
+ def _append_log(heal_dir, action, fields):
699
+ """measure.py's heal_log.jsonl line format, for callers without a facade."""
700
+ entry = {"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"), "action": action}
701
+ entry.update(fields)
702
+ with open(str(Path(heal_dir) / "heal_log.jsonl"), "a", encoding="utf-8") as handle:
703
+ handle.write(json.dumps(entry, ensure_ascii=False) + "\n")
704
+
705
+
706
+ class Provenance:
707
+ """One heal pass's view: proven sets, ledger snapshot, verdicts."""
708
+
709
+ def __init__(self, ledger_path, settings_path, proven_contexts, current_commands,
710
+ darwin, script_names=()):
711
+ self.ledger_path = Path(ledger_path)
712
+ self.settings_path = str(settings_path)
713
+ self.key = settings_key(settings_path)
714
+ self.proven_contexts = frozenset(proven_contexts)
715
+ self.proven_templates = frozenset(c[3] for c in self.proven_contexts)
716
+ self.current_commands = frozenset(current_commands)
717
+ self.darwin = bool(darwin)
718
+ self.script_names = tuple(script_names)
719
+ ledger, self.status = load_ledger(self.ledger_path)
720
+ ok = self.status == "ok"
721
+ records = ledger["contexts"].get(self.key, {}) if ok else {}
722
+ self._recorded = frozenset(records)
723
+ self._recorded_commands = frozenset(v.get("cmd") for v in records.values())
724
+ self._seeded = ok and self.key in ledger["contexts_seeded"]
725
+ self._reported = frozenset(ledger["reported"].get(self.key, [])) if ok else frozenset()
726
+
727
+ @classmethod
728
+ def from_facade(cls, facade, settings_path=None):
729
+ """``settings_path`` is the resolved file this pass read; the ledger
730
+ key comes from it, never from a second resolution of SETTINGS_PATH."""
731
+ system = facade.platform.system()
732
+ install_root = None
733
+ try:
734
+ # facade = <root>/skills/token-optimizer/scripts/measure.py
735
+ install_root = Path(facade.__file__).resolve().parents[3]
736
+ except Exception:
737
+ pass
738
+ roots, setup_root, live = [], None, set()
739
+ try:
740
+ hooks_json = facade._find_plugin_hooks_json()
741
+ except Exception:
742
+ hooks_json = None
743
+ if hooks_json:
744
+ setup_root = Path(hooks_json).parent.parent
745
+ live = _hook_commands(hooks_json)
746
+ if install_root is not None:
747
+ roots.append(str(install_root))
748
+ # setup_all_hooks writes its own root spelling; it proves only when
749
+ # it is this running install (main's ownership boundary).
750
+ if setup_root is not None and _same_path(setup_root, install_root):
751
+ roots.append(str(setup_root))
752
+ resolve = facade._resolve_hook_command
753
+ # Only the frozen shipped set proves a template. The live hooks.json
754
+ # is mutable (and may belong to another install): it can only keep
755
+ # the command setup_all_hooks writes now from churning, never add
756
+ # deletion authority. A newly installed command is proven by the ledger.
757
+ proven = instantiate_contexts(SHIPPED_HOOK_CONTEXTS, sorted(set(roots)), resolve)
758
+ current = set()
759
+ if setup_root is not None:
760
+ for template in live:
761
+ try:
762
+ current.add(resolve(template, setup_root))
763
+ except Exception:
764
+ pass
765
+ return cls(ledger_path_for(facade),
766
+ facade.SETTINGS_PATH if settings_path is None else settings_path,
767
+ proven, current, system == "Darwin", getattr(facade, "_TO_SCRIPT_NAMES", ()))
768
+
769
+ def proof(self, command, context=None):
770
+ """"template", "ledger" or None for ``command`` in ``context``
771
+ (``(event, matcher, type)``). Exact bytes of the whole tuple only.
772
+ Without a context: proven in SOME context (diagnostics and
773
+ ``_is_malformed_to_hook``; the healer always passes the context)."""
774
+ if context is None:
775
+ if command in self.proven_templates:
776
+ return "template"
777
+ return "ledger" if command_digest(command) in self._recorded_commands else None
778
+ full = tuple(context) + (command,)
779
+ if full in self.proven_contexts:
780
+ return "template"
781
+ if context_digest(full) in self._recorded:
782
+ return "ledger"
783
+ return None
784
+
785
+ def verdict(self, command, context=None):
786
+ if not isinstance(command, str) or not command:
787
+ return KEEP
788
+ if not looks_malformed(command, self.darwin):
789
+ return KEEP
790
+ if command in self.current_commands:
791
+ return KEEP # what setup_all_hooks writes now: never churn it
792
+ if self.proof(command, context):
793
+ return REMOVE
794
+ return UNPROVEN
795
+
796
+ def verdict_entry(self, event, group, hook):
797
+ """The healer's verdict for one settings.json entry, in its context.
798
+ An entry with no writable context is never proven."""
799
+ command = hook.get("command", "") if isinstance(hook, dict) else ""
800
+ context = entry_context(event, group, hook)
801
+ if context is None:
802
+ if not isinstance(command, str) or not command or command in self.current_commands \
803
+ or not looks_malformed(command, self.darwin):
804
+ return KEEP
805
+ return UNPROVEN
806
+ return self.verdict(command, context[:3])
807
+
808
+ def reportable(self, command):
809
+ # Diagnostics only: the entries the old heuristic would have weighed.
810
+ # Never consulted for a removal.
811
+ return any(name in command for name in self.script_names)
812
+
813
+ def finish(self, present, unproven, log=None):
814
+ """After a heal pass: seed the ledger on first run (exact template
815
+ matches only) and report each unproven entry once.
816
+
817
+ ``present`` is every entry context left in settings; ``unproven`` is a
818
+ list of ``(event, command)``. ``log(action, **fields)`` is the heal log.
819
+ """
820
+ try:
821
+ if self.status == "unreadable":
822
+ return
823
+ seeds = [] if self._seeded else sorted(
824
+ {c for c in present if c in self.proven_contexts}, key=repr)
825
+ reports, seen = [], set()
826
+ for event, command in unproven:
827
+ digest = command_digest(command)
828
+ if digest in self._reported or digest in seen or not self.reportable(command):
829
+ continue
830
+ seen.add(digest)
831
+ reports.append((event, command, digest))
832
+ if self._seeded and not reports and self.status == "ok" \
833
+ and not has_pending(self.ledger_path):
834
+ return
835
+ key, now, logged = self.key, int(time.time()), []
836
+
837
+ def mutate(data):
838
+ changed = False
839
+ if key not in data["contexts_seeded"]:
840
+ entries = data["contexts"].setdefault(key, {})
841
+ for context in seeds:
842
+ entries.setdefault(context_digest(context),
843
+ {"source": "migration-seed", "ts": now,
844
+ "cmd": command_digest(context[3])})
845
+ data["contexts_seeded"][key] = now
846
+ changed = True
847
+ done = data["reported"].setdefault(key, [])
848
+ for event, command, digest in reports:
849
+ if digest not in done:
850
+ done.append(digest)
851
+ logged.append((event, command, digest))
852
+ changed = True
853
+ return changed
854
+
855
+ written, reset = _update(self.ledger_path, mutate)
856
+ if log is None:
857
+ return
858
+ if reset:
859
+ log("hook_provenance_reset", reason="corrupt ledger moved aside; template-only proof")
860
+ if written:
861
+ for event, command, digest in logged:
862
+ log("hook_unproven", event=event, sha256=digest, command=echo_command(command, 200),
863
+ settings=self.settings_path,
864
+ reason="not recorded by Token Optimizer and not a shipped template; left in place")
865
+ except Exception:
866
+ return
867
+
868
+
869
+ def write_codex_hooks(path, data, proof, writer, extra=(), source="codex_install"):
870
+ """Codex installer: write hooks.json via ``writer`` (raises on failure, as
871
+ before), then record in the Codex ledger every entry ``proof``
872
+ (codex_hook_provenance.CodexProof) owns plus ``extra``, the entries
873
+ (contexts) this run just rewrote."""
874
+ writer(path, data)
875
+ try:
876
+ proof.record_present(data, extra, source)
877
+ except Exception:
878
+ pass