burnoff 2.0.0 → 2.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "burnoff",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Deterministic circuit breakers, bounded file-read guards, Turn-0 CI linters, and PR spend gates for Claude Code.",
5
5
  "author": {
6
6
  "name": "Gizzant"
@@ -23,6 +23,8 @@ jobs:
23
23
  with:
24
24
  node-version: '22'
25
25
 
26
+ # If .burnoff-ci/pr-summary.json (exported locally via `burnoff pr-cost --write-summary`)
27
+ # is committed in the PR branch, `pr-cost` automatically hydrates and verifies it with zero secrets.
26
28
  - name: Compute PR Cost Attribution
27
29
  run: |
28
30
  mkdir -p .burnoff-ci
@@ -30,13 +32,13 @@ jobs:
30
32
  if [ -s .burnoff-ci/provider-usage.json ]; then
31
33
  USAGE_FLAG="--provider-usage .burnoff-ci/provider-usage.json"
32
34
  fi
33
- npx -y burnoff@2.0.0 pr-cost --base "origin/${{ github.base_ref }}" $USAGE_FLAG --json --out .burnoff-ci/pr-cost.json
34
- npx -y burnoff@2.0.0 pr-cost --base "origin/${{ github.base_ref }}" $USAGE_FLAG --markdown --out .burnoff-ci/pr-cost.md
35
+ npx -y burnoff@2.1.0 pr-cost --base "origin/${{ github.base_ref }}" $USAGE_FLAG --json --out .burnoff-ci/pr-cost.json
36
+ npx -y burnoff@2.1.0 pr-cost --base "origin/${{ github.base_ref }}" $USAGE_FLAG --markdown --out .burnoff-ci/pr-cost.md
35
37
 
36
38
  - name: Enforce CI Token-Budget Gate
37
39
  id: gate
38
40
  run: |
39
- npx -y burnoff@2.0.0 ci-gate --input .burnoff-ci/pr-cost.json --strict --github-annotations --out .burnoff-ci/ci-gate.md
41
+ npx -y burnoff@2.1.0 ci-gate --input .burnoff-ci/pr-cost.json --strict --github-annotations --out .burnoff-ci/ci-gate.md
40
42
  cat .burnoff-ci/pr-cost.md >> "$GITHUB_STEP_SUMMARY"
41
43
  cat .burnoff-ci/ci-gate.md >> "$GITHUB_STEP_SUMMARY"
42
44
  echo "summary_path=.burnoff-ci/pr-cost.md" >> "$GITHUB_OUTPUT"
@@ -27,11 +27,11 @@ jobs:
27
27
  node-version: '22'
28
28
 
29
29
  - name: Run Repo-Local Turn-0 Startup Audit
30
- # External consumers copying this workflow can use npx -y burnoff@2.0.0 directly.
30
+ # External consumers copying this workflow can use npx -y burnoff@2.1.0 directly.
31
31
  run: |
32
32
  if [ -f bin/burnoff.mjs ]; then
33
33
  node bin/burnoff.mjs audit --startup --ci --github-annotations --client auto | tee burnoff-startup-lint.txt
34
34
  else
35
- npx -y burnoff@2.0.0 audit --startup --ci --github-annotations --client auto | tee burnoff-startup-lint.txt
35
+ npx -y burnoff@2.1.0 audit --startup --ci --github-annotations --client auto | tee burnoff-startup-lint.txt
36
36
  fi
37
37
  cat burnoff-startup-lint.txt >> "$GITHUB_STEP_SUMMARY"
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [2.1.0] - 2026-11-28
4
+
5
+ ### Added
6
+ - **Zero-Secret PR Usage Summary Export & Ephemeral CI Runner Hydration (`burnoff-pr-summary/v1`)** (`src/ci/pr-summary.mjs`, `src/ci/pr-cost.mjs`, `src/ci/ci-gate.mjs`, `bin/burnoff.mjs`, `test/pr-summary-sync.test.mjs`):
7
+ - Added `burnoff pr-cost --write-summary [file]` (default `.burnoff-ci/pr-summary.json`) to export a zero-prompt, zero-secret PR usage summary with allowlisted metrics, stripped OS home paths, `.claude/settings.local.json` and `author`/`sessionId` removal, credential redaction via `redactSecretsPure`, and a canonical SHA-256 `integrity.digest`.
8
+ - Wired automatic `.burnoff-ci/pr-summary.json` hydration into `buildPrCostAttribution` when ephemeral CI runners have zero local transcripts, alongside explicit `--summary <file>` on `pr-cost` and `ci-gate`, `burnoff-pr-summary/v1` verification inside `ci-gate --input`, fail-closed `SUMMARY_INTEGRITY_MISMATCH` tamper rejection, `STALE_PR_SUMMARY` `HEAD`-drift notice, `wasteRatioBasis` override support, and `--provider-usage` reconciliation on hydrated summaries.
9
+
3
10
  ## [2.0.0] - 2026-11-28
4
11
 
5
12
  ### Summary
package/README.md CHANGED
@@ -83,7 +83,7 @@ Single-pass reproducible workload benchmark (`node scripts/bench-savings.mjs`, `
83
83
 
84
84
  ## How Burnoff Compares
85
85
 
86
- | Feature | **Burnoff (`v2.0.0`)** | Cloud API Proxies | CLI Output Compressors (RTK, etc.) | Usage Viewers (`ccusage`) | Hand-Rolled Shell Hooks |
86
+ | Feature | **Burnoff (`v2.1.0`)** | Cloud API Proxies | CLI Output Compressors (RTK, etc.) | Usage Viewers (`ccusage`) | Hand-Rolled Shell Hooks |
87
87
  | :--- | :---: | :---: | :---: | :---: | :---: |
88
88
  | **100% Local (Zero MITM / Zero Network)** | Yes | No (proxy server) | Yes | Yes | Yes |
89
89
  | **Ring-0 Secret & Destructive Shell Hard Blocks** | Yes (`DET-01`/`02`/`03`) | Partial | No | No | Fragile regexes |
@@ -134,7 +134,7 @@ Single-pass reproducible workload benchmark (`node scripts/bench-savings.mjs`, `
134
134
  | `burnoff allow-once <DET-ID> --scope <substr>` | Single-use scoped `ask` override (`snooze` for timed overrides). |
135
135
  | `burnoff doctor [--gc] [--json]` | Run Node, SQLite FTS5, hook, warm daemon, and ledger diagnostics. |
136
136
  | `burnoff audit [--startup [--ci] [--strict] [--github-annotations]]` | Audit local sessions or lint Turn-0 `CLAUDE.md`/`GEMINI.md`/`.mcp.json` bloat. |
137
- | `burnoff pr-cost [--base main]` / `burnoff ci-gate` | Attribute branch spend & enforce `.burnoff.yaml` CI thresholds. |
137
+ | `burnoff pr-cost [--base main] [--write-summary [file]]` / `burnoff ci-gate [--summary <file>]` | Attribute branch spend, export zero-secret `.burnoff-ci/pr-summary.json` for ephemeral CI runners, & enforce `.burnoff.yaml` CI thresholds. |
138
138
  | `burnoff team-digest [--days 7]` / `burnoff search <turnId> [kw]` | 5-line EM spend summary & FTS5 log search. |
139
139
  | `burnoff daemon <start\|stop\|status>` | Manually inspect or manage the auto-spawned workspace IPC daemon. |
140
140
 
@@ -169,6 +169,8 @@ ciBudgetGate:
169
169
  maxRing0Violations: 0
170
170
  ```
171
171
 
172
+ **Ephemeral CI Runner Sync (Zero-Secret):** GitHub Actions runners lack local `~/.claude/projects/` transcripts. Run `burnoff pr-cost --write-summary` locally to export a scrubbed, SHA-256 integrity-verified `.burnoff-ci/pr-summary.json` (zero prompts, zero secrets, zero OS home paths) that `burnoff pr-cost` and `burnoff ci-gate` automatically hydrate and verify in CI.
173
+
172
174
  **Environment Variables:**
173
175
  - `BURNOFF_HOME` — Override `~/.burnoff/` state directory.
174
176
  - `BURNOFF_IPC_PATH` — Override daemon pipe / socket path (disables auto-daemon spawn).
package/bin/burnoff.mjs CHANGED
@@ -27,7 +27,7 @@ function getPackageVersion() {
27
27
  } catch (err) {
28
28
  void err; // ignore: package.json read fallback
29
29
  }
30
- return '2.0.0';
30
+ return '2.1.0';
31
31
  }
32
32
 
33
33
  const BOOLEAN_FLAGS = new Set([
@@ -117,9 +117,9 @@ function formatHelp() {
117
117
  ' snooze [DET-01..DET-04,DET-07..DET-10,DET-17|*] [--minutes 15] [--scope <substr>] [--session <id>] [--client claude|antigravity|both|auto] [--list|--clear] Timed ask-gate snooze',
118
118
  ' pause [15m|1h|status|off] [--client claude|antigravity|both|auto] [--json] Soft-pause ask gates & read clamps (Ring-0 denies stay active)',
119
119
  ' bypass [--grant <substr> | --] <cmd...> Grant a 1-use DET-07 override or run a command outside hook read clamps',
120
- ' pr-cost [--base main] [--client auto|claude|antigravity|both] [--json|--markdown] Attribute branch commits to AI cost',
120
+ ' pr-cost [--base main] [--client auto|claude|antigravity|both] [--write-summary [file]] [--summary <file>] [--json|--markdown] Attribute branch commits to AI cost',
121
121
  ' export [--since <7d|ISO-date|sha>] [--base <ref>] [--format json|csv] [--out <file>] Export PR attribution for CI budget gate',
122
- ' ci-gate [--strict] [--github-annotations] Enforce .burnoff.yaml ciBudgetGate thresholds',
122
+ ' ci-gate [--strict] [--summary <file>] [--github-annotations] Enforce .burnoff.yaml ciBudgetGate thresholds',
123
123
  ' team-digest [--days 7] [--json] Generate 5-line Engineering Manager spend & savings digest',
124
124
  ' search <turnId> [keyword] Query archived FTS5 tool outputs',
125
125
  ' daemon <start|stop|status> [--foreground] Manage warm workspace-scoped IPC daemon',
@@ -250,23 +250,55 @@ async function handleAudit(flags, io) {
250
250
  }
251
251
 
252
252
  async function handlePrCost(flags, io) {
253
- const { buildPrCostAttribution, formatPrAttributionMarkdown } = await import('../src/ci/pr-cost.mjs');
253
+ const { buildPrCostAttribution, formatPrAttributionMarkdown, writePrSummary } = await import(
254
+ '../src/ci/pr-cost.mjs'
255
+ );
256
+ const cwd = flags.cwd || process.cwd();
254
257
  const report = buildPrCostAttribution({
255
- cwd: flags.cwd || process.cwd(),
258
+ cwd,
256
259
  homeDir: flags.home || undefined,
257
260
  client: typeof flags.client === 'string' ? flags.client : 'auto',
258
261
  base: typeof flags.base === 'string' ? flags.base : 'main',
259
262
  head: typeof flags.head === 'string' ? flags.head : 'HEAD',
260
263
  wasteRatioBasis: typeof flags['waste-basis'] === 'string' ? flags['waste-basis'] : undefined,
261
- providerUsagePath: typeof flags['provider-usage'] === 'string' ? flags['provider-usage'] : undefined
264
+ providerUsagePath: typeof flags['provider-usage'] === 'string' ? flags['provider-usage'] : undefined,
265
+ summaryPath: typeof flags.summary === 'string' ? flags.summary : undefined
262
266
  });
263
267
  if (!report.ok) {
264
268
  io.stderr.write(`Burnoff pr-cost error: ${report.error || 'failed'}\n`);
265
269
  return 1;
266
270
  }
271
+
272
+ let outputReport = report;
273
+ let writtenNote = '';
274
+ if (flags['write-summary']) {
275
+ const written = writePrSummary(report, {
276
+ cwd,
277
+ outPath: typeof flags['write-summary'] === 'string' ? flags['write-summary'] : undefined
278
+ });
279
+ if (!written.ok) {
280
+ io.stderr.write(`Burnoff pr-cost summary error: ${written.error || 'failed'}\n`);
281
+ return 1;
282
+ }
283
+ if (flags.json) {
284
+ outputReport = {
285
+ ...report,
286
+ summaryWritten: {
287
+ format: written.format,
288
+ path: written.relativePath,
289
+ headSha: written.headSha,
290
+ digest: written.digest,
291
+ redactedCount: written.redactedCount
292
+ }
293
+ };
294
+ } else {
295
+ writtenNote = `\n> Exported zero-secret PR summary: \`${written.relativePath}\` (\`sha256:${written.digest.slice(0, 12)}\`)\n`;
296
+ }
297
+ }
298
+
267
299
  const text = flags.json
268
- ? JSON.stringify(report, null, 2) + '\n'
269
- : formatPrAttributionMarkdown(report);
300
+ ? JSON.stringify(outputReport, null, 2) + '\n'
301
+ : formatPrAttributionMarkdown(report) + writtenNote;
270
302
  writeOut(text, flags.out, io.stdout);
271
303
  return 0;
272
304
  }
@@ -314,6 +346,7 @@ async function handleCiGate(flags, io) {
314
346
  base: typeof flags.base === 'string' ? flags.base : 'main',
315
347
  head: typeof flags.head === 'string' ? flags.head : 'HEAD',
316
348
  inputPath: typeof flags.input === 'string' ? flags.input : undefined,
349
+ summaryPath: typeof flags.summary === 'string' ? flags.summary : undefined,
317
350
  wasteRatioBasis: typeof flags['waste-basis'] === 'string' ? flags['waste-basis'] : undefined,
318
351
  providerUsagePath: typeof flags['provider-usage'] === 'string' ? flags['provider-usage'] : undefined,
319
352
  maxPrQuotaUnits: flags['max-pr-quota-units'] !== undefined ? Number(flags['max-pr-quota-units']) : undefined,
@@ -3,7 +3,7 @@ description: Run Burnoff diagnostics, Turn-0 startup audits, pause/bypass overri
3
3
  argument-hint: "[doctor|audit|startup|allow-once <DET-xx>|snooze <DET-xx>|pause [15m|1h|status|off]|bypass [--grant <substr>|-- <cmd>]|pr-cost|team-digest|init]"
4
4
  ---
5
5
 
6
- Run Burnoff (`npx -y burnoff@2.0.0` or local `node bin/burnoff.mjs` when developing in the Burnoff repo) according to `$ARGUMENTS`:
6
+ Run Burnoff (`npx -y burnoff@2.1.0` or local `node bin/burnoff.mjs` when developing in the Burnoff repo) according to `$ARGUMENTS`:
7
7
 
8
8
  - Empty arguments: run `burnoff doctor` and `burnoff team-digest --days 7` and summarize findings clearly.
9
9
  - `doctor`: run `burnoff doctor` to verify Node/SQLite FTS5, hooks, and warm daemon health.
@@ -30,9 +30,9 @@ Burnoff (`MIT`, zero runtime dependencies, 100% local execution) is onboarding a
30
30
  Run inside a representative repo and paste sanitized summary lines only:
31
31
 
32
32
  ```bash
33
- npx -y burnoff@2.0.0 doctor
34
- npx -y burnoff@2.0.0 audit --startup --ci
35
- npx -y burnoff@2.0.0 team-digest --days 7
33
+ npx -y burnoff@2.1.0 doctor
34
+ npx -y burnoff@2.1.0 audit --startup --ci
35
+ npx -y burnoff@2.1.0 team-digest --days 7
36
36
  ```
37
37
 
38
38
  ### 4. Security & Privacy Requirements
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "burnoff",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Deterministic circuit breakers, bounded file-read guards, and CI spend gates for Claude Code and Google Antigravity.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -11,6 +11,7 @@ import fs from 'node:fs';
11
11
  import path from 'node:path';
12
12
  import { loadBurnoffPolicy } from '../config/policy.mjs';
13
13
  import { buildPrCostAttribution } from './pr-cost.mjs';
14
+ import { PR_SUMMARY_FORMAT, readPrSummary } from './pr-summary.mjs';
14
15
 
15
16
  export const DEFAULT_CI_BUDGET_POLICY = Object.freeze({
16
17
  maxPrCostUsd: 15.0,
@@ -149,6 +150,22 @@ export function evaluateCiBudgetGate(options = {}) {
149
150
  const policy = loadCiBudgetPolicy(cwd, policyOverrides);
150
151
 
151
152
  let attribution = options.attribution || null;
153
+ if (!attribution && typeof options.summaryPath === 'string' && options.summaryPath.trim()) {
154
+ const sumRes = readPrSummary(options.summaryPath.trim(), {
155
+ cwd,
156
+ head: options.head || 'HEAD',
157
+ wasteRatioBasis: policy.wasteRatioBasis
158
+ });
159
+ if (!sumRes.ok) {
160
+ return {
161
+ ok: false,
162
+ verdict: 'ERROR',
163
+ exitCode: 1,
164
+ error: sumRes.error
165
+ };
166
+ }
167
+ attribution = sumRes.report;
168
+ }
152
169
  if (!attribution && options.inputPath) {
153
170
  const absIn = path.resolve(options.inputPath);
154
171
  if (!fs.existsSync(absIn)) {
@@ -160,7 +177,25 @@ export function evaluateCiBudgetGate(options = {}) {
160
177
  };
161
178
  }
162
179
  try {
163
- attribution = JSON.parse(fs.readFileSync(absIn, 'utf8'));
180
+ const parsed = JSON.parse(fs.readFileSync(absIn, 'utf8'));
181
+ if (parsed?.format === PR_SUMMARY_FORMAT) {
182
+ const sumRes = readPrSummary(absIn, {
183
+ cwd,
184
+ head: options.head || 'HEAD',
185
+ wasteRatioBasis: policy.wasteRatioBasis
186
+ });
187
+ if (!sumRes.ok) {
188
+ return {
189
+ ok: false,
190
+ verdict: 'ERROR',
191
+ exitCode: 1,
192
+ error: sumRes.error
193
+ };
194
+ }
195
+ attribution = sumRes.report;
196
+ } else {
197
+ attribution = parsed;
198
+ }
164
199
  } catch (err) {
165
200
  return {
166
201
  ok: false,
@@ -246,7 +281,7 @@ export function evaluateCiBudgetGate(options = {}) {
246
281
 
247
282
  if (missingTranscripts) {
248
283
  const noticeMsg =
249
- 'No Claude Code session transcripts matched this PR window (0 tokens attributed). Upload .burnoff-ci/provider-usage.json or session transcripts, or set failOnMissingTranscripts: true to enforce.';
284
+ 'No Claude Code session transcripts matched this PR window (0 tokens attributed). Run "burnoff pr-cost --write-summary" locally to export .burnoff-ci/pr-summary.json, or upload .burnoff-ci/provider-usage.json, or set failOnMissingTranscripts: true to enforce.';
250
285
  notices.push({ code: 'MISSING_TRANSCRIPTS', message: noticeMsg });
251
286
  if (policy.failOnMissingTranscripts === true) {
252
287
  violations.push({
@@ -28,6 +28,21 @@ import {
28
28
  readAntigravityConversationDbMetrics,
29
29
  mergeAntigravitySessionSources
30
30
  } from '../storage/telemetry-metrics.mjs';
31
+ import {
32
+ PR_SUMMARY_FORMAT,
33
+ DEFAULT_PR_SUMMARY_REL_PATH,
34
+ buildPrSummary,
35
+ writePrSummary,
36
+ readPrSummary
37
+ } from './pr-summary.mjs';
38
+
39
+ export {
40
+ PR_SUMMARY_FORMAT,
41
+ DEFAULT_PR_SUMMARY_REL_PATH,
42
+ buildPrSummary,
43
+ writePrSummary,
44
+ readPrSummary
45
+ };
31
46
 
32
47
  export const PR_ATTRIBUTION_FORMAT = 'burnoff-pr-attribution/v1';
33
48
 
@@ -112,6 +127,38 @@ function readProviderUsageExportUsd(providerUsagePath) {
112
127
  return found ? Number(total.toFixed(4)) : null;
113
128
  }
114
129
 
130
+ function applyProviderUsageToReport(report, providerUsagePath) {
131
+ if (!providerUsagePath) return { ok: true, report };
132
+ try {
133
+ const rawProviderUsd = readProviderUsageExportUsd(providerUsagePath);
134
+ if (typeof rawProviderUsd === 'number' && Number.isFinite(rawProviderUsd)) {
135
+ const estimatedCostUsd = Number(report?.summary?.estimatedCostUsd || 0);
136
+ const reconciledCostUsd = Number(rawProviderUsd.toFixed(4));
137
+ const attributionVariancePct =
138
+ reconciledCostUsd > 0
139
+ ? Number((((estimatedCostUsd - reconciledCostUsd) / reconciledCostUsd) * 100).toFixed(2))
140
+ : 0;
141
+ return {
142
+ ok: true,
143
+ report: {
144
+ ...report,
145
+ summary: {
146
+ ...(report.summary || {}),
147
+ reconciledCostUsd,
148
+ attributionVariancePct
149
+ }
150
+ }
151
+ };
152
+ }
153
+ return { ok: true, report };
154
+ } catch (err) {
155
+ return {
156
+ ok: false,
157
+ error: err?.message || String(err)
158
+ };
159
+ }
160
+ }
161
+
115
162
  function parseGitLogNumstat(rawText = '', cwd = '') {
116
163
  const commits = [];
117
164
  let current = null;
@@ -430,6 +477,23 @@ export function buildPrCostAttribution(options = {}) {
430
477
  const homeDir = explicitHomeDir || getHomeDir();
431
478
  const base = String(options.base || 'main');
432
479
  const head = String(options.head || 'HEAD');
480
+
481
+ if (typeof options.summaryPath === 'string' && options.summaryPath.trim()) {
482
+ const sumRes = readPrSummary(options.summaryPath.trim(), {
483
+ cwd,
484
+ head,
485
+ wasteRatioBasis: options.wasteRatioBasis
486
+ });
487
+ if (!sumRes.ok) {
488
+ return { ok: false, error: sumRes.error, code: sumRes.code, base, head };
489
+ }
490
+ const applied = applyProviderUsageToReport(sumRes.report, options.providerUsagePath);
491
+ if (!applied.ok) {
492
+ return { ok: false, error: applied.error, base, head };
493
+ }
494
+ return applied.report;
495
+ }
496
+
433
497
  const hasExplicitPriceOverride = options.pricePerMillionUsd !== undefined && options.pricePerMillionUsd !== null;
434
498
  const pricePerMillionUsd = Number(options.pricePerMillionUsd || 3.0);
435
499
 
@@ -810,6 +874,32 @@ export function buildPrCostAttribution(options = {}) {
810
874
  }
811
875
 
812
876
  const totalTokens = sumIn + sumWrite + sumCache + sumOut;
877
+
878
+ if (
879
+ sessionCount === 0 &&
880
+ totalTokens === 0 &&
881
+ !Array.isArray(options.steps) &&
882
+ !Array.isArray(options.sessions) &&
883
+ options.autoLoadSummary !== false
884
+ ) {
885
+ const defaultSummaryAbs = path.join(cwd, DEFAULT_PR_SUMMARY_REL_PATH);
886
+ if (fs.existsSync(defaultSummaryAbs)) {
887
+ const sumRes = readPrSummary(defaultSummaryAbs, {
888
+ cwd,
889
+ head,
890
+ wasteRatioBasis: options.wasteRatioBasis
891
+ });
892
+ if (!sumRes.ok) {
893
+ return { ok: false, error: sumRes.error, code: sumRes.code, base, head };
894
+ }
895
+ const applied = applyProviderUsageToReport(sumRes.report, options.providerUsagePath);
896
+ if (!applied.ok) {
897
+ return { ok: false, error: applied.error, base, head };
898
+ }
899
+ return applied.report;
900
+ }
901
+ }
902
+
813
903
  const cacheDenom = sumIn + sumWrite + sumCache;
814
904
  const cacheHitPct = cacheDenom > 0 ? Math.round((sumCache / cacheDenom) * 100) : 0;
815
905
  const estimatedCostUsd = Number(sumCostUsd.toFixed(4));
@@ -980,6 +1070,11 @@ export function formatPrAttributionMarkdown(report = {}) {
980
1070
  '| Metric | Value |',
981
1071
  '| :--- | :--- |',
982
1072
  `| **Commits / Files Changed** | \`${s.totalCommits ?? 0}\` commits · \`${s.totalFilesChanged ?? 0}\` files (\`+${s.totalAdditions ?? 0} / -${s.totalDeletions ?? 0}\`) |`,
1073
+ ...(report.source === 'pr-summary'
1074
+ ? [
1075
+ `| **Attribution Source** | \`pr-summary\` (\`${report.summarySourcePath || DEFAULT_PR_SUMMARY_REL_PATH}\`, \`sha256:${String(report.summaryDigest || '').slice(0, 12)}\`) |`
1076
+ ]
1077
+ : []),
983
1078
  `| **Total Attributed Tokens** | \`${((s.totalTokens || 0) / 1000).toFixed(1)}k\` |`,
984
1079
  `| **Cache Hit Rate** | \`${s.cacheHitPct ?? 0}%\` |`,
985
1080
  `| **Estimated PR AI Cost** | \`$${Number(s.estimatedCostUsd || 0).toFixed(4)}\` (\`$${Number(s.usdPer100Loc || 0).toFixed(4)} / 100 LOC\`) |`,
@@ -1032,8 +1127,13 @@ export function formatPrAttributionMarkdown(report = {}) {
1032
1127
 
1033
1128
  export default {
1034
1129
  PR_ATTRIBUTION_FORMAT,
1130
+ PR_SUMMARY_FORMAT,
1131
+ DEFAULT_PR_SUMMARY_REL_PATH,
1035
1132
  sanitizeRelativeRepoPath,
1036
1133
  collectGitBranchCommits,
1037
1134
  buildPrCostAttribution,
1038
- formatPrAttributionMarkdown
1135
+ formatPrAttributionMarkdown,
1136
+ buildPrSummary,
1137
+ writePrSummary,
1138
+ readPrSummary
1039
1139
  };
@@ -0,0 +1,467 @@
1
+ /**
2
+ * @file src/ci/pr-summary.mjs
3
+ * Zero-Secret PR Usage Summary Exporter & Ephemeral CI Runner Verifier (`burnoff-pr-summary/v1`).
4
+ *
5
+ * Exports sanitized, integrity-hashed branch/PR token & cost summaries locally so
6
+ * ephemeral CI runners without `~/.claude/projects/` transcripts can verify and gate PRs
7
+ * without leaking prompts, credentials, author PII, or local OS paths.
8
+ * Zero runtime dependencies, zero network calls.
9
+ */
10
+
11
+ import { execFileSync } from 'node:child_process';
12
+ import crypto from 'node:crypto';
13
+ import fs from 'node:fs';
14
+ import os from 'node:os';
15
+ import path from 'node:path';
16
+ import { redactSecretsPure } from '../guards/credential-scrubber.mjs';
17
+ import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
18
+
19
+ export const PR_SUMMARY_FORMAT = 'burnoff-pr-summary/v1';
20
+ export const PR_ATTRIBUTION_FORMAT = 'burnoff-pr-attribution/v1';
21
+ export const DEFAULT_PR_SUMMARY_REL_PATH = '.burnoff-ci/pr-summary.json';
22
+
23
+ const SUMMARY_ALLOWED_KEYS = Object.freeze([
24
+ 'sessionCount',
25
+ 'totalCommits',
26
+ 'totalFilesChanged',
27
+ 'totalAdditions',
28
+ 'totalDeletions',
29
+ 'totalLoc',
30
+ 'totalInputTokens',
31
+ 'totalCacheWriteTokens',
32
+ 'totalCacheReadTokens',
33
+ 'totalOutputTokens',
34
+ 'totalTokens',
35
+ 'cacheHitPct',
36
+ 'estimatedCostUsd',
37
+ 'reconciledCostUsd',
38
+ 'attributionVariancePct',
39
+ 'estimatedSavedUsd',
40
+ 'estimatedQuotaUnits',
41
+ 'quotaUnitLabel',
42
+ 'quotaWeightsDisclosure',
43
+ 'quotaBreakdown',
44
+ 'wasteRatioBasis',
45
+ 'grossWasteTokens',
46
+ 'grossWasteRatioPct',
47
+ 'excludedUpstreamTokens',
48
+ 'excludedUpstreamSharePct',
49
+ 'appendFloorTokens',
50
+ 'upstreamEvictionTokens',
51
+ 'evictionByPattern',
52
+ 'actionableWasteTokens',
53
+ 'actionableWasteRatioPct',
54
+ 'estimatedWasteTokens',
55
+ 'wasteRatioPct',
56
+ 'ring0Violations',
57
+ 'usdPer100Loc'
58
+ ]);
59
+
60
+ function isExcludedLocalToolPath(relPath = '') {
61
+ const norm = String(relPath || '').replace(/\\/g, '/').replace(/^\.\//, '').toLowerCase();
62
+ return norm === '.claude/settings.local.json' || norm.endsWith('/.claude/settings.local.json');
63
+ }
64
+
65
+ function sanitizeRepoPath(rawPath = '', cwd = '') {
66
+ const input = String(rawPath || '').trim();
67
+ if (!input) return '';
68
+ let normalized = input.replace(/\\/g, '/');
69
+ if (cwd) {
70
+ const abs = path.isAbsolute(input) ? input : path.resolve(cwd, input);
71
+ const rel = path.relative(cwd, abs).replace(/\\/g, '/');
72
+ if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
73
+ normalized = rel;
74
+ }
75
+ }
76
+ const homeNorm = String(os.homedir() || '').replace(/\\/g, '/').replace(/\/+$/, '');
77
+ if (homeNorm && normalized.toLowerCase().startsWith(`${homeNorm.toLowerCase()}/`)) {
78
+ normalized = normalized.slice(homeNorm.length + 1);
79
+ }
80
+ normalized = normalized
81
+ .replace(/^[A-Za-z]:\/Users\/[^/]+\//i, '')
82
+ .replace(/^\/Users\/[^/]+\//i, '')
83
+ .replace(/^\/home\/[^/]+\//i, '')
84
+ .replace(/^file:\/\/\//i, '')
85
+ .replace(/^\.\//, '');
86
+ return normalized;
87
+ }
88
+
89
+ function escapeRegExp(str = '') {
90
+ return String(str).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
91
+ }
92
+
93
+ function scrubTextField(rawText = '', maxLen = 200) {
94
+ let out = String(rawText ?? '');
95
+
96
+ const homeRaw = String(os.homedir() || '').replace(/[\\/]+$/, '');
97
+ if (homeRaw) {
98
+ const homeSlash = homeRaw.replace(/\\/g, '/');
99
+ const homeBack = homeRaw.replace(/\//g, '\\');
100
+ for (const prefix of new Set([homeRaw, homeSlash, homeBack])) {
101
+ if (!prefix) continue;
102
+ const prefixRe = new RegExp(`${escapeRegExp(prefix)}[\\\\/]?`, 'gi');
103
+ out = out.replace(prefixRe, '');
104
+ }
105
+ }
106
+
107
+ out = out
108
+ .replace(/file:\/\/\/[A-Za-z]:[\\/][^ \r\n\t'"]+/gi, (m) => sanitizeRepoPath(m))
109
+ .replace(/\b[A-Za-z]:[\\/]Users[\\/][^\\/\s'"]+[\\/]/gi, '')
110
+ .replace(/(^|[\s'"])(?:\/Users\/[^/\s'"]+\/|\/home\/[^/\s'"]+\/)/g, '$1');
111
+
112
+ const secretRes = redactSecretsPure(out);
113
+ const collapsed = secretRes.sanitized.replace(/[\r\n]+/g, ' ').trim();
114
+ const capped = maxLen > 0 && collapsed.length > maxLen ? `${collapsed.slice(0, maxLen - 3)}...` : collapsed;
115
+
116
+ return {
117
+ text: capped,
118
+ redactedCount: secretRes.redactedCount
119
+ };
120
+ }
121
+
122
+ function canonicalizeValue(value) {
123
+ if (Array.isArray(value)) {
124
+ return value.map((item) => canonicalizeValue(item));
125
+ }
126
+ if (value && typeof value === 'object') {
127
+ const sorted = {};
128
+ for (const key of Object.keys(value).sort()) {
129
+ const v = value[key];
130
+ if (v !== undefined) {
131
+ sorted[key] = canonicalizeValue(v);
132
+ }
133
+ }
134
+ return sorted;
135
+ }
136
+ return value;
137
+ }
138
+
139
+ /**
140
+ * Resolves the git commit SHA for `head` (defaults to `HEAD`), returning `null` if unavailable.
141
+ */
142
+ export function resolveGitHeadSha(cwd, head = 'HEAD') {
143
+ try {
144
+ const out = execFileSync('git', ['rev-parse', '--verify', '--quiet', `${head}^{commit}`], {
145
+ cwd: path.resolve(cwd || process.cwd()),
146
+ encoding: 'utf8',
147
+ stdio: ['ignore', 'pipe', 'ignore']
148
+ });
149
+ const trimmed = String(out || '').trim();
150
+ return trimmed || null;
151
+ } catch {
152
+ return null; // ignore: non-git workspace or unresolvable revision yields null headSha
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Computes deterministic SHA-256 integrity digest over the signed PR summary payload.
158
+ */
159
+ export function computePrSummaryDigest(doc = {}) {
160
+ const payload = canonicalizeValue({
161
+ format: doc.format,
162
+ headSha: doc.headSha ?? null,
163
+ base: doc.base ?? 'main',
164
+ head: doc.head ?? 'HEAD',
165
+ summary: doc.summary ?? {},
166
+ notices: Array.isArray(doc.notices) ? doc.notices : [],
167
+ commits: Array.isArray(doc.commits) ? doc.commits : [],
168
+ topCostFiles: Array.isArray(doc.topCostFiles) ? doc.topCostFiles : []
169
+ });
170
+ return crypto.createHash('sha256').update(JSON.stringify(payload), 'utf8').digest('hex');
171
+ }
172
+
173
+ function pickSummaryFields(rawSummary = {}) {
174
+ const out = {};
175
+ for (const key of SUMMARY_ALLOWED_KEYS) {
176
+ if (rawSummary[key] === undefined) continue;
177
+ const val = rawSummary[key];
178
+ if (val === null || typeof val === 'number' || typeof val === 'boolean') {
179
+ out[key] = val;
180
+ } else if (typeof val === 'string') {
181
+ out[key] = scrubTextField(val, 240).text;
182
+ } else if (key === 'quotaBreakdown' && val && typeof val === 'object') {
183
+ out[key] = {
184
+ unit: typeof val.unit === 'string' ? val.unit : 'Q-units',
185
+ estimated: Boolean(val.estimated),
186
+ totalQuotaUnits: Number(val.totalQuotaUnits || 0),
187
+ effectiveMultiplier: Number(val.effectiveMultiplier || 1),
188
+ elevatedModels: Array.isArray(val.elevatedModels) ? val.elevatedModels.map(String).sort() : [],
189
+ sdkCliCalls: Number(val.sdkCliCalls || 0),
190
+ acpCustomAgentCalls: Number(val.acpCustomAgentCalls || 0)
191
+ };
192
+ } else if (key === 'evictionByPattern' && val && typeof val === 'object') {
193
+ const cleanPatterns = {};
194
+ for (const [pk, pv] of Object.entries(val)) {
195
+ if (Number.isFinite(Number(pv))) {
196
+ cleanPatterns[String(pk)] = Number(pv);
197
+ }
198
+ }
199
+ out[key] = cleanPatterns;
200
+ }
201
+ }
202
+ return out;
203
+ }
204
+
205
+ function sanitizeCommitRow(row = {}) {
206
+ const scrubbedSubject = scrubTextField(row.subject || '', 160);
207
+ const sha = String(row.sha || '');
208
+ return {
209
+ row: {
210
+ sha,
211
+ shortSha: String(row.shortSha || sha.slice(0, 7)),
212
+ timestampIso: String(row.timestampIso || ''),
213
+ subject: scrubbedSubject.text,
214
+ filesChanged: Number(row.filesChanged || 0),
215
+ additions: Number(row.additions || 0),
216
+ deletions: Number(row.deletions || 0),
217
+ inputTokens: Number(row.inputTokens || 0),
218
+ cacheWriteTokens: Number(row.cacheWriteTokens || 0),
219
+ cacheReadTokens: Number(row.cacheReadTokens || 0),
220
+ outputTokens: Number(row.outputTokens || 0),
221
+ attributedTokens: Number(row.attributedTokens || 0),
222
+ cacheHitPct: Number(row.cacheHitPct || 0),
223
+ estimatedCostUsd: Number(row.estimatedCostUsd || 0),
224
+ wasteTokens: Number(row.wasteTokens || 0),
225
+ ring0Violations: Number(row.ring0Violations || 0)
226
+ },
227
+ redactedCount: scrubbedSubject.redactedCount
228
+ };
229
+ }
230
+
231
+ function sanitizeTopCostFiles(files = [], cwd = '') {
232
+ return (Array.isArray(files) ? files : [])
233
+ .map((f) => {
234
+ const cleanPath = sanitizeRepoPath(f?.filePath || '', cwd);
235
+ return {
236
+ filePath: cleanPath,
237
+ additions: Number(f?.additions || 0),
238
+ deletions: Number(f?.deletions || 0),
239
+ attributedTokens: Number(f?.attributedTokens || 0),
240
+ estimatedCostUsd: Number(f?.estimatedCostUsd || 0)
241
+ };
242
+ })
243
+ .filter((f) => f.filePath && !isExcludedLocalToolPath(f.filePath));
244
+ }
245
+
246
+ function sanitizeNotices(notices = []) {
247
+ const cleaned = [];
248
+ let redactedCount = 0;
249
+ for (const n of Array.isArray(notices) ? notices : []) {
250
+ if (!n || !n.code) continue;
251
+ const msgRes = scrubTextField(n.message || '', 300);
252
+ redactedCount += msgRes.redactedCount;
253
+ cleaned.push({
254
+ code: String(n.code),
255
+ message: msgRes.text
256
+ });
257
+ }
258
+ return { notices: cleaned, redactedCount };
259
+ }
260
+
261
+ /**
262
+ * Builds a zero-secret, integrity-hashed `burnoff-pr-summary/v1` document from a `pr-cost` report.
263
+ */
264
+ export function buildPrSummary(report, options = {}) {
265
+ if (!report || report.ok === false || !report.summary || typeof report.summary !== 'object') {
266
+ throw new Error('Cannot build PR summary: attribution report is missing or invalid.');
267
+ }
268
+
269
+ const cwd = path.resolve(options.cwd || process.cwd());
270
+ const base = String(report.base || options.base || 'main');
271
+ const head = String(report.head || options.head || 'HEAD');
272
+
273
+ let redactedCount = 0;
274
+ const commits = [];
275
+ for (const rawCommit of Array.isArray(report.commits) ? report.commits : []) {
276
+ const res = sanitizeCommitRow(rawCommit);
277
+ redactedCount += res.redactedCount;
278
+ commits.push(res.row);
279
+ }
280
+
281
+ const topCostFiles = sanitizeTopCostFiles(report.topCostFiles, cwd);
282
+ const noticeRes = sanitizeNotices(report.notices);
283
+ redactedCount += noticeRes.redactedCount;
284
+
285
+ const summary = pickSummaryFields(report.summary);
286
+ const headSha =
287
+ options.headSha !== undefined
288
+ ? options.headSha
289
+ : report.headSha !== undefined
290
+ ? report.headSha
291
+ : resolveGitHeadSha(cwd, head) ?? (commits.length ? commits[commits.length - 1].sha || null : null);
292
+
293
+ const doc = {
294
+ format: PR_SUMMARY_FORMAT,
295
+ generatedAt: report.generatedAt || new Date().toISOString(),
296
+ headSha,
297
+ base,
298
+ head,
299
+ fallbackUsed: Boolean(report.fallbackUsed),
300
+ privacy: {
301
+ zeroSecrets: true,
302
+ promptsIncluded: false,
303
+ localPathsStripped: true,
304
+ redactedCount
305
+ },
306
+ summary,
307
+ notices: noticeRes.notices,
308
+ commits,
309
+ topCostFiles
310
+ };
311
+
312
+ doc.integrity = {
313
+ algorithm: 'sha256',
314
+ digest: computePrSummaryDigest(doc)
315
+ };
316
+
317
+ return doc;
318
+ }
319
+
320
+ /**
321
+ * Exports and atomically writes a zero-secret PR summary file (defaults to `.burnoff-ci/pr-summary.json`).
322
+ */
323
+ export function writePrSummary(report, options = {}) {
324
+ try {
325
+ const cwd = path.resolve(options.cwd || process.cwd());
326
+ const doc = buildPrSummary(report, { ...options, cwd });
327
+ const targetPath = options.outPath
328
+ ? path.resolve(cwd, options.outPath)
329
+ : path.join(cwd, DEFAULT_PR_SUMMARY_REL_PATH);
330
+
331
+ atomicWriteFileSync(targetPath, JSON.stringify(doc, null, 2) + '\n', { encoding: 'utf8' });
332
+
333
+ return {
334
+ ok: true,
335
+ format: PR_SUMMARY_FORMAT,
336
+ path: targetPath,
337
+ relativePath: sanitizeRepoPath(targetPath, cwd) || DEFAULT_PR_SUMMARY_REL_PATH,
338
+ headSha: doc.headSha,
339
+ digest: doc.integrity.digest,
340
+ redactedCount: doc.privacy.redactedCount,
341
+ summary: doc
342
+ };
343
+ } catch (err) {
344
+ return {
345
+ ok: false,
346
+ error: err?.message || String(err)
347
+ };
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Reads, integrity-verifies, and hydrates a `.burnoff-ci/pr-summary.json` into a `pr-cost` report.
353
+ */
354
+ export function readPrSummary(summaryPath, options = {}) {
355
+ const cwd = path.resolve(options.cwd || process.cwd());
356
+ const absPath = path.resolve(cwd, summaryPath || DEFAULT_PR_SUMMARY_REL_PATH);
357
+
358
+ if (!fs.existsSync(absPath)) {
359
+ return {
360
+ ok: false,
361
+ code: 'SUMMARY_NOT_FOUND',
362
+ error: `PR summary file not found: ${absPath}`
363
+ };
364
+ }
365
+
366
+ let doc;
367
+ try {
368
+ doc = JSON.parse(fs.readFileSync(absPath, 'utf8'));
369
+ } catch (err) {
370
+ return {
371
+ ok: false,
372
+ code: 'SUMMARY_INVALID_JSON',
373
+ error: `Invalid PR summary JSON (${absPath}): ${err?.message || String(err)}`
374
+ };
375
+ }
376
+
377
+ if (!doc || typeof doc !== 'object' || doc.format !== PR_SUMMARY_FORMAT || !doc.summary || typeof doc.summary !== 'object') {
378
+ return {
379
+ ok: false,
380
+ code: 'SUMMARY_INVALID_FORMAT',
381
+ error: `Invalid PR summary format in ${absPath} (expected format "${PR_SUMMARY_FORMAT}").`
382
+ };
383
+ }
384
+
385
+ if (options.verifyIntegrity !== false) {
386
+ const expectedDigest = computePrSummaryDigest(doc);
387
+ if (
388
+ !doc.integrity ||
389
+ doc.integrity.algorithm !== 'sha256' ||
390
+ typeof doc.integrity.digest !== 'string' ||
391
+ doc.integrity.digest !== expectedDigest
392
+ ) {
393
+ return {
394
+ ok: false,
395
+ code: 'SUMMARY_INTEGRITY_MISMATCH',
396
+ error: 'PR summary integrity digest mismatch (file may be corrupted or modified). Re-run `burnoff pr-cost --write-summary`.'
397
+ };
398
+ }
399
+ }
400
+
401
+ const expectedHeadSha =
402
+ options.expectedHeadSha !== undefined
403
+ ? options.expectedHeadSha
404
+ : resolveGitHeadSha(cwd, options.head || doc.head || 'HEAD');
405
+
406
+ const notices = sanitizeNotices(doc.notices).notices;
407
+ let stale = false;
408
+ if (expectedHeadSha && doc.headSha && expectedHeadSha !== doc.headSha) {
409
+ stale = true;
410
+ notices.push({
411
+ code: 'STALE_PR_SUMMARY',
412
+ message: `PR summary was exported at ${String(doc.headSha).slice(0, 7)}, current HEAD is ${String(expectedHeadSha).slice(0, 7)}; re-run 'burnoff pr-cost --write-summary' to refresh.`
413
+ });
414
+ }
415
+
416
+ const summary = pickSummaryFields(doc.summary);
417
+ if (options.wasteRatioBasis !== undefined && options.wasteRatioBasis !== null) {
418
+ const basis = String(options.wasteRatioBasis).trim().toLowerCase() === 'gross' ? 'gross' : 'actionable';
419
+ summary.wasteRatioBasis = basis;
420
+ if (basis === 'gross') {
421
+ if (summary.grossWasteTokens !== undefined) summary.estimatedWasteTokens = summary.grossWasteTokens;
422
+ if (summary.grossWasteRatioPct !== undefined) summary.wasteRatioPct = summary.grossWasteRatioPct;
423
+ } else {
424
+ if (summary.actionableWasteTokens !== undefined) summary.estimatedWasteTokens = summary.actionableWasteTokens;
425
+ if (summary.actionableWasteRatioPct !== undefined) summary.wasteRatioPct = summary.actionableWasteRatioPct;
426
+ }
427
+ }
428
+
429
+ const commits = (Array.isArray(doc.commits) ? doc.commits : []).map((c) => sanitizeCommitRow(c).row);
430
+ const topCostFiles = sanitizeTopCostFiles(doc.topCostFiles, cwd);
431
+ const relativePath = sanitizeRepoPath(absPath, cwd) || DEFAULT_PR_SUMMARY_REL_PATH;
432
+
433
+ return {
434
+ ok: true,
435
+ stale,
436
+ summaryPath: absPath,
437
+ relativePath,
438
+ report: {
439
+ ok: true,
440
+ format: PR_ATTRIBUTION_FORMAT,
441
+ source: 'pr-summary',
442
+ summaryFormat: PR_SUMMARY_FORMAT,
443
+ summarySourcePath: relativePath,
444
+ summaryDigest: doc.integrity?.digest || null,
445
+ headSha: doc.headSha ?? null,
446
+ staleSummary: stale,
447
+ generatedAt: doc.generatedAt || null,
448
+ base: doc.base || 'main',
449
+ head: doc.head || 'HEAD',
450
+ fallbackUsed: Boolean(doc.fallbackUsed),
451
+ summary,
452
+ notices,
453
+ commits,
454
+ topCostFiles
455
+ }
456
+ };
457
+ }
458
+
459
+ export default {
460
+ PR_SUMMARY_FORMAT,
461
+ DEFAULT_PR_SUMMARY_REL_PATH,
462
+ resolveGitHeadSha,
463
+ computePrSummaryDigest,
464
+ buildPrSummary,
465
+ writePrSummary,
466
+ readPrSummary
467
+ };