@rbbtsn0w/adg 0.8.0-beta.4 → 0.8.0-beta.6

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,29 +1,24 @@
1
1
  import { existsSync, readdirSync } from 'fs';
2
+ import { spawnSync } from 'child_process';
2
3
  import { join, dirname, relative, sep } from 'path';
3
4
  import { fileURLToPath } from 'url';
4
5
  import * as p from '@clack/prompts';
5
6
  import pc from 'picocolors';
6
7
  import { readSkillLock, writeSkillLock, getGitHubToken } from "./skill-lock.js";
7
8
  import { computeSkillFolderHash, readLocalLock } from "./local-lock.js";
8
- import { formatSourceInput, buildUpdateInstallSource, buildLocalUpdateSource, } from "./update-source.js";
9
- import { cloneRepo, cleanupTempDir } from "./git.js";
9
+ import { formatSourceInput, buildUpdateInstallSource, buildLocalUpdateSource, buildLocalCloneSource, shouldUseFullDepthForUpdate, } from "./update-source.js";
10
+ import { cloneRepo, cleanupTempDir, getGitTreeHash } from "./git.js";
10
11
  import { discoverSkills } from "./skills.js";
11
- import { fetchRepoTree, findSkillMdPaths, getSkillFolderHashFromTree } from "./blob.js";
12
+ import { fetchRepoTree, getSkillFolderHashFromTree } from "./blob.js";
13
+ import { wellKnownProvider, computeWellKnownSkillDigest } from "./providers/index.js";
12
14
  import { removeCommand } from "./remove.js";
13
15
  import { sanitizeMetadata } from "./sanitize.js";
14
16
  import { track, getTracer } from "./telemetry.js";
15
17
  import { agents, isUniversalAgent } from "./agents.js";
16
- import { selfCliArgv } from "./self-cli.js";
17
18
  import { SpanKind, SpanStatusCode } from '@opentelemetry/api';
18
- import { runSubprocessSync } from "../../../src/subprocess.js";
19
+ import { annotateSubprocess } from "../../../src/subprocess.js";
20
+ import { selfCliArgv } from "./self-cli.js";
19
21
  const __dirname = dirname(fileURLToPath(import.meta.url));
20
- /**
21
- * ADG patch: upstream re-invokes its *built* `bin/cli.mjs` to perform an update,
22
- * which a source-only vendoring (we copy `src/` only) does not ship — every
23
- * update then failed with "CLI entrypoint not found". Point self-invocation at
24
- * our actual TS entry, run via Node's type-stripping (Node >= 22.6), exactly how
25
- * `adg skills` launches the CLI. See vendor/skills/PROVENANCE.md.
26
- */
27
22
  export function resolveSelfCliEntry(moduleDir = __dirname, exists = existsSync) {
28
23
  const sourceEntry = join(moduleDir, '../../../bin/adg.ts');
29
24
  if (exists(sourceEntry))
@@ -33,43 +28,46 @@ export function resolveSelfCliEntry(moduleDir = __dirname, exists = existsSync)
33
28
  const SELF_CLI_ENTRY = resolveSelfCliEntry();
34
29
  function recordSelfCliEntrypointMissing() {
35
30
  const tracer = getTracer();
36
- const span = tracer.startSpan("adg", { kind: SpanKind.CLIENT });
31
+ const span = tracer.startSpan('adg', { kind: SpanKind.CLIENT });
37
32
  try {
38
- span.setAttribute("process.executable.name", "adg");
39
- span.setAttribute("process.command_args", ["adg", "skills", "add"]);
40
- span.setAttribute("process.exit.code", -1);
41
- span.setAttribute("error.type", "CLI_ENTRYPOINT_NOT_FOUND");
42
- span.setStatus({
43
- code: SpanStatusCode.ERROR,
44
- message: "CLI entrypoint not found",
45
- });
33
+ span.setAttribute('process.executable.name', 'adg');
34
+ span.setAttribute('process.pid', process.pid);
35
+ span.setAttribute('process.command_args', ['adg', 'skills', 'add']);
36
+ span.setAttribute('process.exit.code', -1);
37
+ span.setAttribute('error.type', 'CLI_ENTRYPOINT_NOT_FOUND');
38
+ span.setStatus({ code: SpanStatusCode.ERROR, message: 'CLI entrypoint not found' });
46
39
  }
47
40
  finally {
48
41
  span.end();
49
42
  }
50
43
  }
44
+ function runUpdateChild(args, options) {
45
+ const tracer = getTracer();
46
+ return tracer.startActiveSpan('node', { kind: SpanKind.CLIENT }, (span) => {
47
+ try {
48
+ const result = spawnSync(process.execPath, args, options);
49
+ annotateSubprocess(span, 'node', args, result);
50
+ return result;
51
+ }
52
+ finally {
53
+ span.end();
54
+ }
55
+ });
56
+ }
51
57
  const RESET = '\x1b[0m';
52
58
  const BOLD = '\x1b[1m';
53
59
  const DIM = '\x1b[38;5;102m';
54
60
  const TEXT = '\x1b[38;5;145m';
55
- // ADG patch: the per-source status line is *transient* on a TTY — it carries no
56
- // trailing newline so the next source overwrites it in place. That means the
57
- // cursor stays parked on it, and anything else written while a source is being
58
- // checked (an error line, a deletion warning, a clack prompt) would be
59
- // concatenated onto it. Every such site clears the line first via
60
- // `clearSourceStatus()`. Off a TTY the line is an ordinary log line and both
61
- // helpers degrade to plain behavior.
62
- function writeSourceStatus(source) {
63
- if (process.stdout.isTTY) {
64
- process.stdout.write(`\r${DIM}Checking skills from source: ${source}${RESET}\x1b[K`);
65
- }
66
- else {
67
- process.stdout.write(`Checking skills from source: ${source}\n`);
61
+ /**
62
+ * Public GitHub lock entries use owner/repo shorthand to preserve the exact
63
+ * skill subpath. Pin that shorthand to github.com so an ambient GH_HOST for a
64
+ * GitHub Enterprise account cannot redirect an existing public installation.
65
+ */
66
+ function getUpdateChildEnv(sourceType) {
67
+ if (sourceType !== 'github') {
68
+ return undefined;
68
69
  }
69
- }
70
- function clearSourceStatus() {
71
- if (process.stdout.isTTY)
72
- process.stdout.write('\r\x1b[K');
70
+ return { ...process.env, GH_HOST: 'github.com' };
73
71
  }
74
72
  export function parseUpdateOptions(args) {
75
73
  const options = {};
@@ -241,10 +239,33 @@ export async function getProjectSkillsForUpdate(skillFilter) {
241
239
  if (entry.sourceType === 'node_modules' || entry.sourceType === 'local') {
242
240
  continue;
243
241
  }
244
- skills.push({ name, source: entry.source, entry });
242
+ skills.push({ name, source: entry.sourceUrl || entry.source, entry });
245
243
  }
246
244
  return skills;
247
245
  }
246
+ export async function promptDeletions(source, deletedSkills, isGlobal, options) {
247
+ if (deletedSkills.length === 0)
248
+ return;
249
+ console.log();
250
+ console.log(`${DIM}Warning:${RESET} The following skills from ${DIM}${source}${RESET} appear to have been deleted upstream:`);
251
+ for (const s of deletedSkills) {
252
+ console.log(` ${DIM}•${RESET} ${s}`);
253
+ }
254
+ const isNonInteractive = options.yes || !process.stdin.isTTY;
255
+ if (isNonInteractive) {
256
+ console.log(`${DIM}Skipping deletion in non-interactive mode.${RESET}`);
257
+ return;
258
+ }
259
+ const confirmed = await p.confirm({
260
+ message: `Would you like to remove the local copies of these deleted skills?`,
261
+ });
262
+ if (confirmed && !p.isCancel(confirmed)) {
263
+ for (const s of deletedSkills) {
264
+ console.log(`${DIM}Removing${RESET} ${s}…`);
265
+ await removeCommand([s], { yes: true, global: isGlobal });
266
+ }
267
+ }
268
+ }
248
269
  export async function checkAndPromptForDeletions(source, allLockedForSource, lockSkills, isGlobal, options, discoveredPaths) {
249
270
  const deletedSkills = allLockedForSource.filter((name) => {
250
271
  const entry = lockSkills[name];
@@ -252,32 +273,128 @@ export async function checkAndPromptForDeletions(source, allLockedForSource, loc
252
273
  return false;
253
274
  return !discoveredPaths.includes(entry.skillPath);
254
275
  });
255
- if (deletedSkills.length > 0) {
256
- // ADG patch: this warning and the confirm prompt below land while the
257
- // transient per-source status line still owns the cursor.
258
- clearSourceStatus();
259
- console.log();
260
- console.log(`${DIM}Warning:${RESET} The following skills from ${DIM}${source}${RESET} appear to have been deleted upstream:`);
261
- for (const s of deletedSkills) {
262
- console.log(` ${DIM}•${RESET} ${s}`);
263
- }
264
- const isNonInteractive = options.yes || !process.stdin.isTTY;
265
- if (isNonInteractive) {
266
- console.log(`${DIM}Skipping deletion in non-interactive mode.${RESET}`);
276
+ await promptDeletions(source, deletedSkills, isGlobal, options);
277
+ return deletedSkills;
278
+ }
279
+ export async function checkWellKnownForUpdates(baseUrl, items) {
280
+ let indexResult;
281
+ try {
282
+ indexResult = await wellKnownProvider.fetchIndex(baseUrl, { updateCheck: true });
283
+ }
284
+ catch {
285
+ return { status: 'error' };
286
+ }
287
+ if (!indexResult)
288
+ return { status: 'error' };
289
+ const byName = new Map(indexResult.entries.map((entry) => [entry.name, entry]));
290
+ const removedSkills = items.filter((item) => !byName.has(item.name)).map((item) => item.name);
291
+ const localNames = new Set(items.map((item) => item.name));
292
+ const newSkills = indexResult.entries
293
+ .map((entry) => entry.name)
294
+ .filter((name) => !localNames.has(name));
295
+ const changedSkills = [];
296
+ const needsContentCheck = [];
297
+ for (const item of items) {
298
+ const entry = byName.get(item.name);
299
+ if (!entry)
300
+ continue;
301
+ if (entry.version === '0.2.0') {
302
+ if (!item.digest || entry.digest !== item.digest) {
303
+ changedSkills.push(item.name);
304
+ }
267
305
  }
268
306
  else {
269
- const confirmed = await p.confirm({
270
- message: `Would you like to remove the local copies of these deleted skills?`,
307
+ needsContentCheck.push(item);
308
+ }
309
+ }
310
+ if (needsContentCheck.length > 0) {
311
+ const tracked = new Set(needsContentCheck.map((item) => item.name));
312
+ const skills = (await Promise.all(indexResult.entries
313
+ .filter((entry) => tracked.has(entry.name))
314
+ .map((entry) => wellKnownProvider.fetchSkillByEntry(entry).catch(() => null)))).filter((skill) => skill !== null);
315
+ if (skills.length === 0)
316
+ return { status: 'error' };
317
+ const digests = new Map(skills.map((skill) => [skill.installName, computeWellKnownSkillDigest(skill)]));
318
+ for (const item of needsContentCheck) {
319
+ const digest = digests.get(item.name);
320
+ if (!digest || !item.digest || digest !== item.digest) {
321
+ changedSkills.push(item.name);
322
+ }
323
+ }
324
+ }
325
+ if (changedSkills.length === 0 && removedSkills.length === 0) {
326
+ return { status: 'current', newSkills };
327
+ }
328
+ return { status: 'changed', changedSkills, removedSkills, newSkills };
329
+ }
330
+ function printNewSkills(baseUrl, newSkills, isGlobal) {
331
+ if (newSkills.length === 0)
332
+ return;
333
+ const names = newSkills.map(sanitizeMetadata);
334
+ console.log(` ${DIM}${newSkills.length} new skill(s) available from this source:${RESET} ${names.join(', ')}`);
335
+ console.log(` ${DIM}To install: ${TEXT}npx skills add ${baseUrl} --skill ${names.join(' ')}${isGlobal ? ' -g' : ''}${RESET}`);
336
+ }
337
+ export async function processWellKnownUpdates(groups, isGlobal, options) {
338
+ let successCount = 0;
339
+ let failCount = 0;
340
+ let changed = false;
341
+ for (const [baseUrl, items] of groups) {
342
+ process.stdout.write(`\r${DIM}Checking skills from source: ${baseUrl}${RESET}\x1b[K\n`);
343
+ const result = await checkWellKnownForUpdates(baseUrl, items);
344
+ if (result.status === 'error') {
345
+ console.log(` ${DIM}✗ Failed to check skills from ${baseUrl}${RESET}`);
346
+ failCount += items.length;
347
+ continue;
348
+ }
349
+ if (result.status === 'current') {
350
+ printNewSkills(baseUrl, result.newSkills, isGlobal);
351
+ continue;
352
+ }
353
+ changed = true;
354
+ await promptDeletions(baseUrl, result.removedSkills, isGlobal, options);
355
+ printNewSkills(baseUrl, result.newSkills, isGlobal);
356
+ if (result.changedSkills.length === 0)
357
+ continue;
358
+ const cliEntry = SELF_CLI_ENTRY;
359
+ if (!existsSync(cliEntry)) {
360
+ failCount += result.changedSkills.length;
361
+ console.log(` ${DIM}✗ CLI entrypoint not found at ${cliEntry}${RESET}`);
362
+ continue;
363
+ }
364
+ const itemByName = new Map(items.map((item) => [item.name, item]));
365
+ for (const name of result.changedSkills) {
366
+ const safeName = sanitizeMetadata(name);
367
+ console.log(`${TEXT}Updating ${safeName}…${RESET}`);
368
+ const subagents = itemByName.get(name)?.subagents;
369
+ const subagentArgs = !isGlobal && subagents?.length
370
+ ? ['--subagent', ...subagents.map((s) => (s === '' ? 'root' : s))]
371
+ : [];
372
+ const spawnResult = runUpdateChild(selfCliArgv(cliEntry, [
373
+ 'skills',
374
+ 'add',
375
+ baseUrl,
376
+ '--skill',
377
+ name,
378
+ ...subagentArgs,
379
+ ...(isGlobal ? ['-g'] : []),
380
+ '-y',
381
+ ]), {
382
+ stdio: ['inherit', 'pipe', 'pipe'],
383
+ encoding: 'utf-8',
384
+ env: getUpdateChildEnv(isGlobal ? 'github' : 'well-known'),
385
+ shell: false,
271
386
  });
272
- if (confirmed && !p.isCancel(confirmed)) {
273
- for (const s of deletedSkills) {
274
- console.log(`${DIM}Removing${RESET} ${s}...`);
275
- await removeCommand([s], { yes: true, global: isGlobal });
276
- }
387
+ if (spawnResult.status === 0) {
388
+ successCount++;
389
+ console.log(` ${TEXT}✓${RESET} Updated ${safeName}`);
390
+ }
391
+ else {
392
+ failCount++;
393
+ console.log(` ${DIM}✗ Failed to update ${safeName}${RESET}`);
277
394
  }
278
395
  }
279
396
  }
280
- return deletedSkills;
397
+ return { successCount, failCount, changed };
281
398
  }
282
399
  export async function updateGlobalSkills(options = {}) {
283
400
  const lock = await readSkillLock();
@@ -294,10 +411,8 @@ export async function updateGlobalSkills(options = {}) {
294
411
  const updates = [];
295
412
  const skipped = [];
296
413
  const checkable = [];
297
- // ADG patch: sources whose tree/clone could not be checked (e.g. a private
298
- // repo with no usable token). Tracked so we don't falsely report "up to date".
414
+ const wellKnownGroups = new Map();
299
415
  const failedSources = [];
300
- // ADG patch: set when we normalize a legacy non-tree-SHA hash (see below).
301
416
  let healed = false;
302
417
  for (const skillName of skillNames) {
303
418
  if (!matchesSkillFilter(skillName, options.skills))
@@ -305,6 +420,12 @@ export async function updateGlobalSkills(options = {}) {
305
420
  const entry = lock.skills[skillName];
306
421
  if (!entry)
307
422
  continue;
423
+ if (entry.sourceType === 'well-known' && entry.sourceBaseUrl && entry.wellKnownDigest) {
424
+ const group = wellKnownGroups.get(entry.sourceBaseUrl) || [];
425
+ group.push({ name: skillName, digest: entry.wellKnownDigest });
426
+ wellKnownGroups.set(entry.sourceBaseUrl, group);
427
+ continue;
428
+ }
308
429
  if (!entry.skillFolderHash || !entry.skillPath) {
309
430
  skipped.push({
310
431
  name: skillName,
@@ -317,71 +438,65 @@ export async function updateGlobalSkills(options = {}) {
317
438
  }
318
439
  checkable.push({ name: skillName, entry });
319
440
  }
441
+ const wellKnownCount = Array.from(wellKnownGroups.values()).reduce((sum, items) => sum + items.length, 0);
442
+ const { successCount: wkSuccessCount, failCount: wkFailCount, changed: wkChanged, } = await processWellKnownUpdates(wellKnownGroups, true, options);
443
+ successCount += wkSuccessCount;
444
+ failCount += wkFailCount;
445
+ // Key by source AND ref: two skills from the same repo pinned to different
446
+ // refs must each be checked against their own ref's tree. Grouping by source
447
+ // alone checks the whole group against the first entry's ref, which falsely
448
+ // reports the other-ref skills as deleted upstream (and then removes them).
320
449
  const bySource = new Map();
321
450
  for (const item of checkable) {
322
- const source = item.entry.source;
323
- const existing = bySource.get(source) || [];
451
+ const key = `${item.entry.source}\n${item.entry.ref ?? ''}`;
452
+ const existing = bySource.get(key) || [];
324
453
  existing.push(item);
325
- bySource.set(source, existing);
454
+ bySource.set(key, existing);
326
455
  }
327
- for (const [source, itemsForSource] of bySource) {
456
+ for (const [, itemsForSource] of bySource) {
328
457
  const firstEntry = itemsForSource[0].entry;
458
+ const source = firstEntry.source;
329
459
  const sourceUrl = firstEntry.sourceUrl || firstEntry.source;
330
460
  let tempDir = null;
331
- // ADG patch: was terminated with \n despite the leading \r + clear-to-EOL,
332
- // so every source left a permanent line behind and the cleanup below
333
- // cleared an already blank line. See writeSourceStatus().
334
- writeSourceStatus(source);
461
+ process.stdout.write(`\r${DIM}Checking skills from source: ${source}${RESET}\x1b[K\n`);
335
462
  try {
336
463
  const isGitHubSource = firstEntry.sourceType === 'github';
337
464
  if (isGitHubSource) {
338
465
  const tree = await fetchRepoTree(source, firstEntry.ref, getGitHubToken);
339
- if (!tree) {
340
- // ADG patch: a private repo returns 404 to anon and fetchRepoTree now
341
- // retries with a token; reaching here means even that failed (no token
342
- // or no access). Record it so the summary is honest.
343
- clearSourceStatus();
344
- console.log(` ${DIM}✗ Could not check ${source} — private repo or no GitHub access.${RESET}`);
345
- console.log(` ${DIM}Set ${RESET}${TEXT}GITHUB_TOKEN${RESET}${DIM} or run ${RESET}${TEXT}gh auth login${RESET}${DIM} with access to it.${RESET}`);
346
- failedSources.push(source);
347
- continue;
348
- }
349
- const discoveredPaths = findSkillMdPaths(tree);
350
- const allLockedForSource = Object.entries(lock.skills)
351
- .filter(([_, entry]) => entry.source === source)
352
- .map(([name, _]) => name);
353
- const deletedSkills = await checkAndPromptForDeletions(source, allLockedForSource, lock.skills, true, options, discoveredPaths);
354
- const deletedSkillSet = new Set(deletedSkills);
355
- for (const { name: skillName, entry } of itemsForSource) {
356
- if (deletedSkillSet.has(skillName))
357
- continue;
358
- const latestHash = getSkillFolderHashFromTree(tree, entry.skillPath);
359
- if (!latestHash)
360
- continue;
361
- // ADG patch (self-heal): a github entry whose stored hash isn't a
362
- // 40-hex git tree SHA was written by an older clone-fallback that used
363
- // a sha256 content hash — it can never match `latestHash`, so it would
364
- // be re-flagged on every update. We can't tell whether the content
365
- // truly changed, so normalize the lock to the current tree SHA and do
366
- // NOT flag a spurious update. `add.ts` now always stores a tree SHA, so
367
- // this only ever fires for pre-fix entries.
368
- if (!/^[0-9a-f]{40}$/.test(entry.skillFolderHash)) {
369
- entry.skillFolderHash = latestHash;
370
- healed = true;
371
- continue;
372
- }
373
- if (latestHash !== entry.skillFolderHash) {
374
- updates.push({ name: skillName, source, entry });
466
+ if (tree) {
467
+ const discoveredPaths = tree.tree
468
+ .filter((entry) => entry.type === 'blob')
469
+ .map((entry) => entry.path);
470
+ const allLockedForSource = Object.entries(lock.skills)
471
+ .filter(([_, entry]) => entry.source === source && entry.ref === firstEntry.ref)
472
+ .map(([name, _]) => name);
473
+ const deletedSkills = await checkAndPromptForDeletions(source, allLockedForSource, lock.skills, true, options, discoveredPaths);
474
+ const deletedSkillSet = new Set(deletedSkills);
475
+ for (const { name: skillName, entry } of itemsForSource) {
476
+ if (deletedSkillSet.has(skillName))
477
+ continue;
478
+ const latestHash = getSkillFolderHashFromTree(tree, entry.skillPath);
479
+ // Older lockfiles stored a SHA-256 content hash. Only normalize that
480
+ // legacy shape; arbitrary values must still be compared and updated.
481
+ if (latestHash && /^[0-9a-f]{64}$/i.test(entry.skillFolderHash)) {
482
+ entry.skillFolderHash = latestHash;
483
+ healed = true;
484
+ continue;
485
+ }
486
+ if (latestHash && latestHash !== entry.skillFolderHash) {
487
+ updates.push({ name: skillName, source, entry });
488
+ }
375
489
  }
490
+ continue;
376
491
  }
377
- continue;
492
+ console.log(` ${DIM}GitHub API unavailable; checking via Git clone${RESET}`);
378
493
  }
379
494
  tempDir = await cloneRepo(sourceUrl, firstEntry.ref);
380
- const discoveredPaths = (await discoverSkills(tempDir)).map((skill) => {
495
+ const discoveredPaths = (await discoverSkills(tempDir, undefined, { fullDepth: true })).map((skill) => {
381
496
  return join(relative(tempDir, skill.path), 'SKILL.md').split(sep).join('/');
382
497
  });
383
498
  const allLockedForSource = Object.entries(lock.skills)
384
- .filter(([_, entry]) => entry.source === source)
499
+ .filter(([_, entry]) => entry.source === source && entry.ref === firstEntry.ref)
385
500
  .map(([name, _]) => name);
386
501
  const deletedSkills = await checkAndPromptForDeletions(source, allLockedForSource, lock.skills, true, options, discoveredPaths);
387
502
  const deletedSkillSet = new Set(deletedSkills);
@@ -391,75 +506,103 @@ export async function updateGlobalSkills(options = {}) {
391
506
  const skillPath = entry.skillPath;
392
507
  if (!discoveredPaths.includes(skillPath))
393
508
  continue;
394
- const latestHash = await computeSkillFolderHash(join(tempDir, dirname(skillPath)));
509
+ const usesGitTreeHash = isGitHubSource && /^[0-9a-f]{40}$/i.test(entry.skillFolderHash);
510
+ const latestHash = usesGitTreeHash
511
+ ? await getGitTreeHash(tempDir, skillPath)
512
+ : await computeSkillFolderHash(join(tempDir, dirname(skillPath)));
395
513
  if (latestHash && latestHash !== entry.skillFolderHash) {
396
514
  updates.push({ name: skillName, source, entry });
397
515
  }
398
516
  }
399
517
  }
400
518
  catch (error) {
401
- clearSourceStatus();
402
519
  console.log(` ${DIM}✗ Failed to check skills from ${source}${RESET}`);
403
- failedSources.push(source); // ADG patch: surface in the summary
520
+ failedSources.push(source);
404
521
  }
405
522
  finally {
406
523
  if (tempDir)
407
524
  await cleanupTempDir(tempDir);
408
525
  }
409
526
  }
410
- // ADG patch: only meaningful now that the status line above no longer ends in
411
- // a newline — the cursor is actually parked on it. No-op off a TTY.
412
- if (checkable.length > 0)
413
- clearSourceStatus();
414
- // ADG patch: persist any self-healed (normalized) hashes once.
527
+ if (checkable.length > 0) {
528
+ process.stdout.write('\r\x1b[K');
529
+ }
415
530
  if (healed) {
416
531
  try {
417
532
  await writeSkillLock(lock);
418
533
  }
419
534
  catch {
420
- // A failed heal-write is non-fatal: next run simply normalizes again.
535
+ // A failed healing write is non-fatal; the next run can retry it.
421
536
  }
422
537
  }
423
- const checkedCount = checkable.length + skipped.length;
424
- if (checkable.length === 0 && skipped.length === 0) {
538
+ const checkedCount = checkable.length + skipped.length + wellKnownCount;
539
+ if (checkable.length === 0 && skipped.length === 0 && wellKnownCount === 0) {
425
540
  if (!options.skills) {
426
541
  console.log(`${DIM}No global skills to check.${RESET}`);
427
542
  }
428
543
  return { successCount, failCount, checkedCount: 0 };
429
544
  }
545
+ if (checkable.length === 0 && skipped.length === 0) {
546
+ if (failedSources.length > 0) {
547
+ console.log(`${DIM}Some skill sources could not be verified.${RESET}`);
548
+ return { successCount, failCount: failCount + failedSources.length, checkedCount };
549
+ }
550
+ if (!wkChanged) {
551
+ console.log(`${TEXT}✓ All global skills are up to date${RESET}`);
552
+ }
553
+ return { successCount, failCount, checkedCount };
554
+ }
430
555
  if (checkable.length === 0 && skipped.length > 0) {
431
556
  printSkippedSkills(skipped);
432
557
  return { successCount, failCount, checkedCount };
433
558
  }
434
559
  if (updates.length === 0) {
435
- // ADG patch: don't claim everything is current if some sources couldn't be
436
- // checked — that's how a private-repo fetch failure used to be hidden.
437
560
  if (failedSources.length > 0) {
438
- const n = failedSources.length;
439
- console.log(`${TEXT}✓ Checked global skills; ${n} source${n !== 1 ? 's' : ''} could not be verified (see above)${RESET}`);
440
- return { successCount, failCount: failCount + n, checkedCount };
561
+ console.log(`${DIM}Some skill sources could not be verified.${RESET}`);
562
+ return { successCount, failCount: failCount + failedSources.length, checkedCount };
563
+ }
564
+ if (!wkChanged) {
565
+ console.log(`${TEXT}✓ All global skills are up to date${RESET}`);
441
566
  }
442
- console.log(`${TEXT}✓ All global skills are up to date${RESET}`);
443
567
  return { successCount, failCount, checkedCount };
444
568
  }
445
569
  console.log(`${TEXT}Found ${updates.length} global update(s)${RESET}`);
446
570
  console.log();
447
571
  for (const update of updates) {
448
572
  const safeName = sanitizeMetadata(update.name);
449
- console.log(`${TEXT}Updating ${safeName}...${RESET}`);
573
+ console.log(`${TEXT}Updating ${safeName}…${RESET}`);
450
574
  const installUrl = buildUpdateInstallSource(update.entry);
575
+ if (!installUrl) {
576
+ failCount++;
577
+ console.log(` ${DIM}✗ Cannot update ${safeName}: lock file is missing sourceUrl for this generic Git source${RESET}`);
578
+ continue;
579
+ }
451
580
  const cliEntry = SELF_CLI_ENTRY;
452
- const args = ['skills', 'add', installUrl, '-g', '-y'];
453
581
  if (!existsSync(cliEntry)) {
454
582
  failCount++;
455
- recordSelfCliEntrypointMissing();
456
583
  console.log(` ${DIM}✗ Failed to update ${safeName}: CLI entrypoint not found at ${cliEntry}${RESET}`);
457
584
  continue;
458
585
  }
459
- const result = runSubprocessSync(process.execPath, selfCliArgv(cliEntry, args), {
586
+ const fullDepthArgs = shouldUseFullDepthForUpdate(update.entry) ? ['--full-depth'] : [];
587
+ const result = runUpdateChild(selfCliArgv(cliEntry, [
588
+ 'skills',
589
+ 'add',
590
+ installUrl,
591
+ '--skill',
592
+ update.name,
593
+ ...fullDepthArgs,
594
+ '-g',
595
+ '-y',
596
+ ]), {
460
597
  stdio: ['inherit', 'pipe', 'pipe'],
461
598
  encoding: 'utf-8',
462
- shell: process.platform === 'win32',
599
+ env: getUpdateChildEnv(update.entry.sourceType),
600
+ // Never spawn through a shell. process.execPath is an absolute path to the
601
+ // node binary, so no shell is needed to resolve it. installUrl is derived
602
+ // from the lock file (and ref is URL-decoded, so influenceable by whoever
603
+ // publishes a skill); a shell on Windows would let metacharacters in that
604
+ // value inject commands. Passing argv directly keeps it inert.
605
+ shell: false,
463
606
  });
464
607
  if (result.status === 0) {
465
608
  successCount++;
@@ -484,9 +627,27 @@ export async function updateProjectSkills(options = {}) {
484
627
  }
485
628
  return { successCount, failCount, foundCount: 0 };
486
629
  }
487
- const updatable = projectSkills.filter((s) => s.entry.skillPath);
488
- const legacy = projectSkills.filter((s) => !s.entry.skillPath);
489
- if (updatable.length === 0) {
630
+ const wellKnownGroups = new Map();
631
+ const nonWellKnown = [];
632
+ for (const skill of projectSkills) {
633
+ const { entry } = skill;
634
+ if (entry.sourceType === 'well-known' && entry.sourceUrl && entry.wellKnownDigest) {
635
+ const group = wellKnownGroups.get(entry.sourceUrl) || [];
636
+ group.push({
637
+ name: skill.name,
638
+ digest: entry.wellKnownDigest,
639
+ subagents: entry.subagents,
640
+ });
641
+ wellKnownGroups.set(entry.sourceUrl, group);
642
+ }
643
+ else {
644
+ nonWellKnown.push(skill);
645
+ }
646
+ }
647
+ const wellKnownCount = Array.from(wellKnownGroups.values()).reduce((sum, items) => sum + items.length, 0);
648
+ const updatable = nonWellKnown.filter((s) => s.entry.skillPath);
649
+ const legacy = nonWellKnown.filter((s) => !s.entry.skillPath);
650
+ if (updatable.length === 0 && wellKnownCount === 0) {
490
651
  console.log(`${DIM}No project skills can be updated in place.${RESET}`);
491
652
  printLegacyProjectSkills(legacy);
492
653
  return { successCount, failCount, foundCount: projectSkills.length };
@@ -514,34 +675,49 @@ export async function updateProjectSkills(options = {}) {
514
675
  if (targetParts.length > 0) {
515
676
  console.log(`${TEXT}Updating for: ${targetParts.join(', ')}${RESET}`);
516
677
  }
517
- console.log(`${TEXT}Refreshing ${updatable.length} skill(s)...${RESET}`);
678
+ console.log(`${TEXT}Refreshing ${updatable.length + wellKnownCount} skill(s)…${RESET}`);
518
679
  console.log();
680
+ const { successCount: wkSuccessCount, failCount: wkFailCount } = await processWellKnownUpdates(wellKnownGroups, false, options);
681
+ successCount += wkSuccessCount;
682
+ failCount += wkFailCount;
683
+ // Key by source AND ref (see updateGlobalSkills) so skills from one repo
684
+ // pinned to different refs are each checked against their own ref's tree.
519
685
  const bySource = new Map();
520
686
  for (const skill of updatable) {
521
- const source = skill.entry.source;
522
- const existing = bySource.get(source) || [];
687
+ const source = skill.entry.sourceUrl || skill.entry.source;
688
+ const key = `${source}\n${skill.entry.ref ?? ''}`;
689
+ const existing = bySource.get(key) || [];
523
690
  existing.push(skill);
524
- bySource.set(source, existing);
691
+ bySource.set(key, existing);
525
692
  }
526
693
  const localLock = await readLocalLock();
527
694
  const cliEntry = SELF_CLI_ENTRY;
528
- if (!existsSync(cliEntry)) {
529
- recordSelfCliEntrypointMissing();
695
+ if (updatable.length > 0 && !existsSync(cliEntry)) {
530
696
  console.log(`${DIM}✗ CLI entrypoint not found at ${cliEntry}${RESET}`);
531
- return { successCount, failCount: updatable.length, foundCount: projectSkills.length };
697
+ return {
698
+ successCount,
699
+ failCount: failCount + updatable.length,
700
+ foundCount: projectSkills.length,
701
+ };
532
702
  }
533
- for (const [source, skillsForSource] of bySource) {
703
+ for (const [, skillsForSource] of bySource) {
534
704
  const firstEntry = skillsForSource[0].entry;
535
- const sourceUrl = firstEntry.source;
705
+ const source = firstEntry.sourceUrl || firstEntry.source;
706
+ const cloneSource = buildLocalCloneSource(firstEntry);
536
707
  const ref = firstEntry.ref;
537
708
  const allLockedForSource = Object.entries(localLock.skills)
538
- .filter(([_, entry]) => entry.source === source)
709
+ .filter(([_, entry]) => (entry.sourceUrl || entry.source) === source && entry.ref === ref)
539
710
  .map(([name, _]) => name);
540
711
  let tempDir = null;
541
712
  let deletedSkills = [];
713
+ if (cloneSource === null) {
714
+ failCount += skillsForSource.length;
715
+ console.log(`${DIM}✗ Cannot update ${source}: skills-lock.json is missing sourceUrl for this generic Git source${RESET}`);
716
+ continue;
717
+ }
542
718
  try {
543
- tempDir = await cloneRepo(sourceUrl, ref);
544
- const discovered = await discoverSkills(tempDir);
719
+ tempDir = await cloneRepo(cloneSource, ref);
720
+ const discovered = await discoverSkills(tempDir, undefined, { fullDepth: true });
545
721
  const discoveredPaths = discovered.map((s) => {
546
722
  const relPath = relative(tempDir, s.path);
547
723
  return join(relPath, 'SKILL.md').split(sep).join('/');
@@ -559,18 +735,37 @@ export async function updateProjectSkills(options = {}) {
559
735
  const remainingSkills = skillsForSource.filter((s) => !deletedSkills.includes(s.name));
560
736
  for (const skill of remainingSkills) {
561
737
  const safeName = sanitizeMetadata(skill.name);
562
- console.log(`${TEXT}Updating ${safeName}...${RESET}`);
563
- const installUrl = formatSourceInput(skill.entry.source, skill.entry.ref);
738
+ console.log(`${TEXT}Updating ${safeName}…${RESET}`);
739
+ const installUrl = buildLocalUpdateSource(skill.entry);
740
+ if (!installUrl) {
741
+ failCount++;
742
+ console.log(` ${DIM}✗ Cannot update ${safeName}: skills-lock.json is missing sourceUrl for this generic Git source${RESET}`);
743
+ continue;
744
+ }
564
745
  // Preserve Eve subagent placement recorded at install time. The lock stores
565
746
  // '' for the root agent, which maps to the `root` keyword for `add --subagent`.
566
747
  const subagentArgs = skill.entry.subagents?.length
567
748
  ? ['--subagent', ...skill.entry.subagents.map((s) => (s === '' ? 'root' : s))]
568
749
  : [];
569
- const args = ['skills', 'add', installUrl, '--skill', skill.name, ...subagentArgs, '-y'];
570
- const result = runSubprocessSync(process.execPath, selfCliArgv(cliEntry, args), {
750
+ const fullDepthArgs = shouldUseFullDepthForUpdate(skill.entry) ? ['--full-depth'] : [];
751
+ const result = runUpdateChild(selfCliArgv(cliEntry, [
752
+ 'skills',
753
+ 'add',
754
+ installUrl,
755
+ '--skill',
756
+ skill.name,
757
+ ...subagentArgs,
758
+ ...fullDepthArgs,
759
+ '-y',
760
+ ]), {
571
761
  stdio: ['inherit', 'pipe', 'pipe'],
572
762
  encoding: 'utf-8',
573
- shell: process.platform === 'win32',
763
+ env: getUpdateChildEnv(skill.entry.sourceType),
764
+ // Never spawn through a shell — same reasoning as updateGlobalSkills:
765
+ // execPath is absolute (no shell resolution needed) and installUrl/ref
766
+ // come from the lock file, so a shell would allow command injection on
767
+ // Windows. Pass argv directly instead.
768
+ shell: false,
574
769
  });
575
770
  if (result.status === 0) {
576
771
  successCount++;
@@ -591,19 +786,24 @@ export function printLegacyProjectSkills(legacy) {
591
786
  console.log();
592
787
  console.log(`${DIM}${legacy.length} project skill(s) cannot be updated automatically (installed before skillPath tracking):${RESET}`);
593
788
  for (const skill of legacy) {
594
- const reinstall = formatSourceInput(skill.entry.source, skill.entry.ref);
789
+ const reinstall = buildLocalUpdateSource(skill.entry);
595
790
  console.log(` ${TEXT}•${RESET} ${sanitizeMetadata(skill.name)}`);
596
- console.log(` ${DIM}To refresh: ${TEXT}adg skills add ${reinstall} -y${RESET}`);
791
+ if (reinstall) {
792
+ console.log(` ${DIM}To refresh: ${TEXT}npx skills add ${reinstall} -y${RESET}`);
793
+ }
794
+ else {
795
+ console.log(` ${DIM}To refresh: reinstall using the original full Git URL; this lock entry only has an ambiguous shorthand.${RESET}`);
796
+ }
597
797
  }
598
798
  }
599
799
  export async function runUpdate(args = []) {
600
800
  const options = parseUpdateOptions(args);
601
801
  const scope = await resolveUpdateScope(options);
602
802
  if (options.skills) {
603
- console.log(`${TEXT}Updating ${options.skills.join(', ')}...${RESET}`);
803
+ console.log(`${TEXT}Updating ${options.skills.join(', ')}…${RESET}`);
604
804
  }
605
805
  else {
606
- console.log(`${TEXT}Checking for skill updates...${RESET}`);
806
+ console.log(`${TEXT}Checking for skill updates…${RESET}`);
607
807
  }
608
808
  console.log();
609
809
  let totalSuccess = 0;