@ai-primitives-hub/cli 0.2.1 → 0.2.2-next.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.
Files changed (105) hide show
  1. package/README.md +26 -1
  2. package/dist/commands/bundle-build.d.ts +1 -0
  3. package/dist/commands/bundle-build.d.ts.map +1 -1
  4. package/dist/commands/bundle-build.js +23 -4
  5. package/dist/commands/bundle-build.js.map +1 -1
  6. package/dist/commands/collection-affected.d.ts.map +1 -1
  7. package/dist/commands/collection-affected.js +1 -34
  8. package/dist/commands/collection-affected.js.map +1 -1
  9. package/dist/commands/collection-validate.d.ts +15 -2
  10. package/dist/commands/collection-validate.d.ts.map +1 -1
  11. package/dist/commands/collection-validate.js +42 -4
  12. package/dist/commands/collection-validate.js.map +1 -1
  13. package/dist/commands/doctor.d.ts +4 -0
  14. package/dist/commands/doctor.d.ts.map +1 -1
  15. package/dist/commands/doctor.js +37 -0
  16. package/dist/commands/doctor.js.map +1 -1
  17. package/dist/commands/explain.d.ts.map +1 -1
  18. package/dist/commands/explain.js +54 -4
  19. package/dist/commands/explain.js.map +1 -1
  20. package/dist/commands/hub-replicate.d.ts +1 -0
  21. package/dist/commands/hub-replicate.d.ts.map +1 -1
  22. package/dist/commands/hub-replicate.js +16 -5
  23. package/dist/commands/hub-replicate.js.map +1 -1
  24. package/dist/commands/hub-scoped-governance.d.ts +21 -0
  25. package/dist/commands/hub-scoped-governance.d.ts.map +1 -0
  26. package/dist/commands/hub-scoped-governance.js +74 -0
  27. package/dist/commands/hub-scoped-governance.js.map +1 -0
  28. package/dist/commands/hub.d.ts +6 -0
  29. package/dist/commands/hub.d.ts.map +1 -1
  30. package/dist/commands/hub.js +68 -0
  31. package/dist/commands/hub.js.map +1 -1
  32. package/dist/commands/init.d.ts.map +1 -1
  33. package/dist/commands/init.js +3 -10
  34. package/dist/commands/init.js.map +1 -1
  35. package/dist/commands/install.d.ts +18 -10
  36. package/dist/commands/install.d.ts.map +1 -1
  37. package/dist/commands/install.js +472 -253
  38. package/dist/commands/install.js.map +1 -1
  39. package/dist/commands/plugin-create.d.ts.map +1 -1
  40. package/dist/commands/plugin-create.js +72 -43
  41. package/dist/commands/plugin-create.js.map +1 -1
  42. package/dist/commands/profile.d.ts +42 -4
  43. package/dist/commands/profile.d.ts.map +1 -1
  44. package/dist/commands/profile.js +739 -144
  45. package/dist/commands/profile.js.map +1 -1
  46. package/dist/commands/registry.d.ts.map +1 -1
  47. package/dist/commands/registry.js +5 -0
  48. package/dist/commands/registry.js.map +1 -1
  49. package/dist/commands/security-rate.d.ts +26 -0
  50. package/dist/commands/security-rate.d.ts.map +1 -0
  51. package/dist/commands/security-rate.js +281 -0
  52. package/dist/commands/security-rate.js.map +1 -0
  53. package/dist/commands/security-scan.d.ts +40 -0
  54. package/dist/commands/security-scan.d.ts.map +1 -0
  55. package/dist/commands/security-scan.js +395 -0
  56. package/dist/commands/security-scan.js.map +1 -0
  57. package/dist/commands/status.d.ts +18 -11
  58. package/dist/commands/status.d.ts.map +1 -1
  59. package/dist/commands/status.js +42 -33
  60. package/dist/commands/status.js.map +1 -1
  61. package/dist/commands/uninstall.d.ts +2 -9
  62. package/dist/commands/uninstall.d.ts.map +1 -1
  63. package/dist/commands/uninstall.js +413 -147
  64. package/dist/commands/uninstall.js.map +1 -1
  65. package/dist/commands/update.d.ts +1 -2
  66. package/dist/commands/update.d.ts.map +1 -1
  67. package/dist/commands/update.js +379 -56
  68. package/dist/commands/update.js.map +1 -1
  69. package/dist/commands/validation-governance.d.ts +27 -0
  70. package/dist/commands/validation-governance.d.ts.map +1 -0
  71. package/dist/commands/validation-governance.js +92 -0
  72. package/dist/commands/validation-governance.js.map +1 -0
  73. package/dist/doctor/diagnostics.d.ts +72 -5
  74. package/dist/doctor/diagnostics.d.ts.map +1 -1
  75. package/dist/doctor/diagnostics.js +94 -40
  76. package/dist/doctor/diagnostics.js.map +1 -1
  77. package/dist/doctor/primitive-driver.d.ts +24 -0
  78. package/dist/doctor/primitive-driver.d.ts.map +1 -0
  79. package/dist/doctor/primitive-driver.js +162 -0
  80. package/dist/doctor/primitive-driver.js.map +1 -0
  81. package/dist/doctor/primitives-text.d.ts +27 -0
  82. package/dist/doctor/primitives-text.d.ts.map +1 -0
  83. package/dist/doctor/primitives-text.js +131 -0
  84. package/dist/doctor/primitives-text.js.map +1 -0
  85. package/dist/doctor/primitives.d.ts +24 -0
  86. package/dist/doctor/primitives.d.ts.map +1 -0
  87. package/dist/doctor/primitives.js +101 -0
  88. package/dist/doctor/primitives.js.map +1 -0
  89. package/dist/framework/error.d.ts +19 -18
  90. package/dist/framework/error.d.ts.map +1 -1
  91. package/dist/framework/error.js +78 -22
  92. package/dist/framework/error.js.map +1 -1
  93. package/dist/framework/index.d.ts +3 -1
  94. package/dist/framework/index.d.ts.map +1 -1
  95. package/dist/framework/index.js +42 -1
  96. package/dist/framework/index.js.map +1 -1
  97. package/dist/framework/install-record.d.ts +555 -0
  98. package/dist/framework/install-record.d.ts.map +1 -0
  99. package/dist/framework/install-record.js +968 -0
  100. package/dist/framework/install-record.js.map +1 -0
  101. package/dist/framework/target.d.ts +9 -12
  102. package/dist/framework/target.d.ts.map +1 -1
  103. package/dist/framework/target.js +9 -12
  104. package/dist/framework/target.js.map +1 -1
  105. package/package.json +6 -4
@@ -37,20 +37,15 @@ exports.UpdateCommand = exports.isNewerVersion = void 0;
37
37
  /**
38
38
  * `update` command — checks installed bundles for newer versions and upgrades them.
39
39
  *
40
- * Reference's version keys each lockfile entry by its own `target` field and
41
- * resolves a target per-entry. Our `LockfileBundleEntry` has no `target`
42
- * field (see `app/stores/json-lockfile-store.ts`'s module doc — repository
43
- * scope always writes to `.github/`, invariant of target), so `update`
44
- * instead resolves a single target for the whole run — same
45
- * flag/auto-detect pattern as `install`/`uninstall` — and updates every
46
- * bundle tracked by that target's lockfile.
40
+ * `update` selects one install record level and updates every (bundle, tool)
41
+ * entry there through the target mapped to its tool; `--target` narrows it to
42
+ * one tool. Bundles only an older 2.0.0 file lists are updated on that file.
47
43
  */
48
44
  const path = __importStar(require("node:path"));
49
45
  const app_1 = require("@ai-primitives-hub/app");
50
46
  const core_1 = require("@ai-primitives-hub/core");
51
47
  const infra_1 = require("@ai-primitives-hub/infra");
52
48
  const framework_1 = require("../framework");
53
- const framework_2 = require("../framework");
54
49
  /**
55
50
  * Return true when `candidate` is a strictly higher semver than `installed`.
56
51
  * Strips leading `v` from either value before comparing.
@@ -114,8 +109,8 @@ class UpdateCommand extends BaseUpdateCommand {
114
109
  details: `
115
110
  Usage: ai-primitives-hub update [options]
116
111
 
117
- Reads the lockfile, checks each remote bundle against its upstream source,
118
- and installs available upgrades.
112
+ Reads the install record, checks each remote bundle against its upstream
113
+ source, and installs available upgrades.
119
114
 
120
115
  Options:
121
116
  --lockfile <path> Path to a lockfile
@@ -157,9 +152,37 @@ class UpdateCommand extends BaseUpdateCommand {
157
152
  };
158
153
  await detectUpdateContext(opts, ctx);
159
154
  try {
160
- const targetName = await (0, framework_2.resolveTargetName)(opts.target, 'update', ctx, () => (0, framework_1.loadTargets)(ctx));
161
- const configuredTarget = await (0, framework_2.resolveTarget)(targetName, 'update', ctx, () => (0, framework_1.loadTargets)(ctx));
162
- const target = (0, framework_1.resolveEffectiveTarget)(ctx, configuredTarget, opts);
155
+ // Without an inferred target the record decides; read-only first, so a failing run changes nothing.
156
+ const input = { command: 'update', lockfile: this.lockfile, scope: opts.scope };
157
+ const run = {
158
+ ctx, fmt, http, tokens, overrides: opts, dryRun: this.dryRun, interactive: this.interactive, noHubSync: this.noHubSync
159
+ };
160
+ const targetName = await (0, framework_1.inferTargetName)(ctx, opts.target);
161
+ if (targetName === undefined) {
162
+ const decided = await runRecordUpdate(run, await prepareRecordWithoutTarget(ctx, input, this.dryRun));
163
+ if (decided !== undefined) {
164
+ return decided;
165
+ }
166
+ }
167
+ const target = await (0, framework_1.resolveCommandTarget)(ctx, 'update', targetName, opts);
168
+ // Select the record first, so a bad record stops before anything is fetched or written; a dry run never migrates.
169
+ const decision = await (0, framework_1.prepareRecordDecision)(ctx, input, { write: this.dryRun !== true, target });
170
+ const recorded = await runRecordUpdate(run, decision, this.target !== undefined && this.target.length > 0 ? target : undefined);
171
+ if (recorded !== undefined) {
172
+ return recorded;
173
+ }
174
+ // Once the user record imported the old user lockfile, an empty record never falls back to that file;
175
+ // a workspace-scope target and an explicit --lockfile still use it.
176
+ const prepared = decision?.prepared;
177
+ if (prepared !== undefined && prepared.selection.level === 'user' && prepared.selection.locations.length > 0
178
+ && target.scope === 'user' && !(this.lockfile?.length)
179
+ && (await prepared.store.load(prepared.selection.locations[0])).record[core_1.IMPORTED_USER_LOCKFILE_FIELD] !== undefined) {
180
+ return (0, framework_1.failWith)(ctx, fmt, 'update', new framework_1.RegistryError({
181
+ code: 'USAGE.MISSING_FLAG',
182
+ message: 'update: nothing is installed at the user level',
183
+ hint: 'Install a bundle first; the old user lockfile was imported and is no longer read.'
184
+ }));
185
+ }
163
186
  const commitMode = target.commitMode ?? 'commit';
164
187
  const scope = target.scope;
165
188
  const lockPath = opts.lockfile !== undefined && opts.lockfile.length > 0
@@ -167,7 +190,7 @@ class UpdateCommand extends BaseUpdateCommand {
167
190
  : (0, framework_1.lockfilePathForTarget)(ctx, target, commitMode);
168
191
  const lock = await (0, app_1.readLockfile)(lockPath, ctx.fs);
169
192
  if (lock === null) {
170
- return (0, framework_1.failWith)(ctx, fmt, 'update', new framework_2.RegistryError({
193
+ return (0, framework_1.failWith)(ctx, fmt, 'update', new framework_1.RegistryError({
171
194
  code: 'USAGE.MISSING_FLAG',
172
195
  message: 'update: no lockfile found',
173
196
  hint: 'Run `ai-primitives-hub install` first, or pass --lockfile <path>.'
@@ -177,11 +200,7 @@ class UpdateCommand extends BaseUpdateCommand {
177
200
  await syncActiveHub(ctx);
178
201
  }
179
202
  const bundleIds = Object.keys(lock.bundles);
180
- const remoteBundleIds = bundleIds.filter((id) => {
181
- const src = lock.sources[lock.bundles[id].sourceId];
182
- return src !== undefined && isRemoteSource(src.type);
183
- });
184
- const { candidates, skipped, failures: discoveryFailures } = await findUpdateCandidates(remoteBundleIds, lock, ctx, http, tokens);
203
+ const { candidates, skipped, failures: discoveryFailures } = await findUpdateCandidates(remoteBundleIds(lock, bundleIds), lock, ctx, http, tokens);
185
204
  if (this.dryRun) {
186
205
  return renderDryRun(ctx, fmt, lockPath, bundleIds.length, skipped.length, candidates, discoveryFailures);
187
206
  }
@@ -191,7 +210,7 @@ class UpdateCommand extends BaseUpdateCommand {
191
210
  }
192
211
  const { updatedCount, updateResults, failures: updateFailures } = await applyUpdates(toInstall, target, scope, commitMode, lockPath, ctx, http, tokens);
193
212
  const failures = [...discoveryFailures, ...updateFailures];
194
- (0, framework_2.formatOutput)({
213
+ (0, framework_1.formatOutput)({
195
214
  ctx, command: 'update', output: fmt, status: failures.length > 0 ? 'warning' : 'ok',
196
215
  data: { lockfile: lockPath, target: target.name, checked: bundleIds.length, updated: updatedCount, skipped: skipped.length, updates: updateResults, failures },
197
216
  warnings: failures,
@@ -211,7 +230,7 @@ class UpdateCommand extends BaseUpdateCommand {
211
230
  return failures.length > 0 ? 1 : 0;
212
231
  }
213
232
  catch (err) {
214
- if (err instanceof framework_2.RegistryError) {
233
+ if (err instanceof framework_1.RegistryError) {
215
234
  return (0, framework_1.failWith)(ctx, fmt, 'update', err);
216
235
  }
217
236
  throw err;
@@ -221,7 +240,7 @@ class UpdateCommand extends BaseUpdateCommand {
221
240
  exports.UpdateCommand = UpdateCommand;
222
241
  /**
223
242
  * Detect update context from the project environment (symmetric with install/uninstall).
224
- * Fills in `opts.target` when it can be inferred.
243
+ * Fills in `opts.lockfile` when it can be inferred; the target is inferred later.
225
244
  * @param opts Update options (mutated in-place).
226
245
  * @param ctx CLI context.
227
246
  */
@@ -232,16 +251,43 @@ async function detectUpdateContext(opts, ctx) {
232
251
  opts.lockfile = found;
233
252
  }
234
253
  }
235
- if (!opts.target || opts.target.length === 0) {
236
- const targets = await (0, framework_2.readTargetsSafely)((0, framework_1.loadTargets)(ctx));
237
- if (targets.length === 1) {
238
- opts.target = targets[0].name;
239
- }
240
- }
241
254
  }
242
255
  function isRemoteSource(type) {
243
256
  return type === 'github' || type === 'awesome-copilot' || type === 'skills' || type === 'artifactory';
244
257
  }
258
+ const remoteBundleIds = (lock, bundleIds) => bundleIds.filter((bundleId) => {
259
+ const src = lock.sources[lock.bundles[bundleId].sourceId];
260
+ return src !== undefined && isRemoteSource(src.type);
261
+ });
262
+ /**
263
+ * The record `update` acts on with no inferred target, migrated unless `--dry-run`;
264
+ * `undefined` when it has no entries.
265
+ * @param ctx CLI context.
266
+ * @param input Command name and the typed `--lockfile` / `--scope`.
267
+ * @param dryRun `true` for `--dry-run`.
268
+ * @throws {RegistryError} A `RECORD.*` error naming the file.
269
+ */
270
+ async function prepareRecordWithoutTarget(ctx, input, dryRun) {
271
+ const decision = await (0, framework_1.prepareRecordDecision)(ctx, input);
272
+ return decision.rows.length === 0 ? undefined : (0, framework_1.migrateDecision)(ctx, decision, { dryRun });
273
+ }
274
+ /**
275
+ * Sync the active hub unless `--no-hub-sync`, then update from the record.
276
+ * @param run Context, clients, overrides and flags of the update.
277
+ * @param decision The selected record and its entries, if any.
278
+ * @param explicit The target named by `--target`.
279
+ * @returns Exit code, or `undefined` when the record has no entry.
280
+ */
281
+ async function runRecordUpdate(run, decision, explicit) {
282
+ if (decision === undefined || decision.rows.length === 0) {
283
+ return undefined;
284
+ }
285
+ const { noHubSync, ...base } = run;
286
+ if (!noHubSync) {
287
+ await syncActiveHub(base.ctx);
288
+ }
289
+ return updateFromRecord({ ...base, ...(explicit === undefined ? {} : { explicit }), prepared: decision.prepared });
290
+ }
245
291
  /**
246
292
  * Build a `RegistrySource`-shaped object from a lockfile source entry,
247
293
  * for `SourceDispatcher.resolverFor` — the dispatcher only reads
@@ -303,11 +349,12 @@ async function sourceAwareUpdateDependencies(sourceId, src, ctx, http) {
303
349
  downloadTokens: runtime.tokenProviderFor(decision.category) ?? new infra_1.StaticTokenProvider('')
304
350
  };
305
351
  }
306
- async function findUpdateCandidates(bundleIds, lock, ctx, http, tokens) {
352
+ async function findUpdateCandidates(bundleIds, lock, ctx, http, tokens, anonymous = false) {
307
353
  const candidates = [];
308
354
  const skipped = [];
309
355
  const failures = [];
310
- const sourceAware = (0, infra_1.isGitHubAppAuthEnabled)(ctx.env);
356
+ // A source taken from the record runs without credentials.
357
+ const sourceAware = !anonymous && (0, infra_1.isGitHubAppAuthEnabled)(ctx.env);
311
358
  const githubApi = new infra_1.GitHubApiClient(http, { tokenProvider: tokens });
312
359
  const dispatcher = new infra_1.SourceDispatcher({ githubApi, fs: ctx.fs });
313
360
  const sourceDependencies = new Map();
@@ -373,7 +420,7 @@ async function findUpdateCandidates(bundleIds, lock, ctx, http, tokens) {
373
420
  return { candidates, skipped, failures };
374
421
  }
375
422
  function renderDryRun(ctx, fmt, lockPath, checked, skippedCount, candidates, failures) {
376
- (0, framework_2.formatOutput)({
423
+ (0, framework_1.formatOutput)({
377
424
  ctx, command: 'update', output: fmt, status: failures.length > 0 ? 'warning' : 'ok',
378
425
  data: {
379
426
  dryRun: true, lockfile: lockPath,
@@ -404,7 +451,7 @@ async function selectUpdatesInteractively(interactive, candidates) {
404
451
  return answers.selected;
405
452
  }
406
453
  function renderNoUpdates(ctx, fmt, checked, skippedCount, failures) {
407
- (0, framework_2.formatOutput)({
454
+ (0, framework_1.formatOutput)({
408
455
  ctx, command: 'update', output: fmt, status: failures.length > 0 ? 'warning' : 'ok',
409
456
  data: { checked, updated: 0, skipped: skippedCount, updates: [], failures },
410
457
  warnings: failures,
@@ -421,25 +468,23 @@ function renderNoUpdates(ctx, fmt, checked, skippedCount, failures) {
421
468
  * @param target Target being updated.
422
469
  * @param scope Effective scope (may override `target.scope`).
423
470
  * @param commitMode Effective commit mode (repository scope only).
471
+ * @param exclusion Where a local-only write lists its files; `<workspace>/.git/info/exclude` by default.
424
472
  * @returns A TargetWriter.
425
473
  */
426
- function writerFor(ctx, target, scope, commitMode) {
474
+ function writerFor(ctx, target, scope, commitMode, exclusion) {
427
475
  const effectiveScope = scope;
428
476
  if (effectiveScope === 'repository' && new Set(['vscode', 'vscode-insiders', 'copilot-cli']).has(target.type)) {
429
477
  const writer = new infra_1.RepositoryScopeWriter({
430
478
  fs: ctx.fs,
431
479
  workspaceRoot: target.rootPath ?? ctx.cwd(),
432
- commitMode
480
+ commitMode,
481
+ exclusion
433
482
  });
434
483
  return new infra_1.RepositoryScopeWriterAdapter(writer);
435
484
  }
436
485
  const transformer = app_1.TransformerRegistry.withBuiltIns().getTransformer(target.type);
437
- const layoutLoader = new infra_1.FileSystemLayoutConfigLoader({
438
- cwd: ctx.cwd(),
439
- fs: ctx.fs,
440
- userConfigDir: (0, infra_1.resolveUserConfigDir)(ctx.env)
441
- });
442
- return new app_1.FileTreeTargetWriter({ fs: ctx.fs, env: ctx.env, transformer, layoutLoader });
486
+ const layoutLoader = (0, framework_1.createLayoutLoader)(ctx);
487
+ return new app_1.FileTreeTargetWriter({ fs: ctx.fs, env: (0, framework_1.writerEnv)(ctx.env, effectiveScope), transformer, layoutLoader });
443
488
  }
444
489
  async function applyUpdates(toInstall, target, scope, commitMode, lockPath, ctx, http, tokens) {
445
490
  let updatedCount = 0;
@@ -477,14 +522,8 @@ async function syncActiveHub(ctx) {
477
522
  }
478
523
  }
479
524
  async function applyUpdate(candidate, target, scope, commitMode, lockPath, ctx, http, tokens) {
480
- const downloader = candidate.source.type === 'artifactory' && candidate.artifactoryClient !== undefined
481
- ? new infra_1.ArtifactoryBundleDownloader(candidate.artifactoryClient)
482
- : new infra_1.HttpsBundleDownloader(http, candidate.downloadTokens ?? tokens, candidate.repositoryTarget, candidate.authenticationCategory);
483
- const extractor = new infra_1.ZipBundleExtractor();
484
- const dl = await downloader.download(candidate.installable);
485
- const files = await extractor.extract(dl.bytes);
525
+ const { dl, files, manifest } = await downloadCandidate(candidate, http, tokens);
486
526
  const isArtifactory = candidate.source.type === 'artifactory';
487
- const manifest = (0, core_1.validateManifest)(files, { expectedId: undefined, expectedVersion: isArtifactory ? candidate.installable.ref.bundleVersion : undefined });
488
527
  const writer = writerFor(ctx, target, scope, commitMode);
489
528
  const { installableFiles: targetFiles, result } = await (0, app_1.writeBundleSafely)(writer, target, files, manifest);
490
529
  const entry = {
@@ -508,17 +547,301 @@ async function applyUpdate(candidate, target, scope, commitMode, lockPath, ctx,
508
547
  nextLock = (0, app_1.upsertSource)(nextLock, candidate.entry.sourceId, candidate.source);
509
548
  await (0, app_1.writeLockfile)(lockPath, nextLock, ctx.fs);
510
549
  await (0, app_1.removeSupersededFiles)(writer, target, previousFiles, entry.files);
511
- const stateStore = new infra_1.TargetStateStore({ fs: ctx.fs, statePath: path.join(ctx.cwd(), '.ai-primitives-hub', 'target-state.json') });
512
- const existingState = await stateStore.load(target.name);
513
- const bundles = existingState?.lastInstalledBundles ?? [];
514
- const idx = bundles.findIndex((b) => b.bundleId === lockKey);
515
- const bundleState = { bundleId: lockKey, version: manifest.version, installedAt: new Date().toISOString() };
516
- if (idx === -1) {
517
- bundles.push(bundleState);
550
+ }
551
+ async function downloadCandidate(candidate, http, tokens, expect) {
552
+ const downloader = candidate.source.type === 'artifactory' && candidate.artifactoryClient !== undefined
553
+ ? new infra_1.ArtifactoryBundleDownloader(candidate.artifactoryClient)
554
+ : new infra_1.HttpsBundleDownloader(http, candidate.downloadTokens ?? tokens, candidate.repositoryTarget, candidate.authenticationCategory);
555
+ const extractor = new infra_1.ZipBundleExtractor();
556
+ const dl = await downloader.download(candidate.installable);
557
+ const files = await extractor.extract(dl.bytes);
558
+ const isArtifactory = candidate.source.type === 'artifactory';
559
+ // A record update checks the archive is the recorded bundle at the candidate version, as replay does.
560
+ const manifest = (0, core_1.validateManifest)(files, expect === undefined
561
+ ? { expectedId: undefined, expectedVersion: isArtifactory ? candidate.installable.ref.bundleVersion : undefined }
562
+ : {
563
+ expectedId: isArtifactory ? undefined : expect.bundleId,
564
+ expectedVersion: candidate.installable.ref.bundleVersion,
565
+ sourceRepoSlug: (0, app_1.githubRepoSlugForSource)(expect.source)
566
+ });
567
+ return { dl, files, manifest };
568
+ }
569
+ /**
570
+ * Key of a (bundle, tool) entry that matches the entry at any version of a versioned id.
571
+ * @param bundleId Recorded key.
572
+ * @param version Version recorded for it.
573
+ * @param tool Tool key.
574
+ */
575
+ const entryKey = (bundleId, version, tool) => `${(0, app_1.recordIdentityOf)(bundleId, version)}\u0000${tool}`;
576
+ /**
577
+ * A one-bundle legacy lockfile for `findUpdateCandidates`, built only from the entry and the decided source.
578
+ * @param item Plan item.
579
+ */
580
+ const lookupLockfile = (item) => ({
581
+ $schema: '',
582
+ version: '2.0.0',
583
+ generatedAt: '',
584
+ generatedBy: framework_1.CLI_RECORD_GENERATED_BY,
585
+ bundles: { [item.bundleId]: (0, app_1.toLockfileBundleEntry)(item.entry) },
586
+ sources: { [item.sourceId]: item.source }
587
+ });
588
+ async function writeForTarget(ctx, target, files, manifest, exclusion) {
589
+ const writer = writerFor(ctx, target, target.scope, target.commitMode ?? 'commit', exclusion);
590
+ const { result } = await (0, app_1.writeBundleSafely)(writer, target, files, manifest);
591
+ return [...result.written];
592
+ }
593
+ /**
594
+ * Build the update plan, mapping and gating every entry before any lookup, also under `--dry-run`.
595
+ * @param run Update inputs.
596
+ */
597
+ async function planRecordUpdates(run) {
598
+ const { ctx, prepared, explicit } = run;
599
+ const { selection, store, service, fs } = prepared;
600
+ const plan = await (0, app_1.planRecordEntries)({
601
+ service,
602
+ store,
603
+ fs,
604
+ selection,
605
+ targets: await (0, framework_1.readTargetsSafely)((0, framework_1.loadTargets)(ctx)),
606
+ ...await (0, framework_1.configuredRecordSources)(ctx),
607
+ explicit,
608
+ cwd: ctx.cwd(),
609
+ holdingFile: 'listed'
610
+ });
611
+ return {
612
+ items: plan.items.map((item) => ({
613
+ bundleId: item.bundleId,
614
+ tool: item.tool,
615
+ location: item.location,
616
+ entry: item.entry,
617
+ sourceId: item.entry.sourceId,
618
+ source: (0, app_1.toLockfileSourceEntry)(item.source),
619
+ target: (0, framework_1.resolveEffectiveTarget)(ctx, item.target),
620
+ fromRecord: item.fromRecordOnly,
621
+ ...(item.source.hubId === undefined ? {} : { hubId: item.source.hubId }),
622
+ ...(item.hub === undefined ? {} : { hub: item.hub })
623
+ })),
624
+ skipped: [
625
+ ...plan.skipped,
626
+ // An entry whose tool is unknown cannot be updated in place.
627
+ ...plan.needsReinstall.map((row) => ({
628
+ bundleId: row.bundleId, tool: row.tool, reason: `needs reinstall (tool unknown, still ${row.version}): install it for a tool`
629
+ }))
630
+ ],
631
+ notes: plan.notes,
632
+ mapTool: plan.mapTool
633
+ };
634
+ }
635
+ /**
636
+ * Apply one update and run each synced sibling's own writer at the new version; deletes nothing.
637
+ * @param run Update inputs.
638
+ * @param item Plan item.
639
+ * @param candidate Its update candidate, looked up from the decided source.
640
+ * @param siblingTargets Mapped targets of the bundle's other tools.
641
+ * @returns The record changes and the siblings synced or left out of date.
642
+ */
643
+ async function applyRecordUpdate(run, item, candidate, siblingTargets) {
644
+ const { ctx, http, prepared } = run;
645
+ // A versioned id moves to the new version's key; the record then drops the old one.
646
+ const bundleId = (0, app_1.recordKeyForVersion)(item.bundleId, item.entry.version, candidate.to);
647
+ const { files, manifest } = await downloadCandidate(candidate, http, (0, framework_1.tokensForRecordSource)(run.tokens, item.fromRecord), { bundleId, source: item.source });
648
+ const mcp = (0, framework_1.bundleMcpOf)(manifest, ctx.env, item.source.type === 'github' ? item.source.url : undefined);
649
+ const record = async (tool, location, target, syncSiblings) => {
650
+ // An MCP server another writer put in the tool's file refuses the update before any file is written.
651
+ await (0, framework_1.checkPlannedInstallMcp)(prepared.service, { bundleId, tool, location }, target, ctx, manifest.version, mcp);
652
+ return (0, framework_1.recordPlannedInstall)(prepared.service, { ...item, bundleId, tool, location, sourceType: item.source.type }, target, ctx, manifest.version, await writeForTarget(ctx, target, files, manifest, prepared.exclusion), syncSiblings, { name: manifest.id, files }, mcp);
653
+ };
654
+ // The primary save only finds the siblings: each keeps its entry, and the files it lists, until
655
+ // its own update succeeds, so a failed sibling keeps its version and the cleanup keeps its files.
656
+ const change = await record(item.tool, item.location, item.target, () => false);
657
+ const changes = [change];
658
+ const synced = [];
659
+ const outOfDate = [];
660
+ const failed = [];
661
+ for (const sibling of change.siblings) {
662
+ const siblingTarget = siblingTargets.get(sibling.tool);
663
+ if (siblingTarget === undefined) {
664
+ outOfDate.push({ tool: sibling.tool, version: sibling.version });
665
+ continue;
666
+ }
667
+ // A failed sibling, MCP conflict or record error included, is reported; the primary change is
668
+ // already saved, so it is returned and the caller still finishes its cleanup.
669
+ try {
670
+ changes.push(await record(sibling.tool, sibling.location, siblingTarget, false));
671
+ synced.push(sibling.tool);
672
+ }
673
+ catch (error) {
674
+ failed.push({ tool: sibling.tool, reason: error instanceof Error ? error.message : String(error) });
675
+ }
676
+ }
677
+ return { version: manifest.version, changes, synced, outOfDate, failed };
678
+ }
679
+ function renderRecordUpdateOutput(d) {
680
+ const lines = [];
681
+ const updateLines = d.updates.map((u) => ` ${u.bundleId} (${u.tool}): ${u.from} → ${u.to}`);
682
+ if (d.dryRun === true) {
683
+ lines.push(...(updateLines.length > 0 ? [`Available updates (${String(updateLines.length)}):`, ...updateLines] : []));
684
+ }
685
+ else if (updateLines.length > 0) {
686
+ lines.push(`Updated ${String(updateLines.length)} entr${updateLines.length === 1 ? 'y' : 'ies'}:`, ...updateLines);
687
+ }
688
+ if (lines.length === 0 && d.failures.length === 0) {
689
+ lines.push(`All bundles are up to date. (checked ${String(d.checked)})`);
690
+ }
691
+ lines.push(...d.alsoUpdated.map((a) => `Also updated ${a.bundleId} for ${a.tool}.`), ...d.skipped.map((s) => `Skipped ${s.bundleId} (${s.tool}): ${s.reason}`));
692
+ if (d.oldFile !== undefined) {
693
+ const old = d.oldFile;
694
+ const verb = d.dryRun === true ? 'available' : 'updated';
695
+ lines.push(`Old file ${old.lockfile}: ${String(old.updates.length)} of ${String(old.checked)} bundle${old.checked === 1 ? '' : 's'} ${verb}.`, ...old.updates.map((u) => ` ${u.bundleId}: ${u.from} → ${u.to}`));
696
+ }
697
+ if (d.failures.length > 0) {
698
+ lines.push(`${String(d.failures.length)} update check${d.failures.length === 1 ? '' : 's'} or installation${d.failures.length === 1 ? '' : 's'} failed. Review the reported failures.`);
699
+ }
700
+ if (d.dryRun === true && updateLines.length > 0) {
701
+ lines.push('Re-run without --dry-run to apply.');
702
+ }
703
+ return lines.join('\n') + '\n' + (0, framework_1.renderMigration)(d.migration) + d.recordLine;
704
+ }
705
+ /**
706
+ * Update every tool entry of the selected repository record.
707
+ * @param run Update inputs.
708
+ * @returns Exit code.
709
+ */
710
+ async function updateFromRecord(run) {
711
+ const { ctx, fmt, http, prepared } = run;
712
+ const { selection, service, fs } = prepared;
713
+ const { items, skipped, notes, mapTool } = await planRecordUpdates(run);
714
+ const checked = items.length + skipped.length;
715
+ const failures = [];
716
+ const found = [];
717
+ for (const item of items.filter((planned) => isRemoteSource(planned.source.type))) {
718
+ const lookup = await findUpdateCandidates([item.bundleId], lookupLockfile(item), ctx, http, (0, framework_1.tokensForRecordSource)(run.tokens, item.fromRecord), item.fromRecord);
719
+ failures.push(...lookup.failures);
720
+ found.push(...lookup.candidates.map((candidate) => ({ item, candidate })));
721
+ // A lookup that found no installable release is reported, not taken as up to date.
722
+ if (lookup.skipped.includes(item.bundleId) && lookup.failures.length === 0) {
723
+ skipped.push({ bundleId: item.bundleId, tool: item.tool, reason: `no installable release found at ${item.source.url}` });
724
+ }
725
+ }
726
+ const data = {
727
+ ...await (0, framework_1.recordOutputFields)(selection, fs),
728
+ checked,
729
+ updated: 0,
730
+ updates: [],
731
+ alsoUpdated: [],
732
+ skipped,
733
+ failures,
734
+ ...(prepared.migration === undefined ? {} : { migration: prepared.migration })
735
+ };
736
+ const warnings = [...notes];
737
+ if (run.dryRun) {
738
+ data.dryRun = true;
739
+ data.updates = found.map(({ item, candidate }) => ({ bundleId: item.bundleId, tool: item.tool, from: candidate.from, to: candidate.to }));
518
740
  }
519
741
  else {
520
- bundles[idx] = bundleState;
742
+ const chosen = new Set(await selectUpdatesInteractively(run.interactive, found.map(({ candidate }) => candidate)));
743
+ const rows = await service.listEntries(selection.locations);
744
+ const done = new Set();
745
+ const changes = [];
746
+ for (const { item, candidate } of found.filter((pair) => chosen.has(pair.candidate))) {
747
+ const key = entryKey(item.bundleId, item.entry.version, item.tool);
748
+ if (done.has(key)) {
749
+ continue;
750
+ }
751
+ const identity = (0, app_1.recordIdentityOf)(item.bundleId, item.entry.version);
752
+ const siblingTargets = new Map();
753
+ const sameBundle = (other) => other.bundleId === item.bundleId || (0, app_1.recordIdentityOf)(other.bundleId, other.version) === identity;
754
+ for (const row of rows.filter((other) => sameBundle(other) && other.tool !== item.tool && !other.needsReinstall)) {
755
+ const mapping = await mapTool(row.tool);
756
+ if ('target' in mapping) {
757
+ siblingTargets.set(row.tool, (0, framework_1.resolveEffectiveTarget)(ctx, mapping.target));
758
+ }
759
+ }
760
+ try {
761
+ const applied = await applyRecordUpdate(run, item, candidate, siblingTargets);
762
+ changes.push(...applied.changes);
763
+ done.add(key);
764
+ data.updates.push({ bundleId: item.bundleId, tool: item.tool, from: candidate.from, to: applied.version });
765
+ for (const tool of applied.synced) {
766
+ done.add(entryKey(item.bundleId, item.entry.version, tool));
767
+ data.alsoUpdated.push({ bundleId: item.bundleId, tool });
768
+ }
769
+ for (const sibling of applied.failed) {
770
+ failures.push(`Failed to update ${item.bundleId} for ${sibling.tool}: ${sibling.reason}`);
771
+ }
772
+ for (const stale of applied.outOfDate) {
773
+ const mapping = await mapTool(stale.tool);
774
+ const why = 'skip' in mapping ? mapping.skip : 'not updated';
775
+ const existing = skipped.find((s) => s.bundleId === item.bundleId && s.tool === stale.tool);
776
+ const reason = `out of date (still ${stale.version}): ${existing?.reason ?? why}`;
777
+ if (existing === undefined) {
778
+ skipped.push({ bundleId: item.bundleId, tool: stale.tool, reason });
779
+ }
780
+ else {
781
+ existing.reason = reason;
782
+ }
783
+ }
784
+ }
785
+ catch (error) {
786
+ failures.push(`Failed to update ${item.bundleId} for ${item.tool}: ${error instanceof Error ? error.message : String(error)}`);
787
+ }
788
+ }
789
+ warnings.push(...await (0, framework_1.finishRecordRun)(service, changes));
790
+ data.updated = data.updates.length;
791
+ }
792
+ // Bundles only in the old file are updated with the old code; the record wins for the others.
793
+ const oldFile = await updateOldFileOnly(run);
794
+ if (oldFile !== undefined) {
795
+ data.oldFile = oldFile;
796
+ failures.push(...oldFile.failures);
797
+ }
798
+ // Exit 1 when every planned entry was skipped.
799
+ const nothingProcessed = checked > 0 && items.length === 0 && (oldFile === undefined || oldFile.checked === oldFile.skipped);
800
+ (0, framework_1.formatOutput)({
801
+ ctx,
802
+ command: 'update',
803
+ output: fmt,
804
+ status: failures.length > 0 || skipped.length > 0 ? 'warning' : 'ok',
805
+ data,
806
+ warnings: [...warnings, ...failures],
807
+ textRenderer: (d) => renderRecordUpdateOutput({ ...d, recordLine: (0, framework_1.renderRecordLine)({ level: d.level, records: d.records }) })
808
+ });
809
+ return failures.length > 0 || nothingProcessed ? 1 : 0;
810
+ }
811
+ /**
812
+ * Update the bundles only the old `prompt-registry.*` file has, with the old code and on that file.
813
+ * They go to the `--target` or only configured target, with the overrides applied, else fail per bundle.
814
+ * @param run Update inputs.
815
+ * @returns `undefined` when there is no old-file-only bundle.
816
+ */
817
+ async function updateOldFileOnly(run) {
818
+ const { ctx, http, tokens } = run;
819
+ const old = await (0, framework_1.prepareOldFileOnly)(ctx, run.prepared, { command: 'update', target: run.explicit, overrides: run.overrides });
820
+ if (old === undefined) {
821
+ return undefined;
822
+ }
823
+ const { lockPath, lock, bundleIds } = old;
824
+ if ('reason' in old) {
825
+ return {
826
+ lockfile: lockPath, checked: bundleIds.length, updated: 0, updates: [], skipped: 0,
827
+ failures: bundleIds.map((bundleId) => `Failed to update ${bundleId}: ${old.reason}`)
828
+ };
829
+ }
830
+ const { target } = old;
831
+ const { candidates, skipped, failures } = await findUpdateCandidates(remoteBundleIds(lock, bundleIds), lock, ctx, http, tokens);
832
+ const checkedOnly = {
833
+ lockfile: lockPath,
834
+ checked: bundleIds.length,
835
+ updated: 0,
836
+ updates: candidates.map((c) => ({ bundleId: c.bundleId, from: c.from, to: c.to })),
837
+ skipped: skipped.length,
838
+ failures
839
+ };
840
+ if (run.dryRun) {
841
+ return checkedOnly;
521
842
  }
522
- await stateStore.save({ targetName: target.name, lastInstalledBundles: bundles, lastUsedAt: new Date().toISOString() });
843
+ const toInstall = await selectUpdatesInteractively(run.interactive, candidates);
844
+ const applied = await applyUpdates(toInstall, target, target.scope, target.commitMode ?? 'commit', lockPath, ctx, http, tokens);
845
+ return { ...checkedOnly, updated: applied.updatedCount, updates: applied.updateResults, failures: [...failures, ...applied.failures] };
523
846
  }
524
847
  //# sourceMappingURL=update.js.map