@fabersep/spec 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.mjs ADDED
@@ -0,0 +1,288 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ getPackageVersion,
4
+ getStatus,
5
+ installEngines,
6
+ uninstallEngines,
7
+ } from './installer.mjs';
8
+ import { promptMultiSelect } from './prompt.mjs';
9
+
10
+ const ESC = '\x1b';
11
+ const useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
12
+ const bold = (s) => (useColor ? `${ESC}[1m${s}${ESC}[0m` : s);
13
+ const green = (s) => (useColor ? `${ESC}[32m${s}${ESC}[0m` : s);
14
+ const yellow = (s) => (useColor ? `${ESC}[33m${s}${ESC}[0m` : s);
15
+ const dim = (s) => (useColor ? `${ESC}[2m${s}${ESC}[0m` : s);
16
+ const red = (s) => (useColor ? `${ESC}[31m${s}${ESC}[0m` : s);
17
+
18
+ function printHelp() {
19
+ const version = getPackageVersion();
20
+ console.log(`${bold(`FaberSEP Spec v${version}`)} — Spec-driven templates & faber-* skills for AI coding agents
21
+
22
+ ${bold('Usage:')}
23
+ npx @fabersep/spec init [options] Detect installed AI tools and install faber-* skills
24
+ npx @fabersep/spec status Show installed version, skills, and connected tools
25
+ npx @fabersep/spec uninstall [options] Remove FaberSEP Spec links/files from AI tools
26
+
27
+ ${bold('Init options:')}
28
+ -y, --yes Skip interactive prompt and install into all detected tools
29
+ --engine <list> Comma-separated tools: antigravity,claude-code,codex,cursor
30
+ --dry-run Preview what would be installed without modifying disk
31
+ --link Link directly to this local checkout (for contributors)
32
+ --undo Alias for uninstall
33
+
34
+ ${bold('Examples:')}
35
+ npx @fabersep/spec init
36
+ npx @fabersep/spec init --yes
37
+ npx @fabersep/spec init --engine antigravity,claude-code
38
+ npx @fabersep/spec status
39
+ npx @fabersep/spec uninstall
40
+ `);
41
+ }
42
+
43
+ function parseArgs(argv) {
44
+ const args = argv.slice(2);
45
+ let command = null;
46
+ const flags = {
47
+ yes: false,
48
+ dryRun: false,
49
+ link: false,
50
+ undo: false,
51
+ help: false,
52
+ version: false,
53
+ engines: null,
54
+ };
55
+
56
+ for (let i = 0; i < args.length; i++) {
57
+ const arg = args[i];
58
+ if (arg === '-h' || arg === '--help') {
59
+ flags.help = true;
60
+ } else if (arg === '-v' || arg === '--version') {
61
+ flags.version = true;
62
+ } else if (arg === '-y' || arg === '--yes') {
63
+ flags.yes = true;
64
+ } else if (arg === '--dry-run') {
65
+ flags.dryRun = true;
66
+ } else if (arg === '--link') {
67
+ flags.link = true;
68
+ } else if (arg === '--undo') {
69
+ flags.undo = true;
70
+ } else if (arg === '--engine' || arg === '--engines') {
71
+ const val = args[++i];
72
+ if (!val) throw new Error(`${arg} requires a comma-separated list of engines`);
73
+ flags.engines = val
74
+ .split(',')
75
+ .map((s) => s.trim())
76
+ .filter(Boolean);
77
+ } else if (arg.startsWith('--engine=')) {
78
+ flags.engines = arg
79
+ .slice('--engine='.length)
80
+ .split(',')
81
+ .map((s) => s.trim())
82
+ .filter(Boolean);
83
+ } else if (!arg.startsWith('-') && !command) {
84
+ command = arg;
85
+ } else {
86
+ throw new Error(`Unknown argument: ${arg}`);
87
+ }
88
+ }
89
+
90
+ return { command, flags };
91
+ }
92
+
93
+ async function runInit(flags) {
94
+ if (flags.undo) {
95
+ return runUninstall(flags);
96
+ }
97
+
98
+ const version = getPackageVersion();
99
+ const statusBefore = getStatus();
100
+ const detectedList = statusBefore.engines;
101
+ const availableList = detectedList.filter((e) => e.detected || e.installed);
102
+ let selectedIds = flags.engines;
103
+ let deselectedIds = [];
104
+
105
+ if (!selectedIds) {
106
+ if (flags.yes || !process.stdin.isTTY) {
107
+ selectedIds = detectedList.filter((e) => e.detected).map((e) => e.id);
108
+ if (selectedIds.length === 0) {
109
+ console.log(
110
+ yellow(
111
+ 'No supported AI coding tools were auto-detected (~/.gemini, ~/.claude, ~/.codex, ~/.cursor).',
112
+ ),
113
+ );
114
+ console.log(
115
+ 'Specify targets explicitly, e.g.: npx @fabersep/spec init --engine claude-code,antigravity',
116
+ );
117
+ return 1;
118
+ }
119
+ } else {
120
+ const promptList = availableList.length > 0 ? availableList : detectedList;
121
+ console.log('');
122
+ selectedIds = await promptMultiSelect({
123
+ title: `FaberSEP Spec v${version} — Select AI coding tools to install into:`,
124
+ subtitle:
125
+ availableList.length > 0
126
+ ? 'Detected tools are pre-selected. Uncheck any tool to skip or remove it, then press Enter.'
127
+ : 'No AI coding tools were auto-detected. Select any tool to install into, then press Enter.',
128
+ items: promptList.map((e) => ({
129
+ id: e.id,
130
+ label: e.label,
131
+ hint: e.installed
132
+ ? `(installed: ${e.detectHint})`
133
+ : e.detected
134
+ ? `(detected: ${e.detectHint})`
135
+ : `(${e.detectHint})`,
136
+ checked: e.detected || e.installed,
137
+ })),
138
+ });
139
+
140
+ if (selectedIds === null) {
141
+ console.log(dim('Cancelled. Nothing was modified.'));
142
+ return 0;
143
+ }
144
+
145
+ const selectedSet = new Set(selectedIds);
146
+ deselectedIds = promptList
147
+ .filter((e) => e.installed && !selectedSet.has(e.id))
148
+ .map((e) => e.id);
149
+
150
+ if (selectedIds.length === 0 && deselectedIds.length === 0) {
151
+ console.log(yellow('No tools selected. Nothing was installed.'));
152
+ return 0;
153
+ }
154
+ }
155
+ }
156
+
157
+ if (deselectedIds.length > 0) {
158
+ const removed = uninstallEngines({
159
+ engines: deselectedIds,
160
+ dryRun: flags.dryRun,
161
+ });
162
+ const prefix = flags.dryRun ? '[dry-run] Would remove' : 'Removed';
163
+ for (const item of removed.removed) {
164
+ console.log(` ${green('✓')} ${prefix} (${item.label}): ${item.path}`);
165
+ }
166
+ if (removed.removedCanonical) {
167
+ console.log(` ${green('✓')} ${prefix} canonical store: ${removed.canonicalRoot}`);
168
+ }
169
+ if (selectedIds.length === 0) {
170
+ console.log(dim('\nProject docs/ folders in your repositories were not touched.'));
171
+ return 0;
172
+ }
173
+ }
174
+
175
+ const summary = installEngines({
176
+ engines: selectedIds,
177
+ linkDev: flags.link,
178
+ dryRun: flags.dryRun,
179
+ });
180
+
181
+ if (flags.dryRun) {
182
+ console.log(bold(`[dry-run] Would install FaberSEP Spec v${summary.version}`));
183
+ console.log(` Canonical store: ${summary.canonicalRoot}`);
184
+ console.log(` Skills (${summary.skills.length}): ${summary.skills.join(', ')}`);
185
+ for (const r of summary.results) {
186
+ console.log(` • ${r.label}: ${r.targets.join(', ')}`);
187
+ }
188
+ return 0;
189
+ }
190
+
191
+ console.log(green(`✓ Installed FaberSEP Spec v${summary.version}`));
192
+ console.log(dim(` Source: ${summary.canonicalRoot}`));
193
+ console.log(dim(` Skills (${summary.skills.length}): ${summary.skills.join(', ')}`));
194
+ console.log('');
195
+ for (const r of summary.results) {
196
+ const targetSummary =
197
+ r.mode === 'plugin' ? r.targets[0] : `${r.targets.length} skills -> ${r.targets[0].replace(/\/faber-[^/]+$/, '')}`;
198
+ console.log(` ${green('✓')} ${bold(r.label.padEnd(22))} ${targetSummary} ${dim(`(${r.method})`)}`);
199
+ if (r.backedUpTo) {
200
+ console.log(yellow(` backed up previous directory to: ${r.backedUpTo}`));
201
+ }
202
+ }
203
+ console.log('');
204
+ console.log(bold('Next step:'));
205
+ console.log(' Open any project in your AI coding tool and ask:');
206
+ console.log(dim(' "Run faber-init-arch to document this repository\'s architecture."'));
207
+ console.log('');
208
+ return 0;
209
+ }
210
+
211
+ function runStatus() {
212
+ const st = getStatus();
213
+ console.log(bold(`FaberSEP Spec Status`));
214
+ console.log(
215
+ ` Canonical store: ${st.canonicalRoot} ${
216
+ st.canonicalExists ? green(`(v${st.installedVersion || '?'})`) : yellow('(not installed)')
217
+ }`,
218
+ );
219
+ console.log(` Skills (${st.skills.length}): ${st.skills.join(', ')}`);
220
+ console.log('');
221
+ for (const e of st.engines) {
222
+ const state = e.installed
223
+ ? green('installed')
224
+ : e.detected
225
+ ? yellow('detected (not linked)')
226
+ : dim('not detected');
227
+ const detail = e.installed
228
+ ? e.mode === 'plugin'
229
+ ? e.targetHint
230
+ : `${e.installedSkills.length}/${st.skills.length} skills in ${e.targetHint}`
231
+ : e.detectHint;
232
+ console.log(` ${e.label.padEnd(23)} ${state.padEnd(28)} ${dim(detail)}`);
233
+ }
234
+ return 0;
235
+ }
236
+
237
+ function runUninstall(flags) {
238
+ const res = uninstallEngines({
239
+ engines: flags.engines || undefined,
240
+ dryRun: flags.dryRun,
241
+ });
242
+
243
+ if (res.removed.length === 0 && !res.removedCanonical) {
244
+ console.log(dim('Nothing to uninstall — FaberSEP Spec was not installed.'));
245
+ return 0;
246
+ }
247
+
248
+ const prefix = flags.dryRun ? '[dry-run] Would remove' : 'Removed';
249
+ for (const item of res.removed) {
250
+ console.log(` ${green('✓')} ${prefix} (${item.label}): ${item.path}`);
251
+ }
252
+ if (res.removedCanonical) {
253
+ console.log(` ${green('✓')} ${prefix} canonical store: ${res.canonicalRoot}`);
254
+ }
255
+ console.log(dim('\nProject docs/ folders in your repositories were not touched.'));
256
+ return 0;
257
+ }
258
+
259
+ async function main() {
260
+ try {
261
+ const { command, flags } = parseArgs(process.argv);
262
+ if (flags.version) {
263
+ console.log(getPackageVersion());
264
+ return 0;
265
+ }
266
+ if (flags.help || !command) {
267
+ printHelp();
268
+ return 0;
269
+ }
270
+ if (command === 'init') {
271
+ return await runInit(flags);
272
+ }
273
+ if (command === 'status') {
274
+ return runStatus();
275
+ }
276
+ if (command === 'uninstall' || command === 'remove') {
277
+ return runUninstall(flags);
278
+ }
279
+ console.error(red(`Unknown command: ${command}`));
280
+ printHelp();
281
+ return 1;
282
+ } catch (err) {
283
+ console.error(red(`Error: ${err.message}`));
284
+ return 1;
285
+ }
286
+ }
287
+
288
+ process.exitCode = await main();
@@ -0,0 +1,387 @@
1
+ import * as fs from 'node:fs';
2
+ import * as os from 'node:os';
3
+ import * as path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = path.dirname(__filename);
8
+
9
+ export const PACKAGE_ROOT = path.resolve(__dirname, '..');
10
+ export const META_FILENAME = '.faber-spec-meta.json';
11
+
12
+ export function getPackageVersion() {
13
+ const pkgPath = path.join(PACKAGE_ROOT, 'package.json');
14
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
15
+ return pkg.version;
16
+ }
17
+
18
+ export function getUserHome() {
19
+ return process.env.FABER_USER_HOME || os.homedir();
20
+ }
21
+
22
+ export function getCanonicalRoot(userHome = getUserHome()) {
23
+ return path.join(userHome, '.faber', 'spec');
24
+ }
25
+
26
+ export function getSkillNames(sourceRoot = PACKAGE_ROOT) {
27
+ const skillsDir = path.join(sourceRoot, 'skills');
28
+ if (!fs.existsSync(skillsDir)) return [];
29
+ return fs
30
+ .readdirSync(skillsDir, { withFileTypes: true })
31
+ .filter((entry) => entry.isDirectory() && entry.name.startsWith('faber-'))
32
+ .map((entry) => entry.name)
33
+ .sort();
34
+ }
35
+
36
+ export function getEngineDefs(userHome = getUserHome()) {
37
+ return [
38
+ {
39
+ id: 'antigravity',
40
+ label: 'Antigravity',
41
+ detectPath: path.join(userHome, '.gemini'),
42
+ detectHint: '~/.gemini',
43
+ mode: 'plugin',
44
+ targetPath: path.join(userHome, '.gemini', 'config', 'plugins', 'faber-spec'),
45
+ targetHint: '~/.gemini/config/plugins/faber-spec',
46
+ },
47
+ {
48
+ id: 'claude-code',
49
+ label: 'Claude Code / Desktop',
50
+ detectPath: path.join(userHome, '.claude'),
51
+ detectHint: '~/.claude',
52
+ mode: 'plugin',
53
+ targetPath: path.join(userHome, '.claude', 'skills', 'faber-spec'),
54
+ targetHint: '~/.claude/skills/faber-spec',
55
+ },
56
+ {
57
+ id: 'codex',
58
+ label: 'OpenAI Codex',
59
+ detectPath: path.join(userHome, '.codex'),
60
+ detectHint: '~/.codex',
61
+ mode: 'skills',
62
+ targetPath: path.join(userHome, '.codex', 'skills'),
63
+ targetHint: '~/.codex/skills/faber-*',
64
+ },
65
+ {
66
+ id: 'cursor',
67
+ label: 'Cursor',
68
+ detectPath: path.join(userHome, '.cursor'),
69
+ detectHint: '~/.cursor',
70
+ mode: 'skills',
71
+ targetPath: path.join(userHome, '.cursor', 'skills'),
72
+ targetHint: '~/.cursor/skills/faber-*',
73
+ },
74
+ ];
75
+ }
76
+
77
+ export function detectEngines(userHome = getUserHome()) {
78
+ return getEngineDefs(userHome).map((engine) => ({
79
+ ...engine,
80
+ detected: fs.existsSync(engine.detectPath),
81
+ }));
82
+ }
83
+
84
+ function shouldCopyEntry(srcPath) {
85
+ const base = path.basename(srcPath);
86
+ if (base === '__pycache__' || base === '.DS_Store' || base.endsWith('.pyc')) {
87
+ return false;
88
+ }
89
+ return true;
90
+ }
91
+
92
+ function copyTree(src, dst) {
93
+ if (!shouldCopyEntry(src)) return;
94
+ const stat = fs.statSync(src);
95
+ if (stat.isDirectory()) {
96
+ fs.mkdirSync(dst, { recursive: true });
97
+ for (const entry of fs.readdirSync(src)) {
98
+ copyTree(path.join(src, entry), path.join(dst, entry));
99
+ }
100
+ } else {
101
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
102
+ fs.copyFileSync(src, dst);
103
+ fs.chmodSync(dst, stat.mode);
104
+ }
105
+ }
106
+
107
+ export function stageCanonicalInstall({
108
+ userHome = getUserHome(),
109
+ sourceRoot = PACKAGE_ROOT,
110
+ dryRun = false,
111
+ } = {}) {
112
+ const canonicalRoot = getCanonicalRoot(userHome);
113
+ const version = getPackageVersion();
114
+ const itemsToStage = [
115
+ 'plugin.json',
116
+ '.claude-plugin',
117
+ 'rules',
118
+ 'templates',
119
+ 'skills',
120
+ 'LICENSE',
121
+ 'README.md',
122
+ ];
123
+
124
+ if (dryRun) {
125
+ return { canonicalRoot, version, staged: false };
126
+ }
127
+
128
+ fs.rmSync(canonicalRoot, { recursive: true, force: true });
129
+ fs.mkdirSync(canonicalRoot, { recursive: true });
130
+
131
+ for (const rel of itemsToStage) {
132
+ const src = path.join(sourceRoot, rel);
133
+ if (fs.existsSync(src)) {
134
+ copyTree(src, path.join(canonicalRoot, rel));
135
+ }
136
+ }
137
+
138
+ const meta = {
139
+ name: '@fabersep/spec',
140
+ version,
141
+ installedAt: new Date().toISOString(),
142
+ skills: getSkillNames(canonicalRoot),
143
+ };
144
+ fs.writeFileSync(
145
+ path.join(canonicalRoot, META_FILENAME),
146
+ JSON.stringify(meta, null, 2) + '\n',
147
+ 'utf8',
148
+ );
149
+
150
+ return { canonicalRoot, version, staged: true, skills: meta.skills };
151
+ }
152
+
153
+ function isSymlink(p) {
154
+ try {
155
+ return fs.lstatSync(p).isSymbolicLink();
156
+ } catch {
157
+ return false;
158
+ }
159
+ }
160
+
161
+ function isManagedTarget(p) {
162
+ if (isSymlink(p)) return true;
163
+ if (!fs.existsSync(p)) return false;
164
+ if (fs.existsSync(path.join(p, META_FILENAME))) return true;
165
+ const pluginJson = path.join(p, 'plugin.json');
166
+ if (fs.existsSync(pluginJson)) {
167
+ try {
168
+ const parsed = JSON.parse(fs.readFileSync(pluginJson, 'utf8'));
169
+ if (parsed.name === 'faber-spec') return true;
170
+ } catch {
171
+ return false;
172
+ }
173
+ }
174
+ const skillMd = path.join(p, 'SKILL.md');
175
+ if (fs.existsSync(skillMd) && path.basename(p).startsWith('faber-')) {
176
+ return true;
177
+ }
178
+ return false;
179
+ }
180
+
181
+ function linkOrCopyDir(src, dst, { dryRun = false } = {}) {
182
+ let backedUpTo = null;
183
+ if (isSymlink(dst) || fs.existsSync(dst)) {
184
+ if (isManagedTarget(dst)) {
185
+ if (!dryRun) {
186
+ fs.rmSync(dst, { recursive: true, force: true });
187
+ }
188
+ } else {
189
+ backedUpTo = `${dst}.bak.${Date.now()}`;
190
+ if (!dryRun) {
191
+ fs.renameSync(dst, backedUpTo);
192
+ }
193
+ }
194
+ }
195
+
196
+ if (dryRun) {
197
+ return { method: 'symlink', backedUpTo };
198
+ }
199
+
200
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
201
+ try {
202
+ const type = process.platform === 'win32' ? 'junction' : 'dir';
203
+ fs.symlinkSync(src, dst, type);
204
+ return { method: 'symlink', backedUpTo };
205
+ } catch (err) {
206
+ if (err && (err.code === 'EPERM' || err.code === 'EACCES' || err.code === 'EXDEV')) {
207
+ copyTree(src, dst);
208
+ return { method: 'copy', backedUpTo };
209
+ }
210
+ throw err;
211
+ }
212
+ }
213
+
214
+ export function installEngines({
215
+ engines,
216
+ userHome = getUserHome(),
217
+ sourceRoot = PACKAGE_ROOT,
218
+ linkDev = false,
219
+ dryRun = false,
220
+ } = {}) {
221
+ const allDefs = new Map(getEngineDefs(userHome).map((e) => [e.id, e]));
222
+ const selectedIds = engines && engines.length > 0 ? engines : [];
223
+ for (const id of selectedIds) {
224
+ if (!allDefs.has(id)) {
225
+ throw new Error(`Unknown engine "${id}". Supported: ${[...allDefs.keys()].join(', ')}`);
226
+ }
227
+ }
228
+
229
+ const effectiveRoot = linkDev
230
+ ? path.resolve(sourceRoot)
231
+ : stageCanonicalInstall({ userHome, sourceRoot, dryRun }).canonicalRoot;
232
+
233
+ const skills = getSkillNames(linkDev ? effectiveRoot : sourceRoot);
234
+ const results = [];
235
+
236
+ for (const id of selectedIds) {
237
+ const def = allDefs.get(id);
238
+ if (def.mode === 'plugin') {
239
+ const outcome = linkOrCopyDir(effectiveRoot, def.targetPath, { dryRun });
240
+ results.push({
241
+ engine: id,
242
+ label: def.label,
243
+ mode: 'plugin',
244
+ targets: [def.targetPath],
245
+ method: outcome.method,
246
+ backedUpTo: outcome.backedUpTo,
247
+ });
248
+ } else {
249
+ const targets = [];
250
+ let method = 'symlink';
251
+ const backups = [];
252
+ for (const skill of skills) {
253
+ const srcSkill = path.join(effectiveRoot, 'skills', skill);
254
+ const dstSkill = path.join(def.targetPath, skill);
255
+ const outcome = linkOrCopyDir(srcSkill, dstSkill, { dryRun });
256
+ targets.push(dstSkill);
257
+ method = outcome.method;
258
+ if (outcome.backedUpTo) backups.push(outcome.backedUpTo);
259
+ }
260
+ results.push({
261
+ engine: id,
262
+ label: def.label,
263
+ mode: 'skills',
264
+ targets,
265
+ method,
266
+ backedUpTo: backups.length > 0 ? backups : null,
267
+ });
268
+ }
269
+ }
270
+
271
+ return {
272
+ version: getPackageVersion(),
273
+ canonicalRoot: effectiveRoot,
274
+ skills,
275
+ dryRun,
276
+ results,
277
+ };
278
+ }
279
+
280
+ export function getStatus({ userHome = getUserHome() } = {}) {
281
+ const canonicalRoot = getCanonicalRoot(userHome);
282
+ const metaPath = path.join(canonicalRoot, META_FILENAME);
283
+ let meta = null;
284
+ if (fs.existsSync(metaPath)) {
285
+ try {
286
+ meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
287
+ } catch {
288
+ meta = null;
289
+ }
290
+ }
291
+
292
+ const expectedSkills = meta?.skills || getSkillNames(PACKAGE_ROOT);
293
+ const engines = detectEngines(userHome).map((engine) => {
294
+ if (engine.mode === 'plugin') {
295
+ const exists = isSymlink(engine.targetPath) || fs.existsSync(engine.targetPath);
296
+ const linkTarget = isSymlink(engine.targetPath) ? fs.readlinkSync(engine.targetPath) : null;
297
+ return {
298
+ ...engine,
299
+ installed: exists,
300
+ linkTarget,
301
+ installedSkills: exists ? expectedSkills : [],
302
+ };
303
+ }
304
+ const installedSkills = expectedSkills.filter((skill) => {
305
+ const p = path.join(engine.targetPath, skill);
306
+ return isSymlink(p) || fs.existsSync(p);
307
+ });
308
+ return {
309
+ ...engine,
310
+ installed: installedSkills.length > 0,
311
+ linkTarget: null,
312
+ installedSkills,
313
+ };
314
+ });
315
+
316
+ return {
317
+ canonicalRoot,
318
+ canonicalExists: fs.existsSync(canonicalRoot),
319
+ installedVersion: meta?.version || null,
320
+ packageVersion: getPackageVersion(),
321
+ skills: expectedSkills,
322
+ engines,
323
+ };
324
+ }
325
+
326
+ export function uninstallEngines({
327
+ engines,
328
+ userHome = getUserHome(),
329
+ removeCanonical = true,
330
+ dryRun = false,
331
+ } = {}) {
332
+ const allDefs = getEngineDefs(userHome);
333
+ const targetIds = engines && engines.length > 0 ? new Set(engines) : new Set(allDefs.map((e) => e.id));
334
+ const canonicalRoot = getCanonicalRoot(userHome);
335
+ const skillNames = new Set([
336
+ ...getSkillNames(PACKAGE_ROOT),
337
+ ...(fs.existsSync(canonicalRoot) ? getSkillNames(canonicalRoot) : []),
338
+ ]);
339
+
340
+ const removed = [];
341
+
342
+ for (const def of allDefs) {
343
+ if (!targetIds.has(def.id)) continue;
344
+ if (def.mode === 'plugin') {
345
+ if ((isSymlink(def.targetPath) || fs.existsSync(def.targetPath)) && isManagedTarget(def.targetPath)) {
346
+ if (!dryRun) {
347
+ fs.rmSync(def.targetPath, { recursive: true, force: true });
348
+ }
349
+ removed.push({ engine: def.id, label: def.label, path: def.targetPath });
350
+ }
351
+ } else {
352
+ for (const skill of skillNames) {
353
+ const p = path.join(def.targetPath, skill);
354
+ if ((isSymlink(p) || fs.existsSync(p)) && isManagedTarget(p)) {
355
+ if (!dryRun) {
356
+ fs.rmSync(p, { recursive: true, force: true });
357
+ }
358
+ removed.push({ engine: def.id, label: def.label, path: p });
359
+ }
360
+ }
361
+ }
362
+ }
363
+
364
+ let removedCanonical = false;
365
+ const remainingInstalled =
366
+ engines && engines.length > 0
367
+ ? allDefs.some((def) => {
368
+ if (targetIds.has(def.id)) return false;
369
+ if (def.mode === 'plugin') {
370
+ return isSymlink(def.targetPath) || fs.existsSync(def.targetPath);
371
+ }
372
+ return [...skillNames].some((skill) => {
373
+ const p = path.join(def.targetPath, skill);
374
+ return isSymlink(p) || fs.existsSync(p);
375
+ });
376
+ })
377
+ : false;
378
+
379
+ if (removeCanonical && !remainingInstalled && fs.existsSync(canonicalRoot)) {
380
+ if (!dryRun) {
381
+ fs.rmSync(canonicalRoot, { recursive: true, force: true });
382
+ }
383
+ removedCanonical = true;
384
+ }
385
+
386
+ return { removed, removedCanonical, canonicalRoot, dryRun };
387
+ }