diff --git a/package.json b/package.json index 2b6f8b94a..1e7eccbee 100644 --- a/package.json +++ b/package.json @@ -532,6 +532,7 @@ "carrier-closure:check": "node scripts/ci/validate-carrier-closure.js", "routing:check": "node scripts/ci/evaluate-context-routing.js", "catalog:sync": "node scripts/ci/catalog.js --write --text", + "skills:references": "node scripts/ci/skill-references.js", "command-registry:generate": "node scripts/ci/generate-command-registry.js", "command-registry:write": "node scripts/ci/generate-command-registry.js --write", "command-registry:check": "node scripts/ci/generate-command-registry.js --check", diff --git a/scripts/ci/skill-references.js b/scripts/ci/skill-references.js new file mode 100644 index 000000000..d4ba3463d --- /dev/null +++ b/scripts/ci/skill-references.js @@ -0,0 +1,203 @@ +#!/usr/bin/env node +/** + * Report which curated skills have reference evidence, for the catalog review + * in docs/ROADMAP.md: "every skill has a test, a command, an agent, or a + * README mention, or it is marked for removal". + * + * Evidence contract: + * - test: a test file under tests/ (`*.test.{js,cjs,mjs}`, `test_*.py`, + * `*_test.py`), outside tests/fixtures/, that names the skill's path + * (`skills/`, `skills\`, or `'skills', ''` as in + * path.join), quotes the name as a whole string literal (a list the test + * iterates), or whose file name is the skill name. A fixture that lists a + * skill, such as a routing corpus, is data and not a test of that skill. + * - command: a commands/*.md file that mentions the skill name. + * - agent: an agents/*.md file that mentions the skill name. + * - readme: README.md mentions the skill name. + * + * A mention is the skill name as a whole token: `api` does not match inside + * `api-design`. Generated mirrors (.agents/, .opencode/, docs//, + * legacy-command-shims/) are not evidence. Ambiguous text counts as a + * reference: a skill wrongly reported as unreferenced could be removed, while + * a false reference only keeps it listed for review. + * + * Read-only by design: the report never edits, marks, or removes a skill, and + * exits 0 whatever it finds. Removal stays a maintainer decision. + */ + +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const SCHEMA = 'ecc.skill-references/v1'; +const KINDS = ['test', 'command', 'agent', 'readme']; +const TEST_FILE_PATTERN = /(?:\.test\.(?:js|cjs|mjs)|^test_.+\.py|_test\.py)$/; +const TOKEN_PATTERN = /(? entry.isDirectory() && fs.existsSync(path.join(skillsDir, entry.name, 'SKILL.md'))) + .map(entry => entry.name) + .sort(); +} + +function walkFiles(dir, accept, acc = []) { + if (!fs.existsSync(dir)) return acc; + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { + if (entry.name !== 'node_modules') walkFiles(full, accept, acc); + } else if (entry.isFile() && accept(full, entry.name)) { + acc.push(full); + } + } + return acc; +} + +function evidenceSources(root) { + const fixtures = path.join(root, 'tests', 'fixtures') + path.sep; + const markdown = (_full, name) => name.endsWith('.md'); + const readme = path.join(root, 'README.md'); + return { + test: walkFiles(path.join(root, 'tests'), (full, name) => !full.startsWith(fixtures) && TEST_FILE_PATTERN.test(name)), + command: walkFiles(path.join(root, 'commands'), markdown), + agent: walkFiles(path.join(root, 'agents'), markdown), + readme: fs.existsSync(readme) ? [readme] : [], + }; +} + +function lineAt(text, index) { + let line = 1; + for (let i = 0; i < index; i += 1) if (text.charCodeAt(i) === 10) line += 1; + return line; +} + +/** Earliest line in `text` where each known skill matches one of `patterns` ([regex, group]). */ +function firstMatches(text, patterns, skills) { + const found = new Map(); + for (const [pattern, group] of patterns) { + for (const match of text.matchAll(pattern)) { + const name = match[group]; + if (!skills.has(name)) continue; + const line = lineAt(text, match.index); + if (!found.has(name) || line < found.get(name)) found.set(name, line); + } + } + return found; +} + +const TEST_PATTERNS = [[SKILL_PATH_PATTERN, 1], [QUOTED_NAME_PATTERN, 2]]; +const MENTION_PATTERNS = [[TOKEN_PATTERN, 0]]; + +function testFileSkill(file, skills) { + const stem = path.basename(file).replace(/\.test\.(?:js|cjs|mjs)$|\.py$/, ''); + // Strip one marker only: test_py_test.py names the skill py-test. + const base = (stem.startsWith('test_') ? stem.slice(5) : stem.replace(/_test$/, '')).replace(/_/g, '-'); + return skills.has(base) ? base : null; +} + +function collectSkillReferences(root) { + const resolved = path.resolve(root); + const names = listSkills(resolved); + const skills = new Set(names); + const evidence = new Map(names.map(name => [name, Object.fromEntries(KINDS.map(kind => [kind, []]))])); + const sources = evidenceSources(resolved); + for (const kind of KINDS) { + for (const file of sources[kind].sort()) { + const text = fs.readFileSync(file, 'utf8'); + const relative = path.relative(resolved, file).split(path.sep).join('/'); + const found = firstMatches(text, kind === 'test' ? TEST_PATTERNS : MENTION_PATTERNS, skills); + const named = kind === 'test' ? testFileSkill(file, skills) : null; + if (named && !found.has(named)) found.set(named, 1); + for (const [name, line] of found) evidence.get(name)[kind].push({ file: relative, line }); + } + } + const rows = names.map(name => ({ name, evidence: evidence.get(name) })); + const unreferenced = rows.filter(row => KINDS.every(kind => row.evidence[kind].length === 0)).map(row => row.name); + const counts = Object.fromEntries(KINDS.map(kind => [kind, rows.filter(row => row.evidence[kind].length > 0).length])); + return { schema: SCHEMA, total: names.length, counts, unreferenced, skills: rows }; +} + +function formatText(report) { + const lines = [ + 'Skill reference audit (report only)', + `Curated skills: ${report.total}`, + `With evidence: test ${report.counts.test}, command ${report.counts.command}, agent ${report.counts.agent}, readme ${report.counts.readme}`, + `No test, command, agent, or README reference: ${report.unreferenced.length}`, + ...report.unreferenced.map(name => ` ${name}`), + ]; + return lines.join('\n') + '\n'; +} + +function formatSkill(report, name) { + const row = report.skills.find(skill => skill.name === name); + if (!row) return null; + const lines = [`${name}`]; + for (const kind of KINDS) { + const hits = row.evidence[kind]; + lines.push(` ${kind}: ${hits.length ? '' : 'none'}`); + for (const hit of hits) lines.push(` ${hit.file}:${hit.line}`); + } + return lines.join('\n') + '\n'; +} + +function parseArgs(argv) { + const options = { json: false, root: path.join(__dirname, '..', '..'), skill: null }; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === '--json') options.json = true; + else if (arg === '--root' || arg === '--skill') { + const value = argv[i + 1]; + if (!value || value.startsWith('--')) throw new Error(`Missing value for ${arg}`); + options[arg.slice(2)] = value; + i += 1; + } else if (arg === '--help' || arg === '-h') options.help = true; + else throw new Error(`Unknown argument: ${arg}`); + } + return options; +} + +const USAGE = `Usage: node scripts/ci/skill-references.js [--json] [--skill ] [--root ] + + --json Emit the full report, with file:line evidence per skill + --skill Show the evidence for one skill + --root Audit another checkout (default: this repository) +`; + +function main(argv = process.argv.slice(2)) { + let options; + try { + options = parseArgs(argv); + } catch (error) { + process.stderr.write(`${error.message}\n${USAGE}`); + process.exitCode = 1; + return; + } + if (options.help) { + process.stdout.write(USAGE); + return; + } + const report = collectSkillReferences(options.root); + if (options.skill) { + const text = formatSkill(report, options.skill); + if (!text) { + process.stderr.write(`Unknown skill: ${options.skill}\n`); + process.exitCode = 1; + return; + } + process.stdout.write(options.json ? `${JSON.stringify(report.skills.find(s => s.name === options.skill), null, 2)}\n` : text); + return; + } + process.stdout.write(options.json ? `${JSON.stringify(report, null, 2)}\n` : formatText(report)); +} + +module.exports = { SCHEMA, KINDS, collectSkillReferences, formatText, formatSkill, parseArgs }; + +if (require.main === module) main(); diff --git a/tests/ci/skill-references.test.js b/tests/ci/skill-references.test.js new file mode 100644 index 000000000..cdd7ba9a6 --- /dev/null +++ b/tests/ci/skill-references.test.js @@ -0,0 +1,172 @@ +#!/usr/bin/env node +/** + * Tests for the skill reference audit (scripts/ci/skill-references.js). + * + * A synthetic checkout exercises each evidence rule and each exclusion: + * whole-token mentions, test path/quoted/file-name evidence, fixtures, + * prose in tests, non-test helpers and generated mirrors. A smoke run over + * this repository checks that every reported location exists. + */ + +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +const audit = require('../../scripts/ci/skill-references.js'); + +const SCRIPT_PATH = path.join(__dirname, '..', '..', 'scripts', 'ci', 'skill-references.js'); +const REPO_ROOT = path.join(__dirname, '..', '..'); + +function test(name, fn) { + try { + fn(); + console.log(` ✓ ${name}`); + return true; + } catch (error) { + console.log(` ✗ ${name}`); + console.log(` Error: ${error.message}`); + return false; + } +} + +function write(root, relative, content) { + const file = path.join(root, ...relative.split('/')); + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, content); +} + +const SKILLS = [ + 'alpha', 'alpha-beta', 'api', 'cmd-only', 'agent-only', 'readme-only', 'path-test', 'win-path-test', + 'join-test', 'quoted-test', 'named-test', 'py-test', 'fixture-only', 'prose-test', 'mirror-only', 'orphan', +]; + +function buildFixture() { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'skill-references-')); + for (const name of SKILLS) write(root, `skills/${name}/SKILL.md`, `---\nname: ${name}\n---\n`); + write(root, 'skills/not-a-skill/notes.md', 'no SKILL.md here\n'); + write(root, 'commands/do.md', '# Do\n\nUse the `cmd-only` skill.\nSee alpha-beta for more.\n'); + write(root, 'agents/reviewer.md', '---\nname: reviewer\n---\n\nLoad agent-only first.\n'); + write(root, 'README.md', '# Fixture\n\n- [api](skills/api/SKILL.md)\n- readme-only\n'); + write(root, 'tests/ci/path.test.js', "const a = read('skills/path-test/SKILL.md');\nconst b = 'skills\\\\win-path-test\\\\SKILL.md';\n"); + write(root, 'tests/skills/join.test.js', "\n\nconst p = path.join(root, 'skills', 'join-test', 'SKILL.md');\n"); + write(root, 'tests/ci/list.test.js', "// prose-test cases are described here\nfor (const skill of ['quoted-test']) check(skill);\n"); + write(root, 'tests/skills/named-test.test.js', 'assert.ok(true);\n'); + write(root, 'tests/test_py_test.py', 'def test_ok():\n assert True\n'); + write(root, 'tests/fixtures/routing-prompts.json', '[{"skill": "fixture-only"}, {"skill": "orphan"}]\n'); + write(root, 'tests/helpers.js', "module.exports = ['orphan'];\n"); + write(root, '.agents/skills/mirror-only/SKILL.md', 'mirror-only\n'); + write(root, 'docs/de-DE/README.md', 'mirror-only\n'); + write(root, 'legacy-command-shims/commands/old.md', 'Use mirror-only.\n'); + return root; +} + +function run() { + console.log('\n=== Testing skill reference audit ===\n'); + let passed = 0; + let failed = 0; + const check = (name, fn) => (test(name, fn) ? passed++ : failed++); + const root = buildFixture(); + try { + const report = audit.collectSkillReferences(root); + const evidence = name => report.skills.find(skill => skill.name === name).evidence; + + check('lists only skill directories that contain SKILL.md, sorted', () => { + assert.strictEqual(report.schema, 'ecc.skill-references/v1'); + assert.deepStrictEqual(report.skills.map(skill => skill.name), [...SKILLS].sort()); + assert.strictEqual(report.total, SKILLS.length); + }); + + check('command, agent and README mentions count as whole tokens with file:line', () => { + assert.deepStrictEqual(evidence('cmd-only').command, [{ file: 'commands/do.md', line: 3 }]); + assert.deepStrictEqual(evidence('agent-only').agent, [{ file: 'agents/reviewer.md', line: 5 }]); + assert.deepStrictEqual(evidence('readme-only').readme, [{ file: 'README.md', line: 4 }]); + assert.deepStrictEqual(evidence('api').readme, [{ file: 'README.md', line: 3 }]); + assert.deepStrictEqual(evidence('alpha-beta').command, [{ file: 'commands/do.md', line: 4 }]); + assert.deepStrictEqual(evidence('alpha').command, [], 'alpha must not match inside alpha-beta'); + }); + + check('tests count by skill path, path.join segments, quoted literals or file name', () => { + assert.deepStrictEqual(evidence('path-test').test, [{ file: 'tests/ci/path.test.js', line: 1 }]); + assert.deepStrictEqual(evidence('win-path-test').test, [{ file: 'tests/ci/path.test.js', line: 2 }]); + assert.deepStrictEqual(evidence('join-test').test, [{ file: 'tests/skills/join.test.js', line: 3 }]); + assert.deepStrictEqual(evidence('quoted-test').test, [{ file: 'tests/ci/list.test.js', line: 2 }]); + assert.deepStrictEqual(evidence('named-test').test, [{ file: 'tests/skills/named-test.test.js', line: 1 }]); + assert.deepStrictEqual(evidence('py-test').test, [{ file: 'tests/test_py_test.py', line: 1 }]); + }); + + check('fixtures, unquoted prose in tests, non-test helpers and mirrors are not evidence', () => { + for (const name of ['fixture-only', 'prose-test', 'mirror-only', 'orphan']) { + for (const kind of audit.KINDS) assert.deepStrictEqual(evidence(name)[kind], [], `${name} ${kind}`); + } + assert.deepStrictEqual(report.unreferenced, ['alpha', 'fixture-only', 'mirror-only', 'orphan', 'prose-test']); + }); + + check('counts are skills with at least one reference of each kind', () => { + assert.deepStrictEqual(report.counts, { test: 6, command: 2, agent: 1, readme: 2 }); + }); + + check('text report summarizes counts and lists unreferenced skills', () => { + const text = audit.formatText(report); + assert.match(text, /Curated skills: 16\n/); + assert.match(text, /With evidence: test 6, command 2, agent 1, readme 2\n/); + assert.match(text, /No test, command, agent, or README reference: 5\n {2}alpha\n {2}fixture-only\n/); + assert.strictEqual(audit.formatSkill(report, 'missing'), null); + assert.match(audit.formatSkill(report, 'join-test'), /test: \n {4}tests\/skills\/join\.test\.js:3\n {2}command: none/); + }); + + check('CLI reports with exit 0, and rejects bad arguments or unknown skills with exit 1', () => { + const cli = args => spawnSync(process.execPath, [SCRIPT_PATH, ...args], { encoding: 'utf8' }); + const json = cli(['--root', root, '--json']); + assert.strictEqual(json.status, 0, json.stderr); + assert.deepStrictEqual(JSON.parse(json.stdout), report); + const one = cli(['--root', root, '--skill', 'cmd-only', '--json']); + assert.strictEqual(one.status, 0, one.stderr); + assert.deepStrictEqual(JSON.parse(one.stdout).evidence.command, [{ file: 'commands/do.md', line: 3 }]); + assert.strictEqual(cli(['--root', root, '--skill', 'missing']).status, 1); + assert.strictEqual(cli(['--bogus']).status, 1); + assert.strictEqual(cli(['--root']).status, 1); + assert.strictEqual(cli(['--help']).status, 0); + }); + + check('the report is read-only: the checkout is unchanged after a run', () => { + const snapshot = (dir, acc = []) => { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) snapshot(full, acc); + else acc.push(`${path.relative(root, full)}:${fs.readFileSync(full, 'utf8')}`); + } + return acc.sort(); + }; + const before = snapshot(root); + audit.collectSkillReferences(root); + assert.deepStrictEqual(snapshot(root), before); + }); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + + check('this repository: every skill is reported and every location exists', () => { + const report = audit.collectSkillReferences(REPO_ROOT); + const skillDirs = fs.readdirSync(path.join(REPO_ROOT, 'skills'), { withFileTypes: true }) + .filter(entry => entry.isDirectory() && fs.existsSync(path.join(REPO_ROOT, 'skills', entry.name, 'SKILL.md'))); + assert.strictEqual(report.total, skillDirs.length); + for (const skill of report.skills) { + for (const kind of audit.KINDS) { + for (const hit of skill.evidence[kind]) { + const lines = fs.readFileSync(path.join(REPO_ROOT, hit.file), 'utf8').split('\n'); + assert.ok(hit.line >= 1 && hit.line <= lines.length, `${skill.name} ${hit.file}:${hit.line}`); + } + } + } + assert.deepStrictEqual(audit.collectSkillReferences(REPO_ROOT), report, 'repeat runs are identical'); + }); + + console.log(`\nResults: Passed: ${passed}, Failed: ${failed}`); + process.exit(failed > 0 ? 1 : 0); +} + +run();