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 +21 -0
- package/README.md +93 -2
- package/bin/burnoff.mjs +406 -0
- package/hooks/hook-io.mjs +590 -0
- package/hooks/hooks.json +12 -0
- package/hooks/post-tool-use.mjs +118 -0
- package/hooks/pre-tool-use.mjs +149 -0
- package/package.json +42 -4
- package/src/ci/ci-gate.mjs +270 -0
- package/src/ci/pr-cost.mjs +582 -0
- package/src/ci/team-digest.mjs +123 -0
- package/src/cli/audit.mjs +196 -0
- package/src/cli/doctor.mjs +257 -0
- package/src/cli/init.mjs +306 -0
- package/src/config/catalog.json +874 -0
- package/src/config/loader.mjs +626 -0
- package/src/config/paths.mjs +196 -0
- package/src/config/policy.mjs +208 -0
- package/src/guards/loop-breaker.mjs +501 -0
- package/src/guards/post-tool-engine.mjs +573 -0
- package/src/guards/pre-tool-engine.mjs +563 -0
- package/src/guards/read-clamp.mjs +730 -0
- package/src/guards/shell-guard.mjs +1140 -0
- package/src/ipc/daemon.mjs +273 -0
- package/src/ipc/fast-client.mjs +198 -0
- package/src/ipc/protocol.mjs +142 -0
- package/src/storage/atomic-io.mjs +151 -0
- package/src/storage/file-lock.mjs +206 -0
- package/src/storage/fts5-archive.mjs +718 -0
- package/src/storage/jsonl-parser.mjs +760 -0
- package/src/storage/ledger.mjs +1150 -0
- package/src/storage/sqlite-client.mjs +566 -0
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/ci/pr-cost.mjs
|
|
3
|
+
* Git Branch & PR Token/USD Cost Attribution (`burnoff-pr-attribution/v1`).
|
|
4
|
+
*
|
|
5
|
+
* Correlates `git log <base>..HEAD --numstat` commits with Claude Code session steps
|
|
6
|
+
* and Burnoff ledger entries without leaking OS home directories or `.claude/settings.local.json`.
|
|
7
|
+
* Zero runtime dependencies, zero license gates, zero network calls.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { execFileSync } from 'node:child_process';
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import os from 'node:os';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { getHomeDir } from '../config/paths.mjs';
|
|
15
|
+
import { readLedgerEntries } from '../storage/ledger.mjs';
|
|
16
|
+
import {
|
|
17
|
+
discoverClaudeCodeSessions,
|
|
18
|
+
parseTranscriptIncremental
|
|
19
|
+
} from '../storage/jsonl-parser.mjs';
|
|
20
|
+
|
|
21
|
+
export const PR_ATTRIBUTION_FORMAT = 'burnoff-pr-attribution/v1';
|
|
22
|
+
|
|
23
|
+
const RING0_DETECTORS = new Set(['DET-01', 'DET-02', 'DET-03', 'DET-04', 'DET-05']);
|
|
24
|
+
|
|
25
|
+
function isExcludedLocalToolPath(relPath = '') {
|
|
26
|
+
const norm = String(relPath || '').replace(/\\/g, '/').replace(/^\.\//, '').toLowerCase();
|
|
27
|
+
return norm === '.claude/settings.local.json' || norm.endsWith('/.claude/settings.local.json');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function sanitizeRelativeRepoPath(rawPath = '', cwd = '') {
|
|
31
|
+
const input = String(rawPath || '').trim();
|
|
32
|
+
if (!input) return '';
|
|
33
|
+
let normalized = input.replace(/\\/g, '/');
|
|
34
|
+
if (cwd) {
|
|
35
|
+
const abs = path.isAbsolute(input) ? input : path.resolve(cwd, input);
|
|
36
|
+
const rel = path.relative(cwd, abs).replace(/\\/g, '/');
|
|
37
|
+
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
|
|
38
|
+
normalized = rel;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const homeNorm = String(os.homedir() || '').replace(/\\/g, '/').replace(/\/+$/, '');
|
|
42
|
+
if (homeNorm && normalized.toLowerCase().startsWith(`${homeNorm.toLowerCase()}/`)) {
|
|
43
|
+
normalized = normalized.slice(homeNorm.length + 1);
|
|
44
|
+
}
|
|
45
|
+
normalized = normalized
|
|
46
|
+
.replace(/^[A-Za-z]:\/Users\/[^/]+\//i, '')
|
|
47
|
+
.replace(/^\/Users\/[^/]+\//i, '')
|
|
48
|
+
.replace(/^\/home\/[^/]+\//i, '')
|
|
49
|
+
.replace(/^file:\/\/\//i, '')
|
|
50
|
+
.replace(/^\.\//, '');
|
|
51
|
+
return normalized;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function readProviderUsageExportUsd(providerUsagePath) {
|
|
55
|
+
if (!providerUsagePath || typeof providerUsagePath !== 'string') return null;
|
|
56
|
+
const abs = path.resolve(providerUsagePath);
|
|
57
|
+
if (!fs.existsSync(abs)) {
|
|
58
|
+
throw new Error(`Provider usage export not found: ${abs}`);
|
|
59
|
+
}
|
|
60
|
+
const parsed = JSON.parse(fs.readFileSync(abs, 'utf8'));
|
|
61
|
+
const numField = (obj) => {
|
|
62
|
+
if (!obj || typeof obj !== 'object') return null;
|
|
63
|
+
for (const k of ['totalCostUsd', 'total_cost_usd', 'costUsd', 'cost_usd', 'amountUsd', 'amount_usd']) {
|
|
64
|
+
if (obj[k] !== undefined && obj[k] !== null && Number.isFinite(Number(obj[k]))) {
|
|
65
|
+
return Number(obj[k]);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return null;
|
|
69
|
+
};
|
|
70
|
+
const direct = numField(parsed);
|
|
71
|
+
if (direct !== null) return direct;
|
|
72
|
+
|
|
73
|
+
const list = Array.isArray(parsed)
|
|
74
|
+
? parsed
|
|
75
|
+
: Array.isArray(parsed?.records)
|
|
76
|
+
? parsed.records
|
|
77
|
+
: Array.isArray(parsed?.usage)
|
|
78
|
+
? parsed.usage
|
|
79
|
+
: Array.isArray(parsed?.data)
|
|
80
|
+
? parsed.data
|
|
81
|
+
: null;
|
|
82
|
+
if (!list) return null;
|
|
83
|
+
|
|
84
|
+
let total = 0;
|
|
85
|
+
let found = false;
|
|
86
|
+
for (const item of list) {
|
|
87
|
+
const v = numField(item);
|
|
88
|
+
if (v !== null) {
|
|
89
|
+
total += v;
|
|
90
|
+
found = true;
|
|
91
|
+
} else if (Array.isArray(item?.results)) {
|
|
92
|
+
for (const r of item.results) {
|
|
93
|
+
const rv = numField(r);
|
|
94
|
+
if (rv !== null) {
|
|
95
|
+
total += rv;
|
|
96
|
+
found = true;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return found ? Number(total.toFixed(4)) : null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function parseGitLogNumstat(rawText = '', cwd = '') {
|
|
105
|
+
const commits = [];
|
|
106
|
+
let current = null;
|
|
107
|
+
|
|
108
|
+
for (const line of String(rawText || '').split(/\r?\n/)) {
|
|
109
|
+
if (!line.trim()) continue;
|
|
110
|
+
if (line.startsWith('COMMIT|')) {
|
|
111
|
+
const parts = line.split('|');
|
|
112
|
+
const sha = parts[1] || '';
|
|
113
|
+
const timestampIso = parts[2] || '';
|
|
114
|
+
const author = parts[3] || '';
|
|
115
|
+
const subject = parts.slice(4).join('|').trim();
|
|
116
|
+
const parsedMs = Date.parse(timestampIso);
|
|
117
|
+
current = {
|
|
118
|
+
sha,
|
|
119
|
+
shortSha: sha.slice(0, 7),
|
|
120
|
+
timestampIso,
|
|
121
|
+
timestampMs: Number.isFinite(parsedMs) ? parsedMs : 0,
|
|
122
|
+
author,
|
|
123
|
+
subject,
|
|
124
|
+
files: [],
|
|
125
|
+
totalAdditions: 0,
|
|
126
|
+
totalDeletions: 0,
|
|
127
|
+
totalLoc: 0
|
|
128
|
+
};
|
|
129
|
+
commits.push(current);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (!current) continue;
|
|
133
|
+
const numMatch = line.match(/^(\d+|-)\t(\d+|-)\t(.+)$/);
|
|
134
|
+
if (numMatch) {
|
|
135
|
+
const additions = numMatch[1] === '-' ? 0 : Number(numMatch[1]);
|
|
136
|
+
const deletions = numMatch[2] === '-' ? 0 : Number(numMatch[2]);
|
|
137
|
+
const filePath = sanitizeRelativeRepoPath(numMatch[3], cwd);
|
|
138
|
+
current.files.push({ filePath, additions, deletions });
|
|
139
|
+
current.totalAdditions += additions;
|
|
140
|
+
current.totalDeletions += deletions;
|
|
141
|
+
current.totalLoc += additions + deletions;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return commits;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Runs local read-only `git log <base>..<head> --numstat` cleanly without shell expansion.
|
|
150
|
+
*/
|
|
151
|
+
export function collectGitBranchCommits(
|
|
152
|
+
cwd,
|
|
153
|
+
{ base = 'main', head = 'HEAD', maxCommits = 100, fallbackToRecent = true } = {}
|
|
154
|
+
) {
|
|
155
|
+
const repoDir = path.resolve(cwd || process.cwd());
|
|
156
|
+
const formatArg = '--format=COMMIT|%H|%aI|%an|%s';
|
|
157
|
+
|
|
158
|
+
const runGit = (revRangeArgs) =>
|
|
159
|
+
execFileSync('git', ['log', ...revRangeArgs, formatArg, '--numstat', '-n', String(maxCommits)], {
|
|
160
|
+
cwd: repoDir,
|
|
161
|
+
encoding: 'utf8',
|
|
162
|
+
stdio: ['ignore', 'pipe', 'pipe']
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
try {
|
|
166
|
+
const raw = runGit([`${base}..${head}`]);
|
|
167
|
+
return {
|
|
168
|
+
ok: true,
|
|
169
|
+
base,
|
|
170
|
+
head,
|
|
171
|
+
fallbackUsed: false,
|
|
172
|
+
commits: parseGitLogNumstat(raw, repoDir)
|
|
173
|
+
};
|
|
174
|
+
} catch (rangeErr) {
|
|
175
|
+
if (!fallbackToRecent) {
|
|
176
|
+
return { ok: false, base, head, commits: [], error: rangeErr?.message || String(rangeErr) };
|
|
177
|
+
}
|
|
178
|
+
try {
|
|
179
|
+
const rawFallback = runGit([head]);
|
|
180
|
+
return {
|
|
181
|
+
ok: true,
|
|
182
|
+
base,
|
|
183
|
+
head,
|
|
184
|
+
fallbackUsed: true,
|
|
185
|
+
commits: parseGitLogNumstat(rawFallback, repoDir)
|
|
186
|
+
};
|
|
187
|
+
} catch (headErr) {
|
|
188
|
+
return {
|
|
189
|
+
ok: false,
|
|
190
|
+
base,
|
|
191
|
+
head,
|
|
192
|
+
fallbackUsed: false,
|
|
193
|
+
commits: [],
|
|
194
|
+
error: headErr?.message || String(headErr)
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function extractStepFields(step = {}, cwd = '') {
|
|
201
|
+
const usage = step.tokenUsage || {};
|
|
202
|
+
const inTok =
|
|
203
|
+
Number(step.inputTokens ?? step.input_tokens ?? usage.freshInputTokens ?? usage.inputTokens ?? 0) +
|
|
204
|
+
Number(step.cacheCreationTokens ?? step.cache_creation_input_tokens ?? usage.cacheCreationTokens ?? 0);
|
|
205
|
+
const cacheReadTok = Number(
|
|
206
|
+
step.cacheReadTokens ?? step.cache_read_input_tokens ?? usage.cacheReadTokens ?? 0
|
|
207
|
+
);
|
|
208
|
+
const outTok =
|
|
209
|
+
Number(step.outputTokens ?? step.output_tokens ?? usage.outputTokens ?? 0) +
|
|
210
|
+
Number(step.thinkingTokens ?? step.thinking_tokens ?? usage.thinkingTokens ?? 0);
|
|
211
|
+
const wasteTok = Number(step.wasteTokens ?? step.wastedTokens ?? 0);
|
|
212
|
+
const rawTs = step.timestampMs ?? step.createdAt ?? step.created_at ?? step.timestamp ?? null;
|
|
213
|
+
const tsMs = typeof rawTs === 'number' ? rawTs : rawTs ? Date.parse(String(rawTs)) : NaN;
|
|
214
|
+
|
|
215
|
+
const filesTouched = new Set();
|
|
216
|
+
const explicitFile = step.filePath || step.path || step.targetFile;
|
|
217
|
+
if (explicitFile) {
|
|
218
|
+
const clean = sanitizeRelativeRepoPath(explicitFile, cwd);
|
|
219
|
+
if (clean) filesTouched.add(clean);
|
|
220
|
+
}
|
|
221
|
+
const calls = Array.isArray(step.toolCalls)
|
|
222
|
+
? step.toolCalls
|
|
223
|
+
: Array.isArray(step.tool_calls)
|
|
224
|
+
? step.tool_calls
|
|
225
|
+
: [];
|
|
226
|
+
for (const c of calls) {
|
|
227
|
+
const args = c?.args || c?.parameters || c?.Arguments || c?.input || {};
|
|
228
|
+
const fp = args.file_path || args.Path || args.path || args.TargetFile || args.AbsolutePath;
|
|
229
|
+
if (fp) {
|
|
230
|
+
const clean = sanitizeRelativeRepoPath(fp, cwd);
|
|
231
|
+
if (clean) filesTouched.add(clean);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
const detector = String(step.detector || step.detectorId || '').toUpperCase();
|
|
236
|
+
const isRing0 =
|
|
237
|
+
Boolean(step.ring0Violation) ||
|
|
238
|
+
Boolean(step.blocked && RING0_DETECTORS.has(detector)) ||
|
|
239
|
+
(step.decision === 'deny' && RING0_DETECTORS.has(detector));
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
inTok,
|
|
243
|
+
cacheReadTok,
|
|
244
|
+
outTok,
|
|
245
|
+
wasteTok,
|
|
246
|
+
totalTok: inTok + cacheReadTok + outTok,
|
|
247
|
+
tsMs: Number.isFinite(tsMs) ? tsMs : null,
|
|
248
|
+
filesTouched: Array.from(filesTouched),
|
|
249
|
+
isRing0
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function computeStepCostUsd(inTok, cacheReadTok, outTok, pricePerMillionUsd = 3.0) {
|
|
254
|
+
return ((inTok * 1.0 + cacheReadTok * 0.1 + outTok * 5.0) / 1_000_000) * pricePerMillionUsd;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Builds Git branch / PR token and USD attribution report.
|
|
259
|
+
*/
|
|
260
|
+
export function buildPrCostAttribution(options = {}) {
|
|
261
|
+
const cwd = path.resolve(options.cwd || process.cwd());
|
|
262
|
+
const homeDir = options.homeDir || getHomeDir();
|
|
263
|
+
const base = String(options.base || 'main');
|
|
264
|
+
const head = String(options.head || 'HEAD');
|
|
265
|
+
const pricePerMillionUsd = Number(options.pricePerMillionUsd || 3.0);
|
|
266
|
+
|
|
267
|
+
let commits = Array.isArray(options.commits) ? options.commits : null;
|
|
268
|
+
let fallbackUsed = false;
|
|
269
|
+
if (!commits) {
|
|
270
|
+
const gitRes = collectGitBranchCommits(cwd, {
|
|
271
|
+
base,
|
|
272
|
+
head,
|
|
273
|
+
fallbackToRecent: options.fallbackToRecent !== false
|
|
274
|
+
});
|
|
275
|
+
if (!gitRes.ok) {
|
|
276
|
+
return { ok: false, error: gitRes.error, base, head };
|
|
277
|
+
}
|
|
278
|
+
commits = gitRes.commits;
|
|
279
|
+
fallbackUsed = gitRes.fallbackUsed;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const rawSteps = [];
|
|
283
|
+
if (Array.isArray(options.steps)) {
|
|
284
|
+
rawSteps.push(...options.steps);
|
|
285
|
+
}
|
|
286
|
+
if (Array.isArray(options.sessions)) {
|
|
287
|
+
for (const sess of options.sessions) {
|
|
288
|
+
if (Array.isArray(sess?.steps)) rawSteps.push(...sess.steps);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
if (!Array.isArray(options.steps) && !Array.isArray(options.sessions) && options.readSessions !== false) {
|
|
292
|
+
const maxSessions = Math.max(1, Number(options.maxSessions ?? 20));
|
|
293
|
+
const discovered = discoverClaudeCodeSessions(homeDir, { cwd }).slice(0, maxSessions);
|
|
294
|
+
for (const meta of discovered) {
|
|
295
|
+
const parsed = parseTranscriptIncremental(meta.filePath, { homeDir });
|
|
296
|
+
if (Array.isArray(parsed?.steps)) {
|
|
297
|
+
rawSteps.push(...parsed.steps);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
const normalizedSteps = rawSteps.map((s) => extractStepFields(s, cwd));
|
|
302
|
+
|
|
303
|
+
const rawLedger = Array.isArray(options.ledgerEntries)
|
|
304
|
+
? options.ledgerEntries
|
|
305
|
+
: options.readLedger !== false
|
|
306
|
+
? readLedgerEntries({ homeDir, cwd })
|
|
307
|
+
: [];
|
|
308
|
+
|
|
309
|
+
const validTimestamps = commits.map((c) => c.timestampMs).filter((t) => Number.isFinite(t) && t > 0);
|
|
310
|
+
const minCommitMs = validTimestamps.length ? Math.min(...validTimestamps) : -Infinity;
|
|
311
|
+
const maxCommitMs = validTimestamps.length ? Math.max(...validTimestamps) : Infinity;
|
|
312
|
+
|
|
313
|
+
const sortedCommits = [...commits]
|
|
314
|
+
.map((c, origIdx) => ({
|
|
315
|
+
...c,
|
|
316
|
+
origIdx,
|
|
317
|
+
files: (Array.isArray(c.files) ? c.files : [])
|
|
318
|
+
.map((f) => ({
|
|
319
|
+
filePath: sanitizeRelativeRepoPath(f.filePath, cwd),
|
|
320
|
+
additions: Number(f.additions || 0),
|
|
321
|
+
deletions: Number(f.deletions || 0)
|
|
322
|
+
}))
|
|
323
|
+
.filter((f) => f.filePath && !isExcludedLocalToolPath(f.filePath))
|
|
324
|
+
}))
|
|
325
|
+
.sort((a, b) => (a.timestampMs || 0) - (b.timestampMs || 0));
|
|
326
|
+
|
|
327
|
+
for (const c of sortedCommits) {
|
|
328
|
+
if (!c.totalLoc) {
|
|
329
|
+
c.totalAdditions = c.files.reduce((s, f) => s + f.additions, 0);
|
|
330
|
+
c.totalDeletions = c.files.reduce((s, f) => s + f.deletions, 0);
|
|
331
|
+
c.totalLoc = c.totalAdditions + c.totalDeletions;
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const matchingLedger = rawLedger.filter((entry) => {
|
|
336
|
+
const rawTs = entry.timestamp ?? entry.ts ?? null;
|
|
337
|
+
const tsMs = typeof rawTs === 'number' ? rawTs : rawTs ? Date.parse(String(rawTs)) : NaN;
|
|
338
|
+
if (!Number.isFinite(tsMs) || !validTimestamps.length) return true;
|
|
339
|
+
return tsMs >= minCommitMs - 30 * 60 * 1000 && tsMs <= maxCommitMs + 15 * 60 * 1000;
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
const ledgerSavedUsd = matchingLedger.reduce((s, e) => s + Number(e.savedUSD ?? e.savedUsd ?? 0), 0);
|
|
343
|
+
|
|
344
|
+
const commitBuckets = new Map(sortedCommits.map((_, idx) => [idx, []]));
|
|
345
|
+
const totalBranchLoc = sortedCommits.reduce((s, c) => s + Math.max(1, c.totalLoc || 0), 0);
|
|
346
|
+
|
|
347
|
+
let unmatchedIn = 0;
|
|
348
|
+
let unmatchedCache = 0;
|
|
349
|
+
let unmatchedOut = 0;
|
|
350
|
+
let unmatchedWaste = 0;
|
|
351
|
+
let unmatchedRing0 = 0;
|
|
352
|
+
|
|
353
|
+
for (const st of normalizedSteps) {
|
|
354
|
+
let assignedIdx = -1;
|
|
355
|
+
|
|
356
|
+
if (st.tsMs !== null && validTimestamps.length > 0) {
|
|
357
|
+
const windowStart = minCommitMs - 30 * 60 * 1000;
|
|
358
|
+
const windowEnd = maxCommitMs + 15 * 60 * 1000;
|
|
359
|
+
if (st.tsMs < windowStart || st.tsMs > windowEnd) {
|
|
360
|
+
continue;
|
|
361
|
+
}
|
|
362
|
+
for (let i = 0; i < sortedCommits.length; i++) {
|
|
363
|
+
const prevMs = i > 0 ? sortedCommits[i - 1].timestampMs : windowStart;
|
|
364
|
+
const curMs =
|
|
365
|
+
i === sortedCommits.length - 1
|
|
366
|
+
? Math.max(sortedCommits[i].timestampMs, windowEnd)
|
|
367
|
+
: sortedCommits[i].timestampMs;
|
|
368
|
+
if (st.tsMs >= prevMs && st.tsMs <= curMs) {
|
|
369
|
+
assignedIdx = i;
|
|
370
|
+
break;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
if (assignedIdx === -1 && st.filesTouched.length > 0 && sortedCommits.length > 0) {
|
|
376
|
+
assignedIdx = sortedCommits.findIndex((c) =>
|
|
377
|
+
c.files.some((cf) => st.filesTouched.includes(cf.filePath))
|
|
378
|
+
);
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
if (assignedIdx >= 0) {
|
|
382
|
+
commitBuckets.get(assignedIdx).push(st);
|
|
383
|
+
} else if (sortedCommits.length > 0 && st.tsMs === null) {
|
|
384
|
+
unmatchedIn += st.inTok;
|
|
385
|
+
unmatchedCache += st.cacheReadTok;
|
|
386
|
+
unmatchedOut += st.outTok;
|
|
387
|
+
unmatchedWaste += st.wasteTok;
|
|
388
|
+
if (st.isRing0) unmatchedRing0 += 1;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const fileAggMap = new Map();
|
|
393
|
+
let sumIn = 0;
|
|
394
|
+
let sumCache = 0;
|
|
395
|
+
let sumOut = 0;
|
|
396
|
+
let sumWaste = 0;
|
|
397
|
+
let sumRing0 = unmatchedRing0;
|
|
398
|
+
|
|
399
|
+
const commitRows = sortedCommits.map((c, idx) => {
|
|
400
|
+
const bucket = commitBuckets.get(idx) || [];
|
|
401
|
+
const locShare = totalBranchLoc > 0 ? Math.max(1, c.totalLoc || 0) / totalBranchLoc : 0;
|
|
402
|
+
|
|
403
|
+
const cIn = bucket.reduce((s, st) => s + st.inTok, 0) + Math.round(unmatchedIn * locShare);
|
|
404
|
+
const cCache = bucket.reduce((s, st) => s + st.cacheReadTok, 0) + Math.round(unmatchedCache * locShare);
|
|
405
|
+
const cOut = bucket.reduce((s, st) => s + st.outTok, 0) + Math.round(unmatchedOut * locShare);
|
|
406
|
+
const cWaste = bucket.reduce((s, st) => s + st.wasteTok, 0) + Math.round(unmatchedWaste * locShare);
|
|
407
|
+
const cRing0 = bucket.filter((st) => st.isRing0).length;
|
|
408
|
+
const cTotal = cIn + cCache + cOut;
|
|
409
|
+
const cDenom = cIn + cCache;
|
|
410
|
+
const cHitPct = cDenom > 0 ? Math.round((cCache / cDenom) * 100) : 0;
|
|
411
|
+
const cCostUsd = Number(computeStepCostUsd(cIn, cCache, cOut, pricePerMillionUsd).toFixed(4));
|
|
412
|
+
|
|
413
|
+
sumIn += cIn;
|
|
414
|
+
sumCache += cCache;
|
|
415
|
+
sumOut += cOut;
|
|
416
|
+
sumWaste += cWaste;
|
|
417
|
+
sumRing0 += cRing0;
|
|
418
|
+
|
|
419
|
+
const fileLocSum = c.files.reduce((s, f) => s + Math.max(1, f.additions + f.deletions), 0);
|
|
420
|
+
for (const f of c.files) {
|
|
421
|
+
const share = fileLocSum > 0 ? Math.max(1, f.additions + f.deletions) / fileLocSum : 0;
|
|
422
|
+
const cur = fileAggMap.get(f.filePath) || {
|
|
423
|
+
filePath: f.filePath,
|
|
424
|
+
commits: 0,
|
|
425
|
+
additions: 0,
|
|
426
|
+
deletions: 0,
|
|
427
|
+
attributedTokens: 0,
|
|
428
|
+
estimatedCostUsd: 0
|
|
429
|
+
};
|
|
430
|
+
cur.commits += 1;
|
|
431
|
+
cur.additions += f.additions;
|
|
432
|
+
cur.deletions += f.deletions;
|
|
433
|
+
cur.attributedTokens += Math.round(cTotal * share);
|
|
434
|
+
cur.estimatedCostUsd = Number((cur.estimatedCostUsd + cCostUsd * share).toFixed(4));
|
|
435
|
+
fileAggMap.set(f.filePath, cur);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
return {
|
|
439
|
+
sha: c.sha,
|
|
440
|
+
shortSha: c.shortSha,
|
|
441
|
+
timestampIso: c.timestampIso,
|
|
442
|
+
author: c.author,
|
|
443
|
+
subject: c.subject,
|
|
444
|
+
filesChanged: c.files.length,
|
|
445
|
+
additions: c.totalAdditions,
|
|
446
|
+
deletions: c.totalDeletions,
|
|
447
|
+
attributedTokens: cTotal,
|
|
448
|
+
inputTokens: cIn,
|
|
449
|
+
cacheReadTokens: cCache,
|
|
450
|
+
outputTokens: cOut,
|
|
451
|
+
wasteTokens: cWaste,
|
|
452
|
+
cacheHitPct: cHitPct,
|
|
453
|
+
estimatedCostUsd: cCostUsd,
|
|
454
|
+
ring0Violations: cRing0
|
|
455
|
+
};
|
|
456
|
+
});
|
|
457
|
+
|
|
458
|
+
const totalTokens = sumIn + sumCache + sumOut;
|
|
459
|
+
const cacheDenom = sumIn + sumCache;
|
|
460
|
+
const cacheHitPct = cacheDenom > 0 ? Math.round((sumCache / cacheDenom) * 100) : 0;
|
|
461
|
+
const estimatedCostUsd = Number(computeStepCostUsd(sumIn, sumCache, sumOut, pricePerMillionUsd).toFixed(4));
|
|
462
|
+
const wasteRatioPct = totalTokens > 0 ? Math.round((sumWaste / totalTokens) * 100) : 0;
|
|
463
|
+
const uniqueFiles = new Set(commitRows.flatMap((_, idx) => sortedCommits[idx].files.map((f) => f.filePath)));
|
|
464
|
+
const totalAdditions = sortedCommits.reduce((s, c) => s + c.totalAdditions, 0);
|
|
465
|
+
const totalDeletions = sortedCommits.reduce((s, c) => s + c.totalDeletions, 0);
|
|
466
|
+
const totalLoc = totalAdditions + totalDeletions;
|
|
467
|
+
const usdPer100Loc = totalLoc > 0 ? Number(((estimatedCostUsd / totalLoc) * 100).toFixed(4)) : 0;
|
|
468
|
+
|
|
469
|
+
const topCostFiles = Array.from(fileAggMap.values())
|
|
470
|
+
.filter((f) => f.filePath && !isExcludedLocalToolPath(f.filePath))
|
|
471
|
+
.sort((a, b) => b.attributedTokens - a.attributedTokens || b.estimatedCostUsd - a.estimatedCostUsd)
|
|
472
|
+
.slice(0, 10);
|
|
473
|
+
|
|
474
|
+
let reconciledCostUsd = null;
|
|
475
|
+
let attributionVariancePct = null;
|
|
476
|
+
if (options.providerUsagePath) {
|
|
477
|
+
try {
|
|
478
|
+
const rawProviderUsd = readProviderUsageExportUsd(options.providerUsagePath);
|
|
479
|
+
if (typeof rawProviderUsd === 'number' && Number.isFinite(rawProviderUsd)) {
|
|
480
|
+
reconciledCostUsd = Number(rawProviderUsd.toFixed(4));
|
|
481
|
+
attributionVariancePct =
|
|
482
|
+
reconciledCostUsd > 0
|
|
483
|
+
? Number((((estimatedCostUsd - reconciledCostUsd) / reconciledCostUsd) * 100).toFixed(2))
|
|
484
|
+
: 0;
|
|
485
|
+
}
|
|
486
|
+
} catch (err) {
|
|
487
|
+
return {
|
|
488
|
+
ok: false,
|
|
489
|
+
error: err?.message || String(err),
|
|
490
|
+
base,
|
|
491
|
+
head
|
|
492
|
+
};
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
return {
|
|
497
|
+
ok: true,
|
|
498
|
+
format: PR_ATTRIBUTION_FORMAT,
|
|
499
|
+
generatedAt: new Date().toISOString(),
|
|
500
|
+
base,
|
|
501
|
+
head,
|
|
502
|
+
fallbackUsed,
|
|
503
|
+
summary: {
|
|
504
|
+
totalCommits: commitRows.length,
|
|
505
|
+
totalFilesChanged: uniqueFiles.size,
|
|
506
|
+
totalAdditions,
|
|
507
|
+
totalDeletions,
|
|
508
|
+
totalLoc,
|
|
509
|
+
totalInputTokens: sumIn,
|
|
510
|
+
totalCacheReadTokens: sumCache,
|
|
511
|
+
totalOutputTokens: sumOut,
|
|
512
|
+
totalTokens,
|
|
513
|
+
cacheHitPct,
|
|
514
|
+
estimatedCostUsd,
|
|
515
|
+
reconciledCostUsd,
|
|
516
|
+
attributionVariancePct,
|
|
517
|
+
estimatedSavedUsd: Number(ledgerSavedUsd.toFixed(4)),
|
|
518
|
+
estimatedWasteTokens: sumWaste,
|
|
519
|
+
wasteRatioPct,
|
|
520
|
+
ring0Violations: sumRing0,
|
|
521
|
+
usdPer100Loc
|
|
522
|
+
},
|
|
523
|
+
commits: commitRows,
|
|
524
|
+
topCostFiles
|
|
525
|
+
};
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Formats PR cost attribution as clean PR comment Markdown with zero local paths.
|
|
530
|
+
*/
|
|
531
|
+
export function formatPrAttributionMarkdown(report = {}) {
|
|
532
|
+
const s = report.summary || {};
|
|
533
|
+
const lines = [
|
|
534
|
+
`### Burnoff PR Token & Cost Attribution (\`${report.base || 'main'}..${report.head || 'HEAD'}\`)`,
|
|
535
|
+
'',
|
|
536
|
+
'| Metric | Value |',
|
|
537
|
+
'| :--- | :--- |',
|
|
538
|
+
`| **Commits / Files Changed** | \`${s.totalCommits ?? 0}\` commits · \`${s.totalFilesChanged ?? 0}\` files (\`+${s.totalAdditions ?? 0} / -${s.totalDeletions ?? 0}\`) |`,
|
|
539
|
+
`| **Total Attributed Tokens** | \`${((s.totalTokens || 0) / 1000).toFixed(1)}k\` |`,
|
|
540
|
+
`| **Cache Hit Rate** | \`${s.cacheHitPct ?? 0}%\` |`,
|
|
541
|
+
`| **Estimated PR AI Cost** | \`$${Number(s.estimatedCostUsd || 0).toFixed(4)}\` (\`$${Number(s.usdPer100Loc || 0).toFixed(4)} / 100 LOC\`) |`,
|
|
542
|
+
...(typeof s.reconciledCostUsd === 'number'
|
|
543
|
+
? [
|
|
544
|
+
`| **Provider Reconciled Cost** | \`$${s.reconciledCostUsd.toFixed(4)}\` (\`${(s.attributionVariancePct || 0) >= 0 ? '+' : ''}${s.attributionVariancePct ?? 0}%\` variance) |`
|
|
545
|
+
]
|
|
546
|
+
: []),
|
|
547
|
+
`| **Preventable Waste Ratio** | \`${s.wasteRatioPct ?? 0}%\` (\`${((s.estimatedWasteTokens || 0) / 1000).toFixed(1)}k\` tok) |`,
|
|
548
|
+
`| **Estimated Saved USD** | \`$${Number(s.estimatedSavedUsd || 0).toFixed(4)}\` |`,
|
|
549
|
+
`| **Ring-0 Violations** | \`${s.ring0Violations ?? 0}\` |`
|
|
550
|
+
];
|
|
551
|
+
|
|
552
|
+
const cleanFiles = (Array.isArray(report.topCostFiles) ? report.topCostFiles : [])
|
|
553
|
+
.map((f) => ({ ...f, filePath: sanitizeRelativeRepoPath(f.filePath) }))
|
|
554
|
+
.filter((f) => f.filePath && !isExcludedLocalToolPath(f.filePath));
|
|
555
|
+
if (cleanFiles.length > 0) {
|
|
556
|
+
lines.push('', '#### Top Cost-Driver Files', '', '| File | LOC Changed | Attributed Tokens | Est. Cost |', '| :--- | :---: | :---: | :---: |');
|
|
557
|
+
for (const f of cleanFiles) {
|
|
558
|
+
lines.push(
|
|
559
|
+
`| \`${f.filePath}\` | \`+${f.additions}/-${f.deletions}\` | \`${(f.attributedTokens / 1000).toFixed(1)}k\` | \`$${Number(f.estimatedCostUsd || 0).toFixed(4)}\` |`
|
|
560
|
+
);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
if (Array.isArray(report.commits) && report.commits.length > 0) {
|
|
565
|
+
lines.push('', '#### Commit Attribution Breakdown', '', '| Commit | Subject | Tokens | Cache Hit | Est. Cost |', '| :--- | :--- | :---: | :---: | :---: |');
|
|
566
|
+
for (const c of report.commits) {
|
|
567
|
+
lines.push(
|
|
568
|
+
`| \`${c.shortSha}\` | ${String(c.subject || '').replace(/\|/g, '\\|')} | \`${(c.attributedTokens / 1000).toFixed(1)}k\` | \`${c.cacheHitPct}%\` | \`$${Number(c.estimatedCostUsd || 0).toFixed(4)}\` |`
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
return lines.join('\n') + '\n';
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
export default {
|
|
577
|
+
PR_ATTRIBUTION_FORMAT,
|
|
578
|
+
sanitizeRelativeRepoPath,
|
|
579
|
+
collectGitBranchCommits,
|
|
580
|
+
buildPrCostAttribution,
|
|
581
|
+
formatPrAttributionMarkdown
|
|
582
|
+
};
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/ci/team-digest.mjs
|
|
3
|
+
* Concise 5-line weekly Engineering Manager (EM) digest summarizing Claude Code
|
|
4
|
+
* session spend, cache efficiency, top cost driver, Burnoff guard savings, and CI status.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { getHomeDir } from '../config/paths.mjs';
|
|
9
|
+
import { auditClaudeSessions } from '../cli/audit.mjs';
|
|
10
|
+
import { getSavedQuotaReceiptSummary } from '../storage/ledger.mjs';
|
|
11
|
+
import { loadCiBudgetPolicy } from './ci-gate.mjs';
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Aggregates trailing `days` (default 7) session spend + ledger savings for the EM digest.
|
|
15
|
+
*/
|
|
16
|
+
export function buildTeamDigest(options = {}) {
|
|
17
|
+
const cwd = path.resolve(options.cwd || process.cwd());
|
|
18
|
+
const homeDir = options.homeDir || getHomeDir();
|
|
19
|
+
const days = Math.max(1, Number(options.days ?? 7));
|
|
20
|
+
const nowMs = Number(options.nowMs || Date.now());
|
|
21
|
+
const cutoffMs = nowMs - days * 24 * 60 * 60 * 1000;
|
|
22
|
+
|
|
23
|
+
let sessions = Array.isArray(options.sessions) ? options.sessions : null;
|
|
24
|
+
if (!sessions) {
|
|
25
|
+
const audited = auditClaudeSessions({ cwd, homeDir, limit: options.limit ?? 50 });
|
|
26
|
+
sessions = audited.sessions.filter((s) => !s.mtimeMs || s.mtimeMs >= cutoffMs);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const prReports = Array.isArray(options.prReports) ? options.prReports : [];
|
|
30
|
+
const ledgerSummary = options.ledgerSummary || getSavedQuotaReceiptSummary({ homeDir, nowMs });
|
|
31
|
+
const policy = loadCiBudgetPolicy(cwd, options.policyOverrides || {});
|
|
32
|
+
|
|
33
|
+
let totalSpendUsd = 0;
|
|
34
|
+
let totalTokens = 0;
|
|
35
|
+
let totalInput = 0;
|
|
36
|
+
let totalCacheRead = 0;
|
|
37
|
+
let totalCommits = 0;
|
|
38
|
+
let ring0Violations = 0;
|
|
39
|
+
let topDriver = null;
|
|
40
|
+
|
|
41
|
+
for (const s of sessions) {
|
|
42
|
+
const spend = Number(s.estimatedCostUsd || 0);
|
|
43
|
+
const tok = Number(s.totalTokens || 0);
|
|
44
|
+
totalSpendUsd += spend;
|
|
45
|
+
totalTokens += tok;
|
|
46
|
+
totalInput += Number(s.inputTokens || 0) + Number(s.cacheWriteTokens || 0);
|
|
47
|
+
totalCacheRead += Number(s.cacheReadTokens || 0);
|
|
48
|
+
const label = s.sessionTitle || s.sessionId || s.fileName || 'session';
|
|
49
|
+
if (!topDriver || spend > topDriver.spendUsd) {
|
|
50
|
+
topDriver = { label: String(label).slice(0, 48), spendUsd: spend, tokens: tok };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
for (const pr of prReports) {
|
|
55
|
+
const sum = pr?.summary || {};
|
|
56
|
+
totalCommits += Number(sum.totalCommits || 0);
|
|
57
|
+
ring0Violations += Number(sum.ring0Violations || 0);
|
|
58
|
+
if (sessions.length === 0) {
|
|
59
|
+
totalSpendUsd += Number(sum.estimatedCostUsd || 0);
|
|
60
|
+
totalTokens += Number(sum.totalTokens || 0);
|
|
61
|
+
totalInput += Number(sum.totalInputTokens || 0);
|
|
62
|
+
totalCacheRead += Number(sum.totalCacheReadTokens || 0);
|
|
63
|
+
}
|
|
64
|
+
const topFile = Array.isArray(pr?.topCostFiles) ? pr.topCostFiles[0] : null;
|
|
65
|
+
if (topFile && (!topDriver || Number(topFile.estimatedCostUsd || 0) > topDriver.spendUsd)) {
|
|
66
|
+
topDriver = {
|
|
67
|
+
label: String(topFile.filePath || 'file'),
|
|
68
|
+
spendUsd: Number(topFile.estimatedCostUsd || 0),
|
|
69
|
+
tokens: Number(topFile.attributedTokens || 0)
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const cacheDenom = totalInput + totalCacheRead;
|
|
75
|
+
const cacheHitPct = cacheDenom > 0 ? Math.round((totalCacheRead / cacheDenom) * 100) : 0;
|
|
76
|
+
|
|
77
|
+
const avoidedUsd = Number(ledgerSummary.burnoffAvoidedWriteUSD ?? ledgerSummary.avoidedWriteUSD ?? 0);
|
|
78
|
+
const avoidedTokens = Number(ledgerSummary.burnoffAvoidedWriteTokens ?? ledgerSummary.avoidedWriteTokens ?? 0);
|
|
79
|
+
const interventions = Number(
|
|
80
|
+
ledgerSummary.buckets?.avoidedWrites?.count ?? ledgerSummary.entryCount ?? 0
|
|
81
|
+
);
|
|
82
|
+
|
|
83
|
+
return {
|
|
84
|
+
ok: true,
|
|
85
|
+
days,
|
|
86
|
+
generatedAt: new Date(nowMs).toISOString(),
|
|
87
|
+
summary: {
|
|
88
|
+
sessions: sessions.length,
|
|
89
|
+
commits: totalCommits,
|
|
90
|
+
totalSpendUsd: Number(totalSpendUsd.toFixed(4)),
|
|
91
|
+
totalTokens,
|
|
92
|
+
cacheHitPct,
|
|
93
|
+
avoidedUsd: Number(avoidedUsd.toFixed(4)),
|
|
94
|
+
avoidedTokens,
|
|
95
|
+
interventions,
|
|
96
|
+
ring0Violations,
|
|
97
|
+
maxPrCostUsd: policy.maxPrCostUsd
|
|
98
|
+
},
|
|
99
|
+
topDriver: topDriver || { label: 'none', spendUsd: 0, tokens: 0 }
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Formats the digest strictly as a 5-line weekly EM summary.
|
|
105
|
+
*/
|
|
106
|
+
export function formatTeamDigest(digest = {}) {
|
|
107
|
+
const s = digest.summary || {};
|
|
108
|
+
const td = digest.topDriver || { label: 'none', spendUsd: 0, tokens: 0 };
|
|
109
|
+
const days = Number(digest.days ?? 7);
|
|
110
|
+
const lines = [
|
|
111
|
+
`1. Burnoff ${days}d Spend: $${Number(s.totalSpendUsd || 0).toFixed(2)} across ${s.sessions ?? 0} sessions (${s.commits ?? 0} PR commits).`,
|
|
112
|
+
`2. Cache Efficiency: ${s.cacheHitPct ?? 0}% prompt cache hit rate (${((s.totalTokens || 0) / 1000).toFixed(1)}k total tokens).`,
|
|
113
|
+
`3. Top Cost Driver: ${td.label} ($${Number(td.spendUsd || 0).toFixed(2)}, ${((td.tokens || 0) / 1000).toFixed(1)}k tok).`,
|
|
114
|
+
`4. Guard Savings: $${Number(s.avoidedUsd || 0).toFixed(2)} avoided (${((s.avoidedTokens || 0) / 1000).toFixed(1)}k tok across ${s.interventions ?? 0} interventions).`,
|
|
115
|
+
`5. Policy Gate Status: ${s.ring0Violations ?? 0} Ring-0 violations | PR cap <= $${Number(s.maxPrCostUsd || 25).toFixed(2)}.`
|
|
116
|
+
];
|
|
117
|
+
return lines.join('\n') + '\n';
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export default {
|
|
121
|
+
buildTeamDigest,
|
|
122
|
+
formatTeamDigest
|
|
123
|
+
};
|