config-audit/scanners/lib/yaml-parser.mjs
Kjell Tore Guttormsen 62d910ed6d feat(acr,yaml): v5.6 Foundation — load-pattern enumeration + block-seq parser
Foundation chunk of v5.6 "steering-model II" (internal plumbing for B/C;
no command-output change, so --json/--raw/SC-5/6/7 stay byte-stable, count
stays 13).

active-config-reader.mjs:
- deriveLoadPattern(kind,{scoped}) — pure helper mapping each source kind to
  loadPattern {always,on-demand,external} + survivesCompaction {yes,no,n/a}
  + derivationConfidence {confirmed,inferred}, traced to the published
  loading model (V-rows in docs/v5.5-steering-model-plan.md).
- enumerateRules / enumerateAgents / enumerateOutputStyles — the three
  source kinds previously unenumerated (mirror enumerateSkills). Output-style
  discovery is direct (not a new file-discovery type) to keep the discovery
  surface stable.
- readActiveConfig now exposes rules/agents/outputStyles arrays + totals
  counts/subtotals (folded into grandTotal).

yaml-parser.mjs:
- parseSimpleYaml now reads YAML block sequences (paths:\n  - a), not just
  inline paths:. An empty-valued key with no `- ` items stays null
  (backcompat). Resolves a pre-existing RUL false-positive (a block-seq-scoped
  rule was misread as unscoped) — fix flows through unchanged RUL code.

Tests +35 (961 -> 996): block-seq parser cases, RUL block-seq regression
(no-misflag + durability-fires), deriveLoadPattern table, three enumerators
(positive+negative). Amended two existing ACR asserts (top-level key shape +
grandTotal sum). self-audit A/A, readmeCheck passed, mismatches []. tests
badge 961+->996+; README testing prose de-staled (635/36 -> 996/56);
CLAUDE.md Foundation note.

B (manifest/tokens render + snapshot regen) and C (CA-OST, count->14)
deferred to their own sessions/GO.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ter3E2JSi1Khgmuf2kady8
2026-06-20 16:57:52 +02:00

234 lines
6.6 KiB
JavaScript

/**
* Regex-based YAML frontmatter parser for Claude Code .md files.
* Handles YAML frontmatter (--- delimited) and basic YAML parsing.
* Zero external dependencies.
*/
/**
* Parse YAML frontmatter from markdown content.
* @param {string} content
* @returns {{ frontmatter: object | null, body: string, bodyStartLine: number }}
*/
export function parseFrontmatter(content) {
const match = content.match(/^---\r?\n([\s\S]*?)(?:\r?\n)?---(?:\r?\n|$)/);
if (!match) {
return { frontmatter: null, body: content, bodyStartLine: 1 };
}
const raw = match[1];
const bodyStartLine = raw.split('\n').length + 3; // 2 for --- lines + 1-based
const body = content.slice(match[0].length);
const frontmatter = parseSimpleYaml(raw);
return { frontmatter, body, bodyStartLine };
}
/**
* Parse simple YAML key-value pairs (no nesting beyond arrays).
* @param {string} yaml
* @returns {object}
*/
export function parseSimpleYaml(yaml) {
const result = {};
const lines = yaml.split('\n');
let currentKey = null;
let multiLineValue = '';
let inMultiLine = false;
// Block-sequence state: an empty-valued key may be a YAML block sequence
// key:
// - item
// - item
// We defer the decision until the next line: a `- item` line starts an array;
// anything else (or end-of-input) leaves the empty-valued key as `null` —
// indistinguishable from a plain null value, preserving backwards compatibility.
let seqKey = null; // key awaiting/collecting block-sequence items
let seqItems = null; // null until the first `- ` item is seen
let seqPending = false; // an empty-valued key was seen; items may follow
// Commit the current block-sequence (or empty-valued key) to result.
const commitSeq = () => {
if (seqKey !== null) {
result[normalizeKey(seqKey)] = seqItems !== null ? seqItems : null;
}
seqKey = null;
seqItems = null;
seqPending = false;
};
for (const line of lines) {
// Skip comments and empty lines (these do NOT terminate a block sequence)
if (line.trim().startsWith('#') || line.trim() === '') {
if (inMultiLine) multiLineValue += '\n';
continue;
}
// Block-sequence item: only while a sequence is pending or active
const seqMatch = (seqPending || seqItems !== null) && !inMultiLine
? line.match(/^\s+-\s*(.*)$/)
: null;
if (seqMatch) {
if (seqItems === null) seqItems = [];
const itemVal = parseValue(seqMatch[1].trim());
if (itemVal !== null && itemVal !== '') seqItems.push(itemVal);
seqPending = false;
continue;
}
// Key-value pair
const kvMatch = line.match(/^(\w[\w-]*):\s*(.*)/);
if (kvMatch && !inMultiLine) {
// A new key terminates any pending/active block sequence.
commitSeq();
if (currentKey && multiLineValue) {
result[normalizeKey(currentKey)] = multiLineValue.trim();
}
currentKey = kvMatch[1];
const value = kvMatch[2].trim();
if (value === '|' || value === '>') {
inMultiLine = true;
multiLineValue = '';
continue;
}
if (value === '') {
// Defer: this may be a block sequence (next line) or a null value.
seqKey = currentKey;
seqItems = null;
seqPending = true;
currentKey = null;
continue;
}
result[normalizeKey(currentKey)] = parseValue(value);
currentKey = null;
continue;
}
// Multi-line continuation
if (inMultiLine) {
if (line.match(/^\s+/)) {
multiLineValue += (multiLineValue ? '\n' : '') + line.trim();
} else {
result[normalizeKey(currentKey)] = multiLineValue.trim();
inMultiLine = false;
multiLineValue = '';
// Re-process this line as a new key
const reMatch = line.match(/^(\w[\w-]*):\s*(.*)/);
if (reMatch) {
currentKey = reMatch[1];
result[normalizeKey(currentKey)] = parseValue(reMatch[2].trim());
currentKey = null;
}
}
continue;
}
// A non-item, non-key line while a sequence is pending/active terminates it
// (then the line is ignored, as before the fix).
if (seqPending || seqItems !== null) {
commitSeq();
}
}
// Flush remaining multi-line
if (inMultiLine && currentKey) {
result[normalizeKey(currentKey)] = multiLineValue.trim();
}
// Flush a trailing block sequence / empty-valued key
commitSeq();
// Normalize arrays for known list fields
for (const field of ['allowed_tools', 'tools', 'paths', 'globs']) {
if (typeof result[field] === 'string') {
result[field] = result[field].split(',').map(s => s.trim()).filter(Boolean);
}
}
return result;
}
/**
* Parse a YAML value string.
*/
function parseValue(str) {
if (str === '' || str === '~' || str === 'null') return null;
if (str === 'true') return true;
if (str === 'false') return false;
if (/^\d+$/.test(str)) return parseInt(str, 10);
if (/^\d+\.\d+$/.test(str)) return parseFloat(str);
// Inline array: [a, b, c]
if (str.startsWith('[') && str.endsWith(']')) {
return str.slice(1, -1).split(',').map(s => {
const v = s.trim();
return v.replace(/^["']|["']$/g, '');
}).filter(Boolean);
}
// Quoted string
if ((str.startsWith('"') && str.endsWith('"')) || (str.startsWith("'") && str.endsWith("'"))) {
return str.slice(1, -1);
}
return str;
}
/**
* Normalize key: hyphens to underscores.
*/
function normalizeKey(key) {
return key.replace(/-/g, '_');
}
/**
* Parse a JSON file content. Returns null on error.
* @param {string} content
* @returns {object | null}
*/
export function parseJson(content) {
try {
return JSON.parse(content);
} catch {
return null;
}
}
/**
* Find @import references in CLAUDE.md content.
* @param {string} content
* @returns {{ path: string, line: number }[]}
*/
export function findImports(content) {
const imports = [];
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(/^@(.+)$/);
if (match) {
imports.push({ path: match[1].trim(), line: i + 1 });
}
}
return imports;
}
/**
* Extract markdown sections (## headings) from content.
* @param {string} content
* @returns {{ heading: string, level: number, line: number }[]}
*/
export function extractSections(content) {
const sections = [];
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
const match = lines[i].match(/^(#{1,6})\s+(.+)/);
if (match) {
sections.push({
heading: match[2].trim(),
level: match[1].length,
line: i + 1,
});
}
}
return sections;
}