burnoff 0.0.0-stage → 1.0.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.
@@ -0,0 +1,118 @@
1
+ /**
2
+ * @file hooks/post-tool-use.mjs
3
+ * Thin Tier-2 Command Hook Fast-Shell for `PostToolUse`.
4
+ * Imports strictly `./hook-io.mjs` and `../src/ipc/fast-client.mjs` on the warm/fast path;
5
+ * lazy-imports `../src/guards/post-tool-engine.mjs` only on cold fallback.
6
+ */
7
+
8
+ import {
9
+ isCliEntrypoint,
10
+ readStdinJsonAsync,
11
+ exitPassThrough,
12
+ exitDiagnosticZero,
13
+ exitWithStdoutJson,
14
+ recordHookTrace,
15
+ tryTier1PostToolFastPath
16
+ } from './hook-io.mjs';
17
+ import { tryFastDaemonRpc } from '../src/ipc/fast-client.mjs';
18
+
19
+ let _engineMod = null;
20
+ if (!isCliEntrypoint(import.meta.url)) {
21
+ _engineMod = await import('../src/guards/post-tool-engine.mjs');
22
+ }
23
+
24
+ export async function runPostToolUseHookAsync(event = {}, options = {}) {
25
+ const fast = tryTier1PostToolFastPath(event, options);
26
+ if (fast) return fast;
27
+ if (!_engineMod) {
28
+ _engineMod = await import('../src/guards/post-tool-engine.mjs');
29
+ }
30
+ return _engineMod.runPostToolUseHook(event, options);
31
+ }
32
+
33
+ export function runPostToolUseHook(event = {}, options = {}) {
34
+ const fast = tryTier1PostToolFastPath(event, options);
35
+ if (fast) return fast;
36
+ if (!_engineMod) {
37
+ throw new Error('post-tool-engine.mjs is not loaded; use runPostToolUseHookAsync() when invoked as CLI entrypoint.');
38
+ }
39
+ return _engineMod.runPostToolUseHook(event, options);
40
+ }
41
+
42
+ export async function executePostToolUseCli(cliOptions = {}) {
43
+ const readPayload = cliOptions.readPayload || readStdinJsonAsync;
44
+ const ioOverride = cliOptions.ioOverride || {};
45
+ let payload = {};
46
+ try {
47
+ payload = await readPayload(cliOptions.timeoutMs);
48
+ const hasCustomOptions = Boolean(cliOptions.runHook || cliOptions.hookOptions);
49
+ const traceBase = { tracePath: cliOptions.tracePath };
50
+
51
+ if (cliOptions.runHook) {
52
+ const res = cliOptions.runHook(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
53
+ if (res.stdout) {
54
+ recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'custom', exitCode: 0 });
55
+ exitWithStdoutJson(res.stdout, ioOverride);
56
+ } else {
57
+ recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'custom', exitCode: 0 });
58
+ exitPassThrough(ioOverride.exitFn);
59
+ }
60
+ return;
61
+ }
62
+
63
+ if (!hasCustomOptions) {
64
+ if (tryTier1PostToolFastPath(payload)) {
65
+ recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'tier1_fast', exitCode: 0 });
66
+ exitPassThrough(ioOverride.exitFn);
67
+ return;
68
+ }
69
+
70
+ const ipcRes = await tryFastDaemonRpc(
71
+ 'hook.claude.postToolUse',
72
+ { event: payload },
73
+ { ipcPath: cliOptions.ipcPath }
74
+ );
75
+ if (ipcRes && ipcRes.fullVerdict === true) {
76
+ if (ipcRes.stdout) {
77
+ recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'daemon_ipc', exitCode: 0 });
78
+ exitWithStdoutJson(ipcRes.stdout, ioOverride);
79
+ } else {
80
+ recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'daemon_ipc', exitCode: 0 });
81
+ exitPassThrough(ioOverride.exitFn);
82
+ }
83
+ return;
84
+ }
85
+ }
86
+
87
+ const { runPostToolUseHook: runCore } = await import('../src/guards/post-tool-engine.mjs');
88
+ const res = runCore(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
89
+ if (res.stdout) {
90
+ recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'core', exitCode: 0 });
91
+ exitWithStdoutJson(res.stdout, ioOverride);
92
+ } else {
93
+ recordHookTrace('PostToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'core', exitCode: 0 });
94
+ exitPassThrough(ioOverride.exitFn);
95
+ }
96
+ } catch (err) {
97
+ recordHookTrace('PostToolUse', payload, {
98
+ tracePath: cliOptions.tracePath,
99
+ outcome: 'error',
100
+ path: 'fault',
101
+ exitCode: 0,
102
+ error: err?.message || String(err)
103
+ });
104
+ exitDiagnosticZero(err?.message || String(err), 'PostToolUse', ioOverride);
105
+ }
106
+ }
107
+
108
+ if (isCliEntrypoint(import.meta.url)) {
109
+ executePostToolUseCli().catch((err) => {
110
+ exitDiagnosticZero(err?.message || String(err), 'PostToolUse');
111
+ });
112
+ }
113
+
114
+ export default {
115
+ runPostToolUseHookAsync,
116
+ runPostToolUseHook,
117
+ executePostToolUseCli
118
+ };
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @file hooks/pre-tool-use.mjs
3
+ * Thin Tier-2 Command Hook Fast-Shell for `PreToolUse`.
4
+ * Imports strictly `./hook-io.mjs` and `../src/ipc/fast-client.mjs` on the warm/fast path;
5
+ * lazy-imports `../src/guards/pre-tool-engine.mjs` only on cold fallback.
6
+ */
7
+
8
+ import {
9
+ isCliEntrypoint,
10
+ readStdinJsonAsync,
11
+ exitPassThrough,
12
+ exitDiagnosticZero,
13
+ exitHardBlockStderr,
14
+ exitWithStdoutJson,
15
+ recordHookTrace,
16
+ canFastAllowBoundedRead,
17
+ tryTier1PreToolFastPath
18
+ } from './hook-io.mjs';
19
+ import { tryFastDaemonRpc } from '../src/ipc/fast-client.mjs';
20
+
21
+ let _engineMod = null;
22
+ if (!isCliEntrypoint(import.meta.url)) {
23
+ _engineMod = await import('../src/guards/pre-tool-engine.mjs');
24
+ }
25
+
26
+ export async function runPreToolUseHookAsync(event = {}, options = {}) {
27
+ const fast = tryTier1PreToolFastPath(event, options);
28
+ if (fast) return fast;
29
+ if (!_engineMod) {
30
+ _engineMod = await import('../src/guards/pre-tool-engine.mjs');
31
+ }
32
+ return _engineMod.runPreToolUseHook(event, options);
33
+ }
34
+
35
+ export function runPreToolUseHook(event = {}, options = {}) {
36
+ const fast = tryTier1PreToolFastPath(event, options);
37
+ if (fast) return fast;
38
+ if (!_engineMod) {
39
+ throw new Error('pre-tool-engine.mjs is not loaded; use runPreToolUseHookAsync() when invoked as CLI entrypoint.');
40
+ }
41
+ return _engineMod.runPreToolUseHook(event, options);
42
+ }
43
+
44
+ function exitOnInternalFault(err, ioOverride = {}) {
45
+ const msg = err?.message || String(err);
46
+ const strict =
47
+ String(globalThis.process?.env?.BURNOFF_PRETOOL_FAIL_MODE || '').toLowerCase() === 'closed';
48
+ if (strict) {
49
+ exitHardBlockStderr(`[Burnoff Fail-Closed] ${msg}`, 'PreToolUse', ioOverride);
50
+ return;
51
+ }
52
+ exitDiagnosticZero(`internal error, tool call allowed (fail-open): ${msg}`, 'PreToolUse', ioOverride);
53
+ }
54
+
55
+ export async function executePreToolUseCli(cliOptions = {}) {
56
+ const readPayload = cliOptions.readPayload || readStdinJsonAsync;
57
+ const ioOverride = cliOptions.ioOverride || {};
58
+ let payload = {};
59
+ try {
60
+ payload = await readPayload(cliOptions.timeoutMs);
61
+ const hasCustomOptions = Boolean(cliOptions.runHook || cliOptions.hookOptions);
62
+ const traceBase = { tracePath: cliOptions.tracePath };
63
+
64
+ if (cliOptions.runHook) {
65
+ const res = cliOptions.runHook(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
66
+ if (res.exitCode === 2) {
67
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'block', path: 'custom', exitCode: 2 });
68
+ exitHardBlockStderr(res.stderr, 'PreToolUse', ioOverride);
69
+ } else if (res.stdout) {
70
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'custom', exitCode: 0 });
71
+ exitWithStdoutJson(res.stdout, ioOverride);
72
+ } else {
73
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'custom', exitCode: 0 });
74
+ exitPassThrough(ioOverride.exitFn);
75
+ }
76
+ return;
77
+ }
78
+
79
+ if (!hasCustomOptions) {
80
+ if (tryTier1PreToolFastPath(payload)) {
81
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'tier1_fast', exitCode: 0 });
82
+ exitPassThrough(ioOverride.exitFn);
83
+ return;
84
+ }
85
+
86
+ const ipcRes = await tryFastDaemonRpc(
87
+ 'hook.claude.preToolUse',
88
+ { event: payload },
89
+ { ipcPath: cliOptions.ipcPath }
90
+ );
91
+ if (ipcRes && ipcRes.fullVerdict === true) {
92
+ if (ipcRes.exitCode === 2) {
93
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'block', path: 'daemon_ipc', exitCode: 2 });
94
+ exitHardBlockStderr(ipcRes.stderr, 'PreToolUse', ioOverride);
95
+ } else if (ipcRes.stdout) {
96
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'daemon_ipc', exitCode: 0 });
97
+ exitWithStdoutJson(ipcRes.stdout, ioOverride);
98
+ } else {
99
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'daemon_ipc', exitCode: 0 });
100
+ exitPassThrough(ioOverride.exitFn);
101
+ }
102
+ return;
103
+ }
104
+
105
+ if (canFastAllowBoundedRead(payload, { cwd: payload?.cwd })) {
106
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'bounded_read_fast', exitCode: 0 });
107
+ exitPassThrough(ioOverride.exitFn);
108
+ return;
109
+ }
110
+ }
111
+
112
+ const { runPreToolUseHook: runCore } = await import('../src/guards/pre-tool-engine.mjs');
113
+ const res = runCore(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
114
+
115
+ if (res.exitCode === 2) {
116
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'block', path: 'core', exitCode: 2 });
117
+ exitHardBlockStderr(res.stderr, 'PreToolUse', ioOverride);
118
+ } else if (res.stdout) {
119
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'stdout_json', path: 'core', exitCode: 0 });
120
+ exitWithStdoutJson(res.stdout, ioOverride);
121
+ } else {
122
+ recordHookTrace('PreToolUse', payload, { ...traceBase, outcome: 'pass_through', path: 'core', exitCode: 0 });
123
+ exitPassThrough(ioOverride.exitFn);
124
+ }
125
+ } catch (err) {
126
+ const strict =
127
+ String(globalThis.process?.env?.BURNOFF_PRETOOL_FAIL_MODE || '').toLowerCase() === 'closed';
128
+ recordHookTrace('PreToolUse', payload, {
129
+ tracePath: cliOptions.tracePath,
130
+ outcome: 'error',
131
+ path: 'fault',
132
+ exitCode: strict ? 2 : 0,
133
+ error: err?.message || String(err)
134
+ });
135
+ exitOnInternalFault(err, ioOverride);
136
+ }
137
+ }
138
+
139
+ if (isCliEntrypoint(import.meta.url)) {
140
+ executePreToolUseCli().catch((err) => {
141
+ exitOnInternalFault(err);
142
+ });
143
+ }
144
+
145
+ export default {
146
+ runPreToolUseHookAsync,
147
+ runPreToolUseHook,
148
+ executePreToolUseCli
149
+ };
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "burnoff",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Gizzant",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/Gizzant/burnoff.git"
11
+ },
12
+ "homepage": "https://github.com/Gizzant/burnoff#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/Gizzant/burnoff/issues"
15
+ },
16
+ "keywords": [
17
+ "claude-code",
18
+ "hooks",
19
+ "circuit-breaker",
20
+ "finops",
21
+ "ci-gate",
22
+ "guardrails"
23
+ ],
24
+ "bin": {
25
+ "burnoff": "./bin/burnoff.mjs"
26
+ },
27
+ "engines": {
28
+ "node": ">=20.19.0"
29
+ },
30
+ "files": [
31
+ "bin/",
32
+ "hooks/",
33
+ "src/",
34
+ "LICENSE",
35
+ "README.md"
36
+ ],
37
+ "dependencies": {},
38
+ "scripts": {
39
+ "test": "node --test test/*.test.mjs",
40
+ "test:bench": "node --test test/ipc-daemon-bench.test.mjs",
41
+ "doctor": "node bin/burnoff.mjs doctor",
42
+ "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','anti'+'gravity','pro_'+'license','ah-status'+'line'].join('|'),'i');const dirs=['bin','hooks','src','.github'];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'].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.');})\""
43
+ }
44
+ }
@@ -0,0 +1,270 @@
1
+ /**
2
+ * @file src/ci/ci-gate.mjs
3
+ * CI / PR Token-Budget Gate.
4
+ *
5
+ * Enforces organizational token/cost/cache-efficiency/safety budgets on PR branches
6
+ * using `.burnoff.yaml` `ciBudgetGate` policy and emits GitHub Actions workflow
7
+ * annotations + Markdown Job Summary tables. Zero runtime dependencies, zero license gates.
8
+ */
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { loadBurnoffPolicy } from '../config/policy.mjs';
13
+ import { buildPrCostAttribution } from './pr-cost.mjs';
14
+
15
+ export const DEFAULT_CI_BUDGET_POLICY = Object.freeze({
16
+ maxPrCostUsd: 15.0,
17
+ maxPrTokens: 1_500_000,
18
+ minCacheHitPct: 50,
19
+ maxWasteRatioPct: 35,
20
+ maxRing0Violations: 0,
21
+ mode: 'enforce'
22
+ });
23
+
24
+ function toFiniteNumber(value) {
25
+ if (value === undefined || value === null || value === '') return null;
26
+ const n = Number(value);
27
+ return Number.isFinite(n) ? n : null;
28
+ }
29
+
30
+ /**
31
+ * Loads `.burnoff.yaml` `ciBudgetGate` policy merged with explicit CLI overrides.
32
+ * Supports both percentage thresholds (`minCacheHitPct`, `maxWasteRatioPct`) and
33
+ * ratio keys (`maxCacheMissRatio`, `maxWasteRatio`).
34
+ */
35
+ export function loadCiBudgetPolicy(cwd, overrides = {}) {
36
+ const repoDir = path.resolve(cwd || process.cwd());
37
+ const loaded = loadBurnoffPolicy(repoDir);
38
+ const filePolicy = loaded.exists && loaded.ciBudgetGate && typeof loaded.ciBudgetGate === 'object'
39
+ ? loaded.ciBudgetGate
40
+ : {};
41
+
42
+ const merged = { ...DEFAULT_CI_BUDGET_POLICY };
43
+
44
+ const applyLayer = (layer) => {
45
+ if (!layer || typeof layer !== 'object') return;
46
+ if (toFiniteNumber(layer.maxPrCostUsd) !== null) {
47
+ merged.maxPrCostUsd = toFiniteNumber(layer.maxPrCostUsd);
48
+ }
49
+ if (toFiniteNumber(layer.maxPrTokens) !== null) {
50
+ merged.maxPrTokens = toFiniteNumber(layer.maxPrTokens);
51
+ }
52
+ if (toFiniteNumber(layer.minCacheHitPct) !== null) {
53
+ merged.minCacheHitPct = toFiniteNumber(layer.minCacheHitPct);
54
+ } else if (toFiniteNumber(layer.maxCacheMissRatio) !== null) {
55
+ const missRatio = Math.min(1, Math.max(0, toFiniteNumber(layer.maxCacheMissRatio)));
56
+ merged.minCacheHitPct = Math.round((1 - missRatio) * 100);
57
+ }
58
+ if (toFiniteNumber(layer.maxWasteRatioPct) !== null) {
59
+ merged.maxWasteRatioPct = toFiniteNumber(layer.maxWasteRatioPct);
60
+ } else if (toFiniteNumber(layer.maxWasteRatio) !== null) {
61
+ const r = toFiniteNumber(layer.maxWasteRatio);
62
+ merged.maxWasteRatioPct = r <= 1 ? Math.round(Math.max(0, r) * 100) : Math.round(r);
63
+ }
64
+ if (toFiniteNumber(layer.maxRing0Violations) !== null) {
65
+ merged.maxRing0Violations = toFiniteNumber(layer.maxRing0Violations);
66
+ }
67
+ if (layer.mode !== undefined && layer.mode !== null) {
68
+ merged.mode = String(layer.mode).toLowerCase();
69
+ }
70
+ };
71
+
72
+ if (loaded.exists) {
73
+ applyLayer(filePolicy);
74
+ }
75
+ applyLayer(overrides);
76
+
77
+ if (overrides?.strict === true) {
78
+ merged.mode = 'enforce';
79
+ }
80
+ if (merged.mode !== 'advisory' && merged.mode !== 'enforce') {
81
+ merged.mode = 'enforce';
82
+ }
83
+ return merged;
84
+ }
85
+
86
+ /**
87
+ * Evaluates a PR branch or attribution report against the Burnoff CI Token-Budget Gate.
88
+ */
89
+ export function evaluateCiBudgetGate(options = {}) {
90
+ const cwd = path.resolve(options.cwd || process.cwd());
91
+ const policyOverrides = {
92
+ ...(options.policyOverrides || options),
93
+ ...(options.strict ? { strict: true, mode: 'enforce' } : {})
94
+ };
95
+ const policy = loadCiBudgetPolicy(cwd, policyOverrides);
96
+
97
+ let attribution = options.attribution || null;
98
+ if (!attribution && options.inputPath) {
99
+ const absIn = path.resolve(options.inputPath);
100
+ if (!fs.existsSync(absIn)) {
101
+ return {
102
+ ok: false,
103
+ verdict: 'ERROR',
104
+ exitCode: 1,
105
+ error: `Attribution input file not found: ${absIn}`
106
+ };
107
+ }
108
+ try {
109
+ attribution = JSON.parse(fs.readFileSync(absIn, 'utf8'));
110
+ } catch (err) {
111
+ return {
112
+ ok: false,
113
+ verdict: 'ERROR',
114
+ exitCode: 1,
115
+ error: `Invalid attribution JSON: ${err?.message || String(err)}`
116
+ };
117
+ }
118
+ }
119
+
120
+ if (!attribution) {
121
+ const attrRes = buildPrCostAttribution({ ...options, cwd });
122
+ if (!attrRes.ok) {
123
+ return {
124
+ ok: false,
125
+ verdict: 'ERROR',
126
+ exitCode: 1,
127
+ error: attrRes.error || 'Failed to compute PR cost attribution.'
128
+ };
129
+ }
130
+ attribution = attrRes;
131
+ }
132
+
133
+ const summary = attribution.summary || attribution;
134
+ const totalInputTokens = Number(summary.totalInputTokens || 0);
135
+ const totalCacheReadTokens = Number(summary.totalCacheReadTokens || 0);
136
+ const estimatedCostUsd = Number(summary.estimatedCostUsd || 0);
137
+ const reconciledCostUsd =
138
+ typeof summary.reconciledCostUsd === 'number' && Number.isFinite(summary.reconciledCostUsd)
139
+ ? summary.reconciledCostUsd
140
+ : null;
141
+ const attributionVariancePct =
142
+ typeof summary.attributionVariancePct === 'number' && Number.isFinite(summary.attributionVariancePct)
143
+ ? summary.attributionVariancePct
144
+ : null;
145
+ const effectiveCostUsd =
146
+ reconciledCostUsd !== null ? Math.max(estimatedCostUsd, reconciledCostUsd) : estimatedCostUsd;
147
+ const totalTokens = Number(summary.totalTokens || 0);
148
+ const cacheHitPct = Number(summary.cacheHitPct || 0);
149
+ const wasteRatioPct = Number(summary.wasteRatioPct || 0);
150
+ const ring0Violations = Number(summary.ring0Violations || 0);
151
+
152
+ const violations = [];
153
+
154
+ if (effectiveCostUsd > policy.maxPrCostUsd) {
155
+ violations.push({
156
+ ruleId: 'MAX_PR_COST_USD',
157
+ actual: effectiveCostUsd,
158
+ limit: policy.maxPrCostUsd,
159
+ message: `Estimated/reconciled PR cost $${effectiveCostUsd.toFixed(4)} exceeds limit $${policy.maxPrCostUsd.toFixed(2)}`
160
+ });
161
+ }
162
+ if (totalTokens > policy.maxPrTokens) {
163
+ violations.push({
164
+ ruleId: 'MAX_PR_TOKENS',
165
+ actual: totalTokens,
166
+ limit: policy.maxPrTokens,
167
+ message: `Total PR tokens ${totalTokens.toLocaleString('en-US')} exceeds limit ${policy.maxPrTokens.toLocaleString('en-US')}`
168
+ });
169
+ }
170
+ if (totalInputTokens + totalCacheReadTokens > 0 && cacheHitPct < policy.minCacheHitPct) {
171
+ violations.push({
172
+ ruleId: 'MIN_CACHE_HIT_PCT',
173
+ actual: cacheHitPct,
174
+ limit: policy.minCacheHitPct,
175
+ message: `Prompt cache hit rate ${cacheHitPct}% is below minimum threshold ${policy.minCacheHitPct}%`
176
+ });
177
+ }
178
+ if (wasteRatioPct > policy.maxWasteRatioPct) {
179
+ violations.push({
180
+ ruleId: 'MAX_WASTE_RATIO_PCT',
181
+ actual: wasteRatioPct,
182
+ limit: policy.maxWasteRatioPct,
183
+ message: `Preventable waste ratio ${wasteRatioPct}% exceeds limit ${policy.maxWasteRatioPct}%`
184
+ });
185
+ }
186
+ if (ring0Violations > policy.maxRing0Violations) {
187
+ violations.push({
188
+ ruleId: 'MAX_RING0_VIOLATIONS',
189
+ actual: ring0Violations,
190
+ limit: policy.maxRing0Violations,
191
+ message: `Ring-0 guardrail violations (${ring0Violations}) exceed allowed maximum (${policy.maxRing0Violations})`
192
+ });
193
+ }
194
+
195
+ let verdict = 'PASS';
196
+ let exitCode = 0;
197
+ if (violations.length > 0) {
198
+ if (policy.mode === 'advisory') {
199
+ verdict = 'WARN';
200
+ exitCode = 0;
201
+ } else {
202
+ verdict = 'FAIL';
203
+ exitCode = 1;
204
+ }
205
+ }
206
+
207
+ const annotationLevel = verdict === 'FAIL' ? '::error' : '::warning';
208
+ const annotations = violations.map(
209
+ (v) => `${annotationLevel} title=Burnoff CI Budget Gate (${v.ruleId})::${v.message}`
210
+ );
211
+
212
+ return {
213
+ ok: verdict !== 'FAIL',
214
+ verdict,
215
+ exitCode,
216
+ policy,
217
+ metrics: {
218
+ estimatedCostUsd,
219
+ reconciledCostUsd,
220
+ attributionVariancePct,
221
+ totalTokens,
222
+ cacheHitPct,
223
+ wasteRatioPct,
224
+ ring0Violations,
225
+ totalInputTokens,
226
+ totalCacheReadTokens
227
+ },
228
+ violations,
229
+ annotations
230
+ };
231
+ }
232
+
233
+ /**
234
+ * Formats CI Budget Gate evaluation as GitHub Actions Job Summary / PR comment Markdown.
235
+ */
236
+ export function formatCiGateMarkdown(result = {}) {
237
+ const m = result.metrics || {};
238
+ const p = result.policy || DEFAULT_CI_BUDGET_POLICY;
239
+ const violatedSet = new Set((result.violations || []).map((v) => v.ruleId));
240
+
241
+ const statusTag = (ruleId) => (violatedSet.has(ruleId) ? result.verdict : 'PASS');
242
+
243
+ const lines = [
244
+ `### Burnoff CI / PR Token-Budget Gate: **${result.verdict || 'UNKNOWN'}** (\`mode: ${p.mode}\`)`,
245
+ '',
246
+ '| Check | Actual | Limit | Status |',
247
+ '| :--- | :---: | :---: | :---: |',
248
+ `| \`MAX_PR_COST_USD\` | \`$${Number(m.estimatedCostUsd || 0).toFixed(4)}\` | \`<=$${Number(p.maxPrCostUsd).toFixed(2)}\` | **${statusTag('MAX_PR_COST_USD')}** |`,
249
+ `| \`MAX_PR_TOKENS\` | \`${Number(m.totalTokens || 0).toLocaleString('en-US')}\` | \`<=${Number(p.maxPrTokens).toLocaleString('en-US')}\` | **${statusTag('MAX_PR_TOKENS')}** |`,
250
+ `| \`MIN_CACHE_HIT_PCT\` | \`${m.cacheHitPct ?? 0}%\` | \`>=${p.minCacheHitPct}%\` | **${statusTag('MIN_CACHE_HIT_PCT')}** |`,
251
+ `| \`MAX_WASTE_RATIO_PCT\` | \`${m.wasteRatioPct ?? 0}%\` | \`<=${p.maxWasteRatioPct}%\` | **${statusTag('MAX_WASTE_RATIO_PCT')}** |`,
252
+ `| \`MAX_RING0_VIOLATIONS\` | \`${m.ring0Violations ?? 0}\` | \`<=${p.maxRing0Violations}\` | **${statusTag('MAX_RING0_VIOLATIONS')}** |`
253
+ ];
254
+
255
+ if (Array.isArray(result.violations) && result.violations.length > 0) {
256
+ lines.push('', '#### Violations', '');
257
+ for (const v of result.violations) {
258
+ lines.push(`- **${v.ruleId}**: ${v.message}`);
259
+ }
260
+ }
261
+
262
+ return lines.join('\n') + '\n';
263
+ }
264
+
265
+ export default {
266
+ DEFAULT_CI_BUDGET_POLICY,
267
+ loadCiBudgetPolicy,
268
+ evaluateCiBudgetGate,
269
+ formatCiGateMarkdown
270
+ };