@cotal-ai/cli 0.182.1 → 0.183.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 (192) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +218 -141
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +65 -9
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/app-identity.d.ts +1 -0
  8. package/dist/commands/app-identity.d.ts.map +1 -1
  9. package/dist/commands/app-identity.js +1 -1
  10. package/dist/commands/app-identity.js.map +1 -1
  11. package/dist/commands/backup.d.ts.map +1 -1
  12. package/dist/commands/backup.js +43 -21
  13. package/dist/commands/backup.js.map +1 -1
  14. package/dist/commands/down.d.ts.map +1 -1
  15. package/dist/commands/down.js +12 -3
  16. package/dist/commands/down.js.map +1 -1
  17. package/dist/commands/ext.d.ts +4 -2
  18. package/dist/commands/ext.d.ts.map +1 -1
  19. package/dist/commands/ext.js +27 -11
  20. package/dist/commands/ext.js.map +1 -1
  21. package/dist/commands/join.js +1 -1
  22. package/dist/commands/join.js.map +1 -1
  23. package/dist/commands/meshes.d.ts.map +1 -1
  24. package/dist/commands/meshes.js +2 -1
  25. package/dist/commands/meshes.js.map +1 -1
  26. package/dist/commands/setup-current-connectors.d.ts +7 -0
  27. package/dist/commands/setup-current-connectors.d.ts.map +1 -0
  28. package/dist/commands/setup-current-connectors.js +31 -0
  29. package/dist/commands/setup-current-connectors.js.map +1 -0
  30. package/dist/commands/setup.d.ts +1 -0
  31. package/dist/commands/setup.d.ts.map +1 -1
  32. package/dist/commands/setup.js +5 -0
  33. package/dist/commands/setup.js.map +1 -1
  34. package/dist/commands/space-registration.d.ts.map +1 -1
  35. package/dist/commands/space-registration.js +6 -1
  36. package/dist/commands/space-registration.js.map +1 -1
  37. package/dist/commands/spawn-flags.js +1 -1
  38. package/dist/commands/spawn-flags.js.map +1 -1
  39. package/dist/commands/spawn-managed-launch.d.ts.map +1 -1
  40. package/dist/commands/spawn-managed-launch.js +2 -1
  41. package/dist/commands/spawn-managed-launch.js.map +1 -1
  42. package/dist/commands/spawn-preview.d.ts.map +1 -1
  43. package/dist/commands/spawn-preview.js +21 -4
  44. package/dist/commands/spawn-preview.js.map +1 -1
  45. package/dist/commands/spawn.d.ts +2 -15
  46. package/dist/commands/spawn.d.ts.map +1 -1
  47. package/dist/commands/spawn.js +117 -120
  48. package/dist/commands/spawn.js.map +1 -1
  49. package/dist/commands/stack-lost-records.d.ts +12 -0
  50. package/dist/commands/stack-lost-records.d.ts.map +1 -1
  51. package/dist/commands/stack-lost-records.js +31 -10
  52. package/dist/commands/stack-lost-records.js.map +1 -1
  53. package/dist/commands/stack-up.d.ts +1 -1
  54. package/dist/commands/stack-up.d.ts.map +1 -1
  55. package/dist/commands/stack-up.js +20 -9
  56. package/dist/commands/stack-up.js.map +1 -1
  57. package/dist/commands/status-health.d.ts +4 -1
  58. package/dist/commands/status-health.d.ts.map +1 -1
  59. package/dist/commands/status-health.js +4 -3
  60. package/dist/commands/status-health.js.map +1 -1
  61. package/dist/commands/status-meshes.d.ts +4 -1
  62. package/dist/commands/status-meshes.d.ts.map +1 -1
  63. package/dist/commands/status-meshes.js +8 -3
  64. package/dist/commands/status-meshes.js.map +1 -1
  65. package/dist/commands/status.d.ts.map +1 -1
  66. package/dist/commands/status.js +14 -9
  67. package/dist/commands/status.js.map +1 -1
  68. package/dist/commands/sync.d.ts.map +1 -1
  69. package/dist/commands/sync.js +2 -2
  70. package/dist/commands/sync.js.map +1 -1
  71. package/dist/commands/team.js +6 -6
  72. package/dist/commands/team.js.map +1 -1
  73. package/dist/commands/topology.d.ts.map +1 -1
  74. package/dist/commands/topology.js +3 -2
  75. package/dist/commands/topology.js.map +1 -1
  76. package/dist/commands/trust.d.ts +27 -0
  77. package/dist/commands/trust.d.ts.map +1 -0
  78. package/dist/commands/trust.js +39 -0
  79. package/dist/commands/trust.js.map +1 -0
  80. package/dist/commands/up-detach.d.ts.map +1 -1
  81. package/dist/commands/up-detach.js +5 -1
  82. package/dist/commands/up-detach.js.map +1 -1
  83. package/dist/commands/up-manifest.d.ts.map +1 -1
  84. package/dist/commands/up-manifest.js +4 -5
  85. package/dist/commands/up-manifest.js.map +1 -1
  86. package/dist/commands/up-project-trust.d.ts +8 -0
  87. package/dist/commands/up-project-trust.d.ts.map +1 -0
  88. package/dist/commands/up-project-trust.js +35 -0
  89. package/dist/commands/up-project-trust.js.map +1 -0
  90. package/dist/commands/up.d.ts.map +1 -1
  91. package/dist/commands/up.js +5 -5
  92. package/dist/commands/up.js.map +1 -1
  93. package/dist/commands/update-continuity.d.ts +4 -0
  94. package/dist/commands/update-continuity.d.ts.map +1 -1
  95. package/dist/commands/update-continuity.js +54 -1
  96. package/dist/commands/update-continuity.js.map +1 -1
  97. package/dist/commands/update-offline.d.ts +4 -0
  98. package/dist/commands/update-offline.d.ts.map +1 -0
  99. package/dist/commands/update-offline.js +39 -0
  100. package/dist/commands/update-offline.js.map +1 -0
  101. package/dist/commands/update.d.ts.map +1 -1
  102. package/dist/commands/update.js +23 -66
  103. package/dist/commands/update.js.map +1 -1
  104. package/dist/help.d.ts.map +1 -1
  105. package/dist/help.js +13 -7
  106. package/dist/help.js.map +1 -1
  107. package/dist/index.d.ts.map +1 -1
  108. package/dist/index.js +17 -1
  109. package/dist/index.js.map +1 -1
  110. package/dist/lib/app-user-identity.d.ts +10 -13
  111. package/dist/lib/app-user-identity.d.ts.map +1 -1
  112. package/dist/lib/app-user-identity.js +237 -59
  113. package/dist/lib/app-user-identity.js.map +1 -1
  114. package/dist/lib/conversation-identity.d.ts +2 -1
  115. package/dist/lib/conversation-identity.d.ts.map +1 -1
  116. package/dist/lib/conversation-identity.js +1 -1
  117. package/dist/lib/conversation-identity.js.map +1 -1
  118. package/dist/lib/conversation-resume.d.ts +30 -0
  119. package/dist/lib/conversation-resume.d.ts.map +1 -0
  120. package/dist/lib/conversation-resume.js +73 -0
  121. package/dist/lib/conversation-resume.js.map +1 -0
  122. package/dist/lib/extension-core-peer.d.ts +2 -0
  123. package/dist/lib/extension-core-peer.d.ts.map +1 -0
  124. package/dist/lib/extension-core-peer.js +23 -0
  125. package/dist/lib/extension-core-peer.js.map +1 -0
  126. package/dist/lib/extension-stage.d.ts +1 -1
  127. package/dist/lib/extension-stage.d.ts.map +1 -1
  128. package/dist/lib/extension-stage.js +15 -5
  129. package/dist/lib/extension-stage.js.map +1 -1
  130. package/dist/lib/hermes-windows-host.d.ts +8 -0
  131. package/dist/lib/hermes-windows-host.d.ts.map +1 -0
  132. package/dist/lib/hermes-windows-host.js +85 -0
  133. package/dist/lib/hermes-windows-host.js.map +1 -0
  134. package/dist/lib/hermes-windows-preload.d.ts +2 -0
  135. package/dist/lib/hermes-windows-preload.d.ts.map +1 -0
  136. package/dist/lib/hermes-windows-preload.js +7 -0
  137. package/dist/lib/hermes-windows-preload.js.map +1 -0
  138. package/dist/lib/leading-flags.d.ts.map +1 -1
  139. package/dist/lib/leading-flags.js +9 -1
  140. package/dist/lib/leading-flags.js.map +1 -1
  141. package/dist/lib/manifest/index.d.ts +1 -1
  142. package/dist/lib/manifest/index.d.ts.map +1 -1
  143. package/dist/lib/manifest/index.js +3 -3
  144. package/dist/lib/manifest/index.js.map +1 -1
  145. package/dist/lib/manifest/preflight.d.ts +1 -1
  146. package/dist/lib/manifest/preflight.d.ts.map +1 -1
  147. package/dist/lib/manifest/preflight.js +14 -4
  148. package/dist/lib/manifest/preflight.js.map +1 -1
  149. package/dist/lib/restore.d.ts.map +1 -1
  150. package/dist/lib/restore.js +12 -5
  151. package/dist/lib/restore.js.map +1 -1
  152. package/dist/lib/self-exec.d.ts +4 -2
  153. package/dist/lib/self-exec.d.ts.map +1 -1
  154. package/dist/lib/self-exec.js +9 -4
  155. package/dist/lib/self-exec.js.map +1 -1
  156. package/dist/lib/service-process.d.ts.map +1 -1
  157. package/dist/lib/service-process.js +8 -2
  158. package/dist/lib/service-process.js.map +1 -1
  159. package/dist/lib/service-start-options.d.ts +1 -0
  160. package/dist/lib/service-start-options.d.ts.map +1 -1
  161. package/dist/lib/service-start-options.js +3 -0
  162. package/dist/lib/service-start-options.js.map +1 -1
  163. package/dist/lib/stack-journal.d.ts.map +1 -1
  164. package/dist/lib/stack-journal.js +2 -1
  165. package/dist/lib/stack-journal.js.map +1 -1
  166. package/dist/lib/stdout-owner.d.ts +5 -0
  167. package/dist/lib/stdout-owner.d.ts.map +1 -1
  168. package/dist/lib/stdout-owner.js +33 -1
  169. package/dist/lib/stdout-owner.js.map +1 -1
  170. package/dist/lib/team-deploy-inspection.js +1 -1
  171. package/dist/lib/team-deploy-inspection.js.map +1 -1
  172. package/dist/lib/update-connector-config.d.ts +4 -1
  173. package/dist/lib/update-connector-config.d.ts.map +1 -1
  174. package/dist/lib/update-connector-config.js +32 -4
  175. package/dist/lib/update-connector-config.js.map +1 -1
  176. package/dist/lib/update-pending.d.ts +1 -1
  177. package/dist/lib/update-pending.d.ts.map +1 -1
  178. package/dist/lib/update-pending.js +1 -1
  179. package/dist/lib/update-pending.js.map +1 -1
  180. package/dist/lib/version.js +2 -2
  181. package/dist/lib/version.js.map +1 -1
  182. package/dist/seed/reconcile.js +1 -1
  183. package/dist/seed/reconcile.js.map +1 -1
  184. package/dist/seed/store.d.ts +3 -7
  185. package/dist/seed/store.d.ts.map +1 -1
  186. package/dist/seed/store.js +83 -15
  187. package/dist/seed/store.js.map +1 -1
  188. package/dist/seed/verify.d.ts +2 -2
  189. package/dist/seed/verify.d.ts.map +1 -1
  190. package/dist/seed/verify.js +8 -4
  191. package/dist/seed/verify.js.map +1 -1
  192. package/package.json +5 -4
@@ -1 +1 @@
1
- {"version":3,"file":"command.d.ts","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":"AAIA,OAAO,EAA6E,KAAK,OAAO,EAAkC,KAAK,QAAQ,EAAmB,MAAM,gBAAgB,CAAC;AAmEzL,OAAO,EAAqB,KAAK,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAuWlF,2DAA2D;AAC3D,MAAM,WAAW,aAAa;IAC5B;;;oCAGgC;IAChC,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;gCAE4B;IAC5B,aAAa,CAAC,EAAE,aAAa,CAAC;CAC/B;AAiWD,+FAA+F;AAC/F,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAUtE;AA8JD;;;;;;;;;;GAUG;AACH,wBAAgB,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,IAAI,GAAE,aAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAGlG"}
1
+ {"version":3,"file":"command.d.ts","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":"AAIA,OAAO,EAA6E,KAAK,OAAO,EAAkC,KAAK,QAAQ,EAAmB,MAAM,gBAAgB,CAAC;AAqEzL,OAAO,EAAqB,KAAK,aAAa,EAAE,MAAM,2BAA2B,CAAC;AA6WlF,2DAA2D;AAC3D,MAAM,WAAW,aAAa;IAC5B;;;oCAGgC;IAChC,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;gCAE4B;IAC5B,aAAa,CAAC,EAAE,aAAa,CAAC;CAC/B;AAsZD,+FAA+F;AAC/F,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAUtE;AAmKD;;;;;;;;;;GAUG;AACH,wBAAgB,MAAM,CAAC,QAAQ,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,IAAI,GAAE,aAAkB,GAAG,OAAO,CAAC,IAAI,CAAC,CAGlG"}
package/dist/command.js CHANGED
@@ -3,7 +3,7 @@ import { homedir } from "node:os";
3
3
  import { isAbsolute, join, parse, resolve } from "node:path";
4
4
  import { parseArgs } from "node:util";
5
5
  import { commandDeclarationProblems, findCommand, findSubcommand, parseCommandArgs } from "@cotal-ai/core";
6
- import { CommandFailure, commandFailureReport, cachedPreferences, CorruptExtensionsManifestError, cotalDirProblem, cotalHomeProblem, findCotalRoot, disableColor, disableInput, envelopeLine, exitCode, failureEnvelope, GLOBAL_FLAGS, globalConfigDirProblem, globalFlagDeclarationProblems, hasMeshTargetFlags, inOperationSpace, isCommandFailure, checkServer, isConnectRefusal, isMeshRegistryError, isSeededCommand, isWorkspaceTargetError, jsonFlag, localeIsUtf8, operationWarnings, outputDeclarationProblems, oneLine, paintFor, preferencesFolderWarning, recordOperationWarning, renderReport, renderWorkspaceError, runOperation, workspaceErrorParts, spaceRootTarget, targetErrorCode, targetErrorSpace, terminalWidth, userCotalDir, windowsShellWord, staleStoreHint, UnreadableConnectorSelection, } from "@cotal-ai/workspace";
6
+ import { CommandFailure, commandFailureReport, cachedPreferences, withProjectTrustMigration, CorruptExtensionsManifestError, cotalDirProblem, cotalHomeProblem, findCotalRoot, disableColor, disableInput, envelopeLine, exitCode, failureEnvelope, GLOBAL_FLAGS, globalConfigDirProblem, globalFlagDeclarationProblems, hasMeshTargetFlags, inOperationSpace, isCommandFailure, checkServer, isConnectRefusal, isMeshRegistryError, isSeededCommand, isWorkspaceTargetError, jsonFlag, localeIsUtf8, operationWarnings, outputDeclarationProblems, oneLine, paintFor, plainFlag, preferencesFolderWarning, recordOperationWarning, renderReport, renderWorkspaceError, runOperation, workspaceErrorParts, spaceRootTarget, targetErrorCode, targetErrorSpace, terminalWidth, userCotalDir, windowsShellWord, staleStoreHint, UnreadableConnectorSelection, } from "@cotal-ai/workspace";
7
7
  import { c, stderrLine } from "./ui.js";
8
8
  import { debugFlag } from "./lib/debug-flag.js";
9
9
  import { commandSurface, isExtensionStub, materializeExtension, materializeExtensionCommand, overlayExtensions, setCommandSurface, setInstalledExtensionsEnabled, } from "./ext-loader.js";
@@ -22,9 +22,9 @@ import { registryFailure } from "./lib/registry-errors.js";
22
22
  import { FlagValueRefusal } from "./lib/flag-value-refusal.js";
23
23
  import { workingFolderRemoved } from "./lib/paths.js";
24
24
  import { npmProjectDirectory, preserveUpdatePath } from "./lib/npm-invocation.js";
25
- import { reportLostOutput, writeAllSync } from "./lib/stdout-owner.js";
25
+ import { reportLostOutput, writeWholeSync } from "./lib/stdout-owner.js";
26
26
  import { shellWord } from "./lib/endpoint-errors.js";
27
- import { displayRemedy, hasMovedStackRemedy } from "./lib/self-exec.js";
27
+ import { displayProjectTrustFailure, displayRemedy, hasMovedStackRemedy } from "./lib/self-exec.js";
28
28
  import { asksForHelp, GLOBAL_FLAG_WORDS, leadingInvocation, OUTPUT_FLAG_WORDS, TYPOGRAPHIC_OPTION } from "./lib/leading-flags.js";
29
29
  import { takeManagedHandoffCustody } from "./managed-handoff.js";
30
30
  import { nearestWords, LEADING_FLAGS, unknownCommandMessage, unknownSubcommandMessage } from "./lib/nearest-word.js";
@@ -188,7 +188,12 @@ function failureExit(cmd, failure, json, plain = false, scope, words = [], valid
188
188
  process.exit(1);
189
189
  }
190
190
  // Rendered in the run's scope, so the `Mesh:` heading keeps the note on how the run chose its space.
191
- const report = () => renderReport(commandFailureReport(failure), plain ? "plain" : "rich", process.stderr);
191
+ const report = () => {
192
+ const message = displayProjectTrustFailure(failure.message);
193
+ const remedy = failure.remedy === undefined ? undefined : displayProjectTrustFailure(failure.remedy);
194
+ const shown = message === failure.message && remedy === failure.remedy ? failure : new CommandFailure(failure.outcome, failure.code, message, { ...failure, remedy });
195
+ return renderReport(commandFailureReport(shown), plain ? "plain" : "rich", process.stderr);
196
+ };
192
197
  const writeReport = () => writeSync(2, `${scope ? runOperation(scope, report) : report()}
193
198
  `);
194
199
  // Under --json the envelope alone reports the failure. Its text report goes to stderr only when the
@@ -218,7 +223,7 @@ function failureExit(cmd, failure, json, plain = false, scope, words = [], valid
218
223
  }, failure)
219
224
  : cmd.name === "watch" && validationArgs && !plain ? watchSetupFailureRecords(validationArgs, failure) : undefined;
220
225
  const lines = records ? records.map((record) => `${JSON.stringify(record)}\n`).join("") : envelopeLine(failureEnvelope(command, failure, warnings, scope));
221
- writeAllSync(1, Buffer.from(lines));
226
+ writeWholeSync(1, Buffer.from(lines));
222
227
  }
223
228
  catch (error) {
224
229
  const writeError = error;
@@ -300,6 +305,8 @@ function skipsSeed(name, sub, argv, cmd, values) {
300
305
  return true; // local files or existing native manager routes; neither installs connectors
301
306
  if (name === "telemetry")
302
307
  return true; // one local settings file; never installs connectors
308
+ if (name === "trust")
309
+ return true; // one local trust record; never installs connectors
303
310
  if (["__service-feedback-intake", "__service-delivery", "__service-manager", "__service-auth", "__service-linear", "__service-web", "__service-exec-endpoint"].includes(name))
304
311
  return true; // explicit native service child; never repairs the installation
305
312
  if (name === "team" && (sub === "deploy" || sub === "remove"))
@@ -435,7 +442,7 @@ function usageRefusal(failure, plain, cmd, words = []) {
435
442
  return;
436
443
  if (report)
437
444
  console.error("");
438
- paintFor(process.stderr, () => printHelpPath(cmd, helpPath(cmd, words).path, (line) => console.error(line), terminalWidth(process.stderr), plain ? "plain" : "rich"));
445
+ paintFor(process.stderr, () => printHelpPath(cmd, helpPath(cmd, words).path, (line) => console.error(line), terminalWidth(process.stderr), plain ? "plain" : "rich", words));
439
446
  }
440
447
  /** Recover the requested stream output and target for a refusal, without running the command. */
441
448
  function streamRefusalArgs(cmd, words) {
@@ -471,9 +478,15 @@ function streamRefusalArgs(cmd, words) {
471
478
  }
472
479
  /** An unreadable extension surface refuses dispatch, using the known built-in output mode if available. */
473
480
  function overlayFailureExit(error, builtin, words, wantsHelp, scope) {
474
- if (error instanceof CorruptExtensionsManifestError && builtin && !wantsHelp && !takesWordsRaw(builtin) && asksForJson(builtin, words)) {
475
- const failure = new CommandFailure("refused", "SCHEMA_INVALID", error.diagnosis, { remedy: error.remedy, cause: error });
476
- failureExit(builtin, failure, true, false, scope, words, streamRefusalArgs(builtin, words));
481
+ const denied = isCommandFailure(error) && error.code === "PERMISSION_DENIED" ? error : undefined;
482
+ const corrupt = error instanceof CorruptExtensionsManifestError
483
+ ? new CommandFailure("refused", "SCHEMA_INVALID", error.diagnosis, { remedy: error.remedy, cause: error }) : undefined;
484
+ const failure = denied ?? corrupt;
485
+ if (failure && builtin && !wantsHelp && !takesWordsRaw(builtin)) {
486
+ const end = words.indexOf("--");
487
+ const plain = (end === -1 ? words : words.slice(0, end)).includes("--plain");
488
+ if (asksForJson(builtin, words) || plain || denied)
489
+ failureExit(builtin, failure, asksForJson(builtin, words), plain, scope, words, streamRefusalArgs(builtin, words));
477
490
  }
478
491
  stderrLine("✗ ", error.message, c.red);
479
492
  process.exit(1);
@@ -548,13 +561,17 @@ function misspelledOption(cmd, rest, flagNames) {
548
561
  return { message: `${word} gives -${short[1]} the value "=${value}"`, remedy: `write ${correction}${windows && common === undefined ? " in PowerShell" : ""}` };
549
562
  }
550
563
  const typed = positionals.has(index) ? recognize(word) : undefined;
551
- if (typed && (cmd.name === "ext" || cmd.name === "endpoint") && typed.flagName && typed.flagName !== "help") {
564
+ if (typed && (cmd.name === "ext" || cmd.name === "endpoint" || cmd.name === "history") && typed.flagName && typed.flagName !== "help") {
552
565
  const first = metadataPositionals(cmd, rest, { optionSpelling: (arg) => recognize(arg)?.spelling }).positionals[0]?.value;
553
566
  const sub = findSubcommand(cmd, first);
554
567
  const accepted = sub ? sub.flagNames : cmd.flagNames;
555
- if ((cmd.name === "ext" || sub?.name === "check") && accepted && !accepted.includes(typed.flagName))
568
+ if (cmd.name === "history" && sub?.name === "clear" && HISTORY_LIMIT_FLAGS.some((name) => name === typed.flagName))
569
+ return { message: typed.message, remedy: `omit --${typed.flagName} from \`history clear\` and keep the other arguments. Use it with \`history limit\` to change retention` };
570
+ if ((cmd.name === "ext" || (cmd.name === "endpoint" && sub?.name === "check")) && accepted && !accepted.includes(typed.flagName))
556
571
  return { message: typed.message, remedy: `omit this option; \`cotal ${cmd.name}${sub ? ` ${sub.name}` : ""}\` does not take --${typed.flagName}` };
557
572
  }
573
+ if (typed && typed.flagName === "plain" && asksForJson(cmd, rest))
574
+ return { message: typed.message, remedy: "omit the mistyped plain option" };
558
575
  if (typed)
559
576
  return typed;
560
577
  }
@@ -597,6 +614,10 @@ function switchValueRefusal(flag, cmd, rest = [], json = false) {
597
614
  : structured(cmd, first)));
598
615
  return { message: `${flag} takes no value`, remedy: `omit ${flag}${acceptsFlag ? " or pass it without a value" : ""}` };
599
616
  }
617
+ /** `--help` takes no value. Name the bare switch, not a positional that starts with `-`. */
618
+ function helpSwitchValueRefusal(cmd) {
619
+ return { message: "--help takes no value", remedy: displayRemedy(`run \`cotal ${cmd.name} --help\``) };
620
+ }
600
621
  /** Positional word limit for the separator remedy only, counting subcommand words. Commands with
601
622
  * variable or unspecified arity keep their own grammar. */
602
623
  function operandLimit(cmd, selected, first, rest) {
@@ -681,6 +702,43 @@ function operandLimit(cmd, selected, first, rest) {
681
702
  default: return Infinity;
682
703
  }
683
704
  }
705
+ /** A persona invocation whose unknown word starts with `-`. Flags stay before `--` and only that
706
+ * word follows it, which is the form the command can parse. Undefined when there is no such word. */
707
+ function personaSeparatorRemedy(cmd, rest) {
708
+ const end = rest.indexOf("--");
709
+ const head = end === -1 ? rest : rest.slice(0, end);
710
+ const flags = [];
711
+ const names = [];
712
+ for (let index = 0; index < head.length; index++) {
713
+ const word = head[index];
714
+ if (word === "--")
715
+ continue;
716
+ const inline = /^--([^=]+)=/.exec(word)?.[1];
717
+ const long = inline ?? (/^--([^=]+)$/.exec(word)?.[1]);
718
+ const letter = /^-([^-])$/.exec(word)?.[1];
719
+ const flag = long !== undefined ? cmd.flags?.find((item) => item.name === long)
720
+ : letter === undefined ? undefined : cmd.flags?.find((item) => item.short === letter);
721
+ if (flag) {
722
+ flags.push(word);
723
+ const next = head[index + 1];
724
+ if (!inline && flag.type === "string" && next !== undefined && !next.startsWith("--") && (next === "-" || /^-\d/.test(next) || !next.startsWith("-"))) {
725
+ flags.push(shellWord(next));
726
+ index++;
727
+ }
728
+ continue;
729
+ }
730
+ names.push(word);
731
+ }
732
+ const dashed = names.find((word) => word.startsWith("-") && word !== "-");
733
+ if (dashed === undefined)
734
+ return undefined;
735
+ const kept = names.filter((word) => word !== dashed);
736
+ const line = `cotal persona ${[...kept, ...flags].join(" ")}`;
737
+ // A catalog name cannot start with `-`, so reprinting one would refuse again.
738
+ if (names[0] === "create" || names[0] === "edit" || names[0] === "remove")
739
+ return `choose a catalog name that starts with a letter, digit or _, then repeat \`${line} <name>\``;
740
+ return `repeat it as \`${line} -- ${shellWord(dashed)}\``;
741
+ }
684
742
  /** A parse error as a refusal. A mistyped option names its spelling. A word that starts with `-`
685
743
  * goes after `--` only where the command has room for an operand and there is no spelling suggestion.
686
744
  * An option value that starts with `-` is written `--name=value`, and an option given with no value,
@@ -691,6 +749,9 @@ function parseRefusal(error, cmd, rest, flagNames, takesOperands, operandsFull)
691
749
  const option = /^Unknown option '(--.+)'$/su.exec(reason)?.[1];
692
750
  if (option && GLOBAL_FLAG_WORDS.has(option) && !takesWordsRaw(cmd))
693
751
  return switchValueRefusal(option);
752
+ // `--help` is a switch, not a command flag, so a value on it is not an unknown option.
753
+ if (option === "--help" && !takesWordsRaw(cmd))
754
+ return helpSwitchValueRefusal(cmd);
694
755
  if (cmd.name === "help" && option === "--preset") {
695
756
  const [service, verb] = metadataPositionals(cmd, rest).positionals;
696
757
  if (findCommand(commandSurface(), service?.value)?.name === "service" && verb?.value === "add")
@@ -705,9 +766,10 @@ function parseRefusal(error, cmd, rest, flagNames, takesOperands, operandsFull)
705
766
  return { message: reason, remedy: `drop the unknown option${value}; --${flag.name} is already set` };
706
767
  }
707
768
  const message = spellings ? `${reason} - did you mean ${spellings}?` : reason;
708
- const remedy = cmd.name === "completion" ? "drop the unknown option"
769
+ const personaSeparator = cmd.name === "persona" && !operandsFull() ? personaSeparatorRemedy(cmd, rest) : undefined;
770
+ const remedy = personaSeparator ?? (cmd.name === "completion" ? "drop the unknown option"
709
771
  : !takesOperands ? undefined : spellings ? `use ${spellings}`
710
- : operandsFull() ? "drop the unknown option" : "to pass a word that starts with \"-\", put -- before it";
772
+ : operandsFull() ? "drop the unknown option" : "to pass a word that starts with \"-\", put -- before it");
711
773
  return { message, remedy };
712
774
  }
713
775
  if (error.code === "ERR_PARSE_ARGS_UNEXPECTED_POSITIONAL") {
@@ -950,7 +1012,7 @@ async function serviceSurface(found, words, forRefusal = false) {
950
1012
  /** Recover the command and output mode for a malformed leading switch without dispatching it. */
951
1013
  async function unknownInvocationExit(commands, word, args, output, beforeSeparator, warnings) {
952
1014
  const typed = typographicOption(word, new Set(LEADING_FLAGS.map((flag) => flag.slice(2))), [
953
- jsonFlag, { name: "help", short: "h", type: "boolean" }, { name: "version", short: "V", type: "boolean" },
1015
+ jsonFlag, plainFlag, { name: "help", short: "h", type: "boolean" }, { name: "version", short: "V", type: "boolean" },
954
1016
  ]);
955
1017
  const equals = word.indexOf("=");
956
1018
  const flag = equals === -1 ? word : word.slice(0, equals);
@@ -966,12 +1028,17 @@ async function unknownInvocationExit(commands, word, args, output, beforeSeparat
966
1028
  const words = [...output, ...retry.leading.filter((item) => OUTPUT_FLAG_WORDS.has(item)), ...retry.args];
967
1029
  const { cmd, rest } = await serviceSurface(takesWordsRaw(found) ? undefined : found, words, true);
968
1030
  const json = cmd !== undefined && asksForJson(cmd, rest);
1031
+ // With JSON chosen, correcting a mistyped `--plain` would ask for both outputs at once, so the
1032
+ // remedy drops the word instead of retyping it.
1033
+ const plainRefusal = typed?.flagName === "plain" && json
1034
+ ? { ...typed, remedy: "omit the mistyped plain option" }
1035
+ : typed;
969
1036
  if (typed && !json)
970
1037
  return textExit();
971
1038
  routeCollisionWarnings(warnings, cmd, rest, false);
972
1039
  const end = rest.indexOf("--");
973
1040
  const plain = (end === -1 ? rest : rest.slice(0, end)).includes("--plain");
974
- const refusal = typed ?? switchValueRefusal(flag, cmd, rest, json);
1041
+ const refusal = plainRefusal ?? switchValueRefusal(flag, cmd, rest, json);
975
1042
  return usageExit(refusal.message, cmd, json, plain, refusal.remedy, rest);
976
1043
  }
977
1044
  function repeatedInvocationExit(repeated, cmd, rest, warnings, commands, tail, output) {
@@ -999,6 +1066,34 @@ export function runCli(registry, argv, opts = {}) {
999
1066
  const scope = {};
1000
1067
  return runOperation(scope, () => dispatchCli(registry, argv, opts, scope));
1001
1068
  }
1069
+ function checkCommandLocalState(cmd, parsed, rest) {
1070
+ if (cmd.name.startsWith("__") || cmd.name === "help" || cmd.name === "completion")
1071
+ return;
1072
+ const json = structured(cmd, parsed.positionals[0]) && parsed.values.json === true;
1073
+ const refuse = (failure) => failureExit(cmd, failure, json, parsed.values.plain === true, undefined, rest, parsed);
1074
+ // A relative COTAL_HOME would select different records in each working folder.
1075
+ const home = process.env.COTAL_HOME;
1076
+ if (home && !isAbsolute(home))
1077
+ refuse(new CommandFailure("refused", "USAGE_INVALID", `COTAL_HOME ${JSON.stringify(home)} is a relative path, so each folder a command runs in would have its own Cotal home; the command did not run`, { remedy: `set COTAL_HOME to an absolute path, or unset it to use ${userCotalDir()}` }));
1078
+ const homeProblem = cotalHomeProblem();
1079
+ if (homeProblem)
1080
+ refuse(new CommandFailure("refused", "SCHEMA_INVALID", `${homeProblem}; the command did not run`, { remedy: `point COTAL_HOME at a directory, or unset it to use ${userCotalDir()}` }));
1081
+ // The machine daemon uses its selected home, not the invoking project's records.
1082
+ const dirProblem = cmd.name === "version" || cmd.name === "daemon" || workingFolderRemoved() ? undefined : cotalDirProblem(typeof parsed.values.root === "string" ? resolve(parsed.values.root) : findCotalRoot());
1083
+ if (dirProblem)
1084
+ refuse(new CommandFailure("refused", "CONFLICT", `${dirProblem}; the command did not run`, { remedy: "rename or move that file, then run the command again" }));
1085
+ // Commands that act on preferences refuse an invalid file. Status reports it as a warning.
1086
+ if (!["version", "docs", "status", "daemon"].includes(cmd.name)) {
1087
+ try {
1088
+ cachedPreferences();
1089
+ }
1090
+ catch (error) {
1091
+ if (!isCommandFailure(error))
1092
+ throw error;
1093
+ refuse(error);
1094
+ }
1095
+ }
1096
+ }
1002
1097
  // Explicit help for the bundled reference needs only the built-in command metadata.
1003
1098
  function isExplicitDocsHelp(registry, builtin, wantsHelp, words) {
1004
1099
  return builtin?.name === "help" && !wantsHelp && registry.has("command", "docs")
@@ -1059,41 +1154,7 @@ async function dispatchCli(registry, argv, opts, scope) {
1059
1154
  }
1060
1155
  if (word === "-v")
1061
1156
  usageExit("-v is not the version flag - run `cotal version` or `cotal -V`");
1062
- // The built-in check reports an unreadable inventory itself. Do not require that inventory to
1063
- // construct its command surface, or recover an installation as a prelude to this read-only mode.
1064
- const updateCheck = builtin?.name === "update" && words.includes("--check") && !wantsHelp
1065
- && parseOrExit(builtin, ownWords(builtin)).values.check === true;
1066
- // Version reports inventory failures itself and needs no extension commands.
1067
- const versionRead = builtin?.name === "version" && !wantsHelp;
1068
- // The built-in updater repairs its connector paths before opening any promotion journal.
1069
- const selfUpdate = builtin?.name === "update" && words.includes("--self") && !wantsHelp
1070
- && parseOrExit(builtin, ownWords(builtin)).values.self === true;
1071
- const preference = builtin?.name === "update" && !wantsHelp && (words.includes("--auto") || words.includes("--notify"))
1072
- ? parseOrExit(builtin, ownWords(builtin)).values : undefined;
1073
- const extMode = builtin?.name === "ext" ? metadataPositionals(builtin, words).positionals[0]?.value : undefined;
1074
- // Root only resolves a path. The JSON list classifies inventory errors in its handler.
1075
- const extDiagnostics = builtin?.name === "ext" && !wantsHelp
1076
- && (extMode === "root" || ((extMode === undefined || extMode === "list") && asksForJson(builtin, words)));
1077
- const readMode = builtin && !wantsHelp && (builtin.name === "config" || builtin.name === "completion")
1078
- ? metadataPositionals(builtin, words).positionals[0]?.value : undefined;
1079
- const configRead = builtin?.name === "config" && !wantsHelp && (readMode === undefined || readMode === "get");
1080
- const completionStatus = builtin?.name === "completion" && !wantsHelp && readMode === undefined;
1081
- let useExtensionOverlay = opts.extensions && !docsHelp && !updateCheck && !selfUpdate && !preference?.auto && !preference?.notify && builtin?.name !== "start";
1082
- function skipUnreadableConnectorOverlay(error) {
1083
- if (!(error instanceof UnreadableConnectorSelection) || !builtin || !["version", "status", "down"].includes(builtin.name))
1084
- return false;
1085
- if (builtin.name === "down") {
1086
- const parsed = parseOrExit(builtin, ownWords(builtin));
1087
- if (parsed.positionals.length || parsed.values.file || parsed.values.run || parsed.values["with-agents"] || parsed.values["preserve-state"])
1088
- return false;
1089
- }
1090
- // These built-ins can report or stop recorded state without loading extension commands.
1091
- // Status still reports the unreadable inventory from its own readers.
1092
- useExtensionOverlay = false;
1093
- setInstalledExtensionsEnabled(false);
1094
- return true;
1095
- }
1096
- const configFolder = globalConfigDirProblem();
1157
+ const { configFolder, configRead, surface, useExtensionOverlay, skipUnreadableConnectorOverlay } = prepareDispatchSurface(registry, opts, builtin, words, wantsHelp, docsHelp, repeatedLeading, ownWords, scope);
1097
1158
  if (useExtensionOverlay) {
1098
1159
  try {
1099
1160
  if (builtin?.name === "ext" && await extSeedGate(builtin, ownWords(builtin), configFolder, opts.startupNotice))
@@ -1118,40 +1179,6 @@ async function dispatchCli(registry, argv, opts, scope) {
1118
1179
  }
1119
1180
  }
1120
1181
  }
1121
- const surface = (warnings) => {
1122
- let commands;
1123
- try {
1124
- commands = useExtensionOverlay && !versionRead && !extDiagnostics && !configFolder ? overlayExtensions(registry, collisionWarning(warnings)) : registry.all("command");
1125
- }
1126
- catch (e) {
1127
- const infrastructureStatus = builtin?.name === "status" && !wantsHelp && !words.includes("--components")
1128
- && metadataPositionals(builtin, words).positionals.length === 0;
1129
- if (((configRead || completionStatus || infrastructureStatus) && e instanceof CorruptExtensionsManifestError)
1130
- || (infrastructureStatus && isCommandFailure(e) && e.code === "PERMISSION_DENIED") || skipUnreadableConnectorOverlay(e)) {
1131
- // The infrastructure report reads the manifest itself and can name the gap.
1132
- if (infrastructureStatus)
1133
- setInstalledExtensionsEnabled(false);
1134
- commands = registry.all("command");
1135
- }
1136
- else {
1137
- if (repeatedLeading)
1138
- usageExit(`Option '${repeatedLeading}' cannot be repeated`);
1139
- overlayFailureExit(e, builtin, words, wantsHelp, scope);
1140
- }
1141
- }
1142
- for (const cmd of commands) {
1143
- const problems = [
1144
- ...commandDeclarationProblems(cmd),
1145
- ...outputDeclarationProblems(cmd),
1146
- ...(cmd.subcommands ?? []).flatMap((sub) => outputDeclarationProblems({ name: `${cmd.name} ${sub.name}`, outputs: sub.outputs, flags: cmd.flags })),
1147
- ...globalFlagDeclarationProblems(cmd),
1148
- ];
1149
- if (problems.length)
1150
- usageExit(`internal error: ${problems.join("; ")}`);
1151
- }
1152
- setCommandSurface(commands); // the completion dispatcher reads the SAME surface help renders
1153
- return commands;
1154
- };
1155
1182
  let commands = surface(pendingWarnings);
1156
1183
  let cmd = findCommand(commands, word);
1157
1184
  let rest = ownWords(cmd);
@@ -1183,9 +1210,8 @@ async function dispatchCli(registry, argv, opts, scope) {
1183
1210
  };
1184
1211
  arm();
1185
1212
  // `cotal <cmd> --help` / `-h` → that command's help, never run it. This intercept also covers
1186
- // rawArgs commands and extension STUBS (cached specs are exactly the display surface) — only
1187
- // `__`-internal ones are exempt, because __complete's argv is ANOTHER command's half-typed
1188
- // line, where `--help` is a word being completed, not a request.
1213
+ // rawArgs commands and extension stubs. The `__`-internal ones are exempt: `__complete` receives
1214
+ // another command's half-typed line, where `--help` is a word being completed, not a request.
1189
1215
  if (cmd && !cmd.name.startsWith("__") && wantsHelp)
1190
1216
  return printHelpFor(cmd, rest);
1191
1217
  let parsed = cmd && !isExtensionStub(cmd) ? parseOrExit(cmd, rest, scoped.noMoreOperands) : undefined;
@@ -1199,36 +1225,15 @@ async function dispatchCli(registry, argv, opts, scope) {
1199
1225
  // an extension stub resolves against the manifest the seed left.
1200
1226
  const controlOnlyManager = parsed?.values.execution === "none" && (cmd?.name === "supervise" || cmd?.name === "__daemon-manager");
1201
1227
  if (opts.extensions && !controlOnlyManager && !skipsSeed(cmd?.name ?? word, parsed ? parsed.positionals[0] : rest[0], rest, cmd, parsed?.values)) {
1202
- // Startup checks seed compatibility here and reconciles at launch. A restore that refuses
1203
- // before launch leaves the operator-global store as it found it.
1204
1228
  const deferred = cmd?.name === "up" || (cmd?.name === "backup" && parsed?.positionals[0] === "restore");
1205
1229
  try {
1206
- if (deferred) {
1207
- // Broker-only startup still checks the store generation. An explicit restore can start its
1208
- // recorded manager even when --no-manager is present, so it retains the full seed path.
1209
- const brokerOnly = parsed?.values["no-manager"] === true && !parsed.values.restore;
1210
- const refusal = brokerOnly ? seedDowngradeRefusal() : deferredSeedRefusal();
1211
- if (refusal)
1212
- throw refusal;
1213
- if (!brokerOnly)
1214
- deferSeedToLaunch();
1215
- }
1230
+ if (deferred)
1231
+ deferStartupSeed(parsed);
1216
1232
  else
1217
1233
  await reconcileSeededConnectors(cmd?.name === "setup");
1218
1234
  }
1219
1235
  catch (e) {
1220
- // The seed runs before the command reaches its own failure path. A structured command still
1221
- // reports the same outcome and exit status in every presentation.
1222
- const sub = parsed?.positionals[0] ?? (cmd && metadataPositionals(cmd, rest).positionals[0]?.value);
1223
- if (cmd && structured(cmd, sub)) {
1224
- const message = e instanceof Error ? e.message : String(e);
1225
- const failure = isCommandFailure(e) ? e : new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", displayRemedy(message), e instanceof SeedChildFailure ? { remedy: displayRemedy("fix that, then run `cotal ext seed --repair`") } : {});
1226
- const end = rest.indexOf("--");
1227
- const plain = parsed?.values.plain === true || (!parsed && (end === -1 ? rest : rest.slice(0, end)).includes("--plain"));
1228
- failureExit(cmd, failure, asksForJson(cmd, rest), plain, undefined, rest);
1229
- }
1230
- seedRefusal(e);
1231
- process.exit(1);
1236
+ dispatchSeedRefusal(e, cmd, parsed, rest);
1232
1237
  }
1233
1238
  if (!deferred) {
1234
1239
  const warnings = [];
@@ -1247,7 +1252,7 @@ async function dispatchCli(registry, argv, opts, scope) {
1247
1252
  }
1248
1253
  }
1249
1254
  // An extension stub materializes before parsing: verify the version pin, import the package
1250
- // (self-registers), and parse with the LIVE specs — the cache never drives run's input.
1255
+ // (self-registers), and parse with the live specs. The cache never drives run's input.
1251
1256
  if (cmd && isExtensionStub(cmd)) {
1252
1257
  try {
1253
1258
  cmd = await materializeExtensionCommand(cmd);
@@ -1260,42 +1265,114 @@ async function dispatchCli(registry, argv, opts, scope) {
1260
1265
  }
1261
1266
  if (!cmd || !parsed)
1262
1267
  throw new Error("internal error: dispatch reached its effects without a parsed command");
1263
- const updateDirectory = cmd.name === "update" ? prepareUpdateFolder(parsed) : undefined;
1264
- // A preferences file that does not validate stops every command that could act on a default, as a
1265
- // broken config file does, so nothing runs on a default the person did not mean. Help, shell
1266
- // completion, version, docs and machine-daemon operations need no preference defaults, and status
1267
- // reports the file as a warning, so they still run. `--help` has already returned above.
1268
- if (!cmd.name.startsWith("__") && cmd.name !== "help" && cmd.name !== "completion") {
1269
- // A relative COTAL_HOME would name another home in each folder a command runs in, and a
1270
- // COTAL_HOME that cannot be a directory can hold no record: both stop them before any command
1271
- // reads it.
1272
- const home = process.env.COTAL_HOME;
1273
- if (home && !isAbsolute(home))
1274
- failureExit(cmd, new CommandFailure("refused", "USAGE_INVALID", `COTAL_HOME ${JSON.stringify(home)} is a relative path, so each folder a command runs in would have its own Cotal home; the command did not run`, { remedy: `set COTAL_HOME to an absolute path, or unset it to use ${userCotalDir()}` }), structured(cmd, parsed.positionals[0]) && parsed.values.json === true, parsed.values.plain === true, undefined, rest, parsed);
1275
- const homeProblem = cotalHomeProblem();
1276
- if (homeProblem)
1277
- failureExit(cmd, new CommandFailure("refused", "SCHEMA_INVALID", `${homeProblem}; the command did not run`, { remedy: `point COTAL_HOME at a directory, or unset it to use ${userCotalDir()}` }), structured(cmd, parsed.positionals[0]) && parsed.values.json === true, parsed.values.plain === true, undefined, rest, parsed);
1278
- // A `.cotal` that is a file in the folder the command uses, such as someone's notes, holds no
1279
- // records, and every reader would otherwise report a different wrong cause. The machine daemon
1280
- // uses its selected home, not the invoking project's records.
1281
- const dirProblem = cmd.name === "version" || cmd.name === "daemon" || workingFolderRemoved() ? undefined : cotalDirProblem(typeof parsed.values.root === "string" ? resolve(parsed.values.root) : findCotalRoot());
1282
- if (dirProblem)
1283
- failureExit(cmd, new CommandFailure("refused", "CONFLICT", `${dirProblem}; the command did not run`, { remedy: "rename or move that file, then run the command again" }), structured(cmd, parsed.positionals[0]) && parsed.values.json === true, parsed.values.plain === true, undefined, rest, parsed);
1284
- if (!["version", "docs", "status", "daemon"].includes(cmd.name)) {
1285
- try {
1286
- cachedPreferences();
1268
+ return executeDispatchedCommand(cmd, parsed, rest, argv, opts, scope, configRead);
1269
+ }
1270
+ function prepareDispatchSurface(registry, opts, builtin, words, wantsHelp, docsHelp, repeatedLeading, ownWords, scope) {
1271
+ // The built-in check reports an unreadable inventory itself. Do not require that inventory to
1272
+ // construct its command surface, or recover an installation as a prelude to this read-only mode.
1273
+ const updateCheck = builtin?.name === "update" && words.includes("--check") && !wantsHelp
1274
+ && parseOrExit(builtin, ownWords(builtin)).values.check === true;
1275
+ // Version reports inventory failures itself and needs no extension commands.
1276
+ const versionRead = builtin?.name === "version" && !wantsHelp;
1277
+ // The built-in updater repairs its connector paths before opening any promotion journal.
1278
+ const selfUpdate = builtin?.name === "update" && words.includes("--self") && !wantsHelp
1279
+ && parseOrExit(builtin, ownWords(builtin)).values.self === true;
1280
+ const preference = builtin?.name === "update" && !wantsHelp && (words.includes("--auto") || words.includes("--notify"))
1281
+ ? parseOrExit(builtin, ownWords(builtin)).values : undefined;
1282
+ const extMode = builtin?.name === "ext" ? metadataPositionals(builtin, words).positionals[0]?.value : undefined;
1283
+ // Root only resolves a path. The JSON list classifies inventory errors in its handler.
1284
+ const extDiagnostics = builtin?.name === "ext" && !wantsHelp
1285
+ && (extMode === "root" || ((extMode === undefined || extMode === "list") && asksForJson(builtin, words)));
1286
+ const readMode = builtin && !wantsHelp && (builtin.name === "config" || builtin.name === "completion")
1287
+ ? metadataPositionals(builtin, words).positionals[0]?.value : undefined;
1288
+ const configRead = builtin?.name === "config" && !wantsHelp && (readMode === undefined || readMode === "get");
1289
+ const completionStatus = builtin?.name === "completion" && !wantsHelp && readMode === undefined;
1290
+ let useExtensionOverlay = opts.extensions && !docsHelp && !updateCheck && !selfUpdate && !preference?.auto && !preference?.notify && builtin?.name !== "start";
1291
+ function skipUnreadableConnectorOverlay(error) {
1292
+ if (!(error instanceof UnreadableConnectorSelection) || !builtin || !["version", "status", "down"].includes(builtin.name))
1293
+ return false;
1294
+ if (builtin.name === "down") {
1295
+ const parsed = parseOrExit(builtin, ownWords(builtin));
1296
+ if (parsed.positionals.length || parsed.values.file || parsed.values.run || parsed.values["with-agents"] || parsed.values["preserve-state"])
1297
+ return false;
1298
+ }
1299
+ // These built-ins can report or stop recorded state without loading extension commands.
1300
+ // Status still reports the unreadable inventory from its own readers.
1301
+ useExtensionOverlay = false;
1302
+ setInstalledExtensionsEnabled(false);
1303
+ return true;
1304
+ }
1305
+ const configFolder = globalConfigDirProblem();
1306
+ function surface(warnings) {
1307
+ let commands;
1308
+ try {
1309
+ commands = useExtensionOverlay && !versionRead && !extDiagnostics && !configFolder ? overlayExtensions(registry, collisionWarning(warnings)) : registry.all("command");
1310
+ }
1311
+ catch (e) {
1312
+ const infrastructureStatus = builtin?.name === "status" && !wantsHelp && !words.includes("--components")
1313
+ && metadataPositionals(builtin, words).positionals.length === 0;
1314
+ if (((configRead || completionStatus || infrastructureStatus) && e instanceof CorruptExtensionsManifestError)
1315
+ || (infrastructureStatus && isCommandFailure(e) && e.code === "PERMISSION_DENIED") || skipUnreadableConnectorOverlay(e)) {
1316
+ // The infrastructure report reads the manifest itself and can name the gap.
1317
+ if (infrastructureStatus)
1318
+ setInstalledExtensionsEnabled(false);
1319
+ commands = registry.all("command");
1287
1320
  }
1288
- catch (e) {
1289
- if (!isCommandFailure(e))
1290
- throw e;
1291
- failureExit(cmd, e, structured(cmd, parsed.positionals[0]) && parsed.values.json === true, parsed.values.plain === true, undefined, rest, parsed);
1321
+ else {
1322
+ if (repeatedLeading)
1323
+ usageExit(`Option '${repeatedLeading}' cannot be repeated`);
1324
+ overlayFailureExit(e, builtin, words, wantsHelp, scope);
1292
1325
  }
1293
1326
  }
1327
+ for (const cmd of commands) {
1328
+ const problems = [
1329
+ ...commandDeclarationProblems(cmd),
1330
+ ...outputDeclarationProblems(cmd),
1331
+ ...(cmd.subcommands ?? []).flatMap((sub) => outputDeclarationProblems({ name: `${cmd.name} ${sub.name}`, outputs: sub.outputs, flags: cmd.flags })),
1332
+ ...globalFlagDeclarationProblems(cmd),
1333
+ ];
1334
+ if (problems.length)
1335
+ usageExit(`internal error: ${problems.join("; ")}`);
1336
+ }
1337
+ setCommandSurface(commands); // the completion dispatcher reads the SAME surface help renders
1338
+ return commands;
1339
+ }
1340
+ return { configFolder, configRead, surface, useExtensionOverlay, skipUnreadableConnectorOverlay };
1341
+ }
1342
+ function deferStartupSeed(parsed) {
1343
+ // Startup checks seed compatibility here and reconciles at launch. A restore that refuses
1344
+ // before launch leaves the operator-global store as it found it.
1345
+ // Broker-only startup still checks the store generation. An explicit restore can start its
1346
+ // recorded manager even when `--no-manager` is present, so it retains the full seed path.
1347
+ const brokerOnly = parsed?.values["no-manager"] === true && !parsed.values.restore;
1348
+ const refusal = brokerOnly ? seedDowngradeRefusal() : deferredSeedRefusal();
1349
+ if (refusal)
1350
+ throw refusal;
1351
+ if (!brokerOnly)
1352
+ deferSeedToLaunch();
1353
+ }
1354
+ function dispatchSeedRefusal(e, cmd, parsed, rest) {
1355
+ // The seed runs before the command reaches its own failure path. A structured command still
1356
+ // reports the same outcome and exit status in every presentation.
1357
+ const sub = parsed?.positionals[0] ?? (cmd && metadataPositionals(cmd, rest).positionals[0]?.value);
1358
+ if (cmd && structured(cmd, sub)) {
1359
+ const message = e instanceof Error ? e.message : String(e);
1360
+ const failure = isCommandFailure(e) ? e : new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", displayRemedy(message), e instanceof SeedChildFailure ? { remedy: displayRemedy("fix that, then run `cotal ext seed --repair`") } : {});
1361
+ const end = rest.indexOf("--");
1362
+ const plain = parsed?.values.plain === true || (!parsed && (end === -1 ? rest : rest.slice(0, end)).includes("--plain"));
1363
+ failureExit(cmd, failure, asksForJson(cmd, rest), plain, undefined, rest);
1294
1364
  }
1365
+ seedRefusal(e);
1366
+ process.exit(1);
1367
+ }
1368
+ async function executeDispatchedCommand(cmd, parsed, rest, argv, opts, scope, configRead) {
1369
+ const updateDirectory = cmd.name === "update" ? prepareUpdateFolder(parsed) : undefined;
1370
+ checkCommandLocalState(cmd, parsed, rest);
1295
1371
  // Keep failures in the resolved space and completion warnings behind COTAL_COMPLETE_DEBUG.
1296
1372
  if (cmd.name === "__complete" && !debugFlag("COTAL_COMPLETE_DEBUG"))
1297
1373
  scope.quiet = true;
1298
- const execute = async () => npmProjectDirectory.run(updateDirectory, async () => {
1374
+ const execute = () => withProjectTrustMigration(parsed.values["dry-run"] !== true && cmd.name !== "update", structured(cmd, parsed.positionals[0]) && parsed.values.json === true, executeCommand);
1375
+ const executeCommand = async () => npmProjectDirectory.run(updateDirectory, async () => {
1299
1376
  if (opts.extensions && cmd.requiredExtensions) {
1300
1377
  for (const ref of cmd.requiredExtensions(parsed))
1301
1378
  await materializeExtension(ref);