burnoff 1.4.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,854 +1,875 @@
1
- /**
2
- * @file src/guards/post-tool-engine.mjs
3
- * Pure ESM orchestrator for Claude Code `PostToolUse` evaluation.
4
- * Atomically updates `DET-04` failure counters and `git stash` timestamps, strips ANSI/spinners,
5
- * compresses eligible CLI logs via SQLite FTS5 (`npx burnoff search`), offloads >4,000-token blobs
6
- * while preserving 100% of critical error lines, and replaces tool outputs in native host shapes.
7
- */
8
-
9
- import fs from 'node:fs';
10
- import path from 'node:path';
11
- import crypto from 'node:crypto';
12
- import { getClientAdapter, normalizeHookEvent } from '../clients/detect.mjs';
13
- import { loadBurnoffPolicy } from '../config/policy.mjs';
14
- import { getBurnoffCacheDir, getHomeDir } from '../config/paths.mjs';
15
- import { computeTotalPromptTokens, resolveEffectiveRates } from '../config/loader.mjs';
16
- import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
17
- import {
18
- compressCliOutputFts5Sync,
19
- classifyShellPostToolPolicy,
20
- getDefaultToolLogsDbPath
21
- } from '../storage/fts5-archive.mjs';
22
- import { recordSavingsReceipt, rotateMonthlyLedger, LEDGER_BUCKETS } from '../storage/ledger.mjs';
23
- import { recordToolOutcomeAtomicSync, releaseScopeLock } from './loop-breaker.mjs';
24
-
25
- export const OFFLOAD_TOKEN_THRESHOLD = 4000;
26
- export const CHARS_PER_TOKEN_ESTIMATE = 4;
27
- export const DEFAULT_ARTIFACT_MAX_FILES = 200;
28
- export const DEFAULT_ARTIFACT_MAX_TOTAL_BYTES = 50 * 1024 * 1024;
29
- export const OPPORTUNISTIC_GC_INTERVAL_MS = 24 * 60 * 60 * 1000;
30
-
31
- export const CRITICAL_ERROR_REGEX =
32
- /(Error|Exception|FAIL|error\[E\d+\]|panic:|ERR!|ERESOLVE|AssertionError|SyntaxError)/i;
33
-
34
- const ANSI_CSI_OSC_REGEX =
35
- /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
36
-
37
- const DOWNLOAD_NOISE_LINE_REGEX =
38
- /^\s*(?:npm\s+(?:http|verb|silly|timing|notice)\b|Progress:\s+resolved\s+\d+|Downloading\s+\S+\s+\[[=#>-]+\s*\]|\d+%\s+\[[=#>-]+\s*\]|Receiving objects:\s+\d+%|Resolving deltas:\s+\d+%)/i;
39
-
40
- const PASSING_TEST_LINE_REGEX =
41
- /^\s*(?:✔|✓|PASS\s+\S+|ok\s+\d+\s+-\s+)/;
42
-
43
- const HTML_BOILERPLATE_BLOCK_REGEX =
44
- /<(nav|footer|script|style|svg|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi;
45
-
46
- const SHELL_TOOL_NAME_RE = /^(?:Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash)$/i;
47
- const PROTECTED_WORKSPACE_TOOL_RE =
48
- /^(?:Read|read_file|view_file|View|Edit|edit_file|Write|write_file|replace_file_content|MultiEdit|NotebookEdit)$/i;
49
- const EDIT_WRITE_SCOPE_LOCK_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit)$/i;
50
- const ELIGIBLE_POST_TOOL_RE =
51
- /^(?:Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash|WebFetch|Grep|Glob|Task|Agent|mcp__.+)$/i;
52
-
53
- export function stripAnsiAndSpinners(rawText = '') {
54
- const withoutAnsi = String(rawText || '').replace(ANSI_CSI_OSC_REGEX, '');
55
- const lines = withoutAnsi.split(/\n/);
56
- const resolvedLines = lines.map((line) => {
57
- const trimmedCr = line.replace(/\r$/, '');
58
- if (!trimmedCr.includes('\r')) return trimmedCr;
59
- const segments = trimmedCr.split('\r').filter((seg) => seg.trim().length > 0);
60
- return segments.length > 0 ? segments[segments.length - 1] : '';
61
- });
62
- return resolvedLines.join('\n');
63
- }
64
-
65
- export function extractCriticalErrorLines(cleanText = '') {
66
- return String(cleanText || '')
67
- .split(/\r?\n/)
68
- .filter((line) => CRITICAL_ERROR_REGEX.test(line));
69
- }
70
-
71
- export function extractPostToolText(event = {}) {
72
- const resp = event.tool_response ?? event.tool_output ?? event.toolOutput ?? event.output;
73
- if (typeof resp === 'string') return resp;
74
- if (resp && typeof resp === 'object') {
75
- if (Array.isArray(resp.content)) {
76
- const blockText = resp.content
77
- .filter((b) => b && b.type === 'text' && typeof b.text === 'string' && b.text.length > 0)
78
- .map((b) => b.text)
79
- .join('\n');
80
- if (blockText.length > 0) return blockText;
81
- }
82
- const parts = [resp.stdout, resp.stderr, resp.output, resp.content, resp.result, resp.error]
83
- .filter((x) => typeof x === 'string' && x.length > 0);
84
- if (parts.length > 0) return parts.join('\n');
85
- for (const arrKey of ['filenames', 'files']) {
86
- if (
87
- Array.isArray(resp[arrKey]) &&
88
- resp[arrKey].length > 0 &&
89
- resp[arrKey].every((item) => typeof item === 'string')
90
- ) {
91
- return resp[arrKey].join('\n');
92
- }
93
- }
94
- return '';
95
- }
96
- return resp !== undefined && resp !== null ? String(resp) : '';
97
- }
98
-
99
- /**
100
- * Builds a replacement `tool_response` in the exact shape the host sent (`updatedToolOutput`).
101
- * Returns `{ ok: false }` for unrecognized object shapes so no phantom savings are recorded.
102
- */
103
- export function buildReplacementToolOutput(event = {}, finalOutput = '') {
104
- const resp = event.tool_response ?? event.tool_output ?? event.toolOutput ?? event.output;
105
- if (typeof resp === 'string') return { ok: true, value: finalOutput };
106
- if (resp && typeof resp === 'object' && !Array.isArray(resp)) {
107
- if (Array.isArray(resp.content)) {
108
- const hasTextBlock = resp.content.some((b) => b && b.type === 'text' && typeof b.text === 'string');
109
- const hasNonTextBlock = resp.content.some((b) => !b || b.type !== 'text');
110
- if (hasTextBlock && !hasNonTextBlock) {
111
- return { ok: true, value: { ...resp, content: [{ type: 'text', text: finalOutput }] } };
112
- }
113
- }
114
- const textKeys = ['stdout', 'output', 'content', 'result', 'error', 'stderr'];
115
- const primary = textKeys.find((k) => typeof resp[k] === 'string' && resp[k].length > 0);
116
- if (primary) {
117
- const next = { ...resp };
118
- for (const k of textKeys) {
119
- if (typeof next[k] === 'string') next[k] = k === primary ? finalOutput : '';
120
- }
121
- if (primary === 'content' && typeof next.numLines === 'number') {
122
- next.numLines = finalOutput ? String(finalOutput).split(/\r?\n/).length : 0;
123
- }
124
- return { ok: true, value: next };
125
- }
126
- const arrayKeys = ['filenames', 'files'];
127
- const primaryArr = arrayKeys.find(
128
- (k) => Array.isArray(resp[k]) && resp[k].length > 0 && resp[k].every((item) => typeof item === 'string')
129
- );
130
- if (primaryArr) {
131
- const nextItems = String(finalOutput || '')
132
- .split(/\r?\n/)
133
- .map((line) => line.trimEnd())
134
- .filter((line) => line.length > 0);
135
- const next = { ...resp, [primaryArr]: nextItems };
136
- if (typeof next.numFiles === 'number') {
137
- const pathCount = nextItems.filter((line) => !/^\[/.test(line.trim())).length;
138
- next.numFiles = pathCount > 0 ? pathCount : nextItems.length;
139
- }
140
- if (typeof next.truncated === 'boolean') {
141
- next.truncated = true;
142
- }
143
- return { ok: true, value: next };
144
- }
145
- return { ok: false };
146
- }
147
- return { ok: false };
148
- }
149
-
150
- function resolveHostShellOutputCap() {
151
- const n = Number(globalThis.process?.env?.BASH_MAX_OUTPUT_LENGTH);
152
- return Number.isFinite(n) && n > 0 ? n : 30_000;
153
- }
154
-
155
- export function isHostTruncatedShellOutput(toolName, rawOutput) {
156
- if (!/^(?:Bash|PowerShell)$/i.test(String(toolName || ''))) return false;
157
- return String(rawOutput || '').length >= resolveHostShellOutputCap() - 100;
158
- }
159
-
160
- export function didToolExecutionFail(event = {}, toolNameHint = '') {
161
- const hookEventName = String(event.hook_event_name || event.hookEventName || '');
162
- if (hookEventName === 'PostToolUseFailure') {
163
- return true;
164
- }
165
- if (
166
- event.is_error === true ||
167
- event.isError === true ||
168
- event.succeeded === false ||
169
- Boolean(event.tool_error || event.error) ||
170
- (typeof event.exit_code === 'number' && event.exit_code !== 0) ||
171
- (typeof event.exitCode === 'number' && event.exitCode !== 0)
172
- ) {
173
- return true;
174
- }
175
- const resp = event.tool_response;
176
- if (resp && typeof resp === 'object') {
177
- if (
178
- resp.is_error === true ||
179
- resp.isError === true ||
180
- resp.succeeded === false ||
181
- resp.status === 'error' ||
182
- resp.status === 'failed' ||
183
- Boolean(resp.error) ||
184
- (typeof resp.exit_code === 'number' && resp.exit_code !== 0) ||
185
- (typeof resp.exitCode === 'number' && resp.exitCode !== 0) ||
186
- (typeof resp.returncode === 'number' && resp.returncode !== 0)
187
- ) {
188
- return true;
189
- }
190
- }
191
-
192
- const rawTool = String(
193
- toolNameHint || event.tool_name || event.toolName || event.toolCall?.name || event.name || ''
194
- ).trim();
195
- const isShellLike =
196
- !rawTool || SHELL_TOOL_NAME_RE.test(rawTool) || /^(?:Shell|Command)$/i.test(rawTool);
197
- if (isShellLike) {
198
- const rawText = stripAnsiAndSpinners(extractPostToolText(event));
199
- if (rawText) {
200
- const exitMarkerRe =
201
- /(?:^|\r?\n)\s*(?:exit\s+(?:code|status)|command\s+exited\s+with\s+(?:code|status)|process\s+exited\s+with\s+(?:code|status)|returned\s+non-zero\s+exit\s+status)\s*[:=]?\s*(-?\d+)\b/gim;
202
- for (const m of rawText.matchAll(exitMarkerRe)) {
203
- const code = Number(m[1]);
204
- if (Number.isFinite(code) && code !== 0) {
205
- return true;
206
- }
207
- }
208
- }
209
- }
210
- return false;
211
- }
212
-
213
- function resolvePostOutputMode(policyPost = {}) {
214
- const envRaw = String(globalThis.process?.env?.BURNOFF_POST_OUTPUT_MODE || '').trim().toLowerCase();
215
- if (envRaw === 'context' || envRaw === 'additionalcontext') return 'context';
216
- if (envRaw === 'replace' || envRaw === 'updatedtooloutput') return 'replace';
217
- if (envRaw === 'auto') return 'auto';
218
- const cfgMode = String(policyPost.outputMode || 'auto').trim().toLowerCase();
219
- if (cfgMode === 'context' || cfgMode === 'additionalcontext') return 'context';
220
- if (cfgMode === 'replace' || cfgMode === 'updatedtooloutput') return 'replace';
221
- return 'auto';
222
- }
223
-
224
- export function enforceArtifactDirCap(
225
- artifactsDir,
226
- {
227
- maxFiles = DEFAULT_ARTIFACT_MAX_FILES,
228
- maxTotalBytes = DEFAULT_ARTIFACT_MAX_TOTAL_BYTES,
229
- keepPath = null
230
- } = {}
231
- ) {
232
- if (!artifactsDir || !fs.existsSync(artifactsDir)) {
233
- return { removedFiles: 0, reclaimedBytes: 0 };
234
- }
235
- const keepAbs = keepPath ? path.resolve(keepPath) : null;
236
- let entries;
237
- try {
238
- entries = fs.readdirSync(artifactsDir, { withFileTypes: true });
239
- } catch (err) {
240
- void err; // ignore: unreadable artifacts dir skips cap
241
- return { removedFiles: 0, reclaimedBytes: 0 };
242
- }
243
-
244
- const files = [];
245
- let totalBytes = 0;
246
- for (const ent of entries) {
247
- if (!ent.isFile() || !/^burnoff_.*\.txt$/i.test(ent.name)) continue;
248
- const full = path.join(artifactsDir, ent.name);
249
- try {
250
- const st = fs.statSync(full);
251
- files.push({ full, abs: path.resolve(full), mtimeMs: st.mtimeMs || 0, size: st.size || 0 });
252
- totalBytes += st.size || 0;
253
- } catch (err) {
254
- void err; // ignore: vanished artifact entry skipped
255
- }
256
- }
257
-
258
- if (files.length <= maxFiles && totalBytes <= maxTotalBytes) {
259
- return { removedFiles: 0, reclaimedBytes: 0 };
260
- }
261
-
262
- files.sort((a, b) => a.mtimeMs - b.mtimeMs);
263
- let remainingFiles = files.length;
264
- let remainingBytes = totalBytes;
265
- let removedFiles = 0;
266
- let reclaimedBytes = 0;
267
-
268
- for (const f of files) {
269
- if (remainingFiles <= maxFiles && remainingBytes <= maxTotalBytes) break;
270
- if (keepAbs && f.abs === keepAbs) continue;
271
- try {
272
- fs.unlinkSync(f.full);
273
- remainingFiles -= 1;
274
- remainingBytes -= f.size;
275
- removedFiles += 1;
276
- reclaimedBytes += f.size;
277
- } catch (err) {
278
- void err; // ignore: locked or already removed artifact
279
- }
280
- }
281
-
282
- return { removedFiles, reclaimedBytes };
283
- }
284
-
285
- function reapStaleFilesInDir(dirPath, cutoffMs, skipNames = new Set()) {
286
- if (!dirPath || !fs.existsSync(dirPath)) {
287
- return { removedFiles: 0, reclaimedBytes: 0 };
288
- }
289
- let entries;
290
- try {
291
- entries = fs.readdirSync(dirPath, { withFileTypes: true });
292
- } catch (err) {
293
- void err; // ignore: unreadable cache directory
294
- return { removedFiles: 0, reclaimedBytes: 0 };
295
- }
296
- let removedFiles = 0;
297
- let reclaimedBytes = 0;
298
- for (const ent of entries) {
299
- if (!ent.isFile()) continue;
300
- if (
301
- skipNames.has(ent.name) ||
302
- ent.name.startsWith('tool_logs_fts5.db') ||
303
- ent.name.startsWith('tool_logs_fallback.json')
304
- ) {
305
- continue;
306
- }
307
- const full = path.join(dirPath, ent.name);
308
- try {
309
- const st = fs.statSync(full);
310
- if (st.mtimeMs < cutoffMs) {
311
- fs.unlinkSync(full);
312
- removedFiles += 1;
313
- reclaimedBytes += st.size;
314
- }
315
- } catch (err) {
316
- void err; // ignore: locked or concurrently unlinked cache file
317
- }
318
- }
319
- return { removedFiles, reclaimedBytes };
320
- }
321
-
322
- /**
323
- * Throttled (<= 1x per 24h) cache reap, artifact cap enforcement, and monthly ledger rotation.
324
- */
325
- export function runOpportunisticPostToolGc({
326
- baseCwd = null,
327
- homeDir = null,
328
- maxCacheAgeDays = 14,
329
- nowMs = Date.now(),
330
- force = false,
331
- artifactMaxFiles = DEFAULT_ARTIFACT_MAX_FILES,
332
- artifactMaxBytes = DEFAULT_ARTIFACT_MAX_TOTAL_BYTES
333
- } = {}) {
334
- const cacheDir = getBurnoffCacheDir(homeDir);
335
- const stampPath = path.join(cacheDir, 'burnoff_last_gc.json');
336
- const skipNames = new Set(['burnoff_last_gc.json']);
337
-
338
- if (!force && fs.existsSync(stampPath)) {
339
- try {
340
- const raw = JSON.parse(fs.readFileSync(stampPath, 'utf8'));
341
- const lastGcMs = Number(raw?.lastGcMs || 0);
342
- if (lastGcMs > 0 && nowMs - lastGcMs < OPPORTUNISTIC_GC_INTERVAL_MS) {
343
- return { skipped: true, reason: 'throttled_24h', lastGcMs };
344
- }
345
- } catch (err) {
346
- void err; // ignore: corrupt stamp file falls through to run GC
347
- }
348
- }
349
-
350
- try {
351
- fs.mkdirSync(cacheDir, { recursive: true });
352
- atomicWriteFileSync(stampPath, JSON.stringify({ lastGcMs: nowMs }) + '\n', {
353
- encoding: 'utf8',
354
- mode: 0o600,
355
- dirMode: 0o700
356
- });
357
- } catch (err) {
358
- void err; // ignore: stamp write error does not fail hook
359
- }
360
-
361
- const cutoffMs = nowMs - Math.max(1, Number(maxCacheAgeDays || 14)) * 24 * 60 * 60 * 1000;
362
- const homeReap = reapStaleFilesInDir(cacheDir, cutoffMs, skipNames);
363
- const wsCacheReap = baseCwd
364
- ? reapStaleFilesInDir(path.join(baseCwd, '.claude', 'cache'), cutoffMs, skipNames)
365
- : { removedFiles: 0, reclaimedBytes: 0 };
366
- const artifactsDir = baseCwd ? path.join(baseCwd, '.claude', 'cache', 'artifacts') : null;
367
- const wsArtifactsReap = artifactsDir
368
- ? reapStaleFilesInDir(artifactsDir, cutoffMs, skipNames)
369
- : { removedFiles: 0, reclaimedBytes: 0 };
370
- const cappedArtifacts = artifactsDir
371
- ? enforceArtifactDirCap(artifactsDir, { maxFiles: artifactMaxFiles, maxTotalBytes: artifactMaxBytes })
372
- : { removedFiles: 0, reclaimedBytes: 0 };
373
- const ledgerRotation = rotateMonthlyLedger({ homeDir, nowMs });
374
-
375
- return {
376
- skipped: false,
377
- lastGcMs: nowMs,
378
- reapedFiles: homeReap.removedFiles + wsCacheReap.removedFiles + wsArtifactsReap.removedFiles,
379
- reclaimedBytes:
380
- homeReap.reclaimedBytes + wsCacheReap.reclaimedBytes + wsArtifactsReap.reclaimedBytes + cappedArtifacts.reclaimedBytes,
381
- cappedArtifacts,
382
- ledgerRotation
383
- };
384
- }
385
-
386
- function offloadOversizedOutput(
387
- toolName,
388
- cleanText,
389
- filteredLines,
390
- criticalErrorLines,
391
- baseCwd,
392
- { artifactMaxFiles = DEFAULT_ARTIFACT_MAX_FILES, artifactMaxBytes = DEFAULT_ARTIFACT_MAX_TOTAL_BYTES } = {}
393
- ) {
394
- const sha256 = crypto.createHash('sha256').update(cleanText, 'utf8').digest('hex');
395
- const candidateArtifactPath = path.join(
396
- baseCwd,
397
- '.claude',
398
- 'cache',
399
- 'artifacts',
400
- `burnoff_${sha256}.txt`
401
- );
402
-
403
- try {
404
- atomicWriteFileSync(candidateArtifactPath, cleanText, { encoding: 'utf8', mode: 0o600, dirMode: 0o700 });
405
- enforceArtifactDirCap(path.dirname(candidateArtifactPath), {
406
- maxFiles: artifactMaxFiles,
407
- maxTotalBytes: artifactMaxBytes,
408
- keepPath: candidateArtifactPath
409
- });
410
- } catch (err) {
411
- void err; // ignore: fail-open offload preserves ANSI-cleaned output in memory
412
- return { offloaded: false, artifactPath: null, output: cleanText };
413
- }
414
-
415
- const originalTokens = Math.ceil(cleanText.length / CHARS_PER_TOKEN_ESTIMATE);
416
- const rawLines = cleanText.split(/\n/);
417
- const nonEmpty = filteredLines.filter((l) => l.trim().length > 0);
418
- const sampleLines = nonEmpty.slice(0, 3);
419
- const summaryParts = [
420
- `[Burnoff Artifact Offload: ${originalTokens.toLocaleString('en-US')} tokens (${rawLines.length} lines) archived locally]`,
421
- `Sample lines (1..${sampleLines.length}):`,
422
- ...sampleLines.map((l, idx) => ` ${idx + 1}: ${l.slice(0, 200)}`)
423
- ];
424
-
425
- if (criticalErrorLines.length > 0) {
426
- summaryParts.push(`Critical Error / Failure Lines Preserved Verbatim (${criticalErrorLines.length}):`);
427
- for (const errLine of criticalErrorLines) {
428
- summaryParts.push(` ${errLine}`);
429
- }
430
- }
431
-
432
- return {
433
- offloaded: true,
434
- artifactPath: candidateArtifactPath,
435
- output: summaryParts.join('\n')
436
- };
437
- }
438
-
439
- function sanitizePostOutputFallback(toolName, rawOutput, { baseCwd, allowOffload, offloadThresholdTokens }) {
440
- const originalTokens = Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE);
441
- let cleaned = stripAnsiAndSpinners(rawOutput);
442
- if (/^WebFetch$/i.test(toolName)) {
443
- cleaned = cleaned.replace(HTML_BOILERPLATE_BLOCK_REGEX, '');
444
- }
445
- const criticalErrorLines = extractCriticalErrorLines(cleaned);
446
- const rawLines = cleaned.split(/\n/);
447
- const filteredLines = [];
448
- let strippedPassingTests = 0;
449
-
450
- for (const line of rawLines) {
451
- if (CRITICAL_ERROR_REGEX.test(line)) {
452
- filteredLines.push(line);
453
- continue;
454
- }
455
- if (DOWNLOAD_NOISE_LINE_REGEX.test(line)) {
456
- continue;
457
- }
458
- if (PASSING_TEST_LINE_REGEX.test(line) && rawLines.length > 10) {
459
- strippedPassingTests += 1;
460
- continue;
461
- }
462
- filteredLines.push(line);
463
- }
464
- if (strippedPassingTests > 0) {
465
- filteredLines.push(`[... ${strippedPassingTests} passing test lines compacted by Burnoff ...]`);
466
- }
467
-
468
- let sanitizedText = filteredLines.join('\n');
469
- for (const errLine of criticalErrorLines) {
470
- if (!sanitizedText.includes(errLine)) {
471
- sanitizedText += `\n${errLine}`;
472
- }
473
- }
474
-
475
- const postFilterTokens = Math.ceil(sanitizedText.length / CHARS_PER_TOKEN_ESTIMATE);
476
- let offloaded = false;
477
- let artifactPath = null;
478
- let finalOutput = sanitizedText;
479
-
480
- if (allowOffload && baseCwd && (originalTokens > offloadThresholdTokens || postFilterTokens > offloadThresholdTokens)) {
481
- const offRes = offloadOversizedOutput(toolName, cleaned, filteredLines, criticalErrorLines, baseCwd);
482
- offloaded = offRes.offloaded;
483
- artifactPath = offRes.artifactPath;
484
- finalOutput = offRes.output;
485
- }
486
-
487
- const finalTokens = Math.ceil(finalOutput.length / CHARS_PER_TOKEN_ESTIMATE);
488
- return {
489
- toolName,
490
- eligible: true,
491
- sanitized: finalOutput !== rawOutput,
492
- offloaded,
493
- artifactPath,
494
- originalTokens,
495
- finalTokens,
496
- savedTokens: Math.max(0, originalTokens - finalTokens),
497
- criticalErrorsPreserved: criticalErrorLines.length,
498
- updatedToolOutput: finalOutput
499
- };
500
- }
501
-
502
- function appendMissingCriticalLines(summaryText, criticalLines) {
503
- if (!criticalLines || criticalLines.length === 0) return summaryText;
504
- const missing = [];
505
- for (const line of criticalLines) {
506
- const probe = line.trim().slice(0, 140);
507
- if (probe && !summaryText.includes(probe)) {
508
- missing.push(line);
509
- }
510
- }
511
- if (missing.length === 0) return summaryText;
512
- return `${summaryText}\nCritical Error / Failure Lines Preserved:\n${missing.map((l) => ` ${l}`).join('\n')}`;
513
- }
514
-
515
- /**
516
- * Evaluates a `PostToolUse` hook event and returns the host-formatted output contract.
517
- */
518
- export function runPostToolUseHook(event = {}, options = {}) {
519
- const { client, adapter, canonical } =
520
- event && event.__canonical === true
521
- ? { client: event.client || 'claude-code', adapter: getClientAdapter(event.client || 'claude-code'), canonical: event }
522
- : normalizeHookEvent(event, options);
523
-
524
- const finalize = (res) => (client === 'antigravity' ? adapter.renderPost(res) : res);
525
-
526
- const rawEvent = canonical.raw || event;
527
- const toolName = String(canonical.toolName || 'Bash');
528
- const rawOutput = extractPostToolText(rawEvent);
529
- const tier1Active = Boolean(
530
- options.tier1Active ||
531
- rawEvent.tier1Active ||
532
- globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
533
- );
534
- const failed = canonical.failed === true || didToolExecutionFail(rawEvent, toolName);
535
-
536
- if (
537
- tier1Active &&
538
- /^(?:Grep|Glob)$/i.test(toolName) &&
539
- rawOutput.length < 16_000 &&
540
- !failed
541
- ) {
542
- return finalize({
543
- exitCode: 0,
544
- stdout: '',
545
- stderr: '',
546
- fastPath: 'tier1_active',
547
- sanitized: { modified: false, offloaded: false, savedTokens: 0 }
548
- });
549
- }
550
-
551
- const sessionId = String(canonical.sessionId || 'default');
552
- const hasExplicitCwd = Boolean(canonical.cwd || options.cwd);
553
- const baseCwd = path.resolve(String(canonical.cwd || options.cwd || process.cwd()));
554
- const cwdOptions = { ...(hasExplicitCwd ? { ...options, cwd: baseCwd } : options), client };
555
- const policy = options.policy || loadBurnoffPolicy(baseCwd);
556
- const postCfg = policy.postTool || {};
557
-
558
- const toolInput = canonical.toolInput || {};
559
- const filePath = String(
560
- toolInput.file_path || toolInput.notebook_path || toolInput.filePath || toolInput.path || toolInput.Path || toolInput.TargetFile || event.filePath || ''
561
- ).trim();
562
- const cmdStr = String(
563
- toolInput.command || toolInput.CommandLine || toolInput.cmd || event.command || ''
564
- );
565
- const rawExit =
566
- event.exit_code ??
567
- event.exitCode ??
568
- event.tool_response?.exit_code ??
569
- event.tool_response?.exitCode;
570
-
571
- const shouldPersistState =
572
- options.persistState !== false &&
573
- Boolean(canonical.cwd || options.cwd || options.breakerStatePath || options.persistState);
574
-
575
- if (shouldPersistState) {
576
- recordToolOutcomeAtomicSync(
577
- sessionId,
578
- {
579
- toolName,
580
- command: cmdStr,
581
- filePath,
582
- failed,
583
- nowMs: options.nowMs ?? Date.now()
584
- },
585
- cwdOptions
586
- );
587
-
588
- if (
589
- EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) &&
590
- filePath &&
591
- policy.guards?.scopeLockEnabled !== false
592
- ) {
593
- const ownerId = String(
594
- canonical.agentId || rawEvent.ownerId || rawEvent.agentId || rawEvent.subagentId || sessionId
595
- );
596
- try {
597
- releaseScopeLock(ownerId, {
598
- ...cwdOptions,
599
- scope: filePath,
600
- nowMs: options.nowMs ?? Date.now()
601
- });
602
- } catch (err) {
603
- void err; // ignore: best-effort scope lock release
604
- }
605
- }
606
-
607
- if (options.disableOpportunisticGc !== true) {
608
- try {
609
- runOpportunisticPostToolGc({
610
- baseCwd: hasExplicitCwd ? baseCwd : null,
611
- homeDir: options.homeDir || null,
612
- maxCacheAgeDays: Number(postCfg.retentionDays ?? 30),
613
- nowMs: options.nowMs ?? Date.now(),
614
- artifactMaxFiles: Number(options.artifactMaxFiles ?? postCfg.artifactMaxFiles ?? DEFAULT_ARTIFACT_MAX_FILES),
615
- artifactMaxBytes: Number(options.artifactMaxBytes ?? postCfg.artifactMaxBytes ?? DEFAULT_ARTIFACT_MAX_TOTAL_BYTES)
616
- });
617
- } catch (gcErr) {
618
- void gcErr; // ignore: non-fatal opportunistic post-tool gc
619
- }
620
- }
621
- }
622
-
623
- // Antigravity PostToolUse expects `{}` only and provides no tool stdout to compress.
624
- if (client === 'antigravity') {
625
- return finalize({
626
- exitCode: 0,
627
- stdout: '{}',
628
- stderr: '',
629
- sanitized: { eligible: false, sanitized: false, offloaded: false, savedTokens: 0 }
630
- });
631
- }
632
-
633
- if (isHostTruncatedShellOutput(toolName, rawOutput)) {
634
- return {
635
- exitCode: 0,
636
- stdout: '',
637
- stderr: '',
638
- hostTruncated: true,
639
- sanitized: { modified: false, offloaded: false, savedTokens: 0 }
640
- };
641
- }
642
-
643
- const unprefixed = toolName.replace(/^mcp__[a-zA-Z0-9_-]+__/i, '');
644
- if (PROTECTED_WORKSPACE_TOOL_RE.test(unprefixed) || !ELIGIBLE_POST_TOOL_RE.test(toolName)) {
645
- return {
646
- exitCode: 0,
647
- stdout: '',
648
- stderr: '',
649
- sanitized: { eligible: false, sanitized: false, offloaded: false, savedTokens: 0 }
650
- };
651
- }
652
-
653
- const isShellTool = SHELL_TOOL_NAME_RE.test(toolName);
654
- let shellPolicy = { allowFts5: true, allowOffload: true, reason: 'default' };
655
- if (isShellTool && cmdStr) {
656
- shellPolicy = classifyShellPostToolPolicy(cmdStr);
657
- }
658
-
659
- let finalOutput = rawOutput;
660
- let wasModified = false;
661
- let ftsSavedTokens = 0;
662
- let sanitized = {
663
- toolName,
664
- eligible: true,
665
- sanitized: false,
666
- offloaded: false,
667
- artifactPath: null,
668
- originalTokens: Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE),
669
- finalTokens: Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE),
670
- savedTokens: 0,
671
- criticalErrorsPreserved: 0,
672
- updatedToolOutput: rawOutput
673
- };
674
-
675
- const ftsEnabled =
676
- postCfg.fts5Enabled !== false && options.enableFts5CliCompression !== false;
677
- const minFtsBytes = Number(options.minBytes ?? postCfg.minBytesToCompress ?? 4096);
678
-
679
- if (ftsEnabled && hasExplicitCwd && isShellTool && cmdStr && shellPolicy.allowFts5 !== false) {
680
- try {
681
- const ansiCleanShell = stripAnsiAndSpinners(rawOutput);
682
- const criticalLines = extractCriticalErrorLines(ansiCleanShell);
683
- const ftsDbPath =
684
- options.dbPath ||
685
- options.ftsDbPath ||
686
- getDefaultToolLogsDbPath(options.homeDir || null);
687
- const turnId = String(event.tool_use_id || event.turn_id || event.turnId || `turn-${Date.now()}`);
688
- const ftsComp = compressCliOutputFts5Sync({
689
- sessionId,
690
- turnId,
691
- command: cmdStr,
692
- exitCode: typeof rawExit === 'number' ? rawExit : (failed ? 1 : 0),
693
- rawOutput: ansiCleanShell,
694
- dbPath: ftsDbPath,
695
- homeDir: options.homeDir || null,
696
- recordLedger: false,
697
- minBytes: minFtsBytes,
698
- minTokensSaved: Number(options.minTokensSaved ?? 500),
699
- retentionDays: Number(postCfg.retentionDays ?? 30)
700
- });
701
-
702
- if (ftsComp.compressed && ftsComp.tokensSaved > 0) {
703
- const guaranteedOutput = appendMissingCriticalLines(ftsComp.output, criticalLines);
704
- const guaranteedTokens = Math.ceil(guaranteedOutput.length / CHARS_PER_TOKEN_ESTIMATE);
705
- const rawTokens = Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE);
706
- const netSavedTokens = Math.max(0, rawTokens - guaranteedTokens);
707
- if (netSavedTokens > 0 && guaranteedOutput.length < rawOutput.length) {
708
- finalOutput = guaranteedOutput;
709
- ftsSavedTokens = netSavedTokens;
710
- wasModified = true;
711
- sanitized = {
712
- ...sanitized,
713
- sanitized: true,
714
- offloaded: false,
715
- finalTokens: guaranteedTokens,
716
- savedTokens: netSavedTokens,
717
- criticalErrorsPreserved: criticalLines.length,
718
- turnId,
719
- queryHandle: ftsComp.queryHandle,
720
- updatedToolOutput: finalOutput
721
- };
722
- }
723
- }
724
- } catch (ftsErr) {
725
- void ftsErr; // ignore: FTS5 failure fails open cleanly to sanitizer fallback
726
- }
727
- }
728
-
729
- const isMcpTool = /^mcp__/i.test(toolName);
730
- const postOutputMode = resolvePostOutputMode(postCfg);
731
-
732
- if (ftsSavedTokens === 0) {
733
- const allowOffload =
734
- (isMcpTool || postOutputMode !== 'auto') &&
735
- !(isShellTool && shellPolicy.allowOffload === false) &&
736
- options.disableOffload !== true;
737
- sanitized = sanitizePostOutputFallback(toolName, rawOutput, {
738
- baseCwd: hasExplicitCwd ? baseCwd : null,
739
- allowOffload,
740
- offloadThresholdTokens: Number(
741
- options.offloadThresholdTokens ?? postCfg.offloadThresholdTokens ?? OFFLOAD_TOKEN_THRESHOLD
742
- )
743
- });
744
- finalOutput = sanitized.updatedToolOutput;
745
- wasModified = sanitized.sanitized;
746
- }
747
-
748
- const replacement =
749
- !isMcpTool && wasModified && postOutputMode === 'replace'
750
- ? buildReplacementToolOutput(event, finalOutput)
751
- : { ok: false };
752
- const wouldInflate = !isMcpTool && replacement.ok && finalOutput.length >= rawOutput.length;
753
- const effectiveReplacementOk = replacement.ok && !wouldInflate;
754
- const emitContext =
755
- !isMcpTool &&
756
- !effectiveReplacementOk &&
757
- wasModified &&
758
- postOutputMode === 'context';
759
-
760
- if (!wasModified || (!isMcpTool && !effectiveReplacementOk && !emitContext)) {
761
- return {
762
- exitCode: 0,
763
- stdout: '',
764
- stderr: '',
765
- sanitized
766
- };
767
- }
768
-
769
- const outputAcceptedByHost = isMcpTool ? wasModified : effectiveReplacementOk;
770
- const totalSavedTokens = outputAcceptedByHost
771
- ? (ftsSavedTokens > 0 ? ftsSavedTokens : sanitized.savedTokens)
772
- : 0;
773
-
774
- if (totalSavedTokens > 0 && options.recordLedger !== false && (hasExplicitCwd || options.ledgerPath || options.recordLedger === true)) {
775
- const rawEventModel =
776
- typeof event.model === 'string'
777
- ? event.model
778
- : event.model?.id || event.model?.model_id || event.modelId || event.model_id;
779
- const modelId = rawEventModel || 'claude-sonnet-5-5';
780
- const usageSource = event.usage || event.context_window?.current_usage || {};
781
- const totalPromptTokens = computeTotalPromptTokens(usageSource);
782
- const rates = resolveEffectiveRates(modelId, totalPromptTokens, cwdOptions);
783
- const computedSavedUSD =
784
- rates && !rates.unknownModel && Number.isFinite(rates.inputPer1M)
785
- ? Number(((totalSavedTokens / 1_000_000) * rates.inputPer1M).toFixed(6))
786
- : 0;
787
- const writeRatePer1M =
788
- rates && !rates.unknownModel ? (rates.write5mPer1M ?? rates.inputPer1M) : 0;
789
- const writeRateUSD =
790
- Number.isFinite(writeRatePer1M) && writeRatePer1M > 0
791
- ? Number(((totalSavedTokens / 1_000_000) * writeRatePer1M).toFixed(6))
792
- : 0;
793
-
794
- recordSavingsReceipt(
795
- {
796
- sessionId,
797
- cwd: baseCwd,
798
- modelId: rates.unknownModel ? (rates.rawModelId || modelId) : rates.modelId,
799
- ledgerBucket: LEDGER_BUCKETS.AVOIDED_WRITE,
800
- category: sanitized.offloaded
801
- ? 'ARTIFACT_OFFLOAD_4K'
802
- : ftsSavedTokens > 0
803
- ? 'CLI_FTS5_COMPRESSED'
804
- : 'LOSSLESS_POST_SANITIZER',
805
- savedTokens: totalSavedTokens,
806
- savedUSD: computedSavedUSD,
807
- writeRateUSD,
808
- detail: `${toolName} output compressed (+${totalSavedTokens} tokens saved)`
809
- },
810
- cwdOptions
811
- );
812
- }
813
-
814
- const hookSpecificOutput = isMcpTool
815
- ? {
816
- hookEventName: 'PostToolUse',
817
- updatedMCPToolOutput: finalOutput
818
- }
819
- : effectiveReplacementOk
820
- ? {
821
- hookEventName: 'PostToolUse',
822
- updatedToolOutput: replacement.value
823
- }
824
- : {
825
- hookEventName: 'PostToolUse',
826
- additionalContext: finalOutput
827
- };
828
-
829
- return {
830
- exitCode: 0,
831
- stdout: JSON.stringify({ hookSpecificOutput }),
832
- stderr: '',
833
- sanitized,
834
- hookSpecificOutput
835
- };
836
- }
837
-
838
- export default {
839
- OFFLOAD_TOKEN_THRESHOLD,
840
- CHARS_PER_TOKEN_ESTIMATE,
841
- DEFAULT_ARTIFACT_MAX_FILES,
842
- DEFAULT_ARTIFACT_MAX_TOTAL_BYTES,
843
- OPPORTUNISTIC_GC_INTERVAL_MS,
844
- CRITICAL_ERROR_REGEX,
845
- stripAnsiAndSpinners,
846
- extractCriticalErrorLines,
847
- extractPostToolText,
848
- enforceArtifactDirCap,
849
- runOpportunisticPostToolGc,
850
- buildReplacementToolOutput,
851
- isHostTruncatedShellOutput,
852
- didToolExecutionFail,
853
- runPostToolUseHook
854
- };
1
+ /**
2
+ * @file src/guards/post-tool-engine.mjs
3
+ * Pure ESM orchestrator for Claude Code `PostToolUse` evaluation.
4
+ * Atomically updates `DET-04` failure counters and `git stash` timestamps, strips ANSI/spinners,
5
+ * compresses eligible CLI logs via SQLite FTS5 (`npx burnoff search`), offloads >4,000-token blobs
6
+ * while preserving 100% of critical error lines, and replaces tool outputs in native host shapes.
7
+ */
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import crypto from 'node:crypto';
12
+ import { getClientAdapter, normalizeHookEvent } from '../clients/detect.mjs';
13
+ import { loadBurnoffPolicy } from '../config/policy.mjs';
14
+ import { getBurnoffCacheDir, getHomeDir } from '../config/paths.mjs';
15
+ import { computeTotalPromptTokens, resolveEffectiveRates } from '../config/loader.mjs';
16
+ import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
17
+ import {
18
+ compressCliOutputFts5Sync,
19
+ classifyShellPostToolPolicy,
20
+ getDefaultToolLogsDbPath
21
+ } from '../storage/fts5-archive.mjs';
22
+ import { recordSavingsReceipt, rotateMonthlyLedger, LEDGER_BUCKETS } from '../storage/ledger.mjs';
23
+ import { recordToolOutcomeAtomicSync, releaseScopeLock } from './loop-breaker.mjs';
24
+ import { redactSecretsPure } from './credential-scrubber.mjs';
25
+
26
+ export const OFFLOAD_TOKEN_THRESHOLD = 4000;
27
+ export const CHARS_PER_TOKEN_ESTIMATE = 4;
28
+ export const DEFAULT_ARTIFACT_MAX_FILES = 200;
29
+ export const DEFAULT_ARTIFACT_MAX_TOTAL_BYTES = 50 * 1024 * 1024;
30
+ export const OPPORTUNISTIC_GC_INTERVAL_MS = 24 * 60 * 60 * 1000;
31
+
32
+ export const CRITICAL_ERROR_REGEX =
33
+ /(Error|Exception|FAIL|error\[E\d+\]|panic:|ERR!|ERESOLVE|AssertionError|SyntaxError)/i;
34
+
35
+ const ANSI_CSI_OSC_REGEX =
36
+ /\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
37
+
38
+ const DOWNLOAD_NOISE_LINE_REGEX =
39
+ /^\s*(?:npm\s+(?:http|verb|silly|timing|notice)\b|Progress:\s+resolved\s+\d+|Downloading\s+\S+\s+\[[=#>-]+\s*\]|\d+%\s+\[[=#>-]+\s*\]|Receiving objects:\s+\d+%|Resolving deltas:\s+\d+%)/i;
40
+
41
+ const PASSING_TEST_LINE_REGEX =
42
+ /^\s*(?:✔|✓|PASS\s+\S+|ok\s+\d+\s+-\s+)/;
43
+
44
+ const HTML_BOILERPLATE_BLOCK_REGEX =
45
+ /<(nav|footer|script|style|svg|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi;
46
+
47
+ const SHELL_TOOL_NAME_RE = /^(?:Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash)$/i;
48
+ const PROTECTED_WORKSPACE_TOOL_RE =
49
+ /^(?:Read|read_file|view_file|View|Edit|edit_file|Write|write_file|replace_file_content|MultiEdit|NotebookEdit)$/i;
50
+ const EDIT_WRITE_SCOPE_LOCK_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit)$/i;
51
+ const ELIGIBLE_POST_TOOL_RE =
52
+ /^(?:Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash|WebFetch|Grep|Glob|Task|Agent|mcp__.+)$/i;
53
+
54
+ export function stripAnsiAndSpinners(rawText = '') {
55
+ const withoutAnsi = String(rawText || '').replace(ANSI_CSI_OSC_REGEX, '');
56
+ const lines = withoutAnsi.split(/\n/);
57
+ const resolvedLines = lines.map((line) => {
58
+ const trimmedCr = line.replace(/\r$/, '');
59
+ if (!trimmedCr.includes('\r')) return trimmedCr;
60
+ const segments = trimmedCr.split('\r').filter((seg) => seg.trim().length > 0);
61
+ return segments.length > 0 ? segments[segments.length - 1] : '';
62
+ });
63
+ return resolvedLines.join('\n');
64
+ }
65
+
66
+ export function extractCriticalErrorLines(cleanText = '') {
67
+ return String(cleanText || '')
68
+ .split(/\r?\n/)
69
+ .filter((line) => CRITICAL_ERROR_REGEX.test(line));
70
+ }
71
+
72
+ export function extractPostToolText(event = {}) {
73
+ const resp = event.tool_response ?? event.tool_output ?? event.toolOutput ?? event.output;
74
+ if (typeof resp === 'string') return resp;
75
+ if (resp && typeof resp === 'object') {
76
+ if (Array.isArray(resp.content)) {
77
+ const blockText = resp.content
78
+ .filter((b) => b && b.type === 'text' && typeof b.text === 'string' && b.text.length > 0)
79
+ .map((b) => b.text)
80
+ .join('\n');
81
+ if (blockText.length > 0) return blockText;
82
+ }
83
+ const parts = [resp.stdout, resp.stderr, resp.output, resp.content, resp.result, resp.error]
84
+ .filter((x) => typeof x === 'string' && x.length > 0);
85
+ if (parts.length > 0) return parts.join('\n');
86
+ for (const arrKey of ['filenames', 'files']) {
87
+ if (
88
+ Array.isArray(resp[arrKey]) &&
89
+ resp[arrKey].length > 0 &&
90
+ resp[arrKey].every((item) => typeof item === 'string')
91
+ ) {
92
+ return resp[arrKey].join('\n');
93
+ }
94
+ }
95
+ return '';
96
+ }
97
+ return resp !== undefined && resp !== null ? String(resp) : '';
98
+ }
99
+
100
+ /**
101
+ * Builds a replacement `tool_response` in the exact shape the host sent (`updatedToolOutput`).
102
+ * Returns `{ ok: false }` for unrecognized object shapes so no phantom savings are recorded.
103
+ */
104
+ export function buildReplacementToolOutput(event = {}, finalOutput = '') {
105
+ const resp = event.tool_response ?? event.tool_output ?? event.toolOutput ?? event.output;
106
+ if (typeof resp === 'string') return { ok: true, value: finalOutput };
107
+ if (resp && typeof resp === 'object' && !Array.isArray(resp)) {
108
+ if (Array.isArray(resp.content)) {
109
+ const hasTextBlock = resp.content.some((b) => b && b.type === 'text' && typeof b.text === 'string');
110
+ const hasNonTextBlock = resp.content.some((b) => !b || b.type !== 'text');
111
+ if (hasTextBlock && !hasNonTextBlock) {
112
+ return { ok: true, value: { ...resp, content: [{ type: 'text', text: finalOutput }] } };
113
+ }
114
+ }
115
+ const textKeys = ['stdout', 'output', 'content', 'result', 'error', 'stderr'];
116
+ const primary = textKeys.find((k) => typeof resp[k] === 'string' && resp[k].length > 0);
117
+ if (primary) {
118
+ const next = { ...resp };
119
+ for (const k of textKeys) {
120
+ if (typeof next[k] === 'string') next[k] = k === primary ? finalOutput : '';
121
+ }
122
+ if (primary === 'content' && typeof next.numLines === 'number') {
123
+ next.numLines = finalOutput ? String(finalOutput).split(/\r?\n/).length : 0;
124
+ }
125
+ return { ok: true, value: next };
126
+ }
127
+ const arrayKeys = ['filenames', 'files'];
128
+ const primaryArr = arrayKeys.find(
129
+ (k) => Array.isArray(resp[k]) && resp[k].length > 0 && resp[k].every((item) => typeof item === 'string')
130
+ );
131
+ if (primaryArr) {
132
+ const nextItems = String(finalOutput || '')
133
+ .split(/\r?\n/)
134
+ .map((line) => line.trimEnd())
135
+ .filter((line) => line.length > 0);
136
+ const next = { ...resp, [primaryArr]: nextItems };
137
+ if (typeof next.numFiles === 'number') {
138
+ const pathCount = nextItems.filter((line) => !/^\[/.test(line.trim())).length;
139
+ next.numFiles = pathCount > 0 ? pathCount : nextItems.length;
140
+ }
141
+ if (typeof next.truncated === 'boolean') {
142
+ next.truncated = true;
143
+ }
144
+ return { ok: true, value: next };
145
+ }
146
+ return { ok: false };
147
+ }
148
+ return { ok: false };
149
+ }
150
+
151
+ function resolveHostShellOutputCap() {
152
+ const n = Number(globalThis.process?.env?.BASH_MAX_OUTPUT_LENGTH);
153
+ return Number.isFinite(n) && n > 0 ? n : 30_000;
154
+ }
155
+
156
+ export function isHostTruncatedShellOutput(toolName, rawOutput) {
157
+ if (!/^(?:Bash|PowerShell)$/i.test(String(toolName || ''))) return false;
158
+ return String(rawOutput || '').length >= resolveHostShellOutputCap() - 100;
159
+ }
160
+
161
+ export function didToolExecutionFail(event = {}, toolNameHint = '') {
162
+ const hookEventName = String(event.hook_event_name || event.hookEventName || '');
163
+ if (hookEventName === 'PostToolUseFailure') {
164
+ return true;
165
+ }
166
+ if (
167
+ event.is_error === true ||
168
+ event.isError === true ||
169
+ event.succeeded === false ||
170
+ Boolean(event.tool_error || event.error) ||
171
+ (typeof event.exit_code === 'number' && event.exit_code !== 0) ||
172
+ (typeof event.exitCode === 'number' && event.exitCode !== 0)
173
+ ) {
174
+ return true;
175
+ }
176
+ const resp = event.tool_response;
177
+ if (resp && typeof resp === 'object') {
178
+ if (
179
+ resp.is_error === true ||
180
+ resp.isError === true ||
181
+ resp.succeeded === false ||
182
+ resp.status === 'error' ||
183
+ resp.status === 'failed' ||
184
+ Boolean(resp.error) ||
185
+ (typeof resp.exit_code === 'number' && resp.exit_code !== 0) ||
186
+ (typeof resp.exitCode === 'number' && resp.exitCode !== 0) ||
187
+ (typeof resp.returncode === 'number' && resp.returncode !== 0)
188
+ ) {
189
+ return true;
190
+ }
191
+ }
192
+
193
+ const rawTool = String(
194
+ toolNameHint || event.tool_name || event.toolName || event.toolCall?.name || event.name || ''
195
+ ).trim();
196
+ const isShellLike =
197
+ !rawTool || SHELL_TOOL_NAME_RE.test(rawTool) || /^(?:Shell|Command)$/i.test(rawTool);
198
+ if (isShellLike) {
199
+ const rawText = stripAnsiAndSpinners(extractPostToolText(event));
200
+ if (rawText) {
201
+ const exitMarkerRe =
202
+ /(?:^|\r?\n)\s*(?:exit\s+(?:code|status)|command\s+exited\s+with\s+(?:code|status)|process\s+exited\s+with\s+(?:code|status)|returned\s+non-zero\s+exit\s+status)\s*[:=]?\s*(-?\d+)\b/gim;
203
+ for (const m of rawText.matchAll(exitMarkerRe)) {
204
+ const code = Number(m[1]);
205
+ if (Number.isFinite(code) && code !== 0) {
206
+ return true;
207
+ }
208
+ }
209
+ }
210
+ }
211
+ return false;
212
+ }
213
+
214
+ export function resolvePostOutputMode(policyPost = {}) {
215
+ const envRaw = String(globalThis.process?.env?.BURNOFF_POST_OUTPUT_MODE || '').trim().toLowerCase();
216
+ if (envRaw === 'context' || envRaw === 'additionalcontext') return 'context';
217
+ if (envRaw === 'replace' || envRaw === 'updatedtooloutput') return 'replace';
218
+ if (envRaw === 'auto') return 'auto';
219
+ const cfgMode = String(policyPost.outputMode || 'replace').trim().toLowerCase();
220
+ if (cfgMode === 'context' || cfgMode === 'additionalcontext') return 'context';
221
+ if (cfgMode === 'auto') return 'auto';
222
+ return 'replace';
223
+ }
224
+
225
+ export function enforceArtifactDirCap(
226
+ artifactsDir,
227
+ {
228
+ maxFiles = DEFAULT_ARTIFACT_MAX_FILES,
229
+ maxTotalBytes = DEFAULT_ARTIFACT_MAX_TOTAL_BYTES,
230
+ keepPath = null
231
+ } = {}
232
+ ) {
233
+ if (!artifactsDir || !fs.existsSync(artifactsDir)) {
234
+ return { removedFiles: 0, reclaimedBytes: 0 };
235
+ }
236
+ const keepAbs = keepPath ? path.resolve(keepPath) : null;
237
+ let entries;
238
+ try {
239
+ entries = fs.readdirSync(artifactsDir, { withFileTypes: true });
240
+ } catch (err) {
241
+ void err; // ignore: unreadable artifacts dir skips cap
242
+ return { removedFiles: 0, reclaimedBytes: 0 };
243
+ }
244
+
245
+ const files = [];
246
+ let totalBytes = 0;
247
+ for (const ent of entries) {
248
+ if (!ent.isFile() || !/^burnoff_.*\.txt$/i.test(ent.name)) continue;
249
+ const full = path.join(artifactsDir, ent.name);
250
+ try {
251
+ const st = fs.statSync(full);
252
+ files.push({ full, abs: path.resolve(full), mtimeMs: st.mtimeMs || 0, size: st.size || 0 });
253
+ totalBytes += st.size || 0;
254
+ } catch (err) {
255
+ void err; // ignore: vanished artifact entry skipped
256
+ }
257
+ }
258
+
259
+ if (files.length <= maxFiles && totalBytes <= maxTotalBytes) {
260
+ return { removedFiles: 0, reclaimedBytes: 0 };
261
+ }
262
+
263
+ files.sort((a, b) => a.mtimeMs - b.mtimeMs);
264
+ let remainingFiles = files.length;
265
+ let remainingBytes = totalBytes;
266
+ let removedFiles = 0;
267
+ let reclaimedBytes = 0;
268
+
269
+ for (const f of files) {
270
+ if (remainingFiles <= maxFiles && remainingBytes <= maxTotalBytes) break;
271
+ if (keepAbs && f.abs === keepAbs) continue;
272
+ try {
273
+ fs.unlinkSync(f.full);
274
+ remainingFiles -= 1;
275
+ remainingBytes -= f.size;
276
+ removedFiles += 1;
277
+ reclaimedBytes += f.size;
278
+ } catch (err) {
279
+ void err; // ignore: locked or already removed artifact
280
+ }
281
+ }
282
+
283
+ return { removedFiles, reclaimedBytes };
284
+ }
285
+
286
+ function reapStaleFilesInDir(dirPath, cutoffMs, skipNames = new Set()) {
287
+ if (!dirPath || !fs.existsSync(dirPath)) {
288
+ return { removedFiles: 0, reclaimedBytes: 0 };
289
+ }
290
+ let entries;
291
+ try {
292
+ entries = fs.readdirSync(dirPath, { withFileTypes: true });
293
+ } catch (err) {
294
+ void err; // ignore: unreadable cache directory
295
+ return { removedFiles: 0, reclaimedBytes: 0 };
296
+ }
297
+ let removedFiles = 0;
298
+ let reclaimedBytes = 0;
299
+ for (const ent of entries) {
300
+ if (!ent.isFile()) continue;
301
+ if (
302
+ skipNames.has(ent.name) ||
303
+ ent.name.startsWith('tool_logs_fts5.db') ||
304
+ ent.name.startsWith('tool_logs_fallback.json')
305
+ ) {
306
+ continue;
307
+ }
308
+ const full = path.join(dirPath, ent.name);
309
+ try {
310
+ const st = fs.statSync(full);
311
+ if (st.mtimeMs < cutoffMs) {
312
+ fs.unlinkSync(full);
313
+ removedFiles += 1;
314
+ reclaimedBytes += st.size;
315
+ }
316
+ } catch (err) {
317
+ void err; // ignore: locked or concurrently unlinked cache file
318
+ }
319
+ }
320
+ return { removedFiles, reclaimedBytes };
321
+ }
322
+
323
+ /**
324
+ * Throttled (<= 1x per 24h) cache reap, artifact cap enforcement, and monthly ledger rotation.
325
+ */
326
+ export function runOpportunisticPostToolGc({
327
+ baseCwd = null,
328
+ homeDir = null,
329
+ maxCacheAgeDays = 14,
330
+ nowMs = Date.now(),
331
+ force = false,
332
+ artifactMaxFiles = DEFAULT_ARTIFACT_MAX_FILES,
333
+ artifactMaxBytes = DEFAULT_ARTIFACT_MAX_TOTAL_BYTES
334
+ } = {}) {
335
+ const cacheDir = getBurnoffCacheDir(homeDir);
336
+ const stampPath = path.join(cacheDir, 'burnoff_last_gc.json');
337
+ const skipNames = new Set(['burnoff_last_gc.json']);
338
+
339
+ if (!force && fs.existsSync(stampPath)) {
340
+ try {
341
+ const raw = JSON.parse(fs.readFileSync(stampPath, 'utf8'));
342
+ const lastGcMs = Number(raw?.lastGcMs || 0);
343
+ if (lastGcMs > 0 && nowMs - lastGcMs < OPPORTUNISTIC_GC_INTERVAL_MS) {
344
+ return { skipped: true, reason: 'throttled_24h', lastGcMs };
345
+ }
346
+ } catch (err) {
347
+ void err; // ignore: corrupt stamp file falls through to run GC
348
+ }
349
+ }
350
+
351
+ try {
352
+ fs.mkdirSync(cacheDir, { recursive: true });
353
+ atomicWriteFileSync(stampPath, JSON.stringify({ lastGcMs: nowMs }) + '\n', {
354
+ encoding: 'utf8',
355
+ mode: 0o600,
356
+ dirMode: 0o700
357
+ });
358
+ } catch (err) {
359
+ void err; // ignore: stamp write error does not fail hook
360
+ }
361
+
362
+ const cutoffMs = nowMs - Math.max(1, Number(maxCacheAgeDays || 14)) * 24 * 60 * 60 * 1000;
363
+ const homeReap = reapStaleFilesInDir(cacheDir, cutoffMs, skipNames);
364
+ const wsCacheReap = baseCwd
365
+ ? reapStaleFilesInDir(path.join(baseCwd, '.claude', 'cache'), cutoffMs, skipNames)
366
+ : { removedFiles: 0, reclaimedBytes: 0 };
367
+ const artifactsDir = baseCwd ? path.join(baseCwd, '.claude', 'cache', 'artifacts') : null;
368
+ const wsArtifactsReap = artifactsDir
369
+ ? reapStaleFilesInDir(artifactsDir, cutoffMs, skipNames)
370
+ : { removedFiles: 0, reclaimedBytes: 0 };
371
+ const cappedArtifacts = artifactsDir
372
+ ? enforceArtifactDirCap(artifactsDir, { maxFiles: artifactMaxFiles, maxTotalBytes: artifactMaxBytes })
373
+ : { removedFiles: 0, reclaimedBytes: 0 };
374
+ const ledgerRotation = rotateMonthlyLedger({ homeDir, nowMs });
375
+
376
+ return {
377
+ skipped: false,
378
+ lastGcMs: nowMs,
379
+ reapedFiles: homeReap.removedFiles + wsCacheReap.removedFiles + wsArtifactsReap.removedFiles,
380
+ reclaimedBytes:
381
+ homeReap.reclaimedBytes + wsCacheReap.reclaimedBytes + wsArtifactsReap.reclaimedBytes + cappedArtifacts.reclaimedBytes,
382
+ cappedArtifacts,
383
+ ledgerRotation
384
+ };
385
+ }
386
+
387
+ function offloadOversizedOutput(
388
+ toolName,
389
+ cleanText,
390
+ filteredLines,
391
+ criticalErrorLines,
392
+ baseCwd,
393
+ { artifactMaxFiles = DEFAULT_ARTIFACT_MAX_FILES, artifactMaxBytes = DEFAULT_ARTIFACT_MAX_TOTAL_BYTES } = {}
394
+ ) {
395
+ const sha256 = crypto.createHash('sha256').update(cleanText, 'utf8').digest('hex');
396
+ const candidateArtifactPath = path.join(
397
+ baseCwd,
398
+ '.claude',
399
+ 'cache',
400
+ 'artifacts',
401
+ `burnoff_${sha256}.txt`
402
+ );
403
+
404
+ try {
405
+ atomicWriteFileSync(candidateArtifactPath, cleanText, { encoding: 'utf8', mode: 0o600, dirMode: 0o700 });
406
+ enforceArtifactDirCap(path.dirname(candidateArtifactPath), {
407
+ maxFiles: artifactMaxFiles,
408
+ maxTotalBytes: artifactMaxBytes,
409
+ keepPath: candidateArtifactPath
410
+ });
411
+ } catch (err) {
412
+ void err; // ignore: fail-open offload preserves ANSI-cleaned output in memory
413
+ return { offloaded: false, artifactPath: null, output: cleanText };
414
+ }
415
+
416
+ const originalTokens = Math.ceil(cleanText.length / CHARS_PER_TOKEN_ESTIMATE);
417
+ const rawLines = cleanText.split(/\n/);
418
+ const nonEmpty = filteredLines.filter((l) => l.trim().length > 0);
419
+ const sampleLines = nonEmpty.slice(0, 3);
420
+ const summaryParts = [
421
+ `[Burnoff Artifact Offload: ${originalTokens.toLocaleString('en-US')} tokens (${rawLines.length} lines) archived locally]`,
422
+ `Sample lines (1..${sampleLines.length}):`,
423
+ ...sampleLines.map((l, idx) => ` ${idx + 1}: ${l.slice(0, 200)}`)
424
+ ];
425
+
426
+ if (criticalErrorLines.length > 0) {
427
+ summaryParts.push(`Critical Error / Failure Lines Preserved Verbatim (${criticalErrorLines.length}):`);
428
+ for (const errLine of criticalErrorLines) {
429
+ summaryParts.push(` ${errLine}`);
430
+ }
431
+ }
432
+
433
+ return {
434
+ offloaded: true,
435
+ artifactPath: candidateArtifactPath,
436
+ output: summaryParts.join('\n')
437
+ };
438
+ }
439
+
440
+ function sanitizePostOutputFallback(toolName, rawOutput, { baseCwd, allowOffload, offloadThresholdTokens }) {
441
+ const originalTokens = Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE);
442
+ const scrubbedInit = redactSecretsPure(stripAnsiAndSpinners(rawOutput));
443
+ let cleaned = scrubbedInit.sanitized;
444
+ let redactedSecrets = scrubbedInit.redactedCount;
445
+ if (/^WebFetch$/i.test(toolName)) {
446
+ cleaned = cleaned.replace(HTML_BOILERPLATE_BLOCK_REGEX, '');
447
+ }
448
+ const criticalErrorLines = extractCriticalErrorLines(cleaned);
449
+ const rawLines = cleaned.split(/\n/);
450
+ const filteredLines = [];
451
+ let strippedPassingTests = 0;
452
+
453
+ for (const line of rawLines) {
454
+ if (CRITICAL_ERROR_REGEX.test(line)) {
455
+ filteredLines.push(line);
456
+ continue;
457
+ }
458
+ if (DOWNLOAD_NOISE_LINE_REGEX.test(line)) {
459
+ continue;
460
+ }
461
+ if (PASSING_TEST_LINE_REGEX.test(line) && rawLines.length > 10) {
462
+ strippedPassingTests += 1;
463
+ continue;
464
+ }
465
+ filteredLines.push(line);
466
+ }
467
+ if (strippedPassingTests > 0) {
468
+ filteredLines.push(`[... ${strippedPassingTests} passing test lines compacted by Burnoff ...]`);
469
+ }
470
+
471
+ let sanitizedText = filteredLines.join('\n');
472
+ for (const errLine of criticalErrorLines) {
473
+ if (!sanitizedText.includes(errLine)) {
474
+ sanitizedText += `\n${errLine}`;
475
+ }
476
+ }
477
+
478
+ const postFilterTokens = Math.ceil(sanitizedText.length / CHARS_PER_TOKEN_ESTIMATE);
479
+ let offloaded = false;
480
+ let artifactPath = null;
481
+ let finalOutput = sanitizedText;
482
+
483
+ if (allowOffload && baseCwd && (originalTokens > offloadThresholdTokens || postFilterTokens > offloadThresholdTokens)) {
484
+ const cleanScrub = redactSecretsPure(cleaned);
485
+ cleaned = cleanScrub.sanitized;
486
+ redactedSecrets = Math.max(redactedSecrets, cleanScrub.redactedCount);
487
+ const offRes = offloadOversizedOutput(toolName, cleaned, filteredLines, criticalErrorLines, baseCwd);
488
+ offloaded = offRes.offloaded;
489
+ artifactPath = offRes.artifactPath;
490
+ finalOutput = redactSecretsPure(offRes.output).sanitized;
491
+ } else {
492
+ const finalScrub = redactSecretsPure(finalOutput);
493
+ finalOutput = finalScrub.sanitized;
494
+ redactedSecrets = Math.max(redactedSecrets, finalScrub.redactedCount);
495
+ }
496
+
497
+ const finalTokens = Math.ceil(finalOutput.length / CHARS_PER_TOKEN_ESTIMATE);
498
+ return {
499
+ toolName,
500
+ eligible: true,
501
+ sanitized: finalOutput !== rawOutput,
502
+ offloaded,
503
+ artifactPath,
504
+ redactedSecrets,
505
+ originalTokens,
506
+ finalTokens,
507
+ savedTokens: Math.max(0, originalTokens - finalTokens),
508
+ criticalErrorsPreserved: criticalErrorLines.length,
509
+ updatedToolOutput: finalOutput
510
+ };
511
+ }
512
+
513
+ function appendMissingCriticalLines(summaryText, criticalLines) {
514
+ if (!criticalLines || criticalLines.length === 0) return summaryText;
515
+ const missing = [];
516
+ for (const line of criticalLines) {
517
+ const probe = line.trim().slice(0, 140);
518
+ if (probe && !summaryText.includes(probe)) {
519
+ missing.push(line);
520
+ }
521
+ }
522
+ if (missing.length === 0) return summaryText;
523
+ return `${summaryText}\nCritical Error / Failure Lines Preserved:\n${missing.map((l) => ` ${l}`).join('\n')}`;
524
+ }
525
+
526
+ /**
527
+ * Evaluates a `PostToolUse` hook event and returns the host-formatted output contract.
528
+ */
529
+ export function runPostToolUseHook(event = {}, options = {}) {
530
+ const { client, adapter, canonical } =
531
+ event && event.__canonical === true
532
+ ? { client: event.client || 'claude-code', adapter: getClientAdapter(event.client || 'claude-code'), canonical: event }
533
+ : normalizeHookEvent(event, options);
534
+
535
+ const finalize = (res) => (client === 'antigravity' ? adapter.renderPost(res) : res);
536
+
537
+ const rawEvent = canonical.raw || event;
538
+ const toolName = String(canonical.toolName || 'Bash');
539
+ const rawOutput = extractPostToolText(rawEvent);
540
+ const tier1Active = Boolean(
541
+ options.tier1Active ||
542
+ rawEvent.tier1Active ||
543
+ globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
544
+ );
545
+ const failed = canonical.failed === true || didToolExecutionFail(rawEvent, toolName);
546
+
547
+ if (
548
+ tier1Active &&
549
+ /^(?:Grep|Glob)$/i.test(toolName) &&
550
+ rawOutput.length < 16_000 &&
551
+ !failed
552
+ ) {
553
+ return finalize({
554
+ exitCode: 0,
555
+ stdout: '',
556
+ stderr: '',
557
+ fastPath: 'tier1_active',
558
+ sanitized: { modified: false, offloaded: false, savedTokens: 0 }
559
+ });
560
+ }
561
+
562
+ const sessionId = String(canonical.sessionId || 'default');
563
+ const hasExplicitCwd = Boolean(canonical.cwd || options.cwd);
564
+ const baseCwd = path.resolve(String(canonical.cwd || options.cwd || process.cwd()));
565
+ const cwdOptions = { ...(hasExplicitCwd ? { ...options, cwd: baseCwd } : options), client };
566
+ const policy = options.policy || loadBurnoffPolicy(baseCwd);
567
+ const postCfg = policy.postTool || {};
568
+
569
+ const toolInput = canonical.toolInput || {};
570
+ const filePath = String(
571
+ toolInput.file_path || toolInput.notebook_path || toolInput.filePath || toolInput.path || toolInput.Path || toolInput.TargetFile || event.filePath || ''
572
+ ).trim();
573
+ const cmdStr = String(
574
+ toolInput.command || toolInput.CommandLine || toolInput.cmd || event.command || ''
575
+ );
576
+ const rawExit =
577
+ event.exit_code ??
578
+ event.exitCode ??
579
+ event.tool_response?.exit_code ??
580
+ event.tool_response?.exitCode;
581
+
582
+ const shouldPersistState =
583
+ options.persistState !== false &&
584
+ Boolean(canonical.cwd || options.cwd || options.breakerStatePath || options.persistState);
585
+
586
+ if (shouldPersistState) {
587
+ recordToolOutcomeAtomicSync(
588
+ sessionId,
589
+ {
590
+ toolName,
591
+ command: cmdStr,
592
+ filePath,
593
+ failed,
594
+ nowMs: options.nowMs ?? Date.now()
595
+ },
596
+ cwdOptions
597
+ );
598
+
599
+ if (
600
+ EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) &&
601
+ filePath &&
602
+ policy.guards?.scopeLockEnabled !== false
603
+ ) {
604
+ const ownerId = String(
605
+ canonical.agentId || rawEvent.ownerId || rawEvent.agentId || rawEvent.subagentId || sessionId
606
+ );
607
+ try {
608
+ releaseScopeLock(ownerId, {
609
+ ...cwdOptions,
610
+ scope: filePath,
611
+ nowMs: options.nowMs ?? Date.now()
612
+ });
613
+ } catch (err) {
614
+ void err; // ignore: best-effort scope lock release
615
+ }
616
+ }
617
+
618
+ if (options.disableOpportunisticGc !== true) {
619
+ try {
620
+ runOpportunisticPostToolGc({
621
+ baseCwd: hasExplicitCwd ? baseCwd : null,
622
+ homeDir: options.homeDir || null,
623
+ maxCacheAgeDays: Number(postCfg.retentionDays ?? 30),
624
+ nowMs: options.nowMs ?? Date.now(),
625
+ artifactMaxFiles: Number(options.artifactMaxFiles ?? postCfg.artifactMaxFiles ?? DEFAULT_ARTIFACT_MAX_FILES),
626
+ artifactMaxBytes: Number(options.artifactMaxBytes ?? postCfg.artifactMaxBytes ?? DEFAULT_ARTIFACT_MAX_TOTAL_BYTES)
627
+ });
628
+ } catch (gcErr) {
629
+ void gcErr; // ignore: non-fatal opportunistic post-tool gc
630
+ }
631
+ }
632
+ }
633
+
634
+ // Antigravity PostToolUse expects `{}` only and provides no tool stdout to compress.
635
+ if (client === 'antigravity') {
636
+ return finalize({
637
+ exitCode: 0,
638
+ stdout: '{}',
639
+ stderr: '',
640
+ sanitized: { eligible: false, sanitized: false, offloaded: false, savedTokens: 0 }
641
+ });
642
+ }
643
+
644
+ if (isHostTruncatedShellOutput(toolName, rawOutput)) {
645
+ return {
646
+ exitCode: 0,
647
+ stdout: '',
648
+ stderr: '',
649
+ hostTruncated: true,
650
+ sanitized: { modified: false, offloaded: false, savedTokens: 0 }
651
+ };
652
+ }
653
+
654
+ const unprefixed = toolName.replace(/^mcp__[a-zA-Z0-9_-]+__/i, '');
655
+ if (PROTECTED_WORKSPACE_TOOL_RE.test(unprefixed) || !ELIGIBLE_POST_TOOL_RE.test(toolName)) {
656
+ return {
657
+ exitCode: 0,
658
+ stdout: '',
659
+ stderr: '',
660
+ sanitized: { eligible: false, sanitized: false, offloaded: false, savedTokens: 0 }
661
+ };
662
+ }
663
+
664
+ const isShellTool = SHELL_TOOL_NAME_RE.test(toolName);
665
+ let shellPolicy = { allowFts5: true, allowOffload: true, reason: 'default' };
666
+ if (isShellTool && cmdStr) {
667
+ shellPolicy = classifyShellPostToolPolicy(cmdStr);
668
+ }
669
+
670
+ let finalOutput = rawOutput;
671
+ let wasModified = false;
672
+ let ftsSavedTokens = 0;
673
+ let sanitized = {
674
+ toolName,
675
+ eligible: true,
676
+ sanitized: false,
677
+ offloaded: false,
678
+ artifactPath: null,
679
+ originalTokens: Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE),
680
+ finalTokens: Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE),
681
+ savedTokens: 0,
682
+ criticalErrorsPreserved: 0,
683
+ updatedToolOutput: rawOutput
684
+ };
685
+
686
+ const ftsEnabled =
687
+ postCfg.fts5Enabled !== false && options.enableFts5CliCompression !== false;
688
+ const minFtsBytes = Number(options.minBytes ?? postCfg.minBytesToCompress ?? 4096);
689
+
690
+ if (ftsEnabled && hasExplicitCwd && isShellTool && cmdStr && shellPolicy.allowFts5 !== false) {
691
+ try {
692
+ const ftsScrub = redactSecretsPure(stripAnsiAndSpinners(rawOutput));
693
+ const ansiCleanShell = ftsScrub.sanitized;
694
+ const criticalLines = extractCriticalErrorLines(ansiCleanShell);
695
+ const ftsDbPath =
696
+ options.dbPath ||
697
+ options.ftsDbPath ||
698
+ getDefaultToolLogsDbPath(options.homeDir || null);
699
+ const turnId = String(event.tool_use_id || event.turn_id || event.turnId || `turn-${Date.now()}`);
700
+ const ftsComp = compressCliOutputFts5Sync({
701
+ sessionId,
702
+ turnId,
703
+ command: cmdStr,
704
+ exitCode: typeof rawExit === 'number' ? rawExit : (failed ? 1 : 0),
705
+ rawOutput: ansiCleanShell,
706
+ dbPath: ftsDbPath,
707
+ homeDir: options.homeDir || null,
708
+ recordLedger: false,
709
+ minBytes: minFtsBytes,
710
+ minTokensSaved: Number(options.minTokensSaved ?? 500),
711
+ retentionDays: Number(postCfg.retentionDays ?? 30)
712
+ });
713
+
714
+ if (ftsComp.compressed && ftsComp.tokensSaved > 0) {
715
+ const guaranteedOutput = redactSecretsPure(
716
+ appendMissingCriticalLines(ftsComp.output, criticalLines)
717
+ ).sanitized;
718
+ const guaranteedTokens = Math.ceil(guaranteedOutput.length / CHARS_PER_TOKEN_ESTIMATE);
719
+ const rawTokens = Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE);
720
+ const netSavedTokens = Math.max(0, rawTokens - guaranteedTokens);
721
+ if (netSavedTokens > 0 && guaranteedOutput.length < rawOutput.length) {
722
+ finalOutput = guaranteedOutput;
723
+ ftsSavedTokens = netSavedTokens;
724
+ wasModified = true;
725
+ sanitized = {
726
+ ...sanitized,
727
+ sanitized: true,
728
+ offloaded: false,
729
+ redactedSecrets: ftsScrub.redactedCount,
730
+ finalTokens: guaranteedTokens,
731
+ savedTokens: netSavedTokens,
732
+ criticalErrorsPreserved: criticalLines.length,
733
+ turnId,
734
+ queryHandle: ftsComp.queryHandle,
735
+ updatedToolOutput: finalOutput
736
+ };
737
+ }
738
+ }
739
+ } catch (ftsErr) {
740
+ void ftsErr; // ignore: FTS5 failure fails open cleanly to sanitizer fallback
741
+ }
742
+ }
743
+
744
+ const isMcpTool = /^mcp__/i.test(toolName);
745
+ const postOutputMode = resolvePostOutputMode(postCfg);
746
+
747
+ if (ftsSavedTokens === 0) {
748
+ const allowOffload =
749
+ (isMcpTool || postOutputMode !== 'auto') &&
750
+ !(isShellTool && shellPolicy.allowOffload === false) &&
751
+ options.disableOffload !== true;
752
+ sanitized = sanitizePostOutputFallback(toolName, rawOutput, {
753
+ baseCwd: hasExplicitCwd ? baseCwd : null,
754
+ allowOffload,
755
+ offloadThresholdTokens: Number(
756
+ options.offloadThresholdTokens ?? postCfg.offloadThresholdTokens ?? OFFLOAD_TOKEN_THRESHOLD
757
+ )
758
+ });
759
+ finalOutput = sanitized.updatedToolOutput;
760
+ wasModified = sanitized.sanitized;
761
+ }
762
+
763
+ const hadSecretRedaction = Number(sanitized.redactedSecrets || 0) > 0;
764
+ const replacement =
765
+ !isMcpTool && wasModified && postOutputMode === 'replace'
766
+ ? buildReplacementToolOutput(event, finalOutput)
767
+ : { ok: false };
768
+ const wouldInflate =
769
+ !isMcpTool &&
770
+ !hadSecretRedaction &&
771
+ replacement.ok &&
772
+ finalOutput.length >= rawOutput.length;
773
+ const effectiveReplacementOk = replacement.ok && !wouldInflate;
774
+ const emitContext =
775
+ !isMcpTool &&
776
+ !effectiveReplacementOk &&
777
+ wasModified &&
778
+ postOutputMode === 'context';
779
+
780
+ if (!wasModified || (!isMcpTool && !effectiveReplacementOk && !emitContext)) {
781
+ return {
782
+ exitCode: 0,
783
+ stdout: '',
784
+ stderr: '',
785
+ sanitized
786
+ };
787
+ }
788
+
789
+ const outputAcceptedByHost = isMcpTool ? wasModified : effectiveReplacementOk;
790
+ const totalSavedTokens = outputAcceptedByHost
791
+ ? (ftsSavedTokens > 0 ? ftsSavedTokens : sanitized.savedTokens)
792
+ : 0;
793
+
794
+ if (totalSavedTokens > 0 && options.recordLedger !== false && (hasExplicitCwd || options.ledgerPath || options.recordLedger === true)) {
795
+ const rawEventModel =
796
+ typeof event.model === 'string'
797
+ ? event.model
798
+ : event.model?.id || event.model?.model_id || event.modelId || event.model_id;
799
+ const modelId = rawEventModel || 'claude-sonnet-5-5';
800
+ const usageSource = event.usage || event.context_window?.current_usage || {};
801
+ const totalPromptTokens = computeTotalPromptTokens(usageSource);
802
+ const rates = resolveEffectiveRates(modelId, totalPromptTokens, cwdOptions);
803
+ const computedSavedUSD =
804
+ rates && !rates.unknownModel && Number.isFinite(rates.inputPer1M)
805
+ ? Number(((totalSavedTokens / 1_000_000) * rates.inputPer1M).toFixed(6))
806
+ : 0;
807
+ const writeRatePer1M =
808
+ rates && !rates.unknownModel ? (rates.write5mPer1M ?? rates.inputPer1M) : 0;
809
+ const writeRateUSD =
810
+ Number.isFinite(writeRatePer1M) && writeRatePer1M > 0
811
+ ? Number(((totalSavedTokens / 1_000_000) * writeRatePer1M).toFixed(6))
812
+ : 0;
813
+
814
+ recordSavingsReceipt(
815
+ {
816
+ sessionId,
817
+ cwd: baseCwd,
818
+ modelId: rates.unknownModel ? (rates.rawModelId || modelId) : rates.modelId,
819
+ ledgerBucket: LEDGER_BUCKETS.AVOIDED_WRITE,
820
+ category: sanitized.offloaded
821
+ ? 'ARTIFACT_OFFLOAD_4K'
822
+ : ftsSavedTokens > 0
823
+ ? 'CLI_FTS5_COMPRESSED'
824
+ : 'LOSSLESS_POST_SANITIZER',
825
+ savedTokens: totalSavedTokens,
826
+ savedUSD: computedSavedUSD,
827
+ writeRateUSD,
828
+ detail: `${toolName} output compressed (+${totalSavedTokens} tokens saved)`
829
+ },
830
+ cwdOptions
831
+ );
832
+ }
833
+
834
+ const hookSpecificOutput = isMcpTool
835
+ ? {
836
+ hookEventName: 'PostToolUse',
837
+ updatedMCPToolOutput: finalOutput
838
+ }
839
+ : effectiveReplacementOk
840
+ ? {
841
+ hookEventName: 'PostToolUse',
842
+ updatedToolOutput: replacement.value
843
+ }
844
+ : {
845
+ hookEventName: 'PostToolUse',
846
+ additionalContext: finalOutput
847
+ };
848
+
849
+ return {
850
+ exitCode: 0,
851
+ stdout: JSON.stringify({ hookSpecificOutput }),
852
+ stderr: '',
853
+ sanitized,
854
+ hookSpecificOutput
855
+ };
856
+ }
857
+
858
+ export default {
859
+ OFFLOAD_TOKEN_THRESHOLD,
860
+ CHARS_PER_TOKEN_ESTIMATE,
861
+ DEFAULT_ARTIFACT_MAX_FILES,
862
+ DEFAULT_ARTIFACT_MAX_TOTAL_BYTES,
863
+ OPPORTUNISTIC_GC_INTERVAL_MS,
864
+ CRITICAL_ERROR_REGEX,
865
+ stripAnsiAndSpinners,
866
+ extractCriticalErrorLines,
867
+ extractPostToolText,
868
+ enforceArtifactDirCap,
869
+ runOpportunisticPostToolGc,
870
+ resolvePostOutputMode,
871
+ buildReplacementToolOutput,
872
+ isHostTruncatedShellOutput,
873
+ didToolExecutionFail,
874
+ runPostToolUseHook
875
+ };