@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,998 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Token Optimizer - Structured first-read preview for huge non-code files.
|
|
3
|
+
|
|
4
|
+
When a full Read (no offset/limit) targets a large (>40 KB) non-code file
|
|
5
|
+
(lockfiles, logs, CSV/TSV, JSON/JSONL data dumps, minified bundles, generated
|
|
6
|
+
non-code artifacts), replaces the raw dump with a bounded structured preview:
|
|
7
|
+
- shape/schema summary and exact row/key/package counts
|
|
8
|
+
- head and tail
|
|
9
|
+
- every error/warning/stack-frame line preserved verbatim for logs/SARIF/JSONL
|
|
10
|
+
- exact ranged Read call to inspect more
|
|
11
|
+
- full original archived behind `expand` (via archive_result.archive_original)
|
|
12
|
+
|
|
13
|
+
Safety invariants (fail-open everywhere):
|
|
14
|
+
- Only when offset == 0 and limit == 0 (never overrides ranged Reads).
|
|
15
|
+
- Never for source code, prose/Markdown, or editable config files.
|
|
16
|
+
- Never for files edited in the current session (store.was_file_edited).
|
|
17
|
+
- Conservative size floor (> 40 KB) and ceiling (<= 10 MB).
|
|
18
|
+
- Escape hatch: a second full Read of the same file in the session returns
|
|
19
|
+
the whole file untouched.
|
|
20
|
+
- Requires >= 40% token reduction; otherwise serves the full file untouched.
|
|
21
|
+
- Any archive or parsing failure fails open (serves the full file untouched).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import csv
|
|
27
|
+
import io
|
|
28
|
+
import json
|
|
29
|
+
import os
|
|
30
|
+
import re
|
|
31
|
+
import sys
|
|
32
|
+
from collections import Counter
|
|
33
|
+
from pathlib import Path
|
|
34
|
+
from typing import Any, Callable, Optional
|
|
35
|
+
|
|
36
|
+
from plugin_env import is_v5_flag_enabled
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
from token_estimate import estimate_tokens
|
|
40
|
+
except ImportError: # pragma: no cover
|
|
41
|
+
def estimate_tokens(text: str) -> int:
|
|
42
|
+
return max(1, len(text.encode("utf-8", errors="replace")) // 4) if text else 0
|
|
43
|
+
|
|
44
|
+
# Conservative thresholds
|
|
45
|
+
MIN_BYTES = 40 * 1024 # 40 KiB floor for lockfiles/logs/csv/jsonl/minified/generated
|
|
46
|
+
JSON_DATA_MIN_BYTES = 64 * 1024 # 64 KiB floor for generic .json data dumps (preserves 16-64KB shadow band)
|
|
47
|
+
MAX_BYTES = 10 * 1024 * 1024 # 10 MiB ceiling (hook latency / memory guard)
|
|
48
|
+
MIN_SAVINGS_RATIO = 0.40 # Must save at least 40% of tokens
|
|
49
|
+
MAX_PREVIEW_CHARS = 6000 # Generous cap for log error preservation
|
|
50
|
+
STRICT_PREVIEW_CHARS = 2400 # Tighter cap when hook additionalContext is saved
|
|
51
|
+
MIN_LINES_NON_MINIFIED = 15 # Leave short multi-line files untouched
|
|
52
|
+
|
|
53
|
+
FEATURE_NAME = "big_read_preview"
|
|
54
|
+
REPLACEMENT_TYPE = "big_noncode_preview"
|
|
55
|
+
|
|
56
|
+
# Exact lockfile basenames (lowercased)
|
|
57
|
+
LOCKFILE_NAMES = frozenset({
|
|
58
|
+
"package-lock.json",
|
|
59
|
+
"npm-shrinkwrap.json",
|
|
60
|
+
"shrinkwrap.json",
|
|
61
|
+
"pnpm-lock.yaml",
|
|
62
|
+
"yarn.lock",
|
|
63
|
+
"cargo.lock",
|
|
64
|
+
"uv.lock",
|
|
65
|
+
"poetry.lock",
|
|
66
|
+
"composer.lock",
|
|
67
|
+
"gemfile.lock",
|
|
68
|
+
"go.sum",
|
|
69
|
+
"flake.lock",
|
|
70
|
+
"podfile.lock",
|
|
71
|
+
"pipfile.lock",
|
|
72
|
+
"bun.lock",
|
|
73
|
+
"packages.lock.json",
|
|
74
|
+
"mix.lock",
|
|
75
|
+
"pubspec.lock",
|
|
76
|
+
"paket.lock",
|
|
77
|
+
"pdm.lock",
|
|
78
|
+
"conda-lock.yml",
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
# Minified / bundle suffixes (checked before generic source-code exclusions)
|
|
82
|
+
MINIFIED_SUFFIXES = (
|
|
83
|
+
".min.js",
|
|
84
|
+
".min.css",
|
|
85
|
+
".min.mjs",
|
|
86
|
+
".min.cjs",
|
|
87
|
+
".bundle.js",
|
|
88
|
+
".bundle.css",
|
|
89
|
+
".chunk.js",
|
|
90
|
+
".chunk.css",
|
|
91
|
+
".js.map",
|
|
92
|
+
".css.map",
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
# Generated non-code suffixes
|
|
96
|
+
GENERATED_SUFFIXES = frozenset({".snap", ".har", ".sarif", ".lcov"})
|
|
97
|
+
|
|
98
|
+
# Source code and prose extensions: NEVER intercept
|
|
99
|
+
SOURCE_AND_PROSE_SUFFIXES = frozenset({
|
|
100
|
+
".py", ".pyi", ".js", ".jsx", ".ts", ".tsx", ".mjs", ".cjs", ".mts", ".cts",
|
|
101
|
+
".go", ".rs", ".java", ".kt", ".kts", ".swift", ".c", ".cc", ".cpp", ".cxx",
|
|
102
|
+
".h", ".hh", ".hpp", ".cs", ".rb", ".php", ".sh", ".bash", ".zsh", ".fish",
|
|
103
|
+
".ps1", ".sql", ".html", ".htm", ".css", ".scss", ".sass", ".less",
|
|
104
|
+
".vue", ".svelte", ".astro", ".ex", ".exs", ".erl", ".hs", ".lua",
|
|
105
|
+
".r", ".jl", ".dart", ".scala", ".clj", ".cljs", ".tf", ".hcl",
|
|
106
|
+
".proto", ".graphql", ".gql", ".zig", ".nim", ".ml", ".mli", ".fs", ".fsx",
|
|
107
|
+
".groovy", ".pl", ".pm", ".vb", ".asm", ".s", ".cmake", ".gradle",
|
|
108
|
+
".nix", ".dhall", ".prisma", ".sol",
|
|
109
|
+
# Prose / documentation / config formats
|
|
110
|
+
".md", ".mdx", ".rst", ".txt", ".adoc", ".org", ".tex",
|
|
111
|
+
".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".properties", ".xml",
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
# Editable config basenames (never intercept even if .json and > 40 KB)
|
|
115
|
+
CONFIG_JSON_NAMES = frozenset({
|
|
116
|
+
"package.json",
|
|
117
|
+
"tsconfig.json",
|
|
118
|
+
"jsconfig.json",
|
|
119
|
+
"settings.json",
|
|
120
|
+
"settings.local.json",
|
|
121
|
+
"config.json",
|
|
122
|
+
"hooks.json",
|
|
123
|
+
"plugin.json",
|
|
124
|
+
"marketplace.json",
|
|
125
|
+
"composer.json",
|
|
126
|
+
"manifest.json",
|
|
127
|
+
"launch.json",
|
|
128
|
+
"tasks.json",
|
|
129
|
+
"extensions.json",
|
|
130
|
+
"vercel.json",
|
|
131
|
+
"netlify.json",
|
|
132
|
+
"firebase.json",
|
|
133
|
+
"angular.json",
|
|
134
|
+
"nx.json",
|
|
135
|
+
"turbo.json",
|
|
136
|
+
"lerna.json",
|
|
137
|
+
"renovate.json",
|
|
138
|
+
"devcontainer.json",
|
|
139
|
+
"deno.json",
|
|
140
|
+
"deno.jsonc",
|
|
141
|
+
"biome.json",
|
|
142
|
+
"biome.jsonc",
|
|
143
|
+
"babel.config.json",
|
|
144
|
+
"jest.config.json",
|
|
145
|
+
"wrangler.json",
|
|
146
|
+
"wrangler.jsonc",
|
|
147
|
+
"mcp.json",
|
|
148
|
+
".mcp.json",
|
|
149
|
+
"claude.json",
|
|
150
|
+
".claude.json",
|
|
151
|
+
".eslintrc.json",
|
|
152
|
+
".prettierrc.json",
|
|
153
|
+
"project.json",
|
|
154
|
+
"workspace.json",
|
|
155
|
+
"appsettings.json",
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
# Config directories whose JSON files are usually hand-edited config
|
|
159
|
+
CONFIG_DIR_PARTS = frozenset({
|
|
160
|
+
".claude", ".codex", ".cursor", ".vscode", ".github",
|
|
161
|
+
".config", ".idea", ".husky", ".circleci",
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
_ROTATED_LOG_RE = re.compile(r"\.log\.\d+(?:-\d+)*$", re.IGNORECASE)
|
|
165
|
+
_LOG_LEVEL_RE = re.compile(
|
|
166
|
+
r"\b(FATAL|CRITICAL|SEVERE|ALERT|EMERG|ERROR|ERR|WARN|WARNING|INFO|DEBUG|TRACE)\b"
|
|
167
|
+
)
|
|
168
|
+
_LOG_IMPORTANT_RE = re.compile(
|
|
169
|
+
r"(?:\b(?:FATAL|CRITICAL|SEVERE|ALERT|EMERG|ERROR|WARN|WARNING|FAILED|PANIC)\b"
|
|
170
|
+
r"|Traceback \(most recent call last\):"
|
|
171
|
+
r"|(?:Exception|Error|Panic):\s"
|
|
172
|
+
r"|^\s+File \"[^\"]+\", line \d+"
|
|
173
|
+
r"|^\s+at\s+\S+\s*\([^)]+:\d+"
|
|
174
|
+
r"|^Caused by:)",
|
|
175
|
+
re.IGNORECASE,
|
|
176
|
+
)
|
|
177
|
+
_TIMESTAMP_RE = re.compile(
|
|
178
|
+
r"\b\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b"
|
|
179
|
+
)
|
|
180
|
+
_ERROR_KEY_RE = re.compile(r"^(?:error|errors|err|warning|warnings|warn|failure|failures|diagnostics?)$", re.IGNORECASE)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def is_big_noncode_read_enabled() -> bool:
|
|
184
|
+
"""Feature flag: default OFF (DECISION row 9). Opt in via TOKEN_OPTIMIZER_BIG_NONCODE_READ=1."""
|
|
185
|
+
return is_v5_flag_enabled(
|
|
186
|
+
"v5_big_noncode_read",
|
|
187
|
+
"TOKEN_OPTIMIZER_BIG_NONCODE_READ",
|
|
188
|
+
default=False,
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def classify_big_noncode_file(file_path: str) -> Optional[str]:
|
|
193
|
+
"""Return non-code file kind or None if the file must NOT be intercepted.
|
|
194
|
+
|
|
195
|
+
Categories: 'lockfile', 'minified', 'log', 'csv', 'jsonl', 'json_data', 'generated'.
|
|
196
|
+
Returns None for all source code, prose, credentials, and editable config files.
|
|
197
|
+
"""
|
|
198
|
+
p = Path(file_path)
|
|
199
|
+
name = p.name.lower()
|
|
200
|
+
ext = p.suffix.lower()
|
|
201
|
+
|
|
202
|
+
# Never touch credential / env files
|
|
203
|
+
if name.startswith(".env"):
|
|
204
|
+
return None
|
|
205
|
+
|
|
206
|
+
# 1. Explicit lockfiles (before extension exclusions, e.g. pnpm-lock.yaml, Cargo.lock)
|
|
207
|
+
if name in LOCKFILE_NAMES:
|
|
208
|
+
return "lockfile"
|
|
209
|
+
|
|
210
|
+
# 2. Minified bundles & source maps (before .js/.css source-code exclusions)
|
|
211
|
+
if any(name.endswith(suf) for suf in MINIFIED_SUFFIXES):
|
|
212
|
+
return "minified"
|
|
213
|
+
if ext == ".map":
|
|
214
|
+
return "minified"
|
|
215
|
+
|
|
216
|
+
# 3. Log files (allowed even inside dot-dirs)
|
|
217
|
+
if ext == ".log" or _ROTATED_LOG_RE.search(name):
|
|
218
|
+
return "log"
|
|
219
|
+
|
|
220
|
+
# 4. Source code and prose: hard exclude
|
|
221
|
+
if ext in SOURCE_AND_PROSE_SUFFIXES:
|
|
222
|
+
return None
|
|
223
|
+
|
|
224
|
+
# 5. CSV / TSV
|
|
225
|
+
if ext in (".csv", ".tsv"):
|
|
226
|
+
return "csv"
|
|
227
|
+
|
|
228
|
+
# 6. JSONL / NDJSON
|
|
229
|
+
if ext in (".jsonl", ".ndjson"):
|
|
230
|
+
return "jsonl"
|
|
231
|
+
|
|
232
|
+
# 7. Generated non-code artifacts
|
|
233
|
+
if ext in GENERATED_SUFFIXES or name == "lcov.info":
|
|
234
|
+
return "generated"
|
|
235
|
+
|
|
236
|
+
# 8. JSON data dumps (strictly exclude editable config files and config dirs)
|
|
237
|
+
if ext == ".json":
|
|
238
|
+
if name in CONFIG_JSON_NAMES:
|
|
239
|
+
return None
|
|
240
|
+
if name.startswith(("tsconfig.", "appsettings.")) or name.endswith(".config.json"):
|
|
241
|
+
return None
|
|
242
|
+
parts_lower = {part.lower() for part in p.parts[:-1]}
|
|
243
|
+
if parts_lower & CONFIG_DIR_PARTS:
|
|
244
|
+
return None
|
|
245
|
+
return "json_data"
|
|
246
|
+
|
|
247
|
+
return None
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _clip_line(line: str, max_len: int = 220) -> str:
|
|
251
|
+
if len(line) <= max_len:
|
|
252
|
+
return line
|
|
253
|
+
return line[: max_len - 18] + f"... ({len(line):,} chars)"
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _is_error_line(line: str, *, strict_exception_only: bool = False) -> bool:
|
|
257
|
+
try:
|
|
258
|
+
from visibility_rule import is_error_or_failure_line
|
|
259
|
+
if is_error_or_failure_line(line, strict_exception_only=strict_exception_only):
|
|
260
|
+
return True
|
|
261
|
+
except Exception:
|
|
262
|
+
pass
|
|
263
|
+
if strict_exception_only:
|
|
264
|
+
return False
|
|
265
|
+
return bool(_LOG_IMPORTANT_RE.search(line))
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _format_head_tail(
|
|
269
|
+
lines: list[str],
|
|
270
|
+
head_n: int = 10,
|
|
271
|
+
tail_n: int = 8,
|
|
272
|
+
line_cap: int = 220,
|
|
273
|
+
*,
|
|
274
|
+
place: str = "",
|
|
275
|
+
strict_errors: bool = False,
|
|
276
|
+
skip_middle_errors: bool = False,
|
|
277
|
+
) -> list[str]:
|
|
278
|
+
total = len(lines)
|
|
279
|
+
out: list[str] = []
|
|
280
|
+
if total <= head_n + tail_n:
|
|
281
|
+
for idx, ln in enumerate(lines, 1):
|
|
282
|
+
out.append(f"L{idx}: {_clip_line(ln, line_cap)}")
|
|
283
|
+
return out
|
|
284
|
+
out.append(f"Head (lines 1-{head_n}):")
|
|
285
|
+
for idx in range(head_n):
|
|
286
|
+
ln = lines[idx]
|
|
287
|
+
out.append(f" L{idx + 1}: {ln if _is_error_line(ln) else _clip_line(ln, line_cap)}")
|
|
288
|
+
mid_start = head_n + 1
|
|
289
|
+
mid_end = total - tail_n
|
|
290
|
+
preserved_middle: list[tuple[int, str]] = []
|
|
291
|
+
if not skip_middle_errors:
|
|
292
|
+
for idx in range(head_n, total - tail_n):
|
|
293
|
+
if _is_error_line(lines[idx], strict_exception_only=strict_errors):
|
|
294
|
+
preserved_middle.append((idx + 1, lines[idx]))
|
|
295
|
+
omitted = (total - head_n - tail_n) - len(preserved_middle)
|
|
296
|
+
place_note = f" in {place}" if place else ""
|
|
297
|
+
if preserved_middle:
|
|
298
|
+
out.append(f" Preserved error/failure lines ({len(preserved_middle)} verbatim):")
|
|
299
|
+
for lno, text in preserved_middle:
|
|
300
|
+
out.append(f" L{lno}: {text}")
|
|
301
|
+
if omitted > 0:
|
|
302
|
+
out.append(f" ... ({omitted:,} lines omitted{place_note}, lines {mid_start}-{mid_end}) ...")
|
|
303
|
+
out.append(f"Tail (lines {total - tail_n + 1}-{total}):")
|
|
304
|
+
for idx in range(total - tail_n, total):
|
|
305
|
+
ln = lines[idx]
|
|
306
|
+
out.append(f" L{idx + 1}: {ln if _is_error_line(ln) else _clip_line(ln, line_cap)}")
|
|
307
|
+
return out
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _preview_lockfile(content: str, file_path: str, lines: list[str]) -> tuple[str, int]:
|
|
311
|
+
name = Path(file_path).name.lower()
|
|
312
|
+
summary_lines: list[str] = []
|
|
313
|
+
pkg_names: list[str] = []
|
|
314
|
+
pkg_count: Optional[int] = None
|
|
315
|
+
|
|
316
|
+
if name.endswith(".json"):
|
|
317
|
+
try:
|
|
318
|
+
data = json.loads(content)
|
|
319
|
+
if isinstance(data, dict):
|
|
320
|
+
lf_ver = data.get("lockfileVersion")
|
|
321
|
+
root_name = data.get("name", "")
|
|
322
|
+
packages = data.get("packages")
|
|
323
|
+
deps = data.get("dependencies")
|
|
324
|
+
if isinstance(packages, dict):
|
|
325
|
+
pkg_count = max(0, len(packages) - (1 if "" in packages else 0))
|
|
326
|
+
for k in packages:
|
|
327
|
+
if k:
|
|
328
|
+
pkg_names.append(k.split("node_modules/")[-1])
|
|
329
|
+
elif isinstance(deps, dict):
|
|
330
|
+
pkg_count = len(deps)
|
|
331
|
+
pkg_names = list(deps.keys())
|
|
332
|
+
elif isinstance(data.get("nodes"), dict): # flake.lock
|
|
333
|
+
pkg_count = len(data["nodes"])
|
|
334
|
+
pkg_names = list(data["nodes"].keys())
|
|
335
|
+
meta_parts = [f"format={name}"]
|
|
336
|
+
if root_name:
|
|
337
|
+
meta_parts.append(f"project={root_name}")
|
|
338
|
+
if lf_ver is not None:
|
|
339
|
+
meta_parts.append(f"lockfileVersion={lf_ver}")
|
|
340
|
+
if pkg_count is not None:
|
|
341
|
+
meta_parts.append(f"packages={pkg_count:,}")
|
|
342
|
+
summary_lines.append("Shape: " + ", ".join(meta_parts))
|
|
343
|
+
except Exception:
|
|
344
|
+
pass
|
|
345
|
+
elif name in ("cargo.lock", "uv.lock", "poetry.lock"):
|
|
346
|
+
pkg_re = re.compile(r'^\s*name\s*=\s*"([^"]+)"')
|
|
347
|
+
in_pkg = False
|
|
348
|
+
for ln in lines:
|
|
349
|
+
s = ln.strip()
|
|
350
|
+
if s == "[[package]]":
|
|
351
|
+
in_pkg = True
|
|
352
|
+
elif in_pkg:
|
|
353
|
+
m = pkg_re.match(ln)
|
|
354
|
+
if m:
|
|
355
|
+
pkg_names.append(m.group(1))
|
|
356
|
+
in_pkg = False
|
|
357
|
+
pkg_count = len(pkg_names)
|
|
358
|
+
summary_lines.append(f"Shape: format={name}, packages={pkg_count:,}")
|
|
359
|
+
elif name == "go.sum":
|
|
360
|
+
mods = {ln.split()[0] for ln in lines if ln.strip()}
|
|
361
|
+
pkg_count = len(mods)
|
|
362
|
+
pkg_names = sorted(mods)
|
|
363
|
+
summary_lines.append(f"Shape: format=go.sum, entries={len(lines):,}, unique_modules={pkg_count:,}")
|
|
364
|
+
elif name == "yarn.lock":
|
|
365
|
+
entries = [ln.rstrip(":").strip('"') for ln in lines if ln and not ln[0].isspace() and not ln.startswith("#") and ln.endswith(":")]
|
|
366
|
+
pkg_count = len(entries)
|
|
367
|
+
pkg_names = entries
|
|
368
|
+
summary_lines.append(f"Shape: format=yarn.lock, entries={pkg_count:,}")
|
|
369
|
+
elif name == "pnpm-lock.yaml":
|
|
370
|
+
in_pkgs = False
|
|
371
|
+
for ln in lines:
|
|
372
|
+
if ln.startswith("packages:"):
|
|
373
|
+
in_pkgs = True
|
|
374
|
+
continue
|
|
375
|
+
if in_pkgs:
|
|
376
|
+
if ln and not ln[0].isspace():
|
|
377
|
+
break
|
|
378
|
+
if ln.startswith(" ") and not ln.startswith(" ") and ln.rstrip().endswith(":"):
|
|
379
|
+
pkg_names.append(ln.strip().rstrip(":").strip("'\""))
|
|
380
|
+
pkg_count = len(pkg_names)
|
|
381
|
+
summary_lines.append(f"Shape: format=pnpm-lock.yaml, packages={pkg_count:,}")
|
|
382
|
+
else:
|
|
383
|
+
summary_lines.append(f"Shape: format={name}, lines={len(lines):,}")
|
|
384
|
+
|
|
385
|
+
if pkg_names:
|
|
386
|
+
sample = ", ".join(pkg_names[:15])
|
|
387
|
+
more = f" (+{len(pkg_names) - 15:,} more)" if len(pkg_names) > 15 else ""
|
|
388
|
+
summary_lines.append(f"Sample packages: {sample}{more}")
|
|
389
|
+
|
|
390
|
+
summary_lines.extend(_format_head_tail(lines, head_n=10, tail_n=6, place=Path(file_path).name, strict_errors=True))
|
|
391
|
+
return "\n".join(summary_lines), 11
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _preview_log(content: str, file_path: str, lines: list[str]) -> tuple[str, int]:
|
|
395
|
+
level_counts: Counter[str] = Counter()
|
|
396
|
+
important_groups: dict[str, list[int]] = {}
|
|
397
|
+
important_order: list[str] = []
|
|
398
|
+
first_ts: Optional[str] = None
|
|
399
|
+
last_ts: Optional[str] = None
|
|
400
|
+
|
|
401
|
+
for idx, ln in enumerate(lines, 1):
|
|
402
|
+
m_lvl = _LOG_LEVEL_RE.search(ln)
|
|
403
|
+
if m_lvl:
|
|
404
|
+
lvl = m_lvl.group(1).upper()
|
|
405
|
+
if lvl == "WARNING":
|
|
406
|
+
lvl = "WARN"
|
|
407
|
+
elif lvl == "ERR":
|
|
408
|
+
lvl = "ERROR"
|
|
409
|
+
level_counts[lvl] += 1
|
|
410
|
+
if first_ts is None:
|
|
411
|
+
m_ts = _TIMESTAMP_RE.search(ln)
|
|
412
|
+
if m_ts:
|
|
413
|
+
first_ts = m_ts.group(0)
|
|
414
|
+
if _is_error_line(ln):
|
|
415
|
+
# Preserve exact text verbatim; deduplicate only exact identical lines
|
|
416
|
+
if ln not in important_groups:
|
|
417
|
+
important_groups[ln] = [idx]
|
|
418
|
+
important_order.append(ln)
|
|
419
|
+
else:
|
|
420
|
+
important_groups[ln].append(idx)
|
|
421
|
+
|
|
422
|
+
for ln in reversed(lines):
|
|
423
|
+
m_ts = _TIMESTAMP_RE.search(ln)
|
|
424
|
+
if m_ts:
|
|
425
|
+
last_ts = m_ts.group(0)
|
|
426
|
+
break
|
|
427
|
+
|
|
428
|
+
out: list[str] = []
|
|
429
|
+
shape_parts = [f"lines={len(lines):,}"]
|
|
430
|
+
if first_ts and last_ts and first_ts != last_ts:
|
|
431
|
+
shape_parts.append(f"time_range={first_ts} .. {last_ts}")
|
|
432
|
+
elif first_ts:
|
|
433
|
+
shape_parts.append(f"time={first_ts}")
|
|
434
|
+
if level_counts:
|
|
435
|
+
lvl_str = ", ".join(f"{k}={v:,}" for k, v in level_counts.most_common())
|
|
436
|
+
shape_parts.append(f"levels=({lvl_str})")
|
|
437
|
+
out.append("Shape: " + "; ".join(shape_parts))
|
|
438
|
+
|
|
439
|
+
total_imp = sum(len(v) for v in important_groups.values())
|
|
440
|
+
if important_order:
|
|
441
|
+
out.append(f"Errors/warnings/stack frames ({total_imp:,} total, {len(important_order):,} unique):")
|
|
442
|
+
for text in important_order:
|
|
443
|
+
lns = important_groups[text]
|
|
444
|
+
if len(lns) == 1:
|
|
445
|
+
out.append(f" L{lns[0]}: {text}")
|
|
446
|
+
elif len(lns) <= 4:
|
|
447
|
+
refs = ",".join(f"L{n}" for n in lns)
|
|
448
|
+
out.append(f" {refs} (x{len(lns)}): {text}")
|
|
449
|
+
else:
|
|
450
|
+
out.append(f" L{lns[0]}..L{lns[-1]} (x{len(lns)}): {text}")
|
|
451
|
+
else:
|
|
452
|
+
out.append("Errors/warnings: 0 detected.")
|
|
453
|
+
|
|
454
|
+
out.extend(_format_head_tail(lines, head_n=8, tail_n=12, place=Path(file_path).name, skip_middle_errors=True))
|
|
455
|
+
return "\n".join(out), 9
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def _preview_csv(content: str, file_path: str, lines: list[str]) -> tuple[str, int]:
|
|
459
|
+
ext = Path(file_path).suffix.lower()
|
|
460
|
+
delim = "\t" if ext == ".tsv" else ","
|
|
461
|
+
delim_label = "TSV (tab)" if delim == "\t" else "CSV (comma)"
|
|
462
|
+
|
|
463
|
+
header: list[str] = []
|
|
464
|
+
sample_vals: list[str] = []
|
|
465
|
+
row_count = 0
|
|
466
|
+
try:
|
|
467
|
+
reader = csv.reader(io.StringIO(content), delimiter=delim)
|
|
468
|
+
header = next(reader, [])
|
|
469
|
+
sample_vals = [""] * len(header)
|
|
470
|
+
for row in reader:
|
|
471
|
+
row_count += 1
|
|
472
|
+
if row_count <= 20:
|
|
473
|
+
for i, val in enumerate(row[: len(sample_vals)]):
|
|
474
|
+
if not sample_vals[i] and val.strip():
|
|
475
|
+
sample_vals[i] = val.strip()[:40]
|
|
476
|
+
except Exception:
|
|
477
|
+
row_count = max(0, len(lines) - 1)
|
|
478
|
+
|
|
479
|
+
out: list[str] = [
|
|
480
|
+
f"Shape: {delim_label}, rows={row_count:,}, columns={len(header)}"
|
|
481
|
+
]
|
|
482
|
+
if header:
|
|
483
|
+
cols_desc = []
|
|
484
|
+
for i, col in enumerate(header[:15]):
|
|
485
|
+
ex = sample_vals[i] if i < len(sample_vals) and sample_vals[i] else ""
|
|
486
|
+
cols_desc.append(f"{col} (e.g. {ex!r})" if ex else col)
|
|
487
|
+
more = f" (+{len(header) - 15} more)" if len(header) > 15 else ""
|
|
488
|
+
out.append("Columns: " + ", ".join(cols_desc) + more)
|
|
489
|
+
|
|
490
|
+
out.extend(_format_head_tail(lines, head_n=8, tail_n=5, place=Path(file_path).name))
|
|
491
|
+
return "\n".join(out), 9
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _json_type_label(val: Any) -> str:
|
|
495
|
+
if val is None:
|
|
496
|
+
return "null"
|
|
497
|
+
if isinstance(val, bool):
|
|
498
|
+
return "bool"
|
|
499
|
+
if isinstance(val, int):
|
|
500
|
+
return "int"
|
|
501
|
+
if isinstance(val, float):
|
|
502
|
+
return "float"
|
|
503
|
+
if isinstance(val, str):
|
|
504
|
+
return "str"
|
|
505
|
+
if isinstance(val, list):
|
|
506
|
+
return f"list[{len(val):,}]"
|
|
507
|
+
if isinstance(val, dict):
|
|
508
|
+
return f"dict[{len(val):,}]"
|
|
509
|
+
return type(val).__name__
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
def _preview_jsonl(content: str, file_path: str, lines: list[str]) -> tuple[str, int]:
|
|
513
|
+
total = len(lines)
|
|
514
|
+
valid_objs = 0
|
|
515
|
+
non_json_lines: list[tuple[int, str]] = []
|
|
516
|
+
error_records: list[tuple[int, str]] = []
|
|
517
|
+
key_counts: Counter[str] = Counter()
|
|
518
|
+
key_types: dict[str, set[str]] = {}
|
|
519
|
+
|
|
520
|
+
for idx, ln in enumerate(lines, 1):
|
|
521
|
+
s = ln.strip()
|
|
522
|
+
if not s:
|
|
523
|
+
continue
|
|
524
|
+
try:
|
|
525
|
+
obj = json.loads(s)
|
|
526
|
+
except Exception:
|
|
527
|
+
non_json_lines.append((idx, _clip_line(s, 180)))
|
|
528
|
+
continue
|
|
529
|
+
if isinstance(obj, dict):
|
|
530
|
+
valid_objs += 1
|
|
531
|
+
if valid_objs <= 500 or idx > total - 20:
|
|
532
|
+
for k, v in obj.items():
|
|
533
|
+
key_counts[k] += 1
|
|
534
|
+
key_types.setdefault(k, set()).add(_json_type_label(v))
|
|
535
|
+
# Preserve any record carrying an error/warning
|
|
536
|
+
has_err = False
|
|
537
|
+
for k, v in obj.items():
|
|
538
|
+
if _ERROR_KEY_RE.match(k) and v:
|
|
539
|
+
has_err = True
|
|
540
|
+
break
|
|
541
|
+
if k.lower() in ("level", "severity") and isinstance(v, str) and v.upper() in ("ERROR", "FATAL", "CRITICAL", "WARN", "WARNING"):
|
|
542
|
+
has_err = True
|
|
543
|
+
break
|
|
544
|
+
if has_err or _is_error_line(s):
|
|
545
|
+
error_records.append((idx, s))
|
|
546
|
+
|
|
547
|
+
out: list[str] = [
|
|
548
|
+
f"Shape: JSONL, lines={total:,}, json_objects={valid_objs:,}, non_json_lines={len(non_json_lines)}"
|
|
549
|
+
]
|
|
550
|
+
if key_counts:
|
|
551
|
+
schema_parts = []
|
|
552
|
+
for k, _cnt in key_counts.most_common(15):
|
|
553
|
+
types = "/".join(sorted(key_types.get(k, set()))[:3])
|
|
554
|
+
schema_parts.append(f"{k} ({types})")
|
|
555
|
+
more = f" (+{len(key_counts) - 15} more)" if len(key_counts) > 15 else ""
|
|
556
|
+
out.append("Schema keys: " + ", ".join(schema_parts) + more)
|
|
557
|
+
|
|
558
|
+
if error_records:
|
|
559
|
+
out.append(f"Error/warning records ({len(error_records):,}):")
|
|
560
|
+
for idx, txt in error_records:
|
|
561
|
+
out.append(f" L{idx}: {txt}")
|
|
562
|
+
if non_json_lines:
|
|
563
|
+
out.append(f"Non-JSON lines ({len(non_json_lines):,}):")
|
|
564
|
+
for idx, txt in non_json_lines[:20]:
|
|
565
|
+
out.append(f" L{idx}: {txt}")
|
|
566
|
+
|
|
567
|
+
out.extend(_format_head_tail(lines, head_n=5, tail_n=3, line_cap=240, place=Path(file_path).name, skip_middle_errors=True))
|
|
568
|
+
return "\n".join(out), 6
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def _preview_json_data(content: str, file_path: str, lines: list[str]) -> tuple[str, int]:
|
|
572
|
+
out: list[str] = []
|
|
573
|
+
try:
|
|
574
|
+
data = json.loads(content)
|
|
575
|
+
except Exception:
|
|
576
|
+
out.append(f"Shape: JSON (unparsed), lines={len(lines):,}, bytes={len(content.encode('utf-8', errors='replace')):,}")
|
|
577
|
+
out.extend(_format_head_tail(lines, head_n=10, tail_n=6))
|
|
578
|
+
return "\n".join(out), 11
|
|
579
|
+
|
|
580
|
+
if isinstance(data, list):
|
|
581
|
+
out.append(f"Shape: JSON array, items={len(data):,}, lines={len(lines):,}")
|
|
582
|
+
item_types = Counter(_json_type_label(x).split("[")[0] for x in data[:200])
|
|
583
|
+
out.append("Item types: " + ", ".join(f"{k}={v}" for k, v in item_types.most_common(5)))
|
|
584
|
+
dict_items = [x for x in data[:200] if isinstance(x, dict)]
|
|
585
|
+
if dict_items:
|
|
586
|
+
keys: Counter[str] = Counter()
|
|
587
|
+
ktypes: dict[str, set[str]] = {}
|
|
588
|
+
for item in dict_items:
|
|
589
|
+
for k, v in item.items():
|
|
590
|
+
keys[k] += 1
|
|
591
|
+
ktypes.setdefault(k, set()).add(_json_type_label(v).split("[")[0])
|
|
592
|
+
schema = ", ".join(f"{k} ({'/'.join(sorted(ktypes[k])[:2])})" for k, _ in keys.most_common(15))
|
|
593
|
+
more = f" (+{len(keys) - 15} more)" if len(keys) > 15 else ""
|
|
594
|
+
out.append(f"Item schema: {schema}{more}")
|
|
595
|
+
if data:
|
|
596
|
+
out.append("First items:")
|
|
597
|
+
for i, item in enumerate(data[:3]):
|
|
598
|
+
out.append(f" [{i}]: {_clip_line(json.dumps(item, ensure_ascii=False), 240)}")
|
|
599
|
+
if len(data) > 5:
|
|
600
|
+
out.append(f" ... ({len(data) - 5:,} items omitted in middle) ...")
|
|
601
|
+
out.append("Last items:")
|
|
602
|
+
for i in range(len(data) - 2, len(data)):
|
|
603
|
+
out.append(f" [{i}]: {_clip_line(json.dumps(data[i], ensure_ascii=False), 240)}")
|
|
604
|
+
elif isinstance(data, dict):
|
|
605
|
+
out.append(f"Shape: JSON object, top_level_keys={len(data):,}, lines={len(lines):,}")
|
|
606
|
+
key_summary = [f"{k}: {_json_type_label(v)}" for k, v in list(data.items())[:20]]
|
|
607
|
+
more = f" (+{len(data) - 20:,} more)" if len(data) > 20 else ""
|
|
608
|
+
out.append("Top-level keys: " + ", ".join(key_summary) + more)
|
|
609
|
+
# Preserve any top-level error/warning fields verbatim (bounded)
|
|
610
|
+
for k, v in data.items():
|
|
611
|
+
if _ERROR_KEY_RE.match(k) and v:
|
|
612
|
+
rendered = json.dumps(v, ensure_ascii=False)
|
|
613
|
+
out.append(f"Field {k!r}: {_clip_line(rendered, 600)}")
|
|
614
|
+
if len(lines) > 3:
|
|
615
|
+
out.extend(_format_head_tail(lines, head_n=10, tail_n=6))
|
|
616
|
+
else:
|
|
617
|
+
out.append(f"Head chars: {content[:300]}")
|
|
618
|
+
out.append(f"Tail chars: {content[-200:]}")
|
|
619
|
+
else:
|
|
620
|
+
out.append(f"Shape: JSON {_json_type_label(data)}, lines={len(lines):,}")
|
|
621
|
+
out.extend(_format_head_tail(lines, head_n=10, tail_n=6))
|
|
622
|
+
|
|
623
|
+
return "\n".join(out), 11
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _preview_minified(content: str, file_path: str, lines: list[str]) -> tuple[str, int]:
|
|
627
|
+
name = Path(file_path).name.lower()
|
|
628
|
+
max_line_len = max((len(ln) for ln in lines), default=0)
|
|
629
|
+
out: list[str] = []
|
|
630
|
+
|
|
631
|
+
if name.endswith(".map"):
|
|
632
|
+
try:
|
|
633
|
+
data = json.loads(content)
|
|
634
|
+
if isinstance(data, dict):
|
|
635
|
+
sources = data.get("sources") or []
|
|
636
|
+
names = data.get("names") or []
|
|
637
|
+
out.append(
|
|
638
|
+
f"Shape: SourceMap v{data.get('version', '?')}, file={data.get('file', '?')}, "
|
|
639
|
+
f"sources={len(sources):,}, names={len(names):,}"
|
|
640
|
+
)
|
|
641
|
+
if sources:
|
|
642
|
+
sample = ", ".join(str(s) for s in sources[:15])
|
|
643
|
+
more = f" (+{len(sources) - 15:,} more)" if len(sources) > 15 else ""
|
|
644
|
+
out.append(f"Sources in {Path(file_path).name}: {sample}{more}")
|
|
645
|
+
return "\n".join(out), 1
|
|
646
|
+
except Exception:
|
|
647
|
+
pass
|
|
648
|
+
|
|
649
|
+
kind_label = "minified CSS" if name.endswith(".css") else "minified JS/bundle"
|
|
650
|
+
extra = f", css_blocks~={content.count('{'):,}" if name.endswith(".css") else ""
|
|
651
|
+
out.append(
|
|
652
|
+
f"Shape: {kind_label}, lines={len(lines):,}, max_line_chars={max_line_len:,}{extra}"
|
|
653
|
+
)
|
|
654
|
+
out.append(f"Head (first 300 chars): {content[:300]!r}")
|
|
655
|
+
if len(content) > 500:
|
|
656
|
+
out.append(f"... ({len(content) - 500:,} chars omitted in line 1, middle) ...")
|
|
657
|
+
out.append(f"Tail (last 200 chars): {content[-200:]!r}")
|
|
658
|
+
return "\n".join(out), 1
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def _preview_generated(content: str, file_path: str, lines: list[str]) -> tuple[str, int]:
|
|
662
|
+
name = Path(file_path).name.lower()
|
|
663
|
+
ext = Path(file_path).suffix.lower()
|
|
664
|
+
out: list[str] = []
|
|
665
|
+
|
|
666
|
+
if ext == ".snap":
|
|
667
|
+
exports = [
|
|
668
|
+
m.group(1)
|
|
669
|
+
for ln in lines
|
|
670
|
+
for m in (re.match(r'^exports\[`([^`]+)`\]', ln),)
|
|
671
|
+
if m
|
|
672
|
+
]
|
|
673
|
+
out.append(f"Shape: snapshot file, lines={len(lines):,}, snapshots={len(exports):,}")
|
|
674
|
+
if exports:
|
|
675
|
+
sample = ", ".join(exports[:12])
|
|
676
|
+
more = f" (+{len(exports) - 12:,} more)" if len(exports) > 12 else ""
|
|
677
|
+
out.append(f"Snapshots: {sample}{more}")
|
|
678
|
+
elif ext == ".har":
|
|
679
|
+
try:
|
|
680
|
+
data = json.loads(content)
|
|
681
|
+
entries = (data.get("log") or {}).get("entries") or []
|
|
682
|
+
statuses: Counter[int] = Counter()
|
|
683
|
+
errors: list[str] = []
|
|
684
|
+
for e in entries:
|
|
685
|
+
st = int((e.get("response") or {}).get("status") or 0)
|
|
686
|
+
statuses[st] += 1
|
|
687
|
+
if st >= 400:
|
|
688
|
+
url = (e.get("request") or {}).get("url", "")
|
|
689
|
+
errors.append(f" HTTP {st}: {_clip_line(str(url), 160)}")
|
|
690
|
+
st_str = ", ".join(f"{k}={v}" for k, v in sorted(statuses.items()))
|
|
691
|
+
out.append(f"Shape: HAR archive, entries={len(entries):,}, statuses=({st_str})")
|
|
692
|
+
if errors:
|
|
693
|
+
out.append(f"HTTP 4xx/5xx entries ({len(errors)}):")
|
|
694
|
+
out.extend(errors[:30])
|
|
695
|
+
except Exception:
|
|
696
|
+
out.append(f"Shape: HAR file, lines={len(lines):,}")
|
|
697
|
+
elif ext == ".sarif":
|
|
698
|
+
try:
|
|
699
|
+
data = json.loads(content)
|
|
700
|
+
runs = data.get("runs") or []
|
|
701
|
+
results = [r for run in runs for r in (run.get("results") or [])]
|
|
702
|
+
levels = Counter(str(r.get("level", "warning")) for r in results)
|
|
703
|
+
out.append(f"Shape: SARIF report, runs={len(runs)}, results={len(results):,}, levels={dict(levels)}")
|
|
704
|
+
for r in results:
|
|
705
|
+
lvl = str(r.get("level", "warning")).lower()
|
|
706
|
+
if lvl in ("error", "warning"):
|
|
707
|
+
rule = r.get("ruleId", "?")
|
|
708
|
+
msg = ((r.get("message") or {}).get("text") or "").strip()
|
|
709
|
+
loc = ""
|
|
710
|
+
locs = r.get("locations") or []
|
|
711
|
+
if locs:
|
|
712
|
+
pl = (locs[0].get("physicalLocation") or {})
|
|
713
|
+
uri = (pl.get("artifactLocation") or {}).get("uri", "")
|
|
714
|
+
line = (pl.get("region") or {}).get("startLine", "")
|
|
715
|
+
if uri:
|
|
716
|
+
loc = f" ({uri}:{line})" if line else f" ({uri})"
|
|
717
|
+
out.append(f" [{lvl.upper()}] {rule}{loc}: {_clip_line(msg, 180)}")
|
|
718
|
+
except Exception:
|
|
719
|
+
out.append(f"Shape: SARIF file, lines={len(lines):,}")
|
|
720
|
+
else:
|
|
721
|
+
out.append(f"Shape: generated file ({name}), lines={len(lines):,}")
|
|
722
|
+
|
|
723
|
+
out.extend(_format_head_tail(lines, head_n=8, tail_n=6, place=Path(file_path).name))
|
|
724
|
+
return "\n".join(out), 9
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
_BUILDERS = {
|
|
728
|
+
"lockfile": _preview_lockfile,
|
|
729
|
+
"log": _preview_log,
|
|
730
|
+
"csv": _preview_csv,
|
|
731
|
+
"jsonl": _preview_jsonl,
|
|
732
|
+
"json_data": _preview_json_data,
|
|
733
|
+
"minified": _preview_minified,
|
|
734
|
+
"generated": _preview_generated,
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
|
|
738
|
+
def build_big_noncode_preview(
|
|
739
|
+
file_path: str,
|
|
740
|
+
content: str,
|
|
741
|
+
*,
|
|
742
|
+
kind: Optional[str] = None,
|
|
743
|
+
archive_key: Optional[str] = None,
|
|
744
|
+
max_chars: int = MAX_PREVIEW_CHARS,
|
|
745
|
+
) -> Optional[dict[str, Any]]:
|
|
746
|
+
"""Build a structured preview dict, or return None if compression is not worthwhile.
|
|
747
|
+
|
|
748
|
+
Returns dict with keys: kind, reason, context, orig_tokens, preview_tokens, ratio.
|
|
749
|
+
"""
|
|
750
|
+
raw_bytes = len(content.encode("utf-8", errors="replace"))
|
|
751
|
+
if raw_bytes < MIN_BYTES or raw_bytes > MAX_BYTES:
|
|
752
|
+
return None
|
|
753
|
+
|
|
754
|
+
file_kind = kind or classify_big_noncode_file(file_path)
|
|
755
|
+
if file_kind is None:
|
|
756
|
+
return None
|
|
757
|
+
if file_kind == "json_data" and raw_bytes < JSON_DATA_MIN_BYTES:
|
|
758
|
+
return None
|
|
759
|
+
|
|
760
|
+
lines = content.splitlines()
|
|
761
|
+
if file_kind != "minified" and file_kind != "json_data" and len(lines) < MIN_LINES_NON_MINIFIED:
|
|
762
|
+
return None
|
|
763
|
+
|
|
764
|
+
builder = _BUILDERS.get(file_kind)
|
|
765
|
+
if builder is None:
|
|
766
|
+
return None
|
|
767
|
+
|
|
768
|
+
body, next_offset = builder(content, file_path, lines)
|
|
769
|
+
orig_tokens = estimate_tokens(content)
|
|
770
|
+
if orig_tokens <= 0:
|
|
771
|
+
return None
|
|
772
|
+
|
|
773
|
+
size_kb = raw_bytes / 1024.0
|
|
774
|
+
name = Path(file_path).name
|
|
775
|
+
header = (
|
|
776
|
+
f"[Token Optimizer] Structured preview of {name} "
|
|
777
|
+
f"({size_kb:.1f} KB, {len(lines):,} lines, ~{orig_tokens:,} tokens, kind={file_kind})."
|
|
778
|
+
)
|
|
779
|
+
ranged_hint = (
|
|
780
|
+
f'For more lines: Read(file_path="{file_path}", offset={next_offset}, limit=200)\n'
|
|
781
|
+
f'To load the entire file as-is, call Read(file_path="{file_path}") again.'
|
|
782
|
+
)
|
|
783
|
+
preview_text = f"{header}\n{body}\n\n{ranged_hint}"
|
|
784
|
+
|
|
785
|
+
# Visibility rule (a): never hide any critical error/exception/traceback line.
|
|
786
|
+
try:
|
|
787
|
+
from visibility_rule import find_missing_critical_lines
|
|
788
|
+
missing_crit = find_missing_critical_lines(content, preview_text)
|
|
789
|
+
if missing_crit:
|
|
790
|
+
crit_block = "\n".join(f" L{lno}: {txt}" for lno, txt in missing_crit)
|
|
791
|
+
preview_text = f"{header}\n{body}\nPreserved critical lines ({len(missing_crit)}):\n{crit_block}\n\n{ranged_hint}"
|
|
792
|
+
except Exception:
|
|
793
|
+
pass
|
|
794
|
+
|
|
795
|
+
if archive_key:
|
|
796
|
+
try:
|
|
797
|
+
from archive_result import build_archive_pointer
|
|
798
|
+
preview_text = build_archive_pointer(preview_text, len(content), archive_key)
|
|
799
|
+
except Exception:
|
|
800
|
+
return None
|
|
801
|
+
|
|
802
|
+
if len(preview_text) > max_chars:
|
|
803
|
+
# Never silently truncate away log/SARIF error lines; fail open instead.
|
|
804
|
+
return None
|
|
805
|
+
from emit_safety_gate import gate_or_none as _emit_gate
|
|
806
|
+
if _emit_gate(content, preview_text, feature=FEATURE_NAME, tool_name="Read", require_expand=bool(archive_key)) is None:
|
|
807
|
+
return None
|
|
808
|
+
|
|
809
|
+
reason = (
|
|
810
|
+
f"{name} is a large non-code {file_kind} ({size_kb:.1f} KB, ~{orig_tokens:,} tokens); "
|
|
811
|
+
f"served structured preview. Call Read with offset/limit, use expand, or re-Read for full file."
|
|
812
|
+
)
|
|
813
|
+
preview_tokens = estimate_tokens(reason) + estimate_tokens(preview_text)
|
|
814
|
+
ratio = 1.0 - (preview_tokens / orig_tokens)
|
|
815
|
+
if ratio < MIN_SAVINGS_RATIO:
|
|
816
|
+
return None
|
|
817
|
+
|
|
818
|
+
return {
|
|
819
|
+
"kind": file_kind,
|
|
820
|
+
"reason": reason,
|
|
821
|
+
"context": preview_text,
|
|
822
|
+
"orig_tokens": orig_tokens,
|
|
823
|
+
"preview_tokens": preview_tokens,
|
|
824
|
+
"ratio": round(ratio, 4),
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def compress_for_benchmark(command: str, raw_output: str) -> str:
|
|
829
|
+
"""Benchmark adapter compatible with benchmark.run_single_fixture(fixture, compressor).
|
|
830
|
+
|
|
831
|
+
Accepts command like 'Read:package-lock.json' or 'Read:/tmp/app.log'.
|
|
832
|
+
Returns the structured preview text if eligible, else raw_output untouched.
|
|
833
|
+
"""
|
|
834
|
+
file_path = command.split("Read:", 1)[1].strip() if "Read:" in command else command.strip()
|
|
835
|
+
result = build_big_noncode_preview(file_path, raw_output, archive_key=None)
|
|
836
|
+
if result is None:
|
|
837
|
+
return raw_output
|
|
838
|
+
return result["context"]
|
|
839
|
+
|
|
840
|
+
|
|
841
|
+
def try_big_noncode_read(
|
|
842
|
+
file_path: str,
|
|
843
|
+
stat: os.stat_result,
|
|
844
|
+
offset: int,
|
|
845
|
+
limit: int,
|
|
846
|
+
session_id: str,
|
|
847
|
+
store: Any,
|
|
848
|
+
mode: str,
|
|
849
|
+
entry: dict[str, Any],
|
|
850
|
+
*,
|
|
851
|
+
cached_content: Optional[str] = None,
|
|
852
|
+
reset_epoch: Any = None,
|
|
853
|
+
save_hook_context_enabled: bool = False,
|
|
854
|
+
quiet: bool = True,
|
|
855
|
+
emit_fn: Optional[Callable[..., None]] = None,
|
|
856
|
+
log_decision_fn: Optional[Callable[..., None]] = None,
|
|
857
|
+
log_savings_fn: Optional[Callable[..., Any]] = None,
|
|
858
|
+
) -> bool:
|
|
859
|
+
"""PreToolUse[Read] entry point called from read_cache.py on first read (entry is None).
|
|
860
|
+
|
|
861
|
+
Returns True iff a structured preview was archived and emitted (caller must stop).
|
|
862
|
+
Returns False (fail-open) on any ineligible file, safety exclusion, or error.
|
|
863
|
+
"""
|
|
864
|
+
try:
|
|
865
|
+
if not is_big_noncode_read_enabled():
|
|
866
|
+
return False
|
|
867
|
+
if mode not in ("soft_block", "block"):
|
|
868
|
+
return False
|
|
869
|
+
# Never override ranged Reads
|
|
870
|
+
if offset != 0 or limit != 0:
|
|
871
|
+
return False
|
|
872
|
+
|
|
873
|
+
size = int(stat.st_size)
|
|
874
|
+
if size < MIN_BYTES or size > MAX_BYTES:
|
|
875
|
+
return False
|
|
876
|
+
|
|
877
|
+
kind = classify_big_noncode_file(file_path)
|
|
878
|
+
if kind is None:
|
|
879
|
+
return False
|
|
880
|
+
if kind == "json_data" and size < JSON_DATA_MIN_BYTES:
|
|
881
|
+
return False
|
|
882
|
+
|
|
883
|
+
# Never intercept files edited in this session
|
|
884
|
+
if store is not None and store.was_file_edited(file_path):
|
|
885
|
+
return False
|
|
886
|
+
|
|
887
|
+
content = (
|
|
888
|
+
cached_content
|
|
889
|
+
if cached_content is not None
|
|
890
|
+
else Path(file_path).read_text(encoding="utf-8", errors="replace")
|
|
891
|
+
)
|
|
892
|
+
|
|
893
|
+
# Archive full original BEFORE emitting preview; fail open if archive fails
|
|
894
|
+
from archive_result import (
|
|
895
|
+
archive_entry_exists,
|
|
896
|
+
archive_original,
|
|
897
|
+
derive_archive_key,
|
|
898
|
+
)
|
|
899
|
+
|
|
900
|
+
key = derive_archive_key(session_id, file_path, stat.st_mtime_ns)
|
|
901
|
+
if (
|
|
902
|
+
archive_original(
|
|
903
|
+
content,
|
|
904
|
+
session_id,
|
|
905
|
+
key,
|
|
906
|
+
"Read",
|
|
907
|
+
quiet=quiet,
|
|
908
|
+
file_path=file_path,
|
|
909
|
+
language=kind,
|
|
910
|
+
)
|
|
911
|
+
is None
|
|
912
|
+
):
|
|
913
|
+
return False
|
|
914
|
+
if not archive_entry_exists(session_id, key):
|
|
915
|
+
return False
|
|
916
|
+
|
|
917
|
+
cap = STRICT_PREVIEW_CHARS if save_hook_context_enabled else MAX_PREVIEW_CHARS
|
|
918
|
+
result = build_big_noncode_preview(
|
|
919
|
+
file_path, content, kind=kind, archive_key=key, max_chars=cap
|
|
920
|
+
)
|
|
921
|
+
if result is None:
|
|
922
|
+
return False
|
|
923
|
+
|
|
924
|
+
# Escape hatch: store a non-empty sentinel range [[-1, -1]] (empty []
|
|
925
|
+
# falls back to [[0, 0]] in read_cache.py) so a second full Read sees
|
|
926
|
+
# range_covered == False and returns the entire file whole.
|
|
927
|
+
entry["ranges_seen"] = [[-1, -1]]
|
|
928
|
+
entry["last_replacement_type"] = REPLACEMENT_TYPE
|
|
929
|
+
entry["tokens_est"] = result["orig_tokens"]
|
|
930
|
+
if store is not None:
|
|
931
|
+
store.upsert_file_entry(file_path, entry, expected_reset_epoch=reset_epoch)
|
|
932
|
+
|
|
933
|
+
net_saved = max(0, result["orig_tokens"] - result["preview_tokens"])
|
|
934
|
+
if log_decision_fn is not None:
|
|
935
|
+
log_decision_fn(
|
|
936
|
+
"block",
|
|
937
|
+
file_path,
|
|
938
|
+
"big_noncode_preview",
|
|
939
|
+
session_id,
|
|
940
|
+
mode=mode,
|
|
941
|
+
actual_substitution=True,
|
|
942
|
+
eligible=True,
|
|
943
|
+
language=kind,
|
|
944
|
+
reason_code=REPLACEMENT_TYPE,
|
|
945
|
+
offset=offset,
|
|
946
|
+
limit=limit,
|
|
947
|
+
replacement_type=REPLACEMENT_TYPE,
|
|
948
|
+
file_tokens_est=result["orig_tokens"],
|
|
949
|
+
replacement_tokens_est=result["preview_tokens"],
|
|
950
|
+
net_saved_tokens_est=net_saved,
|
|
951
|
+
replacement_fingerprint=key,
|
|
952
|
+
repeat_replacement_count=1,
|
|
953
|
+
save_hook_additional_context_enabled=save_hook_context_enabled,
|
|
954
|
+
)
|
|
955
|
+
|
|
956
|
+
# Log Measured savings to savings_events (primary ledger, owns the key)
|
|
957
|
+
# and compression_events (ratio telemetry, excluded from double-count)
|
|
958
|
+
# per docs/METHODOLOGY.md Section 3.1. Re-expanding the archive debits
|
|
959
|
+
# via tool_archive_reexpand in savings_events (R8).
|
|
960
|
+
if log_savings_fn is not None and net_saved > 0:
|
|
961
|
+
try:
|
|
962
|
+
log_savings_fn(
|
|
963
|
+
FEATURE_NAME,
|
|
964
|
+
net_saved,
|
|
965
|
+
session_id,
|
|
966
|
+
f"{Path(file_path).name}:{kind}:archive={key}",
|
|
967
|
+
)
|
|
968
|
+
except Exception:
|
|
969
|
+
pass
|
|
970
|
+
try:
|
|
971
|
+
from compression_log import log_compression_event
|
|
972
|
+
log_compression_event(
|
|
973
|
+
feature=FEATURE_NAME,
|
|
974
|
+
session_id=session_id,
|
|
975
|
+
command_pattern=f"Read:{kind}:{Path(file_path).name}",
|
|
976
|
+
tier="measured",
|
|
977
|
+
verified=True,
|
|
978
|
+
quality_preserved=True,
|
|
979
|
+
detail=f"kind={kind} size_bytes={size} archive={key}",
|
|
980
|
+
original_tokens=result["orig_tokens"],
|
|
981
|
+
compressed_tokens=result["preview_tokens"],
|
|
982
|
+
)
|
|
983
|
+
except Exception:
|
|
984
|
+
pass
|
|
985
|
+
|
|
986
|
+
if not quiet:
|
|
987
|
+
print(
|
|
988
|
+
f"[Read Cache] Big non-code preview ({kind}): {file_path} "
|
|
989
|
+
f"(~{result['orig_tokens']:,} -> ~{result['preview_tokens']:,} tokens, "
|
|
990
|
+
f"saved ~{net_saved:,})",
|
|
991
|
+
file=sys.stderr,
|
|
992
|
+
)
|
|
993
|
+
|
|
994
|
+
if emit_fn is not None:
|
|
995
|
+
emit_fn("deny", result["reason"], result["context"])
|
|
996
|
+
return True
|
|
997
|
+
except Exception:
|
|
998
|
+
return False
|