@alexgreensh/token-optimizer 5.13.74 → 5.13.76
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/module_runner.py +1 -1
- package/hooks/posttooluse_runner.py +7 -9
- package/hooks/run.py +5 -1
- package/hooks/stop_runner.py +15 -56
- package/hooks/userpromptsubmit_runner.py +29 -4
- package/package.json +1 -1
- package/skills/token-optimizer/assets/dashboard.html +30 -14
- package/skills/token-optimizer/assets/savings_story.js +103 -27
- package/skills/token-optimizer/references/agent-prompts.md +2 -0
- package/skills/token-optimizer/references/implementation-playbook.md +1 -0
- package/skills/token-optimizer/scripts/_measure/__init__.py +1 -1
- package/skills/token-optimizer/scripts/_measure/apply_safe.py +512 -0
- package/skills/token-optimizer/scripts/_measure/audit.py +9 -20
- package/skills/token-optimizer/scripts/_measure/autocompact_advice.py +455 -0
- package/skills/token-optimizer/scripts/_measure/cache_policy.py +82 -127
- package/skills/token-optimizer/scripts/_measure/cli.py +10 -24
- package/skills/token-optimizer/scripts/_measure/cold_guard.py +777 -0
- package/skills/token-optimizer/scripts/_measure/continuity.py +45 -4
- package/skills/token-optimizer/scripts/_measure/counted_closes.py +398 -0
- package/skills/token-optimizer/scripts/_measure/counted_headline.py +112 -0
- package/skills/token-optimizer/scripts/_measure/dashboard.py +14 -6
- package/skills/token-optimizer/scripts/_measure/feature_health.py +6 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_auto.py +452 -0
- package/skills/token-optimizer/scripts/_measure/keepwarm_economics.py +8 -4
- package/skills/token-optimizer/scripts/_measure/keepwarm_safety.py +548 -24
- package/skills/token-optimizer/scripts/_measure/limit_units.py +463 -0
- package/skills/token-optimizer/scripts/_measure/local_adapt.py +192 -0
- package/skills/token-optimizer/scripts/_measure/mod_action_booking.py +71 -14
- package/skills/token-optimizer/scripts/_measure/next_actions.py +420 -0
- package/skills/token-optimizer/scripts/_measure/poc_commands.py +44 -0
- package/skills/token-optimizer/scripts/_measure/prefix_cost.py +215 -0
- package/skills/token-optimizer/scripts/_measure/pt_resume_cues.py +46 -0
- package/skills/token-optimizer/scripts/_measure/quality_archive.py +7 -10
- package/skills/token-optimizer/scripts/_measure/savings.py +80 -82
- package/skills/token-optimizer/scripts/_measure/savings_headline.py +17 -21
- package/skills/token-optimizer/scripts/_measure/savings_story.py +8 -1
- package/skills/token-optimizer/scripts/_measure/session_store_spool.py +119 -78
- package/skills/token-optimizer/scripts/_measure/status_bar_refresh.py +38 -3
- package/skills/token-optimizer/scripts/_measure/structural_ledger.py +1 -1
- package/skills/token-optimizer/scripts/_measure/subscription_audits.py +725 -0
- package/skills/token-optimizer/scripts/_measure/transcript_backfill.py +1 -1
- package/skills/token-optimizer/scripts/_measure/transcript_stream.py +8 -2
- package/skills/token-optimizer/scripts/antigravity_install.py +3 -0
- package/skills/token-optimizer/scripts/archive_result.py +16 -28
- package/skills/token-optimizer/scripts/archive_verify.py +1 -1
- package/skills/token-optimizer/scripts/bash_compress.py +156 -176
- package/skills/token-optimizer/scripts/bash_compress_hook.py +218 -174
- package/skills/token-optimizer/scripts/bash_search_results.py +189 -9
- package/skills/token-optimizer/scripts/bash_whitelist.py +6 -1
- package/skills/token-optimizer/scripts/benchmark.py +11 -13
- package/skills/token-optimizer/scripts/big_noncode_read.py +998 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +103 -8
- package/skills/token-optimizer/scripts/builtin_tool_compress.py +716 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1 -1
- package/skills/token-optimizer/scripts/codex_doctor.py +1 -1
- package/skills/token-optimizer/scripts/command_compress_extra.py +955 -0
- package/skills/token-optimizer/scripts/compact_markers.py +129 -0
- package/skills/token-optimizer/scripts/copilot_install.py +3 -0
- package/skills/token-optimizer/scripts/cursor_install.py +7 -0
- package/skills/token-optimizer/scripts/devin_source.py +5 -5
- package/skills/token-optimizer/scripts/emit_safety_gate.py +518 -0
- package/skills/token-optimizer/scripts/fixtures/b2_more_commands.json +142 -0
- package/skills/token-optimizer/scripts/fixtures/b5_more_savings.json +26 -0
- package/skills/token-optimizer/scripts/fixtures/builtin_tools.json +103 -0
- package/skills/token-optimizer/scripts/fixtures/c7_review_ratchet.json +52 -0
- package/skills/token-optimizer/scripts/fixtures/large_output_policy.json +55 -0
- package/skills/token-optimizer/scripts/go_cargo_test_compress.py +493 -0
- package/skills/token-optimizer/scripts/grok_install.py +3 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +4 -1
- package/skills/token-optimizer/scripts/hermes_install.py +10 -1
- package/skills/token-optimizer/scripts/hook_fastpath.py +94 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +6 -2
- package/skills/token-optimizer/scripts/large_output_policy.py +431 -0
- package/skills/token-optimizer/scripts/measure.py +10 -12
- package/skills/token-optimizer/scripts/pipe_file_compress.py +900 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +15 -1
- package/skills/token-optimizer/scripts/post_run_classify.py +2 -2
- package/skills/token-optimizer/scripts/preserved_reinject.py +20 -3
- package/skills/token-optimizer/scripts/process_identity.py +66 -0
- package/skills/token-optimizer/scripts/read_cache.py +51 -60
- package/skills/token-optimizer/scripts/statusline.js +21 -3
- package/skills/token-optimizer/scripts/visibility_rule.py +536 -0
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Shared visibility rule for all Token Optimizer compressors.
|
|
3
|
+
|
|
4
|
+
Rule enforced across every compressor:
|
|
5
|
+
a) Lines showing an error, failure, exception (including CamelCase names like
|
|
6
|
+
ValueError / TimeoutException), traceback, panic, failing test, or
|
|
7
|
+
non-zero exit stay visible verbatim.
|
|
8
|
+
b) Ordinary hidden content is allowed ONLY when the output states exactly
|
|
9
|
+
what was hidden, by count and place (e.g. "21 more matches in src/x.py
|
|
10
|
+
(lines 40-212)"), followed by the exact runnable expand command.
|
|
11
|
+
c) Counts must exactly match what was hidden; output stays deterministic;
|
|
12
|
+
fail open on any error.
|
|
13
|
+
d) If expand storage write fails or the entry was pruned, return the original
|
|
14
|
+
output untouched.
|
|
15
|
+
|
|
16
|
+
Search-hit distinction:
|
|
17
|
+
Grep/ripgrep/git-grep match lines in structured ``file:line:content`` form
|
|
18
|
+
(where the path is non-empty, not numeric, not a tool diagnostic prefix such
|
|
19
|
+
as ``rg:``/``grep:``/``git:``/``fatal:``/``error:``, and not a Python stack
|
|
20
|
+
frame ``File "...", line N``) are ordinary search hits even when the matched
|
|
21
|
+
source code contains the literal word "error" or an exception name. Search
|
|
22
|
+
*failures* are identified by non-zero exit code, non-empty stderr, or
|
|
23
|
+
non-match diagnostic/error lines on stdout, all of which stay visible verbatim
|
|
24
|
+
(or pass through raw).
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import re
|
|
30
|
+
|
|
31
|
+
# Structured grep/rg/ag/ack/git-grep match line: file:line:content
|
|
32
|
+
_SEARCH_MATCH_RE = re.compile(r"^((?:[A-Za-z]:)?[^:\n]+):(\d+):(.*)$")
|
|
33
|
+
|
|
34
|
+
# Tool-diagnostic prefixes that can look superficially like `word:digits:`
|
|
35
|
+
# or appear on stdout when stderr is merged (2>&1).
|
|
36
|
+
_SEARCH_TOOL_ERROR_PREFIXES = (
|
|
37
|
+
"rg:",
|
|
38
|
+
"grep:",
|
|
39
|
+
"egrep:",
|
|
40
|
+
"fgrep:",
|
|
41
|
+
"ag:",
|
|
42
|
+
"ack:",
|
|
43
|
+
"git:",
|
|
44
|
+
"fatal:",
|
|
45
|
+
"error:",
|
|
46
|
+
"warning:",
|
|
47
|
+
"traceback",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# Python stack frame line (never a grep match even though it has colons/digits).
|
|
51
|
+
_PY_FRAME_RE = re.compile(r'^\s*File\s+"[^"]+",\s+line\s+\d+')
|
|
52
|
+
|
|
53
|
+
# CamelCase exception/error class names: ValueError, TimeoutException,
|
|
54
|
+
# NullPointerException, AssertionError, SegmentationFault, etc.
|
|
55
|
+
_EXCEPTION_NAME_RE = re.compile(
|
|
56
|
+
r"\b[A-Z][A-Za-z0-9_]*(?:Error|Exception|Fault|Panic|Failure)\b"
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
# Non-zero exit status indicators (never match HTTP status=200).
|
|
60
|
+
_NONZERO_EXIT_RE = re.compile(
|
|
61
|
+
r"(?i)(?:"
|
|
62
|
+
r"\bexit(?:ed)?(?:\s+with)?(?:\s+(?:code|status))?\s*[:=]?\s*[1-9]\d*\b|"
|
|
63
|
+
r"\breturn(?:ed)?\s+(?:exit\s+)?(?:code|status)\s*[:=]?\s*[1-9]\d*\b|"
|
|
64
|
+
r"\bexit[_-]?(?:code|status)\s*[:=]\s*[1-9]\d*\b|"
|
|
65
|
+
r"\bprocess\s+completed\s+with\s+exit\s+code\s+[1-9]\d*\b"
|
|
66
|
+
r")"
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
# Strict error/exception/traceback/panic/non-zero-exit pattern (safe even on
|
|
70
|
+
# lockfiles where package names like "http-errors" appear).
|
|
71
|
+
_STRICT_ERROR_RE = re.compile(
|
|
72
|
+
r"(?:"
|
|
73
|
+
r"Traceback \(most recent call last\):|"
|
|
74
|
+
r"^\s*File \"[^\"]+\", line \d+|"
|
|
75
|
+
r"^\s+at\s+\S+\s*\([^)]+:\d+|"
|
|
76
|
+
r"^Caused by:|"
|
|
77
|
+
r"^\s*goroutine \d+|"
|
|
78
|
+
r"##\[error\]|"
|
|
79
|
+
r"\bpanicked at\b|"
|
|
80
|
+
r"(?i:\b(?:panic|fatal(?:\s+error)?)\s*:)|"
|
|
81
|
+
r"^\s*--- FAIL:\s+|"
|
|
82
|
+
r"^FAIL\t\S+|"
|
|
83
|
+
r"^test .+? \.\.\. FAILED\s*$|"
|
|
84
|
+
r"^\s*not ok \d+\s+-|"
|
|
85
|
+
r"^\s*[X✗✖]\s+"
|
|
86
|
+
r")"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# General error/failure/exception/traceback/panic/failing-test pattern.
|
|
90
|
+
_GENERAL_ERROR_RE = re.compile(
|
|
91
|
+
r"(?:"
|
|
92
|
+
r"##\[(?:error|warning)\]|"
|
|
93
|
+
r"(?i:\b(?:error|errors|err!|fatal|panic|panicked|fail|failed|failing|"
|
|
94
|
+
r"failure|failures|exception|traceback|segfault|aborted|oomkilled|"
|
|
95
|
+
r"crashloopbackoff|imagepullbackoff|evicted|unhealthy|timed\s+out|timeout|"
|
|
96
|
+
r"permission\s+denied|access\s+denied|connection\s+refused)\b)|"
|
|
97
|
+
r"^\s*E\s+(?:assert\b|[A-Z][A-Za-z0-9_]*(?:Error|Exception))|"
|
|
98
|
+
# Localized / foreign error markers (mirrors bash_compress._ERROR_STDERR_PATTERNS
|
|
99
|
+
# and _FOREIGN_ERROR_PATTERNS).
|
|
100
|
+
r"(?i:\b(?:fehler|erreur|errore|ошибка|fout|fel|virhe|hiba|hata|erro|blad|l\u1ed7i)\s*[::])|"
|
|
101
|
+
r"错误\s*[::]|錯誤\s*[::]|エラー\s*[::]|오류\s*[::]|"
|
|
102
|
+
r"\u0e02\u0e49\u0e2d\u0e1c\u0e34\u0e14\u0e1e\u0e25\u0e32\u0e14|"
|
|
103
|
+
r"\u05e9\u05d2\u05d9\u05d0\u05d4|"
|
|
104
|
+
r"\u062e\u0637\u0623|"
|
|
105
|
+
r"\u062e\u0637\u0627"
|
|
106
|
+
r")"
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def is_search_match_line(line: str) -> bool:
|
|
111
|
+
"""Return True iff ``line`` is a structured ``file:line:content`` search hit.
|
|
112
|
+
|
|
113
|
+
Distinguishes ordinary grep/rg/git-grep matches of literal words like
|
|
114
|
+
``error`` or ``ValueError`` inside source code from actual tool failures
|
|
115
|
+
(``rg: ...``, ``grep: ...``, tracebacks, exit-code lines).
|
|
116
|
+
"""
|
|
117
|
+
if not line:
|
|
118
|
+
return False
|
|
119
|
+
stripped = line.lstrip()
|
|
120
|
+
low = stripped.lower()
|
|
121
|
+
if low.startswith(_SEARCH_TOOL_ERROR_PREFIXES):
|
|
122
|
+
return False
|
|
123
|
+
if _PY_FRAME_RE.match(line):
|
|
124
|
+
return False
|
|
125
|
+
m = _SEARCH_MATCH_RE.match(line)
|
|
126
|
+
if not m:
|
|
127
|
+
return False
|
|
128
|
+
fname = m.group(1).strip()
|
|
129
|
+
if not fname or fname.isdigit():
|
|
130
|
+
return False
|
|
131
|
+
# Reject lines where the "filename" contains whitespace-only or starts with
|
|
132
|
+
# common diagnostic words followed by space (e.g. "Error in file:10: ...").
|
|
133
|
+
if " " in fname and not ("/" in fname or "\\" in fname):
|
|
134
|
+
return False
|
|
135
|
+
return True
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def extract_search_line_number(line: str) -> int | None:
|
|
139
|
+
"""Extract the 1-based line number from a ``file:line:content`` search hit."""
|
|
140
|
+
m = _SEARCH_MATCH_RE.match(line)
|
|
141
|
+
if not m:
|
|
142
|
+
return None
|
|
143
|
+
try:
|
|
144
|
+
return int(m.group(2))
|
|
145
|
+
except (TypeError, ValueError):
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
_BENIGN_ZERO_ERR_RE = re.compile(
|
|
150
|
+
r"\b(?:0|no|zero|without)\s+(?:errors?|failures?|failed)\b|"
|
|
151
|
+
r"\b(?:error_count|errors|failures|failed)\s*[:=]\s*0\b",
|
|
152
|
+
re.I,
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
# Failure lines that carry no literal "error" word (shared with emit_safety_gate).
|
|
156
|
+
_NON_ERROR_FAILURE_RE = re.compile(
|
|
157
|
+
r"(?:"
|
|
158
|
+
r"(?i:\bcommand\s+not\s+found\b)|"
|
|
159
|
+
r"(?i:\bno\s+such\s+file\s+or\s+directory\b)|"
|
|
160
|
+
r"^CONFLICT\b|(?i:\bmerge\s+conflict\b)|"
|
|
161
|
+
r"\[rejected\]|"
|
|
162
|
+
r"^\s*Killed(?:\s|$|:)|\bKilled:\s*\d+|"
|
|
163
|
+
r"(?i:\bexceeded\s+its\s+progress\s+deadline\b)|"
|
|
164
|
+
r"(?i:\bno\s+space\s+left\s+on\s+device\b)|"
|
|
165
|
+
r"(?i:\baddress\s+already\s+in\s+use\b)|"
|
|
166
|
+
r"(?i:\bread-only\s+file\s+system\b)|"
|
|
167
|
+
r"(?i:\bcannot\s+(?:access|open|create|remove)\b)|"
|
|
168
|
+
r"(?i:\b(?:could|unable)\s+to\s+resolve\b)"
|
|
169
|
+
r")"
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
_STRICT_PANIC_RE = re.compile(
|
|
173
|
+
r"\b(?:fatal|panic|panicked|segfault|segmentation fault|core dumped|out of memory)\b",
|
|
174
|
+
re.I,
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def is_strict_critical_line(line: str) -> bool:
|
|
179
|
+
"""True for unambiguous hard failures (traceback, fatal/panic, non-zero exit)
|
|
180
|
+
that must stay visible even when matched inside a ``file:line:content`` search hit."""
|
|
181
|
+
if not line or not line.strip():
|
|
182
|
+
return False
|
|
183
|
+
return bool(
|
|
184
|
+
_STRICT_ERROR_RE.search(line)
|
|
185
|
+
or _NONZERO_EXIT_RE.search(line)
|
|
186
|
+
or _STRICT_PANIC_RE.search(line)
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def is_error_or_failure_line(
|
|
191
|
+
line: str,
|
|
192
|
+
*,
|
|
193
|
+
strict_exception_only: bool = False,
|
|
194
|
+
include_stack_frames: bool = True,
|
|
195
|
+
) -> bool:
|
|
196
|
+
"""Return True if ``line`` shows an error, failure, exception, traceback,
|
|
197
|
+
panic, failing test, or non-zero exit that must stay visible verbatim.
|
|
198
|
+
"""
|
|
199
|
+
if not line or not line.strip():
|
|
200
|
+
return False
|
|
201
|
+
if not include_stack_frames and _PY_FRAME_RE.match(line):
|
|
202
|
+
return False
|
|
203
|
+
if _EXCEPTION_NAME_RE.search(line):
|
|
204
|
+
return True
|
|
205
|
+
if _NONZERO_EXIT_RE.search(line):
|
|
206
|
+
return True
|
|
207
|
+
if _STRICT_ERROR_RE.search(line):
|
|
208
|
+
return True
|
|
209
|
+
if _NON_ERROR_FAILURE_RE.search(line):
|
|
210
|
+
return True
|
|
211
|
+
if strict_exception_only:
|
|
212
|
+
return False
|
|
213
|
+
if _BENIGN_ZERO_ERR_RE.search(line):
|
|
214
|
+
return False
|
|
215
|
+
return bool(_GENERAL_ERROR_RE.search(line))
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def format_line_range(line_numbers: list[int]) -> str:
|
|
219
|
+
"""Format a non-empty sequence of 1-based line numbers as ``line N`` or ``lines A-B``."""
|
|
220
|
+
if not line_numbers:
|
|
221
|
+
return ""
|
|
222
|
+
lo = min(line_numbers)
|
|
223
|
+
hi = max(line_numbers)
|
|
224
|
+
if lo == hi:
|
|
225
|
+
return f"line {lo}"
|
|
226
|
+
return f"lines {lo}-{hi}"
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def format_line_ranges(line_numbers: list[int]) -> str:
|
|
230
|
+
"""Format sorted 1-based line numbers into exact contiguous ranges."""
|
|
231
|
+
if not line_numbers:
|
|
232
|
+
return ""
|
|
233
|
+
nums = sorted(set(line_numbers))
|
|
234
|
+
runs: list[tuple[int, int]] = []
|
|
235
|
+
start = prev = nums[0]
|
|
236
|
+
for n in nums[1:]:
|
|
237
|
+
if n == prev + 1:
|
|
238
|
+
prev = n
|
|
239
|
+
else:
|
|
240
|
+
runs.append((start, prev))
|
|
241
|
+
start = prev = n
|
|
242
|
+
runs.append((start, prev))
|
|
243
|
+
return ", ".join(f"line {a}" if a == b else f"lines {a}-{b}" for a, b in runs)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
_FAST_STRICT_RE = re.compile(
|
|
247
|
+
r"traceback|file \"|at \S+\s*\(|caused by:|goroutine \d+|##\[error\]|"
|
|
248
|
+
r"panicked|panic|fatal|segfault|segmentation fault|core dumped|out of memory|"
|
|
249
|
+
r"--- fail:|fail\t|\.\.\. failed|not ok \d+|exit|return",
|
|
250
|
+
re.I,
|
|
251
|
+
)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def find_missing_critical_lines(
|
|
255
|
+
raw_text: str,
|
|
256
|
+
compressed_text: str,
|
|
257
|
+
*,
|
|
258
|
+
is_search: bool = False,
|
|
259
|
+
strict_exception_only: bool = False,
|
|
260
|
+
) -> list[tuple[int, str]]:
|
|
261
|
+
"""Return ``(1-based line_no, line)`` for every critical line in ``raw_text``
|
|
262
|
+
that is not visible verbatim in ``compressed_text`` (O(N+M))."""
|
|
263
|
+
if not raw_text:
|
|
264
|
+
return []
|
|
265
|
+
# Fast whole-text pre-check for search output: if no strict-critical keyword
|
|
266
|
+
# appears anywhere in raw_text and no non-match diagnostic line is possible,
|
|
267
|
+
# skip per-line regex scanning.
|
|
268
|
+
has_strict_anywhere = bool(_FAST_STRICT_RE.search(raw_text))
|
|
269
|
+
comp_lines = compressed_text.splitlines()
|
|
270
|
+
comp_set = set(comp_lines) | {ln.strip() for ln in comp_lines}
|
|
271
|
+
missing: list[tuple[int, str]] = []
|
|
272
|
+
for idx, line in enumerate(raw_text.splitlines(), 1):
|
|
273
|
+
stripped = line.strip()
|
|
274
|
+
if not stripped:
|
|
275
|
+
continue
|
|
276
|
+
if is_search and is_search_match_line(line):
|
|
277
|
+
if not has_strict_anywhere or not is_strict_critical_line(line):
|
|
278
|
+
continue
|
|
279
|
+
elif not is_error_or_failure_line(line, strict_exception_only=strict_exception_only):
|
|
280
|
+
continue
|
|
281
|
+
if line in comp_set or stripped in comp_set:
|
|
282
|
+
continue
|
|
283
|
+
# Fallback substring check only for the few critical lines not matching a whole line.
|
|
284
|
+
if line not in compressed_text and stripped not in compressed_text:
|
|
285
|
+
missing.append((idx, line))
|
|
286
|
+
return missing
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
_GENERIC_OMIT_LINE_RE = re.compile(
|
|
290
|
+
r"(?m)^\.\.\.\s+(\d+)\s+lines?\s+omitted(?:\s*\([^)]*\))?\s*\.\.\.$"
|
|
291
|
+
)
|
|
292
|
+
_DIFF_MORE_LINE_RE = re.compile(
|
|
293
|
+
r"(?m)^\.\.\.\s+\((\d+)\s+more\s+lines,\s+([^)]+)\)$"
|
|
294
|
+
)
|
|
295
|
+
_ANY_DECLARED_HIDE_RE = re.compile(
|
|
296
|
+
r"(?i)(?:"
|
|
297
|
+
r"\.\.\.\s*\(?\d+\s+(?:more\s+)?(?:lines?|matches?|files?|items?|entries|stack frames|non-file lines|preamble lines|extra lines)\b|"
|
|
298
|
+
r"\b\d+\s+(?:more\s+)?(?:lines?|matches?|files?|items?|entries)\s+(?:omitted|hidden|archived|truncated)\b|"
|
|
299
|
+
r"\[Folded noisy matches:\s*\d+|"
|
|
300
|
+
r"\[large_output_policy:\s*\d+\s+of\s+\d+\s+lines\s+hidden|"
|
|
301
|
+
r"plus\s+\d+\s+more\s+files\s+with\s+matches"
|
|
302
|
+
r")"
|
|
303
|
+
)
|
|
304
|
+
_ARCHIVE_POINTER_START = "\n\n[Full result archived ("
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def compress_generic_exact(text: str, *, head_n: int = 20, tail_n: int = 20) -> str:
|
|
308
|
+
"""Generic structural/log compression with exact raw-line omission counts
|
|
309
|
+
and zero dropped critical lines."""
|
|
310
|
+
lines = text.splitlines()
|
|
311
|
+
# Collapse consecutive identical lines while tracking exact raw line spans.
|
|
312
|
+
collapsed: list[tuple[str, int, int, int]] = [] # (rendered, start_lno, end_lno, raw_count)
|
|
313
|
+
run_val: str | None = None
|
|
314
|
+
run_start = 1
|
|
315
|
+
run_count = 0
|
|
316
|
+
|
|
317
|
+
def _flush(end_lno: int) -> None:
|
|
318
|
+
if run_val is None:
|
|
319
|
+
return
|
|
320
|
+
rendered = f"{run_val} (x{run_count})" if run_count > 1 else run_val
|
|
321
|
+
collapsed.append((rendered, run_start, end_lno, run_count))
|
|
322
|
+
|
|
323
|
+
for idx, ln in enumerate(lines, 1):
|
|
324
|
+
if ln == run_val:
|
|
325
|
+
run_count += 1
|
|
326
|
+
else:
|
|
327
|
+
_flush(idx - 1)
|
|
328
|
+
run_val = ln
|
|
329
|
+
run_start = idx
|
|
330
|
+
run_count = 1
|
|
331
|
+
_flush(len(lines))
|
|
332
|
+
|
|
333
|
+
if len(collapsed) <= head_n + tail_n:
|
|
334
|
+
return "\n".join(item[0] for item in collapsed)
|
|
335
|
+
|
|
336
|
+
head = collapsed[:head_n]
|
|
337
|
+
tail = collapsed[len(collapsed) - tail_n:]
|
|
338
|
+
middle = collapsed[head_n:len(collapsed) - tail_n]
|
|
339
|
+
|
|
340
|
+
kept_middle: list[str] = []
|
|
341
|
+
omitted_raw_lines: list[int] = []
|
|
342
|
+
for rendered, s_lno, e_lno, _cnt in middle:
|
|
343
|
+
if is_error_or_failure_line(rendered) or re.search(r"(?i)\bwarn(?:ing)?s?\b", rendered):
|
|
344
|
+
kept_middle.append(rendered)
|
|
345
|
+
else:
|
|
346
|
+
omitted_raw_lines.extend(range(s_lno, e_lno + 1))
|
|
347
|
+
|
|
348
|
+
out = [item[0] for item in head]
|
|
349
|
+
if omitted_raw_lines:
|
|
350
|
+
ranges = format_line_ranges(omitted_raw_lines)
|
|
351
|
+
if kept_middle:
|
|
352
|
+
out.append(
|
|
353
|
+
f"... {len(omitted_raw_lines)} lines omitted ({ranges}; "
|
|
354
|
+
f"kept {len(kept_middle)} error/warning lines) ..."
|
|
355
|
+
)
|
|
356
|
+
out.extend(kept_middle)
|
|
357
|
+
else:
|
|
358
|
+
out.append(f"... {len(omitted_raw_lines)} lines omitted ({ranges}) ...")
|
|
359
|
+
elif kept_middle:
|
|
360
|
+
out.extend(kept_middle)
|
|
361
|
+
out.extend(item[0] for item in tail)
|
|
362
|
+
return "\n".join(out)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def enforce_visibility_and_exact_hidden(
|
|
366
|
+
raw_text: str,
|
|
367
|
+
compressed_text: str,
|
|
368
|
+
*,
|
|
369
|
+
is_search: bool = False,
|
|
370
|
+
skip_hidden_check: bool = False,
|
|
371
|
+
) -> str:
|
|
372
|
+
"""Enforce zero hidden critical lines and accurate hidden-line declaration.
|
|
373
|
+
|
|
374
|
+
Called on compressed Bash output before attaching the archive pointer.
|
|
375
|
+
Deterministic and fail-open.
|
|
376
|
+
"""
|
|
377
|
+
if not raw_text or not compressed_text or compressed_text == raw_text:
|
|
378
|
+
return compressed_text
|
|
379
|
+
|
|
380
|
+
result = compressed_text
|
|
381
|
+
|
|
382
|
+
# 1. Guarantee every critical line in raw_text is visible verbatim.
|
|
383
|
+
missing_crit = find_missing_critical_lines(raw_text, result, is_search=is_search)
|
|
384
|
+
if missing_crit:
|
|
385
|
+
result = result + "\n" + "\n".join(ln for _, ln in missing_crit)
|
|
386
|
+
|
|
387
|
+
if skip_hidden_check:
|
|
388
|
+
return result
|
|
389
|
+
|
|
390
|
+
# 2. Compute exact hidden raw lines (O(N+M) via line set).
|
|
391
|
+
raw_lines = raw_text.splitlines()
|
|
392
|
+
res_lines = result.splitlines()
|
|
393
|
+
res_set = set(res_lines) | {ln.strip() for ln in res_lines}
|
|
394
|
+
hidden_nos = [
|
|
395
|
+
idx for idx, ln in enumerate(raw_lines, 1)
|
|
396
|
+
if ln.strip() and ln not in res_set and ln.strip() not in res_set
|
|
397
|
+
]
|
|
398
|
+
if not hidden_nos:
|
|
399
|
+
return result
|
|
400
|
+
|
|
401
|
+
exact_count = len(hidden_nos)
|
|
402
|
+
exact_ranges = format_line_ranges(hidden_nos)
|
|
403
|
+
|
|
404
|
+
# Fix up known generic/diff omission markers if their count drifted (e.g. after reinject).
|
|
405
|
+
m_gen = _GENERIC_OMIT_LINE_RE.search(result)
|
|
406
|
+
if m_gen:
|
|
407
|
+
declared = int(m_gen.group(1))
|
|
408
|
+
if declared != exact_count or "line" not in m_gen.group(0).split("omitted", 1)[-1]:
|
|
409
|
+
replacement = f"... {exact_count} lines omitted ({exact_ranges}) ..."
|
|
410
|
+
result = result[:m_gen.start()] + replacement + result[m_gen.end():]
|
|
411
|
+
return result
|
|
412
|
+
|
|
413
|
+
m_diff = _DIFF_MORE_LINE_RE.search(result)
|
|
414
|
+
if m_diff:
|
|
415
|
+
declared = int(m_diff.group(1))
|
|
416
|
+
stats_tail = m_diff.group(2)
|
|
417
|
+
if declared != exact_count or "lines " not in stats_tail:
|
|
418
|
+
replacement = f"... ({exact_count} more lines, {exact_ranges}, {stats_tail})"
|
|
419
|
+
result = result[:m_diff.start()] + replacement + result[m_diff.end():]
|
|
420
|
+
return result
|
|
421
|
+
|
|
422
|
+
# If no hidden-count declaration exists at all, append an exact one.
|
|
423
|
+
if not _ANY_DECLARED_HIDE_RE.search(result):
|
|
424
|
+
result = result + f"\n... {exact_count} lines omitted ({exact_ranges}) ..."
|
|
425
|
+
|
|
426
|
+
return result
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def enforce_baseline_safe(
|
|
430
|
+
text: str,
|
|
431
|
+
raw_output: str,
|
|
432
|
+
archive_key: str | None,
|
|
433
|
+
*,
|
|
434
|
+
threshold_chars: int = 30_000,
|
|
435
|
+
stub_chars: int = 2200,
|
|
436
|
+
is_search: bool = False,
|
|
437
|
+
) -> str:
|
|
438
|
+
"""Line-boundary, visibility-preserving baseline-size invariant.
|
|
439
|
+
|
|
440
|
+
- For raw outputs <= threshold_chars (30 KB), if compressed+pointer would
|
|
441
|
+
exceed raw_output, return raw_output untouched rather than slicing the
|
|
442
|
+
preview mid-sentence and dropping matches/critical lines/hidden counts.
|
|
443
|
+
- For raw outputs > threshold_chars, if compressed+pointer exceeds stub_chars,
|
|
444
|
+
trim cleanly on line boundaries while keeping every critical line and an
|
|
445
|
+
exact hidden-line declaration + archive pointer; if even those exceed
|
|
446
|
+
stub_chars, return raw_output untouched (fail-open).
|
|
447
|
+
"""
|
|
448
|
+
cap = len(raw_output) if len(raw_output) <= threshold_chars else stub_chars
|
|
449
|
+
if len(text) <= cap or text == raw_output:
|
|
450
|
+
return text
|
|
451
|
+
|
|
452
|
+
# Short output: compressed + pointer is larger than raw -> serve raw verbatim.
|
|
453
|
+
if len(raw_output) <= threshold_chars:
|
|
454
|
+
return raw_output
|
|
455
|
+
|
|
456
|
+
raw_lines = raw_output.splitlines()
|
|
457
|
+
crit_lines: list[tuple[int, str]] = []
|
|
458
|
+
for idx, ln in enumerate(raw_lines, 1):
|
|
459
|
+
if not ln.strip():
|
|
460
|
+
continue
|
|
461
|
+
if is_search and is_search_match_line(ln):
|
|
462
|
+
if is_strict_critical_line(ln):
|
|
463
|
+
crit_lines.append((idx, ln))
|
|
464
|
+
continue
|
|
465
|
+
if is_error_or_failure_line(ln):
|
|
466
|
+
crit_lines.append((idx, ln))
|
|
467
|
+
|
|
468
|
+
def _safe_head(s: str, limit: int) -> str:
|
|
469
|
+
from bash_compress import _unicode_safe_head
|
|
470
|
+
return _unicode_safe_head(s, limit)
|
|
471
|
+
|
|
472
|
+
if not archive_key:
|
|
473
|
+
if crit_lines:
|
|
474
|
+
return raw_output
|
|
475
|
+
return _safe_head(text, cap)
|
|
476
|
+
|
|
477
|
+
try:
|
|
478
|
+
from archive_result import build_archive_pointer
|
|
479
|
+
pointer = build_archive_pointer("", len(raw_output), archive_key)
|
|
480
|
+
except Exception:
|
|
481
|
+
return raw_output
|
|
482
|
+
|
|
483
|
+
if not pointer or len(pointer) >= cap:
|
|
484
|
+
return raw_output
|
|
485
|
+
|
|
486
|
+
# Strip existing pointer suffix before trimming body on line boundaries.
|
|
487
|
+
body = text
|
|
488
|
+
ptr_pos = body.find(_ARCHIVE_POINTER_START)
|
|
489
|
+
if ptr_pos >= 0:
|
|
490
|
+
body = body[:ptr_pos]
|
|
491
|
+
|
|
492
|
+
budget = cap - len(pointer)
|
|
493
|
+
# Single-line preview with no critical lines: cap cleanly on grapheme boundary
|
|
494
|
+
# while keeping the archive pointer intact.
|
|
495
|
+
if "\n" not in body and not crit_lines:
|
|
496
|
+
return _safe_head(body, budget) + pointer
|
|
497
|
+
|
|
498
|
+
# Reserve space for critical lines and an exact omission footer.
|
|
499
|
+
crit_block = "\n".join(ln for _, ln in crit_lines)
|
|
500
|
+
reserve_footer = 96
|
|
501
|
+
head_budget = budget - (len(crit_block) + 1 if crit_block else 0) - reserve_footer
|
|
502
|
+
if head_budget < 80:
|
|
503
|
+
return raw_output
|
|
504
|
+
|
|
505
|
+
kept_lines: list[str] = []
|
|
506
|
+
used = 0
|
|
507
|
+
for ln in body.splitlines():
|
|
508
|
+
add_len = len(ln) + (1 if kept_lines else 0)
|
|
509
|
+
if used + add_len > head_budget:
|
|
510
|
+
break
|
|
511
|
+
kept_lines.append(ln)
|
|
512
|
+
used += add_len
|
|
513
|
+
|
|
514
|
+
if not kept_lines and not crit_lines:
|
|
515
|
+
return raw_output
|
|
516
|
+
|
|
517
|
+
preview = "\n".join(kept_lines)
|
|
518
|
+
if crit_lines:
|
|
519
|
+
missing = [ln for _, ln in crit_lines if ln not in preview and ln.strip() not in preview]
|
|
520
|
+
if missing:
|
|
521
|
+
preview = (preview + "\n" if preview else "") + "\n".join(missing)
|
|
522
|
+
|
|
523
|
+
prev_lines = preview.splitlines()
|
|
524
|
+
prev_set = set(prev_lines) | {ln.strip() for ln in prev_lines}
|
|
525
|
+
hidden_nos = [
|
|
526
|
+
idx for idx, ln in enumerate(raw_lines, 1)
|
|
527
|
+
if ln.strip() and ln not in prev_set and ln.strip() not in prev_set
|
|
528
|
+
]
|
|
529
|
+
if hidden_nos:
|
|
530
|
+
footer = f"... {len(hidden_nos)} lines omitted ({format_line_range(hidden_nos)}) ..."
|
|
531
|
+
preview = (preview + "\n" if preview else "") + footer
|
|
532
|
+
|
|
533
|
+
candidate = preview + pointer
|
|
534
|
+
if len(candidate) > cap:
|
|
535
|
+
return raw_output
|
|
536
|
+
return candidate
|