@rbbtsn0w/adg 0.5.0 → 0.6.0-beta.10

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 (42) hide show
  1. package/README.md +67 -2
  2. package/dist/bin/adg.js +0 -1
  3. package/dist/src/adapters/codex.js +12 -0
  4. package/dist/src/adapters/reverse.js +22 -1
  5. package/dist/src/agents/claude.js +52 -6
  6. package/dist/src/agents/codex.js +94 -14
  7. package/dist/src/cli/handlers.js +164 -141
  8. package/dist/src/cli/index.js +14 -4
  9. package/dist/src/codex-marketplace-migration.js +139 -0
  10. package/dist/src/commands/cache.js +92 -15
  11. package/dist/src/commands/inspect.js +41 -0
  12. package/dist/src/commands/install.js +140 -73
  13. package/dist/src/commands/link.js +4 -16
  14. package/dist/src/commands/marketplace.js +74 -20
  15. package/dist/src/commands/migrate.js +15 -3
  16. package/dist/src/commands/projection.js +15 -0
  17. package/dist/src/commands/select-components.js +12 -0
  18. package/dist/src/commands/state.js +4 -2
  19. package/dist/src/commands/sync.js +9 -15
  20. package/dist/src/commands/update.js +51 -10
  21. package/dist/src/commands/validate.js +9 -2
  22. package/dist/src/components.js +3 -0
  23. package/dist/src/default-dsl.js +142 -0
  24. package/dist/src/lock.js +25 -7
  25. package/dist/src/manifest.js +29 -1
  26. package/dist/src/materialize.js +5 -1
  27. package/dist/src/mcp.js +59 -0
  28. package/dist/src/paths.js +31 -4
  29. package/dist/src/render/plugins.js +7 -1
  30. package/dist/src/source-cache.js +140 -0
  31. package/dist/src/sources.js +76 -5
  32. package/dist/src/telemetry.js +28 -21
  33. package/dist/src/types.js +5 -1
  34. package/dist/vendor/skills/src/cli.js +6 -1
  35. package/dist/vendor/skills/src/update.js +29 -4
  36. package/docs/agents-spec.md +27 -4
  37. package/docs/authoring.md +19 -2
  38. package/package.json +8 -2
  39. package/schemas/adg-plugin.schema.json +1 -0
  40. package/schemas/plugin-lock.schema.json +23 -1
  41. package/vendor/skills/src/cli.ts +6 -1
  42. package/vendor/skills/src/update.ts +32 -4
@@ -1,7 +1,8 @@
1
1
  import { existsSync, readdirSync, rmSync, statSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { join, resolve } from "node:path";
3
3
  import { readLock } from "../lock.js";
4
- import { lockPath, pluginCacheRoot } from "../paths.js";
4
+ import { legacyPluginCacheRoot, legacyPluginSourceCacheDir, lockPath, pluginCacheRoot, pluginSourceCacheDir } from "../paths.js";
5
+ import { resolvePluginSourceSnapshot } from "../source-cache.js";
5
6
  export function directoryBytes(dir) {
6
7
  let total = 0;
7
8
  try {
@@ -24,31 +25,107 @@ export function directoryBytes(dir) {
24
25
  }
25
26
  return total;
26
27
  }
28
+ function cacheDirectories(root) {
29
+ try {
30
+ if (!existsSync(root))
31
+ return [];
32
+ return readdirSync(root, { withFileTypes: true })
33
+ .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
34
+ .map((entry) => entry.name);
35
+ }
36
+ catch {
37
+ return [];
38
+ }
39
+ }
40
+ function removeRootIfEmpty(root) {
41
+ try {
42
+ if (existsSync(root) && readdirSync(root).length === 0)
43
+ rmSync(root, { recursive: true, force: true });
44
+ }
45
+ catch {
46
+ // A concurrent cache mutation or unreadable directory must not make prune fail.
47
+ }
48
+ }
27
49
  export function pluginCacheStatus(pluginsDir) {
28
50
  const root = pluginCacheRoot(pluginsDir);
29
- const installed = new Set(Object.keys(readLock(lockPath(pluginsDir)).plugins));
30
- const entries = existsSync(root)
31
- ? readdirSync(root, { withFileTypes: true })
32
- .filter((entry) => entry.isDirectory() && !entry.name.startsWith("."))
33
- .map((entry) => {
34
- const path = join(root, entry.name);
35
- return { name: entry.name, path, bytes: directoryBytes(path), orphan: !installed.has(entry.name) };
36
- })
37
- .sort((a, b) => a.name.localeCompare(b.name))
38
- : [];
51
+ const lock = readLock(lockPath(pluginsDir));
52
+ const installed = new Set(Object.keys(lock.plugins));
53
+ let entries = [];
54
+ try {
55
+ if (existsSync(root)) {
56
+ entries = cacheDirectories(root)
57
+ .map((name) => {
58
+ const path = join(root, name);
59
+ return { name, path, bytes: directoryBytes(path), orphan: !installed.has(name), recovery: "present" };
60
+ })
61
+ .sort((a, b) => a.name.localeCompare(b.name));
62
+ }
63
+ }
64
+ catch {
65
+ // Treat an unreadable or concurrently removed directory as empty.
66
+ }
67
+ for (const [name, entry] of Object.entries(lock.plugins)) {
68
+ if (entries.some((item) => item.name === name))
69
+ continue;
70
+ const legacy = legacyPluginSourceCacheDir(pluginsDir, name);
71
+ const localRecoverable = entry.origin.type === "local" && existsSync(resolve(pluginsDir, entry.origin.path));
72
+ const remoteRecoverable = (entry.origin.type === "github" || entry.origin.type === "git") && Boolean(entry.resolvedRevision);
73
+ const hasLegacy = existsSync(legacy);
74
+ entries.push({
75
+ name,
76
+ path: hasLegacy ? legacy : pluginSourceCacheDir(pluginsDir, name),
77
+ bytes: hasLegacy ? directoryBytes(legacy) : 0,
78
+ orphan: false,
79
+ recovery: hasLegacy ? "legacy" : (localRecoverable || remoteRecoverable ? "missing-recoverable" : "missing-unrecoverable"),
80
+ });
81
+ }
82
+ const seen = new Set(entries.map((entry) => entry.name));
83
+ for (const name of cacheDirectories(legacyPluginCacheRoot(pluginsDir))) {
84
+ if (seen.has(name))
85
+ continue;
86
+ if (installed.has(name))
87
+ continue;
88
+ const path = legacyPluginSourceCacheDir(pluginsDir, name);
89
+ entries.push({ name, path, bytes: directoryBytes(path), orphan: true, recovery: "legacy" });
90
+ }
91
+ entries.sort((a, b) => a.name.localeCompare(b.name));
39
92
  return { root, entries, totalBytes: entries.reduce((sum, entry) => sum + entry.bytes, 0) };
40
93
  }
94
+ /** Restore the selected snapshots with lock-hash verification. */
95
+ export function restorePluginCache(pluginsDir, names) {
96
+ const lock = readLock(lockPath(pluginsDir));
97
+ const selected = names?.length ? [...new Set(names)] : Object.keys(lock.plugins);
98
+ const missing = selected.filter((name) => !lock.plugins[name]);
99
+ if (missing.length > 0)
100
+ throw new Error(`not installed: ${missing.join(", ")}. See \`adg plugins list\`.`);
101
+ const restored = [];
102
+ for (const name of selected) {
103
+ const cache = pluginSourceCacheDir(pluginsDir, name);
104
+ const wasPresent = existsSync(cache);
105
+ resolvePluginSourceSnapshot(pluginsDir, name, lock.plugins[name]);
106
+ if (!wasPresent)
107
+ restored.push(name);
108
+ }
109
+ return restored;
110
+ }
41
111
  /** Delete cache snapshots that have no corresponding lock entry. */
42
112
  export function prunePluginCache(pluginsDir) {
43
113
  const status = pluginCacheStatus(pluginsDir);
44
114
  const removed = status.entries.filter((entry) => entry.orphan);
45
115
  for (const entry of removed)
46
116
  rmSync(entry.path, { recursive: true, force: true });
47
- if (existsSync(status.root) && readdirSync(status.root).length === 0)
48
- rmSync(status.root, { recursive: true, force: true });
49
- return removed.map((entry) => entry.name);
117
+ const installed = new Set(Object.keys(readLock(lockPath(pluginsDir)).plugins));
118
+ const legacyRoot = legacyPluginCacheRoot(pluginsDir);
119
+ for (const name of cacheDirectories(legacyRoot)) {
120
+ if (!installed.has(name))
121
+ rmSync(legacyPluginSourceCacheDir(pluginsDir, name), { recursive: true, force: true });
122
+ }
123
+ removeRootIfEmpty(status.root);
124
+ removeRootIfEmpty(legacyRoot);
125
+ return [...new Set(removed.map((entry) => entry.name))];
50
126
  }
51
127
  /** Delete every rebuildable source snapshot for this store. */
52
128
  export function cleanPluginCache(pluginsDir) {
53
129
  rmSync(pluginCacheRoot(pluginsDir), { recursive: true, force: true });
130
+ rmSync(legacyPluginCacheRoot(pluginsDir), { recursive: true, force: true });
54
131
  }
@@ -0,0 +1,41 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { basename, join, resolve } from "node:path";
4
+ import { findManifestFile, readManifest } from "../manifest.js";
5
+ import { resolveDefaultDsl } from "../default-dsl.js";
6
+ import { pluginContents } from "../components.js";
7
+ import { cloneGitHub, githubRepositoryDescription, parseSource } from "../sources.js";
8
+ /** Read-only definition resolution for a local plugin root. */
9
+ export function inspectPlugin(root, metadata) {
10
+ const dir = resolve(root);
11
+ const file = findManifestFile(dir);
12
+ const manifest = file
13
+ ? readManifest(dir)
14
+ : resolveDefaultDsl(dir, metadata ?? { name: basename(dir), description: basename(dir) }).manifest;
15
+ const contents = pluginContents(dir, manifest);
16
+ return { kind: file ? "manifest" : "default-dsl", root: dir, manifest, components: Object.entries(contents).filter(([, v]) => v.length > 0).map(([k]) => k) };
17
+ }
18
+ /** Resolve a local or GitHub source without creating a store, lock, or projection. */
19
+ export async function inspectSource(opts) {
20
+ const parsed = parseSource(opts.spec);
21
+ if (parsed.kind === "local") {
22
+ return inspectPlugin(parsed.dir);
23
+ }
24
+ if (parsed.path)
25
+ throw new Error("GitHub subdirectory sources are not supported; define a marketplace and select with --plugin or --all");
26
+ const staging = mkdtempSync(join(tmpdir(), "adg-inspect-"));
27
+ try {
28
+ cloneGitHub({ ...parsed, ref: opts.ref ?? parsed.ref }, staging, { runner: opts.gitRunner });
29
+ const manifestFile = findManifestFile(staging);
30
+ const description = manifestFile
31
+ ? undefined
32
+ : await (opts.descriptionResolver ?? githubRepositoryDescription)(parsed.source);
33
+ const result = inspectPlugin(staging, manifestFile
34
+ ? undefined
35
+ : { name: parsed.source, description: description ?? parsed.source });
36
+ return { ...result, root: "." };
37
+ }
38
+ finally {
39
+ rmSync(staging, { recursive: true, force: true });
40
+ }
41
+ }
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
1
+ import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { basename, join, relative, resolve } from "node:path";
4
4
  import { isDeepStrictEqual } from "node:util";
@@ -6,20 +6,22 @@ import { ADAPTER_TARGETS } from "../adapters/index.js";
6
6
  import { fromNativeManifest } from "../adapters/reverse.js";
7
7
  import { adaptPlugin } from "./adapt.js";
8
8
  import { removePlugin } from "./remove.js";
9
- import { toPosix, writeJson } from "../fsutil.js";
9
+ import { copyPluginDir, toPosix, writeJson } from "../fsutil.js";
10
10
  import { folderHash } from "../hash.js";
11
11
  import { packageFilter, PROJECTION_DIRS } from "../package.js";
12
12
  import { lockPath, marketplacePath, marketplaceSourcePath, pluginDir, pluginSourceCacheDir } from "../paths.js";
13
13
  import { readLock, upsertEntry, writeLock } from "../lock.js";
14
14
  import { ADG_MANIFEST_PATH, readManifest } from "../manifest.js";
15
+ import { recordTelemetryEvent } from "../telemetry.js";
15
16
  import { readMarketplace, upsertMarketplacePlugin, writeMarketplace } from "../marketplace.js";
16
17
  import { resolveInstallOrder } from "../deps.js";
17
- import { cloneGitHub, parseSource, scanNativePlugins, scanPlugins } from "../sources.js";
18
+ import { cloneGitHub, gitRevision, githubRepositoryDescription, parseGitHubSource, parseSource, scanNativePlugins, scanPlugins } from "../sources.js";
18
19
  import { normalizePluginSelection, pluginState, resolveSelectionDependencies, sameSource, COMPONENT_TYPES } from "../types.js";
19
20
  import { pluginContents, presentComponents } from "../components.js";
20
21
  import { skillDescriptionLoader } from "../skills.js";
21
22
  import { resolveAgents } from "../agents/index.js";
22
23
  import { effectivePackageFilter, materializePlugin, withPluginSourceCache } from "../materialize.js";
24
+ import { resolveDefaultDsl } from "../default-dsl.js";
23
25
  // Generated runtime projections never count toward a plugin's content hash.
24
26
  const HASH_IGNORE = PROJECTION_DIRS;
25
27
  /** Content hash over a plugin's packaged payload (hooks files are authored content, not generated). */
@@ -38,7 +40,7 @@ function contentHash(dir, manifest) {
38
40
  */
39
41
  export function installPlugin(opts) {
40
42
  const source = resolve(opts.source);
41
- const manifest = readManifest(source);
43
+ const manifest = readManifest(source, opts.telemetrySpan);
42
44
  const name = manifest.name;
43
45
  // Local installs stay flat; remote sources derive a per-marketplace dir from
44
46
  // their origin. The default (no origin) is a flat local copy-in.
@@ -55,6 +57,27 @@ export function installPlugin(opts) {
55
57
  // partial installs survive re-install / `marketplace upgrade`.
56
58
  const desiredSelection = normalizePluginSelection(opts.selection ?? prev?.selection);
57
59
  const selection = resolveSelectionDependencies(manifest, desiredSelection);
60
+ if (selection) {
61
+ const contents = pluginContents(source, manifest);
62
+ if (selection.skills) {
63
+ const invalid = selection.skills.filter((s) => !contents.skills.includes(s));
64
+ if (invalid.length > 0) {
65
+ throw new Error(`selected skill(s) not declared: ${invalid.join(", ")}`);
66
+ }
67
+ }
68
+ if (selection.mcp) {
69
+ const invalid = selection.mcp.filter((s) => !contents.mcp.includes(s));
70
+ if (invalid.length > 0) {
71
+ throw new Error(`selected mcp server(s) not declared: ${invalid.join(", ")}`);
72
+ }
73
+ }
74
+ recordTelemetryEvent("adg.install.selection", {
75
+ plugin: name,
76
+ "components.count": selection.components.length,
77
+ "skills.count": selection.skills ? selection.skills.length : -1,
78
+ "mcp.count": selection.mcp ? selection.mcp.length : -1,
79
+ }, opts.telemetrySpan);
80
+ }
58
81
  const sourceHash = contentHash(source, manifest);
59
82
  const cacheDir = pluginSourceCacheDir(opts.pluginsDir, name);
60
83
  return withPluginSourceCache(source, cacheDir, manifest, (snapshot) => {
@@ -95,6 +118,7 @@ export function installPlugin(opts) {
95
118
  version: manifest.version,
96
119
  sourceHash,
97
120
  installedHash,
121
+ ...(opts.resolvedRevision ? { resolvedRevision: opts.resolvedRevision } : {}),
98
122
  };
99
123
  if (manifest.dependencies?.length) {
100
124
  entry.dependencies = Object.fromEntries(manifest.dependencies.map((d) => [d.name, d.version]));
@@ -103,6 +127,8 @@ export function installPlugin(opts) {
103
127
  entry.selection = desiredSelection;
104
128
  if (prev?.state)
105
129
  entry.state = prev.state;
130
+ if (opts.definition)
131
+ entry.definition = opts.definition;
106
132
  const previousEntry = prev && Object.fromEntries(Object.entries(prev).filter(([key]) => key !== "installedAt" && key !== "updatedAt"));
107
133
  const changed = !prev || !isDeepStrictEqual(previousEntry, entry);
108
134
  if (changed) {
@@ -140,23 +166,14 @@ function discoverPlugins(root) {
140
166
  if (native.kind === "adg")
141
167
  continue;
142
168
  const raw = JSON.parse(readFileSync(native.manifestFile, "utf8"));
143
- const manifest = fromNativeManifest(raw, native.kind);
144
- // A Claude manifest omits `hooks` (Claude auto-loads hooks/hooks.json), and
145
- // `walkNative` prefers it over a sibling Codex manifest that *does* declare
146
- // hooks — so the reverse-adapt would silently drop the hooks payload. Recover
147
- // it from disk: a hooks/ directory means the ADG manifest must declare it, or
148
- // packagedRoots won't copy it and every downstream projection loses hooks.
149
- const hooksDir = join(native.dir, "hooks");
150
- if (!manifest.hooks && existsSync(hooksDir) && statSync(hooksDir).isDirectory()) {
151
- manifest.hooks = "./hooks/";
152
- }
169
+ const manifest = fromNativeManifest(raw, native.kind, native.dir);
153
170
  writeJson(join(native.dir, ADG_MANIFEST_PATH), manifest);
154
171
  converted.push(manifest.name);
155
172
  }
156
173
  return { candidates: scanPlugins(root), converted };
157
174
  }
158
175
  /** Resolve which discovered plugins to install from the selection options. */
159
- async function selectPluginNames(opts, candidates, workRoot, converted) {
176
+ async function selectPluginNames(opts, candidates, converted) {
160
177
  const names = [...candidates.keys()];
161
178
  if (opts.plugins?.length) {
162
179
  const missing = opts.plugins.filter((p) => !candidates.has(p));
@@ -165,13 +182,6 @@ async function selectPluginNames(opts, candidates, workRoot, converted) {
165
182
  }
166
183
  return opts.plugins.filter((p) => candidates.has(p));
167
184
  }
168
- if (opts.path) {
169
- const target = resolve(join(workRoot, opts.path));
170
- const hit = [...candidates.values()].find((c) => resolve(c.dir) === target);
171
- if (!hit)
172
- throw new Error(`no plugin found at --path ${opts.path}`);
173
- return [hit.manifest.name];
174
- }
175
185
  if (opts.all || candidates.size === 1)
176
186
  return names;
177
187
  if (opts.selectPlugins) {
@@ -196,15 +206,21 @@ async function selectPluginNames(opts, candidates, workRoot, converted) {
196
206
  */
197
207
  async function resolveSelections(opts, selected, candidates) {
198
208
  const selections = new Map();
199
- if (opts.only || opts.skillsSubset) {
209
+ if (opts.only || opts.skillsSubset || opts.mcpSubset) {
200
210
  const flagSelection = {
201
211
  components: opts.only ?? [...COMPONENT_TYPES],
202
212
  ...(opts.skillsSubset ? { skills: opts.skillsSubset } : {}),
213
+ ...(opts.mcpSubset ? { mcp: opts.mcpSubset } : {}),
203
214
  };
204
215
  for (const name of selected)
205
216
  selections.set(name, flagSelection);
206
217
  return selections;
207
218
  }
219
+ if (opts.replaySelection) {
220
+ for (const name of selected)
221
+ selections.set(name, opts.replaySelection);
222
+ return selections;
223
+ }
208
224
  if (!opts.confirmFull || !opts.selectComponents)
209
225
  return selections; // non-interactive default: full
210
226
  if (await opts.confirmFull(selected))
@@ -214,7 +230,7 @@ async function resolveSelections(opts, selected, candidates) {
214
230
  const contents = pluginContents(cand.dir, cand.manifest);
215
231
  const present = presentComponents(contents);
216
232
  // Nothing meaningful to pick: a lone category with at most one member.
217
- if (present.length <= 1 && contents.skills.length <= 1)
233
+ if (present.length <= 1 && contents.skills.length <= 1 && contents.mcp.length <= 1)
218
234
  continue;
219
235
  const skillDescription = skillDescriptionLoader(cand.dir, cand.manifest);
220
236
  selections.set(name, await opts.selectComponents({ name, contents, present, skillDescription }));
@@ -236,13 +252,12 @@ function sameRemoteSource(entry, parsed, ref) {
236
252
  * (`--plugin one` after previously installing `--all`) without leaving stale
237
253
  * runtime exports behind.
238
254
  */
239
- function reconcileRemotePlugins(opts, parsed, ref, narrowed, desired) {
255
+ function reconcileRemotePlugins(opts, parsed, ref, desired) {
240
256
  if (parsed.kind === "local")
241
257
  return [];
242
- // A path/sparse install does not prove the full source shape, so it must not
243
- // prune sibling plugins from the same repo that were intentionally excluded
244
- // from the checkout/selection window.
245
- if (narrowed || opts.sparse?.length)
258
+ // A sparse checkout does not prove the full source shape, so it must not
259
+ // prune sibling plugins from the same repo that were intentionally excluded.
260
+ if (opts.sparse?.length)
246
261
  return [];
247
262
  const lock = readLock(lockPath(opts.pluginsDir));
248
263
  const stale = Object.entries(lock.plugins)
@@ -268,42 +283,110 @@ function reconcileRemotePlugins(opts, parsed, ref, narrowed, desired) {
268
283
  }
269
284
  return stale;
270
285
  }
286
+ function activateInstalled(opts, targets, installed, existingPlugins) {
287
+ const updatedLock = readLock(lockPath(opts.pluginsDir));
288
+ const eligible = installed.filter((result) => pluginState(updatedLock.plugins[result.name]) === "enabled");
289
+ const toActivate = opts.skipUnchanged ? eligible.filter((result) => result.changed) : eligible;
290
+ if (!opts.activate || toActivate.length === 0)
291
+ return undefined;
292
+ const resolved = opts.agents ?? resolveAgents(targets);
293
+ const scope = opts.scope ?? "project";
294
+ const ctxFor = (names) => ({ pluginsDir: opts.pluginsDir, plugins: names, scope });
295
+ return resolved.map((agent) => {
296
+ const queryResult = agent.listInstalled?.(ctxFor([]));
297
+ const agentInstalled = Array.isArray(queryResult) ? queryResult : undefined;
298
+ const alreadyInstalled = (name) => agentInstalled !== undefined
299
+ ? agentInstalled.includes(name)
300
+ : existingPlugins.has(name);
301
+ const activateNames = toActivate.filter((result) => !alreadyInstalled(result.name)).map((result) => result.name);
302
+ const refreshNames = toActivate.filter((result) => alreadyInstalled(result.name)).map((result) => result.name);
303
+ const parts = [];
304
+ if (activateNames.length > 0)
305
+ parts.push(agent.activate(ctxFor(activateNames)));
306
+ if (refreshNames.length > 0)
307
+ parts.push(agent.refresh(ctxFor(refreshNames)));
308
+ return parts.reduce((acc, result) => ({ agent: result.agent, affected: [...acc.affected, ...result.affected], skipped: acc.skipped && result.skipped }), { agent: agent.id, affected: [], skipped: true });
309
+ });
310
+ }
271
311
  /**
272
312
  * The unified install entrypoint. Treats any source as a marketplace: clone or
273
313
  * read it, discover every plugin (ADG plus reverse-adapted native), choose a
274
- * subset (--all / --plugin / --path / sole plugin / interactive picker), then
314
+ * subset (--all / --plugin / sole plugin / interactive picker), then
275
315
  * install the selection in dependency-first order.
276
316
  */
277
317
  export async function addPlugins(opts) {
278
- const parsed = parseSource(opts.spec);
318
+ // Prepared checkouts are used only by remote marketplace update. Parse their
319
+ // persisted owner/repo key as GitHub even when the caller's CWD shadows it.
320
+ const parsed = opts.preparedSourceDir ? parseGitHubSource(opts.spec) : parseSource(opts.spec);
279
321
  const sourceRef = parsed.kind === "local" ? undefined : (opts.ref ?? parsed.ref);
280
- const inferredPath = parsed.kind === "github" ? parsed.path : undefined;
281
- const path = opts.path ?? inferredPath;
322
+ if (parsed.kind === "github" && parsed.path) {
323
+ throw new Error("GitHub subdirectory sources are not supported; define a marketplace and select with --plugin or --all");
324
+ }
282
325
  let workRoot;
283
326
  let buildOrigin;
327
+ let resolvedRevision;
284
328
  let cleanup;
285
- if (parsed.kind === "local") {
329
+ let originDirOverride;
330
+ let definition;
331
+ let defaultDescription;
332
+ let structuralName;
333
+ if (opts.preparedSourceDir) {
334
+ workRoot = resolve(opts.preparedSourceDir);
335
+ resolvedRevision = opts.preparedResolvedRevision;
336
+ buildOrigin = (dir) => ({ type: "github", repo: parsed.kind === "github" ? parsed.source : opts.spec, ...(sourceRef ? { ref: sourceRef } : {}), path: toPosix(relative(workRoot, originDirOverride ?? dir)) || "." });
337
+ }
338
+ else if (parsed.kind === "local") {
286
339
  workRoot = resolve(parsed.dir);
287
- buildOrigin = (dir) => ({ type: "local", path: resolve(dir) });
340
+ buildOrigin = (dir) => ({ type: "local", path: resolve(originDirOverride ?? dir) });
288
341
  }
289
342
  else {
290
343
  const tmp = mkdtempSync(join(tmpdir(), "adg-clone-"));
291
344
  cleanup = () => rmSync(tmp, { recursive: true, force: true });
292
345
  cloneGitHub({ ...parsed, ref: sourceRef }, tmp, { sparse: opts.sparse, runner: opts.gitRunner });
293
346
  workRoot = tmp;
347
+ resolvedRevision = gitRevision(tmp);
294
348
  buildOrigin = (dir) => ({
295
349
  type: "github",
296
350
  repo: parsed.source,
297
351
  ...(sourceRef ? { ref: sourceRef } : {}),
298
- path: toPosix(relative(tmp, dir)) || ".",
352
+ path: toPosix(relative(tmp, originDirOverride ?? dir)) || ".",
299
353
  });
300
354
  }
301
355
  try {
302
- const { candidates, converted } = discoverPlugins(workRoot);
356
+ let { candidates, converted } = discoverPlugins(workRoot);
357
+ const existingLock = readLock(lockPath(opts.pluginsDir));
358
+ if (candidates.size > 0 && opts.as) {
359
+ throw new Error("--as is only supported for a default structural plugin source");
360
+ }
303
361
  if (candidates.size === 0) {
304
- throw new Error(`no plugin found in "${opts.spec}" (no .agents/.plugin.json, .claude-plugin or .codex-plugin manifest).`);
362
+ if (parsed.kind === "github" && !opts.preparedSourceDir && !opts.defaultDescription)
363
+ defaultDescription = await githubRepositoryDescription(parsed.source);
364
+ const structuralIdentity = opts.as ?? (parsed.kind === "github" ? parsed.source : basename(workRoot));
365
+ const generated = resolveDefaultDsl(workRoot, {
366
+ name: structuralIdentity,
367
+ description: defaultDescription ?? opts.defaultDescription ?? structuralIdentity,
368
+ }, {
369
+ ...(parsed.kind === "github" && resolvedRevision ? { resolvedRevision } : {}),
370
+ });
371
+ const authorized = opts.authorizedComponents;
372
+ const unauthorizedRisk = generated.components.some((c) => (c === "hooks" || c === "mcp") && !authorized?.includes(c));
373
+ if (opts.nonInteractive && unauthorizedRisk && opts.only === undefined) {
374
+ throw new Error("default source exposes hooks or MCP; pass --only to explicitly authorize selected components");
375
+ }
376
+ const staging = mkdtempSync(join(tmpdir(), "adg-default-plugin-"));
377
+ copyPluginDir(workRoot, staging);
378
+ writeJson(join(staging, ADG_MANIFEST_PATH), generated.manifest);
379
+ candidates = scanPlugins(staging);
380
+ structuralName = generated.manifest.name;
381
+ converted = [];
382
+ originDirOverride = workRoot;
383
+ definition = { kind: "default-dsl/v1", root: ".", ...(opts.as ? { as: generated.manifest.name } : {}), description: generated.manifest.description, fingerprint: generated.fingerprint, authorizedComponents: authorized ?? (opts.only ?? generated.components) };
384
+ cleanup = (() => {
385
+ const prior = cleanup;
386
+ return () => { rmSync(staging, { recursive: true, force: true }); prior?.(); };
387
+ })();
305
388
  }
306
- const selected = await selectPluginNames({ ...opts, path }, candidates, workRoot, converted);
389
+ const selected = structuralName ? [structuralName] : await selectPluginNames(opts, candidates, converted);
307
390
  // Resolve adapter targets after the plugin choice (lets a CLI agent picker
308
391
  // run once we know what's being installed). undefined → installPlugin's all.
309
392
  const targets = opts.targets ?? (opts.selectTargets ? await opts.selectTargets() : undefined);
@@ -313,13 +396,19 @@ export async function addPlugins(opts) {
313
396
  // upstream: don't abort — return what the source still offers so the
314
397
  // caller can report the deletions.
315
398
  if (opts.missingPlugins === "skip") {
316
- const removed = reconcileRemotePlugins(opts, parsed, sourceRef, Boolean(path), new Set(selected));
399
+ const removed = reconcileRemotePlugins(opts, parsed, sourceRef, new Set(selected));
317
400
  return { order: [], installed: [], removed, converted, available };
318
401
  }
319
402
  throw new Error("no plugins selected");
320
403
  }
321
404
  // Partial-install selection per user-chosen plugin (auto-deps install full).
322
405
  const selections = await resolveSelections(opts, selected, candidates);
406
+ if (definition && structuralName) {
407
+ definition = {
408
+ ...definition,
409
+ authorizedComponents: selections.get(structuralName)?.components ?? definition.authorizedComponents,
410
+ };
411
+ }
323
412
  // Dependency-first order across every selected plugin (chains deduped).
324
413
  const order = [];
325
414
  const seen = new Set();
@@ -332,7 +421,14 @@ export async function addPlugins(opts) {
332
421
  }
333
422
  }
334
423
  }
335
- const removed = reconcileRemotePlugins(opts, parsed, sourceRef, Boolean(path), new Set(order));
424
+ // A generated Default DSL replay retains its definition profile. Only an
425
+ // explicit manifest discovered from the source may replace that profile.
426
+ const definitionSwitches = definition ? [] : order.filter((name) => existingLock.plugins[name]?.definition);
427
+ if (definitionSwitches.length > 0) {
428
+ const names = definitionSwitches.sort().map((name) => `"${name}"`).join(", ");
429
+ throw new Error(`source definition changed from default DSL to a manifest for ${names}; re-add or migrate the plugin explicitly`);
430
+ }
431
+ const removed = reconcileRemotePlugins(opts, parsed, sourceRef, new Set(order));
336
432
  // Snapshot which plugins already existed before this call mutates the lock,
337
433
  // so the activation step below can tell brand-new installs from updates.
338
434
  const existingPlugins = new Set(Object.keys(readLock(lockPath(opts.pluginsDir)).plugins));
@@ -343,11 +439,13 @@ export async function addPlugins(opts) {
343
439
  source: candidate.dir,
344
440
  pluginsDir: opts.pluginsDir,
345
441
  origin: buildOrigin(candidate.dir),
442
+ resolvedRevision,
346
443
  marketplaceName: opts.marketplaceName,
347
444
  targets,
348
445
  selection: selections.get(name),
349
446
  skipUnchanged: opts.skipUnchanged,
350
447
  now: opts.now,
448
+ definition: name === structuralName ? definition : undefined,
351
449
  }));
352
450
  }
353
451
  // Activate into the selected agents so the plugins are actually usable, not
@@ -355,38 +453,7 @@ export async function addPlugins(opts) {
355
453
  // undefined targets = all registered agents. Under skipUnchanged (the update
356
454
  // path) only re-activate plugins that actually changed — re-running an agent
357
455
  // CLI for an untouched plugin is wasted work.
358
- let agents;
359
- const updatedLock = readLock(lockPath(opts.pluginsDir));
360
- const eligible = installed.filter((result) => pluginState(updatedLock.plugins[result.name]) === "enabled");
361
- const toActivate = opts.skipUnchanged ? eligible.filter((r) => r.changed) : eligible;
362
- if (opts.activate && toActivate.length > 0) {
363
- const resolved = opts.agents ?? resolveAgents(targets);
364
- const scope = opts.scope ?? "project";
365
- const ctxFor = (names) => ({ pluginsDir: opts.pluginsDir, plugins: names, scope });
366
- agents = resolved.map((a) => {
367
- const queryResult = a.listInstalled?.(ctxFor([]));
368
- const agentInstalled = Array.isArray(queryResult) ? queryResult : undefined;
369
- const alreadyInstalled = (name) => agentInstalled !== undefined
370
- ? agentInstalled.includes(name)
371
- : existingPlugins.has(name);
372
- // Existing plugins must go through refresh even on an explicit `add`:
373
- // agents like Claude cache an installed copy, and their plain install
374
- // command is a no-op when the plugin already exists. If the agent can
375
- // enumerate live installs, trust that state; otherwise fall back to the
376
- // ADG lock to preserve clean-update behavior.
377
- const activateNames = toActivate.filter((r) => !alreadyInstalled(r.name)).map((r) => r.name);
378
- const refreshNames = toActivate.filter((r) => alreadyInstalled(r.name)).map((r) => r.name);
379
- // An agent may run both lifecycles (new installs + updates) in one pass;
380
- // merge into the existing affected/skipped contract so downstream report
381
- // and consolidation (renderAgentReport, mergeAgentResults) stay unchanged.
382
- const parts = [];
383
- if (activateNames.length > 0)
384
- parts.push(a.activate(ctxFor(activateNames)));
385
- if (refreshNames.length > 0)
386
- parts.push(a.refresh(ctxFor(refreshNames)));
387
- return parts.reduce((acc, r) => ({ agent: r.agent, affected: [...acc.affected, ...r.affected], skipped: acc.skipped && r.skipped }), { agent: a.id, affected: [], skipped: true });
388
- });
389
- }
456
+ const agents = activateInstalled(opts, targets, installed, existingPlugins);
390
457
  return { order, installed, removed, converted, available, agents };
391
458
  }
392
459
  finally {
@@ -1,9 +1,6 @@
1
- import { adaptedFilesForTarget, selectInstalled } from "./projection.js";
2
- import { pluginRematerializationSource } from "../paths.js";
1
+ import { adaptedFilesForTarget, rematerializeInstalled, selectInstalled } from "./projection.js";
3
2
  import { getAgent } from "../agents/index.js";
4
- import { ADAPTER_TARGETS } from "../adapters/index.js";
5
3
  import { pluginState } from "../types.js";
6
- import { installPlugin } from "./install.js";
7
4
  /**
8
5
  * Project installed plugins into an agent: (re)generate that agent's manifest
9
6
  * from each plugin (honoring its partial-install selection), then enable the
@@ -20,18 +17,8 @@ export function linkPlugins(opts) {
20
17
  throw new Error(`disabled plugin(s): ${names.join(", ")}. Run \`adg plugins enable ${names.join(" ")}\`.`);
21
18
  }
22
19
  const enabled = selected.filter((p) => pluginState(p) === "enabled");
23
- const actions = [];
24
- for (const p of enabled) {
25
- const result = installPlugin({
26
- source: pluginRematerializationSource(opts.pluginsDir, p.name, p.origin),
27
- pluginsDir: opts.pluginsDir,
28
- origin: p.origin,
29
- selection: p.selection,
30
- targets: [...ADAPTER_TARGETS],
31
- forceMaterialize: true,
32
- });
33
- actions.push({ name: p.name, adapted: adaptedFilesForTarget(result.installedTo, result.adapted, adaptTarget) });
34
- }
20
+ const actions = rematerializeInstalled(opts.pluginsDir, enabled)
21
+ .map((result) => ({ name: result.name, adapted: adaptedFilesForTarget(result.installedTo, result.adapted, adaptTarget) }));
35
22
  if (!agent)
36
23
  return { target: opts.target, actions };
37
24
  if (actions.length === 0)
@@ -40,6 +27,7 @@ export function linkPlugins(opts) {
40
27
  pluginsDir: opts.pluginsDir,
41
28
  plugins: actions.map((a) => a.name),
42
29
  scope: opts.global ? "user" : "project",
30
+ ...(opts.target === "codex" ? { reconcileLegacyAliases: true } : {}),
43
31
  });
44
32
  for (const a of actions)
45
33
  if (res.affected.includes(a.name))