@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51
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 +76 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +130 -0
- package/LICENSE-SMALL-BUSINESS.md +62 -0
- package/PRIVACY.md +200 -0
- package/README.md +13 -2
- package/hooks/codex-hooks.json +4 -0
- package/hooks/hooks.json +182 -0
- package/hooks/module_runner.py +448 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +788 -0
- package/hooks/sessionstart_runner.py +629 -0
- package/hooks/stop_runner.py +408 -0
- package/hooks/userpromptsubmit_runner.py +722 -0
- package/hooks/windows-launcher.py +163 -0
- package/install-cloud.sh +23 -0
- package/package.json +29 -4
- package/skills/fleet-auditor/SKILL.md +149 -0
- package/skills/fleet-auditor/references/fleet-systems.md +167 -0
- package/skills/fleet-auditor/references/report-template.md +50 -0
- package/skills/fleet-auditor/references/waste-patterns.md +126 -0
- package/skills/fleet-auditor/scripts/fleet.py +3633 -0
- package/skills/fleet-auditor/scripts/shared.py +277 -0
- package/skills/resume-checkpoint/SKILL.md +52 -0
- package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
- package/skills/token-coach/SKILL.md +141 -0
- package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
- package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
- package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
- package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
- package/skills/token-coach/references/agentic-systems.md +147 -0
- package/skills/token-coach/references/coach-patterns.md +120 -0
- package/skills/token-coach/references/coaching-scripts.md +146 -0
- package/skills/token-coach/references/deterministic-stages.md +102 -0
- package/skills/token-coach/references/keepwarm-consent.md +48 -0
- package/skills/token-coach/references/quick-reference.md +155 -0
- package/skills/token-dashboard/SKILL.md +93 -0
- package/skills/token-optimizer/SKILL.md +150 -0
- package/skills/token-optimizer/assets/dashboard.html +7251 -0
- package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
- package/skills/token-optimizer/examples/hooks-starter.json +179 -0
- package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
- package/skills/token-optimizer/pricing/prices.json +695 -0
- package/skills/token-optimizer/references/agent-prompts.md +687 -0
- package/skills/token-optimizer/references/cli-reference.md +92 -0
- package/skills/token-optimizer/references/codex-workflow.md +188 -0
- package/skills/token-optimizer/references/cursor-workflow.md +74 -0
- package/skills/token-optimizer/references/error-recovery.md +37 -0
- package/skills/token-optimizer/references/implementation-playbook.md +416 -0
- package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
- package/skills/token-optimizer/references/opencode-workflow.md +72 -0
- package/skills/token-optimizer/references/optimization-checklist.md +714 -0
- package/skills/token-optimizer/references/phase0-setup.md +142 -0
- package/skills/token-optimizer/references/presentation-workflow.md +72 -0
- package/skills/token-optimizer/references/session-continuity.md +19 -0
- package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +379 -0
- package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
- package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
- package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
- package/skills/token-optimizer/scripts/archive_result.py +1725 -0
- package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
- package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
- package/skills/token-optimizer/scripts/bash_hook.py +61 -0
- package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
- package/skills/token-optimizer/scripts/benchmark.py +1765 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +1011 -0
- package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
- package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
- package/skills/token-optimizer/scripts/codex_install.py +810 -0
- package/skills/token-optimizer/scripts/codex_io.py +119 -0
- package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
- package/skills/token-optimizer/scripts/codex_models.py +34 -0
- package/skills/token-optimizer/scripts/codex_session.py +1186 -0
- package/skills/token-optimizer/scripts/codex_state.py +707 -0
- package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
- package/skills/token-optimizer/scripts/command_filters.py +386 -0
- package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
- package/skills/token-optimizer/scripts/compression_log.py +230 -0
- package/skills/token-optimizer/scripts/context_intel.py +331 -0
- package/skills/token-optimizer/scripts/context_pressure.py +115 -0
- package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
- package/skills/token-optimizer/scripts/copilot_install.py +288 -0
- package/skills/token-optimizer/scripts/copilot_session.py +496 -0
- package/skills/token-optimizer/scripts/copilot_state.py +569 -0
- package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
- package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
- package/skills/token-optimizer/scripts/cowork_install.py +380 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
- package/skills/token-optimizer/scripts/cursor_install.py +426 -0
- package/skills/token-optimizer/scripts/cursor_session.py +303 -0
- package/skills/token-optimizer/scripts/cursor_state.py +348 -0
- package/skills/token-optimizer/scripts/delta_diff.py +110 -0
- package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
- package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
- package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
- package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
- package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
- package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
- package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
- package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
- package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
- package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
- package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
- package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
- package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
- package/skills/token-optimizer/scripts/devin_compress.py +790 -0
- package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
- package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
- package/skills/token-optimizer/scripts/devin_install.py +1086 -0
- package/skills/token-optimizer/scripts/devin_source.py +119 -0
- package/skills/token-optimizer/scripts/devin_state.py +330 -0
- package/skills/token-optimizer/scripts/devin_verify.py +67 -0
- package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
- package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
- package/skills/token-optimizer/scripts/grok_install.py +400 -0
- package/skills/token-optimizer/scripts/grok_session.py +317 -0
- package/skills/token-optimizer/scripts/grok_state.py +299 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
- package/skills/token-optimizer/scripts/hermes_install.py +668 -0
- package/skills/token-optimizer/scripts/hermes_session.py +691 -0
- package/skills/token-optimizer/scripts/hermes_state.py +448 -0
- package/skills/token-optimizer/scripts/hook_io.py +120 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +716 -0
- package/skills/token-optimizer/scripts/injection.py +156 -0
- package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
- package/skills/token-optimizer/scripts/measure.py +59531 -0
- package/skills/token-optimizer/scripts/outline.py +53 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
- package/skills/token-optimizer/scripts/plugin_env.py +562 -0
- package/skills/token-optimizer/scripts/py_trust.py +80 -0
- package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
- package/skills/token-optimizer/scripts/read_cache.py +2489 -0
- package/skills/token-optimizer/scripts/recovery_output.py +110 -0
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
- package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
- package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
- package/skills/token-optimizer/scripts/runtime_env.py +1923 -0
- package/skills/token-optimizer/scripts/session_store.py +979 -0
- package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
- package/skills/token-optimizer/scripts/statusline.js +660 -0
- package/skills/token-optimizer/scripts/structure_map.py +2880 -0
- package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
- package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
- package/skills/token-optimizer/scripts/token_estimate.py +80 -0
- package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
- package/skills/token-optimizer/scripts/utf8_io.py +219 -0
|
@@ -0,0 +1,776 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Token Optimizer: Build/Test/Run Output Compression (PostToolUse only).
|
|
3
|
+
|
|
4
|
+
Compresses build, test, and run command output AFTER execution. The command
|
|
5
|
+
already ran; this module only compresses the captured stdout so the model sees
|
|
6
|
+
a compact summary instead of thousands of repetitive lines.
|
|
7
|
+
|
|
8
|
+
This module is invoked by ``bash_compress_hook.py`` on the NOT-read-only
|
|
9
|
+
branch — when ``is_read_only_pipeline`` returns false. Build/test/run commands
|
|
10
|
+
(gcc, pytest, cargo, npm, make, ...) are typically not read-only (they compile,
|
|
11
|
+
run tests, have side effects), so they never reach the read-only compression
|
|
12
|
+
path. This module fills that gap.
|
|
13
|
+
|
|
14
|
+
Safety (same stack as bash_compress.py):
|
|
15
|
+
- Fail-open: any exception -> returns None -> raw output stands
|
|
16
|
+
- PostToolUse only: the command already ran, nothing is denied or re-executed
|
|
17
|
+
- Never compress outputs under ~2 KB (byte-identical passthrough)
|
|
18
|
+
- Credential-bearing lines are never dropped (re-injected via _find_preserved_lines)
|
|
19
|
+
- Every distinct error line in the original appears in the compressed output
|
|
20
|
+
- The full original is archived behind the existing expand pointer (by the hook)
|
|
21
|
+
- _enforce_baseline_invariant is applied by the hook
|
|
22
|
+
|
|
23
|
+
Architecture:
|
|
24
|
+
classify(command) -> bool # Stage 1: command match
|
|
25
|
+
classify_by_shape(output, command) -> bool # Stage 2: output shape fallback
|
|
26
|
+
compress(command, output, ...) -> str | None # Main entry point
|
|
27
|
+
"""
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import re
|
|
31
|
+
import shlex
|
|
32
|
+
|
|
33
|
+
# ---------------------------------------------------------------------------
|
|
34
|
+
# Credential patterns — imported from the shared credential_patterns module.
|
|
35
|
+
# F7: fail-closed. If credential_patterns cannot be imported, compress() must
|
|
36
|
+
# return None (pass through raw) rather than compressing with no credential
|
|
37
|
+
# scanning. A line carrying a secret must never be silently dropped.
|
|
38
|
+
# ---------------------------------------------------------------------------
|
|
39
|
+
try:
|
|
40
|
+
from credential_patterns import PATTERNS_ONLY as _CRED_PATTERNS
|
|
41
|
+
from credential_patterns import _text_may_contain_credentials as _cred_prefilter
|
|
42
|
+
_CRED_PATTERNS_AVAILABLE = True
|
|
43
|
+
except Exception:
|
|
44
|
+
_CRED_PATTERNS = ()
|
|
45
|
+
_cred_prefilter = None
|
|
46
|
+
_CRED_PATTERNS_AVAILABLE = False
|
|
47
|
+
|
|
48
|
+
# ---------------------------------------------------------------------------
|
|
49
|
+
# Minimum size gate: outputs below this are never compressed. The gate is on
|
|
50
|
+
# line count, not bytes: build/test tools (valgrind, integration runners)
|
|
51
|
+
# emit 30-40+ short boilerplate lines that add up to only ~1.5-2 KB, which a
|
|
52
|
+
# byte gate would skip despite being highly compressible.
|
|
53
|
+
# ---------------------------------------------------------------------------
|
|
54
|
+
_MIN_COMPRESS_LINES = 25
|
|
55
|
+
|
|
56
|
+
# ---------------------------------------------------------------------------
|
|
57
|
+
# Head/tail preservation window.
|
|
58
|
+
# ---------------------------------------------------------------------------
|
|
59
|
+
_HEAD_LINES = 20
|
|
60
|
+
_TAIL_LINES = 20
|
|
61
|
+
|
|
62
|
+
# ---------------------------------------------------------------------------
|
|
63
|
+
# Stage 1: command-based eligibility.
|
|
64
|
+
# Maps command name -> set of subcommands that indicate build/test/run.
|
|
65
|
+
# A None subcommand set means ANY invocation of that command is eligible.
|
|
66
|
+
# ---------------------------------------------------------------------------
|
|
67
|
+
_BUILD_TEST_COMMANDS: dict[str, frozenset[str] | None] = {
|
|
68
|
+
# Compilers — any invocation
|
|
69
|
+
"gcc": None, "g++": None, "cc": None, "clang": None, "clang++": None,
|
|
70
|
+
"rustc": None,
|
|
71
|
+
# Build systems — any invocation
|
|
72
|
+
"make": None, "cmake": None, "ninja": None,
|
|
73
|
+
# Cargo (Rust)
|
|
74
|
+
"cargo": frozenset({"build", "test", "check", "run", "clippy", "bench",
|
|
75
|
+
"fmt", "doc", "install"}),
|
|
76
|
+
# Go
|
|
77
|
+
"go": frozenset({"build", "test", "vet", "bench", "doc"}),
|
|
78
|
+
# Node ecosystem
|
|
79
|
+
"npm": frozenset({"test", "run", "install", "ci", "build", "lint",
|
|
80
|
+
"start", "exec"}),
|
|
81
|
+
"yarn": frozenset({"test", "build", "install", "lint", "start",
|
|
82
|
+
"run", "exec"}),
|
|
83
|
+
"pnpm": frozenset({"test", "build", "install", "lint", "start",
|
|
84
|
+
"run", "exec"}),
|
|
85
|
+
"npx": None, # npx runs arbitrary build/test tools
|
|
86
|
+
# TypeScript / JS bundlers
|
|
87
|
+
"tsc": None,
|
|
88
|
+
"webpack": None, "esbuild": None, "vite": None, "next": None,
|
|
89
|
+
"rollup": None,
|
|
90
|
+
# JVM
|
|
91
|
+
"mvn": None, "gradle": None, "gradlew": None,
|
|
92
|
+
# .NET
|
|
93
|
+
"dotnet": frozenset({"build", "test", "publish", "restore", "run",
|
|
94
|
+
"format", "vet"}),
|
|
95
|
+
# Swift
|
|
96
|
+
"swift": frozenset({"build", "test", "run", "package"}),
|
|
97
|
+
# Linters / type checkers (non-read-only variants)
|
|
98
|
+
"eslint": None, "ruff": None, "mypy": None,
|
|
99
|
+
# Python test runners (non-read-only variants, e.g. with coverage)
|
|
100
|
+
"pytest": None, "py.test": None,
|
|
101
|
+
"tox": None, "nox": None,
|
|
102
|
+
# Ruby
|
|
103
|
+
"rspec": None, "rake": None,
|
|
104
|
+
# Python project/dependency manager (uv run pytest, uv pip install, ...)
|
|
105
|
+
"uv": frozenset({"run", "sync", "pip"}),
|
|
106
|
+
# Debuggers / instrumentation
|
|
107
|
+
"valgrind": None,
|
|
108
|
+
"gdb": frozenset({"-batch"}),
|
|
109
|
+
"ctest": None,
|
|
110
|
+
# Container builds — docker build / docker compose build produce BuildKit
|
|
111
|
+
# output (the progress-prefixed error lines the error-before-noise fix
|
|
112
|
+
# preserves). docker-compose is the legacy hyphenated form.
|
|
113
|
+
"docker": frozenset({"build", "compose"}),
|
|
114
|
+
"docker-compose": frozenset({"build", "up"}),
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
# F5: command-name keywords that make a command eligible for the shape
|
|
118
|
+
# fallback. The shape fallback catches unknown build/test tools by output
|
|
119
|
+
# shape, but must not compress side-effecting commands (deploy, publish,
|
|
120
|
+
# git push, etc.) whose output the model needs verbatim. A command whose
|
|
121
|
+
# basename contains one of these keywords is plausibly a build/test/run
|
|
122
|
+
# tool and may be shape-compressed; everything else is left raw.
|
|
123
|
+
_SHAPE_FALLBACK_KEYWORDS = frozenset({
|
|
124
|
+
"build", "test", "compile", "check", "lint", "make", "run", "bench",
|
|
125
|
+
"ci", "clean", "install", "pack", "bundle", "dist", "fmt", "vet",
|
|
126
|
+
"clippy", "tsc", "eslint", "ruff", "mypy", "pytest", "cargo", "go",
|
|
127
|
+
"npm", "yarn", "pnpm", "mvn", "gradle", "cmake", "ninja", "gcc",
|
|
128
|
+
"g++", "cc", "clang", "rustc", "dotnet", "swift", "rspec", "rake",
|
|
129
|
+
"tox", "nox", "webpack", "vite", "rollup", "esbuild", "next",
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
# ---------------------------------------------------------------------------
|
|
133
|
+
# Stage 2: output-shape markers for the generic fallback.
|
|
134
|
+
# ---------------------------------------------------------------------------
|
|
135
|
+
_SHAPE_MARKER_PATTERNS = [
|
|
136
|
+
re.compile(r"error\[E\d{4}\]"), # Rust error codes
|
|
137
|
+
re.compile(r"^error:", re.MULTILINE), # generic error
|
|
138
|
+
re.compile(r"^warning:", re.MULTILINE), # generic warning
|
|
139
|
+
re.compile(r"\bFAILED\b"), # test failure
|
|
140
|
+
re.compile(r"\bTraceback\b"), # Python traceback
|
|
141
|
+
re.compile(r"Compiling\s"), # Rust/cargo compiling
|
|
142
|
+
re.compile(r"Building\s"), # make/build
|
|
143
|
+
re.compile(r"Finished\s"), # cargo finished
|
|
144
|
+
re.compile(r"--> .*:\d+:\d+"), # Rust/gcc file:line:col
|
|
145
|
+
re.compile(r"\w+:\d+:\d+:\s*(error|warning)"), # gcc/clang file:line:col: error
|
|
146
|
+
re.compile(r"\w+:\d+:\s*(error|warning)"), # gcc/clang file:line: error
|
|
147
|
+
re.compile(r"make:\s*\*\*\*"), # make error
|
|
148
|
+
re.compile(r"npm\s+ERR!"), # npm error
|
|
149
|
+
re.compile(r"npm\s+WARN"), # npm warning
|
|
150
|
+
re.compile(r"\d+\s+passed"), # pytest summary
|
|
151
|
+
re.compile(r"\d+\s+failed"), # pytest summary
|
|
152
|
+
re.compile(r"::\s*\w+\s+PASSED"), # pytest per-test result
|
|
153
|
+
re.compile(r"::\s*\w+\s+FAILED"), # pytest per-test result
|
|
154
|
+
re.compile(r"::\s*\w+\s+SKIPPED"), # pytest per-test result
|
|
155
|
+
re.compile(r"BUILD\s+(SUCCESSFUL|FAILED|SUCCESS|FAILURE)", re.I), # gradle/maven
|
|
156
|
+
re.compile(r"Tests:\s"), # jest summary
|
|
157
|
+
re.compile(r"Test Suites:\s"), # jest summary
|
|
158
|
+
re.compile(r"undefined reference to"), # linker
|
|
159
|
+
re.compile(r"cannot find -l"), # linker
|
|
160
|
+
re.compile(r"ld:\s*(error|warning)"), # linker
|
|
161
|
+
re.compile(r"note:"), # Rust/gcc note
|
|
162
|
+
re.compile(r"error: could not compile"), # Rust
|
|
163
|
+
re.compile(r"Collecting\s"), # pip install
|
|
164
|
+
re.compile(r"Downloading\s"), # pip/npm download
|
|
165
|
+
re.compile(r"Using cached\s"), # pip
|
|
166
|
+
re.compile(r"Successfully installed"), # pip
|
|
167
|
+
re.compile(r"added \d+ package"), # npm
|
|
168
|
+
re.compile(r"removed \d+ package"), # npm
|
|
169
|
+
]
|
|
170
|
+
|
|
171
|
+
# Combined shape-marker regex for the classify_by_shape fallback (single
|
|
172
|
+
# DFA pass per line instead of 29 separate searches).
|
|
173
|
+
_COMBINED_SHAPE_RE = re.compile(
|
|
174
|
+
"|".join(
|
|
175
|
+
f"(?i:{p.pattern})" if p.flags & re.I else f"(?:{p.pattern})"
|
|
176
|
+
for p in _SHAPE_MARKER_PATTERNS
|
|
177
|
+
),
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
# ---------------------------------------------------------------------------
|
|
181
|
+
# Error line patterns — every DISTINCT line matching one of these is preserved.
|
|
182
|
+
# F8: generic error/warning markers are case-insensitive so Error:, ERROR:,
|
|
183
|
+
# FATAL: etc. are caught. Specific identifiers (FAILED, Traceback,
|
|
184
|
+
# AssertionError) stay case-sensitive to avoid false positives.
|
|
185
|
+
# ---------------------------------------------------------------------------
|
|
186
|
+
_ERROR_LINE_PATTERNS = [
|
|
187
|
+
re.compile(r"error\[E\d{4}\]"), # Rust
|
|
188
|
+
re.compile(r"^error:", re.MULTILINE | re.I), # generic (case-insensitive)
|
|
189
|
+
re.compile(r"^fatal error:", re.MULTILINE | re.I),
|
|
190
|
+
re.compile(r"\bFAILED\b"), # test failure (case-sensitive)
|
|
191
|
+
re.compile(r"\bTraceback\b"), # Python (case-sensitive)
|
|
192
|
+
re.compile(r"AssertionError"),
|
|
193
|
+
re.compile(r"AssertionFailedError"),
|
|
194
|
+
re.compile(r"\w+:\d+:\d+:\s*(error|fatal error)", re.I), # gcc/clang
|
|
195
|
+
re.compile(r"\w+:\d+:\s*(error|fatal error)", re.I), # gcc/clang short
|
|
196
|
+
re.compile(r"make:\s*\*\*\*.*Error", re.I), # make error
|
|
197
|
+
re.compile(r"npm\s+ERR!"), # npm error
|
|
198
|
+
re.compile(r"undefined reference to", re.I), # linker
|
|
199
|
+
re.compile(r"cannot find -l", re.I), # linker
|
|
200
|
+
re.compile(r"ld:\s*error", re.I), # linker
|
|
201
|
+
re.compile(r"Exception in thread", re.I),
|
|
202
|
+
re.compile(r"BUILD\s+FAILED", re.I), # gradle/maven
|
|
203
|
+
re.compile(r"BUILD\s+FAILURE", re.I), # maven
|
|
204
|
+
re.compile(r"error: could not compile", re.I), # Rust
|
|
205
|
+
re.compile(r"error: aborting", re.I), # Rust/gcc
|
|
206
|
+
re.compile(r"note: previous declaration", re.I), # Rust/gcc note
|
|
207
|
+
re.compile(r"help: ", re.I), # Rust help
|
|
208
|
+
re.compile(r"panicked at", re.I), # Rust panic
|
|
209
|
+
re.compile(r"thread '.*' panicked", re.I), # Rust panic
|
|
210
|
+
]
|
|
211
|
+
|
|
212
|
+
# F4: import foreign-language and localized error markers from bash_compress
|
|
213
|
+
# so non-English errors (Dutch fout:, French erreur:, German Fehler:, CJK
|
|
214
|
+
# variants, etc.) are preserved instead of silently dropped in the truncated
|
|
215
|
+
# middle. _ERROR_STDERR_PATTERNS covers French/German/Italian/Russian/CJK;
|
|
216
|
+
# _FOREIGN_ERROR_PATTERNS covers Dutch/Swedish/Finnish/Hungarian/Turkish/etc.
|
|
217
|
+
# F8: _ERROR_STDERR_PATTERNS also includes \bfatal\s*: (re.I) which catches
|
|
218
|
+
# bare "FATAL:" that the case-sensitive ^fatal error: pattern misses.
|
|
219
|
+
try:
|
|
220
|
+
from bash_compress import _ERROR_STDERR_PATTERNS as _STDERR_ERRORS
|
|
221
|
+
from bash_compress import _FOREIGN_ERROR_PATTERNS as _FOREIGN_ERRORS
|
|
222
|
+
except Exception:
|
|
223
|
+
_STDERR_ERRORS = []
|
|
224
|
+
_FOREIGN_ERRORS = []
|
|
225
|
+
_ERROR_LINE_PATTERNS.extend(_STDERR_ERRORS)
|
|
226
|
+
_ERROR_LINE_PATTERNS.extend(_FOREIGN_ERRORS)
|
|
227
|
+
|
|
228
|
+
# Combined error regex for fast scanning. Preserves per-pattern case
|
|
229
|
+
# sensitivity via inline (?i:...) groups, matching the approach in
|
|
230
|
+
# bash_compress_hook._get_combined_error_re.
|
|
231
|
+
_COMBINED_ERROR_RE = re.compile(
|
|
232
|
+
"|".join(
|
|
233
|
+
f"(?i:{p.pattern})" if p.flags & re.I else f"(?:{p.pattern})"
|
|
234
|
+
for p in _ERROR_LINE_PATTERNS
|
|
235
|
+
),
|
|
236
|
+
re.MULTILINE,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
# ---------------------------------------------------------------------------
|
|
240
|
+
# Summary line patterns — exit/summary lines are always preserved.
|
|
241
|
+
# ---------------------------------------------------------------------------
|
|
242
|
+
_SUMMARY_LINE_PATTERNS = [
|
|
243
|
+
re.compile(r"\d+\s+passed.*", re.I),
|
|
244
|
+
re.compile(r"\d+\s+failed.*", re.I),
|
|
245
|
+
re.compile(r"\d+\s+skipped.*", re.I),
|
|
246
|
+
re.compile(r"\d+\s+errors?.*", re.I),
|
|
247
|
+
re.compile(r"\d+\s+warnings?.*", re.I),
|
|
248
|
+
re.compile(r"error: could not compile", re.I),
|
|
249
|
+
re.compile(r"^\s*Finished\s+", re.MULTILINE), # cargo
|
|
250
|
+
re.compile(r"Build\s+(finished|complete|successful)", re.I),
|
|
251
|
+
re.compile(r"npm\s+ERR!.*", re.I),
|
|
252
|
+
re.compile(r"Tests:\s+.*", re.I),
|
|
253
|
+
re.compile(r"Test Suites:\s+.*", re.I),
|
|
254
|
+
re.compile(r"make:\s*\*\*\*.*", re.I),
|
|
255
|
+
re.compile(r"BUILD\s+(SUCCESSFUL|FAILED|SUCCESS|FAILURE)", re.I),
|
|
256
|
+
re.compile(r"Found\s+\d+\s+(error|warning|problem)", re.I),
|
|
257
|
+
re.compile(r"Successfully\s+(installed|built|deployed)", re.I),
|
|
258
|
+
re.compile(r"added\s+\d+\s+package", re.I),
|
|
259
|
+
re.compile(r"removed\s+\d+\s+package", re.I),
|
|
260
|
+
re.compile(r"audited\s+\d+\s+package", re.I),
|
|
261
|
+
re.compile(r"Compilation\s+(finished|succeeded|failed)", re.I),
|
|
262
|
+
re.compile(r"Total\s+time:.*", re.I),
|
|
263
|
+
re.compile(r"Results:.*", re.I),
|
|
264
|
+
re.compile(r"Tests\s+run:.*", re.I),
|
|
265
|
+
re.compile(r"FAILED\s+tests", re.I),
|
|
266
|
+
re.compile(r"===\s*FAILURES\s*===", re.I),
|
|
267
|
+
re.compile(r"===\s*ERRORS\s*===", re.I),
|
|
268
|
+
re.compile(r"---\s*FAILED\s+---", re.I),
|
|
269
|
+
]
|
|
270
|
+
|
|
271
|
+
_COMBINED_SUMMARY_RE = re.compile(
|
|
272
|
+
"|".join(f"(?:{p.pattern})" for p in _SUMMARY_LINE_PATTERNS),
|
|
273
|
+
re.IGNORECASE,
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
# ---------------------------------------------------------------------------
|
|
277
|
+
# Progress / spinner noise patterns — these lines are dropped.
|
|
278
|
+
# ---------------------------------------------------------------------------
|
|
279
|
+
_PROGRESS_NOISE_PATTERNS = [
|
|
280
|
+
re.compile(r"^\s*Compiling\s+.*\.\.\.\s*$"), # "Compiling foo v0.1.0..."
|
|
281
|
+
re.compile(r"^\s*Building\s+.*\.\.\.\s*$"),
|
|
282
|
+
re.compile(r"^\s*Generating\s+.*\.\.\.\s*$"),
|
|
283
|
+
re.compile(r"^\s*Running\s+.*\.\.\.\s*$"),
|
|
284
|
+
re.compile(r"^\s*Downloading\s+.*", re.I),
|
|
285
|
+
re.compile(r"^\s*Collecting\s+.*", re.I),
|
|
286
|
+
re.compile(r"^\s*Using cached\s+.*", re.I),
|
|
287
|
+
re.compile(r"^\s*Requirement already satisfied.*", re.I),
|
|
288
|
+
re.compile(r"^\s*Building wheels?\s+.*", re.I),
|
|
289
|
+
re.compile(r"^\s*Created wheel\s+.*", re.I),
|
|
290
|
+
re.compile(r"^\s*Stored in directory:.*", re.I),
|
|
291
|
+
re.compile(r"^\s*Resolving dependencies?\s+.*", re.I),
|
|
292
|
+
re.compile(r"^\s*Installing collected packages?\s+.*", re.I),
|
|
293
|
+
re.compile(r"^\s*Preparing metadata?\s+.*", re.I),
|
|
294
|
+
re.compile(r"^\s*Downloading.*\.whl", re.I),
|
|
295
|
+
re.compile(r"^\s*\[=*>\s*\]\s*\d+%", re.I), # progress bar
|
|
296
|
+
re.compile(r"^\s*\[=\s*\]\s*\d+%", re.I), # progress bar
|
|
297
|
+
re.compile(r"^\s*\d+%\|.*\|", re.I), # tqdm progress bar
|
|
298
|
+
re.compile(r"^\s*=>\s*", re.I), # spinner
|
|
299
|
+
re.compile(r"^\s*\.+\s*$"), # dots spinner
|
|
300
|
+
re.compile(r"^\s*collecting\s*\.\.\.\s*$", re.I), # pytest collecting
|
|
301
|
+
re.compile(r"^\s*running\s+\d+.*", re.I), # test running
|
|
302
|
+
re.compile(r"PASSED\s*$"), # pytest per-test PASSED
|
|
303
|
+
re.compile(r"SKIPPED\s*$"), # pytest per-test SKIPPED
|
|
304
|
+
re.compile(r"XFAIL\s*$"), # pytest per-test XFAIL
|
|
305
|
+
re.compile(r"XPASS\s*$"), # pytest per-test XPASS
|
|
306
|
+
# Cargo progress: " Compiling foo v0.1.0"
|
|
307
|
+
re.compile(r"^\s+Compiling\s+\S+\s+v\S+"),
|
|
308
|
+
re.compile(r"^\s+Running\s+`?unittests`?"),
|
|
309
|
+
re.compile(r"^\s+Running\s+`?target"),
|
|
310
|
+
# Docker build progress
|
|
311
|
+
re.compile(r"^#\d+\s+"),
|
|
312
|
+
re.compile(r"^#[\d.]+\s+"),
|
|
313
|
+
# npm install progress
|
|
314
|
+
re.compile(r"^\s*⸨\s*⸩\s*"), # npm spinner
|
|
315
|
+
]
|
|
316
|
+
|
|
317
|
+
_COMBINED_PROGRESS_RE = re.compile(
|
|
318
|
+
"|".join(f"(?:{p.pattern})" for p in _PROGRESS_NOISE_PATTERNS),
|
|
319
|
+
re.IGNORECASE,
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
# Pre-compiled regexes for near-identical warning normalization (module-level
|
|
323
|
+
# so they compile once, not per call).
|
|
324
|
+
_NORMALIZE_RE = re.compile(r"\d+:\d+(?::\d+)?")
|
|
325
|
+
_BARE_NUM_RE = re.compile(r"(?<!\[E)\b\d+\b")
|
|
326
|
+
_HEX_RE = re.compile(r"\b0x[0-9a-fA-F]+\b")
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
# ---------------------------------------------------------------------------
|
|
330
|
+
# Classification
|
|
331
|
+
# ---------------------------------------------------------------------------
|
|
332
|
+
|
|
333
|
+
def classify(command: str) -> bool:
|
|
334
|
+
"""Stage 1: decide if this command is a build/test/run command.
|
|
335
|
+
|
|
336
|
+
Matches the command name (and optionally subcommand) against the
|
|
337
|
+
eligibility list. Returns True if the command is a known build/test/run
|
|
338
|
+
command. Never raises.
|
|
339
|
+
"""
|
|
340
|
+
try:
|
|
341
|
+
tokens = shlex.split(command)
|
|
342
|
+
if not tokens:
|
|
343
|
+
return False
|
|
344
|
+
|
|
345
|
+
# Strip leading env var assignments (FOO=bar) and `env` command
|
|
346
|
+
cmd_start = 0
|
|
347
|
+
if tokens[cmd_start] == "env":
|
|
348
|
+
cmd_start += 1
|
|
349
|
+
while (cmd_start < len(tokens)
|
|
350
|
+
and "=" in tokens[cmd_start]
|
|
351
|
+
and not tokens[cmd_start].startswith("-")):
|
|
352
|
+
cmd_start += 1
|
|
353
|
+
if cmd_start >= len(tokens):
|
|
354
|
+
return False
|
|
355
|
+
|
|
356
|
+
cmd = tokens[cmd_start]
|
|
357
|
+
subcmd = tokens[cmd_start + 1] if cmd_start + 1 < len(tokens) else ""
|
|
358
|
+
|
|
359
|
+
# Handle ./gradlew, ./configure, etc.
|
|
360
|
+
if "/" in cmd:
|
|
361
|
+
cmd = cmd.rsplit("/", 1)[-1]
|
|
362
|
+
|
|
363
|
+
# Python: running a module (-m <anything>) or a script (first
|
|
364
|
+
# non-flag argument ending in .py) is a build/test/run invocation.
|
|
365
|
+
if cmd.startswith("python"):
|
|
366
|
+
if subcmd == "-m":
|
|
367
|
+
return cmd_start + 2 < len(tokens)
|
|
368
|
+
if (subcmd and not subcmd.startswith("-")
|
|
369
|
+
and subcmd.endswith(".py")):
|
|
370
|
+
return True
|
|
371
|
+
return False
|
|
372
|
+
|
|
373
|
+
# Direct command match
|
|
374
|
+
if cmd in _BUILD_TEST_COMMANDS:
|
|
375
|
+
allowed_subs = _BUILD_TEST_COMMANDS[cmd]
|
|
376
|
+
if allowed_subs is None:
|
|
377
|
+
return True # any subcommand
|
|
378
|
+
if subcmd in allowed_subs:
|
|
379
|
+
return True
|
|
380
|
+
# npm run <script> — any script is build/test/run
|
|
381
|
+
if cmd == "npm" and subcmd == "run":
|
|
382
|
+
return True
|
|
383
|
+
if cmd in ("yarn", "pnpm") and subcmd == "run":
|
|
384
|
+
return True
|
|
385
|
+
# npx <anything> runs a build/test tool
|
|
386
|
+
if cmd == "npx":
|
|
387
|
+
return True
|
|
388
|
+
return False
|
|
389
|
+
|
|
390
|
+
return False
|
|
391
|
+
except Exception:
|
|
392
|
+
return False
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
def _command_eligible_for_shape_fallback(command: str) -> bool:
|
|
396
|
+
"""F5: check if the command name is plausibly a build/test/run tool.
|
|
397
|
+
|
|
398
|
+
The shape fallback must not compress side-effecting commands (deploy,
|
|
399
|
+
publish, git push, etc.) whose output the model needs verbatim. Only
|
|
400
|
+
commands whose basename contains a build/test keyword are eligible.
|
|
401
|
+
Never raises.
|
|
402
|
+
"""
|
|
403
|
+
try:
|
|
404
|
+
tokens = shlex.split(command)
|
|
405
|
+
if not tokens:
|
|
406
|
+
return False
|
|
407
|
+
cmd_start = 0
|
|
408
|
+
if tokens[cmd_start] == "env":
|
|
409
|
+
cmd_start += 1
|
|
410
|
+
while (cmd_start < len(tokens)
|
|
411
|
+
and "=" in tokens[cmd_start]
|
|
412
|
+
and not tokens[cmd_start].startswith("-")):
|
|
413
|
+
cmd_start += 1
|
|
414
|
+
if cmd_start >= len(tokens):
|
|
415
|
+
return False
|
|
416
|
+
cmd = tokens[cmd_start]
|
|
417
|
+
if "/" in cmd:
|
|
418
|
+
cmd = cmd.rsplit("/", 1)[-1]
|
|
419
|
+
# Strip common extensions so ./build.sh -> "build"
|
|
420
|
+
for ext in (".sh", ".py", ".bash", ".zsh"):
|
|
421
|
+
if cmd.endswith(ext):
|
|
422
|
+
cmd = cmd[: -len(ext)]
|
|
423
|
+
# Check if the basename (or any hyphen/underscore-separated part)
|
|
424
|
+
# contains a known build/test keyword.
|
|
425
|
+
parts = re.split(r"[-_.\s]+", cmd.lower())
|
|
426
|
+
for part in parts:
|
|
427
|
+
if part in _SHAPE_FALLBACK_KEYWORDS:
|
|
428
|
+
return True
|
|
429
|
+
return False
|
|
430
|
+
except Exception:
|
|
431
|
+
return False
|
|
432
|
+
|
|
433
|
+
|
|
434
|
+
def classify_by_shape(output: str, command: str = "") -> bool:
|
|
435
|
+
"""Stage 2: generic fallback on output shape.
|
|
436
|
+
|
|
437
|
+
Returns True when the output has >= 3 lines matching build/test markers
|
|
438
|
+
and is large enough to justify compression. F5: the command must also
|
|
439
|
+
be plausibly a build/test/run tool (checked via
|
|
440
|
+
_command_eligible_for_shape_fallback) so side-effecting commands like
|
|
441
|
+
``./deploy.sh`` are never shape-compressed. Never raises.
|
|
442
|
+
"""
|
|
443
|
+
try:
|
|
444
|
+
if not output:
|
|
445
|
+
return False
|
|
446
|
+
# F5: gate on command name to avoid compressing side-effecting commands
|
|
447
|
+
if command and not _command_eligible_for_shape_fallback(command):
|
|
448
|
+
return False
|
|
449
|
+
lines = output.splitlines()
|
|
450
|
+
if len(lines) < _MIN_COMPRESS_LINES:
|
|
451
|
+
return False
|
|
452
|
+
match_count = 0
|
|
453
|
+
for line in lines:
|
|
454
|
+
if _COMBINED_SHAPE_RE.search(line):
|
|
455
|
+
match_count += 1
|
|
456
|
+
if match_count >= 3:
|
|
457
|
+
return True
|
|
458
|
+
return match_count >= 3
|
|
459
|
+
except Exception:
|
|
460
|
+
return False
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
# ---------------------------------------------------------------------------
|
|
464
|
+
# Compression helpers
|
|
465
|
+
# ---------------------------------------------------------------------------
|
|
466
|
+
|
|
467
|
+
def _is_error_line(line: str) -> bool:
|
|
468
|
+
"""True if this line is a distinct error line that must be preserved."""
|
|
469
|
+
return bool(_COMBINED_ERROR_RE.search(line))
|
|
470
|
+
|
|
471
|
+
|
|
472
|
+
def _is_summary_line(line: str) -> bool:
|
|
473
|
+
"""True if this line is an exit/summary line that must be preserved."""
|
|
474
|
+
return bool(_COMBINED_SUMMARY_RE.search(line))
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _is_progress_noise(line: str) -> bool:
|
|
478
|
+
"""True if this line is progress/spinner noise that can be dropped."""
|
|
479
|
+
return bool(_COMBINED_PROGRESS_RE.search(line))
|
|
480
|
+
|
|
481
|
+
|
|
482
|
+
def _collapse_identical_runs(lines: list[str]) -> list[str]:
|
|
483
|
+
"""Collapse runs of identical consecutive lines into one + count marker.
|
|
484
|
+
|
|
485
|
+
"Compiling foo..." x 50 -> "Compiling foo... [x50 identical lines collapsed]"
|
|
486
|
+
"""
|
|
487
|
+
if not lines:
|
|
488
|
+
return []
|
|
489
|
+
result: list[str] = []
|
|
490
|
+
i = 0
|
|
491
|
+
while i < len(lines):
|
|
492
|
+
current = lines[i]
|
|
493
|
+
run = 1
|
|
494
|
+
while i + run < len(lines) and lines[i + run] == current:
|
|
495
|
+
run += 1
|
|
496
|
+
if run > 1:
|
|
497
|
+
result.append(f"{current} [{run} identical lines collapsed]")
|
|
498
|
+
else:
|
|
499
|
+
result.append(current)
|
|
500
|
+
i += run
|
|
501
|
+
return result
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def _collapse_near_identical_warnings(lines: list[str]) -> list[str]:
|
|
505
|
+
"""Collapse near-identical warning blocks.
|
|
506
|
+
|
|
507
|
+
Lines that differ only in line numbers or addresses are grouped:
|
|
508
|
+
"warning: unused variable: `x` (at 10:5)"
|
|
509
|
+
"warning: unused variable: `x` (at 20:8)"
|
|
510
|
+
-> "warning: unused variable: `x` (at 10:5) [+2 near-identical warnings]"
|
|
511
|
+
|
|
512
|
+
Single O(n) walk with lazy normalization: only warning lines get
|
|
513
|
+
normalized, and only as the run grows.
|
|
514
|
+
"""
|
|
515
|
+
if len(lines) < 3:
|
|
516
|
+
return list(lines)
|
|
517
|
+
|
|
518
|
+
def _normalize(ln: str) -> str:
|
|
519
|
+
s = _NORMALIZE_RE.sub("N:N", ln)
|
|
520
|
+
s = _BARE_NUM_RE.sub("N", s)
|
|
521
|
+
s = _HEX_RE.sub("0xADDR", s)
|
|
522
|
+
return s.strip()
|
|
523
|
+
|
|
524
|
+
result: list[str] = []
|
|
525
|
+
i = 0
|
|
526
|
+
while i < len(lines):
|
|
527
|
+
current = lines[i]
|
|
528
|
+
# Only collapse lines that look like warnings; skip normalization
|
|
529
|
+
# for non-warning lines (the common case in build output).
|
|
530
|
+
if "warning" not in current.lower():
|
|
531
|
+
result.append(current)
|
|
532
|
+
i += 1
|
|
533
|
+
continue
|
|
534
|
+
norm_current = _normalize(current)
|
|
535
|
+
run = 1
|
|
536
|
+
while (i + run < len(lines)
|
|
537
|
+
and "warning" in lines[i + run].lower()
|
|
538
|
+
and _normalize(lines[i + run]) == norm_current):
|
|
539
|
+
run += 1
|
|
540
|
+
if run > 1:
|
|
541
|
+
result.append(f"{current} [+{run - 1} near-identical warnings]")
|
|
542
|
+
else:
|
|
543
|
+
result.append(current)
|
|
544
|
+
i += run
|
|
545
|
+
return result
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
_TRACEBACK_FILE_RE = re.compile(r"^\s+File ")
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _collapse_traceback_frames(lines: list[str]) -> list[str]:
|
|
552
|
+
"""Collapse the middle frames of each Python traceback block.
|
|
553
|
+
|
|
554
|
+
A traceback block is the ``Traceback (most recent call last):`` header
|
|
555
|
+
plus the consecutive `` File ...`` frames (each frame includes its
|
|
556
|
+
source and caret lines). The header, the first frame, the last two
|
|
557
|
+
frames, and every non-frame line (the exception text) are kept; frames
|
|
558
|
+
in between are replaced by a count marker. Exception lines match the
|
|
559
|
+
error-line patterns and are preserved by the caller regardless.
|
|
560
|
+
"""
|
|
561
|
+
if not lines:
|
|
562
|
+
return list(lines)
|
|
563
|
+
result: list[str] = []
|
|
564
|
+
i = 0
|
|
565
|
+
n = len(lines)
|
|
566
|
+
while i < n:
|
|
567
|
+
if "Traceback (most recent call last)" not in lines[i]:
|
|
568
|
+
result.append(lines[i])
|
|
569
|
+
i += 1
|
|
570
|
+
continue
|
|
571
|
+
header = lines[i]
|
|
572
|
+
i += 1
|
|
573
|
+
frames: list[list[str]] = []
|
|
574
|
+
while i < n and _TRACEBACK_FILE_RE.match(lines[i]):
|
|
575
|
+
frame = [lines[i]]
|
|
576
|
+
i += 1
|
|
577
|
+
while (i < n
|
|
578
|
+
and lines[i][:1] in (" ", "\t")
|
|
579
|
+
and not _TRACEBACK_FILE_RE.match(lines[i])):
|
|
580
|
+
frame.append(lines[i])
|
|
581
|
+
i += 1
|
|
582
|
+
frames.append(frame)
|
|
583
|
+
result.append(header)
|
|
584
|
+
if len(frames) > 3:
|
|
585
|
+
for frame in frames[:1]:
|
|
586
|
+
result.extend(frame)
|
|
587
|
+
for frame in frames[-2:]:
|
|
588
|
+
result.extend(frame)
|
|
589
|
+
result.append(
|
|
590
|
+
f" ... [{len(frames) - 3} traceback frames dropped] ...")
|
|
591
|
+
else:
|
|
592
|
+
for frame in frames:
|
|
593
|
+
result.extend(frame)
|
|
594
|
+
return result
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
def _find_distinct_error_lines(lines: list[str]) -> list[str]:
|
|
598
|
+
"""Find every DISTINCT error line (deduplicated by exact text).
|
|
599
|
+
|
|
600
|
+
F3: no cap — every distinct error line must survive. Duplicates are
|
|
601
|
+
collapsed by the caller's _collapse_identical_runs, not dropped here.
|
|
602
|
+
"""
|
|
603
|
+
seen: set[str] = set()
|
|
604
|
+
errors: list[str] = []
|
|
605
|
+
for line in lines:
|
|
606
|
+
if _is_error_line(line):
|
|
607
|
+
if line not in seen:
|
|
608
|
+
seen.add(line)
|
|
609
|
+
errors.append(line)
|
|
610
|
+
return errors
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def _find_summary_lines(lines: list[str]) -> list[str]:
|
|
614
|
+
"""Find all summary/exit lines (deduplicated, order preserved)."""
|
|
615
|
+
seen: set[str] = set()
|
|
616
|
+
summaries: list[str] = []
|
|
617
|
+
for line in lines:
|
|
618
|
+
if _is_summary_line(line):
|
|
619
|
+
if line not in seen:
|
|
620
|
+
seen.add(line)
|
|
621
|
+
summaries.append(line)
|
|
622
|
+
return summaries
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
# ---------------------------------------------------------------------------
|
|
628
|
+
# Main compression entry point
|
|
629
|
+
# ---------------------------------------------------------------------------
|
|
630
|
+
|
|
631
|
+
def compress(command: str, output: str) -> str | None:
|
|
632
|
+
"""Compress build/test/run output.
|
|
633
|
+
|
|
634
|
+
Returns the compressed string, or None to signal "pass through raw".
|
|
635
|
+
Never raises (fail-open: any exception -> None).
|
|
636
|
+
|
|
637
|
+
The caller (bash_compress_hook.py) handles:
|
|
638
|
+
- ANSI stripping (done before calling this)
|
|
639
|
+
- Archiving the full original behind the expand pointer
|
|
640
|
+
- _enforce_baseline_invariant
|
|
641
|
+
- Logging to trends.db with feature=build_output_compress
|
|
642
|
+
- Appending the thrash nudge
|
|
643
|
+
"""
|
|
644
|
+
try:
|
|
645
|
+
if not output:
|
|
646
|
+
return None
|
|
647
|
+
|
|
648
|
+
# F7: fail-closed. If credential_patterns could not be imported at
|
|
649
|
+
# module load time, do not compress — pass through raw so a secret
|
|
650
|
+
# is never silently dropped.
|
|
651
|
+
if not _CRED_PATTERNS_AVAILABLE:
|
|
652
|
+
return None
|
|
653
|
+
|
|
654
|
+
lines = output.splitlines()
|
|
655
|
+
if len(lines) < _MIN_COMPRESS_LINES:
|
|
656
|
+
return None
|
|
657
|
+
|
|
658
|
+
# --- single O(n) pass: credential scan + noise drop + error/summary ---
|
|
659
|
+
# F1: credential scan runs FIRST, before the progress-noise drop. A
|
|
660
|
+
# line matching a credential pattern is always preserved and never
|
|
661
|
+
# dropped as noise. F2: the pre-filter uses the shared
|
|
662
|
+
# credential_patterns._text_may_contain_credentials (covering ~30
|
|
663
|
+
# prefixes) instead of a hand-maintained 13-token list.
|
|
664
|
+
kept_lines: list[str] = []
|
|
665
|
+
noise_dropped = 0
|
|
666
|
+
distinct_errors: list[str] = []
|
|
667
|
+
_error_seen: set[str] = set()
|
|
668
|
+
summary_lines: list[str] = []
|
|
669
|
+
_summary_seen: set[str] = set()
|
|
670
|
+
preserved_lines: list[str] = []
|
|
671
|
+
|
|
672
|
+
for line in lines:
|
|
673
|
+
# F1: credential check FIRST — a credential-bearing line is
|
|
674
|
+
# never dropped, even if it also matches progress noise.
|
|
675
|
+
is_credential = False
|
|
676
|
+
if _CRED_PATTERNS and _cred_prefilter(line):
|
|
677
|
+
for pat in _CRED_PATTERNS:
|
|
678
|
+
if pat.search(line):
|
|
679
|
+
preserved_lines.append(line)
|
|
680
|
+
is_credential = True
|
|
681
|
+
break
|
|
682
|
+
|
|
683
|
+
# Error line: collect BEFORE the progress-noise drop so that a
|
|
684
|
+
# progress-prefixed error line (e.g. Docker BuildKit
|
|
685
|
+
# "#10 0.317 ERROR: failed to solve") survives in
|
|
686
|
+
# distinct_errors even when the progress filter would drop it
|
|
687
|
+
# from kept_lines. It is re-injected later either way.
|
|
688
|
+
if _COMBINED_ERROR_RE.search(line):
|
|
689
|
+
if line not in _error_seen:
|
|
690
|
+
_error_seen.add(line)
|
|
691
|
+
distinct_errors.append(line)
|
|
692
|
+
|
|
693
|
+
# Progress noise: drop immediately (cheapest check, most common).
|
|
694
|
+
# But never drop a credential-bearing line (F1).
|
|
695
|
+
if not is_credential and _COMBINED_PROGRESS_RE.search(line):
|
|
696
|
+
noise_dropped += 1
|
|
697
|
+
continue
|
|
698
|
+
kept_lines.append(line)
|
|
699
|
+
|
|
700
|
+
# Summary line: keep distinct
|
|
701
|
+
if _COMBINED_SUMMARY_RE.search(line):
|
|
702
|
+
if line not in _summary_seen:
|
|
703
|
+
_summary_seen.add(line)
|
|
704
|
+
summary_lines.append(line)
|
|
705
|
+
|
|
706
|
+
# --- collapse repetition (each pass is O(n) over kept_lines) ---
|
|
707
|
+
collapsed = _collapse_identical_runs(kept_lines)
|
|
708
|
+
collapsed = _collapse_near_identical_warnings(collapsed)
|
|
709
|
+
collapsed = _collapse_traceback_frames(collapsed)
|
|
710
|
+
|
|
711
|
+
# If we didn't actually reduce the line count meaningfully, bail out
|
|
712
|
+
if len(collapsed) >= len(lines) * 0.85 and noise_dropped < len(lines) * 0.10:
|
|
713
|
+
# Not enough repetition to justify compression.
|
|
714
|
+
# Still re-inject preserved, error, and summary lines in case a
|
|
715
|
+
# collapse pass dropped them (traceback-frame collapse removes
|
|
716
|
+
# middle frames, which can carry error-matching source lines).
|
|
717
|
+
# Dedup: a line already in collapsed is not re-injected, and a
|
|
718
|
+
# line already appended is not appended again.
|
|
719
|
+
result = "\n".join(collapsed)
|
|
720
|
+
collapsed_set = set(collapsed)
|
|
721
|
+
appended: list[str] = []
|
|
722
|
+
for line in preserved_lines + distinct_errors + summary_lines:
|
|
723
|
+
if line not in collapsed_set and line not in appended:
|
|
724
|
+
appended.append(line)
|
|
725
|
+
if appended:
|
|
726
|
+
result = result + "\n" + "\n".join(appended)
|
|
727
|
+
# Never return output larger than (or equal to) the original:
|
|
728
|
+
# re-injection can add lines that make the result longer than
|
|
729
|
+
# the input, which defeats the purpose of compression. Prefer
|
|
730
|
+
# the original (return None) in that case.
|
|
731
|
+
if result != output and len(result) < len(output):
|
|
732
|
+
return result
|
|
733
|
+
return None
|
|
734
|
+
|
|
735
|
+
# --- assemble the compressed output ---
|
|
736
|
+
if len(collapsed) <= _HEAD_LINES + _TAIL_LINES:
|
|
737
|
+
parts = list(collapsed)
|
|
738
|
+
else:
|
|
739
|
+
head = collapsed[:_HEAD_LINES]
|
|
740
|
+
tail = collapsed[-_TAIL_LINES:]
|
|
741
|
+
middle = collapsed[_HEAD_LINES:-_TAIL_LINES]
|
|
742
|
+
parts = list(head)
|
|
743
|
+
if len(middle) > 50:
|
|
744
|
+
parts.append(f"... [{len(middle)} more lines, repetition collapsed] ...")
|
|
745
|
+
else:
|
|
746
|
+
parts.extend(middle)
|
|
747
|
+
parts.extend(tail)
|
|
748
|
+
|
|
749
|
+
# Re-inject distinct error lines not already in the output
|
|
750
|
+
current_set = set(parts)
|
|
751
|
+
for e in distinct_errors:
|
|
752
|
+
if e not in current_set:
|
|
753
|
+
parts.append(e)
|
|
754
|
+
current_set.add(e)
|
|
755
|
+
|
|
756
|
+
# Re-inject summary lines not already in the output
|
|
757
|
+
for s in summary_lines:
|
|
758
|
+
if s not in current_set:
|
|
759
|
+
parts.append(s)
|
|
760
|
+
current_set.add(s)
|
|
761
|
+
|
|
762
|
+
# Re-inject credential-bearing lines not already in the output
|
|
763
|
+
for p in preserved_lines:
|
|
764
|
+
if p not in current_set:
|
|
765
|
+
parts.append(p)
|
|
766
|
+
current_set.add(p)
|
|
767
|
+
|
|
768
|
+
compressed = "\n".join(parts)
|
|
769
|
+
|
|
770
|
+
# Only return if we actually shrank the output
|
|
771
|
+
if len(compressed) >= len(output):
|
|
772
|
+
return None
|
|
773
|
+
|
|
774
|
+
return compressed
|
|
775
|
+
except Exception:
|
|
776
|
+
return None
|