#!/usr/bin/env node /** * graph.js — query the build-emitted artefact graph. * * Usage: * node scripts/graph.js impact [--depth N] [--json] * node scripts/graph.js dependencies [--depth N] [--json] * node scripts/graph.js neighbors [--json] * node scripts/graph.js path [--json] * node scripts/graph.js orphans [--json] * node scripts/graph.js stats [--json] * node scripts/graph.js history [--layer product|internal] [--limit N] [--json] * node scripts/graph.js mermaid [] [--depth N] [--kinds a,b] | --write * node scripts/graph.js ecosystem [--write] * * A node id is `//`, e.g. product/skill/add-doc-schemas. * A bare name is resolved when it is unambiguous. * * Why a CLI and not only an MCP server: the callers are this framework's own * commands, running on five providers. Every one of them can shell out; only * some have MCP configured. * * The MCP surface is mcp/server.mjs --corpus=artefacts, which serves this * corpus and a user's docs corpus from one binary. It does NOT wrap this * module: it reads the same emitted sidecar, and cli/tests/mcp-engine.test.js * asserts the two answer identically verb for verb rather than by shared code. */ const fs = require('node:fs'); const path = require('node:path'); const ROOT = path.resolve(__dirname, '..'); const DEFAULT_GRAPH = path.join(ROOT, 'framwork', '.codeadd', 'artefact-graph.json'); /** * Edge types that mean "this would break if that changed". * * MENTIONS is deliberately absent. It records that one doc names another while * pointing AWAY from it ("use X instead"); counting it would inflate every * blast radius with relationships that cannot break anything. */ const DEPENDENCY_TYPES = new Set(['USES_SKILL', 'DISPATCHES', 'HANDS_OFF_TO', 'RUNS_SCRIPT', 'INJECTS_INTO', 'CONTAINS']); /** * The same set MINUS `CONTAINS`, and `orphans()` reads THIS one. * * ⛔ DO NOT collapse the two back together. A feature or a plugin contains * every file in its directory, so counting CONTAINS as a dependency would give * each of those files a permanent inbound edge — and NOTHING under * `fragments/` or `plugins/` could ever be reported as an orphan again. Dead * weight would become invisible by directory placement alone, which is the one * failure `orphans` exists to prevent. * * `CONTAINS` belongs in DEPENDENCY_TYPES above because `dependencies` on a * feature node SHOULD list its members — that is the question containers were * added to answer. The two sets differ because the two questions differ. * * ⛔ DUPLICATED in `mcp/engine.mjs`. `mcp/` takes no dependency at all and * cannot import from here; only a test holds them equal. */ const ORPHAN_DEPENDENCY_TYPES = new Set( [...DEPENDENCY_TYPES].filter((t) => t !== 'CONTAINS'), ); /** * Kinds nothing is expected to depend on, so absence of dependants is normal. * * Commands are invoked by people. Fragments are the SOURCE of every * INJECTS_INTO edge and never its target, so they are orphans by construction — * reporting all 23 buries the findings that matter. Features and plugins are * the same case one level up: a user enables them, nothing declares them. * Everything else earns its place in the graph by being depended on, and a * reference file or script that nothing reaches is genuinely dead weight worth * surfacing. * * ⛔ `template` is deliberately ABSENT. Nothing in `.codeadd/` names any of the * four shipped templates, so they report as orphans — and that is the finding, * not a nuisance to suppress. Adding the kind here would hide the one thing * indexing them was for. * * ⛔ THIS SET IS DUPLICATED in `mcp/engine.mjs` as ENTRY_POINT_KINDS.artefacts, * which is PRODUCT code and cannot import from here — `mcp/` takes no * dependency at all. Neither copy reads the other; a test is the only thing * holding them equal. Change one and change the other in the same delivery. */ const ENTRY_POINT_KINDS = new Set(['command', 'fragment', 'feature', 'plugin']); function loadGraph(file = DEFAULT_GRAPH) { if (!fs.existsSync(file)) { throw new Error( `No artefact graph at ${path.relative(ROOT, file)}. Run \`node scripts/build.js\` first.`, ); } return JSON.parse(fs.readFileSync(file, 'utf8')); } /** * Resolve a node id, accepting a bare name when it is unambiguous. * Ambiguity is an error, not a guess: `add-commit` is both a product and an * internal skill, and silently picking one would answer the wrong question. */ function resolve(graph, ref) { if (graph.nodes.some((n) => n.id === ref)) return ref; const matches = graph.nodes.filter((n) => n.name === ref || n.id.endsWith(`/${ref}`)); if (matches.length === 1) return matches[0].id; if (matches.length > 1) { throw new Error( `"${ref}" is ambiguous — it matches ${matches.length} nodes:\n ` + matches.map((m) => m.id).join('\n '), ); } throw new Error(`No node matches "${ref}".`); } /** Adjacency in one direction, dependency edges only unless told otherwise. */ function adjacency(graph, { reverse = false, all = false } = {}) { const adj = new Map(); for (const e of graph.edges) { if (!all && !DEPENDENCY_TYPES.has(e.type)) continue; const [from, to] = reverse ? [e.to, e.from] : [e.from, e.to]; if (!adj.has(from)) adj.set(from, []); adj.get(from).push({ id: to, type: e.type, modifier: e.modifier }); } return adj; } /** * Breadth-first walk returning every reachable node with its distance. * `seen` is what makes a dependency cycle terminate instead of hanging. */ function walk(graph, startId, { reverse, depth = Infinity }) { const adj = adjacency(graph, { reverse }); const seen = new Set([startId]); const out = []; let frontier = [startId]; for (let d = 1; d <= depth && frontier.length; d++) { const next = []; for (const id of frontier) { for (const edge of adj.get(id) || []) { if (seen.has(edge.id)) continue; seen.add(edge.id); out.push({ id: edge.id, depth: d, via: edge.type }); next.push(edge.id); } } frontier = next; } return out; } /** Everything that transitively depends on `ref` — the blast radius. */ function impact(graph, ref, opts = {}) { return walk(graph, resolve(graph, ref), { reverse: true, depth: opts.depth }); } /** Everything `ref` transitively depends on. */ function dependencies(graph, ref, opts = {}) { return walk(graph, resolve(graph, ref), { reverse: false, depth: opts.depth }); } /** Immediate edges either way, MENTIONS included — a listing is not a radius. */ function neighbors(graph, ref) { const id = resolve(graph, ref); return { in: graph.edges.filter((e) => e.to === id), out: graph.edges.filter((e) => e.from === id), }; } /** * Artefacts nothing depends on. * * Commands are excluded: people invoke them, so all 24 would otherwise be * reported and drown the findings that matter. */ function orphans(graph) { const depended = new Set( graph.edges.filter((e) => ORPHAN_DEPENDENCY_TYPES.has(e.type)).map((e) => e.to), ); return graph.nodes.filter((n) => !ENTRY_POINT_KINDS.has(n.kind) && !depended.has(n.id)); } /** Shortest dependency chain from → to, or null. */ function pathBetween(graph, fromRef, toRef) { const from = resolve(graph, fromRef); const to = resolve(graph, toRef); if (from === to) return [from]; const adj = adjacency(graph); const prev = new Map([[from, null]]); let frontier = [from]; while (frontier.length) { const next = []; for (const id of frontier) { for (const edge of adj.get(id) || []) { if (prev.has(edge.id)) continue; prev.set(edge.id, id); if (edge.id === to) { const chain = [to]; for (let at = id; at !== null; at = prev.get(at)) chain.unshift(at); return chain; } next.push(edge.id); } } frontier = next; } return null; } function stats(graph) { const byKind = {}; const byEdge = {}; const byLayer = {}; for (const n of graph.nodes) { byKind[n.kind] = (byKind[n.kind] || 0) + 1; byLayer[n.layer] = (byLayer[n.layer] || 0) + 1; } for (const e of graph.edges) byEdge[e.type] = (byEdge[e.type] || 0) + 1; const inbound = {}; for (const e of graph.edges) { if (DEPENDENCY_TYPES.has(e.type)) inbound[e.to] = (inbound[e.to] || 0) + 1; } const hubs = Object.entries(inbound) .sort((a, b) => b[1] - a[1]) .slice(0, 10) .map(([id, count]) => ({ id, dependents: count })); return { nodes: graph.nodes.length, edges: graph.edges.length, byKind, byEdge, byLayer, hubs }; } // --------------------------------------------------------------------------- // History — the time axis, read in-process // --------------------------------------------------------------------------- /** * The native delivery reader, required directly since F4. * * `history` used to spawn `bash delivered.sh read`: a second process, a shell * and a shebang script stood between the query and the index, and the verb * failed outright wherever bash was absent (native Windows, a stripped CI * image). `delivery-index-core.cjs` is F3's side-effect-free boundary over the * same index, and `delivered.cjs` is its command-line entry — so requiring the * core removes the shell without creating a second reader. There is ONE * implementation of the index format; graph history and the shipped entry * consume it rather than reimplementing it in parallel. * * Kept as a lazy require: a missing core must be REPORTED as an unavailable * answer, never thrown at module load, because graph.js also answers the verbs * that have nothing to do with history. That is the contract the shell * delegation had. */ const DELIVERY_CORE = path.join(ROOT, 'framwork', '.codeadd', 'scripts', 'delivery-index-core.cjs'); function deliveryIndex(reader = DELIVERY_CORE) { const loaded = require(path.resolve(reader)); const core = loaded?.core ?? loaded; for (const method of ['resolveRoot', 'createContext', 'performRead', 'performHistoryRead', 'performTouched']) { if (typeof core?.[method] !== 'function') throw new Error(`Native delivery reader lacks ${method}`); } return core; } /** Flags `history` refuses outright. graph.js is query-only, by plan 0077. */ const WRITING_FLAGS = new Set(['--repair', '--write', '--fix']); /** * When this artefact was delivered, and what it replaced. * * THE READ IS DELEGATED, NEVER REIMPLEMENTED. `delivery-index-core.cjs` owns * last-line-wins, corrupt-line tolerance and status ordering — the same rules * the retired `delivered.sh read` enforced. Parsing the JSONL here in * JavaScript would be a SECOND implementation of one format — plan 0075's * whole subject, recreated inside the design that cites it as the lesson. * Inlining the parse looks cleaner and is the likeliest future regression; * this comment is the reason it must not happen. * * This verb owns the JOIN and nothing else: * index -> what existed, when it arrived, what it replaced (time) * graph -> what depends on it today (structure) * * It NEVER writes. There is no `--repair` passthrough: the native * `delivered.cjs verify --repair` stays the single writing path. * * A missing reader is REPORTED, never thrown. The same function once ran * inside the long-lived MCP server, where a throw would kill every later query * rather than the one that failed. * * RETIRED BASH OVERRIDES and what replaced them: * opts.script was the path to the `delivered.sh` this verb executed. It now * names a native core module or an entry exporting `core`. * The selected module supplies the implementation. Default: * the core path above. * opts.bash was the interpreter. Retired with the spawn: the native path * has no interpreter, so passing it changes nothing. * opts.cwd unchanged: the repository whose index is read. */ function history(graph, ref, opts = {}) { const node = resolve(graph, ref); // The question is exact — which entries record THIS node — so it goes to // `performHistoryRead` with the full node id, never to the text ranker: a // relevance cut could drop the very entry that carries the node. The filter // below stays as the same check over what comes back. const name = node.slice(node.lastIndexOf('/') + 1); const unavailable = (reason, detail) => ({ node, name, entries: [], matched: 0, unavailable: { reason, detail }, }); const reader = opts.script ?? DELIVERY_CORE; const cwd = opts.cwd ?? ROOT; if (!fs.existsSync(reader)) { return unavailable('script-missing', `${reader} does not exist`); } let core; try { core = deliveryIndex(reader); } catch (e) { return unavailable('read-failed', e.message); } if (opts.layer && opts.layer !== 'product' && opts.layer !== 'internal') { return unavailable('read-failed', 'read refused: --layer must be product or internal'); } const limit = opts.limit ?? 50; if (!Number.isInteger(limit) || limit <= 0) { return unavailable('read-failed', 'read refused: --limit must be a positive whole number'); } let rootRes; try { rootRes = core.resolveRoot(cwd); } catch (e) { return unavailable('read-failed', e.message); } if (!rootRes.ok) { // The shell reported this as an `ERROR=` line and exit 2; the core returns // the same fact as a value. Same `read-failed` answer either way. return unavailable('read-failed', `ERROR=${rootRes.error}`); } // `--layer` narrows which entries are read at all, which is what // /add-framework--plan needs when it asks a product-layer question. It is // handed to the core, never reimplemented as a post-filter here. let read; try { const ctx = core.createContext({ root: rootRes.root }); read = core.performHistoryRead(ctx, { node, layer: opts.layer || '', limit: opts.limit ?? 50, }); } catch (e) { // A reader failure is REPORTED, never thrown — the contract the shell // delegation had. A throw inside a long-lived server would kill every // later query rather than the one that failed. return unavailable('read-failed', e.message); } // The KEY=VALUE protocol the shell emitted, rebuilt from the core's // structured result. The CLI renders the dead-cap note from MATCHED_DEAD and // RETURNED_DEAD, so those names must survive exactly. const keys = { MATCHED_LIVE: String(read.matchedLive), MATCHED_DEAD: String(read.matchedDead), RETURNED_LIVE: String(read.returnedLive), RETURNED_DEAD: String(read.returnedDead), LIVE_CAP: String(read.liveCap), DEAD_CAP: String(read.deadCap), SKIPPED_LINES: read.skipped.join(','), }; const dependentsOf = (id) => { try { return impact(graph, id, { depth: 1 }).length; } catch { return null; } }; // `node` IS READ AT BOTH LEVELS, and the entry level is the one that matters. // // THE SCHEMA PUTS `node` ON THE RECORD. add-doc-schemas/references/ // delivery-index.md lists it in "The record" table and defines an item as // exactly {what, at, find}, and the core's `serialize` implements that: a // `node` inside an item is normalised away on write. That is correct, not a // defect — do not "fix" the writer to preserve it. The delivered suite pins // both directions. // // The item level is read anyway for two honest reasons: `read` returns // whatever a line carries, and a human may hand-write one (the reference says // humans author lines for `superseded`); and an internal design note specifies // per-item ids, so if that ever becomes the schema this reader already agrees // with it. Matching on items ALONE would match nothing any writer produces — // which is how this was nearly shipped, from a fixture that hand-wrote JSONL // the writer would never emit. const carriesNode = (e) => e.node === node || (Array.isArray(e.items) && e.items.some((it) => it && it.node === node)); // Ordering is the core's contract (live -> changed -> superseded -> gone) // and is preserved exactly. Re-sorting here would be a consumer re-ranking // one shared structure, which is how two readers come to disagree. const matched = read.entries.filter(carriesNode).map((e) => { const out = { ...e, items: (Array.isArray(e.items) ? e.items : []).map((it) => (it && it.node // Enriched only where the record already carries a node. An item // without one is returned untouched — never with a fabricated id, // which would resolve to nothing and be worse than an absent field. ? { ...it, dependents: dependentsOf(it.node) } : it)), }; if (e.node) out.dependents = dependentsOf(e.node); return out; }); return { node, name, entries: matched, matched: matched.length, keys, unavailable: null }; } // --------------------------------------------------------------------------- // Mermaid emission // --------------------------------------------------------------------------- /** Node shape per kind, so the diagram reads without a legend lookup. */ const MERMAID_SHAPE = { command: (id, label) => `${id}(["${label}"])`, skill: (id, label) => `${id}["${label}"]`, agent: (id, label) => `${id}[/"${label}"/]`, script: (id, label) => `${id}[("${label}")]`, reference: (id, label) => `${id}>"${label}"]`, fragment: (id, label) => `${id}{{"${label}"}}`, }; /** * Mermaid identifiers allow only word characters, but a node id is * `product/command/add.plan`. Emitted raw it produces a diagram that silently * fails to render — no error, just a blank panel on the docs site. */ function mermaidId(nodeId) { return `n_${nodeId.replace(/[^A-Za-z0-9]/g, '_')}`; } /** * Render a SCOPED slice of the graph as a mermaid flowchart. * * Scoping is the design, not a limitation: 202 nodes and 625 edges rendered at * once is an unreadable hairball that tells a reader nothing. * * @param {object} graph * @param {{root?: string, depth?: number, kinds?: string[], layers?: string[], direction?: string}} opts * root — centre the diagram on one artefact and walk out from it * kinds — otherwise, include only these node kinds * layers — keep only nodes of these layers, in either mode */ function toMermaid(graph, opts = {}) { const { depth = 2, direction = 'LR' } = opts; let keep; if (opts.root) { const rootId = resolve(graph, opts.root); keep = new Set([rootId, ...walk(graph, rootId, { reverse: false, depth }).map((r) => r.id)]); // MENTIONS is excluded from the walk (it is not a dependency) but belongs // in a picture: a reader wants to see the pointer, drawn so it cannot be // mistaken for one. for (const e of graph.edges) { if (e.type === 'MENTIONS' && keep.has(e.from)) keep.add(e.to); } } else { const kinds = new Set(opts.kinds || ['command', 'skill', 'agent']); keep = new Set(graph.nodes.filter((n) => kinds.has(n.kind)).map((n) => n.id)); } const byId = new Map(graph.nodes.map((n) => [n.id, n])); if (opts.layers) { const layers = new Set(opts.layers); for (const id of [...keep]) { const n = byId.get(id); if (n && !layers.has(n.layer)) keep.delete(id); } } const lines = [`flowchart ${direction}`]; for (const id of [...keep].sort()) { const n = byId.get(id); if (!n) continue; const shape = MERMAID_SHAPE[n.kind] || MERMAID_SHAPE.skill; lines.push(` ${shape(mermaidId(id), n.name)}`); } const drawn = new Set(); for (const e of graph.edges) { if (!keep.has(e.from) || !keep.has(e.to)) continue; const key = `${e.from}|${e.type}|${e.to}`; if (drawn.has(key)) continue; drawn.add(key); // A dotted link for MENTIONS — the picture must not let a "use X instead" // pointer read as a dependency. const link = e.type === 'MENTIONS' ? '-.->' : '-->'; lines.push(` ${mermaidId(e.from)} ${link} ${mermaidId(e.to)}`); } return `${lines.join('\n')}\n`; } /** * The diagram the docs site ships, as ONE definition. * * `mermaid --write` renders this and the test asserts the checked-in file * matches it. They previously each carried their own options: the documented * command emitted 606 lines while the checked-in file was 92, so running the * documented command failed the test and replaced the docs diagram with a * hairball. Sharing the profile is what makes "regenerate" and "assert current" * describe the same picture by construction. * * `layers: ['product']` keeps the internal pipeline out of a public page: its * commands are not installable by a user, and drawing them promises something * the site cannot deliver. Filtering by layer, not by a name prefix, also keeps * an internal skill or agent out the day this profile grows beyond commands. */ const DOCS_PROFILE = { kinds: ['command'], depth: 1, layers: ['product'] }; const DOCS_DIAGRAM = path.join(ROOT, 'web', 'public', 'artefact-graph.mmd'); /** * The docs "Ecosystem Map", as Cytoscape elements. * * The map used to be a ~500-line hand-written literal in docs.astro and had * drifted to 29 skills and 17 agents against a shipped 42 and 22. This renders * it from the sidecar, so the site cannot disagree with the build. * * Nodes: product layer, kind command, skill or agent, MINUS anything under * `framwork/.codeadd/plugins/`. A plugin-bundled skill (`add--gitnexus`) is not * part of the core set the installer always lays down, and * `scripts/inventory.js` does not list it either — the two must name the same * artefacts. * * Edges: only the four shapes the map draws. Everything else (HANDS_OFF_TO, * MENTIONS, RUNS_SCRIPT, skill-to-agent DISPATCHES, any edge touching a node * outside the set) is dropped, so the picture stays a map of what loads and * dispatches what rather than the hairball `mermaid` warns about. * * A node id is the artefact NAME (unique across the three kinds today), the * label is the short form the map shows. */ const ECOSYSTEM_FILE = path.join(ROOT, 'web', 'public', 'ecosystem.json'); const ECOSYSTEM_KINDS = ['command', 'skill', 'agent']; const ECOSYSTEM_EDGES = { 'USES_SKILL command>skill': 'loads', 'USES_SKILL agent>skill': 'uses', 'USES_SKILL skill>skill': 'uses', 'DISPATCHES command>agent': 'dispatches', }; const ECOSYSTEM_LABEL = { command: (name) => name, skill: (name) => name.replace(/^add--/, ''), agent: (name) => name.replace(/-agent$/, ''), }; function toEcosystem(graph) { const inSet = graph.nodes .filter((n) => n.layer === 'product' && ECOSYSTEM_KINDS.includes(n.kind) && !String(n.path).startsWith('framwork/.codeadd/plugins/')) .sort((a, b) => ECOSYSTEM_KINDS.indexOf(a.kind) - ECOSYSTEM_KINDS.indexOf(b.kind) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); const byId = new Map(inSet.map((n) => [n.id, n])); const seen = new Set(); const rows = []; for (const e of graph.edges) { const from = byId.get(e.from); const to = byId.get(e.to); if (!from || !to || from === to) continue; const type = ECOSYSTEM_EDGES[`${e.type} ${from.kind}>${to.kind}`]; if (!type) continue; const key = `${from.name}|${to.name}|${type}`; if (seen.has(key)) continue; seen.add(key); rows.push({ source: from.name, target: to.name, type }); } rows.sort((a, b) => (a.source < b.source ? -1 : a.source > b.source ? 1 : 0) || (a.target < b.target ? -1 : a.target > b.target ? 1 : 0) || (a.type < b.type ? -1 : a.type > b.type ? 1 : 0)); return { nodes: inSet.map((n) => ({ data: { id: n.name, label: ECOSYSTEM_LABEL[n.kind](n.name), type: n.kind } })), edges: rows.map((r, i) => ({ data: { id: `e${i}`, ...r } })), }; } const NL = String.fromCharCode(10); /** One element per line: a regenerated file diffs by element, not as one 2,500-line reflow. */ function formatEcosystem(eco) { const block = (rows) => rows.map((r) => ' ' + JSON.stringify(r)).join(',' + NL); return ['{', ' "nodes": [', block(eco.nodes), ' ],', ' "edges": [', block(eco.edges), ' ]', '}', ''].join(NL); } module.exports = { loadGraph, resolve, impact, dependencies, neighbors, orphans, pathBetween, stats, history, toMermaid, mermaidId, toEcosystem, DEPENDENCY_TYPES, DEFAULT_GRAPH, DOCS_PROFILE, DOCS_DIAGRAM, ECOSYSTEM_FILE, }; // --------------------------------------------------------------------------- // CLI // --------------------------------------------------------------------------- function main(argv) { const json = argv.includes('--json'); // Flags that take a value. Their value must be excluded from the positionals // too — `--kinds` was not, so `mermaid --kinds command` put "command" in // args[1] and it was read as the root node, failing with `No node matches // "command"`. Any future valued flag must be added here or it breaks the same // way. const VALUED = new Set(['--depth', '--kinds', '--limit', '--layer']); const valueIndexes = new Set(); argv.forEach((a, i) => { if (VALUED.has(a)) valueIndexes.add(i + 1); }); const valueOf = (flag) => { const at = argv.indexOf(flag); return at >= 0 ? argv[at + 1] : undefined; }; const rawDepth = valueOf('--depth'); if (rawDepth !== undefined && !/^\d+$/.test(rawDepth)) { console.error(`--depth needs a whole number, got ${JSON.stringify(rawDepth ?? '')}.`); process.exitCode = 2; return; } const depth = rawDepth === undefined ? undefined : Number(rawDepth); const kinds = valueOf('--kinds')?.split(','); const rawLimit = valueOf('--limit'); const limit = rawLimit === undefined ? undefined : Number(rawLimit); const args = argv.filter((a, i) => !a.startsWith('--') && !valueIndexes.has(i)); const [cmd, a, b] = args; const graph = loadGraph(); const emit = (v, text) => console.log(json ? JSON.stringify(v, null, 2) : text(v)); const list = (rows) => rows.length ? rows.map((r) => ` ${String(r.depth).padStart(2)} ${r.id} (${r.via})`).join('\n') : ' (none)'; switch (cmd) { case 'impact': return emit(impact(graph, a, { depth }), (r) => `${r.length} artefact(s) depend on ${resolve(graph, a)}:\n${list(r)}`); case 'dependencies': return emit(dependencies(graph, a, { depth }), (r) => `${resolve(graph, a)} depends on ${r.length} artefact(s):\n${list(r)}`); case 'neighbors': return emit(neighbors(graph, a), (n) => `in (${n.in.length}):\n` + (n.in.map((e) => ` ${e.from} (${e.type})`).join('\n') || ' (none)') + `\nout (${n.out.length}):\n` + (n.out.map((e) => ` ${e.to} (${e.type})`).join('\n') || ' (none)')); case 'path': { const p = pathBetween(graph, a, b); return emit(p, (r) => (r ? r.join('\n -> ') : 'no dependency path')); } case 'orphans': return emit(orphans(graph), (r) => `${r.length} artefact(s) nothing depends on:\n` + (r.map((n) => ` ${n.id}`).join('\n') || ' (none)')); case 'mermaid': { // --write always renders the shared docs profile, never whatever flags // happen to be on the command line. Otherwise `mermaid --write` and the // test that holds the file current can describe different diagrams — and // they did: 606 lines against 92. if (argv.includes('--write')) { const out = toMermaid(graph, DOCS_PROFILE); fs.mkdirSync(path.dirname(DOCS_DIAGRAM), { recursive: true }); fs.writeFileSync(DOCS_DIAGRAM, out, 'utf8'); return console.log( `wrote ${path.relative(ROOT, DOCS_DIAGRAM)} ` + `(${out.split('\n').length - 1} lines, profile: ${JSON.stringify(DOCS_PROFILE)})`, ); } return console.log(toMermaid(graph, { root: a, depth, kinds })); } case 'ecosystem': { // Like mermaid, --write always renders the one fixed definition. Without // it the JSON goes to stdout. const out = formatEcosystem(toEcosystem(graph)); if (argv.includes('--write')) { fs.mkdirSync(path.dirname(ECOSYSTEM_FILE), { recursive: true }); fs.writeFileSync(ECOSYSTEM_FILE, out, 'utf8'); const eco = JSON.parse(out); return console.log( `wrote ${path.relative(ROOT, ECOSYSTEM_FILE)} (${eco.nodes.length} nodes, ${eco.edges.length} edges)`, ); } return process.stdout.write(out); } case 'stats': return emit(stats(graph), (s) => `nodes ${s.nodes} | edges ${s.edges}\n` + `kinds ${JSON.stringify(s.byKind)}\n` + `edges ${JSON.stringify(s.byEdge)}\n` + `layers ${JSON.stringify(s.byLayer)}\n` + 'top hubs (most depended on):\n' + s.hubs.map((h) => ` ${String(h.dependents).padStart(3)} ${h.id}`).join('\n')); case 'history': { // The verb has NO write path, so a writing flag is rejected rather than // ignored. Silently dropping `--repair` would teach a caller that // `graph.js` can repair the index, and the next caller would rely on it. const writing = argv.filter((f) => WRITING_FLAGS.has(f)); if (writing.length) { console.error( `history never writes — ${writing.join(', ')} is not accepted.\n` + 'Run `node framwork/.codeadd/scripts/delivered.cjs verify --repair` instead.', ); process.exitCode = 2; return; } const h = history(graph, a, { limit, layer: valueOf('--layer') }); return emit(h, (r) => { if (r.unavailable) { return `history unavailable for ${r.node}: ${r.unavailable.reason} (${r.unavailable.detail})`; } if (!r.entries.length) return `no delivery recorded for ${r.node}`; // THE DEAD CAP MUST BE ANNOUNCED. This verb passes --limit 50, which // governs the core's LIVE bucket only; dead entries are capped at 2 // and no argument raises it. `history` exists to answer "was this // attempted before?", so a cut `gone` or `superseded` entry is the // answer it most needs to give — silence here would hide exactly what // the caller came for. const cut = Number(r.keys?.MATCHED_DEAD || 0) - Number(r.keys?.RETURNED_DEAD || 0); const note = cut > 0 ? `\n (dead cap: ${cut} more dead entr(ies) matched and were not shown)` : ''; return `${r.matched} delivery entr(ies) for ${r.node}:\n` + r.entries.map((e) => { const items = e.items .map((it) => ` ${it.what} (${it.at})` + (it.dependents === null || it.dependents === undefined ? '' : ` [${it.dependents} dependant(s)]`)) .join('\n'); return ` ${e.status.padEnd(10)} ${e.ts} ${e.id}\n` + ` ${e.name}` + (e.superseded_by ? `\n superseded by ${e.superseded_by}` : '') + `\n${items}`; }).join('\n') + note; }); } default: console.error(fs.readFileSync(__filename, 'utf8').split('\n').slice(2, 19).join('\n') .replace(/^ \* ?/gm, '')); process.exitCode = 2; } } if (require.main === module) main(process.argv.slice(2));