@alexgreensh/token-optimizer 5.13.75 → 5.13.76
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +75 -81
- 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,955 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Additional structured command-output compressors for Token Optimizer.
|
|
3
|
+
|
|
4
|
+
Stdlib-only helper module invoked lazily by ``bash_compress.py`` and
|
|
5
|
+
``build_output_compress.py`` to keep legacy modules under the file-size cap.
|
|
6
|
+
|
|
7
|
+
Covered command families:
|
|
8
|
+
- ``git diff --stat`` / ``git show --stat`` (huge diffs): lossless file
|
|
9
|
+
names grouped by directory (dir prefix once, every basename + churn),
|
|
10
|
+
plus the exact trailing ``N files changed, ...`` summary line verbatim.
|
|
11
|
+
- ``git ls-files`` / ``git ls-tree``: lossless directory-grouped path list
|
|
12
|
+
(dir prefix once, every basename preserved).
|
|
13
|
+
- ``git grep``: routes to existing ``search_results`` handler.
|
|
14
|
+
- ``gh run view --log`` / ``--log-failed``: strips only known GitHub Actions
|
|
15
|
+
setup/checkout/cache/cleanup boilerplate while keeping every line of any
|
|
16
|
+
step/group that contains a failure.
|
|
17
|
+
- ``gh {run,pr,issue,workflow,release} list``: keeps header, top rows, EVERY
|
|
18
|
+
failed/flagged row (uncapped), and a compact summary of remaining entries.
|
|
19
|
+
- ``terraform plan`` / ``tofu plan``: drops state-refresh/read chatter and
|
|
20
|
+
repetitive ``(known after apply)`` / unchanged-attribute noise while
|
|
21
|
+
keeping every resource action header, every ``->`` / ``forces replacement``
|
|
22
|
+
/ ``+`` / ``-`` / ``~`` attribute line, diagnostics, and ``Plan:`` summary.
|
|
23
|
+
- ``kubectl describe``: keeps top metadata, container status, ``Conditions:``,
|
|
24
|
+
full ``Events:`` table, secret/config ``Environment:`` references, and
|
|
25
|
+
error/warning lines; collapses large non-sensitive blocks.
|
|
26
|
+
- Package installers (``pip``/``pip3``/``uv pip``/``npm``/``pnpm``/``yarn``/
|
|
27
|
+
``brew`` install/upgrade/update): drops download/cache/pour progress noise
|
|
28
|
+
while keeping every error, warning, deprecation, vulnerability, caveat,
|
|
29
|
+
and final summary verbatim.
|
|
30
|
+
- ``mypy``: preserves every ``error:``, ``warning:``, ``Revealed type``,
|
|
31
|
+
error-attached ``note:`` (including ``Expected:``/``Got:`` pairs), and
|
|
32
|
+
final summary line verbatim while collapsing only long overload dumps.
|
|
33
|
+
|
|
34
|
+
Safety invariants (all handlers):
|
|
35
|
+
- Fail-open: any unexpected input or exception returns ``None`` so the caller
|
|
36
|
+
leaves the raw output untouched.
|
|
37
|
+
- Short outputs (< 15-25 lines depending on handler) return ``None``.
|
|
38
|
+
- Never returns output longer than (or >= 85% of) the input; lossless path
|
|
39
|
+
groupers pass through unless savings >= ~25%.
|
|
40
|
+
- Errors, warnings, file:line locations, stack frames, and summaries are
|
|
41
|
+
always preserved verbatim. Credential re-injection is additionally enforced
|
|
42
|
+
by the calling pipelines (``bash_compress`` / ``build_output_compress``).
|
|
43
|
+
"""
|
|
44
|
+
from __future__ import annotations
|
|
45
|
+
|
|
46
|
+
import re
|
|
47
|
+
import shlex
|
|
48
|
+
|
|
49
|
+
# ---------------------------------------------------------------------------
|
|
50
|
+
# Feature map for compression_events logging (measured tier)
|
|
51
|
+
# ---------------------------------------------------------------------------
|
|
52
|
+
FEATURE_MAP: dict[str, str] = {
|
|
53
|
+
"git_diff_stat": "cmd_git_diff_stat",
|
|
54
|
+
"git_ls": "cmd_git_ls",
|
|
55
|
+
"gh_run_log": "cmd_gh_log",
|
|
56
|
+
"gh_list": "cmd_gh_list",
|
|
57
|
+
"terraform_plan": "cmd_terraform",
|
|
58
|
+
"kubectl_describe": "cmd_kubectl_describe",
|
|
59
|
+
"pkg_install": "cmd_pkg_install",
|
|
60
|
+
"mypy": "cmd_mypy",
|
|
61
|
+
}
|
|
62
|
+
FEATURE_LABELS: dict[str, str] = {
|
|
63
|
+
"cmd_git_diff_stat": "Git diff --stat compression",
|
|
64
|
+
"cmd_git_ls": "Git ls-files/ls-tree compression",
|
|
65
|
+
"cmd_gh_log": "GitHub Actions log compression",
|
|
66
|
+
"cmd_gh_list": "GitHub CLI list compression",
|
|
67
|
+
"cmd_terraform": "Terraform/OpenTofu plan compression",
|
|
68
|
+
"cmd_kubectl_describe": "kubectl describe compression",
|
|
69
|
+
"cmd_pkg_install": "Package installer compression",
|
|
70
|
+
"cmd_mypy": "mypy output compression",
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
# Read-only gh sub-subcommands allowed across pipeline_analyzer / whitelist.
|
|
74
|
+
GH_READ_ONLY_GROUPS = frozenset({"run", "pr", "issue", "workflow", "release"})
|
|
75
|
+
GH_READ_ONLY_ACTIONS = frozenset({"view", "list", "checks", "diff", "status"})
|
|
76
|
+
|
|
77
|
+
_SHELL_SPLIT_TOKENS = frozenset({"|", "|&", "&&", "||", ";"})
|
|
78
|
+
|
|
79
|
+
# Shared error/warning/location detector used across handlers.
|
|
80
|
+
_IMPORTANT_LINE_RE = re.compile(
|
|
81
|
+
r"(?:##\[(?:error|warning)\]|"
|
|
82
|
+
r"\b(?:error|errors|err!|fatal|panic|fail|failed|failure|exception|"
|
|
83
|
+
r"traceback|assertionerror|warning|warn|deprecated|vulnerabilit|"
|
|
84
|
+
r"conflict|incompatible|oomkilled|crashloopbackoff|imagepullbackoff|"
|
|
85
|
+
r"evicted|unhealthy|backoff|denied|refused|timed out|timeout)\b|"
|
|
86
|
+
r"exit code [1-9]|"
|
|
87
|
+
r"^\s*File \".+\", line \d+)",
|
|
88
|
+
re.IGNORECASE,
|
|
89
|
+
)
|
|
90
|
+
# Case-sensitive failed-job row prefix (e.g. `gh run view <id>` summary rows).
|
|
91
|
+
_GH_FAIL_ROW_RE = re.compile(r"^\s*[X✗✖]\s+")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _is_important_line(ln: str) -> bool:
|
|
95
|
+
"""Return True if a line carries an error, exception, failure, warning, or non-zero exit."""
|
|
96
|
+
try:
|
|
97
|
+
from visibility_rule import is_error_or_failure_line
|
|
98
|
+
if is_error_or_failure_line(ln):
|
|
99
|
+
return True
|
|
100
|
+
except Exception:
|
|
101
|
+
pass
|
|
102
|
+
return bool(_IMPORTANT_LINE_RE.search(ln) or _GH_FAIL_ROW_RE.search(ln))
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def feature_for_pattern(pattern: str) -> str | None:
|
|
106
|
+
"""Return the measured-tier feature name for an extra pattern."""
|
|
107
|
+
return FEATURE_MAP.get(pattern)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def feature_for_command(command_str: str, output: str = "") -> str | None:
|
|
111
|
+
"""Return the dedicated measured feature name for a B2 command, or None."""
|
|
112
|
+
try:
|
|
113
|
+
pat = detect_pattern(command_str)
|
|
114
|
+
if pat in FEATURE_MAP:
|
|
115
|
+
return FEATURE_MAP[pat]
|
|
116
|
+
tokens = _extract_primary_tokens(command_str)
|
|
117
|
+
if not tokens:
|
|
118
|
+
return None
|
|
119
|
+
cmd = tokens[0].rsplit("/", 1)[-1]
|
|
120
|
+
sub = tokens[1] if len(tokens) > 1 else ""
|
|
121
|
+
if cmd == "git":
|
|
122
|
+
j = 1
|
|
123
|
+
while j < len(tokens) and tokens[j].startswith("-"):
|
|
124
|
+
j += 2 if tokens[j] in ("-C", "-c", "--git-dir", "--work-tree") else 1
|
|
125
|
+
gsub = tokens[j] if j < len(tokens) else ""
|
|
126
|
+
if gsub in ("diff", "show") and any(t == "--stat" or t.startswith("--stat=") for t in tokens[j + 1 :]):
|
|
127
|
+
if not output or not any(ln.startswith("diff --git ") for ln in output.splitlines()[:40]):
|
|
128
|
+
return "cmd_git_diff_stat"
|
|
129
|
+
if cmd == "kubectl" and sub == "describe":
|
|
130
|
+
return "cmd_kubectl_describe"
|
|
131
|
+
if cmd == "npm" and sub in ("install", "ci"):
|
|
132
|
+
return "cmd_pkg_install"
|
|
133
|
+
return None
|
|
134
|
+
except Exception:
|
|
135
|
+
return None
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _extract_primary_tokens(command_str: str) -> list[str]:
|
|
139
|
+
"""Return shlex tokens for the primary command (env prefixes stripped)."""
|
|
140
|
+
if not command_str or not isinstance(command_str, str):
|
|
141
|
+
return []
|
|
142
|
+
try:
|
|
143
|
+
tokens = shlex.split(command_str)
|
|
144
|
+
except ValueError:
|
|
145
|
+
return []
|
|
146
|
+
if not tokens:
|
|
147
|
+
return []
|
|
148
|
+
stage: list[str] = []
|
|
149
|
+
for tok in tokens:
|
|
150
|
+
if tok in _SHELL_SPLIT_TOKENS:
|
|
151
|
+
break
|
|
152
|
+
stage.append(tok)
|
|
153
|
+
idx = 0
|
|
154
|
+
if idx < len(stage) and stage[idx] == "env":
|
|
155
|
+
idx += 1
|
|
156
|
+
while idx < len(stage) and "=" in stage[idx] and not stage[idx].startswith("-"):
|
|
157
|
+
idx += 1
|
|
158
|
+
return stage[idx:]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def detect_pattern(command_str: str) -> str | None:
|
|
162
|
+
"""Detect extra command patterns not natively handled by bash_compress."""
|
|
163
|
+
try:
|
|
164
|
+
tokens = _extract_primary_tokens(command_str)
|
|
165
|
+
if not tokens:
|
|
166
|
+
return None
|
|
167
|
+
cmd = tokens[0].rsplit("/", 1)[-1]
|
|
168
|
+
sub = tokens[1] if len(tokens) > 1 else ""
|
|
169
|
+
sub2 = tokens[2] if len(tokens) > 2 else ""
|
|
170
|
+
|
|
171
|
+
if cmd == "git":
|
|
172
|
+
# Skip git global flags like -C <dir> or -c k=v
|
|
173
|
+
j = 1
|
|
174
|
+
while j < len(tokens) and tokens[j].startswith("-"):
|
|
175
|
+
if tokens[j] in ("-C", "-c", "--git-dir", "--work-tree"):
|
|
176
|
+
j += 2
|
|
177
|
+
else:
|
|
178
|
+
j += 1
|
|
179
|
+
gsub = tokens[j] if j < len(tokens) else ""
|
|
180
|
+
if gsub == "grep":
|
|
181
|
+
return "search_results"
|
|
182
|
+
if gsub in ("ls-files", "ls-tree"):
|
|
183
|
+
return "git_ls"
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
if cmd == "gh":
|
|
187
|
+
if sub == "run" and sub2 == "view":
|
|
188
|
+
# Only route to the log compressor when --log / --log-failed is passed;
|
|
189
|
+
# `gh run view <id>` without --log emits a job summary table.
|
|
190
|
+
if any(t in ("--log", "--log-failed") for t in tokens[3:]):
|
|
191
|
+
return "gh_run_log"
|
|
192
|
+
return None
|
|
193
|
+
if sub in GH_READ_ONLY_GROUPS and sub2 == "list":
|
|
194
|
+
return "gh_list"
|
|
195
|
+
return None
|
|
196
|
+
|
|
197
|
+
if cmd in ("terraform", "tofu") and sub == "plan":
|
|
198
|
+
return "terraform_plan"
|
|
199
|
+
|
|
200
|
+
if cmd == "mypy":
|
|
201
|
+
return "mypy"
|
|
202
|
+
|
|
203
|
+
if cmd in ("pnpm", "yarn") and sub in ("install", "add", "upgrade", "up"):
|
|
204
|
+
return "pkg_install"
|
|
205
|
+
if cmd in ("pip", "pip3") and sub == "install":
|
|
206
|
+
return "pkg_install"
|
|
207
|
+
if cmd == "uv" and sub == "pip" and sub2 == "install":
|
|
208
|
+
return "pkg_install"
|
|
209
|
+
if cmd == "uv" and sub == "sync":
|
|
210
|
+
return "pkg_install"
|
|
211
|
+
if cmd == "brew" and sub in ("install", "upgrade", "reinstall", "update"):
|
|
212
|
+
return "pkg_install"
|
|
213
|
+
|
|
214
|
+
return None
|
|
215
|
+
except Exception:
|
|
216
|
+
return None
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
# ---------------------------------------------------------------------------
|
|
220
|
+
# 1. git diff --stat / git show --stat (LOSSLESS names, grouped by directory)
|
|
221
|
+
# ---------------------------------------------------------------------------
|
|
222
|
+
_DIFF_STAT_LINE_RE = re.compile(
|
|
223
|
+
r"^\s*(.+?)\s+\|\s+(?:(\d+)\s*[+-]*|(Bin\s+\d+\s*->\s*\d+\s*bytes))\s*$"
|
|
224
|
+
)
|
|
225
|
+
_DIFF_STAT_SUMMARY_RE = re.compile(
|
|
226
|
+
r"^\s*\d+\s+files?\s+changed(?:,\s+\d+\s+insertions?\(\+\))?(?:,\s+\d+\s+deletions?\(-\))?\s*$"
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _split_stat_dir_base(path: str) -> tuple[str, str]:
|
|
231
|
+
"""Split a diff-stat path into (dir_prefix, basename) without losing renames."""
|
|
232
|
+
if " => " in path:
|
|
233
|
+
brace_idx = path.find("{")
|
|
234
|
+
if brace_idx > 0:
|
|
235
|
+
slash_idx = path.rfind("/", 0, brace_idx)
|
|
236
|
+
if slash_idx >= 0:
|
|
237
|
+
return path[: slash_idx + 1], path[slash_idx + 1 :]
|
|
238
|
+
return "./", path
|
|
239
|
+
if "/" in path:
|
|
240
|
+
d, base = path.rsplit("/", 1)
|
|
241
|
+
return d + "/", base
|
|
242
|
+
return "./", path
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def compress_git_diff_stat(output: str) -> str | None:
|
|
246
|
+
"""Compress ``git diff --stat`` losslessly by grouping basenames under each dir."""
|
|
247
|
+
try:
|
|
248
|
+
lines = output.splitlines()
|
|
249
|
+
if len(lines) < 25:
|
|
250
|
+
return None
|
|
251
|
+
# Do not touch full patch diffs (those have diff --git headers)
|
|
252
|
+
if any(ln.startswith("diff --git ") for ln in lines[:40]):
|
|
253
|
+
return None
|
|
254
|
+
|
|
255
|
+
summary_idx = -1
|
|
256
|
+
for i in range(len(lines) - 1, max(-1, len(lines) - 6), -1):
|
|
257
|
+
if _DIFF_STAT_SUMMARY_RE.match(lines[i]):
|
|
258
|
+
summary_idx = i
|
|
259
|
+
break
|
|
260
|
+
if summary_idx < 0:
|
|
261
|
+
return None
|
|
262
|
+
|
|
263
|
+
preamble: list[tuple[int, str]] = []
|
|
264
|
+
stat_entries: list[tuple[str, int, str | None]] = [] # (path, count, bin_info)
|
|
265
|
+
extra_lines: list[tuple[int, str]] = []
|
|
266
|
+
|
|
267
|
+
for lno, ln in enumerate(lines[:summary_idx], 1):
|
|
268
|
+
m = _DIFF_STAT_LINE_RE.match(ln)
|
|
269
|
+
if m:
|
|
270
|
+
path = m.group(1).strip()
|
|
271
|
+
count = int(m.group(2)) if m.group(2) else 0
|
|
272
|
+
bin_info = m.group(3)
|
|
273
|
+
stat_entries.append((path, count, bin_info))
|
|
274
|
+
elif not stat_entries:
|
|
275
|
+
preamble.append((lno, ln))
|
|
276
|
+
elif ln.strip():
|
|
277
|
+
extra_lines.append((lno, ln))
|
|
278
|
+
|
|
279
|
+
if len(stat_entries) < 20:
|
|
280
|
+
return None
|
|
281
|
+
|
|
282
|
+
# Group ALL entries by directory; keep every basename and its churn count.
|
|
283
|
+
dir_groups: dict[str, list[tuple[str, int, str | None]]] = {}
|
|
284
|
+
for path, count, bin_info in stat_entries:
|
|
285
|
+
d, base = _split_stat_dir_base(path)
|
|
286
|
+
dir_groups.setdefault(d, []).append((base, count, bin_info))
|
|
287
|
+
|
|
288
|
+
out: list[str] = []
|
|
289
|
+
if preamble:
|
|
290
|
+
out.extend(ln for _, ln in preamble[:10])
|
|
291
|
+
if len(preamble) > 10:
|
|
292
|
+
kept_pre = [(n, ln) for n, ln in preamble[10:] if _is_important_line(ln)]
|
|
293
|
+
omitted_pre = [n for n, ln in preamble[10:] if not _is_important_line(ln) and ln.strip()]
|
|
294
|
+
out.extend(ln for _, ln in kept_pre)
|
|
295
|
+
if omitted_pre:
|
|
296
|
+
out.append(f"... {len(omitted_pre)} preamble lines omitted (lines {omitted_pre[0]}-{omitted_pre[-1]}) ...")
|
|
297
|
+
out.append(f"[git diff --stat: {len(stat_entries)} files, grouped by dir]")
|
|
298
|
+
for d in sorted(dir_groups):
|
|
299
|
+
items = dir_groups[d]
|
|
300
|
+
rendered = [
|
|
301
|
+
f"{base}({bin_info})" if bin_info else f"{base}({count})"
|
|
302
|
+
for base, count, bin_info in items
|
|
303
|
+
]
|
|
304
|
+
out.append(f" {d} " + ", ".join(rendered))
|
|
305
|
+
if extra_lines:
|
|
306
|
+
out.extend(ln for _, ln in extra_lines[:10])
|
|
307
|
+
if len(extra_lines) > 10:
|
|
308
|
+
kept_ex = [(n, ln) for n, ln in extra_lines[10:] if _is_important_line(ln)]
|
|
309
|
+
omitted_ex = [n for n, ln in extra_lines[10:] if not _is_important_line(ln)]
|
|
310
|
+
out.extend(ln for _, ln in kept_ex)
|
|
311
|
+
if omitted_ex:
|
|
312
|
+
out.append(f"... {len(omitted_ex)} extra lines omitted (lines {omitted_ex[0]}-{omitted_ex[-1]}) ...")
|
|
313
|
+
# Exact trailing summary line(s) verbatim
|
|
314
|
+
out.extend(lines[summary_idx:])
|
|
315
|
+
|
|
316
|
+
result = "\n".join(out)
|
|
317
|
+
# Pass through if savings < ~25%
|
|
318
|
+
return result if len(result) < len(output) * 0.75 else None
|
|
319
|
+
except Exception:
|
|
320
|
+
return None
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
# ---------------------------------------------------------------------------
|
|
324
|
+
# 2. git ls-files / git ls-tree (LOSSLESS names, grouped by directory)
|
|
325
|
+
# ---------------------------------------------------------------------------
|
|
326
|
+
_LS_TREE_LINE_RE = re.compile(r"^\d{6}\s+(?:blob|tree|commit)\s+[0-9a-f]{40,64}\t(.+)$")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def compress_git_ls(output: str, command_str: str = "") -> str | None:
|
|
330
|
+
"""Compress ``git ls-files`` or ``git ls-tree`` losslessly by directory prefix."""
|
|
331
|
+
try:
|
|
332
|
+
lines = [ln for ln in output.splitlines() if ln.strip()]
|
|
333
|
+
if len(lines) < 25 or len(lines) > 50_000:
|
|
334
|
+
return None
|
|
335
|
+
|
|
336
|
+
paths: list[str] = []
|
|
337
|
+
is_tree = False
|
|
338
|
+
for ln in lines:
|
|
339
|
+
m = _LS_TREE_LINE_RE.match(ln)
|
|
340
|
+
if m:
|
|
341
|
+
is_tree = True
|
|
342
|
+
paths.append(m.group(1))
|
|
343
|
+
else:
|
|
344
|
+
if ln.startswith(("fatal:", "error:", "usage:")):
|
|
345
|
+
return None
|
|
346
|
+
paths.append(ln)
|
|
347
|
+
|
|
348
|
+
groups: dict[str, list[str]] = {}
|
|
349
|
+
root_files: list[str] = []
|
|
350
|
+
for p in paths:
|
|
351
|
+
if "/" in p:
|
|
352
|
+
d, base = p.rsplit("/", 1)
|
|
353
|
+
groups.setdefault(d + "/", []).append(base)
|
|
354
|
+
else:
|
|
355
|
+
root_files.append(p)
|
|
356
|
+
|
|
357
|
+
label = "git ls-tree" if (is_tree or "ls-tree" in command_str) else "git ls-files"
|
|
358
|
+
out = [f"[{label}: {len(paths)} paths total, grouped by directory]"]
|
|
359
|
+
if root_files:
|
|
360
|
+
out.append("./ " + " ".join(root_files))
|
|
361
|
+
for d in sorted(groups):
|
|
362
|
+
out.append(d + " " + " ".join(groups[d]))
|
|
363
|
+
|
|
364
|
+
result = "\n".join(out)
|
|
365
|
+
# Pass through if savings < ~25%
|
|
366
|
+
return result if len(result) < len(output) * 0.75 else None
|
|
367
|
+
except Exception:
|
|
368
|
+
return None
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
# ---------------------------------------------------------------------------
|
|
372
|
+
# 3. gh run view --log / --log-failed
|
|
373
|
+
# ---------------------------------------------------------------------------
|
|
374
|
+
_GH_LOG_NOISE_RE = re.compile(
|
|
375
|
+
r"(?:##\[(?:group|endgroup)\]|"
|
|
376
|
+
r"Current runner version:|Operating System|Runner Image|GITHUB_TOKEN Permissions|"
|
|
377
|
+
r"Prepare workflow directory|Prepare all required actions|"
|
|
378
|
+
r"Getting action download info|Download action repository|"
|
|
379
|
+
r"Complete job name:|Syncing repository:|Fetching the repository|"
|
|
380
|
+
r"Getting Git version info|Temporarily overriding HOME|"
|
|
381
|
+
r"Adding repository directory to the temporary git global config|"
|
|
382
|
+
r"Checking out the ref|Post job cleanup|Cleaning up orphan processes|"
|
|
383
|
+
r"Cache restored from key|Restoring cache|Saving cache|Post Cache|"
|
|
384
|
+
r"Set up job|Run actions/checkout|Run actions/setup-|Run actions/cache|"
|
|
385
|
+
r"Post Run actions/|Complete job\b)",
|
|
386
|
+
re.IGNORECASE,
|
|
387
|
+
)
|
|
388
|
+
_GH_TS_PREFIX_RE = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\s+")
|
|
389
|
+
_GH_FAIL_BODY_RE = re.compile(
|
|
390
|
+
r"^\s*(?:E\s+|>\s+|FAILED\s+|___+\s+.+?\s+___+|===+\s+(?:FAILURES|ERRORS)\s+===+)"
|
|
391
|
+
)
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _gh_log_line_parts(ln: str) -> tuple[str | None, str]:
|
|
395
|
+
"""Return (tab_step_key_or_None, message_body_without_timestamp)."""
|
|
396
|
+
parts = ln.split("\t", 2)
|
|
397
|
+
if len(parts) == 3:
|
|
398
|
+
step_key = f"{parts[0]}\t{parts[1]}"
|
|
399
|
+
body = _GH_TS_PREFIX_RE.sub("", parts[2])
|
|
400
|
+
return step_key, body
|
|
401
|
+
return None, _GH_TS_PREFIX_RE.sub("", ln)
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def compress_gh_run_log(output: str) -> str | None:
|
|
405
|
+
"""Compress ``gh run view --log`` by stripping known CI noise only.
|
|
406
|
+
|
|
407
|
+
Every line of any step or ``##[group]`` that contains a failure (assertion,
|
|
408
|
+
``E`` lines, test body, traceback, error, non-zero exit) is preserved whole.
|
|
409
|
+
Non-noise lines outside failing steps are also preserved.
|
|
410
|
+
"""
|
|
411
|
+
try:
|
|
412
|
+
lines = output.splitlines()
|
|
413
|
+
if len(lines) < 25:
|
|
414
|
+
return None
|
|
415
|
+
|
|
416
|
+
# Assign each line to its step (job\tstep) or ##[group]..##[endgroup] block.
|
|
417
|
+
keys: list[tuple[str, str | int]] = []
|
|
418
|
+
failing_keys: set[tuple[str, str | int]] = set()
|
|
419
|
+
group_id = 0
|
|
420
|
+
in_group = False
|
|
421
|
+
|
|
422
|
+
for idx, ln in enumerate(lines):
|
|
423
|
+
tab_key, body = _gh_log_line_parts(ln)
|
|
424
|
+
if tab_key is not None:
|
|
425
|
+
key: tuple[str, str | int] = ("step", tab_key)
|
|
426
|
+
else:
|
|
427
|
+
if "##[group]" in ln:
|
|
428
|
+
group_id += 1
|
|
429
|
+
in_group = True
|
|
430
|
+
key = ("grp", group_id)
|
|
431
|
+
elif in_group:
|
|
432
|
+
key = ("grp", group_id)
|
|
433
|
+
if "##[endgroup]" in ln:
|
|
434
|
+
in_group = False
|
|
435
|
+
else:
|
|
436
|
+
key = ("line", idx)
|
|
437
|
+
keys.append(key)
|
|
438
|
+
if _is_important_line(ln) or _GH_FAIL_BODY_RE.search(body):
|
|
439
|
+
failing_keys.add(key)
|
|
440
|
+
|
|
441
|
+
out: list[str] = []
|
|
442
|
+
omitted = 0
|
|
443
|
+
omitted_start = 0
|
|
444
|
+
omitted_end = 0
|
|
445
|
+
noise_dropped = 0
|
|
446
|
+
for idx, (ln, key) in enumerate(zip(lines, keys), 1):
|
|
447
|
+
if key in failing_keys:
|
|
448
|
+
if omitted:
|
|
449
|
+
out.append(f"... [{omitted} CI setup/boilerplate lines omitted (lines {omitted_start}-{omitted_end})] ...")
|
|
450
|
+
omitted = 0
|
|
451
|
+
out.append(ln)
|
|
452
|
+
elif _GH_LOG_NOISE_RE.search(ln):
|
|
453
|
+
if omitted == 0:
|
|
454
|
+
omitted_start = idx
|
|
455
|
+
omitted_end = idx
|
|
456
|
+
omitted += 1
|
|
457
|
+
noise_dropped += 1
|
|
458
|
+
else:
|
|
459
|
+
if omitted:
|
|
460
|
+
out.append(f"... [{omitted} CI setup/boilerplate lines omitted (lines {omitted_start}-{omitted_end})] ...")
|
|
461
|
+
omitted = 0
|
|
462
|
+
out.append(ln)
|
|
463
|
+
if omitted:
|
|
464
|
+
out.append(f"... [{omitted} CI setup/boilerplate lines omitted (lines {omitted_start}-{omitted_end})] ...")
|
|
465
|
+
|
|
466
|
+
if noise_dropped < 5:
|
|
467
|
+
return None
|
|
468
|
+
result = "\n".join(out)
|
|
469
|
+
return result if len(result) < len(output) * 0.85 else None
|
|
470
|
+
except Exception:
|
|
471
|
+
return None
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
# ---------------------------------------------------------------------------
|
|
475
|
+
# 4. gh {run,pr,issue,workflow,release} list
|
|
476
|
+
# ---------------------------------------------------------------------------
|
|
477
|
+
_GH_LIST_ALERT_RE = re.compile(
|
|
478
|
+
r"\b(?:failure|failed|cancelled|timed_out|action_required|error|changes_requested)\b",
|
|
479
|
+
re.IGNORECASE,
|
|
480
|
+
)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _is_gh_list_alert(ln: str) -> bool:
|
|
484
|
+
try:
|
|
485
|
+
from visibility_rule import is_error_or_failure_line
|
|
486
|
+
if is_error_or_failure_line(ln):
|
|
487
|
+
return True
|
|
488
|
+
except Exception:
|
|
489
|
+
pass
|
|
490
|
+
return bool(_GH_LIST_ALERT_RE.search(ln) or _GH_FAIL_ROW_RE.search(ln))
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
def compress_gh_list(output: str) -> str | None:
|
|
494
|
+
"""Compress long ``gh run/pr/issue list`` tabular outputs without capping failures."""
|
|
495
|
+
try:
|
|
496
|
+
lines = [ln for ln in output.splitlines() if ln.strip()]
|
|
497
|
+
if len(lines) < 20:
|
|
498
|
+
return None
|
|
499
|
+
|
|
500
|
+
keep_head = 12
|
|
501
|
+
head = lines[:keep_head]
|
|
502
|
+
rest = lines[keep_head:]
|
|
503
|
+
alert_rows: list[str] = []
|
|
504
|
+
other_rows: list[tuple[int, str]] = []
|
|
505
|
+
for idx, ln in enumerate(rest, keep_head + 1):
|
|
506
|
+
if _is_gh_list_alert(ln):
|
|
507
|
+
alert_rows.append(ln)
|
|
508
|
+
else:
|
|
509
|
+
other_rows.append((idx, ln))
|
|
510
|
+
|
|
511
|
+
out = list(head)
|
|
512
|
+
if alert_rows:
|
|
513
|
+
out.append(f"... [{len(alert_rows)} additional failing/flagged rows preserved] ...")
|
|
514
|
+
out.extend(alert_rows)
|
|
515
|
+
if other_rows:
|
|
516
|
+
ids = []
|
|
517
|
+
for _idx, ln in other_rows:
|
|
518
|
+
cols = ln.split("\t") if "\t" in ln else ln.split()
|
|
519
|
+
if cols:
|
|
520
|
+
ids.append(cols[0].strip())
|
|
521
|
+
sample = ", ".join(ids[:20])
|
|
522
|
+
suffix = f", ... (+{len(ids) - 20} more)" if len(ids) > 20 else ""
|
|
523
|
+
lo, hi = other_rows[0][0], other_rows[-1][0]
|
|
524
|
+
loc = f"line {lo}" if lo == hi else f"lines {lo}-{hi}"
|
|
525
|
+
out.append(f"... plus {len(other_rows)} more rows ({loc} of {len(lines)} total): {sample}{suffix}")
|
|
526
|
+
|
|
527
|
+
result = "\n".join(out)
|
|
528
|
+
return result if len(result) < len(output) * 0.85 else None
|
|
529
|
+
except Exception:
|
|
530
|
+
return None
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
# ---------------------------------------------------------------------------
|
|
534
|
+
# 5. terraform plan / tofu plan
|
|
535
|
+
# ---------------------------------------------------------------------------
|
|
536
|
+
_TF_DETECT_RE = re.compile(
|
|
537
|
+
r"(?:Terraform will perform|OpenTofu will perform|Plan:\s+\d+\s+to add|"
|
|
538
|
+
r"No changes\.|Refreshing state\.\.\.|Terraform used the selected providers|"
|
|
539
|
+
r"OpenTofu used the selected providers)"
|
|
540
|
+
)
|
|
541
|
+
_TF_NOISE_RE = re.compile(
|
|
542
|
+
r"^(?:\s*[\w.\-\[\]\"']+:\s*(?:Refreshing state\.\.\.|Reading\.\.\.|Read complete after|Still reading\.\.\.)|"
|
|
543
|
+
r"Acquiring state lock\.|Releasing state lock\.|"
|
|
544
|
+
r"\s*#\s*\(\d+\s+unchanged\s+(?:attributes?|blocks?)\s+hidden\)\s*$)"
|
|
545
|
+
)
|
|
546
|
+
_TF_RESOURCE_HDR_RE = re.compile(r"^\s*#\s+\S+.*(?:will be|must be|has changed|is tainted)")
|
|
547
|
+
_TF_RESOURCE_BLOCK_RE = re.compile(r"^\s*(?:[+~-]|-/\+|\+/-)\s+(?:resource|data|module)\s+")
|
|
548
|
+
_TF_SUMMARY_RE = re.compile(
|
|
549
|
+
r"^(?:Plan:\s+|No changes\.|Changes to Outputs:|Saved the plan to:|"
|
|
550
|
+
r"Apply complete!|Destroy complete!)"
|
|
551
|
+
)
|
|
552
|
+
_TF_DIAG_RE = re.compile(r"^[│╷╵]|\b(?:Warning|Error):|^\s*on\s+\S+\s+line\s+\d+")
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def compress_terraform_plan(output: str) -> str | None:
|
|
556
|
+
"""Compress verbose ``terraform plan`` / ``tofu plan`` output safely.
|
|
557
|
+
|
|
558
|
+
Never drops any ``->``, ``forces replacement``, or ``+``/``-``/``~``
|
|
559
|
+
attribute line inside a changed resource; collapses only state-refresh
|
|
560
|
+
chatter, ``(known after apply)`` lines, and unchanged-attribute noise.
|
|
561
|
+
"""
|
|
562
|
+
try:
|
|
563
|
+
lines = output.splitlines()
|
|
564
|
+
if len(lines) < 20:
|
|
565
|
+
return None
|
|
566
|
+
if not _TF_DETECT_RE.search(output):
|
|
567
|
+
return None
|
|
568
|
+
|
|
569
|
+
out: list[str] = []
|
|
570
|
+
noise_dropped = 0
|
|
571
|
+
noise_first = 0
|
|
572
|
+
noise_last = 0
|
|
573
|
+
in_resource = False
|
|
574
|
+
resource_indent = 0
|
|
575
|
+
unchanged_kept = 0
|
|
576
|
+
unchanged_dropped = 0
|
|
577
|
+
known_after_dropped = 0
|
|
578
|
+
res_first = 0
|
|
579
|
+
res_last = 0
|
|
580
|
+
in_outputs = False
|
|
581
|
+
|
|
582
|
+
def _flush_resource_omissions() -> None:
|
|
583
|
+
nonlocal unchanged_dropped, known_after_dropped, res_first, res_last
|
|
584
|
+
parts = []
|
|
585
|
+
if known_after_dropped:
|
|
586
|
+
parts.append(f"{known_after_dropped} '(known after apply)'")
|
|
587
|
+
if unchanged_dropped:
|
|
588
|
+
parts.append(f"{unchanged_dropped} unchanged attributes")
|
|
589
|
+
if parts:
|
|
590
|
+
loc = f", lines {res_first}-{res_last}" if res_first else ""
|
|
591
|
+
out.append(f" # ... ({', '.join(parts)} collapsed{loc})")
|
|
592
|
+
unchanged_dropped = 0
|
|
593
|
+
known_after_dropped = 0
|
|
594
|
+
res_first = 0
|
|
595
|
+
res_last = 0
|
|
596
|
+
|
|
597
|
+
for idx, ln in enumerate(lines, 1):
|
|
598
|
+
if _TF_NOISE_RE.match(ln):
|
|
599
|
+
if noise_dropped == 0:
|
|
600
|
+
noise_first = idx
|
|
601
|
+
noise_last = idx
|
|
602
|
+
noise_dropped += 1
|
|
603
|
+
continue
|
|
604
|
+
|
|
605
|
+
if _TF_DIAG_RE.search(ln) or _is_important_line(ln):
|
|
606
|
+
_flush_resource_omissions()
|
|
607
|
+
out.append(ln)
|
|
608
|
+
continue
|
|
609
|
+
|
|
610
|
+
if _TF_SUMMARY_RE.match(ln.strip()):
|
|
611
|
+
_flush_resource_omissions()
|
|
612
|
+
in_resource = False
|
|
613
|
+
if ln.strip().startswith("Changes to Outputs:"):
|
|
614
|
+
in_outputs = True
|
|
615
|
+
out.append(ln)
|
|
616
|
+
continue
|
|
617
|
+
|
|
618
|
+
if in_outputs:
|
|
619
|
+
out.append(ln)
|
|
620
|
+
continue
|
|
621
|
+
|
|
622
|
+
if _TF_RESOURCE_HDR_RE.match(ln):
|
|
623
|
+
_flush_resource_omissions()
|
|
624
|
+
in_resource = True
|
|
625
|
+
resource_indent = len(ln) - len(ln.lstrip(" "))
|
|
626
|
+
unchanged_kept = 0
|
|
627
|
+
out.append(ln)
|
|
628
|
+
continue
|
|
629
|
+
|
|
630
|
+
if _TF_RESOURCE_BLOCK_RE.match(ln):
|
|
631
|
+
in_resource = True
|
|
632
|
+
resource_indent = len(ln) - len(ln.lstrip(" "))
|
|
633
|
+
unchanged_kept = 0
|
|
634
|
+
out.append(ln)
|
|
635
|
+
continue
|
|
636
|
+
|
|
637
|
+
if in_resource:
|
|
638
|
+
stripped = ln.strip()
|
|
639
|
+
indent = len(ln) - len(ln.lstrip(" "))
|
|
640
|
+
if stripped == "}":
|
|
641
|
+
_flush_resource_omissions()
|
|
642
|
+
out.append(ln)
|
|
643
|
+
if indent <= resource_indent + 2:
|
|
644
|
+
in_resource = False
|
|
645
|
+
continue
|
|
646
|
+
# Never drop `->` or `forces replacement` lines.
|
|
647
|
+
if "forces replacement" in ln or "->" in ln:
|
|
648
|
+
_flush_resource_omissions()
|
|
649
|
+
out.append(ln)
|
|
650
|
+
continue
|
|
651
|
+
# Collapse `(known after apply)` placeholder lines.
|
|
652
|
+
if "(known after apply)" in ln:
|
|
653
|
+
if not res_first:
|
|
654
|
+
res_first = idx
|
|
655
|
+
res_last = idx
|
|
656
|
+
known_after_dropped += 1
|
|
657
|
+
continue
|
|
658
|
+
# Never drop any `+`, `-`, or `~` attribute line inside a resource.
|
|
659
|
+
if stripped.startswith(("+", "-", "~")):
|
|
660
|
+
_flush_resource_omissions()
|
|
661
|
+
out.append(ln)
|
|
662
|
+
continue
|
|
663
|
+
# Keep structural block openers/closers and a few unchanged context lines.
|
|
664
|
+
if stripped.endswith("{") or not stripped:
|
|
665
|
+
_flush_resource_omissions()
|
|
666
|
+
out.append(ln)
|
|
667
|
+
continue
|
|
668
|
+
if unchanged_kept < 4:
|
|
669
|
+
_flush_resource_omissions()
|
|
670
|
+
out.append(ln)
|
|
671
|
+
unchanged_kept += 1
|
|
672
|
+
else:
|
|
673
|
+
if not res_first:
|
|
674
|
+
res_first = idx
|
|
675
|
+
res_last = idx
|
|
676
|
+
unchanged_dropped += 1
|
|
677
|
+
continue
|
|
678
|
+
|
|
679
|
+
if ln.strip():
|
|
680
|
+
out.append(ln)
|
|
681
|
+
|
|
682
|
+
_flush_resource_omissions()
|
|
683
|
+
if noise_dropped:
|
|
684
|
+
out.insert(0, f"[terraform plan: {noise_dropped} state-refresh/unchanged lines collapsed (lines {noise_first}-{noise_last})]")
|
|
685
|
+
|
|
686
|
+
result = "\n".join(out)
|
|
687
|
+
return result if len(result) < len(output) * 0.85 else None
|
|
688
|
+
except Exception:
|
|
689
|
+
return None
|
|
690
|
+
|
|
691
|
+
|
|
692
|
+
# ---------------------------------------------------------------------------
|
|
693
|
+
# 6. kubectl describe
|
|
694
|
+
# ---------------------------------------------------------------------------
|
|
695
|
+
_K8S_DESC_COLLAPSE_SECTIONS = frozenset({
|
|
696
|
+
"Annotations:", "Labels:", "Environment:", "Mounts:", "Volumes:",
|
|
697
|
+
"Tolerations:", "Managed Fields:", "Args:", "Command:", "Data",
|
|
698
|
+
})
|
|
699
|
+
_K8S_ENV_KEEP_RE = re.compile(
|
|
700
|
+
r"(?:valueFrom|secretKeyRef|configMapKeyRef|<set to the key\b|"
|
|
701
|
+
r"\b[A-Za-z0-9_]*_(?:URL|KEY|SECRET|TOKEN|PASSWORD|DSN)\b)",
|
|
702
|
+
re.IGNORECASE,
|
|
703
|
+
)
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def compress_kubectl_describe(output: str) -> str | None:
|
|
707
|
+
"""Compress verbose ``kubectl describe`` output while keeping Events, status & secret env refs."""
|
|
708
|
+
try:
|
|
709
|
+
lines = output.splitlines()
|
|
710
|
+
if len(lines) < 25:
|
|
711
|
+
return None
|
|
712
|
+
head_blob = "\n".join(lines[:15])
|
|
713
|
+
if "Name:" not in head_blob or not any(
|
|
714
|
+
k in output for k in ("Namespace:", "Status:", "Events:", "Conditions:", "Containers:")
|
|
715
|
+
):
|
|
716
|
+
return None
|
|
717
|
+
|
|
718
|
+
out: list[str] = []
|
|
719
|
+
i = 0
|
|
720
|
+
n = len(lines)
|
|
721
|
+
while i < n:
|
|
722
|
+
ln = lines[i]
|
|
723
|
+
stripped = ln.strip()
|
|
724
|
+
indent = len(ln) - len(ln.lstrip(" "))
|
|
725
|
+
|
|
726
|
+
# Events: and Conditions: are ALWAYS preserved in full
|
|
727
|
+
if indent == 0 and stripped in ("Events:", "Conditions:"):
|
|
728
|
+
out.append(ln)
|
|
729
|
+
i += 1
|
|
730
|
+
while i < n and (not lines[i].strip() or lines[i].startswith(" ")):
|
|
731
|
+
out.append(lines[i])
|
|
732
|
+
i += 1
|
|
733
|
+
continue
|
|
734
|
+
|
|
735
|
+
# Check if this starts a collapsible block (e.g. Annotations:, Environment:, Mounts:)
|
|
736
|
+
sec_key = stripped.split(":", 1)[0] + ":" if ":" in stripped else stripped
|
|
737
|
+
if sec_key in _K8S_DESC_COLLAPSE_SECTIONS and sec_key != "Status:":
|
|
738
|
+
block = [ln]
|
|
739
|
+
j = i + 1
|
|
740
|
+
while j < n and lines[j].strip() and (len(lines[j]) - len(lines[j].lstrip(" "))) > indent:
|
|
741
|
+
block.append(lines[j])
|
|
742
|
+
j += 1
|
|
743
|
+
if len(block) > 6:
|
|
744
|
+
out.append(block[0])
|
|
745
|
+
kept_children = block[1:3]
|
|
746
|
+
out.extend(kept_children)
|
|
747
|
+
is_env = sec_key == "Environment:"
|
|
748
|
+
important_children = [
|
|
749
|
+
b for b in block[3:]
|
|
750
|
+
if _is_important_line(b) or (is_env and _K8S_ENV_KEEP_RE.search(b))
|
|
751
|
+
]
|
|
752
|
+
out.extend(important_children)
|
|
753
|
+
dropped = len(block) - 3 - len(important_children)
|
|
754
|
+
if dropped > 0:
|
|
755
|
+
out.append(f"{' ' * (indent + 2)}... ({dropped} more {sec_key.rstrip(':')} lines collapsed, lines {i + 4}-{j})")
|
|
756
|
+
i = j
|
|
757
|
+
continue
|
|
758
|
+
|
|
759
|
+
out.append(ln)
|
|
760
|
+
i += 1
|
|
761
|
+
|
|
762
|
+
result = "\n".join(out)
|
|
763
|
+
return result if len(result) < len(output) * 0.85 else None
|
|
764
|
+
except Exception:
|
|
765
|
+
return None
|
|
766
|
+
|
|
767
|
+
|
|
768
|
+
# ---------------------------------------------------------------------------
|
|
769
|
+
# 7. Package installers (pip / uv pip / npm / pnpm / yarn / brew)
|
|
770
|
+
# ---------------------------------------------------------------------------
|
|
771
|
+
_PKG_NOISE_RE = re.compile(
|
|
772
|
+
r"^(?:\s*(?:Collecting|Downloading|Using cached|Requirement already satisfied|"
|
|
773
|
+
r"Preparing metadata|Getting requirements to build|Building wheels?|"
|
|
774
|
+
r"Created wheel|Stored in directory:|Installing build dependencies|"
|
|
775
|
+
r"Installing collected packages|Resolved \d+ package|Prepared \d+ package|"
|
|
776
|
+
r"Uninstalled \d+ package|Downloaded \d+ package|"
|
|
777
|
+
r"Progress: resolved|Packages: [+-]|Resolving packages|Fetching packages|"
|
|
778
|
+
r"Linking dependencies|Building fresh packages|Already downloaded:|"
|
|
779
|
+
r"==> (?:Downloading|Pouring|Fetching|Installing|Cleaning up|Running `brew cleanup`)|"
|
|
780
|
+
r"reify:|idealTree:|sill |http fetch|⸨|[+]{5,}|[#]{5,}|[━─=]{5,}))",
|
|
781
|
+
re.IGNORECASE,
|
|
782
|
+
)
|
|
783
|
+
_PKG_SUMMARY_RE = re.compile(
|
|
784
|
+
r"(?:Successfully installed|Installed \d+ package|added \d+ package|"
|
|
785
|
+
r"removed \d+ package|changed \d+ package|audited \d+ package|"
|
|
786
|
+
r"up to date|found \d+ vulnerabilit|Done in \d|==> Summary|==> Caveats|"
|
|
787
|
+
r"Already up-to-date|🍺)",
|
|
788
|
+
re.IGNORECASE,
|
|
789
|
+
)
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def compress_package_install(output: str) -> str | None:
|
|
793
|
+
"""Compress verbose pip/uv/npm/pnpm/yarn/brew install/upgrade output."""
|
|
794
|
+
try:
|
|
795
|
+
lines = output.splitlines()
|
|
796
|
+
if len(lines) < 15:
|
|
797
|
+
return None
|
|
798
|
+
|
|
799
|
+
kept: list[str] = []
|
|
800
|
+
dropped = 0
|
|
801
|
+
first_dropped = 0
|
|
802
|
+
last_dropped = 0
|
|
803
|
+
in_caveats = False
|
|
804
|
+
|
|
805
|
+
for idx, ln in enumerate(lines, 1):
|
|
806
|
+
stripped = ln.strip()
|
|
807
|
+
if not stripped:
|
|
808
|
+
if in_caveats:
|
|
809
|
+
in_caveats = False
|
|
810
|
+
continue
|
|
811
|
+
|
|
812
|
+
if stripped.startswith("==> Caveats"):
|
|
813
|
+
in_caveats = True
|
|
814
|
+
kept.append(ln)
|
|
815
|
+
continue
|
|
816
|
+
if in_caveats:
|
|
817
|
+
if stripped.startswith("==>"):
|
|
818
|
+
in_caveats = False
|
|
819
|
+
else:
|
|
820
|
+
kept.append(ln)
|
|
821
|
+
continue
|
|
822
|
+
|
|
823
|
+
if _is_important_line(ln) or _PKG_SUMMARY_RE.search(ln):
|
|
824
|
+
kept.append(ln)
|
|
825
|
+
continue
|
|
826
|
+
|
|
827
|
+
if _PKG_NOISE_RE.match(ln):
|
|
828
|
+
if dropped == 0:
|
|
829
|
+
first_dropped = idx
|
|
830
|
+
last_dropped = idx
|
|
831
|
+
dropped += 1
|
|
832
|
+
continue
|
|
833
|
+
|
|
834
|
+
kept.append(ln)
|
|
835
|
+
|
|
836
|
+
if dropped < 8:
|
|
837
|
+
return None
|
|
838
|
+
|
|
839
|
+
header = f"[package install: {dropped} download/progress lines collapsed (lines {first_dropped}-{last_dropped})]"
|
|
840
|
+
result = header + "\n" + "\n".join(kept)
|
|
841
|
+
return result if len(result) < len(output) * 0.85 else None
|
|
842
|
+
except Exception:
|
|
843
|
+
return None
|
|
844
|
+
|
|
845
|
+
|
|
846
|
+
# ---------------------------------------------------------------------------
|
|
847
|
+
# 8. mypy type checker (keeps error-attached notes; collapses long overload dumps)
|
|
848
|
+
# ---------------------------------------------------------------------------
|
|
849
|
+
_MYPY_NOTE_RE = re.compile(r"^.+?:\d+(?::\d+)?:\s+note: (.*)$")
|
|
850
|
+
_MYPY_OVERLOAD_HDR_RE = re.compile(r"^\s*Possible overload variants:\s*$", re.IGNORECASE)
|
|
851
|
+
_MYPY_OVERLOAD_ITEM_RE = re.compile(r"^\s*Overload candidate\b", re.IGNORECASE)
|
|
852
|
+
|
|
853
|
+
|
|
854
|
+
def compress_mypy(output: str) -> str | None:
|
|
855
|
+
"""Compress verbose ``mypy`` output by collapsing only long overload dumps.
|
|
856
|
+
|
|
857
|
+
Preserves every ``error:``, ``warning:``, ``Revealed type``, summary, and
|
|
858
|
+
error-attached ``note:`` (including ``Expected:`` / ``Got:`` pairs).
|
|
859
|
+
"""
|
|
860
|
+
try:
|
|
861
|
+
lines = output.splitlines()
|
|
862
|
+
if len(lines) < 15:
|
|
863
|
+
return None
|
|
864
|
+
|
|
865
|
+
out: list[str] = []
|
|
866
|
+
total_notes_dropped = 0
|
|
867
|
+
i = 0
|
|
868
|
+
n = len(lines)
|
|
869
|
+
|
|
870
|
+
while i < n:
|
|
871
|
+
m = _MYPY_NOTE_RE.match(lines[i])
|
|
872
|
+
if m:
|
|
873
|
+
body = m.group(1)
|
|
874
|
+
# Case A: "Possible overload variants:" followed by indented signature notes
|
|
875
|
+
if _MYPY_OVERLOAD_HDR_RE.match(body):
|
|
876
|
+
j = i + 1
|
|
877
|
+
while j < n:
|
|
878
|
+
mj = _MYPY_NOTE_RE.match(lines[j])
|
|
879
|
+
if mj and mj.group(1).startswith((" ", "\t")) and not _is_important_line(lines[j]):
|
|
880
|
+
j += 1
|
|
881
|
+
else:
|
|
882
|
+
break
|
|
883
|
+
block_len = j - i
|
|
884
|
+
if block_len >= 4:
|
|
885
|
+
out.append(f" ... ({block_len} mypy overload variant notes collapsed, lines {i + 1}-{j})")
|
|
886
|
+
total_notes_dropped += block_len
|
|
887
|
+
i = j
|
|
888
|
+
continue
|
|
889
|
+
# Case B: contiguous "Overload candidate ..." notes
|
|
890
|
+
if _MYPY_OVERLOAD_ITEM_RE.match(body):
|
|
891
|
+
j = i + 1
|
|
892
|
+
while j < n:
|
|
893
|
+
mj = _MYPY_NOTE_RE.match(lines[j])
|
|
894
|
+
if mj and _MYPY_OVERLOAD_ITEM_RE.match(mj.group(1)) and not _is_important_line(lines[j]):
|
|
895
|
+
j += 1
|
|
896
|
+
else:
|
|
897
|
+
break
|
|
898
|
+
block_len = j - i
|
|
899
|
+
if block_len >= 4:
|
|
900
|
+
out.append(f" ... ({block_len} mypy overload variant notes collapsed, lines {i + 1}-{j})")
|
|
901
|
+
total_notes_dropped += block_len
|
|
902
|
+
i = j
|
|
903
|
+
continue
|
|
904
|
+
out.append(lines[i])
|
|
905
|
+
i += 1
|
|
906
|
+
|
|
907
|
+
if total_notes_dropped < 4:
|
|
908
|
+
return None
|
|
909
|
+
result = "\n".join(out)
|
|
910
|
+
return result if len(result) < len(output) * 0.85 else None
|
|
911
|
+
except Exception:
|
|
912
|
+
return None
|
|
913
|
+
|
|
914
|
+
|
|
915
|
+
# ---------------------------------------------------------------------------
|
|
916
|
+
# Unified dispatchers
|
|
917
|
+
# ---------------------------------------------------------------------------
|
|
918
|
+
def compress_for_pattern(pattern: str, output: str, command_str: str = "") -> str | None:
|
|
919
|
+
"""Dispatch an extra pattern name to its structured compressor."""
|
|
920
|
+
try:
|
|
921
|
+
res: str | None = None
|
|
922
|
+
if pattern == "git_ls":
|
|
923
|
+
res = compress_git_ls(output, command_str)
|
|
924
|
+
elif pattern == "gh_run_log":
|
|
925
|
+
res = compress_gh_run_log(output)
|
|
926
|
+
elif pattern == "gh_list":
|
|
927
|
+
res = compress_gh_list(output)
|
|
928
|
+
elif pattern == "terraform_plan":
|
|
929
|
+
res = compress_terraform_plan(output)
|
|
930
|
+
elif pattern == "pkg_install":
|
|
931
|
+
res = compress_package_install(output)
|
|
932
|
+
elif pattern == "mypy":
|
|
933
|
+
res = compress_mypy(output)
|
|
934
|
+
if res is None:
|
|
935
|
+
return None
|
|
936
|
+
from emit_safety_gate import gate_or_none as _emit_gate
|
|
937
|
+
feat = feature_for_command(command_str, output) or pattern
|
|
938
|
+
return _emit_gate(output, res, feature=feat, tool_name="Bash", command=command_str, require_expand=False)
|
|
939
|
+
except Exception:
|
|
940
|
+
return None
|
|
941
|
+
|
|
942
|
+
|
|
943
|
+
def compress_build_command(command_str: str, output: str) -> str | None:
|
|
944
|
+
"""Structured fast-path called by ``build_output_compress.compress``."""
|
|
945
|
+
try:
|
|
946
|
+
pat = detect_pattern(command_str)
|
|
947
|
+
if pat in ("pkg_install", "terraform_plan", "gh_run_log", "mypy"):
|
|
948
|
+
return compress_for_pattern(pat, output, command_str)
|
|
949
|
+
# Also catch `npm install` / `npm ci` routed through build_output_compress
|
|
950
|
+
tokens = _extract_primary_tokens(command_str)
|
|
951
|
+
if len(tokens) >= 2 and tokens[0].rsplit("/", 1)[-1] == "npm" and tokens[1] in ("install", "ci"):
|
|
952
|
+
return compress_package_install(output)
|
|
953
|
+
return None
|
|
954
|
+
except Exception:
|
|
955
|
+
return None
|