@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,2490 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer v5: Bash Output Compression Wrapper.
3
+
4
+ Invoked by bash_hook.py via PreToolUse command rewriting:
5
+ bash_compress.py git status
6
+ bash_compress.py pytest tests/
7
+
8
+ Runs the command, captures output, applies pattern-matched compression.
9
+ On ANY error, returns raw output unchanged (fail-open).
10
+
11
+ Security:
12
+ - shell=True is NEVER used
13
+ - Token preservation scan runs on PRE-compression output
14
+ - Output buffered completely before writing to stdout
15
+ - Partial output on timeout is NEVER compressed
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import json
21
+ import os
22
+ import re
23
+ import shlex
24
+ import subprocess
25
+ import sys
26
+ import time
27
+ import unicodedata
28
+ from pathlib import Path
29
+
30
+ # Windows: spawning a console exe (git, where, tasklist, ...) from a console-less
31
+ # hook flashes a cmd window on every Bash call. CREATE_NO_WINDOW suppresses
32
+ # it. getattr-guarded so it is 0 -- a no-op -- on POSIX and on builds without it.
33
+ _NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # Claude Code tool-output truncation baseline (never show more than baseline)
37
+ # ---------------------------------------------------------------------------
38
+ # Claude Code 2.1.247 (2026-08) replaces any tool result LARGER than
39
+ # CC_PERSISTED_OUTPUT_THRESHOLD_CHARS with a ~2.2KB "<persisted-output>"
40
+ # stub (measured: a 41.1KB `ls -la /usr/bin` result -> a 2,206-char stub).
41
+ # Token Optimizer must NEVER make the model see more chars than that
42
+ # baseline would, so these two numbers are the single tuning point: if a
43
+ # future Claude Code version changes its truncation behavior, adjust them
44
+ # together here (see _enforce_baseline_invariant).
45
+ CC_PERSISTED_OUTPUT_THRESHOLD_CHARS = 30_000 # raw tool result size that triggers CC's stub
46
+ CC_PERSISTED_OUTPUT_STUB_CHARS = 2_206 # size of the stub CC shows for such results
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Token/credential preservation patterns (scanned PRE-compression)
50
+ # ---------------------------------------------------------------------------
51
+ try:
52
+ from credential_patterns import PATTERNS_ONLY as _TOKEN_PATTERNS
53
+ except ImportError:
54
+ # Standalone execution or import failure: inline minimal set
55
+ _TOKEN_PATTERNS = [
56
+ re.compile(r"AKIA[0-9A-Z]{16}"),
57
+ re.compile(r"sk-[a-zA-Z0-9]{20,}"),
58
+ re.compile(r"sk-ant-[a-zA-Z0-9\-]{20,}"),
59
+ re.compile(r"ghp_[a-zA-Z0-9]{36}"),
60
+ re.compile(r"gho_[a-zA-Z0-9]{36}"),
61
+ re.compile(r"ghs_[a-zA-Z0-9]{36}"),
62
+ re.compile(r"ghr_[a-zA-Z0-9]{36}"),
63
+ re.compile(r"github_pat_[a-zA-Z0-9_]{80,}"),
64
+ re.compile(r"npm_[a-zA-Z0-9]{36}"),
65
+ re.compile(r"xoxb-[0-9]+-[a-zA-Z0-9]+"),
66
+ re.compile(r"xoxp-[0-9]+-[a-zA-Z0-9]+"),
67
+ re.compile(r"xoxa-[0-9]+-[a-zA-Z0-9]+"),
68
+ re.compile(r"sk_live_[a-zA-Z0-9]{24,}"),
69
+ re.compile(r"rk_live_[a-zA-Z0-9]{24,}"),
70
+ re.compile(r"hf_[a-zA-Z0-9]{34}"),
71
+ re.compile(r"gl(?:pat|dt|rt|cbt|ptt|ft|imt|agent|soat)-[a-zA-Z0-9_.\-]{20,}"),
72
+ re.compile(r"Bearer\s+[a-zA-Z0-9\-._~+/]+=*", re.I),
73
+ re.compile(r"AIza[0-9A-Za-z_\-]{35}"),
74
+ re.compile(r"ya29\.[0-9A-Za-z_\-]{20,}"),
75
+ re.compile(r"eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}"),
76
+ re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
77
+ re.compile(r"(?:postgres|postgresql|mysql|mongodb|mongodb\+srv|redis)://[^:\s/]+:[^@\s]+@", re.I),
78
+ re.compile(r"https?://[^:\s/@]+:[^@\s]+@", re.I),
79
+ ]
80
+
81
+ # ANSI escape code patterns.
82
+ #
83
+ # _ANSI_CSI_RE drops colour/style/cursor escape sequences.
84
+ #
85
+ # _ANSI_OSC8_RE matches a full OSC 8 hyperlink -- opener, label text, closer --
86
+ # and is used with a ``\1`` backreference so the visible label text survives
87
+ # (captured as group 1). The previous combined regex swallowed the label along
88
+ # with the opener/closer, which meant any credential embedded in the visible
89
+ # hyperlink text vanished before the preservation scan ran.
90
+ _ANSI_CSI_RE = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]")
91
+ _ANSI_OSC8_RE = re.compile(r"\x1b\]8;[^\x07]*\x07([^\x1b]*)\x1b\]8;;\x07")
92
+
93
+ # Stderr patterns that indicate failure even with exit code 0 (linters often
94
+ # emit errors on stderr but exit 0 because they only reported warnings).
95
+ # Localised error markers are included so non-English toolchains still trip
96
+ # the tee. The patterns are case-insensitive for Latin scripts and literal
97
+ # for CJK scripts (case folding is a no-op there).
98
+ _ERROR_STDERR_PATTERNS = [
99
+ re.compile(r"\berror\s*:", re.I),
100
+ re.compile(r"\bfatal\s*:", re.I),
101
+ re.compile(r"\bpanic\s*:", re.I),
102
+ re.compile(r"\bFAILED\b"),
103
+ re.compile(r"\bTraceback\b"),
104
+ # Localised variants:
105
+ re.compile(r"\bfehler\s*:", re.I), # German
106
+ re.compile(r"\berreur\s*:", re.I), # French
107
+ re.compile(r"\berrore\s*:", re.I), # Italian
108
+ re.compile(r"\bошибка\s*:", re.I), # Russian
109
+ re.compile(r"错误\s*[::]"), # Chinese (simplified)
110
+ re.compile(r"錯誤\s*[::]"), # Chinese (traditional)
111
+ re.compile(r"エラー\s*[::]"), # Japanese
112
+ re.compile(r"오류\s*[::]"), # Korean
113
+ ]
114
+
115
+
116
+ def _strip_ansi(text):
117
+ """Remove ANSI escape codes. Preserve visible text from OSC 8 hyperlinks.
118
+
119
+ Two-step replace: first collapse OSC 8 hyperlinks to their visible label
120
+ (via the captured group 1), then drop CSI escape sequences. This keeps
121
+ any credential that happens to appear inside the visible label text
122
+ available to the pre-compression preservation scan, instead of dropping
123
+ it with the surrounding hyperlink structure.
124
+ """
125
+ text = _ANSI_OSC8_RE.sub(r"\1", text)
126
+ return _ANSI_CSI_RE.sub("", text)
127
+
128
+
129
+ def _looks_like_failure(returncode, stderr):
130
+ """Return True when the command should not have its output compressed.
131
+
132
+ Triggers on non-zero exit, OR on exit code 0 with an error pattern on
133
+ stderr (common for linters that print "error:" on stderr while exiting 0).
134
+ Fail-open: on any surprise, treat as non-failure so the normal compression
135
+ path still runs.
136
+ """
137
+ try:
138
+ if returncode not in (0, None):
139
+ return True
140
+ if not stderr:
141
+ return False
142
+ for pat in _ERROR_STDERR_PATTERNS:
143
+ if pat.search(stderr):
144
+ return True
145
+ except Exception:
146
+ return False
147
+ return False
148
+
149
+
150
+ # Error markers in scripts/languages the English-keyword handlers would
151
+ # otherwise drop. Any line matching one of these is re-injected through the
152
+ # same preservation path credentials use, so a foreign-language error
153
+ # surfaces even when the compression handler speaks only English.
154
+ #
155
+ # Latin-script entries require a trailing colon so short Latin tokens that
156
+ # also appear in English tech vocabulary do not false-positive. FOUT
157
+ # (Flash Of Unstyled Text) in web-perf output, FEL in Free Electron Laser
158
+ # toolchains, and Hata propagation model references are common enough
159
+ # that a bare word boundary would preserve unrelated lines and inflate
160
+ # the compressed output.
161
+ #
162
+ # CJK-script entries stay as literal character sequences since those
163
+ # characters do not collide with English tech tokens.
164
+ _FOREIGN_ERROR_PATTERNS = [
165
+ re.compile(r"\bfout\s*[::]", re.I), # Dutch
166
+ re.compile(r"\bfel\s*[::]", re.I), # Swedish
167
+ re.compile(r"\bvirhe\s*[::]", re.I), # Finnish
168
+ re.compile(r"\bhiba\s*[::]", re.I), # Hungarian
169
+ re.compile(r"\bhata\s*[::]", re.I), # Turkish
170
+ re.compile(r"\berro\s*[::]", re.I), # Portuguese / Spanish
171
+ re.compile(r"\bblad\s*[::]", re.I), # Polish
172
+ re.compile(r"l\u1ed7i\s*[::]", re.I), # Vietnamese
173
+ re.compile(r"\u0e02\u0e49\u0e2d\u0e1c\u0e34\u0e14\u0e1e\u0e25\u0e32\u0e14"), # Thai
174
+ re.compile(r"\u05e9\u05d2\u05d9\u05d0\u05d4"), # Hebrew
175
+ re.compile(r"\u062e\u0637\u0623"), # Arabic
176
+ re.compile(r"\u062e\u0637\u0627"), # Persian
177
+ ]
178
+
179
+
180
+ def _find_preserved_lines(text):
181
+ """Find line indices that must survive compression (credentials + errors).
182
+
183
+ Two scans run here:
184
+ 1. Token patterns (credentials) — never drop a line carrying a secret.
185
+ 2. Foreign-language error markers — the English-keyword handlers below
186
+ will happily drop a Dutch "fout:" line because it does not contain
187
+ "error"/"failed"/etc. We flag it here so the re-injection path
188
+ brings it back after compression runs.
189
+ """
190
+ preserved = set()
191
+ for i, line in enumerate(text.splitlines()):
192
+ for pat in _TOKEN_PATTERNS:
193
+ if pat.search(line):
194
+ preserved.add(i)
195
+ break
196
+ else:
197
+ # Only scan error patterns when the line did not already match
198
+ # a credential pattern (small optimization).
199
+ for pat in _ERROR_STDERR_PATTERNS:
200
+ if pat.search(line):
201
+ preserved.add(i)
202
+ break
203
+ else:
204
+ for pat in _FOREIGN_ERROR_PATTERNS:
205
+ if pat.search(line):
206
+ preserved.add(i)
207
+ break
208
+ return preserved
209
+
210
+
211
+ # Identifier-shaped token: >=6 chars, contains a letter, not a bare
212
+ # number/timestamp. Captures UUIDs, URLs, hashes, emails, dotted names, IDs --
213
+ # the kinds of things a user greps a log FOR -- while ignoring counters,
214
+ # timestamps, and short plain words.
215
+ _DISTINCTIVE_TOKEN_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:/@\-]{5,}")
216
+ _BARE_NUMERIC_RE = re.compile(r"^[0-9][0-9:.\-T/]*$")
217
+
218
+
219
+ def _find_distinctive_lines(text, rare_max=2, cap_frac=0.30, min_lines=8):
220
+ """Find lines carrying a token that is RARE within this output (the needle).
221
+
222
+ Aggressive summarizers (search/grep -> top-N + count, generic log -> head/
223
+ tail) drop the one line the user actually wants when it is not near the top.
224
+ The model then re-runs a narrower query to recover it, spending the tokens
225
+ the compression just saved. This scan flags lines whose distinctive token
226
+ (a UUID, URL, hash, email, id -- something with identifier shape) appears on
227
+ only a couple of lines, so the shared re-injection path keeps that needle.
228
+
229
+ Rarity, not type, is the signal. A token on EVERY line (a per-line request
230
+ id, a ubiquitous host) is boilerplate and is NOT preserved -- otherwise a
231
+ log where every line carries an id would preserve every line and defeat
232
+ compression. If more than ``cap_frac`` of lines look distinctive the output
233
+ is too varied to have a single needle, so we bail (return nothing) and let
234
+ normal compression run unhindered. Never raises: on any surprise the caller
235
+ still has the credential/error scan and progressive-disclosure archive.
236
+ """
237
+ try:
238
+ lines = text.splitlines()
239
+ n = len(lines)
240
+ if n < min_lines:
241
+ return set() # too small to bother; full output likely survives
242
+ from collections import Counter
243
+ toksets = []
244
+ df = Counter()
245
+ for ln in lines:
246
+ toks = set()
247
+ for m in _DISTINCTIVE_TOKEN_RE.finditer(ln):
248
+ t = m.group(0)
249
+ if _BARE_NUMERIC_RE.match(t):
250
+ continue # counter / timestamp, not a needle
251
+ if not any(c.isalpha() for c in t):
252
+ continue
253
+ toks.add(t)
254
+ toksets.append(toks)
255
+ for t in toks:
256
+ df[t] += 1
257
+ distinctive = {
258
+ i for i, toks in enumerate(toksets)
259
+ if any(df[t] <= rare_max for t in toks)
260
+ }
261
+ if len(distinctive) > n * cap_frac:
262
+ return set() # too varied to needle-preserve; do not defeat compression
263
+ return distinctive
264
+ except Exception:
265
+ return set() # fail open -- credential scan + archive still protect data
266
+
267
+
268
+ # ---------------------------------------------------------------------------
269
+ # Compression patterns (one per command family)
270
+ # ---------------------------------------------------------------------------
271
+
272
+ def _compress_git_status(output):
273
+ """Compress git status to one-line summary."""
274
+ lines = output.strip().splitlines()
275
+ branch = "?"
276
+ ahead_behind = ""
277
+
278
+ staged_files = []
279
+ unstaged_files = []
280
+ untracked_files = []
281
+ unmerged_files = []
282
+ section = None
283
+ for line in lines:
284
+ if line.startswith("On branch "):
285
+ branch = line.replace("On branch ", "").strip()
286
+ elif "ahead" in line or "behind" in line:
287
+ ahead_behind = line.strip().lstrip("(").rstrip(")")
288
+ elif line.strip() in (
289
+ "nothing to commit, working tree clean",
290
+ "nothing to commit (working directory clean)",
291
+ "nothing to commit, working directory clean",
292
+ ):
293
+ # Anchored equality check: the string "nothing to commit" can
294
+ # legitimately appear inside a filename under "Untracked files:"
295
+ # (e.g. `nothing to commit.txt`). A substring match there would
296
+ # falsely report the tree clean and hide real untracked work.
297
+ return f"branch: {branch}, clean{f' ({ahead_behind})' if ahead_behind else ''}"
298
+ elif "Changes to be committed:" in line:
299
+ section = "staged"
300
+ elif "Changes not staged" in line:
301
+ section = "unstaged"
302
+ elif "Untracked files:" in line:
303
+ section = "untracked"
304
+ elif "Unmerged paths:" in line:
305
+ section = "unmerged"
306
+ elif (line.startswith("\t") or line.startswith(" ")) and section:
307
+ fname = line.strip()
308
+ # Strip prefixes: staged/unstaged AND merge-conflict prefixes, so
309
+ # conflicted files are captured (they were silently dropped before).
310
+ for prefix in ("new file:", "modified:", "deleted:", "renamed:", "copied:",
311
+ "both modified:", "both added:", "both deleted:",
312
+ "added by us:", "added by them:",
313
+ "deleted by us:", "deleted by them:"):
314
+ if fname.startswith(prefix):
315
+ fname = fname[len(prefix):].strip()
316
+ break
317
+ if section == "staged":
318
+ staged_files.append(fname)
319
+ elif section == "unstaged":
320
+ unstaged_files.append(fname)
321
+ elif section == "untracked":
322
+ untracked_files.append(fname)
323
+ elif section == "unmerged":
324
+ unmerged_files.append(fname)
325
+
326
+ if (branch == "?" and not ahead_behind and not staged_files
327
+ and not unstaged_files and not untracked_files and not unmerged_files):
328
+ # Nothing recognised: the input is not git status output (for example
329
+ # a "git status"-hinted capture of a grep or git log). Hand the raw
330
+ # output back rather than emit "branch: ?" and silently drop the
331
+ # whole capture; the caller's generic fallback then applies.
332
+ return output
333
+
334
+ parts = [f"branch: {branch}"]
335
+ if ahead_behind:
336
+ parts.append(ahead_behind)
337
+ if staged_files:
338
+ parts.append(f"{len(staged_files)} staged: {', '.join(staged_files)}")
339
+ if unstaged_files:
340
+ parts.append(f"{len(unstaged_files)} unstaged: {', '.join(unstaged_files)}")
341
+ if untracked_files:
342
+ parts.append(f"{len(untracked_files)} untracked: {', '.join(untracked_files)}")
343
+ if unmerged_files:
344
+ # Merge conflicts must NEVER be silently dropped -- surface prominently.
345
+ parts.append(f"{len(unmerged_files)} UNMERGED (merge conflicts): {', '.join(unmerged_files)}")
346
+ return "\n".join(parts) if len(parts) > 2 else ", ".join(parts)
347
+
348
+
349
+ def _compress_git_log_basic(output):
350
+ """Identity: shapes the summarizer must not touch (custom formats, patches,
351
+ signatures, stat listings) are delivered exactly as git printed them."""
352
+ return output
353
+
354
+
355
+ _GIT_LOG_COMMIT_RE = re.compile(r"^commit ([0-9a-f]{40}|[0-9a-f]{64})(?: \((.*)\))?$")
356
+ _GIT_LOG_HEADER_RE = re.compile(r"^(Author|Date|Merge|Commit|CommitDate|AuthorDate):\s*(.*)$")
357
+ _GIT_LOG_TRAILER_RE = re.compile(
358
+ r"^(Signed-off-by|Co-authored-by|Reviewed-by|Acked-by|Tested-by|Reported-by|"
359
+ r"Suggested-by|Helped-by|Cc|Change-Id|Fixes|Closes|Refs?)\s*:", re.IGNORECASE)
360
+ _GIT_LOG_ALL_HASHES_RE = re.compile(r"(?m)^commit ([0-9a-f]{40}|[0-9a-f]{64})\b")
361
+ _GIT_LOG_OUT_HASH_RE = re.compile(r"(?m)^([0-9a-f]{10}) ")
362
+ # Separators str.splitlines() honours beyond "\n" (and NUL): a message holding
363
+ # one would be cut mid-line, so such output is delivered untouched.
364
+ _AMBIGUOUS_SEPARATORS_RE = re.compile("[\x00\r\x0b\x0c\x1c-\x1e\x85\u2028\u2029]")
365
+ _GIT_LOG_MIN_COMMITS = 5
366
+ _GIT_LOG_MAX_COMMITS = 50000
367
+ _GIT_LOG_SHORT = 10
368
+
369
+
370
+ def _plural(n, one, many):
371
+ return f"{n} {one if n == 1 else many}"
372
+
373
+
374
+ def _git_log_date(raw):
375
+ """'Thu Oct 15 12:39:24 2026 +0300' -> '2026-10-15 12:39 +0300' (raw on any doubt)."""
376
+ try:
377
+ import datetime as _dt
378
+ parts = raw.split()
379
+ stamp = _dt.datetime.strptime(" ".join(parts[:5]), "%a %b %d %H:%M:%S %Y")
380
+ tz = parts[5] if len(parts) > 5 and re.fullmatch(r"[+-]\d{4}", parts[5]) else ""
381
+ return (stamp.strftime("%Y-%m-%d %H:%M") + (" " + tz if tz else "")).strip()
382
+ except Exception:
383
+ return raw.strip()
384
+
385
+
386
+ def _compress_git_log(output):
387
+ """Summarize default-format ``git log``: one line per commit.
388
+
389
+ Keeps, for EVERY commit: 10-char hash, date, author name, subject (plus
390
+ decorations and a merge marker). Bodies, trailers (Signed-off-by,
391
+ Co-authored-by ...) and author emails are condensed to counts. Anything
392
+ that is not cleanly parseable default-format output (patches, --stat,
393
+ signatures, graph, custom formats, ambiguous separators) is returned
394
+ unchanged, as is any result whose hash recount disagrees with the input.
395
+ A last commit cut off by ``| head`` is listed as truncated, never guessed.
396
+ """
397
+ if _AMBIGUOUS_SEPARATORS_RE.search(output):
398
+ return output
399
+ input_hashes = _GIT_LOG_ALL_HASHES_RE.findall(output)
400
+ if not _GIT_LOG_MIN_COMMITS <= len(input_hashes) <= _GIT_LOG_MAX_COMMITS:
401
+ return output
402
+ commits = []
403
+ cur = None
404
+ stream = output.split("\n")
405
+ if stream and stream[-1] == "":
406
+ stream.pop() # the newline that ends the stream is not a blank line
407
+ for line in stream:
408
+ m = _GIT_LOG_COMMIT_RE.match(line)
409
+ if m:
410
+ cur = {"hash": m.group(1), "deco": m.group(2), "hdr": {}, "msg": [], "in_msg": False}
411
+ commits.append(cur)
412
+ continue
413
+ if cur is None:
414
+ if line.strip():
415
+ return output # preamble: not default format
416
+ continue
417
+ if not cur["in_msg"]:
418
+ hm = _GIT_LOG_HEADER_RE.match(line)
419
+ if hm:
420
+ cur["hdr"][hm.group(1)] = hm.group(2)
421
+ continue
422
+ if not line.strip():
423
+ cur["in_msg"] = True
424
+ continue
425
+ return output # unknown header shape (gpg lines, reflog ...)
426
+ # message region: default format indents every message line by 4 spaces
427
+ if line.strip() and not line.startswith(" "):
428
+ return output # patch / stat / graph content
429
+ cur["msg"].append(line[4:] if line.startswith(" ") else line.strip())
430
+ if len(commits) != len(input_hashes) or [c["hash"] for c in commits] != input_hashes:
431
+ return output
432
+
433
+ def _incomplete(c):
434
+ # Cut off only when the headers really are incomplete: no Date line, or
435
+ # the stream ends before the blank line that closes the headers. A
436
+ # commit with an empty message is complete: "(no message)".
437
+ return ("Date" not in c["hdr"] and "AuthorDate" not in c["hdr"]) or not c["in_msg"]
438
+
439
+ truncated = None
440
+ if _incomplete(commits[-1]):
441
+ truncated = commits[-1]
442
+ for c in commits[:-1]:
443
+ if "Date" not in c["hdr"] and "AuthorDate" not in c["hdr"]:
444
+ return output
445
+ out = []
446
+ for c in commits:
447
+ if c is truncated:
448
+ out.append(f"{c['hash'][:_GIT_LOG_SHORT]} [truncated: the output ends inside this "
449
+ f"commit; its date, author and subject are not in the original stream]")
450
+ continue
451
+ hdr = c["hdr"]
452
+ author = re.sub(r"\s*<[^>]*>\s*$", "", hdr.get("Author", "?")).strip() or "?"
453
+ date = _git_log_date(hdr.get("Date") or hdr.get("AuthorDate", ""))
454
+ msg = list(c["msg"])
455
+ while msg and not msg[0].strip():
456
+ msg.pop(0)
457
+ subject_lines = []
458
+ while msg and msg[0].strip():
459
+ subject_lines.append(msg.pop(0).strip()) # git's subject is the first paragraph
460
+ subject = " ".join(subject_lines) or "(no message)"
461
+ rest = [m for m in msg if m.strip()]
462
+ trailers = [m for m in rest if _GIT_LOG_TRAILER_RE.match(m.strip())]
463
+ body = len(rest) - len(trailers)
464
+ flags = []
465
+ if "Merge" in hdr:
466
+ flags.append("merge")
467
+ if body:
468
+ flags.append("+" + _plural(body, "body line", "body lines"))
469
+ if trailers:
470
+ flags.append("+" + _plural(len(trailers), "trailer", "trailers"))
471
+ coauth = [re.sub(r"\s*<[^>]*>\s*$", "", t.split(":", 1)[1]).strip()
472
+ for t in trailers if t.strip().lower().startswith("co-authored-by")]
473
+ if coauth:
474
+ flags.append("co-authors: " + ", ".join(coauth[:3]))
475
+ line = f"{c['hash'][:_GIT_LOG_SHORT]} {date} {author} | {subject}"
476
+ if c["deco"]:
477
+ line += f" ({c['deco']})"
478
+ if flags:
479
+ line += " [" + "; ".join(flags) + "]"
480
+ out.append(line)
481
+ body_text = "\n".join(out)
482
+ # Recount from the text that will actually be delivered.
483
+ if _GIT_LOG_OUT_HASH_RE.findall(body_text) != [h[:_GIT_LOG_SHORT] for h in input_hashes]:
484
+ return output
485
+ header = (f"[git log: {_plural(len(commits), 'commit', 'commits')}, one line each: "
486
+ f"{_GIT_LOG_SHORT}-char hash, date, author, subject. "
487
+ f"Text in [ ] counts omitted body lines and trailers and names co-authors; "
488
+ f"text in ( ) is branch/tag decoration. Author emails and message bodies are "
489
+ f"omitted; the full original output is recoverable.]")
490
+ return header + "\n" + body_text
491
+
492
+
493
+ _FIND_MIN_PATHS = 40 # fewer paths pass through unchanged
494
+ _FIND_MAX_PATHS = 50000 # larger lists are delivered untouched (time bound)
495
+ _FIND_DIR_KEEP = 8 # a directory with <= this many entries lists all names
496
+ _FIND_DIR_KEEP_SEARCH = 40 # ... in a name/path search, where the names are the answer
497
+ _FIND_EXAMPLES = 3
498
+ _FIND_NOISE_DIRS = frozenset({
499
+ ".git", "node_modules", "__pycache__", ".venv", "venv", ".tox", ".pytest_cache",
500
+ ".mypy_cache", ".ruff_cache", ".next", ".gradle", "target", ".idea",
501
+ })
502
+ _FIND_SEARCH_PREDICATES = frozenset({
503
+ "-name", "-iname", "-path", "-ipath", "-wholename", "-iwholename", "-regex", "-iregex",
504
+ })
505
+ _FIND_GLOBAL_OPTIONS = frozenset({"-H", "-L", "-P", "-E", "-X", "-x", "-s", "-d"})
506
+
507
+
508
+ def _find_ext(name):
509
+ base = name.rsplit("/", 1)[-1]
510
+ if "." in base.lstrip("."):
511
+ return "*." + base.rsplit(".", 1)[-1]
512
+ return "(no ext)"
513
+
514
+
515
+ def _find_name(name):
516
+ return shlex.quote(name) if re.search(r"[\s'\"\\$`*?\[\](){}<>|&;#~!]", name) else name
517
+
518
+
519
+ def _find_summary(label, names, with_examples=True, unit="entry", unit_many="entries",
520
+ count=None):
521
+ count = len(names) if count is None else count
522
+ exts = {}
523
+ for n in names:
524
+ exts[_find_ext(n)] = exts.get(_find_ext(n), 0) + 1
525
+ ranked = sorted(exts.items(), key=lambda kv: (-kv[1], kv[0]))
526
+ shown = ", ".join(f"{e} x{k}" for e, k in ranked[:4])
527
+ if len(ranked) > 4:
528
+ shown += f", {_plural(len(ranked) - 4, 'other type', 'other types')}"
529
+ text = f"* {_find_name(label)} ({_plural(count, unit, unit_many)}" + (f": {shown})" if shown else ")")
530
+ if with_examples and names:
531
+ text += " e.g. " + " ".join(_find_name(n) for n in names[:_FIND_EXAMPLES])
532
+ return text
533
+
534
+
535
+ def _find_command_scope(command_str):
536
+ """(roots, search_mode) read from the find invocation, or (None, False)."""
537
+ if not command_str:
538
+ return None, False
539
+ try:
540
+ tokens = shlex.split(command_str)
541
+ except ValueError:
542
+ return None, False
543
+ if "|" in tokens:
544
+ tokens = tokens[:tokens.index("|")]
545
+ idx = next((i for i, t in enumerate(tokens) if t == "find"), None)
546
+ if idx is None:
547
+ return None, False
548
+ rest = tokens[idx + 1:]
549
+ roots = []
550
+ i = 0
551
+ while i < len(rest):
552
+ t = rest[i]
553
+ if t in _FIND_GLOBAL_OPTIONS or re.fullmatch(r"-O\d", t):
554
+ i += 1
555
+ elif t == "-D":
556
+ i += 2
557
+ else:
558
+ break
559
+ while i < len(rest) and not (rest[i].startswith("-") or rest[i] in ("(", "!", ")")):
560
+ roots.append(rest[i])
561
+ i += 1
562
+ search = any(t in _FIND_SEARCH_PREDICATES for t in rest[i:])
563
+ return (roots or ["."]), search
564
+
565
+
566
+ def _norm_components(path):
567
+ parts = [p for p in path.split("/") if p not in ("", ".")]
568
+ return (path.startswith("/"), tuple(parts))
569
+
570
+
571
+ def _under(root, path):
572
+ r_abs, r = _norm_components(root)
573
+ p_abs, p = _norm_components(path)
574
+ return r_abs == p_abs and p[:len(r)] == r
575
+
576
+
577
+ def _find_recount(text, paths):
578
+ """Recount, from the delivered text, how many paths it accounts for."""
579
+ expected = set(paths)
580
+ seen = set()
581
+ total = 0
582
+ try:
583
+ for ln in text.split("\n")[1:]:
584
+ if ln.startswith("* "):
585
+ t = shlex.split(ln[2:])
586
+ m = re.fullmatch(r"\((\d+)", t[1])
587
+ total += int(m.group(1))
588
+ elif ln.startswith("= "):
589
+ for name in shlex.split(ln[2:]):
590
+ if name not in expected or name in seen:
591
+ return False
592
+ seen.add(name)
593
+ total += 1
594
+ else:
595
+ t = shlex.split(ln)
596
+ label = t[0]
597
+ for name in t[1:]:
598
+ full = label + (name[:-1] if name.endswith("/") else name)
599
+ if full not in expected or full in seen:
600
+ return False
601
+ seen.add(full)
602
+ total += 1
603
+ except (ValueError, IndexError, AttributeError):
604
+ return False
605
+ return total == len(paths)
606
+
607
+
608
+ def _compress_find(output, command_str=None):
609
+ """Summarize a plain ``find`` path list, grouped by directory.
610
+
611
+ Small lists pass through. Otherwise every directory with few entries lists
612
+ every name once (its prefix stated once, not per path); larger directories
613
+ collapse to a count, a type breakdown and example names; with a plain
614
+ full-tree listing, noise trees (.git, node_modules, __pycache__ ...)
615
+ collapse whole. Noise is never collapsed when the find root is inside it or
616
+ when the command is a name/path search. The total path count is always
617
+ stated. Anything that is not plainly a path list is returned unchanged.
618
+ """
619
+ if _AMBIGUOUS_SEPARATORS_RE.search(output):
620
+ return output
621
+ paths = [ln for ln in output.split("\n") if ln]
622
+ if not _FIND_MIN_PATHS <= len(paths) <= _FIND_MAX_PATHS:
623
+ return output
624
+ if len(set(paths)) != len(paths):
625
+ return output
626
+ for p in paths:
627
+ # tab/control chars, leading blanks (uniq -c, columns), error lines,
628
+ # trailing or doubled slashes: not plainly a list of find paths.
629
+ if (len(p) > 1024 or p != p.strip() or p.startswith("find:")
630
+ or re.search(r"[\x00-\x1f\x7f]", p) or "//" in p
631
+ or (len(p) > 1 and p.endswith("/")) or re.match(r"^\S+\s{2,}\S", p)):
632
+ return output
633
+ roots, search_mode = _find_command_scope(command_str)
634
+ if roots is not None:
635
+ prefixes = [r.rstrip("/") or "/" for r in roots]
636
+ if not all(any(p == r or p.startswith(r if r.endswith("/") else r + "/")
637
+ for r in prefixes) for p in paths):
638
+ return output
639
+ else:
640
+ forms = {("abs" if p.startswith("/") else "dot" if p.split("/")[0] == "." else "rel")
641
+ for p in paths}
642
+ if len(forms) != 1:
643
+ return output
644
+ keep = _FIND_DIR_KEEP_SEARCH if search_mode else _FIND_DIR_KEEP
645
+
646
+ noise_roots = {}
647
+ groups = {}
648
+ special = []
649
+ dir_set = set()
650
+ for p in paths:
651
+ d = p
652
+ while "/" in d: # every ancestor directory, even of a collapsed tree
653
+ d = d[:d.rfind("/")]
654
+ if not d:
655
+ break
656
+ dir_set.add(d)
657
+ if p in (".", "/") or (not p.startswith("/") and "/" not in p):
658
+ special.append(p)
659
+ continue
660
+ parts = p.split("/")
661
+ cut = None
662
+ if not search_mode:
663
+ for i, comp in enumerate(parts):
664
+ if comp in _FIND_NOISE_DIRS:
665
+ cut = i
666
+ break
667
+ if cut is not None:
668
+ root = "/".join(parts[:cut + 1])
669
+ if roots is not None and any(_under(root, r) for r in roots):
670
+ cut = None # the find root is inside this noise tree
671
+ if cut is not None:
672
+ noise_roots.setdefault(root, []).append("/".join(parts[cut + 1:]))
673
+ continue
674
+ parent = p[:p.rfind("/")] or "/"
675
+ groups.setdefault(parent, []).append(parts[-1])
676
+
677
+ out = []
678
+ collapsed = False
679
+ if special:
680
+ out.append("= " + " ".join(_find_name(s) for s in special))
681
+ for parent in sorted(groups):
682
+ names = groups[parent]
683
+ label = parent if parent.endswith("/") else parent + "/"
684
+ disp = []
685
+ for n in names:
686
+ full = (parent if parent != "/" else "") + "/" + n
687
+ disp.append(n + "/" if full in dir_set else n)
688
+ if len(names) <= keep:
689
+ out.append(_find_name(label) + " " + " ".join(_find_name(n) for n in disp))
690
+ else:
691
+ collapsed = True
692
+ out.append(_find_summary(label, names))
693
+ for root in sorted(noise_roots):
694
+ collapsed = True
695
+ members = noise_roots[root]
696
+ named = [m for m in members if m]
697
+ out.append(_find_summary(root + "/", named, unit="path collapsed",
698
+ unit_many="paths collapsed", count=len(members)))
699
+ head = (f"[find: {_plural(len(paths), 'path', 'paths')} total, grouped by directory; "
700
+ f"a name ending in / has its own children listed in that directory's group.")
701
+ if special:
702
+ head += " A line starting with = lists top-level paths such as the search root itself."
703
+ if collapsed:
704
+ head += (" Lines starting with * are collapsed groups: they show a count, a type "
705
+ "breakdown and a few example names only, not every entry.")
706
+ head += " The full original output is recoverable.]"
707
+ result = head + "\n" + "\n".join(out)
708
+ if not _find_recount(result, paths):
709
+ return output
710
+ return result
711
+
712
+
713
+ def _compress_git_diff(output):
714
+ """Compress git diff: keep file names and stats, truncate large diffs."""
715
+ lines = output.strip().splitlines()
716
+ if len(lines) <= 50:
717
+ return output # small diff, keep full
718
+
719
+ # Extract summary stats
720
+ additions = 0
721
+ deletions = 0
722
+
723
+ for line in lines:
724
+ if line.startswith("diff --git"):
725
+ pass
726
+ elif line.startswith("+++"):
727
+ pass
728
+ elif line.startswith("+") and not line.startswith("+++"):
729
+ additions += 1
730
+ elif line.startswith("-") and not line.startswith("---"):
731
+ deletions += 1
732
+
733
+ # Keep first 30 lines of actual diff content
734
+ changed = [ln for ln in lines if ln.startswith("diff --git ")]
735
+ result_lines = lines[:30]
736
+ if len(lines) > 30:
737
+ result_lines.append(f"\n... ({len(lines) - 30} more lines, +{additions}/-{deletions} total)")
738
+ if changed:
739
+ # Keep every changed FILENAME so "did file X change?" is answerable.
740
+ names = [c.split(" b/")[-1] for c in changed]
741
+ result_lines.append(f"All {len(names)} changed files: " + ", ".join(names))
742
+
743
+ return "\n".join(result_lines)
744
+
745
+
746
+ _PYTEST_SUMMARY_TAIL_LINES = 40
747
+
748
+
749
+ def _compress_pytest(output):
750
+ """Compress pytest/cypress/playwright/mocha/karma/rspec/unittest/gradle/tox/deno/bun/ava test output.
751
+
752
+ Extracts trailing summary lines (anything containing passed, passing,
753
+ failed, failing, error, pending, or skipped) plus the explicit
754
+ FAILURES/ERRORS section when pytest emits one. Cypress and playwright
755
+ speak in "passing" / "failing" terms, so the reverse-scan accepts both
756
+ vocabularies. The v5.8 extensions add "ran " (unittest), "build
757
+ successful"/"build failed" (gradle), "congratulations" (tox), and
758
+ "ok |" (deno) to the summary keyword set. The scan window is bounded
759
+ by ``_PYTEST_SUMMARY_TAIL_LINES`` to avoid walking the whole output on
760
+ pathological inputs, but is wide enough to survive 15-20 trailing
761
+ warning lines emitted after the summary.
762
+ """
763
+ lines = output.strip().splitlines()
764
+ if not lines:
765
+ return output
766
+ if len(lines) < 15:
767
+ return output # too short to meaningfully compress
768
+
769
+ summary_kw = ("passed", "passing", "failed", "failing", "error",
770
+ "pending", "skipped",
771
+ # v5.8 test-runner extension summary markers
772
+ "ran ", "build successful", "build failed",
773
+ "congratulations", "ok |",
774
+ # v5.8 bun test runner (uses "pass"/"fail" without -ed/-ing)
775
+ "pass,", "fail,")
776
+
777
+ # Reverse-scan the tail for a contiguous block of summary lines.
778
+ # Accept up to 5 non-matching lines inside the block (trailing warnings)
779
+ # before declaring the summary region over.
780
+ summary_block = []
781
+ non_match_run = 0
782
+ MAX_NON_MATCH = 5
783
+ for line in reversed(lines[-_PYTEST_SUMMARY_TAIL_LINES:]):
784
+ stripped = line.strip().lstrip("=").strip()
785
+ if not stripped:
786
+ if summary_block:
787
+ non_match_run += 1
788
+ if non_match_run > MAX_NON_MATCH:
789
+ break
790
+ continue
791
+ if any(kw in stripped.lower() for kw in summary_kw):
792
+ summary_block.append(stripped)
793
+ non_match_run = 0
794
+ elif summary_block:
795
+ non_match_run += 1
796
+ if non_match_run > MAX_NON_MATCH:
797
+ break
798
+ summary_block.reverse()
799
+ summary_line = "\n".join(summary_block)
800
+
801
+ # Find failure section (pytest-native)
802
+ failure_lines = []
803
+ in_failures = False
804
+ for line in lines:
805
+ if "FAILURES" in line or "ERRORS" in line:
806
+ in_failures = True
807
+ continue
808
+ if in_failures:
809
+ if line.startswith("=" * 10):
810
+ break # end of failures section
811
+ failure_lines.append(line)
812
+
813
+ if failure_lines:
814
+ failure_text = "\n".join(failure_lines[:30])
815
+ if len(failure_lines) > 30:
816
+ failure_text += f"\n... ({len(failure_lines) - 30} more failure lines)"
817
+ return f"{summary_line}\n\n{failure_text}"
818
+
819
+ return summary_line if summary_line else output
820
+
821
+
822
+ def _compress_jest(output):
823
+ """Compress jest/vitest: keep summary + failure details."""
824
+ lines = output.strip().splitlines()
825
+
826
+ summary_lines = []
827
+ failure_lines = []
828
+
829
+ for line in lines:
830
+ if "Tests:" in line or "Test Suites:" in line or "Time:" in line:
831
+ summary_lines.append(line.strip())
832
+ elif "FAIL" in line and ("::" in line or ">" in line):
833
+ failure_lines.append(line.strip())
834
+ elif line.strip().startswith("Expected:") or line.strip().startswith("Received:"):
835
+ failure_lines.append(line.strip())
836
+
837
+ result = "\n".join(summary_lines)
838
+ if failure_lines:
839
+ result += "\n\nFailures:\n" + "\n".join(failure_lines[:20])
840
+ return result if result.strip() else output
841
+
842
+
843
+ def _compress_npm_install(output):
844
+ """Compress npm/pip install: summary only."""
845
+ lines = output.strip().splitlines()
846
+ result = []
847
+ for line in lines:
848
+ stripped = line.strip()
849
+ if not stripped:
850
+ continue
851
+ # Keep: added/removed/audited summary, vulnerability count, warnings
852
+ if any(kw in stripped.lower() for kw in [
853
+ "added", "removed", "audited", "packages",
854
+ "vulnerabilit", "up to date", "successfully installed",
855
+ "warn", "error", "fatal",
856
+ ]):
857
+ result.append(stripped)
858
+ return "\n".join(result) if result else output
859
+
860
+
861
+ def _ls_entry_name(line):
862
+ """Extract the entry NAME from one ls line, spaces and symlinks intact.
863
+
864
+ ``split()[-1]`` is wrong for two real cases: a filename with spaces ("My
865
+ Important Doc.txt" -> "Doc.txt") and a symlink (``link -> target`` -> the
866
+ target, hiding the link's own name). Both make the agent search for a name
867
+ that "isn't there" and infer false absence. For long format (``ls -l``) the
868
+ name is everything after the 8 metadata columns; for a plain listing the
869
+ whole line is the name.
870
+ """
871
+ toks = line.split()
872
+ if not toks:
873
+ return line
874
+ first = toks[0]
875
+ is_long = (
876
+ len(toks) >= 9
877
+ and len(first) in (10, 11)
878
+ and first[0] in "bcdlps-"
879
+ and set(first[1:10]) <= set("rwxXsStT-")
880
+ )
881
+ if is_long:
882
+ name = line.split(None, 8)[-1]
883
+ # symlink "link -> target": keep the link's own name, not the target.
884
+ return name.split(" -> ", 1)[0].rstrip()
885
+ # plain listing (ls -1 / find output): the whole line is the path/name.
886
+ return line.rstrip()
887
+
888
+
889
+ def _compress_ls(output):
890
+ """Compress directory listing: truncate at 50 entries."""
891
+ lines = output.strip().splitlines()
892
+ if len(lines) <= 50:
893
+ return output
894
+
895
+ result = lines[:50]
896
+ # Keep every entry NAME (cheap) so "is file X here?" stays answerable; only
897
+ # the metadata columns of entries past 50 are dropped, never the names.
898
+ rest = lines[50:]
899
+ names = [_ls_entry_name(ln) for ln in rest]
900
+ result.append(f"... plus {len(rest)} more (names only, none dropped): "
901
+ f"{', '.join(names)}")
902
+ return "\n".join(result)
903
+
904
+
905
+ # Lint rule-code patterns. Ordered by specificity so the first match wins.
906
+ # The CAPS+digits pattern catches ruff/flake8/pylint/shellcheck/pydocstyle.
907
+ # The trailing kebab pattern catches eslint rule names. The CamelCase/slash
908
+ # pattern catches rubocop cops. The parenthesised trailing word catches
909
+ # golangci-lint linter tags like `(typecheck)` or `(govet)`.
910
+ _LINT_CODE_PATTERNS = [
911
+ re.compile(r"\b([A-Z]{1,4}\d{2,5})\b"), # F401, E501, SC2086, W0611
912
+ re.compile(r"\s([a-z][a-z0-9]*(?:-[a-z0-9]+)+)\s*$"), # eslint trailing kebab
913
+ re.compile(r"\b([A-Z][A-Za-z]+/[A-Z][A-Za-z]+)\b"), # rubocop Style/Foo
914
+ re.compile(r"\(([a-z][a-z0-9]+)\)\s*$"), # golangci (typecheck)
915
+ ]
916
+
917
+ # Prefixes that look like lint rule codes but are not. A line like
918
+ # "vulnerable to CVE2024" or "HTTP404 on /api" would otherwise get grouped
919
+ # as if CVE2024 / HTTP404 were linter rules. The handler discards matches
920
+ # whose first two letters are any of these prefixes.
921
+ _LINT_CODE_BLOCKLIST_PREFIXES = (
922
+ "CVE", "RFC", "ISO", "HTTP", "ISBN", "USD", "EUR", "GBP",
923
+ "JPY", "SHA", "MD5", "PGP", "TCP", "UDP", "DNS",
924
+ )
925
+
926
+
927
+ def _compress_build(output):
928
+ """Compress JS/TS/Go build output (tsc/webpack/esbuild/vite/next/go build).
929
+
930
+ Keeps lines that look like errors, warnings, or final summary markers.
931
+ Drops the bulk of bundler chatter (asset lists, file size tables,
932
+ incremental compile stats). When there is no recognisable error/warning
933
+ or summary signal at all, returns the raw output unchanged — the 10%
934
+ ratio gate in ``compress()`` then throws the compression away on its own.
935
+ The handler never fabricates a positive "build clean" claim.
936
+ """
937
+ lines = output.splitlines()
938
+ if len(lines) < 20:
939
+ return output
940
+
941
+ error_kw = ("error", "warning", "failed", "fatal")
942
+ summary_kw = (
943
+ "compiled successfully", "built in", "build finished",
944
+ "build completed", "done in", "errors", "warnings",
945
+ "bundled ", "chunk ", "emitted ", "hash:", "version:",
946
+ )
947
+ # "Found 0 errors" / "0 warnings" / "no errors" are CLEAN signals that
948
+ # happen to contain an error_kw substring. Treat them as summary,
949
+ # not as error/warning, so a clean build is not reported with a
950
+ # misleading "1 error/warning lines" header. The match is
951
+ # left-anchored so a real error line like
952
+ # `error TS2322: Expected 'no errors' but found 'undefined'` is not
953
+ # mis-routed to the summary bucket, and so a line like
954
+ # `10 errors in 5 files` cannot match the `0 errors` prefix.
955
+ clean_summary_patterns = (
956
+ "found 0 error", "0 errors", "0 warnings", "no errors",
957
+ "no warnings", "0 problems",
958
+ )
959
+ # "Found N errors" (N > 0) is an aggregate summary, not an individual
960
+ # error line. Counting it as an error inflates the handler's "N
961
+ # error/warning lines" header. We detect it via a regex and route to
962
+ # the summary bucket.
963
+ found_n_errors_re = re.compile(r"^found\s+\d+\s+(error|warning|problem)s?", re.I)
964
+ # "Errors Files" style tsc trailing column headers are also summary.
965
+ error_header_res = re.compile(r"^(errors?\s+files?|errors?\s+warnings?)$", re.I)
966
+
967
+ errors = []
968
+ summaries = []
969
+ total_kept = 0
970
+ for raw in lines:
971
+ stripped = raw.strip()
972
+ if not stripped:
973
+ continue
974
+ low = stripped.lower()
975
+ if any(low.startswith(pat) for pat in clean_summary_patterns):
976
+ summaries.append(stripped)
977
+ continue
978
+ if found_n_errors_re.match(low) or error_header_res.match(low):
979
+ summaries.append(stripped)
980
+ continue
981
+ if any(kw in low for kw in error_kw):
982
+ errors.append(stripped)
983
+ total_kept += 1
984
+ if total_kept > 80: # bound even on pathological error dumps
985
+ break
986
+ elif any(kw in low for kw in summary_kw):
987
+ summaries.append(stripped)
988
+
989
+ if not errors and not summaries:
990
+ # No recognisable signal — hand the raw output back unchanged. The
991
+ # 10% ratio gate in compress() will see zero compression and also
992
+ # return raw. Do NOT fabricate a "no errors detected" marker: that
993
+ # would be a positive claim about build state we cannot verify.
994
+ return output
995
+
996
+ parts = []
997
+ if errors:
998
+ parts.append(f"{len(errors)} error/warning lines:")
999
+ parts.extend(errors[:40])
1000
+ if len(errors) > 40:
1001
+ parts.append(f"... ({len(errors) - 40} more errors/warnings)")
1002
+ if summaries:
1003
+ parts.append("")
1004
+ parts.extend(summaries[-5:])
1005
+
1006
+ return "\n".join(parts)
1007
+
1008
+
1009
+ def _compress_list(output):
1010
+ """Compress long listing commands (pip list / npm ls / docker ps / brew list).
1011
+
1012
+ Shows the first ~10 entries verbatim, then a "... N more" placeholder,
1013
+ and preserves any trailing summary line. Header lines (first non-empty
1014
+ line plus common "Name Version" style headers) survive to keep the
1015
+ output interpretable. Short lists (<20 entries) pass through raw.
1016
+ """
1017
+ lines = output.splitlines()
1018
+ non_empty = [ln for ln in lines if ln.strip()]
1019
+ if len(non_empty) < 20:
1020
+ return output
1021
+
1022
+ header_lines = []
1023
+ data_lines = []
1024
+ seen_data = False
1025
+ for line in lines:
1026
+ stripped = line.strip()
1027
+ if not stripped:
1028
+ continue
1029
+ # Detect header separators (all dashes, "Package Version", etc.)
1030
+ if not seen_data and (
1031
+ set(stripped) <= set("-= ")
1032
+ or any(stripped.lower().startswith(prefix) for prefix in (
1033
+ "package", "name ", "container", "image", "repository",
1034
+ ))
1035
+ ):
1036
+ header_lines.append(line)
1037
+ continue
1038
+ seen_data = True
1039
+ data_lines.append(line)
1040
+
1041
+ if len(data_lines) < 20:
1042
+ return output
1043
+
1044
+ keep_count = 10
1045
+ result = list(header_lines)
1046
+ result.extend(data_lines[:keep_count])
1047
+ rest = data_lines[keep_count:]
1048
+ # Which column holds the identifying NAME depends on the command:
1049
+ # - docker ps: NAMES is the LAST column (first col is CONTAINER ID) -> split()[-1]
1050
+ # - npm/pnpm ls: lines are a glyph tree (+--, |--, `--) -> strip glyph, take pkg
1051
+ # - pip list / brew / apt: NAME is the FIRST column -> split()[0]
1052
+ header_blob = " ".join(header_lines).upper()
1053
+ tree_glyphs = ("+--", "|--", "`--", "\\--", "├", "└", "│", "|__")
1054
+
1055
+ def _name_of(ln):
1056
+ toks = ln.split()
1057
+ if not toks:
1058
+ return ""
1059
+ # npm-style tree row: drop leading glyph tokens, keep the package spec.
1060
+ if any(g in ln for g in tree_glyphs):
1061
+ cleaned = ln
1062
+ for g in ("+--", "|--", "`--", "\\--", "├──",
1063
+ "└──", "│", "|__"):
1064
+ cleaned = cleaned.replace(g, " ")
1065
+ ct = cleaned.split()
1066
+ return ct[0] if ct else ""
1067
+ # docker ps: NAMES is the last whitespace-column.
1068
+ if "CONTAINER ID" in header_blob and "NAMES" in header_blob:
1069
+ return toks[-1]
1070
+ return toks[0]
1071
+
1072
+ names = [n for n in (_name_of(ln) for ln in rest) if n]
1073
+ result.append(
1074
+ f"... plus {len(rest)} more entries (names only; a name not listed is "
1075
+ f"not present): {', '.join(names)}")
1076
+ return "\n".join(result)
1077
+
1078
+
1079
+ def _compress_progress(output):
1080
+ """Compress build progress output (docker build, cargo build verbose, etc.).
1081
+
1082
+ Drops noisy progress lines (layer staging, "Downloading", "Extracting",
1083
+ cache hit indicators) and keeps lines that signal status, warnings,
1084
+ errors, or final outcomes. Safe for pip install / cargo build / docker
1085
+ build style output. Unknown lines fall through as summary context when
1086
+ there are few enough of them to matter.
1087
+ """
1088
+ lines = output.splitlines()
1089
+ if len(lines) < 20:
1090
+ return output
1091
+
1092
+ noisy_prefixes = (
1093
+ "Downloading ", "Collecting ", "Resolving ", "Building wheels ",
1094
+ "Created wheel", "Using cached ", "Requirement already ",
1095
+ "Extracting", "Transferring",
1096
+ )
1097
+ # docker-buildx progress markers: `#12 DONE 0.1s`, `#12 ...`, etc.
1098
+ docker_progress_re = re.compile(r"^#\d+\s+")
1099
+ # docker pull layer fetch progress (shows up as `abc123456789: Pulling...`)
1100
+ pull_progress_re = re.compile(
1101
+ r"^[a-f0-9]{12}:\s+(Pulling|Waiting|Already|Extracting|Download|Verifying)"
1102
+ )
1103
+
1104
+ keep = []
1105
+ dropped = 0
1106
+ for raw in lines:
1107
+ stripped = raw.strip()
1108
+ if not stripped:
1109
+ continue
1110
+ low = stripped.lower()
1111
+
1112
+ # Always keep errors, warnings, failures, and final success markers.
1113
+ if any(kw in low for kw in ("error", "warning", "fail", "fatal",
1114
+ "successfully", "built ",
1115
+ "installed", "complete", "naming to",
1116
+ "exporting")):
1117
+ keep.append(stripped)
1118
+ continue
1119
+
1120
+ # Drop noisy progress chatter.
1121
+ if stripped.startswith(noisy_prefixes):
1122
+ dropped += 1
1123
+ continue
1124
+ if docker_progress_re.match(stripped) and "DONE" not in stripped:
1125
+ dropped += 1
1126
+ continue
1127
+ if pull_progress_re.match(stripped):
1128
+ dropped += 1
1129
+ continue
1130
+
1131
+ # Keep everything else as context.
1132
+ keep.append(stripped)
1133
+
1134
+ if dropped < max(10, len(lines) // 4):
1135
+ return output # not noisy enough to justify compression
1136
+
1137
+ return "\n".join(keep)
1138
+
1139
+
1140
+ def _tree_line_depth(line):
1141
+ """Return the logical depth of a `tree` output line.
1142
+
1143
+ Walks the 4-character prefix chunks `tree` emits: vertical pipes ("│ "),
1144
+ blanks (" "), and branch markers ("├── "/"└── "). Each pipe or blank
1145
+ chunk is one level; a branch marker contributes the final +1 for the leaf.
1146
+ Root-level names with no prefix return 0.
1147
+ """
1148
+ i = 0
1149
+ depth = 0
1150
+ while i + 4 <= len(line):
1151
+ chunk = line[i:i + 4]
1152
+ if chunk == "\u2502 " or chunk == " ": # "│ " or four spaces
1153
+ depth += 1
1154
+ i += 4
1155
+ elif chunk == "\u251c\u2500\u2500 " or chunk == "\u2514\u2500\u2500 ": # ├── / └──
1156
+ return depth + 1
1157
+ else:
1158
+ return depth
1159
+ return depth
1160
+
1161
+
1162
+ def _compress_tree(output):
1163
+ """Compress the `tree` command: keep entries up to depth 2 plus the summary.
1164
+
1165
+ Depth is inferred from `tree`'s box-drawing prefix. Root (depth 0), direct
1166
+ children (depth 1), and grandchildren (depth 2) are kept; anything deeper
1167
+ is dropped and replaced with a single "(N entries at depth > 2 truncated)"
1168
+ marker. The trailing "N directories, M files" summary line survives
1169
+ because summary lines have depth 0. Credentials appearing in deep file
1170
+ names are preserved by the pre-compression token scan.
1171
+ """
1172
+ lines = output.splitlines()
1173
+ if len(lines) < 20:
1174
+ return output # not enough to bother
1175
+
1176
+ result = []
1177
+ truncated = 0
1178
+ for line in lines:
1179
+ if not line.strip():
1180
+ result.append(line)
1181
+ continue
1182
+ depth = _tree_line_depth(line)
1183
+ if depth <= 2:
1184
+ result.append(line)
1185
+ else:
1186
+ truncated += 1
1187
+
1188
+ if truncated == 0:
1189
+ return output
1190
+
1191
+ result.append(f"... ({truncated} entries at depth > 2 truncated)")
1192
+ return "\n".join(result)
1193
+
1194
+
1195
+ def _compress_logs(output):
1196
+ """Compress log-like output (tail/journalctl).
1197
+
1198
+ Detects runs of adjacent duplicate lines and collapses them to a single
1199
+ line plus a "(xN)" marker. Only activates when the duplicate rate is at
1200
+ least 30% of the input, so normal mixed logs pass through raw.
1201
+
1202
+ Credential safety: the collapsed line is ``<original> (xN)``, so the
1203
+ original line text is kept verbatim as a prefix. Any credential on the
1204
+ line is therefore preserved by the line itself — the pre-compression
1205
+ token scan still runs as a backstop, and its re-injection check (``if
1206
+ preserved_line not in compressed_text``) correctly finds the credential
1207
+ as a substring and skips adding a duplicate copy.
1208
+ """
1209
+ lines = output.splitlines()
1210
+ if len(lines) < 20:
1211
+ return output # short logs: not worth the compression risk
1212
+
1213
+ collapsed = []
1214
+ dup_removed = 0
1215
+ i = 0
1216
+ while i < len(lines):
1217
+ current = lines[i]
1218
+ run = 1
1219
+ while i + run < len(lines) and lines[i + run] == current:
1220
+ run += 1
1221
+ if run > 1:
1222
+ collapsed.append(f"{current} (x{run})")
1223
+ dup_removed += run - 1
1224
+ else:
1225
+ collapsed.append(current)
1226
+ i += run
1227
+
1228
+ # Require meaningful dup density before accepting the compression.
1229
+ if dup_removed < max(10, len(lines) // 3):
1230
+ return output
1231
+
1232
+ return "\n".join(collapsed)
1233
+
1234
+
1235
+ def _compress_lint(output):
1236
+ """Compress lint output (eslint/ruff/flake8/rubocop/shellcheck/biome/pylint/golangci-lint).
1237
+
1238
+ Group findings by rule code, show top-5 codes with a single sample line,
1239
+ preserve trailing summary lines (e.g. "Found 6 errors") verbatim. Unknown
1240
+ lines fall through uncounted so the handler stays robust against format
1241
+ drift — credentials are preserved via the PRE-compression token scan.
1242
+ """
1243
+ lines = output.splitlines()
1244
+ if len(lines) < 10:
1245
+ return output
1246
+
1247
+ counts = {}
1248
+ samples = {}
1249
+ summary_lines = []
1250
+ total_findings = 0
1251
+ files_with_findings = set()
1252
+
1253
+ for line in lines:
1254
+ stripped = line.strip()
1255
+ if not stripped:
1256
+ continue
1257
+ matched_code = None
1258
+ for pat in _LINT_CODE_PATTERNS:
1259
+ # Walk every match of this pattern on the line so a blocked
1260
+ # candidate (e.g. CVE2024) does not shadow a real lint code
1261
+ # (e.g. E501) that appears later in the same line.
1262
+ for m in pat.finditer(stripped):
1263
+ candidate = m.group(1)
1264
+ if candidate.startswith(_LINT_CODE_BLOCKLIST_PREFIXES):
1265
+ continue
1266
+ matched_code = candidate
1267
+ break
1268
+ if matched_code:
1269
+ break
1270
+ if matched_code:
1271
+ counts[matched_code] = counts.get(matched_code, 0) + 1
1272
+ # Capture the file this finding is in (path:line:col: CODE format) so
1273
+ # "does file X have lint errors?" is answerable, not just top-5 codes.
1274
+ # Grab everything before the first :LINE[:COL] group -- this keeps
1275
+ # Windows drive paths (C:\...) and paths containing spaces, which a
1276
+ # plain split(":")[0] would truncate to the drive letter or a prose
1277
+ # word, silently dropping the file from a list that reads as complete.
1278
+ fm = re.match(r"^(.*?):\d+(?::\d+)?[:\s]", stripped)
1279
+ head = fm.group(1).strip() if fm else ""
1280
+ if head and ("/" in head or "\\" in head or "." in head):
1281
+ files_with_findings.add(head)
1282
+ if matched_code not in samples:
1283
+ sample = stripped
1284
+ if len(sample) > 140:
1285
+ sample = sample[:137] + "..."
1286
+ samples[matched_code] = sample
1287
+ total_findings += 1
1288
+ else:
1289
+ # Trailing summary context: "Found 6 errors.", "✖ 12 problems", etc.
1290
+ low = stripped.lower()
1291
+ if any(tok in low for tok in ("found", "error", "warning", "problem",
1292
+ "clean", "passed", "failed", "checked")):
1293
+ summary_lines.append(stripped)
1294
+
1295
+ if total_findings < 5:
1296
+ return output # not worth the complexity for short lint runs
1297
+
1298
+ parts = [f"{total_findings} findings across {len(counts)} rule codes"]
1299
+
1300
+ ranked = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
1301
+ for code, cnt in ranked[:5]:
1302
+ sample = samples.get(code, "")
1303
+ parts.append(f" {code} x{cnt}: {sample}")
1304
+
1305
+ if len(ranked) > 5:
1306
+ tail_count = sum(c for _, c in ranked[5:])
1307
+ parts.append(f" ... {len(ranked) - 5} other codes ({tail_count} findings)")
1308
+
1309
+ if files_with_findings:
1310
+ flist = sorted(files_with_findings)
1311
+ # Deliberately NOT an "all files listed" claim: eslint's grouped format
1312
+ # carries no path on finding lines, so this list can under-count. Never
1313
+ # let the agent infer a file is clean just because it is absent here.
1314
+ parts.append(f"Files with findings (>= {len(flist)}, parsed from finding "
1315
+ f"lines, may under-count): {', '.join(flist)}")
1316
+
1317
+ if summary_lines:
1318
+ parts.append("")
1319
+ for line in summary_lines[-3:]:
1320
+ parts.append(line)
1321
+
1322
+ return "\n".join(parts)
1323
+
1324
+
1325
+ # ---------------------------------------------------------------------------
1326
+ # Pattern dispatch
1327
+ # ---------------------------------------------------------------------------
1328
+
1329
+ _GIT_LOG_SHAPE_FLAGS = ("--oneline", "--format", "--pretty", "--porcelain", "--null",
1330
+ "--name-status", "--name-only", "--numstat", "--stat", "--shortstat",
1331
+ "--dirstat", "--summary", "--patch", "--graph", "--raw", "--cc",
1332
+ "--diff", "--show-signature", "--abbrev-commit", "--walk-reflogs",
1333
+ "--left-right", "--cherry", "-L")
1334
+ _CONTENT_SHAPED_PATTERNS = frozenset({"find", "git_log"})
1335
+ _PIPE_TRIMMERS = frozenset({"head", "tail", "sort"})
1336
+ _GIT_LOG_PATH_SEP = "--"
1337
+ _GIT_LOG_SHAPE_LETTERS = frozenset("zpuc")
1338
+ _GIT_LOG_SHAPE_EXACT = frozenset({"-p", "-u", "-z", "-c", "-m", "-s"})
1339
+ _FIND_FPRINT_PREFIX = "-fprint"
1340
+ _FIND_RAW_ARGS = frozenset({"-print0", "-printf", "-exec", "-execdir", "-ok", "-okdir",
1341
+ "-delete", "-ls", "-fls"})
1342
+
1343
+
1344
+ def _detect_pattern(command_str):
1345
+ """Detect which compression pattern to use based on command."""
1346
+ # U9: user exclude runs BEFORE built-in detection so a user can remove a
1347
+ # built-in command from compression (returns None = raw passthrough).
1348
+ # User add runs AFTER built-in detection (at the bottom) so it only
1349
+ # extends, never replaces a built-in handler.
1350
+ try:
1351
+ from command_filters import get_effective_filters
1352
+ eff = get_effective_filters()
1353
+ if eff.is_user_excluded(command_str):
1354
+ return None
1355
+ except Exception:
1356
+ pass
1357
+
1358
+ try:
1359
+ tokens = shlex.split(command_str)
1360
+ except ValueError:
1361
+ return None
1362
+
1363
+ if not tokens:
1364
+ return None
1365
+
1366
+ # Pipelines: dispatch on the stage that DEFINES the output shape. The last
1367
+ # stage usually does -- `cat f | grep X` produces grep output and must get
1368
+ # the aggressive search summarizer, exactly like a bare `grep X f`, not the
1369
+ # timid generic path. But a terminal TRIMMER (`head`/`tail`/`sort`) has no
1370
+ # handler of its own; there we fall back to the FIRST stage, which still
1371
+ # defines the shape (`du | sort | head` -> du). So: try the last stage, then
1372
+ # the first. shlex keeps a quoted pipe (`grep 'a|b'`) inside its token, so
1373
+ # only a real stage-separator `|` splits here. Only reached for read-only
1374
+ # pipelines (the PostToolUse hook gates on is_read_only_pipeline first).
1375
+ if "|&" in tokens or ("|" not in tokens and any("|" in t for t in tokens)):
1376
+ # `|&` is a pipe too, and `f|sed` is one when written without spaces.
1377
+ # Re-tokenize with punctuation split off; quoted `|` stays inside its token.
1378
+ try:
1379
+ lexer = shlex.shlex(command_str, posix=True, punctuation_chars=True)
1380
+ lexer.whitespace_split = True
1381
+ punct = list(lexer)
1382
+ if "|" in punct or "|&" in punct:
1383
+ tokens = ["|" if t == "|&" else t for t in punct]
1384
+ except ValueError:
1385
+ return None
1386
+
1387
+ if "|" in tokens:
1388
+ pipes = [i for i, t in enumerate(tokens) if t == "|"]
1389
+ last_stage = tokens[pipes[-1] + 1:]
1390
+ first_stage = tokens[:pipes[0]]
1391
+ later_stages, cur_stage = [], []
1392
+ for t in tokens:
1393
+ if t == "|":
1394
+ later_stages.append(cur_stage)
1395
+ cur_stage = []
1396
+ else:
1397
+ cur_stage.append(t)
1398
+ later_stages.append(cur_stage)
1399
+ first_p = _detect_pattern(" ".join(shlex.quote(t) for t in first_stage)) if first_stage else None
1400
+ if first_p in _CONTENT_SHAPED_PATTERNS and all(
1401
+ next((t for t in st if "=" not in t), "") in _PIPE_TRIMMERS
1402
+ for st in later_stages[1:]):
1403
+ return first_p # `| head`, `| tail`, `| sort` keep the list shape
1404
+ for stage in (last_stage, first_stage):
1405
+ if stage:
1406
+ p = _detect_pattern(" ".join(shlex.quote(t) for t in stage))
1407
+ if p is not None:
1408
+ if stage is first_stage and p in _CONTENT_SHAPED_PATTERNS:
1409
+ # find / git log output is summarized only when every
1410
+ # later stage merely trims or orders it. cut, uniq,
1411
+ # xargs, awk, sed, wc, stat ... change the content, so
1412
+ # the result is no longer a path list / commit log.
1413
+ stages, cur_stage = [], []
1414
+ for t in tokens:
1415
+ if t == "|":
1416
+ stages.append(cur_stage)
1417
+ cur_stage = []
1418
+ else:
1419
+ cur_stage.append(t)
1420
+ stages.append(cur_stage)
1421
+ for later in stages[1:]:
1422
+ name = next((t for t in later if "=" not in t), "")
1423
+ if name not in _PIPE_TRIMMERS:
1424
+ return "find_raw" if p.startswith("find") else "git_log_basic"
1425
+ return p
1426
+ return None
1427
+
1428
+ # Strip leading env vars
1429
+ cmd_start = 0
1430
+ while cmd_start < len(tokens) and "=" in tokens[cmd_start]:
1431
+ cmd_start += 1
1432
+
1433
+ if cmd_start >= len(tokens):
1434
+ return None
1435
+
1436
+ cmd = tokens[cmd_start]
1437
+ subcmd = tokens[cmd_start + 1] if cmd_start + 1 < len(tokens) else ""
1438
+
1439
+ if cmd == "git":
1440
+ if subcmd in ("status",):
1441
+ # Only the default human-readable format is parseable. Any
1442
+ # flag that switches to machine-readable output (--porcelain
1443
+ # v1/v2, --short/-s, -z) routes to raw so the handler does not
1444
+ # swallow file lists it cannot recognise.
1445
+ git_args = tokens[cmd_start + 2:]
1446
+ for arg in git_args:
1447
+ if arg.startswith("--porcelain") or arg.startswith("--short"):
1448
+ return None
1449
+ # Short-flag clusters (-s, -sb, -bs, -z, -sz): any
1450
+ # cluster containing s or z changes the output format.
1451
+ if arg.startswith("-") and not arg.startswith("--"):
1452
+ if "s" in arg[1:] or "z" in arg[1:]:
1453
+ return None
1454
+ return "git_status"
1455
+ elif subcmd in ("log",):
1456
+ # Only the default human-readable format is summarized. Anything
1457
+ # that switches the output shape (custom/one-line formats, NUL
1458
+ # separation, porcelain, name/stat listings, patches, graph) keeps
1459
+ # the light cleanup so no machine-readable line is rewritten.
1460
+ for arg in tokens[cmd_start + 2:]:
1461
+ if arg == _GIT_LOG_PATH_SEP:
1462
+ break
1463
+ if arg.startswith(_GIT_LOG_SHAPE_FLAGS) or arg in _GIT_LOG_SHAPE_EXACT:
1464
+ return "git_log_basic"
1465
+ if arg.startswith("-") and not arg.startswith("--") and (
1466
+ set(arg[1:]) & _GIT_LOG_SHAPE_LETTERS):
1467
+ return "git_log_basic"
1468
+ return "git_log"
1469
+ elif subcmd in ("diff", "show"):
1470
+ return "git_diff"
1471
+ elif subcmd in ("branch",):
1472
+ # `git branch` lists branches — route through the list handler
1473
+ # so long branch lists truncate with a summary.
1474
+ return "list"
1475
+ elif cmd in ("pytest", "py.test") or (cmd in ("python", "python3") and subcmd == "-m" and
1476
+ cmd_start + 2 < len(tokens) and tokens[cmd_start + 2] == "pytest"):
1477
+ return "pytest"
1478
+ elif cmd in ("jest", "vitest") or (cmd == "npx" and subcmd in ("jest", "vitest")):
1479
+ return "jest"
1480
+ elif cmd == "rspec":
1481
+ return "pytest" # similar enough format
1482
+ # v5.1 test-runner extensions (dispatch-only: cypress/playwright/mocha/
1483
+ # karma all report in "passing/failing" terminology; the extended pytest
1484
+ # handler now reads all five formats.)
1485
+ elif cmd == "mocha" or (cmd == "npx" and subcmd == "mocha"):
1486
+ return "pytest"
1487
+ elif cmd == "karma" or (cmd == "npx" and subcmd == "karma"):
1488
+ return "pytest"
1489
+ elif cmd == "cypress" and subcmd == "run":
1490
+ return "pytest"
1491
+ elif cmd == "npx" and subcmd == "cypress":
1492
+ return "pytest"
1493
+ elif cmd == "playwright" and subcmd == "test":
1494
+ return "pytest"
1495
+ elif cmd == "npx" and subcmd == "playwright":
1496
+ return "pytest"
1497
+ elif cmd in ("go", "cargo") and subcmd == "test":
1498
+ return "pytest"
1499
+ # v5.8 test-runner extensions: unittest, tox, nox, gradle, mvn, deno, bun, ava
1500
+ elif cmd in ("python", "python3") and subcmd == "-m" and cmd_start + 2 < len(tokens) and tokens[cmd_start + 2] == "unittest":
1501
+ return "pytest"
1502
+ elif cmd in ("tox", "nox", "nox-sessions"):
1503
+ return "pytest"
1504
+ elif cmd in ("gradle", "gradlew", "./gradlew") and subcmd == "test":
1505
+ return "pytest"
1506
+ elif cmd == "mvn" and subcmd == "test":
1507
+ return "pytest"
1508
+ elif cmd == "deno" and subcmd == "test":
1509
+ return "pytest"
1510
+ elif cmd == "bun" and subcmd == "test":
1511
+ return "pytest"
1512
+ elif cmd == "ava" or (cmd == "npx" and subcmd == "ava"):
1513
+ return "pytest"
1514
+ elif cmd == "npm" and subcmd in ("install", "ci"):
1515
+ return "npm_install"
1516
+ elif cmd == "npm" and subcmd == "test":
1517
+ # `npm test` dispatches to whatever the project wires up, usually
1518
+ # jest/vitest/mocha. Route through the pytest handler, which
1519
+ # understands all of them.
1520
+ return "pytest"
1521
+ elif cmd in ("pip", "pip3") and subcmd == "install":
1522
+ return "npm_install"
1523
+ elif cmd == "cargo" and subcmd == "build":
1524
+ return "npm_install"
1525
+ elif cmd == "find":
1526
+ # Machine-oriented or acting find (NUL/printf/exec/delete/ls) is never
1527
+ # rewritten; a plain path list gets the directory-grouping summarizer.
1528
+ if any(a in _FIND_RAW_ARGS or a.startswith(_FIND_FPRINT_PREFIX) for a in tokens[cmd_start + 1:]):
1529
+ return "find_raw"
1530
+ return "find"
1531
+ elif cmd == "ls":
1532
+ return "ls"
1533
+ # v5.1 lint handlers
1534
+ elif cmd in ("eslint", "flake8", "pylint", "shellcheck", "rubocop"):
1535
+ return "lint"
1536
+ elif cmd == "ruff" and subcmd == "check":
1537
+ return "lint"
1538
+ elif cmd == "biome" and subcmd == "lint":
1539
+ return "lint"
1540
+ elif cmd == "golangci-lint" and subcmd == "run":
1541
+ return "lint"
1542
+ # v5.1 logs handler (read-only log inspection). `cat` is intentionally
1543
+ # NOT whitelisted — only tail and journalctl, which are log-specific.
1544
+ elif cmd in ("tail", "journalctl"):
1545
+ return "logs"
1546
+ # v5.1 tree handler
1547
+ elif cmd == "tree":
1548
+ return "tree"
1549
+ # v5.1 progress handler (docker build, docker pull)
1550
+ elif cmd == "docker" and subcmd in ("build", "pull"):
1551
+ return "progress"
1552
+ # v5.1 build handler
1553
+ elif cmd in ("tsc", "webpack", "esbuild"):
1554
+ return "build"
1555
+ elif cmd in ("vite", "next") and subcmd == "build":
1556
+ return "build"
1557
+ elif cmd == "go" and subcmd == "build":
1558
+ return "build"
1559
+ # v5.1 list handler
1560
+ elif cmd in ("pip", "pip3") and subcmd == "list":
1561
+ return "list"
1562
+ elif cmd == "npm" and subcmd == "ls":
1563
+ return "list"
1564
+ elif cmd == "pnpm" and subcmd == "list":
1565
+ return "list"
1566
+ elif cmd == "docker" and subcmd == "ps":
1567
+ return "list"
1568
+ elif cmd == "brew" and subcmd == "list":
1569
+ return "list"
1570
+ elif cmd == "sqlite3":
1571
+ return "sqlite3"
1572
+ elif cmd in ("wc", "du", "df"):
1573
+ return "disk_stats"
1574
+ elif cmd == "printenv":
1575
+ return "list"
1576
+ elif cmd == "docker" and subcmd in ("exec", "logs", "inspect"):
1577
+ if subcmd == "logs":
1578
+ return "logs"
1579
+ return "docker_output"
1580
+ elif cmd == "kubectl" and subcmd in ("get", "describe", "logs"):
1581
+ if subcmd == "logs":
1582
+ return "logs"
1583
+ return "k8s"
1584
+ elif cmd == "kubectl" and subcmd in ("top", "events"):
1585
+ return "k8s"
1586
+ elif cmd in ("gcloud", "aws", "az"):
1587
+ return "cloud_cli"
1588
+ elif cmd in ("jq", "yq"):
1589
+ return "json"
1590
+ elif cmd in ("python", "python3") and subcmd == "-m" and cmd_start + 2 < len(tokens) and tokens[cmd_start + 2] == "json.tool":
1591
+ return "json"
1592
+ elif cmd in ("csvtool", "mlr", "csvcut"):
1593
+ return "csv"
1594
+ elif cmd in ("node", "deno", "bun") and any(".json" in arg for arg in tokens[cmd_start + 1:]):
1595
+ return "json"
1596
+ # v5.9 search results handler (grep/ripgrep output)
1597
+ elif cmd in ("grep", "rg", "ag", "ack"):
1598
+ return "search_results"
1599
+
1600
+ # U9: user TOML command filters (add only — exclude already ran at the
1601
+ # top). Built-in detection ran first, so user add only extends, never
1602
+ # replaces a built-in handler for the same command. The _is_safe_add gate
1603
+ # already ran in the loader, so add entries are read-only and
1604
+ # handler-validated.
1605
+ try:
1606
+ add_entry = eff.find_user_add(command_str)
1607
+ if add_entry is not None:
1608
+ return add_entry.handler
1609
+ except Exception:
1610
+ pass
1611
+
1612
+ return None
1613
+
1614
+
1615
+ def _compress_sqlite3(output):
1616
+ """Compress sqlite3 query output: truncate large result sets."""
1617
+ lines = output.strip().splitlines()
1618
+ if len(lines) < 30:
1619
+ return output
1620
+ header = lines[:2]
1621
+ data = lines[2:22]
1622
+ result = header + data
1623
+ result.append(f"... ({len(lines) - 22} more rows, {len(lines)} total)")
1624
+ return "\n".join(result)
1625
+
1626
+
1627
+ def _compress_disk_stats(output):
1628
+ """Compress du/df/wc output: keep header + totals."""
1629
+ lines = output.strip().splitlines()
1630
+ if len(lines) < 20:
1631
+ return output
1632
+ head = lines[:3]
1633
+ tail = lines[-5:]
1634
+ kept = len(head) + len(tail)
1635
+ result = head
1636
+ result.append(f"... ({len(lines) - kept} entries omitted)")
1637
+ result.extend(tail)
1638
+ return "\n".join(result)
1639
+
1640
+
1641
+ def _compress_docker_output(output):
1642
+ """Compress docker exec/logs/inspect output."""
1643
+ stripped = output.strip()
1644
+ if stripped.startswith("[") or stripped.startswith("{"):
1645
+ try:
1646
+ data = json.loads(stripped[:200_000])
1647
+ if isinstance(data, list) and len(data) > 0:
1648
+ first_preview = json.dumps(data[0], indent=2)[:500]
1649
+ return f"[{len(data)} items, first:\n{first_preview}\n...]"
1650
+ elif isinstance(data, dict):
1651
+ keys = list(data.keys())[:10]
1652
+ return f"Object with {len(data)} keys: {', '.join(keys)}"
1653
+ except (json.JSONDecodeError, RecursionError, TypeError):
1654
+ pass
1655
+ return _compress_logs(output)
1656
+
1657
+
1658
+ # ---------------------------------------------------------------------------
1659
+ # JSON / CSV / stack-trace / k8s / cloud-CLI handlers
1660
+ # ---------------------------------------------------------------------------
1661
+
1662
+ _JSON_MIN_CHARS = 500
1663
+ _JSON_MAX_PARSE = 500_000
1664
+ _JSON_CELL_CAP = 100
1665
+ _JSON_MAX_COLS = 40
1666
+ _JSON_MIN_ROWS = 3
1667
+ _JSON_TOTAL_CAP = 8192
1668
+ _JSON_MIN_REDUCTION = 0.40
1669
+
1670
+
1671
+ def _compress_json(output):
1672
+ """Compress JSON output: columnar for arrays-of-dicts, key-summary for objects."""
1673
+ stripped = output.strip()
1674
+ if len(stripped) < _JSON_MIN_CHARS:
1675
+ return output
1676
+ if not (stripped.startswith("[") or stripped.startswith("{")):
1677
+ return output
1678
+ try:
1679
+ data = json.loads(stripped[:_JSON_MAX_PARSE])
1680
+ except (json.JSONDecodeError, RecursionError, TypeError):
1681
+ return output
1682
+
1683
+ if isinstance(data, list):
1684
+ dict_rows = [r for r in data if isinstance(r, dict)]
1685
+ if len(dict_rows) >= max(_JSON_MIN_ROWS, int(len(data) * 0.8)):
1686
+ cols: list[str] = []
1687
+ seen: set[str] = set()
1688
+ for row in dict_rows:
1689
+ for k in row.keys():
1690
+ if k not in seen:
1691
+ seen.add(k)
1692
+ cols.append(str(k))
1693
+ if cols and len(cols) <= _JSON_MAX_COLS:
1694
+ def _cell(v) -> str:
1695
+ s = v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)
1696
+ s = s.replace("\n", " ").replace("\t", " ")
1697
+ return s[:_JSON_CELL_CAP] + ("…" if len(s) > _JSON_CELL_CAP else "")
1698
+
1699
+ lines = [
1700
+ f"JSON array ({len(data)} items), columnar (schema-stripped, values preserved):",
1701
+ "cols: " + ", ".join(cols),
1702
+ ]
1703
+ for row in data:
1704
+ if isinstance(row, dict):
1705
+ lines.append("- " + " | ".join(_cell(row.get(c, "")) for c in cols))
1706
+ else:
1707
+ lines.append("- " + _cell(row))
1708
+ result = "\n".join(lines)
1709
+ if len(result) <= _JSON_TOTAL_CAP and len(result) < len(stripped) * (1.0 - _JSON_MIN_REDUCTION):
1710
+ return result
1711
+ if len(data) > 20:
1712
+ first = json.dumps(data[0], indent=2, ensure_ascii=False)[:500]
1713
+ return f"JSON array ({len(data)} items), first:\n{first}\n... ({len(data) - 1} more items)"
1714
+ return output
1715
+
1716
+ if isinstance(data, dict):
1717
+ keys = list(data.keys())[:50]
1718
+ result = f"JSON object ({len(data)} keys): {', '.join(keys)}"
1719
+ if len(result) < len(stripped) * 0.9:
1720
+ return result
1721
+ return output
1722
+
1723
+ return output
1724
+
1725
+
1726
+ _CSV_MIN_LINES = 20
1727
+ _CSV_MAX_COLS = 40
1728
+ _CSV_CELL_CAP = 80
1729
+ _CSV_TOTAL_CAP = 8192
1730
+ _CSV_PREVIEW_ROWS = 15
1731
+
1732
+
1733
+ def _compress_csv(output):
1734
+ """Compress CSV/TSV output: keep header + first rows, summarize the rest."""
1735
+ lines = output.strip().splitlines()
1736
+ if len(lines) < _CSV_MIN_LINES:
1737
+ return output
1738
+ delimiter = "\t" if "\t" in lines[0] else ","
1739
+ try:
1740
+ import csv as _csv
1741
+ reader = _csv.reader(lines, delimiter=delimiter)
1742
+ header = next(reader, None)
1743
+ if not header:
1744
+ return output
1745
+ cols = header[:_CSV_MAX_COLS]
1746
+ data_rows = list(reader)
1747
+ total = len(data_rows)
1748
+ if total < _CSV_MIN_LINES - 1:
1749
+ return output
1750
+ preview = data_rows[:_CSV_PREVIEW_ROWS]
1751
+ lines_out = [delimiter.join(header)]
1752
+ for row in preview:
1753
+ row = row[:_CSV_MAX_COLS]
1754
+ lines_out.append(delimiter.join(
1755
+ (c[:_CSV_CELL_CAP] + "…" if len(c) > _CSV_CELL_CAP else c) for c in row
1756
+ ))
1757
+ lines_out.append(f"... ({total - len(preview)} more rows, {total} total)")
1758
+ result = "\n".join(lines_out)
1759
+ if len(result) > _CSV_TOTAL_CAP:
1760
+ lines_out = lines_out[:2] + [lines_out[-1]]
1761
+ result = "\n".join(lines_out)
1762
+ return result
1763
+ except Exception:
1764
+ return output
1765
+
1766
+
1767
+ _STACK_TRACE_FRAME_RE = re.compile(r'^\s+(?:at\s+)?(.+?)\s+')
1768
+ _STACK_TRACE_FILE_RE = re.compile(r'\((.+?):(\d+)(?::(\d+))?\)')
1769
+ _STACK_TRACE_MIN_LINES = 15
1770
+ _STACK_TRACE_MAX_FRAMES = 20
1771
+ _STACK_TRACE_MARKERS = re.compile(
1772
+ r'(?:Traceback \(most recent call last\)|'
1773
+ r'^\s+at\s+[\w.$]+\(|'
1774
+ r'Caused by:|'
1775
+ r'Exception in thread|'
1776
+ r'^\s+at\s+[\w.]+\([^)]+:\d+\))',
1777
+ re.MULTILINE
1778
+ )
1779
+
1780
+
1781
+ def _looks_like_stack_trace(text: str) -> bool:
1782
+ """Check if output contains a stack trace worth compressing."""
1783
+ lines = text.splitlines()
1784
+ if len(lines) < _STACK_TRACE_MIN_LINES:
1785
+ return False
1786
+ return bool(_STACK_TRACE_MARKERS.search(text))
1787
+
1788
+
1789
+ def _compress_stack_trace(output):
1790
+ """Compress stack traces: keep exception message + top N frames, summarize the rest."""
1791
+ lines = output.splitlines()
1792
+ if len(lines) < _STACK_TRACE_MIN_LINES:
1793
+ return output
1794
+ exception_lines: list[str] = []
1795
+ frames: list[str] = []
1796
+ in_traceback = False
1797
+ for line in lines:
1798
+ stripped = line.strip()
1799
+ # Detect start of traceback section
1800
+ if stripped.startswith("Traceback") or stripped.startswith("Exception in thread"):
1801
+ in_traceback = True
1802
+ exception_lines.append(line)
1803
+ continue
1804
+ # Lines after the traceback section that look like the final exception
1805
+ # (e.g. "ValueError: ...", "java.lang.NPE")
1806
+ if in_traceback and not stripped.startswith("File ") and not stripped.startswith("at ") and not _STACK_TRACE_FRAME_RE.match(line):
1807
+ # This is the exception message line (after all frames)
1808
+ if stripped and not stripped.startswith("..."):
1809
+ exception_lines.append(line)
1810
+ continue
1811
+ if in_traceback and (stripped.startswith("File ") or stripped.startswith("at ") or _STACK_TRACE_FRAME_RE.match(line)):
1812
+ frames.append(line)
1813
+ elif not in_traceback:
1814
+ exception_lines.append(line)
1815
+ else:
1816
+ frames.append(line)
1817
+ if not frames:
1818
+ return output
1819
+ kept_frames = frames[:_STACK_TRACE_MAX_FRAMES]
1820
+ omitted = len(frames) - len(kept_frames)
1821
+ result_lines = list(exception_lines)
1822
+ result_lines.extend(kept_frames)
1823
+ if omitted > 0:
1824
+ result_lines.append(f"... ({omitted} stack frames omitted)")
1825
+ result = "\n".join(result_lines)
1826
+ if len(result) >= len(output) * 0.9:
1827
+ return output
1828
+ return result
1829
+
1830
+
1831
+ _K8S_MIN_LINES = 20
1832
+ _K8S_MAX_COLS = 40
1833
+ _K8S_CELL_CAP = 60
1834
+ _K8S_PREVIEW_ROWS = 15
1835
+
1836
+
1837
+ def _compress_k8s(output):
1838
+ """Compress kubectl get/describe/top/events output: keep header + preview rows."""
1839
+ lines = output.strip().splitlines()
1840
+ if len(lines) < _K8S_MIN_LINES:
1841
+ return output
1842
+ if lines[0].startswith("NAME") or lines[0].startswith("NAMESPACE"):
1843
+ header = lines[0].split()
1844
+ data_lines = lines[1:]
1845
+ total = len(data_lines)
1846
+ if total < _K8S_MIN_LINES - 1:
1847
+ return output
1848
+ preview = data_lines[:_K8S_PREVIEW_ROWS]
1849
+ result_lines = [lines[0]]
1850
+ for row in preview:
1851
+ result_lines.append(row)
1852
+ rest = data_lines[_K8S_PREVIEW_ROWS:]
1853
+ # Keep the NAME (first column) of every dropped row so "is pod X running?"
1854
+ # is answerable; a name not listed here genuinely does not exist. Without
1855
+ # this the agent infers false absence from the truncated preview.
1856
+ rest_names = [r.split()[0] for r in rest if r.split()]
1857
+ if rest_names:
1858
+ result_lines.append(
1859
+ f"... plus {len(rest)} more rows ({total} total; names only, "
1860
+ f"a name not listed has no matching resource): {', '.join(rest_names)}")
1861
+ result = "\n".join(result_lines)
1862
+ return result
1863
+ return _compress_logs(output)
1864
+
1865
+
1866
+ _CLOUD_CLI_MIN_CHARS = 1000
1867
+ _CLOUD_CLI_HEAD = 15
1868
+ _CLOUD_CLI_TAIL = 10
1869
+
1870
+
1871
+ def _compress_cloud_cli(output):
1872
+ """Compress gcloud/aws/az output: keep head + tail, preserve important lines."""
1873
+ lines = output.strip().splitlines()
1874
+ if len(lines) < _CLOUD_CLI_MIN_CHARS // 40:
1875
+ return output
1876
+ collapsed: list[str] = []
1877
+ run_val = None
1878
+ run_count = 0
1879
+ for ln in lines:
1880
+ if ln == run_val:
1881
+ run_count += 1
1882
+ else:
1883
+ if run_val is not None:
1884
+ collapsed.append(f"{run_val} (x{run_count})" if run_count > 1 else run_val)
1885
+ run_val = ln
1886
+ run_count = 1
1887
+ if run_val is not None:
1888
+ collapsed.append(f"{run_val} (x{run_count})" if run_count > 1 else run_val)
1889
+ if len(collapsed) <= _CLOUD_CLI_HEAD + _CLOUD_CLI_TAIL:
1890
+ return "\n".join(collapsed)
1891
+ head = collapsed[:_CLOUD_CLI_HEAD]
1892
+ tail = collapsed[len(collapsed) - _CLOUD_CLI_TAIL:]
1893
+ middle = collapsed[_CLOUD_CLI_HEAD:len(collapsed) - _CLOUD_CLI_TAIL]
1894
+ important = [ln for ln in middle if _GENERIC_IMPORTANT.search(ln)][:_CLOUD_CLI_HEAD * 5]
1895
+ omitted = len(middle) - len(important)
1896
+ out = list(head)
1897
+ if important:
1898
+ out.append(f"... {omitted} lines omitted (kept {len(important)} error/warning lines) ...")
1899
+ out.extend(important)
1900
+ else:
1901
+ out.append(f"... {omitted} lines omitted ...")
1902
+ out.extend(tail)
1903
+ return "\n".join(out)
1904
+
1905
+
1906
+ _SEARCH_FILE_LINE_RE = re.compile(r'^(.+?):(\d+)[:](.*)$')
1907
+
1908
+
1909
+ def _compress_search_results(output):
1910
+ """Compress grep/ripgrep/ag/ack output: group by file, keep top matches per file.
1911
+
1912
+ Search output is typically `file:line:content` (or `file:line:content` with
1913
+ color codes). For large result sets, we group by file, keep the first N
1914
+ matches per file, and summarize the rest. Files with only 1-2 matches are
1915
+ kept verbatim. The goal is the same as a skilled human skimming search
1916
+ results: see which files have hits, see a few representative lines, skip
1917
+ the rest.
1918
+ """
1919
+ if not output:
1920
+ return output
1921
+ lines = output.strip().splitlines()
1922
+ if len(lines) < 30:
1923
+ return output
1924
+
1925
+ # Strip ANSI color codes from grep/rg output
1926
+ cleaned = _strip_ansi(output)
1927
+ lines = cleaned.strip().splitlines()
1928
+ if len(lines) < 30:
1929
+ return output
1930
+
1931
+ # Group lines by file (non-greedy up to :digits: to handle colons in filenames)
1932
+ files: dict[str, list[str]] = {}
1933
+ no_file: list[str] = []
1934
+ for ln in lines:
1935
+ m = _SEARCH_FILE_LINE_RE.match(ln)
1936
+ if m:
1937
+ fname = m.group(1)
1938
+ files.setdefault(fname, []).append(ln)
1939
+ else:
1940
+ no_file.append(ln)
1941
+
1942
+ if not files:
1943
+ return output # not file:line format, don't compress
1944
+
1945
+ _MAX_PER_FILE = 3
1946
+ _MAX_FILES = 20
1947
+ result: list[str] = []
1948
+ file_count = 0
1949
+ file_items = list(files.items())
1950
+ for fname, file_lines in file_items:
1951
+ if file_count >= _MAX_FILES:
1952
+ break
1953
+ if len(file_lines) <= _MAX_PER_FILE:
1954
+ result.extend(file_lines)
1955
+ else:
1956
+ result.extend(file_lines[:_MAX_PER_FILE])
1957
+ result.append(f" ... {len(file_lines) - _MAX_PER_FILE} more matches in {fname} ...")
1958
+ file_count += 1
1959
+
1960
+ # Keep EVERY matching filename (cheap) so "does file X match?" stays
1961
+ # answerable; only per-line CONTENT past the top-N is dropped, never names.
1962
+ if file_count < len(file_items):
1963
+ result.append(f"... plus {len(file_items) - file_count} more files with matches "
1964
+ f"(filenames + counts, content omitted):")
1965
+ for fname, file_lines in file_items[file_count:]:
1966
+ result.append(f" {fname}: {len(file_lines)} matches")
1967
+
1968
+ if no_file:
1969
+ result.append("")
1970
+ # "Binary file X matches" lines name a matching file; keep ALL of them so
1971
+ # the banner's "a file not listed has NO matches" stays true for binaries.
1972
+ binary = [ln for ln in no_file if ln.startswith("Binary file ") and " matches" in ln]
1973
+ other = [ln for ln in no_file if not (ln.startswith("Binary file ") and " matches" in ln)]
1974
+ result.extend(binary)
1975
+ result.extend(other[:10])
1976
+ if len(other) > 10:
1977
+ result.append(f"... {len(other) - 10} more non-file lines omitted ...")
1978
+
1979
+ total_matches = sum(len(v) for v in files.values())
1980
+ result.insert(0, f"[Search results: {total_matches} matches across {len(files)} files. "
1981
+ f"ALL matching filenames listed; per-line content shown for the top "
1982
+ f"{_MAX_FILES}. A file not listed here has NO matches.]")
1983
+ return "\n".join(result)
1984
+
1985
+
1986
+ _PATTERN_HANDLERS = {
1987
+ "git_status": _compress_git_status,
1988
+ "git_log": _compress_git_log,
1989
+ "git_log_basic": _compress_git_log_basic,
1990
+ "find": _compress_find,
1991
+ "find_raw": lambda output: output,
1992
+ "git_diff": _compress_git_diff,
1993
+ "pytest": _compress_pytest,
1994
+ "jest": _compress_jest,
1995
+ "npm_install": _compress_npm_install,
1996
+ "ls": _compress_ls,
1997
+ "lint": _compress_lint,
1998
+ "logs": _compress_logs,
1999
+ "tree": _compress_tree,
2000
+ "progress": _compress_progress,
2001
+ "list": _compress_list,
2002
+ "build": _compress_build,
2003
+ "sqlite3": _compress_sqlite3,
2004
+ "disk_stats": _compress_disk_stats,
2005
+ "docker_output": _compress_docker_output,
2006
+ "json": _compress_json,
2007
+ "csv": _compress_csv,
2008
+ "stack_trace": _compress_stack_trace,
2009
+ "k8s": _compress_k8s,
2010
+ "cloud_cli": _compress_cloud_cli,
2011
+ "search_results": _compress_search_results,
2012
+ }
2013
+
2014
+ # Maps _detect_pattern() output to the feature name stored in compression_events.
2015
+ _COMPRESS_FEATURE_MAP = {
2016
+ "git_status": "bash_compress_git",
2017
+ "git_log": "bash_compress_git",
2018
+ "git_log_basic": "bash_compress_git",
2019
+ "find": "bash_compress_ls",
2020
+ "find_raw": "bash_compress_ls",
2021
+ "git_diff": "bash_compress_git",
2022
+ "pytest": "bash_compress_pytest",
2023
+ "jest": "bash_compress_jest",
2024
+ "npm_install": "bash_compress_npm",
2025
+ "ls": "bash_compress_ls",
2026
+ "lint": "bash_compress_lint",
2027
+ "logs": "bash_compress_logs",
2028
+ "tree": "bash_compress_tree",
2029
+ "progress": "bash_compress_progress",
2030
+ "list": "bash_compress_list",
2031
+ "build": "bash_compress_build",
2032
+ "sqlite3": "bash_compress_build",
2033
+ "disk_stats": "bash_compress_list",
2034
+ "docker_output": "bash_compress_build",
2035
+ "json": "bash_compress_json",
2036
+ "csv": "bash_compress_csv",
2037
+ "stack_trace": "bash_compress_stack",
2038
+ "k8s": "bash_compress_k8s",
2039
+ "cloud_cli": "bash_compress_cloud",
2040
+ "search_results": "bash_compress_search",
2041
+ }
2042
+
2043
+
2044
+ # ---------------------------------------------------------------------------
2045
+ # Main entry point
2046
+ # ---------------------------------------------------------------------------
2047
+
2048
+ _GENERIC_MIN_CHARS = 2000 # only compress reasonably large unmatched output
2049
+ _GENERIC_HEAD = 20 # lines kept from the top
2050
+ _GENERIC_TAIL = 20 # lines kept from the bottom
2051
+ _GENERIC_IMPORTANT = re.compile(
2052
+ r"\b(error|errors|warn|warning|fail|failed|failure|exception|traceback|"
2053
+ r"fatal|panic|denied|refused|timeout|timed out)\b",
2054
+ re.IGNORECASE,
2055
+ )
2056
+
2057
+
2058
+ def _compress_generic(text):
2059
+ """Generic structural/log compression for output matching no known pattern.
2060
+
2061
+ Collapses consecutive duplicate lines, keeps head + tail, and preserves
2062
+ every error/warning line anywhere in the body. Deterministic, fail-open
2063
+ (caller wraps in try/except), and credential lines are independently
2064
+ re-injected by the PRE-compression scan in compress().
2065
+ """
2066
+ lines = text.splitlines()
2067
+
2068
+ # Collapse runs of identical consecutive lines into "<line> (xN)".
2069
+ collapsed: list[str] = []
2070
+ run_val = None
2071
+ run_count = 0
2072
+
2073
+ def _flush_run():
2074
+ if run_val is None:
2075
+ return
2076
+ if run_count > 1:
2077
+ collapsed.append(f"{run_val} (x{run_count})")
2078
+ else:
2079
+ collapsed.append(run_val)
2080
+
2081
+ for ln in lines:
2082
+ if ln == run_val:
2083
+ run_count += 1
2084
+ else:
2085
+ _flush_run()
2086
+ run_val = ln
2087
+ run_count = 1
2088
+ _flush_run()
2089
+
2090
+ if len(collapsed) <= _GENERIC_HEAD + _GENERIC_TAIL:
2091
+ return "\n".join(collapsed)
2092
+
2093
+ head = collapsed[:_GENERIC_HEAD]
2094
+ tail = collapsed[len(collapsed) - _GENERIC_TAIL:]
2095
+ middle = collapsed[_GENERIC_HEAD:len(collapsed) - _GENERIC_TAIL]
2096
+ _IMPORTANT_CAP = _GENERIC_HEAD * 10
2097
+ important = [ln for ln in middle if _GENERIC_IMPORTANT.search(ln)][:_IMPORTANT_CAP]
2098
+ omitted = len(middle) - len(important)
2099
+
2100
+ out: list[str] = list(head)
2101
+ if important:
2102
+ out.append(f"... {omitted} lines omitted (kept {len(important)} error/warning lines) ...")
2103
+ out.extend(important)
2104
+ else:
2105
+ out.append(f"... {omitted} lines omitted ...")
2106
+ out.extend(tail)
2107
+ return "\n".join(out)
2108
+
2109
+
2110
+ def _baseline_visible_chars(raw_chars):
2111
+ """Chars Claude Code would show for a raw tool result of ``raw_chars`` chars.
2112
+
2113
+ UNIT C baseline: results at or under CC's persisted-output threshold are
2114
+ shown in full; larger results are collapsed to the ~2.2KB stub (CC 2.1.247
2115
+ behavior -- see the CC_PERSISTED_OUTPUT_* constants above).
2116
+ """
2117
+ if raw_chars <= CC_PERSISTED_OUTPUT_THRESHOLD_CHARS:
2118
+ return raw_chars
2119
+ return CC_PERSISTED_OUTPUT_STUB_CHARS
2120
+
2121
+
2122
+ def _unicode_safe_head(text, limit):
2123
+ """Keep the cap without splitting marks, format controls or ZWJ runs.
2124
+
2125
+ Walk only the bounded visible prefix, never an unbounded combining tail.
2126
+ Dropping the whole boundary cluster preserves its meaning in the archive
2127
+ and prevents an over-cap preview from hiding the recovery pointer.
2128
+ This is a conservative boundary guard, not a full Unicode segmenter.
2129
+ """
2130
+ cut = min(max(0, limit), len(text))
2131
+ if cut == len(text):
2132
+ return text
2133
+ safe = 0
2134
+ for boundary in range(1, cut + 1):
2135
+ following = text[boundary]
2136
+ code = ord(following)
2137
+ attaches = (unicodedata.category(following) in ('Mn', 'Mc', 'Me', 'Cf')
2138
+ or 0x1F3FB <= code <= 0x1F3FF)
2139
+ if not attaches and text[boundary - 1] != '\u200d':
2140
+ safe = boundary
2141
+ return text[:safe]
2142
+
2143
+
2144
+ def _enforce_baseline_invariant(text, raw_output, archive_key):
2145
+ """Never show the model MORE chars than the CC baseline would.
2146
+
2147
+ Claude Code 2.1.247 already truncates any tool result larger than
2148
+ ~30KB down to a ~2.2KB "<persisted-output>" stub on its own, so the
2149
+ baseline the model sees for such outputs is only the stub -- NOT the
2150
+ raw result. When our compressed preview + archive pointer would exceed
2151
+ that baseline, shrink the preview to fit UNDER the stub while keeping
2152
+ the pointer intact, so the full original stays retrievable via
2153
+ `expand <key>` and CC does not re-stub (and thereby swallow) our output.
2154
+
2155
+ Three branches:
2156
+ * text already <= baseline -> unchanged (the common case).
2157
+ * text IS the raw output -> left untouched: CC truncates raw output
2158
+ at its own layer to the same stub it would show without Token
2159
+ Optimizer, i.e. exactly the baseline (defer, fail-open, no data
2160
+ loss beyond what CC itself does).
2161
+ * lossy preview (pointer failed to build) -> keep the most useful
2162
+ head of the preview, capped at the baseline.
2163
+ """
2164
+ cap = _baseline_visible_chars(len(raw_output))
2165
+ if len(text) <= cap:
2166
+ return text
2167
+ if text == raw_output:
2168
+ return text # CC stubs raw output itself; that IS the baseline
2169
+ if archive_key:
2170
+ try:
2171
+ from archive_result import build_archive_pointer
2172
+ pointer = build_archive_pointer("", len(raw_output), archive_key)
2173
+ if pointer and len(pointer) <= cap:
2174
+ # text is preview + "\n\n" + pointer; text > cap guarantees
2175
+ # text[:cap - len(pointer)] cuts inside the preview, never
2176
+ # into the pointer region, so no duplicated pointer bytes.
2177
+ return _unicode_safe_head(text, cap - len(pointer)) + pointer
2178
+ except Exception:
2179
+ pass # fall through to plain head-cap
2180
+ return _unicode_safe_head(text, cap)
2181
+
2182
+
2183
+ def compress(command_str, raw_output, returncode=0, stderr=""):
2184
+ """Compress CLI output based on command pattern.
2185
+
2186
+ Returns compressed output. On any issue, returns raw output.
2187
+ Token preservation scan runs FIRST on raw output.
2188
+
2189
+ Tee-on-failure: if the command failed (non-zero exit) or printed error
2190
+ patterns on stderr even with exit 0, return raw output verbatim. Never
2191
+ compress failure output — the user needs the full signal to debug.
2192
+ """
2193
+ if _looks_like_failure(returncode, stderr):
2194
+ return raw_output # fail-open tee: full output, unchanged
2195
+
2196
+ if not raw_output or len(raw_output) < 100:
2197
+ return raw_output # too small to bother
2198
+
2199
+ # Strip ANSI codes (always safe)
2200
+ cleaned = _strip_ansi(raw_output)
2201
+
2202
+ # PRE-compression token preservation scan (credentials + errors), plus
2203
+ # rarity-based needle preservation: a line carrying a distinctive token
2204
+ # (UUID/URL/hash/id) that the user is likely grepping FOR must survive the
2205
+ # summarizer, or the model re-runs a narrower query and spends back the
2206
+ # tokens we just saved. Both feed the shared re-injection path below (capped
2207
+ # at _MAX_REINJECTED_LINES, so a needle-dense log still compresses).
2208
+ # The git log / find summarizers keep every hash and path themselves, so
2209
+ # re-injecting "rare token" lines would only paste raw "commit <hash>" lines
2210
+ # back; they keep only the credential/error scan.
2211
+ _summarizer_pattern = False
2212
+ try:
2213
+ _summarizer_pattern = _detect_pattern(command_str) in ("git_log", "find")
2214
+ except Exception:
2215
+ pass
2216
+ preserved_lines = _find_preserved_lines(cleaned)
2217
+ if not _summarizer_pattern:
2218
+ preserved_lines = preserved_lines | _find_distinctive_lines(cleaned)
2219
+
2220
+ # Detect pattern
2221
+ pattern = _detect_pattern(command_str)
2222
+ if pattern is None:
2223
+ # Output-based detection: stack traces can appear from any command.
2224
+ # Check before generic compression so tracebacks get frame-limited.
2225
+ if _looks_like_stack_trace(cleaned):
2226
+ pattern = "stack_trace"
2227
+ if pattern is None:
2228
+ # U4: generic structural/log compression for unmatched large output.
2229
+ # Small outputs pass through; large ones get deduped + head/tail with
2230
+ # all error/warning lines kept. The shared 10% gate below still applies.
2231
+ if len(cleaned) < _GENERIC_MIN_CHARS:
2232
+ return cleaned
2233
+ try:
2234
+ compressed = _compress_generic(cleaned)
2235
+ except Exception:
2236
+ return cleaned # fail open
2237
+ else:
2238
+ handler = _PATTERN_HANDLERS.get(pattern)
2239
+ if handler is None:
2240
+ return cleaned
2241
+ try:
2242
+ if pattern == "find":
2243
+ compressed = handler(cleaned, command_str)
2244
+ else:
2245
+ compressed = handler(cleaned)
2246
+ except Exception:
2247
+ return cleaned # fail open
2248
+
2249
+ # Re-inject preserved lines that were stripped by compression.
2250
+ # Uses exact-line membership (not substring) so a short preserved
2251
+ # line that happens to be contained inside a longer compressed line
2252
+ # is still emitted on its own rather than silently folded into the
2253
+ # larger line.
2254
+ #
2255
+ # Cap at _MAX_REINJECTED_LINES: when a credential pattern appears on
2256
+ # most lines (e.g. grep for API keys), re-injecting all of them
2257
+ # defeats compression. The first N are re-injected; the full original
2258
+ # is already archived via progressive disclosure for retrieval.
2259
+ if preserved_lines:
2260
+ _MAX_REINJECTED_LINES = max(1, min(20, len(compressed.splitlines()) // 5))
2261
+ original_lines = cleaned.splitlines()
2262
+ compressed_line_set = set(compressed.splitlines())
2263
+ appended: list[str] = []
2264
+ injected = 0
2265
+ for line_idx in preserved_lines:
2266
+ if injected >= _MAX_REINJECTED_LINES:
2267
+ break
2268
+ if line_idx < len(original_lines):
2269
+ preserved_line = original_lines[line_idx]
2270
+ if _summarizer_pattern and preserved_line.strip() in compressed:
2271
+ continue # already carried by a summary line
2272
+ if preserved_line not in compressed_line_set:
2273
+ appended.append(preserved_line)
2274
+ compressed_line_set.add(preserved_line)
2275
+ injected += 1
2276
+ if appended:
2277
+ if injected < len(preserved_lines):
2278
+ appended.append(
2279
+ f"... {len(preserved_lines) - injected} more credential-bearing lines "
2280
+ f"archived in full original (retrieve via expand key) ..."
2281
+ )
2282
+ compressed = compressed + "\n" + "\n".join(appended)
2283
+
2284
+ try:
2285
+ from token_estimate import estimate_tokens as _est
2286
+ except Exception:
2287
+ _est = lambda t: len(t.encode("utf-8", errors="replace")) // 4
2288
+ original_tokens = _est(cleaned)
2289
+ compressed_tokens = _est(compressed)
2290
+ if original_tokens > 0 and (1.0 - compressed_tokens / original_tokens) < 0.10:
2291
+ return cleaned # not worth the risk
2292
+
2293
+ return compressed
2294
+
2295
+
2296
+ def _run_original(command_args):
2297
+ """Execute the command uncompressed and relay its output and exit code."""
2298
+ try:
2299
+ result = subprocess.run(
2300
+ command_args,
2301
+ shell=False,
2302
+ capture_output=True,
2303
+ text=True,
2304
+ encoding="utf-8",
2305
+ errors="replace",
2306
+ timeout=60,
2307
+ creationflags=_NO_WINDOW,
2308
+ )
2309
+ except subprocess.TimeoutExpired:
2310
+ sys.exit(124)
2311
+ except OSError as exc:
2312
+ print(f"bash_compress.py: {exc}", file=sys.stderr)
2313
+ sys.exit(127)
2314
+ sys.stdout.write(result.stdout or "")
2315
+ sys.stdout.flush()
2316
+ sys.stderr.write(result.stderr or "")
2317
+ sys.stderr.flush()
2318
+ sys.exit(result.returncode)
2319
+
2320
+
2321
+ def main():
2322
+ """Run a command through compression wrapper."""
2323
+ if len(sys.argv) < 2:
2324
+ print("Usage: bash_compress.py <command...>", file=sys.stderr)
2325
+ sys.exit(1)
2326
+
2327
+ command_args = sys.argv[1:]
2328
+ command_str = shlex.join(command_args)
2329
+
2330
+ # R13a: independently re-validate the argv before running anything, so a
2331
+ # cached "always allow" on this wrapper's command prefix can never turn
2332
+ # bash_compress.py into an unguarded command runner. Exact same whitelist +
2333
+ # dangerous-character gate the Antigravity / Copilot / Claude bridges apply
2334
+ # before rewriting. A direct `bash_compress.py <anything-not-whitelisted>`
2335
+ # (or a hostile `rm -rf /`, `curl | sh`, etc.) is refused and spawns
2336
+ # nothing.
2337
+ #
2338
+ # The gate module is dependency-free, but if it cannot be imported (stale
2339
+ # or partial payload copy) the wrapper must fail OPEN: the command runs
2340
+ # uncompressed exactly as the user typed it. Refusing here would silently
2341
+ # drop whitelisted commands on every platform that shares this wrapper.
2342
+ try:
2343
+ import bash_whitelist as _self_check
2344
+ except Exception:
2345
+ _self_check = None
2346
+ if _self_check is None:
2347
+ _run_original(command_args)
2348
+ sys.exit(0)
2349
+ if _self_check.has_dangerous_chars(command_str) or not _self_check.is_whitelisted(command_str):
2350
+ print("bash_compress.py: command is not eligible for compression", file=sys.stderr)
2351
+ sys.exit(1)
2352
+
2353
+ try:
2354
+ result = subprocess.run(
2355
+ command_args,
2356
+ shell=False,
2357
+ capture_output=True,
2358
+ text=True,
2359
+ encoding="utf-8",
2360
+ errors="replace",
2361
+ timeout=60,
2362
+ creationflags=_NO_WINDOW,
2363
+ )
2364
+ stdout = result.stdout or ""
2365
+ stderr = result.stderr or ""
2366
+ raw_output = stdout + stderr
2367
+
2368
+ # Memory safety: commands like `find /`, `tree /`, or `journalctl`
2369
+ # under a large time window can emit hundreds of MB through
2370
+ # capture_output. Compression would duplicate that payload multiple
2371
+ # times across regex scans and rebuilt strings, so above 5MB we
2372
+ # emit raw and skip the compression path entirely.
2373
+ MAX_COMPRESS_BYTES = 5 * 1024 * 1024
2374
+ if len(raw_output.encode("utf-8", errors="replace")) > MAX_COMPRESS_BYTES:
2375
+ sys.stdout.write(raw_output)
2376
+ sys.stdout.flush()
2377
+ sys.exit(result.returncode)
2378
+
2379
+ compressed = compress(
2380
+ command_str,
2381
+ raw_output,
2382
+ returncode=result.returncode,
2383
+ stderr=stderr,
2384
+ )
2385
+
2386
+ # Progressive disclosure: archive the raw original BEFORE compression
2387
+ # so the model can retrieve it via `expand <key>` if needed. Fail-open:
2388
+ # if archiving fails, compression proceeds without the pointer.
2389
+ _archive_key = None
2390
+ if compressed != raw_output and len(raw_output) > 500:
2391
+ try:
2392
+ from archive_result import archive_entry_exists, archive_original, build_archive_pointer
2393
+ _session_id = os.environ.get("CLAUDE_SESSION_ID", "")
2394
+ _archive_key = hashlib.sha256(
2395
+ f"{_session_id}|{command_str}|{time.time()}|{os.urandom(4).hex()}".encode("utf-8", errors="replace")
2396
+ ).hexdigest()[:16]
2397
+ if archive_original(raw_output, _session_id, _archive_key, "Bash") is not None:
2398
+ # Re-check the entry survived any concurrent retention prune
2399
+ # before we emit a pointer that would strand the model.
2400
+ if archive_entry_exists(_session_id, _archive_key):
2401
+ compressed = build_archive_pointer(compressed, len(raw_output), _archive_key)
2402
+ else:
2403
+ # Entry was pruned before we could point to it. The lossy
2404
+ # `compressed` preview has no recovery path once the archive
2405
+ # copy is gone, so serving it here would be silent, permanent
2406
+ # data loss. raw_output is still in scope untouched -- serve
2407
+ # that instead, matching the guarantee archive_result.py /
2408
+ # read_cache.py already give on the same post-prune re-check
2409
+ # (they fall back to the full original rather than a preview).
2410
+ compressed = raw_output
2411
+ _archive_key = None
2412
+ else:
2413
+ _archive_key = None
2414
+ except Exception:
2415
+ _archive_key = None
2416
+
2417
+ # Record savings to trends.db if compression was meaningful
2418
+ try:
2419
+ orig_bytes = len(raw_output.encode("utf-8", errors="replace"))
2420
+ comp_bytes = len(compressed.encode("utf-8", errors="replace"))
2421
+ if comp_bytes < orig_bytes * 0.9:
2422
+ _pattern = _detect_pattern(command_str)
2423
+ _feature = _COMPRESS_FEATURE_MAP.get(_pattern or "")
2424
+ if _feature is None and _pattern is None:
2425
+ _feature = "bash_generic" # U4: unmatched-output coverage
2426
+ if _feature:
2427
+ from measure import _log_compression_event
2428
+ # C-2: command_pattern is persisted to trends.db's
2429
+ # compression_events table. Redact BEFORE truncating so an
2430
+ # inline secret (Bearer token, mysql -pPASSWORD,
2431
+ # PGPASSWORD=... psql) never reaches disk in cleartext.
2432
+ # Mirrors the fix in bash_compress_hook._log_event. When the
2433
+ # redactor is unavailable or refuses (a broken custom
2434
+ # pattern file fails closed), skip the event entirely —
2435
+ # persisting the raw command would store what the configured
2436
+ # rules exist to keep off disk.
2437
+ try:
2438
+ from credential_patterns import redact_credentials as _redact
2439
+ _safe_pattern = _redact(command_str)[:100]
2440
+ except Exception:
2441
+ _safe_pattern = None
2442
+ if _safe_pattern is not None:
2443
+ _log_compression_event(
2444
+ feature=_feature,
2445
+ original_text=raw_output,
2446
+ compressed_text=compressed,
2447
+ session_id=os.environ.get("CLAUDE_SESSION_ID", ""),
2448
+ command_pattern=_safe_pattern,
2449
+ quality_preserved=True,
2450
+ verified=True,
2451
+ tier="measured",
2452
+ )
2453
+ except Exception:
2454
+ pass
2455
+
2456
+ # UNIT C guard: the final gate on what the model sees. If our
2457
+ # preview + archive pointer would exceed what Claude Code itself
2458
+ # would show for this output (full raw below ~30KB, ~2.2KB stub
2459
+ # above it), shrink it so Token Optimizer never loses to baseline.
2460
+ # Fail-open: a guard failure must never break the pipeline.
2461
+ try:
2462
+ compressed = _enforce_baseline_invariant(compressed, raw_output, _archive_key)
2463
+ except Exception:
2464
+ pass
2465
+
2466
+ # Buffer completely, then write
2467
+ sys.stdout.write(compressed)
2468
+ sys.stdout.flush()
2469
+ sys.exit(result.returncode)
2470
+
2471
+ except subprocess.TimeoutExpired as e:
2472
+ # NEVER compress partial output on timeout
2473
+ partial = ""
2474
+ if e.stdout:
2475
+ partial += e.stdout if isinstance(e.stdout, str) else e.stdout.decode("utf-8", errors="replace")
2476
+ if e.stderr:
2477
+ partial += e.stderr if isinstance(e.stderr, str) else e.stderr.decode("utf-8", errors="replace")
2478
+ sys.stdout.write(partial)
2479
+ sys.stdout.write("\n[TIMEOUT after 60s - output may be incomplete]\n")
2480
+ sys.stdout.flush()
2481
+ sys.exit(124)
2482
+
2483
+ except Exception as e:
2484
+ # Fail open: emit the error so Claude sees it instead of empty output
2485
+ sys.stderr.write(f"[bash_compress: wrapper error: {type(e).__name__}: {e}]\n")
2486
+ sys.exit(1)
2487
+
2488
+
2489
+ if __name__ == "__main__":
2490
+ main()