/** * Explainer freshness audit (`check-explainers` subcommand). * * Explainers are hand-authored markdown documents (usually generated by the * `explain-change` skill) whose frontmatter carries a machine-readable * `explainer` block citing the scenarios they explain, with per-scenario * content hashes stamped at generation time. This module walks a directory of * explainers, validates each block against the explainer-v1 JSON Schema, and * checks every cited scenario against the current run: * * fresh — every cited scenario exists with matching content * stale — a cited scenario changed, was renamed, or disappeared * * Generation of explainers is deliberately NOT here: that is an agent-side * concern (a skill). This pipeline only renders and audits — same rule as the * rest of the formatter. */ import * as fs from "node:fs"; import * as path from "node:path"; import Ajv from "ajv/dist/2020.js"; import { parse as parseYaml } from "yaml"; import { checkExplainerRef, explainerRefFromFrontmatter, type ExplainerCheck, type ExplainerRef, } from "executable-stories-core/explainer"; import { toStoryReport } from "executable-stories-core/converters/story-report"; import type { TestRunResult } from "executable-stories-core/types/test-result"; import explainerSchema from "../schemas/explainer-v1.json" with { type: "json" }; import { collectMarkdownFiles } from "./utils/markdown-files"; const ajv = new Ajv({ allErrors: true }); const validateExplainer = ajv.compile(explainerSchema); export interface ExplainerDocResult { /** Path relative to the scanned directory. */ file: string; /** Audit outcome; `invalid` means the block failed schema validation. */ status: "fresh" | "stale" | "invalid"; check?: ExplainerCheck; explainer?: ExplainerRef; errors: string[]; } export interface ExplainersReport { dir: string; runId: string; summary: { total: number; fresh: number; stale: number; invalid: number }; explainers: ExplainerDocResult[]; } /** * Extract the YAML frontmatter block from a markdown document. Distinguishes * "no frontmatter" (undefined) from "frontmatter that fails to parse" * (`error` + the raw block) — a broken explainer must report invalid, not * silently pass CI as a plain document. */ export function extractFrontmatter( markdown: string, ): { value?: unknown; raw: string; error?: string } | undefined { const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown); if (!match) return undefined; try { return { value: parseYaml(match[1]), raw: match[1] }; } catch (err) { return { raw: match[1], error: err instanceof Error ? err.message : String(err) }; } } /** * Parse + validate one explainer document. Returns nothing when the document * has no `explainer` frontmatter block (a plain doc, not an explainer). */ export function parseExplainerDoc( markdown: string, ): { explainer?: ExplainerRef; errors: string[] } | undefined { const frontmatter = extractFrontmatter(markdown); if (!frontmatter) return undefined; if (frontmatter.error !== undefined) { // Unparseable YAML: if the raw block mentions an explainer key, this IS a // broken explainer and must be reported; otherwise it's someone else's // broken doc, not ours to police. if (/^explainer\s*:/m.test(frontmatter.raw)) { return { errors: [`frontmatter: YAML parse failed: ${frontmatter.error}`] }; } return undefined; } if (typeof frontmatter.value !== "object" || frontmatter.value === null) return undefined; const block = (frontmatter.value as Record).explainer; if (block === undefined || block === null) return undefined; if (!validateExplainer(block)) { const errors = (validateExplainer.errors ?? []).map( (err) => `explainer${err.instancePath || ""}: ${err.message ?? "invalid"}`, ); return { errors }; } const explainer = explainerRefFromFrontmatter(block); if (!explainer) { // Unreachable while the schema and the coercion agree (a sync test pins // the hash regex); reaching it means they drifted. return { errors: ["explainer: internal — the schema accepted a block the core coercion rejected"], }; } return { explainer, errors: [] }; } /** Audit every explainer under `dir` against the run. */ export function buildExplainersReport( args: { run: TestRunResult; dir: string }, _deps: Record = {}, ): ExplainersReport { const report = toStoryReport(args.run); const scenarios = report.features.flatMap((feature) => feature.scenarios); const explainers: ExplainerDocResult[] = []; for (const file of collectMarkdownFiles(args.dir).sort()) { const parsed = parseExplainerDoc(fs.readFileSync(file, "utf8")); if (!parsed) continue; // plain doc, not an explainer const rel = path.relative(args.dir, file); if (!parsed.explainer) { explainers.push({ file: rel, status: "invalid", errors: parsed.errors }); continue; } const check = checkExplainerRef(parsed.explainer, scenarios); explainers.push({ file: rel, status: check.status, check, explainer: parsed.explainer, errors: [], }); } return { dir: args.dir, runId: report.runId, summary: { total: explainers.length, fresh: explainers.filter((e) => e.status === "fresh").length, stale: explainers.filter((e) => e.status === "stale").length, invalid: explainers.filter((e) => e.status === "invalid").length, }, explainers, }; } /** True when CI should fail: anything stale or invalid. */ export function explainersGateFailed(report: ExplainersReport): boolean { return report.summary.stale > 0 || report.summary.invalid > 0; } export function renderExplainersReport( report: ExplainersReport, format: "text" | "json", ): string { if (format === "json") return JSON.stringify(report, null, 2); const lines: string[] = []; const { summary } = report; lines.push( `Explainers: ${summary.total} checked — ${summary.fresh} fresh, ${summary.stale} stale, ${summary.invalid} invalid`, ); for (const doc of report.explainers) { if (doc.status === "fresh") { lines.push(` ✓ ${doc.file}`); continue; } if (doc.status === "invalid") { lines.push(` ✗ ${doc.file} (invalid frontmatter)`); for (const err of doc.errors) lines.push(` ${err}`); continue; } lines.push(` ✗ ${doc.file} (stale)`); for (const s of doc.check?.scenarios ?? []) { if (s.status === "ok") continue; const label = s.ref.title ?? s.ref.id; switch (s.status) { case "changed": { // A title-only match means the id moved too — say so, or the reader // fixes the hash and misses the stale id in their frontmatter. const idMoved = s.matchedId && s.matchedId !== s.ref.id ? `, id ${s.ref.id} → ${s.matchedId}` : ""; lines.push(` changed: "${label}" (hash ${s.ref.hash} → ${s.currentHash}${idMoved})`); break; } case "renamed": lines.push(` renamed: "${label}" (id ${s.ref.id} → ${s.matchedId})`); break; case "missing": lines.push(` missing: "${label}" (no scenario by id or title)`); break; } } } return lines.join("\n"); }