superpowers-manager 0.2.0 → 0.4.0

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 (68) hide show
  1. package/README.md +340 -66
  2. package/dist/adapter-result.js +204 -0
  3. package/dist/adapter.js +690 -0
  4. package/dist/atomic.js +142 -0
  5. package/dist/cli-arguments.js +32 -0
  6. package/dist/cli.js +313 -0
  7. package/dist/codex-harness.js +271 -0
  8. package/dist/codex-json.js +89 -0
  9. package/dist/codex-prepare.js +199 -0
  10. package/dist/codex-presentation.js +259 -0
  11. package/dist/codex-state.js +78 -0
  12. package/dist/commands/context.js +1 -0
  13. package/dist/commands/install.js +291 -0
  14. package/dist/commands/pin.js +79 -0
  15. package/dist/commands/prepare.js +420 -0
  16. package/dist/commands/probe.js +257 -0
  17. package/dist/commands/track-latest.js +44 -0
  18. package/dist/commands/uninstall.js +217 -0
  19. package/dist/commands/unpin.js +95 -0
  20. package/dist/commands/update.js +79 -0
  21. package/dist/domain/fingerprint.js +4 -0
  22. package/dist/domain/refs.js +37 -0
  23. package/dist/effective-selection.js +123 -0
  24. package/dist/generated-plugin.js +748 -0
  25. package/dist/git.js +38 -0
  26. package/dist/harness.js +1 -0
  27. package/dist/hooks.js +290 -0
  28. package/dist/lifecycle.js +135 -0
  29. package/dist/manifest-overlay.js +125 -0
  30. package/dist/provenance.js +111 -0
  31. package/dist/python-json-format.js +83 -0
  32. package/dist/python-json.js +29 -0
  33. package/dist/python-text.js +74 -0
  34. package/dist/safe-path.js +137 -0
  35. package/dist/safety-error.js +10 -0
  36. package/dist/selection-state-cli.js +85 -0
  37. package/dist/selection-store.js +172 -0
  38. package/dist/selection.js +200 -0
  39. package/dist/status.js +24 -0
  40. package/dist/strict-json.js +248 -0
  41. package/dist/upstream-cli.js +110 -0
  42. package/dist/upstream-version.js +40 -0
  43. package/dist/upstream.js +253 -0
  44. package/dist/validate-generated-plugin-cli.js +118 -0
  45. package/dist/validator.js +317 -0
  46. package/dist/workspace.js +139 -0
  47. package/package.json +25 -4
  48. package/bin/superpowers-manager.js +0 -290
  49. package/scripts/adapters/codex/adapter +0 -603
  50. package/scripts/adapters/codex/lib.sh +0 -449
  51. package/scripts/adapters/codex/validate-generated-plugin.py +0 -314
  52. package/scripts/core/adapter.sh +0 -103
  53. package/scripts/core/common.sh +0 -59
  54. package/scripts/core/lifecycle.sh +0 -141
  55. package/scripts/core/provenance.sh +0 -135
  56. package/scripts/core/selection-state.py +0 -414
  57. package/scripts/core/selection.sh +0 -168
  58. package/scripts/core/status.sh +0 -27
  59. package/scripts/core/upstream.sh +0 -280
  60. package/scripts/core/validate-adapter-response.py +0 -284
  61. package/scripts/install +0 -59
  62. package/scripts/pin +0 -51
  63. package/scripts/prepare +0 -117
  64. package/scripts/probe +0 -82
  65. package/scripts/track-latest +0 -30
  66. package/scripts/uninstall +0 -35
  67. package/scripts/unpin +0 -41
  68. package/scripts/update +0 -34
@@ -0,0 +1,690 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { execFile } from "node:child_process";
3
+ import { constants } from "node:fs";
4
+ import { access, copyFile, mkdir, readFile, realpath, stat, writeFile, } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { delimiter, isAbsolute, join } from "node:path";
7
+ import { AdapterMessageLog, failureResult, successResult, } from "./adapter-result.js";
8
+ import { activePluginVersionFromJson, installedListingHas, marketplaceRootFromJson, } from "./codex-json.js";
9
+ import { oneLine } from "./cli-arguments.js";
10
+ import { installedCommitFromRoot, installedRootForVersion, pathsEqual, } from "./codex-state.js";
11
+ import { validateGeneratedPlugin } from "./generated-plugin.js";
12
+ import { classifyHooks, materializeHooks, readManifest, } from "./hooks.js";
13
+ import { applyManifestOverlay } from "./manifest-overlay.js";
14
+ import { readCodexBuildSource } from "./provenance.js";
15
+ import { isAcceptedSplitValue } from "./validate-generated-plugin-cli.js";
16
+ import { withWorkspace, workspaceRemovalFailure } from "./workspace.js";
17
+ const PLUGIN_ID = "superpowers@superpowers-manager";
18
+ const MARKETPLACE_NAME = "superpowers-manager";
19
+ const LEGACY_PLUGIN_ID = "superpowers@superpowers-wrapper";
20
+ const LEGACY_MARKETPLACE_NAME = "superpowers-wrapper";
21
+ class AdapterFailure extends Error {
22
+ code;
23
+ hints;
24
+ constructor(code, message, hints = []) {
25
+ super(message);
26
+ this.code = code;
27
+ this.hints = hints;
28
+ }
29
+ }
30
+ function fail(code, message, hints = []) {
31
+ throw new AdapterFailure(code, message, hints);
32
+ }
33
+ function parseFlags(argv, allowed) {
34
+ const values = {};
35
+ for (let index = 0; index < argv.length; index += 2) {
36
+ const flag = argv[index];
37
+ if (!allowed.includes(flag)) {
38
+ fail("invalid-arguments", `unknown flag: ${flag}`);
39
+ }
40
+ if (index + 1 >= argv.length) {
41
+ fail("invalid-arguments", `missing value for ${flag}`);
42
+ }
43
+ if (Object.hasOwn(values, flag)) {
44
+ fail("invalid-arguments", `duplicate flag: ${flag}`);
45
+ }
46
+ values[flag] = argv[index + 1];
47
+ }
48
+ for (const flag of allowed) {
49
+ if (!Object.hasOwn(values, flag)) {
50
+ fail("invalid-arguments", `missing required flag: ${flag}`);
51
+ }
52
+ }
53
+ return values;
54
+ }
55
+ function runCommand(file, args, env) {
56
+ // `git show ad56569a4c161e7b122967442e2b026eeb6395f6:scripts/core/common.sh:71::NODE_OPTIONS`
57
+ // is the system's only scrubbing site and it dies with scripts/ in 4c.
58
+ // Without this, NODE_OPTIONS would NEWLY reach codex.
59
+ // Preserves the property that was load-bearing — the child is clean — and
60
+ // drops the part that was never true, that the dispatcher scrubbed itself.
61
+ // Carried matrix row 11.
62
+ const childEnv = { ...env };
63
+ delete childEnv.NODE_OPTIONS;
64
+ delete childEnv.NODE_PATH;
65
+ return new Promise((resolve, reject) => {
66
+ execFile(file, [...args], {
67
+ encoding: "buffer",
68
+ env: childEnv,
69
+ maxBuffer: Infinity,
70
+ shell: false,
71
+ windowsHide: true,
72
+ }, (error, stdout, stderr) => {
73
+ if (error === null) {
74
+ resolve({ status: 0, signal: null, stdout, stderr });
75
+ return;
76
+ }
77
+ const failure = error;
78
+ if (typeof failure.code === "string") {
79
+ reject(failure);
80
+ return;
81
+ }
82
+ resolve({
83
+ status: typeof failure.code === "number" ? failure.code : null,
84
+ signal: failure.signal ?? null,
85
+ stdout,
86
+ stderr,
87
+ });
88
+ });
89
+ });
90
+ }
91
+ // Exported only so tests/unit/adapter.test.js can assert the env scrub
92
+ // directly. No production caller uses this name.
93
+ export { runCommand as runCommandForTest };
94
+ function commandFailed(result) {
95
+ return result.status !== 0;
96
+ }
97
+ // Exported only so its unit test can reach it. No integration test can cover
98
+ // it: on Linux glibc, `execvp`'s ENOEXEC falls back to `/bin/sh`, so the spawn
99
+ // still succeeds, and every other candidate errno is already peeled off by an
100
+ // `X_OK` check or the `ENOENT`/`EACCES` branch. See the test's own comment
101
+ // for the full analysis.
102
+ export function mapCodexLaunchFailure(cause, codexBin) {
103
+ const code = cause !== null && typeof cause === "object" && "code" in cause
104
+ ? String(cause.code)
105
+ : "";
106
+ if (code === "ENOENT" || code === "EACCES") {
107
+ fail("command-not-found", `required Codex command not found: ${codexBin}`);
108
+ }
109
+ // A bounded, enumerable, path-free errno is not the cause's message, so the no-interpolation rule
110
+ // does not reach it; unvalidated, String(cause.code) would put another module's free-form text
111
+ // in a sentence this module signs. appendBytes below escapes it, but escaping is not ownership:
112
+ // the rule governs whose wording the operator reads, not whether it reaches the terminal intact.
113
+ const detail = /^E[A-Z0-9]+$/.test(code) ? `: ${code}` : "";
114
+ return {
115
+ status: 1,
116
+ signal: null,
117
+ stdout: Buffer.alloc(0),
118
+ // Trailing newline matches how a real process writes stderr;
119
+ // `src/adapter-result.ts:133::appendBytes` splits on newlines and terminates the
120
+ // final chunk at end-of-buffer either way.
121
+ stderr: Buffer.from(`cannot launch Codex command ${codexBin}${detail}\n`, "utf8"),
122
+ };
123
+ }
124
+ async function runCodexCommand(codexBin, args, env) {
125
+ try {
126
+ return await runCommand(codexBin, args, env);
127
+ }
128
+ catch (cause) {
129
+ return mapCodexLaunchFailure(cause, codexBin);
130
+ }
131
+ }
132
+ function reportOrphanedWorkspace(log) {
133
+ return (path) => {
134
+ log.appendText("stderr", workspaceRemovalFailure(path));
135
+ };
136
+ }
137
+ async function mutationCommand(log, codexBin, args, env) {
138
+ const result = await runCodexCommand(codexBin, args, env);
139
+ log.appendBytes("stderr", result.stdout);
140
+ log.appendBytes("stderr", result.stderr);
141
+ return result;
142
+ }
143
+ async function listingCommand(log, codexBin, args, env) {
144
+ const result = await runCodexCommand(codexBin, args, env);
145
+ log.appendBytes("stderr", result.stderr);
146
+ return result;
147
+ }
148
+ async function executable(path) {
149
+ try {
150
+ await access(path, constants.X_OK);
151
+ return (await stat(path)).isFile();
152
+ }
153
+ catch {
154
+ return false;
155
+ }
156
+ }
157
+ async function commandAvailable(command, env) {
158
+ if (command.includes("/"))
159
+ return executable(command);
160
+ if (env.PATH === undefined)
161
+ return false;
162
+ for (const directory of env.PATH.split(delimiter)) {
163
+ if (await executable(join(directory, command))) {
164
+ return true;
165
+ }
166
+ }
167
+ return false;
168
+ }
169
+ async function requireCodex(codexBin, env) {
170
+ if (!(await commandAvailable(codexBin, env))) {
171
+ fail("command-not-found", `required Codex command not found: ${codexBin}`);
172
+ }
173
+ }
174
+ const BUILD_FLAGS = [
175
+ "--upstream-root",
176
+ "--candidate-root",
177
+ "--requested-ref",
178
+ "--resolved-ref",
179
+ "--commit",
180
+ "--manager-version",
181
+ "--upstream-manifest-version",
182
+ "--fallback-manifest",
183
+ ];
184
+ async function directoryExists(path) {
185
+ try {
186
+ return (await stat(path)).isDirectory();
187
+ }
188
+ catch {
189
+ return false;
190
+ }
191
+ }
192
+ async function fileExists(path) {
193
+ try {
194
+ return (await stat(path)).isFile();
195
+ }
196
+ catch {
197
+ return false;
198
+ }
199
+ }
200
+ async function runBuild(input, env, log) {
201
+ const { upstreamRoot, candidateRoot, fallbackManifest } = input;
202
+ if (!isAbsolute(upstreamRoot)) {
203
+ fail("invalid-arguments", "--upstream-root must be an absolute path");
204
+ }
205
+ if (!isAbsolute(candidateRoot)) {
206
+ fail("invalid-arguments", "--candidate-root must be an absolute path");
207
+ }
208
+ if (!(await directoryExists(upstreamRoot))) {
209
+ fail("invalid-arguments", `upstream root not found: ${upstreamRoot}`);
210
+ }
211
+ if (!(await directoryExists(candidateRoot))) {
212
+ fail("invalid-arguments", `candidate root not found: ${candidateRoot}`);
213
+ }
214
+ if (!(await fileExists(fallbackManifest))) {
215
+ fail("invalid-arguments", `fallback manifest not found: ${fallbackManifest}`);
216
+ }
217
+ let entered = false;
218
+ try {
219
+ return await withWorkspace(tmpdir(), "superpowers-manager.adapter-build.", async () => {
220
+ entered = true;
221
+ const candidateManifest = join(candidateRoot, ".codex-plugin/plugin.json");
222
+ const upstreamManifest = join(upstreamRoot, ".codex-plugin/plugin.json");
223
+ const manifestSource = (await fileExists(upstreamManifest))
224
+ ? "upstream"
225
+ : "fallback";
226
+ try {
227
+ await mkdir(join(candidateRoot, ".codex-plugin"), {
228
+ recursive: true,
229
+ });
230
+ await copyFile(manifestSource === "upstream" ? upstreamManifest : fallbackManifest, candidateManifest);
231
+ }
232
+ catch {
233
+ fail("build-failed", manifestSource === "upstream"
234
+ ? "cannot copy upstream manifest into candidate"
235
+ : "cannot copy fallback manifest into candidate");
236
+ }
237
+ let plan;
238
+ let sourceRoot;
239
+ let realCandidateRoot;
240
+ try {
241
+ sourceRoot = await realpath(upstreamRoot);
242
+ realCandidateRoot = await realpath(candidateRoot);
243
+ const manifest = await readManifest(candidateManifest);
244
+ plan = await classifyHooks(manifest, manifestSource, sourceRoot);
245
+ }
246
+ catch (cause) {
247
+ log.appendText("stderr", `hook classification failed: ${oneLine(cause)}`);
248
+ fail("build-failed", "failed to prepare upstream Codex hooks");
249
+ }
250
+ try {
251
+ await materializeHooks(plan, sourceRoot, realCandidateRoot);
252
+ }
253
+ catch (cause) {
254
+ log.appendText("stderr", `hook materialization failed: ${oneLine(cause)}`);
255
+ fail("build-failed", "failed to prepare upstream Codex hooks");
256
+ }
257
+ let source;
258
+ try {
259
+ // Decoded fatally, not leniently: the file can change between this read and `readManifest`'s read above.
260
+ const rawManifestBytes = await readFile(candidateManifest);
261
+ source = new TextDecoder("utf-8", {
262
+ fatal: true,
263
+ ignoreBOM: true,
264
+ }).decode(rawManifestBytes);
265
+ }
266
+ catch {
267
+ // Deliberately drops the cause. The Python interpolated the raw OSError here:
268
+ // `git show 0b6d50e1e9c688397285c6fa274dc8c9437d8ba3:scripts/adapters/codex/apply-manifest-overlay.py:42::read`,
269
+ // putting "[Errno 2] No such file or directory" on the operator's stream.
270
+ // The prefix is preserved; the errno leak is not.
271
+ log.appendText("stderr", `cannot read manifest JSON in ${candidateManifest}`);
272
+ fail("build-failed", "failed to apply manager manifest overlay");
273
+ }
274
+ let overlaid;
275
+ try {
276
+ overlaid = applyManifestOverlay(source, input.managerVersion, candidateManifest);
277
+ }
278
+ catch (cause) {
279
+ // applyManifestOverlay's own messages already name the manifest
280
+ // path — three are the frozen CPython wording, and the fourth (the
281
+ // numeric-overflow diagnostic, which has no CPython oracle wording
282
+ // to match) now carries the path via its own rewrap in
283
+ // src/manifest-overlay.ts. Emit as-is, with no added prefix — a
284
+ // prefix here would double up the path these messages already
285
+ // name.
286
+ log.appendText("stderr", oneLine(cause));
287
+ fail("build-failed", "failed to apply manager manifest overlay");
288
+ }
289
+ try {
290
+ await writeFile(candidateManifest, overlaid, "utf8");
291
+ }
292
+ catch {
293
+ log.appendText("stderr", `cannot write manifest JSON in ${candidateManifest}`);
294
+ fail("build-failed", "failed to apply manager manifest overlay");
295
+ }
296
+ try {
297
+ await copyFile(fallbackManifest, join(candidateRoot, ".codex-plugin/plugin.template.json"));
298
+ }
299
+ catch {
300
+ fail("build-failed", "cannot copy fallback manifest template into candidate");
301
+ }
302
+ let upstreamSource;
303
+ try {
304
+ upstreamSource = await readCodexBuildSource(join(candidateRoot, ".superpowers-upstream.json"));
305
+ }
306
+ catch {
307
+ fail("invalid-provenance", "candidate provenance is missing or invalid");
308
+ }
309
+ // The seven values the validator CLI would receive in split form:
310
+ // --plugin-root, --requested-ref, --resolved-ref, --commit,
311
+ // --manifest-version, --manifest-source, --upstream-manifest-version.
312
+ // The eighth, --source, is passed attached, where argparse accepts any
313
+ // dash-leading value, so it is deliberately absent here. Each value is
314
+ // paired with the ADAPTER-facing flag name to report: --manager-version
315
+ // (the CLI calls it --manifest-version) and --plugin-root /
316
+ // --manifest-source (derived, not user-supplied) deliberately differ
317
+ // from the validator CLI's own names, since the operator can only act
318
+ // on the adapter's surface.
319
+ const splitValues = [
320
+ { value: candidateRoot, name: "--plugin-root" },
321
+ { value: input.requestedRef, name: "--requested-ref" },
322
+ { value: input.resolvedRef, name: "--resolved-ref" },
323
+ { value: input.commit, name: "--commit" },
324
+ { value: input.managerVersion, name: "--manager-version" },
325
+ { value: manifestSource, name: "--manifest-source" },
326
+ {
327
+ value: input.upstreamManifestVersion,
328
+ name: "--upstream-manifest-version",
329
+ },
330
+ ];
331
+ const firstRejected = splitValues.find(({ value }) => !isAcceptedSplitValue(value));
332
+ if (firstRejected !== undefined) {
333
+ // Declared exception to message-record parity: argparse wrote usage
334
+ // records here; this guard precedes the call and writes a
335
+ // differently-worded record naming the rejected flag instead. The
336
+ // failure code and message are unchanged.
337
+ const text = "Generated plugin validation failed:\n" +
338
+ `- validator argument \`${firstRejected.name}\` has a dash-leading value the argument parser rejects\n`;
339
+ log.appendBytes("stderr", Buffer.from(text, "utf8"));
340
+ fail("generated-plugin-validation-failed", "built-in generated plugin validation failed");
341
+ }
342
+ let errors;
343
+ try {
344
+ errors = await validateGeneratedPlugin({
345
+ pluginRoot: candidateRoot,
346
+ source: upstreamSource,
347
+ requestedRef: input.requestedRef,
348
+ resolvedRef: input.resolvedRef,
349
+ commit: input.commit,
350
+ manifestVersion: input.managerVersion,
351
+ manifestSource,
352
+ upstreamManifestVersion: input.upstreamManifestVersion,
353
+ });
354
+ }
355
+ catch {
356
+ fail("generated-plugin-validation-failed", "built-in generated plugin validation failed");
357
+ }
358
+ if (errors.length > 0) {
359
+ // appendBytes, not appendText: one record per line, matching what
360
+ // mutationCommand writes from the subprocess streams.
361
+ const text = "Generated plugin validation failed:\n" +
362
+ errors.map((error) => `- ${error}\n`).join("");
363
+ log.appendBytes("stderr", Buffer.from(text, "utf8"));
364
+ fail("generated-plugin-validation-failed", "built-in generated plugin validation failed");
365
+ }
366
+ log.appendBytes("stdout", Buffer.from(`generated plugin validation passed: ${candidateRoot}\n`, "utf8"));
367
+ return {};
368
+ }, { onCleanupFailure: reportOrphanedWorkspace(log) });
369
+ }
370
+ catch (cause) {
371
+ if (!entered) {
372
+ fail("build-failed", `cannot create adapter build workspace under ${tmpdir()}`);
373
+ }
374
+ throw cause;
375
+ }
376
+ }
377
+ async function runInstall(packageRoot, env, log) {
378
+ if (!isAbsolute(packageRoot)) {
379
+ fail("invalid-arguments", "--package-root must be an absolute path");
380
+ }
381
+ if (!(await directoryExists(packageRoot))) {
382
+ fail("invalid-arguments", `package root not found: ${packageRoot}`);
383
+ }
384
+ const codexBin = env.SUPERPOWERS_CODEX || "codex";
385
+ const refreshMode = env.SUPERPOWERS_INSTALL_REFRESH_MODE || "add-only";
386
+ await requireCodex(codexBin, env);
387
+ if (refreshMode !== "add-only" && refreshMode !== "remove-add") {
388
+ fail("invalid-arguments", `unsupported SUPERPOWERS_INSTALL_REFRESH_MODE: ${refreshMode}`);
389
+ }
390
+ let entered = false;
391
+ try {
392
+ return await withWorkspace(tmpdir(), "superpowers-manager.adapter-install.", async () => {
393
+ entered = true;
394
+ const marketplaceList = await listingCommand(log, codexBin, ["plugin", "marketplace", "list", "--json"], env);
395
+ if (commandFailed(marketplaceList)) {
396
+ fail("install-failed", `cannot list Codex marketplaces via '${codexBin} plugin marketplace list --json'`);
397
+ }
398
+ let registeredRoot;
399
+ try {
400
+ registeredRoot = marketplaceRootFromJson(marketplaceList.stdout, MARKETPLACE_NAME);
401
+ }
402
+ catch {
403
+ fail("install-failed", `cannot parse output of '${codexBin} plugin marketplace list --json'`);
404
+ }
405
+ if (registeredRoot.length === 0) {
406
+ const added = await mutationCommand(log, codexBin, ["plugin", "marketplace", "add", packageRoot], env);
407
+ if (commandFailed(added)) {
408
+ fail("install-failed", `codex marketplace add failed for ${packageRoot}`);
409
+ }
410
+ }
411
+ else if (!(await pathsEqual(packageRoot, registeredRoot))) {
412
+ log.appendText("stdout", `marketplace ${MARKETPLACE_NAME} registered at ${registeredRoot}; re-registering at ${packageRoot}`);
413
+ const removed = await mutationCommand(log, codexBin, ["plugin", "marketplace", "remove", MARKETPLACE_NAME], env);
414
+ if (commandFailed(removed)) {
415
+ fail("install-failed", `codex marketplace remove failed for ${MARKETPLACE_NAME} (registered at ${registeredRoot})`);
416
+ }
417
+ const added = await mutationCommand(log, codexBin, ["plugin", "marketplace", "add", packageRoot], env);
418
+ if (commandFailed(added)) {
419
+ fail("install-failed", `marketplace ${MARKETPLACE_NAME} was removed but re-adding failed.`, [
420
+ `recover with: ${codexBin} plugin marketplace add ${packageRoot}`,
421
+ `previous root (last known good): ${registeredRoot}`,
422
+ ]);
423
+ }
424
+ }
425
+ if (refreshMode === "remove-add") {
426
+ await mutationCommand(log, codexBin, ["plugin", "remove", PLUGIN_ID], env);
427
+ }
428
+ const pluginAdded = await mutationCommand(log, codexBin, ["plugin", "add", PLUGIN_ID], env);
429
+ if (commandFailed(pluginAdded)) {
430
+ fail("install-failed", `codex plugin add failed for ${PLUGIN_ID}`);
431
+ }
432
+ return {
433
+ verification_hints: {
434
+ ...(refreshMode === "add-only"
435
+ ? {
436
+ mismatch: "retry with SUPERPOWERS_INSTALL_REFRESH_MODE=remove-add",
437
+ }
438
+ : {}),
439
+ missing: "verify with 'codex plugin list --json'.",
440
+ },
441
+ };
442
+ }, { onCleanupFailure: reportOrphanedWorkspace(log) });
443
+ }
444
+ catch (cause) {
445
+ if (!entered) {
446
+ fail("install-failed", `cannot create adapter install workspace under ${tmpdir()}`);
447
+ }
448
+ throw cause;
449
+ }
450
+ }
451
+ async function runUninstall(input, env, log) {
452
+ const { pluginPresent, marketplacePresent } = input;
453
+ const codexBin = env.SUPERPOWERS_CODEX || "codex";
454
+ await requireCodex(codexBin, env);
455
+ let entered = false;
456
+ try {
457
+ return await withWorkspace(tmpdir(), "superpowers-manager.adapter-uninstall.", async () => {
458
+ entered = true;
459
+ if (pluginPresent) {
460
+ const result = await mutationCommand(log, codexBin, ["plugin", "remove", PLUGIN_ID], env);
461
+ if (commandFailed(result)) {
462
+ fail("uninstall-failed", `codex plugin remove failed for ${PLUGIN_ID}`);
463
+ }
464
+ log.appendText("stdout", `removed plugin ${PLUGIN_ID}`);
465
+ }
466
+ else {
467
+ log.appendText("stdout", "plugin not installed; skipping");
468
+ }
469
+ if (marketplacePresent) {
470
+ const result = await mutationCommand(log, codexBin, ["plugin", "marketplace", "remove", MARKETPLACE_NAME], env);
471
+ if (commandFailed(result)) {
472
+ fail("uninstall-failed", `codex plugin marketplace remove failed for ${MARKETPLACE_NAME}`);
473
+ }
474
+ log.appendText("stdout", `removed marketplace ${MARKETPLACE_NAME}`);
475
+ }
476
+ else {
477
+ log.appendText("stdout", "marketplace not registered; skipping");
478
+ }
479
+ return {};
480
+ }, { onCleanupFailure: reportOrphanedWorkspace(log) });
481
+ }
482
+ catch (cause) {
483
+ if (!entered) {
484
+ fail("uninstall-failed", `cannot create adapter uninstall workspace under ${tmpdir()}`);
485
+ }
486
+ throw cause;
487
+ }
488
+ }
489
+ async function runInspect(view, env, log) {
490
+ if (view === "update-control") {
491
+ return { view: "update-control", update_control: "managed" };
492
+ }
493
+ if (view === "fingerprint") {
494
+ const codexBin = env.SUPERPOWERS_CODEX || "codex";
495
+ await requireCodex(codexBin, env);
496
+ let entered = false;
497
+ try {
498
+ return await withWorkspace(tmpdir(), "superpowers-manager.adapter-fingerprint.", async () => {
499
+ entered = true;
500
+ const listing = await listingCommand(log, codexBin, ["plugin", "list", "--json"], env);
501
+ if (commandFailed(listing)) {
502
+ fail("inspect-failed", `cannot list Codex plugins via '${codexBin} plugin list --json'`);
503
+ }
504
+ let activeVersion;
505
+ try {
506
+ activeVersion = activePluginVersionFromJson(listing.stdout, PLUGIN_ID);
507
+ }
508
+ catch {
509
+ fail("inspect-failed", `cannot parse output of '${codexBin} plugin list --json'`);
510
+ }
511
+ if (activeVersion.length === 0) {
512
+ return { view: "fingerprint", fingerprint: null };
513
+ }
514
+ let searchRoot = env.SUPERPOWERS_INSTALLED_SEARCH_ROOT;
515
+ if (!searchRoot) {
516
+ if (env.HOME === undefined) {
517
+ fail("inspect-failed", "cannot inspect active Codex plugin fingerprint without HOME");
518
+ }
519
+ searchRoot = join(env.HOME || "/", ".codex");
520
+ }
521
+ const activeRoot = installedRootForVersion(searchRoot, MARKETPLACE_NAME, "superpowers", activeVersion);
522
+ const fingerprint = await installedCommitFromRoot(activeRoot);
523
+ if (fingerprint.length === 0) {
524
+ fail("inspect-failed", `cannot inspect active Codex plugin fingerprint under ${activeRoot}`);
525
+ }
526
+ return { view: "fingerprint", fingerprint };
527
+ }, { onCleanupFailure: reportOrphanedWorkspace(log) });
528
+ }
529
+ catch (cause) {
530
+ if (!entered) {
531
+ fail("inspect-failed", `cannot create adapter fingerprint workspace under ${tmpdir()}`);
532
+ }
533
+ throw cause;
534
+ }
535
+ }
536
+ if (view === "ownership") {
537
+ const codexBin = env.SUPERPOWERS_CODEX || "codex";
538
+ await requireCodex(codexBin, env);
539
+ let entered = false;
540
+ try {
541
+ return await withWorkspace(tmpdir(), "superpowers-manager.adapter-inspect.", async () => {
542
+ entered = true;
543
+ const plugins = await listingCommand(log, codexBin, ["plugin", "list", "--json"], env);
544
+ if (commandFailed(plugins)) {
545
+ fail("inspect-failed", `cannot list Codex plugins via '${codexBin} plugin list --json'`);
546
+ }
547
+ const marketplaces = await listingCommand(log, codexBin, ["plugin", "marketplace", "list", "--json"], env);
548
+ if (commandFailed(marketplaces)) {
549
+ fail("inspect-failed", `cannot list Codex marketplaces via '${codexBin} plugin marketplace list --json'`);
550
+ }
551
+ let managerPlugin;
552
+ let legacyPlugin;
553
+ let managerMarketplace;
554
+ let legacyMarketplace;
555
+ try {
556
+ managerPlugin = installedListingHas(plugins.stdout, "installed", "pluginId", PLUGIN_ID);
557
+ legacyPlugin = installedListingHas(plugins.stdout, "installed", "pluginId", LEGACY_PLUGIN_ID);
558
+ }
559
+ catch {
560
+ fail("inspect-failed", `cannot parse output of '${codexBin} plugin list --json'`);
561
+ }
562
+ try {
563
+ managerMarketplace = installedListingHas(marketplaces.stdout, "marketplaces", "name", MARKETPLACE_NAME);
564
+ legacyMarketplace = installedListingHas(marketplaces.stdout, "marketplaces", "name", LEGACY_MARKETPLACE_NAME);
565
+ }
566
+ catch {
567
+ fail("inspect-failed", `cannot parse output of '${codexBin} plugin marketplace list --json'`);
568
+ }
569
+ const managerPresent = managerPlugin || managerMarketplace;
570
+ const legacyPresent = legacyPlugin || legacyMarketplace;
571
+ return {
572
+ view: "ownership",
573
+ resources: {
574
+ plugin: managerPlugin,
575
+ marketplace: managerMarketplace,
576
+ },
577
+ legacy_resources: {
578
+ plugin: legacyPlugin,
579
+ marketplace: legacyMarketplace,
580
+ },
581
+ identity_state: managerPresent
582
+ ? legacyPresent
583
+ ? "both"
584
+ : "manager"
585
+ : legacyPresent
586
+ ? "legacy"
587
+ : "neither",
588
+ };
589
+ }, { onCleanupFailure: reportOrphanedWorkspace(log) });
590
+ }
591
+ catch (cause) {
592
+ if (!entered) {
593
+ fail("inspect-failed", `cannot create adapter inspect workspace under ${tmpdir()}`);
594
+ }
595
+ throw cause;
596
+ }
597
+ }
598
+ const unsupportedView = view;
599
+ fail("invalid-arguments", `unsupported inspect view: ${unsupportedView}`);
600
+ }
601
+ async function runCodexOperation(operation, context, execute) {
602
+ const env = { ...process.env, ...context.env };
603
+ const log = new AdapterMessageLog();
604
+ try {
605
+ const result = await execute(env, log);
606
+ return successResult(operation, result, log.snapshot());
607
+ }
608
+ catch (cause) {
609
+ if (cause instanceof AdapterFailure) {
610
+ return failureResult(operation, cause.code, cause.message, cause.hints, log.snapshot());
611
+ }
612
+ throw cause;
613
+ }
614
+ }
615
+ export function codexBuild(input, context) {
616
+ return runCodexOperation("build", context, (env, log) => runBuild(input, env, log));
617
+ }
618
+ export function codexInstall(packageRoot, context) {
619
+ return runCodexOperation("install", context, (env, log) => runInstall(packageRoot, env, log));
620
+ }
621
+ export function codexRemove(input, context) {
622
+ return runCodexOperation("uninstall", context, (env, log) => runUninstall(input, env, log));
623
+ }
624
+ export function codexInspect(view, context) {
625
+ return runCodexOperation("inspect", context, (env, log) => runInspect(view, env, log));
626
+ }
627
+ export async function runAdapter(argv, context) {
628
+ const rawOperation = argv[0];
629
+ const operation = rawOperation || "adapter";
630
+ const args = argv.slice(1);
631
+ try {
632
+ if (rawOperation === undefined || rawOperation.length === 0) {
633
+ fail("invalid-arguments", "missing adapter operation");
634
+ }
635
+ else if (operation === "build") {
636
+ const flags = parseFlags(args, BUILD_FLAGS);
637
+ return codexBuild({
638
+ upstreamRoot: flags["--upstream-root"],
639
+ candidateRoot: flags["--candidate-root"],
640
+ requestedRef: flags["--requested-ref"],
641
+ resolvedRef: flags["--resolved-ref"],
642
+ commit: flags["--commit"],
643
+ managerVersion: flags["--manager-version"],
644
+ upstreamManifestVersion: flags["--upstream-manifest-version"],
645
+ fallbackManifest: flags["--fallback-manifest"],
646
+ }, context);
647
+ }
648
+ else if (operation === "install") {
649
+ const flags = parseFlags(args, ["--package-root"]);
650
+ return codexInstall(flags["--package-root"], context);
651
+ }
652
+ else if (operation === "uninstall") {
653
+ const flags = parseFlags(args, [
654
+ "--plugin-present",
655
+ "--marketplace-present",
656
+ ]);
657
+ const pluginPresent = flags["--plugin-present"];
658
+ const marketplacePresent = flags["--marketplace-present"];
659
+ if (pluginPresent !== "true" && pluginPresent !== "false") {
660
+ fail("invalid-arguments", "--plugin-present must be true or false");
661
+ }
662
+ if (marketplacePresent !== "true" && marketplacePresent !== "false") {
663
+ fail("invalid-arguments", "--marketplace-present must be true or false");
664
+ }
665
+ return codexRemove({
666
+ pluginPresent: pluginPresent === "true",
667
+ marketplacePresent: marketplacePresent === "true",
668
+ }, context);
669
+ }
670
+ else if (operation === "inspect") {
671
+ const flags = parseFlags(args, ["--view"]);
672
+ const view = flags["--view"];
673
+ if (view !== "ownership" &&
674
+ view !== "update-control" &&
675
+ view !== "fingerprint") {
676
+ fail("invalid-arguments", `unsupported inspect view: ${view}`);
677
+ }
678
+ return codexInspect(view, context);
679
+ }
680
+ else {
681
+ fail("unsupported-operation", `unsupported adapter operation: ${operation}`);
682
+ }
683
+ }
684
+ catch (cause) {
685
+ if (cause instanceof AdapterFailure) {
686
+ return failureResult(operation, cause.code, cause.message, cause.hints, []);
687
+ }
688
+ throw cause;
689
+ }
690
+ }