madr-lint 0.2.0 → 0.3.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/CHANGELOG.md +15 -0
- package/README.md +2 -0
- package/dist/cli.js +94 -17
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +25 -4
- package/dist/index.js +67 -9
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/core/baseline.ts","../src/core/types.ts","../src/core/cache.ts","../src/core/config.ts","../src/configs/recommended.ts","../src/core/discover.ts","../src/core/ignore.ts","../src/core/lint.ts","../src/core/runner.ts","../src/core/parser.ts","../src/core/suppression.ts","../src/core/reporter.ts","../src/rules/index.ts","../src/rules/date-iso8601/schema.json","../src/rules/date-iso8601/index.ts","../src/rules/filename-format/index.ts","../src/core/regex-safety.ts","../src/rules/filename-format/schema.json","../src/rules/no-broken-links/index.ts","../src/rules/no-broken-links/schema.json","../src/rules/no-duplicate-numbering/index.ts","../src/rules/no-duplicate-numbering/schema.json","../src/rules/no-numbering-gap/index.ts","../src/rules/no-numbering-gap/schema.json","../src/rules/required-sections/index.ts","../src/rules/required-sections/schema.json","../src/rules/status-enum/schema.json","../src/rules/status-enum/index.ts","../src/rules/supersedes-bidirectional/index.ts","../src/rules/supersedes-bidirectional/schema.json"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { relative, resolve, sep } from 'node:path';\nimport { defineCommand, runMain } from 'citty';\nimport {\n baselineHiddenSummary,\n baselineMalformedWarning,\n baselinePath,\n baselineWriteSummary,\n buildBaseline,\n loadBaseline,\n writeBaseline,\n} from './core/baseline.js';\nimport { computeConfigHash } from './core/cache.js';\nimport {\n ConfigFileNotFoundError,\n loadConfig,\n loadConfigFromPath,\n resolveExtends,\n type ResolvedConfig,\n} from './core/config.js';\nimport { findAdrFiles } from './core/discover.js';\nimport { shouldIgnore } from './core/ignore.js';\nimport { lintFiles, type CacheConfig } from './core/lint.js';\nimport { reporters, type ReporterFormat } from './core/reporter.js';\nimport { RuleOptionsError } from './core/runner.js';\nimport type { AnyRule } from './core/types.js';\nimport * as builtinRules from './rules/index.js';\n\nfunction toPosix(p: string): string {\n if (sep === '/') return p;\n return p.split(sep).join('/');\n}\n\nconst pkg = JSON.parse(\n readFileSync(new URL('../package.json', import.meta.url), 'utf8'),\n) as { version: string };\n\nconst main = defineCommand({\n meta: {\n name: 'madr-lint',\n version: pkg.version,\n description: 'A linter for MADR (Markdown Architectural Decision Records)',\n },\n args: {\n paths: {\n type: 'positional',\n description:\n 'One or more paths (files or directories). Defaults to config.adrDir',\n required: false,\n },\n cache: {\n type: 'boolean',\n description:\n 'Use per-file content-hash cache (use --no-cache to disable)',\n default: true,\n },\n 'cache-dir': {\n type: 'string',\n description: 'Cache directory (default: .madr-lint/cache)',\n required: false,\n },\n format: {\n type: 'string',\n description: 'Reporter format: text (default), json, sarif, or github',\n default: 'text',\n },\n baseline: {\n type: 'boolean',\n description:\n 'Subtract .madr-lint/baseline.json when present (use --no-baseline to ignore it)',\n default: true,\n },\n 'update-baseline': {\n type: 'boolean',\n description:\n 'Rewrite .madr-lint/baseline.json from a full lint, then exit 0',\n default: false,\n },\n quiet: {\n type: 'boolean',\n description: 'Report errors only; suppress warnings from output',\n default: false,\n },\n 'max-warnings': {\n type: 'string',\n description:\n 'Exit 1 when warning count exceeds n. n=0 means any warning fails. Negative = no limit.',\n required: false,\n },\n config: {\n type: 'string',\n description: 'Path to config file, bypassing auto-discovery',\n required: false,\n },\n },\n run({ args }) {\n const cwd = process.cwd();\n\n // Parse --max-warnings. Require an integer (including negative); float or\n // non-numeric is a usage error (exit 2), not a lint failure (exit 1).\n // Number('') === 0, so an empty value (e.g. --max-warnings \"$UNSET_VAR\")\n // would silently become the strictest limit — reject it explicitly.\n let maxWarnings = -1;\n const rawMaxWarnings = args['max-warnings'] as string | undefined;\n if (rawMaxWarnings !== undefined) {\n const parsed = Number(rawMaxWarnings);\n if (rawMaxWarnings.trim() === '' || !Number.isInteger(parsed)) {\n console.error(\n `Invalid --max-warnings \"${rawMaxWarnings}\": must be an integer.`,\n );\n process.exit(2);\n }\n maxWarnings = parsed;\n }\n\n // --config bypasses the config discovery walk. When the user explicitly\n // points to a config file we skip the recommended fallback — they chose\n // the config intentionally (even if it has no rules).\n let config: ResolvedConfig;\n let configExplicit = false;\n const configArg = args.config as string | undefined;\n if (configArg) {\n const absConfigPath = resolve(cwd, configArg);\n try {\n config = loadConfigFromPath(absConfigPath);\n configExplicit = true;\n } catch (err) {\n if (err instanceof ConfigFileNotFoundError) {\n console.error(err.message);\n } else {\n console.error(\n `Failed to load config \"${configArg}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n process.exit(2);\n }\n } else {\n config = loadConfig(cwd);\n }\n\n // When no rules are configured and no explicit config was provided, fall\n // back to `recommended` so users get useful output without authoring a\n // config first.\n if (!configExplicit && Object.keys(config.rules).length === 0) {\n config = resolveExtends({ extends: ['madr-lint:recommended'] });\n }\n\n // citty: positionals collect into `args._` (array of strings). If\n // empty, fall back to the config's adrDir.\n const positionals = (args._ as string[] | undefined) ?? [];\n const inputs = positionals.length > 0 ? positionals : [config.adrDir];\n\n const seen = new Set<string>();\n const allFiles: string[] = [];\n for (const input of inputs) {\n for (const file of findAdrFiles(input)) {\n if (!seen.has(file)) {\n seen.add(file);\n allFiles.push(file);\n }\n }\n }\n\n // Apply ignorePatterns from config (e.g. README.md, template.md, 9999-*).\n // POSIX-normalize so path-suffix patterns work cross-platform on Windows.\n const files = allFiles.filter(\n (absPath) =>\n !shouldIgnore(toPosix(relative(cwd, absPath)), config.ignorePatterns),\n );\n\n if (files.length === 0) {\n const skipped = allFiles.length - files.length;\n const note = skipped > 0 ? ` (${skipped} ignored by config)` : '';\n const where = inputs.length === 1 ? inputs[0] : inputs.join(', ');\n console.log(`No .md files to lint in ${where}${note}`);\n process.exit(0);\n }\n\n // CLI flag wins over config — `--no-cache` sets args.cache=false,\n // overriding `cache: true` from .madrlintrc.json.\n const cacheEnabled = (args.cache ?? config.cache) === true;\n const cacheDir = (args['cache-dir'] ?? config.cacheLocation) as string;\n const cacheConfig: CacheConfig | null = cacheEnabled\n ? {\n dir: resolve(cwd, cacheDir),\n configHash: computeConfigHash({\n rules: config.rules,\n ignorePatterns: config.ignorePatterns,\n madrVersion: config.madrVersion,\n }),\n pkgVersion: pkg.version,\n }\n : null;\n\n // --update-baseline runs a full lint IGNORING any existing baseline, so we\n // subtract nothing here and (below) rebuild the file from the raw output.\n const baselineFile = baselinePath(cwd);\n const updateBaseline = args['update-baseline'] === true;\n const useBaseline = !updateBaseline && args.baseline !== false;\n const baseline = useBaseline ? loadBaseline(baselineFile) : null;\n // Absent → silent no-op. Present but unusable → warn: silently ignoring a\n // corrupt baseline would flip CI red with zero explanation.\n if (useBaseline && baseline === null && existsSync(baselineFile)) {\n console.error(baselineMalformedWarning());\n }\n\n const allRulesArray: AnyRule[] = Object.values(builtinRules);\n let result: ReturnType<typeof lintFiles>;\n try {\n result = lintFiles({\n rules: allRulesArray,\n ruleSeverity: config.rules,\n files,\n cwd,\n cache: cacheConfig,\n baseline,\n });\n } catch (err) {\n // Invalid rule options in the user's config fail AJV validation now that\n // options actually reach the rules. Surface a clear message instead of a\n // stack trace, and exit 2 (config error, distinct from lint failures).\n if (err instanceof RuleOptionsError) {\n console.error(`Invalid rule options in config: ${err.message}`);\n process.exit(2);\n }\n throw err;\n }\n\n // Rebuild the baseline from the full (pre-baseline) diagnostics and exit.\n if (updateBaseline) {\n const built = buildBaseline(result.diagnostics);\n writeBaseline(baselineFile, built);\n console.log(baselineWriteSummary(built));\n process.exit(0);\n }\n\n const rulesByName = new Map<string, AnyRule>(\n allRulesArray.map((r) => [r.meta.name, r]),\n );\n const format = (args.format ?? 'text') as ReporterFormat;\n const reporter = reporters[format];\n if (!reporter) {\n console.error(\n `Unknown --format \"${format}\". Available: ${Object.keys(reporters).join(', ')}`,\n );\n process.exit(2);\n }\n // result.diagnostics is POST-baseline (lintFiles subtracts before\n // returning), so baselined warnings never count toward --max-warnings —\n // the whole point of a baseline is that inherited debt does not fail CI.\n const allDiagnostics = result.diagnostics;\n const warningCount = allDiagnostics.filter((d) => d.severity === 'warn').length;\n const errorCount = allDiagnostics.filter((d) => d.severity === 'error').length;\n const overWarningLimit = maxWarnings >= 0 && warningCount > maxWarnings;\n\n // --quiet filters warnings from OUTPUT but the original warning count is\n // still used for --max-warnings (mirrors ESLint: \"warnings still run, not\n // reported\"). So `--quiet --max-warnings 0` keeps the log free of warning\n // noise while still failing the build — the threshold verdict below goes\n // to stderr so the failure is never mute.\n const reported = args.quiet\n ? allDiagnostics.filter((d) => d.severity !== 'warn')\n : allDiagnostics;\n\n // Text-only: a \"✓ All clear.\" banner beside exit 1 would lie, so suppress\n // it when the run fails purely on the warning threshold. json/sarif\n // payloads still print — machine consumers read stdout + stderr + exit.\n const suppressAllClear =\n format === 'text' && reported.length === 0 && overWarningLimit;\n if (!suppressAllClear) {\n console.log(\n reporter.format(reported, rulesByName, {\n baselineHidden: result.baselineHidden,\n }),\n );\n }\n // Text-only footer: JSON carries the count in its summary; SARIF stays\n // schema-clean. Printed even when --quiet or the banner is suppressed —\n // knowing the baseline absorbed diagnostics is never noise.\n if (format === 'text' && result.baselineHidden > 0) {\n console.log(baselineHiddenSummary(result.baselineHidden));\n }\n\n // The threshold verdict goes to stderr for every format so it survives\n // --quiet and machine-readable stdout alike.\n if (overWarningLimit) {\n console.error(\n `madr-lint: ${warningCount} warning(s) found, exceeds --max-warnings ${maxWarnings}`,\n );\n }\n\n process.exit(errorCount > 0 || overWarningLimit ? 1 : 0);\n },\n});\n\nawait runMain(main);\n","// Baseline file for gradual adoption (issue #24).\n//\n// FINGERPRINT MODEL: a violation is identified by `(relative posix path,\n// ruleName, messageId)` mapped to an allowed COUNT. No line numbers, no\n// message text, no interpolation data — so the baseline survives unrelated\n// edits by construction (a rule that fires the same number of times on the\n// same file+message is fully absorbed regardless of where the lines moved).\n// This is the tsc-baseline-style count model; see ADR-0007 for the rationale\n// and the rejected line-based / content-hash alternatives.\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { INTERNAL_ERROR_RULE_NAME, type Diagnostic } from './types.js';\n\n/** Bumped only on a breaking change to the on-disk shape. */\nexport const BASELINE_VERSION = 1;\n\n/** Fixed, project-root-relative location. Also used verbatim in summaries. */\nexport const BASELINE_DISPLAY_PATH = '.madr-lint/baseline.json';\n\n/**\n * On-disk baseline. `entries` nests path → ruleName → messageId → count.\n * The nesting (rather than a flat hash) is what yields clean, reviewable git\n * diffs once keys are sorted at serialization time.\n */\nexport interface Baseline {\n version: number;\n entries: Record<string, Record<string, Record<string, number>>>;\n}\n\nexport interface BaselineApplyResult {\n /** Diagnostics that survive subtraction (new / over-count / never baselined). */\n kept: Diagnostic[];\n /** How many diagnostics the baseline absorbed. */\n hidden: number;\n}\n\n/** Absolute path to the baseline file for a given project root. */\nexport function baselinePath(cwd: string): string {\n return join(cwd, '.madr-lint', 'baseline.json');\n}\n\n/**\n * Null-prototype map. Fingerprint keys derive from on-disk filenames and\n * rule metadata, so a key like '__proto__' must behave as ordinary data —\n * on a plain object it would read/write THROUGH Object.prototype instead\n * (prototype pollution + silently dropped entries). With no prototype there\n * is nothing to pollute. JSON.stringify output is identical.\n */\nfunction nullProtoMap<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\n/**\n * Aggregate diagnostics into a baseline by counting each\n * `(path, ruleName, messageId)`. `core/internal-error` is never recorded —\n * it signals a rule bug and must never be silenced (same contract as inline\n * suppression).\n */\nexport function buildBaseline(diagnostics: readonly Diagnostic[]): Baseline {\n const entries = nullProtoMap<Record<string, Record<string, number>>>();\n for (const d of diagnostics) {\n if (d.ruleName === INTERNAL_ERROR_RULE_NAME) continue;\n const byRule = (entries[d.path] ??= nullProtoMap());\n const byMessage = (byRule[d.ruleName] ??= nullProtoMap());\n byMessage[d.messageId] = (byMessage[d.messageId] ?? 0) + 1;\n }\n return { version: BASELINE_VERSION, entries };\n}\n\n/**\n * Deterministic serialization: keys sorted at every level (path, then rule,\n * then messageId), 2-space indent, trailing newline. Same logical baseline\n * always produces byte-identical output → minimal git diffs.\n */\nexport function serializeBaseline(baseline: Baseline): string {\n // Null-proto targets: on a plain object, assigning a '__proto__' key goes\n // through the inherited setter and the entry silently vanishes from the\n // JSON output.\n const sortedEntries = nullProtoMap<Record<string, Record<string, number>>>();\n for (const path of Object.keys(baseline.entries).toSorted()) {\n const byRule = baseline.entries[path] ?? {};\n const sortedByRule = nullProtoMap<Record<string, number>>();\n for (const rule of Object.keys(byRule).toSorted()) {\n const byMessage = byRule[rule] ?? {};\n const sortedByMessage = nullProtoMap<number>();\n for (const messageId of Object.keys(byMessage).toSorted()) {\n sortedByMessage[messageId] = byMessage[messageId] ?? 0;\n }\n sortedByRule[rule] = sortedByMessage;\n }\n sortedEntries[path] = sortedByRule;\n }\n const ordered = { version: baseline.version, entries: sortedEntries };\n return JSON.stringify(ordered, null, 2) + '\\n';\n}\n\n/**\n * Read a baseline file. Returns null when absent or unreadable/malformed —\n * a missing or corrupt baseline is treated as \"no baseline\" (a no-op),\n * never a hard error.\n */\nexport function loadBaseline(path: string): Baseline | null {\n if (!existsSync(path)) return null;\n try {\n const data = JSON.parse(readFileSync(path, 'utf8')) as Partial<Baseline>;\n if (typeof data.entries !== 'object' || data.entries === null) return null;\n return {\n version: typeof data.version === 'number' ? data.version : BASELINE_VERSION,\n entries: rebuildEntries(data.entries as Record<string, unknown>),\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Copy parsed JSON into null-proto maps, keeping only well-shaped levels\n * (objects) and leaves (numbers). JSON.parse itself creates '__proto__' as\n * a safe own property, but handing proto-ful objects downstream would\n * re-expose every consumer write to the pollution hazard — and a malformed\n * inner level (e.g. `\"a.md\": null`) would crash applyBaseline.\n */\nfunction rebuildEntries(raw: Record<string, unknown>): Baseline['entries'] {\n const entries = nullProtoMap<Record<string, Record<string, number>>>();\n for (const [path, rawByRule] of Object.entries(raw)) {\n if (typeof rawByRule !== 'object' || rawByRule === null) continue;\n const byRule = nullProtoMap<Record<string, number>>();\n for (const [rule, rawByMessage] of Object.entries(rawByRule)) {\n if (typeof rawByMessage !== 'object' || rawByMessage === null) continue;\n const byMessage = nullProtoMap<number>();\n for (const [messageId, count] of Object.entries(\n rawByMessage as Record<string, unknown>,\n )) {\n if (typeof count === 'number') byMessage[messageId] = count;\n }\n byRule[rule] = byMessage;\n }\n entries[path] = byRule;\n }\n return entries;\n}\n\n/** Write the baseline deterministically, creating `.madr-lint/` if needed. */\nexport function writeBaseline(path: string, baseline: Baseline): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, serializeBaseline(baseline), 'utf8');\n}\n\n// NUL cannot appear in paths, rule names, or messageIds, so joined keys\n// can never collide. Written as an escape (not a raw byte) to keep this\n// file text for git diff/blame.\nconst KEY_SEP = '\\u0000';\n\nfunction fingerprint(d: Diagnostic): string {\n return d.path + KEY_SEP + d.ruleName + KEY_SEP + d.messageId;\n}\n\n/**\n * Subtract a baseline from a diagnostic list. For each fingerprint the first\n * N matching diagnostics (N = baselined count) are absorbed; any extras are\n * reported as new. `core/internal-error` is never absorbed. Stale entries\n * (count exceeding current matches) are simply inert — no error is raised.\n *\n * O(1) per diagnostic: a mutable per-fingerprint allowance map is built once,\n * then each diagnostic is a single map lookup + decrement.\n */\nexport function applyBaseline(\n diagnostics: readonly Diagnostic[],\n baseline: Baseline,\n): BaselineApplyResult {\n const remaining = new Map<string, number>();\n for (const [path, byRule] of Object.entries(baseline.entries)) {\n for (const [rule, byMessage] of Object.entries(byRule)) {\n if (rule === INTERNAL_ERROR_RULE_NAME) continue;\n for (const [messageId, count] of Object.entries(byMessage)) {\n remaining.set(path + KEY_SEP + rule + KEY_SEP + messageId, count);\n }\n }\n }\n\n const kept: Diagnostic[] = [];\n let hidden = 0;\n for (const d of diagnostics) {\n if (d.ruleName === INTERNAL_ERROR_RULE_NAME) {\n kept.push(d);\n continue;\n }\n const key = fingerprint(d);\n const left = remaining.get(key);\n if (left !== undefined && left > 0) {\n remaining.set(key, left - 1);\n hidden++;\n } else {\n kept.push(d);\n }\n }\n return { kept, hidden };\n}\n\nfunction totalCount(baseline: Baseline): number {\n let total = 0;\n for (const byRule of Object.values(baseline.entries)) {\n for (const byMessage of Object.values(byRule)) {\n for (const count of Object.values(byMessage)) total += count;\n }\n }\n return total;\n}\n\n/**\n * One-line summary after `--update-baseline`. Counts the SUM of allowed\n * counts (\"violations\") — not fingerprint keys, and deliberately not the\n * word \"entries\", which names the on-disk map.\n */\nexport function baselineWriteSummary(baseline: Baseline): string {\n const violations = totalCount(baseline);\n const files = Object.keys(baseline.entries).length;\n const v = `${violations} ${violations === 1 ? 'violation' : 'violations'}`;\n const f = `${files} ${files === 1 ? 'file' : 'files'}`;\n return `Wrote ${v} across ${f} to ${BASELINE_DISPLAY_PATH}`;\n}\n\n/**\n * Stderr warning for a baseline file that EXISTS but could not be used.\n * A missing file is silent by design; a present-but-broken one must not be —\n * silently ignoring it would flip CI red with zero explanation.\n */\nexport function baselineMalformedWarning(): string {\n return `madr-lint: warning: ${BASELINE_DISPLAY_PATH} is malformed; ignoring it (run --update-baseline to regenerate)`;\n}\n\n/** One-line summary appended to text output when the baseline hid diagnostics. */\nexport function baselineHiddenSummary(hidden: number): string {\n return `${hidden} ${hidden === 1 ? 'problem' : 'problems'} hidden by baseline (${BASELINE_DISPLAY_PATH})`;\n}\n","// MADR linter core types.\n// Per ADR-0002, the runner uses a single-pass visitor registry over mdast.\n// The Rule type below supports BOTH:\n// - Filename / metadata-only rules: create() returns void\n// - AST-based rules: create() returns RuleListeners with enter/exit handlers\n// keyed by mdast node type. The runner walks each file's tree once and\n// dispatches to all subscribed rules.\n\nimport type { AnySchemaObject } from 'ajv';\nimport type { Nodes, Root } from 'mdast';\n// Note: imports of project-internal modules use the `.js` extension per\n// Node ESM convention. tsc resolves these to the .ts source files.\n\n// All mdast node types rules can subscribe to. `'root'` is the top-level\n// document node — useful for \"after all children visited\" reporting in\n// exit handlers.\nexport type MdastNodeType = Root['type'] | Nodes['type'];\n\n// The argument type for visitor handlers — covers root + all descendants.\nexport type MdastNode = Root | Nodes;\n\n/** Severity levels supported by every rule. */\nexport type Severity = 'error' | 'warn';\n\n/**\n * The reserved rule name used for internal-error diagnostics. A real rule\n * cannot register with this name (the registry should reject collisions).\n * Lives here (not in runner.ts) so leaf modules like the suppression layer\n * can reference it without importing the runner.\n */\nexport const INTERNAL_ERROR_RULE_NAME = 'core/internal-error';\n\n/**\n * User-facing severity declaration in config files.\n * - bare string: enable/disable with default options\n * - tuple: enable with explicit options\n */\nexport type RuleSeverity =\n | Severity\n | 'off'\n | readonly [Severity, Record<string, unknown>];\n\nexport type MadrVersion = 'v2' | 'v3' | 'v4';\n\nexport interface RuleMeta<TOptions = Record<string, unknown>> {\n /** Rule identifier, e.g. 'madr/filename-format'. */\n name: string;\n /** Whether the rule operates per-file or across the project. */\n type: 'perFile' | 'project';\n /** Which MADR versions this rule applies to. */\n versionCompat: readonly MadrVersion[];\n docs: {\n description: string;\n url?: string;\n recommended: boolean;\n };\n /** messageId -> template string with {{placeholders}}. */\n messages: Record<string, string>;\n /** Default options merged with user config. */\n defaultOptions: TOptions;\n /** AJV JSON Schema for options. Validated at runRule time. */\n schema?: AnySchemaObject;\n}\n\nexport interface FileContext {\n /** File path (typically basename or repo-relative). */\n path: string;\n /** Raw file content. */\n content: string;\n}\n\nexport interface Diagnostic {\n /** Rule that emitted this diagnostic. */\n ruleName: string;\n /** messageId from rule.meta.messages. */\n messageId: string;\n /** Severity resolved against the user config. */\n severity: Severity;\n /** Path of the offending file. */\n path: string;\n /** Optional source range. Filename rules omit this. */\n loc?: {\n line: number;\n column: number;\n };\n /** Data for placeholder interpolation in messages[messageId]. */\n data?: Record<string, unknown>;\n}\n\nexport interface RuleContext<TOptions = Record<string, unknown>> {\n /** The file being linted. */\n file: FileContext;\n /**\n * Parsed YAML frontmatter (v3/v4 only), or null if absent.\n * Use this when the rule must validate strict YAML frontmatter shape.\n */\n frontmatter: Record<string, unknown> | null;\n /**\n * Combined metadata: YAML frontmatter merged with v2 bold-list extracted\n * from the body. Frontmatter wins on key conflict. null only when both\n * are absent. See ADR-0006. Use this for format-agnostic field reads.\n */\n metadata: Record<string, unknown> | null;\n /**\n * Body-coordinate positions for `metadata` keys whose effective value came\n * from the v2 leading list (the list item's start). Frontmatter-sourced\n * keys are absent — frontmatter is stripped before mdast parsing, so it\n * has no body line. Rules attach this as `loc` on metadata-value\n * diagnostics so inline suppression directives can target them by line.\n */\n metadataLoc: Record<string, { line: number; column: number }> | null;\n /** User-merged options for this rule (validated against rule.meta.schema). */\n options: TOptions;\n /** Emit a diagnostic. */\n report(diagnostic: Omit<Diagnostic, 'ruleName' | 'severity' | 'path'>): void;\n}\n\n/**\n * Visitor map dispatched during single-pass mdast traversal.\n * Rules subscribe to specific node types; the runner walks the tree once\n * and calls the matching enter/exit handler for each node.\n */\nexport interface RuleListeners {\n enter?: Partial<Record<MdastNodeType, (node: MdastNode) => void>>;\n exit?: Partial<Record<MdastNodeType, (node: MdastNode) => void>>;\n}\n\n/**\n * A lint rule.\n *\n * - Filename / metadata-only rules: `create` reports diagnostics directly,\n * then returns void.\n * - AST-based rules: `create` returns RuleListeners; the runner invokes\n * them during single-pass traversal of the file's mdast tree.\n */\nexport interface Rule<TOptions = Record<string, unknown>> {\n meta: RuleMeta<TOptions>;\n create(context: RuleContext<TOptions>): RuleListeners | void;\n}\n\n// ──────────────────────────────────────────────────────────────────\n// Project rules (cross-file). See ADR-0005.\n// ──────────────────────────────────────────────────────────────────\n\n/**\n * A pre-parsed file passed to project rules. Built once per\n * `runRulesOnProject` invocation.\n */\nexport interface ProjectFile {\n /** File path relative to the project root. */\n path: string;\n /** Raw file content (unparsed). */\n content: string;\n /**\n * Body content with frontmatter stripped — the same coordinate space as\n * `ast` positions. Used by the suppression layer for line-level directive\n * targeting.\n */\n body: string;\n /** Parsed YAML frontmatter (v3/v4 only), or null if absent. */\n frontmatter: Record<string, unknown> | null;\n /**\n * Combined metadata: frontmatter merged with v2 bold-list extracted\n * from the body. Frontmatter wins on key conflict. See ADR-0006.\n */\n metadata: Record<string, unknown> | null;\n /** mdast root of the body (frontmatter stripped). */\n ast: Root;\n}\n\nexport interface ProjectRuleContext<TOptions = Record<string, unknown>> {\n /** All files in the project (eager-parsed). */\n files: readonly ProjectFile[];\n /** User-merged options for this rule. */\n options: TOptions;\n /**\n * Predicate: does a project-root-relative POSIX path exist as a regular\n * file WITHIN the project root? Injected by the orchestrator so rules (e.g.\n * no-broken-links) can verify link targets that are NOT in the linted `.md`\n * set — non-Markdown assets or files outside the scanned paths. Returns\n * false for directories and for any target that resolves at or above the\n * project root (i.e. escapes it). Undefined when no filesystem is available\n * (e.g. in-memory unit tests), in which case rules fall back to the `files`\n * set alone.\n */\n fileExists?: (resolvedPath: string) => boolean;\n /**\n * Emit a diagnostic. Unlike per-file rules, project rules MUST set\n * `path` explicitly — the runner cannot infer which file the\n * diagnostic relates to.\n */\n report(diagnostic: Omit<Diagnostic, 'ruleName' | 'severity'>): void;\n}\n\n/**\n * A cross-file rule. Receives all parsed files at once and reports\n * diagnostics with explicit `path` per file.\n *\n * Project rules use a different runner function (`runRulesOnProject`)\n * and a distinct context shape from per-file rules. See ADR-0005 for\n * the rationale behind keeping the two APIs separate.\n */\nexport interface ProjectRule<TOptions = Record<string, unknown>> {\n meta: RuleMeta<TOptions>;\n check(context: ProjectRuleContext<TOptions>): void;\n}\n\n/** Either a per-file or a project rule. */\nexport type AnyRule<TOptions = Record<string, unknown>> =\n | Rule<TOptions>\n | ProjectRule<TOptions>;\n\n/** Type guard distinguishing project rules from per-file rules. */\nexport function isProjectRule(rule: AnyRule): rule is ProjectRule {\n return 'check' in rule;\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { Diagnostic } from './types.js';\n\n/**\n * Per-file cache entry: the file content's sha1 hash plus the per-file\n * diagnostics that the rule pipeline emitted last time.\n *\n * Note: project (cross-file) diagnostics are NOT cached — they depend on\n * the entire file set and would invalidate on any add/remove/rename.\n */\nexport interface CacheEntry {\n contentHash: string;\n perFileDiagnostics: Diagnostic[];\n}\n\nexport interface CacheManifest {\n /** madr-lint version when this manifest was written. Mismatch invalidates the cache. */\n version: string;\n /** Stable hash of the resolved config. Mismatch invalidates the cache. */\n configHash: string;\n /** Per-file cached entries, keyed by POSIX-normalized relative path. */\n files: Record<string, CacheEntry>;\n}\n\nexport function computeContentHash(content: string): string {\n return createHash('sha1').update(content, 'utf8').digest('hex');\n}\n\nexport function computeConfigHash(config: unknown): string {\n return createHash('sha1').update(stableStringify(config), 'utf8').digest('hex');\n}\n\n/**\n * Stable JSON stringify: object keys are sorted so the same logical\n * config always produces the same hash regardless of property insertion\n * order. Cycles are not handled — config objects are tree-shaped.\n */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return '[' + value.map(stableStringify).join(',') + ']';\n }\n const entries = Object.entries(value as Record<string, unknown>).toSorted(\n ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0),\n );\n return (\n '{' +\n entries\n .map(([k, v]) => JSON.stringify(k) + ':' + stableStringify(v))\n .join(',') +\n '}'\n );\n}\n\nexport function manifestPath(cacheDir: string): string {\n return join(cacheDir, 'manifest.json');\n}\n\nexport function loadManifest(path: string): CacheManifest | null {\n if (!existsSync(path)) return null;\n try {\n const data = JSON.parse(readFileSync(path, 'utf8')) as Partial<CacheManifest>;\n if (\n typeof data.version !== 'string' ||\n typeof data.configHash !== 'string' ||\n typeof data.files !== 'object' ||\n data.files === null\n ) {\n return null;\n }\n return data as CacheManifest;\n } catch {\n return null;\n }\n}\n\nexport function saveManifest(path: string, manifest: CacheManifest): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(manifest), 'utf8');\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { createJiti } from 'jiti';\nimport { recommended } from '../configs/recommended.js';\nimport type { MadrLintConfig } from '../index.js';\nimport type { MadrVersion, RuleSeverity } from './types.js';\n\nexport interface ResolvedConfig {\n /** ADR directory, relative to cwd or absolute. Default: 'docs/adr'. */\n adrDir: string;\n /** Per-rule severity / options map. Empty when no preset extended. */\n rules: Record<string, RuleSeverity>;\n /** Glob patterns to skip. */\n ignorePatterns: string[];\n /** MADR version target. Default: 'auto'. */\n madrVersion: MadrVersion | 'auto';\n /** Whether to use per-file content-hash cache. Default: true. */\n cache: boolean;\n /** Cache directory (relative to cwd). Default: '.madr-lint/cache'. */\n cacheLocation: string;\n}\n\n/**\n * Config file resolution order. First match wins.\n *\n * `.json` is parsed directly (no module loader), so it stays the fastest\n * and dependency-free path. The other extensions go through `jiti`,\n * which transpiles TS/ESM/CJS on the fly.\n */\nconst CONFIG_FILES = [\n '.madrlintrc.json',\n '.madrlintrc.ts',\n '.madrlintrc.mts',\n '.madrlintrc.js',\n '.madrlintrc.mjs',\n '.madrlintrc.cjs',\n 'madr-lint.config.ts',\n 'madr-lint.config.mts',\n 'madr-lint.config.js',\n 'madr-lint.config.mjs',\n 'madr-lint.config.cjs',\n];\n\nexport class ConfigFileNotFoundError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigFileNotFoundError';\n }\n}\n\n/**\n * Load and resolve a config from an explicit file path, bypassing discovery.\n * Throws `ConfigFileNotFoundError` if the file does not exist.\n * Throws `SyntaxError` or other load errors if the file is malformed.\n */\nexport function loadConfigFromPath(filePath: string): ResolvedConfig {\n // Race-free error classification: fs check-APIs (existsSync/statSync) before\n // a use are TOCTOU by construction (CodeQL js/file-system-race). Reading IS\n // the use, so classify its errors instead: ENOENT/EISDIR carry exactly the\n // two cases we distinguish, with no check-then-use window.\n let raw: string;\n try {\n raw = readFileSync(filePath, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n throw new ConfigFileNotFoundError(`Config file not found: ${filePath}`);\n }\n // A directory exists on disk but jiti's failure reads like a missing\n // npm package (\"Cannot find module\") — fail with an honest message instead.\n if (code === 'EISDIR') {\n throw new ConfigFileNotFoundError(\n `Config path is a directory, not a file: ${filePath}`,\n );\n }\n throw err;\n }\n if (filePath.endsWith('.json')) {\n const parsed = JSON.parse(raw) as MadrLintConfig;\n return resolveExtends(parsed);\n }\n const jiti = createJiti(import.meta.url, { interopDefault: true });\n const loaded = jiti(filePath) as MadrLintConfig | { default: MadrLintConfig };\n const config: MadrLintConfig =\n typeof loaded === 'object' && loaded !== null && 'default' in loaded\n ? (loaded.default as MadrLintConfig)\n : (loaded as MadrLintConfig);\n return resolveExtends(config);\n}\n\n/**\n * Loads and resolves a config from `cwd`. If no config file is found,\n * returns the defaults (no rules enabled — caller can opt into the\n * recommended preset by extending).\n *\n * `.json` is read synchronously and parsed inline. All other extensions\n * are loaded via `jiti`, supporting TypeScript and both module systems.\n */\nexport function loadConfig(cwd: string): ResolvedConfig {\n for (const name of CONFIG_FILES) {\n const path = resolve(cwd, name);\n if (!existsSync(path)) continue;\n\n if (name.endsWith('.json')) {\n const parsed = JSON.parse(readFileSync(path, 'utf8')) as MadrLintConfig;\n return resolveExtends(parsed);\n }\n\n const jiti = createJiti(import.meta.url, { interopDefault: true });\n const loaded = jiti(path) as MadrLintConfig | { default: MadrLintConfig };\n const config: MadrLintConfig =\n typeof loaded === 'object' && loaded !== null && 'default' in loaded\n ? (loaded.default as MadrLintConfig)\n : (loaded as MadrLintConfig);\n return resolveExtends(config);\n }\n return resolveExtends({});\n}\n\n/**\n * Pure function: turns a raw `MadrLintConfig` into a `ResolvedConfig`\n * with defaults filled in and `extends` presets merged.\n */\nexport function resolveExtends(config: MadrLintConfig): ResolvedConfig {\n const baseRules: Record<string, RuleSeverity> = config.extends?.includes(\n 'madr-lint:recommended',\n )\n ? { ...recommended }\n : {};\n\n return {\n adrDir: config.adrDir ?? 'docs/adr',\n rules: { ...baseRules, ...config.rules },\n ignorePatterns: config.ignorePatterns ?? [],\n madrVersion: config.madrVersion ?? 'auto',\n cache: config.cache ?? true,\n cacheLocation: config.cacheLocation ?? '.madr-lint/cache',\n };\n}\n","import type { RuleSeverity } from '../core/types.js';\n\n// The `recommended` preset enables rules whose default behavior is broadly\n// useful and grounded in the MADR spec. New rules append here via the\n// add-rule skill, with severity decided per-rule (default `error` for\n// spec-grounded rules, `warn` for convention-only rules).\n//\n// Both bare-string and tuple forms are supported here:\n// 'madr/foo': 'error' — enable with defaults\n// 'madr/foo': ['error', { pattern: '^X' }] — enable with override\n\nexport const recommended: Record<string, RuleSeverity> = {\n 'madr/date-iso8601': 'error',\n 'madr/filename-format': 'error',\n 'madr/no-broken-links': 'error',\n 'madr/no-duplicate-numbering': 'error',\n // Convention-only — opt in if your team treats ADR numbering as a\n // contiguous sequence. See https://knktkc.github.io/madr-lint/rules/no-numbering-gap/.\n 'madr/no-numbering-gap': 'off',\n 'madr/required-sections': 'error',\n 'madr/status-enum': 'error',\n 'madr/supersedes-bidirectional': 'error',\n};\n","import { existsSync, readdirSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * Resolves a target path to a list of `.md` files to lint.\n *\n * - If the target is a directory: recursively walks it and returns every `.md`\n * file, sorted lexicographically.\n * - If the target is a `.md` file: returns just that file.\n * - If the target is a non-`.md` file or does not exist: returns `[]`.\n *\n * The empty-array fallback lets the CLI print \"No .md files found\" rather\n * than crashing — the caller decides whether that is an error.\n */\nexport function findAdrFiles(target: string): string[] {\n if (!existsSync(target)) return [];\n\n const stat = statSync(target);\n if (stat.isFile()) {\n return target.endsWith('.md') ? [target] : [];\n }\n if (!stat.isDirectory()) return [];\n\n const entries = readdirSync(target, { recursive: true, withFileTypes: true });\n return entries\n .filter((e) => e.isFile() && e.name.endsWith('.md'))\n .map((e) => join(e.parentPath, e.name))\n .toSorted();\n}\n","import { basename } from 'node:path';\nimport picomatch from 'picomatch';\n\n/**\n * Should the given relative path be excluded from linting?\n *\n * Patterns are tested in three forms (any match wins):\n * - **Full glob via picomatch** against the relative POSIX path:\n * `docs/**\\/draft-*.md`, `**\\/template.md`, `9999-*.md`\n * - Full glob via picomatch against the file's basename, so patterns\n * like `README.md` or `9999-*` work without a `**\\/` prefix.\n * - Exact relative-path match (defensive — picomatch with default\n * options also handles this, but we keep the explicit branch for\n * clarity and to avoid surprises if picomatch ever changes default\n * `dot`/`bash` semantics).\n *\n * Picomatch is invoked with `{ dot: true }` so dotfiles (rare for ADRs\n * but possible — e.g. `.archived/*.md`) are matched naturally.\n */\nexport function shouldIgnore(\n relativePath: string,\n patterns: readonly string[],\n): boolean {\n if (patterns.length === 0) return false;\n const base = basename(relativePath);\n for (const pattern of patterns) {\n if (matchesPattern(relativePath, base, pattern)) return true;\n }\n return false;\n}\n\nfunction matchesPattern(\n relativePath: string,\n base: string,\n pattern: string,\n): boolean {\n if (relativePath === pattern) return true;\n const matcher = picomatch(pattern, { dot: true });\n if (matcher(relativePath)) return true;\n if (matcher(base)) return true;\n // Back-compat shortcut: a pattern like `adr/template.md` (sub-path\n // without leading `**/`) should match `docs/adr/template.md`. Also\n // handles `adr/9999-*` against `docs/adr/9999-x.md` via picomatch\n // applied to the suffix.\n if (pattern.includes('/') && !pattern.startsWith('**/')) {\n const suffixMatcher = picomatch(`**/${pattern}`, { dot: true });\n if (suffixMatcher(relativePath)) return true;\n }\n return false;\n}\n","import { readFileSync, statSync } from 'node:fs';\nimport { isAbsolute, relative, resolve, sep } from 'node:path';\nimport { applyBaseline, type Baseline } from './baseline.js';\nimport {\n computeContentHash,\n loadManifest,\n manifestPath,\n saveManifest,\n type CacheEntry,\n type CacheManifest,\n} from './cache.js';\nimport {\n buildProjectFile,\n runRulesOnFile,\n runRulesOnProject,\n} from './runner.js';\nimport {\n collectDirectives,\n isSuppressed,\n DIRECTIVE_PREFIX,\n type DirectiveIndex,\n} from './suppression.js';\n\n/**\n * Normalize a relative path to POSIX form (forward-slashes). On Windows,\n * `relative()` returns backslash-separated paths, but project rules\n * (e.g. `no-broken-links`) resolve URLs using `posix.normalize`. Mixing\n * separators causes silent false positives — so the orchestrator owns\n * the normalization.\n */\nfunction toPosix(p: string): string {\n if (sep === '/') return p;\n return p.split(sep).join('/');\n}\nimport {\n INTERNAL_ERROR_RULE_NAME,\n isProjectRule,\n type AnyRule,\n type Diagnostic,\n type ProjectFile,\n type ProjectRule,\n type Rule,\n type RuleSeverity,\n type Severity,\n} from './types.js';\n\nexport interface CacheConfig {\n /** Directory under which manifest.json is read/written. */\n dir: string;\n /** Stable hash of the resolved config. Mismatch invalidates the cache. */\n configHash: string;\n /** madr-lint package version. Mismatch invalidates the cache. */\n pkgVersion: string;\n}\n\nexport interface LintOptions {\n /** All available rules (per-file or project). The orchestrator picks\n * enabled ones via ruleSeverity and dispatches to the right runner. */\n rules: readonly AnyRule[];\n /** User-configured severity per rule name. Missing entry === 'off'. */\n ruleSeverity: Record<string, RuleSeverity>;\n /** Files to lint, absolute or cwd-relative paths. */\n files: readonly string[];\n /** Working directory. Diagnostics' `path` is reported relative to this. */\n cwd: string;\n /**\n * If set, persist per-file diagnostics keyed by content hash to enable\n * fast re-runs of unchanged files. Project (cross-file) rules always\n * re-run regardless of the cache. Pass `null` to disable.\n */\n cache?: CacheConfig | null;\n /**\n * Parsed baseline to subtract, or null/undefined to disable. Subtraction\n * runs AFTER inline-suppression filtering and is NEVER written to the cache\n * (the cache keeps pre-baseline diagnostics, so editing or deleting the\n * baseline file takes effect without cache invalidation). See ADR-0007.\n */\n baseline?: Baseline | null;\n}\n\nexport interface LintResult {\n filesChecked: number;\n filesFromCache: number;\n diagnostics: Diagnostic[];\n /** How many diagnostics the baseline absorbed (0 when no baseline). */\n baselineHidden: number;\n}\n\n/**\n * Lint a list of files against per-file AND project rules.\n *\n * Per-file rules go through `runRulesOnFile` (single-pass AST per file).\n * Project rules go through `runRulesOnProject` (eager parse all files,\n * single check call per rule). See ADR-0005.\n *\n * File contents are read once and shared between both passes.\n */\nexport function lintFiles(opts: LintOptions): LintResult {\n const allDiagnostics: Diagnostic[] = [];\n\n // Read all file contents once — shared between per-file and project passes.\n // POSIX-normalize the relative path so cross-platform diagnostics and\n // path-based rules (e.g. no-broken-links) work consistently on Windows.\n const fileEntries = opts.files.map((absolutePath) => ({\n relativePath: toPosix(relative(opts.cwd, absolutePath)),\n content: readFileSync(absolutePath, 'utf8'),\n }));\n\n // Partition rules by kind.\n const perFileRules: Rule[] = [];\n const projectRules: ProjectRule[] = [];\n for (const rule of opts.rules) {\n if (isProjectRule(rule)) projectRules.push(rule);\n else perFileRules.push(rule);\n }\n\n // Per-rule options from config tuples (`['error', {...}]`), threaded into\n // both passes so rule options actually take effect (not just defaults).\n const optionsByRule = extractOptionsByRule(opts.ruleSeverity);\n\n // ── Cache setup ──────────────────────────────────────────────────\n let manifest: CacheManifest | null = null;\n let filesFromCache = 0;\n if (opts.cache) {\n const path = manifestPath(opts.cache.dir);\n const loaded = loadManifest(path);\n if (\n loaded &&\n loaded.version === opts.cache.pkgVersion &&\n loaded.configHash === opts.cache.configHash\n ) {\n manifest = loaded;\n } else {\n manifest = {\n version: opts.cache.pkgVersion,\n configHash: opts.cache.configHash,\n files: {},\n };\n }\n }\n\n // ── Per-file pass ────────────────────────────────────────────────\n for (const file of fileEntries) {\n if (manifest) {\n const contentHash = computeContentHash(file.content);\n const entry = manifest.files[file.relativePath];\n if (entry && entry.contentHash === contentHash) {\n allDiagnostics.push(...entry.perFileDiagnostics);\n filesFromCache++;\n continue;\n }\n // Cache miss — run rules and store result.\n const fileDiagnostics = runPerFileRulesForFile(\n perFileRules,\n opts.ruleSeverity,\n optionsByRule,\n file,\n );\n allDiagnostics.push(...fileDiagnostics);\n const next: CacheEntry = {\n contentHash,\n perFileDiagnostics: fileDiagnostics,\n };\n manifest.files[file.relativePath] = next;\n } else {\n allDiagnostics.push(\n ...runPerFileRulesForFile(\n perFileRules,\n opts.ruleSeverity,\n optionsByRule,\n file,\n ),\n );\n }\n }\n\n // ── Project pass ─────────────────────────────────────────────────\n const enabledProjectRules = projectRules.filter(\n (rule) => resolveSeverity(opts.ruleSeverity[rule.meta.name]) !== 'off',\n );\n if (enabledProjectRules.length > 0) {\n const projectFiles = fileEntries.map((f) =>\n buildProjectFile({ path: f.relativePath, content: f.content }),\n );\n\n // Does a path exist as a regular file WITHIN the project root? Lets\n // project rules verify link targets that are not in the linted .md set\n // (non-Markdown assets, files outside the scanned paths). Contract:\n // - a target that resolves at or above the root escapes the project →\n // false (path traversal cannot reach above the root);\n // - directories are not files → false (a link must point at a file);\n // - results are memoized per lint run (repeated targets cost one stat).\n // The containment test compares the resolved absolute path to the root\n // rather than a lexical prefix on `resolvedPath`, which may be\n // un-normalized (e.g. a `/`-rooted link resolving to `foo/../../x`).\n // NOTE: statSync follows symlinks, so a symlink that lives inside the root\n // but points outside it is accepted — it is a real entry in the project\n // tree. `resolvedPath` is POSIX; node's path.resolve accepts forward\n // slashes on all platforms.\n const projectRoot = resolve(opts.cwd);\n const existsCache = new Map<string, boolean>();\n const fileExists = (resolvedPath: string): boolean => {\n const cached = existsCache.get(resolvedPath);\n if (cached !== undefined) return cached;\n const abs = resolve(projectRoot, resolvedPath);\n const rel = relative(projectRoot, abs);\n const escapesRoot =\n rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel);\n let result: boolean;\n if (escapesRoot) {\n result = false;\n } else {\n try {\n result = statSync(abs, { throwIfNoEntry: false })?.isFile() ?? false;\n } catch {\n // ELOOP / EACCES / invalid path → cannot confirm a regular file.\n result = false;\n }\n }\n existsCache.set(resolvedPath, result);\n return result;\n };\n\n const errorRules: ProjectRule[] = [];\n const warnRules: ProjectRule[] = [];\n for (const rule of enabledProjectRules) {\n const sev = resolveSeverity(opts.ruleSeverity[rule.meta.name]);\n if (sev === 'error') errorRules.push(rule);\n else if (sev === 'warn') warnRules.push(rule);\n }\n\n const projectDiagnostics: Diagnostic[] = [];\n if (errorRules.length > 0) {\n projectDiagnostics.push(\n ...runRulesOnProject(errorRules, projectFiles, {\n severity: 'error',\n fileExists,\n optionsByRule,\n }),\n );\n }\n if (warnRules.length > 0) {\n projectDiagnostics.push(\n ...runRulesOnProject(warnRules, projectFiles, {\n severity: 'warn',\n fileExists,\n optionsByRule,\n }),\n );\n }\n\n // Inline suppression for project diagnostics (issue #23): a directive\n // lives in the file the diagnostic is attributed to (project rules report\n // an explicit `path`). File-scoped directives (disable-file, or an\n // open-ended disable) suppress line-less project diagnostics; line-scoped\n // directives apply when the diagnostic carries a line.\n allDiagnostics.push(\n ...filterSuppressedProjectDiagnostics(projectDiagnostics, projectFiles),\n );\n }\n\n // ── Persist cache ────────────────────────────────────────────────\n // Cache the PRE-baseline diagnostics: subtraction happens below, after the\n // save, so the on-disk cache is independent of the baseline file.\n if (manifest && opts.cache) {\n saveManifest(manifestPath(opts.cache.dir), manifest);\n }\n\n // ── Baseline subtraction ─────────────────────────────────────────\n // Zero work when no baseline is provided (the common hot path).\n if (!opts.baseline) {\n return {\n filesChecked: opts.files.length,\n filesFromCache,\n diagnostics: allDiagnostics,\n baselineHidden: 0,\n };\n }\n const applied = applyBaseline(allDiagnostics, opts.baseline);\n return {\n filesChecked: opts.files.length,\n filesFromCache,\n diagnostics: applied.kept,\n baselineHidden: applied.hidden,\n };\n}\n\nfunction runPerFileRulesForFile(\n perFileRules: readonly Rule[],\n ruleSeverity: Record<string, RuleSeverity>,\n optionsByRule: Record<string, Record<string, unknown>>,\n file: { relativePath: string; content: string },\n): Diagnostic[] {\n const fileContext = {\n content: file.content,\n path: file.relativePath,\n };\n\n const errorRules: Rule[] = [];\n const warnRules: Rule[] = [];\n for (const rule of perFileRules) {\n const sev = resolveSeverity(ruleSeverity[rule.meta.name]);\n if (sev === 'off') continue;\n if (sev === 'error') errorRules.push(rule);\n else warnRules.push(rule);\n }\n\n const diagnostics: Diagnostic[] = [];\n if (errorRules.length > 0) {\n diagnostics.push(\n ...runRulesOnFile(errorRules, fileContext, {\n severity: 'error',\n optionsByRule,\n }),\n );\n }\n if (warnRules.length > 0) {\n diagnostics.push(\n ...runRulesOnFile(warnRules, fileContext, {\n severity: 'warn',\n optionsByRule,\n }),\n );\n }\n return diagnostics;\n}\n\n/**\n * Filter suppressed project-rule diagnostics. Each diagnostic is matched\n * against the directives of the file it is attributed to (by `path`).\n * Directive indexes are collected lazily and memoized so a file with no\n * suppressed diagnostics is walked at most once. `core/internal-error`\n * diagnostics (and any diagnostic whose path has no source file, e.g. the\n * `<project>` sentinel) are never suppressed.\n */\nfunction filterSuppressedProjectDiagnostics(\n diagnostics: readonly Diagnostic[],\n projectFiles: readonly ProjectFile[],\n): Diagnostic[] {\n if (diagnostics.length === 0) return [];\n\n const fileByPath = new Map(projectFiles.map((f) => [f.path, f]));\n const indexByPath = new Map<string, DirectiveIndex | null>();\n const indexFor = (path: string): DirectiveIndex | null => {\n const cached = indexByPath.get(path);\n if (cached !== undefined) return cached;\n const file = fileByPath.get(path);\n // Unlike the per-file path, no parse can be forced here — project files\n // are eager-parsed by buildProjectFile before rules run. The prefix\n // check just skips the AST walk for directive-free files (same\n // soundness argument: no 'madr-lint-' in content ⇒ no directives).\n const index =\n file && file.content.includes(DIRECTIVE_PREFIX)\n ? collectDirectives(file.ast, file.body)\n : null;\n indexByPath.set(path, index);\n return index;\n };\n\n return diagnostics.filter((d) => {\n if (d.ruleName === INTERNAL_ERROR_RULE_NAME) return true;\n const index = indexFor(d.path);\n if (!index) return true;\n return !isSuppressed(index, d.ruleName, d.loc?.line);\n });\n}\n\nfunction resolveSeverity(config: RuleSeverity | undefined): Severity | 'off' {\n if (config === undefined) return 'off';\n if (typeof config === 'string') return config;\n return config[0];\n}\n\n/**\n * Build a ruleName → options map from config tuples (`['error', {...}]`).\n * Bare-string severities carry no options and are omitted, so rules without\n * configured options fall back to their `meta.defaultOptions` in the runner.\n */\nfunction extractOptionsByRule(\n ruleSeverity: Record<string, RuleSeverity>,\n): Record<string, Record<string, unknown>> {\n const map: Record<string, Record<string, unknown>> = {};\n for (const [name, config] of Object.entries(ruleSeverity)) {\n // Only tuples carry options; guard config[1] so a malformed 1-element\n // `['error']` doesn't put `undefined` into the map.\n if (Array.isArray(config) && config[1]) map[name] = config[1];\n }\n return map;\n}\n","import Ajv, { type AnySchemaObject, type ValidateFunction } from 'ajv';\nimport {\n INTERNAL_ERROR_RULE_NAME,\n type Diagnostic,\n type FileContext,\n type MdastNode,\n type ProjectFile,\n type ProjectRule,\n type ProjectRuleContext,\n type Rule,\n type RuleContext,\n type RuleListeners,\n type Severity,\n} from './types.js';\nimport { parseFile, type ParsedFile } from './parser.js';\nimport {\n collectDirectives,\n filterSuppressed,\n DIRECTIVE_PREFIX,\n} from './suppression.js';\n\n// strict: true catches typo'd schema keywords at compile time.\n// allErrors: true so RuleOptionsError surfaces every issue at once.\nconst ajv = new Ajv({ strict: true, allErrors: true });\n\n// Cache compiled validators per schema object reference.\n// Schemas are module-level static on rules, so the cache key never goes stale.\n// (If a rule mutates `meta.schema` post-load — don't — the cache will desync.)\nconst validatorCache = new WeakMap<AnySchemaObject, ValidateFunction>();\n\nfunction getValidator(schema: AnySchemaObject): ValidateFunction {\n let validator = validatorCache.get(schema);\n if (!validator) {\n validator = ajv.compile(schema);\n validatorCache.set(schema, validator);\n }\n return validator;\n}\n\n// Defined in types.ts (leaf module) so the suppression layer can reference\n// it without a runner import cycle; re-exported here for API stability.\nexport { INTERNAL_ERROR_RULE_NAME };\n\n/**\n * Thrown when a rule's merged options fail AJV validation against\n * `rule.meta.schema`. Distinct from generic `Error` so callers can\n * `instanceof` to skip rules with bad config and continue.\n */\nexport class RuleOptionsError extends Error {\n constructor(\n public readonly ruleName: string,\n public readonly ajvErrors: string,\n ) {\n super(`Invalid options for rule ${ruleName}: ${ajvErrors}`);\n this.name = 'RuleOptionsError';\n }\n}\n\nexport interface RunRuleOptions {\n /** Per-rule options to merge over rule.meta.defaultOptions. */\n options?: Record<string, unknown>;\n /**\n * Options keyed by rule name, for multi-rule calls where each rule needs\n * its own options (e.g. config tuples `['error', {...}]`). For a given rule,\n * an entry here takes precedence over `options`; rules absent from the map\n * fall back to `options` (if any), then `meta.defaultOptions`.\n */\n optionsByRule?: Record<string, Record<string, unknown>>;\n /** Severity to attach to emitted diagnostics. Defaults to 'error'. */\n severity?: Severity;\n /** Skip AJV options validation. Default false. */\n skipValidation?: boolean;\n /**\n * Filesystem-existence predicate exposed to project rules as\n * `context.fileExists`. Per-file runs ignore this. See\n * ProjectRuleContext.fileExists.\n */\n fileExists?: (resolvedPath: string) => boolean;\n}\n\n/**\n * Per-rule, per-file rule context. The lazy-parse getters live on the class\n * PROTOTYPE — object literals with getters force expensive per-call shape\n * setup, which the filename-format micro-bench (~400ns/op) measured as a\n * double-digit % regression when a third getter was added (PR #53).\n * Prototype accessors are set up once; instantiation is near-free. `report`\n * stays a per-instance closure (it captures the rule name and severity, and\n * this keeps it safely destructurable by rule authors).\n */\nclass PerFileRuleContext implements RuleContext {\n readonly file: FileContext;\n readonly options: Record<string, unknown>;\n readonly report: RuleContext['report'];\n private readonly ensureParsed: () => ParsedFile;\n\n constructor(\n file: FileContext,\n options: Record<string, unknown>,\n ensureParsed: () => ParsedFile,\n report: RuleContext['report'],\n ) {\n this.file = file;\n this.options = options;\n this.ensureParsed = ensureParsed;\n this.report = report;\n }\n\n get frontmatter(): Record<string, unknown> | null {\n return this.ensureParsed().frontmatter;\n }\n\n get metadata(): Record<string, unknown> | null {\n return this.ensureParsed().metadata;\n }\n\n get metadataLoc(): Record<string, { line: number; column: number }> | null {\n return this.ensureParsed().metadataLoc;\n }\n}\n\n/**\n * Run a single rule against a single file. Sugar over runRulesOnFile\n * for the common one-rule case (used heavily by tests).\n *\n * Note: inline suppression directives (`<!-- madr-lint-disable... -->`)\n * present in `file.content` ARE honored — matching diagnostics are filtered.\n */\nexport function runRule<TOptions extends Record<string, unknown>>(\n rule: Rule<TOptions>,\n file: FileContext,\n runtime: RunRuleOptions = {},\n): Diagnostic[] {\n return runRulesOnFile([rule as Rule], file, runtime);\n}\n\n/**\n * Run multiple rules against a single file with a single mdast traversal.\n *\n * Steps:\n * 1. Validate each rule's merged options against its schema (AJV).\n * Throws RuleOptionsError on failure (caller decides whether to skip).\n * 2. Call each rule's create(). If a rule throws, the error is caught\n * and reported as a `core/internal-error` diagnostic — other rules\n * continue. The same isolation wraps every enter/exit handler so a\n * single buggy rule cannot abort the whole lint run.\n * 3. If at least one rule returned RuleListeners, call parseFile()\n * ONCE (gray-matter + mdast-util-from-markdown together; there is\n * no separate cheap \"frontmatter only\" path) and walk the tree,\n * dispatching enter/exit handlers per node type.\n *\n * Frontmatter is exposed lazily via context.frontmatter — the getter\n * triggers parseFile() on first access. Filename-style rules that never\n * touch frontmatter and return void from create() pay zero parse cost.\n *\n * Note: inline suppression directives (`<!-- madr-lint-disable... -->`)\n * present in `file.content` ARE honored — matching diagnostics are filtered\n * centrally after all rules have reported (see suppression.ts).\n */\nexport function runRulesOnFile(\n rules: readonly Rule[],\n file: FileContext,\n runtime: RunRuleOptions = {},\n): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n const severity = runtime.severity ?? 'error';\n\n let parsed: ParsedFile | null = null;\n const ensureParsed = (): ParsedFile => {\n parsed ??= parseFile(file.content);\n return parsed;\n };\n\n const enterMap: Record<string, Array<(node: MdastNode) => void>> = {};\n const exitMap: Record<string, Array<(node: MdastNode) => void>> = {};\n let hasASTRule = false;\n\n for (const rule of rules) {\n const perRuleOptions =\n runtime.optionsByRule?.[rule.meta.name] ?? runtime.options;\n const mergedOptions = {\n ...rule.meta.defaultOptions,\n ...perRuleOptions,\n };\n\n if (rule.meta.schema && !runtime.skipValidation) {\n const validator = getValidator(rule.meta.schema);\n if (!validator(mergedOptions)) {\n throw new RuleOptionsError(rule.meta.name, ajv.errorsText(validator.errors));\n }\n }\n\n const context: RuleContext = new PerFileRuleContext(\n file,\n mergedOptions,\n ensureParsed,\n (d) => {\n diagnostics.push({\n ruleName: rule.meta.name,\n severity,\n path: file.path,\n ...d,\n });\n },\n );\n\n let listeners: RuleListeners | void;\n try {\n listeners = rule.create(context);\n } catch (err) {\n // RuleOptionsError signals the user's config is wrong (e.g. unsafe\n // regex). Propagate it so the CLI can render a clear \"fix your\n // .madrlintrc\" message rather than burying it as a per-file\n // internal-error diagnostic.\n if (err instanceof RuleOptionsError) throw err;\n diagnostics.push(\n internalErrorDiagnostic(rule.meta.name, 'create', err, file.path),\n );\n continue;\n }\n\n if (listeners) {\n hasASTRule = true;\n collectListeners(rule, listeners, enterMap, exitMap, diagnostics, file);\n }\n }\n\n if (hasASTRule) {\n walk(ensureParsed().ast, enterMap, exitMap);\n }\n\n // Central, post-report suppression (issue #23). Rules stay unaware; the\n // runner filters here using directives collected from the file's `html`\n // comment nodes. We only pay the parse + directive walk when there is\n // something to potentially suppress — a clean file short-circuits, so\n // filename-only rules on passing files keep their zero-parse fast path.\n if (diagnostics.length === 0) return diagnostics;\n // Perf guard (PR #53): every directive form contains the literal\n // 'madr-lint-', and the parsed body is a substring of the raw content, so\n // its absence PROVES no directives exist — filtering can be skipped\n // without parsing. Without this, a Shape-A filename diagnostic on an\n // otherwise-unparsed file forced a full gray-matter+mdast parse here\n // (measured -99% on the filename-format invalid-path bench). The substring\n // scan is ~µs; files that do contain the literal proceed exactly as before.\n if (!file.content.includes(DIRECTIVE_PREFIX)) return diagnostics;\n const { ast, body } = ensureParsed();\n const directives = collectDirectives(ast, body);\n return directives ? filterSuppressed(diagnostics, directives) : diagnostics;\n}\n\n// Internal-error diagnostics are ALWAYS severity 'error' regardless of the\n// runtime-passed severity for the rule that threw — a rule misbehaving is\n// never something the user wants to silence as a warning.\nfunction internalErrorDiagnostic(\n ruleName: string,\n operation: 'create' | 'enter' | 'exit' | 'check',\n err: unknown,\n path: string,\n): Diagnostic {\n return {\n ruleName: INTERNAL_ERROR_RULE_NAME,\n messageId: 'ruleThrew',\n severity: 'error',\n path,\n data: {\n rule: ruleName,\n operation,\n error: err instanceof Error ? err.message : String(err),\n },\n };\n}\n\nfunction collectListeners(\n rule: Rule,\n listeners: RuleListeners,\n enterMap: Record<string, Array<(node: MdastNode) => void>>,\n exitMap: Record<string, Array<(node: MdastNode) => void>>,\n diagnostics: Diagnostic[],\n file: FileContext,\n): void {\n const wrap =\n (op: 'enter' | 'exit') => (handler: (node: MdastNode) => void) => (node: MdastNode) => {\n try {\n handler(node);\n } catch (err) {\n diagnostics.push(\n internalErrorDiagnostic(rule.meta.name, op, err, file.path),\n );\n }\n };\n\n if (listeners.enter) {\n const wrapEnter = wrap('enter');\n for (const [type, handler] of Object.entries(listeners.enter)) {\n if (handler) (enterMap[type] ??= []).push(wrapEnter(handler));\n }\n }\n if (listeners.exit) {\n const wrapExit = wrap('exit');\n for (const [type, handler] of Object.entries(listeners.exit)) {\n if (handler) (exitMap[type] ??= []).push(wrapExit(handler));\n }\n }\n}\n\nfunction walk(\n node: MdastNode,\n enterMap: Record<string, Array<(node: MdastNode) => void>>,\n exitMap: Record<string, Array<(node: MdastNode) => void>>,\n): void {\n const enterHandlers = enterMap[node.type];\n if (enterHandlers) {\n for (const handler of enterHandlers) handler(node);\n }\n if ('children' in node && Array.isArray(node.children)) {\n for (const child of node.children) {\n walk(child as MdastNode, enterMap, exitMap);\n }\n }\n const exitHandlers = exitMap[node.type];\n if (exitHandlers) {\n for (const handler of exitHandlers) handler(node);\n }\n}\n\n/**\n * Build a `ProjectFile` (path + content + parsed frontmatter + AST) from\n * a raw file. Used by `runRulesOnProject` and by the lint orchestrator\n * to share parsing between per-file and project passes when needed.\n */\nexport function buildProjectFile(file: FileContext): ProjectFile {\n const parsed: ParsedFile = parseFile(file.content);\n return {\n path: file.path,\n content: file.content,\n body: parsed.body,\n frontmatter: parsed.frontmatter,\n metadata: parsed.metadata,\n ast: parsed.ast,\n };\n}\n\n/**\n * Run multiple project rules across all parsed files. Each rule's\n * `check()` is called once with the full file array. Throws are\n * captured as `core/internal-error` diagnostics (attached to the\n * first file's path, since project rules have no file context).\n *\n * See ADR-0005 for the API rationale.\n */\nexport function runRulesOnProject(\n rules: readonly ProjectRule[],\n files: readonly ProjectFile[],\n runtime: RunRuleOptions = {},\n): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n const severity = runtime.severity ?? 'error';\n\n for (const rule of rules) {\n const perRuleOptions =\n runtime.optionsByRule?.[rule.meta.name] ?? runtime.options;\n const mergedOptions = {\n ...rule.meta.defaultOptions,\n ...perRuleOptions,\n };\n\n if (rule.meta.schema && !runtime.skipValidation) {\n const validator = getValidator(rule.meta.schema);\n if (!validator(mergedOptions)) {\n throw new RuleOptionsError(\n rule.meta.name,\n ajv.errorsText(validator.errors),\n );\n }\n }\n\n const context: ProjectRuleContext = {\n files,\n options: mergedOptions,\n fileExists: runtime.fileExists,\n report(d) {\n diagnostics.push({\n ruleName: rule.meta.name,\n severity,\n ...d,\n });\n },\n };\n\n try {\n rule.check(context);\n } catch (err) {\n // Project rules have no current-file context — attribute the\n // internal-error to a sentinel path rather than mis-attributing\n // to whatever file happens to be first in the array.\n diagnostics.push(\n internalErrorDiagnostic(rule.meta.name, 'check', err, '<project>'),\n );\n }\n }\n\n return diagnostics;\n}\n","import type { List, ListItem, Paragraph, Root } from 'mdast';\nimport { fromMarkdown } from 'mdast-util-from-markdown';\nimport { toString } from 'mdast-util-to-string';\nimport grayMatter from 'gray-matter';\n\n/** Source position of a metadata list item, in body coordinates. */\nexport interface MetadataPosition {\n line: number;\n column: number;\n}\n\nexport interface ParsedFile {\n /** Parsed YAML frontmatter (v3/v4), or null if absent. */\n frontmatter: Record<string, unknown> | null;\n /**\n * v2 body-list metadata extracted from the leading list, or null if absent.\n * Covers both the bold-key (`- **Status**:`) and the canonical MADR v2.1.2\n * plain-key (`* Status:`) shapes. See ADR-0006.\n */\n listMetadata: Record<string, unknown> | null;\n /**\n * Combined metadata: frontmatter merged with bold-list. Frontmatter wins\n * on key conflict. null only when both are absent. See ADR-0006.\n */\n metadata: Record<string, unknown> | null;\n /**\n * Body-coordinate positions (list item start) for metadata keys whose\n * EFFECTIVE value came from the v2 leading list. Keys won by defined\n * frontmatter values are absent: frontmatter is stripped before mdast\n * parsing, so it has no body line — and inline suppression directives\n * (which live in the body) could not target it anyway. null when no\n * effective value is list-sourced.\n */\n metadataLoc: Record<string, MetadataPosition> | null;\n /** mdast root of the body (frontmatter stripped). */\n ast: Root;\n /** Body content with frontmatter stripped. */\n body: string;\n}\n\n/**\n * Parse a Markdown file: extract YAML frontmatter via gray-matter, then\n * feed the body into mdast-util-from-markdown directly (per ADR-0002,\n * we skip the unified+remark pipeline overhead). Additionally, extract\n * v2-style list metadata from the body's first list — both bold-key and\n * canonical plain-key shapes (see ADR-0006).\n */\nexport function parseFile(content: string): ParsedFile {\n const matter = grayMatter(content);\n const data = matter.data as Record<string, unknown>;\n const frontmatter = Object.keys(data).length > 0 ? data : null;\n const ast = fromMarkdown(matter.content);\n const listResult = extractListMetadataWithLoc(ast);\n const listMetadata = listResult?.values ?? null;\n\n let metadata: Record<string, unknown> | null = null;\n let metadataLoc: Record<string, MetadataPosition> | null =\n listResult && Object.keys(listResult.loc).length > 0\n ? { ...listResult.loc }\n : null;\n if (frontmatter && listMetadata) {\n // Frontmatter wins on conflict, BUT explicit null/undefined are\n // skipped so that `status: ~` in YAML doesn't blank a present\n // list value (counterintuitive UX otherwise).\n const frontmatterDefined: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(frontmatter)) {\n if (v !== null && v !== undefined) frontmatterDefined[k] = v;\n }\n metadata = { ...listMetadata, ...frontmatterDefined };\n // A frontmatter-won key's effective value is not in the body, so it\n // must not advertise the (shadowed) list item's position.\n if (metadataLoc) {\n for (const k of Object.keys(frontmatterDefined)) delete metadataLoc[k];\n if (Object.keys(metadataLoc).length === 0) metadataLoc = null;\n }\n } else if (frontmatter) {\n metadata = frontmatter;\n } else if (listMetadata) {\n metadata = listMetadata;\n }\n\n return {\n frontmatter,\n listMetadata,\n metadata,\n metadataLoc,\n ast,\n body: matter.content,\n };\n}\n\n// Canonical MADR metadata field names across v2/v3/v4 (after key\n// normalization). Used to distinguish a genuine metadata block from an\n// ordinary leading list: the plain-key shape (`Foo: bar`) is syntactically\n// identical to prose bullets, so we only promote a list to metadata when it\n// carries at least one of these keys. The set is deliberately the canonical\n// fields — a list keyed only by non-standard fields (e.g. `Tags`, `Author`)\n// is treated as prose, not metadata. See the dogfooding notes in ADR-0006.\nconst RECOGNIZED_METADATA_KEYS = new Set([\n 'status',\n 'date',\n 'deciders',\n 'decision-makers',\n 'consulted',\n 'informed',\n]);\n\n/**\n * Extract v2-style list metadata from an mdast Root. The metadata block is\n * the leading list — the first block after the H1 title (only headings may\n * precede it; an intervening paragraph means the list is body content, not\n * metadata). Each `listItem` is read as one `Key: value` pair in either of\n * two shapes:\n *\n * - Bold key: `- **Status**: accepted` (some MADR v2 authors)\n * - Plain key: `* Status: accepted` (official MADR v2.1.2 template)\n *\n * Key normalization: trim → lowercase → spaces become hyphens\n * (matches v4 frontmatter convention, e.g. \"Decision Makers\" →\n * \"decision-makers\"). On duplicate keys, first occurrence wins.\n *\n * Returns null unless the list carries a recognized MADR key, so ordinary\n * leading prose lists are not mistaken for metadata. (A leading list keyed by\n * a recognized field is still treated as metadata even if its value reads\n * prose-like, e.g. `Status: under discussion` — that position + key is\n * overwhelmingly metadata; this is an intentional, bounded tradeoff.)\n *\n * Because the result is gated on MADR field names, callers using this as a\n * generic list reader will get null for purely non-MADR lists.\n */\nexport function extractListMetadata(\n ast: Root,\n): Record<string, unknown> | null {\n return extractListMetadataWithLoc(ast)?.values ?? null;\n}\n\n/**\n * Position-carrying variant used by parseFile: alongside the values, records\n * each key's list-item start position (body coordinates) so diagnostics on\n * list-sourced metadata can carry a line — which is what makes inline\n * suppression directives able to target them.\n */\nfunction extractListMetadataWithLoc(ast: Root): {\n values: Record<string, unknown>;\n loc: Record<string, MetadataPosition>;\n} | null {\n let firstList: List | null = null;\n for (const child of ast.children) {\n if (child.type === 'heading') {\n if (child.depth >= 2) break; // reached the first H2 — no metadata block\n continue; // skip the H1 title (and any further headings)\n }\n // Leading HTML comments / markers don't displace the metadata block.\n if (child.type === 'html') continue;\n if (child.type === 'list') {\n firstList = child;\n break;\n }\n // Any other leading block (paragraph, code, thematic break, …) means the\n // metadata block — which must lead — is absent; the list, if any, is prose.\n break;\n }\n\n if (!firstList) return null;\n\n const values: Record<string, unknown> = {};\n const loc: Record<string, MetadataPosition> = {};\n for (const item of firstList.children) {\n const pair = extractListItemKV(item);\n if (pair && !(pair.key in values)) {\n values[pair.key] = pair.value;\n const start = item.position?.start;\n if (start) loc[pair.key] = { line: start.line, column: start.column };\n }\n }\n\n const hasRecognizedKey = Object.keys(values).some((k) =>\n RECOGNIZED_METADATA_KEYS.has(k),\n );\n return hasRecognizedKey ? { values, loc } : null;\n}\n\nconst KEY_PATTERN = /^[A-Za-z][A-Za-z0-9 \\-_]*$/;\nconst SEPARATOR_PATTERN = /^\\s*:\\s*/;\n\nfunction normalizeKey(rawKey: string): string {\n return rawKey.trim().toLowerCase().replace(/\\s+/g, '-');\n}\n\n/**\n * Read a single `Key: value` pair from one list item. Returns null for any\n * item not shaped as metadata. Two shapes are supported:\n *\n * - Bold key: paragraph starts with `strong` (the Key), followed by a\n * `: value` text node and optional inline tail.\n * - Plain key: paragraph starts with a `text` node holding `Key: value`,\n * followed by optional inline tail.\n *\n * In both shapes the value's inline tail (links, code, emphasis) is\n * flattened via mdast-util-to-string so values keep their text.\n */\nfunction extractListItemKV(\n item: ListItem,\n): { key: string; value: string } | null {\n const para = item.children[0];\n if (para?.type !== 'paragraph') return null;\n\n const paragraph = para as Paragraph;\n const first = paragraph.children[0];\n if (!first) return null;\n\n // Bold key: `**Key**` then a separator text node carrying `: value`.\n if (first.type === 'strong') {\n const keyNode = first.children[0];\n if (keyNode?.type !== 'text' || !KEY_PATTERN.test(keyNode.value)) {\n return null;\n }\n\n const sep = paragraph.children[1];\n if (sep?.type !== 'text' || !SEPARATOR_PATTERN.test(sep.value)) return null;\n\n const valueHead = sep.value.replace(SEPARATOR_PATTERN, '');\n const valueTail = paragraph.children\n .slice(2)\n .map((n) => toString(n))\n .join('');\n const value = (valueHead + valueTail).trim();\n if (value === '') return null;\n\n return { key: normalizeKey(keyNode.value), value };\n }\n\n // Plain key (canonical MADR v2.1.2): first text node holds `Key: value`.\n if (first.type === 'text') {\n const colonIdx = first.value.indexOf(':');\n if (colonIdx === -1) return null;\n\n const rawKey = first.value.slice(0, colonIdx);\n if (!KEY_PATTERN.test(rawKey)) return null;\n\n const valueHead = first.value.slice(colonIdx + 1).replace(/^\\s+/, '');\n const valueTail = paragraph.children\n .slice(1)\n .map((n) => toString(n))\n .join('');\n const value = (valueHead + valueTail).trim();\n if (value === '') return null;\n\n return { key: normalizeKey(rawKey), value };\n }\n\n return null;\n}\n","// Inline suppression directives (see issue #23).\n//\n// Rules stay completely unaware of suppression: they emit diagnostics as\n// usual, and the runner / lint layer filters them centrally *after* reporting,\n// using directives collected from the file's mdast `html` comment nodes.\n//\n// COORDINATE SYSTEM: directives are read from mdast `html` node positions.\n// Because `parseFile` strips YAML frontmatter with gray-matter BEFORE feeding\n// the body to `mdast-util-from-markdown`, every mdast position — and therefore\n// every directive line AND every AST-derived diagnostic `loc.line` — lives in\n// the same body coordinate space (frontmatter height removed). We deliberately\n// do NOT scan the raw file text, which would put directive lines in raw-file\n// coordinates and silently mis-align them with diagnostic lines.\n\nimport type { Root } from 'mdast';\nimport {\n INTERNAL_ERROR_RULE_NAME,\n type Diagnostic,\n type MdastNode,\n} from './types.js';\n\ntype DirectiveKind = 'disable-file' | 'disable' | 'enable' | 'disable-next-line';\n\n// Only these exact keywords are directives. An unknown suffix (e.g.\n// `madr-lint-disable-line`) is a full non-matching token and is ignored.\nconst DIRECTIVE_KINDS = new Set<DirectiveKind>([\n 'disable-file',\n 'disable',\n 'enable',\n 'disable-next-line',\n]);\n\n/**\n * Every directive form contains this literal. Callers use it as a cheap\n * raw-content pre-filter: since the parsed body is a substring of the raw\n * content, `!content.includes(DIRECTIVE_PREFIX)` PROVES the file contains\n * no directives — so directive collection, and any parse it would otherwise\n * force, can be skipped entirely.\n */\nexport const DIRECTIVE_PREFIX = 'madr-lint-';\n\ninterface Directive {\n kind: DirectiveKind;\n /** null = applies to all rules; otherwise the explicit rule-id list. */\n rules: readonly string[] | null;\n /** 1-based directive line in body (frontmatter-stripped) coordinates. */\n line: number;\n}\n\ninterface NextLineEntry {\n all: boolean;\n rules: Set<string>;\n}\n\nexport interface DirectiveIndex {\n /** An unscoped `disable-file` disables every rule for the whole file. */\n fileDisableAll: boolean;\n /** Rules disabled file-wide via `disable-file <rules>`. */\n fileDisableRules: Set<string>;\n /** `disable` / `enable` directives, sorted by line ascending. */\n ranged: Directive[];\n /** disable-next-line: target line (directive line + 1) → affected rules. */\n nextLine: Map<number, NextLineEntry>;\n}\n\n/** Parse one `<!-- ... -->` html node value into a directive, or null. */\nfunction parseDirective(value: string, line: number): Directive | null {\n const trimmed = value.trim();\n if (!trimmed.startsWith('<!--') || !trimmed.endsWith('-->')) return null;\n\n const inner = trimmed.slice(4, -3).trim();\n // Two comments coalesced into one html node (e.g. `<!-- a --><!-- b -->`\n // on one line) pass the startsWith/endsWith guard but would sweep\n // `--><!--` garbage into the rule list. A directive comment must stand\n // alone: reject any candidate whose interior still carries comment\n // delimiters.\n if (inner.includes('<!--') || inner.includes('-->')) return null;\n if (!inner.startsWith(DIRECTIVE_PREFIX)) return null;\n\n const afterPrefix = inner.slice(DIRECTIVE_PREFIX.length);\n // The keyword token ends at the first whitespace; the remainder is the\n // optional rule list. Matching the FULL token against the exact keyword set\n // is what makes `madr-lint-disable-line` (token `disable-line`) a non-match.\n const wsIndex = afterPrefix.search(/\\s/);\n const keyword = wsIndex === -1 ? afterPrefix : afterPrefix.slice(0, wsIndex);\n if (!DIRECTIVE_KINDS.has(keyword as DirectiveKind)) return null;\n\n const rest = wsIndex === -1 ? '' : afterPrefix.slice(wsIndex);\n return { kind: keyword as DirectiveKind, rules: parseRuleList(rest), line };\n}\n\nfunction parseRuleList(rest: string): readonly string[] | null {\n const trimmed = rest.trim();\n if (trimmed === '') return null; // no list ⇒ all rules\n const rules = trimmed\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s !== '');\n return rules.length > 0 ? rules : null;\n}\n\nfunction walkHtml(node: MdastNode, out: Directive[]): void {\n if (node.type === 'html') {\n const line = node.position?.start.line;\n if (typeof line === 'number') {\n const directive = parseDirective(node.value, line);\n if (directive) out.push(directive);\n }\n }\n if ('children' in node && Array.isArray(node.children)) {\n for (const child of node.children) walkHtml(child as MdastNode, out);\n }\n}\n\n/**\n * Collect suppression directives from a file's mdast tree in one cheap walk.\n * Returns null when the file carries no directives, so callers can skip\n * filtering entirely (fast path). Both block and inline `html` comment nodes\n * are inspected.\n *\n * `body` is the frontmatter-stripped body text — the SAME coordinate space\n * as the mdast positions. It is only consulted (and only split into lines)\n * when a `disable-next-line` directive needs to resolve its target.\n */\nexport function collectDirectives(\n ast: Root,\n body: string,\n): DirectiveIndex | null {\n const all: Directive[] = [];\n walkHtml(ast as MdastNode, all);\n if (all.length === 0) return null;\n\n // disable-next-line targets the next NON-BLANK line, not the literal next\n // line. This deviates from ESLint deliberately: Markdown authors\n // idiomatically leave a blank line after a comment block, and a directive\n // that silently misses across it would be a footgun.\n let lines: string[] | null = null;\n const nextNonBlankLine = (after: number): number | null => {\n lines ??= body.split('\\n');\n for (let ln = after + 1; ln <= lines.length; ln++) {\n if ((lines[ln - 1] ?? '').trim() !== '') return ln;\n }\n return null; // directive at EOF with nothing after it — no target\n };\n\n const index: DirectiveIndex = {\n fileDisableAll: false,\n fileDisableRules: new Set(),\n ranged: [],\n nextLine: new Map(),\n };\n\n for (const directive of all) {\n switch (directive.kind) {\n case 'disable-file': {\n if (directive.rules === null) index.fileDisableAll = true;\n else for (const rule of directive.rules) index.fileDisableRules.add(rule);\n break;\n }\n case 'disable':\n case 'enable': {\n index.ranged.push(directive);\n break;\n }\n case 'disable-next-line': {\n const target = nextNonBlankLine(directive.line);\n if (target === null) break;\n let entry = index.nextLine.get(target);\n if (!entry) {\n entry = { all: false, rules: new Set() };\n index.nextLine.set(target, entry);\n }\n if (directive.rules === null) entry.all = true;\n else for (const rule of directive.rules) entry.rules.add(rule);\n break;\n }\n }\n }\n\n index.ranged.sort((a, b) => a.line - b.line);\n return index;\n}\n\nfunction directiveApplies(directive: Directive, ruleName: string): boolean {\n return directive.rules === null || directive.rules.includes(ruleName);\n}\n\n/**\n * Is a single diagnostic suppressed by the file's directives?\n *\n * `core/internal-error` is handled by the caller and never reaches here.\n *\n * Line-less diagnostics (no `loc`) are treated as spanning the whole file:\n * only `disable-file` OR an OPEN-ENDED `disable` (a `disable` with no later\n * matching `enable`) suppresses them. This is exactly the \"file-scoped\"\n * contract the issue specifies for project-rule diagnostics.\n */\nexport function isSuppressed(\n index: DirectiveIndex,\n ruleName: string,\n line: number | undefined,\n): boolean {\n if (index.fileDisableAll || index.fileDisableRules.has(ruleName)) return true;\n\n if (line !== undefined) {\n const next = index.nextLine.get(line);\n if (next && (next.all || next.rules.has(ruleName))) return true;\n }\n\n // Replay disable/enable in line order; the last one at or before the\n // diagnostic line wins. A line-less diagnostic uses +Infinity as its line,\n // so every directive is replayed and only an unclosed final `disable`\n // (open to EOF) leaves it suppressed. This same replay yields ESLint-style\n // carve-outs, e.g. an unscoped `disable` followed by a scoped `enable`.\n const ceiling = line ?? Number.POSITIVE_INFINITY;\n let disabled = false;\n for (const directive of index.ranged) {\n if (directive.line > ceiling) break; // ranged is sorted ascending\n if (directiveApplies(directive, ruleName)) {\n disabled = directive.kind === 'disable';\n }\n }\n return disabled;\n}\n\n/**\n * Filter suppressed diagnostics. `core/internal-error` diagnostics are NEVER\n * suppressible: they signal a rule bug (always severity 'error'), and letting\n * a `disable`/`disable-file` hide them would mask defects. This is the\n * simplest behavior consistent with the runner already forcing internal-error\n * severity regardless of user config.\n */\nexport function filterSuppressed(\n diagnostics: readonly Diagnostic[],\n index: DirectiveIndex,\n): Diagnostic[] {\n return diagnostics.filter((d) => {\n if (d.ruleName === INTERNAL_ERROR_RULE_NAME) return true;\n return !isSuppressed(index, d.ruleName, d.loc?.line);\n });\n}\n","import pc from 'picocolors';\nimport type { AnyRule, Diagnostic } from './types.js';\n\n/**\n * Run-level facts a reporter cannot derive from the diagnostics themselves.\n * Optional third argument so existing two-arg callers keep working.\n */\nexport interface ReporterMeta {\n /** Diagnostics absorbed by .madr-lint/baseline.json. Absent ⇒ 0. */\n baselineHidden?: number;\n}\n\nexport interface Reporter {\n format(\n diagnostics: readonly Diagnostic[],\n rulesByName: Map<string, AnyRule>,\n meta?: ReporterMeta,\n ): string;\n}\n\nexport type ReporterFormat = 'text' | 'json' | 'sarif' | 'github';\n\n/**\n * Human-readable reporter for terminal output. Groups diagnostics by file,\n * interpolates {{placeholders}} from `data` against the rule's message\n * template, and ends with a count summary.\n *\n * Coloring uses picocolors which honors NO_COLOR / FORCE_COLOR env vars.\n */\nexport const textReporter: Reporter = {\n // Deliberately 2-param (meta unused): the CLI prints baselineHiddenSummary()\n // itself for text format, so the footer can outlive a suppressed banner.\n format(diagnostics, rulesByName) {\n if (diagnostics.length === 0) {\n return pc.green('✓ All clear.');\n }\n\n const byFile = groupByFile(diagnostics);\n const lines: string[] = [];\n\n for (const [file, fileDiagnostics] of byFile) {\n lines.push(pc.underline(file));\n for (const d of fileDiagnostics) {\n const sev =\n d.severity === 'error'\n ? pc.red(' error ')\n : pc.yellow(' warn ');\n const ruleId = pc.dim(d.ruleName.padEnd(28));\n const message = renderMessage(d, rulesByName);\n lines.push(`${sev}${ruleId} ${message}`);\n }\n lines.push('');\n }\n\n const errors = diagnostics.filter((d) => d.severity === 'error').length;\n const warnings = diagnostics.filter((d) => d.severity === 'warn').length;\n lines.push(pc.bold(formatSummary(errors, warnings)));\n\n return lines.join('\\n');\n },\n};\n\nfunction groupByFile(diagnostics: readonly Diagnostic[]): Map<string, Diagnostic[]> {\n const map = new Map<string, Diagnostic[]>();\n for (const d of diagnostics) {\n if (!map.has(d.path)) map.set(d.path, []);\n map.get(d.path)?.push(d);\n }\n return map;\n}\n\nfunction renderMessage(\n d: Diagnostic,\n rulesByName: Map<string, AnyRule>,\n): string {\n const rule = rulesByName.get(d.ruleName);\n const template = rule?.meta.messages[d.messageId] ?? d.messageId;\n return interpolate(template, d.data ?? {});\n}\n\nfunction interpolate(template: string, data: Record<string, unknown>): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key: string) => {\n const v = data[key];\n return v !== undefined ? String(v) : `{{${key}}}`;\n });\n}\n\nfunction formatSummary(errors: number, warnings: number): string {\n const parts: string[] = [];\n if (errors > 0) parts.push(`${errors} ${errors === 1 ? 'error' : 'errors'}`);\n if (warnings > 0) parts.push(`${warnings} ${warnings === 1 ? 'warning' : 'warnings'}`);\n return parts.join(', ');\n}\n\n/**\n * Machine-readable JSON reporter. Stable shape — additive changes only,\n * tagged via `version`. Tools can `JSON.parse` stdout and consume `results`\n * directly without scraping the human-readable formatter.\n */\nexport const jsonReporter: Reporter = {\n format(diagnostics, rulesByName, meta) {\n const errors = diagnostics.filter((d) => d.severity === 'error').length;\n const warnings = diagnostics.filter((d) => d.severity === 'warn').length;\n const payload = {\n version: 1,\n summary: {\n total: diagnostics.length,\n errors,\n warnings,\n // Always present (0 when no baseline) so CI consumers can detect an\n // active baseline without probing for the key. SARIF stays untouched.\n baselineHidden: meta?.baselineHidden ?? 0,\n },\n results: diagnostics.map((d) => ({\n path: d.path,\n ruleName: d.ruleName,\n messageId: d.messageId,\n severity: d.severity,\n message: renderMessage(d, rulesByName),\n data: d.data ?? {},\n })),\n };\n return JSON.stringify(payload, null, 2);\n },\n};\n\n/**\n * SARIF 2.1.0 reporter. Emits a minimal-but-valid Static Analysis Results\n * Interchange Format document so GitHub Code Scanning, VS Code SARIF\n * Viewer, and other consumers can ingest madr-lint results.\n *\n * Spec: https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html\n */\nexport const sarifReporter: Reporter = {\n format(diagnostics, rulesByName) {\n const ruleNames = [...new Set(diagnostics.map((d) => d.ruleName))];\n const ruleIndex = new Map(ruleNames.map((name, i) => [name, i]));\n\n const sarifRules = ruleNames.map((name) => {\n const rule = rulesByName.get(name);\n return {\n id: name,\n name: name.replace(/[^A-Za-z0-9]/g, '_'),\n shortDescription: { text: rule?.meta.docs.description ?? name },\n helpUri: rule?.meta.docs.url,\n };\n });\n\n const sarifResults = diagnostics.map((d) => ({\n ruleId: d.ruleName,\n ruleIndex: ruleIndex.get(d.ruleName) ?? 0,\n level: d.severity === 'error' ? 'error' : 'warning',\n message: { text: renderMessage(d, rulesByName) },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: d.path, uriBaseId: '%SRCROOT%' },\n region: { startLine: 1 },\n },\n },\n ],\n }));\n\n const sarif = {\n $schema:\n 'https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json',\n version: '2.1.0',\n runs: [\n {\n tool: {\n driver: {\n name: 'madr-lint',\n informationUri: 'https://github.com/knktkc/madr-lint',\n rules: sarifRules,\n },\n },\n results: sarifResults,\n },\n ],\n };\n return JSON.stringify(sarif, null, 2);\n },\n};\n\n/** Escape a workflow-command message value (data after `::`). */\nfunction escapeGhMessage(s: string): string {\n return s.replace(/%/g, '%25').replace(/\\r/g, '%0D').replace(/\\n/g, '%0A');\n}\n\n/** Escape a workflow-command property value (e.g. file=, title=). */\nfunction escapeGhProperty(s: string): string {\n return escapeGhMessage(s)\n .replace(/,/g, '%2C')\n .replace(/:/g, '%3A');\n}\n\n/**\n * GitHub Actions annotation reporter. Emits one `::error` / `::warning`\n * workflow command per diagnostic so GitHub renders them as PR diff annotations,\n * then a one-line human summary on stdout.\n *\n * Escape rules from https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions\n */\nexport const githubReporter: Reporter = {\n format(diagnostics, rulesByName, meta) {\n const lines: string[] = [];\n\n for (const d of diagnostics) {\n const level = d.severity === 'error' ? 'error' : 'warning';\n const file = escapeGhProperty(d.path);\n const title = escapeGhProperty(d.ruleName);\n const message = escapeGhMessage(renderMessage(d, rulesByName));\n\n const linePart = d.loc ? `,line=${d.loc.line}` : '';\n lines.push(`::${level} file=${file}${linePart},title=${title}::${message}`);\n }\n\n const errors = diagnostics.filter((d) => d.severity === 'error').length;\n const warnings = diagnostics.filter((d) => d.severity === 'warn').length;\n const summaryParts: string[] = [];\n if (errors > 0) summaryParts.push(`${errors} ${errors === 1 ? 'error' : 'errors'}`);\n if (warnings > 0) summaryParts.push(`${warnings} ${warnings === 1 ? 'warning' : 'warnings'}`);\n // A clean run still prints counts — a silent log line reads as a broken CI step.\n if (summaryParts.length === 0) summaryParts.push('0 errors, 0 warnings');\n const baselineHidden = meta?.baselineHidden ?? 0;\n if (baselineHidden > 0) summaryParts.push(`${baselineHidden} hidden by baseline`);\n lines.push(summaryParts.join(', '));\n\n return lines.join('\\n');\n },\n};\n\nexport const reporters: Record<ReporterFormat, Reporter> = {\n text: textReporter,\n json: jsonReporter,\n sarif: sarifReporter,\n github: githubReporter,\n};\n","// Registry of all built-in madr-lint rules.\n// New rules append here via the add-rule skill.\n\nexport { default as dateIso8601 } from './date-iso8601/index.js';\nexport { default as filenameFormat } from './filename-format/index.js';\nexport { default as noBrokenLinks } from './no-broken-links/index.js';\nexport { default as noDuplicateNumbering } from './no-duplicate-numbering/index.js';\nexport { default as noNumberingGap } from './no-numbering-gap/index.js';\nexport { default as requiredSections } from './required-sections/index.js';\nexport { default as statusEnum } from './status-enum/index.js';\nexport { default as supersedesBidirectional } from './supersedes-bidirectional/index.js';\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"field\": {\n \"type\": \"string\",\n \"description\": \"Frontmatter key to read. Default: 'date'.\"\n }\n }\n}\n","import type { Rule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface DateIso8601Options extends Record<string, unknown> {\n field: string;\n}\n\nfunction normalizeDate(value: unknown): string | null {\n if (typeof value === 'string') return value;\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) return null;\n return value.toISOString().slice(0, 10);\n }\n return null;\n}\n\nfunction isValidIso8601Date(s: string): boolean {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(s)) return false;\n const parts = s.split('-').map(Number);\n const [year, month, day] = parts;\n if (year === undefined || month === undefined || day === undefined) return false;\n const d = new Date(Date.UTC(year, month - 1, day));\n return (\n d.getUTCFullYear() === year &&\n d.getUTCMonth() === month - 1 &&\n d.getUTCDate() === day\n );\n}\n\nconst rule: Rule<DateIso8601Options> = {\n meta: {\n name: 'madr/date-iso8601',\n type: 'perFile',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description: 'Validate that ADR `date` (frontmatter or v2 bold-list) is a valid ISO 8601 calendar date (YYYY-MM-DD)',\n url: 'https://knktkc.github.io/madr-lint/rules/date-iso8601/',\n recommended: true,\n },\n messages: {\n missingDate: 'Metadata does not contain a \"{{field}}\" field (checked frontmatter and v2 bold-list)',\n invalidDate: 'Date \"{{date}}\" is not a valid ISO 8601 calendar date (YYYY-MM-DD)',\n },\n defaultOptions: {\n field: 'date',\n },\n schema,\n },\n create(context) {\n const meta = context.metadata;\n const fieldName = context.options.field;\n\n if (!meta) {\n context.report({\n messageId: 'missingDate',\n data: { field: fieldName },\n });\n return;\n }\n\n const raw = meta[fieldName];\n const dateStr = normalizeDate(raw);\n if (dateStr === null) {\n context.report({\n messageId: 'missingDate',\n data: { field: fieldName },\n });\n return;\n }\n\n if (!isValidIso8601Date(dateStr)) {\n // loc only exists for v2 list-sourced values: frontmatter is stripped\n // before mdast parsing, so a frontmatter-sourced date has no body line\n // to point at — inline suppression directives (which live in the body)\n // can only silence it file-wide, never per line.\n const loc = context.metadataLoc?.[fieldName];\n context.report({\n messageId: 'invalidDate',\n ...(loc ? { loc } : {}),\n data: { date: dateStr },\n });\n }\n },\n};\n\nexport default rule;\n","import { basename } from 'node:path';\nimport { assertSafeRegex } from '../../core/regex-safety.js';\nimport type { Rule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface FilenameFormatOptions extends Record<string, unknown> {\n pattern: string;\n}\n\nconst rule: Rule<FilenameFormatOptions> = {\n meta: {\n name: 'madr/filename-format',\n type: 'perFile',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description: 'Enforce ADR filename convention NNNN-kebab-case.md',\n url: 'https://knktkc.github.io/madr-lint/rules/filename-format/',\n recommended: true,\n },\n messages: {\n invalidFilename:\n 'Filename \"{{filename}}\" does not match expected pattern \"{{expected}}\"',\n },\n defaultOptions: {\n pattern: '^[0-9]{4}-[a-z0-9-]+\\\\.md$',\n },\n schema,\n },\n create(context) {\n const { pattern } = context.options;\n const regex = assertSafeRegex(pattern, 'madr/filename-format', 'pattern');\n const filename = basename(context.file.path);\n if (!regex.test(filename)) {\n context.report({\n messageId: 'invalidFilename',\n data: { filename, expected: pattern },\n });\n }\n },\n};\n\nexport default rule;\n","import safeRegex from 'safe-regex2';\nimport { RuleOptionsError } from './runner.js';\n\nconst SAFE_REGEX_LIMIT = 25;\n\n// Pattern → compiled RegExp cache. Only safe patterns are cached; unsafe\n// or syntactically invalid ones throw on every call (callers should fix\n// their config rather than burn cycles re-validating the same bad input).\n//\n// Cache scope: module-global. Keys are pattern strings, which are static\n// per rule.defaultOptions or per user config. Bounded in practice — a\n// long-running daemon would still see at most O(rules × user-overrides)\n// distinct patterns. If memory becomes a concern in pathological cases\n// (e.g. dynamically-generated patterns), the cache can be swapped for an\n// LRU. As of v0.1, a plain Map is sufficient.\nconst cache = new Map<string, RegExp>();\n\nexport function assertSafeRegex(\n pattern: string,\n ruleName: string,\n optionPath: string,\n): RegExp {\n const cached = cache.get(pattern);\n if (cached) return cached;\n\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (err) {\n throw new RuleOptionsError(\n ruleName,\n `option \"${optionPath}\" is not a valid regular expression: ${(err as Error).message}`,\n );\n }\n if (!safeRegex(regex, { limit: SAFE_REGEX_LIMIT })) {\n throw new RuleOptionsError(\n ruleName,\n `option \"${optionPath}\" (${pattern}) appears unsafe (catastrophic backtracking). Reject before runtime.`,\n );\n }\n cache.set(pattern, regex);\n return regex;\n}\n\n/**\n * Test-only helper to drop the cache between unit tests so that\n * \"unsafe pattern\" assertions don't accidentally short-circuit on a\n * previously-cached safe entry. Not exported from src/index.ts.\n */\nexport function clearRegexCacheForTesting(): void {\n cache.clear();\n}\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"pattern\": {\n \"type\": \"string\",\n \"description\": \"Regex (as string) the basename must match. Defaults to ^[0-9]{4}-[a-z0-9-]+\\\\.md$\"\n }\n }\n}\n","import { dirname, posix } from 'node:path';\nimport type { MdastNode, ProjectRule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface NoBrokenLinksOptions extends Record<string, unknown> {\n // No options at v0.1.\n}\n\nconst PROTOCOL_REGEX = /^[a-z][a-z0-9+.-]*:/i;\n\ninterface LinkLikeNode {\n url: string;\n /** unist position — start carries the body-coordinate line/column. */\n position?: { start: { line: number; column: number } };\n}\n\nfunction isLinkNode(node: MdastNode): node is MdastNode & LinkLikeNode {\n return (\n node.type === 'link' &&\n 'url' in node &&\n typeof (node as { url: unknown }).url === 'string'\n );\n}\n\nfunction isExternalOrAnchor(url: string): boolean {\n if (url === '' || url.startsWith('#')) return true;\n return PROTOCOL_REGEX.test(url);\n}\n\nfunction stripAnchorAndQuery(url: string): string {\n const hash = url.indexOf('#');\n const query = url.indexOf('?');\n let cut = hash;\n if (query !== -1 && (cut === -1 || query < cut)) cut = query;\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n// Markdown link destinations may be percent-encoded (e.g. `my%20file.md`).\n// Decode to the real on-disk path for resolution; leave malformed encoding\n// (e.g. a bare `%`) untouched rather than throwing. Fast-path the common case\n// of no percent-encoding to keep per-link cost minimal (decodeURIComponent is\n// comparatively expensive).\nfunction safeDecode(path: string): string {\n if (!path.includes('%')) return path;\n try {\n return decodeURIComponent(path);\n } catch {\n return path;\n }\n}\n\nfunction resolveRelative(fromDir: string, url: string): string {\n // Treat absolute (`/foo`) as project-rooted by stripping the leading slash,\n // so `[x](/0042-y.md)` resolves to `0042-y.md` rather than the OS root.\n if (url.startsWith('/')) return url.slice(1);\n return posix.normalize(posix.join(fromDir, url));\n}\n\nfunction collectLinks(node: MdastNode, out: LinkLikeNode[]): void {\n if (isLinkNode(node)) out.push(node);\n if ('children' in node && Array.isArray(node.children)) {\n for (const child of node.children) {\n collectLinks(child as MdastNode, out);\n }\n }\n}\n\nconst rule: ProjectRule<NoBrokenLinksOptions> = {\n meta: {\n name: 'madr/no-broken-links',\n type: 'project',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description:\n 'Relative-path Markdown links must resolve to an existing file in the project',\n url: 'https://knktkc.github.io/madr-lint/rules/no-broken-links/',\n recommended: true,\n },\n messages: {\n brokenLink:\n 'Link to \"{{url}}\" resolves to \"{{resolvedPath}}\", which does not exist in the project',\n },\n defaultOptions: {},\n schema,\n },\n check(context) {\n const knownPaths = new Set<string>();\n for (const file of context.files) {\n knownPaths.add(file.path);\n }\n\n for (const file of context.files) {\n const links: LinkLikeNode[] = [];\n collectLinks(file.ast, links);\n\n for (const link of links) {\n const url = link.url;\n if (isExternalOrAnchor(url)) continue;\n\n const pathOnly = safeDecode(stripAnchorAndQuery(url));\n if (pathOnly === '') continue;\n\n const fileDir = dirname(file.path);\n const resolvedPath = resolveRelative(fileDir, pathOnly);\n\n // A target counts as present if it is one of the linted .md files\n // OR exists on disk (covers non-Markdown assets and files outside\n // the scanned paths). fileExists is undefined in pure in-memory\n // runs, where knownPaths is the only source of truth. NOTE: the\n // on-disk check inherits the host filesystem's case-sensitivity —\n // a wrong-case link may pass on macOS/Windows yet fail on Linux/CI.\n const exists =\n knownPaths.has(resolvedPath) ||\n (context.fileExists?.(resolvedPath) ?? false);\n\n if (!exists) {\n // Link position is in body coordinates (frontmatter stripped) —\n // the same space suppression directives use, so disable-next-line\n // can target this diagnostic.\n const start = link.position?.start;\n context.report({\n messageId: 'brokenLink',\n path: file.path,\n ...(start\n ? { loc: { line: start.line, column: start.column } }\n : {}),\n data: { url, resolvedPath },\n });\n }\n }\n }\n },\n};\n\nexport default rule;\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {}\n}\n","import { basename } from 'node:path';\nimport type { ProjectRule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface NoDuplicateNumberingOptions extends Record<string, unknown> {\n // No options at v0.1.\n}\n\nconst NUMBER_REGEX = /^(\\d{4})-/;\n\nconst rule: ProjectRule<NoDuplicateNumberingOptions> = {\n meta: {\n name: 'madr/no-duplicate-numbering',\n type: 'project',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description: 'No two ADRs share the same NNNN- number prefix',\n url: 'https://knktkc.github.io/madr-lint/rules/no-duplicate-numbering/',\n recommended: true,\n },\n messages: {\n duplicateNumber: 'ADR number {{number}} is used by multiple files: {{paths}}',\n },\n defaultOptions: {},\n schema,\n },\n check(context) {\n const byNumber = new Map<string, string[]>();\n for (const file of context.files) {\n const match = NUMBER_REGEX.exec(basename(file.path));\n if (!match) continue;\n const number = match[1];\n if (number === undefined) continue;\n const group = byNumber.get(number) ?? [];\n group.push(file.path);\n byNumber.set(number, group);\n }\n\n for (const [number, paths] of byNumber) {\n if (paths.length > 1) {\n const pathList = paths.join(', ');\n for (const path of paths) {\n context.report({\n messageId: 'duplicateNumber',\n path,\n data: { number, paths: pathList },\n });\n }\n }\n }\n },\n};\n\nexport default rule;\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {}\n}\n","import { basename } from 'node:path';\nimport type { ProjectRule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface NoNumberingGapOptions extends Record<string, unknown> {\n // No options at v0.1.\n}\n\nconst NUMBER_REGEX = /^(\\d{4})-/;\n\nfunction format4(n: number): string {\n return n.toString().padStart(4, '0');\n}\n\nconst rule: ProjectRule<NoNumberingGapOptions> = {\n meta: {\n name: 'madr/no-numbering-gap',\n type: 'project',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description:\n 'Detect gaps in ADR numbering (e.g. 0001 and 0003 exist but 0002 is missing). Convention-only; default off.',\n url: 'https://knktkc.github.io/madr-lint/rules/no-numbering-gap/',\n recommended: false,\n },\n messages: {\n numberingGap:\n 'Numbering gap: missing {{missing}} between ADR-{{from}} and ADR-{{to}}',\n },\n defaultOptions: {},\n schema,\n },\n check(context) {\n // Map ADR number → file path. Files without a NNNN- prefix are ignored.\n const numberToPath = new Map<number, string>();\n for (const file of context.files) {\n const match = NUMBER_REGEX.exec(basename(file.path));\n if (!match?.[1]) continue;\n const n = Number.parseInt(match[1], 10);\n if (!Number.isNaN(n)) numberToPath.set(n, file.path);\n }\n if (numberToPath.size < 2) return;\n\n const sortedNumbers = Array.from(numberToPath.keys()).toSorted(\n (a, b) => a - b,\n );\n\n for (let i = 1; i < sortedNumbers.length; i++) {\n const prev = sortedNumbers[i - 1];\n const curr = sortedNumbers[i];\n if (prev === undefined || curr === undefined) continue;\n if (curr === prev + 1) continue;\n\n const missingNumbers: string[] = [];\n for (let n = prev + 1; n < curr; n++) {\n missingNumbers.push(format4(n));\n }\n\n const currPath = numberToPath.get(curr);\n if (!currPath) continue;\n\n context.report({\n messageId: 'numberingGap',\n path: currPath,\n data: {\n from: format4(prev),\n to: format4(curr),\n missing: missingNumbers.join(', '),\n },\n });\n }\n },\n};\n\nexport default rule;\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {}\n}\n","import { toString } from 'mdast-util-to-string';\nimport type { Rule, RuleListeners } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface RequiredSectionsOptions extends Record<string, unknown> {\n sections: string[];\n matchMode: 'exact' | 'startsWith';\n}\n\nconst rule: Rule<RequiredSectionsOptions> = {\n meta: {\n name: 'madr/required-sections',\n type: 'perFile',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description: 'Enforce that ADRs contain required heading sections',\n url: 'https://knktkc.github.io/madr-lint/rules/required-sections/',\n recommended: true,\n },\n messages: {\n missingSection: 'Missing required section: \"{{section}}\"',\n },\n defaultOptions: {\n sections: [\n 'Context and Problem Statement',\n 'Decision Outcome',\n 'Consequences',\n ],\n matchMode: 'exact',\n },\n schema,\n },\n create(context): RuleListeners {\n const seen: string[] = [];\n return {\n enter: {\n heading(node) {\n if (node.type !== 'heading') return;\n seen.push(toString(node).trim());\n },\n },\n exit: {\n root() {\n const { sections, matchMode } = context.options;\n for (const section of sections) {\n const matched = seen.some((heading) =>\n matchMode === 'startsWith'\n ? heading.startsWith(section)\n : heading === section,\n );\n if (!matched) {\n context.report({\n messageId: 'missingSection',\n data: { section, found: [...seen] },\n });\n }\n }\n },\n },\n };\n },\n};\n\nexport default rule;\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"sections\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" },\n \"description\": \"Required heading texts. Order does not matter.\"\n },\n \"matchMode\": {\n \"type\": \"string\",\n \"enum\": [\"exact\", \"startsWith\"],\n \"description\": \"Comparison mode against heading text.\"\n }\n }\n}\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"values\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" },\n \"description\": \"Exact-match allowed status values.\"\n },\n \"prefixValues\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" },\n \"description\": \"startsWith-match allowed prefixes (e.g. 'superseded by').\"\n },\n \"caseSensitive\": {\n \"type\": \"boolean\",\n \"description\": \"When false, comparisons are case-insensitive.\"\n }\n }\n}\n","import type { Rule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface StatusEnumOptions extends Record<string, unknown> {\n values: string[];\n prefixValues: string[];\n caseSensitive: boolean;\n}\n\nconst rule: Rule<StatusEnumOptions> = {\n meta: {\n name: 'madr/status-enum',\n type: 'perFile',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description: 'Validate that ADR `status` (frontmatter or v2 bold-list) is in the allowed enum',\n url: 'https://knktkc.github.io/madr-lint/rules/status-enum/',\n recommended: true,\n },\n messages: {\n missingStatus: 'Metadata does not contain a \"status\" field (checked frontmatter and v2 bold-list)',\n invalidStatus: 'Status \"{{status}}\" is not one of: {{allowed}}',\n },\n defaultOptions: {\n values: ['proposed', 'rejected', 'accepted', 'deprecated'],\n prefixValues: ['superseded by'],\n caseSensitive: false,\n },\n schema,\n },\n create(context) {\n const meta = context.metadata;\n if (!meta || typeof meta.status !== 'string') {\n context.report({ messageId: 'missingStatus', data: {} });\n return;\n }\n\n const { values, prefixValues, caseSensitive } = context.options;\n const status = meta.status;\n const compareStatus = caseSensitive ? status : status.toLowerCase();\n const compareValues = caseSensitive\n ? values\n : values.map((v) => v.toLowerCase());\n const comparePrefixes = caseSensitive\n ? prefixValues\n : prefixValues.map((p) => p.toLowerCase());\n\n const exactMatch = compareValues.includes(compareStatus);\n const prefixMatch = comparePrefixes.some((p) =>\n compareStatus.startsWith(p),\n );\n\n if (!exactMatch && !prefixMatch) {\n const allowed = [\n ...values,\n ...prefixValues.map((p) => `${p} ...`),\n ];\n // loc only exists for v2 list-sourced values: frontmatter is stripped\n // before mdast parsing, so a frontmatter-sourced status has no body\n // line to point at — inline suppression directives (which live in the\n // body) can only silence it file-wide, never per line.\n const loc = context.metadataLoc?.status;\n context.report({\n messageId: 'invalidStatus',\n ...(loc ? { loc } : {}),\n data: { status, allowed },\n });\n }\n },\n};\n\nexport default rule;\n","import { basename } from 'node:path';\nimport type { ProjectFile, ProjectRule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface SupersedesBidirectionalOptions extends Record<string, unknown> {\n // No options at v0.1.\n}\n\nconst ADR_NUMBER_REGEX = /^(\\d{4})-/;\nconst FORWARD_FIELD = 'supersedes';\nconst BACKWARD_FIELD = 'superseded-by';\n\nfunction extractAdrNumber(path: string): string | null {\n const match = ADR_NUMBER_REGEX.exec(basename(path));\n return match?.[1] ?? null;\n}\n\nfunction normalizeRefs(value: unknown): string[] {\n if (typeof value === 'string') return [value];\n if (Array.isArray(value)) {\n return value.filter((v): v is string => typeof v === 'string');\n }\n return [];\n}\n\nconst rule: ProjectRule<SupersedesBidirectionalOptions> = {\n meta: {\n name: 'madr/supersedes-bidirectional',\n type: 'project',\n versionCompat: ['v3', 'v4'],\n docs: {\n description:\n 'Frontmatter `supersedes` and `superseded-by` must reference each other bidirectionally',\n url: 'https://knktkc.github.io/madr-lint/rules/supersedes-bidirectional/',\n recommended: true,\n },\n messages: {\n unknownReference:\n 'Frontmatter `{{direction}}: {{ref}}` references an ADR that does not exist',\n missingBackReference:\n '`{{source}}` declares `{{direction}}: {{ref}}`, but `{{ref}}` (this file) does not back-reference it via `{{expected}}`',\n },\n defaultOptions: {},\n schema,\n },\n check(context) {\n // Build ADR-NNNN → file index. Files without a NNNN- prefix are\n // not addressable via `supersedes`/`superseded-by` and thus skipped.\n const adrIndex = new Map<string, ProjectFile>();\n for (const file of context.files) {\n const num = extractAdrNumber(file.path);\n if (num) adrIndex.set(`ADR-${num}`, file);\n }\n\n // Walk every file with a frontmatter and check both directions.\n for (const file of context.files) {\n const fm = file.frontmatter;\n if (!fm) continue;\n const fileNumber = extractAdrNumber(file.path);\n if (!fileNumber) continue;\n const fileRef = `ADR-${fileNumber}`;\n\n const forwardRefs = normalizeRefs(fm[FORWARD_FIELD]);\n const backwardRefs = normalizeRefs(fm[BACKWARD_FIELD]);\n\n // Forward direction: this file `supersedes` something — verify\n // the target back-references this file via `superseded-by`.\n for (const ref of forwardRefs) {\n const target = adrIndex.get(ref);\n if (!target) {\n context.report({\n messageId: 'unknownReference',\n path: file.path,\n data: { ref, direction: FORWARD_FIELD },\n });\n continue;\n }\n const targetBack = normalizeRefs(target.frontmatter?.[BACKWARD_FIELD]);\n if (!targetBack.includes(fileRef)) {\n context.report({\n messageId: 'missingBackReference',\n path: target.path,\n data: {\n ref,\n source: file.path,\n direction: BACKWARD_FIELD,\n expected: fileRef,\n },\n });\n }\n }\n\n // Backward direction: this file is `superseded-by` something —\n // verify the target forward-references this file via `supersedes`.\n for (const ref of backwardRefs) {\n const target = adrIndex.get(ref);\n if (!target) {\n context.report({\n messageId: 'unknownReference',\n path: file.path,\n data: { ref, direction: BACKWARD_FIELD },\n });\n continue;\n }\n const targetFwd = normalizeRefs(target.frontmatter?.[FORWARD_FIELD]);\n if (!targetFwd.includes(fileRef)) {\n context.report({\n messageId: 'missingBackReference',\n path: target.path,\n data: {\n ref,\n source: file.path,\n direction: FORWARD_FIELD,\n expected: fileRef,\n },\n });\n }\n }\n }\n },\n};\n\nexport default rule;\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {}\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,cAAAA,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,YAAAC,WAAU,WAAAC,UAAS,OAAAC,YAAW;AACvC,SAAS,eAAe,eAAe;;;ACQvC,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,SAAS,YAAY;;;ACmBvB,IAAM,2BAA2B;AAuLjC,SAAS,cAAcC,OAAoC;AAChE,SAAO,WAAWA;AACpB;;;ADxMO,IAAM,mBAAmB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,cAAQ,KAAK,CAAC;AAAA,IAChB;AAIA,UAAM,iBAAiB,OAAO;AAC9B,UAAM,eAAe,eAAe,OAAO,CAAC,MAAM,EAAE,aAAa,MAAM,EAAE;AACzE,UAAM,aAAa,eAAe,OAAO,CAAC,MAAM,EAAE,aAAa,OAAO,EAAE;AACxE,UAAM,mBAAmB,eAAe,KAAK,eAAe;AAO5D,UAAM,WAAW,KAAK,QAClB,eAAe,OAAO,CAAC,MAAM,EAAE,aAAa,MAAM,IAClD;AAKJ,UAAM,mBACJ,WAAW,UAAU,SAAS,WAAW,KAAK;AAChD,QAAI,CAAC,kBAAkB;AACrB,cAAQ;AAAA,QACN,SAAS,OAAO,UAAU,aAAa;AAAA,UACrC,gBAAgB,OAAO;AAAA,QACzB,CAAC;AAAA,MACH;AAAA,IACF;AAIA,QAAI,WAAW,UAAU,OAAO,iBAAiB,GAAG;AAClD,cAAQ,IAAI,sBAAsB,OAAO,cAAc,CAAC;AAAA,IAC1D;AAIA,QAAI,kBAAkB;AACpB,cAAQ;AAAA,QACN,cAAc,YAAY,6CAA6C,WAAW;AAAA,MACpF;AAAA,IACF;AAEA,YAAQ,KAAK,aAAa,KAAK,mBAAmB,IAAI,CAAC;AAAA,EACzD;AACF,CAAC;AAED,MAAM,QAAQ,IAAI;","names":["existsSync","readFileSync","relative","resolve","sep","rule","rule","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","join","existsSync","readFileSync","readFileSync","existsSync","existsSync","join","readFileSync","statSync","resolve","sep","rule","rule","readFileSync","rule","resolve","statSync","rule","basename","schema_default","rule","schema_default","basename","dirname","schema_default","rule","schema_default","dirname","basename","schema_default","rule","schema_default","basename","basename","schema_default","NUMBER_REGEX","rule","schema_default","basename","toString","schema_default","rule","schema_default","toString","schema_default","rule","schema_default","basename","schema_default","basename","rule","schema_default","toPosix","sep","readFileSync","resolve","relative","existsSync"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/core/baseline.ts","../src/core/types.ts","../src/core/cache.ts","../src/core/config.ts","../src/configs/recommended.ts","../src/core/discover.ts","../src/core/ignore.ts","../src/core/lint.ts","../src/core/runner.ts","../src/core/interpolate.ts","../src/core/parser.ts","../src/core/suppression.ts","../src/core/reporter.ts","../src/rules/index.ts","../src/rules/date-iso8601/schema.json","../src/rules/date-iso8601/index.ts","../src/rules/filename-format/index.ts","../src/core/regex-safety.ts","../src/rules/filename-format/schema.json","../src/rules/no-broken-links/index.ts","../src/rules/no-broken-links/schema.json","../src/rules/no-duplicate-numbering/index.ts","../src/rules/no-duplicate-numbering/schema.json","../src/rules/no-numbering-gap/index.ts","../src/rules/no-numbering-gap/schema.json","../src/rules/required-sections/index.ts","../src/rules/required-sections/schema.json","../src/rules/status-enum/schema.json","../src/rules/status-enum/index.ts","../src/rules/supersedes-bidirectional/index.ts","../src/rules/supersedes-bidirectional/schema.json"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs';\nimport { relative, resolve, sep } from 'node:path';\nimport { defineCommand, runMain } from 'citty';\nimport {\n baselineHiddenSummary,\n baselineMalformedWarning,\n baselinePath,\n baselineWriteSummary,\n buildBaseline,\n loadBaseline,\n writeBaseline,\n} from './core/baseline.js';\nimport { computeConfigHash } from './core/cache.js';\nimport {\n ConfigFileNotFoundError,\n loadConfig,\n loadConfigFromPath,\n resolveExtends,\n type ResolvedConfig,\n} from './core/config.js';\nimport { findAdrFiles } from './core/discover.js';\nimport { shouldIgnore } from './core/ignore.js';\nimport { lintFiles, type CacheConfig } from './core/lint.js';\nimport { reporters, type ReporterFormat } from './core/reporter.js';\nimport { RuleOptionsError } from './core/runner.js';\nimport type { AnyRule } from './core/types.js';\nimport * as builtinRules from './rules/index.js';\n\nfunction toPosix(p: string): string {\n if (sep === '/') return p;\n return p.split(sep).join('/');\n}\n\nconst pkg = JSON.parse(\n readFileSync(new URL('../package.json', import.meta.url), 'utf8'),\n) as { version: string };\n\nconst main = defineCommand({\n meta: {\n name: 'madr-lint',\n version: pkg.version,\n description: 'A linter for MADR (Markdown Architectural Decision Records)',\n },\n args: {\n paths: {\n type: 'positional',\n description:\n 'One or more paths (files or directories). Defaults to config.adrDir',\n required: false,\n },\n cache: {\n type: 'boolean',\n description:\n 'Use per-file content-hash cache (use --no-cache to disable)',\n default: true,\n },\n 'cache-dir': {\n type: 'string',\n description: 'Cache directory (default: .madr-lint/cache)',\n required: false,\n },\n format: {\n type: 'string',\n description: 'Reporter format: text (default), json, sarif, or github',\n default: 'text',\n },\n baseline: {\n type: 'boolean',\n description:\n 'Subtract .madr-lint/baseline.json when present (use --no-baseline to ignore it)',\n default: true,\n },\n 'update-baseline': {\n type: 'boolean',\n description:\n 'Rewrite .madr-lint/baseline.json from a full lint, then exit 0',\n default: false,\n },\n quiet: {\n type: 'boolean',\n description: 'Report errors only; suppress warnings from output',\n default: false,\n },\n 'max-warnings': {\n type: 'string',\n description:\n 'Exit 1 when warning count exceeds n. n=0 means any warning fails. Negative = no limit.',\n required: false,\n },\n config: {\n type: 'string',\n description: 'Path to config file, bypassing auto-discovery',\n required: false,\n },\n },\n run({ args }) {\n const cwd = process.cwd();\n\n // Parse --max-warnings. Require an integer (including negative); float or\n // non-numeric is a usage error (exit 2), not a lint failure (exit 1).\n // Number('') === 0, so an empty value (e.g. --max-warnings \"$UNSET_VAR\")\n // would silently become the strictest limit — reject it explicitly.\n let maxWarnings = -1;\n const rawMaxWarnings = args['max-warnings'] as string | undefined;\n if (rawMaxWarnings !== undefined) {\n const parsed = Number(rawMaxWarnings);\n if (rawMaxWarnings.trim() === '' || !Number.isInteger(parsed)) {\n console.error(\n `Invalid --max-warnings \"${rawMaxWarnings}\": must be an integer.`,\n );\n process.exit(2);\n }\n maxWarnings = parsed;\n }\n\n // --config bypasses the config discovery walk. When the user explicitly\n // points to a config file we skip the recommended fallback — they chose\n // the config intentionally (even if it has no rules).\n let config: ResolvedConfig;\n let configExplicit = false;\n const configArg = args.config as string | undefined;\n if (configArg) {\n const absConfigPath = resolve(cwd, configArg);\n try {\n config = loadConfigFromPath(absConfigPath);\n configExplicit = true;\n } catch (err) {\n if (err instanceof ConfigFileNotFoundError) {\n console.error(err.message);\n } else {\n console.error(\n `Failed to load config \"${configArg}\": ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n process.exit(2);\n }\n } else {\n config = loadConfig(cwd);\n }\n\n // When no rules are configured and no explicit config was provided, fall\n // back to `recommended` so users get useful output without authoring a\n // config first.\n if (!configExplicit && Object.keys(config.rules).length === 0) {\n config = resolveExtends({ extends: ['madr-lint:recommended'] });\n }\n\n // citty: positionals collect into `args._` (array of strings). If\n // empty, fall back to the config's adrDir.\n const positionals = (args._ as string[] | undefined) ?? [];\n const inputs = positionals.length > 0 ? positionals : [config.adrDir];\n\n const seen = new Set<string>();\n const allFiles: string[] = [];\n for (const input of inputs) {\n for (const file of findAdrFiles(input)) {\n if (!seen.has(file)) {\n seen.add(file);\n allFiles.push(file);\n }\n }\n }\n\n // Apply ignorePatterns from config (e.g. README.md, template.md, 9999-*).\n // POSIX-normalize so path-suffix patterns work cross-platform on Windows.\n const files = allFiles.filter(\n (absPath) =>\n !shouldIgnore(toPosix(relative(cwd, absPath)), config.ignorePatterns),\n );\n\n if (files.length === 0) {\n const skipped = allFiles.length - files.length;\n const note = skipped > 0 ? ` (${skipped} ignored by config)` : '';\n const where = inputs.length === 1 ? inputs[0] : inputs.join(', ');\n console.log(`No .md files to lint in ${where}${note}`);\n process.exit(0);\n }\n\n // CLI flag wins over config — `--no-cache` sets args.cache=false,\n // overriding `cache: true` from .madrlintrc.json.\n const cacheEnabled = (args.cache ?? config.cache) === true;\n const cacheDir = (args['cache-dir'] ?? config.cacheLocation) as string;\n const cacheConfig: CacheConfig | null = cacheEnabled\n ? {\n dir: resolve(cwd, cacheDir),\n configHash: computeConfigHash({\n rules: config.rules,\n ignorePatterns: config.ignorePatterns,\n madrVersion: config.madrVersion,\n }),\n pkgVersion: pkg.version,\n }\n : null;\n\n // --update-baseline runs a full lint IGNORING any existing baseline, so we\n // subtract nothing here and (below) rebuild the file from the raw output.\n const baselineFile = baselinePath(cwd);\n const updateBaseline = args['update-baseline'] === true;\n const useBaseline = !updateBaseline && args.baseline !== false;\n const baseline = useBaseline ? loadBaseline(baselineFile) : null;\n // Absent → silent no-op. Present but unusable → warn: silently ignoring a\n // corrupt baseline would flip CI red with zero explanation.\n if (useBaseline && baseline === null && existsSync(baselineFile)) {\n console.error(baselineMalformedWarning());\n }\n\n const allRulesArray: AnyRule[] = Object.values(builtinRules);\n let result: ReturnType<typeof lintFiles>;\n try {\n result = lintFiles({\n rules: allRulesArray,\n ruleSeverity: config.rules,\n files,\n cwd,\n cache: cacheConfig,\n baseline,\n });\n } catch (err) {\n // Invalid rule options in the user's config fail AJV validation now that\n // options actually reach the rules. Surface a clear message instead of a\n // stack trace, and exit 2 (config error, distinct from lint failures).\n if (err instanceof RuleOptionsError) {\n console.error(`Invalid rule options in config: ${err.message}`);\n process.exit(2);\n }\n throw err;\n }\n\n // Rebuild the baseline from the full (pre-baseline) diagnostics and exit.\n if (updateBaseline) {\n const built = buildBaseline(result.diagnostics);\n writeBaseline(baselineFile, built);\n console.log(baselineWriteSummary(built));\n process.exit(0);\n }\n\n const rulesByName = new Map<string, AnyRule>(\n allRulesArray.map((r) => [r.meta.name, r]),\n );\n const format = (args.format ?? 'text') as ReporterFormat;\n const reporter = reporters[format];\n if (!reporter) {\n console.error(\n `Unknown --format \"${format}\". Available: ${Object.keys(reporters).join(', ')}`,\n );\n process.exit(2);\n }\n // result.diagnostics is POST-baseline (lintFiles subtracts before\n // returning), so baselined warnings never count toward --max-warnings —\n // the whole point of a baseline is that inherited debt does not fail CI.\n const allDiagnostics = result.diagnostics;\n const warningCount = allDiagnostics.filter((d) => d.severity === 'warn').length;\n const errorCount = allDiagnostics.filter((d) => d.severity === 'error').length;\n const overWarningLimit = maxWarnings >= 0 && warningCount > maxWarnings;\n\n // --quiet filters warnings from OUTPUT but the original warning count is\n // still used for --max-warnings (mirrors ESLint: \"warnings still run, not\n // reported\"). So `--quiet --max-warnings 0` keeps the log free of warning\n // noise while still failing the build — the threshold verdict below goes\n // to stderr so the failure is never mute.\n const reported = args.quiet\n ? allDiagnostics.filter((d) => d.severity !== 'warn')\n : allDiagnostics;\n\n // Text-only: a \"✓ All clear.\" banner beside exit 1 would lie, so suppress\n // it when the run fails purely on the warning threshold. json/sarif\n // payloads still print — machine consumers read stdout + stderr + exit.\n const suppressAllClear =\n format === 'text' && reported.length === 0 && overWarningLimit;\n if (!suppressAllClear) {\n console.log(\n reporter.format(reported, rulesByName, {\n baselineHidden: result.baselineHidden,\n }),\n );\n }\n // Text-only footer: JSON carries the count in its summary; SARIF stays\n // schema-clean. Printed even when --quiet or the banner is suppressed —\n // knowing the baseline absorbed diagnostics is never noise.\n if (format === 'text' && result.baselineHidden > 0) {\n console.log(baselineHiddenSummary(result.baselineHidden));\n }\n\n // The threshold verdict goes to stderr for every format so it survives\n // --quiet and machine-readable stdout alike.\n if (overWarningLimit) {\n console.error(\n `madr-lint: ${warningCount} warning(s) found, exceeds --max-warnings ${maxWarnings}`,\n );\n }\n\n process.exit(errorCount > 0 || overWarningLimit ? 1 : 0);\n },\n});\n\nawait runMain(main);\n","// Baseline file for gradual adoption (issue #24).\n//\n// FINGERPRINT MODEL: a violation is identified by `(relative posix path,\n// ruleName, messageId)` mapped to an allowed COUNT. No line numbers, no\n// message text, no interpolation data — so the baseline survives unrelated\n// edits by construction (a rule that fires the same number of times on the\n// same file+message is fully absorbed regardless of where the lines moved).\n// This is the tsc-baseline-style count model; see ADR-0007 for the rationale\n// and the rejected line-based / content-hash alternatives.\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { INTERNAL_ERROR_RULE_NAME, type Diagnostic } from './types.js';\n\n/** Bumped only on a breaking change to the on-disk shape. */\nexport const BASELINE_VERSION = 1;\n\n/** Fixed, project-root-relative location. Also used verbatim in summaries. */\nexport const BASELINE_DISPLAY_PATH = '.madr-lint/baseline.json';\n\n/**\n * On-disk baseline. `entries` nests path → ruleName → messageId → count.\n * The nesting (rather than a flat hash) is what yields clean, reviewable git\n * diffs once keys are sorted at serialization time.\n */\nexport interface Baseline {\n version: number;\n entries: Record<string, Record<string, Record<string, number>>>;\n}\n\nexport interface BaselineApplyResult {\n /** Diagnostics that survive subtraction (new / over-count / never baselined). */\n kept: Diagnostic[];\n /** How many diagnostics the baseline absorbed. */\n hidden: number;\n}\n\n/** Absolute path to the baseline file for a given project root. */\nexport function baselinePath(cwd: string): string {\n return join(cwd, '.madr-lint', 'baseline.json');\n}\n\n/**\n * Null-prototype map. Fingerprint keys derive from on-disk filenames and\n * rule metadata, so a key like '__proto__' must behave as ordinary data —\n * on a plain object it would read/write THROUGH Object.prototype instead\n * (prototype pollution + silently dropped entries). With no prototype there\n * is nothing to pollute. JSON.stringify output is identical.\n */\nfunction nullProtoMap<T>(): Record<string, T> {\n return Object.create(null) as Record<string, T>;\n}\n\n/**\n * Aggregate diagnostics into a baseline by counting each\n * `(path, ruleName, messageId)`. `core/internal-error` is never recorded —\n * it signals a rule bug and must never be silenced (same contract as inline\n * suppression).\n */\nexport function buildBaseline(diagnostics: readonly Diagnostic[]): Baseline {\n const entries = nullProtoMap<Record<string, Record<string, number>>>();\n for (const d of diagnostics) {\n if (d.ruleName === INTERNAL_ERROR_RULE_NAME) continue;\n const byRule = (entries[d.path] ??= nullProtoMap());\n const byMessage = (byRule[d.ruleName] ??= nullProtoMap());\n byMessage[d.messageId] = (byMessage[d.messageId] ?? 0) + 1;\n }\n return { version: BASELINE_VERSION, entries };\n}\n\n/**\n * Deterministic serialization: keys sorted at every level (path, then rule,\n * then messageId), 2-space indent, trailing newline. Same logical baseline\n * always produces byte-identical output → minimal git diffs.\n */\nexport function serializeBaseline(baseline: Baseline): string {\n // Null-proto targets: on a plain object, assigning a '__proto__' key goes\n // through the inherited setter and the entry silently vanishes from the\n // JSON output.\n const sortedEntries = nullProtoMap<Record<string, Record<string, number>>>();\n for (const path of Object.keys(baseline.entries).toSorted()) {\n const byRule = baseline.entries[path] ?? {};\n const sortedByRule = nullProtoMap<Record<string, number>>();\n for (const rule of Object.keys(byRule).toSorted()) {\n const byMessage = byRule[rule] ?? {};\n const sortedByMessage = nullProtoMap<number>();\n for (const messageId of Object.keys(byMessage).toSorted()) {\n sortedByMessage[messageId] = byMessage[messageId] ?? 0;\n }\n sortedByRule[rule] = sortedByMessage;\n }\n sortedEntries[path] = sortedByRule;\n }\n const ordered = { version: baseline.version, entries: sortedEntries };\n return JSON.stringify(ordered, null, 2) + '\\n';\n}\n\n/**\n * Read a baseline file. Returns null when absent or unreadable/malformed —\n * a missing or corrupt baseline is treated as \"no baseline\" (a no-op),\n * never a hard error.\n */\nexport function loadBaseline(path: string): Baseline | null {\n if (!existsSync(path)) return null;\n try {\n const data = JSON.parse(readFileSync(path, 'utf8')) as Partial<Baseline>;\n if (typeof data.entries !== 'object' || data.entries === null) return null;\n return {\n version: typeof data.version === 'number' ? data.version : BASELINE_VERSION,\n entries: rebuildEntries(data.entries as Record<string, unknown>),\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Copy parsed JSON into null-proto maps, keeping only well-shaped levels\n * (objects) and leaves (numbers). JSON.parse itself creates '__proto__' as\n * a safe own property, but handing proto-ful objects downstream would\n * re-expose every consumer write to the pollution hazard — and a malformed\n * inner level (e.g. `\"a.md\": null`) would crash applyBaseline.\n */\nfunction rebuildEntries(raw: Record<string, unknown>): Baseline['entries'] {\n const entries = nullProtoMap<Record<string, Record<string, number>>>();\n for (const [path, rawByRule] of Object.entries(raw)) {\n if (typeof rawByRule !== 'object' || rawByRule === null) continue;\n const byRule = nullProtoMap<Record<string, number>>();\n for (const [rule, rawByMessage] of Object.entries(rawByRule)) {\n if (typeof rawByMessage !== 'object' || rawByMessage === null) continue;\n const byMessage = nullProtoMap<number>();\n for (const [messageId, count] of Object.entries(\n rawByMessage as Record<string, unknown>,\n )) {\n if (typeof count === 'number') byMessage[messageId] = count;\n }\n byRule[rule] = byMessage;\n }\n entries[path] = byRule;\n }\n return entries;\n}\n\n/** Write the baseline deterministically, creating `.madr-lint/` if needed. */\nexport function writeBaseline(path: string, baseline: Baseline): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, serializeBaseline(baseline), 'utf8');\n}\n\n// NUL cannot appear in paths, rule names, or messageIds, so joined keys\n// can never collide. Written as an escape (not a raw byte) to keep this\n// file text for git diff/blame.\nconst KEY_SEP = '\\u0000';\n\nfunction fingerprint(d: Diagnostic): string {\n return d.path + KEY_SEP + d.ruleName + KEY_SEP + d.messageId;\n}\n\n/**\n * Subtract a baseline from a diagnostic list. For each fingerprint the first\n * N matching diagnostics (N = baselined count) are absorbed; any extras are\n * reported as new. `core/internal-error` is never absorbed. Stale entries\n * (count exceeding current matches) are simply inert — no error is raised.\n *\n * O(1) per diagnostic: a mutable per-fingerprint allowance map is built once,\n * then each diagnostic is a single map lookup + decrement.\n */\nexport function applyBaseline(\n diagnostics: readonly Diagnostic[],\n baseline: Baseline,\n): BaselineApplyResult {\n const remaining = new Map<string, number>();\n for (const [path, byRule] of Object.entries(baseline.entries)) {\n for (const [rule, byMessage] of Object.entries(byRule)) {\n if (rule === INTERNAL_ERROR_RULE_NAME) continue;\n for (const [messageId, count] of Object.entries(byMessage)) {\n remaining.set(path + KEY_SEP + rule + KEY_SEP + messageId, count);\n }\n }\n }\n\n const kept: Diagnostic[] = [];\n let hidden = 0;\n for (const d of diagnostics) {\n if (d.ruleName === INTERNAL_ERROR_RULE_NAME) {\n kept.push(d);\n continue;\n }\n const key = fingerprint(d);\n const left = remaining.get(key);\n if (left !== undefined && left > 0) {\n remaining.set(key, left - 1);\n hidden++;\n } else {\n kept.push(d);\n }\n }\n return { kept, hidden };\n}\n\nfunction totalCount(baseline: Baseline): number {\n let total = 0;\n for (const byRule of Object.values(baseline.entries)) {\n for (const byMessage of Object.values(byRule)) {\n for (const count of Object.values(byMessage)) total += count;\n }\n }\n return total;\n}\n\n/**\n * One-line summary after `--update-baseline`. Counts the SUM of allowed\n * counts (\"violations\") — not fingerprint keys, and deliberately not the\n * word \"entries\", which names the on-disk map.\n */\nexport function baselineWriteSummary(baseline: Baseline): string {\n const violations = totalCount(baseline);\n const files = Object.keys(baseline.entries).length;\n const v = `${violations} ${violations === 1 ? 'violation' : 'violations'}`;\n const f = `${files} ${files === 1 ? 'file' : 'files'}`;\n return `Wrote ${v} across ${f} to ${BASELINE_DISPLAY_PATH}`;\n}\n\n/**\n * Stderr warning for a baseline file that EXISTS but could not be used.\n * A missing file is silent by design; a present-but-broken one must not be —\n * silently ignoring it would flip CI red with zero explanation.\n */\nexport function baselineMalformedWarning(): string {\n return `madr-lint: warning: ${BASELINE_DISPLAY_PATH} is malformed; ignoring it (run --update-baseline to regenerate)`;\n}\n\n/** One-line summary appended to text output when the baseline hid diagnostics. */\nexport function baselineHiddenSummary(hidden: number): string {\n return `${hidden} ${hidden === 1 ? 'problem' : 'problems'} hidden by baseline (${BASELINE_DISPLAY_PATH})`;\n}\n","// MADR linter core types.\n// Per ADR-0002, the runner uses a single-pass visitor registry over mdast.\n// The Rule type below supports BOTH:\n// - Filename / metadata-only rules: create() returns void\n// - AST-based rules: create() returns RuleListeners with enter/exit handlers\n// keyed by mdast node type. The runner walks each file's tree once and\n// dispatches to all subscribed rules.\n\nimport type { AnySchemaObject } from 'ajv';\nimport type { Nodes, Root } from 'mdast';\n// Note: imports of project-internal modules use the `.js` extension per\n// Node ESM convention. tsc resolves these to the .ts source files.\n\n// All mdast node types rules can subscribe to. `'root'` is the top-level\n// document node — useful for \"after all children visited\" reporting in\n// exit handlers.\nexport type MdastNodeType = Root['type'] | Nodes['type'];\n\n// The argument type for visitor handlers — covers root + all descendants.\nexport type MdastNode = Root | Nodes;\n\n/** Severity levels supported by every rule. */\nexport type Severity = 'error' | 'warn';\n\n/**\n * The reserved rule name used for internal-error diagnostics. A real rule\n * cannot register with this name (the registry should reject collisions).\n * Lives here (not in runner.ts) so leaf modules like the suppression layer\n * can reference it without importing the runner.\n */\nexport const INTERNAL_ERROR_RULE_NAME = 'core/internal-error';\n\n/**\n * User-facing severity declaration in config files.\n * - bare string: enable/disable with default options\n * - tuple: enable with explicit options\n */\nexport type RuleSeverity =\n | Severity\n | 'off'\n | readonly [Severity, Record<string, unknown>];\n\nexport type MadrVersion = 'v2' | 'v3' | 'v4';\n\nexport interface RuleMeta<TOptions = Record<string, unknown>> {\n /** Rule identifier, e.g. 'madr/filename-format'. */\n name: string;\n /** Whether the rule operates per-file or across the project. */\n type: 'perFile' | 'project';\n /** Which MADR versions this rule applies to. */\n versionCompat: readonly MadrVersion[];\n docs: {\n description: string;\n url?: string;\n recommended: boolean;\n };\n /** messageId -> template string with {{placeholders}}. */\n messages: Record<string, string>;\n /**\n * messageId -> machine-actionable remediation template, parallel to\n * `messages` and interpolated the same way. Partial: declare an entry only\n * where a concrete, mechanical fix exists; omit where the fix is inherently\n * contextual. The runner resolves the entry for a reported messageId into\n * `Diagnostic.suggestion` (null when absent). See issue #67.\n */\n suggestions?: Record<string, string>;\n /** Default options merged with user config. */\n defaultOptions: TOptions;\n /** AJV JSON Schema for options. Validated at runRule time. */\n schema?: AnySchemaObject;\n}\n\nexport interface FileContext {\n /** File path (typically basename or repo-relative). */\n path: string;\n /** Raw file content. */\n content: string;\n}\n\nexport interface Diagnostic {\n /** Rule that emitted this diagnostic. */\n ruleName: string;\n /** messageId from rule.meta.messages. */\n messageId: string;\n /** Severity resolved against the user config. */\n severity: Severity;\n /** Path of the offending file. */\n path: string;\n /** Optional source range. Filename rules omit this. */\n loc?: {\n line: number;\n column: number;\n };\n /** Data for placeholder interpolation in messages[messageId]. */\n data?: Record<string, unknown>;\n /**\n * Machine-actionable remediation, resolved by the runner at report time from\n * `rule.meta.suggestions[messageId]` (interpolated with `data`, exactly like\n * the message). `null` when the rule declares no suggestion for this\n * messageId. Every runner-produced diagnostic sets this. See issue #67.\n */\n suggestion: string | null;\n /**\n * The rule's documentation URL (`rule.meta.docs.url`), resolved by the runner\n * so consumers need not reconstruct it from `ruleName`. `core/internal-error`\n * diagnostics point at the repository; a rule without a docs URL yields `''`.\n */\n docsUrl: string;\n}\n\nexport interface RuleContext<TOptions = Record<string, unknown>> {\n /** The file being linted. */\n file: FileContext;\n /**\n * Parsed YAML frontmatter (v3/v4 only), or null if absent.\n * Use this when the rule must validate strict YAML frontmatter shape.\n */\n frontmatter: Record<string, unknown> | null;\n /**\n * Combined metadata: YAML frontmatter merged with v2 bold-list extracted\n * from the body. Frontmatter wins on key conflict. null only when both\n * are absent. See ADR-0006. Use this for format-agnostic field reads.\n */\n metadata: Record<string, unknown> | null;\n /**\n * Body-coordinate positions for `metadata` keys whose effective value came\n * from the v2 leading list (the list item's start). Frontmatter-sourced\n * keys are absent — frontmatter is stripped before mdast parsing, so it\n * has no body line. Rules attach this as `loc` on metadata-value\n * diagnostics so inline suppression directives can target them by line.\n */\n metadataLoc: Record<string, { line: number; column: number }> | null;\n /** User-merged options for this rule (validated against rule.meta.schema). */\n options: TOptions;\n /** Emit a diagnostic. `suggestion` / `docsUrl` are resolved by the runner. */\n report(\n diagnostic: Omit<\n Diagnostic,\n 'ruleName' | 'severity' | 'path' | 'suggestion' | 'docsUrl'\n >,\n ): void;\n}\n\n/**\n * Visitor map dispatched during single-pass mdast traversal.\n * Rules subscribe to specific node types; the runner walks the tree once\n * and calls the matching enter/exit handler for each node.\n */\nexport interface RuleListeners {\n enter?: Partial<Record<MdastNodeType, (node: MdastNode) => void>>;\n exit?: Partial<Record<MdastNodeType, (node: MdastNode) => void>>;\n}\n\n/**\n * A lint rule.\n *\n * - Filename / metadata-only rules: `create` reports diagnostics directly,\n * then returns void.\n * - AST-based rules: `create` returns RuleListeners; the runner invokes\n * them during single-pass traversal of the file's mdast tree.\n */\nexport interface Rule<TOptions = Record<string, unknown>> {\n meta: RuleMeta<TOptions>;\n create(context: RuleContext<TOptions>): RuleListeners | void;\n}\n\n// ──────────────────────────────────────────────────────────────────\n// Project rules (cross-file). See ADR-0005.\n// ──────────────────────────────────────────────────────────────────\n\n/**\n * A pre-parsed file passed to project rules. Built once per\n * `runRulesOnProject` invocation.\n */\nexport interface ProjectFile {\n /** File path relative to the project root. */\n path: string;\n /** Raw file content (unparsed). */\n content: string;\n /**\n * Body content with frontmatter stripped — the same coordinate space as\n * `ast` positions. Used by the suppression layer for line-level directive\n * targeting.\n */\n body: string;\n /** Parsed YAML frontmatter (v3/v4 only), or null if absent. */\n frontmatter: Record<string, unknown> | null;\n /**\n * Combined metadata: frontmatter merged with v2 bold-list extracted\n * from the body. Frontmatter wins on key conflict. See ADR-0006.\n */\n metadata: Record<string, unknown> | null;\n /** mdast root of the body (frontmatter stripped). */\n ast: Root;\n}\n\nexport interface ProjectRuleContext<TOptions = Record<string, unknown>> {\n /** All files in the project (eager-parsed). */\n files: readonly ProjectFile[];\n /** User-merged options for this rule. */\n options: TOptions;\n /**\n * Predicate: does a project-root-relative POSIX path exist as a regular\n * file WITHIN the project root? Injected by the orchestrator so rules (e.g.\n * no-broken-links) can verify link targets that are NOT in the linted `.md`\n * set — non-Markdown assets or files outside the scanned paths. Returns\n * false for directories and for any target that resolves at or above the\n * project root (i.e. escapes it). Undefined when no filesystem is available\n * (e.g. in-memory unit tests), in which case rules fall back to the `files`\n * set alone.\n */\n fileExists?: (resolvedPath: string) => boolean;\n /**\n * Emit a diagnostic. Unlike per-file rules, project rules MUST set\n * `path` explicitly — the runner cannot infer which file the\n * diagnostic relates to. `suggestion` / `docsUrl` are resolved by the runner.\n */\n report(\n diagnostic: Omit<\n Diagnostic,\n 'ruleName' | 'severity' | 'suggestion' | 'docsUrl'\n >,\n ): void;\n}\n\n/**\n * A cross-file rule. Receives all parsed files at once and reports\n * diagnostics with explicit `path` per file.\n *\n * Project rules use a different runner function (`runRulesOnProject`)\n * and a distinct context shape from per-file rules. See ADR-0005 for\n * the rationale behind keeping the two APIs separate.\n */\nexport interface ProjectRule<TOptions = Record<string, unknown>> {\n meta: RuleMeta<TOptions>;\n check(context: ProjectRuleContext<TOptions>): void;\n}\n\n/** Either a per-file or a project rule. */\nexport type AnyRule<TOptions = Record<string, unknown>> =\n | Rule<TOptions>\n | ProjectRule<TOptions>;\n\n/** Type guard distinguishing project rules from per-file rules. */\nexport function isProjectRule(rule: AnyRule): rule is ProjectRule {\n return 'check' in rule;\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport type { Diagnostic } from './types.js';\n\n/**\n * Per-file cache entry: the file content's sha1 hash plus the per-file\n * diagnostics that the rule pipeline emitted last time.\n *\n * Note: project (cross-file) diagnostics are NOT cached — they depend on\n * the entire file set and would invalidate on any add/remove/rename.\n */\nexport interface CacheEntry {\n contentHash: string;\n perFileDiagnostics: Diagnostic[];\n}\n\n/**\n * On-disk manifest schema version. Bump whenever the shape of what we CACHE\n * changes — in particular the `Diagnostic` shape inside `perFileDiagnostics`.\n * pkgVersion invalidation only saves npm upgraders; repo devs and\n * same-version CI caches would otherwise be served stale-shape entries\n * verbatim (e.g. diagnostics missing the #67 `suggestion`/`docsUrl` keys,\n * silently dropped from json output). History: 2 = Diagnostic gained\n * `suggestion` + `docsUrl` (#67); 1 (implicit) = pre-schema manifests, which\n * carry no `schemaVersion` field at all.\n */\nexport const CACHE_SCHEMA_VERSION = 2;\n\nexport interface CacheManifest {\n /** Manifest schema version. Missing or mismatched ⇒ the cache is cold. */\n schemaVersion: number;\n /** madr-lint version when this manifest was written. Mismatch invalidates the cache. */\n version: string;\n /** Stable hash of the resolved config. Mismatch invalidates the cache. */\n configHash: string;\n /** Per-file cached entries, keyed by POSIX-normalized relative path. */\n files: Record<string, CacheEntry>;\n}\n\nexport function computeContentHash(content: string): string {\n return createHash('sha1').update(content, 'utf8').digest('hex');\n}\n\nexport function computeConfigHash(config: unknown): string {\n return createHash('sha1').update(stableStringify(config), 'utf8').digest('hex');\n}\n\n/**\n * Stable JSON stringify: object keys are sorted so the same logical\n * config always produces the same hash regardless of property insertion\n * order. Cycles are not handled — config objects are tree-shaped.\n */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return '[' + value.map(stableStringify).join(',') + ']';\n }\n const entries = Object.entries(value as Record<string, unknown>).toSorted(\n ([a], [b]) => (a < b ? -1 : a > b ? 1 : 0),\n );\n return (\n '{' +\n entries\n .map(([k, v]) => JSON.stringify(k) + ':' + stableStringify(v))\n .join(',') +\n '}'\n );\n}\n\nexport function manifestPath(cacheDir: string): string {\n return join(cacheDir, 'manifest.json');\n}\n\nexport function loadManifest(path: string): CacheManifest | null {\n if (!existsSync(path)) return null;\n try {\n const data = JSON.parse(readFileSync(path, 'utf8')) as Partial<CacheManifest>;\n if (\n // Single invalidation point for schema drift: an unknown (or absent)\n // schema version nulls here, so every consumer sees a cold cache — no\n // scattered re-hydration of stale-shape entries downstream.\n data.schemaVersion !== CACHE_SCHEMA_VERSION ||\n typeof data.version !== 'string' ||\n typeof data.configHash !== 'string' ||\n typeof data.files !== 'object' ||\n data.files === null\n ) {\n return null;\n }\n return data as CacheManifest;\n } catch {\n return null;\n }\n}\n\nexport function saveManifest(path: string, manifest: CacheManifest): void {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(manifest), 'utf8');\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { createJiti } from 'jiti';\nimport { recommended } from '../configs/recommended.js';\nimport type { MadrLintConfig } from '../index.js';\nimport type { MadrVersion, RuleSeverity } from './types.js';\n\nexport interface ResolvedConfig {\n /** ADR directory, relative to cwd or absolute. Default: 'docs/adr'. */\n adrDir: string;\n /** Per-rule severity / options map. Empty when no preset extended. */\n rules: Record<string, RuleSeverity>;\n /** Glob patterns to skip. */\n ignorePatterns: string[];\n /** MADR version target. Default: 'auto'. */\n madrVersion: MadrVersion | 'auto';\n /** Whether to use per-file content-hash cache. Default: true. */\n cache: boolean;\n /** Cache directory (relative to cwd). Default: '.madr-lint/cache'. */\n cacheLocation: string;\n}\n\n/**\n * Config file resolution order. First match wins.\n *\n * `.json` is parsed directly (no module loader), so it stays the fastest\n * and dependency-free path. The other extensions go through `jiti`,\n * which transpiles TS/ESM/CJS on the fly.\n */\nconst CONFIG_FILES = [\n '.madrlintrc.json',\n '.madrlintrc.ts',\n '.madrlintrc.mts',\n '.madrlintrc.js',\n '.madrlintrc.mjs',\n '.madrlintrc.cjs',\n 'madr-lint.config.ts',\n 'madr-lint.config.mts',\n 'madr-lint.config.js',\n 'madr-lint.config.mjs',\n 'madr-lint.config.cjs',\n];\n\nexport class ConfigFileNotFoundError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ConfigFileNotFoundError';\n }\n}\n\n/**\n * Load and resolve a config from an explicit file path, bypassing discovery.\n * Throws `ConfigFileNotFoundError` if the file does not exist.\n * Throws `SyntaxError` or other load errors if the file is malformed.\n */\nexport function loadConfigFromPath(filePath: string): ResolvedConfig {\n // Race-free error classification: fs check-APIs (existsSync/statSync) before\n // a use are TOCTOU by construction (CodeQL js/file-system-race). Reading IS\n // the use, so classify its errors instead: ENOENT/EISDIR carry exactly the\n // two cases we distinguish, with no check-then-use window.\n let raw: string;\n try {\n raw = readFileSync(filePath, 'utf8');\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === 'ENOENT') {\n throw new ConfigFileNotFoundError(`Config file not found: ${filePath}`);\n }\n // A directory exists on disk but jiti's failure reads like a missing\n // npm package (\"Cannot find module\") — fail with an honest message instead.\n if (code === 'EISDIR') {\n throw new ConfigFileNotFoundError(\n `Config path is a directory, not a file: ${filePath}`,\n );\n }\n throw err;\n }\n if (filePath.endsWith('.json')) {\n const parsed = JSON.parse(raw) as MadrLintConfig;\n return resolveExtends(parsed);\n }\n const jiti = createJiti(import.meta.url, { interopDefault: true });\n const loaded = jiti(filePath) as MadrLintConfig | { default: MadrLintConfig };\n const config: MadrLintConfig =\n typeof loaded === 'object' && loaded !== null && 'default' in loaded\n ? (loaded.default as MadrLintConfig)\n : (loaded as MadrLintConfig);\n return resolveExtends(config);\n}\n\n/**\n * Loads and resolves a config from `cwd`. If no config file is found,\n * returns the defaults (no rules enabled — caller can opt into the\n * recommended preset by extending).\n *\n * `.json` is read synchronously and parsed inline. All other extensions\n * are loaded via `jiti`, supporting TypeScript and both module systems.\n */\nexport function loadConfig(cwd: string): ResolvedConfig {\n for (const name of CONFIG_FILES) {\n const path = resolve(cwd, name);\n if (!existsSync(path)) continue;\n\n if (name.endsWith('.json')) {\n const parsed = JSON.parse(readFileSync(path, 'utf8')) as MadrLintConfig;\n return resolveExtends(parsed);\n }\n\n const jiti = createJiti(import.meta.url, { interopDefault: true });\n const loaded = jiti(path) as MadrLintConfig | { default: MadrLintConfig };\n const config: MadrLintConfig =\n typeof loaded === 'object' && loaded !== null && 'default' in loaded\n ? (loaded.default as MadrLintConfig)\n : (loaded as MadrLintConfig);\n return resolveExtends(config);\n }\n return resolveExtends({});\n}\n\n/**\n * Pure function: turns a raw `MadrLintConfig` into a `ResolvedConfig`\n * with defaults filled in and `extends` presets merged.\n */\nexport function resolveExtends(config: MadrLintConfig): ResolvedConfig {\n const baseRules: Record<string, RuleSeverity> = config.extends?.includes(\n 'madr-lint:recommended',\n )\n ? { ...recommended }\n : {};\n\n return {\n adrDir: config.adrDir ?? 'docs/adr',\n rules: { ...baseRules, ...config.rules },\n ignorePatterns: config.ignorePatterns ?? [],\n madrVersion: config.madrVersion ?? 'auto',\n cache: config.cache ?? true,\n cacheLocation: config.cacheLocation ?? '.madr-lint/cache',\n };\n}\n","import type { RuleSeverity } from '../core/types.js';\n\n// The `recommended` preset enables rules whose default behavior is broadly\n// useful and grounded in the MADR spec. New rules append here via the\n// add-rule skill, with severity decided per-rule (default `error` for\n// spec-grounded rules, `warn` for convention-only rules).\n//\n// Both bare-string and tuple forms are supported here:\n// 'madr/foo': 'error' — enable with defaults\n// 'madr/foo': ['error', { pattern: '^X' }] — enable with override\n\nexport const recommended: Record<string, RuleSeverity> = {\n 'madr/date-iso8601': 'error',\n 'madr/filename-format': 'error',\n 'madr/no-broken-links': 'error',\n 'madr/no-duplicate-numbering': 'error',\n // Convention-only — opt in if your team treats ADR numbering as a\n // contiguous sequence. See https://knktkc.github.io/madr-lint/rules/no-numbering-gap/.\n 'madr/no-numbering-gap': 'off',\n 'madr/required-sections': 'error',\n 'madr/status-enum': 'error',\n 'madr/supersedes-bidirectional': 'error',\n};\n","import { existsSync, readdirSync, statSync } from 'node:fs';\nimport { join } from 'node:path';\n\n/**\n * Resolves a target path to a list of `.md` files to lint.\n *\n * - If the target is a directory: recursively walks it and returns every `.md`\n * file, sorted lexicographically.\n * - If the target is a `.md` file: returns just that file.\n * - If the target is a non-`.md` file or does not exist: returns `[]`.\n *\n * The empty-array fallback lets the CLI print \"No .md files found\" rather\n * than crashing — the caller decides whether that is an error.\n */\nexport function findAdrFiles(target: string): string[] {\n if (!existsSync(target)) return [];\n\n const stat = statSync(target);\n if (stat.isFile()) {\n return target.endsWith('.md') ? [target] : [];\n }\n if (!stat.isDirectory()) return [];\n\n const entries = readdirSync(target, { recursive: true, withFileTypes: true });\n return entries\n .filter((e) => e.isFile() && e.name.endsWith('.md'))\n .map((e) => join(e.parentPath, e.name))\n .toSorted();\n}\n","import { basename } from 'node:path';\nimport picomatch from 'picomatch';\n\n/**\n * Should the given relative path be excluded from linting?\n *\n * Patterns are tested in three forms (any match wins):\n * - **Full glob via picomatch** against the relative POSIX path:\n * `docs/**\\/draft-*.md`, `**\\/template.md`, `9999-*.md`\n * - Full glob via picomatch against the file's basename, so patterns\n * like `README.md` or `9999-*` work without a `**\\/` prefix.\n * - Exact relative-path match (defensive — picomatch with default\n * options also handles this, but we keep the explicit branch for\n * clarity and to avoid surprises if picomatch ever changes default\n * `dot`/`bash` semantics).\n *\n * Picomatch is invoked with `{ dot: true }` so dotfiles (rare for ADRs\n * but possible — e.g. `.archived/*.md`) are matched naturally.\n */\nexport function shouldIgnore(\n relativePath: string,\n patterns: readonly string[],\n): boolean {\n if (patterns.length === 0) return false;\n const base = basename(relativePath);\n for (const pattern of patterns) {\n if (matchesPattern(relativePath, base, pattern)) return true;\n }\n return false;\n}\n\nfunction matchesPattern(\n relativePath: string,\n base: string,\n pattern: string,\n): boolean {\n if (relativePath === pattern) return true;\n const matcher = picomatch(pattern, { dot: true });\n if (matcher(relativePath)) return true;\n if (matcher(base)) return true;\n // Back-compat shortcut: a pattern like `adr/template.md` (sub-path\n // without leading `**/`) should match `docs/adr/template.md`. Also\n // handles `adr/9999-*` against `docs/adr/9999-x.md` via picomatch\n // applied to the suffix.\n if (pattern.includes('/') && !pattern.startsWith('**/')) {\n const suffixMatcher = picomatch(`**/${pattern}`, { dot: true });\n if (suffixMatcher(relativePath)) return true;\n }\n return false;\n}\n","import { readFileSync, statSync } from 'node:fs';\nimport { isAbsolute, relative, resolve, sep } from 'node:path';\nimport { applyBaseline, type Baseline } from './baseline.js';\nimport {\n computeContentHash,\n loadManifest,\n manifestPath,\n saveManifest,\n CACHE_SCHEMA_VERSION,\n type CacheEntry,\n type CacheManifest,\n} from './cache.js';\nimport {\n buildProjectFile,\n runRulesOnFile,\n runRulesOnProject,\n} from './runner.js';\nimport {\n collectDirectives,\n isSuppressed,\n DIRECTIVE_PREFIX,\n type DirectiveIndex,\n} from './suppression.js';\n\n/**\n * Normalize a relative path to POSIX form (forward-slashes). On Windows,\n * `relative()` returns backslash-separated paths, but project rules\n * (e.g. `no-broken-links`) resolve URLs using `posix.normalize`. Mixing\n * separators causes silent false positives — so the orchestrator owns\n * the normalization.\n */\nfunction toPosix(p: string): string {\n if (sep === '/') return p;\n return p.split(sep).join('/');\n}\nimport {\n INTERNAL_ERROR_RULE_NAME,\n isProjectRule,\n type AnyRule,\n type Diagnostic,\n type ProjectFile,\n type ProjectRule,\n type Rule,\n type RuleSeverity,\n type Severity,\n} from './types.js';\n\nexport interface CacheConfig {\n /** Directory under which manifest.json is read/written. */\n dir: string;\n /** Stable hash of the resolved config. Mismatch invalidates the cache. */\n configHash: string;\n /** madr-lint package version. Mismatch invalidates the cache. */\n pkgVersion: string;\n}\n\nexport interface LintOptions {\n /** All available rules (per-file or project). The orchestrator picks\n * enabled ones via ruleSeverity and dispatches to the right runner. */\n rules: readonly AnyRule[];\n /** User-configured severity per rule name. Missing entry === 'off'. */\n ruleSeverity: Record<string, RuleSeverity>;\n /** Files to lint, absolute or cwd-relative paths. */\n files: readonly string[];\n /** Working directory. Diagnostics' `path` is reported relative to this. */\n cwd: string;\n /**\n * If set, persist per-file diagnostics keyed by content hash to enable\n * fast re-runs of unchanged files. Project (cross-file) rules always\n * re-run regardless of the cache. Pass `null` to disable.\n */\n cache?: CacheConfig | null;\n /**\n * Parsed baseline to subtract, or null/undefined to disable. Subtraction\n * runs AFTER inline-suppression filtering and is NEVER written to the cache\n * (the cache keeps pre-baseline diagnostics, so editing or deleting the\n * baseline file takes effect without cache invalidation). See ADR-0007.\n */\n baseline?: Baseline | null;\n}\n\nexport interface LintResult {\n filesChecked: number;\n filesFromCache: number;\n diagnostics: Diagnostic[];\n /** How many diagnostics the baseline absorbed (0 when no baseline). */\n baselineHidden: number;\n}\n\n/**\n * Lint a list of files against per-file AND project rules.\n *\n * Per-file rules go through `runRulesOnFile` (single-pass AST per file).\n * Project rules go through `runRulesOnProject` (eager parse all files,\n * single check call per rule). See ADR-0005.\n *\n * File contents are read once and shared between both passes.\n */\nexport function lintFiles(opts: LintOptions): LintResult {\n const allDiagnostics: Diagnostic[] = [];\n\n // Read all file contents once — shared between per-file and project passes.\n // POSIX-normalize the relative path so cross-platform diagnostics and\n // path-based rules (e.g. no-broken-links) work consistently on Windows.\n const fileEntries = opts.files.map((absolutePath) => ({\n relativePath: toPosix(relative(opts.cwd, absolutePath)),\n content: readFileSync(absolutePath, 'utf8'),\n }));\n\n // Partition rules by kind.\n const perFileRules: Rule[] = [];\n const projectRules: ProjectRule[] = [];\n for (const rule of opts.rules) {\n if (isProjectRule(rule)) projectRules.push(rule);\n else perFileRules.push(rule);\n }\n\n // Per-rule options from config tuples (`['error', {...}]`), threaded into\n // both passes so rule options actually take effect (not just defaults).\n const optionsByRule = extractOptionsByRule(opts.ruleSeverity);\n\n // ── Cache setup ──────────────────────────────────────────────────\n let manifest: CacheManifest | null = null;\n let filesFromCache = 0;\n if (opts.cache) {\n const path = manifestPath(opts.cache.dir);\n const loaded = loadManifest(path);\n if (\n loaded &&\n loaded.version === opts.cache.pkgVersion &&\n loaded.configHash === opts.cache.configHash\n ) {\n manifest = loaded;\n } else {\n manifest = {\n schemaVersion: CACHE_SCHEMA_VERSION,\n version: opts.cache.pkgVersion,\n configHash: opts.cache.configHash,\n files: {},\n };\n }\n }\n\n // ── Per-file pass ────────────────────────────────────────────────\n for (const file of fileEntries) {\n if (manifest) {\n const contentHash = computeContentHash(file.content);\n const entry = manifest.files[file.relativePath];\n if (entry && entry.contentHash === contentHash) {\n allDiagnostics.push(...entry.perFileDiagnostics);\n filesFromCache++;\n continue;\n }\n // Cache miss — run rules and store result.\n const fileDiagnostics = runPerFileRulesForFile(\n perFileRules,\n opts.ruleSeverity,\n optionsByRule,\n file,\n );\n allDiagnostics.push(...fileDiagnostics);\n const next: CacheEntry = {\n contentHash,\n perFileDiagnostics: fileDiagnostics,\n };\n manifest.files[file.relativePath] = next;\n } else {\n allDiagnostics.push(\n ...runPerFileRulesForFile(\n perFileRules,\n opts.ruleSeverity,\n optionsByRule,\n file,\n ),\n );\n }\n }\n\n // ── Project pass ─────────────────────────────────────────────────\n const enabledProjectRules = projectRules.filter(\n (rule) => resolveSeverity(opts.ruleSeverity[rule.meta.name]) !== 'off',\n );\n if (enabledProjectRules.length > 0) {\n const projectFiles = fileEntries.map((f) =>\n buildProjectFile({ path: f.relativePath, content: f.content }),\n );\n\n // Does a path exist as a regular file WITHIN the project root? Lets\n // project rules verify link targets that are not in the linted .md set\n // (non-Markdown assets, files outside the scanned paths). Contract:\n // - a target that resolves at or above the root escapes the project →\n // false (path traversal cannot reach above the root);\n // - directories are not files → false (a link must point at a file);\n // - results are memoized per lint run (repeated targets cost one stat).\n // The containment test compares the resolved absolute path to the root\n // rather than a lexical prefix on `resolvedPath`, which may be\n // un-normalized (e.g. a `/`-rooted link resolving to `foo/../../x`).\n // NOTE: statSync follows symlinks, so a symlink that lives inside the root\n // but points outside it is accepted — it is a real entry in the project\n // tree. `resolvedPath` is POSIX; node's path.resolve accepts forward\n // slashes on all platforms.\n const projectRoot = resolve(opts.cwd);\n const existsCache = new Map<string, boolean>();\n const fileExists = (resolvedPath: string): boolean => {\n const cached = existsCache.get(resolvedPath);\n if (cached !== undefined) return cached;\n const abs = resolve(projectRoot, resolvedPath);\n const rel = relative(projectRoot, abs);\n const escapesRoot =\n rel === '' || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel);\n let result: boolean;\n if (escapesRoot) {\n result = false;\n } else {\n try {\n result = statSync(abs, { throwIfNoEntry: false })?.isFile() ?? false;\n } catch {\n // ELOOP / EACCES / invalid path → cannot confirm a regular file.\n result = false;\n }\n }\n existsCache.set(resolvedPath, result);\n return result;\n };\n\n const errorRules: ProjectRule[] = [];\n const warnRules: ProjectRule[] = [];\n for (const rule of enabledProjectRules) {\n const sev = resolveSeverity(opts.ruleSeverity[rule.meta.name]);\n if (sev === 'error') errorRules.push(rule);\n else if (sev === 'warn') warnRules.push(rule);\n }\n\n const projectDiagnostics: Diagnostic[] = [];\n if (errorRules.length > 0) {\n projectDiagnostics.push(\n ...runRulesOnProject(errorRules, projectFiles, {\n severity: 'error',\n fileExists,\n optionsByRule,\n }),\n );\n }\n if (warnRules.length > 0) {\n projectDiagnostics.push(\n ...runRulesOnProject(warnRules, projectFiles, {\n severity: 'warn',\n fileExists,\n optionsByRule,\n }),\n );\n }\n\n // Inline suppression for project diagnostics (issue #23): a directive\n // lives in the file the diagnostic is attributed to (project rules report\n // an explicit `path`). File-scoped directives (disable-file, or an\n // open-ended disable) suppress line-less project diagnostics; line-scoped\n // directives apply when the diagnostic carries a line.\n allDiagnostics.push(\n ...filterSuppressedProjectDiagnostics(projectDiagnostics, projectFiles),\n );\n }\n\n // ── Persist cache ────────────────────────────────────────────────\n // Cache the PRE-baseline diagnostics: subtraction happens below, after the\n // save, so the on-disk cache is independent of the baseline file.\n if (manifest && opts.cache) {\n saveManifest(manifestPath(opts.cache.dir), manifest);\n }\n\n // ── Baseline subtraction ─────────────────────────────────────────\n // Zero work when no baseline is provided (the common hot path).\n if (!opts.baseline) {\n return {\n filesChecked: opts.files.length,\n filesFromCache,\n diagnostics: allDiagnostics,\n baselineHidden: 0,\n };\n }\n const applied = applyBaseline(allDiagnostics, opts.baseline);\n return {\n filesChecked: opts.files.length,\n filesFromCache,\n diagnostics: applied.kept,\n baselineHidden: applied.hidden,\n };\n}\n\nfunction runPerFileRulesForFile(\n perFileRules: readonly Rule[],\n ruleSeverity: Record<string, RuleSeverity>,\n optionsByRule: Record<string, Record<string, unknown>>,\n file: { relativePath: string; content: string },\n): Diagnostic[] {\n const fileContext = {\n content: file.content,\n path: file.relativePath,\n };\n\n const errorRules: Rule[] = [];\n const warnRules: Rule[] = [];\n for (const rule of perFileRules) {\n const sev = resolveSeverity(ruleSeverity[rule.meta.name]);\n if (sev === 'off') continue;\n if (sev === 'error') errorRules.push(rule);\n else warnRules.push(rule);\n }\n\n const diagnostics: Diagnostic[] = [];\n if (errorRules.length > 0) {\n diagnostics.push(\n ...runRulesOnFile(errorRules, fileContext, {\n severity: 'error',\n optionsByRule,\n }),\n );\n }\n if (warnRules.length > 0) {\n diagnostics.push(\n ...runRulesOnFile(warnRules, fileContext, {\n severity: 'warn',\n optionsByRule,\n }),\n );\n }\n return diagnostics;\n}\n\n/**\n * Filter suppressed project-rule diagnostics. Each diagnostic is matched\n * against the directives of the file it is attributed to (by `path`).\n * Directive indexes are collected lazily and memoized so a file with no\n * suppressed diagnostics is walked at most once. `core/internal-error`\n * diagnostics (and any diagnostic whose path has no source file, e.g. the\n * `<project>` sentinel) are never suppressed.\n */\nfunction filterSuppressedProjectDiagnostics(\n diagnostics: readonly Diagnostic[],\n projectFiles: readonly ProjectFile[],\n): Diagnostic[] {\n if (diagnostics.length === 0) return [];\n\n const fileByPath = new Map(projectFiles.map((f) => [f.path, f]));\n const indexByPath = new Map<string, DirectiveIndex | null>();\n const indexFor = (path: string): DirectiveIndex | null => {\n const cached = indexByPath.get(path);\n if (cached !== undefined) return cached;\n const file = fileByPath.get(path);\n // Unlike the per-file path, no parse can be forced here — project files\n // are eager-parsed by buildProjectFile before rules run. The prefix\n // check just skips the AST walk for directive-free files (same\n // soundness argument: no 'madr-lint-' in content ⇒ no directives).\n const index =\n file && file.content.includes(DIRECTIVE_PREFIX)\n ? collectDirectives(file.ast, file.body)\n : null;\n indexByPath.set(path, index);\n return index;\n };\n\n return diagnostics.filter((d) => {\n if (d.ruleName === INTERNAL_ERROR_RULE_NAME) return true;\n const index = indexFor(d.path);\n if (!index) return true;\n return !isSuppressed(index, d.ruleName, d.loc?.line);\n });\n}\n\nfunction resolveSeverity(config: RuleSeverity | undefined): Severity | 'off' {\n if (config === undefined) return 'off';\n if (typeof config === 'string') return config;\n return config[0];\n}\n\n/**\n * Build a ruleName → options map from config tuples (`['error', {...}]`).\n * Bare-string severities carry no options and are omitted, so rules without\n * configured options fall back to their `meta.defaultOptions` in the runner.\n */\nfunction extractOptionsByRule(\n ruleSeverity: Record<string, RuleSeverity>,\n): Record<string, Record<string, unknown>> {\n const map: Record<string, Record<string, unknown>> = {};\n for (const [name, config] of Object.entries(ruleSeverity)) {\n // Only tuples carry options; guard config[1] so a malformed 1-element\n // `['error']` doesn't put `undefined` into the map.\n if (Array.isArray(config) && config[1]) map[name] = config[1];\n }\n return map;\n}\n","import Ajv, { type AnySchemaObject, type ValidateFunction } from 'ajv';\nimport {\n INTERNAL_ERROR_RULE_NAME,\n type Diagnostic,\n type FileContext,\n type MdastNode,\n type ProjectFile,\n type ProjectRule,\n type ProjectRuleContext,\n type Rule,\n type RuleContext,\n type RuleListeners,\n type Severity,\n} from './types.js';\nimport { interpolate } from './interpolate.js';\nimport { parseFile, type ParsedFile } from './parser.js';\nimport {\n collectDirectives,\n filterSuppressed,\n DIRECTIVE_PREFIX,\n} from './suppression.js';\n\n// strict: true catches typo'd schema keywords at compile time.\n// allErrors: true so RuleOptionsError surfaces every issue at once.\nconst ajv = new Ajv({ strict: true, allErrors: true });\n\n// Cache compiled validators per schema object reference.\n// Schemas are module-level static on rules, so the cache key never goes stale.\n// (If a rule mutates `meta.schema` post-load — don't — the cache will desync.)\nconst validatorCache = new WeakMap<AnySchemaObject, ValidateFunction>();\n\nfunction getValidator(schema: AnySchemaObject): ValidateFunction {\n let validator = validatorCache.get(schema);\n if (!validator) {\n validator = ajv.compile(schema);\n validatorCache.set(schema, validator);\n }\n return validator;\n}\n\n// Defined in types.ts (leaf module) so the suppression layer can reference\n// it without a runner import cycle; re-exported here for API stability.\nexport { INTERNAL_ERROR_RULE_NAME };\n\n// core/internal-error diagnostics carry no rule docs URL of their own — a rule\n// bug is a repository issue, so point consumers at the repo. See issue #67.\nconst INTERNAL_ERROR_DOCS_URL = 'https://github.com/knktkc/madr-lint';\n\n/**\n * Thrown when a rule's merged options fail AJV validation against\n * `rule.meta.schema`. Distinct from generic `Error` so callers can\n * `instanceof` to skip rules with bad config and continue.\n */\nexport class RuleOptionsError extends Error {\n constructor(\n public readonly ruleName: string,\n public readonly ajvErrors: string,\n ) {\n super(`Invalid options for rule ${ruleName}: ${ajvErrors}`);\n this.name = 'RuleOptionsError';\n }\n}\n\nexport interface RunRuleOptions {\n /** Per-rule options to merge over rule.meta.defaultOptions. */\n options?: Record<string, unknown>;\n /**\n * Options keyed by rule name, for multi-rule calls where each rule needs\n * its own options (e.g. config tuples `['error', {...}]`). For a given rule,\n * an entry here takes precedence over `options`; rules absent from the map\n * fall back to `options` (if any), then `meta.defaultOptions`.\n */\n optionsByRule?: Record<string, Record<string, unknown>>;\n /** Severity to attach to emitted diagnostics. Defaults to 'error'. */\n severity?: Severity;\n /** Skip AJV options validation. Default false. */\n skipValidation?: boolean;\n /**\n * Filesystem-existence predicate exposed to project rules as\n * `context.fileExists`. Per-file runs ignore this. See\n * ProjectRuleContext.fileExists.\n */\n fileExists?: (resolvedPath: string) => boolean;\n}\n\n/**\n * Per-rule, per-file rule context. The lazy-parse getters live on the class\n * PROTOTYPE — object literals with getters force expensive per-call shape\n * setup, which the filename-format micro-bench (~400ns/op) measured as a\n * double-digit % regression when a third getter was added (PR #53).\n * Prototype accessors are set up once; instantiation is near-free. `report`\n * stays a per-instance closure (it captures the rule name and severity, and\n * this keeps it safely destructurable by rule authors).\n */\nclass PerFileRuleContext implements RuleContext {\n readonly file: FileContext;\n readonly options: Record<string, unknown>;\n readonly report: RuleContext['report'];\n private readonly ensureParsed: () => ParsedFile;\n\n constructor(\n file: FileContext,\n options: Record<string, unknown>,\n ensureParsed: () => ParsedFile,\n report: RuleContext['report'],\n ) {\n this.file = file;\n this.options = options;\n this.ensureParsed = ensureParsed;\n this.report = report;\n }\n\n get frontmatter(): Record<string, unknown> | null {\n return this.ensureParsed().frontmatter;\n }\n\n get metadata(): Record<string, unknown> | null {\n return this.ensureParsed().metadata;\n }\n\n get metadataLoc(): Record<string, { line: number; column: number }> | null {\n return this.ensureParsed().metadataLoc;\n }\n}\n\n/**\n * Run a single rule against a single file. Sugar over runRulesOnFile\n * for the common one-rule case (used heavily by tests).\n *\n * Note: inline suppression directives (`<!-- madr-lint-disable... -->`)\n * present in `file.content` ARE honored — matching diagnostics are filtered.\n */\nexport function runRule<TOptions extends Record<string, unknown>>(\n rule: Rule<TOptions>,\n file: FileContext,\n runtime: RunRuleOptions = {},\n): Diagnostic[] {\n return runRulesOnFile([rule as Rule], file, runtime);\n}\n\n/**\n * Run multiple rules against a single file with a single mdast traversal.\n *\n * Steps:\n * 1. Validate each rule's merged options against its schema (AJV).\n * Throws RuleOptionsError on failure (caller decides whether to skip).\n * 2. Call each rule's create(). If a rule throws, the error is caught\n * and reported as a `core/internal-error` diagnostic — other rules\n * continue. The same isolation wraps every enter/exit handler so a\n * single buggy rule cannot abort the whole lint run.\n * 3. If at least one rule returned RuleListeners, call parseFile()\n * ONCE (gray-matter + mdast-util-from-markdown together; there is\n * no separate cheap \"frontmatter only\" path) and walk the tree,\n * dispatching enter/exit handlers per node type.\n *\n * Frontmatter is exposed lazily via context.frontmatter — the getter\n * triggers parseFile() on first access. Filename-style rules that never\n * touch frontmatter and return void from create() pay zero parse cost.\n *\n * Note: inline suppression directives (`<!-- madr-lint-disable... -->`)\n * present in `file.content` ARE honored — matching diagnostics are filtered\n * centrally after all rules have reported (see suppression.ts).\n */\nexport function runRulesOnFile(\n rules: readonly Rule[],\n file: FileContext,\n runtime: RunRuleOptions = {},\n): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n const severity = runtime.severity ?? 'error';\n\n let parsed: ParsedFile | null = null;\n const ensureParsed = (): ParsedFile => {\n parsed ??= parseFile(file.content);\n return parsed;\n };\n\n const enterMap: Record<string, Array<(node: MdastNode) => void>> = {};\n const exitMap: Record<string, Array<(node: MdastNode) => void>> = {};\n let hasASTRule = false;\n\n for (const rule of rules) {\n const perRuleOptions =\n runtime.optionsByRule?.[rule.meta.name] ?? runtime.options;\n const mergedOptions = {\n ...rule.meta.defaultOptions,\n ...perRuleOptions,\n };\n\n if (rule.meta.schema && !runtime.skipValidation) {\n const validator = getValidator(rule.meta.schema);\n if (!validator(mergedOptions)) {\n throw new RuleOptionsError(rule.meta.name, ajv.errorsText(validator.errors));\n }\n }\n\n // Per-rule constants hoisted OUT of the report closure: resolving them per\n // report() call (helper call + rule.meta.docs.url chain + an absent\n // `suggestions` property walk) measured a confirmed -19% on the CI x64\n // no-numbering-gap dirty-path bench, though Apple-silicon runs masked it.\n // The literal below also keeps the base construction pattern — boilerplate\n // head then a single trailing spread — so no post-spread shape transitions.\n const ruleName = rule.meta.name;\n const suggestions = rule.meta.suggestions;\n const docsUrl = rule.meta.docs.url ?? '';\n const context: RuleContext = new PerFileRuleContext(\n file,\n mergedOptions,\n ensureParsed,\n (d) => {\n const template = suggestions?.[d.messageId];\n diagnostics.push({\n ruleName,\n severity,\n path: file.path,\n suggestion: template === undefined ? null : interpolate(template, d.data ?? {}),\n docsUrl,\n ...d,\n });\n },\n );\n\n let listeners: RuleListeners | void;\n try {\n listeners = rule.create(context);\n } catch (err) {\n // RuleOptionsError signals the user's config is wrong (e.g. unsafe\n // regex). Propagate it so the CLI can render a clear \"fix your\n // .madrlintrc\" message rather than burying it as a per-file\n // internal-error diagnostic.\n if (err instanceof RuleOptionsError) throw err;\n diagnostics.push(\n internalErrorDiagnostic(rule.meta.name, 'create', err, file.path),\n );\n continue;\n }\n\n if (listeners) {\n hasASTRule = true;\n collectListeners(rule, listeners, enterMap, exitMap, diagnostics, file);\n }\n }\n\n if (hasASTRule) {\n walk(ensureParsed().ast, enterMap, exitMap);\n }\n\n // Central, post-report suppression (issue #23). Rules stay unaware; the\n // runner filters here using directives collected from the file's `html`\n // comment nodes. We only pay the parse + directive walk when there is\n // something to potentially suppress — a clean file short-circuits, so\n // filename-only rules on passing files keep their zero-parse fast path.\n if (diagnostics.length === 0) return diagnostics;\n // Perf guard (PR #53): every directive form contains the literal\n // 'madr-lint-', and the parsed body is a substring of the raw content, so\n // its absence PROVES no directives exist — filtering can be skipped\n // without parsing. Without this, a Shape-A filename diagnostic on an\n // otherwise-unparsed file forced a full gray-matter+mdast parse here\n // (measured -99% on the filename-format invalid-path bench). The substring\n // scan is ~µs; files that do contain the literal proceed exactly as before.\n if (!file.content.includes(DIRECTIVE_PREFIX)) return diagnostics;\n const { ast, body } = ensureParsed();\n const directives = collectDirectives(ast, body);\n return directives ? filterSuppressed(diagnostics, directives) : diagnostics;\n}\n\n// Internal-error diagnostics are ALWAYS severity 'error' regardless of the\n// runtime-passed severity for the rule that threw — a rule misbehaving is\n// never something the user wants to silence as a warning.\nfunction internalErrorDiagnostic(\n ruleName: string,\n operation: 'create' | 'enter' | 'exit' | 'check',\n err: unknown,\n path: string,\n): Diagnostic {\n return {\n ruleName: INTERNAL_ERROR_RULE_NAME,\n messageId: 'ruleThrew',\n severity: 'error',\n path,\n suggestion: null,\n docsUrl: INTERNAL_ERROR_DOCS_URL,\n data: {\n rule: ruleName,\n operation,\n error: err instanceof Error ? err.message : String(err),\n },\n };\n}\n\nfunction collectListeners(\n rule: Rule,\n listeners: RuleListeners,\n enterMap: Record<string, Array<(node: MdastNode) => void>>,\n exitMap: Record<string, Array<(node: MdastNode) => void>>,\n diagnostics: Diagnostic[],\n file: FileContext,\n): void {\n const wrap =\n (op: 'enter' | 'exit') => (handler: (node: MdastNode) => void) => (node: MdastNode) => {\n try {\n handler(node);\n } catch (err) {\n diagnostics.push(\n internalErrorDiagnostic(rule.meta.name, op, err, file.path),\n );\n }\n };\n\n if (listeners.enter) {\n const wrapEnter = wrap('enter');\n for (const [type, handler] of Object.entries(listeners.enter)) {\n if (handler) (enterMap[type] ??= []).push(wrapEnter(handler));\n }\n }\n if (listeners.exit) {\n const wrapExit = wrap('exit');\n for (const [type, handler] of Object.entries(listeners.exit)) {\n if (handler) (exitMap[type] ??= []).push(wrapExit(handler));\n }\n }\n}\n\nfunction walk(\n node: MdastNode,\n enterMap: Record<string, Array<(node: MdastNode) => void>>,\n exitMap: Record<string, Array<(node: MdastNode) => void>>,\n): void {\n const enterHandlers = enterMap[node.type];\n if (enterHandlers) {\n for (const handler of enterHandlers) handler(node);\n }\n if ('children' in node && Array.isArray(node.children)) {\n for (const child of node.children) {\n walk(child as MdastNode, enterMap, exitMap);\n }\n }\n const exitHandlers = exitMap[node.type];\n if (exitHandlers) {\n for (const handler of exitHandlers) handler(node);\n }\n}\n\n/**\n * Build a `ProjectFile` (path + content + parsed frontmatter + AST) from\n * a raw file. Used by `runRulesOnProject` and by the lint orchestrator\n * to share parsing between per-file and project passes when needed.\n */\nexport function buildProjectFile(file: FileContext): ProjectFile {\n const parsed: ParsedFile = parseFile(file.content);\n return {\n path: file.path,\n content: file.content,\n body: parsed.body,\n frontmatter: parsed.frontmatter,\n metadata: parsed.metadata,\n ast: parsed.ast,\n };\n}\n\n/**\n * Run multiple project rules across all parsed files. Each rule's\n * `check()` is called once with the full file array. Throws are\n * captured as `core/internal-error` diagnostics (attached to the\n * first file's path, since project rules have no file context).\n *\n * See ADR-0005 for the API rationale.\n */\nexport function runRulesOnProject(\n rules: readonly ProjectRule[],\n files: readonly ProjectFile[],\n runtime: RunRuleOptions = {},\n): Diagnostic[] {\n const diagnostics: Diagnostic[] = [];\n const severity = runtime.severity ?? 'error';\n\n for (const rule of rules) {\n const perRuleOptions =\n runtime.optionsByRule?.[rule.meta.name] ?? runtime.options;\n const mergedOptions = {\n ...rule.meta.defaultOptions,\n ...perRuleOptions,\n };\n\n if (rule.meta.schema && !runtime.skipValidation) {\n const validator = getValidator(rule.meta.schema);\n if (!validator(mergedOptions)) {\n throw new RuleOptionsError(\n rule.meta.name,\n ajv.errorsText(validator.errors),\n );\n }\n }\n\n // Same hoisting as the per-file closure — see the comment there (CI x64\n // bench regression when these resolved per report call).\n const ruleName = rule.meta.name;\n const suggestions = rule.meta.suggestions;\n const docsUrl = rule.meta.docs.url ?? '';\n const context: ProjectRuleContext = {\n files,\n options: mergedOptions,\n fileExists: runtime.fileExists,\n report(d) {\n const template = suggestions?.[d.messageId];\n diagnostics.push({\n ruleName,\n severity,\n suggestion: template === undefined ? null : interpolate(template, d.data ?? {}),\n docsUrl,\n ...d,\n });\n },\n };\n\n try {\n rule.check(context);\n } catch (err) {\n // Project rules have no current-file context — attribute the\n // internal-error to a sentinel path rather than mis-attributing\n // to whatever file happens to be first in the array.\n diagnostics.push(\n internalErrorDiagnostic(rule.meta.name, 'check', err, '<project>'),\n );\n }\n }\n\n return diagnostics;\n}\n","// Shared {{placeholder}} interpolation for message AND suggestion templates.\n// Lives in a leaf module so both the runner (which resolves a diagnostic's\n// `suggestion` at report time) and the reporter (which renders the `message`\n// from its template) use one implementation — never two that can drift.\n\n/**\n * Substitute `{{key}}` placeholders in `template` with the matching value from\n * `data`, stringified. An unknown key is left intact (`{{key}}`) so a missing\n * interpolation is a visible bug surface rather than a silent empty string.\n */\nexport function interpolate(\n template: string,\n data: Record<string, unknown>,\n): string {\n // Fast-path placeholder-free templates (e.g. static suggestions): skip the\n // regex scan + callback allocation entirely. This is on the report hot path\n // — resolved once per emitted diagnostic — so the substring guard matters for\n // the sub-microsecond filename-format micro-bench.\n if (!template.includes('{{')) return template;\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key: string) => {\n const v = data[key];\n return v !== undefined ? String(v) : `{{${key}}}`;\n });\n}\n","import type { List, ListItem, Paragraph, Root } from 'mdast';\nimport { fromMarkdown } from 'mdast-util-from-markdown';\nimport { toString } from 'mdast-util-to-string';\nimport grayMatter from 'gray-matter';\n\n/** Source position of a metadata list item, in body coordinates. */\nexport interface MetadataPosition {\n line: number;\n column: number;\n}\n\nexport interface ParsedFile {\n /** Parsed YAML frontmatter (v3/v4), or null if absent. */\n frontmatter: Record<string, unknown> | null;\n /**\n * v2 body-list metadata extracted from the leading list, or null if absent.\n * Covers both the bold-key (`- **Status**:`) and the canonical MADR v2.1.2\n * plain-key (`* Status:`) shapes. See ADR-0006.\n */\n listMetadata: Record<string, unknown> | null;\n /**\n * Combined metadata: frontmatter merged with bold-list. Frontmatter wins\n * on key conflict. null only when both are absent. See ADR-0006.\n */\n metadata: Record<string, unknown> | null;\n /**\n * Body-coordinate positions (list item start) for metadata keys whose\n * EFFECTIVE value came from the v2 leading list. Keys won by defined\n * frontmatter values are absent: frontmatter is stripped before mdast\n * parsing, so it has no body line — and inline suppression directives\n * (which live in the body) could not target it anyway. null when no\n * effective value is list-sourced.\n */\n metadataLoc: Record<string, MetadataPosition> | null;\n /** mdast root of the body (frontmatter stripped). */\n ast: Root;\n /** Body content with frontmatter stripped. */\n body: string;\n}\n\n/**\n * Parse a Markdown file: extract YAML frontmatter via gray-matter, then\n * feed the body into mdast-util-from-markdown directly (per ADR-0002,\n * we skip the unified+remark pipeline overhead). Additionally, extract\n * v2-style list metadata from the body's first list — both bold-key and\n * canonical plain-key shapes (see ADR-0006).\n */\nexport function parseFile(content: string): ParsedFile {\n const matter = grayMatter(content);\n const data = matter.data as Record<string, unknown>;\n const frontmatter = Object.keys(data).length > 0 ? data : null;\n const ast = fromMarkdown(matter.content);\n const listResult = extractListMetadataWithLoc(ast);\n const listMetadata = listResult?.values ?? null;\n\n let metadata: Record<string, unknown> | null = null;\n let metadataLoc: Record<string, MetadataPosition> | null =\n listResult && Object.keys(listResult.loc).length > 0\n ? { ...listResult.loc }\n : null;\n if (frontmatter && listMetadata) {\n // Frontmatter wins on conflict, BUT explicit null/undefined are\n // skipped so that `status: ~` in YAML doesn't blank a present\n // list value (counterintuitive UX otherwise).\n const frontmatterDefined: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(frontmatter)) {\n if (v !== null && v !== undefined) frontmatterDefined[k] = v;\n }\n metadata = { ...listMetadata, ...frontmatterDefined };\n // A frontmatter-won key's effective value is not in the body, so it\n // must not advertise the (shadowed) list item's position.\n if (metadataLoc) {\n for (const k of Object.keys(frontmatterDefined)) delete metadataLoc[k];\n if (Object.keys(metadataLoc).length === 0) metadataLoc = null;\n }\n } else if (frontmatter) {\n metadata = frontmatter;\n } else if (listMetadata) {\n metadata = listMetadata;\n }\n\n return {\n frontmatter,\n listMetadata,\n metadata,\n metadataLoc,\n ast,\n body: matter.content,\n };\n}\n\n// Canonical MADR metadata field names across v2/v3/v4 (after key\n// normalization). Used to distinguish a genuine metadata block from an\n// ordinary leading list: the plain-key shape (`Foo: bar`) is syntactically\n// identical to prose bullets, so we only promote a list to metadata when it\n// carries at least one of these keys. The set is deliberately the canonical\n// fields — a list keyed only by non-standard fields (e.g. `Tags`, `Author`)\n// is treated as prose, not metadata. See the dogfooding notes in ADR-0006.\nconst RECOGNIZED_METADATA_KEYS = new Set([\n 'status',\n 'date',\n 'deciders',\n 'decision-makers',\n 'consulted',\n 'informed',\n]);\n\n/**\n * Extract v2-style list metadata from an mdast Root. The metadata block is\n * the leading list — the first block after the H1 title (only headings may\n * precede it; an intervening paragraph means the list is body content, not\n * metadata). Each `listItem` is read as one `Key: value` pair in either of\n * two shapes:\n *\n * - Bold key: `- **Status**: accepted` (some MADR v2 authors)\n * - Plain key: `* Status: accepted` (official MADR v2.1.2 template)\n *\n * Key normalization: trim → lowercase → spaces become hyphens\n * (matches v4 frontmatter convention, e.g. \"Decision Makers\" →\n * \"decision-makers\"). On duplicate keys, first occurrence wins.\n *\n * Returns null unless the list carries a recognized MADR key, so ordinary\n * leading prose lists are not mistaken for metadata. (A leading list keyed by\n * a recognized field is still treated as metadata even if its value reads\n * prose-like, e.g. `Status: under discussion` — that position + key is\n * overwhelmingly metadata; this is an intentional, bounded tradeoff.)\n *\n * Because the result is gated on MADR field names, callers using this as a\n * generic list reader will get null for purely non-MADR lists.\n */\nexport function extractListMetadata(\n ast: Root,\n): Record<string, unknown> | null {\n return extractListMetadataWithLoc(ast)?.values ?? null;\n}\n\n/**\n * Position-carrying variant used by parseFile: alongside the values, records\n * each key's list-item start position (body coordinates) so diagnostics on\n * list-sourced metadata can carry a line — which is what makes inline\n * suppression directives able to target them.\n */\nfunction extractListMetadataWithLoc(ast: Root): {\n values: Record<string, unknown>;\n loc: Record<string, MetadataPosition>;\n} | null {\n let firstList: List | null = null;\n for (const child of ast.children) {\n if (child.type === 'heading') {\n if (child.depth >= 2) break; // reached the first H2 — no metadata block\n continue; // skip the H1 title (and any further headings)\n }\n // Leading HTML comments / markers don't displace the metadata block.\n if (child.type === 'html') continue;\n if (child.type === 'list') {\n firstList = child;\n break;\n }\n // Any other leading block (paragraph, code, thematic break, …) means the\n // metadata block — which must lead — is absent; the list, if any, is prose.\n break;\n }\n\n if (!firstList) return null;\n\n const values: Record<string, unknown> = {};\n const loc: Record<string, MetadataPosition> = {};\n for (const item of firstList.children) {\n const pair = extractListItemKV(item);\n if (pair && !(pair.key in values)) {\n values[pair.key] = pair.value;\n const start = item.position?.start;\n if (start) loc[pair.key] = { line: start.line, column: start.column };\n }\n }\n\n const hasRecognizedKey = Object.keys(values).some((k) =>\n RECOGNIZED_METADATA_KEYS.has(k),\n );\n return hasRecognizedKey ? { values, loc } : null;\n}\n\nconst KEY_PATTERN = /^[A-Za-z][A-Za-z0-9 \\-_]*$/;\nconst SEPARATOR_PATTERN = /^\\s*:\\s*/;\n\nfunction normalizeKey(rawKey: string): string {\n return rawKey.trim().toLowerCase().replace(/\\s+/g, '-');\n}\n\n/**\n * Read a single `Key: value` pair from one list item. Returns null for any\n * item not shaped as metadata. Two shapes are supported:\n *\n * - Bold key: paragraph starts with `strong` (the Key), followed by a\n * `: value` text node and optional inline tail.\n * - Plain key: paragraph starts with a `text` node holding `Key: value`,\n * followed by optional inline tail.\n *\n * In both shapes the value's inline tail (links, code, emphasis) is\n * flattened via mdast-util-to-string so values keep their text.\n */\nfunction extractListItemKV(\n item: ListItem,\n): { key: string; value: string } | null {\n const para = item.children[0];\n if (para?.type !== 'paragraph') return null;\n\n const paragraph = para as Paragraph;\n const first = paragraph.children[0];\n if (!first) return null;\n\n // Bold key: `**Key**` then a separator text node carrying `: value`.\n if (first.type === 'strong') {\n const keyNode = first.children[0];\n if (keyNode?.type !== 'text' || !KEY_PATTERN.test(keyNode.value)) {\n return null;\n }\n\n const sep = paragraph.children[1];\n if (sep?.type !== 'text' || !SEPARATOR_PATTERN.test(sep.value)) return null;\n\n const valueHead = sep.value.replace(SEPARATOR_PATTERN, '');\n const valueTail = paragraph.children\n .slice(2)\n .map((n) => toString(n))\n .join('');\n const value = (valueHead + valueTail).trim();\n if (value === '') return null;\n\n return { key: normalizeKey(keyNode.value), value };\n }\n\n // Plain key (canonical MADR v2.1.2): first text node holds `Key: value`.\n if (first.type === 'text') {\n const colonIdx = first.value.indexOf(':');\n if (colonIdx === -1) return null;\n\n const rawKey = first.value.slice(0, colonIdx);\n if (!KEY_PATTERN.test(rawKey)) return null;\n\n const valueHead = first.value.slice(colonIdx + 1).replace(/^\\s+/, '');\n const valueTail = paragraph.children\n .slice(1)\n .map((n) => toString(n))\n .join('');\n const value = (valueHead + valueTail).trim();\n if (value === '') return null;\n\n return { key: normalizeKey(rawKey), value };\n }\n\n return null;\n}\n","// Inline suppression directives (see issue #23).\n//\n// Rules stay completely unaware of suppression: they emit diagnostics as\n// usual, and the runner / lint layer filters them centrally *after* reporting,\n// using directives collected from the file's mdast `html` comment nodes.\n//\n// COORDINATE SYSTEM: directives are read from mdast `html` node positions.\n// Because `parseFile` strips YAML frontmatter with gray-matter BEFORE feeding\n// the body to `mdast-util-from-markdown`, every mdast position — and therefore\n// every directive line AND every AST-derived diagnostic `loc.line` — lives in\n// the same body coordinate space (frontmatter height removed). We deliberately\n// do NOT scan the raw file text, which would put directive lines in raw-file\n// coordinates and silently mis-align them with diagnostic lines.\n\nimport type { Root } from 'mdast';\nimport {\n INTERNAL_ERROR_RULE_NAME,\n type Diagnostic,\n type MdastNode,\n} from './types.js';\n\ntype DirectiveKind = 'disable-file' | 'disable' | 'enable' | 'disable-next-line';\n\n// Only these exact keywords are directives. An unknown suffix (e.g.\n// `madr-lint-disable-line`) is a full non-matching token and is ignored.\nconst DIRECTIVE_KINDS = new Set<DirectiveKind>([\n 'disable-file',\n 'disable',\n 'enable',\n 'disable-next-line',\n]);\n\n/**\n * Every directive form contains this literal. Callers use it as a cheap\n * raw-content pre-filter: since the parsed body is a substring of the raw\n * content, `!content.includes(DIRECTIVE_PREFIX)` PROVES the file contains\n * no directives — so directive collection, and any parse it would otherwise\n * force, can be skipped entirely.\n */\nexport const DIRECTIVE_PREFIX = 'madr-lint-';\n\ninterface Directive {\n kind: DirectiveKind;\n /** null = applies to all rules; otherwise the explicit rule-id list. */\n rules: readonly string[] | null;\n /** 1-based directive line in body (frontmatter-stripped) coordinates. */\n line: number;\n}\n\ninterface NextLineEntry {\n all: boolean;\n rules: Set<string>;\n}\n\nexport interface DirectiveIndex {\n /** An unscoped `disable-file` disables every rule for the whole file. */\n fileDisableAll: boolean;\n /** Rules disabled file-wide via `disable-file <rules>`. */\n fileDisableRules: Set<string>;\n /** `disable` / `enable` directives, sorted by line ascending. */\n ranged: Directive[];\n /** disable-next-line: target line (directive line + 1) → affected rules. */\n nextLine: Map<number, NextLineEntry>;\n}\n\n/** Parse one `<!-- ... -->` html node value into a directive, or null. */\nfunction parseDirective(value: string, line: number): Directive | null {\n const trimmed = value.trim();\n if (!trimmed.startsWith('<!--') || !trimmed.endsWith('-->')) return null;\n\n const inner = trimmed.slice(4, -3).trim();\n // Two comments coalesced into one html node (e.g. `<!-- a --><!-- b -->`\n // on one line) pass the startsWith/endsWith guard but would sweep\n // `--><!--` garbage into the rule list. A directive comment must stand\n // alone: reject any candidate whose interior still carries comment\n // delimiters.\n if (inner.includes('<!--') || inner.includes('-->')) return null;\n if (!inner.startsWith(DIRECTIVE_PREFIX)) return null;\n\n const afterPrefix = inner.slice(DIRECTIVE_PREFIX.length);\n // The keyword token ends at the first whitespace; the remainder is the\n // optional rule list. Matching the FULL token against the exact keyword set\n // is what makes `madr-lint-disable-line` (token `disable-line`) a non-match.\n const wsIndex = afterPrefix.search(/\\s/);\n const keyword = wsIndex === -1 ? afterPrefix : afterPrefix.slice(0, wsIndex);\n if (!DIRECTIVE_KINDS.has(keyword as DirectiveKind)) return null;\n\n const rest = wsIndex === -1 ? '' : afterPrefix.slice(wsIndex);\n return { kind: keyword as DirectiveKind, rules: parseRuleList(rest), line };\n}\n\nfunction parseRuleList(rest: string): readonly string[] | null {\n const trimmed = rest.trim();\n if (trimmed === '') return null; // no list ⇒ all rules\n const rules = trimmed\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s !== '');\n return rules.length > 0 ? rules : null;\n}\n\nfunction walkHtml(node: MdastNode, out: Directive[]): void {\n if (node.type === 'html') {\n const line = node.position?.start.line;\n if (typeof line === 'number') {\n const directive = parseDirective(node.value, line);\n if (directive) out.push(directive);\n }\n }\n if ('children' in node && Array.isArray(node.children)) {\n for (const child of node.children) walkHtml(child as MdastNode, out);\n }\n}\n\n/**\n * Collect suppression directives from a file's mdast tree in one cheap walk.\n * Returns null when the file carries no directives, so callers can skip\n * filtering entirely (fast path). Both block and inline `html` comment nodes\n * are inspected.\n *\n * `body` is the frontmatter-stripped body text — the SAME coordinate space\n * as the mdast positions. It is only consulted (and only split into lines)\n * when a `disable-next-line` directive needs to resolve its target.\n */\nexport function collectDirectives(\n ast: Root,\n body: string,\n): DirectiveIndex | null {\n const all: Directive[] = [];\n walkHtml(ast as MdastNode, all);\n if (all.length === 0) return null;\n\n // disable-next-line targets the next NON-BLANK line, not the literal next\n // line. This deviates from ESLint deliberately: Markdown authors\n // idiomatically leave a blank line after a comment block, and a directive\n // that silently misses across it would be a footgun.\n let lines: string[] | null = null;\n const nextNonBlankLine = (after: number): number | null => {\n lines ??= body.split('\\n');\n for (let ln = after + 1; ln <= lines.length; ln++) {\n if ((lines[ln - 1] ?? '').trim() !== '') return ln;\n }\n return null; // directive at EOF with nothing after it — no target\n };\n\n const index: DirectiveIndex = {\n fileDisableAll: false,\n fileDisableRules: new Set(),\n ranged: [],\n nextLine: new Map(),\n };\n\n for (const directive of all) {\n switch (directive.kind) {\n case 'disable-file': {\n if (directive.rules === null) index.fileDisableAll = true;\n else for (const rule of directive.rules) index.fileDisableRules.add(rule);\n break;\n }\n case 'disable':\n case 'enable': {\n index.ranged.push(directive);\n break;\n }\n case 'disable-next-line': {\n const target = nextNonBlankLine(directive.line);\n if (target === null) break;\n let entry = index.nextLine.get(target);\n if (!entry) {\n entry = { all: false, rules: new Set() };\n index.nextLine.set(target, entry);\n }\n if (directive.rules === null) entry.all = true;\n else for (const rule of directive.rules) entry.rules.add(rule);\n break;\n }\n }\n }\n\n index.ranged.sort((a, b) => a.line - b.line);\n return index;\n}\n\nfunction directiveApplies(directive: Directive, ruleName: string): boolean {\n return directive.rules === null || directive.rules.includes(ruleName);\n}\n\n/**\n * Is a single diagnostic suppressed by the file's directives?\n *\n * `core/internal-error` is handled by the caller and never reaches here.\n *\n * Line-less diagnostics (no `loc`) are treated as spanning the whole file:\n * only `disable-file` OR an OPEN-ENDED `disable` (a `disable` with no later\n * matching `enable`) suppresses them. This is exactly the \"file-scoped\"\n * contract the issue specifies for project-rule diagnostics.\n */\nexport function isSuppressed(\n index: DirectiveIndex,\n ruleName: string,\n line: number | undefined,\n): boolean {\n if (index.fileDisableAll || index.fileDisableRules.has(ruleName)) return true;\n\n if (line !== undefined) {\n const next = index.nextLine.get(line);\n if (next && (next.all || next.rules.has(ruleName))) return true;\n }\n\n // Replay disable/enable in line order; the last one at or before the\n // diagnostic line wins. A line-less diagnostic uses +Infinity as its line,\n // so every directive is replayed and only an unclosed final `disable`\n // (open to EOF) leaves it suppressed. This same replay yields ESLint-style\n // carve-outs, e.g. an unscoped `disable` followed by a scoped `enable`.\n const ceiling = line ?? Number.POSITIVE_INFINITY;\n let disabled = false;\n for (const directive of index.ranged) {\n if (directive.line > ceiling) break; // ranged is sorted ascending\n if (directiveApplies(directive, ruleName)) {\n disabled = directive.kind === 'disable';\n }\n }\n return disabled;\n}\n\n/**\n * Filter suppressed diagnostics. `core/internal-error` diagnostics are NEVER\n * suppressible: they signal a rule bug (always severity 'error'), and letting\n * a `disable`/`disable-file` hide them would mask defects. This is the\n * simplest behavior consistent with the runner already forcing internal-error\n * severity regardless of user config.\n */\nexport function filterSuppressed(\n diagnostics: readonly Diagnostic[],\n index: DirectiveIndex,\n): Diagnostic[] {\n return diagnostics.filter((d) => {\n if (d.ruleName === INTERNAL_ERROR_RULE_NAME) return true;\n return !isSuppressed(index, d.ruleName, d.loc?.line);\n });\n}\n","import pc from 'picocolors';\nimport { interpolate } from './interpolate.js';\nimport type { AnyRule, Diagnostic } from './types.js';\n\n/**\n * Run-level facts a reporter cannot derive from the diagnostics themselves.\n * Optional third argument so existing two-arg callers keep working.\n */\nexport interface ReporterMeta {\n /** Diagnostics absorbed by .madr-lint/baseline.json. Absent ⇒ 0. */\n baselineHidden?: number;\n}\n\nexport interface Reporter {\n format(\n diagnostics: readonly Diagnostic[],\n rulesByName: Map<string, AnyRule>,\n meta?: ReporterMeta,\n ): string;\n}\n\nexport type ReporterFormat = 'text' | 'json' | 'sarif' | 'github';\n\n/**\n * Human-readable reporter for terminal output. Groups diagnostics by file,\n * interpolates {{placeholders}} from `data` against the rule's message\n * template, and ends with a count summary.\n *\n * Coloring uses picocolors which honors NO_COLOR / FORCE_COLOR env vars.\n */\nexport const textReporter: Reporter = {\n // Deliberately 2-param (meta unused): the CLI prints baselineHiddenSummary()\n // itself for text format, so the footer can outlive a suppressed banner.\n format(diagnostics, rulesByName) {\n if (diagnostics.length === 0) {\n return pc.green('✓ All clear.');\n }\n\n const byFile = groupByFile(diagnostics);\n const lines: string[] = [];\n\n // Aligns a suggestion / docs line under the message column:\n // severity gutter (9) + padded ruleId (28) + the 2-space separator.\n const gutter = ' '.repeat(9 + 28 + 2);\n\n for (const [file, fileDiagnostics] of byFile) {\n lines.push(pc.underline(file));\n // ruleName -> docs URL, first-seen order, one entry per rule in the group.\n const docsByRule = new Map<string, string>();\n for (const d of fileDiagnostics) {\n const sev =\n d.severity === 'error'\n ? pc.red(' error ')\n : pc.yellow(' warn ');\n const ruleId = pc.dim(d.ruleName.padEnd(28));\n const message = renderMessage(d, rulesByName);\n lines.push(`${sev}${ruleId} ${message}`);\n if (d.suggestion) {\n lines.push(`${gutter}${pc.cyan(`→ ${d.suggestion}`)}`);\n }\n if (d.docsUrl && !docsByRule.has(d.ruleName)) {\n docsByRule.set(d.ruleName, d.docsUrl);\n }\n }\n // Compact footer: the docs URL once per rule per file group, never per\n // diagnostic — self-contained without repeating the link. See issue #67.\n for (const [ruleName, url] of docsByRule) {\n lines.push(pc.dim(` ${ruleName} ${url}`));\n }\n lines.push('');\n }\n\n const errors = diagnostics.filter((d) => d.severity === 'error').length;\n const warnings = diagnostics.filter((d) => d.severity === 'warn').length;\n lines.push(pc.bold(formatSummary(errors, warnings)));\n\n return lines.join('\\n');\n },\n};\n\nfunction groupByFile(diagnostics: readonly Diagnostic[]): Map<string, Diagnostic[]> {\n const map = new Map<string, Diagnostic[]>();\n for (const d of diagnostics) {\n if (!map.has(d.path)) map.set(d.path, []);\n map.get(d.path)?.push(d);\n }\n return map;\n}\n\nfunction renderMessage(\n d: Diagnostic,\n rulesByName: Map<string, AnyRule>,\n): string {\n const rule = rulesByName.get(d.ruleName);\n const template = rule?.meta.messages[d.messageId] ?? d.messageId;\n return interpolate(template, d.data ?? {});\n}\n\nfunction formatSummary(errors: number, warnings: number): string {\n const parts: string[] = [];\n if (errors > 0) parts.push(`${errors} ${errors === 1 ? 'error' : 'errors'}`);\n if (warnings > 0) parts.push(`${warnings} ${warnings === 1 ? 'warning' : 'warnings'}`);\n return parts.join(', ');\n}\n\n/**\n * Machine-readable JSON reporter. Stable shape — additive changes only,\n * tagged via `version`. Tools can `JSON.parse` stdout and consume `results`\n * directly without scraping the human-readable formatter.\n */\nexport const jsonReporter: Reporter = {\n format(diagnostics, rulesByName, meta) {\n const errors = diagnostics.filter((d) => d.severity === 'error').length;\n const warnings = diagnostics.filter((d) => d.severity === 'warn').length;\n const payload = {\n version: 1,\n summary: {\n total: diagnostics.length,\n errors,\n warnings,\n // Always present (0 when no baseline) so CI consumers can detect an\n // active baseline without probing for the key. SARIF stays untouched.\n baselineHidden: meta?.baselineHidden ?? 0,\n },\n results: diagnostics.map((d) => ({\n path: d.path,\n ruleName: d.ruleName,\n messageId: d.messageId,\n severity: d.severity,\n message: renderMessage(d, rulesByName),\n // Self-contained diagnostics (#67): always present so consumers can\n // rely on the keys — `suggestion` is null when the rule declares none.\n suggestion: d.suggestion,\n docsUrl: d.docsUrl,\n data: d.data ?? {},\n })),\n };\n return JSON.stringify(payload, null, 2);\n },\n};\n\n/**\n * SARIF 2.1.0 reporter. Emits a minimal-but-valid Static Analysis Results\n * Interchange Format document so GitHub Code Scanning, VS Code SARIF\n * Viewer, and other consumers can ingest madr-lint results.\n *\n * Spec: https://docs.oasis-open.org/sarif/sarif/v2.1.0/sarif-v2.1.0.html\n */\nexport const sarifReporter: Reporter = {\n format(diagnostics, rulesByName) {\n const ruleNames = [...new Set(diagnostics.map((d) => d.ruleName))];\n const ruleIndex = new Map(ruleNames.map((name, i) => [name, i]));\n\n const sarifRules = ruleNames.map((name) => {\n const rule = rulesByName.get(name);\n return {\n id: name,\n name: name.replace(/[^A-Za-z0-9]/g, '_'),\n shortDescription: { text: rule?.meta.docs.description ?? name },\n helpUri: rule?.meta.docs.url,\n };\n });\n\n const sarifResults = diagnostics.map((d) => ({\n ruleId: d.ruleName,\n ruleIndex: ruleIndex.get(d.ruleName) ?? 0,\n level: d.severity === 'error' ? 'error' : 'warning',\n message: { text: renderMessage(d, rulesByName) },\n locations: [\n {\n physicalLocation: {\n artifactLocation: { uri: d.path, uriBaseId: '%SRCROOT%' },\n region: { startLine: 1 },\n },\n },\n ],\n }));\n\n const sarif = {\n $schema:\n 'https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0.json',\n version: '2.1.0',\n runs: [\n {\n tool: {\n driver: {\n name: 'madr-lint',\n informationUri: 'https://github.com/knktkc/madr-lint',\n rules: sarifRules,\n },\n },\n results: sarifResults,\n },\n ],\n };\n return JSON.stringify(sarif, null, 2);\n },\n};\n\n/** Escape a workflow-command message value (data after `::`). */\nfunction escapeGhMessage(s: string): string {\n return s.replace(/%/g, '%25').replace(/\\r/g, '%0D').replace(/\\n/g, '%0A');\n}\n\n/** Escape a workflow-command property value (e.g. file=, title=). */\nfunction escapeGhProperty(s: string): string {\n return escapeGhMessage(s)\n .replace(/,/g, '%2C')\n .replace(/:/g, '%3A');\n}\n\n/**\n * GitHub Actions annotation reporter. Emits one `::error` / `::warning`\n * workflow command per diagnostic so GitHub renders them as PR diff annotations,\n * then a one-line human summary on stdout.\n *\n * Escape rules from https://docs.github.com/en/actions/writing-workflows/choosing-what-your-workflow-does/workflow-commands-for-github-actions\n */\nexport const githubReporter: Reporter = {\n format(diagnostics, rulesByName, meta) {\n const lines: string[] = [];\n\n for (const d of diagnostics) {\n const level = d.severity === 'error' ? 'error' : 'warning';\n const file = escapeGhProperty(d.path);\n const title = escapeGhProperty(d.ruleName);\n // Self-contained diagnostics (#67): fold the suggestion into the single\n // annotation message (annotations carry no separate remediation field),\n // escaping the combined string once. Properties are unchanged.\n const rendered = renderMessage(d, rulesByName);\n const message = escapeGhMessage(\n d.suggestion ? `${rendered} — ${d.suggestion}` : rendered,\n );\n\n const linePart = d.loc ? `,line=${d.loc.line}` : '';\n lines.push(`::${level} file=${file}${linePart},title=${title}::${message}`);\n }\n\n const errors = diagnostics.filter((d) => d.severity === 'error').length;\n const warnings = diagnostics.filter((d) => d.severity === 'warn').length;\n const summaryParts: string[] = [];\n if (errors > 0) summaryParts.push(`${errors} ${errors === 1 ? 'error' : 'errors'}`);\n if (warnings > 0) summaryParts.push(`${warnings} ${warnings === 1 ? 'warning' : 'warnings'}`);\n // A clean run still prints counts — a silent log line reads as a broken CI step.\n if (summaryParts.length === 0) summaryParts.push('0 errors, 0 warnings');\n const baselineHidden = meta?.baselineHidden ?? 0;\n if (baselineHidden > 0) summaryParts.push(`${baselineHidden} hidden by baseline`);\n lines.push(summaryParts.join(', '));\n\n return lines.join('\\n');\n },\n};\n\nexport const reporters: Record<ReporterFormat, Reporter> = {\n text: textReporter,\n json: jsonReporter,\n sarif: sarifReporter,\n github: githubReporter,\n};\n","// Registry of all built-in madr-lint rules.\n// New rules append here via the add-rule skill.\n\nexport { default as dateIso8601 } from './date-iso8601/index.js';\nexport { default as filenameFormat } from './filename-format/index.js';\nexport { default as noBrokenLinks } from './no-broken-links/index.js';\nexport { default as noDuplicateNumbering } from './no-duplicate-numbering/index.js';\nexport { default as noNumberingGap } from './no-numbering-gap/index.js';\nexport { default as requiredSections } from './required-sections/index.js';\nexport { default as statusEnum } from './status-enum/index.js';\nexport { default as supersedesBidirectional } from './supersedes-bidirectional/index.js';\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"field\": {\n \"type\": \"string\",\n \"description\": \"Frontmatter key to read. Default: 'date'.\"\n }\n }\n}\n","import type { Rule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface DateIso8601Options extends Record<string, unknown> {\n field: string;\n}\n\nfunction normalizeDate(value: unknown): string | null {\n if (typeof value === 'string') return value;\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) return null;\n return value.toISOString().slice(0, 10);\n }\n return null;\n}\n\nfunction isValidIso8601Date(s: string): boolean {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(s)) return false;\n const parts = s.split('-').map(Number);\n const [year, month, day] = parts;\n if (year === undefined || month === undefined || day === undefined) return false;\n const d = new Date(Date.UTC(year, month - 1, day));\n return (\n d.getUTCFullYear() === year &&\n d.getUTCMonth() === month - 1 &&\n d.getUTCDate() === day\n );\n}\n\nconst rule: Rule<DateIso8601Options> = {\n meta: {\n name: 'madr/date-iso8601',\n type: 'perFile',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description: 'Validate that ADR `date` (frontmatter or v2 bold-list) is a valid ISO 8601 calendar date (YYYY-MM-DD)',\n url: 'https://knktkc.github.io/madr-lint/rules/date-iso8601/',\n recommended: true,\n },\n messages: {\n missingDate: 'Metadata does not contain a \"{{field}}\" field (checked frontmatter and v2 bold-list)',\n invalidDate: 'Date \"{{date}}\" is not a valid ISO 8601 calendar date (YYYY-MM-DD)',\n },\n suggestions: {\n missingDate:\n 'add a \"{{field}}\" field in YYYY-MM-DD format to the frontmatter (for MADR v2, a \"* Date: ...\" list item)',\n invalidDate: 'use the YYYY-MM-DD calendar-date format, e.g. 2025-03-14',\n },\n defaultOptions: {\n field: 'date',\n },\n schema,\n },\n create(context) {\n const meta = context.metadata;\n const fieldName = context.options.field;\n\n if (!meta) {\n context.report({\n messageId: 'missingDate',\n data: { field: fieldName },\n });\n return;\n }\n\n const raw = meta[fieldName];\n const dateStr = normalizeDate(raw);\n if (dateStr === null) {\n context.report({\n messageId: 'missingDate',\n data: { field: fieldName },\n });\n return;\n }\n\n if (!isValidIso8601Date(dateStr)) {\n // loc only exists for v2 list-sourced values: frontmatter is stripped\n // before mdast parsing, so a frontmatter-sourced date has no body line\n // to point at — inline suppression directives (which live in the body)\n // can only silence it file-wide, never per line.\n const loc = context.metadataLoc?.[fieldName];\n context.report({\n messageId: 'invalidDate',\n ...(loc ? { loc } : {}),\n data: { date: dateStr },\n });\n }\n },\n};\n\nexport default rule;\n","import { basename } from 'node:path';\nimport { assertSafeRegex } from '../../core/regex-safety.js';\nimport type { Rule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface FilenameFormatOptions extends Record<string, unknown> {\n pattern: string;\n}\n\nconst rule: Rule<FilenameFormatOptions> = {\n meta: {\n name: 'madr/filename-format',\n type: 'perFile',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description: 'Enforce ADR filename convention NNNN-kebab-case.md',\n url: 'https://knktkc.github.io/madr-lint/rules/filename-format/',\n recommended: true,\n },\n messages: {\n invalidFilename:\n 'Filename \"{{filename}}\" does not match expected pattern \"{{expected}}\"',\n },\n suggestions: {\n // The message already states the expected pattern; the suggestion adds a\n // concrete, conforming example of the NNNN-kebab-case.md convention.\n invalidFilename:\n 'rename the file to the NNNN-kebab-case.md convention, e.g. 0001-record-architecture-decisions.md',\n },\n defaultOptions: {\n pattern: '^[0-9]{4}-[a-z0-9-]+\\\\.md$',\n },\n schema,\n },\n create(context) {\n const { pattern } = context.options;\n const regex = assertSafeRegex(pattern, 'madr/filename-format', 'pattern');\n const filename = basename(context.file.path);\n if (!regex.test(filename)) {\n context.report({\n messageId: 'invalidFilename',\n data: { filename, expected: pattern },\n });\n }\n },\n};\n\nexport default rule;\n","import safeRegex from 'safe-regex2';\nimport { RuleOptionsError } from './runner.js';\n\nconst SAFE_REGEX_LIMIT = 25;\n\n// Pattern → compiled RegExp cache. Only safe patterns are cached; unsafe\n// or syntactically invalid ones throw on every call (callers should fix\n// their config rather than burn cycles re-validating the same bad input).\n//\n// Cache scope: module-global. Keys are pattern strings, which are static\n// per rule.defaultOptions or per user config. Bounded in practice — a\n// long-running daemon would still see at most O(rules × user-overrides)\n// distinct patterns. If memory becomes a concern in pathological cases\n// (e.g. dynamically-generated patterns), the cache can be swapped for an\n// LRU. As of v0.1, a plain Map is sufficient.\nconst cache = new Map<string, RegExp>();\n\nexport function assertSafeRegex(\n pattern: string,\n ruleName: string,\n optionPath: string,\n): RegExp {\n const cached = cache.get(pattern);\n if (cached) return cached;\n\n let regex: RegExp;\n try {\n regex = new RegExp(pattern);\n } catch (err) {\n throw new RuleOptionsError(\n ruleName,\n `option \"${optionPath}\" is not a valid regular expression: ${(err as Error).message}`,\n );\n }\n if (!safeRegex(regex, { limit: SAFE_REGEX_LIMIT })) {\n throw new RuleOptionsError(\n ruleName,\n `option \"${optionPath}\" (${pattern}) appears unsafe (catastrophic backtracking). Reject before runtime.`,\n );\n }\n cache.set(pattern, regex);\n return regex;\n}\n\n/**\n * Test-only helper to drop the cache between unit tests so that\n * \"unsafe pattern\" assertions don't accidentally short-circuit on a\n * previously-cached safe entry. Not exported from src/index.ts.\n */\nexport function clearRegexCacheForTesting(): void {\n cache.clear();\n}\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"pattern\": {\n \"type\": \"string\",\n \"description\": \"Regex (as string) the basename must match. Defaults to ^[0-9]{4}-[a-z0-9-]+\\\\.md$\"\n }\n }\n}\n","import { dirname, posix } from 'node:path';\nimport type { MdastNode, ProjectRule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface NoBrokenLinksOptions extends Record<string, unknown> {\n // No options at v0.1.\n}\n\nconst PROTOCOL_REGEX = /^[a-z][a-z0-9+.-]*:/i;\n\ninterface LinkLikeNode {\n url: string;\n /** unist position — start carries the body-coordinate line/column. */\n position?: { start: { line: number; column: number } };\n}\n\nfunction isLinkNode(node: MdastNode): node is MdastNode & LinkLikeNode {\n return (\n node.type === 'link' &&\n 'url' in node &&\n typeof (node as { url: unknown }).url === 'string'\n );\n}\n\nfunction isExternalOrAnchor(url: string): boolean {\n if (url === '' || url.startsWith('#')) return true;\n return PROTOCOL_REGEX.test(url);\n}\n\nfunction stripAnchorAndQuery(url: string): string {\n const hash = url.indexOf('#');\n const query = url.indexOf('?');\n let cut = hash;\n if (query !== -1 && (cut === -1 || query < cut)) cut = query;\n return cut === -1 ? url : url.slice(0, cut);\n}\n\n// Markdown link destinations may be percent-encoded (e.g. `my%20file.md`).\n// Decode to the real on-disk path for resolution; leave malformed encoding\n// (e.g. a bare `%`) untouched rather than throwing. Fast-path the common case\n// of no percent-encoding to keep per-link cost minimal (decodeURIComponent is\n// comparatively expensive).\nfunction safeDecode(path: string): string {\n if (!path.includes('%')) return path;\n try {\n return decodeURIComponent(path);\n } catch {\n return path;\n }\n}\n\nfunction resolveRelative(fromDir: string, url: string): string {\n // Treat absolute (`/foo`) as project-rooted by stripping the leading slash,\n // so `[x](/0042-y.md)` resolves to `0042-y.md` rather than the OS root.\n if (url.startsWith('/')) return url.slice(1);\n return posix.normalize(posix.join(fromDir, url));\n}\n\nfunction collectLinks(node: MdastNode, out: LinkLikeNode[]): void {\n if (isLinkNode(node)) out.push(node);\n if ('children' in node && Array.isArray(node.children)) {\n for (const child of node.children) {\n collectLinks(child as MdastNode, out);\n }\n }\n}\n\nconst rule: ProjectRule<NoBrokenLinksOptions> = {\n meta: {\n name: 'madr/no-broken-links',\n type: 'project',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description:\n 'Relative-path Markdown links must resolve to an existing file in the project',\n url: 'https://knktkc.github.io/madr-lint/rules/no-broken-links/',\n recommended: true,\n },\n messages: {\n brokenLink:\n 'Link to \"{{url}}\" resolves to \"{{resolvedPath}}\", which does not exist in the project',\n },\n suggestions: {\n brokenLink:\n \"fix the link target or remove the link; relative paths resolve from the ADR file's own directory\",\n },\n defaultOptions: {},\n schema,\n },\n check(context) {\n const knownPaths = new Set<string>();\n for (const file of context.files) {\n knownPaths.add(file.path);\n }\n\n for (const file of context.files) {\n const links: LinkLikeNode[] = [];\n collectLinks(file.ast, links);\n\n for (const link of links) {\n const url = link.url;\n if (isExternalOrAnchor(url)) continue;\n\n const pathOnly = safeDecode(stripAnchorAndQuery(url));\n if (pathOnly === '') continue;\n\n const fileDir = dirname(file.path);\n const resolvedPath = resolveRelative(fileDir, pathOnly);\n\n // A target counts as present if it is one of the linted .md files\n // OR exists on disk (covers non-Markdown assets and files outside\n // the scanned paths). fileExists is undefined in pure in-memory\n // runs, where knownPaths is the only source of truth. NOTE: the\n // on-disk check inherits the host filesystem's case-sensitivity —\n // a wrong-case link may pass on macOS/Windows yet fail on Linux/CI.\n const exists =\n knownPaths.has(resolvedPath) ||\n (context.fileExists?.(resolvedPath) ?? false);\n\n if (!exists) {\n // Link position is in body coordinates (frontmatter stripped) —\n // the same space suppression directives use, so disable-next-line\n // can target this diagnostic.\n const start = link.position?.start;\n context.report({\n messageId: 'brokenLink',\n path: file.path,\n ...(start\n ? { loc: { line: start.line, column: start.column } }\n : {}),\n data: { url, resolvedPath },\n });\n }\n }\n }\n },\n};\n\nexport default rule;\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {}\n}\n","import { basename } from 'node:path';\nimport type { ProjectRule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface NoDuplicateNumberingOptions extends Record<string, unknown> {\n // No options at v0.1.\n}\n\nconst NUMBER_REGEX = /^(\\d{4})-/;\n\nconst rule: ProjectRule<NoDuplicateNumberingOptions> = {\n meta: {\n name: 'madr/no-duplicate-numbering',\n type: 'project',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description: 'No two ADRs share the same NNNN- number prefix',\n url: 'https://knktkc.github.io/madr-lint/rules/no-duplicate-numbering/',\n recommended: true,\n },\n messages: {\n duplicateNumber: 'ADR number {{number}} is used by multiple files: {{paths}}',\n },\n suggestions: {\n duplicateNumber:\n 'renumber all but one of these files so each ADR has a unique NNNN- prefix',\n },\n defaultOptions: {},\n schema,\n },\n check(context) {\n const byNumber = new Map<string, string[]>();\n for (const file of context.files) {\n const match = NUMBER_REGEX.exec(basename(file.path));\n if (!match) continue;\n const number = match[1];\n if (number === undefined) continue;\n const group = byNumber.get(number) ?? [];\n group.push(file.path);\n byNumber.set(number, group);\n }\n\n for (const [number, paths] of byNumber) {\n if (paths.length > 1) {\n const pathList = paths.join(', ');\n for (const path of paths) {\n context.report({\n messageId: 'duplicateNumber',\n path,\n data: { number, paths: pathList },\n });\n }\n }\n }\n },\n};\n\nexport default rule;\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {}\n}\n","import { basename } from 'node:path';\nimport type { ProjectRule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface NoNumberingGapOptions extends Record<string, unknown> {\n // No options at v0.1.\n}\n\nconst NUMBER_REGEX = /^(\\d{4})-/;\n\nfunction format4(n: number): string {\n return n.toString().padStart(4, '0');\n}\n\nconst rule: ProjectRule<NoNumberingGapOptions> = {\n meta: {\n name: 'madr/no-numbering-gap',\n type: 'project',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description:\n 'Detect gaps in ADR numbering (e.g. 0001 and 0003 exist but 0002 is missing). Convention-only; default off.',\n url: 'https://knktkc.github.io/madr-lint/rules/no-numbering-gap/',\n recommended: false,\n },\n messages: {\n numberingGap:\n 'Numbering gap: missing {{missing}} between ADR-{{from}} and ADR-{{to}}',\n },\n // No `suggestions`: a gap can be intentional (a rejected or deleted ADR),\n // and closing it may mean either adding the missing ADR OR renumbering —\n // the right remediation is contextual, so we omit a suggestion. See #67.\n defaultOptions: {},\n schema,\n },\n check(context) {\n // Map ADR number → file path. Files without a NNNN- prefix are ignored.\n const numberToPath = new Map<number, string>();\n for (const file of context.files) {\n const match = NUMBER_REGEX.exec(basename(file.path));\n if (!match?.[1]) continue;\n const n = Number.parseInt(match[1], 10);\n if (!Number.isNaN(n)) numberToPath.set(n, file.path);\n }\n if (numberToPath.size < 2) return;\n\n const sortedNumbers = Array.from(numberToPath.keys()).toSorted(\n (a, b) => a - b,\n );\n\n for (let i = 1; i < sortedNumbers.length; i++) {\n const prev = sortedNumbers[i - 1];\n const curr = sortedNumbers[i];\n if (prev === undefined || curr === undefined) continue;\n if (curr === prev + 1) continue;\n\n const missingNumbers: string[] = [];\n for (let n = prev + 1; n < curr; n++) {\n missingNumbers.push(format4(n));\n }\n\n const currPath = numberToPath.get(curr);\n if (!currPath) continue;\n\n context.report({\n messageId: 'numberingGap',\n path: currPath,\n data: {\n from: format4(prev),\n to: format4(curr),\n missing: missingNumbers.join(', '),\n },\n });\n }\n },\n};\n\nexport default rule;\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {}\n}\n","import { toString } from 'mdast-util-to-string';\nimport type { Rule, RuleListeners } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface RequiredSectionsOptions extends Record<string, unknown> {\n sections: string[];\n matchMode: 'exact' | 'startsWith';\n}\n\nconst rule: Rule<RequiredSectionsOptions> = {\n meta: {\n name: 'madr/required-sections',\n type: 'perFile',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description: 'Enforce that ADRs contain required heading sections',\n url: 'https://knktkc.github.io/madr-lint/rules/required-sections/',\n recommended: true,\n },\n messages: {\n missingSection: 'Missing required section: \"{{section}}\"',\n },\n suggestions: {\n missingSection:\n 'add a \"## {{section}}\" heading to the document body',\n },\n defaultOptions: {\n sections: [\n 'Context and Problem Statement',\n 'Decision Outcome',\n 'Consequences',\n ],\n matchMode: 'exact',\n },\n schema,\n },\n create(context): RuleListeners {\n const seen: string[] = [];\n return {\n enter: {\n heading(node) {\n if (node.type !== 'heading') return;\n seen.push(toString(node).trim());\n },\n },\n exit: {\n root() {\n const { sections, matchMode } = context.options;\n for (const section of sections) {\n const matched = seen.some((heading) =>\n matchMode === 'startsWith'\n ? heading.startsWith(section)\n : heading === section,\n );\n if (!matched) {\n context.report({\n messageId: 'missingSection',\n data: { section, found: [...seen] },\n });\n }\n }\n },\n },\n };\n },\n};\n\nexport default rule;\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"sections\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" },\n \"description\": \"Required heading texts. Order does not matter.\"\n },\n \"matchMode\": {\n \"type\": \"string\",\n \"enum\": [\"exact\", \"startsWith\"],\n \"description\": \"Comparison mode against heading text.\"\n }\n }\n}\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"values\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" },\n \"description\": \"Exact-match allowed status values.\"\n },\n \"prefixValues\": {\n \"type\": \"array\",\n \"items\": { \"type\": \"string\" },\n \"description\": \"startsWith-match allowed prefixes (e.g. 'superseded by').\"\n },\n \"caseSensitive\": {\n \"type\": \"boolean\",\n \"description\": \"When false, comparisons are case-insensitive.\"\n }\n }\n}\n","import type { Rule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface StatusEnumOptions extends Record<string, unknown> {\n values: string[];\n prefixValues: string[];\n caseSensitive: boolean;\n}\n\nconst rule: Rule<StatusEnumOptions> = {\n meta: {\n name: 'madr/status-enum',\n type: 'perFile',\n versionCompat: ['v2', 'v3', 'v4'],\n docs: {\n description: 'Validate that ADR `status` (frontmatter or v2 bold-list) is in the allowed enum',\n url: 'https://knktkc.github.io/madr-lint/rules/status-enum/',\n recommended: true,\n },\n messages: {\n missingStatus: 'Metadata does not contain a \"status\" field (checked frontmatter and v2 bold-list)',\n invalidStatus: 'Status \"{{status}}\" is not one of: {{allowed}}',\n },\n // No suggestion for invalidStatus: the message already lists the allowed\n // values (the expected-vs-actual is self-contained), so a suggestion would\n // only restate it. See issue #67.\n suggestions: {\n missingStatus:\n 'add a \"status\" field to the frontmatter (for MADR v2, a \"* Status: ...\" list item) — allowed values: {{allowed}}',\n },\n defaultOptions: {\n values: ['proposed', 'rejected', 'accepted', 'deprecated'],\n prefixValues: ['superseded by'],\n caseSensitive: false,\n },\n schema,\n },\n create(context) {\n const { values, prefixValues, caseSensitive } = context.options;\n // The allowed-value list is shared by both the invalidStatus message and\n // the missingStatus suggestion, so build it once up front.\n const allowed = [...values, ...prefixValues.map((p) => `${p} ...`)];\n\n const meta = context.metadata;\n if (!meta || typeof meta.status !== 'string') {\n context.report({ messageId: 'missingStatus', data: { allowed } });\n return;\n }\n\n const status = meta.status;\n const compareStatus = caseSensitive ? status : status.toLowerCase();\n const compareValues = caseSensitive\n ? values\n : values.map((v) => v.toLowerCase());\n const comparePrefixes = caseSensitive\n ? prefixValues\n : prefixValues.map((p) => p.toLowerCase());\n\n const exactMatch = compareValues.includes(compareStatus);\n const prefixMatch = comparePrefixes.some((p) =>\n compareStatus.startsWith(p),\n );\n\n if (!exactMatch && !prefixMatch) {\n // loc only exists for v2 list-sourced values: frontmatter is stripped\n // before mdast parsing, so a frontmatter-sourced status has no body\n // line to point at — inline suppression directives (which live in the\n // body) can only silence it file-wide, never per line.\n const loc = context.metadataLoc?.status;\n context.report({\n messageId: 'invalidStatus',\n ...(loc ? { loc } : {}),\n data: { status, allowed },\n });\n }\n },\n};\n\nexport default rule;\n","import { basename } from 'node:path';\nimport type { ProjectFile, ProjectRule } from '../../core/types.js';\nimport schema from './schema.json' with { type: 'json' };\n\ninterface SupersedesBidirectionalOptions extends Record<string, unknown> {\n // No options at v0.1.\n}\n\nconst ADR_NUMBER_REGEX = /^(\\d{4})-/;\nconst FORWARD_FIELD = 'supersedes';\nconst BACKWARD_FIELD = 'superseded-by';\n\nfunction extractAdrNumber(path: string): string | null {\n const match = ADR_NUMBER_REGEX.exec(basename(path));\n return match?.[1] ?? null;\n}\n\nfunction normalizeRefs(value: unknown): string[] {\n if (typeof value === 'string') return [value];\n if (Array.isArray(value)) {\n return value.filter((v): v is string => typeof v === 'string');\n }\n return [];\n}\n\nconst rule: ProjectRule<SupersedesBidirectionalOptions> = {\n meta: {\n name: 'madr/supersedes-bidirectional',\n type: 'project',\n versionCompat: ['v3', 'v4'],\n docs: {\n description:\n 'Frontmatter `supersedes` and `superseded-by` must reference each other bidirectionally',\n url: 'https://knktkc.github.io/madr-lint/rules/supersedes-bidirectional/',\n recommended: true,\n },\n messages: {\n unknownReference:\n 'Frontmatter `{{direction}}: {{ref}}` references an ADR that does not exist',\n // `declared` is the field the SOURCE file actually declares;\n // `direction` is the field THIS file (the diagnostic's path) must add.\n // They are opposites — rendering `direction` as the declared field\n // would mislabel the source's frontmatter in both directions.\n missingBackReference:\n '`{{source}}` declares `{{declared}}: {{ref}}`, but `{{ref}}` (this file) does not back-reference it via `{{direction}}: {{expected}}`',\n },\n suggestions: {\n unknownReference:\n 'correct \"{{ref}}\" to an existing ADR number, or remove \"{{direction}}: {{ref}}\" from the frontmatter',\n missingBackReference:\n 'add \"{{direction}}: {{expected}}\" to the frontmatter of this file',\n },\n defaultOptions: {},\n schema,\n },\n check(context) {\n // Build ADR-NNNN → file index. Files without a NNNN- prefix are\n // not addressable via `supersedes`/`superseded-by` and thus skipped.\n const adrIndex = new Map<string, ProjectFile>();\n for (const file of context.files) {\n const num = extractAdrNumber(file.path);\n if (num) adrIndex.set(`ADR-${num}`, file);\n }\n\n // Walk every file with a frontmatter and check both directions.\n for (const file of context.files) {\n const fm = file.frontmatter;\n if (!fm) continue;\n const fileNumber = extractAdrNumber(file.path);\n if (!fileNumber) continue;\n const fileRef = `ADR-${fileNumber}`;\n\n const forwardRefs = normalizeRefs(fm[FORWARD_FIELD]);\n const backwardRefs = normalizeRefs(fm[BACKWARD_FIELD]);\n\n // Forward direction: this file `supersedes` something — verify\n // the target back-references this file via `superseded-by`.\n for (const ref of forwardRefs) {\n const target = adrIndex.get(ref);\n if (!target) {\n context.report({\n messageId: 'unknownReference',\n path: file.path,\n data: { ref, direction: FORWARD_FIELD },\n });\n continue;\n }\n const targetBack = normalizeRefs(target.frontmatter?.[BACKWARD_FIELD]);\n if (!targetBack.includes(fileRef)) {\n context.report({\n messageId: 'missingBackReference',\n path: target.path,\n data: {\n ref,\n source: file.path,\n declared: FORWARD_FIELD,\n direction: BACKWARD_FIELD,\n expected: fileRef,\n },\n });\n }\n }\n\n // Backward direction: this file is `superseded-by` something —\n // verify the target forward-references this file via `supersedes`.\n for (const ref of backwardRefs) {\n const target = adrIndex.get(ref);\n if (!target) {\n context.report({\n messageId: 'unknownReference',\n path: file.path,\n data: { ref, direction: BACKWARD_FIELD },\n });\n continue;\n }\n const targetFwd = normalizeRefs(target.frontmatter?.[FORWARD_FIELD]);\n if (!targetFwd.includes(fileRef)) {\n context.report({\n messageId: 'missingBackReference',\n path: target.path,\n data: {\n ref,\n source: file.path,\n declared: BACKWARD_FIELD,\n direction: FORWARD_FIELD,\n expected: fileRef,\n },\n });\n }\n }\n }\n },\n};\n\nexport default rule;\n","{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {}\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,cAAAA,aAAY,gBAAAC,qBAAoB;AACzC,SAAS,YAAAC,WAAU,WAAAC,UAAS,OAAAC,YAAW;AACvC,SAAS,eAAe,eAAe;;;ACQvC,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,SAAS,YAAY;;;ACmBvB,IAAM,2BAA2B;AAsNjC,SAAS,cAAcC,OAAoC;AAChE,SAAO,WAAWA;AACpB;;;ADvOO,IAAM,mBAAmB;AAGzB,IAAM,wBAAwB;AAoB9B,SAAS,aAAa,KAAqB;AAChD,SAAO,KAAK,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,KAAK,CAAC;AACvC,cAAQ,KAAK,CAAC;AAAA,IAChB;AAEA,UAAM,cAAc,IAAI;AAAA,MACtB,cAAc,IAAI,CAAC,MAAM,CAAC,EAAE,KAAK,MAAM,CAAC,CAAC;AAAA,IAC3C;AACA,UAAM,SAAU,KAAK,UAAU;AAC/B,UAAM,WAAW,UAAU,MAAM;AACjC,QAAI,CAAC,UAAU;AACb,cAAQ;AAAA,QACN,qBAAqB,MAAM,iBAAiB,OAAO,KAAK,SAAS,EAAE,KAAK,IAAI,CAAC;AAAA,MAC/E;AACA,cAAQ,KAAK,CAAC;AAAA,IAChB;AAIA,UAAM,iBAAiB,OAAO;AAC9B,UAAM,eAAe,eAAe,OAAO,CAAC,MAAM,EAAE,aAAa,MAAM,EAAE;AACzE,UAAM,aAAa,eAAe,OAAO,CAAC,MAAM,EAAE,aAAa,OAAO,EAAE;AACxE,UAAM,mBAAmB,eAAe,KAAK,eAAe;AAO5D,UAAM,WAAW,KAAK,QAClB,eAAe,OAAO,CAAC,MAAM,EAAE,aAAa,MAAM,IAClD;AAKJ,UAAM,mBACJ,WAAW,UAAU,SAAS,WAAW,KAAK;AAChD,QAAI,CAAC,kBAAkB;AACrB,cAAQ;AAAA,QACN,SAAS,OAAO,UAAU,aAAa;AAAA,UACrC,gBAAgB,OAAO;AAAA,QACzB,CAAC;AAAA,MACH;AAAA,IACF;AAIA,QAAI,WAAW,UAAU,OAAO,iBAAiB,GAAG;AAClD,cAAQ,IAAI,sBAAsB,OAAO,cAAc,CAAC;AAAA,IAC1D;AAIA,QAAI,kBAAkB;AACpB,cAAQ;AAAA,QACN,cAAc,YAAY,6CAA6C,WAAW;AAAA,MACpF;AAAA,IACF;AAEA,YAAQ,KAAK,aAAa,KAAK,mBAAmB,IAAI,CAAC;AAAA,EACzD;AACF,CAAC;AAED,MAAM,QAAQ,IAAI;","names":["existsSync","readFileSync","relative","resolve","sep","rule","rule","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","join","existsSync","readFileSync","readFileSync","existsSync","existsSync","join","readFileSync","statSync","resolve","sep","rule","rule","readFileSync","rule","resolve","statSync","rule","basename","schema_default","rule","schema_default","basename","dirname","schema_default","rule","schema_default","dirname","basename","schema_default","rule","schema_default","basename","basename","schema_default","NUMBER_REGEX","rule","schema_default","basename","toString","schema_default","rule","schema_default","toString","schema_default","rule","schema_default","basename","schema_default","basename","rule","schema_default","toPosix","sep","readFileSync","resolve","relative","existsSync"]}
|