@rbbtsn0w/adg 0.7.2-beta.1 → 0.7.2-beta.2

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.
package/README.md CHANGED
@@ -459,6 +459,30 @@ Debugging tips:
459
459
  - GitHub clone/sparse logic is injectable (`gitRunner`) and covered offline by
460
460
  the test suite; live network clones are exercised by `import owner/repo`.
461
461
 
462
+ ## Telemetry
463
+
464
+ `adg` sends anonymous OpenTelemetry usage spans (command names, outcomes,
465
+ timings) to `https://telemetry-gateway.hamiltonsnow.workers.dev/v1/traces`, a
466
+ maintainer-run gateway on Cloudflare Workers, by default. A sanitized command
467
+ *shape* is included in each span: [`sanitizeArgs`](src/telemetry.ts) keeps
468
+ only the top two positions after `adg` — the domain and its verb (e.g. `adg
469
+ plugins add [VALUE] [FLAG]`) — redacting everything past that depth (`adg
470
+ plugins marketplace list` → `adg plugins marketplace [VALUE]`) as well as
471
+ every positional value, including file paths, to `[VALUE]`. The literal
472
+ argument values themselves — plugin names, sources, paths — are never
473
+ included.
474
+
475
+ Opt out with any of:
476
+
477
+ ```bash
478
+ export DO_NOT_TRACK=1 # community-standard opt-out
479
+ export DISABLE_TELEMETRY=1 # adg-specific opt-out
480
+ export OTEL_SDK_DISABLED=true
481
+ ```
482
+
483
+ See [src/telemetry.ts](src/telemetry.ts) for exactly what's collected and how
484
+ it's sanitized.
485
+
462
486
  ## Contributing
463
487
 
464
488
  All feature/fix pull requests target the **`beta`** integration branch; `main`
@@ -0,0 +1,172 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readFileSync, realpathSync } from "node:fs";
3
+ import { dirname, resolve } from "node:path";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
+
6
+ /**
7
+ * Antigravity tool name -> Claude tool name, the inverse of TOOL_ALIASES in
8
+ * antigravity-hooks.ts. Kept as a literal (not derived at runtime — this file
9
+ * runs standalone, as a child process, with no import access to the TS
10
+ * module) but `test/antigravity-hook-runner.test.ts` asserts it stays the
11
+ * exact inverse of TOOL_ALIASES so the two tables can't silently drift.
12
+ */
13
+ export function claudeToolName(name) {
14
+ return ({
15
+ run_command: "Bash",
16
+ view_file: "Read",
17
+ write_to_file: "Write",
18
+ replace_file_content: "Edit",
19
+ multi_replace_file_content: "Edit",
20
+ find_by_name: "Glob",
21
+ grep_search: "Grep",
22
+ search_web: "WebSearch",
23
+ read_url_content: "WebFetch",
24
+ invoke_subagent: "Agent",
25
+ ask_question: "AskUserQuestion",
26
+ })[name] ?? name;
27
+ }
28
+
29
+ function main() {
30
+ const [event, encodedCommand] = process.argv.slice(2);
31
+ const rawInput = readFileSync(0, "utf8");
32
+ let input;
33
+ try {
34
+ input = rawInput.trim() ? JSON.parse(rawInput) : {};
35
+ } catch (error) {
36
+ fail("invalid Antigravity hook input", error);
37
+ }
38
+
39
+ if (event === "SessionStart" && input.invocationNum !== 0) {
40
+ emit({});
41
+ process.exit(0);
42
+ }
43
+
44
+ const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
45
+ const command = Buffer.from(encodedCommand, "base64url").toString("utf8")
46
+ .replaceAll("${CLAUDE_PLUGIN_ROOT}", pluginRoot)
47
+ .replaceAll("${PLUGIN_ROOT}", pluginRoot);
48
+ const childInput = claudeInput(event, input, pluginRoot);
49
+ const child = spawnSync(command, {
50
+ cwd: pluginRoot,
51
+ env: { ...process.env, CLAUDE_PLUGIN_ROOT: pluginRoot, PLUGIN_ROOT: pluginRoot },
52
+ input: JSON.stringify(childInput),
53
+ encoding: "utf8",
54
+ shell: true,
55
+ maxBuffer: 10 * 1024 * 1024,
56
+ });
57
+ if (child.stderr) process.stderr.write(child.stderr);
58
+ if (child.error) fail("failed to launch hook command", child.error);
59
+ if (child.status !== 0) process.exit(child.status ?? 1);
60
+
61
+ const output = parseOutput(event, child.stdout);
62
+ emit(antigravityOutput(event, output));
63
+ }
64
+
65
+ function claudeInput(hookEvent, source, pluginRoot) {
66
+ const common = {
67
+ ...source,
68
+ session_id: source.conversationId,
69
+ transcript_path: source.transcriptPath,
70
+ cwd: source.workspacePaths?.[0] ?? pluginRoot,
71
+ hook_event_name: hookEvent,
72
+ };
73
+ if (hookEvent === "SessionStart") return { ...common, source: "startup" };
74
+ if (hookEvent === "PreToolUse" || hookEvent === "PostToolUse") {
75
+ return {
76
+ ...common,
77
+ tool_name: claudeToolName(source.toolCall?.name),
78
+ tool_input: source.toolCall?.args ?? {},
79
+ tool_response: source.toolCall?.result,
80
+ };
81
+ }
82
+ if (hookEvent === "Stop") return { ...common, stop_hook_active: false };
83
+ return common;
84
+ }
85
+
86
+ function parseOutput(hookEvent, stdout) {
87
+ const text = stdout.trim();
88
+ if (!text) return {};
89
+ try {
90
+ const parsed = JSON.parse(text);
91
+ return (typeof parsed === "object" && parsed !== null) ? parsed : {};
92
+ } catch (error) {
93
+ if (hookEvent === "SessionStart") return { additionalContext: text };
94
+ fail("hook command returned invalid JSON", error);
95
+ }
96
+ }
97
+
98
+ function antigravityOutput(hookEvent, output) {
99
+ if (output.continue === false) {
100
+ const reason = output.stopReason ?? output.reason ?? "Claude hook stopped processing";
101
+ if (hookEvent === "PreToolUse") return { decision: "deny", reason };
102
+ if (hookEvent === "Stop") return { decision: "stop" };
103
+ fail(hookEvent + " continue:false output has no safe Antigravity mapping", reason);
104
+ }
105
+ if (hookEvent === "SessionStart") {
106
+ if (Array.isArray(output.injectSteps)) return output;
107
+ const context = output.hookSpecificOutput?.additionalContext
108
+ ?? output.additionalContext
109
+ ?? output.additional_context;
110
+ return typeof context === "string" && context ? { injectSteps: [{ ephemeralMessage: context }] } : {};
111
+ }
112
+ if (hookEvent === "PreToolUse") {
113
+ const specific = output.hookSpecificOutput ?? {};
114
+ const decision = specific.permissionDecision ?? output.permissionDecision ?? output.decision;
115
+ const reason = specific.permissionDecisionReason ?? output.reason;
116
+ if (specific.updatedInput !== undefined) {
117
+ process.stderr.write("antigravity hook bridge: Claude updatedInput is unsupported; requesting confirmation\n");
118
+ return { decision: "ask", reason: reason ?? "Hook requested a tool-input change that Antigravity cannot apply" };
119
+ }
120
+ if (decision === "deny" || decision === "block") return { decision: "deny", ...(reason ? { reason } : {}) };
121
+ if (decision === "allow" || decision === "approve") return { decision: "allow", ...(reason ? { reason } : {}) };
122
+ if (decision === "ask") return { decision: "ask", ...(reason ? { reason } : {}) };
123
+ if (decision === "defer") {
124
+ process.stderr.write("antigravity hook bridge: Claude defer is unsupported; requesting confirmation\n");
125
+ return { decision: "ask", reason: reason ?? "Hook deferred to Antigravity's permission flow" };
126
+ }
127
+ return { decision: "allow", ...(reason ? { reason } : {}) };
128
+ }
129
+ if (hookEvent === "PostToolUse") {
130
+ if (output.decision === "block") {
131
+ fail("PostToolUse block output has no safe Antigravity mapping", output.reason ?? "block");
132
+ }
133
+ return {};
134
+ }
135
+ if (hookEvent === "Stop") {
136
+ return output.decision === "block"
137
+ ? { decision: "continue", ...(output.reason ? { reason: output.reason } : {}) }
138
+ : { decision: "stop" };
139
+ }
140
+ return {};
141
+ }
142
+
143
+ function emit(value) {
144
+ process.stdout.write(JSON.stringify(value) + "\n");
145
+ }
146
+
147
+ function fail(message, error) {
148
+ process.stderr.write("antigravity hook bridge: " + message + ": " + String(error) + "\n");
149
+ process.exit(1);
150
+ }
151
+
152
+ // Only run the hook bridge when executed directly (`node hook-runner.mjs ...`),
153
+ // so the module can be imported for its pure exports (claudeToolName) in tests
154
+ // without reading stdin or spawning a child process. Realpath process.argv[1]
155
+ // first: import.meta.url is symlink-resolved by Node (e.g. macOS /tmp is a
156
+ // symlink to /private/tmp) but the literal argv[1] is not, so a plain string
157
+ // comparison between the two silently never matches on such systems.
158
+ function isDirectlyExecuted() {
159
+ if (!process.argv[1]) return false;
160
+ try {
161
+ // realpathSync throws when argv[1] isn't a real filesystem path — e.g.
162
+ // `node -e "..."` sets it to the literal string "-e". A throw here means
163
+ // this can't be the running entry file, not that the check failed.
164
+ return import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href;
165
+ } catch {
166
+ return false;
167
+ }
168
+ }
169
+
170
+ if (isDirectlyExecuted()) {
171
+ main();
172
+ }
@@ -1,19 +1,43 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { cpSync, existsSync, readFileSync, renameSync, rmSync, statSync } from "node:fs";
3
- import { basename, join, resolve } from "node:path";
3
+ import { basename, dirname, join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
4
5
  import { isExposed } from "../components.js";
5
6
  import { writeJson, writeText } from "../fsutil.js";
6
7
  const TARGET_FILE = "hooks.json";
7
8
  const PROJECTION_DIR = ".antigravity-plugin";
8
9
  const RUNNER_FILE = "hook-runner.mjs";
10
+ const RUNNER_ASSET = "antigravity-hook-runner.mjs";
9
11
  const NATIVE_OVERRIDE = "hooks-antigravity.json";
12
+ let cachedHookRunner;
13
+ /**
14
+ * The runner materialized into each plugin's projection dir. A real,
15
+ * standalone, lintable/testable .mjs (see antigravity-hook-runner.mjs and
16
+ * test/antigravity-hook-runner.test.ts), copied into `dist/` alongside the
17
+ * compiled output by the `build` script since tsc only emits .ts. Read lazily
18
+ * and cached so an `adg` invocation with no antigravity hooks never touches it.
19
+ */
20
+ function hookRunnerSource() {
21
+ if (cachedHookRunner === undefined) {
22
+ cachedHookRunner = readFileSync(join(dirname(fileURLToPath(import.meta.url)), RUNNER_ASSET), "utf8");
23
+ }
24
+ return cachedHookRunner;
25
+ }
10
26
  const EVENT_MAP = {
11
27
  SessionStart: "PreInvocation",
12
28
  PreToolUse: "PreToolUse",
13
29
  PostToolUse: "PostToolUse",
14
30
  Stop: "Stop",
15
31
  };
16
- const TOOL_ALIASES = {
32
+ /**
33
+ * Claude tool name -> Antigravity tool name(s) ("|"-joined when a Claude tool
34
+ * has more than one Antigravity counterpart). The inverse direction lives in
35
+ * antigravity-hook-runner.mjs's `claudeToolName` — that file runs as a
36
+ * standalone child process with no import access to this module, so the two
37
+ * tables can't be unified into one; `test/antigravity-hook-runner.test.ts`
38
+ * asserts they stay exact inverses of each other instead.
39
+ */
40
+ export const TOOL_ALIASES = {
17
41
  Bash: "run_command",
18
42
  Read: "view_file",
19
43
  Write: "write_to_file",
@@ -313,7 +337,7 @@ export function writeAntigravityHooks(pluginDir, manifest, selection) {
313
337
  if (Object.keys(definition).length) {
314
338
  const projected = { [manifest.name]: definition };
315
339
  validateNativeDocument(projected);
316
- replaceText(join(pluginDir, PROJECTION_DIR, RUNNER_FILE), HOOK_RUNNER);
340
+ replaceText(join(pluginDir, PROJECTION_DIR, RUNNER_FILE), hookRunnerSource());
317
341
  replaceJson(target, projected);
318
342
  }
319
343
  else {
@@ -321,145 +345,3 @@ export function writeAntigravityHooks(pluginDir, manifest, selection) {
321
345
  }
322
346
  return warnings;
323
347
  }
324
- const HOOK_RUNNER = String.raw `import { spawnSync } from "node:child_process";
325
- import { readFileSync } from "node:fs";
326
- import { dirname, resolve } from "node:path";
327
- import { fileURLToPath } from "node:url";
328
-
329
- const [event, encodedCommand] = process.argv.slice(2);
330
- const rawInput = readFileSync(0, "utf8");
331
- let input;
332
- try {
333
- input = rawInput.trim() ? JSON.parse(rawInput) : {};
334
- } catch (error) {
335
- fail("invalid Antigravity hook input", error);
336
- }
337
-
338
- if (event === "SessionStart" && input.invocationNum !== 0) {
339
- emit({});
340
- process.exit(0);
341
- }
342
-
343
- const pluginRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
344
- const command = Buffer.from(encodedCommand, "base64url").toString("utf8")
345
- .replaceAll("$" + "{CLAUDE_PLUGIN_ROOT}", pluginRoot)
346
- .replaceAll("$" + "{PLUGIN_ROOT}", pluginRoot);
347
- const childInput = claudeInput(event, input);
348
- const child = spawnSync(command, {
349
- cwd: pluginRoot,
350
- env: { ...process.env, CLAUDE_PLUGIN_ROOT: pluginRoot, PLUGIN_ROOT: pluginRoot },
351
- input: JSON.stringify(childInput),
352
- encoding: "utf8",
353
- shell: true,
354
- maxBuffer: 10 * 1024 * 1024,
355
- });
356
- if (child.stderr) process.stderr.write(child.stderr);
357
- if (child.error) fail("failed to launch hook command", child.error);
358
- if (child.status !== 0) process.exit(child.status ?? 1);
359
-
360
- const output = parseOutput(event, child.stdout);
361
- emit(antigravityOutput(event, output));
362
-
363
- function claudeInput(hookEvent, source) {
364
- const common = {
365
- ...source,
366
- session_id: source.conversationId,
367
- transcript_path: source.transcriptPath,
368
- cwd: source.workspacePaths?.[0] ?? pluginRoot,
369
- hook_event_name: hookEvent,
370
- };
371
- if (hookEvent === "SessionStart") return { ...common, source: "startup" };
372
- if (hookEvent === "PreToolUse" || hookEvent === "PostToolUse") {
373
- return {
374
- ...common,
375
- tool_name: claudeToolName(source.toolCall?.name),
376
- tool_input: source.toolCall?.args ?? {},
377
- tool_response: source.toolCall?.result,
378
- };
379
- }
380
- if (hookEvent === "Stop") return { ...common, stop_hook_active: false };
381
- return common;
382
- }
383
-
384
- function claudeToolName(name) {
385
- return ({
386
- run_command: "Bash",
387
- view_file: "Read",
388
- write_to_file: "Write",
389
- replace_file_content: "Edit",
390
- multi_replace_file_content: "Edit",
391
- find_by_name: "Glob",
392
- grep_search: "Grep",
393
- search_web: "WebSearch",
394
- read_url_content: "WebFetch",
395
- invoke_subagent: "Agent",
396
- ask_question: "AskUserQuestion",
397
- })[name] ?? name;
398
- }
399
-
400
- function parseOutput(hookEvent, stdout) {
401
- const text = stdout.trim();
402
- if (!text) return {};
403
- try {
404
- const parsed = JSON.parse(text);
405
- return (typeof parsed === "object" && parsed !== null) ? parsed : {};
406
- } catch (error) {
407
- if (hookEvent === "SessionStart") return { additionalContext: text };
408
- fail("hook command returned invalid JSON", error);
409
- }
410
- }
411
-
412
- function antigravityOutput(hookEvent, output) {
413
- if (output.continue === false) {
414
- const reason = output.stopReason ?? output.reason ?? "Claude hook stopped processing";
415
- if (hookEvent === "PreToolUse") return { decision: "deny", reason };
416
- if (hookEvent === "Stop") return { decision: "stop" };
417
- fail(hookEvent + " continue:false output has no safe Antigravity mapping", reason);
418
- }
419
- if (hookEvent === "SessionStart") {
420
- if (Array.isArray(output.injectSteps)) return output;
421
- const context = output.hookSpecificOutput?.additionalContext
422
- ?? output.additionalContext
423
- ?? output.additional_context;
424
- return typeof context === "string" && context ? { injectSteps: [{ ephemeralMessage: context }] } : {};
425
- }
426
- if (hookEvent === "PreToolUse") {
427
- const specific = output.hookSpecificOutput ?? {};
428
- const decision = specific.permissionDecision ?? output.permissionDecision ?? output.decision;
429
- const reason = specific.permissionDecisionReason ?? output.reason;
430
- if (specific.updatedInput !== undefined) {
431
- process.stderr.write("antigravity hook bridge: Claude updatedInput is unsupported; requesting confirmation\n");
432
- return { decision: "ask", reason: reason ?? "Hook requested a tool-input change that Antigravity cannot apply" };
433
- }
434
- if (decision === "deny" || decision === "block") return { decision: "deny", ...(reason ? { reason } : {}) };
435
- if (decision === "allow" || decision === "approve") return { decision: "allow", ...(reason ? { reason } : {}) };
436
- if (decision === "ask") return { decision: "ask", ...(reason ? { reason } : {}) };
437
- if (decision === "defer") {
438
- process.stderr.write("antigravity hook bridge: Claude defer is unsupported; requesting confirmation\n");
439
- return { decision: "ask", reason: reason ?? "Hook deferred to Antigravity's permission flow" };
440
- }
441
- return { decision: "allow", ...(reason ? { reason } : {}) };
442
- }
443
- if (hookEvent === "PostToolUse") {
444
- if (output.decision === "block") {
445
- fail("PostToolUse block output has no safe Antigravity mapping", output.reason ?? "block");
446
- }
447
- return {};
448
- }
449
- if (hookEvent === "Stop") {
450
- return output.decision === "block"
451
- ? { decision: "continue", ...(output.reason ? { reason: output.reason } : {}) }
452
- : { decision: "stop" };
453
- }
454
- return {};
455
- }
456
-
457
- function emit(value) {
458
- process.stdout.write(JSON.stringify(value) + "\n");
459
- }
460
-
461
- function fail(message, error) {
462
- process.stderr.write("antigravity hook bridge: " + message + ": " + String(error) + "\n");
463
- process.exit(1);
464
- }
465
- `;
@@ -290,12 +290,13 @@ async function handleSync(rest, cmd) {
290
290
  printCliUnavailableNote(target, `manifests were regenerated, but nothing was re-synced in ${target}.`);
291
291
  }
292
292
  }
293
- async function handleUpdate(rest, cmd) {
294
- const { values, positionals } = parseVerb("update", cmd.flags, rest);
295
- const source = positionals[0];
296
- // First paint, before the scope prompt and before any lock read, so the run
297
- // never opens on a blank screen. stderr keeps stdout to the report alone.
298
- process.stderr.write(`${ui.title("adg plugins update")}\n`);
293
+ /**
294
+ * Re-fetch every scope in `resolveUpdateScopes(values)` and refresh its
295
+ * installed plugins, with per-scope progress reporting and error handling.
296
+ * Shared by `plugins update` and its deprecated `marketplace upgrade` alias
297
+ * so the two verbs can't drift from each other.
298
+ */
299
+ async function runUpdateAcrossScopes(values, opts) {
299
300
  let succeeded = 0;
300
301
  let failed = 0;
301
302
  for (const sc of await resolveUpdateScopes(values)) {
@@ -305,11 +306,12 @@ async function handleUpdate(rest, cmd) {
305
306
  try {
306
307
  const result = await updatePlugins({
307
308
  pluginsDir: sc.dir,
308
- source,
309
+ source: opts.source,
309
310
  all: values.all,
310
311
  activate: true,
311
312
  agentScope: sc.agentScope,
312
313
  scope: { label: sc.label, globalDir: globalPluginsDir() },
314
+ targets: opts.targets,
313
315
  onProgress: (phase) => progress.update(phase),
314
316
  });
315
317
  // Clear the animated line before the report goes to stdout, so the two
@@ -331,6 +333,13 @@ async function handleUpdate(rest, cmd) {
331
333
  return commandOutcome("success");
332
334
  return commandOutcome(succeeded > 0 ? "partial" : "failure", "dependency");
333
335
  }
336
+ async function handleUpdate(rest, cmd) {
337
+ const { values, positionals } = parseVerb("update", cmd.flags, rest);
338
+ // First paint, before the scope prompt and before any lock read, so the run
339
+ // never opens on a blank screen. stderr keeps stdout to the report alone.
340
+ process.stderr.write(`${ui.title("adg plugins update")}\n`);
341
+ return runUpdateAcrossScopes(values, { source: positionals[0] });
342
+ }
334
343
  async function runPluginsVerb(verb, rest, cmd) {
335
344
  if (await handleCorePluginVerb(verb, rest, cmd))
336
345
  return;
@@ -473,45 +482,14 @@ async function runMarketplace(args) {
473
482
  return commandOutcome("success");
474
483
  }
475
484
  case "upgrade": {
476
- // Deprecated: a thin alias for `adg plugins update`. It runs the exact same
477
- // update path (re-fetch + refresh, with the richer changed/unchanged/deleted
478
- // report) so there is no second implementation to drift.
485
+ // Deprecated: a thin alias for `adg plugins update`. It calls the same
486
+ // `runUpdateAcrossScopes` helper (scope resolution, progress reporting,
487
+ // and error handling) so the alias can't drift from the verb it aliases.
488
+ // `--target` narrows the runtimes.
479
489
  console.error(ui.warn("note: `marketplace upgrade` is a deprecated alias for `adg plugins update`."));
480
490
  const { values, positionals } = parseVerb("marketplace", ["all", "target", ...SCOPE], rest);
481
- // Drive the exact same scope resolution + per-scope loop as `plugins update`
482
- // (project/global/both, with the home==global trap guard) so the deprecated
483
- // alias can't drift from the verb it aliases. `--target` narrows the runtimes.
484
491
  const targets = values.target !== undefined ? resolveTargets(values.target) : undefined;
485
- let succeeded = 0;
486
- let failed = 0;
487
- for (const sc of await resolveUpdateScopes(values)) {
488
- if (sc.heading)
489
- console.log(`${ui.name(sc.heading)}`);
490
- // Mirror `plugins update`'s error handling: report a failed re-fetch and
491
- // exit cleanly rather than throwing to the top-level catch.
492
- try {
493
- const result = await updatePlugins({
494
- pluginsDir: sc.dir,
495
- scope: { label: sc.label, globalDir: globalPluginsDir() },
496
- activate: true,
497
- agentScope: sc.agentScope,
498
- source: positionals[0],
499
- all: values.all,
500
- targets,
501
- });
502
- printUpdateReport(result);
503
- const counts = updateResultCounts(result);
504
- succeeded += counts.succeeded;
505
- failed += counts.failed;
506
- }
507
- catch (err) {
508
- console.error(`${ui.err("error:")} ${err instanceof Error ? err.message : String(err)}`);
509
- failed += 1;
510
- }
511
- }
512
- if (failed === 0)
513
- return commandOutcome("success");
514
- return commandOutcome(succeeded > 0 ? "partial" : "failure", "dependency");
492
+ return runUpdateAcrossScopes(values, { source: positionals[0], targets });
515
493
  }
516
494
  case "remove":
517
495
  case "rm": {
@@ -309,6 +309,105 @@ function activateInstalled(opts, targets, installed, existingPlugins) {
309
309
  return parts.reduce((acc, result) => ({ agent: result.agent, affected: [...acc.affected, ...result.affected], skipped: acc.skipped && result.skipped }), { agent: agent.id, affected: [], skipped: true });
310
310
  });
311
311
  }
312
+ /**
313
+ * Resolve `opts.spec` to a local working directory plus an origin builder and
314
+ * cleanup, covering the three source kinds: a prepared checkout (remote
315
+ * marketplace update, already on disk), a local directory (no clone, no
316
+ * cleanup), or a GitHub source (clone to a temp dir, cleaned up by the caller).
317
+ */
318
+ function prepareSource(opts, parsed, sourceRef) {
319
+ if (opts.preparedSourceDir) {
320
+ const workRoot = resolve(opts.preparedSourceDir);
321
+ return {
322
+ workRoot,
323
+ resolvedRevision: opts.preparedResolvedRevision,
324
+ buildOrigin: (dir, dirOverride) => ({
325
+ type: "github",
326
+ repo: parsed.kind === "github" ? parsed.source : opts.spec,
327
+ ...(sourceRef ? { ref: sourceRef } : {}),
328
+ path: toPosix(relative(workRoot, dirOverride ?? dir)) || ".",
329
+ }),
330
+ cleanup: undefined,
331
+ };
332
+ }
333
+ if (parsed.kind === "local") {
334
+ const workRoot = resolve(parsed.dir);
335
+ return {
336
+ workRoot,
337
+ resolvedRevision: undefined,
338
+ buildOrigin: (dir, dirOverride) => ({ type: "local", path: resolve(dirOverride ?? dir) }),
339
+ cleanup: undefined,
340
+ };
341
+ }
342
+ const tmp = mkdtempSync(join(tmpdir(), "adg-clone-"));
343
+ try {
344
+ cloneGitHub({ ...parsed, ref: sourceRef }, tmp, { sparse: opts.sparse, runner: opts.gitRunner });
345
+ const resolvedRevision = gitRevision(tmp);
346
+ return {
347
+ workRoot: tmp,
348
+ resolvedRevision,
349
+ buildOrigin: (dir, dirOverride) => ({
350
+ type: "github",
351
+ repo: parsed.source,
352
+ ...(sourceRef ? { ref: sourceRef } : {}),
353
+ path: toPosix(relative(tmp, dirOverride ?? dir)) || ".",
354
+ }),
355
+ cleanup: () => rmSync(tmp, { recursive: true, force: true }),
356
+ };
357
+ }
358
+ catch (error) {
359
+ rmSync(tmp, { recursive: true, force: true });
360
+ throw error;
361
+ }
362
+ }
363
+ /**
364
+ * Synthesize a single Default DSL plugin from a source that holds no explicit
365
+ * ADG/native manifest: generate a manifest for the whole tree, stage a copy
366
+ * with it written in, and scan that staging copy as the sole candidate.
367
+ */
368
+ async function synthesizeDefaultDslPlugin(opts, parsed, workRoot, resolvedRevision) {
369
+ const defaultDescription = parsed.kind === "github" && !opts.preparedSourceDir && !opts.defaultDescription
370
+ ? await githubRepositoryDescription(parsed.source)
371
+ : undefined;
372
+ const structuralIdentity = opts.as ?? opts.structuralIdentity ?? (parsed.kind === "github" ? parsed.source : basename(workRoot));
373
+ const generated = resolveDefaultDsl(workRoot, {
374
+ name: structuralIdentity,
375
+ description: defaultDescription ?? opts.defaultDescription ?? structuralIdentity,
376
+ }, {
377
+ ...(parsed.kind === "github" && resolvedRevision ? { resolvedRevision } : {}),
378
+ });
379
+ const authorized = opts.authorizedComponents;
380
+ const unauthorizedRisk = generated.components.some((c) => (c === "hooks" || c === "mcp") && !authorized?.includes(c));
381
+ if (opts.nonInteractive && unauthorizedRisk && opts.only === undefined) {
382
+ throw new Error("default source exposes hooks or MCP; pass --only to explicitly authorize selected components");
383
+ }
384
+ const staging = mkdtempSync(join(tmpdir(), "adg-default-plugin-"));
385
+ let candidates;
386
+ try {
387
+ copyPluginDir(workRoot, staging);
388
+ writeJson(join(staging, ADG_MANIFEST_PATH), generated.manifest);
389
+ candidates = scanPlugins(staging);
390
+ }
391
+ catch (error) {
392
+ rmSync(staging, { recursive: true, force: true });
393
+ throw error;
394
+ }
395
+ return {
396
+ candidates,
397
+ converted: [],
398
+ structuralName: generated.manifest.name,
399
+ originDirOverride: workRoot,
400
+ definition: {
401
+ kind: "default-dsl/v1",
402
+ root: ".",
403
+ ...(opts.as ? { as: generated.manifest.name } : {}),
404
+ description: generated.manifest.description,
405
+ fingerprint: generated.fingerprint,
406
+ authorizedComponents: authorized ?? (opts.only ?? generated.components),
407
+ },
408
+ cleanup: () => rmSync(staging, { recursive: true, force: true }),
409
+ };
410
+ }
312
411
  /**
313
412
  * The unified install entrypoint. Treats any source as a marketplace: clone or
314
413
  * read it, discover every plugin (ADG plus reverse-adapted native), choose a
@@ -323,36 +422,12 @@ export async function addPlugins(opts) {
323
422
  if (parsed.kind === "github" && parsed.path) {
324
423
  throw new Error("GitHub subdirectory sources are not supported; define a marketplace and select with --plugin or --all");
325
424
  }
326
- let workRoot;
327
- let buildOrigin;
328
- let resolvedRevision;
329
- let cleanup;
425
+ const prepared = prepareSource(opts, parsed, sourceRef);
426
+ const { workRoot, buildOrigin, resolvedRevision } = prepared;
427
+ let cleanup = prepared.cleanup;
330
428
  let originDirOverride;
331
429
  let definition;
332
- let defaultDescription;
333
430
  let structuralName;
334
- if (opts.preparedSourceDir) {
335
- workRoot = resolve(opts.preparedSourceDir);
336
- resolvedRevision = opts.preparedResolvedRevision;
337
- buildOrigin = (dir) => ({ type: "github", repo: parsed.kind === "github" ? parsed.source : opts.spec, ...(sourceRef ? { ref: sourceRef } : {}), path: toPosix(relative(workRoot, originDirOverride ?? dir)) || "." });
338
- }
339
- else if (parsed.kind === "local") {
340
- workRoot = resolve(parsed.dir);
341
- buildOrigin = (dir) => ({ type: "local", path: resolve(originDirOverride ?? dir) });
342
- }
343
- else {
344
- const tmp = mkdtempSync(join(tmpdir(), "adg-clone-"));
345
- cleanup = () => rmSync(tmp, { recursive: true, force: true });
346
- cloneGitHub({ ...parsed, ref: sourceRef }, tmp, { sparse: opts.sparse, runner: opts.gitRunner });
347
- workRoot = tmp;
348
- resolvedRevision = gitRevision(tmp);
349
- buildOrigin = (dir) => ({
350
- type: "github",
351
- repo: parsed.source,
352
- ...(sourceRef ? { ref: sourceRef } : {}),
353
- path: toPosix(relative(tmp, originDirOverride ?? dir)) || ".",
354
- });
355
- }
356
431
  try {
357
432
  let { candidates, converted } = discoverPlugins(workRoot);
358
433
  const existingLock = readLock(lockPath(opts.pluginsDir));
@@ -365,32 +440,14 @@ export async function addPlugins(opts) {
365
440
  }
366
441
  }
367
442
  if (candidates.size === 0) {
368
- if (parsed.kind === "github" && !opts.preparedSourceDir && !opts.defaultDescription)
369
- defaultDescription = await githubRepositoryDescription(parsed.source);
370
- const structuralIdentity = opts.as ?? opts.structuralIdentity ?? (parsed.kind === "github" ? parsed.source : basename(workRoot));
371
- const generated = resolveDefaultDsl(workRoot, {
372
- name: structuralIdentity,
373
- description: defaultDescription ?? opts.defaultDescription ?? structuralIdentity,
374
- }, {
375
- ...(parsed.kind === "github" && resolvedRevision ? { resolvedRevision } : {}),
376
- });
377
- const authorized = opts.authorizedComponents;
378
- const unauthorizedRisk = generated.components.some((c) => (c === "hooks" || c === "mcp") && !authorized?.includes(c));
379
- if (opts.nonInteractive && unauthorizedRisk && opts.only === undefined) {
380
- throw new Error("default source exposes hooks or MCP; pass --only to explicitly authorize selected components");
381
- }
382
- const staging = mkdtempSync(join(tmpdir(), "adg-default-plugin-"));
383
- copyPluginDir(workRoot, staging);
384
- writeJson(join(staging, ADG_MANIFEST_PATH), generated.manifest);
385
- candidates = scanPlugins(staging);
386
- structuralName = generated.manifest.name;
387
- converted = [];
388
- originDirOverride = workRoot;
389
- definition = { kind: "default-dsl/v1", root: ".", ...(opts.as ? { as: generated.manifest.name } : {}), description: generated.manifest.description, fingerprint: generated.fingerprint, authorizedComponents: authorized ?? (opts.only ?? generated.components) };
390
- cleanup = (() => {
391
- const prior = cleanup;
392
- return () => { rmSync(staging, { recursive: true, force: true }); prior?.(); };
393
- })();
443
+ const synthesized = await synthesizeDefaultDslPlugin(opts, parsed, workRoot, resolvedRevision);
444
+ candidates = synthesized.candidates;
445
+ converted = synthesized.converted;
446
+ structuralName = synthesized.structuralName;
447
+ originDirOverride = synthesized.originDirOverride;
448
+ definition = synthesized.definition;
449
+ const priorCleanup = cleanup;
450
+ cleanup = () => { synthesized.cleanup(); priorCleanup?.(); };
394
451
  }
395
452
  const selected = structuralName ? [structuralName] : await selectPluginNames(opts, candidates, converted);
396
453
  // Resolve adapter targets after the plugin choice (lets a CLI agent picker
@@ -446,7 +503,7 @@ export async function addPlugins(opts) {
446
503
  installed.push(installPlugin({
447
504
  source: candidate.dir,
448
505
  pluginsDir: opts.pluginsDir,
449
- origin: buildOrigin(candidate.dir),
506
+ origin: buildOrigin(candidate.dir, originDirOverride),
450
507
  resolvedRevision,
451
508
  marketplaceName: opts.marketplaceName,
452
509
  targets,
@@ -161,10 +161,44 @@ export function sanitizePath(path) {
161
161
  return "";
162
162
  return "[PATH]";
163
163
  }
164
+ /**
165
+ * `adg <domain> <verb>` positionals safe to record verbatim: the top-level
166
+ * domains (`plugin`/`plugins`/`skill`/`skills`/`update`) plus every `plugins`
167
+ * verb and alias (`test/telemetry.test.ts` asserts this stays a superset of
168
+ * `PLUGIN_COMMANDS` and `PLUGIN_ALIASES` in `src/cli/index.ts`, so a new verb
169
+ * can't silently fall through to `[VALUE]`).
170
+ */
171
+ export const ADG_SAFE_POSITIONALS = new Set([
172
+ "plugin",
173
+ "plugins",
174
+ "skill",
175
+ "skills",
176
+ "update",
177
+ "add",
178
+ "list",
179
+ "status",
180
+ "remove",
181
+ "disable",
182
+ "enable",
183
+ "init",
184
+ "adapt",
185
+ "validate",
186
+ "inspect",
187
+ "link",
188
+ "unlink",
189
+ "sync",
190
+ "migrate",
191
+ "marketplace",
192
+ "cache",
193
+ "import-skills",
194
+ // PLUGIN_ALIASES
195
+ "rm",
196
+ "mp",
197
+ ]);
164
198
  export function sanitizeArgs(args) {
165
199
  const [executableName, ...rest] = args;
166
200
  const safePositionals = executableName === "adg"
167
- ? new Set(["plugin", "plugins", "skill", "skills", "update", "add", "remove", "sync", "list", "status", "inspect", "validate", "migrate", "cache", "marketplace", "link", "unlink", "enable", "disable", "import-skills"])
201
+ ? ADG_SAFE_POSITIONALS
168
202
  : executableName === "git"
169
203
  ? new Set(["clone", "fetch", "pull", "rev-parse", "ls-remote", "show", "init", "add", "commit", "sparse-checkout"])
170
204
  : executableName === "npm"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rbbtsn0w/adg",
3
- "version": "0.7.2-beta.1",
3
+ "version": "0.7.2-beta.2",
4
4
  "description": "Agent Directory Group (ADG) toolkit — two domains: plugins and skills.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -23,7 +23,7 @@
23
23
  },
24
24
  "scripts": {
25
25
  "adg": "node ./bin/adg.ts",
26
- "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json --noCheck && node -e \"require('fs').chmodSync('dist/bin/adg.js',0o755)\"",
26
+ "build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p tsconfig.build.json --noCheck && node -e \"require('fs').cpSync('src/adapters/antigravity-hook-runner.mjs','dist/src/adapters/antigravity-hook-runner.mjs')\" && node -e \"require('fs').chmodSync('dist/bin/adg.js',0o755)\"",
27
27
  "test": "node scripts/run-tests.mjs \"test/**/*.test.ts\" test/cache-sandbox.test.mjs",
28
28
  "test:codex-sandbox": "node --test test/codex-sandbox.test.mjs",
29
29
  "test:cache-sandbox": "node --test test/cache-sandbox.test.mjs",