burnoff 1.4.1 → 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.
Files changed (62) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.github/workflows/burnoff-pr-gate.yml +5 -3
  3. package/.github/workflows/burnoff-startup-lint.yml +2 -2
  4. package/CHANGELOG.md +74 -0
  5. package/README.md +187 -213
  6. package/SECURITY.md +38 -0
  7. package/bin/burnoff.mjs +307 -32
  8. package/commands/burnoff.md +6 -4
  9. package/docs/CLAUDE_CODE_PLUGIN.md +29 -28
  10. package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
  11. package/hooks/hook-io.mjs +216 -11
  12. package/hooks/hooks.json +44 -0
  13. package/hooks/post-tool-use.mjs +3 -1
  14. package/hooks/pre-tool-use.mjs +47 -8
  15. package/hooks/session-lifecycle.mjs +24 -3
  16. package/hooks/user-prompt-submit.mjs +98 -0
  17. package/package.json +6 -4
  18. package/scripts/bench-hooks.mjs +34 -3
  19. package/scripts/bench-savings.mjs +318 -0
  20. package/scripts/burnoff-statusline.mjs +138 -6
  21. package/src/ci/ci-gate.mjs +199 -13
  22. package/src/ci/pr-cost.mjs +417 -45
  23. package/src/ci/pr-summary.mjs +467 -0
  24. package/src/cli/audit.mjs +179 -28
  25. package/src/cli/doctor.mjs +32 -6
  26. package/src/cli/hook-health.mjs +9 -1
  27. package/src/cli/init.mjs +226 -39
  28. package/src/cli/preview.mjs +299 -0
  29. package/src/cli/startup-audit/formatter.mjs +248 -0
  30. package/src/cli/startup-audit/jsonc.mjs +601 -0
  31. package/src/cli/startup-audit/mcp-audit.mjs +735 -0
  32. package/src/cli/startup-audit/rules-hygiene.mjs +645 -0
  33. package/src/cli/startup-audit/telemetry-scan.mjs +975 -0
  34. package/src/cli/startup-audit.mjs +451 -2471
  35. package/src/clients/claude-code.mjs +41 -4
  36. package/src/config/catalog.json +295 -0
  37. package/src/config/effort.mjs +145 -0
  38. package/src/config/harness-quirks.mjs +340 -0
  39. package/src/config/loader.mjs +27 -2
  40. package/src/config/policy.mjs +81 -9
  41. package/src/config/pricing.mjs +247 -19
  42. package/src/config/semver.mjs +25 -0
  43. package/src/config/uncached-attribution.mjs +280 -41
  44. package/src/guards/compaction-baton.mjs +248 -0
  45. package/src/guards/loop-breaker.mjs +328 -47
  46. package/src/guards/model-switch-hook.mjs +126 -0
  47. package/src/guards/phase5-detectors.mjs +275 -21
  48. package/src/guards/post-tool-engine.mjs +333 -11
  49. package/src/guards/pre-tool-engine.mjs +607 -45
  50. package/src/guards/prefix-guard.mjs +609 -0
  51. package/src/guards/prompt-guard.mjs +309 -0
  52. package/src/guards/read-clamp.mjs +192 -8
  53. package/src/guards/session-hook.mjs +149 -7
  54. package/src/guards/shell-guard.mjs +56 -5
  55. package/src/guards/snooze.mjs +169 -5
  56. package/src/ipc/daemon.mjs +76 -0
  57. package/src/ipc/fast-client.mjs +165 -4
  58. package/src/ipc/protocol.mjs +16 -3
  59. package/src/storage/antigravity-parser.mjs +16 -2
  60. package/src/storage/file-lock.mjs +16 -3
  61. package/src/storage/jsonl-parser.mjs +133 -22
  62. package/src/storage/telemetry-metrics.mjs +254 -4
@@ -7,6 +7,12 @@
7
7
 
8
8
  import fs from 'node:fs';
9
9
  import { readLedgerSummary } from '../src/storage/ledger.mjs';
10
+ import { readBreakerStateSnapshot } from '../src/guards/loop-breaker.mjs';
11
+ import { normalizeCacheTokenAccounting } from '../src/config/uncached-attribution.mjs';
12
+ import { HARNESS_QUIRK_CONSTANTS } from '../src/config/harness-quirks.mjs';
13
+ import { resolveModelRateCard } from '../src/config/pricing.mjs';
14
+ import { isOpenAiModel } from '../src/guards/prefix-guard.mjs';
15
+ import { getWorkspacePauseStatus } from '../src/guards/snooze.mjs';
10
16
  import { isCliEntrypoint } from '../hooks/hook-io.mjs';
11
17
 
12
18
  function formatCompactTokens(tokens = 0) {
@@ -44,24 +50,81 @@ export function renderBurnoffStatusLine(inputJson = {}, options = {}) {
44
50
  const savedTokens = Number(summary?.totalSavedTokens || 0);
45
51
  const savedUsd = Number(summary?.totalSavedUSD || 0);
46
52
  const guardCount = Number(summary?.categories?.loopAndReadGuarded?.count || 0);
53
+ const savedSeg =
54
+ savedUsd >= 0.10
55
+ ? `7d saved: ${formatCompactTokens(savedTokens)} tok (${formatUsd(savedUsd)})`
56
+ : `7d saved: ${formatCompactTokens(savedTokens)} tok`;
47
57
 
48
- const parts = [
49
- `burnoff`,
50
- `saved: ${formatCompactTokens(savedTokens)} tok (${formatUsd(savedUsd)})`,
51
- `guards: ${guardCount}`
52
- ];
58
+ const parts = [`burnoff`, savedSeg, `guards: ${guardCount}`];
53
59
 
54
60
  const usedPct = Number(payload.context_window?.used_percentage);
55
61
  if (Number.isFinite(usedPct) && usedPct >= 0) {
56
62
  parts.push(`ctx: ${Math.round(usedPct)}%`);
57
63
  }
58
64
 
65
+ const telemetryOpt = options.telemetry || payload.telemetry || payload.metrics || {};
66
+ const modelId = String(
67
+ payload.model?.id || payload.model?.display_name || payload.model || telemetryOpt.model || ''
68
+ );
69
+ const usageObj =
70
+ payload.context_window?.current_usage ||
71
+ payload.usage ||
72
+ payload.token_usage ||
73
+ telemetryOpt.usage ||
74
+ null;
75
+ const acct = usageObj && typeof usageObj === 'object' ? normalizeCacheTokenAccounting(usageObj, modelId) : null;
76
+ if (acct && acct.hitRate !== null && acct.totalPrompt > 0) {
77
+ parts.push(`hit: ${Math.round(acct.hitRate * 100)}%`);
78
+ } else {
79
+ const rawHitPct = telemetryOpt.cacheHitPct ?? payload.cache_hit_pct ?? payload.cacheHitPct;
80
+ const hitPct = rawHitPct === null || rawHitPct === undefined ? NaN : Number(rawHitPct);
81
+ if (Number.isFinite(hitPct) && hitPct >= 0 && hitPct <= 100) {
82
+ parts.push(`hit: ${Math.round(hitPct)}%`);
83
+ }
84
+ }
85
+
86
+ const isGemini4 = /gemini[-\s]?4/i.test(modelId);
87
+ const isAntigravity =
88
+ String(options.client || payload.client || payload.harness || '').toLowerCase() === 'antigravity' ||
89
+ Boolean(payload.antigravity) ||
90
+ Number(payload.context_window?.binary_clamp_tokens) === HARNESS_QUIRK_CONSTANTS.ANTIGRAVITY_BINARY_CLAMP_TOKENS ||
91
+ (isGemini4 && acct?.accounting === 'gemini_inclusive');
92
+ const explicitUsagePromptTokens = Number(
93
+ usageObj?.promptTokens ?? usageObj?.prompt_tokens ?? usageObj?.totalPromptTokens ?? 0
94
+ );
95
+ const contextTokens =
96
+ Math.max(
97
+ Number(acct?.totalPrompt || 0),
98
+ Number.isFinite(explicitUsagePromptTokens) && explicitUsagePromptTokens > 0
99
+ ? explicitUsagePromptTokens
100
+ : 0
101
+ ) ||
102
+ Number(payload.context_window?.current_tokens ?? payload.context_window?.used_tokens ?? telemetryOpt.contextTokens ?? 0);
103
+ if (
104
+ isGemini4 &&
105
+ isAntigravity &&
106
+ Number.isFinite(contextTokens) &&
107
+ contextTokens >=
108
+ HARNESS_QUIRK_CONSTANTS.ANTIGRAVITY_BINARY_CLAMP_TOKENS * HARNESS_QUIRK_CONSTANTS.ANTIGRAVITY_CLAMP_WARN_PCT
109
+ ) {
110
+ parts.push(`clamp: ${Math.round(contextTokens / 1000)}k/256k`);
111
+ }
112
+
113
+ const cliffThreshold = modelId ? Number(resolveModelRateCard({ model: modelId, promptTokens: contextTokens })?.cliffThresholdTokens || 0) : 0;
114
+ if (
115
+ cliffThreshold > 0 &&
116
+ Number.isFinite(contextTokens) &&
117
+ contextTokens >= Math.floor(cliffThreshold * 0.90)
118
+ ) {
119
+ const crossedTag = contextTokens > cliffThreshold ? ' 2x!' : '!';
120
+ parts.push(`cliff: ${Math.round(contextTokens / 1000)}k/${Math.round(cliffThreshold / 1000)}k${crossedTag}`);
121
+ }
122
+
59
123
  const sessionCost = Number(payload.cost?.total_cost_usd);
60
124
  if (Number.isFinite(sessionCost) && sessionCost > 0) {
61
125
  parts.push(`sess: ${formatUsd(sessionCost)}`);
62
126
  }
63
127
 
64
- const telemetryOpt = options.telemetry || payload.telemetry || payload.metrics || {};
65
128
  const ttftMs = Number(
66
129
  telemetryOpt.medianTtftMs ?? telemetryOpt.ttftMs ?? telemetryOpt.ttft_ms ?? payload.ttft_ms ?? payload.ttftMs
67
130
  );
@@ -81,6 +144,75 @@ export function renderBurnoffStatusLine(inputJson = {}, options = {}) {
81
144
  parts.push(`${tokensPerSec.toFixed(1)} tok/s`);
82
145
  }
83
146
 
147
+ const nowMs = Number.isFinite(Number(options.nowMs)) ? Number(options.nowMs) : Date.now();
148
+ let snap = null;
149
+ const sessionId = String(payload.session_id || payload.sessionId || options.sessionId || '').trim();
150
+ if (sessionId) {
151
+ try {
152
+ snap = readBreakerStateSnapshot(sessionId, { cwd, homeDir, client: options.client });
153
+ } catch {
154
+ snap = null; // ignore: missing/unreadable breaker snapshot omits runtime badges
155
+ }
156
+ if (snap && typeof snap === 'object') {
157
+ const lastTurnAtMs = Number(snap.lastTurnAtMs || 0);
158
+ if (Number.isFinite(lastTurnAtMs) && lastTurnAtMs > 0) {
159
+ const ttlTier = String(
160
+ options.cacheTtlTier || payload.cacheTtlTier || snap.cacheTtlTier || '5m'
161
+ ).toLowerCase();
162
+ const effectiveTtlMs = ttlTier === '1h' ? 60 * 60 * 1000 : 5 * 60 * 1000;
163
+ const remMs = effectiveTtlMs - Math.max(0, nowMs - lastTurnAtMs);
164
+ if (remMs <= 0) {
165
+ parts.push('ttl: COLD');
166
+ } else {
167
+ const totalSec = Math.ceil(remMs / 1000);
168
+ const mins = Math.floor(totalSec / 60);
169
+ const secs = String(totalSec % 60).padStart(2, '0');
170
+ parts.push(`ttl: ${mins}m${secs}s`);
171
+ }
172
+ }
173
+ if (Number(snap.mcpCallsTotal || 0) === 0 && Number(snap.nonMcpTurnCount || 0) >= 5) {
174
+ parts.push('mcp: idle');
175
+ }
176
+ if (isOpenAiModel(modelId) && Array.isArray(snap.recentOpenAiInputEvents)) {
177
+ const rollingTpm = snap.recentOpenAiInputEvents
178
+ .filter((e) => e && Number.isFinite(Number(e.ts)) && nowMs - Number(e.ts) <= 60_000)
179
+ .reduce((sum, e) => sum + Math.max(0, Number(e.tokens || 0)), 0);
180
+ if (rollingTpm >= 150_000) {
181
+ parts.push(`tpm: ${Math.round(rollingTpm / 1000)}k/m!`);
182
+ }
183
+ }
184
+ const totalInTok = Number(payload.context_window?.total_input_tokens ?? contextTokens ?? 0);
185
+ if (
186
+ Number(snap.lastGitCommitAtMs || 0) > 0 &&
187
+ ((Number.isFinite(usedPct) && usedPct >= 20) || totalInTok >= 25_000)
188
+ ) {
189
+ parts.push('hint: /clear');
190
+ }
191
+ }
192
+ }
193
+
194
+ const thinkTok = Number(
195
+ usageObj?.thinking_tokens ??
196
+ usageObj?.thinkingTokens ??
197
+ usageObj?.reasoning_tokens ??
198
+ usageObj?.reasoningTokens ??
199
+ telemetryOpt.thinkingTokens ??
200
+ snap?.lastThinkingTokens ??
201
+ 0
202
+ );
203
+ if (Number.isFinite(thinkTok) && thinkTok >= 4000) {
204
+ parts.push(`think: ${formatCompactTokens(thinkTok)}`);
205
+ }
206
+
207
+ try {
208
+ const pause = getWorkspacePauseStatus({ nowMs }, { cwd, homeDir, client: options.client });
209
+ if (pause?.active && pause.remainingMs > 0) {
210
+ parts.push(`PAUSED ${Math.max(1, Math.ceil(pause.remainingMs / 60000))}m`);
211
+ }
212
+ } catch {
213
+ // ignore: unreadable pause state omits PAUSED badge
214
+ }
215
+
84
216
  return parts.join(' | ');
85
217
  }
86
218
 
@@ -11,13 +11,17 @@ 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,
17
18
  maxPrTokens: 1_500_000,
18
19
  minCacheHitPct: 50,
19
20
  maxWasteRatioPct: 35,
21
+ wasteRatioBasis: 'actionable',
20
22
  maxRing0Violations: 0,
23
+ maxPrQuotaUnits: null,
24
+ quotaGateMode: 'warn',
21
25
  mode: 'enforce',
22
26
  failOnMissingTranscripts: false
23
27
  });
@@ -67,9 +71,26 @@ export function loadCiBudgetPolicy(cwd, overrides = {}) {
67
71
  const r = toFiniteNumber(layer.maxWasteRatio);
68
72
  merged.maxWasteRatioPct = r <= 1 ? Math.round(Math.max(0, r) * 100) : Math.round(r);
69
73
  }
74
+ if (layer.wasteRatioBasis !== undefined && layer.wasteRatioBasis !== null) {
75
+ const basis = String(layer.wasteRatioBasis).trim().toLowerCase();
76
+ if (basis === 'gross' || basis === 'actionable') {
77
+ merged.wasteRatioBasis = basis;
78
+ }
79
+ }
70
80
  if (toFiniteNumber(layer.maxRing0Violations) !== null) {
71
81
  merged.maxRing0Violations = toFiniteNumber(layer.maxRing0Violations);
72
82
  }
83
+ if (layer.maxPrQuotaUnits === null) {
84
+ merged.maxPrQuotaUnits = null;
85
+ } else if (toFiniteNumber(layer.maxPrQuotaUnits) !== null) {
86
+ merged.maxPrQuotaUnits = toFiniteNumber(layer.maxPrQuotaUnits);
87
+ }
88
+ if (layer.quotaGateMode !== undefined && layer.quotaGateMode !== null) {
89
+ const qm = String(layer.quotaGateMode).trim().toLowerCase();
90
+ if (qm === 'warn' || qm === 'fail') {
91
+ merged.quotaGateMode = qm;
92
+ }
93
+ }
73
94
  if (typeof layer.failOnMissingTranscripts === 'boolean') {
74
95
  merged.failOnMissingTranscripts = layer.failOnMissingTranscripts;
75
96
  }
@@ -102,6 +123,9 @@ export function loadCiBudgetPolicy(cwd, overrides = {}) {
102
123
  if (merged.mode !== 'advisory' && merged.mode !== 'enforce') {
103
124
  merged.mode = 'enforce';
104
125
  }
126
+ if (merged.quotaGateMode !== 'warn' && merged.quotaGateMode !== 'fail') {
127
+ merged.quotaGateMode = 'warn';
128
+ }
105
129
  return merged;
106
130
  }
107
131
 
@@ -126,6 +150,22 @@ export function evaluateCiBudgetGate(options = {}) {
126
150
  const policy = loadCiBudgetPolicy(cwd, policyOverrides);
127
151
 
128
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
+ }
129
169
  if (!attribution && options.inputPath) {
130
170
  const absIn = path.resolve(options.inputPath);
131
171
  if (!fs.existsSync(absIn)) {
@@ -137,7 +177,25 @@ export function evaluateCiBudgetGate(options = {}) {
137
177
  };
138
178
  }
139
179
  try {
140
- 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
+ }
141
199
  } catch (err) {
142
200
  return {
143
201
  ok: false,
@@ -149,7 +207,7 @@ export function evaluateCiBudgetGate(options = {}) {
149
207
  }
150
208
 
151
209
  if (!attribution) {
152
- const attrRes = buildPrCostAttribution({ ...options, cwd });
210
+ const attrRes = buildPrCostAttribution({ ...options, cwd, wasteRatioBasis: policy.wasteRatioBasis });
153
211
  if (!attrRes.ok) {
154
212
  return {
155
213
  ok: false,
@@ -177,25 +235,53 @@ export function evaluateCiBudgetGate(options = {}) {
177
235
  reconciledCostUsd !== null ? Math.max(estimatedCostUsd, reconciledCostUsd) : estimatedCostUsd;
178
236
  const totalTokens = Number(summary.totalTokens || 0);
179
237
  const cacheHitPct = Number(summary.cacheHitPct || 0);
180
- const wasteRatioPct = Number(summary.wasteRatioPct || 0);
238
+ const grossWasteTokens = Number(summary.grossWasteTokens ?? summary.estimatedWasteTokens ?? 0);
239
+ const grossWasteRatioPct = Number(summary.grossWasteRatioPct ?? summary.wasteRatioPct ?? 0);
240
+ const excludedUpstreamTokens = Number(summary.excludedUpstreamTokens ?? 0);
241
+ const appendFloorTokens = Number(summary.appendFloorTokens ?? 0);
242
+ const upstreamEvictionTokens = Number(summary.upstreamEvictionTokens ?? 0);
243
+ const evictionByPattern =
244
+ summary.evictionByPattern && typeof summary.evictionByPattern === 'object' ? summary.evictionByPattern : {};
245
+ const actionableWasteTokens = Number(summary.actionableWasteTokens ?? summary.estimatedWasteTokens ?? 0);
246
+ const actionableWasteRatioPct = Number(summary.actionableWasteRatioPct ?? summary.wasteRatioPct ?? 0);
247
+ const wasteRatioPct =
248
+ policy.wasteRatioBasis === 'gross' ? grossWasteRatioPct : actionableWasteRatioPct;
181
249
  const ring0Violations = Number(summary.ring0Violations || 0);
250
+ const estimatedQuotaUnits = Number(summary.estimatedQuotaUnits ?? 0);
251
+ const quotaWeightsDisclosure =
252
+ summary.quotaWeightsDisclosure || 'est.; weights: Carbon/Argon 3.0x, sdk-cli 1.8x heuristic, baseline 1.0x';
253
+ const quotaBreakdown =
254
+ summary.quotaBreakdown && typeof summary.quotaBreakdown === 'object' ? summary.quotaBreakdown : null;
182
255
  const sessionCount =
183
256
  typeof summary.sessionCount === 'number' && Number.isFinite(summary.sessionCount)
184
257
  ? summary.sessionCount
185
258
  : null;
186
- const missingTranscripts =
187
- reconciledCostUsd === null &&
259
+ const missingUsageTranscripts =
188
260
  totalTokens === 0 &&
189
261
  totalInputTokens === 0 &&
190
262
  totalCacheReadTokens === 0 &&
191
263
  (sessionCount === null || sessionCount === 0);
264
+ const missingTranscripts =
265
+ reconciledCostUsd === null &&
266
+ missingUsageTranscripts;
192
267
 
193
268
  const notices = [];
269
+ const seenNotices = new Set();
270
+ if (Array.isArray(attribution.notices)) {
271
+ for (const n of attribution.notices) {
272
+ if (!n || !n.code) continue;
273
+ const key = `${n.code}:${n.sessionId || ''}`;
274
+ if (seenNotices.has(key)) continue;
275
+ seenNotices.add(key);
276
+ notices.push(n);
277
+ }
278
+ }
194
279
  const violations = [];
280
+ let quotaWarningTriggered = false;
195
281
 
196
282
  if (missingTranscripts) {
197
283
  const noticeMsg =
198
- '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.';
199
285
  notices.push({ code: 'MISSING_TRANSCRIPTS', message: noticeMsg });
200
286
  if (policy.failOnMissingTranscripts === true) {
201
287
  violations.push({
@@ -207,6 +293,46 @@ export function evaluateCiBudgetGate(options = {}) {
207
293
  }
208
294
  }
209
295
 
296
+ if (policy.maxPrQuotaUnits !== null) {
297
+ if (missingUsageTranscripts) {
298
+ const quotaMissingMsg =
299
+ 'No session usage transcripts matched this PR window; maxPrQuotaUnits cannot pass silently on 0 Q-units.';
300
+ if (!notices.some((n) => n.code === 'MISSING_TRANSCRIPTS')) {
301
+ notices.push({ code: 'MISSING_TRANSCRIPTS', message: quotaMissingMsg });
302
+ }
303
+ if (policy.quotaGateMode === 'fail') {
304
+ if (!violations.some((v) => v.ruleId === 'MISSING_TRANSCRIPTS')) {
305
+ violations.push({
306
+ ruleId: 'MISSING_TRANSCRIPTS',
307
+ actual: 0,
308
+ limit: 1,
309
+ message: quotaMissingMsg
310
+ });
311
+ }
312
+ } else {
313
+ quotaWarningTriggered = true;
314
+ }
315
+ } else if (estimatedQuotaUnits > policy.maxPrQuotaUnits) {
316
+ const quotaMsg = `Estimated Quota Burn: ${estimatedQuotaUnits.toFixed(2)} Q-units (${quotaWeightsDisclosure}) exceeds limit ${policy.maxPrQuotaUnits.toFixed(2)} Q-units`;
317
+ if (policy.quotaGateMode === 'fail') {
318
+ violations.push({
319
+ ruleId: 'MAX_PR_QUOTA_UNITS',
320
+ actual: estimatedQuotaUnits,
321
+ limit: policy.maxPrQuotaUnits,
322
+ message: quotaMsg
323
+ });
324
+ } else {
325
+ notices.push({
326
+ code: 'MAX_PR_QUOTA_UNITS',
327
+ actual: estimatedQuotaUnits,
328
+ limit: policy.maxPrQuotaUnits,
329
+ message: quotaMsg
330
+ });
331
+ quotaWarningTriggered = true;
332
+ }
333
+ }
334
+ }
335
+
210
336
  if (effectiveCostUsd > policy.maxPrCostUsd) {
211
337
  violations.push({
212
338
  ruleId: 'MAX_PR_COST_USD',
@@ -236,7 +362,7 @@ export function evaluateCiBudgetGate(options = {}) {
236
362
  ruleId: 'MAX_WASTE_RATIO_PCT',
237
363
  actual: wasteRatioPct,
238
364
  limit: policy.maxWasteRatioPct,
239
- message: `Preventable waste ratio ${wasteRatioPct}% exceeds limit ${policy.maxWasteRatioPct}%`
365
+ message: `Preventable waste ratio (${policy.wasteRatioBasis}) ${wasteRatioPct}% exceeds limit ${policy.maxWasteRatioPct}%`
240
366
  });
241
367
  }
242
368
  if (ring0Violations > policy.maxRing0Violations) {
@@ -258,16 +384,21 @@ export function evaluateCiBudgetGate(options = {}) {
258
384
  verdict = 'FAIL';
259
385
  exitCode = 1;
260
386
  }
387
+ } else if (quotaWarningTriggered) {
388
+ verdict = 'WARN';
389
+ exitCode = 0;
261
390
  }
262
391
 
263
392
  const annotationLevel = verdict === 'FAIL' ? '::error' : '::warning';
264
393
  const annotations = [
265
394
  ...violations.map((v) => `${annotationLevel} title=Burnoff CI Budget Gate (${v.ruleId})::${v.message}`),
266
- ...(verdict !== 'FAIL'
267
- ? notices
268
- .filter((n) => !violations.some((v) => v.ruleId === n.code))
269
- .map((n) => `::warning title=Burnoff CI Budget Gate (${n.code})::${n.message}`)
270
- : [])
395
+ ...notices
396
+ .filter(
397
+ (n) =>
398
+ !violations.some((v) => v.ruleId === n.code) &&
399
+ (verdict !== 'FAIL' || n.code === 'MAX_PR_QUOTA_UNITS')
400
+ )
401
+ .map((n) => `::warning title=Burnoff CI Budget Gate (${n.code})::${n.message}`)
271
402
  ];
272
403
 
273
404
  return {
@@ -280,8 +411,20 @@ export function evaluateCiBudgetGate(options = {}) {
280
411
  reconciledCostUsd,
281
412
  effectiveCostUsd,
282
413
  attributionVariancePct,
414
+ estimatedQuotaUnits,
415
+ quotaWeightsDisclosure,
416
+ quotaBreakdown,
283
417
  totalTokens,
284
418
  cacheHitPct,
419
+ wasteRatioBasis: policy.wasteRatioBasis,
420
+ grossWasteTokens,
421
+ grossWasteRatioPct,
422
+ excludedUpstreamTokens,
423
+ appendFloorTokens,
424
+ upstreamEvictionTokens,
425
+ evictionByPattern,
426
+ actionableWasteTokens,
427
+ actionableWasteRatioPct,
285
428
  wasteRatioPct,
286
429
  ring0Violations,
287
430
  totalInputTokens,
@@ -308,6 +451,7 @@ export function formatCiGateMarkdown(result = {}) {
308
451
  ? `$${m.reconciledCostUsd.toFixed(4)} (reconciled)`
309
452
  : `$${Number(m.estimatedCostUsd || 0).toFixed(4)}`;
310
453
 
454
+ const basis = p.wasteRatioBasis || m.wasteRatioBasis || 'actionable';
311
455
  const lines = [
312
456
  `### Burnoff CI / PR Token-Budget Gate: **${result.verdict || 'UNKNOWN'}** (\`mode: ${p.mode}\`)`,
313
457
  '',
@@ -316,10 +460,52 @@ export function formatCiGateMarkdown(result = {}) {
316
460
  `| \`MAX_PR_COST_USD\` | \`${costDisplay}\` | \`<=$${Number(p.maxPrCostUsd).toFixed(2)}\` | **${statusTag('MAX_PR_COST_USD')}** |`,
317
461
  `| \`MAX_PR_TOKENS\` | \`${Number(m.totalTokens || 0).toLocaleString('en-US')}\` | \`<=${Number(p.maxPrTokens).toLocaleString('en-US')}\` | **${statusTag('MAX_PR_TOKENS')}** |`,
318
462
  `| \`MIN_CACHE_HIT_PCT\` | \`${m.cacheHitPct ?? 0}%\` | \`>=${p.minCacheHitPct}%\` | **${statusTag('MIN_CACHE_HIT_PCT')}** |`,
319
- `| \`MAX_WASTE_RATIO_PCT\` | \`${m.wasteRatioPct ?? 0}%\` | \`<=${p.maxWasteRatioPct}%\` | **${statusTag('MAX_WASTE_RATIO_PCT')}** |`,
463
+ `| \`MAX_WASTE_RATIO_PCT\` | \`${m.wasteRatioPct ?? 0}%\` (\`${basis}\`) | \`<=${p.maxWasteRatioPct}%\` | **${statusTag('MAX_WASTE_RATIO_PCT')}** |`,
320
464
  `| \`MAX_RING0_VIOLATIONS\` | \`${m.ring0Violations ?? 0}\` | \`<=${p.maxRing0Violations}\` | **${statusTag('MAX_RING0_VIOLATIONS')}** |`
321
465
  ];
322
466
 
467
+ if (p.maxPrQuotaUnits !== null && p.maxPrQuotaUnits !== undefined) {
468
+ const quotaStatus = violatedSet.has('MAX_PR_QUOTA_UNITS')
469
+ ? result.verdict
470
+ : violatedSet.has('MISSING_TRANSCRIPTS')
471
+ ? result.verdict
472
+ : (result.notices || []).some(
473
+ (n) => n.code === 'MAX_PR_QUOTA_UNITS' || n.code === 'MISSING_TRANSCRIPTS'
474
+ )
475
+ ? 'WARN'
476
+ : 'PASS';
477
+ lines.push(
478
+ `| \`MAX_PR_QUOTA_UNITS\` | \`${Number(m.estimatedQuotaUnits || 0).toFixed(2)} Q-units\` (est.) | \`<=${Number(p.maxPrQuotaUnits).toFixed(2)} Q-units\` (\`mode: ${p.quotaGateMode || 'warn'}\`) | **${quotaStatus}** |`
479
+ );
480
+ }
481
+
482
+ lines.push(
483
+ '',
484
+ `Estimated Quota Burn: ${Number(m.estimatedQuotaUnits || 0).toFixed(2)} Q-units (${m.quotaWeightsDisclosure || 'est.; weights: Carbon/Argon 3.0x, sdk-cli 1.8x heuristic, baseline 1.0x'})`
485
+ );
486
+
487
+ if (typeof m.grossWasteTokens === 'number' || typeof m.actionableWasteTokens === 'number') {
488
+ const patternEntries = m.evictionByPattern && typeof m.evictionByPattern === 'object' ? Object.entries(m.evictionByPattern) : [];
489
+ const upstreamNotes = [];
490
+ if (Number(m.appendFloorTokens || 0) > 0) {
491
+ upstreamNotes.push(`append_floor: ${Number(m.appendFloorTokens).toLocaleString('en-US')}`);
492
+ }
493
+ if (patternEntries.length > 0) {
494
+ upstreamNotes.push(patternEntries.map(([k, v]) => `${k}: ${v}`).join(', '));
495
+ }
496
+ const upstreamDetail = upstreamNotes.length > 0 ? ` (${upstreamNotes.join('; ')})` : '';
497
+ lines.push(
498
+ '',
499
+ '#### Waste Attribution Breakdown',
500
+ '',
501
+ '| Basis | Tokens | Share of Total |',
502
+ '| :--- | :---: | :---: |',
503
+ `| **Gross Waste** | \`${Number(m.grossWasteTokens || 0).toLocaleString('en-US')}\` | \`${m.grossWasteRatioPct ?? m.wasteRatioPct ?? 0}%\` |`,
504
+ `| **Excluded (Attributed to Upstream)** | \`${Number(m.excludedUpstreamTokens || 0).toLocaleString('en-US')}\`${upstreamDetail} | \`-\` |`,
505
+ `| **Actionable Waste** | \`${Number(m.actionableWasteTokens || 0).toLocaleString('en-US')}\` | \`${m.actionableWasteRatioPct ?? m.wasteRatioPct ?? 0}%\` |`
506
+ );
507
+ }
508
+
323
509
  if (Array.isArray(result.notices) && result.notices.length > 0) {
324
510
  lines.push('', '#### Notices', '');
325
511
  for (const n of result.notices) {