// `yad detect` (E50): what is installed for the agents that work in a folder. Runs on Linux, macOS and // Windows — the Windows CI job runs this file too — so every path here is built with path.join. import { test } from 'node:test'; import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import crypto from 'node:crypto'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; // The #280 guard, as in cli/test.mjs: under `node --test` this file's stdout carries the runner's own // messages, and a printed `info()` line landing between them can lose every result after it. if (process.env.NODE_TEST_CONTEXT) { const write = process.stdout.write; for (const k of ['log', 'info']) { const orig = console[k]; console[k] = (...a) => (process.stdout.write === write ? console.error(...a) : orig(...a)); } } process.env.YAD_NO_UPDATE_NOTIFIER = '1'; const { detectInstalled, skillMeta, stripJsonComments, tomlAgentName, tomlTableNames } = await import('./detect.mjs'); const ROOT = fileURLToPath(new URL('..', import.meta.url)); const YAD = path.join(ROOT, 'bin', 'yad.mjs'); // A value that must never reach the output: it stands for a token in an MCP server's settings. const SECRET = 'SECRET-TOKEN-e50'; const put = (file, text) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, text); }; const skill = (dir, name, front = '') => put(path.join(dir, name, 'SKILL.md'), `---\n${front}description: a skill\n---\nbody\n`); const sha = (file) => `sha256:${crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex')}`; const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'yad-detect-')); const find = (items, kind, name, where) => items.filter((i) => i.kind === kind && i.name === name && (where === undefined || i.where === where)); // Every file under a folder with its size and modification time — to prove a run wrote nothing. function snapshot(dir) { const out = []; const walk = (d) => { for (const e of fs.readdirSync(d, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) { const full = path.join(d, e.name); const st = fs.lstatSync(full); out.push(`${path.relative(dir, full)}|${e.isDirectory() ? 'd' : st.size}|${st.mtimeMs}`); if (e.isDirectory()) walk(full); } }; walk(dir); return out; } // A project and a home folder holding one of everything the detector reads. function fixture() { const T = tmp(); const proj = path.join(T, 'proj'); const home = path.join(T, 'home'); fs.mkdirSync(proj, { recursive: true }); fs.mkdirSync(home, { recursive: true }); // Project skills in every place yad installs into, plus Cursor's `.codex/skills`. skill(path.join(proj, '.claude/skills'), 'alpha', 'name: alpha\nversion: 1.2.0\n'); skill(path.join(proj, '.agents/skills'), 'beta', 'metadata:\n author: x\n version: "2.0"\n'); skill(path.join(proj, '.cursor/skills'), 'gamma'); skill(path.join(proj, '.gemini/skills'), 'delta'); skill(path.join(proj, '.zencoder/skills'), 'epsilon'); skill(path.join(proj, '.codex/skills'), 'zeta'); put(path.join(proj, '.opencode/commands/eta.md'), '---\nname: eta\n---\nbody\n'); put(path.join(proj, '.opencode/commands/notes.txt'), 'not a skill'); // Not skills: a folder with no SKILL.md, and a plain file sitting in a skills folder. fs.mkdirSync(path.join(proj, '.claude/skills/empty'), { recursive: true }); put(path.join(proj, '.claude/skills/README.md'), 'hello'); // Frontmatter with a BOM and Windows line ends, and a quoted name. put(path.join(proj, '.claude/skills/crlf/SKILL.md'), '\uFEFF---\r\nname: \'crlf-skill\'\r\nversion: 3\r\n---\r\nbody\r\n'); // A SKILL.md too big to read: left out, not read into memory. put(path.join(proj, '.claude/skills/huge/SKILL.md'), `---\nname: huge\n---\n${'x'.repeat(1024 * 1024 + 1)}`); // Home skills. skill(path.join(home, '.claude/skills'), 'alpha', 'name: alpha\n'); skill(path.join(home, '.agents/skills'), 'theta'); skill(path.join(home, '.cursor/skills'), 'iota'); skill(path.join(home, '.gemini/skills'), 'kappa'); skill(path.join(home, '.codex/skills'), 'lambda'); // Agents. put(path.join(proj, '.claude/agents/reviewer.md'), '---\nname: reviewer\nversion: 0.1\n---\nprompt\n'); put(path.join(home, '.claude/agents/helper.md'), 'no frontmatter at all\n'); put(path.join(proj, '.cursor/agents/c-agent.md'), '---\nname: c-agent\n---\n'); put(path.join(home, '.gemini/agents/g-agent.md'), '---\nname: g-agent\n---\n'); put(path.join(proj, '.codex/agents/x.toml'), '# a Codex agent\nname = "codex-reviewer"\ndescription = "d"\n'); put(path.join(home, '.codex/agents/late.toml'), '[extra]\nname = "not-the-agent-name"\n'); put(path.join(home, '.codex/agents/skip.md'), '---\nname: wrong-extension\n---\n'); // MCP servers, each with a secret in its settings. const server = { command: 'npx', args: ['--token', SECRET], env: { API_KEY: SECRET }, headers: { Authorization: `Bearer ${SECRET}` } }; put(path.join(proj, '.mcp.json'), JSON.stringify({ mcpServers: { 'proj-server': server } })); put(path.join(proj, '.cursor/mcp.json'), JSON.stringify({ mcpServers: { 'cursor-server': server } })); put(path.join(home, '.cursor/mcp.json'), JSON.stringify({ mcpServers: { 'cursor-home': server } })); // Gemini CLI strips comments from its settings before reading them, so a commented file still counts. put(path.join(proj, '.gemini/settings.json'), `// my settings\n{ "theme": "dark", /* servers: */ "mcpServers": ${JSON.stringify({ 'gem-server': server })} }`); put(path.join(home, '.gemini/settings.json'), JSON.stringify({ theme: 'dark' })); put(path.join(home, '.claude.json'), JSON.stringify({ mcpServers: { 'user-server': server }, projects: { [path.resolve(proj)]: { mcpServers: { 'local-server': server } }, '/somewhere/else': { mcpServers: { 'other-project': server } } }, })); put(path.join(home, '.codex/config.toml'), [ 'model = "x"', `[mcp_servers.docs]\ncommand = "npx"\nargs = [\n "--token",\n "${SECRET}"\n]\ndescription = """\n${SECRET}=1\n[mcp_servers.fake]\n"""`, `[mcp_servers.docs.env]\nKEY = "${SECRET}"`, '[mcp_servers."quoted.name"]\nurl = "https://example.invalid"', '[plugins."tool@market"]\nenabled = true', ].join('\n')); put(path.join(proj, '.codex/config.toml'), `[mcp_servers]\nproj-codex = { command = "x", env = { K = "${SECRET}" } }\n`); // Claude Code plugins: one for everyone, one for THIS folder, one for another folder. const plug = (name) => path.join(home, '.claude/plugins/cache/m', name); skill(path.join(plug('p1'), 'skills'), 'p1-skill', 'name: p1-skill\n'); put(path.join(plug('p1'), 'agents/p1-agent.md'), '---\nname: p1-agent\n---\n'); put(path.join(plug('p1'), '.mcp.json'), JSON.stringify({ mcpServers: { 'p1-mcp': server } })); put(path.join(plug('p2'), '.claude-plugin/plugin.json'), JSON.stringify({ name: 'p2', mcpServers: { 'p2-mcp': server } })); put(path.join(plug('p3'), '.claude-plugin/plugin.json'), JSON.stringify({ name: 'p3', mcpServers: './servers.json' })); put(path.join(plug('p3'), 'servers.json'), JSON.stringify({ 'p3-mcp': server })); put(path.join(plug('p4'), '.claude-plugin/plugin.json'), JSON.stringify({ name: 'p4', mcpServers: '../p1/.mcp.json' })); // `mcpServers` as a list of paths and objects; a name that only starts with `..` is still the plugin's. put(path.join(plug('p5'), '.claude-plugin/plugin.json'), JSON.stringify({ name: 'p5', mcpServers: ['./a.json', { 'p5-inline': server }, '..x.json'] })); put(path.join(plug('p5'), 'a.json'), JSON.stringify({ mcpServers: { 'p5-a': server } })); put(path.join(plug('p5'), '..x.json'), JSON.stringify({ 'p5-dots': server })); put(path.join(plug('p6'), '.claude-plugin/plugin.json'), '{ not json'); // A `mcpServers` that is not an object is a problem, not a reason to list the file's other keys. put(path.join(plug('p7'), '.mcp.json'), JSON.stringify({ $schema: 's', mcpServers: [] })); put(path.join(home, '.claude/plugins/installed_plugins.json'), JSON.stringify({ version: 2, plugins: { 'p1@m': [{ scope: 'user', installPath: plug('p1'), version: '1.0.0', gitCommitSha: 'abc123' }], 'p2@m': [{ scope: 'local', projectPath: proj, installPath: plug('p2'), version: '2.0.0' }], 'p3@m': [{ scope: 'project', projectPath: path.join(T, 'elsewhere'), installPath: plug('p3'), version: '3.0.0' }], 'p4@m': [{ scope: 'user', installPath: plug('p4') }], 'p5@m': [{ scope: 'project', projectPath: proj, installPath: plug('p5') }], 'p6@m': [{ scope: 'user', installPath: plug('p6') }], 'p7@m': [{ scope: 'user', installPath: plug('p7') }], 'gone@m': [{ scope: 'user', installPath: path.join(T, 'missing') }], }, })); put(path.join(home, '.claude/settings.json'), JSON.stringify({ enabledPlugins: { 'p1@m': true, 'p4@m': false, 'p2@m': true } })); // The folder's own settings win over the home folder's, and settings.local.json over settings.json. put(path.join(proj, '.claude/settings.json'), JSON.stringify({ enabledPlugins: { 'p2@m': true, 'p4@m': true } })); put(path.join(proj, '.claude/settings.local.json'), JSON.stringify({ enabledPlugins: { 'p2@m': false } })); return { T, proj, home }; } test('E50: every place is read, and each item says where it came from and which agents read it', () => { const { T, proj, home } = fixture(); try { const { items, problems } = detectInstalled(proj, { home }); assert.deepEqual(problems, [ { where: '~/.claude/plugins (p4@m: .claude-plugin/plugin.json)', problem: 'names an MCP file outside the plugin' }, { where: '~/.claude/plugins (p6@m: .claude-plugin/plugin.json)', problem: 'could not be read as a JSON object' }, { where: '~/.claude/plugins (p7@m: .mcp.json)', problem: '`mcpServers` is not an object' }, ]); const alpha = find(items, 'skill', 'alpha'); assert.deepEqual(alpha.map((i) => [i.scope, i.where, i.version]), [['project', '.claude/skills/alpha', '1.2.0'], ['user', '~/.claude/skills/alpha', null]]); assert.deepEqual(alpha[0].agents, ['Claude Code', 'Cursor']); assert.equal(alpha[0].hash, sha(path.join(proj, '.claude/skills/alpha/SKILL.md'))); assert.equal(find(items, 'skill', 'beta')[0].version, '2.0', 'metadata.version, unquoted'); assert.deepEqual(find(items, 'skill', 'beta')[0].agents, ['Codex CLI', 'Gemini CLI', 'Cursor', 'GitHub Copilot']); assert.deepEqual(find(items, 'skill', 'zeta')[0].agents, ['Cursor'], 'Codex does not read .codex/skills; Cursor does'); assert.deepEqual(find(items, 'skill', 'epsilon')[0].agents, ['Zencoder']); assert.equal(find(items, 'skill', 'eta')[0].where, '.opencode/commands/eta.md'); assert.deepEqual(find(items, 'skill', 'crlf-skill').map((i) => i.version), ['3'], 'BOM + CRLF + quotes'); assert.equal(find(items, 'skill', 'empty').length + find(items, 'skill', 'README').length + find(items, 'skill', 'huge').length, 0); assert.deepEqual(find(items, 'skill', 'theta')[0].agents, ['Codex CLI', 'Gemini CLI', 'Cursor']); assert.equal(find(items, 'skill', 'lambda')[0].where, '~/.codex/skills/lambda'); assert.equal(find(items, 'agent', 'reviewer')[0].version, '0.1'); assert.equal(find(items, 'agent', 'helper')[0].where, '~/.claude/agents/helper.md', 'no frontmatter: the file name'); assert.deepEqual(find(items, 'agent', 'codex-reviewer')[0].agents, ['Codex CLI']); assert.equal(find(items, 'agent', 'late').length, 1, 'a name inside a table is not the agent name'); assert.equal(find(items, 'agent', 'wrong-extension').length, 0); assert.deepEqual(find(items, 'agent', 'g-agent')[0].agents, ['Gemini CLI']); const mcp = items.filter((i) => i.kind === 'mcp').map((i) => `${i.name}@${i.where}@${i.scope}`).sort(); assert.deepEqual(mcp, [ 'cursor-home@~/.cursor/mcp.json@user', 'cursor-server@.cursor/mcp.json@project', 'docs@~/.codex/config.toml@user', 'gem-server@.gemini/settings.json@project', 'local-server@~/.claude.json (this folder)@user', 'p1-mcp@p1@m: .mcp.json@user', 'p2-mcp@p2@m: .claude-plugin/plugin.json@user', 'p5-a@p5@m: a.json@project', 'p5-dots@p5@m: ..x.json@project', 'p5-inline@p5@m: .claude-plugin/plugin.json@project', 'proj-codex@.codex/config.toml@project', 'proj-server@.mcp.json@project', 'quoted.name@~/.codex/config.toml@user', 'user-server@~/.claude.json@user', ]); const plugins = items.filter((i) => i.kind === 'plugin').map((i) => [i.name, i.scope, i.version, i.enabled]); assert.deepEqual(plugins, [ ['tool@market', 'user', null, undefined], ['gone@m', 'user', null, null], ['p1@m', 'user', '1.0.0', true], ['p2@m', 'user', '2.0.0', false], ['p4@m', 'user', null, true], ['p5@m', 'project', null, null], ['p6@m', 'user', null, null], ['p7@m', 'user', null, null], ], 'another folder\'s plugin (p3) is left out; `local` is the user\'s; the folder\'s settings win, local first'); assert.equal(find(items, 'plugin', 'p1@m')[0].commit, 'abc123'); const p1skill = find(items, 'skill', 'p1-skill')[0]; assert.deepEqual([p1skill.plugin, p1skill.version, p1skill.where], ['p1@m', '1.0.0', 'p1@m: skills/p1-skill']); assert.equal(find(items, 'agent', 'p1-agent')[0].plugin, 'p1@m'); assert.equal(find(items, 'mcp', 'p1-mcp').length, 1, 'p4 points outside itself and adds nothing'); // The same keys on every item. for (const it of items) for (const k of ['kind', 'name', 'scope', 'where', 'agents', 'version', 'hash', 'plugin']) assert.ok(Object.hasOwn(it, k), `${it.kind} ${it.name} has ${k}`); // No secret, and no absolute home path, anywhere in the answer. // Every string of the answer, as it is — JSON.stringify doubles a Windows backslash, so a search of // the serialised text could never find a leaked Windows path. const strings = []; const walk = (v) => { if (typeof v === 'string') strings.push(v); else if (v && typeof v === 'object') Object.values(v).forEach(walk); }; walk({ items, problems }); assert.ok(!strings.some((v) => v.includes(SECRET)), 'an MCP server is named, never described'); assert.ok(!strings.some((v) => v.includes(home) || v.includes(T)), 'the home folder is shown as ~, and no absolute path appears'); assert.equal(find(items, 'mcp', 'fake').length, 0, 'text inside a multi-line string is not a server'); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50: detection writes nothing — not in the project, not in the home folder', () => { const { T, proj, home } = fixture(); try { const before = snapshot(T); detectInstalled(proj, { home }); assert.deepEqual(snapshot(T), before); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50: a file that is there but unreadable is a problem, named by place and never by content', () => { const T = tmp(); const proj = path.join(T, 'p'); const home = path.join(T, 'h'); try { put(path.join(proj, '.mcp.json'), `{ "mcpServers": { "x": { "env": "${SECRET}" }`); put(path.join(proj, '.cursor/mcp.json'), JSON.stringify({ mcpServers: ['not', 'an', 'object'] })); put(path.join(home, '.claude.json'), '[1, 2]'); put(path.join(home, '.claude/plugins/installed_plugins.json'), JSON.stringify({ plugins: [] })); // `~/.claude.json` is broken on purpose below; the next test covers its `mcpServers` shapes. put(path.join(home, '.gemini/settings.json'), 'null'); // A comment is allowed in Gemini's settings only: in Cursor's file it stops Cursor loading it. put(path.join(home, '.cursor/mcp.json'), '// mine\n{ "mcpServers": { "x": {} } }'); const { items, problems } = detectInstalled(proj, { home }); assert.deepEqual(items, []); assert.deepEqual(problems.map((p) => p.where).sort(), ['.cursor/mcp.json', '.mcp.json', '~/.claude.json', '~/.claude/plugins/installed_plugins.json', '~/.cursor/mcp.json', '~/.gemini/settings.json']); assert.ok(!JSON.stringify(problems).includes(SECRET)); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50: a settings file that cannot be read is a problem, and the answer falls through to the next', () => { const T = tmp(); const proj = path.join(T, 'p'); const home = path.join(T, 'h'); try { put(path.join(home, '.claude/plugins/installed_plugins.json'), JSON.stringify({ plugins: { 'a@m': [{ scope: 'user' }] } })); put(path.join(proj, '.claude/settings.local.json'), '{ broken'); put(path.join(proj, '.claude/settings.json'), JSON.stringify({ enabledPlugins: { 'a@m': false } })); put(path.join(home, '.claude/settings.json'), JSON.stringify({ enabledPlugins: { 'a@m': true } })); const { items, problems } = detectInstalled(proj, { home }); assert.equal(find(items, 'plugin', 'a@m')[0].enabled, false); assert.deepEqual(problems, [{ where: '.claude/settings.local.json', problem: 'could not be read as a JSON object' }]); // Run in the home folder, a file that is both the folder's and the user's is reported once. put(path.join(home, '.claude/settings.json'), '{ broken'); const same = detectInstalled(home, { home }); assert.equal(same.problems.filter((p) => p.problem.startsWith('could not be read')).length, 1, JSON.stringify(same.problems)); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50: a `mcpServers` that is not an object is a problem wherever it is read', () => { const T = tmp(); const proj = path.join(T, 'p'); const home = path.join(T, 'h'); try { fs.mkdirSync(proj, { recursive: true }); put(path.join(home, '.claude.json'), JSON.stringify({ mcpServers: SECRET, projects: { [path.resolve(proj)]: { mcpServers: [1] } } })); const plug = path.join(home, 'plug'); put(path.join(plug, '.claude-plugin/plugin.json'), JSON.stringify({ mcpServers: [5, { ok: {} }] })); put(path.join(home, '.claude/plugins/installed_plugins.json'), JSON.stringify({ plugins: { 'q@m': [{ scope: 'user', installPath: plug }] } })); const { items, problems } = detectInstalled(proj, { home }); assert.deepEqual(items.filter((i) => i.kind === 'mcp').map((i) => i.name), ['ok'], 'the good entry of a list still counts'); assert.deepEqual(problems, [ { where: '~/.claude.json', problem: '`mcpServers` is not an object' }, { where: '~/.claude.json (this folder)', problem: '`mcpServers` is not an object' }, { where: '~/.claude/plugins (q@m: .claude-plugin/plugin.json)', problem: '`mcpServers` is not an object' }, ]); assert.ok(!JSON.stringify(problems).includes(SECRET)); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50: a stray value under this folder\'s exact path does not hide its real entry', () => { const T = tmp(); const proj = path.join(T, 'p'); const home = path.join(T, 'h'); try { fs.mkdirSync(proj, { recursive: true }); fs.symlinkSync(proj, path.join(T, 'link'), 'junction'); put(path.join(home, '.claude.json'), JSON.stringify({ projects: { [path.resolve(proj)]: 'x', [path.join(T, 'link')]: { mcpServers: { s: {} } } } })); const { items } = detectInstalled(proj, { home }); assert.deepEqual(items.map((i) => `${i.kind}:${i.name}:${i.where}`), ['mcp:s:~/.claude.json (this folder)']); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50: a plugin MCP path that leaves the plugin, or names nothing, is a problem that shows no path', () => { const T = tmp(); const home = path.join(T, 'h'); try { const out = path.join(T, 'outside.json'); put(out, JSON.stringify({ mcpServers: { leaked: {} } })); put(path.join(home, 'a/.claude-plugin/plugin.json'), JSON.stringify({ mcpServers: out })); put(path.join(home, 'b/.claude-plugin/plugin.json'), JSON.stringify({ mcpServers: 'missing.json' })); // Naming `.mcp.json` itself is naming a file: it must be there, unlike the unnamed default. put(path.join(home, 'c/.claude-plugin/plugin.json'), JSON.stringify({ mcpServers: '.mcp.json' })); put(path.join(home, 'd/.claude-plugin/plugin.json'), JSON.stringify({ mcpServers: '.' })); put(path.join(home, 'e/.claude-plugin/plugin.json'), JSON.stringify({ name: 'e' })); put(path.join(home, '.claude/plugins/installed_plugins.json'), JSON.stringify({ plugins: { 'a@m': [{ scope: 'user', installPath: path.join(home, 'a') }], 'b@m': [{ scope: 'user', installPath: path.join(home, 'b') }], 'c@m': [{ scope: 'user', installPath: path.join(home, 'c') }], 'd@m': [{ scope: 'user', installPath: path.join(home, 'd') }], 'e@m': [{ scope: 'user', installPath: path.join(home, 'e') }], } })); const { items, problems } = detectInstalled(path.join(T, 'none'), { home }); assert.equal(items.filter((i) => i.kind === 'mcp').length, 0); assert.deepEqual(problems, [ { where: '~/.claude/plugins (a@m: .claude-plugin/plugin.json)', problem: 'names an MCP file outside the plugin' }, { where: '~/.claude/plugins (b@m: .claude-plugin/plugin.json)', problem: 'names an MCP file that is not there' }, { where: '~/.claude/plugins (c@m: .claude-plugin/plugin.json)', problem: 'names an MCP file that is not there' }, { where: '~/.claude/plugins (d@m: .claude-plugin/plugin.json)', problem: 'names the plugin folder, not an MCP file' }, ], 'e has neither mcpServers nor .mcp.json: nothing to report'); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50: nothing installed anywhere is an empty answer, not an error', () => { const T = tmp(); try { assert.deepEqual(detectInstalled(T, { home: path.join(T, 'no-home') }), { items: [], problems: [] }); assert.deepEqual(detectInstalled(T, { home: null }), { items: [], problems: [] }); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50: run in the home folder itself, nothing is listed twice', () => { const T = tmp(); try { skill(path.join(T, '.claude/skills'), 'once'); put(path.join(T, '.claude.json'), JSON.stringify({ mcpServers: { s: {} } })); const { items } = detectInstalled(T, { home: T }); // `~/.claude.json` has no project twin, so it is still read. assert.deepEqual(items.map((i) => `${i.kind}:${i.name}:${i.scope}`), ['skill:once:project', 'mcp:s:user']); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50: a skill installed as a link (as skill managers do) is found through the link', { skip: process.platform === 'win32' && 'links need admin rights on Windows' }, () => { const T = tmp(); try { skill(path.join(T, 'store'), 'linked', 'name: linked\n'); fs.mkdirSync(path.join(T, 'home/.claude/skills'), { recursive: true }); fs.symlinkSync(path.join(T, 'store/linked'), path.join(T, 'home/.claude/skills/linked')); const { items } = detectInstalled(path.join(T, 'proj-none'), { home: path.join(T, 'home') }); assert.deepEqual(items.map((i) => i.where), ['~/.claude/skills/linked']); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50: the frontmatter, TOML name and TOML table readers', () => { assert.deepEqual(skillMeta('no frontmatter'), {}); assert.deepEqual(skillMeta('---\nname: a\nmetadata:\n version: 1\nversion: 2\n---\n'), { name: 'a', version: '2' }, 'top-level version wins'); assert.deepEqual(skillMeta('---\nmetadata:\n version: 1\nother:\n version: 9\n---\n'), { version: '1' }, 'only metadata.version'); assert.deepEqual(skillMeta('---\nname:\n---\n'), {}, 'an empty value is missing'); assert.equal(tomlAgentName("name = 'single' # c"), 'single'); assert.equal(tomlAgentName('name = unquoted'), null); const toml = [ '# [mcp_servers.commented]', 'mcp_servers.dotted.command = "x"', '[mcp_servers.bare_one]', '[ mcp_servers . "spaced" ]', "[mcp_servers.'lit']", '[mcp_servers.bare_one.env]', '[mcp_servers]', 'inline = { command = "y" }', 'also.command = "z"', '[other]', 'mcp_servers = "not a table here"', '[mcp_serversx.nope]', ].join('\n'); assert.deepEqual(tomlTableNames(toml, 'mcp_servers'), ['also', 'bare_one', 'dotted', 'inline', 'lit', 'spaced']); assert.deepEqual(tomlTableNames('', 'plugins'), []); // Text inside a value is never a key — the leak the first reader had. assert.deepEqual(tomlTableNames(`[mcp_servers]\ndocs.command = "npx"\ndocs.args = [\n "--token",\n "${SECRET}"\n]\n`, 'mcp_servers'), ['docs']); assert.deepEqual(tomlTableNames(`[mcp_servers]\ndocs.d = """\n${SECRET}=1\n[mcp_servers.fake]\n"""\nb = 1\n`, 'mcp_servers'), ['b', 'docs']); assert.deepEqual(tomlTableNames(`[mcp_servers]\nd.x = '''\n${SECRET} = 2\n'''\n`, 'mcp_servers'), ['d']); assert.deepEqual(tomlTableNames('[a]\nx = [\n ["mcp_servers"],\n]\nafter = 1\n[mcp_servers.y]\n', 'mcp_servers'), ['y'], 'a nested array line is not a header, so `after` stays in [a]'); assert.deepEqual(tomlTableNames('mcp_servers = { docs = { command = "x" }, "q.x" = {} }\n', 'mcp_servers'), ['docs', 'q.x'], 'a top-level inline table'); assert.deepEqual(tomlTableNames(String.raw`[mcp_servers."a\"b"]`, 'mcp_servers'), ['a"b'], 'escapes in a quoted key are decoded'); assert.deepEqual(tomlTableNames(String.raw`[mcp_servers."x\U0001F600A\q"]`, 'mcp_servers'), [`x${String.fromCodePoint(0x1f600)}A\\q`], 'TOML escapes, JSON has no \\U; an unknown one is kept'); assert.equal(tomlAgentName('name = """multi"""'), null, 'a multi-line string is never read'); assert.deepEqual(skillMeta('---\nname: foo # a comment\nversion: "1 # kept"\n---\n'), { name: 'foo', version: '1 # kept' }); assert.deepEqual(skillMeta(`---\nname: "a" # was "b"\nversion: 'x' # 'y'\n---\n`), { name: 'a', version: 'x' }, 'the value ends at its own closing quote'); assert.deepEqual(skillMeta('---\nname: "\\u0000\\u202e"\nversion: " "\n---\n'), {}, 'a value of only invisible characters is no value'); assert.deepEqual(skillMeta('---\nname: "\\u200b"\nversion: "\\u061c\\u2060\\ufeff"\n---\n'), {}, 'zero-width and format characters are invisible too'); assert.deepEqual(skillMeta(String.raw`--- name: 'it''s' version: "1\"2" --- `), { name: "it's", version: '1"2' }, "YAML's quote escapes are decoded"); assert.deepEqual(skillMeta('---\nmetadata:\n a:\n version: 9\n version: 2\n---\n'), { version: '2' }, 'a deeper version is not metadata.version'); assert.deepEqual(JSON.parse(stripJsonComments(String.raw`{"u":"http://x//y", // c "b":/* z */1, "q":"a\"//"}`)), { u: 'http://x//y', b: 1, q: 'a"//' }); }); test('E50: the same SKILL.md hashes the same with LF and CRLF line ends', () => { const T = tmp(); try { put(path.join(T, 'a/.claude/skills/s/SKILL.md'), '---\nname: s\n---\nbody\n'); put(path.join(T, 'b/.claude/skills/s/SKILL.md'), '---\r\nname: s\r\n---\r\nbody\r\n'); const h = (d) => detectInstalled(path.join(T, d), { home: null }).items[0].hash; assert.equal(h('a'), h('b')); assert.equal(h('a'), sha(path.join(T, 'a/.claude/skills/s/SKILL.md')), 'a file with no CR hashes as its bytes'); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50/E84: `yad detect` and `yad toolbox` skip the newer-version check — no network, no cache file', () => { // A source pin, because a run from this checkout cannot show it: the check already stays quiet when the // package folder holds `.git`, so dropping `detect` from the skip list would pass every run here. const src = fs.readFileSync(YAD, 'utf8'); assert.match(src, /if \(!\['hook', 'detect', 'toolbox'\]\.includes\(parseArgs\(process\.argv\.slice\(2\)\)\._\[0\]\)\) \{\s*const \{ maybeNotifyUpdate \}/); }); // The command as a person runs it: HOME (and USERPROFILE, which Windows reads) point at a fixture. function yad(args, { cwd, home }) { return spawnSync(process.execPath, [YAD, ...args], { cwd, encoding: 'utf8', env: { ...process.env, HOME: home, USERPROFILE: home, NO_COLOR: '1' }, }); } test('E50: `yad detect --json` answers in the E1 envelope, from a folder that is not a Product', () => { const { T, proj, home } = fixture(); try { const before = snapshot(T); const r = yad(['detect', '--json'], { cwd: proj, home }); assert.equal(r.status, 0, r.stderr); assert.deepEqual(snapshot(T), before, 'the whole command writes nothing, in the folder or the home folder'); const out = JSON.parse(r.stdout); assert.equal(out.command, 'detect'); assert.equal(out.ok, true); assert.equal(typeof out.jsonVersion, 'number'); assert.equal(out.counts.skill, out.items.filter((i) => i.kind === 'skill').length); assert.ok(out.counts.mcp > 0 && out.counts.plugin > 0 && out.counts.agent > 0); assert.ok(!r.stdout.includes(SECRET) && !r.stderr.includes(SECRET)); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E50: `yad detect` prints each place once, caps long lists, and refuses extra words', () => { const { T, proj, home } = fixture(); try { for (let i = 0; i < 12; i++) skill(path.join(proj, '.claude/skills'), `many-${String(i).padStart(2, '0')}`); const r = yad(['detect'], { cwd: proj, home }); assert.equal(r.status, 0, r.stderr); assert.match(r.stdout, /\.claude\/skills \[project\] — 14 — read by Claude Code, Cursor/); assert.match(r.stdout, /… and 6 more/); assert.match(r.stdout, /1 skill name\(s\) are installed in more than one place \(alpha\)/); assert.match(r.stdout, /p2@m(?: \S+)? \(disabled\)/, "the folder's settings.local.json turns p2 off"); assert.ok(!r.stdout.includes(SECRET)); skill(path.join(proj, '.claude/skills'), 'esc', 'name: "evil\u001b[2Jname"\n'); const esc = yad(['detect'], { cwd: proj, home }); assert.ok(!esc.stdout.includes('\u001b'), 'no control character reaches the terminal'); skill(path.join(proj, '.claude/skills'), 'bidi', `name: "abc${String.fromCharCode(0x202e)}def"\n`); const bidi = yad(['detect'], { cwd: proj, home }); assert.ok(!bidi.stdout.includes(String.fromCharCode(0x202e)), 'no character that reorders the line reaches the terminal'); // A Product whose two settings files disagree: every Product command refuses it (E122); `yad detect` // reads none of them, so it still answers. put(path.join(proj, '.sdlc/cli-version.json'), '{"version":"4.0.0"}\n'); put(path.join(proj, '.sdlc/product.json'), '{"schemaVersion":10,"platform":null}\n'); put(path.join(proj, '.sdlc/hub.json'), '{"schemaVersion":10,"platform":"github"}\n'); const drift = yad(['detect', '--json'], { cwd: proj, home }); assert.equal(drift.status, 0, drift.stdout + drift.stderr); assert.equal(JSON.parse(drift.stdout).ok, true); const bad = yad(['detect', 'skills'], { cwd: proj, home }); assert.equal(bad.status, 1); assert.match(bad.stdout, /yad detect takes no words/); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); // ---------- E84: the toolbox ---------- // The shipped list of external tools, and what this machine has of them. It builds on `yad detect`, so it // is tested here, on Linux, macOS and Windows. const { INSTALL_TYPES, TIERS, TOOLBOX, onPath, parseRange, parseVersion, toolProblems, toolStatus, toolboxLines, versionInRange } = await import('./toolbox.mjs'); // E87: each skill's "When a tool is missing" section, built from the toolbox. const { SKILL_FALLBACK_END, SKILL_FALLBACK_HEADING, connectorFile, isFallbackHeading, skillFallbackSection, skillSectionOf, skillSectionProblem, skillsUsing, syncSkillFallbacks, withSkillSection } = await import('./toolbox.mjs'); test('E84: every shipped toolbox entry is well formed, and every tier has entries', () => { for (const t of TOOLBOX) assert.deepEqual(toolProblems(t), [], t.id); const ids = TOOLBOX.map((t) => t.id); assert.equal(new Set(ids).size, ids.length, 'ids are unique'); for (const tier of TIERS) assert.ok(TOOLBOX.some((t) => t.tier === tier), tier); assert.deepEqual(TOOLBOX.filter((t) => t.tier === 'core').map((t) => t.id), ['repomix', 'spec-kit', 'impeccable'], 'the roadmap\'s three core tools'); for (const t of TOOLBOX) for (const r of t.install) assert.ok(INSTALL_TYPES.includes(r.type), `${t.id}: ${r.type}`); // The roadmap's own finding: npm `ecc` is an unrelated crypto library, never ECC's install command. for (const t of TOOLBOX) for (const r of t.install) assert.doesNotMatch(r.command, /\bnpx ecc(@|\s|$)|\bnpm (i|install) (-g )?ecc(\s|$)/, t.id); }); // ---- E88: every toolbox tool is vetted (licence + source) before it ships ---------------------------- const { REPOMIX_VERSION, VET_MAX_AGE_DAYS, isRepoLicenceFile, staleVettings, vettingAge, vettingProblems } = await import('./toolbox.mjs'); test('E88: every shipped toolbox entry carries a complete vetting record', () => { for (const t of TOOLBOX) assert.deepEqual(vettingProblems(t), [], t.id); // The proof matches the answer: an open licence was read from the source's own LICENSE file, a closed // one from the vendor's terms page — never a LICENSE file it does not have. A dual-licensed repo names // each file (LICENSE-APACHE, LICENSE-MIT: Plannotator), as `isRepoLicenceFile` reads them. for (const t of TOOLBOX) { if (t.licence === 'proprietary') assert.doesNotMatch(t.vetted.licenceFrom, /\/LICENSE$/, t.id); else { // A named file only for a dual licence, and only one of the licences it names (`Apache-2.0 OR MIT`). const named = t.licence.includes(' OR ') ? t.licence.split(' OR ').map((l) => l.split('-')[0].toUpperCase()) : []; const file = t.vetted.licenceFrom.split('/').at(-1); assert.ok(t.vetted.licenceFrom.startsWith(`${t.vetted.source}/blob/`) && (file === 'LICENSE' || named.some((n) => file === `LICENSE-${n}`)), `${t.id}: ${t.vetted.licenceFrom}`); } } // Every registry package an install route names is in the record — so a package nobody vetted cannot // ride in on an install line. The forms read: npx / npm exec / npm i|install [-g], with -y or --yes; // uvx / uv tool install / pipx install / pip|pip3 install [-U|--upgrade]. A git URL is not a package. const NPM = /\b(?:npx|npm (?:exec|i|install))(?: (?:-g|--global|-y|--yes))* (@?[A-Za-z0-9][\w./-]*?)(?:@[\w.+^~-]+)?(?=[\s,]|$)/g; const PYPI = /\b(?:uvx|uv tool install|pipx install|pip3? install)(?: (?:-U|--upgrade))* ([A-Za-z0-9][\w.-]*)(?=[\s,]|$)/g; // FAIL CLOSED (review 2): each installer word on a line must yield its package. A form the two readers // do not know — `npm i -D x`, `pip install "x>=1"`, `bunx x`, `pnpm add x` — then fails here, loudly, // instead of checking nothing. One package per installer word: a second bare package after the first // (`npm install a b`) is not read, and no shipped line has one. Widen the readers when a new entry needs it. const INSTALLERS = /\b(?:npx|bunx|npm (?:exec|i|install|add)|pnpm (?:dlx|add)|yarn (?:dlx|add|global add)|uvx|uv tool install|pipx install|pip3? install)\b/g; const GIT_URL = /\binstall (?:-\S+ )*git\+/; const named = (cmd) => [...cmd.matchAll(NPM)].map((m) => `npm:${m[1].toLowerCase()}`) .concat([...cmd.matchAll(PYPI)].map((m) => `pypi:${m[1].toLowerCase()}`)); // The reader itself, on the forms a future entry may use. assert.deepEqual(named('npm install -g repomix@1.18.1'), ['npm:repomix']); assert.deepEqual(named('npx -y foo@1.0.0-beta.1'), ['npm:foo']); assert.deepEqual(named('claude mcp add playwright npx @playwright/mcp@latest'), ['npm:@playwright/mcp']); assert.deepEqual(named('npm exec x, then pip3 install --upgrade Y'), ['npm:x', 'pypi:y']); assert.deepEqual(named('uvx z'), ['pypi:z']); assert.deepEqual(named('pipx install git+https://github.com/a/b.git'), [], 'a git URL is not a registry package'); assert.deepEqual(named('npx x@^1.2'), ['npm:x']); const unread = (cmd) => (cmd.match(INSTALLERS) || []).length - (GIT_URL.test(cmd) ? 1 : 0) !== named(cmd).length; for (const form of ['npm i -D evil', 'pip install "evil>=1"', 'bunx evil', 'pnpm dlx evil', 'uv tool install evil==1.0', 'npx -p evil x', 'npm add evil', 'yarn global add evil', 'pnpm add evil', 'yarn add evil', 'yarn dlx evil']) { assert.ok(unread(form), `${form}: a form the readers do not know must be caught`); } for (const t of TOOLBOX) { const vetted = new Set(t.vetted.packages.map((p) => `${p.registry}:${p.name}`)); for (const r of t.install) { assert.ok(!unread(r.command), `${t.id}: \`${r.command}\` installs something these readers cannot name — widen them`); for (const pkg of named(r.command)) assert.ok(vetted.has(pkg), `${t.id}: ${pkg} is installed but not vetted`); } } }); test('E164: a check run by hand on a pinned version — moving the pin fails until it is run again', async () => { const op = TOOLBOX.find((t) => t.id === 'openpencil'); assert.deepEqual(op.vetted.handCheck, { script: 'scripts/openpencil-node-ids.mjs', package: '@open-pencil/cli', version: '0.16.0' }); assert.ok(fs.existsSync(path.join(ROOT, op.vetted.handCheck.script)), 'the script it names is shipped'); assert.deepEqual(vettingProblems(op), []); const bumped = { ...op, vetted: { ...op.vetted, packages: op.vetted.packages.map((p) => ({ ...p, version: '0.17.0' })) } }; assert.deepEqual(vettingProblems(bumped), ['run scripts/openpencil-node-ids.mjs again: it last passed on @open-pencil/cli@0.16.0, and the pinned version is 0.17.0 — then set vetted.handCheck.version']); for (const handCheck of [null, { script: 'x.mjs', package: '@open-pencil/cli', version: '0.16.0' }, { script: 'scripts/openpencil-node-ids.mjs', package: '@other/pkg', version: '0.16.0' }]) { assert.deepEqual(vettingProblems({ ...op, vetted: { ...op.vetted, handCheck } }), ['vetted.handCheck names its script (scripts/.mjs) and one of vetted.packages'], JSON.stringify(handCheck)); } // The release check reads it through vet-check, which fails on any vetting problem. A fixed day — the newest // vetting of any entry, so none is "after today" and the age rule never turns this test red by itself. const { asVetted, RECOMMENDATIONS } = await import('./recommend.mjs'); const newest = [...TOOLBOX.map((t) => t.vetted.on), ...RECOMMENDATIONS.map(asVetted).map((r) => r.vetted.on)].sort().pop(); const r = spawnSync(process.execPath, [path.join(ROOT, 'scripts/vet-check.mjs'), '--today', newest], { encoding: 'utf8' }); assert.equal(r.status, 0, r.stderr); }); test('E88: vettingProblems names each way a record is incomplete; a team\'s own tool needs none', () => { const good = TOOLBOX.find((t) => t.id === 'repomix'); const bad = (vetted, extra = {}) => vettingProblems({ ...good, ...extra, vetted }); assert.match(bad(undefined).join(), /vetted is set/); for (const on of ['2026-13-45', '2026-02-30', '2025-02-29', '2026-04-31', '26-1-1']) assert.match(bad({ ...good.vetted, on }).join(), /vetted\.on/, on); assert.deepEqual(bad({ ...good.vetted, on: '2024-02-29' }), [], 'a real leap day'); assert.match(bad({ ...good.vetted, licenceFrom: 'https://' }).join(), /licenceFrom/); assert.match(bad({ ...good.vetted, licenceFrom: 'https://github.com/x/y/blob/main/LICENSE.md' }, { licence: 'proprietary' }).join(), /terms page/); assert.match(bad({ ...good.vetted, licenceFrom: 'https://github.com/x/y/blob/main/LICENSE-MIT' }, { licence: 'proprietary' }).join(), /terms page/); // …but a terms PAGE whose address happens to say "license" is the right proof (review 3). for (const page of ['https://vendor.com/license-agreement', 'https://vendor.com/legal/license_terms', 'https://vendor.com/license']) { assert.deepEqual(bad({ ...good.vetted, licenceFrom: page }, { licence: 'proprietary' }), [], page); } // A repository file is told by where it lives, in any letter case, query or not (review 4). for (const file of ['https://github.com/a/b/blob/main/license', 'https://github.com/a/b/blob/main/License.md', 'https://github.com/a/b/blob/main/LICENSE-Apache-2.0', 'https://github.com/a/b/blob/main/LICENSE?plain=1', 'https://raw.githubusercontent.com/a/b/main/COPYING', 'https://git.example.org/a/b/raw/main/LICENCE.txt', 'https://github.com/a/b/blob/main/LICEN%53E', 'https://codeberg.org/a/b/src/branch/main/LICENSE', 'https://gitlab.com/a/b/-/blob/main/LICENSE']) { assert.equal(isRepoLicenceFile(file), true, file); } for (const page of ['https://www.figma.com/legal/tos/', 'https://vendor.com/license', 'https://github.com/a/b/blob/main/README.md', 'not a url', 'https://github.com/org/license-tool', 'https://github.com/org/repo?tab=License-1-ov-file']) { assert.equal(isRepoLicenceFile(page), false, page); } // Every open tool's proof is a repository licence file; no closed tool's is. for (const t of TOOLBOX) assert.equal(isRepoLicenceFile(t.vetted.licenceFrom), t.licence !== 'proprietary', t.id); assert.match(bad({ ...good.vetted, licenceFrom: 'http://x' }).join(), /licenceFrom/); assert.match(bad({ ...good.vetted, source: '' }).join(), /vetted\.source/); assert.match(bad({ ...good.vetted, release: '' }).join(), /vetted\.release/); assert.match(bad({ ...good.vetted, packages: [{ registry: 'cargo', name: 'x', version: '1.0.0' }] }).join(), /registry/); assert.match(bad({ ...good.vetted, packages: [{ registry: 'npm', name: 'x', version: 'latest' }] }).join(), /full version/); assert.match(bad({ ...good.vetted, note: '' }).join(), /note/); assert.match(bad(good.vetted, { licence: 'proprietary' }).join(), /terms page/); assert.deepEqual(bad({ ...good.vetted, release: null, packages: [] }), []); }); test('E88: the age is checked against a day passed in, and only past the limit', () => { const t = { ...TOOLBOX[0], id: 'x', name: 'X', vetted: { ...TOOLBOX[0].vetted, on: '2026-01-01' } }; assert.equal(vettingAge(t, new Date('2026-01-01T23:59:00Z')), 0); assert.equal(vettingAge(t, new Date('2026-07-01T00:00:00Z')), 181); const on = (d) => staleVettings(new Date(`${d}T12:00:00Z`), [t]); const limit = new Date(Date.UTC(2026, 0, 1 + VET_MAX_AGE_DAYS)).toISOString().slice(0, 10); const past = new Date(Date.UTC(2026, 0, 2 + VET_MAX_AGE_DAYS)).toISOString().slice(0, 10); assert.deepEqual(on(limit), [], 'exactly the limit is still current'); assert.deepEqual(on(past), [{ id: 'x', name: 'X', on: '2026-01-01', age: VET_MAX_AGE_DAYS + 1, why: 'stale' }]); // A date after today is refused too (review 1): a typo of 2027 for 2026 would keep the tool out of the // gate for a year. assert.deepEqual(on('2025-12-31'), [{ id: 'x', name: 'X', on: '2026-01-01', age: -1, why: 'future' }]); }); test('E88: scripts/vet-check.mjs passes on a vetted list and names each stale tool with what to do', async () => { const run = (...a) => spawnSync(process.execPath, [path.join(ROOT, 'scripts/vet-check.mjs'), ...a], { encoding: 'utf8' }); const { RECOMMENDATIONS, asVetted } = await import('./recommend.mjs'); const newest = [...TOOLBOX, ...RECOMMENDATIONS].map((x) => x.vetted.on).sort().at(-1); const ok = run('--today', newest); assert.equal(ok.status, 0, ok.stderr); assert.match(ok.stdout, new RegExp(`all ${TOOLBOX.length} toolbox tools and ${RECOMMENDATIONS.length} recommended skills are vetted`)); const later = new Date(Date.parse(`${newest}T00:00:00Z`) + (VET_MAX_AGE_DAYS + 1) * 86400000).toISOString().slice(0, 10); const stale = run('--today', later); assert.equal(stale.status, 1); for (const t of TOOLBOX) assert.match(stale.stderr, new RegExp(`^${t.id} \\(.*cli/toolbox\\.mjs\\)`, 'm')); // E52: every recommended skill carries the same record and is held to the same age. for (const r of RECOMMENDATIONS.map(asVetted)) assert.ok(stale.stderr.split('\n').some((l) => l.startsWith(`${r.id} (`) && l.includes('cli/recommend.mjs')), r.id); assert.match(stale.stderr, /re-vet each one in the file named/); for (const bad of ['soon', '2026-13-01', '2026-02-30']) assert.equal(run('--today', bad).status, 2, bad); // A vetting date after today fails the release too. const before = new Date(Date.parse(`${TOOLBOX.map((x) => x.vetted.on).sort()[0]}T00:00:00Z`) - 86400000).toISOString().slice(0, 10); const early = run('--today', before); assert.equal(early.status, 1); assert.match(early.stderr, /which is after today/); assert.doesNotMatch(early.stderr, /re-vet each one/, 'a future date is a typo to fix, not a licence to re-read'); // The release check runs it, as step 8 of 9. const rc = fs.readFileSync(path.join(ROOT, 'scripts/release-check.sh'), 'utf8'); assert.match(rc, /say "8\/9 {2}every toolbox tool and recommended skill was vetted recently"/); assert.match(rc, /^node "\$ROOT\/scripts\/vet-check\.mjs" \|\| die/m); // And step 9 (E134): the lifecycle defaults earlier releases shipped are unchanged. assert.match(rc, /say "9\/9 {2}the lifecycle defaults earlier releases shipped are unchanged"/); assert.match(rc, /^bash "\$ROOT\/scripts\/lifecycle-defaults-check\.sh"$/m); assert.equal((rc.match(/say "\d\/[78] /g) || []).length, 0, 'a step still counts to 7 or 8'); }); test('E88: Repomix runs at its vetted version everywhere yad names it — never @latest', () => { assert.equal(REPOMIX_VERSION, TOOLBOX.find((t) => t.id === 'repomix').vetted.packages.find((p) => p.name === 'repomix').version); assert.ok(parseVersion(REPOMIX_VERSION)?.full); // Every Repomix command in the code and in the skills (which write it out as text) is the vetted one. // `/plugin install repomix-mcp@repomix` names a marketplace, not a version, and is not matched. const files = []; const walk = (dir) => { for (const e of fs.readdirSync(dir, { withFileTypes: true })) { const p = path.join(dir, e.name); if (e.isDirectory()) walk(p); else if (/\.(mjs|md|ya?ml|csv)$/.test(e.name) && !/^test/.test(e.name)) files.push(p); } }; walk(path.join(ROOT, 'cli')); walk(path.join(ROOT, 'skills')); for (const doc of ['docs/CLI.md', 'docs/WALKTHROUGH.md', 'TEAM-GUIDE.md', 'docs/sdlc-site/public/report.html']) files.push(path.join(ROOT, doc)); let seen = 0; const at = REPOMIX_VERSION.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); for (const f of files) { const text = fs.readFileSync(f, 'utf8'); const rel = path.relative(ROOT, f); for (const m of text.matchAll(/\brepomix@([^\s`'",)<\]]+)/g)) { seen += 1; if (m[1] === '${REPOMIX_VERSION}') continue; // the code reads the constant itself assert.equal(m[1], REPOMIX_VERSION, `${rel}: repomix@${m[1]}`); } // No version at all runs the newest, as `@latest` does: `npx repomix`, `npx -y repomix`, `npm exec repomix`. assert.doesNotMatch(text, /\b(?:npx|bunx|npm (?:exec|i|install|add)|pnpm (?:dlx|add)|yarn (?:dlx|add|global add))(?:\s+(?:-g|--global|-y|--yes|-D|--save-dev|-p|--package|--))*(?:\s+|=)repomix(?![@\w-])/, `${rel}: Repomix run or installed without the vetted version`); assert.doesNotMatch(text, new RegExp(`\\brepomix@(?!${at}\\b)[\\w.-]`), `${rel}: another Repomix version`); } assert.ok(seen >= 10, `expected the pinned command in the skills and docs, found ${seen}`); const setup = fs.readFileSync(path.join(ROOT, 'cli/setup.mjs'), 'utf8'); assert.match(setup, /`repomix@\$\{REPOMIX_VERSION\}`/, 'yad setup and yad repo refresh run the vetted version'); assert.doesNotMatch(setup, /repomix@latest/); }); test('E88: yad toolbox list prints each shipped tool\'s licence and vetting day; a team\'s own tool has none', () => { const rows = TOOLBOX.map((t) => ({ ...t, status: { state: 'missing' }, used: false })); const out = toolboxLines([...rows, { ...rows[0], id: 'mine', name: 'Mine', tier: 'project', licence: null, vetted: null }]).join('\n'); assert.match(out, new RegExp(`licence MIT, vetted ${TOOLBOX[0].vetted.on}`)); assert.equal((out.match(/vetted \d{4}-/g) || []).length, TOOLBOX.length, 'one line per shipped tool, none for the team\'s'); }); test('E84: a fallback a skill records is written there word for word, so E87 renames nothing', () => { for (const t of TOOLBOX.filter((x) => x.records)) { const skills = t.usedBy.filter((u) => fs.existsSync(path.join(ROOT, 'skills', u, 'SKILL.md'))); assert.ok(skills.length, `${t.id}: names a skill that exists`); // Only the body, and outside the E87 section, which quotes every record: the skill's own steps must // write the line. The description is left out too (yad-spec's names the record). const body = (s) => withSkillSection(fs.readFileSync(path.join(ROOT, 'skills', s, 'SKILL.md'), 'utf8'), null).replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, ''); for (const s of skills) assert.ok(body(s).includes(t.records), `${s} writes "${t.records}"`); } }); // E87: every skill a tool names says what it does without it, in the toolbox's own words. Held in both // directions: a skill the toolbox names has the section, word for word, and a skill with the section is // one the toolbox names. `node scripts/skill-fallbacks.mjs` rewrites the sections after a wording change. test('E87: every skill a tool names quotes its fallback word for word, and no other skill has the section', () => { const skills = fs.readdirSync(path.join(ROOT, 'skills')).filter((s) => fs.existsSync(path.join(ROOT, 'skills', s, 'SKILL.md'))); const named = new Set(TOOLBOX.filter((t) => t.tier !== 'recommended').flatMap(skillsUsing)); assert.ok(named.size >= 9, 'the toolbox names the skills that use its tools'); for (const t of TOOLBOX) for (const u of t.usedBy) assert.ok(u.startsWith('yad ') || skills.includes(u), `${t.id}: usedBy "${u}" is a yad command or a skill folder`); for (const s of skills) { const text = fs.readFileSync(path.join(ROOT, 'skills', s, 'SKILL.md'), 'utf8'); // One copy at most, in any spelling, closed by its end marker: a second, stale one would be read by // the agent too, and a section without its marker cannot be rewritten. assert.equal(skillSectionProblem(text), null, `skills/${s}/SKILL.md`); const found = skillSectionOf(text); if (named.has(s)) assert.equal(found, skillFallbackSection(s), `skills/${s}/SKILL.md: the section matches the toolbox — run node scripts/skill-fallbacks.mjs`); else assert.equal(found, null, `skills/${s}/SKILL.md has the section, but no toolbox tool names ${s}`); } // The rewriting script agrees: nothing to change. const r = spawnSync(process.execPath, [path.join(ROOT, 'scripts', 'skill-fallbacks.mjs'), '--check'], { encoding: 'utf8' }); assert.equal(r.status, 0, r.stdout + r.stderr); }); // #244: a skill that runs `yad` starts with a block that says it needs the `yad` command, and what to do when // it is missing — written from cli/skill-yad-cli.mjs by scripts/skill-yad-cli.mjs, as the E87 section is. const { YAD_CLI_BEGIN, YAD_CLI_END, YAD_CLI_LINES, YAD_CLI_MENTIONS_ONLY, ownLines, skillRunsYad, syncSkillYadCli, withYadCliBlock, yadCliBlock, yadCliBlockOf } = await import('./skill-yad-cli.mjs'); // #244: held in both directions over the real skills, as E87 is: a skill that runs `yad` has the block word for // word, right after its `# ` title; a skill that runs none has no block. `node scripts/skill-yad-cli.mjs` // rewrites them after a wording change. test('#244: every skill that runs yad starts with the yad-cli block word for word, and no other skill has it', () => { const skills = fs.readdirSync(path.join(ROOT, 'skills')).filter((s) => fs.existsSync(path.join(ROOT, 'skills', s, 'SKILL.md'))); const block = yadCliBlock(); const without = []; for (const s of skills) { const text = fs.readFileSync(path.join(ROOT, 'skills', s, 'SKILL.md'), 'utf8'); const lines = text.replace(/\r\n/g, '\n').split('\n'); if (!skillRunsYad(s, text)) { without.push(s); assert.equal(yadCliBlockOf(text), null, `skills/${s}/SKILL.md has the yad-cli block, but runs no yad command — run node scripts/skill-yad-cli.mjs`); continue; } assert.equal(yadCliBlockOf(text), block, `skills/${s}/SKILL.md: the yad-cli block matches cli/skill-yad-cli.mjs — run node scripts/skill-yad-cli.mjs`); assert.equal(lines.filter((l) => l === YAD_CLI_BEGIN).length, 1, `skills/${s}/SKILL.md: one block`); // Right after the title, and below the frontmatter, so the description is never touched. const title = lines.findIndex((l, i) => i > lines.indexOf('---', 1) && /^# \S/.test(l)); assert.ok(title > 0, `skills/${s}/SKILL.md has a # title below its frontmatter`); assert.deepEqual(lines.slice(title + 1, title + 3), ['', YAD_CLI_BEGIN], `skills/${s}/SKILL.md: the block is not right after the # title — move it under the # title`); } // The skills that run no yad, each for a reason the rule or YAD_CLI_MENTIONS_ONLY gives. assert.deepEqual(without.sort(), ['yad-connect-docs', 'yad-learn', 'yad-pr-template']); for (const s of Object.keys(YAD_CLI_MENTIONS_ONLY)) { const text = fs.readFileSync(path.join(ROOT, 'skills', s, 'SKILL.md'), 'utf8'); assert.ok(ownLines(text).some((l) => /`yad [a-z]/.test(l)), `${s} still names a yad command; drop it from YAD_CLI_MENTIONS_ONLY if not`); } // yad-guide still starts a workspace before `yad` is installed. const guide = fs.readFileSync(path.join(ROOT, 'skills', 'yad-guide', 'SKILL.md'), 'utf8'); for (const cmd of ['npx -y yadflow@4 new', 'npx -y yadflow@4 join', 'npx -y yadflow@4 member add']) assert.ok(guide.includes(cmd), cmd); // The rewriting script agrees: nothing to change. const r = spawnSync(process.execPath, [path.join(ROOT, 'scripts', 'skill-yad-cli.mjs'), '--check'], { encoding: 'utf8' }); assert.equal(r.status, 0, r.stdout + r.stderr); }); test('#244: the block checks for yad, says how to install it or use npx, and why the CLI is needed', () => { const b = yadCliBlock(); assert.ok(b.startsWith(`${YAD_CLI_BEGIN}\n`) && b.endsWith(`\n${YAD_CLI_END}`)); assert.match(b, /`command -v yad`/, 'the check'); assert.match(b, /`\(Get-Command yad -ErrorAction SilentlyContinue\)\.Source`/, 'the PowerShell check also prints nothing or a path'); assert.match(b, /`npm install -g yadflow@latest`/, 'the install'); assert.match(b, /`npx -y yadflow@4 …`/, 'the way without the install'); assert.match(b, /the CLI is what enforces the approvals/, 'why'); assert.match(b, /Before its first `yad …` command/, 'the stop is before a yad command, so npx steps still run'); assert.doesNotMatch(b, /\n\n\n/, 'no double blank line'); assert.equal(YAD_CLI_LINES[0], ''); assert.equal(YAD_CLI_LINES.at(-1), ''); }); test('#244: a skill runs yad when its own words name a yad command — not its frontmatter, a generated block or the E87 section', () => { assert.equal(skillRunsYad('s', '# S\n\nRun `yad guide --json`.\n'), true, 'inline code'); assert.equal(skillRunsYad('s', '# S\n\n```bash\n$ yad next\n```\n'), true, 'a code block line'); assert.equal(skillRunsYad('s', '# S\n\n```bash\n yad gate status EP-x\n```\n'), true, 'indented'); assert.equal(skillRunsYad('s', '# S\n\nSee `yad-status` and the yad CLI.\n'), false, 'a skill name or a bare word is not a command'); assert.equal(skillRunsYad('s', '# S\n\nRun `npx -y yadflow@4 new acme`.\n'), false, 'npx runs without the install'); assert.equal(skillRunsYad('s', "---\nname: s\ndescription: 'run `yad next`'\n---\n\n# S\n\nnothing\n"), false, 'the frontmatter'); assert.equal(skillRunsYad('s', '# S\n\n\nrun `yad brain status`\n\n'), false, 'a generated block'); assert.equal(skillRunsYad('s', `# S\n\n${yadCliBlock()}\n`), false, 'the block itself'); assert.equal(skillRunsYad('s', `# S\n\n${SKILL_FALLBACK_HEADING}\n\nrun \`yad toolbox list --json\`\n\n${SKILL_FALLBACK_END}\n\n## Steps\n`), false, 'the E87 section'); assert.equal(skillRunsYad('s', `# S\n\n${SKILL_FALLBACK_HEADING}\n\nx\n\n${SKILL_FALLBACK_END}\n\nRun \`yad next\`.\n`), true, 'words after a region count'); assert.equal(skillRunsYad('s', '# S\r\n\r\nRun `yad next`.\r\n'), true, 'CRLF'); assert.equal(skillRunsYad('s', '---\nname: s\nRun `yad next`\n'), false, 'an unclosed frontmatter is all frontmatter'); for (const s of Object.keys(YAD_CLI_MENTIONS_ONLY)) assert.equal(skillRunsYad(s, '# S\n\nRun `yad next`.\n'), false, s); assert.deepEqual(ownLines('# S\n\nin\n\nout'), ['# S', 'out']); }); test('#244: the block goes right after the `# ` title, past the frontmatter and any code fence, and keeps CRLF', () => { const block = yadCliBlock(); const fm = '---\nname: s\ndescription: d\n---\n'; assert.equal(withYadCliBlock(`${fm}\n# S\n\nRun \`yad next\`.\n`, true).text, `${fm}\n# S\n\n${block}\n\nRun \`yad next\`.\n`); assert.equal(withYadCliBlock('# S\nRun `yad next`.\n', true).text, `# S\n\n${block}\n\nRun \`yad next\`.\n`, 'a blank line is added below'); assert.equal(withYadCliBlock('```md\n# not this\n```\n# S\n\nx\n', true).text, `\`\`\`md\n# not this\n\`\`\`\n# S\n\n${block}\n\nx\n`, 'a title in a fence is skipped'); assert.equal(withYadCliBlock('~~~\n```\n# not this\n~~~\n# S\n', true).text, `~~~\n\`\`\`\n# not this\n~~~\n# S\n\n${block}\n`, 'a fence closes only with its own mark'); assert.equal(withYadCliBlock('# S\r\n\r\nx\r\n', true).text, `# S\n\n${block}\n\nx\n`.replace(/\n/g, '\r\n'), 'CRLF kept'); for (const t of ['## Only a section\n\nx\n', '---\nname: s\n# S\n', '```\n# S\n```\n']) { const r = withYadCliBlock(t, true); assert.equal(r.text, t, JSON.stringify(t)); assert.match(r.refused, /no `# ` title line/); } assert.deepEqual(withYadCliBlock('# S\n\nx\n', false), { text: '# S\n\nx\n', refused: null }, 'no block wanted, none there'); }); test('#244: a byte-order mark, a fence that does not close, markers in a fence, and mixed line endings', () => { const block = yadCliBlock(); // A byte-order mark before the frontmatter, or before the title, as toolbox.mjs's sectionBounds allows. const bom = "\uFEFF---\nname: s\ndescription: 'run `yad next`'\n---\n\n# S\n\nx\n"; assert.equal(skillRunsYad('s', bom), false, 'the frontmatter after a BOM is still frontmatter'); assert.equal(withYadCliBlock(bom, true).text, `\uFEFF---\nname: s\ndescription: 'run \`yad next\`'\n---\n\n# S\n\n${block}\n\nx\n`); assert.equal(withYadCliBlock('\uFEFF# S\n\nx\n', true).text, `\uFEFF# S\n\n${block}\n\nx\n`, 'a title on the first line, after a BOM'); // A closing fence has nothing after its mark (CommonMark): "```js" inside a fence does not close it. assert.equal(withYadCliBlock('```\n```js\n# not this\n```\n# S\n', true).text, `\`\`\`\n\`\`\`js\n# not this\n\`\`\`\n# S\n\n${block}\n`); assert.equal(withYadCliBlock('````\n```\n# not this\n````\n# S\n', true).text, `\`\`\`\`\n\`\`\`\n# not this\n\`\`\`\`\n# S\n\n${block}\n`, 'a shorter mark does not close a longer fence'); assert.equal(skillRunsYad('s', '# S\n\n```\n``` x\n$ yad next\n```\n'), true, 'still in the fence: a code line'); // A marker or the E87 heading in a fence is an example, not a region: the text after it still counts. assert.equal(skillRunsYad('s', '# S\n\n```md\n\n```\n\nRun `yad next`.\n\n\n'), true, 'a generated marker in a fence'); assert.equal(skillRunsYad('s', `# S\n\n\`\`\`md\n${SKILL_FALLBACK_HEADING}\n\`\`\`\n\nRun \`yad next\`.\n\n${SKILL_FALLBACK_END}\n`), true, 'the E87 heading in a fence'); assert.deepEqual(ownLines('# S\n```\n\n```\nout'), ['# S', '```', '', '```', 'out']); // Each line yad does not write keeps its own ending; yad's lines take the ending of the line they follow. const mixed = '# S\r\nintro\nmore\r\n'; const put = withYadCliBlock(mixed, true).text; assert.equal(put, `# S\r\n\r\n${block.replace(/\n/g, '\r\n')}\r\n\r\nintro\nmore\r\n`); assert.equal(withYadCliBlock(put, false).text, '# S\r\n\r\nintro\nmore\r\n', 'taken out, the rest byte for byte'); assert.equal(withYadCliBlock('# S', true).text, `# S\n\n${block}\n`, 'a title with no newline at the end of the file'); }); test('#244: the sync writes, rewrites and removes the block, and refuses markers it cannot trust', () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'yad-244-')); try { const block = yadCliBlock(); const old = `${YAD_CLI_BEGIN}\n\nold words\n\n${YAD_CLI_END}`; const put = (s, text) => { fs.mkdirSync(path.join(dir, s), { recursive: true }); fs.writeFileSync(path.join(dir, s, 'SKILL.md'), text); }; const get = (s) => fs.readFileSync(path.join(dir, s, 'SKILL.md'), 'utf8'); fs.mkdirSync(path.join(dir, 'sdlc')); // a folder with no SKILL.md is not a skill put('runs', '---\nname: runs\ndescription: d\n---\n\n# Runs\n\nRun `yad guide --json`.\n'); put('quiet', "---\nname: quiet\ndescription: 'names `yad next`'\n---\n\n# Quiet\n\nNo command here.\n"); put('gone', `# Gone\n\n${old}\n\nNo command here.\n`); put('stale', `# Stale\n\n${old}\n\nRun \`yad next\`.\n`); put('crlf', `# Crlf\n\n${old}\n\nRun \`yad next\`.\n`.replace(/\n/g, '\r\n')); const twice = `# Twice\n\n${old}\n\n${old}\n\nRun \`yad next\`.\n`; put('twice', twice); const backwards = `# Backwards\n\n${YAD_CLI_END}\n${YAD_CLI_BEGIN}\n\nNo command here.\n`; put('backwards', backwards); const notitle = 'Run `yad next`.\n'; put('notitle', notitle); put('yad-connect-docs', '# Docs\n\nyad-docs drives `yad docs deploy`.\n'); const before = fs.readdirSync(dir).filter((s) => s !== 'sdlc').map(get); const stale = ['crlf', 'gone', 'runs', 'stale']; const refused = (r) => r.refused.map((x) => x.skill); const c = syncSkillYadCli(dir, { check: true }); assert.deepEqual([c.stale, c.wrote, refused(c)], [stale, [], ['backwards', 'notitle', 'twice']], 'check names what a write would change or refuse'); assert.match(c.refused.find((x) => x.skill === 'twice').reason, /exactly one line/); assert.match(c.refused.find((x) => x.skill === 'notitle').reason, /no `# ` title/); assert.deepEqual(fs.readdirSync(dir).filter((s) => s !== 'sdlc').map(get), before, 'check writes nothing'); const w = syncSkillYadCli(dir); assert.deepEqual([w.stale, w.wrote, refused(w)], [stale, stale, ['backwards', 'notitle', 'twice']]); assert.equal(get('runs'), `---\nname: runs\ndescription: d\n---\n\n# Runs\n\n${block}\n\nRun \`yad guide --json\`.\n`); assert.equal(yadCliBlockOf(get('runs')), block); assert.equal(get('quiet'), "---\nname: quiet\ndescription: 'names `yad next`'\n---\n\n# Quiet\n\nNo command here.\n", 'a skill that runs no yad gets none'); assert.equal(get('gone'), '# Gone\n\nNo command here.\n', 'a skill that stopped running yad loses it, and its blank line'); assert.equal(get('stale'), `# Stale\n\n${block}\n\nRun \`yad next\`.\n`, 'rewritten in place'); assert.equal(get('crlf'), `# Crlf\n\n${block}\n\nRun \`yad next\`.\n`.replace(/\n/g, '\r\n'), 'CRLF kept'); assert.equal(get('twice'), twice, 'refused: left as it is'); assert.equal(get('backwards'), backwards); assert.equal(get('notitle'), notitle); assert.equal(get('yad-connect-docs'), '# Docs\n\nyad-docs drives `yad docs deploy`.\n', 'a skill that only names a command another runs'); const again = syncSkillYadCli(dir, { check: true }); assert.deepEqual(again.stale, [], 'a second run changes nothing'); assert.equal(yadCliBlockOf('# S\n'), null); assert.deepEqual(syncSkillYadCli(path.join(dir, 'none')), { stale: [], wrote: [], refused: [] }, 'no skills folder'); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test('E87: the section says when to use each tool, its fallback, and what to record', () => { assert.equal(skillFallbackSection('yad-epic'), null, 'a skill no tool names gets no section'); const spec = skillFallbackSection('yad-spec'); assert.ok(spec.startsWith(`${SKILL_FALLBACK_HEADING}\n`)); assert.match(spec, /`yad toolbox list --json`/, 'decide from yad\'s answer'); assert.match(spec, /`used: true` and `status\.state` is `installed` or `available`/); assert.match(spec, /`yad toolbox remove spec-kit`/, 'a team skip means the fallback'); assert.ok(spec.includes(` - Fallback — ${TOOLBOX.find((t) => t.id === 'spec-kit').fallback}.\n - Record \`speckit: not-installed\`.`)); // A light spec chose not to run Spec Kit: the section names its own line, so the two never disagree (#348). assert.ok(spec.includes('whatever the reason — except a light spec, which never runs Spec Kit and records `speckit: not-used` (#348).')); // A connector follows the file its connect skill writes, not the toolbox's use flag. const ui = skillFallbackSection('yad-ui'); assert.match(ui, /\*\*Figma\*\* \(`figma`, a connector\)\. Used when `\.sdlc\/design\.json` connects it/); assert.doesNotMatch(ui, /yad toolbox remove figma/); assert.match(ui, /For Impeccable \(the one tool here that is not a connector\), decide from yad's answer/, 'the rules are for the core tool'); assert.match(spec, /\nFor Spec Kit, decide from yad's answer/, 'with no connector, the tool is named plainly'); assert.match(ui, /yad-connect-design writes that file; follow it, not yad's toolbox answer/); // A skill whose tools are all connectors is not told to ask yad, then to ignore the answer. for (const s of ['yad-learn', 'yad-test-cases', 'yad-connect-design', 'yad-connect-testing', 'yad-connect-learning']) { assert.doesNotMatch(skillFallbackSection(s), /yad toolbox list --json|used: false/, s); } assert.doesNotMatch(skillFallbackSection('yad-learn'), /\n\n\n/, 'no double blank line'); assert.match(spec, /`product` is null/, 'no Product means the team choices were not read'); assert.match(spec, /never when the entry says `used: false`/, 'a tool yad cannot see is used, but never against a skip'); assert.match(skillFallbackSection('yad-connect-design'), /This skill connects it, by writing `\.sdlc\/design\.json`/, 'the connect skill does not follow its own file'); assert.equal(connectorFile(TOOLBOX.find((t) => t.id === 'deeptutor')), '.sdlc/learning.json'); assert.equal(connectorFile(TOOLBOX.find((t) => t.id === 'spec-kit')), null); // Recommended tools are bound with `yad skill bind`, never named by a skill. const fake = [{ ...TOOLBOX.find((t) => t.id === 'ecc'), usedBy: ['yad-epic'] }]; assert.equal(skillFallbackSection('yad-epic', fake), null); }); test('E87: the section is exactly heading to end marker, found the same way in a CRLF file and never in a fence', () => { const section = `${SKILL_FALLBACK_HEADING}\n\nbody\n\n${SKILL_FALLBACK_END}`; const lf = '# Skill\n\nintro\n\n```md\n## not a heading\n```\n\n## Conventions\n\n- x\n'; const added = withSkillSection(lf, section); assert.equal(added, `# Skill\n\nintro\n\n\`\`\`md\n## not a heading\n\`\`\`\n\n${section}\n\n## Conventions\n\n- x\n`, 'before the first real heading'); assert.equal(skillSectionOf(added), section); assert.equal(withSkillSection(added, section), added, 'writing it again changes nothing'); assert.equal(withSkillSection(added, null), lf, 'null takes it out again, with its blank line'); // A Windows checkout: the same answers, and the file keeps its CRLF endings. const crlf = added.replace(/\n/g, '\r\n'); assert.equal(skillSectionOf(crlf), section); assert.equal(withSkillSection(crlf, section), crlf); assert.equal(withSkillSection(crlf, section.replace('body', 'body 2')), crlf.replace('body', 'body 2')); // The last thing in a file, a file with no heading at all, and an empty file. assert.equal(skillSectionOf(`# S\n\n${section}\n\n\n`), section); assert.equal(withSkillSection('# S\n\nintro\n', section), `# S\n\nintro\n\n${section}\n`); assert.equal(withSkillSection('', section), `${section}\n`); // YAML frontmatter is metadata: a `## comment` line in it is not where a section goes. for (const fm of ['---\nname: x\n## a yaml comment\n---\n', '---\ndescription: |\n ## Usage\n---\n']) { assert.equal(withSkillSection(`${fm}\n# S\n\n## Steps\n`, section), `${fm}\n# S\n\n${section}\n\n## Steps\n`, JSON.stringify(fm)); } // With a byte-order mark too. A section inside what looks like frontmatter (a file opening with a // `---` divider) shows as a marker with no heading: refused, never hidden behind a second copy. assert.equal(withSkillSection('\uFEFF---\nname: x\n## c\n---\n\n## Steps\n', section), `\uFEFF---\nname: x\n## c\n---\n\n${section}\n\n## Steps\n`); // Frontmatter needs a YAML key on its next line: a `---` divider above a title is Markdown, so a // section after it is found and rewritten in place — even with a `...` line in a code sample. const divided = `---\n# T\n\n${section.replace('body', 'old')}\n\n## Steps\n\n---\n`; assert.equal(skillSectionProblem(divided), null); assert.equal(withSkillSection(divided, section), divided.replace('old', 'body')); const dots = `---\n\n# T\n\n\`\`\`js\nfoo(\n...\n)\n\`\`\`\n\n${section.replace('body', 'old')}\n\n\`\`\`bash\nyad x\n\`\`\`\n\n## Steps\n`; assert.equal(withSkillSection(dots, section), dots.replace('old', 'body')); const again = withSkillSection(withSkillSection(dots, null), section); assert.equal(skillSectionOf(again), section, 'removed, then added again: one copy, read back whole'); assert.equal(again.split('\n').filter(isFallbackHeading).length, 1); // A quoted key on the second line still opens frontmatter (a `# comment` does not: it is a title too). for (const second of ['"name": x', "'name': x"]) { const fm = `---\n${second}\n## c\n---\n`; assert.equal(withSkillSection(`${fm}\n## Steps\n`, section), `${fm}\n${section}\n\n## Steps\n`, second); } // A YAML value that quotes the heading is not the section: a write works, and with a stray marker in // the body it is refused — never a section running across the closing `---`. const quoted = '---\ndescription: |\n ## When a tool is missing\n---\n\n# T\n\n## Steps\n'; assert.equal(withSkillSection(quoted, section), quoted.replace('## Steps', `${section}\n\n## Steps`)); // The block may close with trailing spaces or `...`: the quoted heading stays inside it. for (const close of ['--- ', '...']) { const t = `---\nname: x\ndescription: |\n ## Usage\n${close}\n\n# T\n\n## Steps\n`; assert.equal(withSkillSection(t, section), t.replace('# T\n\n## Steps', `# T\n\n${section}\n\n## Steps`), JSON.stringify(close)); } const stray = `---\ndescription: |\n ## When a tool is missing\n---\n\n# T\n\nintro\n\n${SKILL_FALLBACK_END}\n\n## Steps\n`; assert.match(skillSectionProblem(stray), /without the section's heading/); assert.equal(withSkillSection(stray, section), stray); assert.equal(withSkillSection(stray, null), stray); // Insert then remove gives the file back, whatever sits above the insertion point. for (const t of ['# T\nintro\n## Steps\n', '---\nname: x\n---\n## Steps\n', '# T\n\nintro\n\n## Steps\n', '# S\n\nintro\n', '']) { assert.equal(withSkillSection(withSkillSection(t, section), null), t.endsWith('\n') || t === '' ? t : `${t}\n`, JSON.stringify(t)); } // A removal takes its blank line only when one sits above too: text either side never closes up. assert.equal(withSkillSection(`para A\n${section}\n\npara B\n`, null), 'para A\n\npara B\n'); assert.equal(withSkillSection(`# T\n\nintro\n${section}\n`, null), '# T\n\nintro\n'); // THE POINT OF THE MARKER: whatever Markdown sits inside or after the section, a rewrite replaces // only heading..marker. Headings the finder cannot see (setext, HTML, inside a list) are just text. for (const inside of ['Usage\n=====', '- a\n ---', '

x

', '> ## q', '```\n## fenced\n```', '## Not ours']) { const t = `# S\n\n${SKILL_FALLBACK_HEADING}\n\n${inside}\n\n${SKILL_FALLBACK_END}\n\nUsage\n-----\n\nkeep me\n`; assert.equal(withSkillSection(t, section), `# S\n\n${section}\n\nUsage\n-----\n\nkeep me\n`, JSON.stringify(inside)); } // Only lines outside a fence count: a fenced example of the heading or the marker is not the section. assert.equal(skillSectionOf(`# S\n\n\`\`\`\n${section}\n\`\`\`\n`), null); for (const fence of ['~~~\n```\n~~~', '````\n```\n````', '```md\n## x\n```', '```js x```']) { const t = `# S\n\n${fence}\n\n${section}\n\n## Next\n`; assert.equal(skillSectionOf(t), section, JSON.stringify(fence)); } // One rule for "is this the heading": indent, case, trailing spaces and closing #s all count, so a // copy spelled differently is seen (and refused as a second copy), never kept beside a new one. for (const l of ['## When a tool is missing', ' ## when a tool is missing ', '## When a tool is missing ##', '## When a tool is missing\r']) assert.ok(isFallbackHeading(l), JSON.stringify(l)); for (const l of ['# When a tool is missing', '### When a tool is missing', ' ## When a tool is missing', '##When a tool is missing', '## When a tool is missing \\#', '## When a tool is missing\u00a0']) assert.ok(!isFallbackHeading(l), JSON.stringify(l)); }); test('E87: a section yad cannot read whole is never rewritten', () => { const section = `${SKILL_FALLBACK_HEADING}\n\nbody\n\n${SKILL_FALLBACK_END}`; const cases = [ [`# S\n\n${SKILL_FALLBACK_HEADING}\n\nhand-made, no marker\n\n## Next\n`, /no end marker/], [`# S\n\n${section}\n\n## when a tool is missing ##\n\nold\n`, /heading is there more than once/], [`# S\n\n${section}\n\n${SKILL_FALLBACK_END}\n`, /end marker is there more than once/], [`# S\n\n${SKILL_FALLBACK_END}\n\n## Next\n`, /without the section's heading/], ]; for (const [text, why] of cases) { assert.match(skillSectionProblem(text), why); assert.equal(skillSectionOf(text), null); assert.equal(withSkillSection(text, section), text, 'left as it is'); assert.equal(withSkillSection(text, null), text, 'not removed either'); assert.equal(withSkillSection(text.replace(/\n/g, '\r\n'), section), text.replace(/\n/g, '\r\n')); } // A fence that never closes hides everything after it, so a write could never find what it wrote. for (const text of ['# T\n\n```\ncode\n', `# T\n\n\n\n${section}\n\n## Steps\n`]) { assert.match(skillSectionProblem(text), /never closed \(it opens on line \d+\)/); assert.equal(withSkillSection(text, section), text); } // Each reason says what to do. for (const [text] of cases) assert.match(skillSectionProblem(text), / — (delete|close) /); assert.equal(skillSectionProblem(`# S\n\n${section}\n`), null); assert.equal(skillSectionProblem('# S\n'), null, 'no section is no problem'); assert.equal(skillSectionProblem(`# S\n\n\`\`\`\n${SKILL_FALLBACK_END}\n\`\`\`\n`), null, 'a fenced marker is an example'); }); // Every function that reads a skill's text, on long awkward input: a pattern that backtracks shows up // here as seconds, whichever function holds it. One test for the whole class, so a fix in one place // cannot leave its twin slow (rounds 5 to 7 found them one at a time). test('E87: the section readers stay fast on long, awkward input', () => { const N = 40000; const H = SKILL_FALLBACK_HEADING; const inputs = [ `## a${' '.repeat(N)}x`, `## a${' \t'.repeat(N)}`, `## a ${'#'.repeat(N)}x`, `## a ${'#'.repeat(N)}x#`, `##${' '.repeat(N)}\rx`, `##${' '.repeat(N)}\u2028x`, `\`\`\`${'`'.repeat(N)}\rx`, `~~~${'~'.repeat(N)}\u2029x`, `x${'\n'.repeat(N)}x`, `${H}\n${'\n'.repeat(N)}x`, `${'#'.repeat(N)}`, `${SKILL_FALLBACK_END}${' '.repeat(N)}x`, `${H}\n${'```\n'.repeat(N / 4)}`, ]; for (const input of inputs) { const t0 = Date.now(); isFallbackHeading(input); skillSectionProblem(input); skillSectionOf(input); withSkillSection(input, `${H}\n\nbody\n\n${SKILL_FALLBACK_END}`); withSkillSection(input, null); assert.ok(Date.now() - t0 < 1000, `slow on ${JSON.stringify(input.slice(0, 30))}… (${Date.now() - t0} ms)`); } }); test('E87: the sync writes, rewrites and removes sections, keeps CRLF, and refuses one without its marker', () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'yad-e87-')); try { const tools = [{ ...TOOLBOX.find((t) => t.id === 'spec-kit'), usedBy: ['named', 'crlf', 'stale', 'handmade'] }]; const want = (s) => skillFallbackSection(s, tools); const old = `${SKILL_FALLBACK_HEADING}\n\nold words\n\n${SKILL_FALLBACK_END}`; const put = (s, text) => { fs.mkdirSync(path.join(dir, s), { recursive: true }); fs.writeFileSync(path.join(dir, s, 'SKILL.md'), text); }; const get = (s) => fs.readFileSync(path.join(dir, s, 'SKILL.md'), 'utf8'); put('named', '# Named\n\nintro\n\n## Steps\n\n- do it\n'); put('unnamed', `# Unnamed\n\n${old}\n\n## Steps\n\n- do it\n`); put('crlf', `# Crlf\n\n${old}\n\n## Steps\n`.replace(/\n/g, '\r\n')); // After the marker, a heading no finder reads (setext) — kept, because nothing past the marker is touched. put('stale', `# Stale\n\n${old}\n\nUsage\n=====\n\nkeep me\n`); const handmade = `# Handmade\n\n${SKILL_FALLBACK_HEADING}\n\nno marker\n\nUsage\n=====\n\nkeep me\n`; put('handmade', handmade); const before = fs.readdirSync(dir).map(get); const refused = [{ skill: 'handmade', reason: skillSectionProblem(handmade) }]; assert.match(refused[0].reason, /no end marker/); const stale = ['crlf', 'handmade', 'named', 'stale', 'unnamed']; assert.deepEqual(syncSkillFallbacks(dir, { check: true, tools }), { stale, wrote: [], refused }, 'check names what a write would refuse'); assert.deepEqual(fs.readdirSync(dir).map(get), before, 'check writes nothing'); assert.deepEqual(syncSkillFallbacks(dir, { tools }), { stale, wrote: ['crlf', 'named', 'stale', 'unnamed'], refused }); assert.equal(get('named'), `# Named\n\nintro\n\n${want('named')}\n\n## Steps\n\n- do it\n`); assert.equal(get('unnamed'), '# Unnamed\n\n## Steps\n\n- do it\n', 'a skill no tool names loses the section'); assert.equal(get('crlf'), `# Crlf\n\n${want('crlf')}\n\n## Steps\n`.replace(/\n/g, '\r\n'), 'CRLF kept'); assert.equal(get('stale'), `# Stale\n\n${want('stale')}\n\nUsage\n=====\n\nkeep me\n`, 'everything after the marker kept'); assert.equal(get('handmade'), handmade, 'a section without its marker is left alone'); assert.deepEqual(syncSkillFallbacks(dir, { check: true, tools }), { stale: ['handmade'], wrote: [], refused }, 'the rest is now clean'); // The fix the message gives: delete the old section, and the next run adds a fresh one. put('handmade', '# Handmade\n\nUsage\n=====\n\nkeep me\n'); assert.deepEqual(syncSkillFallbacks(dir, { tools }).wrote, ['handmade']); assert.ok(get('handmade').includes('keep me')); // The last check reads no Markdown: a heading-like line yad cannot see as the section (in a code // block, or indented in a list) would leave two copies after a write, so the write is refused. for (const hidden of ['```md\n## When a tool is missing\n```', `- item\n\n ${SKILL_FALLBACK_END}`]) { const t = `# Hidden\n\n${hidden}\n\n## Steps\n`; put('named', t); const c = syncSkillFallbacks(dir, { check: true, tools }); assert.match(c.refused.find((x) => x.skill === 'named').reason, /another line that looks like/, 'check names it too'); const r = syncSkillFallbacks(dir, { tools }); assert.deepEqual(r.wrote, [], JSON.stringify(hidden)); assert.match(r.refused.find((x) => x.skill === 'named').reason, /another line that looks like/); assert.equal(get('named'), t); } } finally { fs.rmSync(dir, { recursive: true, force: true }); } // The generator's own text always ends with its marker, and is read back whole. for (const s of fs.readdirSync(path.join(ROOT, 'skills'))) { const section = skillFallbackSection(s); if (section) assert.equal(skillSectionOf(`# S\n\n${section}\n`), section, s); } }); test('E84: the connectors are the adapters skills/sdlc/config.yaml names, with the same fallbacks', () => { const yaml = fs.readFileSync(path.join(ROOT, 'skills/sdlc/config.yaml'), 'utf8'); const named = []; for (const section of ['design', 'testing', 'learning']) { const block = yaml.slice(yaml.search(new RegExp(`^${section}:`, 'm'))); const tools = block.match(/^\s+tools:\s*\[([^\]]*)\]/m)[1].split(',').map((x) => x.trim()); const degrade = block.match(/^\s+degrade:\s*([\w-]+)/m)[1]; named.push(...tools); for (const id of tools) { const t = TOOLBOX.find((x) => x.id === id); assert.ok(t, `${section}: ${id} is in the toolbox`); assert.equal(t.tier, 'connector', id); assert.ok(t.fallback.startsWith(degrade), `${id}: the fallback is config.yaml's "${degrade}"`); } } // And the other way: no connector that config.yaml does not name. assert.deepEqual(TOOLBOX.filter((t) => t.tier === 'connector').map((t) => t.id).sort(), [...named].sort()); }); test('E84: toolProblems names each way an entry can be wrong', () => { const good = TOOLBOX[0]; const bad = (patch) => toolProblems({ ...good, ...patch }); assert.deepEqual(toolProblems(good), []); assert.ok(bad({ id: 'Has Spaces' }).some((p) => p.startsWith('id '))); assert.ok(bad({ tier: 'default' }).some((p) => p.startsWith('tier '))); assert.ok(bad({ install: [{ type: 'brew', command: 'brew install x' }] }).some((p) => p.includes("route's type"))); assert.ok(bad({ install: [], manual: null }).some((p) => p.includes('manual steps'))); assert.ok(bad({ install: [], manual: 'https://example.invalid/setup' }).every((p) => !p.includes('manual steps')), 'no command, but a manual link, is fine'); assert.ok(bad({ checked: 'yesterday' }).some((p) => p.startsWith('checked '))); assert.ok(bad({ source: 'http://x' }).some((p) => p.startsWith('source '))); assert.ok(bad({ detect: {} }).some((p) => p.includes('at least one'))); assert.ok(bad({ detect: { skills: 'impeccable' } }).some((p) => p.includes('detect.skills'))); assert.ok(bad({ versions: 'latest' }).some((p) => p.startsWith('versions '))); assert.ok(bad({ fallback: '' }).some((p) => p.startsWith('fallback '))); for (const patch of [{ recordsElse: '' }, { recordsElse: 'a case.' }, { records: null, recordsElse: 'a case' }]) { assert.ok(bad(patch).some((p) => p.startsWith('recordsElse ')), JSON.stringify(patch)); } assert.ok(bad({ usedBy: [] }).length === 0, 'an empty usedBy list is still a list'); assert.ok(bad({ usedBy: 'yad-ui' }).some((p) => p.startsWith('usedBy '))); for (const [patch, start] of [[{ name: '' }, 'name '], [{ role: '' }, 'role '], [{ licence: '' }, 'licence '], [{ records: '' }, 'records '], [{ note: '' }, 'note '], [{ manual: 'ftp://x' }, 'manual '], [{ install: 'npm i x' }, 'install '], [{ detect: { npx: 'yes' } }, 'detect.npx']]) { assert.ok(bad(patch).some((p) => p.startsWith(start)), JSON.stringify(patch)); } assert.ok(bad({ install: [{ type: 'npm', command: '' }] }).some((p) => p.includes('has its command'))); assert.ok(toolProblems(null).length > 5, 'nothing at all is many problems, not a crash'); // E87: a skill's section adds the full stop, and a connector says which file connects it. assert.ok(bad({ fallback: 'writes it by hand.' }).some((p) => p.startsWith('fallback ends'))); assert.ok(bad({ tier: 'connector', usedBy: ['yad-ui'] }).some((p) => p.startsWith('a connector names'))); assert.deepEqual(bad({ tier: 'connector', usedBy: ['yad-connect-testing', 'yad-test-cases'] }), []); }); test('E84: versions and ranges', () => { assert.deepEqual(parseVersion('v1.2'), { parts: [1, 2, 0], pre: null, full: false }); assert.deepEqual(parseVersion('3.7.1-beta.2+build'), { parts: [3, 7, 1], pre: 'beta.2', full: true }); // A range needs all three numbers: each operator reads a partial version differently, and guessing // got `~1`, `^0` and `>1.2` wrong. Refused, so toolProblems rejects the entry. for (const r of ['~1', '^0', '>1.2', '^3.2', '<=2']) assert.equal(parseRange(r), null, r); assert.equal(parseVersion('aa5654b7acb7'), null, 'a git sha is not a version'); assert.equal(parseVersion(null), null); assert.equal(parseRange('latest'), null); const cases = [ ['3.7.1', '>=3.0.0 <4.0.0', true], ['4.0.0', '>=3.0.0 <4.0.0', false], ['2.9.9', '>=3.0.0', false], ['4.0.0-beta', '^3.2.0', false], ['3.9.9', '^3.2.0', true], ['3.1.0', '^3.2.0', false], ['0.2.5', '^0.2.1', true], ['0.3.0', '^0.2.1', false], ['0.0.3', '^0.0.3', true], ['0.0.9', '^0.0.3', false], ['0.0.4-rc.1', '^0.0.3', false], // One rule for pre-releases: an upper bound keeps out its own pre-releases, written or derived. ['4.0.0-beta', '>=3.0.0 <4.0.0', false], ['4.0.0-beta', '<4.0.0-rc.1', true], // Pre-releases in order: alpha < alpha.1 < alpha.beta < beta < beta.2 < beta.11 < rc.1 < release. ['1.0.0-alpha', '<1.0.0-alpha.1', true], ['1.0.0-alpha.1', '<1.0.0-alpha.beta', true], ['1.0.0-beta.2', '<1.0.0-beta.11', true], ['1.0.0-beta.11', '<1.0.0-rc.1', true], ['1.0.0-rc.1', '>=1.0.0-rc.1 <=1.0.0-rc.1', true], ['1.0.0-1', '<1.0.0-alpha', true], ['1.4.9', '~1.4.0', true], ['1.5.0', '~1.4.0', false], ['2.0.0', '2.0.0', true], ['2.0.1', '=2.0.0', false], ['1.0.0', '>1.0.0', false], ['1.0.0', '<=1.0.0', true], ['3.0.0-rc.1', '>=3.0.0', false], ]; for (const [v, r, want] of cases) assert.equal(versionInRange(v, r), want, `${v} in ${r}`); assert.equal(versionInRange('aa5654b7acb7', '>=1.0.0'), null, 'cannot tell'); assert.equal(versionInRange('1.0.0', null), null, 'no range, nothing to say'); }); test('E84: onPath reads the PATH folders and starts nothing', () => { const T = tmp(); try { put(path.join(T, 'a/tool'), '#!/bin/sh\n'); fs.chmodSync(path.join(T, 'a/tool'), 0o755); put(path.join(T, 'a/plain'), 'not runnable'); fs.chmodSync(path.join(T, 'a/plain'), 0o644); fs.mkdirSync(path.join(T, 'a/dir'), { recursive: true }); // POSIX rules need POSIX folders: on the Windows runner a temp folder is `D:\…`, which those rules // rightly call relative (and `:` splits it). The Windows block below covers that runner. if (process.platform !== 'win32') { const env = { PATH: [path.join(T, 'none'), path.join(T, 'a')].join(':') }; assert.equal(onPath('tool', { env, platform: 'linux' }), true); assert.equal(onPath('missing', { env, platform: 'linux' }), false); assert.equal(onPath('dir', { env, platform: 'linux' }), false, 'a folder is not a program'); // An empty or relative entry is "the current folder": never where a tool is installed. const rel = path.relative(process.cwd(), path.join(T, 'a')); assert.equal(onPath('tool', { env: { PATH: `${rel}::` }, platform: 'linux' }), false, 'a relative entry is skipped'); assert.equal(onPath('tool', { env: { PATH: '', Path: path.join(T, 'a') }, platform: 'linux' }), true, 'an empty PATH falls back to Path'); assert.equal(onPath('plain', { env, platform: 'linux' }), false, 'a file that cannot run is not a program'); } // Windows: a program is its name plus a PATHEXT ending. put(path.join(T, 'w/maestro.CMD'), '@echo off'); // Under Windows' rule only a drive and a root, or a share, is absolute. On the Windows runner the // temp folder has a drive; elsewhere `//` + the folder reads as a share AND still names the same // folder on macOS and Linux, so the found side is tested on every runner. const winDir = process.platform === 'win32' ? path.join(T, 'w') : `/${path.join(T, 'w')}`; const winEnv = { Path: winDir, PATHEXT: '.EXE;.CMD' }; assert.equal(onPath('maestro', { env: winEnv, platform: 'win32' }), true); assert.equal(onPath('maestro', { env: { ...winEnv, PATHEXT: '.EXE' }, platform: 'win32' }), false); // Windows accepts an entry in quotes. Only a drive and a root, or a share, is absolute there; the // folder below stands in for one (on a Mac or Linux runner it is a plain absolute path). assert.equal(onPath('maestro', { env: { Path: `"${winDir}"`, PATHEXT: '.CMD' }, platform: 'win32' }), true, 'a quoted entry is read like an unquoted one'); assert.equal(onPath('maestro', { env: { Path: path.join(T, 'w').replace(/^[A-Za-z]:/, ''), PATHEXT: '.CMD' }, platform: 'win32' }), false, 'a root with no drive is the current drive'); for (const rel of ['\\w', 'D:w', '.\\w']) assert.equal(onPath('maestro', { env: { Path: rel, PATHEXT: '.CMD' }, platform: 'win32' }), false, rel); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E84: toolStatus — installed, available through npx, missing; versions warn, never disqualify', () => { const tool = (detect, versions = null) => ({ ...TOOLBOX[0], detect, versions }); const none = () => false; const item = (kind, name, where, version = null) => ({ kind, name, where, version }); assert.equal(toolStatus(tool({ skills: ['Impeccable'] }), [item('skill', 'impeccable', '~/.claude/skills/impeccable', '3.7.1')], { has: none }).state, 'installed', 'names compare without case'); assert.deepEqual(toolStatus(tool({ skillPrefixes: ['speckit-'] }), [item('skill', 'speckit-plan', 'a'), item('skill', 'speckit-tasks', 'b'), item('skill', 'other', 'c')], { has: none }).found, ['a', 'b']); assert.equal(toolStatus(tool({ plugins: ['figma'] }), [item('plugin', 'figma@claude-plugins-official', 'p')], { has: none }).state, 'installed', 'a plugin by its name, without the marketplace'); assert.equal(toolStatus(tool({ plugins: ['figma'] }), [item('plugin', 'figmatic@x', 'p')], { has: none }).state, 'missing', 'not by a prefix'); assert.equal(toolStatus(tool({ plugins: ['figma@claude-plugins-official'] }), [item('plugin', 'figma@claude-plugins-official', 'p')], { has: none }).state, 'installed', 'or by its full id'); assert.equal(toolStatus(tool({ plugins: ['figma@claude-plugins-official'] }), [item('plugin', 'figma@other', 'p')], { has: none }).state, 'missing', 'a full id is exact'); assert.equal(toolStatus(tool({ skillPrefixes: ['SpecKit-'] }), [item('skill', 'speckit-plan', 'a')], { has: none }).state, 'installed', 'a prefix compares without case'); assert.equal(toolStatus(tool({ skills: ['reviewer'] }), [item('agent', 'reviewer', 'a')], { has: none }).state, 'missing', 'an agent is not a skill'); assert.equal(toolStatus(tool({ mcp: ['pencil'] }), [item('mcp', 'pencil', '~/.claude.json')], { has: none }).state, 'installed'); assert.equal(toolStatus(tool({ mcp: ['pencil'] }), [item('skill', 'pencil', 'x')], { has: none }).state, 'missing', 'the kind must match'); assert.deepEqual(toolStatus(tool({ bins: ['deeptutor'] }), [], { has: (b) => b === 'deeptutor' }), { state: 'installed', found: ['deeptutor on PATH'], version: null, inRange: null }); assert.deepEqual(toolStatus(tool({ npx: true }), [], { has: (b) => b === 'npx' }), { state: 'available', found: ['npx on PATH'], version: null, inRange: null }); assert.equal(toolStatus(tool({ npx: true }), [], { has: none }).state, 'missing'); const old = toolStatus(tool({ skills: ['impeccable'] }, '>=4.0.0'), [item('skill', 'impeccable', 'x', '3.7.1')], { has: none }); assert.deepEqual([old.state, old.version, old.inRange], ['installed', '3.7.1', false], 'out of range: still installed'); assert.equal(toolStatus(tool({ skills: ['impeccable'] }, '>=4.0.0'), [item('skill', 'impeccable', 'x', 'aa5654b7acb7')], { has: none }).inRange, null); }); test('E84: a tool found only through a plugin your settings turn off is `disabled`, not installed', () => { const tool = { ...TOOLBOX.find((t) => t.id === 'figma') }; const CC = ['Claude Code']; const plugin = (enabled) => ({ kind: 'plugin', name: 'figma@claude-plugins-official', where: '~/.claude/plugins/installed_plugins.json', agents: CC, version: '2.2.124', plugin: null, enabled }); const server = { kind: 'mcp', name: 'figma', where: 'figma@claude-plugins-official: .mcp.json', agents: CC, version: null, plugin: 'figma@claude-plugins-official' }; const off = toolStatus(tool, [plugin(false), server], { has: () => false }); assert.deepEqual([off.state, off.found.length], ['disabled', 2], 'the plugin AND the server it brings are off'); assert.equal(toolStatus(tool, [plugin(null), server], { has: () => false }).state, 'installed', 'no setting means on'); assert.equal(toolStatus(tool, [plugin(true), server], { has: () => false }).state, 'installed'); // The same server added by hand (no plugin) still counts while the plugin is off. const own = { ...server, where: '~/.claude.json', plugin: null }; assert.deepEqual(toolStatus(tool, [plugin(false), server, own], { has: () => false }).found, ['~/.claude.json']); // A Codex plugin of the same name has its own switch: the Claude Code one being off says nothing about it. const codex = { kind: 'plugin', name: 'figma@claude-plugins-official', where: '~/.codex/config.toml', agents: ['Codex CLI'], version: null, plugin: null }; assert.deepEqual(toolStatus(tool, [plugin(false), codex], { has: () => false }).found, ['~/.codex/config.toml']); // A tool yadflow runs through npx stays available when its plugin is off. const repomix = TOOLBOX.find((t) => t.id === 'repomix'); const rp = { kind: 'plugin', name: 'repomix-mcp@repomix', where: 'p', agents: CC, version: null, plugin: null, enabled: false }; const rs = { kind: 'mcp', name: 'repomix', where: 'repomix-mcp@repomix: .mcp.json', agents: CC, version: null, plugin: 'repomix-mcp@repomix' }; assert.equal(toolStatus(repomix, [rp, rs], { has: (b) => b === 'npx' }).state, 'available'); assert.equal(toolStatus(repomix, [rp, rs], { has: () => false }).state, 'disabled'); const text = toolboxLines([{ ...tool, status: off }]).join('\n'); assert.match(text, /Figma .*: installed, but its plugin is turned off in your Claude Code settings\n\s+without it: markdown-only/); }); test('E84: the printed list — a warning for a version out of range, the fallback for a missing tool', () => { const rows = [ { ...TOOLBOX.find((t) => t.id === 'impeccable'), versions: '>=4.0.0', status: { state: 'installed', found: ['x'], version: '3.7.1', inRange: false } }, { ...TOOLBOX.find((t) => t.id === 'spec-kit'), status: { state: 'missing', found: [], version: null, inRange: null } }, { ...TOOLBOX.find((t) => t.id === 'repomix'), status: { state: 'available', found: ['npx on PATH'], version: null, inRange: null } }, { ...TOOLBOX.find((t) => t.id === 'figma'), status: { state: 'installed', found: ['x'], version: `1${String.fromCharCode(27)}[2J`, inRange: null } }, ]; const text = toolboxLines(rows).join('\n'); assert.match(text, /Impeccable .*: installed 3\.7\.1\n\s+! version 3\.7\.1 is outside the known-good range >=4\.0\.0 — still used/); assert.match(text, /Spec Kit .*: not found\n\s+without it: yad-spec writes the same spec files by hand/); assert.match(text, /Repomix .*: available \(npx fetches it when needed\)/); assert.ok(!text.includes(String.fromCharCode(27)), 'a version read from a file is cleaned for the terminal'); assert.ok(text.indexOf('Core —') < text.indexOf('Connectors —'), 'tiers in order'); assert.ok(!text.includes('Recommended —'), 'a tier with no rows is not printed'); }); test('E84: `yad toolbox list` answers in the E1 envelope, writes nothing, and refuses a word it does not know', () => { const T = tmp(); const proj = path.join(T, 'p'); const home = path.join(T, 'h'); try { fs.mkdirSync(proj, { recursive: true }); skill(path.join(home, '.claude/skills'), 'impeccable', 'name: impeccable\nversion: 3.7.1\n'); put(path.join(home, '.claude.json'), JSON.stringify({ mcpServers: { pencil: { env: { TOKEN: SECRET } } } })); // A Product whose settings disagree: the toolbox reads none of them, so it still answers. put(path.join(proj, '.sdlc/product.json'), '{"schemaVersion":10,"platform":null}\n'); put(path.join(proj, '.sdlc/hub.json'), '{"schemaVersion":10,"platform":"github"}\n'); const before = snapshot(T); const r = yad(['toolbox', '--json'], { cwd: proj, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.deepEqual(snapshot(T), before, 'nothing written'); const out = JSON.parse(r.stdout); assert.equal(out.command, 'toolbox list', '`yad toolbox` is `toolbox list`'); assert.equal(out.tools.length, TOOLBOX.length); const byId = Object.fromEntries(out.tools.map((t) => [t.id, t.status])); assert.deepEqual([byId.impeccable.state, byId.impeccable.version], ['installed', '3.7.1']); assert.equal(byId.pencil.state, 'installed'); assert.ok(!r.stdout.includes(SECRET) && !r.stdout.includes(home)); const human = yad(['toolbox', 'list'], { cwd: proj, home }); assert.equal(human.status, 0, human.stderr); assert.match(human.stdout, /Impeccable .*: installed 3\.7\.1/); for (const [args, re] of [[['toolbox', 'frob'], /unknown toolbox action: frob/], [['toolbox', 'list', 'extra'], /takes no more words/], [['toolbox', 'check', 'extra'], /takes no more words/]]) { const bad = yad(args, { cwd: proj, home }); assert.equal(bad.status, 1, args.join(' ')); assert.match(bad.stdout, re); } } finally { fs.rmSync(T, { recursive: true, force: true }); } }); // ---------- E86: the team's choices ---------- const { connectedTools, customProblems, loadChoices, parseDetect, parseInstall, toolUse, toolboxCheck, toolboxRows } = await import('./toolbox.mjs'); // A Product: settings, plus any files given as { 'rel/path': text }. function product(files = {}) { const T = tmp(); const p = path.join(T, 'p'); const home = path.join(T, 'h'); fs.mkdirSync(home, { recursive: true }); put(path.join(p, '.sdlc/product.json'), '{"schemaVersion":10,"platform":null}\n'); for (const [rel, text] of Object.entries(files)) put(path.join(p, rel), text); return { T, p, home }; } const toolboxJSON = (p) => JSON.parse(fs.readFileSync(path.join(p, '.sdlc/toolbox.json'), 'utf8')); const CUSTOM = { id: 'doclint', role: 'lints the docs', fallback: 'the docs are not linted', detect: { bins: ['doclint-e86'] } }; test('E86: in use by default — the core tools, and the connector a Product connected; a choice overrides either', () => { const none = { shipped: new Map(), connected: new Map() }; const byId = (id) => TOOLBOX.find((t) => t.id === id); assert.deepEqual(toolUse(byId('spec-kit'), none), { used: true, because: 'core' }); assert.deepEqual(toolUse(byId('bmad-method'), none), { used: false, because: null }); assert.deepEqual(toolUse(byId('figma'), none), { used: false, because: null }); const figma = { shipped: new Map(), connected: new Map([['figma', '.sdlc/design.json']]) }; assert.deepEqual(toolUse(byId('figma'), figma), { used: true, because: 'connected', connectedIn: '.sdlc/design.json' }); assert.deepEqual(toolUse(byId('spec-kit'), { ...none, shipped: new Map([['spec-kit', 'skip']]) }), { used: false, because: 'removed' }); assert.deepEqual(toolUse(byId('figma'), { ...figma, shipped: new Map([['figma', 'skip']]) }), { used: false, because: 'removed' }); assert.deepEqual(toolUse(byId('ecc'), { ...none, shipped: new Map([['ecc', 'use']]) }), { used: true, because: 'added' }); // What counts as connected: a connector id the toolbox knows. `none`, an unknown adapter, a core tool // and a broken file name nothing — and none of them stops the read. const { T, p } = product({ '.sdlc/design.json': '{"tool":"pencil"}', '.sdlc/testing.json': '{"tool":"none"}', '.sdlc/learning.json': '{broken', }); try { assert.deepEqual([...connectedTools(p)], [['pencil', '.sdlc/design.json']]); put(path.join(p, '.sdlc/testing.json'), '{"tool":"spec-kit"}'); put(path.join(p, '.sdlc/learning.json'), '{"tool":"my-own-tutor"}'); assert.deepEqual([...connectedTools(p)], [['pencil', '.sdlc/design.json']]); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86: a team\'s own entry — what makes it usable, and the two flag readers', () => { assert.deepEqual(customProblems(CUSTOM), []); assert.deepEqual(customProblems({ ...CUSTOM, install: [{ type: 'npm', command: 'npx doclint' }], source: 'https://example.com', name: 'Doc Lint' }), []); const bad = (t, re) => assert.match(customProblems(t).join('\n'), re, JSON.stringify(t)); bad({ ...CUSTOM, id: 'Doc Lint' }, /id is lower-case/); bad({ ...CUSTOM, id: 'spec-kit' }, /not the id of a shipped tool/); bad({ ...CUSTOM, role: ' ' }, /role says/); bad({ ...CUSTOM, fallback: undefined }, /fallback says/); bad({ ...CUSTOM, detect: {} }, /detect names at least one/); bad({ ...CUSTOM, detect: { programs: ['x'] } }, /detect names at least one/); bad({ ...CUSTOM, detect: { bins: [''] } }, /detect names at least one/); bad({ ...CUSTOM, install: [{ type: 'docker', command: 'x' }] }, /install, when set/); bad({ ...CUSTOM, source: 'http://example.com' }, /https URL/); assert.deepEqual(customProblems('x'), ['an entry is a JSON object']); assert.deepEqual(parseDetect('skill:a, prefix:b-,plugin:c,mcp:d,bin:e,bin:f'), { detect: { skills: ['a'], skillPrefixes: ['b-'], plugins: ['c'], mcp: ['d'], bins: ['e', 'f'] } }); assert.match(parseDetect('program:x').error, /not :/); assert.match(parseDetect('').error, /names nothing/); assert.match(parseDetect('__proto__:x').error, /not :/, 'only the five kinds become keys'); assert.deepEqual(parseInstall('npm: npx doclint --yes '), { route: { type: 'npm', command: 'npx doclint --yes' } }); assert.match(parseInstall('docker: run x').error, /: /); assert.match(parseInstall('npx doclint').error, /: /); }); test('E86: a broken or odd toolbox.json — the list still answers with the defaults, and names each line that does nothing', () => { const doc = { schemaVersion: 10, // `__proto__` from JSON.parse is an own key, not the prototype: it is reported, never applied. shipped: JSON.parse('{"ecc":"use","spec-kit":"maybe","future-tool":"use","__proto__":"use"}'), custom: [CUSTOM, { ...CUSTOM }, { id: 'half' }, 7], }; const { T, p } = product({ '.sdlc/toolbox.json': JSON.stringify(doc) }); try { const c = loadChoices(p); assert.deepEqual([...c.shipped], [['ecc', 'use']]); assert.deepEqual(c.custom.map((t) => [t.id, t.tier, t.name]), [['doclint', 'project', 'doclint']]); const text = c.problems.join('\n'); assert.match(text, /`spec-kit` should be "use" or "skip"/); assert.match(text, /`future-tool` is not a tool this yadflow ships/); assert.match(text, /`__proto__` is not a tool this yadflow ships/); assert.match(text, /`doclint` is listed twice/); assert.match(text, /`half` is ignored — .*role says/); assert.match(text, /number 4 is ignored — an entry is a JSON object/); assert.equal(Object.getPrototypeOf(c.shipped), Map.prototype); put(path.join(p, '.sdlc/toolbox.json'), '{not json'); const broken = loadChoices(p); assert.match(broken.problems[0], /does not parse \[YAD-STATE-001\] — showing the defaults/); put(path.join(p, '.sdlc/toolbox.json'), '{"shipped":["ecc"]}'); assert.match(loadChoices(p).problems[0], /`shipped` must be a JSON object/); put(path.join(p, '.sdlc/toolbox.json'), '{"custom":{"id":"x"}}'); assert.match(loadChoices(p).problems[0], /`custom` must be a JSON list/); assert.deepEqual(loadChoices(null), { problems: [], unreachable: false, shipped: new Map(), custom: [], connected: new Map() }); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86: a team\'s own words are cleaned before they reach the terminal', () => { const ESC = String.fromCharCode(27); const { T, p } = product({ '.sdlc/toolbox.json': JSON.stringify({ custom: [{ ...CUSTOM, name: `Doc${ESC}[2J`, role: `lints${ESC}]0;x`, fallback: `none${ESC}[31m` }] }) }); try { const { rows } = toolboxRows(p, p, { items: [], has: () => false }); const text = toolboxLines(rows).join('\n'); assert.match(text, /Added by this project\n\s+– Doc\?\[2J — lints\?\]0;x: not found \[used here\]\n\s+without it: none\?\[31m/); assert.ok(!text.includes(ESC)); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('#361 Docker MCP Toolkit: a recommended tool, found by its MCP_DOCKER server, added like any other', () => { const t = TOOLBOX.find((x) => x.id === 'docker-mcp'); assert.equal(t.tier, 'recommended'); assert.deepEqual([toolProblems(t), vettingProblems(t)], [[], []]); // The server name is matched whatever its case, as a client config spells it. const { T, p, home } = product({ '.mcp.json': JSON.stringify({ mcpServers: { mcp_docker: { command: 'docker', args: ['mcp', 'gateway', 'run'] } } }) }); try { let r = yad(['toolbox', '--json'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.equal(JSON.parse(r.stdout).tools.find((x) => x.id === 'docker-mcp').status.state, 'installed'); const human = yad(['toolbox', 'list'], { cwd: p, home }).stdout; const recommended = human.slice(human.indexOf('Recommended'), human.indexOf('Connectors')); assert.match(recommended, /Docker MCP Toolkit/, 'listed under Recommended'); r = yad(['toolbox', 'add', 'docker-mcp'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.match(r.stdout, /Docker MCP Toolkit is used here now/); assert.match(r.stdout, /set it up by hand: https:\/\/docs\.docker\.com\//, 'it comes with Docker Desktop: the manual page is the way in'); assert.deepEqual(toolboxJSON(p).shipped, { 'docker-mcp': 'use' }); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('EP-plannotator-review-S01 Plannotator: a recommended tool, found by its program, plugin or Inbox server, added like any other', () => { const t = TOOLBOX.find((x) => x.id === 'plannotator'); assert.equal(t.tier, 'recommended'); assert.deepEqual([toolProblems(t), vettingProblems(t)], [[], []]); // Exactly the contract's toolbox row (EP-plannotator-review contract.md, Data model). assert.deepEqual(t.detect, { bins: ['plannotator'], plugins: ['plannotator'], mcp: ['plannotator-inbox'] }); assert.deepEqual([t.licence, t.vetted.release, t.records, t.usedBy], ['Apache-2.0 OR MIT', 'v0.29.3', null, []]); assert.ok(t.install.some((r) => r.type === 'script' && r.command.includes('--version v0.29.3') && r.command.includes('--verify-attestation')), 'the script is pinned and signature-checked'); assert.match(t.note, /PLANNOTATOR_SHARE=disabled/); // Each signal alone finds it: the program, the plugin (by its id or id@marketplace), the Inbox server in any case. const none = () => false; assert.equal(toolStatus(t, [], { has: (b) => b === 'plannotator' }).state, 'installed'); for (const name of ['plannotator', 'plannotator@plannotator']) { assert.equal(toolStatus(t, [{ kind: 'plugin', name, enabled: true, agents: ['Claude Code'], where: 'Claude Code plugins' }], { has: none }).state, 'installed', name); } assert.equal(toolStatus(t, [{ kind: 'mcp', name: 'Plannotator-Inbox', where: '.mcp.json' }], { has: none }).state, 'installed'); // A plugin the settings turn off is not loaded. assert.equal(toolStatus(t, [{ kind: 'plugin', name: 'plannotator@plannotator', enabled: false, agents: ['Claude Code'], where: 'Claude Code plugins' }], { has: none }).state, 'disabled'); assert.equal(toolStatus(t, [], { has: none }).state, 'missing'); const { T, p, home } = product({ '.mcp.json': JSON.stringify({ mcpServers: { 'plannotator-inbox': { command: 'plannotator', args: ['inbox', 'mcp'] } } }) }); try { let r = yad(['toolbox', '--json'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.equal(JSON.parse(r.stdout).tools.find((x) => x.id === 'plannotator').status.state, 'installed'); const human = yad(['toolbox', 'list'], { cwd: p, home }).stdout; const recommended = human.slice(human.indexOf('Recommended'), human.indexOf('Connectors')); assert.match(recommended, /Plannotator/, 'listed under Recommended'); r = yad(['toolbox', 'add', 'plannotator'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.match(r.stdout, /Plannotator is used here now/); assert.deepEqual(toolboxJSON(p).shipped, { plannotator: 'use' }); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('#321 Unity MCP: a recommended tool used by yad-implement, found by its UnityMCP server in any case, set up by the person', () => { const t = TOOLBOX.find((x) => x.id === 'unity-mcp'); assert.equal(t.tier, 'recommended'); assert.deepEqual([toolProblems(t), vettingProblems(t)], [[], []]); assert.deepEqual(t.install, [], 'it is set up inside the Unity Editor'); assert.deepEqual(t.usedBy, ['yad-implement']); // Claude Code names it UnityMCP, other clients unityMCP. for (const name of ['UnityMCP', 'unityMCP']) { const { T, p, home } = product({ '.mcp.json': JSON.stringify({ mcpServers: { [name]: { type: 'http', url: 'http://localhost:8080/mcp' } } }) }); try { const r = yad(['toolbox', '--json'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.equal(JSON.parse(r.stdout).tools.find((x) => x.id === 'unity-mcp').status.state, 'installed', name); if (name === 'UnityMCP') { const human = yad(['toolbox', 'list'], { cwd: p, home }).stdout; assert.match(human.slice(human.indexOf('Recommended'), human.indexOf('Connectors')), /Unity MCP/, 'listed under Recommended'); const added = yad(['toolbox', 'add', 'unity-mcp'], { cwd: p, home }); assert.equal(added.status, 0, added.stdout + added.stderr); assert.match(added.stdout, /set it up by hand: https:\/\/github\.com\/CoplayDev\/unity-mcp#quickstart/); assert.deepEqual(toolboxJSON(p).shipped, { 'unity-mcp': 'use' }); } } finally { fs.rmSync(T, { recursive: true, force: true }); } } // Not found: connect hands the person the steps, with the package pinned to the vetted tag. const { T, p, home } = product(); try { const j = JSON.parse(yad(['toolbox', 'connect', 'unity-mcp', '--json'], { cwd: p, home }).stdout); assert.ok(j.steps.length === 2 && j.steps.every((x) => x.who === 'person'), JSON.stringify(j.steps)); assert.match(j.steps[0].run, /package from git URL, and enter https:\/\/github\.com\/CoplayDev\/unity-mcp\.git\?path=\/MCPForUnity#v10\.3\.0$/); assert.ok(j.steps[0].run.endsWith(`#${t.vetted.release}`), 'the pin is the vetted release'); assert.match(j.steps[1].run, /Toggle MCP Window; under Per-client setup, with Claude Code chosen, set Client Project Dir to the folder your agent starts in .*; press Configure All Detected Clients, and restart your agent$/); assert.equal(j.verify, 'yad toolbox connect unity-mcp --verify --json'); } finally { fs.rmSync(T, { recursive: true, force: true }); } // Where Unity really writes it for Claude Code: ~/.claude.json, for the Unity project folder only (local // scope). Found from that folder, not from another (the Product): the reason the skill runs yad from there. const L = fs.mkdtempSync(path.join(os.tmpdir(), 'yad-unity-')); try { const home = path.join(L, 'home'), unity = path.join(L, 'game'), other = path.join(L, 'product'); for (const d of [home, path.join(unity, 'Assets'), path.join(unity, 'ProjectSettings'), other]) fs.mkdirSync(d, { recursive: true }); fs.writeFileSync(path.join(home, '.claude.json'), JSON.stringify({ projects: { [fs.realpathSync(unity)]: { mcpServers: { UnityMCP: { type: 'http', url: 'http://localhost:8080/mcp' } } } } })); const state = (cwd) => JSON.parse(yad(['toolbox', '--json'], { cwd, home }).stdout).tools.find((x) => x.id === 'unity-mcp').status.state; assert.equal(state(unity), 'installed', 'from the Unity repo'); assert.equal(state(other), 'missing', 'not from another folder'); } finally { fs.rmSync(L, { recursive: true, force: true }); } }); test('E175 AI Game Developer: the default Unity tool for yad-implement, found by its own server name only; connect installs it and writes a local server', () => { const t = TOOLBOX.find((x) => x.id === 'ai-game-developer'); assert.equal(t.tier, 'recommended'); assert.deepEqual([toolProblems(t), vettingProblems(t)], [[], []]); assert.equal(t.licence, 'Apache-2.0'); assert.deepEqual(t.install, [], 'it is set up in the Unity project and its Editor'); assert.deepEqual(t.usedBy, ['yad-implement']); assert.equal(t.fallback, TOOLBOX.find((x) => x.id === 'unity-mcp').fallback, 'one fallback, quoted once by yad-implement'); // Each Unity tool is found by its own server name, whatever its case, and never by the other's. const states = (name) => { const { T, p, home } = product({ '.mcp.json': JSON.stringify({ mcpServers: { [name]: { command: 'gamedev-mcp-server' } } }) }); try { const r = yad(['toolbox', '--json'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); const tools = JSON.parse(r.stdout).tools; return ['ai-game-developer', 'unity-mcp'].map((id) => tools.find((x) => x.id === id).status.state); } finally { fs.rmSync(T, { recursive: true, force: true }); } }; assert.deepEqual(states('ai-game-developer'), ['installed', 'missing']); assert.deepEqual(states('AI-Game-Developer'), ['installed', 'missing']); assert.deepEqual(states('UnityMCP'), ['missing', 'installed']); // Not found: the agent adds the plugin and writes a local stdio server, both pinned to the vetted release, // in this project folder; the person sets Custom mode in the Editor, then restarts the agent. const { T, p, home } = product(); try { const j = JSON.parse(yad(['toolbox', 'connect', 'ai-game-developer', '--json'], { cwd: p, home }).stdout); const r = t.vetted.release; assert.deepEqual(j.steps.map((x) => [x.who, x.scope ?? null]), [['agent', 'project'], ['agent', 'project'], ['person', null], ['person', null]], JSON.stringify(j.steps)); assert.equal(j.steps[0].run, `npx unity-mcp-cli@${r} install-plugin . --plugin-version ${r}`, 'the CLI and the plugin, both at the vetted release'); assert.equal(j.steps[1].run, `npx unity-mcp-cli@${r} setup-mcp claude-code . --transport stdio`, 'a local stdio server'); for (const s of j.steps.slice(0, 2)) assert.doesNotMatch(s.run, /--oauth|--token|--url|ai-game\.dev|--regenerate-key/, 'never a cloud endpoint or a key'); assert.match(j.steps[2].run, /set the connection mode to Custom, not Cloud, and the transport to stdio$/, 'stdio, or the Editor\'s own server blocks the agent\'s'); assert.match(j.steps[2].why, /Cloud sends your Editor data to ai-game\.dev/); assert.equal(j.steps[3].run, 'restart your agent, and approve the ai-game-developer server when it asks'); assert.match(j.ask, /^Connect Unity MCP \(AI Game Developer\)\? I will run `npx unity-mcp-cli@1\.11\.1 install-plugin \. --plugin-version 1\.11\.1`, then `npx unity-mcp-cli@1\.11\.1 setup-mcp claude-code \. --transport stdio` \(in this project folder: it changes the project's files and this folder's agent settings\); then you /); assert.equal(j.verify, 'yad toolbox connect ai-game-developer --verify --json'); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E175: yad-implement uses one Unity tool — AI Game Developer by default — and helps install it when none is there', () => { const skill = fs.readFileSync(path.join(ROOT, 'skills/yad-implement/SKILL.md'), 'utf8').replace(/\s+/g, ' '); for (const words of ['yad toolbox connect ai-game-developer --json', 'connection mode to Custom (local)', '`rql-schema`', '`rql-query`', '`tests-run`', '`com.ivanmurzak.unity.mcp`', 'confirm the AI Game Dev window shows connection mode **Custom**', '`AI Game Developer: Custom mode and stdio confirmed by `', 'transport **stdio**', 'Work with that one tool for the whole task', 'Ask the person once whether to install AI Game Developer', 'then run its `verify` and check your session sees the server', '`npx unity-mcp-cli@1.11.1 compile . --format json`', 'With no Editor open it starts a hidden (batch) Unity of its own, so never run it then', "Read the answer's `errors[0].code`, never its message", '`COMPILATION_FAILED` — fix every error in `data.errors`', '`NOT_AUTHENTICATED` — the project is in Cloud mode', '`BUSY` — run it once more', '`.mcp.json`, which holds this machine\'s path to the server', 'run its agent steps from the folder you edit']) { assert.ok(skill.includes(words), words); } // The order: AI Game Developer first (also when both are installed), then MCP for Unity, then one connect — // AI Game Developer's, unless the team chose MCP for Unity. const pick = skill.slice(skill.indexOf('- **Use one Unity tool.**'), skill.indexOf('- **With AI Game Developer.**')); const at = (w) => { const i = pick.indexOf(w); assert.notEqual(i, -1, w); return i; }; assert.ok(at('`ai-game-developer` when its `status.state` is `installed` (also when both are)') < at('else `unity-mcp` when its `status.state` is `installed`'), 'AI Game Developer is the default'); assert.ok(at('else `unity-mcp` when its `status.state` is `installed`') < at('else offer one connect'), 'a connect only when neither is installed'); assert.ok(at('run `yad toolbox connect ai-game-developer --json`') < at('`yad toolbox connect unity-mcp --json` when that entry is `used: true` and `ai-game-developer`\'s is not'), 'AI Game Developer is offered, unless the team chose the other'); assert.ok(!skill.includes('progress bar'), 'the compile is checked by the CLI, not by eye'); // The tools that run code or change files are named only on the "never" line. const never = skill.match(/Never `rql-mutate`[^:]*:/); assert.ok(never, 'a never line for AI Game Developer'); for (const tool of ['`rql-mutate`', '`script-execute`', '`script-update-or-create`', '`script-delete`', '`package-add`', '`package-remove`', '`assetstore-add`', '`tool-set-visibility`', '`tool-set-enabled-state`', '`screenshot-*`']) { assert.ok(never[0].includes(tool), tool); assert.equal(skill.split(tool).length - 1, 1, `${tool} appears once`); } }); test('#321: yad-implement says when a repo is a Unity repo, how it reaches Unity MCP, and quotes its fallback word for word', () => { const t = TOOLBOX.find((x) => x.id === 'unity-mcp'); const skill = fs.readFileSync(path.join(ROOT, 'skills/yad-implement/SKILL.md'), 'utf8'); assert.ok(skill.includes(`\`${t.fallback}\``), 'the fallback, quoted exactly: change one, change both'); for (const words of ['`ProjectSettings/ProjectVersion.txt` and an `Assets/` folder', 'Run the yad commands from inside the folder you edit', '`unity-mcp`', 'yad toolbox connect unity-mcp --json', 'Client Project Dir', '`read_console`', '`get_test_job`', '`find_gameobjects` and `find_in_file`', '`compile: "request"`', 'Never `execute_code`, `execute_menu_item`, `manage_packages`, `manage_build`', "a declared file's own `.meta`, and the `.meta` of a folder made for it, go in the commit with it", '`yad commit` counts a `.meta` only when its own file or folder is not staged', 'the agent guard does not see MCP calls']) { assert.ok(skill.replace(/\s+/g, ' ').includes(words), words); } }); test('E86: `yad toolbox add / remove` write only the difference from the default, and install nothing', () => { const { T, p, home } = product({ '.sdlc/design.json': '{"tool":"figma"}' }); const file = path.join(p, '.sdlc/toolbox.json'); try { // A shipped tool that is not in use: `use` is written, and the install commands are printed. let r = yad(['toolbox', 'add', 'bmad-method'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.match(r.stdout, /BMAD-METHOD is used here now/); assert.match(r.stdout, /to install it: npm: npx bmad-method install {3}or {3}plugin:/); assert.deepEqual(toolboxJSON(p), { schemaVersion: 10, shipped: { 'bmad-method': 'use' } }); // Already in use: nothing written — not even the same bytes again. const before = snapshot(T); for (const id of ['bmad-method', 'spec-kit', 'figma']) { r = yad(['toolbox', 'add', id, '--json'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); const out = JSON.parse(r.stdout); assert.deepEqual([out.command, out.changed, out.used], ['toolbox add', false, true], id); assert.match(r.stderr, /is already used here — nothing to change/); } assert.deepEqual(snapshot(T), before); // A core tool and a connected one are skipped by writing `skip`; adding them back deletes the line. r = yad(['toolbox', 'remove', 'spec-kit'], { cwd: p, home }); assert.match(r.stdout, /Spec Kit is not used here now\. Without it: yad-spec writes the same spec files by hand/); r = yad(['toolbox', 'remove', 'figma'], { cwd: p, home }); assert.match(r.stdout, /\.sdlc\/design\.json still connects it — `yad-connect-design` changes the connection/); assert.deepEqual(toolboxJSON(p).shipped, { 'bmad-method': 'use', 'spec-kit': 'skip', figma: 'skip' }); yad(['toolbox', 'add', 'spec-kit'], { cwd: p, home }); yad(['toolbox', 'add', 'figma'], { cwd: p, home }); yad(['toolbox', 'remove', 'bmad-method'], { cwd: p, home }); // The last choice gone: the file stays, holding its stamp, and keeps a key this release does not know. const doc = toolboxJSON(p); assert.deepEqual(doc, { schemaVersion: 10 }); fs.writeFileSync(file, JSON.stringify({ ...doc, later: { kept: true } })); r = yad(['toolbox', 'remove', 'ecc'], { cwd: p, home }); assert.match(r.stdout, /ECC .* is already not used here — nothing to change/); yad(['toolbox', 'add', 'ecc'], { cwd: p, home }); assert.deepEqual(toolboxJSON(p), { schemaVersion: 10, later: { kept: true }, shipped: { ecc: 'use' } }); // A tool of the team's own. r = yad(['toolbox', 'add', 'doclint', '--custom', '--role', 'lints the docs', '--fallback', 'the docs are not linted', '--detect', 'bin:doclint-e86,mcp:doclint', '--install', 'npm: npm install -g doclint', '--source', 'https://example.com/doclint'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.deepEqual(toolboxJSON(p).custom, [{ id: 'doclint', role: 'lints the docs', fallback: 'the docs are not linted', detect: { bins: ['doclint-e86'], mcp: ['doclint'] }, install: [{ type: 'npm', command: 'npm install -g doclint' }], source: 'https://example.com/doclint' }]); r = yad(['toolbox', 'add', 'doclint'], { cwd: p, home }); assert.match(r.stdout, /already one of this project's tools — nothing to change/); r = yad(['toolbox', 'remove', 'doclint'], { cwd: p, home }); assert.match(r.stdout, /doclint removed/); assert.equal(toolboxJSON(p).custom, undefined); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86: `yad toolbox add / remove` refuse — and never write over a file they cannot read', () => { const { T, p, home } = product(); try { const refuses = (args, re, cwd = p) => { const r = yad(['toolbox', ...args], { cwd, home }); assert.equal(r.status, 1, `${args.join(' ')}\n${r.stdout}${r.stderr}`); assert.match(r.stdout, re, args.join(' ')); }; const before = snapshot(T); refuses(['add'], /needs a tool id/); refuses(['remove'], /needs a tool id/); refuses(['add', 'a', 'b'], /takes one tool id/); refuses(['add', 'Not_An_Id'], /is not a tool id/); refuses(['add', '__proto__'], /is not a tool id/); refuses(['add', 'nope'], /nope is not in the toolbox/); refuses(['remove', 'nope'], /nope is not in the toolbox/); refuses(['add', 'ecc', '--role', 'x'], /--role describes a tool of your own, and goes with --custom/); refuses(['add', 'spec-kit', '--custom', '--role', 'r', '--fallback', 'f', '--detect', 'bin:x'], /spec-kit is a shipped tool/); refuses(['add', 'x', '--custom', '--role', 'r', '--fallback', 'f'], /needs --detect/); refuses(['add', 'x', '--custom', '--role', 'r', '--fallback', 'f', '--detect', 'exe:x'], /not :/); refuses(['add', 'x', '--custom', '--role', 'r', '--detect', 'bin:x'], /cannot add x: fallback says/); refuses(['add', 'x', '--custom', '--role', 'r', '--fallback', 'f', '--detect', 'bin:x', '--install', 'brew install x'], /--install is ": "/); refuses(['add', 'x', '--custom', '--role', 'r', '--fallback', 'f', '--detect', 'bin:x', '--source', 'http://x'], /source, when set, is an https URL/); // Not a Product: nothing is written into the folder it ran in. const elsewhere = path.join(T, 'elsewhere'); fs.mkdirSync(elsewhere); refuses(['add', 'ecc'], /no Product here .* writes the Product's \.sdlc\/toolbox\.json/, elsewhere); assert.deepEqual(snapshot(T).filter((l) => !l.startsWith('elsewhere')), before); assert.deepEqual(fs.readdirSync(elsewhere), []); // A file that does not parse is refused, byte for byte unchanged. const file = path.join(p, '.sdlc/toolbox.json'); fs.writeFileSync(file, '{"shipped":{"ecc":"use"},'); refuses(['add', 'bmad-method'], /does not parse \[YAD-STATE-001\]/); refuses(['remove', 'ecc'], /does not parse/); assert.equal(fs.readFileSync(file, 'utf8'), '{"shipped":{"ecc":"use"},'); fs.writeFileSync(file, '[]'); refuses(['add', 'bmad-method'], /has the wrong shape \[YAD-STATE-002\]/); assert.equal(fs.readFileSync(file, 'utf8'), '[]'); // Settings under two names that disagree: every writer refuses (E122); the list still answers. fs.rmSync(file); put(path.join(p, '.sdlc/hub.json'), '{"schemaVersion":10,"platform":"github"}\n'); const drift = yad(['toolbox', 'add', 'ecc'], { cwd: p, home }); assert.equal(drift.status, 1); assert.match(drift.stdout + drift.stderr, /YAD-STATE-008/); assert.ok(!fs.existsSync(file)); assert.equal(yad(['toolbox', 'list'], { cwd: p, home }).status, 0); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86: from inside a code repo — the Product\'s file is written, and the repo\'s own skills are found', () => { const { T, p, home } = product({ '.sdlc/repos.json': JSON.stringify({ schemaVersion: 10, repos: [{ name: 'api', path: 'api' }] }) }); const repo = path.join(p, 'api'); try { fs.mkdirSync(path.join(repo, '.git'), { recursive: true }); // A skill only this code repo has. skill(path.join(repo, '.claude/skills'), 'impeccable', 'name: impeccable\nversion: 3.7.1\n'); let r = yad(['toolbox', 'add', 'ecc'], { cwd: repo, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.match(r.stderr, /Product: \.\./); assert.deepEqual(toolboxJSON(p).shipped, { ecc: 'use' }); assert.ok(!fs.existsSync(path.join(repo, '.sdlc')), 'nothing written into the code repo'); r = yad(['toolbox', 'list', '--json'], { cwd: repo, home }); assert.equal(r.status, 0, r.stderr); const byId = Object.fromEntries(JSON.parse(r.stdout).tools.map((t) => [t.id, t])); assert.deepEqual([byId.impeccable.status.state, byId.impeccable.used], ['installed', true], 'found in the code repo'); assert.deepEqual([byId.ecc.used, byId.ecc.because], [true, 'added'], 'the choice read from the Product'); // From the Product's own folder the code repo's skill is not there. r = yad(['toolbox', 'list', '--json'], { cwd: p, home }); assert.equal(JSON.parse(r.stdout).tools.find((t) => t.id === 'impeccable').status.state, 'missing'); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86: `yad toolbox check` names what the project uses and is not here — and exits 0', () => { const { T, p, home } = product({ '.sdlc/design.json': '{"tool":"figma"}', '.sdlc/toolbox.json': JSON.stringify({ shipped: { 'bmad-method': 'use', 'spec-kit': 'skip' }, custom: [CUSTOM] }), }); try { const before = snapshot(T); const r = yad(['toolbox', 'check', '--json'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.deepEqual(snapshot(T), before, 'check writes nothing'); const out = JSON.parse(r.stdout); assert.equal(out.command, 'toolbox check'); assert.equal(out.ok, true); assert.ok(out.used.includes('figma') && out.used.includes('bmad-method') && out.used.includes('doclint')); assert.ok(!out.used.includes('spec-kit') && !out.used.includes('ecc')); const f = Object.fromEntries(out.findings.map((x) => [x.id, x])); assert.equal(f.figma.problem, 'missing'); assert.equal(f['bmad-method'].install[0].command, 'npx bmad-method install'); assert.equal(f.doclint.fallback, 'the docs are not linted'); assert.equal(f['spec-kit'], undefined, 'a removed tool is not reported'); const human = yad(['toolbox', 'check'], { cwd: p, home }); assert.equal(human.status, 0); assert.match(human.stdout, /are not ready here\. None is required\./); assert.match(human.stdout, /– Figma: not found\n\s+plugin: claude plugin install figma@claude-plugins-official\n\s+without it: markdown-only/); assert.match(human.stdout, /– doclint: not found\n\s+without it: the docs are not linted/); // The same answer as a function, for E85: a turned-off plugin and an out-of-range version are named too. const tools = [{ ...TOOLBOX.find((t) => t.id === 'impeccable'), versions: '>=4.0.0' }, TOOLBOX.find((t) => t.id === 'repomix')]; const items = [ { kind: 'skill', name: 'impeccable', where: 'x', agents: ['Claude Code'], version: '3.7.1', plugin: null }, { kind: 'plugin', name: 'repomix-mcp@repomix', where: 'y', agents: ['Claude Code'], version: null, plugin: null, enabled: false }, ]; const res = toolboxCheck(p, null, { tools, items, has: () => false }); assert.deepEqual(res.findings.map((x) => [x.id, x.problem]), [['impeccable', 'out-of-range'], ['repomix', 'disabled']]); // E165 PR 2: the agent's command — for a shipped tool that is missing; not for one out of range (connect // would find it here, and --verify reads no version), a plugin turned off (the person turns it on), nor a // team's own tool (yad has no recipe for it). assert.deepEqual(res.findings.map((x) => [x.id, x.connect]), [['impeccable', null], ['repomix', null]]); assert.equal(f.figma.connect, 'yad toolbox connect figma --json'); assert.equal(f['bmad-method'].connect, 'yad toolbox connect bmad-method --json', 'a recipe of person steps is still offered: the command hands them over'); assert.equal(f.doclint.connect, null, 'a custom tool has no recipe'); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86: doctor reports a toolbox.json that does nothing, never a missing tool, and rewrites nothing', async () => { const { toolboxFileChecks } = await import('./doctor.mjs'); const run = (text) => { const { T, p } = product(text === null ? {} : { '.sdlc/toolbox.json': text }); try { const checks = []; toolboxFileChecks(checks, p); if (text !== null) assert.equal(fs.readFileSync(path.join(p, '.sdlc/toolbox.json'), 'utf8'), text); return checks.map((c) => [c.status, c.id, c.message]); } finally { fs.rmSync(T, { recursive: true, force: true }); } }; assert.deepEqual(run(null), []); const [[s1, id1, m1]] = run('{oops'); assert.deepEqual([s1, id1], ['fail', 'toolbox']); assert.match(m1, /does not parse \[YAD-STATE-001\]/); const [[s2, , m2]] = run(JSON.stringify({ shipped: { nope: 'use', ecc: 'yes' } })); assert.equal(s2, 'warn'); assert.match(m2, /2 line\(s\) do nothing — `nope` is not a tool .*`ecc` should be "use" or "skip".*\[YAD-CFG-007\]/); const [[s3, , m3]] = run(JSON.stringify({ shipped: { 'bmad-method': 'use' }, custom: [CUSTOM] })); assert.equal(s3, 'ok'); assert.match(m3, /1 shipped tool choice\(s\), 1 tool\(s\) of this project's own/); }); // ---------- E86 review 1 ---------- test('E86 review 1: removing a line that did nothing is said as that, not as "nothing to change"', () => { const { T, p, home } = product({ '.sdlc/toolbox.json': JSON.stringify({ shipped: { repomix: 'use', figma: 'bogus', ecc: 'yes' } }) }); try { // repomix is core: its `use` repeats the default. let r = yad(['toolbox', 'add', 'repomix', '--json'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.deepEqual([JSON.parse(r.stdout).changed, JSON.parse(r.stdout).used], [true, true]); assert.match(r.stderr, /Repomix is already used here — removed a line in \.sdlc\/toolbox\.json that did nothing/); assert.doesNotMatch(r.stderr, /undo with/, 'the "opposite" command would switch Repomix off, not undo'); assert.doesNotMatch(r.stderr, /nothing to change/); r = yad(['toolbox', 'remove', 'figma'], { cwd: p, home }); assert.match(r.stdout, /Figma is already not used here — removed a line in \.sdlc\/toolbox\.json that did nothing/); assert.doesNotMatch(r.stdout, /undo with/); // A bad value on a tool that is not used by default: `add` now really uses it. r = yad(['toolbox', 'add', 'ecc'], { cwd: p, home }); assert.match(r.stdout, /ECC .* is used here now/); assert.deepEqual(toolboxJSON(p).shipped, { ecc: 'use' }); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86 review 1: an entry the list ignores is never answered as in use, and remove clears every kind of dead line', () => { const { T, p, home } = product({ '.sdlc/toolbox.json': JSON.stringify({ shipped: { 'future-tool': 'use', ecc: 'use' }, custom: [{ id: 'half' }, { id: 'Doc Lint', role: 'r', fallback: 'f', detect: { bins: ['x'] } }, CUSTOM, CUSTOM] }), }); try { let r = yad(['toolbox', 'add', 'half', '--json'], { cwd: p, home }); assert.equal(r.status, 1); const out = JSON.parse(r.stdout); assert.deepEqual([out.ok, out.command], [false, 'toolbox add']); assert.match(out.error, /half is in \.sdlc\/toolbox\.json but ignored: role says/); for (const id of ['half', 'Doc Lint', 'future-tool']) { r = yad(['toolbox', 'remove', id], { cwd: p, home }); assert.equal(r.status, 0, `${id}\n${r.stdout}${r.stderr}`); } r = yad(['toolbox', 'remove', 'doclint'], { cwd: p, home }); assert.match(r.stdout, /doclint removed — .*listed 2 times; every copy is gone/); assert.deepEqual(toolboxJSON(p), { schemaVersion: 10, shipped: { ecc: 'use' } }); r = yad(['toolbox', 'remove', 'Doc Lint'], { cwd: p, home }); assert.match(r.stdout, /is not a tool id/, 'an id the file no longer holds is judged as an id again'); r = yad(['toolbox', 'remove', 'ecc', '--role', 'x'], { cwd: p, home }); assert.equal(r.status, 1); assert.match(r.stdout, /remove takes only the tool id \(got --role\)/); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86 review 1: a custom program is a name, never a path; a detect kind is one of the five', () => { for (const bin of ['../x', 'a/b', 'a\\b', '..', '.']) assert.match(customProblems({ ...CUSTOM, detect: { bins: [bin] } }).join(), /names programs, not paths/, bin); assert.match(parseDetect('constructor:x').error, /not :/); assert.match(parseDetect('toString:x').error, /not :/); }); test('E86 review 1: refusals answer in JSON; --dir names the Product itself for a writer, any folder for a reader', () => { const { T, p, home } = product({ '.sdlc/repos.json': JSON.stringify({ schemaVersion: 10, repos: [{ name: 'api', path: 'api' }] }) }); const repo = path.join(p, 'api'); try { fs.mkdirSync(path.join(repo, '.git'), { recursive: true }); fs.mkdirSync(path.join(p, 'specs')); const before = snapshot(T); for (const dir of [repo, path.join(p, 'specs'), path.join(p, 'typo')]) { const r = yad(['toolbox', 'add', 'ecc', '--json', '--dir', dir], { cwd: T, home }); assert.equal(r.status, 1, dir); const out = JSON.parse(r.stdout); assert.deepEqual([out.ok, out.command], [false, 'toolbox add']); assert.match(out.error, /no Product here/); assert.match(out.hint, /name the Product folder itself \(the one holding \.sdlc\/product\.json\): --dir \S*p$/, 'the refusal names the Product it found'); } assert.deepEqual(snapshot(T), before, 'nothing written'); let r = yad(['toolbox', 'add', 'ecc', '--json', '--dir', p], { cwd: T, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.deepEqual([JSON.parse(r.stdout).product, JSON.parse(r.stdout).file], ['p', '.sdlc/toolbox.json']); // A reader pointed at the code repo reads the Product it belongs to. r = yad(['toolbox', 'list', '--json', '--dir', repo], { cwd: T, home }); const list = JSON.parse(r.stdout); assert.equal(list.product, 'p'); assert.equal(list.tools.find((t) => t.id === 'ecc').because, 'added'); // Drift refused under --json too. put(path.join(p, '.sdlc/hub.json'), '{"schemaVersion":10,"platform":"github"}\n'); r = yad(['toolbox', 'remove', 'ecc', '--json'], { cwd: p, home }); assert.equal(r.status, 1); assert.equal(JSON.parse(r.stdout).code, 'YAD-STATE-008'); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86 review 1: through a workspace — a repo beside the Product writes it; the workspace folder itself is told where it is', () => { const T = tmp(); const ws = path.join(T, 'ws'); const p = path.join(ws, 'product'); const repo = path.join(ws, 'api'); const home = path.join(T, 'h'); try { fs.mkdirSync(home, { recursive: true }); put(path.join(p, '.sdlc/product.json'), '{"schemaVersion":10,"platform":null}\n'); put(path.join(p, '.sdlc/repos.json'), JSON.stringify({ schemaVersion: 10, repos: [{ name: 'api', path: '../api' }] })); put(path.join(ws, '.yad-workspace.json'), JSON.stringify({ version: 1, product: 'product' })); fs.mkdirSync(path.join(repo, '.git'), { recursive: true }); let r = yad(['toolbox', 'add', 'ecc'], { cwd: repo, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.deepEqual(toolboxJSON(p).shipped, { ecc: 'use' }); r = yad(['toolbox', 'list'], { cwd: ws, home }); assert.equal(r.status, 0); assert.match(r.stdout, /not in a repo the Product registers — the Product is product/); r = yad(['toolbox', 'add', 'bmad-method'], { cwd: ws, home }); assert.equal(r.status, 1); assert.match(r.stdout, /the Product is product: cd there/); // A broken workspace file is named, not silently skipped. put(path.join(ws, '.yad-workspace.json'), '{"version":9,"product":"product"}'); r = yad(['toolbox', 'check'], { cwd: repo, home }); assert.equal(r.status, 0); assert.match(r.stdout, /is version 9, .* — showing the defaults/); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); // ---------- E86 review 2 ---------- test('E86 review 2: one remove clears everything under an id, and its answer agrees with the list', () => { const dead = { id: 'ecc', role: 'r', fallback: 'f', detect: { bins: ['x'] } }; const { T, p, home } = product({ '.sdlc/toolbox.json': JSON.stringify({ shipped: { ecc: 'use', doclint: 'use' }, custom: [dead, CUSTOM] }) }); try { // A dead custom entry under a shipped id, and the shipped `use` line: both go, and the tool is unused. let r = yad(['toolbox', 'remove', 'ecc', '--json'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.deepEqual([JSON.parse(r.stdout).used, JSON.parse(r.stdout).changed], [false, true]); assert.match(r.stderr, /also removed 1 custom entry under the id ecc, which was ignored/); const listed = (id) => JSON.parse(yad(['toolbox', 'list', '--json'], { cwd: p, home }).stdout).tools.find((t) => t.id === id); assert.equal(listed('ecc').used, false); // A valid custom tool and a dead shipped line under its id: one run, no line left under it. r = yad(['toolbox', 'remove', 'doclint'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.match(r.stdout, /doclint removed/); assert.match(r.stdout, /removed the line for `doclint` under shipped/); assert.deepEqual(toolboxJSON(p), { schemaVersion: 10 }); // A core tool with a dead custom entry under its id: removed AND unused. fs.writeFileSync(path.join(p, '.sdlc/toolbox.json'), JSON.stringify({ custom: [{ ...dead, id: 'spec-kit' }] })); r = yad(['toolbox', 'remove', 'spec-kit', '--json'], { cwd: p, home }); assert.equal(JSON.parse(r.stdout).used, false); assert.equal(listed('spec-kit').used, false); assert.deepEqual(toolboxJSON(p), { schemaVersion: 10, shipped: { 'spec-kit': 'skip' } }); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86 review 2: add judges "in use" exactly as the list does — a broken copy before a good one, or alone', () => { const { T, p, home } = product({ '.sdlc/toolbox.json': JSON.stringify({ custom: [{ id: 'doclint', role: 'r' }, CUSTOM, { id: 'half' }] }) }); try { let r = yad(['toolbox', 'add', 'doclint', '--json'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.deepEqual([JSON.parse(r.stdout).used, JSON.parse(r.stdout).changed], [true, false]); r = yad(['toolbox', 'add', 'doclint', '--custom', '--role', 'r', '--fallback', 'f', '--detect', 'bin:x'], { cwd: p, home }); assert.match(r.stdout, /doclint is already one of this project's tools/); r = yad(['toolbox', 'add', 'half', '--custom', '--role', 'r', '--fallback', 'f', '--detect', 'bin:x'], { cwd: p, home }); assert.equal(r.status, 1); assert.match(r.stdout, /half is in \.sdlc\/toolbox\.json but ignored: role says/); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86 review 2: doctor says an entry with no id is fixed by hand', async () => { const { toolboxFileChecks } = await import('./doctor.mjs'); const { T, p } = product({ '.sdlc/toolbox.json': JSON.stringify({ custom: [{ role: 'r' }] }) }); try { const checks = []; toolboxFileChecks(checks, p); assert.match(checks[0].hint, /\(an entry with no id, or an empty one: fix it by hand\)/); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); // ---------- E86 review 3 ---------- test('E86 review 3: a dead custom entry under a shipped id is one removal, said once, with no false undo', () => { const dead = (id) => ({ id, role: 'r', fallback: 'f', detect: { bins: ['x'] } }); const { T, p, home } = product({ '.sdlc/toolbox.json': JSON.stringify({ shipped: { 'spec-kit': 'skip' }, custom: [dead('ecc'), dead('spec-kit'), dead('repomix')] }) }); try { // Scenario A: ecc is not used; only its dead custom entry goes. let r = yad(['toolbox', 'remove', 'ecc'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); assert.match(r.stdout, /removed 1 custom entry under the id ecc, which was ignored .* — ECC .* is still not used here/); assert.doesNotMatch(r.stdout, /also removed|already not used|undo with/); // Scenario B: spec-kit already skipped. r = yad(['toolbox', 'remove', 'spec-kit'], { cwd: p, home }); assert.match(r.stdout, /removed 1 custom entry under the id spec-kit, .* — Spec Kit is still not used here/); assert.doesNotMatch(r.stdout, /undo with/); // add clears a dead entry too, and says so once. r = yad(['toolbox', 'add', 'repomix'], { cwd: p, home }); assert.match(r.stdout, /removed 1 custom entry under the id repomix, which was ignored .* — Repomix is still used here/); assert.doesNotMatch(r.stdout, /nothing to change|also removed/, 'one write, said once'); assert.doesNotMatch(r.stdout, /undo with/); assert.deepEqual(toolboxJSON(p), { schemaVersion: 10, shipped: { 'spec-kit': 'skip' } }); // A real change still offers its undo. r = yad(['toolbox', 'add', 'spec-kit'], { cwd: p, home }); assert.match(r.stdout, /undo with `yad toolbox remove spec-kit`/); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86 review 3: removing an entry that was ignored says so; an empty id is fixed by hand', async () => { const { T, p, home } = product({ '.sdlc/toolbox.json': JSON.stringify({ shipped: { '': 'use' }, custom: [{ id: 'half' }, { id: '', role: 'r' }] }) }); try { const r = yad(['toolbox', 'remove', 'half'], { cwd: p, home }); assert.match(r.stdout, /removed the entry for half, which was ignored/); assert.doesNotMatch(r.stdout, /one of this project's own tools/); const c = loadChoices(p); assert.equal(c.unreachable, true); const { toolboxFileChecks } = await import('./doctor.mjs'); const checks = []; toolboxFileChecks(checks, p); assert.match(checks[0].hint, /\(an entry with no id, or an empty one: fix it by hand\)/); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); // ---------- E86 review 4 ---------- test('E86 review 4: add says "also removed" when the shipped part changed too', () => { const { T, p, home } = product({ '.sdlc/toolbox.json': JSON.stringify({ custom: [{ id: 'ecc', role: 'r', fallback: 'f', detect: { bins: ['x'] } }] }) }); try { const r = yad(['toolbox', 'add', 'ecc'], { cwd: p, home }); assert.match(r.stdout, /ECC .* is used here now/); assert.match(r.stdout, /also removed 1 custom entry under the id ecc/); assert.match(r.stdout, /undo with `yad toolbox remove ecc`/); assert.deepEqual(toolboxJSON(p), { schemaVersion: 10, shipped: { ecc: 'use' } }); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E86 review 4: each way to be out of remove\'s reach is flagged on its own; a broken entry with an id is not', async () => { const { toolboxFileChecks } = await import('./doctor.mjs'); for (const [doc, flagged] of [ [{ shipped: { '': 'use' } }, true], [{ custom: [{ id: '', role: 'r' }] }, true], [{ custom: [{ role: 'r' }] }, true], [{ custom: ['str'] }, true], [{ custom: [{ id: 'Bad Id', role: 'r' }] }, false], [{ shipped: { 'future-tool': 'use' } }, false], ]) { const { T, p } = product({ '.sdlc/toolbox.json': JSON.stringify(doc) }); try { assert.equal(loadChoices(p).unreachable, flagged, JSON.stringify(doc)); const checks = []; toolboxFileChecks(checks, p); assert.equal(/fix it by hand\)/.test(checks[0].hint), flagged, JSON.stringify(doc)); } finally { fs.rmSync(T, { recursive: true, force: true }); } } }); // ---------- E86 small notes ---------- test('E86: a removed tool\'s fallback reads as "without it", and a copy\'s reason names the id', () => { const { T, p, home } = product({ '.sdlc/toolbox.json': JSON.stringify({ shipped: { ecc: 'use' }, custom: [{ id: 'ecc', role: 'r', fallback: 'f', detect: { bins: ['x'] } }] }) }); try { const r = yad(['toolbox', 'remove', 'ecc'], { cwd: p, home }); assert.match(r.stdout, /ECC .* is not used here now\. Without it: nothing changes: yadflow's own skills run every step/); assert.match(r.stdout, /also removed 1 custom entry under the id ecc, which was ignored \(the id is a shipped tool's\)/); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); // ---------- E85: the toolbox step of setup, check, update and join ---------- const { offerToolbox, toolboxCheckLines } = await import('./toolbox.mjs'); const { stripAnsi } = await import('./lib.mjs'); test('E85: the check lines — nothing in use, everything here, and what is missing with how to get it', () => { const plain = (lines) => lines.map(stripAnsi); assert.match(plain(toolboxCheckLines({ used: [], findings: [] }))[0], /uses no tool from the toolbox — `yad toolbox list` shows them all/); const repomix = TOOLBOX.find((t) => t.id === 'repomix'); assert.deepEqual(plain(toolboxCheckLines({ used: [repomix], findings: [] })), [' ✓ all 1 tool(s) this project uses are here: Repomix']); const lines = plain(toolboxCheckLines({ used: [repomix], findings: [{ id: 'repomix', name: 'Repomix', problem: 'missing', fallback: repomix.fallback }] })); assert.match(lines[0], /1 of the 1 tool\(s\) this project uses is not ready here\. None is required\./); assert.ok(lines.some((l) => l.includes(`npm: ${repomix.install[0].command}`)), 'the install command is printed, not run'); assert.match(lines.at(-1), /without it: /); }); test('E85: the offer never fails the command it is part of — a check that throws is said, and the answer is empty', () => { const { T, p } = product(); try { const res = offerToolbox(p, p, { items: [], has: () => { throw new Error('PATH unreadable'); } }); assert.deepEqual(res, { used: [], findings: [], problems: [], error: 'could not check' }); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E85: `yad setup` offers the tools in use after the tools step — a connector chosen there counts — and writes no toolbox.json', () => { const T = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'yad-e85-'))); const p = path.join(T, 'p'); const home = path.join(T, 'h'); fs.mkdirSync(p, { recursive: true }); fs.mkdirSync(home, { recursive: true }); try { const env = { ...process.env, HOME: home, USERPROFILE: home, NO_COLOR: '1', SDLC_NONINTERACTIVE: '1', YAD_NO_UPDATE_NOTIFIER: '1' }; const run = (args) => spawnSync(process.execPath, [YAD, ...args], { cwd: p, encoding: 'utf8', env }); // --tools with no answers takes each tool step's default: Figma, Playwright, DeepTutor. const r = run(['setup', '--solo', '--greenfield', '--monorepo', '--tools', '--ide-targets', '.claude', '--json']); assert.equal(r.status, 0, r.stdout + r.stderr); const out = JSON.parse(r.stdout); for (const id of ['repomix', 'spec-kit', 'impeccable', 'figma', 'playwright', 'deeptutor']) assert.ok(out.toolbox.used.includes(id), id); assert.ok(out.toolbox.findings.some((f) => f.id === 'playwright' && f.problem === 'missing'), 'an empty home folder has no Playwright'); assert.ok(!fs.existsSync(path.join(p, '.sdlc/toolbox.json')), 'offering writes no choice'); const human = run(['setup', '--solo', '--greenfield', '--monorepo', '--ide-targets', '.claude']); assert.equal(human.status, 0, human.stdout + human.stderr); assert.match(human.stdout, /\[9\/11\] Toolbox \(external tools this project uses\)[\s\S]*– Playwright MCP: not found[\s\S]*nothing is installed without asking[\s\S]*`yad toolbox connect ` \(it asks you once first\)[\s\S]*\[10\/11\] Local setup script[\s\S]*\[11\/11\] Done/); // E165 PR 2: the agent is offered each tool to connect, in the AI-only steps, and reads `connect` in the JSON. assert.match(human.stdout, /AI-only steps[\s\S]*offer to connect Playwright MCP: `yad toolbox connect playwright --json` \(the connect-tool rule/); assert.equal(out.toolbox.findings.find((f) => f.id === 'playwright').connect, 'yad toolbox connect playwright --json'); // `yad check` and `yad update` end with the same section, exit 0 with tools missing, and write no choice. for (const verb of ['check', 'update']) { const j = run([verb, '--json']); assert.equal(j.status, 0, verb + j.stdout + j.stderr); const a = JSON.parse(j.stdout); assert.ok(a.toolbox.used.includes('playwright') && a.toolbox.findings.length > 0, verb); assert.equal(a.toolbox.findings.find((f) => f.id === 'playwright')?.connect, 'yad toolbox connect playwright --json', verb); const h = run([verb]); assert.match(h.stdout, /\nToolbox\n[\s\S]*– Playwright MCP: not found[\s\S]*`yad toolbox connect `/, verb); } assert.ok(!fs.existsSync(path.join(p, '.sdlc/toolbox.json'))); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E85 review 1: `yad check` from a code repo finds that repo\'s tools, as `yad toolbox check` does; the --fix hint comes before the section', () => { const { T, p, home } = product({ '.sdlc/repos.json': JSON.stringify({ schemaVersion: 10, repos: [{ name: 'api', path: 'api' }] }) }); const repo = path.join(p, 'api'); try { fs.mkdirSync(path.join(repo, '.git'), { recursive: true }); skill(path.join(repo, '.claude/skills'), 'impeccable', 'name: impeccable\nversion: 3.7.1\n'); const missing = (r) => JSON.parse(r.stdout).toolbox.findings.map((f) => f.id); for (const verb of ['check', 'update']) { const fromRepo = yad([verb, '--json'], { cwd: repo, home }); assert.equal(fromRepo.status, 0, verb + fromRepo.stdout + fromRepo.stderr); assert.ok(!missing(fromRepo).includes('impeccable'), `${verb}: found in the code repo`); assert.ok(missing(yad([verb, '--json'], { cwd: p, home })).includes('impeccable'), `${verb}: not in the Product's own folder`); } const human = yad(['check'], { cwd: p, home }); assert.match(human.stdout, /yad check --fix[^\n]*\n\nToolbox\n/, 'the --fix hint is above the Toolbox section, not under it'); assert.match(human.stdout, /for the whole team, stop using a tool with `yad toolbox remove `/); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('`yad update --dry-run` previews the update and writes nothing; with --push or --open-pr it refuses', () => { const { T, p, home } = product(); // Each file's path with a hash of its content: a dry run must neither add a file nor change one. const files = () => Object.fromEntries(fs.readdirSync(p, { recursive: true }).sort() .filter((f) => fs.statSync(path.join(p, f)).isFile()).map((f) => [f, sha(path.join(p, f))])); try { const before = files(); const dry = yad(['update', '--dry-run'], { cwd: p, home }); assert.equal(dry.status, 0, dry.stdout + dry.stderr); assert.match(dry.stdout, /new\s+yad-epic/, 'the preview lists what the update would add'); assert.match(dry.stdout, /run `yad update` to apply it/, 'the hint names the command that applies the preview'); assert.doesNotMatch(dry.stdout, /yad check --fix` to reconcile/); assert.deepEqual(files(), before, 'a dry run writes no file'); for (const flag of ['--push', '--open-pr']) { const r = yad(['update', '--dry-run', flag], { cwd: p, home }); assert.notEqual(r.status, 0, flag); assert.match(r.stdout + r.stderr, /--dry-run writes nothing/, flag); } assert.deepEqual(files(), before); const real = yad(['update'], { cwd: p, home }); assert.equal(real.status, 0, real.stdout + real.stderr); assert.ok(Object.keys(files()).length > Object.keys(before).length, 'without --dry-run the update still writes'); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E85 review 1: join\'s offer does not advise removing a tool the team chose', () => { const { T, p } = product(); try { const lines = []; const orig = console.log; console.log = (...a) => lines.push(a.join(' ')); try { offerToolbox(p, p, { canRemove: false, items: [], has: () => false }); offerToolbox(p, p, { items: [], has: () => false }); } finally { console.log = orig; } const hints = lines.filter((l) => l.includes('nothing is installed without asking')); assert.equal(hints.length, 2); assert.ok(!hints[0].includes('yad toolbox remove'), 'join: no remove advice'); assert.match(hints[1], /for the whole team/); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E85 review 2: from a subfolder, tools are looked for at the top of its repo; --dir reads that repo\'s Product', () => { const { T, p, home } = product({ '.sdlc/repos.json': JSON.stringify({ schemaVersion: 10, repos: [{ name: 'api', path: 'api' }] }), '.sdlc/toolbox.json': JSON.stringify({ schemaVersion: 10, shipped: { 'spec-kit': 'skip' } }), }); const repo = path.join(p, 'api'); try { fs.mkdirSync(path.join(repo, '.git'), { recursive: true }); fs.mkdirSync(path.join(repo, 'src'), { recursive: true }); fs.mkdirSync(path.join(p, 'epics', 'sub'), { recursive: true }); skill(path.join(p, '.claude/skills'), 'impeccable', 'name: impeccable\nversion: 3.7.1\n'); skill(path.join(repo, '.claude/skills'), 'impeccable', 'name: impeccable\nversion: 3.7.1\n'); const findings = (r) => { assert.equal(r.status, 0, r.stdout + r.stderr); const o = JSON.parse(r.stdout); return (o.toolbox?.findings ?? o.findings).map((f) => f.id); }; for (const cwd of [path.join(p, 'epics', 'sub'), path.join(repo, 'src')]) { for (const args of [['check', '--json'], ['update', '--json'], ['toolbox', 'check', '--json']]) { assert.ok(!findings(yad(args, { cwd, home })).includes('impeccable'), `${args[0]} from ${path.relative(p, cwd)}: found at the repo's top`); } } // --dir : the team's `skip` is read from that repo's Product, so Spec Kit is not offered. const viaDir = findings(yad(['check', '--json', '--dir', repo], { cwd: T, home })); assert.ok(!viaDir.includes('spec-kit') && !viaDir.includes('impeccable'), JSON.stringify(viaDir)); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E85 review 3: tools are looked for at the deepest of checkout, registered repo and Product that holds the folder', async () => { const { toolsFolder, findProduct } = await import('./find-product.mjs'); const { T, p, home } = product({ '.sdlc/repos.json': JSON.stringify({ schemaVersion: 10, repos: [{ name: 'api', path: 'api' }, { name: 'web', path: 'apps/web' }, { name: 'be', path: '../be' }] }) }); // On disk as `toolsFolder` reads it: `.native` expands a Windows short name (RUNNER~1) that the JS // `realpathSync` keeps. try { const mk = (rel, git) => { const d = path.join(T, rel); fs.mkdirSync(d, { recursive: true }); if (git === 'dir') fs.mkdirSync(path.join(d, '.git')); if (git === 'file') fs.writeFileSync(path.join(d, '.git'), 'gitdir: x\n'); return fs.realpathSync.native(d); }; mk('p', 'dir'); const api = mk('p/api', 'dir'); const wt = mk('p/api/.claude/worktrees/x', 'file'); mk('p/api/.claude/worktrees/x/src'); const web = mk('p/apps/web'); mk('p/apps/web/src'); mk('p/epics/sub'); mk('be', 'dir'); const beWt = mk('be/wt', 'file'); mk('be/wt/src'); fs.writeFileSync(path.join(T, '.yad-workspace.json'), JSON.stringify({ version: 1, product: 'p' })); const lone = mk('lone', 'dir'); mk('lone/src'); const at = (rel) => toolsFolder(findProduct(path.join(T, rel)), path.join(T, rel)); assert.equal(at('p/epics/sub'), fs.realpathSync.native(p), 'a Product subfolder → the Product'); assert.equal(at('p/api'), api, 'a registered repo → itself'); assert.equal(at('p/api/.claude/worktrees/x/src'), wt, 'a worktree inside a registered repo → the worktree, never api'); assert.equal(at('p/apps/web/src'), web, 'a monorepo subfolder registered as a repo → that folder, not the Product'); assert.equal(at('be/wt/src'), beWt, 'a worktree inside a repo found through the workspace file → the worktree'); assert.equal(at('lone/src'), lone, 'no Product → the top of the checkout'); // A folder reached through a link: lifted to the top of the checkout it really is in. try { fs.symlinkSync(path.join(T, 'lone/src'), path.join(T, 'link'), 'dir'); } catch { /* no links here (Windows without rights) */ } if (fs.existsSync(path.join(T, 'link'))) assert.equal(toolsFolder(null, path.join(T, 'link')), lone, 'through a link → the real checkout'); // Through the command: a skill only the worktree has is found there, and not from api's own top. skill(path.join(wt, '.claude/skills'), 'impeccable', 'name: impeccable\nversion: 3.7.1\n'); const ids = (cwd) => JSON.parse(yad(['toolbox', 'check', '--json'], { cwd, home }).stdout).findings.map((f) => f.id); assert.ok(!ids(path.join(wt, 'src')).includes('impeccable')); assert.ok(ids(api).includes('impeccable')); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E164: OpenPencil is a design connector — vetted, pinned exactly, one install route, found by its CLI or its MCP server', () => { const op = TOOLBOX.find((t) => t.id === 'openpencil'); assert.ok(op, 'in the toolbox'); assert.deepEqual([op.tier, op.licence, op.fallback], ['connector', 'MIT', 'markdown-only: yad-ui writes ui-design.md and DESIGN.md only']); assert.deepEqual(op.vetted.packages.map((p) => `${p.name}@${p.version}`), ['@open-pencil/mcp@0.16.0', '@open-pencil/cli@0.16.0']); assert.equal(op.install.length, 1, 'one route: the MCP connection does nothing without the packages'); assert.equal(op.install[0].command, 'npm install -g @open-pencil/mcp@0.16.0 @open-pencil/cli@0.16.0, then claude mcp add --scope user open-pencil -- openpencil-mcp'); assert.match(op.note, /no app open/); assert.match(op.note, /only forwards to the running desktop app/); assert.match(op.note, /the home folder on Windows/); for (const p of op.vetted.packages) assert.ok(op.install[0].command.includes(`${p.name}@${p.version}`), `${p.name}: the install line names the vetted version`); assert.deepEqual(toolProblems(op), [], 'a well-formed entry'); const none = () => false; assert.equal(toolStatus(op, [{ kind: 'mcp', name: 'open-pencil', where: '~/.claude.json', version: null }], { has: none }).state, 'installed'); assert.equal(toolStatus(op, [], { has: (b) => b === 'openpencil' }).state, 'installed'); assert.equal(toolStatus(op, [], { has: none }).state, 'missing'); assert.deepEqual([op.reach.local, op.reach.appBound, op.reach.ownServer], [['openpencil-cli'], ['openpencil-mcp'], undefined], 'E164 PR 2: the CLI is local, the MCP server needs the app'); }); // ---- E165: `yad toolbox connect` — the agent connects a tool after one yes --------------------------- const { RECIPES, recipeProblems } = await import('./toolbox-connect.mjs'); const { RULES } = await import('./agent-rules.mjs'); // A `claude mcp add` step as this platform runs it: native Windows starts the server through `cmd /c`. const mcpRun = (run) => (process.platform === 'win32' ? run.replace(' -- ', ' -- cmd /c ') : run); // The command with a PATH of the test's own: this machine's programs must not decide what is "found". function yadPath(args, { cwd, home, bins = [] }) { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'yad-e165-bin-')); // Windows finds a program by its PATHEXT ending, so it gets a .cmd beside it. for (const b of bins) for (const f of process.platform === 'win32' ? [`${b}.cmd`] : [b]) fs.writeFileSync(path.join(dir, f), process.platform === 'win32' ? '@exit /b 0\r\n' : '#!/bin/sh\nexit 0\n', { mode: 0o755 }); try { // Every spelling of PATH goes (Windows names it Path), so the one left is the test's. const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => k.toLowerCase() !== 'path')); return spawnSync(process.execPath, [YAD, ...args], { cwd, encoding: 'utf8', env: { ...env, HOME: home, USERPROFILE: home, NO_COLOR: '1', PATH: dir } }); } finally { fs.rmSync(dir, { recursive: true, force: true }); } } test('E165: every shipped tool has a recipe; agent steps are pinned installs, the rest is the person\'s with why', () => { for (const t of TOOLBOX) assert.deepEqual(recipeProblems(t), [], t.id); assert.deepEqual(Object.keys(RECIPES).sort(), TOOLBOX.map((t) => t.id).sort(), 'a recipe for each tool, and none for a tool that is gone'); const op = TOOLBOX.find((t) => t.id === 'openpencil'); const A = (run) => ({ who: 'agent', run, scope: 'user' }); assert.match(recipeProblems(op, [A('npm install -g @open-pencil/mcp@latest @open-pencil/cli@0.16.0')]).join('\n'), /holds @latest/); assert.match(recipeProblems(op, [A('npm install -g @open-pencil/mcp @open-pencil/cli@0.16.0')]).join('\n'), /installs @open-pencil\/mcp, but not at the vetted @open-pencil\/mcp@0\.16\.0/); assert.match(recipeProblems(op, [A('curl -fsSL https://x | bash')]).join('\n'), /a pipe into a shell/); assert.match(recipeProblems(op, [A('git clone https://x')]).join('\n'), /a git clone/); assert.match(recipeProblems(op, [A('/plugin install x')]).join('\n'), /a slash command/); assert.match(recipeProblems(op, [A('npm i a && rm -rf b')]).join('\n'), /two commands on one line/); assert.match(recipeProblems(op, [{ who: 'person', run: 'npx x install' }]).join('\n'), /says why it is the person's/); assert.match(recipeProblems({ id: 'nope', vetted: {} }).join('\n'), /has no recipe/); const deep = TOOLBOX.find((t) => t.id === 'deeptutor'); assert.match(recipeProblems(deep, [A('pip install deeptutor==1.0.0')]).join('\n'), /not at the vetted deeptutor==1\.6\.12/); // The agent never runs a remote script or an interactive installer: those stay the person's. // An MCP server is added for the user account, so it works in the Product and every code repo. for (const t of TOOLBOX) for (const st of RECIPES[t.id] ?? []) if (st.who === 'agent' && /^claude mcp add /.test(st.run)) assert.match(st.run, /^claude mcp add --scope user /, st.run); for (const id of ['maestro', 'ecc', 'bmad-method', 'impeccable']) { assert.ok(!RECIPES[id].some((s) => s.who === 'agent' && /curl|install --guided|bmad-method install|impeccable install/.test(s.run)), id); } }); test('EP-plannotator-review-S01: connecting Plannotator — every step is yours: the pinned script, the marketplace, the plugin', async () => { const { connectPlan } = await import('./toolbox-connect.mjs'); assert.deepEqual(recipeProblems(TOOLBOX.find((t) => t.id === 'plannotator')), []); const j = connectPlan('plannotator', { items: [], has: () => false, productRoot: null }); assert.equal(j.state, 'missing'); const commands = [ 'curl -fsSL https://plannotator.ai/install.sh | bash -s -- --version v0.29.3 --verify-attestation --skip-claude-plugin', 'claude plugin marketplace add backnotprop/plannotator', 'claude plugin install plannotator@plannotator', ]; assert.deepEqual(j.steps.map((s) => [s.who, s.run]), [...commands.map((c) => ['person', c]), ['person', 'restart your agent']]); // The agent runs nothing: a remote script, and a plugin from a marketplace you add first, are yours (docs/CLI.md). assert.deepEqual(j.steps.filter((s) => s.who === 'agent'), []); for (const s of j.steps) assert.ok(s.why, `${s.run}: says why it is yours`); // The script's reason names what it changes besides the program. assert.match(j.steps[0].why, /other agents it finds/); assert.match(j.steps[0].why, /needs the gh program/); assert.match(j.steps[2].why, /not pinned/); assert.match(j.ask, /^Plannotator needs steps only you can do\. First, you run `curl -fsSL https:\/\/plannotator\.ai\/install\.sh [^`]+` \(a remote install script, /); assert.equal(j.verify, 'yad toolbox connect plannotator --verify --json'); assert.deepEqual(j.person.commands, commands); // Already on this machine: nothing to install, only the record. assert.deepEqual(connectPlan('plannotator', { items: [], has: (b) => b === 'plannotator' }).steps, []); }); test('E165: `yad toolbox connect --json` reads only — the steps, the question, what will be recorded', () => { const { T, p, home } = product(); try { const before = fs.readdirSync(path.join(p, '.sdlc')).sort(); let r = yadPath(['toolbox', 'connect', 'openpencil', '--json'], { cwd: p, home }); assert.equal(r.status, 0, r.stdout + r.stderr); let j = JSON.parse(r.stdout); assert.equal(j.state, 'missing'); assert.deepEqual(j.steps.map((s) => [s.who, s.run]), [ ['agent', 'npm install -g @open-pencil/mcp@0.16.0 @open-pencil/cli@0.16.0'], ['agent', mcpRun('claude mcp add --scope user open-pencil -- openpencil-mcp')], ]); assert.equal(j.ask, `Connect OpenPencil? I will run \`npm install -g @open-pencil/mcp@0.16.0 @open-pencil/cli@0.16.0\`, then \`${mcpRun('claude mcp add --scope user open-pencil -- openpencil-mcp')}\` (for your user account on this machine); then I will check that it is found and record it as this team's choice in .sdlc/design.json.`); assert.deepEqual([j.record, j.replaces, j.person, j.verify], [['.sdlc/design.json'], null, null, 'yad toolbox connect openpencil --verify --json']); // A person step first is said first, with why, and its command is in the person block. j = JSON.parse(yadPath(['toolbox', 'connect', 'maestro', '--json'], { cwd: p, home }).stdout); assert.match(j.ask, /^Connect Maestro\? First, you run `curl -fsSL "https:\/\/get\.maestro\.mobile\.dev" \| bash` \(a remote install script: [^)]+\); then I will run `claude mcp add --scope user maestro -- (cmd \/c )?maestro mcp`/); assert.deepEqual(j.person.commands, ['curl -fsSL "https://get.maestro.mobile.dev" | bash']); assert.match(j.person.why, /remote install script/); // Found here: nothing to install, only the record. put(path.join(p, '.mcp.json'), JSON.stringify({ mcpServers: { 'open-pencil': { command: 'openpencil-mcp' } } })); j = JSON.parse(yadPath(['toolbox', 'connect', 'openpencil', '--json'], { cwd: p, home }).stdout); assert.deepEqual([j.state, j.steps], ['installed', []]); assert.equal(j.ask, 'OpenPencil is already on this machine. Record it as this team\'s choice in .sdlc/design.json?'); // The team's design tool is another one: the question says so, and so does the verify command. put(path.join(p, '.sdlc/design.json'), JSON.stringify({ tool: 'figma', project_url: 'https://figma.example/f' })); j = JSON.parse(yadPath(['toolbox', 'connect', 'openpencil', '--json'], { cwd: p, home }).stdout); assert.equal(j.replaces, 'figma'); assert.match(j.ask, /[Rr]ecord it as this team's choice in \.sdlc\/design\.json, in place of Figma \(what that file holds for Figma is dropped\)\?$/); assert.equal(j.verify, 'yad toolbox connect openpencil --verify --replace --json'); // A person step's block names the same command, --replace included. put(path.join(p, '.sdlc/design.json'), JSON.stringify({ tool: 'Figma' })); j = JSON.parse(yadPath(['toolbox', 'connect', 'pencil', '--json'], { cwd: p, home }).stdout); assert.deepEqual([j.replaces, j.person.verify], ['Figma', 'yad toolbox connect pencil --verify --replace --json']); put(path.join(p, '.sdlc/design.json'), JSON.stringify({ tool: 'OpenPencil' })); assert.equal(JSON.parse(yadPath(['toolbox', 'connect', 'openpencil', '--json'], { cwd: p, home }).stdout).replaces, null, 'the same tool in other letters is not a replacement'); fs.rmSync(path.join(p, '.sdlc/design.json')); fs.rmSync(path.join(p, '.mcp.json')); assert.deepEqual(fs.readdirSync(path.join(p, '.sdlc')).sort(), before, 'nothing written'); // No Product: the question says nothing will be recorded. const away = fs.mkdtempSync(path.join(os.tmpdir(), 'yad-e165-away-')); try { j = JSON.parse(yadPath(['toolbox', 'connect', 'repomix', '--json'], { cwd: away, home }).stdout); assert.deepEqual(j.record, []); assert.match(j.ask, /There is no Product here, so nothing will be recorded\.$/); } finally { fs.rmSync(away, { recursive: true, force: true }); } r = yadPath(['toolbox', 'connect', 'sketch', '--json'], { cwd: p, home }); assert.equal(r.status, 1); assert.match(JSON.parse(r.stdout).error, /sketch is not in the toolbox/); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E165: `--verify` records only a tool it finds — the connector\'s file, or the team\'s toolbox line — and never writes over a broken file', () => { const { T, p, home } = product(); const design = path.join(p, '.sdlc/design.json'); try { // Not found: refused, a person block, nothing written. let r = yadPath(['toolbox', 'connect', 'openpencil', '--verify', '--json'], { cwd: p, home }); assert.equal(r.status, 1); let j = JSON.parse(r.stdout); assert.match(j.error, /OpenPencil is not found here yet, so nothing was recorded/); assert.deepEqual(j.person.steps, ['npm install -g @open-pencil/mcp@0.16.0 @open-pencil/cli@0.16.0', mcpRun('claude mcp add --scope user open-pencil -- openpencil-mcp')]); assert.ok(!fs.existsSync(design) && !fs.existsSync(path.join(p, '.sdlc/toolbox.json'))); // Found (its CLI on PATH): the connector's own file is written, which makes it used. r = yadPath(['toolbox', 'connect', 'openpencil', '--verify', '--json'], { cwd: p, home, bins: ['openpencil'] }); assert.equal(r.status, 0, r.stdout + r.stderr); j = JSON.parse(r.stdout); assert.deepEqual([j.used, j.written], [true, ['.sdlc/design.json']]); assert.equal(JSON.parse(fs.readFileSync(design, 'utf8')).tool, 'openpencil'); // The same tool already recorded, with the team's own fields: left exactly as it is. fs.writeFileSync(design, JSON.stringify({ tool: 'openpencil', project_url: 'keep-me', source: 'openpencil-cli' })); j = JSON.parse(yadPath(['toolbox', 'connect', 'openpencil', '--verify', '--json'], { cwd: p, home, bins: ['openpencil'] }).stdout); assert.deepEqual(j.written, []); assert.equal(JSON.parse(fs.readFileSync(design, 'utf8')).project_url, 'keep-me'); // A file that does not parse is never written over. fs.writeFileSync(design, '{broken'); r = yadPath(['toolbox', 'connect', 'openpencil', '--verify', '--json'], { cwd: p, home, bins: ['openpencil'] }); assert.equal(r.status, 1); assert.match(JSON.parse(r.stdout).error, /\.sdlc\/design\.json does not parse/); assert.equal(fs.readFileSync(design, 'utf8'), '{broken'); // Replacing the team's tool needs --replace (the yes to a question that said so); without it nothing changes. fs.writeFileSync(design, JSON.stringify({ tool: 'figma', project_url: 'https://figma.example/f' })); r = yadPath(['toolbox', 'connect', 'openpencil', '--verify', '--json'], { cwd: p, home, bins: ['openpencil'] }); assert.equal(r.status, 1); assert.match(JSON.parse(r.stdout).error, /OpenPencil would replace Figma as this team's choice in \.sdlc\/design\.json, so nothing was recorded/); assert.equal(JSON.parse(fs.readFileSync(design, 'utf8')).tool, 'figma'); j = JSON.parse(yadPath(['toolbox', 'connect', 'openpencil', '--verify', '--replace', '--json'], { cwd: p, home, bins: ['openpencil'] }).stdout); assert.deepEqual([j.written, j.replaced], [['.sdlc/design.json'], 'figma']); assert.equal(JSON.parse(fs.readFileSync(design, 'utf8')).tool, 'openpencil'); // A broken toolbox file refuses before ANY write: the connector's file stays as it was. fs.writeFileSync(design, JSON.stringify({ tool: 'figma' })); fs.writeFileSync(path.join(p, '.sdlc/toolbox.json'), '{broken'); r = yadPath(['toolbox', 'connect', 'openpencil', '--verify', '--replace', '--json'], { cwd: p, home, bins: ['openpencil'] }); assert.equal(r.status, 1); assert.equal(JSON.parse(fs.readFileSync(design, 'utf8')).tool, 'figma'); fs.rmSync(path.join(p, '.sdlc/toolbox.json')); // A tool that is not a connector: its use goes in the team's toolbox file. put(path.join(p, '.mcp.json'), JSON.stringify({ mcpServers: { MCP_DOCKER: { command: 'docker' } } })); j = JSON.parse(yadPath(['toolbox', 'connect', 'docker-mcp', '--verify', '--json'], { cwd: p, home }).stdout); assert.deepEqual([j.used, j.written], [true, ['.sdlc/toolbox.json']]); assert.deepEqual(toolboxJSON(p).shipped, { 'docker-mcp': 'use' }); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E165: the connect skills offer `yad toolbox connect` under the connect-tool rule, and no longer say never install', () => { for (const [skill, tool] of [['yad-connect-design', ''], ['yad-connect-testing', ''], ['yad-connect-learning', 'deeptutor']]) { const text = fs.readFileSync(path.join(ROOT, 'skills', skill, 'SKILL.md'), 'utf8'); assert.ok(text.includes(`yad toolbox connect ${tool} --json`), `${skill} asks the command first`); assert.match(text, /--verify --json/, `${skill} verifies after`); assert.match(text, /connect-tool rule/, `${skill} names the rule`); assert.doesNotMatch(text, /Do \*\*not\*\* install/, `${skill} no longer forbids the connect step`); } }); test('E165: on Windows an MCP server started through npx or an npm program gets `cmd /c`, as Claude Code needs there', async () => { const { connectPlan } = await import('./toolbox-connect.mjs'); const none = { items: [], has: () => false }; assert.equal(connectPlan('playwright', { ...none, platform: 'win32' }).steps[0].run, 'claude mcp add --scope user playwright -- cmd /c npx @playwright/mcp@0.0.83'); assert.equal(connectPlan('openpencil', { ...none, platform: 'win32' }).steps[1].run, 'claude mcp add --scope user open-pencil -- cmd /c openpencil-mcp'); assert.equal(connectPlan('openpencil', { ...none, platform: 'win32' }).steps[0].run, 'npm install -g @open-pencil/mcp@0.16.0 @open-pencil/cli@0.16.0', 'a package install is the same everywhere'); assert.equal(connectPlan('playwright', { ...none, platform: 'darwin' }).steps[0].run, 'claude mcp add --scope user playwright -- npx @playwright/mcp@0.0.83'); }); test('E165 PR 2: the flow offers the connect step — yad-ui and the test step before they degrade, spec and implement on a failed probe, every fallback section', () => { const read = (skill) => fs.readFileSync(path.join(ROOT, 'skills', skill, 'SKILL.md'), 'utf8'); for (const skill of ['yad-ui', 'yad-test-cases']) { const text = read(skill); assert.ok(text.includes('yad toolbox connect --json') && text.includes('yad toolbox connect --verify --json'), `${skill} asks, then verifies`); assert.match(text, /A tool is named, but it is not on this machine[\s\S]*connect-tool rule[\s\S]*On a no, or when a step fails, degrade/, `${skill} offers before it degrades`); // Review 1: --verify records the tool, not the server found — the connect skill's refresh writes `source`. assert.match(text, /run `yad-connect-(design|testing)` with\s+`action: refresh`/, `${skill} refreshes the connection before it goes on`); } assert.match(read('yad-ui'), /out of scope for Shape, except the one connect offer/, 'the Shape rule does not forbid the offer'); // Review 2: a server just added is loaded only when the agent starts — restart, never "unavailable". for (const skill of ['yad-spec', 'yad-implement']) assert.match(read(skill), /restart the agent and run\s+this step again/, `${skill} says a new server needs a restart`); for (const skill of ['yad-ui', 'yad-test-cases']) assert.ok(!/with\s+`action: refresh`(?! and the same `tool`)/.test(read(skill)), `${skill}: every refresh names the same tool`); // Review 6: the rule itself keeps the refresh, with the same tool. assert.match(RULES.find((r) => r.id === 'connect-tool').text, /its connect skill with `action: refresh` and the same `tool` first/); // Review 4: after the restart, refresh first — `--verify` records the tool, never its server. for (const [skill, connect] of [['yad-ui', 'yad-connect-design'], ['yad-test-cases', 'yad-connect-testing']]) { assert.match(read(skill), new RegExp(`restart the agent, run\\s+\`${connect}\` with \`action: refresh\` and the same \`tool\`, and then run\\s+this step again`), skill); } for (const skill of ['yad-ui', 'yad-test-cases']) assert.match(read(skill), /first check that you can reach the tool[\s\S]*do not\s+refresh — it would record the tool as unavailable[\s\S]*If you can, run `yad-connect-/, `${skill}: the check comes before the refresh`); assert.match(read('yad-ui'), /or for OpenPencil its CLI on PATH/, 'the CLI path needs no restart'); // Review 3: the connect skills themselves never write `unavailable` right after a connect. // Review 4: the restart branch writes nothing — it skips the degrade and Step 2. for (const skill of ['yad-connect-design', 'yad-connect-testing']) { assert.match(read(skill), /When `--verify` passes, detect again[\s\S]*\*\*If you can\*\*, go on to Step 2 and record what you found\. \*\*If you cannot\*\*[\s\S]*do \*\*not\*\* write the file:\s+skip the degrade below and Step 2[\s\S]*restart the agent and run this skill\s+again with `action: refresh`/, skill); // Review 6: the refresh names the tool just connected, or it would check the default tool. assert.ok(!/with\s+`action: refresh`(?! and the same `tool`)/.test(read(skill)), `${skill}: every refresh names the same tool`); // Review 5: the report says only what is true before the restart. assert.match(read(skill), /### Step 3[\s\S]*\*\*Right after a `--verify` that passed but could not reach the\s+tool yet:\*\* report only/, skill); assert.match(read(skill), /\*\*Graceful degradation\*\* \(never right after a `--verify` that passed — see above\)/, skill); } assert.match(read('yad-implement'), /On a no, when a step fails, if it still fails, or if another\s+file is open, \*\*STOP\*\*/, 'implement says what a no means'); for (const skill of ['yad-spec', 'yad-implement']) { const text = read(skill); assert.match(text, /not on this machine at all[\s\S]*not a\s+closed app[\s\S]*the answer has `preflight\.connect`[\s\S]*connect-tool rule/, `${skill} offers only when the tool is absent, never for a closed app`); } // The generated section says it once, in every skill that has one. const section = skillFallbackSection('yad-ui'); assert.match(section, /offer to connect it, once: run `yad toolbox connect --json` and follow the\nconnect-tool rule\. On a no, or when a step fails, use the fallback\./); assert.match(section, /not turned off, not removed\nby the team/, 'a plugin turned off, or a tool the team removed, is never offered'); }); // ---- E125 b: a project file is read only as a plain file (EP-factory-safety-S02) ------------------- const LINK_SKIP = process.platform === 'win32' && 'links need admin rights on Windows'; const NOT_PLAIN = 'is a link or not a plain file, so it was not read'; test('E125 b detect: a project MCP or settings file that is a link or a folder is a problem, never read', { skip: LINK_SKIP }, () => { const T = tmp(); const proj = path.join(T, 'p'); const home = path.join(T, 'h'); try { // Valid files outside the project: a read that followed the link would list their servers. put(path.join(T, 'outside.json'), JSON.stringify({ mcpServers: { leaked: { command: 'x' } }, enabledPlugins: { 'a@m': true } })); fs.mkdirSync(path.join(proj, '.cursor'), { recursive: true }); fs.symlinkSync(path.join(T, 'outside.json'), path.join(proj, '.mcp.json')); fs.mkdirSync(path.join(proj, '.cursor/mcp.json')); // A dangling link is a link too, not a missing file. fs.symlinkSync(path.join(T, 'nowhere.json'), path.join(proj, '.gemini-settings-link')); fs.mkdirSync(path.join(proj, '.gemini')); fs.renameSync(path.join(proj, '.gemini-settings-link'), path.join(proj, '.gemini/settings.json')); put(path.join(home, '.claude/plugins/installed_plugins.json'), JSON.stringify({ plugins: { 'a@m': [{ scope: 'user' }] } })); fs.mkdirSync(path.join(proj, '.claude')); fs.symlinkSync(path.join(T, 'outside.json'), path.join(proj, '.claude/settings.json')); // The home folder's own files are the person's: a link there is followed, as before. fs.mkdirSync(path.join(home, '.cursor'), { recursive: true }); fs.symlinkSync(path.join(T, 'outside.json'), path.join(home, '.cursor/mcp.json')); const { items, problems } = detectInstalled(proj, { home }); assert.deepEqual(problems.filter((p) => p.problem === NOT_PLAIN).map((p) => p.where).sort(), ['.claude/settings.json', '.cursor/mcp.json', '.gemini/settings.json', '.mcp.json']); assert.deepEqual(find(items, 'mcp', 'leaked').map((i) => i.where), ['~/.cursor/mcp.json'], 'only the home folder\'s link is followed'); assert.equal(find(items, 'plugin', 'a@m')[0].enabled, null, 'the linked settings file is not read for the plugin\'s switch'); // A broken project file keeps its own answer. fs.rmSync(path.join(proj, '.mcp.json')); put(path.join(proj, '.mcp.json'), '{ broken'); assert.deepEqual(detectInstalled(proj, { home }).problems.find((p) => p.where === '.mcp.json'), { where: '.mcp.json', problem: 'could not be read as a JSON object' }); // A byte-order mark is still read past. fs.rmSync(path.join(proj, '.mcp.json')); put(path.join(proj, '.mcp.json'), `\ufeff${JSON.stringify({ mcpServers: { bom: { command: 'x' } } })}`); assert.equal(find(detectInstalled(proj, { home }).items, 'mcp', 'bom').length, 1); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E125 b detect: a project .mcp.json that links to /dev/zero is a problem at once', { skip: process.platform === 'win32' && 'no /dev/zero on Windows' }, () => { const T = tmp(); try { fs.mkdirSync(path.join(T, 'p')); fs.symlinkSync('/dev/zero', path.join(T, 'p', '.mcp.json')); const url = JSON.stringify(new URL('./detect.mjs', import.meta.url).href); const r = spawnSync(process.execPath, ['--input-type=module', '-e', `const { detectInstalled } = await import(${url}); process.stdout.write(JSON.stringify(detectInstalled(process.argv[1], { home: process.argv[2] }).problems));`, path.join(T, 'p'), path.join(T, 'h')], { encoding: 'utf8', timeout: 20000, env: { ...process.env, YAD_NO_UPDATE_NOTIFIER: '1' } }); assert.equal(r.signal, null, `the read did not end: ${r.stderr}`); assert.equal(r.status, 0, r.stderr); assert.deepEqual(JSON.parse(r.stdout.trim().split('\n').pop()), [{ where: '.mcp.json', problem: NOT_PLAIN }]); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E125 b detect: run in the home folder, its own linked files are read as the person\'s', { skip: LINK_SKIP }, () => { const T = tmp(); try { put(path.join(T, 'dotfiles/mcp.json'), JSON.stringify({ mcpServers: { mine: { command: 'x' } } })); fs.symlinkSync(path.join(T, 'dotfiles/mcp.json'), path.join(T, '.mcp.json')); const { items, problems } = detectInstalled(T, { home: T }); assert.deepEqual(problems, []); assert.equal(find(items, 'mcp', 'mine').length, 1); } finally { fs.rmSync(T, { recursive: true, force: true }); } }); test('E125 b detect: a project .codex/config.toml that is a link, a folder or a link to /dev/zero is a problem, never read', { skip: LINK_SKIP }, () => { const T = tmp(); const proj = path.join(T, 'p'); const home = path.join(T, 'h'); try { put(path.join(T, 'outside.toml'), '[mcp_servers.leaked]\ncommand = "x"\n'); fs.mkdirSync(path.join(proj, '.codex'), { recursive: true }); fs.symlinkSync(path.join(T, 'outside.toml'), path.join(proj, '.codex/config.toml')); // The home folder's own is the person's: followed, as before. fs.mkdirSync(path.join(home, '.codex'), { recursive: true }); fs.symlinkSync(path.join(T, 'outside.toml'), path.join(home, '.codex/config.toml')); let got = detectInstalled(proj, { home }); assert.deepEqual(got.problems, [{ where: '.codex/config.toml', problem: NOT_PLAIN }]); assert.deepEqual(find(got.items, 'mcp', 'leaked').map((i) => i.where), ['~/.codex/config.toml']); fs.rmSync(path.join(proj, '.codex/config.toml')); fs.mkdirSync(path.join(proj, '.codex/config.toml')); assert.deepEqual(detectInstalled(proj, { home }).problems, [{ where: '.codex/config.toml', problem: NOT_PLAIN }]); // A plain file is read as before. fs.rmSync(path.join(proj, '.codex/config.toml'), { recursive: true }); put(path.join(proj, '.codex/config.toml'), '[mcp_servers.mine]\ncommand = "x"\n'); got = detectInstalled(proj, { home }); assert.deepEqual(got.problems, []); assert.deepEqual(find(got.items, 'mcp', 'mine').map((i) => i.where), ['.codex/config.toml']); // Run in the home folder, its own linked file is the person's. fs.rmSync(path.join(proj, '.codex/config.toml')); assert.deepEqual(detectInstalled(home, { home }).problems, []); if (process.platform !== 'win32') { fs.symlinkSync('/dev/zero', path.join(proj, '.codex/config.toml')); const url = JSON.stringify(new URL('./detect.mjs', import.meta.url).href); const r = spawnSync(process.execPath, ['--input-type=module', '-e', `const { detectInstalled } = await import(${url}); process.stdout.write(JSON.stringify(detectInstalled(process.argv[1], { home: process.argv[2] }).problems));`, proj, path.join(T, 'none')], { encoding: 'utf8', timeout: 20000, env: { ...process.env, YAD_NO_UPDATE_NOTIFIER: '1' } }); assert.equal(r.signal, null, `the read did not end: ${r.stderr}`); assert.deepEqual(JSON.parse(r.stdout.trim().split('\n').pop()), [{ where: '.codex/config.toml', problem: NOT_PLAIN }]); } } finally { fs.rmSync(T, { recursive: true, force: true }); } });