@rbbtsn0w/adg 0.11.0 → 0.11.1-dev.pr200.c6ce45e

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 (59) hide show
  1. package/README.md +131 -73
  2. package/dist/src/agents/antigravity.js +218 -45
  3. package/dist/src/agents/base.js +1 -1
  4. package/dist/src/agents/claude.js +98 -38
  5. package/dist/src/agents/codex.js +32 -42
  6. package/dist/src/cli/core-plugin-handlers.js +3 -3
  7. package/dist/src/cli/handlers.js +171 -39
  8. package/dist/src/cli/index.js +23 -14
  9. package/dist/src/cli/review-update.js +80 -0
  10. package/dist/src/commands/install/default-dsl.js +1 -1
  11. package/dist/src/commands/install/discovery.js +3 -1
  12. package/dist/src/commands/install/install-one.js +41 -31
  13. package/dist/src/commands/install.js +59 -24
  14. package/dist/src/commands/marketplace.js +171 -115
  15. package/dist/src/commands/migrate.js +2 -2
  16. package/dist/src/commands/projection.js +3 -1
  17. package/dist/src/commands/remove.js +10 -0
  18. package/dist/src/commands/review-executables.js +106 -0
  19. package/dist/src/commands/select-agents.js +2 -2
  20. package/dist/src/commands/select-components.js +2 -2
  21. package/dist/src/commands/select-plugins.js +15 -2
  22. package/dist/src/commands/select-scope.js +3 -4
  23. package/dist/src/commands/source-upgrade.js +552 -0
  24. package/dist/src/commands/state.js +3 -1
  25. package/dist/src/commands/status.js +1 -0
  26. package/dist/src/commands/update.js +3 -1
  27. package/dist/src/lock.js +13 -5
  28. package/dist/src/migration-transaction.js +1011 -0
  29. package/dist/src/native-retry.js +329 -0
  30. package/dist/src/process-identity.js +88 -0
  31. package/dist/src/render/plugins.js +149 -27
  32. package/dist/src/render/ui.js +4 -4
  33. package/dist/src/source-history.js +194 -0
  34. package/dist/src/source-intent.js +7 -0
  35. package/dist/src/store-mutex.js +179 -0
  36. package/dist/src/types.js +1 -1
  37. package/dist/src/update-executables.js +193 -0
  38. package/dist/src/upgrade-plan.js +378 -0
  39. package/docs/agents/antigravity.md +5 -0
  40. package/docs/agents-spec.md +10 -0
  41. package/docs/branching-and-release.md +369 -55
  42. package/docs/cli-json.md +9 -0
  43. package/docs/marketing/README.md +211 -0
  44. package/docs/marketing/assets.json +228 -0
  45. package/docs/marketing/capture.json +130 -0
  46. package/docs/marketing/live-readiness.json +353 -0
  47. package/docs/marketing/posts.en.md +94 -0
  48. package/docs/marketing/posts.zh-CN.md +67 -0
  49. package/docs/marketing/production.md +210 -0
  50. package/docs/marketing/source/timeline.json +29 -0
  51. package/docs/marketing/source/workflow-01.svg +16 -0
  52. package/docs/marketing/source/workflow-02.svg +14 -0
  53. package/docs/marketing/source/workflow-03.svg +19 -0
  54. package/docs/marketing/source/workflow-poster.svg +32 -0
  55. package/docs/marketing/transcript.md +48 -0
  56. package/docs/plugin-update-semantics.md +53 -10
  57. package/docs/plugin-upgrade-migrations.md +349 -0
  58. package/package.json +14 -10
  59. package/schemas/plugin-lock.schema.json +78 -1
@@ -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"));
@@ -3,7 +3,10 @@ import { tmpdir } from "node:os";
3
3
  import { join, relative, resolve } from "node:path";
4
4
  import { toPosix } from "../fsutil.js";
5
5
  import { lockPath } from "../paths.js";
6
- import { readLock } from "../lock.js";
6
+ import { syncNativeBatchWithRetry } from "../native-retry.js";
7
+ import { installedHistory } from "../source-history.js";
8
+ import { sourceIntent, setSourceIntent } from "../source-intent.js";
9
+ import { readLock, writeLock } from "../lock.js";
7
10
  import { resolveInstallOrder } from "../deps.js";
8
11
  import { cloneGitHub, gitRevision, parseGitHubSource, parseSource } from "../sources.js";
9
12
  import { materializeSource } from "../remote/index.js";
@@ -67,7 +70,7 @@ async function prepareSource(opts, parsed, sourceRef) {
67
70
  throw error;
68
71
  }
69
72
  }
70
- function activateInstalled(opts, targets, installed, existingPlugins) {
73
+ async function activateInstalled(opts, targets, installed, existingPlugins) {
71
74
  const updatedLock = readLock(lockPath(opts.pluginsDir));
72
75
  const eligible = installed.filter((result) => pluginState(updatedLock.plugins[result.name]) === "enabled");
73
76
  const toActivate = opts.skipUnchanged ? eligible.filter((result) => result.runtimeRefreshRequired ?? result.changed) : eligible;
@@ -76,30 +79,23 @@ function activateInstalled(opts, targets, installed, existingPlugins) {
76
79
  const resolved = opts.agents ?? resolveAgents(targets);
77
80
  const scope = opts.scope ?? "project";
78
81
  const ctxFor = (names) => ({ pluginsDir: opts.pluginsDir, plugins: names, scope });
79
- return resolved.map((agent) => {
82
+ const requests = [];
83
+ for (const agent of resolved) {
80
84
  opts.onProgress?.({ kind: "activate", agent: agent.id, count: toActivate.length });
81
85
  const queryResult = agent.listInstalled?.(ctxFor([]));
82
86
  const agentInstalled = Array.isArray(queryResult) ? queryResult : undefined;
83
87
  const alreadyInstalled = (name) => agentInstalled !== undefined
84
- ? agentInstalled.includes(name)
85
- : existingPlugins.has(name);
86
- const activateNames = toActivate.filter((result) => !alreadyInstalled(result.name)).map((result) => result.name);
87
- const refreshNames = toActivate.filter((result) => alreadyInstalled(result.name)).map((result) => result.name);
88
- const parts = [];
89
- if (activateNames.length > 0)
90
- parts.push(agent.activate(ctxFor(activateNames)));
91
- if (refreshNames.length > 0)
92
- parts.push(agent.refresh(ctxFor(refreshNames)));
93
- return parts.reduce((acc, result) => ({
94
- agent: result.agent,
95
- affected: [...acc.affected, ...result.affected],
96
- skipped: acc.skipped && result.skipped,
97
- ...((acc.failures?.length || result.failures?.length) ? { failures: [...(acc.failures ?? []), ...(result.failures ?? [])] } : {}),
98
- ...Object.fromEntries(["verified", "unverified", "preservedDisabled"]
99
- .filter((field) => acc[field] !== undefined || result[field] !== undefined)
100
- .map((field) => [field, [...new Set([...(acc[field] ?? []), ...(result[field] ?? [])])]])),
101
- }), { agent: agent.id, affected: [], skipped: true });
102
- });
88
+ ? agentInstalled.includes(name) : existingPlugins.has(name);
89
+ const activateNames = toActivate.filter(result => !alreadyInstalled(result.name)).map(result => result.name);
90
+ const refreshNames = toActivate.filter(result => alreadyInstalled(result.name)).map(result => result.name);
91
+ requests.push({
92
+ agent,
93
+ activate: activateNames,
94
+ refresh: refreshNames,
95
+ preserveRuntimeDisabled: Boolean(opts.skipUnchanged || opts.preserveExisting),
96
+ });
97
+ }
98
+ return syncNativeBatchWithRetry({ pluginsDir: opts.pluginsDir, scope, requests });
103
99
  }
104
100
  /**
105
101
  * The unified install entrypoint. Treats any source as a marketplace: clone or
@@ -133,6 +129,12 @@ export async function addPlugins(opts) {
133
129
  }
134
130
  }
135
131
  if (candidates.size === 0) {
132
+ // Ordinary plugin updates cannot authorize a new structural identity
133
+ // after all explicit manifests disappear. Existing DSL profiles replay
134
+ // separately with their persisted identity and authorization.
135
+ if (opts.preserveExisting && !opts.structuralIdentity) {
136
+ return { order: [], installed: [], removed: [], converted, available: [] };
137
+ }
136
138
  const synthesized = await synthesizeDefaultDslPlugin(opts, parsed, workRoot, resolvedRevision);
137
139
  candidates = synthesized.candidates;
138
140
  converted = synthesized.converted;
@@ -149,7 +151,15 @@ export async function addPlugins(opts) {
149
151
  }
150
152
  };
151
153
  }
152
- const selected = structuralName ? [structuralName] : await selectPluginNames(opts, candidates, converted);
154
+ const installedAtAnotherRef = (name) => {
155
+ const origin = existingLock.plugins[name]?.origin;
156
+ return parsed.kind === "github" && origin?.type === "github"
157
+ && origin.repo === parsed.source && origin.ref !== sourceRef;
158
+ };
159
+ const chosen = structuralName ? [structuralName] : await selectPluginNames(opts, candidates, converted);
160
+ // --all permits additions, but an existing sibling still belongs to its
161
+ // own ref. Explicit add remains the operation that can change that pin.
162
+ const selected = opts.preserveExisting ? chosen.filter((name) => !installedAtAnotherRef(name)) : chosen;
153
163
  // Resolve adapter targets after the plugin choice (lets a CLI agent picker
154
164
  // run once we know what's being installed). undefined → installPlugin's all.
155
165
  const targets = opts.targets ?? (opts.selectTargets ? await opts.selectTargets() : undefined);
@@ -184,6 +194,12 @@ export async function addPlugins(opts) {
184
194
  }
185
195
  }
186
196
  }
197
+ if (opts.preserveExisting) {
198
+ const conflicts = order.filter(installedAtAnotherRef);
199
+ if (conflicts.length > 0) {
200
+ throw new Error(`dependency plugin(s) installed at a different source ref: ${conflicts.join(", ")}; re-add or migrate explicitly`);
201
+ }
202
+ }
187
203
  // A generated Default DSL replay retains its definition profile. Only an
188
204
  // explicit manifest discovered from the source may replace that profile.
189
205
  const definitionSwitches = definition
@@ -221,7 +237,26 @@ export async function addPlugins(opts) {
221
237
  // undefined targets = all registered agents. Under skipUnchanged (the update
222
238
  // path) only re-activate plugins that actually changed — re-running an agent
223
239
  // CLI for an untouched plugin is wasted work.
224
- const agents = activateInstalled(opts, targets, installed, existingPlugins);
240
+ if (!opts.preserveExisting && parsed.kind === "github") {
241
+ const file = lockPath(opts.pluginsDir);
242
+ const lock = readLock(file);
243
+ const previous = sourceIntent(existingLock, parsed.source, sourceRef);
244
+ const followAll = Boolean((opts.all || opts.followAllSelected) && !opts.plugins?.length && !opts.sparse?.length && !structuralName);
245
+ setSourceIntent(lock, {
246
+ source: parsed.source, ref: sourceRef, mode: followAll ? "all" : "selected",
247
+ roots: selected, excluded: followAll ? [] : (previous?.excluded ?? []).filter((name) => !order.includes(name)),
248
+ appliedMigrations: [],
249
+ history: installedHistory(opts.pluginsDir, lock, parsed.source, sourceRef),
250
+ deferredRecovery: previous?.deferredRecovery,
251
+ executableDecisions: previous?.executableDecisions,
252
+ ...(targets ? { targets } : {}),
253
+ withDeps: opts.withDeps !== false,
254
+ ...(opts.sparse ? { sparse: opts.sparse } : {}),
255
+ ...(opts.only || opts.skillsSubset || opts.mcpSubset ? { selection: selections.get(selected[0]) } : {}),
256
+ });
257
+ writeLock(file, lock);
258
+ }
259
+ const agents = await activateInstalled(opts, targets, installed, existingPlugins);
225
260
  return { order, installed, removed, converted, available, agents };
226
261
  }
227
262
  finally {
@@ -1,17 +1,23 @@
1
+ import { upgradeSource, publishUpgradeTransaction, UpdateCancelled } from "./source-upgrade.js";
2
+ import { ADAPTER_TARGETS } from "../adapters/index.js";
3
+ import { sourceIntent } from "../source-intent.js";
4
+ import { replayNativeRetries, syncNativeWithRetry } from "../native-retry.js";
5
+ import { discoverPendingMigrations } from "../migration-transaction.js";
1
6
  import { repairCodex } from "./runtime-repair.js";
2
- import { getAgent, resolveAgents, allAgents } from "../agents/index.js";
3
- import { gitRemoteRevision } from "../sources.js";
7
+ import { getAgent, resolveAgents } from "../agents/index.js";
8
+ import {} from "../sources.js";
4
9
  import { cloneGitHub, gitRevision, parseGitHubSource } from "../sources.js";
5
10
  import { materializeSource, resolveRemoteRevision } from "../remote/index.js";
6
11
  import { mkdtempSync, rmSync } from "node:fs";
7
12
  import { tmpdir } from "node:os";
8
13
  import { join } from "node:path";
14
+ import { pluginState } from "../types.js";
9
15
  import { lockPath } from "../paths.js";
10
- import { readLock } from "../lock.js";
11
- import { addPlugins } from "./install.js";
16
+ import { readLock, writeLock } from "../lock.js";
12
17
  import { removePlugin } from "./remove.js";
13
18
  import { syncPlugins } from "./sync.js";
14
19
  import { updateLock } from "./update.js";
20
+ import { recordTelemetryEvent } from "../telemetry.js";
15
21
  /**
16
22
  * A stable key identifying the source a plugin came from. GitHub/git plugins
17
23
  * group by repo/url (the marketplace root, ignoring per-plugin sub-paths);
@@ -37,22 +43,29 @@ export function marketplaceList(opts) {
37
43
  const lock = readLock(lockPath(opts.pluginsDir));
38
44
  const groups = new Map();
39
45
  for (const [name, entry] of Object.entries(lock.plugins)) {
40
- const key = sourceKey(entry.origin);
46
+ const source = sourceKey(entry.origin);
41
47
  const ref = entry.origin.type === "github" || entry.origin.type === "git" ? entry.origin.ref : undefined;
42
- const g = groups.get(key) ?? { ref, installed: [] };
43
- g.installed.push(name);
44
- if (g.ref === undefined && ref !== undefined)
45
- g.ref = ref;
46
- groups.set(key, g);
48
+ const group = groups.get(source) ?? {
49
+ source, ...(ref ? { ref } : {}), installed: [], disabled: [], remote: isRemoteKey(source),
50
+ };
51
+ if (group.ref !== ref)
52
+ delete group.ref;
53
+ group.installed.push(name);
54
+ if (pluginState(entry) === "disabled")
55
+ group.disabled.push(name);
56
+ groups.set(source, group);
47
57
  }
48
- return [...groups.entries()]
49
- .map(([source, g]) => ({
50
- source,
51
- ...(g.ref ? { ref: g.ref } : {}),
52
- installed: g.installed.sort(),
53
- remote: isRemoteKey(source),
54
- }))
55
- .sort((a, b) => a.source.localeCompare(b.source));
58
+ for (const intent of lock.sources ?? []) {
59
+ const { source, ref } = intent;
60
+ if ((intent.mode === "all" || intent.deferredRecovery?.length) && !groups.has(source)) {
61
+ groups.set(source, { source, ...(ref ? { ref } : {}), installed: [], disabled: [], remote: isRemoteKey(source) });
62
+ }
63
+ }
64
+ for (const group of groups.values()) {
65
+ group.installed.sort();
66
+ group.disabled.sort();
67
+ }
68
+ return [...groups.values()].sort((a, b) => a.source.localeCompare(b.source));
56
69
  }
57
70
  /**
58
71
  * Find one source group by key, or throw with the available keys. The error is
@@ -108,20 +121,83 @@ export function mergeAgentResults(groups) {
108
121
  /**
109
122
  * The plugins-domain equivalent of `adg skills update`: re-fetch every remote
110
123
  * source (or one named `source`), report which installed plugins changed,
111
- * stayed the same, were deleted upstream, or are newly available, and refresh
124
+ * stayed the same, are missing upstream, or are newly available, and refresh
112
125
  * local-source plugins in place. Failures are recorded per-source rather than
113
126
  * aborting the whole pass, so one unreachable repo doesn't hide the rest.
114
127
  */
115
128
  export async function updatePlugins(opts) {
129
+ const executionProviders = opts.activate ? opts.agents ?? [...new Map([
130
+ ...resolveAgents(opts.targets), ...(opts.repair ? resolveAgents(["codex"]) : []),
131
+ ].map(agent => [agent.id, agent])).values()] : [];
132
+ // Replay pending operations before probing any remote revision.
133
+ const pending = discoverPendingMigrations(opts.pluginsDir).filter(item => !opts.source || item.source === opts.source);
134
+ const remote = [];
135
+ const resumedAgents = [];
136
+ const managedByMigration = new Set();
137
+ const rememberManagedNative = (targets) => {
138
+ for (const target of targets)
139
+ if (target.agent === "codex")
140
+ for (const name of target.plugins)
141
+ managedByMigration.add(name);
142
+ };
143
+ for (const item of pending) {
144
+ let resumed;
145
+ try {
146
+ resumed = await publishUpgradeTransaction(item.journalPath, executionProviders, item.source, opts.review, item.ref, opts.repair ? ["codex"] : undefined);
147
+ }
148
+ catch (error) {
149
+ if (error instanceof UpdateCancelled) {
150
+ error.partial = { remote: [...remote, ...(error.partial?.remote ?? [])], local: { results: [], missing: [] },
151
+ agents: [...resumedAgents, ...(error.partial?.agents ?? [])] };
152
+ }
153
+ throw error;
154
+ }
155
+ resumedAgents.push(...(resumed.agents ?? []));
156
+ rememberManagedNative(resumed.managedNative ?? []);
157
+ remote.push({
158
+ source: item.source, ref: item.ref, updated: [], unchanged: [], deleted: [], available: [],
159
+ ...(resumed.complete ? { resumed: true } : { pendingRuntime: resumed.failures.map(failure => failure.message) }),
160
+ });
161
+ }
162
+ const recovered = await replayNativeRetries({
163
+ pluginsDir: opts.pluginsDir, source: opts.source, agents: executionProviders,
164
+ onProgress: opts.onProgress,
165
+ });
166
+ for (const group of recovered.groups) {
167
+ const failures = recovered.pending.filter(item => item.source === group.source && item.ref === group.ref);
168
+ remote.push({ ...group, updated: [], unchanged: [], deleted: [], available: [],
169
+ ...(failures.length ? { pendingRuntime: failures.map(item => item.message) } : { resumed: true }) });
170
+ }
116
171
  const allGroups = marketplaceList({ pluginsDir: opts.pluginsDir });
117
172
  // A named source narrows to just that group (and must be remote); otherwise we
118
173
  // refresh every remote source and rescan the local bucket.
119
- const remoteGroups = opts.source
120
- ? [requireGroup(opts.pluginsDir, opts.source, opts.scope)]
174
+ const selectedGroups = opts.source
175
+ ? (remote.some(group => group.source === opts.source) ? allGroups.filter(group => group.source === opts.source)
176
+ : [requireGroup(opts.pluginsDir, opts.source, opts.scope)])
121
177
  : allGroups.filter((g) => g.remote);
122
- if (opts.source && !remoteGroups[0].remote) {
178
+ if (opts.source && selectedGroups[0]?.remote === false) {
123
179
  throw new Error(`source "${opts.source}" is local and cannot be re-synced; re-run \`adg plugins add\`.`);
124
180
  }
181
+ // The marketplace view aggregates a repository for list/remove/sync. Update
182
+ // must fetch each ref independently so one plugin cannot move a sibling's
183
+ // pin or make it appear absent at the wrong revision.
184
+ const initialLock = readLock(lockPath(opts.pluginsDir));
185
+ const remoteGroups = selectedGroups.flatMap((group) => {
186
+ const refs = new Map();
187
+ for (const name of group.installed) {
188
+ const origin = initialLock.plugins[name].origin;
189
+ const ref = origin.type === "local" ? undefined : origin.ref;
190
+ const member = refs.get(ref) ?? { source: group.source, ...(ref ? { ref } : {}), installed: [], remote: true };
191
+ member.installed.push(name);
192
+ refs.set(ref, member);
193
+ }
194
+ for (const intent of initialLock.sources ?? []) {
195
+ if (intent.source === group.source && (intent.mode === "all" || intent.deferredRecovery?.length) && !refs.has(intent.ref)) {
196
+ refs.set(intent.ref, { source: group.source, ref: intent.ref, installed: [], remote: true });
197
+ }
198
+ }
199
+ return [...refs.values()].filter(group => !remote.some(item => item.source === group.source && item.ref === group.ref));
200
+ });
125
201
  const repairAgent = opts.agents
126
202
  ? opts.agents.find((agent) => agent.id === "codex") ?? null
127
203
  : getAgent("codex");
@@ -129,46 +205,43 @@ export async function updatePlugins(opts) {
129
205
  const initial = opts.repair ? repairAgent?.inspectPlugins?.({ pluginsDir: opts.pluginsDir, plugins: [], scope: repairScope }) : undefined;
130
206
  // Source materialization proceeds, but this mode owns every Codex mutation.
131
207
  const updateAgents = opts.repair ? (opts.agents ?? resolveAgents(opts.targets)).filter((agent) => agent.id !== "codex") : opts.agents;
132
- const removalAgents = opts.repair ? (opts.deactivationAgents ?? allAgents()).filter((agent) => agent.id !== "codex") : opts.deactivationAgents;
133
208
  const now = opts.now ?? new Date().toISOString();
134
- const remote = [];
135
- const remoteAgents = [];
209
+ const remoteAgents = [...resumedAgents, ...recovered.agents];
136
210
  let sourceIndex = 0;
137
211
  for (const group of remoteGroups) {
138
212
  const position = { index: ++sourceIndex, total: remoteGroups.length };
139
213
  try {
140
214
  opts.onProgress?.({ kind: "check", ...position, source: group.source });
141
215
  const lock = readLock(lockPath(opts.pluginsDir));
142
- const revisions = group.installed.map((name) => lock.plugins[name]?.resolvedRevision).filter((revision) => Boolean(revision));
143
- const remoteRevision = await (opts.revisionResolver ?? resolveRemoteRevision)(group.source, group.ref);
144
- if (!opts.all && remoteRevision && revisions.length === group.installed.length && revisions.every((revision) => revision === remoteRevision)) {
145
- remote.push({ source: group.source, ...(group.ref ? { ref: group.ref } : {}), updated: [], unchanged: [...group.installed].sort(), deleted: [], available: [] });
216
+ const policy = sourceIntent(lock, group.source, group.ref);
217
+ const targets = opts.targets ?? policy?.targets?.filter((id) => ADAPTER_TARGETS.includes(id));
218
+ const runtime = opts.activate ? opts.agents ?? resolveAgents(targets) : [];
219
+ const refreshExisting = runtime.flatMap(agent => {
220
+ if (!agent.needsProjectionRefresh || !agent.detect())
221
+ return [];
222
+ const names = group.installed.filter(name => lock.plugins[name]?.state !== "disabled");
223
+ return agent.needsProjectionRefresh({ pluginsDir: opts.pluginsDir, scope: repairScope, plugins: names })
224
+ .map(name => ({ name, target: agent.id }));
225
+ });
226
+ const refreshProjections = async (unchanged) => {
227
+ for (const agent of runtime) {
228
+ const refresh = refreshExisting.filter(item => item.target === agent.id && unchanged.includes(item.name)).map(item => item.name);
229
+ if (refresh.length)
230
+ remoteAgents.push(await syncNativeWithRetry({
231
+ pluginsDir: opts.pluginsDir, scope: repairScope, agent, activate: [], refresh, preserveRuntimeDisabled: true,
232
+ }));
233
+ }
234
+ };
235
+ const revisions = group.installed.map((name) => policy?.retained?.includes(name) ? policy.retainedAtRevision : lock.plugins[name]?.resolvedRevision).filter((revision) => Boolean(revision));
236
+ // A supplied transport owns its checkout, including offline fixtures.
237
+ const probe = opts.revisionResolver ?? (opts.gitRunner ? undefined : resolveRemoteRevision);
238
+ const remoteRevision = await probe?.(group.source, group.ref);
239
+ if (!opts.all && !(opts.repair && policy?.deferredRecovery?.length) && revisions.length > 0 && remoteRevision && revisions.length === group.installed.length && revisions.every((revision) => revision === remoteRevision)) {
240
+ await refreshProjections(group.installed);
241
+ remote.push({ source: group.source, ...(group.ref ? { ref: group.ref } : {}), updated: [], unchanged: group.installed.filter(name => !policy?.retained?.includes(name)).sort(), retained: policy?.retained, deleted: [], available: [],
242
+ ...(policy?.deferredRecovery?.length ? { deferredRecovery: [...new Set(policy.deferredRecovery.flatMap(item => item.skills))].sort() } : {}) });
146
243
  continue;
147
244
  }
148
- const structural = group.installed.flatMap((name) => {
149
- const definition = lock.plugins[name]?.definition;
150
- return definition ? [{ name, definition, selection: lock.plugins[name]?.selection }] : [];
151
- });
152
- const ordinary = group.installed.filter((name) => !lock.plugins[name]?.definition);
153
- // A structural profile always describes the source root. Replay each
154
- // profile independently so its stable --as identity is preserved.
155
- const requests = [
156
- ...structural.map(({ name, definition, selection }) => ({
157
- plugins: [name],
158
- as: definition.as,
159
- structuralIdentity: name,
160
- defaultDescription: definition.description,
161
- authorizedComponents: definition.authorizedComponents,
162
- replaySelection: selection ?? (definition.authorizedComponents ? { components: definition.authorizedComponents } : undefined),
163
- })),
164
- // A structural profile represents the whole source root. Never append
165
- // an --all fallback that could derive a second Default DSL identity.
166
- ...(structural.length === 0 && (ordinary.length > 0 || opts.all)
167
- ? [{ plugins: opts.all ? undefined : ordinary }]
168
- : []),
169
- ];
170
- const installed = [];
171
- const available = new Set();
172
245
  const checkout = mkdtempSync(join(tmpdir(), "adg-marketplace-update-"));
173
246
  try {
174
247
  const parsed = parseGitHubSource(group.source);
@@ -176,67 +249,46 @@ export async function updatePlugins(opts) {
176
249
  const mat = await materializeSource({ ...parsed, ref: group.ref }, checkout, {
177
250
  runner: opts.gitRunner,
178
251
  resolvedRevision: remoteRevision,
252
+ // A complete source catalog is required to distinguish relocation
253
+ // from deletion, including siblings outside an earlier sparse add.
179
254
  });
180
255
  const resolvedRevision = mat.resolvedRevision ?? gitRevision(checkout);
181
- let requestIndex = 0;
182
- for (const request of requests) {
183
- opts.onProgress?.({
184
- kind: "install",
185
- index: ++requestIndex,
186
- total: requests.length,
187
- source: group.source,
188
- ...(request.structuralIdentity ? { plugin: request.structuralIdentity } : {}),
189
- });
190
- const result = await addPlugins({
191
- spec: group.source,
192
- pluginsDir: opts.pluginsDir,
193
- ref: group.ref,
194
- ...(opts.all && request.plugins === undefined ? { all: true } : { plugins: request.plugins }),
195
- missingPlugins: "skip",
196
- skipUnchanged: true,
197
- nonInteractive: true,
198
- ...(request.authorizedComponents ? { authorizedComponents: request.authorizedComponents } : {}),
199
- ...(request.structuralIdentity ? { structuralIdentity: request.structuralIdentity } : {}),
200
- ...(request.replaySelection ? { replaySelection: request.replaySelection } : {}),
201
- targets: opts.targets,
202
- marketplaceName: group.source,
203
- gitRunner: opts.gitRunner,
204
- ...(request.as ? { as: request.as } : {}),
205
- ...(request.defaultDescription ? { defaultDescription: request.defaultDescription } : {}),
206
- activate: opts.activate,
207
- scope: opts.agentScope,
208
- agents: updateAgents,
209
- deactivationAgents: removalAgents,
210
- now,
211
- preparedSourceDir: checkout,
212
- preparedResolvedRevision: resolvedRevision,
213
- ...(opts.cwd ? { cwd: opts.cwd } : {}),
214
- ...(opts.onProgress ? { onProgress: opts.onProgress } : {}),
215
- });
216
- installed.push(...result.installed);
217
- result.available.forEach((name) => available.add(name));
218
- if (result.agents)
219
- remoteAgents.push(...result.agents);
220
- }
256
+ const result = await upgradeSource({
257
+ group, checkout, revision: resolvedRevision, pluginsDir: opts.pluginsDir,
258
+ all: opts.all, repair: opts.repair, activate: opts.activate, scope: repairScope, agents: opts.agents,
259
+ targets: opts.targets, now, review: opts.review, refreshExisting,
260
+ gitRunner: opts.gitRunner, onProgress: opts.onProgress,
261
+ onAgentResults: results => remoteAgents.push(...results),
262
+ onNativeManaged: rememberManagedNative,
263
+ });
264
+ remote.push(result);
265
+ if (result.deferredRecovery?.length)
266
+ recordTelemetryEvent("adg.plugins.update.recovery_deferred", {
267
+ "skills.count": result.deferredRecovery.length,
268
+ }, opts.telemetrySpan);
269
+ if (result.missingUpstream?.length)
270
+ recordTelemetryEvent("adg.plugins.update.missing_upstream", {
271
+ "plugins.retained": result.missingUpstream.length,
272
+ "update.include_new": Boolean(opts.all),
273
+ }, opts.telemetrySpan);
274
+ else
275
+ recordTelemetryEvent("adg.plugins.update.migration", {
276
+ "migration.count": result.migrated?.length ?? 0,
277
+ "action_required.count": result.actionRequired?.length ?? 0,
278
+ "pending.count": result.pendingRuntime?.length ?? 0,
279
+ "plugins.retained": result.missingUpstream?.length ?? 0,
280
+ }, opts.telemetrySpan);
221
281
  }
222
282
  finally {
223
283
  rmSync(checkout, { recursive: true, force: true });
224
284
  }
225
- const availableSet = available;
226
- const installedNow = new Set(installed.map((r) => r.name));
227
- remote.push({
228
- source: group.source,
229
- ...(group.ref ? { ref: group.ref } : {}),
230
- updated: installed.filter((r) => r.changed).map((r) => r.name).sort(),
231
- unchanged: installed.filter((r) => !r.changed).map((r) => r.name).sort(),
232
- deleted: group.installed.filter((n) => !availableSet.has(n)).sort(),
233
- available: [...available].filter((n) => !installedNow.has(n) && !group.installed.includes(n)).sort(),
234
- changes: installed.filter((r) => r.changes).map((r) => ({
235
- name: r.name, ...r.changes, runtimeRefreshRequired: r.runtimeRefreshRequired ?? r.changed,
236
- })).sort((a, b) => a.name.localeCompare(b.name)),
237
- });
238
285
  }
239
286
  catch (err) {
287
+ if (err instanceof UpdateCancelled) {
288
+ err.partial = { remote: [...remote, ...(err.partial?.remote ?? [])], local: { results: [], missing: [] },
289
+ agents: [...remoteAgents, ...(err.partial?.agents ?? [])] };
290
+ throw err;
291
+ }
240
292
  remote.push({
241
293
  source: group.source,
242
294
  ...(group.ref ? { ref: group.ref } : {}),
@@ -261,18 +313,16 @@ export async function updatePlugins(opts) {
261
313
  ...(opts.onProgress ? { onProgress: opts.onProgress } : {}),
262
314
  })
263
315
  : { results: [], missing: [] };
264
- const repairNames = [...new Set([...remoteGroups.flatMap((group) => group.installed), ...remote.flatMap((source) => [...source.updated, ...source.unchanged]), ...localNames])];
316
+ const repairNames = [...new Set([...selectedGroups.flatMap((group) => group.installed), ...remote.flatMap((source) => [...source.updated, ...source.unchanged]), ...localNames])].filter(name => !managedByMigration.has(name));
265
317
  const currentLock = readLock(lockPath(opts.pluginsDir));
266
- const repairs = opts.repair ? [repairCodex({
267
- pluginsDir: opts.pluginsDir,
268
- plugins: repairNames.filter((name) => currentLock.plugins[name]),
269
- scope: opts.agentScope ?? "project",
318
+ const repairs = opts.activate && opts.repair && repairNames.length ? [repairCodex({
319
+ pluginsDir: opts.pluginsDir, plugins: repairNames.filter(name => currentLock.plugins[name]), scope: repairScope,
270
320
  }, false, repairAgent, {
271
321
  initial, observed: true,
272
- changed: [...remote.flatMap((source) => source.changes
273
- ? source.changes.filter((plugin) => plugin.runtimeRefreshRequired).map((plugin) => plugin.name)
274
- : source.updated), ...local.results.filter((plugin) => plugin.runtimeRefreshRequired ?? plugin.changed).map((plugin) => plugin.name)],
275
- removed: repairNames.filter((name) => !currentLock.plugins[name]),
322
+ changed: [...remote.flatMap(source => source.changes
323
+ ? source.changes.filter(plugin => plugin.runtimeRefreshRequired).map(plugin => plugin.name)
324
+ : source.updated), ...local.results.filter(plugin => plugin.runtimeRefreshRequired ?? plugin.changed).map(plugin => plugin.name)],
325
+ removed: repairNames.filter(name => !currentLock.plugins[name]),
276
326
  })] : [];
277
327
  const agents = mergeAgentResults([remoteAgents, local.agents ?? [], repairs]);
278
328
  return { remote, local, agents };
@@ -291,6 +341,12 @@ export function marketplaceRemove(opts) {
291
341
  });
292
342
  removed.push(name);
293
343
  }
344
+ const file = lockPath(opts.pluginsDir);
345
+ const lock = readLock(file);
346
+ if (lock.sources?.some(intent => intent.source === opts.source)) {
347
+ lock.sources = lock.sources.filter(intent => intent.source !== opts.source);
348
+ writeLock(file, lock);
349
+ }
294
350
  return { source: opts.source, removed };
295
351
  }
296
352
  /**
@@ -73,9 +73,9 @@ function migrateLock(pluginsDir, telemetrySpan) {
73
73
  if (raw.version === LOCK_VERSION)
74
74
  return false;
75
75
  if (typeof raw?.version === "number") {
76
- recordTelemetryEvent("adg.lock.read", { "format.version": raw.version === 2 || raw.version === 3 || raw.version === 4 ? raw.version : -1 }, telemetrySpan);
76
+ recordTelemetryEvent("adg.lock.read", { "format.version": raw.version === 2 || raw.version === 3 || raw.version === 4 || raw.version === 5 ? raw.version : -1 }, telemetrySpan);
77
77
  }
78
- if ((raw.version === 3 || raw.version === 4) && typeof raw.plugins === "object" && raw.plugins !== null) {
78
+ if ([3, 4, 5].includes(raw.version) && typeof raw.plugins === "object" && raw.plugins !== null) {
79
79
  // v3 has the same payload model; v4 adds optional immutable provenance.
80
80
  // Existing remote entries remain explicitly legacy until an update/add
81
81
  // resolves their commit, rather than inventing a moving ref as a revision.