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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Burnoff Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,94 @@
1
- # Temporary Holding Version
1
+ # Burnoff
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code.**
4
+
5
+ Burnoff stops runaway agent failure loops, protects repositories from destructive shell commands and credential reads, bounds oversized file reads before they blow up context windows, and enforces per-PR AI spend budgets in GitHub Actions. Designed as a zero-dependency, zero-proxy companion to `rtk` and `ccusage`.
6
+
7
+ ## Why Burnoff?
8
+
9
+ - **Runaway Loop Circuit Breaker (`DET-04`):** Trips after 3 consecutive identical tool/command failures with atomic cross-process state locking (`O_EXCL`), resetting cleanly on success or `git stash`.
10
+ - **Destructive Command & Secret Guards (`DET-01`, `DET-02`, `DET-03`):** Blocks `git push --force`, `--no-verify`, `HUSKY=0`, `rm -rf`, and credential/env reads (allowing safe templates like `.env.example`), while downgrading reversible `git checkout --` / `git restore` calls to an interactive `ask` prompt.
11
+ - **Bounded File-Read Clamp (`updatedInput`):** Caps unbounded doc/log reads (`250 lines / 16 KB`), fast-clamps multi-megabyte sparse files via an `8 MB` head probe (`<50 ms`), trims overlapping re-reads, and leaves active source code unclamped (`neverClampCodeOffCliff: true`).
12
+ - **FTS5 CLI Output Archival (`node:sqlite`):** Archives noisy test/build stdout into `~/.burnoff/cache/tool_logs_fts5.db` while keeping `100%` of critical error lines and returning a `npx burnoff search <turnId> "<keyword>"` handle.
13
+ - **Infracost-Style PR Spend Gates (`pr-cost`, `ci-gate`, `team-digest`):** Attributes branch commits to Claude Code session spend, reconciles against `--provider-usage <export.json>`, and enforces `.burnoff.yaml` thresholds in CI without touching `.claude/settings.json`.
14
+
15
+ ## Requirements
16
+
17
+ - **Node.js `>=20.19.0`** (`Node.js >=22.13.0` recommended for native built-in `node:sqlite` FTS5 indexing; older supported versions automatically run in JSONL fallback mode).
18
+ - **Zero runtime npm dependencies.**
19
+
20
+ ## Quickstart
21
+
22
+ Install hooks into your repository's local Claude Code settings (`.claude/settings.local.json`) and protect `git status` via `.git/info/exclude`:
23
+
24
+ ```bash
25
+ npx burnoff init
26
+ npx burnoff doctor
27
+ ```
28
+
29
+ Remove hooks cleanly at any time:
30
+
31
+ ```bash
32
+ npx burnoff uninstall
33
+ ```
34
+
35
+ ## CLI Commands
36
+
37
+ | Command | Purpose |
38
+ | :--- | :--- |
39
+ | `burnoff init [--dry-run]` | Wire `PreToolUse` and `PostToolUse` hooks in `.claude/settings.local.json` and update `.git/info/exclude`. |
40
+ | `burnoff uninstall [--dry-run]` | Remove Burnoff hooks and `.git/info/exclude` block. |
41
+ | `burnoff doctor [--gc] [--json]` | Inspect Node/SQLite FTS5, `.burnoff.yaml`, hook wiring, warm daemon, ledger, and prune >14d caches with `--gc`. |
42
+ | `burnoff audit [--session <file>] [--json]` | Parse Claude Code JSONL transcripts (`~/.claude/projects/`) and report per-session cost, cache hit %, and 200k-cliff turns. |
43
+ | `burnoff pr-cost [--base main] [--provider-usage file.json]` | Correlate `git log <base>..HEAD` commits with session spend and output Markdown or `burnoff-pr-attribution/v1` JSON. |
44
+ | `burnoff ci-gate [--strict] [--github-annotations]` | Enforce `.burnoff.yaml` `ciBudgetGate` thresholds (`MAX_PR_COST_USD`, `MAX_PR_TOKENS`, `MIN_CACHE_HIT_PCT`, `MAX_WASTE_RATIO_PCT`, `MAX_RING0_VIOLATIONS`). |
45
+ | `burnoff team-digest [--days 7]` | Output a 5-line weekly Engineering Manager summary of spend, cache efficiency, top cost driver, and guard savings. |
46
+ | `burnoff search <turnId> [keyword]` | Search archived FTS5 CLI output without re-running expensive test or build commands. |
47
+ | `burnoff daemon <start\|stop\|status>` | Manage the workspace-scoped warm IPC daemon (`~/.burnoff/run/` or Windows named pipe). |
48
+
49
+ ## Team Policy (`.burnoff.yaml`)
50
+
51
+ Create an optional `.burnoff.yaml` in your repository root to customize guardrails and CI spend gates:
52
+
53
+ ```yaml
54
+ guards:
55
+ mode: guard
56
+ det04Threshold: 3
57
+ strictTestIntegrity: false
58
+ scopeLockEnabled: true
59
+
60
+ readClamp:
61
+ enabled: true
62
+ maxLines: 250
63
+ maxBytes: 16384
64
+ neverClampCodeOffCliff: true
65
+
66
+ postTool:
67
+ fts5Enabled: true
68
+ minBytesToCompress: 6144
69
+ retentionDays: 30
70
+
71
+ ciBudgetGate:
72
+ maxPrCostUsd: 15
73
+ maxPrTokens: 1500000
74
+ minCacheHitPct: 50
75
+ maxWasteRatioPct: 35
76
+ maxRing0Violations: 0
77
+ mode: enforce
78
+ ```
79
+
80
+ ## GitHub Actions PR Gate
81
+
82
+ See [`.github/workflows/burnoff-pr-gate.yml`](.github/workflows/burnoff-pr-gate.yml) for a SHA-pinned, least-privilege (`permissions: contents: read`) workflow that computes PR cost attribution, enforces `ci-gate --strict`, and posts PR summary comments on non-fork PRs.
83
+
84
+ ## Environment Variables
85
+
86
+ - `BURNOFF_HOME`: Override `~/.burnoff/` state directory.
87
+ - `BURNOFF_IPC_PATH`: Override daemon named pipe / Unix domain socket path.
88
+ - `BURNOFF_PRETOOL_FAIL_MODE`: Set to `closed` to fail-closed on internal hook faults (guard `exitCode: 2` blocks always fail-closed).
89
+ - `BURNOFF_POST_OUTPUT_MODE`: Override `PostToolUse` output mode (`auto`, `updatedToolOutput`, `additionalContext`).
90
+ - `BURNOFF_TIER1_ACTIVE`: Set to `1` to enable Tier-1 `Grep`/`Glob` fast-path pass-through.
91
+
92
+ ## License
93
+
94
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,406 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file bin/burnoff.mjs
4
+ * Single CLI entrypoint for Burnoff (`burnoff`).
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { spawn } from 'node:child_process';
10
+ import { fileURLToPath } from 'node:url';
11
+ import {
12
+ suppressSqliteExperimentalWarning,
13
+ ensureSupportedNodeVersion,
14
+ getHomeDir
15
+ } from '../src/config/paths.mjs';
16
+ import { isCliEntrypoint } from '../hooks/hook-io.mjs';
17
+ import { atomicWriteFileSync } from '../src/storage/atomic-io.mjs';
18
+
19
+ suppressSqliteExperimentalWarning();
20
+
21
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
22
+ const PACKAGE_ROOT = path.resolve(__dirname, '..');
23
+
24
+ function getPackageVersion() {
25
+ try {
26
+ const pkg = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8'));
27
+ if (pkg?.version) return String(pkg.version);
28
+ } catch (err) {
29
+ void err; // ignore: package.json read fallback
30
+ }
31
+ return '1.0.0';
32
+ }
33
+
34
+ function parseCliArgs(argv = []) {
35
+ const positionals = [];
36
+ const flags = {};
37
+ for (let i = 0; i < argv.length; i++) {
38
+ const arg = String(argv[i] ?? '');
39
+ if (!arg.startsWith('-')) {
40
+ positionals.push(arg);
41
+ continue;
42
+ }
43
+ if (arg === '-h' || arg === '--help') {
44
+ flags.help = true;
45
+ continue;
46
+ }
47
+ if (arg === '-v' || arg === '--version') {
48
+ flags.version = true;
49
+ continue;
50
+ }
51
+ if (arg.startsWith('--')) {
52
+ const eq = arg.indexOf('=');
53
+ if (eq !== -1) {
54
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1);
55
+ } else {
56
+ const key = arg.slice(2);
57
+ const next = argv[i + 1];
58
+ if (next !== undefined && !String(next).startsWith('-')) {
59
+ flags[key] = next;
60
+ i += 1;
61
+ } else {
62
+ flags[key] = true;
63
+ }
64
+ }
65
+ }
66
+ }
67
+ return { positionals, flags };
68
+ }
69
+
70
+ function writeOut(text, outPath, stream = process.stdout) {
71
+ const str = String(text ?? '');
72
+ if (outPath && typeof outPath === 'string') {
73
+ atomicWriteFileSync(path.resolve(outPath), str, { encoding: 'utf8' });
74
+ return;
75
+ }
76
+ stream.write(str);
77
+ }
78
+
79
+ function formatHelp() {
80
+ return [
81
+ `burnoff v${getPackageVersion()} — Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code`,
82
+ '',
83
+ 'Usage:',
84
+ ' burnoff <command> [options]',
85
+ '',
86
+ 'Commands:',
87
+ ' init [--dry-run] [--cwd <dir>] Install PreToolUse/PostToolUse hooks in .claude/settings.local.json',
88
+ ' uninstall [--dry-run] [--cwd <dir>] Remove Burnoff hooks and .git/info/exclude entries',
89
+ ' doctor [--gc] [--json] Run Node/SQLite/hooks/daemon/FTS5/ledger diagnostics',
90
+ ' audit [--session <file>] [--json] Audit Claude Code JSONL transcripts and spend',
91
+ ' pr-cost [--base main] [--json|--markdown] Attribute branch commits to Claude Code token/USD cost',
92
+ ' ci-gate [--strict] [--github-annotations] Enforce .burnoff.yaml ciBudgetGate thresholds',
93
+ ' team-digest [--days 7] [--json] Generate 5-line Engineering Manager spend & savings digest',
94
+ ' search <turnId> [keyword] Query archived FTS5 tool outputs',
95
+ ' daemon <start|stop|status> [--foreground] Manage warm workspace-scoped IPC daemon',
96
+ '',
97
+ 'Options:',
98
+ ' -h, --help Show this help message',
99
+ ' -v, --version Print Burnoff version',
100
+ ''
101
+ ].join('\n');
102
+ }
103
+
104
+ async function handleInit(flags, io) {
105
+ const { initBurnoff } = await import('../src/cli/init.mjs');
106
+ const res = initBurnoff({
107
+ cwd: flags.cwd || process.cwd(),
108
+ dryRun: Boolean(flags['dry-run'])
109
+ });
110
+ if (flags.json) {
111
+ io.stdout.write(JSON.stringify(res, null, 2) + '\n');
112
+ } else {
113
+ io.stdout.write(
114
+ `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}installed in ${res.settingsPath}\n` +
115
+ (res.excludePath ? ` git exclude: ${res.excludePath}\n` : '')
116
+ );
117
+ }
118
+ return 0;
119
+ }
120
+
121
+ async function handleUninstall(flags, io) {
122
+ const { uninstallBurnoff } = await import('../src/cli/init.mjs');
123
+ const res = uninstallBurnoff({
124
+ cwd: flags.cwd || process.cwd(),
125
+ dryRun: Boolean(flags['dry-run'])
126
+ });
127
+ if (flags.json) {
128
+ io.stdout.write(JSON.stringify(res, null, 2) + '\n');
129
+ } else {
130
+ io.stdout.write(
131
+ `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}removed from ${res.settingsPath}\n`
132
+ );
133
+ }
134
+ return 0;
135
+ }
136
+
137
+ async function handleDoctor(flags, io) {
138
+ const { runDoctor, formatDoctorReport } = await import('../src/cli/doctor.mjs');
139
+ const report = await runDoctor({
140
+ cwd: flags.cwd || process.cwd(),
141
+ homeDir: flags.home || getHomeDir(),
142
+ gc: Boolean(flags.gc),
143
+ skipDaemonCheck: Boolean(flags['skip-daemon'])
144
+ });
145
+ const text = flags.json ? JSON.stringify(report, null, 2) + '\n' : formatDoctorReport(report);
146
+ writeOut(text, flags.out, io.stdout);
147
+ return report.ok ? 0 : 1;
148
+ }
149
+
150
+ async function handleAudit(flags, io) {
151
+ const { auditClaudeSessions, formatAuditReport } = await import('../src/cli/audit.mjs');
152
+ const report = auditClaudeSessions({
153
+ cwd: flags.cwd || process.cwd(),
154
+ homeDir: flags.home || getHomeDir(),
155
+ sessionPath: typeof flags.session === 'string' ? flags.session : undefined,
156
+ limit: flags.limit ? Number(flags.limit) : undefined
157
+ });
158
+ const text = flags.json ? JSON.stringify(report, null, 2) + '\n' : formatAuditReport(report);
159
+ writeOut(text, flags.out, io.stdout);
160
+ return 0;
161
+ }
162
+
163
+ async function handlePrCost(flags, io) {
164
+ const { buildPrCostAttribution, formatPrAttributionMarkdown } = await import('../src/ci/pr-cost.mjs');
165
+ const report = buildPrCostAttribution({
166
+ cwd: flags.cwd || process.cwd(),
167
+ homeDir: flags.home || getHomeDir(),
168
+ base: typeof flags.base === 'string' ? flags.base : 'main',
169
+ head: typeof flags.head === 'string' ? flags.head : 'HEAD',
170
+ providerUsagePath: typeof flags['provider-usage'] === 'string' ? flags['provider-usage'] : undefined
171
+ });
172
+ if (!report.ok) {
173
+ io.stderr.write(`Burnoff pr-cost error: ${report.error || 'failed'}\n`);
174
+ return 1;
175
+ }
176
+ const text = flags.json
177
+ ? JSON.stringify(report, null, 2) + '\n'
178
+ : formatPrAttributionMarkdown(report);
179
+ writeOut(text, flags.out, io.stdout);
180
+ return 0;
181
+ }
182
+
183
+ async function handleCiGate(flags, io) {
184
+ const { evaluateCiBudgetGate, formatCiGateMarkdown } = await import('../src/ci/ci-gate.mjs');
185
+ const result = evaluateCiBudgetGate({
186
+ cwd: flags.cwd || process.cwd(),
187
+ homeDir: flags.home || getHomeDir(),
188
+ base: typeof flags.base === 'string' ? flags.base : 'main',
189
+ head: typeof flags.head === 'string' ? flags.head : 'HEAD',
190
+ inputPath: typeof flags.input === 'string' ? flags.input : undefined,
191
+ providerUsagePath: typeof flags['provider-usage'] === 'string' ? flags['provider-usage'] : undefined,
192
+ strict: Boolean(flags.strict)
193
+ });
194
+ if (result.verdict === 'ERROR') {
195
+ io.stderr.write(`Burnoff ci-gate error: ${result.error || 'failed'}\n`);
196
+ return 1;
197
+ }
198
+ if (flags['github-annotations'] && Array.isArray(result.annotations)) {
199
+ for (const line of result.annotations) {
200
+ io.stdout.write(`${line}\n`);
201
+ }
202
+ }
203
+ const text = flags.json
204
+ ? JSON.stringify(result, null, 2) + '\n'
205
+ : formatCiGateMarkdown(result);
206
+ writeOut(text, flags.out, io.stdout);
207
+ return result.exitCode;
208
+ }
209
+
210
+ async function handleTeamDigest(flags, io) {
211
+ const { buildTeamDigest, formatTeamDigest } = await import('../src/ci/team-digest.mjs');
212
+ const digest = buildTeamDigest({
213
+ cwd: flags.cwd || process.cwd(),
214
+ homeDir: flags.home || getHomeDir(),
215
+ days: flags.days ? Number(flags.days) : 7
216
+ });
217
+ const text = flags.json ? JSON.stringify(digest, null, 2) + '\n' : formatTeamDigest(digest);
218
+ writeOut(text, flags.out, io.stdout);
219
+ return 0;
220
+ }
221
+
222
+ async function handleSearch(positionals, flags, io) {
223
+ const { searchToolLogsFts5 } = await import('../src/storage/fts5-archive.mjs');
224
+ const args = positionals.slice(1);
225
+ let turnId = typeof flags.turn === 'string' ? flags.turn : '';
226
+ let keyword = typeof flags.query === 'string' ? flags.query : '';
227
+ if (!turnId && !keyword && args.length >= 2) {
228
+ turnId = args[0];
229
+ keyword = args.slice(1).join(' ');
230
+ } else if (!turnId && !keyword && args.length === 1) {
231
+ if (/^turn[-_]/i.test(args[0])) turnId = args[0];
232
+ else keyword = args[0];
233
+ }
234
+ const searchOpts = {
235
+ turnId,
236
+ keyword,
237
+ limit: flags.limit ? Number(flags.limit) : 10,
238
+ homeDir: flags.home || getHomeDir()
239
+ };
240
+ let res;
241
+ if (typeof flags.db === 'string' && flags.db) {
242
+ res = await searchToolLogsFts5(path.resolve(flags.db), searchOpts);
243
+ } else {
244
+ const wsDbPath = path.join(path.resolve(flags.cwd || process.cwd()), '.claude', 'cache', 'tool_logs_fts5.db');
245
+ if (fs.existsSync(wsDbPath)) {
246
+ res = await searchToolLogsFts5(wsDbPath, searchOpts);
247
+ }
248
+ if (!res || !res.matchedLines || res.matchedLines.length === 0) {
249
+ const homeRes = await searchToolLogsFts5(null, searchOpts);
250
+ if (!res || (homeRes.matchedLines && homeRes.matchedLines.length > 0)) {
251
+ res = homeRes;
252
+ }
253
+ }
254
+ }
255
+ if (flags.json) {
256
+ io.stdout.write(JSON.stringify(res, null, 2) + '\n');
257
+ return 0;
258
+ }
259
+ if (!res.matchedLines || res.matchedLines.length === 0) {
260
+ io.stdout.write('No matching archived FTS5 tool log lines found.\n');
261
+ return 0;
262
+ }
263
+ for (const line of res.matchedLines) {
264
+ io.stdout.write(`[${line.turnId}:L${line.lineNumber}] ${line.text}\n`);
265
+ }
266
+ return 0;
267
+ }
268
+
269
+ async function handleDaemon(positionals, flags, io) {
270
+ const sub = String(positionals[1] || 'status').toLowerCase();
271
+ const cwd = path.resolve(flags.cwd || process.cwd());
272
+ const homeDir = flags.home || getHomeDir();
273
+ const { sendDaemonRpc, resolveFastIpcPipePath } = await import('../src/ipc/fast-client.mjs');
274
+ const ipcPath = resolveFastIpcPipePath({ cwd, homeDir, ipcPath: flags.ipc });
275
+
276
+ if (sub === 'status') {
277
+ const ping = await sendDaemonRpc('daemon.ping', {}, { cwd, homeDir, ipcPath, requestTimeoutMs: 250 });
278
+ const statusObj = ping?.pong
279
+ ? { running: true, ...ping }
280
+ : { running: false, ipcPath };
281
+ if (flags.json) {
282
+ io.stdout.write(JSON.stringify(statusObj, null, 2) + '\n');
283
+ } else {
284
+ io.stdout.write(
285
+ statusObj.running
286
+ ? `Burnoff daemon running (pid=${statusObj.pid}, ipc=${statusObj.ipcPath}, requests=${statusObj.requestCount})\n`
287
+ : `Burnoff daemon stopped (ipc=${ipcPath})\n`
288
+ );
289
+ }
290
+ return 0;
291
+ }
292
+
293
+ if (sub === 'stop') {
294
+ const stopRes = await sendDaemonRpc('daemon.stop', {}, { cwd, homeDir, ipcPath, requestTimeoutMs: 500 });
295
+ if (flags.json) {
296
+ io.stdout.write(JSON.stringify({ stopped: Boolean(stopRes?.stopping), ipcPath }, null, 2) + '\n');
297
+ } else {
298
+ io.stdout.write(stopRes?.stopping ? `Burnoff daemon stopping (pid=${stopRes.pid})\n` : 'Burnoff daemon not running.\n');
299
+ }
300
+ return 0;
301
+ }
302
+
303
+ if (sub === 'start') {
304
+ const existing = await sendDaemonRpc('daemon.ping', {}, { cwd, homeDir, ipcPath, requestTimeoutMs: 150 });
305
+ if (existing?.pong) {
306
+ io.stdout.write(`Burnoff daemon already running (pid=${existing.pid}, ipc=${existing.ipcPath})\n`);
307
+ return 0;
308
+ }
309
+
310
+ if (flags.foreground) {
311
+ const { BurnoffDaemon } = await import('../src/ipc/daemon.mjs');
312
+ const daemon = new BurnoffDaemon({ cwd, homeDir, ipcPath });
313
+ await daemon.listen();
314
+ io.stdout.write(`Burnoff daemon listening on ${daemon.ipcPath} (pid=${process.pid})\n`);
315
+ await new Promise((resolve) => {
316
+ const stop = () => daemon.close().finally(resolve);
317
+ process.once('SIGINT', stop);
318
+ process.once('SIGTERM', stop);
319
+ });
320
+ return 0;
321
+ }
322
+
323
+ const cliEntry = path.join(PACKAGE_ROOT, 'bin', 'burnoff.mjs');
324
+ const child = spawn(
325
+ process.execPath,
326
+ [cliEntry, 'daemon', 'start', '--foreground', '--cwd', cwd, '--ipc', ipcPath],
327
+ {
328
+ cwd,
329
+ detached: true,
330
+ stdio: 'ignore',
331
+ windowsHide: true
332
+ }
333
+ );
334
+ child.unref();
335
+ io.stdout.write(`Burnoff daemon started (pid=${child.pid}, ipc=${ipcPath})\n`);
336
+ return 0;
337
+ }
338
+
339
+ io.stderr.write(`Unknown daemon subcommand: ${sub}\n`);
340
+ return 1;
341
+ }
342
+
343
+ /**
344
+ * Dispatches Burnoff CLI commands and returns an exit code.
345
+ */
346
+ export async function runCli(argv = process.argv.slice(2), io = { stdout: process.stdout, stderr: process.stderr }) {
347
+ const { positionals, flags } = parseCliArgs(argv);
348
+ const cmd = String(positionals[0] || '').toLowerCase();
349
+
350
+ if (flags.version) {
351
+ io.stdout.write(`${getPackageVersion()}\n`);
352
+ return 0;
353
+ }
354
+ if (!cmd || flags.help || cmd === 'help') {
355
+ io.stdout.write(formatHelp());
356
+ return 0;
357
+ }
358
+
359
+ const nodeStatus = ensureSupportedNodeVersion({
360
+ exitOnUnsupported: false,
361
+ stream: io.stderr,
362
+ quietFallback: Boolean(flags.json)
363
+ });
364
+ if (!nodeStatus.supported) {
365
+ return 1;
366
+ }
367
+
368
+ switch (cmd) {
369
+ case 'init':
370
+ return handleInit(flags, io);
371
+ case 'uninstall':
372
+ return handleUninstall(flags, io);
373
+ case 'doctor':
374
+ return handleDoctor(flags, io);
375
+ case 'audit':
376
+ return handleAudit(flags, io);
377
+ case 'pr-cost':
378
+ return handlePrCost(flags, io);
379
+ case 'ci-gate':
380
+ return handleCiGate(flags, io);
381
+ case 'team-digest':
382
+ return handleTeamDigest(flags, io);
383
+ case 'search':
384
+ return handleSearch(positionals, flags, io);
385
+ case 'daemon':
386
+ return handleDaemon(positionals, flags, io);
387
+ default:
388
+ io.stderr.write(`Unknown command "${cmd}". Run "burnoff --help" for usage.\n`);
389
+ return 1;
390
+ }
391
+ }
392
+
393
+ if (isCliEntrypoint(import.meta.url)) {
394
+ runCli()
395
+ .then((code) => {
396
+ process.exitCode = Number.isInteger(code) ? code : 0;
397
+ })
398
+ .catch((err) => {
399
+ process.stderr.write(`Burnoff error: ${err?.message || String(err)}\n`);
400
+ process.exitCode = 1;
401
+ });
402
+ }
403
+
404
+ export default {
405
+ runCli
406
+ };