burnoff 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/burnoff-pr-gate.yml +3 -3
- package/README.md +66 -78
- package/bin/burnoff.mjs +67 -23
- package/hooks/hook-io.mjs +19 -7
- package/hooks/post-tool-use.mjs +33 -26
- package/hooks/pre-tool-use.mjs +43 -41
- package/hooks/session-lifecycle.mjs +40 -0
- package/package.json +7 -5
- package/src/ci/ci-gate.mjs +22 -0
- package/src/ci/pr-cost.mjs +42 -10
- package/src/ci/team-digest.mjs +5 -3
- package/src/cli/audit.mjs +103 -18
- package/src/cli/doctor.mjs +209 -14
- package/src/cli/init.mjs +349 -96
- package/src/cli/startup-audit.mjs +500 -24
- package/src/clients/antigravity.mjs +285 -0
- package/src/clients/claude-code.mjs +180 -0
- package/src/clients/detect.mjs +64 -0
- package/src/config/loader.mjs +11 -4
- package/src/config/paths.mjs +62 -2
- package/src/config/policy.mjs +34 -5
- package/src/config/pricing.mjs +16 -5
- package/src/guards/loop-breaker.mjs +198 -13
- package/src/guards/post-tool-engine.mjs +289 -29
- package/src/guards/pre-tool-engine.mjs +336 -129
- package/src/guards/read-clamp.mjs +78 -18
- package/src/guards/session-hook.mjs +207 -0
- package/src/guards/shell-guard.mjs +583 -73
- package/src/ipc/daemon.mjs +50 -8
- package/src/ipc/fast-client.mjs +62 -5
- package/src/ipc/protocol.mjs +1 -1
- package/src/storage/antigravity-parser.mjs +258 -0
- package/src/storage/file-lock.mjs +13 -4
- package/src/storage/fts5-archive.mjs +4 -4
- package/src/storage/jsonl-parser.mjs +7 -1
- package/src/storage/ledger.mjs +10 -3
- package/src/storage/sqlite-client.mjs +4 -2
- package/hooks/hooks.json +0 -12
|
@@ -9,8 +9,9 @@
|
|
|
9
9
|
import fs from 'node:fs';
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import crypto from 'node:crypto';
|
|
12
|
+
import { getClientAdapter, normalizeHookEvent } from '../clients/detect.mjs';
|
|
12
13
|
import { loadBurnoffPolicy } from '../config/policy.mjs';
|
|
13
|
-
import { getHomeDir } from '../config/paths.mjs';
|
|
14
|
+
import { getBurnoffCacheDir, getHomeDir } from '../config/paths.mjs';
|
|
14
15
|
import { computeTotalPromptTokens, resolveEffectiveRates } from '../config/loader.mjs';
|
|
15
16
|
import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
|
|
16
17
|
import {
|
|
@@ -18,11 +19,14 @@ import {
|
|
|
18
19
|
classifyShellPostToolPolicy,
|
|
19
20
|
getDefaultToolLogsDbPath
|
|
20
21
|
} from '../storage/fts5-archive.mjs';
|
|
21
|
-
import { recordSavingsReceipt, LEDGER_BUCKETS } from '../storage/ledger.mjs';
|
|
22
|
-
import { recordToolOutcomeAtomicSync } from './loop-breaker.mjs';
|
|
22
|
+
import { recordSavingsReceipt, rotateMonthlyLedger, LEDGER_BUCKETS } from '../storage/ledger.mjs';
|
|
23
|
+
import { recordToolOutcomeAtomicSync, releaseScopeLock } from './loop-breaker.mjs';
|
|
23
24
|
|
|
24
25
|
export const OFFLOAD_TOKEN_THRESHOLD = 4000;
|
|
25
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;
|
|
26
30
|
|
|
27
31
|
export const CRITICAL_ERROR_REGEX =
|
|
28
32
|
/(Error|Exception|FAIL|error\[E\d+\]|panic:|ERR!|ERESOLVE|AssertionError|SyntaxError)/i;
|
|
@@ -42,6 +46,7 @@ const HTML_BOILERPLATE_BLOCK_REGEX =
|
|
|
42
46
|
const SHELL_TOOL_NAME_RE = /^(?:Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash)$/i;
|
|
43
47
|
const PROTECTED_WORKSPACE_TOOL_RE =
|
|
44
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;
|
|
45
50
|
const ELIGIBLE_POST_TOOL_RE =
|
|
46
51
|
/^(?:Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash|WebFetch|Grep|Glob|Task|Agent|mcp__.+)$/i;
|
|
47
52
|
|
|
@@ -152,7 +157,11 @@ export function isHostTruncatedShellOutput(toolName, rawOutput) {
|
|
|
152
157
|
return String(rawOutput || '').length >= resolveHostShellOutputCap() - 100;
|
|
153
158
|
}
|
|
154
159
|
|
|
155
|
-
export function didToolExecutionFail(event = {}) {
|
|
160
|
+
export function didToolExecutionFail(event = {}, toolNameHint = '') {
|
|
161
|
+
const hookEventName = String(event.hook_event_name || event.hookEventName || '');
|
|
162
|
+
if (hookEventName === 'PostToolUseFailure') {
|
|
163
|
+
return true;
|
|
164
|
+
}
|
|
156
165
|
if (
|
|
157
166
|
event.is_error === true ||
|
|
158
167
|
event.isError === true ||
|
|
@@ -179,6 +188,25 @@ export function didToolExecutionFail(event = {}) {
|
|
|
179
188
|
return true;
|
|
180
189
|
}
|
|
181
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
|
+
}
|
|
182
210
|
return false;
|
|
183
211
|
}
|
|
184
212
|
|
|
@@ -193,9 +221,177 @@ function resolvePostOutputMode(policyPost = {}) {
|
|
|
193
221
|
return 'auto';
|
|
194
222
|
}
|
|
195
223
|
|
|
196
|
-
function
|
|
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
|
+
) {
|
|
197
394
|
const sha256 = crypto.createHash('sha256').update(cleanText, 'utf8').digest('hex');
|
|
198
|
-
const relativeArtifactPath = `.claude/cache/artifacts/burnoff_${sha256}.txt`;
|
|
199
395
|
const candidateArtifactPath = path.join(
|
|
200
396
|
baseCwd,
|
|
201
397
|
'.claude',
|
|
@@ -206,6 +402,11 @@ function offloadOversizedOutput(toolName, cleanText, filteredLines, criticalErro
|
|
|
206
402
|
|
|
207
403
|
try {
|
|
208
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
|
+
});
|
|
209
410
|
} catch (err) {
|
|
210
411
|
void err; // ignore: fail-open offload preserves ANSI-cleaned output in memory
|
|
211
412
|
return { offloaded: false, artifactPath: null, output: cleanText };
|
|
@@ -216,8 +417,7 @@ function offloadOversizedOutput(toolName, cleanText, filteredLines, criticalErro
|
|
|
216
417
|
const nonEmpty = filteredLines.filter((l) => l.trim().length > 0);
|
|
217
418
|
const sampleLines = nonEmpty.slice(0, 3);
|
|
218
419
|
const summaryParts = [
|
|
219
|
-
`[Burnoff Artifact Offload: ${originalTokens.toLocaleString('en-US')} tokens (${rawLines.length} lines)
|
|
220
|
-
`Full lossless ${toolName} output saved to: ${candidateArtifactPath}`,
|
|
420
|
+
`[Burnoff Artifact Offload: ${originalTokens.toLocaleString('en-US')} tokens (${rawLines.length} lines) archived locally]`,
|
|
221
421
|
`Sample lines (1..${sampleLines.length}):`,
|
|
222
422
|
...sampleLines.map((l, idx) => ` ${idx + 1}: ${l.slice(0, 200)}`)
|
|
223
423
|
];
|
|
@@ -313,39 +513,49 @@ function appendMissingCriticalLines(summaryText, criticalLines) {
|
|
|
313
513
|
}
|
|
314
514
|
|
|
315
515
|
/**
|
|
316
|
-
* Evaluates a `PostToolUse` hook event and returns
|
|
516
|
+
* Evaluates a `PostToolUse` hook event and returns the host-formatted output contract.
|
|
317
517
|
*/
|
|
318
518
|
export function runPostToolUseHook(event = {}, options = {}) {
|
|
319
|
-
const
|
|
320
|
-
|
|
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);
|
|
321
529
|
const tier1Active = Boolean(
|
|
322
530
|
options.tier1Active ||
|
|
323
|
-
|
|
531
|
+
rawEvent.tier1Active ||
|
|
324
532
|
globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
|
|
325
533
|
);
|
|
534
|
+
const failed = canonical.failed === true || didToolExecutionFail(rawEvent, toolName);
|
|
535
|
+
|
|
326
536
|
if (
|
|
327
537
|
tier1Active &&
|
|
328
538
|
/^(?:Grep|Glob)$/i.test(toolName) &&
|
|
329
539
|
rawOutput.length < 16_000 &&
|
|
330
|
-
!
|
|
540
|
+
!failed
|
|
331
541
|
) {
|
|
332
|
-
return {
|
|
542
|
+
return finalize({
|
|
333
543
|
exitCode: 0,
|
|
334
544
|
stdout: '',
|
|
335
545
|
stderr: '',
|
|
336
546
|
fastPath: 'tier1_active',
|
|
337
547
|
sanitized: { modified: false, offloaded: false, savedTokens: 0 }
|
|
338
|
-
};
|
|
548
|
+
});
|
|
339
549
|
}
|
|
340
550
|
|
|
341
|
-
const sessionId = String(
|
|
342
|
-
const hasExplicitCwd = Boolean(
|
|
343
|
-
const baseCwd = path.resolve(String(
|
|
344
|
-
const cwdOptions = hasExplicitCwd ? { ...options, cwd: baseCwd } : options;
|
|
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 };
|
|
345
555
|
const policy = options.policy || loadBurnoffPolicy(baseCwd);
|
|
346
556
|
const postCfg = policy.postTool || {};
|
|
347
557
|
|
|
348
|
-
const toolInput =
|
|
558
|
+
const toolInput = canonical.toolInput || {};
|
|
349
559
|
const filePath = String(
|
|
350
560
|
toolInput.file_path || toolInput.notebook_path || toolInput.filePath || toolInput.path || toolInput.Path || toolInput.TargetFile || event.filePath || ''
|
|
351
561
|
).trim();
|
|
@@ -357,11 +567,10 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
357
567
|
event.exitCode ??
|
|
358
568
|
event.tool_response?.exit_code ??
|
|
359
569
|
event.tool_response?.exitCode;
|
|
360
|
-
const failed = didToolExecutionFail(event);
|
|
361
570
|
|
|
362
571
|
const shouldPersistState =
|
|
363
572
|
options.persistState !== false &&
|
|
364
|
-
Boolean(
|
|
573
|
+
Boolean(canonical.cwd || options.cwd || options.breakerStatePath || options.persistState);
|
|
365
574
|
|
|
366
575
|
if (shouldPersistState) {
|
|
367
576
|
recordToolOutcomeAtomicSync(
|
|
@@ -375,6 +584,50 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
375
584
|
},
|
|
376
585
|
cwdOptions
|
|
377
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
|
+
});
|
|
378
631
|
}
|
|
379
632
|
|
|
380
633
|
if (isHostTruncatedShellOutput(toolName, rawOutput)) {
|
|
@@ -430,7 +683,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
430
683
|
const ftsDbPath =
|
|
431
684
|
options.dbPath ||
|
|
432
685
|
options.ftsDbPath ||
|
|
433
|
-
getDefaultToolLogsDbPath(options.homeDir ||
|
|
686
|
+
getDefaultToolLogsDbPath(options.homeDir || null);
|
|
434
687
|
const turnId = String(event.tool_use_id || event.turn_id || event.turnId || `turn-${Date.now()}`);
|
|
435
688
|
const ftsComp = compressCliOutputFts5Sync({
|
|
436
689
|
sessionId,
|
|
@@ -439,7 +692,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
439
692
|
exitCode: typeof rawExit === 'number' ? rawExit : (failed ? 1 : 0),
|
|
440
693
|
rawOutput: ansiCleanShell,
|
|
441
694
|
dbPath: ftsDbPath,
|
|
442
|
-
homeDir: options.homeDir ||
|
|
695
|
+
homeDir: options.homeDir || null,
|
|
443
696
|
recordLedger: false,
|
|
444
697
|
minBytes: minFtsBytes,
|
|
445
698
|
minTokensSaved: Number(options.minTokensSaved ?? 500),
|
|
@@ -473,9 +726,14 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
473
726
|
}
|
|
474
727
|
}
|
|
475
728
|
|
|
729
|
+
const isMcpTool = /^mcp__/i.test(toolName);
|
|
730
|
+
const postOutputMode = resolvePostOutputMode(postCfg);
|
|
731
|
+
|
|
476
732
|
if (ftsSavedTokens === 0) {
|
|
477
733
|
const allowOffload =
|
|
478
|
-
|
|
734
|
+
(isMcpTool || postOutputMode !== 'auto') &&
|
|
735
|
+
!(isShellTool && shellPolicy.allowOffload === false) &&
|
|
736
|
+
options.disableOffload !== true;
|
|
479
737
|
sanitized = sanitizePostOutputFallback(toolName, rawOutput, {
|
|
480
738
|
baseCwd: hasExplicitCwd ? baseCwd : null,
|
|
481
739
|
allowOffload,
|
|
@@ -487,20 +745,17 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
487
745
|
wasModified = sanitized.sanitized;
|
|
488
746
|
}
|
|
489
747
|
|
|
490
|
-
const isMcpTool = /^mcp__/i.test(toolName);
|
|
491
|
-
const postOutputMode = resolvePostOutputMode(postCfg);
|
|
492
748
|
const replacement =
|
|
493
749
|
!isMcpTool && wasModified && postOutputMode === 'replace'
|
|
494
750
|
? buildReplacementToolOutput(event, finalOutput)
|
|
495
751
|
: { ok: false };
|
|
496
752
|
const wouldInflate = !isMcpTool && replacement.ok && finalOutput.length >= rawOutput.length;
|
|
497
753
|
const effectiveReplacementOk = replacement.ok && !wouldInflate;
|
|
498
|
-
const hasActionablePointer = Boolean(sanitized.offloaded || ftsSavedTokens > 0);
|
|
499
754
|
const emitContext =
|
|
500
755
|
!isMcpTool &&
|
|
501
756
|
!effectiveReplacementOk &&
|
|
502
757
|
wasModified &&
|
|
503
|
-
|
|
758
|
+
postOutputMode === 'context';
|
|
504
759
|
|
|
505
760
|
if (!wasModified || (!isMcpTool && !effectiveReplacementOk && !emitContext)) {
|
|
506
761
|
return {
|
|
@@ -583,10 +838,15 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
583
838
|
export default {
|
|
584
839
|
OFFLOAD_TOKEN_THRESHOLD,
|
|
585
840
|
CHARS_PER_TOKEN_ESTIMATE,
|
|
841
|
+
DEFAULT_ARTIFACT_MAX_FILES,
|
|
842
|
+
DEFAULT_ARTIFACT_MAX_TOTAL_BYTES,
|
|
843
|
+
OPPORTUNISTIC_GC_INTERVAL_MS,
|
|
586
844
|
CRITICAL_ERROR_REGEX,
|
|
587
845
|
stripAnsiAndSpinners,
|
|
588
846
|
extractCriticalErrorLines,
|
|
589
847
|
extractPostToolText,
|
|
848
|
+
enforceArtifactDirCap,
|
|
849
|
+
runOpportunisticPostToolGc,
|
|
590
850
|
buildReplacementToolOutput,
|
|
591
851
|
isHostTruncatedShellOutput,
|
|
592
852
|
didToolExecutionFail,
|