From dc3e649e2f52d4900e85d4fbde6cfd540bd218b1 Mon Sep 17 00:00:00 2001 From: Christopher Tso Date: Tue, 10 Nov 2026 16:14:35 +1100 Subject: [PATCH] fix(plugin): apply skill selection before syncing Discover and validate requested skills before saving the plugin declaration or synchronizing client files. Preserve existing allowlists after resolving marketplace aliases and remove the preliminary unfiltered synchronization. --- docs/src/content/docs/docs/reference/cli.mdx | 10 +- src/cli/commands/plugin.ts | 130 ++++++++--------- tests/e2e/plugin-git-remotes.test.ts | 39 ++++++ tests/e2e/plugin-install-options.test.ts | 139 ++++++++++++++++++- 4 files changed, 250 insertions(+), 68 deletions(-) diff --git a/docs/src/content/docs/docs/reference/cli.mdx b/docs/src/content/docs/docs/reference/cli.mdx index 51bdba40..f887000a 100644 --- a/docs/src/content/docs/docs/reference/cli.mdx +++ b/docs/src/content/docs/docs/reference/cli.mdx @@ -402,7 +402,15 @@ Only enable specific skills from the plugin. Can be specified multiple times: allagents plugin install superpowers@marketplace --skill brainstorming --skill tdd ``` -When used, all other skills from the plugin are implicitly disabled. Skills can be added later with `skill add`. +On a new installation, only the named skills are enabled. Reinstalling a plugin +with an existing allowlist extends that list. Skills can also be added later +with `skill add`. + +AllAgents discovers and validates the requested names before saving the plugin +declaration or synchronizing client files. It does not install other skills as +an intermediate discovery step. Unknown names fail without changing the plugin +declaration or client files. A plugin using `skills.exclude` must use `skill add` +to enable an individual skill rather than `plugin install --skill`. When the selected client uses native install mode, this command validates the runtime, source, scope, and live inventory before editing `workspace.yaml`. diff --git a/src/cli/commands/plugin.ts b/src/cli/commands/plugin.ts index f832b436..4b392f43 100644 --- a/src/cli/commands/plugin.ts +++ b/src/cli/commands/plugin.ts @@ -24,6 +24,7 @@ import { buildPluginSyncPlans, nativeIdentityMatches, preflightNativePluginDeclaration, + validateAllPlugins, type SyncOptions, } from '../../core/sync.js'; import type { NativeEffectData } from '../../core/native/types.js'; @@ -31,8 +32,7 @@ import { loadSyncState } from '../../core/sync-state.js'; import { addPluginForTarget, removePlugin, - addEnabledSkill, - extractPluginNames, + mergeTargetedPluginEntry, resolveMarketplacePluginDeclaration, } from '../../core/workspace-modify.js'; import { @@ -42,7 +42,6 @@ import { getInstalledUserPlugins, getInstalledProjectPlugins, getUserWorkspaceConfig, - addUserEnabledSkill, type InstalledPluginInfo, } from '../../core/user-workspace.js'; import { @@ -52,7 +51,7 @@ import { type PluginUpdateCheck, } from '../../core/plugin.js'; import { UpdateContext } from '../../core/update-context.js'; -import { getAllSkillsFromPlugins } from '../../core/skills.js'; +import { discoverSkillEntriesFromPluginRoot } from '../../core/skills.js'; import { validateLocalPlugin } from '../../validators/plugin.js'; import { getWorkspaceStatus, @@ -100,6 +99,7 @@ import { getPluginDisplayName, isRemotePluginSource, parseRemotePluginSource, + normalizePluginPath, } from '../../utils/plugin-path.js'; import { parseUserWorkspaceConfig, @@ -1270,6 +1270,34 @@ const pluginInstallCmd = command({ } prospectiveDeclaration = resolution.declaration; registeredMarketplace = resolution.registeredAs; + if (skills.length > 0) { + const config = isUser + ? await getUserWorkspaceConfig() + : existsSync(projectConfigPath) + ? await parseWorkspaceConfig(projectConfigPath) + : undefined; + const source = getPluginSource(prospectiveDeclaration); + const existing = config?.plugins.find((entry) => getPluginSource(entry) === source); + prospectiveDeclaration = mergeTargetedPluginEntry( + existing, + prospectiveDeclaration, + source, + config?.clients ?? target.clients, + ); + } + } + + if (skills.length > 0) { + const entry = typeof prospectiveDeclaration === 'string' + ? { source: prospectiveDeclaration } + : prospectiveDeclaration; + if (entry.skills && !Array.isArray(entry.skills)) { + throw new Error('Plugin is in blocklist mode; use skill add to enable an individual skill.'); + } + prospectiveDeclaration = { + ...entry, + skills: [...new Set([...(entry.skills ?? []), ...skills])], + }; } // Emit override warnings for project-scope installs @@ -1306,6 +1334,37 @@ const pluginInstallCmd = command({ installPlan.clients.length === 0 && installPlan.nativeClients.length > 0; + if (skills.length > 0 && installPlan) { + const discoveryPlan = { + ...installPlan, + source: isPluginSpec(installPlan.source) || isRemotePluginSource(installPlan.source) + ? installPlan.source + : normalizePluginPath(installPlan.source, workspacePath), + }; + const [validated] = await withPluginProgress((onProgress) => + validateAllPlugins( + [discoveryPlan], + isUser ? getHomeDir() : workspacePath, + false, + onProgress, + ), + ); + if (!validated?.success) { + throw new Error(validated?.error ?? 'Plugin discovery failed'); + } + const entries = await discoverSkillEntriesFromPluginRoot( + validated.resolved, + [], + validated.components, + validated.exclude, + ); + const availableNames = entries.map((entry) => entry.name); + const invalid = skills.filter((name) => !availableNames.includes(name)); + if (invalid.length > 0) { + throw new Error(`Unknown skills: ${invalid.join(', ')}. Available: ${availableNames.join(', ')}`); + } + } + const installTarget = { declaration: prospectiveDeclaration, clients: target.clients, @@ -1335,66 +1394,8 @@ const pluginInstallCmd = command({ const displayPlugin = result.normalizedPlugin ?? plugin; - // Handle --skill flag: write enabledSkills BEFORE sync so only one sync pass is needed - if (skills.length > 0) { - const workspacePath = isUser ? getHomeDir() : process.cwd(); - - // Do an initial sync to fetch the plugin so we can discover its skills. - const initialSync = isUser - ? await syncUserWorkspace() - : await syncProjectWorkspace(workspacePath, { yes }); - - if (!initialSync.success) { - const error = `Initial sync failed: ${initialSync.error ?? 'Unknown error'}`; - if (isJsonMode()) { - jsonOutput({ success: false, command: 'plugin install', error }); - process.exit(1); - } - console.error(`Error: ${error}`); - process.exit(1); - } - - const allSkills = await getAllSkillsFromPlugins(workspacePath); - const displayNames = extractPluginNames(displayPlugin); - const pluginSkills = allSkills.filter((s) => - s.pluginSource === displayPlugin || displayNames.includes(s.pluginName), - ); - - if (pluginSkills.length === 0) { - if (!isJsonMode()) { - console.error(`Warning: No skills found in plugin ${displayPlugin}`); - } - } else { - const pluginName = pluginSkills[0]?.pluginName; - const availableNames = pluginSkills.map((s) => s.name); - - // Validate requested skill names - const invalid = skills.filter((s) => !availableNames.includes(s)); - if (invalid.length > 0) { - const error = `Unknown skills: ${invalid.join(', ')}. Available: ${availableNames.join(', ')}`; - if (isJsonMode()) { - jsonOutput({ success: false, command: 'plugin install', error }); - process.exit(1); - } - console.error(`Error: ${error}`); - process.exit(1); - } - - // Add each skill to enabledSkills - for (const skillName of skills) { - const skillKey = `${pluginName}:${skillName}`; - const addResult = isUser - ? await addUserEnabledSkill(skillKey) - : await addEnabledSkill(skillKey, workspacePath); - if (!addResult.success && !isJsonMode()) { - console.error(`Warning: ${addResult.error}`); - } - } - - if (!isJsonMode()) { - console.log(`\nEnabled skills: ${skills.join(', ')}`); - } - } + if (skills.length > 0 && !isJsonMode()) { + console.log(`\nEnabled skills: ${skills.join(', ')}`); } if (result.replaced && !isJsonMode()) { @@ -1408,7 +1409,6 @@ const pluginInstallCmd = command({ console.log(`Installing plugin "${displayPlugin}"...\n`); } - // Single sync pass (enabledSkills already written if --skill was used) const { ok: syncOk, syncData, error: syncError } = isUser ? await runUserSyncAndPrint() : await runSyncAndPrint({ yes }); diff --git a/tests/e2e/plugin-git-remotes.test.ts b/tests/e2e/plugin-git-remotes.test.ts index 28e21e5d..4322467c 100644 --- a/tests/e2e/plugin-git-remotes.test.ts +++ b/tests/e2e/plugin-git-remotes.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:te import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import { parse as load } from 'yaml'; const repoRoot = join(import.meta.dir, '../..'); const cli = join(repoRoot, 'dist/index.js'); @@ -81,6 +82,44 @@ beforeEach(() => { afterEach(() => rmSync(root, { recursive: true, force: true })); describe('file-mode Git remotes through the built CLI', () => { + test.each(['project', 'user'] as const)('extends the canonical marketplace allowlist when reinstalling its repository alias at %s scope', (scope) => { + for (const name of ['fixture', 'unselected']) { + const directory = join(upstream, 'plugins', 'bundle', 'skills', name); + mkdirSync(directory, { recursive: true }); + writeFileSync(join(directory, 'SKILL.md'), `---\nname: ${name}\ndescription: ${name}\n---\n`); + } + mkdirSync(join(upstream, '.claude-plugin'), { recursive: true }); + writeFileSync(join(upstream, '.claude-plugin', 'marketplace.json'), JSON.stringify({ + name: 'canonical-market', + plugins: [{ name: 'bundle', source: './plugins/bundle' }], + })); + git(upstream, 'add', '.claude-plugin', 'plugins'); + git(upstream, 'commit', '-m', 'add marketplace fixture'); + git(upstream, 'push', remote, 'main'); + writeFileSync(gitConfig, readFileSync(gitConfig, 'utf8') + `[url "file://${remote}"]\n\tinsteadOf = https://github.com/fixture/selection-market.git\n`); + const source = 'bundle@fixture/selection-market'; + const install = (skill: string) => run(['plugin', 'install', source, '--scope', scope, '--client', 'codex', '--skill', skill, '--yes']); + const first = install('fixture'); + expect(first.exit, first.stdout + first.stderr).toBe(0); + const destination = scope === 'user' ? home : project; + const configPath = join(destination, '.allagents', 'workspace.yaml'); + writeFileSync(configPath, 'version: 2\nrepositories: []\nclients: [codex]\nplugins:\n - source: bundle@canonical-market\n skills: [fixture]\n exclude: [private/**]\n hooks: false\n'); + + const second = install('unselected'); + + expect(second.exit, second.stdout + second.stderr).toBe(0); + const config = load(readFileSync(configPath, 'utf8')) as { plugins: unknown[] }; + expect(config.plugins).toEqual([{ + source: 'bundle@canonical-market', + skills: ['fixture', 'unselected'], + exclude: ['private/**'], + hooks: false, + }]); + for (const skill of ['fixture', 'unselected']) { + expect(existsSync(join(destination, '.codex', 'skills', skill, 'SKILL.md'))).toBe(true); + } + }, 30_000); + test('local plugin installation checks an unchanged remote once and still applies later upstream changes', () => { const source = 'https://github.com/fixture/refresh/tree/main/collection/fixture'; writeFileSync(gitConfig, readFileSync(gitConfig, 'utf8') + `[url "file://${remote}"]\n\tinsteadOf = https://github.com/fixture/refresh.git\n`); diff --git a/tests/e2e/plugin-install-options.test.ts b/tests/e2e/plugin-install-options.test.ts index 71511df4..5ed816bb 100644 --- a/tests/e2e/plugin-install-options.test.ts +++ b/tests/e2e/plugin-install-options.test.ts @@ -11,13 +11,13 @@ let home: string; let workspace: string; let plugin: string; -async function runInstall(args: string[]): Promise<{ +async function runCli(args: string[]): Promise<{ exitCode: number; stdout: string; stderr: string; }> { const process = Bun.spawn( - ['bun', 'run', cliEntry, '--json', 'plugin', 'install', plugin, ...args], + ['bun', 'run', cliEntry, '--json', ...args], { cwd: workspace, env: { @@ -40,6 +40,10 @@ async function runInstall(args: string[]): Promise<{ return { exitCode, stdout, stderr }; } +async function runInstall(args: string[]) { + return runCli(['plugin', 'install', plugin, ...args]); +} + async function runInteractiveInstall( input: string, args: string[] = [ @@ -116,6 +120,137 @@ afterEach(async () => { }); describe('plugin install target options', () => { + test.each(['project', 'user'] as const)( + '--skill preserves unselected skill directories at %s scope', + async (scope) => { + await mkdir(join(plugin, 'skills', 'other'), { recursive: true }); + await writeFile( + join(plugin, 'skills', 'other', 'SKILL.md'), + '---\nname: other\ndescription: Other\n---\n# Upstream other\n', + ); + const destination = scope === 'user' ? home : workspace; + const privateSkill = '---\nname: other\ndescription: Private\n---\n# Private other\n'; + for (const client of ['.codex', '.cursor']) { + const directory = join(destination, client, 'skills', 'other'); + await mkdir(directory, { recursive: true }); + await writeFile(join(directory, 'SKILL.md'), privateSkill); + await writeFile(join(directory, 'personal.txt'), 'keep this file\n'); + } + + const result = await runInstall([ + '--scope', scope, '--client', 'codex,cursor', '--skill', 'demo', '--yes', + ]); + + expect(result.exitCode).toBe(0); + expect(JSON.parse(result.stdout).data.enabledSkills).toEqual(['demo']); + for (const client of ['.codex', '.cursor']) { + const directory = join(destination, client, 'skills'); + expect(await readFile(join(directory, 'other', 'SKILL.md'), 'utf8')).toBe(privateSkill); + expect(await readFile(join(directory, 'other', 'personal.txt'), 'utf8')).toBe('keep this file\n'); + expect(existsSync(join(directory, 'demo', 'SKILL.md'))).toBe(true); + } + const config = load(await readFile(join(destination, '.allagents', 'workspace.yaml'), 'utf8')) as { + plugins: Array<{ source: string; skills: string[] }>; + }; + expect(config.plugins).toEqual([{ source: plugin, skills: ['demo'] }]); + const state = JSON.parse(await readFile(join(destination, '.allagents', 'sync-state.json'), 'utf8')); + expect(Object.values(state.files).flat().some((path) => String(path).includes('/other/'))).toBe(false); + }, + 20_000, + ); + + test('rejects unknown --skill names before changing configuration or client files', async () => { + const configPath = join(workspace, '.allagents', 'workspace.yaml'); + await mkdir(join(workspace, '.allagents'), { recursive: true }); + const original = dump({ version: 2, repositories: [], plugins: [], clients: ['codex'] }); + await writeFile(configPath, original); + const directory = join(workspace, '.codex', 'skills', 'demo'); + await mkdir(directory, { recursive: true }); + await writeFile(join(directory, 'SKILL.md'), 'private demo\n'); + + const result = await runInstall([ + '--scope', 'project', '--client', 'codex', '--skill', 'missing', '--yes', + ]); + + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout).error).toContain('Unknown skills: missing'); + expect(await readFile(configPath, 'utf8')).toBe(original); + expect(await readFile(join(directory, 'SKILL.md'), 'utf8')).toBe('private demo\n'); + expect(existsSync(join(workspace, '.allagents', 'sync-state.json'))).toBe(false); + }, 20_000); + + test('--skill extends an existing allowlist while preserving plugin fields', async () => { + await mkdir(join(plugin, 'skills', 'other'), { recursive: true }); + await writeFile(join(plugin, 'skills', 'other', 'SKILL.md'), '---\nname: other\ndescription: Other\n---\n'); + await mkdir(join(workspace, '.allagents'), { recursive: true }); + await writeFile(join(workspace, '.allagents', 'workspace.yaml'), dump({ + version: 2, + repositories: [], + clients: ['codex'], + plugins: [{ source: plugin, skills: ['demo'], exclude: ['private/**'], hooks: false }], + })); + + const result = await runInstall([ + '--scope', 'project', '--client', 'codex', '--skill', 'other', '--skill', 'demo', '--yes', + ]); + + expect(result.exitCode).toBe(0); + const config = load(await readFile(join(workspace, '.allagents', 'workspace.yaml'), 'utf8')) as { plugins: unknown[] }; + expect(config.plugins).toEqual([{ source: plugin, skills: ['demo', 'other'], exclude: ['private/**'], hooks: false }]); + for (const name of ['demo', 'other']) { + expect(existsSync(join(workspace, '.codex', 'skills', name, 'SKILL.md'))).toBe(true); + } + }, 20_000); + + test.each(['project', 'user'] as const)( + '--skill respects marketplace component declarations at %s scope', + async (scope) => { + await mkdir(join(root, '.claude-plugin'), { recursive: true }); + await mkdir(join(plugin, '.claude-plugin'), { recursive: true }); + await mkdir(join(plugin, 'custom-skills', 'selected'), { recursive: true }); + await writeFile(join(plugin, 'custom-skills', 'selected', 'SKILL.md'), '---\nname: selected\ndescription: Selected\n---\n'); + await writeFile(join(plugin, '.claude-plugin', 'plugin.json'), JSON.stringify({ name: 'bundle', skills: './custom-skills/' })); + await writeFile(join(root, '.claude-plugin', 'marketplace.json'), JSON.stringify({ + name: 'selection-market', + plugins: [{ name: 'bundle', source: './plugin' }], + })); + if (scope === 'project') { + await mkdir(join(workspace, '.allagents'), { recursive: true }); + await writeFile(join(workspace, '.allagents', 'workspace.yaml'), dump({ version: 2, repositories: [], plugins: [], clients: ['codex'] })); + } + const registration = await runCli(['plugin', 'marketplace', 'add', root, '--scope', scope]); + expect(registration).toMatchObject({ exitCode: 0 }); + plugin = 'bundle@selection-market'; + const destination = scope === 'user' ? home : workspace; + + const invalid = await runInstall(['--scope', scope, '--client', 'codex', '--skill', 'demo', '--yes']); + expect(invalid.exitCode).toBe(1); + expect(JSON.parse(invalid.stdout).error).toContain('Unknown skills: demo'); + expect(existsSync(join(destination, '.codex', 'skills', 'demo'))).toBe(false); + + const result = await runInstall(['--scope', scope, '--client', 'codex', '--skill', 'selected', '--yes']); + expect(result.exitCode).toBe(0); + expect(existsSync(join(destination, '.codex', 'skills', 'selected', 'SKILL.md'))).toBe(true); + const config = load(await readFile(join(destination, '.allagents', 'workspace.yaml'), 'utf8')) as { plugins: unknown[] }; + expect(config.plugins).toEqual([{ source: plugin, skills: ['selected'] }]); + }, + 30_000, + ); + + test('--skill rejects blocklist mode before changing its declaration or copying files', async () => { + await mkdir(join(workspace, '.allagents'), { recursive: true }); + const configPath = join(workspace, '.allagents', 'workspace.yaml'); + const original = dump({ version: 2, repositories: [], clients: ['codex'], plugins: [{ source: plugin, skills: { exclude: ['demo'] } }] }); + await writeFile(configPath, original); + + const result = await runInstall(['--scope', 'project', '--client', 'codex', '--skill', 'demo', '--yes']); + + expect(result.exitCode).toBe(1); + expect(JSON.parse(result.stdout).error).toContain('blocklist mode'); + expect(await readFile(configPath, 'utf8')).toBe(original); + expect(existsSync(join(workspace, '.codex', 'skills', 'demo'))).toBe(false); + }, 20_000); + test('persists an explicit client subset without changing scope defaults', async () => { await mkdir(join(workspace, '.allagents'), { recursive: true }); await writeFile(