burnoff 1.3.0 → 1.4.1

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.
@@ -1,733 +1,734 @@
1
- /**
2
- * @file src/storage/fts5-archive.mjs
3
- * Fail-Open CLI Output Compressor & Local SQLite FTS5 Index (`tool_logs_fts5.db`).
4
- *
5
- * Strictly FAIL-OPEN: if any exception occurs during SQLite indexing or parsing,
6
- * returns the raw output untouched so builds and test workflows never break.
7
- */
8
-
9
- import fs from 'node:fs';
10
- import path from 'node:path';
11
- import { getHomeDir, getBurnoffCacheDir } from '../config/paths.mjs';
12
- import { openBurnoffDb, resolveFallbackDbPath } from './sqlite-client.mjs';
13
- import { recordInterventionSavings } from './ledger.mjs';
14
-
15
- export const FTS5_COMPRESSOR_CONSTANTS = Object.freeze({
16
- MIN_LINES_TO_COMPRESS: 40,
17
- MIN_BYTES_TO_COMPRESS: 4096,
18
- MAX_SUMMARY_LINES: 25,
19
- TARGET_COMMAND_REGEX:
20
- /(?:(?:^|[\s;|&])@['"]|\b(?:pytest|jest|vitest|cargo\s+(?:test|clippy|check|build)|tsc|go\s+test|eslint|biome|ruff|next\s+build|vite\s+build|(?:mvn|mvnw(?:\.cmd)?|gradle|gradlew(?:\.bat)?|kotlinc)\b|dotnet\s+(?:test|build)\b|make\b|ctest\b|bazel\s+(?:test|build)\b|(?:(?:npx|pnpm(?:\s+exec)?)\s+)?playwright\s+test\b|(?:bundle\s+exec\s+)?rspec\b|phpunit\b|deno\s+test\b|docker\s+(?:build|logs)|kubectl\s+(?:logs|get|describe)|gh\s+(?:pr|run|api|issue|release|workflow)|git\s+(?:diff|log|show|status|grep|ls-files|blame|branch|tag|stash|reflog|cherry-pick)|(?:npm|pnpm|yarn|bun)\s+(?:test|run\s+(?:test|lint|build|typecheck)|install|ci|add|update|audit|outdated|pack|publish)|(?:pip3?|uv|poetry)\s+(?:install|sync|audit|list|show)|node(?:\.exe)?|python3?(?:\.exe)?|select-string|get-childitem|gci|get-content|write-output|powershell|pwsh|rg|ripgrep|grep|find|fd|tree|curl|wget|aws|gcloud|terraform)\b)/i
21
- });
22
-
23
- export function getDefaultToolLogsDbPath(homeDir = null) {
24
- return path.join(getBurnoffCacheDir(homeDir), 'tool_logs_fts5.db');
25
- }
26
-
27
- export function isCompressibleCliCommand(command = '') {
28
- return FTS5_COMPRESSOR_CONSTANTS.TARGET_COMMAND_REGEX.test(String(command || ''));
29
- }
30
-
31
- const POWERSHELL_HEREDOC_OR_SEARCH_RE =
32
- /(?:(?:^|[\s;|&])@['"]|\b(?:select-string|get-childitem|gci)\b)/i;
33
- const BOUNDED_PIPE_FILTER_RE =
34
- /\|\s*(?:head|tail|sed|awk|cut|wc|grep|egrep|fgrep|rg|ripgrep|jq)\b/i;
35
- const INLINE_SCRIPT_OR_HEREDOC_RE =
36
- /\b(?:node(?:\.exe)?\s+(?:-[ep]\b|--eval\b|--print\b)|python3?(?:\.exe)?\s+(?:-c\b|-\s*<<|<<))|\bcat\s*>\s*\S+[\s\S]*<</i;
37
- const FILE_INSPECTION_SEGMENT_RE =
38
- /^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)*(?:(?:\/[\w./-]+)?\/)?(?:cat|head|tail|sed|awk|cut|wc|nl|tac|rev|less|more|bat|jq|stat|file(?=\s+\S)|ls|dir|tree|grep|egrep|fgrep|rg|ripgrep|get-content)(?=\s|$)(?![.\w-])/i;
39
- const GIT_INSPECTION_CMD_RE = /\bgit\s+(?:diff|show|status|blame|log)\b/i;
40
- const NOISY_PRIMARY_RUNNER_RE =
41
- /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:test|install|ci|run|build|lint|typecheck)|node\s+--test|pytest|jest|vitest|cargo|go\s+test|tsc|eslint|biome|ruff|next\s+build|vite\s+build|mvn|mvnw|gradle|gradlew|kotlinc|dotnet\s+(?:test|build)|make|ctest|bazel\s+(?:test|build)|playwright\s+test|rspec|phpunit|deno\s+test|docker|kubectl)\b/i;
42
-
43
- export function classifyShellPostToolPolicy(command = '') {
44
- const cmd = String(command || '').trim();
45
- if (!cmd) {
46
- return { allowFts5: false, allowOffload: true, reason: 'empty_command' };
47
- }
48
- if (BOUNDED_PIPE_FILTER_RE.test(cmd)) {
49
- return { allowFts5: false, allowOffload: false, reason: 'explicitly_bounded_shell_output' };
50
- }
51
- const segments = cmd.split(/(?:&&|\|\||;|\||\r?\n)/);
52
- const hasInspectionSegment = segments.some((seg) => FILE_INSPECTION_SEGMENT_RE.test(seg));
53
- if (POWERSHELL_HEREDOC_OR_SEARCH_RE.test(cmd) && !hasInspectionSegment) {
54
- return { allowFts5: true, allowOffload: true, reason: 'eligible_powershell_cli' };
55
- }
56
- if (INLINE_SCRIPT_OR_HEREDOC_RE.test(cmd)) {
57
- return { allowFts5: false, allowOffload: false, reason: 'inline_script_or_heredoc' };
58
- }
59
- if (hasInspectionSegment) {
60
- return { allowFts5: false, allowOffload: false, reason: 'file_inspection_shell_command' };
61
- }
62
- if (GIT_INSPECTION_CMD_RE.test(cmd) && !NOISY_PRIMARY_RUNNER_RE.test(cmd)) {
63
- return { allowFts5: false, allowOffload: false, reason: 'git_inspection_command' };
64
- }
65
- return { allowFts5: true, allowOffload: true, reason: 'eligible_cli_output' };
66
- }
67
-
68
- export function classifyCliCommandFamily(command = '') {
69
- const cmd = String(command || '').toLowerCase();
70
- if (/\bgit\s+(diff|log|show|status)\b/.test(cmd)) return 'git';
71
- if (/\b(docker|kubectl)\b/.test(cmd) || /\bgh\s+(pr|run)\b/.test(cmd)) return 'infra';
72
- if (
73
- /\b(pytest|jest|vitest|cargo\s+test|node\s+--test|(?:npm|pnpm|yarn|bun)\s+(?:test|run\s+(?:test|lint|build|typecheck))|go\s+test|(?:mvn|mvnw(?:\.cmd)?)\s+[^\n]*(?:test|verify)|(?:gradle|gradlew(?:\.bat)?)\s+[^\n]*(?:test|check)|dotnet\s+test|bazel\s+test|playwright\s+test|rspec|phpunit|deno\s+test|ctest|make\s+(?:test|check))\b/.test(
74
- cmd
75
- )
76
- ) {
77
- return 'test';
78
- }
79
- if (
80
- /\b(eslint|biome|ruff|tsc|cargo\s+(clippy|check|build)|next\s+build|vite\s+build|mvn|mvnw(?:\.cmd)?|gradle|gradlew(?:\.bat)?|kotlinc|dotnet\s+build|bazel\s+build|make)\b/.test(
81
- cmd
82
- )
83
- ) {
84
- return 'lint_build';
85
- }
86
- if (
87
- /\b(select-string|get-childitem|gci|rg|ripgrep|grep|find|fd|tree)\b/.test(cmd) ||
88
- /\bgit\s+(grep|ls-files)\b/.test(cmd)
89
- ) {
90
- return 'search_list';
91
- }
92
- if (/\bgh\b/.test(cmd) && !/\bgh\s+(api|issue|release|workflow)\b/.test(cmd)) return 'infra';
93
- return 'generic_cli';
94
- }
95
-
96
- function pushUniqueBounded(arr, item, maxLen, sliceLen = 140) {
97
- const cleaned = String(item || '').trim().slice(0, sliceLen);
98
- if (!cleaned || arr.includes(cleaned) || arr.length >= maxLen) return;
99
- arr.push(cleaned);
100
- }
101
-
102
- export function buildDeterministicSummary(rawOutput = '', {
103
- command = 'pytest',
104
- exitCode = 1,
105
- turnId = 'turn-1',
106
- maxLines = FTS5_COMPRESSOR_CONSTANTS.MAX_SUMMARY_LINES
107
- } = {}) {
108
- const lines = String(rawOutput || '').split(/\r?\n/);
109
- const family = classifyCliCommandFamily(command);
110
- const queryHandleLine = `FTS5 Query Handle: npx burnoff search ${turnId} "<keyword>" (full output archived; do not re-run)`;
111
-
112
- if (family === 'git') {
113
- const fileHeaders = [];
114
- const hunksOrMeta = [];
115
- const conflictsOrErrors = [];
116
- for (const rawLine of lines) {
117
- const line = rawLine.trim();
118
- if (!line) continue;
119
- if (/^(diff --git |\+\+\+ [ab]\/|--- [ab]\/|commit [0-9a-f]{7,})/.test(line)) {
120
- pushUniqueBounded(fileHeaders, line, 10);
121
- } else if (/^\s*(M|A|D|R\d*|C\d*|UU|\?\?)\s+\S+/.test(rawLine)) {
122
- pushUniqueBounded(fileHeaders, line, 10);
123
- } else if (/^@@\s+.*\s+@@/.test(line) || /^(\d+\s+files?\s+changed|[\w./-]+\s+\|\s+\d+)/.test(line)) {
124
- pushUniqueBounded(hunksOrMeta, line, 8);
125
- } else if (/^(<{7}|={7}|>{7}|error:|fatal:)/i.test(line)) {
126
- pushUniqueBounded(conflictsOrErrors, line, 4);
127
- }
128
- }
129
- const out = [
130
- `[FTS5 Compressed CLI Output] cmd="${command}" exit_code=${exitCode} raw_lines=${lines.length}`,
131
- `Git Files & Hunks (${fileHeaders.length} files, ${hunksOrMeta.length} hunks):`
132
- ];
133
- for (const f of fileHeaders) out.push(` ${f}`);
134
- for (const h of hunksOrMeta) out.push(` ${h}`);
135
- for (const c of conflictsOrErrors) out.push(` ${c}`);
136
- if (out.length <= 2) {
137
- for (const tailLine of lines.slice(-6)) {
138
- if (tailLine.trim()) out.push(` ${tailLine.trim().slice(0, 140)}`);
139
- }
140
- }
141
- const bounded = out.slice(0, Math.max(1, maxLines - 1));
142
- bounded.push(queryHandleLine);
143
- return bounded.slice(0, maxLines).join('\n');
144
- }
145
-
146
- if (family === 'infra') {
147
- const errors = [];
148
- const stages = [];
149
- for (const rawLine of lines) {
150
- const line = rawLine.trim();
151
- if (!line) continue;
152
- if (/\b(ERROR|FATAL|panic:|CrashLoopBackOff|ImagePullBackOff|ErrImagePull|OOMKilled|FAILED|fail)\b/i.test(line) || /^[✗✖X]\s+/.test(line)) {
153
- pushUniqueBounded(errors, line, 12);
154
- } else if (/^(#\d+\s+(?:DONE|ERROR)|Step\s+\d+\/\d+|NAME\s+READY|Successfully\s+(?:built|tagged))/i.test(line)) {
155
- pushUniqueBounded(stages, line, 6);
156
- }
157
- }
158
- const out = [
159
- `[FTS5 Compressed CLI Output] cmd="${command}" exit_code=${exitCode} raw_lines=${lines.length}`,
160
- `Infra & Deploy Diagnostics (${errors.length} error(s), ${stages.length} stage(s)):`
161
- ];
162
- for (const e of errors) out.push(` ${e}`);
163
- for (const s of stages) out.push(` ${s}`);
164
- if (errors.length === 0 && stages.length === 0) {
165
- for (const tailLine of lines.slice(-6)) {
166
- if (tailLine.trim()) out.push(` ${tailLine.trim().slice(0, 140)}`);
167
- }
168
- }
169
- const bounded = out.slice(0, Math.max(1, maxLines - 1));
170
- bounded.push(queryHandleLine);
171
- return bounded.slice(0, maxLines).join('\n');
172
- }
173
-
174
- if (family === 'search_list') {
175
- const groups = new Map();
176
- const samples = [];
177
- const errors = [];
178
- for (const rawLine of lines) {
179
- const line = rawLine.trim();
180
- if (!line) continue;
181
- if (/\b(ERROR|FATAL|Exception|AccessDenied|UnauthorizedAccess)\b/i.test(line)) {
182
- pushUniqueBounded(errors, line, 4, 140);
183
- continue;
184
- }
185
- const grepMatch = line.match(/^((?:[A-Za-z]:)?[./\\\w-]+?\.[a-zA-Z0-9]{1,8}):(\d+):(.*)$/);
186
- if (grepMatch) {
187
- const key = grepMatch[1];
188
- if (!groups.has(key)) groups.set(key, { count: 0, first: `L${grepMatch[2]}: ${grepMatch[3].trim()}` });
189
- groups.get(key).count += 1;
190
- } else {
191
- pushUniqueBounded(samples, line, 12, 140);
192
- }
193
- }
194
- const rawBytes = Buffer.byteLength(String(rawOutput || ''), 'utf8');
195
- const out = [
196
- `[FTS5 Compressed CLI Output] cmd="${String(command).slice(0, 80)}" exit_code=${exitCode} raw_lines=${lines.length} raw_bytes=${rawBytes}`,
197
- `Search/List Summary (${groups.size} matched file(s), ${samples.length} other line(s)):`
198
- ];
199
- for (const e of errors) out.push(` ! ${e}`);
200
- let shown = 0;
201
- for (const [fileKey, info] of groups.entries()) {
202
- shown += 1;
203
- if (shown > 10) {
204
- out.push(` ... +${groups.size - 10} more matched files indexed`);
205
- break;
206
- }
207
- out.push(` ${fileKey} (${info.count}): ${info.first}`.slice(0, 140));
208
- }
209
- if (groups.size === 0) {
210
- for (const s of samples.slice(0, 10)) out.push(` ${s}`);
211
- if (lines.length > 10) out.push(` ... +${lines.length - 10} more lines indexed`);
212
- }
213
- const bounded = out.slice(0, Math.max(1, maxLines - 1));
214
- bounded.push(queryHandleLine);
215
- return bounded.slice(0, maxLines).join('\n');
216
- }
217
-
218
- if (family === 'generic_cli') {
219
- const errors = [];
220
- const nonEmpty = [];
221
- for (const rawLine of lines) {
222
- const line = rawLine.trim();
223
- if (!line) continue;
224
- if (
225
- /\b(ERROR|FATAL|WARN|WARNING|Exception|AssertionError|TypeError|ReferenceError|SyntaxError|ERR!|FAILED|fail)\b/i.test(line) ||
226
- /^(?:ℹ\s*(?:tests|suites|pass|fail)\b|#\s*(?:tests|suites|pass|fail)\b)/i.test(line)
227
- ) {
228
- pushUniqueBounded(errors, line, 10, 240);
229
- }
230
- nonEmpty.push(line);
231
- }
232
- const rawBytes = Buffer.byteLength(String(rawOutput || ''), 'utf8');
233
- const out = [
234
- `[FTS5 Compressed CLI Output] cmd="${String(command).slice(0, 80)}" exit_code=${exitCode} raw_lines=${lines.length} raw_bytes=${rawBytes}`,
235
- `Diagnostics & Head/Tail Preview (${errors.length} error/warn line(s)):`
236
- ];
237
- for (const e of errors) out.push(` ${e}`);
238
- for (const h of nonEmpty.slice(0, 5)) pushUniqueBounded(out, ` ${h}`, maxLines - 1, 140);
239
- if (nonEmpty.length > 5) {
240
- for (const t of nonEmpty.slice(-5)) pushUniqueBounded(out, ` ${t}`, maxLines - 1, 140);
241
- }
242
- const bounded = out.slice(0, Math.max(1, maxLines - 1));
243
- bounded.push(queryHandleLine);
244
- return bounded.slice(0, maxLines).join('\n');
245
- }
246
-
247
- const failingTests = [];
248
- const fileLineTraces = [];
249
- const assertionLines = [];
250
- const summaryLines = [];
251
- const warningLines = [];
252
-
253
- for (const rawLine of lines) {
254
- const line = rawLine.trim();
255
- if (!line) continue;
256
-
257
- const isKotlinWarning = /^w:\s+/.test(line);
258
- const isKotlinError = /^e:\s+/.test(line);
259
-
260
- if (
261
- /^(FAILED|FAIL|✖|✗|✘|--- FAIL:)\s+/.test(line) ||
262
- /^[✘✖×]\s+\d+\s+/.test(line) ||
263
- /^\d+\)\s+(?:\[[^\]]+\]\s+›\s+|\S+)/.test(line) ||
264
- /^_{3,}\s+.+\s+_{3,}$/.test(line) ||
265
- /^test\s+[\w:./-]+\s+\.\.\.\s+FAILED/i.test(line) ||
266
- /^FAIL\t\S+/.test(line) ||
267
- /^\[ERROR\]\s+(?:Failures:|Errors:|BUILD\s+FAILURE|.+<<<\s*(?:FAILURE|ERROR)!|\S+:\d+\s+)/.test(line) ||
268
- /^>\s+Task\s+:\S+\s+FAILED/.test(line) ||
269
- /^.+\s+>\s+.+\s+FAILED$/.test(line) ||
270
- /^FAILURE:\s+Build\s+failed/.test(line) ||
271
- /^Execution\s+failed\s+for\s+task\s+':\S+'/i.test(line) ||
272
- /^Failed\s+\S+/.test(line) ||
273
- /^make(?:\[\d+\])?:\s*\*\*\*/.test(line) ||
274
- /^\d+\/\d+\s+Test\s+#\d+:.+\*\*\*Failed/i.test(line) ||
275
- /^(?:FAIL|ERROR):\s+(?:\/\/)?\S+/.test(line) ||
276
- /^rspec\s+[\w./\\-]+:\d+/.test(line) ||
277
- /^(?:FAILURES|ERRORS)!$/.test(line) ||
278
- /^.+\s+\.\.\.\s+FAILED\s+\(/.test(line)
279
- ) {
280
- const cleaned = line.replace(/^_{3,}\s*|\s*_{3,}$/g, '').trim();
281
- pushUniqueBounded(failingTests, cleaned, 6, 160);
282
- }
283
-
284
- if (
285
- /^(?:ℹ\s*(?:tests|suites|pass|fail|cancelled|skipped|todo|duration_ms)\b|#\s*(?:tests|suites|pass|fail|cancelled|skipped|todo|ok)\b|Tests?:|Test Suites?:|Test Files?:|Ran\s+\d+\s+tests?|test result:|===+\s+\d+\s+(?:passed|failed)|\d+\s+(?:passed|passing|failed|failing)\b|PASS(?:\s+\S+)?$|ok\s+\S+\s+[\d.]+s|\[(?:INFO|ERROR)\]\s+(?:Tests\s+run:\s*\d+|BUILD\s+(?:SUCCESS|FAILURE))|\d+\s+tests?\s+completed,\s*\d+\s+failed|BUILD\s+(?:SUCCESSFUL|FAILED)|(?:Failed|Passed)!\s+-\s+Failed:\s*\d+|Build\s+(?:FAILED|succeeded)|\d+%\s+tests?\s+passed,\s*\d+\s+tests?\s+failed|Executed\s+\d+\s+out\s+of\s+\d+\s+tests?:|\d+\s+examples?,\s*\d+\s+failures?|Tests:\s*\d+,\s*Assertions:\s*\d+|OK\s+\(\d+\s+tests?|(?:ok|FAILED)\s+\|\s+\d+\s+passed\s+\|\s+\d+\s+failed)/i.test(
286
- line
287
- )
288
- ) {
289
- pushUniqueBounded(summaryLines, line, 8, 200);
290
- }
291
-
292
- if (/\b(?:WARN|WARNING)\b[:\s]/i.test(line) || isKotlinWarning) {
293
- pushUniqueBounded(warningLines, line, 4, 240);
294
- }
295
-
296
- if (
297
- !isKotlinWarning &&
298
- (/\b[A-Za-z0-9_./\\-]+\.(?:py|ts|tsx|js|mjs|cjs|rs|go|java|kt|kts|groovy|scala|rb|php|cs|cpp|cc|cxx|c|h|hpp)(?::\d+(?::\d+)?|\[\d+,\d+\]|(?::\s*)?\(\d+,\s*\d+\)|\s*:\s*line\s+\d+)/i.test(
299
- line
300
- ) ||
301
- /\b[A-Za-z0-9_./\\-]+\.(?:ts|tsx|cs)\(\d+,\d+\):\s*error\s+(?:TS|CS)\d+/i.test(line) ||
302
- /\bMakefile:\d+/.test(line) ||
303
- /^\d+:\d+\s+(?:error|warning)\s+/i.test(line) ||
304
- /\berror\[E\d+\]:/i.test(line) ||
305
- (family === 'lint_build' && /^[A-Za-z0-9_./\\-]+\.(?:py|ts|tsx|js|mjs|cjs|rs|go|jsx|java|kt|cs|cpp|c)$/.test(line)))
306
- ) {
307
- pushUniqueBounded(fileLineTraces, line, 9, 180);
308
- }
309
-
310
- if (
311
- isKotlinError ||
312
- /^(E\s+|AssertionError:|Error:|Expected\b|Received\b|Actual\b|assert\s+|error\s+|Failed asserting|Caused by:|org\.junit|org\.opentest4j\.|kotlin\.test\.|java\.lang\.AssertionError|AssertionFailedError\b|Assert\.|\[ERROR\]\s+.*error:|>\s+(?:Compilation\s+error|Could\s+not\s+resolve|There\s+were\s+failing\s+tests))/i.test(
313
- line
314
- )
315
- ) {
316
- pushUniqueBounded(assertionLines, line, 5, 180);
317
- }
318
- }
319
-
320
- const out = [];
321
- out.push(`[FTS5 Compressed CLI Output] cmd="${command}" exit_code=${exitCode} raw_lines=${lines.length}`);
322
- if (failingTests.length === 0 && Number(exitCode) === 0) {
323
- out.push('Result: PASS (0 failing tests)');
324
- if (warningLines.length > 0) {
325
- out.push(`Warnings (${warningLines.length}):`);
326
- for (const w of warningLines) out.push(` ${w}`);
327
- }
328
- out.push('Test Summary:');
329
- if (summaryLines.length > 0) {
330
- for (const s of summaryLines) out.push(` ${s}`);
331
- } else if (fileLineTraces.length > 0) {
332
- for (const tr of fileLineTraces.slice(0, 8)) out.push(` ${tr}`);
333
- } else {
334
- for (const tailLine of lines.slice(-6)) {
335
- if (tailLine.trim()) out.push(` ${tailLine.trim().slice(0, 140)}`);
336
- }
337
- }
338
- } else {
339
- out.push(`Failing Tests (${failingTests.length}):`);
340
- if (failingTests.length > 0) {
341
- for (const ft of failingTests.slice(0, 6)) out.push(` - ${ft}`);
342
- } else {
343
- out.push(` - (No structured test header matched; see tracebacks below)`);
344
- }
345
-
346
- out.push(`File:Line Tracebacks & Assertions:`);
347
- const combinedTraces = [...new Set([...fileLineTraces, ...assertionLines])].slice(summaryLines.length > 0 ? 0 : 0, summaryLines.length > 0 ? 8 : 10);
348
- if (combinedTraces.length > 0) {
349
- for (const tr of combinedTraces) out.push(` ${tr}`);
350
- } else {
351
- for (const tailLine of lines.slice(-6)) {
352
- if (tailLine.trim()) out.push(` ${tailLine.trim().slice(0, 140)}`);
353
- }
354
- }
355
- if (warningLines.length > 0) {
356
- out.push(`Warnings (${warningLines.length}):`);
357
- for (const w of warningLines.slice(0, 2)) out.push(` ${w}`);
358
- }
359
- if (summaryLines.length > 0) {
360
- out.push('Test Summary:');
361
- for (const s of summaryLines.slice(0, 4)) out.push(` ${s}`);
362
- }
363
- }
364
-
365
- const bounded = out.slice(0, Math.max(1, maxLines - 1));
366
- bounded.push(queryHandleLine);
367
- return bounded.slice(0, maxLines).join('\n');
368
- }
369
-
370
- export function compressCliOutputFts5Sync({
371
- sessionId = 'default-session',
372
- turnId = 'turn-1',
373
- command = 'pytest',
374
- exitCode = 1,
375
- rawOutput = '',
376
- dbPath = null,
377
- homeDir = getHomeDir(),
378
- DatabaseSync = null,
379
- forceCompress = false,
380
- recordLedger = true,
381
- ledgerPath = null,
382
- minBytes = 0,
383
- minTokensSaved = 0,
384
- retentionDays = 30
385
- } = {}) {
386
- const rawStr = String(rawOutput || '');
387
- const rawLines = rawStr.split(/\r?\n/);
388
- const rawBytes = Buffer.byteLength(rawStr, 'utf8');
389
- const rawTokens = Math.ceil(rawStr.length / 4);
390
- const meetsMinBytes = minBytes <= 0 || rawBytes >= Number(minBytes);
391
- const meetsSizeThreshold =
392
- meetsMinBytes &&
393
- (rawLines.length > FTS5_COMPRESSOR_CONSTANTS.MIN_LINES_TO_COMPRESS ||
394
- rawBytes >= FTS5_COMPRESSOR_CONSTANTS.MIN_BYTES_TO_COMPRESS);
395
-
396
- if (!forceCompress && (!meetsSizeThreshold || !isCompressibleCliCommand(command))) {
397
- return {
398
- compressed: false,
399
- failOpen: false,
400
- output: rawStr,
401
- lineCount: rawLines.length,
402
- rawTokens,
403
- compressedTokens: rawTokens,
404
- tokensSaved: 0,
405
- reductionPct: 0,
406
- turnId,
407
- queryHandle: null
408
- };
409
- }
410
-
411
- let db = null;
412
- try {
413
- const resolvedDbPath = dbPath || getDefaultToolLogsDbPath(homeDir);
414
- db = openBurnoffDb(resolvedDbPath, { readOnly: false, DatabaseSync });
415
-
416
- db.exec(`
417
- CREATE VIRTUAL TABLE IF NOT EXISTS tool_logs USING fts5(
418
- session_id,
419
- turn_id,
420
- command,
421
- exit_code,
422
- raw_output,
423
- created_at
424
- );
425
- CREATE TABLE IF NOT EXISTS tool_logs_meta (
426
- key TEXT PRIMARY KEY,
427
- value TEXT NOT NULL
428
- );
429
- `);
430
-
431
- const createdAt = new Date().toISOString();
432
- db.prepare(`
433
- INSERT INTO tool_logs (session_id, turn_id, command, exit_code, raw_output, created_at)
434
- VALUES (?, ?, ?, ?, ?, ?)
435
- `).run(
436
- String(sessionId),
437
- String(turnId),
438
- String(command),
439
- String(exitCode),
440
- rawStr,
441
- createdAt
442
- );
443
-
444
- try {
445
- pruneExpiredFts5LogsSync(db, Date.now(), Number(retentionDays ?? 30));
446
- } catch (pruneErr) {
447
- void pruneErr; // ignore: non-fatal background retention prune
448
- }
449
-
450
- const summary = buildDeterministicSummary(rawStr, {
451
- command,
452
- exitCode,
453
- turnId,
454
- maxLines: FTS5_COMPRESSOR_CONSTANTS.MAX_SUMMARY_LINES
455
- });
456
- if (!forceCompress && summary.length >= rawStr.length) {
457
- return {
458
- compressed: false,
459
- failOpen: false,
460
- dbPath: resolvedDbPath,
461
- output: rawStr,
462
- lineCount: rawLines.length,
463
- rawTokens,
464
- compressedTokens: rawTokens,
465
- tokensSaved: 0,
466
- reductionPct: 0,
467
- turnId: String(turnId),
468
- queryHandle: null
469
- };
470
- }
471
- const summaryLines = summary.split(/\r?\n/);
472
- const compressedTokens = Math.ceil(summary.length / 4);
473
- const tokensSaved = Math.max(0, rawTokens - compressedTokens);
474
- if (!forceCompress && minTokensSaved > 0 && tokensSaved < Number(minTokensSaved)) {
475
- return {
476
- compressed: false,
477
- failOpen: false,
478
- dbPath: resolvedDbPath,
479
- output: rawStr,
480
- lineCount: rawLines.length,
481
- rawTokens,
482
- compressedTokens: rawTokens,
483
- tokensSaved: 0,
484
- reductionPct: 0,
485
- turnId: String(turnId),
486
- queryHandle: null
487
- };
488
- }
489
- const reductionPct = rawTokens > 0 ? Number(((tokensSaved / rawTokens) * 100).toFixed(1)) : 0;
490
-
491
- if (recordLedger && tokensSaved > 0 && !DatabaseSync) {
492
- try {
493
- recordInterventionSavings(
494
- {
495
- sessionId: String(sessionId),
496
- turnId: String(turnId),
497
- dedupeId: `fts5:${sessionId}:${turnId}:${command}`,
498
- category: 'CLI_FTS5_COMPRESSED',
499
- savedTokens: tokensSaved,
500
- detail: `FTS5 compressed "${String(command).slice(0, 60)}" (${rawLines.length} -> ${summaryLines.length} lines)`
501
- },
502
- { homeDir, ledgerPath }
503
- );
504
- } catch (err) {
505
- void err; // ignore: best-effort ledger telemetry must never break fail-open compression
506
- }
507
- }
508
-
509
- return {
510
- compressed: true,
511
- failOpen: false,
512
- dbPath: resolvedDbPath,
513
- output: summary,
514
- lineCount: summaryLines.length,
515
- rawLineCount: rawLines.length,
516
- rawTokens,
517
- compressedTokens,
518
- tokensSaved,
519
- reductionPct,
520
- turnId: String(turnId),
521
- queryHandle: `npx burnoff search ${turnId} "<keyword>"`,
522
- recallCommand: `npx burnoff search ${turnId} "<keyword>"`
523
- };
524
- } catch (err) {
525
- return {
526
- compressed: false,
527
- failOpen: true,
528
- error: String(err?.message || err),
529
- output: rawStr,
530
- lineCount: rawLines.length,
531
- rawTokens,
532
- compressedTokens: rawTokens,
533
- tokensSaved: 0,
534
- reductionPct: 0,
535
- turnId: String(turnId),
536
- queryHandle: null
537
- };
538
- } finally {
539
- try {
540
- if (db) db.close();
541
- } catch (closeErr) {
542
- void closeErr; // ignore: db close guard
543
- }
544
- }
545
- }
546
-
547
- export async function compressCliOutputFts5(options = {}) {
548
- return compressCliOutputFts5Sync(options);
549
- }
550
-
551
- export async function compressToolOutputWithFts5(options = {}) {
552
- return compressCliOutputFts5Sync(options);
553
- }
554
-
555
- /**
556
- * Prunes FTS5 `tool_logs` entries older than `retentionDays` at most once per 24 hours.
557
- * Runs `VACUUM` automatically when `deletedRows >= 500`.
558
- */
559
- export function pruneExpiredFts5LogsSync(
560
- db,
561
- nowMs = Date.now(),
562
- retentionDays = 30,
563
- options = {}
564
- ) {
565
- if (!db || typeof db.exec !== 'function' || typeof db.prepare !== 'function') {
566
- return { skipped: true, deletedRows: 0, vacuumed: false };
567
- }
568
- db.exec(`
569
- CREATE TABLE IF NOT EXISTS tool_logs_meta (
570
- key TEXT PRIMARY KEY,
571
- value TEXT NOT NULL
572
- );
573
- `);
574
-
575
- const metaRow = db.prepare("SELECT value FROM tool_logs_meta WHERE key = 'last_prune_ms'").get();
576
- const lastPruneMs = metaRow ? Number(metaRow.value) : 0;
577
- if (!options.force && Number.isFinite(lastPruneMs) && lastPruneMs > 0 && nowMs - lastPruneMs < 86_400_000) {
578
- return { skipped: true, deletedRows: 0, vacuumed: false };
579
- }
580
-
581
- const cutoffMs = nowMs - Math.max(1, Number(retentionDays || 30)) * 86_400_000;
582
- const cutoffIso = new Date(cutoffMs).toISOString();
583
- const res = db.prepare('DELETE FROM tool_logs WHERE created_at < ?').run(cutoffIso);
584
- const deletedRows = Number(res?.changes || 0);
585
-
586
- db.prepare("INSERT OR REPLACE INTO tool_logs_meta (key, value) VALUES ('last_prune_ms', ?)").run(String(nowMs));
587
-
588
- let vacuumed = false;
589
- if (deletedRows >= 500) {
590
- db.exec('VACUUM');
591
- vacuumed = true;
592
- }
593
-
594
- return { skipped: false, deletedRows, vacuumed, cutoffIso };
595
- }
596
-
597
- export async function searchToolLogsFts5(dbPath, {
598
- turnId = '',
599
- keyword = '',
600
- limit = 10,
601
- homeDir = null,
602
- DatabaseSync = null
603
- } = {}) {
604
- const resolvedDbPath = dbPath || getDefaultToolLogsDbPath(homeDir);
605
- if (!fs.existsSync(resolvedDbPath) && !fs.existsSync(resolveFallbackDbPath(resolvedDbPath))) {
606
- return { hits: [], matchedLines: [] };
607
- }
608
-
609
- let db = null;
610
- try {
611
- db = openBurnoffDb(resolvedDbPath, { readOnly: true, DatabaseSync });
612
- const cleanKeyword = String(keyword || '').replace(/[^A-Za-z0-9_./:-]/g, ' ').trim();
613
- const maxLimit = Math.max(1, Number(limit) || 10);
614
- const cleanTurnId = turnId ? String(turnId) : '';
615
-
616
- let rows = [];
617
- if (cleanKeyword) {
618
- const ftsToken = cleanKeyword.split(/\s+/).filter(Boolean).map((t) => `"${t}"`).join(' AND ');
619
- if (cleanTurnId) {
620
- rows = db.prepare(`
621
- SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
622
- FROM tool_logs
623
- WHERE turn_id = ? AND tool_logs MATCH ?
624
- LIMIT ?
625
- `).all(cleanTurnId, ftsToken, maxLimit);
626
- } else {
627
- rows = db.prepare(`
628
- SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
629
- FROM tool_logs
630
- WHERE tool_logs MATCH ?
631
- LIMIT ?
632
- `).all(ftsToken, maxLimit);
633
- }
634
- } else if (cleanTurnId) {
635
- rows = db.prepare(`
636
- SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
637
- FROM tool_logs
638
- WHERE turn_id = ?
639
- LIMIT ?
640
- `).all(cleanTurnId, maxLimit);
641
- } else {
642
- rows = db.prepare(`
643
- SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
644
- FROM tool_logs
645
- LIMIT ?
646
- `).all(maxLimit);
647
- }
648
-
649
- const matchedLines = [];
650
- const kwLower = String(keyword || '').toLowerCase();
651
- for (const r of rows) {
652
- const lines = String(r.rawOutput || '').split(/\r?\n/);
653
- for (let i = 0; i < lines.length; i++) {
654
- if (!kwLower || lines[i].toLowerCase().includes(kwLower)) {
655
- matchedLines.push({
656
- turnId: r.turnId,
657
- lineNumber: i + 1,
658
- text: lines[i],
659
- source: 'tool_logs'
660
- });
661
- if (matchedLines.length >= 25) break;
662
- }
663
- }
664
- if (matchedLines.length >= 25) break;
665
- }
666
-
667
- return { hits: rows, matchedLines };
668
- } catch (err) {
669
- void err; // ignore: search failure returns empty hits
670
- return { hits: [], matchedLines: [] };
671
- } finally {
672
- try {
673
- if (db) db.close();
674
- } catch (closeErr) {
675
- void closeErr; // ignore: db close guard
676
- }
677
- }
678
- }
679
-
680
- export async function searchFts5Logs(options = {}) {
681
- const { turnId = '', keyword = '', limit = 10, dbPath = null, homeDir = null, DatabaseSync = null } = options;
682
- return searchToolLogsFts5(dbPath, { turnId, keyword, limit, homeDir, DatabaseSync });
683
- }
684
-
685
- export function getFts5CompressionStats(dbPath = null, { DatabaseSync = null, homeDir = null } = {}) {
686
- const resolvedDbPath = dbPath || getDefaultToolLogsDbPath(homeDir);
687
- if (!fs.existsSync(resolvedDbPath) && !fs.existsSync(resolveFallbackDbPath(resolvedDbPath))) {
688
- return { active: true, logCount: 0, savedTokens: 0, formattedSavedK: '0.0k' };
689
- }
690
-
691
- let db = null;
692
- try {
693
- db = openBurnoffDb(resolvedDbPath, { readOnly: true, DatabaseSync });
694
- const row = db.prepare(`
695
- SELECT count(*) as count, coalesce(sum(length(raw_output)), 0) as totalBytes
696
- FROM tool_logs
697
- `).get();
698
-
699
- const count = Number(row?.count || 0);
700
- const totalBytes = Number(row?.totalBytes || 0);
701
- const rawTokensEst = Math.ceil(totalBytes / 4);
702
- const summaryTokensEst = count * 300;
703
- const savedTokens = Math.max(0, rawTokensEst - summaryTokensEst);
704
- const formattedSavedK = `${(savedTokens / 1000).toFixed(1)}k`;
705
-
706
- return { active: true, logCount: count, savedTokens, formattedSavedK };
707
- } catch (err) {
708
- void err; // ignore: unreadable FTS5 store reports empty stats
709
- return { active: true, logCount: 0, savedTokens: 0, formattedSavedK: '0.0k' };
710
- } finally {
711
- try {
712
- if (db) db.close();
713
- } catch (closeErr) {
714
- void closeErr; // ignore: db close guard
715
- }
716
- }
717
- }
718
-
719
- export default {
720
- FTS5_COMPRESSOR_CONSTANTS,
721
- getDefaultToolLogsDbPath,
722
- isCompressibleCliCommand,
723
- classifyShellPostToolPolicy,
724
- classifyCliCommandFamily,
725
- buildDeterministicSummary,
726
- compressCliOutputFts5Sync,
727
- compressCliOutputFts5,
728
- compressToolOutputWithFts5,
729
- pruneExpiredFts5LogsSync,
730
- searchToolLogsFts5,
731
- searchFts5Logs,
732
- getFts5CompressionStats
733
- };
1
+ /**
2
+ * @file src/storage/fts5-archive.mjs
3
+ * Fail-Open CLI Output Compressor & Local SQLite FTS5 Index (`tool_logs_fts5.db`).
4
+ *
5
+ * Strictly FAIL-OPEN: if any exception occurs during SQLite indexing or parsing,
6
+ * returns the raw output untouched so builds and test workflows never break.
7
+ */
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { getHomeDir, getBurnoffCacheDir } from '../config/paths.mjs';
12
+ import { openBurnoffDb, resolveFallbackDbPath } from './sqlite-client.mjs';
13
+ import { recordInterventionSavings } from './ledger.mjs';
14
+ import { redactSecretsPure } from '../guards/credential-scrubber.mjs';
15
+
16
+ export const FTS5_COMPRESSOR_CONSTANTS = Object.freeze({
17
+ MIN_LINES_TO_COMPRESS: 40,
18
+ MIN_BYTES_TO_COMPRESS: 4096,
19
+ MAX_SUMMARY_LINES: 25,
20
+ TARGET_COMMAND_REGEX:
21
+ /(?:(?:^|[\s;|&])@['"]|\b(?:pytest|jest|vitest|cargo\s+(?:test|clippy|check|build)|tsc|go\s+test|eslint|biome|ruff|next\s+build|vite\s+build|(?:mvn|mvnw(?:\.cmd)?|gradle|gradlew(?:\.bat)?|kotlinc)\b|dotnet\s+(?:test|build)\b|make\b|ctest\b|bazel\s+(?:test|build)\b|(?:(?:npx|pnpm(?:\s+exec)?)\s+)?playwright\s+test\b|(?:bundle\s+exec\s+)?rspec\b|phpunit\b|deno\s+test\b|docker\s+(?:build|logs)|kubectl\s+(?:logs|get|describe)|gh\s+(?:pr|run|api|issue|release|workflow)|git\s+(?:diff|log|show|status|grep|ls-files|blame|branch|tag|stash|reflog|cherry-pick)|(?:npm|pnpm|yarn|bun)\s+(?:test|run\s+(?:test|lint|build|typecheck)|install|ci|add|update|audit|outdated|pack|publish)|(?:pip3?|uv|poetry)\s+(?:install|sync|audit|list|show)|node(?:\.exe)?|python3?(?:\.exe)?|select-string|get-childitem|gci|get-content|write-output|powershell|pwsh|rg|ripgrep|grep|find|fd|tree|curl|wget|aws|gcloud|terraform)\b)/i
22
+ });
23
+
24
+ export function getDefaultToolLogsDbPath(homeDir = null) {
25
+ return path.join(getBurnoffCacheDir(homeDir), 'tool_logs_fts5.db');
26
+ }
27
+
28
+ export function isCompressibleCliCommand(command = '') {
29
+ return FTS5_COMPRESSOR_CONSTANTS.TARGET_COMMAND_REGEX.test(String(command || ''));
30
+ }
31
+
32
+ const POWERSHELL_HEREDOC_OR_SEARCH_RE =
33
+ /(?:(?:^|[\s;|&])@['"]|\b(?:select-string|get-childitem|gci)\b)/i;
34
+ const BOUNDED_PIPE_FILTER_RE =
35
+ /\|\s*(?:head|tail|sed|awk|cut|wc|grep|egrep|fgrep|rg|ripgrep|jq)\b/i;
36
+ const INLINE_SCRIPT_OR_HEREDOC_RE =
37
+ /\b(?:node(?:\.exe)?\s+(?:-[ep]\b|--eval\b|--print\b)|python3?(?:\.exe)?\s+(?:-c\b|-\s*<<|<<))|\bcat\s*>\s*\S+[\s\S]*<</i;
38
+ const FILE_INSPECTION_SEGMENT_RE =
39
+ /^\s*(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)*(?:(?:\/[\w./-]+)?\/)?(?:cat|head|tail|sed|awk|cut|wc|nl|tac|rev|less|more|bat|jq|stat|file(?=\s+\S)|ls|dir|tree|grep|egrep|fgrep|rg|ripgrep|get-content)(?=\s|$)(?![.\w-])/i;
40
+ const GIT_INSPECTION_CMD_RE = /\bgit\s+(?:diff|show|status|blame|log)\b/i;
41
+ const NOISY_PRIMARY_RUNNER_RE =
42
+ /\b(?:(?:npm|pnpm|yarn|bun)\s+(?:test|install|ci|run|build|lint|typecheck)|node\s+--test|pytest|jest|vitest|cargo|go\s+test|tsc|eslint|biome|ruff|next\s+build|vite\s+build|mvn|mvnw|gradle|gradlew|kotlinc|dotnet\s+(?:test|build)|make|ctest|bazel\s+(?:test|build)|playwright\s+test|rspec|phpunit|deno\s+test|docker|kubectl)\b/i;
43
+
44
+ export function classifyShellPostToolPolicy(command = '') {
45
+ const cmd = String(command || '').trim();
46
+ if (!cmd) {
47
+ return { allowFts5: false, allowOffload: true, reason: 'empty_command' };
48
+ }
49
+ if (BOUNDED_PIPE_FILTER_RE.test(cmd)) {
50
+ return { allowFts5: false, allowOffload: false, reason: 'explicitly_bounded_shell_output' };
51
+ }
52
+ const segments = cmd.split(/(?:&&|\|\||;|\||\r?\n)/);
53
+ const hasInspectionSegment = segments.some((seg) => FILE_INSPECTION_SEGMENT_RE.test(seg));
54
+ if (POWERSHELL_HEREDOC_OR_SEARCH_RE.test(cmd) && !hasInspectionSegment) {
55
+ return { allowFts5: true, allowOffload: true, reason: 'eligible_powershell_cli' };
56
+ }
57
+ if (INLINE_SCRIPT_OR_HEREDOC_RE.test(cmd)) {
58
+ return { allowFts5: false, allowOffload: false, reason: 'inline_script_or_heredoc' };
59
+ }
60
+ if (hasInspectionSegment) {
61
+ return { allowFts5: false, allowOffload: false, reason: 'file_inspection_shell_command' };
62
+ }
63
+ if (GIT_INSPECTION_CMD_RE.test(cmd) && !NOISY_PRIMARY_RUNNER_RE.test(cmd)) {
64
+ return { allowFts5: false, allowOffload: false, reason: 'git_inspection_command' };
65
+ }
66
+ return { allowFts5: true, allowOffload: true, reason: 'eligible_cli_output' };
67
+ }
68
+
69
+ export function classifyCliCommandFamily(command = '') {
70
+ const cmd = String(command || '').toLowerCase();
71
+ if (/\bgit\s+(diff|log|show|status)\b/.test(cmd)) return 'git';
72
+ if (/\b(docker|kubectl)\b/.test(cmd) || /\bgh\s+(pr|run)\b/.test(cmd)) return 'infra';
73
+ if (
74
+ /\b(pytest|jest|vitest|cargo\s+test|node\s+--test|(?:npm|pnpm|yarn|bun)\s+(?:test|run\s+(?:test|lint|build|typecheck))|go\s+test|(?:mvn|mvnw(?:\.cmd)?)\s+[^\n]*(?:test|verify)|(?:gradle|gradlew(?:\.bat)?)\s+[^\n]*(?:test|check)|dotnet\s+test|bazel\s+test|playwright\s+test|rspec|phpunit|deno\s+test|ctest|make\s+(?:test|check))\b/.test(
75
+ cmd
76
+ )
77
+ ) {
78
+ return 'test';
79
+ }
80
+ if (
81
+ /\b(eslint|biome|ruff|tsc|cargo\s+(clippy|check|build)|next\s+build|vite\s+build|mvn|mvnw(?:\.cmd)?|gradle|gradlew(?:\.bat)?|kotlinc|dotnet\s+build|bazel\s+build|make)\b/.test(
82
+ cmd
83
+ )
84
+ ) {
85
+ return 'lint_build';
86
+ }
87
+ if (
88
+ /\b(select-string|get-childitem|gci|rg|ripgrep|grep|find|fd|tree)\b/.test(cmd) ||
89
+ /\bgit\s+(grep|ls-files)\b/.test(cmd)
90
+ ) {
91
+ return 'search_list';
92
+ }
93
+ if (/\bgh\b/.test(cmd) && !/\bgh\s+(api|issue|release|workflow)\b/.test(cmd)) return 'infra';
94
+ return 'generic_cli';
95
+ }
96
+
97
+ function pushUniqueBounded(arr, item, maxLen, sliceLen = 140) {
98
+ const cleaned = String(item || '').trim().slice(0, sliceLen);
99
+ if (!cleaned || arr.includes(cleaned) || arr.length >= maxLen) return;
100
+ arr.push(cleaned);
101
+ }
102
+
103
+ export function buildDeterministicSummary(rawOutput = '', {
104
+ command = 'pytest',
105
+ exitCode = 1,
106
+ turnId = 'turn-1',
107
+ maxLines = FTS5_COMPRESSOR_CONSTANTS.MAX_SUMMARY_LINES
108
+ } = {}) {
109
+ const lines = String(rawOutput || '').split(/\r?\n/);
110
+ const family = classifyCliCommandFamily(command);
111
+ const queryHandleLine = `FTS5 Query Handle: npx burnoff search ${turnId} "<keyword>" (full output archived; do not re-run)`;
112
+
113
+ if (family === 'git') {
114
+ const fileHeaders = [];
115
+ const hunksOrMeta = [];
116
+ const conflictsOrErrors = [];
117
+ for (const rawLine of lines) {
118
+ const line = rawLine.trim();
119
+ if (!line) continue;
120
+ if (/^(diff --git |\+\+\+ [ab]\/|--- [ab]\/|commit [0-9a-f]{7,})/.test(line)) {
121
+ pushUniqueBounded(fileHeaders, line, 10);
122
+ } else if (/^\s*(M|A|D|R\d*|C\d*|UU|\?\?)\s+\S+/.test(rawLine)) {
123
+ pushUniqueBounded(fileHeaders, line, 10);
124
+ } else if (/^@@\s+.*\s+@@/.test(line) || /^(\d+\s+files?\s+changed|[\w./-]+\s+\|\s+\d+)/.test(line)) {
125
+ pushUniqueBounded(hunksOrMeta, line, 8);
126
+ } else if (/^(<{7}|={7}|>{7}|error:|fatal:)/i.test(line)) {
127
+ pushUniqueBounded(conflictsOrErrors, line, 4);
128
+ }
129
+ }
130
+ const out = [
131
+ `[FTS5 Compressed CLI Output] cmd="${command}" exit_code=${exitCode} raw_lines=${lines.length}`,
132
+ `Git Files & Hunks (${fileHeaders.length} files, ${hunksOrMeta.length} hunks):`
133
+ ];
134
+ for (const f of fileHeaders) out.push(` ${f}`);
135
+ for (const h of hunksOrMeta) out.push(` ${h}`);
136
+ for (const c of conflictsOrErrors) out.push(` ${c}`);
137
+ if (out.length <= 2) {
138
+ for (const tailLine of lines.slice(-6)) {
139
+ if (tailLine.trim()) out.push(` ${tailLine.trim().slice(0, 140)}`);
140
+ }
141
+ }
142
+ const bounded = out.slice(0, Math.max(1, maxLines - 1));
143
+ bounded.push(queryHandleLine);
144
+ return bounded.slice(0, maxLines).join('\n');
145
+ }
146
+
147
+ if (family === 'infra') {
148
+ const errors = [];
149
+ const stages = [];
150
+ for (const rawLine of lines) {
151
+ const line = rawLine.trim();
152
+ if (!line) continue;
153
+ if (/\b(ERROR|FATAL|panic:|CrashLoopBackOff|ImagePullBackOff|ErrImagePull|OOMKilled|FAILED|fail)\b/i.test(line) || /^[✗✖X]\s+/.test(line)) {
154
+ pushUniqueBounded(errors, line, 12);
155
+ } else if (/^(#\d+\s+(?:DONE|ERROR)|Step\s+\d+\/\d+|NAME\s+READY|Successfully\s+(?:built|tagged))/i.test(line)) {
156
+ pushUniqueBounded(stages, line, 6);
157
+ }
158
+ }
159
+ const out = [
160
+ `[FTS5 Compressed CLI Output] cmd="${command}" exit_code=${exitCode} raw_lines=${lines.length}`,
161
+ `Infra & Deploy Diagnostics (${errors.length} error(s), ${stages.length} stage(s)):`
162
+ ];
163
+ for (const e of errors) out.push(` ${e}`);
164
+ for (const s of stages) out.push(` ${s}`);
165
+ if (errors.length === 0 && stages.length === 0) {
166
+ for (const tailLine of lines.slice(-6)) {
167
+ if (tailLine.trim()) out.push(` ${tailLine.trim().slice(0, 140)}`);
168
+ }
169
+ }
170
+ const bounded = out.slice(0, Math.max(1, maxLines - 1));
171
+ bounded.push(queryHandleLine);
172
+ return bounded.slice(0, maxLines).join('\n');
173
+ }
174
+
175
+ if (family === 'search_list') {
176
+ const groups = new Map();
177
+ const samples = [];
178
+ const errors = [];
179
+ for (const rawLine of lines) {
180
+ const line = rawLine.trim();
181
+ if (!line) continue;
182
+ if (/\b(ERROR|FATAL|Exception|AccessDenied|UnauthorizedAccess)\b/i.test(line)) {
183
+ pushUniqueBounded(errors, line, 4, 140);
184
+ continue;
185
+ }
186
+ const grepMatch = line.match(/^((?:[A-Za-z]:)?[./\\\w-]+?\.[a-zA-Z0-9]{1,8}):(\d+):(.*)$/);
187
+ if (grepMatch) {
188
+ const key = grepMatch[1];
189
+ if (!groups.has(key)) groups.set(key, { count: 0, first: `L${grepMatch[2]}: ${grepMatch[3].trim()}` });
190
+ groups.get(key).count += 1;
191
+ } else {
192
+ pushUniqueBounded(samples, line, 12, 140);
193
+ }
194
+ }
195
+ const rawBytes = Buffer.byteLength(String(rawOutput || ''), 'utf8');
196
+ const out = [
197
+ `[FTS5 Compressed CLI Output] cmd="${String(command).slice(0, 80)}" exit_code=${exitCode} raw_lines=${lines.length} raw_bytes=${rawBytes}`,
198
+ `Search/List Summary (${groups.size} matched file(s), ${samples.length} other line(s)):`
199
+ ];
200
+ for (const e of errors) out.push(` ! ${e}`);
201
+ let shown = 0;
202
+ for (const [fileKey, info] of groups.entries()) {
203
+ shown += 1;
204
+ if (shown > 10) {
205
+ out.push(` ... +${groups.size - 10} more matched files indexed`);
206
+ break;
207
+ }
208
+ out.push(` ${fileKey} (${info.count}): ${info.first}`.slice(0, 140));
209
+ }
210
+ if (groups.size === 0) {
211
+ for (const s of samples.slice(0, 10)) out.push(` ${s}`);
212
+ if (lines.length > 10) out.push(` ... +${lines.length - 10} more lines indexed`);
213
+ }
214
+ const bounded = out.slice(0, Math.max(1, maxLines - 1));
215
+ bounded.push(queryHandleLine);
216
+ return bounded.slice(0, maxLines).join('\n');
217
+ }
218
+
219
+ if (family === 'generic_cli') {
220
+ const errors = [];
221
+ const nonEmpty = [];
222
+ for (const rawLine of lines) {
223
+ const line = rawLine.trim();
224
+ if (!line) continue;
225
+ if (
226
+ /\b(ERROR|FATAL|WARN|WARNING|Exception|AssertionError|TypeError|ReferenceError|SyntaxError|ERR!|FAILED|fail)\b/i.test(line) ||
227
+ /^(?:ℹ\s*(?:tests|suites|pass|fail)\b|#\s*(?:tests|suites|pass|fail)\b)/i.test(line)
228
+ ) {
229
+ pushUniqueBounded(errors, line, 10, 240);
230
+ }
231
+ nonEmpty.push(line);
232
+ }
233
+ const rawBytes = Buffer.byteLength(String(rawOutput || ''), 'utf8');
234
+ const out = [
235
+ `[FTS5 Compressed CLI Output] cmd="${String(command).slice(0, 80)}" exit_code=${exitCode} raw_lines=${lines.length} raw_bytes=${rawBytes}`,
236
+ `Diagnostics & Head/Tail Preview (${errors.length} error/warn line(s)):`
237
+ ];
238
+ for (const e of errors) out.push(` ${e}`);
239
+ for (const h of nonEmpty.slice(0, 5)) pushUniqueBounded(out, ` ${h}`, maxLines - 1, 140);
240
+ if (nonEmpty.length > 5) {
241
+ for (const t of nonEmpty.slice(-5)) pushUniqueBounded(out, ` ${t}`, maxLines - 1, 140);
242
+ }
243
+ const bounded = out.slice(0, Math.max(1, maxLines - 1));
244
+ bounded.push(queryHandleLine);
245
+ return bounded.slice(0, maxLines).join('\n');
246
+ }
247
+
248
+ const failingTests = [];
249
+ const fileLineTraces = [];
250
+ const assertionLines = [];
251
+ const summaryLines = [];
252
+ const warningLines = [];
253
+
254
+ for (const rawLine of lines) {
255
+ const line = rawLine.trim();
256
+ if (!line) continue;
257
+
258
+ const isKotlinWarning = /^w:\s+/.test(line);
259
+ const isKotlinError = /^e:\s+/.test(line);
260
+
261
+ if (
262
+ /^(FAILED|FAIL|✖|✗|✘|--- FAIL:)\s+/.test(line) ||
263
+ /^[✘✖×]\s+\d+\s+/.test(line) ||
264
+ /^\d+\)\s+(?:\[[^\]]+\]\s+›\s+|\S+)/.test(line) ||
265
+ /^_{3,}\s+.+\s+_{3,}$/.test(line) ||
266
+ /^test\s+[\w:./-]+\s+\.\.\.\s+FAILED/i.test(line) ||
267
+ /^FAIL\t\S+/.test(line) ||
268
+ /^\[ERROR\]\s+(?:Failures:|Errors:|BUILD\s+FAILURE|.+<<<\s*(?:FAILURE|ERROR)!|\S+:\d+\s+)/.test(line) ||
269
+ /^>\s+Task\s+:\S+\s+FAILED/.test(line) ||
270
+ /^.+\s+>\s+.+\s+FAILED$/.test(line) ||
271
+ /^FAILURE:\s+Build\s+failed/.test(line) ||
272
+ /^Execution\s+failed\s+for\s+task\s+':\S+'/i.test(line) ||
273
+ /^Failed\s+\S+/.test(line) ||
274
+ /^make(?:\[\d+\])?:\s*\*\*\*/.test(line) ||
275
+ /^\d+\/\d+\s+Test\s+#\d+:.+\*\*\*Failed/i.test(line) ||
276
+ /^(?:FAIL|ERROR):\s+(?:\/\/)?\S+/.test(line) ||
277
+ /^rspec\s+[\w./\\-]+:\d+/.test(line) ||
278
+ /^(?:FAILURES|ERRORS)!$/.test(line) ||
279
+ /^.+\s+\.\.\.\s+FAILED\s+\(/.test(line)
280
+ ) {
281
+ const cleaned = line.replace(/^_{3,}\s*|\s*_{3,}$/g, '').trim();
282
+ pushUniqueBounded(failingTests, cleaned, 6, 160);
283
+ }
284
+
285
+ if (
286
+ /^(?:ℹ\s*(?:tests|suites|pass|fail|cancelled|skipped|todo|duration_ms)\b|#\s*(?:tests|suites|pass|fail|cancelled|skipped|todo|ok)\b|Tests?:|Test Suites?:|Test Files?:|Ran\s+\d+\s+tests?|test result:|===+\s+\d+\s+(?:passed|failed)|\d+\s+(?:passed|passing|failed|failing)\b|PASS(?:\s+\S+)?$|ok\s+\S+\s+[\d.]+s|\[(?:INFO|ERROR)\]\s+(?:Tests\s+run:\s*\d+|BUILD\s+(?:SUCCESS|FAILURE))|\d+\s+tests?\s+completed,\s*\d+\s+failed|BUILD\s+(?:SUCCESSFUL|FAILED)|(?:Failed|Passed)!\s+-\s+Failed:\s*\d+|Build\s+(?:FAILED|succeeded)|\d+%\s+tests?\s+passed,\s*\d+\s+tests?\s+failed|Executed\s+\d+\s+out\s+of\s+\d+\s+tests?:|\d+\s+examples?,\s*\d+\s+failures?|Tests:\s*\d+,\s*Assertions:\s*\d+|OK\s+\(\d+\s+tests?|(?:ok|FAILED)\s+\|\s+\d+\s+passed\s+\|\s+\d+\s+failed)/i.test(
287
+ line
288
+ )
289
+ ) {
290
+ pushUniqueBounded(summaryLines, line, 8, 200);
291
+ }
292
+
293
+ if (/\b(?:WARN|WARNING)\b[:\s]/i.test(line) || isKotlinWarning) {
294
+ pushUniqueBounded(warningLines, line, 4, 240);
295
+ }
296
+
297
+ if (
298
+ !isKotlinWarning &&
299
+ (/\b[A-Za-z0-9_./\\-]+\.(?:py|ts|tsx|js|mjs|cjs|rs|go|java|kt|kts|groovy|scala|rb|php|cs|cpp|cc|cxx|c|h|hpp)(?::\d+(?::\d+)?|\[\d+,\d+\]|(?::\s*)?\(\d+,\s*\d+\)|\s*:\s*line\s+\d+)/i.test(
300
+ line
301
+ ) ||
302
+ /\b[A-Za-z0-9_./\\-]+\.(?:ts|tsx|cs)\(\d+,\d+\):\s*error\s+(?:TS|CS)\d+/i.test(line) ||
303
+ /\bMakefile:\d+/.test(line) ||
304
+ /^\d+:\d+\s+(?:error|warning)\s+/i.test(line) ||
305
+ /\berror\[E\d+\]:/i.test(line) ||
306
+ (family === 'lint_build' && /^[A-Za-z0-9_./\\-]+\.(?:py|ts|tsx|js|mjs|cjs|rs|go|jsx|java|kt|cs|cpp|c)$/.test(line)))
307
+ ) {
308
+ pushUniqueBounded(fileLineTraces, line, 9, 180);
309
+ }
310
+
311
+ if (
312
+ isKotlinError ||
313
+ /^(E\s+|AssertionError:|Error:|Expected\b|Received\b|Actual\b|assert\s+|error\s+|Failed asserting|Caused by:|org\.junit|org\.opentest4j\.|kotlin\.test\.|java\.lang\.AssertionError|AssertionFailedError\b|Assert\.|\[ERROR\]\s+.*error:|>\s+(?:Compilation\s+error|Could\s+not\s+resolve|There\s+were\s+failing\s+tests))/i.test(
314
+ line
315
+ )
316
+ ) {
317
+ pushUniqueBounded(assertionLines, line, 5, 180);
318
+ }
319
+ }
320
+
321
+ const out = [];
322
+ out.push(`[FTS5 Compressed CLI Output] cmd="${command}" exit_code=${exitCode} raw_lines=${lines.length}`);
323
+ if (failingTests.length === 0 && Number(exitCode) === 0) {
324
+ out.push('Result: PASS (0 failing tests)');
325
+ if (warningLines.length > 0) {
326
+ out.push(`Warnings (${warningLines.length}):`);
327
+ for (const w of warningLines) out.push(` ${w}`);
328
+ }
329
+ out.push('Test Summary:');
330
+ if (summaryLines.length > 0) {
331
+ for (const s of summaryLines) out.push(` ${s}`);
332
+ } else if (fileLineTraces.length > 0) {
333
+ for (const tr of fileLineTraces.slice(0, 8)) out.push(` ${tr}`);
334
+ } else {
335
+ for (const tailLine of lines.slice(-6)) {
336
+ if (tailLine.trim()) out.push(` ${tailLine.trim().slice(0, 140)}`);
337
+ }
338
+ }
339
+ } else {
340
+ out.push(`Failing Tests (${failingTests.length}):`);
341
+ if (failingTests.length > 0) {
342
+ for (const ft of failingTests.slice(0, 6)) out.push(` - ${ft}`);
343
+ } else {
344
+ out.push(` - (No structured test header matched; see tracebacks below)`);
345
+ }
346
+
347
+ out.push(`File:Line Tracebacks & Assertions:`);
348
+ const combinedTraces = [...new Set([...fileLineTraces, ...assertionLines])].slice(summaryLines.length > 0 ? 0 : 0, summaryLines.length > 0 ? 8 : 10);
349
+ if (combinedTraces.length > 0) {
350
+ for (const tr of combinedTraces) out.push(` ${tr}`);
351
+ } else {
352
+ for (const tailLine of lines.slice(-6)) {
353
+ if (tailLine.trim()) out.push(` ${tailLine.trim().slice(0, 140)}`);
354
+ }
355
+ }
356
+ if (warningLines.length > 0) {
357
+ out.push(`Warnings (${warningLines.length}):`);
358
+ for (const w of warningLines.slice(0, 2)) out.push(` ${w}`);
359
+ }
360
+ if (summaryLines.length > 0) {
361
+ out.push('Test Summary:');
362
+ for (const s of summaryLines.slice(0, 4)) out.push(` ${s}`);
363
+ }
364
+ }
365
+
366
+ const bounded = out.slice(0, Math.max(1, maxLines - 1));
367
+ bounded.push(queryHandleLine);
368
+ return bounded.slice(0, maxLines).join('\n');
369
+ }
370
+
371
+ export function compressCliOutputFts5Sync({
372
+ sessionId = 'default-session',
373
+ turnId = 'turn-1',
374
+ command = 'pytest',
375
+ exitCode = 1,
376
+ rawOutput = '',
377
+ dbPath = null,
378
+ homeDir = getHomeDir(),
379
+ DatabaseSync = null,
380
+ forceCompress = false,
381
+ recordLedger = true,
382
+ ledgerPath = null,
383
+ minBytes = 0,
384
+ minTokensSaved = 0,
385
+ retentionDays = 30
386
+ } = {}) {
387
+ const rawStr = redactSecretsPure(String(rawOutput || '')).sanitized;
388
+ const rawLines = rawStr.split(/\r?\n/);
389
+ const rawBytes = Buffer.byteLength(rawStr, 'utf8');
390
+ const rawTokens = Math.ceil(rawStr.length / 4);
391
+ const meetsMinBytes = minBytes <= 0 || rawBytes >= Number(minBytes);
392
+ const meetsSizeThreshold =
393
+ meetsMinBytes &&
394
+ (rawLines.length > FTS5_COMPRESSOR_CONSTANTS.MIN_LINES_TO_COMPRESS ||
395
+ rawBytes >= FTS5_COMPRESSOR_CONSTANTS.MIN_BYTES_TO_COMPRESS);
396
+
397
+ if (!forceCompress && (!meetsSizeThreshold || !isCompressibleCliCommand(command))) {
398
+ return {
399
+ compressed: false,
400
+ failOpen: false,
401
+ output: rawStr,
402
+ lineCount: rawLines.length,
403
+ rawTokens,
404
+ compressedTokens: rawTokens,
405
+ tokensSaved: 0,
406
+ reductionPct: 0,
407
+ turnId,
408
+ queryHandle: null
409
+ };
410
+ }
411
+
412
+ let db = null;
413
+ try {
414
+ const resolvedDbPath = dbPath || getDefaultToolLogsDbPath(homeDir);
415
+ db = openBurnoffDb(resolvedDbPath, { readOnly: false, DatabaseSync });
416
+
417
+ db.exec(`
418
+ CREATE VIRTUAL TABLE IF NOT EXISTS tool_logs USING fts5(
419
+ session_id,
420
+ turn_id,
421
+ command,
422
+ exit_code,
423
+ raw_output,
424
+ created_at
425
+ );
426
+ CREATE TABLE IF NOT EXISTS tool_logs_meta (
427
+ key TEXT PRIMARY KEY,
428
+ value TEXT NOT NULL
429
+ );
430
+ `);
431
+
432
+ const createdAt = new Date().toISOString();
433
+ db.prepare(`
434
+ INSERT INTO tool_logs (session_id, turn_id, command, exit_code, raw_output, created_at)
435
+ VALUES (?, ?, ?, ?, ?, ?)
436
+ `).run(
437
+ String(sessionId),
438
+ String(turnId),
439
+ String(command),
440
+ String(exitCode),
441
+ rawStr,
442
+ createdAt
443
+ );
444
+
445
+ try {
446
+ pruneExpiredFts5LogsSync(db, Date.now(), Number(retentionDays ?? 30));
447
+ } catch (pruneErr) {
448
+ void pruneErr; // ignore: non-fatal background retention prune
449
+ }
450
+
451
+ const summary = buildDeterministicSummary(rawStr, {
452
+ command,
453
+ exitCode,
454
+ turnId,
455
+ maxLines: FTS5_COMPRESSOR_CONSTANTS.MAX_SUMMARY_LINES
456
+ });
457
+ if (!forceCompress && summary.length >= rawStr.length) {
458
+ return {
459
+ compressed: false,
460
+ failOpen: false,
461
+ dbPath: resolvedDbPath,
462
+ output: rawStr,
463
+ lineCount: rawLines.length,
464
+ rawTokens,
465
+ compressedTokens: rawTokens,
466
+ tokensSaved: 0,
467
+ reductionPct: 0,
468
+ turnId: String(turnId),
469
+ queryHandle: null
470
+ };
471
+ }
472
+ const summaryLines = summary.split(/\r?\n/);
473
+ const compressedTokens = Math.ceil(summary.length / 4);
474
+ const tokensSaved = Math.max(0, rawTokens - compressedTokens);
475
+ if (!forceCompress && minTokensSaved > 0 && tokensSaved < Number(minTokensSaved)) {
476
+ return {
477
+ compressed: false,
478
+ failOpen: false,
479
+ dbPath: resolvedDbPath,
480
+ output: rawStr,
481
+ lineCount: rawLines.length,
482
+ rawTokens,
483
+ compressedTokens: rawTokens,
484
+ tokensSaved: 0,
485
+ reductionPct: 0,
486
+ turnId: String(turnId),
487
+ queryHandle: null
488
+ };
489
+ }
490
+ const reductionPct = rawTokens > 0 ? Number(((tokensSaved / rawTokens) * 100).toFixed(1)) : 0;
491
+
492
+ if (recordLedger && tokensSaved > 0 && !DatabaseSync) {
493
+ try {
494
+ recordInterventionSavings(
495
+ {
496
+ sessionId: String(sessionId),
497
+ turnId: String(turnId),
498
+ dedupeId: `fts5:${sessionId}:${turnId}:${command}`,
499
+ category: 'CLI_FTS5_COMPRESSED',
500
+ savedTokens: tokensSaved,
501
+ detail: `FTS5 compressed "${String(command).slice(0, 60)}" (${rawLines.length} -> ${summaryLines.length} lines)`
502
+ },
503
+ { homeDir, ledgerPath }
504
+ );
505
+ } catch (err) {
506
+ void err; // ignore: best-effort ledger telemetry must never break fail-open compression
507
+ }
508
+ }
509
+
510
+ return {
511
+ compressed: true,
512
+ failOpen: false,
513
+ dbPath: resolvedDbPath,
514
+ output: summary,
515
+ lineCount: summaryLines.length,
516
+ rawLineCount: rawLines.length,
517
+ rawTokens,
518
+ compressedTokens,
519
+ tokensSaved,
520
+ reductionPct,
521
+ turnId: String(turnId),
522
+ queryHandle: `npx burnoff search ${turnId} "<keyword>"`,
523
+ recallCommand: `npx burnoff search ${turnId} "<keyword>"`
524
+ };
525
+ } catch (err) {
526
+ return {
527
+ compressed: false,
528
+ failOpen: true,
529
+ error: String(err?.message || err),
530
+ output: rawStr,
531
+ lineCount: rawLines.length,
532
+ rawTokens,
533
+ compressedTokens: rawTokens,
534
+ tokensSaved: 0,
535
+ reductionPct: 0,
536
+ turnId: String(turnId),
537
+ queryHandle: null
538
+ };
539
+ } finally {
540
+ try {
541
+ if (db) db.close();
542
+ } catch (closeErr) {
543
+ void closeErr; // ignore: db close guard
544
+ }
545
+ }
546
+ }
547
+
548
+ export async function compressCliOutputFts5(options = {}) {
549
+ return compressCliOutputFts5Sync(options);
550
+ }
551
+
552
+ export async function compressToolOutputWithFts5(options = {}) {
553
+ return compressCliOutputFts5Sync(options);
554
+ }
555
+
556
+ /**
557
+ * Prunes FTS5 `tool_logs` entries older than `retentionDays` at most once per 24 hours.
558
+ * Runs `VACUUM` automatically when `deletedRows >= 500`.
559
+ */
560
+ export function pruneExpiredFts5LogsSync(
561
+ db,
562
+ nowMs = Date.now(),
563
+ retentionDays = 30,
564
+ options = {}
565
+ ) {
566
+ if (!db || typeof db.exec !== 'function' || typeof db.prepare !== 'function') {
567
+ return { skipped: true, deletedRows: 0, vacuumed: false };
568
+ }
569
+ db.exec(`
570
+ CREATE TABLE IF NOT EXISTS tool_logs_meta (
571
+ key TEXT PRIMARY KEY,
572
+ value TEXT NOT NULL
573
+ );
574
+ `);
575
+
576
+ const metaRow = db.prepare("SELECT value FROM tool_logs_meta WHERE key = 'last_prune_ms'").get();
577
+ const lastPruneMs = metaRow ? Number(metaRow.value) : 0;
578
+ if (!options.force && Number.isFinite(lastPruneMs) && lastPruneMs > 0 && nowMs - lastPruneMs < 86_400_000) {
579
+ return { skipped: true, deletedRows: 0, vacuumed: false };
580
+ }
581
+
582
+ const cutoffMs = nowMs - Math.max(1, Number(retentionDays || 30)) * 86_400_000;
583
+ const cutoffIso = new Date(cutoffMs).toISOString();
584
+ const res = db.prepare('DELETE FROM tool_logs WHERE created_at < ?').run(cutoffIso);
585
+ const deletedRows = Number(res?.changes || 0);
586
+
587
+ db.prepare("INSERT OR REPLACE INTO tool_logs_meta (key, value) VALUES ('last_prune_ms', ?)").run(String(nowMs));
588
+
589
+ let vacuumed = false;
590
+ if (deletedRows >= 500) {
591
+ db.exec('VACUUM');
592
+ vacuumed = true;
593
+ }
594
+
595
+ return { skipped: false, deletedRows, vacuumed, cutoffIso };
596
+ }
597
+
598
+ export async function searchToolLogsFts5(dbPath, {
599
+ turnId = '',
600
+ keyword = '',
601
+ limit = 10,
602
+ homeDir = null,
603
+ DatabaseSync = null
604
+ } = {}) {
605
+ const resolvedDbPath = dbPath || getDefaultToolLogsDbPath(homeDir);
606
+ if (!fs.existsSync(resolvedDbPath) && !fs.existsSync(resolveFallbackDbPath(resolvedDbPath))) {
607
+ return { hits: [], matchedLines: [] };
608
+ }
609
+
610
+ let db = null;
611
+ try {
612
+ db = openBurnoffDb(resolvedDbPath, { readOnly: true, DatabaseSync });
613
+ const cleanKeyword = String(keyword || '').replace(/[^A-Za-z0-9_./:-]/g, ' ').trim();
614
+ const maxLimit = Math.max(1, Number(limit) || 10);
615
+ const cleanTurnId = turnId ? String(turnId) : '';
616
+
617
+ let rows = [];
618
+ if (cleanKeyword) {
619
+ const ftsToken = cleanKeyword.split(/\s+/).filter(Boolean).map((t) => `"${t}"`).join(' AND ');
620
+ if (cleanTurnId) {
621
+ rows = db.prepare(`
622
+ SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
623
+ FROM tool_logs
624
+ WHERE turn_id = ? AND tool_logs MATCH ?
625
+ LIMIT ?
626
+ `).all(cleanTurnId, ftsToken, maxLimit);
627
+ } else {
628
+ rows = db.prepare(`
629
+ SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
630
+ FROM tool_logs
631
+ WHERE tool_logs MATCH ?
632
+ LIMIT ?
633
+ `).all(ftsToken, maxLimit);
634
+ }
635
+ } else if (cleanTurnId) {
636
+ rows = db.prepare(`
637
+ SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
638
+ FROM tool_logs
639
+ WHERE turn_id = ?
640
+ LIMIT ?
641
+ `).all(cleanTurnId, maxLimit);
642
+ } else {
643
+ rows = db.prepare(`
644
+ SELECT session_id AS sessionId, turn_id AS turnId, command, exit_code AS exitCode, raw_output AS rawOutput, created_at AS createdAt
645
+ FROM tool_logs
646
+ LIMIT ?
647
+ `).all(maxLimit);
648
+ }
649
+
650
+ const matchedLines = [];
651
+ const kwLower = String(keyword || '').toLowerCase();
652
+ for (const r of rows) {
653
+ const lines = String(r.rawOutput || '').split(/\r?\n/);
654
+ for (let i = 0; i < lines.length; i++) {
655
+ if (!kwLower || lines[i].toLowerCase().includes(kwLower)) {
656
+ matchedLines.push({
657
+ turnId: r.turnId,
658
+ lineNumber: i + 1,
659
+ text: lines[i],
660
+ source: 'tool_logs'
661
+ });
662
+ if (matchedLines.length >= 25) break;
663
+ }
664
+ }
665
+ if (matchedLines.length >= 25) break;
666
+ }
667
+
668
+ return { hits: rows, matchedLines };
669
+ } catch (err) {
670
+ void err; // ignore: search failure returns empty hits
671
+ return { hits: [], matchedLines: [] };
672
+ } finally {
673
+ try {
674
+ if (db) db.close();
675
+ } catch (closeErr) {
676
+ void closeErr; // ignore: db close guard
677
+ }
678
+ }
679
+ }
680
+
681
+ export async function searchFts5Logs(options = {}) {
682
+ const { turnId = '', keyword = '', limit = 10, dbPath = null, homeDir = null, DatabaseSync = null } = options;
683
+ return searchToolLogsFts5(dbPath, { turnId, keyword, limit, homeDir, DatabaseSync });
684
+ }
685
+
686
+ export function getFts5CompressionStats(dbPath = null, { DatabaseSync = null, homeDir = null } = {}) {
687
+ const resolvedDbPath = dbPath || getDefaultToolLogsDbPath(homeDir);
688
+ if (!fs.existsSync(resolvedDbPath) && !fs.existsSync(resolveFallbackDbPath(resolvedDbPath))) {
689
+ return { active: true, logCount: 0, savedTokens: 0, formattedSavedK: '0.0k' };
690
+ }
691
+
692
+ let db = null;
693
+ try {
694
+ db = openBurnoffDb(resolvedDbPath, { readOnly: true, DatabaseSync });
695
+ const row = db.prepare(`
696
+ SELECT count(*) as count, coalesce(sum(length(raw_output)), 0) as totalBytes
697
+ FROM tool_logs
698
+ `).get();
699
+
700
+ const count = Number(row?.count || 0);
701
+ const totalBytes = Number(row?.totalBytes || 0);
702
+ const rawTokensEst = Math.ceil(totalBytes / 4);
703
+ const summaryTokensEst = count * 300;
704
+ const savedTokens = Math.max(0, rawTokensEst - summaryTokensEst);
705
+ const formattedSavedK = `${(savedTokens / 1000).toFixed(1)}k`;
706
+
707
+ return { active: true, logCount: count, savedTokens, formattedSavedK };
708
+ } catch (err) {
709
+ void err; // ignore: unreadable FTS5 store reports empty stats
710
+ return { active: true, logCount: 0, savedTokens: 0, formattedSavedK: '0.0k' };
711
+ } finally {
712
+ try {
713
+ if (db) db.close();
714
+ } catch (closeErr) {
715
+ void closeErr; // ignore: db close guard
716
+ }
717
+ }
718
+ }
719
+
720
+ export default {
721
+ FTS5_COMPRESSOR_CONSTANTS,
722
+ getDefaultToolLogsDbPath,
723
+ isCompressibleCliCommand,
724
+ classifyShellPostToolPolicy,
725
+ classifyCliCommandFamily,
726
+ buildDeterministicSummary,
727
+ compressCliOutputFts5Sync,
728
+ compressCliOutputFts5,
729
+ compressToolOutputWithFts5,
730
+ pruneExpiredFts5LogsSync,
731
+ searchToolLogsFts5,
732
+ searchFts5Logs,
733
+ getFts5CompressionStats
734
+ };