@rbbtsn0w/adg 0.11.1-beta.1 → 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 (56) hide show
  1. package/README.md +131 -73
  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 +171 -39
  7. package/dist/src/cli/index.js +23 -14
  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/discovery.js +3 -1
  11. package/dist/src/commands/install/install-one.js +41 -31
  12. package/dist/src/commands/install.js +59 -24
  13. package/dist/src/commands/marketplace.js +171 -115
  14. package/dist/src/commands/migrate.js +2 -2
  15. package/dist/src/commands/projection.js +3 -1
  16. package/dist/src/commands/remove.js +10 -0
  17. package/dist/src/commands/review-executables.js +106 -0
  18. package/dist/src/commands/select-agents.js +2 -2
  19. package/dist/src/commands/select-components.js +2 -2
  20. package/dist/src/commands/select-plugins.js +15 -2
  21. package/dist/src/commands/select-scope.js +3 -4
  22. package/dist/src/commands/source-upgrade.js +552 -0
  23. package/dist/src/commands/state.js +3 -1
  24. package/dist/src/commands/update.js +3 -1
  25. package/dist/src/lock.js +13 -5
  26. package/dist/src/migration-transaction.js +1011 -0
  27. package/dist/src/native-retry.js +329 -0
  28. package/dist/src/process-identity.js +88 -0
  29. package/dist/src/render/plugins.js +149 -27
  30. package/dist/src/render/ui.js +4 -4
  31. package/dist/src/source-history.js +194 -0
  32. package/dist/src/source-intent.js +7 -0
  33. package/dist/src/store-mutex.js +179 -0
  34. package/dist/src/types.js +1 -1
  35. package/dist/src/update-executables.js +193 -0
  36. package/dist/src/upgrade-plan.js +378 -0
  37. package/docs/agents/antigravity.md +5 -0
  38. package/docs/agents-spec.md +10 -0
  39. package/docs/branching-and-release.md +369 -55
  40. package/docs/marketing/README.md +211 -0
  41. package/docs/marketing/assets.json +228 -0
  42. package/docs/marketing/capture.json +130 -0
  43. package/docs/marketing/live-readiness.json +353 -0
  44. package/docs/marketing/posts.en.md +94 -0
  45. package/docs/marketing/posts.zh-CN.md +67 -0
  46. package/docs/marketing/production.md +210 -0
  47. package/docs/marketing/source/timeline.json +29 -0
  48. package/docs/marketing/source/workflow-01.svg +16 -0
  49. package/docs/marketing/source/workflow-02.svg +14 -0
  50. package/docs/marketing/source/workflow-03.svg +19 -0
  51. package/docs/marketing/source/workflow-poster.svg +32 -0
  52. package/docs/marketing/transcript.md +48 -0
  53. package/docs/plugin-update-semantics.md +53 -10
  54. package/docs/plugin-upgrade-migrations.md +349 -0
  55. package/package.json +14 -10
  56. package/schemas/plugin-lock.schema.json +78 -1
@@ -0,0 +1,329 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { dirname, isAbsolute, join, resolve } from "node:path";
5
+ import { resolveAgents } from "./agents/index.js";
6
+ import { readLock, writeLock } from "./lock.js";
7
+ import { installedPluginDir, lockPath } from "./paths.js";
8
+ import { readManifest } from "./manifest.js";
9
+ import { folderHash } from "./hash.js";
10
+ import { effectivePackageFilter } from "./materialize.js";
11
+ import { PROJECTION_DIRS } from "./package.js";
12
+ import { pluginState, resolveSelectionDependencies } from "./types.js";
13
+ import { withStoreMutex } from "./store-mutex.js";
14
+ import { recordTelemetryEvent } from "./telemetry.js";
15
+ function canonical(path) { return existsSync(path) ? realpathSync(path) : resolve(path); }
16
+ function privateRoot() {
17
+ return resolve(process.env.ADG_NATIVE_RETRY_HOME || (process.env.ADG_MIGRATION_HOME
18
+ ? join(process.env.ADG_MIGRATION_HOME, "native-retries")
19
+ : join(process.env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "adg", "native-retries")));
20
+ }
21
+ function ledgerPath(pluginsDir) {
22
+ return join(privateRoot(), `${createHash("sha256").update(canonical(pluginsDir)).digest("hex")}.json`);
23
+ }
24
+ function assertPrivate(path, directory) {
25
+ const stat = lstatSync(path);
26
+ if (stat.isSymbolicLink() || (directory ? !stat.isDirectory() : !stat.isFile())
27
+ || (process.getuid && stat.uid !== process.getuid()) || (process.platform !== "win32" && (stat.mode & 0o077) !== 0)) {
28
+ throw new Error("Native retry state must be private and owned by the current user");
29
+ }
30
+ }
31
+ function load(pluginsDir) {
32
+ const path = ledgerPath(pluginsDir);
33
+ if (!existsSync(path))
34
+ return { version: 1, pluginsDir: canonical(pluginsDir), requests: [] };
35
+ assertPrivate(privateRoot(), true);
36
+ assertPrivate(path, false);
37
+ const ledger = JSON.parse(readFileSync(path, "utf8"));
38
+ if (ledger.version !== 1 || ledger.pluginsDir !== canonical(pluginsDir) || !Array.isArray(ledger.requests)
39
+ || ledger.requests.some(request => !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(request.plugin)
40
+ || typeof request.agent !== "string" || !request.agent || !["activate", "refresh"].includes(request.kind)
41
+ || !["user", "project"].includes(request.scope) || typeof request.installedHash !== "string"
42
+ || !request.origin || request.origin.type !== "github" || typeof request.origin.repo !== "string"
43
+ || typeof request.started !== "boolean" || typeof request.preserveRuntimeDisabled !== "boolean"
44
+ || request.nativeStore !== undefined && (!isAbsolute(request.nativeStore) || canonical(request.nativeStore) !== ledger.pluginsDir))) {
45
+ throw new Error("Invalid native retry state");
46
+ }
47
+ for (const request of ledger.requests)
48
+ request.nativeStore ??= resolve(pluginsDir);
49
+ return ledger;
50
+ }
51
+ function save(ledger) {
52
+ mkdirSync(privateRoot(), { recursive: true, mode: 0o700 });
53
+ assertPrivate(privateRoot(), true);
54
+ const path = ledgerPath(ledger.pluginsDir);
55
+ if (existsSync(path))
56
+ assertPrivate(path, false);
57
+ const temporary = `${path}.${randomUUID()}.tmp`;
58
+ const fd = openSync(temporary, "wx", 0o600);
59
+ try {
60
+ writeFileSync(fd, JSON.stringify(ledger));
61
+ fsyncSync(fd);
62
+ }
63
+ finally {
64
+ closeSync(fd);
65
+ }
66
+ renameSync(temporary, path);
67
+ if (process.platform === "win32")
68
+ return; // Windows cannot open directories for fsync.
69
+ const dir = openSync(dirname(path), "r");
70
+ try {
71
+ fsyncSync(dir);
72
+ }
73
+ finally {
74
+ closeSync(dir);
75
+ }
76
+ }
77
+ function sameOrigin(a, b) {
78
+ return a.type === "github" && b.type === "github" && a.repo === b.repo && a.ref === b.ref && a.path === b.path;
79
+ }
80
+ function group(request) {
81
+ const origin = request.origin;
82
+ if (origin.type !== "github")
83
+ throw new Error("Native retry source is not remote");
84
+ return { source: origin.repo, ...(origin.ref ? { ref: origin.ref } : {}) };
85
+ }
86
+ function key(request) { return `${request.agent}\0${request.plugin}\0${request.scope}\0${request.nativeStore ?? ""}`; }
87
+ function failure(agent, plugin, message) {
88
+ return { agent, affected: [], skipped: false, failures: [{ plugin, stage: "verify", errorType: "NATIVE_RETRY_PENDING", message }] };
89
+ }
90
+ function merge(agent, results) {
91
+ const result = { agent, affected: [...new Set(results.flatMap(item => item.affected))], skipped: results.every(item => item.skipped) };
92
+ for (const field of ["verified", "unverified", "preservedDisabled"]) {
93
+ if (results.some(item => item[field] !== undefined))
94
+ result[field] = [...new Set(results.flatMap(item => item[field] ?? []))];
95
+ }
96
+ const failures = results.flatMap(item => item.failures ?? []);
97
+ if (failures.length)
98
+ result.failures = failures;
99
+ return result;
100
+ }
101
+ function rememberRuntimeState(ledger, request, enabled) {
102
+ const lock = readLock(lockPath(ledger.pluginsDir));
103
+ const entry = lock.plugins[request.plugin];
104
+ if (!entry || !sameOrigin(entry.origin, request.origin) || entry.installedHash !== request.installedHash
105
+ || entry.runtimeStates?.[request.agent] === enabled)
106
+ return;
107
+ lock.plugins[request.plugin] = { ...entry, runtimeStates: { ...entry.runtimeStates, [request.agent]: enabled } };
108
+ const file = lockPath(ledger.pluginsDir);
109
+ writeLock(file, lock);
110
+ // The ledger can be cleared only after the per-runtime intent is durable.
111
+ const fd = openSync(file, process.platform === "win32" ? "r+" : "r");
112
+ try {
113
+ fsyncSync(fd);
114
+ }
115
+ finally {
116
+ closeSync(fd);
117
+ }
118
+ if (process.platform !== "win32") {
119
+ const directory = openSync(dirname(file), "r");
120
+ try {
121
+ fsyncSync(directory);
122
+ }
123
+ finally {
124
+ closeSync(directory);
125
+ }
126
+ }
127
+ }
128
+ /** Execute one saved batch, durably marking its start before calling an adapter. */
129
+ function execute(ledger, requests, agent) {
130
+ const parts = [];
131
+ const lock = readLock(lockPath(ledger.pluginsDir));
132
+ const remove = (request) => { ledger.requests = ledger.requests.filter(item => item !== request); save(ledger); };
133
+ for (const kind of ["activate", "refresh"]) {
134
+ const batch = [];
135
+ for (const request of requests.filter(item => item.kind === kind)) {
136
+ const entry = lock.plugins[request.plugin];
137
+ if (!entry || !sameOrigin(entry.origin, request.origin) || entry.installedHash !== request.installedHash
138
+ || pluginState(entry) === "disabled") {
139
+ remove(request);
140
+ continue;
141
+ }
142
+ const ctx = { pluginsDir: request.nativeStore ?? ledger.pluginsDir, plugins: [request.plugin], scope: request.scope };
143
+ try {
144
+ const payload = installedPluginDir(ledger.pluginsDir, request.plugin, entry.origin);
145
+ const manifest = existsSync(payload) ? readManifest(payload) : undefined;
146
+ const selection = manifest ? resolveSelectionDependencies(manifest, entry.selection) : entry.selection;
147
+ if (!manifest || folderHash(payload, PROJECTION_DIRS, effectivePackageFilter(manifest, selection)) !== request.installedHash) {
148
+ parts.push(failure(agent.id, request.plugin, "The installed payload no longer matches the saved synchronization request. Restore its managed files or explicitly re-add the plugin before retrying."));
149
+ continue;
150
+ }
151
+ const native = request.preserveRuntimeDisabled || request.started ? agent.inspectPlugins?.(ctx) : undefined;
152
+ if ((request.preserveRuntimeDisabled || request.started) && agent.inspectPlugins && !Array.isArray(native)) {
153
+ parts.push(failure(agent.id, request.plugin, "Native enabled/disabled state could not be inspected; restore native listing and rerun the same ADG update."));
154
+ continue;
155
+ }
156
+ const installed = Array.isArray(native) ? native.find(item => item.name === request.plugin && item.installed) : undefined;
157
+ if ((installed && !installed.enabled)
158
+ || (request.preserveRuntimeDisabled && entry.runtimeStates?.[agent.id] === false && !installed?.enabled)) {
159
+ parts.push({ agent: agent.id, affected: [], skipped: false, preservedDisabled: [request.plugin] });
160
+ rememberRuntimeState(ledger, request, false);
161
+ remove(request);
162
+ continue;
163
+ }
164
+ if (request.preserveRuntimeDisabled && installed?.enabled && entry.runtimeStates?.[agent.id] === false) {
165
+ // An independently enabled native registration is a newer user choice.
166
+ rememberRuntimeState(ledger, request, true);
167
+ }
168
+ if (request.started && !agent.retrySafeOperations?.includes(request.kind)) {
169
+ if (Array.isArray(native) && !native.some(item => item.name === request.plugin && item.installed)) {
170
+ // Confirmed absence permits a fresh activation after explicit native
171
+ // cleanup, without repeating an unsafe interrupted refresh.
172
+ request.kind = "activate";
173
+ request.started = false;
174
+ save(ledger);
175
+ parts.push(execute(ledger, [request], agent));
176
+ }
177
+ else {
178
+ parts.push(failure(agent.id, request.plugin, "The previous native operation was interrupted; this adapter cannot safely replay it. Use the native plugin manager to remove its registration, then retry ADG update."));
179
+ }
180
+ continue;
181
+ }
182
+ batch.push(request);
183
+ }
184
+ catch (error) {
185
+ parts.push(failure(agent.id, request.plugin, error instanceof Error ? error.message : String(error)));
186
+ }
187
+ }
188
+ if (!batch.length)
189
+ continue;
190
+ // Different saved scopes must never share one native invocation.
191
+ for (const scope of ["project", "user"]) {
192
+ const namespaces = new Set(batch.filter(request => request.scope === scope).map(request => request.nativeStore ?? ledger.pluginsDir));
193
+ for (const nativeStore of namespaces) {
194
+ const selected = batch.filter(request => request.scope === scope && (request.nativeStore ?? ledger.pluginsDir) === nativeStore);
195
+ const ctx = { pluginsDir: nativeStore, plugins: selected.map(request => request.plugin), scope };
196
+ try {
197
+ for (const request of selected)
198
+ request.started = true;
199
+ save(ledger);
200
+ const result = kind === "activate" ? agent.activate(ctx) : agent.refresh(ctx);
201
+ parts.push(result);
202
+ const snapshot = agent.listInstalled?.(ctx);
203
+ for (const request of selected) {
204
+ const failed = result.failures?.some(item => !item.plugin || item.plugin === request.plugin);
205
+ const verified = result.affected.includes(request.plugin) && (result.verified?.includes(request.plugin)
206
+ || (snapshot === undefined || Array.isArray(snapshot) && snapshot.includes(request.plugin)));
207
+ if (result.preservedDisabled?.includes(request.plugin)
208
+ || (!result.skipped && !failed && !result.unverified?.includes(request.plugin) && verified)) {
209
+ rememberRuntimeState(ledger, request, !result.preservedDisabled?.includes(request.plugin));
210
+ remove(request);
211
+ }
212
+ else if (!failed)
213
+ parts.push(failure(agent.id, request.plugin, "Native synchronization remains unconfirmed; rerun the same ADG update to resume offline."));
214
+ }
215
+ }
216
+ catch (error) {
217
+ for (const request of selected)
218
+ parts.push(failure(agent.id, request.plugin, error instanceof Error ? error.message : String(error)));
219
+ }
220
+ }
221
+ }
222
+ }
223
+ return merge(agent.id, parts);
224
+ }
225
+ /** Persist every requested native target before the first adapter side effect. */
226
+ export async function syncNativeBatchWithRetry(options) {
227
+ return withStoreMutex(options.pluginsDir, () => {
228
+ const ledger = load(options.pluginsDir);
229
+ const lock = readLock(lockPath(options.pluginsDir));
230
+ const batches = options.requests.map((item) => {
231
+ const requests = [];
232
+ const local = { activate: [], refresh: [] };
233
+ if (!item.agent.available())
234
+ return { item, requests, local, absent: true };
235
+ for (const kind of ["activate", "refresh"]) {
236
+ for (const plugin of new Set(item[kind])) {
237
+ const entry = lock.plugins[plugin];
238
+ if (!entry || pluginState(entry) === "disabled")
239
+ continue;
240
+ if (entry.origin.type !== "github") {
241
+ local[kind].push(plugin);
242
+ continue;
243
+ }
244
+ const request = {
245
+ agent: item.agent.id, plugin, scope: options.scope, origin: structuredClone(entry.origin),
246
+ installedHash: entry.installedHash, kind, preserveRuntimeDisabled: Boolean(item.preserveRuntimeDisabled), started: false,
247
+ nativeStore: resolve(options.pluginsDir),
248
+ };
249
+ const previous = ledger.requests.find((saved) => key(saved) === key(request));
250
+ if (previous && sameOrigin(previous.origin, request.origin) && previous.installedHash === request.installedHash) {
251
+ requests.push(previous);
252
+ }
253
+ else {
254
+ ledger.requests = ledger.requests.filter((saved) => key(saved) !== key(request));
255
+ ledger.requests.push(request);
256
+ requests.push(request);
257
+ }
258
+ }
259
+ }
260
+ return { item, requests, local, absent: false };
261
+ });
262
+ if (batches.some((batch) => batch.requests.length))
263
+ save(ledger);
264
+ recordTelemetryEvent("adg.native_retry.prepared", { "request.count": batches.reduce((count, batch) => count + batch.requests.length, 0) });
265
+ return batches.map(({ item, requests, local, absent }) => {
266
+ if (absent)
267
+ return { agent: item.agent.id, affected: [], skipped: true };
268
+ if (!item.agent.available()) {
269
+ return requests.length ? merge(item.agent.id, requests.map((request) => failure(item.agent.id, request.plugin, `Saved native target ${item.agent.id} is unavailable; retry with the same runtime to resume offline.`)))
270
+ : { agent: item.agent.id, affected: [], skipped: true };
271
+ }
272
+ const results = [];
273
+ if (requests.length)
274
+ results.push(execute(ledger, requests, item.agent));
275
+ for (const kind of ["activate", "refresh"]) {
276
+ if (!local[kind].length)
277
+ continue;
278
+ const ctx = { pluginsDir: options.pluginsDir, plugins: local[kind], scope: options.scope };
279
+ results.push(kind === "activate" ? item.agent.activate(ctx) : item.agent.refresh(ctx));
280
+ }
281
+ return merge(item.agent.id, results);
282
+ });
283
+ });
284
+ }
285
+ /** Single-target compatibility wrapper around the batch persistence boundary. */
286
+ export async function syncNativeWithRetry(options) {
287
+ return (await syncNativeBatchWithRetry({ pluginsDir: options.pluginsDir, scope: options.scope, requests: [options] }))[0];
288
+ }
289
+ /** Replay saved operations from installed payloads before contacting upstream. */
290
+ export async function replayNativeRetries(options) {
291
+ return withStoreMutex(options.pluginsDir, () => {
292
+ const ledger = load(options.pluginsDir);
293
+ const requests = ledger.requests.filter(request => {
294
+ const owner = group(request);
295
+ return (!options.source || owner.source === options.source) && (options.ref === undefined || owner.ref === options.ref);
296
+ });
297
+ const groups = [...new Map(requests.map(request => { const owner = group(request); return [JSON.stringify(owner), owner]; })).values()];
298
+ const results = [];
299
+ const agents = options.agents ?? resolveAgents();
300
+ const current = readLock(lockPath(options.pluginsDir));
301
+ const live = requests.filter(request => {
302
+ const entry = current.plugins[request.plugin];
303
+ return entry && sameOrigin(entry.origin, request.origin)
304
+ && entry.installedHash === request.installedHash && pluginState(entry) === "enabled";
305
+ });
306
+ if (live.length !== requests.length) {
307
+ ledger.requests = ledger.requests.filter(request => !requests.includes(request) || live.includes(request));
308
+ save(ledger);
309
+ }
310
+ for (const id of new Set(live.map(request => request.agent))) {
311
+ const selected = live.filter(request => request.agent === id);
312
+ const agent = agents.find(item => item.id === id);
313
+ options.onProgress?.({ kind: "activate", agent: id, count: selected.length });
314
+ if (!agent || !agent.available()) {
315
+ results.push(merge(id, selected.map(request => failure(id, request.plugin, `Saved native target ${id} is unavailable; retry with the same runtime to resume offline.`))));
316
+ }
317
+ else
318
+ results.push(execute(ledger, selected, agent));
319
+ }
320
+ const remaining = new Set(ledger.requests);
321
+ const pending = requests.filter(request => remaining.has(request)).map(request => ({
322
+ ...group(request), plugin: request.plugin, agent: request.agent,
323
+ message: results.find(result => result.agent === request.agent)?.failures?.find(item => !item.plugin || item.plugin === request.plugin)?.message ?? "Native synchronization remains pending",
324
+ }));
325
+ if (requests.length)
326
+ recordTelemetryEvent("adg.native_retry.replayed", { "request.count": requests.length, "pending.count": pending.length });
327
+ return { agents: results, groups, pending };
328
+ });
329
+ }
@@ -0,0 +1,88 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { win32 } from "node:path";
3
+ import { runSubprocessSync } from "./subprocess.js";
4
+ let ownIdentity;
5
+ let ownWindowsFailure;
6
+ /** Return only OS birth evidence. Failure is uncertainty, never proof of death. */
7
+ export function queryProcessIdentity(pid) {
8
+ if (!Number.isSafeInteger(pid) || pid <= 0)
9
+ return undefined;
10
+ if (pid === process.pid && ownIdentity)
11
+ return ownIdentity;
12
+ try {
13
+ if (process.platform === "linux") {
14
+ const boot = readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim();
15
+ if (!/^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i.test(boot))
16
+ return undefined;
17
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
18
+ // comm may contain spaces and parentheses. Field 22 follows the final ')'.
19
+ const end = stat.lastIndexOf(")");
20
+ if (!stat.startsWith(`${pid} (`) || end < 0)
21
+ return undefined;
22
+ const start = stat.slice(end + 1).trim().split(/\s+/)[19];
23
+ if (!start || !/^\d+$/.test(start))
24
+ return undefined;
25
+ return { kind: "linux-proc", version: 1, birthToken: `${boot}:${start}` };
26
+ }
27
+ if (process.platform === "darwin") {
28
+ const result = runSubprocessSync("/bin/ps", ["-p", String(pid), "-o", "lstart="], {
29
+ encoding: "utf8", timeout: 2000, maxBuffer: 1024,
30
+ env: { ...process.env, LC_ALL: "C", TZ: "UTC0" },
31
+ });
32
+ if (result.error || result.status !== 0)
33
+ return undefined;
34
+ const token = result.stdout.trim();
35
+ if (!/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/.test(token))
36
+ return undefined;
37
+ // ps has second precision: a same-second reuse remains conservatively live.
38
+ return { kind: "darwin-ps-lstart", version: 1, birthToken: token };
39
+ }
40
+ if (process.platform === "win32") {
41
+ // Retain only bounded categories for self failures; never expose OS output,
42
+ // paths, or another process's diagnostic in the mutation error.
43
+ const fail = (reason) => {
44
+ if (pid === process.pid)
45
+ ownWindowsFailure = `Windows process query: ${reason}`;
46
+ return undefined;
47
+ };
48
+ try {
49
+ const systemRoot = process.env.SystemRoot;
50
+ if (!systemRoot || !win32.isAbsolute(systemRoot))
51
+ return fail("missing or non-absolute SystemRoot");
52
+ const executable = win32.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
53
+ // Capture self identity before publishing a contender, allowing a cold shell start.
54
+ const timeout = pid === process.pid ? 10_000 : 2000;
55
+ const result = runSubprocessSync(executable, ["-NoProfile", "-NonInteractive", "-Command",
56
+ `(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToFileTimeUtc().ToString([System.Globalization.CultureInfo]::InvariantCulture)`], {
57
+ encoding: "utf8", timeout, maxBuffer: 1024, windowsHide: true,
58
+ });
59
+ if (result.error) {
60
+ const code = result.error.code;
61
+ if (code === "ETIMEDOUT")
62
+ return fail(`timeout after ${timeout}ms (ETIMEDOUT)`);
63
+ const category = code && ["ENOENT", "EACCES", "EPERM", "ENOBUFS"].includes(code) ? code : "unclassified";
64
+ return fail(`spawn failed (${category})`);
65
+ }
66
+ if (result.signal)
67
+ return fail("terminated by signal");
68
+ if (result.status !== 0)
69
+ return fail(Number.isSafeInteger(result.status) ? `exit status ${result.status}` : "missing exit status");
70
+ const token = result.stdout.trim();
71
+ if (!/^[1-9]\d*$/.test(token))
72
+ return fail("invalid birth token output");
73
+ return { kind: "windows-start-filetime", version: 1, birthToken: token };
74
+ }
75
+ catch {
76
+ return fail("unexpected query failure");
77
+ }
78
+ }
79
+ }
80
+ catch { /* Access failures do not establish process identity. */ }
81
+ return undefined;
82
+ }
83
+ export function getCurrentProcessIdentity() {
84
+ ownIdentity ??= queryProcessIdentity(process.pid);
85
+ if (!ownIdentity)
86
+ throw new Error(`Cannot establish ADG mutation process identity; restore access to OS process information and retry.${ownWindowsFailure ? ` ${ownWindowsFailure}.` : ""}`);
87
+ return ownIdentity;
88
+ }
@@ -22,7 +22,7 @@ export function renderContents(contents, headerIndent) {
22
22
  return out;
23
23
  }
24
24
  /** Per-agent sync outcomes (enabled/disabled/re-synced), printed generically. */
25
- export function renderAgentReport(agents, verb) {
25
+ export function renderAgentReport(agents, verb, opts = {}) {
26
26
  const out = [];
27
27
  for (const r of agents ?? []) {
28
28
  const name = getAgent(r.agent)?.displayName ?? r.agent;
@@ -35,7 +35,7 @@ export function renderAgentReport(agents, verb) {
35
35
  if (completed.length > 0)
36
36
  out.push(`${ui.ok(verb)} in ${ui.name(name)}: ${completed.join(", ")}`);
37
37
  if (r.failures?.length || r.unverified?.length)
38
- out.push(ui.warn(`runtime synchronization pending in ${name}; run \`adg plugins sync --target ${r.agent}\` with the same scope to retry.`));
38
+ out.push(ui.warn(`runtime synchronization pending in ${name}; run \`${opts.retryCommand ?? `adg plugins sync --target ${r.agent}`}\` to retry.`));
39
39
  if (r.unverified?.length)
40
40
  out.push(ui.warn(`installed, recovery unverified in ${name}: ${r.unverified.join(", ")}`));
41
41
  if (r.preservedDisabled?.length)
@@ -45,6 +45,46 @@ export function renderAgentReport(agents, verb) {
45
45
  }
46
46
  return out;
47
47
  }
48
+ export function renderUpdateAgentReport(agents, opts = {}) {
49
+ if (opts.verbose)
50
+ return renderAgentReport(agents, "re-synced", { retryCommand: opts.retryCommand ?? "adg plugins update" });
51
+ const out = [];
52
+ const completed = new Set();
53
+ const targets = new Set();
54
+ const preserved = new Set();
55
+ const reported = new Set(opts.reportedFailures ?? []);
56
+ let needsRetry = false;
57
+ for (const agent of agents) {
58
+ const display = getAgent(agent.agent)?.displayName ?? agent.agent;
59
+ const failed = new Set((agent.failures ?? []).flatMap(failure => failure.plugin ? [failure.plugin] : []));
60
+ const uncertain = new Set(agent.unverified ?? []);
61
+ const globalFailure = agent.failures?.some(failure => !failure.plugin);
62
+ const verified = (agent.verified ?? (globalFailure ? [] : agent.affected))
63
+ .filter(plugin => !failed.has(plugin) && !uncertain.has(plugin));
64
+ if (verified.length) {
65
+ targets.add(display);
66
+ for (const plugin of verified)
67
+ completed.add(plugin);
68
+ }
69
+ for (const plugin of agent.preservedDisabled ?? [])
70
+ preserved.add(plugin);
71
+ for (const failure of agent.failures ?? []) {
72
+ if (!reported.has(failure.message))
73
+ out.push(ui.err(`${display}${failure.plugin ? ` / ${failure.plugin}` : ""}: ${failure.message}`));
74
+ }
75
+ if (agent.failures?.length || agent.unverified?.length)
76
+ needsRetry = true;
77
+ if (agent.skipped && !agent.failures?.length)
78
+ out.push(ui.meta(`${display}: runtime unavailable; installed files retained`));
79
+ }
80
+ if (completed.size)
81
+ out.unshift(ui.ok(`runtime synchronized: ${completed.size} plugin${completed.size === 1 ? "" : "s"} across ${[...targets].join(", ")}`));
82
+ if (preserved.size)
83
+ out.push(ui.meta(`runtime disabled, preserved: ${preserved.size} plugin${preserved.size === 1 ? "" : "s"}`));
84
+ if (needsRetry && !reported.size)
85
+ out.push(ui.warn(`Run \`${opts.retryCommand ?? "adg plugins update"}\` to resume runtime synchronization.`));
86
+ return out;
87
+ }
48
88
  const PATH_MAX = 44;
49
89
  function pluginLabel(plugin) {
50
90
  if (plugin.definition?.kind === "default-dsl/v1" && plugin.resolvedRevision) {
@@ -102,16 +142,77 @@ export function renderPluginList(plugins, pluginsDir, opts = {}) {
102
142
  * plus the local-bucket rescan, in the spirit of `adg skills update`. Returns a
103
143
  * one-line "nothing to update" message when no remote source had any change.
104
144
  */
105
- export function renderUpdateReport(result) {
145
+ export function renderUpdateReport(result, opts = {}) {
106
146
  const out = [];
147
+ const untouched = (source) => !source.updated.length && !source.deleted.length
148
+ && !source.failed && !source.actionRequired?.length && !source.pendingRuntime?.length
149
+ && !source.migrated?.length && !source.resumed && !source.restored?.length
150
+ && !source.retained?.length && !source.notRestored?.length && !source.deferredRecovery?.length
151
+ && !source.missingUpstream?.length && !source.available.length;
152
+ const collapsed = !opts.verbose && result.remote.length > 1 ? result.remote.filter(untouched) : [];
153
+ const retry = opts.retryCommand ?? "adg plugins update";
107
154
  for (const r of result.remote) {
155
+ if (collapsed.includes(r))
156
+ continue;
108
157
  const ref = r.ref ? `@${r.ref}` : "";
109
158
  const head = `${ui.name(`${r.source}${ref}`)}`;
159
+ const deferredReport = () => {
160
+ if (!r.deferredRecovery?.length)
161
+ return;
162
+ const count = r.deferredRecovery.length;
163
+ out.push(ui.meta(` historical recovery deferred: ${count} candidate${count === 1 ? "" : "s"} (prior selection unknown)`));
164
+ if (opts.verbose)
165
+ out.push(ui.meta(` deferred candidates: ${r.deferredRecovery.join(", ")}`));
166
+ const reconsider = /(?:^|\s)--repair(?:\s|$)/.test(retry) ? retry : `${retry} --repair`;
167
+ out.push(ui.meta(` Run \`${reconsider}\` in a terminal to reconsider these candidates.`));
168
+ };
110
169
  if (r.failed) {
111
170
  out.push(`${head} ${ui.err("could not be checked")} ${ui.meta(`— ${r.failed}`)}`);
171
+ deferredReport();
172
+ continue;
173
+ }
174
+ if (r.actionRequired?.length) {
175
+ out.push(`${head}: ${ui.warn("action required; current installation retained")}`);
176
+ for (const message of r.actionRequired) {
177
+ const readable = opts.verbose ? message : message.startsWith("Review state:")
178
+ ? "Choose whether the merged plugin should be enabled or disabled."
179
+ : message.startsWith("Review drop:") ? "Choose whether to keep or remove a skill without a replacement."
180
+ : message.startsWith("Review unmapped:") ? "Choose whether to keep or remove the old plugin without a declared replacement."
181
+ : message.startsWith("Review ")
182
+ ? `Choose whether to restore historical skills${message.includes(": ") ? ` (${message.split(": ").slice(1).join(": ").split(", ").length})` : ""}.`
183
+ : message.replace(/ \(unmapped:[^)]+\)\./g, ".");
184
+ out.push(ui.warn(` ${readable}`));
185
+ }
186
+ out.push(ui.meta(` Run \`${retry}\` in a terminal with the same scope and source ref to review.`));
187
+ deferredReport();
112
188
  continue;
113
189
  }
114
- if (r.updated.length > 0 && r.changes) {
190
+ if (r.pendingRuntime?.length) {
191
+ out.push(`${head}: ${ui.warn("runtime synchronization pending; existing installation retained")}`);
192
+ for (const message of new Set(r.pendingRuntime))
193
+ out.push(ui.warn(` ${message}`));
194
+ out.push(ui.meta(` Run \`${retry}\` with the same scope to resume offline.`));
195
+ }
196
+ if (r.resumed)
197
+ out.push(`${head}: ${ui.ok(r.deferredRecovery?.length ? "runtime synchronization complete" : "recovery complete")}`);
198
+ if (!r.pendingRuntime?.length && r.migrated?.length) {
199
+ const restored = r.restored?.length ? `; restored ${r.restored.length} historical skill${r.restored.length === 1 ? "" : "s"}` : "";
200
+ out.push(`${head}: ${ui.ok(`source migrated${restored}`)}`);
201
+ if (opts.verbose) {
202
+ out.push(ui.meta(` migrations: ${r.migrated.join(", ")}`));
203
+ if (r.restored?.length)
204
+ out.push(ui.meta(` restored: ${r.restored.join(", ")}`));
205
+ }
206
+ }
207
+ if (r.retained?.length)
208
+ out.push(ui.meta(` preserved by choice: ${r.retained.join(", ")}`));
209
+ if (r.notRestored?.length)
210
+ out.push(ui.meta(` not restored by choice (${r.notRestored.length})${opts.verbose ? `: ${r.notRestored.join(", ")}` : ""}`));
211
+ if (!opts.verbose && r.updated.length > 0) {
212
+ if (!r.migrated?.length || r.pendingRuntime?.length)
213
+ out.push(`${head}: ${ui.ok(`updated ${r.updated.length} plugin${r.updated.length === 1 ? "" : "s"}`)}`);
214
+ }
215
+ else if (r.updated.length > 0 && r.changes) {
115
216
  const versionOnly = r.updated.filter((name) => {
116
217
  const change = r.changes.find((item) => item.name === name);
117
218
  return change?.version && !change.content && !change.selection;
@@ -124,14 +225,25 @@ export function renderUpdateReport(result) {
124
225
  }
125
226
  else if (r.updated.length > 0)
126
227
  out.push(`${head}: ${ui.ok(`updated ${r.updated.join(", ")}`)}`);
127
- else
228
+ else if (r.missingUpstream?.length)
229
+ out.push(`${head}: ${ui.warn(`update incomplete (${r.unchanged.length} unchanged)`)}`);
230
+ else if (!r.pendingRuntime?.length && !r.migrated?.length && !r.resumed)
128
231
  out.push(`${head}: ${ui.meta(`up to date (${r.unchanged.length})`)}`);
129
- if (r.deleted.length > 0) {
130
- out.push(ui.warn(` removed stale upstream entries: ${r.deleted.join(", ")}`));
232
+ if (r.deleted.length > 0 && !r.pendingRuntime?.length) {
233
+ out.push(ui.warn(` retired plugins: ${r.deleted.join(", ")}`));
234
+ }
235
+ if (r.missingUpstream?.length) {
236
+ out.push(ui.warn(` retained installed plugins missing upstream: ${r.missingUpstream.join(", ")}`));
237
+ out.push(ui.warn(` Run \`${retry}\` with the same scope in a terminal to keep or remove them.`));
131
238
  }
132
239
  if (r.available.length > 0) {
133
- out.push(ui.meta(` ${r.available.length} more available (use --all): ${r.available.join(", ")}`));
240
+ out.push(ui.meta(` ${r.available.length} more available${opts.verbose ? `: ${r.available.join(", ")}` : ""}; use update --all to include these once, or add <source> --all to follow future plugins`));
134
241
  }
242
+ deferredReport();
243
+ }
244
+ if (collapsed.length) {
245
+ const other = result.remote.length > collapsed.length ? " other" : "";
246
+ out.push(ui.meta(`${collapsed.length}${other} source${collapsed.length === 1 ? "" : "s"} up to date`));
135
247
  }
136
248
  for (const res of result.local.results) {
137
249
  const versionOnly = res.changes?.version && !res.changes.content && !res.changes.selection;
@@ -231,29 +343,39 @@ export function renderPrune(results) {
231
343
  }
232
344
  return out;
233
345
  }
234
- /**
235
- * `adg plugins marketplace list` — installed plugins grouped by source.
236
- * `details` (name → ListedPlugin) enables the verbose per-plugin component drill;
237
- * pass it only when --verbose is set.
238
- */
239
- export function renderMarketplaceList(groups, details) {
346
+ export function marketplaceListCounts(groups) {
347
+ let installed = 0;
348
+ let disabled = 0;
349
+ for (const group of groups) {
350
+ installed += group.installed.length;
351
+ disabled += group.disabled.length;
352
+ }
353
+ return { sources: groups.length, installed, enabled: installed - disabled, disabled };
354
+ }
355
+ /** Render installed plugins grouped by source, with optional component details. */
356
+ export function renderMarketplaceList(groups, opts) {
357
+ const { sources, installed, enabled, disabled } = marketplaceListCounts(groups);
358
+ const sourceLabel = sources === 1 ? "source" : "sources";
359
+ const out = [ui.title(`${opts.scope} · ${sources} ${sourceLabel} · ${installed} installed · ${enabled} enabled · ${disabled} disabled`)];
240
360
  if (groups.length === 0)
241
- return [ui.meta("No plugins installed.")];
242
- const out = [];
243
- for (const g of groups) {
244
- const ref = g.ref ? `@${g.ref}` : "";
245
- const n = g.installed.length;
246
- const tag = g.remote ? "" : ui.warn(" (local — re-run add to update)");
247
- out.push(`${ui.name(`${g.source}${ref}`)} ${ui.meta(`(${n} plugin${n !== 1 ? "s" : ""})`)}${tag}`);
248
- if (details) {
249
- for (const name of g.installed) {
250
- const p = details.get(name);
251
- out.push(` ${ui.name(name)}${p?.selection ? ui.meta(" (partial)") : ""}`);
361
+ return [...out, "", ui.meta("No plugins installed.")];
362
+ for (const group of groups) {
363
+ const ref = group.ref ? `@${group.ref}` : "";
364
+ const disabledCount = group.disabled.length ? ` · ${group.disabled.length} disabled` : "";
365
+ const tag = group.remote ? "" : ui.warn(" (local — re-run add to update)");
366
+ const disabledNames = new Set(group.disabled);
367
+ const stateSuffix = (name) => disabledNames.has(name) ? " [disabled]" : "";
368
+ out.push("", `${ui.name(`${group.source}${ref}`)} ${ui.meta(`(${group.installed.length} installed${disabledCount})`)}${tag}`);
369
+ if (opts.details) {
370
+ for (const name of group.installed) {
371
+ const p = opts.details.get(name);
372
+ out.push(` ${ui.name(name)}${stateSuffix(name)}${p?.selection ? ui.meta(" (partial)") : ""}`);
252
373
  out.push(...renderContents(p?.contents, 4));
253
374
  }
254
375
  }
255
- else {
256
- out.push(...formatColumns(g.installed).split("\n"));
376
+ else if (group.installed.length > 0) {
377
+ const labels = group.installed.map((name) => name + stateSuffix(name));
378
+ out.push(...formatColumns(labels, { maxColWidth: false, width: opts.width }).split("\n"));
257
379
  }
258
380
  }
259
381
  return out;