burnoff 1.3.0 → 1.4.1

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,294 +1,307 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- export const DEFAULT_POLICY = Object.freeze({
5
- guards: Object.freeze({
6
- mode: 'guard',
7
- det01Enabled: true,
8
- det02Enabled: true,
9
- det03Enabled: true,
10
- det04Enabled: true,
11
- det04Threshold: 3,
12
- secretAllow: Object.freeze([]),
13
- strictTestIntegrity: false,
14
- scopeLockEnabled: true,
15
- subagentFanoutEnabled: true,
16
- subagentFanoutAction: 'advisory',
17
- subagentMaxBurstCount: 4,
18
- subagentBurstWindowSec: 60,
19
- subagentMaxPromptChars: 8000
20
- }),
21
- readClamp: Object.freeze({
22
- enabled: true,
23
- maxLines: 250,
24
- maxBytes: 16384,
25
- neverClampCodeOffCliff: true,
26
- neverClampExt: Object.freeze([]),
27
- headProbeMaxBytes: 8388608,
28
- codeRealizationDiscount: 0.27
29
- }),
30
- postTool: Object.freeze({
31
- fts5Enabled: true,
32
- minBytesToCompress: 6144,
33
- retentionDays: 30,
34
- outputMode: 'auto'
35
- }),
36
- ciBudgetGate: Object.freeze({
37
- maxPrCostUsd: 15,
38
- maxPrTokens: 1_500_000,
39
- maxCacheMissRatio: 0.50,
40
- maxWasteRatio: 0.35,
41
- maxRing0Violations: 0,
42
- mode: 'enforce',
43
- failOnMissingTranscripts: false
44
- })
45
- });
46
-
47
- function cloneDefaultPolicy() {
48
- return {
49
- guards: {
50
- ...DEFAULT_POLICY.guards,
51
- secretAllow: [...DEFAULT_POLICY.guards.secretAllow]
52
- },
53
- readClamp: {
54
- ...DEFAULT_POLICY.readClamp,
55
- neverClampExt: [...DEFAULT_POLICY.readClamp.neverClampExt]
56
- },
57
- postTool: { ...DEFAULT_POLICY.postTool },
58
- ciBudgetGate: { ...DEFAULT_POLICY.ciBudgetGate }
59
- };
60
- }
61
-
62
- function stripInlineComment(line) {
63
- let inSingle = false;
64
- let inDouble = false;
65
- for (let i = 0; i < line.length; i++) {
66
- const ch = line[i];
67
- if (ch === '\'' && !inDouble) inSingle = !inSingle;
68
- else if (ch === '"' && !inSingle) inDouble = !inDouble;
69
- else if (ch === '#' && !inSingle && !inDouble) {
70
- if (i === 0 || /\s/.test(line[i - 1])) {
71
- return line.slice(0, i);
72
- }
73
- }
74
- }
75
- return line;
76
- }
77
-
78
- function parseScalar(raw) {
79
- const s = String(raw ?? '').trim();
80
- if (!s) return '';
81
- if (
82
- (s.startsWith('"') && s.endsWith('"') && s.length >= 2) ||
83
- (s.startsWith('\'') && s.endsWith('\'') && s.length >= 2)
84
- ) {
85
- return s.slice(1, -1);
86
- }
87
- if (s === 'true') return true;
88
- if (s === 'false') return false;
89
- if (s === 'null' || s === '~') return null;
90
- if (/^-?\d+(?:\.\d+)?$/.test(s)) return Number(s);
91
- if (s.startsWith('[') && s.endsWith(']')) {
92
- const inner = s.slice(1, -1).trim();
93
- if (!inner) return [];
94
- return inner.split(',').map((part) => parseScalar(part));
95
- }
96
- return s;
97
- }
98
-
99
- /**
100
- * Zero-dependency YAML subset parser with automatic JSON fallback.
101
- * Supports nested maps via indentation, scalars (bool/number/string/null), inline lists `[a, b]`,
102
- * and block lists (`- item`).
103
- */
104
- export function parseSimpleYaml(text = '') {
105
- const trimmed = String(text || '').trim();
106
- if (!trimmed) return {};
107
- if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
108
- return JSON.parse(trimmed);
109
- }
110
-
111
- const lines = trimmed.split(/\r?\n/);
112
- const root = {};
113
- // Stack entries track { indent, container, pendingKey, parentObj }
114
- const stack = [{ indent: -1, container: root }];
115
-
116
- for (let idx = 0; idx < lines.length; idx++) {
117
- const rawLine = stripInlineComment(lines[idx]);
118
- if (!rawLine.trim()) continue;
119
- if (/^\t|^ *\t/.test(rawLine)) {
120
- throw new SyntaxError(`Invalid YAML tab indentation at line ${idx + 1}`);
121
- }
122
- const indent = rawLine.match(/^ */)[0].length;
123
- const content = rawLine.trim();
124
-
125
- while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {
126
- stack.pop();
127
- }
128
- const top = stack[stack.length - 1];
129
-
130
- if (content === '-' || content.startsWith('- ')) {
131
- const itemText = content.slice(2).trim();
132
- if (!Array.isArray(top.container)) {
133
- throw new SyntaxError(`Unexpected YAML list item at line ${idx + 1}`);
134
- }
135
- top.container.push(parseScalar(itemText));
136
- continue;
137
- }
138
-
139
- const colonIdx = content.indexOf(':');
140
- if (colonIdx === -1) {
141
- throw new SyntaxError(`Invalid YAML syntax (missing ':') at line ${idx + 1}`);
142
- }
143
-
144
- const key = content.slice(0, colonIdx).trim().replace(/^['"]|['"]$/g, '');
145
- const rest = content.slice(colonIdx + 1).trim();
146
- if (!key) {
147
- throw new SyntaxError(`Invalid YAML empty key at line ${idx + 1}`);
148
- }
149
-
150
- if (rest === '') {
151
- // Peek next non-empty line to determine object vs array
152
- let nextIsArray = false;
153
- for (let j = idx + 1; j < lines.length; j++) {
154
- const peek = stripInlineComment(lines[j]);
155
- if (!peek.trim()) continue;
156
- const peekIndent = peek.match(/^ */)[0].length;
157
- if (peekIndent > indent && peek.trim().startsWith('- ')) {
158
- nextIsArray = true;
159
- }
160
- break;
161
- }
162
- const child = nextIsArray ? [] : {};
163
- if (top.container && typeof top.container === 'object' && !Array.isArray(top.container)) {
164
- top.container[key] = child;
165
- stack.push({ indent, container: child });
166
- }
167
- } else if (top.container && typeof top.container === 'object' && !Array.isArray(top.container)) {
168
- top.container[key] = parseScalar(rest);
169
- }
170
- }
171
-
172
- return root;
173
- }
174
-
175
- function mergePolicy(base, override) {
176
- const result = cloneDefaultPolicy();
177
- if (!override || typeof override !== 'object') return result;
178
-
179
- for (const section of ['guards', 'readClamp', 'postTool', 'ciBudgetGate']) {
180
- if (override[section] && typeof override[section] === 'object' && !Array.isArray(override[section])) {
181
- result[section] = { ...result[section], ...override[section] };
182
- }
183
- }
184
- if (Array.isArray(result.guards.secretAllow)) {
185
- result.guards.secretAllow = result.guards.secretAllow
186
- .map((item) => String(item || '').trim())
187
- .filter(Boolean);
188
- } else {
189
- result.guards.secretAllow = [];
190
- }
191
- if (Array.isArray(result.readClamp.neverClampExt)) {
192
- result.readClamp.neverClampExt = result.readClamp.neverClampExt
193
- .map((item) => String(item || '').trim().toLowerCase())
194
- .filter(Boolean)
195
- .map((ext) => (ext.startsWith('.') ? ext : `.${ext}`));
196
- } else {
197
- result.readClamp.neverClampExt = [];
198
- }
199
- for (const [k, v] of Object.entries(override)) {
200
- if (!(k in result)) {
201
- result[k] = v;
202
- }
203
- }
204
- return result;
205
- }
206
-
207
- const POLICY_CACHE = new Map();
208
- const POLICY_CACHE_TTL_MS = 500;
209
-
210
- export function clearBurnoffPolicyCache() {
211
- POLICY_CACHE.clear();
212
- }
213
-
214
- /**
215
- * Loads `.burnoff.yaml` (or `.burnoff.yml`) from `cwd` and merges with `DEFAULT_POLICY`.
216
- */
217
- export function loadBurnoffPolicy(cwd = process.cwd()) {
218
- const baseDir = path.resolve(cwd || process.cwd());
219
- const nowMs = Date.now();
220
- const cached = POLICY_CACHE.get(baseDir);
221
- if (cached && nowMs - cached.ts < POLICY_CACHE_TTL_MS) {
222
- try {
223
- if (cached.value.sourcePath) {
224
- const st = fs.statSync(cached.value.sourcePath);
225
- if (st.mtimeMs === cached.mtimeMs) {
226
- return cached.value;
227
- }
228
- } else if (
229
- !fs.existsSync(path.join(baseDir, '.burnoff.yaml')) &&
230
- !fs.existsSync(path.join(baseDir, '.burnoff.yml'))
231
- ) {
232
- return cached.value;
233
- }
234
- } catch {
235
- // ignore: stat/exists check failure invalidates cache entry cleanly
236
- }
237
- }
238
-
239
- for (const name of ['.burnoff.yaml', '.burnoff.yml']) {
240
- const candidate = path.join(baseDir, name);
241
- if (!fs.existsSync(candidate)) continue;
242
- let mtimeMs = 0;
243
- try {
244
- mtimeMs = fs.statSync(candidate).mtimeMs;
245
- } catch {
246
- // ignore: fallback mtimeMs = 0
247
- }
248
- try {
249
- const raw = fs.readFileSync(candidate, 'utf8');
250
- const parsed = parseSimpleYaml(raw);
251
- const rawCiBudgetGate =
252
- parsed?.ciBudgetGate && typeof parsed.ciBudgetGate === 'object' && !Array.isArray(parsed.ciBudgetGate)
253
- ? { ...parsed.ciBudgetGate }
254
- : {};
255
- const value = {
256
- ...mergePolicy(DEFAULT_POLICY, parsed),
257
- rawCiBudgetGate,
258
- sourcePath: candidate,
259
- exists: true
260
- };
261
- if (POLICY_CACHE.size > 64) POLICY_CACHE.clear();
262
- POLICY_CACHE.set(baseDir, { ts: nowMs, mtimeMs, value });
263
- return value;
264
- } catch (err) {
265
- const value = {
266
- ...cloneDefaultPolicy(),
267
- rawCiBudgetGate: {},
268
- sourcePath: candidate,
269
- exists: true,
270
- parseError: true,
271
- parseErrorMessage: err?.message || 'Invalid YAML syntax'
272
- };
273
- if (POLICY_CACHE.size > 64) POLICY_CACHE.clear();
274
- POLICY_CACHE.set(baseDir, { ts: nowMs, mtimeMs, value });
275
- return value;
276
- }
277
- }
278
-
279
- const value = {
280
- ...cloneDefaultPolicy(),
281
- sourcePath: null,
282
- exists: false
283
- };
284
- if (POLICY_CACHE.size > 64) POLICY_CACHE.clear();
285
- POLICY_CACHE.set(baseDir, { ts: nowMs, mtimeMs: 0, value });
286
- return value;
287
- }
288
-
289
- export default {
290
- DEFAULT_POLICY,
291
- parseSimpleYaml,
292
- loadBurnoffPolicy,
293
- clearBurnoffPolicyCache
294
- };
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ export const DEFAULT_POLICY = Object.freeze({
5
+ guards: Object.freeze({
6
+ mode: 'guard',
7
+ det01Enabled: true,
8
+ det02Enabled: true,
9
+ det03Enabled: true,
10
+ det04Enabled: true,
11
+ det04Threshold: 3,
12
+ secretAllow: Object.freeze([]),
13
+ strictTestIntegrity: false,
14
+ scopeLockEnabled: true,
15
+ subagentFanoutEnabled: true,
16
+ subagentFanoutAction: 'advisory',
17
+ subagentMaxBurstCount: 4,
18
+ subagentBurstWindowSec: 60,
19
+ subagentMaxPromptChars: 8000,
20
+ det07Enabled: true,
21
+ det07Action: 'ask',
22
+ det07ReadBypassMaxBytes: 16384,
23
+ det07ReadBypassMaxLines: 250,
24
+ det08Enabled: true,
25
+ det08Action: 'ask',
26
+ det08CheckTestSkip: true,
27
+ det08CheckEmptyCatch: true,
28
+ det09Enabled: true,
29
+ det09Action: 'ask',
30
+ det09MaxEditsPerFile: 5,
31
+ det09WindowSec: 300,
32
+ inspectReadOnlyTools: false
33
+ }),
34
+ readClamp: Object.freeze({
35
+ enabled: true,
36
+ maxLines: 250,
37
+ maxBytes: 16384,
38
+ neverClampCodeOffCliff: true,
39
+ neverClampExt: Object.freeze([]),
40
+ headProbeMaxBytes: 8388608,
41
+ codeRealizationDiscount: 0.27
42
+ }),
43
+ postTool: Object.freeze({
44
+ fts5Enabled: true,
45
+ minBytesToCompress: 6144,
46
+ retentionDays: 30,
47
+ outputMode: 'replace'
48
+ }),
49
+ ciBudgetGate: Object.freeze({
50
+ maxPrCostUsd: 15,
51
+ maxPrTokens: 1_500_000,
52
+ maxCacheMissRatio: 0.50,
53
+ maxWasteRatio: 0.35,
54
+ maxRing0Violations: 0,
55
+ mode: 'enforce',
56
+ failOnMissingTranscripts: false
57
+ })
58
+ });
59
+
60
+ function cloneDefaultPolicy() {
61
+ return {
62
+ guards: {
63
+ ...DEFAULT_POLICY.guards,
64
+ secretAllow: [...DEFAULT_POLICY.guards.secretAllow]
65
+ },
66
+ readClamp: {
67
+ ...DEFAULT_POLICY.readClamp,
68
+ neverClampExt: [...DEFAULT_POLICY.readClamp.neverClampExt]
69
+ },
70
+ postTool: { ...DEFAULT_POLICY.postTool },
71
+ ciBudgetGate: { ...DEFAULT_POLICY.ciBudgetGate }
72
+ };
73
+ }
74
+
75
+ function stripInlineComment(line) {
76
+ let inSingle = false;
77
+ let inDouble = false;
78
+ for (let i = 0; i < line.length; i++) {
79
+ const ch = line[i];
80
+ if (ch === '\'' && !inDouble) inSingle = !inSingle;
81
+ else if (ch === '"' && !inSingle) inDouble = !inDouble;
82
+ else if (ch === '#' && !inSingle && !inDouble) {
83
+ if (i === 0 || /\s/.test(line[i - 1])) {
84
+ return line.slice(0, i);
85
+ }
86
+ }
87
+ }
88
+ return line;
89
+ }
90
+
91
+ function parseScalar(raw) {
92
+ const s = String(raw ?? '').trim();
93
+ if (!s) return '';
94
+ if (
95
+ (s.startsWith('"') && s.endsWith('"') && s.length >= 2) ||
96
+ (s.startsWith('\'') && s.endsWith('\'') && s.length >= 2)
97
+ ) {
98
+ return s.slice(1, -1);
99
+ }
100
+ if (s === 'true') return true;
101
+ if (s === 'false') return false;
102
+ if (s === 'null' || s === '~') return null;
103
+ if (/^-?\d+(?:\.\d+)?$/.test(s)) return Number(s);
104
+ if (s.startsWith('[') && s.endsWith(']')) {
105
+ const inner = s.slice(1, -1).trim();
106
+ if (!inner) return [];
107
+ return inner.split(',').map((part) => parseScalar(part));
108
+ }
109
+ return s;
110
+ }
111
+
112
+ /**
113
+ * Zero-dependency YAML subset parser with automatic JSON fallback.
114
+ * Supports nested maps via indentation, scalars (bool/number/string/null), inline lists `[a, b]`,
115
+ * and block lists (`- item`).
116
+ */
117
+ export function parseSimpleYaml(text = '') {
118
+ const trimmed = String(text || '').trim();
119
+ if (!trimmed) return {};
120
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
121
+ return JSON.parse(trimmed);
122
+ }
123
+
124
+ const lines = trimmed.split(/\r?\n/);
125
+ const root = {};
126
+ // Stack entries track { indent, container, pendingKey, parentObj }
127
+ const stack = [{ indent: -1, container: root }];
128
+
129
+ for (let idx = 0; idx < lines.length; idx++) {
130
+ const rawLine = stripInlineComment(lines[idx]);
131
+ if (!rawLine.trim()) continue;
132
+ if (/^\t|^ *\t/.test(rawLine)) {
133
+ throw new SyntaxError(`Invalid YAML tab indentation at line ${idx + 1}`);
134
+ }
135
+ const indent = rawLine.match(/^ */)[0].length;
136
+ const content = rawLine.trim();
137
+
138
+ while (stack.length > 1 && indent <= stack[stack.length - 1].indent) {
139
+ stack.pop();
140
+ }
141
+ const top = stack[stack.length - 1];
142
+
143
+ if (content === '-' || content.startsWith('- ')) {
144
+ const itemText = content.slice(2).trim();
145
+ if (!Array.isArray(top.container)) {
146
+ throw new SyntaxError(`Unexpected YAML list item at line ${idx + 1}`);
147
+ }
148
+ top.container.push(parseScalar(itemText));
149
+ continue;
150
+ }
151
+
152
+ const colonIdx = content.indexOf(':');
153
+ if (colonIdx === -1) {
154
+ throw new SyntaxError(`Invalid YAML syntax (missing ':') at line ${idx + 1}`);
155
+ }
156
+
157
+ const key = content.slice(0, colonIdx).trim().replace(/^['"]|['"]$/g, '');
158
+ const rest = content.slice(colonIdx + 1).trim();
159
+ if (!key) {
160
+ throw new SyntaxError(`Invalid YAML empty key at line ${idx + 1}`);
161
+ }
162
+
163
+ if (rest === '') {
164
+ // Peek next non-empty line to determine object vs array
165
+ let nextIsArray = false;
166
+ for (let j = idx + 1; j < lines.length; j++) {
167
+ const peek = stripInlineComment(lines[j]);
168
+ if (!peek.trim()) continue;
169
+ const peekIndent = peek.match(/^ */)[0].length;
170
+ if (peekIndent > indent && peek.trim().startsWith('- ')) {
171
+ nextIsArray = true;
172
+ }
173
+ break;
174
+ }
175
+ const child = nextIsArray ? [] : {};
176
+ if (top.container && typeof top.container === 'object' && !Array.isArray(top.container)) {
177
+ top.container[key] = child;
178
+ stack.push({ indent, container: child });
179
+ }
180
+ } else if (top.container && typeof top.container === 'object' && !Array.isArray(top.container)) {
181
+ top.container[key] = parseScalar(rest);
182
+ }
183
+ }
184
+
185
+ return root;
186
+ }
187
+
188
+ function mergePolicy(base, override) {
189
+ const result = cloneDefaultPolicy();
190
+ if (!override || typeof override !== 'object') return result;
191
+
192
+ for (const section of ['guards', 'readClamp', 'postTool', 'ciBudgetGate']) {
193
+ if (override[section] && typeof override[section] === 'object' && !Array.isArray(override[section])) {
194
+ result[section] = { ...result[section], ...override[section] };
195
+ }
196
+ }
197
+ if (Array.isArray(result.guards.secretAllow)) {
198
+ result.guards.secretAllow = result.guards.secretAllow
199
+ .map((item) => String(item || '').trim())
200
+ .filter(Boolean);
201
+ } else {
202
+ result.guards.secretAllow = [];
203
+ }
204
+ if (Array.isArray(result.readClamp.neverClampExt)) {
205
+ result.readClamp.neverClampExt = result.readClamp.neverClampExt
206
+ .map((item) => String(item || '').trim().toLowerCase())
207
+ .filter(Boolean)
208
+ .map((ext) => (ext.startsWith('.') ? ext : `.${ext}`));
209
+ } else {
210
+ result.readClamp.neverClampExt = [];
211
+ }
212
+ for (const [k, v] of Object.entries(override)) {
213
+ if (!(k in result)) {
214
+ result[k] = v;
215
+ }
216
+ }
217
+ return result;
218
+ }
219
+
220
+ const POLICY_CACHE = new Map();
221
+ const POLICY_CACHE_TTL_MS = 500;
222
+
223
+ export function clearBurnoffPolicyCache() {
224
+ POLICY_CACHE.clear();
225
+ }
226
+
227
+ /**
228
+ * Loads `.burnoff.yaml` (or `.burnoff.yml`) from `cwd` and merges with `DEFAULT_POLICY`.
229
+ */
230
+ export function loadBurnoffPolicy(cwd = process.cwd()) {
231
+ const baseDir = path.resolve(cwd || process.cwd());
232
+ const nowMs = Date.now();
233
+ const cached = POLICY_CACHE.get(baseDir);
234
+ if (cached && nowMs - cached.ts < POLICY_CACHE_TTL_MS) {
235
+ try {
236
+ if (cached.value.sourcePath) {
237
+ const st = fs.statSync(cached.value.sourcePath);
238
+ if (st.mtimeMs === cached.mtimeMs) {
239
+ return cached.value;
240
+ }
241
+ } else if (
242
+ !fs.existsSync(path.join(baseDir, '.burnoff.yaml')) &&
243
+ !fs.existsSync(path.join(baseDir, '.burnoff.yml'))
244
+ ) {
245
+ return cached.value;
246
+ }
247
+ } catch {
248
+ // ignore: stat/exists check failure invalidates cache entry cleanly
249
+ }
250
+ }
251
+
252
+ for (const name of ['.burnoff.yaml', '.burnoff.yml']) {
253
+ const candidate = path.join(baseDir, name);
254
+ if (!fs.existsSync(candidate)) continue;
255
+ let mtimeMs = 0;
256
+ try {
257
+ mtimeMs = fs.statSync(candidate).mtimeMs;
258
+ } catch {
259
+ // ignore: fallback mtimeMs = 0
260
+ }
261
+ try {
262
+ const raw = fs.readFileSync(candidate, 'utf8');
263
+ const parsed = parseSimpleYaml(raw);
264
+ const rawCiBudgetGate =
265
+ parsed?.ciBudgetGate && typeof parsed.ciBudgetGate === 'object' && !Array.isArray(parsed.ciBudgetGate)
266
+ ? { ...parsed.ciBudgetGate }
267
+ : {};
268
+ const value = {
269
+ ...mergePolicy(DEFAULT_POLICY, parsed),
270
+ rawCiBudgetGate,
271
+ sourcePath: candidate,
272
+ exists: true
273
+ };
274
+ if (POLICY_CACHE.size > 64) POLICY_CACHE.clear();
275
+ POLICY_CACHE.set(baseDir, { ts: nowMs, mtimeMs, value });
276
+ return value;
277
+ } catch (err) {
278
+ const value = {
279
+ ...cloneDefaultPolicy(),
280
+ rawCiBudgetGate: {},
281
+ sourcePath: candidate,
282
+ exists: true,
283
+ parseError: true,
284
+ parseErrorMessage: err?.message || 'Invalid YAML syntax'
285
+ };
286
+ if (POLICY_CACHE.size > 64) POLICY_CACHE.clear();
287
+ POLICY_CACHE.set(baseDir, { ts: nowMs, mtimeMs, value });
288
+ return value;
289
+ }
290
+ }
291
+
292
+ const value = {
293
+ ...cloneDefaultPolicy(),
294
+ sourcePath: null,
295
+ exists: false
296
+ };
297
+ if (POLICY_CACHE.size > 64) POLICY_CACHE.clear();
298
+ POLICY_CACHE.set(baseDir, { ts: nowMs, mtimeMs: 0, value });
299
+ return value;
300
+ }
301
+
302
+ export default {
303
+ DEFAULT_POLICY,
304
+ parseSimpleYaml,
305
+ loadBurnoffPolicy,
306
+ clearBurnoffPolicyCache
307
+ };