superpowers-manager 0.5.2 → 0.6.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.
@@ -2,13 +2,12 @@ import { Buffer } from "node:buffer";
2
2
  import { execFile } from "node:child_process";
3
3
  import { constants } from "node:fs";
4
4
  import { access, copyFile, mkdir, readFile, realpath, stat, writeFile, } from "node:fs/promises";
5
- import { tmpdir } from "node:os";
6
5
  import { delimiter, isAbsolute, join } from "node:path";
7
- import { AdapterMessageLog, failureResult, successResult, } from "../../adapter-result.js";
6
+ import { AdapterMessageLog, failureResult, hasTerminalControl, successResult, } from "../../adapter-result.js";
8
7
  import { activePluginVersionFromJson, codexInstalledPluginsFromJson, installedListingHas, marketplaceRootFromJson, } from "./json.js";
9
8
  import { CODEX_LEGACY_PLUGIN_ID, CODEX_MANAGER_PLUGIN_ID, inspectCodexConflicts, } from "./conflicts.js";
10
9
  import { oneLine } from "../../cli-arguments.js";
11
- import { installedCommitFromRoot, installedRootForVersion, pathsEqual, } from "./state.js";
10
+ import { installedRootForVersion, pathsEqual } from "./state.js";
12
11
  import { codexHome } from "./paths.js";
13
12
  import { readCodexStoredState } from "./stored-state.js";
14
13
  import { validateGeneratedPlugin } from "./generated-plugin.js";
@@ -16,7 +15,8 @@ import { classifyHooks, materializeHooks, readManifest, } from "./hooks.js";
16
15
  import { applyManifestOverlay } from "./manifest-overlay.js";
17
16
  import { readCodexBuildSource } from "../../provenance.js";
18
17
  import { isAcceptedSplitValue } from "../../validate-generated-plugin-cli.js";
19
- import { withWorkspace, workspaceRemovalFailure } from "../../workspace.js";
18
+ import { codexControlInspection, codexOwnershipInspection, } from "./lifecycle.js";
19
+ import { codexInstallReceipt } from "./presentation.js";
20
20
  const PLUGIN_ID = CODEX_MANAGER_PLUGIN_ID;
21
21
  const MARKETPLACE_NAME = "superpowers-manager";
22
22
  const LEGACY_PLUGIN_ID = CODEX_LEGACY_PLUGIN_ID;
@@ -39,28 +39,6 @@ class AdapterFailure extends Error {
39
39
  function fail(code, message, hints = []) {
40
40
  throw new AdapterFailure(code, message, hints);
41
41
  }
42
- function parseFlags(argv, allowed) {
43
- const values = {};
44
- for (let index = 0; index < argv.length; index += 2) {
45
- const flag = argv[index];
46
- if (!allowed.includes(flag)) {
47
- fail("invalid-arguments", `unknown flag: ${flag}`);
48
- }
49
- if (index + 1 >= argv.length) {
50
- fail("invalid-arguments", `missing value for ${flag}`);
51
- }
52
- if (Object.hasOwn(values, flag)) {
53
- fail("invalid-arguments", `duplicate flag: ${flag}`);
54
- }
55
- values[flag] = argv[index + 1];
56
- }
57
- for (const flag of allowed) {
58
- if (!Object.hasOwn(values, flag)) {
59
- fail("invalid-arguments", `missing required flag: ${flag}`);
60
- }
61
- }
62
- return values;
63
- }
64
42
  function runCommand(file, args, env) {
65
43
  // `git show ad56569a4c161e7b122967442e2b026eeb6395f6:scripts/core/common.sh:71::NODE_OPTIONS`
66
44
  // is the system's only scrubbing site and it dies with scripts/ in 4c.
@@ -146,11 +124,6 @@ async function runCodexCommand(codexBin, args, env) {
146
124
  return mapCodexLaunchFailure(cause, codexBin);
147
125
  }
148
126
  }
149
- function reportOrphanedWorkspace(log) {
150
- return (path) => {
151
- log.appendText("stderr", workspaceRemovalFailure(path));
152
- };
153
- }
154
127
  async function mutationCommand(log, codexBin, args, env) {
155
128
  const result = await runCodexCommand(codexBin, args, env);
156
129
  log.appendBytes("stderr", result.stdout);
@@ -188,16 +161,6 @@ async function requireCodex(codexBin, env) {
188
161
  fail("command-not-found", `required Codex command not found: ${codexBin}`);
189
162
  }
190
163
  }
191
- const BUILD_FLAGS = [
192
- "--upstream-root",
193
- "--candidate-root",
194
- "--requested-ref",
195
- "--resolved-ref",
196
- "--commit",
197
- "--manager-version",
198
- "--upstream-manifest-version",
199
- "--fallback-manifest",
200
- ];
201
164
  async function directoryExists(path) {
202
165
  try {
203
166
  return (await stat(path)).isDirectory();
@@ -231,165 +194,153 @@ async function runBuild(input, env, log) {
231
194
  if (!(await fileExists(fallbackManifest))) {
232
195
  fail("invalid-arguments", `fallback manifest not found: ${fallbackManifest}`);
233
196
  }
234
- let entered = false;
197
+ const candidateManifest = join(candidateRoot, ".codex-plugin/plugin.json");
198
+ const upstreamManifest = join(upstreamRoot, ".codex-plugin/plugin.json");
199
+ const manifestSource = (await fileExists(upstreamManifest))
200
+ ? "upstream"
201
+ : "fallback";
235
202
  try {
236
- return await withWorkspace(tmpdir(), "superpowers-manager.adapter-build.", async () => {
237
- entered = true;
238
- const candidateManifest = join(candidateRoot, ".codex-plugin/plugin.json");
239
- const upstreamManifest = join(upstreamRoot, ".codex-plugin/plugin.json");
240
- const manifestSource = (await fileExists(upstreamManifest))
241
- ? "upstream"
242
- : "fallback";
243
- try {
244
- await mkdir(join(candidateRoot, ".codex-plugin"), {
245
- recursive: true,
246
- });
247
- await copyFile(manifestSource === "upstream" ? upstreamManifest : fallbackManifest, candidateManifest);
248
- }
249
- catch {
250
- fail("build-failed", manifestSource === "upstream"
251
- ? "cannot copy upstream manifest into candidate"
252
- : "cannot copy fallback manifest into candidate");
253
- }
254
- let plan;
255
- let sourceRoot;
256
- let realCandidateRoot;
257
- try {
258
- sourceRoot = await realpath(upstreamRoot);
259
- realCandidateRoot = await realpath(candidateRoot);
260
- const manifest = await readManifest(candidateManifest);
261
- plan = await classifyHooks(manifest, manifestSource, sourceRoot);
262
- }
263
- catch (cause) {
264
- log.appendText("stderr", `hook classification failed: ${oneLine(cause)}`);
265
- fail("build-failed", "failed to prepare upstream Codex hooks");
266
- }
267
- try {
268
- await materializeHooks(plan, sourceRoot, realCandidateRoot);
269
- }
270
- catch (cause) {
271
- log.appendText("stderr", `hook materialization failed: ${oneLine(cause)}`);
272
- fail("build-failed", "failed to prepare upstream Codex hooks");
273
- }
274
- let source;
275
- try {
276
- // Decoded fatally, not leniently: the file can change between this read and `readManifest`'s read above.
277
- const rawManifestBytes = await readFile(candidateManifest);
278
- source = new TextDecoder("utf-8", {
279
- fatal: true,
280
- ignoreBOM: true,
281
- }).decode(rawManifestBytes);
282
- }
283
- catch {
284
- // Deliberately drops the cause. The Python interpolated the raw OSError here:
285
- // `git show 0b6d50e1e9c688397285c6fa274dc8c9437d8ba3:scripts/adapters/codex/apply-manifest-overlay.py:42::read`,
286
- // putting "[Errno 2] No such file or directory" on the operator's stream.
287
- // The prefix is preserved; the errno leak is not.
288
- log.appendText("stderr", `cannot read manifest JSON in ${candidateManifest}`);
289
- fail("build-failed", "failed to apply manager manifest overlay");
290
- }
291
- let overlaid;
292
- try {
293
- overlaid = applyManifestOverlay(source, input.managerVersion, candidateManifest);
294
- }
295
- catch (cause) {
296
- // applyManifestOverlay's own messages already name the manifest
297
- // path — three are the frozen CPython wording, and the fourth (the
298
- // numeric-overflow diagnostic, which has no CPython oracle wording
299
- // to match) now carries the path via its own rewrap in
300
- // src/harnesses/codex/manifest-overlay.ts. Emit as-is, with no added prefix — a
301
- // prefix here would double up the path these messages already
302
- // name.
303
- log.appendText("stderr", oneLine(cause));
304
- fail("build-failed", "failed to apply manager manifest overlay");
305
- }
306
- try {
307
- await writeFile(candidateManifest, overlaid, "utf8");
308
- }
309
- catch {
310
- log.appendText("stderr", `cannot write manifest JSON in ${candidateManifest}`);
311
- fail("build-failed", "failed to apply manager manifest overlay");
312
- }
313
- try {
314
- await copyFile(fallbackManifest, join(candidateRoot, ".codex-plugin/plugin.template.json"));
315
- }
316
- catch {
317
- fail("build-failed", "cannot copy fallback manifest template into candidate");
318
- }
319
- let upstreamSource;
320
- try {
321
- upstreamSource = await readCodexBuildSource(join(candidateRoot, ".superpowers-upstream.json"));
322
- }
323
- catch {
324
- fail("invalid-provenance", "candidate provenance is missing or invalid");
325
- }
326
- // The seven values the validator CLI would receive in split form:
327
- // --plugin-root, --requested-ref, --resolved-ref, --commit,
328
- // --manifest-version, --manifest-source, --upstream-manifest-version.
329
- // The eighth, --source, is passed attached, where argparse accepts any
330
- // dash-leading value, so it is deliberately absent here. Each value is
331
- // paired with the ADAPTER-facing flag name to report: --manager-version
332
- // (the CLI calls it --manifest-version) and --plugin-root /
333
- // --manifest-source (derived, not user-supplied) deliberately differ
334
- // from the validator CLI's own names, since the operator can only act
335
- // on the adapter's surface.
336
- const splitValues = [
337
- { value: candidateRoot, name: "--plugin-root" },
338
- { value: input.requestedRef, name: "--requested-ref" },
339
- { value: input.resolvedRef, name: "--resolved-ref" },
340
- { value: input.commit, name: "--commit" },
341
- { value: input.managerVersion, name: "--manager-version" },
342
- { value: manifestSource, name: "--manifest-source" },
343
- {
344
- value: input.upstreamManifestVersion,
345
- name: "--upstream-manifest-version",
346
- },
347
- ];
348
- const firstRejected = splitValues.find(({ value }) => !isAcceptedSplitValue(value));
349
- if (firstRejected !== undefined) {
350
- // Declared exception to message-record parity: argparse wrote usage
351
- // records here; this guard precedes the call and writes a
352
- // differently-worded record naming the rejected flag instead. The
353
- // failure code and message are unchanged.
354
- const text = "Generated plugin validation failed:\n" +
355
- `- validator argument \`${firstRejected.name}\` has a dash-leading value the argument parser rejects\n`;
356
- log.appendBytes("stderr", Buffer.from(text, "utf8"));
357
- fail("generated-plugin-validation-failed", "built-in generated plugin validation failed");
358
- }
359
- let errors;
360
- try {
361
- errors = await validateGeneratedPlugin({
362
- pluginRoot: candidateRoot,
363
- source: upstreamSource,
364
- requestedRef: input.requestedRef,
365
- resolvedRef: input.resolvedRef,
366
- commit: input.commit,
367
- manifestVersion: input.managerVersion,
368
- manifestSource,
369
- upstreamManifestVersion: input.upstreamManifestVersion,
370
- });
371
- }
372
- catch {
373
- fail("generated-plugin-validation-failed", "built-in generated plugin validation failed");
374
- }
375
- if (errors.length > 0) {
376
- // appendBytes, not appendText: one record per line, matching what
377
- // mutationCommand writes from the subprocess streams.
378
- const text = "Generated plugin validation failed:\n" +
379
- errors.map((error) => `- ${error}\n`).join("");
380
- log.appendBytes("stderr", Buffer.from(text, "utf8"));
381
- fail("generated-plugin-validation-failed", "built-in generated plugin validation failed");
382
- }
383
- log.appendBytes("stdout", Buffer.from(`generated plugin validation passed: ${candidateRoot}\n`, "utf8"));
384
- return {};
385
- }, { onCleanupFailure: reportOrphanedWorkspace(log) });
203
+ await mkdir(join(candidateRoot, ".codex-plugin"), {
204
+ recursive: true,
205
+ });
206
+ await copyFile(manifestSource === "upstream" ? upstreamManifest : fallbackManifest, candidateManifest);
207
+ }
208
+ catch {
209
+ fail("build-failed", manifestSource === "upstream"
210
+ ? "cannot copy upstream manifest into candidate"
211
+ : "cannot copy fallback manifest into candidate");
212
+ }
213
+ let plan;
214
+ let sourceRoot;
215
+ let realCandidateRoot;
216
+ try {
217
+ sourceRoot = await realpath(upstreamRoot);
218
+ realCandidateRoot = await realpath(candidateRoot);
219
+ const manifest = await readManifest(candidateManifest);
220
+ plan = await classifyHooks(manifest, manifestSource, sourceRoot);
386
221
  }
387
222
  catch (cause) {
388
- if (!entered) {
389
- fail("build-failed", `cannot create adapter build workspace under ${tmpdir()}`);
390
- }
391
- throw cause;
223
+ log.appendText("stderr", `hook classification failed: ${oneLine(cause)}`);
224
+ fail("build-failed", "failed to prepare upstream Codex hooks");
225
+ }
226
+ try {
227
+ await materializeHooks(plan, sourceRoot, realCandidateRoot);
228
+ }
229
+ catch (cause) {
230
+ log.appendText("stderr", `hook materialization failed: ${oneLine(cause)}`);
231
+ fail("build-failed", "failed to prepare upstream Codex hooks");
232
+ }
233
+ let source;
234
+ try {
235
+ // Decoded fatally, not leniently: the file can change between this read and `readManifest`'s read above.
236
+ const rawManifestBytes = await readFile(candidateManifest);
237
+ source = new TextDecoder("utf-8", {
238
+ fatal: true,
239
+ ignoreBOM: true,
240
+ }).decode(rawManifestBytes);
241
+ }
242
+ catch {
243
+ // Deliberately drops the cause. The Python interpolated the raw OSError here:
244
+ // `git show 0b6d50e1e9c688397285c6fa274dc8c9437d8ba3:scripts/adapters/codex/apply-manifest-overlay.py:42::read`,
245
+ // putting "[Errno 2] No such file or directory" on the operator's stream.
246
+ // The prefix is preserved; the errno leak is not.
247
+ log.appendText("stderr", `cannot read manifest JSON in ${candidateManifest}`);
248
+ fail("build-failed", "failed to apply manager manifest overlay");
249
+ }
250
+ let overlaid;
251
+ try {
252
+ overlaid = applyManifestOverlay(source, input.managerVersion, candidateManifest);
253
+ }
254
+ catch (cause) {
255
+ // applyManifestOverlay's own messages already name the manifest
256
+ // path — three are the frozen CPython wording, and the fourth (the
257
+ // numeric-overflow diagnostic, which has no CPython oracle wording
258
+ // to match) now carries the path via its own rewrap in
259
+ // src/harnesses/codex/manifest-overlay.ts. Emit as-is, with no added prefix — a
260
+ // prefix here would double up the path these messages already
261
+ // name.
262
+ log.appendText("stderr", oneLine(cause));
263
+ fail("build-failed", "failed to apply manager manifest overlay");
264
+ }
265
+ try {
266
+ await writeFile(candidateManifest, overlaid, "utf8");
267
+ }
268
+ catch {
269
+ log.appendText("stderr", `cannot write manifest JSON in ${candidateManifest}`);
270
+ fail("build-failed", "failed to apply manager manifest overlay");
392
271
  }
272
+ try {
273
+ await copyFile(fallbackManifest, join(candidateRoot, ".codex-plugin/plugin.template.json"));
274
+ }
275
+ catch {
276
+ fail("build-failed", "cannot copy fallback manifest template into candidate");
277
+ }
278
+ let upstreamSource;
279
+ try {
280
+ upstreamSource = await readCodexBuildSource(join(candidateRoot, ".superpowers-upstream.json"));
281
+ }
282
+ catch {
283
+ fail("invalid-provenance", "candidate provenance is missing or invalid");
284
+ }
285
+ // The seven values the validator CLI would receive in split form:
286
+ // --plugin-root, --requested-ref, --resolved-ref, --commit,
287
+ // --manifest-version, --manifest-source, --upstream-manifest-version.
288
+ // The eighth, --source, is passed attached, where argparse accepts any
289
+ // dash-leading value, so it is deliberately absent here. Each value is
290
+ // paired with the ADAPTER-facing flag name to report: --manager-version
291
+ // (the CLI calls it --manifest-version) and --plugin-root /
292
+ // --manifest-source (derived, not user-supplied) deliberately differ
293
+ // from the validator CLI's own names, since the operator can only act
294
+ // on the adapter's surface.
295
+ const splitValues = [
296
+ { value: candidateRoot, name: "--plugin-root" },
297
+ { value: input.requestedRef, name: "--requested-ref" },
298
+ { value: input.resolvedRef, name: "--resolved-ref" },
299
+ { value: input.commit, name: "--commit" },
300
+ { value: input.managerVersion, name: "--manager-version" },
301
+ { value: manifestSource, name: "--manifest-source" },
302
+ {
303
+ value: input.upstreamManifestVersion,
304
+ name: "--upstream-manifest-version",
305
+ },
306
+ ];
307
+ const firstRejected = splitValues.find(({ value }) => !isAcceptedSplitValue(value));
308
+ if (firstRejected !== undefined) {
309
+ // Declared exception to message-record parity: argparse wrote usage
310
+ // records here; this guard precedes the call and writes a
311
+ // differently-worded record naming the rejected flag instead. The
312
+ // failure code and message are unchanged.
313
+ const text = "Generated plugin validation failed:\n" +
314
+ `- validator argument \`${firstRejected.name}\` has a dash-leading value the argument parser rejects\n`;
315
+ log.appendBytes("stderr", Buffer.from(text, "utf8"));
316
+ fail("generated-plugin-validation-failed", "built-in generated plugin validation failed");
317
+ }
318
+ let errors;
319
+ try {
320
+ errors = await validateGeneratedPlugin({
321
+ pluginRoot: candidateRoot,
322
+ source: upstreamSource,
323
+ requestedRef: input.requestedRef,
324
+ resolvedRef: input.resolvedRef,
325
+ commit: input.commit,
326
+ manifestVersion: input.managerVersion,
327
+ manifestSource,
328
+ upstreamManifestVersion: input.upstreamManifestVersion,
329
+ });
330
+ }
331
+ catch {
332
+ fail("generated-plugin-validation-failed", "built-in generated plugin validation failed");
333
+ }
334
+ if (errors.length > 0) {
335
+ // appendBytes, not appendText: one record per line, matching what
336
+ // mutationCommand writes from the subprocess streams.
337
+ const text = "Generated plugin validation failed:\n" +
338
+ errors.map((error) => `- ${error}\n`).join("");
339
+ log.appendBytes("stderr", Buffer.from(text, "utf8"));
340
+ fail("generated-plugin-validation-failed", "built-in generated plugin validation failed");
341
+ }
342
+ log.appendBytes("stdout", Buffer.from(`generated plugin validation passed: ${candidateRoot}\n`, "utf8"));
343
+ return {};
393
344
  }
394
345
  async function runInstall(packageRoot, env, log) {
395
346
  if (!isAbsolute(packageRoot)) {
@@ -404,268 +355,128 @@ async function runInstall(packageRoot, env, log) {
404
355
  if (refreshMode === null) {
405
356
  fail("invalid-arguments", `unsupported SUPERPOWERS_INSTALL_REFRESH_MODE: ${env.SUPERPOWERS_INSTALL_REFRESH_MODE}`);
406
357
  }
407
- let entered = false;
408
- try {
409
- return await withWorkspace(tmpdir(), "superpowers-manager.adapter-install.", async () => {
410
- entered = true;
411
- const marketplaceList = await listingCommand(log, codexBin, ["plugin", "marketplace", "list", "--json"], env);
412
- let registeredRoot;
413
- if (commandFailed(marketplaceList)) {
414
- registeredRoot = (await storedStateAfterListingFailure(env, "install-failed", `cannot list Codex marketplaces via '${codexBin} plugin marketplace list --json'`)).managerMarketplaceRoot;
415
- }
416
- else {
417
- try {
418
- registeredRoot = marketplaceRootFromJson(marketplaceList.stdout, MARKETPLACE_NAME);
419
- }
420
- catch {
421
- fail("install-failed", `cannot parse output of '${codexBin} plugin marketplace list --json'`);
422
- }
423
- }
424
- if (registeredRoot.length === 0) {
425
- const added = await mutationCommand(log, codexBin, ["plugin", "marketplace", "add", packageRoot], env);
426
- if (commandFailed(added)) {
427
- fail("install-failed", `codex marketplace add failed for ${packageRoot}`);
428
- }
429
- }
430
- else if (!(await pathsEqual(packageRoot, registeredRoot))) {
431
- log.appendText("stdout", `marketplace ${MARKETPLACE_NAME} registered at ${registeredRoot}; re-registering at ${packageRoot}`);
432
- const removed = await mutationCommand(log, codexBin, ["plugin", "marketplace", "remove", MARKETPLACE_NAME], env);
433
- if (commandFailed(removed)) {
434
- fail("install-failed", `codex marketplace remove failed for ${MARKETPLACE_NAME} (registered at ${registeredRoot})`);
435
- }
436
- const added = await mutationCommand(log, codexBin, ["plugin", "marketplace", "add", packageRoot], env);
437
- if (commandFailed(added)) {
438
- fail("install-failed", `marketplace ${MARKETPLACE_NAME} was removed but re-adding failed.`, [
439
- `recover with: ${codexBin} plugin marketplace add ${packageRoot}`,
440
- `previous root (last known good): ${registeredRoot}`,
441
- ]);
442
- }
443
- }
444
- if (refreshMode === "remove-add") {
445
- await mutationCommand(log, codexBin, ["plugin", "remove", PLUGIN_ID], env);
446
- }
447
- const pluginAdded = await mutationCommand(log, codexBin, ["plugin", "add", PLUGIN_ID], env);
448
- if (commandFailed(pluginAdded)) {
449
- fail("install-failed", `codex plugin add failed for ${PLUGIN_ID}`);
450
- }
451
- return {
452
- verification_hints: {
453
- ...(refreshMode === "add-only"
454
- ? {
455
- mismatch: "retry with SUPERPOWERS_INSTALL_REFRESH_MODE=remove-add",
456
- }
457
- : {}),
458
- missing: "verify with 'codex plugin list --json'.",
459
- },
460
- };
461
- }, { onCleanupFailure: reportOrphanedWorkspace(log) });
358
+ const marketplaceList = await listingCommand(log, codexBin, ["plugin", "marketplace", "list", "--json"], env);
359
+ let registeredRoot;
360
+ if (commandFailed(marketplaceList)) {
361
+ registeredRoot = (await storedStateAfterListingFailure(env, "install-failed", `cannot list Codex marketplaces via '${codexBin} plugin marketplace list --json'`)).managerMarketplaceRoot;
462
362
  }
463
- catch (cause) {
464
- if (!entered) {
465
- fail("install-failed", `cannot create adapter install workspace under ${tmpdir()}`);
363
+ else {
364
+ try {
365
+ registeredRoot = marketplaceRootFromJson(marketplaceList.stdout, MARKETPLACE_NAME);
366
+ }
367
+ catch {
368
+ fail("install-failed", `cannot parse output of '${codexBin} plugin marketplace list --json'`);
369
+ }
370
+ }
371
+ if (registeredRoot.length === 0) {
372
+ const added = await mutationCommand(log, codexBin, ["plugin", "marketplace", "add", packageRoot], env);
373
+ if (commandFailed(added)) {
374
+ fail("install-failed", `codex marketplace add failed for ${packageRoot}`);
466
375
  }
467
- throw cause;
468
376
  }
377
+ else if (!(await pathsEqual(packageRoot, registeredRoot))) {
378
+ log.appendText("stdout", `marketplace ${MARKETPLACE_NAME} registered at ${registeredRoot}; re-registering at ${packageRoot}`);
379
+ const removed = await mutationCommand(log, codexBin, ["plugin", "marketplace", "remove", MARKETPLACE_NAME], env);
380
+ if (commandFailed(removed)) {
381
+ fail("install-failed", `codex marketplace remove failed for ${MARKETPLACE_NAME} (registered at ${registeredRoot})`);
382
+ }
383
+ const added = await mutationCommand(log, codexBin, ["plugin", "marketplace", "add", packageRoot], env);
384
+ if (commandFailed(added)) {
385
+ fail("install-failed", `marketplace ${MARKETPLACE_NAME} was removed but re-adding failed.`, [
386
+ `recover with: ${codexBin} plugin marketplace add ${packageRoot}`,
387
+ `previous root (last known good): ${registeredRoot}`,
388
+ ]);
389
+ }
390
+ }
391
+ if (refreshMode === "remove-add") {
392
+ await mutationCommand(log, codexBin, ["plugin", "remove", PLUGIN_ID], env);
393
+ }
394
+ const pluginAdded = await mutationCommand(log, codexBin, ["plugin", "add", PLUGIN_ID], env);
395
+ if (commandFailed(pluginAdded)) {
396
+ fail("install-failed", `codex plugin add failed for ${PLUGIN_ID}`);
397
+ }
398
+ return codexInstallReceipt("verify with 'codex plugin list --json'.", refreshMode === "add-only"
399
+ ? "retry with SUPERPOWERS_INSTALL_REFRESH_MODE=remove-add"
400
+ : "");
469
401
  }
470
402
  async function runUninstall(input, env, log) {
471
403
  const { pluginPresent, marketplacePresent } = input;
472
404
  const codexBin = env.SUPERPOWERS_CODEX || "codex";
473
405
  await requireCodex(codexBin, env);
474
- let entered = false;
475
- try {
476
- return await withWorkspace(tmpdir(), "superpowers-manager.adapter-uninstall.", async () => {
477
- entered = true;
478
- if (pluginPresent) {
479
- const result = await mutationCommand(log, codexBin, ["plugin", "remove", PLUGIN_ID], env);
480
- if (commandFailed(result)) {
481
- fail("uninstall-failed", `codex plugin remove failed for ${PLUGIN_ID}`);
482
- }
483
- log.appendText("stdout", `removed plugin ${PLUGIN_ID}`);
484
- }
485
- else {
486
- log.appendText("stdout", "plugin not installed; skipping");
487
- }
488
- if (marketplacePresent) {
489
- const result = await mutationCommand(log, codexBin, ["plugin", "marketplace", "remove", MARKETPLACE_NAME], env);
490
- if (commandFailed(result)) {
491
- fail("uninstall-failed", `codex plugin marketplace remove failed for ${MARKETPLACE_NAME}`);
492
- }
493
- log.appendText("stdout", `removed marketplace ${MARKETPLACE_NAME}`);
494
- }
495
- else {
496
- log.appendText("stdout", "marketplace not registered; skipping");
497
- }
498
- return {};
499
- }, { onCleanupFailure: reportOrphanedWorkspace(log) });
406
+ if (pluginPresent) {
407
+ const result = await mutationCommand(log, codexBin, ["plugin", "remove", PLUGIN_ID], env);
408
+ if (commandFailed(result)) {
409
+ fail("uninstall-failed", `codex plugin remove failed for ${PLUGIN_ID}`);
410
+ }
411
+ log.appendText("stdout", `removed plugin ${PLUGIN_ID}`);
500
412
  }
501
- catch (cause) {
502
- if (!entered) {
503
- fail("uninstall-failed", `cannot create adapter uninstall workspace under ${tmpdir()}`);
413
+ else {
414
+ log.appendText("stdout", "plugin not installed; skipping");
415
+ }
416
+ if (marketplacePresent) {
417
+ const result = await mutationCommand(log, codexBin, ["plugin", "marketplace", "remove", MARKETPLACE_NAME], env);
418
+ if (commandFailed(result)) {
419
+ fail("uninstall-failed", `codex plugin marketplace remove failed for ${MARKETPLACE_NAME}`);
504
420
  }
505
- throw cause;
421
+ log.appendText("stdout", `removed marketplace ${MARKETPLACE_NAME}`);
506
422
  }
423
+ else {
424
+ log.appendText("stdout", "marketplace not registered; skipping");
425
+ }
426
+ return {};
427
+ }
428
+ function ownershipFromResources(pluginPresent, marketplacePresent, legacyPresent, conflicts) {
429
+ if (conflicts.some((item) => typeof item !== "string" ||
430
+ item.length === 0 ||
431
+ hasTerminalControl(item))) {
432
+ fail("malformed-result", "expected an array of strings at conflicts");
433
+ }
434
+ const managerPresent = pluginPresent || marketplacePresent;
435
+ const identityState = managerPresent
436
+ ? legacyPresent
437
+ ? "both"
438
+ : "manager"
439
+ : legacyPresent
440
+ ? "legacy"
441
+ : "neither";
442
+ return codexOwnershipInspection(identityState, { pluginPresent, marketplacePresent }, conflicts);
507
443
  }
508
- async function runInspect(view, context, env, log) {
509
- if (view === "update-control") {
510
- return { view: "update-control", update_control: "managed" };
444
+ async function runOwnership(context, env, log) {
445
+ const codexBin = env.SUPERPOWERS_CODEX || "codex";
446
+ await requireCodex(codexBin, env);
447
+ const plugins = await listingCommand(log, codexBin, ["plugin", "list", "--json"], env);
448
+ if (commandFailed(plugins)) {
449
+ const stored = await storedStateAfterListingFailure(env, "inspect-failed", `cannot list Codex plugins via '${codexBin} plugin list --json'`);
450
+ const conflicts = await inspectCodexConflicts({ root: context.root, env }, stored.installedListingJson);
451
+ return ownershipFromResources(stored.managerPluginPresent, true, stored.legacyPluginPresent || stored.legacyMarketplaceRoot !== null, conflicts);
452
+ }
453
+ let managerPlugin;
454
+ let legacyPlugin;
455
+ let conflicts;
456
+ try {
457
+ managerPlugin = installedListingHas(plugins.stdout, "installed", "pluginId", PLUGIN_ID);
458
+ legacyPlugin = installedListingHas(plugins.stdout, "installed", "pluginId", LEGACY_PLUGIN_ID);
459
+ conflicts = await inspectCodexConflicts({ root: context.root, env }, plugins.stdout.toString("utf8"));
511
460
  }
512
- if (view === "fingerprint") {
513
- const codexBin = env.SUPERPOWERS_CODEX || "codex";
514
- await requireCodex(codexBin, env);
515
- let entered = false;
516
- try {
517
- return await withWorkspace(tmpdir(), "superpowers-manager.adapter-fingerprint.", async () => {
518
- entered = true;
519
- const listing = await listingCommand(log, codexBin, ["plugin", "list", "--json"], env);
520
- if (commandFailed(listing)) {
521
- fail("inspect-failed", `cannot list Codex plugins via '${codexBin} plugin list --json'`);
522
- }
523
- let activeVersion;
524
- try {
525
- activeVersion = activePluginVersionFromJson(listing.stdout, PLUGIN_ID);
526
- }
527
- catch {
528
- fail("inspect-failed", `cannot parse output of '${codexBin} plugin list --json'`);
529
- }
530
- if (activeVersion.length === 0) {
531
- return { view: "fingerprint", fingerprint: null };
532
- }
533
- let searchRoot = env.SUPERPOWERS_INSTALLED_SEARCH_ROOT;
534
- if (!searchRoot) {
535
- if (env.HOME === undefined) {
536
- fail("inspect-failed", "cannot inspect active Codex plugin fingerprint without HOME");
537
- }
538
- searchRoot = join(env.HOME || "/", ".codex");
539
- }
540
- const activeRoot = installedRootForVersion(searchRoot, MARKETPLACE_NAME, "superpowers", activeVersion);
541
- const fingerprint = await installedCommitFromRoot(activeRoot);
542
- if (fingerprint.length === 0) {
543
- fail("inspect-failed", `cannot inspect active Codex plugin fingerprint under ${activeRoot}`);
544
- }
545
- return { view: "fingerprint", fingerprint };
546
- }, { onCleanupFailure: reportOrphanedWorkspace(log) });
547
- }
548
- catch (cause) {
549
- if (!entered) {
550
- fail("inspect-failed", `cannot create adapter fingerprint workspace under ${tmpdir()}`);
551
- }
552
- throw cause;
553
- }
461
+ catch {
462
+ fail("inspect-failed", `cannot parse output of '${codexBin} plugin list --json'`);
554
463
  }
555
- if (view === "ownership") {
556
- const codexBin = env.SUPERPOWERS_CODEX || "codex";
557
- await requireCodex(codexBin, env);
558
- let entered = false;
559
- try {
560
- return await withWorkspace(tmpdir(), "superpowers-manager.adapter-inspect.", async () => {
561
- entered = true;
562
- const plugins = await listingCommand(log, codexBin, ["plugin", "list", "--json"], env);
563
- if (commandFailed(plugins)) {
564
- const stored = await storedStateAfterListingFailure(env, "inspect-failed", `cannot list Codex plugins via '${codexBin} plugin list --json'`);
565
- const conflicts = await inspectCodexConflicts({ root: context.root, env }, stored.installedListingJson);
566
- const managerPresent = stored.managerPluginPresent ||
567
- stored.managerMarketplaceRoot.length > 0;
568
- const legacyPresent = stored.legacyPluginPresent ||
569
- stored.legacyMarketplaceRoot !== null;
570
- return {
571
- view: "ownership",
572
- resources: {
573
- plugin: stored.managerPluginPresent,
574
- marketplace: true,
575
- },
576
- legacy_resources: {
577
- plugin: stored.legacyPluginPresent,
578
- marketplace: stored.legacyMarketplaceRoot !== null,
579
- },
580
- identity_state: managerPresent
581
- ? legacyPresent
582
- ? "both"
583
- : "manager"
584
- : legacyPresent
585
- ? "legacy"
586
- : "neither",
587
- conflicts: [...conflicts],
588
- };
589
- }
590
- let managerPlugin;
591
- let legacyPlugin;
592
- let conflicts;
593
- try {
594
- managerPlugin = installedListingHas(plugins.stdout, "installed", "pluginId", PLUGIN_ID);
595
- legacyPlugin = installedListingHas(plugins.stdout, "installed", "pluginId", LEGACY_PLUGIN_ID);
596
- conflicts = await inspectCodexConflicts({ root: context.root, env }, plugins.stdout.toString("utf8"));
597
- }
598
- catch {
599
- fail("inspect-failed", `cannot parse output of '${codexBin} plugin list --json'`);
600
- }
601
- const marketplaces = await listingCommand(log, codexBin, ["plugin", "marketplace", "list", "--json"], env);
602
- if (commandFailed(marketplaces)) {
603
- const stored = await storedStateAfterListingFailure(env, "inspect-failed", `cannot list Codex marketplaces via '${codexBin} plugin marketplace list --json'`);
604
- const conflicts = await inspectCodexConflicts({ root: context.root, env }, stored.installedListingJson);
605
- const managerPresent = true;
606
- const legacyPresent = stored.legacyPluginPresent ||
607
- stored.legacyMarketplaceRoot !== null;
608
- return {
609
- view: "ownership",
610
- resources: {
611
- plugin: stored.managerPluginPresent,
612
- marketplace: true,
613
- },
614
- legacy_resources: {
615
- plugin: stored.legacyPluginPresent,
616
- marketplace: stored.legacyMarketplaceRoot !== null,
617
- },
618
- identity_state: managerPresent
619
- ? legacyPresent
620
- ? "both"
621
- : "manager"
622
- : legacyPresent
623
- ? "legacy"
624
- : "neither",
625
- conflicts: [...conflicts],
626
- };
627
- }
628
- let managerMarketplace;
629
- let legacyMarketplace;
630
- try {
631
- managerMarketplace = installedListingHas(marketplaces.stdout, "marketplaces", "name", MARKETPLACE_NAME);
632
- legacyMarketplace = installedListingHas(marketplaces.stdout, "marketplaces", "name", LEGACY_MARKETPLACE_NAME);
633
- }
634
- catch {
635
- fail("inspect-failed", `cannot parse output of '${codexBin} plugin marketplace list --json'`);
636
- }
637
- const managerPresent = managerPlugin || managerMarketplace;
638
- const legacyPresent = legacyPlugin || legacyMarketplace;
639
- return {
640
- view: "ownership",
641
- resources: {
642
- plugin: managerPlugin,
643
- marketplace: managerMarketplace,
644
- },
645
- legacy_resources: {
646
- plugin: legacyPlugin,
647
- marketplace: legacyMarketplace,
648
- },
649
- identity_state: managerPresent
650
- ? legacyPresent
651
- ? "both"
652
- : "manager"
653
- : legacyPresent
654
- ? "legacy"
655
- : "neither",
656
- conflicts: [...conflicts],
657
- };
658
- }, { onCleanupFailure: reportOrphanedWorkspace(log) });
659
- }
660
- catch (cause) {
661
- if (!entered) {
662
- fail("inspect-failed", `cannot create adapter inspect workspace under ${tmpdir()}`);
663
- }
664
- throw cause;
665
- }
464
+ const marketplaces = await listingCommand(log, codexBin, ["plugin", "marketplace", "list", "--json"], env);
465
+ if (commandFailed(marketplaces)) {
466
+ const stored = await storedStateAfterListingFailure(env, "inspect-failed", `cannot list Codex marketplaces via '${codexBin} plugin marketplace list --json'`);
467
+ const conflicts = await inspectCodexConflicts({ root: context.root, env }, stored.installedListingJson);
468
+ return ownershipFromResources(stored.managerPluginPresent, true, stored.legacyPluginPresent || stored.legacyMarketplaceRoot !== null, conflicts);
469
+ }
470
+ let managerMarketplace;
471
+ let legacyMarketplace;
472
+ try {
473
+ managerMarketplace = installedListingHas(marketplaces.stdout, "marketplaces", "name", MARKETPLACE_NAME);
474
+ legacyMarketplace = installedListingHas(marketplaces.stdout, "marketplaces", "name", LEGACY_MARKETPLACE_NAME);
475
+ }
476
+ catch {
477
+ fail("inspect-failed", `cannot parse output of '${codexBin} plugin marketplace list --json'`);
666
478
  }
667
- const unsupportedView = view;
668
- fail("invalid-arguments", `unsupported inspect view: ${unsupportedView}`);
479
+ return ownershipFromResources(managerPlugin, managerMarketplace, legacyPlugin || legacyMarketplace, conflicts);
669
480
  }
670
481
  async function runCodexOperation(operation, context, execute) {
671
482
  const env = { ...process.env, ...context.env };
@@ -690,8 +501,11 @@ export function codexInstall(packageRoot, context) {
690
501
  export function codexRemove(input, context) {
691
502
  return runCodexOperation("uninstall", context, (env, log) => runUninstall(input, env, log));
692
503
  }
693
- export function codexInspect(view, context) {
694
- return runCodexOperation("inspect", context, (env, log) => runInspect(view, context, env, log));
504
+ export function codexInspectOwnership(context) {
505
+ return runCodexOperation("inspect", context, (env, log) => runOwnership(context, env, log));
506
+ }
507
+ export function codexInspectControl(context) {
508
+ return runCodexOperation("inspect", context, async () => codexControlInspection("managed"));
695
509
  }
696
510
  export function codexReadNativeState(context) {
697
511
  return runCodexOperation("native-state", context, async (env, log) => {
@@ -757,67 +571,3 @@ export function codexReadNativeState(context) {
757
571
  };
758
572
  });
759
573
  }
760
- export async function runAdapter(argv, context) {
761
- const rawOperation = argv[0];
762
- const operation = rawOperation || "adapter";
763
- const args = argv.slice(1);
764
- try {
765
- if (rawOperation === undefined || rawOperation.length === 0) {
766
- fail("invalid-arguments", "missing adapter operation");
767
- }
768
- else if (operation === "build") {
769
- const flags = parseFlags(args, BUILD_FLAGS);
770
- return codexBuild({
771
- upstreamRoot: flags["--upstream-root"],
772
- candidateRoot: flags["--candidate-root"],
773
- requestedRef: flags["--requested-ref"],
774
- resolvedRef: flags["--resolved-ref"],
775
- commit: flags["--commit"],
776
- managerVersion: flags["--manager-version"],
777
- upstreamManifestVersion: flags["--upstream-manifest-version"],
778
- fallbackManifest: flags["--fallback-manifest"],
779
- }, context);
780
- }
781
- else if (operation === "install") {
782
- const flags = parseFlags(args, ["--package-root"]);
783
- return codexInstall(flags["--package-root"], context);
784
- }
785
- else if (operation === "uninstall") {
786
- const flags = parseFlags(args, [
787
- "--plugin-present",
788
- "--marketplace-present",
789
- ]);
790
- const pluginPresent = flags["--plugin-present"];
791
- const marketplacePresent = flags["--marketplace-present"];
792
- if (pluginPresent !== "true" && pluginPresent !== "false") {
793
- fail("invalid-arguments", "--plugin-present must be true or false");
794
- }
795
- if (marketplacePresent !== "true" && marketplacePresent !== "false") {
796
- fail("invalid-arguments", "--marketplace-present must be true or false");
797
- }
798
- return codexRemove({
799
- pluginPresent: pluginPresent === "true",
800
- marketplacePresent: marketplacePresent === "true",
801
- }, context);
802
- }
803
- else if (operation === "inspect") {
804
- const flags = parseFlags(args, ["--view"]);
805
- const view = flags["--view"];
806
- if (view !== "ownership" &&
807
- view !== "update-control" &&
808
- view !== "fingerprint") {
809
- fail("invalid-arguments", `unsupported inspect view: ${view}`);
810
- }
811
- return codexInspect(view, context);
812
- }
813
- else {
814
- fail("unsupported-operation", `unsupported adapter operation: ${operation}`);
815
- }
816
- }
817
- catch (cause) {
818
- if (cause instanceof AdapterFailure) {
819
- return failureResult(operation, cause.code, cause.message, cause.hints, []);
820
- }
821
- throw cause;
822
- }
823
- }