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
@@ -0,0 +1,609 @@
1
+ /**
2
+ * @file src/guards/prefix-guard.mjs
3
+ * Shared runtime prompt-prefix integrity guard (`BO-MOD-02` & `BO-PFX-01`)
4
+ * invoked by `UserPromptSubmit` and `PreToolUse` hooks.
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { resolveModelRateCard } from '../config/pricing.mjs';
10
+ import { effortChangePreservesCache, resolveEffortLevel } from '../config/effort.mjs';
11
+
12
+ export function isOpenAiModel(modelId = '') {
13
+ return /^(?:openai\/)?(?:gpt-|o[134](?:-|$)|codex)/i.test(String(modelId || '').trim());
14
+ }
15
+
16
+ function hashText(str = '') {
17
+ let h = 2166136261;
18
+ for (let i = 0; i < str.length; i += 1) {
19
+ h ^= str.charCodeAt(i);
20
+ h = Math.imul(h, 16777619);
21
+ }
22
+ return (h >>> 0).toString(16);
23
+ }
24
+
25
+ function readMcpSection(filePath, cwd) {
26
+ try {
27
+ if (!filePath || !fs.existsSync(filePath)) return null;
28
+ const raw = fs.readFileSync(filePath, 'utf8');
29
+ const parsed = JSON.parse(raw);
30
+ const keys = new Set();
31
+ if (parsed?.mcpServers && typeof parsed.mcpServers === 'object') {
32
+ for (const k of Object.keys(parsed.mcpServers)) {
33
+ if (k) keys.add(k);
34
+ }
35
+ }
36
+ if (cwd && parsed?.projects?.[cwd]?.mcpServers && typeof parsed.projects[cwd].mcpServers === 'object') {
37
+ for (const k of Object.keys(parsed.projects[cwd].mcpServers)) {
38
+ if (k) keys.add(k);
39
+ }
40
+ }
41
+ return {
42
+ len: raw.length,
43
+ hash: hashText(raw),
44
+ keys: [...keys].sort()
45
+ };
46
+ } catch (err) {
47
+ void err; // ignore: unreadable or malformed optional MCP config
48
+ return null;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Computes a deterministic fingerprint of `.mcp.json` (cwd) and `~/.claude.json` (homeDir)
54
+ * so mid-session MCP server edits/reloads can be detected across turns.
55
+ */
56
+ export function computeMcpConfigFingerprint(cwd = '', homeDir = '') {
57
+ const parts = [];
58
+ if (cwd) {
59
+ const cwdSection = readMcpSection(path.join(cwd, '.mcp.json'), cwd);
60
+ if (cwdSection) {
61
+ parts.push(`cwd:${cwdSection.len}:${cwdSection.hash}:${cwdSection.keys.join(',')}`);
62
+ }
63
+ }
64
+ if (homeDir) {
65
+ const homeSection = readMcpSection(path.join(homeDir, '.claude.json'), cwd);
66
+ if (homeSection && homeSection.keys.length > 0) {
67
+ parts.push(`home:${homeSection.len}:${homeSection.hash}:${homeSection.keys.join(',')}`);
68
+ }
69
+ }
70
+ return parts.join('|');
71
+ }
72
+
73
+ /**
74
+ * Extracts normalized cache-read, cache-creation, uncached, prompt-token, and message-count
75
+ * metrics from Anthropic, Gemini, or synthetic hook usage payloads.
76
+ */
77
+ export function extractUsageMetrics(event = {}) {
78
+ const u =
79
+ (event.usage && typeof event.usage === 'object' ? event.usage : null) ||
80
+ (event.context_window?.current_usage && typeof event.context_window.current_usage === 'object'
81
+ ? event.context_window.current_usage
82
+ : null) ||
83
+ event ||
84
+ {};
85
+
86
+ const cacheRead = Math.max(
87
+ 0,
88
+ Number(
89
+ u.cache_read_input_tokens ??
90
+ u.cachedTokens ??
91
+ u.cacheReadTokens ??
92
+ u.cached_tokens ??
93
+ 0
94
+ ) || 0
95
+ );
96
+
97
+ const explicitCreation =
98
+ u.cache_creation_input_tokens ?? u.cacheCreationTokens ?? u.cache_creation_tokens;
99
+ const splitCreation =
100
+ Number(u.cacheWrite5mTokens ?? u.cache_write_5m_tokens ?? 0) +
101
+ Number(u.cacheWrite1hTokens ?? u.cache_write_1h_tokens ?? 0);
102
+ const cacheCreation = Math.max(
103
+ 0,
104
+ explicitCreation !== undefined && explicitCreation !== null
105
+ ? Number(explicitCreation) || 0
106
+ : splitCreation || 0
107
+ );
108
+
109
+ const uncached = Math.max(
110
+ 0,
111
+ Number(u.input_tokens ?? u.uncachedTokens ?? u.uncached_tokens ?? 0) || 0
112
+ );
113
+
114
+ const rawPrompt =
115
+ u.promptTokens ??
116
+ u.prompt_tokens ??
117
+ event.promptTokens ??
118
+ event.context_window?.total_input_tokens;
119
+ const promptTokens =
120
+ rawPrompt !== undefined && rawPrompt !== null && Number.isFinite(Number(rawPrompt))
121
+ ? Math.max(0, Number(rawPrompt))
122
+ : cacheRead + cacheCreation + uncached;
123
+
124
+ let messageCount = null;
125
+ if (Array.isArray(event.messages)) {
126
+ messageCount = event.messages.length;
127
+ } else {
128
+ const rawMsgCount = event.messageCount ?? event.message_count;
129
+ if (rawMsgCount !== undefined && rawMsgCount !== null && Number.isFinite(Number(rawMsgCount))) {
130
+ messageCount = Math.max(0, Math.floor(Number(rawMsgCount)));
131
+ }
132
+ }
133
+
134
+ const thinkingTokens = Math.max(
135
+ 0,
136
+ Number(
137
+ u.thinking_tokens ??
138
+ u.thinkingTokens ??
139
+ u.output_tokens_details?.thinking_tokens ??
140
+ u.output_tokens_details?.reasoning_tokens ??
141
+ u.completion_tokens_details?.reasoning_tokens ??
142
+ u.reasoning_tokens ??
143
+ u.reasoningTokens ??
144
+ 0
145
+ ) || 0
146
+ );
147
+ const thinkingTokensEstimated = Boolean(
148
+ u.thinkingTokensEstimated ?? event.thinkingTokensEstimated ?? false
149
+ );
150
+ const outputTokens = Math.max(
151
+ 0,
152
+ Number(u.output_tokens ?? u.outputTokens ?? u.completion_tokens ?? 0) || 0
153
+ );
154
+
155
+ return {
156
+ cacheRead,
157
+ cacheCreation,
158
+ uncached,
159
+ promptTokens,
160
+ thinkingTokens,
161
+ thinkingTokensEstimated,
162
+ outputTokens,
163
+ messageCount
164
+ };
165
+ }
166
+
167
+ function resolveModel(event = {}, explicitModel = '') {
168
+ if (explicitModel) return String(explicitModel).trim();
169
+ if (typeof event.model === 'string') return event.model.trim();
170
+ if (event.model && typeof event.model === 'object') {
171
+ return String(event.model.id || event.model.name || '').trim();
172
+ }
173
+ return '';
174
+ }
175
+
176
+ function resolveEffort(event = {}, explicitEffort = '', env = undefined) {
177
+ return resolveEffortLevel(event, { explicitEffort, env });
178
+ }
179
+
180
+ /**
181
+ * Evaluates whether prompt tokens are approaching or crossing the active model's
182
+ * global long-context pricing cliff (`BO-CLF-01`, default 90% warn ratio).
183
+ */
184
+ export function evaluatePreCliffAlarm({
185
+ model = '',
186
+ promptTokens = 0,
187
+ policy = null,
188
+ prior = null
189
+ } = {}) {
190
+ const prevStage = prior?.lastCliffStage || null;
191
+ if (!model || policy?.guards?.preCliffEnabled === false || !(promptTokens > 0)) {
192
+ return { finding: null, nextCliffStage: prevStage };
193
+ }
194
+ const card = resolveModelRateCard({ model, promptTokens });
195
+ const cliff = Number(card?.cliffThresholdTokens || 0);
196
+ if (!cliff || !Number.isFinite(cliff)) {
197
+ return { finding: null, nextCliffStage: prevStage };
198
+ }
199
+
200
+ const rawRatio = Number(policy?.guards?.preCliffWarnRatio ?? 0.90);
201
+ const warnRatio = Number.isFinite(rawRatio) && rawRatio > 0 && rawRatio < 1 ? rawRatio : 0.90;
202
+ const warnAt = Math.floor(cliff * warnRatio);
203
+
204
+ if (promptTokens > cliff) {
205
+ if (prevStage !== 'crossed') {
206
+ return {
207
+ nextCliffStage: 'crossed',
208
+ finding: {
209
+ detectorId: 'BO-CLF-01',
210
+ subType: 'CLIFF_CROSSED',
211
+ reason:
212
+ `[Burnoff BO-CLF-01 Long-Context Cliff Crossed] Context (${promptTokens.toLocaleString('en-US')} tok) crossed ` +
213
+ `${card.modelId}'s ${cliff.toLocaleString('en-US')}-token pricing cliff, doubling rates across the full request. ` +
214
+ 'Run /compact or /handoff + /clear before continuing.'
215
+ }
216
+ };
217
+ }
218
+ return { finding: null, nextCliffStage: 'crossed' };
219
+ }
220
+
221
+ if (promptTokens >= warnAt) {
222
+ if (prevStage !== 'warn' && prevStage !== 'crossed') {
223
+ const headroom = Math.max(0, cliff - promptTokens);
224
+ return {
225
+ nextCliffStage: 'warn',
226
+ finding: {
227
+ detectorId: 'BO-CLF-01',
228
+ subType: 'PRE_CLIFF_WARNING',
229
+ reason:
230
+ `[Burnoff BO-CLF-01 Pre-Cliff Alarm] Context at ${promptTokens.toLocaleString('en-US')} tok ` +
231
+ `(${headroom.toLocaleString('en-US')} tok below ${card.modelId}'s ${cliff.toLocaleString('en-US')}-token 2x pricing cliff). ` +
232
+ 'Consider /compact or /handoff + /clear soon to avoid global rate escalation.'
233
+ }
234
+ };
235
+ }
236
+ return { finding: null, nextCliffStage: prevStage };
237
+ }
238
+
239
+ if (promptTokens < Math.floor(warnAt * 0.8)) {
240
+ return { finding: null, nextCliffStage: null };
241
+ }
242
+ return { finding: null, nextCliffStage: prevStage };
243
+ }
244
+
245
+ /**
246
+ * Evaluates mid-session prompt-prefix integrity across MCP/toolset mutations,
247
+ * model/effort switches (including A->B->A router ping-pong), history slicing/truncation,
248
+ * long-context pricing cliffs (`BO-CLF-01`), OpenAI TPM velocity (`BO-TPM-01`), and thinking spend (`BO-THK-01`).
249
+ */
250
+ export function evaluatePrefixIntegrity({
251
+ event = {},
252
+ prior = null,
253
+ policy = null,
254
+ cwd = '',
255
+ homeDir = '',
256
+ effectiveTtlMs = 300_000,
257
+ nowMs = Date.now(),
258
+ explicitModel = '',
259
+ explicitEffort = '',
260
+ env = undefined
261
+ } = {}) {
262
+ const mcpFingerprint = computeMcpConfigFingerprint(cwd, homeDir);
263
+ const toolsetHash = String(event.toolsetHash || event.toolset_hash || '').trim();
264
+ const incomingModel = resolveModel(event, explicitModel);
265
+ const incomingEffort = resolveEffort(event, explicitEffort, env);
266
+ const effectiveModel = incomingModel || String(prior?.lastModel || '');
267
+ const effectiveEffort = incomingEffort || String(prior?.lastEffort || '');
268
+ const incomingStreamKey =
269
+ incomingModel || incomingEffort ? `${effectiveModel}|${effectiveEffort}` : '';
270
+
271
+ const hasPriorTurn = Boolean(
272
+ prior &&
273
+ (Number(prior.promptCount || 0) >= 1 ||
274
+ Number(prior.lastTurnAtMs || 0) > 0 ||
275
+ prior.lastModel ||
276
+ prior.lastMcpFingerprint ||
277
+ Number(prior.lastPromptTokens || 0) > 0)
278
+ );
279
+
280
+ const explicitIdleMs = Number(event.idle_ms ?? event.idleMs);
281
+ const elapsedMs = Number.isFinite(explicitIdleMs)
282
+ ? Math.max(0, explicitIdleMs)
283
+ : prior?.lastTurnAtMs
284
+ ? Math.max(0, nowMs - Number(prior.lastTurnAtMs))
285
+ : 0;
286
+ const isIdleExpired = elapsedMs > effectiveTtlMs;
287
+
288
+ const findings = [];
289
+ let toolsetChanged = false;
290
+ let modelChanged = false;
291
+ let effortChanged = false;
292
+ let effortSwitchPreservesCache = false;
293
+
294
+ // 1. MCP / Toolset mid-session change (BO-MOD-02)
295
+ if (hasPriorTurn) {
296
+ toolsetChanged = Boolean(
297
+ event.hadToolsetChange === true ||
298
+ event.hadMcpReload === true ||
299
+ (toolsetHash && prior.lastToolsetHash && toolsetHash !== prior.lastToolsetHash) ||
300
+ (mcpFingerprint && prior.lastMcpFingerprint && mcpFingerprint !== prior.lastMcpFingerprint)
301
+ );
302
+ if (toolsetChanged) {
303
+ findings.push({
304
+ detectorId: 'BO-MOD-02',
305
+ subType: 'MID_SESSION_TOOLSET_CHANGE',
306
+ reason:
307
+ '[Burnoff BO-MOD-02 Mid-Session Prefix Invalidation] MCP/toolset configuration changed mid-session, ' +
308
+ 'invalidating the cached prompt prefix. Queue toolset changes between sessions or after /compact.'
309
+ });
310
+ }
311
+ }
312
+
313
+ // 2. Model/Effort switch & A->B->A Router Ping-Pong (BO-MOD-02)
314
+ const prevRecentModels = Array.isArray(prior?.recentModels) ? [...prior.recentModels] : [];
315
+ if (hasPriorTurn) {
316
+ modelChanged = Boolean(incomingModel && prior.lastModel && incomingModel !== prior.lastModel);
317
+ effortChanged = Boolean(incomingEffort && prior.lastEffort && incomingEffort !== prior.lastEffort);
318
+ // 5.5-generation / Fable 5.1+ models on first-party API keep the cache warm across effort-only
319
+ // changes, so those must not raise a cache-invalidation warning (state is still updated).
320
+ const effortOnlyChange = effortChanged && !modelChanged;
321
+ effortSwitchPreservesCache =
322
+ effortOnlyChange && effortChangePreservesCache({ model: effectiveModel, env });
323
+ if (modelChanged || (effortChanged && !effortSwitchPreservesCache)) {
324
+ const priorNonAdjacent = prevRecentModels.length > 1 ? prevRecentModels.slice(0, -1) : [];
325
+ const isPingPong = Boolean(
326
+ incomingStreamKey && priorNonAdjacent.some((entry) => entry?.streamKey === incomingStreamKey)
327
+ );
328
+ const fromLabel = `${prior.lastModel || 'current'}/${prior.lastEffort || 'default'}`;
329
+ const toLabel = `${effectiveModel || 'current'}/${effectiveEffort || 'default'}`;
330
+ if (isPingPong) {
331
+ findings.push({
332
+ detectorId: 'BO-MOD-02',
333
+ subType: 'MODEL_ROUTER_PING_PONG',
334
+ reason:
335
+ `[Burnoff BO-MOD-02 Model Router Ping-Pong] Mid-thread A->B->A model/effort detour (${fromLabel} -> ${toLabel}) ` +
336
+ 'invalidated cached prefix. Use a subagent for side questions instead of switching models mid-thread.'
337
+ });
338
+ } else {
339
+ findings.push({
340
+ detectorId: 'BO-MOD-02',
341
+ subType: 'MID_SESSION_MODEL_EFFORT_SWITCH',
342
+ reason:
343
+ `[Burnoff BO-MOD-02 Mid-Session Prefix Invalidation] Model/effort switched mid-session (${fromLabel} -> ${toLabel}), ` +
344
+ 'invalidating cached prompt prefix. Route side checks to a subagent or fresh thread.'
345
+ });
346
+ }
347
+ }
348
+ }
349
+
350
+ const nextRecentModels = [...prevRecentModels];
351
+ if (incomingStreamKey) {
352
+ const lastEntry = nextRecentModels[nextRecentModels.length - 1];
353
+ if (!lastEntry || lastEntry.streamKey !== incomingStreamKey) {
354
+ nextRecentModels.push({
355
+ model: effectiveModel,
356
+ effort: effectiveEffort,
357
+ streamKey: incomingStreamKey
358
+ });
359
+ }
360
+ }
361
+ const boundedRecentModels = nextRecentModels.slice(-4);
362
+
363
+ // 3. Mid-History Mutation / Sliding-Window Front-Slice (BO-PFX-01)
364
+ const u = extractUsageMetrics(event);
365
+ if (
366
+ hasPriorTurn &&
367
+ !isIdleExpired &&
368
+ !event.hadCompactionBefore &&
369
+ !event.isCompactionBoundary &&
370
+ !modelChanged &&
371
+ (!effortChanged || effortSwitchPreservesCache) &&
372
+ !toolsetChanged
373
+ ) {
374
+ const prevPrompt = Number(prior.lastPromptTokens || 0);
375
+ const prevCacheRead = Number(prior.lastCacheReadTokens || 0);
376
+ const rebuildTok = u.cacheCreation + u.uncached;
377
+ if (
378
+ prevPrompt >= 10_000 &&
379
+ prevCacheRead >= 4096 &&
380
+ u.promptTokens >= 10_000 &&
381
+ u.cacheRead < prevPrompt * 0.5 &&
382
+ rebuildTok >= 10_000
383
+ ) {
384
+ if (u.cacheRead === 0) {
385
+ findings.push({
386
+ detectorId: 'BO-PFX-01',
387
+ subType: 'FRONT_SLICE_HISTORY_MUTATION',
388
+ reason:
389
+ `[Burnoff BO-PFX-01 Sliding-Window Front-Slice Detected] 0 matched prefix tokens of prior ` +
390
+ `~${prevPrompt.toLocaleString('en-US')} tok (~${rebuildTok.toLocaleString('en-US')} tok cold rebuild). ` +
391
+ 'Avoid dropping oldest messages mid-thread; use /compact or start a clean session.'
392
+ });
393
+ } else {
394
+ const pct = ((u.cacheRead / prevPrompt) * 100).toFixed(1);
395
+ findings.push({
396
+ detectorId: 'BO-PFX-01',
397
+ subType: 'MID_HISTORY_MUTATION',
398
+ reason:
399
+ `[Burnoff BO-PFX-01 Mid-History Prefix Mutation] Matched prefix dropped to ` +
400
+ `~${u.cacheRead.toLocaleString('en-US')} tok (${pct}% of prior ~${prevPrompt.toLocaleString('en-US')} tok; ` +
401
+ `~${rebuildTok.toLocaleString('en-US')} tok rebuild). Avoid editing or pruning earlier messages mid-session.`
402
+ });
403
+ }
404
+ }
405
+ }
406
+
407
+ // 4. Long-context pricing pre-cliff alarm (BO-CLF-01)
408
+ const cliffEval = evaluatePreCliffAlarm({
409
+ model: effectiveModel,
410
+ promptTokens: u.promptTokens,
411
+ policy,
412
+ prior
413
+ });
414
+ if (cliffEval.finding) {
415
+ findings.push(cliffEval.finding);
416
+ }
417
+
418
+ // 5. OpenAI TPM velocity advisory (BO-TPM-01): OpenAI counts cached input tokens 100% toward TPM
419
+ let nextOpenAiEvents = Array.isArray(prior?.recentOpenAiInputEvents)
420
+ ? prior.recentOpenAiInputEvents.filter(
421
+ (e) => e && Number.isFinite(Number(e.ts)) && nowMs - Number(e.ts) <= 60_000
422
+ )
423
+ : [];
424
+ let lastTpmWarnAtMs = prior?.lastTpmWarnAtMs || null;
425
+ if (isOpenAiModel(effectiveModel) && u.promptTokens > 0) {
426
+ nextOpenAiEvents.push({ ts: nowMs, tokens: u.promptTokens });
427
+ nextOpenAiEvents = nextOpenAiEvents.slice(-32);
428
+ const rollingTpm = nextOpenAiEvents.reduce(
429
+ (sum, entry) => sum + Math.max(0, Number(entry.tokens || 0)),
430
+ 0
431
+ );
432
+ const tpmWarnThreshold = Math.max(
433
+ 10_000,
434
+ Number(policy?.guards?.openaiTpmWarnThreshold ?? 150_000)
435
+ );
436
+ if (
437
+ rollingTpm >= tpmWarnThreshold &&
438
+ (!lastTpmWarnAtMs || nowMs - Number(lastTpmWarnAtMs) >= 60_000)
439
+ ) {
440
+ lastTpmWarnAtMs = nowMs;
441
+ findings.push({
442
+ detectorId: 'BO-TPM-01',
443
+ subType: 'OPENAI_TPM_VELOCITY',
444
+ reason:
445
+ `[Burnoff BO-TPM-01 OpenAI TPM Velocity Advisory] Rolling 60s input throughput on ${effectiveModel} reached ` +
446
+ `~${rollingTpm.toLocaleString('en-US')} tok/min (>= ${tpmWarnThreshold.toLocaleString('en-US')} threshold). ` +
447
+ 'OpenAI counts cached input reads 100% toward TPM rate limits (unlike Anthropic ITPM); stagger parallel sweeps/subagents to avoid 429 throttling.'
448
+ });
449
+ }
450
+ }
451
+
452
+ // 6. Thinking/reasoning token spend telemetry (BO-THK-01) without recommending cache-breaking mid-session effort toggles
453
+ const thinkTurnWarn = Math.max(500, Number(policy?.guards?.thinkingTokensTurnWarn ?? 4000));
454
+ const thinkShareWarn = Number(policy?.guards?.thinkingSpendWarnShare ?? 0.45);
455
+ let lastThinkingWarnAtMs = prior?.lastThinkingWarnAtMs || null;
456
+ const failureEscalation =
457
+ Number(prior?.consecutiveFailures || 0) >= 1 &&
458
+ u.thinkingTokens >= Math.floor(thinkTurnWarn * 0.5);
459
+ const thinkShare =
460
+ u.thinkingTokens > 0 && u.outputTokens > 0
461
+ ? u.thinkingTokens / Math.max(1, u.thinkingTokens + u.outputTokens)
462
+ : 0;
463
+ const shareExceeded = u.thinkingTokens >= 2000 && thinkShare >= thinkShareWarn;
464
+ if (
465
+ u.thinkingTokens > 0 &&
466
+ (u.thinkingTokens >= thinkTurnWarn || failureEscalation || shareExceeded) &&
467
+ (!lastThinkingWarnAtMs || nowMs - Number(lastThinkingWarnAtMs) >= 120_000)
468
+ ) {
469
+ lastThinkingWarnAtMs = nowMs;
470
+ const thinkEffortCacheSafe = effortChangePreservesCache({ model: effectiveModel, env });
471
+ const thinkGuidance = thinkEffortCacheSafe
472
+ ? 'Lower effort with `/effort medium` or `/effort low` (cache-safe on this model/connection) or tighten the task scope.'
473
+ : 'Do NOT toggle reasoning effort mid-session (which invalidates the prompt cache per BO-MOD-02); ' +
474
+ 'lower effort at the start of the next session or delegate narrow checks to a lower-effort subagent.';
475
+ findings.push({
476
+ detectorId: 'BO-THK-01',
477
+ subType: 'HIGH_THINKING_SPEND',
478
+ reason: u.thinkingTokensEstimated
479
+ ? `[Burnoff BO-THK-01 Thinking Spend Advisory] Turn consumed ~${u.thinkingTokens.toLocaleString('en-US')} est. thinking tokens ` +
480
+ `(upper bound from output minus visible text; billed at full uncached output rates). ${thinkGuidance}`
481
+ : `[Burnoff BO-THK-01 Thinking Spend Advisory] Turn consumed ${u.thinkingTokens.toLocaleString('en-US')} thinking tokens ` +
482
+ `(billed at full uncached output rates). ${thinkGuidance}`
483
+ });
484
+ }
485
+
486
+ const nextStatePatch = {
487
+ lastMcpFingerprint: mcpFingerprint,
488
+ ...(toolsetHash ? { lastToolsetHash: toolsetHash } : {}),
489
+ recentModels: boundedRecentModels,
490
+ lastCliffStage: cliffEval.nextCliffStage,
491
+ ...(isOpenAiModel(effectiveModel) ? { recentOpenAiInputEvents: nextOpenAiEvents } : {}),
492
+ ...(lastTpmWarnAtMs ? { lastTpmWarnAtMs } : {}),
493
+ ...(u.thinkingTokens > 0 ? { lastThinkingTokens: u.thinkingTokens } : {}),
494
+ ...(lastThinkingWarnAtMs ? { lastThinkingWarnAtMs } : {}),
495
+ ...(u.promptTokens > 0 ? { lastPromptTokens: u.promptTokens, lastCacheReadTokens: u.cacheRead } : {}),
496
+ ...(u.messageCount !== null ? { lastMessageCount: u.messageCount } : {})
497
+ };
498
+
499
+ return {
500
+ findings,
501
+ nextStatePatch
502
+ };
503
+ }
504
+
505
+ function pickModelId(...candidates) {
506
+ for (const c of candidates) {
507
+ if (typeof c === 'string' && c.trim()) return c.trim();
508
+ if (c && typeof c === 'object') {
509
+ const id = String(c.id || c.name || c.model_id || '').trim();
510
+ if (id) return id;
511
+ }
512
+ }
513
+ return '';
514
+ }
515
+
516
+ /**
517
+ * Pure evaluator for Claude Code `PreModelSwitch` / `PostModelSwitch` events (`BO-MOD-02`).
518
+ *
519
+ * - `phase: 'pre'`: scores warm-cache invalidation cost and A->B->A ping-pong risk; warns by default
520
+ * and only blocks when `guards.modelSwitchAction === 'deny'` and a warm prefix or ping-pong exists.
521
+ * - `phase: 'post'`: records `lastModel` / `recentModels` and resets cache-read baselines so the next
522
+ * turn does not double-report the switch or misattribute the rebuild to `BO-PFX-01`.
523
+ */
524
+ export function evaluateModelSwitch({
525
+ phase = 'pre',
526
+ event = {},
527
+ prior = null,
528
+ policy = null,
529
+ effectiveTtlMs = 300_000,
530
+ nowMs = Date.now(),
531
+ env = undefined
532
+ } = {}) {
533
+ const isPost = String(phase).toLowerCase() === 'post';
534
+ const fromModel = pickModelId(event.from_model, event.fromModel, prior?.lastModel);
535
+ const toModel = pickModelId(event.to_model, event.toModel);
536
+ const effort = resolveEffortLevel(event, { env, priorEffort: prior?.lastEffort });
537
+ const findings = [];
538
+ const noop = { findings, decision: 'allow', stdoutMessage: '', nextStatePatch: {}, fromModel, toModel };
539
+ if (!toModel || (fromModel && fromModel === toModel)) return noop;
540
+
541
+ const prevPrompt = Math.max(0, Number(prior?.lastPromptTokens || 0));
542
+ const prevCacheRead = Math.max(0, Number(prior?.lastCacheReadTokens || 0));
543
+ const warmTokens = Math.max(prevPrompt, prevCacheRead);
544
+ const warmMinTokens = Math.max(
545
+ 1000,
546
+ Number(policy?.guards?.modelSwitchWarmMinTokens ?? 10_000) || 10_000
547
+ );
548
+ const elapsedMs = prior?.lastTurnAtMs ? Math.max(0, nowMs - Number(prior.lastTurnAtMs)) : 0;
549
+ const isWarmPrefix = warmTokens >= warmMinTokens && elapsedMs <= effectiveTtlMs;
550
+
551
+ const recent = Array.isArray(prior?.recentModels) ? prior.recentModels : [];
552
+ const isPingPong = Boolean(
553
+ fromModel &&
554
+ recent.length > 1 &&
555
+ recent.slice(0, -1).some((entry) => entry?.model === toModel && entry.model !== fromModel)
556
+ );
557
+
558
+ const fromLabel = fromModel || 'current';
559
+ let message = '';
560
+ if (isPingPong) {
561
+ message =
562
+ `[Burnoff BO-MOD-02 Model Switch Ping-Pong] Switching ${fromLabel} -> ${toModel} returns to a model used earlier in this thread (A->B->A); ` +
563
+ 'each hop rebuilds the prompt cache. Use a subagent for side questions instead of switching models mid-thread.';
564
+ findings.push({ detectorId: 'BO-MOD-02', subType: 'MODEL_SWITCH_PING_PONG', reason: message });
565
+ } else if (isWarmPrefix) {
566
+ message =
567
+ `[Burnoff BO-MOD-02 Warm-Cache Model Switch] Switching ${fromLabel} -> ${toModel} abandons a warm ~${warmTokens.toLocaleString('en-US')} tok prefix; ` +
568
+ 'the next turn rebuilds it at cache-write rates. Prefer switching after /compact, in a fresh session, or delegating the side task to a subagent.';
569
+ findings.push({ detectorId: 'BO-MOD-02', subType: 'WARM_CACHE_MODEL_SWITCH', reason: message });
570
+ }
571
+
572
+ const action = String(policy?.guards?.modelSwitchAction ?? 'allow').trim().toLowerCase();
573
+ const decision = !isPost && findings.length > 0 && action === 'deny' ? 'deny' : 'allow';
574
+
575
+ const nextStatePatch = {};
576
+ if (isPost) {
577
+ const streamKey = `${toModel}|${effort}`;
578
+ const nextRecent = [...recent];
579
+ const lastEntry = nextRecent[nextRecent.length - 1];
580
+ if (!lastEntry || lastEntry.streamKey !== streamKey) {
581
+ nextRecent.push({ model: toModel, effort, streamKey });
582
+ }
583
+ Object.assign(nextStatePatch, {
584
+ lastModel: toModel,
585
+ recentModels: nextRecent.slice(-4),
586
+ // The switch rebuilds the cache; zero the cache-read baseline so BO-PFX-01 does not fire on the cold turn.
587
+ lastCacheReadTokens: 0,
588
+ lastModelSwitchAtMs: nowMs
589
+ });
590
+ }
591
+
592
+ return {
593
+ findings,
594
+ decision,
595
+ stdoutMessage: message,
596
+ nextStatePatch,
597
+ fromModel,
598
+ toModel
599
+ };
600
+ }
601
+
602
+ export default {
603
+ isOpenAiModel,
604
+ computeMcpConfigFingerprint,
605
+ extractUsageMetrics,
606
+ evaluatePreCliffAlarm,
607
+ evaluatePrefixIntegrity,
608
+ evaluateModelSwitch
609
+ };