burnoff 1.0.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 +75 -0
- package/README.md +94 -20
- package/bin/burnoff.mjs +129 -30
- package/hooks/hook-io.mjs +27 -18
- 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 +8 -5
- package/src/ci/ci-gate.mjs +84 -9
- package/src/ci/pr-cost.mjs +207 -22
- package/src/ci/team-digest.mjs +6 -4
- package/src/cli/audit.mjs +177 -23
- package/src/cli/doctor.mjs +230 -25
- package/src/cli/init.mjs +415 -75
- package/src/cli/startup-audit.mjs +2824 -0
- 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/catalog.json +188 -45
- package/src/config/loader.mjs +96 -13
- package/src/config/paths.mjs +92 -2
- package/src/config/policy.mjs +103 -17
- package/src/config/pricing.mjs +1033 -0
- package/src/config/uncached-attribution.mjs +719 -0
- package/src/guards/loop-breaker.mjs +267 -24
- package/src/guards/post-tool-engine.mjs +316 -35
- package/src/guards/pre-tool-engine.mjs +389 -130
- package/src/guards/read-clamp.mjs +149 -75
- package/src/guards/session-hook.mjs +207 -0
- package/src/guards/shell-guard.mjs +610 -74
- 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/atomic-io.mjs +2 -2
- package/src/storage/file-lock.mjs +66 -13
- package/src/storage/fts5-archive.mjs +31 -16
- package/src/storage/jsonl-parser.mjs +209 -20
- package/src/storage/ledger.mjs +15 -10
- package/src/storage/sqlite-client.mjs +35 -11
- package/hooks/hooks.json +0 -12
|
@@ -9,15 +9,24 @@
|
|
|
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';
|
|
14
|
+
import { getBurnoffCacheDir, getHomeDir } from '../config/paths.mjs';
|
|
13
15
|
import { computeTotalPromptTokens, resolveEffectiveRates } from '../config/loader.mjs';
|
|
14
16
|
import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
|
|
15
|
-
import {
|
|
16
|
-
|
|
17
|
-
|
|
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';
|
|
18
24
|
|
|
19
25
|
export const OFFLOAD_TOKEN_THRESHOLD = 4000;
|
|
20
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;
|
|
21
30
|
|
|
22
31
|
export const CRITICAL_ERROR_REGEX =
|
|
23
32
|
/(Error|Exception|FAIL|error\[E\d+\]|panic:|ERR!|ERESOLVE|AssertionError|SyntaxError)/i;
|
|
@@ -37,6 +46,7 @@ const HTML_BOILERPLATE_BLOCK_REGEX =
|
|
|
37
46
|
const SHELL_TOOL_NAME_RE = /^(?:Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash)$/i;
|
|
38
47
|
const PROTECTED_WORKSPACE_TOOL_RE =
|
|
39
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;
|
|
40
50
|
const ELIGIBLE_POST_TOOL_RE =
|
|
41
51
|
/^(?:Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash|WebFetch|Grep|Glob|Task|Agent|mcp__.+)$/i;
|
|
42
52
|
|
|
@@ -147,7 +157,11 @@ export function isHostTruncatedShellOutput(toolName, rawOutput) {
|
|
|
147
157
|
return String(rawOutput || '').length >= resolveHostShellOutputCap() - 100;
|
|
148
158
|
}
|
|
149
159
|
|
|
150
|
-
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
|
+
}
|
|
151
165
|
if (
|
|
152
166
|
event.is_error === true ||
|
|
153
167
|
event.isError === true ||
|
|
@@ -174,20 +188,210 @@ export function didToolExecutionFail(event = {}) {
|
|
|
174
188
|
return true;
|
|
175
189
|
}
|
|
176
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
|
+
}
|
|
177
210
|
return false;
|
|
178
211
|
}
|
|
179
212
|
|
|
180
213
|
function resolvePostOutputMode(policyPost = {}) {
|
|
181
214
|
const envRaw = String(globalThis.process?.env?.BURNOFF_POST_OUTPUT_MODE || '').trim().toLowerCase();
|
|
182
|
-
if (envRaw === 'context') return 'context';
|
|
183
|
-
if (envRaw === 'replace') return 'replace';
|
|
215
|
+
if (envRaw === 'context' || envRaw === 'additionalcontext') return 'context';
|
|
216
|
+
if (envRaw === 'replace' || envRaw === 'updatedtooloutput') return 'replace';
|
|
217
|
+
if (envRaw === 'auto') return 'auto';
|
|
184
218
|
const cfgMode = String(policyPost.outputMode || 'auto').trim().toLowerCase();
|
|
185
|
-
|
|
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
|
+
};
|
|
186
384
|
}
|
|
187
385
|
|
|
188
|
-
function offloadOversizedOutput(
|
|
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
|
+
) {
|
|
189
394
|
const sha256 = crypto.createHash('sha256').update(cleanText, 'utf8').digest('hex');
|
|
190
|
-
const relativeArtifactPath = `.claude/cache/artifacts/burnoff_${sha256}.txt`;
|
|
191
395
|
const candidateArtifactPath = path.join(
|
|
192
396
|
baseCwd,
|
|
193
397
|
'.claude',
|
|
@@ -198,6 +402,11 @@ function offloadOversizedOutput(toolName, cleanText, filteredLines, criticalErro
|
|
|
198
402
|
|
|
199
403
|
try {
|
|
200
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
|
+
});
|
|
201
410
|
} catch (err) {
|
|
202
411
|
void err; // ignore: fail-open offload preserves ANSI-cleaned output in memory
|
|
203
412
|
return { offloaded: false, artifactPath: null, output: cleanText };
|
|
@@ -208,8 +417,7 @@ function offloadOversizedOutput(toolName, cleanText, filteredLines, criticalErro
|
|
|
208
417
|
const nonEmpty = filteredLines.filter((l) => l.trim().length > 0);
|
|
209
418
|
const sampleLines = nonEmpty.slice(0, 3);
|
|
210
419
|
const summaryParts = [
|
|
211
|
-
`[Burnoff Artifact Offload: ${originalTokens.toLocaleString('en-US')} tokens (${rawLines.length} lines)
|
|
212
|
-
`Full lossless ${toolName} output saved to: ${candidateArtifactPath}`,
|
|
420
|
+
`[Burnoff Artifact Offload: ${originalTokens.toLocaleString('en-US')} tokens (${rawLines.length} lines) archived locally]`,
|
|
213
421
|
`Sample lines (1..${sampleLines.length}):`,
|
|
214
422
|
...sampleLines.map((l, idx) => ` ${idx + 1}: ${l.slice(0, 200)}`)
|
|
215
423
|
];
|
|
@@ -305,39 +513,52 @@ function appendMissingCriticalLines(summaryText, criticalLines) {
|
|
|
305
513
|
}
|
|
306
514
|
|
|
307
515
|
/**
|
|
308
|
-
* Evaluates a `PostToolUse` hook event and returns
|
|
516
|
+
* Evaluates a `PostToolUse` hook event and returns the host-formatted output contract.
|
|
309
517
|
*/
|
|
310
518
|
export function runPostToolUseHook(event = {}, options = {}) {
|
|
311
|
-
const
|
|
312
|
-
|
|
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);
|
|
313
529
|
const tier1Active = Boolean(
|
|
314
530
|
options.tier1Active ||
|
|
315
|
-
|
|
531
|
+
rawEvent.tier1Active ||
|
|
316
532
|
globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
|
|
317
533
|
);
|
|
534
|
+
const failed = canonical.failed === true || didToolExecutionFail(rawEvent, toolName);
|
|
535
|
+
|
|
318
536
|
if (
|
|
319
537
|
tier1Active &&
|
|
320
538
|
/^(?:Grep|Glob)$/i.test(toolName) &&
|
|
321
539
|
rawOutput.length < 16_000 &&
|
|
322
|
-
!
|
|
540
|
+
!failed
|
|
323
541
|
) {
|
|
324
|
-
return {
|
|
542
|
+
return finalize({
|
|
325
543
|
exitCode: 0,
|
|
326
544
|
stdout: '',
|
|
327
545
|
stderr: '',
|
|
328
546
|
fastPath: 'tier1_active',
|
|
329
547
|
sanitized: { modified: false, offloaded: false, savedTokens: 0 }
|
|
330
|
-
};
|
|
548
|
+
});
|
|
331
549
|
}
|
|
332
550
|
|
|
333
|
-
const sessionId = String(
|
|
334
|
-
const hasExplicitCwd = Boolean(
|
|
335
|
-
const baseCwd = path.resolve(String(
|
|
336
|
-
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 };
|
|
337
555
|
const policy = options.policy || loadBurnoffPolicy(baseCwd);
|
|
338
556
|
const postCfg = policy.postTool || {};
|
|
339
557
|
|
|
340
|
-
const toolInput =
|
|
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();
|
|
341
562
|
const cmdStr = String(
|
|
342
563
|
toolInput.command || toolInput.CommandLine || toolInput.cmd || event.command || ''
|
|
343
564
|
);
|
|
@@ -346,11 +567,10 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
346
567
|
event.exitCode ??
|
|
347
568
|
event.tool_response?.exit_code ??
|
|
348
569
|
event.tool_response?.exitCode;
|
|
349
|
-
const failed = didToolExecutionFail(event);
|
|
350
570
|
|
|
351
571
|
const shouldPersistState =
|
|
352
572
|
options.persistState !== false &&
|
|
353
|
-
Boolean(
|
|
573
|
+
Boolean(canonical.cwd || options.cwd || options.breakerStatePath || options.persistState);
|
|
354
574
|
|
|
355
575
|
if (shouldPersistState) {
|
|
356
576
|
recordToolOutcomeAtomicSync(
|
|
@@ -358,11 +578,56 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
358
578
|
{
|
|
359
579
|
toolName,
|
|
360
580
|
command: cmdStr,
|
|
581
|
+
filePath,
|
|
361
582
|
failed,
|
|
362
583
|
nowMs: options.nowMs ?? Date.now()
|
|
363
584
|
},
|
|
364
585
|
cwdOptions
|
|
365
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
|
+
});
|
|
366
631
|
}
|
|
367
632
|
|
|
368
633
|
if (isHostTruncatedShellOutput(toolName, rawOutput)) {
|
|
@@ -375,7 +640,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
375
640
|
};
|
|
376
641
|
}
|
|
377
642
|
|
|
378
|
-
const unprefixed = toolName.replace(/^
|
|
643
|
+
const unprefixed = toolName.replace(/^mcp__[a-zA-Z0-9_-]+__/i, '');
|
|
379
644
|
if (PROTECTED_WORKSPACE_TOOL_RE.test(unprefixed) || !ELIGIBLE_POST_TOOL_RE.test(toolName)) {
|
|
380
645
|
return {
|
|
381
646
|
exitCode: 0,
|
|
@@ -416,7 +681,9 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
416
681
|
const ansiCleanShell = stripAnsiAndSpinners(rawOutput);
|
|
417
682
|
const criticalLines = extractCriticalErrorLines(ansiCleanShell);
|
|
418
683
|
const ftsDbPath =
|
|
419
|
-
options.dbPath ||
|
|
684
|
+
options.dbPath ||
|
|
685
|
+
options.ftsDbPath ||
|
|
686
|
+
getDefaultToolLogsDbPath(options.homeDir || null);
|
|
420
687
|
const turnId = String(event.tool_use_id || event.turn_id || event.turnId || `turn-${Date.now()}`);
|
|
421
688
|
const ftsComp = compressCliOutputFts5Sync({
|
|
422
689
|
sessionId,
|
|
@@ -425,6 +692,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
425
692
|
exitCode: typeof rawExit === 'number' ? rawExit : (failed ? 1 : 0),
|
|
426
693
|
rawOutput: ansiCleanShell,
|
|
427
694
|
dbPath: ftsDbPath,
|
|
695
|
+
homeDir: options.homeDir || null,
|
|
428
696
|
recordLedger: false,
|
|
429
697
|
minBytes: minFtsBytes,
|
|
430
698
|
minTokensSaved: Number(options.minTokensSaved ?? 500),
|
|
@@ -458,9 +726,14 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
458
726
|
}
|
|
459
727
|
}
|
|
460
728
|
|
|
729
|
+
const isMcpTool = /^mcp__/i.test(toolName);
|
|
730
|
+
const postOutputMode = resolvePostOutputMode(postCfg);
|
|
731
|
+
|
|
461
732
|
if (ftsSavedTokens === 0) {
|
|
462
733
|
const allowOffload =
|
|
463
|
-
|
|
734
|
+
(isMcpTool || postOutputMode !== 'auto') &&
|
|
735
|
+
!(isShellTool && shellPolicy.allowOffload === false) &&
|
|
736
|
+
options.disableOffload !== true;
|
|
464
737
|
sanitized = sanitizePostOutputFallback(toolName, rawOutput, {
|
|
465
738
|
baseCwd: hasExplicitCwd ? baseCwd : null,
|
|
466
739
|
allowOffload,
|
|
@@ -472,17 +745,19 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
472
745
|
wasModified = sanitized.sanitized;
|
|
473
746
|
}
|
|
474
747
|
|
|
475
|
-
const isMcpTool = /^mcp__/i.test(toolName);
|
|
476
|
-
const postOutputMode = resolvePostOutputMode(postCfg);
|
|
477
748
|
const replacement =
|
|
478
749
|
!isMcpTool && wasModified && postOutputMode === 'replace'
|
|
479
750
|
? buildReplacementToolOutput(event, finalOutput)
|
|
480
751
|
: { ok: false };
|
|
481
752
|
const wouldInflate = !isMcpTool && replacement.ok && finalOutput.length >= rawOutput.length;
|
|
482
753
|
const effectiveReplacementOk = replacement.ok && !wouldInflate;
|
|
483
|
-
const
|
|
754
|
+
const emitContext =
|
|
755
|
+
!isMcpTool &&
|
|
756
|
+
!effectiveReplacementOk &&
|
|
757
|
+
wasModified &&
|
|
758
|
+
postOutputMode === 'context';
|
|
484
759
|
|
|
485
|
-
if (!wasModified || (!isMcpTool && !effectiveReplacementOk && !
|
|
760
|
+
if (!wasModified || (!isMcpTool && !effectiveReplacementOk && !emitContext)) {
|
|
486
761
|
return {
|
|
487
762
|
exitCode: 0,
|
|
488
763
|
stdout: '',
|
|
@@ -491,8 +766,8 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
491
766
|
};
|
|
492
767
|
}
|
|
493
768
|
|
|
494
|
-
const
|
|
495
|
-
const totalSavedTokens =
|
|
769
|
+
const outputAcceptedByHost = isMcpTool ? wasModified : effectiveReplacementOk;
|
|
770
|
+
const totalSavedTokens = outputAcceptedByHost
|
|
496
771
|
? (ftsSavedTokens > 0 ? ftsSavedTokens : sanitized.savedTokens)
|
|
497
772
|
: 0;
|
|
498
773
|
|
|
@@ -501,7 +776,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
501
776
|
typeof event.model === 'string'
|
|
502
777
|
? event.model
|
|
503
778
|
: event.model?.id || event.model?.model_id || event.modelId || event.model_id;
|
|
504
|
-
const modelId = rawEventModel || 'claude-sonnet-
|
|
779
|
+
const modelId = rawEventModel || 'claude-sonnet-5-5';
|
|
505
780
|
const usageSource = event.usage || event.context_window?.current_usage || {};
|
|
506
781
|
const totalPromptTokens = computeTotalPromptTokens(usageSource);
|
|
507
782
|
const rates = resolveEffectiveRates(modelId, totalPromptTokens, cwdOptions);
|
|
@@ -519,6 +794,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
519
794
|
recordSavingsReceipt(
|
|
520
795
|
{
|
|
521
796
|
sessionId,
|
|
797
|
+
cwd: baseCwd,
|
|
522
798
|
modelId: rates.unknownModel ? (rates.rawModelId || modelId) : rates.modelId,
|
|
523
799
|
ledgerBucket: LEDGER_BUCKETS.AVOIDED_WRITE,
|
|
524
800
|
category: sanitized.offloaded
|
|
@@ -562,10 +838,15 @@ export function runPostToolUseHook(event = {}, options = {}) {
|
|
|
562
838
|
export default {
|
|
563
839
|
OFFLOAD_TOKEN_THRESHOLD,
|
|
564
840
|
CHARS_PER_TOKEN_ESTIMATE,
|
|
841
|
+
DEFAULT_ARTIFACT_MAX_FILES,
|
|
842
|
+
DEFAULT_ARTIFACT_MAX_TOTAL_BYTES,
|
|
843
|
+
OPPORTUNISTIC_GC_INTERVAL_MS,
|
|
565
844
|
CRITICAL_ERROR_REGEX,
|
|
566
845
|
stripAnsiAndSpinners,
|
|
567
846
|
extractCriticalErrorLines,
|
|
568
847
|
extractPostToolText,
|
|
848
|
+
enforceArtifactDirCap,
|
|
849
|
+
runOpportunisticPostToolGc,
|
|
569
850
|
buildReplacementToolOutput,
|
|
570
851
|
isHostTruncatedShellOutput,
|
|
571
852
|
didToolExecutionFail,
|