@rbbtsn0w/adg 0.11.4 → 1.0.1

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 (41) hide show
  1. package/README.md +31 -12
  2. package/dist/src/agents/antigravity.js +218 -45
  3. package/dist/src/agents/claude.js +98 -38
  4. package/dist/src/agents/codex.js +1 -0
  5. package/dist/src/cli/core-plugin-handlers.js +3 -3
  6. package/dist/src/cli/handlers.js +160 -36
  7. package/dist/src/cli/index.js +19 -12
  8. package/dist/src/cli/review-update.js +80 -0
  9. package/dist/src/commands/install/default-dsl.js +1 -1
  10. package/dist/src/commands/install/install-one.js +41 -31
  11. package/dist/src/commands/install.js +38 -23
  12. package/dist/src/commands/marketplace.js +136 -109
  13. package/dist/src/commands/migrate.js +2 -2
  14. package/dist/src/commands/projection.js +3 -1
  15. package/dist/src/commands/remove.js +10 -0
  16. package/dist/src/commands/review-executables.js +106 -0
  17. package/dist/src/commands/select-agents.js +2 -2
  18. package/dist/src/commands/select-components.js +2 -2
  19. package/dist/src/commands/select-plugins.js +15 -2
  20. package/dist/src/commands/select-scope.js +3 -4
  21. package/dist/src/commands/source-upgrade.js +552 -0
  22. package/dist/src/commands/state.js +3 -1
  23. package/dist/src/commands/update.js +3 -1
  24. package/dist/src/lock.js +13 -5
  25. package/dist/src/migration-transaction.js +1011 -0
  26. package/dist/src/native-retry.js +329 -0
  27. package/dist/src/process-identity.js +65 -0
  28. package/dist/src/render/plugins.js +115 -9
  29. package/dist/src/source-history.js +194 -0
  30. package/dist/src/source-intent.js +7 -0
  31. package/dist/src/store-mutex.js +179 -0
  32. package/dist/src/types.js +1 -1
  33. package/dist/src/update-executables.js +193 -0
  34. package/dist/src/upgrade-plan.js +378 -0
  35. package/docs/agents/antigravity.md +5 -0
  36. package/docs/agents-spec.md +10 -0
  37. package/docs/branching-and-release.md +53 -0
  38. package/docs/plugin-update-semantics.md +30 -34
  39. package/docs/plugin-upgrade-migrations.md +349 -0
  40. package/package.json +4 -3
  41. package/schemas/plugin-lock.schema.json +78 -1
@@ -1,5 +1,5 @@
1
1
  import { existsSync } from "node:fs";
2
- import { resolve } from "node:path";
2
+ import { dirname, resolve } from "node:path";
3
3
  import { addPlugins } from "../commands/install.js";
4
4
  import { listPlugins } from "../commands/list.js";
5
5
  import { importSkills } from "../commands/import.js";
@@ -12,21 +12,46 @@ import { migrateLayout } from "../commands/migrate.js";
12
12
  import { cleanPluginCache, pluginCacheStatus, prunePluginCache, restorePluginCache } from "../commands/cache.js";
13
13
  import { marketplaceList, marketplaceRemove, marketplaceSync, updatePlugins } from "../commands/marketplace.js";
14
14
  import { confirmFullInstall, selectComponentsInteractive } from "../commands/select-components.js";
15
- import { selectPluginsInteractive } from "../commands/select-plugins.js";
15
+ import { FOLLOW_ALL_PLUGINS, selectPluginsInteractive } from "../commands/select-plugins.js";
16
16
  import { selectTargetsInteractive } from "../commands/select-agents.js";
17
17
  import { selectScopeInteractive, selectUpdateScopeInteractive } from "../commands/select-scope.js";
18
18
  import { globalPluginsDir, projectPluginsDir, lockPath } from "../paths.js";
19
19
  import { getAgent } from "../agents/index.js";
20
20
  import { ui } from "../render/ui.js";
21
21
  import { createProgress, formatUpdateSummary } from "../render/progress.js";
22
- import { renderAgentReport, renderMarketplaceList, renderUpdateReport, } from "../render/plugins.js";
23
- import { CACHE_USAGE, MARKETPLACE_USAGE, PLUGIN_ALIASES, PLUGIN_COMMANDS, SCOPE, fail, parseVerb, renderPluginsHelp, renderVerbHelp, requireSingleTarget, resolveComponents, resolveScopeDir, resolveTargets, scopeOf, wantsHelp, } from "./index.js";
22
+ import { renderAgentReport, renderMarketplaceList, renderUpdateReport, renderUpdateAgentReport, } from "../render/plugins.js";
23
+ import { CACHE_USAGE, MARKETPLACE_USAGE, PLUGIN_ALIASES, PLUGIN_COMMANDS, SCOPE, fail, parseVerb, renderPluginsHelp, renderVerbHelp, requireSingleTarget, resolveComponents, resolveScopeDir, resolveTargets, scopeOf, wantsHelp, CliUsageError, } from "./index.js";
24
24
  import { handleCorePluginVerb } from "./core-plugin-handlers.js";
25
25
  import { commandOutcome, mergeCommandOutcomes, agentCommandOutcome } from "../command-outcome.js";
26
+ import { withStoreMutex } from "../store-mutex.js";
27
+ import { discoverPendingMigrations } from "../migration-transaction.js";
28
+ import { UpdateCancelled } from "../commands/source-upgrade.js";
29
+ import { reviewUpdate } from "./review-update.js";
30
+ /** Pending transactions own the selected store until update resumes them. */
31
+ function assertNoPendingMigration(pluginsDir) {
32
+ if (discoverPendingMigrations(pluginsDir).length) {
33
+ throw new Error("A plugin migration is pending. Run `adg plugins update` with the same scope to resume it before making other changes.");
34
+ }
35
+ }
26
36
  export function updateResultCounts(result) {
27
- const failedRemote = result.remote.filter((source) => source.failed !== undefined || Boolean(source.missingUpstream?.length)).length;
28
- // A failed plugin remains one unit even if several stages report diagnostics.
29
- const runtimeFailures = new Set(result.agents.flatMap((agent) => (agent.failures ?? []).map((failure) => JSON.stringify([agent.agent, failure.plugin ?? null, failure.plugin ? null : failure.stage]))));
37
+ const failedRemote = result.remote.filter((source) => source.failed !== undefined || Boolean(source.missingUpstream?.length || source.actionRequired?.length || source.pendingRuntime?.length)).length;
38
+ // Replayed source diagnostics already account for their native failures.
39
+ const sourceMessages = new Set(result.remote.flatMap(source => source.pendingRuntime ?? []));
40
+ const runtimeFailures = new Set(result.agents.flatMap(agent => (agent.failures ?? [])
41
+ .filter(failure => !sourceMessages.has(failure.message))
42
+ .map(failure => JSON.stringify([agent.agent, failure.plugin ?? null, failure.plugin ? null : failure.stage]))));
43
+ const sourceReportedPlugins = new Set(result.agents.flatMap(agent => (agent.failures ?? [])
44
+ .filter(failure => failure.plugin && sourceMessages.has(failure.message))
45
+ .map(failure => JSON.stringify([agent.agent, failure.plugin, null]))));
46
+ for (const agent of result.agents) {
47
+ if (agent.skipped)
48
+ continue;
49
+ for (const plugin of agent.unverified ?? []) {
50
+ const key = JSON.stringify([agent.agent, plugin, null]);
51
+ if (!sourceReportedPlugins.has(key))
52
+ runtimeFailures.add(key);
53
+ }
54
+ }
30
55
  return {
31
56
  succeeded: result.remote.length - failedRemote +
32
57
  result.local.results.length,
@@ -53,7 +78,7 @@ async function resolveUpdateScopes(values) {
53
78
  choice = "global";
54
79
  else if (values.project)
55
80
  choice = "project";
56
- else if (process.stdin.isTTY)
81
+ else if (process.stdin.isTTY && !values.json)
57
82
  choice = await selectUpdateScopeInteractive();
58
83
  else
59
84
  choice = existsSync(lockPath(projectPluginsDir())) ? "project" : "global";
@@ -70,10 +95,14 @@ async function resolveUpdateScopes(values) {
70
95
  return [choice === "global" ? global : project];
71
96
  }
72
97
  /** Render an update/upgrade result: per-source changes, then per-agent re-sync. */
73
- function printUpdateReport(result) {
74
- for (const line of renderUpdateReport(result))
98
+ function printUpdateReport(result, verbose = false, retryCommand) {
99
+ for (const line of renderUpdateReport(result, { verbose, retryCommand }))
75
100
  console.log(line);
76
- for (const line of renderAgentReport(result.agents, "re-synced"))
101
+ for (const line of renderUpdateAgentReport(result.agents, {
102
+ verbose,
103
+ retryCommand,
104
+ reportedFailures: result.remote.flatMap(source => source.pendingRuntime ?? []),
105
+ }))
77
106
  console.log(line);
78
107
  }
79
108
  /**
@@ -110,6 +139,11 @@ export function promoteGlobalTrap(global, projectDir = projectPluginsDir(), glob
110
139
  * - promotes the home==global trap to global with a warning.
111
140
  */
112
141
  async function resolveActionScope(values, verb) {
142
+ const scope = await resolveActionScopeUnchecked(values, verb);
143
+ assertNoPendingMigration(scope.pluginsDir);
144
+ return scope;
145
+ }
146
+ async function resolveActionScopeUnchecked(values, verb) {
113
147
  if (typeof values.dir === "string") {
114
148
  // --dir is an explicit ad-hoc store; --global still selects the user agent
115
149
  // scope (matching the old scopeOf behavior), the trap guard doesn't apply.
@@ -124,7 +158,7 @@ async function resolveActionScope(values, verb) {
124
158
  global = true;
125
159
  else if (values.project)
126
160
  global = false;
127
- else if (process.stdin.isTTY)
161
+ else if (process.stdin.isTTY && !values.json)
128
162
  global = await selectScopeInteractive();
129
163
  else
130
164
  fail(`plugins ${verb} needs an explicit scope in a non-interactive run: pass --global or --project`);
@@ -155,6 +189,33 @@ function printCliUnavailableNote(target, message) {
155
189
  * dispatch surface is unit-testable.
156
190
  */
157
191
  export async function runPlugins(rawVerb, rest) {
192
+ const verb = rawVerb ? PLUGIN_ALIASES[rawVerb] ?? rawVerb : undefined;
193
+ const readOnly = !verb || ["help", "-h", "--help", "list", "status", "validate", "inspect"].includes(verb)
194
+ || wantsHelp(rest)
195
+ || (verb === "marketplace" && (!rest[0] || ["help", "list"].includes(rest[0])))
196
+ || (verb === "cache" && (!rest[0] || ["help", "status"].includes(rest[0])));
197
+ try {
198
+ if (readOnly)
199
+ return await dispatchPlugins(rawVerb, rest);
200
+ return await withStoreMutex(projectPluginsDir(), async () => {
201
+ // Prune operates across native registries rather than one chosen store.
202
+ if (verb === "prune") {
203
+ assertNoPendingMigration(projectPluginsDir());
204
+ assertNoPendingMigration(globalPluginsDir());
205
+ }
206
+ return await dispatchPlugins(rawVerb, rest);
207
+ });
208
+ }
209
+ catch (error) {
210
+ if (error instanceof CliUsageError)
211
+ return commandOutcome("failure", "user");
212
+ if (!(error instanceof UpdateCancelled))
213
+ throw error;
214
+ console.error(ui.warn("Cancelled; no further changes were made."));
215
+ return commandOutcome("cancelled");
216
+ }
217
+ }
218
+ async function dispatchPlugins(rawVerb, rest) {
158
219
  // `adg plugins` (no verb) or an explicit help request → the L1 overview.
159
220
  if (rawVerb === undefined || rawVerb === "-h" || rawVerb === "--help" || rawVerb === "help") {
160
221
  console.log(renderPluginsHelp());
@@ -192,7 +253,7 @@ async function handleAdd(rest, cmd) {
192
253
  const spec = positionals[0];
193
254
  if (!spec)
194
255
  fail("plugins add requires a <plugin-dir | owner/repo[@ref] | github-url>");
195
- const tty = process.stdin.isTTY;
256
+ const tty = process.stdin.isTTY && !values.json;
196
257
  let global = Boolean(values.global);
197
258
  if (!values.dir && values.global === undefined && values.project === undefined && tty) {
198
259
  global = await selectScopeInteractive();
@@ -204,11 +265,13 @@ async function handleAdd(rest, cmd) {
204
265
  : global
205
266
  ? globalPluginsDir()
206
267
  : projectPluginsDir();
268
+ assertNoPendingMigration(pluginsDir);
269
+ let followExplicit = false;
207
270
  const only = resolveComponents(values.only);
208
271
  const skillsSubset = values.skill && values.skill.length > 0 ? values.skill : undefined;
209
272
  const mcpSubset = values.mcp && values.mcp.length > 0 ? values.mcp : undefined;
210
273
  const narrowed = only !== undefined || skillsSubset !== undefined || mcpSubset !== undefined;
211
- const { order, installed, removed, converted, agents } = await addPlugins({
274
+ const result = await addPlugins({
212
275
  spec,
213
276
  pluginsDir,
214
277
  ref: values.ref,
@@ -222,7 +285,15 @@ async function handleAdd(rest, cmd) {
222
285
  marketplaceName: values["marketplace-name"],
223
286
  as: values.as,
224
287
  targets: values.target !== undefined ? resolveTargets(values.target) : undefined,
225
- selectPlugins: tty ? selectPluginsInteractive : undefined,
288
+ selectPlugins: tty ? async (choices) => {
289
+ const selected = await selectPluginsInteractive(choices);
290
+ if (selected.includes(FOLLOW_ALL_PLUGINS)) {
291
+ followExplicit = true;
292
+ return choices.map(choice => choice.name);
293
+ }
294
+ return selected;
295
+ } : undefined,
296
+ get followAllSelected() { return followExplicit; },
226
297
  selectTargets: tty && values.target === undefined ? selectTargetsInteractive : undefined,
227
298
  confirmFull: tty && !narrowed ? confirmFullInstall : undefined,
228
299
  selectComponents: tty && !narrowed ? selectComponentsInteractive : undefined,
@@ -230,18 +301,25 @@ async function handleAdd(rest, cmd) {
230
301
  nonInteractive: !tty,
231
302
  scope: global ? "user" : "project",
232
303
  });
304
+ const { order, installed, removed, converted, agents } = result;
305
+ if (values.json) {
306
+ console.log(JSON.stringify({ schemaVersion: "adg.plugins.add/v1", ...result }));
307
+ return runtimeOutcome(agents);
308
+ }
233
309
  for (const name of converted)
234
310
  console.log(ui.meta(`converted native manifest -> .agents/.plugin.json: ${name}`));
235
311
  for (const name of removed)
236
312
  console.log(`${ui.warn("removed")} ${ui.name(name)}`);
237
- if (order.length > 1)
313
+ if (values.verbose && order.length > 1)
238
314
  console.log(ui.meta(`install order: ${order.join(" -> ")}`));
239
315
  for (const res of installed) {
240
316
  console.log(`${ui.ok("added")} ${ui.name(res.name)} ${ui.meta(`-> ${res.installedTo}`)}`);
241
- console.log(ui.meta(` sourceHash: ${res.sourceHash}`));
242
- console.log(ui.meta(` installedHash: ${res.installedHash}`));
243
- for (const f of res.adapted)
244
- console.log(ui.meta(` adapted: ${f}`));
317
+ if (values.verbose) {
318
+ console.log(ui.meta(` sourceHash: ${res.sourceHash}`));
319
+ console.log(ui.meta(` installedHash: ${res.installedHash}`));
320
+ for (const file of res.adapted)
321
+ console.log(ui.meta(` adapted: ${file}`));
322
+ }
245
323
  }
246
324
  for (const line of renderAgentReport(agents, "enabled"))
247
325
  console.log(line);
@@ -321,12 +399,33 @@ async function handleSync(rest, cmd) {
321
399
  async function runUpdateAcrossScopes(values, opts) {
322
400
  let succeeded = 0;
323
401
  let failed = 0;
402
+ let cancelled = false;
403
+ const scopes = [];
324
404
  for (const sc of await resolveUpdateScopes(values)) {
325
- if (sc.heading)
405
+ if (sc.heading && !values.json)
326
406
  console.log(`${ui.name(sc.heading)}`);
327
- const progress = createProgress();
407
+ const progress = createProgress(values.json ? { stream: { write() { } }, isTTY: false } : {});
408
+ const reportResult = (result, interrupted = false) => {
409
+ scopes.push({ scope: sc.label, result, ...(interrupted ? { cancelled: true } : {}) });
410
+ const quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
411
+ const scopeFlag = typeof values.dir === "string" ? `--dir ${quote(sc.dir)}` : sc.agentScope === "user" ? "--global" : "--project";
412
+ const target = typeof values.target === "string" ? values.target : undefined;
413
+ const retryVerb = target ? "marketplace upgrade" : "update";
414
+ const retryCommand = `adg plugins ${retryVerb}${opts.source ? ` ${quote(opts.source)}` : ""} ${scopeFlag}${values.all ? " --all" : ""}${values.repair ? " --repair" : ""}${target ? ` --target ${quote(target)}` : ""}`;
415
+ const hasCompletedWork = result.remote.length || result.local.results.length || result.local.missing.length || result.agents.length;
416
+ if (!values.json && (!interrupted || hasCompletedWork))
417
+ printUpdateReport(result, values.verbose, retryCommand);
418
+ const counts = updateResultCounts(result);
419
+ if (!values.json && (!interrupted || hasCompletedWork)) {
420
+ const awaitingReview = result.remote.filter(source => source.actionRequired?.length).length;
421
+ const summary = formatUpdateSummary({ succeeded: counts.succeeded, failed: counts.failed - awaitingReview }, progress.elapsedMs());
422
+ console.log(`${summary}${awaitingReview ? ui.warn(` · ${awaitingReview} awaiting review`) : ""}`);
423
+ }
424
+ succeeded += counts.succeeded;
425
+ failed += counts.failed;
426
+ };
328
427
  try {
329
- const result = await updatePlugins({
428
+ const result = await withStoreMutex(sc.dir, () => updatePlugins({
330
429
  pluginsDir: sc.dir,
331
430
  source: opts.source,
332
431
  all: values.all,
@@ -335,23 +434,36 @@ async function runUpdateAcrossScopes(values, opts) {
335
434
  agentScope: sc.agentScope,
336
435
  scope: { label: sc.label, globalDir: globalPluginsDir() },
337
436
  targets: opts.targets,
338
- onProgress: (phase) => progress.update(phase),
339
- });
340
- // Clear the animated line before the report goes to stdout, so the two
341
- // streams don't interleave mid-line.
437
+ review: process.stdin.isTTY && !values.json ? async (review) => {
438
+ progress.stop();
439
+ return reviewUpdate(review);
440
+ } : undefined,
441
+ onProgress: values.json ? undefined : phase => progress.update(phase),
442
+ }));
342
443
  progress.stop();
343
- printUpdateReport(result);
344
- const counts = updateResultCounts(result);
345
- console.log(formatUpdateSummary(counts, progress.elapsedMs()));
346
- succeeded += counts.succeeded;
347
- failed += counts.failed;
444
+ reportResult(result);
348
445
  }
349
- catch (err) {
446
+ catch (error) {
350
447
  progress.stop();
351
- console.error(`${ui.err("error:")} ${err instanceof Error ? err.message : String(err)}`);
448
+ if (error instanceof UpdateCancelled) {
449
+ cancelled = true;
450
+ if (error.partial)
451
+ reportResult(error.partial, true);
452
+ if (!values.json)
453
+ console.error(ui.warn("Update cancelled; completed changes are kept. Remaining updates were not run."));
454
+ break;
455
+ }
456
+ const message = error instanceof Error ? error.message : String(error);
457
+ scopes.push({ scope: sc.label, error: message });
458
+ if (!values.json)
459
+ console.error(`${ui.err("error:")} ${message}`);
352
460
  failed += 1;
353
461
  }
354
462
  }
463
+ if (values.json)
464
+ console.log(JSON.stringify({ schemaVersion: "adg.plugins.update/v1", scopes, summary: { succeeded, failed }, cancelled }));
465
+ if (cancelled)
466
+ return commandOutcome("cancelled");
355
467
  if (failed === 0)
356
468
  return commandOutcome("success");
357
469
  return commandOutcome(succeeded > 0 ? "partial" : "failure", "dependency");
@@ -360,10 +472,22 @@ async function handleUpdate(rest, cmd) {
360
472
  const { values, positionals } = parseVerb("update", cmd.flags, rest);
361
473
  // First paint, before the scope prompt and before any lock read, so the run
362
474
  // never opens on a blank screen. stderr keeps stdout to the report alone.
363
- process.stderr.write(`${ui.title("adg plugins update")}\n`);
475
+ if (!values.json)
476
+ process.stderr.write(`${ui.title("adg plugins update")}\n`);
364
477
  return runUpdateAcrossScopes(values, { source: positionals[0] });
365
478
  }
366
479
  async function runPluginsVerb(verb, rest, cmd) {
480
+ if (verb === "adapt" || verb === "init") {
481
+ const { values, positionals } = parseVerb(verb, cmd.flags, rest);
482
+ let target = verb === "adapt" ? resolve(positionals[0] ?? process.cwd()) : resolve(values.dir ?? "plugins");
483
+ for (;;) {
484
+ assertNoPendingMigration(target);
485
+ const parent = dirname(target);
486
+ if (parent === target)
487
+ break;
488
+ target = parent;
489
+ }
490
+ }
367
491
  if (await handleCorePluginVerb(verb, rest, cmd))
368
492
  return;
369
493
  switch (verb) {
@@ -502,7 +626,7 @@ async function runMarketplace(args) {
502
626
  // and error handling) so the alias can't drift from the verb it aliases.
503
627
  // `--target` narrows the runtimes.
504
628
  console.error(ui.warn("note: `marketplace upgrade` is a deprecated alias for `adg plugins update`."));
505
- const { values, positionals } = parseVerb("marketplace", ["all", "target", ...SCOPE], rest);
629
+ const { values, positionals } = parseVerb("marketplace", ["all", "repair", "target", "verbose", "json", ...SCOPE], rest);
506
630
  const targets = values.target !== undefined ? resolveTargets(values.target) : undefined;
507
631
  return runUpdateAcrossScopes(values, { source: positionals[0], targets });
508
632
  }
@@ -28,7 +28,7 @@ export const FLAGS = {
28
28
  only: { type: "string", hint: "<types>", help: "limit to these component types (skills,agents,commands,mcp,hooks,apps)" },
29
29
  as: { type: "string", hint: "<name>", help: "installed identity for a manifest-free structural source" },
30
30
  prefix: { type: "string", hint: "<p>", help: "prefix imported skill names" },
31
- verbose: { type: "boolean", short: "v", help: "expand each component to its member names" },
31
+ verbose: { type: "boolean", short: "v", help: "show detailed component and update information" },
32
32
  repair: { type: "boolean", help: "repair missing Codex registrations after updating; preserve runtime-disabled plugins" },
33
33
  json: { type: "boolean", help: "print stable machine-readable JSON" },
34
34
  };
@@ -49,8 +49,10 @@ export const PLUGIN_COMMANDS = {
49
49
  positional: "<source> = <local-dir> | <owner/repo[@ref]> | <github-url>",
50
50
  blurb: "In a terminal, add guides you through: scope → plugins → agents → what to install.\n" +
51
51
  "By default it installs everything; choose 'No, let me choose' to pick components,\n" +
52
- "or pass the flags below to skip any prompt (e.g. for scripts/CI).",
53
- flags: ["all", "plugin", "only", "skill", "mcp", "target", "no-deps", "ref", "sparse", "marketplace-name", "as", ...SCOPE],
52
+ "or pass the flags below to skip any prompt (e.g. for scripts/CI).\n" +
53
+ "Choose 'Follow all plugins' or pass --all to subscribe to future additions.\n" +
54
+ "Selecting every plugin manually keeps a selected-plugin subscription.",
55
+ flags: ["all", "plugin", "only", "skill", "mcp", "target", "no-deps", "ref", "sparse", "marketplace-name", "as", "verbose", "json", ...SCOPE],
54
56
  examples: [
55
57
  "adg plugins add owner/repo # guided",
56
58
  "adg plugins add owner/repo --all --global # all plugins, global, non-interactive",
@@ -89,19 +91,22 @@ export const PLUGIN_COMMANDS = {
89
91
  positional: "<source> limit to one source key from `adg plugins marketplace list` (default: all)",
90
92
  blurb: "Re-fetches every remote source and refreshes the plugins installed from it,\n" +
91
93
  "reporting what changed, what's unchanged, what's missing upstream, and what's\n" +
92
- "newly available (install those too with --all). Local-source plugins are\n" +
93
- "rescanned in place. Missing upstream plugins are retained; migrate or remove\n" +
94
- "them explicitly. Updates never uninstall plugins, including with --all.\n" +
94
+ "newly available (--all includes these once). Local-source plugins are\n" +
95
+ "rescanned in place. ADG follows verified skill relocations and existing\n" +
96
+ "marketplace renames. Missing upstream plugins are retained and can be\n" +
97
+ "reviewed in this update. Skill choices and disabled state are preserved\n" +
98
+ "before old owners are retired.\n" +
95
99
  "In a terminal, it asks whether to update project, global,\n" +
96
100
  "or both; pass a scope flag to skip the prompt.\n\n" +
97
- "This is the plugins-domain twin of `adg skills update`.",
98
- flags: ["all", "repair", ...SCOPE],
101
+ "Historical skill restoration is separate from following future plugins.\n" +
102
+ "Use --verbose for details; --json is non-interactive machine output.",
103
+ flags: ["all", "repair", "verbose", "json", ...SCOPE],
99
104
  examples: [
100
105
  "adg plugins update --global --repair # explicitly restore missing Codex registrations",
101
106
  "adg plugins update # guided: project / global / both",
102
107
  "adg plugins update --global # every global source",
103
108
  "adg plugins update owner/repo # just one source",
104
- "adg plugins update owner/repo --all # also install newly-added plugins",
109
+ "adg plugins update owner/repo --all # include current additions once",
105
110
  ],
106
111
  },
107
112
  remove: {
@@ -310,11 +315,13 @@ export function renderVerbHelp(name) {
310
315
  export function wantsHelp(args) {
311
316
  return args.includes("-h") || args.includes("--help");
312
317
  }
313
- /** Print a top-level usage error and exit non-zero. */
318
+ export class CliUsageError extends Error {
319
+ }
320
+ /** Report invalid usage; the dispatcher returns failure after releasing resources. */
314
321
  export function fail(msg) {
315
322
  console.error(`${ui.err("error:")} ${msg}\n`);
316
323
  console.error(TOP_USAGE);
317
- process.exit(1);
324
+ throw new CliUsageError(msg);
318
325
  }
319
326
  export function resolveScopeDir(values) {
320
327
  if (typeof values.dir === "string")
@@ -375,6 +382,6 @@ export function parseVerb(name, flags, rest) {
375
382
  catch (err) {
376
383
  console.error(`${ui.err("error:")} ${err instanceof Error ? err.message : String(err)}\n`);
377
384
  console.error(renderVerbHelp(name));
378
- process.exit(1);
385
+ throw new CliUsageError(err instanceof Error ? err.message : String(err));
379
386
  }
380
387
  }
@@ -0,0 +1,80 @@
1
+ import * as prompts from "@clack/prompts";
2
+ const labels = {
3
+ restore: { label: "Restore all candidates", hint: "explicitly restore every listed candidate; future plugin subscriptions stay unchanged" },
4
+ keep: { label: "Skip historical restoration", hint: "leave these historical skills unrestored and continue the remaining updates" },
5
+ select: { label: "Choose individual skills", hint: "restore only the skills you select" },
6
+ enabled: { label: "Enable the merged plugin", hint: "enable the combined selection in agent runtimes" },
7
+ disabled: { label: "Keep the merged plugin disabled (Recommended)", hint: "preserve it in the store without activating its contents" },
8
+ drop: { label: "Remove this skill permanently", hint: "no replacement is declared; the old skill will be removed" },
9
+ };
10
+ /** Returns undefined on cancellation; authorization is never implied by a prompt. */
11
+ export async function reviewUpdate(review, ui = {
12
+ select: options => prompts.select(options),
13
+ multiselect: options => prompts.multiselect(options),
14
+ confirm: options => prompts.confirm(options),
15
+ isCancel: prompts.isCancel,
16
+ }) {
17
+ const answer = { history: {}, allow: [] };
18
+ for (const item of review.history) {
19
+ const uncertainSelection = item.uncertain || item.choices.includes("restore");
20
+ const ordered = uncertainSelection
21
+ ? ["keep", "select", "restore", "drop"].filter(action => item.choices.includes(action))
22
+ : item.choices.includes("disabled") ? ["disabled", "enabled"] : item.choices;
23
+ const message = item.id.startsWith("state:")
24
+ ? `${review.source}: resolve enabled and disabled selections for ${item.id.slice(6)}`
25
+ : item.id.startsWith("unmapped:")
26
+ ? `${review.source}: no declared replacement for old plugin ${item.skills.join(", ")}`
27
+ : item.id.startsWith("drop:")
28
+ ? `${review.source}: no replacement for ${item.skills.join(", ")}`
29
+ : item.id.startsWith("ownership:") && !uncertainSelection
30
+ ? `${review.source}: choose a current owner for ${item.skills.join(", ")}`
31
+ : `${review.source}: prior selection of these ${item.skills.length} skill candidates is unknown.\n${item.skills.join(", ")}`;
32
+ const selected = await ui.select({
33
+ message,
34
+ options: ordered.map(action => ({
35
+ value: action,
36
+ ...(item.id.startsWith("unmapped:")
37
+ ? action === "keep"
38
+ ? { label: "Keep the old plugin (Recommended)", hint: "preserve its installed contents and runtime state" }
39
+ : { label: "Remove the old plugin", hint: "explicitly retire this plugin without a declared replacement" }
40
+ : uncertainSelection && action === "keep"
41
+ ? { label: "Keep current selection (Recommended)", hint: "defer these candidates and continue the remaining updates" }
42
+ : labels[action]),
43
+ })),
44
+ initialValue: ordered[0],
45
+ });
46
+ if (ui.isCancel(selected))
47
+ return undefined;
48
+ const action = selected;
49
+ if (!item.choices.includes(action))
50
+ throw new Error(`Invalid migration decision: ${item.id}`);
51
+ let skills;
52
+ if (action === "select") {
53
+ const ownerSelection = item.id.startsWith("ownership:");
54
+ const chosen = await (ownerSelection ? ui.select({
55
+ message: "Choose the current plugin that should own this skill",
56
+ options: item.skills.map(address => ({ value: address, label: address })),
57
+ initialValue: item.skills[0],
58
+ }) : ui.multiselect({
59
+ message: "Choose candidates to restore; their prior selection is unknown (space to toggle)",
60
+ options: item.skills.map(skill => ({ value: skill, label: skill })),
61
+ initialValues: [],
62
+ required: false,
63
+ }));
64
+ if (ui.isCancel(chosen))
65
+ return undefined;
66
+ skills = ownerSelection ? [chosen] : chosen;
67
+ if (!Array.isArray(skills) || skills.some(skill => !item.skills.includes(skill)))
68
+ throw new Error("Invalid historical skill selection");
69
+ }
70
+ answer.history[item.id] = { action, ...(skills ? { skills } : {}) };
71
+ }
72
+ for (const executable of review.executable) {
73
+ const allowed = await ui.confirm({ message: `Allow ${executable.label}?`, initialValue: false });
74
+ if (ui.isCancel(allowed))
75
+ return undefined;
76
+ if (allowed === true)
77
+ answer.allow.push(executable.key);
78
+ }
79
+ return answer;
80
+ }
@@ -23,7 +23,7 @@ export async function synthesizeDefaultDslPlugin(opts, parsed, workRoot, resolve
23
23
  });
24
24
  const authorized = opts.authorizedComponents;
25
25
  const unauthorizedRisk = generated.components.some((c) => (c === "hooks" || c === "mcp") && !authorized?.includes(c));
26
- if (opts.nonInteractive && unauthorizedRisk && opts.only === undefined) {
26
+ if (opts.nonInteractive && unauthorizedRisk && opts.only === undefined && !opts.replaySelection) {
27
27
  throw new Error("default source exposes hooks or MCP; pass --only to explicitly authorize selected components");
28
28
  }
29
29
  const staging = mkdtempSync(join(tmpdir(), "adg-default-plugin-"));
@@ -21,6 +21,40 @@ const HASH_IGNORE = PROJECTION_DIRS;
21
21
  export function contentHash(dir, manifest) {
22
22
  return folderHash(dir, HASH_IGNORE, packageFilter(manifest, { includeProjections: false }));
23
23
  }
24
+ /** Verify managed payload and every generated runtime projection using the same materialization rules. */
25
+ export function verifyInstallation(dir, expectedHash, selection, targets) {
26
+ let projectionsIntact = false;
27
+ let installationIntact = false;
28
+ try {
29
+ const installedManifest = readManifest(dir);
30
+ const previousSelection = resolveSelectionDependencies(installedManifest, selection);
31
+ installationIntact = Boolean(expectedHash && folderHash(dir, PROJECTION_DIRS, effectivePackageFilter(installedManifest, previousSelection)) === expectedHash);
32
+ // Generate the complete expected installation, including auxiliary MCP,
33
+ // hooks and runner files that are outside native manifest directories.
34
+ const work = mkdtempSync(join(tmpdir(), "adg-projection-check-"));
35
+ try {
36
+ const expected = join(work, "expected");
37
+ materializePlugin({ source: dir, destination: expected, manifest: installedManifest, selection: previousSelection,
38
+ build: (staging) => { adaptPlugin(staging, targets, previousSelection, dir); } });
39
+ const paths = new Set();
40
+ const collect = (dir, prefix = "") => {
41
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
42
+ const path = prefix ? `${prefix}/${entry.name}` : entry.name;
43
+ paths.add(path);
44
+ if (entry.isDirectory())
45
+ collect(join(dir, entry.name), path);
46
+ }
47
+ };
48
+ collect(expected);
49
+ projectionsIntact = folderHash(expected) === folderHash(dir, [], (path) => paths.has(path));
50
+ }
51
+ finally {
52
+ rmSync(work, { recursive: true, force: true });
53
+ }
54
+ }
55
+ catch { /* Missing or damaged projections must be regenerated. */ }
56
+ return { installationIntact, projectionsIntact };
57
+ }
24
58
  function describe(s) {
25
59
  switch (s.type) {
26
60
  case "local": return `local:${s.path}`;
@@ -56,6 +90,7 @@ export function installPlugin(opts) {
56
90
  // A new selection wins; otherwise keep whatever a prior install recorded so
57
91
  // partial installs survive re-install / `marketplace upgrade`.
58
92
  const desiredSelection = normalizePluginSelection(opts.selection ?? prev?.selection);
93
+ const selectionKnown = opts.selectionKnown ?? true;
59
94
  const selection = resolveSelectionDependencies(manifest, desiredSelection);
60
95
  if (selection) {
61
96
  const contents = pluginContents(source, manifest);
@@ -104,36 +139,7 @@ export function installPlugin(opts) {
104
139
  }
105
140
  catch { /* Missing/invalid comparison evidence requires a conservative update. */ }
106
141
  }
107
- let projectionsIntact = false;
108
- let installationIntact = false;
109
- try {
110
- const installedManifest = readManifest(dest);
111
- const previousSelection = resolveSelectionDependencies(installedManifest, prev?.selection);
112
- installationIntact = Boolean(prev && folderHash(dest, PROJECTION_DIRS, effectivePackageFilter(installedManifest, previousSelection)) === prev.installedHash);
113
- // Generate the complete expected installation, including auxiliary MCP,
114
- // hooks and runner files that are outside native manifest directories.
115
- const work = mkdtempSync(join(tmpdir(), "adg-projection-check-"));
116
- try {
117
- const expected = join(work, "expected");
118
- materializePlugin({ source: dest, destination: expected, manifest: installedManifest, selection: previousSelection,
119
- build: (staging) => { adaptPlugin(staging, targets, previousSelection, dest); } });
120
- const paths = new Set();
121
- const collect = (dir, prefix = "") => {
122
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
123
- const path = prefix ? `${prefix}/${entry.name}` : entry.name;
124
- paths.add(path);
125
- if (entry.isDirectory())
126
- collect(join(dir, entry.name), path);
127
- }
128
- };
129
- collect(expected);
130
- projectionsIntact = folderHash(expected) === folderHash(dest, [], (path) => paths.has(path));
131
- }
132
- finally {
133
- rmSync(work, { recursive: true, force: true });
134
- }
135
- }
136
- catch { /* Missing or damaged projections must be regenerated. */ }
142
+ const { installationIntact, projectionsIntact } = verifyInstallation(dest, prev?.installedHash, prev?.selection, targets);
137
143
  return withPluginSourceCache(source, cacheDir, manifest, (snapshot) => {
138
144
  // Detect-then-update compares the complete source snapshot, never the
139
145
  // selection-pruned runtime installation.
@@ -143,10 +149,11 @@ export function installPlugin(opts) {
143
149
  const installedIntact = existsSync(dest)
144
150
  && folderHash(dest, PROJECTION_DIRS, effectivePackageFilter(manifest, selection)) === prev.installedHash;
145
151
  if (installedIntact) {
146
- if (changes.source || changes.selection) {
152
+ if (changes.source || changes.selection || prev.selectionKnown !== selectionKnown) {
147
153
  // Exact bytes are verified at this revision; this is not an install.
148
154
  lock.plugins[name] = {
149
155
  ...prev,
156
+ selectionKnown,
150
157
  ...(changes.source ? { resolvedRevision: opts.resolvedRevision } : {}),
151
158
  ...(desiredSelection ? { selection: desiredSelection } : {}),
152
159
  };
@@ -184,6 +191,7 @@ export function installPlugin(opts) {
184
191
  version: manifest.version,
185
192
  sourceHash,
186
193
  installedHash,
194
+ selectionKnown,
187
195
  ...(opts.resolvedRevision ? { resolvedRevision: opts.resolvedRevision } : {}),
188
196
  };
189
197
  if (manifest.dependencies?.length) {
@@ -193,6 +201,8 @@ export function installPlugin(opts) {
193
201
  entry.selection = desiredSelection;
194
202
  if (prev?.state)
195
203
  entry.state = prev.state;
204
+ if (prev?.runtimeStates)
205
+ entry.runtimeStates = prev.runtimeStates;
196
206
  if (opts.definition)
197
207
  entry.definition = opts.definition;
198
208
  const previousEntry = prev && Object.fromEntries(Object.entries(prev).filter(([key]) => key !== "installedAt" && key !== "updatedAt"));