impeccable 2.3.1 → 3.0.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.
@@ -2,25 +2,62 @@
2
2
  * `impeccable skills` subcommand
3
3
  *
4
4
  * Usage:
5
- * impeccable skills help Show all available skills and commands
6
- * impeccable skills install Install compiled skills from the universal bundle
7
- * impeccable skills update Update skills to latest version
5
+ * impeccable help Show all available skills and commands
6
+ * impeccable install Install compiled skills from the universal bundle
7
+ * impeccable link Symlink compiled skills from a local checkout
8
+ * impeccable update Update skills to latest version
8
9
  */
9
10
 
10
11
  import { execSync } from 'node:child_process';
11
- import { existsSync, readFileSync, readdirSync, statSync, lstatSync, symlinkSync, readlinkSync, unlinkSync, mkdirSync, writeFileSync, rmSync, renameSync, createWriteStream, realpathSync } from 'node:fs';
12
- import { join, resolve, dirname } from 'node:path';
13
- import { createInterface } from 'node:readline';
12
+ import { existsSync, readFileSync, readdirSync, statSync, lstatSync, unlinkSync, mkdirSync, writeFileSync, rmSync, renameSync, createWriteStream, realpathSync, symlinkSync, readlinkSync, cpSync } from 'node:fs';
13
+ import { join, resolve, dirname, relative, isAbsolute } from 'node:path';
14
+ import { createInterface, emitKeypressEvents } from 'node:readline';
14
15
  import { fileURLToPath } from 'node:url';
15
16
  import { get } from 'node:https';
16
17
  import { createHash } from 'node:crypto';
17
18
  import { tmpdir, homedir } from 'node:os';
19
+ import extract from 'extract-zip';
20
+ import { getHookConsent, setHookConsent } from '../../lib/impeccable-config.mjs';
18
21
 
19
22
  const __dirname = dirname(fileURLToPath(import.meta.url));
20
23
  const API_BASE = 'https://impeccable.style';
21
24
 
22
25
  // Provider folder names in project roots
23
- const PROVIDER_DIRS = ['.claude', '.cursor', '.gemini', '.agents', '.github', '.kiro', '.opencode', '.pi', '.qoder', '.trae', '.trae-cn'];
26
+ const PROVIDER_DIRS = ['.claude', '.cursor', '.gemini', '.agents', '.github', '.kiro', '.opencode', '.pi', '.qoder', '.trae', '.trae-cn', '.rovodev'];
27
+ const PROVIDER_ALIASES = {
28
+ agents: '.agents',
29
+ claude: '.claude',
30
+ 'claude-code': '.claude',
31
+ codex: '.agents',
32
+ copilot: '.github',
33
+ cursor: '.cursor',
34
+ gemini: '.gemini',
35
+ github: '.github',
36
+ kiro: '.kiro',
37
+ opencode: '.opencode',
38
+ pi: '.pi',
39
+ qoder: '.qoder',
40
+ 'rovo-dev': '.rovodev',
41
+ rovodev: '.rovodev',
42
+ trae: '.trae',
43
+ 'trae-cn': '.trae-cn',
44
+ };
45
+
46
+ const PROVIDER_DISPLAY = {
47
+ '.agents': { name: 'Codex CLI', input: 'codex' },
48
+ '.claude': { name: 'Claude Code', input: 'claude' },
49
+ '.cursor': { name: 'Cursor', input: 'cursor' },
50
+ '.gemini': { name: 'Gemini CLI', input: 'gemini' },
51
+ '.github': { name: 'GitHub Copilot', input: 'github' },
52
+ '.kiro': { name: 'Kiro', input: 'kiro' },
53
+ '.opencode': { name: 'OpenCode', input: 'opencode' },
54
+ '.pi': { name: 'Project Indigo', input: 'pi' },
55
+ '.qoder': { name: 'Qoder', input: 'qoder' },
56
+ '.rovodev': { name: 'Rovo Dev', input: 'rovo-dev' },
57
+ '.trae': { name: 'Trae', input: 'trae' },
58
+ '.trae-cn': { name: 'Trae CN', input: 'trae-cn' },
59
+ };
60
+ const PROVIDER_INPUT_ORDER = ['claude', 'codex', 'cursor', 'gemini', 'github', 'kiro', 'opencode', 'pi', 'qoder', 'trae', 'trae-cn', 'rovo-dev'];
24
61
 
25
62
  // When a project has no harness folder yet, infer the target from globally
26
63
  // installed harnesses (~/.claude, ~/.codex, ...). Codex reads skills from
@@ -33,15 +70,306 @@ const GLOBAL_HARNESS_HINTS = [
33
70
  { home: '.kiro', provider: '.kiro' },
34
71
  { home: '.opencode', provider: '.opencode' },
35
72
  { home: '.qoder', provider: '.qoder' },
73
+ { home: '.rovodev', provider: '.rovodev' },
36
74
  ];
37
75
 
38
76
  // Last-resort default when nothing is detected: Claude Code + the universal
39
77
  // (.agents, also Codex) folder, which covers the most common setups.
40
78
  const DEFAULT_TARGETS = ['.claude', '.agents'];
79
+ const IGNORED_SKILL_DIR_NAMES = new Set([
80
+ 'codex-primary-runtime',
81
+ ]);
82
+ const IMPECCABLE_HOOK_COMMAND_MARKERS = [
83
+ 'skills/impeccable/scripts/hook-probe.mjs',
84
+ 'skills/impeccable/scripts/hook.mjs',
85
+ 'skills/impeccable/scripts/hook-before-edit.mjs',
86
+ 'skills/impeccable/scripts/hook-after-edit.mjs',
87
+ 'skills/impeccable/scripts/hook-stop.mjs',
88
+ ];
89
+ const PROVIDER_HOOK_ARTIFACTS = {
90
+ '.claude': [
91
+ // The hook is a machine-local install side effect, so it lands in the
92
+ // gitignored `.claude/settings.local.json` rather than the team-shared
93
+ // `settings.json`. The bundle still ships the manifest as `settings.json`
94
+ // (the `rel` source), but we write it to `destRel`. A hook the user moved
95
+ // into `settings.json` is honored in place; see copyProviderHooks.
96
+ { sourceProvider: '.claude', rel: 'settings.json', destProvider: '.claude', destRel: 'settings.local.json' },
97
+ ],
98
+ '.cursor': [
99
+ { sourceProvider: '.cursor', rel: 'hooks.json', destProvider: '.cursor' },
100
+ ],
101
+ // Codex reads skills from `.agents/skills`, but project hooks from
102
+ // `.codex/hooks.json`, so the `.agents` install target owns this sidecar.
103
+ '.agents': [
104
+ { sourceProvider: '.codex', rel: 'hooks.json', destProvider: '.codex' },
105
+ ],
106
+ };
107
+
108
+ let pipedAnswers = null;
109
+ class PromptAbortError extends Error {
110
+ constructor() {
111
+ super('Aborted.');
112
+ this.name = 'PromptAbortError';
113
+ this.code = 'IMPECCABLE_PROMPT_ABORT';
114
+ }
115
+ }
116
+
117
+ function isPromptAbortError(error) {
118
+ return error?.code === 'IMPECCABLE_PROMPT_ABORT';
119
+ }
120
+
121
+ function canStyleTerminal() {
122
+ return Boolean(process.stdout.isTTY && process.env.NO_COLOR === undefined && process.env.TERM !== 'dumb');
123
+ }
124
+
125
+ function ansi(open, close, value) {
126
+ const text = String(value);
127
+ return canStyleTerminal() ? `${open}${text}${close}` : text;
128
+ }
129
+
130
+ const ui = {
131
+ accent: value => ansi('\x1b[36m', '\x1b[0m', value),
132
+ bold: value => ansi('\x1b[1m', '\x1b[22m', value),
133
+ dim: value => ansi('\x1b[2m', '\x1b[22m', value),
134
+ good: value => ansi('\x1b[32m', '\x1b[0m', value),
135
+ };
41
136
 
42
137
  function ask(question) {
138
+ if (!process.stdin.isTTY) {
139
+ process.stdout.write(question);
140
+ if (!pipedAnswers) {
141
+ let input = '';
142
+ try {
143
+ input = readFileSync(0, 'utf-8');
144
+ } catch {}
145
+ pipedAnswers = input.split(/\r?\n/);
146
+ }
147
+ return Promise.resolve(String(pipedAnswers.shift() || '').trim().toLowerCase());
148
+ }
149
+
43
150
  const rl = createInterface({ input: process.stdin, output: process.stdout });
44
- return new Promise(r => rl.question(question, ans => { rl.close(); r(ans.trim().toLowerCase()); }));
151
+ return new Promise((resolve, reject) => {
152
+ rl.once('SIGINT', () => {
153
+ rl.close();
154
+ reject(new PromptAbortError());
155
+ });
156
+ rl.question(question, ans => {
157
+ rl.close();
158
+ resolve(ans.trim().toLowerCase());
159
+ });
160
+ });
161
+ }
162
+
163
+ function isInteractivePrompt() {
164
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY && typeof process.stdin.setRawMode === 'function');
165
+ }
166
+
167
+ function promptKeypressSession(renderInitial, handleKey) {
168
+ const input = process.stdin;
169
+ const output = process.stdout;
170
+ const wasRaw = Boolean(input.isRaw);
171
+ let lastLineCount = 0;
172
+ let done = false;
173
+
174
+ emitKeypressEvents(input);
175
+
176
+ return new Promise((resolve, reject) => {
177
+ function cleanup() {
178
+ if (done) return;
179
+ done = true;
180
+ input.off('keypress', onKeypress);
181
+ if (typeof input.setRawMode === 'function') input.setRawMode(wasRaw);
182
+ output.write('\x1b[?25h');
183
+ input.pause();
184
+ }
185
+
186
+ function render(lines) {
187
+ const nextLines = Array.isArray(lines) ? lines : String(lines).split('\n');
188
+ if (lastLineCount > 0) output.write(`\x1b[${lastLineCount}A`);
189
+ const lineCount = Math.max(lastLineCount, nextLines.length);
190
+ for (let index = 0; index < lineCount; index++) {
191
+ const line = nextLines[index] || '';
192
+ output.write(`\x1b[2K\r${line}\n`);
193
+ }
194
+ lastLineCount = lineCount;
195
+ }
196
+
197
+ function finish(value) {
198
+ cleanup();
199
+ resolve(value);
200
+ }
201
+
202
+ function abort() {
203
+ cleanup();
204
+ reject(new PromptAbortError());
205
+ }
206
+
207
+ function onKeypress(str, key = {}) {
208
+ if (key.ctrl && key.name === 'c') {
209
+ abort();
210
+ return;
211
+ }
212
+ const next = handleKey(str, key);
213
+ if (!next) return;
214
+ if (next.abort) {
215
+ abort();
216
+ return;
217
+ }
218
+ if (next.done) {
219
+ render(next.lines);
220
+ finish(next.value);
221
+ return;
222
+ }
223
+ render(next.lines);
224
+ }
225
+
226
+ input.on('keypress', onKeypress);
227
+ input.setRawMode(true);
228
+ input.resume();
229
+ output.write('\x1b[?25l');
230
+ render(renderInitial());
231
+ });
232
+ }
233
+
234
+ function clampIndex(index, length) {
235
+ if (length <= 0) return 0;
236
+ if (index < 0) return length - 1;
237
+ if (index >= length) return 0;
238
+ return index;
239
+ }
240
+
241
+ function visibleWindow(cursor, total, maxVisible) {
242
+ const visible = Math.max(1, Math.min(total, maxVisible));
243
+ let start = Math.max(0, cursor - visible + 1);
244
+ if (cursor < start) start = cursor;
245
+ start = Math.min(start, Math.max(0, total - visible));
246
+ return { start, end: start + visible };
247
+ }
248
+
249
+ async function promptRadio(message, options, { initialIndex = 0 } = {}) {
250
+ let cursor = clampIndex(initialIndex, options.length);
251
+
252
+ const render = () => [
253
+ `${ui.accent('◆')} ${ui.bold(message)}`,
254
+ '',
255
+ ...options.map((option, index) => {
256
+ const active = index === cursor;
257
+ const pointer = active ? ui.accent('›') : ' ';
258
+ const mark = active ? ui.good('●') : ui.dim('○');
259
+ const label = active ? ui.bold(option.label) : option.label;
260
+ const hint = option.hint ? ` ${ui.dim(option.hint)}` : '';
261
+ return ` ${pointer} ${mark} ${label}${hint}`;
262
+ }),
263
+ '',
264
+ ` ${ui.dim('↑/↓ move, enter confirm')}`,
265
+ ];
266
+
267
+ return promptKeypressSession(render, (_str, key = {}) => {
268
+ if (key.name === 'up' || key.name === 'k') cursor = clampIndex(cursor - 1, options.length);
269
+ if (key.name === 'down' || key.name === 'j') cursor = clampIndex(cursor + 1, options.length);
270
+ if (key.name === 'return' || key.name === 'enter') {
271
+ return { done: true, value: options[cursor].value, lines: render() };
272
+ }
273
+ return { lines: render() };
274
+ });
275
+ }
276
+
277
+ async function promptCheckbox(message, options, { selectedValues = [] } = {}) {
278
+ const selected = new Set(selectedValues);
279
+ let cursor = 0;
280
+ let error = '';
281
+ let query = '';
282
+ const maxVisible = Math.max(5, Math.min(options.length, (process.stdout.rows || 24) - 9, 10));
283
+
284
+ function filteredOptions() {
285
+ const needle = query.trim().toLowerCase();
286
+ if (!needle) return options;
287
+ return options.filter(option => option.searchText.toLowerCase().includes(needle));
288
+ }
289
+
290
+ function selectedSummary() {
291
+ const selectedOptions = options.filter(option => selected.has(option.value));
292
+ if (selectedOptions.length === 0) return ui.dim('none');
293
+ const labels = selectedOptions.map(option => option.label);
294
+ if (labels.length <= 4) return labels.join(', ');
295
+ return `${labels.slice(0, 4).join(', ')} ${ui.dim(`+${labels.length - 4} more`)}`;
296
+ }
297
+
298
+ const render = () => {
299
+ const filtered = filteredOptions();
300
+ cursor = clampIndex(cursor, filtered.length);
301
+ const { start, end } = visibleWindow(cursor, filtered.length, maxVisible);
302
+ const lines = [
303
+ `${ui.accent('◆')} ${ui.bold(message)}`,
304
+ '',
305
+ ` Search: ${query || ui.dim('type to filter')}`,
306
+ ` ${ui.dim('↑/↓ move, space select, enter confirm')}`,
307
+ '',
308
+ ];
309
+ if (filtered.length === 0) {
310
+ lines.push(` ${ui.dim('No matches')}`);
311
+ } else if (filtered.length > maxVisible) {
312
+ lines.push(` ${ui.dim(`Showing ${start + 1}-${end} of ${filtered.length}`)}`);
313
+ }
314
+
315
+ if (filtered.length > 0) {
316
+ for (let index = start; index < end; index++) {
317
+ const option = filtered[index];
318
+ const active = index === cursor;
319
+ const pointer = active ? ui.accent('›') : ' ';
320
+ const mark = selected.has(option.value) ? ui.good('●') : ui.dim('○');
321
+ const label = active ? ui.bold(option.label) : option.label;
322
+ const hint = option.hint ? ` ${ui.dim(option.hint)}` : '';
323
+ lines.push(` ${pointer} ${mark} ${label}${hint}`);
324
+ }
325
+ }
326
+
327
+ lines.push('');
328
+ lines.push(` Selected: ${selectedSummary()}`);
329
+ if (error) lines.push(` ${error}`);
330
+ return lines;
331
+ };
332
+
333
+ return promptKeypressSession(render, (str, key = {}) => {
334
+ const filtered = filteredOptions();
335
+ if (key.name === 'up') cursor = clampIndex(cursor - 1, filtered.length);
336
+ if (key.name === 'down') cursor = clampIndex(cursor + 1, filtered.length);
337
+ if (key.name === 'space' || str === ' ') {
338
+ const option = filtered[cursor];
339
+ if (option) {
340
+ if (selected.has(option.value)) selected.delete(option.value);
341
+ else selected.add(option.value);
342
+ error = '';
343
+ }
344
+ }
345
+ if (key.name === 'backspace' || key.name === 'delete') {
346
+ query = query.slice(0, -1);
347
+ cursor = 0;
348
+ error = '';
349
+ }
350
+ if (key.ctrl && key.name === 'u') {
351
+ query = '';
352
+ cursor = 0;
353
+ error = '';
354
+ }
355
+ if (str && str.length === 1 && str >= '!' && !key.ctrl && !key.meta) {
356
+ query += str;
357
+ cursor = 0;
358
+ error = '';
359
+ }
360
+ if (key.name === 'return' || key.name === 'enter') {
361
+ if (selected.size === 0) {
362
+ error = ui.dim('Choose at least one harness.');
363
+ return { lines: render() };
364
+ }
365
+ return {
366
+ done: true,
367
+ value: options.filter(option => selected.has(option.value)).map(option => option.value),
368
+ lines: render(),
369
+ };
370
+ }
371
+ return { lines: render() };
372
+ });
45
373
  }
46
374
 
47
375
  // ─── skills help ──────────────────────────────────────────────────────────────
@@ -59,8 +387,9 @@ async function showHelp() {
59
387
  const pad = (s, n) => s + ' '.repeat(Math.max(0, n - s.length));
60
388
 
61
389
  console.log('\n Impeccable Skills & Commands\n');
62
- console.log(' Install: npx impeccable skills install');
63
- console.log(' Update: npx impeccable skills update');
390
+ console.log(' Install: npx impeccable install');
391
+ console.log(' Link: npx impeccable link --source=.impeccable');
392
+ console.log(' Update: npx impeccable update');
64
393
  console.log(' Docs: https://impeccable.style/cheatsheet\n');
65
394
  console.log(` ${pad('Command', 22)} Description`);
66
395
  console.log(` ${'-'.repeat(22)} ${'-'.repeat(52)}`);
@@ -112,15 +441,36 @@ function hashSkillsDir(skillsDir) {
112
441
  * Caller is responsible for cleanup.
113
442
  */
114
443
  async function downloadAndExtractBundle() {
444
+ const localBundle = process.env.IMPECCABLE_BUNDLE_PATH;
445
+ if (localBundle) return copyOrExtractLocalBundle(localBundle);
446
+
115
447
  const tmpZip = join(tmpdir(), `impeccable-update-${Date.now()}.zip`);
116
448
  const tmpDir = join(tmpdir(), `impeccable-update-${Date.now()}`);
117
449
  await downloadFile(`${API_BASE}/api/download/bundle/universal`, tmpZip);
118
450
  mkdirSync(tmpDir, { recursive: true });
119
- execSync(`unzip -qo "${tmpZip}" -d "${tmpDir}"`, { encoding: 'utf8' });
451
+ await extract(tmpZip, { dir: tmpDir });
120
452
  rmSync(tmpZip, { force: true });
121
453
  return tmpDir;
122
454
  }
123
455
 
456
+ async function copyOrExtractLocalBundle(sourceValue) {
457
+ const source = resolve(sourceValue);
458
+ if (!existsSync(source)) {
459
+ throw new Error(`Local bundle not found: ${source}`);
460
+ }
461
+
462
+ const tmpDir = join(tmpdir(), `impeccable-local-bundle-${process.pid}-${Date.now()}`);
463
+ mkdirSync(tmpDir, { recursive: true });
464
+
465
+ if (statSync(source).isDirectory()) {
466
+ cpSync(source, tmpDir, { recursive: true });
467
+ return tmpDir;
468
+ }
469
+
470
+ await extract(source, { dir: tmpDir });
471
+ return tmpDir;
472
+ }
473
+
124
474
  /**
125
475
  * Normalize a SKILL.md's content for comparison by stripping
126
476
  * provider-specific paths. Different install methods (npx skills add
@@ -191,7 +541,7 @@ async function check() {
191
541
 
192
542
  if (!installed) {
193
543
  console.log('Impeccable is not installed in this project.');
194
- console.log('Run `npx impeccable skills install` to install.');
544
+ console.log('Run `npx impeccable install` to install.');
195
545
  process.exit(0);
196
546
  }
197
547
 
@@ -208,7 +558,7 @@ async function check() {
208
558
  console.log(`Skills are up to date${v ? ` (v${v})` : ''}.`);
209
559
  } else {
210
560
  console.log('Updates available.');
211
- console.log('Run `npx impeccable skills update` to update.');
561
+ console.log('Run `npx impeccable update` to update.');
212
562
  }
213
563
  } catch (e) {
214
564
  console.error(`Could not check for updates: ${e.message}`);
@@ -237,31 +587,6 @@ function isAlreadyInstalled(root) {
237
587
  return null;
238
588
  }
239
589
 
240
- function escapeRegex(str) {
241
- return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
242
- }
243
-
244
- function prefixSkillContent(content, prefix, allSkillNames) {
245
- // Prefix the name in frontmatter
246
- let result = content.replace(/^name:\s*(.+)$/m, (_, name) => `name: ${prefix}${name.trim()}`);
247
-
248
- // Prefix cross-references: /skillname -> /prefix-skillname
249
- const sorted = [...allSkillNames].sort((a, b) => b.length - a.length);
250
- for (const name of sorted) {
251
- // Command invocations: /skillname
252
- result = result.replace(
253
- new RegExp(`/(?=${escapeRegex(name)}(?:[^a-zA-Z0-9_-]|$))`, 'g'),
254
- `/${prefix}`
255
- );
256
- // Prose references: "the skillname skill"
257
- result = result.replace(
258
- new RegExp(`(the) ${escapeRegex(name)} skill`, 'gi'),
259
- (_, article) => `${article} ${prefix}${name} skill`
260
- );
261
- }
262
- return result;
263
- }
264
-
265
590
  function isSkillDir(skillsDir, name) {
266
591
  // Skill entries can be real directories or symlinks to directories (npx skills uses symlinks)
267
592
  const full = join(skillsDir, name);
@@ -270,6 +595,17 @@ function isSkillDir(skillsDir, name) {
270
595
  } catch { return false; }
271
596
  }
272
597
 
598
+ function hasRealSkillEntries(skillsDir) {
599
+ if (!existsSync(skillsDir)) return false;
600
+ let entries;
601
+ try { entries = readdirSync(skillsDir); } catch { return false; }
602
+ return entries.some(name =>
603
+ !name.startsWith('.') &&
604
+ !IGNORED_SKILL_DIR_NAMES.has(name) &&
605
+ isSkillDir(skillsDir, name)
606
+ );
607
+ }
608
+
273
609
  function isRealSkillDir(skillsDir, name) {
274
610
  // Only real directories, not symlinks -- renaming the real dir renames the symlink targets too
275
611
  const full = join(skillsDir, name);
@@ -279,63 +615,164 @@ function isRealSkillDir(skillsDir, name) {
279
615
  } catch { return false; }
280
616
  }
281
617
 
282
- function renameSkillsWithPrefix(root, prefix) {
283
- // First pass: collect all skill names across all providers (use first provider found)
284
- let allSkillNames = [];
618
+ /**
619
+ * One-way migration for installs from the era when the CLI offered a command
620
+ * prefix (default `i-`), renaming the skill to e.g. `i-impeccable`. The prefix
621
+ * only earned its keep when every command was its own skill; with a single
622
+ * `impeccable` skill it does nothing, so it is no longer offered. Rename any
623
+ * prefixed impeccable skill back to the canonical `impeccable` (the fresh
624
+ * install/update content lands there next) so users aren't left with a stale,
625
+ * orphaned `i-impeccable` alongside the new one. Scoped to the impeccable skill
626
+ * by name -- never touches third-party skills that happen to start with `i-`.
627
+ * Returns the number of skills migrated.
628
+ */
629
+ function migrateUnprefixImpeccable(root) {
630
+ let migrated = 0;
285
631
  for (const d of PROVIDER_DIRS) {
286
632
  const skillsDir = join(root, d, 'skills');
287
633
  if (!existsSync(skillsDir)) continue;
288
- const entries = readdirSync(skillsDir);
289
- allSkillNames = entries.filter(name => isSkillDir(skillsDir, name));
290
- if (allSkillNames.length > 0) break;
634
+ let entries;
635
+ try { entries = readdirSync(skillsDir); } catch { continue; }
636
+ for (const name of entries) {
637
+ // A prefixed impeccable skill is `<prefix>impeccable`, not the canonical
638
+ // `impeccable` and not an unrelated legacy skill name.
639
+ if (name === 'impeccable' || name === 'teach-impeccable') continue;
640
+ if (!name.endsWith('-impeccable')) continue;
641
+ if (!isRealSkillDir(skillsDir, name)) continue;
642
+
643
+ const dest = join(skillsDir, 'impeccable');
644
+ try {
645
+ rmSync(dest, { recursive: true, force: true });
646
+ renameSync(join(skillsDir, name), dest);
647
+ migrated++;
648
+ } catch {}
649
+ }
291
650
  }
651
+ return migrated;
652
+ }
292
653
 
293
- // Second pass: rename real dirs and update their content
294
- let count = 0;
295
- for (const d of PROVIDER_DIRS) {
296
- const skillsDir = join(root, d, 'skills');
297
- if (!existsSync(skillsDir)) continue;
298
- try {
299
- const entries = readdirSync(skillsDir);
300
- for (const name of entries) {
301
- if (name.startsWith(prefix)) continue;
302
- if (!isRealSkillDir(skillsDir, name)) continue;
654
+ function getFlagValue(flags, name) {
655
+ const prefix = `${name}=`;
656
+ const inline = flags.find(f => f.startsWith(prefix));
657
+ if (inline) return inline.slice(prefix.length);
658
+ const index = flags.indexOf(name);
659
+ if (index !== -1 && flags[index + 1] && !flags[index + 1].startsWith('-')) {
660
+ return flags[index + 1];
661
+ }
662
+ return null;
663
+ }
303
664
 
304
- const src = join(skillsDir, name);
305
- const dest = join(skillsDir, prefix + name);
665
+ function normalizeProviderName(value) {
666
+ const raw = String(value || '').trim();
667
+ if (!raw) return null;
668
+ if (PROVIDER_DIRS.includes(raw)) return raw;
669
+ const key = raw.replace(/^\./, '').toLowerCase();
670
+ return PROVIDER_ALIASES[key] || null;
671
+ }
306
672
 
307
- renameSync(src, dest);
673
+ function parseProviderList(value) {
674
+ const providers = [];
675
+ const invalid = [];
676
+ for (const raw of String(value || '').split(',').map(s => s.trim()).filter(Boolean)) {
677
+ const provider = normalizeProviderName(raw);
678
+ if (!provider) {
679
+ invalid.push(raw);
680
+ continue;
681
+ }
682
+ if (!providers.includes(provider)) providers.push(provider);
683
+ }
684
+ return { providers, invalid };
685
+ }
308
686
 
309
- // Prefix frontmatter name + all cross-references in SKILL.md
310
- let content = readFileSync(join(dest, 'SKILL.md'), 'utf8');
311
- content = prefixSkillContent(content, prefix, allSkillNames);
312
- writeFileSync(join(dest, 'SKILL.md'), content);
313
- count++;
314
- }
315
- } catch {}
687
+ function providerInputName(provider) {
688
+ return PROVIDER_DISPLAY[provider]?.input || provider.replace(/^\./, '');
689
+ }
690
+
691
+ function providerDisplayName(provider) {
692
+ return PROVIDER_DISPLAY[provider]?.name || provider;
693
+ }
694
+
695
+ function formatProviderList(providers) {
696
+ return providers.map(providerInputName).join(', ');
697
+ }
698
+
699
+ function providerPromptOptions() {
700
+ return PROVIDER_INPUT_ORDER.map(input => {
701
+ const provider = normalizeProviderName(input);
702
+ const label = providerDisplayName(provider);
703
+ const hint = `(${provider}/skills)`;
704
+ return {
705
+ value: provider,
706
+ label,
707
+ hint,
708
+ searchText: `${label} ${input} ${provider} ${hint}`,
709
+ };
710
+ });
711
+ }
712
+
713
+ function formatPathForDisplay(path, home = homedir()) {
714
+ if (path === home) return '~';
715
+ if (path.startsWith(`${home}/`)) return `~/${path.slice(home.length + 1)}`;
716
+ return path;
717
+ }
718
+
719
+ function uniquePaths(paths) {
720
+ return [...new Set(paths)];
721
+ }
722
+
723
+ function userSkillProbePaths(home, harnessDir, provider) {
724
+ return uniquePaths([
725
+ join(home, provider, 'skills'),
726
+ join(home, harnessDir, 'skills'),
727
+ ]);
728
+ }
729
+
730
+ function collectInstallDetections(root, home = homedir()) {
731
+ const detections = [];
732
+ for (const provider of PROVIDER_DIRS) {
733
+ const foundPath = join(root, provider);
734
+ if (!existsSync(foundPath)) continue;
735
+ detections.push({
736
+ provider,
737
+ scope: 'project',
738
+ foundPath,
739
+ installRoot: root,
740
+ installPath: join(root, provider, 'skills'),
741
+ hasRealSkills: hasRealSkillEntries(join(root, provider, 'skills')),
742
+ reason: 'project harness folder',
743
+ });
316
744
  }
317
745
 
318
- // Third pass: fix symlinks that now point to renamed targets (npx skills uses these)
319
- for (const d of PROVIDER_DIRS) {
320
- const skillsDir = join(root, d, 'skills');
321
- if (!existsSync(skillsDir)) continue;
322
- try {
323
- const entries = readdirSync(skillsDir);
324
- for (const name of entries) {
325
- if (name.startsWith(prefix)) continue;
326
- const full = join(skillsDir, name);
327
- try {
328
- if (!lstatSync(full).isSymbolicLink()) continue;
329
- const target = readlinkSync(full);
330
- const newTarget = target.replace(new RegExp(`/${escapeRegex(name)}$`), `/${prefix}${name}`);
331
- unlinkSync(full);
332
- symlinkSync(newTarget, join(skillsDir, prefix + name));
333
- } catch {}
334
- }
335
- } catch {}
746
+ for (const { home: h, provider } of GLOBAL_HARNESS_HINTS) {
747
+ const foundPath = join(home, h);
748
+ if (!existsSync(foundPath)) continue;
749
+ const skillProbePaths = userSkillProbePaths(home, h, provider);
750
+ detections.push({
751
+ provider,
752
+ scope: 'user',
753
+ foundPath,
754
+ installRoot: home,
755
+ installPath: join(home, provider, 'skills'),
756
+ skillProbePaths,
757
+ hasRealSkills: skillProbePaths.some(hasRealSkillEntries),
758
+ reason: 'user harness folder',
759
+ });
336
760
  }
761
+ return detections;
762
+ }
337
763
 
338
- return count;
764
+ function uniqueProviders(detections) {
765
+ const providers = [];
766
+ for (const detection of detections) {
767
+ if (!providers.includes(detection.provider)) providers.push(detection.provider);
768
+ }
769
+ return providers;
770
+ }
771
+
772
+ function defaultDetectedProviders(detections) {
773
+ const projectProviders = uniqueProviders(detections.filter(d => d.scope === 'project'));
774
+ if (projectProviders.length > 0) return projectProviders;
775
+ return uniqueProviders(detections.filter(d => d.scope === 'user'));
339
776
  }
340
777
 
341
778
  /**
@@ -347,26 +784,178 @@ function renameSkillsWithPrefix(root, prefix) {
347
784
  */
348
785
  function resolveInstallTargets(root, providersValue) {
349
786
  if (providersValue) {
350
- const wanted = providersValue
351
- .split(',')
352
- .map(s => s.trim())
353
- .filter(Boolean)
354
- .map(s => (s.startsWith('.') ? s : `.${s}`))
355
- .filter(p => PROVIDER_DIRS.includes(p));
356
- return [...new Set(wanted)];
787
+ return parseProviderList(providersValue).providers;
357
788
  }
358
789
 
359
- const inProject = PROVIDER_DIRS.filter(d => existsSync(join(root, d)));
360
- if (inProject.length > 0) return inProject;
790
+ const detected = defaultDetectedProviders(collectInstallDetections(root));
791
+ if (detected.length > 0) return detected;
361
792
 
362
- const home = homedir();
363
- const inferred = [];
364
- for (const { home: h, provider } of GLOBAL_HARNESS_HINTS) {
365
- if (existsSync(join(home, h)) && !inferred.includes(provider)) inferred.push(provider);
793
+ return [...DEFAULT_TARGETS];
794
+ }
795
+
796
+ function normalizeInstallScope(value) {
797
+ const key = String(value || '').trim().toLowerCase();
798
+ if (['u', 'user', 'home', 'global'].includes(key)) return 'user';
799
+ if (['p', 'project', 'local', 'repo'].includes(key)) return 'project';
800
+ return null;
801
+ }
802
+
803
+ function getInstallScopeValue(flags) {
804
+ if (flags.includes('--user') || flags.includes('--home') || flags.includes('--global')) return 'user';
805
+ if (flags.includes('--project') || flags.includes('--local')) return 'project';
806
+ return getFlagValue(flags, '--scope') || getFlagValue(flags, '--install-scope');
807
+ }
808
+
809
+ function defaultInstallScope(detections, providers) {
810
+ const selected = new Set(providers);
811
+ if (detections.some(d => selected.has(d.provider) && d.scope === 'project')) return 'project';
812
+ if (detections.some(d => selected.has(d.provider) && d.scope === 'user' && d.hasRealSkills)) return 'user';
813
+ return 'project';
814
+ }
815
+
816
+ function installRootForScope(scope, projectRoot) {
817
+ return scope === 'user' ? homedir() : projectRoot;
818
+ }
819
+
820
+ function printInstallIntro() {
821
+ if (!isInteractivePrompt()) return;
822
+ console.log(`${ui.accent(ui.bold('impeccable'))} ${ui.dim('install')}`);
823
+ console.log('');
824
+ }
825
+
826
+ function formatInstallDetectionLines(projectRoot, detections, home = homedir(), { styled = false } = {}) {
827
+ if (detections.length === 0) {
828
+ const message = `No harnesses detected under ${formatPathForDisplay(projectRoot, home)} or ${formatPathForDisplay(home, home)}.`;
829
+ return styled
830
+ ? [`${ui.accent('◇')} ${ui.bold('Detected harnesses')}`, ` ${ui.dim(message)}`]
831
+ : [message];
366
832
  }
367
- if (inferred.length > 0) return inferred;
368
833
 
369
- return [...DEFAULT_TARGETS];
834
+ const names = detections.map(d => providerDisplayName(d.provider));
835
+ const paths = detections.map(d => formatPathForDisplay(d.foundPath, home));
836
+ const nameWidth = Math.max(...names.map(name => name.length));
837
+ const heading = styled ? `${ui.accent('◇')} ${ui.bold('Detected harnesses')}` : 'Detected harnesses:';
838
+ return [
839
+ heading,
840
+ ...detections.map((detection, index) => {
841
+ const rawName = names[index].padEnd(nameWidth);
842
+ const rawFoundPath = paths[index];
843
+ const name = styled ? ui.bold(rawName) : rawName;
844
+ const foundPath = styled ? ui.dim(rawFoundPath) : rawFoundPath;
845
+ return ` ${name} ${foundPath}`;
846
+ }),
847
+ ];
848
+ }
849
+
850
+ function printInstallDetections(projectRoot, detections) {
851
+ for (const line of formatInstallDetectionLines(projectRoot, detections, homedir(), { styled: isInteractivePrompt() })) console.log(line);
852
+ console.log('');
853
+ }
854
+
855
+ async function promptForProviders(defaultProviders = []) {
856
+ if (isInteractivePrompt()) {
857
+ return promptCheckbox('Select harnesses', providerPromptOptions(), { selectedValues: defaultProviders });
858
+ }
859
+
860
+ const choices = PROVIDER_INPUT_ORDER.join(', ');
861
+ const suffix = defaultProviders.length > 0
862
+ ? ` [blank keeps ${formatProviderList(defaultProviders)}]`
863
+ : '';
864
+ while (true) {
865
+ const answer = await ask(`Select harnesses (comma-separated: ${choices})${suffix}: `);
866
+ if (!answer && defaultProviders.length > 0) return [...defaultProviders];
867
+ const { providers, invalid } = parseProviderList(answer);
868
+ if (invalid.length > 0) {
869
+ console.log(`Unknown provider(s): ${invalid.join(', ')}`);
870
+ continue;
871
+ }
872
+ if (providers.length > 0) return providers;
873
+ console.log('Choose at least one provider.');
874
+ }
875
+ }
876
+
877
+ async function promptDetectedInstallMode(detectedProviders) {
878
+ if (isInteractivePrompt()) {
879
+ return promptRadio('Install for detected harnesses only, or add more?', [
880
+ { value: 'detected', label: 'Detected only', hint: `(${formatProviderList(detectedProviders)})` },
881
+ { value: 'add', label: 'Customize...' },
882
+ ]);
883
+ }
884
+
885
+ while (true) {
886
+ const answer = await ask(`Install target: [1] Detected only (${formatProviderList(detectedProviders)}) [2] Customize [1]: `);
887
+ if (!answer || ['1', 'detected', 'detected only', 'only', 'd'].includes(answer)) return 'detected';
888
+ if (['2', 'customize', 'customise', 'add', 'add more', 'more', 'a', 'n', 'no'].includes(answer)) return 'add';
889
+ console.log('Choose 1 for detected only, or 2 to customize.');
890
+ }
891
+ }
892
+
893
+ async function chooseInstallProviders(projectRoot, providersValue, { yes } = {}) {
894
+ const detections = collectInstallDetections(projectRoot);
895
+ if (providersValue) {
896
+ const { providers, invalid } = parseProviderList(providersValue);
897
+ if (invalid.length > 0) {
898
+ throw new Error(`Unknown provider(s): ${invalid.join(', ')}`);
899
+ }
900
+ return { targets: providers, detections, explicit: true };
901
+ }
902
+
903
+ if (yes) {
904
+ return { targets: resolveInstallTargets(projectRoot, null), detections, explicit: false };
905
+ }
906
+
907
+ printInstallDetections(projectRoot, detections);
908
+ const detectedProviders = defaultDetectedProviders(detections);
909
+ if (detectedProviders.length === 0) {
910
+ return { targets: await promptForProviders(), detections, explicit: false };
911
+ }
912
+
913
+ const mode = await promptDetectedInstallMode(detectedProviders);
914
+ if (mode === 'add') {
915
+ return { targets: await promptForProviders(detectedProviders), detections, explicit: false };
916
+ }
917
+ return { targets: detectedProviders, detections, explicit: false };
918
+ }
919
+
920
+ async function chooseInstallScope(projectRoot, targets, detections, { yes, scopeValue } = {}) {
921
+ const explicitScope = normalizeInstallScope(scopeValue);
922
+ if (scopeValue && !explicitScope) {
923
+ throw new Error(`Unknown install scope: ${scopeValue}. Use --scope=project or --scope=global.`);
924
+ }
925
+ if (explicitScope) return explicitScope;
926
+
927
+ // Preserve the old scripted behavior: `-y` installs into the current project
928
+ // unless the caller explicitly opts into `--scope=global`.
929
+ if (yes) return 'project';
930
+
931
+ const fallback = defaultInstallScope(detections, targets);
932
+ if (isInteractivePrompt()) {
933
+ return promptRadio('Install location', [
934
+ { value: 'project', label: 'Project', hint: `(${formatPathForDisplay(projectRoot)})` },
935
+ { value: 'user', label: 'Global', hint: `(${formatPathForDisplay(homedir())})` },
936
+ ], { initialIndex: fallback === 'user' ? 1 : 0 });
937
+ }
938
+
939
+ const answer = await ask(`Install location: project (${formatPathForDisplay(projectRoot)}) or global (${formatPathForDisplay(homedir())})? [${fallback === 'user' ? 'global' : fallback}] `);
940
+ if (!answer) return fallback;
941
+ const scope = normalizeInstallScope(answer);
942
+ if (!scope) {
943
+ console.log(`Unknown install location "${answer}", using ${fallback}.`);
944
+ return fallback;
945
+ }
946
+ return scope;
947
+ }
948
+
949
+ async function chooseInstallPlan(projectRoot, flags, { yes } = {}) {
950
+ const providersValue = getFlagValue(flags, '--providers');
951
+ const scopeValue = getInstallScopeValue(flags);
952
+ const { targets, detections } = await chooseInstallProviders(projectRoot, providersValue, { yes });
953
+ if (targets.length === 0) {
954
+ throw new Error('Could not determine a target harness folder.');
955
+ }
956
+ const scope = await chooseInstallScope(projectRoot, targets, detections, { yes, scopeValue });
957
+ const installRoot = installRootForScope(scope, projectRoot);
958
+ return { targets, scope, installRoot, hookRoot: projectRoot, detections };
370
959
  }
371
960
 
372
961
  /**
@@ -378,36 +967,481 @@ function copyProviderSkills(bundleDir, root, targets) {
378
967
  let written = 0;
379
968
  for (const provider of targets) {
380
969
  const srcDir = join(bundleDir, provider, 'skills');
381
- if (!existsSync(srcDir)) continue;
970
+ if (existsSync(srcDir)) {
971
+ const localSkillsDir = join(root, provider, 'skills');
972
+ // A previous `npx skills` install may have left this provider's skills dir
973
+ // as a symlink to another provider's canonical copy. Drop the link so we
974
+ // write a real, provider-specific directory instead of writing through it.
975
+ try {
976
+ if (lstatSync(localSkillsDir).isSymbolicLink()) unlinkSync(localSkillsDir);
977
+ } catch {}
978
+ for (const skill of readdirSync(srcDir, { withFileTypes: true })) {
979
+ if (!skill.isDirectory()) continue;
980
+ const src = join(srcDir, skill.name);
981
+ const dest = join(localSkillsDir, skill.name);
982
+ rmSync(dest, { recursive: true, force: true });
983
+ copyDirSync(src, dest);
984
+ written++;
985
+ }
986
+ }
987
+ }
988
+ return written;
989
+ }
990
+
991
+ function hookArtifactsForProvider(bundleDir, root, provider) {
992
+ return (PROVIDER_HOOK_ARTIFACTS[provider] || []).map(({ sourceProvider, rel, destProvider, destRel }) => {
993
+ const writeRel = destRel || rel;
994
+ const artifact = {
995
+ src: join(bundleDir, sourceProvider, rel),
996
+ dest: join(root, destProvider, writeRel),
997
+ };
998
+ // When the write target is a local override (e.g. settings.local.json), the
999
+ // team-shared sibling (settings.json) is where a legacy install or a
1000
+ // deliberate user move would put our hook. Track it so we never duplicate.
1001
+ if (writeRel !== rel) {
1002
+ artifact.sharedDest = join(root, destProvider, rel);
1003
+ }
1004
+ return artifact;
1005
+ });
1006
+ }
1007
+
1008
+ function hookScriptPathForProvider(skillRoot, provider) {
1009
+ if (provider === '.cursor') {
1010
+ return join(skillRoot, provider, 'skills', 'impeccable', 'scripts', 'hook-before-edit.mjs');
1011
+ }
1012
+ if (provider === '.claude' || provider === '.agents') {
1013
+ return join(skillRoot, provider, 'skills', 'impeccable', 'scripts', 'hook.mjs');
1014
+ }
1015
+ return null;
1016
+ }
1017
+
1018
+ function rewriteHookCommandsForSkillRoot(value, provider, skillRoot) {
1019
+ const hookScript = hookScriptPathForProvider(skillRoot, provider);
1020
+ if (!hookScript) return value;
1021
+
1022
+ if (typeof value === 'string') {
1023
+ if (valueHasImpeccableHookMarker(value)) return `node ${JSON.stringify(hookScript)}`;
1024
+ return value;
1025
+ }
1026
+ if (Array.isArray(value)) {
1027
+ return value.map(item => rewriteHookCommandsForSkillRoot(item, provider, skillRoot));
1028
+ }
1029
+ if (value && typeof value === 'object') {
1030
+ const next = {};
1031
+ for (const [key, child] of Object.entries(value)) {
1032
+ next[key] = rewriteHookCommandsForSkillRoot(child, provider, skillRoot);
1033
+ }
1034
+ return next;
1035
+ }
1036
+ return value;
1037
+ }
1038
+
1039
+ // The file paths the CLI writes hook manifests to (the local override target,
1040
+ // e.g. settings.local.json — not the shared sibling).
1041
+ function expectedHookDests(root, providers) {
1042
+ const targets = Array.isArray(providers) ? providers : [providers];
1043
+ return targets.flatMap(provider =>
1044
+ (PROVIDER_HOOK_ARTIFACTS[provider] || []).map(({ rel, destProvider, destRel }) =>
1045
+ join(root, destProvider, destRel || rel))
1046
+ );
1047
+ }
1048
+
1049
+ // Whether a hook manifest file actually wires up the Impeccable hook. We parse
1050
+ // the JSON and scan only the `hooks` subtree (via valueHasImpeccableHookMarker),
1051
+ // not the raw file text: an unrelated string elsewhere — e.g. a permissions
1052
+ // allow entry that happens to mention the hook path — must not read as a hook.
1053
+ function fileHasImpeccableHookMarker(file) {
1054
+ if (!existsSync(file)) return false;
1055
+ let parsed;
1056
+ try {
1057
+ parsed = JSON.parse(readFileSync(file, 'utf-8'));
1058
+ } catch {
1059
+ return false;
1060
+ }
1061
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return false;
1062
+ if (!parsed.hooks || typeof parsed.hooks !== 'object') return false;
1063
+ return valueHasImpeccableHookMarker(parsed.hooks);
1064
+ }
1065
+
1066
+ // Whether our hook is already wired up for a provider, used to decide if the
1067
+ // already-installed fast path should top up a missing hook. We look for the
1068
+ // Impeccable marker — not mere file existence — because the target files
1069
+ // (settings.local.json, hooks.json) commonly hold unrelated local settings; an
1070
+ // existence check would falsely report "installed" and skip repairing a missing
1071
+ // hook that `update` would otherwise add. For Claude we also honor our hook
1072
+ // living in the shared settings.json sibling (a legacy install or user move).
1073
+ function hookInstalledForProvider(root, provider) {
1074
+ const artifacts = PROVIDER_HOOK_ARTIFACTS[provider] || [];
1075
+ if (artifacts.length === 0) return true;
1076
+ return artifacts.every(({ destProvider, rel, destRel }) => {
1077
+ const writeRel = destRel || rel;
1078
+ if (fileHasImpeccableHookMarker(join(root, destProvider, writeRel))) return true;
1079
+ if (writeRel !== rel && fileHasImpeccableHookMarker(join(root, destProvider, rel))) return true;
1080
+ return false;
1081
+ });
1082
+ }
1083
+
1084
+ function valueHasImpeccableHookMarker(value) {
1085
+ if (typeof value === 'string') {
1086
+ return IMPECCABLE_HOOK_COMMAND_MARKERS.some(marker => value.includes(marker));
1087
+ }
1088
+ if (Array.isArray(value)) return value.some(valueHasImpeccableHookMarker);
1089
+ if (value && typeof value === 'object') {
1090
+ return Object.values(value).some(valueHasImpeccableHookMarker);
1091
+ }
1092
+ return false;
1093
+ }
1094
+
1095
+ function stripImpeccableHookEntry(entry) {
1096
+ if (!entry || typeof entry !== 'object') return entry;
1097
+ if (valueHasImpeccableHookMarker(entry.command) || valueHasImpeccableHookMarker(entry.args)) {
1098
+ return null;
1099
+ }
1100
+ if (!Array.isArray(entry.hooks)) return entry;
1101
+
1102
+ const strippedHooks = entry.hooks
1103
+ .map(stripImpeccableHookEntry)
1104
+ .filter(Boolean);
1105
+
1106
+ if (strippedHooks.length === 0 && entry.hooks.some(valueHasImpeccableHookMarker)) {
1107
+ return null;
1108
+ }
1109
+
1110
+ return { ...entry, hooks: strippedHooks };
1111
+ }
1112
+
1113
+ function stripImpeccableHookEntries(entries) {
1114
+ if (!Array.isArray(entries)) return [];
1115
+ return entries
1116
+ .map(stripImpeccableHookEntry)
1117
+ .filter(Boolean);
1118
+ }
1119
+
1120
+ // Remove our hook from a manifest file, preserving any unrelated content. Used
1121
+ // when the hook is honored in the shared settings.json so a stale machine-local
1122
+ // copy doesn't make the detector run twice. Drops the file if nothing but our
1123
+ // hook scaffolding remains. Returns true if it changed anything.
1124
+ function pruneImpeccableHookFromManifest(manifestPath) {
1125
+ if (!fileHasImpeccableHookMarker(manifestPath)) return false;
1126
+ let parsed;
1127
+ try {
1128
+ parsed = JSON.parse(readFileSync(manifestPath, 'utf-8'));
1129
+ } catch {
1130
+ return false;
1131
+ }
1132
+
1133
+ const existingHooks = parsed.hooks && typeof parsed.hooks === 'object' && !Array.isArray(parsed.hooks)
1134
+ ? parsed.hooks
1135
+ : {};
1136
+ const cleanedHooks = {};
1137
+ for (const [event, entries] of Object.entries(existingHooks)) {
1138
+ const kept = stripImpeccableHookEntries(entries);
1139
+ if (kept.length > 0) cleanedHooks[event] = kept;
1140
+ }
1141
+
1142
+ const next = { ...parsed };
1143
+ if (Object.keys(cleanedHooks).length > 0) {
1144
+ next.hooks = cleanedHooks;
1145
+ } else {
1146
+ // Our hook was the only thing here; drop the hook-manifest scaffolding too.
1147
+ delete next.hooks;
1148
+ delete next.description;
1149
+ delete next.version;
1150
+ }
1151
+
1152
+ if (Object.keys(next).length === 0) {
1153
+ rmSync(manifestPath, { force: true });
1154
+ } else {
1155
+ writeFileSync(manifestPath, `${JSON.stringify(next, null, 2)}\n`);
1156
+ }
1157
+ return true;
1158
+ }
1159
+
1160
+ function mergeHookManifests(existing, fresh) {
1161
+ const existingObject = existing && typeof existing === 'object' && !Array.isArray(existing) ? existing : {};
1162
+ const freshObject = fresh && typeof fresh === 'object' && !Array.isArray(fresh) ? fresh : {};
1163
+ const existingHooks = existingObject.hooks && typeof existingObject.hooks === 'object' && !Array.isArray(existingObject.hooks)
1164
+ ? existingObject.hooks
1165
+ : {};
1166
+ const freshHooks = freshObject.hooks && typeof freshObject.hooks === 'object' && !Array.isArray(freshObject.hooks)
1167
+ ? freshObject.hooks
1168
+ : {};
1169
+
1170
+ const merged = { ...existingObject, hooks: {} };
1171
+ if (freshObject.version !== undefined) merged.version = freshObject.version;
1172
+ if (freshObject.description !== undefined) merged.description = freshObject.description;
1173
+
1174
+ const hookEvents = new Set([...Object.keys(existingHooks), ...Object.keys(freshHooks)]);
1175
+ for (const event of hookEvents) {
1176
+ const preserved = stripImpeccableHookEntries(existingHooks[event]);
1177
+ const added = Array.isArray(freshHooks[event]) ? freshHooks[event] : [];
1178
+ const mergedEntries = [...preserved, ...added];
1179
+ if (mergedEntries.length > 0) merged.hooks[event] = mergedEntries;
1180
+ }
1181
+
1182
+ return merged;
1183
+ }
1184
+
1185
+ function readJsonFile(filePath, description) {
1186
+ try {
1187
+ return JSON.parse(readFileSync(filePath, 'utf-8'));
1188
+ } catch (e) {
1189
+ throw new Error(`${description} is not valid JSON: ${filePath}. ${e.message}`);
1190
+ }
1191
+ }
1192
+
1193
+ function copyProviderHooks(bundleDir, root, providers, { force = false, skillRoot = root } = {}) {
1194
+ const targets = Array.isArray(providers) ? providers : [providers];
1195
+ const written = [];
1196
+ for (const provider of targets) {
1197
+ for (const { src, dest, sharedDest } of hookArtifactsForProvider(bundleDir, root, provider)) {
1198
+ if (!existsSync(src)) continue;
1199
+
1200
+ // Leave-it-never-duplicate: our hook already lives in the team-shared
1201
+ // settings.json (a legacy install or a deliberate user move). Honor it in
1202
+ // place and skip the local write — but first strip any stale copy from the
1203
+ // local override, or Claude Code would load both and run the detector
1204
+ // twice per edit.
1205
+ if (sharedDest && fileHasImpeccableHookMarker(sharedDest)) {
1206
+ pruneImpeccableHookFromManifest(dest);
1207
+ continue;
1208
+ }
1209
+
1210
+ const freshManifest = readJsonFile(src, 'Bundled hook manifest');
1211
+ const fresh = skillRoot === root
1212
+ ? freshManifest
1213
+ : rewriteHookCommandsForSkillRoot(freshManifest, provider, skillRoot);
1214
+ let next = fresh;
1215
+
1216
+ if (existsSync(dest)) {
1217
+ try {
1218
+ const existing = JSON.parse(readFileSync(dest, 'utf-8'));
1219
+ next = mergeHookManifests(existing, fresh);
1220
+ } catch {
1221
+ if (!force) {
1222
+ throw new Error(`Existing hook manifest is not valid JSON: ${dest}. Re-run with --force to replace it.`);
1223
+ }
1224
+ writeFileSync(`${dest}.bak`, readFileSync(dest));
1225
+ next = fresh;
1226
+ }
1227
+ }
1228
+
1229
+ mkdirSync(dirname(dest), { recursive: true });
1230
+ writeFileSync(dest, `${JSON.stringify(next, null, 2)}\n`);
1231
+ written.push(provider);
1232
+ }
1233
+ }
1234
+ return [...new Set(written)];
1235
+ }
1236
+
1237
+ const HOOK_EXPLAINER = [
1238
+ '',
1239
+ 'Impeccable can install a design hook for this project. In Claude/Codex it',
1240
+ 'checks UI files after edits; in Cursor it checks proposed writes before they',
1241
+ 'land and can block writes with detector findings. It feeds results back to',
1242
+ 'your agent so design slop gets caught as you build. Change it later with',
1243
+ '/impeccable hooks on|off.',
1244
+ '',
1245
+ ].join('\n');
1246
+
1247
+ // Decide whether to install the design hook. Prompts once (default yes) the
1248
+ // first time, records the answer in .impeccable/config.local.json, and never
1249
+ // re-asks: a recorded decision or an already-installed hook short-circuits, and
1250
+ // non-interactive runs keep the historical install-by-default behavior.
1251
+ async function decideHookInstall(root, targets, { yes } = {}) {
1252
+ if (targets.length === 0) return false;
1253
+ const consent = getHookConsent(root);
1254
+ if (consent === 'declined') return false;
1255
+ if (consent === 'accepted') return true;
1256
+ // Existing hook users (hook already wired up) are never nagged.
1257
+ if (targets.length > 0 && targets.every(provider => hookInstalledForProvider(root, provider))) {
1258
+ return true;
1259
+ }
1260
+ // Undecided and not yet installed. Non-interactive (-y or no TTY) keeps the
1261
+ // historical default-on behavior without recording a (re-promptable) decision.
1262
+ if (yes || !process.stdin.isTTY) return true;
1263
+
1264
+ process.stdout.write(HOOK_EXPLAINER);
1265
+ const ans = await ask('Install the design hook? (Y/n) ');
1266
+ const accepted = !(ans === 'n' || ans === 'no');
1267
+ setHookConsent(root, accepted ? 'accepted' : 'declined');
1268
+ return accepted;
1269
+ }
1270
+
1271
+ function resolveLinkSource(sourceValue, root) {
1272
+ const sourcePath = sourceValue || '.impeccable';
1273
+ const checkoutRoot = isAbsolute(sourcePath) ? sourcePath : resolve(root, sourcePath);
1274
+ const universalRoot = join(checkoutRoot, 'dist', 'universal');
1275
+ if (existsSync(universalRoot)) {
1276
+ return { checkoutRoot, bundleRoot: universalRoot };
1277
+ }
1278
+ if (PROVIDER_DIRS.some(provider => existsSync(join(checkoutRoot, provider, 'skills')))) {
1279
+ return { checkoutRoot, bundleRoot: checkoutRoot };
1280
+ }
1281
+ throw new Error(`Could not find compiled skills in ${sourcePath}. Expected dist/universal/ or provider skill folders.`);
1282
+ }
1283
+
1284
+ function pathExistsOrLink(path) {
1285
+ try {
1286
+ lstatSync(path);
1287
+ return true;
1288
+ } catch {
1289
+ return false;
1290
+ }
1291
+ }
1292
+
1293
+ function isSymlinkTo(dest, expectedSource) {
1294
+ try {
1295
+ if (!lstatSync(dest).isSymbolicLink()) return false;
1296
+ const target = readlinkSync(dest);
1297
+ const resolvedTarget = resolve(dirname(dest), target);
1298
+ return realpathSync(resolvedTarget) === realpathSync(expectedSource);
1299
+ } catch {
1300
+ return false;
1301
+ }
1302
+ }
1303
+
1304
+ function resolveUniqueLinkTargets(root, targets) {
1305
+ const seen = new Set();
1306
+ const unique = [];
1307
+ for (const provider of targets) {
382
1308
  const localSkillsDir = join(root, provider, 'skills');
383
- // A previous `npx skills` install may have left this provider's skills dir
384
- // as a symlink to another provider's canonical copy. Drop the link so we
385
- // write a real, provider-specific directory instead of writing through it.
386
- try {
387
- if (lstatSync(localSkillsDir).isSymbolicLink()) unlinkSync(localSkillsDir);
388
- } catch {}
1309
+ mkdirSync(localSkillsDir, { recursive: true });
1310
+ const real = realpathSync(localSkillsDir);
1311
+ if (seen.has(real)) continue;
1312
+ seen.add(real);
1313
+ unique.push({ provider, localSkillsDir });
1314
+ }
1315
+ return unique;
1316
+ }
1317
+
1318
+ function linkProviderSkills(bundleRoot, root, targets, { force = false } = {}) {
1319
+ let linked = 0;
1320
+ let already = 0;
1321
+ let skipped = 0;
1322
+
1323
+ for (const { provider, localSkillsDir } of resolveUniqueLinkTargets(root, targets)) {
1324
+ const srcDir = join(bundleRoot, provider, 'skills');
1325
+ if (!existsSync(srcDir)) continue;
1326
+
389
1327
  for (const skill of readdirSync(srcDir, { withFileTypes: true })) {
390
1328
  if (!skill.isDirectory()) continue;
391
1329
  const src = join(srcDir, skill.name);
392
1330
  const dest = join(localSkillsDir, skill.name);
393
- rmSync(dest, { recursive: true, force: true });
394
- copyDirSync(src, dest);
395
- written++;
1331
+
1332
+ if (pathExistsOrLink(dest)) {
1333
+ if (isSymlinkTo(dest, src)) {
1334
+ already++;
1335
+ continue;
1336
+ }
1337
+ if (!force) {
1338
+ console.warn(`Skipped existing ${provider}/skills/${skill.name}. Use --force to replace it with a link.`);
1339
+ skipped++;
1340
+ continue;
1341
+ }
1342
+ rmSync(dest, { recursive: true, force: true });
1343
+ }
1344
+
1345
+ const target = relative(dirname(dest), src) || '.';
1346
+ symlinkSync(target, dest, 'dir');
1347
+ linked++;
396
1348
  }
397
1349
  }
398
- return written;
1350
+
1351
+ return { linked, already, skipped };
399
1352
  }
400
1353
 
401
- async function install(flags) {
1354
+ async function link(flags) {
402
1355
  const force = flags.includes('--force');
403
1356
  const yes = flags.includes('-y') || flags.includes('--yes');
404
- const prefixFlag = flags.find(f => f.startsWith('--prefix='));
405
- const providersFlag = flags.find(f => f.startsWith('--providers='));
1357
+ const sourceValue = getFlagValue(flags, '--source');
1358
+ const providersValue = getFlagValue(flags, '--providers');
406
1359
  const root = findProjectRoot();
407
- const existing = isAlreadyInstalled(root);
1360
+
1361
+ let source;
1362
+ try {
1363
+ source = resolveLinkSource(sourceValue, root);
1364
+ } catch (e) {
1365
+ console.error(e.message);
1366
+ process.exit(1);
1367
+ }
1368
+
1369
+ const targets = resolveInstallTargets(root, providersValue);
1370
+ if (targets.length === 0) {
1371
+ console.error('Could not determine a target harness folder.');
1372
+ console.error('Pass one explicitly, e.g. --providers=claude,cursor');
1373
+ process.exit(1);
1374
+ }
1375
+
1376
+ if (!yes) {
1377
+ console.log(`Source checkout: ${source.checkoutRoot}`);
1378
+ console.log(`Target harness folder(s): ${targets.join(', ')}`);
1379
+ const ans = await ask(`Link impeccable skills into ${targets.length} folder(s)? (Y/n) `);
1380
+ if (ans === 'n' || ans === 'no') {
1381
+ console.log('Aborted. Re-run with --providers=<names> to choose explicitly (e.g. --providers=claude,cursor).');
1382
+ process.exit(0);
1383
+ }
1384
+ }
1385
+
1386
+ const result = linkProviderSkills(source.bundleRoot, root, targets, { force });
1387
+ if (result.linked === 0 && result.already === 0) {
1388
+ if (result.skipped > 0) {
1389
+ console.error('Nothing was linked because matching skill folders already exist.');
1390
+ console.error('Existing skills were left untouched. Re-run with --force to replace them with links.');
1391
+ } else {
1392
+ console.error(`Nothing was linked: ${source.bundleRoot} had no variants for ${targets.join(', ')}.`);
1393
+ }
1394
+ process.exit(1);
1395
+ }
1396
+
1397
+ const parts = [];
1398
+ if (result.linked > 0) parts.push(`${result.linked} linked`);
1399
+ if (result.already > 0) parts.push(`${result.already} already linked`);
1400
+ if (result.skipped > 0) parts.push(`${result.skipped} skipped`);
1401
+ console.log(`Linked impeccable into: ${targets.join(', ')} (${parts.join(', ')}).`);
1402
+ console.log('Update with `git submodule update --remote` from your project root, then rerun this command if new skills are added.\n');
1403
+ }
1404
+
1405
+ async function install(flags) {
1406
+ const force = flags.includes('--force');
1407
+ const yes = flags.includes('-y') || flags.includes('--yes');
1408
+ const installHooks = !flags.includes('--no-hooks');
1409
+ const projectRoot = findProjectRoot();
1410
+ if (!yes) printInstallIntro();
1411
+ let plan;
1412
+ try {
1413
+ plan = await chooseInstallPlan(projectRoot, flags, { yes });
1414
+ } catch (e) {
1415
+ if (isPromptAbortError(e)) throw e;
1416
+ console.error(e.message);
1417
+ console.error('Pass providers explicitly, e.g. --providers=claude,cursor');
1418
+ process.exit(1);
1419
+ }
1420
+
1421
+ const { targets, installRoot, hookRoot, scope } = plan;
1422
+ const existing = isAlreadyInstalled(installRoot);
408
1423
 
409
1424
  if (existing && !force) {
410
1425
  console.log(`Impeccable skills are already installed (found in ${existing}/).`);
1426
+ const installedTargets = findInstalledProviders(installRoot);
1427
+ const hookTargets = targets.filter(provider => installedTargets.includes(provider));
1428
+ const wantHooks = installHooks && await decideHookInstall(hookRoot, hookTargets, { yes });
1429
+ const missingHookTargets = wantHooks
1430
+ ? hookTargets.filter(provider => !hookInstalledForProvider(hookRoot, provider))
1431
+ : [];
1432
+ if (missingHookTargets.length > 0) {
1433
+ let bundleDir;
1434
+ try {
1435
+ bundleDir = await downloadAndExtractBundle();
1436
+ const writtenHookTargets = copyProviderHooks(bundleDir, hookRoot, missingHookTargets, { skillRoot: installRoot });
1437
+ if (writtenHookTargets.length > 0) console.log(`Installed hooks into: ${writtenHookTargets.join(', ')}`);
1438
+ } catch (e) {
1439
+ console.error(`Hook install failed: ${e.message}`);
1440
+ process.exit(1);
1441
+ } finally {
1442
+ if (bundleDir) rmSync(bundleDir, { recursive: true, force: true });
1443
+ }
1444
+ }
411
1445
  console.log('Run with --force to reinstall.\n');
412
1446
  process.exit(0);
413
1447
  }
@@ -417,21 +1451,13 @@ async function install(flags) {
417
1451
  // to `npx skills add`: its name-based discovery can install the uncompiled
418
1452
  // source, and its symlink default points every harness at one shared variant.
419
1453
  // Copying per-provider variants is the only correct install for this skill.
420
- const targets = resolveInstallTargets(root, providersFlag ? providersFlag.split('=')[1] : null);
421
1454
  if (targets.length === 0) {
422
1455
  console.error('Could not determine a target harness folder.');
423
1456
  console.error('Pass one explicitly, e.g. --providers=.claude,.cursor');
424
1457
  process.exit(1);
425
1458
  }
426
1459
 
427
- if (!yes) {
428
- console.log(`Target harness folder(s): ${targets.join(', ')}`);
429
- const ans = await ask(`Install impeccable skills into ${targets.length} folder(s)? (Y/n) `);
430
- if (ans === 'n' || ans === 'no') {
431
- console.log('Aborted. Re-run with --providers=<dirs> to choose explicitly (e.g. --providers=.claude,.cursor).');
432
- process.exit(0);
433
- }
434
- }
1460
+ const wantHooks = installHooks && await decideHookInstall(hookRoot, targets, { yes });
435
1461
 
436
1462
  console.log('\nDownloading impeccable skills...');
437
1463
  let bundleDir;
@@ -442,9 +1468,15 @@ async function install(flags) {
442
1468
  process.exit(1);
443
1469
  }
444
1470
 
1471
+ // Retire any old `i-`-prefixed install so the fresh copy lands on the
1472
+ // canonical `impeccable` dir instead of orphaning the prefixed one.
1473
+ migrateUnprefixImpeccable(installRoot);
1474
+
445
1475
  let written = 0;
1476
+ let hookTargets = [];
446
1477
  try {
447
- written = copyProviderSkills(bundleDir, root, targets);
1478
+ written = copyProviderSkills(bundleDir, installRoot, targets);
1479
+ hookTargets = wantHooks ? copyProviderHooks(bundleDir, hookRoot, targets, { force, skillRoot: installRoot }) : [];
448
1480
  } catch (e) {
449
1481
  rmSync(bundleDir, { recursive: true, force: true });
450
1482
  console.error(`Install failed: ${e.message}`);
@@ -456,106 +1488,10 @@ async function install(flags) {
456
1488
  console.error(`Nothing was installed: the bundle had no variants for ${targets.join(', ')}.`);
457
1489
  process.exit(1);
458
1490
  }
459
- console.log(`Installed impeccable into: ${targets.join(', ')}`);
460
-
461
- // Ask about prefixing (skip in CI mode unless --prefix= is set)
462
- let prefix = '';
463
- if (prefixFlag) {
464
- prefix = prefixFlag.split('=')[1] || 'i-';
465
- } else if (!yes) {
466
- console.log();
467
- const wantPrefix = await ask('Prefix commands to avoid conflicts? e.g. /i-audit instead of /audit (y/N) ');
468
- if (wantPrefix === 'y' || wantPrefix === 'yes') {
469
- const custom = await ask('Prefix (default: i-): ');
470
- prefix = custom || 'i-';
471
- }
472
- }
473
-
474
- if (prefix) {
475
- const count = renameSkillsWithPrefix(root, prefix);
476
- if (count > 0) {
477
- console.log(`\nRenamed ${count} skills with "${prefix}" prefix.`);
478
- console.log(`Commands are now available as /${prefix}<command> (e.g. /${prefix}audit).`);
479
- }
480
- }
481
-
482
- // Clean up deprecated skills from previous versions
483
- try {
484
- const { cleanup } = await import('../../../skill/scripts/cleanup-deprecated.mjs');
485
- const result = cleanup(root);
486
- const total = result.deletedPaths.length + result.removedLockEntries.length;
487
- if (total > 0) {
488
- console.log(`Cleaned up ${total} deprecated skill(s) from previous versions.`);
489
- }
490
- } catch {
491
- // Cleanup script not available -- skip
492
- }
493
-
494
- console.log(`\nDone! Run /${prefix}impeccable init in your AI harness to set up design context.\n`);
495
- }
496
-
497
- /** Detect prefix by looking for the 'impeccable' skill (or legacy 'teach-impeccable') */
498
- function detectPrefix(root) {
499
- for (const d of PROVIDER_DIRS) {
500
- const skillsDir = join(root, d, 'skills');
501
- if (!existsSync(skillsDir)) continue;
502
- for (const name of readdirSync(skillsDir)) {
503
- if (name === 'impeccable') return '';
504
- if (name.endsWith('-impeccable') && name !== 'teach-impeccable') return name.slice(0, -'impeccable'.length);
505
- // Legacy fallback
506
- if (name === 'teach-impeccable') return '';
507
- if (name.endsWith('-teach-impeccable')) return name.slice(0, -'teach-impeccable'.length);
508
- }
509
- }
510
- return '';
511
- }
1491
+ console.log(`Installed impeccable into: ${targets.join(', ')} (${scope === 'user' ? 'global' : 'project'})`);
1492
+ if (hookTargets.length > 0) console.log(`Installed hooks into: ${hookTargets.join(', ')}`);
512
1493
 
513
- /** Undo prefixing: rename folders back and strip prefix from SKILL.md content */
514
- function undoPrefix(root, prefix) {
515
- if (!prefix) return;
516
- // Collect the unprefixed names (strip our prefix)
517
- let allPrefixedNames = [];
518
- for (const d of PROVIDER_DIRS) {
519
- const skillsDir = join(root, d, 'skills');
520
- if (!existsSync(skillsDir)) continue;
521
- allPrefixedNames = readdirSync(skillsDir).filter(n => n.startsWith(prefix) && isRealSkillDir(skillsDir, n));
522
- if (allPrefixedNames.length > 0) break;
523
- }
524
- const unprefixedNames = allPrefixedNames.map(n => n.slice(prefix.length));
525
-
526
- for (const d of PROVIDER_DIRS) {
527
- const skillsDir = join(root, d, 'skills');
528
- if (!existsSync(skillsDir)) continue;
529
- for (const name of readdirSync(skillsDir)) {
530
- if (!name.startsWith(prefix)) continue;
531
- const unprefixed = name.slice(prefix.length);
532
- const src = join(skillsDir, name);
533
- const dest = join(skillsDir, unprefixed);
534
-
535
- if (lstatSync(src).isSymbolicLink()) {
536
- const target = readlinkSync(src);
537
- const newTarget = target.replace(`/${name}`, `/${unprefixed}`);
538
- unlinkSync(src);
539
- symlinkSync(newTarget, dest);
540
- } else {
541
- renameSync(src, dest);
542
- // Strip prefix from SKILL.md content
543
- const skillMd = join(dest, 'SKILL.md');
544
- if (existsSync(skillMd)) {
545
- let content = readFileSync(skillMd, 'utf8');
546
- // Reverse the prefixing: replace prefixed names with unprefixed
547
- content = content.replace(new RegExp(`^name:\\s*${escapeRegex(prefix)}`, 'm'), 'name: ');
548
- const sorted = [...allPrefixedNames].sort((a, b) => b.length - a.length);
549
- for (const pName of sorted) {
550
- const uName = pName.slice(prefix.length);
551
- content = content.replace(new RegExp(`/${escapeRegex(pName)}(?=[^a-zA-Z0-9_-]|$)`, 'g'), `/${uName}`);
552
- content = content.replace(new RegExp(`(the) ${escapeRegex(pName)} skill`, 'gi'), `$1 ${uName} skill`);
553
- }
554
- writeFileSync(skillMd, content);
555
- }
556
- }
557
- }
558
- }
1494
+ console.log('\nDone! Run /impeccable init in your AI harness to set up design context.\n');
559
1495
  }
560
1496
 
561
1497
  // ─── skills update ────────────────────────────────────────────────────────────
@@ -582,6 +1518,17 @@ function findInstalledProviders(root) {
582
1518
  return found;
583
1519
  }
584
1520
 
1521
+ function findLinkedProviders(root, providers) {
1522
+ return providers.filter(provider => {
1523
+ const skillDir = join(root, provider, 'skills', 'impeccable');
1524
+ try {
1525
+ return lstatSync(skillDir).isSymbolicLink();
1526
+ } catch {
1527
+ return false;
1528
+ }
1529
+ });
1530
+ }
1531
+
585
1532
  function getModifiedSkillFiles(root, providerDirs) {
586
1533
  // Use git to check if any skill files have local modifications
587
1534
  const modified = [];
@@ -627,32 +1574,30 @@ function downloadFile(url, dest) {
627
1574
 
628
1575
  async function update(flags = []) {
629
1576
  const yes = flags.includes('-y') || flags.includes('--yes');
630
-
631
- // Clean up deprecated skills from previous versions.
632
- try {
633
- const { cleanup } = await import('../../../skill/scripts/cleanup-deprecated.mjs');
634
- const root = findProjectRoot();
635
- const result = cleanup(root);
636
- const total = result.deletedPaths.length + result.removedLockEntries.length;
637
- if (total > 0) {
638
- console.log(`Cleaned up ${total} deprecated skill(s) from previous versions.\n`);
639
- }
640
- } catch {
641
- // Cleanup script not available (e.g. running from npm package) -- skip
642
- }
1577
+ const force = flags.includes('--force');
1578
+ const installHooks = !flags.includes('--no-hooks');
643
1579
 
644
1580
  // Download the latest skills directly from impeccable.style.
645
1581
  // We skip `npx skills update` because it has a known upstream bug
646
1582
  // (vercel-labs/skills#775) where it can't find the lock file.
647
1583
  const root = findProjectRoot();
648
1584
  const providers = findInstalledProviders(root);
1585
+ const linkedProviders = findLinkedProviders(root, providers);
1586
+ const copyProviders = providers.filter(provider => !linkedProviders.includes(provider));
649
1587
 
650
1588
  if (providers.length === 0) {
651
1589
  console.log('No impeccable skill folders found in this project.');
652
- console.log('Run `npx impeccable skills install` to install first.');
1590
+ console.log('Run `npx impeccable install` to install first.');
653
1591
  process.exit(1);
654
1592
  }
655
1593
 
1594
+ if (linkedProviders.length > 0) {
1595
+ console.log(`Linked skills found in: ${linkedProviders.join(', ')}`);
1596
+ console.log('Update the source checkout with `git submodule update --remote`, then rerun `npx impeccable link --source=.impeccable` if new skills are added.');
1597
+ if (copyProviders.length === 0) process.exit(0);
1598
+ console.log(`Continuing with copied installs in: ${copyProviders.join(', ')}\n`);
1599
+ }
1600
+
656
1601
  console.log('Checking for updates...');
657
1602
 
658
1603
  let tmpDir;
@@ -664,17 +1609,27 @@ async function update(flags = []) {
664
1609
  }
665
1610
 
666
1611
  // Compare local vs remote -- skip if already up to date
667
- if (isUpToDate(root, providers, tmpDir)) {
668
- rmSync(tmpDir, { recursive: true, force: true });
669
- const v = getSkillsVersion(root);
670
- console.log(`Skills are up to date${v ? ` (v${v})` : ''}. Nothing to do.`);
671
- process.exit(0);
1612
+ if (isUpToDate(root, copyProviders, tmpDir)) {
1613
+ try {
1614
+ const wantHooks = installHooks && await decideHookInstall(root, copyProviders, { yes });
1615
+ const hookTargets = wantHooks ? copyProviderHooks(tmpDir, root, copyProviders, { force }) : [];
1616
+ rmSync(tmpDir, { recursive: true, force: true });
1617
+ const v = getSkillsVersion(root);
1618
+ console.log(`Skills are up to date${v ? ` (v${v})` : ''}.`);
1619
+ if (hookTargets.length > 0) console.log(`Installed hooks into: ${hookTargets.join(', ')}`);
1620
+ console.log('Nothing else to do.');
1621
+ process.exit(0);
1622
+ } catch (e) {
1623
+ rmSync(tmpDir, { recursive: true, force: true });
1624
+ console.error(`Update failed: ${e.message}`);
1625
+ process.exit(1);
1626
+ }
672
1627
  }
673
1628
 
674
- console.log(`Found skills in: ${providers.join(', ')}`);
1629
+ console.log(`Found skills in: ${copyProviders.join(', ')}`);
675
1630
 
676
1631
  if (!yes) {
677
- const ans = await ask(`Update skills in ${providers.length} provider folder(s)? (Y/n) `);
1632
+ const ans = await ask(`Update skills in ${copyProviders.length} provider folder(s)? (Y/n) `);
678
1633
  if (ans === 'n' || ans === 'no') {
679
1634
  rmSync(tmpDir, { recursive: true, force: true });
680
1635
  console.log('Aborted.');
@@ -684,10 +1639,15 @@ async function update(flags = []) {
684
1639
 
685
1640
  try {
686
1641
 
1642
+ // Retire any old `i-`-prefixed install up front so the refresh lands on the
1643
+ // canonical `impeccable` dir rather than orphaning the prefixed copy.
1644
+ const migrated = migrateUnprefixImpeccable(root);
1645
+ if (migrated > 0) console.log('Migrated a prefixed install back to /impeccable (the i- prefix is no longer used).');
1646
+
687
1647
  // Copy from the bundle to each unique provider folder.
688
1648
  // Deduplicate so symlinked dirs (e.g. .claude/skills -> .agents/skills)
689
1649
  // are only written once with the correct provider's content.
690
- const unique = deduplicateProviders(root, providers);
1650
+ const unique = deduplicateProviders(root, copyProviders);
691
1651
  let updated = 0;
692
1652
  for (const { provider, localSkillsDir } of unique) {
693
1653
  const srcDir = join(tmpDir, provider, 'skills');
@@ -703,26 +1663,14 @@ async function update(flags = []) {
703
1663
  updated++;
704
1664
  }
705
1665
  }
1666
+ const wantHooks = installHooks && await decideHookInstall(root, providers, { yes });
1667
+ const hookTargets = wantHooks ? copyProviderHooks(tmpDir, root, providers, { force }) : [];
706
1668
 
707
1669
  rmSync(tmpDir, { recursive: true, force: true });
708
1670
 
709
- // Re-apply prefix if detected
710
- const prefix = detectPrefix(root);
711
- if (prefix) {
712
- const count = renameSkillsWithPrefix(root, prefix);
713
- if (count > 0) console.log(`Re-applied "${prefix}" prefix to ${count} skills.`);
714
- }
715
-
716
- // Run cleanup to remove deprecated stubs from the fresh download
717
- try {
718
- const { cleanup: postCleanup } = await import('../../../skill/scripts/cleanup-deprecated.mjs');
719
- postCleanup(root);
720
- } catch {
721
- // Not available -- skip
722
- }
723
-
724
1671
  const v = getSkillsVersion(root);
725
1672
  console.log(`Updated ${updated} skill(s)${v ? ` to v${v}` : ''}.`);
1673
+ if (hookTargets.length > 0) console.log(`Installed hooks into: ${hookTargets.join(', ')}`);
726
1674
  console.log('Done!\n');
727
1675
  } catch (e) {
728
1676
  console.error(`Update failed: ${e.message}`);
@@ -744,6 +1692,23 @@ function copyDirSync(src, dest) {
744
1692
  }
745
1693
  }
746
1694
 
1695
+ // ─── Test surface ───────────────────────────────────────────────────────────
1696
+ // Exported so the test suite exercises the real implementation rather than a
1697
+ // reimplementation in a helper script (which is how bugs slip through).
1698
+ export {
1699
+ collectInstallDetections,
1700
+ copyProviderHooks,
1701
+ copyProviderSkills,
1702
+ decideHookInstall,
1703
+ expectedHookDests,
1704
+ formatInstallDetectionLines,
1705
+ linkProviderSkills,
1706
+ mergeHookManifests,
1707
+ migrateUnprefixImpeccable,
1708
+ resolveInstallTargets,
1709
+ resolveLinkSource,
1710
+ };
1711
+
747
1712
  // ─── Router ───────────────────────────────────────────────────────────────────
748
1713
 
749
1714
  export async function run(args) {
@@ -753,13 +1718,15 @@ export async function run(args) {
753
1718
  await showHelp();
754
1719
  } else if (sub === 'install') {
755
1720
  await install(args.slice(1));
1721
+ } else if (sub === 'link') {
1722
+ await link(args.slice(1));
756
1723
  } else if (sub === 'update') {
757
1724
  await update(args.slice(1));
758
1725
  } else if (sub === 'check') {
759
1726
  await check();
760
1727
  } else {
761
1728
  console.error(`Unknown skills command: ${sub}`);
762
- console.error(`Run 'impeccable skills --help' for available commands.`);
1729
+ console.error(`Run 'impeccable --help' for available commands.`);
763
1730
  process.exit(1);
764
1731
  }
765
1732
  }