@alexgreensh/token-optimizer 5.13.75 → 5.13.76

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 (84) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/module_runner.py +1 -1
  4. package/hooks/posttooluse_runner.py +7 -9
  5. package/hooks/run.py +5 -1
  6. package/hooks/stop_runner.py +15 -56
  7. package/hooks/userpromptsubmit_runner.py +29 -4
  8. package/package.json +1 -1
  9. package/skills/token-optimizer/assets/dashboard.html +30 -14
  10. package/skills/token-optimizer/assets/savings_story.js +103 -27
  11. package/skills/token-optimizer/references/agent-prompts.md +2 -0
  12. package/skills/token-optimizer/references/implementation-playbook.md +1 -0
  13. package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
  14. package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
  15. package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
  16. package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
  17. package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
  18. package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
  19. package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
  20. package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
  21. package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
  22. package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
  23. package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
  24. package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
  25. package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
  26. package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
  27. package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
  28. package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
  29. package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
  30. package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
  31. package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
  32. package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
  33. package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
  34. package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
  35. package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
  36. package/skills/token-optimizer/scripts/_measure/savings.py +75 -81
  37. package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
  38. package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
  39. package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
  40. package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
  41. package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
  42. package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
  43. package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
  44. package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
  45. package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
  46. package/skills/token-optimizer/scripts/archive_result.py +16 -28
  47. package/skills/token-optimizer/scripts/archive_verify.py +1 -1
  48. package/skills/token-optimizer/scripts/bash_compress.py +156 -176
  49. package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
  50. package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
  51. package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
  52. package/skills/token-optimizer/scripts/benchmark.py +11 -13
  53. package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
  54. package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
  55. package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
  56. package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
  57. package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
  58. package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
  59. package/skills/token-optimizer/scripts/compact_markers.py +129 -0
  60. package/skills/token-optimizer/scripts/copilot_install.py +3 -0
  61. package/skills/token-optimizer/scripts/cursor_install.py +7 -0
  62. package/skills/token-optimizer/scripts/devin_source.py +5 -5
  63. package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
  64. package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
  65. package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
  66. package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
  67. package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
  68. package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
  69. package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
  70. package/skills/token-optimizer/scripts/grok_install.py +3 -0
  71. package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
  72. package/skills/token-optimizer/scripts/hermes_install.py +10 -1
  73. package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
  74. package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
  75. package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
  76. package/skills/token-optimizer/scripts/measure.py +10 -12
  77. package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
  78. package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
  79. package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
  80. package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
  81. package/skills/token-optimizer/scripts/process_identity.py +66 -0
  82. package/skills/token-optimizer/scripts/read_cache.py +51 -60
  83. package/skills/token-optimizer/scripts/statusline.js +21 -3
  84. package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
@@ -0,0 +1,716 @@
1
+ #!/usr/bin/env python3
2
+ """PostToolUse compression for Claude Code built-in tools (Grep, Glob).
3
+
4
+ Compresses oversized built-in tool results after execution via Claude Code's
5
+ ``hookSpecificOutput.updatedToolOutput`` mechanism, preserving each tool's
6
+ exact Zod ``outputSchema`` (verified against Claude Code v2.1.330):
7
+
8
+ - ``Grep`` (>4 KB, >=15 lines, multi-file, no context/head_limit/offset):
9
+ LOSSLESS on every ``file:line`` location. Factors out repeated file paths
10
+ and trims only overly long matched line text with a clear marker.
11
+ ``files_with_matches`` and ``count`` modes factor out shared directory
12
+ prefixes losslessly (every file preserved).
13
+ - ``Glob`` (>4 KB, >=15 paths): LOSSLESS directory-prefix grouping (dir
14
+ prefix once, then every basename; ``numFiles`` matches the listed count).
15
+ Passes through untouched if compression saves under 25%.
16
+
17
+ Safety invariants (all enforced):
18
+ - Fail-open: any unparseable line or exception -> original output untouched.
19
+ - Zero location loss: every ``file:line`` (Grep) and every file path (Glob)
20
+ is preserved; errors, warnings, and binary match lines stay verbatim.
21
+ - Passes through untouched for short outputs, single-file Grep searches, and
22
+ Grep calls with context flags (``-A``/``-B``/``-C``/``context``) or
23
+ ``head_limit`` / ``offset``.
24
+ - Always includes an ``expand`` pointer referencing the full raw archive
25
+ (with ``Full result archived`` marker for ``archive_verify``).
26
+ - Version gate + session self-disable: gates on known-good Claude Code
27
+ versions when available, and if the host rejects a replacement once in a
28
+ session (``archive_verify`` verdict ``full``), logs one warning and
29
+ disables built-in replacements for the rest of the session.
30
+ - Respects ``TOKEN_OPTIMIZER_NO_UPDATED_TOOL_OUTPUT`` and exempt tools.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import json
36
+ import os
37
+ import re
38
+ import sqlite3
39
+ import sys
40
+ from collections import OrderedDict
41
+ from pathlib import Path
42
+ from typing import Any
43
+
44
+ BUILTIN_COMPRESS_TOOLS = frozenset({"Grep", "Glob"})
45
+ BUILTIN_EVENT_TYPES = {"Grep": "builtin_grep", "Glob": "builtin_glob"}
46
+
47
+ GREP_THRESHOLD = 4096
48
+ GLOB_THRESHOLD = 4096
49
+ MIN_LINES_LINE_TOOLS = 15
50
+ MIN_SAVINGS_RATIO = 0.15
51
+ MIN_GLOB_SAVINGS_RATIO = 0.25
52
+ MIN_SAVINGS_CHARS = 200
53
+
54
+ _GREP_MAX_LINE_CHARS = 160
55
+ _MIN_CLAUDE_CODE_VERSION = (2, 1, 0)
56
+
57
+ _GREP_PASSTHROUGH_INPUT_KEYS = (
58
+ "-A", "-B", "-C", "context", "head_limit", "offset",
59
+ "A", "B", "C", "after_context", "before_context",
60
+ )
61
+
62
+ # Strict match-line patterns (colon separator only; never matches `-<digits>-`
63
+ # inside dated filenames like `docs/notes/2026-11-22-release-plan.md`).
64
+ # Supports optional Windows drive prefix (`C:\...` or `C:/...`) and arbitrary
65
+ # colons in the matched line text.
66
+ _GREP_CONTENT_LINE_RE = re.compile(r"^((?:[A-Za-z]:)?[^:\n]+):(\d+):(.*)$")
67
+ _GREP_COUNT_LINE_RE = re.compile(r"^((?:[A-Za-z]:)?[^:\n]+):(\d+)\s*$")
68
+
69
+ _ERROR_WARN_RE = re.compile(
70
+ r"(?:^|\b)(?:error|fatal|warning|warn|panic|exception|traceback|"
71
+ r"permission denied|no such file|timed out|timeout|access denied)\b",
72
+ re.IGNORECASE,
73
+ )
74
+
75
+ _SEMVER_RE = re.compile(r"(\d+)\.(\d+)\.(\d+)")
76
+ _AI_AGENT_CLAUDE_RE = re.compile(r"claude-code[_-](\d+)\.(\d+)\.(\d+)")
77
+
78
+
79
+ def _updated_tool_output_disabled() -> bool:
80
+ val = (os.environ.get("TOKEN_OPTIMIZER_NO_UPDATED_TOOL_OUTPUT") or "").strip().lower()
81
+ return val in ("1", "true", "yes", "on")
82
+
83
+
84
+ def _is_error_or_warning(line: str) -> bool:
85
+ stripped = line.strip()
86
+ if not stripped:
87
+ return False
88
+ if stripped.startswith(("rg:", "grep:", "Error:", "Warning:", "FATAL:", "ERROR:")):
89
+ return True
90
+ try:
91
+ from visibility_rule import is_error_or_failure_line
92
+ if is_error_or_failure_line(stripped):
93
+ return True
94
+ except Exception:
95
+ pass
96
+ return bool(_ERROR_WARN_RE.search(stripped))
97
+
98
+
99
+ def _trim_match_text(body: str, max_chars: int = _GREP_MAX_LINE_CHARS) -> str:
100
+ """Trim overly long matched line text with a clear marker; never trim errors."""
101
+ if len(body) <= max_chars or _is_error_or_warning(body):
102
+ return body
103
+ extra = len(body) - max_chars
104
+ return f"{body[:max_chars]}... [trimmed, +{extra} chars]"
105
+
106
+
107
+ def _passes_savings_gate(
108
+ original_chars: int,
109
+ replacement_chars: int,
110
+ *,
111
+ min_ratio: float = MIN_SAVINGS_RATIO,
112
+ ) -> bool:
113
+ if replacement_chars >= original_chars:
114
+ return False
115
+ saved = original_chars - replacement_chars
116
+ if saved < MIN_SAVINGS_CHARS:
117
+ return False
118
+ return (saved / max(original_chars, 1)) >= min_ratio
119
+
120
+
121
+ def _has_grep_passthrough_flags(tool_input: dict[str, Any] | None) -> bool:
122
+ """True when Grep tool_input sets any context flag, head_limit, or offset."""
123
+ if not isinstance(tool_input, dict):
124
+ return False
125
+ for key in _GREP_PASSTHROUGH_INPUT_KEYS:
126
+ val = tool_input.get(key)
127
+ if val not in (None, False, 0, ""):
128
+ return True
129
+ return False
130
+
131
+
132
+ # ---------------------------------------------------------------------------
133
+ # Version gate & per-session self-disable on host schema rejection
134
+ # ---------------------------------------------------------------------------
135
+
136
+ def _detect_claude_code_version(hook_input: dict[str, Any] | None) -> tuple[int, int, int] | None:
137
+ """Extract Claude Code semver tuple when exposed to the hook, else None."""
138
+ for env_key in ("CLAUDE_CODE_VERSION", "CLAUDE_VERSION"):
139
+ raw = (os.environ.get(env_key) or "").strip()
140
+ if raw:
141
+ m = _SEMVER_RE.search(raw)
142
+ if m:
143
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
144
+
145
+ ai_agent = (os.environ.get("AI_AGENT") or "").strip()
146
+ if ai_agent:
147
+ m = _AI_AGENT_CLAUDE_RE.search(ai_agent)
148
+ if m:
149
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
150
+
151
+ if isinstance(hook_input, dict):
152
+ for key in ("claude_code_version", "version"):
153
+ raw = hook_input.get(key)
154
+ if isinstance(raw, str) and raw.strip():
155
+ m = _SEMVER_RE.search(raw)
156
+ if m:
157
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
158
+ return None
159
+
160
+
161
+ def _is_version_supported(hook_input: dict[str, Any] | None) -> bool:
162
+ """Gate on known-good Claude Code versions when version is available."""
163
+ ver = _detect_claude_code_version(hook_input)
164
+ if ver is None:
165
+ return True
166
+ return ver >= _MIN_CLAUDE_CODE_VERSION
167
+
168
+
169
+ def _safe_sid(session_id: str) -> str:
170
+ cleaned = re.sub(r"[^A-Za-z0-9_.-]", "_", session_id or "unknown")[:128]
171
+ return cleaned or "unknown"
172
+
173
+
174
+ def _session_disable_marker(trends_db: Path, session_id: str) -> Path:
175
+ return Path(trends_db).parent / "tool-archive" / _safe_sid(session_id) / ".builtin_compress_disabled"
176
+
177
+
178
+ def _check_and_update_session_rejection(trends_db: Path, session_id: str) -> bool:
179
+ """Return True if built-in replacements are disabled for this session.
180
+
181
+ Checks the fast marker file first; otherwise runs ``archive_verify.verify``
182
+ and disables the rest of the session on the first ``full`` verdict for a
183
+ built-in tool, logging one warning to stderr.
184
+ """
185
+ if not session_id:
186
+ return False
187
+ marker = _session_disable_marker(trends_db, session_id)
188
+ try:
189
+ if marker.is_file():
190
+ return True
191
+ except OSError:
192
+ pass
193
+
194
+ try:
195
+ import archive_verify # noqa: PLC0415
196
+ archive_verify.verify(trends_db, session_id)
197
+ except Exception:
198
+ return False
199
+
200
+ rejected = False
201
+ conn = None
202
+ try:
203
+ if not Path(trends_db).is_file():
204
+ return False
205
+ conn = sqlite3.connect(str(trends_db), timeout=0.2)
206
+ row = conn.execute(
207
+ "SELECT 1 FROM archive_verifications "
208
+ "WHERE session_id=? AND tool_name IN ('Grep', 'Glob') AND verdict='full' LIMIT 1",
209
+ (session_id,),
210
+ ).fetchone()
211
+ rejected = row is not None
212
+ except Exception:
213
+ return False
214
+ finally:
215
+ if conn is not None:
216
+ conn.close()
217
+
218
+ if not rejected:
219
+ return False
220
+
221
+ try:
222
+ marker.parent.mkdir(parents=True, exist_ok=True)
223
+ marker.write_text("disabled: host rejected builtin updatedToolOutput\n", encoding="utf-8")
224
+ os.chmod(marker, 0o600)
225
+ except OSError:
226
+ pass
227
+ try:
228
+ sys.stderr.write(
229
+ f"[Token Optimizer] Built-in tool output replacement was rejected by the host "
230
+ f"in session {session_id}; disabling for the rest of this session.\n"
231
+ )
232
+ sys.stderr.flush()
233
+ except (OSError, ValueError):
234
+ pass
235
+ return True
236
+
237
+
238
+ # ---------------------------------------------------------------------------
239
+ # Grep compressors (LOSSLESS on every file:line location; fail-open parser)
240
+ # ---------------------------------------------------------------------------
241
+
242
+ def compress_grep_content(
243
+ text: str,
244
+ *,
245
+ num_files: int | None = None,
246
+ num_matches: int | None = None,
247
+ tool_input: dict[str, Any] | None = None,
248
+ ) -> str | None:
249
+ """Losslessly compress multi-file Grep content output (>4 KB).
250
+
251
+ - Passes through untouched when context flags (-A/-B/-C/context),
252
+ head_limit, or offset are set, or for single-file searches.
253
+ - Fails open (returns None) on ANY non-empty line it cannot parse cleanly
254
+ (including context separators ``--``, context lines, single-file
255
+ ``100:text`` lines, or malformed paths).
256
+ - Preserves EVERY ``file:line`` location; factors out repeated file paths
257
+ and trims only overly long matched line text with a clear marker.
258
+ """
259
+ if _has_grep_passthrough_flags(tool_input):
260
+ return None
261
+ if not text or len(text) < GREP_THRESHOLD:
262
+ return None
263
+ if num_files is not None and int(num_files) <= 1:
264
+ return None
265
+
266
+ lines = text.splitlines()
267
+ if len(lines) < MIN_LINES_LINE_TOOLS:
268
+ return None
269
+
270
+ files: OrderedDict[str, list[tuple[str, str]]] = OrderedDict()
271
+ errors: list[str] = []
272
+ binaries: list[str] = []
273
+
274
+ for ln in lines:
275
+ if not ln:
276
+ continue
277
+ if ln == "--":
278
+ # Context separator: context lines are present -> pass through untouched.
279
+ return None
280
+ if ln.startswith("Binary file ") and " matches" in ln:
281
+ binaries.append(ln)
282
+ continue
283
+ if ln.startswith(("rg:", "grep:")):
284
+ errors.append(ln)
285
+ continue
286
+ m = _GREP_CONTENT_LINE_RE.match(ln)
287
+ if not m:
288
+ # Fail open on any line we cannot parse cleanly.
289
+ return None
290
+ fname, lno, body = m.group(1), m.group(2), m.group(3)
291
+ if not fname.strip() or fname.isdigit():
292
+ # Guard against single-file `100:foo:200:bar` turning a line number into a filename.
293
+ return None
294
+ files.setdefault(fname, []).append((lno, body))
295
+
296
+ # Single-file search -> pass through untouched.
297
+ if len(files) <= 1:
298
+ return None
299
+
300
+ parsed_matches = sum(len(v) for v in files.values())
301
+ total_files = max(len(files), int(num_files)) if num_files is not None else len(files)
302
+ total_matches = max(parsed_matches, int(num_matches)) if num_matches is not None else parsed_matches
303
+
304
+ out: list[str] = [
305
+ f"[Grep results: {total_matches:,} matches across {total_files:,} files "
306
+ f"(all file:line locations preserved; long lines trimmed).]"
307
+ ]
308
+
309
+ for fname, hits in files.items():
310
+ out.append(f"{fname} ({len(hits)}):")
311
+ for lno, body in hits:
312
+ out.append(f" {lno}:{_trim_match_text(body)}")
313
+
314
+ if binaries:
315
+ out.extend(binaries)
316
+ if errors:
317
+ out.append("Errors/warnings:")
318
+ out.extend(errors)
319
+
320
+ result = "\n".join(out)
321
+ if not _passes_savings_gate(len(text), len(result), min_ratio=MIN_SAVINGS_RATIO):
322
+ return None
323
+ return result
324
+
325
+
326
+ def _split_dir_base(path: str) -> tuple[str, str] | None:
327
+ """Split a path into ``(dir_prefix, basename)`` preserving path separators."""
328
+ p = path.strip()
329
+ if not p:
330
+ return None
331
+ sep = "\\" if ("\\" in p and "/" not in p) else "/"
332
+ if sep in p:
333
+ parent, base = p.rsplit(sep, 1)
334
+ if not base:
335
+ return None
336
+ prefix = (parent + sep) if parent else sep
337
+ return prefix, base
338
+ return "", p
339
+
340
+
341
+ def compress_grep_count(
342
+ text: str,
343
+ *,
344
+ tool_input: dict[str, Any] | None = None,
345
+ ) -> str | None:
346
+ """Losslessly compress Grep count-mode output (dir prefix once, every file:count)."""
347
+ if _has_grep_passthrough_flags(tool_input):
348
+ return None
349
+ if not text or len(text) < GREP_THRESHOLD:
350
+ return None
351
+ lines = [ln for ln in text.splitlines() if ln.strip()]
352
+ if len(lines) < MIN_LINES_LINE_TOOLS:
353
+ return None
354
+
355
+ groups: OrderedDict[str, list[tuple[str, int]]] = OrderedDict()
356
+ errors: list[str] = []
357
+ total_files = 0
358
+ total_matches = 0
359
+
360
+ for ln in lines:
361
+ if ln.startswith(("rg:", "grep:")):
362
+ errors.append(ln)
363
+ continue
364
+ m = _GREP_COUNT_LINE_RE.match(ln)
365
+ if not m:
366
+ return None
367
+ split = _split_dir_base(m.group(1))
368
+ if split is None:
369
+ return None
370
+ prefix, base = split
371
+ cnt = int(m.group(2))
372
+ groups.setdefault(prefix, []).append((base, cnt))
373
+ total_files += 1
374
+ total_matches += cnt
375
+
376
+ if total_files < MIN_LINES_LINE_TOOLS:
377
+ return None
378
+
379
+ out: list[str] = [
380
+ f"[Grep counts: {total_matches:,} matches across {total_files:,} files "
381
+ f"({len(groups):,} dirs; all files preserved).]"
382
+ ]
383
+ for prefix, items in groups.items():
384
+ rendered = ", ".join(f"{base}:{cnt}" for base, cnt in items)
385
+ out.append(f"{prefix} {rendered}" if prefix else rendered)
386
+ if errors:
387
+ out.append("Errors/warnings:")
388
+ out.extend(errors)
389
+
390
+ result = "\n".join(out)
391
+ if not _passes_savings_gate(len(text), len(result), min_ratio=MIN_GLOB_SAVINGS_RATIO):
392
+ return None
393
+ return result
394
+
395
+
396
+ # ---------------------------------------------------------------------------
397
+ # Lossless Glob & Grep files_with_matches compressor
398
+ # ---------------------------------------------------------------------------
399
+
400
+ def compress_glob_paths(
401
+ paths: list[str],
402
+ *,
403
+ total_matches: int | None = None,
404
+ truncated: bool = False,
405
+ label: str = "Glob",
406
+ ) -> list[str] | None:
407
+ """Losslessly group file paths by directory: dir prefix once, then every basename.
408
+
409
+ Every single path is preserved. Returns None (pass through untouched) if
410
+ the grouped representation saves less than 25% vs the raw path list.
411
+ """
412
+ if not paths or len(paths) < MIN_LINES_LINE_TOOLS:
413
+ return None
414
+ raw_chars = sum(len(str(p)) + 1 for p in paths)
415
+ if raw_chars < GLOB_THRESHOLD:
416
+ return None
417
+
418
+ groups: OrderedDict[str, list[str]] = OrderedDict()
419
+ listed_count = 0
420
+
421
+ for raw_p in paths:
422
+ split = _split_dir_base(str(raw_p))
423
+ if split is None:
424
+ # Fail open on empty or malformed path entry.
425
+ return None
426
+ prefix, base = split
427
+ groups.setdefault(prefix, []).append(base)
428
+ listed_count += 1
429
+
430
+ if listed_count != len(paths) or not groups:
431
+ return None
432
+
433
+ total_note = f"{listed_count:,}"
434
+ if total_matches is not None and total_matches > listed_count:
435
+ total_note = f"{listed_count:,} of {total_matches:,}"
436
+ trunc_note = " (truncated)" if truncated else ""
437
+
438
+ out: list[str] = [
439
+ f"[{label}: {total_note} files across {len(groups):,} dirs{trunc_note}; all paths preserved]"
440
+ ]
441
+ for prefix, names in groups.items():
442
+ joined_names = ", ".join(names)
443
+ out.append(f"{prefix} {joined_names}" if prefix else joined_names)
444
+
445
+ rep_chars = sum(len(ln) + 1 for ln in out)
446
+ if not _passes_savings_gate(raw_chars, rep_chars, min_ratio=MIN_GLOB_SAVINGS_RATIO):
447
+ return None
448
+ return out
449
+
450
+
451
+ # ---------------------------------------------------------------------------
452
+ # Claude Code schema-preserving updatedToolOutput builder
453
+ # ---------------------------------------------------------------------------
454
+
455
+ def _builtin_expand_instruction(tool_use_id: str) -> str:
456
+ """Build an expand pointer explaining how to retrieve the full archived result."""
457
+ try:
458
+ from refetch_fingerprint import expand_command # noqa: PLC0415
459
+ cmd = expand_command(tool_use_id)
460
+ except Exception:
461
+ cmd = f"expand {tool_use_id}"
462
+ return f"To view the full archived result, run in Bash:\n {cmd}"
463
+
464
+
465
+ def _archive_footer(
466
+ original_char_count: int,
467
+ char_count: int,
468
+ tool_use_id: str,
469
+ expand_instruction: str | None,
470
+ truncated: bool,
471
+ ) -> str:
472
+ instr = expand_instruction or _builtin_expand_instruction(tool_use_id)
473
+ if truncated:
474
+ return (
475
+ f"\n\n[Full result archived ({original_char_count:,} chars, truncated to 5MB) — "
476
+ f"saved to disk, not lost.\n{instr}\n]"
477
+ )
478
+ return (
479
+ f"\n\n[Full result archived ({char_count:,} chars) — saved to disk, not lost.\n"
480
+ f"{instr}\n]"
481
+ )
482
+
483
+
484
+ def build_builtin_updated_output(
485
+ tool_name: str,
486
+ raw_response: Any,
487
+ safe_response: str,
488
+ tool_input: dict[str, Any] | None,
489
+ tool_use_id: str,
490
+ expand_instruction: str | None,
491
+ original_char_count: int,
492
+ char_count: int,
493
+ truncated: bool = False,
494
+ redact_fn=None,
495
+ ) -> tuple[dict[str, Any], int, int] | None:
496
+ """Build a schema-valid ``updatedToolOutput`` dict for Grep or Glob, or None.
497
+
498
+ Returns ``(updated_tool_output_dict, original_field_chars, replacement_field_chars)``
499
+ so measured savings are always computed against the exact field that was
500
+ replaced. Returns ``None`` to fail open.
501
+ """
502
+ if tool_name not in BUILTIN_COMPRESS_TOOLS:
503
+ return None
504
+ if not isinstance(raw_response, dict):
505
+ return None
506
+
507
+ t_input = tool_input if isinstance(tool_input, dict) else {}
508
+ footer = _archive_footer(
509
+ original_char_count, char_count, tool_use_id, expand_instruction, truncated
510
+ )
511
+
512
+ if tool_name == "Grep":
513
+ if _has_grep_passthrough_flags(t_input):
514
+ return None
515
+ mode = raw_response.get("mode")
516
+ filenames = raw_response.get("filenames")
517
+ num_files = raw_response.get("numFiles")
518
+ if not isinstance(filenames, list) or not isinstance(num_files, int):
519
+ return None
520
+
521
+ content = raw_response.get("content")
522
+ if isinstance(content, str) and len(content) >= GREP_THRESHOLD:
523
+ safe_content = redact_fn(content) if redact_fn else content
524
+ if mode == "count":
525
+ comp = compress_grep_count(safe_content, tool_input=t_input)
526
+ min_ratio = MIN_GLOB_SAVINGS_RATIO
527
+ else:
528
+ comp = compress_grep_content(
529
+ safe_content,
530
+ num_files=num_files,
531
+ num_matches=raw_response.get("numMatches"),
532
+ tool_input=t_input,
533
+ )
534
+ min_ratio = MIN_SAVINGS_RATIO
535
+ if not comp:
536
+ return None
537
+ new_content = comp + footer
538
+ orig_field_chars = len(content)
539
+ rep_field_chars = len(new_content)
540
+ if not _passes_savings_gate(orig_field_chars, rep_field_chars, min_ratio=min_ratio):
541
+ return None
542
+ try:
543
+ from emit_safety_gate import gate_or_none as _emit_gate
544
+ if _emit_gate(safe_content, new_content, feature="builtin_grep", tool_name="Grep", require_expand=True) is None:
545
+ return None
546
+ except Exception:
547
+ return None
548
+ updated = dict(raw_response)
549
+ updated["content"] = new_content
550
+ return updated, orig_field_chars, rep_field_chars
551
+
552
+ # files_with_matches mode (filenames list carries the bulk)
553
+ if filenames:
554
+ safe_names = [redact_fn(str(f)) if redact_fn else str(f) for f in filenames]
555
+ summary_lines = compress_glob_paths(
556
+ safe_names,
557
+ total_matches=raw_response.get("totalFiles") or num_files,
558
+ label="Grep files",
559
+ )
560
+ if not summary_lines:
561
+ return None
562
+ new_filenames = summary_lines + [footer.strip()]
563
+ orig_field_chars = sum(len(str(f)) + 1 for f in filenames)
564
+ rep_field_chars = sum(len(ln) + 1 for ln in new_filenames)
565
+ if not _passes_savings_gate(orig_field_chars, rep_field_chars, min_ratio=MIN_GLOB_SAVINGS_RATIO):
566
+ return None
567
+ try:
568
+ from emit_safety_gate import gate_or_none as _emit_gate
569
+ if _emit_gate("\n".join(safe_names), "\n".join(new_filenames), feature="builtin_grep", tool_name="Grep", require_expand=True) is None:
570
+ return None
571
+ except Exception:
572
+ return None
573
+ updated = dict(raw_response)
574
+ updated["filenames"] = new_filenames
575
+ updated["numFiles"] = len(filenames)
576
+ return updated, orig_field_chars, rep_field_chars
577
+ return None
578
+
579
+ if tool_name == "Glob":
580
+ filenames = raw_response.get("filenames")
581
+ if (
582
+ not isinstance(filenames, list)
583
+ or not isinstance(raw_response.get("numFiles"), int)
584
+ or not isinstance(raw_response.get("truncated"), bool)
585
+ or not isinstance(raw_response.get("durationMs"), (int, float))
586
+ ):
587
+ return None
588
+ safe_names = [redact_fn(str(f)) if redact_fn else str(f) for f in filenames]
589
+ summary_lines = compress_glob_paths(
590
+ safe_names,
591
+ total_matches=raw_response.get("totalMatches"),
592
+ truncated=bool(raw_response.get("truncated")),
593
+ label="Glob",
594
+ )
595
+ if not summary_lines:
596
+ return None
597
+ new_filenames = summary_lines + [footer.strip()]
598
+ orig_field_chars = sum(len(str(f)) + 1 for f in filenames)
599
+ rep_field_chars = sum(len(ln) + 1 for ln in new_filenames)
600
+ if not _passes_savings_gate(orig_field_chars, rep_field_chars, min_ratio=MIN_GLOB_SAVINGS_RATIO):
601
+ return None
602
+ try:
603
+ from emit_safety_gate import gate_or_none as _emit_gate
604
+ if _emit_gate("\n".join(safe_names), "\n".join(new_filenames), feature="builtin_glob", tool_name="Glob", require_expand=True) is None:
605
+ return None
606
+ except Exception:
607
+ return None
608
+ updated = dict(raw_response)
609
+ updated["filenames"] = new_filenames
610
+ updated["numFiles"] = len(filenames)
611
+ return updated, orig_field_chars, rep_field_chars
612
+
613
+ return None
614
+
615
+
616
+ def maybe_emit_builtin_replacement(
617
+ *,
618
+ tool_name: str,
619
+ raw_response: Any,
620
+ safe_response: str,
621
+ hook_input: dict[str, Any],
622
+ tool_use_id: str,
623
+ raw_tool_use_id: str,
624
+ session_id: str,
625
+ original_char_count: int,
626
+ char_count: int,
627
+ truncated: bool,
628
+ expand_instruction: str | None = None,
629
+ code_chars_per_token: float,
630
+ trends_db: Path,
631
+ log_savings_event_fn,
632
+ is_exempt_fn,
633
+ redact_fn=None,
634
+ ) -> bool:
635
+ """Compress & emit ``updatedToolOutput`` for eligible built-in tools. Fail-open."""
636
+ try:
637
+ if tool_name not in BUILTIN_COMPRESS_TOOLS:
638
+ return False
639
+ if _updated_tool_output_disabled():
640
+ return False
641
+ if not _is_version_supported(hook_input):
642
+ return False
643
+ if is_exempt_fn and is_exempt_fn(tool_name):
644
+ return False
645
+ if _check_and_update_session_rejection(trends_db, session_id):
646
+ return False
647
+
648
+ built = build_builtin_updated_output(
649
+ tool_name=tool_name,
650
+ raw_response=raw_response,
651
+ safe_response=safe_response,
652
+ tool_input=hook_input.get("tool_input"),
653
+ tool_use_id=tool_use_id,
654
+ expand_instruction=expand_instruction,
655
+ original_char_count=original_char_count,
656
+ char_count=char_count,
657
+ truncated=truncated,
658
+ redact_fn=redact_fn,
659
+ )
660
+ if built is None:
661
+ return False
662
+
663
+ updated_output, orig_field_chars, rep_field_chars = built
664
+ original_tokens = int(orig_field_chars / code_chars_per_token)
665
+ replacement_tokens = int(rep_field_chars / code_chars_per_token)
666
+ tokens_saved = max(0, original_tokens - replacement_tokens)
667
+ detail = f"replaced {tool_name} ({orig_field_chars:,} chars -> {rep_field_chars:,} chars)"
668
+ event_type = BUILTIN_EVENT_TYPES.get(tool_name, "tool_archive")
669
+ if log_savings_event_fn is not None:
670
+ log_savings_event_fn(event_type, tokens_saved, session_id=session_id, detail=detail)
671
+
672
+ try:
673
+ import archive_verify # noqa: PLC0415
674
+ if tokens_saved > 0:
675
+ archive_verify.record(
676
+ trends_db,
677
+ session_id,
678
+ raw_tool_use_id,
679
+ tool_name,
680
+ orig_field_chars,
681
+ rep_field_chars,
682
+ hook_input.get("transcript_path"),
683
+ detail,
684
+ )
685
+ except Exception:
686
+ pass
687
+
688
+ envelope = {
689
+ "hookSpecificOutput": {
690
+ "hookEventName": "PostToolUse",
691
+ "updatedToolOutput": updated_output,
692
+ }
693
+ }
694
+ print(json.dumps(envelope))
695
+ return True
696
+ except Exception:
697
+ return False
698
+
699
+
700
+ def compress_benchmark_fixture(fixture: dict[str, Any]) -> str:
701
+ """Run a benchmark.py fixture through the matching built-in compressor."""
702
+ tool = fixture.get("tool", "")
703
+ raw = fixture.get("raw_output", "")
704
+ tool_input = fixture.get("tool_input") if isinstance(fixture.get("tool_input"), dict) else None
705
+ if tool == "Grep":
706
+ mode = fixture.get("mode", "content")
707
+ if mode == "count":
708
+ return compress_grep_count(raw, tool_input=tool_input) or raw
709
+ if mode == "files_with_matches":
710
+ lines = compress_glob_paths(raw.splitlines(), label="Grep files")
711
+ return "\n".join(lines) if lines else raw
712
+ return compress_grep_content(raw, tool_input=tool_input) or raw
713
+ if tool == "Glob":
714
+ lines = compress_glob_paths(raw.splitlines(), truncated=bool(fixture.get("truncated", False)))
715
+ return "\n".join(lines) if lines else raw
716
+ return raw