@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
@@ -104,8 +104,8 @@ from datetime import datetime, timedelta, timezone
104
104
  from pathlib import Path, PureWindowsPath
105
105
  try:
106
106
  import tomllib
107
- except ImportError: # pragma: no cover - Python < 3.11 fallback
108
- tomllib = None
107
+ except ImportError: # Python 3.9/3.10, without runtime pip dependencies
108
+ from _measure._vendor import tomli as tomllib
109
109
 
110
110
 
111
111
  def _redirect_bytecode_out_of_repo():
@@ -0,0 +1,420 @@
1
+ """Token Optimizer's own SessionEnd, Stop and smart-compact entries in
2
+ settings.json: which ones the fossil reconcile, setup_hook's upgrade and
3
+ uninstall, and setup_smart_compact --uninstall may rewrite or remove.
4
+
5
+ These used to act on any command that merely mentioned measure.py with one
6
+ of our subcommands, so a user's own /home/me/mytool/measure.py collect was
7
+ rewritten or deleted. An entry is now theirs to touch only when it is
8
+ proven ours (a shipped context or a ledger record, exactly as the healer
9
+ proves), or it is byte-identical to one of the exact commands setup_hook /
10
+ setup_smart_compact ever generated, rebuilt forward with a measure.py path
11
+ that is a Token Optimizer install's.
12
+
13
+ Command tokens only propose candidates here; byte equality of a forward
14
+ rebuild decides. Lives beside measure.py and must stay importable on Python
15
+ 3.9 with the standard library only.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import shlex
22
+ import subprocess
23
+ from pathlib import Path
24
+
25
+ import hook_heal
26
+ import hook_provenance as hp
27
+ from shipped_starter_hooks import STARTER_HOOK_CONTEXTS
28
+
29
+
30
+ _PLACEHOLDER_SCRIPT = "${CLAUDE_PLUGIN_ROOT}/skills/token-optimizer/scripts/measure.py"
31
+ _SCRIPT_TAIL = ("skills", "token-optimizer", "scripts", "measure.py")
32
+
33
+
34
+ def _sq(path):
35
+ return "'%s'" % path
36
+
37
+
38
+ def _sh(text):
39
+ return shlex.quote(str(text).replace("\\", "/"))
40
+
41
+
42
+ def _l2c(*args):
43
+ return subprocess.list2cmdline(list(args))
44
+
45
+
46
+ # setup_hook's HOOK_COMMAND, every shape it shipped (git history of measure.py).
47
+ SESSION_END_SHAPES = (
48
+ lambda py, mp: "python3 %s collect --quiet" % mp,
49
+ lambda py, mp: "python3 %s collect --quiet" % _sq(mp),
50
+ lambda py, mp: "python3 {0} collect --quiet && python3 {0} dashboard --quiet".format(_sq(mp)),
51
+ lambda py, mp: "%s && %s >NUL 2>&1" % (_l2c(py, mp, "collect", "--quiet"), _l2c(py, mp, "dashboard", "--quiet")),
52
+ lambda py, mp: "{0} {1} collect --quiet && {0} {1} dashboard --quiet >/dev/null 2>&1".format(_sh(py), _sh(mp)),
53
+ lambda py, mp: "python3 %s session-end-flush --trigger end" % _sq(mp),
54
+ lambda py, mp: "%s %s session-end-flush --trigger end >/dev/null 2>&1" % (_sh(py), _sh(mp)),
55
+ )
56
+
57
+ # setup_smart_compact's commands, every shape it shipped.
58
+ _COMPACT_SUBCOMMANDS = ("compact-capture --trigger auto", "compact-restore",
59
+ "compact-restore --new-session-only",
60
+ "compact-capture --trigger stop", "compact-capture --trigger end")
61
+ COMPACT_SHAPES = tuple(
62
+ shape for sub in _COMPACT_SUBCOMMANDS for shape in (
63
+ lambda py, mp, sub=sub: "python3 %s %s" % (_sq(mp), sub),
64
+ lambda py, mp, sub=sub: "[ -r {0} ] || exit 0; python3 {0} {1}".format(_sq(mp), sub),
65
+ lambda py, mp, sub=sub: "[ -r {0} ] || exit 0; {1} {0} {2}".format(_sh(mp), _sh(py), sub),
66
+ ))
67
+
68
+
69
+ # setup_quality_bar's UserPromptSubmit command, every shape it shipped.
70
+ QUALITY_SHAPES = (
71
+ lambda py, mp: "python3 %s quality-cache --quiet" % _sq(mp),
72
+ lambda py, mp: "%s %s quality-cache --quiet" % (_sh(py), _sh(mp)),
73
+ )
74
+
75
+
76
+ def _path_parts(path):
77
+ text = str(path).replace("\\", "/")
78
+ if os.name == "nt":
79
+ text = text.lower()
80
+ return tuple(part for part in text.split("/") if part)
81
+
82
+
83
+ def _install_roots(facade):
84
+ """Fixed roots R whose R/skills/token-optimizer/scripts/measure.py is ours."""
85
+ roots = [Path(facade.CLAUDE_DIR), # script install, skill link: ~/.claude/skills/token-optimizer
86
+ Path(facade.CLAUDE_DIR) / "token-optimizer"] # install.sh's clone that link points into
87
+ for get in (lambda: Path(facade.MEASURE_PY_PATH).parents[3],
88
+ lambda: Path(facade.__file__).resolve().parents[3],
89
+ lambda: Path(facade._find_plugin_hooks_json()).parent.parent):
90
+ try:
91
+ roots.append(get())
92
+ except Exception:
93
+ pass
94
+ return roots
95
+
96
+
97
+ def is_install_script(facade, path):
98
+ """True when ``path`` is a Token Optimizer install's measure.py: this copy,
99
+ the script install (skill link or its clone), the plugin root hooks.json names, any plugin-cache
100
+ version (one since removed included), or the placeholder spelling."""
101
+ if path == _PLACEHOLDER_SCRIPT:
102
+ return True
103
+ text = str(path).replace("\\", "/")
104
+ if not _absolute(text):
105
+ return False
106
+ parts = _path_parts(text)
107
+ if parts[-4:] != _path_parts("/".join(_SCRIPT_TAIL)) or "." in parts or ".." in parts:
108
+ return False
109
+ head = parts[:-4]
110
+ if any(head == _path_parts(root) for root in _install_roots(facade)):
111
+ return True
112
+ # Any marketplace: Claude Code names the cache dir after the plugin, our
113
+ # marketplace has been renamed and mirrored, and this path only proposes a
114
+ # candidate; the whole command must still equal one we generated.
115
+ cache = _path_parts(Path(facade.CLAUDE_DIR) / "plugins" / "cache")
116
+ return len(head) == len(cache) + 3 and head[:len(cache)] == cache and head[-2] == "token-optimizer"
117
+
118
+
119
+ def _absolute(text):
120
+ text = str(text).replace("\\", "/")
121
+ return text.startswith("/") or (len(text) > 2 and text[1] == ":" and text[2] == "/")
122
+
123
+
124
+ def matches_shape(facade, command, shapes):
125
+ """``command`` is exactly one of ``shapes`` rebuilt from its own measure.py
126
+ and interpreter tokens, with that measure.py an install's. The tokens only
127
+ propose candidates; byte equality of the rebuilt command decides."""
128
+ for tokens in _token_views(command):
129
+ for i, token in enumerate(tokens):
130
+ if not token.endswith("measure.py") or not is_install_script(facade, token):
131
+ continue
132
+ for py in {"python3", tokens[i - 1] if i else "python3"}:
133
+ if not _our_interpreter(py):
134
+ continue # a wrapper (sudo, env, nice) is not a command we wrote
135
+ for shape in shapes:
136
+ try:
137
+ if shape(py, token) == command:
138
+ return True
139
+ except Exception:
140
+ continue
141
+ return False
142
+
143
+
144
+ def _our_interpreter(token):
145
+ """An interpreter token our generators wrote: bare python3 (POSIX shapes)
146
+ or sys.executable, an absolute path to a CPython or PyPy binary (Windows
147
+ shapes): python / python3 / python3.N, free-threaded or debug builds
148
+ (python3.13t, python3.13d, python3.12-dbg, python_d.exe), pythonw, and
149
+ pypy / pypy3 / pypy3.N, each with or without .exe. Never a ``py``
150
+ launcher or a wrapper: no generator emitted one."""
151
+ if token == "python3":
152
+ return True
153
+ if not _absolute(token):
154
+ return False
155
+ parts = _path_parts(token)
156
+ name = parts[-1].lower() if parts else ""
157
+ for suffix in (".exe", "-dbg", "_d", "w"):
158
+ if name[-len(suffix):] == suffix:
159
+ name = name[:-len(suffix)]
160
+ for family in ("python", "pypy"):
161
+ if name[:len(family)] != family:
162
+ continue
163
+ version = name[len(family):]
164
+ if family == "python" and version[:1] == "w":
165
+ version = version[1:] # pythonw3.13t.exe
166
+ for flag in ("d", "t"): # ABI flags, in CPython's order (3.13td)
167
+ if version[-1:] == flag and version[:-1]:
168
+ version = version[:-1]
169
+ return all(c.isdigit() or c == "." for c in version) and ".." not in version \
170
+ and version[:1] != "." and version[-1:] != "."
171
+ return False
172
+
173
+
174
+ def _token_views(command):
175
+ """POSIX shell tokens, plus cmd-style tokens (list2cmdline output, where a
176
+ backslash is a plain path separator) with one pair of quotes removed."""
177
+ views = []
178
+ for posix in (True, False):
179
+ try:
180
+ tokens = shlex.split(command, posix=posix)
181
+ except ValueError:
182
+ continue
183
+ if not posix:
184
+ tokens = [t[1:-1] if len(t) > 1 and t[0] == t[-1] == '"' else t for t in tokens]
185
+ views.append(tokens)
186
+ return views
187
+
188
+
189
+ def owner(facade, shapes):
190
+ """``owns(event, group, hook)`` for one pass: proven ours in its context,
191
+ or an exact generated shape. Proof is loaded on first use only."""
192
+ cache = []
193
+
194
+ def owns(event, group, hook):
195
+ context = hp.entry_context(event, group, hook)
196
+ if context is None:
197
+ return False
198
+ if not cache:
199
+ dest = hook_heal._resolved(facade.SETTINGS_PATH)
200
+ cache.append(hp.Provenance.from_facade(facade, settings_path=dest or facade.SETTINGS_PATH))
201
+ return bool(cache[0].proof(context[3], context[:3])) or matches_shape(facade, context[3], shapes)
202
+ return owns
203
+
204
+
205
+ def _entries(groups):
206
+ """``(group, hook)`` for every hook dict under a list of groups."""
207
+ for group in groups if isinstance(groups, list) else ():
208
+ entries = group.get("hooks") if isinstance(group, dict) else None
209
+ for hook in entries if isinstance(entries, list) else ():
210
+ if isinstance(hook, dict):
211
+ yield group, hook
212
+
213
+
214
+ def _map_groups(hooks, event, fn):
215
+ """Apply ``fn(group, hook)`` to each hook dict in ``hooks[event]``: it
216
+ returns the hook (kept), a replacement, or None (dropped). A group emptied
217
+ by drops goes; an untouched group stays the same object. Returns
218
+ ``(dropped, replaced)``."""
219
+ groups = hooks.get(event)
220
+ if not isinstance(groups, list):
221
+ return 0, 0
222
+ dropped = replaced = 0
223
+ new_groups = []
224
+ for group in groups:
225
+ entries = group.get("hooks") if isinstance(group, dict) else None
226
+ if not isinstance(entries, list):
227
+ new_groups.append(group)
228
+ continue
229
+ out = []
230
+ for hook in entries:
231
+ new = fn(group, hook) if isinstance(hook, dict) else hook
232
+ if new is None:
233
+ dropped += 1
234
+ else:
235
+ replaced += new is not hook
236
+ out.append(new)
237
+ if len(out) == len(entries) and all(x is y for x, y in zip(out, entries)):
238
+ new_groups.append(group)
239
+ elif out:
240
+ new_groups.append(dict(group, hooks=out))
241
+ if dropped or replaced:
242
+ if new_groups:
243
+ hooks[event] = new_groups
244
+ else:
245
+ hooks.pop(event, None)
246
+ return dropped, replaced
247
+
248
+
249
+ def _filter_groups(hooks, event, drop):
250
+ """Drop the hooks ``drop(group, hook)`` selects; returns how many."""
251
+ return _map_groups(hooks, event, lambda g, h: None if drop(g, h) else h)[0]
252
+
253
+
254
+ def _plugin_provides_stop_flush(facade):
255
+ try:
256
+ if not facade._is_plugin_installed():
257
+ return False
258
+ path = facade._find_plugin_hooks_json()
259
+ plugin = json.loads(Path(path).read_text(encoding="utf-8")) if path else {}
260
+ return any(facade._sessionend_cmd_is_flush(hook.get("command", ""))
261
+ for _, hook in _entries((plugin.get("hooks") or {}).get("Stop")))
262
+ except (OSError, ValueError, TypeError, AttributeError):
263
+ return False
264
+
265
+
266
+ def apply_fossil_reconcile(facade, settings, result):
267
+ """lifecycle._apply_sessionend_fossil_reconcile, on our entries only.
268
+
269
+ SessionEnd: each collect/dashboard fossil of ours is rewritten in place to
270
+ HOOK_COMMAND, or removed when a current flush of ours is already there.
271
+ Stop: our collect fossils go, and so does every flush of ours after the
272
+ first (all of them when the plugin's hooks.json provides the Stop flush).
273
+ Anything not ours is left byte for byte. Returns True if anything changed;
274
+ ``result`` counts this call's changes."""
275
+ hooks = settings.get("hooks") if isinstance(settings, dict) else None
276
+ if not isinstance(hooks, dict):
277
+ return False
278
+ owns = owner(facade, SESSION_END_SHAPES)
279
+ flush, fossil = facade._sessionend_cmd_is_flush, facade._sessionend_cmd_is_collect_fossil
280
+
281
+ def ours(event, group, hook, shape):
282
+ return shape(hook.get("command", "")) and owns(event, group, hook)
283
+
284
+ has_current = [any(ours("SessionEnd", g, h, flush) for g, h in _entries(hooks.get("SessionEnd")))]
285
+
286
+ def heal_session_end(group, hook):
287
+ if not ours("SessionEnd", group, hook, fossil):
288
+ return hook
289
+ if has_current[0]:
290
+ result["removed"] += 1
291
+ return None
292
+ result["rewritten"] += 1
293
+ has_current[0] = True
294
+ return facade._rewrite_collect_fossil_hook(hook)
295
+
296
+ changed = any(_map_groups(hooks, "SessionEnd", heal_session_end))
297
+ provides, seen = _plugin_provides_stop_flush(facade), [False]
298
+
299
+ def drop_stop(group, hook):
300
+ if ours("Stop", group, hook, fossil):
301
+ return True
302
+ if ours("Stop", group, hook, flush):
303
+ if provides or seen[0]:
304
+ return True
305
+ seen[0] = True
306
+ return False
307
+
308
+ stop_removed = _filter_groups(hooks, "Stop", drop_stop)
309
+ result["stop_removed"] += stop_removed
310
+ return changed or stop_removed > 0
311
+
312
+
313
+ def remove_session_end(facade, settings):
314
+ """setup_hook --uninstall / cleanup: drop our SessionEnd hooks only."""
315
+ hooks = settings.get("hooks") if isinstance(settings, dict) else None
316
+ if not isinstance(hooks, dict):
317
+ return 0
318
+ owns = owner(facade, SESSION_END_SHAPES)
319
+ return _filter_groups(hooks, "SessionEnd", lambda group, hook: (
320
+ facade._is_token_optimizer_session_end_hook(hook) and owns("SessionEnd", group, hook)))
321
+
322
+
323
+ def session_end_view(facade, settings):
324
+ """``settings`` reduced to our own SessionEnd hooks, for setup_hook's
325
+ installed / up-to-date check: a user's own measure.py session-end-flush
326
+ must never read as ours and make setup_hook skip installing it."""
327
+ hooks = settings.get("hooks") if isinstance(settings, dict) else None
328
+ groups = hooks.get("SessionEnd") if isinstance(hooks, dict) else None
329
+ owns = owner(facade, SESSION_END_SHAPES)
330
+ mine = [hook for group, hook in _entries(groups) if owns("SessionEnd", group, hook)]
331
+ return {"hooks": {"SessionEnd": [{"hooks": mine}]}}
332
+
333
+
334
+ def replace_session_end_fossil(facade, hooks, new_hook):
335
+ """setup_hook's upgrade: in each SessionEnd group, our first fossil
336
+ becomes ``new_hook``. True when one was replaced; with none of ours,
337
+ the caller installs alongside instead."""
338
+ owns, replaced = owner(facade, SESSION_END_SHAPES), False
339
+ groups = hooks.get("SessionEnd") if isinstance(hooks, dict) else None
340
+ for group in groups if isinstance(groups, list) else ():
341
+ entries = group.get("hooks") if isinstance(group, dict) else None
342
+ for i, hook in enumerate(entries if isinstance(entries, list) else ()):
343
+ if isinstance(hook, dict) and facade._sessionend_cmd_is_collect_fossil(hook.get("command", "")) \
344
+ and owns("SessionEnd", group, hook):
345
+ entries[i] = new_hook
346
+ replaced = True
347
+ break
348
+ return replaced
349
+
350
+
351
+ def remove_smart_compact(facade, settings):
352
+ """setup_smart_compact --uninstall: drop our compact-capture /
353
+ compact-restore entries from its four events. Returns hooks removed."""
354
+ hooks = settings.get("hooks") if isinstance(settings, dict) else None
355
+ if not isinstance(hooks, dict):
356
+ return 0
357
+ owns = owner(facade, COMPACT_SHAPES)
358
+ removed = 0
359
+ for event in ("PreCompact", "SessionStart", "Stop", "SessionEnd"):
360
+ removed += _filter_groups(hooks, event, lambda group, hook, event=event: (
361
+ isinstance(hook.get("command"), str)
362
+ and ("compact-capture" in hook["command"] or "compact-restore" in hook["command"])
363
+ and owns(event, group, hook)))
364
+ return removed
365
+
366
+
367
+ def _cache_roots_named(facade, command):
368
+ """Plugin-cache version roots (.../plugins/cache/<m>/token-optimizer/<v>)
369
+ a command names, removed versions included. Candidates only."""
370
+ roots = []
371
+ for cache in {str(Path(facade.CLAUDE_DIR) / "plugins" / "cache"),
372
+ str(Path(facade.CLAUDE_DIR) / "plugins" / "cache").replace("\\", "/")}:
373
+ start = 0
374
+ while True:
375
+ at = command.find(cache, start)
376
+ if at < 0:
377
+ break
378
+ start = at + len(cache)
379
+ rest = command[start:].replace("\\", "/").split("/")
380
+ if len(rest) > 3 and rest[0] == "" and rest[2] == "token-optimizer":
381
+ version = rest[3]
382
+ for stop in ("'", '"', " ", ";", ")"):
383
+ version = version.split(stop)[0]
384
+ if version and version not in (".", ".."):
385
+ roots.append(str(Path(cache) / rest[1] / "token-optimizer" / version))
386
+ return roots
387
+
388
+
389
+ def cleanup_owner(facade):
390
+ """``owns(event, group, hook)`` for measure.py cleanup: proven ours only.
391
+
392
+ Ours when the entry is proven in its context (ledger, or a shipped
393
+ hooks.json entry for this install), or is a shipped hooks.json entry
394
+ instantiated for an install root the command itself names (a removed
395
+ plugin version, the script-install clone, the ${CLAUDE_PLUGIN_ROOT}
396
+ spelling), or is an examples/hooks-starter.json entry pasted as shipped,
397
+ or is byte-identical to a SessionEnd, smart-compact or quality-bar command
398
+ we generated for an install's measure.py. Naming our subcommands or
399
+ scripts proves nothing."""
400
+ base = owner(facade, SESSION_END_SHAPES + COMPACT_SHAPES + QUALITY_SHAPES)
401
+ fixed = [str(r) for r in _install_roots(facade)] + ["${CLAUDE_PLUGIN_ROOT}"]
402
+ cache = {}
403
+
404
+ def instantiated(roots):
405
+ key = tuple(sorted(set(roots)))
406
+ if key not in cache:
407
+ cache[key] = hp.instantiate_contexts(hp.SHIPPED_HOOK_CONTEXTS, list(key),
408
+ getattr(facade, "_resolve_hook_command", None))
409
+ return cache[key]
410
+
411
+ def owns(event, group, hook):
412
+ if base(event, group, hook):
413
+ return True
414
+ context = hp.entry_context(event, group, hook)
415
+ if context is None:
416
+ return False
417
+ if context in STARTER_HOOK_CONTEXTS:
418
+ return True
419
+ return context in instantiated(fixed + _cache_roots_named(facade, context[3]))
420
+ return owns
@@ -34,6 +34,7 @@ from typing import Any, Optional
34
34
  from hook_io import read_stdin_hook_input
35
35
  from plugin_env import is_v5_flag_enabled, resolve_snapshot_dir
36
36
  from runtime_env import project_config_value, run_origin, runtime_home
37
+ from reset_epoch import _reset_replacement_state, refresh_message, snapshot_reset_epoch
37
38
 
38
39
  try:
39
40
  from session_store import SessionStore, cleanup_old_stores, mark_context_reset
@@ -599,16 +600,6 @@ def _decisions_log_path(session_id: str = "unknown") -> Path:
599
600
  return decisions_dir / f"{safe_id}.jsonl"
600
601
 
601
602
 
602
-
603
- def _reset_replacement_state(entry: dict[str, Any]) -> None:
604
- entry["last_replacement_fingerprint"] = ""
605
- entry["last_replacement_type"] = ""
606
- entry["repeat_replacement_count"] = 0
607
- entry["consecutive_denials"] = 0
608
- entry["last_structure_reason"] = ""
609
- entry["last_structure_confidence"] = 0.0
610
-
611
-
612
603
  def _check_escape_hatch(
613
604
  entry: dict[str, Any],
614
605
  store: Any,
@@ -623,6 +614,7 @@ def _check_escape_hatch(
623
614
  summary: Any,
624
615
  save_hook_context_enabled: bool,
625
616
  quiet: bool,
617
+ reset_epoch: Any = None,
626
618
  ) -> bool:
627
619
  """Allow the read if consecutive denials reach the threshold. Returns True if escaped."""
628
620
  consecutive_denials = int(entry.get("consecutive_denials", 0) or 0) + 1
@@ -632,7 +624,7 @@ def _check_escape_hatch(
632
624
 
633
625
  entry["consecutive_denials"] = 0
634
626
  _reset_replacement_state(entry)
635
- store.upsert_file_entry(file_path, entry)
627
+ store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
636
628
  _log_decision(
637
629
  "allow",
638
630
  file_path,
@@ -1506,6 +1498,9 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1506
1498
  except Exception:
1507
1499
  pass
1508
1500
 
1501
+ # U2: snapshot the reset epoch AFTER the compaction scan above; a reset
1502
+ # landing before the record write drops the guarded upsert (reset_epoch.py).
1503
+ reset_epoch = snapshot_reset_epoch(store)
1509
1504
  try:
1510
1505
  entry = store.get_file_entry(file_path)
1511
1506
  except Exception:
@@ -1557,7 +1552,7 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1557
1552
  except Exception:
1558
1553
  pass
1559
1554
  _reset_replacement_state(entry)
1560
- store.upsert_file_entry(file_path, entry)
1555
+ store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
1561
1556
  # U5: first-read skeleton. Active cohorts serve a skeleton (returns True,
1562
1557
  # we stop here); others fall through to serve the full file + shadow-log.
1563
1558
  # Reuses content delta mode already read this turn (even when too large to
@@ -1748,7 +1743,7 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1748
1743
  else:
1749
1744
  entry["content_hash"] = None
1750
1745
  store.delete_cached_content(file_path)
1751
- store.upsert_file_entry(file_path, entry)
1746
+ store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
1752
1747
 
1753
1748
  net_saved = max(0, old_tokens - delta_tokens)
1754
1749
 
@@ -1858,7 +1853,7 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1858
1853
  except Exception:
1859
1854
  pass
1860
1855
  _reset_replacement_state(entry)
1861
- store.upsert_file_entry(file_path, entry)
1856
+ store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
1862
1857
  _log_decision(
1863
1858
  "allow",
1864
1859
  file_path,
@@ -1900,7 +1895,7 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1900
1895
  decision = "warn" if mode == "warn" else "allow"
1901
1896
  entry["last_structure_reason"] = reason_code
1902
1897
  entry["last_structure_confidence"] = summary.confidence if summary else 0.0
1903
- store.upsert_file_entry(file_path, entry)
1898
+ store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
1904
1899
  _log_decision(
1905
1900
  decision,
1906
1901
  file_path,
@@ -1929,7 +1924,7 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1929
1924
  if eligible_structure and summary is not None:
1930
1925
  if _check_escape_hatch(
1931
1926
  entry, store, file_path, session_id, mode, offset, limit,
1932
- tokens_est, language, True, summary, save_hook_context_enabled, quiet,
1927
+ tokens_est, language, True, summary, save_hook_context_enabled, quiet, reset_epoch,
1933
1928
  ):
1934
1929
  return
1935
1930
 
@@ -1940,7 +1935,7 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1940
1935
  entry["repeat_replacement_count"] = repeat_count
1941
1936
  entry["last_structure_reason"] = reason_code
1942
1937
  entry["last_structure_confidence"] = summary.confidence
1943
- store.upsert_file_entry(file_path, entry)
1938
+ store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
1944
1939
 
1945
1940
  if repeat_count == 1:
1946
1941
  replacement_tokens_est = summary.replacement_tokens_est
@@ -2022,11 +2017,11 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
2022
2017
  if mode == "block":
2023
2018
  if _check_escape_hatch(
2024
2019
  entry, store, file_path, session_id, mode, offset, limit,
2025
- tokens_est, language, False, summary, save_hook_context_enabled, quiet,
2020
+ tokens_est, language, False, summary, save_hook_context_enabled, quiet, reset_epoch,
2026
2021
  ):
2027
2022
  return
2028
2023
 
2029
- store.upsert_file_entry(file_path, entry)
2024
+ store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
2030
2025
  block_net_saved = max(0, tokens_est - REASON_ONLY_TOKENS_EST)
2031
2026
  _log_decision(
2032
2027
  "block",
@@ -2211,6 +2206,10 @@ def handle_invalidate(hook_input: dict[str, Any], quiet: bool) -> None:
2211
2206
  if store is None:
2212
2207
  return
2213
2208
 
2209
+ # Same U2 contract as handle_read: a reset landing before the rewrite below
2210
+ # must drop the write, not resurrect a pre-clear row.
2211
+ _invalidate_epoch = snapshot_reset_epoch(store)
2212
+
2214
2213
  # Checkpoints can predate this edit. Preserve its path independently of
2215
2214
  # cache entries, including edits to files that have never been read.
2216
2215
  try:
@@ -2313,9 +2312,9 @@ def handle_invalidate(hook_input: dict[str, Any], quiet: bool) -> None:
2313
2312
  existing["content_hash"] = None
2314
2313
  store.delete_cached_content(file_path)
2315
2314
 
2316
- store.upsert_file_entry(file_path, existing)
2315
+ written = store.upsert_file_entry(file_path, existing, expected_reset_epoch=_invalidate_epoch)
2317
2316
  if not quiet:
2318
- print(f"[Read Cache] Refreshed after edit: {file_path}", file=sys.stderr)
2317
+ print(refresh_message(file_path, written), file=sys.stderr)
2319
2318
  except Exception:
2320
2319
  # Fallback: purge on any unexpected error so a stale entry is never
2321
2320
  # served.