burnoff 0.0.0-stage → 1.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.
@@ -0,0 +1,461 @@
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.1.0';
32
+ }
33
+
34
+ const BOOLEAN_FLAGS = new Set([
35
+ 'json',
36
+ 'dry-run',
37
+ 'gc',
38
+ 'strict',
39
+ 'github-annotations',
40
+ 'markdown',
41
+ 'startup',
42
+ 'foreground',
43
+ 'skip-daemon',
44
+ 'help',
45
+ 'version'
46
+ ]);
47
+
48
+ function parseCliArgs(argv = []) {
49
+ const positionals = [];
50
+ const flags = {};
51
+ for (let i = 0; i < argv.length; i++) {
52
+ const arg = String(argv[i] ?? '');
53
+ if (!arg.startsWith('-')) {
54
+ positionals.push(arg);
55
+ continue;
56
+ }
57
+ if (arg === '-h' || arg === '--help') {
58
+ flags.help = true;
59
+ continue;
60
+ }
61
+ if (arg === '-v' || arg === '--version') {
62
+ flags.version = true;
63
+ continue;
64
+ }
65
+ if (arg.startsWith('--')) {
66
+ const eq = arg.indexOf('=');
67
+ if (eq !== -1) {
68
+ flags[arg.slice(2, eq)] = arg.slice(eq + 1);
69
+ } else {
70
+ const key = arg.slice(2);
71
+ const next = argv[i + 1];
72
+ if (!BOOLEAN_FLAGS.has(key) && next !== undefined && !String(next).startsWith('-')) {
73
+ flags[key] = next;
74
+ i += 1;
75
+ } else {
76
+ flags[key] = true;
77
+ }
78
+ }
79
+ }
80
+ }
81
+ return { positionals, flags };
82
+ }
83
+
84
+ function writeOut(text, outPath, stream = process.stdout) {
85
+ const str = String(text ?? '');
86
+ if (outPath && typeof outPath === 'string') {
87
+ atomicWriteFileSync(path.resolve(outPath), str, { encoding: 'utf8' });
88
+ return;
89
+ }
90
+ stream.write(str);
91
+ }
92
+
93
+ function formatHelp() {
94
+ return [
95
+ `burnoff v${getPackageVersion()} — Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code`,
96
+ '',
97
+ 'Usage:',
98
+ ' burnoff <command> [options]',
99
+ '',
100
+ 'Commands:',
101
+ ' init [--dry-run] [--cwd <dir>] Install PreToolUse/PostToolUse hooks in .claude/settings.local.json',
102
+ ' uninstall [--dry-run] [--cwd <dir>] Remove Burnoff hooks and .git/info/exclude entries',
103
+ ' doctor [--gc] [--json] Run Node/SQLite/hooks/daemon/FTS5/ledger diagnostics',
104
+ ' audit [--startup] [--session <file>] [--json] Audit Claude Code JSONL transcripts or Turn-0 startup config',
105
+ ' pr-cost [--base main] [--json|--markdown] Attribute branch commits to Claude Code token/USD cost',
106
+ ' ci-gate [--strict] [--github-annotations] Enforce .burnoff.yaml ciBudgetGate thresholds',
107
+ ' team-digest [--days 7] [--json] Generate 5-line Engineering Manager spend & savings digest',
108
+ ' search <turnId> [keyword] Query archived FTS5 tool outputs',
109
+ ' daemon <start|stop|status> [--foreground] Manage warm workspace-scoped IPC daemon',
110
+ '',
111
+ 'Options:',
112
+ ' -h, --help Show this help message',
113
+ ' -v, --version Print Burnoff version',
114
+ ''
115
+ ].join('\n');
116
+ }
117
+
118
+ async function handleInit(flags, io) {
119
+ const { initBurnoff } = await import('../src/cli/init.mjs');
120
+ const res = initBurnoff({
121
+ cwd: flags.cwd || process.cwd(),
122
+ dryRun: Boolean(flags['dry-run'])
123
+ });
124
+ if (flags.json) {
125
+ io.stdout.write(JSON.stringify(res, null, 2) + '\n');
126
+ } else {
127
+ io.stdout.write(
128
+ `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}installed in ${res.settingsPath}\n` +
129
+ (res.excludePath ? ` git exclude: ${res.excludePath}\n` : '') +
130
+ (Array.isArray(res.warnings) && res.warnings.length > 0
131
+ ? res.warnings.map((w) => ` warning: ${w}\n`).join('')
132
+ : '')
133
+ );
134
+ }
135
+ return 0;
136
+ }
137
+
138
+ async function handleUninstall(flags, io) {
139
+ const { uninstallBurnoff } = await import('../src/cli/init.mjs');
140
+ const res = uninstallBurnoff({
141
+ cwd: flags.cwd || process.cwd(),
142
+ dryRun: Boolean(flags['dry-run'])
143
+ });
144
+ if (flags.json) {
145
+ io.stdout.write(JSON.stringify(res, null, 2) + '\n');
146
+ } else {
147
+ io.stdout.write(
148
+ `Burnoff hooks ${res.dryRun ? '[DRY RUN] ' : ''}removed from ${res.settingsPath}\n`
149
+ );
150
+ }
151
+ return 0;
152
+ }
153
+
154
+ async function handleDoctor(flags, io) {
155
+ const { runDoctor, formatDoctorReport } = await import('../src/cli/doctor.mjs');
156
+ const report = await runDoctor({
157
+ cwd: flags.cwd || process.cwd(),
158
+ homeDir: flags.home || getHomeDir(),
159
+ gc: Boolean(flags.gc),
160
+ skipDaemonCheck: Boolean(flags['skip-daemon'])
161
+ });
162
+ const text = flags.json ? JSON.stringify(report, null, 2) + '\n' : formatDoctorReport(report);
163
+ writeOut(text, flags.out, io.stdout);
164
+ return report.ok ? 0 : 1;
165
+ }
166
+
167
+ async function handleAudit(flags, io) {
168
+ if (flags.startup) {
169
+ const { runClaudeStartupAudit, formatClaudeStartupAuditReport } = await import('../src/cli/startup-audit.mjs');
170
+ const report = runClaudeStartupAudit({
171
+ cwd: flags.cwd || process.cwd(),
172
+ homeDir: flags.home || getHomeDir(),
173
+ days: flags.days ? Number(flags.days) : 7
174
+ });
175
+ const text = flags.json ? JSON.stringify(report, null, 2) + '\n' : formatClaudeStartupAuditReport(report);
176
+ writeOut(text, flags.out, io.stdout);
177
+ return 0;
178
+ }
179
+ const { auditClaudeSessions, formatAuditReport } = await import('../src/cli/audit.mjs');
180
+ const report = auditClaudeSessions({
181
+ cwd: flags.cwd || process.cwd(),
182
+ homeDir: flags.home || getHomeDir(),
183
+ sessionPath: typeof flags.session === 'string' ? flags.session : undefined,
184
+ limit: flags.limit ? Number(flags.limit) : undefined
185
+ });
186
+ const text = flags.json ? JSON.stringify(report, null, 2) + '\n' : formatAuditReport(report);
187
+ writeOut(text, flags.out, io.stdout);
188
+ return 0;
189
+ }
190
+
191
+ async function handlePrCost(flags, io) {
192
+ const { buildPrCostAttribution, formatPrAttributionMarkdown } = await import('../src/ci/pr-cost.mjs');
193
+ const report = buildPrCostAttribution({
194
+ cwd: flags.cwd || process.cwd(),
195
+ homeDir: flags.home || getHomeDir(),
196
+ base: typeof flags.base === 'string' ? flags.base : 'main',
197
+ head: typeof flags.head === 'string' ? flags.head : 'HEAD',
198
+ providerUsagePath: typeof flags['provider-usage'] === 'string' ? flags['provider-usage'] : undefined
199
+ });
200
+ if (!report.ok) {
201
+ io.stderr.write(`Burnoff pr-cost error: ${report.error || 'failed'}\n`);
202
+ return 1;
203
+ }
204
+ const text = flags.json
205
+ ? JSON.stringify(report, null, 2) + '\n'
206
+ : formatPrAttributionMarkdown(report);
207
+ writeOut(text, flags.out, io.stdout);
208
+ return 0;
209
+ }
210
+
211
+ async function handleCiGate(flags, io) {
212
+ const { evaluateCiBudgetGate, formatCiGateMarkdown } = await import('../src/ci/ci-gate.mjs');
213
+ const result = evaluateCiBudgetGate({
214
+ cwd: flags.cwd || process.cwd(),
215
+ homeDir: flags.home || getHomeDir(),
216
+ base: typeof flags.base === 'string' ? flags.base : 'main',
217
+ head: typeof flags.head === 'string' ? flags.head : 'HEAD',
218
+ inputPath: typeof flags.input === 'string' ? flags.input : undefined,
219
+ providerUsagePath: typeof flags['provider-usage'] === 'string' ? flags['provider-usage'] : undefined,
220
+ strict: Boolean(flags.strict)
221
+ });
222
+ if (result.verdict === 'ERROR') {
223
+ io.stderr.write(`Burnoff ci-gate error: ${result.error || 'failed'}\n`);
224
+ return 1;
225
+ }
226
+ if (flags['github-annotations'] && Array.isArray(result.annotations)) {
227
+ for (const line of result.annotations) {
228
+ io.stdout.write(`${line}\n`);
229
+ }
230
+ }
231
+ const text = flags.json
232
+ ? JSON.stringify(result, null, 2) + '\n'
233
+ : formatCiGateMarkdown(result);
234
+ writeOut(text, flags.out, io.stdout);
235
+ return result.exitCode;
236
+ }
237
+
238
+ async function handleTeamDigest(flags, io) {
239
+ const { buildTeamDigest, formatTeamDigest } = await import('../src/ci/team-digest.mjs');
240
+ const { buildPrCostAttribution } = await import('../src/ci/pr-cost.mjs');
241
+ const cwd = flags.cwd || process.cwd();
242
+ const homeDir = flags.home || getHomeDir();
243
+ const prReports = [];
244
+ try {
245
+ const prReport = buildPrCostAttribution({
246
+ cwd,
247
+ homeDir,
248
+ base: typeof flags.base === 'string' ? flags.base : 'main',
249
+ head: typeof flags.head === 'string' ? flags.head : 'HEAD',
250
+ fallbackToRecent: true
251
+ });
252
+ if (prReport?.ok) {
253
+ prReports.push(prReport);
254
+ }
255
+ } catch {
256
+ // ignore: non-git workspace or unavailable git history falls back to session telemetry
257
+ }
258
+ const digest = buildTeamDigest({
259
+ cwd,
260
+ homeDir,
261
+ days: flags.days ? Number(flags.days) : 7,
262
+ prReports
263
+ });
264
+ const text = flags.json ? JSON.stringify(digest, null, 2) + '\n' : formatTeamDigest(digest);
265
+ writeOut(text, flags.out, io.stdout);
266
+ return 0;
267
+ }
268
+
269
+ async function handleSearch(positionals, flags, io) {
270
+ const { searchToolLogsFts5 } = await import('../src/storage/fts5-archive.mjs');
271
+ const args = positionals.slice(1);
272
+ let turnId = typeof flags.turn === 'string' ? flags.turn : '';
273
+ let keyword = typeof flags.query === 'string' ? flags.query : '';
274
+ if (!turnId && !keyword && args.length >= 2) {
275
+ turnId = args[0];
276
+ keyword = args.slice(1).join(' ');
277
+ } else if (!turnId && !keyword && args.length === 1) {
278
+ if (/^turn[-_]/i.test(args[0])) turnId = args[0];
279
+ else keyword = args[0];
280
+ }
281
+ const searchOpts = {
282
+ turnId,
283
+ keyword,
284
+ limit: flags.limit ? Number(flags.limit) : 10,
285
+ homeDir: flags.home || getHomeDir()
286
+ };
287
+ let res;
288
+ if (typeof flags.db === 'string' && flags.db) {
289
+ res = await searchToolLogsFts5(path.resolve(flags.db), searchOpts);
290
+ } else {
291
+ res = await searchToolLogsFts5(null, searchOpts);
292
+ if (!res || !res.matchedLines || res.matchedLines.length === 0) {
293
+ const wsDbPath = path.join(path.resolve(flags.cwd || process.cwd()), '.claude', 'cache', 'tool_logs_fts5.db');
294
+ if (fs.existsSync(wsDbPath)) {
295
+ const wsRes = await searchToolLogsFts5(wsDbPath, searchOpts);
296
+ if (wsRes.matchedLines && wsRes.matchedLines.length > 0) {
297
+ res = wsRes;
298
+ }
299
+ }
300
+ }
301
+ }
302
+ if (flags.json) {
303
+ io.stdout.write(JSON.stringify(res, null, 2) + '\n');
304
+ return 0;
305
+ }
306
+ if (!res.matchedLines || res.matchedLines.length === 0) {
307
+ io.stdout.write('No matching archived FTS5 tool log lines found.\n');
308
+ return 0;
309
+ }
310
+ for (const line of res.matchedLines) {
311
+ io.stdout.write(`[${line.turnId}:L${line.lineNumber}] ${line.text}\n`);
312
+ }
313
+ return 0;
314
+ }
315
+
316
+ async function handleDaemon(positionals, flags, io) {
317
+ const sub = String(positionals[1] || 'status').toLowerCase();
318
+ const cwd = path.resolve(flags.cwd || process.cwd());
319
+ const homeDir = flags.home || getHomeDir();
320
+ const { sendDaemonRpc, resolveFastIpcPipePath } = await import('../src/ipc/fast-client.mjs');
321
+ const ipcPath = resolveFastIpcPipePath({ cwd, homeDir, ipcPath: flags.ipc });
322
+
323
+ if (sub === 'status') {
324
+ const ping = await sendDaemonRpc('daemon.ping', {}, { cwd, homeDir, ipcPath, requestTimeoutMs: 250 });
325
+ const statusObj = ping?.pong
326
+ ? { running: true, ...ping }
327
+ : { running: false, ipcPath };
328
+ if (flags.json) {
329
+ io.stdout.write(JSON.stringify(statusObj, null, 2) + '\n');
330
+ } else {
331
+ io.stdout.write(
332
+ statusObj.running
333
+ ? `Burnoff daemon running (pid=${statusObj.pid}, ipc=${statusObj.ipcPath}, requests=${statusObj.requestCount})\n`
334
+ : `Burnoff daemon stopped (ipc=${ipcPath})\n`
335
+ );
336
+ }
337
+ return 0;
338
+ }
339
+
340
+ if (sub === 'stop') {
341
+ const stopRes = await sendDaemonRpc('daemon.stop', {}, { cwd, homeDir, ipcPath, requestTimeoutMs: 500 });
342
+ if (flags.json) {
343
+ io.stdout.write(JSON.stringify({ stopped: Boolean(stopRes?.stopping), ipcPath }, null, 2) + '\n');
344
+ } else {
345
+ io.stdout.write(stopRes?.stopping ? `Burnoff daemon stopping (pid=${stopRes.pid})\n` : 'Burnoff daemon not running.\n');
346
+ }
347
+ return 0;
348
+ }
349
+
350
+ if (sub === 'start') {
351
+ const existing = await sendDaemonRpc('daemon.ping', {}, { cwd, homeDir, ipcPath, requestTimeoutMs: 150 });
352
+ if (existing?.pong) {
353
+ io.stdout.write(`Burnoff daemon already running (pid=${existing.pid}, ipc=${existing.ipcPath})\n`);
354
+ return 0;
355
+ }
356
+
357
+ if (flags.foreground) {
358
+ const { BurnoffDaemon } = await import('../src/ipc/daemon.mjs');
359
+ const daemon = new BurnoffDaemon({ cwd, homeDir, ipcPath });
360
+ await daemon.listen();
361
+ io.stdout.write(`Burnoff daemon listening on ${daemon.ipcPath} (pid=${process.pid})\n`);
362
+ await new Promise((resolve) => {
363
+ const stop = () => daemon.close().finally(resolve);
364
+ process.once('SIGINT', stop);
365
+ process.once('SIGTERM', stop);
366
+ });
367
+ return 0;
368
+ }
369
+
370
+ const cliEntry = path.join(PACKAGE_ROOT, 'bin', 'burnoff.mjs');
371
+ const child = spawn(
372
+ process.execPath,
373
+ [cliEntry, 'daemon', 'start', '--foreground', '--cwd', cwd, '--home', homeDir, '--ipc', ipcPath],
374
+ {
375
+ cwd,
376
+ detached: true,
377
+ stdio: 'ignore',
378
+ windowsHide: true
379
+ }
380
+ );
381
+ child.unref();
382
+ let readyPing = null;
383
+ for (let attempt = 0; attempt < 16; attempt += 1) {
384
+ readyPing = await sendDaemonRpc('daemon.ping', {}, { cwd, homeDir, ipcPath, requestTimeoutMs: 100 });
385
+ if (readyPing?.pong) break;
386
+ await new Promise((r) => setTimeout(r, 50));
387
+ }
388
+ io.stdout.write(
389
+ `Burnoff daemon started (pid=${readyPing?.pid || child.pid}, ipc=${ipcPath}, ready=${Boolean(readyPing?.pong)})\n`
390
+ );
391
+ return 0;
392
+ }
393
+
394
+ io.stderr.write(`Unknown daemon subcommand: ${sub}\n`);
395
+ return 1;
396
+ }
397
+
398
+ /**
399
+ * Dispatches Burnoff CLI commands and returns an exit code.
400
+ */
401
+ export async function runCli(argv = process.argv.slice(2), io = { stdout: process.stdout, stderr: process.stderr }) {
402
+ const { positionals, flags } = parseCliArgs(argv);
403
+ const cmd = String(positionals[0] || '').toLowerCase();
404
+
405
+ if (flags.version) {
406
+ io.stdout.write(`${getPackageVersion()}\n`);
407
+ return 0;
408
+ }
409
+ if (!cmd || flags.help || cmd === 'help') {
410
+ io.stdout.write(formatHelp());
411
+ return 0;
412
+ }
413
+
414
+ const nodeStatus = ensureSupportedNodeVersion({
415
+ exitOnUnsupported: false,
416
+ stream: io.stderr,
417
+ quietFallback: Boolean(flags.json)
418
+ });
419
+ if (!nodeStatus.supported) {
420
+ return 1;
421
+ }
422
+
423
+ switch (cmd) {
424
+ case 'init':
425
+ return handleInit(flags, io);
426
+ case 'uninstall':
427
+ return handleUninstall(flags, io);
428
+ case 'doctor':
429
+ return handleDoctor(flags, io);
430
+ case 'audit':
431
+ return handleAudit(flags, io);
432
+ case 'pr-cost':
433
+ return handlePrCost(flags, io);
434
+ case 'ci-gate':
435
+ return handleCiGate(flags, io);
436
+ case 'team-digest':
437
+ return handleTeamDigest(flags, io);
438
+ case 'search':
439
+ return handleSearch(positionals, flags, io);
440
+ case 'daemon':
441
+ return handleDaemon(positionals, flags, io);
442
+ default:
443
+ io.stderr.write(`Unknown command "${cmd}". Run "burnoff --help" for usage.\n`);
444
+ return 1;
445
+ }
446
+ }
447
+
448
+ if (isCliEntrypoint(import.meta.url)) {
449
+ runCli()
450
+ .then((code) => {
451
+ process.exitCode = Number.isInteger(code) ? code : 0;
452
+ })
453
+ .catch((err) => {
454
+ process.stderr.write(`Burnoff error: ${err?.message || String(err)}\n`);
455
+ process.exitCode = 1;
456
+ });
457
+ }
458
+
459
+ export default {
460
+ runCli
461
+ };