@alexgreensh/token-optimizer 5.13.69 → 5.13.71

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 (148) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/PRIVACY.md +4 -0
  4. package/hooks/hooks.json +11 -1
  5. package/hooks/module_runner.py +4 -1
  6. package/hooks/posttooluse_runner.py +44 -48
  7. package/hooks/sessionstart_runner.py +24 -5
  8. package/hooks/stop_runner.py +6 -6
  9. package/package.json +1 -1
  10. package/skills/token-optimizer/assets/dashboard.html +729 -767
  11. package/skills/token-optimizer/assets/savings_story.js +765 -0
  12. package/skills/token-optimizer/pricing/prices.json +1 -0
  13. package/skills/token-optimizer/references/cli-reference.md +1 -1
  14. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  15. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  16. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  17. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  18. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  19. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  20. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  21. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  22. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  23. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  24. package/skills/token-optimizer/scripts/_measure/cli.py +12 -8
  25. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  26. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  27. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  28. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  29. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +66 -0
  30. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  31. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  32. package/skills/token-optimizer/scripts/_measure/counted_cap.py +30 -0
  33. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  34. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  35. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  36. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  37. package/skills/token-optimizer/scripts/_measure/coverage_report.py +295 -0
  38. package/skills/token-optimizer/scripts/_measure/daemon.py +53 -74
  39. package/skills/token-optimizer/scripts/_measure/dashboard.py +90 -151
  40. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  41. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  42. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  43. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  44. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  45. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  46. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  47. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  48. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  49. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  50. package/skills/token-optimizer/scripts/_measure/holdout_report.py +129 -0
  51. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  52. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  53. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +260 -0
  54. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  55. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  56. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  57. package/skills/token-optimizer/scripts/_measure/lifecycle.py +54 -162
  58. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  59. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  60. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  61. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  62. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  63. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  64. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  65. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  66. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  67. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +174 -0
  68. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  69. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  70. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  71. package/skills/token-optimizer/scripts/_measure/savings.py +439 -864
  72. package/skills/token-optimizer/scripts/_measure/savings_headline.py +130 -0
  73. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  74. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  75. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  76. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  77. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  78. package/skills/token-optimizer/scripts/_measure/sessions.py +103 -196
  79. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  80. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  81. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  82. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  83. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  84. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  85. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  86. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  87. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  88. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  89. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  90. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  91. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  92. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  93. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  94. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  95. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  96. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  97. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  98. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  99. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  100. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  101. package/skills/token-optimizer/scripts/antigravity_install.py +2 -0
  102. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  103. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  104. package/skills/token-optimizer/scripts/bash_compress.py +14 -43
  105. package/skills/token-optimizer/scripts/bash_compress_hook.py +132 -2
  106. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  107. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  108. package/skills/token-optimizer/scripts/codemap.py +274 -0
  109. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  110. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  111. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  112. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  113. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  114. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  115. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  116. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  117. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  118. package/skills/token-optimizer/scripts/copilot_install.py +2 -0
  119. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  120. package/skills/token-optimizer/scripts/cursor_install.py +12 -0
  121. package/skills/token-optimizer/scripts/cursor_quality.py +16 -64
  122. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  123. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  124. package/skills/token-optimizer/scripts/devin_source.py +8 -3
  125. package/skills/token-optimizer/scripts/devin_verify.py +7 -1
  126. package/skills/token-optimizer/scripts/grok_install.py +2 -0
  127. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  128. package/skills/token-optimizer/scripts/hermes_doctor.py +9 -1
  129. package/skills/token-optimizer/scripts/hermes_install.py +7 -1
  130. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  131. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  132. package/skills/token-optimizer/scripts/holdout.py +136 -0
  133. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  134. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  135. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  136. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  137. package/skills/token-optimizer/scripts/measure.py +34 -76
  138. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  139. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  140. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  141. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  142. package/skills/token-optimizer/scripts/session_store.py +49 -99
  143. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  144. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  145. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  146. package/skills/token-optimizer/scripts/statusline.js +144 -30
  147. package/skills/token-optimizer/scripts/structural.py +25 -0
  148. package/skills/token-optimizer/scripts/structure_map.py +4 -26
@@ -0,0 +1,54 @@
1
+ """Re-inject lines a compressor must not lose (used by bash_compress.compress).
2
+
3
+ Error and warning lines come first and are never capped or evicted. The other
4
+ preserved lines (credential-bearing, distinctive tokens) follow in input order
5
+ and are capped, so a needle-dense output still compresses. Deterministic: the
6
+ order depends only on line positions, never on set iteration.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+
12
+ # Warning lines are signal the model must see, like error lines
13
+ # ("warning:", "DeprecationWarning", "1 warning in 2s").
14
+ WARNING_LINE_RE = re.compile(r"(?i)\bwarn(?:ing)?s?\b|\b[A-Za-z]+Warning\b")
15
+
16
+
17
+ def find_priority_lines(text, error_patterns):
18
+ """Indices of error and warning lines."""
19
+ out = set()
20
+ for i, line in enumerate(text.splitlines()):
21
+ if WARNING_LINE_RE.search(line) or any(p.search(line) for p in error_patterns):
22
+ out.add(i)
23
+ return out
24
+
25
+
26
+ def reinject(compressed, cleaned, preserved_lines, priority_lines, summarizer_pattern):
27
+ """Return ``compressed`` with missing preserved lines appended."""
28
+ cap = max(1, min(20, len(compressed.splitlines()) // 5))
29
+ original_lines = cleaned.splitlines()
30
+ present = set(compressed.splitlines())
31
+ appended = []
32
+ injected = 0
33
+ skipped_other = 0
34
+ for idx in sorted(priority_lines) + sorted(set(preserved_lines) - set(priority_lines)):
35
+ if idx >= len(original_lines):
36
+ continue
37
+ line = original_lines[idx]
38
+ if line in present:
39
+ continue
40
+ if idx not in priority_lines:
41
+ if summarizer_pattern and line.strip() in compressed:
42
+ continue # already carried by a summary line
43
+ if injected >= cap:
44
+ skipped_other += 1
45
+ continue
46
+ injected += 1
47
+ appended.append(line)
48
+ present.add(line)
49
+ if not appended:
50
+ return compressed
51
+ if skipped_other:
52
+ appended.append(f"... {skipped_other} more credential-bearing lines "
53
+ f"archived in full original (retrieve via expand key) ...")
54
+ return compressed + "\n" + "\n".join(appended)
@@ -160,14 +160,10 @@ def _is_first_read_active_enabled():
160
160
  # sessions / 31,885 first-reads (edit-within-5-turns metric, first-read-per-file):
161
161
  # * FULL-GATE cohorts (>=20 reads, >=5 sessions, edit-rate <15%):
162
162
  # markdown/python/typescript 16-64KB, python 64-256KB.
163
- # * INTERPOLATED cohorts: a low-sample cohort with ZERO observed edits in
164
- # history graduates when the SAME language already passed the full gate in an
165
- # ADJACENT size band. markdown 64-256KB (13 reads, 0% edits; markdown 16-64KB
166
- # passed) and typescript 64-256KB (2 reads, 0% edits; typescript 16-64KB
167
- # passed) qualify. This trades a thin sample for the strong language signal
168
- # plus the always-recoverable `expand` safety net. New languages with no
169
- # adjacent passing band (json/yaml/javascript) stay measure-only until they
170
- # accumulate enough history or are promoted via `measure.py cohorts promote`.
163
+ # * INTERPOLATED cohorts: a low-sample cohort with ZERO observed edits graduates
164
+ # when the SAME language passed the full gate in an ADJACENT size band:
165
+ # markdown and typescript 64-256KB. `expand` keeps it recoverable; json/yaml/
166
+ # javascript stay measure-only until enough history or `measure.py cohorts promote`.
171
167
  FIRST_READ_ACTIVE_COHORTS = frozenset({
172
168
  ("python", "16-64KB"),
173
169
  ("python", "64-256KB"),
@@ -696,6 +692,15 @@ def _log_decision(
696
692
  pass
697
693
 
698
694
 
695
+ def _codemap(fn: str, *args: Any, **kwargs: Any) -> Any:
696
+ """Code map hooks (codemap_reread.py). Any failure is a silent no-op (fail open)."""
697
+ try:
698
+ import codemap_reread
699
+ return getattr(codemap_reread, fn)(*args, **kwargs)
700
+ except Exception:
701
+ return None
702
+
703
+
699
704
  def _log_unexpected_tool(tool_name: str, quiet: bool = False) -> None:
700
705
  """Log when the hook is invoked for a non-Read tool (matcher bypass)."""
701
706
  log_dir = SNAPSHOT_DIR / "diagnostics"
@@ -827,22 +832,13 @@ def _extract_session_uuid_rc(session_id: Optional[str]) -> tuple:
827
832
  return None, False
828
833
 
829
834
 
830
- # Process-local: once the savings_events columns are confirmed present we skip
831
- # the per-write PRAGMA introspection. Fresh tables get all columns from the
832
- # schema; the ALTERs only matter for pre-v5.10 tables, so one verification per
833
- # process is enough. (Worst case across mixed old/new DBs in one process: a stale
834
- # skip -- acceptable for a measurement path, and executescript already creates
835
- # new tables fully-formed.)
835
+ # Process-local: savings_events columns verified once per process (the ALTERs only
836
+ # matter for pre-v5.10 tables; a stale skip is acceptable on a measurement path).
836
837
  _savings_columns_verified = False
837
838
 
838
839
 
839
840
  def _ensure_savings_columns(conn: sqlite3.Connection) -> None:
840
- """Idempotent migration: ensure model, session_uuid, and unjoinable columns exist.
841
-
842
- The shipped schema declares all three, but pre-existing tables created before
843
- v5.10 lack session_uuid and unjoinable. Runs the PRAGMA once per process, then
844
- short-circuits on subsequent calls in the hot savings-write path.
845
- """
841
+ """Idempotent migration for pre-v5.10 tables; PRAGMA runs once per process."""
846
842
  global _savings_columns_verified
847
843
  if _savings_columns_verified:
848
844
  return
@@ -870,9 +866,9 @@ def _ensure_savings_model_column(conn: sqlite3.Connection) -> None:
870
866
  _ensure_savings_columns(conn)
871
867
 
872
868
 
873
- def _log_savings_event(event_type: str, tokens_saved: int, session_id: str, detail: str) -> None:
869
+ def _log_savings_event(event_type: str, tokens_saved: int, session_id: str, detail: str) -> bool:
874
870
  if tokens_saved <= 0:
875
- return
871
+ return False
876
872
  conn: Optional[sqlite3.Connection] = None
877
873
  try:
878
874
  SNAPSHOT_DIR.mkdir(parents=True, exist_ok=True)
@@ -899,7 +895,7 @@ def _log_savings_event(event_type: str, tokens_saved: int, session_id: str, deta
899
895
  pass
900
896
  cost_saved = tokens_saved * cost_per_mtok / 1_000_000
901
897
  if _savings_columns_verified:
902
- conn.execute(
898
+ cursor = conn.execute(
903
899
  "INSERT INTO savings_events "
904
900
  "(timestamp, event_type, tokens_saved, cost_saved_usd, session_id, session_uuid, detail, model, unjoinable, origin) "
905
901
  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
@@ -910,7 +906,7 @@ def _log_savings_event(event_type: str, tokens_saved: int, session_id: str, deta
910
906
  else:
911
907
  # Column migration did not complete (locked DB): keep the event,
912
908
  # without origin, rather than lose it.
913
- conn.execute(
909
+ cursor = conn.execute(
914
910
  "INSERT INTO savings_events "
915
911
  "(timestamp, event_type, tokens_saved, cost_saved_usd, session_id, session_uuid, detail, model, unjoinable) "
916
912
  "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
@@ -918,8 +914,9 @@ def _log_savings_event(event_type: str, tokens_saved: int, session_id: str, deta
918
914
  session_id, session_uuid, detail, model, 1 if unjoinable else 0),
919
915
  )
920
916
  conn.commit()
917
+ return bool(conn.execute("SELECT 1 FROM savings_events WHERE rowid=?", (cursor.lastrowid,)).fetchone())
921
918
  except Exception:
922
- pass
919
+ return False
923
920
  finally:
924
921
  if conn is not None:
925
922
  try:
@@ -944,11 +941,8 @@ def _summarize_redundant_read(
944
941
  except OSError:
945
942
  return None, "unreadable"
946
943
 
947
- # fix-2: fail open. This runs inside the PreToolUse Read hook; an uncaught
948
- # error in summarization (e.g. a RecursionError on a pathological AST) would
949
- # crash the hook and could block the user's Read. Any failure here returns
950
- # (None, "summarize_error"), which the caller treats as not-eligible and
951
- # serves the file normally.
944
+ # fix-2: fail open. Any summarization error (e.g. RecursionError) returns
945
+ # (None, "summarize_error") and the file is served normally.
952
946
  try:
953
947
  summary = summarize_code_source(
954
948
  content,
@@ -990,6 +984,7 @@ def _first_read_compress(
990
984
  cached_content: Optional[str] = None,
991
985
  save_hook_context_enabled: bool = False,
992
986
  quiet: bool = True,
987
+ tool_use_id: str = "", parent_session_id: str = "",
993
988
  ) -> bool:
994
989
  """First-read skeleton path. Returns True iff it SERVED a skeleton
995
990
  (active mode emitted a deny+inject and the caller must stop).
@@ -1040,15 +1035,13 @@ def _first_read_compress(
1040
1035
  and cohort not in _demoted_cohorts()
1041
1036
  and result.replacement_text
1042
1037
  ):
1043
- # retarget: the Read TARGET is served full (never denied); the
1044
- # compression budget moves to PERIPHERY skeletons injected as
1045
- # additionalContext. Returns False so the caller serves the full
1046
- # target via the normal allow path. No ``first_read_skeleton`` event
1047
- # is emitted for the target, and the target-keyed ``active_fr:``
1048
- # marker is no longer armed here (periphery files carry their own,
1049
- # armed inside _inject_periphery_skeletons once U2 populates them).
1038
+ from _measure import first_read_revive
1039
+ if first_read_revive.enabled(SNAPSHOT_DIR / _TRIPWIRE_SIDECAR_NAME, language, cohort[1]):
1040
+ if first_read_revive.serve(file_path, stat, language, cohort[1], session_id, content,
1041
+ result, orig_tokens, estimate_tokens, _emit_pretool_response, SNAPSHOT_DIR, tool_use_id, _additional_context_within_cap, save_hook_context_enabled, parent_session_id):
1042
+ return True
1050
1043
  return _serve_first_read_retarget(
1051
- file_path, size, language, session_id, store, content, quiet,
1044
+ file_path, size, language, session_id, store, content, quiet, tool_use_id,
1052
1045
  )
1053
1046
 
1054
1047
  # SHADOW (cohort not yet promoted): serve full, measure the opportunity.
@@ -1085,6 +1078,11 @@ def _first_read_compress(
1085
1078
  original_tokens=orig_tokens,
1086
1079
  compressed_tokens=skel_tokens,
1087
1080
  )
1081
+ try:
1082
+ from _measure.periphery_exposure import record_control
1083
+ record_control(SNAPSHOT_DIR, session_id, tool_use_id, file_path, language, cohort[1])
1084
+ except Exception:
1085
+ pass
1088
1086
  # U5: record a tool_outputs row with source lineage so the shadow
1089
1087
  # first-read is self-identifiable from the SQLite store and joinable
1090
1088
  # to the file-archive meta. Keyed by a derived stable id so the row
@@ -1139,24 +1137,9 @@ def _inject_periphery_skeletons(
1139
1137
  store: "SessionStore",
1140
1138
  quiet: bool,
1141
1139
  target_band: str = "",
1140
+ tool_use_id: str = "",
1142
1141
  ) -> None:
1143
- """Inject bounded skeletons of periphery (one-hop) files as additionalContext.
1144
-
1145
- the Read target is served full by the caller; this hook point
1146
- adds skeletons of related files the agent would otherwise have to explore.
1147
- The reference graph is computed on-read, one hop out, and never persisted
1148
- (no DB/cache writes beyond the periphery edit-rate marker, which lives in
1149
- the existing per-session store).
1150
-
1151
- Resolves one-hop relationships for the just-read target, builds a bounded
1152
- periphery block (PageRank-ordered once U3 lands), and emits it via
1153
- ``_emit_pretool_response(None, None, block)`` only when it fits
1154
- ``_additional_context_within_cap``; otherwise the block is dropped (the
1155
- target is still served full). Periphery-keyed ``active_fr:<periphery_path>``
1156
- edit-rate markers are armed with the TARGET's lang|band so the cohort
1157
- tripwire attributes a periphery edit to the target's cohort. Fail-open:
1158
- any error drops the block.
1159
- """
1142
+ """Emit bounded periphery maps while leaving the target read unchanged."""
1160
1143
  try:
1161
1144
  from structure_map import (
1162
1145
  build_periphery_skeleton, resolve_one_hop_relationships,
@@ -1166,7 +1149,8 @@ def _inject_periphery_skeletons(
1166
1149
  related = resolve_one_hop_relationships(file_path, language, content=content)
1167
1150
  if not related:
1168
1151
  return
1169
- block = build_periphery_skeleton(related)
1152
+ shown = []
1153
+ block = build_periphery_skeleton(related, shown_paths=shown)
1170
1154
  if not block:
1171
1155
  return
1172
1156
  message = (
@@ -1178,8 +1162,11 @@ def _inject_periphery_skeletons(
1178
1162
  if not _additional_context_within_cap(text, _hook_additional_context_saved()):
1179
1163
  # Never withhold the target: drop the periphery block over the cap.
1180
1164
  return
1181
- _arm_periphery_markers(related, language, target_band, store)
1182
1165
  _emit_pretool_response(None, None, text)
1166
+ sys.stdout.flush()
1167
+ _arm_periphery_markers(shown, language, target_band, store)
1168
+ from _measure.periphery_exposure import record_exposures
1169
+ record_exposures(SNAPSHOT_DIR, session_id, tool_use_id, shown, language, target_band)
1183
1170
  except Exception:
1184
1171
  return
1185
1172
 
@@ -1192,10 +1179,7 @@ def _arm_periphery_markers(
1192
1179
  ) -> None:
1193
1180
  """Arm periphery-keyed ``active_fr:<periphery_path>`` edit-rate markers.
1194
1181
 
1195
- The marker stores the TARGET's lang|band (not the periphery file's) so the
1196
- cohort tripwire attributes a subsequent edit of a periphery file to the
1197
- target's cohort -- the signal that the periphery skeleton omitted
1198
- content the model then needed. Best-effort; never raises.
1182
+ The marker stores the target's lang|band for cohort attribution.
1199
1183
  """
1200
1184
  if store is None:
1201
1185
  return
@@ -1225,6 +1209,7 @@ def _serve_first_read_retarget(
1225
1209
  store: "SessionStore",
1226
1210
  content: str,
1227
1211
  quiet: bool,
1212
+ tool_use_id: str = "",
1228
1213
  ) -> bool:
1229
1214
  """ACTIVE mode, retargeted Returns False so the caller serves the
1230
1215
  Read TARGET in full -- the target is never replaced by a skeleton.
@@ -1244,7 +1229,7 @@ def _serve_first_read_retarget(
1244
1229
  try:
1245
1230
  _inject_periphery_skeletons(
1246
1231
  file_path, content, language, session_id, store, quiet,
1247
- target_band=_first_read_size_band(size),
1232
+ target_band=_first_read_size_band(size), tool_use_id=tool_use_id,
1248
1233
  )
1249
1234
  except Exception:
1250
1235
  pass
@@ -1344,6 +1329,17 @@ def _resolve_first_read_marker(
1344
1329
 
1345
1330
 
1346
1331
  def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1332
+ from _measure.structure_funnel import Funnel, append
1333
+ funnel = Funnel(str(hook_input.get("session_id") or ""), str(hook_input.get("agent_id") or ""),
1334
+ str(hook_input.get("tool_use_id") or ""), lambda row: append(SNAPSHOT_DIR, row))
1335
+ funnel.row["mode"] = mode if mode in READ_CACHE_MODES else "other"
1336
+ try:
1337
+ return _handle_read_impl(hook_input, mode, quiet, funnel)
1338
+ finally:
1339
+ funnel.finish()
1340
+
1341
+
1342
+ def _handle_read_impl(hook_input: dict[str, Any], mode: str, quiet: bool, funnel) -> None:
1347
1343
  """Handle a PreToolUse Read event. Caller must verify tool_name == "Read"."""
1348
1344
 
1349
1345
  tool_input = hook_input.get("tool_input", {})
@@ -1366,6 +1362,7 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1366
1362
  save_hook_context_enabled = _hook_additional_context_saved()
1367
1363
 
1368
1364
  if _is_contextignored(file_path):
1365
+ funnel.row["exit_reason"] = "contextignore"
1369
1366
  reason = f"Blocked by .contextignore: {Path(file_path).name}"
1370
1367
  # The read is fully denied, so the tokens that would have entered context
1371
1368
  # are genuinely saved (measured / realized — TO performed the prevention).
@@ -1408,6 +1405,7 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1408
1405
  return
1409
1406
 
1410
1407
  if ext in BINARY_EXTENSIONS:
1408
+ funnel.row["exit_reason"] = "binary"
1411
1409
  # Warn about expensive binary ingestion (PDF, images, Office docs)
1412
1410
  try:
1413
1411
  binary_stat = os.stat(file_path)
@@ -1458,16 +1456,13 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1458
1456
  _emit_pretool_response(None, None, context_msg)
1459
1457
  return
1460
1458
 
1459
+ _codemap("note_read", file_path)
1461
1460
  store = _make_store(session_id)
1462
1461
  if store is None:
1462
+ funnel.row["exit_reason"] = "store_unavailable"
1463
1463
  return
1464
1464
 
1465
- # U-G3: if a proactive prior-session hint surfaced this exact file to this
1466
- # session, the agent reading it is observed evidence the hint was followed.
1467
- # Whether it spared an exploratory search is counterfactual -- we see the
1468
- # read, not the search that did not happen -- so the credit is a fixed
1469
- # avoided-search ESTIMATE (claimed once: claim_hint_follow flips the flag),
1470
- # filed in the estimated tier downstream. Best-effort.
1465
+ # Hint follow-through is an estimate, not a measured avoided read.
1471
1466
  try:
1472
1467
  if store.claim_hint_follow(file_path):
1473
1468
  _log_savings_event(
@@ -1479,8 +1474,7 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1479
1474
  except Exception:
1480
1475
  pass
1481
1476
 
1482
- # A compaction since the last Read dropped every earlier read from the
1483
- # model's context: forget them so this Read is judged a first read.
1477
+ # Compaction resets the read ledger for this context.
1484
1478
  try:
1485
1479
  if _scan_for_compaction(store, hook_input.get("transcript_path")):
1486
1480
  if hook_input.get("agent_id"):
@@ -1498,25 +1492,19 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1498
1492
  except Exception:
1499
1493
  pass
1500
1494
 
1501
- # U2: snapshot the reset epoch AFTER the compaction scan above; a reset
1502
- # landing before the record write drops the guarded upsert (reset_epoch.py).
1495
+ # Snapshot after compaction so guarded writes respect the reset epoch.
1503
1496
  reset_epoch = snapshot_reset_epoch(store)
1504
1497
  try:
1505
1498
  entry = store.get_file_entry(file_path)
1506
1499
  except Exception:
1507
1500
  return
1501
+ funnel.state(entry is not None)
1508
1502
 
1509
- # F1b: tool_use_id idempotency. The host does not expose the merged hook
1510
- # set, so double-registration from another settings layer can make the same
1511
- # PreToolUse/Read fire twice. Without this guard, fire #1 creates the
1512
- # file_reads entry and fire #2 denies the read as "redundant" -- even though
1513
- # it is the same tool call and the user has never actually read the file.
1514
- # The fix: store the tool_use_id on the entry and, on a subsequent fire with
1515
- # the SAME tool_use_id, allow the read (it is the same call, not a reread).
1516
- # A genuine reread has a DIFFERENT tool_use_id and is still blocked.
1503
+ # Duplicate hook invocations for one tool use must not deny the first read.
1517
1504
  current_tool_use_id = str(hook_input.get("tool_use_id", "") or "")
1518
1505
 
1519
1506
  if entry is None:
1507
+ funnel.row["exit_reason"] = "first_read"
1520
1508
  try:
1521
1509
  stat = os.stat(file_path)
1522
1510
  except OSError:
@@ -1553,15 +1541,12 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1553
1541
  pass
1554
1542
  _reset_replacement_state(entry)
1555
1543
  store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
1556
- # U5: first-read skeleton. Active cohorts serve a skeleton (returns True,
1557
- # we stop here); others fall through to serve the full file + shadow-log.
1558
- # Reuses content delta mode already read this turn (even when too large to
1559
- # persist) so the file is never read twice.
1544
+ # Reuse cached content for the first-read decision when available.
1560
1545
  if _first_read_compress(
1561
1546
  file_path, stat, offset, limit, language, session_id, store, mode,
1562
1547
  cached_content=entry.get("cached_content") or delta_content,
1563
1548
  save_hook_context_enabled=save_hook_context_enabled,
1564
- quiet=quiet,
1549
+ quiet=quiet, tool_use_id=current_tool_use_id, parent_session_id=str(hook_input.get("session_id") or ""),
1565
1550
  ):
1566
1551
  return
1567
1552
  _log_decision(
@@ -1588,14 +1573,10 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1588
1573
 
1589
1574
  _ensure_entry_defaults(entry)
1590
1575
 
1591
- # F1b: tool_use_id idempotency guard. If the current tool_use_id matches
1592
- # the one stored on the entry, this is the same PreToolUse/Read firing again
1593
- # (double-registration from another settings layer). Allow the read -- it is
1594
- # NOT a genuine reread, and denying it would block a first-ever read as
1595
- # "redundant" (the damage from the double-hook bug). A genuine reread has a
1596
- # different tool_use_id and falls through to the normal redundant check.
1576
+ # A repeated tool-use ID is the same call, not a reread.
1597
1577
  stored_tool_use_id = str(entry.get("last_tool_use_id", "") or "")
1598
1578
  if current_tool_use_id and stored_tool_use_id == current_tool_use_id:
1579
+ funnel.row["exit_reason"] = "duplicate_tool_use"
1599
1580
  _log_decision(
1600
1581
  "allow",
1601
1582
  file_path,
@@ -1618,14 +1599,12 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1618
1599
  )
1619
1600
  return
1620
1601
 
1621
- # Update the stored tool_use_id so a subsequent double-fire of THIS call
1622
- # is also caught. This is done after the idempotency check and before the
1623
- # redundant-read evaluation, so the entry always reflects the latest call.
1624
1602
  entry["last_tool_use_id"] = current_tool_use_id
1625
1603
 
1626
1604
  try:
1627
1605
  current_stat = os.stat(file_path)
1628
1606
  except OSError:
1607
+ funnel.row["exit_reason"] = "file_unavailable"
1629
1608
  store.delete_file_entry(file_path)
1630
1609
  _log_decision(
1631
1610
  "allow",
@@ -1671,7 +1650,9 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1671
1650
  range_covered = True
1672
1651
  break
1673
1652
 
1653
+ funnel.metadata(mtime_match, size_match, range_covered)
1674
1654
  if not (mtime_match and size_match and range_covered):
1655
+ funnel.row["exit_reason"] = "metadata_or_range"
1675
1656
  # v5.0: Delta mode -- return diff instead of allowing full re-read
1676
1657
  delta_enabled = _is_v5_delta_enabled()
1677
1658
  cached_content_after_read = None
@@ -1890,8 +1871,26 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1890
1871
  file_tokens_est=tokens_est,
1891
1872
  )
1892
1873
  eligible_structure = bool(summary and summary.eligible and reason_code == "ok")
1874
+ funnel.structure(eligible_structure, reason_code)
1875
+ served = None if eligible_structure else _codemap(
1876
+ "try_outline", file_path, entry, offset=offset, limit=limit, tokens_est=tokens_est,
1877
+ reason_code=reason_code, mode=mode, mtime_ns=current_stat.st_mtime_ns,
1878
+ max_context_chars=STRICT_ADDITIONAL_CONTEXT_CHARS if save_hook_context_enabled else MAX_ADDITIONAL_CONTEXT_CHARS)
1879
+ if served: # Code map outline for an unchanged full re-read the skeleton path declined.
1880
+ funnel.row["exit_reason"] = "codemap_outline"
1881
+ store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
1882
+ _log_decision("block", file_path, f"redundant_read_{entry['read_count']}", session_id, mode=mode,
1883
+ actual_substitution=True, eligible=True, language=language, reason_code="codemap_outline",
1884
+ offset=offset, limit=limit, replacement_type="codemap_outline", file_tokens_est=tokens_est,
1885
+ replacement_tokens_est=served["outline_tokens"],
1886
+ net_saved_tokens_est=max(0, tokens_est - served["outline_tokens"]), replacement_fingerprint=None,
1887
+ repeat_replacement_count=1, save_hook_additional_context_enabled=save_hook_context_enabled)
1888
+ _codemap("record_served", file_path, tokens_est, served["outline_tokens"], session_id)
1889
+ _emit_pretool_response("deny", served["reason"], served["context"])
1890
+ return
1893
1891
 
1894
1892
  if mode in {"shadow", "warn"} or (mode == "soft_block" and not eligible_structure):
1893
+ funnel.row["exit_reason"] = "nonblocking"
1895
1894
  decision = "warn" if mode == "warn" else "allow"
1896
1895
  entry["last_structure_reason"] = reason_code
1897
1896
  entry["last_structure_confidence"] = summary.confidence if summary else 0.0
@@ -1922,6 +1921,7 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1922
1921
  return
1923
1922
 
1924
1923
  if eligible_structure and summary is not None:
1924
+ funnel.row["exit_reason"] = "structure_eligible"
1925
1925
  if _check_escape_hatch(
1926
1926
  entry, store, file_path, session_id, mode, offset, limit,
1927
1927
  tokens_est, language, True, summary, save_hook_context_enabled, quiet, reset_epoch,
@@ -1981,12 +1981,6 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
1981
1981
  save_hook_additional_context_enabled=save_hook_context_enabled,
1982
1982
  confidence=summary.confidence,
1983
1983
  )
1984
- _log_savings_event(
1985
- "structure_map",
1986
- net_saved_tokens_est,
1987
- session_id,
1988
- f"{Path(file_path).name}:{summary.replacement_type}:repeat={repeat_count}",
1989
- )
1990
1984
  # v5.0: Structure map beta telemetry
1991
1985
  if _is_v5_structure_map_beta():
1992
1986
  try:
@@ -2012,6 +2006,11 @@ def handle_read(hook_input: dict[str, Any], mode: str, quiet: bool) -> None:
2012
2006
  file=sys.stderr,
2013
2007
  )
2014
2008
  _emit_pretool_response("deny", reason, additional_context)
2009
+ sys.stdout.flush()
2010
+ funnel.row["output_emitted"] = True
2011
+ funnel.row["event_written"] = _log_savings_event(
2012
+ "structure_map", net_saved_tokens_est, session_id,
2013
+ f"{Path(file_path).name}:{summary.replacement_type}:repeat={repeat_count}")
2015
2014
  return
2016
2015
 
2017
2016
  if mode == "block":
@@ -26,15 +26,15 @@ def bump_reset_epoch(conn) -> None:
26
26
 
27
27
 
28
28
  def snapshot_reset_epoch(store: Any) -> Any:
29
- """Epoch to hand to guarded writes, or None (legacy unconditional write).
29
+ """Epoch to hand to guarded writes, or an invalid sentinel on failure.
30
30
 
31
31
  Call AFTER any compaction scan that may itself reset the session. Never
32
- raises: a store that cannot report an epoch degrades to the legacy write.
32
+ raises: a store that cannot report an epoch must not resurrect stale state.
33
33
  """
34
34
  try:
35
35
  return store.get_reset_epoch()
36
36
  except Exception:
37
- return None
37
+ return "unavailable"
38
38
 
39
39
 
40
40
  def _reset_replacement_state(entry: dict[str, Any]) -> None: