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,196 @@
1
+ /**
2
+ * @file src/cli/audit.mjs
3
+ * Claude Code JSONL transcript auditor (`burnoff audit`).
4
+ * Discovers `~/.claude/projects/*.jsonl`, parses via `parseTranscriptIncremental()`,
5
+ * and calculates per-session & aggregate token/USD spend and pricing-cliff hits.
6
+ */
7
+
8
+ import path from 'node:path';
9
+ import { getHomeDir } from '../config/paths.mjs';
10
+ import { calculateTurnCostUSD } from '../config/loader.mjs';
11
+ import {
12
+ discoverClaudeCodeSessions,
13
+ parseTranscriptIncremental
14
+ } from '../storage/jsonl-parser.mjs';
15
+ import { getSavedQuotaReceiptSummary } from '../storage/ledger.mjs';
16
+
17
+ function summarizeParsedSession(meta, parsed, options = {}) {
18
+ const steps = Array.isArray(parsed?.steps) ? parsed.steps : [];
19
+ let inputTokens = 0;
20
+ let cacheWriteTokens = 0;
21
+ let cacheReadTokens = 0;
22
+ let outputTokens = 0;
23
+ let thinkingTokens = 0;
24
+ let estimatedCostUsd = 0;
25
+ let cliffTurns = 0;
26
+ let unknownModelTurns = 0;
27
+ let lastModel = 'claude-sonnet-5-5';
28
+
29
+ for (const step of steps) {
30
+ const u = step?.tokenUsage || step || {};
31
+ const inTok = Number(u.freshInputTokens ?? u.inputTokens ?? 0);
32
+ const w5m = Number(u.cacheCreationEphemeral5mInputTokens ?? 0);
33
+ const w1h = Number(u.cacheCreationEphemeral1hInputTokens ?? 0);
34
+ const cwTok = Number(u.cacheCreationTokens ?? w5m + w1h ?? 0);
35
+ const crTok = Number(u.cacheReadTokens ?? 0);
36
+ const outTok = Number(u.outputTokens ?? 0);
37
+ const thinkTok = Number(u.thinkingTokens ?? 0);
38
+ if (inTok + cwTok + crTok + outTok + thinkTok === 0) continue;
39
+
40
+ if (step.model) lastModel = step.model;
41
+ const costRes = calculateTurnCostUSD(
42
+ {
43
+ model: step.model || lastModel,
44
+ inputTokens: inTok,
45
+ cacheWrite5mTokens: w5m,
46
+ cacheWrite1hTokens: w1h,
47
+ cacheWriteTokens: cwTok,
48
+ cacheReadTokens: crTok,
49
+ outputTokens: outTok,
50
+ thinkingTokens: thinkTok
51
+ },
52
+ options
53
+ );
54
+
55
+ inputTokens += inTok;
56
+ cacheWriteTokens += cwTok;
57
+ cacheReadTokens += crTok;
58
+ outputTokens += outTok;
59
+ thinkingTokens += thinkTok;
60
+
61
+ if (costRes.unknownModel) {
62
+ unknownModelTurns += 1;
63
+ } else {
64
+ estimatedCostUsd += Number(costRes.costsUSD.totalActualSpendUSD || 0);
65
+ if (costRes.cliffTriggered) cliffTurns += 1;
66
+ }
67
+ }
68
+
69
+ const totalTokens = inputTokens + cacheWriteTokens + cacheReadTokens + outputTokens + thinkingTokens;
70
+ const cacheDenom = inputTokens + cacheWriteTokens + cacheReadTokens;
71
+ const cacheHitPct = cacheDenom > 0 ? Math.round((cacheReadTokens / cacheDenom) * 100) : 0;
72
+
73
+ return {
74
+ sessionId: meta.sessionId || path.basename(meta.filePath || 'session.jsonl', '.jsonl'),
75
+ fileName: path.basename(meta.filePath || ''),
76
+ projectSlug: meta.projectSlug || '',
77
+ sessionTitle: parsed?.sessionTitle || '',
78
+ modelId: lastModel,
79
+ turns: steps.length,
80
+ inputTokens,
81
+ cacheWriteTokens,
82
+ cacheReadTokens,
83
+ outputTokens,
84
+ thinkingTokens,
85
+ totalTokens,
86
+ cacheHitPct,
87
+ estimatedCostUsd: Number(estimatedCostUsd.toFixed(4)),
88
+ cliffTurns,
89
+ unknownModelTurns,
90
+ rewindBranches: Array.isArray(parsed?.claudeDag?.rewindBranches)
91
+ ? parsed.claudeDag.rewindBranches.length
92
+ : 0,
93
+ mtimeMs: meta.mtimeMs || 0
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Audits local Claude Code JSONL transcripts (or a single `--session <path>` file).
99
+ */
100
+ export function auditClaudeSessions(options = {}) {
101
+ const homeDir = options.homeDir || getHomeDir();
102
+ const limit = Math.max(1, Number(options.limit ?? 20));
103
+ const candidates = options.sessionPath
104
+ ? [
105
+ {
106
+ filePath: path.resolve(options.sessionPath),
107
+ sessionId: path.basename(options.sessionPath, '.jsonl'),
108
+ projectSlug: '',
109
+ mtimeMs: 0
110
+ }
111
+ ]
112
+ : discoverClaudeCodeSessions(homeDir, options).slice(0, limit);
113
+
114
+ const sessions = [];
115
+ for (const meta of candidates) {
116
+ const parsed = parseTranscriptIncremental(meta.filePath, {
117
+ homeDir,
118
+ tailBytes: options.tailBytes
119
+ });
120
+ sessions.push(summarizeParsedSession(meta, parsed, options));
121
+ }
122
+
123
+ const totals = sessions.reduce(
124
+ (acc, s) => {
125
+ acc.sessions += 1;
126
+ acc.turns += s.turns;
127
+ acc.inputTokens += s.inputTokens;
128
+ acc.cacheWriteTokens += s.cacheWriteTokens;
129
+ acc.cacheReadTokens += s.cacheReadTokens;
130
+ acc.outputTokens += s.outputTokens;
131
+ acc.thinkingTokens += s.thinkingTokens;
132
+ acc.totalTokens += s.totalTokens;
133
+ acc.estimatedCostUsd = Number((acc.estimatedCostUsd + s.estimatedCostUsd).toFixed(4));
134
+ acc.cliffTurns += s.cliffTurns;
135
+ acc.rewindBranches += s.rewindBranches;
136
+ return acc;
137
+ },
138
+ {
139
+ sessions: 0,
140
+ turns: 0,
141
+ inputTokens: 0,
142
+ cacheWriteTokens: 0,
143
+ cacheReadTokens: 0,
144
+ outputTokens: 0,
145
+ thinkingTokens: 0,
146
+ totalTokens: 0,
147
+ cacheHitPct: 0,
148
+ estimatedCostUsd: 0,
149
+ cliffTurns: 0,
150
+ rewindBranches: 0
151
+ }
152
+ );
153
+ const denom = totals.inputTokens + totals.cacheWriteTokens + totals.cacheReadTokens;
154
+ totals.cacheHitPct = denom > 0 ? Math.round((totals.cacheReadTokens / denom) * 100) : 0;
155
+
156
+ const ledger = getSavedQuotaReceiptSummary({ homeDir });
157
+
158
+ return {
159
+ ok: true,
160
+ totals,
161
+ ledger: {
162
+ avoidedWriteUSD: ledger.burnoffAvoidedWriteUSD,
163
+ avoidedWriteTokens: ledger.burnoffAvoidedWriteTokens,
164
+ platformCacheUSD: ledger.platformCacheDiscountUSD
165
+ },
166
+ sessions
167
+ };
168
+ }
169
+
170
+ /**
171
+ * Formats an `auditClaudeSessions()` report for terminal output.
172
+ */
173
+ export function formatAuditReport(report = {}) {
174
+ const t = report.totals || {};
175
+ const lines = [
176
+ `Burnoff Claude Code Session Audit (${t.sessions ?? 0} sessions, ${t.turns ?? 0} steps)`,
177
+ ` Total Tokens : ${(t.totalTokens ?? 0).toLocaleString('en-US')} (cache hit ${t.cacheHitPct ?? 0}%)`,
178
+ ` Estimated Cost : $${Number(t.estimatedCostUsd || 0).toFixed(4)} | 200k-cliff turns=${t.cliffTurns ?? 0} | rewind branches=${t.rewindBranches ?? 0}`,
179
+ ` Guard Savings : $${Number(report.ledger?.avoidedWriteUSD || 0).toFixed(4)} avoided (${(report.ledger?.avoidedWriteTokens || 0).toLocaleString('en-US')} tok)`
180
+ ];
181
+ if (Array.isArray(report.sessions) && report.sessions.length > 0) {
182
+ lines.push('', ' Recent Sessions:');
183
+ for (const s of report.sessions.slice(0, 10)) {
184
+ const title = s.sessionTitle ? ` "${s.sessionTitle.slice(0, 36)}"` : '';
185
+ lines.push(
186
+ ` - ${s.sessionId.slice(0, 16)} | ${s.turns} steps | ${(s.totalTokens / 1000).toFixed(1)}k tok | ${s.cacheHitPct}% hit | $${s.estimatedCostUsd.toFixed(4)}${title}`
187
+ );
188
+ }
189
+ }
190
+ return lines.join('\n') + '\n';
191
+ }
192
+
193
+ export default {
194
+ auditClaudeSessions,
195
+ formatAuditReport
196
+ };
@@ -0,0 +1,257 @@
1
+ /**
2
+ * @file src/cli/doctor.mjs
3
+ * Burnoff local diagnostics & garbage collection (`burnoff doctor [--gc]`).
4
+ * Checks Node/SQLite support, `.burnoff.yaml` policy, `.claude/settings.local.json` hooks,
5
+ * warm daemon status, FTS5 archive health, ledger summary, and `atomic-io` retry metrics.
6
+ */
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import {
11
+ MIN_NODE_VERSION,
12
+ NATIVE_SQLITE_NODE_VERSION,
13
+ isSupportedNodeVersion,
14
+ hasNativeNodeSqlite,
15
+ getHomeDir,
16
+ getBurnoffHomeDir,
17
+ getBurnoffCacheDir
18
+ } from '../config/paths.mjs';
19
+ import { loadBurnoffPolicy } from '../config/policy.mjs';
20
+ import { getAtomicIoMetrics } from '../storage/atomic-io.mjs';
21
+ import {
22
+ getDefaultToolLogsDbPath,
23
+ getFts5CompressionStats,
24
+ pruneExpiredFts5LogsSync
25
+ } from '../storage/fts5-archive.mjs';
26
+ import { getSavedQuotaReceiptSummary, rotateMonthlyLedger } from '../storage/ledger.mjs';
27
+ import { openBurnoffDb } from '../storage/sqlite-client.mjs';
28
+ import { sendDaemonRpc, resolveFastIpcPipePath } from '../ipc/fast-client.mjs';
29
+
30
+ function inspectHookWiring(cwd) {
31
+ const settingsLocalPath = path.join(cwd, '.claude', 'settings.local.json');
32
+ let preToolHook = false;
33
+ let postToolHook = false;
34
+
35
+ if (fs.existsSync(settingsLocalPath)) {
36
+ try {
37
+ const parsed = JSON.parse(fs.readFileSync(settingsLocalPath, 'utf8'));
38
+ const hooks = parsed?.hooks || {};
39
+ const containsHook = (groups, targetName) =>
40
+ Array.isArray(groups) &&
41
+ groups.some((g) =>
42
+ Array.isArray(g?.hooks)
43
+ ? g.hooks.some((h) => String(h?.command || '').includes(targetName))
44
+ : String(g?.command || '').includes(targetName)
45
+ );
46
+ preToolHook = containsHook(hooks.PreToolUse, 'pre-tool-use.mjs');
47
+ postToolHook = containsHook(hooks.PostToolUse, 'post-tool-use.mjs');
48
+ } catch (err) {
49
+ void err; // ignore: malformed settings.local.json reported as unwired
50
+ }
51
+ }
52
+
53
+ let gitExcludeProtected = false;
54
+ const dotGit = path.join(cwd, '.git');
55
+ let excludePath = null;
56
+ if (fs.existsSync(dotGit)) {
57
+ try {
58
+ const st = fs.statSync(dotGit);
59
+ let gitDir = st.isDirectory() ? dotGit : null;
60
+ if (!gitDir && st.isFile()) {
61
+ const m = fs.readFileSync(dotGit, 'utf8').match(/^gitdir:\s*(.+)$/im);
62
+ if (m && m[1]) {
63
+ gitDir = path.isAbsolute(m[1].trim()) ? m[1].trim() : path.resolve(cwd, m[1].trim());
64
+ }
65
+ }
66
+ if (gitDir) {
67
+ excludePath = path.join(gitDir, 'info', 'exclude');
68
+ if (fs.existsSync(excludePath)) {
69
+ const text = fs.readFileSync(excludePath, 'utf8');
70
+ gitExcludeProtected = text.includes('.claude/settings.local.json');
71
+ }
72
+ }
73
+ } catch (err) {
74
+ void err; // ignore: unreadable git metadata leaves exclude status false
75
+ }
76
+ }
77
+
78
+ return {
79
+ settingsLocalPath,
80
+ installed: preToolHook && postToolHook,
81
+ preToolHook,
82
+ postToolHook,
83
+ excludePath,
84
+ gitExcludeProtected
85
+ };
86
+ }
87
+
88
+ function reapStaleCacheFiles(dirPath, cutoffMs, skipNames = new Set()) {
89
+ let removedFiles = 0;
90
+ let reclaimedBytes = 0;
91
+ if (!dirPath || !fs.existsSync(dirPath)) {
92
+ return { removedFiles, reclaimedBytes };
93
+ }
94
+ let entries = [];
95
+ try {
96
+ entries = fs.readdirSync(dirPath, { withFileTypes: true });
97
+ } catch (err) {
98
+ void err; // ignore: missing or unreadable cache directory
99
+ return { removedFiles, reclaimedBytes };
100
+ }
101
+ for (const entry of entries) {
102
+ if (!entry.isFile()) continue;
103
+ if (skipNames.has(entry.name) || entry.name.startsWith('tool_logs_fts5.db')) continue;
104
+ const full = path.join(dirPath, entry.name);
105
+ try {
106
+ const st = fs.statSync(full);
107
+ if (st.mtimeMs < cutoffMs) {
108
+ fs.unlinkSync(full);
109
+ removedFiles += 1;
110
+ reclaimedBytes += st.size;
111
+ }
112
+ } catch (err) {
113
+ void err; // ignore: file locked or concurrently removed
114
+ }
115
+ }
116
+ return { removedFiles, reclaimedBytes };
117
+ }
118
+
119
+ /**
120
+ * Runs local Burnoff diagnostics and optional `--gc` cache/FTS5/ledger maintenance.
121
+ */
122
+ export async function runDoctor(options = {}) {
123
+ const cwd = path.resolve(options.cwd || process.cwd());
124
+ const homeDir = options.homeDir || getHomeDir();
125
+ const nodeVersion = options.nodeVersion || process.versions.node;
126
+ const nowMs = Number(options.nowMs || Date.now());
127
+ const maxCacheAgeDays = Math.max(1, Number(options.maxCacheAgeDays ?? 14));
128
+
129
+ const nodeSupported = isSupportedNodeVersion(nodeVersion);
130
+ const nativeSqlite = hasNativeNodeSqlite(nodeVersion);
131
+ const policy = loadBurnoffPolicy(cwd);
132
+ const hooks = inspectHookWiring(cwd);
133
+ const fts5DbPath = getDefaultToolLogsDbPath(homeDir);
134
+ const fts5Stats = getFts5CompressionStats(fts5DbPath, { homeDir });
135
+ const ledgerSummary = getSavedQuotaReceiptSummary({ homeDir, nowMs });
136
+ const atomicIo = getAtomicIoMetrics();
137
+
138
+ let daemonPing = null;
139
+ const ipcPath = resolveFastIpcPipePath({ cwd, homeDir, ipcPath: options.ipcPath });
140
+ if (!options.skipDaemonCheck) {
141
+ daemonPing = await sendDaemonRpc(
142
+ 'daemon.ping',
143
+ {},
144
+ { cwd, homeDir, ipcPath: options.ipcPath, requestTimeoutMs: 80 }
145
+ );
146
+ }
147
+
148
+ let gcResult = null;
149
+ if (options.gc) {
150
+ const retentionDays = Number(policy?.postTool?.retentionDays ?? 30);
151
+ let fts5Pruned = { skipped: true, deletedRows: 0, vacuumed: false };
152
+ if (fs.existsSync(fts5DbPath)) {
153
+ let db = null;
154
+ try {
155
+ db = openBurnoffDb(fts5DbPath, { readOnly: false });
156
+ fts5Pruned = pruneExpiredFts5LogsSync(db, nowMs, retentionDays, { force: true });
157
+ } finally {
158
+ if (db) {
159
+ try { db.close(); } catch (err) { void err; /* ignore: db close guard */ }
160
+ }
161
+ }
162
+ }
163
+ const cutoffMs = nowMs - maxCacheAgeDays * 24 * 60 * 60 * 1000;
164
+ const homeCacheReaped = reapStaleCacheFiles(getBurnoffCacheDir(homeDir), cutoffMs);
165
+ const wsCacheReaped = reapStaleCacheFiles(path.join(cwd, '.claude', 'cache'), cutoffMs);
166
+ const wsArtifactsReaped = reapStaleCacheFiles(path.join(cwd, '.claude', 'cache', 'artifacts'), cutoffMs);
167
+ const ledgerRotation = rotateMonthlyLedger({ homeDir, nowMs });
168
+ gcResult = {
169
+ performed: true,
170
+ maxCacheAgeDays,
171
+ fts5Pruned,
172
+ reapedCacheFiles:
173
+ homeCacheReaped.removedFiles + wsCacheReaped.removedFiles + wsArtifactsReaped.removedFiles,
174
+ reclaimedBytes:
175
+ homeCacheReaped.reclaimedBytes + wsCacheReaped.reclaimedBytes + wsArtifactsReaped.reclaimedBytes,
176
+ ledgerRotation
177
+ };
178
+ }
179
+
180
+ const status = !nodeSupported ? 'ERROR' : (!nativeSqlite || policy.parseError ? 'WARN' : 'OK');
181
+
182
+ return {
183
+ ok: nodeSupported,
184
+ status,
185
+ cwd,
186
+ burnoffHome: getBurnoffHomeDir(homeDir),
187
+ node: {
188
+ version: nodeVersion,
189
+ supported: nodeSupported,
190
+ minVersion: MIN_NODE_VERSION,
191
+ recommendedSqliteVersion: NATIVE_SQLITE_NODE_VERSION
192
+ },
193
+ sqlite: {
194
+ nativeFts5: nativeSqlite,
195
+ mode: nativeSqlite ? 'node:sqlite' : 'jsonl_fallback'
196
+ },
197
+ policy: {
198
+ sourcePath: policy.sourcePath,
199
+ exists: policy.exists,
200
+ parseError: Boolean(policy.parseError),
201
+ guardMode: policy.guards?.mode || 'guard',
202
+ strictTestIntegrity: Boolean(policy.guards?.strictTestIntegrity),
203
+ neverClampCodeOffCliff: Boolean(policy.readClamp?.neverClampCodeOffCliff)
204
+ },
205
+ hooks,
206
+ daemon: {
207
+ ipcPath,
208
+ running: Boolean(daemonPing?.pong),
209
+ pid: daemonPing?.pid || null,
210
+ requestCount: daemonPing?.requestCount ?? 0
211
+ },
212
+ fts5: {
213
+ dbPath: fts5DbPath,
214
+ exists: fs.existsSync(fts5DbPath),
215
+ ...fts5Stats
216
+ },
217
+ ledger: {
218
+ avoidedWriteTokens: ledgerSummary.burnoffAvoidedWriteTokens,
219
+ avoidedWriteUSD: ledgerSummary.burnoffAvoidedWriteUSD,
220
+ platformCacheTokens: ledgerSummary.platformCacheDiscountTokens,
221
+ platformCacheUSD: ledgerSummary.platformCacheDiscountUSD,
222
+ realizedPromptBillUSD: ledgerSummary.realizedPromptBillUSD,
223
+ entryCount: ledgerSummary.entryCount
224
+ },
225
+ atomicIo,
226
+ gc: gcResult
227
+ };
228
+ }
229
+
230
+ /**
231
+ * Formats a `runDoctor()` report for terminal output.
232
+ */
233
+ export function formatDoctorReport(report = {}) {
234
+ const lines = [
235
+ `Burnoff Doctor: ${report.status || 'UNKNOWN'}`,
236
+ ` Node.js : v${report.node?.version || 'unknown'} (${report.node?.supported ? 'supported' : `requires >=${report.node?.minVersion}`})`,
237
+ ` SQLite FTS5 : ${report.sqlite?.mode || 'unknown'}`,
238
+ ` Burnoff Home : ${report.burnoffHome || ''}`,
239
+ ` Policy : ${report.policy?.exists ? report.policy.sourcePath : 'defaults (no .burnoff.yaml)'} [mode=${report.policy?.guardMode || 'guard'}]`,
240
+ ` Claude Hooks : ${report.hooks?.installed ? 'installed (.claude/settings.local.json)' : 'not installed'} | git exclude=${report.hooks?.gitExcludeProtected ? 'yes' : 'no'}`,
241
+ ` Warm Daemon : ${report.daemon?.running ? `running (pid=${report.daemon.pid})` : 'stopped (cold fallback active)'}`,
242
+ ` FTS5 Archive : ${report.fts5?.logCount ?? 0} logs (~${report.fts5?.formattedSavedK || '0.0k'} tok compressed)`,
243
+ ` Ledger : $${Number(report.ledger?.avoidedWriteUSD || 0).toFixed(4)} avoided | $${Number(report.ledger?.platformCacheUSD || 0).toFixed(4)} cache discount (${report.ledger?.entryCount ?? 0} receipts)`,
244
+ ` Atomic I/O : ${report.atomicIo?.renameRetries ?? 0} rename retries, ${report.atomicIo?.renameExhausted ?? 0} exhausted`
245
+ ];
246
+ if (report.gc?.performed) {
247
+ lines.push(
248
+ ` GC : pruned=${report.gc.fts5Pruned?.deletedRows ?? 0} FTS5 rows, reaped=${report.gc.reapedCacheFiles} cache files (${report.gc.reclaimedBytes} bytes), rotated=${report.gc.ledgerRotation?.rotatedCount ?? 0} ledger entries`
249
+ );
250
+ }
251
+ return lines.join('\n') + '\n';
252
+ }
253
+
254
+ export default {
255
+ runDoctor,
256
+ formatDoctorReport
257
+ };