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.
- package/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/burnoff-pr-gate.yml +5 -3
- package/.github/workflows/burnoff-startup-lint.yml +2 -2
- package/CHANGELOG.md +74 -0
- package/README.md +187 -213
- package/SECURITY.md +38 -0
- package/bin/burnoff.mjs +307 -32
- package/commands/burnoff.md +6 -4
- package/docs/CLAUDE_CODE_PLUGIN.md +29 -28
- package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
- package/hooks/hook-io.mjs +216 -11
- package/hooks/hooks.json +44 -0
- package/hooks/post-tool-use.mjs +3 -1
- package/hooks/pre-tool-use.mjs +47 -8
- package/hooks/session-lifecycle.mjs +24 -3
- package/hooks/user-prompt-submit.mjs +98 -0
- package/package.json +6 -4
- package/scripts/bench-hooks.mjs +34 -3
- package/scripts/bench-savings.mjs +318 -0
- package/scripts/burnoff-statusline.mjs +138 -6
- package/src/ci/ci-gate.mjs +199 -13
- package/src/ci/pr-cost.mjs +417 -45
- package/src/ci/pr-summary.mjs +467 -0
- package/src/cli/audit.mjs +179 -28
- package/src/cli/doctor.mjs +32 -6
- package/src/cli/hook-health.mjs +9 -1
- package/src/cli/init.mjs +226 -39
- package/src/cli/preview.mjs +299 -0
- package/src/cli/startup-audit/formatter.mjs +248 -0
- package/src/cli/startup-audit/jsonc.mjs +601 -0
- package/src/cli/startup-audit/mcp-audit.mjs +735 -0
- package/src/cli/startup-audit/rules-hygiene.mjs +645 -0
- package/src/cli/startup-audit/telemetry-scan.mjs +975 -0
- package/src/cli/startup-audit.mjs +451 -2471
- package/src/clients/claude-code.mjs +41 -4
- package/src/config/catalog.json +295 -0
- package/src/config/effort.mjs +145 -0
- package/src/config/harness-quirks.mjs +340 -0
- package/src/config/loader.mjs +27 -2
- package/src/config/policy.mjs +81 -9
- package/src/config/pricing.mjs +247 -19
- package/src/config/semver.mjs +25 -0
- package/src/config/uncached-attribution.mjs +280 -41
- package/src/guards/compaction-baton.mjs +248 -0
- package/src/guards/loop-breaker.mjs +328 -47
- package/src/guards/model-switch-hook.mjs +126 -0
- package/src/guards/phase5-detectors.mjs +275 -21
- package/src/guards/post-tool-engine.mjs +333 -11
- package/src/guards/pre-tool-engine.mjs +607 -45
- package/src/guards/prefix-guard.mjs +609 -0
- package/src/guards/prompt-guard.mjs +309 -0
- package/src/guards/read-clamp.mjs +192 -8
- package/src/guards/session-hook.mjs +149 -7
- package/src/guards/shell-guard.mjs +56 -5
- package/src/guards/snooze.mjs +169 -5
- package/src/ipc/daemon.mjs +76 -0
- package/src/ipc/fast-client.mjs +165 -4
- package/src/ipc/protocol.mjs +16 -3
- package/src/storage/antigravity-parser.mjs +16 -2
- package/src/storage/file-lock.mjs +16 -3
- package/src/storage/jsonl-parser.mjs +133 -22
- package/src/storage/telemetry-metrics.mjs +254 -4
|
@@ -0,0 +1,645 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/cli/startup-audit/rules-hygiene.mjs
|
|
3
|
+
* Markdown rules token/count/contradiction auditing, prompt volatility, and skill frontmatter checks.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
import { canonicalizePath } from '../../config/paths.mjs';
|
|
9
|
+
import { CHARS_PER_TOKEN } from './jsonc.mjs';
|
|
10
|
+
|
|
11
|
+
export const RULES_THRESHOLDS = Object.freeze({
|
|
12
|
+
cautionRuleCount: 100,
|
|
13
|
+
ifScaleCliffRuleCount: 200,
|
|
14
|
+
cautionTokenWarning: 4500,
|
|
15
|
+
tokenWarning: 8000
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
export const SKILL_DESCRIPTION_MAX_CHARS = 1024;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Counts discrete imperative bullets and numbered rules in markdown, ignoring fenced code blocks
|
|
23
|
+
* and markdown table separator rows.
|
|
24
|
+
*/
|
|
25
|
+
export function countDiscreteRules(markdown) {
|
|
26
|
+
const lines = String(markdown || '').split(/\r?\n/);
|
|
27
|
+
let inFence = false;
|
|
28
|
+
let fenceChar = '';
|
|
29
|
+
let count = 0;
|
|
30
|
+
|
|
31
|
+
for (const line of lines) {
|
|
32
|
+
const fenceMatch = line.match(/^\s*(```+|~~~+)/);
|
|
33
|
+
if (fenceMatch) {
|
|
34
|
+
const markerChar = fenceMatch[1][0];
|
|
35
|
+
if (!inFence) {
|
|
36
|
+
inFence = true;
|
|
37
|
+
fenceChar = markerChar;
|
|
38
|
+
} else if (markerChar === fenceChar) {
|
|
39
|
+
inFence = false;
|
|
40
|
+
fenceChar = '';
|
|
41
|
+
}
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (inFence) continue;
|
|
45
|
+
if (/^\s*\|?(?:\s*:?-+:?\s*\|)+\s*$/.test(line)) continue;
|
|
46
|
+
if (/^\s*(?:[-*+]|\d+\.)\s+\S/.test(line)) {
|
|
47
|
+
count += 1;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return count;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const RULE_CONTRADICTION_NEG_RE =
|
|
54
|
+
/\b(?:never|do\s+not|don'?t|avoid|forbid(?:den)?|prohibit(?:ed)?|must\s+not)\b/i;
|
|
55
|
+
const RULE_CONTRADICTION_POS_RE = /\b(?:always|must|require[ds]?|enforce)\b/i;
|
|
56
|
+
const RULE_CONTRADICTION_STOPWORDS = new Set([
|
|
57
|
+
'the', 'and', 'for', 'with', 'you', 'your', 'that', 'this', 'from', 'into', 'when', 'before', 'after',
|
|
58
|
+
'all', 'every', 'any', 'file', 'files', 'code', 'always', 'never', 'must', 'not', 'avoid', 'only',
|
|
59
|
+
'prefer', 'should', 'would', 'could', 'are', 'was', 'were', 'can', 'will', 'please', 'sure', 'make',
|
|
60
|
+
'keep', 'ensure', 'than', 'then', 'over', 'under', 'about', 'using', 'used'
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
function extractContradictionTerms(lineText = '') {
|
|
64
|
+
const cleaned = String(lineText || '')
|
|
65
|
+
.toLowerCase()
|
|
66
|
+
.replace(/`[^`]*`/g, (m) => m.slice(1, -1))
|
|
67
|
+
.replace(/[^a-z0-9\s_-]/g, ' ');
|
|
68
|
+
const terms = new Set();
|
|
69
|
+
for (const rawWord of cleaned.split(/\s+/)) {
|
|
70
|
+
const w = rawWord.trim();
|
|
71
|
+
if (w.length < 3) continue;
|
|
72
|
+
if (RULE_CONTRADICTION_STOPWORDS.has(w)) continue;
|
|
73
|
+
terms.add(w);
|
|
74
|
+
}
|
|
75
|
+
return terms;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* BO-CFG-12: Detects Always/NEVER polarity-pair contradictions outside fenced code blocks in rules files.
|
|
80
|
+
*/
|
|
81
|
+
export function detectRuleContradictions(text = '', filePath = '') {
|
|
82
|
+
const raw = String(text || '');
|
|
83
|
+
if (!raw.trim()) return [];
|
|
84
|
+
const normLines = raw.replace(/\r\n/g, '\n').split('\n');
|
|
85
|
+
const posDirectives = [];
|
|
86
|
+
const negDirectives = [];
|
|
87
|
+
let inFence = false;
|
|
88
|
+
|
|
89
|
+
for (let i = 0; i < normLines.length; i += 1) {
|
|
90
|
+
const line = normLines[i];
|
|
91
|
+
const trimmed = line.trim();
|
|
92
|
+
if (/^```/.test(trimmed)) {
|
|
93
|
+
inFence = !inFence;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (inFence || !trimmed || /^#/.test(trimmed)) continue;
|
|
97
|
+
|
|
98
|
+
const isNeg = RULE_CONTRADICTION_NEG_RE.test(trimmed);
|
|
99
|
+
const isPos = !isNeg && RULE_CONTRADICTION_POS_RE.test(trimmed);
|
|
100
|
+
if (!isNeg && !isPos) continue;
|
|
101
|
+
|
|
102
|
+
const terms = extractContradictionTerms(trimmed);
|
|
103
|
+
if (terms.size < 2) continue;
|
|
104
|
+
|
|
105
|
+
const entry = { line: i + 1, text: trimmed, terms };
|
|
106
|
+
if (isNeg) negDirectives.push(entry);
|
|
107
|
+
else posDirectives.push(entry);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const contradictions = [];
|
|
111
|
+
const seenPairs = new Set();
|
|
112
|
+
for (const pos of posDirectives) {
|
|
113
|
+
for (const neg of negDirectives) {
|
|
114
|
+
let intersection = 0;
|
|
115
|
+
for (const term of pos.terms) {
|
|
116
|
+
if (neg.terms.has(term)) intersection += 1;
|
|
117
|
+
}
|
|
118
|
+
if (intersection < 2) continue;
|
|
119
|
+
const union = pos.terms.size + neg.terms.size - intersection;
|
|
120
|
+
const jaccard = union > 0 ? intersection / union : 0;
|
|
121
|
+
const overlap = Math.min(pos.terms.size, neg.terms.size) > 0
|
|
122
|
+
? intersection / Math.min(pos.terms.size, neg.terms.size)
|
|
123
|
+
: 0;
|
|
124
|
+
if ((intersection >= 2 && jaccard >= 0.5) || (intersection >= 3 && overlap >= 0.6)) {
|
|
125
|
+
const sig = `${pos.text.toLowerCase()}::${neg.text.toLowerCase()}`;
|
|
126
|
+
if (seenPairs.has(sig)) continue;
|
|
127
|
+
seenPairs.add(sig);
|
|
128
|
+
contradictions.push({
|
|
129
|
+
ruleId: 'BO-CFG-12',
|
|
130
|
+
file: filePath ? String(filePath).replace(/\\/g, '/') : null,
|
|
131
|
+
linePos: pos.line,
|
|
132
|
+
lineNeg: neg.line,
|
|
133
|
+
textPos: pos.text.slice(0, 180),
|
|
134
|
+
textNeg: neg.text.slice(0, 180),
|
|
135
|
+
overlapCount: intersection,
|
|
136
|
+
jaccard: Number(jaccard.toFixed(3))
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return contradictions;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function auditRulesFiles(filePaths = []) {
|
|
145
|
+
const seen = new Set();
|
|
146
|
+
const files = [];
|
|
147
|
+
const contradictions = [];
|
|
148
|
+
let totalTokensEst = 0;
|
|
149
|
+
let totalRuleCount = 0;
|
|
150
|
+
|
|
151
|
+
for (const fp of filePaths) {
|
|
152
|
+
if (!fp || !fs.existsSync(fp)) continue;
|
|
153
|
+
let dedupeKey = canonicalizePath(fp);
|
|
154
|
+
try {
|
|
155
|
+
dedupeKey = canonicalizePath(fs.realpathSync(fp));
|
|
156
|
+
} catch {
|
|
157
|
+
// ignore: fallback to canonicalized path when realpath fails
|
|
158
|
+
}
|
|
159
|
+
if (seen.has(dedupeKey)) continue;
|
|
160
|
+
seen.add(dedupeKey);
|
|
161
|
+
|
|
162
|
+
try {
|
|
163
|
+
const text = fs.readFileSync(fp, 'utf8');
|
|
164
|
+
const chars = text.length;
|
|
165
|
+
const tokensEst = Math.ceil(chars / CHARS_PER_TOKEN);
|
|
166
|
+
const ruleCount = countDiscreteRules(text);
|
|
167
|
+
const fileContradictions = detectRuleContradictions(text, fp);
|
|
168
|
+
if (fileContradictions.length > 0) {
|
|
169
|
+
contradictions.push(...fileContradictions);
|
|
170
|
+
}
|
|
171
|
+
files.push({
|
|
172
|
+
path: String(fp).replace(/\\/g, '/'),
|
|
173
|
+
chars,
|
|
174
|
+
tokensEst,
|
|
175
|
+
ruleCount,
|
|
176
|
+
contradictionCount: fileContradictions.length
|
|
177
|
+
});
|
|
178
|
+
totalTokensEst += tokensEst;
|
|
179
|
+
totalRuleCount += ruleCount;
|
|
180
|
+
} catch {
|
|
181
|
+
// ignore: unreadable rules markdown file
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
let status = 'pass';
|
|
186
|
+
const advisories = [];
|
|
187
|
+
if (totalRuleCount >= RULES_THRESHOLDS.ifScaleCliffRuleCount) {
|
|
188
|
+
status = 'warn';
|
|
189
|
+
advisories.push(
|
|
190
|
+
`IFScale instruction cliff exceeded (${totalRuleCount} >= ${RULES_THRESHOLDS.ifScaleCliffRuleCount} rules); keep hard safety invariants as concise 1-line rules in CLAUDE.md or PreToolUse hooks and move verbose domain workflows into on-demand SKILL.md files.`
|
|
191
|
+
);
|
|
192
|
+
} else if (totalRuleCount >= RULES_THRESHOLDS.cautionRuleCount) {
|
|
193
|
+
status = 'caution';
|
|
194
|
+
advisories.push(
|
|
195
|
+
`Approaching IFScale instruction adherence drop-off (${totalRuleCount} >= ${RULES_THRESHOLDS.cautionRuleCount} rules).`
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
if (totalTokensEst >= RULES_THRESHOLDS.tokenWarning) {
|
|
199
|
+
status = 'warn';
|
|
200
|
+
advisories.push(
|
|
201
|
+
`Static Turn-0 prefix bloat (${totalTokensEst} >= ${RULES_THRESHOLDS.tokenWarning} est. tokens across active rules files).`
|
|
202
|
+
);
|
|
203
|
+
} else if (totalTokensEst >= RULES_THRESHOLDS.cautionTokenWarning) {
|
|
204
|
+
if (status === 'pass') status = 'caution';
|
|
205
|
+
advisories.push(
|
|
206
|
+
`Static rules approaching saturation (${totalTokensEst} >= ${RULES_THRESHOLDS.cautionTokenWarning} est. tokens); keep hard safety invariants in CLAUDE.md/hooks and split verbose domain guidelines into modular, demand-loaded SKILL.md files.`
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
if (contradictions.length > 0) {
|
|
210
|
+
status = 'warn';
|
|
211
|
+
advisories.push(
|
|
212
|
+
`Conflicting directives detected (BO-CFG-12): ${contradictions.length} Always/NEVER contradiction(s) found across rules files ("${contradictions[0].textPos}" vs "${contradictions[0].textNeg}").`
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return { files, totalTokensEst, totalRuleCount, contradictions, status, advisories };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
const VOLATILE_NEGATION_RE =
|
|
221
|
+
/\b(?:never|do\s+not|don't|avoid|forbid|forbidden|prohibit|anti-pattern|breaks?\s+(?:the\s+)?(?:kv\s+|prompt\s+)?cache|invalidat(?:e|es|ing)\s+(?:the\s+)?(?:kv\s+|prompt\s+)?cache)\b/i;
|
|
222
|
+
const VOLATILE_TEMPLATE_RE =
|
|
223
|
+
/(\{\{\s*(?:timestamp|now|current_time|current_date|date|time|uuid|request_id|session_uuid)\s*\}\}|\$\{\s*(?:Date\.now\(\)|new\s+Date\(|crypto\.randomUUID\()|\$\(\s*(?:date\b|uuidgen\b))/i;
|
|
224
|
+
const VOLATILE_INSTRUCTION_RE =
|
|
225
|
+
/\b(?:always|must|every\s+(?:turn|request|prompt)|prepend|inject|include|embed|insert|put)\b.{0,70}\b(?:current\s+(?:timestamp|time|date(?:\s+and\s+time)?)|live\s+timestamp|unix\s+timestamp|epoch\s+time|random\s+uuid|uuidv4|unique\s+request[_\s-]?id)\b/i;
|
|
226
|
+
const SESSION_START_VOLATILE_CMD_RE =
|
|
227
|
+
/\b(?:date\s+(?:\+|-[uIr])|Get-Date\b|uuidgen\b|New-Guid\b|Date\.now\(\)|randomUUID\(\))/i;
|
|
228
|
+
const SESSION_START_AGENT_WRITE_RE =
|
|
229
|
+
/(?:>>?\s*["']?[^\s"'|;&]*\.claude[\\/]agents[\\/]|(?:\b(?:cp|mv|tee|install|Set-Content|Add-Content|Out-File|Copy-Item)\b|sed\s+-i)[^\r\n]*\.claude[\\/]agents[\\/])/i;
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Scans markdown rule text (outside fenced code blocks) for volatile timestamp/UUID
|
|
233
|
+
* prompt-prefix patterns that invalidate KV prefix caches every turn.
|
|
234
|
+
*/
|
|
235
|
+
export function scanVolatilePromptPatterns(markdown = '') {
|
|
236
|
+
const lines = String(markdown || '').split(/\r?\n/);
|
|
237
|
+
const findings = [];
|
|
238
|
+
let inFence = false;
|
|
239
|
+
|
|
240
|
+
for (let i = 0; i < lines.length; i++) {
|
|
241
|
+
const line = lines[i];
|
|
242
|
+
if (/^\s*(?:```|~~~)/.test(line)) {
|
|
243
|
+
inFence = !inFence;
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
if (inFence) continue;
|
|
247
|
+
const trimmed = line.trim();
|
|
248
|
+
if (!trimmed) continue;
|
|
249
|
+
if (VOLATILE_NEGATION_RE.test(trimmed)) continue;
|
|
250
|
+
|
|
251
|
+
if (VOLATILE_TEMPLATE_RE.test(trimmed)) {
|
|
252
|
+
findings.push({
|
|
253
|
+
lineNumber: i + 1,
|
|
254
|
+
patternKind: 'volatile_template',
|
|
255
|
+
snippet: trimmed.slice(0, 140)
|
|
256
|
+
});
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (VOLATILE_INSTRUCTION_RE.test(trimmed)) {
|
|
260
|
+
findings.push({
|
|
261
|
+
lineNumber: i + 1,
|
|
262
|
+
patternKind: 'volatile_instruction',
|
|
263
|
+
snippet: trimmed.slice(0, 140)
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
return {
|
|
269
|
+
matched: findings.length > 0,
|
|
270
|
+
findings
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* BO-CFG-11: Audits active always-on rules files and `SessionStart` hook commands
|
|
276
|
+
* for volatile timestamps, dates, or UUIDs that bust the token-0 prompt prefix.
|
|
277
|
+
*/
|
|
278
|
+
export function auditVolatilePromptPrefix({
|
|
279
|
+
ruleFilePaths = [],
|
|
280
|
+
settingsLayers = [],
|
|
281
|
+
harness = 'claude-code'
|
|
282
|
+
} = {}) {
|
|
283
|
+
const seen = new Set();
|
|
284
|
+
const findings = [];
|
|
285
|
+
const lints = [];
|
|
286
|
+
const remediation =
|
|
287
|
+
'Remove dynamic timestamps/UUIDs from static rules or SessionStart hooks; append turn-specific metadata at the tail of user turns if needed.';
|
|
288
|
+
|
|
289
|
+
for (const fp of ruleFilePaths) {
|
|
290
|
+
if (!fp || !fs.existsSync(fp)) continue;
|
|
291
|
+
let dedupeKey = canonicalizePath(fp);
|
|
292
|
+
try {
|
|
293
|
+
dedupeKey = canonicalizePath(fs.realpathSync(fp));
|
|
294
|
+
} catch {
|
|
295
|
+
// ignore: fallback to canonicalized path when realpath fails
|
|
296
|
+
}
|
|
297
|
+
if (seen.has(dedupeKey)) continue;
|
|
298
|
+
seen.add(dedupeKey);
|
|
299
|
+
|
|
300
|
+
try {
|
|
301
|
+
const text = fs.readFileSync(fp, 'utf8');
|
|
302
|
+
if (harness === 'antigravity') {
|
|
303
|
+
const triggerMode = parseRuleTriggerMode(text);
|
|
304
|
+
if (triggerMode === 'model_decision' || triggerMode === 'manual') continue;
|
|
305
|
+
}
|
|
306
|
+
const scan = scanVolatilePromptPatterns(text);
|
|
307
|
+
if (scan.matched) {
|
|
308
|
+
const normFile = String(fp).replace(/\\/g, '/');
|
|
309
|
+
const first = scan.findings[0];
|
|
310
|
+
findings.push({
|
|
311
|
+
file: normFile,
|
|
312
|
+
sourceType: 'rules_file',
|
|
313
|
+
matches: scan.findings
|
|
314
|
+
});
|
|
315
|
+
lints.push({
|
|
316
|
+
ruleId: 'BO-CFG-11',
|
|
317
|
+
severity: 'warn',
|
|
318
|
+
harness,
|
|
319
|
+
file: normFile,
|
|
320
|
+
message: `Volatile Prompt Prefix Risk (BO-CFG-11): ${normFile}:${first.lineNumber} injects dynamic timestamp/UUID (${first.patternKind}), mutating the token-0 prefix each turn, collapsing KV cache reuse and triggering 1.25x cache-write surcharges.`,
|
|
321
|
+
remediation
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
} catch {
|
|
325
|
+
// ignore: unreadable rules markdown file
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
for (const layerEntry of settingsLayers) {
|
|
330
|
+
const doc = layerEntry?.doc?.parsed;
|
|
331
|
+
if (!doc || typeof doc !== 'object') continue;
|
|
332
|
+
const fileLabel = String(layerEntry?.label || layerEntry?.doc?.path || 'settings.json').replace(/\\/g, '/');
|
|
333
|
+
const sessionStartHooks = doc?.hooks?.SessionStart;
|
|
334
|
+
if (!Array.isArray(sessionStartHooks)) continue;
|
|
335
|
+
const matchedCmds = [];
|
|
336
|
+
const matchedAgentWriteCmds = [];
|
|
337
|
+
for (const entry of sessionStartHooks) {
|
|
338
|
+
const hookList = Array.isArray(entry?.hooks) ? entry.hooks : [entry];
|
|
339
|
+
for (const h of hookList) {
|
|
340
|
+
const cmd = typeof h?.command === 'string' ? h.command.trim() : '';
|
|
341
|
+
if (cmd && SESSION_START_VOLATILE_CMD_RE.test(cmd)) {
|
|
342
|
+
matchedCmds.push(cmd.slice(0, 140));
|
|
343
|
+
}
|
|
344
|
+
if (cmd && SESSION_START_AGENT_WRITE_RE.test(cmd)) {
|
|
345
|
+
matchedAgentWriteCmds.push(cmd.slice(0, 140));
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (matchedCmds.length > 0) {
|
|
350
|
+
findings.push({
|
|
351
|
+
file: fileLabel,
|
|
352
|
+
sourceType: 'session_start_hook',
|
|
353
|
+
commands: matchedCmds
|
|
354
|
+
});
|
|
355
|
+
lints.push({
|
|
356
|
+
ruleId: 'BO-CFG-11',
|
|
357
|
+
severity: 'warn',
|
|
358
|
+
harness,
|
|
359
|
+
file: fileLabel,
|
|
360
|
+
message: `Volatile Prompt Prefix Risk (BO-CFG-11): SessionStart hook in ${fileLabel} runs "${matchedCmds[0]}", mutating the token-0 prefix each turn, collapsing KV cache reuse and triggering 1.25x cache-write surcharges.`,
|
|
361
|
+
remediation
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
if (matchedAgentWriteCmds.length > 0) {
|
|
365
|
+
findings.push({
|
|
366
|
+
file: fileLabel,
|
|
367
|
+
sourceType: 'session_start_agent_write',
|
|
368
|
+
commands: matchedAgentWriteCmds
|
|
369
|
+
});
|
|
370
|
+
lints.push({
|
|
371
|
+
ruleId: 'BO-CFG-11',
|
|
372
|
+
severity: 'warn',
|
|
373
|
+
harness,
|
|
374
|
+
file: fileLabel,
|
|
375
|
+
message: `Subagent Definition Mutation Risk (BO-CFG-11): SessionStart hook in ${fileLabel} writes to .claude/agents/ ("${matchedAgentWriteCmds[0]}"), changing subagent system prompts each session and forcing cold spawns.`,
|
|
376
|
+
remediation:
|
|
377
|
+
'Avoid rewriting .claude/agents/*.md in SessionStart hooks; keep agent definitions static across sessions.'
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
return {
|
|
383
|
+
status: lints.length > 0 ? 'warn' : 'pass',
|
|
384
|
+
findings,
|
|
385
|
+
lints
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
function unquoteYamlScalar(raw = '') {
|
|
390
|
+
const s = String(raw || '').trim();
|
|
391
|
+
if (s.length >= 2 && ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'")))) {
|
|
392
|
+
return s.slice(1, -1).trim();
|
|
393
|
+
}
|
|
394
|
+
return s;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Parses `name` and `description` from SKILL.md YAML frontmatter, including multi-line block scalars.
|
|
399
|
+
*/
|
|
400
|
+
export function parseSkillFrontmatter(markdown = '') {
|
|
401
|
+
const fmMatch = String(markdown || '').match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
402
|
+
if (!fmMatch) return { hasFrontmatter: false, name: null, description: null };
|
|
403
|
+
|
|
404
|
+
const lines = fmMatch[1].split(/\r?\n/);
|
|
405
|
+
let name = null;
|
|
406
|
+
let description = null;
|
|
407
|
+
|
|
408
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
409
|
+
const line = lines[i];
|
|
410
|
+
const keyMatch = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/);
|
|
411
|
+
if (!keyMatch) continue;
|
|
412
|
+
|
|
413
|
+
const key = keyMatch[1].toLowerCase();
|
|
414
|
+
const rawVal = keyMatch[2].trim();
|
|
415
|
+
|
|
416
|
+
if (key === 'name') {
|
|
417
|
+
name = unquoteYamlScalar(rawVal) || null;
|
|
418
|
+
continue;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
if (key === 'description') {
|
|
422
|
+
if (/^[>|][+-]?$/.test(rawVal)) {
|
|
423
|
+
const blockLines = [];
|
|
424
|
+
let j = i + 1;
|
|
425
|
+
while (j < lines.length && (/^\s+/.test(lines[j]) || lines[j].trim() === '')) {
|
|
426
|
+
blockLines.push(lines[j].trim());
|
|
427
|
+
j += 1;
|
|
428
|
+
}
|
|
429
|
+
i = j - 1;
|
|
430
|
+
description = blockLines.filter(Boolean).join(' ').trim() || null;
|
|
431
|
+
} else {
|
|
432
|
+
const single = unquoteYamlScalar(rawVal);
|
|
433
|
+
if (single) {
|
|
434
|
+
description = single;
|
|
435
|
+
} else {
|
|
436
|
+
// Support indented multiline value without explicit > or | block marker
|
|
437
|
+
const blockLines = [];
|
|
438
|
+
let j = i + 1;
|
|
439
|
+
while (j < lines.length && (/^\s+/.test(lines[j]) || lines[j].trim() === '')) {
|
|
440
|
+
blockLines.push(lines[j].trim());
|
|
441
|
+
j += 1;
|
|
442
|
+
}
|
|
443
|
+
i = j - 1;
|
|
444
|
+
description = blockLines.filter(Boolean).join(' ').trim() || null;
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
return { hasFrontmatter: true, name, description };
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
function collectSkillMarkdownFiles(rootDir) {
|
|
454
|
+
const out = [];
|
|
455
|
+
if (!rootDir || !fs.existsSync(rootDir)) return out;
|
|
456
|
+
const direct = path.join(rootDir, 'SKILL.md');
|
|
457
|
+
if (fs.existsSync(direct)) out.push(direct);
|
|
458
|
+
try {
|
|
459
|
+
for (const entry of fs.readdirSync(rootDir, { withFileTypes: true })) {
|
|
460
|
+
if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
|
|
461
|
+
const nested = path.join(rootDir, entry.name, 'SKILL.md');
|
|
462
|
+
if (fs.existsSync(nested)) out.push(nested);
|
|
463
|
+
}
|
|
464
|
+
} catch {
|
|
465
|
+
// ignore: skip unreadable skill directory
|
|
466
|
+
}
|
|
467
|
+
return out.sort();
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const SKILL_TRIGGER_HIJACK_PATTERNS = Object.freeze([
|
|
471
|
+
{ label: 'MUST be used BEFORE', re: /\bMUST\s+be\s+used\s+BEFORE\b/i },
|
|
472
|
+
{ label: 'for ANY request', re: /\bfor\s+ANY\s+request\b/i },
|
|
473
|
+
{ label: 'ALWAYS invoke/use first', re: /\bALWAYS\s+(?:invoke|use|call|run)\b[^.!?\n]{0,40}\bfirst\b/i },
|
|
474
|
+
{
|
|
475
|
+
label: 'BEFORE web search / model memory / any other skill',
|
|
476
|
+
re: /\bBEFORE\s+(?:web\s+search|model\s+memory|any\s+other\s+\w+\s+skill)\b/i
|
|
477
|
+
}
|
|
478
|
+
]);
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* BO-CFG-16: Lean static check for missing/overlong SKILL.md frontmatter, broad trigger hijacking, and `.agents/skills` placement.
|
|
482
|
+
*/
|
|
483
|
+
export function auditSkillFrontmatterLimits({ cwd, harness = 'claude-code' } = {}) {
|
|
484
|
+
if (!cwd) return [];
|
|
485
|
+
const claudeSkillsDir = path.join(cwd, '.claude', 'skills');
|
|
486
|
+
const agentsSkillsDir = path.join(cwd, '.agents', 'skills');
|
|
487
|
+
const claudeFiles = collectSkillMarkdownFiles(claudeSkillsDir);
|
|
488
|
+
const agentsFiles = collectSkillMarkdownFiles(agentsSkillsDir);
|
|
489
|
+
const allFiles = [...new Set([...claudeFiles, ...agentsFiles])];
|
|
490
|
+
const lints = [];
|
|
491
|
+
|
|
492
|
+
for (const fp of allFiles) {
|
|
493
|
+
const normPath = fp.replace(/\\/g, '/');
|
|
494
|
+
let text = '';
|
|
495
|
+
try {
|
|
496
|
+
text = fs.readFileSync(fp, 'utf8');
|
|
497
|
+
} catch {
|
|
498
|
+
continue; // ignore: skip unreadable SKILL.md file
|
|
499
|
+
}
|
|
500
|
+
const fm = parseSkillFrontmatter(text);
|
|
501
|
+
if (!fm.hasFrontmatter || !fm.name || !fm.description) {
|
|
502
|
+
lints.push({
|
|
503
|
+
ruleId: 'BO-CFG-16',
|
|
504
|
+
severity: 'warn',
|
|
505
|
+
harness,
|
|
506
|
+
file: normPath,
|
|
507
|
+
message: `Skill Frontmatter Incomplete (BO-CFG-16): ${normPath} is missing valid YAML frontmatter name or description.`,
|
|
508
|
+
remediation:
|
|
509
|
+
'Add YAML frontmatter with concise "name" and "description" fields so host harnesses discover the skill reliably.'
|
|
510
|
+
});
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
if (fm.description.length > SKILL_DESCRIPTION_MAX_CHARS) {
|
|
514
|
+
lints.push({
|
|
515
|
+
ruleId: 'BO-CFG-16',
|
|
516
|
+
severity: 'warn',
|
|
517
|
+
harness,
|
|
518
|
+
file: normPath,
|
|
519
|
+
message: `Skill Description Exceeds Harness Limit (BO-CFG-16): description in ${normPath} is ${fm.description.length} chars (> ${SKILL_DESCRIPTION_MAX_CHARS}), risking silent clipping or drops (Codex 1,021 chars; Copilot CLI 1,024 UTF-16 units).`,
|
|
520
|
+
remediation: `Tighten the SKILL.md description to <= ${SKILL_DESCRIPTION_MAX_CHARS} characters and move details into the body.`
|
|
521
|
+
});
|
|
522
|
+
}
|
|
523
|
+
const hijackMatch = SKILL_TRIGGER_HIJACK_PATTERNS.find((p) => p.re.test(fm.description));
|
|
524
|
+
if (hijackMatch) {
|
|
525
|
+
lints.push({
|
|
526
|
+
ruleId: 'BO-CFG-16',
|
|
527
|
+
severity: 'warn',
|
|
528
|
+
harness,
|
|
529
|
+
file: normPath,
|
|
530
|
+
message: `Skill Frontmatter Trigger Hijack Pattern (BO-CFG-16): description in ${normPath} uses broad routing imperative ("${hijackMatch.label}"), risking false activations and unwanted SKILL.md context bloat.`,
|
|
531
|
+
remediation:
|
|
532
|
+
'Replace global routing imperatives with narrow, literal scope triggers describing exact tasks or file types.'
|
|
533
|
+
});
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
if (harness === 'claude-code' && agentsFiles.length > 0 && claudeFiles.length === 0) {
|
|
538
|
+
const normAgentsDir = agentsSkillsDir.replace(/\\/g, '/');
|
|
539
|
+
lints.push({
|
|
540
|
+
ruleId: 'BO-CFG-16',
|
|
541
|
+
severity: 'info',
|
|
542
|
+
harness: 'claude-code',
|
|
543
|
+
file: normAgentsDir,
|
|
544
|
+
message: `Skills Path Placement Note (BO-CFG-16): ${agentsFiles.length} project SKILL.md file(s) exist only under .agents/skills/, while Claude Code discovers project skills under .claude/skills/.`,
|
|
545
|
+
remediation: 'Mirror or symlink project skills you want Claude Code to load into .claude/skills/.'
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
return lints;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
function listMarkdownFilesInDir(dirPath) {
|
|
554
|
+
if (!dirPath || !fs.existsSync(dirPath)) return [];
|
|
555
|
+
try {
|
|
556
|
+
return fs
|
|
557
|
+
.readdirSync(dirPath, { withFileTypes: true })
|
|
558
|
+
.filter((e) => e.isFile() && /\.md$/i.test(e.name))
|
|
559
|
+
.map((e) => path.join(dirPath, e.name));
|
|
560
|
+
} catch {
|
|
561
|
+
return []; // ignore: unreadable rules directory
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function parseRuleTriggerMode(markdown = '') {
|
|
566
|
+
const m = String(markdown || '').match(/^---\s*\r?\n([\s\S]*?)\r?\n---/);
|
|
567
|
+
if (!m) return 'always_on';
|
|
568
|
+
const trig = m[1].match(/^\s*trigger\s*:\s*([^\r\n#]+)/im);
|
|
569
|
+
if (!trig) return 'always_on';
|
|
570
|
+
return trig[1].trim().toLowerCase() || 'always_on';
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
function auditAntigravityRulesFiles(filePaths = []) {
|
|
574
|
+
const seen = new Set();
|
|
575
|
+
const files = [];
|
|
576
|
+
let totalTokensEst = 0;
|
|
577
|
+
let totalRuleCount = 0;
|
|
578
|
+
let onDemandCount = 0;
|
|
579
|
+
|
|
580
|
+
for (const fp of filePaths) {
|
|
581
|
+
if (!fp || !fs.existsSync(fp)) continue;
|
|
582
|
+
let dedupeKey = canonicalizePath(fp);
|
|
583
|
+
try {
|
|
584
|
+
dedupeKey = canonicalizePath(fs.realpathSync(fp));
|
|
585
|
+
} catch {
|
|
586
|
+
// ignore: fallback to canonicalized path when realpath fails
|
|
587
|
+
}
|
|
588
|
+
if (seen.has(dedupeKey)) continue;
|
|
589
|
+
seen.add(dedupeKey);
|
|
590
|
+
|
|
591
|
+
try {
|
|
592
|
+
const text = fs.readFileSync(fp, 'utf8');
|
|
593
|
+
const triggerMode = parseRuleTriggerMode(text);
|
|
594
|
+
const chars = text.length;
|
|
595
|
+
const tokensEst = Math.ceil(chars / CHARS_PER_TOKEN);
|
|
596
|
+
const ruleCount = countDiscreteRules(text);
|
|
597
|
+
const isAlwaysOn = triggerMode !== 'model_decision' && triggerMode !== 'manual';
|
|
598
|
+
files.push({
|
|
599
|
+
path: String(fp).replace(/\\/g, '/'),
|
|
600
|
+
triggerMode,
|
|
601
|
+
alwaysOn: isAlwaysOn,
|
|
602
|
+
chars,
|
|
603
|
+
tokensEst,
|
|
604
|
+
ruleCount
|
|
605
|
+
});
|
|
606
|
+
if (isAlwaysOn) {
|
|
607
|
+
totalTokensEst += tokensEst;
|
|
608
|
+
totalRuleCount += ruleCount;
|
|
609
|
+
} else {
|
|
610
|
+
onDemandCount += 1;
|
|
611
|
+
}
|
|
612
|
+
} catch {
|
|
613
|
+
// ignore: unreadable Antigravity rule markdown
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
let status = 'pass';
|
|
618
|
+
const advisories = [];
|
|
619
|
+
if (totalRuleCount >= RULES_THRESHOLDS.ifScaleCliffRuleCount) {
|
|
620
|
+
status = 'warn';
|
|
621
|
+
advisories.push(
|
|
622
|
+
`IFScale instruction cliff exceeded (${totalRuleCount} >= ${RULES_THRESHOLDS.ifScaleCliffRuleCount} always-on rules); set trigger: model_decision or move domain rules into skills.`
|
|
623
|
+
);
|
|
624
|
+
} else if (totalRuleCount >= RULES_THRESHOLDS.cautionRuleCount) {
|
|
625
|
+
status = 'caution';
|
|
626
|
+
advisories.push(
|
|
627
|
+
`Approaching IFScale instruction adherence drop-off (${totalRuleCount} >= ${RULES_THRESHOLDS.cautionRuleCount} always-on rules).`
|
|
628
|
+
);
|
|
629
|
+
}
|
|
630
|
+
if (totalTokensEst >= RULES_THRESHOLDS.tokenWarning) {
|
|
631
|
+
status = 'warn';
|
|
632
|
+
advisories.push(
|
|
633
|
+
`Static Turn-0 prefix bloat (${totalTokensEst} >= ${RULES_THRESHOLDS.tokenWarning} est. tokens across always-on Antigravity rules).`
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
return { files, totalTokensEst, totalRuleCount, onDemandCount, status, advisories };
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
export {
|
|
642
|
+
listMarkdownFilesInDir,
|
|
643
|
+
parseRuleTriggerMode,
|
|
644
|
+
auditAntigravityRulesFiles
|
|
645
|
+
};
|