#!/usr/bin/env node /** * build.js - Compile provider files from .codeadd/ + framwork/provider-map.json * Usage: node scripts/build.js * * Architecture: * readMap() → loads provider-map.json (single source of truth) * stripHtmlComments → pure fn, removes + collapses blank lines * TRANSFORMERS → registry of format converters (md, toml, ...) * METADATA → registry of metadata generators (frontmatter, toml header, ...) * buildResources() → generic loop for any resource type (commands, skills) * resourceStrategies → per-type config (source path, resolve output, post-process) * * Transform references: framwork/.codeadd/transforms/{provider}/{resource}.md */ const fs = require('node:fs'); const path = require('node:path'); const crypto = require('node:crypto'); const ROOT = path.resolve(__dirname, '..'); // The doc format version is declared ONCE, in docs-root.cjs. The build reads that // constant through require() and never holds a second copy of the number. const { DOC_SCHEMA_VERSION } = require(path.join(ROOT, 'framwork', '.codeadd', 'scripts', 'docs-root.cjs')); // --------------------------------------------------------------------------- // I/O helpers (thin wrappers — keep logic out of here) // --------------------------------------------------------------------------- function readMap() { const map = JSON.parse(fs.readFileSync(path.join(ROOT, 'framwork', 'provider-map.json'), 'utf8')); assertProductNames(map); return map; } function assertProductNames(map) { for (const name of Object.keys(map.commands || {})) { if (!/^add-[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) { throw new Error(`Invalid product command name: ${name}`); } } for (const name of Object.keys(map.skills || {})) { if (!/^add--[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) { throw new Error(`Invalid product skill name: ${name}`); } } } function readFile(filePath) { return fs.readFileSync(filePath, 'utf8').replace(/\r\n/g, '\n'); } function writeFile(filePath, content) { fs.mkdirSync(path.dirname(filePath), { recursive: true }); fs.writeFileSync(filePath, content, 'utf8'); } function copyDirRecursive(src, dest, provider = null) { let count = 0; fs.mkdirSync(dest, { recursive: true }); for (const entry of fs.readdirSync(src, { withFileTypes: true })) { const srcPath = path.join(src, entry.name); const destPath = path.join(dest, entry.name); if (entry.isDirectory()) { count += copyDirRecursive(srcPath, destPath, provider); } else { // When a provider is supplied, transform markdown files (resolve {{cmd:}}, {{skill:}}, {{addpath:}}). // Used for skill sibling files; null provider preserves verbatim copy semantics for other callers. if (provider && entry.name.endsWith('.md')) { const raw = readFile(srcPath); lintResourcePaths(raw, srcPath); const cleaned = stripHtmlComments(raw); const resolved = resolveResourcePaths(cleaned, provider); writeFile(destPath, resolved); } else { fs.copyFileSync(srcPath, destPath); } count++; } } return count; } // --------------------------------------------------------------------------- // Pure transforms (no I/O, fully testable) // --------------------------------------------------------------------------- /** * Remove HTML comments and collapse excess blank lines (saves tokens). * * ALL comments strip uniformly — including `feature:`/`plugin:` injection * markers. The markers are consumed at build time by extractSlots() * into the content-anchored sidecar (injection-points.json); the built provider * files ship marker-free and post-install injection locates anchors by text. */ function stripHtmlComments(content) { // Scan rather than regex-replace so a leftover `', start + 4); if (end === -1) { i = start + 4; continue; } i = end + 3; } return out.replace(/\n{3,}/g, '\n\n').trim(); } // --------------------------------------------------------------------------- // Injection-point extraction (marker → content-anchor sidecar) // // Source files keep `` markers for authoring // ergonomics + exclusion-by-omission. At build time each OPEN marker is recorded // as an injection point anchored to the nearest surviving non-blank line above it // (identified by text + occurrence ordinal, so it survives per-provider frontmatter // offsets, line shifts, and most user edits). The markers are then stripped. // --------------------------------------------------------------------------- // Matches an OPEN injection marker (closers start with `/`). const OPEN_MARKER_RE = /^\s*(feature|plugin):([^:\s]+):(\S+?)\s*$/; const CLOSE_MARKER_RE = /^\s*\/(feature|plugin):([^:\s]+):(\S+?)\s*$/; const SLOT_OPEN_RE = /^\s*slot:([A-Za-z0-9][A-Za-z0-9.+_-]*)\s+fallback="([^"]+)"\s*$/; const SLOT_CLOSE_RE = /^\s*\/slot:([A-Za-z0-9][A-Za-z0-9.+_-]*)\s*$/; const SECTION_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; const SAFE_FALLBACK_RE = /^fallbacks\/[A-Za-z0-9][A-Za-z0-9._-]*\.md$/; // Resource-path variables that resolve differently per provider — illegal in an anchor. const ANCHOR_VARIABLE_RE = /\{\{(?:(?:cmd|skill|addpath):|doc-schema\}\})/; /** * A real injection marker stands alone on its line. A marker embedded in prose * (e.g. a `` shown inside a table cell or code span as * documentation) is NOT an injection point — only a comment to be stripped. * @param {string} raw full source * @param {number} start comment start index * @param {number} end comment end index (exclusive) * @returns {boolean} */ function isStandaloneMarker(raw, start, end) { const lineStart = raw.lastIndexOf('\n', start - 1) + 1; const lineEnd = raw.indexOf('\n', end); const before = raw.slice(lineStart, start); const after = raw.slice(end, lineEnd === -1 ? raw.length : lineEnd); return before.trim() === '' && after.trim() === ''; } /** * Split text into trimmed lines, dropping leading/trailing blank-only lines so * "nearest non-blank" math matches the post-strip installed body. * @param {string} text * @returns {string[]} non-empty trimmed lines, in order */ function nonBlankLines(text) { return text.split('\n').map((l) => l.trim()).filter((l) => l.length > 0); } /** * Parse a resource body, returning one injection point per OPEN marker. * Anchors are computed against the comment-stripped (but not blank-collapsed) * body, so ordinals match what the CLI counts in the installed file. * * @param {string} rawContent * @param {string} resourceName logical name (e.g. "add.build", "backend-agent") * @param {'command'|'agent'} resourceKind * @returns {Array<{namespace,name,section,resource:{name,kind},anchor:{text,ordinal,position,next}}>} * @throws if a chosen anchor line carries a {{cmd:}}/{{skill:}}/{{addpath:}} variable */ /** * Standalone feature/plugin pairs must be empty and balanced. Non-empty * content between markers ships in every provider baseline; an open without * a close is authoring drift. Prose-embedded markers are ignored. * @param {string} rawContent * @param {string} resourceName */ function assertEmptyMarkerPairs(rawContent, resourceName) { const commentRe = //g; const markers = []; let m; while ((m = commentRe.exec(rawContent)) !== null) { const start = m.index; const end = m.index + m[0].length; if (!isStandaloneMarker(rawContent, start, end)) continue; const line = rawContent.slice(0, start).split('\n').length; const open = m[1].match(OPEN_MARKER_RE); const close = m[1].match(CLOSE_MARKER_RE); if (open) { markers.push({ kind: 'open', ns: open[1], name: open[2], section: open[3], start, end, line }); } else if (close) { markers.push({ kind: 'close', ns: close[1], name: close[2], section: close[3], start, end, line }); } } for (let i = 0; i < markers.length; i++) { const mk = markers[i]; if (mk.kind !== 'open') continue; const key = `${mk.ns}:${mk.name}:${mk.section}`; const close = markers.slice(i + 1).find((c) => c.kind === 'close' && `${c.ns}:${c.name}:${c.section}` === key); if (!close) { throw new Error( `Unbalanced injection marker ${key} in ${resourceName}:${mk.line} — open has no close`, ); } if (rawContent.slice(mk.end, close.start).trim().length > 0) { throw new Error( `Non-empty injection pair ${key} in ${resourceName}:${mk.line} — marker pairs must be empty`, ); } } } function standaloneComments(rawContent) { const commentRe = //g; const found = []; let m; while ((m = commentRe.exec(rawContent)) !== null) { const start = m.index; const end = m.index + m[0].length; if (!isStandaloneMarker(rawContent, start, end)) continue; found.push({ body: m[1], start, end, line: rawContent.slice(0, start).split('\n').length, }); } return found; } function assertSafeFallbackPath(rel, resourceName, line) { if (typeof rel !== 'string' || rel !== rel.trim() || !SAFE_FALLBACK_RE.test(rel) || rel.includes('..') || path.isAbsolute(rel)) { throw new Error(`Unsafe fallback path ${JSON.stringify(rel)} in ${resourceName}:${line}`); } } /** * v1 when the resource has no standalone slot marker. v2 when it has any. * A member outside a slot, or a slot in a resource that also has bare members, * is a mixed source and throws from extractSlots. * @param {string} rawContent * @returns {'v1'|'v2'} */ function injectionMode(rawContent) { return standaloneComments(rawContent).some((c) => SLOT_OPEN_RE.test(c.body) || SLOT_CLOSE_RE.test(c.body)) ? 'v2' : 'v1'; } /** * Parse a fully slotted resource. Fallback bytes come from readFallback, so a * synthetic caller never touches product files. * @param {string} rawContent * @param {string} resourceName * @param {'command'|'agent'} resourceKind * @param {(rel: string) => string} readFallback */ function extractSlots(rawContent, resourceName, resourceKind, readFallback) { assertEmptyMarkerPairs(rawContent, resourceName); const comments = standaloneComments(rawContent); const slots = []; let open = null; const seenIds = new Set(); // A slot's region holds member markers and whitespace, nothing else. Both halves // are checked here rather than by filtering the region: `assertNoGap` catches // plain prose between two comments, and the final branch catches a comment that // is not a member marker. Filtering the region with a regex replacement is what // CodeQL flagged as incomplete sanitization. const assertNoGap = (o, nextStart, line) => { if (rawContent.slice(o.gapEnd, nextStart).trim()) { throw new Error(`Invalid slot ${o.id} in ${resourceName}:${line} — only member markers and whitespace are allowed`); } }; for (const c of comments) { const slotOpen = c.body.match(SLOT_OPEN_RE); const slotClose = c.body.match(SLOT_CLOSE_RE); const memberOpen = c.body.match(OPEN_MARKER_RE); const memberClose = c.body.match(CLOSE_MARKER_RE); if (open) assertNoGap(open, c.start, c.line); if (slotOpen) { if (open) { throw new Error(`Nested slot ${slotOpen[1]} in ${resourceName}:${c.line} — inside ${open.id}`); } if (seenIds.has(slotOpen[1])) { throw new Error(`Duplicate slot ${slotOpen[1]} in ${resourceName}:${c.line}`); } assertSafeFallbackPath(slotOpen[2], resourceName, c.line); seenIds.add(slotOpen[1]); open = { id: slotOpen[1], fallbackPath: slotOpen[2], line: c.line, start: c.start, end: c.end, gapEnd: c.end, members: [] }; continue; } if (slotClose) { if (!open || open.id !== slotClose[1]) { throw new Error(`Orphan slot close ${slotClose[1]} in ${resourceName}:${c.line}`); } if (open.members.length === 0) { throw new Error(`Orphan slot ${open.id} in ${resourceName}:${open.line} — no members`); } slots.push(open); open = null; continue; } if (memberOpen) { if (!SECTION_RE.test(memberOpen[3])) { throw new Error(`Unknown section ${memberOpen[3]} in ${resourceName}:${c.line}`); } if (!open) { throw new Error( `Mixed injection source in ${resourceName}:${c.line} — ${memberOpen[1]}:${memberOpen[2]}:${memberOpen[3]} is outside a slot`, ); } open.members.push({ namespace: memberOpen[1], name: memberOpen[2], section: memberOpen[3], line: c.line, start: c.start, }); open.gapEnd = c.end; continue; } if (memberClose) { if (!open) { throw new Error(`Mixed injection source in ${resourceName}:${c.line} — close marker outside a slot`); } open.gapEnd = c.end; continue; } if (open) { throw new Error(`Invalid slot ${open.id} in ${resourceName}:${open.line} — only member markers and whitespace are allowed`); } } if (open) { throw new Error(`Unclosed slot ${open.id} in ${resourceName}:${open.line}`); } let surviving = ''; let lastIndex = 0; const commentRe = //g; let m; const opens = []; while ((m = commentRe.exec(rawContent)) !== null) { surviving += rawContent.slice(lastIndex, m.index); lastIndex = m.index + m[0].length; if (isStandaloneMarker(rawContent, m.index, lastIndex) && SLOT_OPEN_RE.test(m[1])) { opens.push(surviving.length); } } surviving += rawContent.slice(lastIndex); const anchored = slots.map((slot, i) => { let fallback; try { fallback = readFallback(slot.fallbackPath); } catch (err) { throw new Error(`Missing fallback ${slot.fallbackPath} for slot ${slot.id} in ${resourceName}:${slot.line} — ${err.message}`); } if (typeof fallback !== 'string') { throw new Error(`Missing fallback ${slot.fallbackPath} for slot ${slot.id} in ${resourceName}:${slot.line}`); } const anchor = anchorAt(surviving, opens[i], `${resourceName}:${slot.id}`); return { id: slot.id, resource: { name: resourceName, kind: resourceKind }, fallbackPath: slot.fallbackPath, fallback, members: slot.members.map(({ namespace, name, section }) => ({ namespace, name, section })), anchor, }; }); const seenAnchor = new Set(); for (const slot of anchored) { const key = `${slot.anchor.position}\0${slot.anchor.ordinal}\0${slot.anchor.text}`; if (seenAnchor.has(key)) { throw new Error(`Ambiguous anchor for slot ${slot.id} in ${resourceName} — ${slot.anchor.text}`); } seenAnchor.add(key); } return anchored; } function anchorAt(surviving, survivingPos, label) { const above = nonBlankLines(surviving.slice(0, survivingPos)); const below = nonBlankLines(surviving.slice(survivingPos)); let text = null; let position; let ordinal; let next = null; let aboveIdx = -1; for (let k = above.length - 1; k >= 0; k--) { if (!ANCHOR_VARIABLE_RE.test(above[k])) { aboveIdx = k; break; } } if (aboveIdx !== -1) { text = above[aboveIdx]; position = 'after'; ordinal = above.slice(0, aboveIdx + 1).filter((l) => l === text).length; const walked = aboveIdx !== above.length - 1; next = !walked && below.length > 0 && !ANCHOR_VARIABLE_RE.test(below[0]) ? below[0] : null; } else { const belowIdx = below.findIndex((l) => !ANCHOR_VARIABLE_RE.test(l)); if (belowIdx !== -1) { text = below[belowIdx]; position = 'before'; ordinal = above.filter((l) => l === text).length + below.slice(0, belowIdx + 1).filter((l) => l === text).length; } } if (text == null) { throw new Error(`No variable-free anchor for ${label} — every adjacent line resolves a resource-path variable.`); } return { text, ordinal, position, next }; } // Build-run accumulator (reset per build). let INJECTION_SLOTS = []; let INJECTION_MODE = null; // Reads one fallback file and lints it like any other authored source: a // fallback is installed text, so a raw .codeadd/ path in it is as wrong as in // a command. The returned bytes are the lint's input, never its output. function readFallbackFile(full) { const raw = fs.readFileSync(full, 'utf8'); lintResourcePaths(raw, full); return raw.replace(/\r\n/g, '\n').replace(/\n$/, ''); } function readProductFallback(rel) { assertSafeFallbackPath(rel, 'fallback', 0); const full = path.join(CODEADD_DIR, rel); if (!fs.existsSync(full)) throw new Error(`file not found: ${rel}`); return readFallbackFile(full); } // A provider the CLI cannot inject into (codex, antigravity, zcode: no commandsSubdir in // cli/src/providers.js, flagged `featureInjection: false` in provider-map.json) never runs a slot's // renderer, so a slot left empty in its build output would silently drop what the command used to // say inline. For those providers the build writes an agent-mode slot's FALLBACK in place, which is // what the CLI writes for every other provider when the feature is off. Only agent-mode.* slots are // baked: their fallbacks carry text the command held before the feature existed. Every other // slot's fallback is empty or an installer-time line, and stays exactly as it was. const BAKED_SLOT_RE = /(?<=\n)(?:[ \t]*\n)*[ \t]*[\s\S]*?[ \t]*\n(?:[ \t]*\n)*/g; /** * @param {string} rawContent the command source, markers included * @param {string} resourceName * @returns {string} the source with every agent-mode slot replaced by its fallback text */ function bakeSlotFallbacks(rawContent, resourceName) { return rawContent.replace(/\r\n/g, '\n').replace(BAKED_SLOT_RE, (_match, id, rel) => { const text = readProductFallback(rel); const slot = INJECTION_SLOTS.find((x) => x.id === id && x.resource.name === resourceName); if (!slot) throw new Error(`bakeSlotFallbacks: no extracted slot ${id} for ${resourceName}`); if (text === '') return ''; const block = text.endsWith('\n') ? text : `${text}\n`; // An insertion-only slot (no `next` anchor line) leaves the pristine blank line in place. return slot.anchor.next == null ? `${block}\n` : block; }); } /** * Extract + accumulate injection points for one resource body. * @param {string} rawContent * @param {string} resourceName * @param {'command'|'agent'} resourceKind */ function collectInjectionPoints(rawContent, resourceName, resourceKind) { const comments = standaloneComments(rawContent); const hasMember = comments.some((c) => OPEN_MARKER_RE.test(c.body)); const mode = injectionMode(rawContent); if (!hasMember && mode === 'v1') return; if (INJECTION_MODE && INJECTION_MODE !== mode) { throw new Error(`Mixed injection source: ${resourceName} is ${mode} but this build already saw ${INJECTION_MODE}`); } INJECTION_MODE = mode; if (mode === 'v1') { throw new Error(`Legacy injection markers in ${resourceName} are not accepted. Wrap them in a slot.`); } INJECTION_SLOTS.push(...extractSlots(rawContent, resourceName, resourceKind, readProductFallback)); } /** * Write the sidecar map. Stable sort by (kind, name) for clean diffs while * preserving source-encounter order within a resource (needed for clustered * markers that share an anchor). * @param {string} outPath * @returns {number} number of points written */ function writeInjectionPoints(outPath) { const slots = INJECTION_SLOTS .map((s, i) => ({ s, i })) .sort((a, b) => { const ak = a.s.resource.kind, bk = b.s.resource.kind; if (ak !== bk) return ak < bk ? -1 : 1; const an = a.s.resource.name, bn = b.s.resource.name; if (an !== bn) return an < bn ? -1 : 1; return a.i - b.i; }) .map(({ s }) => s); const points = slots.flatMap((slot) => slot.members.map((m) => ({ namespace: m.namespace, name: m.name, section: m.section, resource: slot.resource, anchor: slot.anchor, }))); writeFile(outPath, JSON.stringify({ version: 2, slots, points }, null, 2) + '\n'); return slots.length; } // --------------------------------------------------------------------------- // Setup contracts (source-declared → build-extracted sidecar) // // A command that materializes state into the user's project declares a // "## Materializes" H2. That block is the SINGLE source of every shape the // command writes; `shape` is a hand-declared hash of it, recomputed here so a // changed shape cannot ship silently. The build has no previous shape to diff // against — the declared value IS the baseline. Identity is the hash: there // is no version integer and no recipe chain. // --------------------------------------------------------------------------- const CONTRACT_HEADING_RE = /^## Materializes[ \t]*$/m; // A RESOLVABLE resource-path variable — anything resolveResourcePaths() would // substitute. Its three patterns each require [^}]+, so this mirrors them exactly: // one or more characters after the colon. The ONLY tolerated form is the exactly // empty `{{cmd:}}` / `{{skill:}}` / `{{addpath:}}`, which matches no resolver, // ships identically to every provider, and is how the block's own prose documents // this ban — banning it would leave the declaration unable to describe itself. // Do NOT relax this to [^}\s]+: `{{cmd: add.plan}}` DOES resolve (to a path with a // leading space) and must stay banned. const CONTRACT_VARIABLE_RE = /\{\{(?:(?:cmd|skill|addpath):[^}]+|doc-schema)\}\}/; const SHAPE_LINE_RE = /^shape:[ \t]*\S+[ \t]*$/; // `changed-in:` is the version that ships the current shape. Hand-declared like // `shape:` and excluded from the hash the same way — it describes the shape, it // is not part of what the command materializes. const CHANGED_IN_LINE_RE = /^changed-in:[ \t]*\S+[ \t]*$/; const SEMVER_RE = /^\d+\.\d+\.\d+$/; // Backticks OR tildes. A `~~~`-fenced example of a `uses:` block — the form // used when the example itself contains backticks — would otherwise be // extracted as a real declaration. const FENCE_RE = /^[ \t]*(`{3,}|~{3,})/; /** Default `.codeadd` root; overridable so tests can supply a throwaway tree. */ const CODEADD_DIR = path.join(ROOT, 'framwork', '.codeadd'); /** * Slice the "## Materializes" block: everything after the heading up to the next * H2 that lies OUTSIDE every fenced code block, with HTML comments removed. * * Fence-awareness is load-bearing, not tidiness. The declaration embeds a fenced * markdown template carrying its own H2s (`## Conventions`, `## Managed App * Lifecycle`, `## Auth / Seed`). A naive `^## ` scan ends the block at the first * of them, and everything below silently stops participating in BOTH the shape * hash (drift ships green) and the resource-path-variable ban. * * @returns {string|null} the block, or null when the command declares none */ function sliceContractBlock(rawContent) { const m = CONTRACT_HEADING_RE.exec(rawContent); if (!m) return null; const lines = rawContent.slice(m.index + m[0].length).split('\n'); let openFence = 0; // backtick count of the open fence; 0 when none is open let end = lines.length; for (let i = 0; i < lines.length; i++) { const fence = FENCE_RE.exec(lines[i]); if (fence) { // Standard markdown: a fence closes on a run at least as long as the one // that opened it. So an embedded template must open with MORE backticks // than any fence it contains — a 3-backtick inner fence closes a // 3-backtick outer one, which would truncate the block here. if (openFence === 0) openFence = fence[1].length; else if (fence[1].length >= openFence) openFence = 0; continue; } if (openFence === 0 && /^## /.test(lines[i])) { end = i; break; } } return stripHtmlComments(lines.slice(0, end).join('\n')); } /** * Canonical form hashed by `shape`: the block minus its own `shape:` line, with * per-line trailing whitespace removed. Changing any declared character — * including inside a fence — must move the hash. * * Blank-line normalization is NOT repeated here: sliceContractBlock already runs * stripHtmlComments, which collapses 3+ newlines and trims. A duplicate trim on * this side was unreachable (contractShape is only ever fed sliced output) and * read as the enforcing code while a test could not isolate it. */ function canonicalContractBody(block) { // Drop only the FIRST `shape:` line — the declaration's own. A `shape:` line // at column 0 inside an embedded template is declared content: excluding it // would make it invisible to drift detection. `changed-in:` follows the same // first-line-only rule for the same reason. let shapeDropped = false; let changedInDropped = false; return block .split('\n') .filter((l) => { if (!shapeDropped && SHAPE_LINE_RE.test(l)) { shapeDropped = true; return false; } if (!changedInDropped && CHANGED_IN_LINE_RE.test(l)) { changedInDropped = true; return false; } return true; }) .map((l) => l.replace(/[ \t\r]+$/, '')) .join('\n'); } /** sha256: — short enough to hand-paste, unique enough to gate. */ function contractShape(block) { const hex = crypto.createHash('sha256').update(canonicalContractBody(block), 'utf8').digest('hex'); return `sha256:${hex.slice(0, 16)}`; } /** * Read the YAML preamble of a "## Materializes" block. Deliberately a hand-rolled * reader over the flat, fixed shape this contract declares — the build has no * YAML dependency and must not acquire one. */ function parseContractDeclaration(block) { const fence = block.match(/```yaml\r?\n([\s\S]*?)\r?\n```/); if (!fence) return null; const out = { paths: [] }; let current = null; for (const raw of fence[1].split('\n')) { const line = raw.replace(/[ \t\r]+$/, ''); if (!line.trim()) continue; const top = line.match(/^([a-z-]+):[ \t]*(.*)$/); if (top) { if (top[1] === 'paths') { current = null; continue; } out[top[1]] = top[2]; continue; } const item = line.match(/^[ \t]*-[ \t]*([a-z-]+):[ \t]*(.*)$/); if (item) { current = { [item[1]]: item[2] }; out.paths.push(current); continue; } const field = line.match(/^[ \t]+([a-z-]+):[ \t]*(.*)$/); if (field && current) current[field[1]] = field[2]; } return out; } /** * Extract + validate one command's contract. * @param {string} rawContent command source (pre-strip, markers intact) * @param {string} resourceName logical command name (e.g. "add.qa-setup") * @param {string} [_codeaddDir] unused; kept so existing call sites that pass a * throwaway `.codeadd` root keep working * @returns {object|null} { contract, shape, paths } or null * @throws on a resource-path variable in the block, a shape mismatch, or a missing field */ function extractContract(rawContent, resourceName, _codeaddDir = CODEADD_DIR) { const block = sliceContractBlock(rawContent); if (block === null) return null; if (CONTRACT_VARIABLE_RE.test(block)) { throw new Error( `Contract block in ${resourceName} carries a resource-path variable — ` + `{{cmd:}}/{{skill:}}/{{addpath:}}/{{doc-schema}} are variables and would produce a different shape ` + `per build target. Write the literal path inside "## Materializes".`, ); } const decl = parseContractDeclaration(block); if (!decl || !decl.contract || !decl.shape) { throw new Error( `Contract block in ${resourceName} is missing a required field — ` + `"contract" and "shape" are mandatory.`, ); } if (decl.contract !== resourceName) { throw new Error( `Contract block in ${resourceName} declares contract: ${decl.contract}. ` + `The sidecar is keyed by this value and both status.cjs and add-setup-contract ` + `look it up by command name — a mismatch keys the contract under a name nothing ` + `ever finds, leaving every project's staleness check silently blind.`, ); } for (const p of decl.paths) { if (!p.path || (p.owner !== 'setup' && p.owner !== 'shared')) { throw new Error( `Contract block in ${resourceName} declares a path without a "path" or with an ` + `owner outside {setup, shared}: ${JSON.stringify(p)}. A partially extracted ` + `contract is worse than none — it would ship as authoritative.`, ); } } const changedIn = decl['changed-in']; if (changedIn !== undefined && !SEMVER_RE.test(changedIn)) { throw new Error( `Contract block in ${resourceName} declares changed-in: ${changedIn}. ` + `The value is the version that ships the shape, written MAJOR.MINOR.PATCH.`, ); } const computed = contractShape(block); if (decl.shape !== computed) { throw new Error( `Contract shape changed in ${resourceName}.\n` + ` declared: ${decl.shape}\n computed: ${computed}\n` + `Set shape: ${computed} and changed-in: . ` + `Every installed project will need /add-qa-setup.`, ); } return { contract: decl.contract, shape: decl.shape, ...(changedIn !== undefined ? { changed_in: changedIn } : {}), paths: decl.paths, }; } // Build-run accumulator (reset per build). let CONTRACTS = {}; /** * Extract + accumulate one command's contract. Throws before anything is * accumulated, so a firing gate can never leave a half-built sidecar. */ function collectContract(rawContent, resourceName, codeaddDir = CODEADD_DIR) { const c = extractContract(rawContent, resourceName, codeaddDir); if (c) { // Unreachable by construction during a real build: the name gate above forces // c.contract to equal the provider-map.json key, and JSON keys are unique. // Kept as defence-in-depth for direct callers (and tests) — a silent overwrite // would ship a sidecar describing only one of two commands. if (Object.prototype.hasOwnProperty.call(CONTRACTS, c.contract)) { throw new Error( `Duplicate contract "${c.contract}" — two commands declare it. The second would ` + `silently overwrite the first, so the sidecar would describe only one of them.`, ); } CONTRACTS[c.contract] = { shape: c.shape, ...(c.changed_in !== undefined ? { changed_in: c.changed_in } : {}), paths: c.paths, }; } } /** * Write the contracts sidecar. Keys sorted for clean diffs + byte-identical * rebuilds from unchanged sources. * @returns {number} number of contracts written */ function writeContracts(outPath) { const sorted = {}; for (const k of Object.keys(CONTRACTS).sort()) sorted[k] = CONTRACTS[k]; writeFile(outPath, JSON.stringify({ version: 1, contracts: sorted }, null, 2) + '\n'); return Object.keys(sorted).length; } // --------------------------------------------------------------------------- // Artefact graph (source-declared → build-extracted sidecar) // // Every artefact may declare what it uses in a source-only `` // HTML comment. It is read from RAW content here, before stripHtmlComments() // runs, so the block never reaches a provider file — the same arrangement the // feature/plugin markers use. Nothing below adds stripping logic; adding any // would create a second implementation free to drift from the first. // // The declaration is build metadata, not an instruction: unlike // "## Materializes", the agent reading the command at runtime has no use for it, // and shipping it would cost tokens on every invocation of every command on // every provider. // --------------------------------------------------------------------------- /** Declaration kind → edge type. A kind absent here is a hard error. */ const USES_EDGE_TYPES = { skill: 'USES_SKILL', agent: 'DISPATCHES', command: 'HANDS_OFF_TO', // The next stage when that stage is not a command. `command:` resolves to a // command node only, so the internal pipeline — four skills handing off to // one another — had no way to say which out-edge is the next stage. The // target resolves by its own kind, with the sigils `mention:` already uses. handoff: 'HANDS_OFF_TO', script: 'RUNS_SCRIPT', // An acknowledged reference that is NOT a dependency. A name-matching sniffer // cannot tell "uses X" from "explicitly does not use X" — add-health-check's // only reference to add-security-audit is "Security-only audit (use // add-security-audit)", a pointer AWAY inside a list of when not to use the // skill. Declaring it `skill:` puts a false edge in the graph; omitting it // fails the build on correct prose once wave 2 hardens the sniff levels. // `mention:` is the third option, and it is a real edge: the graph gains the // fact, and the dangling gate validates the target like any other. mention: 'MENTIONS', }; /** `- : ` with an optional trailing `()`. */ const USES_ENTRY_RE = /^-\s+([A-Za-z]+)\s*:\s*(.+?)\s*(?:\(([^)]*)\))?\s*$/; /** * Kinds whose artefacts may carry a declaration block. * * `fragment` is here, and its absence was a real blind spot rather than an * oversight of taste. A fragment is injected INTO a command and carries * `DISPATCH AGENT:` headings of its own, so it names agents the way a command * does — but with `declares: false` the undeclared-reference gate skipped it * before ever reading its text. `@test-agent` is dispatched from two * tdd-pipeline fragments and from no command directly, so asking the graph who * dispatched it returned an answer that was confidently incomplete. * * `SNIFFABLE_KINDS` deliberately does NOT gain `fragment`. That set governs * being NAMED BY others, and nothing loads a fragment by name — the injection * marker does that. The two sets answer different questions. */ const DECLARING_KINDS = new Set(['command', 'skill', 'agent', 'fragment']); /** * Filenames under commands/ and agents/ that the build never transforms. * * The identity rule — a node is what the build can transform, never what sits * in the right folder — was first applied to skills only, via the SKILL.md * check. Commands and agents took every `*.md`, so a README documenting the * agents directory FAILED THE BUILD as an unregistered artefact. That is the * exact false-positive class the rule exists to prevent, on the two kinds it * did not cover. * * A leading `_` is the conventional "not a resource" prefix; README and NOTES * are the two that occur in practice. * * The name must match WHOLE, never as a prefix. A first version used * `/^README\b/i`, which matches `readme-analyzer.md` — `-` is a word boundary — * and silently dropped a real agent, breaking two commands that dispatch it. * A guard against false positives that introduces one is worse than no guard. */ const NON_ARTEFACT_FILE = /^(_|(README|NOTES|CHANGELOG)\.[A-Za-z0-9]+$)/i; /** * Character spans covered by fenced code blocks. * * A declaration shown inside a fence is documentation — a skill * teaching the convention, a plan quoting an example. Treating it as a * declaration invents edges out of prose, and those edges point at artefacts the * quoting file never actually uses. * * An unclosed fence swallows the rest of the file deliberately: that is what a * markdown renderer does, so the graph agrees with what a reader sees. * * @param {string} raw * @returns {Array<[number, number]>} [start, end) index pairs */ function fencedSpans(raw) { const spans = []; let open = 0; // backtick count of the open fence; 0 when none is open let spanStart = 0; let pos = 0; for (const line of raw.split('\n')) { const fence = FENCE_RE.exec(line); if (fence) { if (open === 0) { open = fence[1].length; spanStart = pos; } else if (fence[1].length >= open) { open = 0; spans.push([spanStart, pos + line.length]); } } pos += line.length + 1; // +1 for the newline consumed by split } if (open !== 0) spans.push([spanStart, raw.length]); return spans; } /** * Resolve a declaration target to a node id. * * A `skill:` target carrying a slash names a reference FILE, not the skill. The * author writes `skill:` because that is how they think about it; the resolver * decides the node kind. Collapsing the two would leave the dangling-reference * gate unable to tell a missing file from a missing skill. */ function usesTargetId(kind, target) { if (kind === 'mention' || kind === 'handoff') { // Reuses sigils the framework's prose already uses, so a mention is written // the way the thing is written where it was mentioned: // @reviewer-agent -> agent /add.plan -> command *.cjs -> script // anything else -> skill (much the commonest case) if (target.startsWith('@')) return `agent/${target.slice(1)}`; if (target.startsWith('/')) return `command/${target.slice(1)}`; if (/\.(?:sh|js|mjs|cjs)$/.test(target)) return `script/${target}`; return usesTargetId('skill', target); } if (kind === 'skill') { // `{{skill:NAME/SKILL.md}}` is how a source points at the SKILL itself, not // at a file beside it. SKILL.md files are skill nodes, so a bare // "contains a slash → reference" rule would resolve this to a node that // does not exist and fail the build on a correct declaration. const bare = target.replace(/\/SKILL\.md$/, ''); return bare.includes('/') ? `reference/${bare}` : `skill/${bare}`; } if (kind === 'command') return `command/${target.replace(/^\//, '')}`; return `${kind}/${target}`; } /** * Extract declared edges from one artefact body. * * @param {string} rawContent * @param {string} resourceName logical name (e.g. "add.build", "reviewer-agent") * @param {'command'|'skill'|'agent'} resourceKind * @returns {Array<{from,to,type,origin,modifier}>} * @throws on a malformed entry, an unknown kind, or a second declaration block */ function extractUses(rawContent, resourceName, resourceKind, layer = 'product') { const spans = fencedSpans(rawContent); const inFence = (i) => spans.some(([s, e]) => i >= s && i < e); const commentRe = //g; const blocks = []; let m; while ((m = commentRe.exec(rawContent)) !== null) { if (!/^[ \t]*uses:/.test(m[1])) continue; if (inFence(m.index)) continue; if (!isStandaloneMarker(rawContent, m.index, m.index + m[0].length)) continue; blocks.push(m); } if (blocks.length > 1) { throw new Error( `${resourceKind} "${resourceName}" declares ${blocks.length} \`uses:\` blocks. ` + `Only the first would be read, so the second's edges would vanish from the graph ` + `while still reading as declared in the source. Merge them into one block.`, ); } if (blocks.length === 0) return []; const block = blocks[0]; // Line of the `` block at all. Pointed at // either of them, extractUses returns [] with no error and no warning, // and the graph silently loses every internal edge. const claudeDir = path.join(internalDir, 'workbench'); // The four pipeline stages — add-framework--brainstorm, --plan, --build and // --done — are SKILLS, not commands: they hand off to one another, and a // skill is what the agent loads to continue. The skills walk below finds // them with no special case. This walk keeps the internal commands that are // not pipeline stages. for (const f of walkFiles(path.join(claudeDir, 'commands'), '.md').sort()) { if (NON_ARTEFACT_FILE.test(path.basename(f))) continue; push('command', 'internal', path.basename(f, '.md'), f, true, []); } const internalSkills = path.join(claudeDir, 'skills'); if (fs.existsSync(internalSkills)) { for (const d of fs.readdirSync(internalSkills, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) { if (!d.isDirectory()) continue; const skillFile = path.join(internalSkills, d.name, 'SKILL.md'); if (!fs.existsSync(skillFile)) continue; push('skill', 'internal', d.name, skillFile, true, []); for (const ref of walkFiles(path.join(internalSkills, d.name), '.md').sort()) { if (path.basename(ref) === 'SKILL.md') continue; push('reference', 'internal', relId(internalSkills, ref), ref, true, []); } } } for (const f of walkFiles(path.join(claudeDir, 'agents'), '.md').sort()) { if (NON_ARTEFACT_FILE.test(path.basename(f))) continue; push('agent', 'internal', path.basename(f, '.md'), f, true, []); } return nodes; } /** * The fragment FILE behind one injection point. * * Injection points record namespace + feature/plugin name + target resource, not * the fragment path. The path is a pure function of those three, and the layout * is fixed by the feature/plugin system: * * feature → fragments/{name}/{command}.md * plugin → plugins/{name}/fragments/{command}.md * plugin → plugins/{name}/fragments/agents/{agent}.md * * Reconstructing it wrongly yields an edge whose `from` points at nothing, and * nothing else in the build would notice — hence the endpoint-resolution level. */ function fragmentNodeName(point) { const { namespace, name, resource } = point; if (namespace === 'feature') return `fragments/${name}/${resource.name}.md`; return resource.kind === 'agent' ? `plugins/${name}/fragments/agents/${resource.name}.md` : `plugins/${name}/fragments/${resource.name}.md`; } /** * Assemble the graph: every node, plus declared edges and injection edges. * * Declarations are read from disk per declaring node rather than accumulated * during buildResources(). That is deliberate: buildResources() only iterates * REGISTERED resources, so an unregistered artefact would never be visited — and * an unregistered artefact is exactly what the gate exists to find. * * @param {object} map provider-map.json * @param {string} codeaddDir * @param {string} internalDir * @param {Array} points injection points; defaults to this build's accumulator * @returns {{nodes: Array, edges: Array}} */ function buildArtefactGraph(map, codeaddDir = CODEADD_DIR, internalDir = ROOT, points = []) { const nodes = collectNodes(map, codeaddDir, internalDir); const edges = []; for (const n of nodes) { if (!n.declares) continue; edges.push(...extractUses(readFile(path.join(ROOT, n.path)), n.name, n.kind, n.layer)); } // Container ownership, derived from the path prefix — a feature or a plugin // CONTAINS every node that lives inside its directory. Derived here rather // than declared, exactly like INJECTS_INTO below: nothing writes a `uses:` // block for a directory, and the layout is the fact. // // ⛔ `CONTAINS` MUST NOT reach the orphans calculation. `orphans()` builds its // "depended" set from DEPENDENCY_TYPES membership, so a container owning every // file beneath it would give each one a permanent inbound dependency — and // NOTHING under `fragments/` or `plugins/` could ever be reported as dead // weight again. `scripts/graph.js` and `mcp/engine.mjs` each keep a separate // ORPHAN_DEPENDENCY_TYPES that excludes it. for (const c of nodes.filter((n) => n.kind === 'feature' || n.kind === 'plugin')) { const prefix = `${c.path}/`; for (const m of nodes) { if (m.id === c.id || !m.path.startsWith(prefix)) continue; edges.push({ from: c.id, to: m.id, type: 'CONTAINS', origin: 'layout', modifier: null }); } } // One edge per point, not per (fragment, target) pair: a fragment with three // sections injects three times, and collapsing them would lose which section // landed where. for (const p of points) { edges.push({ from: `product/fragment/${fragmentNodeName(p)}`, to: `product/${p.resource.kind}/${p.resource.name}`, type: 'INJECTS_INTO', origin: 'sidecar', modifier: `${p.namespace}:${p.name}:${p.section}`, }); } return { nodes, edges }; } /** Total order over edges — stable output is what makes a graph diffable. */ function edgeSortKey(e) { // Joined on U+001F (unit separator) written as an ESCAPE, never as a raw // byte. A raw control character is invisible in every editor and diff, so a // careless edit destroys it silently. It cannot occur in an id or a // modifier, so unlike a space it cannot let two edges collide on one key. return [e.from, e.type, e.to, e.modifier ?? ''].join('\u001f'); } /** * Write the artefact-graph sidecar. Sorted for clean diffs and byte-identical * rebuilds from unchanged sources; no timestamp, for the same reason. * @returns {{nodes: number, edges: number}} */ function writeArtefactGraph(outPath, graph) { const cmp = (a, b) => (a < b ? -1 : a > b ? 1 : 0); const nodes = [...graph.nodes].sort((a, b) => cmp(a.id, b.id)); const edges = [...graph.edges].sort((a, b) => cmp(edgeSortKey(a), edgeSortKey(b))); writeFile(outPath, JSON.stringify({ version: 1, nodes, edges }, null, 2) + '\n'); return { nodes: nodes.length, edges: edges.length }; } // --------------------------------------------------------------------------- // Artefact graph guard // // Three levels, and the SPLIT matters more than the checks. The two hard gates // compare declarations against the filesystem and the registry, where no // false-positive path exists. The two sniff levels compare declarations against // PROSE, which is measurably unreliable — three crude probes written while // specifying this change each produced wrong answers. A gate that cries wolf is // a gate someone switches off, so sniffing warns and never fails. // // The sniff levels become failures in wave 2, once all 97 artefacts declare. // Shipping them as failures now would block every build in the repo. // --------------------------------------------------------------------------- /** Kinds a prose sniffer can look for. Fragment names are paths; prose never carries them. */ const SNIFFABLE_KINDS = new Set(['command', 'skill', 'agent', 'script', 'reference']); function escapeRe(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } /** * Match a name only when it stands alone. * * Both guards are load-bearing. Under a naive `\b`, `/add` matches inside * `/add.plan` (`.` is a word boundary) and `add-qa` matches inside * `add-qa-migration`. Those two mistakes produced a 43× overcount and 11 false * orphans out of 13 in the probes that motivated this work. */ function mentionRe(name) { return new RegExp(`(?/g, ''); // Splice from the end so earlier removals do not shift later spans. for (const [s, e] of fencedSpans(out).reverse()) out = out.slice(0, s) + out.slice(e); return out; } /** * Check a graph. Returns findings; throwing is the caller's job. * * Returning instead of throwing is what lets the suite assert on BOTH lists * without catching, and what keeps "fails" and "warns" from collapsing into one * another by accident. * * @param {{nodes: Array, edges: Array}} graph * @param {{readSource?: (node) => string}} opts * @returns {{failures: string[], warnings: string[]}} */ function checkArtefactGraph(graph, { readSource, productRoot = readSource ? null : ROOT } = {}) { const read = readSource || ((n) => { try { return readFile(path.join(ROOT, n.path)); } catch { return ''; } }); const byId = new Map(graph.nodes.map((n) => [n.id, n])); const failures = []; const warnings = []; // --- FAIL: a declaration names something that does not exist --------------- for (const e of graph.edges) { if (e.origin !== 'declared' || byId.has(e.to)) continue; failures.push( 'artefact-graph: dangling reference\n' + ` ${byId.get(e.from)?.path ?? e.from}\n` + ` declares ${e.to}\n` + ' no such artefact. Fix the name, or add the file.', ); } // --- FAIL: on disk, absent from the registry, therefore built for nobody --- for (const n of graph.nodes) { if (!n.declares || n.registered) continue; failures.push( 'artefact-graph: unregistered artefact\n' + ` ${n.path}\n` + ' exists on disk, absent from framwork/provider-map.json → never built for any provider\n' + ` add an entry under "${n.kind}s", or delete the file.`, ); } // --- WARN: declaration vs prose, both directions --------------------------- // Both dependency edges AND `mention:` acknowledgements count as "declared" // for the sniff levels: the point of a mention is to say "yes, that name is // in my prose on purpose, and no, I do not depend on it". const declaredFrom = new Map(); for (const e of graph.edges) { if (e.origin !== 'declared') continue; if (!declaredFrom.has(e.from)) declaredFrom.set(e.from, new Map()); declaredFrom.get(e.from).set(e.to, { modifier: e.modifier, type: e.type }); } const sniffable = graph.nodes.filter((n) => SNIFFABLE_KINDS.has(n.kind)); // --- FAIL: a distributed artefact naming a workbench command --------------- // // THE WORKBENCH NOW HAS PROVIDER OUTPUT, AND THIS GATE IS UNCHANGED BY IT. // `scripts/build-workbench.js` compiles `workbench/` into `.claude/`, // `.opencode/`, `.agents/` and `.codex/` at the REPOSITORY root. That is a // provider mirror, and it used // to be this layer's defining absence -- so a reader meeting the gate after // that change can reasonably wonder whether it still holds. // // It does, because its reason was never 'the internal layer is not built'. // Its reason is that an artefact reaching a USER'S project must not point them // at something their install does not contain, and nothing under `workbench/` // is in `framwork/provider-map.json`, packaged by `release.yml`, or written by // `cli/src/installer.js`. Building it for three providers inside this // repository changes none of those three. // // DO NOT weaken or remove this gate on the grounds that the workbench 'is // distributed now'. It is built; it is not distributed. // // The same-layer sniff below is deliberately blind here: `add-commit` exists // in both layers, so a product artefact naming it means the product one. That // skip leaves exactly one direction unwatched, and it is the direction that // SHIPS — a `framwork/.codeadd/` artefact reaching a user's project while // pointing them at a command only this repository has. Not hypothetical: // `add-plan-review` told five providers' users not to confuse its review with // an internal command they do not have. // // Three things this check does NOT do, each learned from an audit of its own // first version: // // 1. It does not iterate internal command NODES. The line that motivated the // gate named a command that the very same delivery deleted, so a node walk // was blind to the one case it existed for. It matches the namespace, so a // removed command is caught like a live one — which is the worse case, not // the exempt one. // 2. It does not sit behind `if (!n.declares)`. Scripts and reference subdocs // carry no `uses:` block and ship verbatim, which makes them the artefacts // that reach a user's project most literally. // 3. It does not warn. `assertArtefactGraph` prints warnings as a bare count // unless ADD_GRAPH_WARNINGS is set, and nothing in CI sets it. The hard // gate below is reserved for "the name is right there, so the fix is // mechanical" — which is this case exactly, and unlike the sibling warning // it has no legitimate waiver: no distributed artefact has a reason to name // an internal command. // // The reverse direction stays open on purpose. `/add-framework--done` names // `delivered.cjs` because a cross-layer `uses:` target resolves inside the // declaring artefact's own layer and would dangle, leaving the prose mention // as the only way to write it. // 4. It does not read `proseOf()`. That helper answers "what did the author // write about other artefacts", and for this gate it is wrong in BOTH // directions. It keeps HTML comments other than `uses:`, which the build // strips and which therefore never ship — so a source-only note explaining // a cross-layer name would FAIL the build for text no user can ever read. // And it removes fenced blocks, which DO ship — so a command name in an // example invocation, the likeliest place for one, passed clean. The // shipped text is what `stripHtmlComments` leaves, so that is what is read. // // It matches the NAMESPACE, not one artefact kind. Four of its members — // the pipeline stages brainstorm, plan, build and done — are skills, the // rest commands, and the regex reaches both because it never resolves a // node. The double dash is load-bearing: the stage skills keep it so this // match still reaches them, and a single-dash rename would take them out // of the gate in silence. const INTERNAL_COMMAND_NS = /(? { for (const name of new Set(text.match(INTERNAL_COMMAND_NS) ?? [])) { failures.push( 'artefact-graph: internal command or skill named by a distributed artefact\n' + ` ${path_}\n` + ` names ${name}, which is in the workbench add-framework-- namespace, built for this repository only\n` + ' a user installing this artefact has no such command or skill. Describe the\n' + ' distinction without the name, or name the product equivalent.\n' + ' A source-only note is exempt: HTML comments are stripped at build.', ); } }; for (const n of graph.nodes) { if (n.layer !== 'product') continue; flagCrossLayer(n.path, stripHtmlComments(read(n))); } // 5. This sweep used to be the ONLY thing that could see three classes, // because none of them was a graph node: `templates/`, `transforms/` and a // plugin's own `skills/`. Two of the three now are — `collectNodes` walks // plugin skills as `skill` nodes and templates as a `template` kind — so // for those two this walk is a second look at files the node walk above // already covered. Harmless and kept: a cross-layer name is cheap to check // twice, and narrowing the list is a behaviour change, not a comment fix. // // `transforms/` is the one genuinely still invisible, and it is invisible // ON PURPOSE. It does NOT ship: `release.yml` packages `.codeadd/scripts`, // `fragments`, `templates` and `plugins` — not `transforms`. It is // build-time input, like `provider-map.json`, so it is no more a // distributed artefact than the registry is. (The previous wording called // all three "shipped classes" and credited SHIPPED_SUBDIRS with copying // them; that constant feeds the raw-path linter, and does not list // `transforms` either.) // // `productRoot` is absent when a caller passes a synthetic graph, and that // is the only case this sweep is skipped. if (productRoot) { const walk = (dir) => { let entries; try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; } for (const e of entries) { const full = path.join(dir, e.name); if (e.isDirectory()) { walk(full); continue; } if (!/\.(md|sh|json)$/.test(e.name)) continue; let text; try { text = fs.readFileSync(full, 'utf8'); } catch { continue; } flagCrossLayer(path.relative(productRoot, full).split(path.sep).join('/'), stripHtmlComments(text)); } }; for (const sub of ['templates', 'transforms', 'plugins']) { walk(path.join(productRoot, 'framwork', '.codeadd', sub)); } } for (const n of graph.nodes) { if (!n.declares) continue; const prose = proseOf(read(n)); const declared = declaredFrom.get(n.id) ?? new Map(); const observed = new Set(); for (const t of sniffable) { // Same layer only: `add-commit` exists in both, and a product command // mentioning it means the product one. if (t.id === n.id || t.layer !== n.layer) continue; if (nodeMentionRe(t).test(prose)) { observed.add(t.id); continue; } // A skill links its OWN reference files relatively — `references/foo.md`, // not `add-qa/references/foo.md`. Matching only the node name reported // them as unreferenced, which put 48 files that are linked from the very // skill that owns them into `orphans`. Same failure the sniffer was built // to avoid, one level down. if (t.kind === 'reference' && n.kind === 'skill' && t.name.startsWith(`${n.name}/`)) { const relative = t.name.slice(n.name.length + 1); if (mentionRe(relative).test(prose)) observed.add(t.id); } } for (const id of observed) { if (declared.has(id)) continue; failures.push( 'artefact-graph: undeclared reference\n' + ` ${n.path}\n` + ` names ${id} in prose but declares no relationship to it\n` + ' add it to the `uses:` block — or, if the prose points AWAY from it\n' + ' ("use X instead", "do not use for"), add `- mention: `.', ); } for (const [id, { modifier, type }] of declared) { // `conditional` is the reserved waiver for a legitimate non-greppable // load. Free text is documentation, not a waiver. if (modifier === 'conditional' || observed.has(id)) continue; const t = byId.get(id); if (!t || !SNIFFABLE_KINDS.has(t.kind)) continue; // WARNING, not a failure, and the asymmetry is deliberate. // // "Named in prose but undeclared" is a hard gate: the name is right there, // so the fix is mechanical and the author knows what to write. // // This is the inverse — declared, never named. It is usually stale, but a // load that is genuinely real and simply not greppable also lands here, // and `(conditional)` is a valve with no field use yet, so its ergonomics // are unproven. Failing the build on an unproven valve trades a real // finding for a blocked build. It warns until the valve has been exercised. warnings.push( type === 'MENTIONS' ? `${n.path}: acknowledges ${id} with mention: but its prose no longer names it — ` + 'remove the entry, a stale acknowledgement silences a real finding later' : `${n.path}: declares ${id} but its prose never names it (phantom edge) — ` + 'remove it, or mark it (conditional) if the load is real but not greppable', ); } } return { failures, warnings }; } /** * Throw on failures; summarise warnings. * * The summary is deliberate. Wave 1 has ~97 artefacts declaring almost nothing, * so printing every sniff warning would bury the two hard gates under hundreds * of lines nobody can act on yet. Set ADD_GRAPH_WARNINGS=1 for the full list. */ function assertArtefactGraph(graph) { const { failures, warnings } = checkArtefactGraph(graph); if (warnings.length) { if (process.env.ADD_GRAPH_WARNINGS) for (const w of warnings) console.warn(` WARN ${w}`); else console.warn(` ${warnings.length} graph warning(s) — ADD_GRAPH_WARNINGS=1 to list`); } if (failures.length) throw new Error(`\n\n${failures.join('\n\n')}\n`); } // --------------------------------------------------------------------------- // Metadata generators (format-specific wrappers around content) // --------------------------------------------------------------------------- const METADATA = { /** YAML frontmatter for markdown-based providers */ mdFrontmatter(meta) { return meta.skillFormat ? `---\nname: ${meta.name}\ndescription: ${meta.description}\n---\n\n` : `---\ndescription: ${meta.description}\n---\n\n`; }, }; // --------------------------------------------------------------------------- // Transformer registry — keyed by nativeFormat from provider capabilities // // Each transformer: (content, meta) → final file content // Reference docs: framwork/.codeadd/transforms/{provider}/{resource}.md // --------------------------------------------------------------------------- const TRANSFORMERS = { /** Identity + frontmatter — all providers accept markdown as-is */ md(content, meta) { return METADATA.mdFrontmatter(meta) + content; }, }; // --------------------------------------------------------------------------- // Resource path resolution (build-time variable substitution) // --------------------------------------------------------------------------- /** * Resolve the one provider-independent doc-format variable. Shared by the * per-provider resolver and by the packaged-tree pass below, so there is one rule. * @param {string} content * @returns {string} */ function resolveDocSchema(content) { return content.replace(/\{\{doc-schema\}\}/g, String(DOC_SCHEMA_VERSION)); } /** * Resolve {{doc-schema}} in the trees that ship UNBUILT — .codeadd/{templates, * fragments,plugins,fallbacks,agent-mode}. release.yml packs them as authored, * so without this pass the token would reach a user's project and be copied into * a generated doc. It rewrites files in place, which is only right in a throwaway * checkout: `node scripts/build.js --package` (the release workflow) runs it, a * developer's plain build never does, and the tracked sources keep the token. * @param {string} codeaddDir the .codeadd directory to resolve in * @returns {number} files rewritten */ function resolvePackagedDocSchema(codeaddDir = CODEADD_DIR) { let changed = 0; const walk = (dir) => { if (!fs.existsSync(dir)) return; for (const e of fs.readdirSync(dir, { withFileTypes: true })) { const p = path.join(dir, e.name); if (e.isDirectory()) walk(p); else if (e.name.endsWith('.md')) { const raw = fs.readFileSync(p, 'utf8'); const out = resolveDocSchema(raw); if (out !== raw) { fs.writeFileSync(p, out, 'utf8'); changed++; } } } }; for (const sub of ['templates', 'fragments', 'plugins', 'fallbacks', 'agent-mode']) walk(path.join(codeaddDir, sub)); return changed; } /** * Resolve {{cmd:NAME}}, {{skill:NAME/FILE}}, {{addpath:X}} variables for a specific provider. * Scripts (.codeadd/scripts/) are fixed paths — no substitution needed. * * {{addpath:X}} resolves to literal `.codeadd/X` regardless of provider — used for * runtime paths that exist in the user's installed project (e.g. the wiki generated * by /add-wiki, manifest.json, runtime-only artefacts). * * @param {string} content raw content with variables * @param {object} provider provider config from provider-map.json * @returns {string} */ function resolveResourcePaths(content, provider) { const base = provider.dir.replace(/^framwork\//, ''); // {{cmd:NAME}} → full command path for this provider content = content.replace(/\{\{cmd:([^}]+)\}\}/g, (_, name) => { const resolved = provider.commands.replace('{name}', name); return `${base}/${resolved}`; }); // {{skill:NAME/FILE}} → full skill file path for this provider content = content.replace(/\{\{skill:([^/}]+)\/([^}]+)\}\}/g, (_, name, file) => { const skillDir = path.dirname(provider.skills.replace('{name}', name)); return `${base}/${skillDir}/${file}`; }); // {{addpath:X}} → literal .codeadd/X (provider-agnostic runtime path) content = content.replace(/\{\{addpath:([^}]+)\}\}/g, (_, sub) => `.codeadd/${sub}`); // {{doc-schema}} → DOC_SCHEMA_VERSION from docs-root.cjs (provider-independent, like addpath) content = resolveDocSchema(content); return content; } /** * Warn if source content contains raw .codeadd/commands/ or .codeadd/skills/ paths. * These should use {{cmd:}}, {{skill:}}, or {{addpath:}} variables instead. * Skips lines inside fenced code blocks (``` ... ```). * * @param {string} content source file content * @param {string} srcPath path for warning messages */ const LINTED_PATHS = new Set(); function lintResourcePaths(content, srcPath) { const relPath = path.relative(ROOT, srcPath); // Skip the resource-path-convention skill itself (it documents the patterns) if (relPath.includes('add--resource-path-convention') || relPath.includes('add-resource-path-convention')) return; // Skip the workbench layer, for the same reason and a second one. // // The rule this lint enforces exists because `.codeadd/` does not exist in a // user's installed project, so a raw path there resolves to nothing. The // workbench reaches no user's project, and its artefacts are the ones that // DOCUMENT the product layer: add-framework-development spells out the lint // rule itself, and add-framework-product-layer describes where product // resources live. Those strings are prose about a path, not a reference to // resolve — and `{{cmd:}}` inside a workbench artefact would resolve against // the WORKBENCH registry, to `.claude/commands/`, which is a different file. // // Regression this prevents: 13 warnings on every `build-workbench.js` run, // none of them actionable, which is how a warning stream stops being read. if (relPath.startsWith('workbench' + path.sep) || relPath.startsWith('workbench/')) return; // Lint each source file at most once per build (postWrite invokes per provider) if (LINTED_PATHS.has(relPath)) return; LINTED_PATHS.add(relPath); const lines = content.split('\n'); let inCodeBlock = false; for (let i = 0; i < lines.length; i++) { const line = lines[i]; if (/^```/.test(line.trim())) { inCodeBlock = !inCodeBlock; continue; } if (inCodeBlock) continue; if (/\.codeadd\/commands\//.test(line)) { console.warn(` LINT ${relPath}:${i + 1}: raw .codeadd/commands/ reference — use {{cmd:NAME}} or {{addpath:commands/NAME.md}}`); } if (/\.codeadd\/skills\//.test(line)) { console.warn(` LINT ${relPath}:${i + 1}: raw .codeadd/skills/ reference — use {{skill:NAME/FILE}} or {{addpath:skills/NAME/...}}`); } } // The doc format version is never a literal in markdown source — fenced examples included. const allLines = content.split('\n'); for (let i = 0; i < allLines.length; i++) { if (/\bschema:[ \t]*\d/.test(allLines[i])) { console.warn(` LINT ${relPath}:${i + 1}: literal schema number — use {{doc-schema}}`); } } } // --------------------------------------------------------------------------- // Shipped-surface source guard // // Everything under the trees below lands verbatim in a consumer's repository: // release.yml packages .codeadd/{scripts,fragments,templates,plugins} plus every // provider dir, and the installer unpacks them into the project root. A file the // consumer's toolchain recognises as source therefore becomes their CI failure, // and we control neither their ruleset nor their formatter config — so silencing // today's warnings only postpones the next one. Ship prose, shell and data — and // a `.cjs` only when it sits directly under `scripts/` and is built-ins-only. // // Regression this exists to prevent: v0.7.1 shipped // skills/add-skill-creator/render-graphs.js (an unreferenced upstream orphan), // which reddened `biome lint` and `biome format` repo-wide for every installer. // --------------------------------------------------------------------------- const LINTABLE_EXTENSIONS = new Set([ '.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts', '.css', '.scss', '.sass', '.less', '.vue', '.svelte', ]); // .json is deliberately absent: contracts.json and injection-points.json are // shipped by design, and JSON only ever trips a formatter's indent preference, // never a lint rule. const SHIPPED_SUBDIRS = ['scripts', 'fragments', 'templates', 'plugins']; // Exact allowlist for shipped exceptions the built-ins-only RULE below cannot // admit. The native runtime is admitted by the rule, not by path — the shared // cores qualify on their own merits — so this set names only files that must // ship yet cannot pass that rule. Each entry is an unanalysed hole, so adding // one is the last resort, never the first; the rationale is recorded inline. const SHIPPED_SOURCE_ALLOWLIST = new Set([ // Probes the PROJECT's optional @playwright/test through require.resolve and // createRequire, so its specifier is dynamic by nature — built-ins-only // cannot admit it, yet QA setup requires the probe. The only entry. 'framwork/.codeadd/scripts/qa-preflight.cjs', ]); // What a native shipped `.cjs` may require: a `node:` builtin, or a `./` // sibling `.cjs` in the SAME directory. Anything else — a bare package name, a // path that walks out with `../`, a nested `./dir/file.cjs`, a non-`.cjs` // sibling — is outside the closure. const NATIVE_BUILTIN_RE = /^node:[A-Za-z0-9_./-]+$/; const NATIVE_SIBLING_RE = /^\.\/[A-Za-z0-9._-]+\.cjs$/; // Bare builtin spellings (`fs`, `path`, …) are built-ins too, and a shipped // `.cjs` may use either form. Resolved against Node's own list rather than a // hand-maintained one, so a new builtin is admitted without a build.js edit. const BUILTIN_SPECIFIERS = new Set([ ...require('node:module').builtinModules, ...require('node:module').builtinModules.map((m) => `node:${m}`), ]); /** A builtin under either spelling. */ function isBuiltinSpecifier(spec) { return NATIVE_BUILTIN_RE.test(spec) || BUILTIN_SPECIFIERS.has(spec); } /** * Every static module specifier in a CommonJS source, plus whether any was * written in a form this guard cannot verify. Three forms are unverifiable: a * dynamic `require(expr)` or `import(expr)`, and an indirect require — a * require factory invoked on a computed value, `createRequire(…)(expr)`, whose * specifier never appears as the argument of a `require(` call. An unverifiable * specifier is an offender: the point is that the closure be provable * statically. */ function moduleSpecifiers(source) { const specs = []; let unverifiable = false; const literal = (arg) => { const m = /^(['"])([^'"]+)\1$/.exec(arg.trim()); return m ? m[2] : null; }; // The first argument as a leading literal, ignoring any options object after // it — `require.resolve('@scope/pkg', { paths: […] })` still names a specifier. const leadingLiteral = (arg) => { const m = /^\s*(['"])([^'"]+)\1/.exec(arg); return m ? m[2] : null; }; for (const re of [/\brequire\s*\(([^)]*)\)/g, /\bimport\s*\(([^)]*)\)/g]) { let m; while ((m = re.exec(source))) { const spec = literal(m[1]); if (spec === null) unverifiable = true; else specs.push(spec); } } // `require.resolve(…)` names a specifier the `require(` scan never sees, // because `.resolve` sits between the name and the paren. The capture stops at // the first `)` — enough to read the leading literal, and a non-literal there // is unverifiable rather than silently ignored. { const re = /\brequire\s*\.\s*resolve\s*\(([^)]*)/g; let m; while ((m = re.exec(source))) { const spec = leadingLiteral(m[1]); if (spec === null) unverifiable = true; else specs.push(spec); } } // A require factory called on a value — `createRequire(…)(expr)`. The nested // call is the marker, and the whole file is unverifiable: the outer // invocation's specifier is invisible to the `require(` scan. An ALIASED // factory (`const r = createRequire(…); r('pkg')`) is beyond a static scan; // the closure admits no such indirection in the files it ships. if (/\bcreateRequire\s*\([^)]*\)\s*\(/.test(source)) unverifiable = true; // Static ESM form only: anchored to an import/export statement so the word // "from" inside ordinary prose or a string cannot be read as a specifier. for (const re of [/^\s*import\s+[^;\n]*?from\s*(['"])([^'"]+)\1/gm, /^\s*export\s+[^;\n]*?from\s*(['"])([^'"]+)\1/gm]) { let m; while ((m = re.exec(source))) specs.push(m[2]); } return { specs, unverifiable }; } /** Built-ins-only: `node:` builtins and `./` sibling `.cjs` files, nothing else. */ function isBuiltinsOnlyCjs(absPath) { let source; try { source = fs.readFileSync(absPath, 'utf8'); } catch { return false; } const { specs, unverifiable } = moduleSpecifiers(source); if (unverifiable) return false; return specs.every((s) => isBuiltinSpecifier(s) || NATIVE_SIBLING_RE.test(s)); } /** * A shipped `.cjs` is admitted only when it is a DIRECT child of the shipped * scripts directory and is built-ins-only. One level deep: a copy in a nested * directory keeps the basename but not the exemption. */ function isAllowedNativeScript(absPath, scriptsDir) { return path.extname(absPath).toLowerCase() === '.cjs' && path.dirname(absPath) === scriptsDir && isBuiltinsOnlyCjs(absPath); } function collectLintableSources(dir, offenders = [], options = {}) { const scriptsDir = options.scriptsDir ? path.resolve(options.scriptsDir) : null; if (!fs.existsSync(dir)) return offenders; for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const entryPath = path.join(dir, entry.name); if (entry.isDirectory()) { collectLintableSources(entryPath, offenders, options); } else if (LINTABLE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) { const absPath = path.resolve(entryPath); const relPath = path.relative(ROOT, absPath).split(path.sep).join('/'); if (SHIPPED_SOURCE_ALLOWLIST.has(relPath)) continue; if (scriptsDir && isAllowedNativeScript(absPath, scriptsDir)) continue; offenders.push(relPath); } } return offenders; } /** * Fail the build when a shipped tree carries a linter-visible source file. * * Skills are walked per registry entry rather than by listing the skills dir: * an unregistered directory is never built and never reaches a user, so * flagging it would block the build over a file nobody receives. */ function assertNoLintableSources(map, codeaddDir = CODEADD_DIR) { const offenders = []; const scriptsDir = path.resolve(path.join(codeaddDir, 'scripts')); for (const subdir of SHIPPED_SUBDIRS) { collectLintableSources(path.join(codeaddDir, subdir), offenders, { scriptsDir }); } for (const name of Object.keys(map.skills || {})) { collectLintableSources(path.join(codeaddDir, 'skills', name), offenders); } if (offenders.length === 0) return; const list = offenders.sort().map((f) => ` ${f}`).join('\n'); throw new Error( `Shipped tree carries linter-visible source file(s):\n${list}\n\n` + `These install into the consumer's repository and break their lint/format run.\n` + `Delete the file, or ship it as a built-ins-only .cjs directly under ` + `.codeadd/scripts/ (the rule above). A probe that legitimately needs an ` + `external specifier goes in SHIPPED_SOURCE_ALLOWLIST with a rationale — the last resort.`, ); } // --------------------------------------------------------------------------- // Generic resource builder // --------------------------------------------------------------------------- /** * Build all resources of a given type using a strategy object. * * Strategy shape: * entries(map) → Object.entries of the resource map * sourcePath(name) → absolute path to source file * providerPattern(provider) → pattern string from provider config (or null to skip) * resolveProviders(entry,map)→ array of provider keys * meta(name, entry, pattern) → metadata object for the transformer * getTransformer(format) → optional, returns format-specific transformer fn * postWrite(name, entry, provider, outDir) → optional, returns extra file count */ function buildResources(map, strategy) { let count = 0; for (const [name, entry] of strategy.entries(map)) { const srcPath = strategy.sourcePath(name); if (!fs.existsSync(srcPath)) { // A registered resource with no source is a registry/tree mismatch. For // agents that must fail loud: a silently missing agent file degrades every // named dispatch to a generic subagent with no signal that it happened. if (strategy.requireSource) { throw new Error( `Registered ${strategy.injectionKind || 'resource'} "${name}" has no source at ` + `${path.relative(ROOT, srcPath)}. Remove it from provider-map.json or add the file.`, ); } console.warn(` SKIP (not found): ${path.relative(ROOT, srcPath)}`); continue; } // Read + clean once per resource (not per provider) const raw = readFile(srcPath); lintResourcePaths(raw, srcPath); if (strategy.injectionKind) collectInjectionPoints(raw, name, strategy.injectionKind); // Commands only — skills and agents materialize nothing into a user's project. if (strategy.injectionKind === 'command') collectContract(raw, name); const cleaned = stripHtmlComments(raw); const baked = strategy.injectionKind === 'command' ? stripHtmlComments(bakeSlotFallbacks(raw, name)) : null; const providers = strategy.resolveProviders(entry, map); for (const key of providers) { const provider = map.providers[key]; const patternStr = strategy.providerPattern(provider); if (!patternStr) continue; const format = provider.capabilities?.nativeFormat || 'md'; const transformer = strategy.transform || TRANSFORMERS[format]; if (!transformer) { console.warn(` SKIP (unknown format "${format}"): ${key}`); continue; } // Resolve {{cmd:}}, {{skill:}} variables per provider. A provider the CLI cannot inject into // gets the agent-mode fallbacks written in place (see bakeSlotFallbacks). const withPaths = resolveResourcePaths(baked && provider.featureInjection === false ? baked : cleaned, provider); const resolved = patternStr.replace('{name}', name); const outRoot = strategy.outRoot ? strategy.outRoot(provider) : provider.dir; const outPath = path.join(ROOT, outRoot, resolved); const meta = strategy.meta(name, entry, resolved, key, provider); const output = transformer(withPaths, meta); writeFile(outPath, output); count++; // Post-write hook (e.g. copy skill extra files) if (strategy.postWrite) { count += strategy.postWrite(name, entry, provider, path.dirname(outPath)); } } } return count; } // --------------------------------------------------------------------------- // Resource strategies // --------------------------------------------------------------------------- const commandStrategy = { entries: (map) => Object.entries(map.commands), sourcePath: (name) => path.join(ROOT, 'framwork', '.codeadd', 'commands', `${name}.md`), providerPattern: (provider) => provider.commands || null, resolveProviders: (entry, map) => entry.providers ?? Object.keys(map.providers), injectionKind: 'command', meta: (name, entry, resolvedPattern) => ({ name, description: entry.description, skillFormat: resolvedPattern.includes('SKILL.md'), }), }; const skillStrategy = { entries: (map) => Object.entries(map.skills), sourcePath: (name) => path.join(ROOT, 'framwork', '.codeadd', 'skills', name, 'SKILL.md'), providerPattern: (provider) => provider.skills || null, resolveProviders: (entry, map) => entry.providers ?? Object.keys(map.providers), meta: (name) => ({ name }), /** * Skills always use passthrough — SKILL.md already has its own YAML frontmatter. * nativeFormat (toml) applies to commands only; all providers output skills as .md. */ transform: (content) => content, /** * Copy extra files/subdirs from skill source (everything except SKILL.md). * Markdown files are passed through stripHtmlComments + resolveResourcePaths * so {{cmd:}}, {{skill:}}, {{addpath:}} variables resolve per provider, matching * SKILL.md's pipeline. Non-markdown files are copied verbatim. */ postWrite(name, _entry, provider, outDir) { const sourceDir = path.join(ROOT, 'framwork', '.codeadd', 'skills', name); let extra = 0; for (const entry of fs.readdirSync(sourceDir, { withFileTypes: true })) { if (entry.name === 'SKILL.md') continue; const srcEntry = path.join(sourceDir, entry.name); const destEntry = path.join(outDir, entry.name); if (entry.isDirectory()) { extra += copyDirRecursive(srcEntry, destEntry, provider); } else { fs.mkdirSync(outDir, { recursive: true }); if (entry.name.endsWith('.md')) { const raw = readFile(srcEntry); lintResourcePaths(raw, srcEntry); const cleaned = stripHtmlComments(raw); const resolved = resolveResourcePaths(cleaned, provider); writeFile(destEntry, resolved); } else { fs.copyFileSync(srcEntry, destEntry); } extra++; } } return extra; }, }; // --------------------------------------------------------------------------- // Agent frontmatter dialects // // Every provider reads a different agent frontmatter. The BODY is identical // everywhere; only the header changes. Reference: brainstorm 002 Discovery // table (verified 2026-08-24). // // claude .claude/agents/.md name, description, model, tools // opencode .opencode/agents/.md description, mode: subagent, permission // cursor .cursor/agents/.md name, description, readonly // codex .codex/agents/.toml name, description, developer_instructions // zcode .zcode/agents/.md name, description, tools, disallowedTools // // `model` reaches claude only. The sources pin Claude names (sonnet, haiku, // inherit), which name nothing on the other four — a subagent pinned to one // fails to dispatch on a non-Claude session. Without the key, each of those // providers runs the subagent on the session model. // // antigrav is deliberately absent: its native agents live at .agents/agents/, // which collides with this repo's Codex skills root, and resolving that means // relocating installed projects. Deferred with the decision recorded, not // guessed. It carries no `agents` pattern, so buildResources skips it. // --------------------------------------------------------------------------- /** * Split `---\nkey: value\n---\n\nbody` into its frontmatter and body. * * Returns both a scalar map (`fields`) and the verbatim source text per key * (`blocks`). The verbatim form matters: `skills:` is a multi-line YAML list, * and re-serialising it from a scalar would silently drop every entry. * * @returns {{fields: Record, blocks: Record, body: string}} */ function splitFrontmatter(content) { const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(content); if (!match) return { fields: {}, blocks: {}, body: content.trim() }; const fields = {}; const blocks = {}; const lines = match[1].split(/\r?\n/); let current = null; for (const line of lines) { const kv = /^([A-Za-z_][A-Za-z0-9_-]*):\s*(.*)$/.exec(line); if (kv) { current = kv[1]; fields[current] = kv[2].trim(); blocks[current] = line; } else if (current !== null && line.trim() !== '') { // Continuation of the previous key (list item / block scalar). blocks[current] += `\n${line}`; } } return { fields, blocks, body: content.slice(match[0].length).trim() }; } /** Quote a value for single-line YAML when it carries YAML-significant chars. */ function yamlScalar(value) { const safe = /^[^"'\n]*$/.test(value) && !/^[&*!|>%@`-]/.test(value) && !/:\s/.test(value) && !/\s#/.test(value); return safe ? value : `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`; } /** TOML basic string (single line). */ function tomlString(value) { return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\r?\n/g, ' ')}"`; } /** * TOML multi-line basic string. Escapes backslashes, then any `"""` that would * close the literal early, then a trailing quote adjacent to the delimiter. */ function tomlMultiline(value) { const escaped = value.replace(/\\/g, '\\\\').replace(/"""/g, '\\"\\"\\"'); return `"""\n${escaped.replace(/"$/, '\\"')}\n"""`; } const AGENT_DIALECTS = { claude({ blocks }, body, meta) { const out = [`name: ${meta.name}`, `description: ${yamlScalar(meta.description)}`]; // Verbatim passthrough — `skills:` and `tools:` are multi-line YAML lists, // so re-serialising them from a scalar would silently drop every entry. for (const key of ['model', 'tools', 'disallowedTools', 'skills', 'memory']) { if (blocks[key]) out.push(blocks[key]); } // `readonly: true` reaches Claude as nothing unless it is spelled as a tool // denial: this dialect has no capability field of its own, so the constraint // ships as prose in the body and the agent merely DECLINES a write. A // decline is not an error — the caller carries on and the file is missing. // A source declaring `disallowedTools` keeps its own value, which is how the // agents that deny more than these three (Bash, Grep, Glob) stay wider. if (meta.readonly && !blocks.disallowedTools) { out.push('disallowedTools: Write, Edit, NotebookEdit'); } return `---\n${out.join('\n')}\n---\n\n${body}\n`; }, opencode({ blocks }, body, meta) { const out = [`description: ${yamlScalar(meta.description)}`, 'mode: subagent']; // A read-only agent gets its constraint enforced by the engine, not merely // stated in prose. OpenCode's permission map is the only dialect that can. // // `edit: deny` is unconditional -- it is what read-only MEANS, and nothing // in a source file may opt out of it. // // DO NOT make `bash: deny` unconditional again. Its condition is the // source's own `tools:` line, and an agent that declares Bash declares it // on purpose: git-history-agent runs read-only git, and // framework-discovery-agent shells out to `node scripts/graph.js` where no // MCP is configured. Denying bash to those two did not make them safer -- // it removed their only working route while the declaration went on saying // otherwise. Read-only is still enforced, by `edit: deny`. const declaresBash = /(^|[\s,])Bash([\s,]|$)/.test((blocks && blocks.tools) || ''); if (meta.readonly) { out.push('permission:', ' edit: deny'); if (!declaresBash) out.push(' bash: deny'); out.push(' webfetch: allow'); } return `---\n${out.join('\n')}\n---\n\n${body}\n`; }, cursor(_frontmatter, body, meta) { const out = [`name: ${meta.name}`, `description: ${yamlScalar(meta.description)}`]; if (meta.readonly) out.push('readonly: true'); return `---\n${out.join('\n')}\n---\n\n${body}\n`; }, codex(_frontmatter, body, meta) { const out = [`name = ${tomlString(meta.name)}`, `description = ${tomlString(meta.description)}`]; out.push(`developer_instructions = ${tomlMultiline(body)}`); return `${out.join('\n')}\n`; }, zcode({ blocks }, body, meta) { // Same shape as claude — ZCode's documented agent keys (name, description, // tools, disallowedTools, skills) match Claude's dialect. `model` is // dropped: ZCode model ids are not `sonnet`/`opus`/`inherit`, so passing // Claude's value through would pin the agent to a name that means nothing // there, rather than running it on the session model. const out = [`name: ${meta.name}`, `description: ${yamlScalar(meta.description)}`]; for (const key of ['tools', 'disallowedTools', 'skills', 'memory']) { if (blocks[key]) out.push(blocks[key]); } if (meta.readonly && !blocks.disallowedTools) { out.push('disallowedTools: Write, Edit, NotebookEdit'); } return `---\n${out.join('\n')}\n---\n\n${body}\n`; }, }; const agentStrategy = { entries: (map) => Object.entries(map.agents || {}), sourcePath: (name) => path.join(ROOT, 'framwork', '.codeadd', 'agents', `${name}.md`), providerPattern: (provider) => provider.agents || null, resolveProviders: (entry, map) => entry.providers ?? Object.keys(map.providers), injectionKind: 'agent', /** A registered agent with no source file must fail the build, never warn-and-skip. */ requireSource: true, /** Codex agents live outside its skills root — see the agentsDir note in provider-map.json. */ outRoot: (provider) => provider.agentsDir || provider.dir, meta: (name, entry, _resolved, providerKey) => ({ name, description: entry.description, providerKey, }), transform(content, meta) { const { fields, blocks, body } = splitFrontmatter(content); const dialect = AGENT_DIALECTS[meta.providerKey]; if (!dialect) { throw new Error( `No agent frontmatter dialect for provider "${meta.providerKey}". An agent emitted ` + `with the wrong header silently never loads — add a dialect, or drop that provider's ` + `"agents" pattern from provider-map.json.`, ); } // `readonly: true` in the source frontmatter is the single declaration of a // read-only agent; each dialect renders it however that engine expresses it. return dialect({ fields, blocks }, body, { ...meta, readonly: fields.readonly === 'true' }); }, }; // --------------------------------------------------------------------------- // Façade functions (preserve public API for tests + external callers) // --------------------------------------------------------------------------- function buildCommands(map) { return buildResources(map, commandStrategy); } function buildSkills(map) { return buildResources(map, skillStrategy); } function buildAgents(map) { return buildResources(map, agentStrategy); } // --------------------------------------------------------------------------- // Main // --------------------------------------------------------------------------- /** * Delete provider output files for resources the registry no longer declares. * * The build writes but never deletes, so a removed command kept shipping its * stale output forever — invisible locally because provider dirs are gitignored, * and invisible in CI because CI always builds from a clean checkout. Pruning * makes a local build byte-match a CI build, which is what makes the removal * tests trustworthy wherever they run. * * Scoped to commands and agents: both are registry-declared with a * one-file-per-name pattern. Skills own arbitrary sibling files, so pruning them * would need a manifest this build does not keep. * * @param {object} map provider-map.json * @returns {number} files removed */ function pruneStaleOutputs(map) { let removed = 0; for (const [key, provider] of Object.entries(map.providers)) { for (const [kind, registry] of [['commands', map.commands], ['agents', map.agents || {}]]) { const pattern = provider[kind]; if (!pattern) continue; const root = kind === 'agents' ? provider.agentsDir || provider.dir : provider.dir; // Flat layout: "/{name}." → prune stale files. const flat = /^([^/]+)\/\{name\}(\.[A-Za-z0-9]+)$/.exec(pattern); if (flat) { const [, subdir, ext] = flat; const outDir = path.join(ROOT, root, subdir); if (!fs.existsSync(outDir)) continue; const declared = new Set(Object.keys(registry).map((n) => `${n}${ext}`)); for (const entry of fs.readdirSync(outDir, { withFileTypes: true })) { if (!entry.isFile() || !entry.name.endsWith(ext)) continue; if (declared.has(entry.name)) continue; fs.rmSync(path.join(outDir, entry.name)); console.log(` PRUNED (not in registry): ${key}/${subdir}/${entry.name}`); removed++; } continue; } // Directory layout: "/{name}/" — Codex and Antigravity emit // commands as skills. Prune only a directory whose name is not declared // in EITHER registry: commands and skills share this tree, so a name // absent from `commands` may still be a legitimate skill. const nested = /^([^/]+)\/\{name\}\//.exec(pattern); if (!nested) continue; const [, subdir] = nested; const outDir = path.join(ROOT, root, subdir); if (!fs.existsSync(outDir)) continue; const declared = new Set([...Object.keys(map.commands), ...Object.keys(map.skills)]); for (const entry of fs.readdirSync(outDir, { withFileTypes: true })) { if (!entry.isDirectory() || declared.has(entry.name)) continue; fs.rmSync(path.join(outDir, entry.name), { recursive: true }); console.log(` PRUNED (not in registry): ${key}/${subdir}/${entry.name}/`); removed++; } } } return removed; } /** * The build's single-file outputs, in one place because they have FOUR * consumers and only one of them is JavaScript: * * 1. main() below, which writes them * 2. framwork/.gitignore, which must ignore each — or every build dirties the tree * 3. .github/workflows/release.yml, which must package each explicitly: * a sidecar is a file, not a subdir, so the `for subdir` loop misses it * 4. AGENTS.md, which documents them * * Commit 56bc22d fixed exactly this class of bug ("the registry has three * consumers, and the build only checked two"). The fix is not a test that * enumerates names — that is the same bug rewritten — but this single list, * which cli/tests/release-packaging.test.js derives its levels from. */ const SIDECARS = ['injection-points.json', 'contracts.json', 'artefact-graph.json']; /** * The knowledge-graph MCP server: where its source lives, and where the build * puts it so `npm publish` packs it. * * BOTH ENDS ARE NAMED HERE AND NOWHERE ELSE. The destination has three * consumers that must agree — this copy, `cli/package.json`'s `files` * whitelist, and the `.gitignore` entry that keeps the generated copy out of * review — and `cli/tests/mcp-packaging.test.js` derives its levels from these * two constants rather than repeating the strings. * * `mcp/` is PRODUCT source living at the repository root. It is not registered * in provider-map.json and build.js does not transform it: the files are * dependency-free `.mjs` and the source IS the bundle, so this is a copy and * never a compile. */ const MCP_SOURCE = 'mcp'; const MCP_PACKAGED = 'cli/src/mcp'; /** * Mirror `mcp/` into the CLI package. * * A MIRROR, NOT A MERGE. A copy that only adds leaves a deleted module in * every published package forever, which is the same class of bug the sidecar * prune above already guards against. * * `root` defaults to this repository. A test passes a temporary one, so it can * prove the prune without touching the real cli/src/mcp or running the whole * build — which clears the sidecars every other test reads. * * @param {string} [root] * @returns {{copied: number, pruned: number}} */ function copyMcpIntoCli(root = ROOT) { const from = path.join(root, MCP_SOURCE); const to = path.join(root, MCP_PACKAGED); if (!fs.existsSync(from)) return { copied: 0, pruned: 0 }; const wanted = new Set(); const walk = (dir, rel = '') => { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const next = rel ? path.join(rel, entry.name) : entry.name; if (entry.isDirectory()) walk(path.join(dir, entry.name), next); else wanted.add(next); } }; walk(from); let copied = 0; for (const rel of wanted) { const target = path.join(to, rel); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.copyFileSync(path.join(from, rel), target); copied += 1; } let pruned = 0; if (fs.existsSync(to)) { const sweep = (dir, rel = '') => { for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const next = rel ? path.join(rel, entry.name) : entry.name; if (entry.isDirectory()) { sweep(path.join(dir, entry.name), next); if (fs.readdirSync(path.join(dir, entry.name)).length === 0) { fs.rmdirSync(path.join(dir, entry.name)); } } else if (!wanted.has(next)) { fs.rmSync(path.join(dir, entry.name)); pruned += 1; } } }; sweep(to); } return { copied, pruned }; } function main() { console.log('Building provider files...\n'); INJECTION_SLOTS = []; INJECTION_MODE = null; CONTRACTS = {}; // Clear the sidecar BEFORE building. A gate firing mid-build aborts before // writeContracts(), and a leftover file from an earlier run would let status.cjs // read a stale `version` and report a behind project as current — the exact // outcome I8 exists to prevent. // Driven by SIDECARS so a new one is cleared without a second edit here. for (const name of SIDECARS) { fs.rmSync(path.join(ROOT, 'framwork', '.codeadd', name), { force: true }); } const contractsPath = path.join(ROOT, 'framwork', '.codeadd', 'contracts.json'); const map = readMap(); assertNoLintableSources(map); const prunedCount = pruneStaleOutputs(map); const commandCount = buildCommands(map); const skillCount = buildSkills(map); const agentCount = buildAgents(map); const sidecarPath = path.join(ROOT, 'framwork', '.codeadd', 'injection-points.json'); const pointCount = writeInjectionPoints(sidecarPath); const contractCount = writeContracts(contractsPath); // Built AFTER the resource passes so every slot member is in hand. // INJECTS_INTO edges come from those members, never from a second extractor. const graphPath = path.join(ROOT, 'framwork', '.codeadd', 'artefact-graph.json'); const injectionPoints = INJECTION_SLOTS.flatMap((slot) => slot.members.map((m) => ({ ...m, resource: slot.resource }))); const artefactGraph = buildArtefactGraph(map, CODEADD_DIR, ROOT, injectionPoints); // Gate BEFORE writing, so a failed build never leaves a sidecar describing a // tree the gate rejected — the same reason contracts.json is cleared upfront. assertArtefactGraph(artefactGraph); const graph = writeArtefactGraph(graphPath, artefactGraph); const mcp = copyMcpIntoCli(); const total = commandCount + skillCount + agentCount; console.log(`\nBuild complete:`); console.log(` Commands : ${Object.keys(map.commands).length} × providers → ${commandCount} files`); console.log(` Skills : ${Object.keys(map.skills).length} skills → ${skillCount} files`); console.log(` Agents : ${Object.keys(map.agents || {}).length} agents → ${agentCount} files`); if (prunedCount) console.log(` Pruned : ${prunedCount} stale output file(s)`); console.log(` Injection points : ${pointCount} → ${path.relative(ROOT, sidecarPath)}`); console.log(` Contracts : ${contractCount} → ${path.relative(ROOT, contractsPath)}`); console.log(` Artefact graph : ${graph.nodes} nodes, ${graph.edges} edges → ${path.relative(ROOT, graphPath)}`); console.log(` MCP server : ${mcp.copied} file(s) → ${MCP_PACKAGED}${mcp.pruned ? ` (${mcp.pruned} stale removed)` : ''}`); console.log(` Total : ${total} files generated`); } // Export for testing module.exports = { assertProductNames, stripHtmlComments, collectInjectionPoints, writeInjectionPoints, _resetInjectionPoints: () => { INJECTION_SLOTS = []; INJECTION_MODE = null; }, injectionMode, extractSlots, extractUses, collectNodes, buildArtefactGraph, writeArtefactGraph, checkArtefactGraph, assertArtefactGraph, copyMcpIntoCli, MCP_SOURCE, MCP_PACKAGED, SIDECARS, fragmentNodeName, fencedSpans, nodeMentionRe, sliceContractBlock, contractShape, CONTRACT_VARIABLE_RE, extractContract, collectContract, writeContracts, _resetContracts: () => { CONTRACTS = {}; }, resolveResourcePaths, resolveDocSchema, resolvePackagedDocSchema, lintResourcePaths, readFallbackFile, collectLintableSources, assertNoLintableSources, SHIPPED_SOURCE_ALLOWLIST, LINTABLE_EXTENSIONS, copyDirRecursive, _resetLintCache: () => LINTED_PATHS.clear(), TRANSFORMERS, METADATA, buildCommands, buildSkills, buildAgents, buildResources, pruneStaleOutputs, splitFrontmatter, tomlString, tomlMultiline, AGENT_DIALECTS, readMap, }; // Only run when executed directly if (require.main === module) { main(); // `--package`: the release workflow's throwaway checkout also resolves the // doc-format variable in the trees that ship unbuilt (see resolvePackagedDocSchema). if (process.argv.includes('--package')) { console.log(` Packaged trees : ${resolvePackagedDocSchema()} file(s) resolved ({{doc-schema}})`); } }