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