@ai-primitives-hub/cli 0.2.0 → 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 (112) 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 +95 -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/dist/main.d.ts.map +1 -1
  106. package/dist/main.js +3 -1
  107. package/dist/main.js.map +1 -1
  108. package/dist/version.d.ts +7 -0
  109. package/dist/version.d.ts.map +1 -0
  110. package/dist/version.js +15 -0
  111. package/dist/version.js.map +1 -0
  112. package/package.json +6 -4
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.ProfilePublishCommand = exports.ProfileEditCommand = exports.ProfileCreateCommand = exports.ProfileDeactivateCommand = exports.ProfileActivateCommand = exports.ProfileCurrentCommand = exports.ProfileShowCommand = exports.ProfileListCommand = exports.buildHubMgr = void 0;
36
+ exports.ProfilePublishCommand = exports.ProfileEditCommand = exports.ProfileCreateCommand = exports.ProfileDeactivateCommand = exports.ProfileInstallCommand = exports.ProfileActivateCommand = exports.ProfileCurrentCommand = exports.ProfileShowCommand = exports.ProfileListCommand = exports.buildHubMgr = void 0;
37
37
  exports.runProfileActivation = runProfileActivation;
38
38
  /**
39
39
  * `profile` commands.
@@ -55,16 +55,10 @@ exports.runProfileActivation = runProfileActivation;
55
55
  * `ProfileLifecycleSync` that writes the bundles.
56
56
  *
57
57
  * Activation writes bundle files to every configured target (optionally
58
- * filtered via `--target`), reusing the same fetch/write primitives as
59
- * `install.ts` (`fetchFilesForSource`, `createWriterFactory`) and the same
60
- * removal primitives as `uninstall.ts` (`runUserScopeUninstall`,
61
- * `UninstallPipeline`) for deactivation. Unlike the reference branch, there
62
- * is no per-entry `target` field or `useProfile` field on the lockfile
63
- * (see `stores/json-lockfile-store.ts`'s module doc) — activation state
64
- * (which hub/profile is active, and which bundles it synced) is tracked
65
- * exclusively via `ProfileActivationStore`, and each target's own lockfile
66
- * (resolved via `lockfilePathForTarget`) is updated per bundle exactly as
67
- * a direct `install` would.
58
+ * filtered via `--target`) with the same primitives as `install`. Repository
59
+ * and user targets record bundles in the install record, as `install` and
60
+ * `uninstall` do; workspace targets keep the older user lockfile. Activation
61
+ * state is tracked only via `ProfileActivationStore`.
68
62
  */
69
63
  const path = __importStar(require("node:path"));
70
64
  const app_1 = require("@ai-primitives-hub/app");
@@ -72,9 +66,36 @@ const core_1 = require("@ai-primitives-hub/core");
72
66
  const infra_1 = require("@ai-primitives-hub/infra");
73
67
  const yaml = __importStar(require("js-yaml"));
74
68
  const framework_1 = require("../framework");
75
- const framework_2 = require("../framework");
76
69
  const install_1 = require("./install");
77
70
  const uninstall_1 = require("./uninstall");
71
+ /**
72
+ * Re-wrap a record error under a profile command's name; the original error is used, since activation rolls back its files.
73
+ * @param command - message prefix
74
+ * @param error - any error
75
+ */
76
+ const toProfileRecordError = (command, error) => {
77
+ if (!(0, core_1.isRecordError)(error)) {
78
+ return error;
79
+ }
80
+ const original = (0, core_1.isRecordError)(error.cause) ? error.cause : error;
81
+ return (0, framework_1.toCommandRecordError)(command, original);
82
+ };
83
+ const errorMessage = (error) => (error instanceof Error ? error.message : String(error));
84
+ /**
85
+ * The `Record: <level> <path>` lines, one per level, each file once.
86
+ * @param records - record files per target
87
+ */
88
+ const renderProfileRecordLines = (records) => {
89
+ const byLevel = new Map();
90
+ for (const record of records) {
91
+ const paths = byLevel.get(record.level) ?? [];
92
+ if (!paths.includes(record.path)) {
93
+ paths.push(record.path);
94
+ }
95
+ byLevel.set(record.level, paths);
96
+ }
97
+ return [...byLevel].map(([level, paths]) => (0, framework_1.renderRecordLine)({ level, records: paths })).join('');
98
+ };
78
99
  /**
79
100
  * Build HubManager and related instances.
80
101
  * @param ctx CLI context.
@@ -113,7 +134,7 @@ const resolveHubId = async (mgr, hubId) => {
113
134
  }
114
135
  const active = await mgr.getActiveHub();
115
136
  if (!active) {
116
- throw new framework_2.RegistryError({
137
+ throw new framework_1.RegistryError({
117
138
  code: 'HUB.NOT_FOUND',
118
139
  message: 'no active hub',
119
140
  hint: 'Run `ai-primitives-hub hub add` to import a hub, then `hub use <id>` to activate it.'
@@ -162,14 +183,14 @@ class ProfileListCommand extends BaseProfileCommand {
162
183
  hubId = await resolveHubId(mgr, this.hubId);
163
184
  }
164
185
  catch (err) {
165
- if (err instanceof framework_2.RegistryError) {
186
+ if (err instanceof framework_1.RegistryError) {
166
187
  return (0, framework_1.failWith)(ctx, fmt, 'profile', err);
167
188
  }
168
189
  throw err;
169
190
  }
170
191
  const hubs = await mgr.listHubs();
171
192
  if (!hubs.some((h) => h.id === hubId)) {
172
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
193
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
173
194
  code: 'HUB.NOT_FOUND',
174
195
  message: `profile list: hub "${hubId}" not found`,
175
196
  hint: 'Run `ai-primitives-hub hub list` to see available hubs.'
@@ -183,7 +204,7 @@ class ProfileListCommand extends BaseProfileCommand {
183
204
  id: p.id, name: p.name, bundles: p.bundles.length
184
205
  }))
185
206
  : [];
186
- (0, framework_2.formatOutput)({
207
+ (0, framework_1.formatOutput)({
187
208
  ctx, command: 'profile.list', output: fmt, status: 'ok',
188
209
  data: { hubId, profiles, sourceCount },
189
210
  textRenderer: (d) => d.profiles.length === 0
@@ -221,7 +242,7 @@ class ProfileShowCommand extends BaseProfileCommand {
221
242
  const built = (0, exports.buildHubMgr)(ctx, http, tokens);
222
243
  const mgr = built.mgr;
223
244
  if (!this.profileId) {
224
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
245
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
225
246
  code: 'USAGE.MISSING_FLAG',
226
247
  message: 'profile show: <profileId> required'
227
248
  }));
@@ -231,7 +252,7 @@ class ProfileShowCommand extends BaseProfileCommand {
231
252
  hubId = await resolveHubId(mgr, this.hubId);
232
253
  }
233
254
  catch (err) {
234
- if (err instanceof framework_2.RegistryError) {
255
+ if (err instanceof framework_1.RegistryError) {
235
256
  return (0, framework_1.failWith)(ctx, fmt, 'profile', err);
236
257
  }
237
258
  throw err;
@@ -242,13 +263,13 @@ class ProfileShowCommand extends BaseProfileCommand {
242
263
  }
243
264
  const profile = active.config.profiles.find((p) => p.id === this.profileId);
244
265
  if (profile === undefined) {
245
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
266
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
246
267
  code: 'BUNDLE.NOT_FOUND',
247
268
  message: `profile show: "${this.profileId}" not in hub "${hubId}"`,
248
269
  hint: 'Run `ai-primitives-hub profile list` to see available profiles.'
249
270
  }));
250
271
  }
251
- (0, framework_2.formatOutput)({
272
+ (0, framework_1.formatOutput)({
252
273
  ctx, command: 'profile.show', output: fmt, status: 'ok',
253
274
  data: { hubId, profile },
254
275
  textRenderer: (d) => `${d.profile.name} (${d.profile.id})\n`
@@ -281,14 +302,14 @@ class ProfileCurrentCommand extends BaseProfileCommand {
281
302
  const allActive = await built.activations.listAll();
282
303
  const active = allActive[0];
283
304
  if (!active) {
284
- (0, framework_2.formatOutput)({
305
+ (0, framework_1.formatOutput)({
285
306
  ctx, command: 'profile.current', output: fmt, status: 'ok',
286
307
  data: { active: null },
287
308
  textRenderer: () => 'No active profile.\n'
288
309
  });
289
310
  return 0;
290
311
  }
291
- (0, framework_2.formatOutput)({
312
+ (0, framework_1.formatOutput)({
292
313
  ctx, command: 'profile.current', output: fmt, status: 'ok',
293
314
  data: { active: { hubId: active.hubId, profileId: active.profileId } },
294
315
  textRenderer: (d) => `Active profile: ${d.active.profileId} (hub: ${d.active.hubId})\n`
@@ -310,19 +331,19 @@ exports.ProfileCurrentCommand = ProfileCurrentCommand;
310
331
  * @param tokens Token provider.
311
332
  * @param ctx CLI context.
312
333
  * @param sourceAwareDependencyCache
334
+ * @param record - The target's prepared install record; its MCP servers are checked before any file is written.
313
335
  * @returns The written files and lockfile entries on success, or a failure reason.
314
336
  */
315
- async function activateBundleForTarget(bundleRef, sources, target, writer, http, tokens, ctx, sourceAwareDependencyCache) {
337
+ async function activateBundleForTarget(bundleRef, sources, target, writer, http, tokens, ctx, sourceAwareDependencyCache, record) {
316
338
  const src = sources[bundleRef.source];
317
339
  if (!src) {
318
340
  return { ok: false, reason: `source "${bundleRef.source}" not found in hub` };
319
341
  }
320
- const sourceEntry = {
321
- type: src.type,
322
- url: src.url,
323
- ...(src.config?.branch ? { branch: src.config.branch } : {}),
324
- ...(src.config?.collectionsPath ? { collectionsPath: src.config.collectionsPath } : {})
325
- };
342
+ // Same record source as `install`, so the source trust gate sees one source.
343
+ const hub = await (0, framework_1.recordHubOf)(ctx, src).catch(() => undefined);
344
+ const source = (0, app_1.toRecordSource)(src, src.id, hub);
345
+ // The fetch entry keeps every recorded field, Artifactory's index file and auth included.
346
+ const sourceEntry = (0, app_1.toLockfileSourceEntry)(source);
326
347
  // `fetchFilesForSource` only reads `.version`/`.sourceId` off this
327
348
  // parameter — the rest are dummy values to satisfy `LockfileBundleEntry`'s
328
349
  // shape without fabricating a fake install history.
@@ -339,11 +360,15 @@ async function activateBundleForTarget(bundleRef, sources, target, writer, http,
339
360
  return { ok: false, reason: 'failed to fetch bundle files' };
340
361
  }
341
362
  const manifest = (0, core_1.validateManifest)(files, {
342
- expectedId: bundleRef.id,
363
+ // Artifactory identity is already bound to the resolved index entry during fetch.
364
+ expectedId: src.type === 'artifactory' ? undefined : bundleRef.id,
343
365
  expectedVersion: bundleRef.version === 'latest' ? undefined : bundleRef.version,
344
366
  // Hub profiles name GitHub bundles `{owner}-{repo}-{manifestId}`.
345
367
  sourceRepoSlug: (0, app_1.githubRepoSlugForSource)(src)
346
368
  });
369
+ const mcp = (0, framework_1.bundleMcpOf)(manifest, ctx.env, src.type === 'github' ? src.url : undefined);
370
+ // An MCP server another writer put in the tool's file refuses the bundle before any file is written.
371
+ await (0, framework_1.checkRepositoryInstallMcp)(record, { bundleId: bundleRef.id, version: manifest.version, tool: target.type, mcp });
347
372
  const { installableFiles: targetFiles, result } = await (0, app_1.writeBundleSafely)(writer, target, files, manifest);
348
373
  const entry = {
349
374
  version: manifest.version,
@@ -355,56 +380,90 @@ async function activateBundleForTarget(bundleRef, sources, target, writer, http,
355
380
  if (target.scope === 'repository') {
356
381
  entry.commitMode = target.commitMode ?? 'commit';
357
382
  }
358
- return { ok: true, written: result.written, entry, sourceEntry };
383
+ return {
384
+ ok: true, written: result.written, entry, sourceEntry, source, ...(hub === undefined ? {} : { hub }), bundle: { name: manifest.id, files }, mcp
385
+ };
359
386
  }
360
387
  catch (err) {
361
388
  return { ok: false, reason: err instanceof Error ? err.message : String(err) };
362
389
  }
363
390
  }
364
391
  /**
365
- * Remove every bundle recorded in a profile activation state from every
366
- * given target — the inverse of the activate loop below. Mirrors
367
- * `uninstall.ts`'s `performBundleUninstall` scope routing (repository
368
- * scope via `UninstallPipeline`, everything else via
369
- * `runUserScopeUninstall`), looped over every synced bundle. Best-effort:
370
- * a bundle missing from a given target's lockfile is silently skipped
371
- * (it was never written there).
392
+ * Remove a profile's bundles from one repository or user target through the record uninstall path.
393
+ * A bundle is matched by its id or, at any version of a versioned id, by its identity.
394
+ * A bundle whose only entry is `unknown` is kept and reported, since its tool is not known.
395
+ * @param ctx - CLI context
396
+ * @param bundles - bundles the profile synced
397
+ * @param target - effective repository or user target
398
+ * @param report - report to fill in
399
+ */
400
+ async function deactivateRecordTarget(ctx, bundles, target, report) {
401
+ const prepared = await (0, framework_1.prepareUninstallForTarget)(ctx, target);
402
+ if (prepared === undefined) {
403
+ return;
404
+ }
405
+ if (prepared.migration !== undefined) {
406
+ report.migrations.push(prepared.migration);
407
+ }
408
+ const rows = (await prepared.service.listEntries(prepared.locations)).filter((row) => row.tool === prepared.tool);
409
+ const removed = new Set();
410
+ const files = new Set();
411
+ for (const bundle of bundles) {
412
+ const identity = bundle.version === undefined ? bundle.id : (0, app_1.recordIdentityOf)(bundle.id, bundle.version);
413
+ const keys = [...new Set(rows
414
+ .filter((row) => row.bundleId === bundle.id || (0, app_1.recordIdentityOf)(row.bundleId, row.version) === identity)
415
+ .map((row) => row.bundleId))];
416
+ for (const key of keys.filter((candidate) => !removed.has(candidate))) {
417
+ const recorded = await (0, framework_1.recordRepositoryUninstall)(prepared, key);
418
+ removed.add(key);
419
+ files.add(recorded.lockfile);
420
+ report.warnings.push(...recorded.warnings);
421
+ }
422
+ if (keys.length === 0 && prepared.loneUnknown?.has(bundle.id) === true
423
+ && !report.unknown.some((kept) => kept.bundleId === bundle.id && kept.lockfile === prepared.location.path)) {
424
+ report.unknown.push({ bundleId: bundle.id, target: target.name, lockfile: prepared.location.path });
425
+ }
426
+ }
427
+ for (const file of files) {
428
+ report.records.push({ target: target.name, level: prepared.location.level, path: file });
429
+ }
430
+ }
431
+ /**
432
+ * Remove every bundle in a profile activation state from every target, the inverse of the activate loop.
433
+ * Best-effort: a target that fails becomes a warning.
372
434
  * @param ctx CLI context.
373
435
  * @param state Activation state recording which bundles were synced.
374
436
  * @param targets Targets to remove the profile's bundles from.
375
437
  */
376
438
  async function deactivateProfileBundles(ctx, state, targets) {
439
+ const report = { records: [], migrations: [], unknown: [], warnings: [] };
440
+ const syncedBundles = [...new Set(state.syncedBundles)].map((id) => {
441
+ const version = state.syncedBundleVersions?.[id];
442
+ return version === undefined ? { id } : { id, version };
443
+ });
377
444
  for (const configuredTarget of targets) {
378
445
  const target = (0, framework_1.resolveEffectiveTarget)(ctx, configuredTarget);
379
- if (target.scope === 'repository') {
380
- const pipeline = new app_1.UninstallPipeline({
381
- fs: ctx.fs,
382
- target,
383
- repositoryPath: target.rootPath ?? ctx.cwd(),
384
- writerFactory: (0, uninstall_1.createWriterFactory)(ctx, {})
385
- });
386
- for (const bundleId of state.syncedBundles) {
387
- try {
388
- await pipeline.run(bundleId);
389
- }
390
- catch {
391
- // Best-effort cleanup.
392
- }
446
+ if ((0, framework_1.usesInstallRecord)(target)) {
447
+ try {
448
+ await deactivateRecordTarget(ctx, syncedBundles, target, report);
449
+ }
450
+ catch (error) {
451
+ report.warnings.push(`${target.name}: ${errorMessage(toProfileRecordError('profile deactivate', error))}`);
393
452
  }
453
+ continue;
394
454
  }
395
- else {
396
- const lockPath = (0, framework_1.lockfilePathForTarget)(ctx, target);
397
- const writer = (0, uninstall_1.createWriterFactory)(ctx, {})(target);
398
- for (const bundleId of state.syncedBundles) {
399
- try {
400
- await (0, uninstall_1.runUserScopeUninstall)(bundleId, lockPath, target, ctx, writer);
401
- }
402
- catch {
403
- // Best-effort cleanup.
404
- }
455
+ const lockPath = (0, framework_1.lockfilePathForTarget)(ctx, target);
456
+ const writer = (0, uninstall_1.createWriterFactory)(ctx, {})(target);
457
+ for (const bundleId of state.syncedBundles) {
458
+ try {
459
+ await (0, uninstall_1.runUserScopeUninstall)(bundleId, lockPath, target, ctx, writer);
460
+ }
461
+ catch {
462
+ // Best-effort cleanup.
405
463
  }
406
464
  }
407
465
  }
466
+ return report;
408
467
  }
409
468
  /**
410
469
  * Deactivate whatever profile(s) were previously active, then activate
@@ -424,14 +483,17 @@ async function deactivateProfileBundles(ctx, state, targets) {
424
483
  */
425
484
  async function runProfileActivation(ctx, built, hubId, profile, targets) {
426
485
  const effectiveTargets = targets.map((target) => (0, framework_1.resolveEffectiveTarget)(ctx, target));
486
+ // Before the prior profile is cleaned up, so a refused activation changes nothing.
487
+ await refuseSameToolTargets(ctx, effectiveTargets);
427
488
  const lifecycle = { store: built.hubs, activationStore: built.activations };
428
489
  // The CLI's record of what is active is the activation store, not the hub
429
490
  // `active` flag that app's lifecycle scans (`hub sync` rewrites hub configs
430
491
  // and drops that flag). Deactivate every tracked profile first, including
431
492
  // this one when it is re-activated (`apply`), so bundles it no longer
432
- // lists are removed.
493
+ // lists are removed. Their migration reports and warnings join this output.
494
+ const prior = [];
433
495
  for (const prev of await built.activations.listAll()) {
434
- await deactivateTrackedProfile(ctx, lifecycle, prev, effectiveTargets);
496
+ prior.push(await deactivateTrackedProfile(ctx, lifecycle, prev, effectiveTargets));
435
497
  }
436
498
  const sync = createTargetProfileSync({
437
499
  ctx,
@@ -450,9 +512,13 @@ async function runProfileActivation(ctx, built, hubId, profile, targets) {
450
512
  throw sync.report.error;
451
513
  }
452
514
  if (!result.success) {
453
- // e.g. the activation state could not be saved after the install.
454
515
  await rollbackProfileActivation(ctx, lifecycle, hubId, profile.id, effectiveTargets, sync.report);
455
- throw new framework_2.RegistryError({
516
+ const missing = result.missingRequiredBundles ?? [];
517
+ if (missing.length > 0) {
518
+ throw requiredBundleMissingError('activate', hubId, profile.id, missing, sync.report.failures);
519
+ }
520
+ // e.g. the activation state could not be saved after the install.
521
+ throw new framework_1.RegistryError({
456
522
  code: 'HUB.ACTIVATION_FAILED',
457
523
  message: `profile activate: ${result.error ?? 'activation failed'}`,
458
524
  hint: 'Check that the hubs configuration directory is writable, then re-run the command.',
@@ -463,7 +529,42 @@ async function runProfileActivation(ctx, built, hubId, profile, targets) {
463
529
  if (state === null) {
464
530
  throw new Error(`profile activate: no activation state recorded for "${profile.id}"`);
465
531
  }
466
- return { state, written: sync.report.written, failures: sync.report.failures };
532
+ return {
533
+ state,
534
+ written: sync.report.written,
535
+ failures: sync.report.failures,
536
+ records: [...prior.flatMap((removed) => removed.records), ...sync.report.records],
537
+ migrations: [...prior.flatMap((removed) => removed.migrations), ...sync.report.migrations],
538
+ warnings: [
539
+ ...prior.flatMap((removed) => [...removed.warnings, ...removed.unknown.map((kept) => unknownBundleWarning(kept))]),
540
+ ...sync.report.warnings
541
+ ]
542
+ };
543
+ }
544
+ /**
545
+ * The error `profile activate` and `profile install` report when a
546
+ * `required: true` bundle was not installed.
547
+ * @param verb Subcommand name, used in the message.
548
+ * @param hubId Hub of the profile.
549
+ * @param profileId Profile id.
550
+ * @param missing Ids of the required bundles that were not installed.
551
+ * @param failures Per-bundle/per-target install failures, for the reasons.
552
+ * @param detail Optional sentence appended to the message.
553
+ * @returns The error.
554
+ */
555
+ function requiredBundleMissingError(verb, hubId, profileId, missing, failures, detail) {
556
+ const reasons = failures
557
+ .filter((f) => missing.includes(f.bundleId))
558
+ .map((f) => `${f.bundleId} (${f.target}): ${f.reason}`);
559
+ return new framework_1.RegistryError({
560
+ code: 'HUB.REQUIRED_BUNDLE_MISSING',
561
+ message: `profile ${verb}: required bundles were not installed: ${missing.join(', ')}`
562
+ + (reasons.length > 0 ? ` (${reasons.join('; ')})` : '')
563
+ + (detail === undefined ? '' : `. ${detail}`),
564
+ hint: 'Fix the install error of each required bundle (source configured, reachable, and authenticated), '
565
+ + 'then re-run the command. Bundles a profile can do without should be marked `required: false` in the hub.',
566
+ context: { hubId, profileId, missingRequiredBundles: missing }
567
+ });
467
568
  }
468
569
  /**
469
570
  * Remove a tracked profile's bundles from the targets, then clear its
@@ -474,14 +575,21 @@ async function runProfileActivation(ctx, built, hubId, profile, targets) {
474
575
  * @param targets Targets to remove the profile's bundles from.
475
576
  */
476
577
  async function deactivateTrackedProfile(ctx, lifecycle, state, targets) {
477
- await deactivateProfileBundles(ctx, state, targets);
578
+ const report = await deactivateProfileBundles(ctx, state, targets);
478
579
  const result = await (0, app_1.deactivateProfile)(lifecycle, state.hubId, state.profileId);
479
580
  if (!result.success) {
480
581
  // The hub or profile no longer exists, so there is no flag to clear;
481
582
  // the activation state must still go.
482
583
  await lifecycle.activationStore.delete(state.hubId, state.profileId);
483
584
  }
585
+ return report;
484
586
  }
587
+ /**
588
+ * Warning for a bundle kept because its record entry is `unknown`.
589
+ * @param kept - the kept bundle
590
+ */
591
+ const unknownBundleWarning = (kept) => `${kept.bundleId} (${kept.target}): kept, its entry in ${kept.lockfile} has tool unknown; `
592
+ + `run \`ai-primitives-hub uninstall ${kept.bundleId}\` to remove the entry (its files are kept)`;
485
593
  /**
486
594
  * Best-effort undo of a failed activation: deactivate the profile from
487
595
  * the state app's lifecycle saved (removes the bundles recorded in target
@@ -527,7 +635,7 @@ async function rollbackProfileActivation(ctx, lifecycle, hubId, profileId, targe
527
635
  * @returns The sync, plus the report it fills in.
528
636
  */
529
637
  function createTargetProfileSync(opts) {
530
- const report = { written: {}, failures: [] };
638
+ const report = { written: {}, failures: [], records: [], migrations: [], warnings: [] };
531
639
  return {
532
640
  report,
533
641
  deactivateProfile: async (profileId) => {
@@ -541,15 +649,66 @@ function createTargetProfileSync(opts) {
541
649
  return await installProfileBundles(opts, items.map((item) => item.bundleId), report);
542
650
  }
543
651
  catch (err) {
544
- report.error = err instanceof Error ? err : new Error(String(err));
652
+ const error = toProfileRecordError('profile activate', err);
653
+ report.error = error instanceof Error ? error : new Error(String(error));
545
654
  throw report.error;
546
655
  }
547
656
  }
548
657
  };
549
658
  }
550
659
  /**
551
- * Write the named profile bundles to every target and update each
552
- * target's lockfile, recording per-bundle/per-target failures.
660
+ * Refuse two targets of one tool at one level before anything changes, the
661
+ * prior profile's cleanup included; nothing is migrated or written.
662
+ * @param ctx - CLI context
663
+ * @param targets - effective targets
664
+ * @throws {RegistryError} `USAGE.INVALID_FLAG` naming both targets, or a `RECORD.*` error from loading.
665
+ */
666
+ async function refuseSameToolTargets(ctx, targets) {
667
+ const owners = new Map();
668
+ for (const target of targets.filter((candidate) => (0, framework_1.usesInstallRecord)(candidate))) {
669
+ const { selection } = await (0, framework_1.prepareRecordSelection)(ctx, { command: 'profile activate' }, target);
670
+ const key = `${selection.level}\u0000${selection.root}\u0000${target.type}`;
671
+ const owner = owners.get(key);
672
+ if (owner !== undefined) {
673
+ throw sameToolTargetsError(owner, target, selection.locations[0]?.path ?? selection.root);
674
+ }
675
+ owners.set(key, target.name);
676
+ }
677
+ }
678
+ const sameToolTargetsError = (owner, target, record, command = 'profile activate') => new framework_1.RegistryError({
679
+ code: 'USAGE.INVALID_FLAG',
680
+ message: `${command}: targets "${owner}" and "${target.name}" both record ${target.type} bundles in ${record}`,
681
+ hint: 'The install record keeps one entry per bundle and tool at a level. Pick one of them with --target.',
682
+ context: { targets: [owner, target.name], tool: target.type, record }
683
+ });
684
+ /**
685
+ * Prepare the install record of every repository and user target before any bundle is written.
686
+ * Refuses two targets of one tool at one level, since the record keeps one entry per bundle and tool.
687
+ * @param ctx - CLI context
688
+ * @param targets - effective targets
689
+ * @param command - message prefix
690
+ * @returns The prepared record per target name; workspace targets have none.
691
+ */
692
+ async function prepareProfileRecords(ctx, targets, command = 'profile activate') {
693
+ const prepared = new Map();
694
+ const owners = new Map();
695
+ for (const target of targets) {
696
+ const record = await (0, framework_1.prepareRecordForTarget)(ctx, target);
697
+ if (record === undefined) {
698
+ continue;
699
+ }
700
+ const key = `${record.location.level}\u0000${record.location.root}\u0000${target.type}`;
701
+ const owner = owners.get(key);
702
+ if (owner !== undefined) {
703
+ throw sameToolTargetsError(owner, target, record.location.path, command);
704
+ }
705
+ owners.set(key, target.name);
706
+ prepared.set(target.name, record);
707
+ }
708
+ return prepared;
709
+ }
710
+ /**
711
+ * Write the named profile bundles to every target and record them, noting per-bundle/per-target failures.
553
712
  * @param opts Sync options.
554
713
  * @param bundleIds Bundle ids to install, in profile order.
555
714
  * @param report Report to fill in.
@@ -564,29 +723,114 @@ async function installProfileBundles(opts, bundleIds, report) {
564
723
  const sourceAwareDependencyCache = (0, infra_1.isGitHubAppAuthEnabled)(ctx.env)
565
724
  ? (0, install_1.createSourceAwareInstallDependencyCache)(built.http, ctx)
566
725
  : undefined;
726
+ const records = await prepareProfileRecords(ctx, opts.targets);
727
+ for (const record of records.values()) {
728
+ if (record.migration !== undefined) {
729
+ report.migrations.push(record.migration);
730
+ }
731
+ }
567
732
  for (const target of opts.targets) {
568
733
  const writer = (0, install_1.createWriterFactory)(ctx, {})(target);
569
734
  const written = [];
570
735
  // Filled as bundles are written, so a failed activation can roll back
571
- // files no lockfile recorded yet.
736
+ // files no record or lockfile kept.
572
737
  report.written[target.name] = written;
738
+ const record = records.get(target.name);
573
739
  const lockPath = (0, framework_1.lockfilePathForTarget)(ctx, target);
574
- let lock = await (0, app_1.readLockfile)(lockPath, ctx.fs) ?? (0, app_1.emptyLockfile)('ai-primitives-hub-cli');
740
+ // Workspace targets keep the older user lockfile, as `install` does.
741
+ let lock = record === undefined
742
+ ? await (0, app_1.readLockfile)(lockPath, ctx.fs) ?? (0, app_1.emptyLockfile)('ai-primitives-hub-cli')
743
+ : undefined;
575
744
  for (const bundleRef of bundleRefs) {
576
- const outcome = await activateBundleForTarget(bundleRef, opts.sources, target, writer, built.http, built.tokens, ctx, sourceAwareDependencyCache);
745
+ const outcome = await activateBundleForTarget(bundleRef, opts.sources, target, writer, built.http, built.tokens, ctx, sourceAwareDependencyCache, record);
577
746
  if (!outcome.ok) {
578
747
  report.failures.push({ bundleId: bundleRef.id, target: target.name, reason: outcome.reason });
579
748
  continue;
580
749
  }
581
750
  written.push(...outcome.written);
582
- lock = (0, app_1.upsertBundleEntry)(lock, bundleRef.id, outcome.entry);
583
- lock = (0, app_1.upsertSource)(lock, outcome.entry.sourceId, outcome.sourceEntry);
751
+ if (lock !== undefined) {
752
+ lock = (0, app_1.upsertSource)((0, app_1.upsertBundleEntry)(lock, bundleRef.id, outcome.entry), outcome.entry.sourceId, outcome.sourceEntry);
753
+ }
754
+ else if (record !== undefined) {
755
+ const recorded = await (0, framework_1.recordRepositoryInstall)(record, {
756
+ bundleId: bundleRef.id,
757
+ version: outcome.entry.version,
758
+ tool: target.type,
759
+ source: outcome.source,
760
+ ...(outcome.hub === undefined ? {} : { hub: outcome.hub }),
761
+ writtenPaths: outcome.written,
762
+ bundle: outcome.bundle,
763
+ mcp: outcome.mcp
764
+ });
765
+ if (!report.records.some((file) => file.target === target.name && file.path === recorded.lockfile)) {
766
+ report.records.push({ target: target.name, level: record.location.level, path: recorded.lockfile });
767
+ }
768
+ report.warnings.push(...recorded.warnings);
769
+ }
584
770
  synced.set(bundleRef.id, outcome.entry.version);
585
771
  }
586
- await (0, app_1.writeLockfile)(lockPath, lock, ctx.fs);
772
+ if (lock !== undefined) {
773
+ await (0, app_1.writeLockfile)(lockPath, lock, ctx.fs);
774
+ }
587
775
  }
588
776
  return { synced: [...synced].map(([bundleId, version]) => ({ bundleId, version })) };
589
777
  }
778
+ /**
779
+ * Resolve the hub, the profile, and the targets a `profile activate` or
780
+ * `profile install` acts on, reporting a usage error when one is missing.
781
+ * @param ctx CLI context.
782
+ * @param fmt Output format.
783
+ * @param built HubManager + stores (from `buildHubMgr`).
784
+ * @param verb Subcommand name, used in messages.
785
+ * @param profileId `<profile-id>` argument.
786
+ * @param hubIdOption `--hub` value.
787
+ * @param targetsOption `--target` value (comma-separated names).
788
+ * @returns The hub id, profile, and targets, or the exit code of the reported error.
789
+ */
790
+ async function resolveProfileAndTargets(ctx, fmt, built, verb, profileId, hubIdOption, targetsOption) {
791
+ if (!profileId) {
792
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
793
+ code: 'USAGE.MISSING_FLAG',
794
+ message: `profile ${verb}: <profileId> required`,
795
+ hint: 'Run `ai-primitives-hub profile list` to see available profile IDs.'
796
+ }));
797
+ }
798
+ let hubId;
799
+ try {
800
+ hubId = await resolveHubId(built.mgr, hubIdOption);
801
+ }
802
+ catch (err) {
803
+ if (err instanceof framework_1.RegistryError) {
804
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', err);
805
+ }
806
+ throw err;
807
+ }
808
+ const active = await (0, framework_1.requireActiveHubOrFail)(built.mgr, hubId, `profile.${verb}`, ctx, fmt);
809
+ if (typeof active === 'number') {
810
+ return active;
811
+ }
812
+ const profile = active.config.profiles.find((p) => p.id === profileId);
813
+ if (profile === undefined) {
814
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
815
+ code: 'BUNDLE.NOT_FOUND',
816
+ message: `profile ${verb}: "${profileId}" not in hub "${hubId}"`,
817
+ hint: 'Run `ai-primitives-hub profile list` to see available profiles.'
818
+ }));
819
+ }
820
+ let targets = await (0, framework_1.loadTargets)(ctx);
821
+ if (targetsOption) {
822
+ const wanted = new Set(targetsOption.split(',').map((s) => s.trim()).filter((s) => s.length > 0));
823
+ targets = targets.filter((t) => wanted.has(t.name));
824
+ }
825
+ if (targets.length === 0) {
826
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
827
+ code: 'USAGE.MISSING_FLAG',
828
+ message: `profile ${verb}: no targets configured`,
829
+ hint: 'Run `ai-primitives-hub target add <name> --type <type>` to configure a target.'
830
+ }));
831
+ }
832
+ return { hubId, profile, targets };
833
+ }
590
834
  /**
591
835
  * profile activate - activate a profile
592
836
  */
@@ -617,49 +861,13 @@ class ProfileActivateCommand extends BaseProfileCommand {
617
861
  const { ctx, http, tokens } = this.commandContext;
618
862
  const fmt = (this.output ?? 'text');
619
863
  const built = (0, exports.buildHubMgr)(ctx, http, tokens);
620
- if (!this.profileId) {
621
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
622
- code: 'USAGE.MISSING_FLAG',
623
- message: 'profile activate: <profileId> required',
624
- hint: 'Run `ai-primitives-hub profile list` to see available profile IDs.'
625
- }));
626
- }
627
- let hubId;
628
- try {
629
- hubId = await resolveHubId(built.mgr, this.hubId);
630
- }
631
- catch (err) {
632
- if (err instanceof framework_2.RegistryError) {
633
- return (0, framework_1.failWith)(ctx, fmt, 'profile', err);
634
- }
635
- throw err;
636
- }
637
- const active = await (0, framework_1.requireActiveHubOrFail)(built.mgr, hubId, 'profile.activate', ctx, fmt);
638
- if (typeof active === 'number') {
639
- return active;
640
- }
641
- const profile = active.config.profiles.find((p) => p.id === this.profileId);
642
- if (profile === undefined) {
643
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
644
- code: 'BUNDLE.NOT_FOUND',
645
- message: `profile activate: "${this.profileId}" not in hub "${hubId}"`,
646
- hint: 'Run `ai-primitives-hub profile list` to see available profiles.'
647
- }));
648
- }
649
- let targets = await (0, framework_1.loadTargets)(ctx);
650
- if (this.targets) {
651
- const wanted = new Set(this.targets.split(',').map((s) => s.trim()).filter((s) => s.length > 0));
652
- targets = targets.filter((t) => wanted.has(t.name));
653
- }
654
- if (targets.length === 0) {
655
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
656
- code: 'USAGE.MISSING_FLAG',
657
- message: 'profile activate: no targets configured',
658
- hint: 'Run `ai-primitives-hub target add <name> --type <type>` to configure a target.'
659
- }));
864
+ const resolved = await resolveProfileAndTargets(ctx, fmt, built, 'activate', this.profileId, this.hubId, this.targets);
865
+ if (typeof resolved === 'number') {
866
+ return resolved;
660
867
  }
868
+ const { hubId, profile, targets } = resolved;
661
869
  if (this.dryRun) {
662
- (0, framework_2.formatOutput)({
870
+ (0, framework_1.formatOutput)({
663
871
  ctx, command: 'profile.activate', output: fmt, status: 'ok',
664
872
  data: {
665
873
  dryRun: true,
@@ -681,28 +889,405 @@ class ProfileActivateCommand extends BaseProfileCommand {
681
889
  activation = await runProfileActivation(ctx, built, hubId, profile, targets);
682
890
  }
683
891
  catch (err) {
684
- if (err instanceof framework_2.RegistryError) {
892
+ if (err instanceof framework_1.RegistryError) {
685
893
  return (0, framework_1.failWith)(ctx, fmt, 'profile', err);
686
894
  }
687
895
  throw err;
688
896
  }
689
- const { state, written, failures } = activation;
897
+ const { state, written, failures, records, migrations } = activation;
898
+ const warnings = [...failures.map((f) => `${f.bundleId} (${f.target}): ${f.reason}`), ...activation.warnings];
690
899
  const status = failures.length === 0 ? 'ok' : 'warning';
691
- (0, framework_2.formatOutput)({
900
+ (0, framework_1.formatOutput)({
692
901
  ctx, command: 'profile.activate', output: fmt, status,
693
- data: { hubId, profileId: profile.id, state, written, failures },
694
- warnings: failures.length > 0 ? failures.map((f) => `${f.bundleId} (${f.target}): ${f.reason}`) : undefined,
902
+ data: { hubId, profileId: profile.id, state, written, failures, records, ...(migrations.length > 0 ? { migrations } : {}) },
903
+ warnings: warnings.length > 0 ? warnings : undefined,
695
904
  textRenderer: (d) => `Activated profile "${d.profileId}" from hub "${d.hubId}":\n`
696
905
  + ` Bundles: ${[...new Set(d.state.syncedBundles)].join(', ')}\n`
697
906
  + ` Targets: ${Object.keys(d.written).join(', ')}\n`
698
907
  + (d.failures.length > 0
699
908
  ? ` Failures:\n${d.failures.map((f) => ` - ${f.bundleId} (${f.target}): ${f.reason}\n`).join('')}`
700
909
  : '')
910
+ + (d.migrations ?? []).map((migration) => (0, framework_1.renderMigration)(migration)).join('')
911
+ + renderProfileRecordLines(d.records)
701
912
  });
702
913
  return failures.length === 0 ? 0 : 1;
703
914
  }
704
915
  }
705
916
  exports.ProfileActivateCommand = ProfileActivateCommand;
917
+ /**
918
+ * Install `profile`'s bundles onto every target as ordinary installs,
919
+ * through app's shared `batchInstallProfile`, without activating the
920
+ * profile: no activation state is saved and active profiles stay active.
921
+ *
922
+ * Repository and user targets record the bundles in the install record,
923
+ * prepared before anything is written; workspace targets keep the older
924
+ * lockfile. What a target held before is read once, before anything is
925
+ * written. Only bundles new to a target count as added: undoing the batch
926
+ * removes the files this command wrote for them and, once those are gone,
927
+ * their entries. Files that cannot be removed stay tracked and are reported.
928
+ * @param ctx CLI context.
929
+ * @param built HubManager + HTTP/token deps (from `buildHubMgr`).
930
+ * @param hubId Hub the profile belongs to.
931
+ * @param profile Profile whose bundles to install.
932
+ * @param targets Targets to install onto.
933
+ * @returns The batch outcome plus per-target failures and the record files written.
934
+ * @throws {RegistryError} A `RECORD.*` error naming the file, or `USAGE.INVALID_FLAG` for two same-tool targets; nothing was written.
935
+ */
936
+ async function runProfileInstall(ctx, built, hubId, profile, targets) {
937
+ const effectiveTargets = targets.map((target) => (0, framework_1.resolveEffectiveTarget)(ctx, target));
938
+ const sources = Object.fromEntries((await built.mgr.listSources(hubId)).map((s) => [s.id, s]));
939
+ const failures = [];
940
+ const records = [];
941
+ const migrations = [];
942
+ const warnings = [];
943
+ const sourceAwareDependencyCache = (0, infra_1.isGitHubAppAuthEnabled)(ctx.env)
944
+ ? (0, install_1.createSourceAwareInstallDependencyCache)(built.http, ctx)
945
+ : undefined;
946
+ // Record entries before this command, per record target.
947
+ const prepared = new Map();
948
+ const recordedBefore = new Map();
949
+ try {
950
+ for (const [name, record] of await prepareProfileRecords(ctx, effectiveTargets, 'profile install')) {
951
+ prepared.set(name, record);
952
+ if (record.migration !== undefined) {
953
+ migrations.push(record.migration);
954
+ }
955
+ }
956
+ for (const target of effectiveTargets.filter((candidate) => prepared.has(candidate.name))) {
957
+ const uninstall = await (0, framework_1.prepareUninstallForTarget)(ctx, target);
958
+ if (uninstall !== undefined) {
959
+ recordedBefore.set(target.name, (await uninstall.service.listEntries(uninstall.locations))
960
+ .filter((row) => row.tool === uninstall.tool));
961
+ }
962
+ }
963
+ }
964
+ catch (error) {
965
+ throw toProfileRecordError('profile install', error);
966
+ }
967
+ // Lockfiles of workspace targets as they were before this command, by path.
968
+ const lockfilesBefore = new Map();
969
+ for (const target of effectiveTargets.filter((candidate) => !prepared.has(candidate.name))) {
970
+ const lockPath = (0, framework_1.lockfilePathForTarget)(ctx, target);
971
+ if (!lockfilesBefore.has(lockPath)) {
972
+ lockfilesBefore.set(lockPath, await (0, app_1.readLockfile)(lockPath, ctx.fs));
973
+ }
974
+ }
975
+ const versionBefore = (target, bundleId, version) => {
976
+ const rows = recordedBefore.get(target.name);
977
+ if (rows === undefined) {
978
+ return lockfilesBefore.get((0, framework_1.lockfilePathForTarget)(ctx, target))?.bundles[bundleId];
979
+ }
980
+ const identity = (0, app_1.recordIdentityOf)(bundleId, version);
981
+ return rows.find((row) => row.bundleId === bundleId || (0, app_1.recordIdentityOf)(row.bundleId, row.version) === identity);
982
+ };
983
+ // What this command added: files written for bundles new to a target, per
984
+ // target and bundle, and the entries it created, per target and bundle,
985
+ // with the bundle's status there.
986
+ const addedFiles = new Map();
987
+ const createdEntries = new Map();
988
+ const statusRank = { unchanged: 0, updated: 1, new: 2 };
989
+ // Each bundle's install outcome across targets (the strongest change wins).
990
+ const installed = new Map();
991
+ /**
992
+ * Drop the entry this command created for a bundle on a target. Where the
993
+ * bundle was new, it goes once its files there are gone (otherwise it stays,
994
+ * so `uninstall` can still find them). Where it was installed before, its
995
+ * files stay: a lockfile entry goes only when nothing changed; after an
996
+ * update it stays, since it describes the files on disk. A record keeps one
997
+ * entry per bundle and tool, so only a new bundle's entry is removed there.
998
+ * @param target - effective target
999
+ * @param bundleIds - bundles being removed
1000
+ * @param leftover - bundles whose files are still on this target
1001
+ */
1002
+ const dropCreatedEntries = async (target, bundleIds, leftover) => {
1003
+ const created = createdEntries.get(target.name) ?? new Map();
1004
+ const record = prepared.get(target.name);
1005
+ if (record !== undefined) {
1006
+ const drop = [...created].filter(([bundleId, status]) => status === 'new' && bundleIds.has(bundleId) && !leftover.has(bundleId));
1007
+ if (drop.length === 0) {
1008
+ return;
1009
+ }
1010
+ const uninstall = await (0, framework_1.prepareUninstallForTarget)(ctx, target);
1011
+ for (const [bundleId] of drop) {
1012
+ if (uninstall !== undefined) {
1013
+ await (0, framework_1.recordRepositoryUninstall)(uninstall, bundleId);
1014
+ }
1015
+ }
1016
+ const written = drop.flatMap(([bundleId]) => addedFiles.get(target.name)?.get(bundleId) ?? []);
1017
+ if (target.scope === 'repository' && target.commitMode === 'local-only' && written.length > 0) {
1018
+ await uninstall?.exclusion?.remove(written);
1019
+ }
1020
+ return;
1021
+ }
1022
+ const lockPath = (0, framework_1.lockfilePathForTarget)(ctx, target);
1023
+ let lock = await (0, app_1.readLockfile)(lockPath, ctx.fs);
1024
+ if (lock === null) {
1025
+ return;
1026
+ }
1027
+ for (const [bundleId, status] of created) {
1028
+ const entry = lock.bundles[bundleId];
1029
+ const drop = status === 'new' ? bundleIds.has(bundleId) && !leftover.has(bundleId) : status === 'unchanged';
1030
+ if (entry !== undefined && drop) {
1031
+ lock = (0, app_1.cleanupOrphanedSource)((0, app_1.removeBundleEntry)(lock, bundleId), entry.sourceId);
1032
+ }
1033
+ }
1034
+ await (0, app_1.writeLockfile)(lockPath, lock, ctx.fs);
1035
+ };
1036
+ const removeAdded = async (bundleIds) => {
1037
+ const leftovers = [];
1038
+ const removing = new Set(bundleIds);
1039
+ for (const target of effectiveTargets) {
1040
+ const writer = (0, install_1.createWriterFactory)(ctx, {})(target);
1041
+ const leftover = new Set();
1042
+ for (const bundleId of bundleIds) {
1043
+ const written = addedFiles.get(target.name)?.get(bundleId) ?? [];
1044
+ try {
1045
+ await (writer.rollback === undefined
1046
+ ? Promise.all(written.map((file) => ctx.fs.remove(file)))
1047
+ : writer.rollback(target, written));
1048
+ }
1049
+ catch {
1050
+ // Checked file by file below.
1051
+ }
1052
+ for (const file of written) {
1053
+ if (await ctx.fs.exists(file)) {
1054
+ leftovers.push(file);
1055
+ leftover.add(bundleId);
1056
+ }
1057
+ }
1058
+ }
1059
+ await dropCreatedEntries(target, removing, leftover);
1060
+ }
1061
+ if (leftovers.length > 0) {
1062
+ throw new Error(`could not remove ${leftovers.join(', ')}`);
1063
+ }
1064
+ };
1065
+ /**
1066
+ * Note a bundle's install on a target: the files it added and the entry it created.
1067
+ * @param target - effective target
1068
+ * @param bundleId - bundle id
1069
+ * @param version - installed version
1070
+ * @param status - how the install changed the target
1071
+ * @param written - files written
1072
+ */
1073
+ const noteInstalled = (target, bundleId, version, status, written) => {
1074
+ if (status === 'new') {
1075
+ const files = addedFiles.get(target.name) ?? new Map();
1076
+ addedFiles.set(target.name, files.set(bundleId, written));
1077
+ }
1078
+ createdEntries.set(target.name, (createdEntries.get(target.name) ?? new Map()).set(bundleId, status));
1079
+ const previous = installed.get(bundleId);
1080
+ installed.set(bundleId, {
1081
+ version,
1082
+ status: previous !== undefined && statusRank[previous.status] > statusRank[status] ? previous.status : status
1083
+ });
1084
+ };
1085
+ /**
1086
+ * Install the bundles onto one target and record them.
1087
+ * @param target - effective target
1088
+ * @param bundleRefs - bundles to install
1089
+ */
1090
+ const installOnTarget = async (target, bundleRefs) => {
1091
+ const writer = (0, install_1.createWriterFactory)(ctx, {})(target);
1092
+ const record = prepared.get(target.name);
1093
+ const lockPath = (0, framework_1.lockfilePathForTarget)(ctx, target);
1094
+ let lock = record === undefined
1095
+ ? await (0, app_1.readLockfile)(lockPath, ctx.fs) ?? (0, app_1.emptyLockfile)('ai-primitives-hub-cli')
1096
+ : undefined;
1097
+ const superseded = [];
1098
+ for (const bundleRef of bundleRefs) {
1099
+ const outcome = await activateBundleForTarget(bundleRef, sources, target, writer, built.http, built.tokens, ctx, sourceAwareDependencyCache, record);
1100
+ if (!outcome.ok) {
1101
+ failures.push({ bundleId: bundleRef.id, target: target.name, reason: outcome.reason });
1102
+ continue;
1103
+ }
1104
+ const before = versionBefore(target, bundleRef.id, outcome.entry.version);
1105
+ let status = 'new';
1106
+ if (before !== undefined) {
1107
+ const sameSource = before.sourceId === undefined || before.sourceId === outcome.entry.sourceId;
1108
+ status = before.version === outcome.entry.version && sameSource ? 'unchanged' : 'updated';
1109
+ }
1110
+ if (lock !== undefined) {
1111
+ // Like `install`, drop files a replaced version no longer ships.
1112
+ const previousFiles = lockfilesBefore.get(lockPath)?.bundles[bundleRef.id]?.files;
1113
+ if (previousFiles !== undefined) {
1114
+ superseded.push({ previous: previousFiles, next: outcome.entry.files });
1115
+ }
1116
+ lock = (0, app_1.upsertSource)((0, app_1.upsertBundleEntry)(lock, bundleRef.id, outcome.entry), outcome.entry.sourceId, outcome.sourceEntry);
1117
+ }
1118
+ else if (record !== undefined && status !== 'unchanged') {
1119
+ // An unchanged bundle keeps its entry, so a failed batch moves nothing between record files.
1120
+ if (status === 'new') {
1121
+ // Noted before recording, so a failed record still undoes the files.
1122
+ addedFiles.set(target.name, (addedFiles.get(target.name) ?? new Map()).set(bundleRef.id, outcome.written));
1123
+ }
1124
+ const recorded = await (0, framework_1.recordRepositoryInstall)(record, {
1125
+ bundleId: bundleRef.id,
1126
+ version: outcome.entry.version,
1127
+ tool: target.type,
1128
+ source: outcome.source,
1129
+ ...(outcome.hub === undefined ? {} : { hub: outcome.hub }),
1130
+ writtenPaths: outcome.written,
1131
+ bundle: outcome.bundle,
1132
+ mcp: outcome.mcp
1133
+ });
1134
+ if (!records.some((file) => file.target === target.name && file.path === recorded.lockfile)) {
1135
+ records.push({ target: target.name, level: record.location.level, path: recorded.lockfile });
1136
+ }
1137
+ warnings.push(...recorded.warnings);
1138
+ }
1139
+ noteInstalled(target, bundleRef.id, outcome.entry.version, status, outcome.written);
1140
+ }
1141
+ if (lock !== undefined) {
1142
+ await (0, app_1.writeLockfile)(lockPath, lock, ctx.fs);
1143
+ for (const { previous, next } of superseded) {
1144
+ await (0, app_1.removeSupersededFiles)(writer, target, previous, next);
1145
+ }
1146
+ }
1147
+ };
1148
+ const result = await (0, app_1.batchInstallProfile)({
1149
+ installBundles: async (bundleRefs) => {
1150
+ try {
1151
+ for (const target of effectiveTargets) {
1152
+ await installOnTarget(target, bundleRefs);
1153
+ }
1154
+ }
1155
+ catch (err) {
1156
+ // e.g. record or lockfile I/O: undo what this command added, then
1157
+ // report the error, together with what could not be undone.
1158
+ const error = toProfileRecordError('profile install', err);
1159
+ const newBundles = [...new Set([...addedFiles.values()].flatMap((files) => [...files.keys()]))];
1160
+ const undoError = await removeAdded(newBundles).then(() => undefined, (e) => e);
1161
+ if (undoError === undefined) {
1162
+ throw error;
1163
+ }
1164
+ throw new Error(`${errorMessage(error)}; undoing this install also failed: ${errorMessage(undoError)}`, { cause: error });
1165
+ }
1166
+ return {
1167
+ installed: [...installed].map(([bundleId, v]) => ({ bundleId, ...v })),
1168
+ failed: bundleRefs
1169
+ .filter((b) => !installed.has(b.id))
1170
+ .map((b) => ({
1171
+ bundleId: b.id,
1172
+ reason: failures.filter((f) => f.bundleId === b.id).map((f) => `${f.target}: ${f.reason}`).join('; ')
1173
+ }))
1174
+ };
1175
+ },
1176
+ removeBundles: removeAdded
1177
+ }, profile.bundles);
1178
+ return { result, failures, records, migrations, warnings };
1179
+ }
1180
+ /**
1181
+ * profile install - install a profile's bundles without activating it
1182
+ */
1183
+ class ProfileInstallCommand extends BaseProfileCommand {
1184
+ static paths = [['profile', 'install']];
1185
+ static usage = framework_1.Command.Usage({
1186
+ description: 'Install a profile\'s bundles on configured targets without activating the profile.',
1187
+ category: 'Hub & Discovery',
1188
+ details: `
1189
+ Usage: ai-primitives-hub profile install <profile-id> [options]
1190
+
1191
+ Installs every bundle of the profile as an ordinary install, recorded in
1192
+ the install record (workspace targets keep the older lockfile). The profile
1193
+ is not activated, active profiles stay active, and \`profile deactivate\`
1194
+ does not remove these bundles; use \`uninstall\` for that. When a required
1195
+ bundle cannot be installed, the bundles this command added are removed
1196
+ again and the command fails.
1197
+
1198
+ Options:
1199
+ --hub <hub-id> Hub ID containing the profile
1200
+ --target <name> Comma-separated target names to limit the install
1201
+ --dry-run Preview changes without applying
1202
+ -o, --output <format> Output format (text, json, yaml, ndjson)
1203
+
1204
+ Examples:
1205
+ ai-primitives-hub profile install default
1206
+ ai-primitives-hub profile install default --target vscode
1207
+ ai-primitives-hub profile install default --dry-run
1208
+ `
1209
+ });
1210
+ profileId = framework_1.Option.String({ required: false });
1211
+ targets = framework_1.Option.String('--target');
1212
+ dryRun = framework_1.Option.Boolean('--dry-run', false);
1213
+ async execute() {
1214
+ const { ctx, http, tokens } = this.commandContext;
1215
+ const fmt = (this.output ?? 'text');
1216
+ const built = (0, exports.buildHubMgr)(ctx, http, tokens);
1217
+ const resolved = await resolveProfileAndTargets(ctx, fmt, built, 'install', this.profileId, this.hubId, this.targets);
1218
+ if (typeof resolved === 'number') {
1219
+ return resolved;
1220
+ }
1221
+ const { hubId, profile, targets } = resolved;
1222
+ if (this.dryRun) {
1223
+ (0, framework_1.formatOutput)({
1224
+ ctx, command: 'profile.install', output: fmt, status: 'ok',
1225
+ data: {
1226
+ dryRun: true,
1227
+ hubId,
1228
+ profileId: profile.id,
1229
+ profileName: profile.name,
1230
+ bundles: profile.bundles.map((b) => b.id),
1231
+ targets: targets.map((t) => t.name)
1232
+ },
1233
+ textRenderer: (d) => `[dry-run] Would install the bundles of profile "${d.profileId}" from hub "${d.hubId}":\n`
1234
+ + ` Bundles: ${d.bundles.join(', ')}\n`
1235
+ + ` Targets: ${d.targets.join(', ')}\n`
1236
+ + 'Run without --dry-run to apply.\n'
1237
+ });
1238
+ return 0;
1239
+ }
1240
+ let run;
1241
+ try {
1242
+ run = await runProfileInstall(ctx, built, hubId, profile, targets);
1243
+ }
1244
+ catch (err) {
1245
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', err instanceof framework_1.RegistryError
1246
+ ? err
1247
+ : new framework_1.RegistryError({
1248
+ code: 'FS.PROFILE_INSTALL_FAILED',
1249
+ message: `profile install: ${err instanceof Error ? err.message : String(err)}`,
1250
+ hint: 'Check that the targets and the install record are writable, remove any file named above, then re-run the command.',
1251
+ context: { hubId, profileId: profile.id }
1252
+ }));
1253
+ }
1254
+ const { result, failures, records, migrations } = run;
1255
+ if (!result.success) {
1256
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', requiredBundleMissingError('install', hubId, profile.id, result.missingRequiredBundles ?? [], failures, result.removalError === undefined
1257
+ ? 'Bundles this command added were removed again'
1258
+ : `Removing the bundles this command added failed (${result.removalError}); remove those files manually`));
1259
+ }
1260
+ const warnings = [...failures.map((f) => `${f.bundleId} (${f.target}): ${f.reason}`), ...run.warnings];
1261
+ const status = failures.length === 0 ? 'ok' : 'warning';
1262
+ (0, framework_1.formatOutput)({
1263
+ ctx, command: 'profile.install', output: fmt, status,
1264
+ data: {
1265
+ hubId,
1266
+ profileId: profile.id,
1267
+ installed: result.installed,
1268
+ alreadyInstalled: result.alreadyInstalled,
1269
+ failures,
1270
+ targets: targets.map((t) => t.name),
1271
+ records,
1272
+ ...(migrations.length > 0 ? { migrations } : {})
1273
+ },
1274
+ warnings: warnings.length > 0 ? warnings : undefined,
1275
+ textRenderer: (d) => `Installed the bundles of profile "${d.profileId}" from hub "${d.hubId}" (profile not activated):\n`
1276
+ + ` Installed: ${d.installed.map((b) => `${b.bundleId}@${b.version}`).join(', ') || 'none'}\n`
1277
+ + (d.alreadyInstalled.length > 0
1278
+ ? ` Already installed: ${d.alreadyInstalled.map((b) => `${b.bundleId}@${b.version}`).join(', ')}\n`
1279
+ : '')
1280
+ + ` Targets: ${d.targets.join(', ')}\n`
1281
+ + (d.failures.length > 0
1282
+ ? ` Failures:\n${d.failures.map((f) => ` - ${f.bundleId} (${f.target}): ${f.reason}\n`).join('')}`
1283
+ : '')
1284
+ + (d.migrations ?? []).map((migration) => (0, framework_1.renderMigration)(migration)).join('')
1285
+ + renderProfileRecordLines(d.records)
1286
+ });
1287
+ return failures.length === 0 ? 0 : 1;
1288
+ }
1289
+ }
1290
+ exports.ProfileInstallCommand = ProfileInstallCommand;
706
1291
  /**
707
1292
  * profile deactivate - deactivate the active profile
708
1293
  */
@@ -731,7 +1316,7 @@ class ProfileDeactivateCommand extends BaseProfileCommand {
731
1316
  const allActive = await built.activations.listAll();
732
1317
  const cur = allActive[0];
733
1318
  if (!cur) {
734
- (0, framework_2.formatOutput)({
1319
+ (0, framework_1.formatOutput)({
735
1320
  ctx, command: 'profile.deactivate', output: fmt, status: 'ok',
736
1321
  data: { deactivated: null },
737
1322
  textRenderer: () => 'No active profile.\n'
@@ -739,7 +1324,7 @@ class ProfileDeactivateCommand extends BaseProfileCommand {
739
1324
  return 0;
740
1325
  }
741
1326
  if (this.dryRun) {
742
- (0, framework_2.formatOutput)({
1327
+ (0, framework_1.formatOutput)({
743
1328
  ctx, command: 'profile.deactivate', output: fmt, status: 'ok',
744
1329
  data: {
745
1330
  dryRun: true,
@@ -753,11 +1338,21 @@ class ProfileDeactivateCommand extends BaseProfileCommand {
753
1338
  return 0;
754
1339
  }
755
1340
  const targets = await (0, framework_1.loadTargets)(ctx);
756
- await deactivateTrackedProfile(ctx, { store: built.hubs, activationStore: built.activations }, cur, targets);
757
- (0, framework_2.formatOutput)({
758
- ctx, command: 'profile.deactivate', output: fmt, status: 'ok',
759
- data: { deactivated: { hubId: cur.hubId, profileId: cur.profileId } },
760
- textRenderer: (d) => `Deactivated profile "${d.deactivated?.profileId}".\n`
1341
+ const removed = await deactivateTrackedProfile(ctx, { store: built.hubs, activationStore: built.activations }, cur, targets);
1342
+ const warnings = [...removed.warnings, ...removed.unknown.map((kept) => unknownBundleWarning(kept))];
1343
+ (0, framework_1.formatOutput)({
1344
+ ctx, command: 'profile.deactivate', output: fmt, status: warnings.length === 0 ? 'ok' : 'warning',
1345
+ data: {
1346
+ deactivated: { hubId: cur.hubId, profileId: cur.profileId },
1347
+ records: removed.records,
1348
+ unknown: removed.unknown,
1349
+ ...(removed.migrations.length > 0 ? { migrations: removed.migrations } : {})
1350
+ },
1351
+ warnings: warnings.length > 0 ? warnings : undefined,
1352
+ textRenderer: (d) => `Deactivated profile "${d.deactivated.profileId}".\n`
1353
+ + d.unknown.map((kept) => ` kept ${kept.bundleId} (${kept.target}): tool unknown, files kept\n`).join('')
1354
+ + (d.migrations ?? []).map((migration) => (0, framework_1.renderMigration)(migration)).join('')
1355
+ + renderProfileRecordLines(d.records)
761
1356
  });
762
1357
  return 0;
763
1358
  }
@@ -795,13 +1390,13 @@ class ProfileCreateCommand extends BaseProfileCommand {
795
1390
  const built = (0, exports.buildHubMgr)(ctx, http, tokens);
796
1391
  const mgr = built.mgr;
797
1392
  if (!this.profileId) {
798
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
1393
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
799
1394
  code: 'USAGE.MISSING_FLAG',
800
1395
  message: 'profile create: <profile-id> is required'
801
1396
  }));
802
1397
  }
803
1398
  if (!this.name) {
804
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
1399
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
805
1400
  code: 'USAGE.MISSING_FLAG',
806
1401
  message: 'profile create: --name is required'
807
1402
  }));
@@ -825,7 +1420,7 @@ class ProfileCreateCommand extends BaseProfileCommand {
825
1420
  updatedAt: now,
826
1421
  bundles: profileBundles
827
1422
  });
828
- (0, framework_2.formatOutput)({
1423
+ (0, framework_1.formatOutput)({
829
1424
  ctx, command: 'profile.create', output: fmt, status: 'ok',
830
1425
  data: { hubId, profile: { id: profile.id, name: profile.name, bundles: profile.bundles.length } },
831
1426
  textRenderer: (d) => `Created profile "${d.profile.id}" in hub "${d.hubId}" with ${String(d.profile.bundles)} bundle${d.profile.bundles === 1 ? '' : 's'}.\n`
@@ -889,7 +1484,7 @@ class ProfileEditCommand extends BaseProfileCommand {
889
1484
  const built = (0, exports.buildHubMgr)(ctx, http, tokens);
890
1485
  const mgr = built.mgr;
891
1486
  if (!this.profileId) {
892
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
1487
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
893
1488
  code: 'USAGE.MISSING_FLAG',
894
1489
  message: 'profile edit: <profile-id> is required'
895
1490
  }));
@@ -898,7 +1493,7 @@ class ProfileEditCommand extends BaseProfileCommand {
898
1493
  const hubs = await mgr.listHubs();
899
1494
  const hub = hubs.find((h) => h.id === hubId);
900
1495
  if (!hub) {
901
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
1496
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
902
1497
  code: 'USAGE.MISSING_FLAG',
903
1498
  message: `profile edit: hub "${hubId}" not found`
904
1499
  }));
@@ -907,7 +1502,7 @@ class ProfileEditCommand extends BaseProfileCommand {
907
1502
  const profiles = active?.id === hubId ? active.config.profiles : [];
908
1503
  const existingProfile = profiles.find((p) => p.id === this.profileId);
909
1504
  if (!existingProfile) {
910
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
1505
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
911
1506
  code: 'USAGE.MISSING_FLAG',
912
1507
  message: `profile edit: profile "${this.profileId}" not found in hub "${hubId}"`
913
1508
  }));
@@ -926,7 +1521,7 @@ class ProfileEditCommand extends BaseProfileCommand {
926
1521
  bundles: updatedBundles,
927
1522
  updatedAt: new Date().toISOString()
928
1523
  });
929
- (0, framework_2.formatOutput)({
1524
+ (0, framework_1.formatOutput)({
930
1525
  ctx, command: 'profile.edit', output: fmt, status: 'ok',
931
1526
  data: { hubId, profile: { id: updatedProfile.id, name: updatedProfile.name, bundles: updatedProfile.bundles.length } },
932
1527
  textRenderer: (d) => `Updated profile "${d.profile.id}" in hub "${d.hubId}" with ${String(d.profile.bundles)} bundle${d.profile.bundles === 1 ? '' : 's'}.\n`
@@ -964,14 +1559,14 @@ class ProfilePublishCommand extends BaseProfileCommand {
964
1559
  const built = (0, exports.buildHubMgr)(ctx, http, tokens);
965
1560
  const mgr = built.mgr;
966
1561
  if (!this.profileId) {
967
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
1562
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
968
1563
  code: 'USAGE.MISSING_FLAG',
969
1564
  message: 'profile publish: <profile-id> is required',
970
1565
  hint: 'Run `ai-primitives-hub profile publish <id> --hub <hub-id>`'
971
1566
  }));
972
1567
  }
973
1568
  if (!this.hubId) {
974
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
1569
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
975
1570
  code: 'USAGE.MISSING_FLAG',
976
1571
  message: 'profile publish: --hub <id> is required',
977
1572
  hint: 'Run `ai-primitives-hub hub list` to see available hubs.'
@@ -979,7 +1574,7 @@ class ProfilePublishCommand extends BaseProfileCommand {
979
1574
  }
980
1575
  const profilePath = this.profileFile ?? path.join(ctx.cwd(), `${this.profileId}.profile.yml`);
981
1576
  if (!(await ctx.fs.exists(profilePath))) {
982
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
1577
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
983
1578
  code: 'FS.NOT_FOUND',
984
1579
  message: `Profile file not found: ${profilePath}`,
985
1580
  hint: 'Export a profile first or provide --file <path>.'
@@ -988,14 +1583,14 @@ class ProfilePublishCommand extends BaseProfileCommand {
988
1583
  const profileYaml = await ctx.fs.readFile(profilePath);
989
1584
  const parsed = yaml.load(profileYaml);
990
1585
  if (!parsed || typeof parsed !== 'object') {
991
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
1586
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
992
1587
  code: 'PROFILE.INVALID_YAML',
993
1588
  message: 'Profile YAML is invalid or empty'
994
1589
  }));
995
1590
  }
996
1591
  const hubs = await mgr.listHubs();
997
1592
  if (!hubs.some((h) => h.id === this.hubId)) {
998
- return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_2.RegistryError({
1593
+ return (0, framework_1.failWith)(ctx, fmt, 'profile', new framework_1.RegistryError({
999
1594
  code: 'HUB.NOT_FOUND',
1000
1595
  message: `Hub "${this.hubId}" not found`,
1001
1596
  hint: 'Run `ai-primitives-hub hub list` to see available hubs.'
@@ -1012,7 +1607,7 @@ class ProfilePublishCommand extends BaseProfileCommand {
1012
1607
  updatedAt: now,
1013
1608
  bundles: parsed.bundles ?? []
1014
1609
  });
1015
- (0, framework_2.formatOutput)({
1610
+ (0, framework_1.formatOutput)({
1016
1611
  ctx, command: 'profile.publish', output: fmt, status: 'ok',
1017
1612
  data: { profileId: this.profileId, hubId: this.hubId },
1018
1613
  textRenderer: (d) => `Published profile "${d.profileId}" to hub "${d.hubId}".\n`