@alexgreensh/token-optimizer 5.13.68 → 5.13.70

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 (182) 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/fleet-auditor/references/fleet-systems.md +38 -0
  11. package/skills/fleet-auditor/scripts/fleet.py +63 -92
  12. package/skills/fleet-auditor/scripts/fleet_base.py +106 -0
  13. package/skills/fleet-auditor/scripts/fleet_cursor_adapter.py +376 -0
  14. package/skills/token-coach/SKILL.md +21 -23
  15. package/skills/token-dashboard/SKILL.md +5 -4
  16. package/skills/token-optimizer/SKILL.md +1 -1
  17. package/skills/token-optimizer/assets/dashboard.html +492 -551
  18. package/skills/token-optimizer/assets/savings_story.js +661 -0
  19. package/skills/token-optimizer/pricing/prices.json +1 -0
  20. package/skills/token-optimizer/references/cli-reference.md +1 -1
  21. package/skills/token-optimizer/references/cursor-workflow.md +1 -1
  22. package/skills/token-optimizer/references/implementation-playbook.md +3 -0
  23. package/skills/token-optimizer/references/phase0-setup.md +1 -1
  24. package/skills/token-optimizer/references/presentation-workflow.md +1 -1
  25. package/skills/token-optimizer/scripts/_measure/__init__.py +3 -1
  26. package/skills/token-optimizer/scripts/_measure/archive_health.py +14 -0
  27. package/skills/token-optimizer/scripts/_measure/archive_void_codex.py +163 -0
  28. package/skills/token-optimizer/scripts/_measure/archive_void_evidence.py +165 -0
  29. package/skills/token-optimizer/scripts/_measure/audit.py +27 -135
  30. package/skills/token-optimizer/scripts/_measure/baseline_provenance.py +339 -0
  31. package/skills/token-optimizer/scripts/_measure/cache_policy.py +261 -581
  32. package/skills/token-optimizer/scripts/_measure/checkpoint_direction.py +97 -0
  33. package/skills/token-optimizer/scripts/_measure/checkpoint_retention.py +20 -0
  34. package/skills/token-optimizer/scripts/_measure/cli.py +98 -8
  35. package/skills/token-optimizer/scripts/_measure/codex_quality.py +246 -0
  36. package/skills/token-optimizer/scripts/_measure/compaction_survival.py +158 -0
  37. package/skills/token-optimizer/scripts/_measure/compression_fixture_void.py +147 -0
  38. package/skills/token-optimizer/scripts/_measure/compression_scan_checkpoint.py +72 -0
  39. package/skills/token-optimizer/scripts/_measure/context_reset_marker.py +64 -0
  40. package/skills/token-optimizer/scripts/_measure/continuity.py +64 -118
  41. package/skills/token-optimizer/scripts/_measure/cost_per_message_trend.py +40 -0
  42. package/skills/token-optimizer/scripts/_measure/counted_cap.py +28 -0
  43. package/skills/token-optimizer/scripts/_measure/counted_orphans.py +190 -0
  44. package/skills/token-optimizer/scripts/_measure/counted_position.py +20 -0
  45. package/skills/token-optimizer/scripts/_measure/counted_pricing_v5.py +267 -0
  46. package/skills/token-optimizer/scripts/_measure/counted_subagents.py +371 -0
  47. package/skills/token-optimizer/scripts/_measure/coverage_report.py +285 -0
  48. package/skills/token-optimizer/scripts/_measure/daemon.py +61 -94
  49. package/skills/token-optimizer/scripts/_measure/dashboard.py +149 -187
  50. package/skills/token-optimizer/scripts/_measure/dashboard_heal_claim.py +36 -0
  51. package/skills/token-optimizer/scripts/_measure/dashboard_history.py +79 -0
  52. package/skills/token-optimizer/scripts/_measure/evidence_parallel.py +95 -0
  53. package/skills/token-optimizer/scripts/_measure/feature_health.py +256 -0
  54. package/skills/token-optimizer/scripts/_measure/file_refetch.py +250 -0
  55. package/skills/token-optimizer/scripts/_measure/first_call_context.py +216 -0
  56. package/skills/token-optimizer/scripts/_measure/first_read_outcomes.py +261 -0
  57. package/skills/token-optimizer/scripts/_measure/first_read_revive.py +137 -0
  58. package/skills/token-optimizer/scripts/_measure/fixture_context.py +65 -0
  59. package/skills/token-optimizer/scripts/_measure/headline.py +100 -0
  60. package/skills/token-optimizer/scripts/_measure/holdout_fallback.py +96 -0
  61. package/skills/token-optimizer/scripts/_measure/holdout_report.py +125 -0
  62. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +201 -0
  63. package/skills/token-optimizer/scripts/_measure/keepwarm_fork.py +140 -0
  64. package/skills/token-optimizer/scripts/_measure/keepwarm_guard.py +35 -0
  65. package/skills/token-optimizer/scripts/_measure/keepwarm_guard_server.py +85 -0
  66. package/skills/token-optimizer/scripts/_measure/keepwarm_linux.py +121 -0
  67. package/skills/token-optimizer/scripts/_measure/keepwarm_prefix.py +143 -0
  68. package/skills/token-optimizer/scripts/_measure/keepwarm_response_filter.py +84 -0
  69. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +256 -0
  70. package/skills/token-optimizer/scripts/_measure/lean_resume_receivers.py +260 -0
  71. package/skills/token-optimizer/scripts/_measure/lean_resume_threshold.py +76 -0
  72. package/skills/token-optimizer/scripts/_measure/lease_candidate_cleanup.py +82 -0
  73. package/skills/token-optimizer/scripts/_measure/lifecycle.py +59 -168
  74. package/skills/token-optimizer/scripts/_measure/mcp_archive_tripwire.py +120 -0
  75. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +178 -0
  76. package/skills/token-optimizer/scripts/_measure/mod_compaction_booking.py +276 -0
  77. package/skills/token-optimizer/scripts/_measure/mod_fresh_booking.py +105 -0
  78. package/skills/token-optimizer/scripts/_measure/output_reread.py +629 -0
  79. package/skills/token-optimizer/scripts/_measure/own_price_card.py +268 -0
  80. package/skills/token-optimizer/scripts/_measure/periphery_exposure.py +85 -0
  81. package/skills/token-optimizer/scripts/_measure/pricing.py +152 -87
  82. package/skills/token-optimizer/scripts/_measure/quality_archive.py +159 -215
  83. package/skills/token-optimizer/scripts/_measure/quality_checkpoint.py +173 -0
  84. package/skills/token-optimizer/scripts/_measure/quality_continuity.py +43 -0
  85. package/skills/token-optimizer/scripts/_measure/rework_metrics.py +194 -0
  86. package/skills/token-optimizer/scripts/_measure/routing_period.py +48 -0
  87. package/skills/token-optimizer/scripts/_measure/savings.py +451 -933
  88. package/skills/token-optimizer/scripts/_measure/savings_story.py +187 -0
  89. package/skills/token-optimizer/scripts/_measure/session_best.py +24 -0
  90. package/skills/token-optimizer/scripts/_measure/session_effect.py +557 -0
  91. package/skills/token-optimizer/scripts/_measure/session_flush_lock.py +75 -0
  92. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +220 -0
  93. package/skills/token-optimizer/scripts/_measure/sessions.py +154 -216
  94. package/skills/token-optimizer/scripts/_measure/setup_attachment_counter.py +196 -0
  95. package/skills/token-optimizer/scripts/_measure/setup_budget_monitor.py +180 -0
  96. package/skills/token-optimizer/scripts/_measure/setup_connector_ledger.py +126 -0
  97. package/skills/token-optimizer/scripts/_measure/setup_step.py +220 -0
  98. package/skills/token-optimizer/scripts/_measure/status_bar_lock.py +117 -0
  99. package/skills/token-optimizer/scripts/_measure/structural_archives.py +79 -0
  100. package/skills/token-optimizer/scripts/_measure/structural_dedupe.py +91 -0
  101. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +418 -0
  102. package/skills/token-optimizer/scripts/_measure/structural_listing.py +163 -0
  103. package/skills/token-optimizer/scripts/_measure/structural_report.py +339 -0
  104. package/skills/token-optimizer/scripts/_measure/structural_seed.py +164 -0
  105. package/skills/token-optimizer/scripts/_measure/structural_value.py +248 -0
  106. package/skills/token-optimizer/scripts/_measure/structure_funnel.py +97 -0
  107. package/skills/token-optimizer/scripts/_measure/timestamp_cache.py +11 -0
  108. package/skills/token-optimizer/scripts/_measure/token_type_split.py +29 -0
  109. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +419 -0
  110. package/skills/token-optimizer/scripts/_measure/transcript_product.py +228 -0
  111. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +279 -0
  112. package/skills/token-optimizer/scripts/_measure/trends.py +44 -185
  113. package/skills/token-optimizer/scripts/_measure/ttl_period.py +6 -0
  114. package/skills/token-optimizer/scripts/_measure/upgrade_drain_control.py +287 -0
  115. package/skills/token-optimizer/scripts/_measure/weekly_activity.py +69 -0
  116. package/skills/token-optimizer/scripts/activity_tracker.py +4 -33
  117. package/skills/token-optimizer/scripts/antigravity_install.py +6 -0
  118. package/skills/token-optimizer/scripts/archive_result.py +15 -19
  119. package/skills/token-optimizer/scripts/archive_verify.py +165 -0
  120. package/skills/token-optimizer/scripts/bash_compress.py +22 -83
  121. package/skills/token-optimizer/scripts/bash_compress_hook.py +137 -1
  122. package/skills/token-optimizer/scripts/bash_search_results.py +43 -0
  123. package/skills/token-optimizer/scripts/checkpoint_state.py +2 -2
  124. package/skills/token-optimizer/scripts/cloud_kit.py +3 -6
  125. package/skills/token-optimizer/scripts/codemap.py +274 -0
  126. package/skills/token-optimizer/scripts/codemap_hint.py +153 -0
  127. package/skills/token-optimizer/scripts/codemap_index.py +656 -0
  128. package/skills/token-optimizer/scripts/codemap_ledger.py +309 -0
  129. package/skills/token-optimizer/scripts/codemap_reread.py +161 -0
  130. package/skills/token-optimizer/scripts/codex_doctor.py +9 -1
  131. package/skills/token-optimizer/scripts/codex_log_index.py +34 -15
  132. package/skills/token-optimizer/scripts/codex_session.py +16 -216
  133. package/skills/token-optimizer/scripts/compression_backfill.py +4 -35
  134. package/skills/token-optimizer/scripts/context_intel.py +5 -3
  135. package/skills/token-optimizer/scripts/copilot_install.py +6 -0
  136. package/skills/token-optimizer/scripts/coverage_funnel.py +261 -0
  137. package/skills/token-optimizer/scripts/credential_patterns.py +4 -19
  138. package/skills/token-optimizer/scripts/credential_url_patterns.py +42 -0
  139. package/skills/token-optimizer/scripts/cursor_audit.py +723 -0
  140. package/skills/token-optimizer/scripts/cursor_bridge_checkpoint.py +213 -0
  141. package/skills/token-optimizer/scripts/cursor_bridge_payload.py +170 -0
  142. package/skills/token-optimizer/scripts/cursor_bridge_rewrite.py +106 -0
  143. package/skills/token-optimizer/scripts/cursor_bridge_rollup.py +115 -0
  144. package/skills/token-optimizer/scripts/cursor_coach.py +485 -0
  145. package/skills/token-optimizer/scripts/cursor_doctor.py +89 -9
  146. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +393 -276
  147. package/skills/token-optimizer/scripts/cursor_install.py +118 -19
  148. package/skills/token-optimizer/scripts/cursor_quality.py +457 -0
  149. package/skills/token-optimizer/scripts/cursor_read_cache.py +597 -0
  150. package/skills/token-optimizer/scripts/cursor_session.py +26 -5
  151. package/skills/token-optimizer/scripts/cursor_state.py +8 -0
  152. package/skills/token-optimizer/scripts/cursor_statusline.py +372 -0
  153. package/skills/token-optimizer/scripts/cursor_thrash.py +78 -0
  154. package/skills/token-optimizer/scripts/cursor_transcript.py +223 -0
  155. package/skills/token-optimizer/scripts/dashboard_assets.py +21 -0
  156. package/skills/token-optimizer/scripts/deterministic_candidates.py +2 -10
  157. package/skills/token-optimizer/scripts/devin_source.py +19 -4
  158. package/skills/token-optimizer/scripts/devin_verify.py +13 -6
  159. package/skills/token-optimizer/scripts/grok_install.py +6 -0
  160. package/skills/token-optimizer/scripts/heal_report.py +7 -6
  161. package/skills/token-optimizer/scripts/hermes_doctor.py +12 -1
  162. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  163. package/skills/token-optimizer/scripts/hermes_session.py +14 -136
  164. package/skills/token-optimizer/scripts/hint_paths.py +21 -0
  165. package/skills/token-optimizer/scripts/holdout.py +136 -0
  166. package/skills/token-optimizer/scripts/hook_runtime.py +1 -0
  167. package/skills/token-optimizer/scripts/hook_skip_log.py +89 -0
  168. package/skills/token-optimizer/scripts/large_transcripts.py +31 -0
  169. package/skills/token-optimizer/scripts/lean_resume_carry.py +518 -0
  170. package/skills/token-optimizer/scripts/measure.py +36 -78
  171. package/skills/token-optimizer/scripts/post_run_classify.py +349 -0
  172. package/skills/token-optimizer/scripts/preserved_reinject.py +54 -0
  173. package/skills/token-optimizer/scripts/read_cache.py +99 -100
  174. package/skills/token-optimizer/scripts/reset_epoch.py +3 -3
  175. package/skills/token-optimizer/scripts/session_store.py +49 -99
  176. package/skills/token-optimizer/scripts/session_store_guard.py +75 -0
  177. package/skills/token-optimizer/scripts/settings_backup.py +379 -0
  178. package/skills/token-optimizer/scripts/shipped_hook_templates.py +1 -0
  179. package/skills/token-optimizer/scripts/statusline.js +1 -1
  180. package/skills/token-optimizer/scripts/structural.py +25 -0
  181. package/skills/token-optimizer/scripts/structure_map.py +4 -26
  182. package/skills/token-optimizer/scripts/thrash_guard.py +10 -5
@@ -0,0 +1,250 @@
1
+ """Re-fetch metric for file content printed through the shell. Measures only.
2
+
3
+ When the generic fallback cuts the middle out of `sed -n`, `cat`, `head`,
4
+ `tail`, `nl` or `git show <rev>:<file>` output, that is file content the model
5
+ asked to see. This module answers one question from the user's own transcripts:
6
+ after such an elided result, did the same session fetch the same file range
7
+ again (a Read, or a shell print of the same file) within the next three tool
8
+ calls? It changes nothing about compression.
9
+
10
+ Decision rule, fixed before any measurement:
11
+ fewer than 200 elided events CANNOT-MEASURE
12
+ re-fetch rate above 15% MAKE-VERBATIM (these commands become lossless)
13
+ re-fetch rate below 5% MAY-WIDEN (fallback may reach prefixed forms, in shadow)
14
+ otherwise NO-CHANGE
15
+
16
+ Privacy: only counts leave this module. No path, command or output text is kept
17
+ past the comparison, and nothing is written anywhere.
18
+ """
19
+ import json
20
+ import os
21
+ import re
22
+ import shlex
23
+
24
+ WINDOW_CALLS = 3
25
+ MIN_EVENTS = 200
26
+ VERBATIM_ABOVE = 0.15
27
+ WIDEN_BELOW = 0.05
28
+
29
+ # TO's own elision line from the generic compressor (bash_compress._compress_generic).
30
+ _ELIDED = re.compile(r"(?m)^\.\.\. \d+ lines omitted(?: \(kept \d+ error/warning lines\))? \.\.\.$")
31
+ _PREFIX = re.compile(r"^\s*cd\s+(\"[^\"]*\"|'[^']*'|[^\s;&|]+)\s*(?:&&|;)\s*")
32
+ _FILE_PRINTERS = {"cat", "head", "tail", "nl", "sed"}
33
+ _NO_RANGE = None # an unknown range overlaps everything (conservative: counts as a re-fetch)
34
+
35
+
36
+ def _text(content):
37
+ if isinstance(content, str):
38
+ return content
39
+ if isinstance(content, list):
40
+ return "\n".join(b.get("text", "") for b in content
41
+ if isinstance(b, dict) and b.get("type") == "text")
42
+ return ""
43
+
44
+
45
+ def calls(path):
46
+ """Ordered tool calls of one transcript: [{name, input, cwd, text, is_error}].
47
+
48
+ ``text`` is kept for Bash results only; other tools never need it here.
49
+ """
50
+ order, by_id = [], {}
51
+ with open(path, encoding="utf-8", errors="replace") as stream:
52
+ for line in stream:
53
+ if '"tool_use"' not in line and '"tool_result"' not in line:
54
+ continue
55
+ try:
56
+ row = json.loads(line)
57
+ except ValueError:
58
+ continue
59
+ message = row.get("message") if isinstance(row, dict) else None
60
+ content = message.get("content") if isinstance(message, dict) else None
61
+ if not isinstance(content, list):
62
+ continue
63
+ cwd = row.get("cwd") if isinstance(row.get("cwd"), str) else ""
64
+ for block in content:
65
+ if not isinstance(block, dict):
66
+ continue
67
+ kind = block.get("type")
68
+ if kind == "tool_use" and block.get("id"):
69
+ entry = {"name": block.get("name"), "input": block.get("input") or {},
70
+ "cwd": cwd, "text": "", "is_error": False, "has_result": False}
71
+ order.append(entry)
72
+ by_id[block["id"]] = entry
73
+ elif kind == "tool_result":
74
+ entry = by_id.get(block.get("tool_use_id"))
75
+ if entry is not None:
76
+ entry["has_result"] = True
77
+ entry["is_error"] = bool(block.get("is_error"))
78
+ if entry["name"] == "Bash":
79
+ entry["text"] = _text(block.get("content"))
80
+ return order
81
+
82
+
83
+ def _abs(path, cwd, base):
84
+ p = os.path.expanduser(path)
85
+ if not os.path.isabs(p):
86
+ p = os.path.join(base or cwd or "", p)
87
+ return os.path.normpath(p)
88
+
89
+
90
+ def print_targets(command, cwd=""):
91
+ """For a single-stage file print, return [(key, (start, end) or None)], else [].
92
+
93
+ key is a normalized absolute path, or ``rev:path`` for `git show`. Pipelines,
94
+ redirections, substitutions and multi-statement commands return [] because
95
+ TO is not the only thing shaping their output.
96
+ """
97
+ if not isinstance(command, str):
98
+ return []
99
+ base = cwd
100
+ m = _PREFIX.match(command)
101
+ if m:
102
+ d = m.group(1).strip("'\"")
103
+ base = _abs(d, cwd, cwd)
104
+ command = command[m.end():]
105
+ if any(c in command for c in "|&;<>`$\n"):
106
+ return []
107
+ try:
108
+ tokens = shlex.split(command)
109
+ except ValueError:
110
+ return []
111
+ if not tokens:
112
+ return []
113
+ head = tokens[0]
114
+ if head == "git":
115
+ if len(tokens) == 3 and tokens[1] == "show" and ":" in tokens[2] and not tokens[2].startswith("-"):
116
+ rev, _, rel = tokens[2].partition(":")
117
+ return [(f"git:{rev}:{_abs(rel, cwd, base)}", _NO_RANGE)] if rev and rel else []
118
+ return []
119
+ if head not in _FILE_PRINTERS:
120
+ return []
121
+ rest = tokens[1:]
122
+ rng, files, i = _NO_RANGE, [], 0
123
+ if head == "sed":
124
+ script, i = None, 0
125
+ for a in rest:
126
+ if a == "-n":
127
+ continue
128
+ if a.startswith("-") and a != "-":
129
+ return [] # -i, -e, -E ... not the plain print form
130
+ if script is None:
131
+ script = a
132
+ else:
133
+ files.append(a)
134
+ mm = re.fullmatch(r"(\d+)(?:,(\d+))?p", script or "")
135
+ if not mm or not files:
136
+ return []
137
+ start = int(mm.group(1))
138
+ rng = (start, int(mm.group(2) or start))
139
+ else:
140
+ count = None
141
+ while i < len(rest):
142
+ a = rest[i]
143
+ if head in ("head", "tail") and a in ("-n", "-c", "--lines") and i + 1 < len(rest):
144
+ count = rest[i + 1] if a != "-c" else None
145
+ i += 2
146
+ elif head in ("head", "tail") and re.fullmatch(r"-\d+", a):
147
+ count = a[1:]
148
+ i += 1
149
+ elif a.startswith("-") and a != "-":
150
+ i += 1
151
+ else:
152
+ files.append(a)
153
+ i += 1
154
+ if head == "head" and not files:
155
+ return []
156
+ if head == "head":
157
+ n = int(count) if count and count.lstrip("+").isdigit() else 10
158
+ rng = (1, n)
159
+ if head in ("cat", "nl"):
160
+ rng = _NO_RANGE
161
+ if not files:
162
+ return []
163
+ return [(_abs(f, cwd, base), rng) for f in files]
164
+
165
+
166
+ def read_target(entry):
167
+ path = (entry.get("input") or {}).get("file_path")
168
+ if not isinstance(path, str) or not path:
169
+ return None
170
+ inp = entry["input"]
171
+ offset, limit = inp.get("offset"), inp.get("limit")
172
+ rng = _NO_RANGE
173
+ if isinstance(offset, int) and offset >= 1:
174
+ rng = (offset, offset + limit - 1 if isinstance(limit, int) and limit >= 1 else 10 ** 9)
175
+ elif isinstance(limit, int) and limit >= 1:
176
+ rng = (1, limit)
177
+ return _abs(path, entry.get("cwd", ""), entry.get("cwd", "")), rng
178
+
179
+
180
+ def _overlap(a, b):
181
+ if a is _NO_RANGE or b is _NO_RANGE:
182
+ return True
183
+ return a[0] <= b[1] and b[0] <= a[1]
184
+
185
+
186
+ def _follow_up_targets(entry):
187
+ if entry["name"] == "Read":
188
+ t = read_target(entry)
189
+ return [t] if t else []
190
+ if entry["name"] == "Bash":
191
+ cmd = entry["input"].get("command")
192
+ return print_targets(cmd, entry.get("cwd", ""))
193
+ return []
194
+
195
+
196
+ def scan(sequence, acc=None):
197
+ """Count elided file prints and re-fetches in one transcript's call order."""
198
+ acc = acc if acc is not None else new_counts()
199
+ for i, entry in enumerate(sequence):
200
+ if entry["name"] != "Bash" or entry["is_error"] or not _ELIDED.search(entry["text"]):
201
+ continue
202
+ targets = print_targets(entry["input"].get("command"), entry.get("cwd", ""))
203
+ if not targets:
204
+ continue
205
+ acc["events"] += 1
206
+ same_file = same_range = False
207
+ for later in sequence[i + 1:i + 1 + WINDOW_CALLS]:
208
+ for key, rng in _follow_up_targets(later):
209
+ for tkey, trng in targets:
210
+ if key == tkey:
211
+ same_file = True
212
+ if _overlap(rng, trng):
213
+ same_range = True
214
+ acc["refetched_file"] += int(same_file)
215
+ acc["refetched"] += int(same_range)
216
+ return acc
217
+
218
+
219
+ def new_counts():
220
+ return {"events": 0, "refetched": 0, "refetched_file": 0}
221
+
222
+
223
+ def verdict(events, refetched):
224
+ if events < MIN_EVENTS:
225
+ return "CANNOT-MEASURE"
226
+ rate = refetched / events
227
+ if rate > VERBATIM_ABOVE:
228
+ return "MAKE-VERBATIM"
229
+ if rate < WIDEN_BELOW:
230
+ return "MAY-WIDEN"
231
+ return "NO-CHANGE"
232
+
233
+
234
+ def summarize(acc):
235
+ events = acc["events"]
236
+ return {"events": events, "refetched": acc["refetched"], "refetched_any_range": acc["refetched_file"],
237
+ "rate": (acc["refetched"] / events) if events else None,
238
+ "rate_any_range": (acc["refetched_file"] / events) if events else None,
239
+ "window_calls": WINDOW_CALLS, "min_events": MIN_EVENTS,
240
+ "verdict": verdict(events, acc["refetched"])}
241
+
242
+
243
+ def format_lines(summary):
244
+ rate = "n/a" if summary["rate"] is None else f"{summary['rate'] * 100:.1f}%"
245
+ return [f"File content printed through the shell and cut by the generic fallback: "
246
+ f"{summary['events']:,} events.",
247
+ f"Same file range fetched again within {summary['window_calls']} calls: "
248
+ f"{summary['refetched']:,} ({rate}). Same file, any range: {summary['refetched_any_range']:,}.",
249
+ f"Verdict by the written rule (>15% verbatim, <5% may widen, under "
250
+ f"{summary['min_events']} events cannot measure): {summary['verdict']}."]
@@ -0,0 +1,216 @@
1
+ """Privacy-safe first-call context observations from parent transcripts."""
2
+ import json
3
+ import re
4
+ import sqlite3
5
+ import statistics
6
+ import threading
7
+ import time
8
+ from collections import defaultdict, OrderedDict
9
+ from functools import lru_cache
10
+ from pathlib import Path
11
+
12
+
13
+ @lru_cache(maxsize=1)
14
+ def _optimizer_commands():
15
+ """Use registered hook commands as identity evidence, not runner names."""
16
+ try:
17
+ root = json.loads((Path(__file__).resolve().parents[4] / "hooks" / "hooks.json").read_text(encoding="utf-8"))
18
+ except (OSError, ValueError, IndexError):
19
+ return frozenset()
20
+ commands, pending = set(), [root]
21
+ while pending:
22
+ item = pending.pop()
23
+ if isinstance(item, dict):
24
+ if isinstance(item.get("command"), str):
25
+ commands.add(item["command"])
26
+ pending.extend(item.values())
27
+ elif isinstance(item, list):
28
+ pending.extend(item)
29
+ return frozenset(commands)
30
+
31
+
32
+ def _text(value):
33
+ if isinstance(value, str):
34
+ return value
35
+ if isinstance(value, list):
36
+ return "\n".join(_text(item) for item in value)
37
+ if isinstance(value, dict):
38
+ return _text(value.get("text", value.get("content", "")))
39
+ return ""
40
+
41
+
42
+ def observe(rows, estimate):
43
+ """Return estimates and measured API input for the first parent call only."""
44
+ parts = defaultdict(int)
45
+ first_user = False
46
+ hook_outputs = []
47
+ for row in rows:
48
+ if row.get("isSidechain"):
49
+ continue
50
+ kind = row.get("type")
51
+ if kind == "assistant":
52
+ message = row.get("message") or {}
53
+ usage = message.get("usage") or {}
54
+ if not isinstance(usage, dict) or not usage:
55
+ continue
56
+ try:
57
+ total = sum(int(usage.get(key) or 0) for key in
58
+ ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"))
59
+ except (TypeError, ValueError):
60
+ return None
61
+ timestamp = row.get("timestamp")
62
+ if total <= 0 or not isinstance(timestamp, str) or len(timestamp) < 7:
63
+ return None
64
+ return {"month": timestamp[:7], "total": total, "components": dict(parts)}
65
+ if kind == "user" and not first_user and not row.get("isMeta"):
66
+ message = row.get("message") or {}
67
+ if isinstance(message, dict) and message.get("role") == "user":
68
+ parts["first_user"] += estimate(_text(message.get("content")))
69
+ first_user = True
70
+ if kind != "attachment":
71
+ continue
72
+ a = row.get("attachment") or {}
73
+ if not isinstance(a, dict):
74
+ continue
75
+ typ = a.get("type")
76
+ if typ == "hook_success":
77
+ command = str(a.get("command") or "")
78
+ if command in _optimizer_commands() or any(name in command.lower() for name in ("token-optimizer", "token_optimizer")):
79
+ try:
80
+ output = json.loads(a.get("stdout") or "{}")
81
+ context = (output.get("hookSpecificOutput") or {}).get("additionalContext")
82
+ if isinstance(context, str) and context:
83
+ hook_outputs.append((a.get("hookEvent"), context))
84
+ except (ValueError, TypeError, AttributeError):
85
+ pass
86
+ mapping = {"skill_listing": ("skills", "content"),
87
+ "deferred_tools_delta": ("mcp_tools", "addedLines"),
88
+ "mcp_instructions_delta": ("mcp_instructions", "addedBlocks"),
89
+ "agent_listing_delta": ("agents", "addedLines")}
90
+ if typ in mapping:
91
+ name, field = mapping[typ]
92
+ parts[name] += estimate(_text(a.get(field)))
93
+ if typ == "deferred_tools_delta":
94
+ parts[name] += sum(estimate(_text(item.get("definition"))) for item in a.get("surfacedDefinitions") or [] if isinstance(item, dict))
95
+ elif typ == "instructions":
96
+ for item in a.get("files") or []:
97
+ if isinstance(item, dict):
98
+ path = str(item.get("path") or "").replace("\\", "/").lower()
99
+ kind = str(item.get("type") or "").lower()
100
+ if path.endswith("/claude.md") or path == "claude.md":
101
+ name = "claude_md"
102
+ elif "/memory/" in path or path.endswith("/memory.md") or kind == "memory":
103
+ name = "memory_files"
104
+ else:
105
+ name = "other_instructions"
106
+ parts[name] += estimate(_text(item.get("content")))
107
+ elif typ == "hook_additional_context":
108
+ event = a.get("hookEvent")
109
+ if event in ("SessionStart", "UserPromptSubmit"):
110
+ content = _text(a.get("content"))
111
+ for item in hook_outputs[:]:
112
+ if item[0] == event and item[1] in content:
113
+ parts[event + "_token_optimizer"] += estimate(item[1])
114
+ content = content.replace(item[1], "", 1)
115
+ hook_outputs.remove(item)
116
+ parts[event + "_other_or_unknown"] += estimate(content)
117
+ return None
118
+
119
+
120
+ def _quantile(values, fraction):
121
+ values = sorted(values)
122
+ index = (len(values) - 1) * fraction
123
+ lo = int(index)
124
+ hi = min(lo + 1, len(values) - 1)
125
+ return round(values[lo] + (values[hi] - values[lo]) * (index - lo))
126
+
127
+
128
+ def summarize(observations):
129
+ groups = defaultdict(list)
130
+ for row in observations:
131
+ if row:
132
+ groups[row["month"]].append(row)
133
+ result = []
134
+ for month, rows in sorted(groups.items()):
135
+ totals = [row["total"] for row in rows]
136
+ names = set().union(*(row["components"] for row in rows))
137
+ components = {}
138
+ for name in sorted(names):
139
+ found = [row["components"][name] for row in rows if name in row["components"]]
140
+ components[name] = {"median": round(statistics.median(found)), "observed": len(found)}
141
+ result.append({"month": month, "n": len(rows), "median": round(statistics.median(totals)),
142
+ "p25": _quantile(totals, .25), "p75": _quantile(totals, .75),
143
+ "components": components})
144
+ return result
145
+
146
+
147
+ _RELEVANT_TYPE = re.compile(r'"type"\s*:\s*"(?:assistant|user|attachment)"')
148
+
149
+
150
+ def transcript(path):
151
+ with open(path, encoding="utf-8", errors="replace") as stream:
152
+ for line in stream:
153
+ if '\\u' not in line and not _RELEVANT_TYPE.search(line):
154
+ continue
155
+ try:
156
+ row = json.loads(line)
157
+ except ValueError:
158
+ continue
159
+ if isinstance(row, dict):
160
+ yield row
161
+
162
+
163
+ _cache = OrderedDict()
164
+ _cache_lock = threading.Lock()
165
+
166
+
167
+ def collect(db_path, data_dir):
168
+ """Share a scan for one minute after it finishes, even if it ran slowly."""
169
+ key = (str(db_path), str(data_dir))
170
+ with _cache_lock:
171
+ entry = _cache.get(key)
172
+ if entry and time.monotonic() - entry[0] < 60:
173
+ _cache.move_to_end(key)
174
+ return entry[1]
175
+ value = _collect_uncached(*key)
176
+ _cache[key] = (time.monotonic(), value)
177
+ _cache.move_to_end(key)
178
+ while len(_cache) > 4:
179
+ _cache.popitem(last=False)
180
+ return value
181
+
182
+
183
+ def _collect_uncached(db_path, data_dir):
184
+ from . import structural_ledger
185
+ db_path = Path(db_path)
186
+ if not db_path.is_file():
187
+ return {"months": [], "trim_dates": [], "missing": 0}
188
+ observations, missing, seen = [], 0, set()
189
+ try:
190
+ with sqlite3.connect(db_path.resolve().as_uri() + "?mode=ro", uri=True) as conn:
191
+ paths = conn.execute("SELECT DISTINCT jsonl_path FROM session_log WHERE jsonl_path IS NOT NULL AND COALESCE(is_sidechain,0)=0").fetchall()
192
+ files = []
193
+ for (name,) in paths:
194
+ path = Path(name)
195
+ if path in seen:
196
+ continue
197
+ seen.add(path)
198
+ try:
199
+ files.append((str(path), path.stat()))
200
+ except (OSError, ValueError, TypeError):
201
+ missing += 1
202
+ from . import evidence_parallel
203
+ if len(files) >= 256 and evidence_parallel.safe_entrypoint():
204
+ batches = evidence_parallel.batches(files, None, 8 * 1024 * 1024, evidence_parallel.first_call)
205
+ else:
206
+ batches = ([((path, stat), evidence_parallel.first_call(path))] for path, stat in files)
207
+ for batch in batches:
208
+ for _, (item, failed) in batch:
209
+ missing += int(failed)
210
+ if item:
211
+ observations.append(item)
212
+ dates = sorted({str(t.get("ts"))[:10] for t in structural_ledger.load_trims(data_dir)
213
+ if t.get("ts") and int(t.get("tokens") or 0) > 0})
214
+ return {"months": summarize(observations), "trim_dates": dates, "missing": missing}
215
+ except (sqlite3.Error, OSError, ValueError, TypeError):
216
+ return {"months": [], "trim_dates": [], "missing": missing}