@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,2489 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer - PreToolUse Read Cache (standalone entry point).
3
+
4
+ Conservatively intercepts Read tool calls to detect redundant file reads.
5
+ Default behavior is production-safe structure substitution for a narrow slice:
6
+ unchanged whole-file supported code rereads that can be replaced with a bounded
7
+ code map.
8
+
9
+ Default ON. Opt out via TOKEN_OPTIMIZER_READ_CACHE=0 or config.json
10
+ {"read_cache_enabled": false}.
11
+
12
+ Modes:
13
+ soft_block (default) - deny eligible redundant rereads and inject structure map
14
+ warn - log redundant rereads but allow the read
15
+ shadow - measure-only, allow the read without warning noise
16
+ block - deny all redundant rereads; only inject structure map for
17
+ eligible supported code files, reason-only otherwise
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import os
24
+ import re
25
+ import sqlite3
26
+ import stat as stat_module
27
+ import sys
28
+ import time
29
+ from datetime import datetime
30
+ from fnmatch import fnmatch
31
+ from pathlib import Path
32
+ from typing import Any, Optional
33
+
34
+ from hook_io import read_stdin_hook_input
35
+ from plugin_env import is_v5_flag_enabled, resolve_snapshot_dir
36
+ from runtime_env import project_config_value, run_origin, runtime_home
37
+
38
+ try:
39
+ from session_store import SessionStore, cleanup_old_stores
40
+ except ImportError:
41
+ SessionStore = None # type: ignore[assignment,misc]
42
+ cleanup_old_stores = None # type: ignore[assignment]
43
+
44
+ try:
45
+ from credential_patterns import redact_credentials as _redact_creds
46
+ from credential_patterns import pop_redaction_warning as _pop_redaction_warning
47
+ except ImportError:
48
+ _redact_creds = None
49
+ _pop_redaction_warning = None
50
+
51
+
52
+ def _redact_for_storage(text: str) -> Optional[str]:
53
+ """Credential-redacted copy of ``text`` for persistence, or None.
54
+
55
+ None means "do not persist": the shared redactor is missing, or it refused
56
+ because a configured custom pattern file failed to load. Writing the raw
57
+ text in either case would store content the configured redaction rules
58
+ were meant to cover — the cache simply goes without the content.
59
+ """
60
+ if _redact_creds is None:
61
+ return None
62
+ try:
63
+ return _redact_creds(text)
64
+ except Exception:
65
+ return None
66
+
67
+ def _marker_key(kind: str, file_path: str) -> Optional[str]:
68
+ """``<kind>:<redacted path>`` meta key for a first-read ledger marker.
69
+
70
+ The key is persisted in the session store, and a path can embed a token (a
71
+ URL-ish checkout dir, a credential in a cache folder name). Writer and
72
+ lookup both build the key here, so they always agree; a path with no
73
+ credential shape keeps its plain key. None means "do not persist": the
74
+ redactor is missing or refused, and the marker is simply not armed.
75
+ """
76
+ safe = _redact_for_storage(file_path)
77
+ return None if safe is None else f"{kind}:{safe}"
78
+
79
+
80
+ from structure_map import (
81
+ StructureMapResult,
82
+ detect_structure_language,
83
+ is_structure_supported_file,
84
+ summarize_code_file,
85
+ summarize_code_source,
86
+ )
87
+
88
+ try:
89
+ from token_estimate import estimate_tokens_from_bytes, estimate_tokens
90
+ except ImportError: # pragma: no cover - fallback keeps the hook resilient
91
+ def estimate_tokens_from_bytes(n_bytes):
92
+ return max(1, int(n_bytes) // 4) if n_bytes and n_bytes > 0 else 0
93
+
94
+ def estimate_tokens(text):
95
+ return max(1, len(text) // 4) if text else 0
96
+
97
+
98
+ def _read_text_with_stat(file_path: str) -> tuple[str, os.stat_result]:
99
+ """Read one file snapshot and return metadata for that same open file."""
100
+ with open(file_path, "r", encoding="utf-8", errors="replace") as handle:
101
+ content = handle.read()
102
+ stat = os.fstat(handle.fileno())
103
+ return content, stat
104
+
105
+
106
+ def _is_v5_delta_enabled():
107
+ """Check if delta mode is enabled. Default ON in v5.1."""
108
+ return is_v5_flag_enabled("v5_delta_mode", "TOKEN_OPTIMIZER_READ_CACHE_DELTA", default=True)
109
+
110
+
111
+ def _is_v5_structure_map_beta():
112
+ """Check if structure map beta telemetry is enabled."""
113
+ return is_v5_flag_enabled(
114
+ "v5_structure_map_beta",
115
+ "TOKEN_OPTIMIZER_STRUCTURE_MAP",
116
+ default=False,
117
+ env_truthy_value="beta",
118
+ )
119
+
120
+
121
+ def _is_first_read_shadow_enabled():
122
+ """Master switch for the first-read skeleton feature (default ON).
123
+
124
+ Off (TOKEN_OPTIMIZER_FIRST_READ_SHADOW=0 / config first_read_shadow_enabled)
125
+ disables BOTH the shadow measurement and active skeleton serving — the read
126
+ falls through untouched.
127
+ """
128
+ return is_v5_flag_enabled(
129
+ "v5_first_read_shadow",
130
+ "TOKEN_OPTIMIZER_FIRST_READ_SHADOW",
131
+ default=True,
132
+ )
133
+
134
+
135
+ def _is_first_read_active_enabled():
136
+ """Whether validated cohorts serve a SKELETON instead of the full file.
137
+
138
+ Default ON. Off (TOKEN_OPTIMIZER_FIRST_READ_ACTIVE=0) drops every cohort back
139
+ to shadow (measure-only) without disabling measurement. The full file is
140
+ always served (retarget: the target is never skeletonized; periphery
141
+ skeletons are injected as additionalContext, see _serve_first_read_retarget).
142
+ """
143
+ return is_v5_flag_enabled(
144
+ "v5_first_read_active",
145
+ "TOKEN_OPTIMIZER_FIRST_READ_ACTIVE",
146
+ default=True,
147
+ )
148
+
149
+
150
+ # Cohorts (language, size-band) promoted shadow->active because real-history
151
+ # backfill showed an edit-within-5-turns rate well under the 15% gate with a
152
+ # confident sample (>=20). Bands MUST match compression_backfill._size_band.
153
+ # Reversible: drop a tuple here (or set TOKEN_OPTIMIZER_FIRST_READ_ACTIVE=0).
154
+ #
155
+ # Two tiers of promotion, both validated by the 2026-06-11 backfill on 6,009
156
+ # sessions / 31,885 first-reads (edit-within-5-turns metric, first-read-per-file):
157
+ # * FULL-GATE cohorts (>=20 reads, >=5 sessions, edit-rate <15%):
158
+ # markdown/python/typescript 16-64KB, python 64-256KB.
159
+ # * INTERPOLATED cohorts: a low-sample cohort with ZERO observed edits in
160
+ # history graduates when the SAME language already passed the full gate in an
161
+ # ADJACENT size band. markdown 64-256KB (13 reads, 0% edits; markdown 16-64KB
162
+ # passed) and typescript 64-256KB (2 reads, 0% edits; typescript 16-64KB
163
+ # passed) qualify. This trades a thin sample for the strong language signal
164
+ # plus the always-recoverable `expand` safety net. New languages with no
165
+ # adjacent passing band (json/yaml/javascript) stay measure-only until they
166
+ # accumulate enough history or are promoted via `measure.py cohorts promote`.
167
+ FIRST_READ_ACTIVE_COHORTS = frozenset({
168
+ ("python", "16-64KB"),
169
+ ("python", "64-256KB"),
170
+ ("typescript", "16-64KB"),
171
+ ("typescript", "64-256KB"), # interpolated (ts 16-64KB passed, 0% edits)
172
+ })
173
+ # NOTE: markdown cohorts were demoted to shadow (measure-only) on
174
+ # 2026-06-30. A code skeleton (signatures/imports) is structure-preserving, but
175
+ # the markdown skeleton is headings-only — prose docs read for understanding
176
+ # lose load-bearing content, and the edit-rate promotion gate does not capture
177
+ # read-need. Markdown still flows through the shadow path so telemetry is kept;
178
+ # re-promote only behind a prose-aware summary. Reversible: re-add the tuples.
179
+
180
+ # Interpolated cohorts: a thin-sample subset of the active set, graduated on an
181
+ # adjacent passing band rather than their own full gate. Tracked as a named
182
+ # constant so measure/backfill can pin against it (drift test) and the dashboard
183
+ # can flag the higher-exposure tier. Serving is identical (they ARE active); the
184
+ # distinction only changes the runtime tripwire's sample floor in measure.py.
185
+ _INTERPOLATED_COHORTS = frozenset({
186
+ ("typescript", "64-256KB"),
187
+ })
188
+
189
+
190
+ def _first_read_size_band(n_bytes: int) -> str:
191
+ """Size band for cohort lookup. MUST match compression_backfill._size_band."""
192
+ kb = n_bytes / 1024
193
+ if kb < 16:
194
+ return "<16KB" # below the shadow floor; never a promoted cohort
195
+ if kb < 64:
196
+ return "16-64KB"
197
+ if kb < 256:
198
+ return "64-256KB"
199
+ if kb < 1024:
200
+ return "256KB-1MB"
201
+ return "1-2MB"
202
+
203
+
204
+ # First-read shadow size window (bytes). Below the floor a skeleton saves too
205
+ # little to justify the extra hot-path read; above the ceiling we refuse to read
206
+ # content on the PreToolUse path to stay inside the hook budget.
207
+ FIRST_READ_SHADOW_MIN_BYTES = 16 * 1024
208
+ FIRST_READ_SHADOW_MAX_BYTES = 2 * 1024 * 1024
209
+ # Only log a shadow opportunity when the skeleton is a clear win, matching the
210
+ # >=40% gate U3/U4 use, so coverage reflects genuinely compressible reads.
211
+ FIRST_READ_SHADOW_MIN_RATIO = 0.40
212
+
213
+ # compression_events feature names for the first-read shadow path. measure.py's
214
+ # coverage view matches on these same strings (its own mirror constants).
215
+ FEATURE_FIRST_READ_SKELETON = "first_read_skeleton"
216
+ FEATURE_FIRST_READ_EDIT_FOLLOWUP = "first_read_edit_followup"
217
+
218
+ # WS2 runtime tripwire: measure.py writes the set of auto-demoted cohorts here
219
+ # when a cohort's live edit-rate exceeds the gate. The hot-path read consults it
220
+ # so a demoted cohort falls back to shadow (measure-only) without a code change.
221
+ # Cached in-process with an mtime gate so repeated reads in one process are free.
222
+ _TRIPWIRE_SIDECAR_NAME = "cohort_tripwire.json"
223
+ _demoted_cohorts_cache: "tuple[float, frozenset | _AllCohortsDemoted] | None" = None
224
+
225
+
226
+ class _AllCohortsDemoted(frozenset):
227
+ """Sentinel meaning 'sidecar exists but is unreadable → demote everything'.
228
+
229
+ A frozenset subclass whose membership test is always True, so the hot-path
230
+ `cohort not in _demoted_cohorts()` short-circuits every active cohort back to
231
+ shadow (measure-only) for this call. Used ONLY for a sidecar that EXISTS but
232
+ is corrupt/malformed — fail-CLOSED on corruption. A MISSING sidecar stays
233
+ fail-open (empty frozenset) since "no sidecar yet" legitimately means "no
234
+ demotions computed yet", not "verdict lost".
235
+ """
236
+
237
+ __slots__ = ()
238
+
239
+ def __contains__(self, item) -> bool: # type: ignore[override]
240
+ return True
241
+
242
+
243
+ _ALL_COHORTS_DEMOTED = _AllCohortsDemoted()
244
+
245
+
246
+ def _valid_tripwire_payload(data: Any) -> bool:
247
+ """Schema-validate the tripwire sidecar (T1 fail-closed-on-corruption).
248
+
249
+ `demoted` must be a list of 2-element string pairs; `edit_rates` (when
250
+ present) a dict. Anything else is treated as corruption.
251
+ """
252
+ if not isinstance(data, dict):
253
+ return False
254
+ demoted = data.get("demoted", [])
255
+ if not isinstance(demoted, list):
256
+ return False
257
+ for pair in demoted:
258
+ if not isinstance(pair, (list, tuple)) or len(pair) != 2:
259
+ return False
260
+ if not all(isinstance(x, str) for x in pair):
261
+ return False
262
+ rates = data.get("edit_rates", {})
263
+ if not isinstance(rates, dict):
264
+ return False
265
+ return True
266
+
267
+
268
+ def _demoted_cohorts() -> "frozenset | _AllCohortsDemoted":
269
+ """Cohorts auto-demoted by the runtime tripwire (frozenset of (lang, band)).
270
+
271
+ Reads the `cohort_tripwire.json` sidecar maintained by measure.py.
272
+ * MISSING sidecar -> empty frozenset (fail-OPEN: no demotions computed yet;
273
+ worst case is serving a skeleton the tripwire would later demote, which
274
+ the next edit-rate cycle re-resolves).
275
+ * CORRUPT/malformed sidecar that EXISTS -> _ALL_COHORTS_DEMOTED sentinel
276
+ (fail-CLOSED for corruption: every active cohort drops to shadow this
277
+ call rather than trusting a verdict we cannot parse).
278
+ TOCTOU-safe: a single open('rb') + os.fstat(fd) reads the mtime of the EXACT
279
+ bytes consumed (T2), so the cached verdict can never key off a different file
280
+ version than the one parsed. Mtime-gated so the hot path pays ~one open/fstat
281
+ per process.
282
+ """
283
+ global _demoted_cohorts_cache
284
+ try:
285
+ path = SNAPSHOT_DIR / _TRIPWIRE_SIDECAR_NAME
286
+ try:
287
+ fd = os.open(str(path), os.O_RDONLY)
288
+ except OSError:
289
+ return frozenset() # missing -> fail-open
290
+ try:
291
+ st = os.fstat(fd)
292
+ mtime = st.st_mtime
293
+ if (
294
+ _demoted_cohorts_cache is not None
295
+ and _demoted_cohorts_cache[0] == mtime
296
+ ):
297
+ return _demoted_cohorts_cache[1]
298
+ raw = os.read(fd, st.st_size) if st.st_size else b""
299
+ finally:
300
+ os.close(fd)
301
+ try:
302
+ data = json.loads(raw.decode("utf-8")) if raw else {}
303
+ except (ValueError, UnicodeDecodeError):
304
+ _demoted_cohorts_cache = (mtime, _ALL_COHORTS_DEMOTED)
305
+ return _ALL_COHORTS_DEMOTED
306
+ if not _valid_tripwire_payload(data):
307
+ _demoted_cohorts_cache = (mtime, _ALL_COHORTS_DEMOTED)
308
+ return _ALL_COHORTS_DEMOTED
309
+ demoted = frozenset(
310
+ (str(c[0]), str(c[1])) for c in data.get("demoted", [])
311
+ )
312
+ _demoted_cohorts_cache = (mtime, demoted)
313
+ return demoted
314
+ except Exception:
315
+ # Any unexpected error after we KNOW the sidecar exists is treated as
316
+ # corruption (fail-closed); a pre-open OSError already returned fail-open.
317
+ return _ALL_COHORTS_DEMOTED
318
+
319
+ # ---------------------------------------------------------------------------
320
+ # Configuration
321
+ # ---------------------------------------------------------------------------
322
+
323
+ SNAPSHOT_DIR = resolve_snapshot_dir()
324
+ CACHE_DIR = SNAPSHOT_DIR / "read-cache"
325
+ TRENDS_DB = SNAPSHOT_DIR / "trends.db"
326
+ MAX_CONTEXTIGNORE_PATTERNS = 200
327
+ READ_CACHE_MODES = frozenset({"shadow", "warn", "soft_block", "block"})
328
+ DEFAULT_MODE = "soft_block"
329
+
330
+ MIN_STRUCTURE_CONFIDENCE = 0.75
331
+ MAX_CONSECUTIVE_DENIALS = 3
332
+ REASON_ONLY_TOKENS_EST = 10
333
+ # U-G3: conservative avoided-search credit when a proactive hint sends the agent
334
+ # straight to a file (~2 exploratory reads of ~2500 tokens it didn't have to do
335
+ # to locate it). Deliberately small -- lean understated, observed-once per file.
336
+ _HINT_FOLLOW_AVOIDED_TOKENS = 5000
337
+ STRICT_CONTEXT_CAPS = {
338
+ "signatures": 350,
339
+ "top_level": 500,
340
+ "skeleton": 850,
341
+ "digest": 500,
342
+ }
343
+ MAX_ADDITIONAL_CONTEXT_CHARS = 2600
344
+ STRICT_ADDITIONAL_CONTEXT_CHARS = 1000
345
+
346
+ # All binary extensions (early-return path). Token-cost warnings use the
347
+ # narrower EXPENSIVE_BINARY subset in detectors/pdf_ingestion.py.
348
+ BINARY_EXTENSIONS = frozenset({
349
+ ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".webp", ".svg",
350
+ ".pdf", ".wasm", ".zip", ".tar", ".gz", ".bz2", ".7z", ".rar",
351
+ ".exe", ".dll", ".so", ".dylib", ".o", ".a",
352
+ ".mp3", ".mp4", ".wav", ".avi", ".mov", ".mkv",
353
+ ".ttf", ".otf", ".woff", ".woff2", ".eot",
354
+ ".pyc", ".pyo", ".class", ".jar",
355
+ ".sqlite", ".db", ".sqlite3",
356
+ })
357
+
358
+
359
+ # ---------------------------------------------------------------------------
360
+ # .contextignore
361
+ # ---------------------------------------------------------------------------
362
+
363
+ _contextignore_cache: dict[str, list[str]] = {}
364
+
365
+
366
+ def _load_contextignore_patterns() -> list[str]:
367
+ """Load .contextignore patterns from project root and global config."""
368
+
369
+ cache_key = "patterns"
370
+ if cache_key in _contextignore_cache:
371
+ return _contextignore_cache[cache_key]
372
+
373
+ patterns: list[str] = []
374
+
375
+ project_ignore = Path(".contextignore")
376
+ if project_ignore.exists():
377
+ try:
378
+ for line in project_ignore.read_text(encoding="utf-8").splitlines():
379
+ line = line.strip()
380
+ if line and not line.startswith("#"):
381
+ patterns.append(line)
382
+ except OSError:
383
+ pass
384
+
385
+ global_ignore = runtime_home() / ".contextignore"
386
+ if global_ignore.exists():
387
+ try:
388
+ for line in global_ignore.read_text(encoding="utf-8").splitlines():
389
+ line = line.strip()
390
+ if line and not line.startswith("#"):
391
+ patterns.append(line)
392
+ except OSError:
393
+ pass
394
+
395
+ patterns = patterns[:MAX_CONTEXTIGNORE_PATTERNS]
396
+ _contextignore_cache[cache_key] = patterns
397
+ return patterns
398
+
399
+
400
+ def _is_contextignored(file_path: str) -> bool:
401
+ """Check if file matches any .contextignore pattern."""
402
+
403
+ patterns = _load_contextignore_patterns()
404
+ if not patterns:
405
+ return False
406
+ for pattern in patterns:
407
+ if fnmatch(file_path, pattern) or fnmatch(Path(file_path).name, pattern):
408
+ return True
409
+ return False
410
+
411
+
412
+ # ---------------------------------------------------------------------------
413
+ # Cache operations
414
+ # ---------------------------------------------------------------------------
415
+
416
+ def _make_store(
417
+ session_id: str, busy_timeout_ms: Optional[int] = None
418
+ ) -> Optional["SessionStore"]:
419
+ if SessionStore is None:
420
+ return None
421
+ try:
422
+ if busy_timeout_ms is None:
423
+ return SessionStore(session_id)
424
+ return SessionStore(session_id, busy_timeout_ms=busy_timeout_ms)
425
+ except Exception:
426
+ return None
427
+
428
+
429
+ # --- Compaction boundary detection -----------------------------------------
430
+ # After a compaction the model no longer holds the files it read earlier, so a
431
+ # file_reads row from before the boundary must not make a re-Read "redundant".
432
+ # Native Claude Code clears the rows from SessionStart(compact)
433
+ # (--clear-compacted), but hosts without that hook (the Cowork build ships no
434
+ # SessionStart/PreCompact) never cleared them, and soft_block then told the
435
+ # model a file was "already in context" when it was gone. So the Read hook
436
+ # checks the transcript itself: Claude Code appends a
437
+ # {"type":"system","subtype":"compact_boundary"} row at every /compact or
438
+ # auto-compact, followed by the summary as a user row with
439
+ # "isCompactSummary": true. A per-session cursor (session_meta) means each
440
+ # Read scans only the bytes appended since the previous Read.
441
+ #
442
+ # The cursor is a {transcript_path: offset} map, not a single path: hooks fired
443
+ # from a subagent carry a different transcript_path than the main session, and
444
+ # with one slot every alternation reset the offset to 0, rescanned the whole
445
+ # file, re-found the OLD boundaries and cleared file_reads again, so read dedup
446
+ # was effectively off in any session that used subagents. Boundaries already
447
+ # acted on are remembered (row uuid, else a hash of the row), so the same
448
+ # boundary never clears twice even if a file is rescanned from 0.
449
+ _COMPACT_SCAN_META_KEY = "compact_scan_cursor"
450
+ _COMPACT_SCAN_MAX_PATHS = 32
451
+ _COMPACT_SCAN_MAX_SEEN = 256
452
+ _COMPACT_MARKERS = (b"compact_boundary", b"isCompactSummary")
453
+ _COMPACT_SCAN_CHUNK = 1 << 20 # 1 MiB
454
+ _COMPACT_SCAN_MAX_SECONDS = 0.25
455
+
456
+
457
+ def _compact_boundary_id(line: bytes, where: str = ""):
458
+ """Stable id of a real compaction row (its uuid, else a hash of the row and
459
+ ``where`` it sits: path + byte offset, so two identical uuid-less rows stay
460
+ distinct), or None when the line is not one: a tool result that merely
461
+ quotes the marker text (reading TO's own source would otherwise trip it)
462
+ is not."""
463
+ if not any(m in line for m in _COMPACT_MARKERS):
464
+ return None
465
+ try:
466
+ row = json.loads(line.decode("utf-8", errors="replace"))
467
+ except (ValueError, UnicodeDecodeError):
468
+ return None
469
+ if not isinstance(row, dict):
470
+ return None
471
+ if not ((row.get("type") == "system" and row.get("subtype") == "compact_boundary")
472
+ or row.get("isCompactSummary") is True):
473
+ return None
474
+ uuid = row.get("uuid")
475
+ if isinstance(uuid, str) and uuid:
476
+ return "u:" + uuid[:80]
477
+ import hashlib
478
+ return "h:" + hashlib.sha1(where.encode("utf-8", "replace") + b"\0" + line.strip()).hexdigest()[:20]
479
+
480
+
481
+ def _is_compact_boundary_row(line: bytes) -> bool:
482
+ return _compact_boundary_id(line) is not None
483
+
484
+
485
+ def _load_compact_cursor(store: Any) -> tuple:
486
+ """(paths: {path: offset}, seen: [boundary ids]) from session_meta. Reads
487
+ the pre-map single-slot shape too. Never raises."""
488
+ try:
489
+ raw = store.get_meta(_COMPACT_SCAN_META_KEY)
490
+ cur = json.loads(raw) if raw else None
491
+ except Exception:
492
+ cur = None
493
+ if not isinstance(cur, dict):
494
+ return {}, []
495
+ paths: dict = {}
496
+ if isinstance(cur.get("paths"), dict):
497
+ for k, v in cur["paths"].items():
498
+ try:
499
+ paths[str(k)] = max(0, int(v))
500
+ except (TypeError, ValueError):
501
+ continue
502
+ elif isinstance(cur.get("path"), str):
503
+ try:
504
+ paths[cur["path"]] = max(0, int(cur.get("offset") or 0))
505
+ except (TypeError, ValueError):
506
+ pass
507
+ seen = [x for x in cur.get("seen") or [] if isinstance(x, str)]
508
+ return paths, seen
509
+
510
+
511
+ def _scan_for_compaction(store: Any, transcript_path: Any) -> bool:
512
+ """Advance this session's cursor for ``transcript_path``; True when a
513
+ compaction boundary not acted on before appeared in that file.
514
+
515
+ Line-aligned: the cursor only moves past complete lines, so a row being
516
+ written while we read is seen whole on the next Read. Bounded by
517
+ _COMPACT_SCAN_MAX_SECONDS; an unfinished scan resumes next time. Each
518
+ transcript keeps its own offset (subagent hooks alternate paths); a
519
+ transcript that shrank restarts from 0, and a boundary seen before never
520
+ counts again. Fail-open: any error returns False (status quo behaviour),
521
+ never raises.
522
+ """
523
+ if store is None or not transcript_path:
524
+ return False
525
+ try:
526
+ path = str(transcript_path)
527
+ st = os.stat(path)
528
+ if not stat_module.S_ISREG(st.st_mode):
529
+ return False
530
+ size = st.st_size
531
+ paths, seen = _load_compact_cursor(store)
532
+ offset = paths.get(path, 0)
533
+ if offset > size:
534
+ offset = 0 # rewritten / truncated transcript: rescan
535
+ if offset == size:
536
+ return False
537
+ found = False
538
+ new_ids: list = []
539
+ start = time.monotonic()
540
+ pos = offset
541
+ with open(path, "rb") as fh:
542
+ fh.seek(offset)
543
+ carry = b""
544
+ while pos + len(carry) < size:
545
+ chunk = fh.read(min(_COMPACT_SCAN_CHUNK, size - pos - len(carry)))
546
+ if not chunk:
547
+ break
548
+ buf = carry + chunk
549
+ cut = buf.rfind(b"\n")
550
+ if cut < 0:
551
+ carry = buf
552
+ if len(carry) > 64 * _COMPACT_SCAN_CHUNK:
553
+ break # absurd single line: stop, resume later
554
+ continue
555
+ complete, carry = buf[: cut + 1], buf[cut + 1:]
556
+ if any(m in complete for m in _COMPACT_MARKERS):
557
+ line_at = pos
558
+ for line in complete.split(b"\n"):
559
+ bid = _compact_boundary_id(line, "%s@%d" % (path, line_at)) if line else None
560
+ line_at += len(line) + 1
561
+ if bid and bid not in seen and bid not in new_ids:
562
+ new_ids.append(bid)
563
+ found = True
564
+ pos += len(complete)
565
+ if time.monotonic() - start > _COMPACT_SCAN_MAX_SECONDS:
566
+ break
567
+ if pos != offset or new_ids:
568
+ paths.pop(path, None)
569
+ paths[path] = pos # most recent last; the oldest paths drop first
570
+ while len(paths) > _COMPACT_SCAN_MAX_PATHS:
571
+ paths.pop(next(iter(paths)))
572
+ seen = (seen + new_ids)[-_COMPACT_SCAN_MAX_SEEN:]
573
+ try:
574
+ store.set_meta(_COMPACT_SCAN_META_KEY,
575
+ json.dumps({"v": 2, "paths": paths, "seen": seen}))
576
+ except Exception:
577
+ pass
578
+ return found
579
+ except Exception:
580
+ return False
581
+
582
+
583
+ def _cache_path(session_id: str) -> Path:
584
+ safe_id = re.sub(r"[^a-zA-Z0-9_-]", "", session_id) or "unknown"
585
+ return CACHE_DIR / f"{safe_id}.json"
586
+
587
+
588
+ def _decisions_log_path(session_id: str = "unknown") -> Path:
589
+ safe_id = re.sub(r"[^a-zA-Z0-9_-]", "", session_id) or "unknown"
590
+ decisions_dir = CACHE_DIR / "decisions"
591
+ decisions_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
592
+ return decisions_dir / f"{safe_id}.jsonl"
593
+
594
+
595
+
596
+ def _reset_replacement_state(entry: dict[str, Any]) -> None:
597
+ entry["last_replacement_fingerprint"] = ""
598
+ entry["last_replacement_type"] = ""
599
+ entry["repeat_replacement_count"] = 0
600
+ entry["consecutive_denials"] = 0
601
+ entry["last_structure_reason"] = ""
602
+ entry["last_structure_confidence"] = 0.0
603
+
604
+
605
+ def _check_escape_hatch(
606
+ entry: dict[str, Any],
607
+ store: Any,
608
+ file_path: str,
609
+ session_id: str,
610
+ mode: str,
611
+ offset: int,
612
+ limit: int,
613
+ tokens_est: int,
614
+ language: str,
615
+ eligible: bool,
616
+ summary: Any,
617
+ save_hook_context_enabled: bool,
618
+ quiet: bool,
619
+ ) -> bool:
620
+ """Allow the read if consecutive denials reach the threshold. Returns True if escaped."""
621
+ consecutive_denials = int(entry.get("consecutive_denials", 0) or 0) + 1
622
+ if consecutive_denials < MAX_CONSECUTIVE_DENIALS:
623
+ entry["consecutive_denials"] = consecutive_denials
624
+ return False
625
+
626
+ entry["consecutive_denials"] = 0
627
+ _reset_replacement_state(entry)
628
+ store.upsert_file_entry(file_path, entry)
629
+ _log_decision(
630
+ "allow",
631
+ file_path,
632
+ f"escape_hatch_read_{entry['read_count']}",
633
+ session_id,
634
+ mode=mode,
635
+ actual_substitution=False,
636
+ eligible=eligible,
637
+ language=language,
638
+ reason_code="consecutive_denial_escape",
639
+ offset=offset,
640
+ limit=limit,
641
+ replacement_type=summary.replacement_type if summary else None,
642
+ file_tokens_est=tokens_est,
643
+ replacement_tokens_est=0,
644
+ net_saved_tokens_est=0,
645
+ replacement_fingerprint=summary.fingerprint if summary else None,
646
+ repeat_replacement_count=consecutive_denials,
647
+ save_hook_additional_context_enabled=save_hook_context_enabled,
648
+ confidence=summary.confidence if summary else 0.0,
649
+ )
650
+ if not quiet:
651
+ print(
652
+ f"[Read Cache] Escape hatch: allowing read after {consecutive_denials} consecutive denials: {file_path}",
653
+ file=sys.stderr,
654
+ )
655
+ return True
656
+
657
+
658
+ def _ensure_entry_defaults(entry: dict[str, Any]) -> None:
659
+ entry.setdefault("mtime_ns", 0)
660
+ entry.setdefault("size_bytes", 0)
661
+ entry.setdefault("tokens_est", 0)
662
+ entry.setdefault("read_count", 0)
663
+ entry.setdefault("last_access", 0.0)
664
+ entry.setdefault("last_replacement_fingerprint", "")
665
+ entry.setdefault("last_replacement_type", "")
666
+ entry["repeat_replacement_count"] = int(entry.get("repeat_replacement_count", 0) or 0)
667
+ entry["consecutive_denials"] = int(entry.get("consecutive_denials", 0) or 0)
668
+ entry["last_structure_reason"] = entry.get("last_structure_reason", "")
669
+ entry["last_structure_confidence"] = float(entry.get("last_structure_confidence", 0.0) or 0.0)
670
+ if "ranges_seen" not in entry:
671
+ old_off = int(entry.get("offset", 0) or 0)
672
+ old_lim = int(entry.get("limit", 0) or 0)
673
+ entry["ranges_seen"] = [[old_off, old_lim]]
674
+
675
+
676
+ def _log_decision(
677
+ decision: str,
678
+ file_path: str,
679
+ reason: str,
680
+ session_id: str,
681
+ **extra: Any,
682
+ ) -> None:
683
+ entry = {
684
+ "ts": time.time(),
685
+ "decision": decision,
686
+ "file": file_path,
687
+ "reason": reason,
688
+ "session": session_id,
689
+ }
690
+ entry.update(extra)
691
+ log_path = _decisions_log_path(session_id)
692
+ try:
693
+ fd = os.open(str(log_path), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
694
+ with os.fdopen(fd, "a", encoding="utf-8") as handle:
695
+ handle.write(json.dumps(entry, sort_keys=True) + "\n")
696
+ except OSError:
697
+ pass
698
+
699
+
700
+ def _log_unexpected_tool(tool_name: str, quiet: bool = False) -> None:
701
+ """Log when the hook is invoked for a non-Read tool (matcher bypass)."""
702
+ log_dir = SNAPSHOT_DIR / "diagnostics"
703
+ try:
704
+ log_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
705
+ log_path = log_dir / "unexpected_tool_invocations.jsonl"
706
+ entry = {
707
+ "ts": time.time(),
708
+ "tool_name": tool_name,
709
+ "event": "read_cache_invoked_for_non_read_tool",
710
+ }
711
+ fd = os.open(str(log_path), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
712
+ with os.fdopen(fd, "a", encoding="utf-8") as handle:
713
+ handle.write(json.dumps(entry, sort_keys=True) + "\n")
714
+ except OSError:
715
+ pass
716
+ if not quiet:
717
+ print(
718
+ f"[Read Cache] WARNING: invoked for tool '{tool_name}', expected 'Read'. Skipping.",
719
+ file=sys.stderr,
720
+ )
721
+
722
+
723
+ # ---------------------------------------------------------------------------
724
+ # Hook response helpers
725
+ # ---------------------------------------------------------------------------
726
+
727
+ def _emit_pretool_response(
728
+ permission_decision: Optional[str],
729
+ reason: Optional[str],
730
+ additional_context: Optional[str] = None,
731
+ ) -> None:
732
+ payload: dict[str, Any] = {
733
+ "hookSpecificOutput": {
734
+ "hookEventName": "PreToolUse",
735
+ }
736
+ }
737
+ hook_output = payload["hookSpecificOutput"]
738
+ if permission_decision:
739
+ hook_output["permissionDecision"] = permission_decision
740
+ if reason:
741
+ hook_output["permissionDecisionReason"] = reason
742
+ if additional_context:
743
+ hook_output["additionalContext"] = additional_context
744
+ # A broken custom pattern file keeps redacted writes out of every cache —
745
+ # surface that once per file hash as a user-visible systemMessage.
746
+ if _pop_redaction_warning is not None:
747
+ try:
748
+ _warn_msg = _pop_redaction_warning()
749
+ except Exception:
750
+ _warn_msg = None
751
+ if _warn_msg:
752
+ payload["systemMessage"] = _warn_msg
753
+ print(json.dumps(payload))
754
+
755
+
756
+ def _build_structure_message(
757
+ file_path: str,
758
+ summary: StructureMapResult,
759
+ net_saved_tokens_est: int,
760
+ ) -> str:
761
+ return "\n".join(
762
+ [
763
+ f"[Token Optimizer] {Path(file_path).name} is unchanged (already read this session).",
764
+ f"Using {summary.replacement_type} view (~{net_saved_tokens_est:,} tokens saved).",
765
+ "You can still Edit this file directly, or Read a specific range (offset/limit) for full content.",
766
+ "",
767
+ summary.replacement_text,
768
+ ]
769
+ )
770
+
771
+
772
+ def _build_reason_only_message(file_path: str) -> str:
773
+ return (
774
+ f"[Token Optimizer] {Path(file_path).name} is unchanged, already in context, and was already "
775
+ "summarized in this session. You can still Edit this file or Read a specific range."
776
+ )
777
+
778
+
779
+ def _hook_additional_context_saved() -> bool:
780
+ value = os.environ.get("CLAUDE_CODE_SAVE_HOOK_ADDITIONAL_CONTEXT", "").strip().lower()
781
+ return value not in ("", "0", "false", "no")
782
+
783
+
784
+ def _additional_context_within_cap(text: str, strict: bool) -> bool:
785
+ cap = STRICT_ADDITIONAL_CONTEXT_CHARS if strict else MAX_ADDITIONAL_CONTEXT_CHARS
786
+ return len(text) <= cap
787
+
788
+
789
+ # ---------------------------------------------------------------------------
790
+ # Savings tracking
791
+ # ---------------------------------------------------------------------------
792
+
793
+ _SAVINGS_SCHEMA = """
794
+ CREATE TABLE IF NOT EXISTS savings_events (
795
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
796
+ timestamp TEXT NOT NULL,
797
+ event_type TEXT NOT NULL,
798
+ tokens_saved INTEGER DEFAULT 0,
799
+ cost_saved_usd REAL DEFAULT 0.0,
800
+ session_id TEXT,
801
+ session_uuid TEXT,
802
+ detail TEXT,
803
+ model TEXT,
804
+ unjoinable INTEGER DEFAULT 0
805
+ );
806
+ """
807
+
808
+ _UUID_PAT_RC = re.compile(
809
+ r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
810
+ re.IGNORECASE,
811
+ )
812
+
813
+
814
+ def _extract_session_uuid_rc(session_id: Optional[str]) -> tuple:
815
+ """Return (session_uuid, unjoinable) for the read_cache fast path.
816
+
817
+ A full Claude UUID (8-4-4-4-12 hex) is the JSONL stem and can be joined
818
+ directly on session_log.session_uuid. Short opaque agent_ids (<=20 chars,
819
+ no dashes) cannot be resolved and are flagged unjoinable=1 so the
820
+ aggregation layer never silently prices them at the Sonnet fallback.
821
+ """
822
+ if not session_id or session_id in ("unknown", "test-123", "perf_test", "regtest", "demo"):
823
+ return None, False
824
+ if _UUID_PAT_RC.match(session_id):
825
+ return session_id, False
826
+ if len(session_id) <= 20 and "-" not in session_id:
827
+ return None, True
828
+ return None, False
829
+
830
+
831
+ # Process-local: once the savings_events columns are confirmed present we skip
832
+ # the per-write PRAGMA introspection. Fresh tables get all columns from the
833
+ # schema; the ALTERs only matter for pre-v5.10 tables, so one verification per
834
+ # process is enough. (Worst case across mixed old/new DBs in one process: a stale
835
+ # skip -- acceptable for a measurement path, and executescript already creates
836
+ # new tables fully-formed.)
837
+ _savings_columns_verified = False
838
+
839
+
840
+ def _ensure_savings_columns(conn: sqlite3.Connection) -> None:
841
+ """Idempotent migration: ensure model, session_uuid, and unjoinable columns exist.
842
+
843
+ The shipped schema declares all three, but pre-existing tables created before
844
+ v5.10 lack session_uuid and unjoinable. Runs the PRAGMA once per process, then
845
+ short-circuits on subsequent calls in the hot savings-write path.
846
+ """
847
+ global _savings_columns_verified
848
+ if _savings_columns_verified:
849
+ return
850
+ try:
851
+ cols = {row[1] for row in conn.execute("PRAGMA table_info(savings_events)")}
852
+ if "model" not in cols:
853
+ conn.execute("ALTER TABLE savings_events ADD COLUMN model TEXT")
854
+ if "session_uuid" not in cols:
855
+ conn.execute("ALTER TABLE savings_events ADD COLUMN session_uuid TEXT")
856
+ if "unjoinable" not in cols:
857
+ conn.execute("ALTER TABLE savings_events ADD COLUMN unjoinable INTEGER DEFAULT 0")
858
+ # origin: local / cloud / cowork (runtime_env.run_origin). NULL on rows
859
+ # written before the column existed.
860
+ if "origin" not in cols:
861
+ conn.execute("ALTER TABLE savings_events ADD COLUMN origin TEXT")
862
+ # All columns now exist (present already or just ALTER'd, which
863
+ # auto-commits), so future introspection in this process is redundant.
864
+ _savings_columns_verified = True
865
+ except Exception:
866
+ pass
867
+
868
+
869
+ def _ensure_savings_model_column(conn: sqlite3.Connection) -> None:
870
+ """Backward-compat alias for _ensure_savings_columns (used in tests)."""
871
+ _ensure_savings_columns(conn)
872
+
873
+
874
+ def _log_savings_event(event_type: str, tokens_saved: int, session_id: str, detail: str) -> None:
875
+ if tokens_saved <= 0:
876
+ return
877
+ conn: Optional[sqlite3.Connection] = None
878
+ try:
879
+ SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
880
+ conn = sqlite3.connect(str(TRENDS_DB))
881
+ conn.execute("PRAGMA journal_mode=WAL")
882
+ conn.execute("PRAGMA busy_timeout=5000")
883
+ conn.executescript(_SAVINGS_SCHEMA)
884
+ _ensure_savings_columns(conn)
885
+ # U1: derive the stable UUID join key before calling measure imports.
886
+ session_uuid, unjoinable = _extract_session_uuid_rc(session_id)
887
+ # Resolve the event's REAL model from its session and price at that model's
888
+ # rate -- never a flat default. Persisting `model` makes the row repriceable
889
+ # later. Import lazily (measure isn't always loaded in the hook fast path).
890
+ model = None
891
+ cost_per_mtok = 3.0
892
+ try:
893
+ from measure import ( # type: ignore
894
+ _estimate_compression_cost_per_mtok,
895
+ _resolve_session_model,
896
+ )
897
+ model = _resolve_session_model(session_id)
898
+ cost_per_mtok = _estimate_compression_cost_per_mtok(model)
899
+ except Exception:
900
+ pass
901
+ cost_saved = tokens_saved * cost_per_mtok / 1_000_000
902
+ if _savings_columns_verified:
903
+ conn.execute(
904
+ "INSERT INTO savings_events "
905
+ "(timestamp, event_type, tokens_saved, cost_saved_usd, session_id, session_uuid, detail, model, unjoinable, origin) "
906
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
907
+ (datetime.now().isoformat(), event_type, tokens_saved, cost_saved,
908
+ session_id, session_uuid, detail, model, 1 if unjoinable else 0,
909
+ run_origin()),
910
+ )
911
+ else:
912
+ # Column migration did not complete (locked DB): keep the event,
913
+ # without origin, rather than lose it.
914
+ conn.execute(
915
+ "INSERT INTO savings_events "
916
+ "(timestamp, event_type, tokens_saved, cost_saved_usd, session_id, session_uuid, detail, model, unjoinable) "
917
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
918
+ (datetime.now().isoformat(), event_type, tokens_saved, cost_saved,
919
+ session_id, session_uuid, detail, model, 1 if unjoinable else 0),
920
+ )
921
+ conn.commit()
922
+ except Exception:
923
+ pass
924
+ finally:
925
+ if conn is not None:
926
+ try:
927
+ conn.close()
928
+ except Exception:
929
+ pass
930
+
931
+
932
+ # ---------------------------------------------------------------------------
933
+ # Structure summarization
934
+ # ---------------------------------------------------------------------------
935
+
936
+ def _summarize_redundant_read(
937
+ file_path: str,
938
+ *,
939
+ offset: int,
940
+ limit: int,
941
+ file_tokens_est: int,
942
+ ) -> tuple[Optional[StructureMapResult], str]:
943
+ try:
944
+ content = Path(file_path).read_text(encoding="utf-8", errors="replace")
945
+ except OSError:
946
+ return None, "unreadable"
947
+
948
+ # fix-2: fail open. This runs inside the PreToolUse Read hook; an uncaught
949
+ # error in summarization (e.g. a RecursionError on a pathological AST) would
950
+ # crash the hook and could block the user's Read. Any failure here returns
951
+ # (None, "summarize_error"), which the caller treats as not-eligible and
952
+ # serves the file normally.
953
+ try:
954
+ summary = summarize_code_source(
955
+ content,
956
+ file_path=file_path,
957
+ offset=offset,
958
+ limit=limit,
959
+ file_tokens_est=file_tokens_est,
960
+ file_size_bytes=len(content.encode("utf-8", errors="ignore")),
961
+ )
962
+ except Exception:
963
+ return None, "summarize_error"
964
+ reason_code = summary.reason
965
+
966
+ if not summary.eligible:
967
+ return summary, reason_code
968
+
969
+ if summary.confidence < MIN_STRUCTURE_CONFIDENCE:
970
+ return summary, "low_confidence"
971
+
972
+ if _hook_additional_context_saved():
973
+ strict_cap = STRICT_CONTEXT_CAPS.get(summary.replacement_type, len(summary.replacement_text))
974
+ if len(summary.replacement_text) > strict_cap:
975
+ return summary, "hook_context_cap"
976
+
977
+ return summary, "ok"
978
+ # ---------------------------------------------------------------------------
979
+ # Main hook logic
980
+ # ---------------------------------------------------------------------------
981
+
982
+ def _first_read_compress(
983
+ file_path: str,
984
+ stat: os.stat_result,
985
+ offset: int,
986
+ limit: int,
987
+ language: str,
988
+ session_id: str,
989
+ store: "SessionStore",
990
+ mode: str,
991
+ cached_content: Optional[str] = None,
992
+ save_hook_context_enabled: bool = False,
993
+ quiet: bool = True,
994
+ ) -> bool:
995
+ """First-read skeleton path. Returns True iff it SERVED a skeleton
996
+ (active mode emitted a deny+inject and the caller must stop).
997
+
998
+ For a whole-file first read of a structure-supported file in the size window
999
+ that compresses well:
1000
+ * ACTIVE cohort (validated by history) -> serve the skeleton, archive the
1001
+ full original for `expand`, log a measured event. Returns True.
1002
+ * Otherwise -> SHADOW: serve the full file unchanged, log an opportunity
1003
+ event + arm the edit-rate ledger marker (resolved at the Edit hook).
1004
+ Returns False.
1005
+ Fully fail-open: any error returns False (serve the full file).
1006
+ """
1007
+ try:
1008
+ if not _is_first_read_shadow_enabled():
1009
+ return False
1010
+ # Whole-file reads only: a partial range has no skeleton equivalent.
1011
+ if offset != 0 or limit != 0:
1012
+ return False
1013
+ size = int(stat.st_size)
1014
+ if size < FIRST_READ_SHADOW_MIN_BYTES or size > FIRST_READ_SHADOW_MAX_BYTES:
1015
+ return False
1016
+ if not is_structure_supported_file(file_path):
1017
+ return False
1018
+
1019
+ # Reuse the content delta mode already read this turn, if present, to
1020
+ # avoid a second full read of the same file on the hot path.
1021
+ content = (
1022
+ cached_content
1023
+ if cached_content is not None
1024
+ else Path(file_path).read_text(encoding="utf-8", errors="replace")
1025
+ )
1026
+ result = summarize_code_file(file_path, content=content, file_size_bytes=size)
1027
+ if not result.eligible:
1028
+ return False
1029
+ orig_tokens = int(result.file_tokens_est or estimate_tokens(content))
1030
+ skel_tokens = int(result.replacement_tokens_est or 0)
1031
+ if orig_tokens <= 0:
1032
+ return False
1033
+ would_be_ratio = 1.0 - (skel_tokens / orig_tokens)
1034
+ if would_be_ratio < FIRST_READ_SHADOW_MIN_RATIO:
1035
+ return False
1036
+
1037
+ cohort = (language, _first_read_size_band(size))
1038
+ if (
1039
+ _is_first_read_active_enabled()
1040
+ and cohort in FIRST_READ_ACTIVE_COHORTS
1041
+ and cohort not in _demoted_cohorts()
1042
+ and result.replacement_text
1043
+ ):
1044
+ # retarget: the Read TARGET is served full (never denied); the
1045
+ # compression budget moves to PERIPHERY skeletons injected as
1046
+ # additionalContext. Returns False so the caller serves the full
1047
+ # target via the normal allow path. No ``first_read_skeleton`` event
1048
+ # is emitted for the target, and the target-keyed ``active_fr:``
1049
+ # marker is no longer armed here (periphery files carry their own,
1050
+ # armed inside _inject_periphery_skeletons once U2 populates them).
1051
+ return _serve_first_read_retarget(
1052
+ file_path, size, language, session_id, store, content, quiet,
1053
+ )
1054
+
1055
+ # SHADOW (cohort not yet promoted): serve full, measure the opportunity.
1056
+ # Write the ledger marker FIRST, then the skeleton event. If the second
1057
+ # write fails, the failure biases the R9 edit-rate the SAFE way (an
1058
+ # orphan marker can only over-count edits → looks less safe to promote),
1059
+ # never the unsafe way. Keyed by the resolved file_path (handle_invalidate
1060
+ # normalizes the path identically).
1061
+ _shadow_key = _marker_key("shadow_fr", file_path)
1062
+ if _shadow_key is None:
1063
+ return False
1064
+ store.set_meta(
1065
+ _shadow_key,
1066
+ json.dumps({
1067
+ "ts": time.time(),
1068
+ "lang": language,
1069
+ # v5.11.1 (T10): carry the size band so shadow follow-ups emit
1070
+ # lang|band like active ones. _resolve_first_read_marker packs
1071
+ # lang|band when present; older markers without it fall back to
1072
+ # bare lang, so this is backward-compatible.
1073
+ "band": _first_read_size_band(size),
1074
+ "ratio": round(would_be_ratio, 4),
1075
+ "resolved": 0,
1076
+ }),
1077
+ )
1078
+ from compression_log import log_compression_event
1079
+ log_compression_event(
1080
+ feature=FEATURE_FIRST_READ_SKELETON,
1081
+ session_id=session_id,
1082
+ command_pattern=language,
1083
+ tier="opportunity",
1084
+ verified=False,
1085
+ detail=f"shadow size_bytes={size}",
1086
+ original_tokens=orig_tokens,
1087
+ compressed_tokens=skel_tokens,
1088
+ )
1089
+ # U5: record a tool_outputs row with source lineage so the shadow
1090
+ # first-read is self-identifiable from the SQLite store and joinable
1091
+ # to the file-archive meta. Keyed by a derived stable id so the row
1092
+ # and the file archive stay joinable. Fail-open: a write error here
1093
+ # does not affect the read path (the skeleton event above already
1094
+ # recorded the opportunity).
1095
+ try:
1096
+ import hashlib as _hl
1097
+ # The skeleton is derived from file content and can carry a
1098
+ # hardcoded credential; the path can carry tokens too. Same rule
1099
+ # as the read-cache rows above: redacted or not persisted.
1100
+ _safe_skel = _redact_for_storage(result.replacement_text or "")
1101
+ # Redact the whole path, then cut: a token straddling the 500th
1102
+ # character is a prefix no pattern recognises.
1103
+ _safe_path = _redact_for_storage(file_path)
1104
+ if _safe_path is not None:
1105
+ _safe_path = _safe_path[:500]
1106
+ if _safe_skel is None or _safe_path is None:
1107
+ return False
1108
+ _fr_tool_use_id = "fr_shadow_" + _hl.sha256(
1109
+ f"{session_id}|{file_path}".encode("utf-8", errors="replace")
1110
+ ).hexdigest()[:16]
1111
+ _fr_output_hash = _hl.sha256(
1112
+ (result.replacement_text or "")[:10000].encode("utf-8", errors="replace")
1113
+ ).hexdigest()[:16]
1114
+ store.insert_tool_output(
1115
+ tool_use_id=_fr_tool_use_id,
1116
+ tool_name="Read",
1117
+ tool_type="read",
1118
+ command_or_path=_safe_path,
1119
+ output_hash=_fr_output_hash,
1120
+ output_chars=len(result.replacement_text or ""),
1121
+ output_tokens_est=skel_tokens,
1122
+ compressed_preview=_safe_skel[:1500],
1123
+ source_file_path=_safe_path,
1124
+ language=language,
1125
+ archived_from="first_read_skeleton",
1126
+ output_text=_safe_skel[:50000],
1127
+ )
1128
+ except Exception:
1129
+ pass
1130
+ return False
1131
+ except Exception:
1132
+ return False
1133
+
1134
+
1135
+ def _inject_periphery_skeletons(
1136
+ file_path: str,
1137
+ content: str,
1138
+ language: str,
1139
+ session_id: str,
1140
+ store: "SessionStore",
1141
+ quiet: bool,
1142
+ target_band: str = "",
1143
+ ) -> None:
1144
+ """Inject bounded skeletons of periphery (one-hop) files as additionalContext.
1145
+
1146
+ the Read target is served full by the caller; this hook point
1147
+ adds skeletons of related files the agent would otherwise have to explore.
1148
+ The reference graph is computed on-read, one hop out, and never persisted
1149
+ (no DB/cache writes beyond the periphery edit-rate marker, which lives in
1150
+ the existing per-session store).
1151
+
1152
+ Resolves one-hop relationships for the just-read target, builds a bounded
1153
+ periphery block (PageRank-ordered once U3 lands), and emits it via
1154
+ ``_emit_pretool_response(None, None, block)`` only when it fits
1155
+ ``_additional_context_within_cap``; otherwise the block is dropped (the
1156
+ target is still served full). Periphery-keyed ``active_fr:<periphery_path>``
1157
+ edit-rate markers are armed with the TARGET's lang|band so the cohort
1158
+ tripwire attributes a periphery edit to the target's cohort. Fail-open:
1159
+ any error drops the block.
1160
+ """
1161
+ try:
1162
+ from structure_map import (
1163
+ build_periphery_skeleton, resolve_one_hop_relationships,
1164
+ )
1165
+ # Thread the already-in-memory target source so resolve_one_hop doesn't
1166
+ # re-read/re-parse the file we just read on the hot path (LOW).
1167
+ related = resolve_one_hop_relationships(file_path, language, content=content)
1168
+ if not related:
1169
+ return
1170
+ block = build_periphery_skeleton(related)
1171
+ if not block:
1172
+ return
1173
+ message = (
1174
+ f"[Token Optimizer] Periphery skeletons for {Path(file_path).name} "
1175
+ f"(one-hop relations: {len(related)}). The file you opened is served "
1176
+ f"in full; these are bounded maps of related files."
1177
+ )
1178
+ text = message + "\n\n" + block
1179
+ if not _additional_context_within_cap(text, _hook_additional_context_saved()):
1180
+ # Never withhold the target: drop the periphery block over the cap.
1181
+ return
1182
+ _arm_periphery_markers(related, language, target_band, store)
1183
+ _emit_pretool_response(None, None, text)
1184
+ except Exception:
1185
+ return
1186
+
1187
+
1188
+ def _arm_periphery_markers(
1189
+ related: list,
1190
+ language: str,
1191
+ target_band: str,
1192
+ store: "SessionStore",
1193
+ ) -> None:
1194
+ """Arm periphery-keyed ``active_fr:<periphery_path>`` edit-rate markers.
1195
+
1196
+ The marker stores the TARGET's lang|band (not the periphery file's) so the
1197
+ cohort tripwire attributes a subsequent edit of a periphery file to the
1198
+ target's cohort -- the signal that the periphery skeleton omitted
1199
+ content the model then needed. Best-effort; never raises.
1200
+ """
1201
+ if store is None:
1202
+ return
1203
+ for p in related:
1204
+ try:
1205
+ _active_key = _marker_key("active_fr", p)
1206
+ if _active_key is None:
1207
+ continue
1208
+ store.set_meta(
1209
+ _active_key,
1210
+ json.dumps({
1211
+ "ts": time.time(),
1212
+ "lang": language,
1213
+ "band": target_band,
1214
+ "resolved": 0,
1215
+ }),
1216
+ )
1217
+ except Exception:
1218
+ pass
1219
+
1220
+
1221
+ def _serve_first_read_retarget(
1222
+ file_path: str,
1223
+ size: int,
1224
+ language: str,
1225
+ session_id: str,
1226
+ store: "SessionStore",
1227
+ content: str,
1228
+ quiet: bool,
1229
+ ) -> bool:
1230
+ """ACTIVE mode, retargeted Returns False so the caller serves the
1231
+ Read TARGET in full -- the target is never replaced by a skeleton.
1232
+
1233
+ The compression budget moves to the PERIPHERY: bounded skeletons of one-hop
1234
+ call/import relatives are injected as additionalContext (never replacing
1235
+ content already promised to the model). _inject_periphery_skeletons owns
1236
+ that path and arms periphery-keyed edit-rate markers; the target-keyed
1237
+ ``active_fr:<file_path>`` marker is NOT armed here, so the cohort tripwire
1238
+ now measures periphery edits, not target edits.
1239
+
1240
+ No ``first_read_skeleton`` measured event is emitted for the target. Shadow
1241
+ (measure-only) behavior is unchanged and preserves telemetry continuity.
1242
+ Fully fail-open: any error in the periphery path drops the block (the target
1243
+ is already served full), so this always returns False.
1244
+ """
1245
+ try:
1246
+ _inject_periphery_skeletons(
1247
+ file_path, content, language, session_id, store, quiet,
1248
+ target_band=_first_read_size_band(size),
1249
+ )
1250
+ except Exception:
1251
+ pass
1252
+ return False
1253
+
1254
+
1255
+ def _resolve_first_read_shadow_on_edit(
1256
+ file_path: str,
1257
+ language: str,
1258
+ session_id: str,
1259
+ store: "SessionStore",
1260
+ ) -> None:
1261
+ """Resolve a shadow first-read ledger marker at the Edit/Write hook.
1262
+
1263
+ A shadow-measured first read followed by an edit to the same file is the
1264
+ "the model needed the full file" proxy. Emit an Opportunity-tier follow-up
1265
+ event so coverage can compute the cohort edit-rate
1266
+ (followups / shadows). Marked resolved so repeated edits count once.
1267
+ Fully fail-open.
1268
+
1269
+ Known limitation: the marker lives in the per-session store, so an edit in a
1270
+ DIFFERENT session than the shadow read is not resolved. The proxy therefore
1271
+ undercounts edits for cross-session read→edit patterns, biasing the edit-rate
1272
+ LOW (toward "promote"). The promotion decision must account for this with
1273
+ a conservative gate and human review before any active-mode flip — it must
1274
+ not auto-promote purely on this proxy.
1275
+ """
1276
+ # Resolve BOTH the shadow marker (measure-only cohorts, opportunity tier) and
1277
+ # the active marker (promoted cohorts, measured tier). The active follow-ups
1278
+ # feed the WS2 runtime tripwire's per-cohort live edit-rate; a demotion fires
1279
+ # when that rate exceeds the gate.
1280
+ for _kind, _tier, _detail in (
1281
+ ("shadow_fr", "opportunity", "shadow first-read followed by edit"),
1282
+ ("active_fr", "measured", "active first-read skeleton followed by edit"),
1283
+ ):
1284
+ _key = _marker_key(_kind, file_path)
1285
+ if _key is None:
1286
+ continue
1287
+ _resolve_first_read_marker(
1288
+ store, _key, FEATURE_FIRST_READ_EDIT_FOLLOWUP,
1289
+ _tier, session_id, language, _detail,
1290
+ )
1291
+
1292
+
1293
+ def _resolve_first_read_marker(
1294
+ store: "SessionStore",
1295
+ marker_key: str,
1296
+ feature: str,
1297
+ tier: str,
1298
+ session_id: str,
1299
+ language: str,
1300
+ detail: str,
1301
+ ) -> None:
1302
+ """Resolve one first-read ledger marker, emitting a follow-up event once.
1303
+
1304
+ Tier selects the cohort population: opportunity = shadow (measure-only)
1305
+ cohorts, measured = active (promoted) cohorts watched by the tripwire. The
1306
+ follow-up's command_pattern carries the marker's stored language|band so the
1307
+ tripwire can attribute the edit to the exact (language, band) cohort.
1308
+ """
1309
+ try:
1310
+ raw = store.get_meta(marker_key)
1311
+ if not raw:
1312
+ return
1313
+ try:
1314
+ data = json.loads(raw)
1315
+ except (json.JSONDecodeError, TypeError):
1316
+ # A corrupt marker would otherwise stay un-resolvable forever and
1317
+ # silently drop this file from the edit-rate numerator. Clear it.
1318
+ store.set_meta(marker_key, "")
1319
+ return
1320
+ if data.get("resolved"):
1321
+ return
1322
+ band = data.get("band")
1323
+ lang = data.get("lang") or language
1324
+ # Pack lang|band so the tripwire can recover the cohort; fall back to bare
1325
+ # lang for shadow markers (the opportunity proxy is language-agnostic).
1326
+ pattern = f"{lang}|{band}" if band else lang
1327
+ from compression_log import log_compression_event
1328
+ log_compression_event(
1329
+ feature=feature,
1330
+ session_id=session_id,
1331
+ command_pattern=pattern,
1332
+ tier=tier,
1333
+ verified=(tier == "measured"),
1334
+ # The full file was needed right after the read — a skeleton would
1335
+ # have withheld content. That is the opposite of quality-preserving.
1336
+ quality_preserved=False,
1337
+ detail=detail,
1338
+ original_tokens=0,
1339
+ compressed_tokens=0,
1340
+ )
1341
+ data["resolved"] = 1
1342
+ store.set_meta(marker_key, json.dumps(data))
1343
+ except Exception:
1344
+ pass
1345
+
1346
+
1347
+ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1348
+ """Handle a PreToolUse Read event. Caller must verify tool_name == "Read"."""
1349
+
1350
+ tool_input = hook_input.get("tool_input", {})
1351
+ raw_path = tool_input.get("file_path", "")
1352
+ if not raw_path:
1353
+ return
1354
+
1355
+ file_path = str(Path(raw_path).resolve())
1356
+ session_id = str(hook_input.get("agent_id") or hook_input.get("session_id") or "unknown")
1357
+ try:
1358
+ offset = int(tool_input.get("offset", 0) or 0)
1359
+ except (ValueError, TypeError):
1360
+ offset = 0
1361
+ try:
1362
+ limit = int(tool_input.get("limit", 0) or 0)
1363
+ except (ValueError, TypeError):
1364
+ limit = 0
1365
+ ext = Path(file_path).suffix.lower()
1366
+ language = detect_structure_language(file_path)
1367
+ save_hook_context_enabled = _hook_additional_context_saved()
1368
+
1369
+ if _is_contextignored(file_path):
1370
+ reason = f"Blocked by .contextignore: {Path(file_path).name}"
1371
+ # The read is fully denied, so the tokens that would have entered context
1372
+ # are genuinely saved (measured / realized — TO performed the prevention).
1373
+ # Estimate from file size (st_size//4), matching the redundant-read path's
1374
+ # convention. Guarded: a missing/unreadable file just records zero.
1375
+ ignore_tokens_est = 0
1376
+ try:
1377
+ ignore_tokens_est = estimate_tokens_from_bytes(os.stat(file_path).st_size)
1378
+ except OSError:
1379
+ ignore_tokens_est = 0
1380
+ _log_decision(
1381
+ "block",
1382
+ file_path,
1383
+ "contextignore",
1384
+ session_id,
1385
+ mode=mode,
1386
+ actual_substitution=False,
1387
+ eligible=False,
1388
+ language=language,
1389
+ reason_code="contextignore",
1390
+ offset=offset,
1391
+ limit=limit,
1392
+ replacement_type=None,
1393
+ file_tokens_est=ignore_tokens_est,
1394
+ replacement_tokens_est=0,
1395
+ net_saved_tokens_est=ignore_tokens_est,
1396
+ replacement_fingerprint=None,
1397
+ repeat_replacement_count=0,
1398
+ save_hook_additional_context_enabled=save_hook_context_enabled,
1399
+ )
1400
+ _log_savings_event(
1401
+ "contextignore_block",
1402
+ ignore_tokens_est,
1403
+ session_id,
1404
+ Path(file_path).name,
1405
+ )
1406
+ if not quiet:
1407
+ print(f"[Read Cache] Blocked by .contextignore: {file_path}", file=sys.stderr)
1408
+ _emit_pretool_response("deny", reason)
1409
+ return
1410
+
1411
+ if ext in BINARY_EXTENSIONS:
1412
+ # Warn about expensive binary ingestion (PDF, images, Office docs)
1413
+ try:
1414
+ binary_stat = os.stat(file_path)
1415
+ binary_size = binary_stat.st_size
1416
+ except OSError:
1417
+ return
1418
+
1419
+ finding = None
1420
+ try:
1421
+ from detectors.pdf_ingestion import detect_pdf_ingestion_inline
1422
+ finding = detect_pdf_ingestion_inline(file_path, binary_size, ext)
1423
+ except ImportError:
1424
+ pass
1425
+
1426
+ if finding:
1427
+ size_mb = binary_size / (1024 * 1024)
1428
+ context_msg = (
1429
+ f"[Token Optimizer] {Path(file_path).name} is a {ext} file "
1430
+ f"({size_mb:.1f}MB, ~{finding['savings_tokens']:,} estimated tokens). "
1431
+ f"{finding['suggestion']}"
1432
+ )
1433
+ _log_decision(
1434
+ "allow",
1435
+ file_path,
1436
+ "binary_ingestion_warning",
1437
+ session_id,
1438
+ mode=mode,
1439
+ actual_substitution=False,
1440
+ eligible=False,
1441
+ language=language,
1442
+ reason_code="binary_ingestion",
1443
+ offset=offset,
1444
+ limit=limit,
1445
+ replacement_type=None,
1446
+ file_tokens_est=finding["savings_tokens"],
1447
+ replacement_tokens_est=0,
1448
+ net_saved_tokens_est=0,
1449
+ replacement_fingerprint=None,
1450
+ repeat_replacement_count=0,
1451
+ save_hook_additional_context_enabled=save_hook_context_enabled,
1452
+ )
1453
+ if not quiet:
1454
+ print(
1455
+ f"[Read Cache] Binary ingestion warning: {file_path} "
1456
+ f"(~{finding['savings_tokens']:,} tokens)",
1457
+ file=sys.stderr,
1458
+ )
1459
+ _emit_pretool_response(None, None, context_msg)
1460
+ return
1461
+
1462
+ store = _make_store(session_id)
1463
+ if store is None:
1464
+ return
1465
+
1466
+ # U-G3: if a proactive prior-session hint surfaced this exact file to this
1467
+ # session, the agent reading it is observed evidence the hint spared an
1468
+ # exploratory search to locate it. Credit once (claim_hint_follow flips the
1469
+ # credited flag) with a conservative avoided-search estimate. Best-effort.
1470
+ try:
1471
+ if store.claim_hint_follow(file_path):
1472
+ _log_savings_event(
1473
+ "hint_followed",
1474
+ _HINT_FOLLOW_AVOIDED_TOKENS,
1475
+ session_id,
1476
+ f"hint->read: {os.path.basename(file_path)}",
1477
+ )
1478
+ except Exception:
1479
+ pass
1480
+
1481
+ # A compaction since the last Read dropped every earlier read from the
1482
+ # model's context: forget them so this Read is judged a first read.
1483
+ try:
1484
+ if _scan_for_compaction(store, hook_input.get("transcript_path")):
1485
+ store.clear_file_entries()
1486
+ if not quiet:
1487
+ print(
1488
+ f"[Read Cache] Compaction detected; cleared file_reads for {session_id}",
1489
+ file=sys.stderr,
1490
+ )
1491
+ except Exception:
1492
+ pass
1493
+
1494
+ try:
1495
+ entry = store.get_file_entry(file_path)
1496
+ except Exception:
1497
+ return
1498
+
1499
+ # F1b: tool_use_id idempotency. The host does not expose the merged hook
1500
+ # set, so double-registration from another settings layer can make the same
1501
+ # PreToolUse/Read fire twice. Without this guard, fire #1 creates the
1502
+ # file_reads entry and fire #2 denies the read as "redundant" -- even though
1503
+ # it is the same tool call and the user has never actually read the file.
1504
+ # The fix: store the tool_use_id on the entry and, on a subsequent fire with
1505
+ # the SAME tool_use_id, allow the read (it is the same call, not a reread).
1506
+ # A genuine reread has a DIFFERENT tool_use_id and is still blocked.
1507
+ current_tool_use_id = str(hook_input.get("tool_use_id", "") or "")
1508
+
1509
+ if entry is None:
1510
+ try:
1511
+ stat = os.stat(file_path)
1512
+ except OSError:
1513
+ return
1514
+
1515
+ tokens_est = estimate_tokens_from_bytes(stat.st_size)
1516
+ entry = {
1517
+ "mtime_ns": stat.st_mtime_ns,
1518
+ "size_bytes": stat.st_size,
1519
+ "ranges_seen": [[offset, limit]],
1520
+ "tokens_est": tokens_est,
1521
+ "read_count": 1,
1522
+ "last_access": time.time(),
1523
+ "last_tool_use_id": current_tool_use_id,
1524
+ }
1525
+ delta_content = None
1526
+ if _is_v5_delta_enabled() and offset == 0 and limit == 0:
1527
+ try:
1528
+ from delta_diff import is_delta_eligible, content_hash, MAX_CONTENT_CACHE_BYTES
1529
+ if is_delta_eligible(file_path):
1530
+ fc, stat = _read_text_with_stat(file_path)
1531
+ tokens_est = estimate_tokens_from_bytes(stat.st_size)
1532
+ entry["mtime_ns"] = stat.st_mtime_ns
1533
+ entry["size_bytes"] = stat.st_size
1534
+ delta_content = fc # reusable in-process even if too big to persist
1535
+ if len(fc.encode("utf-8", errors="replace")) <= MAX_CONTENT_CACHE_BYTES:
1536
+ safe_fc = _redact_for_storage(fc)
1537
+ if safe_fc is not None:
1538
+ entry["cached_content"] = safe_fc
1539
+ safe_hash = content_hash(safe_fc)
1540
+ entry["content_hash"] = safe_hash
1541
+ store.upsert_cached_content(file_path, safe_fc, safe_hash)
1542
+ except Exception:
1543
+ pass
1544
+ _reset_replacement_state(entry)
1545
+ store.upsert_file_entry(file_path, entry)
1546
+ # U5: first-read skeleton. Active cohorts serve a skeleton (returns True,
1547
+ # we stop here); others fall through to serve the full file + shadow-log.
1548
+ # Reuses content delta mode already read this turn (even when too large to
1549
+ # persist) so the file is never read twice.
1550
+ if _first_read_compress(
1551
+ file_path, stat, offset, limit, language, session_id, store, mode,
1552
+ cached_content=entry.get("cached_content") or delta_content,
1553
+ save_hook_context_enabled=save_hook_context_enabled,
1554
+ quiet=quiet,
1555
+ ):
1556
+ return
1557
+ _log_decision(
1558
+ "allow",
1559
+ file_path,
1560
+ "first_read",
1561
+ session_id,
1562
+ mode=mode,
1563
+ actual_substitution=False,
1564
+ eligible=False,
1565
+ language=language,
1566
+ reason_code="first_read",
1567
+ offset=offset,
1568
+ limit=limit,
1569
+ replacement_type=None,
1570
+ file_tokens_est=tokens_est,
1571
+ replacement_tokens_est=0,
1572
+ net_saved_tokens_est=0,
1573
+ replacement_fingerprint=None,
1574
+ repeat_replacement_count=0,
1575
+ save_hook_additional_context_enabled=save_hook_context_enabled,
1576
+ )
1577
+ return
1578
+
1579
+ _ensure_entry_defaults(entry)
1580
+
1581
+ # F1b: tool_use_id idempotency guard. If the current tool_use_id matches
1582
+ # the one stored on the entry, this is the same PreToolUse/Read firing again
1583
+ # (double-registration from another settings layer). Allow the read -- it is
1584
+ # NOT a genuine reread, and denying it would block a first-ever read as
1585
+ # "redundant" (the damage from the double-hook bug). A genuine reread has a
1586
+ # different tool_use_id and falls through to the normal redundant check.
1587
+ stored_tool_use_id = str(entry.get("last_tool_use_id", "") or "")
1588
+ if current_tool_use_id and stored_tool_use_id == current_tool_use_id:
1589
+ _log_decision(
1590
+ "allow",
1591
+ file_path,
1592
+ "same_tool_use_id",
1593
+ session_id,
1594
+ mode=mode,
1595
+ actual_substitution=False,
1596
+ eligible=False,
1597
+ language=language,
1598
+ reason_code="same_tool_use_id",
1599
+ offset=offset,
1600
+ limit=limit,
1601
+ replacement_type=None,
1602
+ file_tokens_est=int(entry.get("tokens_est", 0) or 0),
1603
+ replacement_tokens_est=0,
1604
+ net_saved_tokens_est=0,
1605
+ replacement_fingerprint=None,
1606
+ repeat_replacement_count=0,
1607
+ save_hook_additional_context_enabled=save_hook_context_enabled,
1608
+ )
1609
+ return
1610
+
1611
+ # Update the stored tool_use_id so a subsequent double-fire of THIS call
1612
+ # is also caught. This is done after the idempotency check and before the
1613
+ # redundant-read evaluation, so the entry always reflects the latest call.
1614
+ entry["last_tool_use_id"] = current_tool_use_id
1615
+
1616
+ try:
1617
+ current_stat = os.stat(file_path)
1618
+ except OSError:
1619
+ store.delete_file_entry(file_path)
1620
+ _log_decision(
1621
+ "allow",
1622
+ file_path,
1623
+ "file_deleted",
1624
+ session_id,
1625
+ mode=mode,
1626
+ actual_substitution=False,
1627
+ eligible=False,
1628
+ language=language,
1629
+ reason_code="file_deleted",
1630
+ offset=offset,
1631
+ limit=limit,
1632
+ replacement_type=None,
1633
+ file_tokens_est=entry.get("tokens_est", 0),
1634
+ replacement_tokens_est=0,
1635
+ net_saved_tokens_est=0,
1636
+ replacement_fingerprint=None,
1637
+ repeat_replacement_count=0,
1638
+ save_hook_additional_context_enabled=save_hook_context_enabled,
1639
+ )
1640
+ return
1641
+
1642
+ mtime_match = int(entry.get("mtime_ns", 0) or 0) == current_stat.st_mtime_ns
1643
+ size_match = int(entry.get("size_bytes", 0) or 0) == current_stat.st_size
1644
+
1645
+ ranges_seen = entry.get("ranges_seen", [])
1646
+ if not ranges_seen:
1647
+ old_off = int(entry.get("offset", 0) or 0)
1648
+ old_lim = int(entry.get("limit", 0) or 0)
1649
+ ranges_seen = [[old_off, old_lim]]
1650
+
1651
+ range_covered = False
1652
+ for cached_off, cached_lim in ranges_seen:
1653
+ if cached_off == 0 and cached_lim == 0:
1654
+ range_covered = True
1655
+ break
1656
+ if offset >= cached_off:
1657
+ if cached_lim == 0:
1658
+ range_covered = True
1659
+ break
1660
+ if limit > 0 and (offset + limit) <= (cached_off + cached_lim):
1661
+ range_covered = True
1662
+ break
1663
+
1664
+ if not (mtime_match and size_match and range_covered):
1665
+ # v5.0: Delta mode -- return diff instead of allowing full re-read
1666
+ delta_enabled = _is_v5_delta_enabled()
1667
+ cached_content_after_read = None
1668
+ cached_hash_after_read = None
1669
+ cache_needs_clear_after_read = False
1670
+ cached = store.get_cached_content(file_path) if delta_enabled else None
1671
+ old_content = cached.get("content") if cached else entry.get("cached_content")
1672
+ old_hash = cached.get("content_hash") if cached else entry.get("content_hash")
1673
+ if (
1674
+ delta_enabled
1675
+ and offset == 0
1676
+ and limit == 0
1677
+ and not mtime_match
1678
+ and old_hash
1679
+ and old_content
1680
+ ):
1681
+ try:
1682
+ from delta_diff import compute_delta, content_hash, is_delta_eligible, MAX_CONTENT_CACHE_BYTES
1683
+ if is_delta_eligible(file_path):
1684
+ new_content, current_stat = _read_text_with_stat(file_path)
1685
+ safe_new_content = _redact_for_storage(new_content)
1686
+ new_hash = content_hash(safe_new_content) if safe_new_content is not None else None
1687
+ if new_hash is not None and new_hash != old_hash:
1688
+ if len(safe_new_content.encode("utf-8", errors="replace")) <= MAX_CONTENT_CACHE_BYTES:
1689
+ cached_content_after_read = safe_new_content
1690
+ cached_hash_after_read = new_hash
1691
+ else:
1692
+ cache_needs_clear_after_read = True
1693
+ # A redacted snapshot cannot safely describe a raw file
1694
+ # change. Let the host perform the full read instead.
1695
+ if (
1696
+ safe_new_content != new_content
1697
+ or "[CREDENTIAL REDACTED:" in old_content
1698
+ ):
1699
+ delta_text, delta_stats = None, None
1700
+ else:
1701
+ delta_text, delta_stats = compute_delta(
1702
+ old_content, safe_new_content, Path(file_path).name
1703
+ )
1704
+ # Guard: if the diff is no smaller than the file, serving
1705
+ # it would cost MORE tokens or bytes than a full re-read.
1706
+ # Skip delta and fall through to the normal allow path.
1707
+ # Compute both counts once here; reuse the token count below.
1708
+ # Use estimate_tokens(new_content) (char-based, same units
1709
+ # as delta_tokens) rather than estimate_tokens_from_bytes
1710
+ # (byte-based) to avoid non-ASCII misfires and the
1711
+ # stat-vs-read race (current_stat was sampled before
1712
+ # new_content was read).
1713
+ old_tokens = estimate_tokens(new_content)
1714
+ if delta_text is not None:
1715
+ delta_tokens = estimate_tokens(delta_text)
1716
+ delta_bytes = len(delta_text.encode("utf-8", errors="replace"))
1717
+ new_bytes = len(new_content.encode("utf-8", errors="replace"))
1718
+ if delta_tokens >= old_tokens or delta_bytes >= new_bytes:
1719
+ delta_text = None # diff too large, fall through
1720
+ if delta_text is not None:
1721
+ entry["mtime_ns"] = current_stat.st_mtime_ns
1722
+ entry["size_bytes"] = current_stat.st_size
1723
+ entry["content_hash"] = new_hash
1724
+ entry["read_count"] = int(entry.get("read_count", 0) or 0) + 1
1725
+ entry["last_access"] = time.time()
1726
+ _reset_replacement_state(entry)
1727
+ if len(safe_new_content.encode("utf-8", errors="replace")) <= MAX_CONTENT_CACHE_BYTES:
1728
+ store.upsert_cached_content(file_path, safe_new_content, new_hash)
1729
+ cached = store.get_cached_content(file_path)
1730
+ if not cached or cached.get("content_hash") != new_hash:
1731
+ entry["content_hash"] = None
1732
+ store.delete_cached_content(file_path)
1733
+ else:
1734
+ entry["content_hash"] = None
1735
+ store.delete_cached_content(file_path)
1736
+ store.upsert_file_entry(file_path, entry)
1737
+
1738
+ net_saved = max(0, old_tokens - delta_tokens)
1739
+
1740
+ _log_decision(
1741
+ "block",
1742
+ file_path,
1743
+ f"delta_read_{entry['read_count']}",
1744
+ session_id,
1745
+ mode=mode,
1746
+ actual_substitution=True,
1747
+ eligible=True,
1748
+ language=language,
1749
+ reason_code="delta_diff",
1750
+ offset=offset,
1751
+ limit=limit,
1752
+ replacement_type="delta",
1753
+ file_tokens_est=old_tokens,
1754
+ replacement_tokens_est=delta_tokens,
1755
+ net_saved_tokens_est=net_saved,
1756
+ replacement_fingerprint=new_hash[:16],
1757
+ repeat_replacement_count=0,
1758
+ save_hook_additional_context_enabled=save_hook_context_enabled,
1759
+ )
1760
+ _log_savings_event("delta_read", net_saved, session_id,
1761
+ f"{Path(file_path).name}:+{delta_stats['added']}/-{delta_stats['removed']}")
1762
+ # Log to compression_events for v5 telemetry
1763
+ try:
1764
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
1765
+ from measure import _log_compression_event
1766
+ _log_compression_event(
1767
+ feature="delta_read",
1768
+ original_text=" " * (old_tokens * 4), # proxy
1769
+ compressed_text=delta_text,
1770
+ session_id=session_id,
1771
+ command_pattern=f"Read:{Path(file_path).name}",
1772
+ quality_preserved=True,
1773
+ verified=True,
1774
+ tier="measured", # realized: reaches headline explicitly
1775
+ detail=f"+{delta_stats['added']}/-{delta_stats['removed']}",
1776
+ )
1777
+ except Exception:
1778
+ pass
1779
+ if not quiet:
1780
+ print(
1781
+ f"[Read Cache] Delta mode: {file_path} "
1782
+ f"(+{delta_stats['added']}/-{delta_stats['removed']}, saved~{net_saved:,})",
1783
+ file=sys.stderr,
1784
+ )
1785
+ reason = (
1786
+ f"{Path(file_path).name} was edited; showing diff "
1787
+ f"(+{delta_stats['added']}/-{delta_stats['removed']} lines) "
1788
+ f"instead of full re-read."
1789
+ )
1790
+ _emit_pretool_response("deny", reason, delta_text)
1791
+ return # EXIT: delta handled, do NOT evaluate structure map
1792
+ else:
1793
+ # Hash unchanged despite mtime change (e.g., touch). Allow normal read.
1794
+ pass
1795
+ except Exception:
1796
+ pass # Fail open: fall through to normal allow
1797
+
1798
+ file_changed = not (mtime_match and size_match)
1799
+ reason_code_allow = "file_modified" if file_changed else "new_range"
1800
+ entry["mtime_ns"] = current_stat.st_mtime_ns
1801
+ entry["size_bytes"] = current_stat.st_size
1802
+ if file_changed:
1803
+ entry["ranges_seen"] = [[offset, limit]]
1804
+ else:
1805
+ ranges_seen.append([offset, limit])
1806
+ if len(ranges_seen) > 20:
1807
+ ranges_seen = ranges_seen[-20:]
1808
+ entry["ranges_seen"] = ranges_seen
1809
+ entry["tokens_est"] = estimate_tokens_from_bytes(current_stat.st_size)
1810
+ entry["read_count"] = int(entry.get("read_count", 0) or 0) + 1
1811
+ entry["last_access"] = time.time()
1812
+ if (
1813
+ delta_enabled
1814
+ and offset == 0
1815
+ and limit == 0
1816
+ and cached_content_after_read is not None
1817
+ and cached_hash_after_read is not None
1818
+ ):
1819
+ entry["cached_content"] = cached_content_after_read
1820
+ entry["content_hash"] = cached_hash_after_read
1821
+ store.upsert_cached_content(
1822
+ file_path, cached_content_after_read, cached_hash_after_read
1823
+ )
1824
+ cached = store.get_cached_content(file_path)
1825
+ if not cached or cached.get("content_hash") != cached_hash_after_read:
1826
+ entry["content_hash"] = None
1827
+ store.delete_cached_content(file_path)
1828
+ elif delta_enabled and offset == 0 and limit == 0 and cache_needs_clear_after_read:
1829
+ entry["content_hash"] = None
1830
+ store.delete_cached_content(file_path)
1831
+ elif delta_enabled and offset == 0 and limit == 0 and not entry.get("cached_content"):
1832
+ try:
1833
+ from delta_diff import is_delta_eligible, content_hash, MAX_CONTENT_CACHE_BYTES
1834
+ if is_delta_eligible(file_path):
1835
+ fc, current_stat = _read_text_with_stat(file_path)
1836
+ if len(fc.encode("utf-8", errors="replace")) <= MAX_CONTENT_CACHE_BYTES:
1837
+ safe_fc = _redact_for_storage(fc)
1838
+ if safe_fc is not None:
1839
+ entry["cached_content"] = safe_fc
1840
+ safe_hash = content_hash(safe_fc)
1841
+ entry["content_hash"] = safe_hash
1842
+ store.upsert_cached_content(file_path, safe_fc, safe_hash)
1843
+ except Exception:
1844
+ pass
1845
+ _reset_replacement_state(entry)
1846
+ store.upsert_file_entry(file_path, entry)
1847
+ _log_decision(
1848
+ "allow",
1849
+ file_path,
1850
+ reason_code_allow,
1851
+ session_id,
1852
+ mode=mode,
1853
+ actual_substitution=False,
1854
+ eligible=False,
1855
+ language=language,
1856
+ reason_code=reason_code_allow,
1857
+ offset=offset,
1858
+ limit=limit,
1859
+ replacement_type=None,
1860
+ file_tokens_est=entry.get("tokens_est", 0),
1861
+ replacement_tokens_est=0,
1862
+ net_saved_tokens_est=0,
1863
+ replacement_fingerprint=None,
1864
+ repeat_replacement_count=0,
1865
+ save_hook_additional_context_enabled=save_hook_context_enabled,
1866
+ )
1867
+ return
1868
+
1869
+ entry["read_count"] = int(entry.get("read_count", 0) or 0) + 1
1870
+ entry["last_access"] = time.time()
1871
+ tokens_est = int(entry.get("tokens_est", 0) or 0)
1872
+
1873
+ summary: Optional[StructureMapResult] = None
1874
+ reason_code = "unsupported_language"
1875
+ if is_structure_supported_file(file_path):
1876
+ summary, reason_code = _summarize_redundant_read(
1877
+ file_path,
1878
+ offset=offset,
1879
+ limit=limit,
1880
+ file_tokens_est=tokens_est,
1881
+ )
1882
+ eligible_structure = bool(summary and summary.eligible and reason_code == "ok")
1883
+
1884
+ if mode in {"shadow", "warn"} or (mode == "soft_block" and not eligible_structure):
1885
+ decision = "warn" if mode == "warn" else "allow"
1886
+ entry["last_structure_reason"] = reason_code
1887
+ entry["last_structure_confidence"] = summary.confidence if summary else 0.0
1888
+ store.upsert_file_entry(file_path, entry)
1889
+ _log_decision(
1890
+ decision,
1891
+ file_path,
1892
+ f"redundant_read_{entry['read_count']}",
1893
+ session_id,
1894
+ mode=mode,
1895
+ actual_substitution=False,
1896
+ eligible=eligible_structure,
1897
+ language=language,
1898
+ reason_code=reason_code,
1899
+ offset=offset,
1900
+ limit=limit,
1901
+ replacement_type=summary.replacement_type if summary else None,
1902
+ file_tokens_est=tokens_est,
1903
+ replacement_tokens_est=summary.replacement_tokens_est if summary else 0,
1904
+ net_saved_tokens_est=max(0, tokens_est - (summary.replacement_tokens_est if summary else 0)),
1905
+ replacement_fingerprint=summary.fingerprint if summary else None,
1906
+ repeat_replacement_count=0,
1907
+ save_hook_additional_context_enabled=save_hook_context_enabled,
1908
+ confidence=summary.confidence if summary else 0.0,
1909
+ )
1910
+ if not quiet and mode == "warn":
1911
+ print(f"[Read Cache] Redundant read allowed in warn mode: {file_path}", file=sys.stderr)
1912
+ return
1913
+
1914
+ if eligible_structure and summary is not None:
1915
+ if _check_escape_hatch(
1916
+ entry, store, file_path, session_id, mode, offset, limit,
1917
+ tokens_est, language, True, summary, save_hook_context_enabled, quiet,
1918
+ ):
1919
+ return
1920
+
1921
+ same_fingerprint = summary.fingerprint == entry.get("last_replacement_fingerprint", "")
1922
+ repeat_count = int(entry.get("repeat_replacement_count", 0) or 0) + 1 if same_fingerprint else 1
1923
+ entry["last_replacement_fingerprint"] = summary.fingerprint
1924
+ entry["last_replacement_type"] = summary.replacement_type
1925
+ entry["repeat_replacement_count"] = repeat_count
1926
+ entry["last_structure_reason"] = reason_code
1927
+ entry["last_structure_confidence"] = summary.confidence
1928
+ store.upsert_file_entry(file_path, entry)
1929
+
1930
+ if repeat_count == 1:
1931
+ replacement_tokens_est = summary.replacement_tokens_est
1932
+ additional_context = _build_structure_message(
1933
+ file_path,
1934
+ summary,
1935
+ max(0, tokens_est - summary.replacement_tokens_est),
1936
+ )
1937
+ if not _additional_context_within_cap(additional_context, save_hook_context_enabled):
1938
+ additional_context = None
1939
+ replacement_tokens_est = REASON_ONLY_TOKENS_EST
1940
+ else:
1941
+ additional_context = None
1942
+ replacement_tokens_est = REASON_ONLY_TOKENS_EST
1943
+
1944
+ net_saved_tokens_est = max(0, tokens_est - replacement_tokens_est)
1945
+ if repeat_count == 1:
1946
+ reason = (
1947
+ f"{Path(file_path).name} is unchanged and already in context; "
1948
+ f"using {summary.replacement_type} view."
1949
+ )
1950
+ else:
1951
+ reason = _build_reason_only_message(file_path)
1952
+
1953
+ _log_decision(
1954
+ "block",
1955
+ file_path,
1956
+ f"redundant_read_{entry['read_count']}",
1957
+ session_id,
1958
+ mode=mode,
1959
+ actual_substitution=True,
1960
+ eligible=True,
1961
+ language=language,
1962
+ reason_code=f"structure_map_repeat_{repeat_count}",
1963
+ offset=offset,
1964
+ limit=limit,
1965
+ replacement_type=summary.replacement_type,
1966
+ file_tokens_est=tokens_est,
1967
+ replacement_tokens_est=replacement_tokens_est,
1968
+ net_saved_tokens_est=net_saved_tokens_est,
1969
+ replacement_fingerprint=summary.fingerprint,
1970
+ repeat_replacement_count=repeat_count,
1971
+ save_hook_additional_context_enabled=save_hook_context_enabled,
1972
+ confidence=summary.confidence,
1973
+ )
1974
+ _log_savings_event(
1975
+ "structure_map",
1976
+ net_saved_tokens_est,
1977
+ session_id,
1978
+ f"{Path(file_path).name}:{summary.replacement_type}:repeat={repeat_count}",
1979
+ )
1980
+ # v5.0: Structure map beta telemetry
1981
+ if _is_v5_structure_map_beta():
1982
+ try:
1983
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
1984
+ from measure import _log_compression_event
1985
+ _log_compression_event(
1986
+ feature="structure_map",
1987
+ original_text=" " * (tokens_est * 4), # proxy
1988
+ compressed_text=summary.replacement_text if summary.replacement_text else "",
1989
+ session_id=session_id,
1990
+ command_pattern=f"Read:{Path(file_path).name}",
1991
+ quality_preserved=True,
1992
+ verified=False, # we don't know if AI would have used full file
1993
+ detail=f"type={summary.replacement_type} confidence={summary.confidence:.2f} repeat={repeat_count} lang={language}",
1994
+ )
1995
+ except Exception:
1996
+ pass
1997
+ if not quiet:
1998
+ print(
1999
+ f"[Read Cache] Blocked redundant read #{entry['read_count']}: {file_path} "
2000
+ f"(mode={mode}, replacement={summary.replacement_type}, repeat={repeat_count}, "
2001
+ f"saved~{net_saved_tokens_est:,})",
2002
+ file=sys.stderr,
2003
+ )
2004
+ _emit_pretool_response("deny", reason, additional_context)
2005
+ return
2006
+
2007
+ if mode == "block":
2008
+ if _check_escape_hatch(
2009
+ entry, store, file_path, session_id, mode, offset, limit,
2010
+ tokens_est, language, False, summary, save_hook_context_enabled, quiet,
2011
+ ):
2012
+ return
2013
+
2014
+ store.upsert_file_entry(file_path, entry)
2015
+ block_net_saved = max(0, tokens_est - REASON_ONLY_TOKENS_EST)
2016
+ _log_decision(
2017
+ "block",
2018
+ file_path,
2019
+ f"redundant_read_{entry['read_count']}",
2020
+ session_id,
2021
+ mode=mode,
2022
+ actual_substitution=False,
2023
+ eligible=False,
2024
+ language=language,
2025
+ reason_code=reason_code,
2026
+ offset=offset,
2027
+ limit=limit,
2028
+ replacement_type=None,
2029
+ file_tokens_est=tokens_est,
2030
+ replacement_tokens_est=REASON_ONLY_TOKENS_EST,
2031
+ net_saved_tokens_est=block_net_saved,
2032
+ replacement_fingerprint=None,
2033
+ repeat_replacement_count=0,
2034
+ save_hook_additional_context_enabled=save_hook_context_enabled,
2035
+ confidence=summary.confidence if summary else 0.0,
2036
+ )
2037
+ # B3: a hard block of a redundant reread (no structure-map replacement)
2038
+ # still prevents the full file from re-entering context. Credit the saved
2039
+ # tokens as a measured event, mirroring the structure_map path.
2040
+ _log_savings_event(
2041
+ "redundant_block",
2042
+ block_net_saved,
2043
+ session_id,
2044
+ f"{Path(file_path).name}:redundant_read_{entry['read_count']}",
2045
+ )
2046
+ reason = (
2047
+ f"{Path(file_path).name} is unchanged and already in context; "
2048
+ "redundant reread blocked. You can still Edit this file or Read a specific range."
2049
+ )
2050
+ _emit_pretool_response("deny", reason)
2051
+ return
2052
+
2053
+
2054
+ def handle_clear_compacted(hook_input: dict[str, Any], quiet: bool) -> None:
2055
+ """Clear ONLY the current session's file_reads after a compaction.
2056
+
2057
+ Wired to SessionStart (matcher ``compact``) via the ``--clear-compacted``
2058
+ flag, which reads ``session_id`` from the stdin hook input. Post-compaction
2059
+ the live session's read cache is stale: an unchanged file whose ``file_reads``
2060
+ row survives can be judged redundant on a re-Read even though compaction
2061
+ dropped it from context.
2062
+
2063
+ Calls ``store.clear_file_entries()`` ONLY -- never ``handle_clear``'s
2064
+ session-scoped branch, which also unlinks the decisions telemetry log
2065
+ (``_decisions_log_path``) and the legacy cache json. Routed through
2066
+ compaction, that branch would delete per-session decision/shadow telemetry
2067
+ on every compaction. ``cached_content`` is intentionally kept: the delta-read
2068
+ path is gated on the file entry existing, so clearing only ``file_reads`` is
2069
+ safe and preserves the delta baseline for an edited file.
2070
+
2071
+ Contention-safe: SessionStore connects fail-fast
2072
+ (``busy_timeout=50ms``), so under a sibling SessionStart compact-restore or
2073
+ PostToolUse archive write holding the same per-session sqlite write lock, a
2074
+ bare ``clear_file_entries()`` raised ``sqlite3.OperationalError('database is
2075
+ locked')`` BEFORE the DELETE, ``main()`` exited 0, and the silent-resurrection
2076
+ bug returned. This path raises a per-call ``busy_timeout`` (default 5000ms,
2077
+ tunable via ``TOKEN_OPTIMIZER_CLEAR_COMPACTED_BUSY_TIMEOUT``) so it waits out
2078
+ a short lock within the 10s hook budget, and wraps the clear in
2079
+ ``try/except sqlite3.OperationalError`` emitting a LOUD stderr line on
2080
+ failure instead of a silent exit-0 no-op.
2081
+ """
2082
+ session_id = str(
2083
+ hook_input.get("agent_id") or hook_input.get("session_id") or "unknown"
2084
+ )
2085
+ if not session_id or session_id == "unknown":
2086
+ # FAILED branches stay loud even under --quiet.
2087
+ print(
2088
+ "[read_cache] --clear-compacted FAILED: no session_id in hook "
2089
+ "input; live session file_reads left intact (not cleared)",
2090
+ file=sys.stderr,
2091
+ )
2092
+ return
2093
+ # Per-call busy_timeout: wait out a sibling write lock within the hook
2094
+ # budget instead of dying at the 50ms fail-fast default. Tunable for
2095
+ # environments with a different hook budget.
2096
+ try:
2097
+ busy_timeout_ms = int(
2098
+ os.environ.get(
2099
+ "TOKEN_OPTIMIZER_CLEAR_COMPACTED_BUSY_TIMEOUT", "5000"
2100
+ )
2101
+ )
2102
+ except ValueError:
2103
+ busy_timeout_ms = 5000
2104
+ store = _make_store(session_id, busy_timeout_ms=busy_timeout_ms)
2105
+ if store is None:
2106
+ # FAILED branches stay loud even under --quiet.
2107
+ print(
2108
+ "[read_cache] --clear-compacted FAILED: SessionStore unavailable; "
2109
+ f"file_reads for {session_id} left intact (not cleared)",
2110
+ file=sys.stderr,
2111
+ )
2112
+ return
2113
+ try:
2114
+ # The per-instance busy_timeout (set on the SessionStore above) is
2115
+ # honored by _connect() for BOTH the schema init and the DELETE, so the
2116
+ # clear waits out a sibling write lock within the hook budget instead
2117
+ # of dying at the 50ms fail-fast default during _init_schema.
2118
+ store.clear_file_entries()
2119
+ except sqlite3.OperationalError as exc:
2120
+ # LOUD failure: never a silent exit-0 no-op that resurrects the bug.
2121
+ print(
2122
+ f"[read_cache] --clear-compacted FAILED: {exc}; file_reads for "
2123
+ f"{session_id} left intact (not cleared)",
2124
+ file=sys.stderr,
2125
+ )
2126
+ return
2127
+ finally:
2128
+ store.close()
2129
+ if not quiet:
2130
+ print(
2131
+ f"[Read Cache] Cleared compacted session file_reads for {session_id}",
2132
+ file=sys.stderr,
2133
+ )
2134
+
2135
+
2136
+ def handle_clear(session_id: str, quiet: bool) -> None:
2137
+ """Clear read cache for a session."""
2138
+
2139
+ if session_id and session_id != "all":
2140
+ store = _make_store(session_id)
2141
+ if store is not None:
2142
+ try:
2143
+ store.clear_file_entries()
2144
+ finally:
2145
+ store.close()
2146
+ cp = _cache_path(session_id)
2147
+ if cp.exists():
2148
+ cp.unlink()
2149
+ dp = _decisions_log_path(session_id)
2150
+ if dp.exists():
2151
+ try:
2152
+ dp.unlink()
2153
+ except OSError:
2154
+ pass
2155
+ if not quiet:
2156
+ print(f"[Read Cache] Cleared cache for session {session_id}", file=sys.stderr)
2157
+ elif session_id == "all" and CACHE_DIR.exists():
2158
+ for candidate in CACHE_DIR.glob("*.json"):
2159
+ candidate.unlink()
2160
+ for candidate in CACHE_DIR.glob("*.tmp"):
2161
+ try:
2162
+ candidate.unlink()
2163
+ except OSError:
2164
+ pass
2165
+ decisions_dir = CACHE_DIR / "decisions"
2166
+ if decisions_dir.exists():
2167
+ for candidate in decisions_dir.glob("*.jsonl"):
2168
+ try:
2169
+ candidate.unlink()
2170
+ except OSError:
2171
+ pass
2172
+ deleted = cleanup_old_stores()
2173
+ if not quiet:
2174
+ extra = f", pruned {deleted} old session stores" if deleted else ""
2175
+ print(f"[Read Cache] Cleared all caches{extra}", file=sys.stderr)
2176
+
2177
+
2178
+ def handle_invalidate(hook_input: dict[str, Any], quiet: bool) -> None:
2179
+ """Invalidate cache entry when a file is edited/written."""
2180
+
2181
+ tool_name = hook_input.get("tool_name", "")
2182
+ if tool_name not in ("Edit", "Write", "MultiEdit", "NotebookEdit"):
2183
+ return
2184
+
2185
+ tool_input = hook_input.get("tool_input", {})
2186
+ raw_path = tool_input.get("file_path", "")
2187
+ if not raw_path:
2188
+ return
2189
+
2190
+ file_path = str(Path(raw_path).resolve())
2191
+ session_id = str(hook_input.get("agent_id") or hook_input.get("session_id") or "unknown")
2192
+ store = _make_store(session_id)
2193
+ if store is None:
2194
+ return
2195
+
2196
+ # U5: resolve the first-read shadow quality proxy (edit-after-shadow-read).
2197
+ _resolve_first_read_shadow_on_edit(
2198
+ file_path, detect_structure_language(file_path), session_id, store
2199
+ )
2200
+
2201
+ # Instead of deleting the cache entry on edit, UPDATE it with the
2202
+ # post-edit file state. Deleting the entry forces the next read into the
2203
+ # first-read path (full re-read, no savings) and starves delta mode of its
2204
+ # primary trigger (read -> edit -> re-read). By refreshing the entry with
2205
+ # the new mtime/size/content, the next read of an unchanged file hits the
2206
+ # structure-map path (saves tokens), and a subsequent external modification
2207
+ # triggers delta (saves tokens). Falls back to delete on any error.
2208
+ try:
2209
+ existing = store.get_file_entry(file_path)
2210
+ except Exception:
2211
+ # Storage failure: purge rather than risk serving a stale entry.
2212
+ try:
2213
+ store.delete_file_entry(file_path)
2214
+ store.delete_cached_content(file_path)
2215
+ except Exception:
2216
+ pass
2217
+ return
2218
+
2219
+ try:
2220
+ stat = os.stat(file_path)
2221
+ except OSError:
2222
+ # File removed by the edit (e.g., git checkout reverting). Purge stale.
2223
+ try:
2224
+ store.delete_file_entry(file_path)
2225
+ store.delete_cached_content(file_path)
2226
+ except Exception:
2227
+ pass
2228
+ return
2229
+
2230
+ if existing is None:
2231
+ return # never read before; first-read path will cache it
2232
+
2233
+ try:
2234
+ # Read the file content and stat the same open file, so the stored
2235
+ # metadata describes the bytes that were actually cached.
2236
+ new_fc = None
2237
+ new_hash = None
2238
+ if _is_v5_delta_enabled():
2239
+ cached = store.get_cached_content(file_path)
2240
+ if cached:
2241
+ try:
2242
+ from delta_diff import is_delta_eligible, content_hash, MAX_CONTENT_CACHE_BYTES
2243
+ if is_delta_eligible(file_path):
2244
+ fc, stat = _read_text_with_stat(file_path)
2245
+ if len(fc.encode("utf-8", errors="replace")) <= MAX_CONTENT_CACHE_BYTES:
2246
+ safe_fc = _redact_for_storage(fc)
2247
+ if safe_fc is not None:
2248
+ # Hash the SAME bytes that are persisted so a later
2249
+ # delta diff is consistent (redacted old vs new).
2250
+ new_hash = content_hash(safe_fc)
2251
+ new_fc = safe_fc
2252
+ else:
2253
+ # File grew too large to cache; drop cached content
2254
+ # but keep the metadata entry (mtime/size still
2255
+ # useful for structure-map hits on unchanged re-reads).
2256
+ existing["content_hash"] = None
2257
+ store.delete_cached_content(file_path)
2258
+ else:
2259
+ existing["content_hash"] = None
2260
+ store.delete_cached_content(file_path)
2261
+ except OSError:
2262
+ # File vanished between the first stat and the read. Purge.
2263
+ try:
2264
+ store.delete_file_entry(file_path)
2265
+ store.delete_cached_content(file_path)
2266
+ except Exception:
2267
+ pass
2268
+ return
2269
+ except Exception:
2270
+ pass
2271
+
2272
+ existing["mtime_ns"] = stat.st_mtime_ns
2273
+ existing["size_bytes"] = stat.st_size
2274
+ existing["tokens_est"] = estimate_tokens_from_bytes(stat.st_size)
2275
+ existing["ranges_seen"] = [] # content changed; old ranges are stale
2276
+ existing["last_access"] = time.time()
2277
+ _reset_replacement_state(existing)
2278
+
2279
+ if new_fc is not None and new_hash is not None:
2280
+ existing["content_hash"] = new_hash
2281
+ store.upsert_cached_content(file_path, new_fc, new_hash)
2282
+ # Verify the upsert actually persisted (it is a no-op when the
2283
+ # session DB is over its size cap). If the stored hash does not
2284
+ # match, the cached_content row is stale — drop it so a future
2285
+ # delta does not diff against the pre-edit version.
2286
+ verify = store.get_cached_content(file_path)
2287
+ if not verify or verify.get("content_hash") != new_hash:
2288
+ existing["content_hash"] = None
2289
+ store.delete_cached_content(file_path)
2290
+
2291
+ store.upsert_file_entry(file_path, existing)
2292
+ if not quiet:
2293
+ print(f"[Read Cache] Refreshed after edit: {file_path}", file=sys.stderr)
2294
+ except Exception:
2295
+ # Fallback: purge on any unexpected error so a stale entry is never
2296
+ # served.
2297
+ try:
2298
+ store.delete_file_entry(file_path)
2299
+ store.delete_cached_content(file_path)
2300
+ except Exception:
2301
+ pass
2302
+
2303
+
2304
+ def handle_stats(session_id: str) -> None:
2305
+ """Print cache stats for a session."""
2306
+
2307
+ store = _make_store(session_id)
2308
+ files = store.get_all_file_entries()
2309
+ total_reads = sum(int(entry.get("read_count", 0) or 0) for entry in files.values())
2310
+ total_tokens = sum(int(entry.get("tokens_est", 0) or 0) for entry in files.values())
2311
+
2312
+ decisions: dict[str, int] = {}
2313
+ reason_codes: dict[str, int] = {}
2314
+ replacement_types: dict[str, int] = {}
2315
+ eligible_events = 0
2316
+ repeat_replacement_events = 0
2317
+ structure_tokens_avoided = 0
2318
+
2319
+ log_path = _decisions_log_path(session_id)
2320
+ if log_path.exists():
2321
+ try:
2322
+ for line in log_path.read_text(encoding="utf-8").splitlines():
2323
+ try:
2324
+ event = json.loads(line)
2325
+ except json.JSONDecodeError:
2326
+ continue
2327
+ decision = str(event.get("decision", "") or "")
2328
+ decisions[decision] = decisions.get(decision, 0) + 1
2329
+ reason_code = str(event.get("reason_code", "") or "")
2330
+ if reason_code:
2331
+ reason_codes[reason_code] = reason_codes.get(reason_code, 0) + 1
2332
+ replacement_type = event.get("replacement_type")
2333
+ if replacement_type:
2334
+ replacement_types[str(replacement_type)] = replacement_types.get(str(replacement_type), 0) + 1
2335
+ if bool(event.get("eligible")):
2336
+ eligible_events += 1
2337
+ if int(event.get("repeat_replacement_count", 0) or 0) > 1:
2338
+ repeat_replacement_events += 1
2339
+ if bool(event.get("actual_substitution")):
2340
+ structure_tokens_avoided += int(event.get("net_saved_tokens_est", 0) or 0)
2341
+ except OSError:
2342
+ pass
2343
+
2344
+ result = {
2345
+ "session_id": session_id,
2346
+ "cached_files": len(files),
2347
+ "total_reads": total_reads,
2348
+ "total_tokens_cached": total_tokens,
2349
+ "decisions": decisions,
2350
+ "structure": {
2351
+ "eligible_events": eligible_events,
2352
+ "repeat_replacement_events": repeat_replacement_events,
2353
+ "actual_tokens_avoided": structure_tokens_avoided,
2354
+ "replacement_types": replacement_types,
2355
+ "reason_codes": reason_codes,
2356
+ },
2357
+ }
2358
+ print(json.dumps(result, indent=2))
2359
+
2360
+
2361
+ # ---------------------------------------------------------------------------
2362
+ # Opt-out detection
2363
+ # ---------------------------------------------------------------------------
2364
+
2365
+ def _is_read_cache_disabled() -> bool:
2366
+ """Check if user explicitly disabled read-cache via env var or config file."""
2367
+
2368
+ env_val = os.environ.get("TOKEN_OPTIMIZER_READ_CACHE")
2369
+ if env_val == "0":
2370
+ return True
2371
+ if env_val is None:
2372
+ user_set = False
2373
+ for config_dir in [SNAPSHOT_DIR, CACHE_DIR]:
2374
+ config_path = config_dir / "config.json"
2375
+ if config_path.exists():
2376
+ try:
2377
+ config = json.loads(config_path.read_text(encoding="utf-8"))
2378
+ if config.get("read_cache_enabled") is False:
2379
+ return True
2380
+ if "read_cache_enabled" in config:
2381
+ user_set = True
2382
+ except (json.JSONDecodeError, OSError, ValueError, AttributeError):
2383
+ pass
2384
+ # Repo-scoped layer, below the user's own config (runtime_env.project_config).
2385
+ if not user_set and project_config_value("read_cache_enabled") is False:
2386
+ return True
2387
+ return False
2388
+
2389
+
2390
+ # ---------------------------------------------------------------------------
2391
+ # Entry point
2392
+ # ---------------------------------------------------------------------------
2393
+
2394
+ def main() -> None:
2395
+ args = sys.argv[1:]
2396
+ quiet = "--quiet" in args or "-q" in args
2397
+
2398
+ if "--clear-compacted" in args:
2399
+ # SessionStart(compact) clears ONLY the current session's
2400
+ # file_reads (via stdin session_id) so a post-compaction re-Read of an
2401
+ # unchanged file is not judged redundant. Never touches the decisions
2402
+ # telemetry log or legacy cache json (unlike handle_clear's session
2403
+ # branch). Bare --clear semantics are left untouched.
2404
+ hook_input = read_stdin_hook_input(1_000_000)
2405
+ if not hook_input:
2406
+ # FAILED branches stay loud even under --quiet; --quiet only
2407
+ # suppresses success chatter. A silent exit-0 no-op resurrects the bug.
2408
+ print(
2409
+ "[read_cache] --clear-compacted FAILED: no stdin hook input; "
2410
+ "live session file_reads left intact (not cleared)",
2411
+ file=sys.stderr,
2412
+ )
2413
+ return
2414
+ handle_clear_compacted(hook_input, quiet)
2415
+ return
2416
+
2417
+ if "--clear" in args:
2418
+ session_id = "all"
2419
+ has_explicit_session = False
2420
+ for index, arg in enumerate(args):
2421
+ if arg == "--session" and index + 1 < len(args):
2422
+ session_id = args[index + 1]
2423
+ has_explicit_session = True
2424
+ # Bare --clear (no --session) defaults to "all" which wipes EVERY
2425
+ # session's file_reads cache. The PreCompact and CwdChanged hooks call
2426
+ # bare --clear, so a compact or cwd-change in one session nukes the
2427
+ # read cache of all other active sessions too. Scope it: when no
2428
+ # explicit --session is given, read stdin hook_input for the session_id
2429
+ # so only the current session is cleared. Fall back to "all" only when
2430
+ # stdin has no session_id (manual CLI use with no hook context).
2431
+ if not has_explicit_session:
2432
+ hook_input = read_stdin_hook_input(1_000_000)
2433
+ stdin_sid = str(
2434
+ hook_input.get("agent_id")
2435
+ or hook_input.get("session_id")
2436
+ or ""
2437
+ ).strip()
2438
+ if stdin_sid:
2439
+ session_id = stdin_sid
2440
+ handle_clear(session_id, quiet)
2441
+ return
2442
+
2443
+ if "--stats" in args:
2444
+ session_id = "unknown"
2445
+ for index, arg in enumerate(args):
2446
+ if arg == "--session" and index + 1 < len(args):
2447
+ session_id = args[index + 1]
2448
+ handle_stats(session_id)
2449
+ return
2450
+
2451
+ if "--invalidate" in args:
2452
+ hook_input = read_stdin_hook_input(1_000_000)
2453
+ if not hook_input:
2454
+ return
2455
+ handle_invalidate(hook_input, quiet)
2456
+ return
2457
+
2458
+ if _is_read_cache_disabled():
2459
+ return
2460
+
2461
+ mode = os.environ.get("TOKEN_OPTIMIZER_READ_CACHE_MODE", DEFAULT_MODE).lower()
2462
+ if mode not in READ_CACHE_MODES:
2463
+ mode = DEFAULT_MODE
2464
+
2465
+ hook_input = read_stdin_hook_input(1_000_000)
2466
+ if not hook_input:
2467
+ return
2468
+
2469
+ tool_name = hook_input.get("tool_name", "")
2470
+ if tool_name != "Read":
2471
+ if tool_name:
2472
+ _log_unexpected_tool(tool_name, quiet)
2473
+ return
2474
+
2475
+ # Gate under context pressure (token-saving: suppressed only at critical)
2476
+ try:
2477
+ from context_pressure import should_inject, get_pressure_level, log_suppression
2478
+ sid = hook_input.get("session_id") or ""
2479
+ if not should_inject(session_id=sid or None, priority="token-saving"):
2480
+ log_suppression("read_cache", get_pressure_level(session_id=sid or None))
2481
+ return
2482
+ except Exception:
2483
+ pass
2484
+
2485
+ handle_read(hook_input, mode, quiet)
2486
+
2487
+
2488
+ if __name__ == "__main__":
2489
+ main()