impeccable 3.6.0 → 4.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.
@@ -1,2337 +0,0 @@
1
- /**
2
- * `impeccable skills` subcommand
3
- *
4
- * Usage:
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
9
- */
10
-
11
- import { execSync } from 'node:child_process';
12
- import { existsSync, readFileSync, readdirSync, statSync, lstatSync, unlinkSync, mkdirSync, writeFileSync, rmSync, rmdirSync, renameSync, createWriteStream, realpathSync, symlinkSync, readlinkSync, cpSync } from 'node:fs';
13
- import { join, resolve, dirname, relative, isAbsolute, sep } from 'node:path';
14
- import { createInterface, emitKeypressEvents } from 'node:readline';
15
- import { fileURLToPath } from 'node:url';
16
- import { get } from 'node:https';
17
- import { createHash } from 'node:crypto';
18
- import { tmpdir, homedir } from 'node:os';
19
- import { unzipSync } from 'fflate';
20
- import { getHookConsent, setHookConsent } from '../../lib/impeccable-config.mjs';
21
-
22
- const __dirname = dirname(fileURLToPath(import.meta.url));
23
- const API_BASE = 'https://impeccable.style';
24
-
25
- // Provider folder names in project roots
26
- const PROVIDER_DIRS = ['.claude', '.cursor', '.gemini', '.agents', '.agent', '.github', '.grok', '.hermes', '.kiro', '.opencode', '.pi', '.qoder', '.trae', '.trae-cn', '.rovodev', '.vibe'];
27
- const PROVIDER_ALIASES = {
28
- agent: '.agent',
29
- agents: '.agents',
30
- antigravity: '.agent',
31
- claude: '.claude',
32
- 'claude-code': '.claude',
33
- codex: '.agents',
34
- copilot: '.github',
35
- cursor: '.cursor',
36
- gemini: '.gemini',
37
- github: '.github',
38
- grok: '.grok',
39
- 'grok-build': '.grok',
40
- hermes: '.hermes',
41
- xai: '.grok',
42
- kiro: '.kiro',
43
- opencode: '.opencode',
44
- pi: '.pi',
45
- qoder: '.qoder',
46
- 'rovo-dev': '.rovodev',
47
- rovodev: '.rovodev',
48
- trae: '.trae',
49
- 'trae-cn': '.trae-cn',
50
- vibe: '.vibe',
51
- };
52
-
53
- const PROVIDER_DISPLAY = {
54
- '.agent': { name: 'Antigravity', input: 'antigravity' },
55
- '.agents': { name: 'Codex CLI', input: 'codex' },
56
- '.claude': { name: 'Claude Code', input: 'claude' },
57
- '.cursor': { name: 'Cursor', input: 'cursor' },
58
- '.gemini': { name: 'Gemini CLI', input: 'gemini' },
59
- '.github': { name: 'GitHub Copilot', input: 'github' },
60
- '.grok': { name: 'Grok Build', input: 'grok' },
61
- '.hermes': { name: 'Hermes Agent', input: 'hermes' },
62
- '.kiro': { name: 'Kiro', input: 'kiro' },
63
- '.opencode': { name: 'OpenCode', input: 'opencode' },
64
- '.pi': { name: 'Pi Coding Agent', input: 'pi' },
65
- '.qoder': { name: 'Qoder', input: 'qoder' },
66
- '.rovodev': { name: 'Rovo Dev', input: 'rovo-dev' },
67
- '.trae': { name: 'Trae', input: 'trae' },
68
- '.trae-cn': { name: 'Trae CN', input: 'trae-cn' },
69
- '.vibe': { name: 'Mistral Vibe', input: 'vibe' },
70
- };
71
- const PROVIDER_INPUT_ORDER = ['antigravity', 'claude', 'codex', 'cursor', 'gemini', 'github', 'grok', 'hermes', 'kiro', 'opencode', 'pi', 'qoder', 'trae', 'trae-cn', 'rovo-dev', 'vibe'];
72
-
73
- // OpenCode reads global skills from its config directory, not ~/.opencode:
74
- // $OPENCODE_CONFIG_DIR, else $XDG_CONFIG_HOME/opencode, else
75
- // ~/.config/opencode. Writing to ~/.opencode/skills produced an install
76
- // `opencode debug skill` never listed. See issue #406.
77
- function opencodeGlobalConfigDir(home) {
78
- if (process.env.OPENCODE_CONFIG_DIR) return process.env.OPENCODE_CONFIG_DIR;
79
- if (process.env.XDG_CONFIG_HOME) return join(process.env.XDG_CONFIG_HOME, 'opencode');
80
- return join(home, '.config', 'opencode');
81
- }
82
-
83
- // Hermes reads skills from `$HERMES_HOME/skills/`, where $HERMES_HOME defaults
84
- // to `~/.hermes` but is also set to a profile path (e.g.
85
- // `~/.hermes/profiles/forge`) when a non-default profile is active. Reading
86
- // the env var matters here at install time: writing to `~/.hermes/skills/`
87
- // from a profile-scoped Hermes invocation would land in the wrong profile
88
- // (the same cross-profile data-corruption class that the active_profile
89
- // fallback warning in hermes_constants.py exists to detect). Used by
90
- // HOME_SKILLS_DIR_OVERRIDES['.hermes'] only; GLOBAL_HARNESS_HINTS reads the
91
- // fixed `~/.hermes` location so detection doesn't leak the developer's real
92
- // HERMES_HOME into test output (test isolation).
93
- //
94
- // Ignore $HERMES_HOME when it doesn't sit under `home` (the caller-supplied
95
- // home dir, which tests inject via HOME=/tmp/...). Without this guard, an
96
- // inherited $HERMES_HOME=/home/<dev>/.hermes from the developer's shell leaks
97
- // into test output even when the test sets HOME=/tmp/imp-home-xxx: tests
98
- // expect ~/.hermes to live under their tmp home, not under the dev's real
99
- // home. The check uses `resolve()` on both sides so a symlinked test home
100
- // (e.g. /tmp -> /private/tmp on macOS) still compares correctly.
101
- function hermesGlobalHome(home) {
102
- const envHome = process.env.HERMES_HOME;
103
- if (envHome) {
104
- try {
105
- const resolvedEnv = resolve(envHome);
106
- const resolvedHome = resolve(home);
107
- // Honor HERMES_HOME only when it lives under the active home (real
108
- // ~/.hermes or ~/.hermes/profiles/<name>). Cross-home inheritance is
109
- // treated as not-set, so a test running under HOME=/tmp/... doesn't
110
- // pick up the developer's real ~/.hermes.
111
- if (resolvedEnv === resolvedHome || resolvedEnv.startsWith(resolvedHome + sep)) {
112
- return resolvedEnv;
113
- }
114
- } catch {
115
- // fall through to default
116
- }
117
- }
118
- return join(home, '.hermes');
119
- }
120
-
121
- // Providers whose GLOBAL (home) skills dir is not `<provider>/skills`,
122
- // as a function of the home dir. Pi discovers global skills from
123
- // ~/.pi/agent/skills/ (issue #327); OpenCode from its config dir (issue
124
- // #406); Hermes from $HERMES_HOME. Project scope stays `<provider>/skills`
125
- // for all three.
126
- const HOME_SKILLS_DIR_OVERRIDES = {
127
- '.agent': (home) => join(home, '.gemini', 'config', 'skills'),
128
- '.hermes': (home) => join(hermesGlobalHome(home), 'skills'),
129
- '.pi': (home) => join(home, '.pi', 'agent', 'skills'),
130
- '.opencode': (home) => join(opencodeGlobalConfigDir(home), 'skills'),
131
- };
132
-
133
- // When a project has no harness folder yet, infer the target from globally
134
- // installed harnesses (~/.claude, ~/.codex, ...). Codex reads skills from
135
- // .agents/skills, so ~/.codex maps to the .agents bundle variant.
136
- //
137
- // Hermes auto-detection uses the fixed `~/.hermes` location only. When a
138
- // non-default Hermes profile is active (HERMES_HOME points to a profile path),
139
- // the user is expected to be inside a Hermes invocation and can pass
140
- // --providers=hermes explicitly. Auto-detection from a non-default HERMES_HOME
141
- // would also defeat test isolation (tests inject HOME; HERMES_HOME leaks from
142
- // the parent process and would surface the developer's real ~/.hermes in
143
- // detection output). The install path honors $HERMES_HOME; detection does not.
144
- const GLOBAL_HARNESS_HINTS = [
145
- { home: '.agent', provider: '.agent' },
146
- // Antigravity nests under ~/.gemini/ too, so any of these also trips the
147
- // .gemini hint above (harmless double-detection — both get pre-selected).
148
- { home: '.gemini/antigravity', provider: '.agent' },
149
- { home: '.gemini/antigravity-cli', provider: '.agent' },
150
- { home: '.gemini/antigravity-ide', provider: '.agent' },
151
- { home: '.claude', provider: '.claude' },
152
- { home: '.codex', provider: '.agents' },
153
- { home: '.cursor', provider: '.cursor' },
154
- { home: '.gemini', provider: '.gemini' },
155
- { home: '.grok', provider: '.grok' },
156
- { home: '.hermes', provider: '.hermes' },
157
- { home: '.kiro', provider: '.kiro' },
158
- { home: '.opencode', provider: '.opencode' },
159
- // OpenCode's real global config dir (issue #406); the ~/.opencode entry
160
- // above keeps recognizing machines that only have the legacy dir.
161
- { resolve: opencodeGlobalConfigDir, provider: '.opencode' },
162
- { home: '.pi', provider: '.pi' },
163
- { home: '.qoder', provider: '.qoder' },
164
- { home: '.rovodev', provider: '.rovodev' },
165
- { home: '.vibe', provider: '.vibe' },
166
- ];
167
-
168
- // Last-resort default when nothing is detected: Claude Code + the universal
169
- // (.agents, also Codex) folder, which covers the most common setups.
170
- const DEFAULT_TARGETS = ['.claude', '.agents'];
171
- const IGNORED_SKILL_DIR_NAMES = new Set([
172
- 'codex-primary-runtime',
173
- ]);
174
- const IMPECCABLE_HOOK_COMMAND_MARKERS = [
175
- 'skills/impeccable/scripts/hook-probe.mjs',
176
- 'skills/impeccable/scripts/hook.mjs',
177
- 'skills/impeccable/scripts/hook-before-edit.mjs',
178
- 'skills/impeccable/scripts/hook-after-edit.mjs',
179
- 'skills/impeccable/scripts/hook-stop.mjs',
180
- ];
181
- const PROVIDER_HOOK_ARTIFACTS = {
182
- '.claude': [
183
- // The hook is a machine-local install side effect, so it lands in the
184
- // gitignored `.claude/settings.local.json` rather than the team-shared
185
- // `settings.json`. The bundle still ships the manifest as `settings.json`
186
- // (the `rel` source), but we write it to `destRel`. A hook the user moved
187
- // into `settings.json` is honored in place; see copyProviderHooks.
188
- { sourceProvider: '.claude', rel: 'settings.json', destProvider: '.claude', destRel: 'settings.local.json' },
189
- ],
190
- '.cursor': [
191
- { sourceProvider: '.cursor', rel: 'hooks.json', destProvider: '.cursor' },
192
- ],
193
- // Codex reads skills from `.agents/skills`, but project hooks from
194
- // `.codex/hooks.json`, so the `.agents` install target owns this sidecar.
195
- '.agents': [
196
- { sourceProvider: '.codex', rel: 'hooks.json', destProvider: '.codex' },
197
- ],
198
- // GitHub Copilot reads repo-level hooks from `.github/hooks/*.json`. Unlike
199
- // Claude, this is a team-shared, committed file (not a machine-local override),
200
- // so source and dest are the same path.
201
- '.github': [
202
- { sourceProvider: '.github', rel: 'hooks/impeccable.json', destProvider: '.github' },
203
- ],
204
- // Grok Build discovers project hooks from `.grok/hooks/*.json`. Team-shared
205
- // by default (commit them if the whole team uses Grok); folder trust is still
206
- // required via `/hooks-trust` or `--trust` before they run.
207
- '.grok': [
208
- { sourceProvider: '.grok', rel: 'hooks/impeccable.json', destProvider: '.grok' },
209
- ],
210
- };
211
-
212
- function userProviderSkillsDir(home, provider) {
213
- const override = HOME_SKILLS_DIR_OVERRIDES[provider];
214
- if (override) return override(home);
215
- return join(home, provider, 'skills');
216
- }
217
-
218
- // Compare via realpath: the project root comes from process.cwd() (symlinks
219
- // resolved) while homedir() reflects $HOME verbatim, so a home dir reached
220
- // through a symlink (e.g. /tmp -> /private/tmp) would fail a string compare.
221
- function isHomeDir(root) {
222
- if (root === homedir()) return true;
223
- try {
224
- return realpathSync(root) === realpathSync(homedir());
225
- } catch {
226
- return false;
227
- }
228
- }
229
-
230
- // Every layout a provider's installed skills can live in under `root`.
231
- // `scope` narrows the answer when the caller knows which install it is
232
- // acting on: 'user' means the provider's global layout, 'project' means
233
- // `<provider>/skills`. Without a scope (update/check, where installs of
234
- // either kind may live under `root`) both layouts are candidates when
235
- // `root` is the home dir, since an overridden provider (Pi) keeps its
236
- // global skills elsewhere while a repo rooted at ~ still uses the project
237
- // layout. Scoping matters for the same reason: a project-scope install in
238
- // a home-rooted repo must not be conflated with an existing global one.
239
- function providerSkillsDirCandidates(root, provider, scope) {
240
- if (scope === 'user') return [userProviderSkillsDir(root, provider)];
241
- const dirs = [join(root, provider, 'skills')];
242
- if (scope !== 'project' && HOME_SKILLS_DIR_OVERRIDES[provider] && isHomeDir(root)) {
243
- dirs.unshift(userProviderSkillsDir(root, provider));
244
- }
245
- return dirs;
246
- }
247
-
248
- function existingSkillsDirs(root, provider, scope) {
249
- return providerSkillsDirCandidates(root, provider, scope).filter(existsSync);
250
- }
251
-
252
- let pipedAnswers = null;
253
- class PromptAbortError extends Error {
254
- constructor() {
255
- super('Aborted.');
256
- this.name = 'PromptAbortError';
257
- this.code = 'IMPECCABLE_PROMPT_ABORT';
258
- }
259
- }
260
-
261
- function isPromptAbortError(error) {
262
- return error?.code === 'IMPECCABLE_PROMPT_ABORT';
263
- }
264
-
265
- function canStyleTerminal() {
266
- return Boolean(process.stdout.isTTY && process.env.NO_COLOR === undefined && process.env.TERM !== 'dumb');
267
- }
268
-
269
- function ansi(open, close, value) {
270
- const text = String(value);
271
- return canStyleTerminal() ? `${open}${text}${close}` : text;
272
- }
273
-
274
- const ui = {
275
- accent: value => ansi('\x1b[36m', '\x1b[0m', value),
276
- bold: value => ansi('\x1b[1m', '\x1b[22m', value),
277
- dim: value => ansi('\x1b[2m', '\x1b[22m', value),
278
- good: value => ansi('\x1b[32m', '\x1b[0m', value),
279
- };
280
-
281
- function ask(question) {
282
- if (!process.stdin.isTTY) {
283
- process.stdout.write(question);
284
- if (!pipedAnswers) {
285
- let input = '';
286
- try {
287
- input = readFileSync(0, 'utf-8');
288
- } catch {}
289
- pipedAnswers = input.split(/\r?\n/);
290
- }
291
- return Promise.resolve(String(pipedAnswers.shift() || '').trim().toLowerCase());
292
- }
293
-
294
- const rl = createInterface({ input: process.stdin, output: process.stdout });
295
- return new Promise((resolve, reject) => {
296
- rl.once('SIGINT', () => {
297
- rl.close();
298
- reject(new PromptAbortError());
299
- });
300
- rl.question(question, ans => {
301
- rl.close();
302
- resolve(ans.trim().toLowerCase());
303
- });
304
- });
305
- }
306
-
307
- function isInteractivePrompt() {
308
- return Boolean(process.stdin.isTTY && process.stdout.isTTY && typeof process.stdin.setRawMode === 'function');
309
- }
310
-
311
- function promptKeypressSession(renderInitial, handleKey) {
312
- const input = process.stdin;
313
- const output = process.stdout;
314
- const wasRaw = Boolean(input.isRaw);
315
- let lastLineCount = 0;
316
- let done = false;
317
-
318
- emitKeypressEvents(input);
319
-
320
- return new Promise((resolve, reject) => {
321
- function cleanup() {
322
- if (done) return;
323
- done = true;
324
- input.off('keypress', onKeypress);
325
- if (typeof input.setRawMode === 'function') input.setRawMode(wasRaw);
326
- output.write('\x1b[?25h');
327
- input.pause();
328
- }
329
-
330
- function render(lines) {
331
- const nextLines = Array.isArray(lines) ? lines : String(lines).split('\n');
332
- if (lastLineCount > 0) output.write(`\x1b[${lastLineCount}A`);
333
- const lineCount = Math.max(lastLineCount, nextLines.length);
334
- for (let index = 0; index < lineCount; index++) {
335
- const line = nextLines[index] || '';
336
- output.write(`\x1b[2K\r${line}\n`);
337
- }
338
- lastLineCount = lineCount;
339
- }
340
-
341
- function finish(value) {
342
- cleanup();
343
- resolve(value);
344
- }
345
-
346
- function abort() {
347
- cleanup();
348
- reject(new PromptAbortError());
349
- }
350
-
351
- function onKeypress(str, key = {}) {
352
- if (key.ctrl && key.name === 'c') {
353
- abort();
354
- return;
355
- }
356
- const next = handleKey(str, key);
357
- if (!next) return;
358
- if (next.abort) {
359
- abort();
360
- return;
361
- }
362
- if (next.done) {
363
- render(next.lines);
364
- finish(next.value);
365
- return;
366
- }
367
- render(next.lines);
368
- }
369
-
370
- input.on('keypress', onKeypress);
371
- input.setRawMode(true);
372
- input.resume();
373
- output.write('\x1b[?25l');
374
- render(renderInitial());
375
- });
376
- }
377
-
378
- function clampIndex(index, length) {
379
- if (length <= 0) return 0;
380
- if (index < 0) return length - 1;
381
- if (index >= length) return 0;
382
- return index;
383
- }
384
-
385
- function visibleWindow(cursor, total, maxVisible) {
386
- const visible = Math.max(1, Math.min(total, maxVisible));
387
- let start = Math.max(0, cursor - visible + 1);
388
- if (cursor < start) start = cursor;
389
- start = Math.min(start, Math.max(0, total - visible));
390
- return { start, end: start + visible };
391
- }
392
-
393
- async function promptRadio(message, options, { initialIndex = 0 } = {}) {
394
- let cursor = clampIndex(initialIndex, options.length);
395
-
396
- const render = () => [
397
- `${ui.accent('◆')} ${ui.bold(message)}`,
398
- '',
399
- ...options.map((option, index) => {
400
- const active = index === cursor;
401
- const pointer = active ? ui.accent('›') : ' ';
402
- const mark = active ? ui.good('●') : ui.dim('○');
403
- const label = active ? ui.bold(option.label) : option.label;
404
- const hint = option.hint ? ` ${ui.dim(option.hint)}` : '';
405
- return ` ${pointer} ${mark} ${label}${hint}`;
406
- }),
407
- '',
408
- ` ${ui.dim('↑/↓ move, enter confirm')}`,
409
- ];
410
-
411
- return promptKeypressSession(render, (_str, key = {}) => {
412
- if (key.name === 'up' || key.name === 'k') cursor = clampIndex(cursor - 1, options.length);
413
- if (key.name === 'down' || key.name === 'j') cursor = clampIndex(cursor + 1, options.length);
414
- if (key.name === 'return' || key.name === 'enter') {
415
- return { done: true, value: options[cursor].value, lines: render() };
416
- }
417
- return { lines: render() };
418
- });
419
- }
420
-
421
- async function promptCheckbox(message, options, { selectedValues = [] } = {}) {
422
- const selected = new Set(selectedValues);
423
- let cursor = 0;
424
- let error = '';
425
- let query = '';
426
- const maxVisible = Math.max(5, Math.min(options.length, (process.stdout.rows || 24) - 9, 10));
427
-
428
- function filteredOptions() {
429
- const needle = query.trim().toLowerCase();
430
- if (!needle) return options;
431
- return options.filter(option => option.searchText.toLowerCase().includes(needle));
432
- }
433
-
434
- function selectedSummary() {
435
- const selectedOptions = options.filter(option => selected.has(option.value));
436
- if (selectedOptions.length === 0) return ui.dim('none');
437
- const labels = selectedOptions.map(option => option.label);
438
- if (labels.length <= 4) return labels.join(', ');
439
- return `${labels.slice(0, 4).join(', ')} ${ui.dim(`+${labels.length - 4} more`)}`;
440
- }
441
-
442
- const render = () => {
443
- const filtered = filteredOptions();
444
- cursor = clampIndex(cursor, filtered.length);
445
- const { start, end } = visibleWindow(cursor, filtered.length, maxVisible);
446
- const lines = [
447
- `${ui.accent('◆')} ${ui.bold(message)}`,
448
- '',
449
- ` Search: ${query || ui.dim('type to filter')}`,
450
- ` ${ui.dim('↑/↓ move, space select, enter confirm')}`,
451
- '',
452
- ];
453
- if (filtered.length === 0) {
454
- lines.push(` ${ui.dim('No matches')}`);
455
- } else if (filtered.length > maxVisible) {
456
- lines.push(` ${ui.dim(`Showing ${start + 1}-${end} of ${filtered.length}`)}`);
457
- }
458
-
459
- if (filtered.length > 0) {
460
- for (let index = start; index < end; index++) {
461
- const option = filtered[index];
462
- const active = index === cursor;
463
- const pointer = active ? ui.accent('›') : ' ';
464
- const mark = selected.has(option.value) ? ui.good('●') : ui.dim('○');
465
- const label = active ? ui.bold(option.label) : option.label;
466
- const hint = option.hint ? ` ${ui.dim(option.hint)}` : '';
467
- lines.push(` ${pointer} ${mark} ${label}${hint}`);
468
- }
469
- }
470
-
471
- lines.push('');
472
- lines.push(` Selected: ${selectedSummary()}`);
473
- if (error) lines.push(` ${error}`);
474
- return lines;
475
- };
476
-
477
- return promptKeypressSession(render, (str, key = {}) => {
478
- const filtered = filteredOptions();
479
- if (key.name === 'up') cursor = clampIndex(cursor - 1, filtered.length);
480
- if (key.name === 'down') cursor = clampIndex(cursor + 1, filtered.length);
481
- if (key.name === 'space' || str === ' ') {
482
- const option = filtered[cursor];
483
- if (option) {
484
- if (selected.has(option.value)) selected.delete(option.value);
485
- else selected.add(option.value);
486
- error = '';
487
- }
488
- }
489
- if (key.name === 'backspace' || key.name === 'delete') {
490
- query = query.slice(0, -1);
491
- cursor = 0;
492
- error = '';
493
- }
494
- if (key.ctrl && key.name === 'u') {
495
- query = '';
496
- cursor = 0;
497
- error = '';
498
- }
499
- if (str && str.length === 1 && str >= '!' && !key.ctrl && !key.meta) {
500
- query += str;
501
- cursor = 0;
502
- error = '';
503
- }
504
- if (key.name === 'return' || key.name === 'enter') {
505
- if (selected.size === 0) {
506
- error = ui.dim('Choose at least one harness.');
507
- return { lines: render() };
508
- }
509
- return {
510
- done: true,
511
- value: options.filter(option => selected.has(option.value)).map(option => option.value),
512
- lines: render(),
513
- };
514
- }
515
- return { lines: render() };
516
- });
517
- }
518
-
519
- // ─── skills help ──────────────────────────────────────────────────────────────
520
-
521
- async function showHelp() {
522
- let commands;
523
- try {
524
- const res = await fetch(`${API_BASE}/api/commands`);
525
- commands = await res.json();
526
- } catch {
527
- console.error('Could not fetch command list from impeccable.style. Check your network connection.');
528
- process.exit(1);
529
- }
530
-
531
- const pad = (s, n) => s + ' '.repeat(Math.max(0, n - s.length));
532
-
533
- console.log('\n Impeccable Skills & Commands\n');
534
- console.log(' Install: npx impeccable install');
535
- console.log(' Link: npx impeccable link --source=.impeccable');
536
- console.log(' Update: npx impeccable update');
537
- console.log(' Docs: https://impeccable.style/cheatsheet\n');
538
- console.log(` ${pad('Command', 22)} Description`);
539
- console.log(` ${'-'.repeat(22)} ${'-'.repeat(52)}`);
540
-
541
- for (const cmd of commands.sort((a, b) => a.id.localeCompare(b.id))) {
542
- // Trim description to fit terminal
543
- const desc = cmd.description.length > 72
544
- ? cmd.description.substring(0, 69) + '...'
545
- : cmd.description;
546
- console.log(` ${pad('/' + cmd.id, 22)} ${desc}`);
547
- }
548
- console.log(`\n ${commands.length} commands available. Run /<command> in your AI harness.\n`);
549
- }
550
-
551
- // ─── version helpers ─────────────────────────────────────────────────────────
552
-
553
- /**
554
- * Read the skills version from the impeccable SKILL.md frontmatter.
555
- */
556
- function getSkillsVersion(root, scope) {
557
- for (const d of PROVIDER_DIRS) {
558
- for (const skillsDir of providerSkillsDirCandidates(root, d, scope)) {
559
- const skillMd = join(skillsDir, 'impeccable', 'SKILL.md');
560
- if (!existsSync(skillMd)) continue;
561
- const content = readFileSync(skillMd, 'utf-8');
562
- const match = content.match(/^version:\s*(.+)$/m);
563
- if (match) return match[1].trim().replace(/^["']|["']$/g, '');
564
- }
565
- }
566
- return null;
567
- }
568
-
569
- /**
570
- * Return every file in a directory tree, sorted and relative to the tree root.
571
- */
572
- function listSkillTreeFiles(root, dir = root) {
573
- if (!existsSync(dir)) return [];
574
- const files = [];
575
- for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
576
- const full = join(dir, entry.name);
577
- if (entry.isDirectory()) {
578
- files.push(...listSkillTreeFiles(root, full));
579
- } else if (entry.isFile()) {
580
- files.push(relative(root, full).split(sep).join('/'));
581
- }
582
- }
583
- return files;
584
- }
585
-
586
- /**
587
- * Extract every entry of a zip archive into `targetDir`.
588
- *
589
- * This replaces `extract-zip`, whose `yauzl`/`fd-slicer` read stack stalls on
590
- * Node v24.16.0 / v26.1.0+ (nodejs/node#63487): `pause()`/`resume()` became
591
- * no-ops on destroyed streams, so extraction stops after a handful of entries,
592
- * its promise never settles, and -- because nothing else keeps the event loop
593
- * alive -- the CLI exits 0 with no error, silently installing nothing.
594
- *
595
- * `fflate` decompresses from an in-memory buffer and never touches the fs
596
- * stream path, so it is immune to that regression on every Node version. It is
597
- * pure JS with zero dependencies, which keeps the Windows fix from #198 intact
598
- * (no `unzip` binary required). We write the entries to disk ourselves, which
599
- * lets us guard against zip-slip (`../` entries escaping `targetDir`).
600
- */
601
- async function extractZip(zipPath, targetDir) {
602
- const entries = unzipSync(readFileSync(zipPath));
603
- const root = resolve(targetDir);
604
- for (const [entryPath, bytes] of Object.entries(entries)) {
605
- // Directory entries arrive as zero-length names ending in `/`; the files
606
- // beneath them create their parents via mkdirSync below.
607
- if (entryPath.endsWith('/')) continue;
608
- const dest = resolve(root, entryPath);
609
- if (dest !== root && !dest.startsWith(root + sep)) {
610
- throw new Error(`Refusing to extract entry outside target dir: ${entryPath}`);
611
- }
612
- mkdirSync(dirname(dest), { recursive: true });
613
- writeFileSync(dest, bytes);
614
- }
615
- }
616
-
617
- /**
618
- * Download the universal bundle to a temp dir and return its path.
619
- * Caller is responsible for cleanup.
620
- */
621
- async function downloadAndExtractBundle() {
622
- const localBundle = process.env.IMPECCABLE_BUNDLE_PATH;
623
- if (localBundle) return copyOrExtractLocalBundle(localBundle);
624
-
625
- const tmpZip = join(tmpdir(), `impeccable-update-${Date.now()}.zip`);
626
- const tmpDir = join(tmpdir(), `impeccable-update-${Date.now()}`);
627
- await downloadFile(`${API_BASE}/api/download/bundle/universal`, tmpZip);
628
- mkdirSync(tmpDir, { recursive: true });
629
- await extractZip(tmpZip, tmpDir);
630
- rmSync(tmpZip, { force: true });
631
- return tmpDir;
632
- }
633
-
634
- async function copyOrExtractLocalBundle(sourceValue) {
635
- const source = resolve(sourceValue);
636
- if (!existsSync(source)) {
637
- throw new Error(`Local bundle not found: ${source}`);
638
- }
639
-
640
- const tmpDir = join(tmpdir(), `impeccable-local-bundle-${process.pid}-${Date.now()}`);
641
- mkdirSync(tmpDir, { recursive: true });
642
-
643
- if (statSync(source).isDirectory()) {
644
- cpSync(source, tmpDir, { recursive: true });
645
- return tmpDir;
646
- }
647
-
648
- await extractZip(source, tmpDir);
649
- return tmpDir;
650
- }
651
-
652
- /**
653
- * Normalize a SKILL.md's content for comparison by stripping
654
- * provider-specific paths. Different install methods (npx skills add
655
- * vs our bundle) resolve {{scripts_path}} to different provider dirs
656
- * (e.g. .agents vs .claude), so we strip those differences.
657
- * Version fields intentionally remain part of the comparison so metadata-only
658
- * releases still refresh installed files.
659
- */
660
- function normalizeForHash(content) {
661
- return content
662
- .replace(/\.(claude|cursor|agents|agent|github|gemini|codex|grok|hermes|kiro|opencode|pi|qoder|trae|trae-cn|rovodev|vibe)\/skills\//g, '.PROVIDER/skills/');
663
- }
664
-
665
- function hashSkillFile(filePath) {
666
- return createHash('sha256')
667
- .update(normalizeForHash(readFileSync(filePath, 'utf-8')))
668
- .digest('hex');
669
- }
670
-
671
- /**
672
- * Deduplicate providers by resolved path. When .claude/skills is a
673
- * symlink to ../.agents/skills, both resolve to the same directory.
674
- * Returns an array of { provider, localSkillsDir } with one entry
675
- * per unique real path. The first provider that maps to a real path
676
- * wins (so the bundle uses that provider's build).
677
- */
678
- function deduplicateProviders(root, providers, scope) {
679
- const seen = new Map(); // realPath -> { provider, localSkillsDir }
680
- for (const provider of providers) {
681
- // A provider can hold real installs in more than one layout (a home-rooted
682
- // repo may carry both ~/.pi/agent/skills and ~/.pi/skills). Keep each as
683
- // its own entry so update/check touch every tree, not just the first.
684
- for (const skillsDir of existingSkillsDirs(root, provider, scope)) {
685
- const real = realpathSync(skillsDir);
686
- if (!seen.has(real)) {
687
- seen.set(real, { provider, localSkillsDir: skillsDir });
688
- }
689
- }
690
- }
691
- return [...seen.values()];
692
- }
693
-
694
- /**
695
- * Compare local skills against a downloaded bundle.
696
- * Only checks skills that exist in the bundle (ignores user's custom skills
697
- * that aren't part of impeccable). Deduplicates providers that share the same
698
- * real path (symlinks). Compares the full bundled skill tree, not just
699
- * SKILL.md, so script-only fixes and removed files are detected.
700
- * Returns true if every bundle skill matches the local copy.
701
- */
702
- function isUpToDate(root, providers, bundleDir, scope) {
703
- const unique = deduplicateProviders(root, providers, scope);
704
- if (unique.length === 0) return false;
705
-
706
- for (const { provider, localSkillsDir } of unique) {
707
- const bundleSkillsDir = join(bundleDir, provider, 'skills');
708
- if (!existsSync(bundleSkillsDir)) continue;
709
-
710
- for (const name of readdirSync(bundleSkillsDir)) {
711
- const bundleSkillDir = join(bundleSkillsDir, name);
712
- const localSkillDir = join(localSkillsDir, name);
713
- const bundleMd = join(bundleSkillDir, 'SKILL.md');
714
- if (!existsSync(bundleMd)) continue;
715
- if (!existsSync(localSkillDir)) return false;
716
-
717
- const bundleFiles = listSkillTreeFiles(bundleSkillDir);
718
- const localFiles = listSkillTreeFiles(localSkillDir);
719
- if (bundleFiles.join('\n') !== localFiles.join('\n')) return false;
720
-
721
- for (const relPath of bundleFiles) {
722
- const bundleHash = hashSkillFile(join(bundleSkillDir, ...relPath.split('/')));
723
- const localHash = hashSkillFile(join(localSkillDir, ...relPath.split('/')));
724
- if (bundleHash !== localHash) return false;
725
- }
726
- }
727
- }
728
- return true;
729
- }
730
-
731
- // ─── skills check ────────────────────────────────────────────────────────────
732
-
733
- async function check() {
734
- const root = findProjectRoot();
735
- const installed = isAlreadyInstalled(root);
736
-
737
- if (!installed) {
738
- console.log('Impeccable is not installed in this project.');
739
- console.log('Run `npx impeccable install` to install.');
740
- process.exit(0);
741
- }
742
-
743
- const providers = findInstalledProviders(root);
744
-
745
- console.log('Checking for updates...\n');
746
- try {
747
- const bundleDir = await downloadAndExtractBundle();
748
- const upToDate = isUpToDate(root, providers, bundleDir);
749
- rmSync(bundleDir, { recursive: true, force: true });
750
-
751
- if (upToDate) {
752
- const v = getSkillsVersion(root);
753
- console.log(`Skills are up to date${v ? ` (v${v})` : ''}.`);
754
- } else {
755
- console.log('Updates available.');
756
- console.log('Run `npx impeccable update` to update.');
757
- }
758
- } catch (e) {
759
- console.error(`Could not check for updates: ${e.message}`);
760
- process.exit(1);
761
- }
762
- }
763
-
764
- // ─── skills install ───────────────────────────────────────────────────────────
765
-
766
- // Check if impeccable skills are already present in any provider folder
767
- function isAlreadyInstalled(root, scope) {
768
- for (const d of PROVIDER_DIRS) {
769
- for (const skillsDir of existingSkillsDirs(root, d, scope)) {
770
- try {
771
- const entries = readdirSync(skillsDir);
772
- // Look for 'impeccable' skill (or prefixed variant, or legacy 'teach-impeccable')
773
- if (entries.some(e =>
774
- e === 'impeccable' || e.endsWith('-impeccable') ||
775
- e === 'teach-impeccable' || e.endsWith('-teach-impeccable')
776
- )) {
777
- return d;
778
- }
779
- } catch {}
780
- }
781
- }
782
- return null;
783
- }
784
-
785
- function isSkillDir(skillsDir, name) {
786
- // Skill entries can be real directories or symlinks to directories (npx skills uses symlinks)
787
- const full = join(skillsDir, name);
788
- try {
789
- return statSync(full).isDirectory() && existsSync(join(full, 'SKILL.md'));
790
- } catch { return false; }
791
- }
792
-
793
- function hasRealSkillEntries(skillsDir) {
794
- if (!existsSync(skillsDir)) return false;
795
- let entries;
796
- try { entries = readdirSync(skillsDir); } catch { return false; }
797
- return entries.some(name =>
798
- !name.startsWith('.') &&
799
- !IGNORED_SKILL_DIR_NAMES.has(name) &&
800
- isSkillDir(skillsDir, name)
801
- );
802
- }
803
-
804
- function isRealSkillDir(skillsDir, name) {
805
- // Only real directories, not symlinks -- renaming the real dir renames the symlink targets too
806
- const full = join(skillsDir, name);
807
- try {
808
- const lstat = lstatSync(full);
809
- return lstat.isDirectory() && !lstat.isSymbolicLink() && existsSync(join(full, 'SKILL.md'));
810
- } catch { return false; }
811
- }
812
-
813
- /**
814
- * One-way migration for installs from the era when the CLI offered a command
815
- * prefix (default `i-`), renaming the skill to e.g. `i-impeccable`. The prefix
816
- * only earned its keep when every command was its own skill; with a single
817
- * `impeccable` skill it does nothing, so it is no longer offered. Rename any
818
- * prefixed impeccable skill back to the canonical `impeccable` (the fresh
819
- * install/update content lands there next) so users aren't left with a stale,
820
- * orphaned `i-impeccable` alongside the new one. Scoped to the impeccable skill
821
- * by name -- never touches third-party skills that happen to start with `i-`.
822
- * Returns the number of skills migrated.
823
- */
824
- function migrateUnprefixImpeccable(root, scope) {
825
- let migrated = 0;
826
- for (const d of PROVIDER_DIRS) {
827
- for (const skillsDir of existingSkillsDirs(root, d, scope)) {
828
- let entries;
829
- try { entries = readdirSync(skillsDir); } catch { continue; }
830
- for (const name of entries) {
831
- // A prefixed impeccable skill is `<prefix>impeccable`, not the canonical
832
- // `impeccable` and not an unrelated legacy skill name.
833
- if (name === 'impeccable' || name === 'teach-impeccable') continue;
834
- if (!name.endsWith('-impeccable')) continue;
835
- if (!isRealSkillDir(skillsDir, name)) continue;
836
-
837
- const dest = join(skillsDir, 'impeccable');
838
- try {
839
- rmSync(dest, { recursive: true, force: true });
840
- renameSync(join(skillsDir, name), dest);
841
- migrated++;
842
- } catch {}
843
- }
844
- }
845
- }
846
- return migrated;
847
- }
848
-
849
- function getFlagValue(flags, name) {
850
- const prefix = `${name}=`;
851
- const inline = flags.find(f => f.startsWith(prefix));
852
- if (inline) return inline.slice(prefix.length);
853
- const index = flags.indexOf(name);
854
- if (index !== -1 && flags[index + 1] && !flags[index + 1].startsWith('-')) {
855
- return flags[index + 1];
856
- }
857
- return null;
858
- }
859
-
860
- function normalizeProviderName(value) {
861
- const raw = String(value || '').trim();
862
- if (!raw) return null;
863
- if (PROVIDER_DIRS.includes(raw)) return raw;
864
- const key = raw.replace(/^\./, '').toLowerCase();
865
- return PROVIDER_ALIASES[key] || null;
866
- }
867
-
868
- function parseProviderList(value) {
869
- const providers = [];
870
- const invalid = [];
871
- for (const raw of String(value || '').split(',').map(s => s.trim()).filter(Boolean)) {
872
- const provider = normalizeProviderName(raw);
873
- if (!provider) {
874
- invalid.push(raw);
875
- continue;
876
- }
877
- if (!providers.includes(provider)) providers.push(provider);
878
- }
879
- return { providers, invalid };
880
- }
881
-
882
- function providerInputName(provider) {
883
- return PROVIDER_DISPLAY[provider]?.input || provider.replace(/^\./, '');
884
- }
885
-
886
- function providerDisplayName(provider) {
887
- return PROVIDER_DISPLAY[provider]?.name || provider;
888
- }
889
-
890
- function formatProviderList(providers) {
891
- return providers.map(providerInputName).join(', ');
892
- }
893
-
894
- function providerPromptOptions() {
895
- return PROVIDER_INPUT_ORDER.map(input => {
896
- const provider = normalizeProviderName(input);
897
- const label = providerDisplayName(provider);
898
- const hint = `(${provider}/skills)`;
899
- return {
900
- value: provider,
901
- label,
902
- hint,
903
- searchText: `${label} ${input} ${provider} ${hint}`,
904
- };
905
- });
906
- }
907
-
908
- function formatPathForDisplay(path, home = homedir()) {
909
- if (path === home) return '~';
910
- if (path.startsWith(`${home}/`)) return `~/${path.slice(home.length + 1)}`;
911
- return path;
912
- }
913
-
914
- function uniquePaths(paths) {
915
- return [...new Set(paths)];
916
- }
917
-
918
- function userSkillProbePaths(home, harnessDir, provider) {
919
- return uniquePaths([
920
- userProviderSkillsDir(home, provider),
921
- join(home, harnessDir, 'skills'),
922
- ]);
923
- }
924
-
925
- function collectInstallDetections(root, home = homedir()) {
926
- const detections = [];
927
- for (const provider of PROVIDER_DIRS) {
928
- const foundPath = join(root, provider);
929
- if (!existsSync(foundPath)) continue;
930
- detections.push({
931
- provider,
932
- scope: 'project',
933
- foundPath,
934
- installRoot: root,
935
- installPath: join(root, provider, 'skills'),
936
- hasRealSkills: hasRealSkillEntries(join(root, provider, 'skills')),
937
- reason: 'project harness folder',
938
- });
939
- }
940
-
941
- for (const hint of GLOBAL_HARNESS_HINTS) {
942
- const { provider } = hint;
943
- // A hint is either a fixed dir under home or a resolver for harnesses
944
- // whose location depends on the environment (OpenCode's config dir).
945
- const foundPath = hint.resolve ? hint.resolve(home) : join(home, hint.home);
946
- if (!existsSync(foundPath)) continue;
947
- const skillProbePaths = hint.resolve
948
- ? uniquePaths([userProviderSkillsDir(home, provider), join(foundPath, 'skills')])
949
- : userSkillProbePaths(home, hint.home, provider);
950
- detections.push({
951
- provider,
952
- scope: 'user',
953
- foundPath,
954
- installRoot: home,
955
- installPath: userProviderSkillsDir(home, provider),
956
- skillProbePaths,
957
- hasRealSkills: skillProbePaths.some(hasRealSkillEntries),
958
- reason: 'user harness folder',
959
- });
960
- }
961
- return detections;
962
- }
963
-
964
- function uniqueProviders(detections) {
965
- const providers = [];
966
- for (const detection of detections) {
967
- if (!providers.includes(detection.provider)) providers.push(detection.provider);
968
- }
969
- return providers;
970
- }
971
-
972
- function defaultDetectedProviders(detections) {
973
- const projectProviders = uniqueProviders(detections.filter(d => d.scope === 'project'));
974
- if (projectProviders.length > 0) return projectProviders;
975
- return uniqueProviders(detections.filter(d => d.scope === 'user'));
976
- }
977
-
978
- /**
979
- * Decide which provider folders to install into.
980
- * 1. An explicit --providers=.claude,.cursor list wins.
981
- * 2. Otherwise, harness folders already present in the project.
982
- * 3. Otherwise, infer from globally installed harnesses (~/.claude, ~/.codex).
983
- * 4. Otherwise, a sensible default (.claude + .agents).
984
- */
985
- function resolveInstallTargets(root, providersValue) {
986
- if (providersValue) {
987
- return parseProviderList(providersValue).providers;
988
- }
989
-
990
- const detected = defaultDetectedProviders(collectInstallDetections(root));
991
- if (detected.length > 0) return detected;
992
-
993
- return [...DEFAULT_TARGETS];
994
- }
995
-
996
- function normalizeInstallScope(value) {
997
- const key = String(value || '').trim().toLowerCase();
998
- if (['u', 'user', 'home', 'global'].includes(key)) return 'user';
999
- if (['p', 'project', 'local', 'repo'].includes(key)) return 'project';
1000
- return null;
1001
- }
1002
-
1003
- function getInstallScopeValue(flags) {
1004
- if (flags.includes('--user') || flags.includes('--home') || flags.includes('--global')) return 'user';
1005
- if (flags.includes('--project') || flags.includes('--local')) return 'project';
1006
- return getFlagValue(flags, '--scope') || getFlagValue(flags, '--install-scope');
1007
- }
1008
-
1009
- function defaultInstallScope(detections, providers) {
1010
- const selected = new Set(providers);
1011
- if (detections.some(d => selected.has(d.provider) && d.scope === 'project')) return 'project';
1012
- if (detections.some(d => selected.has(d.provider) && d.scope === 'user' && d.hasRealSkills)) return 'user';
1013
- return 'project';
1014
- }
1015
-
1016
- function installRootForScope(scope, projectRoot) {
1017
- return scope === 'user' ? homedir() : projectRoot;
1018
- }
1019
-
1020
- function printInstallIntro() {
1021
- if (!isInteractivePrompt()) return;
1022
- console.log(`${ui.accent(ui.bold('impeccable'))} ${ui.dim('install')}`);
1023
- console.log('');
1024
- }
1025
-
1026
- function formatInstallDetectionLines(projectRoot, detections, home = homedir(), { styled = false } = {}) {
1027
- if (detections.length === 0) {
1028
- const message = `No harnesses detected under ${formatPathForDisplay(projectRoot, home)} or ${formatPathForDisplay(home, home)}.`;
1029
- return styled
1030
- ? [`${ui.accent('◇')} ${ui.bold('Detected harnesses')}`, ` ${ui.dim(message)}`]
1031
- : [message];
1032
- }
1033
-
1034
- const names = detections.map(d => providerDisplayName(d.provider));
1035
- const paths = detections.map(d => formatPathForDisplay(d.foundPath, home));
1036
- const nameWidth = Math.max(...names.map(name => name.length));
1037
- const heading = styled ? `${ui.accent('◇')} ${ui.bold('Detected harnesses')}` : 'Detected harnesses:';
1038
- return [
1039
- heading,
1040
- ...detections.map((detection, index) => {
1041
- const rawName = names[index].padEnd(nameWidth);
1042
- const rawFoundPath = paths[index];
1043
- const name = styled ? ui.bold(rawName) : rawName;
1044
- const foundPath = styled ? ui.dim(rawFoundPath) : rawFoundPath;
1045
- return ` ${name} ${foundPath}`;
1046
- }),
1047
- ];
1048
- }
1049
-
1050
- function printInstallDetections(projectRoot, detections) {
1051
- for (const line of formatInstallDetectionLines(projectRoot, detections, homedir(), { styled: isInteractivePrompt() })) console.log(line);
1052
- console.log('');
1053
- }
1054
-
1055
- async function promptForProviders(defaultProviders = []) {
1056
- if (isInteractivePrompt()) {
1057
- return promptCheckbox('Select harnesses', providerPromptOptions(), { selectedValues: defaultProviders });
1058
- }
1059
-
1060
- const choices = PROVIDER_INPUT_ORDER.join(', ');
1061
- const suffix = defaultProviders.length > 0
1062
- ? ` [blank keeps ${formatProviderList(defaultProviders)}]`
1063
- : '';
1064
- while (true) {
1065
- const answer = await ask(`Select harnesses (comma-separated: ${choices})${suffix}: `);
1066
- if (!answer && defaultProviders.length > 0) return [...defaultProviders];
1067
- const { providers, invalid } = parseProviderList(answer);
1068
- if (invalid.length > 0) {
1069
- console.log(`Unknown provider(s): ${invalid.join(', ')}`);
1070
- continue;
1071
- }
1072
- if (providers.length > 0) return providers;
1073
- console.log('Choose at least one provider.');
1074
- }
1075
- }
1076
-
1077
- async function promptDetectedInstallMode(detectedProviders) {
1078
- if (isInteractivePrompt()) {
1079
- return promptRadio('Install for detected harnesses only, or add more?', [
1080
- { value: 'detected', label: 'Detected only', hint: `(${formatProviderList(detectedProviders)})` },
1081
- { value: 'add', label: 'Customize...' },
1082
- ]);
1083
- }
1084
-
1085
- while (true) {
1086
- const answer = await ask(`Install target: [1] Detected only (${formatProviderList(detectedProviders)}) [2] Customize [1]: `);
1087
- if (!answer || ['1', 'detected', 'detected only', 'only', 'd'].includes(answer)) return 'detected';
1088
- if (['2', 'customize', 'customise', 'add', 'add more', 'more', 'a', 'n', 'no'].includes(answer)) return 'add';
1089
- console.log('Choose 1 for detected only, or 2 to customize.');
1090
- }
1091
- }
1092
-
1093
- async function chooseInstallProviders(projectRoot, providersValue, { yes } = {}) {
1094
- const detections = collectInstallDetections(projectRoot);
1095
- if (providersValue) {
1096
- const { providers, invalid } = parseProviderList(providersValue);
1097
- if (invalid.length > 0) {
1098
- throw new Error(`Unknown provider(s): ${invalid.join(', ')}`);
1099
- }
1100
- return { targets: providers, detections, explicit: true };
1101
- }
1102
-
1103
- if (yes) {
1104
- return { targets: resolveInstallTargets(projectRoot, null), detections, explicit: false };
1105
- }
1106
-
1107
- printInstallDetections(projectRoot, detections);
1108
- const detectedProviders = defaultDetectedProviders(detections);
1109
- if (detectedProviders.length === 0) {
1110
- return { targets: await promptForProviders(), detections, explicit: false };
1111
- }
1112
-
1113
- const mode = await promptDetectedInstallMode(detectedProviders);
1114
- if (mode === 'add') {
1115
- return { targets: await promptForProviders(detectedProviders), detections, explicit: false };
1116
- }
1117
- return { targets: detectedProviders, detections, explicit: false };
1118
- }
1119
-
1120
- async function chooseInstallScope(projectRoot, targets, detections, { yes, scopeValue } = {}) {
1121
- const explicitScope = normalizeInstallScope(scopeValue);
1122
- if (scopeValue && !explicitScope) {
1123
- throw new Error(`Unknown install scope: ${scopeValue}. Use --scope=project or --scope=global.`);
1124
- }
1125
- if (explicitScope) return explicitScope;
1126
-
1127
- // Preserve the old scripted behavior: `-y` installs into the current project
1128
- // unless the caller explicitly opts into `--scope=global`.
1129
- if (yes) return 'project';
1130
-
1131
- const fallback = defaultInstallScope(detections, targets);
1132
- if (isInteractivePrompt()) {
1133
- return promptRadio('Install location', [
1134
- { value: 'project', label: 'Project', hint: `(${formatPathForDisplay(projectRoot)})` },
1135
- { value: 'user', label: 'Global', hint: `(${formatPathForDisplay(homedir())})` },
1136
- ], { initialIndex: fallback === 'user' ? 1 : 0 });
1137
- }
1138
-
1139
- const answer = await ask(`Install location: project (${formatPathForDisplay(projectRoot)}) or global (${formatPathForDisplay(homedir())})? [${fallback === 'user' ? 'global' : fallback}] `);
1140
- if (!answer) return fallback;
1141
- const scope = normalizeInstallScope(answer);
1142
- if (!scope) {
1143
- console.log(`Unknown install location "${answer}", using ${fallback}.`);
1144
- return fallback;
1145
- }
1146
- return scope;
1147
- }
1148
-
1149
- async function chooseInstallPlan(projectRoot, flags, { yes } = {}) {
1150
- const providersValue = getFlagValue(flags, '--providers');
1151
- const scopeValue = getInstallScopeValue(flags);
1152
- const { targets, detections, explicit } = await chooseInstallProviders(projectRoot, providersValue, { yes });
1153
- if (targets.length === 0) {
1154
- throw new Error('Could not determine a target harness folder.');
1155
- }
1156
- const scope = await chooseInstallScope(projectRoot, targets, detections, { yes, scopeValue });
1157
- const installRoot = installRootForScope(scope, projectRoot);
1158
- return { targets, scope, installRoot, hookRoot: projectRoot, detections, explicit };
1159
- }
1160
-
1161
- /**
1162
- * Whether `localSkillsDir` is a symlink that points at ANOTHER in-project
1163
- * provider's skills dir (e.g. `.claude/skills -> ../.agents/skills`, the shape a
1164
- * prior `npx skills` install can leave behind). Only these get dropped so each
1165
- * provider can receive its own compiled variant. A symlink to anywhere else -
1166
- * notably a user's external shared skills dir (`~/.claude/skills ->
1167
- * ~/.config/agents/skills`) - is preserved and written through. See issue #295.
1168
- */
1169
- function isInProjectProviderLink(localSkillsDir, root, provider) {
1170
- let target;
1171
- try {
1172
- if (!lstatSync(localSkillsDir).isSymbolicLink()) return false;
1173
- target = readlinkSync(localSkillsDir);
1174
- } catch {
1175
- return false; // not a symlink, or unreadable
1176
- }
1177
- // Resolve the link's TARGET lexically against the link's own directory. We
1178
- // deliberately do NOT realpathSync the target:
1179
- // * it lets a not-yet-created in-project target still match, so a dangling
1180
- // `.claude/skills -> ../.agents/skills` is still dropped;
1181
- // * it compares the ACTUAL target, not a shared realpath, so two providers
1182
- // pointing at the SAME external dir are never misread as in-project.
1183
- const resolvedTarget = resolve(dirname(localSkillsDir), target);
1184
- for (const other of PROVIDER_DIRS) {
1185
- if (other === provider) continue;
1186
- if (resolvedTarget === join(root, other, 'skills')) return true;
1187
- }
1188
- return false;
1189
- }
1190
-
1191
- /**
1192
- * Copy each target provider's compiled skill variant from an extracted bundle
1193
- * into the project. Writes real directories (copy, never symlink) so every
1194
- * harness keeps the build that was compiled for it. Returns skills written.
1195
- * `scope: 'user'` writes to the provider's global skills layout (see
1196
- * HOME_SKILLS_DIR_OVERRIDES); anything else writes `<provider>/skills`.
1197
- */
1198
- function copyProviderSkills(bundleDir, root, targets, { scope } = {}) {
1199
- let written = 0;
1200
- for (const provider of targets) {
1201
- const srcDir = join(bundleDir, provider, 'skills');
1202
- if (existsSync(srcDir)) {
1203
- const localSkillsDir = scope === 'user'
1204
- ? userProviderSkillsDir(root, provider)
1205
- : join(root, provider, 'skills');
1206
- // A previous `npx skills` install may have left this provider's skills dir
1207
- // as a symlink to ANOTHER in-project provider's canonical copy. Drop only
1208
- // that link so we write a real, provider-specific directory. A user's
1209
- // external shared-skills symlink (e.g. ~/.claude/skills ->
1210
- // ~/.config/agents/skills) is preserved and written through. See #295.
1211
- try {
1212
- if (isInProjectProviderLink(localSkillsDir, root, provider)) unlinkSync(localSkillsDir);
1213
- } catch {}
1214
- for (const skill of readdirSync(srcDir, { withFileTypes: true })) {
1215
- if (!skill.isDirectory()) continue;
1216
- const src = join(srcDir, skill.name);
1217
- const dest = join(localSkillsDir, skill.name);
1218
- rmSync(dest, { recursive: true, force: true });
1219
- copyDirSync(src, dest);
1220
- written++;
1221
- }
1222
- // A pre-#406 global OpenCode install lived at ~/.opencode/skills, a
1223
- // location OpenCode never reads. Now that the real copy sits in the
1224
- // config dir, drop exactly the skills just written from the stranded
1225
- // location; sibling skills and everything else in ~/.opencode stay.
1226
- // Guards (both flagged in review): a symlinked skills dir is shared
1227
- // storage whose target must not be emptied through the link, the
1228
- // just-written dir must be compared by realpath rather than string,
1229
- // and a home-rooted repo makes `.opencode/skills` a live
1230
- // project-scope install rather than a stranded global one.
1231
- if (scope === 'user' && provider === '.opencode') {
1232
- const legacyDir = join(root, '.opencode', 'skills');
1233
- let migratable = false;
1234
- try {
1235
- migratable = existsSync(legacyDir)
1236
- && !lstatSync(legacyDir).isSymbolicLink()
1237
- && realpathSync(legacyDir) !== realpathSync(localSkillsDir)
1238
- && !existsSync(join(root, '.git'));
1239
- } catch { migratable = false; }
1240
- if (migratable) {
1241
- for (const skill of readdirSync(srcDir, { withFileTypes: true })) {
1242
- if (!skill.isDirectory()) continue;
1243
- rmSync(join(legacyDir, skill.name), { recursive: true, force: true });
1244
- }
1245
- try { rmdirSync(legacyDir); } catch { /* not empty: siblings stay */ }
1246
- }
1247
- }
1248
- }
1249
- }
1250
- return written;
1251
- }
1252
-
1253
- // Native subagent definitions that ship in the bundle next to a provider's
1254
- // skills. GitHub Copilot's live at `.github/agents/impeccable-*.agent.md`:
1255
- // project installs commit them at `<repo>/.github/agents/`, user-level
1256
- // installs go to `~/.copilot/agents/` (Copilot's user-scope dir, NOT
1257
- // `~/.github/`). On a name conflict Copilot lets the user-level file shadow
1258
- // the project one, so both paths overwrite existing impeccable-* copies and a
1259
- // project install reports any same-named user-level agents that would shadow
1260
- // it. Cursor's live at `.cursor/agents/impeccable-*.md`, user scope
1261
- // `~/.cursor/agents/`; project agents take precedence there, so no shadow
1262
- // warning is needed.
1263
- const PROVIDER_AGENT_ARTIFACTS = {
1264
- '.github': {
1265
- ext: '.agent.md',
1266
- userDir: home => join(home, '.copilot', 'agents'),
1267
- userShadowsProject: true,
1268
- },
1269
- '.cursor': {
1270
- ext: '.md',
1271
- userDir: home => join(home, '.cursor', 'agents'),
1272
- userShadowsProject: false,
1273
- },
1274
- };
1275
-
1276
- function copyProviderAgents(bundleDir, root, providers, { scope, home = homedir() } = {}) {
1277
- const targets = Array.isArray(providers) ? providers : [providers];
1278
- const results = [];
1279
- for (const provider of targets) {
1280
- const artifact = PROVIDER_AGENT_ARTIFACTS[provider];
1281
- if (!artifact) continue;
1282
- const srcDir = join(bundleDir, provider, 'agents');
1283
- if (!existsSync(srcDir)) continue;
1284
- const agentFiles = readdirSync(srcDir).filter(name => name.endsWith(artifact.ext));
1285
- if (agentFiles.length === 0) continue;
1286
-
1287
- const destDir = scope === 'user'
1288
- ? artifact.userDir(root)
1289
- : join(root, provider, 'agents');
1290
- mkdirSync(destDir, { recursive: true });
1291
- for (const name of agentFiles) {
1292
- writeFileSync(join(destDir, name), readFileSync(join(srcDir, name)));
1293
- }
1294
-
1295
- // A project install can be shadowed by same-named agents in the user-level
1296
- // dir; surface them so the freshly installed project agents actually apply.
1297
- const userDir = artifact.userDir(home);
1298
- const shadowed = artifact.userShadowsProject && scope !== 'user'
1299
- ? agentFiles.filter(name => existsSync(join(userDir, name)))
1300
- : [];
1301
-
1302
- results.push({ provider, written: agentFiles.length, destDir, userDir, shadowed });
1303
- }
1304
- return results;
1305
- }
1306
-
1307
- function reportProviderAgents(results) {
1308
- for (const result of results || []) {
1309
- if (result.written === 0) continue;
1310
- console.log(`Installed ${providerDisplayName(result.provider)} agents into: ${formatPathForDisplay(result.destDir)}`);
1311
- if (result.shadowed.length > 0) {
1312
- console.warn(`Warning: user-level agents in ${formatPathForDisplay(result.userDir)} shadow the project copies just installed: ${result.shadowed.join(', ')}.`);
1313
- console.warn('Run `npx impeccable update --user` to refresh them, or remove them so the project agents apply.');
1314
- }
1315
- }
1316
- }
1317
-
1318
- function refreshProviderSkills(bundleDir, root, providers, scope) {
1319
- const unique = deduplicateProviders(root, providers, scope);
1320
- let updated = 0;
1321
- for (const { provider, localSkillsDir } of unique) {
1322
- const srcDir = join(bundleDir, provider, 'skills');
1323
- if (!existsSync(srcDir)) continue;
1324
-
1325
- const skills = readdirSync(srcDir, { withFileTypes: true });
1326
- for (const skill of skills) {
1327
- if (!skill.isDirectory()) continue;
1328
- const src = join(srcDir, skill.name);
1329
- const dest = join(localSkillsDir, skill.name);
1330
- if (existsSync(dest)) rmSync(dest, { recursive: true, force: true });
1331
- copyDirSync(src, dest);
1332
- updated++;
1333
- }
1334
- }
1335
- return updated;
1336
- }
1337
-
1338
- function hookArtifactsForProvider(bundleDir, root, provider) {
1339
- return (PROVIDER_HOOK_ARTIFACTS[provider] || []).map(({ sourceProvider, rel, destProvider, destRel }) => {
1340
- const writeRel = destRel || rel;
1341
- const artifact = {
1342
- src: join(bundleDir, sourceProvider, rel),
1343
- dest: join(root, destProvider, writeRel),
1344
- };
1345
- // When the write target is a local override (e.g. settings.local.json), the
1346
- // team-shared sibling (settings.json) is where a legacy install or a
1347
- // deliberate user move would put our hook. Track it so we never duplicate.
1348
- if (writeRel !== rel) {
1349
- artifact.sharedDest = join(root, destProvider, rel);
1350
- }
1351
- return artifact;
1352
- });
1353
- }
1354
-
1355
- // The project-relative hook command path for a provider, used for project-scope
1356
- // installs (skillRoot === root). Derived rather than copied from the bundle: the
1357
- // Codex bundle ships a `.codex/skills/...` command (correct for a `.codex`-
1358
- // directory install), but the CLI lays Codex's skill down at `.agents/skills/`,
1359
- // so preserving the bundle token would point the hook at a nonexistent file and
1360
- // silently no-op it. Claude keeps its ${CLAUDE_PROJECT_DIR} token so a manifest
1361
- // read from a nested cwd (or copied into settings.local.json) still resolves.
1362
- function hookScriptRelPathForProvider(provider) {
1363
- const script = provider === '.cursor' ? 'hook-before-edit.mjs' : 'hook.mjs';
1364
- const rel = `${provider}/skills/impeccable/scripts/${script}`;
1365
- return provider === '.claude' ? '${CLAUDE_PROJECT_DIR}/' + rel : rel;
1366
- }
1367
-
1368
- function hookScriptPathForProvider(skillRoot, provider) {
1369
- // `.github` is intentionally absent: its hook manifest (`.github/hooks/
1370
- // impeccable.json`) is a committed, team-shared file that the Copilot cloud
1371
- // agent and every teammate read, so the command must stay portable
1372
- // (`$(git rev-parse --show-toplevel)/.github/skills/...`). Rewriting it to a
1373
- // machine-local absolute skillRoot path would break those. GitHub skills are
1374
- // project-scoped (not a home-provider), so the project-relative path resolves.
1375
- if (provider === '.cursor') {
1376
- return join(skillRoot, provider, 'skills', 'impeccable', 'scripts', 'hook-before-edit.mjs');
1377
- }
1378
- if (provider === '.claude' || provider === '.agents') {
1379
- return join(skillRoot, provider, 'skills', 'impeccable', 'scripts', 'hook.mjs');
1380
- }
1381
- return null;
1382
- }
1383
-
1384
- // Wrap a `node "PATH"` hook command so a missing skill file is a silent no-op
1385
- // (exit 0) instead of a Node module-resolution crash. hook.mjs promises to
1386
- // "never break a turn. Always exit 0.", but that only holds once Node can load
1387
- // the file; a stale/missing path crashes before any of that logic runs. The
1388
- // `[ ! -f X ] || node X` form (NOT `... || true`) preserves Node's own exit
1389
- // code when the file exists, so Claude's exit-2 blocking signal still reaches
1390
- // the agent. POSIX-shell form, consistent with the project's other hook
1391
- // commands (e.g. the GitHub manifest's `$(git rev-parse ...)`).
1392
- //
1393
- // On Windows that guard is a hard failure, not a degraded one (issue #452).
1394
- // Codex runs hook commands through COMSPEC (`cmd.exe /C`), where `[` is not a
1395
- // command: the guard errors noisily and `||` then runs node even when the file
1396
- // is missing, trading the silent no-op for a MODULE_NOT_FOUND crash. Two
1397
- // remedies, by provider:
1398
- //
1399
- // * Codex manifests support a `commandWindows` sibling that Codex 0.146.0+
1400
- // selects on Windows (`command_windows.unwrap_or(command)` in its hook
1401
- // discovery). rewriteHookCommandsForSkillRoot adds it with a cmd.exe
1402
- // `if exist` guard (form contributed and Windows-tested by @PatrickSys in
1403
- // issue #452; `exit /b` forwards node's errorlevel), so the same
1404
- // .codex/hooks.json is correct on every OS no matter where it was
1405
- // written, and `command` stays the plain POSIX guard.
1406
- // * Claude and Cursor manifests have no per-platform field, so a Windows
1407
- // install moves the existence check into node itself: a `node -e` wrapper
1408
- // that exits 0 when the target is missing and otherwise re-spawns node on
1409
- // it with inherited stdio, forwarding the hook's exit code. Cursor's
1410
- // hooks.json is committable and can be consumed on a teammate's POSIX
1411
- // machine, so the wrapper has to hold there too: it uses only characters
1412
- // that survive PowerShell, cmd.exe (issue #445: shims re-parse through
1413
- // `cmd /C`, which claims < > | & ^ % !), and sh double-quoting alike,
1414
- // with single quotes for the inner string literals.
1415
- const WIN32_HOOK_GUARD_SCRIPT = "const p=process.argv[1];const f=require('fs');if(f.existsSync(p)){const r=require('child_process').spawnSync(process.execPath,[p],{stdio:'inherit'});process.exit(r.status===null?1:r.status);}";
1416
-
1417
- // POSIX single-quote escaping. JSON.stringify is not shell quoting: inside
1418
- // double quotes /bin/sh still expands $(...), backticks, and ${}, and this
1419
- // string is baked into a hook manifest the harness re-executes on every edit,
1420
- // so an install path embedding $(...) would run it repeatedly (issue #476).
1421
- // Windows command forms keep double quotes: cmd.exe treats ' as a literal
1422
- // character and performs no command substitution.
1423
- function shSingleQuote(value) {
1424
- return `'${String(value).replace(/'/g, `'\\''`)}'`;
1425
- }
1426
-
1427
- function windowsHookCommand(quotedPath) {
1428
- return `if exist ${quotedPath} (node ${quotedPath} & exit /b)`;
1429
- }
1430
-
1431
- // `quotedPath` carries one pre-quoted form per target shell: { posix, win32 }.
1432
- function guardHookCommand(quotedPath, provider) {
1433
- // `.agents` (Codex) keeps the POSIX form unconditionally: its Windows
1434
- // consumers read the commandWindows sibling instead.
1435
- if (provider !== '.agents' && process.platform === 'win32') {
1436
- return `node -e "${WIN32_HOOK_GUARD_SCRIPT}" ${quotedPath.win32}`;
1437
- }
1438
- return `[ ! -f ${quotedPath.posix} ] || node ${quotedPath.posix}`;
1439
- }
1440
-
1441
- // Transform bundled hook commands for the actual install target:
1442
- // * absolute — rewrite the (marker) command to the resolved absolute skill
1443
- // path. Required when the manifest is a user/global file (~/.claude/
1444
- // settings.local.json) that fires in EVERY project, so ${CLAUDE_PROJECT_DIR}
1445
- // would resolve per-project to dirs without a skill copy (issue #399); also
1446
- // when a project hook points at a skill installed elsewhere (--scope=global).
1447
- // * otherwise — keep the bundle's own ${CLAUDE_PROJECT_DIR}-relative path,
1448
- // which correctly resolves for a project-scoped install.
1449
- // Either way the command goes through guardHookCommand (POSIX shell guard, or
1450
- // the shell-agnostic node -e guard when installing on Windows), and Codex hook
1451
- // entries additionally get a `commandWindows` sibling for cmd.exe.
1452
- function rewriteHookCommandsForSkillRoot(value, provider, { skillRoot, absolute }) {
1453
- const hookScript = hookScriptPathForProvider(skillRoot, provider);
1454
- // Providers we don't own a `node "PATH"` command hook for (.github, .grok)
1455
- // carry their own portable command forms; leave them untouched.
1456
- if (!hookScript) return value;
1457
-
1458
- // Project-scope installs derive the provider's own project-relative path
1459
- // rather than trusting the bundle token, which for Codex points at
1460
- // `.codex/skills/...` while the CLI installs the skill at `.agents/skills/`.
1461
- // The absolute path comes from the install root (project dir or $HOME), so
1462
- // its POSIX form gets real single-quote escaping (issue #476). The relative
1463
- // form is a per-provider constant and stays double-quoted, because Claude's
1464
- // ${CLAUDE_PROJECT_DIR} token must keep expanding at hook time.
1465
- const relPath = hookScriptRelPathForProvider(provider);
1466
- const quotedPath = absolute
1467
- ? { posix: shSingleQuote(hookScript), win32: JSON.stringify(hookScript) }
1468
- : { posix: JSON.stringify(relPath), win32: JSON.stringify(relPath) };
1469
-
1470
- if (typeof value === 'string') {
1471
- if (!valueHasImpeccableHookMarker(value)) return value;
1472
- return guardHookCommand(quotedPath, provider);
1473
- }
1474
- if (Array.isArray(value)) {
1475
- return value.map(item => rewriteHookCommandsForSkillRoot(item, provider, { skillRoot, absolute }));
1476
- }
1477
- if (value && typeof value === 'object') {
1478
- const next = {};
1479
- for (const [key, child] of Object.entries(value)) {
1480
- next[key] = rewriteHookCommandsForSkillRoot(child, provider, { skillRoot, absolute });
1481
- }
1482
- if (provider === '.agents' && typeof value.command === 'string' && valueHasImpeccableHookMarker(value.command)) {
1483
- next.commandWindows = windowsHookCommand(quotedPath.win32);
1484
- }
1485
- return next;
1486
- }
1487
- return value;
1488
- }
1489
-
1490
- // The file paths the CLI writes hook manifests to (the local override target,
1491
- // e.g. settings.local.json — not the shared sibling).
1492
- function expectedHookDests(root, providers) {
1493
- const targets = Array.isArray(providers) ? providers : [providers];
1494
- return targets.flatMap(provider =>
1495
- (PROVIDER_HOOK_ARTIFACTS[provider] || []).map(({ rel, destProvider, destRel }) =>
1496
- join(root, destProvider, destRel || rel))
1497
- );
1498
- }
1499
-
1500
- // Whether a hook manifest file actually wires up the Impeccable hook. We parse
1501
- // the JSON and scan only the `hooks` subtree (via valueHasImpeccableHookMarker),
1502
- // not the raw file text: an unrelated string elsewhere — e.g. a permissions
1503
- // allow entry that happens to mention the hook path — must not read as a hook.
1504
- function fileHasImpeccableHookMarker(file) {
1505
- if (!existsSync(file)) return false;
1506
- let parsed;
1507
- try {
1508
- parsed = JSON.parse(readFileSync(file, 'utf-8'));
1509
- } catch {
1510
- return false;
1511
- }
1512
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return false;
1513
- if (!parsed.hooks || typeof parsed.hooks !== 'object') return false;
1514
- return valueHasImpeccableHookMarker(parsed.hooks);
1515
- }
1516
-
1517
- // Whether our hook is already wired up for a provider, used to decide if the
1518
- // already-installed fast path should top up a missing hook. We look for the
1519
- // Impeccable marker — not mere file existence — because the target files
1520
- // (settings.local.json, hooks.json) commonly hold unrelated local settings; an
1521
- // existence check would falsely report "installed" and skip repairing a missing
1522
- // hook that `update` would otherwise add. For Claude we also honor our hook
1523
- // living in the shared settings.json sibling (a legacy install or user move).
1524
- function hookInstalledForProvider(root, provider) {
1525
- const artifacts = PROVIDER_HOOK_ARTIFACTS[provider] || [];
1526
- if (artifacts.length === 0) return true;
1527
- return artifacts.every(({ destProvider, rel, destRel }) => {
1528
- const writeRel = destRel || rel;
1529
- if (fileHasImpeccableHookMarker(join(root, destProvider, writeRel))) return true;
1530
- if (writeRel !== rel && fileHasImpeccableHookMarker(join(root, destProvider, rel))) return true;
1531
- return false;
1532
- });
1533
- }
1534
-
1535
- function valueHasImpeccableHookMarker(value) {
1536
- if (typeof value === 'string') {
1537
- return IMPECCABLE_HOOK_COMMAND_MARKERS.some(marker => value.includes(marker));
1538
- }
1539
- if (Array.isArray(value)) return value.some(valueHasImpeccableHookMarker);
1540
- if (value && typeof value === 'object') {
1541
- return Object.values(value).some(valueHasImpeccableHookMarker);
1542
- }
1543
- return false;
1544
- }
1545
-
1546
- function stripImpeccableHookEntry(entry) {
1547
- if (!entry || typeof entry !== 'object') return entry;
1548
- // `command`/`args`: Claude/Codex/Cursor. `bash`/`powershell`: GitHub Copilot's
1549
- // flat entry shape, where the marker lives under the shell-command keys.
1550
- if (valueHasImpeccableHookMarker(entry.command) || valueHasImpeccableHookMarker(entry.args)
1551
- || valueHasImpeccableHookMarker(entry.bash) || valueHasImpeccableHookMarker(entry.powershell)) {
1552
- return null;
1553
- }
1554
- if (!Array.isArray(entry.hooks)) return entry;
1555
-
1556
- const strippedHooks = entry.hooks
1557
- .map(stripImpeccableHookEntry)
1558
- .filter(Boolean);
1559
-
1560
- if (strippedHooks.length === 0 && entry.hooks.some(valueHasImpeccableHookMarker)) {
1561
- return null;
1562
- }
1563
-
1564
- return { ...entry, hooks: strippedHooks };
1565
- }
1566
-
1567
- function stripImpeccableHookEntries(entries) {
1568
- if (!Array.isArray(entries)) return [];
1569
- return entries
1570
- .map(stripImpeccableHookEntry)
1571
- .filter(Boolean);
1572
- }
1573
-
1574
- // Remove our hook from a manifest file, preserving any unrelated content. Used
1575
- // when the hook is honored in the shared settings.json so a stale machine-local
1576
- // copy doesn't make the detector run twice. Drops the file if nothing but our
1577
- // hook scaffolding remains. Returns true if it changed anything.
1578
- function pruneImpeccableHookFromManifest(manifestPath) {
1579
- if (!fileHasImpeccableHookMarker(manifestPath)) return false;
1580
- let parsed;
1581
- try {
1582
- parsed = JSON.parse(readFileSync(manifestPath, 'utf-8'));
1583
- } catch {
1584
- return false;
1585
- }
1586
-
1587
- const existingHooks = parsed.hooks && typeof parsed.hooks === 'object' && !Array.isArray(parsed.hooks)
1588
- ? parsed.hooks
1589
- : {};
1590
- const cleanedHooks = {};
1591
- for (const [event, entries] of Object.entries(existingHooks)) {
1592
- const kept = stripImpeccableHookEntries(entries);
1593
- if (kept.length > 0) cleanedHooks[event] = kept;
1594
- }
1595
-
1596
- const next = { ...parsed };
1597
- if (Object.keys(cleanedHooks).length > 0) {
1598
- next.hooks = cleanedHooks;
1599
- } else {
1600
- // Our hook was the only thing here; drop the hook-manifest scaffolding too.
1601
- delete next.hooks;
1602
- delete next.description;
1603
- delete next.version;
1604
- }
1605
-
1606
- if (Object.keys(next).length === 0) {
1607
- rmSync(manifestPath, { force: true });
1608
- } else {
1609
- writeFileSync(manifestPath, `${JSON.stringify(next, null, 2)}\n`);
1610
- }
1611
- return true;
1612
- }
1613
-
1614
- function mergeHookManifests(existing, fresh) {
1615
- const existingObject = existing && typeof existing === 'object' && !Array.isArray(existing) ? existing : {};
1616
- const freshObject = fresh && typeof fresh === 'object' && !Array.isArray(fresh) ? fresh : {};
1617
- const existingHooks = existingObject.hooks && typeof existingObject.hooks === 'object' && !Array.isArray(existingObject.hooks)
1618
- ? existingObject.hooks
1619
- : {};
1620
- const freshHooks = freshObject.hooks && typeof freshObject.hooks === 'object' && !Array.isArray(freshObject.hooks)
1621
- ? freshObject.hooks
1622
- : {};
1623
-
1624
- const merged = { ...existingObject, hooks: {} };
1625
- if (freshObject.version !== undefined) merged.version = freshObject.version;
1626
- if (freshObject.description !== undefined) merged.description = freshObject.description;
1627
-
1628
- const hookEvents = new Set([...Object.keys(existingHooks), ...Object.keys(freshHooks)]);
1629
- for (const event of hookEvents) {
1630
- const preserved = stripImpeccableHookEntries(existingHooks[event]);
1631
- const added = Array.isArray(freshHooks[event]) ? freshHooks[event] : [];
1632
- const mergedEntries = [...preserved, ...added];
1633
- if (mergedEntries.length > 0) merged.hooks[event] = mergedEntries;
1634
- }
1635
-
1636
- return merged;
1637
- }
1638
-
1639
- function readJsonFile(filePath, description) {
1640
- try {
1641
- return JSON.parse(readFileSync(filePath, 'utf-8'));
1642
- } catch (e) {
1643
- throw new Error(`${description} is not valid JSON: ${filePath}. ${e.message}`);
1644
- }
1645
- }
1646
-
1647
- function copyProviderHooks(bundleDir, root, providers, { force = false, skillRoot = root } = {}) {
1648
- const targets = Array.isArray(providers) ? providers : [providers];
1649
- const written = [];
1650
- for (const provider of targets) {
1651
- for (const { src, dest, sharedDest } of hookArtifactsForProvider(bundleDir, root, provider)) {
1652
- if (!existsSync(src)) continue;
1653
-
1654
- // Leave-it-never-duplicate: our hook already lives in the team-shared
1655
- // settings.json (a legacy install or a deliberate user move). Honor it in
1656
- // place and skip the local write — but first strip any stale copy from the
1657
- // local override, or Claude Code would load both and run the detector
1658
- // twice per edit.
1659
- if (sharedDest && fileHasImpeccableHookMarker(sharedDest)) {
1660
- pruneImpeccableHookFromManifest(dest);
1661
- continue;
1662
- }
1663
-
1664
- const freshManifest = readJsonFile(src, 'Bundled hook manifest');
1665
- // Rewrite to an absolute skill path when the skill lives elsewhere than
1666
- // this manifest's root (--scope=global project hook) OR when the manifest
1667
- // itself is a user/global file. A global settings file fires in every
1668
- // project, so ${CLAUDE_PROJECT_DIR} there crashes Node wherever no local
1669
- // skill copy exists (issue #399); the resolved absolute path is correct
1670
- // for the one global skill it targets.
1671
- const absolute = skillRoot !== root || isHomeDir(root);
1672
- const fresh = rewriteHookCommandsForSkillRoot(freshManifest, provider, { skillRoot, absolute });
1673
- let next = fresh;
1674
-
1675
- if (existsSync(dest)) {
1676
- try {
1677
- const existing = JSON.parse(readFileSync(dest, 'utf-8'));
1678
- next = mergeHookManifests(existing, fresh);
1679
- } catch {
1680
- if (!force) {
1681
- throw new Error(`Existing hook manifest is not valid JSON: ${dest}. Re-run with --force to replace it.`);
1682
- }
1683
- writeFileSync(`${dest}.bak`, readFileSync(dest));
1684
- next = fresh;
1685
- }
1686
- }
1687
-
1688
- mkdirSync(dirname(dest), { recursive: true });
1689
- writeFileSync(dest, `${JSON.stringify(next, null, 2)}\n`);
1690
- written.push(provider);
1691
- }
1692
- }
1693
- return [...new Set(written)];
1694
- }
1695
-
1696
- const HOOK_EXPLAINER = [
1697
- '',
1698
- 'Impeccable can install a design hook for this project. In Claude/Codex it',
1699
- 'checks UI files after edits; in Cursor it checks proposed writes before they',
1700
- 'land and can block writes with detector findings. It feeds results back to',
1701
- 'your agent so design slop gets caught as you build. Change it later with',
1702
- '/impeccable hooks on|off.',
1703
- '',
1704
- ].join('\n');
1705
-
1706
- // Decide whether to install the design hook. Prompts once (default yes) the
1707
- // first time, records the answer in .impeccable/config.local.json, and never
1708
- // re-asks: a recorded decision or an already-installed hook short-circuits, and
1709
- // non-interactive runs keep the historical install-by-default behavior.
1710
- async function decideHookInstall(root, targets, { yes } = {}) {
1711
- if (targets.length === 0) return false;
1712
- const consent = getHookConsent(root);
1713
- if (consent === 'declined') return false;
1714
- if (consent === 'accepted') return true;
1715
- // Existing hook users (hook already wired up) are never nagged.
1716
- if (targets.length > 0 && targets.every(provider => hookInstalledForProvider(root, provider))) {
1717
- return true;
1718
- }
1719
- // Undecided and not yet installed. Non-interactive (-y or no TTY) keeps the
1720
- // historical default-on behavior without recording a (re-promptable) decision.
1721
- if (yes || !process.stdin.isTTY) return true;
1722
-
1723
- process.stdout.write(HOOK_EXPLAINER);
1724
- const ans = await ask('Install the design hook? (Y/n) ');
1725
- const accepted = !(ans === 'n' || ans === 'no');
1726
- setHookConsent(root, accepted ? 'accepted' : 'declined');
1727
- return accepted;
1728
- }
1729
-
1730
- function resolveLinkSource(sourceValue, root) {
1731
- const sourcePath = sourceValue || '.impeccable';
1732
- const checkoutRoot = isAbsolute(sourcePath) ? sourcePath : resolve(root, sourcePath);
1733
- const universalRoot = join(checkoutRoot, 'dist', 'universal');
1734
- if (existsSync(universalRoot)) {
1735
- return { checkoutRoot, bundleRoot: universalRoot };
1736
- }
1737
- if (PROVIDER_DIRS.some(provider => existsSync(join(checkoutRoot, provider, 'skills')))) {
1738
- return { checkoutRoot, bundleRoot: checkoutRoot };
1739
- }
1740
- throw new Error(`Could not find compiled skills in ${sourcePath}. Expected dist/universal/ or provider skill folders.`);
1741
- }
1742
-
1743
- function pathExistsOrLink(path) {
1744
- try {
1745
- lstatSync(path);
1746
- return true;
1747
- } catch {
1748
- return false;
1749
- }
1750
- }
1751
-
1752
- function isSymlinkTo(dest, expectedSource) {
1753
- try {
1754
- if (!lstatSync(dest).isSymbolicLink()) return false;
1755
- const target = readlinkSync(dest);
1756
- const resolvedTarget = resolve(dirname(dest), target);
1757
- return realpathSync(resolvedTarget) === realpathSync(expectedSource);
1758
- } catch {
1759
- return false;
1760
- }
1761
- }
1762
-
1763
- function resolveUniqueLinkTargets(root, targets) {
1764
- const seen = new Set();
1765
- const unique = [];
1766
- for (const provider of targets) {
1767
- const localSkillsDir = join(root, provider, 'skills');
1768
- mkdirSync(localSkillsDir, { recursive: true });
1769
- const real = realpathSync(localSkillsDir);
1770
- if (seen.has(real)) continue;
1771
- seen.add(real);
1772
- unique.push({ provider, localSkillsDir });
1773
- }
1774
- return unique;
1775
- }
1776
-
1777
- function linkProviderSkills(bundleRoot, root, targets, { force = false } = {}) {
1778
- let linked = 0;
1779
- let already = 0;
1780
- let skipped = 0;
1781
-
1782
- for (const { provider, localSkillsDir } of resolveUniqueLinkTargets(root, targets)) {
1783
- const srcDir = join(bundleRoot, provider, 'skills');
1784
- if (!existsSync(srcDir)) continue;
1785
-
1786
- for (const skill of readdirSync(srcDir, { withFileTypes: true })) {
1787
- if (!skill.isDirectory()) continue;
1788
- const src = join(srcDir, skill.name);
1789
- const dest = join(localSkillsDir, skill.name);
1790
-
1791
- if (pathExistsOrLink(dest)) {
1792
- if (isSymlinkTo(dest, src)) {
1793
- already++;
1794
- continue;
1795
- }
1796
- if (!force) {
1797
- console.warn(`Skipped existing ${provider}/skills/${skill.name}. Use --force to replace it with a link.`);
1798
- skipped++;
1799
- continue;
1800
- }
1801
- rmSync(dest, { recursive: true, force: true });
1802
- }
1803
-
1804
- const target = relative(dirname(dest), src) || '.';
1805
- symlinkSync(target, dest, 'dir');
1806
- linked++;
1807
- }
1808
- }
1809
-
1810
- return { linked, already, skipped };
1811
- }
1812
-
1813
- async function link(flags) {
1814
- const force = flags.includes('--force');
1815
- const yes = flags.includes('-y') || flags.includes('--yes');
1816
- const sourceValue = getFlagValue(flags, '--source');
1817
- const providersValue = getFlagValue(flags, '--providers');
1818
- const root = findProjectRoot();
1819
-
1820
- let source;
1821
- try {
1822
- source = resolveLinkSource(sourceValue, root);
1823
- } catch (e) {
1824
- console.error(e.message);
1825
- process.exit(1);
1826
- }
1827
-
1828
- const targets = resolveInstallTargets(root, providersValue);
1829
- if (targets.length === 0) {
1830
- console.error('Could not determine a target harness folder.');
1831
- console.error('Pass one explicitly, e.g. --providers=claude,cursor');
1832
- process.exit(1);
1833
- }
1834
-
1835
- if (!yes) {
1836
- console.log(`Source checkout: ${source.checkoutRoot}`);
1837
- console.log(`Target harness folder(s): ${targets.join(', ')}`);
1838
- const ans = await ask(`Link impeccable skills into ${targets.length} folder(s)? (Y/n) `);
1839
- if (ans === 'n' || ans === 'no') {
1840
- console.log('Aborted. Re-run with --providers=<names> to choose explicitly (e.g. --providers=claude,cursor).');
1841
- process.exit(0);
1842
- }
1843
- }
1844
-
1845
- const result = linkProviderSkills(source.bundleRoot, root, targets, { force });
1846
- if (result.linked === 0 && result.already === 0) {
1847
- if (result.skipped > 0) {
1848
- console.error('Nothing was linked because matching skill folders already exist.');
1849
- console.error('Existing skills were left untouched. Re-run with --force to replace them with links.');
1850
- } else {
1851
- console.error(`Nothing was linked: ${source.bundleRoot} had no variants for ${targets.join(', ')}.`);
1852
- }
1853
- process.exit(1);
1854
- }
1855
-
1856
- const parts = [];
1857
- if (result.linked > 0) parts.push(`${result.linked} linked`);
1858
- if (result.already > 0) parts.push(`${result.already} already linked`);
1859
- if (result.skipped > 0) parts.push(`${result.skipped} skipped`);
1860
- console.log(`Linked impeccable into: ${targets.join(', ')} (${parts.join(', ')}).`);
1861
- console.log('Update with `git submodule update --remote` from your project root, then rerun this command if new skills are added.\n');
1862
- }
1863
-
1864
- async function install(flags) {
1865
- const force = flags.includes('--force');
1866
- const yes = flags.includes('-y') || flags.includes('--yes');
1867
- const installHooks = !flags.includes('--no-hooks');
1868
- const projectRoot = findProjectRoot();
1869
- if (!yes) printInstallIntro();
1870
- let plan;
1871
- try {
1872
- plan = await chooseInstallPlan(projectRoot, flags, { yes });
1873
- } catch (e) {
1874
- if (isPromptAbortError(e)) throw e;
1875
- console.error(e.message);
1876
- console.error('Pass providers explicitly, e.g. --providers=claude,cursor');
1877
- process.exit(1);
1878
- }
1879
-
1880
- const { targets, installRoot, hookRoot, scope, explicit } = plan;
1881
- const existing = isAlreadyInstalled(installRoot, scope);
1882
- const installedTargets = existing ? findInstalledProviders(installRoot, scope) : [];
1883
- // An explicit --providers list is a per-target request: a selected provider
1884
- // with no install yet gets a fresh install instead of tripping the global
1885
- // "already installed" early exit (issue #500). When every selected provider
1886
- // is missing, skip the update branch entirely and take the fresh-install path.
1887
- const missingSelectedTargets = (existing && !force && explicit)
1888
- ? targets.filter(provider => !installedTargets.includes(provider))
1889
- : [];
1890
-
1891
- if (existing && !force && missingSelectedTargets.length < targets.length) {
1892
- console.log(`Impeccable skills are already installed (found in ${existing}/).`);
1893
- const selectedInstalledTargets = targets.filter(provider => installedTargets.includes(provider));
1894
- const linkedTargets = findLinkedProviders(installRoot, selectedInstalledTargets, scope);
1895
- const copyTargets = selectedInstalledTargets.filter(provider => !linkedTargets.includes(provider));
1896
- const hookTargets = [...selectedInstalledTargets, ...missingSelectedTargets];
1897
- const wantHooks = installHooks && await decideHookInstall(hookRoot, hookTargets, { yes });
1898
- let bundleDir;
1899
- try {
1900
- if (linkedTargets.length > 0) {
1901
- console.log(`Linked skills found in: ${linkedTargets.join(', ')}`);
1902
- console.log('Update the source checkout with `git submodule update --remote`, then rerun `npx impeccable link --source=.impeccable` if new skills are added.');
1903
- if (copyTargets.length > 0) console.log(`Continuing with copied installs in: ${copyTargets.join(', ')}\n`);
1904
- }
1905
-
1906
- let updated = 0;
1907
- const missingHookTargets = wantHooks
1908
- ? hookTargets.filter(provider => !hookInstalledForProvider(hookRoot, provider))
1909
- : [];
1910
- let updateCheckSkipped = false;
1911
- if (copyTargets.length > 0 || missingHookTargets.length > 0 || missingSelectedTargets.length > 0) {
1912
- try {
1913
- bundleDir = await downloadAndExtractBundle();
1914
- } catch (e) {
1915
- if (missingHookTargets.length > 0 || missingSelectedTargets.length > 0) throw e;
1916
- updateCheckSkipped = true;
1917
- console.log(`Could not check for skill updates: ${e.message}`);
1918
- }
1919
- }
1920
-
1921
- if (!updateCheckSkipped && copyTargets.length > 0 && !isUpToDate(installRoot, copyTargets, bundleDir, scope)) {
1922
- migrateUnprefixImpeccable(installRoot, scope);
1923
- updated = refreshProviderSkills(bundleDir, installRoot, copyTargets, scope);
1924
- reportProviderAgents(copyProviderAgents(bundleDir, installRoot, copyTargets, { scope }));
1925
- const v = getSkillsVersion(installRoot, scope);
1926
- console.log(`Updated ${updated} skill(s)${v ? ` to v${v}` : ''}.`);
1927
- }
1928
-
1929
- let freshWritten = 0;
1930
- if (!updateCheckSkipped && missingSelectedTargets.length > 0) {
1931
- freshWritten = copyProviderSkills(bundleDir, installRoot, missingSelectedTargets, { scope });
1932
- if (freshWritten === 0) {
1933
- console.error(`Nothing was installed: the bundle had no variants for ${missingSelectedTargets.join(', ')}.`);
1934
- process.exit(1);
1935
- }
1936
- console.log(`Installed impeccable into: ${missingSelectedTargets.join(', ')} (${scope === 'user' ? 'global' : 'project'})`);
1937
- reportProviderAgents(copyProviderAgents(bundleDir, installRoot, missingSelectedTargets, { scope }));
1938
- }
1939
-
1940
- const writtenHookTargets = missingHookTargets.length > 0
1941
- ? copyProviderHooks(bundleDir, hookRoot, missingHookTargets, { skillRoot: installRoot })
1942
- : [];
1943
- if (writtenHookTargets.length > 0) console.log(`Installed hooks into: ${writtenHookTargets.join(', ')}`);
1944
-
1945
- if (updateCheckSkipped) {
1946
- console.log('Existing skills were left unchanged.');
1947
- console.log('Run with --force to reinstall.\n');
1948
- } else if (updated === 0 && writtenHookTargets.length === 0 && freshWritten === 0) {
1949
- const v = getSkillsVersion(installRoot, scope);
1950
- console.log(`Skills are up to date${v ? ` (v${v})` : ''}.`);
1951
- console.log('Run with --force to reinstall.\n');
1952
- } else {
1953
- console.log('Done!\n');
1954
- }
1955
- } catch (e) {
1956
- console.error(`Install check failed: ${e.message}`);
1957
- process.exit(1);
1958
- } finally {
1959
- if (bundleDir) rmSync(bundleDir, { recursive: true, force: true });
1960
- }
1961
- process.exit(0);
1962
- }
1963
-
1964
- // Decide which harness folders to install into, then copy each harness's own
1965
- // compiled variant from the universal bundle. We deliberately do NOT shell out
1966
- // to `npx skills add`: its name-based discovery can install the uncompiled
1967
- // source, and its symlink default points every harness at one shared variant.
1968
- // Copying per-provider variants is the only correct install for this skill.
1969
- if (targets.length === 0) {
1970
- console.error('Could not determine a target harness folder.');
1971
- console.error('Pass one explicitly, e.g. --providers=.claude,.cursor');
1972
- process.exit(1);
1973
- }
1974
-
1975
- const wantHooks = installHooks && await decideHookInstall(hookRoot, targets, { yes });
1976
-
1977
- console.log('\nDownloading impeccable skills...');
1978
- let bundleDir;
1979
- try {
1980
- bundleDir = await downloadAndExtractBundle();
1981
- } catch (e) {
1982
- console.error(`Download failed: ${e.message}`);
1983
- process.exit(1);
1984
- }
1985
-
1986
- // Retire any old `i-`-prefixed install so the fresh copy lands on the
1987
- // canonical `impeccable` dir instead of orphaning the prefixed one.
1988
- migrateUnprefixImpeccable(installRoot, scope);
1989
-
1990
- let written = 0;
1991
- let hookTargets = [];
1992
- let agentResults = [];
1993
- try {
1994
- written = copyProviderSkills(bundleDir, installRoot, targets, { scope });
1995
- agentResults = copyProviderAgents(bundleDir, installRoot, targets, { scope });
1996
- hookTargets = wantHooks ? copyProviderHooks(bundleDir, hookRoot, targets, { force, skillRoot: installRoot }) : [];
1997
- } catch (e) {
1998
- rmSync(bundleDir, { recursive: true, force: true });
1999
- console.error(`Install failed: ${e.message}`);
2000
- process.exit(1);
2001
- }
2002
- rmSync(bundleDir, { recursive: true, force: true });
2003
-
2004
- if (written === 0) {
2005
- console.error(`Nothing was installed: the bundle had no variants for ${targets.join(', ')}.`);
2006
- process.exit(1);
2007
- }
2008
- console.log(`Installed impeccable into: ${targets.join(', ')} (${scope === 'user' ? 'global' : 'project'})`);
2009
- reportProviderAgents(agentResults);
2010
- if (hookTargets.length > 0) console.log(`Installed hooks into: ${hookTargets.join(', ')}`);
2011
-
2012
- console.log('\nDone! Now type /impeccable init in your AI coding agent\'s chat (not in this terminal) to set up design context.\n');
2013
- }
2014
-
2015
- // ─── skills update ────────────────────────────────────────────────────────────
2016
-
2017
- function findProjectRoot() {
2018
- let dir = process.cwd();
2019
- while (dir !== dirname(dir)) {
2020
- if (existsSync(join(dir, '.git'))) return dir;
2021
- dir = dirname(dir);
2022
- }
2023
- return process.cwd();
2024
- }
2025
-
2026
- function findInstalledProviders(root, scope) {
2027
- const found = [];
2028
- for (const d of PROVIDER_DIRS) {
2029
- for (const skillsDir of existingSkillsDirs(root, d, scope)) {
2030
- try {
2031
- const entries = readdirSync(skillsDir);
2032
- if (entries.some(name => isSkillDir(skillsDir, name))) {
2033
- found.push(d);
2034
- break;
2035
- }
2036
- } catch {}
2037
- }
2038
- }
2039
- return found;
2040
- }
2041
-
2042
- // Like findInstalledProviders, but only counts a provider whose skills dir
2043
- // actually holds the IMPECCABLE skill (canonical, prefixed, or legacy teach-).
2044
- // `update` uses this so it never mistakes a repo that vendors OTHER first-party
2045
- // skills under .claude/skills for an impeccable install and drops a copy in
2046
- // (issue #399, part 2).
2047
- function findImpeccableProviders(root, scope) {
2048
- const found = [];
2049
- for (const d of PROVIDER_DIRS) {
2050
- for (const skillsDir of existingSkillsDirs(root, d, scope)) {
2051
- let entries;
2052
- try { entries = readdirSync(skillsDir); } catch { continue; }
2053
- if (entries.some(e =>
2054
- e === 'impeccable' || e.endsWith('-impeccable') ||
2055
- e === 'teach-impeccable' || e.endsWith('-teach-impeccable')
2056
- )) {
2057
- found.push(d);
2058
- break;
2059
- }
2060
- }
2061
- }
2062
- return found;
2063
- }
2064
-
2065
- // Resolve which install `skills update` should refresh: project-level (the CWD's
2066
- // git root) or user-level (~/.claude etc.). Returns a plain descriptor; the
2067
- // caller handles the interactive both-exist prompt via `ambiguous`.
2068
- function resolveUpdateTarget({ projectRoot, home, explicitScope }) {
2069
- // A home-rooted repo (a dotfiles checkout at $HOME) overlaps project and user
2070
- // installs under one root; keep the historical unscoped scan so overlapping
2071
- // layouts (e.g. Pi's ~/.pi/skills and ~/.pi/agent/skills) both refresh.
2072
- const homeRooted = isHomeDir(projectRoot);
2073
- if (homeRooted && !explicitScope) {
2074
- const providers = findInstalledProviders(home);
2075
- return providers.length ? { root: home, scope: undefined, providers, scopeLabel: 'user level' } : null;
2076
- }
2077
-
2078
- const projectProviders = homeRooted ? [] : findImpeccableProviders(projectRoot, 'project');
2079
- const userProviders = findImpeccableProviders(home, 'user');
2080
-
2081
- if (explicitScope === 'user') {
2082
- return userProviders.length
2083
- ? { root: home, scope: 'user', providers: userProviders, scopeLabel: 'user level' }
2084
- : null;
2085
- }
2086
- if (explicitScope === 'project') {
2087
- return projectProviders.length
2088
- ? { root: projectRoot, scope: 'project', providers: projectProviders, scopeLabel: 'this project' }
2089
- : null;
2090
- }
2091
- if (projectProviders.length && userProviders.length) {
2092
- return { ambiguous: true, projectRoot, home, projectProviders, userProviders };
2093
- }
2094
- if (projectProviders.length) {
2095
- return { root: projectRoot, scope: 'project', providers: projectProviders, scopeLabel: 'this project' };
2096
- }
2097
- if (userProviders.length) {
2098
- return { root: home, scope: 'user', providers: userProviders, scopeLabel: 'user level' };
2099
- }
2100
- return null;
2101
- }
2102
-
2103
- function findLinkedProviders(root, providers, scope) {
2104
- return providers.filter(provider => {
2105
- for (const skillsDir of providerSkillsDirCandidates(root, provider, scope)) {
2106
- const skillDir = join(skillsDir, 'impeccable');
2107
- try {
2108
- if (lstatSync(skillDir).isSymbolicLink()) return true;
2109
- } catch {}
2110
- }
2111
- return false;
2112
- });
2113
- }
2114
-
2115
- function getModifiedSkillFiles(root, providerDirs) {
2116
- // Use git to check if any skill files have local modifications
2117
- const modified = [];
2118
- try {
2119
- const status = execSync('git status --porcelain', { cwd: root, encoding: 'utf8' });
2120
- for (const line of status.split('\n')) {
2121
- if (!line.trim()) continue;
2122
- const file = line.substring(3);
2123
- for (const d of providerDirs) {
2124
- if (file.startsWith(`${d}/skills/`)) {
2125
- const flag = line.substring(0, 2).trim();
2126
- modified.push({ file, flag });
2127
- }
2128
- }
2129
- }
2130
- } catch {
2131
- // Not a git repo or git not available
2132
- }
2133
- return modified;
2134
- }
2135
-
2136
- function downloadFile(url, dest) {
2137
- return new Promise((resolve, reject) => {
2138
- const file = createWriteStream(dest);
2139
- get(url, (res) => {
2140
- if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
2141
- // Follow redirect
2142
- get(res.headers.location, (res2) => {
2143
- res2.pipe(file);
2144
- file.on('finish', () => { file.close(); resolve(); });
2145
- }).on('error', reject);
2146
- return;
2147
- }
2148
- if (res.statusCode !== 200) {
2149
- reject(new Error(`HTTP ${res.statusCode}`));
2150
- return;
2151
- }
2152
- res.pipe(file);
2153
- file.on('finish', () => { file.close(); resolve(); });
2154
- }).on('error', reject);
2155
- });
2156
- }
2157
-
2158
- async function update(flags = []) {
2159
- const yes = flags.includes('-y') || flags.includes('--yes');
2160
- const force = flags.includes('--force');
2161
- const installHooks = !flags.includes('--no-hooks');
2162
- const scopeValue = getInstallScopeValue(flags);
2163
- const explicitScope = normalizeInstallScope(scopeValue);
2164
- if (scopeValue && !explicitScope) {
2165
- console.error(`Unknown update scope: ${scopeValue}. Use --project or --user.`);
2166
- process.exit(1);
2167
- }
2168
-
2169
- // Download the latest skills directly from impeccable.style.
2170
- // We skip `npx skills update` because it has a known upstream bug
2171
- // (vercel-labs/skills#775) where it can't find the lock file.
2172
- const projectRoot = findProjectRoot();
2173
- const home = homedir();
2174
-
2175
- let target = resolveUpdateTarget({ projectRoot, home, explicitScope });
2176
- if (!target) {
2177
- if (explicitScope) {
2178
- const where = explicitScope === 'user' ? `user level (${formatPathForDisplay(home)})` : `this project (${projectRoot})`;
2179
- console.log(`No impeccable skill folders found at the ${where}.`);
2180
- } else {
2181
- console.log('No impeccable skill folders found in this project or at the user level.');
2182
- }
2183
- console.log('Run `npx impeccable install` to install first.');
2184
- process.exit(1);
2185
- }
2186
-
2187
- // Both a project and a user-level install exist and no scope was given. Never
2188
- // silently pick (issue #399, part 2): prompt when interactive, else default to
2189
- // the project and say how to target the other.
2190
- if (target.ambiguous) {
2191
- console.log('Impeccable is installed both here and at the user level:');
2192
- console.log(` project ${projectRoot} (${target.projectProviders.join(', ')})`);
2193
- console.log(` user level ${formatPathForDisplay(home)} (${target.userProviders.join(', ')})`);
2194
- let pickUser = false;
2195
- if (!yes && process.stdin.isTTY) {
2196
- const ans = await ask('Update which? [project]/user: ');
2197
- pickUser = ['user', 'u', 'global', 'home'].includes(ans);
2198
- } else {
2199
- console.log('Defaulting to the project. Re-run with --user to update the user-level install instead.');
2200
- }
2201
- target = pickUser
2202
- ? { root: home, scope: 'user', providers: target.userProviders, scopeLabel: 'user level' }
2203
- : { root: projectRoot, scope: 'project', providers: target.projectProviders, scopeLabel: 'this project' };
2204
- }
2205
-
2206
- const { root, scope } = target;
2207
- console.log(`Updating the ${target.scopeLabel} install: ${formatPathForDisplay(root)} (${target.providers.join(', ')})`);
2208
- const providers = target.providers;
2209
- const linkedProviders = findLinkedProviders(root, providers, scope);
2210
- const copyProviders = providers.filter(provider => !linkedProviders.includes(provider));
2211
-
2212
- if (linkedProviders.length > 0) {
2213
- console.log(`Linked skills found in: ${linkedProviders.join(', ')}`);
2214
- console.log('Update the source checkout with `git submodule update --remote`, then rerun `npx impeccable link --source=.impeccable` if new skills are added.');
2215
- if (copyProviders.length === 0) process.exit(0);
2216
- console.log(`Continuing with copied installs in: ${copyProviders.join(', ')}\n`);
2217
- }
2218
-
2219
- console.log('Checking for updates...');
2220
-
2221
- let tmpDir;
2222
- try {
2223
- tmpDir = await downloadAndExtractBundle();
2224
- } catch (e) {
2225
- console.error(`Download failed: ${e.message}`);
2226
- process.exit(1);
2227
- }
2228
-
2229
- // Compare local vs remote -- skip if already up to date
2230
- if (isUpToDate(root, copyProviders, tmpDir, scope)) {
2231
- try {
2232
- const wantHooks = installHooks && await decideHookInstall(root, copyProviders, { yes });
2233
- const hookTargets = wantHooks ? copyProviderHooks(tmpDir, root, copyProviders, { force }) : [];
2234
- rmSync(tmpDir, { recursive: true, force: true });
2235
- const v = getSkillsVersion(root, scope);
2236
- console.log(`Skills are up to date${v ? ` (v${v})` : ''}.`);
2237
- if (hookTargets.length > 0) console.log(`Installed hooks into: ${hookTargets.join(', ')}`);
2238
- console.log('Nothing else to do.');
2239
- process.exit(0);
2240
- } catch (e) {
2241
- rmSync(tmpDir, { recursive: true, force: true });
2242
- console.error(`Update failed: ${e.message}`);
2243
- process.exit(1);
2244
- }
2245
- }
2246
-
2247
- console.log(`Found skills in: ${copyProviders.join(', ')}`);
2248
-
2249
- if (!yes) {
2250
- const ans = await ask(`Update skills in ${copyProviders.length} provider folder(s)? (Y/n) `);
2251
- if (ans === 'n' || ans === 'no') {
2252
- rmSync(tmpDir, { recursive: true, force: true });
2253
- console.log('Aborted.');
2254
- process.exit(0);
2255
- }
2256
- }
2257
-
2258
- try {
2259
-
2260
- // Retire any old `i-`-prefixed install up front so the refresh lands on the
2261
- // canonical `impeccable` dir rather than orphaning the prefixed copy.
2262
- const migrated = migrateUnprefixImpeccable(root, scope);
2263
- if (migrated > 0) console.log('Migrated a prefixed install back to /impeccable (the i- prefix is no longer used).');
2264
-
2265
- const updated = refreshProviderSkills(tmpDir, root, copyProviders, scope);
2266
- reportProviderAgents(copyProviderAgents(tmpDir, root, copyProviders, { scope }));
2267
- const wantHooks = installHooks && await decideHookInstall(root, providers, { yes });
2268
- const hookTargets = wantHooks ? copyProviderHooks(tmpDir, root, providers, { force }) : [];
2269
-
2270
- rmSync(tmpDir, { recursive: true, force: true });
2271
-
2272
- const v = getSkillsVersion(root, scope);
2273
- console.log(`Updated ${updated} skill(s)${v ? ` to v${v}` : ''}.`);
2274
- if (hookTargets.length > 0) console.log(`Installed hooks into: ${hookTargets.join(', ')}`);
2275
- console.log('Done!\n');
2276
- } catch (e) {
2277
- console.error(`Update failed: ${e.message}`);
2278
- if (tmpDir) rmSync(tmpDir, { recursive: true, force: true });
2279
- process.exit(1);
2280
- }
2281
- }
2282
-
2283
- function copyDirSync(src, dest) {
2284
- mkdirSync(dest, { recursive: true });
2285
- for (const entry of readdirSync(src, { withFileTypes: true })) {
2286
- const s = join(src, entry.name);
2287
- const d = join(dest, entry.name);
2288
- if (entry.isDirectory()) {
2289
- copyDirSync(s, d);
2290
- } else {
2291
- writeFileSync(d, readFileSync(s));
2292
- }
2293
- }
2294
- }
2295
-
2296
- // ─── Test surface ───────────────────────────────────────────────────────────
2297
- // Exported so the test suite exercises the real implementation rather than a
2298
- // reimplementation in a helper script (which is how bugs slip through).
2299
- export {
2300
- collectInstallDetections,
2301
- copyProviderAgents,
2302
- copyProviderHooks,
2303
- copyProviderSkills,
2304
- decideHookInstall,
2305
- expectedHookDests,
2306
- extractZip,
2307
- formatInstallDetectionLines,
2308
- hermesGlobalHome,
2309
- HOME_SKILLS_DIR_OVERRIDES,
2310
- linkProviderSkills,
2311
- mergeHookManifests,
2312
- migrateUnprefixImpeccable,
2313
- resolveInstallTargets,
2314
- resolveLinkSource,
2315
- };
2316
-
2317
- // ─── Router ───────────────────────────────────────────────────────────────────
2318
-
2319
- export async function run(args) {
2320
- const sub = args[0];
2321
-
2322
- if (!sub || sub === 'help' || sub === '--help' || sub === '-h') {
2323
- await showHelp();
2324
- } else if (sub === 'install') {
2325
- await install(args.slice(1));
2326
- } else if (sub === 'link') {
2327
- await link(args.slice(1));
2328
- } else if (sub === 'update') {
2329
- await update(args.slice(1));
2330
- } else if (sub === 'check') {
2331
- await check();
2332
- } else {
2333
- console.error(`Unknown skills command: ${sub}`);
2334
- console.error(`Run 'impeccable --help' for available commands.`);
2335
- process.exit(1);
2336
- }
2337
- }