@rbbtsn0w/adg 0.11.4 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +31 -12
  2. package/dist/src/agents/antigravity.js +218 -45
  3. package/dist/src/agents/claude.js +98 -38
  4. package/dist/src/agents/codex.js +1 -0
  5. package/dist/src/cli/core-plugin-handlers.js +3 -3
  6. package/dist/src/cli/handlers.js +160 -36
  7. package/dist/src/cli/index.js +19 -12
  8. package/dist/src/cli/review-update.js +80 -0
  9. package/dist/src/commands/install/default-dsl.js +1 -1
  10. package/dist/src/commands/install/install-one.js +41 -31
  11. package/dist/src/commands/install.js +38 -23
  12. package/dist/src/commands/marketplace.js +136 -109
  13. package/dist/src/commands/migrate.js +2 -2
  14. package/dist/src/commands/projection.js +3 -1
  15. package/dist/src/commands/remove.js +10 -0
  16. package/dist/src/commands/review-executables.js +106 -0
  17. package/dist/src/commands/select-agents.js +2 -2
  18. package/dist/src/commands/select-components.js +2 -2
  19. package/dist/src/commands/select-plugins.js +15 -2
  20. package/dist/src/commands/select-scope.js +3 -4
  21. package/dist/src/commands/source-upgrade.js +552 -0
  22. package/dist/src/commands/state.js +3 -1
  23. package/dist/src/commands/update.js +3 -1
  24. package/dist/src/lock.js +13 -5
  25. package/dist/src/migration-transaction.js +1011 -0
  26. package/dist/src/native-retry.js +329 -0
  27. package/dist/src/process-identity.js +65 -0
  28. package/dist/src/render/plugins.js +115 -9
  29. package/dist/src/source-history.js +194 -0
  30. package/dist/src/source-intent.js +7 -0
  31. package/dist/src/store-mutex.js +179 -0
  32. package/dist/src/types.js +1 -1
  33. package/dist/src/update-executables.js +193 -0
  34. package/dist/src/upgrade-plan.js +378 -0
  35. package/docs/agents/antigravity.md +5 -0
  36. package/docs/agents-spec.md +10 -0
  37. package/docs/branching-and-release.md +53 -0
  38. package/docs/plugin-update-semantics.md +30 -34
  39. package/docs/plugin-upgrade-migrations.md +349 -0
  40. package/package.json +4 -3
  41. package/schemas/plugin-lock.schema.json +78 -1
@@ -0,0 +1,1011 @@
1
+ import { chmodSync, closeSync, cpSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, symlinkSync, writeFileSync, } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
5
+ import { LOCK_VERSION, resolveSelectionDependencies } from "./types.js";
6
+ import { readLock } from "./lock.js";
7
+ import { readMarketplace, removeMarketplacePlugin, upsertMarketplacePlugin } from "./marketplace.js";
8
+ import { installedPluginDir, lockPath, marketplacePath, marketplaceSourcePath, pluginDir, pluginSourceCacheDir, } from "./paths.js";
9
+ import { ADAPTER_TARGETS } from "./adapters/index.js";
10
+ import { adaptPlugin } from "./commands/adapt.js";
11
+ import { readManifest } from "./manifest.js";
12
+ import { folderHash } from "./hash.js";
13
+ import { recordTelemetryEvent } from "./telemetry.js";
14
+ import { withStoreMutex } from "./store-mutex.js";
15
+ function syncPath(path) {
16
+ const stat = lstatSync(path);
17
+ if (stat.isDirectory()) {
18
+ if (process.platform === "win32")
19
+ return;
20
+ const fd = openSync(path, "r");
21
+ try {
22
+ fsyncSync(fd);
23
+ }
24
+ finally {
25
+ closeSync(fd);
26
+ }
27
+ return;
28
+ }
29
+ let restoreMode;
30
+ let fd;
31
+ try {
32
+ // Windows FlushFileBuffers needs GENERIC_WRITE. Only owned snapshots and
33
+ // published files reach this helper; source files are never chmodded.
34
+ if (process.platform === "win32" && !(stat.mode & 0o200)) {
35
+ restoreMode = stat.mode & 0o777;
36
+ chmodSync(path, restoreMode | 0o200);
37
+ }
38
+ fd = openSync(path, process.platform === "win32" ? "r+" : "r");
39
+ if (restoreMode !== undefined) {
40
+ chmodSync(path, restoreMode);
41
+ restoreMode = undefined;
42
+ }
43
+ fsyncSync(fd);
44
+ }
45
+ finally {
46
+ try {
47
+ if (restoreMode !== undefined)
48
+ chmodSync(path, restoreMode);
49
+ }
50
+ finally {
51
+ if (fd !== undefined)
52
+ closeSync(fd);
53
+ }
54
+ }
55
+ }
56
+ function syncTree(path) {
57
+ const stat = lstatSync(path);
58
+ if (stat.isSymbolicLink())
59
+ return;
60
+ if (stat.isDirectory()) {
61
+ for (const name of readdirSync(path))
62
+ syncTree(join(path, name));
63
+ }
64
+ syncPath(path);
65
+ }
66
+ /** Rename within the destination filesystem, retaining durable recovery inputs. */
67
+ function atomicJson(file, value) {
68
+ mkdirSync(dirname(file), { recursive: true });
69
+ const temp = `${file}.${randomUUID()}.tmp`;
70
+ const fd = openSync(temp, "wx", 0o600);
71
+ try {
72
+ writeFileSync(fd, JSON.stringify(value, null, 2) + "\n");
73
+ fsyncSync(fd);
74
+ }
75
+ finally {
76
+ closeSync(fd);
77
+ }
78
+ renameSync(temp, file);
79
+ syncPath(dirname(file));
80
+ }
81
+ function privateRoot() {
82
+ return resolve(process.env.ADG_MIGRATION_HOME || join(process.env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "adg", "migrations"));
83
+ }
84
+ function canonicalStore(pluginsDir) {
85
+ return existsSync(pluginsDir) ? realpathSync(pluginsDir) : resolve(pluginsDir);
86
+ }
87
+ function rootFor(pluginsDir) {
88
+ const identity = createHash("sha256").update(canonicalStore(pluginsDir)).digest("hex");
89
+ return join(privateRoot(), identity);
90
+ }
91
+ function assertPrivateDirectory(path) {
92
+ const stat = lstatSync(path);
93
+ if (stat.isSymbolicLink() || !stat.isDirectory()
94
+ || (process.getuid && stat.uid !== process.getuid()) || (process.platform !== "win32" && (stat.mode & 0o077) !== 0)) {
95
+ throw new Error("Migration state directory must be private and owned by the current user.");
96
+ }
97
+ }
98
+ function assertName(name) {
99
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name))
100
+ throw new Error("Invalid migration plugin identity");
101
+ }
102
+ function safeDestination(pluginsDir, name, entry) {
103
+ assertName(name);
104
+ const dest = resolve(pluginDir(pluginsDir, name, entry.origin));
105
+ const rel = relative(pluginsDir, dest);
106
+ if (!rel || rel.startsWith("..") || isAbsolute(rel))
107
+ throw new Error("Migration destination escapes the store");
108
+ let cursor = dirname(dest);
109
+ while (cursor !== pluginsDir) {
110
+ if (existsSync(cursor) && lstatSync(cursor).isSymbolicLink()) {
111
+ throw new Error("Migration destination crosses a symbolic link");
112
+ }
113
+ cursor = dirname(cursor);
114
+ }
115
+ return dest;
116
+ }
117
+ function assertSourceOwner(source, ref, entry) {
118
+ const origin = entry.origin;
119
+ const key = origin.type === "local" ? "(local)" : origin.type === "github" ? origin.repo : origin.url;
120
+ const same = origin.type === "github" ? key.toLowerCase() === source.toLowerCase() : key === source;
121
+ const originRef = origin.type === "local" ? undefined : origin.ref;
122
+ if (!same || originRef !== ref)
123
+ throw new Error("Migration source/ref does not own a replaced or retired plugin");
124
+ }
125
+ function validateTargetDecisions(value, allowed) {
126
+ if (value === undefined)
127
+ return;
128
+ if (!value || typeof value !== "object" || Array.isArray(value)
129
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value))) {
130
+ throw new Error("Successor enabledByTarget must be a plain boolean record");
131
+ }
132
+ for (const [target, enabled] of Object.entries(value)) {
133
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(target) || ["__proto__", "constructor", "prototype"].includes(target)
134
+ || typeof enabled !== "boolean" || (allowed && !allowed.has(target))) {
135
+ throw new Error("Invalid or unauthorized successor target state decision");
136
+ }
137
+ }
138
+ }
139
+ function explicitTargetDecision(op, agent) {
140
+ return op.successor?.enabledByTarget && Object.hasOwn(op.successor.enabledByTarget, agent)
141
+ ? op.successor.enabledByTarget[agent] : undefined;
142
+ }
143
+ function existingProjectionTargets(dir) {
144
+ return ADAPTER_TARGETS.filter((target) => existsSync(join(dir, target === "antigravity" ? "plugin.json" : `.${target}-plugin/plugin.json`)));
145
+ }
146
+ function namespaceAliases(store) {
147
+ const aliases = [];
148
+ let cursor = parse(store).root;
149
+ for (const part of relative(cursor, store).split(sep).filter(Boolean)) {
150
+ cursor = join(cursor, part);
151
+ if (!lstatSync(cursor).isSymbolicLink())
152
+ continue;
153
+ const parent = realpathSync(dirname(cursor));
154
+ const stat = lstatSync(parent);
155
+ aliases.push({ path: cursor, target: realpathSync(cursor), parent, parentDev: stat.dev, parentIno: stat.ino });
156
+ }
157
+ return aliases;
158
+ }
159
+ function missingNamespaceAlias(journal) {
160
+ const store = journal.cacheStore;
161
+ if (!store || store === journal.pluginsDir)
162
+ return undefined;
163
+ if (!isAbsolute(store))
164
+ throw new Error("Migration cache store identity mismatch");
165
+ let cursor = parse(store).root;
166
+ for (const part of relative(cursor, store).split(sep).filter(Boolean)) {
167
+ cursor = join(cursor, part);
168
+ try {
169
+ lstatSync(cursor);
170
+ }
171
+ catch (error) {
172
+ if (error.code !== "ENOENT")
173
+ throw error;
174
+ let alias = journal.namespaceAliases?.find(item => item.path === cursor);
175
+ // Older receipts did not record alias topology. A direct alias beside the
176
+ // canonical store is still confined to that same, existing parent.
177
+ if (!alias && !journal.namespaceAliases && cursor === store
178
+ && realpathSync(dirname(store)) === realpathSync(dirname(journal.pluginsDir))) {
179
+ const parent = realpathSync(dirname(store));
180
+ const stat = lstatSync(parent);
181
+ alias = { path: store, target: journal.pluginsDir, parent, parentDev: stat.dev, parentIno: stat.ino };
182
+ }
183
+ if (!alias || !isAbsolute(alias.target) || !isAbsolute(alias.parent)
184
+ || realpathSync(dirname(cursor)) !== alias.parent
185
+ || canonicalStore(resolve(alias.target, relative(cursor, store))) !== journal.pluginsDir) {
186
+ throw new Error("Migration cache store identity mismatch; restore its original directory alias before retrying");
187
+ }
188
+ const parent = lstatSync(alias.parent);
189
+ if (!parent.isDirectory() || parent.isSymbolicLink() || parent.dev !== alias.parentDev || parent.ino !== alias.parentIno) {
190
+ throw new Error("Migration cache store parent identity mismatch");
191
+ }
192
+ return alias;
193
+ }
194
+ }
195
+ if (realpathSync(store) !== journal.pluginsDir)
196
+ throw new Error("Migration cache store identity mismatch");
197
+ return undefined;
198
+ }
199
+ function restoreNamespaceAlias(journal) {
200
+ const alias = missingNamespaceAlias(journal);
201
+ if (!alias)
202
+ return;
203
+ // symlinkSync refuses an existing slot, including a concurrently planted
204
+ // foreign link. Never create missing ancestors or change the native namespace.
205
+ symlinkSync(alias.target, alias.path, process.platform === "win32" ? "junction" : "dir");
206
+ syncPath(dirname(alias.path));
207
+ if (missingNamespaceAlias(journal))
208
+ throw new Error("Migration cache store identity mismatch");
209
+ }
210
+ function load(path) {
211
+ const resolved = resolve(path);
212
+ const base = privateRoot();
213
+ const rel = relative(base, resolved);
214
+ if (rel.startsWith("..") || isAbsolute(rel) || rel.split(sep).length !== 3 || basename(resolved) !== "journal.json") {
215
+ throw new Error("Untrusted migration journal path");
216
+ }
217
+ assertPrivateDirectory(base);
218
+ assertPrivateDirectory(dirname(dirname(resolved)));
219
+ assertPrivateDirectory(dirname(resolved));
220
+ if (lstatSync(resolved).isSymbolicLink())
221
+ throw new Error("Untrusted migration journal");
222
+ const journal = JSON.parse(readFileSync(resolved, "utf8"));
223
+ if (journal.version !== 1 || journal.pluginsDir !== canonicalStore(journal.pluginsDir)
224
+ || dirname(dirname(resolved)) !== rootFor(journal.pluginsDir)) {
225
+ throw new Error("Migration store identity mismatch");
226
+ }
227
+ if (journal.cacheStore && !isAbsolute(journal.cacheStore))
228
+ throw new Error("Migration cache store identity mismatch");
229
+ if (!journal.complete)
230
+ missingNamespaceAlias(journal);
231
+ for (const p of journal.prepared) {
232
+ assertSourceOwner(journal.source, journal.ref, p.entry);
233
+ if (p.dest !== safeDestination(journal.pluginsDir, p.name, p.entry))
234
+ throw new Error("Migration destination mismatch");
235
+ }
236
+ for (const name of journal.retire) {
237
+ assertName(name);
238
+ const entry = journal.before.plugins[name];
239
+ if (entry) {
240
+ assertSourceOwner(journal.source, journal.ref, entry);
241
+ safeDestination(journal.pluginsDir, name, entry);
242
+ }
243
+ }
244
+ for (const request of journal.refreshExisting ?? []) {
245
+ assertName(request.name);
246
+ const entry = journal.before.plugins[request.name];
247
+ if (!entry || journal.retire.includes(request.name))
248
+ throw new Error("Invalid surviving native repair identity");
249
+ assertSourceOwner(journal.source, journal.ref, entry);
250
+ }
251
+ for (const successor of journal.successors ?? []) {
252
+ assertName(successor.name);
253
+ validateTargetDecisions(successor.enabledByTarget);
254
+ const entry = journal.prepared.find((p) => p.name === successor.name)?.entry ?? journal.before.plugins[successor.name];
255
+ if (!entry || journal.retire.includes(successor.name))
256
+ throw new Error("Invalid required successor");
257
+ assertSourceOwner(journal.source, journal.ref, entry);
258
+ for (const name of successor.predecessors) {
259
+ assertName(name);
260
+ if (!journal.before.plugins[name])
261
+ throw new Error("Invalid successor predecessor");
262
+ assertSourceOwner(journal.source, journal.ref, journal.before.plugins[name]);
263
+ }
264
+ }
265
+ for (const op of journal.operations)
266
+ validateTargetDecisions(op.successor?.enabledByTarget);
267
+ return journal;
268
+ }
269
+ export function discoverPendingMigrations(pluginsDir) {
270
+ const root = rootFor(pluginsDir);
271
+ if (!existsSync(root))
272
+ return [];
273
+ return readdirSync(root).flatMap((id) => {
274
+ const journalPath = join(root, id, "journal.json");
275
+ if (!existsSync(journalPath))
276
+ return [];
277
+ const journal = load(journalPath);
278
+ if (journal.complete) {
279
+ // Leave a receipt for callers replaying the completed transaction. Only
280
+ // retry filesystem cleanup if publication was interrupted after commit.
281
+ if (readdirSync(dirname(journalPath)).some(name => name !== "journal.json"))
282
+ cleanupArtifacts(dirname(journalPath));
283
+ return [];
284
+ }
285
+ return [{ journalPath, source: journal.source, ...(journal.ref ? { ref: journal.ref } : {}) }];
286
+ });
287
+ }
288
+ /** Prepare all durable inputs before touching the live lock or native targets. */
289
+ export async function prepareMigrationTransaction(options) {
290
+ return await withStoreMutex(options.pluginsDir, () => {
291
+ mkdirSync(options.pluginsDir, { recursive: true });
292
+ const pluginsDir = canonicalStore(options.pluginsDir);
293
+ const nativePluginsDir = resolve(options.pluginsDir);
294
+ if (!options.revision)
295
+ throw new Error("Migration requires a fixed revision.");
296
+ const names = new Set();
297
+ for (const p of options.prepared) {
298
+ assertName(p.name);
299
+ if (names.has(p.name))
300
+ throw new Error("Duplicate migration plugin name.");
301
+ names.add(p.name);
302
+ safeDestination(pluginsDir, p.name, p.entry);
303
+ }
304
+ for (const name of options.retire) {
305
+ assertName(name);
306
+ if (names.has(name))
307
+ throw new Error("Migration successor cannot also be retired.");
308
+ }
309
+ const touched = new Set([...names, ...options.retire, ...(options.successors ?? []).flatMap((item) => [item.name, ...item.predecessors]), ...(options.refreshExisting ?? []).map((request) => request.name)]);
310
+ const dependencies = new Set(options.prepared.flatMap((p) => Object.keys(p.entry.dependencies ?? {})));
311
+ for (const pending of discoverPendingMigrations(pluginsDir)) {
312
+ const peer = load(pending.journalPath);
313
+ const protectedNames = new Set([...peer.prepared.map((p) => p.name), ...peer.retire, ...(peer.successors ?? []).flatMap((item) => [item.name, ...item.predecessors]), ...(peer.refreshExisting ?? []).map((request) => request.name)]);
314
+ const peerDependencies = peer.prepared.flatMap((p) => Object.keys(p.entry.dependencies ?? {}));
315
+ if ((peer.source.toLowerCase() === options.source.toLowerCase() && peer.ref === options.ref)
316
+ || [...touched].some((name) => protectedNames.has(name))
317
+ || [...dependencies].some((name) => protectedNames.has(name))
318
+ || peerDependencies.some((name) => touched.has(name))) {
319
+ throw new Error("Resume the pending migration before modifying its source/ref, protected plugins, or dependencies.");
320
+ }
321
+ }
322
+ const before = readLock(lockPath(pluginsDir));
323
+ for (const [name, entry] of Object.entries(before.plugins)) {
324
+ if (!touched.has(name) && Object.keys(entry.dependencies ?? {}).some((dependency) => options.retire.includes(dependency))) {
325
+ throw new Error("Migration retirement would orphan a dependency of an unchanged plugin");
326
+ }
327
+ }
328
+ for (const p of options.prepared) {
329
+ assertSourceOwner(options.source, options.ref, p.entry);
330
+ if (before.plugins[p.name])
331
+ assertSourceOwner(options.source, options.ref, before.plugins[p.name]);
332
+ }
333
+ for (const name of options.retire)
334
+ if (before.plugins[name])
335
+ assertSourceOwner(options.source, options.ref, before.plugins[name]);
336
+ for (const request of options.refreshExisting ?? []) {
337
+ assertName(request.name);
338
+ if (!before.plugins[request.name] || options.retire.includes(request.name))
339
+ throw new Error("Native repair must reference an existing surviving plugin");
340
+ assertSourceOwner(options.source, options.ref, before.plugins[request.name]);
341
+ }
342
+ const decisionTargets = new Set([...(options.targets ?? []), ...(options.retire.length ? options.retireTargets ?? [] : [])].map((target) => target.id));
343
+ for (const successor of options.successors ?? []) {
344
+ assertName(successor.name);
345
+ validateTargetDecisions(successor.enabledByTarget, decisionTargets);
346
+ const entry = options.prepared.find((p) => p.name === successor.name)?.entry ?? before.plugins[successor.name];
347
+ if (!entry || options.retire.includes(successor.name))
348
+ throw new Error("Required successor must survive the transaction");
349
+ assertSourceOwner(options.source, options.ref, entry);
350
+ for (const name of successor.predecessors) {
351
+ assertName(name);
352
+ if (!before.plugins[name])
353
+ throw new Error("Required successor has no installed predecessor");
354
+ assertSourceOwner(options.source, options.ref, before.plugins[name]);
355
+ }
356
+ }
357
+ if (options.sourceIntent && (options.sourceIntent.source !== options.source || options.sourceIntent.ref !== options.ref)) {
358
+ throw new Error("Migration source intent belongs to another source/ref");
359
+ }
360
+ const root = join(rootFor(pluginsDir), randomUUID());
361
+ mkdirSync(privateRoot(), { recursive: true, mode: 0o700 });
362
+ assertPrivateDirectory(privateRoot());
363
+ mkdirSync(rootFor(pluginsDir), { recursive: true, mode: 0o700 });
364
+ assertPrivateDirectory(rootFor(pluginsDir));
365
+ mkdirSync(root, { mode: 0o700 });
366
+ try {
367
+ const operations = [];
368
+ const targets = (options.targets ?? []).filter((target) => target.detect());
369
+ const retirementTargets = options.retire.length ? [...new Map([...targets, ...(options.retireTargets ?? []).filter((target) => target.detect())].map((target) => [target.id, target])).values()] : targets;
370
+ // Persisted ownership survives a missing provider in this invocation.
371
+ const retirementTargetIds = new Set([
372
+ ...retirementTargets.map(target => target.id),
373
+ ...options.retire.flatMap(name => Object.keys(before.plugins[name]?.runtimeStates ?? {})),
374
+ ]);
375
+ const successorNames = new Set((options.successors ?? []).map((item) => item.name));
376
+ const prepared = options.prepared.map((p, index) => {
377
+ const dir = join(root, "payload", String(index));
378
+ mkdirSync(dirname(dir), { recursive: true });
379
+ cpSync(p.dir, dir, { recursive: true, dereference: false });
380
+ const manifest = readManifest(dir);
381
+ if (manifest.name !== p.name)
382
+ throw new Error("Prepared migration plugin identity does not match its manifest");
383
+ const dest = safeDestination(pluginsDir, p.name, p.entry);
384
+ // Generated files must refer to their eventual live location, even offline.
385
+ const projectionTargets = options.projectionTargets ?? [...new Set([
386
+ ...existingProjectionTargets(dir), ...(options.targets ?? []).map((t) => t.adaptTarget),
387
+ ])];
388
+ adaptPlugin(dir, projectionTargets, resolveSelectionDependencies(manifest, p.entry.selection), dest);
389
+ syncTree(dir);
390
+ let cacheHash;
391
+ if (p.cacheDir) {
392
+ const cache = join(root, "cache", String(index));
393
+ mkdirSync(dirname(cache), { recursive: true });
394
+ cpSync(p.cacheDir, cache, { recursive: true, dereference: false });
395
+ syncTree(cache);
396
+ cacheHash = folderHash(cache);
397
+ }
398
+ const previousRuntime = before.plugins[p.name]?.runtimeStates;
399
+ const entry = { ...p.entry,
400
+ ...(previousRuntime || p.entry.runtimeStates ? { runtimeStates: { ...previousRuntime, ...p.entry.runtimeStates } } : {}) };
401
+ for (const target of p.runtimeRefreshRequired === false || successorNames.has(p.name) ? [] : targets) {
402
+ const observed = target.available()
403
+ ? target.inspectPlugins?.({ pluginsDir: nativePluginsDir, plugins: [p.name], scope: options.scope }) : undefined;
404
+ const native = Array.isArray(observed) ? observed.find((r) => r.name === p.name && r.installed) : undefined;
405
+ if (entry.state === "disabled") {
406
+ if (native?.enabled || (!Array.isArray(observed) && before.plugins[p.name])) {
407
+ operations.push({ agent: target.id, plugin: p.name, kind: "disable", desiredEnabled: false, done: false });
408
+ }
409
+ else
410
+ operations.push({ agent: target.id, plugin: p.name, kind: "disable", desiredEnabled: false, done: true });
411
+ continue;
412
+ }
413
+ if ((native && !native.enabled) || (!native && entry.runtimeStates?.[target.id] === false)) {
414
+ operations.push({ agent: target.id, plugin: p.name, kind: "disable", desiredEnabled: false, done: true });
415
+ continue;
416
+ }
417
+ operations.push({ agent: target.id, plugin: p.name, kind: before.plugins[p.name] ? "refresh" : "activate", desiredEnabled: true, done: false });
418
+ }
419
+ return { name: p.name, entry, cache: !!p.cacheDir, dest, payloadHash: folderHash(dir), cacheHash, category: manifest.category, runtimeRefreshRequired: p.runtimeRefreshRequired !== false };
420
+ });
421
+ for (const request of options.refreshExisting ?? []) {
422
+ const target = targets.find((agent) => agent.id === request.target);
423
+ const entry = before.plugins[request.name];
424
+ if (!target || successorNames.has(request.name) || entry.state === "disabled" || operations.some((op) => op.agent === target.id && op.plugin === request.name))
425
+ continue;
426
+ const inspected = target.available() ? target.inspectPlugins?.({ pluginsDir: nativePluginsDir, plugins: [request.name], scope: options.scope }) : undefined;
427
+ const native = Array.isArray(inspected) ? inspected.find((record) => record.name === request.name && record.installed) : undefined;
428
+ if ((native && !native.enabled) || (!native && entry.runtimeStates?.[target.id] === false)) {
429
+ operations.push({ agent: target.id, plugin: request.name, kind: "disable", desiredEnabled: false, done: true });
430
+ continue;
431
+ }
432
+ operations.push({ agent: target.id, plugin: request.name, kind: "refresh", desiredEnabled: true, done: false });
433
+ }
434
+ for (const successor of options.successors ?? []) {
435
+ for (const targetId of retirementTargetIds) {
436
+ operations.push({ agent: targetId, plugin: successor.name, kind: "ensure", done: false,
437
+ successor: { predecessors: successor.predecessors, requiredTarget: targets.some((item) => item.id === targetId),
438
+ forceRefresh: options.prepared.some((p) => p.name === successor.name && p.runtimeRefreshRequired !== false),
439
+ ...(successor.enabledByTarget ? { enabledByTarget: { ...successor.enabledByTarget } } : {}) } });
440
+ }
441
+ }
442
+ for (const name of options.retire) {
443
+ if (before.plugins[name]) {
444
+ for (const targetId of retirementTargetIds)
445
+ operations.push({ agent: targetId, plugin: name, kind: "retire", done: false });
446
+ }
447
+ }
448
+ for (const op of operations)
449
+ if (options.inspectionRequiredTargets?.includes(op.agent))
450
+ op.inspectionRequired = true;
451
+ atomicJson(join(root, "before-lock.json"), before);
452
+ if (existsSync(marketplacePath(pluginsDir))) {
453
+ cpSync(marketplacePath(pluginsDir), join(root, "before-marketplace.json"));
454
+ syncPath(join(root, "before-marketplace.json"));
455
+ }
456
+ const journal = {
457
+ version: 1, pluginsDir, cacheStore: resolve(options.pluginsDir), namespaceAliases: namespaceAliases(resolve(options.pluginsDir)), source: options.source, ref: options.ref, revision: options.revision,
458
+ scope: options.scope, prepared, successors: options.successors ? structuredClone(options.successors) : undefined, refreshExisting: options.refreshExisting, retire: options.retire, sourceIntent: options.sourceIntent,
459
+ before, operations, published: false, complete: false,
460
+ };
461
+ const after = metadataFor(journal, true);
462
+ atomicJson(join(root, "after-lock.json"), after.lock);
463
+ atomicJson(join(root, "after-marketplace.json"), after.market);
464
+ const path = join(root, "journal.json");
465
+ atomicJson(path, journal);
466
+ syncPath(rootFor(pluginsDir));
467
+ syncPath(privateRoot());
468
+ recordTelemetryEvent("adg.migration.prepared", { "plugin.count": prepared.length, "target.count": targets.length });
469
+ return path;
470
+ }
471
+ catch (error) {
472
+ rmSync(root, { recursive: true, force: true });
473
+ throw error;
474
+ }
475
+ });
476
+ }
477
+ function metadataFor(journal, retire) {
478
+ const lock = readLock(lockPath(journal.pluginsDir));
479
+ const market = readMarketplace(marketplacePath(journal.pluginsDir), basename(journal.pluginsDir));
480
+ for (const p of journal.prepared) {
481
+ lock.plugins[p.name] = p.entry;
482
+ upsertMarketplacePlugin(market, {
483
+ name: p.name,
484
+ source: { source: "local", path: marketplaceSourcePath(journal.pluginsDir, p.dest) },
485
+ policy: { installation: "AVAILABLE", authentication: "ON_INSTALL" },
486
+ ...(p.category ? { category: p.category } : {}),
487
+ });
488
+ }
489
+ if (retire) {
490
+ for (const name of journal.retire) {
491
+ delete lock.plugins[name];
492
+ removeMarketplacePlugin(market, name);
493
+ }
494
+ if (lock.lastSelected)
495
+ lock.lastSelected = lock.lastSelected.filter((n) => !journal.retire.includes(n));
496
+ const intent = journal.sourceIntent;
497
+ if (intent) {
498
+ lock.sources = (lock.sources ?? []).filter((s) => s.source !== intent.source || s.ref !== intent.ref);
499
+ lock.sources.push(intent);
500
+ }
501
+ }
502
+ for (const op of journal.operations) {
503
+ const entry = lock.plugins[op.plugin];
504
+ if (entry && op.done && !op.notApplicable && op.kind !== "retire" && typeof op.desiredEnabled === "boolean") {
505
+ lock.plugins[op.plugin] = { ...entry, runtimeStates: { ...entry.runtimeStates, [op.agent]: op.desiredEnabled } };
506
+ }
507
+ }
508
+ return { lock, market };
509
+ }
510
+ function publishMetadata(journal, retire) {
511
+ const { lock, market } = metadataFor(journal, retire);
512
+ atomicJson(lockPath(journal.pluginsDir), lock);
513
+ atomicJson(marketplacePath(journal.pluginsDir), market);
514
+ }
515
+ /** Keep the caller's lexical namespace and canonical aliases coherent. */
516
+ function cacheStores(journal) {
517
+ return [...new Set([journal.cacheStore ?? journal.pluginsDir, journal.pluginsDir])];
518
+ }
519
+ function publishPayloads(journal, root) {
520
+ for (const [index, p] of journal.prepared.entries()) {
521
+ const staged = join(root, "payload", String(index));
522
+ if (folderHash(staged) !== p.payloadHash)
523
+ throw new Error("Migration payload integrity check failed");
524
+ if (p.cache && folderHash(join(root, "cache", String(index))) !== p.cacheHash) {
525
+ throw new Error("Migration source cache integrity check failed");
526
+ }
527
+ const swap = `${p.dest}.migration-${basename(root)}`;
528
+ mkdirSync(dirname(p.dest), { recursive: true });
529
+ rmSync(swap, { recursive: true, force: true });
530
+ cpSync(staged, swap, { recursive: true, dereference: false });
531
+ syncTree(swap);
532
+ if (existsSync(p.dest)) {
533
+ const backup = join(root, "previous", String(index));
534
+ mkdirSync(dirname(backup), { recursive: true });
535
+ // Keep the original payload when replaying a partially published store.
536
+ if (!existsSync(backup))
537
+ cpSync(p.dest, backup, { recursive: true, dereference: false });
538
+ syncTree(backup);
539
+ rmSync(p.dest, { recursive: true, force: true });
540
+ }
541
+ renameSync(swap, p.dest);
542
+ syncPath(dirname(p.dest));
543
+ if (p.cache)
544
+ for (const [cacheIndex, cacheStore] of cacheStores(journal).entries()) {
545
+ const cache = pluginSourceCacheDir(cacheStore, p.name);
546
+ mkdirSync(dirname(cache), { recursive: true });
547
+ const temp = `${cache}.migration-${basename(root)}`;
548
+ rmSync(temp, { recursive: true, force: true });
549
+ cpSync(join(root, "cache", String(index)), temp, { recursive: true, dereference: false });
550
+ syncTree(temp);
551
+ if (existsSync(cache)) {
552
+ const backup = join(root, "previous-cache", String(index), String(cacheIndex));
553
+ mkdirSync(dirname(backup), { recursive: true });
554
+ if (!existsSync(backup))
555
+ cpSync(cache, backup, { recursive: true, dereference: false });
556
+ syncTree(backup);
557
+ }
558
+ rmSync(cache, { recursive: true, force: true });
559
+ renameSync(temp, cache);
560
+ syncPath(dirname(cache));
561
+ }
562
+ }
563
+ }
564
+ function nativeStore(journal) {
565
+ return journal.cacheStore ?? journal.pluginsDir;
566
+ }
567
+ function proveInterruptedOperation(journal, op, agent) {
568
+ const details = agent.inspectPlugins?.({ pluginsDir: nativeStore(journal), plugins: [op.plugin], scope: journal.scope });
569
+ if (!Array.isArray(details))
570
+ return false;
571
+ if (op.kind === "retire" || op.kind === "disable")
572
+ return !details.some((p) => p.name === op.plugin && p.installed);
573
+ const desired = journal.prepared.find((p) => p.name === op.plugin)?.entry ?? journal.before.plugins[op.plugin];
574
+ const previous = journal.before.plugins[op.plugin];
575
+ return details.some((p) => p.name === op.plugin && p.installed && p.enabled && p.version === desired?.version)
576
+ && (op.kind !== "refresh" || previous?.version !== desired?.version);
577
+ }
578
+ function successorEntry(journal, name) {
579
+ return journal.prepared.find((p) => p.name === name)?.entry ?? journal.before.plugins[name];
580
+ }
581
+ class NativeStateDecisionRequired extends Error {
582
+ agent;
583
+ plugin;
584
+ constructor(agent, plugin) {
585
+ super(`Predecessors have mixed enabled/disabled state in ${agent}; choose the successor state before retiring them.`);
586
+ this.agent = agent;
587
+ this.plugin = plugin;
588
+ }
589
+ }
590
+ function applyStateDecisions(journal, decisions) {
591
+ const unique = new Map();
592
+ for (const decision of decisions) {
593
+ assertName(decision.plugin);
594
+ validateTargetDecisions({ [decision.agent]: decision.enabled });
595
+ const op = journal.operations.find((item) => item.agent === decision.agent && item.plugin === decision.plugin);
596
+ const successor = journal.successors?.find((item) => item.name === decision.plugin);
597
+ if (!op?.successor || op.kind !== "ensure" || op.done || !successor) {
598
+ throw new Error("Native state decision must address an existing pending successor target");
599
+ }
600
+ const key = `${decision.agent}\0${decision.plugin}`;
601
+ const previous = unique.get(key);
602
+ if (previous && previous.enabled !== decision.enabled)
603
+ throw new Error("Conflicting native successor state decisions");
604
+ unique.set(key, decision);
605
+ }
606
+ for (const decision of unique.values()) {
607
+ const op = journal.operations.find((item) => item.agent === decision.agent && item.plugin === decision.plugin);
608
+ const successor = journal.successors.find((item) => item.name === decision.plugin);
609
+ (op.successor.enabledByTarget ??= {})[decision.agent] = decision.enabled;
610
+ (successor.enabledByTarget ??= {})[decision.agent] = decision.enabled;
611
+ }
612
+ }
613
+ /** Determine per-target intent while every predecessor registration is retained. */
614
+ function resolveSuccessorOperation(journal, op, agent) {
615
+ const requirement = op.successor;
616
+ op.notApplicable = false;
617
+ const names = [...new Set([op.plugin, ...requirement.predecessors])];
618
+ const ctx = { pluginsDir: nativeStore(journal), plugins: names, scope: journal.scope };
619
+ const records = agent.inspectPlugins?.(ctx);
620
+ if (!Array.isArray(records))
621
+ throw new Error(`Cannot inspect successor/predecessor state in ${agent.id}; predecessor retirement remains pending.`);
622
+ const successor = records.find((item) => item.name === op.plugin && item.installed);
623
+ const predecessorStates = requirement.predecessors.flatMap((name) => {
624
+ const native = records.find((item) => item.name === name && item.installed);
625
+ if (native)
626
+ return [native.enabled];
627
+ // A disabled inherited successor may intentionally never have a native
628
+ // registration. Its saved per-runtime intent must survive another rename.
629
+ const previous = journal.before.plugins[name];
630
+ const saved = previous?.runtimeStates?.[agent.id];
631
+ if (typeof saved === "boolean")
632
+ return [saved];
633
+ return previous?.state === "disabled" ? [false] : [];
634
+ });
635
+ const desired = successorEntry(journal, op.plugin);
636
+ let enabled = desired.state !== "disabled";
637
+ const independentlyInstalled = Boolean(journal.before.plugins[op.plugin]) && Boolean(successor?.enabled)
638
+ && !requirement.predecessors.includes(op.plugin);
639
+ const explicit = explicitTargetDecision(op, agent.id);
640
+ if (explicit !== undefined)
641
+ enabled = explicit;
642
+ else if (successor && !successor.enabled)
643
+ enabled = false;
644
+ else if (independentlyInstalled)
645
+ enabled = desired.state !== "disabled";
646
+ else if (typeof desired.runtimeStates?.[agent.id] === "boolean")
647
+ enabled = enabled && desired.runtimeStates[agent.id];
648
+ else if (predecessorStates.length) {
649
+ if (predecessorStates.includes(true) && predecessorStates.includes(false)) {
650
+ throw new NativeStateDecisionRequired(agent.id, op.plugin);
651
+ }
652
+ enabled = enabled && predecessorStates.includes(true);
653
+ }
654
+ op.desiredEnabled = enabled;
655
+ if (explicit === undefined && !requirement.requiredTarget && !predecessorStates.length && !successor) {
656
+ op.notApplicable = true;
657
+ op.done = true;
658
+ return;
659
+ }
660
+ if (!enabled) {
661
+ if (!successor || !successor.enabled)
662
+ op.done = true;
663
+ else
664
+ op.kind = "disable";
665
+ return;
666
+ }
667
+ const stale = agent.needsProjectionRefresh?.({ ...ctx, plugins: [op.plugin] }).includes(op.plugin) ?? false;
668
+ if (successor?.enabled && successor.version === desired.version && !stale && !requirement.forceRefresh) {
669
+ op.done = true;
670
+ return;
671
+ }
672
+ op.kind = successor ? "refresh" : "activate";
673
+ }
674
+ function verifySuccessor(journal, op, agent) {
675
+ if (!op.successor || op.notApplicable)
676
+ return true;
677
+ const ctx = { pluginsDir: nativeStore(journal), plugins: [op.plugin], scope: journal.scope };
678
+ const records = agent.inspectPlugins?.(ctx);
679
+ if (!Array.isArray(records))
680
+ return false;
681
+ const native = records.find((item) => item.name === op.plugin && item.installed);
682
+ if (!op.desiredEnabled)
683
+ return !native || !native.enabled;
684
+ return !!native?.enabled && native.version === successorEntry(journal, op.plugin)?.version
685
+ && !(agent.needsProjectionRefresh?.(ctx).includes(op.plugin));
686
+ }
687
+ function mergeAgentReports(parts) {
688
+ return [...new Set(parts.map((part) => part.agent))].map((agent) => {
689
+ const items = parts.filter((part) => part.agent === agent);
690
+ const result = {
691
+ agent, affected: [...new Set(items.flatMap((part) => part.affected))], skipped: items.every((part) => part.skipped),
692
+ };
693
+ for (const field of ["verified", "unverified", "preservedDisabled"]) {
694
+ const values = [...new Set(items.flatMap((part) => part[field] ?? []))];
695
+ if (values.length)
696
+ result[field] = values;
697
+ }
698
+ const failures = items.flatMap((part) => part.failures ?? []);
699
+ if (failures.length)
700
+ result.failures = [...new Map(failures.map((failure) => [JSON.stringify(failure), failure])).values()];
701
+ return result;
702
+ });
703
+ }
704
+ function addRepairTargets(journal, options) {
705
+ let changed = false;
706
+ for (const id of new Set(options.repairTargets ?? [])) {
707
+ if (!options.targets?.some(agent => agent.id === id))
708
+ continue;
709
+ const covered = (name) => journal.operations.some(op => op.agent === id && op.plugin === name);
710
+ for (const p of journal.prepared) {
711
+ if (covered(p.name) || p.runtimeRefreshRequired === false || journal.successors?.some(item => item.name === p.name))
712
+ continue;
713
+ journal.operations.push({ agent: id, plugin: p.name, kind: p.entry.state === "disabled" ? "disable" : journal.before.plugins[p.name] ? "refresh" : "activate",
714
+ desiredEnabled: p.entry.state !== "disabled", inspectionRequired: true, done: false });
715
+ changed = true;
716
+ }
717
+ for (const successor of journal.successors ?? []) {
718
+ if (covered(successor.name))
719
+ continue;
720
+ journal.operations.push({ agent: id, plugin: successor.name, kind: "ensure", inspectionRequired: true, done: false,
721
+ successor: { predecessors: successor.predecessors, requiredTarget: true,
722
+ forceRefresh: journal.prepared.some(p => p.name === successor.name && p.runtimeRefreshRequired !== false),
723
+ ...(successor.enabledByTarget ? { enabledByTarget: { ...successor.enabledByTarget } } : {}) } });
724
+ changed = true;
725
+ }
726
+ for (const name of journal.retire) {
727
+ if (covered(name) || !journal.before.plugins[name])
728
+ continue;
729
+ journal.operations.push({ agent: id, plugin: name, kind: "retire", inspectionRequired: true, done: false });
730
+ changed = true;
731
+ }
732
+ }
733
+ if (changed)
734
+ journal.operations = [...journal.operations.filter(op => op.kind !== "retire"), ...journal.operations.filter(op => op.kind === "retire")];
735
+ return changed;
736
+ }
737
+ function cleanupArtifacts(root) {
738
+ for (const name of ["payload", "cache", "previous", "previous-cache", "before-lock.json", "before-marketplace.json", "after-lock.json", "after-marketplace.json"]) {
739
+ rmSync(join(root, name), { recursive: true, force: true });
740
+ }
741
+ syncPath(root);
742
+ }
743
+ /** Offline replay: never resolves a source or selects a newer revision. */
744
+ export async function publishMigrationTransaction(journalPath, options = {}) {
745
+ const initial = load(journalPath);
746
+ return await withStoreMutex(initial.pluginsDir, () => {
747
+ const journal = load(journalPath);
748
+ const root = dirname(journalPath);
749
+ if (!journal.complete && addRepairTargets(journal, options)) {
750
+ // Upgrade legacy obligations before any existing operation or the final
751
+ // checkpoint can complete; a process exit cannot erase requested repair.
752
+ atomicJson(journalPath, journal);
753
+ }
754
+ const failures = [];
755
+ const reports = [];
756
+ const stateDecisions = [];
757
+ const managedNative = [...new Set(journal.operations.map(op => op.agent))].map(agent => ({
758
+ agent, plugins: [...new Set(journal.operations.filter(op => op.agent === agent).map(op => op.plugin))],
759
+ }));
760
+ const record = (op, result) => {
761
+ const synchronizing = op.kind === "activate" || op.kind === "refresh";
762
+ reports.push({
763
+ agent: op.agent, skipped: result.skipped,
764
+ affected: synchronizing ? result.affected.filter((name) => name === op.plugin) : [],
765
+ ...(synchronizing && result.verified ? { verified: result.verified.filter((name) => name === op.plugin) } : {}),
766
+ ...(result.unverified ? { unverified: [...result.unverified] } : {}),
767
+ ...(result.failures ? { failures: result.failures.map((failure) => ({ ...failure })) } : {}),
768
+ ...((result.preservedDisabled?.includes(op.plugin) || (op.kind === "disable" && result.affected.includes(op.plugin)))
769
+ ? { preservedDisabled: [op.plugin] } : {}),
770
+ });
771
+ };
772
+ const confirmed = (op) => {
773
+ if (op.kind === "retire" || op.notApplicable)
774
+ return;
775
+ reports.push({ agent: op.agent, affected: [], skipped: false,
776
+ ...(op.desiredEnabled === false || op.kind === "disable" ? { preservedDisabled: [op.plugin] } : { verified: [op.plugin] }) });
777
+ };
778
+ const pending = (op, message, recordFailure = true, skipped = false) => {
779
+ failures.push({ message });
780
+ for (const report of reports.filter((part) => part.agent === op.agent)) {
781
+ report.affected = report.affected.filter((name) => name !== op.plugin);
782
+ for (const field of ["verified", "preservedDisabled"]) {
783
+ if (report[field])
784
+ report[field] = report[field].filter((name) => name !== op.plugin);
785
+ }
786
+ }
787
+ reports.push({ agent: op.agent, affected: [], skipped, unverified: [op.plugin],
788
+ ...(recordFailure ? { failures: [{ plugin: op.plugin, stage: "verify", errorType: "MIGRATION_NATIVE_PENDING", message }] } : {}) });
789
+ };
790
+ if (journal.complete) {
791
+ cleanupArtifacts(root);
792
+ return { complete: true, journalPath, failures, agents: [], stateDecisions: [], managedNative };
793
+ }
794
+ restoreNamespaceAlias(journal);
795
+ if (options.stateDecisions?.length) {
796
+ applyStateDecisions(journal, options.stateDecisions);
797
+ // Persist the user's choice before invoking any native lifecycle action.
798
+ atomicJson(journalPath, journal);
799
+ }
800
+ const live = readLock(lockPath(journal.pluginsDir));
801
+ for (const name of [...journal.prepared.map((p) => p.name), ...journal.retire, ...(journal.successors ?? []).flatMap((item) => [item.name, ...item.predecessors]), ...(journal.refreshExisting ?? []).map((request) => request.name)]) {
802
+ if (live.plugins[name])
803
+ assertSourceOwner(journal.source, journal.ref, live.plugins[name]);
804
+ }
805
+ if (!journal.published) {
806
+ // Fence older ADG versions before the first runtime-visible payload change.
807
+ atomicJson(lockPath(journal.pluginsDir), { ...live, version: LOCK_VERSION });
808
+ publishPayloads(journal, root);
809
+ publishMetadata(journal, false);
810
+ journal.published = true;
811
+ atomicJson(journalPath, journal);
812
+ }
813
+ for (const op of journal.operations) {
814
+ if (op.done)
815
+ continue;
816
+ if (op.kind === "retire" && journal.operations.some((o) => o.kind !== "retire" && !o.done))
817
+ break;
818
+ const agent = options.targets?.find((t) => t.id === op.agent);
819
+ if (!agent || !agent.available()) {
820
+ pending(op, `Required target ${op.agent} is unavailable; migration remains pending.`, true, true);
821
+ continue;
822
+ }
823
+ try {
824
+ const ctx = { pluginsDir: nativeStore(journal), plugins: [op.plugin], scope: journal.scope, preserveData: true,
825
+ ...(explicitTargetDecision(op, agent.id) === true ? { forceEnable: true } : {}) };
826
+ if (op.kind === "ensure") {
827
+ resolveSuccessorOperation(journal, op, agent);
828
+ atomicJson(journalPath, journal);
829
+ if (op.done) {
830
+ confirmed(op);
831
+ continue;
832
+ }
833
+ }
834
+ if (op.kind === "retire") {
835
+ const required = journal.operations.filter((item) => item.successor);
836
+ let ready = true;
837
+ for (const requirement of required) {
838
+ const provider = options.targets?.find((item) => item.id === requirement.agent);
839
+ if (!provider?.available() || !verifySuccessor(journal, requirement, provider)) {
840
+ requirement.done = false;
841
+ requirement.started = false;
842
+ requirement.kind = "ensure";
843
+ pending(requirement, `Successor ${requirement.plugin} is not confirmed in ${requirement.agent}; retirement remains pending.`);
844
+ ready = false;
845
+ }
846
+ }
847
+ if (!ready) {
848
+ atomicJson(journalPath, journal);
849
+ break;
850
+ }
851
+ const observed = agent.inspectPlugins?.(ctx);
852
+ if (Array.isArray(observed) && !observed.some((item) => item.name === op.plugin && item.installed)) {
853
+ op.done = true;
854
+ atomicJson(journalPath, journal);
855
+ continue;
856
+ }
857
+ }
858
+ if (op.inspectionRequired && !op.started) {
859
+ const observed = agent.inspectPlugins?.(ctx);
860
+ if (!Array.isArray(observed)) {
861
+ pending(op, `${op.agent} state cannot be inspected before repair; no native mutation was attempted.`);
862
+ continue;
863
+ }
864
+ const native = observed.find(item => item.name === op.plugin && item.installed);
865
+ const desired = successorEntry(journal, op.plugin);
866
+ if (op.kind === "disable" && !native) {
867
+ op.desiredEnabled = false;
868
+ op.done = true;
869
+ confirmed(op);
870
+ atomicJson(journalPath, journal);
871
+ continue;
872
+ }
873
+ if ((op.kind === "activate" || op.kind === "refresh")
874
+ && ((native && !native.enabled) || (!native && desired?.runtimeStates?.[agent.id] === false))
875
+ && explicitTargetDecision(op, agent.id) !== true) {
876
+ op.desiredEnabled = false;
877
+ op.done = true;
878
+ confirmed(op);
879
+ atomicJson(journalPath, journal);
880
+ continue;
881
+ }
882
+ if (op.kind === "refresh" && !native)
883
+ op.kind = "activate";
884
+ }
885
+ if (op.started) {
886
+ if (proveInterruptedOperation(journal, op, agent)) {
887
+ confirmed(op);
888
+ op.done = true;
889
+ atomicJson(journalPath, journal);
890
+ continue;
891
+ }
892
+ let native = agent.inspectPlugins?.(ctx);
893
+ if (!agent.inspectPlugins && !op.successor) {
894
+ const enabled = agent.listInstalled?.(ctx);
895
+ // The enabled-only contract proves a listed identity is enabled,
896
+ // but absence cannot prove uninstallation or rule out disablement.
897
+ if (Array.isArray(enabled) && enabled.includes(op.plugin)) {
898
+ native = enabled.map(name => ({ id: name, name, installed: true, enabled: true }));
899
+ }
900
+ }
901
+ if (Array.isArray(native) && native.some((p) => p.name === op.plugin && p.installed && !p.enabled)
902
+ && op.kind !== "retire" && op.kind !== "disable" && explicitTargetDecision(op, agent.id) !== true) {
903
+ op.desiredEnabled = false;
904
+ confirmed(op);
905
+ op.done = true;
906
+ atomicJson(journalPath, journal);
907
+ continue;
908
+ }
909
+ if (op.kind === "activate" && explicitTargetDecision(op, agent.id) === true
910
+ && Array.isArray(native) && native.some((item) => item.name === op.plugin && item.installed && !item.enabled)
911
+ && agent.retrySafeOperations?.includes("refresh")) {
912
+ // Installation may have committed before explicit enablement. Use
913
+ // the adapter's declared safe refresh instead of replaying activate.
914
+ op.kind = "refresh";
915
+ atomicJson(journalPath, journal);
916
+ }
917
+ const retryKind = op.kind === "retire" || op.kind === "disable" ? "deactivate" : op.kind === "ensure" ? "refresh" : op.kind;
918
+ if (retryKind !== "deactivate" && agent.retrySafeOperations?.includes(retryKind) && !Array.isArray(native)) {
919
+ pending(op, `${op.agent} could not inspect disabled state before retrying ${op.plugin}; repair native plugin listing and rerun the same ADG update.`);
920
+ continue;
921
+ }
922
+ if (!agent.retrySafeOperations?.includes(retryKind)) {
923
+ if ((op.kind === "activate" || op.kind === "refresh") && Array.isArray(native) && !native.some((p) => p.name === op.plugin && p.installed)) {
924
+ op.kind = "activate";
925
+ }
926
+ else {
927
+ const remediation = agent.inspectPlugins
928
+ ? `Remove this plugin from the ${op.agent} runtime using its native plugin manager (keep user data), then rerun the same ADG update; ADG will reinstall the durable prepared snapshot.`
929
+ : "This adapter must implement native readback or declare safe idempotent retry before ADG can resume; keep the pending journal and update the adapter, then rerun the same ADG update.";
930
+ pending(op, `${op.agent} ${op.kind} ${op.plugin} was interrupted; native state cannot prove completion. ${remediation}`);
931
+ continue;
932
+ }
933
+ }
934
+ op.started = false;
935
+ atomicJson(journalPath, journal);
936
+ }
937
+ op.started = true;
938
+ atomicJson(journalPath, journal);
939
+ const result = op.kind === "activate" ? agent.activate(ctx)
940
+ : op.kind === "refresh" ? agent.refresh(ctx) : agent.deactivate(ctx);
941
+ record(op, result);
942
+ if (result.preservedDisabled?.includes(op.plugin)) {
943
+ if (explicitTargetDecision(op, agent.id) === true) {
944
+ atomicJson(journalPath, journal);
945
+ pending(op, `${op.agent} preserved disabled state for ${op.plugin} despite the explicit enable decision; native enablement remains pending.`);
946
+ continue;
947
+ }
948
+ op.desiredEnabled = false;
949
+ op.done = true;
950
+ atomicJson(journalPath, journal);
951
+ continue;
952
+ }
953
+ if (result.skipped || result.failures?.length || !result.affected.includes(op.plugin)) {
954
+ if (result.skipped && !result.failures?.length)
955
+ op.started = false;
956
+ atomicJson(journalPath, journal);
957
+ pending(op, `${op.agent} ${op.kind} ${op.plugin}: ${result.failures?.map((f) => f.message).join("; ") || "operation not confirmed"}`, !result.failures?.length);
958
+ continue;
959
+ }
960
+ if (result.unverified?.includes(op.plugin)) {
961
+ pending(op, `${op.agent} did not verify ${op.plugin}`);
962
+ continue;
963
+ }
964
+ const installed = agent.listInstalled?.(ctx);
965
+ if (installed !== undefined && (!Array.isArray(installed)
966
+ || (op.kind === "retire" || op.kind === "disable" ? installed.includes(op.plugin) : !installed.includes(op.plugin)))) {
967
+ pending(op, `${op.agent} could not verify ${op.kind} ${op.plugin}`);
968
+ continue;
969
+ }
970
+ if (!verifySuccessor(journal, op, agent)) {
971
+ pending(op, `${op.agent} could not verify successor ${op.plugin}; retirement remains pending.`);
972
+ continue;
973
+ }
974
+ if ((op.kind === "activate" || op.kind === "refresh") && (Array.isArray(installed) || op.successor)) {
975
+ reports.push({ agent: op.agent, affected: [], verified: [op.plugin], skipped: false });
976
+ }
977
+ op.done = true;
978
+ atomicJson(journalPath, journal);
979
+ }
980
+ catch (error) {
981
+ if (error instanceof NativeStateDecisionRequired && !stateDecisions.some((item) => item.agent === error.agent && item.plugin === error.plugin)) {
982
+ stateDecisions.push({ agent: error.agent, plugin: error.plugin });
983
+ }
984
+ pending(op, `${op.agent} ${op.kind}: ${error instanceof Error ? error.message : String(error)}`);
985
+ }
986
+ }
987
+ if (journal.operations.every((op) => op.done)) {
988
+ publishMetadata(journal, true);
989
+ for (const name of journal.retire) {
990
+ const entry = journal.before.plugins[name];
991
+ if (entry) {
992
+ const path = installedPluginDir(journal.pluginsDir, name, entry.origin);
993
+ rmSync(path, { recursive: true, force: true });
994
+ if (existsSync(dirname(path)))
995
+ syncPath(dirname(path));
996
+ }
997
+ for (const store of cacheStores(journal)) {
998
+ const cache = pluginSourceCacheDir(store, name);
999
+ rmSync(cache, { recursive: true, force: true });
1000
+ if (existsSync(dirname(cache)))
1001
+ syncPath(dirname(cache));
1002
+ }
1003
+ }
1004
+ journal.complete = true;
1005
+ atomicJson(journalPath, journal);
1006
+ cleanupArtifacts(root);
1007
+ }
1008
+ recordTelemetryEvent("adg.migration.publish", { "migration.complete": journal.complete, "failure.count": failures.length });
1009
+ return { complete: journal.complete, journalPath, failures, agents: mergeAgentReports(reports), stateDecisions, managedNative };
1010
+ });
1011
+ }