@rbbtsn0w/adg 0.11.3 → 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 +92 -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
package/README.md CHANGED
@@ -50,6 +50,8 @@ selected with `--plugin` or `--all`.
50
50
 
51
51
  # Install and quick start
52
52
 
53
+ Requires Node.js `^22.22.2 || ^24.15.0 || >=26`. CI and release tooling use npm 12.2.2.
54
+
53
55
  Install the CLI once, then run `adg` from anywhere:
54
56
 
55
57
  ```bash
@@ -325,16 +327,33 @@ discovery manifest/projection is cleared. `update` may refresh a disabled
325
327
  plugin's payload but never activates it. `list` groups enabled and disabled
326
328
  entries, and `status` distinguishes intentional disablement from runtime drift.
327
329
 
328
- `update` also preserves installed plugins that disappear upstream, including
329
- their last verified payload, enabled/disabled state, and component selections.
330
- It reports them as missing upstream and exits nonzero until they return or you
331
- explicitly migrate/remove them. `update --all` installs newly available plugins
332
- without uninstalling existing ones. For an upstream rename or marketplace
333
- restructure, use `adg plugins add <source>` to select replacements (or `--all`
334
- to select everything), keeping the same scope and source ref. Use
335
- `adg plugins remove <name>` for an explicit uninstall. If an older ADG version
336
- already removed every plugin from a source, re-add the source; `update` discovers
337
- sources from installed lock entries and cannot recover an empty source group.
330
+ `adg plugins update -g` updates the global store and follows relocated skills
331
+ using ADG's installation history and the current source catalog. Existing
332
+ marketplace `renames` entries handle plugin identity changes. If an older update
333
+ lost selection history, the same command can recover a verified historical
334
+ release and offer restoration candidates whose prior selection is unknown.
335
+ The default keeps the current selection; choosing individual candidates starts
336
+ with none selected. Deferred recovery is recorded separately from exclusions,
337
+ so repeated updates stay quiet. Use the same update command with `--repair` to
338
+ reconsider deferred candidates. Publishers use their ordinary
339
+ manifests and marketplace. Existing pins, disabled state and component selections are
340
+ preserved. An interrupted migration resumes on the next update, including when
341
+ the source is offline.
342
+
343
+ ADG reads existing lock formats 3 through 5 and writes format 6 for recovery
344
+ history. Every ADG installation sharing the same store must support format 6;
345
+ older clients cannot read a store after it has been upgraded.
346
+
347
+ `plugins add <source> --all` subscribes to future plugins from that source.
348
+ Selecting plugins individually maintains that selection. `plugins update --all`
349
+ includes available plugins for this run. Explicit removals remain excluded.
350
+ New hook handlers and MCP services require review before activation.
351
+ Partial skill choices survive plugin splits and merges, including whole-source
352
+ subscriptions and one-time `--all` updates. An unattended update defers unknown
353
+ historical choices, reports outstanding permissions and preserves affected
354
+ contents. Use `--verbose` for details or `--json` for a structured report;
355
+ `deferredRecovery` identifies unknown candidates separately from `notRestored`.
356
+ See the [update and recovery behavior](docs/plugin-upgrade-migrations.md).
338
357
 
339
358
  For the local-directory-source flow into Claude's registry/cache, see
340
359
  [docs/local-plugin-registration.md](docs/local-plugin-registration.md).
@@ -442,8 +461,8 @@ private discovery path:
442
461
  # Developing from source
443
462
 
444
463
  For working on the CLI itself, or testing a plugin before release. The CLI runs
445
- directly on **Node ≥ 22.18** via native TypeScript type-stripping — **no build
446
- step**.
464
+ directly on the supported Node.js versions above via native TypeScript
465
+ type-stripping — **no build step**.
447
466
 
448
467
  ```bash
449
468
  git clone <this-repo> && cd adg
@@ -1,6 +1,7 @@
1
- import { existsSync, rmSync } from "node:fs";
1
+ import { cpSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { homedir } from "node:os";
3
- import { join, resolve } from "node:path";
4
+ import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
4
5
  import { ensureDir, writeJson } from "../fsutil.js";
5
6
  import { findManifestFile, readManifest } from "../manifest.js";
6
7
  import { isExposed } from "../components.js";
@@ -27,9 +28,9 @@ export { cleanupAntigravityMcp, pruneStaleAntigravity, reconcileAntigravityActiv
27
28
  * We therefore drive Antigravity purely by placing files, never by a CLI:
28
29
  * - Project scope is *in place*: ADG's store folder already sits in the
29
30
  * workspace scan dir, so we just write the agy `plugin.json` at its root.
30
- * - Global scope (and remote-nested project plugins, which live two levels
31
- * under the scan dir) get an exposure symlink `<scanDir>/<name>` -> the real
32
- * store folder, with a copy fallback where symlinks are unavailable.
31
+ * - Global scope and remote-nested project plugins get a real, ADG-owned
32
+ * directory at `<scanDir>/<name>`. Native agy ignores root symlinks while
33
+ * following component symlinks inside a real root.
33
34
  *
34
35
  * Provenance is owned by ADG: `listInstalled` answers from the queried scope's
35
36
  * own lock intersected with that scope's scan dir — never from the agent — so a
@@ -117,6 +118,7 @@ function componentSegment(value) {
117
118
  * Idempotent; safe to re-run. Never deletes a real (non-symlink) component dir.
118
119
  */
119
120
  export function ensureAntigravityRoot(dir, selection) {
121
+ let complete = true;
120
122
  const manifest = readManifest(dir);
121
123
  const { manifest: pluginJson } = toAntigravityManifest(dir, manifest, selection);
122
124
  writeJson(join(dir, ANTIGRAVITY_MANIFEST), pluginJson);
@@ -135,31 +137,123 @@ export function ensureAntigravityRoot(dir, selection) {
135
137
  ? () => console.error(`antigravity: skipping "${field}" alias for "${dir}" — ${link} already exists and is not ADG-managed. ` +
136
138
  `Remove it to let ADG manage this component.`)
137
139
  : undefined;
138
- reconcile(link, desired, warn);
140
+ const reconciled = reconcile(link, desired, warn);
141
+ if (desired.kind === "linked" && !reconciled)
142
+ complete = false;
139
143
  }
144
+ return complete;
140
145
  }
141
- /**
142
- * Expose `realDir` to Antigravity at `<scanDir>/<name>`. No-op when the real dir
143
- * already *is* that path (project, flat). Returns false without touching disk when
144
- * the target is real content `src/projection-slot.ts`'s `observeSlot` can't prove
145
- * ADG owns (no `.adg-owned` marker) — we never clobber a plugin slot we don't own.
146
- * Replacing our own alias or a prior copy-fallback projection (which carries the
147
- * marker) is fine.
148
- *
149
- * Migration note: a copy-fallback exposure created before this module existed
150
- * carries no marker — ownership was inferred from a root `plugin.json` instead,
151
- * which is also just Antigravity's own plugin format and proves nothing on its
152
- * own — so `adoptLegacyExposure` below requires ADG-specific evidence too
153
- * before it plants the marker; see that function's doc for why a bare
154
- * `plugin.json` isn't enough by itself.
146
+ const PROJECTION_STATE = ".adg-antigravity-projection.json";
147
+ function physicalPluginRoot(path) {
148
+ try {
149
+ const stat = lstatSync(path);
150
+ return stat.isDirectory() && !stat.isSymbolicLink() && existsSync(join(path, ANTIGRAVITY_MANIFEST));
151
+ }
152
+ catch (error) {
153
+ if (error.code === "ENOENT")
154
+ return false;
155
+ throw error;
156
+ }
157
+ }
158
+ function ownedExposure(target, name, store, realDir) {
159
+ const observed = observeSlot(target);
160
+ if (observed.kind === "absent")
161
+ return true;
162
+ const storeRoot = existsSync(store) ? realpathSync(store) : resolve(store);
163
+ if (observed.kind === "owned-dir") {
164
+ const stateFile = join(target, PROJECTION_STATE);
165
+ if (!existsSync(stateFile))
166
+ return true; // Legacy copy-fallback marker has no source receipt.
167
+ try {
168
+ const state = JSON.parse(readFileSync(stateFile, "utf8"));
169
+ if (state.version !== 1 || typeof state.source !== "string")
170
+ return false;
171
+ const rel = relative(storeRoot, resolve(state.source));
172
+ return !!rel && !isAbsolute(rel) && !rel.startsWith("..") && basename(state.source) === name;
173
+ }
174
+ catch {
175
+ return false;
176
+ }
177
+ }
178
+ if (observed.kind !== "symlink")
179
+ return false;
180
+ if (realDir && resolve(observed.target) === resolve(realDir))
181
+ return true;
182
+ const linkTarget = existsSync(observed.target) ? realpathSync(observed.target) : resolve(observed.target);
183
+ const rel = relative(storeRoot, linkTarget);
184
+ return !!rel && !isAbsolute(rel) && !rel.startsWith("..") && basename(observed.target) === name;
185
+ }
186
+ /** Build outside the scan directory, then replace only a proven ADG exposure.
187
+ * Native agy skips symlinked plugin roots, but follows component aliases inside
188
+ * real roots. A copied root also keeps native version/manifest discovery local.
155
189
  */
156
- function exposeAt(scanDir, name, realDir) {
190
+ function exposeAt(scanDir, name, realDir, store, entry) {
157
191
  const target = join(scanDir, name);
158
192
  if (resolve(target) === resolve(realDir))
159
- return true; // project, flat: already in the scan dir
193
+ return true;
160
194
  adoptLegacyExposure(target, name);
161
- return reconcile(target, { kind: "linked", target: resolve(realDir) }, () => console.error(`antigravity: skipping "${name}" — ${target} already exists and is not ADG-managed. ` +
162
- `Remove it to let ADG manage this plugin.`));
195
+ if (!ownedExposure(target, name, store, realDir))
196
+ return false;
197
+ const work = join(dirname(scanDir), ".adg-projection-staging", randomUUID());
198
+ const staged = join(work, "next");
199
+ const backup = join(work, "previous");
200
+ mkdirSync(work, { recursive: true, mode: 0o700 });
201
+ try {
202
+ cpSync(realDir, staged, { recursive: true, dereference: false });
203
+ const manifest = readManifest(staged);
204
+ const selection = resolveSelectionDependencies(manifest, entry.selection);
205
+ writeJson(join(staged, ANTIGRAVITY_MANIFEST), toAntigravityManifest(staged, manifest, entry.selection).manifest);
206
+ writeAntigravityMcpConfig(staged, manifest, selection);
207
+ writeAntigravityHooks(staged, manifest, selection, target);
208
+ markOwned(staged);
209
+ writeJson(join(staged, PROJECTION_STATE), {
210
+ version: 1, source: realpathSync(realDir), installedHash: entry.installedHash, selection: entry.selection,
211
+ });
212
+ // Recheck after preparation so a user-owned folder appearing meanwhile stays intact.
213
+ if (!ownedExposure(target, name, store, realDir))
214
+ return false;
215
+ if (observeSlot(target).kind !== "absent")
216
+ renameSync(target, backup);
217
+ try {
218
+ renameSync(staged, target);
219
+ }
220
+ catch (error) {
221
+ if (observeSlot(target).kind === "absent" && existsSync(backup))
222
+ renameSync(backup, target);
223
+ throw error;
224
+ }
225
+ return physicalPluginRoot(target);
226
+ }
227
+ finally {
228
+ rmSync(work, { recursive: true, force: true });
229
+ }
230
+ }
231
+ /** Read-only detection also runs before an unchanged-source revision fast path. */
232
+ export function antigravityProjectionRepairs(ctx) {
233
+ if (!antigravityAgent.detect())
234
+ return [];
235
+ const lock = readLock(lockPath(ctx.pluginsDir));
236
+ const requested = ctx.plugins.length ? new Set(ctx.plugins) : undefined;
237
+ const scan = antigravityScanDir(ctx);
238
+ return Object.entries(lock.plugins).filter(([name, entry]) => {
239
+ if ((requested && !requested.has(name)) || entry.state === "disabled")
240
+ return false;
241
+ const realDir = installedPluginDir(ctx.pluginsDir, name, entry.origin);
242
+ const target = join(scan, name);
243
+ if (!physicalPluginRoot(target))
244
+ return true;
245
+ if (resolve(target) === resolve(realDir))
246
+ return false;
247
+ try {
248
+ if (observeSlot(target).kind !== "owned-dir")
249
+ return true;
250
+ const state = JSON.parse(readFileSync(join(target, PROJECTION_STATE), "utf8"));
251
+ return state.version !== 1 || state.source !== realpathSync(realDir) || state.installedHash !== entry.installedHash;
252
+ }
253
+ catch {
254
+ return true;
255
+ }
256
+ }).map(([name]) => name);
163
257
  }
164
258
  /**
165
259
  * Adopt a copy-fallback exposure created before the projection-slot module
@@ -236,9 +330,31 @@ function pluginRealDir(pluginsDir, name) {
236
330
  const dir = installedPluginDir(pluginsDir, name, entry.origin);
237
331
  if (!existsSync(dir))
238
332
  return undefined;
239
- return { dir, selection: resolveSelectionDependencies(readManifest(dir), entry.selection) };
333
+ return { dir, selection: resolveSelectionDependencies(readManifest(dir), entry.selection), entry };
334
+ }
335
+ /** Compatibility writes are best-effort; native state must still confirm them. */
336
+ function verifyRuntimeState(name, enabled) {
337
+ const home = geminiHome(process.env);
338
+ const configPath = join(home, "config", "config.json");
339
+ if (existsSync(configPath)) {
340
+ const parsed = JSON.parse(readFileSync(configPath, "utf8"));
341
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
342
+ throw new Error("Antigravity configuration cannot be verified");
343
+ const plugins = parsed.plugins;
344
+ if (plugins && (plugins[name]?.enabled ?? false) !== enabled)
345
+ throw new Error("Antigravity enablement write was not confirmed");
346
+ }
347
+ if (!enabled) {
348
+ for (const marker of ANTIGRAVITY_MARKERS) {
349
+ const schemas = join(home, marker, "mcp");
350
+ if (existsSync(schemas) && readdirSync(schemas).some((entry) => entry.startsWith(`${name}_`))) {
351
+ throw new Error("Antigravity runtime tool cleanup was not confirmed");
352
+ }
353
+ }
354
+ }
240
355
  }
241
356
  export const antigravityAgent = {
357
+ retrySafeOperations: ["activate", "refresh", "deactivate"],
242
358
  id: ID,
243
359
  displayName: "Antigravity",
244
360
  adaptTarget: "antigravity",
@@ -246,29 +362,36 @@ export const antigravityAgent = {
246
362
  // home is the signal that Antigravity is installed and its scan dirs are real.
247
363
  detect: (env = process.env) => antigravityPresent(env),
248
364
  available: () => antigravityPresent(process.env),
365
+ needsProjectionRefresh: antigravityProjectionRepairs,
249
366
  activate(ctx) {
250
367
  if (!antigravityAgent.detect())
251
368
  return skippedResult(ID);
252
369
  const scanDir = antigravityScanDir(ctx);
253
370
  ensureDir(scanDir);
254
371
  const affected = [];
372
+ const failures = [];
255
373
  for (const p of ctx.plugins) {
256
374
  // Isolate each plugin: a malformed manifest or fs error must not abort the rest.
257
375
  try {
258
376
  const real = pluginRealDir(ctx.pluginsDir, p);
259
377
  if (!real)
260
- continue;
261
- ensureAntigravityRoot(real.dir, real.selection);
262
- if (exposeAt(scanDir, p, real.dir)) {
378
+ throw new Error("Plugin payload is missing from the store");
379
+ if (!ensureAntigravityRoot(real.dir, real.selection))
380
+ throw new Error("A component alias is occupied by foreign content");
381
+ if (exposeAt(scanDir, p, real.dir, ctx.pluginsDir, real.entry)) {
263
382
  reconcileAntigravityActivation(p);
383
+ verifyRuntimeState(p, true);
264
384
  affected.push(p);
265
385
  }
386
+ else
387
+ throw new Error("Plugin exposure is occupied by foreign content");
266
388
  }
267
389
  catch (err) {
390
+ failures.push({ plugin: p, stage: "install", errorType: "projection_failure", message: err instanceof Error ? err.message : String(err) });
268
391
  console.error(`failed to enable "${p}" in Antigravity:`, err);
269
392
  }
270
393
  }
271
- return { agent: ID, affected, skipped: false };
394
+ return { agent: ID, affected, skipped: false, ...(failures.length ? { failures } : {}) };
272
395
  },
273
396
  deactivate(ctx) {
274
397
  if (!antigravityAgent.detect())
@@ -276,36 +399,86 @@ export const antigravityAgent = {
276
399
  const scanDir = antigravityScanDir(ctx);
277
400
  const lock = readLock(lockPath(ctx.pluginsDir)).plugins;
278
401
  const affected = [];
402
+ const failures = [];
279
403
  for (const p of ctx.plugins) {
280
- const entry = lock[p];
281
- const realDir = entry ? installedPluginDir(ctx.pluginsDir, p, entry.origin) : undefined;
282
- const target = join(scanDir, p);
283
- adoptLegacyExposure(target, p);
284
- if ((!realDir || resolve(target) !== resolve(realDir)) && observeSlot(target).kind === "foreign") {
285
- continue;
404
+ try {
405
+ const entry = lock[p];
406
+ const realDir = entry ? installedPluginDir(ctx.pluginsDir, p, entry.origin) : undefined;
407
+ const target = join(scanDir, p);
408
+ adoptLegacyExposure(target, p);
409
+ if ((!realDir || resolve(target) !== resolve(realDir)) && !ownedExposure(target, p, ctx.pluginsDir, realDir)) {
410
+ throw new Error("Plugin exposure is occupied by foreign content");
411
+ }
412
+ reconcileAntigravityDeactivation(p, scanDir, realDir);
413
+ removeProjection(scanDir, p, realDir);
414
+ verifyRuntimeState(p, false);
415
+ if (existsSync(join(target, ANTIGRAVITY_MANIFEST)))
416
+ throw new Error("Plugin projection is still visible after removal");
417
+ affected.push(p);
418
+ }
419
+ catch (error) {
420
+ failures.push({ plugin: p, stage: "remove", errorType: "projection_failure", message: error instanceof Error ? error.message : String(error) });
286
421
  }
287
- reconcileAntigravityDeactivation(p, scanDir, realDir);
288
- removeProjection(scanDir, p, realDir);
289
- affected.push(p);
290
422
  }
291
- return { agent: ID, affected, skipped: false };
423
+ return { agent: ID, affected, skipped: false, ...(failures.length ? { failures } : {}) };
292
424
  },
293
425
  // Re-running activate is the refresh: it rewrites the manifest and re-exposes
294
426
  // the store dir, so a changed plugin replaces its stale projection in place.
295
427
  refresh(ctx) {
296
- return antigravityAgent.activate(ctx);
428
+ const config = join(geminiHome(process.env), "config", "config.json");
429
+ let preservedDisabled = [];
430
+ try {
431
+ if (!ctx.forceEnable && existsSync(config)) {
432
+ const parsed = JSON.parse(readFileSync(config, "utf8"));
433
+ preservedDisabled = ctx.plugins.filter((name) => parsed?.plugins?.[name]?.enabled === false);
434
+ }
435
+ }
436
+ catch { /* Activation returns an explicit verification failure for malformed configuration. */ }
437
+ const active = ctx.plugins.filter((name) => !preservedDisabled.includes(name));
438
+ const result = active.length ? antigravityAgent.activate({ ...ctx, plugins: active })
439
+ : { agent: ID, affected: [], skipped: !antigravityAgent.detect() };
440
+ return { ...result, ...(preservedDisabled.length ? { preservedDisabled } : {}) };
441
+ },
442
+ inspectPlugins(ctx) {
443
+ if (!antigravityAgent.detect())
444
+ return undefined;
445
+ try {
446
+ const config = join(geminiHome(process.env), "config", "config.json");
447
+ let enabled;
448
+ if (existsSync(config)) {
449
+ const parsed = JSON.parse(readFileSync(config, "utf8"));
450
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
451
+ return { error: "Antigravity enablement cannot be inspected" };
452
+ enabled = parsed.plugins;
453
+ }
454
+ const scan = antigravityScanDir(ctx);
455
+ return ctx.plugins.map((name) => {
456
+ const dir = join(scan, name);
457
+ const entry = readLock(lockPath(ctx.pluginsDir)).plugins[name];
458
+ const real = entry ? installedPluginDir(ctx.pluginsDir, name, entry.origin) : undefined;
459
+ const installed = physicalPluginRoot(dir) && !!real && (resolve(dir) === resolve(real) || ownedExposure(dir, name, ctx.pluginsDir, real));
460
+ return { id: name, name, installed, enabled: installed && (enabled?.[name]?.enabled ?? true),
461
+ ...(installed ? { version: readManifest(dir).version } : {}) };
462
+ });
463
+ }
464
+ catch (error) {
465
+ return { error: error instanceof Error ? error.message : String(error) };
466
+ }
297
467
  },
298
- // Provenance is ADG's, not the agent's: enumerate the queried scope's own lock
299
- // and keep only plugins Antigravity actually sees in that scope's scan dir (a
300
- // root `plugin.json`, reached directly or via the exposure link). A project
468
+ // Native discovery ignores symlinked plugin roots. Scope provenance requires
469
+ // both a real root and a projection belonging to the queried ADG store. A project
301
470
  // query therefore can't surface globally-installed plugins. `undefined` only
302
471
  // when Antigravity isn't present at all ("unknown"), never confused with empty.
303
472
  listInstalled(ctx) {
304
473
  if (!antigravityAgent.detect())
305
474
  return undefined;
306
475
  const scanDir = antigravityScanDir(ctx);
307
- const names = Object.keys(readLock(lockPath(ctx.pluginsDir)).plugins);
308
- return names.filter((name) => existsSync(join(scanDir, name, ANTIGRAVITY_MANIFEST)));
476
+ const entries = readLock(lockPath(ctx.pluginsDir)).plugins;
477
+ return Object.keys(entries).filter((name) => {
478
+ const target = join(scanDir, name);
479
+ const real = installedPluginDir(ctx.pluginsDir, name, entries[name].origin);
480
+ return physicalPluginRoot(target) && (resolve(target) === resolve(real) || ownedExposure(target, name, ctx.pluginsDir, real));
481
+ });
309
482
  },
310
483
  pruneStale() {
311
484
  if (!antigravityAgent.available()) {
@@ -102,13 +102,15 @@ export function syncMarketplace(pluginsDir, name, runner = run, warn = console.w
102
102
  // example, merge-conflict-style failures on older CLI builds). When that
103
103
  // happens, fall back to re-adding the marketplace so the refresh remains
104
104
  // best-effort instead of surfacing a hard EXIT_CODE_1 in the ADG timeline.
105
- if (runner(["plugin", "marketplace", "update", name]).ok)
106
- return;
105
+ const updated = runner(["plugin", "marketplace", "update", name]);
106
+ if (updated.ok)
107
+ return updated;
107
108
  }
108
109
  const added = runner(["plugin", "marketplace", "add", pluginsDir]);
109
110
  if (!added.ok) {
110
111
  warn(`failed to sync Claude marketplace (${name}): ${added.out.trim() || "claude plugin marketplace add failed without an error message"}`);
111
112
  }
113
+ return added;
112
114
  }
113
115
  /**
114
116
  * Parse `claude plugin marketplace list --json` into every directory-backed
@@ -161,49 +163,82 @@ export function pruneStaleClaudeMarketplaces(runner = run, exists = existsSync)
161
163
  }
162
164
  return { agent: "claude", skipped: false, removed, errors };
163
165
  }
166
+ /** Run every requested plugin independently and return actionable native failures. */
167
+ export function runClaudeLifecycle(ctx, operation, runner = run, isAvailable = available) {
168
+ if (!isAvailable())
169
+ return skippedResult("claude");
170
+ const result = { agent: "claude", affected: [], skipped: false, failures: [] };
171
+ const marketplace = claudeMarketplaceName(ctx.pluginsDir);
172
+ if (operation !== "deactivate") {
173
+ writeClaudeCatalog(ctx.pluginsDir);
174
+ const synced = syncMarketplace(ctx.pluginsDir, marketplace, runner);
175
+ if (!synced.ok) {
176
+ result.failures.push({ stage: "marketplace", errorType: "native_failure", message: synced.out.trim() || "Claude marketplace synchronization failed" });
177
+ return result;
178
+ }
179
+ }
180
+ let inspection;
181
+ if (operation === "refresh") {
182
+ const listed = runner(["plugin", "list", "--json"]);
183
+ inspection = listed.ok ? parseClaudePluginRecords(listed.stdout ?? listed.out, marketplace, ctx.scope) : undefined;
184
+ if (!inspection) {
185
+ result.failures.push({ stage: "inspect", errorType: "native_failure", message: listed.out.trim() || "Claude state could not be inspected before refresh" });
186
+ return result;
187
+ }
188
+ }
189
+ for (const plugin of ctx.plugins) {
190
+ const native = inspection?.find((p) => p.name === plugin);
191
+ if (operation === "refresh" && native && !native.enabled && !ctx.forceEnable) {
192
+ (result.preservedDisabled ??= []).push(plugin);
193
+ continue;
194
+ }
195
+ if (operation === "deactivate" || (operation === "refresh" && native)) {
196
+ const removed = runner(["plugin", "uninstall", `${plugin}@${marketplace}`, "--scope", ctx.scope, ...(operation === "refresh" || ctx.preserveData ? ["--keep-data"] : [])]);
197
+ const listed = !removed.ok ? runner(["plugin", "list", "--json"]) : undefined;
198
+ const observed = listed?.ok ? parseClaudePluginRecords(listed.stdout ?? listed.out, marketplace, ctx.scope) : undefined;
199
+ if (!removed.ok && !(observed && !observed.some((p) => p.name === plugin))) {
200
+ result.failures.push({ plugin, stage: "remove", errorType: "native_failure", message: removed.out.trim() || "Claude uninstall failed" });
201
+ continue;
202
+ }
203
+ }
204
+ if (operation !== "deactivate") {
205
+ const installed = runner(["plugin", "install", `${plugin}@${marketplace}`, "--scope", ctx.scope]);
206
+ if (!installed.ok) {
207
+ result.failures.push({ plugin, stage: "install", errorType: "native_failure", message: installed.out.trim() || "Claude install failed" });
208
+ continue;
209
+ }
210
+ if (ctx.forceEnable) {
211
+ const enabled = runner(["plugin", "enable", `${plugin}@${marketplace}`, "--scope", ctx.scope]);
212
+ if (!enabled.ok) {
213
+ result.failures.push({ plugin, stage: "install", errorType: "native_failure", message: enabled.out.trim() || "Claude enable failed" });
214
+ continue;
215
+ }
216
+ }
217
+ }
218
+ result.affected.push(plugin);
219
+ }
220
+ if (!result.failures.length)
221
+ delete result.failures;
222
+ return result;
223
+ }
164
224
  export const claudeAgent = {
225
+ retrySafeOperations: ["refresh", "deactivate"],
165
226
  id: "claude",
166
227
  displayName: "Claude Code",
167
228
  adaptTarget: "claude",
168
229
  detect: (env = process.env) => existsSync(claudeHome(env)),
169
230
  available,
170
- activate(ctx) {
171
- if (!available())
172
- return skippedResult("claude");
173
- const { name: marketplace } = writeClaudeCatalog(ctx.pluginsDir);
174
- syncMarketplace(ctx.pluginsDir, marketplace);
175
- const affected = [];
176
- for (const p of ctx.plugins) {
177
- const r = run(["plugin", "install", `${p}@${marketplace}`, "--scope", ctx.scope]);
178
- if (r.ok)
179
- affected.push(p);
180
- // Surface the CLI's reason instead of silently dropping the plugin — a
181
- // rejected manifest (e.g. `hooks: Invalid input`) otherwise looks like a
182
- // no-op "missing" with no diagnostic.
183
- else
184
- console.error(`claude: failed to install ${p}@${marketplace}: ${r.out.trim()}`);
185
- }
186
- return { agent: "claude", affected, skipped: false };
187
- },
188
- deactivate(ctx) {
189
- if (!available())
190
- return skippedResult("claude");
191
- const affected = [];
192
- for (const p of ctx.plugins) {
193
- if (run(["plugin", "uninstall", p, "--scope", ctx.scope]).ok)
194
- affected.push(p);
195
- }
196
- return { agent: "claude", affected, skipped: false };
197
- },
198
- refresh(ctx) {
231
+ activate: (ctx) => runClaudeLifecycle(ctx, "activate"),
232
+ deactivate: (ctx) => runClaudeLifecycle(ctx, "deactivate"),
233
+ refresh: (ctx) => runClaudeLifecycle(ctx, "refresh"),
234
+ inspectPlugins(ctx) {
199
235
  if (!available())
200
- return skippedResult("claude");
201
- // Claude caches a copy on install and won't re-pull from a local marketplace,
202
- // so uninstall (keeping data) then re-install to force a fresh copy.
203
- for (const p of ctx.plugins)
204
- run(["plugin", "uninstall", p, "--scope", ctx.scope, "--keep-data"]);
205
- const act = claudeAgent.activate(ctx);
206
- return { agent: "claude", affected: act.affected, skipped: act.skipped };
236
+ return undefined;
237
+ const result = run(["plugin", "list", "--json"]);
238
+ if (!result.ok)
239
+ return { error: result.out.trim() || "Claude plugin inspection failed" };
240
+ const records = parseClaudePluginRecords(result.stdout ?? result.out, claudeMarketplaceName(ctx.pluginsDir), ctx.scope);
241
+ return records ?? { error: UNRECOGNIZED_PLUGIN_LIST };
207
242
  },
208
243
  // Query Claude's live plugin state for `adg plugins status`, scoped to the
209
244
  // ADG marketplace and the requested install scope. `available()` gates the
@@ -233,6 +268,31 @@ export function claudeListFailure(out) {
233
268
  const detail = out.trim() || "claude plugin list failed without an error message";
234
269
  return { error: `${UNRECOGNIZED_PLUGIN_LIST}: ${detail}` };
235
270
  }
271
+ /** Preserve disabled registrations and versions for transaction verification. */
272
+ export function parseClaudePluginRecords(out, marketplace, scope) {
273
+ try {
274
+ const parsed = JSON.parse(out);
275
+ if (!Array.isArray(parsed))
276
+ return undefined;
277
+ const records = [];
278
+ for (const value of parsed) {
279
+ if (!value || typeof value !== "object")
280
+ return undefined;
281
+ const record = value;
282
+ if (typeof record.id !== "string" || typeof record.scope !== "string" || typeof record.enabled !== "boolean")
283
+ return undefined;
284
+ const identity = record.id.match(/^(\S+?)@([\w.-]+)$/);
285
+ if (!identity || identity[2] !== marketplace || record.scope.toLowerCase() !== scope)
286
+ continue;
287
+ records.push({ id: record.id, name: identity[1], installed: true, enabled: record.enabled,
288
+ ...(typeof record.version === "string" ? { version: record.version } : {}) });
289
+ }
290
+ return records;
291
+ }
292
+ catch {
293
+ return undefined;
294
+ }
295
+ }
236
296
  /** Parse `claude plugin list --json` into enabled plugin names for a marketplace + scope. */
237
297
  export function parseClaudePluginListJson(out, marketplace, scope) {
238
298
  try {
@@ -240,6 +240,7 @@ export function pruneStaleCodexMarketplaces(runner = run, env = process.env, exi
240
240
  return { agent: "codex", skipped: false, removed, errors };
241
241
  }
242
242
  export const codexAgent = {
243
+ retrySafeOperations: ["activate", "refresh", "deactivate"],
243
244
  id: "codex",
244
245
  displayName: "Codex",
245
246
  adaptTarget: "codex",
@@ -9,7 +9,7 @@ import { validatePlugin } from "../commands/validate.js";
9
9
  import { ui } from "../render/ui.js";
10
10
  import { pluginsListJson, pluginsPruneJson, pluginsStatusJson, printJson } from "../render/json.js";
11
11
  import { renderPluginList, renderPrune, renderStatus } from "../render/plugins.js";
12
- import { fail, parseVerb, resolveScopeDir, resolveTargets, scopeOf, } from "./index.js";
12
+ import { fail, CliUsageError, parseVerb, resolveScopeDir, resolveTargets, scopeOf, } from "./index.js";
13
13
  const CORE_PLUGIN_VERBS = new Set(["init", "adapt", "validate", "inspect", "list", "status", "prune"]);
14
14
  export async function handleCorePluginVerb(verb, rest, cmd) {
15
15
  if (!CORE_PLUGIN_VERBS.has(verb))
@@ -57,7 +57,7 @@ export async function handleCorePluginVerb(verb, rest, cmd) {
57
57
  console.error(`${ui.err("invalid:")} ${ui.name(pluginDir)}`);
58
58
  for (const issue of result.issues)
59
59
  console.error(ui.warn(` - ${issue}`));
60
- process.exit(1);
60
+ throw new CliUsageError("Plugin validation failed");
61
61
  }
62
62
  return true;
63
63
  }
@@ -109,7 +109,7 @@ export async function handleCorePluginVerb(verb, rest, cmd) {
109
109
  // drift" outcome `status` reports at exit 0. See docs/cli-json.md's
110
110
  // exit-code contract for `adg plugins prune --json`.
111
111
  if (pruneHasErrors(results))
112
- process.exit(1);
112
+ throw new CliUsageError("Native registry cleanup is incomplete");
113
113
  return true;
114
114
  }
115
115
  }