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,145 @@
1
+ /**
2
+ * @file src/config/effort.mjs
3
+ * Shared reasoning-effort normalization and cache-safety helpers (zero imports besides `node:fs`
4
+ * so every guard and client adapter can depend on it without cycles).
5
+ *
6
+ * Claude Code sends `effort` as an object (`{ level: "max" }`), while older/other clients send
7
+ * plain strings; `String(obj)` would coerce the former to `"[object object]"` and silently blind
8
+ * `BO-MOD-01`, `BO-MOD-02`, and `BO-THK-01`.
9
+ */
10
+
11
+ import fs from 'node:fs';
12
+
13
+ const BAD_EFFORT_LITERAL = '[object object]';
14
+ const TRANSCRIPT_TAIL_BYTES = 65_536;
15
+ const TRUTHY_ENV_RE = /^(?:1|true|yes|on)$/i;
16
+ const THIRD_PARTY_PROVIDER_ENV_KEYS = Object.freeze([
17
+ 'CLAUDE_CODE_USE_BEDROCK',
18
+ 'CLAUDE_CODE_USE_VERTEX',
19
+ 'CLAUDE_CODE_USE_FOUNDRY'
20
+ ]);
21
+
22
+ function isPlainObject(value) {
23
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
24
+ }
25
+
26
+ /**
27
+ * Normalizes one effort candidate: non-empty strings and `{ level: string }` objects resolve to a
28
+ * trimmed lowercase level; any other type is treated as missing (`''`), never stringified.
29
+ */
30
+ export function normalizeEffortCandidate(candidate) {
31
+ let raw = candidate;
32
+ if (isPlainObject(raw)) raw = raw.level;
33
+ if (typeof raw !== 'string') return '';
34
+ const level = raw.trim().toLowerCase();
35
+ if (!level || level === BAD_EFFORT_LITERAL) return '';
36
+ return level;
37
+ }
38
+
39
+ /**
40
+ * Best-effort bounded tail scan of a Claude Code JSONL transcript for the last recorded effort.
41
+ */
42
+ export function readLastEffortFromTranscript(transcriptPath = '') {
43
+ const filePath = String(transcriptPath || '').trim();
44
+ if (!filePath) return '';
45
+ let fd = null;
46
+ try {
47
+ fd = fs.openSync(filePath, 'r');
48
+ const { size } = fs.fstatSync(fd);
49
+ if (!(size > 0)) return '';
50
+ const start = Math.max(0, size - TRANSCRIPT_TAIL_BYTES);
51
+ const buf = Buffer.alloc(size - start);
52
+ fs.readSync(fd, buf, 0, buf.length, start);
53
+ const tail = buf.toString('utf8');
54
+ const re = /"(?:effort|reasoning_effort|reasoningEffort|effortLevel)"\s*:\s*(?:"([A-Za-z]+)"|\{\s*"level"\s*:\s*"([A-Za-z]+)")/g;
55
+ let last = '';
56
+ for (const m of tail.matchAll(re)) {
57
+ const level = normalizeEffortCandidate(m[1] || m[2]);
58
+ if (level) last = level;
59
+ }
60
+ return last;
61
+ } catch (err) {
62
+ void err; // ignore: unreadable transcript falls through to no effort
63
+ return '';
64
+ } finally {
65
+ if (fd !== null) {
66
+ try {
67
+ fs.closeSync(fd);
68
+ } catch (closeErr) {
69
+ void closeErr; // ignore: best-effort fd close
70
+ }
71
+ }
72
+ }
73
+ }
74
+
75
+ /**
76
+ * Resolves the active reasoning-effort level from a hook payload.
77
+ *
78
+ * Order: `options.explicitEffort`, `payload.effort`, `payload.reasoning_effort`,
79
+ * `payload.reasoningEffort`, `payload.thinking_level`, `payload.thinkingLevel`,
80
+ * `payload.model.effort`, `options.effort`; then `$CLAUDE_EFFORT` (needed on `UserPromptSubmit`,
81
+ * where Claude Code omits the effort object); then `options.priorEffort` and the transcript tail.
82
+ */
83
+ export function resolveEffortLevel(payload = {}, options = {}) {
84
+ const src = payload && typeof payload === 'object' ? payload : {};
85
+ const opts = options && typeof options === 'object' ? options : {};
86
+ const candidates = [
87
+ opts.explicitEffort,
88
+ src.effort,
89
+ src.reasoning_effort,
90
+ src.reasoningEffort,
91
+ src.thinking_level,
92
+ src.thinkingLevel,
93
+ isPlainObject(src.model) ? src.model.effort : undefined,
94
+ opts.effort
95
+ ];
96
+ for (const candidate of candidates) {
97
+ const level = normalizeEffortCandidate(candidate);
98
+ if (level) return level;
99
+ }
100
+
101
+ const env = isPlainObject(opts.env) ? opts.env : globalThis.process?.env || {};
102
+ const envLevel = normalizeEffortCandidate(env.CLAUDE_EFFORT);
103
+ if (envLevel) return envLevel;
104
+
105
+ const priorLevel = normalizeEffortCandidate(opts.priorEffort);
106
+ if (priorLevel) return priorLevel;
107
+
108
+ const transcriptPath = opts.transcriptPath || src.transcript_path || src.transcriptPath;
109
+ return transcriptPath ? readLastEffortFromTranscript(transcriptPath) : '';
110
+ }
111
+
112
+ function isThirdPartyProviderActive(env, provider, rawModel) {
113
+ if (/^(?:bedrock|vertex|foundry)$/i.test(String(provider || '').trim())) return true;
114
+ if (/^(?:bedrock|vertex|foundry)[:/]/i.test(rawModel)) return true;
115
+ // Native Bedrock ids (`anthropic.claude-*`, `us.anthropic.claude-*`) never run on first-party API.
116
+ if (/^(?:[a-z]{2}\.)?anthropic\.claude/i.test(rawModel)) return true;
117
+ return THIRD_PARTY_PROVIDER_ENV_KEYS.some((key) => TRUTHY_ENV_RE.test(String(env?.[key] ?? '').trim()));
118
+ }
119
+
120
+ /**
121
+ * Returns `true` only when a mid-session effort change keeps the prompt cache warm: 5.5-generation
122
+ * Anthropic models and `fable-5.1+` on first-party API/subscription. Bedrock/Vertex/Foundry, 4.x,
123
+ * OpenAI, Gemini, and unknown models return `false`.
124
+ */
125
+ export function effortChangePreservesCache({ model = '', env, provider = '' } = {}) {
126
+ const activeEnv = isPlainObject(env) ? env : globalThis.process?.env || {};
127
+ const rawModel = String(model || '').trim().toLowerCase();
128
+ if (!rawModel) return false;
129
+ if (TRUTHY_ENV_RE.test(String(activeEnv?.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS ?? '').trim())) {
130
+ return false;
131
+ }
132
+ if (isThirdPartyProviderActive(activeEnv, provider, rawModel)) return false;
133
+ if (/(?:^|[^a-z])(?:opus|sonnet|haiku)-5[-.]5(?!\d)/.test(rawModel)) return true;
134
+ if (/(?:^|[^a-z])fable-(?:5[-.](?:[1-9]\d*)|(?:[6-9]|[1-9]\d+)(?:[-.]\d+)*)(?!\d)/.test(rawModel)) {
135
+ return true;
136
+ }
137
+ return false;
138
+ }
139
+
140
+ export default {
141
+ normalizeEffortCandidate,
142
+ readLastEffortFromTranscript,
143
+ resolveEffortLevel,
144
+ effortChangePreservesCache
145
+ };
@@ -0,0 +1,340 @@
1
+ /**
2
+ * @file src/config/harness-quirks.mjs
3
+ * Rank 5 expanded upstream harness quirk detectors (`BO-HAB-01`..`BO-HAB-06`).
4
+ * Identifies verified Antigravity and CLI harness regressions without fabricating telemetry.
5
+ */
6
+
7
+ export const HARNESS_QUIRK_CONSTANTS = Object.freeze({
8
+ ANTIGRAVITY_BINARY_CLAMP_TOKENS: 256_000,
9
+ ANTIGRAVITY_CLAMP_LOW_TOKENS: 245_000,
10
+ ANTIGRAVITY_CLAMP_HIGH_TOKENS: 276_000,
11
+ ANTIGRAVITY_CLAMP_WARN_PCT: 0.80,
12
+ BTW_TRAJECTORY_TYPE: 22,
13
+ RUNAWAY_429_CONSECUTIVE_MIN: 3,
14
+ GEMINI_MD_BLOATED_BYTES: 32_768,
15
+ GEMINI_MD_BLOATED_TOKENS: 8_000
16
+ });
17
+
18
+ export const HARNESS_QUIRK_RULES = Object.freeze({
19
+ 'BO-HAB-01': Object.freeze({
20
+ ruleId: 'BO-HAB-01',
21
+ severity: 'error',
22
+ issueRef: '#1609/#1616/#1634',
23
+ title: 'Unsupported THINKING_LEVEL_XHIGH on Hydrogen / Orchestrator'
24
+ }),
25
+ 'BO-HAB-02': Object.freeze({
26
+ ruleId: 'BO-HAB-02',
27
+ severity: 'warn',
28
+ issueRef: '#1917/#1548/#1638',
29
+ title: 'Antigravity 1.5.18 Orchestrator Misroute / Cache Collapse'
30
+ }),
31
+ 'BO-HAB-03': Object.freeze({
32
+ ruleId: 'BO-HAB-03',
33
+ severity: 'warn',
34
+ issueRef: '#198137/#1646',
35
+ title: '/btw (trajectory_type = 22) KV Miss or Runaway 429 Loop'
36
+ }),
37
+ 'BO-HAB-04': Object.freeze({
38
+ ruleId: 'BO-HAB-04',
39
+ severity: 'warn',
40
+ issueRef: '#1245/#878/#1432',
41
+ title: 'Antigravity 0x3e800 (256K) Binary Compaction Clamp'
42
+ }),
43
+ 'BO-HAB-05': Object.freeze({
44
+ ruleId: 'BO-HAB-05',
45
+ severity: 'warn',
46
+ issueRef: '#1442',
47
+ title: 'Hook userMessage "/compact" Fallacy'
48
+ }),
49
+ 'BO-HAB-06': Object.freeze({
50
+ ruleId: 'BO-HAB-06',
51
+ severity: 'warn',
52
+ issueRef: '#1876',
53
+ title: 'Bloated GEMINI.md / Always-On Rules False-Positive 429'
54
+ })
55
+ });
56
+
57
+ function is429OrExhausted(text = '', status = null) {
58
+ if (Number(status) === 429) return true;
59
+ const s = String(text || '');
60
+ return /\b429\b|RESOURCE_EXHAUSTED|rate[_\s-]?limit/i.test(s);
61
+ }
62
+
63
+ function isXhighThinkingError(text = '', step = {}) {
64
+ const s = String(text || '');
65
+ if (/THINKING_LEVEL_XHIGH/i.test(s)) return true;
66
+ if (/thinking\s+level\s+is\s+unsupported/i.test(s) && /400|INVALID_ARGUMENT/i.test(s)) return true;
67
+ const modelText = `${step.model || ''} ${step.label || ''}`.toLowerCase();
68
+ const level = String(step.thinkingLevel || step.effort || '').toLowerCase();
69
+ if ((level === 'xhigh' || level === 'extra') && (modelText.includes('hydrogen') || modelText.includes('orchestrator'))) {
70
+ return /400|INVALID_ARGUMENT/i.test(s) || Boolean(step.isError || step.error);
71
+ }
72
+ return false;
73
+ }
74
+
75
+ function isOrchestratorCarbonModel(model = '', label = '') {
76
+ const s = `${model || ''} ${label || ''}`.toLowerCase();
77
+ return s.includes('orchestrator') && s.includes('carbon');
78
+ }
79
+
80
+ function isOrchestratorNeonOrFlashModel(model = '', label = '') {
81
+ const s = `${model || ''} ${label || ''}`.toLowerCase();
82
+ return (s.includes('orchestrator') && s.includes('neon')) || s.includes('gemini-3.8-flash');
83
+ }
84
+
85
+ function extractCompactHookPayload(item) {
86
+ if (!item) return null;
87
+ if (typeof item === 'string') {
88
+ const trimmed = item.trim();
89
+ if (trimmed.includes('userMessage') && trimmed.includes('/compact')) {
90
+ try {
91
+ const parsed = JSON.parse(trimmed);
92
+ if (typeof parsed?.userMessage === 'string' && /^\s*\/compact\b/i.test(parsed.userMessage)) {
93
+ return parsed;
94
+ }
95
+ } catch {
96
+ // ignore: non-JSON hook payload string falls back to regex match
97
+ if (/["']userMessage["']\s*:\s*["']\s*\/compact\b/i.test(trimmed)) {
98
+ return { userMessage: '/compact' };
99
+ }
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+ if (typeof item === 'object') {
105
+ const msg = item.userMessage ?? item.hookSpecificOutput?.userMessage;
106
+ if (typeof msg === 'string' && /^\s*\/compact\b/i.test(msg)) {
107
+ return item;
108
+ }
109
+ }
110
+ return null;
111
+ }
112
+
113
+ /**
114
+ * Evaluates Rank 5 upstream harness quirks (`BO-HAB-01..06`) over audited sessions,
115
+ * attribution results, hook payloads, and environment overrides.
116
+ */
117
+ export function detectHarnessQuirks(input = {}) {
118
+ const sessions = Array.isArray(input.sessions) ? input.sessions : [];
119
+ const uncachedAttribution = input.uncachedAttribution || null;
120
+ const antigravityVersion = input.antigravityVersion ? String(input.antigravityVersion).trim() : null;
121
+ const env = input.env || {};
122
+ const hookPayloads = Array.isArray(input.hookPayloads) ? input.hookPayloads : [];
123
+ const findings = [];
124
+ const seenKeys = new Set();
125
+
126
+ const pushFinding = (ruleId, { sessionId = null, message, remediation, details = {} }) => {
127
+ const rule = HARNESS_QUIRK_RULES[ruleId];
128
+ if (!rule) return;
129
+ const dedupKey = `${ruleId}:${sessionId || 'global'}`;
130
+ if (seenKeys.has(dedupKey)) return;
131
+ seenKeys.add(dedupKey);
132
+ findings.push({
133
+ ruleId,
134
+ severity: rule.severity,
135
+ issueRef: rule.issueRef,
136
+ title: rule.title,
137
+ sessionId,
138
+ message,
139
+ remediation,
140
+ details
141
+ });
142
+ };
143
+
144
+ let anySessionHas429 = false;
145
+
146
+ for (const sess of sessions) {
147
+ if (!sess || typeof sess !== 'object') continue;
148
+ const sid = sess.sessionId || null;
149
+ const steps = Array.isArray(sess.steps) ? sess.steps : [];
150
+
151
+ let maxConsecutive429 = 0;
152
+ let curConsecutive429 = 0;
153
+ let xhighHit = false;
154
+ let sawOrchCarbon = false;
155
+ let sawMisroutedNeonOrFlash = false;
156
+ let maxPromptBeforeCompaction = 0;
157
+ let sawClampCompaction = false;
158
+ let prevPrompt = 0;
159
+
160
+ if (isXhighThinkingError(sess.errorText, sess)) {
161
+ xhighHit = true;
162
+ }
163
+ if (is429OrExhausted(sess.errorText, sess.status) || sess.hasRateLimit429) {
164
+ anySessionHas429 = true;
165
+ }
166
+
167
+ const sessionHooks = Array.isArray(sess.hookPayloads) ? sess.hookPayloads : [];
168
+ for (const hp of sessionHooks) {
169
+ if (extractCompactHookPayload(hp)) {
170
+ pushFinding('BO-HAB-05', {
171
+ sessionId: sid,
172
+ message: 'Hook returned {"userMessage": "/compact"} (#1442), which sends literal text "/compact" instead of compacting history.',
173
+ remediation: 'Remove hook userMessage "/compact" overrides and invoke /compact manually at clean commit/phase boundaries.',
174
+ details: { issueRef: '#1442' }
175
+ });
176
+ }
177
+ }
178
+
179
+ for (let i = 0; i < steps.length; i += 1) {
180
+ const st = steps[i] || {};
181
+ const errText = st.errorText || st.errorDetailsText || st.error || '';
182
+ if (isXhighThinkingError(errText, st)) {
183
+ xhighHit = true;
184
+ }
185
+
186
+ if (is429OrExhausted(errText, st.status)) {
187
+ anySessionHas429 = true;
188
+ curConsecutive429 += 1;
189
+ if (curConsecutive429 > maxConsecutive429) maxConsecutive429 = curConsecutive429;
190
+ } else {
191
+ curConsecutive429 = 0;
192
+ }
193
+
194
+ if (isOrchestratorCarbonModel(st.model, st.label)) {
195
+ sawOrchCarbon = true;
196
+ } else if (sawOrchCarbon && isOrchestratorNeonOrFlashModel(st.model, st.label)) {
197
+ sawMisroutedNeonOrFlash = true;
198
+ }
199
+
200
+ if (extractCompactHookPayload(st.hookOutput || st.hookPayload || st.userMessage)) {
201
+ pushFinding('BO-HAB-05', {
202
+ sessionId: sid,
203
+ message: 'Step hook returned {"userMessage": "/compact"} (#1442), sending literal "/compact" text without compacting.',
204
+ remediation: 'Run /compact manually before ~220k tokens at commit/phase boundaries rather than via lifecycle hook userMessage.',
205
+ details: { stepIndex: st.stepIndex ?? i }
206
+ });
207
+ }
208
+
209
+ const u = st.tokenUsage || st;
210
+ const promptTok =
211
+ Number(u.freshInputTokens ?? u.inputTokens ?? 0) +
212
+ Number(u.cacheCreationTokens ?? 0) +
213
+ Number(u.cacheReadTokens ?? 0);
214
+
215
+ if (
216
+ (st.hadCompactionBefore || st.isCompactSummary || st.isCompactionBoundary) &&
217
+ prevPrompt >= HARNESS_QUIRK_CONSTANTS.ANTIGRAVITY_CLAMP_LOW_TOKENS &&
218
+ prevPrompt <= HARNESS_QUIRK_CONSTANTS.ANTIGRAVITY_CLAMP_HIGH_TOKENS &&
219
+ /gemini[-\s]?4/i.test(`${st.model || ''} ${sess.modelId || ''}`)
220
+ ) {
221
+ sawClampCompaction = true;
222
+ maxPromptBeforeCompaction = Math.max(maxPromptBeforeCompaction, prevPrompt);
223
+ }
224
+ if (promptTok > 0) prevPrompt = promptTok;
225
+ }
226
+
227
+ if (xhighHit) {
228
+ pushFinding('BO-HAB-01', {
229
+ sessionId: sid,
230
+ message: 'THINKING_LEVEL_XHIGH / Extra thinking triggered HTTP 400 INVALID_ARGUMENT on Hydrogen or Orchestrator (#1609/#1616).',
231
+ remediation: 'Switch thinking level from Extra/xhigh to High or use a non-Orchestrator model.',
232
+ details: { model: sess.modelId || null }
233
+ });
234
+ }
235
+
236
+ if (sawMisroutedNeonOrFlash) {
237
+ pushFinding('BO-HAB-02', {
238
+ sessionId: sid,
239
+ message: `Orchestrator Carbon session routed turns to Neon/gemini-3.8-flash (${antigravityVersion || 'Antigravity 1.5.18'} #1917/#1548).`,
240
+ remediation: 'Pin a single non-Orchestrator model for deep coding phases to prevent silent misroutes and cache collapse (#1638).',
241
+ details: { antigravityVersion }
242
+ });
243
+ }
244
+
245
+ const isBtw =
246
+ Number(sess.trajectoryType) === HARNESS_QUIRK_CONSTANTS.BTW_TRAJECTORY_TYPE ||
247
+ steps.some((st) => Number(st?.trajectoryType) === HARNESS_QUIRK_CONSTANTS.BTW_TRAJECTORY_TYPE);
248
+ if (isBtw || maxConsecutive429 >= HARNESS_QUIRK_CONSTANTS.RUNAWAY_429_CONSECUTIVE_MIN) {
249
+ pushFinding('BO-HAB-03', {
250
+ sessionId: sid,
251
+ message: isBtw
252
+ ? '/btw side-question (trajectory_type = 22) forked without cached prefix (100% Turn-1 miss, #198137).'
253
+ : `Runaway consecutive HTTP 429 retry loop detected (${maxConsecutive429} consecutive retries, #1646).`,
254
+ remediation: 'Avoid /btw mid-session on large cached contexts and abort runaway 429 continuation loops promptly.',
255
+ details: { trajectoryType: sess.trajectoryType ?? null, maxConsecutive429 }
256
+ });
257
+ }
258
+
259
+ if (sawClampCompaction) {
260
+ pushFinding('BO-HAB-04', {
261
+ sessionId: sid,
262
+ message: `Premature compaction near ${Math.round(maxPromptBeforeCompaction / 1000)}k tokens matches Antigravity 0x3e800 (256K) binary clamp (#1245/#878/#1432).`,
263
+ remediation: 'Compact proactively around ~220k tokens at clean phase/commit boundaries before hitting the 256K clamp.',
264
+ details: { maxPromptBeforeCompaction, clampTokens: HARNESS_QUIRK_CONSTANTS.ANTIGRAVITY_BINARY_CLAMP_TOKENS }
265
+ });
266
+ }
267
+ }
268
+
269
+ // Global BO-HAB-02 check from attribution orchestratorThrash (#1638)
270
+ const thrash = uncachedAttribution?.buckets?.model_or_effort_switch?.orchestratorThrash;
271
+ if (thrash && thrash.calls > 0 && !findings.some((f) => f.ruleId === 'BO-HAB-02')) {
272
+ pushFinding('BO-HAB-02', {
273
+ sessionId: null,
274
+ message: `Orchestrator/worker model ping-pong thrash (${thrash.calls} calls, ${thrash.tokens.toLocaleString('en-US')} uncached tok, #1638).`,
275
+ remediation: thrash.guidance || 'Pin a homogeneous model during deep coding phases.',
276
+ details: { calls: thrash.calls, tokens: thrash.tokens }
277
+ });
278
+ }
279
+
280
+ // Global BO-HAB-04 env override check (*CLI_AUTO_COMPACT_OVERRIDE > 256,000)
281
+ for (const [k, v] of Object.entries(env || {})) {
282
+ if (k.endsWith('CLI_AUTO_COMPACT_OVERRIDE')) {
283
+ const n = Number(v);
284
+ if (Number.isFinite(n) && n > HARNESS_QUIRK_CONSTANTS.ANTIGRAVITY_BINARY_CLAMP_TOKENS) {
285
+ pushFinding('BO-HAB-04', {
286
+ sessionId: null,
287
+ message: `${k}=${n} exceeds Antigravity GetCheckpointConfig 0x3e800 (256,000) clamp and will still be clamped to 256K (#1245).`,
288
+ remediation: 'Compact cleanly before ~220k tokens instead of relying on >256K override values.',
289
+ details: { envKey: k, configuredValue: n, clampTokens: HARNESS_QUIRK_CONSTANTS.ANTIGRAVITY_BINARY_CLAMP_TOKENS }
290
+ });
291
+ }
292
+ }
293
+ }
294
+
295
+ // Global BO-HAB-05 hookPayloads array
296
+ for (const hp of hookPayloads) {
297
+ if (extractCompactHookPayload(hp)) {
298
+ pushFinding('BO-HAB-05', {
299
+ sessionId: null,
300
+ message: 'Lifecycle hook returned {"userMessage": "/compact"} (#1442), which sends literal "/compact" text without compacting.',
301
+ remediation: 'Remove hook userMessage "/compact" and trigger /compact manually at phase boundaries.',
302
+ details: { issueRef: '#1442' }
303
+ });
304
+ }
305
+ }
306
+
307
+ // Global BO-HAB-06 bloated GEMINI.md + 429 diagnostic (#1876)
308
+ const geminiMdBytes = Number(input.geminiMdBytes ?? 0);
309
+ const geminiMdTokens = Number(input.geminiMdTokens ?? 0);
310
+ const isBloatedGeminiMd =
311
+ (Number.isFinite(geminiMdBytes) && geminiMdBytes > HARNESS_QUIRK_CONSTANTS.GEMINI_MD_BLOATED_BYTES) ||
312
+ (Number.isFinite(geminiMdTokens) && geminiMdTokens >= HARNESS_QUIRK_CONSTANTS.GEMINI_MD_BLOATED_TOKENS);
313
+ if (isBloatedGeminiMd && anySessionHas429) {
314
+ pushFinding('BO-HAB-06', {
315
+ sessionId: null,
316
+ message: `Bloated GEMINI.md / always-on rules (${geminiMdBytes > 0 ? `${geminiMdBytes} bytes` : `${geminiMdTokens} tok`}) paired with HTTP 429 / RESOURCE_EXHAUSTED (#1876).`,
317
+ remediation: 'Trim GEMINI.md and move specialized instructions to on-demand rules/skills so prompt bloat does not amplify rate-limit 429s.',
318
+ details: { geminiMdBytes, geminiMdTokens }
319
+ });
320
+ }
321
+
322
+ const byRuleId = {};
323
+ for (const f of findings) {
324
+ byRuleId[f.ruleId] = (byRuleId[f.ruleId] || 0) + 1;
325
+ }
326
+
327
+ return {
328
+ findingCount: findings.length,
329
+ errorCount: findings.filter((f) => f.severity === 'error').length,
330
+ warnCount: findings.filter((f) => f.severity === 'warn').length,
331
+ findings,
332
+ byRuleId
333
+ };
334
+ }
335
+
336
+ export default {
337
+ HARNESS_QUIRK_CONSTANTS,
338
+ HARNESS_QUIRK_RULES,
339
+ detectHarnessQuirks
340
+ };
@@ -45,7 +45,22 @@ const SHORT_MODEL_ALIASES = Object.freeze({
45
45
  mythos: 'claude-mythos-5-2',
46
46
  'claude-opus-4': 'claude-opus-4-0',
47
47
  'claude-sonnet-4': 'claude-sonnet-4-0',
48
- 'claude-3-5-sonnet-v2': 'claude-3-5-sonnet'
48
+ 'claude-3-5-sonnet-v2': 'claude-3-5-sonnet',
49
+ m427: 'gemini-4-carbon',
50
+ m437: 'gemini-4-carbon',
51
+ m438: 'gemini-4-carbon',
52
+ m670: 'gemini-4-carbon',
53
+ 'gemini-pro-orchestrator': 'gemini-4-carbon',
54
+ 'gemini-pro-orchestrator-carbon': 'gemini-4-carbon',
55
+ 'orchestrator-carbon': 'gemini-4-carbon',
56
+ 'gemini-pro-orchestrator-argon': 'gemini-4-argon',
57
+ 'orchestrator-argon': 'gemini-4-argon',
58
+ 'gemini-pro-orchestrator-neon': 'gemini-4-neon',
59
+ 'orchestrator-neon': 'gemini-4-neon',
60
+ 'gemini-pro-orchestrator-hydrogen': 'gemini-4-hydrogen',
61
+ 'orchestrator-hydrogen': 'gemini-4-hydrogen',
62
+ 'gemini-4-carbon-cyber-permissive': 'gemini-4-carbon',
63
+ 'gemini-flash': 'gemini-3-8-flash'
49
64
  });
50
65
 
51
66
  function canonicalizeModelToken(rawModelId = '') {
@@ -405,7 +420,17 @@ export function extractNormalizedTokenBreakdown(usage = {}) {
405
420
  const outputTokens = Math.max(0, Number(usage.outputTokens ?? usage.output_tokens ?? usage.lastOutputTokens ?? 0));
406
421
  const thinkingTokens = Math.max(
407
422
  0,
408
- Number(usage.thinkingTokens ?? usage.thinking_tokens ?? usage.reasoning_tokens ?? nestedCreation?.thinking_tokens ?? usage.lastThinkingTokens ?? 0)
423
+ Number(
424
+ usage.thinkingTokens ??
425
+ usage.thinking_tokens ??
426
+ usage.output_tokens_details?.thinking_tokens ??
427
+ usage.output_tokens_details?.reasoning_tokens ??
428
+ usage.completion_tokens_details?.reasoning_tokens ??
429
+ usage.reasoning_tokens ??
430
+ nestedCreation?.thinking_tokens ??
431
+ usage.lastThinkingTokens ??
432
+ 0
433
+ )
409
434
  );
410
435
 
411
436
  return {
@@ -26,10 +26,33 @@ export const DEFAULT_POLICY = Object.freeze({
26
26
  det08CheckTestSkip: true,
27
27
  det08CheckEmptyCatch: true,
28
28
  det09Enabled: true,
29
- det09Action: 'ask',
29
+ det09Action: 'advisory',
30
30
  det09MaxEditsPerFile: 5,
31
31
  det09WindowSec: 300,
32
- inspectReadOnlyTools: false
32
+ det10Enabled: true,
33
+ fullFileRewriteAction: 'ask',
34
+ promptCoachEnabled: false,
35
+ det13Enabled: null,
36
+ det14Enabled: null,
37
+ det17Enabled: null,
38
+ explorationBudgetCalls: 10,
39
+ blindMultiFileEditAction: 'ask',
40
+ modelSwitchAction: 'allow',
41
+ modelSwitchWarmMinTokens: 10000,
42
+ cacheTtlTier: '5m',
43
+ inspectReadOnlyTools: false,
44
+ compactionBatonEnabled: true,
45
+ compactionBatonMaxBytes: 3584,
46
+ det08CheckAssertionDrop: true,
47
+ det08AssertionDropAction: 'advisory',
48
+ preCliffEnabled: true,
49
+ preCliffWarnRatio: 0.90,
50
+ subagentPrefixCheckEnabled: true,
51
+ subagentPrefixMinSharedChars: 64,
52
+ openaiTpmWarnThreshold: 150000,
53
+ openaiMaxBurstCount: 2,
54
+ thinkingSpendWarnShare: 0.45,
55
+ thinkingTokensTurnWarn: 4000
33
56
  }),
34
57
  readClamp: Object.freeze({
35
58
  enabled: true,
@@ -44,14 +67,19 @@ export const DEFAULT_POLICY = Object.freeze({
44
67
  fts5Enabled: true,
45
68
  minBytesToCompress: 6144,
46
69
  retentionDays: 30,
47
- outputMode: 'replace'
70
+ outputMode: 'replace',
71
+ webFetchMaxTokens: 4000,
72
+ autoFormatOnSave: 'advisory'
48
73
  }),
49
74
  ciBudgetGate: Object.freeze({
50
75
  maxPrCostUsd: 15,
51
76
  maxPrTokens: 1_500_000,
52
77
  maxCacheMissRatio: 0.50,
53
78
  maxWasteRatio: 0.35,
79
+ wasteRatioBasis: 'actionable',
54
80
  maxRing0Violations: 0,
81
+ maxPrQuotaUnits: null,
82
+ quotaGateMode: 'warn',
55
83
  mode: 'enforce',
56
84
  failOnMissingTranscripts: false
57
85
  })
@@ -88,6 +116,40 @@ function stripInlineComment(line) {
88
116
  return line;
89
117
  }
90
118
 
119
+ /** Splits an inline YAML list body on commas that are outside single/double quotes. */
120
+ function splitInlineYamlList(inner) {
121
+ const parts = [];
122
+ let cur = '';
123
+ let quote = null;
124
+ for (let i = 0; i < inner.length; i++) {
125
+ const ch = inner[i];
126
+ if (quote) {
127
+ cur += ch;
128
+ if (ch === '\\' && quote === '"' && i + 1 < inner.length) {
129
+ cur += inner[++i];
130
+ } else if (ch === quote) {
131
+ if (quote === "'" && inner[i + 1] === "'") {
132
+ cur += inner[++i];
133
+ } else {
134
+ quote = null;
135
+ }
136
+ }
137
+ continue;
138
+ }
139
+ if (ch === '"' || ch === "'") {
140
+ quote = ch;
141
+ cur += ch;
142
+ } else if (ch === ',') {
143
+ parts.push(cur);
144
+ cur = '';
145
+ } else {
146
+ cur += ch;
147
+ }
148
+ }
149
+ parts.push(cur);
150
+ return parts;
151
+ }
152
+
91
153
  function parseScalar(raw) {
92
154
  const s = String(raw ?? '').trim();
93
155
  if (!s) return '';
@@ -104,7 +166,7 @@ function parseScalar(raw) {
104
166
  if (s.startsWith('[') && s.endsWith(']')) {
105
167
  const inner = s.slice(1, -1).trim();
106
168
  if (!inner) return [];
107
- return inner.split(',').map((part) => parseScalar(part));
169
+ return splitInlineYamlList(inner).map((part) => parseScalar(part));
108
170
  }
109
171
  return s;
110
172
  }
@@ -135,12 +197,21 @@ export function parseSimpleYaml(text = '') {
135
197
  const indent = rawLine.match(/^ */)[0].length;
136
198
  const content = rawLine.trim();
137
199
 
138
- while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {
139
- stack.pop();
200
+ const isListItem = content === '-' || content.startsWith('- ');
201
+ while (stack.length > 1) {
202
+ const candidate = stack[stack.length - 1];
203
+ if (indent < candidate.indent) {
204
+ stack.pop();
205
+ } else if (indent === candidate.indent && !(isListItem && candidate.isArray)) {
206
+ // A same-indent sibling closes the container, except zero-indent list items of an open list.
207
+ stack.pop();
208
+ } else {
209
+ break;
210
+ }
140
211
  }
141
212
  const top = stack[stack.length - 1];
142
213
 
143
- if (content === '-' || content.startsWith('- ')) {
214
+ if (isListItem) {
144
215
  const itemText = content.slice(2).trim();
145
216
  if (!Array.isArray(top.container)) {
146
217
  throw new SyntaxError(`Unexpected YAML list item at line ${idx + 1}`);
@@ -167,7 +238,8 @@ export function parseSimpleYaml(text = '') {
167
238
  const peek = stripInlineComment(lines[j]);
168
239
  if (!peek.trim()) continue;
169
240
  const peekIndent = peek.match(/^ */)[0].length;
170
- if (peekIndent > indent && peek.trim().startsWith('- ')) {
241
+ const peekTrim = peek.trim();
242
+ if (peekIndent >= indent && (peekTrim === '-' || peekTrim.startsWith('- '))) {
171
243
  nextIsArray = true;
172
244
  }
173
245
  break;
@@ -175,7 +247,7 @@ export function parseSimpleYaml(text = '') {
175
247
  const child = nextIsArray ? [] : {};
176
248
  if (top.container && typeof top.container === 'object' && !Array.isArray(top.container)) {
177
249
  top.container[key] = child;
178
- stack.push({ indent, container: child });
250
+ stack.push({ indent, container: child, isArray: nextIsArray });
179
251
  }
180
252
  } else if (top.container && typeof top.container === 'object' && !Array.isArray(top.container)) {
181
253
  top.container[key] = parseScalar(rest);