@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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 +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -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 +149 -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 +3633 -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 +141 -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 +93 -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 +379 -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 +1011 -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 +288 -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 +426 -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 +400 -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 +716 -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 +59531 -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 +1923 -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,600 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer - first-read shadow BACKFILL analyzer.
3
+
4
+ Replays existing Claude Code (and Codex) transcripts to answer the R9 promotion
5
+ question from REAL history instead of waiting weeks for live shadow data:
6
+
7
+ For large structure-supported whole-file reads, what would a skeleton have
8
+ saved, and how often did the model edit that same file SOON after reading it
9
+ (the "it needed the full file" signal)?
10
+
11
+ A transcript already contains both halves: the Read tool_result holds the file
12
+ content as it entered context, and later Edit/Write/MultiEdit tool_use blocks
13
+ name the file. So `turns_until_edit` -- impossible to know live at read time --
14
+ is directly observable in history.
15
+
16
+ Output: a per-cohort report (language x size-band) of read count, edit-within-N
17
+ rate, and average would-be skeleton ratio. With --write-cohorts it persists the
18
+ cohorts that pass the gate (edit-rate < threshold AND enough samples) to a gate
19
+ file the active first-read path consults. With --write-events it writes
20
+ opportunity-tier rows so the dashboard coverage panel reflects history.
21
+
22
+ This is an offline analysis tool, NOT a hot-path hook: it may import freely.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import argparse
28
+ import json
29
+ import os
30
+ import re
31
+ import sys
32
+ from collections import defaultdict
33
+ from pathlib import Path
34
+
35
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
36
+
37
+ from runtime_env import claude_home # noqa: E402
38
+ from structure_map import ( # noqa: E402
39
+ detect_structure_language,
40
+ is_structure_supported_file,
41
+ summarize_code_file,
42
+ )
43
+
44
+ try: # noqa: E402
45
+ from token_estimate import estimate_tokens
46
+ except Exception: # pragma: no cover
47
+ def estimate_tokens(text: str) -> int:
48
+ return max(1, len(text) // 4) if text else 0
49
+
50
+ # Gate parameters (mirrors read_cache shadow window + measure promotion gate).
51
+ MIN_BYTES = 16 * 1024
52
+ MAX_BYTES = 2 * 1024 * 1024
53
+ MIN_RATIO = 0.40
54
+ DEFAULT_EDIT_WINDOW_TURNS = 5
55
+ PROMOTION_EDIT_RATE = 0.15
56
+ PROMOTION_MIN_SAMPLES = 20
57
+ PROMOTION_MIN_SESSIONS = 5 # spread across >=N distinct sessions, not one loop
58
+
59
+ # Interpolated cohorts (F5 / T9): cohorts that graduate to active on a thin
60
+ # sample because the SAME language already passed the full gate in an ADJACENT
61
+ # size band. Mirrors read_cache._INTERPOLATED_COHORTS + measure._INTERPOLATED_
62
+ # COHORTS. The backfill ASSERTS (assert_interpolated_cohorts_supported) that each
63
+ # one's language really does have a passing adjacent band in the live report, so
64
+ # an interpolated promotion can never rest on a language that itself never passed.
65
+ _INTERPOLATED_COHORTS = frozenset({
66
+ ("typescript", "64-256KB"),
67
+ })
68
+ # Adjacency in band space (ordered): a cohort's adjacent bands are its neighbors.
69
+ _SIZE_BANDS_ORDERED = ("<16KB", "16-64KB", "64-256KB", "256KB-1MB", "1-2MB")
70
+
71
+
72
+ def _adjacent_bands(band: str):
73
+ """Return the immediately-smaller and immediately-larger band names."""
74
+ try:
75
+ i = _SIZE_BANDS_ORDERED.index(band)
76
+ except ValueError:
77
+ return ()
78
+ out = []
79
+ if i > 0:
80
+ out.append(_SIZE_BANDS_ORDERED[i - 1])
81
+ if i < len(_SIZE_BANDS_ORDERED) - 1:
82
+ out.append(_SIZE_BANDS_ORDERED[i + 1])
83
+ return tuple(out)
84
+
85
+
86
+ def assert_interpolated_cohorts_supported(report) -> list:
87
+ """F5: every interpolated cohort's language must pass in an ADJACENT band.
88
+
89
+ Scans the backfill report's cohort rows; for each interpolated cohort
90
+ (lang, band) verifies that (lang, adjacent_band) appears with
91
+ promotion_ready=True for at least one adjacent band. Returns the list of
92
+ UNSUPPORTED interpolated cohorts (empty == all supported). Callers may assert
93
+ on the empty-ness; the report carries it as `interpolated_unsupported` so the
94
+ CLI surfaces a drift without crashing a long backfill run.
95
+ """
96
+ by_cohort = {
97
+ (r["language"], r["size_band"]): r for r in report.get("cohorts", [])
98
+ }
99
+ unsupported = []
100
+ for lang, band in sorted(_INTERPOLATED_COHORTS):
101
+ ok = any(
102
+ by_cohort.get((lang, adj), {}).get("promotion_ready")
103
+ for adj in _adjacent_bands(band)
104
+ )
105
+ if not ok:
106
+ unsupported.append([lang, band])
107
+ return unsupported
108
+
109
+ _LINE_PREFIX = re.compile(r"^\d+\t")
110
+ # Claude Code's Read render is "N\t<line>" (1-indexed, no leading space). Strip
111
+ # exactly that; a leading \s* would clip the first column of legit TSV content.
112
+
113
+
114
+ def _strip_line_numbers(text: str) -> str:
115
+ out = []
116
+ for line in text.splitlines():
117
+ out.append(_LINE_PREFIX.sub("", line, count=1))
118
+ return "\n".join(out)
119
+
120
+
121
+ def _norm(path: str) -> str:
122
+ try:
123
+ return os.path.normpath(path)
124
+ except Exception:
125
+ return path
126
+
127
+
128
+ def _result_text(block: dict) -> str:
129
+ c = block.get("content")
130
+ if isinstance(c, str):
131
+ return c
132
+ if isinstance(c, list):
133
+ return "".join(x.get("text", "") for x in c if isinstance(x, dict))
134
+ return ""
135
+
136
+
137
+ def _size_band(n_bytes: int) -> str:
138
+ # MUST match read_cache._first_read_size_band.
139
+ kb = n_bytes / 1024
140
+ if kb < 16:
141
+ return "<16KB"
142
+ if kb < 64:
143
+ return "16-64KB"
144
+ if kb < 256:
145
+ return "64-256KB"
146
+ if kb < 1024:
147
+ return "256KB-1MB"
148
+ return "1-2MB"
149
+
150
+
151
+ def iter_transcripts(projects_dir: Path):
152
+ for p in projects_dir.rglob("*.jsonl"):
153
+ if p.is_file():
154
+ yield p
155
+
156
+
157
+ def replay_session(path: Path):
158
+ """Yield (kind, file_path, turn_index, payload) in transcript order.
159
+
160
+ kind is "read" (payload=reconstructed content) or "edit" (payload=None).
161
+ turn_index counts assistant messages so "turns until edit" is well-defined.
162
+ """
163
+ try:
164
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
165
+ except OSError:
166
+ return
167
+
168
+ tool_name_by_id: dict[str, str] = {}
169
+ read_path_by_id: dict[str, str] = {}
170
+ pending_reads: dict[str, tuple] = {} # tool_use_id -> (file_path, turn_index)
171
+ turn = 0
172
+
173
+ for ln in lines:
174
+ try:
175
+ ev = json.loads(ln)
176
+ except (json.JSONDecodeError, TypeError):
177
+ continue
178
+ msg = ev.get("message")
179
+ content = msg.get("content") if isinstance(msg, dict) else None
180
+ if ev.get("type") == "assistant":
181
+ turn += 1
182
+ if not isinstance(content, list):
183
+ continue
184
+ for block in content:
185
+ if not isinstance(block, dict):
186
+ continue
187
+ bt = block.get("type")
188
+ if bt == "tool_use":
189
+ name = block.get("name")
190
+ tid = block.get("id")
191
+ inp = block.get("input") or {}
192
+ if tid:
193
+ tool_name_by_id[tid] = name
194
+ if name == "Read":
195
+ # whole-file reads only (no offset/limit), matching live shadow
196
+ if inp.get("offset") or inp.get("limit"):
197
+ continue
198
+ fp = inp.get("file_path")
199
+ if fp and tid:
200
+ read_path_by_id[tid] = _norm(fp)
201
+ pending_reads[tid] = (_norm(fp), turn)
202
+ elif name in ("Edit", "Write", "MultiEdit", "NotebookEdit"):
203
+ fp = inp.get("file_path")
204
+ if fp:
205
+ yield ("edit", _norm(fp), turn, None)
206
+ elif bt == "tool_result":
207
+ tuid = block.get("tool_use_id")
208
+ if tuid in pending_reads and tool_name_by_id.get(tuid) == "Read":
209
+ fp, rturn = pending_reads.pop(tuid)
210
+ raw = _result_text(block)
211
+ if raw:
212
+ yield ("read", fp, rturn, _strip_line_numbers(raw))
213
+
214
+
215
+ def analyze(projects_dir: Path, edit_window: int, limit: int | None):
216
+ """Aggregate first-read->edit cohorts across all transcripts.
217
+
218
+ Counts only the FIRST read of each file per session — exactly the occasion
219
+ active mode would fire on. Re-reads (e.g. hooks re-reading CLAUDE.md every
220
+ session) are excluded so they cannot inflate the denominator and understate
221
+ the edit-rate. Also tracks distinct sessions per cohort for a robustness gate.
222
+ """
223
+ cohorts: dict[tuple, dict] = defaultdict(
224
+ lambda: {"reads": 0, "edited_within": 0, "edited_ever": 0,
225
+ "ratio_sum": 0.0, "would_be_tokens": 0, "sessions": set()}
226
+ )
227
+ totals = {"sessions": 0, "reads_seen": 0, "first_reads": 0, "eligible": 0,
228
+ "skipped_small": 0, "skipped_big": 0, "skipped_unsupported": 0,
229
+ "skipped_ineligible": 0}
230
+
231
+ processed = 0
232
+ for path in iter_transcripts(projects_dir):
233
+ if limit and processed >= limit:
234
+ break
235
+ # Collect this session's reads and edits in order.
236
+ reads = [] # (file_path, turn, content)
237
+ edits = [] # (file_path, turn)
238
+ for kind, fp, turn, payload in replay_session(path):
239
+ if kind == "read":
240
+ reads.append((fp, turn, payload))
241
+ else:
242
+ edits.append((fp, turn))
243
+ if not reads:
244
+ continue
245
+ totals["sessions"] += 1
246
+ processed += 1
247
+ sid = path.stem # session uuid, for distinct-session counting
248
+
249
+ edits_by_path: dict[str, list] = defaultdict(list)
250
+ for fp, turn in edits:
251
+ edits_by_path[fp].append(turn)
252
+
253
+ # First read of each file in this session only.
254
+ first_read: dict[str, tuple] = {}
255
+ for fp, rturn, content in reads:
256
+ totals["reads_seen"] += 1
257
+ if fp not in first_read:
258
+ first_read[fp] = (rturn, content)
259
+
260
+ for fp, (rturn, content) in first_read.items():
261
+ totals["first_reads"] += 1
262
+ nbytes = len(content.encode("utf-8", errors="replace"))
263
+ if nbytes < MIN_BYTES:
264
+ totals["skipped_small"] += 1
265
+ continue
266
+ if nbytes > MAX_BYTES:
267
+ totals["skipped_big"] += 1
268
+ continue
269
+ if not is_structure_supported_file(fp):
270
+ totals["skipped_unsupported"] += 1
271
+ continue
272
+ try:
273
+ result = summarize_code_file(fp, content=content, file_size_bytes=nbytes)
274
+ except Exception:
275
+ continue
276
+ if not result.eligible:
277
+ totals["skipped_ineligible"] += 1
278
+ continue
279
+ orig = int(result.file_tokens_est or estimate_tokens(content))
280
+ skel = int(result.replacement_tokens_est or 0)
281
+ if orig <= 0:
282
+ continue
283
+ ratio = 1.0 - (skel / orig)
284
+ if ratio < MIN_RATIO:
285
+ totals["skipped_ineligible"] += 1
286
+ continue
287
+
288
+ totals["eligible"] += 1
289
+ lang = detect_structure_language(fp) or "unknown"
290
+ band = _size_band(nbytes)
291
+ c = cohorts[(lang, band)]
292
+ c["reads"] += 1
293
+ c["sessions"].add(sid)
294
+ c["ratio_sum"] += ratio
295
+ c["would_be_tokens"] += (orig - skel)
296
+ later = [t for t in edits_by_path.get(fp, []) if t > rturn]
297
+ if later:
298
+ c["edited_ever"] += 1
299
+ if min(later) - rturn <= edit_window:
300
+ c["edited_within"] += 1
301
+
302
+ return cohorts, totals
303
+
304
+
305
+ def build_report(cohorts, totals, edit_window):
306
+ rows = []
307
+ for (lang, band), c in sorted(cohorts.items(), key=lambda kv: -kv[1]["reads"]):
308
+ reads = c["reads"]
309
+ n_sessions = len(c["sessions"])
310
+ edit_rate = (c["edited_within"] / reads) if reads else 0.0
311
+ avg_ratio = (c["ratio_sum"] / reads) if reads else 0.0
312
+ passes = (
313
+ reads >= PROMOTION_MIN_SAMPLES
314
+ and n_sessions >= PROMOTION_MIN_SESSIONS
315
+ and edit_rate < PROMOTION_EDIT_RATE
316
+ )
317
+ rows.append({
318
+ "language": lang,
319
+ "size_band": band,
320
+ "first_reads": reads,
321
+ "sessions": n_sessions,
322
+ "edited_within_n": c["edited_within"],
323
+ "edited_ever": c["edited_ever"],
324
+ "edit_rate_pct": round(100 * edit_rate, 1),
325
+ "avg_would_be_ratio_pct": round(100 * avg_ratio, 1),
326
+ "would_be_tokens": c["would_be_tokens"],
327
+ "promotion_ready": passes,
328
+ })
329
+ report = {
330
+ "edit_window_turns": edit_window,
331
+ "metric": "first-read-only per session",
332
+ "promotion_gate": {"edit_rate_pct": 100 * PROMOTION_EDIT_RATE,
333
+ "min_samples": PROMOTION_MIN_SAMPLES,
334
+ "min_sessions": PROMOTION_MIN_SESSIONS},
335
+ "totals": totals,
336
+ "cohorts": rows,
337
+ }
338
+ # F5: surface any interpolated cohort whose language lacks a passing adjacent
339
+ # band so the CLI/test catches an unsupported interpolation (arch invariant).
340
+ report["interpolated_unsupported"] = assert_interpolated_cohorts_supported(report)
341
+ return report
342
+
343
+
344
+ def print_report(report):
345
+ t = report["totals"]
346
+ print("\n First-read shadow BACKFILL (from real transcripts)")
347
+ print(" " + "=" * 66)
348
+ print(f" Sessions scanned: {t['sessions']:,} reads seen: {t['reads_seen']:,} "
349
+ f"first-reads: {t['first_reads']:,}")
350
+ print(f" Eligible (large, structure-supported, >={int(MIN_RATIO*100)}% win): {t['eligible']:,}")
351
+ print(f" Skipped — small: {t['skipped_small']:,} too big: {t['skipped_big']:,} "
352
+ f"unsupported: {t['skipped_unsupported']:,} low-win/ineligible: {t['skipped_ineligible']:,}")
353
+ g = report["promotion_gate"]
354
+ print(f"\n Metric: {report['metric']}")
355
+ print(f" Promotion gate: edit-rate < {g['edit_rate_pct']:.0f}% within "
356
+ f"{report['edit_window_turns']} turns AND >= {g['min_samples']} first-reads "
357
+ f"across >= {g['min_sessions']} sessions\n")
358
+ if not report["cohorts"]:
359
+ print(" No eligible cohorts found.")
360
+ return
361
+ print(f" {'language':10s} {'size':12s} {'f-reads':>7s} {'sess':>5s} {'edit%':>6s} "
362
+ f"{'ratio%':>7s} {'wouldbe tok':>12s} gate")
363
+ print(" " + "-" * 72)
364
+ for r in report["cohorts"]:
365
+ flag = ("PROMOTE" if r["promotion_ready"]
366
+ else ("hold" if r["first_reads"] >= PROMOTION_MIN_SAMPLES else "low-n"))
367
+ print(f" {r['language']:10s} {r['size_band']:12s} {r['first_reads']:>7d} "
368
+ f"{r['sessions']:>5d} {r['edit_rate_pct']:>5.1f}% {r['avg_would_be_ratio_pct']:>6.1f}% "
369
+ f"{r['would_be_tokens']:>12,} {flag}")
370
+ print()
371
+
372
+
373
+ # ---------------------------------------------------------------------------
374
+ # Agent/Task result compression backfill (WS4).
375
+ #
376
+ # Agent (sub-agent) results enter the parent context whole and are large
377
+ # (a typical 30d sample: ~1.3M tokens of Agent results). The proposed active treatment is
378
+ # a progressive-disclosure replacement: keep HEAD (first _AGENT_HEAD_CHARS) +
379
+ # TAIL (last _AGENT_TAIL_CHARS) inline plus an expand pointer, archiving the full
380
+ # result. The MIDDLE is elided. Because sub-agents often put findings in the
381
+ # middle (head = preamble, tail = usage/continuation block), the HARM PROXY is
382
+ # mandatory: how often does the parent's NEXT assistant turn quote text that
383
+ # lives in the would-be-elided middle (>=_HARM_MIN_SPAN-char verbatim span)? If
384
+ # that rate is >=15% we ship measure-only; below 15% we ship active. The data
385
+ # decides, per the configured exception rule.
386
+ # ---------------------------------------------------------------------------
387
+
388
+ # Single source of truth — import the runtime gate constants from
389
+ # archive_result (the hot-path hook that actually performs the head+tail+pointer
390
+ # treatment) so the backfill measures EXACTLY what production would gate on.
391
+ # Both now use CHAR semantics (the runtime gates on char count, not byte count),
392
+ # so the size floor name carries CHARS. Fail-open to local literals if the
393
+ # import is unavailable (e.g. a partial checkout running the backfill alone).
394
+ try:
395
+ from archive_result import (
396
+ _AGENT_RESULT_MIN_CHARS,
397
+ _AGENT_RESULT_HEAD_CHARS as _AGENT_HEAD_CHARS,
398
+ _AGENT_RESULT_TAIL_CHARS as _AGENT_TAIL_CHARS,
399
+ )
400
+ except Exception: # pragma: no cover - standalone fallback
401
+ _AGENT_RESULT_MIN_CHARS = 8 * 1024
402
+ _AGENT_HEAD_CHARS = 2000
403
+ _AGENT_TAIL_CHARS = 2000
404
+ _HARM_MIN_SPAN = 20 # min verbatim span length to count as a "quote"
405
+ _HARM_MAX_SPANS_CHECK = 400 # cap spans scanned per result (perf)
406
+
407
+
408
+ def _verbatim_overlap_in_middle(middle: str, next_text: str) -> bool:
409
+ """True iff next_text contains a >=_HARM_MIN_SPAN verbatim span from middle.
410
+
411
+ Scans candidate spans from the middle (the would-be-elided region) and checks
412
+ membership in the parent's next assistant turn. Whitespace-run starts are used
413
+ as span anchors so we test meaningful token sequences, not arbitrary offsets.
414
+ Bounded by _HARM_MAX_SPANS_CHECK for performance on large middles.
415
+ """
416
+ if not middle or not next_text or len(middle) < _HARM_MIN_SPAN:
417
+ return False
418
+ # Anchor candidate spans at word boundaries in the middle.
419
+ anchors = [0]
420
+ for m in re.finditer(r"\S{4,}", middle):
421
+ anchors.append(m.start())
422
+ if len(anchors) >= _HARM_MAX_SPANS_CHECK:
423
+ break
424
+ for start in anchors:
425
+ span = middle[start:start + _HARM_MIN_SPAN]
426
+ if len(span) < _HARM_MIN_SPAN:
427
+ continue
428
+ if span.strip() and span in next_text:
429
+ return True
430
+ return False
431
+
432
+
433
+ def replay_agent_results(path: Path):
434
+ """Yield (result_text, next_assistant_text) for EVERY Agent/Task result.
435
+
436
+ next_assistant_text is the concatenation of text blocks in the parent's NEXT
437
+ assistant message after the tool_result (the turn that acts on the result).
438
+
439
+ C3: yields every agent result regardless of size; the caller applies the
440
+ >=_AGENT_RESULT_MIN_CHARS gate so it can count the full pre-gate pool in
441
+ totals["results"]. The gate uses CHAR length (C1 — same semantics the
442
+ runtime hook gates on), not byte length.
443
+ """
444
+ try:
445
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
446
+ except OSError:
447
+ return
448
+
449
+ events = []
450
+ for ln in lines:
451
+ try:
452
+ events.append(json.loads(ln))
453
+ except (json.JSONDecodeError, TypeError):
454
+ continue
455
+
456
+ agent_ids: set[str] = set()
457
+ for idx, ev in enumerate(events):
458
+ msg = ev.get("message")
459
+ content = msg.get("content") if isinstance(msg, dict) else None
460
+ if not isinstance(content, list):
461
+ continue
462
+ for block in content:
463
+ if not isinstance(block, dict):
464
+ continue
465
+ if block.get("type") == "tool_use" and block.get("name") in ("Task", "Agent"):
466
+ if block.get("id"):
467
+ agent_ids.add(block["id"])
468
+ elif block.get("type") == "tool_result" and block.get("tool_use_id") in agent_ids:
469
+ txt = _result_text(block)
470
+ if not txt:
471
+ continue
472
+ # Find the NEXT assistant message after this event.
473
+ next_text = ""
474
+ for j in range(idx + 1, len(events)):
475
+ nmsg = events[j].get("message")
476
+ if events[j].get("type") != "assistant" or not isinstance(nmsg, dict):
477
+ continue
478
+ ncontent = nmsg.get("content")
479
+ if isinstance(ncontent, list):
480
+ next_text = "".join(
481
+ b.get("text", "") for b in ncontent
482
+ if isinstance(b, dict) and b.get("type") == "text"
483
+ )
484
+ break
485
+ yield (txt, next_text)
486
+
487
+
488
+ def analyze_agent_results(projects_dir: Path, limit: int | None):
489
+ """Aggregate the Agent-result pool + harm proxy across all transcripts."""
490
+ from token_estimate import estimate_tokens as _est
491
+ totals = {
492
+ "sessions": 0, "results": 0, "results_over_8kb": 0,
493
+ "orig_tokens": 0, "would_be_tokens": 0,
494
+ "harm_hits": 0, "harm_checked": 0,
495
+ "no_next_turn": 0,
496
+ }
497
+ processed = 0
498
+ for path in iter_transcripts(projects_dir):
499
+ if limit and processed >= limit:
500
+ break
501
+ saw = False
502
+ for result_text, next_text in replay_agent_results(path):
503
+ # Count EVERY agent result in the pool, pre-gate, so the JSON's
504
+ # "results" total is truthful (it was previously initialized but
505
+ # never incremented). The >=8KB gate decides the candidate subset.
506
+ totals["results"] += 1
507
+ if len(result_text) < _AGENT_RESULT_MIN_CHARS:
508
+ continue
509
+ saw = True
510
+ totals["results_over_8kb"] += 1
511
+ orig_tok = _est(result_text)
512
+ head = result_text[:_AGENT_HEAD_CHARS]
513
+ tail = result_text[-_AGENT_TAIL_CHARS:] if len(result_text) > _AGENT_TAIL_CHARS else ""
514
+ middle = result_text[_AGENT_HEAD_CHARS: len(result_text) - _AGENT_TAIL_CHARS]
515
+ would_be = _est(head + tail)
516
+ totals["orig_tokens"] += orig_tok
517
+ totals["would_be_tokens"] += max(0, orig_tok - would_be)
518
+ # Harm proxy: only meaningful when there IS a next turn and a middle.
519
+ if not next_text:
520
+ totals["no_next_turn"] += 1
521
+ continue
522
+ if not middle.strip():
523
+ continue
524
+ totals["harm_checked"] += 1
525
+ if _verbatim_overlap_in_middle(middle, next_text):
526
+ totals["harm_hits"] += 1
527
+ if saw:
528
+ totals["sessions"] += 1
529
+ processed += 1
530
+ return totals
531
+
532
+
533
+ def build_agent_report(totals):
534
+ checked = totals["harm_checked"]
535
+ harm_rate = (totals["harm_hits"] / checked) if checked else 0.0
536
+ return {
537
+ "metric": "agent/task result compression (head+tail+pointer)",
538
+ "head_chars": _AGENT_HEAD_CHARS,
539
+ "tail_chars": _AGENT_TAIL_CHARS,
540
+ "min_chars": _AGENT_RESULT_MIN_CHARS, # Char-semantics gate (shared)
541
+ "harm_span_min_chars": _HARM_MIN_SPAN,
542
+ "totals": totals,
543
+ "harm_rate_pct": round(100 * harm_rate, 1),
544
+ "harm_gate_pct": 100 * PROMOTION_EDIT_RATE,
545
+ "ship_active": harm_rate < PROMOTION_EDIT_RATE,
546
+ }
547
+
548
+
549
+ def print_agent_report(report):
550
+ t = report["totals"]
551
+ print("\n Agent/Task result compression BACKFILL (from real transcripts)")
552
+ print(" " + "=" * 66)
553
+ print(f" Sessions with >8KB agent results: {t['sessions']:,} "
554
+ f"results: {t['results_over_8kb']:,}")
555
+ print(f" Original tokens: {t['orig_tokens']:,} "
556
+ f"would-be saved (head+tail): {t['would_be_tokens']:,}")
557
+ print(f" Harm proxy: next-turn verbatim quote (>= {report['harm_span_min_chars']} chars) "
558
+ f"from the elided MIDDLE")
559
+ print(f" checked: {t['harm_checked']:,} hits: {t['harm_hits']:,} "
560
+ f"no-next-turn: {t['no_next_turn']:,}")
561
+ verdict = "SHIP ACTIVE" if report["ship_active"] else "MEASURE-ONLY"
562
+ print(f" harm rate: {report['harm_rate_pct']:.1f}% "
563
+ f"(gate <{report['harm_gate_pct']:.0f}% — {verdict})")
564
+ print()
565
+
566
+
567
+ def main(argv=None):
568
+ ap = argparse.ArgumentParser(description="First-read shadow backfill analyzer")
569
+ ap.add_argument("--projects-dir", default=str(claude_home() / "projects"))
570
+ ap.add_argument("--edit-window", type=int, default=DEFAULT_EDIT_WINDOW_TURNS)
571
+ ap.add_argument("--limit", type=int, default=None,
572
+ help="max sessions WITH reads to process (for a quick sample)")
573
+ ap.add_argument("--agent-results", action="store_true",
574
+ help="run the WS4 Agent/Task result compression + harm-proxy backfill")
575
+ ap.add_argument("--json", action="store_true")
576
+ args = ap.parse_args(argv)
577
+
578
+ projects_dir = Path(args.projects_dir)
579
+ if not projects_dir.exists():
580
+ print(f"[backfill] projects dir not found: {projects_dir}", file=sys.stderr)
581
+ return 1
582
+ if args.agent_results:
583
+ totals = analyze_agent_results(projects_dir, args.limit)
584
+ report = build_agent_report(totals)
585
+ if args.json:
586
+ print(json.dumps(report, indent=2))
587
+ else:
588
+ print_agent_report(report)
589
+ return 0
590
+ cohorts, totals = analyze(projects_dir, args.edit_window, args.limit)
591
+ report = build_report(cohorts, totals, args.edit_window)
592
+ if args.json:
593
+ print(json.dumps(report, indent=2))
594
+ else:
595
+ print_report(report)
596
+ return 0
597
+
598
+
599
+ if __name__ == "__main__":
600
+ raise SystemExit(main())