burnoff 1.4.1 → 2.1.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/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/burnoff-pr-gate.yml +5 -3
- package/.github/workflows/burnoff-startup-lint.yml +2 -2
- package/CHANGELOG.md +74 -0
- package/README.md +187 -213
- package/SECURITY.md +38 -0
- package/bin/burnoff.mjs +307 -32
- package/commands/burnoff.md +6 -4
- package/docs/CLAUDE_CODE_PLUGIN.md +29 -28
- package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
- package/hooks/hook-io.mjs +216 -11
- package/hooks/hooks.json +44 -0
- package/hooks/post-tool-use.mjs +3 -1
- package/hooks/pre-tool-use.mjs +47 -8
- package/hooks/session-lifecycle.mjs +24 -3
- package/hooks/user-prompt-submit.mjs +98 -0
- package/package.json +6 -4
- package/scripts/bench-hooks.mjs +34 -3
- package/scripts/bench-savings.mjs +318 -0
- package/scripts/burnoff-statusline.mjs +138 -6
- package/src/ci/ci-gate.mjs +199 -13
- package/src/ci/pr-cost.mjs +417 -45
- package/src/ci/pr-summary.mjs +467 -0
- package/src/cli/audit.mjs +179 -28
- package/src/cli/doctor.mjs +32 -6
- package/src/cli/hook-health.mjs +9 -1
- package/src/cli/init.mjs +226 -39
- package/src/cli/preview.mjs +299 -0
- package/src/cli/startup-audit/formatter.mjs +248 -0
- package/src/cli/startup-audit/jsonc.mjs +601 -0
- package/src/cli/startup-audit/mcp-audit.mjs +735 -0
- package/src/cli/startup-audit/rules-hygiene.mjs +645 -0
- package/src/cli/startup-audit/telemetry-scan.mjs +975 -0
- package/src/cli/startup-audit.mjs +451 -2471
- package/src/clients/claude-code.mjs +41 -4
- package/src/config/catalog.json +295 -0
- package/src/config/effort.mjs +145 -0
- package/src/config/harness-quirks.mjs +340 -0
- package/src/config/loader.mjs +27 -2
- package/src/config/policy.mjs +81 -9
- package/src/config/pricing.mjs +247 -19
- package/src/config/semver.mjs +25 -0
- package/src/config/uncached-attribution.mjs +280 -41
- package/src/guards/compaction-baton.mjs +248 -0
- package/src/guards/loop-breaker.mjs +328 -47
- package/src/guards/model-switch-hook.mjs +126 -0
- package/src/guards/phase5-detectors.mjs +275 -21
- package/src/guards/post-tool-engine.mjs +333 -11
- package/src/guards/pre-tool-engine.mjs +607 -45
- package/src/guards/prefix-guard.mjs +609 -0
- package/src/guards/prompt-guard.mjs +309 -0
- package/src/guards/read-clamp.mjs +192 -8
- package/src/guards/session-hook.mjs +149 -7
- package/src/guards/shell-guard.mjs +56 -5
- package/src/guards/snooze.mjs +169 -5
- package/src/ipc/daemon.mjs +76 -0
- package/src/ipc/fast-client.mjs +165 -4
- package/src/ipc/protocol.mjs +16 -3
- package/src/storage/antigravity-parser.mjs +16 -2
- package/src/storage/file-lock.mjs +16 -3
- package/src/storage/jsonl-parser.mjs +133 -22
- package/src/storage/telemetry-metrics.mjs +254 -4
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file hooks/user-prompt-submit.mjs
|
|
3
|
+
* Thin Tier-2 Command Hook Fast-Shell for `UserPromptSubmit`.
|
|
4
|
+
* Fails open (`exitCode: 0`) so user prompts are never blocked by hook errors.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
isCliEntrypoint,
|
|
9
|
+
readStdinJsonAsync,
|
|
10
|
+
exitPassThrough,
|
|
11
|
+
exitDiagnosticZero,
|
|
12
|
+
exitWithStdoutJson,
|
|
13
|
+
recordHookTrace
|
|
14
|
+
} from './hook-io.mjs';
|
|
15
|
+
import { tryFastDaemonRpc } from '../src/ipc/fast-client.mjs';
|
|
16
|
+
|
|
17
|
+
let _promptGuardMod = null;
|
|
18
|
+
if (!isCliEntrypoint(import.meta.url)) {
|
|
19
|
+
_promptGuardMod = await import('../src/guards/prompt-guard.mjs');
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function runUserPromptSubmitHookAsync(event = {}, options = {}) {
|
|
23
|
+
if (!_promptGuardMod) {
|
|
24
|
+
_promptGuardMod = await import('../src/guards/prompt-guard.mjs');
|
|
25
|
+
}
|
|
26
|
+
return _promptGuardMod.runUserPromptSubmitHook(event, options);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function runUserPromptSubmitHook(event = {}, options = {}) {
|
|
30
|
+
if (!_promptGuardMod) {
|
|
31
|
+
throw new Error('prompt-guard.mjs is not loaded; use runUserPromptSubmitHookAsync() when invoked as CLI.');
|
|
32
|
+
}
|
|
33
|
+
return _promptGuardMod.runUserPromptSubmitHook(event, options);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function executeUserPromptSubmitCli(cliOptions = {}) {
|
|
37
|
+
const readPayload = cliOptions.readPayload || readStdinJsonAsync;
|
|
38
|
+
const ioOverride = cliOptions.ioOverride || {};
|
|
39
|
+
let payload = {};
|
|
40
|
+
try {
|
|
41
|
+
payload = await readPayload(cliOptions.timeoutMs);
|
|
42
|
+
const traceBase = { tracePath: cliOptions.tracePath };
|
|
43
|
+
|
|
44
|
+
if (!cliOptions.hookOptions && !cliOptions.runHook) {
|
|
45
|
+
const ipcRes = await tryFastDaemonRpc(
|
|
46
|
+
'hook.userPromptSubmit',
|
|
47
|
+
{ event: payload },
|
|
48
|
+
{ ipcPath: cliOptions.ipcPath }
|
|
49
|
+
);
|
|
50
|
+
if (ipcRes && ipcRes.fullVerdict === true) {
|
|
51
|
+
if (ipcRes.stdout) {
|
|
52
|
+
recordHookTrace('UserPromptSubmit', payload, { ...traceBase, outcome: 'stdout_json', path: 'daemon_ipc', exitCode: 0 });
|
|
53
|
+
exitWithStdoutJson(ipcRes.stdout, ioOverride);
|
|
54
|
+
} else {
|
|
55
|
+
recordHookTrace('UserPromptSubmit', payload, { ...traceBase, outcome: 'pass_through', path: 'daemon_ipc', exitCode: 0 });
|
|
56
|
+
exitPassThrough(ioOverride.exitFn);
|
|
57
|
+
}
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const { runUserPromptSubmitHook: runCore } = await import('../src/guards/prompt-guard.mjs');
|
|
63
|
+
const res = cliOptions.runHook
|
|
64
|
+
? cliOptions.runHook(payload, { persistState: true, ...(cliOptions.hookOptions || {}) })
|
|
65
|
+
: runCore(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
|
|
66
|
+
|
|
67
|
+
if (res?.stdout) {
|
|
68
|
+
recordHookTrace('UserPromptSubmit', payload, { ...traceBase, outcome: 'stdout_json', path: 'core', exitCode: 0 });
|
|
69
|
+
exitWithStdoutJson(res.stdout, ioOverride);
|
|
70
|
+
} else {
|
|
71
|
+
recordHookTrace('UserPromptSubmit', payload, { ...traceBase, outcome: 'pass_through', path: 'core', exitCode: 0 });
|
|
72
|
+
exitPassThrough(ioOverride.exitFn);
|
|
73
|
+
}
|
|
74
|
+
} catch (err) {
|
|
75
|
+
recordHookTrace('UserPromptSubmit', payload, {
|
|
76
|
+
tracePath: cliOptions.tracePath,
|
|
77
|
+
outcome: 'error',
|
|
78
|
+
path: 'fault',
|
|
79
|
+
exitCode: 0,
|
|
80
|
+
error: err?.message || String(err)
|
|
81
|
+
});
|
|
82
|
+
exitDiagnosticZero(err?.message || String(err), 'UserPromptSubmit', ioOverride);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (isCliEntrypoint(import.meta.url)) {
|
|
87
|
+
executeUserPromptSubmitCli().catch((err) => {
|
|
88
|
+
exitDiagnosticZero(err?.message || String(err), 'UserPromptSubmit');
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export { executeUserPromptSubmitCli as main };
|
|
93
|
+
|
|
94
|
+
export default {
|
|
95
|
+
runUserPromptSubmitHookAsync,
|
|
96
|
+
runUserPromptSubmitHook,
|
|
97
|
+
executeUserPromptSubmitCli
|
|
98
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "burnoff",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code and Google Antigravity.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,6 +32,7 @@
|
|
|
32
32
|
"files": [
|
|
33
33
|
"bin/",
|
|
34
34
|
"hooks/*.mjs",
|
|
35
|
+
"hooks/hooks.json",
|
|
35
36
|
"src/",
|
|
36
37
|
".claude-plugin/",
|
|
37
38
|
"commands/",
|
|
@@ -40,14 +41,15 @@
|
|
|
40
41
|
".github/workflows/burnoff-startup-lint.yml",
|
|
41
42
|
"docs/CLAUDE_CODE_PLUGIN.md",
|
|
42
43
|
"docs/DESIGN_PARTNER_INTAKE.md",
|
|
44
|
+
"CHANGELOG.md",
|
|
43
45
|
"LICENSE",
|
|
44
|
-
"README.md"
|
|
46
|
+
"README.md",
|
|
47
|
+
"SECURITY.md"
|
|
45
48
|
],
|
|
46
49
|
"dependencies": {},
|
|
47
50
|
"scripts": {
|
|
48
51
|
"test": "node --test --test-concurrency=1",
|
|
49
52
|
"test:bench": "node --test test/ipc-daemon-bench.test.mjs",
|
|
50
|
-
"doctor": "node bin/burnoff.mjs doctor"
|
|
51
|
-
"check:brands": "node -e \"import('node:fs').then(async fs=>{const p=await import('node:path');const bad=new RegExp(['ctx'+'top','high'+'beam','attention[-_]'+'horizon','ga-visual'+'izer-v2','pro_'+'license','ah-status'+'line','\\\\bHB'+'-(?:CFG|MCP|SEC)-','\\\\ba'+'gy','default'+'_api:','phase0'+'_' ].join('|'),'i');const dirs=['bin','hooks','src','.github','.claude-plugin','commands','scripts'];let hits=[];const walk=(d)=>{if(!fs.existsSync(d))return;for(const e of fs.readdirSync(d,{withFileTypes:true})){const f=p.join(d,e.name);if(e.isDirectory())walk(f);else if(/\\.(mjs|json|ya?ml|md)$/.test(e.name)){const t=fs.readFileSync(f,'utf8');if(bad.test(t))hits.push(f);}}};dirs.forEach(walk);['package.json','README.md','docs/CLAUDE_CODE_PLUGIN.md','docs/DESIGN_PARTNER_INTAKE.md'].forEach(f=>{if(fs.existsSync(f)&&bad.test(fs.readFileSync(f,'utf8')))hits.push(f);});if(hits.length){console.error('Brand leaks:',hits);process.exit(1);}console.log('Zero legacy brand strings found.');})\""
|
|
53
|
+
"doctor": "node bin/burnoff.mjs doctor"
|
|
52
54
|
}
|
|
53
55
|
}
|
package/scripts/bench-hooks.mjs
CHANGED
|
@@ -12,6 +12,8 @@ import os from 'node:os';
|
|
|
12
12
|
import path from 'node:path';
|
|
13
13
|
import { performance } from 'node:perf_hooks';
|
|
14
14
|
import { fileURLToPath } from 'node:url';
|
|
15
|
+
import { BurnoffDaemon } from '../src/ipc/daemon.mjs';
|
|
16
|
+
import { tryFastDaemonRpc } from '../src/ipc/fast-client.mjs';
|
|
15
17
|
|
|
16
18
|
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
|
|
17
19
|
const PROJECT_ROOT = path.resolve(SCRIPT_DIR, '..');
|
|
@@ -71,7 +73,7 @@ function runColdHookSpawn(hookScript, payloadJson, env, cwd) {
|
|
|
71
73
|
*
|
|
72
74
|
* @param {{ runs?: number }} [options={}]
|
|
73
75
|
*/
|
|
74
|
-
export function runHookBenchmarks(options = {}) {
|
|
76
|
+
export async function runHookBenchmarks(options = {}) {
|
|
75
77
|
const runs = Math.max(1, Math.floor(Number(options.runs) || 7));
|
|
76
78
|
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'burnoff-bench-'));
|
|
77
79
|
const homeDir = path.join(tmpRoot, 'home');
|
|
@@ -79,6 +81,13 @@ export function runHookBenchmarks(options = {}) {
|
|
|
79
81
|
fs.mkdirSync(path.join(wsDir, 'src'), { recursive: true });
|
|
80
82
|
fs.mkdirSync(homeDir, { recursive: true });
|
|
81
83
|
|
|
84
|
+
const warmIpcPath =
|
|
85
|
+
process.platform === 'win32'
|
|
86
|
+
? `\\\\.\\pipe\\burnoff-bench-${process.pid}-${Date.now()}`
|
|
87
|
+
: path.join(tmpRoot, 'bench-daemon.sock');
|
|
88
|
+
const daemon = new BurnoffDaemon({ cwd: wsDir, homeDir, ipcPath: warmIpcPath, idleTimeoutMs: 0 });
|
|
89
|
+
await daemon.listen();
|
|
90
|
+
|
|
82
91
|
try {
|
|
83
92
|
const sampleLines = Array.from({ length: 100 }, (_, i) => `export const line_${i} = ${i};`).join('\n');
|
|
84
93
|
fs.writeFileSync(path.join(wsDir, 'src', 'sample.mjs'), `${sampleLines}\n`, 'utf8');
|
|
@@ -86,7 +95,8 @@ export function runHookBenchmarks(options = {}) {
|
|
|
86
95
|
const baseEnv = {
|
|
87
96
|
...process.env,
|
|
88
97
|
HOME: homeDir,
|
|
89
|
-
USERPROFILE: homeDir
|
|
98
|
+
USERPROFILE: homeDir,
|
|
99
|
+
BURNOFF_NO_AUTO_DAEMON: '1'
|
|
90
100
|
};
|
|
91
101
|
delete baseEnv.BURNOFF_HOME;
|
|
92
102
|
delete baseEnv.BURNOFF_CLIENT;
|
|
@@ -188,6 +198,26 @@ export function runHookBenchmarks(options = {}) {
|
|
|
188
198
|
};
|
|
189
199
|
});
|
|
190
200
|
|
|
201
|
+
// Warm IPC daemon RPC benchmarks (what Turn 2+ hits after auto-daemon start)
|
|
202
|
+
const warmRpcSamples = [];
|
|
203
|
+
const warmPayload = {
|
|
204
|
+
session_id: 'bench-warm-rpc',
|
|
205
|
+
cwd: wsDir,
|
|
206
|
+
tool_name: 'Bash',
|
|
207
|
+
tool_input: { command: 'git status --short' }
|
|
208
|
+
};
|
|
209
|
+
await tryFastDaemonRpc('hook.claude.preToolUse', { event: warmPayload }, { ipcPath: warmIpcPath, cwd: wsDir });
|
|
210
|
+
for (let i = 0; i < runs; i += 1) {
|
|
211
|
+
const t0 = performance.now();
|
|
212
|
+
await tryFastDaemonRpc('hook.claude.preToolUse', { event: warmPayload }, { ipcPath: warmIpcPath, cwd: wsDir });
|
|
213
|
+
warmRpcSamples.push(performance.now() - t0);
|
|
214
|
+
}
|
|
215
|
+
results.push({
|
|
216
|
+
id: 'warm_daemon_rpc_pre_bash',
|
|
217
|
+
label: 'Warm Auto-Daemon IPC (`PreToolUse` `Bash`)',
|
|
218
|
+
stats: summarizeDurationsMs(warmRpcSamples)
|
|
219
|
+
});
|
|
220
|
+
|
|
191
221
|
const cpus = os.cpus();
|
|
192
222
|
return {
|
|
193
223
|
runs,
|
|
@@ -201,6 +231,7 @@ export function runHookBenchmarks(options = {}) {
|
|
|
201
231
|
results
|
|
202
232
|
};
|
|
203
233
|
} finally {
|
|
234
|
+
await daemon.close();
|
|
204
235
|
fs.rmSync(tmpRoot, { recursive: true, force: true });
|
|
205
236
|
}
|
|
206
237
|
}
|
|
@@ -243,7 +274,7 @@ const isEntry =
|
|
|
243
274
|
|
|
244
275
|
if (isEntry) {
|
|
245
276
|
const args = parseArgs();
|
|
246
|
-
const report = runHookBenchmarks({ runs: args.runs });
|
|
277
|
+
const report = await runHookBenchmarks({ runs: args.runs });
|
|
247
278
|
if (args.json) {
|
|
248
279
|
console.log(JSON.stringify(report, null, 2));
|
|
249
280
|
} else {
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* @file scripts/bench-savings.mjs
|
|
4
|
+
* Reproducible offline benchmark exercising Burnoff's real guard, FTS5 offload,
|
|
5
|
+
* Turn-0 startup audit, and pricing engines across 4 deterministic workloads.
|
|
6
|
+
* Usage:
|
|
7
|
+
* node scripts/bench-savings.mjs [--json]
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { fileURLToPath } from 'node:url';
|
|
14
|
+
import { runPreToolUseHook } from '../src/guards/pre-tool-engine.mjs';
|
|
15
|
+
import { runPostToolUseHook } from '../src/guards/post-tool-engine.mjs';
|
|
16
|
+
import { runStartupAudit } from '../src/cli/startup-audit.mjs';
|
|
17
|
+
import { resolveModelRateCard } from '../src/config/pricing.mjs';
|
|
18
|
+
import { isCliEntrypoint } from '../hooks/hook-io.mjs';
|
|
19
|
+
|
|
20
|
+
export const CACHE_DISCOUNT_MULTIPLIER = 0.27;
|
|
21
|
+
const CHARS_PER_TOKEN = 4;
|
|
22
|
+
|
|
23
|
+
function estTokens(text = '') {
|
|
24
|
+
return Math.ceil(Buffer.byteLength(String(text || ''), 'utf8') / CHARS_PER_TOKEN);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function usdFromTokens(tokens, per1M) {
|
|
28
|
+
return Number(((Math.max(0, Number(tokens || 0)) / 1_000_000) * Number(per1M || 0)).toFixed(4));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Runs 4 deterministic offline workloads in an isolated temp workspace.
|
|
33
|
+
*/
|
|
34
|
+
export async function runSavingsBenchmarks() {
|
|
35
|
+
const tmpRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'burnoff-bench-savings-'));
|
|
36
|
+
const homeDir = path.join(tmpRoot, 'home');
|
|
37
|
+
const wsDir = path.join(tmpRoot, 'workspace');
|
|
38
|
+
fs.mkdirSync(homeDir, { recursive: true });
|
|
39
|
+
fs.mkdirSync(wsDir, { recursive: true });
|
|
40
|
+
|
|
41
|
+
try {
|
|
42
|
+
const rateCard = resolveModelRateCard({ model: 'claude-sonnet-5-5' });
|
|
43
|
+
const coldPer1M = Number(rateCard.write5mPer1M || rateCard.inputPer1M || 3);
|
|
44
|
+
const inputPer1M = Number(rateCard.inputPer1M || 3);
|
|
45
|
+
|
|
46
|
+
// -----------------------------------------------------------------------
|
|
47
|
+
// Workload 1: 800-line, 72,000-byte log file Read clamp (DET-06)
|
|
48
|
+
// -----------------------------------------------------------------------
|
|
49
|
+
const logLines = Array.from({ length: 800 }, (_, idx) => {
|
|
50
|
+
const n = String(idx + 1).padStart(4, '0');
|
|
51
|
+
return `[2026-11-28T12:00:00Z] INFO worker-${n} processed batch request ok status=200 ms=14`.padEnd(
|
|
52
|
+
89,
|
|
53
|
+
' '
|
|
54
|
+
);
|
|
55
|
+
});
|
|
56
|
+
const logContent = logLines.join('\n') + '\n';
|
|
57
|
+
const logPath = path.join(wsDir, 'APP_SERVER.log');
|
|
58
|
+
fs.writeFileSync(logPath, logContent, 'utf8');
|
|
59
|
+
|
|
60
|
+
const totalLogBytes = Buffer.byteLength(logContent, 'utf8');
|
|
61
|
+
const totalLogTokens = estTokens(logContent);
|
|
62
|
+
const w1Res = runPreToolUseHook(
|
|
63
|
+
{
|
|
64
|
+
session_id: 'bench-w1',
|
|
65
|
+
tool_name: 'Read',
|
|
66
|
+
tool_input: { file_path: logPath }
|
|
67
|
+
},
|
|
68
|
+
{ cwd: wsDir, homeDir }
|
|
69
|
+
);
|
|
70
|
+
const w1Out = w1Res.stdout ? JSON.parse(w1Res.stdout) : {};
|
|
71
|
+
const clampedLimit = Number(w1Out?.hookSpecificOutput?.updatedInput?.limit || 0);
|
|
72
|
+
const clampedSlice = logLines.slice(0, clampedLimit).join('\n') + '\n';
|
|
73
|
+
const clampedBytes = Buffer.byteLength(clampedSlice, 'utf8');
|
|
74
|
+
const clampedTokens = estTokens(clampedSlice);
|
|
75
|
+
const w1SavedTokens = Math.max(0, totalLogTokens - clampedTokens);
|
|
76
|
+
|
|
77
|
+
// -----------------------------------------------------------------------
|
|
78
|
+
// Workload 2: 3x failing test loop break (DET-04) + PostToolUse offload
|
|
79
|
+
// -----------------------------------------------------------------------
|
|
80
|
+
const noisyPassLines = Array.from(
|
|
81
|
+
{ length: 420 },
|
|
82
|
+
(_, idx) => `ok ${idx + 1} - unit spec verified deterministic guard path #${idx + 1} (3.2ms)`
|
|
83
|
+
);
|
|
84
|
+
const noisyTestStdout = [
|
|
85
|
+
...noisyPassLines,
|
|
86
|
+
'AssertionError [ERR_ASSERTION]: Expected 409 conflict status, received 500',
|
|
87
|
+
' at file:///workspace/test/checkout.test.mjs:44:12',
|
|
88
|
+
'FAIL test/checkout.test.mjs (1 failed, 420 passed)'
|
|
89
|
+
].join('\n');
|
|
90
|
+
const postRawTokens = estTokens(noisyTestStdout);
|
|
91
|
+
let postOutTokens = postRawTokens;
|
|
92
|
+
let ftsOffloaded = false;
|
|
93
|
+
|
|
94
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
95
|
+
const cmd = 'npm test -- test/checkout.test.mjs';
|
|
96
|
+
runPreToolUseHook(
|
|
97
|
+
{
|
|
98
|
+
session_id: 'bench-w2',
|
|
99
|
+
tool_name: 'Bash',
|
|
100
|
+
tool_input: { command: cmd }
|
|
101
|
+
},
|
|
102
|
+
{ cwd: wsDir, homeDir }
|
|
103
|
+
);
|
|
104
|
+
const postRes = runPostToolUseHook(
|
|
105
|
+
{
|
|
106
|
+
session_id: 'bench-w2',
|
|
107
|
+
tool_name: 'Bash',
|
|
108
|
+
tool_input: { command: cmd },
|
|
109
|
+
tool_response: { stdout: noisyTestStdout, exit_code: 1 },
|
|
110
|
+
is_error: true
|
|
111
|
+
},
|
|
112
|
+
{ cwd: wsDir, homeDir }
|
|
113
|
+
);
|
|
114
|
+
if (attempt === 1) {
|
|
115
|
+
const postJson = postRes.stdout ? JSON.parse(postRes.stdout) : {};
|
|
116
|
+
const replaced =
|
|
117
|
+
postJson?.hookSpecificOutput?.updatedToolOutput?.stdout ||
|
|
118
|
+
postJson?.hookSpecificOutput?.additionalContext ||
|
|
119
|
+
noisyTestStdout;
|
|
120
|
+
postOutTokens = estTokens(replaced);
|
|
121
|
+
ftsOffloaded = Boolean(postRes.sanitized?.compressed || postOutTokens < postRawTokens);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const breakerTrip = runPreToolUseHook(
|
|
126
|
+
{
|
|
127
|
+
session_id: 'bench-w2',
|
|
128
|
+
tool_name: 'Bash',
|
|
129
|
+
tool_input: { command: 'npm test -- test/checkout.test.mjs' }
|
|
130
|
+
},
|
|
131
|
+
{ cwd: wsDir, homeDir }
|
|
132
|
+
);
|
|
133
|
+
const perPostSavedTokens = Math.max(0, postRawTokens - postOutTokens);
|
|
134
|
+
// Breaking attempt #4 avoids another wasted turn (assumed ~18,000-tok turn replay avoided)
|
|
135
|
+
const avoidedRetryReplayTokens = breakerTrip.exitCode === 2 || breakerTrip.verdict?.triggered ? 18_000 : 0;
|
|
136
|
+
const w2SavedTokens = perPostSavedTokens * 3 + avoidedRetryReplayTokens;
|
|
137
|
+
|
|
138
|
+
// -----------------------------------------------------------------------
|
|
139
|
+
// Workload 3: Bloated Turn-0 config audit (CLAUDE.md + eager .mcp.json)
|
|
140
|
+
// -----------------------------------------------------------------------
|
|
141
|
+
const bloatedClaudeMd = [
|
|
142
|
+
'# Workspace Rules',
|
|
143
|
+
'Always run full clean builds before every single small edit.',
|
|
144
|
+
'NEVER run full builds before small edits.',
|
|
145
|
+
...Array.from(
|
|
146
|
+
{ length: 180 },
|
|
147
|
+
(_, i) => `- Convention #${i + 1}: verify deterministic schema alignment and preserve strict audit parity.`
|
|
148
|
+
)
|
|
149
|
+
].join('\n');
|
|
150
|
+
fs.writeFileSync(path.join(wsDir, 'CLAUDE.md'), bloatedClaudeMd, 'utf8');
|
|
151
|
+
|
|
152
|
+
fs.mkdirSync(path.join(wsDir, '.claude'), { recursive: true });
|
|
153
|
+
fs.writeFileSync(
|
|
154
|
+
path.join(wsDir, '.claude', 'settings.json'),
|
|
155
|
+
JSON.stringify({ env: { ENABLE_TOOL_SEARCH: 'false' } }, null, 2),
|
|
156
|
+
'utf8'
|
|
157
|
+
);
|
|
158
|
+
const mcpServers = {};
|
|
159
|
+
for (let s = 1; s <= 4; s++) {
|
|
160
|
+
mcpServers[`server_${s}`] = {
|
|
161
|
+
command: 'node',
|
|
162
|
+
args: [`./mcp-${s}.mjs`],
|
|
163
|
+
estimatedTokens: 3200
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
fs.writeFileSync(path.join(wsDir, '.mcp.json'), JSON.stringify({ mcpServers }, null, 2), 'utf8');
|
|
167
|
+
|
|
168
|
+
const w3Audit = runStartupAudit({ cwd: wsDir, homeDir, repoOnly: true, client: 'claude' });
|
|
169
|
+
const w3SavedTokens = Number(w3Audit?.summary?.estimatedTurn0ReclaimableTokens || 0);
|
|
170
|
+
|
|
171
|
+
// -----------------------------------------------------------------------
|
|
172
|
+
// Workload 4: Ring-0 secret & destructive shell hard blocks (DET-01 / 02)
|
|
173
|
+
// -----------------------------------------------------------------------
|
|
174
|
+
const envBlock = runPreToolUseHook(
|
|
175
|
+
{
|
|
176
|
+
session_id: 'bench-w4',
|
|
177
|
+
tool_name: 'Read',
|
|
178
|
+
tool_input: { file_path: path.join(wsDir, '.env') }
|
|
179
|
+
},
|
|
180
|
+
{ cwd: wsDir, homeDir }
|
|
181
|
+
);
|
|
182
|
+
const forcePushBlock = runPreToolUseHook(
|
|
183
|
+
{
|
|
184
|
+
session_id: 'bench-w4',
|
|
185
|
+
tool_name: 'Bash',
|
|
186
|
+
tool_input: { command: 'git push --force origin main' }
|
|
187
|
+
},
|
|
188
|
+
{ cwd: wsDir, homeDir }
|
|
189
|
+
);
|
|
190
|
+
const agRmBlock = runPreToolUseHook(
|
|
191
|
+
{
|
|
192
|
+
conversationId: 'bench-w4',
|
|
193
|
+
cwd: wsDir,
|
|
194
|
+
toolCall: { name: 'run_command', args: { CommandLine: 'rm -Recurse -Force src' } }
|
|
195
|
+
},
|
|
196
|
+
{ cwd: wsDir, homeDir }
|
|
197
|
+
);
|
|
198
|
+
const agParsed = agRmBlock.stdout ? JSON.parse(agRmBlock.stdout) : {};
|
|
199
|
+
const blocks = [
|
|
200
|
+
{ case: 'Claude Read .env', detectorId: envBlock.verdict?.detectorId, exitCode: envBlock.exitCode },
|
|
201
|
+
{
|
|
202
|
+
case: 'Claude git push --force',
|
|
203
|
+
detectorId: forcePushBlock.verdict?.detectorId,
|
|
204
|
+
exitCode: forcePushBlock.exitCode
|
|
205
|
+
},
|
|
206
|
+
{
|
|
207
|
+
case: 'Antigravity rm -Recurse -Force',
|
|
208
|
+
decision: agParsed.decision,
|
|
209
|
+
exitCode: agRmBlock.exitCode
|
|
210
|
+
}
|
|
211
|
+
];
|
|
212
|
+
|
|
213
|
+
const workloads = [
|
|
214
|
+
{
|
|
215
|
+
id: 'W1_READ_CLAMP',
|
|
216
|
+
name: '800-line log Read clamp (DET-06)',
|
|
217
|
+
detector: w1Res.verdict?.detectorId || 'DET-06',
|
|
218
|
+
clampedLines: clampedLimit,
|
|
219
|
+
beforeTokens: totalLogTokens,
|
|
220
|
+
afterTokens: clampedTokens,
|
|
221
|
+
savedTokens: w1SavedTokens,
|
|
222
|
+
coldUsdSaved: usdFromTokens(w1SavedTokens, inputPer1M),
|
|
223
|
+
cachedAmortizedUsdSaved: usdFromTokens(w1SavedTokens, inputPer1M * CACHE_DISCOUNT_MULTIPLIER),
|
|
224
|
+
outcome: clampedLimit > 0 && clampedLimit < 800 ? `PASS (clamped ${totalLogBytes} B -> ${clampedBytes} B)` : 'MISS'
|
|
225
|
+
},
|
|
226
|
+
{
|
|
227
|
+
id: 'W2_LOOP_BREAK_FTS5',
|
|
228
|
+
name: '3x failing test loop + PostToolUse offload (DET-04)',
|
|
229
|
+
detector: breakerTrip.verdict?.detectorId || 'DET-04',
|
|
230
|
+
ftsOffloaded,
|
|
231
|
+
perPostRawTokens: postRawTokens,
|
|
232
|
+
perPostAfterTokens: postOutTokens,
|
|
233
|
+
breakerTrippedOnAttempt4: breakerTrip.verdict?.triggered === true,
|
|
234
|
+
breakerDecision: breakerTrip.verdict?.decision || 'none',
|
|
235
|
+
savedTokens: w2SavedTokens,
|
|
236
|
+
coldUsdSaved: usdFromTokens(w2SavedTokens, coldPer1M),
|
|
237
|
+
cachedAmortizedUsdSaved: usdFromTokens(w2SavedTokens, inputPer1M * CACHE_DISCOUNT_MULTIPLIER),
|
|
238
|
+
outcome:
|
|
239
|
+
ftsOffloaded && breakerTrip.verdict?.triggered
|
|
240
|
+
? `PASS (offloaded ${postRawTokens}->${postOutTokens} tok; broke retry #4)`
|
|
241
|
+
: 'PARTIAL'
|
|
242
|
+
},
|
|
243
|
+
{
|
|
244
|
+
id: 'W3_TURN0_AUDIT',
|
|
245
|
+
name: 'Turn-0 bloated CLAUDE.md + eager .mcp.json audit',
|
|
246
|
+
detector: 'BO-CFG/BO-MCP',
|
|
247
|
+
lintCount: Array.isArray(w3Audit?.lints) ? w3Audit.lints.length : 0,
|
|
248
|
+
savedTokens: w3SavedTokens,
|
|
249
|
+
coldUsdSaved: usdFromTokens(w3SavedTokens, coldPer1M),
|
|
250
|
+
cachedAmortizedUsdSaved: usdFromTokens(w3SavedTokens, inputPer1M * CACHE_DISCOUNT_MULTIPLIER),
|
|
251
|
+
weeklyEstUsd: Number(w3Audit?.summary?.estimatedWeeklySavingsUsd || 0),
|
|
252
|
+
outcome: w3SavedTokens > 0 ? `PASS (${w3Audit.lints.length} lints found)` : 'MISS'
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
id: 'W4_RING0_BLOCKS',
|
|
256
|
+
name: 'Ring-0 .env secret & rm -Recurse -Force blocks (DET-01/02)',
|
|
257
|
+
detector: 'DET-01/DET-02',
|
|
258
|
+
blocksEnforced: blocks.filter(
|
|
259
|
+
(b) => b.exitCode === 2 || b.decision === 'deny'
|
|
260
|
+
).length,
|
|
261
|
+
totalCases: blocks.length,
|
|
262
|
+
blocks,
|
|
263
|
+
savedTokens: 0,
|
|
264
|
+
coldUsdSaved: 0,
|
|
265
|
+
cachedAmortizedUsdSaved: 0,
|
|
266
|
+
outcome:
|
|
267
|
+
envBlock.exitCode === 2 && forcePushBlock.exitCode === 2 && agParsed.decision === 'deny'
|
|
268
|
+
? 'PASS (3/3 hard blocks)'
|
|
269
|
+
: 'FAIL'
|
|
270
|
+
}
|
|
271
|
+
];
|
|
272
|
+
|
|
273
|
+
const totalSavedTokens = workloads.reduce((acc, w) => acc + w.savedTokens, 0);
|
|
274
|
+
return {
|
|
275
|
+
modelReference: rateCard.modelId,
|
|
276
|
+
inputPer1M,
|
|
277
|
+
cacheDiscountMultiplier: CACHE_DISCOUNT_MULTIPLIER,
|
|
278
|
+
workloads,
|
|
279
|
+
totals: {
|
|
280
|
+
savedTokens: totalSavedTokens,
|
|
281
|
+
coldUsdSaved: Number(workloads.reduce((acc, w) => acc + w.coldUsdSaved, 0).toFixed(4)),
|
|
282
|
+
cachedAmortizedUsdSaved: Number(
|
|
283
|
+
workloads.reduce((acc, w) => acc + w.cachedAmortizedUsdSaved, 0).toFixed(4)
|
|
284
|
+
)
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
} finally {
|
|
288
|
+
fs.rmSync(tmpRoot, { recursive: true, force: true });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export function formatSavingsReport(res) {
|
|
293
|
+
const lines = [
|
|
294
|
+
`Burnoff Reproducible Savings Benchmark (ref rate: ${res.modelReference} @ $${res.inputPer1M}/1M uncached, ${res.cacheDiscountMultiplier}x cache-read weight)`,
|
|
295
|
+
'',
|
|
296
|
+
'| Workload | Tokens Saved | Uncached USD | 0.27x Cache USD | Outcome |',
|
|
297
|
+
'| :--- | ---: | ---: | ---: | :--- |'
|
|
298
|
+
];
|
|
299
|
+
for (const w of res.workloads) {
|
|
300
|
+
lines.push(
|
|
301
|
+
`| ${w.name} | ${w.savedTokens.toLocaleString('en-US')} | $${w.coldUsdSaved.toFixed(4)} | $${w.cachedAmortizedUsdSaved.toFixed(4)} | ${w.outcome} |`
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
lines.push(
|
|
305
|
+
`| **Total (single session pass)** | **${res.totals.savedTokens.toLocaleString('en-US')}** | **$${res.totals.coldUsdSaved.toFixed(4)}** | **$${res.totals.cachedAmortizedUsdSaved.toFixed(4)}** | **4/4 deterministic** |`
|
|
306
|
+
);
|
|
307
|
+
return lines.join('\n');
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
if (isCliEntrypoint(import.meta.url)) {
|
|
311
|
+
const asJson = process.argv.includes('--json');
|
|
312
|
+
const result = await runSavingsBenchmarks();
|
|
313
|
+
if (asJson) {
|
|
314
|
+
process.stdout.write(JSON.stringify(result, null, 2) + '\n');
|
|
315
|
+
} else {
|
|
316
|
+
process.stdout.write(formatSavingsReport(result) + '\n');
|
|
317
|
+
}
|
|
318
|
+
}
|