#!/usr/bin/env node // generate-reference-index.mjs — writes or checks a router skill's references/index.md. // // A router names its topic pages in its own table, each with a condition for reading it. Past about thirty pages that // table is not read, so the router also ships an index to grep: one line per page, with the condition taken from the // "Load when" text that already names the page, in the router's table or in its topic page's list of references. // The index is generated from those lines and never edited by hand. // // Usage: // node plugin/scripts/generate-reference-index.mjs [--skills DIR] write references/index.md // node plugin/scripts/generate-reference-index.mjs --check [--skills DIR] exit 1 when it differs // node plugin/scripts/generate-reference-index.mjs --unnamed [--skills DIR] list pages with no condition // node plugin/scripts/generate-reference-index.mjs --router-only --unnamed ... named in SKILL.md alone // // Exit: 0 clean, 1 drift or a page with no condition, 64 usage. import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; const args = process.argv.slice(2); const si = args.indexOf("--skills"); const skillsDir = si >= 0 ? path.resolve(args[si + 1]) : path.join(path.dirname(fileURLToPath(import.meta.url)), "../skills"); const skill = args.find((a, i) => !a.startsWith("--") && args[i - 1] !== "--skills"); if (!skill) { console.error("usage: generate-reference-index.mjs [--check | --unnamed] [--router-only] [--skills DIR]"); process.exit(64); } const root = path.join(skillsDir, skill); const refs = path.join(root, "references"); if (!fs.existsSync(path.join(root, "SKILL.md")) || !fs.existsSync(refs)) { console.error(`no skill with references at ${root}`); process.exit(64); } // Generated or version-keyed trees, each named by one row of its own elsewhere. const SKIP = new Set(["constructs", "ledger"]); const walk = (dir) => fs .readdirSync(dir, { withFileTypes: true }) // A topic page sorts before the directory of its deeper pages. .sort((a, b) => { const ka = a.name.replace(/\.md$/, ""); const kb = b.name.replace(/\.md$/, ""); if (ka === kb) return a.isDirectory() ? 1 : -1; return ka < kb ? -1 : 1; }) .flatMap((e) => { const p = path.join(dir, e.name); if (e.isDirectory()) return SKIP.has(e.name) ? [] : walk(p); return e.name.endsWith(".md") ? [p] : []; }); const indexFile = path.join(refs, "index.md"); const pages = walk(refs).filter((p) => p !== indexFile); // Split a markdown file into units: one table row, or one list item with its continuation lines. const units = (text) => { const out = []; let header = null; let item = null; let inFence = false; const flush = () => { if (item) out.push({ text: item.join(" "), cells: null }); item = null; }; for (const line of text.split("\n")) { if (/^```/.test(line)) { inFence = !inFence; flush(); continue; } if (inFence) continue; if (/^\|/.test(line)) { flush(); const cells = line .replace(/^\|/, "") .replace(/\|\s*$/, "") .split(/(? c.trim()); if (cells.every((c) => /^:?-{2,}:?$/.test(c))) continue; if (!header) { header = cells; continue; } out.push({ text: line, cells, header }); continue; } header = null; if (/^\s*[-*+] /.test(line)) { flush(); item = [line.trim()]; } else if (item && /^\s+\S/.test(line)) item.push(line.trim()); else flush(); } flush(); return out; }; const linkRe = /\]\(([^)\s#]+)(?:#[^)]*)?\)/g; const clean = (s) => s .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") .replace(/\s+/g, " ") .replace(/^Load when:?\s*/i, "") .replace(/[\s.|]+$/, "") .trim(); // The condition for each page. The first source wins: SKILL.md, then each topic page in path order. const conditions = new Map(); const sources = [path.join(root, "SKILL.md"), ...(args.includes("--router-only") ? [] : pages)]; for (const src of sources) { for (const u of units(fs.readFileSync(src, "utf8"))) { let cond = null; if (u.cells) { const col = u.header.findIndex((h) => /load when/i.test(h)); if (col >= 0 && u.cells[col]) cond = u.cells[col]; } if (!cond) { const m = u.text.match(/Load when:?\s*(.*)$/i); if (m) cond = m[1]; } if (!cond) continue; const first = u.cells ? u.cells[0] : u.text.split(/Load when/i)[0]; for (const m of first.matchAll(linkRe)) { const target = path.resolve(path.dirname(src), m[1]); if (!pages.includes(target) || conditions.has(target)) continue; conditions.set(target, clean(cond)); } } } const unnamed = pages.filter((p) => !conditions.has(p)); if (args.includes("--unnamed")) { for (const p of unnamed) console.log(path.relative(root, p)); process.exit(unnamed.length ? 1 : 0); } if (unnamed.length) { console.error(`${skill}: ${unnamed.length} page(s) with no "Load when" condition in the router or a topic page:`); for (const p of unnamed) console.error(` ${path.relative(root, p)}`); process.exit(1); } const title = (p) => { const h = fs.readFileSync(p, "utf8").match(/^# (.+)$/m); return h ? h[1].trim() : path.basename(p, ".md"); }; const lines = [ `# Index of the ${skill} pages`, "", 'Generated by `plugin/scripts/generate-reference-index.mjs` from the "Load when" text that names each page. Do not', "edit it by hand: change that text in the router or the topic page, then regenerate.", "", "One line per page: its path, its title and when to read it. Grep it for what you are about to do, then read the", "page.", ]; const groupOf = (p) => path.relative(refs, p).split("/")[0].replace(/\.md$/, ""); let group = null; for (const p of pages) { const rel = path.relative(refs, p); if (groupOf(p) !== group) { group = groupOf(p); lines.push("", `## ${group}`, ""); } lines.push(`- [${rel}](${rel}) — ${title(p)}. Load when: ${conditions.get(p)}.`); } const out = `${lines.join("\n")}\n`; if (args.includes("--check")) { const cur = fs.existsSync(indexFile) ? fs.readFileSync(indexFile, "utf8") : ""; if (cur !== out) { console.error( `${skill}: references/index.md is stale; run node plugin/scripts/generate-reference-index.mjs ${skill}`, ); process.exit(1); } process.exit(0); } fs.writeFileSync(indexFile, out); console.log(`${skill}: wrote references/index.md with ${pages.length} pages`);