Merge current master into reviewed Speko UI

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* origin/master:
  refactor(maps): generate indexes from local story and feature metadata (#16214)

# Conflicts:
#	maps/storybook-map/INDEX.md
#	maps/storybook-map/REVIEW.md
#	maps/storybook-map/catalog.json
#	ui/storybook/generated/feature-index.json
#	ui/storybook/stories/teams/team-catalog.stories.tsx
This commit is contained in:
Dotta committed 2026-10-13 15:34:04 -05:00
commit 249cbc616a
381 files changed
+4046 -11608

No files matched your search

+3 -7
View File
@@ -2,6 +2,7 @@
import { existsSync, readFileSync, readdirSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { featureIndex } from "./feature-map.mjs";
const scriptPath = fileURLToPath(import.meta.url);
const defaultRoot = path.resolve(path.dirname(scriptPath), "..");
@@ -83,7 +84,8 @@ export function checkMaps(repoRoot = defaultRoot) {
const productFiles = files(featureRoot);
const agentFiles = files(agentRoot);
const indexes = [read(path.join(featureRoot, "README.md")), read(path.join(agentRoot, "README.md"))];
try { featureIndex(repoRoot); }
catch (error) { errors.push(error.message); }
let capabilities = 0;
for (const name of new Set([...productFiles, ...agentFiles])) {
const productFile = path.join(featureRoot, name);
@@ -109,12 +111,6 @@ export function checkMaps(repoRoot = defaultRoot) {
}
if (!agent.includes(`](../feature-map/${name})`)) fail(agentFile, "missing matching product link");
if (!product.includes(`](../agent-access-map/${name})`)) fail(productFile, "missing matching companion link");
for (const [index, text] of indexes.entries()) {
if (!new RegExp(`\\]\\((?:\\./)?${name.replaceAll(".", "\\.")}\\)`).test(text)) {
fail(path.join(index === 0 ? featureRoot : agentRoot, "README.md"), `missing area: ${name}`);
}
}
if (!/^Review date: \d{4}-\d{2}-\d{2}\. Source commit: `[a-f\d]{40}`\./m.test(agent)) fail(agentFile, "missing review date/source commit");
links(productFile, product);
links(agentFile, agent);
capabilities += ids.length;
+1 -1
View File
@@ -21,7 +21,7 @@ function fixture(t) {
const agent = path.join(root, "maps/agent-access-map/example.md");
writeFileSync(path.join(root, "maps/README.md"), "# Contract\n");
for (const dir of ["feature-map", "agent-access-map"]) writeFileSync(path.join(root, "maps", dir, "README.md"), "[Example](example.md)\n");
writeFileSync(product, "# Example\n\n[Agent access](../agent-access-map/example.md)\n\n## Sub-features\n\n- `create`: create a record.\n\n## How to get to it (user POV)\n");
writeFileSync(product, '---\nnavigation: {"section":"Work","sectionOrder":10,"order":10}\n---\n# Example\n\nExample workflows.\n\n[Agent access](../agent-access-map/example.md)\n\n## Sub-features\n\n- `create`: create a record.\n\n## How to get to it (user POV)\n');
writeFileSync(agent, `# Agent access\n\nProduct map: [Example](../feature-map/example.md).\n\nReview date: 2026-10-12. Source commit: \`${"a".repeat(40)}\`.\n\n## \`create\`\n\nReview: \`baseline\`.\n\n${record}`);
return { root, product, agent };
}
+98
View File
@@ -0,0 +1,98 @@
import { existsSync, readFileSync, readdirSync } from "node:fs";
import path from "node:path";
export const sidebarLabel = title => title.replaceAll("/", ", ");
export function featureIndex(root) {
const directory = path.join(root, "maps/feature-map");
const sections = new Map();
for (const file of readdirSync(directory).filter(file => file.endsWith(".md") && file !== "README.md").sort()) {
const id = file.slice(0, -3);
const source = readFileSync(path.join(directory, file), "utf8");
const frontmatter = source.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/);
const navigationLine = frontmatter?.[1].match(/^navigation: (.+)$/m)?.[1];
if (!navigationLine) throw new Error(`${file}: missing navigation metadata`);
const navigation = JSON.parse(navigationLine);
if (typeof navigation.section !== "string" || !navigation.section.trim()
|| !Number.isFinite(navigation.sectionOrder) || !Number.isFinite(navigation.order)) {
throw new Error(`${file}: invalid navigation metadata`);
}
const text = source.slice(frontmatter[0].length);
const title = text.match(/^# (.+)$/m)?.[1];
const description = text.split(/^# .+\r?\n/m)[1]?.trim().split(/\r?\n\s*\r?\n/)[0].replaceAll(/\r?\n/g, " ");
if (!title || !description) throw new Error(`${file}: missing title or description`);
const body = text.split(/^## Sub-features\s*$/m)[1]?.split(/^## /m)[0];
if (!body) throw new Error(`${file}: missing sub-features`);
const capabilities = [];
for (const row of body.trim().split(/\r?\n/)) {
const match = row.match(/^- `([^`]+)`:\s*(.*)$/);
if (match) {
const [, key, description] = match;
capabilities.push({ id: `${id}/${key}`, label: key.replaceAll("-", " ").replace(/^./, letter => letter.toUpperCase()), description });
} else if (row.trim() && capabilities.length) capabilities.at(-1).description += ` ${row.trim()}`;
}
if (!capabilities.length || capabilities.some(capability => !/^[a-z0-9-]+\/[a-z0-9-]+$/.test(capability.id))
|| new Set(capabilities.map(capability => capability.id)).size !== capabilities.length) {
throw new Error(`${file}: invalid or duplicate capability IDs`);
}
const verification = text.split(/^### Storybook verification\s*$/m)[1]?.split(/^### /m)[0] ?? "";
const seen = new Set();
for (const entry of verification.split(/^#### /m).slice(1)) {
const key = entry.match(/^`([^`]+)`/)?.[1];
const capability = capabilities.find(capability => capability.id === `${id}/${key}`);
if (!capability || seen.has(key)) throw new Error(`${file}: unknown or duplicate verification capability ${key}`);
seen.add(key);
const fields = Object.fromEntries(["Scope", "Storybook", "Production", "Sources"].map(field => [field.toLowerCase(), entry.match(new RegExp(`^${field}: (.+)$`, "m"))?.[1]]));
if (!["ui", "cli", "browser"].includes(fields.scope) || Object.values(fields).some(value => !value?.trim())) {
throw new Error(`${file}: incomplete verification route for ${key}`);
}
capability.verification = fields;
}
let section = sections.get(navigation.section);
if (!section) {
section = { title: navigation.section, order: navigation.sectionOrder, features: [] };
sections.set(section.title, section);
}
if (section.order !== navigation.sectionOrder) throw new Error(`${file}: inconsistent section order for ${section.title}`);
section.features.push({ id, title, description, capabilities, order: navigation.order });
}
if (!sections.size) throw new Error("Feature map has no feature families");
const ordered = [...sections.values()].sort((a, b) => a.order - b.order || a.title.localeCompare(b.title));
return { sections: ordered.map(({ title, features }) => ({ title, features: features.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id)).map(({ order, ...feature }) => feature) })) };
}
export function mapIndexes(index) {
const features = ["# Product features", "", "Generated from the feature recipes. Edit the affected recipe, not this index.", ""];
const access = ["# Agent access by feature", "", "Generated from the feature recipes and their access companions. Counts are documentation scope, not passing tests.", ""];
for (const section of index.sections) {
for (const lines of [features, access]) lines.push(`## ${section.title}`, "");
for (const feature of section.features) {
features.push(`- [${feature.title}](../feature-map/${feature.id}.md): ${feature.description}`);
access.push(`- [${feature.title}](../agent-access-map/${feature.id}.md) · [Product recipe](../feature-map/${feature.id}.md) · ${feature.capabilities.length} capabilities`);
}
for (const lines of [features, access]) lines.push("");
}
return new Map([["maps/generated/feature-map.md", features.join("\n")], ["maps/generated/agent-access-map.md", access.join("\n")]]);
}
export function pageInventory(root, index) {
const references = new Map();
for (const feature of index.sections.flatMap(section => section.features)) {
const recipe = `maps/feature-map/${feature.id}.md`;
for (const match of readFileSync(path.join(root, recipe), "utf8").matchAll(/\]\(([^)\n]+)\)/g)) {
const target = path.resolve(root, path.dirname(recipe), match[1].split("#")[0]);
if (!references.has(target)) references.set(target, new Set());
references.get(target).add(feature.id);
}
}
function pages(directory) {
if (!existsSync(directory)) return [];
return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
const file = path.join(directory, entry.name);
if (entry.isDirectory()) return pages(file);
if (!entry.name.endsWith(".tsx") || /\.(test|spec|stories)\.tsx$/.test(entry.name)) return [];
return [{ file: path.relative(root, file).split(path.sep).join("/"), features: [...(references.get(file) ?? [])].sort() }];
});
}
return { pages: pages(path.join(root, "ui/src/pages")).sort((a, b) => a.file.localeCompare(b.file)) };
}
+34
View File
@@ -0,0 +1,34 @@
import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
export function mapFixture(t) {
const root = mkdtempSync(path.join(os.tmpdir(), "paperclip-map-test-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
function write(file, content) {
mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
writeFileSync(path.join(root, file), content);
}
write("ui/package.json", '{"type":"module"}\n');
symlinkSync(fileURLToPath(new URL("../ui/node_modules", import.meta.url)), path.join(root, "ui/node_modules"), "junction");
write(".gitignore", "node_modules/\nmaps/generated/\nui/storybook/generated/\nui/storybook/.storybook/preview.tsx\n");
write("maps/README.md", "# Maps\n");
write("maps/feature-map/README.md", "# Feature recipes\n");
write("maps/agent-access-map/README.md", "# Access contracts\n");
write("ui/storybook/.storybook/preview-base.tsx", "export default { parameters: { layout: 'fullscreen' } };\n");
function feature(id, title, capabilities = ["create"], options = {}) {
const { section = "Work", sectionOrder = 10, order = 10 } = options;
write(`maps/feature-map/${id}.md`, `---\nnavigation: ${JSON.stringify({ section, sectionOrder, order })}\n---\n\n# ${title}\n\n${title} workflows.\n\n[Agent access](../agent-access-map/${id}.md)\n\n## Sub-features\n\n${capabilities.map(key => `- \`${key}\`: ${key} work.`).join("\n")}\n\n## Gotchas\n`);
write(`maps/agent-access-map/${id}.md`, `# ${title} access\n\n[Product map](../feature-map/${id}.md)\n\n${capabilities.map(key => `## \`${key}\`\n\nReview: \`baseline\`.\n\nAPI: \`present\` — POST /api/${id}.\nAgent access: \`available\` — REST.\nPolicy: same company.\nEvidence: \`source-only\` — inspect implementation.\nVerification: \`not-run\` — assert access and denial.\nGaps: remaining variants.\n`).join("\n")}`);
}
function story(name = "task", metadata = { capabilities: ["tasks/create"], implementation: "production", boundary: "fixtures" }, options = {}) {
const { area = "tasks", title = `Work/Tasks/${name}`, id = `stable-${name}`, exports = "export const Empty = {};", parameters = "" } = options;
const file = `ui/storybook/stories/${area}/${name}.stories.tsx`;
write(file, `import type { Meta } from '@storybook/react-vite';\nconst meta = { id: ${JSON.stringify(id)}, title: ${JSON.stringify(title)}, parameters: { ${parameters} paperclip: ${JSON.stringify(metadata)} } } satisfies Meta;\nexport default meta;\n${exports}\n`);
return file;
}
feature("tasks", "Tasks", ["create", "discussion"]);
const file = story();
return { root, write, feature, story, file };
}
+6
View File
@@ -0,0 +1,6 @@
export type StorySource = { file: string; title: string; metaId: string; ids: string[]; plays: number };
export function generateStorybook(root?: string, options?: { write?: boolean }): {
catalog: { version: number; entries: Array<{ file: string; stableId: string }> };
stories: StorySource[];
};
export function scanStories(root?: string): StorySource[];
+103 -75
View File
@@ -1,19 +1,19 @@
#!/usr/bin/env node
import { createHash } from "node:crypto";
import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { readFileSync, readdirSync } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { featureIndex, reconcileFeatureArtifacts, sidebarLabel } from "./storybook-feature-index.mjs";
import { featureIndex, sidebarLabel } from "./feature-map.mjs";
import { generateFeatureArtifacts, generatedRoot, writeArtifacts } from "./storybook-feature-index.mjs";
import { checkMaps } from "./check-maps.mjs";
const scriptPath = fileURLToPath(import.meta.url);
const defaultRoot = path.resolve(path.dirname(scriptPath), "..");
const storyRoot = "ui/storybook/stories";
const catalogPath = "maps/storybook-map/catalog.json";
const indexPath = "maps/storybook-map/INDEX.md";
const statuses = ["current", "proposed", "historical", "mixed", "unreviewed"];
const implementations = ["production", "prototype", "mixed", "guide"];
const boundaries = ["fixtures", "fixture-server", "static"];
const implementations = ["production", "prototype", "mixed", "guide", "unreviewed"];
const boundaries = ["fixtures", "fixture-server", "static", "unreviewed"];
const annotationFields = new Set(["capabilities", "status", "implementation", "boundary", "notes", "home", "exception", "replacement"]);
function files(root, dir) {
return readdirSync(path.join(root, dir), { withFileTypes: true }).flatMap(entry => {
@@ -22,27 +22,39 @@ function files(root, dir) {
}).sort();
}
export function fingerprint(root, sources) {
const hash = createHash("sha256");
for (const file of [...new Set(sources)].sort()) {
hash.update(file).update("\0").update(readFileSync(path.join(root, file))).update("\0");
function literal(node, label) {
if (!node) throw new Error(`${label}: expected literal metadata`);
if (["TSAsExpression", "TSSatisfiesExpression"].includes(node.type)) return literal(node.expression, label);
if (["StringLiteral", "BooleanLiteral", "NumericLiteral"].includes(node.type)) return node.value;
if (node.type === "ArrayExpression") return node.elements.map(element => literal(element, label));
if (node.type === "ObjectExpression") {
const result = {};
for (const property of node.properties) {
const key = property.key?.name ?? property.key?.value;
if (property.type !== "ObjectProperty" || property.computed || typeof key !== "string" || Object.hasOwn(result, key) || key === "__proto__") {
throw new Error(`${label}: metadata must use unique literal properties`);
}
result[key] = literal(property.value, label);
}
return result;
}
return hash.digest("hex");
throw new Error(`${label}: metadata must be literal; expressions are not executed`);
}
export function capabilities(root) {
const result = new Map();
for (const file of files(root, "maps/feature-map").filter(file => file.endsWith(".md") && !file.endsWith("README.md"))) {
const text = readFileSync(path.join(root, file), "utf8");
const area = path.basename(file, ".md");
const section = text.split(/^## Sub-features\s*$/m)[1]?.split(/^## /m)[0] ?? "";
for (const match of section.matchAll(/^- `([^`]+)`:/gm)) result.set(`${area}/${match[1]}`, file);
function annotation(csf, file) {
const parameters = csf._metaAnnotations.parameters;
if (parameters?.type !== "ObjectExpression") throw new Error(`${file}: declare parameters.paperclip as literal metadata`);
const matches = parameters.properties.filter(property => (property.key?.name ?? property.key?.value) === "paperclip");
if (matches.length !== 1) throw new Error(`${file}: expected one parameters.paperclip annotation`);
const property = matches[0];
if (property.type !== "ObjectProperty" || property.computed) throw new Error(`${file}: paperclip must be a literal property`);
if (parameters.properties.slice(parameters.properties.indexOf(property) + 1).some(property => property.type === "SpreadElement" || property.computed)) {
throw new Error(`${file}: paperclip metadata must follow parameter spreads and computed properties`);
}
return result;
}
export function featureNavigation(root) {
return new Map(featureIndex(root).sections.flatMap(section => section.features.map(feature => [feature.id, `${sidebarLabel(section.title)}/${sidebarLabel(feature.title)}`])));
const value = literal(property.value, file);
if (!value || Array.isArray(value) || typeof value !== "object") throw new Error(`${file}: paperclip metadata must be an object`);
for (const key of Object.keys(value)) if (!annotationFields.has(key)) throw new Error(`${file}: unknown paperclip field ${key}`);
return value;
}
export function scanStories(root = defaultRoot) {
@@ -50,60 +62,53 @@ export function scanStories(root = defaultRoot) {
const { loadCsf } = require("storybook/internal/csf-tools");
return files(root, storyRoot).filter(file => /\.stories\.(ts|tsx|mdx)$/.test(file)).map(file => {
const csf = loadCsf(readFileSync(path.join(root, file), "utf8"), { fileName: file, makeTitle: title => title }).parse();
return { file, title: csf.meta.title, metaId: csf.meta.id, ids: csf.stories.map(story => story.id), plays: csf.stories.filter(story => story.__stats?.play).length };
return { file, title: csf.meta.title, metaId: csf.meta.id, ids: csf.stories.map(story => story.id), plays: csf.stories.filter(story => story.__stats?.play).length, annotation: annotation(csf, file) };
});
}
function storyHome(entry) {
return entry.home ?? entry.capabilities[0]?.split("/")[0] ?? (entry.implementation === "guide" ? "overview" : "foundations");
export function storyHome(entry) {
return entry.home ?? (typeof entry.capabilities?.[0] === "string" ? entry.capabilities[0].split("/")[0] : undefined) ?? (entry.implementation === "guide" ? "overview" : "foundations");
}
export function validateCatalog(root, catalog, stories) {
export function catalogFromStories(stories, index) {
const navigation = new Map(index.sections.flatMap(section => section.features.map(feature => [feature.id, `${sidebarLabel(section.title)}/${sidebarLabel(feature.title)}`])));
return { version: 2, entries: stories.map(story => {
const entry = { status: "unreviewed", implementation: "unreviewed", boundary: "unreviewed", notes: "", ...story.annotation, file: story.file, stableId: story.metaId, sidebarTitle: story.title };
const prefix = navigation.get(storyHome(entry)) ?? ({ overview: "Overview", foundations: "Foundations" })[storyHome(entry)];
return { ...entry, purpose: story.title?.startsWith(`${prefix}/`) ? story.title.slice(prefix.length + 1) : story.title };
}) };
}
export function validateCatalog(catalog, stories, index) {
const errors = [];
const refs = capabilities(root);
const navigation = featureNavigation(root);
const refs = new Set(index.sections.flatMap(section => section.features.flatMap(feature => feature.capabilities.map(capability => capability.id))));
const navigation = new Map(index.sections.flatMap(section => section.features.map(feature => [feature.id, `${sidebarLabel(section.title)}/${sidebarLabel(feature.title)}`])));
const byFile = new Map(stories.map(story => [story.file, story]));
const seen = new Set();
const local = file => typeof file === "string" && !path.isAbsolute(file) && !file.split("/").includes("..") && existsSync(path.join(root, file));
if (catalog.version !== 1 || !Array.isArray(catalog.entries)) return ["Unsupported catalog version or missing entries"];
function review(label, sources, hash) {
if (!Array.isArray(sources) || !sources.length || sources.some(file => !local(file))) {
errors.push(`${label}: missing/invalid review sources`);
} else if (fingerprint(root, sources) !== hash) errors.push(`${label}: source changed; review before updating its fingerprint`);
}
review("Shared Storybook setup", catalog.sharedReview?.sources, catalog.sharedReview?.fingerprint);
for (const entry of catalog.entries) {
const label = entry.file;
if (seen.has(label)) errors.push(`${label}: duplicate catalog entry`);
seen.add(label);
if (!byFile.has(label)) errors.push(`${label}: missing story file`);
if (!statuses.includes(entry.status)) errors.push(`${label}: invalid product status`);
if (!implementations.includes(entry.implementation)) errors.push(`${label}: invalid implementation`);
if (!boundaries.includes(entry.boundary)) errors.push(`${label}: invalid data boundary`);
if (!entry.purpose?.trim() || !entry.notes?.trim()) errors.push(`${label}: purpose and review notes are required`);
if (!/^\d{4}-\d{2}-\d{2}$/.test(entry.reviewedAt ?? "")) errors.push(`${label}: missing review date`);
if (!Array.isArray(entry.capabilities)) { errors.push(`${label}: missing capabilities`); continue; }
if (typeof entry.notes !== "string") errors.push(`${label}: notes must be text`);
if (!Array.isArray(entry.capabilities) || entry.capabilities.some(ref => typeof ref !== "string")) { errors.push(`${label}: capabilities must be an array of IDs`); continue; }
if (entry.home !== undefined && entry.home !== "foundations") errors.push(`${label}: only shared foundations may override the capability home`);
if (entry.home === "foundations" && !entry.exception?.trim()) errors.push(`${label}: foundation home needs an explicit reason`);
if (entry.exception !== undefined && (typeof entry.exception !== "string" || !entry.exception.trim())) errors.push(`${label}: exception must be nonempty text`);
if (entry.home === "foundations" && !entry.exception) errors.push(`${label}: foundation home needs an explicit reason`);
for (const ref of entry.capabilities) if (!refs.has(ref)) errors.push(`${label}: unknown feature capability ${ref}`);
if (!entry.capabilities.length && !entry.exception?.trim()) errors.push(`${label}: unmapped story needs an explicit reason`);
if (!entry.capabilities.length && !entry.exception) errors.push(`${label}: unmapped story needs an explicit reason`);
if (entry.capabilities.length !== new Set(entry.capabilities).size) errors.push(`${label}: duplicate capability references`);
const area = storyHome(entry);
const prefix = navigation.get(area) ?? ({ overview: "Overview", foundations: "Foundations" })[area];
const story = byFile.get(label);
if (!label.startsWith(`${storyRoot}/${area}/`)) errors.push(`${label}: story must live in its primary feature folder ${area}`);
if (!prefix || !entry.sidebarTitle?.startsWith(`${prefix}/`) || story?.title !== entry.sidebarTitle) errors.push(`${label}: sidebar title must match its feature-map home`);
if (!entry.stableId || story?.metaId !== entry.stableId) errors.push(`${label}: explicit meta ID must preserve the catalog stableId`);
if (entry.replacement && !byFile.has(entry.replacement)) errors.push(`${label}: replacement story is missing`);
if (!entry.sources?.includes(label)) errors.push(`${label}: review must include its story source`);
review(label, entry.sources, entry.fingerprint);
if (!prefix || typeof entry.sidebarTitle !== "string" || !entry.sidebarTitle.startsWith(`${prefix}/`)) errors.push(`${label}: sidebar title must match its feature-map home`);
if (typeof entry.stableId !== "string" || !entry.stableId.trim()) errors.push(`${label}: explicit meta ID is required`);
if (entry.replacement !== undefined && !byFile.has(entry.replacement)) errors.push(`${label}: replacement story is missing`);
}
for (const story of stories) if (!seen.has(story.file)) errors.push(`${story.file}: story missing from catalog`);
const ids = [...stories.flatMap(story => story.ids), ...featureIndex(root).sections.flatMap(section => section.features.map(feature => `feature-map-${feature.id}--overview`))];
if (ids.length !== new Set(ids).size) errors.push("Duplicate story IDs");
const metaIds = stories.map(story => story.metaId);
const ids = [...stories.flatMap(story => story.ids), ...index.sections.flatMap(section => section.features.map(feature => `feature-map-${feature.id}--overview`))];
if (metaIds.length !== new Set(metaIds).size || ids.length !== new Set(ids).size) errors.push("Duplicate story IDs");
return errors;
}
function cell(value) { return String(value).replaceAll("|", "\\|").replaceAll("\n", " "); }
export function renderIndex(catalog, stories, index) {
@@ -115,10 +120,10 @@ export function renderIndex(catalog, stories, index) {
if (!groups.has(area)) groups.set(area, []);
groups.get(area).push(entry);
}
const lines = ["# Storybook by feature", "", "<!-- Generated by node scripts/storybook-catalog.mjs --write. Edit catalog.json. -->", "",
"[Contract and maintenance](README.md) · [Review findings](REVIEW.md)", "",
const lines = ["# Storybook by feature", "", "Generated from story annotations and feature recipes. Do not edit this file.", "",
"[Contract and maintenance](../storybook-map/README.md) · [Verification routes](verification.md)", "",
`${stories.length} story files; ${stories.reduce((n, story) => n + story.ids.length, 0)} indexed stories. Counts describe inventory, not passed tests or complete feature coverage.`, "",
"Status describes product alignment; implementation describes the rendered subject; boundary describes simulated data. Sources and limitations are in catalog.json. Related capabilities cross-list one canonical story file.", ""];
"Status describes product alignment; implementation describes the rendered subject; boundary describes simulated data. Limitations are authored alongside each story. Classification is not executed evidence. Related capabilities cross-list one canonical story file.", ""];
const homes = index.sections.flatMap(section => section.features.map(feature => ({ ...feature, section: section.title })));
homes.push({ id: "foundations-and-guides", title: "Shared foundations and guides", section: "Foundations", description: "Shared components and contributor guidance outside the product feature index." });
let currentSection;
@@ -148,24 +153,47 @@ export function renderIndex(catalog, stories, index) {
return lines.join("\n") + "\n";
}
export function reconcileCatalog(root, catalog, stories, write = false) {
const index = featureIndex(root);
const errors = reconcileFeatureArtifacts(root, index, write);
errors.push(...validateCatalog(root, catalog, stories));
if (!errors.length) {
const generated = renderIndex(catalog, stories, index);
if (write) writeFileSync(path.join(root, indexPath), generated);
else if (!existsSync(path.join(root, indexPath)) || readFileSync(path.join(root, indexPath), "utf8") !== generated) errors.push("Generated INDEX.md is stale; run with --write after reviewing catalog changes");
export function renderVerification(catalog, index) {
const examples = catalog.entries.filter(entry => entry.implementation !== "guide" && !["historical", "proposed"].includes(entry.status));
const capabilities = index.sections.flatMap(section => section.features.flatMap(feature => feature.capabilities));
const missing = capabilities.filter(capability => !examples.some(entry => entry.capabilities.includes(capability.id)));
const lines = ["# Storybook verification routes", "", "Generated from story annotations and feature recipes. Associations are navigation, not proof of passing tests.", "",
`${capabilities.length} capabilities; ${missing.length} without a current, mixed or unreviewed example. Historical examples, proposals and guides do not remove gaps.`, "",
"## Capabilities without examples", ""];
for (const capability of missing) {
const area = capability.id.split("/")[0];
lines.push(`- [${capability.id}](../feature-map/${area}.md): ${capability.verification?.storybook ?? "No example associated. Inspect the feature recipe to select verification."}`);
}
return errors;
lines.push("", "## Authored verification guidance", "");
for (const capability of capabilities.filter(capability => capability.verification)) {
const route = capability.verification;
lines.push(`### ${capability.id}`, "", `Scope: ${route.scope}`, "", `Storybook: ${route.storybook}`, "", `Production: ${route.production}`, "", `Sources: ${route.sources}`, "");
}
return lines.join("\n");
}
export function generateStorybook(root = defaultRoot, { write = true } = {}) {
const mapErrors = checkMaps(root).errors;
if (mapErrors.length) throw new Error(mapErrors.join("\n"));
const index = featureIndex(root);
const stories = scanStories(root);
const catalog = catalogFromStories(stories, index);
const errors = validateCatalog(catalog, stories, index);
if (errors.length) throw new Error(errors.join("\n"));
if (write) {
generateFeatureArtifacts(root, index);
writeArtifacts(root, new Map([
[`${generatedRoot}/catalog.json`, JSON.stringify(catalog, null, 2) + "\n"],
["maps/generated/storybook.md", renderIndex(catalog, stories, index)],
["maps/generated/verification.md", renderVerification(catalog, index)],
]));
}
return { catalog, stories, index };
}
if (process.argv[1] && path.resolve(process.argv[1]) === scriptPath) {
const args = process.argv.slice(2);
if (args.some(arg => arg !== "--write")) throw new Error("Usage: node scripts/storybook-catalog.mjs [--write]");
const catalog = JSON.parse(readFileSync(path.join(defaultRoot, catalogPath), "utf8"));
const stories = scanStories();
const errors = reconcileCatalog(defaultRoot, catalog, stories, args.includes("--write"));
if (errors.length) { errors.forEach(error => console.error(error)); process.exitCode = 1; }
else console.log(`Storybook catalog aligned: ${stories.length} files, ${stories.reduce((n, story) => n + story.ids.length, 0)} stories. Structure and review fingerprints only; no runtime proof.`);
if (args.some(arg => !["--write", "--check"].includes(arg)) || args.length > 1) throw new Error("Usage: node scripts/storybook-catalog.mjs [--write | --check]");
const { stories } = generateStorybook(defaultRoot, { write: !args.includes("--check") });
console.log(`Storybook map: ${stories.length} files, ${stories.reduce((n, story) => n + story.ids.length, 0)} stories. Structure only; no runtime proof.`);
}
+134 -179
View File
@@ -1,208 +1,163 @@
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, writeFileSync, rmSync, symlinkSync } from "node:fs";
import os from "node:os";
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync, rmSync } from "node:fs";
import path from "node:path";
import { test } from "node:test";
import { fileURLToPath } from "node:url";
import { fingerprint, reconcileCatalog, renderIndex, scanStories, validateCatalog } from "./storybook-catalog.mjs";
import { featureIndex, reconcileFeatureArtifacts } from "./storybook-feature-index.mjs";
import { catalogFromStories, generateStorybook, renderVerification, scanStories, validateCatalog } from "./storybook-catalog.mjs";
import { featureIndex } from "./feature-map.mjs";
import { mapFixture } from "./map-test-fixture.mjs";
function fixture(t) {
const root = mkdtempSync(path.join(os.tmpdir(), "storybook-catalog-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
function write(file, text) {
mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
writeFileSync(path.join(root, file), text);
}
write("maps/feature-map/README.md", "# Features\n\n### Tasks and conversations\n\n| [Tasks](./tasks.md) | Tasks |\n");
write("maps/feature-map/tasks.md", "# Tasks\n\n## Sub-features\n\n- `create`: create\n- `discussion`: discuss\n\n## How to get to it\n");
write("ui/storybook/.storybook/preview.tsx", "// shared fixtures\n");
const file = "ui/storybook/stories/tasks/task.stories.tsx";
write(file, "// a story\n");
write("ui/src/Task.tsx", "// production subject\n");
const sharedSources = ["ui/storybook/.storybook/preview.tsx"];
const sources = [file, "ui/src/Task.tsx"];
const catalog = {
version: 1, sharedReview: { sources: sharedSources, fingerprint: fingerprint(root, sharedSources) },
entries: [{ file, stableId: "tasks-create", sidebarTitle: "Tasks and conversations/Tasks/Create", capabilities: ["tasks/create", "tasks/discussion"], purpose: "Create a task", status: "current",
implementation: "production", boundary: "fixtures", notes: "Production subject; callbacks simulated.",
reviewedAt: "2026-10-12", sources, fingerprint: fingerprint(root, sources) }],
};
const stories = [{ file, title: "Tasks and conversations/Tasks/Create", metaId: "tasks-create", ids: ["tasks-create--empty"], plays: 0 }];
return { root, write, file, catalog, stories };
function inspect(f) {
const index = featureIndex(f.root);
const stories = scanStories(f.root);
const catalog = catalogFromStories(stories, index);
return { catalog, stories, index, errors: validateCatalog(catalog, stories, index) };
}
test("complete inventory accepts production subjects with simulated data", t => {
const f = fixture(t);
assert.deepEqual(validateCatalog(f.root, f.catalog, f.stories), []);
test("source annotations assemble an inventory without a registry or review stamps", t => {
const f = mapFixture(t);
const result = inspect(f);
assert.deepEqual(result.errors, []);
assert.equal(result.catalog.entries[0].purpose, "task");
assert.equal(result.catalog.entries[0].status, "unreviewed");
assert.equal(result.catalog.entries[0].stableId, "stable-task");
assert.equal(Object.hasOwn(result.catalog.entries[0], "fingerprint"), false);
assert.equal(Object.hasOwn(result.catalog.entries[0], "reviewedAt"), false);
f.story("new");
assert.equal(inspect(f).catalog.entries.length, 2);
rmSync(path.join(f.root, f.file));
assert.equal(inspect(f).catalog.entries.length, 1);
});
test("adding, removing or duplicating story files requires reconciliation", t => {
const f = fixture(t);
assert.match(validateCatalog(f.root, { ...f.catalog, entries: [] }, f.stories).join("\n"), /missing from catalog/);
assert.match(validateCatalog(f.root, f.catalog, []).join("\n"), /missing story file/);
f.catalog.entries.push(f.catalog.entries[0]);
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /duplicate catalog entry/);
test("unknown capabilities, invalid annotations and inappropriate homes fail", t => {
const f = mapFixture(t);
f.story("task", { capabilities: ["tasks/missing"] });
assert.match(inspect(f).errors.join("\n"), /unknown feature capability/);
f.story("task", { capabilities: [], status: "passed" });
assert.match(inspect(f).errors.join("\n"), /invalid product status/);
assert.match(inspect(f).errors.join("\n"), /explicit reason/);
f.story("task", { capabilities: "tasks/create" });
assert.match(inspect(f).errors.join("\n"), /array of IDs/);
f.story("task", { capabilities: ["tasks/create"] }, { title: "Other/Task" });
assert.match(inspect(f).errors.join("\n"), /sidebar title/);
});
test("capability renames and unjustified unmapped stories fail", t => {
const f = fixture(t);
f.catalog.entries[0].capabilities = ["tasks/old-name"];
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /unknown feature capability/);
f.catalog.entries[0].capabilities = [];
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /explicit reason/);
f.catalog.entries[0].exception = "Shared foundation";
const file = "ui/storybook/stories/foundations/task.stories.tsx";
f.write(file, "export default {};");
const entry = f.catalog.entries[0];
entry.file = file;
entry.sources = [file, "ui/src/Task.tsx"];
entry.fingerprint = fingerprint(f.root, entry.sources);
entry.sidebarTitle = "Foundations/Task";
f.stories[0].file = file;
f.stories[0].title = entry.sidebarTitle;
assert.deepEqual(validateCatalog(f.root, f.catalog, f.stories), []);
test("metadata is parsed without executing code or accepting obsolete bookkeeping fields", t => {
const f = mapFixture(t);
f.write(f.file, `export default { id: 'task', title: 'Work/Tasks/Test', parameters: { paperclip: (() => { throw new Error('executed'); })() } }; export const Empty = {};`);
assert.throws(() => scanStories(f.root), /expressions are not executed/);
f.story("task", { capabilities: ["tasks/create"], fingerprint: "old" });
assert.throws(() => scanStories(f.root), /unknown paperclip field fingerprint/);
f.write(f.file, "export default { id: 'task', title: 'Work/Tasks/Test', parameters: { paperclip: { capabilities: [], capabilities: [] } } }; export const Empty = {};");
assert.throws(() => scanStories(f.root), /unique literal properties/);
});
test("feature organization rejects wrong folders, sidebar homes and unstable meta IDs", t => {
const f = fixture(t);
f.catalog.entries[0].capabilities = ["tasks/discussion"];
assert.deepEqual(validateCatalog(f.root, f.catalog, f.stories), []);
f.stories[0].metaId = "renamed-task";
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /explicit meta ID/);
f.stories[0].metaId = "tasks-create";
f.stories[0].title = "Unrelated/Task";
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /sidebar title/);
f.stories[0].title = f.catalog.entries[0].sidebarTitle;
const originalFile = f.catalog.entries[0].file;
f.catalog.entries[0].file = "ui/storybook/stories/foundations/task.stories.tsx";
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /primary feature folder tasks/);
f.catalog.entries[0].file = originalFile;
f.write("maps/feature-map/README.md", "### Conversations\n| [Tasks](./tasks.md) | Tasks |\n");
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /sidebar title/);
test("parameter spreads cannot silently overwrite a source annotation", t => {
const f = mapFixture(t);
f.write(f.file, "export default { id: 'task', title: 'Work/Tasks/Test', parameters: { paperclip: { capabilities: [] }, ...other } }; export const Empty = {};");
assert.throws(() => scanStories(f.root), /must follow parameter spreads/);
f.write(f.file, "export default { id: 'task', title: 'Work/Tasks/Test', parameters: { paperclip: { capabilities: [] }, [key]: other } }; export const Empty = {};");
assert.throws(() => scanStories(f.root), /must follow parameter spreads/);
f.write(f.file, "export default { id: 'task', title: 'Work/Tasks/Test', parameters: { ['paperclip']: { capabilities: [] } } }; export const Empty = {};");
assert.throws(() => scanStories(f.root), /must be a literal property/);
});
test("shared foundations cross-list capabilities without moving their canonical home or IDs", t => {
const f = fixture(t);
const entry = f.catalog.entries[0];
const file = "ui/storybook/stories/foundations/task.stories.tsx";
f.write(file, "// shared control example\n");
entry.file = file;
entry.home = "foundations";
entry.exception = "Shared control with related product examples.";
entry.sidebarTitle = "Foundations/Task";
entry.sources = [file, "ui/src/Task.tsx"];
entry.fingerprint = fingerprint(f.root, entry.sources);
f.stories[0] = { ...f.stories[0], file, title: entry.sidebarTitle };
assert.deepEqual(validateCatalog(f.root, f.catalog, f.stories), []);
const index = renderIndex(f.catalog, f.stories, featureIndex(f.root));
assert.match(index, /### Tasks[\s\S]*?No primary story suite/);
assert.match(index, /### Shared foundations and guides[\s\S]*?\[Foundations\/Task\]/);
assert.match(index, /`tasks\/create`: \[Foundations\/Task\]/);
assert.deepEqual(f.stories[0].ids, ["tasks-create--empty"]);
entry.home = "tasks";
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /only shared foundations/);
entry.home = "foundations";
delete entry.exception;
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /foundation home needs an explicit reason/);
test("foundations preserve home and cross-capability references", t => {
const f = mapFixture(t);
f.story("control", { capabilities: ["tasks/create"], home: "foundations", exception: "Shared control", implementation: "production" }, { area: "foundations", title: "Foundations/Control" });
const { catalog, errors } = inspect(f);
assert.deepEqual(errors, []);
assert.equal(catalog.entries.find(entry => entry.stableId === "stable-control").home, "foundations");
f.story("control", { capabilities: ["tasks/create"], home: "foundations" }, { area: "foundations", title: "Foundations/Control" });
assert.match(inspect(f).errors.join("\n"), /foundation home needs an explicit reason/);
});
test("production and shared fixture drift invalidate review fingerprints", t => {
const f = fixture(t);
f.write("ui/src/Task.tsx", "// changed contract\n");
f.write("ui/storybook/.storybook/preview.tsx", "// changed shared mocks\n");
const errors = validateCatalog(f.root, f.catalog, f.stories);
assert.equal(errors.filter(error => error.includes("source changed")).length, 2);
assert.equal(f.catalog.entries[0].fingerprint.length, 64);
test("duplicate IDs, missing replacement references and collisions with generated guides fail", t => {
const f = mapFixture(t);
f.story("other", { capabilities: ["tasks/create"] }, { id: "stable-task" });
assert.match(inspect(f).errors.join("\n"), /Duplicate story IDs/);
f.story("other", { capabilities: ["tasks/create"] }, { id: "feature-map-tasks", exports: "export const Overview = {};" });
assert.match(inspect(f).errors.join("\n"), /Duplicate story IDs/);
f.story("other", { capabilities: ["tasks/create"], replacement: "missing.stories.tsx" });
assert.match(inspect(f).errors.join("\n"), /replacement story is missing/);
});
test("missing and escaping source references cannot certify a review", t => {
const f = fixture(t);
f.catalog.entries[0].sources.push("../outside.ts");
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /invalid review sources/);
test("recipe, component and shared fixture edits need no fingerprint acknowledgements", t => {
const f = mapFixture(t);
const before = inspect(f).catalog;
f.write("ui/src/Task.tsx", "export const Task = () => null;");
f.write("ui/storybook/.storybook/preview-base.tsx", "export default { parameters: { changed: true } };");
const file = "maps/feature-map/tasks.md";
f.write(file, readFileSync(path.join(f.root, file), "utf8").replace("discussion work.", "Discuss revised behavior."));
assert.deepEqual(inspect(f).catalog, before);
assert.deepEqual(inspect(f).errors, []);
});
test("cross-capability lookup retains one canonical file and honest status", t => {
const f = fixture(t);
f.catalog.entries[0].status = "historical";
const index = renderIndex(f.catalog, f.stories, featureIndex(f.root));
assert.match(index, /tasks\/create.*\(historical\)/);
assert.match(index, /tasks\/discussion.*\(historical\)/);
assert.match(index, /1 story files; 1 indexed stories/);
assert.match(index, /historical \/ production \/ fixtures/);
test("check mode needs no generated outputs and generation leaves authored files intact", t => {
const f = mapFixture(t);
const before = readFileSync(path.join(f.root, f.file), "utf8");
generateStorybook(f.root, { write: false });
assert.equal(existsSync(path.join(f.root, "ui/storybook/generated")), false);
generateStorybook(f.root);
assert.ok(existsSync(path.join(f.root, "ui/storybook/generated/catalog.json")));
assert.ok(existsSync(path.join(f.root, "maps/generated/verification.md")));
assert.equal(readFileSync(path.join(f.root, f.file), "utf8"), before);
const first = readFileSync(path.join(f.root, "maps/generated/storybook.md"), "utf8");
generateStorybook(f.root);
assert.equal(readFileSync(path.join(f.root, "maps/generated/storybook.md"), "utf8"), first);
});
test("duplicate story IDs cannot silently collapse distinct examples", t => {
const f = fixture(t);
f.stories[0].ids.push(f.stories[0].ids[0]);
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /Duplicate story IDs/);
test("gap reports combine associations with local verification scope and retain historical gaps", t => {
const f = mapFixture(t);
f.story("task", { capabilities: ["tasks/create"], status: "historical" });
const file = "maps/feature-map/tasks.md";
f.write(file, readFileSync(path.join(f.root, file), "utf8") + "\n### Storybook verification\n\n#### `create`\n\nScope: cli\nStorybook: No story required for the command.\nProduction: Run the command.\nSources: Inspect the CLI.\n");
const { catalog, index } = inspect(f);
const report = renderVerification(catalog, index);
assert.match(report, /2 without a current, mixed or unreviewed example/);
assert.match(report, /No story required for the command/);
assert.match(report, /Production: Run the command/);
});
test("feature index keeps empty homes and cross-feature references in map order", t => {
const f = fixture(t);
f.write("maps/feature-map/README.md", "### Work\n| [Goals](./goals.md) | Align work. |\n| [Tasks](./tasks.md) | Create work. |\n");
f.write("maps/feature-map/goals.md", "## Sub-features\n- `hierarchy`: Link goals.\n## Gotchas\n");
f.catalog.entries[0].capabilities.push("goals/hierarchy");
const index = renderIndex(f.catalog, f.stories, featureIndex(f.root));
assert.ok(index.indexOf("### Goals") < index.indexOf("### Tasks"));
assert.match(index, /### Goals[\s\S]*?No primary story suite/);
assert.match(index, /`goals\/hierarchy`: \[Tasks and conversations\/Tasks\/Create\]/);
});
test("authored stories cannot collide with generated overview IDs", t => {
const f = fixture(t);
f.stories[0].ids = ["feature-map-tasks--overview"];
assert.match(validateCatalog(f.root, f.catalog, f.stories).join("\n"), /Duplicate story IDs/);
});
test("regeneration reports review drift from its own writes without refreshing fingerprints", t => {
const f = fixture(t);
f.write("ui/storybook/.storybook/preview.tsx", "export default { parameters: { options: { storySort: { order: [],\n}, } } };\n");
reconcileFeatureArtifacts(f.root, featureIndex(f.root), true);
f.write("maps/storybook-map/INDEX.md", "");
const generatedSource = "ui/storybook/generated/feature-index.json";
f.catalog.sharedReview.sources.push(generatedSource);
f.catalog.entries[0].sources.push(generatedSource);
f.catalog.sharedReview.fingerprint = fingerprint(f.root, f.catalog.sharedReview.sources);
f.catalog.entries[0].fingerprint = fingerprint(f.root, f.catalog.entries[0].sources);
assert.deepEqual(reconcileCatalog(f.root, f.catalog, f.stories, true), []);
const reviewed = f.catalog.sharedReview.fingerprint;
f.write("maps/feature-map/tasks.md", "## Sub-features\n- `create`: Updated description.\n- `discussion`: discuss\n## Gotchas\n");
const errors = reconcileCatalog(f.root, f.catalog, f.stories, true);
assert.equal(errors.filter(error => error.includes("source changed; review")).length, 2);
assert.equal(f.catalog.sharedReview.fingerprint, reviewed);
assert.notEqual(fingerprint(f.root, f.catalog.sharedReview.sources), reviewed);
f.catalog.sharedReview.fingerprint = fingerprint(f.root, f.catalog.sharedReview.sources);
f.catalog.entries[0].fingerprint = fingerprint(f.root, f.catalog.entries[0].sources);
assert.deepEqual(reconcileCatalog(f.root, f.catalog, f.stories, true), []);
assert.deepEqual(reconcileCatalog(f.root, f.catalog, f.stories), []);
});
test("Storybook parser discovers nested files, filters helpers, preserves explicit IDs and counts play functions", t => {
const f = fixture(t);
f.write("ui/package.json", '{"type":"module"}');
symlinkSync(fileURLToPath(new URL("../ui/node_modules", import.meta.url)), path.join(f.root, "ui/node_modules"), "junction");
f.write(f.file, `
import type { Meta, StoryObj } from "@storybook/react-vite";
const meta = { title: "Tasks/Create", id: "stable-task", excludeStories: ["empty"] } satisfies Meta;
test("the CSF parser preserves explicit IDs, export filtering and play counts", t => {
const f = mapFixture(t);
f.write(f.file, `import type { Meta } from '@storybook/react-vite';
const meta = { id: 'stable-task', title: 'Work/Tasks/Create', excludeStories: ['helper'], parameters: { paperclip: { capabilities: ['tasks/create'] } } } satisfies Meta;
export default meta;
type Story = StoryObj<typeof meta>;
export const empty = { value: "fixture" };
export const Empty: Story = {};
export const Filled: Story = { play: async () => {} };
`);
f.write("ui/storybook/stories/nested/other.stories.ts", `
export default { title: "Other/Subject", includeStories: ["Included"] };
export const helper = {};
export const Included = {};
export const Empty = {};
export const Filled = { play: async () => {} };
`);
f.write("ui/storybook/stories/nested/fixture.ts", "export const fixture = {};");
const stories = scanStories(f.root);
assert.equal(stories.length, 2);
assert.deepEqual(stories.find(story => story.file === f.file), {
file: f.file, title: "Tasks/Create", metaId: "stable-task", ids: ["stable-task--empty", "stable-task--filled"], plays: 1,
const [story] = scanStories(f.root);
assert.deepEqual(story.ids, ["stable-task--empty", "stable-task--filled"]);
assert.equal(story.plays, 1);
});
test("independent story and feature branches merge in either order with identical clean generated maps", t => {
const f = mapFixture(t);
f.write(".gitignore", readFileSync(path.join(f.root, ".gitignore"), "utf8") + "node_modules\n");
const git = (...args) => execFileSync("git", ["-c", "user.name=Map test", "-c", "user.email=map@example.test", "-c", "commit.gpgsign=false", ...args], {
cwd: f.root, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" },
});
assert.deepEqual(stories.find(story => story.file.endsWith("other.stories.ts")), {
file: "ui/storybook/stories/nested/other.stories.ts", title: "Other/Subject", metaId: undefined, ids: ["other-subject--included"], plays: 0,
});
git("init", "-b", "main");
git("add", ".");
git("commit", "-qm", "Initial recipes and story");
git("checkout", "-b", "story-change");
f.story("task", { capabilities: ["tasks/create"], notes: "Retain creation draft." }, { exports: "export const Empty = {}; export const Draft = {};" });
git("add", "."); git("commit", "-qm", "Add task draft example");
git("checkout", "-b", "feature-addition", "main");
f.feature("goals", "Goals", ["hierarchy"], { order: 20 });
f.story("goal", { capabilities: ["goals/hierarchy"] }, { area: "goals", title: "Work/Goals/Goal" });
git("add", "."); git("commit", "-qm", "Add goal capability and example");
const results = [];
for (const [first, second] of [["story-change", "feature-addition"], ["feature-addition", "story-change"]]) {
git("checkout", "-b", `merged-${first}`, "main");
git("merge", "--no-edit", first);
git("merge", "--no-edit", second);
const result = generateStorybook(f.root);
assert.equal(git("status", "--porcelain"), "");
assert.deepEqual(result.stories.flatMap(story => story.ids).sort(), ["stable-goal--empty", "stable-task--draft", "stable-task--empty"]);
results.push(["ui/storybook/generated/catalog.json", "ui/storybook/generated/feature-index.json", "maps/generated/storybook.md", "maps/generated/verification.md", "ui/storybook/.storybook/preview.tsx"].map(file => readFileSync(path.join(f.root, file), "utf8")));
}
assert.deepEqual(results[0], results[1]);
});
+39 -80
View File
@@ -1,51 +1,11 @@
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { featureIndex, mapIndexes, pageInventory, sidebarLabel } from "./feature-map.mjs";
export { featureIndex, sidebarLabel } from "./feature-map.mjs";
export const generatedRoot = "ui/storybook/generated";
export const sidebarLabel = title => title.replaceAll("/", ", ");
export function featureIndex(root) {
const sections = [];
let section;
const seen = new Set();
const source = readFileSync(path.join(root, "maps/feature-map/README.md"), "utf8");
for (const line of source.split("\n")) {
if (line.startsWith("### ")) {
section = { title: line.slice(4), features: [] };
sections.push(section);
}
const match = line.match(/^\| \[([^\]]+)\]\(\.\/([a-z0-9-]+)\.md\) \| (.*) \|$/);
if (!match) {
if (line.startsWith("| [")) throw new Error(`Unrecognized feature-map row: ${line}`);
continue;
}
if (!section || seen.has(match[2])) throw new Error(`Invalid feature-map entry: ${line}`);
const [, title, id, description] = match;
seen.add(id);
const recipe = readFileSync(path.join(root, `maps/feature-map/${id}.md`), "utf8");
const body = recipe.split(/^## Sub-features\s*$/m)[1]?.split(/^## /m)[0];
if (!body) throw new Error(`Missing sub-features: ${id}`);
const capabilities = [];
for (const row of body.trim().split("\n")) {
const capability = row.match(/^- `([^`]+)`:\s*(.*)$/);
if (capability) {
const [, key, text] = capability;
capabilities.push({ id: `${id}/${key}`, label: key.replaceAll("-", " ").replace(/^./, letter => letter.toUpperCase()), description: text });
} else if (row.trim() && capabilities.length) {
capabilities.at(-1).description += ` ${row.trim()}`;
}
}
if (!capabilities.length || new Set(capabilities.map(item => item.id)).size !== capabilities.length) throw new Error(`Invalid sub-features: ${id}`);
section.features.push({ id, title, description, capabilities });
}
const populated = sections.filter(item => item.features.length);
if (!populated.length) throw new Error("Feature-map index has no feature families");
for (const file of readdirSync(path.join(root, "maps/feature-map"))) {
if (file.endsWith(".md") && file !== "README.md" && !seen.has(file.slice(0, -3))) throw new Error(`Feature recipe missing from index: ${file}`);
}
return { sections: populated };
}
export const generatedPreview = "ui/storybook/.storybook/preview.tsx";
export function featureOrder(index) {
return ["Overview", ...index.sections.flatMap(section => [sidebarLabel(section.title),
@@ -56,6 +16,24 @@ export function featureOrder(index) {
export function featureArtifacts(index) {
const outputs = new Map([
[`${generatedRoot}/feature-index.json`, JSON.stringify(index, null, 2) + "\n"],
[generatedPreview, [
'import type { Preview } from "@storybook/react-vite";',
'import base from "./preview-base";',
"",
"const preview: Preview = {",
" ...base,",
" parameters: {",
" ...base.parameters,",
" options: {",
" ...base.parameters?.options,",
` storySort: { order: ${JSON.stringify(featureOrder(index))} },`,
" },",
" },",
"};",
"export default preview;",
"",
].join("\n")],
...mapIndexes(index),
]);
for (const section of index.sections) {
for (const feature of section.features) {
@@ -80,47 +58,28 @@ export function featureArtifacts(index) {
return outputs;
}
export function reconcileFeatureArtifacts(root, index, write = false) {
const outputs = featureArtifacts(index);
const errors = [];
function inspect(directory) {
if (!existsSync(path.join(root, directory))) return;
for (const entry of readdirSync(path.join(root, directory), { withFileTypes: true })) {
const file = `${directory}/${entry.name}`;
if (entry.isDirectory()) inspect(file);
else if (!outputs.has(file)) errors.push(`Unexpected generated feature file: ${file}`);
}
}
inspect(generatedRoot);
if (errors.length) return errors;
export function writeArtifacts(root, outputs) {
for (const [file, content] of outputs) {
const destination = path.join(root, file);
if (write) {
mkdirSync(path.dirname(destination), { recursive: true });
writeFileSync(destination, content);
} else if (!existsSync(destination) || readFileSync(destination, "utf8") !== content) {
errors.push(`${file}: generated feature index is stale; run storybook-catalog.mjs --write`);
if (existsSync(destination) && readFileSync(destination, "utf8") === content) continue;
mkdirSync(path.dirname(destination), { recursive: true });
writeFileSync(destination, content);
}
}
export function generateFeatureArtifacts(root, index = featureIndex(root)) {
const outputs = featureArtifacts(index);
outputs.set("maps/generated/coverage.json", JSON.stringify(pageInventory(root, index), null, 2) + "\n");
const directory = `${generatedRoot}/features`;
if (existsSync(path.join(root, directory))) {
for (const name of readdirSync(path.join(root, directory))) {
const file = `${directory}/${name}`;
if (name.endsWith(".stories.tsx") && !outputs.has(file)) rmSync(path.join(root, file), { force: true });
}
}
const previewFile = "ui/storybook/.storybook/preview.tsx";
const previewPath = path.join(root, previewFile);
const preview = readFileSync(previewPath, "utf8");
const pattern = /(\bstorySort:\s*\{\s*order:\s*)([\s\S]*?)(,\s*\n\s*\},)/g;
if ([...preview.matchAll(pattern)].length !== 1) throw new Error("Expected one inline storySort.order in preview.tsx");
const order = JSON.stringify(featureOrder(index), null, 2)
.replace(/("[^"]+",)\n\s+\[\n\s+"Overview",\n\s+"\*"\n\s+\]/g, '$1 ["Overview", "*"]')
.replaceAll("\n", "\n ");
const updated = preview.replace(pattern, (_, before, value, after) => before + order + after);
if (write) writeFileSync(previewPath, updated);
else if (updated !== preview) errors.push(`${previewFile}: generated sidebar order is stale; run storybook-catalog.mjs --write`);
return errors;
writeArtifacts(root, outputs);
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const root = fileURLToPath(new URL("..", import.meta.url));
const errors = reconcileFeatureArtifacts(root, featureIndex(root));
if (errors.length) {
errors.forEach(error => console.error(error));
process.exitCode = 1;
}
generateFeatureArtifacts(fileURLToPath(new URL("..", import.meta.url)));
}
+84 -59
View File
@@ -1,73 +1,98 @@
import assert from "node:assert/strict";
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from "node:fs";
import os from "node:os";
import fs, { existsSync, readFileSync, rmSync } from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import path from "node:path";
import { test } from "node:test";
import { featureArtifacts, featureIndex, featureOrder, reconcileFeatureArtifacts } from "./storybook-feature-index.mjs";
import { featureArtifacts, featureIndex, featureOrder, generateFeatureArtifacts } from "./storybook-feature-index.mjs";
import { mapFixture } from "./map-test-fixture.mjs";
function fixture(t) {
const root = mkdtempSync(path.join(os.tmpdir(), "storybook-feature-index-"));
t.after(() => rmSync(root, { recursive: true, force: true }));
const write = (file, text) => {
mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
writeFileSync(path.join(root, file), text);
};
write("maps/feature-map/README.md", "# Map\n### Work\n| [Tasks](./tasks.md) | Create and follow work. |\n| [Goals](./goals.md) | Align work. |\n### Connections\n| [Apps](./apps.md) | Connect tools. |\n");
write("maps/feature-map/tasks.md", "# Tasks\n## Sub-features\n- `create`: Create work;\n retain the initial description.\n- `review`: Review it.\n## How to get to it\nNot a capability.\n");
write("maps/feature-map/goals.md", "# Goals\n## Sub-features\n- `hierarchy`: Link goals.\n## Gotchas\n");
write("maps/feature-map/apps.md", "# Apps\n## Sub-features\n- `connect`: Connect an app.\n## Gotchas\n");
write("ui/storybook/.storybook/preview.tsx", "export default { parameters: { options: { storySort: { order: [],\n}, unrelated: true } } };\n");
return { root, write };
}
test("feature index preserves recipe names, map order, and multiline capability descriptions", t => {
const { root } = fixture(t);
const index = featureIndex(root);
test("recipes own discovery, names, section order and multiline capability descriptions", t => {
const f = mapFixture(t);
f.feature("goals", "Goals", ["hierarchy"], { order: 20 });
f.feature("apps", "Apps", ["connect"], { section: "Connections", sectionOrder: 20 });
const recipe = path.join(f.root, "maps/feature-map/tasks.md");
f.write("maps/feature-map/tasks.md", readFileSync(recipe, "utf8").replace("create work.", "Create work;\n retain its description."));
const index = featureIndex(f.root);
assert.deepEqual(index.sections.map(section => section.title), ["Work", "Connections"]);
assert.deepEqual(index.sections.flatMap(section => section.features.map(feature => feature.id)), ["tasks", "goals", "apps"]);
assert.deepEqual(index.sections[0].features[0].capabilities, [
{ id: "tasks/create", label: "Create", description: "Create work; retain the initial description." },
{ id: "tasks/review", label: "Review", description: "Review it." },
]);
assert.equal(index.sections[0].features[0].capabilities[0].description, "Create work; retain its description.");
assert.deepEqual(featureOrder(index), ["Overview", "Work", ["Tasks", ["Overview", "*"], "Goals", ["Overview", "*"]], "Connections", ["Apps", ["Overview", "*"]], "Foundations"]);
});
test("every feature gets a stable overview, including features with no authored stories", t => {
const { root } = fixture(t);
const index = featureIndex(root);
const outputs = featureArtifacts(index);
const file = "ui/storybook/generated/features/goals.stories.tsx";
assert.match(outputs.get(file), /id: "feature-map-goals"/);
assert.match(outputs.get(file), /title: "Work\/Goals\/Overview"/);
index.sections[0].features[1].title = "Work alignment";
assert.match(featureArtifacts(index).get(file), /id: "feature-map-goals"/);
assert.match(featureArtifacts(index).get(file), /title: "Work\/Work alignment\/Overview"/);
index.sections[0].features[1].title = "CLI/API and local worktrees";
assert.match(featureArtifacts(index).get(file), /title: "Work\/CLI, API and local worktrees\/Overview"/);
assert.ok(featureOrder(index)[2].includes("CLI, API and local worktrees"));
test("equal local orders preserve independently added features using their stable filename", t => {
const f = mapFixture(t);
f.feature("goals", "Goals");
f.feature("apps", "Apps");
assert.deepEqual(featureIndex(f.root).sections[0].features.map(feature => feature.id), ["apps", "goals", "tasks"]);
});
test("generated guides detect upstream drift, local edits, missing files, and unknown files", t => {
const { root, write } = fixture(t);
const index = featureIndex(root);
assert.equal(reconcileFeatureArtifacts(root, index).length, 5);
assert.deepEqual(reconcileFeatureArtifacts(root, index, true), []);
assert.deepEqual(reconcileFeatureArtifacts(root, index), []);
write("ui/storybook/generated/features/goals.stories.tsx", "export default {};");
assert.match(reconcileFeatureArtifacts(root, index).join("\n"), /goals.stories.tsx: generated feature index is stale/);
reconcileFeatureArtifacts(root, index, true);
index.sections.reverse();
assert.match(reconcileFeatureArtifacts(root, index).join("\n"), /preview.tsx: generated sidebar order is stale/);
assert.match(readFileSync(path.join(root, "ui/storybook/.storybook/preview.tsx"), "utf8"), /unrelated: true/);
write("ui/storybook/generated/features/orphan.stories.tsx", "keep this visible");
assert.match(reconcileFeatureArtifacts(root, index, true).join("\n"), /Unexpected generated feature file/);
assert.equal(readFileSync(path.join(root, "ui/storybook/generated/features/orphan.stories.tsx"), "utf8"), "keep this visible");
test("every discovered feature gets a stable overview, including areas without stories", t => {
const f = mapFixture(t);
f.feature("goals", "CLI/API and goals", ["hierarchy"]);
const index = featureIndex(f.root);
const output = featureArtifacts(index).get("ui/storybook/generated/features/goals.stories.tsx");
assert.match(output, /id: "feature-map-goals"/);
assert.match(output, /title: "Work\/CLI, API and goals\/Overview"/);
});
test("malformed or omitted map entries fail instead of silently hiding a feature", t => {
const { root, write } = fixture(t);
write("maps/feature-map/README.md", "### Work\n| [Tasks](./tasks.md) | Tasks |\n");
assert.throws(() => featureIndex(root), /missing from index/);
write("maps/feature-map/README.md", "### Work\n| [Tasks](tasks.md) | Tasks |\n");
assert.throws(() => featureIndex(root), /Unrecognized feature-map row/);
test("fresh generation rebuilds missing outputs, removes retired overviews and never edits authored preview", t => {
const f = mapFixture(t);
const authored = readFileSync(path.join(f.root, "ui/storybook/.storybook/preview-base.tsx"), "utf8");
f.feature("goals", "Goals", ["hierarchy"]);
generateFeatureArtifacts(f.root);
const overview = path.join(f.root, "ui/storybook/generated/features/goals.stories.tsx");
assert.ok(existsSync(overview));
assert.match(readFileSync(path.join(f.root, "ui/storybook/.storybook/preview.tsx"), "utf8"), /storySort: \{ order: \[/);
rmSync(path.join(f.root, "maps/feature-map/goals.md"));
rmSync(path.join(f.root, "maps/agent-access-map/goals.md"));
generateFeatureArtifacts(f.root);
assert.equal(existsSync(overview), false);
assert.equal(readFileSync(path.join(f.root, "ui/storybook/.storybook/preview-base.tsx"), "utf8"), authored);
assert.match(readFileSync(path.join(f.root, "maps/generated/feature-map.md"), "utf8"), /Tasks/);
});
test("missing metadata, duplicate capabilities and inconsistent group order fail visibly", t => {
const f = mapFixture(t);
f.write("maps/feature-map/new.md", "# New\n");
assert.throws(() => featureIndex(f.root), /missing navigation/);
f.feature("new", "New", ["create", "create"]);
assert.throws(() => featureIndex(f.root), /duplicate capability/);
f.feature("new", "New", ["create"], { sectionOrder: 99 });
assert.throws(() => featureIndex(f.root), /inconsistent section order/);
});
test("overlapping generators can both retire the same overview", t => {
const f = mapFixture(t);
const retired = "ui/storybook/generated/features/retired.stories.tsx";
f.write(retired, "export const Overview = {};\n");
const directory = path.join(f.root, "ui/storybook/generated/features");
const readDirectory = fs.readdirSync;
let competed = false;
// Reproduce the interleaving deterministically: the other generator removes
// the file after this generator lists it, before this generator removes it.
const mock = t.mock.method(fs, "readdirSync", (...args) => {
const listing = readDirectory(...args);
if (args[0] === directory && !competed) {
competed = true;
rmSync(path.join(f.root, retired));
}
return listing;
});
syncBuiltinESMExports();
try {
generateFeatureArtifacts(f.root);
assert.equal(competed, true);
assert.equal(existsSync(path.join(f.root, retired)), false);
assert.ok(existsSync(path.join(directory, "tasks.stories.tsx")));
} finally {
mock.mock.restore();
syncBuiltinESMExports();
}
});
test("verification guidance rejects orphan capability references", t => {
const f = mapFixture(t);
const file = "maps/feature-map/tasks.md";
f.write(file, readFileSync(path.join(f.root, file), "utf8") + "\n### Storybook verification\n\n#### `missing`\n\nScope: cli\nStorybook: Use CLI.\nProduction: Execute.\nSources: Inspect.\n");
assert.throws(() => featureIndex(f.root), /unknown or duplicate verification capability/);
});